3.1.0,很多更改丢失,重新恢复的文件

This commit is contained in:
xaoyaoo committed 2024-08-03 00:29:03 +08:00
commit e2b934ebdc
46 files changed
+3435 -2019

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: __init__.py.py
# Description:
# Author: xaoyaoo
# Date: 2023/08/21
# -------------------------------------------------------------------------------
from .wx_info import get_wx_info, get_wx_db, get_core_db
from .get_bias_addr import BiasAddr
from .decryption import batch_decrypt, decrypt
from .merge_db import merge_db, decrypt_merge, merge_real_time_db, all_merge_real_time_db
+274
View File
@@ -0,0 +1,274 @@
import ctypes
import ctypes.wintypes
from collections import namedtuple
# 定义必要的常量
TH32CS_SNAPPROCESS = 0x00000002
MAX_PATH = 260
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
# MEMORY_BASIC_INFORMATION 结构体定义
class MEMORY_BASIC_INFORMATION(ctypes.Structure):
_fields_ = [
('BaseAddress', ctypes.wintypes.LPVOID),
('AllocationBase', ctypes.wintypes.LPVOID),
('AllocationProtect', ctypes.wintypes.DWORD),
('RegionSize', ctypes.c_size_t),
('State', ctypes.wintypes.DWORD),
('Protect', ctypes.wintypes.DWORD),
('Type', ctypes.wintypes.DWORD)
]
class MODULEINFO(ctypes.Structure):
_fields_ = [
("lpBaseOfDll", ctypes.c_void_p), # remote pointer
("SizeOfImage", ctypes.c_ulong),
("EntryPoint", ctypes.c_void_p), # remote pointer
]
# 定义PROCESSENTRY32结构
class PROCESSENTRY32(ctypes.Structure):
_fields_ = [("dwSize", ctypes.wintypes.DWORD),
("cntUsage", ctypes.wintypes.DWORD),
("th32ProcessID", ctypes.wintypes.DWORD),
("th32DefaultHeapID", ctypes.POINTER(ctypes.wintypes.ULONG)),
("th32ModuleID", ctypes.wintypes.DWORD),
("cntThreads", ctypes.wintypes.DWORD),
("th32ParentProcessID", ctypes.wintypes.DWORD),
("pcPriClassBase", ctypes.wintypes.LONG),
("dwFlags", ctypes.wintypes.DWORD),
("szExeFile", ctypes.c_char * MAX_PATH)]
class VS_FIXEDFILEINFO(ctypes.Structure):
_fields_ = [
('dwSignature', ctypes.wintypes.DWORD),
('dwStrucVersion', ctypes.wintypes.DWORD),
('dwFileVersionMS', ctypes.wintypes.DWORD),
('dwFileVersionLS', ctypes.wintypes.DWORD),
('dwProductVersionMS', ctypes.wintypes.DWORD),
('dwProductVersionLS', ctypes.wintypes.DWORD),
('dwFileFlagsMask', ctypes.wintypes.DWORD),
('dwFileFlags', ctypes.wintypes.DWORD),
('dwFileOS', ctypes.wintypes.DWORD),
('dwFileType', ctypes.wintypes.DWORD),
('dwFileSubtype', ctypes.wintypes.DWORD),
('dwFileDateMS', ctypes.wintypes.DWORD),
('dwFileDateLS', ctypes.wintypes.DWORD),
]
# 加载dll
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
psapi = ctypes.WinDLL('psapi', use_last_error=True)
version = ctypes.WinDLL('version', use_last_error=True)
# 创建进程快照
CreateToolhelp32Snapshot = kernel32.CreateToolhelp32Snapshot
CreateToolhelp32Snapshot.argtypes = [ctypes.wintypes.DWORD, ctypes.wintypes.DWORD]
CreateToolhelp32Snapshot.restype = ctypes.wintypes.HANDLE
# 获取第一个进程
Process32First = kernel32.Process32First
Process32First.argtypes = [ctypes.wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32)]
Process32First.restype = ctypes.wintypes.BOOL
# 获取下一个进程
Process32Next = kernel32.Process32Next
Process32Next.argtypes = [ctypes.wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32)]
Process32Next.restype = ctypes.wintypes.BOOL
# 关闭句柄
CloseHandle = kernel32.CloseHandle
CloseHandle.argtypes = [ctypes.wintypes.HANDLE]
CloseHandle.restype = ctypes.wintypes.BOOL
# 打开进程
OpenProcess = kernel32.OpenProcess
OpenProcess.argtypes = [ctypes.wintypes.DWORD, ctypes.wintypes.BOOL, ctypes.wintypes.DWORD]
OpenProcess.restype = ctypes.wintypes.HANDLE
# 获取模块文件名
GetModuleFileNameEx = psapi.GetModuleFileNameExA
GetModuleFileNameEx.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.HANDLE, ctypes.c_char_p, ctypes.wintypes.DWORD]
GetModuleFileNameEx.restype = ctypes.wintypes.DWORD
# 获取文件版本信息大小
GetFileVersionInfoSizeW = version.GetFileVersionInfoSizeW
GetFileVersionInfoSizeW.argtypes = [ctypes.wintypes.LPCWSTR, ctypes.POINTER(ctypes.wintypes.DWORD)]
GetFileVersionInfoSizeW.restype = ctypes.wintypes.DWORD
# 获取文件版本信息
GetFileVersionInfoW = version.GetFileVersionInfoW
GetFileVersionInfoW.argtypes = [ctypes.wintypes.LPCWSTR, ctypes.wintypes.DWORD, ctypes.wintypes.DWORD, ctypes.c_void_p]
GetFileVersionInfoW.restype = ctypes.wintypes.BOOL
# 查询文件版本信息
VerQueryValueW = version.VerQueryValueW
VerQueryValueW.argtypes = [ctypes.c_void_p, ctypes.wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_void_p),
ctypes.POINTER(ctypes.wintypes.UINT)]
VerQueryValueW.restype = ctypes.wintypes.BOOL
# 获取模块信息
GetModuleInformation = psapi.GetModuleInformation
GetModuleInformation.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.HMODULE, ctypes.POINTER(MODULEINFO),
ctypes.wintypes.DWORD]
GetModuleInformation.restype = ctypes.c_bool
# 读取进程内存
ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory
# 定义VirtualQueryEx函数
VirtualQueryEx = kernel32.VirtualQueryEx
VirtualQueryEx.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.LPCVOID, ctypes.POINTER(MEMORY_BASIC_INFORMATION),
ctypes.c_size_t]
VirtualQueryEx.restype = ctypes.c_size_t
# 获取映射文件名
GetMappedFileName = psapi.GetMappedFileNameA
GetMappedFileName.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.LPVOID, ctypes.c_char_p, ctypes.wintypes.DWORD]
GetMappedFileName.restype = ctypes.wintypes.DWORD
GetMappedFileNameW = psapi.GetMappedFileNameW
GetMappedFileNameW.restype = ctypes.wintypes.DWORD
GetMappedFileNameW.argtypes = [ctypes.wintypes.HANDLE, ctypes.c_void_p, ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD]
def get_info_with_key(h_process, address, address_len=8):
array = ctypes.create_string_buffer(address_len)
if ReadProcessMemory(h_process, ctypes.c_void_p(address), array, address_len, 0) == 0: return None
address = int.from_bytes(array, byteorder='little') # 逆序转换为int地址(key地址)
key = ctypes.create_string_buffer(32)
if ReadProcessMemory(h_process, ctypes.c_void_p(address), key, 32, 0) == 0: return None
key_string = bytes(key).hex()
return key_string
def get_memory_maps(pid):
# 打开进程
access = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ
hProcess = OpenProcess(access, False, pid)
if not hProcess:
return []
memory_maps = []
base_address = 0
mbi = MEMORY_BASIC_INFORMATION()
max_address = 0x7FFFFFFFFFFFFFFF # 64位系统的最大地址
while base_address < max_address:
if VirtualQueryEx(hProcess, base_address, ctypes.byref(mbi), ctypes.sizeof(mbi)) == 0:
break
mapped_file_name = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
if GetMappedFileNameW(hProcess, base_address, mapped_file_name, ctypes.wintypes.MAX_PATH) > 0:
file_name = mapped_file_name.value
else:
file_name = None
# module_info = MODULEINFO()
# if GetModuleInformation(hProcess, mbi.BaseAddress, ctypes.byref(module_info), ctypes.sizeof(module_info)):
# file_name = get_file_version_info(module_info.lpBaseOfDll)
memory_maps.append({
'BaseAddress': mbi.BaseAddress,
'RegionSize': mbi.RegionSize,
'State': mbi.State,
'Protect': mbi.Protect,
'Type': mbi.Type,
'FileName': file_name
})
base_address += mbi.RegionSize
CloseHandle(hProcess)
MemMap = namedtuple('MemMap', ['BaseAddress', 'RegionSize', 'State', 'Protect', 'Type', 'FileName'])
return [MemMap(**m) for m in memory_maps]
def get_process_exe_path(process_id):
h_process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, process_id)
if not h_process:
return None
exe_path = ctypes.create_string_buffer(MAX_PATH)
if GetModuleFileNameEx(h_process, None, exe_path, MAX_PATH) > 0:
CloseHandle(h_process)
return exe_path.value.decode('utf-8', errors='ignore')
else:
CloseHandle(h_process)
return None
def get_file_version_info(file_path):
size = GetFileVersionInfoSizeW(file_path, None)
if size == 0:
return None
res = ctypes.create_string_buffer(size)
if not GetFileVersionInfoW(file_path, 0, size, res):
return None
uLen = ctypes.wintypes.UINT()
lplpBuffer = ctypes.c_void_p()
if not VerQueryValueW(res, r'\\', ctypes.byref(lplpBuffer), ctypes.byref(uLen)):
return None
ffi = ctypes.cast(lplpBuffer, ctypes.POINTER(VS_FIXEDFILEINFO)).contents
if ffi.dwSignature != 0xFEEF04BD:
return None
version = (
(ffi.dwFileVersionMS >> 16) & 0xffff,
ffi.dwFileVersionMS & 0xffff,
(ffi.dwFileVersionLS >> 16) & 0xffff,
ffi.dwFileVersionLS & 0xffff,
)
# f"{version[0]}.{version[1]}.{version[2]}.{version[3]}"
return f"{version[0]}.{version[1]}.{version[2]}.{version[3]}"
def get_process_list():
h_process_snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
if h_process_snap == ctypes.wintypes.HANDLE(-1).value:
print("Failed to create snapshot")
return []
pe32 = PROCESSENTRY32()
pe32.dwSize = ctypes.sizeof(PROCESSENTRY32)
process_list = []
if not Process32First(h_process_snap, ctypes.byref(pe32)):
print("Failed to get first process")
CloseHandle(h_process_snap)
return []
while True:
# process_path = get_process_exe_path(pe32.th32ProcessID)
process_list.append((pe32.th32ProcessID, pe32.szExeFile.decode('utf-8', errors='ignore')))
if not Process32Next(h_process_snap, ctypes.byref(pe32)):
break
CloseHandle(h_process_snap)
return process_list
if __name__ == "__main__":
processes = get_process_list()
for pid, name in processes:
if name == "WeChat.exe":
# print(f"PID: {pid}, Process Name: {name}, Exe Path: {path}")
# Handle = ctypes.windll.kernel32.OpenProcess(0x1F0FFF, False, pid)
# wechat_base_address = 0
memory_maps = get_memory_maps(pid)
for module in memory_maps:
if module.FileName and 'WeChatWin.dll' in module.FileName:
print(module.BaseAddress)
print(module.FileName)
break
# print(wechat_base_address)
# get_info_with_key(Handle, key_baseaddr, addrLen)
+166
View File
@@ -0,0 +1,166 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: getwxinfo.py
# Description:
# Author: xaoyaoo
# Date: 2023/08/21
# 微信数据库采用的加密算法是256位的AES-CBC。数据库的默认的页大小是4096字节即4KB,其中每一个页都是被单独加解密的。
# 加密文件的每一个页都有一个随机的初始化向量,它被保存在每一页的末尾。
# 加密文件的每一页都存有着消息认证码,算法使用的是HMAC-SHA1(安卓数据库使用的是SHA512)。它也被保存在每一页的末尾。
# 每一个数据库文件的开头16字节都保存了一段唯一且随机的盐值,作为HMAC的验证和数据的解密。
# 为了保证数据部分长度是16字节即AES块大小的整倍数,每一页的末尾将填充一段空字节,使得保留字段的长度为48字节。
# 综上,加密文件结构为第一页4KB数据前16字节为盐值,紧接着4032字节数据,再加上16字节IV和20字节HMAC以及12字节空字节;而后的页均是4048字节长度的加密数据段和48字节的保留段。
# -------------------------------------------------------------------------------
import hmac
import hashlib
import os
from typing import Union, List
from Cryptodome.Cipher import AES
# from Crypto.Cipher import AES # 如果上面的导入失败,可以尝试使用这个
from .utils import wx_core_error, wx_core_loger
SQLITE_FILE_HEADER = "SQLite format 3\x00" # SQLite文件头
KEY_SIZE = 32
DEFAULT_PAGESIZE = 4096
# 通过密钥解密数据库
@wx_core_error
def decrypt(key: str, db_path: str, out_path: str):
"""
通过密钥解密数据库
: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())
try:
with open(db_path, "rb") as file:
blist = file.read()
except Exception as e:
return False, f"[-] db_path:'{db_path}' {e}!"
salt = blist[:16]
first = blist[16:4096]
if len(salt) != 16:
return False, f"[-] db_path:'{db_path}' File Error!"
mac_salt = bytes([(salt[i] ^ 58) for i in range(16)])
byteHmac = hashlib.pbkdf2_hmac("sha1", password, salt, 64000, KEY_SIZE)
mac_key = hashlib.pbkdf2_hmac("sha1", byteHmac, mac_salt, 2, KEY_SIZE)
hash_mac = hmac.new(mac_key, blist[16:4064], 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}' )"
with open(out_path, "wb") as deFile:
deFile.write(SQLITE_FILE_HEADER.encode())
for i in range(0, len(blist), 4096):
tblist = blist[i:i + 4096] if i > 0 else blist[16:i + 4096]
deFile.write(AES.new(byteHmac, AES.MODE_CBC, tblist[-48:-32]).decrypt(tblist[:-48]))
deFile.write(tblist[-48:])
return True, [db_path, out_path, key]
@wx_core_error
def batch_decrypt(key: str, db_path: Union[str, List[str]], out_path: str, is_print: bool = False):
"""
批量解密数据库
:param key: 密钥 64位16进制字符串
:param db_path: 待解密的数据库路径(文件或文件夹)
:param out_path: 解密后的数据库输出路径(文件夹)
:param is_logging: 是否打印日志
:return: (bool, [[input_db_path, output_db_path, key],...])
"""
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!"
wx_core_loger.error(error, exc_info=True)
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!"
wx_core_loger.error(error, exc_info=True)
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 "
wx_core_loger.error(error, exc_info=True)
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):
error = f"[-] db_path:'{db_path}' not found!"
wx_core_loger.error(error, exc_info=True)
return False, error
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 "
wx_core_loger.error(error, exc_info=True)
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_print:
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
+186
View File
@@ -0,0 +1,186 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: get_base_addr.py
# Description:
# Author: xaoyaoo
# Date: 2023/08/22
# -------------------------------------------------------------------------------
import ctypes
import json
import os
import re
import sys
import psutil
import pymem
from .utils import get_exe_version, get_exe_bit, verify_key
ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory if sys.platform == "win32" else None
void_p = ctypes.c_void_p
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 db_path and 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.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):
"""
2024.01.26 wx version:3.9.9.35 失效
:return:
"""
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):
addr_len = get_exe_bit(self.exe_path) // 8
db_path = wx_db_path
def read_key_bytes(h_process, address, address_len=8):
array = ctypes.create_string_buffer(address_len)
if ReadProcessMemory(h_process, void_p(address), array, address_len, 0) == 0: return "None"
address = int.from_bytes(array, byteorder='little') # 逆序转换为int地址(key地址)
key = ctypes.create_string_buffer(32)
if ReadProcessMemory(h_process, void_p(address), key, 32, 0) == 0: return "None"
key_bytes = bytes(key)
return key_bytes
phone_type1 = "iphone\x00"
phone_type2 = "android\x00"
phone_type3 = "ipad\x00"
pm = pymem.Pymem(self.pid)
module_name = "WeChatWin.dll"
MicroMsg_path = os.path.join(db_path, "MSG", "MicroMsg.db")
type1_addrs = pm.pattern_scan_module(phone_type1.encode(), module_name, return_multiple=True)
type2_addrs = pm.pattern_scan_module(phone_type2.encode(), module_name, return_multiple=True)
type3_addrs = pm.pattern_scan_module(phone_type3.encode(), module_name, return_multiple=True)
type_addrs = []
if len(type1_addrs) >= 2: type_addrs += type1_addrs
if len(type2_addrs) >= 2: type_addrs += type2_addrs
if len(type3_addrs) >= 2: type_addrs += type3_addrs
if len(type_addrs) == 0: return "None"
type_addrs.sort() # 从小到大排序
module = pymem.process.module_from_name(pm.process_handle, module_name)
for i in type_addrs[::-1]:
for j in range(i, i - 2000, -addr_len):
key_bytes = read_key_bytes(pm.process_handle, j, addr_len)
if key_bytes == "None":
continue
if verify_key(key_bytes, MicroMsg_path):
return j - module.lpBaseOfDll
return 0
def run(self, logging_path=False, WX_OFFS_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() if key_bias <= 0 else key_bias
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) if key_bias <= 0 and self.db_path else key_bias
rdata = {self.version: [name_bias, account_bias, mobile_bias, 0, key_bias]}
if WX_OFFS_PATH and os.path.exists(WX_OFFS_PATH):
with open(WX_OFFS_PATH, "r", encoding="utf-8") as f:
data = json.load(f)
data.update(rdata)
with open(WX_OFFS_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
if __name__ == '__main__':
account, mobile, name, key, db_path = "test", "test", "test", None, r"test"
bias_addr = BiasAddr(account, mobile, name, key, db_path)
bias_addr.run(logging_path=True)
+117
View File
@@ -0,0 +1,117 @@
import ctypes
import ctypes.wintypes as wintypes
import logging
import re
import sys
# 定义常量
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
PAGE_EXECUTE = 0x10
PAGE_EXECUTE_READ = 0x20
PAGE_EXECUTE_READWRITE = 0x40
PAGE_EXECUTE_WRITECOPY = 0x80
PAGE_NOACCESS = 0x01
PAGE_READONLY = 0x02
PAGE_READWRITE = 0x04
PAGE_WRITECOPY = 0x08
PAGE_GUARD = 0x100
PAGE_NOCACHE = 0x200
PAGE_WRITECOMBINE = 0x400
MEM_COMMIT = 0x1000
MEM_FREE = 0x10000
MEM_RESERVE = 0x2000
MEM_DECOMMIT = 0x4000
MEM_RELEASE = 0x8000
# 定义结构体
class MEMORY_BASIC_INFORMATION(ctypes.Structure):
_fields_ = [
("BaseAddress", ctypes.c_void_p),
("AllocationBase", ctypes.c_void_p),
("AllocationProtect", wintypes.DWORD),
("RegionSize", ctypes.c_size_t),
("State", wintypes.DWORD),
("Protect", wintypes.DWORD),
("Type", wintypes.DWORD),
]
# 加载Windows API函数
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
OpenProcess = kernel32.OpenProcess
OpenProcess.restype = wintypes.HANDLE
OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
ReadProcessMemory = kernel32.ReadProcessMemory
VirtualQueryEx = kernel32.VirtualQueryEx
VirtualQueryEx.restype = ctypes.c_size_t
VirtualQueryEx.argtypes = [wintypes.HANDLE, ctypes.c_void_p, ctypes.POINTER(MEMORY_BASIC_INFORMATION), ctypes.c_size_t]
CloseHandle = kernel32.CloseHandle
CloseHandle.restype = wintypes.BOOL
CloseHandle.argtypes = [wintypes.HANDLE]
def search_memory(hProcess, pattern=br'\\Msg\\FTSContact', max_num=100,start_address=0x0,end_address=0x7FFFFFFFFFFFFFFF):
"""
在进程内存中搜索字符串
:param p: 进程ID或者进程句柄
:param pattern: 要搜索的字符串
:param max_num: 最多找到的数量
"""
result = []
# 打开进程
if not hProcess:
raise ctypes.WinError(ctypes.get_last_error())
mbi = MEMORY_BASIC_INFORMATION()
address = start_address
max_address = end_address if sys.maxsize > 2 ** 32 else 0x7fff0000
pattern = re.compile(pattern)
while address < max_address:
if VirtualQueryEx(hProcess, address, ctypes.byref(mbi), ctypes.sizeof(mbi)) == 0:
break
# 读取内存数据
allowed_protections = [PAGE_EXECUTE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, PAGE_READONLY, ]
if mbi.State != MEM_COMMIT or mbi.Protect not in allowed_protections:
address += mbi.RegionSize
continue
# 使用正确的类型来避免OverflowError
base_address_c = ctypes.c_ulonglong(mbi.BaseAddress)
region_size_c = ctypes.c_size_t(mbi.RegionSize)
page_bytes = ctypes.create_string_buffer(mbi.RegionSize)
bytes_read = ctypes.c_size_t()
if ReadProcessMemory(hProcess, base_address_c, page_bytes, region_size_c, ctypes.byref(bytes_read)) == 0:
address += mbi.RegionSize
continue
# 搜索字符串 re print(page_bytes.raw)
find = [address + match.start() for match in pattern.finditer(page_bytes, re.DOTALL)]
if find:
result.extend(find)
if len(result) >= max_num:
break
address += mbi.RegionSize
return result
if __name__ == '__main__':
# 示例用法
pid = 29320 # 将此替换为你要查询的进程ID
try:
maps = search_memory(pid)
print(len(maps))
for m in maps:
print(hex(m))
except Exception as e:
logging.error(e, exc_info=True)
+471
View File
@@ -0,0 +1,471 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: merge_db.py
# Description:
# Author: xaoyaoo
# Date: 2023/12/03
# -------------------------------------------------------------------------------
import logging
import os
import shutil
import sqlite3
import subprocess
import time
from typing import List
from .decryption import batch_decrypt
from .wx_info import get_core_db
from .utils import wx_core_loger, wx_core_error
@wx_core_error
def execute_sql(connection, sql, params=None):
"""
执行给定的SQL语句,返回结果。
参数:
- connection: SQLite连接
- sql:要执行的SQL语句
- params:SQL语句中的参数
"""
try:
# connection.text_factory = bytes
cursor = connection.cursor()
if params:
cursor.execute(sql, params)
else:
cursor.execute(sql)
return cursor.fetchall()
except Exception as e:
try:
connection.text_factory = bytes
cursor = connection.cursor()
if params:
cursor.execute(sql, params)
else:
cursor.execute(sql)
rdata = cursor.fetchall()
connection.text_factory = str
return rdata
except Exception as e:
wx_core_loger.error(f"**********\nSQL: {sql}\nparams: {params}\n{e}\n**********", exc_info=True)
return None
@wx_core_error
def check_create_sync_log(connection):
"""
检查是否存在表 sync_log,用于记录同步记录,包括微信数据库路径,表名,记录数,同步时间
:param connection: SQLite连接
:return: True or False
"""
out_cursor = connection.cursor()
# 检查是否存在表 sync_log,用于记录同步记录,包括微信数据库路径,表名,记录数,同步时间
sync_log_status = execute_sql(connection, "SELECT name FROM sqlite_master WHERE type='table' AND name='sync_log'")
if len(sync_log_status) < 1:
# db_path 微信数据库路径,tbl_name 表名,src_count 源数据库记录数,current_count 当前合并后的数据库对应表记录数
sync_record_create_sql = ("CREATE TABLE sync_log ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"db_path TEXT NOT NULL,"
"tbl_name TEXT NOT NULL,"
"src_count INT,"
"current_count INT,"
"createTime INT DEFAULT (strftime('%s', 'now')), "
"updateTime INT DEFAULT (strftime('%s', 'now'))"
");")
out_cursor.execute(sync_record_create_sql)
# 创建索引
out_cursor.execute("CREATE INDEX idx_sync_log_db_path ON sync_log (db_path);")
out_cursor.execute("CREATE INDEX idx_sync_log_tbl_name ON sync_log (tbl_name);")
# 创建联合索引,防止重复
out_cursor.execute("CREATE UNIQUE INDEX idx_sync_log_db_tbl ON sync_log (db_path, tbl_name);")
connection.commit()
out_cursor.close()
return True
@wx_core_error
def check_create_file_md5(connection):
"""
检查是否存在表 file_md5,用于记录文件信息,后续用于去重等操作,暂时闲置
"""
pass
@wx_core_error
def merge_db(db_paths: list[dict], save_path: str = "merge.db", is_merge_data: bool = True,
startCreateTime: int = 0, endCreateTime: int = 0):
"""
合并数据库 会忽略主键以及重复的行。
:param db_paths: [{"db_path": "xxx", "de_path": "xxx"},...]
db_path表示初始路径,de_path表示解密后的路径;初始路径用于保存合并的日志情况,解密后的路径用于读取数据
:param save_path: str 输出文件路径
:param is_merge_data: bool 是否合并数据(如果为False,则只解密,并创建表,不插入数据)
:param startCreateTime: 开始时间戳 主要用于MSG数据库的合并
:param endCreateTime: 结束时间戳 主要用于MSG数据库的合并
:return:
"""
if os.path.isdir(save_path):
save_path = os.path.join(save_path, f"merge_{int(time.time())}.db")
if isinstance(db_paths, list):
# alias, file_path
databases = {f"MSG{i}": (db['db_path'],
db.get('de_path', db['db_path'])
) for i, db in enumerate(db_paths)
}
else:
raise TypeError("db_paths 类型错误")
outdb = sqlite3.connect(save_path)
is_sync_log = check_create_sync_log(outdb)
if not is_sync_log:
wx_core_loger.warning("创建同步记录表失败")
out_cursor = outdb.cursor()
# 将MSG_db_paths中的数据合并到out_db_path中
for alias, db in databases.items():
db_path = db[0]
de_path = db[1]
# 附加数据库
sql_attach = f"ATTACH DATABASE '{de_path}' AS {alias}"
out_cursor.execute(sql_attach)
outdb.commit()
sql_query_tbl_name = f"SELECT name FROM {alias}.sqlite_master WHERE type='table' ORDER BY name;"
tables = execute_sql(outdb, sql_query_tbl_name)
for table in tables:
table = table[0]
if table == "sqlite_sequence":
continue
# 获取表中的字段名
sql_query_columns = f"PRAGMA table_info({table})"
columns = execute_sql(outdb, sql_query_columns)
col_type = {
(i[1] if isinstance(i[1], str) else i[1].decode(),
i[2] if isinstance(i[2], str) else i[2].decode())
for i in columns}
columns = [i[0] for i in col_type]
if not columns or len(columns) < 1:
continue
# 创建表table
sql_create_tbl = f"CREATE TABLE IF NOT EXISTS {table} AS SELECT * FROM {alias}.{table} WHERE 0 = 1;"
out_cursor.execute(sql_create_tbl)
# 创建包含 NULL 值比较的 UNIQUE 索引
index_name = f"{table}_unique_index"
coalesce_columns = ','.join(f"COALESCE({column}, '')" for column in columns)
sql = f"CREATE UNIQUE INDEX IF NOT EXISTS {index_name} ON {table} ({coalesce_columns})"
out_cursor.execute(sql)
# 插入sync_log
sql_query_sync_log = f"SELECT src_count FROM sync_log WHERE db_path=? AND tbl_name=?"
sync_log = execute_sql(outdb, sql_query_sync_log, (db_path, table))
if not sync_log or len(sync_log) < 1:
sql_insert_sync_log = "INSERT INTO sync_log (db_path, tbl_name, src_count, current_count) VALUES (?, ?, ?, ?)"
out_cursor.execute(sql_insert_sync_log, (db_path, table, 0, 0))
outdb.commit()
if is_merge_data:
# 比较源数据库和合并后的数据库记录数
log_src_count = execute_sql(outdb, sql_query_sync_log, (db_path, table))[0][0]
src_count = execute_sql(outdb, f"SELECT COUNT(*) FROM {alias}.{table}")[0][0]
if src_count <= log_src_count:
wx_core_loger.info(f"忽略 {db_path} {de_path} {table} {src_count} {log_src_count}")
continue
# 构建数据查询sql
sql_base = f"SELECT {','.join([i for i in columns])} FROM {alias}.{table} "
where_clauses, params = [], []
if "CreateTime" in columns:
if startCreateTime > 0:
where_clauses.append("CreateTime > ?")
params.append(startCreateTime)
if endCreateTime > 0:
where_clauses.append("CreateTime < ?")
params.append(endCreateTime)
# 如果有WHERE子句,将其添加到SQL语句中,并添加ORDER BY子句
sql = f"{sql_base} WHERE {' AND '.join(where_clauses)} ORDER BY CreateTime" if where_clauses else sql_base
src_data = execute_sql(outdb, sql, tuple(params))
if not src_data or len(src_data) < 1:
continue
# 插入数据
sql = f"INSERT OR IGNORE INTO {table} ({','.join([i for i in columns])}) VALUES ({','.join(['?'] * len(columns))})"
try:
out_cursor.executemany(sql, src_data)
# update sync_log
sql_update_sync_log = ("UPDATE sync_log "
"SET src_count = ? ,"
f"current_count=(SELECT COUNT(*) FROM {table}) "
"WHERE db_path=? AND tbl_name=?")
out_cursor.execute(sql_update_sync_log, (src_count, db_path, table))
except Exception as e:
wx_core_loger.error(
f"error: {db_path}\n{de_path}\n{table}\n{sql}\n{src_data}\n{len(src_data)}\n{e}\n",
exc_info=True)
# 分离数据库
sql_detach = f"DETACH DATABASE {alias}"
out_cursor.execute(sql_detach)
outdb.commit()
out_cursor.close()
outdb.close()
return save_path
# @wx_core_error
# def merge_db1(db_paths: list[dict], save_path: str = "merge.db", is_merge_data: bool = True,
# startCreateTime: int = 0, endCreateTime: int = 0):
# """
# 合并数据库 会忽略主键以及重复的行。
# :param db_paths: [{"db_path": "xxx", "de_path": "xxx"},...]
# db_path表示初始路径,de_path表示解密后的路径;初始路径用于保存合并的日志情况,解密后的路径用于读取数据
# :param save_path: str 输出文件路径
# :param is_merge_data: bool 是否合并数据(如果为False,则只解密,并创建表,不插入数据)
# :param startCreateTime: 开始时间戳 主要用于MSG数据库的合并
# :param endCreateTime: 结束时间戳 主要用于MSG数据库的合并
# :return:
# """
# if os.path.isdir(save_path):
# save_path = os.path.join(save_path, f"merge_{int(time.time())}.db")
#
# if isinstance(db_paths, list):
# # alias, file_path
# databases = {f"MSG{i}": (db['db_path'],
# db.get('de_path', db['db_path'])
# ) for i, db in enumerate(db_paths)
# }
# else:
# raise TypeError("db_paths 类型错误")
#
# from sqlalchemy import create_engine, MetaData, Table, select, insert, Column, UniqueConstraint
# from sqlalchemy.orm import sessionmaker
# from sqlalchemy import inspect, PrimaryKeyConstraint
#
# outdb = create_engine(f"sqlite:///{save_path}", echo=False)
#
# # 创建Session实例
# Session = sessionmaker()
# Session.configure(bind=outdb)
# session = Session()
#
# # 将MSG_db_paths中的数据合并到out_db_path中
# for alias, db in databases.items():
# db_path = db[0]
# de_path = db[1]
#
# db_engine = create_engine(f"sqlite:///{de_path}", echo=False)
#
# # 反射源数据库的表结构
# metadata = MetaData()
# metadata.reflect(bind=db_engine)
#
# # 创建表
# outdb_metadata = MetaData()
# inspector = inspect(db_engine)
# table_names = [i for i in inspector.get_table_names() if i not in ["sqlite_sequence"]]
# for table_name in table_names:
# # 创建表table
# columns_list_dict = inspector.get_columns(table_name)
# col_names = [i['name'] for i in columns_list_dict]
# columns = [Column(i['name'], i['type'], primary_key=False) for i in columns_list_dict]
# table = Table(table_name, outdb_metadata, *columns)
# if len(columns) > 1: # 联合索引
# unique_constraint = UniqueConstraint(*col_names, name=f"{table_name}_unique_index")
# table.append_constraint(unique_constraint)
# else:
# table.append_constraint(PrimaryKeyConstraint(*col_names))
# table.create(outdb, checkfirst=True)
#
# # 将源数据库中的数据插入目标数据库
# outdb_metadata = MetaData()
# for table_name in metadata.tables:
# source_table = Table(table_name, metadata, autoload_with=db_engine)
# outdb_table = Table(table_name, outdb_metadata, autoload_with=outdb)
#
# # 查询源表中的所有数据
# query = select(source_table)
# with db_engine.connect() as connection:
# result = connection.execute(query).fetchall()
#
# # 插入到目标表中
# for row in result:
# row_data = row._asdict()
#
# # 尝试将所有文本数据转换为 UTF-8
# for key, value in row_data.items():
# if isinstance(value, str):
# row_data[key] = value.encode("utf-8")
#
# insert_stmt = insert(outdb_table).values(row_data)
# try:
# session.execute(insert_stmt)
# except Exception as e:
# pass
# db_engine.dispose()
#
# # 提交事务
# session.commit()
# # 关闭Session
# session.close()
# outdb.dispose()
# return save_path
@wx_core_error
def decrypt_merge(wx_path: str, key: str, outpath: str = "",
merge_save_path: str = None,
is_merge_data=True, is_del_decrypted: bool = True,
startCreateTime: int = 0, endCreateTime: int = 0,
db_type=None) -> (bool, str):
"""
解密合并数据库 msg.db, microMsg.db, media.db,注意:会删除原数据库
:param wx_path: 微信路径 eg: C:\\*******\\WeChat Files\\wxid_*********
:param key: 解密密钥
:param outpath: 输出路径
:param merge_save_path: 合并后的数据库路径
:param is_merge_data: 是否合并数据(如果为False,则只解密,并创建表,不插入数据)
:param is_del_decrypted: 是否删除解密后的数据库(除了合并后的数据库)
:param startCreateTime: 开始时间戳 主要用于MSG数据库的合并
:param endCreateTime: 结束时间戳 主要用于MSG数据库的合并
:param db_type: 数据库类型,从核心数据库中选择
:return: (true,解密后的数据库路径) or (false,错误信息)
"""
if db_type is None:
db_type = []
outpath = outpath if outpath else "decrypt_merge_tmp"
merge_save_path = os.path.join(outpath,
f"merge_{int(time.time())}.db") if merge_save_path is None else merge_save_path
decrypted_path = os.path.join(outpath, "decrypted")
if not wx_path or not key or not os.path.exists(wx_path):
wx_core_loger.error("参数错误", exc_info=True)
return False, "参数错误"
# 解密
code, wxdbpaths = get_core_db(wx_path, db_type)
if not code:
wx_core_loger.error(f"获取数据库路径失败{wxdbpaths}", exc_info=True)
return False, wxdbpaths
# 判断out_path是否为空目录
if os.path.exists(decrypted_path) and os.listdir(decrypted_path):
for root, dirs, files in os.walk(decrypted_path, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
if not os.path.exists(decrypted_path):
os.makedirs(decrypted_path)
wxdbpaths = {i["db_path"]: i for i in wxdbpaths}
# 调用 decrypt 函数,并传入参数 # 解密
code, ret = batch_decrypt(key=key, db_path=list(wxdbpaths.keys()), out_path=decrypted_path, is_print=False)
if not code:
wx_core_loger.error(f"解密失败{ret}", exc_info=True)
return False, ret
out_dbs = []
for code1, ret1 in ret:
if code1:
out_dbs.append(ret1)
parpare_merge_db_path = []
for db_path, out_path, _ in out_dbs:
parpare_merge_db_path.append({"db_path": db_path, "de_path": out_path})
merge_save_path = merge_db(parpare_merge_db_path, merge_save_path, is_merge_data=is_merge_data,
startCreateTime=startCreateTime, endCreateTime=endCreateTime)
if is_del_decrypted:
shutil.rmtree(decrypted_path, True)
if isinstance(merge_save_path, str):
return True, merge_save_path
else:
return False, "未知错误"
@wx_core_error
def merge_real_time_db(key, merge_path: str, db_paths: [dict] or dict):
"""
合并实时数据库消息,暂时只支持64位系统
:param key: 解密密钥
:param db_paths: [dict] or dict eg: {'wxid': 'wxid_***', 'db_type': 'MicroMsg',
'db_path': 'C:\**\wxid_***\Msg\MicroMsg.db', 'wxid_dir': 'C:\***\wxid_***'}
:param merge_path: 合并后的数据库路径
:return:
"""
try:
import platform
except:
raise ImportError("未找到模块 platform")
# 判断系统位数是否为64位,如果不是则抛出异常
if platform.architecture()[0] != '64bit':
raise Exception("System is not 64-bit.")
if isinstance(db_paths, dict):
db_paths = [db_paths]
merge_path = os.path.abspath(merge_path) # 合并后的数据库路径,必须为绝对路径
merge_path_base = os.path.dirname(merge_path) # 合并后的数据库路径
if not os.path.exists(merge_path_base):
os.makedirs(merge_path_base)
endbs = []
for db_info in db_paths:
db_path = os.path.abspath(db_info['db_path'])
if not os.path.exists(db_path):
# raise FileNotFoundError("数据库不存在")
continue
if "MSG" not in db_path and "MicroMsg" not in db_path and "MediaMSG" not in db_path:
# raise FileNotFoundError("数据库不是消息数据库") # MicroMsg实时数据库
continue
endbs.append(os.path.abspath(db_path))
endbs = '" "'.join(list(set(endbs)))
# 获取当前文件夹路径
current_path = os.path.dirname(__file__)
real_time_exe_path = os.path.join(current_path, "tools", "realTime.exe")
# 调用cmd命令
cmd = f'{real_time_exe_path} "{key}" "{merge_path}" "{endbs}"'
# os.system(cmd)
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=merge_path_base,
creationflags=subprocess.CREATE_NO_WINDOW)
# p.communicate()
# 查看返回值
out, err = p.communicate()
if out and out.decode("utf-8").find("SUCCESS") >= 0:
wx_core_loger.info(f"合并实时数据库成功{out}")
return True, merge_path
if err:
wx_core_loger.error(f"合并实时数据库失败\n{out}\n{err}")
return False, err
@wx_core_error
def all_merge_real_time_db(key, wx_path, merge_path: str):
"""
合并所有实时数据库
注:这是全量合并,会有可能产生重复数据,需要自行去重
:param key: 解密密钥
:param wx_path: 微信路径
:param merge_path: 合并后的数据库路径 eg: C:\\*******\\WeChat Files\\wxid_*********\\merge.db
:return:
"""
if not merge_path or not key or not wx_path or not wx_path:
return False, "msg_path or media_path or wx_path or key is required"
try:
from pywxdump import get_core_db
except ImportError:
return False, "未找到模块 pywxdump"
db_paths = get_core_db(wx_path, ["MediaMSG", "MSG", "MicroMsg"])
if not db_paths[0]:
return False, db_paths[1]
db_paths = db_paths[1]
merge_real_time_db(key=key, merge_path=merge_path, db_paths=db_paths)
return True, merge_path
Whitespace-only changes.
Binary file not shown.
+15
View File
@@ -0,0 +1,15 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: __init__.py.py
# Description:
# Author: xaoyaoo
# Date: 2024/07/23
# -------------------------------------------------------------------------------
from .common_utils import verify_key, get_exe_version, get_exe_bit, wx_core_error
from .ctypes_utils import get_process_list, get_memory_maps, get_process_exe_path, \
get_file_version_info
from .memory_search import search_memory
from ._loger import wx_core_loger
DB_TYPE_CORE = ["MSG", "MediaMSG", "MicroMsg", "OpenIMContact", "OpenIMMedia", "OpenIMMsg", "Favorite", "PublicMsg"]
+10
View File
@@ -0,0 +1,10 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: _loger.py
# Description:
# Author: xaoyaoo
# Date: 2024/07/23
# -------------------------------------------------------------------------------
import logging
wx_core_loger = logging.getLogger("wx_core")
+125
View File
@@ -0,0 +1,125 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: utils.py
# Description:
# Author: xaoyaoo
# Date: 2023/12/25
# -------------------------------------------------------------------------------
import os
import re
import hmac
import sys
import traceback
import hashlib
<<<<<<< HEAD:pywxdump/wx_info/utils.py
=======
from ._loger import wx_core_loger
>>>>>>> ta:pywxdump/wx_core/utils/common_utils.py
if sys.platform == "win32":
from win32com.client import Dispatch
else:
Dispatch = None
<<<<<<< HEAD:pywxdump/wx_info/utils.py
def info_error(func):
=======
def wx_core_error(func):
>>>>>>> ta:pywxdump/wx_core/utils/common_utils.py
"""
错误处理装饰器
:param func:
:return:
"""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
<<<<<<< HEAD:pywxdump/wx_info/utils.py
traceback_data = traceback.format_exc()
rdata = f"{traceback_data}"
print(f"info_error: \n{rdata}")
return "None"
=======
wx_core_loger.error(f"wx_core_error: {e}", exc_info=True)
return None
>>>>>>> ta:pywxdump/wx_core/utils/common_utils.py
return wrapper
def verify_key(key, wx_db_path):
"""
验证key是否正确
"""
KEY_SIZE = 32
DEFAULT_PAGESIZE = 4096
DEFAULT_ITER = 64000
with open(wx_db_path, "rb") as file:
blist = file.read(5000)
salt = blist[:16]
pk = hashlib.pbkdf2_hmac("sha1", key, salt, DEFAULT_ITER, KEY_SIZE)
first = blist[16:DEFAULT_PAGESIZE]
mac_salt = bytes([(salt[i] ^ 58) for i in range(16)])
pk = hashlib.pbkdf2_hmac("sha1", pk, mac_salt, 2, KEY_SIZE)
hash_mac = hmac.new(pk, first[:-32], hashlib.sha1)
hash_mac.update(b'\x01\x00\x00\x00')
if hash_mac.digest() != first[-32:-12]:
return False
return True
@wx_core_error
def get_exe_version(file_path):
"""
获取 PE 文件的版本号
:param file_path: PE 文件路径(可执行文件)
:return: 如果遇到错误则返回
"""
if not os.path.exists(file_path):
return "None"
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)]
def get_exe_bit(file_path):
"""
# 获取exe文件的位数
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
+264
View File
@@ -0,0 +1,264 @@
import ctypes
import ctypes.wintypes
from collections import namedtuple
# 定义必要的常量
TH32CS_SNAPPROCESS = 0x00000002
MAX_PATH = 260
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
# MEMORY_BASIC_INFORMATION 结构体定义
class MEMORY_BASIC_INFORMATION(ctypes.Structure):
_fields_ = [
('BaseAddress', ctypes.wintypes.LPVOID),
('AllocationBase', ctypes.wintypes.LPVOID),
('AllocationProtect', ctypes.wintypes.DWORD),
('RegionSize', ctypes.c_size_t),
('State', ctypes.wintypes.DWORD),
('Protect', ctypes.wintypes.DWORD),
('Type', ctypes.wintypes.DWORD)
]
class MODULEINFO(ctypes.Structure):
_fields_ = [
("lpBaseOfDll", ctypes.c_void_p), # remote pointer
("SizeOfImage", ctypes.c_ulong),
("EntryPoint", ctypes.c_void_p), # remote pointer
]
# 定义PROCESSENTRY32结构
class PROCESSENTRY32(ctypes.Structure):
_fields_ = [("dwSize", ctypes.wintypes.DWORD),
("cntUsage", ctypes.wintypes.DWORD),
("th32ProcessID", ctypes.wintypes.DWORD),
("th32DefaultHeapID", ctypes.POINTER(ctypes.wintypes.ULONG)),
("th32ModuleID", ctypes.wintypes.DWORD),
("cntThreads", ctypes.wintypes.DWORD),
("th32ParentProcessID", ctypes.wintypes.DWORD),
("pcPriClassBase", ctypes.wintypes.LONG),
("dwFlags", ctypes.wintypes.DWORD),
("szExeFile", ctypes.c_char * MAX_PATH)]
class VS_FIXEDFILEINFO(ctypes.Structure):
_fields_ = [
('dwSignature', ctypes.wintypes.DWORD),
('dwStrucVersion', ctypes.wintypes.DWORD),
('dwFileVersionMS', ctypes.wintypes.DWORD),
('dwFileVersionLS', ctypes.wintypes.DWORD),
('dwProductVersionMS', ctypes.wintypes.DWORD),
('dwProductVersionLS', ctypes.wintypes.DWORD),
('dwFileFlagsMask', ctypes.wintypes.DWORD),
('dwFileFlags', ctypes.wintypes.DWORD),
('dwFileOS', ctypes.wintypes.DWORD),
('dwFileType', ctypes.wintypes.DWORD),
('dwFileSubtype', ctypes.wintypes.DWORD),
('dwFileDateMS', ctypes.wintypes.DWORD),
('dwFileDateLS', ctypes.wintypes.DWORD),
]
# 加载dll
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
psapi = ctypes.WinDLL('psapi', use_last_error=True)
version = ctypes.WinDLL('version', use_last_error=True)
# 创建进程快照
CreateToolhelp32Snapshot = kernel32.CreateToolhelp32Snapshot
CreateToolhelp32Snapshot.argtypes = [ctypes.wintypes.DWORD, ctypes.wintypes.DWORD]
CreateToolhelp32Snapshot.restype = ctypes.wintypes.HANDLE
# 获取第一个进程
Process32First = kernel32.Process32First
Process32First.argtypes = [ctypes.wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32)]
Process32First.restype = ctypes.wintypes.BOOL
# 获取下一个进程
Process32Next = kernel32.Process32Next
Process32Next.argtypes = [ctypes.wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32)]
Process32Next.restype = ctypes.wintypes.BOOL
# 关闭句柄
CloseHandle = kernel32.CloseHandle
CloseHandle.argtypes = [ctypes.wintypes.HANDLE]
CloseHandle.restype = ctypes.wintypes.BOOL
# 打开进程
OpenProcess = kernel32.OpenProcess
OpenProcess.argtypes = [ctypes.wintypes.DWORD, ctypes.wintypes.BOOL, ctypes.wintypes.DWORD]
OpenProcess.restype = ctypes.wintypes.HANDLE
# 获取模块文件名
GetModuleFileNameEx = psapi.GetModuleFileNameExA
GetModuleFileNameEx.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.HANDLE, ctypes.c_char_p, ctypes.wintypes.DWORD]
GetModuleFileNameEx.restype = ctypes.wintypes.DWORD
# 获取文件版本信息大小
GetFileVersionInfoSizeW = version.GetFileVersionInfoSizeW
GetFileVersionInfoSizeW.argtypes = [ctypes.wintypes.LPCWSTR, ctypes.POINTER(ctypes.wintypes.DWORD)]
GetFileVersionInfoSizeW.restype = ctypes.wintypes.DWORD
# 获取文件版本信息
GetFileVersionInfoW = version.GetFileVersionInfoW
GetFileVersionInfoW.argtypes = [ctypes.wintypes.LPCWSTR, ctypes.wintypes.DWORD, ctypes.wintypes.DWORD, ctypes.c_void_p]
GetFileVersionInfoW.restype = ctypes.wintypes.BOOL
# 查询文件版本信息
VerQueryValueW = version.VerQueryValueW
VerQueryValueW.argtypes = [ctypes.c_void_p, ctypes.wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_void_p),
ctypes.POINTER(ctypes.wintypes.UINT)]
VerQueryValueW.restype = ctypes.wintypes.BOOL
# 获取模块信息
GetModuleInformation = psapi.GetModuleInformation
GetModuleInformation.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.HMODULE, ctypes.POINTER(MODULEINFO),
ctypes.wintypes.DWORD]
GetModuleInformation.restype = ctypes.c_bool
# 读取进程内存
ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory
# 定义VirtualQueryEx函数
VirtualQueryEx = kernel32.VirtualQueryEx
VirtualQueryEx.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.LPCVOID, ctypes.POINTER(MEMORY_BASIC_INFORMATION),
ctypes.c_size_t]
VirtualQueryEx.restype = ctypes.c_size_t
# 获取映射文件名
GetMappedFileName = psapi.GetMappedFileNameA
GetMappedFileName.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.LPVOID, ctypes.c_char_p, ctypes.wintypes.DWORD]
GetMappedFileName.restype = ctypes.wintypes.DWORD
GetMappedFileNameW = psapi.GetMappedFileNameW
GetMappedFileNameW.restype = ctypes.wintypes.DWORD
GetMappedFileNameW.argtypes = [ctypes.wintypes.HANDLE, ctypes.c_void_p, ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD]
def get_memory_maps(pid):
# 打开进程
access = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ
hProcess = OpenProcess(access, False, pid)
if not hProcess:
return []
memory_maps = []
base_address = 0
mbi = MEMORY_BASIC_INFORMATION()
max_address = 0x7FFFFFFFFFFFFFFF # 64位系统的最大地址
while base_address < max_address:
if VirtualQueryEx(hProcess, base_address, ctypes.byref(mbi), ctypes.sizeof(mbi)) == 0:
break
mapped_file_name = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
if GetMappedFileNameW(hProcess, base_address, mapped_file_name, ctypes.wintypes.MAX_PATH) > 0:
file_name = mapped_file_name.value
else:
file_name = None
# module_info = MODULEINFO()
# if GetModuleInformation(hProcess, mbi.BaseAddress, ctypes.byref(module_info), ctypes.sizeof(module_info)):
# file_name = get_file_version_info(module_info.lpBaseOfDll)
memory_maps.append({
'BaseAddress': mbi.BaseAddress,
'RegionSize': mbi.RegionSize,
'State': mbi.State,
'Protect': mbi.Protect,
'Type': mbi.Type,
'FileName': file_name
})
base_address += mbi.RegionSize
CloseHandle(hProcess)
MemMap = namedtuple('MemMap', ['BaseAddress', 'RegionSize', 'State', 'Protect', 'Type', 'FileName'])
return [MemMap(**m) for m in memory_maps]
def get_process_exe_path(process_id):
h_process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, process_id)
if not h_process:
return None
exe_path = ctypes.create_string_buffer(MAX_PATH)
if GetModuleFileNameEx(h_process, None, exe_path, MAX_PATH) > 0:
CloseHandle(h_process)
return exe_path.value.decode('utf-8', errors='ignore')
else:
CloseHandle(h_process)
return None
def get_file_version_info(file_path):
size = GetFileVersionInfoSizeW(file_path, None)
if size == 0:
return None
res = ctypes.create_string_buffer(size)
if not GetFileVersionInfoW(file_path, 0, size, res):
return None
uLen = ctypes.wintypes.UINT()
lplpBuffer = ctypes.c_void_p()
if not VerQueryValueW(res, r'\\', ctypes.byref(lplpBuffer), ctypes.byref(uLen)):
return None
ffi = ctypes.cast(lplpBuffer, ctypes.POINTER(VS_FIXEDFILEINFO)).contents
if ffi.dwSignature != 0xFEEF04BD:
return None
version = (
(ffi.dwFileVersionMS >> 16) & 0xffff,
ffi.dwFileVersionMS & 0xffff,
(ffi.dwFileVersionLS >> 16) & 0xffff,
ffi.dwFileVersionLS & 0xffff,
)
# f"{version[0]}.{version[1]}.{version[2]}.{version[3]}"
return f"{version[0]}.{version[1]}.{version[2]}.{version[3]}"
def get_process_list():
h_process_snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
if h_process_snap == ctypes.wintypes.HANDLE(-1).value:
print("Failed to create snapshot")
return []
pe32 = PROCESSENTRY32()
pe32.dwSize = ctypes.sizeof(PROCESSENTRY32)
process_list = []
if not Process32First(h_process_snap, ctypes.byref(pe32)):
print("Failed to get first process")
CloseHandle(h_process_snap)
return []
while True:
# process_path = get_process_exe_path(pe32.th32ProcessID)
process_list.append((pe32.th32ProcessID, pe32.szExeFile.decode('utf-8', errors='ignore')))
if not Process32Next(h_process_snap, ctypes.byref(pe32)):
break
CloseHandle(h_process_snap)
return process_list
if __name__ == "__main__":
processes = get_process_list()
for pid, name in processes:
if name == "WeChat.exe":
# print(f"PID: {pid}, Process Name: {name}, Exe Path: {path}")
# Handle = ctypes.windll.kernel32.OpenProcess(0x1F0FFF, False, pid)
# wechat_base_address = 0
memory_maps = get_memory_maps(pid)
for module in memory_maps:
if module.FileName and 'WeChatWin.dll' in module.FileName:
print(module.BaseAddress)
print(module.FileName)
break
# print(wechat_base_address)
# get_info_with_key(Handle, key_baseaddr, addrLen)
+117
View File
@@ -0,0 +1,117 @@
import ctypes
import ctypes.wintypes as wintypes
import logging
import re
import sys
# 定义常量
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
PAGE_EXECUTE = 0x10
PAGE_EXECUTE_READ = 0x20
PAGE_EXECUTE_READWRITE = 0x40
PAGE_EXECUTE_WRITECOPY = 0x80
PAGE_NOACCESS = 0x01
PAGE_READONLY = 0x02
PAGE_READWRITE = 0x04
PAGE_WRITECOPY = 0x08
PAGE_GUARD = 0x100
PAGE_NOCACHE = 0x200
PAGE_WRITECOMBINE = 0x400
MEM_COMMIT = 0x1000
MEM_FREE = 0x10000
MEM_RESERVE = 0x2000
MEM_DECOMMIT = 0x4000
MEM_RELEASE = 0x8000
# 定义结构体
class MEMORY_BASIC_INFORMATION(ctypes.Structure):
_fields_ = [
("BaseAddress", ctypes.c_void_p),
("AllocationBase", ctypes.c_void_p),
("AllocationProtect", wintypes.DWORD),
("RegionSize", ctypes.c_size_t),
("State", wintypes.DWORD),
("Protect", wintypes.DWORD),
("Type", wintypes.DWORD),
]
# 加载Windows API函数
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
OpenProcess = kernel32.OpenProcess
OpenProcess.restype = wintypes.HANDLE
OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
ReadProcessMemory = kernel32.ReadProcessMemory
VirtualQueryEx = kernel32.VirtualQueryEx
VirtualQueryEx.restype = ctypes.c_size_t
VirtualQueryEx.argtypes = [wintypes.HANDLE, ctypes.c_void_p, ctypes.POINTER(MEMORY_BASIC_INFORMATION), ctypes.c_size_t]
CloseHandle = kernel32.CloseHandle
CloseHandle.restype = wintypes.BOOL
CloseHandle.argtypes = [wintypes.HANDLE]
def search_memory(hProcess, pattern=br'\\Msg\\FTSContact', max_num=100,start_address=0x0,end_address=0x7FFFFFFFFFFFFFFF):
"""
在进程内存中搜索字符串
:param p: 进程ID或者进程句柄
:param pattern: 要搜索的字符串
:param max_num: 最多找到的数量
"""
result = []
# 打开进程
if not hProcess:
raise ctypes.WinError(ctypes.get_last_error())
mbi = MEMORY_BASIC_INFORMATION()
address = start_address
max_address = end_address if sys.maxsize > 2 ** 32 else 0x7fff0000
pattern = re.compile(pattern)
while address < max_address:
if VirtualQueryEx(hProcess, address, ctypes.byref(mbi), ctypes.sizeof(mbi)) == 0:
break
# 读取内存数据
allowed_protections = [PAGE_EXECUTE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, PAGE_READONLY, ]
if mbi.State != MEM_COMMIT or mbi.Protect not in allowed_protections:
address += mbi.RegionSize
continue
# 使用正确的类型来避免OverflowError
base_address_c = ctypes.c_ulonglong(mbi.BaseAddress)
region_size_c = ctypes.c_size_t(mbi.RegionSize)
page_bytes = ctypes.create_string_buffer(mbi.RegionSize)
bytes_read = ctypes.c_size_t()
if ReadProcessMemory(hProcess, base_address_c, page_bytes, region_size_c, ctypes.byref(bytes_read)) == 0:
address += mbi.RegionSize
continue
# 搜索字符串 re print(page_bytes.raw)
find = [address + match.start() for match in pattern.finditer(page_bytes, re.DOTALL)]
if find:
result.extend(find)
if len(result) >= max_num:
break
address += mbi.RegionSize
return result
if __name__ == '__main__':
# 示例用法
pid = 29320 # 将此替换为你要查询的进程ID
try:
maps = search_memory(pid)
print(len(maps))
for m in maps:
print(hex(m))
except Exception as e:
logging.error(e, exc_info=True)
+438
View File
@@ -0,0 +1,438 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: getwxinfo.py
# Description:
# Author: xaoyaoo
# Date: 2023/08/21
# -------------------------------------------------------------------------------
import ctypes
import json
import os
import re
import winreg
from typing import List, Union
from .utils import verify_key, get_exe_bit, wx_core_error
from .utils import get_process_list, get_memory_maps, get_process_exe_path, get_file_version_info
from .utils import search_memory
from .utils import wx_core_loger, DB_TYPE_CORE
import ctypes.wintypes as wintypes
# 定义常量
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
OpenProcess = kernel32.OpenProcess
OpenProcess.restype = wintypes.HANDLE
OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
CloseHandle = kernel32.CloseHandle
CloseHandle.restype = wintypes.BOOL
CloseHandle.argtypes = [wintypes.HANDLE]
ReadProcessMemory = kernel32.ReadProcessMemory
void_p = ctypes.c_void_p
# 读取内存中的字符串(key部分)
@wx_core_error
def get_key_by_offs(h_process, address, address_len=8):
array = ctypes.create_string_buffer(address_len)
if ReadProcessMemory(h_process, void_p(address), array, address_len, 0) == 0: return None
address = int.from_bytes(array, byteorder='little') # 逆序转换为int地址(key地址)
key = ctypes.create_string_buffer(32)
if ReadProcessMemory(h_process, void_p(address), key, 32, 0) == 0: return None
key_string = bytes(key).hex()
return key_string
# 读取内存中的字符串(非key部分)
@wx_core_error
def get_info_string(h_process, address, n_size=64):
array = ctypes.create_string_buffer(n_size)
if ReadProcessMemory(h_process, void_p(address), array, n_size, 0) == 0: return None
array = bytes(array).split(b"\x00")[0] if b"\x00" in array else bytes(array)
text = array.decode('utf-8', errors='ignore')
return text.strip() if text.strip() != "" else None
# 读取内存中的字符串(昵称部分name)
@wx_core_error
def get_info_name(h_process, address, address_len=8, n_size=64):
array = ctypes.create_string_buffer(n_size)
if ReadProcessMemory(h_process, void_p(address), array, n_size, 0) == 0: return None
address1 = int.from_bytes(array[:address_len], byteorder='little') # 逆序转换为int地址(key地址)
info_name = get_info_string(h_process, address1, n_size)
if info_name != None:
return info_name
array = bytes(array).split(b"\x00")[0] if b"\x00" in array else bytes(array)
text = array.decode('utf-8', errors='ignore')
return text.strip() if text.strip() != "" else None
# 读取内存中的wxid
@wx_core_error
def get_info_wxid(h_process):
find_num = 100
addrs = search_memory(h_process, br'\\Msg\\FTSContact', max_num=find_num)
wxids = []
for addr in addrs:
array = ctypes.create_string_buffer(80)
if ReadProcessMemory(h_process, void_p(addr - 30), array, 80, 0) == 0: return None
array = bytes(array) # .split(b"\\")[0]
array = array.split(b"\\Msg")[0]
array = array.split(b"\\")[-1]
wxids.append(array.decode('utf-8', errors='ignore'))
wxid = max(wxids, key=wxids.count) if wxids else None
return wxid
# 读取内存中的wx_path基于wxid(慢)
@wx_core_error
def get_wx_dir_by_wxid(h_process, wxid=""):
find_num = 10
addrs = search_memory(h_process, wxid.encode() + br'\\Msg\\FTSContact', max_num=find_num)
wxid_dir = []
for addr in addrs:
win_addr_len = 260
array = ctypes.create_string_buffer(win_addr_len)
if ReadProcessMemory(h_process, void_p(addr - win_addr_len + 50), array, win_addr_len, 0) == 0: return None
array = bytes(array).split(b"\\Msg")[0]
array = array.split(b"\00")[-1]
wxid_dir.append(array.decode('utf-8', errors='ignore'))
wxid_dir = max(wxid_dir, key=wxid_dir.count) if wxid_dir else None
return wxid_dir
@wx_core_error
def get_wx_dir_by_reg(wxid="all"):
"""
# 读取 wx_dir (微信文件路径) (快)
:param wxid: 微信id
:return: 返回wx_dir,if wxid="all" return wx_dir else return wx_dir/wxid
"""
if not wxid:
return None
w_dir = "MyDocument:"
is_w_dir = False
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
is_w_dir = True
except Exception as e:
w_dir = "MyDocument:"
if not is_w_dir:
try:
user_profile = os.environ.get("USERPROFILE")
path_3ebffe94 = os.path.join(user_profile, "AppData", "Roaming", "Tencent", "WeChat", "All Users", "config",
"3ebffe94.ini")
with open(path_3ebffe94, "r", encoding="utf-8") as f:
w_dir = f.read()
is_w_dir = True
except Exception as e:
w_dir = "MyDocument:"
if w_dir == "MyDocument:":
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:]))
# print(1, w_dir)
else:
w_dir = documents_path
except Exception as e:
profile = os.environ.get("USERPROFILE")
w_dir = os.path.join(profile, "Documents")
wx_dir = os.path.join(w_dir, "WeChat Files")
if wxid and wxid != "all":
wxid_dir = os.path.join(wx_dir, wxid)
return wxid_dir if os.path.exists(wxid_dir) else None
return wx_dir if os.path.exists(wx_dir) else None
def get_wx_dir(wxid: str = "", Handle=None):
"""
综合运用多种方法获取wx_path
优先调用 get_wx_dir_by_reg (该方法速度快)
次要调用 get_wx_dir_by_wxid (该方法通过搜索内存进行,速度较慢)
"""
if wxid:
wx_dir = get_wx_dir_by_reg(wxid) if wxid else None
if wxid is not None and wx_dir is None and Handle: # 通过wxid获取wx_path,如果wx_path为空则通过wxid获取wx_path
wx_dir = get_wx_dir_by_wxid(Handle, wxid=wxid)
else:
wx_dir = get_wx_dir_by_reg()
return wx_dir
@wx_core_error
def get_key_by_mem_search(pid, db_path, addr_len):
"""
获取key (慢)
:param pid: 进程id
:param db_path: 微信数据库路径
:param addr_len: 地址长度
:return: 返回key
"""
def read_key_bytes(h_process, address, address_len=8):
array = ctypes.create_string_buffer(address_len)
if ReadProcessMemory(h_process, void_p(address), array, address_len, 0) == 0: return None
address = int.from_bytes(array, byteorder='little') # 逆序转换为int地址(key地址)
key = ctypes.create_string_buffer(32)
if ReadProcessMemory(h_process, void_p(address), key, 32, 0) == 0: return None
key_bytes = bytes(key)
return key_bytes
phone_type1 = "iphone\x00"
phone_type2 = "android\x00"
phone_type3 = "ipad\x00"
MicroMsg_path = os.path.join(db_path, "MSG", "MicroMsg.db")
start_adress = 0x7FFFFFFFFFFFFFFF
end_adress = 0
memory_maps = get_memory_maps(pid)
for module in memory_maps:
if module.FileName and 'WeChatWin.dll' in module.FileName:
s = module.BaseAddress
e = module.BaseAddress + module.RegionSize
start_adress = s if s < start_adress else start_adress
end_adress = e if e > end_adress else end_adress
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
type1_addrs = search_memory(hProcess, phone_type1.encode(), max_num=2, start_address=start_adress,
end_address=end_adress)
type2_addrs = search_memory(hProcess, phone_type2.encode(), max_num=2, start_address=start_adress,
end_address=end_adress)
type3_addrs = search_memory(hProcess, phone_type3.encode(), max_num=2, start_address=start_adress,
end_address=end_adress)
type_addrs = []
if len(type1_addrs) >= 2: type_addrs += type1_addrs
if len(type2_addrs) >= 2: type_addrs += type2_addrs
if len(type3_addrs) >= 2: type_addrs += type3_addrs
if len(type_addrs) == 0: return None
type_addrs.sort() # 从小到大排序
for i in type_addrs[::-1]:
for j in range(i, i - 2000, -addr_len):
key_bytes = read_key_bytes(hProcess, j, addr_len)
if key_bytes == None:
continue
if verify_key(key_bytes, MicroMsg_path):
return key_bytes.hex()
CloseHandle(hProcess)
return None
@wx_core_error
def get_wx_key(key: str = "", wx_dir: str = "", pid=0, addrLen=8):
"""
获取key (慢)
:param key: 微信key
:param wx_dir: 微信文件路径
:param pid: 进程id
:param addrLen: 地址长度
:return: 返回key
"""
isKey = verify_key(
bytes.fromhex(key),
os.path.join(wx_dir, "MSG", "MicroMsg.db")) if key is not None and wx_dir is not None else False
if wx_dir is not None and not isKey:
key = get_key_by_mem_search(pid, wx_dir, addrLen)
return key
@wx_core_error
def get_info_details(pid, WX_OFFS: dict = None):
path = get_process_exe_path(pid)
rd = {'pid': pid, 'version': get_file_version_info(path),
"account": None, "mobile": None, "nickname": None, "mail": None,
"wxid": None, "key": None, "wx_dir": None}
try:
bias_list = WX_OFFS.get(rd['version'], None)
Handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
addrLen = get_exe_bit(path) // 8
if not isinstance(bias_list, list) or len(bias_list) <= 4:
wx_core_loger.warning(f"[-] WeChat Current Version Is Not Supported(not get account,mobile,nickname,mail)")
else:
wechat_base_address = 0
memory_maps = get_memory_maps(pid)
for module in memory_maps:
if module.FileName and 'WeChatWin.dll' in module.FileName:
wechat_base_address = module.BaseAddress
rd['version'] = get_file_version_info(module.FileName) if os.path.exists(module.FileName) else rd[
'version']
bias_list = WX_OFFS.get(rd['version'], None)
break
if wechat_base_address != 0:
name_baseaddr = wechat_base_address + bias_list[0]
account_baseaddr = wechat_base_address + bias_list[1]
mobile_baseaddr = wechat_base_address + bias_list[2]
mail_baseaddr = wechat_base_address + bias_list[3]
key_baseaddr = wechat_base_address + bias_list[4]
rd['account'] = get_info_string(Handle, account_baseaddr, 32) if bias_list[1] != 0 else None
rd['mobile'] = get_info_string(Handle, mobile_baseaddr, 64) if bias_list[2] != 0 else None
rd['nickname'] = get_info_name(Handle, name_baseaddr, addrLen, 64) if bias_list[0] != 0 else None
rd['mail'] = get_info_string(Handle, mail_baseaddr, 64) if bias_list[3] != 0 else None
rd['key'] = get_key_by_offs(Handle, key_baseaddr, addrLen) if bias_list[4] != 0 else None
else:
wx_core_loger.warning(f"[-] WeChat WeChatWin.dll Not Found")
rd['wxid'] = get_info_wxid(Handle)
rd['wx_dir'] = get_wx_dir(rd['wxid'], Handle)
rd['key'] = get_wx_key(rd['key'], rd['wx_dir'], rd['pid'], addrLen)
CloseHandle(Handle)
except Exception as e:
wx_core_loger.error(f"[-] WeChat Get Info Error:{e}", exc_info=True)
return rd
# 读取微信信息(account,mobile,nickname,mail,wxid,key)
@wx_core_error
def get_wx_info(WX_OFFS: dict = None, is_print: bool = False, save_path: str = None):
"""
读取微信信息(account,mobile,nickname,mail,wxid,key)
:param WX_OFFS: 版本偏移量
:param is_print: 是否打印结果
:param save_path: 保存路径
:return: 返回微信信息 [{"pid": pid, "version": version, "account": account,
"mobile": mobile, "nickname": nickname, "mail": mail, "wxid": wxid,
"key": key, "wx_dir": wx_dir}, ...]
"""
if WX_OFFS is None:
WX_OFFS = {}
wechat_pids = []
result = []
processes = get_process_list()
for pid, name in processes:
if name == "WeChat.exe":
wechat_pids.append(pid)
if len(wechat_pids) <= 0:
wx_core_loger.error("[-] WeChat No Run")
return result
for pid in wechat_pids:
rd = get_info_details(pid, WX_OFFS)
result.append(rd)
if is_print:
print("=" * 32)
if isinstance(result, str): # 输出报错
print(result)
else: # 输出结果
for i, rlt in enumerate(result):
for k, v in rlt.items():
print(f"[+] {k:>8}: {v if v else 'None'}")
print(end="-" * 32 + "\n" if i != len(result) - 1 else "")
print("=" * 32)
if save_path:
try:
infos = json.load(open(save_path, "r", encoding="utf-8")) if os.path.exists(save_path) else []
except:
infos = []
with open(save_path, "w", encoding="utf-8") as f:
infos += result
json.dump(infos, f, ensure_ascii=False, indent=4)
return result
@wx_core_error
def get_wx_db(msg_dir: str = None,
db_types: Union[List[str], str] = None,
wxids: Union[List[str], str] = None) -> list[dict]:
r"""
获取微信数据库路径
:param msg_dir: 微信数据库目录 eg: C:\Users\user\Documents\WeChat Files (非wxid目录)
:param db_types: 需要获取的数据库类型,如果为空,则获取所有数据库
:param wxids: 微信id列表,如果为空,则获取所有wxid下的数据库
:return: [{"wxid": wxid, "db_type": db_type, "db_path": db_path, "wxid_dir": wxid_dir}, ...]
"""
result = []
if not msg_dir or not os.path.exists(msg_dir):
wx_core_loger.warning(f"[-] 微信文件目录不存在: {msg_dir}, 将使用默认路径")
msg_dir = get_wx_dir_by_reg(wxid="all")
if not os.path.exists(msg_dir):
wx_core_loger.error(f"[-] 目录不存在: {msg_dir}", exc_info=True)
return result
wxids = wxids.split(";") if isinstance(wxids, str) else wxids
if not isinstance(wxids, list) or len(wxids) <= 0:
wxids = None
db_types = db_types.split(";") if isinstance(db_types, str) else db_types
if not isinstance(db_types, list) or len(db_types) <= 0:
db_types = None
wxid_dirs = {} # wx用户目录
for sub_dir in os.listdir(msg_dir):
if os.path.isdir(os.path.join(msg_dir, sub_dir)) and sub_dir not in ["All Users", "Applet", "WMPF"]:
wxid_dirs[os.path.basename(sub_dir)] = os.path.join(msg_dir, sub_dir)
for wxid, wxid_dir in wxid_dirs.items():
if wxids and wxid not in wxids: # 如果指定wxid,则过滤掉其他wxid
continue
for root, dirs, files in os.walk(wxid_dir):
for file_name in files:
if not file_name.endswith(".db"):
continue
db_type = re.sub(r"\d*\.db$", "", file_name)
if db_types and db_type not in db_types: # 如果指定db_type,则过滤掉其他db_type
continue
db_path = os.path.join(root, file_name)
result.append({"wxid": wxid, "db_type": db_type, "db_path": db_path, "wxid_dir": wxid_dir})
return result
@wx_core_error
def get_core_db(wx_path: str, db_types: list = None) -> [dict]:
"""
获取聊天消息核心数据库路径
:param wx_path: 微信文件夹路径 eg:C:\*****\WeChat Files\wxid*******
:param db_types: 数据库类型 eg: DB_TYPE_CORE,中选择一个或多个
:return: 返回数据库路径 eg: [{"wxid": wxid, "db_type": db_type, "db_path": db_path, "wxid_dir": wxid_dir}, ...]
"""
if not os.path.exists(wx_path):
return False, f"[-] 目录不存在: {wx_path}"
if not db_types:
db_types = DB_TYPE_CORE
db_types = [dt for dt in db_types if dt in DB_TYPE_CORE]
msg_dir = os.path.dirname(wx_path)
my_wxid = os.path.basename(wx_path)
wxdbpaths = get_wx_db(msg_dir=msg_dir, db_types=db_types, wxids=my_wxid)
if len(wxdbpaths) == 0:
wx_core_loger.error(f"[-] get_core_db 未获取到数据库路径")
return False, "未获取到数据库路径"
return True, wxdbpaths
if __name__ == '__main__':
from pywxdump import WX_OFFS
get_wx_info(WX_OFFS, is_print=True)