-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi.cpp
More file actions
333 lines (259 loc) · 10.2 KB
/
api.cpp
File metadata and controls
333 lines (259 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/*
COPYRIGHT (C) 2024 ETHAN CHAN
ALL RIGHTS RESERVED. UNAUTHORIZED COPYING, MODIFICATION, DISTRIBUTION, OR USE
OF THIS SOFTWARE WITHOUT PRIOR PERMISSION IS STRICTLY PROHIBITED.
THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM,
OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
PROJECT NAME: DieKnow
FILENAME: src/api.cpp
DESCRIPTION: API functions for DieKnow
AUTHOR: Ethan Chan
DATE: 2024-11-13
VERSION: 1.0.1
Compile with g++ -shared -o api.dll api.cpp -Ofast -fPIC -shared
*/
#include "api.h"
const char* FOLDER_PATH = "C:\\Program Files\\DyKnow\\Cloud";
Settings settings;
DK_API void validate() {
/*
Check for the validity of the DyKnow installation. If the DyKnow
installation cannot be found, the application exits.
Settings are loaded.
*/
bool needs_exit = false;
if (!std::filesystem::exists(FOLDER_PATH)) {
needs_exit = true
std::ostringstream msg;
msg << "A DyKnow installation was not able to be found on your device.\n"
<< "Ensure the folder \"" << FOLDER_PATH
<< "\" exists and you have the permissions to access it!\n\n"
<< "Additionally, ensure you have one of the supported DyKnow versions. "
<< "You may need to upgarde your DieKnow to a later version.";
MessageBox(nullptr, msg.str().c_str(), "FATAL ERROR", MB_ICONERROR);
}
else {
std::cout << "Successfully located DyKnow installation at "
<< FOLDER_PATH << ".\n";
}
bool loaded_settings = settings.load("./settings.conf");
if (loaded_settings)
std::cout << "Successfully loaded DieKnow configuration files.\n";
else
std::cout << "Failed to load DieKnow configuration files!\n";
needs_exit = true;
if (needs_exit) std::exit(EXIT_FAILURE);
}
bool exists(const char* path) {
/*
Check if a filepath exists.
*/
DWORD ftyp = GetFileAttributesA(path);
if (ftyp == INVALID_FILE_ATTRIBUTES) {
return false;
}
return (ftyp & FILE_ATTRIBUTE_DIRECTORY);
}
bool close_application_by_exe(const char* exe_name) {
/*
Close a Windows PE executable file given the executable name.
The win32 function `TerminateProcess()` is used, which has looser
privilleges than `taskkill`. It's uncommon that it will require
administrative permissions.
*/
bool terminated = false;
// Create a snapshot of all running process(es)
HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
// Break out if the snapshot failed
if (hProcessSnap == INVALID_HANDLE_VALUE) return false;
// Iterate through the process list and terminate them as desired
if (Process32First(hProcessSnap, &pe32)) {
// Populate `pe32` with process snapshot information
do {
// Check if the executable name is the one given as a parameter
if (_stricmp(pe32.szExeFile, exe_name) == 0) {
// Open a HANDLE to the process. This is a little ambiguous as
// it appears we are opening the process.
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pe32.th32ProcessID);
if (hProcess) {
TerminateProcess(hProcess, 0);
auto wait = [&]() {
DWORD result = WaitForSingleObject(hProcess, TIMEOUT);
switch (result) {
case WAIT_OBJECT_0:
terminated = true;
std::cout << "Process " << exe_name << " terminated successfully.\n";
break;
case WAIT_TIMEOUT:
std::cerr << "WaitForSingleObject timed out!\n";
break;
case WAIT_FAILED:
// std::cerr << "Failed to terminate " << exe_name << "!\n";
break;
default:
break;
}
};
std::thread wait_thread(wait);
wait_thread.join();
// Destroy the process handle to avoid memory leaks
CloseHandle(hProcess);
}
else {
std::cerr << "Failed to open a handle to the process!";
}
}
} while (Process32Next(hProcessSnap, &pe32));
}
// Destroy the snapshot to avoid memory leaks
CloseHandle(hProcessSnap);
if (terminated) killed++;
return terminated;
}
void monitor_executables(const char* folder_path) {
/*
Begin monitoring and closing of the executables in the given folder path.
A while loop will go through all of the executables in `FOLDER_PATH`. It
will then attempt to terminate them individually. The folder path is
refreshed each iteration of the loop.
An interval that can be specified in settings controls how often the
function is repeated. A low interval may cause high CPU usage while a low
interval may give DyKnow ample time to start back up.
If `FOLDER_PATH` cannot be validated, the `validate()` function is called.
*/
while (running) {
// Search recursively through folder_path and terminate all "*.exe"s
for (const auto& entry : std::filesystem::directory_iterator(folder_path)) {
// If it's a directory, go through its subfiles
if (entry.is_directory()) {
for (const auto& sub_entry : std::filesystem::directory_iterator(entry.path())) {
if ((sub_entry.is_regular_file()) &&
(sub_entry.path().extension() == ".exe")) {
close_application_by_exe(sub_entry.path().filename().string().c_str());
}
}
}
else {
validate();
}
}
int interval = settings.get<int>("interval", 0);
// Minimize CPU usage
std::this_thread::sleep_for(std::chrono::seconds(interval));
}
}
DK_API const char* get_folder_path() {
/*
Retrieve the default DyKnow folder path.
This is made into a function for use with ctypes.
*/
return FOLDER_PATH;
}
DK_API void start_monitoring(const char* folder_path = FOLDER_PATH) {
/*
Begin monitoring executables.
A separate thread is detached from the primary thread. This thread is set
with a lower priority to reduce CPU usage.
See `monitor_executables()`.
*/
if (!running) {
running = true;
std::thread thread(monitor_executables, folder_path);
HANDLE handle = reinterpret_cast<HANDLE>(thread.native_handle());
// Reduces CPU usage by prioritizing other applications.
// Other options:
// * IDLE - only run when its the only thread
// * LOWEST
// * BELOW_NORMAL
// * NORMAL - default priority
// * ABOVE_NORMAL
// * HIGHEST
// * TIME_CRITICAL
SetThreadPriority(handle, THREAD_PRIORITY_BELOW_NORMAL);
// Detach thread from main and start it
thread.detach();
}
else {
std::cout << "The DieKnow process has already been started!\n";
}
}
DK_API void stop_monitoring() {
/*
Stop monitoring executables.
*/
// Although just a variable is set to false, because the DieKnow process is
// in a separate thread it will finish immediately.
if (running) {
running = false;
std::cout << "Successfully stopped DieKnow process.\n";
}
else {
std::cout << "The DieKnow process has already been stopped!\n";
}
}
// Both get_killed_count and is_running must be declared as functions as ctypes
// does not support retrieving variables.
DK_API int get_killed_count() {
/*
Retrieve the amount of DyKnow executables killed.
*/
return killed;
}
DK_API bool is_running() {
/*
Check if DieKnow is running or not.
*/
return running;
}
DK_API const char* get_executables_in_folder(const char* folder_path) {
/*
Retrieve a printable list of executables in a folder.
*/
static std::string result;
result.clear();
for (const auto& entry : std::filesystem::directory_iterator(folder_path)) {
// If it's a directory, go through its subfiles
if (entry.is_directory()) {
for (const auto& sub_entry : std::filesystem::directory_iterator(entry.path())) {
if ((sub_entry.is_regular_file()) &&
(sub_entry.path().extension() == ".exe")) {
// Add newline to print out nicely
result += sub_entry.path().filename().string() + "\n";
}
}
}
else {
validate();
}
}
return result.c_str();
}
DK_API int __stdcall bsod() {
/*
Open the Windows Blue Screen of Death via win32api's `NtRaiseHardError`.
Use with caution! Your system will freeze and shut down within a few
seconds, losing any unsaved work.
*/
BOOLEAN bEnabled;
ULONG uResp;
// Load RtlAdjustPrivilege and NtRaiseHardError functions from ntdll.dll
auto RtlAdjustPrivilege = (NTSTATUS(WINAPI*)(ULONG, BOOLEAN, BOOLEAN, PBOOLEAN))
GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlAdjustPrivilege");
auto NtRaiseHardError = (NTSTATUS(WINAPI*)(NTSTATUS, ULONG, ULONG, PULONG_PTR, ULONG, PULONG))
GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtRaiseHardError");
if (!RtlAdjustPrivilege || !NtRaiseHardError) {
return -1;
}
// Enable shutdown privilege for this process
RtlAdjustPrivilege(19, TRUE, FALSE, &bEnabled);
// Trigger BSOD
NtRaiseHardError(STATUS_ASSERTION_FAILURE, 0, 0, nullptr, 6, &uResp);
return 0;
}