-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSysEnc.cpp
More file actions
1165 lines (1030 loc) · 37.9 KB
/
SysEnc.cpp
File metadata and controls
1165 lines (1030 loc) · 37.9 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
#pragma once
// header guarding
#ifndef __SYSTEM_ENCRYPTION_FF__
#include "SysEnc.hpp"
// double check for namespace macro definition validation
#if defined(__SYSTEM_ENCRYPTION_FF__)
/* Constructor/Destructor/Overloaders *\
\*************************************************************************************/
System::Crypto::Crypto(){};
System::Crypto::Crypto(const System::Crypto &other)
{
this->ID = other.ID;
};
System::Crypto::Crypto(System::Crypto &&other)
{
this->ID = other.ID;
other.ID = 0;
};
System::Crypto &System::Crypto::operator=(const System::Crypto &other)
{
if (*this == other)
return *this;
this->ID = other.ID;
return *this;
};
System::Crypto &System::Crypto::operator=(System::Crypto &&other)
{
if (*this == other)
return *this;
this->ID = other.ID;
other.ID = 0;
return *this;
};
const bool System::Crypto::operator==(const System::Crypto &other)
{
return (this->ID == other.ID);
}
// Destructor
System::Crypto::~Crypto()
{
this->ID = 0;
};
/* Message Log Routines *\
\*****************************************************************************/
void System::Crypto::LogMessage() {};
template <typename mT, typename... tArgs> void System::Crypto::LogMessage(mT msg, tArgs... m_list)
{
if (exeMode & ExecuteMode::VERBOSE)
logInfo(msg, m_list...);
};
void System::Crypto::LogWarning() {};
template <typename mT, typename... tArgs> void System::Crypto::LogWarning(mT msg, tArgs... m_list)
{
if (exeMode & ExecuteMode::VERBOSE)
logWarn(msg, m_list...);
};
void System::Crypto::LogError() {};
template <typename mT, typename... tArgs> void System::Crypto::LogError(mT msg, tArgs... m_list)
{
if (exeMode & ExecuteMode::VERBOSE)
logError(msg, m_list...);
};
/* File Handlers *\
\*****************************************************************************/
/**
* Write *buffer* into *file_name* using binary mode
* @param const StringView_t&
* @param const StringView_t&
* @returns void
*/
[[maybe_unused]] void System::Crypto::WriteFile(const StringView_t &file_name, const StringView_t &buffer, const WriteFileMode write_mode)
{
if (!FileExists(file_name) && write_mode == WriteFileMode::NO_CREATE) [[unlikely]]
{
throw std::runtime_error(String_t(file_name.data()) + " does not exists!");
}
std::ofstream fWriter(file_name.data(), std::ios::binary);
if (!fWriter.is_open()) [[unlikely]]
{
throw std::runtime_error(strerror(errno));
}
if (fWriter.good()) [[likely]]
{
fWriter.write(buffer.data(), buffer.size());
}
fWriter.close();
};
/**
* Read Content From *file_name* and return it as String_t
* @param const StringView_t&
* @returns const String_t
*/
[[maybe_unused, nodiscard]] const System::String_t System::Crypto::ReadFile(const StringView_t &file_name)
{
String_t fContent;
std::ifstream fRead(file_name.data(), std::ios::binary);
if (!fRead.is_open()) [[unlikely]]
throw std::runtime_error(String_t("Cannot read file!") + strerror(errno));
fRead.seekg(0, std::ios::end);
const std::streamsize file_size = fRead.tellg();
fContent.resize(file_size);
fRead.seekg(0, std::ios::beg);
if (fRead.good()) [[likely]]
{
fRead.read(fContent.data(), file_size);
}
fRead.close();
return fContent;
};
/**
* Check if REQUIRED Registry path is set/created, return true if found, false otherwise
* @returns const bool
*/
[[maybe_unused, nodiscard]] const bool System::Crypto::RegistryPathExists() noexcept
{
return (bool)(std::filesystem::exists(REGISTRY_ADDRESS_PATH) && std::filesystem::is_directory(REGISTRY_ADDRESS_PATH));
};
/**
* Create Registry Path for storing registry keys used for encryption and decryption operations, returns true if created, false otherwise.
* @returns const bool
*/
[[maybe_unused, nodiscard]] const bool System::Crypto::RegistryPathCreate() noexcept
{
return (bool)(std::filesystem::create_directory(REGISTRY_ADDRESS_PATH) || std::filesystem::create_directories(REGISTRY_ADDRESS_PATH));
};
[[nodiscard]] const bool System::Crypto::FileExists(const StringView_t &file_name) noexcept
{
std::filesystem::path fileAddress = file_name.data();
return (bool)(std::filesystem::exists(fileAddress) && std::filesystem::is_regular_file(fileAddress));
};
[[maybe_unused, nodiscard]] const bool System::Crypto::DirectoryExists(const StringView_t &dir_name)
{
return std::filesystem::exists(dir_name.data()) && std::filesystem::is_directory(dir_name.data());
};
/**
* Encrypt file content, CBC/AES encryption mode, return true if encrypted, false otherwise
* @param const StringView_t&
* @param CryptoPP::SecByteBlock&
* @returns bool
*/
[[maybe_unused, nodiscard]] const bool System::Crypto::EncryptFile(const StringView_t &file_name, const CryptoPP::SecByteBlock &use_sec_key)
{
try
{
if (file_name.empty() || !FileExists(file_name)) [[unlikely]]
throw std::runtime_error("Cannot find file name to encrypt");
else if (use_sec_key.size() != CryptoPP::AES::DEFAULT_KEYLENGTH) [[unlikely]]
throw std::runtime_error("Encryption Secure Key Block Size is invalid!");
CryptoPP::byte salt_value[CryptoPP::AES::DEFAULT_KEYLENGTH];
CryptoPP::AutoSeededRandomPool prng;
prng.GenerateBlock(salt_value, sizeof(salt_value));
std::ifstream readCipher(file_name.data(), std::ios::binary);
if (!readCipher.is_open()) [[unlikely]]
throw std::runtime_error("Cannot Open file for reading!");
std::stringstream buffer;
buffer << readCipher.rdbuf();
std::string plaintext = buffer.str();
buffer.clear();
readCipher.close();
CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption cbcEncryptor;
cbcEncryptor.SetKeyWithIV(use_sec_key, use_sec_key.size(), salt_value);
String_t ciphertext;
CryptoPP::StringSource(plaintext, true, new CryptoPP::StreamTransformationFilter(cbcEncryptor, new CryptoPP::StringSink(ciphertext)));
std::ofstream writeCipher(file_name.data(), std::ios::binary | std::ios::out | std::ios::trunc);
if (!writeCipher.is_open()) [[unlikely]]
throw std::runtime_error("Cannot write encrypted cipher to file");
writeCipher.write(reinterpret_cast<char *>(&salt_value), sizeof(salt_value));
writeCipher.write(ciphertext.c_str(), ciphertext.size());
writeCipher.close();
CondWait(5000);
LogMessage("[+] ", file_name.data(), " --> encrypted...\n");
if (!System::Crypto::Rename(file_name.data(), true))
{
LogWarning("Cannot rename filename ", file_name, '\n');
}
return true;
}
catch (const CryptoPP::Exception &_e)
{
std::cerr << "Encryption CryptoException: " << _e.what() << '\n';
return false;
}
catch (const std::runtime_error &_e)
{
std::cerr << "Encryption RuntimeError: " << _e.what() << '\n';
return false;
}
catch (const std::exception &_e)
{
std::cerr << "Encryption Exception: " << _e.what() << '\n';
return false;
}
return false;
};
/**
* Decrypt file content, CBC/AES encryption mode, return true if decrypted, false otherwise
* @param const StringView_t&
* @param CryptoPP::SecByteBlock&
* @returns bool
*/
[[maybe_unused, nodiscard]] const bool System::Crypto::DecryptFile(const StringView_t &file_name, const CryptoPP::SecByteBlock &sec_key)
{
try
{
if (file_name.empty() || !FileExists(file_name)) [[unlikely]]
throw std::runtime_error("cannot find file for decryption!");
else if (sec_key.size() != CryptoPP::AES::DEFAULT_KEYLENGTH) [[unlikely]]
throw std::runtime_error("Secure Key Block size is invalid!");
CryptoPP::byte salt_value[CryptoPP::AES::DEFAULT_KEYLENGTH];
std::ifstream readCipher(file_name.data(), std::ios::binary);
if (!readCipher.is_open()) [[unlikely]]
throw std::runtime_error("Cannot open file for decryption!");
readCipher.read(reinterpret_cast<char *>(&salt_value), sizeof(salt_value));
CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption cbcDecryptor;
cbcDecryptor.SetKeyWithIV(sec_key, sec_key.size(), salt_value);
String_t ciphertext((std::istreambuf_iterator<char>(readCipher)), std::istreambuf_iterator<char>());
String_t recovered_cipher;
CryptoPP::StringSource(ciphertext, true, new CryptoPP::StreamTransformationFilter(cbcDecryptor, new CryptoPP::StringSink(recovered_cipher)));
std::ofstream writeRecovered(file_name.data(), std::ios::binary | std::ios::out | std::ios::trunc);
if (!writeRecovered.is_open()) [[unlikely]]
throw std::runtime_error("Cannot write recovered cipher to owner file!");
else if (recovered_cipher.empty()) [[unlikely]]
throw std::runtime_error("Attempting Write decrypted Empty buffer to file!");
writeRecovered.write(recovered_cipher.c_str(), recovered_cipher.size());
writeRecovered.close();
CondWait(5000);
LogMessage("[+] ", file_name.data(), " --> decrypted...\n");
if (!System::Crypto::Rename(file_name.data(), false))
{
LogWarning("Cannot rename filename ", file_name, '\n');
}
return true;
}
catch (const CryptoPP::Exception &_e)
{
std::cerr << "Decryption Error: Supplied Key Invalid!" << '\n';
return false;
}
catch (const std::runtime_error &_e)
{
std::cerr << "Decryption RuntimeError: " << _e.what() << '\n';
return false;
}
catch (const std::exception &_e)
{
std::cerr << "Decryption Exception: " << _e.what() << '\n';
return false;
}
return false;
};
/**
* Create a backup copy of the data to be encrypted, returns true if successfully backup, false otherwise.
* @param const StringView_t& the target path to backup
* @returns const bool
*/
[[maybe_unused, nodiscard]] const bool System::Crypto::CreateBackup(const StringView_t &target)
{
try
{
if (target.empty() || target[0] == ' ')
return false;
std::filesystem::path sourceDir = target.data();
if (!std::filesystem::exists(sourceDir) || !std::filesystem::is_directory(sourceDir)) [[unlikely]]
throw std::runtime_error(String_t("Directory ") + target.data() + " does not exists or not a dir!");
LogMessage("Creating backup of resource: ", target.data(), '\n');
String_t backupFolder = target.data();
backupFolder += "-backup";
std::filesystem::path backupPath = backupFolder;
if (!std::filesystem::exists(backupPath)) [[unlikely]]
{
std::filesystem::create_directories(backupPath) || std::filesystem::create_directory(backupPath);
}
UInt64_t clone_count = 0;
for (auto &entry : std::filesystem::recursive_directory_iterator(sourceDir))
{
std::filesystem::path relativePath = std::filesystem::relative(entry.path(), sourceDir);
std::filesystem::path destinationPath = backupFolder / relativePath;
if (std::filesystem::is_regular_file(entry)) [[likely]]
{
LogMessage("Cloning File ", entry.path(), '\n');
std::filesystem::copy_file(entry.path(), destinationPath, std::filesystem::copy_options::overwrite_existing);
++clone_count;
}
else if (std::filesystem::is_directory(entry)) [[likely]]
{
LogMessage("Cloning Directory ", entry.path(), '\n');
std::filesystem::create_directories(destinationPath);
}
else if (std::filesystem::is_symlink(entry)) [[unlikely]]
{
LogMessage("Cloning SymLink ", entry.path(), '\n');
std::filesystem::copy(entry.path(), destinationPath, std::filesystem::copy_options::create_symlinks);
++clone_count;
}
CondWait(9000);
}
LogMessage("Cloned Total: ", aggregation_size, "/", clone_count, '\n');
return clone_count == aggregation_size ? true : false;
}
catch (const std::exception &_e)
{
LogWarning("Error: cannot backup -> ", std::move(_e.what()));
return false;
}
return false;
};
/**
* Collect target entries and return vector containing all found entries.
* @param const StringView_t& target
* @returns std::vector<String_t>
*/
[[nodiscard]] const std::vector<System::String_t> System::Crypto::DirectoryAggregation(const System::StringView_t &target)
{
std::vector<System::String_t> Aggregation;
const std::filesystem::path ScanPath = target.data();
if (std::filesystem::exists(ScanPath) & std::filesystem::is_directory(ScanPath)) [[likely]]
{
for (const std::filesystem::directory_entry &_aggr_entry : std::filesystem::recursive_directory_iterator(ScanPath))
{
if (!_aggr_entry.is_directory()) [[likely]]
{
LogMessage("[+] ", _aggr_entry.path().string().c_str(), '\n');
CondWait(5000);
Aggregation.push_back(_aggr_entry.path().c_str());
}
}
LogMessage("Collected ", Aggregation.size(), " entries.\n");
aggregation_size = Aggregation.size();
}
else if (std::filesystem::is_regular_file(ScanPath)) [[unlikely]]
{
Aggregation.push_back(target.data());
}
return Aggregation;
};
/**
* Rename file name to a random generated value, returns true on success, false on failure.
* @param const System::StringView_t& the file to rename
* @param const bool if for encryption or decryption
* @returns const bool
*/
[[nodiscard]] const bool System::Crypto::Rename(const System::StringView_t &file_name, const bool byte_plus)
{
try
{
if (!file_name.empty() && file_name.size() < 300) [[likely]]
{
const PathBlocks pBlock = __SplitPath(file_name);
if (!pBlock.file.empty() && !pBlock.path.empty()) [[likely]]
{
String_t new_file_name = pBlock.path.c_str();
__ByteShiftBlocks(pBlock.file, new_file_name, byte_plus);
if (std::rename(file_name.data(), new_file_name.c_str()) != 0)
{
std::cerr << "Failed to rename file " << file_name << " -> " << strerror(errno) << '\n';
}
}
}
}
catch (const std::runtime_error &_e)
{
return false;
}
catch (const std::exception &_e)
{
return false;
}
return true;
};
/**
* Create a test directory with a list of files from test_files list, test_files entries must only contain file name without path,
* and the dir_path value must be an absolute path to the test directory to create.
* For example, dir_path = "/path/to/dir/test" and test_file = {"file1.txt", "file2.txt", ...}
* @param const StringView_t& the directory path
* @param const std::initializer_list<String_t> list of files to create into dir_path
* @returns const bool if test directory was created or not
*/
[[maybe_unused, nodiscard]] const System::String_t System::Crypto::CreateTestDirectory(const StringView_t &dir_path, const std::initializer_list<String_t> test_files)
{
String_t rVal;
if (dir_path.empty())
{
LogWarning("Test Directory is empty!\n");
return rVal;
}
if (test_files.size() == 0)
{
LogWarning("File list is empty, no files will be created..\n");
}
if (DirectoryExists(dir_path))
{
LogWarning("Directory already exists!\n");
return rVal;
}
std::filesystem::create_directories(std::move(dir_path.data())) || std::filesystem::create_directory(std::move(dir_path.data()));
if (DirectoryExists(dir_path.data()))
{
for (const String_t &new_file : test_files)
{
if (new_file.compare(".") == 0 || new_file.compare("..") == 0)
continue;
String_t entry_id = dir_path.data();
entry_id += PATH_SEPARATOR;
entry_id += std::move(new_file.c_str());
LogMessage("Creating test file <", entry_id, ">...\n");
std::ofstream createFile(entry_id.c_str());
createFile << "Something in this file";
createFile.close();
if (FileExists(std::move(entry_id.c_str())))
{
LogMessage("File <", entry_id.c_str(), "> created!\n");
}
}
rVal = dir_path;
}
else
{
LogError("Cannot find directory!");
}
return rVal;
};
/* Suppliers *\
\*****************************************************************************/
[[maybe_unused]] void System::Crypto::SetRecoveryMode(void) noexcept
{
LogMessage("Veryfing Registry Key Address...\n");
if (!RegistryPathExists()) [[likely]]
{
LogMessage("Registry Path Not Found\n");
if (!RegistryPathCreate()) [[unlikely]]
{
LogMessage("Cannot create Registry Path\n");
return;
}
LogMessage("Registry Path Created\n");
}
String_t rec_mode;
std::cout << "Choose Decryption Recovery Mode:\n1) Supply Your Own Recovery key\n2) Generate Secure Keys\n";
SetRecoveryMode:
std::cout << "Select One [1/2] : ";
std::cin >> rec_mode;
if (rec_mode.compare("1") == 0) [[likely]]
{
recovery_mode = RecoveryMode::CUSTOM_SUPPLY;
WriteFile(RECOVERY_MODE_PATH, "S", WriteFileMode::CREATE_NEW);
}
else if (rec_mode.compare("2") == 0) [[unlikely]]
{
recovery_mode = RecoveryMode::GENERATE_SECURE;
WriteFile(RECOVERY_MODE_PATH, "G", WriteFileMode::CREATE_NEW);
}
else
{
goto SetRecoveryMode;
}
};
[[maybe_unused, nodiscard]] const System::String_t System::Crypto::SetCustomKeyAddress() noexcept
{
String_t key_address = "";
RecoveryKeySetPath:
std::cout << "Location to Store Recovery Key (type '?' for default) : ";
std::cin >> key_address;
if (key_address.size() == 0 || key_address.size() > MAX_PATH_LENGTH) [[unlikely]]
{
std::cout << "Path Length error! [0/" << MAX_PATH_LENGTH << "]\n";
goto RecoveryKeySetPath;
}
else if (key_address.compare("?") == 0) [[likely]]
{
key_address.clear();
key_address = DEFAULT_SECURE_OWN_KEY_PATH;
}
return key_address;
};
[[maybe_unused, nodiscard]] const System::String_t System::Crypto::SetRecoveryKey() noexcept
{
String_t recovery_key = "";
RecoveryKeySet:
std::cout << "Recovery Key: ";
std::cin >> recovery_key;
if (recovery_key.size() < 6 || recovery_key.size() > 100) [[unlikely]]
{
std::cout << "Recovery key length error, [6/100]\n";
goto RecoveryKeySet;
}
return recovery_key;
};
[[maybe_unused, nodiscard]] const System::String_t System::Crypto::SetTargetPath() noexcept
{
String_t target_path = "";
TargetPathSupply:
std::cout << "Target to Encrypt (type '.' for root) : ";
std::cin >> target_path;
if (target_path.empty()) [[unlikely]]
{
std::cout << "path is empty!\n";
goto TargetPathSupply;
}
else if (target_path.compare(".") == 0) [[unlikely]]
{
target_path.clear();
target_path = BASE_DIRECTORY;
}
else if (!DirectoryExists(target_path) && !FileExists(target_path)) [[unlikely]]
{
std::cout << "Supplied Path not found!\n";
goto TargetPathSupply;
}
return target_path;
};
[[maybe_unused, nodiscard]] const bool System::Crypto::Want2CreateBackup() noexcept
{
std::cout << "Create Backup? [y/n] : ";
char x;
std::cin >> x;
if (x == 'y' || x == 'Y') [[likely]]
{
return true;
}
return false;
};
[[maybe_unused, nodiscard]] const bool System::Crypto::Approve() noexcept
{
Char_t x;
std::cout << "Continue? [y/n]: ";
std::cin >> x;
return (bool)(x == 'y' || x == 'Y');
}
/* Key/Iv/Secrects *\
\*****************************************************************************/
[[maybe_unused, nodiscard]] const System::RecoveryMode System::Crypto::GetRecoveryMode()
{
if (RegistryPathExists()) [[likely]]
{
if (FileExists(RECOVERY_MODE_PATH)) [[likely]]
{
const String_t rMode = ReadFile(RECOVERY_MODE_PATH).c_str();
if (rMode.size() > 0 && rMode.size() < 5) [[likely]]
return rMode.compare("G") == 0 || rMode.compare("S") == 0 ? (rMode.compare("G") == 0 ? RecoveryMode::GENERATE_SECURE : RecoveryMode::CUSTOM_SUPPLY) : RecoveryMode::NONE;
}
}
return RecoveryMode::NONE;
};
[[maybe_unused, nodiscard]] const System::String_t System::Crypto::GetRecoveryKeyAddress()
{
String_t kAddress;
if (FileExists(SECURE_OWN_KEY_REF)) [[likely]]
{
kAddress = ReadFile(SECURE_OWN_KEY_REF).c_str();
}
return kAddress;
};
/**
* Parse generated secure key block with *raw_key* content, and store it into file.
* @param const StringView_t&
* @returns void
*/
[[maybe_unused]] void System::Crypto::RecoveryKeyIntersectAndRegister(const StringView_t &raw_key)
{
if (raw_key.empty()) [[unlikely]]
{
throw std::runtime_error("Raw key is empty!");
}
String_t rkey = raw_key.data();
CryptoPP::SecByteBlock key(CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::PKCS5_PBKDF2_HMAC<CryptoPP::SHA256> pbkdf2;
pbkdf2.DeriveKey(key, key.size(), (CryptoPP::byte *)rkey.data(), rkey.size());
const String_t location_drop = GetRecoveryKeyAddress();
if (!location_drop.empty()) [[likely]]
{
std::ofstream StoreKey(location_drop.data(), std::ios::binary);
if (StoreKey.is_open()) [[likely]]
{
StoreKey.write(reinterpret_cast<const char *>(key.data()), key.SizeInBytes());
}
StoreKey.close();
}
};
/**
* Parse generated secure key block with *raw_key* content, and return result key block.
* @param const StringView_t&
* @returns std::optional<CryptoPP::SecByteBlock>
*/
[[maybe_unused]] std::optional<CryptoPP::SecByteBlock> System::Crypto::RecoveryKeyIntersect(const StringView_t &raw_key)
{
std::optional<CryptoPP::SecByteBlock> key_parse = std::nullopt;
try
{
if (raw_key.empty()) [[unlikely]]
throw std::runtime_error("Supplied Raw key empty!");
String_t rkey = raw_key.data();
CryptoPP::SecByteBlock key(CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::PKCS5_PBKDF2_HMAC<CryptoPP::SHA256> pbkdf2;
pbkdf2.DeriveKey(key, key.size(), (CryptoPP::byte *)rkey.data(), rkey.size());
key_parse = key;
}
catch (const std::runtime_error &_e)
{
std::cerr << "Custom Key Parse Error: " << _e.what() << '\n';
}
catch (const std::exception &_e)
{
std::cerr << "Custom Key Parse Exception: " << _e.what() << '\n';
}
return key_parse;
};
[[maybe_unused, nodiscard]] const std::optional<CryptoPP::SecByteBlock> System::Crypto::GetRecoveryKey()
{
std::optional<CryptoPP::SecByteBlock> yVal;
if (FileExists(SECURE_OWN_KEY_REF)) [[likely]]
{
const String_t get_key_location = ReadFile(SECURE_OWN_KEY_REF);
if (get_key_location.empty()) [[unlikely]]
{
throw std::runtime_error("Cannot Find Custom Key Location!");
}
std::ifstream ReadKeyFromFile(get_key_location.c_str(), std::ios::binary);
if (ReadKeyFromFile.is_open()) [[likely]]
{
ReadKeyFromFile.seekg(0, std::ios::end);
yVal = CryptoPP::SecByteBlock(ReadKeyFromFile.tellg());
ReadKeyFromFile.seekg(0, std::ios::beg);
ReadKeyFromFile.read(reinterpret_cast<char *>(yVal.value().BytePtr()), yVal.value().size());
ReadKeyFromFile.close();
}
}
return yVal;
};
[[maybe_unused]] void System::Crypto::RegisterTargetPath(const StringView_t &target)
{
if (target.empty()) [[unlikely]]
return;
if (!RegistryPathExists()) [[likely]]
{
if (!RegistryPathCreate()) [[unlikely]]
{
throw std::runtime_error("Cannot create Registry Address!");
}
}
WriteFile(TARGET_ADDRESS_PATH, target, WriteFileMode::CREATE_NEW);
const String_t get_target = ReadFile(TARGET_ADDRESS_PATH);
if (get_target.empty() || get_target.compare(" ") == 0) [[unlikely]]
{
throw std::runtime_error("Cannot get target file name, maybe empty or not valid!");
}
};
[[nodiscard]] const std::optional<System::String_t> System::Crypto::GetTargetPath()
{
std::optional<String_t> rOptBlock = std::nullopt;
if (FileExists(TARGET_ADDRESS_PATH)) [[likely]]
{
const String_t target_path = ReadFile(TARGET_ADDRESS_PATH).c_str();
if (!target_path.empty()) [[likely]]
{
rOptBlock = std::move(target_path.data());
}
}
return rOptBlock;
};
/**
* Verify if key is stored, and stored key size verification to prevent illformed keys from being used, returns true if key is found and valid, false otherwise.
* @param void
* @returns const bool
*/
[[maybe_unused, nodiscard]] const bool System::Crypto::IsKeySet()
{
try
{
if (FileExists(SECURE_OWN_KEY_REF)) [[likely]]
{
const String_t key_validate = ReadFile(std::move(ReadFile(SECURE_OWN_KEY_REF).c_str()));
if (!key_validate.empty()) [[likely]]
{
LogMessage("KEY SIZE: ", key_validate.size(), '\n');
if (key_validate.size() == CryptoPP::AES::DEFAULT_KEYLENGTH) [[likely]]
{
return true;
}
}
}
}
catch (const std::exception &_e)
{
return false;
}
return false;
};
/* Compression *\
\*****************************************************************************/
/**
* Compress file
* @param const StringView_t&
* @param const StringView_t&
* @returns void
*/
[[maybe_unused]] void System::Crypto::CompressFile(const StringView_t &file_path, const StringView_t &dest_file)
{
try
{
std::ifstream readFileContent(file_path.data(), std::ios::binary);
std::ofstream writeFileContent(dest_file.data(), std::ios::binary);
if (!readFileContent.is_open() || !writeFileContent.is_open()) [[unlikely]]
{
throw std::runtime_error("Cannot read or write to file!");
}
z_stream deflateStream;
deflateStream.zalloc = Z_NULL;
deflateStream.zfree = Z_NULL;
deflateStream.opaque = Z_NULL;
if (deflateInit(&deflateStream, Z_BEST_COMPRESSION) != Z_OK) [[unlikely]]
{
throw std::runtime_error("Failed to initialize zlib for compression.");
}
Char_t inBuffer[16384];
Char_t outBuffer[16384];
int bytesRead = 0;
do
{
readFileContent.read(inBuffer, sizeof(inBuffer));
bytesRead = static_cast<int>(readFileContent.gcount());
if (bytesRead > 0)
{
deflateStream.avail_in = bytesRead;
deflateStream.next_in = reinterpret_cast<Bytef *>(inBuffer);
do
{
deflateStream.avail_out = sizeof(outBuffer);
deflateStream.next_out = reinterpret_cast<Bytef *>(outBuffer);
deflate(&deflateStream, Z_NO_FLUSH);
int compressedBytes = sizeof(outBuffer) - deflateStream.avail_out;
writeFileContent.write(outBuffer, compressedBytes);
} while (deflateStream.avail_out == 0);
}
} while (bytesRead > 0);
do
{
deflateStream.avail_out = sizeof(outBuffer);
deflateStream.next_out = reinterpret_cast<Bytef *>(outBuffer);
int result = deflate(&deflateStream, Z_FINISH);
int compressedBytes = sizeof(outBuffer) - deflateStream.avail_out;
writeFileContent.write(outBuffer, compressedBytes);
if (result == Z_STREAM_END)
{
break;
}
} while (true);
deflateEnd(&deflateStream);
readFileContent.close();
writeFileContent.close();
}
catch (const std::runtime_error &e)
{
std::cerr << "Deflate Error: " << e.what() << std::endl;
}
catch (const std::exception &e)
{
std::cerr << "Deflate Exception: " << e.what() << std::endl;
}
};
/**
* Decompress file
* @param const StringView_t&
* @param const StringView_t&
* @returns void
*/
[[maybe_unused]] void System::Crypto::DecompressFile(const StringView_t &compressedFile, const StringView_t &decompressedFile)
{
std::ifstream inFile(compressedFile.data(), std::ios::binary);
if (!inFile.is_open()) [[unlikely]]
{
LogError("Error: Failed to open input file.\n");
return;
}
std::ofstream outFile(decompressedFile.data(), std::ios::binary);
if (!outFile.is_open()) [[unlikely]]
{
LogError("Error: Failed to open output file.\n");
inFile.close();
return;
}
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
stream.avail_in = 0;
stream.next_in = Z_NULL;
if (inflateInit(&stream) != Z_OK) [[unlikely]]
{
LogError("Error: Failed to initialize zlib for decompression.\n");
inFile.close();
outFile.close();
return;
}
Char_t inBuffer[16384];
Char_t outBuffer[16384];
int bytesRead = 0;
do
{
inFile.read(inBuffer, sizeof(inBuffer));
bytesRead = static_cast<int>(inFile.gcount());
if (bytesRead > 0)
{
stream.avail_in = bytesRead;
stream.next_in = reinterpret_cast<Bytef *>(inBuffer);
do
{
stream.avail_out = sizeof(outBuffer);
stream.next_out = reinterpret_cast<Bytef *>(outBuffer);
int result = inflate(&stream, Z_NO_FLUSH);
int decompressedBytes = sizeof(outBuffer) - stream.avail_out;
outFile.write(outBuffer, decompressedBytes);
if (result == Z_STREAM_END)
{
break;
}
} while (stream.avail_out == 0);
}
} while (bytesRead > 0);
inflateEnd(&stream);
inFile.close();
outFile.close();
};
/* SSL Asymmetric/Symmetric Encryption *\
\*****************************************************************************/
/**
* Generate Ssl public/private keys, returns true if keys are created, false otherwise.
* @param const StringView_t& private key path
* @param const StringView_t& public key path
* @param const UInt16_t the key size to generate
* @returns const bool
*/
[[maybe_unused, nodiscard]] const bool System::Crypto::GenSslKeyPair(const StringView_t &private_key_path, const StringView_t &public_key_path, const UInt16_t key_size = 2048)
{
using namespace CryptoPP;
AutoSeededRandomPool rng;
RSA::PrivateKey privateKey;
privateKey.GenerateRandomWithKeySize(rng, key_size);
try
{
Base64Encoder base64Encoder(new FileSink(private_key_path.data()));
privateKey.Save(base64Encoder);
base64Encoder.MessageEnd();
LogMessage("Private key saved to: ", private_key_path, '\n');
}
catch (const Exception &ex)
{
std::cerr << "Failed to save private key: " << ex.what() << std::endl;
return false;
}
RSA::PublicKey publicKey(privateKey);
try
{
Base64Encoder base64Encoder(new FileSink(public_key_path.data()));
publicKey.Save(base64Encoder);
base64Encoder.MessageEnd();
LogMessage("Public key saved to: ", std::move(public_key_path), '\n');
return true;
}
catch (const Exception &ex)
{
std::cerr << "Failed to save public key: " << ex.what() << std::endl;
return false;
}
return true;
};
/**
* Generate a pair of ssl public/private keys, returns true if keys are created, false otherwise.
* @param const System::SslKeyBlock, block containing private/public key and key size
* @returns const bool
*/
[[maybe_unused, nodiscard]] const bool System::Crypto::GenSslKeyPair(const System::SslKeyBlock key_info)
{
if (key_info.public_key.size() < 1 || key_info.private_key.size() < 1) [[unlikely]]
{
std::cout << "Ssl Public/Private key paths not supplied, please use flags --public=/path/to/public/key --private=/path/to/private/key --keysize=2048\n";
return false;
}
using namespace CryptoPP;
AutoSeededRandomPool rng;
RSA::PrivateKey privateKey;
privateKey.GenerateRandomWithKeySize(rng, key_info.key_size);