重构代码
This commit is contained in:
1 parent
86de31f274
commit
f69b9e16e4
22 files changed
+371
-536
No files matched your search
@@ -5,5 +5,7 @@
|
||||
# Author: xaoyaoo
|
||||
# Date: 2023/08/21
|
||||
# -------------------------------------------------------------------------------
|
||||
from .get_wx_info import read_info
|
||||
from .get_wx_db import get_wechat_db
|
||||
from .get_wx_info import read_info, get_wechat_db
|
||||
from .get_bias_addr import BiasAddr
|
||||
from .decryption import batch_decrypt, encrypt, decrypt
|
||||
from .merge_db import merge_msg_db, merge_copy_db, merge_media_msg_db
|
||||
@@ -0,0 +1,227 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: getwxinfo.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2023/08/21
|
||||
# 微信数据库采用的加密算法是256位的AES-CBC。数据库的默认的页大小是4096字节即4KB,其中每一个页都是被单独加解密的。
|
||||
# 加密文件的每一个页都有一个随机的初始化向量,它被保存在每一页的末尾。
|
||||
# 加密文件的每一页都存有着消息认证码,算法使用的是HMAC-SHA1(安卓数据库使用的是SHA512)。它也被保存在每一页的末尾。
|
||||
# 每一个数据库文件的开头16字节都保存了一段唯一且随机的盐值,作为HMAC的验证和数据的解密。
|
||||
# 用来计算HMAC的key与解密的key是不同的,解密用的密钥是主密钥和之前提到的16字节的盐值通过PKCS5_PBKF2_HMAC1密钥扩展算法迭代64000次计算得到的。而计算HMAC的密钥是刚提到的解密密钥和16字节盐值异或0x3a的值通过PKCS5_PBKF2_HMAC1密钥扩展算法迭代2次计算得到的。
|
||||
# 为了保证数据部分长度是16字节即AES块大小的整倍数,每一页的末尾将填充一段空字节,使得保留字段的长度为48字节。
|
||||
# 综上,加密文件结构为第一页4KB数据前16字节为盐值,紧接着4032字节数据,再加上16字节IV和20字节HMAC以及12字节空字节;而后的页均是4048字节长度的加密数据段和48字节的保留段。
|
||||
# -------------------------------------------------------------------------------
|
||||
import argparse
|
||||
import hmac
|
||||
import hashlib
|
||||
import os
|
||||
from typing import Union, List
|
||||
from Cryptodome.Cipher import AES
|
||||
|
||||
# from Crypto.Cipher import AES # 如果上面的导入失败,可以尝试使用这个
|
||||
|
||||
SQLITE_FILE_HEADER = "SQLite format 3\x00" # SQLite文件头
|
||||
|
||||
KEY_SIZE = 32
|
||||
DEFAULT_PAGESIZE = 4096
|
||||
DEFAULT_ITER = 64000
|
||||
|
||||
|
||||
# 通过密钥解密数据库
|
||||
def decrypt(key: str, db_path, out_path):
|
||||
"""
|
||||
通过密钥解密数据库
|
||||
:param key: 密钥 64位16进制字符串
|
||||
:param db_path: 待解密的数据库路径(必须是文件)
|
||||
:param out_path: 解密后的数据库输出路径(必须是文件)
|
||||
:return:
|
||||
"""
|
||||
if not os.path.exists(db_path) or not os.path.isfile(db_path):
|
||||
return False, f"[-] db_path:'{db_path}' File not found!"
|
||||
if not os.path.exists(os.path.dirname(out_path)):
|
||||
return False, f"[-] out_path:'{out_path}' File not found!"
|
||||
|
||||
if len(key) != 64:
|
||||
return False, f"[-] key:'{key}' Len Error!"
|
||||
|
||||
password = bytes.fromhex(key.strip())
|
||||
with open(db_path, "rb") as file:
|
||||
blist = file.read()
|
||||
|
||||
salt = blist[:16]
|
||||
byteKey = hashlib.pbkdf2_hmac("sha1", password, salt, DEFAULT_ITER, KEY_SIZE)
|
||||
first = blist[16:DEFAULT_PAGESIZE]
|
||||
if len(salt) != 16:
|
||||
return False, f"[-] db_path:'{db_path}' File Error!"
|
||||
|
||||
mac_salt = bytes([(salt[i] ^ 58) for i in range(16)])
|
||||
mac_key = hashlib.pbkdf2_hmac("sha1", byteKey, mac_salt, 2, KEY_SIZE)
|
||||
hash_mac = hmac.new(mac_key, first[:-32], hashlib.sha1)
|
||||
hash_mac.update(b'\x01\x00\x00\x00')
|
||||
|
||||
if hash_mac.digest() != first[-32:-12]:
|
||||
return False, f"[-] Key Error! (key:'{key}'; db_path:'{db_path}'; out_path:'{out_path}' )"
|
||||
|
||||
newblist = [blist[i:i + DEFAULT_PAGESIZE] for i in range(DEFAULT_PAGESIZE, len(blist), DEFAULT_PAGESIZE)]
|
||||
|
||||
with open(out_path, "wb") as deFile:
|
||||
deFile.write(SQLITE_FILE_HEADER.encode())
|
||||
t = AES.new(byteKey, AES.MODE_CBC, first[-48:-32])
|
||||
decrypted = t.decrypt(first[:-48])
|
||||
deFile.write(decrypted)
|
||||
deFile.write(first[-48:])
|
||||
|
||||
for i in newblist:
|
||||
t = AES.new(byteKey, AES.MODE_CBC, i[-48:-32])
|
||||
decrypted = t.decrypt(i[:-48])
|
||||
deFile.write(decrypted)
|
||||
deFile.write(i[-48:])
|
||||
return True, [db_path, out_path, key]
|
||||
|
||||
|
||||
def batch_decrypt(key: str, db_path: Union[str, List[str]], out_path: str, is_logging: bool = False):
|
||||
if not isinstance(key, str) or not isinstance(out_path, str) or not os.path.exists(out_path) or len(key) != 64:
|
||||
error = f"[-] (key:'{key}' or out_path:'{out_path}') Error!"
|
||||
if is_logging: print(error)
|
||||
return False, error
|
||||
|
||||
process_list = []
|
||||
|
||||
if isinstance(db_path, str):
|
||||
if not os.path.exists(db_path):
|
||||
error = f"[-] db_path:'{db_path}' not found!"
|
||||
if is_logging: print(error)
|
||||
return False, error
|
||||
|
||||
if os.path.isfile(db_path):
|
||||
inpath = db_path
|
||||
outpath = os.path.join(out_path, 'de_' + os.path.basename(db_path))
|
||||
process_list.append([key, inpath, outpath])
|
||||
|
||||
elif os.path.isdir(db_path):
|
||||
for root, dirs, files in os.walk(db_path):
|
||||
for file in files:
|
||||
inpath = os.path.join(root, file)
|
||||
rel = os.path.relpath(root, db_path)
|
||||
outpath = os.path.join(out_path, rel, 'de_' + file)
|
||||
|
||||
if not os.path.exists(os.path.dirname(outpath)):
|
||||
os.makedirs(os.path.dirname(outpath))
|
||||
process_list.append([key, inpath, outpath])
|
||||
else:
|
||||
error = f"[-] db_path:'{db_path}' Error "
|
||||
if is_logging: print(error)
|
||||
return False, error
|
||||
|
||||
elif isinstance(db_path, list):
|
||||
rt_path = os.path.commonprefix(db_path)
|
||||
if not os.path.exists(rt_path):
|
||||
rt_path = os.path.dirname(rt_path)
|
||||
|
||||
for inpath in db_path:
|
||||
if not os.path.exists(inpath):
|
||||
erreor = f"[-] db_path:'{db_path}' not found!"
|
||||
if is_logging: print(erreor)
|
||||
return False, erreor
|
||||
|
||||
inpath = os.path.normpath(inpath)
|
||||
rel = os.path.relpath(os.path.dirname(inpath), rt_path)
|
||||
outpath = os.path.join(out_path, rel, 'de_' + os.path.basename(inpath))
|
||||
if not os.path.exists(os.path.dirname(outpath)):
|
||||
os.makedirs(os.path.dirname(outpath))
|
||||
process_list.append([key, inpath, outpath])
|
||||
else:
|
||||
error = f"[-] db_path:'{db_path}' Error "
|
||||
if is_logging: print(error)
|
||||
return False, error
|
||||
|
||||
result = []
|
||||
for i in process_list:
|
||||
result.append(decrypt(*i)) # 解密
|
||||
|
||||
# 删除空文件夹
|
||||
for root, dirs, files in os.walk(out_path, topdown=False):
|
||||
for dir in dirs:
|
||||
if not os.listdir(os.path.join(root, dir)):
|
||||
os.rmdir(os.path.join(root, dir))
|
||||
|
||||
if is_logging:
|
||||
print("=" * 32)
|
||||
success_count = 0
|
||||
fail_count = 0
|
||||
for code, ret in result:
|
||||
if code == False:
|
||||
print(ret)
|
||||
fail_count += 1
|
||||
else:
|
||||
print(f'[+] "{ret[0]}" -> "{ret[1]}"')
|
||||
success_count += 1
|
||||
print("-" * 32)
|
||||
print(f"[+] 共 {len(result)} 个文件, 成功 {success_count} 个, 失败 {fail_count} 个")
|
||||
print("=" * 32)
|
||||
return True, result
|
||||
|
||||
|
||||
def encrypt(key: str, db_path, out_path):
|
||||
"""
|
||||
通过密钥加密数据库
|
||||
:param key: 密钥 64位16进制字符串
|
||||
:param db_path: 待加密的数据库路径(必须是文件)
|
||||
:param out_path: 加密后的数据库输出路径(必须是文件)
|
||||
:return:
|
||||
"""
|
||||
if not os.path.exists(db_path) or not os.path.isfile(db_path):
|
||||
return False, f"[-] db_path:'{db_path}' File not found!"
|
||||
if not os.path.exists(os.path.dirname(out_path)):
|
||||
return False, f"[-] out_path:'{out_path}' File not found!"
|
||||
|
||||
if len(key) != 64:
|
||||
return False, f"[-] key:'{key}' Len Error!"
|
||||
|
||||
password = bytes.fromhex(key.strip())
|
||||
with open(db_path, "rb") as file:
|
||||
blist = file.read()
|
||||
|
||||
salt = os.urandom(16) # 生成随机盐值
|
||||
byteKey = hashlib.pbkdf2_hmac("sha1", password, salt, DEFAULT_ITER, KEY_SIZE)
|
||||
|
||||
# 计算消息认证码
|
||||
mac_salt = bytes([(salt[i] ^ 58) for i in range(16)])
|
||||
mac_key = hashlib.pbkdf2_hmac("sha1", byteKey, mac_salt, 2, KEY_SIZE)
|
||||
hash_mac = hmac.new(mac_key, blist[:-32], hashlib.sha1)
|
||||
hash_mac.update(b'\x01\x00\x00\x00')
|
||||
mac_digest = hash_mac.digest()
|
||||
|
||||
newblist = [blist[i:i + DEFAULT_PAGESIZE] for i in range(DEFAULT_PAGESIZE, len(blist), DEFAULT_PAGESIZE)]
|
||||
|
||||
with open(out_path, "wb") as enFile:
|
||||
enFile.write(salt) # 写入盐值
|
||||
enFile.write(mac_digest) # 写入消息认证码
|
||||
|
||||
for i in newblist:
|
||||
t = AES.new(byteKey, AES.MODE_CBC, os.urandom(16)) # 生成随机的初始向量
|
||||
encrypted = t.encrypt(i) # 加密数据块
|
||||
enFile.write(encrypted)
|
||||
|
||||
return True, [db_path, out_path, key]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 创建命令行参数解析器
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("-k", "--key", type=str, help="密钥", required=True)
|
||||
parser.add_argument("-i", "--db_path", type=str, help="数据库路径(目录or文件)", required=True)
|
||||
parser.add_argument("-o", "--out_path", type=str,
|
||||
help="输出路径(必须是目录),输出文件为 out_path/de_{original_name}", required=True)
|
||||
|
||||
# 解析命令行参数
|
||||
args = parser.parse_args()
|
||||
|
||||
# 从命令行参数获取值
|
||||
key = args.key
|
||||
db_path = args.db_path
|
||||
out_path = args.out_path
|
||||
|
||||
# 调用 decrypt 函数,并传入参数
|
||||
result = batch_decrypt(key, db_path, out_path, is_logging=True)
|
||||
@@ -0,0 +1,279 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: get_base_addr.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2023/08/22
|
||||
# -------------------------------------------------------------------------------
|
||||
import argparse
|
||||
import ctypes
|
||||
import hashlib
|
||||
import json
|
||||
import multiprocessing
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
import psutil
|
||||
from win32com.client import Dispatch
|
||||
from pymem import Pymem
|
||||
import pymem
|
||||
import hmac
|
||||
|
||||
ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory
|
||||
void_p = ctypes.c_void_p
|
||||
KEY_SIZE = 32
|
||||
DEFAULT_PAGESIZE = 4096
|
||||
DEFAULT_ITER = 64000
|
||||
|
||||
|
||||
def validate_key(key, salt, first, mac_salt):
|
||||
byteKey = hashlib.pbkdf2_hmac("sha1", key, salt, DEFAULT_ITER, KEY_SIZE)
|
||||
mac_key = hashlib.pbkdf2_hmac("sha1", byteKey, mac_salt, 2, KEY_SIZE)
|
||||
hash_mac = hmac.new(mac_key, first[:-32], hashlib.sha1)
|
||||
hash_mac.update(b'\x01\x00\x00\x00')
|
||||
|
||||
if hash_mac.digest() == first[-32:-12]:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def get_exe_bit(file_path):
|
||||
"""
|
||||
获取 PE 文件的位数: 32 位或 64 位
|
||||
:param file_path: PE 文件路径(可执行文件)
|
||||
:return: 如果遇到错误则返回 64
|
||||
"""
|
||||
try:
|
||||
with open(file_path, 'rb') as f:
|
||||
dos_header = f.read(2)
|
||||
if dos_header != b'MZ':
|
||||
print('get exe bit error: Invalid PE file')
|
||||
return 64
|
||||
# Seek to the offset of the PE signature
|
||||
f.seek(60)
|
||||
pe_offset_bytes = f.read(4)
|
||||
pe_offset = int.from_bytes(pe_offset_bytes, byteorder='little')
|
||||
|
||||
# Seek to the Machine field in the PE header
|
||||
f.seek(pe_offset + 4)
|
||||
machine_bytes = f.read(2)
|
||||
machine = int.from_bytes(machine_bytes, byteorder='little')
|
||||
|
||||
if machine == 0x14c:
|
||||
return 32
|
||||
elif machine == 0x8664:
|
||||
return 64
|
||||
else:
|
||||
print('get exe bit error: Unknown architecture: %s' % hex(machine))
|
||||
return 64
|
||||
except IOError:
|
||||
print('get exe bit error: File not found or cannot be opened')
|
||||
return 64
|
||||
|
||||
|
||||
def get_exe_version(file_path):
|
||||
"""
|
||||
获取 PE 文件的版本号
|
||||
:param file_path: PE 文件路径(可执行文件)
|
||||
:return: 如果遇到错误则返回
|
||||
"""
|
||||
file_version = Dispatch("Scripting.FileSystemObject").GetFileVersion(file_path)
|
||||
return file_version
|
||||
|
||||
|
||||
def find_all(c: bytes, string: bytes, base_addr=0):
|
||||
"""
|
||||
查找字符串中所有子串的位置
|
||||
:param c: 子串 b'123'
|
||||
:param string: 字符串 b'123456789123'
|
||||
:return:
|
||||
"""
|
||||
return [base_addr + m.start() for m in re.finditer(re.escape(c), string)]
|
||||
|
||||
|
||||
class BiasAddr:
|
||||
def __init__(self, account, mobile, name, key, db_path):
|
||||
self.account = account.encode("utf-8")
|
||||
self.mobile = mobile.encode("utf-8")
|
||||
self.name = name.encode("utf-8")
|
||||
self.key = bytes.fromhex(key) if key else b""
|
||||
self.db_path = db_path if os.path.exists(db_path) else ""
|
||||
|
||||
self.process_name = "WeChat.exe"
|
||||
self.module_name = "WeChatWin.dll"
|
||||
|
||||
self.pm = None # Pymem 对象
|
||||
self.is_WoW64 = None # True: 32位进程运行在64位系统上 False: 64位进程运行在64位系统上
|
||||
self.process_handle = None # 进程句柄
|
||||
self.pid = None # 进程ID
|
||||
self.version = None # 微信版本号
|
||||
self.process = None # 进程对象
|
||||
self.exe_path = None # 微信路径
|
||||
self.address_len = None # 4 if self.bits == 32 else 8 # 4字节或8字节
|
||||
self.bits = 64 if sys.maxsize > 2 ** 32 else 32 # 系统:32位或64位
|
||||
|
||||
def get_process_handle(self):
|
||||
try:
|
||||
self.pm = Pymem(self.process_name)
|
||||
self.pm.check_wow64()
|
||||
self.is_WoW64 = self.pm.is_WoW64
|
||||
self.process_handle = self.pm.process_handle
|
||||
self.pid = self.pm.process_id
|
||||
self.process = psutil.Process(self.pid)
|
||||
self.exe_path = self.process.exe()
|
||||
self.version = get_exe_version(self.exe_path)
|
||||
|
||||
version_nums = list(map(int, self.version.split("."))) # 将版本号拆分为数字列表
|
||||
if version_nums[0] <= 3 and version_nums[1] <= 9 and version_nums[2] <= 2:
|
||||
self.address_len = 4
|
||||
else:
|
||||
self.address_len = 8
|
||||
return True, ""
|
||||
except pymem.exception.ProcessNotFound:
|
||||
return False, "[-] WeChat No Run"
|
||||
|
||||
def search_memory_value(self, value: bytes, module_name="WeChatWin.dll"):
|
||||
# 创建 Pymem 对象
|
||||
module = pymem.process.module_from_name(self.pm.process_handle, module_name)
|
||||
ret = self.pm.pattern_scan_module(value, module, return_multiple=True)
|
||||
ret = ret[-1] - module.lpBaseOfDll if len(ret) > 0 else 0
|
||||
return ret
|
||||
|
||||
def get_key_bias1(self):
|
||||
try:
|
||||
byteLen = self.address_len # 4 if self.bits == 32 else 8 # 4字节或8字节
|
||||
|
||||
keyLenOffset = 0x8c if self.bits == 32 else 0xd0
|
||||
keyWindllOffset = 0x90 if self.bits == 32 else 0xd8
|
||||
|
||||
module = pymem.process.module_from_name(self.process_handle, self.module_name)
|
||||
keyBytes = b'-----BEGIN PUBLIC KEY-----\n...'
|
||||
publicKeyList = pymem.pattern.pattern_scan_all(self.process_handle, keyBytes, return_multiple=True)
|
||||
|
||||
keyaddrs = []
|
||||
for addr in publicKeyList:
|
||||
keyBytes = addr.to_bytes(byteLen, byteorder="little", signed=True) # 低位在前
|
||||
may_addrs = pymem.pattern.pattern_scan_module(self.process_handle, module, keyBytes,
|
||||
return_multiple=True)
|
||||
if may_addrs != 0 and len(may_addrs) > 0:
|
||||
for addr in may_addrs:
|
||||
keyLen = self.pm.read_uchar(addr - keyLenOffset)
|
||||
if keyLen != 32:
|
||||
continue
|
||||
keyaddrs.append(addr - keyWindllOffset)
|
||||
|
||||
return keyaddrs[-1] - module.lpBaseOfDll if len(keyaddrs) > 0 else 0
|
||||
except:
|
||||
return 0
|
||||
|
||||
def search_key(self, key: bytes):
|
||||
key = re.escape(key) # 转义特殊字符
|
||||
key_addr = self.pm.pattern_scan_all(key, return_multiple=False)
|
||||
key = key_addr.to_bytes(self.address_len, byteorder='little', signed=True)
|
||||
result = self.search_memory_value(key, self.module_name)
|
||||
return result
|
||||
|
||||
def get_key_bias2(self, wx_db_path, account_bias=0):
|
||||
wx_db_path = os.path.join(wx_db_path, "Msg", "MicroMsg.db")
|
||||
if not os.path.exists(wx_db_path):
|
||||
return 0
|
||||
|
||||
def get_maybe_key(mem_data):
|
||||
min_addr = 0xffffffffffffffffffffffff
|
||||
max_addr = 0
|
||||
for module1 in pm.list_modules():
|
||||
if module1.lpBaseOfDll < min_addr:
|
||||
min_addr = module1.lpBaseOfDll
|
||||
if module1.lpBaseOfDll > max_addr:
|
||||
max_addr = module1.lpBaseOfDll + module1.SizeOfImage
|
||||
|
||||
maybe_key = []
|
||||
for i in range(0, len(mem_data), self.address_len):
|
||||
addr = mem_data[i:i + self.address_len]
|
||||
addr = int.from_bytes(addr, byteorder='little')
|
||||
# 去掉不可能的地址
|
||||
if min_addr < addr < max_addr:
|
||||
key = read_key(addr)
|
||||
if key == b"":
|
||||
continue
|
||||
maybe_key.append([key, i])
|
||||
return maybe_key
|
||||
|
||||
def read_key(addr):
|
||||
key = ctypes.create_string_buffer(35)
|
||||
if ReadProcessMemory(pm.process_handle, void_p(addr - 1), key, 35, 0) == 0:
|
||||
return b""
|
||||
|
||||
if b"\x00\x00" in key.raw[1:33]:
|
||||
return b""
|
||||
|
||||
if b"\x00\x00" == key.raw[33:35] and b"\x90" == key.raw[0:1]:
|
||||
return key.raw[1:33]
|
||||
return b""
|
||||
|
||||
def verify_key(keys, wx_db_path):
|
||||
with open(wx_db_path, "rb") as file:
|
||||
blist = file.read(5000)
|
||||
salt = blist[:16]
|
||||
first = blist[16:DEFAULT_PAGESIZE]
|
||||
mac_salt = bytes([(salt[i] ^ 58) for i in range(16)])
|
||||
|
||||
with multiprocessing.Pool(processes=8) as pool:
|
||||
results = [pool.apply_async(validate_key, args=(key, salt, first, mac_salt)) for key, i in keys[-1::-1]]
|
||||
results = [p.get() for p in results]
|
||||
for i, result in enumerate(results[-1::-1]):
|
||||
if result:
|
||||
return keys[i]
|
||||
return b"", 0
|
||||
|
||||
module_name = "WeChatWin.dll"
|
||||
pm = self.pm
|
||||
module = pymem.process.module_from_name(pm.process_handle, module_name)
|
||||
start_addr = module.lpBaseOfDll
|
||||
size = module.SizeOfImage
|
||||
|
||||
if account_bias > 1:
|
||||
maybe_key = []
|
||||
for i in [0x24, 0x40]:
|
||||
addr = start_addr + account_bias - i
|
||||
mem_data = pm.read_bytes(addr, self.address_len)
|
||||
key = read_key(int.from_bytes(mem_data, byteorder='little'))
|
||||
if key != b"":
|
||||
maybe_key.append([key, addr - start_addr])
|
||||
key, bais = verify_key(maybe_key, wx_db_path)
|
||||
if bais != 0:
|
||||
return bais
|
||||
|
||||
mem_data = pm.read_bytes(start_addr, size)
|
||||
maybe_key = get_maybe_key(mem_data)
|
||||
key, bais = verify_key(maybe_key, wx_db_path)
|
||||
return bais
|
||||
|
||||
def run(self, logging_path=False, version_list_path=None):
|
||||
if not self.get_process_handle()[0]:
|
||||
return None
|
||||
mobile_bias = self.search_memory_value(self.mobile, self.module_name)
|
||||
name_bias = self.search_memory_value(self.name, self.module_name)
|
||||
account_bias = self.search_memory_value(self.account, self.module_name)
|
||||
key_bias = 0
|
||||
key_bias = self.get_key_bias1()
|
||||
key_bias = self.search_key(self.key) if key_bias <= 0 and self.key else key_bias
|
||||
key_bias = self.get_key_bias2(self.db_path, account_bias) if key_bias <= 0 and self.db_path else key_bias
|
||||
|
||||
rdata = {self.version: [name_bias, account_bias, mobile_bias, 0, key_bias]}
|
||||
if version_list_path and os.path.exists(version_list_path):
|
||||
with open(version_list_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
data.update(rdata)
|
||||
with open(version_list_path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=4)
|
||||
if os.path.exists(logging_path) and isinstance(logging_path, str):
|
||||
with open(logging_path, "a", encoding="utf-8") as f:
|
||||
f.write("{版本号:昵称,账号,手机号,邮箱,KEY}" + "\n")
|
||||
f.write(str(rdata) + "\n")
|
||||
elif logging_path:
|
||||
print("{版本号:昵称,账号,手机号,邮箱,KEY}")
|
||||
print(rdata)
|
||||
return rdata
|
||||
@@ -1,101 +0,0 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: get_wx_db.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2023/10/14
|
||||
# -------------------------------------------------------------------------------
|
||||
import os
|
||||
import re
|
||||
import winreg
|
||||
from typing import List, Union
|
||||
|
||||
|
||||
def get_wechat_db(require_list: Union[List[str], str] = "all", msg_dir: str = None, wxid: Union[List[str], str] = None,
|
||||
is_logging: bool = False):
|
||||
if not msg_dir:
|
||||
try:
|
||||
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Tencent\WeChat", 0, winreg.KEY_READ)
|
||||
value, _ = winreg.QueryValueEx(key, "FileSavePath")
|
||||
winreg.CloseKey(key)
|
||||
w_dir = value
|
||||
except Exception as e:
|
||||
# 获取文档实际目录
|
||||
try:
|
||||
# 打开注册表路径
|
||||
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
|
||||
r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders")
|
||||
documents_path = winreg.QueryValueEx(key, "Personal")[0] # 读取文档实际目录路径
|
||||
winreg.CloseKey(key) # 关闭注册表
|
||||
documents_paths = os.path.split(documents_path)
|
||||
if "%" in documents_paths[0]:
|
||||
w_dir = os.environ.get(documents_paths[0].replace("%", ""))
|
||||
w_dir = os.path.join(w_dir, os.path.join(*documents_paths[1:]))
|
||||
else:
|
||||
w_dir = documents_path
|
||||
except Exception as e:
|
||||
profile = os.path.expanduser("~")
|
||||
w_dir = os.path.join(profile, "Documents")
|
||||
msg_dir = os.path.join(w_dir, "WeChat Files")
|
||||
|
||||
if not os.path.exists(msg_dir):
|
||||
error = f"[-] 目录不存在: {msg_dir}"
|
||||
if is_logging: print(error)
|
||||
return error
|
||||
|
||||
user_dirs = {} # wx用户目录
|
||||
files = os.listdir(msg_dir)
|
||||
if wxid: # 如果指定wxid
|
||||
if isinstance(wxid, str):
|
||||
wxid = wxid.split(";")
|
||||
for file_name in files:
|
||||
if file_name in wxid:
|
||||
user_dirs[os.path.join(msg_dir, file_name)] = os.path.join(msg_dir, file_name)
|
||||
else: # 如果未指定wxid
|
||||
for file_name in files:
|
||||
if file_name == "All Users" or file_name == "Applet" or file_name == "WMPF":
|
||||
continue
|
||||
user_dirs[os.path.join(msg_dir, file_name)] = os.path.join(msg_dir, file_name)
|
||||
|
||||
if isinstance(require_list, str):
|
||||
require_list = require_list.split(";")
|
||||
|
||||
# generate pattern
|
||||
if "all" in require_list:
|
||||
pattern = {"all": re.compile(r".*\.db$")}
|
||||
elif isinstance(require_list, list):
|
||||
pattern = {}
|
||||
for require in require_list:
|
||||
pattern[require] = re.compile(r"%s.*\.db$" % require)
|
||||
else:
|
||||
error = f"[-] 参数错误: {require_list}"
|
||||
if is_logging: print(error)
|
||||
return error
|
||||
|
||||
# 获取数据库路径
|
||||
for user, user_dir in user_dirs.items(): # 遍历用户目录
|
||||
user_dirs[user] = {n: [] for n in pattern.keys()}
|
||||
for root, dirs, files in os.walk(user_dir):
|
||||
for file_name in files:
|
||||
for n, p in pattern.items():
|
||||
if p.match(file_name):
|
||||
src_path = os.path.join(root, file_name)
|
||||
user_dirs[user][n].append(src_path)
|
||||
|
||||
if is_logging:
|
||||
for user, user_dir in user_dirs.items():
|
||||
print(f"[+] user_path: {user}")
|
||||
for n, paths in user_dir.items():
|
||||
print(f" {n}:")
|
||||
for path in paths:
|
||||
print(f" {path.replace(user, '')}")
|
||||
print("-" * 32)
|
||||
print(f"[+] 共 {len(user_dirs)} 个微信账号")
|
||||
|
||||
return user_dirs
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
require_list = ["MediaMSG", "MicroMsg", "FTSMSG", "MSG", "Sns", "Emotion"]
|
||||
# require_list = "all"
|
||||
user_dirs = get_wechat_db(require_list, is_logging=True)
|
||||
@@ -13,6 +13,7 @@ import pymem
|
||||
from win32com.client import Dispatch
|
||||
import psutil
|
||||
import sys
|
||||
from typing import List, Union
|
||||
|
||||
ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory
|
||||
void_p = ctypes.c_void_p
|
||||
@@ -181,28 +182,63 @@ def read_info(version_list, is_logging=False):
|
||||
|
||||
return result
|
||||
|
||||
def get_wechat_db(require_list: Union[List[str], str] = "all", msg_dir: str = None, wxid: Union[List[str], str] = None,
|
||||
is_logging: bool = False):
|
||||
if not msg_dir:
|
||||
msg_dir = get_info_filePath(wxid="all")
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
if not os.path.exists(msg_dir):
|
||||
error = f"[-] 目录不存在: {msg_dir}"
|
||||
if is_logging: print(error)
|
||||
return error
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--vlfile", type=str, help="手机号", required=False)
|
||||
parser.add_argument("--vldict", type=str, help="微信昵称", required=False)
|
||||
user_dirs = {} # wx用户目录
|
||||
files = os.listdir(msg_dir)
|
||||
if wxid: # 如果指定wxid
|
||||
if isinstance(wxid, str):
|
||||
wxid = wxid.split(";")
|
||||
for file_name in files:
|
||||
if file_name in wxid:
|
||||
user_dirs[os.path.join(msg_dir, file_name)] = os.path.join(msg_dir, file_name)
|
||||
else: # 如果未指定wxid
|
||||
for file_name in files:
|
||||
if file_name == "All Users" or file_name == "Applet" or file_name == "WMPF":
|
||||
continue
|
||||
user_dirs[os.path.join(msg_dir, file_name)] = os.path.join(msg_dir, file_name)
|
||||
|
||||
args = parser.parse_args()
|
||||
if isinstance(require_list, str):
|
||||
require_list = require_list.split(";")
|
||||
|
||||
# 读取微信各版本偏移
|
||||
if args.vlfile:
|
||||
VERSION_LIST_PATH = args.vlfile
|
||||
with open(VERSION_LIST_PATH, "r", encoding="utf-8") as f:
|
||||
VERSION_LIST = json.load(f)
|
||||
if args.vldict:
|
||||
VERSION_LIST = json.loads(args.vldict)
|
||||
# generate pattern
|
||||
if "all" in require_list:
|
||||
pattern = {"all": re.compile(r".*\.db$")}
|
||||
elif isinstance(require_list, list):
|
||||
pattern = {}
|
||||
for require in require_list:
|
||||
pattern[require] = re.compile(r"%s.*\.db$" % require)
|
||||
else:
|
||||
error = f"[-] 参数错误: {require_list}"
|
||||
if is_logging: print(error)
|
||||
return error
|
||||
|
||||
if not args.vlfile and not args.vldict:
|
||||
VERSION_LIST_PATH = "../version_list.json"
|
||||
# 获取数据库路径
|
||||
for user, user_dir in user_dirs.items(): # 遍历用户目录
|
||||
user_dirs[user] = {n: [] for n in pattern.keys()}
|
||||
for root, dirs, files in os.walk(user_dir):
|
||||
for file_name in files:
|
||||
for n, p in pattern.items():
|
||||
if p.match(file_name):
|
||||
src_path = os.path.join(root, file_name)
|
||||
user_dirs[user][n].append(src_path)
|
||||
|
||||
with open(VERSION_LIST_PATH, "r", encoding="utf-8") as f:
|
||||
VERSION_LIST = json.load(f)
|
||||
if is_logging:
|
||||
for user, user_dir in user_dirs.items():
|
||||
print(f"[+] user_path: {user}")
|
||||
for n, paths in user_dir.items():
|
||||
print(f" {n}:")
|
||||
for path in paths:
|
||||
print(f" {path.replace(user, '')}")
|
||||
print("-" * 32)
|
||||
print(f"[+] 共 {len(user_dirs)} 个微信账号")
|
||||
|
||||
result = read_info(VERSION_LIST, True) # 读取微信信息
|
||||
return user_dirs
|
||||
@@ -0,0 +1,160 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: merge_db.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2023/12/03
|
||||
# -------------------------------------------------------------------------------
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
|
||||
|
||||
def merge_copy_db(db_path, save_path):
|
||||
if isinstance(db_path, list) and len(db_path) == 1:
|
||||
db_path = db_path[0]
|
||||
if not os.path.exists(db_path):
|
||||
raise FileNotFoundError("目录不存在")
|
||||
shutil.move(db_path, save_path)
|
||||
|
||||
|
||||
# 合并相同名称的数据库 MSG0-MSG9.db
|
||||
def merge_msg_db(db_path: list, save_path: str, CreateTime: int = 0): # CreateTime: 从这个时间开始的消息 10位时间戳
|
||||
|
||||
merged_conn = sqlite3.connect(save_path)
|
||||
merged_cursor = merged_conn.cursor()
|
||||
|
||||
for db_file in db_path:
|
||||
c_tabels = merged_cursor.execute(
|
||||
"select tbl_name from sqlite_master where type='table' and tbl_name!='sqlite_sequence'")
|
||||
tabels_all = c_tabels.fetchall() # 所有表名
|
||||
tabels_all = [row[0] for row in tabels_all]
|
||||
|
||||
conn = sqlite3.connect(db_file)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 创建表
|
||||
if len(tabels_all) < 4:
|
||||
cursor.execute(
|
||||
"select tbl_name,sql from sqlite_master where type='table' and tbl_name!='sqlite_sequence'")
|
||||
c_part = cursor.fetchall()
|
||||
|
||||
for tbl_name, sql in c_part:
|
||||
if tbl_name in tabels_all:
|
||||
continue
|
||||
try:
|
||||
merged_cursor.execute(sql)
|
||||
tabels_all.append(tbl_name)
|
||||
except Exception as e:
|
||||
print(f"error: {db_file}\n{tbl_name}\n{sql}\n{e}\n**********")
|
||||
raise e
|
||||
merged_conn.commit()
|
||||
|
||||
# 写入数据
|
||||
for tbl_name in tabels_all:
|
||||
if tbl_name == "MSG":
|
||||
MsgSvrIDs = merged_cursor.execute(
|
||||
f"select MsgSvrID from MSG where CreateTime>{CreateTime} and MsgSvrID!=0").fetchall()
|
||||
|
||||
cursor.execute(f"PRAGMA table_info({tbl_name})")
|
||||
columns = cursor.fetchall()
|
||||
columns = [column[1] for column in columns[1:]]
|
||||
|
||||
ex_sql = f"select {','.join(columns)} from {tbl_name} where CreateTime>{CreateTime} and MsgSvrID not in ({','.join([str(MsgSvrID[0]) for MsgSvrID in MsgSvrIDs])})"
|
||||
cursor.execute(ex_sql)
|
||||
|
||||
insert_sql = f"INSERT INTO {tbl_name} ({','.join(columns)}) VALUES ({','.join(['?' for _ in range(len(columns))])})"
|
||||
try:
|
||||
merged_cursor.executemany(insert_sql, cursor.fetchall())
|
||||
except Exception as e:
|
||||
print(
|
||||
f"error: {db_file}\n{tbl_name}\n{insert_sql}\n{cursor.fetchall()}\n{len(cursor.fetchall())}\n{e}\n**********")
|
||||
raise e
|
||||
merged_conn.commit()
|
||||
else:
|
||||
ex_sql = f"select * from {tbl_name}"
|
||||
cursor.execute(ex_sql)
|
||||
|
||||
for r in cursor.fetchall():
|
||||
cursor.execute(f"PRAGMA table_info({tbl_name})")
|
||||
columns = cursor.fetchall()
|
||||
if len(columns) > 1:
|
||||
columns = [column[1] for column in columns[1:]]
|
||||
values = r[1:]
|
||||
else:
|
||||
columns = [columns[0][1]]
|
||||
values = [r[0]]
|
||||
|
||||
query_1 = "select * from " + tbl_name + " where " + columns[0] + "=?" # 查询语句 用于判断是否存在
|
||||
c2 = merged_cursor.execute(query_1, values)
|
||||
if len(c2.fetchall()) > 0: # 已存在
|
||||
continue
|
||||
query = "INSERT INTO " + tbl_name + " (" + ",".join(columns) + ") VALUES (" + ",".join(
|
||||
["?" for _ in range(len(values))]) + ")"
|
||||
|
||||
try:
|
||||
merged_cursor.execute(query, values)
|
||||
except Exception as e:
|
||||
print(f"error: {db_file}\n{tbl_name}\n{query}\n{values}\n{len(values)}\n{e}\n**********")
|
||||
raise e
|
||||
merged_conn.commit()
|
||||
|
||||
conn.close()
|
||||
sql = '''delete from MSG where localId in (SELECT localId from MSG
|
||||
where MsgSvrID != 0 and MsgSvrID in (select MsgSvrID from MSG
|
||||
where MsgSvrID != 0 GROUP BY MsgSvrID HAVING COUNT(*) > 1)
|
||||
and localId not in (select min(localId) from MSG
|
||||
where MsgSvrID != 0 GROUP BY MsgSvrID HAVING COUNT(*) > 1))'''
|
||||
c = merged_cursor.execute(sql)
|
||||
merged_conn.commit()
|
||||
merged_conn.close()
|
||||
return save_path
|
||||
|
||||
|
||||
def merge_media_msg_db(db_path: list, save_path: str):
|
||||
merged_conn = sqlite3.connect(save_path)
|
||||
merged_cursor = merged_conn.cursor()
|
||||
|
||||
for db_file in db_path:
|
||||
|
||||
s = "select tbl_name,sql from sqlite_master where type='table' and tbl_name!='sqlite_sequence'"
|
||||
have_tables = merged_cursor.execute(s).fetchall()
|
||||
have_tables = [row[0] for row in have_tables]
|
||||
|
||||
conn_part = sqlite3.connect(db_file)
|
||||
cursor = conn_part.cursor()
|
||||
|
||||
if len(have_tables) < 1:
|
||||
cursor.execute(s)
|
||||
table_part = cursor.fetchall()
|
||||
tblname, sql = table_part[0]
|
||||
|
||||
sql = "CREATE TABLE Media(localId INTEGER PRIMARY KEY AUTOINCREMENT,Key TEXT,Reserved0 INT,Buf BLOB,Reserved1 INT,Reserved2 TEXT)"
|
||||
try:
|
||||
merged_cursor.execute(sql)
|
||||
have_tables.append(tblname)
|
||||
except Exception as e:
|
||||
print(f"error: {db_file}\n{tblname}\n{sql}\n{e}\n**********")
|
||||
raise e
|
||||
merged_conn.commit()
|
||||
|
||||
for tblname in have_tables:
|
||||
s = "select Reserved0 from " + tblname
|
||||
merged_cursor.execute(s)
|
||||
r0 = merged_cursor.fetchall()
|
||||
|
||||
ex_sql = f"select `Key`,Reserved0,Buf,Reserved1,Reserved2 from {tblname} where Reserved0 not in ({','.join([str(r[0]) for r in r0])})"
|
||||
cursor.execute(ex_sql)
|
||||
data = cursor.fetchall()
|
||||
|
||||
insert_sql = f"INSERT INTO {tblname} (Key,Reserved0,Buf,Reserved1,Reserved2) VALUES ({','.join(['?' for _ in range(5)])})"
|
||||
try:
|
||||
merged_cursor.executemany(insert_sql, data)
|
||||
except Exception as e:
|
||||
print(f"error: {db_file}\n{tblname}\n{insert_sql}\n{data}\n{len(data)}\n{e}\n**********")
|
||||
raise e
|
||||
merged_conn.commit()
|
||||
conn_part.close()
|
||||
|
||||
merged_conn.close()
|
||||
return save_path
|
||||
Reference in new issue
Block a user