-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUSBProtection.cpp
More file actions
1658 lines (1353 loc) · 53.4 KB
/
Copy pathUSBProtection.cpp
File metadata and controls
1658 lines (1353 loc) · 53.4 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
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
// USBProtection.cpp : Defines the entry point for the application.
//
#include "USBProtection.h"
using namespace std;
//Structures
struct Condition {
uint8_t type = 0;
/*
0 - Invalid
1 - Owner
2 - Time
3 - Known
4 - VID
5 - PID
6 - System Mode
7 - Custom Name
*/
string RHS = "";
char sign = '=';
};
struct ASTNode {
Condition* condition = NULL; //If NULL, assume naturally true - this is for ALLOW / DENY stuff
ASTNode* ifBlock = NULL; //If the end of the chain, NULL
ASTNode* elseBlock = NULL; //NULL if not an IF thing
uint8_t allowCode = 0;
/*
0 - Invalid
1 - ALLOW
2 - REQUEST
3 - DENY
*/
};
struct USBStatus {
//This is not strictly required but keeps things neater IMO
string owner = "";
bool known = false;
string VID = "";
string PID = "";
uint8_t systemMode;
string customName = "";
};
struct USBFile {
string name = "";
uint64_t fileSize = 0;
string fileHash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; //This is the hash for nothing under SHA256
};
//System settings
string policyPath;
string knownCombinationsFilePath;
string knownKeypairsPath;
uint8_t systemMode;
ASTNode root;
bool shouldLearnNewDevices = false;
//Threading stuff - AI
HANDLE g_hUSBDir = INVALID_HANDLE_VALUE;
atomic<bool> g_keepWatching(false);
HWND g_hwnd = NULL;
HDEVNOTIFY g_hHandleNotify = NULL;
//Helpers
string GenerateSubstr(string str, char start, char end) {
string out = "";
for (int i = str.find(start) + 1; i < str.length(); i++) {
if (str[i] == end) break;
out += str[i];
}
return out;
}
string PadAndTrimStr(string str, int finalLen, char padChr = '|') {
//Left aligned
string strNew = str.substr(0, finalLen);
while (strNew.length() < finalLen) strNew += padChr;
return strNew;
}
void DBCCParser(uint64_t* bufferInt, string* bufferStr, string dbcc) {
string VID = dbcc.substr(12, 4);
string PID = dbcc.substr(21, 4);
string serial = dbcc.substr(26, 16);
bufferStr[0] = VID;
bufferStr[1] = PID;
bufferStr[2] = serial;
//cout << "VID : " << VID << "\nPID : " << PID << "\nSerial : " << serial << endl;
bufferInt[0] = stoull(VID, 0, 16);
bufferInt[1] = stoull(PID, 0, 16);
bufferInt[2] = stoull(serial, 0, 16);
}
void GenerateRSAKeys(RSA* rsaKeypair) {
//https://mojoauth.com/keypair-generation/generate-keypair-using-rsa-with-cpp#2-generating-the-rsa-key-pair
//This nonsense is required by OPENSSL
auto bn = BN_new();
BN_set_word(bn, 65537); //Traditional e for RSA
RSA_generate_key_ex(rsaKeypair, 4096, bn, NULL); //Max security w/ RSA
string folderPath;
cout << "PEM folder path : ";
cin >> folderPath;
cout << endl;
string privatePath = folderPath + "/private.pem";
string publicPath = folderPath + "/public.pem";
FILE* privateKeyFile = fopen(privatePath.c_str(), "w");
PEM_write_RSAPrivateKey(privateKeyFile, rsaKeypair, NULL, NULL, 0, NULL, NULL);
fclose(privateKeyFile);
FILE* publicKeyFile = fopen(publicPath.c_str(), "w");
PEM_write_RSAPublicKey(publicKeyFile, rsaKeypair);
fclose(publicKeyFile);
}
RSA* LoadPublicKey(const string& folder, string extension = "/public.pem")
{
ifstream file(folder + extension);
string pem{
istreambuf_iterator<char>(file),
istreambuf_iterator<char>()
};
file.close();
BIO* bio = BIO_new_mem_buf(pem.data(), pem.size());
RSA* rsa = PEM_read_bio_RSAPublicKey(bio, nullptr, nullptr, nullptr);
BIO_free(bio);
return rsa;
}
RSA* LoadPrivateKey(const string& folder)
{
ifstream file(folder + "/private.pem");
string pem{
istreambuf_iterator<char>(file),
istreambuf_iterator<char>()
};
file.close();
BIO* bio = BIO_new_mem_buf(pem.data(), pem.size());
RSA* rsa = PEM_read_bio_RSAPrivateKey(bio, nullptr, nullptr, nullptr);
BIO_free(bio);
return rsa;
}
bool RSASign(RSA* rsa,
const unsigned char* Msg,
size_t MsgLen,
unsigned char** EncMsg,
size_t* MsgLenEnc) {
//https://gist.github.com/irbull/08339ddcd5686f509e9826964b17bb59
EVP_MD_CTX* m_RSASignCtx = EVP_MD_CTX_create();
EVP_PKEY* priKey = EVP_PKEY_new();
//EVP_PKEY_assign_RSA(priKey, rsa);
EVP_PKEY_set1_RSA(priKey, rsa);
if (EVP_DigestSignInit(m_RSASignCtx, NULL, EVP_sha256(), NULL, priKey) <= 0) {
return false;
}
if (EVP_DigestSignUpdate(m_RSASignCtx, Msg, MsgLen) <= 0) {
return false;
}
if (EVP_DigestSignFinal(m_RSASignCtx, NULL, MsgLenEnc) <= 0) {
return false;
}
*EncMsg = (unsigned char*)malloc(*MsgLenEnc);
if (EVP_DigestSignFinal(m_RSASignCtx, *EncMsg, MsgLenEnc) <= 0) {
return false;
}
EVP_PKEY_free(priKey);
EVP_MD_CTX_free(m_RSASignCtx);
return true;
}
string sha256(const string& str)
{
//https://stackoverflow.com/questions/2262386/generate-sha256-with-openssl-and-c
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
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();
}
//AI
// Convert binary bytes to Hex string
string BytesToHex(const unsigned char* data, size_t len) {
stringstream ss;
for (size_t i = 0; i < len; ++i) {
ss << hex << setw(2) << setfill('0') << (int)data[i];
}
return ss.str();
}
//AI
// Convert Hex string back to binary bytes
vector<unsigned char> HexToBytes(const string& hexStr) {
vector<unsigned char> bytes;
for (size_t i = 0; i < hexStr.length(); i += 2) {
string byteString = hexStr.substr(i, 2);
unsigned char byte = static_cast<unsigned char>(strtol(byteString.c_str(), NULL, 16));
bytes.push_back(byte);
}
return bytes;
}
string SHA256FromFile(const string &filePath) {
ifstream file(filePath, ios::in | ios::binary | ios::ate);
if (!file.is_open()) {
cerr << "Error: Cannot open file: " << filePath << endl;
return "NULL";
}
// Get file size
long fileSize = file.tellg();
//cout << "File size: " << fileSize << " bytes" << endl;
// Allocate memory to hold the entire file
char* memBlock = new char[fileSize];
// Read the file into memory
file.seekg(0, ios::beg);
file.read(memBlock, fileSize);
file.close();
// Compute the SHA hash of the file content
string hash = sha256(string(memBlock, fileSize));
delete[] memBlock;
return hash;
}
void WriteEncryptedLogEntry(string entry, string driveLetter) {
string filePath = driveLetter + "usb.log";
time_t timestamp = time(NULL);
tm* ptm = gmtime(×tamp);
char buffer[32];
strftime(buffer, sizeof(buffer), "%S%M%H%d%m%Y", ptm);
entry = (string)buffer + " : " + entry;
RSA* ownerPublic = LoadPublicKey(driveLetter + "public.pem", "");
int rsaLen = RSA_size(ownerPublic);
unsigned char* encryptedBuffer = new unsigned char[rsaLen];
int encryptedLength = RSA_public_encrypt(
entry.length(),
(const unsigned char*)entry.c_str(),
encryptedBuffer,
ownerPublic,
RSA_PKCS1_OAEP_PADDING
);
ofstream f(filePath, ios_base::app | ios_base::out | ios_base::binary);
f.write((char*)encryptedBuffer, encryptedLength);
f.write("\n",1);
f.close();
RSA_free(ownerPublic);
delete[] encryptedBuffer;
}
vector<string> DecryptEntry(RSA* privKey, string filePath) {
vector<string> out = {};
if (privKey == nullptr) {
//cout << "pviv key nullptr" << endl;
return out;
}
int rsaLen = RSA_size(privKey);
unsigned char* encryptedChunk = new unsigned char[rsaLen];
unsigned char* decryptedBuffer = new unsigned char[rsaLen];
ifstream f(filePath, ios_base::in | ios_base::binary);
while (f.read((char*)encryptedChunk, rsaLen)) {
// 5. Decrypt the chunk
int decryptedLength = RSA_private_decrypt(
rsaLen,
encryptedChunk,
decryptedBuffer,
privKey,
RSA_PKCS1_OAEP_PADDING
);
if (decryptedLength == -1) {
//cout << "Length = -1" << endl;
return out;
}
string plaintext((char*)decryptedBuffer, decryptedLength);
out.push_back(plaintext);
char endLine;
f.read(&endLine, 1);
}
RSA_free(privKey);
f.close();
return out;
}
//functions
void FormASTTreeLayer(ASTNode* node, vector<string> scope) {
//cout << "============" << endl;
//cout << "Forming AST Layer" << endl;
//cout << "Scope size : " << scope.size() << endl;
//cout << "Scope : " << endl;
//for (string line : scope) cout << line << endl;
/*We can say a scope has either an IF / ELSE setup or not
If it does, we need to consider the IF/ELSE pair together
If it doesnt, its a simple ALLOW/REQUEST/DENY node*/
if (scope[0].substr(0,2) == "IF") {
//In this case we are dealing with an IF,ELSE clause
string conditionStr = GenerateSubstr(scope[0], '[', ']');
string conditionTypeStr = GenerateSubstr(conditionStr, '~', '~');
uint8_t conditionType = 0;
char conditionSign = '=';
if (conditionTypeStr == "OWNER") conditionType = 1;
else if (conditionTypeStr == "TIME") {
conditionType = 2;
if (conditionStr.find('>') != string::npos) conditionSign = '>';
else if (conditionStr.find('<') != string::npos) conditionSign = '<';
}
else if (conditionTypeStr == "KNOWN") conditionType = 3;
else if (conditionTypeStr == "VID") conditionType = 4;
else if (conditionTypeStr == "PID") conditionType = 5;
else if (conditionTypeStr == "SYSTEM_MODE") conditionType = 6;
else if (conditionTypeStr == "CUSTOM_NAME") conditionType = 7;
node->condition = new Condition{
conditionType,
GenerateSubstr(conditionStr, '#', '#'),
conditionSign
};
//Visualising the condition
//cout << "Condition : " << endl;
//cout << "Type : " << to_string(node->condition->type) << endl;
//cout << "RHS : " << node->condition->RHS << endl;
//cout << "Sign : " << node->condition->sign << endl;
//Counting out the IF scope using depths
uint64_t scopeDepth = 1;
vector<string> ifScope = {};
uint64_t ifBlockEnd = 1;
for (int i = 1; i < scope.size(); i++) {
if (scope[i].find('{') != string::npos) scopeDepth++;
else if (scope[i].find('}') != string::npos) scopeDepth--;
if (scopeDepth == 0) break;
ifScope.push_back(scope[i]);
//cout << "IF Scope Section : " << scope[i] << endl;
ifBlockEnd++;
}
node->ifBlock = new ASTNode();
FormASTTreeLayer(node->ifBlock, ifScope);
//cout << "IF Block end " << ifBlockEnd << endl;
//EL will not always exist - we first need to work out if it exists
if ((scope.size() > ifBlockEnd + 1) && (scope[ifBlockEnd + 1].substr(0, 2) == "EL")) {
//Counting out the EL scope using depths
scopeDepth = 1;
vector<string> elScope = {};
for (int i = ifBlockEnd + 2; i < scope.size(); i++) {
if (scope[i].find('{') != string::npos) scopeDepth++;
else if (scope[i].find('}') != string::npos) scopeDepth--;
if (scopeDepth == 0) break;
elScope.push_back(scope[i]);
//cout << "EL Scope Section : " << scope[i] << endl;
}
node->elseBlock = new ASTNode();
FormASTTreeLayer(node->elseBlock, elScope);
}
}
else {
//In this case we are dealing with an ALLOW/REQUETS/DENY sitauton
//cout << "ALLOW Scope : " << scope[0] << endl;
if (scope[0] == ":ALLOW:") node->allowCode = 1;
else if (scope[0] == ":REQUEST:") node->allowCode = 2;
else node->allowCode = 3;
}
//cout << "-------" << endl;
}
bool CheckCondition(Condition* condition, USBStatus* status) {
//cout << "Checking Condition of type " << to_string(condition->type) << endl;
if (condition->type == 1) {
//Owner
return (status->owner == condition->RHS);
}
else if (condition->type == 2) {
//Time
time_t currentTimestamp = time(NULL);
struct tm comparisonDatetime = *localtime(¤tTimestamp);;
comparisonDatetime.tm_hour = stoi((condition->RHS).substr(0,2));
comparisonDatetime.tm_min = stoi((condition->RHS).substr(3, 2));
comparisonDatetime.tm_sec = stoi((condition->RHS).substr(6, 2));
time_t comparisonTimestamp = mktime(&comparisonDatetime);
double difference = difftime(comparisonTimestamp, currentTimestamp);
if ((difference > 0 && condition->sign == '>')
|| (difference < 0 && condition->sign == '<')
|| (difference == 0 && condition->sign == '=')) return true;
else return false;
}
else if (condition->type == 3) {
//Known
return(status->known == (condition->RHS == "true"));
}
else if (condition->type == 4) {
//VID
return (status->VID == condition->RHS);
}
else if (condition->type == 5) {
//PID
return (status->PID == condition->RHS);
}
else if (condition->type == 6) {
//System Mode
return (to_string(status->systemMode) == condition->RHS);
}
else if (condition->type == 7) {
//Custom name
return (status->customName == condition->RHS);
}
return false; //Backup failure condition
}
uint8_t NodePolicyCheck(USBStatus* status, ASTNode* node) {
//cout << "---" << endl;
//cout << "Node Policy Check" << endl;
//cout << "Node overview :" << endl;
//cout << "Node : " << (node != nullptr) << endl;
if (node == nullptr) throw 1000;
//cout << "Condition : " << (node->condition != nullptr) << endl;
//cout << "IF block : " << (node->ifBlock != nullptr) << endl;
//cout << "EL block : " << (node->elseBlock != nullptr) << endl;
//cout << "Allow Code : " << to_string(node->allowCode) << endl;
uint8_t out = 0; //Safer to assume invalid unless proved otherwise
try {
if (node->condition != nullptr) {
if (CheckCondition(node->condition, status)) out = NodePolicyCheck(status, node->ifBlock);
else if (node->elseBlock != nullptr) out = NodePolicyCheck(status, node->elseBlock);
}
else out = node->allowCode;
}
catch (...) {
cout << "Node Policy Check failed" << endl;
}
return out;
}
uint8_t DoesUSBMatchPolicy(USBStatus* status, ASTNode* rootNode) {
/*
- Policy parameters
- Owner ex
- Time ex
- Known ex
- VID
- PID
- System Mode ex
- Outs
- Allow
- Block
- Request
- Default = blocked as this seems logical
*/
uint8_t out = 0;
//cout << "Step 1 complete" << endl;
out = NodePolicyCheck(status, rootNode);
if (out == 0) out = 3; //Safest to deny unless states otehrwise
//cout << "Policy Check results : " << to_string(out) << endl;
return out;
}
void EjectUSB(string formattedID) {
//Format goal - USB\VID_1234&PID_5678\SERIAL
//cout << "Formatted ID : " << formattedID << endl;
//Gemini, not me
DEVINST devInst;
CONFIGRET cr = CM_Locate_DevNodeA(&devInst, (DEVINSTID_A)formattedID.c_str(), CM_LOCATE_DEVNODE_NORMAL);
if (cr == CR_SUCCESS) {
PNP_VETO_TYPE vetoType = PNP_VetoTypeUnknown;
CHAR vetoName[MAX_PATH] = {0};
// 3. Request safe removal
cr = CM_Request_Device_EjectA(devInst, &vetoType, vetoName, MAX_PATH, 0);
if (cr == CR_SUCCESS) {
//cout << "[+] Device safely ejected due to policy violation." << endl;
}
else {
// A "veto" means Windows blocked the ejection (e.g., a file is currently open)
//cout << "[-] Failed to eject device. Windows Veto Type: " << vetoType << endl;
}
}
else cout << "Not found " << endl;
}
bool IsReadWrite(string formattedID) {
bool isReadWrite = false;
DEVINST devInst;
CONFIGRET cr = CM_Locate_DevNodeA(&devInst, (DEVINSTID_A)formattedID.c_str(), CM_LOCATE_DEVNODE_NORMAL);
if (cr == CR_SUCCESS) {
//AI
char serviceName[MAX_PATH] = { 0 };
ULONG len = sizeof(serviceName);
cr = CM_Get_DevNode_Registry_PropertyA(
devInst,
CM_DRP_SERVICE,
NULL,
serviceName,
&len,
0
);
if (cr == CR_SUCCESS) {
string service(serviceName);
for (char& c : service) c = toupper(c);
if (service == "USBSTOR" || service == "UASPSTOR") isReadWrite = true;
}
}
return isReadWrite;
}
//AI
bool RSAVerify(RSA* rsa, const unsigned char* Msg, size_t MsgLen, const unsigned char* Sig, size_t SigLen) {
EVP_MD_CTX* m_RSAVerifyCtx = EVP_MD_CTX_create();
EVP_PKEY* pubKey = EVP_PKEY_new();
EVP_PKEY_set1_RSA(pubKey, rsa);
bool result = false;
if (EVP_DigestVerifyInit(m_RSAVerifyCtx, NULL, EVP_sha256(), NULL, pubKey) > 0) {
if (EVP_DigestVerifyUpdate(m_RSAVerifyCtx, Msg, MsgLen) > 0) {
result = (EVP_DigestVerifyFinal(m_RSAVerifyCtx, Sig, SigLen) == 1);
}
}
EVP_PKEY_free(pubKey);
EVP_MD_CTX_free(m_RSAVerifyCtx);
return result;
}
void WatchUSB(string driveLetter) {
//cout << "Watching : " << driveLetter << endl;
//Windows stuff is AI
g_hUSBDir = CreateFileA(
driveLetter.c_str(),
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, // Let other programs still use it
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, // Required for getting a handle to a directory
NULL
);
if (g_hUSBDir == INVALID_HANDLE_VALUE) {
//cout << "Failed to open directory." << endl;
return;
}
DEV_BROADCAST_HANDLE filter = {};
filter.dbch_size = sizeof(filter);
filter.dbch_devicetype = DBT_DEVTYP_HANDLE;
filter.dbch_handle = g_hUSBDir;
g_hHandleNotify = RegisterDeviceNotification(g_hwnd, &filter, DEVICE_NOTIFY_WINDOW_HANDLE);
g_keepWatching = true;
//First I want to note the existing situation
unordered_map<string, USBFile> usbFiles;
//BFS
vector<string> pathQueue = {driveLetter};
while (pathQueue.size() > 0) {
string path = pathQueue[0];
pathQueue.erase(pathQueue.begin());
for (const auto& entry : filesystem::directory_iterator(path)) {
if (filesystem::is_directory(entry.path())) {
pathQueue.push_back((entry.path()).string());
//cout << "Directory : " << entry.path() << endl;
}
else if (filesystem::is_regular_file(entry.path())) {
//cout << "File : " << entry.path() << endl;
string sha = SHA256FromFile((entry.path()).string());
USBFile usb{
(entry.path()).string(),
filesystem::file_size(entry.path()),
sha
};
usbFiles[usb.name] = usb;
}
else cout << "Other? : " << entry.path() << endl;
}
}
char buffer[8192];
DWORD bytesReturned;
OVERLAPPED overlapped = {};
overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
//cout << "Watching for changes..." << endl;
while (g_keepWatching) {
bool queued = ReadDirectoryChangesW(
g_hUSBDir,
buffer,
sizeof(buffer),
TRUE, // Watch all subfolders too
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE,
NULL,
&overlapped,
NULL
);
if (!queued) break;
bool success = GetOverlappedResult(g_hUSBDir, &overlapped, &bytesReturned, TRUE);
if (success && bytesReturned > 0) {
//cout << "A file was created, modified, or deleted on the USB!" << endl;
FILE_NOTIFY_INFORMATION* notifyInfo = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(buffer);
string action4OldNameBuffer = "";
while (true) { //This loop means we get everythign out the buffer
DWORD characterCount = notifyInfo->FileNameLength / sizeof(WCHAR); //Used in windows so we use ig
wstring wstr(notifyInfo->FileName, characterCount);
string fileName(wstr.begin(), wstr.end());
if (fileName == "usb.log") {
//cout << "Log edit - breaking";
break; //Otherwise we'll end up in an infinite
}
fileName = driveLetter + fileName;
//cout << "File name : " << fileName << endl;
DWORD action = notifyInfo->Action;
USBFile entry = usbFiles[fileName];
string unencryptedBaseEntry;
//cout << "Action : " << to_string(action) << endl;
//NTS - https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-file_notify_information
if (action == 1) {
unencryptedBaseEntry = '?' + fileName + "? was created | Action Type 1";
entry.name = fileName;
string newSHA = SHA256FromFile(fileName);
entry.fileHash = newSHA;
usbFiles[fileName] = entry;
}
else if (action == 2) {
unencryptedBaseEntry = '?' + fileName + "? was deleted (hash = ?" + entry.fileHash + "?, size = ?" + to_string(entry.fileSize) + "?B) | Action Type 2";
usbFiles.erase(fileName);
}
else if (action == 3) {
uint64_t oldSize = entry.fileSize;
string oldHash = entry.fileHash;
uint64_t newSize = filesystem::file_size(fileName);
string newSHA = SHA256FromFile(fileName);
entry.fileHash = newSHA;
entry.fileSize = newSize;
usbFiles[fileName] = entry;
unencryptedBaseEntry = "?" + fileName + "? was modified (old hash = ?" + oldHash + "?, old size = ?" + to_string(oldSize) + "?B, new hash = ?" + newSHA + "?, new size = ?" + to_string(newSize) + "?B) | Action Type 3";
}
else if (action == 4) {
action4OldNameBuffer = fileName;
}
else if (action == 5) {
unencryptedBaseEntry = "?" + action4OldNameBuffer + "? was renamed to ?" + fileName + "? | Action Type 5";
usbFiles.erase(action4OldNameBuffer);
entry.name = fileName;
usbFiles[fileName] = entry;
}
else cout << "Unprocessed action : " << to_string(action) << endl;
if (unencryptedBaseEntry != "") {
//cout << "Entry : " << unencryptedBaseEntry << endl;
WriteEncryptedLogEntry(unencryptedBaseEntry, driveLetter);
}
//The notify can hold multiple events, so we have to make sure w eget each one
if (notifyInfo->NextEntryOffset == 0) {
//cout << "Event complete" << endl;
break;
}
else {
notifyInfo = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(
reinterpret_cast<char*>(notifyInfo) + notifyInfo->NextEntryOffset
);
}
}
}
else {
//cout << "USB removed" << endl;
break;
}
ResetEvent(overlapped.hEvent);
}
if (overlapped.hEvent) CloseHandle(overlapped.hEvent);
if (g_hUSBDir != INVALID_HANDLE_VALUE) {
CloseHandle(g_hUSBDir);
g_hUSBDir = INVALID_HANDLE_VALUE;
}
g_keepWatching = false;
}
void HandleUSB(DEV_BROADCAST_DEVICEINTERFACE* dev, DEV_BROADCAST_VOLUME* readWriteDev) {
//cout << "DBCC NAME : " << dev->dbcc_name << endl;
uint64_t bufferInt[3] = { 0 };
string bufferStr[3];
DBCCParser(bufferInt, bufferStr, dev->dbcc_name);
string VID = bufferStr[0];
string PID = bufferStr[1];
string serial = bufferStr[2];
string formattedID = "USB\\VID_" + VID + "&PID_" + PID + "\\" + serial;
string deviceOwner = "UNKNOWN";
char volLetter = '~'; //NULL
if (readWriteDev != nullptr) {
//We can try read the read write storage thing
//cout << "Attempting to read device owner" << endl;
DWORD unitMask = readWriteDev->dbcv_unitmask;
volLetter = 'A';
while (true) {
if (unitMask & 0x01) break;
else {
volLetter++;
unitMask = unitMask >> 1;
}
}
//cout << "Vol letter : " << volLetter << endl;
string signaturePath = string(1, volLetter) + ":\\signature.sig";
//cout << "Signature path : " << signaturePath << endl;
//Signature verification
ifstream fSig;
fSig.open(signaturePath);
string signatureBuffer[6];
string buf;
int i = 0;
while (getline(fSig, buf)) {
signatureBuffer[i] = buf;
i++;
}
fSig.close();
bool shouldContinue = true;
if (i != 6) {
cout << "Signature too short / malformed" << endl;
shouldContinue = false;
}
//Check 1 - is the hash correct
string combinedNoHash = signatureBuffer[1] + signatureBuffer[2] + signatureBuffer[3] + signatureBuffer[4];
string hash = sha256(combinedNoHash);
if (shouldContinue && hash != signatureBuffer[0]) {
cout << "Hashes do not align" << endl;
shouldContinue = false;
}
//Stripping the buffer stuff of the padding we added
//Custom strip function beacause this language is afwful
for (int i = 0; i < 6; i++) {
string bufferItem = signatureBuffer[i];
while (bufferItem[bufferItem.length() - 1] == '|') bufferItem = bufferItem.substr(0, bufferItem.length() - 1);
signatureBuffer[i] = bufferItem;
}
//We cannot use the USB for the public key - this must have been sent out of channel - see todo.txt
//Check 2 - was the signature properly signed
if (shouldContinue) {
string ownerPublicKeyPath = knownKeypairsPath + "\\" + signatureBuffer[1] + ".pem";
//cout << "Looking for " << signatureBuffer[1] << " @ " << ownerPublicKeyPath << endl;
//2.1 - do we know the keypair - if not we can tret it as unknown
ifstream ownerPublicKeyPem(ownerPublicKeyPath);
if (!ownerPublicKeyPem.good()) {
cout << "Owner unknown" << endl;
shouldContinue = false;
}
else {
RSA *ownerPublic = RSA_new();
ownerPublic = LoadPublicKey(ownerPublicKeyPath, "");
cout << "Carrying out verification - testing" << endl;
//cout << "Is owner public nullptr : " << (ownerPublic == nullptr) << endl;
//2.2 - Is the signature correct
string combinedWithHash = hash + combinedNoHash;
vector<unsigned char> signatureBytes = HexToBytes(signatureBuffer[5]);
bool verified = RSAVerify(
ownerPublic,
reinterpret_cast<const unsigned char*>(combinedWithHash.c_str()),
combinedWithHash.length(),
signatureBytes.data(),
signatureBytes.size()
);
//cout << "Verification result " << verified << endl;
shouldContinue = verified;
}
ownerPublicKeyPem.close();
}
if (shouldContinue) {
//We are verified in this case
cout << "Verfied and fully correct" << endl;
deviceOwner = signatureBuffer[1];
cout << "Device owner : " << deviceOwner << endl;
}
else {
//We are not verified
cout << "Not allowed - verification failed \nEjection imminent" << endl;
EjectUSB(formattedID);
}
}
else cout << "Device owner unknown" << endl;
//Known systems storage
fstream f;
f.open(knownCombinationsFilePath);
string fileBuffer;
string name = "";
while (getline(f, fileBuffer)) {
if (
(fileBuffer.substr(0, 04) == VID)
&& (fileBuffer.substr(4, 04) == PID)
&& (fileBuffer.substr(8, 16) == serial)
) {
//We know this device already
name = fileBuffer.substr(24, string::npos);
//cout << "Name : " << name << endl;
break;
}
}
if (name == "") {
if (shouldLearnNewDevices) {
cout << "New USB. Name : ";
cin >> name;
cout << endl;
string out = VID + PID + serial + name + "\n";
cout << "Out : " << out;
//File nosnesnse
f.clear();
f.seekp(0, ios::end);
f << out;
}
}
f.close();
//We need to work out how to mesh this with the above code for learning new devices
USBStatus usbStatus = {
deviceOwner,
name != "",
VID,
PID,
systemMode,
name,
};
uint8_t result = DoesUSBMatchPolicy(&usbStatus, &root);
//cout << "Policy Result : " << to_string(result) << endl;
bool ejected = false;
if (result == 2) {
cout << "Request for the following device : " << endl;
cout << "--------------------------------" << endl;
cout << "Previously known? : ";
if (usbStatus.known) cout << "True" << endl;
else cout << "False" << endl;
cout << "Owner : " << usbStatus.owner << endl;
cout << "VID : " << VID << endl;
cout << "PID : " << PID << endl;
cout << "Serial : " << serial << endl;
cout << "Name : " << name << endl;
cout << "--------------------------------" << endl;
string allowInput;
cout << "\nAllow? (Y/N) : ";
cin >> allowInput;
cout << endl;
if (!(allowInput == "Y" || allowInput == "y")) {
EjectUSB(formattedID);
ejected = true;
}
}
else if (result == 3) {
//cout << "Denial" << endl;
EjectUSB(formattedID);
ejected = true;
}
if (!ejected) {
//Watching USBs
string targetDrive = (string() + volLetter) + ":\\";
thread watchThread(WatchUSB, targetDrive);
watchThread.detach();
}
}
void GenerateSignature(RSA*& keypair, string* signatureInfo, string folderPath) {
cout << "Generating signature" << endl;
//Data preprocessing
signatureInfo[0] = PadAndTrimStr(signatureInfo[0], 128);
signatureInfo[1] = PadAndTrimStr(signatureInfo[1], 128);
time_t timestamp = time(NULL);