| 1 |
|
| 2 |
|
| 3 |
import base64 |
| 4 |
import configparser |
| 5 |
import contextlib |
| 6 |
import glob |
| 7 |
import http.cookiejar |
| 8 |
import json |
| 9 |
import os |
| 10 |
import shutil |
| 11 |
import sqlite3 |
| 12 |
import struct |
| 13 |
import subprocess |
| 14 |
import sys |
| 15 |
import tempfile |
| 16 |
from io import BytesIO |
| 17 |
from pathlib import Path |
| 18 |
from typing import Dict, List, Union |
| 19 |
|
| 20 |
|
| 21 |
if sys.platform.startswith('linux') or 'bsd' in sys.platform.lower(): |
| 22 |
try: |
| 23 |
import jeepney |
| 24 |
from jeepney.io.blocking import open_dbus_connection |
| 25 |
USE_DBUS_LINUX = False |
| 26 |
except ImportError: |
| 27 |
import dbus |
| 28 |
USE_DBUS_LINUX = True |
| 29 |
|
| 30 |
|
| 31 |
shadowcopy = None |
| 32 |
if sys.platform == 'win32': |
| 33 |
try: |
| 34 |
import shadowcopy |
| 35 |
except ImportError: |
| 36 |
pass |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
import lz4.block |
| 41 |
from Cryptodome.Cipher import AES |
| 42 |
from Cryptodome.Protocol.KDF import PBKDF2 |
| 43 |
from Cryptodome.Util.Padding import unpad |
| 44 |
|
| 45 |
__doc__ = 'Load browser cookies into a cookiejar' |
| 46 |
|
| 47 |
CHROMIUM_DEFAULT_PASSWORD = b'peanuts' |
| 48 |
|
| 49 |
|
| 50 |
class BrowserCookieError(Exception): |
| 51 |
pass |
| 52 |
|
| 53 |
|
| 54 |
def _windows_group_policy_path(): |
| 55 |
|
| 56 |
from winreg import (HKEY_LOCAL_MACHINE, REG_EXPAND_SZ, REG_SZ, |
| 57 |
ConnectRegistry, OpenKeyEx, QueryValueEx) |
| 58 |
try: |
| 59 |
root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) |
| 60 |
policy_key = OpenKeyEx(root, r"SOFTWARE\Policies\Google\Chrome") |
| 61 |
user_data_dir, type_ = QueryValueEx(policy_key, "UserDataDir") |
| 62 |
if type_ == REG_EXPAND_SZ: |
| 63 |
user_data_dir = os.path.expandvars(user_data_dir) |
| 64 |
elif type_ != REG_SZ: |
| 65 |
return None |
| 66 |
except OSError: |
| 67 |
return None |
| 68 |
return os.path.join(user_data_dir, "Default", "Cookies") |
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
def _crypt_unprotect_data( |
| 73 |
cipher_text=b'', entropy=b'', reserved=None, prompt_struct=None, is_key=False |
| 74 |
): |
| 75 |
|
| 76 |
import ctypes |
| 77 |
import ctypes.wintypes |
| 78 |
|
| 79 |
class DataBlob(ctypes.Structure): |
| 80 |
_fields_ = [ |
| 81 |
('cbData', ctypes.wintypes.DWORD), |
| 82 |
('pbData', ctypes.POINTER(ctypes.c_char)) |
| 83 |
] |
| 84 |
|
| 85 |
blob_in, blob_entropy, blob_out = map( |
| 86 |
lambda x: DataBlob(len(x), ctypes.create_string_buffer(x)), |
| 87 |
[cipher_text, entropy, b''] |
| 88 |
) |
| 89 |
desc = ctypes.c_wchar_p() |
| 90 |
|
| 91 |
CRYPTPROTECT_UI_FORBIDDEN = 0x01 |
| 92 |
|
| 93 |
if not ctypes.windll.crypt32.CryptUnprotectData( |
| 94 |
ctypes.byref(blob_in), ctypes.byref( |
| 95 |
desc), ctypes.byref(blob_entropy), |
| 96 |
reserved, prompt_struct, CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref( |
| 97 |
blob_out) |
| 98 |
): |
| 99 |
raise RuntimeError('Failed to decrypt the cipher text with DPAPI') |
| 100 |
|
| 101 |
description = desc.value |
| 102 |
buffer_out = ctypes.create_string_buffer(int(blob_out.cbData)) |
| 103 |
ctypes.memmove(buffer_out, blob_out.pbData, blob_out.cbData) |
| 104 |
map(ctypes.windll.kernel32.LocalFree, [desc, blob_out.pbData]) |
| 105 |
if is_key: |
| 106 |
return description, buffer_out.raw |
| 107 |
else: |
| 108 |
return description, buffer_out.value |
| 109 |
|
| 110 |
|
| 111 |
def _get_osx_keychain_password(osx_key_service, osx_key_user): |
| 112 |
"""Retrieve password used to encrypt cookies from OSX Keychain""" |
| 113 |
|
| 114 |
cmd = ['/usr/bin/security', '-q', 'find-generic-password', |
| 115 |
'-w', '-a', osx_key_user, '-s', osx_key_service] |
| 116 |
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, |
| 117 |
stderr=subprocess.PIPE) |
| 118 |
out, err = proc.communicate() |
| 119 |
if proc.returncode != 0: |
| 120 |
return CHROMIUM_DEFAULT_PASSWORD |
| 121 |
return out.strip() |
| 122 |
|
| 123 |
|
| 124 |
def _expand_win_path(path: Union[dict, str]): |
| 125 |
if not isinstance(path, dict): |
| 126 |
path = {'path': path, 'env': 'APPDATA'} |
| 127 |
return os.path.join(os.getenv(path['env'], ''), path['path']) |
| 128 |
|
| 129 |
|
| 130 |
def _expand_paths_impl(paths: list, os_name: str): |
| 131 |
"""Expands user paths on Linux, OSX, and windows""" |
| 132 |
|
| 133 |
os_name = os_name.lower() |
| 134 |
assert os_name in ['windows', 'osx', 'linux'] |
| 135 |
|
| 136 |
if not isinstance(paths, list): |
| 137 |
paths = [paths] |
| 138 |
|
| 139 |
if os_name == 'windows': |
| 140 |
paths = map(_expand_win_path, paths) |
| 141 |
else: |
| 142 |
paths = map(os.path.expanduser, paths) |
| 143 |
|
| 144 |
for path in paths: |
| 145 |
|
| 146 |
for i in sorted(glob.glob(path)): |
| 147 |
|
| 148 |
yield i |
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
def _expand_paths(paths: list, os_name: str): |
| 153 |
return next(_expand_paths_impl(paths, os_name), None) |
| 154 |
|
| 155 |
|
| 156 |
def _normalize_genarate_paths_chromium(paths: Union[str, list], channel: Union[str, list] = None): |
| 157 |
channel = channel or [''] |
| 158 |
if not isinstance(channel, list): |
| 159 |
channel = [channel] |
| 160 |
if not isinstance(paths, list): |
| 161 |
paths = [paths] |
| 162 |
return paths, channel |
| 163 |
|
| 164 |
|
| 165 |
def _genarate_nix_paths_chromium(paths: Union[str, list], channel: Union[str, list] = None): |
| 166 |
"""Generate paths for chromium based browsers on *nix systems.""" |
| 167 |
|
| 168 |
paths, channel = _normalize_genarate_paths_chromium(paths, channel) |
| 169 |
genararated_paths = [] |
| 170 |
for chan in channel: |
| 171 |
for path in paths: |
| 172 |
genararated_paths.append(path.format(channel=chan)) |
| 173 |
return genararated_paths |
| 174 |
|
| 175 |
|
| 176 |
def _genarate_win_paths_chromium(paths: Union[str, list], channel: Union[str, list] = None): |
| 177 |
"""Generate paths for chromium based browsers on windows""" |
| 178 |
|
| 179 |
paths, channel = _normalize_genarate_paths_chromium(paths, channel) |
| 180 |
genararated_paths = [] |
| 181 |
for chan in channel: |
| 182 |
for path in paths: |
| 183 |
genararated_paths.append( |
| 184 |
{'env': 'APPDATA', 'path': '..\\Local\\' + path.format(channel=chan)}) |
| 185 |
genararated_paths.append( |
| 186 |
{'env': 'LOCALAPPDATA', 'path': path.format(channel=chan)}) |
| 187 |
genararated_paths.append( |
| 188 |
{'env': 'APPDATA', 'path': path.format(channel=chan)}) |
| 189 |
return genararated_paths |
| 190 |
|
| 191 |
|
| 192 |
def _text_factory(data): |
| 193 |
try: |
| 194 |
return data.decode('utf-8') |
| 195 |
except UnicodeDecodeError: |
| 196 |
return data |
| 197 |
|
| 198 |
|
| 199 |
class _JeepneyConnection: |
| 200 |
def __init__(self, object_path, bus_name, interface): |
| 201 |
self.__dbus_address = jeepney.DBusAddress( |
| 202 |
object_path, bus_name, interface) |
| 203 |
|
| 204 |
def __enter__(self): |
| 205 |
self.__connection = open_dbus_connection() |
| 206 |
return self |
| 207 |
|
| 208 |
def __exit__(self, exc_type, exc_value, traceback): |
| 209 |
self.__connection.close() |
| 210 |
|
| 211 |
def close(self): |
| 212 |
self.__connection.close() |
| 213 |
|
| 214 |
def call_method(self, method_name, signature=None, *args): |
| 215 |
method = jeepney.new_method_call( |
| 216 |
self.__dbus_address, method_name, signature, args) |
| 217 |
response = self.__connection.send_and_get_reply(method) |
| 218 |
if response.header.message_type == jeepney.MessageType.error: |
| 219 |
raise RuntimeError(response.body[0]) |
| 220 |
return response.body[0] if len(response.body) == 1 else response.body |
| 221 |
|
| 222 |
|
| 223 |
class _LinuxPasswordManager: |
| 224 |
"""Retrieve password used to encrypt cookies from KDE Wallet or SecretService""" |
| 225 |
|
| 226 |
_APP_ID = 'browser-cookie3' |
| 227 |
|
| 228 |
def __init__(self, use_dbus): |
| 229 |
if use_dbus: |
| 230 |
self.__methods_map = { |
| 231 |
'kwallet': self.__get_kdewallet_password_dbus, |
| 232 |
'secretstorage': self.__get_secretstorage_item_dbus |
| 233 |
} |
| 234 |
else: |
| 235 |
self.__methods_map = { |
| 236 |
'kwallet': self.__get_kdewallet_password_jeepney, |
| 237 |
'secretstorage': self.__get_secretstorage_item_jeepney |
| 238 |
} |
| 239 |
|
| 240 |
def get_password(self, os_crypt_name): |
| 241 |
try: |
| 242 |
return self.__get_secretstorage_password(os_crypt_name) |
| 243 |
except RuntimeError: |
| 244 |
pass |
| 245 |
try: |
| 246 |
return self.__methods_map.get('kwallet')(os_crypt_name) |
| 247 |
except RuntimeError: |
| 248 |
pass |
| 249 |
|
| 250 |
return CHROMIUM_DEFAULT_PASSWORD |
| 251 |
|
| 252 |
def __get_secretstorage_password(self, os_crypt_name): |
| 253 |
schemas = ['chrome_libsecret_os_crypt_password_v2', |
| 254 |
'chrome_libsecret_os_crypt_password_v1'] |
| 255 |
for schema in schemas: |
| 256 |
try: |
| 257 |
return self.__methods_map.get('secretstorage')(schema, os_crypt_name) |
| 258 |
except RuntimeError: |
| 259 |
pass |
| 260 |
raise RuntimeError(f'Can not find secret for {os_crypt_name}') |
| 261 |
|
| 262 |
def __get_secretstorage_item_dbus(self, schema: str, application: str): |
| 263 |
with contextlib.closing(dbus.SessionBus()) as connection: |
| 264 |
try: |
| 265 |
secret_service = dbus.Interface( |
| 266 |
connection.get_object( |
| 267 |
'org.freedesktop.secrets', '/org/freedesktop/secrets', False), |
| 268 |
'org.freedesktop.Secret.Service', |
| 269 |
) |
| 270 |
except dbus.exceptions.DBusException: |
| 271 |
raise RuntimeError( |
| 272 |
"The name org.freedesktop.secrets was not provided by any .service files") |
| 273 |
object_path = secret_service.SearchItems({ |
| 274 |
'xdg:schema': schema, |
| 275 |
'application': application, |
| 276 |
}) |
| 277 |
object_path = list(filter(lambda x: len(x), object_path)) |
| 278 |
if len(object_path) == 0: |
| 279 |
raise RuntimeError(f'Can not find secret for {application}') |
| 280 |
object_path = object_path[0][0] |
| 281 |
|
| 282 |
secret_service.Unlock([object_path]) |
| 283 |
_, session = secret_service.OpenSession( |
| 284 |
'plain', dbus.String('', variant_level=1)) |
| 285 |
_, _, secret, _ = secret_service.GetSecrets( |
| 286 |
[object_path], session)[object_path] |
| 287 |
return bytes(secret) |
| 288 |
|
| 289 |
def __get_kdewallet_password_dbus(self, os_crypt_name): |
| 290 |
folder = f'{os_crypt_name.capitalize()} Keys' |
| 291 |
key = f'{os_crypt_name.capitalize()} Safe Storage' |
| 292 |
with contextlib.closing(dbus.SessionBus()) as connection: |
| 293 |
try: |
| 294 |
kwalletd5_object = connection.get_object( |
| 295 |
'org.kde.kwalletd5', '/modules/kwalletd5', False) |
| 296 |
except dbus.exceptions.DBusException: |
| 297 |
raise RuntimeError( |
| 298 |
"The name org.kde.kwalletd5 was not provided by any .service files") |
| 299 |
kwalletd5 = dbus.Interface(kwalletd5_object, 'org.kde.KWallet') |
| 300 |
handle = kwalletd5.open( |
| 301 |
kwalletd5.networkWallet(), dbus.Int64(0), self._APP_ID) |
| 302 |
if not kwalletd5.hasFolder(handle, folder, self._APP_ID): |
| 303 |
kwalletd5.close(handle, False, self._APP_ID) |
| 304 |
raise RuntimeError(f'KDE Wallet folder {folder} not found.') |
| 305 |
password = kwalletd5.readPassword( |
| 306 |
handle, folder, key, self._APP_ID) |
| 307 |
kwalletd5.close(handle, False, self._APP_ID) |
| 308 |
return password.encode('utf-8') |
| 309 |
|
| 310 |
def __get_secretstorage_item_jeepney(self, schema, application): |
| 311 |
args = ['/org/freedesktop/secrets', 'org.freedesktop.secrets', |
| 312 |
'org.freedesktop.Secret.Service'] |
| 313 |
with _JeepneyConnection(*args) as connection: |
| 314 |
object_path = connection.call_method( |
| 315 |
'SearchItems', 'a{ss}', {'xdg:schema': schema, 'application': application}) |
| 316 |
object_path = list(filter(lambda x: len(x), object_path)) |
| 317 |
if len(object_path) == 0: |
| 318 |
raise RuntimeError(f'Can not find secret for {application}') |
| 319 |
object_path = object_path[0][0] |
| 320 |
connection.call_method('Unlock', 'ao', [object_path]) |
| 321 |
_, session = connection.call_method( |
| 322 |
'OpenSession', 'sv', 'plain', ('s', '')) |
| 323 |
_, _, secret, _ = connection.call_method( |
| 324 |
'GetSecrets', 'aoo', [object_path], session)[object_path] |
| 325 |
return secret |
| 326 |
|
| 327 |
def __get_kdewallet_password_jeepney(self, os_crypt_name): |
| 328 |
folder = f'{os_crypt_name.capitalize()} Keys' |
| 329 |
key = f'{os_crypt_name.capitalize()} Safe Storage' |
| 330 |
with _JeepneyConnection('/modules/kwalletd5', 'org.kde.kwalletd5', 'org.kde.KWallet') as connection: |
| 331 |
network_wallet = connection.call_method('networkWallet') |
| 332 |
handle = connection.call_method( |
| 333 |
'open', 'sxs', network_wallet, 0, self._APP_ID) |
| 334 |
has_folder = connection.call_method( |
| 335 |
'hasFolder', 'iss', handle, folder, self._APP_ID) |
| 336 |
if not has_folder: |
| 337 |
connection.call_method( |
| 338 |
'close', 'ibs', handle, False, self._APP_ID) |
| 339 |
raise RuntimeError(f'KDE Wallet folder {folder} not found.') |
| 340 |
password = connection.call_method( |
| 341 |
'readPassword', 'isss', handle, folder, key, self._APP_ID) |
| 342 |
connection.call_method('close', 'ibs', handle, False, self._APP_ID) |
| 343 |
return password.encode('utf-8') |
| 344 |
|
| 345 |
|
| 346 |
class _DatabaseConnetion(): |
| 347 |
def __init__(self, database_file: os.PathLike, try_legacy_first: bool = False): |
| 348 |
self.__database_file = database_file |
| 349 |
self.__temp_cookie_file = None |
| 350 |
self.__connection = None |
| 351 |
self.__methods = [ |
| 352 |
self.__sqlite3_connect_readonly, |
| 353 |
] |
| 354 |
|
| 355 |
if try_legacy_first: |
| 356 |
self.__methods.insert(0, self.__get_connection_legacy) |
| 357 |
else: |
| 358 |
self.__methods.append(self.__get_connection_legacy) |
| 359 |
|
| 360 |
if shadowcopy: |
| 361 |
self.__methods.append(self.__get_connection_shadowcopy) |
| 362 |
|
| 363 |
def __enter__(self): |
| 364 |
return self.get_connection() |
| 365 |
|
| 366 |
def __exit__(self, exc_type, exc_value, traceback): |
| 367 |
self.close() |
| 368 |
|
| 369 |
def __check_connection_ok(self, connection): |
| 370 |
try: |
| 371 |
connection.cursor().execute('select 1 from sqlite_master') |
| 372 |
return True |
| 373 |
except sqlite3.OperationalError: |
| 374 |
return False |
| 375 |
|
| 376 |
def __sqlite3_connect_readonly(self): |
| 377 |
uri = Path(self.__database_file).absolute().as_uri() |
| 378 |
for options in ('?mode=ro', '?mode=ro&nolock=1', '?mode=ro&immutable=1'): |
| 379 |
try: |
| 380 |
con = sqlite3.connect(uri + options, uri=True) |
| 381 |
except sqlite3.OperationalError: |
| 382 |
continue |
| 383 |
if self.__check_connection_ok(con): |
| 384 |
return con |
| 385 |
|
| 386 |
def __get_connection_legacy(self): |
| 387 |
with tempfile.NamedTemporaryFile(suffix='.sqlite') as tf: |
| 388 |
self.__temp_cookie_file = tf.name |
| 389 |
try: |
| 390 |
shutil.copyfile(self.__database_file, self.__temp_cookie_file) |
| 391 |
except PermissionError: |
| 392 |
return |
| 393 |
con = sqlite3.connect(self.__temp_cookie_file) |
| 394 |
if self.__check_connection_ok(con): |
| 395 |
return con |
| 396 |
|
| 397 |
def __get_connection_shadowcopy(self): |
| 398 |
if not shadowcopy: |
| 399 |
raise RuntimeError("shadowcopy is not available") |
| 400 |
|
| 401 |
self.__temp_cookie_file = tempfile.NamedTemporaryFile( |
| 402 |
suffix='.sqlite').name |
| 403 |
shadowcopy.shadow_copy(self.__database_file, self.__temp_cookie_file) |
| 404 |
con = sqlite3.connect(self.__temp_cookie_file) |
| 405 |
if self.__check_connection_ok(con): |
| 406 |
return con |
| 407 |
|
| 408 |
def get_connection(self): |
| 409 |
if self.__connection: |
| 410 |
return self.__connection |
| 411 |
for method in self.__methods: |
| 412 |
con = method() |
| 413 |
if con is not None: |
| 414 |
self.__connection = con |
| 415 |
return con |
| 416 |
raise BrowserCookieError('Unable to read database file') |
| 417 |
|
| 418 |
def cursor(self): |
| 419 |
return self.connection().cursor() |
| 420 |
|
| 421 |
def close(self): |
| 422 |
if self.__connection: |
| 423 |
self.__connection.close() |
| 424 |
if self.__temp_cookie_file: |
| 425 |
try: |
| 426 |
os.remove(self.__temp_cookie_file) |
| 427 |
except Exception: |
| 428 |
pass |
| 429 |
|
| 430 |
|
| 431 |
class ChromiumBased: |
| 432 |
"""Super class for all Chromium based browsers""" |
| 433 |
|
| 434 |
|
| 435 |
UNIX_TO_NT_EPOCH_OFFSET = 11644473600 |
| 436 |
|
| 437 |
def __init__(self, browser: str, cookie_file=None, domain_name="", key_file=None, **kwargs): |
| 438 |
self.salt = b'saltysalt' |
| 439 |
self.iv = b' ' * 16 |
| 440 |
self.length = 16 |
| 441 |
self.browser = browser |
| 442 |
self.cookie_file = cookie_file |
| 443 |
self.domain_name = domain_name |
| 444 |
self.key_file = key_file |
| 445 |
self.__add_key_and_cookie_file(**kwargs) |
| 446 |
|
| 447 |
def __add_key_and_cookie_file(self, |
| 448 |
linux_cookies=None, windows_cookies=None, osx_cookies=None, |
| 449 |
windows_keys=None, os_crypt_name=None, osx_key_service=None, osx_key_user=None): |
| 450 |
|
| 451 |
if sys.platform == 'darwin': |
| 452 |
password = _get_osx_keychain_password( |
| 453 |
osx_key_service, osx_key_user) |
| 454 |
iterations = 1003 |
| 455 |
self.v10_key = PBKDF2(password, self.salt, self.length, iterations) |
| 456 |
cookie_file = self.cookie_file or _expand_paths(osx_cookies, 'osx') |
| 457 |
|
| 458 |
elif sys.platform.startswith('linux') or 'bsd' in sys.platform.lower(): |
| 459 |
password = _LinuxPasswordManager( |
| 460 |
USE_DBUS_LINUX).get_password(os_crypt_name) |
| 461 |
iterations = 1 |
| 462 |
self.v10_key = PBKDF2(CHROMIUM_DEFAULT_PASSWORD, |
| 463 |
self.salt, self.length, iterations) |
| 464 |
self.v11_key = PBKDF2(password, self.salt, self.length, iterations) |
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
self.v11_empty_key = PBKDF2( |
| 470 |
b'', self.salt, self.length, iterations) |
| 471 |
|
| 472 |
cookie_file = self.cookie_file or _expand_paths( |
| 473 |
linux_cookies, 'linux') |
| 474 |
|
| 475 |
elif sys.platform == "win32": |
| 476 |
key_file = self.key_file or _expand_paths(windows_keys, 'windows') |
| 477 |
|
| 478 |
if key_file: |
| 479 |
with open(key_file, 'rb') as f: |
| 480 |
key_file_json = json.load(f) |
| 481 |
key64 = key_file_json['os_crypt']['encrypted_key'].encode( |
| 482 |
'utf-8') |
| 483 |
|
| 484 |
|
| 485 |
keydpapi = base64.standard_b64decode(key64)[5:] |
| 486 |
_, self.v10_key = _crypt_unprotect_data( |
| 487 |
keydpapi, is_key=True) |
| 488 |
else: |
| 489 |
self.v10_key = None |
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
cookie_file = self.cookie_file |
| 494 |
|
| 495 |
if not cookie_file: |
| 496 |
if self.browser.lower() == 'chrome' and _windows_group_policy_path(): |
| 497 |
cookie_file = _windows_group_policy_path() |
| 498 |
else: |
| 499 |
cookie_file = _expand_paths(windows_cookies, 'windows') |
| 500 |
|
| 501 |
else: |
| 502 |
raise BrowserCookieError( |
| 503 |
"OS not recognized. Works on OSX, Windows, and Linux.") |
| 504 |
|
| 505 |
if not cookie_file: |
| 506 |
raise BrowserCookieError( |
| 507 |
'Failed to find cookies for {} browser'.format(self.browser)) |
| 508 |
|
| 509 |
self.cookie_file = cookie_file |
| 510 |
|
| 511 |
def __str__(self): |
| 512 |
return self.browser |
| 513 |
|
| 514 |
def load(self): |
| 515 |
"""Load sqlite cookies into a cookiejar""" |
| 516 |
cj = http.cookiejar.CookieJar() |
| 517 |
|
| 518 |
with _DatabaseConnetion(self.cookie_file) as con: |
| 519 |
con.text_factory = _text_factory |
| 520 |
cur = con.cursor() |
| 521 |
has_integrity_check_for_cookie_domain = self._has_integrity_check_for_cookie_domain(cur) |
| 522 |
try: |
| 523 |
|
| 524 |
cur.execute('SELECT host_key, path, secure, expires_utc, name, value, encrypted_value, is_httponly ' |
| 525 |
'FROM cookies WHERE host_key like ?;', ('%{}%'.format(self.domain_name),)) |
| 526 |
except sqlite3.OperationalError: |
| 527 |
try: |
| 528 |
|
| 529 |
cur.execute('SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value, is_httponly ' |
| 530 |
'FROM cookies WHERE host_key like ?;', ('%{}%'.format(self.domain_name),)) |
| 531 |
except sqlite3.OperationalError as e: |
| 532 |
if e.args[0].startswith(('no such table: ', 'file is not a database')): |
| 533 |
raise BrowserCookieError('File {} is not a Chromium-based browser cookie file'.format(self.tmp_cookie_file)) |
| 534 |
|
| 535 |
|
| 536 |
for item in cur.fetchall(): |
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
host, path, secure, expires_nt_time_epoch, name, value, enc_value, http_only = item |
| 544 |
if (expires_nt_time_epoch == 0): |
| 545 |
expires = None |
| 546 |
else: |
| 547 |
expires = (expires_nt_time_epoch / 1000000) - \ |
| 548 |
self.UNIX_TO_NT_EPOCH_OFFSET |
| 549 |
|
| 550 |
value = self._decrypt(value, enc_value, has_integrity_check_for_cookie_domain) |
| 551 |
c = create_cookie(host, path, secure, expires, |
| 552 |
name, value, http_only) |
| 553 |
cj.set_cookie(c) |
| 554 |
return cj |
| 555 |
|
| 556 |
@staticmethod |
| 557 |
def _has_integrity_check_for_cookie_domain(con): |
| 558 |
"""Starting from version 24, the sha256 of the domain is prepended to the encrypted value |
| 559 |
of the cookie. |
| 560 |
|
| 561 |
See: |
| 562 |
- https://issues.chromium.org/issues/40185252 |
| 563 |
- https://chromium-review.googlesource.com/c/chromium/src/+/5792044 |
| 564 |
- https://chromium.googlesource.com/chromium/src/net/+/master/extras/sqlite/sqlite_persistent_cookie_store.cc#193 |
| 565 |
""" |
| 566 |
try: |
| 567 |
value, = con.execute('SELECT value FROM meta WHERE key = "version";').fetchone() |
| 568 |
except sqlite3.OperationalError: |
| 569 |
return False |
| 570 |
|
| 571 |
try: |
| 572 |
version = int(value) |
| 573 |
except ValueError: |
| 574 |
return False |
| 575 |
|
| 576 |
return version >= 24 |
| 577 |
|
| 578 |
@staticmethod |
| 579 |
def _decrypt_windows_chromium(value, encrypted_value): |
| 580 |
|
| 581 |
if len(value) != 0: |
| 582 |
return value |
| 583 |
|
| 584 |
if encrypted_value == b"": |
| 585 |
return "" |
| 586 |
|
| 587 |
_, data = _crypt_unprotect_data(encrypted_value) |
| 588 |
assert isinstance(data, bytes) |
| 589 |
return data.decode() |
| 590 |
|
| 591 |
def _decrypt(self, value, encrypted_value, has_integrity_check_for_cookie_domain=False): |
| 592 |
"""Decrypt encoded cookies""" |
| 593 |
|
| 594 |
if sys.platform == 'win32': |
| 595 |
try: |
| 596 |
return self._decrypt_windows_chromium(value, encrypted_value) |
| 597 |
|
| 598 |
|
| 599 |
except RuntimeError: |
| 600 |
if not self.v10_key: |
| 601 |
raise RuntimeError( |
| 602 |
'Failed to decrypt the cipher text with DPAPI and no AES key.') |
| 603 |
|
| 604 |
|
| 605 |
encrypted_value = encrypted_value[3:] |
| 606 |
nonce, tag = encrypted_value[:12], encrypted_value[-16:] |
| 607 |
aes = AES.new(self.v10_key, AES.MODE_GCM, nonce=nonce) |
| 608 |
|
| 609 |
|
| 610 |
|
| 611 |
try: |
| 612 |
data = aes.decrypt_and_verify(encrypted_value[12:-16], tag) |
| 613 |
except ValueError: |
| 614 |
raise BrowserCookieError( |
| 615 |
'Unable to get key for cookie decryption') |
| 616 |
if has_integrity_check_for_cookie_domain: |
| 617 |
data = data[32:] |
| 618 |
return data.decode() |
| 619 |
|
| 620 |
if value or (encrypted_value[:3] not in [b'v11', b'v10']): |
| 621 |
return value |
| 622 |
|
| 623 |
|
| 624 |
|
| 625 |
|
| 626 |
|
| 627 |
if not hasattr(self, 'v11_key'): |
| 628 |
assert encrypted_value[:3] != b'v11', "v11 keys should only appear on Linux." |
| 629 |
keys = (self.v11_key, self.v11_empty_key) if encrypted_value[:3] == b'v11' else ( |
| 630 |
self.v10_key,) |
| 631 |
encrypted_value = encrypted_value[3:] |
| 632 |
|
| 633 |
for key in keys: |
| 634 |
cipher = AES.new(key, AES.MODE_CBC, self.iv) |
| 635 |
|
| 636 |
|
| 637 |
|
| 638 |
try: |
| 639 |
decrypted = unpad(cipher.decrypt( |
| 640 |
encrypted_value), AES.block_size) |
| 641 |
if has_integrity_check_for_cookie_domain: |
| 642 |
decrypted = decrypted[32:] |
| 643 |
return decrypted.decode('utf-8') |
| 644 |
except ValueError: |
| 645 |
pass |
| 646 |
raise BrowserCookieError('Unable to get key for cookie decryption') |
| 647 |
|
| 648 |
|
| 649 |
class Chrome(ChromiumBased): |
| 650 |
"""Class for Google Chrome""" |
| 651 |
|
| 652 |
def __init__(self, cookie_file=None, domain_name="", key_file=None): |
| 653 |
args = { |
| 654 |
'linux_cookies': _genarate_nix_paths_chromium( |
| 655 |
[ |
| 656 |
'~/.config/google-chrome{channel}/Default/Cookies', |
| 657 |
'~/.config/google-chrome{channel}/Profile */Cookies', |
| 658 |
'~/.var/app/com.google.Chrome/config/google-chrome{channel}/Default/Cookies', |
| 659 |
'~/.var/app/com.google.Chrome/config/google-chrome{channel}/Profile */Cookies' |
| 660 |
], |
| 661 |
channel=['', '-beta', '-unstable'] |
| 662 |
), |
| 663 |
'windows_cookies': _genarate_win_paths_chromium( |
| 664 |
[ |
| 665 |
'Google\\Chrome{channel}\\User Data\\Default\\Cookies', |
| 666 |
'Google\\Chrome{channel}\\User Data\\Default\\Network\\Cookies', |
| 667 |
'Google\\Chrome{channel}\\User Data\\Profile *\\Cookies', |
| 668 |
'Google\\Chrome{channel}\\User Data\\Profile *\\Network\\Cookies' |
| 669 |
], |
| 670 |
channel=['', ' Beta', ' Dev'] |
| 671 |
), |
| 672 |
'osx_cookies': _genarate_nix_paths_chromium( |
| 673 |
[ |
| 674 |
'~/Library/Application Support/Google/Chrome{channel}/Default/Cookies', |
| 675 |
'~/Library/Application Support/Google/Chrome{channel}/Profile */Cookies' |
| 676 |
], |
| 677 |
channel=['', ' Beta', ' Dev'] |
| 678 |
), |
| 679 |
'windows_keys': _genarate_win_paths_chromium( |
| 680 |
'Google\\Chrome{channel}\\User Data\\Local State', |
| 681 |
channel=['', ' Beta', ' Dev'] |
| 682 |
), |
| 683 |
'os_crypt_name': 'chrome', |
| 684 |
'osx_key_service': 'Chrome Safe Storage', |
| 685 |
'osx_key_user': 'Chrome' |
| 686 |
} |
| 687 |
super().__init__(browser='Chrome', cookie_file=cookie_file, |
| 688 |
domain_name=domain_name, key_file=key_file, **args) |
| 689 |
|
| 690 |
|
| 691 |
class Arc(ChromiumBased): |
| 692 |
"""Class for Arc""" |
| 693 |
|
| 694 |
def __init__(self, cookie_file=None, domain_name="", key_file=None): |
| 695 |
args = { |
| 696 |
'osx_cookies': _genarate_nix_paths_chromium( |
| 697 |
[ |
| 698 |
'~/Library/Application Support/Arc/User Data/Default/Cookies', |
| 699 |
'~/Library/Application Support/Arc/User Data/Profile */Cookies' |
| 700 |
], |
| 701 |
channel=[''] |
| 702 |
), |
| 703 |
'os_crypt_name': 'chrome', |
| 704 |
'osx_key_service': 'Arc Safe Storage', |
| 705 |
'osx_key_user': 'Arc' |
| 706 |
} |
| 707 |
super().__init__(browser='Arc', cookie_file=cookie_file, |
| 708 |
domain_name=domain_name, key_file=key_file, **args) |
| 709 |
|
| 710 |
|
| 711 |
class Chromium(ChromiumBased): |
| 712 |
"""Class for Chromium""" |
| 713 |
|
| 714 |
def __init__(self, cookie_file=None, domain_name="", key_file=None): |
| 715 |
args = { |
| 716 |
'linux_cookies': [ |
| 717 |
'~/.config/chromium/Default/Cookies', |
| 718 |
'~/.config/chromium/Profile */Cookies', |
| 719 |
'~/.var/app/org.chromium.Chromium/config/chromium/Default/Cookies', |
| 720 |
'~/.var/app/org.chromium.Chromium/config/chromium/Profile */Cookies' |
| 721 |
], |
| 722 |
'windows_cookies': _genarate_win_paths_chromium( |
| 723 |
[ |
| 724 |
'Chromium\\User Data\\Default\\Cookies', |
| 725 |
'Chromium\\User Data\\Default\\Network\\Cookies', |
| 726 |
'Chromium\\User Data\\Profile *\\Cookies', |
| 727 |
'Chromium\\User Data\\Profile *\\Network\\Cookies' |
| 728 |
] |
| 729 |
), |
| 730 |
'osx_cookies': [ |
| 731 |
'~/Library/Application Support/Chromium/Default/Cookies', |
| 732 |
'~/Library/Application Support/Chromium/Profile */Cookies' |
| 733 |
], |
| 734 |
'windows_keys': _genarate_win_paths_chromium( |
| 735 |
'Chromium\\User Data\\Local State' |
| 736 |
), |
| 737 |
'os_crypt_name': 'chromium', |
| 738 |
'osx_key_service': 'Chromium Safe Storage', |
| 739 |
'osx_key_user': 'Chromium' |
| 740 |
} |
| 741 |
super().__init__(browser='Chromium', cookie_file=cookie_file, |
| 742 |
domain_name=domain_name, key_file=key_file, **args) |
| 743 |
|
| 744 |
|
| 745 |
class Opera(ChromiumBased): |
| 746 |
"""Class for Opera""" |
| 747 |
|
| 748 |
def __init__(self, cookie_file=None, domain_name="", key_file=None): |
| 749 |
args = { |
| 750 |
'linux_cookies': [ |
| 751 |
'~/.config/opera/Cookies', |
| 752 |
'~/.config/opera-beta/Cookies', |
| 753 |
'~/.config/opera-developer/Cookies', |
| 754 |
'~/.var/app/com.opera.Opera/config/opera/Cookies' |
| 755 |
'~/.var/app/com.opera.Opera/config/opera-beta/Cookies' |
| 756 |
'~/.var/app/com.opera.Opera/config/opera-developer/Cookies' |
| 757 |
], |
| 758 |
'windows_cookies': _genarate_win_paths_chromium( |
| 759 |
[ |
| 760 |
'Opera Software\\Opera {channel}\\Cookies', |
| 761 |
'Opera Software\\Opera {channel}\\Network\\Cookies' |
| 762 |
], |
| 763 |
channel=['Stable', 'Next', 'Developer'] |
| 764 |
), |
| 765 |
'osx_cookies': [ |
| 766 |
'~/Library/Application Support/com.operasoftware.Opera/Cookies', |
| 767 |
'~/Library/Application Support/com.operasoftware.OperaNext/Cookies', |
| 768 |
'~/Library/Application Support/com.operasoftware.OperaDeveloper/Cookies' |
| 769 |
], |
| 770 |
'windows_keys': _genarate_win_paths_chromium( |
| 771 |
'Opera Software\\Opera {channel}\\Local State', |
| 772 |
channel=['Stable', 'Next', 'Developer'] |
| 773 |
), |
| 774 |
'os_crypt_name': 'chromium', |
| 775 |
'osx_key_service': 'Opera Safe Storage', |
| 776 |
'osx_key_user': 'Opera' |
| 777 |
} |
| 778 |
super().__init__(browser='Opera', cookie_file=cookie_file, |
| 779 |
domain_name=domain_name, key_file=key_file, **args) |
| 780 |
|
| 781 |
|
| 782 |
class OperaGX(ChromiumBased): |
| 783 |
"""Class for Opera GX""" |
| 784 |
|
| 785 |
def __init__(self, cookie_file=None, domain_name="", key_file=None): |
| 786 |
args = { |
| 787 |
'linux_cookies': [], |
| 788 |
'windows_cookies': _genarate_win_paths_chromium( |
| 789 |
[ |
| 790 |
'Opera Software\\Opera GX {channel}\\Cookies', |
| 791 |
'Opera Software\\Opera GX {channel}\\Network\\Cookies' |
| 792 |
], |
| 793 |
channel=['Stable'] |
| 794 |
), |
| 795 |
'osx_cookies': ['~/Library/Application Support/com.operasoftware.OperaGX/Cookies'], |
| 796 |
'windows_keys': _genarate_win_paths_chromium( |
| 797 |
'Opera Software\\Opera GX {channel}\\Local State', |
| 798 |
channel=['Stable'] |
| 799 |
), |
| 800 |
'os_crypt_name': 'chromium', |
| 801 |
'osx_key_service': 'Opera Safe Storage', |
| 802 |
'osx_key_user': 'Opera' |
| 803 |
} |
| 804 |
super().__init__(browser='Opera GX', cookie_file=cookie_file, |
| 805 |
domain_name=domain_name, key_file=key_file, **args) |
| 806 |
|
| 807 |
|
| 808 |
class Brave(ChromiumBased): |
| 809 |
def __init__(self, cookie_file=None, domain_name="", key_file=None): |
| 810 |
args = { |
| 811 |
'linux_cookies': _genarate_nix_paths_chromium( |
| 812 |
[ |
| 813 |
'~/.config/BraveSoftware/Brave-Browser{channel}/Default/Cookies', |
| 814 |
'~/.config/BraveSoftware/Brave-Browser{channel}/Profile */Cookies', |
| 815 |
'~/.var/app/com.brave.Browser/config/BraveSoftware/Brave-Browser{channel}/Default/Cookies', |
| 816 |
'~/.var/app/com.brave.Browser/config/BraveSoftware/Brave-Browser{channel}/Profile */Cookies' |
| 817 |
], |
| 818 |
channel=['', '-Beta', '-Dev', '-Nightly'] |
| 819 |
), |
| 820 |
'windows_cookies': _genarate_win_paths_chromium( |
| 821 |
[ |
| 822 |
'BraveSoftware\\Brave-Browser{channel}\\User Data\\Default\\Cookies', |
| 823 |
'BraveSoftware\\Brave-Browser{channel}\\User Data\\Default\\Network\\Cookies', |
| 824 |
'BraveSoftware\\Brave-Browser{channel}\\User Data\\Profile *\\Cookies', |
| 825 |
'BraveSoftware\\Brave-Browser{channel}\\User Data\\Profile *\\Network\\Cookies' |
| 826 |
], |
| 827 |
channel=['', '-Beta', '-Dev', '-Nightly'] |
| 828 |
), |
| 829 |
'osx_cookies': _genarate_nix_paths_chromium( |
| 830 |
[ |
| 831 |
'~/Library/Application Support/BraveSoftware/Brave-Browser{channel}/Default/Cookies', |
| 832 |
'~/Library/Application Support/BraveSoftware/Brave-Browser{channel}/Profile */Cookies' |
| 833 |
], |
| 834 |
channel=['', '-Beta', '-Dev', '-Nightly'] |
| 835 |
), |
| 836 |
'windows_keys': _genarate_win_paths_chromium( |
| 837 |
'BraveSoftware\\Brave-Browser{channel}\\User Data\\Local State', |
| 838 |
channel=['', '-Beta', '-Dev', '-Nightly'] |
| 839 |
), |
| 840 |
'os_crypt_name': 'brave', |
| 841 |
'osx_key_service': 'Brave Safe Storage', |
| 842 |
'osx_key_user': 'Brave' |
| 843 |
} |
| 844 |
super().__init__(browser='Brave', cookie_file=cookie_file, |
| 845 |
domain_name=domain_name, key_file=key_file, **args) |
| 846 |
|
| 847 |
|
| 848 |
class Edge(ChromiumBased): |
| 849 |
"""Class for Microsoft Edge""" |
| 850 |
|
| 851 |
def __init__(self, cookie_file=None, domain_name="", key_file=None): |
| 852 |
args = { |
| 853 |
'linux_cookies': _genarate_nix_paths_chromium( |
| 854 |
[ |
| 855 |
'~/.config/microsoft-edge{channel}/Default/Cookies', |
| 856 |
'~/.config/microsoft-edge{channel}/Profile */Cookies', |
| 857 |
"~/.var/app/com.microsoft.Edge/config/microsoft-edge{channel}/Default/Cookies", |
| 858 |
"~/.var/app/com.microsoft.Edge/config/microsoft-edge{channel}/Profile */Cookies", |
| 859 |
], |
| 860 |
channel=['', '-beta', '-dev'] |
| 861 |
), |
| 862 |
'windows_cookies': _genarate_win_paths_chromium( |
| 863 |
[ |
| 864 |
'Microsoft\\Edge{channel}\\User Data\\Default\\Cookies', |
| 865 |
'Microsoft\\Edge{channel}\\User Data\\Default\\Network\\Cookies', |
| 866 |
'Microsoft\\Edge{channel}\\User Data\\Profile *\\Cookies', |
| 867 |
'Microsoft\\Edge{channel}\\User Data\\Profile *\\Network\\Cookies' |
| 868 |
], |
| 869 |
channel=['', ' Beta', ' Dev', ' SxS'] |
| 870 |
), |
| 871 |
'osx_cookies': _genarate_nix_paths_chromium( |
| 872 |
[ |
| 873 |
'~/Library/Application Support/Microsoft Edge{channel}/Default/Cookies', |
| 874 |
'~/Library/Application Support/Microsoft Edge{channel}/Profile */Cookies' |
| 875 |
], |
| 876 |
channel=['', ' Beta', ' Dev', ' Canary'] |
| 877 |
), |
| 878 |
'windows_keys': _genarate_win_paths_chromium( |
| 879 |
'Microsoft\\Edge{channel}\\User Data\\Local State', |
| 880 |
channel=['', ' Beta', ' Dev', ' SxS'] |
| 881 |
), |
| 882 |
'os_crypt_name': 'chromium', |
| 883 |
'osx_key_service': 'Microsoft Edge Safe Storage', |
| 884 |
'osx_key_user': 'Microsoft Edge' |
| 885 |
} |
| 886 |
super().__init__(browser='Edge', cookie_file=cookie_file, |
| 887 |
domain_name=domain_name, key_file=key_file, **args) |
| 888 |
|
| 889 |
|
| 890 |
class Vivaldi(ChromiumBased): |
| 891 |
"""Class for Vivaldi Browser""" |
| 892 |
|
| 893 |
def __init__(self, cookie_file=None, domain_name="", key_file=None): |
| 894 |
args = { |
| 895 |
'linux_cookies': [ |
| 896 |
'~/.config/vivaldi/Default/Cookies', |
| 897 |
'~/.config/vivaldi/Profile */Cookies', |
| 898 |
'~/.config/vivaldi-snapshot/Default/Cookies', |
| 899 |
'~/.config/vivaldi-snapshot/Profile */Cookies', |
| 900 |
'~/.var/app/com.vivaldi.Vivaldi/config/vivaldi/Default/Cookies', |
| 901 |
'~/.var/app/com.vivaldi.Vivaldi/config/vivaldi/Profile */Cookies' |
| 902 |
], |
| 903 |
'windows_cookies': _genarate_win_paths_chromium( |
| 904 |
[ |
| 905 |
'Vivaldi\\User Data\\Default\\Cookies', |
| 906 |
'Vivaldi\\User Data\\Default\\Network\\Cookies', |
| 907 |
'Vivaldi\\User Data\\Profile *\\Cookies', |
| 908 |
'Vivaldi\\User Data\\Profile *\\Network\\Cookies' |
| 909 |
] |
| 910 |
), |
| 911 |
'osx_cookies': [ |
| 912 |
'~/Library/Application Support/Vivaldi/Default/Cookies', |
| 913 |
'~/Library/Application Support/Vivaldi/Profile */Cookies' |
| 914 |
], |
| 915 |
'windows_keys': _genarate_win_paths_chromium( |
| 916 |
'Vivaldi\\User Data\\Local State' |
| 917 |
), |
| 918 |
'os_crypt_name': 'chrome', |
| 919 |
'osx_key_service': 'Vivaldi Safe Storage', |
| 920 |
'osx_key_user': 'Vivaldi' |
| 921 |
} |
| 922 |
super().__init__(browser='Vivaldi', cookie_file=cookie_file, |
| 923 |
domain_name=domain_name, key_file=key_file, **args) |
| 924 |
|
| 925 |
|
| 926 |
class FirefoxBased: |
| 927 |
"""Superclass for Firefox based browsers""" |
| 928 |
|
| 929 |
def __init__(self, browser_name, cookie_file=None, domain_name="", key_file=None, **kwargs): |
| 930 |
self.browser_name = browser_name |
| 931 |
self.cookie_file = cookie_file or self.__find_cookie_file(**kwargs) |
| 932 |
|
| 933 |
self.session_file = os.path.join( |
| 934 |
os.path.dirname(self.cookie_file), 'sessionstore.js') |
| 935 |
self.session_file_lz4 = os.path.join(os.path.dirname( |
| 936 |
self.cookie_file), 'sessionstore-backups', 'recovery.jsonlz4') |
| 937 |
|
| 938 |
self.domain_name = domain_name |
| 939 |
|
| 940 |
def __str__(self): |
| 941 |
return self.browser_name |
| 942 |
|
| 943 |
@staticmethod |
| 944 |
def get_default_profile(user_data_path): |
| 945 |
config = configparser.ConfigParser() |
| 946 |
profiles_ini_path = glob.glob(os.path.join( |
| 947 |
user_data_path + '**', 'profiles.ini')) |
| 948 |
fallback_path = user_data_path + '**' |
| 949 |
|
| 950 |
if not profiles_ini_path: |
| 951 |
return fallback_path |
| 952 |
|
| 953 |
profiles_ini_path = profiles_ini_path[0] |
| 954 |
config.read(profiles_ini_path, encoding="utf8") |
| 955 |
|
| 956 |
profile_path = None |
| 957 |
for section in config.sections(): |
| 958 |
if section.startswith('Install'): |
| 959 |
profile_path = config[section].get('Default') |
| 960 |
break |
| 961 |
|
| 962 |
elif config[section].get('Default') == '1' and not profile_path: |
| 963 |
profile_path = config[section].get('Path') |
| 964 |
|
| 965 |
for section in config.sections(): |
| 966 |
|
| 967 |
if config[section].get('Path') == profile_path: |
| 968 |
absolute = config[section].get('IsRelative') == '0' |
| 969 |
return profile_path if absolute else os.path.join(os.path.dirname(profiles_ini_path), profile_path) |
| 970 |
|
| 971 |
return fallback_path |
| 972 |
|
| 973 |
def __expand_and_check_path(self, paths: Union[str, List[str], Dict[str, str], List[Dict[str, str]]]) -> str: |
| 974 |
"""Expands a path to a list of paths and returns the first one that exists""" |
| 975 |
if not isinstance(paths, list): |
| 976 |
paths = [paths] |
| 977 |
for path in paths: |
| 978 |
if isinstance(path, dict): |
| 979 |
expanded = _expand_win_path(path) |
| 980 |
else: |
| 981 |
expanded = os.path.expanduser(path) |
| 982 |
if os.path.isdir(expanded): |
| 983 |
return expanded |
| 984 |
raise BrowserCookieError( |
| 985 |
f'Could not find {self.browser_name} profile directory') |
| 986 |
|
| 987 |
def __find_cookie_file(self, linux_data_dirs=None, windows_data_dirs=None, osx_data_dirs=None): |
| 988 |
cookie_files = [] |
| 989 |
|
| 990 |
if sys.platform == 'darwin': |
| 991 |
user_data_path = self.__expand_and_check_path(osx_data_dirs) |
| 992 |
elif sys.platform.startswith('linux') or 'bsd' in sys.platform.lower(): |
| 993 |
user_data_path = self.__expand_and_check_path(linux_data_dirs) |
| 994 |
elif sys.platform == 'win32': |
| 995 |
user_data_path = self.__expand_and_check_path(windows_data_dirs) |
| 996 |
else: |
| 997 |
raise BrowserCookieError( |
| 998 |
'Unsupported operating system: ' + sys.platform) |
| 999 |
|
| 1000 |
cookie_files = glob.glob(os.path.join(FirefoxBased.get_default_profile(user_data_path), 'cookies.sqlite')) \ |
| 1001 |
or cookie_files |
| 1002 |
|
| 1003 |
if cookie_files: |
| 1004 |
return cookie_files[0] |
| 1005 |
else: |
| 1006 |
raise BrowserCookieError( |
| 1007 |
f'Failed to find {self.browser_name} cookie file') |
| 1008 |
|
| 1009 |
@staticmethod |
| 1010 |
def __create_session_cookie(cookie_json): |
| 1011 |
return create_cookie(cookie_json.get('host', ''), cookie_json.get('path', ''), |
| 1012 |
cookie_json.get('secure', False), None, |
| 1013 |
cookie_json.get('name', ''), cookie_json.get( |
| 1014 |
'value', ''), |
| 1015 |
cookie_json.get('httponly', False)) |
| 1016 |
|
| 1017 |
def __add_session_cookies(self, cj): |
| 1018 |
if not os.path.exists(self.session_file): |
| 1019 |
return |
| 1020 |
try: |
| 1021 |
with open(self.session_file, 'rb') as file_obj: |
| 1022 |
json_data = json.load(file_obj) |
| 1023 |
except ValueError as e: |
| 1024 |
print(f'Error parsing {self.browser_name} session JSON:', str(e)) |
| 1025 |
else: |
| 1026 |
for window in json_data.get('windows', []): |
| 1027 |
for cookie in window.get('cookies', []): |
| 1028 |
if self.domain_name == '' or self.domain_name in cookie.get('host', ''): |
| 1029 |
cj.set_cookie( |
| 1030 |
FirefoxBased.__create_session_cookie(cookie)) |
| 1031 |
|
| 1032 |
def __add_session_cookies_lz4(self, cj): |
| 1033 |
if not os.path.exists(self.session_file_lz4): |
| 1034 |
return |
| 1035 |
try: |
| 1036 |
with open(self.session_file_lz4, 'rb') as file_obj: |
| 1037 |
file_obj.read(8) |
| 1038 |
json_data = json.loads(lz4.block.decompress(file_obj.read())) |
| 1039 |
except ValueError as e: |
| 1040 |
print( |
| 1041 |
f'Error parsing {self.browser_name} session JSON LZ4:', str(e)) |
| 1042 |
else: |
| 1043 |
for cookie in json_data.get('cookies', []): |
| 1044 |
if self.domain_name == '' or self.domain_name in cookie.get('host', ''): |
| 1045 |
cj.set_cookie(FirefoxBased.__create_session_cookie(cookie)) |
| 1046 |
|
| 1047 |
def load(self): |
| 1048 |
cj = http.cookiejar.CookieJar() |
| 1049 |
|
| 1050 |
with _DatabaseConnetion(self.cookie_file, True) as con: |
| 1051 |
cur = con.cursor() |
| 1052 |
try: |
| 1053 |
cur.execute('select host, path, isSecure, expiry, name, value, isHttpOnly from moz_cookies ' |
| 1054 |
'where host like ?', ('%{}%'.format(self.domain_name),)) |
| 1055 |
except sqlite3.DatabaseError as e: |
| 1056 |
if e.args[0].startswith(('no such table: ', 'file is not a database')): |
| 1057 |
raise BrowserCookieError('File {} is not a Firefox cookie file'.format(self.tmp_cookie_file)) |
| 1058 |
raise |
| 1059 |
|
| 1060 |
for item in cur.fetchall(): |
| 1061 |
host, path, secure, expires, name, value, http_only = item |
| 1062 |
c = create_cookie(host, path, secure, expires, |
| 1063 |
name, value, http_only) |
| 1064 |
cj.set_cookie(c) |
| 1065 |
|
| 1066 |
self.__add_session_cookies(cj) |
| 1067 |
self.__add_session_cookies_lz4(cj) |
| 1068 |
|
| 1069 |
return cj |
| 1070 |
|
| 1071 |
|
| 1072 |
class Firefox(FirefoxBased): |
| 1073 |
"""Class for Firefox""" |
| 1074 |
|
| 1075 |
def __init__(self, cookie_file=None, domain_name="", key_file=None): |
| 1076 |
args = { |
| 1077 |
'linux_data_dirs': [ |
| 1078 |
'~/snap/firefox/common/.mozilla/firefox', |
| 1079 |
'~/.mozilla/firefox' |
| 1080 |
], |
| 1081 |
'windows_data_dirs': [ |
| 1082 |
{'env': 'APPDATA', 'path': r'Mozilla\Firefox'}, |
| 1083 |
{'env': 'LOCALAPPDATA', 'path': r'Mozilla\Firefox'} |
| 1084 |
], |
| 1085 |
'osx_data_dirs': [ |
| 1086 |
'~/Library/Application Support/Firefox' |
| 1087 |
] |
| 1088 |
} |
| 1089 |
super().__init__('Firefox', cookie_file, domain_name, key_file, **args) |
| 1090 |
|
| 1091 |
|
| 1092 |
class LibreWolf(FirefoxBased): |
| 1093 |
"""Class for LibreWolf""" |
| 1094 |
|
| 1095 |
def __init__(self, cookie_file=None, domain_name="", key_file=None): |
| 1096 |
args = { |
| 1097 |
'linux_data_dirs': [ |
| 1098 |
'~/snap/librewolf/common/.librewolf', |
| 1099 |
'~/.librewolf' |
| 1100 |
], |
| 1101 |
'windows_data_dirs': [ |
| 1102 |
{'env': 'APPDATA', 'path': 'librewolf'}, |
| 1103 |
{'env': 'LOCALAPPDATA', 'path': 'librewolf'} |
| 1104 |
], |
| 1105 |
'osx_data_dirs': [ |
| 1106 |
'~/Library/Application Support/librewolf' |
| 1107 |
] |
| 1108 |
} |
| 1109 |
super().__init__('LibreWolf', cookie_file, domain_name, key_file, **args) |
| 1110 |
|
| 1111 |
|
| 1112 |
class Safari: |
| 1113 |
"""Class for Safari""" |
| 1114 |
|
| 1115 |
APPLE_TO_UNIX_TIME = 978307200 |
| 1116 |
NEW_ISSUE_URL = 'https://github.com/borisbabic/browser_cookie3/issues/new' |
| 1117 |
NEW_ISSUE_MESSAGE = f'Page format changed.\nPlease create a new issue on: {NEW_ISSUE_URL}' |
| 1118 |
safari_cookies = [ |
| 1119 |
'~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies', |
| 1120 |
'~/Library/Cookies/Cookies.binarycookies' |
| 1121 |
] |
| 1122 |
|
| 1123 |
def __init__(self, cookie_file=None, domain_name="", key_file=None) -> None: |
| 1124 |
self.__offset = 0 |
| 1125 |
self.__domain_name = domain_name |
| 1126 |
self.__buffer = None |
| 1127 |
self.__open_file(cookie_file) |
| 1128 |
self.__parse_header() |
| 1129 |
|
| 1130 |
def __del__(self): |
| 1131 |
if self.__buffer: |
| 1132 |
self.__buffer.close() |
| 1133 |
|
| 1134 |
def __open_file(self, cookie_file): |
| 1135 |
cookie_file = cookie_file or _expand_paths(self.safari_cookies, 'osx') |
| 1136 |
if not cookie_file: |
| 1137 |
raise BrowserCookieError('Can not find Safari cookie file') |
| 1138 |
self.__buffer = open(cookie_file, 'rb') |
| 1139 |
|
| 1140 |
def __read_file(self, size: int, offset: int = None): |
| 1141 |
if offset is not None: |
| 1142 |
self.__offset = offset |
| 1143 |
self.__buffer.seek(self.__offset) |
| 1144 |
self.__offset += size |
| 1145 |
return BytesIO(self.__buffer.read(size)) |
| 1146 |
|
| 1147 |
def __parse_header(self): |
| 1148 |
assert self.__buffer.read(4) == b'cook', 'Not a safari cookie file' |
| 1149 |
self.__total_page = struct.unpack('>I', self.__buffer.read(4))[0] |
| 1150 |
|
| 1151 |
self.__page_sizes = [] |
| 1152 |
for _ in range(self.__total_page): |
| 1153 |
self.__page_sizes.append(struct.unpack( |
| 1154 |
'>I', self.__buffer.read(4))[0]) |
| 1155 |
|
| 1156 |
@staticmethod |
| 1157 |
def __read_until_null(file: BytesIO, decode: bool = True): |
| 1158 |
data = [] |
| 1159 |
while True: |
| 1160 |
byte = file.read(1) |
| 1161 |
if byte == b'\x00': |
| 1162 |
break |
| 1163 |
data.append(byte) |
| 1164 |
data = b''.join(data) |
| 1165 |
if decode: |
| 1166 |
data = data.decode('utf-8') |
| 1167 |
return data |
| 1168 |
|
| 1169 |
def __parse_cookie(self, page: BytesIO, cookie_offset: int): |
| 1170 |
page.seek(cookie_offset) |
| 1171 |
|
| 1172 |
_ = struct.unpack('<I', page.read(4))[0] |
| 1173 |
page.seek(4, 1) |
| 1174 |
flags = struct.unpack('<I', page.read(4))[0] |
| 1175 |
page.seek(4, 1) |
| 1176 |
is_secure = bool(flags & 0x1) |
| 1177 |
is_httponly = bool(flags & 0x4) |
| 1178 |
|
| 1179 |
host_offset = struct.unpack('<I', page.read(4))[0] |
| 1180 |
name_offset = struct.unpack('<I', page.read(4))[0] |
| 1181 |
path_offset = struct.unpack('<I', page.read(4))[0] |
| 1182 |
value_offset = struct.unpack('<I', page.read(4))[0] |
| 1183 |
comment_offset = struct.unpack('<I', page.read(4))[0] |
| 1184 |
|
| 1185 |
assert page.read(4) == b'\x00\x00\x00\x00', self.NEW_ISSUE_MESSAGE |
| 1186 |
expiry_date = int(struct.unpack('<d', page.read(8))[ |
| 1187 |
0] + self.APPLE_TO_UNIX_TIME) |
| 1188 |
|
| 1189 |
_ = int(struct.unpack('<d', page.read(8))[ |
| 1190 |
0] + self.APPLE_TO_UNIX_TIME) |
| 1191 |
|
| 1192 |
page.seek(cookie_offset + host_offset, 0) |
| 1193 |
host = self.__read_until_null(page) |
| 1194 |
page.seek(cookie_offset + name_offset, 0) |
| 1195 |
name = self.__read_until_null(page) |
| 1196 |
page.seek(cookie_offset + path_offset, 0) |
| 1197 |
path = self.__read_until_null(page) |
| 1198 |
page.seek(cookie_offset + value_offset, 0) |
| 1199 |
value = self.__read_until_null(page) |
| 1200 |
if comment_offset: |
| 1201 |
page.seek(cookie_offset + comment_offset, 0) |
| 1202 |
|
| 1203 |
_ = self.__read_until_null(page) |
| 1204 |
|
| 1205 |
return create_cookie(host, path, is_secure, expiry_date, name, value, is_httponly) |
| 1206 |
|
| 1207 |
def __domain_filter(self, cookie: http.cookiejar.Cookie): |
| 1208 |
if not self.__domain_name: |
| 1209 |
return True |
| 1210 |
return self.__domain_name in cookie.domain |
| 1211 |
|
| 1212 |
def __parse_page(self, page_index: int): |
| 1213 |
offset = 8 + self.__total_page * 4 + \ |
| 1214 |
sum(self.__page_sizes[:page_index]) |
| 1215 |
page = self.__read_file(self.__page_sizes[page_index], offset) |
| 1216 |
assert page.read(4) == b'\x00\x00\x01\x00', self.NEW_ISSUE_MESSAGE |
| 1217 |
n_cookies = struct.unpack('<I', page.read(4))[0] |
| 1218 |
cookie_offsets = [] |
| 1219 |
for _ in range(n_cookies): |
| 1220 |
cookie_offsets.append(struct.unpack('<I', page.read(4))[0]) |
| 1221 |
assert page.read(4) == b'\x00\x00\x00\x00', self.NEW_ISSUE_MESSAGE |
| 1222 |
|
| 1223 |
for offset in cookie_offsets: |
| 1224 |
yield self.__parse_cookie(page, offset) |
| 1225 |
|
| 1226 |
def load(self): |
| 1227 |
cj = http.cookiejar.CookieJar() |
| 1228 |
for i in range(self.__total_page): |
| 1229 |
for cookie in self.__parse_page(i): |
| 1230 |
if self.__domain_filter(cookie): |
| 1231 |
cj.set_cookie(cookie) |
| 1232 |
return cj |
| 1233 |
|
| 1234 |
|
| 1235 |
class Lynx: |
| 1236 |
"""Class for Lynx""" |
| 1237 |
|
| 1238 |
lynx_cookies = [ |
| 1239 |
'~/.lynx_cookies', |
| 1240 |
'~/cookies' |
| 1241 |
] |
| 1242 |
|
| 1243 |
def __init__(self, cookie_file=None, domain_name=""): |
| 1244 |
self.cookie_file = _expand_paths(cookie_file or self.lynx_cookies, 'linux') |
| 1245 |
self.domain_name = domain_name |
| 1246 |
|
| 1247 |
def load(self): |
| 1248 |
cj = http.cookiejar.CookieJar() |
| 1249 |
if not self.cookie_file: |
| 1250 |
raise BrowserCookieError('Cannot find Lynx cookie file') |
| 1251 |
with open(self.cookie_file) as f: |
| 1252 |
for line in f.read().splitlines(): |
| 1253 |
|
| 1254 |
domain, domain_specified, path, secure, expires, name, value = \ |
| 1255 |
[None if word == '' else word for word in line.split('\t')] |
| 1256 |
domain_specified = domain_specified == 'TRUE' |
| 1257 |
secure = secure == 'TRUE' |
| 1258 |
if domain.find(self.domain_name) >= 0: |
| 1259 |
cookie = create_cookie(domain, path, secure, expires, name, |
| 1260 |
value, False) |
| 1261 |
cj.set_cookie(cookie) |
| 1262 |
return cj |
| 1263 |
|
| 1264 |
|
| 1265 |
class W3m: |
| 1266 |
"""Class for W3m""" |
| 1267 |
|
| 1268 |
|
| 1269 |
COO_USE = 1 |
| 1270 |
COO_SECURE = 2 |
| 1271 |
COO_DOMAIN = 4 |
| 1272 |
COO_PATH = 8 |
| 1273 |
COO_DISCARD = 16 |
| 1274 |
COO_OVERRIDE = 32 |
| 1275 |
w3m_cookies = [ |
| 1276 |
'~/.w3m/cookie' |
| 1277 |
] |
| 1278 |
|
| 1279 |
def __init__(self, cookie_file=None, domain_name=""): |
| 1280 |
self.cookie_file = _expand_paths(cookie_file or self.w3m_cookies, 'linux') |
| 1281 |
self.domain_name = domain_name |
| 1282 |
|
| 1283 |
def load(self): |
| 1284 |
cj = http.cookiejar.CookieJar() |
| 1285 |
if not self.cookie_file: |
| 1286 |
raise BrowserCookieError('Cannot find W3m cookie file') |
| 1287 |
with open(self.cookie_file) as f: |
| 1288 |
for line in f.read().splitlines(): |
| 1289 |
|
| 1290 |
url, name, value, expires, domain, path, flag, version, comment, \ |
| 1291 |
port, comment_url = \ |
| 1292 |
[None if word == '' else word for word in line.split('\t')] |
| 1293 |
flag = int(flag) |
| 1294 |
expires = int(expires) |
| 1295 |
secure = bool(flag & self.COO_SECURE) |
| 1296 |
domain_specified = bool(flag & self.COO_DOMAIN) |
| 1297 |
path_specified = bool(flag & self.COO_PATH) |
| 1298 |
discard = bool(flag & self.COO_DISCARD) |
| 1299 |
if domain.find(self.domain_name) >= 0: |
| 1300 |
cookie = http.cookiejar.Cookie(version, name, value, port, |
| 1301 |
bool(port), domain, domain_specified, |
| 1302 |
domain.startswith('.'), path, path_specified, secure, |
| 1303 |
expires, discard, comment, comment_url, {}) |
| 1304 |
cj.set_cookie(cookie) |
| 1305 |
return cj |
| 1306 |
|
| 1307 |
|
| 1308 |
def create_cookie(host, path, secure, expires, name, value, http_only): |
| 1309 |
"""Shortcut function to create a cookie""" |
| 1310 |
|
| 1311 |
return http.cookiejar.Cookie(0, name, value, None, False, host, host.startswith('.'), host.startswith('.'), path, |
| 1312 |
True, secure, expires, False, None, None, |
| 1313 |
{'HTTPOnly': ''} if http_only else {}) |
| 1314 |
|
| 1315 |
|
| 1316 |
def chrome(cookie_file=None, domain_name="", key_file=None): |
| 1317 |
"""Returns a cookiejar of the cookies used by Chrome. Optionally pass in a |
| 1318 |
domain name to only load cookies from the specified domain |
| 1319 |
""" |
| 1320 |
return Chrome(cookie_file, domain_name, key_file).load() |
| 1321 |
|
| 1322 |
|
| 1323 |
def arc(cookie_file=None, domain_name="", key_file=None): |
| 1324 |
"""Returns a cookiejar of the cookies used by Arc. Optionally pass in a |
| 1325 |
domain name to only load cookies from the specified domain |
| 1326 |
""" |
| 1327 |
return Arc(cookie_file, domain_name, key_file).load() |
| 1328 |
|
| 1329 |
|
| 1330 |
def chromium(cookie_file=None, domain_name="", key_file=None): |
| 1331 |
"""Returns a cookiejar of the cookies used by Chromium. Optionally pass in a |
| 1332 |
domain name to only load cookies from the specified domain |
| 1333 |
""" |
| 1334 |
return Chromium(cookie_file, domain_name, key_file).load() |
| 1335 |
|
| 1336 |
|
| 1337 |
def opera(cookie_file=None, domain_name="", key_file=None): |
| 1338 |
"""Returns a cookiejar of the cookies used by Opera. Optionally pass in a |
| 1339 |
domain name to only load cookies from the specified domain |
| 1340 |
""" |
| 1341 |
return Opera(cookie_file, domain_name, key_file).load() |
| 1342 |
|
| 1343 |
|
| 1344 |
def opera_gx(cookie_file=None, domain_name="", key_file=None): |
| 1345 |
"""Returns a cookiejar of the cookies used by Opera GX. Optionally pass in a |
| 1346 |
domain name to only load cookies from the specified domain |
| 1347 |
""" |
| 1348 |
return OperaGX(cookie_file, domain_name, key_file).load() |
| 1349 |
|
| 1350 |
|
| 1351 |
def brave(cookie_file=None, domain_name="", key_file=None): |
| 1352 |
"""Returns a cookiejar of the cookies and sessions used by Brave. Optionally |
| 1353 |
pass in a domain name to only load cookies from the specified domain |
| 1354 |
""" |
| 1355 |
return Brave(cookie_file, domain_name, key_file).load() |
| 1356 |
|
| 1357 |
|
| 1358 |
def edge(cookie_file=None, domain_name="", key_file=None): |
| 1359 |
"""Returns a cookiejar of the cookies used by Microsoft Edge. Optionally pass in a |
| 1360 |
domain name to only load cookies from the specified domain |
| 1361 |
""" |
| 1362 |
return Edge(cookie_file, domain_name, key_file).load() |
| 1363 |
|
| 1364 |
|
| 1365 |
def vivaldi(cookie_file=None, domain_name="", key_file=None): |
| 1366 |
"""Returns a cookiejar of the cookies used by Vivaldi Browser. Optionally pass in a |
| 1367 |
domain name to only load cookies from the specified domain |
| 1368 |
""" |
| 1369 |
return Vivaldi(cookie_file, domain_name, key_file).load() |
| 1370 |
|
| 1371 |
|
| 1372 |
def firefox(cookie_file=None, domain_name="", key_file=None): |
| 1373 |
"""Returns a cookiejar of the cookies and sessions used by Firefox. Optionally |
| 1374 |
pass in a domain name to only load cookies from the specified domain |
| 1375 |
""" |
| 1376 |
return Firefox(cookie_file, domain_name, key_file).load() |
| 1377 |
|
| 1378 |
|
| 1379 |
def librewolf(cookie_file=None, domain_name="", key_file=None): |
| 1380 |
"""Returns a cookiejar of the cookies and sessions used by LibreWolf. Optionally |
| 1381 |
pass in a domain name to only load cookies from the specified domain |
| 1382 |
""" |
| 1383 |
return LibreWolf(cookie_file, domain_name, key_file).load() |
| 1384 |
|
| 1385 |
|
| 1386 |
def safari(cookie_file=None, domain_name="", key_file=None): |
| 1387 |
"""Returns a cookiejar of the cookies and sessions used by Safari. Optionally |
| 1388 |
pass in a domain name to only load cookies from the specified domain |
| 1389 |
""" |
| 1390 |
return Safari(cookie_file, domain_name, key_file).load() |
| 1391 |
|
| 1392 |
def lynx(cookie_file=None, domain_name=""): |
| 1393 |
"""Returns a cookiejar of the cookies and sessions used by Lynx. Optionally |
| 1394 |
pass in a domain name to only load cookies from the specified domain |
| 1395 |
""" |
| 1396 |
return Lynx(cookie_file, domain_name).load() |
| 1397 |
|
| 1398 |
|
| 1399 |
def w3m(cookie_file=None, domain_name=""): |
| 1400 |
"""Returns a cookiejar of the cookies and sessions used by W3m. Optionally |
| 1401 |
pass in a domain name to only load cookies from the specified domain |
| 1402 |
""" |
| 1403 |
return W3m(cookie_file, domain_name).load() |
| 1404 |
|
| 1405 |
all_browsers = [chrome, chromium, opera, opera_gx, brave, edge, vivaldi, firefox, librewolf, safari, lynx, w3m, arc] |
| 1406 |
|
| 1407 |
def load(domain_name=""): |
| 1408 |
"""Try to load cookies from all supported browsers and return combined cookiejar |
| 1409 |
Optionally pass in a domain name to only load cookies from the specified domain |
| 1410 |
""" |
| 1411 |
cj = http.cookiejar.CookieJar() |
| 1412 |
for cookie_fn in all_browsers: |
| 1413 |
try: |
| 1414 |
for cookie in cookie_fn(domain_name=domain_name): |
| 1415 |
cj.set_cookie(cookie) |
| 1416 |
except BrowserCookieError: |
| 1417 |
pass |
| 1418 |
return cj |
| 1419 |
|
| 1420 |
|
| 1421 |
__all__ = ['BrowserCookieError', 'load', 'all_browsers'] + all_browsers |
| 1422 |
|
| 1423 |
|
| 1424 |
if __name__ == '__main__': |
| 1425 |
print(load()) |