-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdllmain.cpp
1750 lines (1474 loc) · 80 KB
/
dllmain.cpp
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Imoprting the required modules
#include "pch.h"
#include "cpu.h"
#include <Windows.h>
#include <thread>
#include <iostream>
#include <map>
#include <string>
#include <cstring>
#include <vector>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <sstream>
#include <winsock.h>
#include <chrono>
#include <tlhelp32.h>
#include <cmath>
#include <limits>
using std::ostringstream;
using std::ends;
#pragma comment(lib,"ws2_32.lib")
/*
Defining functions that are being hooked:
HANDLE CreateFileA(
[in] LPCSTR lpFileName,
[in] DWORD dwDesiredAccess,
[in] DWORD dwShareMode,
[in, optional] LPSECURITY_ATTRIBUTES lpSecurityAttributes,
[in] DWORD dwCreationDisposition,
[in] DWORD dwFlagsAndAttributes,
[in, optional] HANDLE hTemplateFile);
);
BOOL DeleteFileA(
[in] LPCSTR lpFileName
);
BOOL WriteFileEx(
[in] HANDLE hFile,
[in, optional] LPCVOID lpBuffer,
[in] DWORD nNumberOfBytesToWrite,
[in, out] LPOVERLAPPED lpOverlapped,
[in] LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
LPVOID VirtualAlloc(
[in, optional] LPVOID lpAddress,
[in] SIZE_T dwSize,
[in] DWORD flAllocationType,
[in] DWORD flProtect
);
HANDLE CreateThread(
[in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes,
[in] SIZE_T dwStackSize,
[in] LPTHREAD_START_ROUTINE lpStartAddress,
[in, optional] __drv_aliasesMem LPVOID lpParameter,
[in] DWORD dwCreationFlags,
[out, optional] LPDWORD lpThreadId
);
LSTATUS RegOpenKeyExA(
[in] HKEY hKey,
[in, optional] LPCSTR lpSubKey,
[in] DWORD ulOptions,
[in] REGSAM samDesired,
[out] PHKEY phkResult
);
LSTATUS RegSetValueExA(
[in] HKEY hKey,
[in, optional] LPCSTR lpValueName,
DWORD Reserved,
[in] DWORD dwType,
[in] const BYTE *lpData,
[in] DWORD cbData
);
LSTATUS RegCreateKeyExA(
[in] HKEY hKey,
[in] LPCSTR lpSubKey,
DWORD Reserved,
[in, optional] LPSTR lpClass,
[in] DWORD dwOptions,
[in] REGSAM samDesired,
[in, optional] const LPSECURITY_ATTRIBUTES lpSecurityAttributes,
[out] PHKEY phkResult,
[out, optional] LPDWORD lpdwDisposition
);
LSTATUS RegGetValueA(
[in] HKEY hkey,
[in, optional] LPCSTR lpSubKey,
[in, optional] LPCSTR lpValue,
[in, optional] DWORD dwFlags,
[out, optional] LPDWORD pdwType,
[out, optional] PVOID pvData,
[in, out, optional] LPDWORD pcbData
);
SOCKET WSAAPI socket(
[in] int af,
[in] int type,
[in] int protocol
);
int WSAAPI connect(
[in] SOCKET s,
[in] const sockaddr *name,
[in] int namelen
);
int WSAAPI send(
[in] SOCKET s,
[in] const char *buf,
[in] int len,
[in] int flags
);
int recv(
[in] SOCKET s,
[out] char *buf,
[in] int len,
[in] int flags
);
BOOL CloseHandle(
[in] HANDLE hObject
);
BOOL WriteFile(
[in] HANDLE hFile,
[in] LPCVOID lpBuffer,
[in] DWORD nNumberOfBytesToWrite,
[out, optional] LPDWORD lpNumberOfBytesWritten,
[in, out, optional] LPOVERLAPPED lpOverlapped
);
HANDLE OpenProcess(
DWORD dwDesiredAccess,
BOOL bInheritHandle,
DWORD dwProcessId
);
LPVOID VirtualAllocEx(
HANDLE hProcess,
LPVOID lpAddress,
SIZE_T dwSize,
DWORD flAllocationType,
DWORD flProtect
);
HANDLE CreateRemoteThread(
HANDLE hProcess,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId
);
HHOOK SetWindowsHookExA(
int idHook,
HOOKPROC lpfn,
HINSTANCE hMod,
DWORD dwThreadId
);
BOOL GetKeyboardState(
PBYTE lpKeyState
);
DWORD SetFilePointer(
HANDLE hFile,
LONG lDistanceToMove,
PLONG lpDistanceToMoveHigh,
DWORD dwMoveMethod
);
// std::vector<LPVOID> winapi_functions = { CreateFileA, DeleteFileA, WriteFileEx, WriteFile, VirtualAlloc, CreateThread, OpenProcess, VirtualAllocEx, CreateRemoteThread, CloseHandle, RegOpenKeyExA, RegSetValueExA, RegCreateKeyExA, RegGetValueA, socket, connect, send, recv };
*/
// Intializing maps and lists of suspicious function
std::map<const char*, void*> fnMap;
std::map<std::string, int> fnCounter;
std::vector<const char*> suspicious_functions = { "CreateFileA", "DeleteFileA", "WriteFileEx", "WriteFile", "VirtualAlloc", "CreateThread", "OpenProcess", "VirtualAllocEx", "CreateRemoteThread", "CloseHandle", "RegOpenKeyExA", "RegSetValueExA", "RegCreateKeyExA", "RegGetValueA", "socket", "connect", "send", "recv", "SetWindowsHookExA", "GetKeyboardState", "SetFilePointer"};
std::vector<FARPROC> addresses(21);
std::vector<char[6]> original(21);
std::map<HANDLE, int> handle_counter;
std::map<const char*, int> function_index;
// Vectors for the parameters from the parameters file
std::vector<std::string> files(1);
std::vector<std::string> ports(1);
std::vector<std::string> keys(1);
// Declarations
void SetInlineHook(LPCSTR lpProcName, const char* library, const char* funcName, int index);
void FreeHook(int index);
HANDLE hFile;
int writeFileIndex = 0;
// Cpu
double cpuPermitted = 0.0;
double maxCpu = 0;
// Port scanning variables
const char* remote_ip; std::string injected_process = "";
int connect_count = 0, run_once = 1; bool portScanner = false;
// Keboard hook counter
int keyboard_hook = 0;
int show_identified = 0;
namespace FindProcess {
/**
* Namespace containing functions to find process ID and process name.
*/
DWORD FindProcessId(const std::wstring& processName)
{
/**
* Finds the process ID of a given process name.
* @param processName The name of the process to find.
* @return The process ID if found, otherwise 0.
*/
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processesSnapshot == INVALID_HANDLE_VALUE) {
return 0;
}
Process32First(processesSnapshot, &processInfo);
if (!processName.compare(processInfo.szExeFile))
{
//CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
while (Process32Next(processesSnapshot, &processInfo))
{
if (!processName.compare(processInfo.szExeFile))
{
//CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
}
//CloseHandle(processesSnapshot);
return 0;
}
const std::wstring FindProcessName(DWORD id)
{
/**
* Finds the process name of a given process ID.
* @param id The process ID to find.
* @return The process name if found, otherwise an empty string.
*/
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processesSnapshot == INVALID_HANDLE_VALUE) {
return 0;
}
Process32First(processesSnapshot, &processInfo);
if (processInfo.th32ProcessID == id)
{
//CloseHandle(processesSnapshot);
return processInfo.szExeFile;
}
while (Process32Next(processesSnapshot, &processInfo))
{
if (processInfo.th32ProcessID == id)
{
//CloseHandle(processesSnapshot);
return processInfo.szExeFile;
}
}
//CloseHandle(processesSnapshot);
return 0;
}
}
namespace StringAnalyzer {
/**
* Namespace containing functions for string analysis.
*/
int CountString(std::string s, char a) {
/**
* Counts the occurrences of a character in a given string.
* @param s The input string.
* @param a The character to count.
* @return The number of occurrences of the character in the string.
*/
int count = 0;
for (size_t i = 0; i < s.length(); i++)
{
if (s[i] == a) count++;
}
return count;
}
bool CompareStrings(std::string s1, std::string s2) {
/**
* Compares two strings for equality.
* @param s1 The first string to compare.
* @param s2 The second string to compare.
* @return True if the strings are equal, false otherwise.
*/
for (size_t i = 0; i < s1.length(); i++)
{
if ((char)s1[i] != (char)s2[i]) return false;
}
return true;
}
}
namespace CheckContain {
/**
* Namespace containing functions for checking containment.
*/
bool contains(std::vector<std::string> vec, std::string elem, bool Compare)
{
/**
* Checks if a vector contains a specified element.
* @param vec The input vector of strings.
* @param elem The element to search for.
* @param Compare True to perform exact string comparison, false to check substring containment.
* @return True if the vector contains the element based on the specified comparison mode, false otherwise.
*/
bool result = false;
if (Compare) {
for (std::string x : vec) {
if (StringAnalyzer::CompareStrings(elem, x)) return true;
}
}
else {
for (size_t i = 1; i < vec.size(); i++)
{
if (elem.find(vec[i]) != std::string::npos)
{
result = true;
break;
}
}
}
return result;
}
bool ContainsHandle(HANDLE h) {
/**
* Checks if a given handle exists in the handle_counter.
* @param h The handle to check.
* @return True if the handle exists in the handle_counter, false otherwise.
*/
if (handle_counter.find(h) == handle_counter.end())
return false;
return true;
}
}
// Clock
std::chrono::steady_clock::time_point begin;
template<typename T>
void LOG(const char* message, T parameter) {
/**
* Logs a message with a parameter to a file.
* @param message The message to log.
* @param parameter The parameter to include in the log.
*/
FreeHook(writeFileIndex);
WriteFile(hFile, message, strlen(message), NULL, nullptr);
//WriteFile(hFile, "\n", strlen("\n"), NULL, nullptr);
// Convert the parameter to a string
ostringstream oss;
ostringstream oss2;
oss << parameter << ends;
// LOG the parameter
std::string param = oss.str().c_str();
if (param == std::string("-nan(ind)")) {
WriteFile(hFile, "0", strlen("0"), NULL, nullptr);
}
else {
WriteFile(hFile, oss.str().c_str(), strlen(oss.str().c_str()), NULL, nullptr);
}
WriteFile(hFile, "\n", strlen("\n"), NULL, nullptr);
SetInlineHook("WriteFile", "kernel32.dll", "WriteFileHook", writeFileIndex);
}
struct REGISTRY_HOOKING {
/**
* Hook functions for the Registry API.
*/
static void __stdcall RegOpenKeyExAHook(HKEY hKey, LPCSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult) {
/**
* Hook function for the RegOpenKeyExA API.
* @param hKey The handle to the open key or one of the predefined reserved handle values.
* @param lpSubKey The name of the registry subkey to be opened.
* @param ulOptions The option to apply when opening the key.
* @param samDesired A mask that specifies the desired access rights to the key to be opened.
* @param phkResult A pointer to a variable that receives a handle to the opened key.
*/
bool run_key = false;
LOG("\n----------intercepted call to RegOpenKeyExA----------\n\n", "");
if (hKey == ((HKEY)(ULONG_PTR)((LONG)0x80000002))) {
LOG("The key opened is ", "HKEY_LOCAL_MACHINE");
}
if (hKey == ((HKEY)(ULONG_PTR)((LONG)0x80000001))) {
LOG("The key opened is ", "HKEY_CURRENT_USER");
}
LOG("The name of the registry subkey to be opened is ", lpSubKey);
LOG("The option to apply when opening the key is ", ulOptions);
if (samDesired == 0xF003F)
LOG("A mask that specifies the desired access rights to the key to be opened is ", "KEY_ALL_ACCESS");
if (CheckContain::contains(keys, std::string(lpSubKey), true))
LOG("EXE is trying to access a suspicious registry key!", "");
int index = function_index["RegOpenKeyExA"];
++fnCounter[suspicious_functions[index]];
//if ((hKey == ((HKEY)(ULONG_PTR)((LONG)0x80000001)) || hKey == ((HKEY)(ULONG_PTR)((LONG)0x80000002))) &&
// lpSubKey == (LPCSTR)"Software\\Microsoft\\Windows\\CurrentVersion\\Run") {
// LOG("\nExe probably trying to execute a file after every rebot through a Run key!!", "");
//
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
ostringstream oss;
oss << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << ends;
std::string time_difference = std::string(oss.str().c_str());
time_difference.insert(1, ".");
LOG("Time difference since attachment of hooks in [s] is ", time_difference);
double cpuUsage = getCurrentValue();
if (cpuUsage == -std::nan("ind")) cpuUsage = 0;
if (cpuUsage < cpuUsage) cpuUsage = cpuUsage;
while (cpuUsage > 100.0) cpuUsage -= 70.0;
if (cpuUsage > cpuPermitted) LOG("Has passed permitted cpu", "");
LOG("The current cpu usage percantage [%] is ", cpuUsage);
LOG("The number of times user is trying to open a registry key is ", fnCounter[suspicious_functions[index]]);
LOG("\n----------Done intercepting call to RegOpenKeyExA----------\n\n\n\n\n", "");
WriteProcessMemory(GetCurrentProcess(), (LPVOID)addresses[index], original[index], 6, NULL);
RegOpenKeyExA(hKey, lpSubKey, ulOptions, samDesired, phkResult);
return SetInlineHook("RegOpenKeyExA", "advapi32.dll", "RegOpenKeyExAHook", function_index["RegOpenKeyExA"]);
}
static void __stdcall RegSetValueExAHook(HKEY hKey, LPCSTR lpValueName, DWORD Reserved, DWORD dwType, const BYTE* lpData, DWORD cbData) {
/**
* Hook function for the RegSetValueExA API.
* @param hKey The handle to the open key or one of the predefined reserved handle values.
* @param lpValueName The name of the value to be set.
* @param Reserved Reserved; must be zero.
* @param dwType The type of data to be stored.
* @param lpData A pointer to the data to be stored.
* @param cbData The size, in bytes, of the information pointed to by the lpData parameter.
*/
LOG("\n----------intercepted call to RegSetValueExA----------\n\n", "");
LOG("The key opened is ", hKey);
LOG("The name of the value to be set is ", lpValueName);
if (dwType == 4ul)
LOG("The type of data set is ", "REG_DWORD");
if (dwType == 1ul)
LOG("The type of data set is ", "REG_SZ");
LOG("The data to be stored is ", lpData);
int index = function_index["RegSetValueExA"];
++fnCounter[suspicious_functions[index]];
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
ostringstream oss;
oss << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << ends;
std::string time_difference = std::string(oss.str().c_str());
time_difference.insert(1, ".");
LOG("Time difference since attachment of hooks in [s] is ", time_difference);
double cpuUsage = getCurrentValue();
if (cpuUsage == -std::nan("ind")) cpuUsage = 0;
if (cpuUsage < cpuUsage) cpuUsage = cpuUsage;
while (cpuUsage > 100.0) cpuUsage -= 70.0;
if (cpuUsage > cpuPermitted) LOG("Has passed permitted cpu", "");
LOG("The current cpu usage percantage [%] is ", cpuUsage);
LOG("The number of times user is trying to set a registry key is ", fnCounter[suspicious_functions[index]]);
LOG("\n----------Done intercepting call to RegSetValueExA----------\n\n\n\n\n", "");
WriteProcessMemory(GetCurrentProcess(), (LPVOID)addresses[index], original[index], 6, NULL);
RegSetValueExA(hKey, lpValueName, Reserved, dwType, lpData, cbData);
return SetInlineHook("RegSetValueExA", "advapi32.dll", "RegSetValueExAHook", function_index["RegSetValueExA"]);
}
static void __stdcall RegCreateKeyExAHook(HKEY hKey, LPCSTR lpSubKey, DWORD Reserved, LPSTR lpClass, DWORD dwOptions, REGSAM samDesired, const LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition) {
/**
* Hook function for the RegCreateKeyExA API.
* @param hKey A handle to an open registry key or one of the predefined reserved handle values.
* @param lpSubKey The name of a subkey that this function opens or creates.
* @param Reserved This parameter is reserved and must be zero.
* @param lpClass The user-defined class type of this key.
* @param dwOptions This parameter is reserved and must be zero.
* @param samDesired A mask that specifies the desired access rights to the key to be opened or created.
* @param lpSecurityAttributes A pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes.
* @param phkResult A pointer to a variable that receives a handle to the opened or created key.
* @param lpdwDisposition A pointer to a variable that receives one of the following disposition values.
* - REG_CREATED_NEW_KEY: The key did not exist and was created.
* - REG_OPENED_EXISTING_KEY: The key existed and was simply opened without being changed.
*/
LOG("\n----------intercepted call to RegCreateKeyExA----------\n\n", "");
if (hKey == ((HKEY)(ULONG_PTR)((LONG)0x80000002))) {
LOG("The key opened is ", "HKEY_LOCAL_MACHINE");
}
else if (hKey == ((HKEY)(ULONG_PTR)((LONG)0x80000001))) {
LOG("The key opened is ", "HKEY_CURRENT_USER");
}
else {
LOG("The key opened is ", hKey);
}
LOG("The name of a subkey that this function opens or creates is ", lpSubKey);
if (dwOptions == 0x00000000L)
LOG("This key is not volatile", "");
if (samDesired == 0xF003F)
LOG("A mask that specifies the desired access rights to the key to be opened is ", "KEY_ALL_ACCESS");
int index = function_index["RegCreateKeyExA"];
++fnCounter[suspicious_functions[index]];
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
ostringstream oss;
oss << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << ends;
std::string time_difference = std::string(oss.str().c_str());
time_difference.insert(1, ".");
LOG("Time difference since attachment of hooks in [s] is ", time_difference);
double cpuUsage = getCurrentValue();
if (cpuUsage == -std::nan("ind")) cpuUsage = 0;
if (cpuUsage < cpuUsage) cpuUsage = cpuUsage;
while (cpuUsage > 100.0) cpuUsage -= 70.0;
if (cpuUsage > cpuPermitted) LOG("Has passed permitted cpu", "");
LOG("The current cpu usage percantage [%] is ", cpuUsage);
LOG("The number of times user is trying to create a registry key is ", fnCounter[suspicious_functions[index]]);
LOG("\n----------Done intercepting call to RegCreateKeyExA----------\n\n\n\n\n", "");
WriteProcessMemory(GetCurrentProcess(), (LPVOID)addresses[index], original[index], 6, NULL);
RegCreateKeyExA(hKey, lpSubKey, Reserved, lpClass, dwOptions, samDesired, lpSecurityAttributes, phkResult, lpdwDisposition);
return SetInlineHook("RegCreateKeyExA", "advapi32.dll", "RegCreateKeyExAHook", function_index["RegCreateKeyExA"]);
}
static void __stdcall RegGetValueAHook(HKEY hkey, LPCSTR lpSubKey, LPCSTR lpValue, DWORD dwFlags, LPDWORD pdwType, PVOID pvData, LPDWORD pcbData) {
/**
* Hook function for the RegGetValueA API.
* @param hkey A handle to an open registry key.
* @param lpSubKey The name of the subkey that contains the desired value.
* @param lpValue The name of the registry value.
* @param dwFlags The flags that restrict the data type of value to be queried.
* @param pdwType A pointer to a variable that receives a code indicating the type of data stored in the specified value.
* @param pvData A pointer to a buffer that receives the value's data.
* @param pcbData A pointer to a variable that specifies the size of the buffer pointed to by the pvData parameter, in bytes.
* When the function returns, this variable contains the size of the data copied to pvData.
*/
LOG("\n----------intercepted call to RegGetValueA----------\n\n", "");
if (hkey == ((HKEY)(ULONG_PTR)((LONG)0x80000002))) {
LOG("The key opened is ", "HKEY_LOCAL_MACHINE");
}
if (hkey == ((HKEY)(ULONG_PTR)((LONG)0x80000001))) {
LOG("The key opened is ", "HKEY_CURRENT_USER");
}
LOG("The name of a subkey that this function opens or creates is ", lpSubKey);
LOG("The name of the Registry Value Name this function is trying to reach is ", lpValue);
if (dwFlags == 0x0000ffff)
LOG("The specified flags for this questions is ", "RRF_RT_ANY");
int index = function_index["RegGetValueA"];
++fnCounter[suspicious_functions[index]];
WriteProcessMemory(GetCurrentProcess(), (LPVOID)addresses[index], original[index], 6, NULL);
char value[255];
DWORD BufferSize = 8192;
RegGetValueA(hkey, lpSubKey, lpValue, dwFlags, pdwType, (PVOID)&value, &BufferSize);
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
ostringstream oss;
oss << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << ends;
std::string time_difference = std::string(oss.str().c_str());
time_difference.insert(1, ".");
LOG("Time difference since attachment of hooks in [s] is ", time_difference);
double cpuUsage = getCurrentValue();
if (cpuUsage == -std::nan("ind")) cpuUsage = 0;
if (cpuUsage < cpuUsage) cpuUsage = cpuUsage;
while (cpuUsage > 100.0) cpuUsage -= 70.0;
if (cpuUsage > cpuPermitted) LOG("Has passed permitted cpu", "");
LOG("The current cpu usage percantage [%] is ", cpuUsage);
LOG("The Registry Value Data this function was trying to get to is ", value);
LOG("The number of times user is trying to get a registry value is ", fnCounter[suspicious_functions[index]]);
LOG("\n----------Done intercepting call to RegGetValueA----------\n\n\n\n\n", "");
return SetInlineHook("RegGetValueA", "advapi32.dll", "RegGetValueAHook", function_index["RegGetValueA"]);
}
};
struct SOCKET_HOOKING {
/**
* Hook functions for the Socket API.
*/
static SOCKET __stdcall socketHook(int af, int type, int protocol) {
/**
* Hook function for the socket API.
* @param af The address family specification for the new socket.
* @param type The type specification for the new socket.
* @param protocol The protocol to be used.
* @return The newly created socket.
*/
LOG("\n----------intercepted call to socket----------\n\n", "");
if (af == 2)
LOG("The address family specification is ", "(IPv4) address family - AF_INET");
if (type == 1)
LOG("The type specification for the new socket is ", "TCP SOCK_STREAM");
if (type == 2)
LOG("The type specification for the new socket is ", "UDP SOCK_DGRAM");
if (protocol == 1)
LOG("The protocol to be used is ", "ICMP");
if (protocol == 6)
LOG("The protocol to be used is ", "TCP");
if (protocol == 17)
LOG("The protocol to be used is ", "UDP");
int index = function_index["socket"];
++fnCounter[suspicious_functions[index]];
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
ostringstream oss;
oss << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << ends;
std::string time_difference = std::string(oss.str().c_str());
time_difference.insert(1, ".");
LOG("Time difference since attachment of hooks in [s] is ", time_difference);
double cpuUsage = getCurrentValue();
if (cpuUsage == -std::nan("ind")) cpuUsage = 0;
if (cpuUsage < cpuUsage) cpuUsage = cpuUsage;
while (cpuUsage > 100.0) cpuUsage -= 70.0;
if (cpuUsage > cpuPermitted) LOG("Has passed permitted cpu", "");
LOG("The current cpu usage percantage [%] is ", cpuUsage);
LOG("The number of times user is trying to create a socket is ", fnCounter[suspicious_functions[index]]);
LOG("\n----------Done intercepting call to socket----------\n\n\n\n\n", "");
WriteProcessMemory(GetCurrentProcess(), (LPVOID)addresses[index], original[index], 6, NULL);
SOCKET sock = socket(af, type, protocol);
SetInlineHook("socket", "Ws2_32.dll", "socketHook", function_index["socket"]);
return sock;
}
static int __stdcall connectHook(SOCKET s, const sockaddr* name, int namelen) {
/**
* Hook function for the connect API.
* @param s The socket to connect.
* @param name The address to connect to.
* @param namelen The length of the address structure.
* @return The result of the connect operation.
*/
struct sockaddr_in* sin = (struct sockaddr_in*)name;
uint16_t port;
port = htons(sin->sin_port);
ostringstream oss;
oss << port << ends;
char* ip = inet_ntoa((*sin).sin_addr);
if (run_once == 1) remote_ip = ip; run_once = 0;
LOG("\n----------intercepted call to connect----------\n\n", "");
if (CheckContain::contains(ports, std::string(oss.str()), true))
LOG("EXE is trying to connect through a suspicious port!", "");
LOG("The address socket is trying to connect to is ", ip);
LOG("The port socket is using to connect is ", port);
int index = function_index["connect"];
if (run_once == 0) {
if (fnCounter[suspicious_functions[index]] + 1 == fnCounter[suspicious_functions[function_index["socket"]]] && remote_ip == ip) {
connect_count++;
}
if (connect_count >= 3) {
portScanner = true;
LOG("\n----------IDENTIFIED PORT SCANNING----------\n", "");
connect_count = 0;
}
}
++fnCounter[suspicious_functions[index]];
ostringstream oss2;
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
oss2 << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << ends;
std::string time_difference = std::string(oss2.str().c_str());
time_difference.insert(1, ".");
LOG("Time difference since attachment of hooks in [s] is ", time_difference);
double cpuUsage = getCurrentValue();
if (cpuUsage == -std::nan("ind")) cpuUsage = 0;
if (cpuUsage < cpuUsage) cpuUsage = cpuUsage;
while (cpuUsage > 100.0) cpuUsage -= 70.0;
if (cpuUsage > cpuPermitted) LOG("Has passed permitted cpu", "");
LOG("The current cpu usage percantage [%] is ", cpuUsage);
LOG("The number of times user is trying to connect to another socket is ", fnCounter[suspicious_functions[index]]);
LOG("\n----------Done intercepting call to connect----------\n\n\n\n\n", "");
WriteProcessMemory(GetCurrentProcess(), (LPVOID)addresses[index], original[index], 6, NULL);
int r = connect(s, name, namelen);
SetInlineHook("connect", "Ws2_32.dll", "connectHook", function_index["connect"]);
return r;
}
static int __stdcall sendHook(SOCKET s, const char* buff, int len, int flags) {
/**
* Hook function for the send API.
* @param s The socket to send data through.
* @param buff The buffer containing the data to send.
* @param len The length of the buffer.
* @param flags Flags specifying the way in which the call is made.
* @return The result of the send operation.
*/
LOG("\n----------intercepted call to send----------\n\n", "");
LOG("The buffer wanted to be send is ", std::string(buff));
LOG("The length of the buffer is ", len);
int index = function_index["send"];
++fnCounter[suspicious_functions[index]];
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
ostringstream oss;
oss << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << ends;
std::string time_difference = std::string(oss.str().c_str());
time_difference.insert(1, ".");
LOG("Time difference since attachment of hooks in [s] is ", time_difference);
double cpuUsage = getCurrentValue();
if (cpuUsage == -std::nan("ind")) cpuUsage = 0;
if (cpuUsage < cpuUsage) cpuUsage = cpuUsage;
while (cpuUsage > 100.0) cpuUsage -= 70.0;
if (cpuUsage > cpuPermitted) LOG("Has passed permitted cpu", "");
LOG("The current cpu usage percantage [%] is ", cpuUsage);
LOG("The number of times user is trying to send message via socket is ", fnCounter[suspicious_functions[index]]);
LOG("\n----------Done intercepting call to send----------\n\n\n\n\n", "");
WriteProcessMemory(GetCurrentProcess(), (LPVOID)addresses[index], original[index], 6, NULL);
int b = send(s, buff, len, flags);
SetInlineHook("send", "Ws2_32.dll", "sendHook", index);
return b;
}
static int __stdcall recvHook(SOCKET s, char* buff, int len, int flags) {
/**
* Hook function for the recv API.
* @param s The socket to receive data from.
* @param buff The buffer to store the received data.
* @param len The maximum length of the buffer.
* @param flags Flags specifying the way in which the call is made.
* @return The result of the recv operation.
*/
LOG("\n----------intercepted call to recv----------\n\n", "");
int index = function_index["recv"];
WriteProcessMemory(GetCurrentProcess(), (LPVOID)addresses[index], original[index], 6, NULL);
int b = recv(s, buff, len, flags);
LOG("The buffer socket recieved is \n\n", buff);
LOG("\n", "\n");
size_t length = strlen(buff);
LOG("The length of the buffer is ", length);
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
ostringstream oss;
oss << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << ends;
std::string time_difference = std::string(oss.str().c_str());
time_difference.insert(1, ".");
LOG("Time difference since attachment of hooks in [s] is ", time_difference);
double cpuUsage = getCurrentValue();
if (cpuUsage == -std::nan("ind")) cpuUsage = 0;
if (cpuUsage < cpuUsage) cpuUsage = cpuUsage;
while (cpuUsage > 100.0) cpuUsage -= 70.0;
if (cpuUsage > cpuPermitted) LOG("Has passed permitted cpu", "");
LOG("The current cpu usage percantage [%] is ", cpuUsage);
++fnCounter[suspicious_functions[index]];
LOG("The number of times user is trying to receive a buffer is ", fnCounter[suspicious_functions[index]]);
LOG("\n----------Done intercepting call to recv----------\n\n\n\n\n", "");
SetInlineHook("recv", "Ws2_32.dll", "recvHook", index);
return b;
}
};
struct FILE_HOOKING {
/**
* Hook functions for the File API.
*/
static void __stdcall CreateFileAHook(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) {
/**
* Hook function for the CreateFileA API.
* @param lpFileName The name of the file or device to be created or opened.
* @param dwDesiredAccess The requested access to the file or device.
* @param dwShareMode The requested sharing mode of the file or device.
* @param lpSecurityAttributes A pointer to a SECURITY_ATTRIBUTES structure.
* @param dwCreationDisposition An action to take on a file or device that exists or does not exist.
* @param dwFlagsAndAttributes The file or device attributes and flags.
* @param hTemplateFile A handle to a template file.
*/
LOG("\n----------intercepted call to CreateFileA----------\n\n", "");
if (CheckContain::contains(files, std::string(lpFileName), false))
LOG("EXE file is tring to reach a suspicious folder!", "");
LOG("The name of the file or device to be created or opened is ", lpFileName);
LOG("The requested access to the file or device is ", dwDesiredAccess);
LOG("The requested sharing mode of the file or device is ", dwShareMode);
if (dwCreationDisposition == 2)
LOG("An action to take on a file or device that exists or does not exist is ", "CREATE_ALWAYS");
if (dwCreationDisposition == 1)
LOG("An action to take on a file or device that exists or does not exist is ", "CREATE_NEW");
if (dwCreationDisposition == 4)
LOG("An action to take on a file or device that exists or does not exist is ", "OPEN_ALWAYS");
if (dwCreationDisposition == 3)
LOG("An action to take on a file or device that exists or does not exist is ", "OPEN_EXISTING");
if (dwCreationDisposition == 5)
LOG("An action to take on a file or device that exists or does not exist is ", "TRUNCATE_EXISTING");
if (dwFlagsAndAttributes == 128)
LOG("The Flags and Attributes that user is trying for the file are ", "NORMAL");
if (dwFlagsAndAttributes == 16384)
LOG("The Flags and Attributes that user is trying for the file are ", "ENCRYPTED");
if (dwFlagsAndAttributes == 4096)
LOG("The Flags and Attributes that user is trying for the file are ", "OFFLINE");
if (dwFlagsAndAttributes == 2)
LOG("The Flags and Attributes that user is trying for the file are ", "HIDDEN");
if (dwFlagsAndAttributes == 256)
LOG("The Flags and Attributes that user is trying for the file are ", "TEMPORARY");
int index = function_index["CreateFileA"];
++fnCounter[suspicious_functions[index]];
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
ostringstream oss;
oss << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << ends;
std::string time_difference = std::string(oss.str().c_str());
time_difference.insert(1, ".");
LOG("Time difference since attachment of hooks in [s] is ", time_difference);
double cpuUsage = getCurrentValue();
if (cpuUsage == -std::nan("ind")) cpuUsage = 0;
if (cpuUsage < cpuUsage) cpuUsage = cpuUsage;
while (cpuUsage > 100.0) cpuUsage -= 70.0;
if (cpuUsage > cpuPermitted) LOG("Has passed permitted cpu", "");
LOG("The current cpu usage percantage [%] is ", cpuUsage);
LOG("The number of times user is trying to create a file is ", fnCounter[suspicious_functions[index]]);
LOG("\n----------Done intercepting call to CreateFileA----------\n\n\n\n\n", "");
WriteProcessMemory(GetCurrentProcess(), (LPVOID)addresses[index], original[index], 6, NULL);
CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
return SetInlineHook("CreateFileA", "kernel32.dll", "CreateFileAHook", index);
}
static int __stdcall DeleteFileAHook(LPCSTR lpFileName) {
/**
* Hook function for the DeleteFileA API.
* @param lpFileName The path to the file that is to be deleted.
* @return Non-zero if the function succeeds, zero otherwise.
*/
LOG("\n----------intercepted call to DeleteFileA----------\n\n", "");
LOG("The path to the file that is to be deleted is ", lpFileName);
int index = function_index["DeleteFileA"];
++fnCounter[suspicious_functions[index]];
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
ostringstream oss;
oss << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << ends;
std::string time_difference = std::string(oss.str().c_str());
time_difference.insert(1, ".");
LOG("Time difference since attachment of hooks in [s] is ", time_difference);
LOG("The number of times user is trying to delete a file is ", fnCounter[suspicious_functions[index]]);
double cpuUsage = getCurrentValue();
if (cpuUsage == -std::nan("ind")) cpuUsage = 0;
if (cpuUsage < cpuUsage) cpuUsage = cpuUsage;
while (cpuUsage > 100.0) cpuUsage -= 70.0;
if (cpuUsage > cpuPermitted) LOG("Has passed permitted cpu", "");
LOG("The current cpu usage percantage [%] is ", cpuUsage);
LOG("\n----------Done intercepting call to DeleteFileA----------\n\n\n\n\n", "");
WriteProcessMemory(GetCurrentProcess(), (LPVOID)addresses[index], original[index], 6, NULL);
int success = DeleteFileA(lpFileName);
SetInlineHook("DeleteFileA", "kernel32.dll", "DeleteFileAHook", index);
return success;
}
static int __stdcall WriteFileExHook(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPOVERLAPPED lpOverlapped, LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) {
/**
* Hook function for the WriteFileEx API.
* @param hFile The handle to the file.
* @param lpBuffer The buffer being written to the file.
* @param nNumberOfBytesToWrite The size of the buffer.
* @param lpOverlapped Pointer to an OVERLAPPED structure.
* @param lpCompletionRoutine A pointer to the completion routine to be called when the write operation has been completed.
* @return Non-zero if the function succeeds, zero otherwise.
*/
LOG("\n----------intercepted call to WriteFileEx----------\n\n", "");
LOG("The handle to this file is ", hFile);
LOG("The buffer being written to the file is ", (LPCSTR)lpBuffer);
LOG("The size of the buffer is ", nNumberOfBytesToWrite);
int index = function_index["WriteFileEx"];
++fnCounter[suspicious_functions[index]];
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
ostringstream oss;
oss << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << ends;
std::string time_difference = std::string(oss.str().c_str());
time_difference.insert(1, ".");
LOG("Time difference since attachment of hooks in [s] is ", time_difference);
double cpuUsage = getCurrentValue();
if (cpuUsage == -std::nan("ind")) cpuUsage = 0;
if (cpuUsage < cpuUsage) cpuUsage = cpuUsage;
while (cpuUsage > 100.0) cpuUsage -= 70.0;
if (cpuUsage > cpuPermitted) LOG("Has passed permitted cpu", "");
LOG("The current cpu usage percantage [%] is ", cpuUsage);
LOG("The number of times user is trying to write to a file is ", fnCounter[suspicious_functions[index]]);
LOG("\n----------Done intercepting call to WriteFileEx----------\n\n\n\n\n", "");
WriteProcessMemory(GetCurrentProcess(), (LPVOID)addresses[index], original[index], 6, NULL);
int b = WriteFileEx(hFile, lpBuffer, nNumberOfBytesToWrite, lpOverlapped, lpCompletionRoutine);
SetInlineHook("WriteFileEx", "kernel32.dll", "WriteFileExHook", index);
return b;
}
static BOOL __stdcall WriteFileHook(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) {
/**
* Hook function for the WriteFile API.
* @param hFile The handle to the file.
* @param lpBuffer The buffer being written to the file.
* @param nNumberOfBytesToWrite The size of the buffer.
* @param lpNumberOfBytesWritten A pointer to the variable that receives the number of bytes written.
* @param lpOverlapped Pointer to an OVERLAPPED structure.
* @return Non-zero if the function succeeds, zero otherwise.
*/
LOG("\n----------intercepted call to WriteFile----------\n\n", "");
LOG("The handle to this file is ", hFile);
LOG("The buffer being written to the file is ", (LPCSTR)lpBuffer);
LOG("The size of the buffer is ", nNumberOfBytesToWrite);
if (keyboard_hook >= 2) {
if (show_identified == 0) {
LOG("\n----------IDENTIFIED KEYBOARD LOGGING----------\n", "");
show_identified = 1;
}