整体重构项目,优化代码,增加命令行统一操作

This commit is contained in:
xaoyo committed 2023-10-14 21:48:35 +08:00
1 parent 2d44da3960
commit a63884a08b
19 files changed
+837 -332

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: __init__.py.py
# Description:
# Author: xaoyaoo
# Date: 2023/10/14
# -------------------------------------------------------------------------------
from .bias_addr import *
from .wx_info import *
from .decrypted import *
from .analyse import *
+8
View File
@@ -0,0 +1,8 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: __init__.py.py
# Description:
# Author: xaoyaoo
# Date: 2023/09/27
# -------------------------------------------------------------------------------
from .parse import read_img_dat, read_emoji, decompress_CompressContent, read_audio_buf, read_audio
+239
View File
@@ -0,0 +1,239 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: parse.py
# Description: 解析数据库内容
# Author: xaoyaoo
# Date: 2023/09/27
# -------------------------------------------------------------------------------
import sqlite3
import pysilk
from io import BytesIO
import wave
import pyaudio
import requests
import hashlib
from PIL import Image
import xml.etree.ElementTree as ET
def get_md5(data):
md5 = hashlib.md5()
md5.update(data)
return md5.hexdigest()
def parse_xml_string(xml_string):
"""
解析 XML 字符串
:param xml_string: 要解析的 XML 字符串
:return: 解析结果,以字典形式返回
"""
def parse_xml(element):
"""
递归解析 XML 元素
:param element: 要解析的 XML 元素
:return: 解析结果,以字典形式返回
"""
result = {}
# 解析当前元素的属性
for key, value in element.attrib.items():
result[key] = value
# 解析当前元素的子元素
for child in element:
child_result = parse_xml(child)
# 如果子元素的标签已经在结果中存在,则将其转换为列表
if child.tag in result:
if not isinstance(result[child.tag], list):
result[child.tag] = [result[child.tag]]
result[child.tag].append(child_result)
else:
result[child.tag] = child_result
# 如果当前元素没有子元素,则将其文本内容作为值保存
if not result and element.text:
result = element.text
return result
if xml_string is None or not isinstance(xml_string, str):
return None
try:
root = ET.fromstring(xml_string)
except Exception as e:
return xml_string
return parse_xml(root)
def read_img_dat(input_data):
# 常见图片格式的文件头
img_head = {
b"\xFF\xD8\xFF": ".jpg",
b"\x89\x50\x4E\x47": ".png",
b"\x47\x49\x46\x38": ".gif",
b"\x42\x4D": ".BMP",
b"\x49\x49": ".TIFF",
b"\x4D\x4D": ".TIFF",
b"\x00\x00\x01\x00": ".ICO",
b"\x52\x49\x46\x46": ".WebP",
b"\x00\x00\x00\x18\x66\x74\x79\x70\x68\x65\x69\x63": ".HEIC",
}
fomt = "un" # 文件格式
if isinstance(input_data, str):
with open(input_data, "rb") as f:
input_bytes = f.read()
t = 0
for hcode in img_head:
t = input_bytes[0] ^ hcode[0]
for i in range(1, len(hcode)):
if t == input_bytes[i] ^ hcode[i]:
fomt = img_head[hcode]
else:
break
else:
break
else:
return False
if fomt == "un":
print("未知文件格式")
return False
out_bytes = bytearray()
for nowByte in input_bytes: # 读取文件
newByte = nowByte ^ t # 异或解密
out_bytes.append(newByte)
md5 = get_md5(out_bytes)
return fomt, md5, out_bytes
def read_emoji(cdnurl, is_show=False):
headers = {
"User-Agent": "Mozilla/5.0 (Linux; Android 10; Redmi K30 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Mobile Safari/537.36"
}
r1 = requests.get(cdnurl, headers=headers)
rdata = r1.content
if is_show: # 显示表情
img = Image.open(BytesIO(rdata))
img.show()
return rdata
def decompress_CompressContent(data):
"""
解压缩Msg:CompressContent内容
:param data:
:return:
"""
if data is None or not isinstance(data, bytes):
return None
i = 0
uncompressed_data = []
while i < len(data):
# 读取第一个字节
byte1 = data[i]
# 从高四位得到无匹配的明文长度Lh
Lh = byte1 >> 4
Li = byte1 & 0x0F # 从低四位得到匹配的数据长度Li
if Lh == 0x0f:
# 继续读取下一个字节L1
i = i + 1
L1 = data[i]
Lh = L1 + 0x0f
while data[i] == 0xFF:
# 继续读取下一个字节,并累加
i = i + 1
Lh += data[i]
i += 1
uncompressed_data.extend(data[i:i + Lh])
i = i + Lh
# 读取匹配的偏移量Offset
bias = data[i:i + 2]
offset = int.from_bytes(bias, byteorder='little')
i = i + 2
# 读取匹配的数据长度Li
if Li != 0x0F:
# 实际的匹配压缩长度即为Li = Li + 4
Li += 4
else:
# 从偏移量后面的可选匹配长度区域读取一个字节M1
M1 = data[i]
Li += M1
while M1 == 0xFF:
# 继续读取下一个字节M2
i += 1
M1 = data[i]
Li += M1
Li += 4
# 复制匹配的数据到解压缩数据缓冲区
uncompressed_data.extend(uncompressed_data[-offset:-offset + Li])
# break
# 转换为字符串
uncompressed_data = bytes(uncompressed_data) # .decode('utf-8')
return uncompressed_data
def read_audio_buf(buf_data, is_play=False, is_wave=False, rate=24000):
silk_file = BytesIO(buf_data) # 读取silk文件
pcm_file = BytesIO() # 创建pcm文件
pysilk.decode(silk_file, pcm_file, rate) # 解码silk文件->pcm文件
pcm_data = pcm_file.getvalue() # 获取pcm文件数据
silk_file.close() # 关闭silk文件
pcm_file.close() # 关闭pcm文件
if is_play: # 播放音频
def play_audio(pcm_data, rate):
p = pyaudio.PyAudio() # 实例化pyaudio
stream = p.open(format=pyaudio.paInt16, channels=1, rate=rate, output=True) # 创建音频流对象
stream.write(pcm_data) # 写入音频流
stream.stop_stream() # 停止音频流
stream.close() # 关闭音频流
p.terminate() # 关闭pyaudio
play_audio(pcm_data, rate)
if is_wave: # 转换为wav文件
wave_file = BytesIO() # 创建wav文件
with wave.open(wave_file, 'wb') as wf:
wf.setparams((1, 2, rate, 0, 'NONE', 'NONE')) # 设置wav文件参数
wf.writeframes(pcm_data) # 写入wav文件
rdata = wave_file.getvalue() # 获取wav文件数据
wave_file.close() # 关闭wav文件
return rdata
return pcm_data
def read_audio(MsgSvrID, is_play=False, is_wave=False, DB_PATH: str = "", rate=24000):
if DB_PATH == "":
return False
DB = sqlite3.connect(DB_PATH)
cursor = DB.cursor()
sql = "select Buf from Media where Reserved0='{}'".format(MsgSvrID)
DBdata = cursor.execute(sql).fetchall()
if len(DBdata) == 0:
return False
data = DBdata[0][0] # [1:] + b'\xFF\xFF'
pcm_data = read_audio_buf(data, is_play, is_wave, rate)
return pcm_data
if __name__ == '__main__':
pass
+8
View File
@@ -0,0 +1,8 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: __init__.py.py
# Description:
# Author: xaoyaoo
# Date: 2023/10/14
# -------------------------------------------------------------------------------
from .get_bias_addr import BiasAddr
+247
View File
@@ -0,0 +1,247 @@
# -*- 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 time
import winreg
import threading
import psutil
# import win32api
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
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 else ""
self.process_name = "WeChat.exe"
self.module_name = "WeChatWin.dll"
self.pm = Pymem("WeChat.exe")
self.islogin = True
def find_all(self, 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_file_version(self, process_name):
for process in psutil.process_iter(['pid', 'name', 'exe']):
if process.name() == process_name:
file_version = Dispatch("Scripting.FileSystemObject").GetFileVersion(process.exe())
return file_version
self.islogin = False
def search_memory_value(self, value: bytes, module_name="WeChatWin.dll"):
# 创建 Pymem 对象
pm = self.pm
module = pymem.process.module_from_name(pm.process_handle, module_name)
mem_data = pm.read_bytes(module.lpBaseOfDll, module.SizeOfImage)
result = self.find_all(value, mem_data)
result = result[-1] if len(result) > 0 else 0
return result
def search_key(self, key: bytes):
pid = self.pm.process_id
# print(self.pm.process_base.lpBaseOfDll, self.pm.process_base.SizeOfImage)
module_start_addr = 34199871460642
module_end_addr = 0
process = psutil.Process(pid)
for module in process.memory_maps(grouped=False):
if "WeChat" in module.path:
start_addr = int(module.addr, 16)
end_addr = start_addr + module.rss
if module_start_addr > start_addr:
module_start_addr = start_addr
if module_end_addr < end_addr:
module_end_addr = end_addr
batch = 4096
Handle = ctypes.windll.kernel32.OpenProcess(0x1F0FFF, False, pid)
array = ctypes.create_string_buffer(batch)
key_addr = 0
for i in range(module_start_addr, module_end_addr, batch):
if ReadProcessMemory(Handle, void_p(i), array, batch, None) == 0:
continue
hex_string = array.raw # 读取到的内存数据
key_addr = self.find_all(key, hex_string, i)
if len(key_addr) > 0:
key_addr = key_addr[0]
break
# print(hex(key_addr))
key = key_addr.to_bytes(8, byteorder='little')
# print(key.hex())
result = self.search_memory_value(key, self.module_name)
return result
def get_key_bias(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 False
def get_maybe_key(mem_data):
maybe_key = []
for i in range(0, len(mem_data), 8):
addr = mem_data[i:i + 8]
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, 8)
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
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
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):
self.version = self.get_file_version(self.process_name)
if not self.islogin:
return "[-] WeChat No Run"
mobile_bias = self.search_memory_value(self.mobile)
name_bias = self.search_memory_value(self.name)
account_bias = self.search_memory_value(self.account)
# version_bias = self.search_memory_value(self.version.encode("utf-8"))
if self.key:
key_bias = self.search_key(self.key)
elif self.db_path:
key_bias = self.get_key_bias(self.db_path, account_bias)
else:
key_bias = 0
return {self.version: [name_bias, account_bias, mobile_bias, 0, key_bias]}
if __name__ == '__main__':
# 创建命令行参数解析器
parser = argparse.ArgumentParser()
parser.add_argument("--mobile", type=str, help="手机号", required=True)
parser.add_argument("--name", type=str, help="微信昵称", required=True)
parser.add_argument("--account", type=str, help="微信账号", required=True)
parser.add_argument("--key", type=str, help="密钥")
parser.add_argument("--db_path", type=str, help="微信文件夹(已经登录微信)路径")
# 解析命令行参数
args = parser.parse_args()
# 检查是否缺少必要参数,并抛出错误
if not args.mobile or not args.name or not args.account:
raise ValueError("缺少必要的命令行参数!请提供手机号、微信昵称、微信账号。")
if not args.key and not args.db_path:
raise ValueError("缺少必要的命令行参数!请提供密钥或微信文件夹(已经登录微信)路径。")
# 从命令行参数获取值
mobile = args.mobile
name = args.name
account = args.account
key = args.key
db_path = args.db_path
# 调用 run 函数,并传入参数
rdata = BiasAddr(account, mobile, name, key, db_path).run()
print(rdata)
# 添加到version_list.json
with open("../version_list.json", "r", encoding="utf-8") as f:
data = json.load(f)
data.update(rdata)
with open("../version_list.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
+9
View File
@@ -0,0 +1,9 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: __init__.py.py
# Description:
# Author: xaoyaoo
# Date: 2023/08/21
# -------------------------------------------------------------------------------
from .decrypt import batch_decrypt, decrypt
from .get_wx_decrypted_db import all_decrypt, merge_copy_msg_db, merge_msg_db, merge_media_msg_db
+137
View File
@@ -0,0 +1,137 @@
import argparse
import hmac
import hashlib
import os
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):
if not os.path.exists(db_path):
return f"[-] db_path:'{db_path}' File not found!"
if not os.path.exists(os.path.dirname(out_path)):
return f"[-] out_path:'{out_path}' File not found!"
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]
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 f"[-] Password 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: [str | list], out_path: str):
if not isinstance(key, str) or not isinstance(out_path, str) or not os.path.exists(out_path) or len(key) != 64:
return f"[-] (key:'{key}' or out_path:'{out_path}') Error!"
process_list = []
if isinstance(db_path, str):
if not os.path.exists(db_path):
return f"[-] db_path:'{db_path}' not found!"
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:
return f"[-] db_path:'{db_path}' 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):
return f"[-] db_path:'{db_path}' not found!"
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:
return f"[-] db_path:'{db_path}' 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))
return result
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)
for i in result:
if isinstance(i, str):
print(i)
else:
print(f'[+] "{i[1]}" -> "{i[2]}"')
+309
View File
@@ -0,0 +1,309 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: get_wx_decrypted_db.py
# Description:
# Author: xaoyaoo
# Date: 2023/08/25
# -------------------------------------------------------------------------------
import argparse
import os
import re
import shutil
import sqlite3
import winreg
from .decrypt import decrypt
# 开始获取微信数据库
def get_wechat_db():
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:
w_dir = "MyDocument:"
except Exception as e:
print("读取注册表错误:", str(e))
return str(e)
if w_dir == "MyDocument:":
profile = os.path.expanduser("~")
msg_dir = os.path.join(profile, "Documents", "WeChat Files")
else:
msg_dir = os.path.join(w_dir, "WeChat Files")
if not os.path.exists(msg_dir):
return FileNotFoundError("目录不存在")
user_dirs = {} # wx用户目录
files = os.listdir(msg_dir)
for file_name in files:
if file_name == "All Users" or file_name == "Applet" or file_name == "WMPF":
continue
user_dirs[file_name] = os.path.join(msg_dir, file_name)
# 获取数据库路径
for user, user_dir in user_dirs.items():
Media_p = []
Micro_p = []
FTS_p = []
Sns_p = []
Msg = []
Emotion_p = []
for root, dirs, files in os.walk(user_dir):
for file_name in files:
if re.match(r".*MediaMSG.*\.db$", file_name):
src_path = os.path.join(root, file_name)
Media_p.append(src_path)
elif re.match(r".*MicroMsg.*\.db$", file_name):
src_path = os.path.join(root, file_name)
Micro_p.append(src_path)
elif re.match(r".*FTSMSG.*\.db$", file_name):
src_path = os.path.join(root, file_name)
FTS_p.append(src_path)
elif re.match(r".*MSG.*\.db$", file_name):
src_path = os.path.join(root, file_name)
Msg.append(src_path)
elif re.match(r".*Sns.*\.db$", file_name):
src_path = os.path.join(root, file_name)
Sns_p.append(src_path)
elif re.match(r".*Emotion.*\.db$", file_name):
src_path = os.path.join(root, file_name)
Emotion_p.append(src_path)
Media_p.sort()
Msg.sort()
Micro_p.sort()
# FTS_p.sort()
user_dirs[user] = {"MicroMsg": Micro_p, "Msg": Msg, "MediaMSG": Media_p, "Sns": Sns_p, "Emotion": Emotion_p}
return user_dirs
# 解密所有数据库 paths(文件) 到 decrypted_path(目录)
def all_decrypt(keys, paths, decrypted_path):
decrypted_paths = []
for key in keys:
for path in paths:
name = os.path.basename(path) # 文件名
dtp = os.path.join(decrypted_path, name) # 解密后的路径
if not decrypt(key, path, dtp):
break
decrypted_paths.append(dtp)
else: # for循环正常结束,没有break
break # 跳出while循环
else:
return False # while循环正常结束,没有break 解密失败
return decrypted_paths
def merge_copy_msg_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)
# 合并相同名称的数据库
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 * 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
if __name__ == '__main__':
# 创建命令行参数解析器
parser = argparse.ArgumentParser()
parser.add_argument("-k", "--key", help="解密密钥", nargs="+", required=True)
# 解析命令行参数
args = parser.parse_args()
# 检查是否缺少必要参数,并抛出错误
if not args.key:
raise ValueError("缺少必要的命令行参数!请提供密钥。")
# 从命令行参数获取值
keys = args.key
decrypted_ROOT = os.path.join(os.getcwd(), "decrypted")
if keys is None:
print("keys is None")
exit(0)
if isinstance(keys, str):
keys = [keys]
user_dirs = get_wechat_db()
for user, db_path in user_dirs.items(): # 遍历用户
MicroMsgPaths = db_path["MicroMsg"]
MsgPaths = db_path["Msg"]
MediaMSGPaths = db_path["MediaMSG"]
# FTSMSGPaths = db_path["FTSMSG"]
SnsPaths = db_path["Sns"]
EmotionPaths = db_path["Emotion"]
decrypted_path_tmp = os.path.join(decrypted_ROOT, user, "tmp") # 解密后的目录
if not os.path.exists(decrypted_path_tmp):
os.makedirs(decrypted_path_tmp)
MicroMsgDecryptPaths = all_decrypt(keys, MicroMsgPaths, decrypted_path_tmp)
MsgDecryptPaths = all_decrypt(keys, MsgPaths, decrypted_path_tmp)
MediaMSGDecryptPaths = all_decrypt(keys, MediaMSGPaths, decrypted_path_tmp)
SnsDecryptPaths = all_decrypt(keys, SnsPaths, decrypted_path_tmp)
EmotionDecryptPaths = all_decrypt(keys, EmotionPaths, decrypted_path_tmp)
# 合并数据库
decrypted_path = os.path.join(decrypted_ROOT, user) # 解密后的目录
MicroMsgDbPath = os.path.join(decrypted_path, "MicroMsg.db")
MsgDbPath = os.path.join(decrypted_path, "MSG_all.db")
MediaMSGDbPath = os.path.join(decrypted_path, "MediaMSG_all.db")
SnsDbPath = os.path.join(decrypted_path, "Sns_all.db")
EmmotionDbPath = os.path.join(decrypted_path, "Emotion_all.db")
merge_copy_msg_db(MicroMsgDecryptPaths, MicroMsgDbPath)
merge_msg_db(MsgDecryptPaths, MsgDbPath, 0)
merge_media_msg_db(MediaMSGDecryptPaths, MediaMSGDbPath)
merge_copy_msg_db(SnsDecryptPaths, SnsDbPath)
merge_copy_msg_db(EmotionDecryptPaths, EmmotionDbPath)
shutil.rmtree(decrypted_path_tmp) # 删除临时文件
print(f"解密完成:{user}, {decrypted_path}")
+324
View File
@@ -0,0 +1,324 @@
{
"3.2.1.154": [
328121948,
328122328,
328123056,
328121976,
328123020
],
"3.3.0.115": [
31323364,
31323744,
31324472,
31323392,
31324436
],
"3.3.0.84": [
31315212,
31315592,
31316320,
31315240,
31316284
],
"3.3.0.93": [
31323364,
31323744,
31324472,
31323392,
31324436
],
"3.3.5.34": [
30603028,
30603408,
30604120,
30603056,
30604100
],
"3.3.5.42": [
30603012,
30603392,
30604120,
30603040,
30604084
],
"3.3.5.46": [
30578372,
30578752,
30579480,
30578400,
30579444
],
"3.4.0.37": [
31608116,
31608496,
31609224,
31608144,
31609188
],
"3.4.0.38": [
31604044,
31604424,
31605152,
31604072,
31605116
],
"3.4.0.50": [
31688500,
31688880,
31689608,
31688528,
31689572
],
"3.4.0.54": [
31700852,
31701248,
31700920,
31700880,
31701924
],
"3.4.5.27": [
32133788,
32134168,
32134896,
32133816,
32134860
],
"3.4.5.45": [
32147012,
32147392,
32147064,
32147040,
32148084
],
"3.5.0.20": [
35494484,
35494864,
35494536,
35494512,
35495556
],
"3.5.0.29": [
35507980,
35508360,
35508032,
35508008,
35509052
],
"3.5.0.33": [
35512140,
35512520,
35512192,
35512168,
35513212
],
"3.5.0.39": [
35516236,
35516616,
35516288,
35516264,
35517308
],
"3.5.0.42": [
35512140,
35512520,
35512192,
35512168,
35513212
],
"3.5.0.44": [
35510836,
35511216,
35510896,
35510864,
35511908
],
"3.5.0.46": [
35506740,
35507120,
35506800,
35506768,
35507812
],
"3.6.0.18": [
35842996,
35843376,
35843048,
35843024,
35844068
],
"3.6.5.7": [
35864356,
35864736,
35864408,
35864384,
35865428
],
"3.6.5.16": [
35909428,
35909808,
35909480,
35909456,
35910500
],
"3.7.0.26": [
37105908,
37106288,
37105960,
37105936,
37106980
],
"3.7.0.29": [
37105908,
37106288,
37105960,
37105936,
37106980
],
"3.7.0.30": [
37118196,
37118576,
37118248,
37118224,
37119268
],
"3.7.5.11": [
37883280,
37884088,
37883136,
37883008,
37884052
],
"3.7.5.23": [
37895736,
37896544,
37895592,
37883008,
37896508
],
"3.7.5.27": [
37895736,
37896544,
37895592,
37895464,
37896508
],
"3.7.5.31": [
37903928,
37904736,
37903784,
37903656,
37904700
],
"3.7.6.24": [
38978840,
38979648,
38978696,
38978604,
38979612
],
"3.7.6.29": [
38986376,
38987184,
38986232,
38986104,
38987148
],
"3.7.6.44": [
39016520,
39017328,
39016376,
38986104,
39017292
],
"3.8.0.31": [
46064088,
46064912,
46063944,
38986104,
46064876
],
"3.8.0.33": [
46059992,
46060816,
46059848,
38986104,
46060780
],
"3.8.0.41": [
46064024,
46064848,
46063880,
38986104,
46064812
],
"3.8.1.26": [
46409448,
46410272,
46409304,
38986104,
46410236
],
"3.9.0.28": [
48418376,
48419280,
48418232,
38986104,
48419244
],
"3.9.2.23": [
50320784,
50321712,
50320640,
38986104,
50321676
],
"3.9.2.26": [
50329040,
50329968,
50328896,
38986104,
50329932
],
"3.9.5.81": [
61650872,
61652208,
61650680,
0,
61652144
],
"3.9.5.91": [
61654904,
61654680,
61654712,
38986104,
61656176
],
"3.9.6.19": [
61997688,
61997464,
61997496,
38986104,
61998960
],
"3.9.6.33": [
62030600,
62031936,
62030408,
0,
62031872
],
"3.9.7.25": [
63482760,
63484096,
63482568,
0,
63484032
],
"3.9.7.29": [
63486984,
63488320,
63486792,
0,
63488256
]
}
+9
View File
@@ -0,0 +1,9 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: __init__.py.py
# Description:
# Author: xaoyaoo
# Date: 2023/08/21
# -------------------------------------------------------------------------------
from .get_wx_info import read_info
from .get_wx_db import get_wechat_db
+75
View File
@@ -0,0 +1,75 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: get_wx_db.py
# Description:
# Author: xaoyaoo
# Date: 2023/10/14
# -------------------------------------------------------------------------------
import os
import re
import winreg
def get_wechat_db(require_list: [list | str] = "all", msg_dir: str = None):
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:
w_dir = "MyDocument:"
if w_dir == "MyDocument:":
profile = os.path.expanduser("~")
msg_dir = os.path.join(profile, "Documents", "WeChat Files")
else:
msg_dir = os.path.join(w_dir, "WeChat Files")
if not os.path.exists(msg_dir):
return "[-] 目录不存在"
user_dirs = {} # wx用户目录
files = os.listdir(msg_dir)
for file_name in files:
if file_name == "All Users" or file_name == "Applet" or file_name == "WMPF":
continue
user_dirs[file_name] = os.path.join(msg_dir, file_name)
if isinstance(require_list, str):
require_list = require_list.split(";")
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:
return "[-] 参数错误"
# 获取数据库路径
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)
return user_dirs
if __name__ == '__main__':
require_list = ["MediaMSG", "MicroMsg", "FTSMSG", "MSG", "Sns", "Emotion"]
# require_list = "all"
user_dirs = get_wechat_db(require_list)
if isinstance(user_dirs, str):
print(user_dirs)
else:
for user, user_dir in user_dirs.items():
print(f"[+] {user}")
for n, paths in user_dir.items():
print(f" {n}:")
for path in paths:
print(f" {path}")
+98
View File
@@ -0,0 +1,98 @@
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: getwxinfo.py
# Description:
# Author: xaoyaoo
# Date: 2023/08/21
# -------------------------------------------------------------------------------
import json
import ctypes
from win32com.client import Dispatch
import psutil
ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory
void_p = ctypes.c_void_p
# 读取内存中的字符串(非key部分)
def get_info_without_key(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"
# 读取内存中的key
def get_key(h_process, address):
array = ctypes.create_string_buffer(8)
if ReadProcessMemory(h_process, void_p(address), array, 8, 0) == 0: return "None"
key = ctypes.create_string_buffer(32)
address = int.from_bytes(array, byteorder='little') # 逆序转换为int地址(key地址)
if ReadProcessMemory(h_process, void_p(address), key, 32, 0) == 0: return "None"
key_string = bytes(key).hex()
return key_string
# 读取微信信息(key, name, account, mobile, mail)
def read_info(version_list):
wechat_process = []
result = []
for process in psutil.process_iter(['name', 'exe', 'pid', 'cmdline']):
if process.name() == 'WeChat.exe':
wechat_process.append(process)
if len(wechat_process) == 0:
return "[-] WeChat No Run"
for process in wechat_process:
tmp_rd = {}
tmp_rd['pid'] = process.pid
tmp_rd['version'] = Dispatch("Scripting.FileSystemObject").GetFileVersion(process.exe())
support_list = version_list.get(tmp_rd['version'], None)
if not isinstance(support_list, list):
return f"[-] WeChat Current Version {tmp_rd['version']} Is Not Supported"
wechat_base_address = 0
for module in process.memory_maps(grouped=False):
if module.path and 'WeChatWin.dll' in module.path:
wechat_base_address = int(module.addr, 16)
break
if wechat_base_address == 0:
return f"[-] WeChat WeChatWin.dll Not Found"
Handle = ctypes.windll.kernel32.OpenProcess(0x1F0FFF, False, process.pid)
name_baseaddr = wechat_base_address + support_list[0]
account__baseaddr = wechat_base_address + support_list[1]
mobile_baseaddr = wechat_base_address + support_list[2]
mail_baseaddr = wechat_base_address + support_list[3]
key_baseaddr = wechat_base_address + support_list[4]
tmp_rd['account'] = get_info_without_key(Handle, account__baseaddr, 32)
tmp_rd['mobile'] = get_info_without_key(Handle, mobile_baseaddr, 64)
tmp_rd['name'] = get_info_without_key(Handle, name_baseaddr, 64)
tmp_rd['mail'] = get_info_without_key(Handle, mail_baseaddr, 64) if support_list[3] != 0 else "None"
tmp_rd['key'] = get_key(Handle, key_baseaddr)
result.append(tmp_rd)
return result
if __name__ == "__main__":
# 读取微信各版本偏移
version_list = json.load(open("../version_list.json", "r", encoding="utf-8"))
result = read_info(version_list) # 读取微信信息
print("=" * 32)
if isinstance(result, str): # 输出报错
print(result)
else: # 输出结果
for i, rlt in enumerate(result):
for k, v in rlt.items():
print(f"[+] {k:>7}: {v}")
print(end="-" * 32 + "\n" if i != len(result) - 1 else "")
print("=" * 32)