Repository navigation
Expand file tree
/
Copy pathBootEncryption.cpp
More file actions
2457 lines (1912 loc) · 68.7 KB
/
Copy pathBootEncryption.cpp
File metadata and controls
2457 lines (1912 loc) · 68.7 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
/*
Copyright (c) 2008-2010 TrueCrypt Developers Association. All rights reserved.
Governed by the TrueCrypt License 3.0 the full text of which is contained in
the file License.txt included in TrueCrypt binary and source code distribution
packages.
*/
#include "Tcdefs.h"
#include "Platform/Finally.h"
#include "Platform/ForEach.h"
#include <Setupapi.h>
#include <devguid.h>
#include <io.h>
#include <shlobj.h>
#include <atlbase.h>
#include "BootEncryption.h"
#include "Boot/Windows/BootCommon.h"
#include "Common/Resource.h"
#include "Crc.h"
#include "Crypto.h"
#include "Dlgcode.h"
#include "Endian.h"
#include "Language.h"
#include "Random.h"
#include "Registry.h"
#include "Volumes.h"
#ifdef VOLFORMAT
#include "Format/FormatCom.h"
#elif defined (TCMOUNT)
#include "Mount/MainCom.h"
#endif
namespace TrueCrypt
{
#if !defined (SETUP)
class Elevator
{
public:
static void AddReference ()
{
++ReferenceCount;
}
static void CallDriver (DWORD ioctl, void *input, DWORD inputSize, void *output, DWORD outputSize)
{
Elevate();
CComBSTR inputBstr;
if (input && inputBstr.AppendBytes ((const char *) input, inputSize) != S_OK)
throw ParameterIncorrect (SRC_POS);
CComBSTR outputBstr;
if (output && outputBstr.AppendBytes ((const char *) output, outputSize) != S_OK)
throw ParameterIncorrect (SRC_POS);
DWORD result = ElevatedComInstance->CallDriver (ioctl, inputBstr, &outputBstr);
if (output)
memcpy (output, *(void **) &outputBstr, outputSize);
if (result != ERROR_SUCCESS)
{
SetLastError (result);
throw SystemException();
}
}
static void CopyFile (const string &sourceFile, const string &destinationFile)
{
Elevate();
DWORD result = ElevatedComInstance->CopyFile (CComBSTR (sourceFile.c_str()), CComBSTR (destinationFile.c_str()));
if (result != ERROR_SUCCESS)
{
SetLastError (result);
throw SystemException();
}
}
static void DeleteFile (const string &file)
{
Elevate();
DWORD result = ElevatedComInstance->DeleteFile (CComBSTR (file.c_str()));
if (result != ERROR_SUCCESS)
{
SetLastError (result);
throw SystemException();
}
}
static void ReadWriteFile (BOOL write, BOOL device, const string &filePath, byte *buffer, uint64 offset, uint32 size, DWORD *sizeDone)
{
Elevate();
CComBSTR bufferBstr;
if (bufferBstr.AppendBytes ((const char *) buffer, size) != S_OK)
throw ParameterIncorrect (SRC_POS);
DWORD result = ElevatedComInstance->ReadWriteFile (write, device, CComBSTR (filePath.c_str()), &bufferBstr, offset, size, sizeDone);
if (result != ERROR_SUCCESS)
{
SetLastError (result);
throw SystemException();
}
if (!write)
memcpy (buffer, (BYTE *) bufferBstr.m_str, size);
}
static BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly)
{
Elevate();
return ElevatedComInstance->IsPagingFileActive (checkNonWindowsPartitionsOnly);
}
static void WriteLocalMachineRegistryDwordValue (char *keyPath, char *valueName, DWORD value)
{
Elevate();
DWORD result = ElevatedComInstance->WriteLocalMachineRegistryDwordValue (CComBSTR (keyPath), CComBSTR (valueName), value);
if (result != ERROR_SUCCESS)
{
SetLastError (result);
throw SystemException();
}
}
static void RegisterFilterDriver (bool registerDriver, BootEncryption::FilterType filterType)
{
Elevate();
DWORD result = ElevatedComInstance->RegisterFilterDriver (registerDriver ? TRUE : FALSE, filterType);
if (result != ERROR_SUCCESS)
{
SetLastError (result);
throw SystemException();
}
}
static void RegisterSystemFavoritesService (BOOL registerService)
{
Elevate();
DWORD result = ElevatedComInstance->RegisterSystemFavoritesService (registerService);
if (result != ERROR_SUCCESS)
{
SetLastError (result);
throw SystemException();
}
}
static void Release ()
{
if (--ReferenceCount == 0 && ElevatedComInstance)
{
ElevatedComInstance->Release();
ElevatedComInstance = nullptr;
CoUninitialize ();
}
}
static void SetDriverServiceStartType (DWORD startType)
{
Elevate();
DWORD result = ElevatedComInstance->SetDriverServiceStartType (startType);
if (result != ERROR_SUCCESS)
{
SetLastError (result);
throw SystemException();
}
}
protected:
static void Elevate ()
{
if (IsAdmin())
{
SetLastError (ERROR_ACCESS_DENIED);
throw SystemException();
}
if (!ElevatedComInstance || ElevatedComInstanceThreadId != GetCurrentThreadId())
{
CoInitialize (NULL);
ElevatedComInstance = GetElevatedInstance (GetActiveWindow() ? GetActiveWindow() : MainDlg);
ElevatedComInstanceThreadId = GetCurrentThreadId();
}
}
#if defined (TCMOUNT)
static ITrueCryptMainCom *ElevatedComInstance;
#elif defined (VOLFORMAT)
static ITrueCryptFormatCom *ElevatedComInstance;
#endif
static DWORD ElevatedComInstanceThreadId;
static int ReferenceCount;
};
#if defined (TCMOUNT)
ITrueCryptMainCom *Elevator::ElevatedComInstance;
#elif defined (VOLFORMAT)
ITrueCryptFormatCom *Elevator::ElevatedComInstance;
#endif
DWORD Elevator::ElevatedComInstanceThreadId;
int Elevator::ReferenceCount = 0;
#else // SETUP
class Elevator
{
public:
static void AddReference () { }
static void CallDriver (DWORD ioctl, void *input, DWORD inputSize, void *output, DWORD outputSize) { throw ParameterIncorrect (SRC_POS); }
static void ReadWriteFile (BOOL write, BOOL device, const string &filePath, byte *buffer, uint64 offset, uint32 size, DWORD *sizeDone) { throw ParameterIncorrect (SRC_POS); }
static void RegisterFilterDriver (bool registerDriver, BootEncryption::FilterType filterType) { throw ParameterIncorrect (SRC_POS); }
static void Release () { }
static void SetDriverServiceStartType (DWORD startType) { throw ParameterIncorrect (SRC_POS); }
};
#endif // SETUP
File::File (string path, bool readOnly, bool create) : Elevated (false), FileOpen (false)
{
Handle = CreateFile (path.c_str(),
readOnly ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, create ? CREATE_ALWAYS : OPEN_EXISTING,
FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_WRITE_THROUGH, NULL);
try
{
throw_sys_if (Handle == INVALID_HANDLE_VALUE);
}
catch (SystemException &)
{
if (GetLastError() == ERROR_ACCESS_DENIED && IsUacSupported())
Elevated = true;
else
throw;
}
FileOpen = true;
FilePointerPosition = 0;
IsDevice = false;
Path = path;
}
void File::Close ()
{
if (FileOpen)
{
if (!Elevated)
CloseHandle (Handle);
FileOpen = false;
}
}
DWORD File::Read (byte *buffer, DWORD size)
{
DWORD bytesRead;
if (Elevated)
{
DWORD bytesRead;
Elevator::ReadWriteFile (false, IsDevice, Path, buffer, FilePointerPosition, size, &bytesRead);
FilePointerPosition += bytesRead;
return bytesRead;
}
throw_sys_if (!ReadFile (Handle, buffer, size, &bytesRead, NULL));
return bytesRead;
}
void File::SeekAt (int64 position)
{
FilePointerPosition = position;
if (!Elevated)
{
LARGE_INTEGER pos;
pos.QuadPart = position;
throw_sys_if (!SetFilePointerEx (Handle, pos, NULL, FILE_BEGIN));
}
}
void File::Write (byte *buffer, DWORD size)
{
DWORD bytesWritten;
try
{
if (Elevated)
{
Elevator::ReadWriteFile (true, IsDevice, Path, buffer, FilePointerPosition, size, &bytesWritten);
FilePointerPosition += bytesWritten;
throw_sys_if (bytesWritten != size);
}
else
{
throw_sys_if (!WriteFile (Handle, buffer, size, &bytesWritten, NULL) || bytesWritten != size);
}
}
catch (SystemException &e)
{
if (!IsDevice || e.ErrorCode != ERROR_WRITE_PROTECT)
throw;
BootEncryption bootEnc (NULL);
while (size >= TC_SECTOR_SIZE_BIOS)
{
bootEnc.WriteBootDriveSector (FilePointerPosition, buffer);
FilePointerPosition += TC_SECTOR_SIZE_BIOS;
buffer += TC_SECTOR_SIZE_BIOS;
size -= TC_SECTOR_SIZE_BIOS;
}
}
}
void Show (HWND parent, const string &str)
{
MessageBox (parent, str.c_str(), NULL, 0);
}
Device::Device (string path, bool readOnly)
{
FileOpen = false;
Elevated = false;
Handle = CreateFile ((string ("\\\\.\\") + path).c_str(),
readOnly ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_WRITE_THROUGH, NULL);
try
{
throw_sys_if (Handle == INVALID_HANDLE_VALUE);
}
catch (SystemException &)
{
if (GetLastError() == ERROR_ACCESS_DENIED && IsUacSupported())
Elevated = true;
else
throw;
}
FileOpen = true;
FilePointerPosition = 0;
IsDevice = true;
Path = path;
}
BootEncryption::BootEncryption (HWND parent)
: DriveConfigValid (false),
ParentWindow (parent),
RealSystemDriveSizeValid (false),
RescueIsoImage (nullptr),
RescueVolumeHeaderValid (false),
SelectedEncryptionAlgorithmId (0),
VolumeHeaderValid (false)
{
Elevator::AddReference();
}
BootEncryption::~BootEncryption ()
{
if (RescueIsoImage)
delete[] RescueIsoImage;
Elevator::Release();
}
void BootEncryption::CallDriver (DWORD ioctl, void *input, DWORD inputSize, void *output, DWORD outputSize)
{
try
{
DWORD bytesReturned;
throw_sys_if (!DeviceIoControl (hDriver, ioctl, input, inputSize, output, outputSize, &bytesReturned, NULL));
}
catch (SystemException &)
{
if (GetLastError() == ERROR_ACCESS_DENIED && IsUacSupported())
Elevator::CallDriver (ioctl, input, inputSize, output, outputSize);
else
throw;
}
}
// Finds the first partition physically located behind the active one and returns its properties
Partition BootEncryption::GetPartitionForHiddenOS ()
{
Partition candidatePartition;
memset (&candidatePartition, 0, sizeof(candidatePartition));
// The user may have modified/added/deleted partitions since the time the partition table was last scanned
InvalidateCachedSysDriveProperties();
SystemDriveConfiguration config = GetSystemDriveConfiguration ();
bool activePartitionFound = false;
bool candidateForHiddenOSFound = false;
if (config.SystemPartition.IsGPT)
throw ParameterIncorrect (SRC_POS); // It is assumed that CheckRequirements() had been called
// Find the first active partition on the system drive
foreach (const Partition &partition, config.Partitions)
{
if (partition.Info.BootIndicator)
{
if (partition.Info.PartitionNumber != config.SystemPartition.Number)
{
// If there is an extra boot partition, the system partition must be located right behind it
if (IsOSAtLeast (WIN_7) && config.ExtraBootPartitionPresent)
{
int64 minOffsetFound = config.DrivePartition.Info.PartitionLength.QuadPart;
Partition bootPartition = partition;
Partition partitionBehindBoot;
foreach (const Partition &partition, config.Partitions)
{
if (partition.Info.StartingOffset.QuadPart > bootPartition.Info.StartingOffset.QuadPart
&& partition.Info.StartingOffset.QuadPart < minOffsetFound)
{
minOffsetFound = partition.Info.StartingOffset.QuadPart;
partitionBehindBoot = partition;
}
}
if (minOffsetFound != config.DrivePartition.Info.PartitionLength.QuadPart
&& partitionBehindBoot.Number == config.SystemPartition.Number)
{
activePartitionFound = true;
break;
}
}
throw ErrorException (wstring (GetString ("SYSTEM_PARTITION_NOT_ACTIVE"))
+ GetRemarksOnHiddenOS());
}
activePartitionFound = true;
break;
}
}
/* WARNING: Note that the partition number at the end of a device path (\Device\HarddiskY\PartitionX) must
NOT be used to find the first partition physically located behind the active one. The reason is that the
user may have deleted and created partitions during this session and e.g. the second partition could have
a higer number than the third one. */
// Find the first partition physically located behind the active partition
if (activePartitionFound)
{
int64 minOffsetFound = config.DrivePartition.Info.PartitionLength.QuadPart;
foreach (const Partition &partition, config.Partitions)
{
if (partition.Info.StartingOffset.QuadPart > config.SystemPartition.Info.StartingOffset.QuadPart
&& partition.Info.StartingOffset.QuadPart < minOffsetFound)
{
minOffsetFound = partition.Info.StartingOffset.QuadPart;
candidatePartition = partition;
candidateForHiddenOSFound = true;
}
}
if (!candidateForHiddenOSFound)
{
throw ErrorException (wstring (GetString ("NO_PARTITION_FOLLOWS_BOOT_PARTITION"))
+ GetRemarksOnHiddenOS());
}
if (config.SystemPartition.Info.PartitionLength.QuadPart > TC_MAX_FAT_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS)
{
if ((double) candidatePartition.Info.PartitionLength.QuadPart / config.SystemPartition.Info.PartitionLength.QuadPart < MIN_HIDDENOS_DECOY_PARTITION_SIZE_RATIO_NTFS)
{
throw ErrorException (wstring (GetString ("PARTITION_TOO_SMALL_FOR_HIDDEN_OS_NTFS"))
+ GetRemarksOnHiddenOS());
}
}
else if ((double) candidatePartition.Info.PartitionLength.QuadPart / config.SystemPartition.Info.PartitionLength.QuadPart < MIN_HIDDENOS_DECOY_PARTITION_SIZE_RATIO_FAT)
{
throw ErrorException (wstring (GetString ("PARTITION_TOO_SMALL_FOR_HIDDEN_OS"))
+ GetRemarksOnHiddenOS());
}
}
else
{
// No active partition on the system drive
throw ErrorException ("SYSTEM_PARTITION_NOT_ACTIVE");
}
HiddenOSCandidatePartition = candidatePartition;
return candidatePartition;
}
DWORD BootEncryption::GetDriverServiceStartType ()
{
DWORD startType;
throw_sys_if (!ReadLocalMachineRegistryDword ("SYSTEM\\CurrentControlSet\\Services\\truecrypt", "Start", &startType));
return startType;
}
wstring BootEncryption::GetRemarksOnHiddenOS ()
{
return (wstring (L"\n\n")
+ GetString ("TWO_SYSTEMS_IN_ONE_PARTITION_REMARK")
+ L"\n\n"
+ GetString ("FOR_MORE_INFO_ON_PARTITIONS"));
}
void BootEncryption::SetDriverServiceStartType (DWORD startType)
{
if (!IsAdmin() && IsUacSupported())
{
Elevator::SetDriverServiceStartType (startType);
return;
}
BOOL startOnBoot = (startType == SERVICE_BOOT_START);
SC_HANDLE serviceManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS);
throw_sys_if (!serviceManager);
finally_do_arg (SC_HANDLE, serviceManager, { CloseServiceHandle (finally_arg); });
SC_HANDLE service = OpenService (serviceManager, "truecrypt", SERVICE_CHANGE_CONFIG);
throw_sys_if (!service);
finally_do_arg (SC_HANDLE, service, { CloseServiceHandle (finally_arg); });
// Windows versions preceding Vista can be installed on FAT filesystem which does not
// support long filenames during boot. Convert the driver path to short form if required.
string driverPath;
if (startOnBoot && !IsOSAtLeast (WIN_VISTA))
{
char pathBuf[MAX_PATH];
char filesystem[128];
string path (GetWindowsDirectory());
path += "\\drivers\\truecrypt.sys";
if (GetVolumePathName (path.c_str(), pathBuf, sizeof (pathBuf))
&& GetVolumeInformation (pathBuf, NULL, 0, NULL, NULL, NULL, filesystem, sizeof(filesystem))
&& memcmp (filesystem, "FAT", 3) == 0)
{
throw_sys_if (GetShortPathName (path.c_str(), pathBuf, sizeof (pathBuf)) == 0);
// Convert absolute path to relative to the Windows directory
driverPath = pathBuf;
driverPath = driverPath.substr (driverPath.rfind ("\\", driverPath.rfind ("\\", driverPath.rfind ("\\") - 1) - 1) + 1);
}
}
throw_sys_if (!ChangeServiceConfig (service, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE,
startOnBoot ? SERVICE_ERROR_SEVERE : SERVICE_ERROR_NORMAL,
driverPath.empty() ? NULL : driverPath.c_str(),
startOnBoot ? "Filter" : NULL,
NULL, NULL, NULL, NULL, NULL));
// ChangeServiceConfig() rejects SERVICE_BOOT_START with ERROR_INVALID_PARAMETER
throw_sys_if (!WriteLocalMachineRegistryDword ("SYSTEM\\CurrentControlSet\\Services\\truecrypt", "Start", startType));
}
void BootEncryption::ProbeRealSystemDriveSize ()
{
if (RealSystemDriveSizeValid)
return;
GetSystemDriveConfiguration();
ProbeRealDriveSizeRequest request;
_snwprintf (request.DeviceName, array_capacity (request.DeviceName), L"%hs", DriveConfig.DrivePartition.DevicePath.c_str());
CallDriver (TC_IOCTL_PROBE_REAL_DRIVE_SIZE, &request, sizeof (request), &request, sizeof (request));
DriveConfig.DrivePartition.Info.PartitionLength = request.RealDriveSize;
RealSystemDriveSizeValid = true;
if (request.TimeOut)
throw TimeOut (SRC_POS);
}
void BootEncryption::InvalidateCachedSysDriveProperties ()
{
DriveConfigValid = false;
RealSystemDriveSizeValid = false;
}
PartitionList BootEncryption::GetDrivePartitions (int driveNumber)
{
PartitionList partList;
for (int partNumber = 0; partNumber < 64; ++partNumber)
{
stringstream partPath;
partPath << "\\Device\\Harddisk" << driveNumber << "\\Partition" << partNumber;
DISK_PARTITION_INFO_STRUCT diskPartInfo;
_snwprintf (diskPartInfo.deviceName, array_capacity (diskPartInfo.deviceName), L"%hs", partPath.str().c_str());
try
{
CallDriver (TC_IOCTL_GET_DRIVE_PARTITION_INFO, &diskPartInfo, sizeof (diskPartInfo), &diskPartInfo, sizeof (diskPartInfo));
}
catch (...)
{
continue;
}
Partition part;
part.DevicePath = partPath.str();
part.Number = partNumber;
part.Info = diskPartInfo.partInfo;
part.IsGPT = diskPartInfo.IsGPT;
// Mount point
wstringstream ws;
ws << partPath.str().c_str();
int driveNumber = GetDiskDeviceDriveLetter ((wchar_t *) ws.str().c_str());
if (driveNumber >= 0)
{
part.MountPoint += (char) (driveNumber + 'A');
part.MountPoint += ":";
}
// Volume ID
wchar_t volumePath[TC_MAX_PATH];
if (ResolveSymbolicLink ((wchar_t *) ws.str().c_str(), volumePath))
{
wchar_t volumeName[TC_MAX_PATH];
HANDLE fh = FindFirstVolumeW (volumeName, array_capacity (volumeName));
if (fh != INVALID_HANDLE_VALUE)
{
do
{
wstring volumeNameStr = volumeName;
wchar_t devicePath[TC_MAX_PATH];
if (QueryDosDeviceW (volumeNameStr.substr (4, volumeNameStr.size() - 1 - 4).c_str(), devicePath, array_capacity (devicePath)) != 0
&& wcscmp (volumePath, devicePath) == 0)
{
part.VolumeNameId = volumeName;
break;
}
} while (FindNextVolumeW (fh, volumeName, array_capacity (volumeName)));
FindVolumeClose (fh);
}
}
partList.push_back (part);
}
return partList;
}
DISK_GEOMETRY BootEncryption::GetDriveGeometry (int driveNumber)
{
stringstream devName;
devName << "\\Device\\Harddisk" << driveNumber << "\\Partition0";
DISK_GEOMETRY geometry;
throw_sys_if (!::GetDriveGeometry ((char *) devName.str().c_str(), &geometry));
return geometry;
}
string BootEncryption::GetWindowsDirectory ()
{
char buf[MAX_PATH];
throw_sys_if (GetSystemDirectory (buf, sizeof (buf)) == 0);
return string (buf);
}
string BootEncryption::GetTempPath ()
{
char tempPath[MAX_PATH];
DWORD tempLen = ::GetTempPath (sizeof (tempPath), tempPath);
if (tempLen == 0 || tempLen > sizeof (tempPath))
throw ParameterIncorrect (SRC_POS);
return string (tempPath);
}
uint16 BootEncryption::GetInstalledBootLoaderVersion ()
{
uint16 version;
CallDriver (TC_IOCTL_GET_BOOT_LOADER_VERSION, NULL, 0, &version, sizeof (version));
return version;
}
// Note that this does not require admin rights (it just requires the driver to be running)
bool BootEncryption::IsBootLoaderOnDrive (char *devicePath)
{
try
{
OPEN_TEST_STRUCT openTestStruct;
memset (&openTestStruct, 0, sizeof (openTestStruct));
DWORD dwResult;
strcpy ((char *) &openTestStruct.wszFileName[0], devicePath);
ToUNICODE ((char *) &openTestStruct.wszFileName[0]);
openTestStruct.bDetectTCBootLoader = TRUE;
return (DeviceIoControl (hDriver, TC_IOCTL_OPEN_TEST,
&openTestStruct, sizeof (OPEN_TEST_STRUCT),
&openTestStruct, sizeof (OPEN_TEST_STRUCT),
&dwResult, NULL) && openTestStruct.TCBootLoaderDetected);
}
catch (...)
{
return false;
}
}
BootEncryptionStatus BootEncryption::GetStatus ()
{
/* IMPORTANT: Do NOT add any potentially time-consuming operations to this function. */
BootEncryptionStatus status;
CallDriver (TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS, NULL, 0, &status, sizeof (status));
return status;
}
void BootEncryption::GetVolumeProperties (VOLUME_PROPERTIES_STRUCT *properties)
{
if (properties == NULL)
throw ParameterIncorrect (SRC_POS);
CallDriver (TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES, NULL, 0, properties, sizeof (*properties));
}
bool BootEncryption::IsHiddenSystemRunning ()
{
int hiddenSystemStatus;
CallDriver (TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING, nullptr, 0, &hiddenSystemStatus, sizeof (hiddenSystemStatus));
return hiddenSystemStatus != 0;
}
bool BootEncryption::SystemDriveContainsPartitionType (byte type)
{
Device device (GetSystemDriveConfiguration().DevicePath, true);
byte mbrBuf[TC_SECTOR_SIZE_BIOS];
device.SeekAt (0);
device.Read (mbrBuf, sizeof (mbrBuf));
MBR *mbr = reinterpret_cast <MBR *> (mbrBuf);
if (mbr->Signature != 0xaa55)
throw ParameterIncorrect (SRC_POS);
for (size_t i = 0; i < array_capacity (mbr->Partitions); ++i)
{
if (mbr->Partitions[i].Type == type)
return true;
}
return false;
}
bool BootEncryption::SystemDriveContainsExtendedPartition ()
{
return SystemDriveContainsPartitionType (PARTITION_EXTENDED) || SystemDriveContainsPartitionType (PARTITION_XINT13_EXTENDED);
}
bool BootEncryption::SystemDriveContainsNonStandardPartitions ()
{
for (int partitionType = 1; partitionType <= 0xff; ++partitionType)
{
switch (partitionType)
{
case PARTITION_FAT_12:
case PARTITION_FAT_16:
case PARTITION_EXTENDED:
case PARTITION_HUGE:
case PARTITION_IFS:
case PARTITION_FAT32:
case PARTITION_FAT32_XINT13:
case PARTITION_XINT13:
case PARTITION_XINT13_EXTENDED:
continue;
}
if (SystemDriveContainsPartitionType ((byte) partitionType))
return true;
}
return false;
}
bool BootEncryption::SystemDriveIsDynamic ()
{
GetSystemDriveConfigurationRequest request;
_snwprintf (request.DevicePath, array_capacity (request.DevicePath), L"%hs", GetSystemDriveConfiguration().DeviceKernelPath.c_str());
CallDriver (TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG, &request, sizeof (request), &request, sizeof (request));
return request.DriveIsDynamic ? true : false;
}
SystemDriveConfiguration BootEncryption::GetSystemDriveConfiguration ()
{
if (DriveConfigValid)
return DriveConfig;
SystemDriveConfiguration config;
string winDir = GetWindowsDirectory();
// Scan all drives
for (int driveNumber = 0; driveNumber < 32; ++driveNumber)
{
bool windowsFound = false;
bool activePartitionFound = false;
config.ExtraBootPartitionPresent = false;
config.SystemLoaderPresent = false;
PartitionList partitions = GetDrivePartitions (driveNumber);
foreach (const Partition &part, partitions)
{
if (!part.MountPoint.empty()
&& (_access ((part.MountPoint + "\\bootmgr").c_str(), 0) == 0 || _access ((part.MountPoint + "\\ntldr").c_str(), 0) == 0))
{
config.SystemLoaderPresent = true;
}
else if (!part.VolumeNameId.empty()
&& (_waccess ((part.VolumeNameId + L"\\bootmgr").c_str(), 0) == 0 || _waccess ((part.VolumeNameId + L"\\ntldr").c_str(), 0) == 0))
{
config.SystemLoaderPresent = true;
}
if (!windowsFound && !part.MountPoint.empty() && ToUpperCase (winDir).find (ToUpperCase (part.MountPoint)) == 0)
{
config.SystemPartition = part;
windowsFound = true;
}
if (!activePartitionFound && part.Info.BootIndicator)
{
activePartitionFound = true;
if (part.Info.PartitionLength.QuadPart > 0 && part.Info.PartitionLength.QuadPart <= TC_MAX_EXTRA_BOOT_PARTITION_SIZE)
config.ExtraBootPartitionPresent = true;
}
}
if (windowsFound)
{
config.DriveNumber = driveNumber;
stringstream ss;
ss << "PhysicalDrive" << driveNumber;
config.DevicePath = ss.str();
stringstream kernelPath;
kernelPath << "\\Device\\Harddisk" << driveNumber << "\\Partition0";
config.DeviceKernelPath = kernelPath.str();
config.DrivePartition = partitions.front();
partitions.pop_front();
config.Partitions = partitions;
config.InitialUnallocatedSpace = 0x7fffFFFFffffFFFFull;
config.TotalUnallocatedSpace = config.DrivePartition.Info.PartitionLength.QuadPart;
foreach (const Partition &part, config.Partitions)
{
if (part.Info.StartingOffset.QuadPart < config.InitialUnallocatedSpace)
config.InitialUnallocatedSpace = part.Info.StartingOffset.QuadPart;
config.TotalUnallocatedSpace -= part.Info.PartitionLength.QuadPart;
}
DriveConfig = config;
DriveConfigValid = true;
return DriveConfig;
}
}
throw ParameterIncorrect (SRC_POS);
}
bool BootEncryption::SystemPartitionCoversWholeDrive ()
{
SystemDriveConfiguration config = GetSystemDriveConfiguration();
if (IsOSAtLeast (WIN_7)
&& config.Partitions.size() == 2
&& config.ExtraBootPartitionPresent
&& config.DrivePartition.Info.PartitionLength.QuadPart - config.SystemPartition.Info.PartitionLength.QuadPart < 164 * BYTES_PER_MB)
{
return true;
}
return config.Partitions.size() == 1
&& config.DrivePartition.Info.PartitionLength.QuadPart - config.SystemPartition.Info.PartitionLength.QuadPart < 64 * BYTES_PER_MB;
}
uint32 BootEncryption::GetChecksum (byte *data, size_t size)
{
uint32 sum = 0;
while (size-- > 0)
{
sum += *data++;
sum = _rotl (sum, 1);
}
return sum;
}
void BootEncryption::CreateBootLoaderInMemory (byte *buffer, size_t bufferSize, bool rescueDisk, bool hiddenOSCreation)
{
if (bufferSize < TC_BOOT_LOADER_AREA_SIZE - TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE)
throw ParameterIncorrect (SRC_POS);
ZeroMemory (buffer, bufferSize);
int ea = 0;
if (GetStatus().DriveMounted)
{
try
{
GetBootEncryptionAlgorithmNameRequest request;
CallDriver (TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME, NULL, 0, &request, sizeof (request));
if (_stricmp (request.BootEncryptionAlgorithmName, "AES") == 0)
ea = AES;
else if (_stricmp (request.BootEncryptionAlgorithmName, "Serpent") == 0)
ea = SERPENT;
else if (_stricmp (request.BootEncryptionAlgorithmName, "Twofish") == 0)
ea = TWOFISH;
}
catch (...)
{
try
{
VOLUME_PROPERTIES_STRUCT properties;
GetVolumeProperties (&properties);
ea = properties.ea;
}
catch (...) { }
}
}
else
{
if (SelectedEncryptionAlgorithmId == 0)
throw ParameterIncorrect (SRC_POS);
ea = SelectedEncryptionAlgorithmId;
}