bootencryption.cpp
来自「外国开源的硬盘加密软件」· C++ 代码 · 共 2,128 行 · 第 1/5 页
CPP
2,128 行
#ifndef SETUP
void BootEncryption::CreateRescueIsoImage (bool initialSetup, const string &isoImagePath)
{
BootEncryptionStatus encStatus = GetStatus();
if (encStatus.SetupInProgress)
throw ParameterIncorrect (SRC_POS);
Buffer imageBuf (RescueIsoImageSize);
byte *image = imageBuf.Ptr();
memset (image, 0, RescueIsoImageSize);
// Primary volume descriptor
strcpy ((char *)image + 0x8000, "\001CD001\001");
strcpy ((char *)image + 0x7fff + 41, "TrueCrypt Rescue Disk ");
*(uint32 *) (image + 0x7fff + 81) = RescueIsoImageSize / 2048;
*(uint32 *) (image + 0x7fff + 85) = BE32 (RescueIsoImageSize / 2048);
image[0x7fff + 121] = 1;
image[0x7fff + 124] = 1;
image[0x7fff + 125] = 1;
image[0x7fff + 128] = 1;
image[0x7fff + 130] = 8;
image[0x7fff + 131] = 8;
image[0x7fff + 133] = 10;
image[0x7fff + 140] = 10;
image[0x7fff + 141] = 0x14;
image[0x7fff + 157] = 0x22;
image[0x7fff + 159] = 0x18;
// Boot record volume descriptor
strcpy ((char *)image + 0x8801, "CD001\001EL TORITO SPECIFICATION");
image[0x8800 + 0x47] = 0x19;
// Volume descriptor set terminator
strcpy ((char *)image + 0x9000, "\377CD001\001");
// Path table
image[0xA000 + 0] = 1;
image[0xA000 + 2] = 0x18;
image[0xA000 + 6] = 1;
// Root directory
image[0xc000 + 0] = 0x22;
image[0xc000 + 2] = 0x18;
image[0xc000 + 9] = 0x18;
image[0xc000 + 11] = 0x08;
image[0xc000 + 16] = 0x08;
image[0xc000 + 25] = 0x02;
image[0xc000 + 28] = 0x01;
image[0xc000 + 31] = 0x01;
image[0xc000 + 32] = 0x01;
image[0xc000 + 34] = 0x22;
image[0xc000 + 36] = 0x18;
image[0xc000 + 43] = 0x18;
image[0xc000 + 45] = 0x08;
image[0xc000 + 50] = 0x08;
image[0xc000 + 59] = 0x02;
image[0xc000 + 62] = 0x01;
*(uint32 *) (image + 0xc000 + 65) = 0x010101;
// Validation entry
image[0xc800] = 1;
int offset = 0xc800 + 0x1c;
image[offset++] = 0xaa;
image[offset++] = 0x55;
image[offset++] = 0x55;
image[offset] = 0xaa;
// Initial entry
offset = 0xc820;
image[offset++] = 0x88;
image[offset++] = 2;
image[0xc820 + 6] = 1;
image[0xc820 + 8] = TC_CD_BOOT_LOADER_SECTOR;
// TrueCrypt Boot Loader
CreateBootLoaderInMemory (image + TC_CD_BOOTSECTOR_OFFSET, TC_BOOT_LOADER_AREA_SIZE, true);
// Volume header
if (initialSetup)
{
if (!RescueVolumeHeaderValid)
throw ParameterIncorrect (SRC_POS);
memcpy (image + TC_CD_BOOTSECTOR_OFFSET + TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET, RescueVolumeHeader, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE);
}
else
{
Device bootDevice (GetSystemDriveConfiguration().DevicePath, true);
bootDevice.SeekAt (TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET);
bootDevice.Read (image + TC_CD_BOOTSECTOR_OFFSET + TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE);
}
// Original system loader
try
{
File sysBakFile (GetSystemLoaderBackupPath(), true);
sysBakFile.Read (image + TC_CD_BOOTSECTOR_OFFSET + TC_ORIG_BOOT_LOADER_BACKUP_SECTOR_OFFSET, TC_BOOT_LOADER_AREA_SIZE);
image[TC_CD_BOOTSECTOR_OFFSET + TC_BOOT_SECTOR_CONFIG_OFFSET] |= TC_BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER;
}
catch (Exception &e)
{
e.Show (ParentWindow);
Warning ("SYS_LOADER_UNAVAILABLE_FOR_RESCUE_DISK");
}
// Boot loader backup
CreateBootLoaderInMemory (image + TC_CD_BOOTSECTOR_OFFSET + TC_BOOT_LOADER_BACKUP_RESCUE_DISK_SECTOR_OFFSET, TC_BOOT_LOADER_AREA_SIZE, false);
RescueIsoImage = new byte[RescueIsoImageSize];
if (!RescueIsoImage)
throw bad_alloc();
memcpy (RescueIsoImage, image, RescueIsoImageSize);
if (!isoImagePath.empty())
{
File isoFile (isoImagePath, false, true);
isoFile.Write (image, RescueIsoImageSize);
}
}
#endif
bool BootEncryption::VerifyRescueDisk ()
{
if (!RescueIsoImage)
throw ParameterIncorrect (SRC_POS);
for (char drive = 'Z'; drive >= 'D'; --drive)
{
try
{
string path = "X:";
path[0] = drive;
Device driveDevice (path, true);
size_t verifiedSectorCount = (TC_CD_BOOTSECTOR_OFFSET + TC_ORIG_BOOT_LOADER_BACKUP_SECTOR_OFFSET + TC_BOOT_LOADER_AREA_SIZE) / 2048;
Buffer buffer ((verifiedSectorCount + 1) * 2048);
DWORD bytesRead = driveDevice.Read (buffer.Ptr(), buffer.Size());
if (bytesRead != buffer.Size())
continue;
if (memcmp (buffer.Ptr(), RescueIsoImage, buffer.Size()) == 0)
return true;
}
catch (...) { }
}
return false;
}
#ifndef SETUP
void BootEncryption::CreateVolumeHeader (uint64 volumeSize, uint64 encryptedAreaStart, Password *password, int ea, int mode, int pkcs5)
{
PCRYPTO_INFO cryptoInfo = NULL;
if (!IsRandomNumberGeneratorStarted())
throw ParameterIncorrect (SRC_POS);
throw_sys_if (CreateVolumeHeaderInMemory (TRUE, (char *) VolumeHeader, ea, mode, password, pkcs5, NULL, &cryptoInfo,
volumeSize, 0, encryptedAreaStart, 0, TC_SYSENC_KEYSCOPE_MIN_REQ_PROG_VERSION, TC_HEADER_FLAG_ENCRYPTED_SYSTEM, FALSE) != 0);
finally_do_arg (PCRYPTO_INFO*, &cryptoInfo, { crypto_close (*finally_arg); });
// Initial rescue disk assumes encryption of the drive has been completed (EncryptedAreaLength == volumeSize)
memcpy (RescueVolumeHeader, VolumeHeader, sizeof (RescueVolumeHeader));
ReadVolumeHeader (TRUE, (char *) RescueVolumeHeader, password, NULL, cryptoInfo);
DecryptBuffer (RescueVolumeHeader + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo);
if (GetHeaderField32 (RescueVolumeHeader, TC_HEADER_OFFSET_MAGIC) != 0x54525545)
throw ParameterIncorrect (SRC_POS);
byte *fieldPos = RescueVolumeHeader + TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH;
mputInt64 (fieldPos, volumeSize);
// CRC of the header fields
uint32 crc = GetCrc32 (RescueVolumeHeader + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC);
fieldPos = RescueVolumeHeader + TC_HEADER_OFFSET_HEADER_CRC;
mputLong (fieldPos, crc);
EncryptBuffer (RescueVolumeHeader + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo);
VolumeHeaderValid = true;
RescueVolumeHeaderValid = true;
}
void BootEncryption::InstallVolumeHeader ()
{
if (!VolumeHeaderValid)
throw ParameterIncorrect (SRC_POS);
Device device (GetSystemDriveConfiguration().DevicePath);
device.SeekAt (TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET);
device.Write ((byte *) VolumeHeader, sizeof (VolumeHeader));
}
// For synchronous operations use AbortSetupWait()
void BootEncryption::AbortSetup ()
{
CallDriver (TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP);
}
// For asynchronous operations use AbortSetup()
void BootEncryption::AbortSetupWait ()
{
CallDriver (TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP);
BootEncryptionStatus encStatus = GetStatus();
while (encStatus.SetupInProgress)
{
Sleep (TC_ABORT_TRANSFORM_WAIT_INTERVAL);
encStatus = GetStatus();
}
}
void BootEncryption::BackupSystemLoader ()
{
Device device (GetSystemDriveConfiguration().DevicePath, true);
byte bootLoaderBuf[TC_BOOT_LOADER_AREA_SECTOR_COUNT * SECTOR_SIZE];
device.SeekAt (0);
device.Read (bootLoaderBuf, sizeof (bootLoaderBuf));
// Prevent TrueCrypt loader from being backed up
for (size_t i = 0; i < sizeof (bootLoaderBuf) - strlen (TC_APP_NAME); ++i)
{
if (memcmp (bootLoaderBuf + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0)
{
if (AskWarnNoYes ("TC_BOOT_LOADER_ALREADY_INSTALLED") == IDNO)
throw UserAbort (SRC_POS);
return;
}
}
File backupFile (GetSystemLoaderBackupPath(), false, true);
backupFile.Write (bootLoaderBuf, sizeof (bootLoaderBuf));
}
void BootEncryption::RestoreSystemLoader ()
{
byte bootLoaderBuf[TC_BOOT_LOADER_AREA_SECTOR_COUNT * SECTOR_SIZE];
File backupFile (GetSystemLoaderBackupPath(), true);
if (backupFile.Read (bootLoaderBuf, sizeof (bootLoaderBuf)) != sizeof (bootLoaderBuf))
throw ParameterIncorrect (SRC_POS);
Device device (GetSystemDriveConfiguration().DevicePath);
// Preserve current partition table
byte mbr[SECTOR_SIZE];
device.SeekAt (0);
device.Read (mbr, sizeof (mbr));
memcpy (bootLoaderBuf + TC_MAX_MBR_BOOT_CODE_SIZE, mbr + TC_MAX_MBR_BOOT_CODE_SIZE, sizeof (mbr) - TC_MAX_MBR_BOOT_CODE_SIZE);
device.SeekAt (0);
device.Write (bootLoaderBuf, sizeof (bootLoaderBuf));
}
#endif // SETUP
void BootEncryption::RegisterDeviceClassFilter (bool registerFilter, const GUID *deviceClassGuid)
{
HKEY classRegKey = SetupDiOpenClassRegKey (deviceClassGuid, KEY_READ | KEY_WRITE);
throw_sys_if (classRegKey == INVALID_HANDLE_VALUE);
finally_do_arg (HKEY, classRegKey, { RegCloseKey (finally_arg); });
if (registerFilter)
{
// Register class filter below all other filters in the stack
size_t strSize = strlen ("truecrypt") + 1;
byte regKeyBuf[65536];
DWORD size = sizeof (regKeyBuf) - strSize;
// SetupInstallFromInfSection() does not support prepending of values so we have to modify the registry directly
strncpy ((char *) regKeyBuf, "truecrypt", sizeof (regKeyBuf));
if (RegQueryValueEx (classRegKey, "UpperFilters", NULL, NULL, regKeyBuf + strSize, &size) != ERROR_SUCCESS)
size = 1;
throw_sys_if (RegSetValueEx (classRegKey, "UpperFilters", 0, REG_MULTI_SZ, regKeyBuf, strSize + size) != ERROR_SUCCESS);
}
else
{
// Unregister a class filter
string infFileName = GetTempPath() + "\\truecrypt_device_filter.inf";
File infFile (infFileName, false, true);
finally_do_arg (string, infFileName, { DeleteFile (finally_arg.c_str()); });
string infTxt = "[truecrypt]\r\n"
"DelReg=truecrypt_reg\r\n\r\n"
"[truecrypt_reg]\r\n"
"HKR,,\"UpperFilters\",0x00018002,\"truecrypt\"\r\n";
infFile.Write ((byte *) infTxt.c_str(), infTxt.size());
infFile.Close();
HINF hInf = SetupOpenInfFile (infFileName.c_str(), NULL, INF_STYLE_OLDNT | INF_STYLE_WIN4, NULL);
throw_sys_if (hInf == INVALID_HANDLE_VALUE);
finally_do_arg (HINF, hInf, { SetupCloseInfFile (finally_arg); });
throw_sys_if (!SetupInstallFromInfSection (ParentWindow, hInf, "truecrypt", SPINST_REGISTRY, classRegKey, NULL, 0, NULL, NULL, NULL, NULL));
}
}
void BootEncryption::RegisterFilterDriver (bool registerDriver, bool volumeClass)
{
if (!IsAdmin() && IsUacSupported())
{
Elevator::RegisterFilterDriver (registerDriver, volumeClass);
return;
}
if (volumeClass)
{
RegisterDeviceClassFilter (registerDriver, &GUID_DEVCLASS_VOLUME);
RegisterDeviceClassFilter (registerDriver, &GUID_DEVCLASS_FLOPPYDISK);
}
else
{
RegisterDeviceClassFilter (registerDriver, &GUID_DEVCLASS_DISKDRIVE);
}
}
#ifndef SETUP
void BootEncryption::CheckRequirements ()
{
if (nCurrentOS == WIN_2000)
throw ErrorException ("SYS_ENCRYPTION_UNSUPPORTED_ON_CURRENT_OS");
if (CurrentOSMajor == 6 && CurrentOSMinor == 0 && CurrentOSServicePack < 1)
throw ErrorException ("SYS_ENCRYPTION_UNSUPPORTED_ON_VISTA_SP0");
if (IsNonInstallMode())
throw ErrorException ("FEATURE_REQUIRES_INSTALLATION");
SystemDriveConfiguration config = GetSystemDriveConfiguration ();
if (config.SystemPartition.IsGPT)
throw ErrorException ("GPT_BOOT_DRIVE_UNSUPPORTED");
if (SystemDriveIsDynamic())
throw ErrorException ("SYSENC_UNSUPPORTED_FOR_DYNAMIC_DISK");
if (config.InitialUnallocatedSpace < TC_BOOT_LOADER_AREA_SIZE)
throw ErrorException ("NO_SPACE_FOR_BOOT_LOADER");
DISK_GEOMETRY geometry = GetDriveGeometry (config.DriveNumber);
if (geometry.BytesPerSector != SECTOR_SIZE)
throw ErrorException ("LARGE_SECTOR_UNSUPPORTED");
if (!config.SystemLoaderPresent)
throw ErrorException ("WINDOWS_NOT_ON_BOOT_DRIVE_ERROR");
if (!config.SystemPartition.IsGPT)
{
// Determine whether there is an Active partition on the system drive
bool activePartitionFound = false;
foreach (const Partition &partition, config.Partitions)
{
if (partition.Info.BootIndicator)
{
activePartitionFound = true;
break;
}
}
if (!activePartitionFound)
throw ErrorException ("WINDOWS_NOT_ON_BOOT_DRIVE_ERROR");
}
}
void BootEncryption::CheckRequirementsHiddenOS ()
{
// It is assumed that CheckRequirements() had been called (so we don't check e.g. whether it's GPT).
// The user may have modified/added/deleted partitions since the partition table was last scanned.
InvalidateCachedSysDriveProperties ();
GetPartitionForHiddenOS ();
}
void BootEncryption::InitialSecurityChecksForHiddenOS ()
{
char windowsDrive = toupper (GetWindowsDirectory()[0]);
// Paging files
bool pagingFilesOk = !IsPagingFileActive (TRUE);
char pagingFileRegData[65536];
DWORD pagingFileRegDataSize = sizeof (pagingFileRegData);
if (ReadLocalMachineRegistryMultiString ("System\\CurrentControlSet\\Control\\Session Manager\\Memory Management", "PagingFiles", pagingFileRegData, &pagingFileRegDataSize)
&& pagingFileRegDataSize > 4)
{
for (size_t i = 1; i < pagingFileRegDataSize - 2; ++i)
{
if (memcmp (pagingFileRegData + i, ":\\", 2) == 0 && toupper (pagingFileRegData[i - 1]) != windowsDrive)
{
pagingFilesOk = false;
break;
}
}
}
if (!pagingFilesOk)
{
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?