-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_protection.cpp
More file actions
77 lines (63 loc) · 1.71 KB
/
Copy pathmemory_protection.cpp
File metadata and controls
77 lines (63 loc) · 1.71 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
#include "shieldcore/memory_protection.hpp"
#include <atomic>
#include <thread>
#include <chrono>
#include <cstdio>
#if defined(_WIN32)
#include <windows.h>
#else
#include <unistd.h>
#endif
namespace shieldcore {
namespace {
std::atomic<bool> memoryCheckRunning{false};
std::thread* memoryCheckThread = nullptr;
}
bool verifyMemoryRegion(const void* address, std::size_t size, const char* /*regionName*/, std::string& error) {
if (!address || size == 0) {
error = "invalid memory region";
return false;
}
#if defined(_WIN32)
MEMORY_BASIC_INFORMATION mbi;
if (VirtualQuery(address, &mbi, sizeof(mbi)) == 0) {
error = regionName;
error += ": page protection check failed";
return false;
}
if ((mbi.Protect & PAGE_EXECUTE_READWRITE) != 0) {
error = regionName;
error += ": suspicious page protection detected";
return false;
}
#else
char maps_path[64] = {};
snprintf(maps_path, sizeof(maps_path), "/proc/%d/maps", getpid());
FILE* maps = fopen(maps_path, "r");
if (!maps) {
return true;
}
fclose(maps);
#endif
return true;
}
bool enablePeriodicMemoryChecks(int intervalSeconds) {
if (memoryCheckRunning.exchange(true)) {
return false;
}
memoryCheckThread = new std::thread([intervalSeconds]() {
while (memoryCheckRunning.load()) {
std::this_thread::sleep_for(std::chrono::seconds(intervalSeconds));
}
});
return true;
}
void stopMemoryChecks() {
memoryCheckRunning.store(false);
if (memoryCheckThread && memoryCheckThread->joinable()) {
memoryCheckThread->join();
delete memoryCheckThread;
memoryCheckThread = nullptr;
}
}
} // namespace shieldcore