bootencryption.cpp
来自「外国开源的硬盘加密软件」· C++ 代码 · 共 2,128 行 · 第 1/5 页
CPP
2,128 行
if (!candidateForHiddenOSFound)
{
throw ErrorException (wstring (GetString ("NO_PARTITION_FOLLOWS_BOOT_PARTITION"))
+ GetRemarksOnHiddenOS());
}
if (config.SystemPartition.Info.PartitionLength.QuadPart > TC_MAX_FAT_FS_SIZE)
{
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 ("WINDOWS_NOT_ON_BOOT_DRIVE_ERROR");
}
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);
if (Is64BitOs())
driverPath = "SysWOW64" + driverPath.substr (driverPath.find ("\\"));
}
}
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[SECTOR_SIZE];
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::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;
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 (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();
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);
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?