Mercurial > minori
comparison dep/animia/src/win32.cpp @ 56:6ff7aabeb9d7
deps: add animia for open files detection
author | Paper <mrpapersonic@gmail.com> |
---|---|
date | Thu, 28 Sep 2023 12:35:21 -0400 |
parents | |
children | 4c6dd5999b39 |
comparison
equal
deleted
inserted
replaced
54:466ac9870df9 | 56:6ff7aabeb9d7 |
---|---|
1 #include "win32.h" | |
2 #include <windows.h> | |
3 #include <winternl.h> | |
4 #include <libloaderapi.h> | |
5 #include <ntdef.h> | |
6 #include <psapi.h> | |
7 #include <tlhelp32.h> | |
8 #include <fileapi.h> | |
9 #include <handleapi.h> | |
10 #include <vector> | |
11 #include <iostream> | |
12 #include <string> | |
13 #include <unordered_map> | |
14 #include <stdexcept> | |
15 #include <locale> | |
16 #include <codecvt> | |
17 /* This file is noticably more complex than Unix and Linux, and that's because | |
18 there is no "simple" way to get the paths of a file. */ | |
19 | |
20 #define SystemExtendedHandleInformation ((SYSTEM_INFORMATION_CLASS)0x40) | |
21 constexpr NTSTATUS STATUS_INFO_LENGTH_MISMATCH = 0xC0000004UL; | |
22 constexpr NTSTATUS STATUS_SUCCESS = 0x00000000UL; | |
23 | |
24 static unsigned short file_type_index = 0; | |
25 | |
26 struct SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX { | |
27 PVOID Object; | |
28 ULONG_PTR UniqueProcessId; | |
29 HANDLE HandleValue; | |
30 ACCESS_MASK GrantedAccess; | |
31 USHORT CreatorBackTraceIndex; | |
32 USHORT ObjectTypeIndex; | |
33 ULONG HandleAttributes; | |
34 ULONG Reserved; | |
35 }; | |
36 | |
37 struct SYSTEM_HANDLE_INFORMATION_EX { | |
38 ULONG_PTR NumberOfHandles; | |
39 ULONG_PTR Reserved; | |
40 SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1]; | |
41 }; | |
42 | |
43 namespace Animia::Windows { | |
44 | |
45 std::vector<int> get_all_pids() { | |
46 std::vector<int> ret; | |
47 HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); | |
48 PROCESSENTRY32 pe32; | |
49 pe32.dwSize = sizeof(PROCESSENTRY32); | |
50 | |
51 if (hProcessSnap == INVALID_HANDLE_VALUE) | |
52 return std::vector<int>(); | |
53 | |
54 if (!Process32First(hProcessSnap, &pe32)) | |
55 return std::vector<int>(); | |
56 | |
57 ret.push_back(pe32.th32ProcessID); | |
58 while (Process32Next(hProcessSnap, &pe32)) { | |
59 ret.push_back(pe32.th32ProcessID); | |
60 } | |
61 // clean the snapshot object | |
62 CloseHandle(hProcessSnap); | |
63 | |
64 return ret; | |
65 } | |
66 | |
67 std::string get_process_name(int pid) { | |
68 HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); | |
69 if (!handle) | |
70 return ""; | |
71 | |
72 std::string ret(MAX_PATH, '\0'); | |
73 if (!GetModuleBaseNameA(handle, 0, &ret.front(), ret.size())) | |
74 throw std::runtime_error("GetModuleBaseNameA failed: " + std::to_string(GetLastError())); | |
75 CloseHandle(handle); | |
76 | |
77 return ret; | |
78 } | |
79 | |
80 /* All of this BS is required on Windows. Why? */ | |
81 | |
82 HANDLE DuplicateHandle(HANDLE process_handle, HANDLE handle) { | |
83 HANDLE dup_handle = nullptr; | |
84 const bool result = ::DuplicateHandle(process_handle, handle, | |
85 ::GetCurrentProcess(), &dup_handle, 0, false, DUPLICATE_SAME_ACCESS); | |
86 return result ? dup_handle : nullptr; | |
87 } | |
88 | |
89 PVOID GetNTDLLAddress(LPCSTR proc_name) { | |
90 return reinterpret_cast<PVOID>(GetProcAddress(GetModuleHandleA("ntdll.dll"), proc_name)); | |
91 } | |
92 | |
93 NTSTATUS QuerySystemInformation(SYSTEM_INFORMATION_CLASS cls, PVOID sysinfo, ULONG len, PULONG retlen) { | |
94 static const auto func = reinterpret_cast<decltype(::NtQuerySystemInformation)*>(GetNTDLLAddress("NtQuerySystemInformation")); | |
95 return func(cls, sysinfo, len, retlen); | |
96 } | |
97 | |
98 NTSTATUS QueryObject(HANDLE handle, OBJECT_INFORMATION_CLASS cls, PVOID objinf, ULONG objinflen, PULONG retlen) { | |
99 static const auto func = reinterpret_cast<decltype(::NtQueryObject)*>(GetNTDLLAddress("NtQueryObject")); | |
100 return func(handle, cls, objinf, objinflen, retlen); | |
101 } | |
102 | |
103 std::vector<SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX> GetSystemHandleInformation() { | |
104 std::vector<SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX> res; | |
105 ULONG cb = 1 << 19; | |
106 NTSTATUS status = STATUS_SUCCESS; | |
107 SYSTEM_HANDLE_INFORMATION_EX* info; | |
108 | |
109 do { | |
110 status = STATUS_NO_MEMORY; | |
111 | |
112 if (!(info = (SYSTEM_HANDLE_INFORMATION_EX*)malloc(cb *= 2))) | |
113 continue; | |
114 | |
115 if (0 <= (status = QuerySystemInformation(SystemExtendedHandleInformation, info, cb, &cb))) { | |
116 if (ULONG_PTR handles = info->NumberOfHandles) { | |
117 SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX* entry = info->Handles; | |
118 do { | |
119 if (entry) res.push_back(*entry); | |
120 } while (entry++, --handles); | |
121 } | |
122 } | |
123 free(info); | |
124 } while (status == STATUS_INFO_LENGTH_MISMATCH); | |
125 | |
126 return res; | |
127 } | |
128 | |
129 OBJECT_TYPE_INFORMATION QueryObjectTypeInfo(HANDLE handle) { | |
130 OBJECT_TYPE_INFORMATION info; | |
131 QueryObject(handle, ObjectTypeInformation, &info, sizeof(info), NULL); | |
132 return info; | |
133 } | |
134 | |
135 std::string UnicodeStringToStdString(UNICODE_STRING string) { | |
136 ANSI_STRING result; | |
137 static const auto uc_to_ansi = reinterpret_cast<decltype(::RtlUnicodeStringToAnsiString)*>(GetNTDLLAddress("RtlUnicodeStringToAnsiString")); | |
138 uc_to_ansi(&result, &string, TRUE); | |
139 std::string ret = std::string(result.Buffer, result.Length); | |
140 static const auto free_ansi = reinterpret_cast<decltype(::RtlFreeAnsiString)*>(GetNTDLLAddress("RtlFreeAnsiString")); | |
141 free_ansi(&result); | |
142 return ret; | |
143 } | |
144 | |
145 std::string GetHandleType(HANDLE handle) { | |
146 OBJECT_TYPE_INFORMATION info = QueryObjectTypeInfo(handle); | |
147 return UnicodeStringToStdString(info.TypeName); | |
148 } | |
149 | |
150 /* GetFinalPathNameByHandleA literally just doesn't work */ | |
151 std::string GetFinalPathNameByHandle(HANDLE handle) { | |
152 std::wstring buffer; | |
153 | |
154 int result = ::GetFinalPathNameByHandleW(handle, NULL, 0, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS); | |
155 buffer.resize(result); | |
156 ::GetFinalPathNameByHandleW(handle, &buffer.front(), buffer.size(), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS); | |
157 | |
158 std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; | |
159 | |
160 return converter.to_bytes(buffer); | |
161 } | |
162 | |
163 std::string GetSystemDirectory() { | |
164 std::string windir = std::string(MAX_PATH, '\0'); | |
165 ::GetWindowsDirectoryA(&windir.front(), windir.length()); | |
166 return "\\\\?\\" + windir; | |
167 } | |
168 | |
169 /* This function is useless. I'm not exactly sure why, but whenever I try to compare the two | |
170 values, they both come up as different. I'm assuming it's just some Unicode BS I can't be bothered | |
171 to deal with. */ | |
172 bool IsSystemDirectory(const std::string& path) { | |
173 std::string path_l = path; | |
174 CharUpperBuffA(&path_l.front(), path_l.length()); | |
175 | |
176 std::string windir = GetSystemDirectory(); | |
177 CharUpperBuffA(&windir.front(), windir.length()); | |
178 | |
179 return path_l.rfind(windir, 0) != std::string::npos; | |
180 } | |
181 | |
182 bool IsFileHandle(HANDLE handle, unsigned short object_type_index) { | |
183 if (file_type_index) | |
184 return object_type_index == file_type_index; | |
185 else if (!handle) | |
186 return true; | |
187 else if (GetHandleType(handle) == "File") { | |
188 file_type_index = object_type_index; | |
189 return true; | |
190 } | |
191 return false; | |
192 } | |
193 | |
194 bool IsFileMaskOk(ACCESS_MASK access_mask) { | |
195 /* this filters out any file handles that, legitimately, | |
196 do not make sense (for what we're using it for) | |
197 | |
198 shoutout to erengy for having these in Anisthesia */ | |
199 | |
200 if (!(access_mask & FILE_READ_DATA)) | |
201 return false; | |
202 | |
203 if ((access_mask & FILE_APPEND_DATA) || | |
204 (access_mask & FILE_WRITE_EA) || | |
205 (access_mask & FILE_WRITE_ATTRIBUTES)) | |
206 return false; | |
207 | |
208 return true; | |
209 } | |
210 | |
211 bool IsFilePathOk(const std::string& path) { | |
212 if (path.empty() || IsSystemDirectory(path)) | |
213 return false; | |
214 | |
215 const auto file_attributes = GetFileAttributesA(path.c_str()); | |
216 if ((file_attributes == INVALID_FILE_ATTRIBUTES) || | |
217 (file_attributes & FILE_ATTRIBUTE_DIRECTORY)) | |
218 return false; | |
219 | |
220 return true; | |
221 } | |
222 | |
223 std::vector<std::string> get_open_files(int pid) { | |
224 std::unordered_map<int, std::vector<std::string>> map = get_all_open_files(); | |
225 return map[pid]; | |
226 } | |
227 | |
228 std::unordered_map<int, std::vector<std::string>> get_all_open_files() { | |
229 std::unordered_map<int, std::vector<std::string>> map; | |
230 std::vector<SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX> info = GetSystemHandleInformation(); | |
231 for (auto& h : info) { | |
232 int pid = h.UniqueProcessId; | |
233 | |
234 if (!IsFileHandle(nullptr, h.ObjectTypeIndex)) | |
235 continue; | |
236 if (!IsFileMaskOk(h.GrantedAccess)) | |
237 continue; | |
238 | |
239 const HANDLE proc = ::OpenProcess(PROCESS_DUP_HANDLE, false, pid); | |
240 HANDLE handle = DuplicateHandle(proc, h.HandleValue); | |
241 if (!handle) | |
242 continue; | |
243 | |
244 if (GetFileType(handle) != FILE_TYPE_DISK) | |
245 continue; | |
246 | |
247 std::string path = GetFinalPathNameByHandle(handle); | |
248 if (!IsFilePathOk(path)) | |
249 continue; | |
250 | |
251 if (map.find(pid) == map.end()) | |
252 map[pid] = {}; | |
253 map[pid].push_back(path); | |
254 } | |
255 return map; | |
256 } | |
257 | |
258 } |