• 获取 Windows 系统托盘图标信息的最新方案(一)


    目录

    前言

    1 获取系统托盘图标的一般方法

    1.1 使用 TB_ 类消息的注意事项

    1.2 代码编写和测试

    1.3 技术的适用范围

    2 深度分析系统托盘图标信息

    2.1 分析 Shell_NotifyIcon 函数参数

    2.2 分析 Shell_NotifyIcon 函数的内部细节

    2.3 分析 WM_COPYDATA 消息

    2.4 调用方挂钩拦截消息封送过程

    2.5 接收方挂钩实现获取任意图标信息

    3 注入 HOOK 模块的方案

    3.1 创建挂起进程注入

    3.2 创建调试进程注入

    3.3 等待调试事件

    3.4 处理调试事件

    3.5 完整代码和测试结果

    3.6 补充说明

    4 初步分析系统托盘图标的注册表转储

    4.1 传统的注册表转储信息

    4.2 Win11 特有的转储信息


    本文出处链接:[https://blog.csdn.net/qq_59075481/article/details/136134195]

    前言

    本文分析获取系统通知区域图标的多种方法。解释了在 Win11 22H2 更新后无法获取托盘图标信息的问题所在,并给出了有效的解决方案。这篇文章发布前,我一直在我的一篇历史文章中更新我的研究进度。在解决这个这个问题的过程中,我逐步地了解到了通知消息传递的一些细节,而在此之前对细节实现的分析过程只是被我潦草地堆砌在一起,并没有很好地梳理事情的整个流程。所以我决定将文章重新整理出来。也就是大家现在看到的这篇长文,请认真地阅读下去,这将会解决一部分的一直以来在文献中含糊不清的问题。如果你不了解系统通知方面的知识,建议你先阅读第 5 篇 “对通知区域(Win 系统托盘)窗口层次的分析” 以便于了解设计基础知识。

    系列文章列表:

    P.S.: 第 3 篇文章主要解释本篇第 4 节的代码原理,第 4 篇文章是改进了挂钩处理的方式。

    1 获取系统托盘图标的一般方法

    在 Windows 操作系统上,一般情况下我们可以通过 TB_BUTTONCOUNT 消息来获取 ToolBar 的按钮个数。传统的任务栏通知区域(俗称系统托盘)就采用了 Toolbar 的设计,所以我们可以通过发送 TB_BUTTONCOUNT 来获取通知图标的个数。获取到个数后,就可以通过 TB_GETBUTTONTEXT 来获取 Toolbar 上图标的显示文本信息,但调用它的前提是使用 TB_GETBUTTON 消息。这个方法从 WinXP 以来是一直在使用的。

    关于该方法的原理前面已经有人整理过了,可以看这一系列文章:

    1.1 使用 TB_ 类消息的注意事项

    使用 SendMessage 函数发送 TB_BUTTONCOUNT 消息到指定窗口,可以检索工具栏中当前按钮的计数。但这个值可能并不是最新的,个数仅仅是当前的个数,而且并非显示的个数,也非有效按钮窗口的个数,这也是为什么微软想要清除这个接口的原因。

    使用 SendMessage 函数发送 TB_GETBUTTON 消息到指定窗口获取指针,然后向指定进程申请访问内存,获取 TBBUTTON 结构体中 dwData 字段数据,可以获得远线程的工具栏窗口中当前所有按钮的句柄、标题、进程路径信息。但该信息可能包含旧的内容。

    任务栏的通知区域分为四个部分:用户提示的通知区域、系统升级的通知区域,溢出角通知区域、 DUI 弹出式通知区域(部分图标如:电源电量、音量等的注册记录在溢出通知区域窗口,但是并不是在溢出窗口内显示的,所以单独归类)。通知区域是外壳处理器 Shell 控件:ToolBarWindow32.

    首先我们需要明白任务栏的 ToolBarWindow (工具栏视图)的一些特征:

    1)除系统升级的通知区域以外的通知区域图标不会自动刷新,需要接收到鼠标移动消息、模拟点击消息才会逐个刷新。

    2)如果一个窗口多次在通知区域注册通知图标,即使它是由同一个窗口发出的,也会被记录为独立的窗口,但他们具有相同的信息,在外壳程序内存中相应位置按序排列。

    1.2 代码编写和测试

    下面我们简单谈一谈代码的编写,网络上一种用于 Win7-Win11 的代码如下(有缺陷):

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. using namespace std;
    7. // 判断 x64 系统
    8. BOOL Is64bitSystem()
    9. {
    10. SYSTEM_INFO si;
    11. GetNativeSystemInfo(&si);
    12. if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ||
    13. si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
    14. return TRUE;
    15. else
    16. return FALSE;
    17. }
    18. // 获取托盘窗口句柄
    19. HWND FindTrayWnd()
    20. {
    21. HWND hWnd = NULL;
    22. hWnd = FindWindow(_T("Shell_TrayWnd"), NULL);
    23. hWnd = FindWindowEx(hWnd, NULL, _T("TrayNotifyWnd"), NULL);
    24. hWnd = FindWindowEx(hWnd, NULL, _T("SysPager"), NULL);
    25. hWnd = FindWindowEx(hWnd, NULL, _T("ToolbarWindow32"), NULL);
    26. return hWnd;
    27. }
    28. // 获取折叠托盘窗口句柄
    29. HWND FindNotifyIconOverflowWindow()
    30. {
    31. HWND hWnd = NULL;
    32. hWnd = FindWindow(_T("NotifyIconOverflowWindow"), NULL);
    33. hWnd = FindWindowEx(hWnd, NULL, _T("ToolbarWindow32"), NULL);
    34. return hWnd;
    35. }
    36. // 遍历窗口
    37. BOOL EnumNotifyWindow(HWND hWnd)
    38. {
    39. // 获取托盘进程ID
    40. DWORD dwProcessId = 0;
    41. GetWindowThreadProcessId(hWnd, &dwProcessId);
    42. if (dwProcessId == 0) {
    43. cout << "GetWindowThreadProcessId failed:" << GetLastError() << endl;
    44. return FALSE;
    45. }
    46. // 获取托盘进程句柄
    47. HANDLE hProcess = OpenProcess(
    48. PROCESS_VM_OPERATION | // 需要在进程的地址空间上执行操作
    49. PROCESS_VM_READ | // 需要使用 ReadProcessMemory 读取进程中的内存
    50. PROCESS_VM_WRITE, // 需要在使用 WriteProcessMemory 的进程中写入内存
    51. FALSE, // 子进程不继承句柄
    52. dwProcessId // 目标进程 PID
    53. );
    54. if (hProcess == NULL) {
    55. cout << "OpenProcess failed:" << GetLastError() << endl;
    56. return FALSE;
    57. }
    58. // 在进程虚拟空间中分配内存,用来接收 TBBUTTON 结构体指针
    59. LPVOID p_tbbutton = VirtualAllocEx(
    60. hProcess, // 目标进程句柄
    61. 0, // 内存起始地址(默认)
    62. 4096, // 内存大小
    63. MEM_COMMIT, // 内存类型(提交)
    64. PAGE_EXECUTE_READWRITE // 内存保护属性(可读可写可执行)
    65. );
    66. if (p_tbbutton == NULL) {
    67. cout << "VirtualAllocEx failed:" << GetLastError() << endl;
    68. return FALSE;
    69. }
    70. // 初始化
    71. DWORD dw_addr_dwData = 0;
    72. BYTE buff[1024] = { 0 };
    73. wstring ws_filePath = L"";
    74. wstring ws_tile = L"";
    75. HWND h_mainWnd = NULL;
    76. int i_data_offset = 12;
    77. int i_str_offset = 18;
    78. // 判断 x64
    79. if (Is64bitSystem()) {
    80. i_data_offset += 4;
    81. i_str_offset += 6;
    82. }
    83. // 获取托盘图标个数
    84. int i_buttons = 0;
    85. i_buttons = SendMessage(hWnd, TB_BUTTONCOUNT, 0, 0);
    86. if (i_buttons == 0) {
    87. cout << "TB_BUTTONCOUNT message failed:" << GetLastError() << endl;
    88. return FALSE;
    89. }
    90. // 遍历托盘
    91. for (int i = 0; i < i_buttons; i++) {
    92. // 获取 TBBUTTON 结构体指针
    93. if (!SendMessage(hWnd, TB_GETBUTTON, i, (LPARAM)p_tbbutton)) {
    94. cout << "TB_GETBUTTON message failed:" << GetLastError() << endl;
    95. return FALSE;
    96. }
    97. // 读 TBBUTTON.dwData(附加信息)
    98. if (!ReadProcessMemory(hProcess, (LPVOID)((DWORD)p_tbbutton + i_data_offset), &dw_addr_dwData, 4, 0)) {
    99. cout << "ReadProcessMemory failed:" << GetLastError() << endl;
    100. return FALSE;
    101. }
    102. // 读文本
    103. if (dw_addr_dwData) {
    104. if (!ReadProcessMemory(hProcess, (LPCVOID)dw_addr_dwData, buff, 1024, 0)) {
    105. cout << "ReadProcessMemory failed:" << GetLastError() << endl;
    106. return FALSE;
    107. }
    108. h_mainWnd = (HWND)(*((DWORD*)buff));
    109. ws_filePath = (WCHAR*)buff + i_str_offset;
    110. ws_tile = (WCHAR*)buff + i_str_offset + MAX_PATH;
    111. TCHAR szBuff[256];
    112. GetClassNameW(h_mainWnd, szBuff, sizeof(szBuff) / sizeof(TCHAR));//函数调用
    113. cout << "MainWindowHandleVale = " << hex << h_mainWnd << endl;
    114. wcout << "ExecuteFileBinPath = " << ws_filePath << endl;
    115. wcout << "WindowTitle = " << ws_tile << endl;
    116. printf("WindowClassName = %ws\n", szBuff);//控制台的输出类名
    117. printf("Press Enter to continue.");
    118. cin.get();
    119. }
    120. // 清理
    121. dw_addr_dwData = 0;
    122. h_mainWnd = NULL;
    123. ws_filePath = L"";
    124. ws_tile = L"";
    125. cout << endl;
    126. }
    127. if (VirtualFreeEx(hProcess, p_tbbutton, 0, MEM_RELEASE) == 0) {
    128. cout << "VirtualFreeEx failed:" << GetLastError() << endl;
    129. return FALSE;
    130. }
    131. if (CloseHandle(hProcess) == 0) {
    132. cout << "CloseHandle failed:" << GetLastError() << endl;
    133. return FALSE;
    134. }
    135. return TRUE;
    136. }
    137. int main()
    138. {
    139. // 解决控制台中文
    140. setlocale(LC_ALL, "chs");
    141. // 获取托盘句柄
    142. HWND h_tray = FindTrayWnd();
    143. HWND h_tray_fold = FindNotifyIconOverflowWindow();
    144. // 遍历托盘窗口
    145. if (EnumNotifyWindow(h_tray) == FALSE || EnumNotifyWindow(h_tray_fold) == FALSE) {
    146. cout << "EnumNotifyWindow false." << endl;
    147. }
    148. printf("Press any Key to CLOSE Console.");
    149. cin.get();
    150. return 0;
    151. }

    为了满足 Win 10 的需求,我曾对代码做了改进(以前写的有点丑)

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. int RepeatedHwndscout;
    8. HWND h_oldHwnd = NULL;
    9. HWND Lasterrorhwnd = NULL;
    10. // 判断 x64 系统
    11. BOOL Is64bitSystem()
    12. {
    13. SYSTEM_INFO si;
    14. GetNativeSystemInfo(&si);
    15. if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 ||
    16. si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
    17. return TRUE;
    18. else
    19. return FALSE;
    20. }
    21. // 获取托盘窗口句柄
    22. HWND FindTrayWnd()
    23. {
    24. HWND hWnd = NULL;
    25. hWnd = FindWindow(_T("Shell_TrayWnd"), NULL);
    26. hWnd = FindWindowEx(hWnd, NULL, _T("TrayNotifyWnd"), NULL);
    27. hWnd = FindWindowEx(hWnd, NULL, _T("SysPager"), NULL);
    28. hWnd = FindWindowEx(hWnd, NULL, _T("ToolbarWindow32"), NULL);
    29. return hWnd;
    30. }
    31. // 获取折叠托盘窗口句柄
    32. HWND FindNotifyIconOverflowWindow()
    33. {
    34. HWND hWnd = NULL;
    35. hWnd = FindWindow(_T("NotifyIconOverflowWindow"), NULL);
    36. hWnd = FindWindowEx(hWnd, NULL, _T("ToolbarWindow32"), NULL);
    37. return hWnd;
    38. }
    39. // 获取系统升级的通知区域句柄
    40. HWND FindSysUpdateNotifyWindow() {
    41. HWND hWnd = NULL;
    42. hWnd = FindWindow(_T("Shell_TrayWnd"), NULL);
    43. hWnd = FindWindowEx(hWnd, NULL, _T("TrayNotifyWnd"), NULL);
    44. hWnd = FindWindowEx(hWnd, NULL, _T("ToolbarWindow32"), NULL);
    45. return hWnd;
    46. }
    47. /*
    48. * 已知路径转换函数
    49. *
    50. * 例如:{F38BF404-1D43-42F2-9305-67DE0B28FC23} 表示 C:\Windows;
    51. * {F38BF404-1D43-42F2-9305-67DE0B28FC23}\explorer.exe 可以合并转换为 C:\Windows\explorer.exe
    52. * {F38BF404-1D43-42F2-9305-67DE0B28FC23} // SystemRoot:Windows Folder
    53. * {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7} // SystemRoot:Windows\\System32 Folder
    54. * {7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E} // SystemRoot:Program Files (x86) Folder
    55. * {6D809377-6AF0-444B-8957-A3773F02200E} // SystemRoot:Program Files Folder
    56. */
    57. HRESULT RestructureDataFilePath(const wchar_t* strGuid, wchar_t** strBinPathAffer) {
    58. GUID stGuid = { 0 };
    59. WCHAR* strBuffer = nullptr;
    60. size_t wcsBufferlen = 0;
    61. HRESULT str2sidreslt = CLSIDFromString((LPCOLESTR)strGuid, (LPCLSID)&stGuid);
    62. if (str2sidreslt == (HRESULT)NOERROR) {
    63. // 查询已知文件夹路径
    64. str2sidreslt = ::SHGetKnownFolderPath(stGuid, KF_FLAG_DONT_VERIFY, NULL, &strBuffer);
    65. if (SUCCEEDED(str2sidreslt)) {
    66. wcsBufferlen = wcslen(strBuffer) * sizeof(WCHAR) + sizeof(WCHAR);
    67. *strBinPathAffer = (WCHAR*)malloc(wcsBufferlen);
    68. memset(*strBinPathAffer, 0, wcsBufferlen);
    69. memcpy(*strBinPathAffer, strBuffer, wcsBufferlen);
    70. CoTaskMemFree(strBuffer);// 释放内存
    71. return NOERROR;
    72. }
    73. else {
    74. printf("SHGetKnownFolderPathFailed,errorCode = [%d]\n", GetLastError());
    75. return str2sidreslt;
    76. }
    77. }
    78. else
    79. return str2sidreslt;
    80. }
    81. // 遍历窗口
    82. BOOL EnumNotifyWindow(HWND hWnd)
    83. {
    84. // 获取托盘进程ID
    85. DWORD dwProcessId = 0;
    86. // 初始化
    87. DWORD dw_addr_dwData = 0;
    88. BYTE buff[1024] = { 0 };
    89. WCHAR* ws_filePath = nullptr, filepathsuffix[MAX_PATH] = { 0 };
    90. WCHAR* ws_tile = nullptr;
    91. WCHAR KnownfoldID[39] = { 0 };
    92. wchar_t* strBinPathAffer = nullptr;
    93. HWND h_mainWnd = NULL;
    94. TCHAR szWndClassName[256] = { 0 },
    95. toolBarTitle[256] = { 0 },
    96. toolBarClass[256] = { 0 };
    97. const char* delimiter = "\\";
    98. char filepath[256]{};
    99. char* szExeFile = nullptr;
    100. char* pBufferContext = nullptr;
    101. char szWndTitleName[1024] = { 0 };
    102. char shortHwnds[64] = { 0 };
    103. int i_data_offset = 12;
    104. int i_str_offset = 18;
    105. GetWindowThreadProcessId(hWnd, &dwProcessId);
    106. if (dwProcessId == 0) {
    107. printf("-------------------------------------------------------------------------------------\n");
    108. printf("GetWindowThreadProcessId failed: %d \tFrom hwnd: %I64X.\n", GetLastError(), (UINT64)hWnd);
    109. printf("-------------------------------------------------------------------------------------\n");
    110. Lasterrorhwnd = hWnd;
    111. return FALSE;
    112. }
    113. // 获取托盘进程句柄
    114. HANDLE hProcess = OpenProcess(
    115. PROCESS_VM_OPERATION | // 需要在进程的地址空间上执行操作
    116. PROCESS_VM_READ | // 需要使用 ReadProcessMemory 读取进程中的内存
    117. PROCESS_VM_WRITE, // 需要在使用 WriteProcessMemory 的进程中写入内存
    118. FALSE, // 子进程不继承句柄
    119. dwProcessId // 目标进程 PID
    120. );
    121. if (hProcess == nullptr) {
    122. printf("-------------------------------------------------------------------------------------\n");
    123. printf("OpenProcess failed: %d \tFrom hwnd: %I64X.\n", GetLastError(), (UINT64)hWnd);
    124. printf("-------------------------------------------------------------------------------------\n");
    125. Lasterrorhwnd = hWnd;
    126. return FALSE;
    127. }
    128. // 在进程虚拟空间中分配内存,用来接收 TBBUTTON 结构体指针
    129. LPVOID p_tbbutton = VirtualAllocEx(
    130. hProcess, // 目标进程句柄
    131. 0, // 内存起始地址(默认)
    132. 4096, // 内存大小
    133. MEM_COMMIT, // 内存类型(提交)
    134. PAGE_EXECUTE_READWRITE // 内存保护属性(可读可写可执行)
    135. );
    136. if (p_tbbutton == nullptr) {
    137. printf("VirtualAllocEx failed: %d.\n", GetLastError());
    138. Lasterrorhwnd = hWnd;
    139. return FALSE;
    140. }
    141. /*
    142. typedef struct _TBBUTTON {
    143. int iBitmap; // 索引
    144. int idCommand; // 与按钮关联的命令标识符
    145. BYTE fsState; // 按钮状态
    146. BYTE fsStyle; // 按钮风格
    147. #ifdef _WIN64
    148. BYTE bReserved[6]; // 对齐
    149. #elif defined(_WIN32)
    150. BYTE bReserved[2]; // 对齐
    151. #endif
    152. DWORD_PTR dwData; // 存放程序自定义数据
    153. INT_PTR iString; // 存放信息字符
    154. } TBBUTTON, NEAR* PTBBUTTON, *LPTBBUTTON;
    155. */
    156. // 判断 x64
    157. if (Is64bitSystem()) {
    158. i_data_offset += 4;
    159. i_str_offset += 6;
    160. }
    161. // 获取托盘图标个数
    162. int i_buttons = 0;
    163. i_buttons = (int)SendMessage(hWnd, TB_BUTTONCOUNT, 0, 0);
    164. if (i_buttons == 0) {
    165. printf("-------------------------------------------------------------------------------------\n");
    166. printf("TB_BUTTONCOUNT message failed: %d \tFrom hwnd: %I64X.\n", GetLastError(), (UINT64)hWnd);
    167. printf("-------------------------------------------------------------------------------------\n");
    168. Lasterrorhwnd = hWnd;
    169. return FALSE;
    170. }
    171. // 获取通知区域主窗口的标题和窗口类名称
    172. GetWindowTextW(hWnd, toolBarTitle, sizeof(toolBarTitle) / sizeof(TCHAR));
    173. GetClassNameW(hWnd, toolBarClass, sizeof(toolBarClass) / sizeof(TCHAR));
    174. // 输出标题 & 窗口类名称
    175. printf("=====================================================================================\n");
    176. printf("Tray_ToolBar WindowName = %ws | Tray_ToolBar ClassName = %ws\n", toolBarTitle, toolBarClass);
    177. printf("ChildTray PointsNumber = %d.\n\n", i_buttons);
    178. // 遍历通知区域图标信息
    179. for (int i = 0; i < i_buttons; i++) {
    180. // 获取 TBBUTTON 结构体指针
    181. if (!SendMessage(hWnd, TB_GETBUTTON, i, (LPARAM)p_tbbutton)) {
    182. printf("-------------------------------------------------------------------------------------\n");
    183. printf("TB_GETBUTTON message failed: %d \tFrom hwnd: %I64X.\n", GetLastError(), (UINT64)hWnd);
    184. printf("-------------------------------------------------------------------------------------\n");
    185. Lasterrorhwnd = hWnd;
    186. return FALSE;
    187. }
    188. // 读 TBBUTTON.dwData(附加信息)
    189. if (!ReadProcessMemory(hProcess, (LPVOID)((DWORD)p_tbbutton + i_data_offset), &dw_addr_dwData, 4, 0)) {
    190. printf("-------------------------------------------------------------------------------------\n");
    191. printf("ReadProcessMemory failed: %d \tFrom hwnd: %I64X.\n", GetLastError(), (UINT64)hWnd);
    192. printf("-------------------------------------------------------------------------------------\n");
    193. Lasterrorhwnd = hWnd;
    194. return FALSE;
    195. }
    196. // 读取结构体信息
    197. if (dw_addr_dwData) {
    198. if (!ReadProcessMemory(hProcess, (LPCVOID)dw_addr_dwData, buff, 1024, 0)) {
    199. printf("-------------------------------------------------------------------------------------\n");
    200. printf("ReadProcessMemory failed: %d \tFrom hwnd: %I64X.\n", GetLastError(), (UINT64)hWnd);
    201. printf("-------------------------------------------------------------------------------------\n");
    202. Lasterrorhwnd = hWnd;
    203. return FALSE;
    204. }
    205. h_mainWnd = (HWND)(*((DWORD*)buff));
    206. ws_filePath = (WCHAR*)buff + i_str_offset;
    207. ws_tile = (WCHAR*)buff + i_str_offset + MAX_PATH;
    208. /*
    209. * 排除重复记录的窗口
    210. */
    211. if (h_oldHwnd == h_mainWnd) {
    212. printf("Rank(Limited)=%d; HWND 0x%I64X: MultipleRegisted once.\n", i + 1, (UINT64)h_mainWnd);
    213. RepeatedHwndscout += 1;
    214. continue;
    215. }
    216. else {
    217. printf("----------------\n");
    218. printf("Tray Rank = %d: \n", i + 1);
    219. }
    220. printf("MainWindowHandle = 0x%I64X\n", (UINT64)h_mainWnd);
    221. sprintf_s(filepath, "%ws", ws_filePath);
    222. szExeFile = strtok_s(filepath, delimiter, &pBufferContext);
    223. while (szExeFile)
    224. {
    225. size_t len = strlen(szExeFile);
    226. if (szExeFile[len - 1] == 101 && szExeFile[len - 2] == 120 && szExeFile[len - 3] == 101) {
    227. printf("PatrilinealProcessName = %s\n", szExeFile);
    228. }
    229. szExeFile = strtok_s(NULL, delimiter, &pBufferContext);
    230. }
    231. /*
    232. *
    233. * 判断是否是系统已知文件路径,如果是就转换为可读路径
    234. *
    235. */
    236. // 初始化内存操作
    237. wmemset(KnownfoldID, 0, sizeof(KnownfoldID) / sizeof(wchar_t));
    238. wmemset(filepathsuffix, 0, sizeof(filepathsuffix) / sizeof(wchar_t));
    239. // GUID 字符串的特征定位操作,建议使用 C++ 的 std::string 操作
    240. if (ws_filePath[0] == L'{' && ws_filePath[37] == L'}' ) {
    241. for (int i = 0; i < 38; i++) {
    242. KnownfoldID[i] = ws_filePath[i];
    243. }
    244. for (int j = 38; j < wcslen(ws_filePath); j++) {
    245. filepathsuffix[j - 38] = ws_filePath[j];
    246. }
    247. // 查询已知路径字符串的 Win32 路径
    248. HRESULT lpresult = RestructureDataFilePath(KnownfoldID, &strBinPathAffer);
    249. printf("ExecuteFileBinPath = %ws%ws\n", strBinPathAffer, filepathsuffix);
    250. free(strBinPathAffer);
    251. }
    252. else {
    253. printf("ExecuteFileBinPath = %ws\n", ws_filePath);
    254. }
    255. if (!ws_tile[0]) {
    256. printf("WindowTitle = (None)\n");
    257. }
    258. else {
    259. bool bEnterFlag = false;
    260. sprintf_s(szWndTitleName, "%ws", ws_tile);
    261. // 查询并去除 szTip 字符串中的换行符号,
    262. // BUG:对中文处理可能存在问题,建议使用 C++
    263. for (int index = 1; index < strlen(szWndTitleName); index++) {
    264. if (szWndTitleName[index] == '\n') {
    265. // printf("Title have Enter at str[%d].\n", index);
    266. szWndTitleName[index] = ';';
    267. bEnterFlag = true;
    268. }
    269. }
    270. if (bEnterFlag) {
    271. printf("WindowTitle = %s \n", szWndTitleName);
    272. }
    273. else {
    274. wprintf(L"WindowTitle = %ws\n", ws_tile);
    275. }
    276. }
    277. }
    278. // 输出窗口类的名称字符串,如果不为空字符串的话
    279. if (h_mainWnd) {
    280. GetClassNameW(h_mainWnd, szWndClassName, sizeof(szWndClassName) / sizeof(TCHAR));// 函数调用
    281. printf("WindowClassName = %ws\n", szWndClassName);// 控制台的输出窗口类的名称
    282. }
    283. else {
    284. printf("WindowClassName = (None)\n");
    285. }
    286. // 判断窗口是否可见
    287. if (h_mainWnd != NULL && IsWindowVisible(h_mainWnd)) {
    288. printf("IsWindowVisible: True.\n");
    289. }
    290. else {
    291. printf("IsWindowVisible: False.\n");
    292. }
    293. // 获取窗口矩形的相关信息
    294. RECT rect = { 0,0,0,0 };
    295. if (h_mainWnd != NULL && !GetWindowRect(h_mainWnd, &rect)) {
    296. printf("Failed to Find Window Rect.ecode = %d\n", GetLastError());
    297. }
    298. else {
    299. int wid = rect.right - rect.left;
    300. int heit = rect.bottom - rect.top;
    301. if (!wid && !heit) {
    302. printf("Window rectangle size is Zero.\n");
    303. }
    304. else {
    305. printf("WindowRect: \n");
    306. printf(" left \t top \tright\tbottom\t\n");
    307. printf(" %d\t%d\t%d\t%d\t\n", rect.left,
    308. rect.top, rect.right, rect.bottom);
    309. }
    310. if (!rect.right && !rect.left && !rect.bottom && !rect.top) {
    311. printf("The four corners of window are all with Zero-Pos.\n");
    312. }
    313. else {
    314. printf("Position: \n");
    315. printf("\t(%d,%d) - (%d,%d)\n", rect.left,
    316. rect.top, rect.right, rect.bottom);
    317. printf("Rect: %d x %d.\n", wid, heit);
    318. }
    319. }
    320. // 记录遍历的窗口句柄
    321. h_oldHwnd = h_mainWnd;
    322. // 清理内存
    323. dw_addr_dwData = 0;
    324. h_mainWnd = NULL;
    325. ws_filePath = 0;
    326. ws_tile = NULL;
    327. filepath[0] = '\0';
    328. szWndClassName[0] = '\0';
    329. toolBarTitle[0] = '\0';
    330. toolBarClass[0] = '\0';
    331. printf("\n");
    332. }
    333. if (VirtualFreeEx(hProcess, p_tbbutton, 0, MEM_RELEASE) == 0) {
    334. printf("-------------------------------------------------------------------------------------\n");
    335. printf("VirtualFreeEx failed: %d \tFrom hwnd: %I64X\n", GetLastError(), (UINT64)hWnd);
    336. printf("-------------------------------------------------------------------------------------\n");
    337. Lasterrorhwnd = hWnd;
    338. return FALSE;
    339. }
    340. if (CloseHandle(hProcess) == 0) {
    341. printf("-------------------------------------------------------------------------------------\n");
    342. printf("CloseHandle failed: %d \tFrom hwnd: %I64X\n", GetLastError(), (UINT64)hWnd);
    343. printf("-------------------------------------------------------------------------------------\n");
    344. Lasterrorhwnd = hWnd;
    345. return FALSE;
    346. }
    347. if (RepeatedHwndscout != 0) {
    348. printf("Skipped %d Windows.\n", RepeatedHwndscout);
    349. printf("The number of Tray Notification Windows under this Notifi-hWnd should actually be %d, not %d.\n",
    350. i_buttons - RepeatedHwndscout, i_buttons);
    351. }
    352. return TRUE;
    353. }
    354. int main()
    355. {
    356. system("cls");
    357. // 控制台中文支持
    358. setlocale(LC_ALL, ".utf8");
    359. // 获取通知区域窗口的句柄
    360. HWND h_tray = FindTrayWnd();
    361. HWND h_tray_fold = FindNotifyIconOverflowWindow();
    362. HWND h_sys_up = FindSysUpdateNotifyWindow();
    363. // 枚举各个窗口通知区域图标信息
    364. bool t1 = EnumNotifyWindow(h_tray);
    365. bool t2 = EnumNotifyWindow(h_tray_fold);
    366. bool t3 = EnumNotifyWindow(h_sys_up);
    367. // 判断遍历结果
    368. if (t1 == false || t2 == false || t3 == false) {
    369. if (Lasterrorhwnd == h_sys_up) {
    370. printf("===============================================================================================\n");
    371. printf("\t\t\tUpdateNotifyWindow - System, has none Icon now.\t\t\t\n");
    372. printf("===============================================================================================\n");
    373. }
    374. else {
    375. printf("EnumNotifyWindow false.ObjWindowHandle = %I64X.\n", (UINT64)Lasterrorhwnd);
    376. }
    377. }
    378. printf("Press any key to CLOSE the console.");
    379. ::getchar();
    380. return 0;
    381. }

    代码修复了已知路径未将 GUID 或 UUID 转换为完整路径,Taskmgr 重复窗口记录、窗口是否可见等问题。运行效果如下:

    Win10 测试运行结果截图

    1.3 技术的适用范围

    TBBUTTON 方法自 Win11 22H2 Build 22621.1344 和 22621.1413 (正式) 起不再有效。微软修复了加载系统托盘图标相关的问题,因为该问题可能会导致 explorer.exe 卡顿甚至崩溃。就是这一次修复其实微软顺便砍掉了很多冗余的东西,比如像 shell:::{05d7b0f4-2121-4eff-bf6b-ed3f69b894d9} 指向的旧版的通知区域图标管理页面,一些注册表设置等。

    现在你只能看到空白的通知区域图标管理页面

    在这种情况下,TB_BUTTONCOUNT 应该会失败,并返回 0,并且最近一次错误是 “拒绝访问”,这也是国内、国外论坛在讨论的重点。

    但是,资源管理器的图标管理是否存在其他接口,图标的数据是怎么组织的?首先,图标数据肯定不是一直放在内存中的,这不合理,因为伴随着重启,设置里面依然记录着已知的图标信息,即使它们曾经启用过而现在它们的进程并未启动。下文我们将逐个讨论并揭开 explorer 的神秘的面纱。

    2 深度分析系统托盘图标信息

    系统通知区域图标的创建需要依赖一些接口函数,通过分析这些接口函数,我们就能够对资源管理器的通知栏图标有更加多维的理解。

    2.1 分析 Shell_NotifyIcon 函数参数

    托盘图标目前只能通过微软提供的 Shell_NotifyIcon 函数来管理,那么我们研究的切入点也就是这个函数。

     Shell_NotifyIcon 函数的声明和参数的部分解释如下:

    MSDN 称该函数是只将消息发送到任务栏的通知区域的一个函数。这说明了很可能该函数不是实现图标的全部功能,而是将特定的窗口消息发送给 explorer 进程。

    函数声明:

    BOOL Shell_NotifyIconW(
            DWORD                          dwMessage,
            PNOTIFYICONDATAW   lpData
    );

    一个 DWORD 数值,该值指定要由此函数执行的操作。 可以具有下表列出的任意数值之一:

    dwMessage 参数功能
    dwMessage 支持的数值表示的功能

    NIM_ADD

    (0x00000000)

    将图标添加到状态区域。

    NIM_MODIFY

    (0x00000001)

    修改状态区域中的图标。 

    NIM_DELETE

    (0x00000002)

    从状态区域中删除图标。

    NIM_SETFOCUS

    (0x00000003)

    将焦点返回到任务栏通知区域。

    NIM_SETVERSION

    (0x00000004)

    指示通知区域按照 lpdata 所指向结构的 uVersion 成员中指定的版本号的行为。 版本号指定可识别的成员。

    第二个参数 lpData 为指向 NOTIFYICONDATA 结构的指针。 结构的内容取决于 dwMessage 的值。它可以定义要添加到通知区域的图标、使该图标显示通知,或标识要修改或删除的图标。

    NOTIFYICONDATA 结构体有 Unicode 和 ANSI 别名表示的不同版本。其次, MSDN 上给出的是简化版,实际上和 SDK 中的定义不完全一致。下面摘录的是 MSDN 的简化版:

    1. typedef struct _NOTIFYICONDATAW {
    2. DWORD cbSize;
    3. HWND hWnd;
    4. UINT uID;
    5. UINT uFlags;
    6. UINT uCallbackMessage;
    7. HICON hIcon;
    8. #if ...
    9. WCHAR szTip[64];
    10. #else
    11. WCHAR szTip[128];
    12. #endif
    13. DWORD dwState;
    14. DWORD dwStateMask;
    15. WCHAR szInfo[256];
    16. union {
    17. UINT uTimeout;
    18. UINT uVersion;
    19. } DUMMYUNIONNAME;
    20. WCHAR szInfoTitle[64];
    21. DWORD dwInfoFlags;
    22. GUID guidItem;
    23. HICON hBalloonIcon;
    24. } NOTIFYICONDATAW, *PNOTIFYICONDATAW;

    关于各个成员的解释我就不过多介绍了,可以直接看 MSDN 的文档:

    NOTIFYICONDATAW (shellapi.h) - Win32 apps | Microsoft Learn

    2.2 分析 Shell_NotifyIcon 函数的内部细节

    下面我们需要对 Shell_NotifyIcon 函数做进一步的分析。从 NT5.0 开始,Shell_NotifyIcon 函数一直是 Shell32.dll 的导出函数。

    首先,我们通过 IDA Pro 对该函数进行静态分析。该函数查找了 Shell_TrayWnd 窗口的句柄,并且如果该窗口不存在(比如资源管理器未启动),则立即返回失败信息:

    判断任务栏是否已经创建

     Shell_TrayWnd 窗口相信对很多人来说并不陌生,它是任务栏父窗口,在以前的 SendMessage 方法中就涉及到从它的子窗口中获取通知区域窗口句柄的过程。下图展示了 Win 11 的任务栏窗口层次结构:

    任务栏窗口层次结构

    网上的代码大多数情况下忽略了 TrayNotifyWnd 下的“系统升级通知窗口”的图标,我将这个区域称为临时区域,是因为它默认情况下窗口大小为 0,在 Win 7 到 Win11 更新之前的版本上,该区域为程序刚刚创建系统托盘图标时候,微软会将该图标显示在临时通知区域(Win11 更新过后似乎不会自动放到这个区域),它位于系统通知区域和任务栏溢出区域角标之间。具体如下图所示:

    Win10 系统通知区域分块

    最左侧的是溢出栏角标,中间新增的就是临时通知栏,右侧是系统常驻通知区域。系统会将新创建的图标放在这个可变大小的临时通知区域中,时间长达 1 分钟,随后根据配置文件,将该图标从临时区域移动到溢出通知区域或者常驻通知区域。

    这也就解释了我在 1.2 的改进版代码中增加了对系统升级通知区域(临时通知区域)的解析的原因:

    1. // 获取系统升级的通知区域句柄
    2. HWND FindSysUpdateNotifyWindow() {
    3. HWND hWnd = NULL;
    4. hWnd = FindWindow(_T("Shell_TrayWnd"), NULL);
    5. hWnd = FindWindowEx(hWnd, NULL, _T("TrayNotifyWnd"), NULL);
    6. hWnd = FindWindowEx(hWnd, NULL, _T("ToolbarWindow32"), NULL);
    7. return hWnd;
    8. }

    当然,上面谈的这些只适用于 10.0.22621.1413 之前的发布版本系统,对于最新的系统,已经删除了窗口对 TBBUTTON 消息处理的支持。下面我们继续分析 Shell_NotifyIcon 函数。

    由于从 NT 6 (Vista) 以来进行了一些功能性更改,该函数支持的结构体大小不唯一,产生了不同版本号的结构体。所以接下来函数对结构体参数的大小进行了判断,以便于区分版本。

    通过 cbSize 成员解析结构体大小,并对 dwMessage,uFlags 等进行参数校验

    这一部分其实 MSDN 文档中有记录。

    文档中写道:必须使用结构的大小初始化结构。如果使用当前定义的结构的大小,则应用程序可能不会使用早期版本的 Shell32.dll 运行,这需要更小的结构。

    通过适当设置 NOTIFYICONDATA 结构的大小,可以保持应用程序与所有 Shell32.dll 版本的兼容性,同时仍使用当前头文件。 在初始化结构之前,使用 DllGetVersion 确定系统上安装的 Shell32.dll 版本,并使用以下值之一初始化 cbSize :

    Shell32.dll 版本cbSize
    6.0.6 或更高版本 (Windows Vista 及更高版本)sizeof (NOTIFYICONDATA)
    6.0 (Windows XP)NOTIFYICONDATA_V3_SIZE
    5.0 (Windows 2000)NOTIFYICONDATA_V2_SIZE
    低于 5.0 的版本NOTIFYICONDATA_V1_SIZE

    可以看出在Vista之前使用常量定义结构体的大小,在 Vista 之后直接定义 NTDDI_VERSION 宏并使用结构的大小 sizeof (NOTIFYICONDATA) 即可。

    随后,将结构体数据拷贝到新分配的内存上(参数重组,这里的 IDA 分析有部分问题):

    准备要发送的数据

    对字符串参数的处理(这一部分没有仔细去分析):

    字符串参数处理

    随后,开始解析 dwMessage 参数,因为该参数决定了要对通知区域的具体操作:

    解析 dwMessage 参数

    如果 dwMessage == NIM_SETFOCUS 则会调用 AllowSetForegroundWindow 允许 explorer 设置前台窗口。

    在 dwMessage 不是 NIM_SETFOCUS 的情况下,则会首先检查调用方进程的消息线程是否注册了 TaskbarCreated 这个系统保留的消息字符串,该消息在任务栏创建时候会由 explorer 向全部的顶级窗口广播,用于在任务栏重建时候允许调用方重新请求创建通知区域图标。

    如果 dwMessage 是 NIM_MODIFY 则跳转到 LABEL_22 处,不是则跳转到 LABEL_23 处。如果 dwMessage 是 NIM_ADD 则继续向下执行而不跳转。从中可以看出,这里可以解释为下面的伪代码结构:

    1. switch(dwMessage)
    2. {
    3. case NIM_ADD:
    4. {
    5. // 添加通知区域图标
    6. }
    7. break;
    8. case NIM_MODIFY:
    9. {
    10. // 修改通知区域图标信息
    11. }
    12. break;
    13. case NIM_DELETE:
    14. {
    15. // 删除通知区域图标
    16. }
    17. break;
    18. case NIM_SETFOCUS:
    19. {
    20. // 返还任务栏焦点
    21. }
    22. break;
    23. case NIM_SETVERSION:
    24. {
    25. // 设置通知版本
    26. }
    27. break;
    28. default:
    29. // 默认错误处理
    30. break;
    31. }

    如果是 NIM_ADD 则会首先执行下面的过程:

     NIM_ADD 首先执行图中的过程

    通过对 lpData->hWnd 也就是图标绑定的窗口句柄调用 GetWindowThreadProcessId 来获取对应的进程 ID。再使用 OpenProcess 以 PROCESS_QUERY_LIMITED_INFORMATION 权限获取进程的访问句柄,因为后面调用 QueryFullProcessImageNameW 获取进程完整的路径必须指定  PROCESS_QUERY_LIMITED_INFORMATION 权限或者 PROCESS_QUERY_INFORMATION 权限的访问句柄。而像 SYSTEM 进程等完整性较高的进程,普通进程可能无法获取到 PROCESS_QUERY_INFORMATION 访问权限,只能获取到 PROCESS_QUERY_LIMITED_INFORMATION 权限。所以理所当然这里用的是受限访问权限。

    当然这个过程是可能失败的,一方面是窗口句柄可能无效,另一方面是进程的访问和路径获取可能失败。如果路径访问失败,则错误代码是 0x80004005(LRESULT 错误代码),也就是 E_FAIL 未知故障的意思,这个错误代码是十分常见的。

    句柄无效的处理

    那么接下来,你肯定会想到,万一是 hWnd 指向无效窗口导致访问路径失败呢?那我们也不一定需要抛出失败啊,只需要尝试默认窗口即可了啊?该函数确实也是这么做的:

    检查路径的替代品

    此时,会尝试通过 GetCurrentProcessId 获取调用方进程的 PID,随后通过 SHExePathFromPid 函数来获取调用方进程的完整 Win32 路径。这个函数非常有意思,其实和刚刚的流程差不多,只不过进程 PID 不是 hWnd 指向的窗口的进程 PID,而是调用方进程的 PID。

    获取完整可执行路经的方法

    随后对于两种方式获取的路径都需要校验,GetLongPathNameW 判断是否始终为长路径,PathIsNetworkPathW 判断路径中是否不包含网络路径。这两部分就是确保路径是完整的本地路径。

    下面就是一个有意思的环节了:

    转换部分 KNOWNFOLDERID 前缀

    这里将系统中部分已知文件夹的 KNOWNFOLDERID (GUID) 通过 XMM 寄存器传输到全局变量上。

    接下来,通过 SHGetKnownFolderPath 获取 GUID 对应的已知文件夹默认路径,通过 PathCommonPrefixW 的返回值判断当前程序文件路径和已知文件夹路径是否存在公共前缀,并指示公共前缀的字符长度(v45),通过 lstrlenW 判断已知路径长度是否等于公共前缀长度来确定当前文件路径是否是位于已知文件夹路径下。

    如果满足路径在已知文件夹路径下,则用已知文件夹路径的 GUID 字符串(StringFromGUID2 获取),替代实际的文件夹路径前缀。

    判断文件路径前缀是否在 GUID 表中

    这也是为什么上文在 1.2 的改进代码中,我增加了已知路径 GUID 转换函数(GUIDStringToPathPrefix)的原因:

    1. /*
    2. * 已知路径转换函数
    3. *
    4. * 例如:{F38BF404-1D43-42F2-9305-67DE0B28FC23} 表示 C:\Windows;
    5. * {F38BF404-1D43-42F2-9305-67DE0B28FC23}\explorer.exe 将被转换为 C:\Windows\explorer.exe
    6. * {F38BF404-1D43-42F2-9305-67DE0B28FC23} // SystemRoot:Windows Folder
    7. * {1AC14E77-02E7-4E5D-B744-2EB1AE5198B7} // SystemRoot:Windows\\System32 Folder
    8. * {7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E} // SystemRoot:Program Files (x86) Folder
    9. * {6D809377-6AF0-444B-8957-A3773F02200E} // SystemRoot:Program Files Folder
    10. */
    11. HRESULT RestructureDataFilePath(const wchar_t* strGuid, wchar_t** strBinPathAffer) {
    12. GUID stGuid = { 0 };
    13. WCHAR* strBuffer = nullptr;
    14. size_t wcsBufferlen = 0;
    15. HRESULT str2sidreslt = CLSIDFromString((LPCOLESTR)strGuid, (LPCLSID)&stGuid);
    16. if (str2sidreslt == (HRESULT)NOERROR) {
    17. // 查询已知文件夹路径
    18. str2sidreslt = ::SHGetKnownFolderPath(stGuid, KF_FLAG_DONT_VERIFY, NULL, &strBuffer);
    19. if (SUCCEEDED(str2sidreslt)) {
    20. wcsBufferlen = wcslen(strBuffer) * sizeof(WCHAR) + sizeof(WCHAR);
    21. *strBinPathAffer = (WCHAR*)malloc(wcsBufferlen);
    22. memset(*strBinPathAffer, 0, wcsBufferlen);
    23. memcpy(*strBinPathAffer, strBuffer, wcsBufferlen);
    24. CoTaskMemFree(strBuffer);// 释放内存
    25. return NOERROR;
    26. }
    27. else {
    28. printf("SHGetKnownFolderPathFailed,errorCode = [%d]\n", GetLastError());
    29. return str2sidreslt;
    30. }
    31. }
    32. else
    33. return str2sidreslt;
    34. }

    上面的代码是我去年早些时候编写的。现已经改进并整合到在 4.1 节的工具代码中,部分内容如下:

    1. /*
    2. * 已知路径转换函数
    3. *
    4. * 参数:LPCWSTR szKnownPath 包含 GUID 前缀的完整路径
    5. * PWSTR szWin32FilePath 返回 Win32 完整路径
    6. *
    7. * ********************************************************************************************
    8. * 备注:
    9. *
    10. * {F38BF404-1D43-42F2-9305-67DE0B28FC23} 表示 C:\Windows
    11. * {F38BF404-1D43-42F2-9305-67DE0B28FC23}\explorer.exe 将被转换为 C:\Windows\explorer.exe
    12. *
    13. * SystemRoot = "{F38BF404-1D43-42F2-9305-67DE0B28FC23}";//SystemRoot:Windows Folder
    14. * System32 = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}";//SystemRoot:Windows\\System32 Folder
    15. * Program86 = "{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}";//SystemRoot:Program Files (x86) Folder
    16. * Program = "{6D809377-6AF0-444B-8957-A3773F02200E}";//SystemRoot:Program Files Folder
    17. *
    18. * ********************************************************************************************
    19. */
    20. HRESULT FilePathFromKnownPrefix(
    21. LPCWSTR szKnownPath,
    22. PWSTR* szWin32FilePath
    23. )
    24. {
    25. GUID stGuid = { 0 };
    26. PWSTR strPathPrefix = nullptr;
    27. PWSTR strWin32Path = nullptr;
    28. HRESULT str2GuidReslt = E_FAIL;
    29. std::wstring wsKnownPath;
    30. size_t nPos = std::string::npos;
    31. size_t nPrefix = 0,
    32. nKnownPath = 0,
    33. nWin32Path = 0,
    34. wsWin32PathLen = 0;
    35. int nCoResponse = -1;
    36. if (szKnownPath == nullptr)
    37. {
    38. SetLastError(ERROR_INVALID_PARAMETER);
    39. return str2GuidReslt;
    40. }
    41. if (szKnownPath[0] == L'\0')
    42. {
    43. SetLastError(ERROR_INVALID_PARAMETER);
    44. return str2GuidReslt;
    45. }
    46. wsKnownPath = szKnownPath;
    47. nPos = wsKnownPath.find_first_of(L'\\');
    48. if (nPos != 0x26u) // GUID String 长度为 38 字符
    49. {
    50. SetLastError(ERROR_PATH_NOT_FOUND);
    51. return str2GuidReslt;
    52. }
    53. wsKnownPath.resize(0x26u);
    54. SetLastError(0);
    55. str2GuidReslt = CLSIDFromString((LPCOLESTR)wsKnownPath.c_str(), (LPCLSID)&stGuid);
    56. if (str2GuidReslt == (HRESULT)NOERROR) {
    57. //printf("The CLSID was obtained successfully.\n");
    58. str2GuidReslt = SHGetKnownFolderPath(stGuid, KF_FLAG_DONT_VERIFY, NULL, &strPathPrefix);
    59. if (SUCCEEDED(str2GuidReslt) && strPathPrefix != nullptr)
    60. {
    61. nPrefix = wcslen_s(strPathPrefix, 0x800u);
    62. nKnownPath = wcslen_s(szKnownPath, 0x800u);
    63. if (nPrefix == 0 || nKnownPath == 0)
    64. {
    65. std::wcerr << L"Get string length faild." << std::endl;
    66. CoTaskMemFree(strPathPrefix);// 释放内存
    67. return E_FAIL;
    68. }
    69. nWin32Path = nKnownPath - 0x26u + nPrefix + 1;
    70. // 计算需要分配的缓冲区字节数
    71. if (SizeTMult(nWin32Path, sizeof(wchar_t), &wsWin32PathLen) != S_OK) {
    72. // 乘法溢出,处理错误
    73. std::wcerr << L"Multiplication overflow occurred." << std::endl;
    74. CoTaskMemFree(strPathPrefix);// 释放内存
    75. return E_FAIL;
    76. }
    77. strWin32Path = (PWSTR)CoTaskMemAlloc(wsWin32PathLen);
    78. if (strWin32Path == nullptr)
    79. {
    80. CoTaskMemFree(strPathPrefix);// 释放内存
    81. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
    82. return E_FAIL;
    83. }
    84. nCoResponse = CoCreateSuffixFullPath(strWin32Path,
    85. nWin32Path, L"%s%s", strPathPrefix, &szKnownPath[0x26]);
    86. if (nCoResponse && nCoResponse == nWin32Path)
    87. {
    88. *szWin32FilePath = strWin32Path;
    89. CoTaskMemFree(strPathPrefix);// 释放内存
    90. return NOERROR;
    91. }
    92. CoTaskMemFree(strPathPrefix);// 释放内存
    93. return E_FAIL;
    94. }
    95. std::cerr << "SHGetKnownFolderPath Failed,errorCode = "
    96. << GetLastError() << std::endl;
    97. return str2GuidReslt;
    98. }
    99. std::cerr << "CLSIDFromString Failed,errorCode = "
    100. << GetLastError() << std::endl;
    101. return str2GuidReslt;
    102. }
    103. int CoCreateSuffixFullPath(
    104. wchar_t* wsBuffer,
    105. size_t wsCount,
    106. const wchar_t* wsFormat, ...
    107. )
    108. {
    109. if (wsBuffer == nullptr) return -1;
    110. int nWriteCount = 0;
    111. // hold the variable argument
    112. va_list argsList = nullptr;
    113. // A function that invokes va_start
    114. // shall also invoke va_end before it returns.
    115. va_start(argsList, wsFormat);
    116. nWriteCount = vswprintf_s(wsBuffer, wsCount, wsFormat, argsList);
    117. va_end(argsList);
    118. return ++nWriteCount;
    119. }
    120. // wcslen 安全版本
    121. size_t wcslen_s(
    122. const wchar_t* str, size_t ccmaxlen)
    123. {
    124. size_t length = 0;
    125. if (ccmaxlen > 0x5000)
    126. ccmaxlen = 0x5000; // 20480 字节,路径长度应该远小于该值
    127. __try {
    128. while (length < ccmaxlen && str[length] != L'\0') {
    129. ++length;
    130. }
    131. // 说明发生越界访问或者超出限制
    132. if (length == ccmaxlen)
    133. {
    134. std::cerr << "Trigger limit: The buffer exceeds the limit of characters." << std::endl;
    135. return 0;
    136. }
    137. }
    138. __except (EXCEPTION_EXECUTE_HANDLER) {
    139. // 捕获并处理访问无效指针引发的异常
    140. std::cerr << "Access violation: Attempted to read from null pointer." << std::endl;
    141. return 0;
    142. }
    143. return length;
    144. }
    145. errno_t __fastcall memset_s(void* v, rsize_t smax, int c, rsize_t n) {
    146. if (v == NULL) return EINVAL;
    147. if (smax > RSIZE_MAX) return EINVAL;
    148. if (n > smax) return EINVAL;
    149. volatile unsigned char* p = (volatile unsigned char*)v;
    150. while (smax-- && n--) {
    151. *p++ = c;
    152. }
    153. return 0;
    154. }

    当 dwMessage 为 NIM_MODIFY 和 NIM_DELETE 时,过程如下:

    dwMessage 为 NIM_MODIFY 和 NIM_DELETE 的处理

    NIM_MODIFY 过程检查 uFlags 参数是否包含 NIF_MESSAGE 标志。如果包含则说明 lpData->uCallbackMessage 参数有效,该参数是要发送到 hWnd 窗口的用户自定义消息。此时会检查 lpData->hWnd 是否不为空,如果不为空则会调用 ChangeWindowMessageFilterEx 并指定 MSGFLT_ALLOW 允许 uCallbackMessage 消息通过 UIPI ,取消 UIPI 的限制。UIPI 是 Vista 开始引入的一种消息安全机制,限制低完整级别进程向高完整级别进程发送窗口/线程消息。完成修改后,进入 LABEL_32,再次利用相同函数取消对 TaskbarCreated 字符串命名的消息的限制。随后向下执行 LABEL_24。

    如果 dwMessage 为 NIM_DELETE ,则首先检查 uFlags 是否不包含 NIF_MESSAGE 标志,如果不包含,则直接执行 LABEL_24;否则,会检查  lpData->hWnd 是否为空,如果为空,则直接执行 LABEL_24;否则,禁止 uCallbackMessage 消息通过 UIPI,恢复 UIPI 限制。这也很好理解,因为 NIM_DELETE 表明将要删除图标,那么此时 hWnd 肯定不需要再接收消息了。

    我们来看一下 LABEL_24,这是整个调用过程中最重要的一个部分。

    SendMessageTimeout 函数发送消息

    这个部分主要调用了 SendMessageTimeout 函数向最初查找的 Shell_TrayWnd 窗口发送了 0x4a 这个特定的消息,这个消息是什么呢?

    通过查阅 MSDN 文档,我们了解到它是 WM_COPYDATA 消息。分析到这里,其实我们已经明显明白 Shell_NotifyIcon 其实只是消息发送接口,而真正的处理在 explorer 的 Shell_TrayWnd 窗口中。但是这一部分也是最难理解的,下面我将对该消息发送过程进行详细的解释。

    2.3 分析 WM_COPYDATA 消息

    其实早在 2007 年左右,就有工程师逆向分析过资源管理器,在 Geoff Chappell 的个人笔记主页上就有相关的记录。

    下文是摘选自

    [WM_COPYDATA for Taskbar Interface (geoffchappell.com)]

    www.geoffchappell.com/studies/windows/shell/shell32/api/shlnot/copydata.htm?tx=65

    的一段文本介绍,我做了一些翻译:

    任务栏界面的 WM_COPYDATA 消息

    每一个 SHAppBarMessage、Shell_NotifyIcon、 SHEnableServiceObject 和 SHLoadInProc 函数都只不过是一个用于将数据发送到任务栏窗口的接口(在少数情况下用于获取返回数据)。这些数据的打包及其传输方法是(未被文档化的)实现细节,他们的各个功能之间有很多共同点。

    [正文部分]

    调用方进程通常不是实现任务栏通知窗口的进程。在另一个进程中传递数据到一个窗口过程的标准方法是使用 WM_COPYDATA 消息。WM_COPYDATA 消息提供了在 COPYDATASTRUCT 结构的 dwData 成员中传递一个 DWORD 值或者在 lpData 和 cbData 成员描述的缓冲区中传递任意数量的 DWORD 值的方法。SHELL32 同时支持这两种传递模式。下表列出的 DWORD 值用于标识缓冲区中传递的数据用于调用哪个函数:

    0SHAppBarMessage
    1Shell_NotifyIcon
    2SHEnableServiceObject 或者 SHLoadInProc

    1. 传递 SHAppBarMessage 函数调用的参数的缓冲区布局为:

    偏移大小备注
    0x000x28 字节APPBARDATA 结构的扩展,cbSize 设置为 0x28, lParam 符号扩展为QWORD 类型
    0x28DWORD对应于 dwMessage 参数
    0x2CDWORD位于共享内存中 APPBARDATA 扩展结构的副本的句柄,否则为 NULL
    0x30DWORD调用方进程 ID
    0x340x04 字节该字段尚未使用,假定是为 QWORD 填充的对齐字节

    共享内存和进程 ID 的关键在于,对于 dwMessage 的某些值,SHAppBarMessage 函数需要返回 APPBARDATA 结构成员中的信息。然而,WM_COPYDATA 消息的机制只将数据从源复制到任务栏窗口,而不提供回写的方法。SHELL32 给出的解决方案是:在需要的情况下,无论如何在缓冲区中传递的 APPBARDATA 扩展结构也被复制到共享内存中,并且访问该共享内存的方法也在缓冲区中传递。

    2. 对于 Shell_NotifyIcon 函数,其缓冲区的数据结构如下表所示。在 explorer.exe 的符号文件中,微软为这个未记录的结构发布了一个名称:TRAYNOTIFYDATAW。

    偏移大小备注
    0x00DWORD该值写为:0x34753423,explorer 通过该签名确定调用方不是普通的 WM_COPYDATA
    0x04DWORDdwMessage 参数
    0x08

    0x03B8 

    字节 

    表示当前缓冲区布局中的 NOTIFYICONDATAW 结构,该结构在 lpData 的指向堆栈上构造

    3. SHEnableServiceObject 和 SHLoadInProc 函数缩减为一个由标识符区分的操作。缓冲区布局如下:

    偏移大小备注
    0x000x10 字节类型为 CLSID。该值由 rclsid 参数指定。
    0x10DWORD0x01 为 SHLoadInProc
    0x02 为 SHEnableServiceObject 如果 fEnable 参数为 FALSE
    0x03 为 SHEnableServiceObject 如果 fEnable 参数为 非零值

    事实上,现今的 dwData 成员已经不止 0,1,2 三种 ID 了,在我的测试过程中就发现了超过 2 的 ID 号。


    看完上面的笔记,大家可能依然处于懵懂的状态,下面我将分享我的分析理解心得:

    通过 MSDN 文档并结合 IDA 的伪代码,我们知道 SendMessageTimeoutW 在被 Shell_NotifyIcon 函数调用时候,参数分别为:

    参数 1:Shell_TrayWnd 窗口句柄(hWnd);

    参数 2:WM_COPYDATA (0x4A) 消息(uMsg);

    参数 3:调用方的窗口句柄(wParam);

    参数 4:COPYDATASTRUCT 结构体(lParam);

    参数 5:指定 SendMessageTimeoutW 发送消息方式的标识符,该值为 0xB,经过查表知该标志位由 SMTO_BLOCK | SMTO_ABORTIFHUNG | SMTO_NOTIMEOUTIFNOTHUNG 组成;

    参数 6:以毫秒间隔计的等待超时时间,参数值为 0x1B58,表示 7 秒;

    参数 7:消息返回状态,dwResult 是额外参数,表示消息处理的结果。

    为了进一步理解这里 IDA 错误解析的部分参数构造,我们采用 WinDbg 调试分析该函数。

    我首先准备了一个测试程序,该程序调用 Shell_NotifyIcon 并显示一个提示信息,代码如下。

    1. #include
    2. #include
    3. #include
    4. // 系统托盘的自定义消息
    5. #define WM_IAWENTRAY WM_USER + 0x5
    6. // 定义全局变量
    7. NOTIFYICONDATAW lpNotifyData = { 0 };
    8. void SetConsoleCodePageToUTF8() { // Utf-8 为了兼容中文
    9. _wsetlocale(LC_ALL, L".UTF8");
    10. }
    11. int main()
    12. {
    13. SetConsoleCodePageToUTF8();
    14. // 初始化 NOTIFYICONDATA 结构
    15. lpNotifyData.cbSize = (DWORD)sizeof(NOTIFYICONDATAW);
    16. lpNotifyData.hWnd = GetConsoleWindow();
    17. lpNotifyData.uID = 0x5;
    18. lpNotifyData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO;
    19. lpNotifyData.uCallbackMessage = WM_IAWENTRAY;
    20. lpNotifyData.hIcon = LoadIconW(NULL, IDI_APPLICATION);
    21. wcscpy_s(lpNotifyData.szTip, L"通知栏图标测试程序");
    22. wcscpy_s(lpNotifyData.szInfo, L"提示窗口内容");
    23. wcscpy_s(lpNotifyData.szInfoTitle, L"提示窗口标题");
    24. lpNotifyData.dwInfoFlags = NIIF_INFO;
    25. lpNotifyData.uTimeout = 5000;
    26. Shell_NotifyIconW(NIM_ADD, &lpNotifyData); // 在托盘区添加图标
    27. getchar();
    28. Shell_NotifyIconW(NIM_DELETE, &lpNotifyData); // 删除图标
    29. return 0;
    30. }

    运行时候的效果如图所示:

    通知区域的气泡提示消息框

    用 WinDbg 调试测试程序并设置 USER32!SendMessageTimeoutW 断点。随后让测试程序(调用 Shell_NotifyIcon 函数)运行起来并触发断点。

    我们查看此时的寄存器,以便于获取前四个参数的值:

    Breakpoint 0 hit

    USER32!SendMessageTimeoutW:

    00007ffc`be1f53a0        4053        push rbx

    0:000> r

    rax=000000f4d95ee338        rbx=00000000000000cf        rcx=00000000000100fc

    rdx=000000000000004a        rsi=0000000000000000        rdi=00007ff616d45630

    rip=00007ffcbe1f53a0        rsp=000000f4d95ee2b8         rbp=000000f4d95ee3c0

    r8=0000000000050e7c         r9=000000f4d95ee308         r10=0000000000000000

    r11=0000000000000246         r12=0000000000000000         r13=00000000000100fc

    r14=0000000000000005         r15=0000000000000000         

    iopl=0                 nv up ei pl zr na po nc

    cs=0033         ss=002b         ds=002b         es=002b        fs=0053         gs=002b

    efl=00000246

    USER32!SendMessageTimeoutW:

    00007ffc`be1f53a0        4053        push rbx

    我们知道,x64 的前 4 个参数是在寄存器上的,分别对应:

    • rcx = 00000000000100fc  == > HWND hTrayWnd
    • rdx = 000000000000004a  == > UINT Msg
    • r8   = 0000000000050e7c  == > HWND hMainWnd
    • r9   = 000000f4d95ee308  == > PCOPYDATASTRUCT
    • r8 表明了调用方窗口,r9 寄存器就是我们要找的数据,是指向 COPYDATASTRUCT 结构体的指针。

    根据 MSDN 的文档: [https://learn.microsoft.com/zh-cn/windows/win32/dataxchg/wm-copydata]

    WM_COPYDATA 消息发送时,wParam 为传递数据的窗口的句柄,lParam 为指向包含要传递的数据 的 COPYDATASTRUCT 结构的指针。 COPYDATASTRUCT 结构体的声明如下:

    1. typedef struct tagCOPYDATASTRUCT {
    2. ULONG_PTR dwData;
    3. DWORD cbData;
    4. _Field_size_bytes_(cbData) PVOID lpData;
    5. } COPYDATASTRUCT, *PCOPYDATASTRUCT;

    其中,dwData 就是要执行函数的编号,也就是 Geoff Chappell 给的那个表:

    0SHAppBarMessage
    1Shell_NotifyIcon
    2SHEnableServiceObject 或者 SHLoadInProc

    在从 NT 5.2 开始至今的多次改版中,explorer 已经新增了一些该表未能够展示的功能。

    比如 ID 为 3 可以代表调用了 Shell_NotifyIconGetRect 函数(Win 7 引入),该函数可以获取通知图标的边框的屏幕坐标。

    1. SHSTDAPI Shell_NotifyIconGetRect(
    2. const NOTIFYICONIDENTIFIER *identifier,
    3. RECT *iconLocation
    4. );

    第一个是入参,使用仅 guidItem 或者 hWnd 加 uID 来向 explorer 请求数据,该过程中使用一个未文档的 CLSID。他的调试符号是 GUID_ShellNotifyChevron 具体的 GUID 为:{964B6543-BBAD-44EE-848A-3A95D85951EA}。

    Shell_NotifyIconGetRect 伪代码

    当然,对于本文的目的来说这些新增的内容不太重要。

    由于我们测试用的是 Shell_NotifyIcon,则结果应该是 1,WinDbg 查看发现是一致的:

     0:000> dps 000000f4d95ee308

    000000f4`d95ee308        00000000`00000001   ---->  dwData
    000000f4`d95ee310        00000000`000005cc   ---->  cbData
    000000f4`d95ee318        000000f4`d95ee360   ---->  lpData
    000000f4`d95ee320        00000000`00000020
    000000f4`d95ee328        00007ffc`00000000
    000000f4`d95ee330        000001fa`7544f160
    000000f4`d95ee338        00000000`00000000
    000000f4`d95ee340        00000000`40000163
    000000f4`d95ee348        00000000`40000163
    000000f4`d95ee350        000001fa`75430000
    000000f4`d95ee358        00000000`00000000
    000000f4`d95ee360        00000000`34753423
    000000f4`d95ee368        00050e7c`000003bc
    000000f4`d95ee370        00000007`0000245f
    000000f4`d95ee378        0001002b`000007ed
    000000f4`d95ee380        76d86258`8bd56d4b

    这里的 lpData 是什么呢?我们接着分析:

    0:000> dps 000000f4`d95ee360
    000000f4`d95ee360  00000000`34753423
    000000f4`d95ee368  00050e7c`000003bc
    000000f4`d95ee370  00000007`0000245f
    000000f4`d95ee378  0001002b`000007ed
    000000f4`d95ee380  76d86258`8bd56d4b
    000000f4`d95ee388  5e8f7a0b`75285e94
    000000f4`d95ee390  00000000`00000000
    000000f4`d95ee398  00000000`00000000
    000000f4`d95ee3a0  00000000`00000000
    000000f4`d95ee3a8  00000000`00000000
    000000f4`d95ee3b0  00000000`00000000
    000000f4`d95ee3b8  00000000`00000000
    000000f4`d95ee3c0  00000000`00000000
    000000f4`d95ee3c8  00000000`00000000
    000000f4`d95ee3d0  00000000`00000000
    000000f4`d95ee3d8  00000000`00000000

    由于中途关闭了一次电脑,记录的解析图时候来重新画的,下图是前面几个成员的解释:

    WinDbg 参数的分析

    和 Geoff Chappell 说的差不多,基本上是 NOTIFYICONDATAW 结构。为了方便处理我们将 Signature(0x34753423) 和 dwMessage 合并到这个结构体中第一个成员的前面。explorer 通过Signature 验证调用是否是发送至任务栏的通知区域的,因为 lParam->dwData 指向的 ID == 1 并不一定是由 Shell_NotifyIcon 发起的,只是说 Shell_NotifyIcon 发起时的 ID 为 1。

    此外,可能是因为版本问题,HICON hIcon 成员对应位置被改成 DWORD uKnown。这个值在测试过程中是 01002b,暂时还不清楚他是什么。

    根据 IDA 反汇编的代码,ICON 是创建之后才单独去绘制的,所以可能结构体有所变化,其他位置目前没有发现变化,完整的结构体如下所示。

    1. typedef struct _TRAY_ICON_DATAW {
    2. DWORD Signature;
    3. DWORD dwMessage; // dwMessage <-- Shell_NotifyIconW(DWORD dwMessage, PNOTIFYICONDATAW lpData)
    4. DWORD cbSize;
    5. DWORD hWnd;
    6. UINT uID;
    7. UINT uFlags;
    8. UINT uCallbackMessage;
    9. DWORD uIconID; // HICON hIcon; why?
    10. #if (NTDDI_VERSION < NTDDI_WIN2K)
    11. WCHAR szTip[64];
    12. #endif
    13. #if (NTDDI_VERSION >= NTDDI_WIN2K)
    14. WCHAR szTip[128];
    15. DWORD dwState;
    16. DWORD dwStateMask;
    17. WCHAR szInfo[256];
    18. #ifndef _SHELL_EXPORTS_INTERNALAPI_H_
    19. union {
    20. UINT uTimeout;
    21. UINT uVersion; // used with NIM_SETVERSION, values 0, 3 and 4
    22. } DUMMYUNIONNAME;
    23. #endif
    24. WCHAR szInfoTitle[64];
    25. DWORD dwInfoFlags;
    26. #endif
    27. #if (NTDDI_VERSION >= NTDDI_WINXP)
    28. GUID guidItem;
    29. #endif
    30. #if (NTDDI_VERSION >= NTDDI_VISTA)
    31. HICON hBalloonIcon;
    32. #endif
    33. } TRAY_ICON_DATAW, * PTRAY_ICON_DATAW;

    2.4 调用方挂钩拦截消息封送过程

    为了验证我们分析的结论,下面我将通过调用方挂钩拦截这个消息的封送过程。

    我们利用 detours 库挂钩 SendMessageTimeoutW 函数,并对 TRAY_ICON_DATAW 进行解析,就可以获取发送的消息内容。

    一个测试代码如下:

    1. // TrayNotifyIconTest.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
    2. //
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. #pragma comment(lib, "detours.lib")
    10. #define WM_IAWENTRAY WM_USER + 0x5 // 系统托盘的自定义消息
    11. // 保存原始函数指针
    12. LPVOID Real_SendMessageTimeoutW = nullptr;
    13. // 定义全局变量
    14. NOTIFYICONDATAW lpNotifyData = { 0 };
    15. typedef struct _TRAY_ICON_DATAW {
    16. DWORD Signature;
    17. DWORD dwMessage; // dwMessage <-- Shell_NotifyIconW(DWORD dwMessage, PNOTIFYICONDATAW lpData)
    18. DWORD cbSize;
    19. DWORD hWnd;
    20. UINT uID;
    21. UINT uFlags;
    22. UINT uCallbackMessage;
    23. DWORD uIconID; // HICON hIcon; why?
    24. #if (NTDDI_VERSION < NTDDI_WIN2K)
    25. WCHAR szTip[64];
    26. #endif
    27. #if (NTDDI_VERSION >= NTDDI_WIN2K)
    28. WCHAR szTip[128];
    29. DWORD dwState;
    30. DWORD dwStateMask;
    31. WCHAR szInfo[256];
    32. #ifndef _SHELL_EXPORTS_INTERNALAPI_H_
    33. union {
    34. UINT uTimeout;
    35. UINT uVersion; // used with NIM_SETVERSION, values 0, 3 and 4
    36. } DUMMYUNIONNAME;
    37. #endif
    38. WCHAR szInfoTitle[64];
    39. DWORD dwInfoFlags;
    40. #endif
    41. #if (NTDDI_VERSION >= NTDDI_WINXP)
    42. GUID guidItem;
    43. #endif
    44. #if (NTDDI_VERSION >= NTDDI_VISTA)
    45. HICON hBalloonIcon;
    46. #endif
    47. } TRAY_ICON_DATAW, * PTRAY_ICON_DATAW;
    48. // 定义原始函数指针类型
    49. typedef BOOL(WINAPI* RealSendMessageTimeoutW)(
    50. HWND hWnd,
    51. UINT Msg,
    52. WPARAM wParam,
    53. LPARAM lParam,
    54. UINT fuFlags,
    55. UINT uTimeout,
    56. PDWORD_PTR lpdwResult
    57. );
    58. // Utf-8 为了兼容中文
    59. void SetConsoleCodePageToUTF8() {
    60. _wsetlocale(LC_ALL, L".UTF8");
    61. }
    62. // 定义挂钩函数
    63. BOOL WINAPI MySendMessageTimeoutW(
    64. HWND hWnd,
    65. UINT Msg,
    66. WPARAM wParam,
    67. LPARAM lParam,
    68. UINT fuFlags,
    69. UINT uTimeout,
    70. PDWORD_PTR lpdwResult
    71. )
    72. {
    73. // 显示调用参数
    74. std::wcout << "SendMessageTimeoutW called:" << std::endl;
    75. std::wcout << "hWnd: " << std::hex << hWnd << std::endl;
    76. std::wcout << "Msg: " << std::hex << Msg << std::endl;
    77. std::wcout << "wParam: " << std::hex << wParam << std::endl;
    78. std::wcout << "lParam: " << std::hex << lParam << std::endl;
    79. // 如果 lParam 指向 WM_COPYDATA 结构体
    80. if (Msg == WM_COPYDATA) {
    81. PCOPYDATASTRUCT lpCopyData = reinterpret_cast(lParam);
    82. PTRAY_ICON_DATAW lpIconData = reinterpret_cast(lpCopyData->lpData); // x64 系统偏移量 0x58
    83. std::wcout << L"pData: " << std::hex << lpIconData << std::endl;
    84. std::wcout << L"hWnd: " << std::hex << lpIconData->hWnd << std::endl;
    85. std::wcout << L"szTip: " << std::hex << lpIconData->szTip << std::endl;
    86. std::wcout << L"szInfo: " << std::hex << lpIconData->szInfo << std::endl;
    87. std::wcout << L"szInfoTitle: " << std::hex << lpIconData->szInfoTitle << std::endl;
    88. }
    89. // 调用原始函数
    90. BOOL result = ((RealSendMessageTimeoutW)Real_SendMessageTimeoutW)(
    91. hWnd, Msg, wParam, lParam, fuFlags, uTimeout, lpdwResult);
    92. return result;
    93. }
    94. int main()
    95. {
    96. SetConsoleCodePageToUTF8();
    97. // 挂钩 SendMessageTimeoutW
    98. DetourTransactionBegin();
    99. DetourUpdateThread(GetCurrentThread());
    100. Real_SendMessageTimeoutW = &SendMessageTimeoutW;
    101. DetourAttach(&(PVOID&)Real_SendMessageTimeoutW, MySendMessageTimeoutW);
    102. DetourTransactionCommit();
    103. // 初始化NOTIFYICONDATA结构
    104. lpNotifyData.cbSize = (DWORD)sizeof(NOTIFYICONDATAW);
    105. lpNotifyData.hWnd = GetConsoleWindow();
    106. lpNotifyData.uID = 0x5;
    107. lpNotifyData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO;
    108. lpNotifyData.uCallbackMessage = WM_IAWENTRAY;
    109. lpNotifyData.hIcon = LoadIconW(NULL, IDI_APPLICATION);
    110. wcscpy_s(lpNotifyData.szTip, L"通知栏图标测试程序");
    111. wcscpy_s(lpNotifyData.szInfo, L"提示窗口内容");
    112. wcscpy_s(lpNotifyData.szInfoTitle, L"提示窗口标题");
    113. lpNotifyData.dwInfoFlags = NIIF_INFO;
    114. lpNotifyData.uTimeout = 5000;
    115. Shell_NotifyIconW(NIM_ADD, &lpNotifyData); // 在托盘区添加图标
    116. getchar();
    117. Shell_NotifyIconW(NIM_DELETE, &lpNotifyData); // 删除图标
    118. // 卸载挂钩
    119. DetourTransactionBegin();
    120. DetourUpdateThread(GetCurrentThread());
    121. DetourDetach(&(PVOID&)Real_SendMessageTimeoutW, MySendMessageTimeoutW);
    122. DetourTransactionCommit();
    123. return 0;
    124. }

    可以很轻松地解析出发送的数据内容,结果如下图所示:

    调用方挂钩效果

    下面我们解释一下这几个参数,szInfo 和 szInfoTitle 只有在显示气泡提示时候才用到,分别对应消息的内容和标题,如下图所示:

    Win11 气泡提示的标题取决于程序名称

    szTip 则是任务栏图标的标签文本:

    通知区域图标

    这说明了对 WM_COPYDATA 消息的分析是正确的。

    2.5 接收方挂钩实现获取任意图标信息

    讲完了消息封送过程(调用方)的拦截方法,我们必然需要去研究接收方的消息处理机制。这是因为接收方作为消息的总管理者,我们有能力获取所有使用 Shell_NotifyIcon 函数的程序而不必大动干戈地去想着全局挂钩消息的封送过程。全局挂钩往往消耗过多的计算机资源且面临着兼容性风险从而不是一个优选的方案。

    根据我前一阵子研究的动态壁纸制作技术内幕,当时就已经分析了一部分 explorer 内部的桌面机制,分析时遇到了一类消息回调的模板,里面就有这里需要用的内容,只不过第二部分的动态壁纸制作分析文章搁置了很久而未发布。原因是这真的是一个很复杂的工程,而我又没有太多空余时间,所以进展就比较慢,下面是部分未发布的内容截图:

    部分未发布的内容截图

    当然,关于桌面动态壁纸和虚拟桌面等接口,未来有进展了我就会先发布一部分的。

    通过 IDA 分析 explorer 的导入表,我们对所有窗口创建和消息发送函数进行交叉引用、特征字符串等排查。最终确定了 CTray 类是实现系统通知区域的窗口程序类,并在其中找到了 v_WndProc 消息回调函数,在 explorer 所有的窗口回调函数中只有该函数处理 WM_COPYDATA(0x4A) 消息。

    随后我们结合 WinDbg 调试进一步确定了这个函数就是处理 WM_COPYDATA 的函数,由于 explorer 不是很好动态调试,所以测试时没有留图。

    在 x64 系统下,该函数的声明(已经分析并修正参数)如下:

    1. typedef LRESULT(__fastcall* v_WndProc)(
    2. LPVOID pthis, // CTray *this,由于没有 CTray 的原型,这里就改写成 void* 类型。
    3. HWND hWnd,
    4. UINT uMsg,
    5. WPARAM wParam,
    6. LPARAM lParam
    7. );

    我猜测 x86 的调用约定是 __stdcall ,具体声明如何还未进行验证,交给读者啦。

    它后面几个参数其实和一般的窗口回调没有什么区别。

    最后两个参数 IDA 很有可能根据调试符号直接解析为 LPITEMIDLIST 结构体指针,我觉得这是不对的,就改了过来。注意: IDA 对最后一个参数名称解析为 pidl 。

    CTray::v_WndProc 中响应 WM_COPYDATA 消息的部分

    由于这里具体的处理过程理解起来比较复杂,而且我觉得暂时也没有必要去讲解。所以我就不逐一解释了,感兴趣的可以自己去分析一下这个函数,它相对于桌面其他几个窗口的消息处理机制来说还是稍微简单一点的。

    P.S.: 可以不使用挂钩 CTray::v_WndProc  API 的方式拦截消息,详细见第 4 篇文章《最新方案(三)》

    我们使用 Detours 库再次实现挂钩过程,测试时使用了硬编码偏移量,发布时应该采用特征码定位方法,定位过程用到的代码我也会附加在后面的,需要的自己完善一下代码。

    我测试的系统是最新的 Win 11 Release 23H2 | x64 | Build 10.0.22631.3155,该函数偏移量为 0xB630。

    再次警告:Explorer 属于经常更新的组件,且 CTray::v_WndProc 函数是内部函数,偏移量随系统更新而变化,实际过程必须使用定位算法

    下面是 HOOK 模块的简单测试用代码:

    1. #include "pch.h"
    2. #include
    3. #include "detours.h"
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. #pragma comment(lib, "detours.lib")
    10. HINSTANCE g_hinstDLL = NULL; // 模块句柄
    11. LPVOID fpVWndProc = NULL; // CTray::v_WndProc 函数原始地址
    12. // 一些宏定义
    13. #define NIM_ADD 0x00000000
    14. #define NIM_MODIFY 0x00000001
    15. #define NIM_DELETE 0x00000002
    16. #define NIM_SETFOCUS 0x00000003
    17. #define NIM_SETVERSION 0x00000004
    18. #define NIF_TIP 0x00000004
    19. #define NIF_INFO 0x00000010
    20. // Notify Icon Infotip flags
    21. #define NIIF_NONE 0x00000000
    22. #define NIIF_INFO 0x00000001
    23. #define NIIF_WARNING 0x00000002
    24. #define NIIF_ERROR 0x00000003
    25. #define NIIF_USER 0x00000004
    26. #define NIIF_ICON_MASK 0x0000000F
    27. #define NIIF_NOSOUND 0x00000010
    28. #define NIIF_LARGE_ICON 0x00000020
    29. #define NIIF_RESPECT_QUIET_TIME 0x00000080
    30. // 窗口句柄转换字符串的函数
    31. std::wstring make_hwnd_text(HWND hwnd)
    32. {
    33. wchar_t buf[25];
    34. wsprintfW(buf, L"HWND:0x%I64X", (UINT64)hwnd);
    35. return buf;
    36. }
    37. // dwMessage 参数转换为已知参数字符串
    38. std::wstring make_snmsg_text(DWORD dwMessage)
    39. {
    40. #define CHECK_DMSG(dwMessage, var) if (dwMessage == var) return L#var;
    41. CHECK_DMSG(dwMessage, NIM_ADD);
    42. CHECK_DMSG(dwMessage, NIM_MODIFY);
    43. CHECK_DMSG(dwMessage, NIM_DELETE);
    44. CHECK_DMSG(dwMessage, NIM_SETFOCUS);
    45. CHECK_DMSG(dwMessage, NIM_SETVERSION);
    46. wchar_t buf[25];
    47. wsprintfW(buf, L"Message:%u", dwMessage);
    48. return buf;
    49. #undef CHECK_HWND
    50. }
    51. // dwInfoFlags 参数转换为已知参数字符串
    52. std::wstring make_infoflag_text(DWORD dwInfoFlags)
    53. {
    54. #define CHECK_DMSG(dwInfoFlags, var) if (dwInfoFlags == var) return L#var;
    55. CHECK_DMSG(dwInfoFlags, NIIF_NONE);
    56. CHECK_DMSG(dwInfoFlags, NIIF_INFO);
    57. CHECK_DMSG(dwInfoFlags, NIIF_WARNING);
    58. CHECK_DMSG(dwInfoFlags, NIIF_ERROR);
    59. CHECK_DMSG(dwInfoFlags, NIIF_USER);
    60. CHECK_DMSG(dwInfoFlags, NIIF_ICON_MASK);
    61. CHECK_DMSG(dwInfoFlags, NIIF_NOSOUND);
    62. CHECK_DMSG(dwInfoFlags, NIIF_LARGE_ICON);
    63. CHECK_DMSG(dwInfoFlags, NIIF_RESPECT_QUIET_TIME);
    64. wchar_t buf[25];
    65. wsprintfW(buf, L"Message:%u", dwInfoFlags);
    66. return buf;
    67. #undef CHECK_HWND
    68. }
    69. // 方便于调用
    70. #define HWND2TEXT(hwnd) make_hwnd_text(hwnd).c_str()
    71. #define DMSG2TEXT(dwMessage) make_snmsg_text(dwMessage).c_str()
    72. #define NIIF2TEXT(dwInfoFlags) make_infoflag_text(dwInfoFlags).c_str()
    73. // 日志记录函数,在模块的目录下创建 SysNotifyLog.txt 日志文件
    74. void log_printf(const wchar_t* fmt, ...)
    75. {
    76. DWORD dwError = GetLastError();
    77. _wsetlocale(LC_ALL, L".UTF8"); // 设置代码页以支持中文
    78. wchar_t buf[800];
    79. va_list va;
    80. va_start(va, fmt);
    81. vswprintf_s(buf, fmt, va);
    82. va_end(va);
    83. TCHAR szPath[MAX_PATH];
    84. GetModuleFileName(g_hinstDLL, szPath, MAX_PATH);
    85. TCHAR* pch = _tcsrchr(szPath, TEXT('\\'));
    86. if (pch == NULL)
    87. pch = _tcsrchr(szPath, TEXT('/'));
    88. lstrcpy(pch + 1, TEXT("SysNotifyLog.txt"));
    89. HANDLE hMutex = CreateMutex(NULL, FALSE, TEXT("SysNotifyHooker Mutex"));
    90. WaitForSingleObject(hMutex, 800);
    91. {
    92. using namespace std;
    93. FILE* fp = NULL;
    94. _tfopen_s(&fp, szPath, TEXT("a"));
    95. if (fp)
    96. {
    97. fprintf(fp, "PID:%08lX:TID:%08lX> ",
    98. GetCurrentProcessId(), GetCurrentThreadId());
    99. fputws(buf, fp);
    100. fflush(fp);
    101. fclose(fp);
    102. }
    103. }
    104. ReleaseMutex(hMutex);
    105. CloseHandle(hMutex);
    106. SetLastError(dwError);
    107. }
    108. // x64 结构体的声明
    109. typedef struct _TRAY_ICON_DATAW {
    110. DWORD Signature;
    111. DWORD dwMessage; // dwMessage <-- Shell_NotifyIconW(DWORD dwMessage, ...)
    112. DWORD cbSize;
    113. DWORD hWnd;
    114. UINT uID;
    115. UINT uFlags;
    116. UINT uCallbackMessage;
    117. DWORD uIconID; // HICON hIcon; why it changes?
    118. #if (NTDDI_VERSION < NTDDI_WIN2K)
    119. WCHAR szTip[64];
    120. #endif
    121. #if (NTDDI_VERSION >= NTDDI_WIN2K)
    122. WCHAR szTip[128];
    123. DWORD dwState;
    124. DWORD dwStateMask;
    125. WCHAR szInfo[256];
    126. #ifndef _SHELL_EXPORTS_INTERNALAPI_H_
    127. union {
    128. UINT uTimeout;
    129. UINT uVersion; // used with NIM_SETVERSION, values 0, 3 and 4
    130. } DUMMYUNIONNAME;
    131. #endif
    132. WCHAR szInfoTitle[64];
    133. DWORD dwInfoFlags;
    134. #endif
    135. #if (NTDDI_VERSION >= NTDDI_WINXP)
    136. GUID guidItem;
    137. #endif
    138. #if (NTDDI_VERSION >= NTDDI_VISTA)
    139. HICON hBalloonIcon;
    140. #endif
    141. } TRAY_ICON_DATAW, * PTRAY_ICON_DATAW;
    142. // 函数原型的声明
    143. typedef LRESULT(__fastcall* __v_WndProc)(
    144. LPVOID pthis,
    145. HWND hWnd,
    146. UINT uMsg,
    147. WPARAM wParam,
    148. LPARAM lParam
    149. );
    150. // 我们的钩子函数
    151. LRESULT __fastcall v_WndProc(
    152. LPVOID pthis, HWND hWnd,
    153. UINT uMsg, WPARAM wParam,
    154. LPARAM lParam
    155. )
    156. {
    157. LRESULT ret = 0;
    158. ret = ((__v_WndProc)fpVWndProc)(pthis, hWnd, uMsg, wParam, lParam);
    159. if ((UINT)uMsg == WM_COPYDATA)
    160. {
    161. COPYDATASTRUCT* pCopyData = reinterpret_cast(lParam);
    162. if (pCopyData->dwData == 1)
    163. {
    164. PTRAY_ICON_DATAW pTrayIcon = reinterpret_cast(pCopyData->lpData);
    165. if (pTrayIcon->Signature == 0x34753423) // 检查是否是通知区域图标消息
    166. {
    167. // log_printf(L"CTray::v_WndProc -- COPYDATA: Signature = 0x34753423;\n");
    168. log_printf(L"CTray::v_WndProc:[%ws]:[%ws];\n",
    169. DMSG2TEXT(pTrayIcon->dwMessage), HWND2TEXT((HWND)wParam));
    170. if ((pTrayIcon->uFlags & NIF_INFO) != 0)
    171. {
    172. log_printf(L"Tip[%ws], szInfoParam:\n",
    173. pTrayIcon->szTip);
    174. log_printf(L"InfoTitle[%ws], Info[%ws], InfoFlags[%ws];\n",
    175. pTrayIcon->szInfoTitle, pTrayIcon->szInfo, NIIF2TEXT(pTrayIcon->dwInfoFlags));
    176. }
    177. else if ((pTrayIcon->uFlags & NIF_TIP) != 0)
    178. {
    179. log_printf(L"Tip[%ws], non-szInfo;\n", pTrayIcon->szTip);
    180. }
    181. else {
    182. log_printf(L"non-szTip, non-szInfo;\n");
    183. }
    184. // log_printf(L"CTray::v_WndProc: leave: ret = %Id;\n", ret);
    185. }
    186. }
    187. }
    188. return ret;
    189. }
    190. void StartHookingFunction()
    191. {
    192. // 开始事务
    193. DetourTransactionBegin();
    194. // 更新线程信息
    195. DetourUpdateThread(GetCurrentThread());
    196. HMODULE hExpBase = GetModuleHandleW(L"explorer.exe");
    197. if (hExpBase == nullptr)
    198. return;
    199. #if (NTDDI_VERSION >= NTDDI_WIN10 && _WIN64)
    200. // 硬编码了 v_WndProc 函数的偏移量,系统版本 Win11, 10.0.22631.3155, x64, 23H2
    201. fpVWndProc = reinterpret_cast(
    202. reinterpret_cast(hExpBase) + 0xB630u);
    203. #else
    204. NOT_SUPPORT_VERSION;
    205. #endif
    206. if (fpVWndProc == nullptr)
    207. return;
    208. // 将拦截的函数附加到原函数的地址上,这里可以拦截多个函数。
    209. DetourAttach(&fpVWndProc,
    210. v_WndProc);
    211. // 结束事务
    212. DetourTransactionCommit();
    213. }
    214. void UnmappHookedFunction()
    215. {
    216. // 开始事务
    217. DetourTransactionBegin();
    218. // 更新线程信息
    219. DetourUpdateThread(GetCurrentThread());
    220. // 将拦截的函数从原函数的地址上解除,这里可以解除多个函数。
    221. DetourDetach(&fpVWndProc,
    222. v_WndProc);
    223. // 结束事务
    224. DetourTransactionCommit();
    225. }
    226. extern "C"
    227. BOOL WINAPI
    228. DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
    229. {
    230. DisableThreadLibraryCalls(hinstDLL);
    231. switch (fdwReason)
    232. {
    233. case DLL_PROCESS_ATTACH:
    234. g_hinstDLL = hinstDLL;
    235. log_printf(L"DLL_PROCESS_ATTACH: %p\n", hinstDLL);
    236. StartHookingFunction();
    237. break;
    238. case DLL_PROCESS_DETACH:
    239. log_printf(L"DLL_PROCESS_DETACH: %p\n", hinstDLL);
    240. UnmappHookedFunction();
    241. break;
    242. case DLL_THREAD_ATTACH:
    243. case DLL_THREAD_DETACH:
    244. break;
    245. }
    246. return TRUE;
    247. }
    248. // just for exporting a function
    249. extern "C" __declspec(dllexport) void ImportFunc()
    250. {
    251. // Do nothing
    252. }

    日志记录的效果如下图所示:

    测试日志记录截图[旧版]

    P.S.:有趣的是在寻找是否已经存在解决方案的时候,我偶然找到了 ReactOS 团队于 2017 年上半年公开的 explorer.exe 消息挂钩工具的代码。虽然在最新的系统上已经不再适用,并且它主要解析 explorer 作为消息发送者的情况,而不是接收者,但是他们的模板对我来说还是有所帮助的。其 Github 链接如下:SysNotifyHooker: API hook for Windows Explorer

    特征码定位算法整理可以见我的这篇文章:

    https://blog.csdn.net/qq_59075481/article/details/135752520

    我在测试时使用的是暴力方法(不是最优的):

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. inline int BFTracePatternInModule(
    7. LPCWSTR moduleName,
    8. PBYTE pattern,
    9. SIZE_T patternSize,
    10. DWORD dwRepeat,
    11. DWORD dwSelect = 1
    12. )
    13. {
    14. if (pattern == 0 || moduleName == 0 || patternSize == 0 || dwRepeat <= 0)
    15. {
    16. return 0;
    17. }
    18. HMODULE hModule = LoadLibraryW(moduleName);
    19. if (hModule == nullptr) {
    20. printf("Failed to load module: %ws.\n", moduleName);
    21. return 0;
    22. }
    23. MODULEINFO moduleInfo;
    24. if (!GetModuleInformation(GetCurrentProcess(), hModule, &moduleInfo, sizeof(moduleInfo))) {
    25. printf("Failed to get module information.\n");
    26. FreeLibrary(hModule);
    27. return 0;
    28. }
    29. std::vector<uint64_t> vcMachList;
    30. BYTE* moduleBase = reinterpret_cast(hModule);
    31. SIZE_T moduleSize = moduleInfo.SizeOfImage;
    32. printf("模块基址:0x%I64X.\n", reinterpret_cast<uint64_t>(hModule));
    33. printf("模块大小:%I64d Bytes.\n", moduleSize);
    34. if (moduleSize == 0)
    35. {
    36. printf("Failed to get module information.\n");
    37. FreeLibrary(hModule);
    38. return 0;
    39. }
    40. uint64_t thisMatch = 0;
    41. DWORD SelectCase = (dwSelect < 256) && dwSelect ? dwSelect : 256; // 最大结果记录次数
    42. SIZE_T MatchLimit = patternSize * dwRepeat - 1; // 连续重复匹配次数限制
    43. int cwStart = clock();
    44. if (dwRepeat == 1)
    45. {
    46. for (SIZE_T i = 0; i < moduleSize; i++)
    47. {
    48. thisMatch = 0;
    49. SIZE_T j = 0;
    50. for (j; j < patternSize - 1; j++)
    51. {
    52. if (moduleBase[i + j] != pattern[j] && pattern[j] != 0u)
    53. {
    54. break;
    55. }
    56. }
    57. if (j == patternSize - 1)
    58. {
    59. if (moduleBase[i + j] == pattern[j] || pattern[j] == 0u)
    60. {
    61. thisMatch = i;
    62. SelectCase--;
    63. vcMachList.push_back(thisMatch);
    64. if (!SelectCase) break;
    65. }
    66. }
    67. }
    68. }
    69. else {
    70. for (SIZE_T i = 0; i < moduleSize; i++)
    71. {
    72. thisMatch = 0;
    73. SIZE_T j = 0;
    74. for (j; j < MatchLimit; j++)
    75. {
    76. if (moduleBase[i + j] != pattern[j % patternSize] && pattern[j % patternSize] != 0u)
    77. {
    78. break;
    79. }
    80. }
    81. if (j == MatchLimit)
    82. {
    83. if (moduleBase[i + MatchLimit] == pattern[patternSize - 1] || pattern[patternSize - 1] == 0u)
    84. {
    85. thisMatch = i;
    86. SelectCase--;
    87. vcMachList.push_back(thisMatch);
    88. if (!SelectCase) break;
    89. }
    90. }
    91. }
    92. }
    93. int cwEnd = clock();
    94. for (SIZE_T i = 0; i < vcMachList.size(); i++)
    95. {
    96. printf("匹配到模式字符串位于偏移: [0x%I64X] 处,动态地址:[0x%I64X]。\n",
    97. vcMachList[i], reinterpret_cast<uint64_t>(moduleBase) + vcMachList[i]);
    98. }
    99. if (vcMachList.size() == 0)
    100. {
    101. printf("No Found.\n");
    102. }
    103. FreeLibrary(hModule);
    104. return cwEnd - cwStart;
    105. }
    106. /*
    107. * CTray::v_WndProc 函数入口点汇编
    108. * .text:000000014000B630 48 89 5C 24 08 mov [rsp-8+arg_0], rbx
    109. * .text:000000014000B635 48 89 74 24 10 mov [rsp-8+arg_8], rsi
    110. * .text:000000014000B63A 55 push rbp
    111. * .text:000000014000B63B 57 push rdi
    112. * .text:000000014000B63C 41 54 push r12
    113. * .text:000000014000B63E 41 56 push r14
    114. * .text:000000014000B640 41 57 push r15
    115. * .text:000000014000B642 48 8D 6C 24 D1 lea rbp, [rsp-2Fh]
    116. * .text:000000014000B647 48 81 EC E0 00 00 00 sub rsp, 0E0h
    117. */
    118. int main()
    119. {
    120. // 暴力算法
    121. const wchar_t* moduleName = L"C:\\Windows\\explorer.exe";
    122. // 测试使用的是入口点特征码,实际需要自己调整选择最佳的特征
    123. BYTE pattern[] =
    124. {
    125. 0x48u, 0x89u, 0x5Cu, 0x24u, 0x08u,
    126. 0x48u, 0x89u, 0x74u, 0x24u, 0x10u,
    127. 0x55u, 0x57u, 0x41u, 0x54u, 0x41u,
    128. 0x56u, 0x41u, 0x57u
    129. };
    130. SIZE_T patternSize = 18;
    131. DWORD dwRepeat = 1, dwSelect = 1; // 匹配第一次完整匹配,不重复匹配
    132. int TimeCost = 0;
    133. TimeCost = BFTracePatternInModule(moduleName,
    134. pattern, patternSize, dwRepeat, dwSelect);
    135. printf("算法耗时:%d ms.\n", TimeCost);
    136. return 0;
    137. }

    测试结果截图如下:

    特征码定位算法计算结果

    3 注入 HOOK 模块的方案

    对于上面 2.5 节的 Dll 代码,需要重启资源管理器并且在其初始化的特定阶段进行模块注入。一方面注入的过早 explorer 的环境还没有初始化完成,这时候注入是有风险的——启动挂起进程注入有时候会失败;另一方面,注入的过晚 Shell_TrayWnd 窗口已经创建,这时候再处理就迟了,只能拦截到后续注册的图标信息。

    我尝试了在稍晚一些的阶段进行注入,比如 ntdll、Kernel32、KernelBase 等重要的模块已经加载完成时,注入依然有概率失败。但是创建挂起进程注入作为经典的注入方式,不能不去谈。

    3.1 创建挂起进程注入

    一般在进程创建时注入模块,需要使用创建挂起进程注入。通过 CreateProcess 函数并指定 dwCreationFlags 包含 CREATE_SUSPENDED ,即可创建挂起进程。

    再使用 NtCreateThreadEx 函数创建远程线程。对于挂起进程的 explorer 也比较特殊,需要指定 ULONG CreateThreadFlags 参数为 1 来创建挂起的远程线程线程。

    随后在释放线程的时候,必须先释放主线程,再释放我们的远程线程。否则,进程就会崩溃。

    1. std::cout << "> Resume threads: \n" << std::endl;
    2. // 先释放主线程
    3. ResumeThread(hThread);
    4. // 再释放远程线程
    5. if(ResumeThread(hRemoteThread) == (DWORD)-1)
    6. {
    7. std::cout << "Error: Resume threads failed! \n" << std::endl;
    8. return FALSE;
    9. }

    完整的注入器代码如下:

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. #pragma comment(lib, "Rstrtmgr.lib")
    7. #define RM_SESSIONKEY_LEN sizeof(GUID) * 2 + 1
    8. BOOL WINAPI InjectMouldeHandler(
    9. HANDLE hProcess,
    10. HANDLE hThread,
    11. LPCWSTR pszDllFileName
    12. );
    13. BOOL GetShellProcessRmInfoEx(
    14. PRM_UNIQUE_PROCESS* lpRmProcList,
    15. DWORD_PTR* lpdwCountNum
    16. );
    17. void RmProcMemFree(
    18. PRM_UNIQUE_PROCESS lpRmProcList,
    19. DWORD_PTR lpdwCountNum
    20. );
    21. void RmWriteStatusCallback(
    22. UINT nPercentComplete
    23. );
    24. DWORD ShellShutdownManager();
    25. int wmain(int argc, WCHAR* argv[])
    26. {
    27. WCHAR szAppName[256] = L"C:\\Windows\\explorer.exe";
    28. //WCHAR szDllName[256] = { 0 };
    29. BOOL cpResult = FALSE,
    30. isInjected = FALSE;
    31. STARTUPINFO si = { 0 };
    32. si.cb = sizeof(STARTUPINFO);
    33. PROCESS_INFORMATION pi = { 0 };
    34. // 参数检查
    35. if (argc != 2)
    36. {
    37. std::cerr << "Error invalid parameters.\n" <<
    38. " SuspendResumeInjectShell.exe "
    39. << std::endl;
    40. return -1;
    41. }
    42. // 使用 RM 结束 SHELL 进程
    43. std::cout << "> Shutdown Shell process " << std::endl;
    44. if (ERROR_SUCCESS != ShellShutdownManager())
    45. {
    46. std::cerr << "Shutdown Shell process failed.\n" << std::endl;
    47. return -1;
    48. }
    49. // 启动挂起式进程
    50. std::cout << "> Create suspend process " << std::endl;
    51. cpResult = CreateProcessW( NULL, szAppName,
    52. nullptr, nullptr, FALSE,
    53. CREATE_SUSPENDED | CREATE_NEW_CONSOLE,
    54. nullptr, nullptr, &si, &pi );
    55. std::cout << "\thProcess: 0x"
    56. << std::hex << (UINT64)pi.hProcess
    57. << "\thThread: 0x"
    58. << std::hex << (UINT64)pi.hThread
    59. << "\tPID: "
    60. << std::dec << pi.dwProcessId
    61. << "\tTID: "
    62. << std::dec << pi.dwThreadId
    63. << std::endl;
    64. // 远程线程注入
    65. std::cout << "> Inject Moulde to process: \n" << std::endl;
    66. isInjected = InjectMouldeHandler(pi.hProcess, pi.hThread, argv[1]);
    67. if (isInjected == TRUE)
    68. {
    69. std::cout << "Inject Successfully!" << std::endl;
    70. }
    71. // 关闭句柄
    72. CloseHandle(pi.hThread);
    73. CloseHandle(pi.hProcess);
    74. return 0;
    75. }
    76. BOOL WINAPI InjectMouldeHandler(
    77. HANDLE hProcess,
    78. HANDLE hThread,
    79. LPCWSTR pszDllFileName
    80. )
    81. {
    82. // 1.目标进程句柄
    83. if ((hProcess == nullptr) || (hThread == nullptr)
    84. || (pszDllFileName == nullptr))
    85. {
    86. wprintf(L"Error: InvalidSyntax error from InjectMouldeHandler.\n");
    87. SetLastError(ERROR_INVALID_PARAMETER);
    88. return FALSE;
    89. }
    90. size_t pathSize = (wcslen(pszDllFileName) + 1) * sizeof(wchar_t);
    91. SetLastError(0);
    92. // 2.在目标进程中申请空间
    93. LPVOID lpPathAddr = VirtualAllocEx(hProcess, 0, pathSize,
    94. MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
    95. if (lpPathAddr == nullptr)
    96. {
    97. wprintf(L"Error[%d]: Failed to apply memory in the target process!\n", GetLastError());
    98. return FALSE;
    99. }
    100. SetLastError(0);
    101. // 3.在目标进程中写入 Dll 路径
    102. if (FALSE == WriteProcessMemory(hProcess, lpPathAddr,
    103. pszDllFileName, pathSize, NULL))
    104. {
    105. wprintf(L"Error[%d]: Failed to write module path in target process!\n", GetLastError());
    106. return FALSE;
    107. }
    108. SetLastError(0);
    109. // 4.加载 ntdll.dll
    110. HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
    111. if (hNtdll == NULL)
    112. {
    113. wprintf(L"Error[%d]: Failed to load NTDLL.DLL!\n", GetLastError());
    114. VirtualFreeEx(hProcess, lpPathAddr, 0, MEM_RELEASE);
    115. return FALSE;
    116. }
    117. SetLastError(0);
    118. // 5.获取 LoadLibraryW 的函数地址, FARPROC 可以自适应 32 位与 64 位
    119. FARPROC pFuncProcAddr = GetProcAddress(GetModuleHandleW(L"KernelBase.dll"),
    120. "LoadLibraryW");
    121. if (pFuncProcAddr == nullptr)
    122. {
    123. wprintf(L"Error[%d]: Failed to obtain the address of the LoadLibrary function!\n",
    124. GetLastError());
    125. VirtualFreeEx(hProcess, lpPathAddr, 0, MEM_RELEASE);
    126. return FALSE;
    127. }
    128. // 6.获取 NtCreateThreadEx 函数地址,该函数在32位与64位下原型不同
    129. // _WIN64 用来判断编译环境 ,_WIN32用来判断是否是 Windows 系统
    130. #ifdef _WIN64
    131. typedef DWORD(WINAPI* __NtCreateThreadEx)(
    132. PHANDLE ThreadHandle,
    133. ACCESS_MASK DesiredAccess,
    134. LPVOID ObjectAttributes,
    135. HANDLE ProcessHandle,
    136. LPTHREAD_START_ROUTINE lpStartAddress,
    137. LPVOID lpParameter,
    138. ULONG CreateThreadFlags,
    139. SIZE_T ZeroBits,
    140. SIZE_T StackSize,
    141. SIZE_T MaximumStackSize,
    142. LPVOID pUnkown
    143. );
    144. #else
    145. typedef DWORD(WINAPI* __NtCreateThreadEx)(
    146. PHANDLE ThreadHandle,
    147. ACCESS_MASK DesiredAccess,
    148. LPVOID ObjectAttributes,
    149. HANDLE ProcessHandle,
    150. LPTHREAD_START_ROUTINE lpStartAddress,
    151. LPVOID lpParameter,
    152. BOOL CreateSuspended,
    153. DWORD dwStackSize,
    154. DWORD dw1,
    155. DWORD dw2,
    156. LPVOID pUnkown
    157. );
    158. #endif
    159. SetLastError(0);
    160. __NtCreateThreadEx NtCreateThreadEx =
    161. (__NtCreateThreadEx)GetProcAddress(hNtdll, "NtCreateThreadEx");
    162. if (NtCreateThreadEx == nullptr)
    163. {
    164. wprintf(L"Error[%d]: Failed to obtain NtCreateThreadEx function address!\n",
    165. GetLastError());
    166. VirtualFreeEx(hProcess, lpPathAddr, 0, MEM_RELEASE);
    167. return FALSE;
    168. }
    169. SetLastError(0);
    170. // 7.在目标进程中创建远线程
    171. HANDLE hRemoteThread = nullptr;
    172. DWORD lpExitCode = 0;
    173. DWORD dwStatus = NtCreateThreadEx(&hRemoteThread, PROCESS_ALL_ACCESS, NULL,
    174. hProcess, (LPTHREAD_START_ROUTINE)pFuncProcAddr, lpPathAddr,
    175. 1, // 挂起创建线程
    176. 0, 0, 0, NULL);
    177. if (hRemoteThread == nullptr)
    178. {
    179. wprintf(L"Error[%d]: Failed to create thread in target process!\n", GetLastError());
    180. VirtualFreeEx(hProcess, lpPathAddr, 0, MEM_RELEASE);
    181. return FALSE;
    182. }
    183. std::cout << "> Resume threads: \n" << std::endl;
    184. // 先释放主线程
    185. ResumeThread(hThread);
    186. // 再释放远程线程
    187. if(ResumeThread(hRemoteThread) == (DWORD)-1)
    188. {
    189. std::cout << "Error: Resume threads failed! \n" << std::endl;
    190. return FALSE;
    191. }
    192. SetLastError(0);
    193. // 8.等待线程结束
    194. if (WAIT_TIMEOUT == WaitForSingleObject(hRemoteThread, 7000))
    195. {
    196. wprintf(L"Error[%d]: Remote thread not responding.\n", GetLastError());
    197. VirtualFreeEx(hProcess, lpPathAddr, 0, MEM_RELEASE);
    198. return FALSE;
    199. }
    200. GetExitCodeThread(hRemoteThread, &lpExitCode); // 返回值应该是 LoadLibrary 返回的程序注入的地址?
    201. if (lpExitCode == 0)
    202. {
    203. wprintf(L"Error: Injection module failed in the target process.\n");
    204. VirtualFreeEx(hProcess, lpPathAddr, 0, MEM_RELEASE);
    205. return FALSE;
    206. }
    207. // 9.清理环境
    208. VirtualFreeEx(hProcess, lpPathAddr, 0, MEM_RELEASE);
    209. CloseHandle(hRemoteThread);
    210. return TRUE;
    211. }
    212. // 控制结束 explorer 进程
    213. DWORD ShellShutdownManager()
    214. {
    215. DWORD dwRmStatus = 0;
    216. DWORD dwSessionHandle = 0;
    217. WCHAR strSessionKey[RM_SESSIONKEY_LEN] = { 0 };
    218. PRM_UNIQUE_PROCESS lpRmProcList = nullptr;
    219. DWORD_PTR lpdwCountNum = 0u;
    220. // 启动重启管理器会话
    221. dwRmStatus = RmStartSession(&dwSessionHandle, NULL, strSessionKey);
    222. if (ERROR_SUCCESS != dwRmStatus)
    223. {
    224. std::cerr << "RmStartSession failed: " << std::dec << dwRmStatus << std::endl;
    225. return DWORD(-1);
    226. }
    227. // 获取 explorer 进程信息
    228. if (!GetShellProcessRmInfoEx(&lpRmProcList, &lpdwCountNum))
    229. {
    230. std::cerr << "GetShellProcessRmInfoEx failed." << std::endl;
    231. RmEndSession(dwSessionHandle);
    232. return DWORD(-1);
    233. }
    234. // 进程数
    235. UINT dwNum = static_cast(lpdwCountNum);
    236. if (dwNum == UINT(0)) // 没有找到进程
    237. {
    238. std::cerr << "There are no shell processes that need to be closed." << std::endl;
    239. return dwSessionHandle;
    240. }
    241. // GetShellProcessRmInfoEx 失败时的返回值
    242. if (dwNum == UINT(-1))
    243. {
    244. std::cerr << "GetShellProcessRmInfoEx failed." << std::endl;
    245. RmProcMemFree(lpRmProcList, lpdwCountNum);
    246. RmEndSession(dwSessionHandle);
    247. return DWORD(-1);
    248. }
    249. // 遍历进程信息数组
    250. std::cout << "Process Count: " << dwNum << std::endl;
    251. std::cout << "Shell PID: " << std::endl;
    252. for (UINT i = 0; i < dwNum; i++)
    253. {
    254. std::cout << " > " << lpRmProcList[i].dwProcessId << std::endl;
    255. }
    256. // 注册重启管理器信息
    257. dwRmStatus = RmRegisterResources(dwSessionHandle,
    258. 0, NULL, dwNum, lpRmProcList, 0, NULL);
    259. if (ERROR_SUCCESS != dwRmStatus)
    260. {
    261. std::cerr << "RmRegisterResources failed: " << std::dec << dwRmStatus << std::endl;
    262. RmProcMemFree(lpRmProcList, lpdwCountNum);
    263. RmEndSession(dwSessionHandle);
    264. return DWORD(-1);
    265. }
    266. // 强制结束进程
    267. dwRmStatus = RmShutdown(dwSessionHandle, RmForceShutdown, RmWriteStatusCallback);
    268. if (ERROR_SUCCESS != dwRmStatus && ERROR_FAIL_SHUTDOWN != dwRmStatus)
    269. {
    270. std::cerr << "RmShutdown failed: " << std::dec << dwRmStatus << std::endl;
    271. RmEndSession(dwSessionHandle);
    272. return DWORD(-1);
    273. }
    274. // 关闭重启管理器会话
    275. dwRmStatus = RmEndSession(dwSessionHandle);
    276. if (ERROR_SUCCESS != dwRmStatus)
    277. {
    278. std::cerr << "RmEndSession failed: " << std::dec << dwRmStatus << std::endl;
    279. return DWORD(-1);
    280. }
    281. // 释放进程信息数组占用的缓冲区
    282. RmProcMemFree(lpRmProcList, lpdwCountNum);
    283. return ERROR_SUCCESS;
    284. }
    285. // RM 处理回调,显示任务完成的状态
    286. void RmWriteStatusCallback(
    287. UINT nPercentComplete
    288. )
    289. {
    290. std::cout << "Task completion level: " << std::dec << nPercentComplete << std::endl;
    291. }
    292. BOOL GetShellProcessRmInfoEx(
    293. PRM_UNIQUE_PROCESS* lpRmProcList,
    294. DWORD_PTR* lpdwCountNum
    295. )
    296. {
    297. PROCESSENTRY32W pe32 = { 0 };
    298. FILETIME lpCreationTime = { 0 };
    299. FILETIME lpExitTime = { 0 };
    300. FILETIME lpKernelTime = { 0 };
    301. FILETIME lpUserTime = { 0 };
    302. HANDLE hProcess = nullptr;
    303. RM_UNIQUE_PROCESS tpProc = { 0 };
    304. std::vector RmProcVec;
    305. SIZE_T VecLength = 0;
    306. // 在使用这个结构前,先设置它的大小
    307. pe32.dwSize = sizeof(pe32);
    308. // 给系统内所有的进程拍个快照
    309. HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    310. if (hProcessSnap == INVALID_HANDLE_VALUE)
    311. {
    312. std::cerr << "CreateToolhelp32Snapshot 调用失败." << std::endl;
    313. return FALSE;
    314. }
    315. // 遍历进程快照,轮流显示每个进程的信息
    316. BOOL bMore = Process32FirstW(hProcessSnap, &pe32);
    317. while (bMore)
    318. {
    319. if (!_wcsicmp(pe32.szExeFile, L"explorer.exe")
    320. && pe32.cntThreads > 1)// 线程数大于 1,是为了过滤僵尸进程
    321. {
    322. hProcess = OpenProcess(
    323. PROCESS_QUERY_LIMITED_INFORMATION,
    324. FALSE, pe32.th32ProcessID);
    325. if (hProcess != nullptr)
    326. {
    327. memset(&lpCreationTime, 0, sizeof(FILETIME));
    328. // 获取创建时间
    329. if (GetProcessTimes(hProcess,
    330. &lpCreationTime, &lpExitTime,
    331. &lpKernelTime, &lpUserTime) == TRUE)
    332. {
    333. tpProc.dwProcessId = pe32.th32ProcessID;
    334. tpProc.ProcessStartTime = lpCreationTime;
    335. RmProcVec.push_back(tpProc);
    336. }
    337. CloseHandle(hProcess);
    338. hProcess = nullptr;
    339. }
    340. }
    341. bMore = Process32NextW(hProcessSnap, &pe32);
    342. }
    343. // 清除 snapshot 对象
    344. CloseHandle(hProcessSnap);
    345. VecLength = RmProcVec.size();
    346. if (VecLength == 0) // 没有找到进程
    347. {
    348. *lpdwCountNum = 0;
    349. *lpRmProcList = 0;
    350. return TRUE;
    351. }
    352. // 将进程信息复制到数组中
    353. if (VecLength < (SIZE_T)0xf4236u)
    354. {
    355. RM_UNIQUE_PROCESS* lprmUniqueProc =
    356. new(std::nothrow) RM_UNIQUE_PROCESS[VecLength];
    357. if (lprmUniqueProc != nullptr)
    358. {
    359. SIZE_T rSize = VecLength * sizeof(RM_UNIQUE_PROCESS);
    360. if (rSize < (SIZE_T)0xC80000u && rSize > 0)
    361. {
    362. if (!memcpy_s(lprmUniqueProc, rSize, &RmProcVec[0], rSize))
    363. {
    364. *lpdwCountNum = VecLength;
    365. *lpRmProcList = lprmUniqueProc;
    366. return TRUE;
    367. }
    368. }
    369. else {
    370. std::cerr << "Vector Size to large!" << std::endl;
    371. }
    372. }
    373. else {
    374. std::cerr << "Alloc memory failed!" << std::endl;
    375. }
    376. }
    377. else {
    378. std::cerr << "Vector Size is invalid!" << std::endl;
    379. }
    380. return FALSE;
    381. }
    382. void RmProcMemFree(
    383. PRM_UNIQUE_PROCESS lpRmProcList,
    384. DWORD_PTR lpdwCountNum)
    385. {
    386. __try
    387. {
    388. DWORD_PTR dwCountNum = lpdwCountNum;
    389. if (lpRmProcList != nullptr && dwCountNum > 0)
    390. {
    391. while (--dwCountNum)
    392. {
    393. if (IsBadWritePtr(&lpRmProcList[dwCountNum], sizeof(RM_UNIQUE_PROCESS)))
    394. {
    395. throw(L"BadWritePtr event!");
    396. break;
    397. }
    398. memset(&lpRmProcList[dwCountNum], 0, sizeof(RM_UNIQUE_PROCESS));
    399. }
    400. delete[] lpRmProcList;
    401. }
    402. }
    403. __except (EXCEPTION_EXECUTE_HANDLER)
    404. {
    405. // 处理 SEH 异常
    406. std::cerr << "Error access violation." << std::endl;
    407. exit(-1);
    408. }
    409. }
    创建挂起进程注入执行结果

    不过显然后释放远程线程有概率拦截不到一些初始化阶段的信息,并且挂起式注入在进程完成初始化之前的上下文中执行,这可能带来一些崩溃风险。

    创建挂起进程注入有概率失败

    通过多次调试,我发现在 x64dbg 调试器捕获到 explorer 启动时的第一个 TLS 回调事件时注入 explorer 进程,也可以顺利拦截所有托盘图标信息。推测此时已经过了保护阶段,explorer 准备加载不受保护的一些模块。

    那么,我们可以去编写一个调试注入器,以便于在资源管理器启动的合适阶段完成注入。

    下面将分析如何编写简单的调试注入器。

    3.2 创建调试进程注入

    调试器的 “创建调试进程” 功能一般通过 CreateProcess 函数来完成。在 CreateProcess 的 dwCreateFlags 参数中指定 DEBUG_ONLY_THIS_PROCESS 就可以只调试当前进程不调试子进程,CREATE_NEW_CONSOLE 将对应的控制台分离,防止受调试进程和当前进程共用控制台。

    1. BOOL WINAPI OnInitCreateDebugExplorer(PDWORD lpProcessId)
    2. {
    3. // 要调试的进程路径
    4. LPCWSTR lpApplicationName = L"C:\\Windows\\explorer.exe";
    5. // 启动进程并进入调试模式
    6. STARTUPINFOW si = { 0 };
    7. PROCESS_INFORMATION pi = { 0 };
    8. memset(&si, 0, sizeof(si));
    9. memset(&pi, 0, sizeof(pi));
    10. si.cb = sizeof(si);
    11. if (!CreateProcessW(lpApplicationName, NULL, NULL, NULL, FALSE,
    12. DEBUG_ONLY_THIS_PROCESS | CREATE_NEW_CONSOLE,
    13. NULL, NULL, &si, &pi))
    14. {
    15. printf("Error: Failed to create debug process!\n");
    16. return FALSE;
    17. }
    18. *lpProcessId = pi.dwProcessId;
    19. CloseHandle(pi.hProcess);
    20. CloseHandle(pi.hThread);
    21. return TRUE;
    22. }

    3.3 等待调试事件

    我们使用 WaitForDebugEvent 循环来等待被调试进程发出的调试信息,在接收到的消息中使用自定义的回调函数处理调试事件。

    1. // 处理调试事件
    2. int dwStatus = 0;
    3. DEBUG_EVENT debugEvent;
    4. while (WaitForDebugEvent(&debugEvent, INFINITE))
    5. {
    6. // 执行回调函数
    7. UINT uResponse = DebugEventCallback(debugEvent, lpStatusStruct);
    8. // 检查 switch-case 内是否指示了一个 break
    9. if (uResponse != DMSG_ERRORSUCCESS)
    10. {
    11. break;
    12. }
    13. }

    DEBUG_EVENT 结构体描述了调试事件的信息:

    1. typedef struct _DEBUG_EVENT {
    2. DWORD dwDebugEventCode;
    3. DWORD dwProcessId;
    4. DWORD dwThreadId;
    5. union {
    6. EXCEPTION_DEBUG_INFO Exception;
    7. CREATE_THREAD_DEBUG_INFO CreateThread;
    8. CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
    9. EXIT_THREAD_DEBUG_INFO ExitThread;
    10. EXIT_PROCESS_DEBUG_INFO ExitProcess;
    11. LOAD_DLL_DEBUG_INFO LoadDll;
    12. UNLOAD_DLL_DEBUG_INFO UnloadDll;
    13. OUTPUT_DEBUG_STRING_INFO DebugString;
    14. RIP_INFO RipInfo;
    15. } u;
    16. } DEBUG_EVENT, *LPDEBUG_EVENT;

    其中,dwDebugEventCode 描述了调试事件的类型,总共有 9 类调试事件:

    CREATE_PROCESS_DEBUG_EVENT

    创建进程之后发送此类调试事件,这是调试器收到的第一个调试事件。

    CREATE_THREAD_DEBUG_EVENT

    创建一个线程之后发送此类调试事件。

    EXCEPTION_DEBUG_EVENT

    发生异常时发送此类调试事件。

    EXIT_PROCESS_DEBUG_EVENT

    进程结束后发送此类调试事件。

    EXIT_THREAD_DEBUG_EVENT

    一个线程结束后发送此类调试事件。

    LOAD_DLL_DEBUG_EVENT

    装载一个DLL模块之后发送此类调试事件。

    OUTPUT_DEBUG_STRING_EVENT

    被调试进程调用OutputDebugString之类的函数时发送此类调试事件。

    RIP_EVENT

    发生系统调试错误时发送此类调试事件。

    UNLOAD_DLL_DEBUG_EVENT

    卸载一个DLL模块之后发送此类调试事件。

    每种调试事件的详细信息都是放在不同的结构体中的,而结构体通过联合体 u 来记录,通过 u 的字段的名称可以很快地判断哪个字段与哪种事件关联。例如  CREATE_PROCESS_DEBUG_EVENT 调试事件的详细信息由 CreateProcessInfo 字段来记录。

    此外,dwProcessId 和 dwThreadId 分别是触发调试事件的进程 ID 和线程 ID。一个调试器可能同时调试多个进程,而每个进程内又可能有多个线程,通过这两个字段就可以知道调试事件是从哪个进程的哪个线程触发的了。

    3.4 处理调试事件

    调试器通过 WaitForDebugEvent 函数获取调试事件,通过 ContinueDebugEvent 继续被调试进程的执行。ContinueDebugEvent 有三个参数,第一和第二个参数分别是进程 ID 和线程 ID,表示让指定进程内的指定线程继续执行。通常这是在一个循环中完成的,如下面的代码所示:

    1. void OnProcessCreated(const CREATE_PROCESS_DEBUG_INFO*);
    2. void OnThreadCreated(const CREATE_THREAD_DEBUG_INFO*);
    3. void OnException(const EXCEPTION_DEBUG_INFO*);
    4. void OnProcessExited(const EXIT_PROCESS_DEBUG_INFO*);
    5. void OnThreadExited(const EXIT_THREAD_DEBUG_INFO*);
    6. void OnOutputDebugString(const OUTPUT_DEBUG_STRING_INFO*);
    7. void OnRipEvent(const RIP_INFO*);
    8. void OnDllLoaded(const LOAD_DLL_DEBUG_INFO*);
    9. void OnDllUnloaded(const UNLOAD_DLL_DEBUG_INFO*);
    10. BOOL waitEvent = TRUE;
    11. DEBUG_EVENT debugEvent;
    12. while (waitEvent == TRUE && WaitForDebugEvent(&debugEvent, INFINITE)) {
    13. switch (debugEvent.dwDebugEventCode) {
    14. case CREATE_PROCESS_DEBUG_EVENT:
    15. OnProcessCreated(&debugEvent.u.CreateProcessInfo);
    16. break;
    17. case CREATE_THREAD_DEBUG_EVENT:
    18. OnThreadCreated(&debugEvent.u.CreateThread);
    19. break;
    20. case EXCEPTION_DEBUG_EVENT:
    21. OnException(&debugEvent.u.Exception);
    22. break;
    23. case EXIT_PROCESS_DEBUG_EVENT:
    24. OnProcessExited(&debugEvent.u.ExitProcess);
    25. waitEvent = FALSE;
    26. break;
    27. case EXIT_THREAD_DEBUG_EVENT:
    28. OnThreadExited(&debugEvent.u.ExitThread);
    29. break;
    30. case LOAD_DLL_DEBUG_EVENT:
    31. OnDllLoaded(&debugEvent.u.LoadDll);
    32. break;
    33. case UNLOAD_DLL_DEBUG_EVENT:
    34. OnDllUnloaded(&debugEvent.u.UnloadDll);
    35. break;
    36. case OUTPUT_DEBUG_STRING_EVENT:
    37. OnOutputDebugString(&debugEvent.u.DebugString);
    38. break;
    39. case RIP_EVENT:
    40. OnRipEvent(&debugEvent.u.RipInfo);
    41. break;
    42. default:
    43. std::wcout << TEXT("Unknown debug event.") << std::endl;
    44. break;
    45. }
    46. if (waitEvent == TRUE) {
    47. ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, DBG_CONTINUE);
    48. }
    49. else {
    50. break;
    51. }
    52. }

    通过上文的分析,我们只需要对 CREATE_PROCESS_DEBUG_EVENT 和 EXCEPTION_DEBUG_EVENT 进行处理即可。

    在 CREATE_PROCESS_DEBUG_EVENT 也就是进程创建时需要解析 explorer 进程的所有 TLS 回调函数。关于 TLS 结构的原理解释可以参考下面两篇文章:

    首先澄清一点,在内存中动态获取 TLS 回调函数列表和从文件映射中解析的方法是有很大区别的。我们采用简单些的内存动态分析:

    1. #include
    2. #include
    3. // 定义 TLS 回调函数
    4. typedef void (WINAPI* PIMAGE_TLS_CALLBACK)(LPVOID, DWORD, LPVOID);
    5. // TLS 回调函数表结构
    6. typedef struct _IMAGE_TLS_CALLBACK_ENTRY {
    7. struct _IMAGE_TLS_CALLBACK_ENTRY* pNext;
    8. PIMAGE_TLS_CALLBACK pCallbackFunc;
    9. LPVOID pCallbackContext;
    10. } IMAGE_TLS_CALLBACK_ENTRY, * PIMAGE_TLS_CALLBACK_ENTRY;
    11. int main() {
    12. // 要解析的 PE 文件路径
    13. LPCWSTR peFilePath = L"C:\\Windows\\explorer.exe";
    14. SetLastError(0);
    15. // 将模块加载到内存
    16. HMODULE fileBaseAddress = LoadLibraryW(peFilePath);
    17. if (fileBaseAddress == NULL) {
    18. printf("Failed to map file into memory. Error code: %d\n", GetLastError());
    19. return 1;
    20. }
    21. // 获取 DOS 头
    22. PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)fileBaseAddress;
    23. if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
    24. printf("Invalid DOS signature\n");
    25. FreeLibrary(fileBaseAddress);
    26. return 1;
    27. }
    28. // 获取 NT 头
    29. PIMAGE_NT_HEADERS pNtHeaders =
    30. (PIMAGE_NT_HEADERS)((DWORD_PTR)fileBaseAddress
    31. + pDosHeader->e_lfanew);
    32. if (pNtHeaders->Signature != IMAGE_NT_SIGNATURE) {
    33. printf("Invalid NT signature\n");
    34. FreeLibrary(fileBaseAddress);
    35. return 1;
    36. }
    37. // 获取 TLS 目录
    38. PIMAGE_TLS_DIRECTORY pTlsDirectory =
    39. (PIMAGE_TLS_DIRECTORY)((DWORD_PTR)fileBaseAddress
    40. + pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress);
    41. // 获取回调函数表地址
    42. PIMAGE_TLS_CALLBACK_ENTRY pCallbackEntry =
    43. (PIMAGE_TLS_CALLBACK_ENTRY)((DWORD_PTR)pTlsDirectory->AddressOfCallBacks
    44. - pDosHeader->e_lfanew);
    45. printf("> Address of CallBackList Entry: 0x%I64X.\n", (DWORD_PTR)pCallbackEntry);
    46. printf("> Address of CallBacks: \n");
    47. // 遍历回调函数表
    48. while (pCallbackEntry->pCallbackFunc != NULL) {
    49. // 输出回调函数地址
    50. printf("\t\t\t> 0x%I64X\n", (DWORD_PTR)pCallbackEntry->pCallbackFunc);
    51. pCallbackEntry++;
    52. }
    53. // 卸载模块
    54. FreeLibrary(fileBaseAddress);
    55. return 0;
    56. }

    运行的效果很好:

    获取程序 TLS 回调函数地址的结果

    当获取完所有的 TLS 函数地址后,我们需要对每一个地址入口位置写入软件断点。

    程序可能执行任意一个它认为需要的 TLS 回调,我们在所有 TLS 可能进入的位置写入断点,就可以在程序执行到的第一个 TLS 回调开始前中断。我们可以在中断后,恢复所有断点处的原始字节,并进行远程线程注入。此时所有线程处于挂起状态,只需要 ContinueDebugEvent 释放进程,并使用 DebugActiveProcessStop 函数结束调试模式,使得调试器分离。这样,就完成了整个注入过程。

    注入的处理过程如下(在新线程 ThreadProc 中执行远程线程注入,不影响在此线程进行的进程释放过程):

    1. typedef struct __pThreadFunc {
    2. LPCWSTR pszDllFileName;
    3. HANDLE hProcess;
    4. }pThreadFunc;
    5. UINT WINAPI OnInjectModuleHandler(
    6. DWORD dwProcessId,
    7. DWORD dwThreadId,
    8. HANDLE hProcess)
    9. {
    10. SetLastError(0);
    11. DWORD lpExitCode = 0;
    12. std::wstring dllModuleName = MODULE_DLL_NAME; // DLL 模块名称
    13. std::wstring dllModuleFullPath = GetDllModuleFullPath(dllModuleName);
    14. wprintf(L"Full path of DLL module: %s\n", dllModuleFullPath.c_str());
    15. static pThreadFunc pfn = { 0 };
    16. pfn.hProcess = hProcess;
    17. pfn.pszDllFileName = dllModuleFullPath.c_str();
    18. // 创建线程并在其中执行 ThreadProc 函数
    19. HANDLE hThread = CreateThread(NULL, 0, ThreadProc, (LPVOID)&pfn, 0, NULL);
    20. if (hThread == NULL)
    21. {
    22. // 处理无法创建线程的情况
    23. CloseHandle(hProcess);
    24. return ERROR_INITTHREAD;
    25. }
    26. if (!ContinueDebugEvent(
    27. dwProcessId,
    28. dwThreadId,
    29. DBG_CONTINUE
    30. ))
    31. {
    32. printf("Error: Continue Debug Event failed.\n");
    33. return ERROR_CONTINUE_DBG;
    34. }
    35. DebugActiveProcessStop(dwProcessId);
    36. // 等待线程结束
    37. WaitForSingleObject(hThread, INFINITE);
    38. GetExitCodeThread(hThread, &lpExitCode);
    39. if (lpExitCode != 0)
    40. {
    41. printf("ThreadProc > Error:%u\n", lpExitCode);
    42. // 关闭句柄
    43. CloseHandle(hThread);
    44. return ERROR_INJECTFAILED;
    45. }
    46. // 关闭句柄
    47. CloseHandle(hThread);
    48. CloseHandle(hProcess);
    49. return DMSG_COMPLETED;
    50. }

    3.5 完整代码和测试结果

    HOOK 模块代码见 2.5 节最后一段内容即可(已经更新为最新代码)。

    完整的调试注入器代码如下:

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. #define DMSG_ERRORSUCCESS 0
    7. #define DMSG_ONEXITPROC 1
    8. #define DMSG_ONTLSCALLBACK 2
    9. #define DMSG_NOTHANDLED 3
    10. #define DMSG_COMPLETED 4
    11. #define ERROR_CONTINUE_DBG 0xC00001
    12. #define ERROR_INJECTFAILED 0xC00002
    13. #define ERROR_INITTHREAD 0xC00003
    14. #define EXPLORER_ENDTASK_CODE 1
    15. #define MODULE_DLL_NAME L"GetMessageHook.dll"
    16. // 全局变量,用于存储 TLS 回调函数地址
    17. PVOID g_pTlsCallback = NULL;
    18. typedef void* DEBUG_STATUS;
    19. VOID* __fastcall AllocDMsgBuffer();
    20. VOID __fastcall ReleaseDMsgBuffer(LPVOID lpBuffer);
    21. errno_t __fastcall memset_s(void* v, rsize_t smax,
    22. int c, rsize_t n);
    23. std::wstring GetModulePath();
    24. std::wstring GetDllModuleFullPath(const std::wstring& dllModuleName);
    25. BOOL WINAPI SetSoftwareBreakpoint(
    26. HANDLE hProcess,
    27. LPVOID lpAddress,
    28. PBYTE lpByteBuffer
    29. );
    30. BOOL WINAPI ReleaseSoftwareBreakpoint(
    31. HANDLE hProcess,
    32. LPVOID lpAddress,
    33. const BYTE cByteBuffer
    34. );
    35. BOOL WINAPI OnInitCreateDebugExplorer(
    36. PDWORD lpProcessId);
    37. BOOL WINAPI OnCreateProcessEventHandler(
    38. HANDLE hProcess,
    39. LPVOID pImageBase,
    40. LPVOID lpTlsCallbackList,
    41. LPVOID lpByteBufferBase
    42. );
    43. UINT WINAPI OnDebugTlsEventHandler(
    44. HANDLE hProcess,
    45. const std::vector* lpBreakpoint,
    46. const std::vector* lpByteBuffer,
    47. LPVOID lpExceptionAddress
    48. );
    49. BOOL WINAPI InjectMouldeHandler(
    50. HANDLE hProcess,
    51. LPCWSTR pszDllFileName
    52. );
    53. DWORD WINAPI ThreadProc(LPVOID lpParam);
    54. UINT WINAPI OnInjectModuleHandler(
    55. DWORD dwProcessId,
    56. DWORD dwThreadId,
    57. HANDLE hProcess
    58. );
    59. UINT CALLBACK DebugEventCallback(
    60. DEBUG_EVENT& debugEvent,
    61. DEBUG_STATUS lpStatus
    62. );
    63. typedef struct _WND_INFO
    64. {
    65. HWND hWnd;
    66. DWORD dwPid;
    67. DWORD dwTid;
    68. std::wstring strClass;
    69. std::wstring strText;
    70. }WND_INFO;
    71. typedef struct __DEBUGMSGSTRUCT
    72. {
    73. HANDLE hProcess;
    74. HANDLE hThread;
    75. LPVOID lpImageBase;
    76. //SIZE_T cbBreakPoints;
    77. std::vector* lpBreakpoint;
    78. //SIZE_T cbByte;
    79. std::vector* ctByteBuffer;
    80. }DEBUGMSGSTRUCT, * PDEBUGMSGSTRUCT;
    81. // TLS 回调函数表结构
    82. typedef struct _IMAGE_TLS_CALLBACK_ENTRY {
    83. struct _IMAGE_TLS_CALLBACK_ENTRY* pNext;
    84. PIMAGE_TLS_CALLBACK pCallbackFunc;
    85. LPVOID pCallbackContext;
    86. } IMAGE_TLS_CALLBACK_ENTRY, * PIMAGE_TLS_CALLBACK_ENTRY;
    87. BOOL OnInitCheckShellProcess();
    88. int main()
    89. {
    90. _wsetlocale(LC_ALL, L".UTF8"); // 设置代码页
    91. DEBUGMSGSTRUCT* lpStatusStruct = nullptr;
    92. DWORD dwProcessId = 0;
    93. if (!OnInitCheckShellProcess())
    94. {
    95. printf("Error: The task cannot continue.\n");
    96. return -1;
    97. }
    98. // 为结构体分配内存
    99. lpStatusStruct = (DEBUGMSGSTRUCT*)AllocDMsgBuffer();
    100. if (lpStatusStruct == nullptr)
    101. {
    102. printf("Error: Alloc DMsg Buffer failed.\n");
    103. return -1;
    104. }
    105. // 创建调试进程
    106. if (!OnInitCreateDebugExplorer(&dwProcessId))
    107. {
    108. printf("Error: Init debuggie process failed.\n");
    109. return -1;
    110. }
    111. // 处理调试事件
    112. int dwStatus = 0;
    113. DEBUG_EVENT debugEvent;
    114. while (WaitForDebugEvent(&debugEvent, INFINITE))
    115. {
    116. // 执行回调函数
    117. UINT uResponse = DebugEventCallback(debugEvent, lpStatusStruct);
    118. // 检查 switch-case 内是否指示了一个 break
    119. if (uResponse != DMSG_ERRORSUCCESS)
    120. {
    121. break;
    122. }
    123. }
    124. // 释放分配给 DMSG 的内存
    125. ReleaseDMsgBuffer(lpStatusStruct);
    126. lpStatusStruct = nullptr;
    127. return dwStatus;
    128. }
    129. // 该函数用于终止 explorer 进程
    130. BOOL OnInitCheckShellProcess()
    131. {
    132. HWND hWnd = nullptr;
    133. HANDLE hProcess = nullptr;
    134. DWORD dwProcess = 0;
    135. BOOL dwStatus = 0;
    136. hWnd = GetShellWindow();
    137. SetLastError(0);
    138. if (hWnd != NULL)
    139. {
    140. GetWindowThreadProcessId(hWnd, &dwProcess);
    141. if (dwProcess)
    142. {
    143. hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, dwProcess);
    144. if (hProcess)
    145. {
    146. if (IDYES == MessageBoxW(GetConsoleWindow(),
    147. L"EXPLORER is still running, we will restart it.",
    148. L"NOTICE: Is restart explorer now?",
    149. MB_APPLMODAL | MB_ICONINFORMATION | MB_YESNO))
    150. {
    151. // 结束 explorer 进程
    152. dwStatus = TerminateProcess(hProcess, EXPLORER_ENDTASK_CODE);
    153. if (dwStatus)
    154. {
    155. wprintf(L"Terminate explorer process successfully.\n");
    156. Sleep(3000);
    157. return TRUE;
    158. }
    159. else {
    160. wprintf(L"Terminate explorer process failed, error(%u).\n",
    161. GetLastError());
    162. return FALSE;
    163. }
    164. }
    165. else {
    166. wprintf(L"Cancelled restart explorer process.\n");
    167. return FALSE;
    168. }
    169. }
    170. else {
    171. wprintf(L"Open explorer process failed, error(%u).\n",
    172. GetLastError());
    173. return FALSE;
    174. }
    175. }
    176. else {
    177. wprintf(L"Get explorer process id failed, error(%u).\n",
    178. GetLastError());
    179. return FALSE;
    180. }
    181. }
    182. else {
    183. wprintf(L"Get shell windows handle failed, error(%u).\n",
    184. GetLastError());
    185. return FALSE;
    186. }
    187. }
    188. std::wstring GetModulePath()
    189. {
    190. wchar_t modulePath[MAX_PATH];
    191. GetModuleFileName(NULL, modulePath, MAX_PATH);
    192. // 获取程序路径
    193. std::wstring fullPath(modulePath);
    194. // 去除程序名称,只保留路径
    195. size_t lastSlashIndex = fullPath.find_last_of(L"\\");
    196. std::wstring programPath = fullPath.substr(0, lastSlashIndex + 1);
    197. return programPath;
    198. }
    199. std::wstring GetDllModuleFullPath(const std::wstring& dllModuleName)
    200. {
    201. std::wstring programPath = GetModulePath();
    202. // 合成完整的DLL模块路径
    203. std::wstring dllModuleFullPath = programPath + dllModuleName;
    204. return dllModuleFullPath;
    205. }
    206. // 调试事件处理函数
    207. UINT CALLBACK DebugEventCallback(
    208. DEBUG_EVENT& debugEvent,
    209. DEBUG_STATUS lpStatus
    210. )
    211. {
    212. DWORD dwContinueStatus = DBG_CONTINUE;
    213. UINT uMsgResponse = 0;
    214. PDEBUGMSGSTRUCT lpMsgStruct = (PDEBUGMSGSTRUCT)lpStatus;
    215. switch (debugEvent.dwDebugEventCode)
    216. {
    217. case CREATE_PROCESS_DEBUG_EVENT:
    218. {
    219. PDEBUGMSGSTRUCT lpMsgStruct = (PDEBUGMSGSTRUCT)lpStatus;
    220. lpMsgStruct->hProcess = debugEvent.u.CreateProcessInfo.hProcess;
    221. lpMsgStruct->hThread = debugEvent.u.CreateProcessInfo.hThread;
    222. lpMsgStruct->lpImageBase = debugEvent.u.CreateProcessInfo.lpBaseOfImage;
    223. DWORD_PTR TlsCallback = 0, lpByteBuffer = 0;
    224. if (!OnCreateProcessEventHandler(lpMsgStruct->hProcess, lpMsgStruct->lpImageBase,
    225. &TlsCallback, &lpByteBuffer))
    226. {
    227. printf("Error: OnCreateProcessEventHandler failed.\n");
    228. uMsgResponse = 0xC00001;
    229. break;
    230. }
    231. //lpMsgStruct->cbBreakPoints = 1;
    232. //lpMsgStruct->cbByte = 1;
    233. lpMsgStruct->lpBreakpoint = (std::vector*)TlsCallback;
    234. lpMsgStruct->ctByteBuffer = (std::vector*)lpByteBuffer;
    235. break;
    236. }
    237. case EXCEPTION_DEBUG_EVENT:
    238. {
    239. // 判断是否为调试器引起的异常
    240. if (debugEvent.u.Exception.dwFirstChance == FALSE)
    241. {
    242. printf("Warnning: Exception First Chance!\n");
    243. // 返回 DBG_EXCEPTION_NOT_HANDLED 交给程序自身的 SEH 处理
    244. dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
    245. return DMSG_NOTHANDLED;
    246. }
    247. // 捕获到断点异常
    248. if (debugEvent.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
    249. {
    250. debugEvent.u.Exception.dwFirstChance += 1;
    251. const LPVOID lpExceptionAddress =
    252. debugEvent.u.Exception.ExceptionRecord.ExceptionAddress;
    253. const std::vector* lpBreakpoint = lpMsgStruct->lpBreakpoint;
    254. const std::vector* lpByteBuffer = lpMsgStruct->ctByteBuffer;
    255. HANDLE hProcess = lpMsgStruct->hProcess;
    256. uMsgResponse = OnDebugTlsEventHandler(hProcess, lpBreakpoint,
    257. lpByteBuffer, lpExceptionAddress);
    258. }
    259. break;
    260. }
    261. case EXIT_PROCESS_DEBUG_EVENT:
    262. uMsgResponse = DMSG_ONEXITPROC;
    263. break;
    264. default:
    265. dwContinueStatus = DBG_CONTINUE;
    266. // printf("dwDebugEventCode unHandled: %u\n", debugEvent.dwDebugEventCode);
    267. break;
    268. }
    269. // 判断接下来的操作
    270. if (uMsgResponse == DMSG_ERRORSUCCESS) // 继续执行
    271. {
    272. if (!ContinueDebugEvent(
    273. debugEvent.dwProcessId,
    274. debugEvent.dwThreadId,
    275. dwContinueStatus
    276. ))
    277. {
    278. uMsgResponse = ERROR_CONTINUE_DBG;
    279. }
    280. }
    281. else if (uMsgResponse == DMSG_ONTLSCALLBACK) // 准备注入
    282. {
    283. uMsgResponse = OnInjectModuleHandler(debugEvent.dwProcessId,
    284. debugEvent.dwThreadId, lpMsgStruct->hProcess);
    285. if (uMsgResponse == DMSG_COMPLETED) { // 完成注入
    286. printf("Procedure Completed.\n");
    287. }
    288. }
    289. else { // 调试异常,准备终止被调试进程
    290. TerminateProcess(lpMsgStruct->hProcess, 0);
    291. }
    292. return uMsgResponse;
    293. }
    294. BOOL WINAPI OnInitCreateDebugExplorer(PDWORD lpProcessId)
    295. {
    296. // 要调试的进程路径
    297. LPCWSTR lpApplicationName = L"C:\\Windows\\explorer.exe";
    298. // 启动进程并进入调试模式
    299. STARTUPINFOW si = { 0 };
    300. PROCESS_INFORMATION pi = { 0 };
    301. memset(&si, 0, sizeof(si));
    302. memset(&pi, 0, sizeof(pi));
    303. si.cb = sizeof(si);
    304. if (!CreateProcessW(lpApplicationName, NULL, NULL, NULL, FALSE,
    305. DEBUG_ONLY_THIS_PROCESS | CREATE_NEW_CONSOLE,
    306. NULL, NULL, &si, &pi))
    307. {
    308. printf("Error: Failed to create debug process!\n");
    309. return FALSE;
    310. }
    311. *lpProcessId = pi.dwProcessId;
    312. CloseHandle(pi.hProcess);
    313. CloseHandle(pi.hThread);
    314. return TRUE;
    315. }
    316. BOOL WINAPI OnCreateProcessEventHandler(
    317. HANDLE hProcess,
    318. LPVOID pImageBase,
    319. LPVOID lpTlsCallbackList,
    320. LPVOID lpByteBufferBase
    321. )
    322. {
    323. static std::vector tlsCallbackList;
    324. static std::vector ctByteBuffer;
    325. BYTE lpByteBuffer = 0;
    326. IMAGE_DOS_HEADER pDosHeader = { 0 };
    327. ReadProcessMemory(hProcess, pImageBase, &pDosHeader, sizeof(IMAGE_DOS_HEADER), NULL);
    328. IMAGE_NT_HEADERS pNtHeaders = { 0 };
    329. ReadProcessMemory(hProcess, (LPVOID)((DWORD_PTR)pImageBase + pDosHeader.e_lfanew),
    330. &pNtHeaders, sizeof(IMAGE_NT_HEADERS), NULL);
    331. PIMAGE_OPTIONAL_HEADER pOptionalHeader = &pNtHeaders.OptionalHeader;
    332. PIMAGE_DATA_DIRECTORY pDataDirectory = &pOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS];
    333. IMAGE_TLS_DIRECTORY pTlsDirectory = { 0 };
    334. PIMAGE_TLS_CALLBACK_ENTRY pCallbackEntry = nullptr;
    335. IMAGE_TLS_CALLBACK_ENTRY tlsCallback = { 0 };
    336. BOOL ret = FALSE;
    337. // 获取 TLS 回调函数地址
    338. if (pDataDirectory->VirtualAddress != 0 && pDataDirectory->Size != 0)
    339. {
    340. ReadProcessMemory(hProcess, (LPVOID)((DWORD_PTR)pImageBase
    341. + pDataDirectory->VirtualAddress),
    342. &pTlsDirectory, sizeof(IMAGE_TLS_DIRECTORY), NULL);
    343. pCallbackEntry =
    344. (PIMAGE_TLS_CALLBACK_ENTRY)((DWORD_PTR)pTlsDirectory.AddressOfCallBacks - pDosHeader.e_lfanew);
    345. ReadProcessMemory(hProcess, (LPVOID)(pCallbackEntry),
    346. &tlsCallback, sizeof(tlsCallback), NULL);
    347. printf("TlsCallbackFuncEntry: 0x%I64X.\n", (DWORD_PTR)pCallbackEntry);
    348. while (tlsCallback.pCallbackFunc != nullptr) {
    349. tlsCallbackList.push_back((DWORD_PTR)tlsCallback.pCallbackFunc);
    350. pCallbackEntry++;
    351. memset_s(&tlsCallback, sizeof(tlsCallback), 0, sizeof(tlsCallback));
    352. ReadProcessMemory(hProcess, (LPVOID)(pCallbackEntry),
    353. &tlsCallback, sizeof(tlsCallback), NULL);
    354. }
    355. for (size_t i = 0; i < tlsCallbackList.size(); i++)
    356. {
    357. // 写入软件断点
    358. printf("Wrtie Software Breakpoint at: 0x%I64X\n", tlsCallbackList[i]);
    359. lpByteBuffer = 0;
    360. ret = SetSoftwareBreakpoint(hProcess, (LPVOID)tlsCallbackList[i], &lpByteBuffer);
    361. ctByteBuffer.push_back(lpByteBuffer);
    362. }
    363. // 将指针地址拷贝到结构体中
    364. DWORD_PTR tlsCallbaskListEntry = reinterpret_cast(&tlsCallbackList);
    365. DWORD_PTR ctByteBufferBase = reinterpret_cast(&ctByteBuffer);
    366. memcpy(lpTlsCallbackList, &tlsCallbaskListEntry, sizeof(DWORD_PTR));
    367. memcpy(lpByteBufferBase, &ctByteBufferBase, sizeof(DWORD_PTR));
    368. }
    369. return ret;
    370. }
    371. UINT WINAPI OnDebugTlsEventHandler(
    372. HANDLE hProcess,
    373. const std::vector* lpBreakpoint,
    374. const std::vector* lpByteBuffer,
    375. LPVOID lpExceptionAddress
    376. )
    377. {
    378. UINT dwStatus = 0;
    379. std::vector TlsCallbackList =
    380. *lpBreakpoint;
    381. std::vector ctOriByteBuffer = *lpByteBuffer;
    382. DWORD_PTR dwExceptionAddress =
    383. reinterpret_cast(lpExceptionAddress);
    384. for (size_t index = 0; index < TlsCallbackList.size(); index++)
    385. {
    386. if (dwExceptionAddress == TlsCallbackList[index])
    387. {
    388. #ifdef _DEBUG
    389. MessageBoxW(NULL, L"执行到第一个 TLS 函数入口点", L"Debug 提示信息", MB_OK);
    390. #endif // DEBUG
    391. printf("First tlsCallBack function address: 0x%I64X.\n", TlsCallbackList[index]);
    392. dwStatus = DMSG_ONTLSCALLBACK;
    393. break;
    394. }
    395. }
    396. if (dwStatus != DMSG_ONTLSCALLBACK)
    397. {
    398. printf("System Breakpoint at: 0x%I64X.\n", dwExceptionAddress);
    399. }
    400. else {
    401. for (size_t index = 0; index < TlsCallbackList.size(); index++)
    402. {
    403. LPVOID tlsCallbackFunc = reinterpret_cast(TlsCallbackList[index]);
    404. // 恢复原始字节
    405. if (!ReleaseSoftwareBreakpoint(hProcess, tlsCallbackFunc,
    406. ctOriByteBuffer[index]))
    407. {
    408. printf("Release Breakpoint failed: 0x%I64X.\n", TlsCallbackList[index]);
    409. dwStatus = 0xC00002;
    410. break;
    411. }
    412. printf("Release Software Breakpoint at: 0x%I64X.\n", TlsCallbackList[index]);
    413. }
    414. }
    415. return dwStatus;
    416. }
    417. typedef struct __pThreadFunc {
    418. LPCWSTR pszDllFileName;
    419. HANDLE hProcess;
    420. }pThreadFunc;
    421. UINT WINAPI OnInjectModuleHandler(
    422. DWORD dwProcessId,
    423. DWORD dwThreadId,
    424. HANDLE hProcess)
    425. {
    426. SetLastError(0);
    427. DWORD lpExitCode = 0;
    428. std::wstring dllModuleName = MODULE_DLL_NAME; // DLL 模块名称
    429. std::wstring dllModuleFullPath = GetDllModuleFullPath(dllModuleName);
    430. wprintf(L"Full path of DLL module: %s\n", dllModuleFullPath.c_str());
    431. //LPCWSTR pszDllFileName = ; // 要注入的 DLL 文件路径
    432. static pThreadFunc pfn = { 0 };
    433. pfn.hProcess = hProcess;
    434. pfn.pszDllFileName = dllModuleFullPath.c_str();
    435. // 创建线程并在其中执行 ThreadProc 函数
    436. HANDLE hThread = CreateThread(NULL, 0, ThreadProc, (LPVOID)&pfn, 0, NULL);
    437. if (hThread == NULL)
    438. {
    439. // 处理无法创建线程的情况
    440. CloseHandle(hProcess);
    441. return ERROR_INITTHREAD;
    442. }
    443. if (!ContinueDebugEvent(
    444. dwProcessId,
    445. dwThreadId,
    446. DBG_CONTINUE
    447. ))
    448. {
    449. printf("Error: Continue Debug Event failed.\n");
    450. return ERROR_CONTINUE_DBG;
    451. }
    452. DebugActiveProcessStop(dwProcessId);
    453. // 等待线程结束
    454. WaitForSingleObject(hThread, INFINITE);
    455. GetExitCodeThread(hThread, &lpExitCode);
    456. if (lpExitCode != 0)
    457. {
    458. printf("ThreadProc > Error:%u\n", lpExitCode);
    459. // 关闭句柄
    460. CloseHandle(hThread);
    461. return ERROR_INJECTFAILED;
    462. }
    463. // 关闭句柄
    464. CloseHandle(hThread);
    465. CloseHandle(hProcess);
    466. return DMSG_COMPLETED;
    467. }
    468. DWORD WINAPI ThreadProc(LPVOID lpParam)
    469. {
    470. pThreadFunc* pfn = (pThreadFunc*)lpParam;
    471. // 在线程中执行注入函数
    472. if (!InjectMouldeHandler(pfn->hProcess, pfn->pszDllFileName))
    473. {
    474. printf("ThreadProc > Inject Hook Module failed.\n");
    475. return ERROR_MOD_NOT_FOUND;
    476. }
    477. printf("ThreadProc > Inject Hook Module Success!\n");
    478. // 线程结束,返回退出代码
    479. return ERROR_SUCCESS; // 操作成功完成
    480. }
    481. BOOL WINAPI InjectMouldeHandler(
    482. HANDLE hTargetProcess,
    483. LPCWSTR pszDllFileName
    484. )
    485. {
    486. // 1.目标进程句柄
    487. if (hTargetProcess == nullptr || pszDllFileName == nullptr)
    488. {
    489. wprintf(L"Error: InvalidSyntax error from InjectMouldeHandler.\n");
    490. SetLastError(ERROR_INVALID_PARAMETER);
    491. return FALSE;
    492. }
    493. size_t pathSize = (wcslen(pszDllFileName) + 1) * sizeof(wchar_t);
    494. SetLastError(0);
    495. // 2.在目标进程中申请空间
    496. LPVOID lpPathAddr = VirtualAllocEx(hTargetProcess, 0, pathSize,
    497. MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
    498. if (NULL == lpPathAddr)
    499. {
    500. wprintf(L"Error[%d]: Failed to apply memory in the target process!\n", GetLastError());
    501. return FALSE;
    502. }
    503. SetLastError(0);
    504. // 3.在目标进程中写入 Dll 路径
    505. if (FALSE == WriteProcessMemory(hTargetProcess, lpPathAddr,
    506. pszDllFileName, pathSize, NULL))
    507. {
    508. wprintf(L"Error[%d]: Failed to write module path in target process!\n", GetLastError());
    509. return FALSE;
    510. }
    511. SetLastError(0);
    512. // 4.加载 ntdll.dll
    513. HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
    514. if (NULL == hNtdll)
    515. {
    516. wprintf(L"Error[%d]: Failed to load NTDLL.DLL!\n", GetLastError());
    517. VirtualFreeEx(hTargetProcess, lpPathAddr, 0, MEM_RELEASE);
    518. return FALSE;
    519. }
    520. SetLastError(0);
    521. // 5.获取 LoadLibraryW 的函数地址, FARPROC 可以自适应 32 位与 64 位
    522. FARPROC pFuncProcAddr = GetProcAddress(GetModuleHandleW(L"KernelBase.dll"),
    523. "LoadLibraryW");
    524. if (NULL == pFuncProcAddr)
    525. {
    526. wprintf(L"Error[%d]: Failed to obtain the address of the LoadLibrary function!\n",
    527. GetLastError());
    528. VirtualFreeEx(hTargetProcess, lpPathAddr, 0, MEM_RELEASE);
    529. return FALSE;
    530. }
    531. // 6.获取 NtCreateThreadEx 函数地址,该函数在32位与64位下原型不同
    532. // _WIN64 用来判断编译环境 ,_WIN32用来判断是否是 Windows 系统
    533. #ifdef _WIN64
    534. typedef DWORD(WINAPI* __NtCreateThreadEx)(
    535. PHANDLE ThreadHandle,
    536. ACCESS_MASK DesiredAccess,
    537. LPVOID ObjectAttributes,
    538. HANDLE ProcessHandle,
    539. LPTHREAD_START_ROUTINE lpStartAddress,
    540. LPVOID lpParameter,
    541. ULONG CreateThreadFlags,
    542. SIZE_T ZeroBits,
    543. SIZE_T StackSize,
    544. SIZE_T MaximumStackSize,
    545. LPVOID pUnkown
    546. );
    547. #else
    548. typedef DWORD(WINAPI* __NtCreateThreadEx)(
    549. PHANDLE ThreadHandle,
    550. ACCESS_MASK DesiredAccess,
    551. LPVOID ObjectAttributes,
    552. HANDLE ProcessHandle,
    553. LPTHREAD_START_ROUTINE lpStartAddress,
    554. LPVOID lpParameter,
    555. BOOL CreateSuspended,
    556. DWORD dwStackSize,
    557. DWORD dw1,
    558. DWORD dw2,
    559. LPVOID pUnkown
    560. );
    561. #endif
    562. SetLastError(0);
    563. __NtCreateThreadEx NtCreateThreadEx =
    564. (__NtCreateThreadEx)GetProcAddress(hNtdll, "NtCreateThreadEx");
    565. if (NULL == NtCreateThreadEx)
    566. {
    567. wprintf(L"Error[%d]: Failed to obtain NtCreateThreadEx function address!\n",
    568. GetLastError());
    569. VirtualFreeEx(hTargetProcess, lpPathAddr, 0, MEM_RELEASE);
    570. return FALSE;
    571. }
    572. SetLastError(0);
    573. // 7.在目标进程中创建远线程
    574. HANDLE hRemoteThread = NULL;
    575. DWORD lpExitCode = 0;
    576. DWORD dwStatus = NtCreateThreadEx(&hRemoteThread, PROCESS_ALL_ACCESS, NULL,
    577. hTargetProcess,
    578. (LPTHREAD_START_ROUTINE)pFuncProcAddr, lpPathAddr, 0, 0, 0, 0, NULL);
    579. if (NULL == hRemoteThread)
    580. {
    581. wprintf(L"Error[%d]: Failed to create thread in target process!\n", GetLastError());
    582. VirtualFreeEx(hTargetProcess, lpPathAddr, 0, MEM_RELEASE);
    583. return FALSE;
    584. }
    585. SetLastError(0);
    586. // 8.等待线程结束
    587. if (WAIT_TIMEOUT == WaitForSingleObject(hRemoteThread, INFINITE))
    588. {
    589. wprintf(L"Error[%d]: Remote thread not responding.\n", GetLastError());
    590. VirtualFreeEx(hTargetProcess, lpPathAddr, 0, MEM_RELEASE);
    591. return FALSE;
    592. }
    593. GetExitCodeThread(hRemoteThread, &lpExitCode);
    594. if (lpExitCode == 0)
    595. {
    596. wprintf(L"Error: Injection module failed in the target process.\n");
    597. VirtualFreeEx(hTargetProcess, lpPathAddr, 0, MEM_RELEASE);
    598. return FALSE;
    599. }
    600. // 9.清理环境
    601. VirtualFreeEx(hTargetProcess, lpPathAddr, 0, MEM_RELEASE);
    602. CloseHandle(hRemoteThread);
    603. return TRUE;
    604. }
    605. BOOL WINAPI SetSoftwareBreakpoint(
    606. HANDLE hProcess,
    607. LPVOID lpAddress,
    608. PBYTE lpByteBuffer
    609. )
    610. {
    611. DWORD oldProtect;
    612. BOOL vPret = FALSE;
    613. vPret = VirtualProtectEx(hProcess, lpAddress, 1, PAGE_EXECUTE_READWRITE, &oldProtect);
    614. if (vPret == FALSE)
    615. {
    616. return vPret;
    617. }
    618. vPret = ReadProcessMemory(hProcess, lpAddress, lpByteBuffer, 1, NULL); // 保存原始字节
    619. if (vPret == FALSE)
    620. {
    621. VirtualProtectEx(hProcess, lpAddress, 1, oldProtect, &oldProtect);
    622. return vPret;
    623. }
    624. vPret = WriteProcessMemory(hProcess, lpAddress, "\xCC", 1, NULL); // \xCC 是 INT 3 指令,用于产生软件断点
    625. if (vPret == FALSE)
    626. {
    627. VirtualProtectEx(hProcess, lpAddress, 1, oldProtect, &oldProtect);
    628. return vPret;
    629. }
    630. vPret = VirtualProtectEx(hProcess, lpAddress, 1, oldProtect, &oldProtect);
    631. if (vPret == FALSE)
    632. {
    633. WriteProcessMemory(hProcess, lpAddress, lpByteBuffer, 1, NULL);
    634. return vPret;
    635. }
    636. return TRUE;
    637. }
    638. BOOL WINAPI ReleaseSoftwareBreakpoint(
    639. HANDLE hProcess,
    640. LPVOID lpAddress,
    641. const BYTE cByteBuffer
    642. )
    643. {
    644. DWORD oldProtect;
    645. BOOL vPret = FALSE;
    646. vPret = VirtualProtectEx(hProcess, lpAddress, 1, PAGE_EXECUTE_READWRITE, &oldProtect);
    647. if (vPret == FALSE)
    648. {
    649. return vPret;
    650. }
    651. vPret = WriteProcessMemory(hProcess, lpAddress, &cByteBuffer, 1, NULL); // 恢复原始字节
    652. if (vPret == FALSE)
    653. {
    654. VirtualProtectEx(hProcess, lpAddress, 1, oldProtect, &oldProtect);
    655. return vPret;
    656. }
    657. vPret = VirtualProtectEx(hProcess, lpAddress, 1, oldProtect, &oldProtect);
    658. if (vPret == FALSE)
    659. {
    660. return vPret;
    661. }
    662. return TRUE;
    663. }
    664. errno_t __fastcall memset_s(void* v, rsize_t smax, int c, rsize_t n) {
    665. if (v == NULL) return EINVAL;
    666. if (smax > RSIZE_MAX) return EINVAL;
    667. if (n > smax) return EINVAL;
    668. volatile unsigned char* p = (volatile unsigned char*)v;
    669. while (smax-- && n--) {
    670. *p++ = c;
    671. }
    672. return 0;
    673. }
    674. VOID* __fastcall AllocDMsgBuffer()
    675. {
    676. LPVOID lpStatusStruct = malloc(sizeof(DEBUGMSGSTRUCT));
    677. if (lpStatusStruct == nullptr)
    678. {
    679. return NULL;
    680. }
    681. if (EINVAL == memset_s(lpStatusStruct,
    682. sizeof(DEBUGMSGSTRUCT),
    683. 0, sizeof(DEBUGMSGSTRUCT)))
    684. {
    685. free(lpStatusStruct);
    686. return NULL;
    687. }
    688. return lpStatusStruct;
    689. }
    690. VOID __fastcall ReleaseDMsgBuffer(LPVOID lpBuffer)
    691. {
    692. if (lpBuffer == nullptr)
    693. {
    694. return;
    695. }
    696. if (EINVAL == memset_s(lpBuffer,
    697. sizeof(DEBUGMSGSTRUCT),
    698. 0, sizeof(DEBUGMSGSTRUCT)))
    699. {
    700. return;
    701. }
    702. free(lpBuffer);
    703. }

    询问重启资源管理器:

    询问是否重启资源管理器

    P.S.:重启资源管理器有官方支持的方法,你可以在代码中改用重启管理器接口(Restart Manager API),可以见 4.1 的代码中就运用了 RM 重启 explorer 。

    调试注入器可以成功注入 HOOK 模块:

    调试注入器截图

    记录的日志内容如下:

    测试日志记录截图[新版]

    3.6 补充说明

    对于要在启动系统时使用该工具,则可以删除掉关闭进程前的询问环节。可以将程序编写为服务程序或者使用注册表。具体解释如下:

    1)服务进程可以在系统登陆前启动,此时就可以重启并注入 explorer 进程。

    2)使用映像文件执行选项并将注入器程序注册为“调试器”(有关详细信息,请参阅 “如何:自动启动调试器”)。

    原理很简单:

    HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options 项下添加一个包含目标进程名称的项(例如 explorer.exe)。
    在此键下,添加一个名为 debugger 的新字符串值。
    将值设置为修改二进制文件的路径名。这必须是完全限定的路径名​​,或者图像位置必须位于 PATH 环境变量中。
    每当启动 explorer.exe 时,注入器二进制文件都会在加载 explorer.exe(及其依赖项)之后、执行开始之前启动。无论 explorer.exe 如何启动,都会发生这种情况。

    另请注意,在 64 位操作系统上,密钥也会反映在 Wow6432Node 中,因此注入器二进制文件将同时针对 32 位和 64 位版本的 explorer.exe 启动。

    4 初步分析系统托盘图标的注册表转储

    4.1 传统的注册表转储信息

    在 Win11 之前,系统通过 IconStreams 和 PastIconsStream(可能没有) 两个注册表值项获取 explorer 的通知图标信息,他们位于:

    [HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\TrayNotify]

    该注册表具有一个映射位置,只要修改一处即可:

    [HKEY_CLASSES_ROOT\Local Settings\Software\Microsoft\Windows\CurrentVersion\TrayNotify]

    其中一个页面如下图所示:

    TrayNotify 注册表

    这里面一般只存储缓存数据,explorer 会在关闭时将内存中的数据写回到磁盘上的注册表中。

    关于它的参数构成可以参考一篇外文博客:Windows 7 Notification Area Automation

    下面摘选翻译部分内容:

    任务托盘的通知设置以二进制注册表项的形式存储在注册表 HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\TrayNotify 的 IconStreams 值中。对我们来说幸运的是,按键的组织并不像收藏夹栏那样难以理解。二进制流以 20 字节标头开始,后跟 X 个 1640 字节项目,其中 X 是具有通知设置的项目数。每个 1640 字节块至少由(其中一个部分未完全解码,因此它可能由 2 个或更多部分组成)5 个固定字节宽度部分组成,如下所示:

    • 528 字节 – 可执行文件的路径
    • 4 字节 – 通知可见性设置
    • 512 字节 – 最后可见的工具提示
    • 592 字节 – 未知(似乎嵌入了第二个工具提示,但块中的起始位置发生了变化)
    • 4 字节——UID

    出于我的自动化目的,前两个块将非常有用。首先,我们要求两个命令行参数,区分大小写的程序名称(通常是程序的可执行文件)和设置值。允许的设置值为:

    • 0 = 仅显示通知
    • 1 = 隐藏图标和通知
    • 2 = 显示图标和通知

    然后,我们从注册表中读取当前值并将其存储在字节数组中,然后创建字节数组的字符串表示形式以在其中搜索应用程序。

    然后,我们将字节数组和字符串中提供的应用程序名称与注册表值一起编码,然后在注册表项中搜索应用程序。如果没有找到,我们会抛出一个错误并退出。否则我们继续。

    然后,我们将标头存储在它自己的字节数组中(我们不使用这个标头,但如果将来需要它,我们已经有了隔离它的代码)。之后,我们循环遍历剩余的字节,一次 1640 个字节,并将每个块存储在它自己的数组中,该数组又使用起始字节位置作为其键放置在哈希表中。

    最后,我们循环遍历每个键并再次搜索应用程序。如果找到,我们将第 529 个字节设置为等于传入的设置值,然后将字节数组写回注册表。

    精明的脚本阅读器和新手密码学家会注意到我们的老朋友 ROT13。事实证明,微软不想让我们使用这个密钥,所以他们在其内容上使用了牢不可破的 ROT13 算法。 ROT13 是一种数学替换密码(它比听起来简单得多),它将每个字母字符向前推进 13 个字母,因此 A=NB=OC=PD=Q 等等。我创建了一个函数,以区分大小写的方式处理此问题并根据需要调用它。

    现在我们有了脚本,但还有最后一个问题。当资源管理器加载时,IconStreams 注册表值由 Explorer.exe 读入内存,并且对通知区域的所有更改都存储在内存中,然后在关闭时写入注册表。这意味着,如果我们运行脚本,我们不仅不会立即看到任何结果,而且当我们重新启动计算机时,这些结果将被当前设置覆盖。不好。但这是一个简单的修复。我们从批处理文件启动脚本,然后执行taskkill /im explorer.exe /f,然后执行脚本,然后重新启动 explorer.exe。

    目前网上大多数都是 PureBasic 和 PowerShell 脚本实现:

    使用 C/Java 等代码的较少,而且多数脚本的使用并不是太方便,所以我结合多篇文献自己实现了一个修改图标可见性的命令提示符工具 SysTrayIconTool ,使用 C++ 风格的代码。(关于代码的具体讲解见第 3 篇文章)

    参数功能说明:

    • 【/show】 或者 【/showall】:解码系统通知栏所有图标的注册表摘要信息。
    • 【/clear】 或者 【/clearreg】:清除注册表图标缓存信息(严重警告:该操作将彻底清空配置文件),仅限配置异常或冗余时使用。
    • 【/find】【PathName】:通过映像的绝对 Win32 路径匹配注册表信息。程序输出图标可见度级别信息。
    • 【/fuzzyfind】【PathName】:在不知道图标的完整路径情况下,允许模糊查找所有包含特征字符串的图标信息。
    • 【/exactsetval】【PathName】【0/1/2】:通过映像的 Win32 路径修改注册表中图标的可见性级别信息,支持系统文件和当前目录文件的相对路径。
    • 【/setvalfuzzy】【BaseName】【0/1/2】:允许在不知道图标完整路径的情况下批量修改包含特定字符串的图标信息。

    程序需要提升管理员权限!完整代码如下:

    1. /**********************************************************************************************************************
    2. * ______ __ __ ______ _________ ______ ________ __ __ ________ ______ ______ ___ __
    3. * /_____/\ /_/\/_/\ /_____/\ /________/\/_____/\ /_______/\ /_/\/_/\ /_______/\/_____/\ /_____/\ /__/\ /__/\
    4. * \::::_\/_\ \ \ \ \\::::_\/_\__.::.__\/\:::_ \ \ \::: _ \ \\ \ \ \ \\__.::._\/\:::__\/ \:::_ \ \\::\_\\ \ \
    5. * \:\/___/\\:\_\ \ \\:\/___/\ \::\ \ \:(_) ) )_\::(_) \ \\:\_\ \ \ \::\ \ \:\ \ __\:\ \ \ \\:. `-\ \ \
    6. * \_::._\:\\::::_\/ \_::._\:\ \::\ \ \: __ `\ \\:: __ \ \\::::_\/ _\::\ \__\:\ \/_/\\:\ \ \ \\:. _ \ \
    7. * /____\:\ \::\ \ /____\:\ \::\ \ \ \ `\ \ \\:.\ \ \ \ \::\ \ /__\::\__/\\:\_\ \ \\:\_\ \ \\. \ `_ \ \
    8. * \_____\/ \__\/ \_____\/ \__\/ \_\/ \_\/ \__\/\__\/ \__\/ \________\/ \_____\/ \_____\/ \__\/ \__\/
    9. *
    10. *
    11. * FileName: SysTrayIconTool.cpp
    12. * Author: LianYou-516
    13. * Version: 1.0
    14. * Date: 2024/2/19
    15. * Description: This program is mainly used to modify the display status information
    16. * of the notification area icon on the taskbar. The search application's
    17. * pattern supports fuzzy matching and exact matching, with a total of
    18. * three levels of display status, which are:
    19. *
    20. * 0 = Display only notifications
    21. * 1 = Hide icons and notifications
    22. * 2 = Display icons and notifications
    23. * Modify the notification area icon display level of the program
    24. * by specifying one of these three.
    25. *
    26. * *********************************************************************************************************************
    27. */
    28. #include
    29. #include
    30. #include
    31. #include
    32. #include
    33. #include
    34. #include
    35. #include
    36. #include
    37. #include
    38. #include
    39. #pragma comment(lib, "Rstrtmgr.lib")
    40. #pragma comment(lib, "Shlwapi.lib")
    41. #define CS_DISPLAY_MODE 0x2L
    42. #define CS_FULLNAME_MODE 0x4L
    43. #define CS_BASENAME_MODE 0x8L
    44. #define CS_CHANGESETTINGS 0x150L
    45. #define TRAYNOTIFY_REG L"Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\CurrentVersion\\TrayNotify"
    46. #define ICON_STREAM L"IconStreams"
    47. #define PAST_STREAM L"PastIconsStream"
    48. #define RM_SESSIONKEY_LEN sizeof(GUID) * 2 + 1
    49. size_t wcslen_s(
    50. const wchar_t* str, size_t ccmaxlen
    51. );
    52. errno_t __fastcall memset_s(
    53. void* v,
    54. rsize_t smax,
    55. int c,
    56. rsize_t n
    57. );
    58. int CoCreateSuffixFullPath(
    59. wchar_t* wsBuffer,
    60. size_t wsCount,
    61. const wchar_t* wsFormat, ...
    62. );
    63. BOOL GetShellProcessRmInfoEx(
    64. PRM_UNIQUE_PROCESS* lpRmProcList,
    65. DWORD_PTR* lpdwCountNum
    66. );
    67. void RmProcMemFree(
    68. PRM_UNIQUE_PROCESS lpRmProcList,
    69. DWORD_PTR lpdwCountNum
    70. );
    71. void RmWriteStatusCallback(
    72. UINT nPercentComplete
    73. );
    74. DWORD SetShellRestartManager(
    75. DWORD dwSessionPID,
    76. BOOL bEnable,
    77. PRM_UNIQUE_PROCESS* lpRmStatus,
    78. DWORD_PTR* lpdwProcNum
    79. );
    80. std::wstring HexROT13(
    81. const std::wstring& text
    82. );
    83. PWSTR SHGetKnownFolderFullPath(
    84. LPCWSTR pszFullPath
    85. );
    86. PWSTR K32GetSystrayIconPath(
    87. LPCWSTR lpModuleName
    88. );
    89. BOOL ClearRegistryValue(
    90. HKEY hKey,
    91. LPCWSTR subKey,
    92. LPCWSTR valueName,
    93. BOOL bWarnning
    94. );
    95. HRESULT FilePathFromKnownPrefix(
    96. LPCWSTR szKnownPath,
    97. PWSTR* szWin32FilePath
    98. );
    99. BYTE RegSystrayIconSettings(
    100. LPCWSTR lpszAppPath,
    101. DWORD dwCSMode,
    102. const BYTE dwVisable
    103. );
    104. BOOL OnClearTrayIconStream();
    105. BYTE convertWcharToByte(wchar_t ch);
    106. BOOL IsPathExist(LPCWSTR lpFilePath);
    107. #include
    108. #include
    109. void SetConsoleSize(
    110. int cxPos, int cyPos,
    111. int nCols, int nLines
    112. )
    113. {
    114. HANDLE lpoptStdHandle = nullptr;
    115. CONSOLE_FONT_INFO consoleCurrentFont = { 0 };
    116. COORD bufferSize = { 0 }, fontSize = { 0 };
    117. TCHAR title[256];
    118. HWND hConsoleWnd = NULL;
    119. // Set console buffer size
    120. lpoptStdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
    121. GetCurrentConsoleFont(lpoptStdHandle,
    122. false, &consoleCurrentFont);
    123. fontSize = GetConsoleFontSize(lpoptStdHandle,
    124. consoleCurrentFont.nFont);
    125. bufferSize.X = nCols;
    126. bufferSize.Y = nLines;
    127. SetConsoleScreenBufferSize(lpoptStdHandle, bufferSize);
    128. // Set console window size
    129. GetConsoleTitleW(title, 256);
    130. hConsoleWnd = FindWindowW(0, title);
    131. RECT consoleRect;
    132. GetWindowRect(hConsoleWnd, &consoleRect);
    133. // Check if the current size matches the desired size
    134. int desiredWidth = (nCols + 5) * fontSize.X;
    135. int desiredHeight = (nLines + 3) * fontSize.Y;
    136. if ((consoleRect.right - consoleRect.left < (desiredWidth - 25)) ||
    137. consoleRect.bottom - consoleRect.top < (desiredHeight - 25))
    138. {
    139. // 获取窗口的扩展样式
    140. LONG_PTR exStyle = GetWindowLongPtrW(hConsoleWnd, GWL_EXSTYLE);
    141. // 添加 WS_EX_LAYERED 扩展属性
    142. exStyle |= WS_EX_LAYERED;
    143. // 更新窗口的扩展样式
    144. SetWindowLongPtrW(hConsoleWnd, GWL_EXSTYLE, exStyle);
    145. // Fade out
    146. for (int alpha = 255; alpha >= 0; alpha -= 10)
    147. {
    148. SetLayeredWindowAttributes(hConsoleWnd, 0, alpha, LWA_ALPHA);
    149. UpdateWindow(hConsoleWnd);
    150. Sleep(15);
    151. }
    152. // Move and resize the window
    153. MoveWindow(hConsoleWnd, cxPos, cyPos,
    154. desiredWidth, desiredHeight, FALSE);
    155. // Fade in
    156. for (int alpha = 0; alpha <= 255; alpha += 10)
    157. {
    158. SetLayeredWindowAttributes(hConsoleWnd, 0, alpha, LWA_ALPHA);
    159. UpdateWindow(hConsoleWnd);
    160. Sleep(15);
    161. }
    162. }
    163. // Show the window
    164. ShowWindow(hConsoleWnd, SW_SHOW);
    165. }
    166. void SetConsoleFont(const WCHAR* fontName, int fontSize)
    167. {
    168. HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    169. CONSOLE_FONT_INFOEX fontInfo = { 0 };
    170. fontInfo.cbSize = sizeof(CONSOLE_FONT_INFOEX);
    171. // 获取当前控制台字体信息
    172. GetCurrentConsoleFontEx(hConsole, FALSE, &fontInfo);
    173. // 设置字体族为微软雅黑
    174. wcscpy_s(fontInfo.FaceName, LF_FACESIZE, fontName);
    175. // 修改字号
    176. fontInfo.dwFontSize.Y = fontSize;
    177. // 设置新的字体信息
    178. SetCurrentConsoleFontEx(hConsole, FALSE, &fontInfo);
    179. }
    180. void OutputPrintLogo()
    181. {
    182. // 设置控制台窗口尺寸以适应 LOGO 文字宽度
    183. SetConsoleFont(L"点阵字体", 18);
    184. SetConsoleSize(50, 30, 125, 42);
    185. system("cls");
    186. printf(" ______ __ __ ______ _________ ______ ________ __ __ ________ ______ ______ ___ __\n");
    187. printf(" /_____/\\ /_/\\/_/\\ /_____/\\ /________/\\/_____/\\ /_______/\\ /_/\\/_/\\ /_______/\\/_____/\\ /_____/\\ /__/\\ /__/\\ \n");
    188. printf(" \\::::_\\/_\\ \\ \\ \\ \\\\::::_\\/_\\__.::.__\\/\\:::_ \\ \\ \\::: _ \\ \\\\ \\ \\ \\ \\\\__.::._\\/\\:::__\\/ \\:::_ \\ \\\\::\\_\\\\ \\ \\ \n");
    189. printf(" \\:\\/___/\\\\:\\_\\ \\ \\\\:\\/___/\\ \\::\\ \\ \\:(_) ) )_\\::(_) \\ \\\\:\\_\\ \\ \\ \\::\\ \\ \\:\\ \\ __\\:\\ \\ \\ \\\\:. `-\\ \\ \\ \n");
    190. printf(" \\_::._\\:\\\\::::_\\/ \\_::._\\:\\ \\::\\ \\ \\: __ `\\ \\\\:: __ \\ \\\\::::_\\/ _\\::\\ \\__\\:\\ \\/_/\\\\:\\ \\ \\ \\\\:. _ \\ \\ \n");
    191. printf(" /____\\:\\ \\::\\ \\ /____\\:\\ \\::\\ \\ \\ \\ `\\ \\ \\\\:.\\ \\ \\ \\ \\::\\ \\ /__\\::\\__/\\\\:\\_\\ \\ \\\\:\\_\\ \\ \\\\. \\ `_ \\ \\ \n");
    192. printf(" \\_____\\/ \\__\\/ \\_____\\/ \\__\\/ \\_\\/ \\_\\/ \\__\\/\\__\\/ \\__\\/ \\________\\/ \\_____\\/ \\_____\\/ \\__\\/ \\__\\/\n");
    193. printf("\n");
    194. }
    195. void OutputHelpStrings()
    196. {
    197. Sleep(25);
    198. std::cout << " ---------------------------------------- SysTrayIconTool Help ------------------------------------------\n";
    199. std::cout << "\tCAUTION: This tool requires modifying the registry at runtime, which requires extra caution!\n"
    200. << "\tIf you are not familiar with what you are doing, please do not continue to use it!\n";
    201. Sleep(25);
    202. std::cout << "\t\n\n"
    203. << "\t[/show] or [/showall]:\n"
    204. << "\t\tDecode the registry summary information of all icons in the system notification bar.\n\n";
    205. Sleep(25);
    206. std::cout << "\t[/clear] or [/clearreg]: CAUTION!!! \n"
    207. << "\t\tClear registry icon cache information.This operation will completely clear the configuration file.\n\n";
    208. Sleep(25);
    209. std::cout << "\t[/find][PathName]:\n"
    210. << "\t\tMatches registry information through the Win32 path of the image,\n"
    211. << "\t\t supporting relative paths for system files and current directory files.\n";
    212. std::cout << "\t\tProgram output icon visibility level information.\n\n";
    213. Sleep(25);
    214. std::cout << "\t[/fuzzyfind][BaseName]:\n"
    215. << "\t\tAllow fuzzy search of all icon information containing specific strings without knowing the\n"
    216. << "\t\t complete path of the icon.\n\n";
    217. Sleep(25);
    218. std::cout << "\t[/exactsetval][PathName][0/1/2]:\n"
    219. << "\t\tModify the visibility level information of icons in the registry through the\n"
    220. << "\t\t Win32 path of the image, supporting relative paths for system files and current directory files.\n\n";
    221. Sleep(25);
    222. std::cout << "\t[/setvalfuzzy][BaseName][0/1/2]:\n"
    223. << "\t\tAllow batch modification of icon information containing specific strings without knowing \n"
    224. << "\t\t the complete path of the icon.\n";
    225. }
    226. // 主函数
    227. int wmain(int argc, wchar_t* argv[]) {
    228. _wsetlocale(LC_ALL, L".UTF8"); // 设置代码页以支持中文
    229. OutputPrintLogo();
    230. BYTE dwVisable = 0;
    231. BYTE response = -1;
    232. PWSTR szTaryAppPath = nullptr;
    233. DWORD dwSessionPID = 0;
    234. PRM_UNIQUE_PROCESS lpRmStatus = nullptr;
    235. DWORD_PTR lpdwProcNum = 0;
    236. int mainresult = -1;
    237. if (argc < 2 || argc > 4)
    238. {
    239. std::cerr << "Error invalid parameters." << std::endl;
    240. OutputHelpStrings();
    241. return mainresult;
    242. }
    243. std::wstring wsOption_v1 = argv[1];
    244. if (argc == 2)
    245. {
    246. if (wsOption_v1 == L"/showall" || wsOption_v1 == L"/show")
    247. {
    248. response = RegSystrayIconSettings(nullptr, CS_DISPLAY_MODE, dwVisable);
    249. if (response == dwVisable)
    250. {
    251. std::cout << "The task has been successfully completed." << std::endl;
    252. mainresult = 0;
    253. }
    254. else {
    255. std::cerr << "Task execution failed." << std::endl;
    256. mainresult = 1;
    257. }
    258. }
    259. else if (wsOption_v1 == L"/clearreg" || wsOption_v1 == L"/clear")
    260. {
    261. // 结束资源管理器进程
    262. dwSessionPID = SetShellRestartManager(0,
    263. FALSE, &lpRmStatus, &lpdwProcNum);
    264. if (dwSessionPID == DWORD(-1))
    265. {
    266. std::cerr << "Task execution failed." << std::endl;
    267. mainresult = 2;
    268. }
    269. else {
    270. if (!OnClearTrayIconStream())
    271. {
    272. std::cerr << "Task execution failed." << std::endl;
    273. mainresult = 2;
    274. }
    275. else {
    276. std::cout << "The task has been successfully completed." << std::endl;
    277. mainresult = 0;
    278. }
    279. }
    280. if (lpdwProcNum != 0)
    281. {
    282. std::cout << "Restart Shell Process." << std::endl;
    283. // 尝试重启资源管理器
    284. SetShellRestartManager(dwSessionPID,
    285. TRUE, &lpRmStatus, &lpdwProcNum);
    286. }
    287. }
    288. }
    289. else if(argc >= 3){
    290. std::wstring wsOption_v2 = argv[2];
    291. if (wsOption_v1 == L"/find")
    292. {
    293. // 获取完整路径
    294. szTaryAppPath = K32GetSystrayIconPath(argv[2]);
    295. // 执行注册表操作
    296. response = RegSystrayIconSettings(szTaryAppPath,
    297. CS_FULLNAME_MODE, dwVisable);
    298. // 判断状态
    299. if (response == dwVisable)
    300. {
    301. std::cout << "The task has been successfully completed." << std::endl;
    302. mainresult = 0;
    303. }
    304. else {
    305. std::cerr << "Task execution failed." << std::endl;
    306. mainresult = 3;
    307. }
    308. }
    309. else if (wsOption_v1 == L"/fuzzyfind")
    310. {
    311. // 执行注册表操作
    312. response = RegSystrayIconSettings(argv[2],
    313. CS_BASENAME_MODE, dwVisable);
    314. // 判断状态
    315. if (response == dwVisable)
    316. {
    317. std::cout << "The task has been successfully completed." << std::endl;
    318. mainresult = 0;
    319. }
    320. else {
    321. std::cerr << "Task execution failed." << std::endl;
    322. mainresult = 4;
    323. }
    324. }
    325. else if (wsOption_v1 == L"/exactsetval")
    326. {
    327. // 参数校验
    328. if (argv[3] != nullptr && argc == 4)
    329. {
    330. // 获取要设置的显示状态值,可以为 0,1,2
    331. dwVisable = convertWcharToByte(argv[3][0]);
    332. if (dwVisable < 3u) // 0,1,2
    333. {
    334. // 结束资源管理器进程
    335. dwSessionPID = SetShellRestartManager(0,
    336. FALSE, &lpRmStatus, &lpdwProcNum);
    337. if (dwSessionPID == DWORD(-1))
    338. {
    339. std::cerr << "Task execution failed." << std::endl;
    340. mainresult = 2;
    341. }
    342. else {
    343. // 获取 TaryIconPath 支持的完整路径
    344. szTaryAppPath = K32GetSystrayIconPath(argv[2]);
    345. // 执行注册表操作
    346. response = RegSystrayIconSettings(szTaryAppPath,
    347. CS_FULLNAME_MODE | CS_CHANGESETTINGS, dwVisable);
    348. if (response == dwVisable)
    349. {
    350. std::cout << "The task has been successfully completed." << std::endl;
    351. mainresult = 0;
    352. }
    353. else {
    354. std::cerr << "Task execution failed." << std::endl;
    355. mainresult = 5;
    356. }
    357. }
    358. if (lpdwProcNum != 0)
    359. {
    360. std::cout << "Restart Shell Process." << std::endl;
    361. // 尝试重启资源管理器
    362. SetShellRestartManager(dwSessionPID,
    363. TRUE, &lpRmStatus, &lpdwProcNum);
    364. }
    365. }
    366. }
    367. }
    368. else if (wsOption_v1 == L"/setvalfuzzy")
    369. {
    370. // 参数校验
    371. if (argv[3] != nullptr && argc == 4)
    372. {
    373. // 获取要设置的显示状态值,可以为 0,1,2
    374. dwVisable = convertWcharToByte(argv[3][0]);
    375. if (dwVisable < 3u) // 0,1,2
    376. {
    377. // 结束资源管理器进程
    378. dwSessionPID = SetShellRestartManager(0,
    379. FALSE, &lpRmStatus, &lpdwProcNum);
    380. if (dwSessionPID == DWORD(-1))
    381. {
    382. std::cerr << "Task execution failed." << std::endl;
    383. mainresult = 2;
    384. }
    385. else {
    386. // 执行注册表操作
    387. response = RegSystrayIconSettings(argv[2],
    388. CS_BASENAME_MODE | CS_CHANGESETTINGS, dwVisable);
    389. if (response == dwVisable)
    390. {
    391. std::cout << "The task has been successfully completed." << std::endl;
    392. mainresult = 0;
    393. }
    394. else {
    395. std::cerr << "Task execution failed." << std::endl;
    396. mainresult = 6;
    397. }
    398. }
    399. if (lpdwProcNum != 0)
    400. {
    401. std::cout << "Restart Shell Process." << std::endl;
    402. // 尝试重启资源管理器
    403. SetShellRestartManager(dwSessionPID,
    404. TRUE, &lpRmStatus, &lpdwProcNum);
    405. }
    406. }
    407. }
    408. }
    409. }
    410. // 释放存放路径需要的内存
    411. if (szTaryAppPath != nullptr)
    412. {
    413. CoTaskMemFree(szTaryAppPath);
    414. szTaryAppPath = nullptr;
    415. }
    416. if (mainresult == -1)
    417. {
    418. std::cerr << "Error invalid parameters." << std::endl;
    419. OutputHelpStrings();
    420. }
    421. return mainresult;
    422. }
    423. BYTE RegSystrayIconSettings(LPCWSTR lpszAppPath, DWORD dwCSMode, const BYTE dwVisable)
    424. {
    425. HKEY hKey = nullptr;
    426. BYTE ret = -1;
    427. if ((dwCSMode & CS_CHANGESETTINGS) != 0 && dwVisable > 2)
    428. {
    429. std::wcerr << L"dwVisable is invalid, dwVisable must be (0, 1, 2)." << std::endl;
    430. return ret;
    431. }
    432. if ((dwCSMode & CS_DISPLAY_MODE) != 0 && (dwCSMode & (CS_FULLNAME_MODE |
    433. CS_BASENAME_MODE |
    434. CS_CHANGESETTINGS)) != 0)
    435. {
    436. std::wcerr << L"dwCSMode is invalid." << std::endl;
    437. return ret;
    438. }
    439. if ((dwCSMode & CS_FULLNAME_MODE) != 0 && (dwCSMode & CS_BASENAME_MODE) != 0)
    440. {
    441. std::wcerr << L"dwCSMode is invalid." << std::endl;
    442. return ret;
    443. }
    444. if (RegOpenKeyEx(HKEY_CURRENT_USER,
    445. TRAYNOTIFY_REG,
    446. 0, KEY_READ | KEY_WRITE, &hKey) == ERROR_SUCCESS)
    447. {
    448. DWORD dwType = REG_BINARY, lpcbData = 0;
    449. if (RegQueryValueEx(hKey, ICON_STREAM, 0, &dwType, NULL, &lpcbData) == ERROR_SUCCESS) {
    450. LPBYTE lpData = new BYTE[lpcbData];
    451. if (RegQueryValueEx(hKey, ICON_STREAM, 0, &dwType, lpData, &lpcbData) == ERROR_SUCCESS) {
    452. // 解析注册表值
    453. DWORD headerSize = 20;
    454. DWORD itemSize = 1640;
    455. DWORD numItems = (lpcbData - headerSize) / itemSize;
    456. for (DWORD i = 0; i < numItems; ++i) {
    457. LPBYTE itemData = lpData + headerSize + i * itemSize;
    458. std::wstring exePath(reinterpret_cast<wchar_t*>(itemData), 528 / sizeof(wchar_t));
    459. for (int i = 0; i < 528 / sizeof(wchar_t); ++i) {
    460. if (exePath[i] == L'\0') {
    461. exePath.resize(i);
    462. break;
    463. }
    464. }
    465. // 对可执行文件路径进行 ROT13 解密
    466. std::wstring decryptedExePath = HexROT13(exePath);
    467. PWSTR szWin32FilePath = nullptr;
    468. HRESULT hResult = NOERROR;
    469. hResult = FilePathFromKnownPrefix(decryptedExePath.c_str(),
    470. &szWin32FilePath);
    471. if ((dwCSMode & CS_DISPLAY_MODE) != 0) // 打印所有结果
    472. {
    473. if (hResult != NOERROR || szWin32FilePath == nullptr)
    474. {
    475. std::wcout << L"Executable path: " << decryptedExePath << std::endl;
    476. }
    477. else {
    478. std::wcout << L"Executable path: " << szWin32FilePath << std::endl;
    479. CoTaskMemFree(szWin32FilePath);
    480. }
    481. std::wcout << L"Current Visualization level: "
    482. << std::dec << itemData[528] << std::endl;
    483. ret = 0;
    484. }
    485. else if ((dwCSMode & CS_FULLNAME_MODE) != 0) // 匹配完整路径
    486. {
    487. if (lpszAppPath == nullptr) break;
    488. if (decryptedExePath == std::wstring(lpszAppPath))
    489. {
    490. if (hResult != NOERROR || szWin32FilePath == nullptr)
    491. {
    492. std::wcout << L"Executable path: " << decryptedExePath << std::endl;
    493. }
    494. else {
    495. std::wcout << L"Executable path: " << szWin32FilePath << std::endl;
    496. CoTaskMemFree(szWin32FilePath);
    497. }
    498. std::wcout << L"Current Visualization level: "
    499. << std::dec << itemData[528] << std::endl;
    500. if ((dwCSMode & CS_CHANGESETTINGS) != 0)
    501. {
    502. std::wcout << L"Set Visualization level to "
    503. << std::dec << dwVisable << std::endl;
    504. // 找到应用程序,修改其可见性设置
    505. itemData[528] = dwVisable;
    506. // 将修改后的字节数组写回注册表
    507. if (RegSetValueEx(hKey, ICON_STREAM,
    508. 0, REG_BINARY, lpData, lpcbData) == ERROR_SUCCESS)
    509. {
    510. ret = dwVisable;
    511. }
    512. break;
    513. }
    514. ret = dwVisable;
    515. break;
    516. }
    517. }
    518. else if ((dwCSMode & CS_BASENAME_MODE) != 0) // 模糊匹配
    519. {
    520. if (lpszAppPath == nullptr) break;
    521. size_t nPos = decryptedExePath.find(lpszAppPath);
    522. if (nPos != std::string::npos)
    523. {
    524. if (hResult != NOERROR || szWin32FilePath == nullptr)
    525. {
    526. std::wcout << L"Executable path: " << decryptedExePath << std::endl;
    527. }
    528. else {
    529. std::wcout << L"Executable path: " << szWin32FilePath << std::endl;
    530. CoTaskMemFree(szWin32FilePath);
    531. }
    532. std::wcout << L"Current Visualization level: "
    533. << std::dec << itemData[528] << std::endl;
    534. if ((dwCSMode & CS_CHANGESETTINGS) != 0)
    535. {
    536. std::wcout << L"Set Visualization level to "
    537. << std::dec << dwVisable << std::endl;
    538. // 找到应用程序,修改其可见性设置
    539. itemData[528] = dwVisable;
    540. // 将修改后的字节数组写回注册表
    541. if (RegSetValueEx(hKey, ICON_STREAM,
    542. 0, REG_BINARY, lpData, lpcbData) == ERROR_SUCCESS)
    543. {
    544. ret = dwVisable;
    545. }
    546. //break;
    547. }
    548. ret = dwVisable;
    549. //break;
    550. }
    551. }
    552. else {
    553. std::wcerr << L"dwCSMode is invalid." << std::endl;
    554. break;
    555. }
    556. }
    557. }
    558. delete[] lpData;
    559. }
    560. RegCloseKey(hKey);
    561. }
    562. else {
    563. std::cerr << "Failed to open registry key." << std::endl;
    564. return ret;
    565. }
    566. return ret;
    567. }
    568. // ROT13 加密/解密算法
    569. std::wstring HexROT13(const std::wstring& text) {
    570. std::wstring result;
    571. for (wchar_t c : text) {
    572. if (iswalpha(c)) {
    573. wchar_t base = iswupper(c) ? L'A' : L'a';
    574. result += (((c - base) + 13) % 26) + base;
    575. }
    576. else {
    577. result += c;
    578. }
    579. }
    580. return result;
    581. }
    582. // 控制 Explorer 重启状态
    583. DWORD SetShellRestartManager(
    584. DWORD dwSessionPID,
    585. BOOL bEnable,
    586. PRM_UNIQUE_PROCESS* lpRmStatus,
    587. DWORD_PTR* lpdwProcNum
    588. )
    589. {
    590. DWORD dwRmStatus = 0;
    591. DWORD dwSessionHandle = dwSessionPID;
    592. WCHAR strSessionKey[RM_SESSIONKEY_LEN] = { 0 };
    593. PRM_UNIQUE_PROCESS lpRmProcList = *lpRmStatus;
    594. DWORD_PTR lpdwCountNum = *lpdwProcNum;
    595. if (lpRmProcList == nullptr)
    596. {
    597. dwRmStatus = RmStartSession(&dwSessionHandle, NULL, strSessionKey);
    598. if (ERROR_SUCCESS != dwRmStatus)
    599. {
    600. std::cerr << "RmStartSession failed: " << std::dec << dwRmStatus << std::endl;
    601. return DWORD(-1);
    602. }
    603. }
    604. if (!bEnable)
    605. {
    606. if (!GetShellProcessRmInfoEx(&lpRmProcList, &lpdwCountNum))
    607. {
    608. std::cerr << "GetShellProcessRmInfoEx failed." << std::endl;
    609. RmEndSession(dwSessionHandle);
    610. return DWORD(-1);
    611. }
    612. // 传出结果
    613. *lpRmStatus = lpRmProcList;
    614. *lpdwProcNum = lpdwCountNum;
    615. UINT dwNum = static_cast(lpdwCountNum);
    616. if (dwNum == UINT(0)) // 没有找到进程
    617. {
    618. std::cerr << "There are no shell processes that need to be closed." << std::endl;
    619. return dwSessionHandle;
    620. }
    621. if (dwNum == UINT(-1))
    622. {
    623. std::cerr << "GetShellProcessRmInfoEx failed." << std::endl;
    624. RmProcMemFree(lpRmProcList, lpdwCountNum);
    625. RmEndSession(dwSessionHandle);
    626. return DWORD(-1);
    627. }
    628. std::cout << "Process Count: " << dwNum << std::endl;
    629. std::cout << "Shell PID: " << std::endl;
    630. for (UINT i = 0; i < dwNum; i++)
    631. {
    632. std::cout << " > " << lpRmProcList[i].dwProcessId << std::endl;
    633. }
    634. dwRmStatus = RmRegisterResources(dwSessionHandle,
    635. 0, NULL, dwNum, lpRmProcList, 0, NULL);
    636. if (ERROR_SUCCESS != dwRmStatus)
    637. {
    638. std::cerr << "RmRegisterResources failed: " << std::dec << dwRmStatus << std::endl;
    639. RmProcMemFree(lpRmProcList, lpdwCountNum);
    640. RmEndSession(dwSessionHandle);
    641. return DWORD(-1);
    642. }
    643. dwRmStatus = RmShutdown(dwSessionHandle, RmForceShutdown, RmWriteStatusCallback);
    644. if (ERROR_SUCCESS != dwRmStatus && ERROR_FAIL_SHUTDOWN != dwRmStatus)
    645. {
    646. std::cerr << "RmShutdown failed: " << std::dec << dwRmStatus << std::endl;
    647. RmEndSession(dwSessionHandle);
    648. return DWORD(-1);
    649. }
    650. }
    651. else {
    652. // 检查参数不为空
    653. if (lpdwCountNum == 0)
    654. return dwSessionHandle;
    655. dwRmStatus = RmRestart(dwSessionHandle, 0, RmWriteStatusCallback);
    656. if (ERROR_SUCCESS != dwRmStatus)
    657. {
    658. std::cerr << "RmRestart failed: " << std::dec << dwRmStatus << std::endl;
    659. RmEndSession(dwSessionHandle);
    660. return DWORD(-1);
    661. }
    662. dwRmStatus = RmEndSession(dwSessionHandle);
    663. if (ERROR_SUCCESS != dwRmStatus)
    664. {
    665. std::cerr << "RmEndSession failed: " << std::dec << dwRmStatus << std::endl;
    666. return DWORD(-1);
    667. }
    668. RmProcMemFree(lpRmProcList, lpdwCountNum);
    669. // 传出结果
    670. *lpRmStatus = nullptr;
    671. *lpdwProcNum = 0;
    672. }
    673. return dwSessionHandle;
    674. }
    675. void RmWriteStatusCallback(
    676. UINT nPercentComplete
    677. )
    678. {
    679. std::cout << "Task completion level: " << std::dec << nPercentComplete << std::endl;
    680. }
    681. BOOL GetShellProcessRmInfoEx(
    682. PRM_UNIQUE_PROCESS* lpRmProcList,
    683. DWORD_PTR* lpdwCountNum
    684. )
    685. {
    686. PROCESSENTRY32W pe32 = { 0 };
    687. FILETIME lpCreationTime = { 0 };
    688. FILETIME lpExitTime = { 0 };
    689. FILETIME lpKernelTime = { 0 };
    690. FILETIME lpUserTime = { 0 };
    691. HANDLE hProcess = nullptr;
    692. RM_UNIQUE_PROCESS tpProc = { 0 };
    693. std::vector RmProcVec;
    694. SIZE_T VecLength = 0;
    695. // 在使用这个结构前,先设置它的大小
    696. pe32.dwSize = sizeof(pe32);
    697. // 给系统内所有的进程拍个快照
    698. HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    699. if (hProcessSnap == INVALID_HANDLE_VALUE)
    700. {
    701. std::cerr << "CreateToolhelp32Snapshot 调用失败." << std::endl;
    702. return FALSE;
    703. }
    704. // 遍历进程快照,轮流显示每个进程的信息
    705. BOOL bMore = Process32FirstW(hProcessSnap, &pe32);
    706. while (bMore)
    707. {
    708. if (!_wcsicmp(pe32.szExeFile, L"explorer.exe")
    709. && pe32.cntThreads > 1)// 线程数大于 1,是为了过滤僵尸进程
    710. {
    711. hProcess = OpenProcess(
    712. PROCESS_QUERY_LIMITED_INFORMATION,
    713. FALSE, pe32.th32ProcessID);
    714. if (hProcess != nullptr)
    715. {
    716. memset(&lpCreationTime, 0, sizeof(FILETIME));
    717. if (GetProcessTimes(hProcess,
    718. &lpCreationTime, &lpExitTime,
    719. &lpKernelTime, &lpUserTime) == TRUE)
    720. {
    721. tpProc.dwProcessId = pe32.th32ProcessID;
    722. tpProc.ProcessStartTime = lpCreationTime;
    723. RmProcVec.push_back(tpProc);
    724. }
    725. CloseHandle(hProcess);
    726. hProcess = nullptr;
    727. }
    728. }
    729. bMore = Process32NextW(hProcessSnap, &pe32);
    730. }
    731. // 清除 snapshot 对象
    732. CloseHandle(hProcessSnap);
    733. VecLength = RmProcVec.size();
    734. if (VecLength == 0) // 没有找到进程
    735. {
    736. *lpdwCountNum = 0;
    737. *lpRmProcList = 0;
    738. return TRUE;
    739. }
    740. if (VecLength < (SIZE_T)0xf4236u)
    741. {
    742. RM_UNIQUE_PROCESS* lprmUniqueProc =
    743. new(std::nothrow) RM_UNIQUE_PROCESS[VecLength];
    744. if (lprmUniqueProc != nullptr)
    745. {
    746. SIZE_T rSize = VecLength * sizeof(RM_UNIQUE_PROCESS);
    747. if (rSize < (SIZE_T)0xC80000u && rSize > 0)
    748. {
    749. if (!memcpy_s(lprmUniqueProc, rSize, &RmProcVec[0], rSize))
    750. {
    751. *lpdwCountNum = VecLength;
    752. *lpRmProcList = lprmUniqueProc;
    753. return TRUE;
    754. }
    755. }
    756. else {
    757. std::cerr << "Vector Size to large!" << std::endl;
    758. }
    759. }
    760. else {
    761. std::cerr << "Alloc memory failed!" << std::endl;
    762. }
    763. }
    764. else {
    765. std::cerr << "Vector Size is invalid!" << std::endl;
    766. }
    767. return FALSE;
    768. }
    769. void RmProcMemFree(
    770. PRM_UNIQUE_PROCESS lpRmProcList,
    771. DWORD_PTR lpdwCountNum)
    772. {
    773. __try
    774. {
    775. DWORD_PTR dwCountNum = lpdwCountNum;
    776. if (lpRmProcList != nullptr && dwCountNum > 0)
    777. {
    778. while (--dwCountNum)
    779. {
    780. if (IsBadWritePtr(&lpRmProcList[dwCountNum], sizeof(RM_UNIQUE_PROCESS)))
    781. {
    782. throw(L"BadWritePtr event!");
    783. break;
    784. }
    785. memset(&lpRmProcList[dwCountNum], 0, sizeof(RM_UNIQUE_PROCESS));
    786. }
    787. delete[] lpRmProcList;
    788. }
    789. }
    790. __except (EXCEPTION_EXECUTE_HANDLER)
    791. {
    792. // 处理 SEH 异常
    793. std::cerr << "Error access violation." << std::endl;
    794. exit(-1);
    795. }
    796. }
    797. BOOL OnClearTrayIconStream()
    798. {
    799. BOOL bSuccess = FALSE;
    800. // Clear PastIconsStream value
    801. bSuccess = ClearRegistryValue(HKEY_CURRENT_USER,
    802. TRAYNOTIFY_REG,
    803. PAST_STREAM, FALSE);
    804. if (bSuccess)
    805. std::cout << "PastIconsStream value cleared successfully." << std::endl;
    806. // Clear IconStreams value
    807. bSuccess = ClearRegistryValue(HKEY_CURRENT_USER,
    808. TRAYNOTIFY_REG,
    809. ICON_STREAM, TRUE);
    810. if (bSuccess)
    811. std::cout << "IconStreams value cleared successfully." << std::endl;
    812. return bSuccess;
    813. }
    814. BOOL ClearRegistryValue(HKEY hKey, LPCWSTR subKey, LPCWSTR valueName, BOOL bWarnning)
    815. {
    816. HKEY hSubKey;
    817. LONG result = RegOpenKeyExW(hKey, subKey, 0, KEY_SET_VALUE, &hSubKey);
    818. if (result != ERROR_SUCCESS)
    819. {
    820. if (bWarnning)
    821. {
    822. std::cout << "Failed to open registry key: " << subKey << std::endl;
    823. return FALSE;
    824. }
    825. return TRUE;
    826. }
    827. result = RegDeleteValueW(hSubKey, valueName);
    828. if (result != ERROR_SUCCESS && bWarnning)
    829. {
    830. if (bWarnning)
    831. {
    832. std::cout << "Failed to delete registry value: " << valueName << std::endl;
    833. RegCloseKey(hSubKey);
    834. return false;
    835. }
    836. return TRUE;
    837. }
    838. RegCloseKey(hSubKey);
    839. return TRUE;
    840. }
    841. PWSTR K32GetSystrayIconPath(LPCWSTR lpModuleName)
    842. {
    843. if (lpModuleName == nullptr)
    844. {
    845. std::wcerr << L"K32GetSystrayIconPath failed> Error null pointer." << std::endl;
    846. return nullptr;
    847. }
    848. if (lpModuleName[0] == L'\0')
    849. {
    850. std::wcerr << L"K32GetSystrayIconPath failed> Error null buffer." << std::endl;
    851. return nullptr;
    852. }
    853. // 动态分配内存存储程序文件的完整路径
    854. DWORD bufferSize = MAX_PATH;
    855. DWORD cbBufferSize = MAX_PATH;
    856. std::unique_ptr<wchar_t[]> buffer(new wchar_t[bufferSize]);
    857. if (PathIsRelativeW(lpModuleName) == TRUE)
    858. {
    859. // 查询程序文件的完整路径
    860. DWORD pathLength = SearchPathW(NULL, lpModuleName, NULL, bufferSize, buffer.get(), NULL);
    861. if (pathLength == 0) {
    862. // 查询失败,输出错误信息
    863. DWORD error = GetLastError();
    864. std::cerr << "Error searching for file path: " << error << std::endl;
    865. return nullptr;
    866. }
    867. // 如果缓冲区大小不够,重新分配内存并查询路径
    868. if (pathLength >= bufferSize) {
    869. bufferSize = pathLength + 1; // 考虑字符串末尾的空字符
    870. buffer.reset(new wchar_t[bufferSize]);
    871. pathLength = SearchPathW(NULL, lpModuleName, NULL, bufferSize, buffer.get(), NULL);
    872. if (pathLength == 0) {
    873. // 查询失败,输出错误信息
    874. DWORD error = GetLastError();
    875. std::cerr << "Error searching for file path: " << error << std::endl;
    876. return nullptr;
    877. }
    878. }
    879. return SHGetKnownFolderFullPath(buffer.get());
    880. }
    881. else if(!IsPathExist(lpModuleName)){
    882. std::wcerr << "Error file path not exist." << std::endl;
    883. return nullptr;
    884. }
    885. // 对路径进行修改,以便于支持 KNOWNFOLDERID
    886. //PWSTR pszknFullPath;
    887. return SHGetKnownFolderFullPath(lpModuleName);
    888. }
    889. BOOL IsPathExist(LPCWSTR lpFilePath)
    890. {
    891. WIN32_FILE_ATTRIBUTE_DATA attrs = { 0 };
    892. return 0 != GetFileAttributesExW(lpFilePath, GetFileExInfoStandard, &attrs);
    893. }
    894. PWSTR SHGetKnownFolderFullPath(LPCWSTR pszFullPath)
    895. {
    896. if (pszFullPath == nullptr)
    897. {
    898. std::wcerr << L"SHGetKnownFolderFullPath failed> Error null pointer." << std::endl;
    899. return nullptr;
    900. }
    901. if (pszFullPath[0] == L'\0')
    902. {
    903. std::wcerr << L"SHGetKnownFolderFullPath failed> Error null buffer." << std::endl;
    904. return nullptr;
    905. }
    906. #define WSGUID_STRING_LEN 76
    907. #define GUID_STRING_LEN 38
    908. UINT index = 0;
    909. bool fflag = false;
    910. int nPosPrefix = -1, nNewPathRealLen = -1;
    911. PWSTR pszPath = nullptr, pszNewPath = nullptr;
    912. WCHAR szguid[WSGUID_STRING_LEN + 1] = { 0 };
    913. GUID EncodeCommonRelativePath[5] = { 0 };
    914. SIZE_T wsNewPathSize = 0;
    915. SIZE_T szwcharSize = sizeof(WCHAR);
    916. SIZE_T cbNewPathSize = 0;
    917. // 需要检查的 KNOWNFOLDERID 列表
    918. EncodeCommonRelativePath[0] = FOLDERID_ProgramFilesX86;
    919. EncodeCommonRelativePath[1] = FOLDERID_ProgramFilesX64;
    920. EncodeCommonRelativePath[2] = FOLDERID_SystemX86;
    921. EncodeCommonRelativePath[3] = FOLDERID_System;
    922. EncodeCommonRelativePath[4] = FOLDERID_Windows;
    923. // 查找并转换路径前缀
    924. while (index < 5)
    925. {
    926. if (SHGetKnownFolderPath( // 该函数检查 KNOWNFOLDERID 对应的完整路径
    927. EncodeCommonRelativePath[index],
    928. KF_FLAG_DONT_VERIFY | KF_FLAG_NO_ALIAS,
    929. 0,
    930. &pszPath) >= 0)
    931. {
    932. nPosPrefix = PathCommonPrefixW(pszPath, pszFullPath, 0);
    933. if (nPosPrefix && nPosPrefix == wcslen_s(pszPath, 0x800))
    934. {
    935. memset_s(szguid, sizeof(szguid), 0, sizeof(szguid));
    936. // 转换为 GUID 字符串
    937. if (!StringFromGUID2(EncodeCommonRelativePath[index], szguid, sizeof(szguid) / sizeof(*szguid)))
    938. {
    939. std::wcerr << L"Error buffer to small." << std::endl;
    940. break;
    941. }
    942. else {
    943. // 计算将 GUID 前缀和路径后缀拼接成新的完整路径需要的字符数
    944. wsNewPathSize = (GUID_STRING_LEN + wcslen_s(pszFullPath, 0x800) - nPosPrefix + 1);
    945. // 安全地进行乘法运算,以便于获得需要分配的缓冲区字节数
    946. if (SizeTMult(wsNewPathSize, szwcharSize, &cbNewPathSize) != S_OK) {
    947. // 乘法溢出,处理错误
    948. std::wcerr << L"Multiplication overflow occurred." << std::endl;
    949. break;
    950. }
    951. // 分配生成字符串需要的缓冲区
    952. pszNewPath = (PWSTR)CoTaskMemAlloc(cbNewPathSize);
    953. if (pszNewPath == nullptr)
    954. {
    955. std::wcerr << L"Error not enough memory." << std::endl;
    956. break;
    957. }
    958. // 初始化为 0
    959. memset_s(pszNewPath, cbNewPathSize, 0, cbNewPathSize);
    960. // 格式化为完整路径
    961. nNewPathRealLen = CoCreateSuffixFullPath(
    962. pszNewPath, wsNewPathSize,
    963. L"%s%s", szguid,
    964. &pszFullPath[nPosPrefix]
    965. );
    966. // 检查格式化的字符数
    967. if (nNewPathRealLen <= 0 || nNewPathRealLen != wsNewPathSize)
    968. {
    969. std::wcerr << L"Error invalid suffix path." << std::endl;
    970. CoTaskMemFree(pszNewPath);
    971. pszNewPath = nullptr;
    972. break;
    973. }
    974. else {
    975. std::wcout << L"GetKnownFolderFullPath success!" << std::endl;
    976. fflag = true;
    977. break;
    978. }
    979. }
    980. }
    981. // 没有找到匹配的目标前,每遍历一次需要释放占用的缓冲区
    982. CoTaskMemFree(pszPath);
    983. pszPath = nullptr;
    984. }
    985. ++index;
    986. }
    987. // 循环中使用 break 跳出时,过程中分配的缓冲区可能没有释放
    988. if (pszPath != nullptr)
    989. {
    990. CoTaskMemFree(pszPath);
    991. pszPath = nullptr;
    992. }
    993. if (!fflag) // 没有找到时候直接复制输入缓冲区到输出缓冲区
    994. {
    995. size_t cbPathSize = wcslen_s(pszFullPath, 0x800);
    996. size_t wsPathSize = 0;
    997. if (cbPathSize > 0)
    998. {
    999. ++cbPathSize;
    1000. // 获得需要分配的缓冲区字节数
    1001. if (SizeTMult(cbPathSize, szwcharSize, &wsPathSize) == S_OK) {
    1002. pszNewPath = (PWSTR)CoTaskMemAlloc(wsPathSize); // 分配缓冲区
    1003. if (pszNewPath == nullptr)
    1004. {
    1005. std::wcerr << L"Error not enough memory." << std::endl;
    1006. return pszNewPath;
    1007. }
    1008. memset_s(pszNewPath, wsPathSize, 0, wsPathSize);
    1009. memcpy_s(pszNewPath, wsPathSize, pszFullPath, wsPathSize);
    1010. }
    1011. }
    1012. }
    1013. return pszNewPath;
    1014. #undef GUID_STRING_LEN
    1015. #undef WSGUID_STRING_LEN
    1016. }
    1017. /*
    1018. * 已知路径转换函数
    1019. *
    1020. * 参数:LPCWSTR szKnownPath 包含 GUID 前缀的完整路径
    1021. * PWSTR szWin32FilePath 返回 Win32 完整路径
    1022. *
    1023. * ********************************************************************************************
    1024. * 备注:
    1025. *
    1026. * {F38BF404-1D43-42F2-9305-67DE0B28FC23} 表示 C:\Windows
    1027. * {F38BF404-1D43-42F2-9305-67DE0B28FC23}\explorer.exe 将被转换为 C:\Windows\explorer.exe
    1028. *
    1029. * SystemRoot = "{F38BF404-1D43-42F2-9305-67DE0B28FC23}";//SystemRoot:Windows Folder
    1030. * System32 = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}";//SystemRoot:Windows\\System32 Folder
    1031. * Program86 = "{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}";//SystemRoot:Program Files (x86) Folder
    1032. * Program = "{6D809377-6AF0-444B-8957-A3773F02200E}";//SystemRoot:Program Files Folder
    1033. *
    1034. * ********************************************************************************************
    1035. */
    1036. HRESULT FilePathFromKnownPrefix(
    1037. LPCWSTR szKnownPath,
    1038. PWSTR* szWin32FilePath
    1039. )
    1040. {
    1041. GUID stGuid = { 0 };
    1042. PWSTR strPathPrefix = nullptr;
    1043. PWSTR strWin32Path = nullptr;
    1044. HRESULT str2GuidReslt = E_FAIL;
    1045. std::wstring wsKnownPath;
    1046. size_t nPos = std::string::npos;
    1047. size_t nPrefix = 0,
    1048. nKnownPath = 0,
    1049. nWin32Path = 0,
    1050. wsWin32PathLen = 0;
    1051. int nCoResponse = -1;
    1052. if (szKnownPath == nullptr)
    1053. {
    1054. SetLastError(ERROR_INVALID_PARAMETER);
    1055. return str2GuidReslt;
    1056. }
    1057. if (szKnownPath[0] == L'\0')
    1058. {
    1059. SetLastError(ERROR_INVALID_PARAMETER);
    1060. return str2GuidReslt;
    1061. }
    1062. wsKnownPath = szKnownPath;
    1063. nPos = wsKnownPath.find_first_of(L'\\');
    1064. if (nPos != 0x26u) // GUID String 长度为 38 字符
    1065. {
    1066. SetLastError(ERROR_PATH_NOT_FOUND);
    1067. return str2GuidReslt;
    1068. }
    1069. wsKnownPath.resize(0x26u);
    1070. SetLastError(0);
    1071. str2GuidReslt = CLSIDFromString((LPCOLESTR)wsKnownPath.c_str(), (LPCLSID)&stGuid);
    1072. if (str2GuidReslt == (HRESULT)NOERROR) {
    1073. //printf("The CLSID was obtained successfully.\n");
    1074. str2GuidReslt = SHGetKnownFolderPath(stGuid, KF_FLAG_DONT_VERIFY, NULL, &strPathPrefix);
    1075. if (SUCCEEDED(str2GuidReslt) && strPathPrefix != nullptr)
    1076. {
    1077. nPrefix = wcslen_s(strPathPrefix, 0x800u);
    1078. nKnownPath = wcslen_s(szKnownPath, 0x800u);
    1079. if (nPrefix == 0 || nKnownPath == 0)
    1080. {
    1081. std::wcerr << L"Get string length faild." << std::endl;
    1082. CoTaskMemFree(strPathPrefix);// 释放内存
    1083. return E_FAIL;
    1084. }
    1085. nWin32Path = nKnownPath - 0x26u + nPrefix + 1;
    1086. // 计算需要分配的缓冲区字节数
    1087. if (SizeTMult(nWin32Path, sizeof(wchar_t), &wsWin32PathLen) != S_OK) {
    1088. // 乘法溢出,处理错误
    1089. std::wcerr << L"Multiplication overflow occurred." << std::endl;
    1090. CoTaskMemFree(strPathPrefix);// 释放内存
    1091. return E_FAIL;
    1092. }
    1093. strWin32Path = (PWSTR)CoTaskMemAlloc(wsWin32PathLen);
    1094. if (strWin32Path == nullptr)
    1095. {
    1096. CoTaskMemFree(strPathPrefix);// 释放内存
    1097. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
    1098. return E_FAIL;
    1099. }
    1100. nCoResponse = CoCreateSuffixFullPath(strWin32Path,
    1101. nWin32Path, L"%s%s", strPathPrefix, &szKnownPath[0x26]);
    1102. if (nCoResponse && nCoResponse == nWin32Path)
    1103. {
    1104. *szWin32FilePath = strWin32Path;
    1105. CoTaskMemFree(strPathPrefix);// 释放内存
    1106. return NOERROR;
    1107. }
    1108. CoTaskMemFree(strPathPrefix);// 释放内存
    1109. return E_FAIL;
    1110. }
    1111. std::cerr << "SHGetKnownFolderPath Failed,errorCode = "
    1112. << GetLastError() << std::endl;
    1113. return str2GuidReslt;
    1114. }
    1115. std::cerr << "CLSIDFromString Failed,errorCode = "
    1116. << GetLastError() << std::endl;
    1117. return str2GuidReslt;
    1118. }
    1119. int CoCreateSuffixFullPath(
    1120. wchar_t* wsBuffer,
    1121. size_t wsCount,
    1122. const wchar_t* wsFormat, ...
    1123. )
    1124. {
    1125. if (wsBuffer == nullptr) return -1;
    1126. int nWriteCount = 0;
    1127. // hold the variable argument
    1128. va_list argsList = nullptr;
    1129. // A function that invokes va_start
    1130. // shall also invoke va_end before it returns.
    1131. va_start(argsList, wsFormat);
    1132. nWriteCount = vswprintf_s(wsBuffer, wsCount, wsFormat, argsList);
    1133. va_end(argsList);
    1134. return ++nWriteCount;
    1135. }
    1136. // wcslen 安全版本
    1137. size_t wcslen_s(
    1138. const wchar_t* str, size_t ccmaxlen)
    1139. {
    1140. size_t length = 0;
    1141. if (ccmaxlen > 0x5000)
    1142. ccmaxlen = 0x5000; // 20480 字节,路径长度应该远小于该值
    1143. __try {
    1144. while (length < ccmaxlen && str[length] != L'\0') {
    1145. ++length;
    1146. }
    1147. // 说明发生越界访问或者超出限制
    1148. if (length == ccmaxlen)
    1149. {
    1150. std::cerr << "Trigger limit: The buffer exceeds the limit of characters." << std::endl;
    1151. return 0;
    1152. }
    1153. }
    1154. __except (EXCEPTION_EXECUTE_HANDLER) {
    1155. // 捕获并处理访问无效指针引发的异常
    1156. std::cerr << "Access violation: Attempted to read from null pointer." << std::endl;
    1157. return 0;
    1158. }
    1159. return length;
    1160. }
    1161. errno_t __fastcall memset_s(void* v, rsize_t smax, int c, rsize_t n) {
    1162. if (v == NULL) return EINVAL;
    1163. if (smax > RSIZE_MAX) return EINVAL;
    1164. if (n > smax) return EINVAL;
    1165. volatile unsigned char* p = (volatile unsigned char*)v;
    1166. while (smax-- && n--) {
    1167. *p++ = c;
    1168. }
    1169. return 0;
    1170. }
    1171. BYTE convertWcharToByte(wchar_t ch) {
    1172. if (ch >= L'0' && ch <= L'9') {
    1173. return static_cast(ch - L'0');
    1174. }
    1175. else {
    1176. // 非数字字符
    1177. return 255;
    1178. }
    1179. }

    测试截图:

    SysTrayIconTool 帮助页面

    此外,在 Win 11 更新 22621.1413 之前,我们对图标的管理也可以通过控制面板完成。

    4.2 Win11 特有的转储信息

    在注册表下,Win11 依赖设置来完成任务栏的通知区域的图标管理,在这里一切操作会立即生效,甚至不需要重启 explorer。

    [HKEY_CURRENT_USER\Control Panel\NotifyIconSettings]

    在该键下有很多以 TRAYNOTIFYICONID 命名的子键:

    NotifyIconSettings 子键

    每一个子键下包含 5 个值项:ExecutablePath、IconSnapshot、InitialTooltip、IsPromoted 和 UID。

    例如:

    管理通知图标配置注册表项

    ExecutablePath 就是图标对应的可执行文件路径(已经对已知路径进行了 GUID 化处理);

    IconSnapshot 是图标的一个快照;

    InitialTooltip 是初始化时 lpData-> szTip 表示的文本;

    IsPromoted 是 bool 类型,表示是否显示在任务栏。如果该键的值为 1,则托盘图标始终可见,为 0 则表示隐藏。[该值是非常有用的,修改立即生效]

    UID 是初始化时 lpData-> uID 表示的图标标识符,用于一定程度上规范使用并防止图标重复。

    我已经在 Windows 11 中对此内容进行了测试。

    值得注意的是,每个应用程序的密钥名称在每台计算机上都不一致,例如我检查的一台计算机上 OneDrive.exe 的密钥是:

    HKEY_CURRENT_USER\Control Panel\NotifyIconSettings\5434357290411014857

    但在另一个方面,同一个应用程序以不同的键名称列出:

    HKEY_CURRENT_USER\Control Panel\NotifyIconSettings\5889842883606957982

    此外还有可能出现同一个键名称对应多个不同程序的情况。

    这些情况也会发生在同一设备上的不同用户之间。

    因此,Windows 在为每个用户/系统命名密钥时似乎会生成一个唯一的应用程序 ID,但目前掌握的信息不足以让我们理解该 ID 生成的机制。因此,这里的解决方案是创建一个带有遍历循环的程序,搜索“NotifyIconSettings”中的每个键,以查找需要升级(或降级)的特定可执行文件,找到后,将 IsPromoted 表示的 DWORD 值编辑为 1(或 0)。

    一个简易的测试代码如下:

    1. /*
    2. * ------------------------------------------------------------------------
    3. * Visibility of the Application Icon if we use the Systray
    4. * Version: 1.1
    5. *
    6. * Works on Windows 11 Build 10.0.22621.1413 or greater
    7. * Author: LianyiYou 516, at 2024/2/18.
    8. * ------------------------------------------------------------------------
    9. */
    10. #include
    11. #include
    12. #include
    13. bool SetNotifyIconIsPromoted(HKEY TopKey, const std::wstring& sKeyName, int State, const std::wstring& ComputerName = L"")
    14. {
    15. HKEY hKey = nullptr, lhRemoteRegistry = nullptr;
    16. DWORD r1 = 0, ret_value = 0;
    17. DWORD lpData = 0;
    18. DWORD lpcbData = sizeof(DWORD);
    19. DWORD lValue = 0;
    20. std::wstring trimmedKeyName = sKeyName;
    21. trimmedKeyName.erase(trimmedKeyName.find_last_not_of(L" \t") + 1);
    22. if (ComputerName.empty())
    23. r1 = RegOpenKeyEx(TopKey, trimmedKeyName.c_str(), 0, KEY_ALL_ACCESS, &hKey);
    24. else
    25. {
    26. r1 = RegConnectRegistry(ComputerName.c_str(), TopKey, &lhRemoteRegistry);
    27. if (r1 == ERROR_SUCCESS)
    28. r1 = RegOpenKeyEx(lhRemoteRegistry, trimmedKeyName.c_str(), 0, KEY_ALL_ACCESS, &hKey);
    29. }
    30. if (r1 == ERROR_SUCCESS)
    31. {
    32. if (State == 0 || State == 1)
    33. r1 = RegSetValueEx(hKey, L"IsPromoted", 0, REG_DWORD, reinterpret_cast(&State), sizeof(DWORD));
    34. if (r1 == ERROR_SUCCESS)
    35. ret_value = true;
    36. }
    37. RegCloseKey(hKey);
    38. if (lhRemoteRegistry)
    39. RegCloseKey(lhRemoteRegistry);
    40. return ret_value;
    41. }
    42. int GetNotifyIconIsPromoted(HKEY TopKey, const std::wstring& sKeyName, const std::wstring& ComputerName = L"")
    43. {
    44. int ret_value = 0;
    45. HKEY hKey = nullptr, lhRemoteRegistry = nullptr;
    46. DWORD lpData = 0;
    47. DWORD lpcbData = sizeof(DWORD);
    48. DWORD lType = 0;
    49. DWORD lpDataDWORD = 0;
    50. DWORD r1 = 0;
    51. std::wstring trimmedKeyName = sKeyName;
    52. trimmedKeyName.erase(trimmedKeyName.find_last_not_of(L" \t") + 1);
    53. if (ComputerName.empty())
    54. r1 = RegOpenKeyEx(TopKey, trimmedKeyName.c_str(), 0, KEY_ALL_ACCESS, &hKey);
    55. else
    56. {
    57. r1 = RegConnectRegistry(ComputerName.c_str(), TopKey, &lhRemoteRegistry);
    58. if (r1 == ERROR_SUCCESS)
    59. r1 = RegOpenKeyEx(lhRemoteRegistry, trimmedKeyName.c_str(), 0, KEY_ALL_ACCESS, &hKey);
    60. }
    61. if (r1 == ERROR_SUCCESS)
    62. {
    63. r1 = RegQueryValueEx(hKey, L"IsPromoted", 0, &lType, reinterpret_cast(&lpDataDWORD), &lpcbData);
    64. if (r1 == ERROR_SUCCESS && lType == REG_DWORD)
    65. {
    66. ret_value = static_cast<int>(lpDataDWORD);
    67. //std::cout << "IsPromoted == " << ret_value << std::endl;
    68. }
    69. RegCloseKey(hKey);
    70. }
    71. if (lhRemoteRegistry)
    72. RegCloseKey(lhRemoteRegistry);
    73. return ret_value;
    74. }
    75. #define RSIZE_MAX (SIZE_MAX >> 1)
    76. errno_t WINAPI memset_s(void* v, rsize_t smax, int c, rsize_t n) {
    77. if (v == NULL) return EINVAL;
    78. if (smax > RSIZE_MAX) return EINVAL;
    79. if (n > smax) return EINVAL;
    80. volatile unsigned char* p = (volatile unsigned char*)v;
    81. while (smax-- && n--) {
    82. *p++ = c;
    83. }
    84. return 0;
    85. }
    86. std::wstring GetKeyNotifyIcon(
    87. HKEY TopKey,
    88. const std::wstring& sKeyName,
    89. const std::wstring& sProgramFileName,
    90. const std::wstring& ComputerName = L""
    91. )
    92. {
    93. HKEY hKey = nullptr, lhRemoteRegistry = nullptr;
    94. DWORD r1 = 0, index = 0, lpcbData = 0, lType = 0;
    95. FILETIME lpftLastWriteTime = { 0 };
    96. wchar_t lpData[1024] = { 0 };
    97. std::wstring subkey, listsubkey;
    98. std::vector listsubkeys;
    99. std::wstring trimmedKeyName = sKeyName;
    100. trimmedKeyName.erase(trimmedKeyName.find_last_not_of(L" \t") + 1);
    101. if (ComputerName.empty())
    102. r1 = RegOpenKeyEx(TopKey, trimmedKeyName.c_str(), 0, KEY_ALL_ACCESS, &hKey);
    103. else
    104. {
    105. r1 = RegConnectRegistry(ComputerName.c_str(), TopKey, &lhRemoteRegistry);
    106. if (r1 == ERROR_SUCCESS)
    107. r1 = RegOpenKeyEx(lhRemoteRegistry, trimmedKeyName.c_str(), 0, KEY_ALL_ACCESS, &hKey);
    108. }
    109. if (r1 == ERROR_SUCCESS)
    110. {
    111. for (index = 0; index < 1000; index++)
    112. {
    113. lpcbData = 1023;
    114. r1 = RegEnumKeyEx(hKey, index, lpData, &lpcbData, 0, 0, 0, &lpftLastWriteTime);
    115. if (r1 == ERROR_SUCCESS && lpcbData)
    116. {
    117. lpData[lpcbData] = 0;
    118. listsubkeys.push_back(std::wstring(lpData, lpcbData));
    119. }
    120. else
    121. break;
    122. }
    123. RegCloseKey(hKey);
    124. for (std::wstring& subkey : listsubkeys)
    125. {
    126. std::wstring keyPath = trimmedKeyName + L"\\" + subkey;
    127. if (ComputerName.empty())
    128. r1 = RegOpenKeyEx(TopKey, keyPath.c_str(), 0, KEY_ALL_ACCESS, &hKey);
    129. else
    130. {
    131. r1 = RegConnectRegistry(ComputerName.c_str(), TopKey, &lhRemoteRegistry);
    132. if (r1 == ERROR_SUCCESS)
    133. r1 = RegOpenKeyEx(lhRemoteRegistry, keyPath.c_str(), 0, KEY_ALL_ACCESS, &hKey);
    134. }
    135. if (r1 == ERROR_SUCCESS)
    136. {
    137. lpcbData = 1023;
    138. memset_s(lpData, sizeof(lpData), 0, sizeof(lpData));
    139. r1 = RegQueryValueEx(hKey, L"ExecutablePath", 0, &lType, reinterpret_cast(&lpData), &lpcbData);
    140. if (r1 == ERROR_SUCCESS && lType == REG_SZ)
    141. {
    142. std::wstring executablePath(lpData, lpcbData);
    143. size_t nPos = executablePath.find(sProgramFileName);
    144. if (nPos != std::string::npos)
    145. {
    146. listsubkey = subkey;
    147. break;
    148. }
    149. }
    150. RegCloseKey(hKey);
    151. }
    152. if (lhRemoteRegistry)
    153. RegCloseKey(lhRemoteRegistry);
    154. }
    155. }
    156. return listsubkey;
    157. }
    158. int main()
    159. {
    160. // Set the code page to support Chinese input and output
    161. _wsetlocale(LC_ALL, L".UTF8");
    162. HKEY topKey = HKEY_CURRENT_USER;
    163. std::wstring keyName = L"Control Panel\\NotifyIconSettings";
    164. std::wstring programFileName = L"Taskmgr.exe";
    165. // Find named TrayIconID
    166. std::wstring subkey = GetKeyNotifyIcon(topKey, keyName, programFileName);
    167. if (!subkey.empty())
    168. {
    169. // Get current IsPromoted value
    170. int isPromoted = GetNotifyIconIsPromoted(topKey, keyName + L"\\" + subkey);
    171. std::wstring registerPath = L"HKEY_CURRENT_USER\\" + keyName + L"\\" + subkey;
    172. std::wcout << "registerPath == " << registerPath << std::endl;
    173. std::wcout << "IsPromoted == " << isPromoted << std::endl;
    174. // Set IsPromoted to 1
    175. SetNotifyIconIsPromoted(topKey, keyName + L"\\" + subkey, 1);
    176. // Get the updated IsPromoted value
    177. isPromoted = GetNotifyIconIsPromoted(topKey, keyName + L"\\" + subkey);
    178. std::wcout << "IsPromoted == " << isPromoted << std::endl;
    179. }
    180. return 0;
    181. }

    【完】

    P.S.:本文讨论了在 Win11 22H2 上获取系统托盘图标信息的方法,即拦截 Shell_TrayWnd 窗口的 WM_COPYDATA 消息。我主要使用 Inline hook 重写 CTray::v_WndProc 函数,也就是窗口过程函数来拦截 WM_COPYDATA 消息。具体分析了两种注入 explorer 的实现方法:(1)创建挂起进程的远程线程注入;(2)模拟调试进程的 TLS 函数注入。

    事实上,挂钩 CTray::v_WndProc 函数并不是开销最小的方法。在第 4 篇文章中,我将分析通过 SetWindowsHookEx 实现消息钩子的角度分析如何拦截 WM_COPYDATA,该方法与拦截未导出的 CTray::v_WndProc 函数相比,将更加易于实现。


    本文属于原创文章,转载请注明出处:

    https://blog.csdn.net/qq_59075481/article/details/136134195

    本文发布于:2024.02.20,更新于:2024.03.04。

  • 相关阅读:
    真的够可以的,基于Netty实现了RPC框架
    windows server2012搭建邮箱服务器+客户端界面(hmailserver+afterlogic)+批量创建邮箱
    Laravel 实现redis分布式锁
    『MySQL快速上手』-⑤-数据类型
    零基础重庆自考本科行政管理难吗?
    计算机组成原理--------12.4---------开始
    JVM中JAVA对象和数组内存布局
    酷雷曼多种AI数字人形象,打造科技感VR虚拟展厅
    如何优雅的使用 GORM 来实现 MySQL 事务
    【总线】AXI4第四课时:握手机制详解
  • 原文地址:https://blog.csdn.net/qq_59075481/article/details/136134195