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

+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)