-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
684 lines (575 loc) · 27.6 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
# -*- coding: utf-8 -*-
import os
import os.path
import sys
import time
import glob
import http.cookiejar
import tempfile
import lz4.block
import datetime
import configparser
import base64
from Crypto.Cipher import AES
from typing import Union
try:
import json
except ImportError:
import simplejson as json
try:
# 应该使用pysqlit2来读取cookie。sqlite在Windows上
# 否则将引发“sqlite3。数据库错误:文件加密或不是数据库异常
from pysqlite2 import dbapi2 as sqlite3
except ImportError:
import sqlite3
# 外部依赖关系
import keyring
import pyaes
from pbkdf2 import PBKDF2
__doc__ = 'Load browser cookies into a cookiejar'
class BrowserCookieError(Exception):
pass
def create_local_copy(cookie_file):
"""
创建一个sqlite cookie数据库的本地副本,并返回新的文件名。
如果在用户浏览时数据库仍在被写入,这是必要的
避免sqlite锁定错误。
"""
# check if cookie file exists
if os.path.exists(cookie_file):
# 复制到TMP文件夹中的随机名称
tmp_cookie_file = tempfile.NamedTemporaryFile(suffix='.sqlite').name
open(tmp_cookie_file, 'wb').write(open(cookie_file, 'rb').read())
return tmp_cookie_file
else:
raise BrowserCookieError('Can not find cookie file at: ' + cookie_file)
def windows_group_policy_path():
# 我们知道我们现在是在Windows下运行,所以导入是安全的
from winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKeyEx, QueryValueEx, REG_EXPAND_SZ, REG_SZ
try:
root = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
policy_key = OpenKeyEx(root, r"SOFTWARE\Policies\Google\Chrome")
user_data_dir, type_ = QueryValueEx(policy_key, "UserDataDir")
if type_ == REG_EXPAND_SZ:
user_data_dir = os.path.expandvars(user_data_dir)
elif type_ != REG_SZ:
return None
except OSError:
return None
return os.path.join(user_data_dir, "Default", "Cookies")
def crypt_unprotect_data(
cipher_text=b'', entropy=b'', reserved=None, prompt_struct=None, is_key=False
):
import ctypes
import ctypes.wintypes
class DataBlob(ctypes.Structure):
_fields_ = [
('cbData', ctypes.wintypes.DWORD),
('pbData', ctypes.POINTER(ctypes.c_char))
]
blob_in, blob_entropy, blob_out = map(
lambda x: DataBlob(len(x), ctypes.create_string_buffer(x)),
[cipher_text, entropy, b'']
)
desc = ctypes.c_wchar_p()
CRYPTPROTECT_UI_FORBIDDEN = 0x01
if not ctypes.windll.crypt32.CryptUnprotectData(
ctypes.byref(blob_in), ctypes.byref(
desc), ctypes.byref(blob_entropy),
reserved, prompt_struct, CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(
blob_out)
):
raise RuntimeError('Failed to decrypt the cipher text with DPAPI')
description = desc.value
buffer_out = ctypes.create_string_buffer(int(blob_out.cbData))
ctypes.memmove(buffer_out, blob_out.pbData, blob_out.cbData)
map(ctypes.windll.kernel32.LocalFree, [desc, blob_out.pbData])
if is_key:
return description, buffer_out.raw
else:
return description, buffer_out.value
def get_linux_pass(os_crypt_name):
"""Retrive password used to encrypt cookies from libsecret"""
my_pass = None
import secretstorage
connection = secretstorage.dbus_init()
collection = secretstorage.get_default_collection(connection)
secret = None
secret = next(collection.search_items(
{'xdg:schema': 'chrome_libsecret_os_crypt_password_v2',
'application': os_crypt_name}), None)
if not secret:
# trying os_crypt_v1
secret = next(collection.search_items(
{'xdg:schema': 'chrome_libsecret_os_crypt_password_v1',
'application': os_crypt_name}), None)
if secret:
my_pass = secret.get_secret()
connection.close()
# 尝试从keyring获得通行证,它应该支持KDE / KWallet
if not my_pass:
try:
my_pass = keyring.get_password(
"{} Keys".format(os_crypt_name.capitalize()),
"{} Safe Storage".format(os_crypt_name.capitalize())
).encode('utf-8')
except RuntimeError:
pass
except AttributeError:
pass
# try default peanuts password, probably won't work
if not my_pass:
my_pass = 'peanuts'.encode('utf-8')
return my_pass
def __expand_win_path(path:Union[dict,str]):
if not isinstance(path,dict):
path = {'path': path}
return os.path.join(os.getenv(path['env'], ''), path['path'])
def expand_paths(paths:list, os_name:str):
"""Expands user paths on Linux, OSX, and windows"""
os_name = os_name.lower()
assert os_name in ['windows', 'osx', 'linux']
if not isinstance(paths, list):
paths = [paths]
if os_name == 'windows':
paths = map(__expand_win_path, paths)
else:
paths = map(os.path.expanduser, paths)
paths = next(filter(os.path.exists, paths), None)
return paths
def text_factory(data):
try:
return data.decode('utf-8')
except UnicodeDecodeError:
return data
class ChromiumBased:
"""Super class for all Chromium based browser"""
def __init__(self, browser:str, cookie_file=None, domain_name="", key_file=None, **kwargs):
self.salt = b'saltysalt'
self.iv = b' ' * 16
self.length = 16
self.browser = browser
self.cookie_file = cookie_file
self.domain_name = domain_name
self.key_file = key_file
self.__add_key_and_cookie_file(**kwargs)
def __add_key_and_cookie_file(self,
linux_cookies=None, windows_cookies=None, osx_cookies=None,
windows_keys=None, os_crypt_name=None, osx_key_service=None, osx_key_user=None):
if sys.platform == 'darwin':
# 在OSX上运行Chromium或者它的衍生物
my_pass = keyring.get_password(osx_key_service, osx_key_user)
# 尝试默认花生密码,可能不会工作
if not my_pass:
my_pass = 'peanuts'
my_pass = my_pass.encode('utf-8')
iterations = 1003 # MAC上的pbkdf2迭代数
self.key = PBKDF2(my_pass, self.salt,
iterations=iterations).read(self.length)
cookie_file = self.cookie_file or expand_paths(osx_cookies,'osx')
elif sys.platform.startswith('linux'):
my_pass = get_linux_pass(os_crypt_name)
iterations = 1
self.key = PBKDF2(my_pass, self.salt,
iterations=iterations).read(self.length)
cookie_file = self.cookie_file or expand_paths(linux_cookies, 'linux')
elif sys.platform == "win32":
key_file = self.key_file or expand_paths(windows_keys,'windows')
if key_file:
with open(key_file,'rb') as f:
key_file_json = json.load(f)
key64 = key_file_json['os_crypt']['encrypted_key'].encode('utf-8')
# Decode Key, get rid of DPAPI prefix, unprotect data
keydpapi = base64.standard_b64decode(key64)[5:]
_, self.key = crypt_unprotect_data(keydpapi, is_key=True)
# get cookie file from APPDATA
cookie_file = self.cookie_file
if not cookie_file:
if self.browser.lower() == 'chrome' and windows_group_policy_path():
cookie_file = windows_group_policy_path()
else:
cookie_file = expand_paths(windows_cookies,'windows')
else:
raise BrowserCookieError(
"OS not recognized. Works on OSX, Windows, and Linux.")
if not cookie_file:
raise BrowserCookieError('Failed to find {} cookie'.format(self.browser))
self.tmp_cookie_file = create_local_copy(cookie_file)
def __del__(self):
# 删除sqlite cookie数据库的临时备份
if hasattr(self, 'tmp_cookie_file'): # if there was an error till here
os.remove(self.tmp_cookie_file)
def __str__(self):
return self.browser
def load(self):
"""将sqlite cookie加载到cookie罐中"""
con = sqlite3.connect(self.tmp_cookie_file)
con.text_factory = text_factory
cur = con.cursor()
try:
# chrome <=55
cur.execute('SELECT host_key, path, secure, expires_utc, name, value, encrypted_value '
'FROM cookies WHERE host_key like ?;', ('%{}%'.format(self.domain_name),))
except sqlite3.OperationalError:
# chrome >=56
cur.execute('SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value '
'FROM cookies WHERE host_key like ?;', ('%{}%'.format(self.domain_name),))
cj = http.cookiejar.CookieJar()
for item in cur.fetchall():
# chrome浏览器使用expires_utc字段作为cookie数据库的时间戳,expires_utc使用NT时间epoch,而http cookiejar使用Unix时间epoch。
# NT time epoch,又名Win32 time/FILETIME,从格林尼治时间1601-01-01 0:00:00开始,单位为100纳秒。
# Unix时间epoch,即Unix epoch /POSIX,从1970-01-01 0:00:00 GMT开始,单位为秒。
# 如果这个cookie只对这个会话有效,那么在chrome浏览器的cookie数据库中expires_utc为0,它应该在cookiejar中设置为None。
host, path, secure, expires_nt_time_epoch, name = item[:5]
if (expires_nt_time_epoch == 0):
expires = None
else:
# 确保日期不超过10000年的日期时间限制
try:
expires_nt_time_epoch = min(int(expires_nt_time_epoch), 265000000000000000)
expires = (expires_nt_time_epoch/1000000)-11644473600
# Windows 7还有进一步的限制
except OSError:
expires_nt_time_epoch = min(int(expires_nt_time_epoch), 32536799999000000)
expires = (expires_nt_time_epoch/1000000)-11644473600
value = self._decrypt(item[5], item[6])
c = create_cookie(host, path, secure, expires, name, value)
cj.set_cookie(c)
con.close()
return cj
@staticmethod
def _decrypt_windows_chromium(value, encrypted_value):
if len(value) != 0:
return value
if encrypted_value == "":
return ""
_, data = crypt_unprotect_data(encrypted_value)
assert isinstance(data, bytes)
return data.decode()
def _decrypt(self, value, encrypted_value):
"""Decrypt encoded cookies"""
if sys.platform == 'win32':
try:
return self._decrypt_windows_chromium(value, encrypted_value)
# 修复了Chrome 80的变化
except RuntimeError: # Failed to decrypt the cipher text with DPAPI
if not self.key:
raise RuntimeError(
'Failed to decrypt the cipher text with DPAPI and no AES key.')
# #加密的cookie应该以“v10”作为前缀根据
# Chromium code. 关闭.
encrypted_value = encrypted_value[3:]
nonce, tag = encrypted_value[:12], encrypted_value[-16:]
aes = AES.new(self.key, AES.MODE_GCM, nonce=nonce)
# 如果密钥错误,MAC检查失败。
# 可能我们没有钥匙,用了花生
try:
data = aes.decrypt_and_verify(encrypted_value[12:-16], tag)
except ValueError:
raise BrowserCookieError('Unable to get key for cookie decryption')
return data.decode()
if value or (encrypted_value[:3] not in [b'v11', b'v10']):
return value
# 加密的cookie应该以“v10”作为前缀
# Chromium code. Strip it off.
encrypted_value = encrypted_value[3:]
encrypted_value_half_len = int(len(encrypted_value) / 2)
cipher = pyaes.Decrypter(
pyaes.AESModeOfOperationCBC(self.key, self.iv))
# 如果键是错误的,将上升值错误:无效填充字节
# 可能是我们没拿到钥匙
try:
decrypted = cipher.feed(encrypted_value[:encrypted_value_half_len])
decrypted += cipher.feed(encrypted_value[encrypted_value_half_len:])
decrypted += cipher.feed()
except ValueError:
raise BrowserCookieError('Unable to get key for cookie decryption')
return decrypted.decode("utf-8")
class Chrome(ChromiumBased):
"""Class for Google Chrome"""
def __init__(self, cookie_file=None, domain_name="", key_file=None):
args = {
'linux_cookies':[
'~/.config/google-chrome/Default/Cookies',
'~/.config/google-chrome-beta/Default/Cookies'
],
'windows_cookies':[
{'env':'APPDATA', 'path':'..\\Local\\Google\\Chrome\\User Data\\Default\\Network\\Cookies'},
{'env': 'APPDATA', 'path': '..\\Local\\Google\\Chrome\\User Data\\Default\\Cookies'},
{'env':'LOCALAPPDATA', 'path':'Google\\Chrome\\User Data\\Default\\Cookies'},
{'env':'APPDATA', 'path':'Google\\Chrome\\User Data\\Default\\Cookies'}
],
'osx_cookies': ['~/Library/Application Support/Google/Chrome/Default/Cookies'],
'windows_keys': [
{'env':'APPDATA', 'path':'..\\Local\\Google\\Chrome\\User Data\\Local State'},
{'env':'LOCALAPPDATA', 'path':'Google\\Chrome\\User Data\\Local State'},
{'env':'APPDATA', 'path':'Google\\Chrome\\User Data\\Local State'}
],
'os_crypt_name':'chrome',
'osx_key_service' : 'Chrome Safe Storage',
'osx_key_user' : 'Chrome'
}
super().__init__(browser='Chrome', cookie_file=cookie_file, domain_name=domain_name, key_file=key_file, **args)
class Chromium(ChromiumBased):
"""Class for Chromium"""
def __init__(self, cookie_file=None, domain_name="", key_file=None):
args = {
'linux_cookies':['~/.config/chromium/Default/Cookies'],
'windows_cookies':[
{'env':'APPDATA', 'path':'..\\Local\\Chromium\\User Data\\Default\\Cookies'},
{'env':'LOCALAPPDATA', 'path':'Chromium\\User Data\\Default\\Cookies'},
{'env':'APPDATA', 'path':'Chromium\\User Data\\Default\\Cookies'}
],
'osx_cookies': ['~/Library/Application Support/Chromium/Default/Cookies'],
'windows_keys': [
{'env':'APPDATA', 'path':'..\\Local\\Chromium\\User Data\\Local State'},
{'env':'LOCALAPPDATA', 'path':'Chromium\\User Data\\Local State'},
{'env':'APPDATA', 'path':'Chromium\\User Data\\Local State'}
],
'os_crypt_name':'chromium',
'osx_key_service' : 'Chromium Safe Storage',
'osx_key_user' : 'Chromium'
}
super().__init__(browser='Chromium', cookie_file=cookie_file, domain_name=domain_name, key_file=key_file, **args)
class Opera(ChromiumBased):
"""Class for Opera"""
def __init__(self, cookie_file=None, domain_name="", key_file=None):
args = {
'linux_cookies': ['~/.config/opera/Cookies'],
'windows_cookies':[
{'env':'APPDATA', 'path':'..\\Local\\Opera Software\\Opera Stable\\Cookies'},
{'env':'LOCALAPPDATA', 'path':'Opera Software\\Opera Stable\\Cookies'},
{'env':'APPDATA', 'path':'Opera Software\\Opera Stable\\Cookies'}
],
'osx_cookies': ['~/Library/Application Support/com.operasoftware.Opera/Cookies'],
'windows_keys': [
{'env':'APPDATA', 'path':'..\\Local\\Opera Software\\Opera Stable\\Local State'},
{'env':'LOCALAPPDATA', 'path':'Opera Software\\Opera Stable\\Local State'},
{'env':'APPDATA', 'path':'Opera Software\\Opera Stable\\Local State'}
],
'os_crypt_name':'chromium',
'osx_key_service' : 'Opera Safe Storage',
'osx_key_user' : 'Opera'
}
super().__init__(browser='Opera', cookie_file=cookie_file, domain_name=domain_name, key_file=key_file, **args)
class Brave(ChromiumBased):
def __init__(self, cookie_file=None, domain_name="", key_file=None):
args = {
'linux_cookies':[
'~/.config/BraveSoftware/Brave-Browser/Default/Cookies',
'~/.config/BraveSoftware/Brave-Browser-Beta/Default/Cookies'
],
'windows_cookies':[
{'env':'APPDATA', 'path':'..\\Local\\BraveSoftware\\Brave-Browser\\User Data\\Default\\Cookies'},
{'env':'LOCALAPPDATA', 'path':'BraveSoftware\\Brave-Browser\\User Data\\Default\\Cookies'},
{'env':'APPDATA', 'path':'BraveSoftware\\Brave-Browser\\User Data\\Default\\Cookies'},
{'env':'APPDATA', 'path':'..\\Local\\BraveSoftware\\Brave-Browser-Beta\\User Data\\Default\\Cookies'},
{'env':'LOCALAPPDATA', 'path':'BraveSoftware\\Brave-Browser-Beta\\User Data\\Default\\Cookies'},
{'env':'APPDATA', 'path':'BraveSoftware\\Brave-Browser-Beta\\User Data\\Default\\Cookies'}
],
'osx_cookies': [
'~/Library/Application Support/BraveSoftware/Brave-Browser/Default/Cookies',
'~/Library/Application Support/BraveSoftware/Brave-Browser-Beta/Default/Cookies'
],
'windows_keys': [
{'env':'APPDATA', 'path':'..\\Local\\BraveSoftware\\Brave-Browser\\User Data\\Local State'},
{'env':'LOCALAPPDATA', 'path':'BraveSoftware\\Brave-Browser\\User Data\\Local State'},
{'env':'APPDATA', 'path':'BraveSoftware\\Brave-Browser\\User Data\\Local State'},
{'env':'APPDATA', 'path':'..\\Local\\BraveSoftware\\Brave-Browser-Beta\\User Data\\Local State'},
{'env':'LOCALAPPDATA', 'path':'BraveSoftware\\Brave-Browse-Betar\\User Data\\Local State'},
{'env':'APPDATA', 'path':'BraveSoftware\\Brave-Browser-Beta\\User Data\\Local State'}
],
'os_crypt_name':'brave',
'osx_key_service' : 'Brave Safe Storage',
'osx_key_user' : 'Brave'
}
super().__init__(browser='Brave', cookie_file=cookie_file, domain_name=domain_name, key_file=key_file, **args)
class Edge(ChromiumBased):
"""Class for Microsoft Edge"""
def __init__(self, cookie_file=None, domain_name="", key_file=None):
args = {
'linux_cookies': [
'~/.config/microsoft-edge/Default/Cookies',
'~/.config/microsoft-edge-dev/Default/Cookies'
],
'windows_cookies':[
{'env':'APPDATA', 'path':'..\\Local\\Microsoft\\Edge\\User Data\\Default\\Cookies'},
{'env':'LOCALAPPDATA', 'path':'Microsoft\\Edge\\User Data\\Default\\Cookies'},
{'env':'APPDATA', 'path':'Microsoft\\Edge\\User Data\\Default\\Cookies'}
],
'osx_cookies': ['~/Library/Application Support/Microsoft Edge/Default/Cookies'],
'windows_keys': [
{'env':'APPDATA', 'path':'..\\Local\\Microsoft\\Edge\\User Data\\Local State'},
{'env':'LOCALAPPDATA', 'path':'Microsoft\\Edge\\User Data\\Local State'},
{'env':'APPDATA', 'path':'Microsoft\\Edge\\User Data\\Local State'}
],
'os_crypt_name':'chromium',
'osx_key_service' : 'Microsoft Edge Safe Storage',
'osx_key_user' : 'Microsoft Edge'
}
super().__init__(browser='Edge', cookie_file=cookie_file, domain_name=domain_name, key_file=key_file, **args)
class Firefox:
"""Class for Firefox"""
def __init__(self, cookie_file=None, domain_name=""):
self.tmp_cookie_file = None
cookie_file = cookie_file or self.find_cookie_file()
self.tmp_cookie_file = create_local_copy(cookie_file)
# 当前会话保存在sessionstore.js中
self.session_file = os.path.join(
os.path.dirname(cookie_file), 'sessionstore.js')
self.session_file_lz4 = os.path.join(os.path.dirname(
cookie_file), 'sessionstore-backups', 'recovery.jsonlz4')
# domain name to filter cookies by
self.domain_name = domain_name
def __del__(self):
# 删除sqlite cookie数据库的临时备份
if self.tmp_cookie_file:
os.remove(self.tmp_cookie_file)
def __str__(self):
return 'firefox'
@staticmethod
def get_default_profile(user_data_path):
config = configparser.ConfigParser()
profiles_ini_path = glob.glob(os.path.join(
user_data_path + '**', 'profiles.ini'))
fallback_path = user_data_path + '**'
if not profiles_ini_path:
return fallback_path
profiles_ini_path = profiles_ini_path[0]
config.read(profiles_ini_path)
profile_path = None
for section in config.sections():
if section.startswith('Install'):
profile_path = config[section].get('Default')
break
# 在ff 72.0.1中,如果同时存在Install节和Default=1节,前者优先
elif config[section].get('Default') == '1' and not profile_path:
profile_path = config[section].get('Path')
for section in config.sections():
# 安装部分没有相对/绝对信息,所以请检查配置文件
if config[section].get('Path') == profile_path:
absolute = config[section].get('IsRelative') == '0'
return profile_path if absolute else os.path.join(os.path.dirname(profiles_ini_path), profile_path)
return fallback_path
@staticmethod
def find_cookie_file():
cookie_files = []
if sys.platform == 'darwin':
user_data_path = os.path.expanduser(
'~/Library/Application Support/Firefox')
elif sys.platform.startswith('linux'):
user_data_path = os.path.expanduser('~/.mozilla/firefox')
elif sys.platform == 'win32':
user_data_path = os.path.join(
os.environ.get('APPDATA'), 'Mozilla', 'Firefox')
# legacy firefox <68 fallback
cookie_files = glob.glob(os.path.join(os.environ.get('PROGRAMFILES'), 'Mozilla Firefox', 'profile', 'cookies.sqlite')) \
or glob.glob(os.path.join(os.environ.get('PROGRAMFILES(X86)'), 'Mozilla Firefox', 'profile', 'cookies.sqlite'))
else:
raise BrowserCookieError(
'Unsupported operating system: ' + sys.platform)
cookie_files = glob.glob(os.path.join(Firefox.get_default_profile(user_data_path), 'cookies.sqlite')) \
or cookie_files
if cookie_files:
return cookie_files[0]
else:
raise BrowserCookieError('Failed to find Firefox cookie')
@staticmethod
def __create_session_cookie(cookie_json):
expires = str(int(time.time()) + 3600 * 24 * 7)
return create_cookie(cookie_json.get('host', ''), cookie_json.get('path', ''), False, expires,
cookie_json.get('name', ''), cookie_json.get('value', ''))
def __add_session_cookies(self, cj):
if not os.path.exists(self.session_file):
return
try:
json_data = json.loads(
open(self.session_file, 'rb').read().decode())
except ValueError as e:
print('Error parsing firefox session JSON:', str(e))
else:
for window in json_data.get('windows', []):
for cookie in window.get('cookies', []):
if self.domain_name == '' or self.domain_name in cookie.get('host', ''):
cj.set_cookie(Firefox.__create_session_cookie(cookie))
def __add_session_cookies_lz4(self, cj):
if not os.path.exists(self.session_file_lz4):
return
try:
file_obj = open(self.session_file_lz4, 'rb')
file_obj.read(8)
json_data = json.loads(lz4.block.decompress(file_obj.read()))
except ValueError as e:
print('Error parsing firefox session JSON LZ4:', str(e))
else:
for cookie in json_data.get('cookies', []):
if self.domain_name == '' or self.domain_name in cookie.get('host', ''):
cj.set_cookie(Firefox.__create_session_cookie(cookie))
def load(self):
con = sqlite3.connect(self.tmp_cookie_file)
cur = con.cursor()
cur.execute('select host, path, isSecure, expiry, name, value from moz_cookies '
'where host like ?', ('%{}%'.format(self.domain_name),))
cj = http.cookiejar.CookieJar()
for item in cur.fetchall():
c = create_cookie(*item)
cj.set_cookie(c)
con.close()
self.__add_session_cookies(cj)
self.__add_session_cookies_lz4(cj)
return cj
def create_cookie(host, path, secure, expires, name, value):
"""创建cookie的快捷函数"""
return http.cookiejar.Cookie(0, name, value, None, False, host, host.startswith('.'), host.startswith('.'), path,
True, secure, expires, False, None, None, {})
def chrome(cookie_file=None, domain_name="", key_file=None):
"""
返回Chrome使用的cookie的cookie罐。可选地传入
域名只能从指定的域加载cookie
"""
return Chrome(cookie_file, domain_name, key_file).load()
def chromium(cookie_file=None, domain_name="", key_file=None):
"""
返回一个包含Chromium使用的cookie的cookie罐。可选地传入
域名只能从指定的域加载cookie
"""
return Chromium(cookie_file, domain_name, key_file).load()
def opera(cookie_file=None, domain_name="", key_file=None):
"""
返回一个包含Opera使用的cookie的cookie罐。可选地传入
域名只能从指定的域加载cookie
"""
return Opera(cookie_file, domain_name, key_file).load()
def brave(cookie_file=None, domain_name="", key_file=None):
"""
返回Brave使用的cookie和会话的cookie罐子。(可选)
传入一个域名,只从指定的域加载cookie
"""
return Brave(cookie_file, domain_name, key_file).load()
def edge(cookie_file=None, domain_name="", key_file=None):
"""
返回Microsoft Egde使用的cookie的cookie罐。可选地传入
域名只能从指定的域加载cookie
"""
return Edge(cookie_file, domain_name, key_file).load()
def firefox(cookie_file=None, domain_name=""):
"""
返回一个包含Firefox使用的cookie和会话的cookie罐。(可选)
传入一个域名,只从指定的域加载cookie
"""
return Firefox(cookie_file, domain_name).load()
def load(domain_name=""):
"""
尝试从所有支持的浏览器加载cookie,并返回组合的cookiejar
可选地传入一个域名,以便只从指定的域加载cookie
"""
cj = http.cookiejar.CookieJar()
for cookie_fn in [chrome, chromium, opera, brave, edge, firefox]:
try:
for cookie in cookie_fn(domain_name=domain_name):
cj.set_cookie(cookie)
except BrowserCookieError:
pass
return cj
if __name__ == '__main__':
print(load())