-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFUNCTIONS.cpp
More file actions
882 lines (736 loc) · 25.8 KB
/
Copy pathFUNCTIONS.cpp
File metadata and controls
882 lines (736 loc) · 25.8 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
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
#pragma warning(disable : 4996)
#include "header.h"
#include <windows.h>
#include <iostream>
#include <iomanip>
#include <string>
#include <regex>
#include <fstream>
#include <sstream>
#include <filesystem>
#include <vector>
#include <openssl/sha.h>
#include <openssl/md5.h>
#include <cstdlib>
#include <map>
#include <chrono>
#include <ctime>
#include <algorithm>
#include <thread>
#include <mutex>
#include <cmath>
using namespace std;
namespace fs = std::filesystem;
// ===================== GLOBAL STATE =====================
std::mutex g_monitorMutex;
bool g_monitoringActive = false;
map<string, uintmax_t> fileSizes;
map<string, string> fileHashes;
string trackedFilePath;
// ===================== UTILITY FUNCTIONS =====================
fs::path get_app_directory() {
wchar_t szPath[MAX_PATH];
GetModuleFileNameW(NULL, szPath, MAX_PATH);
return fs::path(szPath).parent_path();
}
string getCurrentTimestamp() {
auto now = chrono::system_clock::now();
time_t now_time = chrono::system_clock::to_time_t(now);
tm timeinfo;
localtime_s(&timeinfo, &now_time);
stringstream ss;
ss << put_time(&timeinfo, "%Y-%m-%d %H:%M:%S");
return ss.str();
}
string formatFileSize(uintmax_t size) {
const char* units[] = { "B", "KB", "MB", "GB", "TB" };
int unitIndex = 0;
double displaySize = static_cast<double>(size);
while (displaySize >= 1024 && unitIndex < 4) {
displaySize /= 1024;
unitIndex++;
}
stringstream ss;
ss << fixed << setprecision(2) << displaySize << " " << units[unitIndex];
return ss.str();
}
bool createDirectory(const string& path) {
try {
if (!fs::exists(path)) {
return fs::create_directories(path);
}
return true;
}
catch (const exception& e) {
cerr << "Error creating directory: " << e.what() << endl;
return false;
}
}
bool fileExists(const string& path) {
return fs::exists(path);
}
string getFileExtension(const string& filepath) {
fs::path p(filepath);
return p.extension().string();
}
string sanitizeFilename(const string& filename) {
string sanitized = filename;
const string invalid_chars = "<>:\"/\\|?*";
for (char& c : sanitized) {
if (invalid_chars.find(c) != string::npos) {
c = '_';
}
}
return sanitized;
}
// ===================== BASE64 FUNCTIONS =====================
string readFile(const string& filename) {
ifstream file(filename, ios::binary);
if (!file.is_open()) {
throw runtime_error("Cannot open file: " + filename);
}
stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
string readFileSafe(const string& filename, size_t maxSize) {
try {
if (!fs::exists(filename)) {
throw runtime_error("File does not exist: " + filename);
}
uintmax_t filesize = fs::file_size(filename);
if (filesize > maxSize) {
throw runtime_error("File too large (max: " + to_string(maxSize) + " bytes)");
}
return readFile(filename);
}
catch (const exception& e) {
cerr << "Error reading file: " << e.what() << endl;
return "";
}
}
bool checkMZ(const string& str) {
return ((str.length() >= 2) && (str[0] == 'M') && (str[1] == 'Z'));
}
bool checkPDF(const string& str) {
return ((str.length() >= 4) && (str.substr(0, 4) == "%PDF"));
}
bool checkELF(const string& str) {
return ((str.length() >= 4) && (str[0] == 0x7F) &&
(str[1] == 'E') && (str[2] == 'L') && (str[3] == 'F'));
}
bool isValidBase64(const string& str) {
if (str.length() < 20 || str.length() % 4 != 0) {
return false;
}
for (size_t i = 0; i < str.length(); i++) {
char c = str[i];
if (base64chars.find(c) == string::npos && c != '=') {
return false;
}
if (c == '=' && i < str.length() - 2) {
return false;
}
}
return true;
}
string decodeBase64(const string& encoded) {
string decoded;
vector<int> T(256, -1);
for (size_t i = 0; i < 64; i++) {
T[base64chars[i]] = i;
}
int val = 0, valb = -8;
for (unsigned char c : encoded) {
if (T[c] == -1) {
break;
}
val = (val << 6) + T[c];
valb += 6;
if (valb >= 0) {
decoded.push_back(char((val >> valb) & 0xFF));
valb -= 8;
}
}
return decoded;
}
vector<Base64String> extractBase64(const string& content) {
vector<Base64String> results;
regex pattern(R"([A-Za-z0-9+/]{20,}={0,2})");
auto begin = sregex_iterator(content.begin(), content.end(), pattern);
auto end = sregex_iterator();
for (auto it = begin; it != end; it++) {
string encoded = it->str();
if (isValidBase64(encoded)) {
Base64String bs;
bs.encoded = encoded;
bs.decoded = decodeBase64(encoded);
bs.isExecutable = checkMZ(bs.decoded);
bs.isPDF = checkPDF(bs.decoded);
bs.position = it->position();
results.push_back(bs);
}
}
return results;
}
void printBase64Results(const vector<Base64String>& results) {
cout << "\n=== Base64 Analysis Results ===" << endl;
cout << "Found " << results.size() << " Base64 strings\n" << endl;
if (results.size() == 0) {
cout << "No suspicious Base64 strings detected.\n" << endl;
return;
}
for (size_t i = 0; i < results.size(); i++) {
cout << "[" << (i + 1) << "]" << endl;
cout << "Position: " << results[i].position << endl;
cout << "Length: " << results[i].encoded.length() << " chars" << endl;
cout << "Encoded (preview): " << results[i].encoded.substr(0, min(size_t(50), results[i].encoded.length())) << "..." << endl;
// Show decoded preview (safe characters only)
string decodedPreview;
for (char c : results[i].decoded.substr(0, min(size_t(100), results[i].decoded.length()))) {
if (c >= 32 && c <= 126) {
decodedPreview += c;
}
else {
decodedPreview += '.';
}
}
cout << "Decoded (preview): " << decodedPreview << "..." << endl;
if (results[i].isExecutable) {
cout << "?? ALERT: MZ header detected (Windows Executable)" << endl;
}
if (results[i].isPDF) {
cout << "?? PDF file detected" << endl;
}
cout << endl;
}
}
string analyzeBase64Content(const string& decoded) {
if (checkMZ(decoded)) return "Windows Executable (PE)";
if (checkPDF(decoded)) return "PDF Document";
if (checkELF(decoded)) return "ELF Executable (Linux)";
if (decoded.find("<?xml") != string::npos) return "XML Data";
if (decoded.find("{") != string::npos && decoded.find("}") != string::npos) return "JSON Data";
return "Unknown/Binary Data";
}
// ===================== HASH FUNCTIONS =====================
string generate_fuzzy_hash(const fs::path& filepath) {
try {
ifstream file(filepath, ios::binary);
if (!file.is_open()) {
return "Fuzzy_Error";
}
const int chunk_size = 64;
vector<char> buffer(4096);
vector<int> chunks;
int rolling_hash = 0;
while (file.read(buffer.data(), buffer.size()) || file.gcount() > 0) {
for (int i = 0; i < file.gcount(); i++) {
rolling_hash = ((rolling_hash * 31) + (unsigned char)buffer[i]) % 1000000;
if (rolling_hash % chunk_size == 0) {
chunks.push_back(rolling_hash);
}
}
}
stringstream ss;
ss << chunks.size() << ":";
for (size_t i = 0; i < min(chunks.size(), size_t(10)); i++) {
ss << chunks[i];
if (i < min(chunks.size(), size_t(10)) - 1) ss << ",";
}
return ss.str();
}
catch (const exception& e) {
cerr << "Error generating fuzzy hash: " << e.what() << endl;
return "Fuzzy_Error";
}
}
int calculate_similarity(const string& hash1, const string& hash2) {
if (hash1 == "Fuzzy_Error" || hash2 == "Fuzzy_Error" || hash1.empty() || hash2.empty())
return 0;
size_t colon1 = hash1.find(':');
size_t colon2 = hash2.find(':');
if (colon1 == string::npos || colon2 == string::npos)
return 0;
try {
int count1 = stoi(hash1.substr(0, colon1));
int count2 = stoi(hash2.substr(0, colon2));
int diff = abs(count1 - count2);
int max_count = max(count1, count2);
if (max_count == 0) return 0;
int similarity = (int)(100 * (1 - (double)diff / max_count));
return max(0, min(100, similarity));
}
catch (const exception& e) {
cerr << "Error calculating similarity: " << e.what() << endl;
return 0;
}
}
FuzzyHashResult check_fuzzy_hash(const string& file_fuzzy_hash, const fs::path& known_fuzzy_path) {
FuzzyHashResult result;
result.fuzzy_hash = file_fuzzy_hash;
result.is_suspicious = false;
result.matched_pattern = "None";
result.similarity_score = 0;
try {
if (!fs::exists(known_fuzzy_path)) {
cout << "?? Known fuzzy hashes file not found: " << known_fuzzy_path << endl;
return result;
}
ifstream known_file(known_fuzzy_path);
if (!known_file.is_open()) {
cout << "?? Cannot open known hashes file." << endl;
return result;
}
string line;
int max_similarity = 0;
string best_match = "";
while (getline(known_file, line)) {
// Remove trailing whitespace
while (!line.empty() && (line.back() == '\r' || line.back() == ' ' || line.back() == '\t')) {
line.pop_back();
}
if (line.empty()) continue;
size_t separator = line.find(':');
if (separator != string::npos && separator > 0) {
string pattern_name = line.substr(0, separator);
string known_hash = line.substr(separator + 1);
int similarity = calculate_similarity(file_fuzzy_hash, known_hash);
if (similarity > max_similarity) {
max_similarity = similarity;
best_match = pattern_name;
}
}
}
result.similarity_score = max_similarity;
result.matched_pattern = best_match;
if (max_similarity >= 75) {
result.is_suspicious = true;
}
}
catch (const exception& e) {
cerr << "Error checking fuzzy hash: " << e.what() << endl;
}
return result;
}
string calculate_sha256(const fs::path& filepath) {
try {
ifstream file(filepath, ios::binary);
if (!file.is_open()) {
return "Hash_Error";
}
SHA256_CTX sha256;
SHA256_Init(&sha256);
const int buffer_size = 8192;
vector<char> buffer(buffer_size);
while (file.read(buffer.data(), buffer_size) || file.gcount() > 0) {
SHA256_Update(&sha256, buffer.data(), file.gcount());
}
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_Final(hash, &sha256);
stringstream ss;
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();
}
catch (const exception& e) {
cerr << "Error calculating SHA256: " << e.what() << endl;
return "Hash_Error";
}
}
string calculate_md5(const fs::path& filepath) {
try {
ifstream file(filepath, ios::binary);
if (!file.is_open()) {
return "Hash_Error";
}
MD5_CTX md5;
MD5_Init(&md5);
const int buffer_size = 8192;
vector<char> buffer(buffer_size);
while (file.read(buffer.data(), buffer_size) || file.gcount() > 0) {
MD5_Update(&md5, buffer.data(), file.gcount());
}
unsigned char hash[MD5_DIGEST_LENGTH];
MD5_Final(hash, &md5);
stringstream ss;
for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {
ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();
}
catch (const exception& e) {
cerr << "Error calculating MD5: " << e.what() << endl;
return "Hash_Error";
}
}
bool compare_hash(const string FileHash, const fs::path& known_hashes_path) {
try {
if (!fs::exists(known_hashes_path)) {
cout << "?? Known hashes file not found: " << known_hashes_path << endl;
return false;
}
ifstream known_hashes_file(known_hashes_path);
if (!known_hashes_file.is_open()) {
cerr << "Error: Could not open known hashes file" << endl;
return false;
}
string line;
while (getline(known_hashes_file, line)) {
// Remove trailing whitespace
while (!line.empty() && (line.back() == '\r' || line.back() == ' ' || line.back() == '\t')) {
line.pop_back();
}
if (line == FileHash) {
cout << "?? MALICIOUS FILE DETECTED (Hash match)" << endl;
return true;
}
}
cout << "? Hash not found in malicious database" << endl;
return false;
}
catch (const exception& e) {
cerr << "Error comparing hash: " << e.what() << endl;
return false;
}
}
// ===================== METADATA FUNCTIONS =====================
string fileTimeToString(fs::file_time_type ftime) {
try {
auto sctp = chrono::time_point_cast<chrono::system_clock::duration>(
ftime - fs::file_time_type::clock::now() + chrono::system_clock::now()
);
time_t time_t_val = chrono::system_clock::to_time_t(sctp);
tm time;
localtime_s(&time, &time_t_val);
stringstream ss;
ss << put_time(&time, "%Y-%m-%d %H:%M:%S");
return ss.str();
}
catch (const exception& e) {
return "Unknown";
}
}
string getCreationTime(const fs::path& filepath) {
return getCurrentTimestamp(); // Simplified for cross-platform compatibility
}
void print(fileMetaData data) {
cout << "\n=== File Metadata ===" << endl;
cout << "Name: " << data.name << endl;
cout << "Path: " << data.path << endl;
cout << "Size: " << formatFileSize(data.size) << endl;
cout << "Extension: " << data.extension << endl;
cout << "Type: ";
if (data.Regular) {
cout << "Regular File";
}
else if (data.directory) {
cout << "Directory";
}
else {
cout << "Other";
}
cout << endl;
cout << "Created: " << data.creation_time << endl;
cout << "Last Modified: " << data.last_modified << endl;
cout << "Readable: " << (data.read ? "Yes" : "No") << endl;
cout << "Writeable: " << (data.write ? "Yes" : "No") << endl;
cout << "========================\n" << endl;
}
fileMetaData getMetaData(const fs::path& filepath) {
fileMetaData data;
try {
if (!fs::exists(filepath)) {
throw runtime_error("File does not exist");
}
data.name = filepath.filename().string();
data.path = fs::absolute(filepath).string();
data.size = fs::is_regular_file(filepath) ? fs::file_size(filepath) : 0;
data.last_modified = fileTimeToString(fs::last_write_time(filepath));
data.Regular = fs::is_regular_file(filepath);
data.directory = fs::is_directory(filepath);
data.extension = filepath.extension().string();
data.creation_time = getCreationTime(filepath);
fs::perms permission = fs::status(filepath).permissions();
data.read = (permission & fs::perms::owner_read) != fs::perms::none;
data.write = (permission & fs::perms::owner_write) != fs::perms::none;
}
catch (const exception& e) {
cerr << "Error getting metadata: " << e.what() << endl;
}
return data;
}
string validateFileType(const string& filepath) {
try {
ifstream file(filepath, ios::binary);
if (!file.is_open()) {
return "Cannot read file";
}
unsigned char magic[8] = { 0 };
file.read((char*)magic, 8);
file.close();
// Check magic numbers
if (magic[0] == 0x89 && magic[1] == 0x50 && magic[2] == 0x4E && magic[3] == 0x47) {
return "PNG Image";
}
if (magic[0] == 0xFF && magic[1] == 0xD8 && magic[2] == 0xFF) {
return "JPEG Image";
}
if (magic[0] == 0x25 && magic[1] == 0x50 && magic[2] == 0x44 && magic[3] == 0x46) {
return "PDF Document";
}
if (magic[0] == 0x50 && magic[1] == 0x4B) {
return "ZIP Archive / Office Document";
}
if (magic[0] == 0x4D && magic[1] == 0x5A) {
return "Windows Executable (PE)";
}
if (magic[0] == 0x7F && magic[1] == 0x45 && magic[2] == 0x4C && magic[3] == 0x46) {
return "ELF Executable (Linux)";
}
if (magic[0] == 0x1F && magic[1] == 0x8B) {
return "GZIP Compressed";
}
if (magic[0] == 0x42 && magic[1] == 0x4D) {
return "BMP Image";
}
// Check if text
bool isText = true;
for (int i = 0; i < 8; i++) {
if (magic[i] != 0 && (magic[i] < 32 || magic[i] > 126) &&
magic[i] != 10 && magic[i] != 13 && magic[i] != 9) {
isText = false;
break;
}
}
if (isText) {
return "Text File";
}
return "Unknown/Binary";
}
catch (const exception& e) {
return "Error validating file type";
}
}
// ===================== FILE MONITORING FUNCTIONS =====================
void takeSnapshot(const fs::path& specificFile) {
lock_guard<mutex> lock(g_monitorMutex);
cout << "\n[SNAPSHOT] Recording file state..." << endl;
try {
if (fs::is_regular_file(specificFile)) {
string filepath = specificFile.string();
trackedFilePath = filepath;
fileSizes[filepath] = fs::file_size(specificFile);
fileHashes[filepath] = calculate_sha256(specificFile);
cout << "? File: " << specificFile.filename() << endl;
cout << "? Size: " << formatFileSize(fileSizes[filepath]) << endl;
cout << "? Hash: " << fileHashes[filepath].substr(0, 16) << "..." << endl;
cout << "? Snapshot complete" << endl;
}
}
catch (const exception& e) {
cerr << "Error taking snapshot: " << e.what() << endl;
}
}
void detectChanges() {
lock_guard<mutex> lock(g_monitorMutex);
cout << "\n[DETECTION] Checking for changes..." << endl;
try {
if (trackedFilePath.empty()) {
cout << "?? No file is being tracked" << endl;
return;
}
fs::path trackedPath(trackedFilePath);
if (!fs::exists(trackedPath)) {
cout << "?? [DELETED] File no longer exists: " << trackedPath.filename() << endl;
return;
}
bool changeFound = false;
uintmax_t currentSize = fs::file_size(trackedPath);
if (fileSizes[trackedFilePath] != currentSize) {
cout << "?? [SIZE CHANGED] " << trackedPath.filename() << endl;
cout << " Old size: " << formatFileSize(fileSizes[trackedFilePath]) << endl;
cout << " New size: " << formatFileSize(currentSize) << endl;
changeFound = true;
}
string currentHash = calculate_sha256(trackedPath);
if (fileHashes[trackedFilePath] != currentHash) {
cout << "?? [CONTENT MODIFIED] Hash changed" << endl;
cout << " Old hash: " << fileHashes[trackedFilePath].substr(0, 16) << "..." << endl;
cout << " New hash: " << currentHash.substr(0, 16) << "..." << endl;
changeFound = true;
}
if (!changeFound) {
cout << "? No changes detected" << endl;
}
}
catch (const exception& e) {
cerr << "Error detecting changes: " << e.what() << endl;
}
}
void monitorFileRealtime(const fs::path& filepath, int durationSeconds) {
g_monitoringActive = true;
cout << "\n[MONITOR] Starting real-time monitoring for " << durationSeconds << " seconds..." << endl;
takeSnapshot(filepath);
for (int i = 0; i < durationSeconds && g_monitoringActive; i++) {
this_thread::sleep_for(chrono::seconds(1));
detectChanges();
}
g_monitoringActive = false;
cout << "[MONITOR] Monitoring stopped" << endl;
}
void stopMonitoring() {
g_monitoringActive = false;
}
// ===================== ADVANCED ANALYSIS FUNCTIONS =====================
vector<string> extractStrings(const fs::path& filepath, size_t minLength) {
vector<string> strings;
try {
ifstream file(filepath, ios::binary);
if (!file.is_open()) return strings;
string current;
char c;
while (file.get(c)) {
if (c >= 32 && c <= 126) {
current += c;
}
else {
if (current.length() >= minLength) {
strings.push_back(current);
}
current.clear();
}
}
if (current.length() >= minLength) {
strings.push_back(current);
}
}
catch (const exception& e) {
cerr << "Error extracting strings: " << e.what() << endl;
}
return strings;
}
vector<string> findSuspiciousPatterns(const string& content) {
vector<string> suspiciousPatterns;
vector<string> patterns = {
"cmd.exe", "powershell", "exec", "eval", "system(",
"Registry", "CreateProcess", "VirtualAlloc", "WriteProcessMemory",
"http://", "https://", "ftp://", ".dll", ".exe",
"password", "credentials", "token", "api_key"
};
for (const auto& pattern : patterns) {
if (content.find(pattern) != string::npos) {
suspiciousPatterns.push_back(pattern);
}
}
return suspiciousPatterns;
}
bool containsShellcode(const string& content) {
// Simple heuristic: look for common shellcode patterns
vector<unsigned char> nopSled = { 0x90, 0x90, 0x90, 0x90 };
if (content.length() < 4) return false;
// Check for NOP sleds
int nopCount = 0;
for (size_t i = 0; i < content.length(); i++) {
if ((unsigned char)content[i] == 0x90) {
nopCount++;
if (nopCount > 10) return true;
}
else {
nopCount = 0;
}
}
return false;
}
int calculateEntropy(const string& data) {
if (data.empty()) return 0;
map<unsigned char, int> freq;
for (unsigned char c : data) {
freq[c]++;
}
double entropy = 0.0;
double dataSize = static_cast<double>(data.length());
for (const auto& pair : freq) {
double probability = pair.second / dataSize;
entropy -= probability * log2(probability);
}
return static_cast<int>(entropy * 100 / 8); // Normalize to 0-100
}
// ===================== QUARANTINE SYSTEM =====================
bool quarantineFile(const string& filepath, const string& reason) {
try {
fs::path app_dir = get_app_directory();
fs::path quarantine_dir = app_dir / "Quarantine";
if (!createDirectory(quarantine_dir.string())) {
return false;
}
fs::path sourcePath(filepath);
string timestamp = getCurrentTimestamp();
for (char& c : timestamp) {
if (c == ':' || c == ' ') c = '_';
}
string quarantineName = sourcePath.filename().string() + "_" + timestamp;
fs::path quarantinePath = quarantine_dir / quarantineName;
fs::copy_file(sourcePath, quarantinePath, fs::copy_options::overwrite_existing);
// Save quarantine info
fs::path logPath = quarantine_dir / "quarantine_log.txt";
ofstream infoFile(logPath, ios::app);
if (infoFile.is_open()) {
infoFile << quarantineName << "|"
<< filepath << "|"
<< reason << "|"
<< getCurrentTimestamp() << "|"
<< calculate_sha256(sourcePath) << endl;
infoFile.close();
}
cout << "? File quarantined successfully" << endl;
return true;
}
catch (const exception& e) {
cerr << "Error quarantining file: " << e.what() << endl;
return false;
}
}
vector<QuarantineEntry> listQuarantinedFiles() {
vector<QuarantineEntry> entries;
try {
fs::path logPath = get_app_directory() / "Quarantine" / "quarantine_log.txt";
ifstream logFile(logPath);
if (!logFile.is_open()) return entries;
string line;
while (getline(logFile, line)) {
QuarantineEntry entry;
size_t pos = 0;
vector<string> parts;
while ((pos = line.find('|')) != string::npos) {
parts.push_back(line.substr(0, pos));
line.erase(0, pos + 1);
}
parts.push_back(line);
if (parts.size() >= 5) {
entry.quarantine_path = parts[0];
entry.original_path = parts[1];
entry.reason = parts[2];
entry.timestamp = parts[3];
entry.hash = parts[4];
entries.push_back(entry);
}
}
}
catch (const exception& e) {
cerr << "Error listing quarantined files: " << e.what() << endl;
}
return entries;
}
bool restoreFromQuarantine(const string& quarantine_id) {
// Implementation for restoring files from quarantine
cout << "Restore functionality not yet implemented" << endl;
return false;
}
bool deleteFromQuarantine(const string& quarantine_id) {
// Implementation for deleting files from quarantine
cout << "Delete functionality not yet implemented" << endl;
return false;
}
// The End