⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bootmain.cpp

📁 使用visual studio 2005 开发的开源文件、磁盘加密软件。这是6.1a版。加密自己资料的好工具。也是学习的优秀范本。结成了众多加密算法。
💻 CPP
📖 第 1 页 / 共 2 页
字号:
/*
 Copyright (c) 2008 TrueCrypt Foundation. All rights reserved.

 Governed by the TrueCrypt License 2.6 the full text of which is contained
 in the file License.txt included in TrueCrypt binary and source code
 distribution packages.
*/

#include "Crc.h"
#include "Crypto.h"
#include "Password.h"
#include "Volumes.h"

#include "Platform.h"
#include "Bios.h"
#include "BootConfig.h"
#include "BootMain.h"
#include "BootDefs.h"
#include "BootCommon.h"
#include "BootConsoleIo.h"
#include "BootDebug.h"
#include "BootDiskIo.h"
#include "BootEncryptedIo.h"
#include "BootMemory.h"
#include "BootStrings.h"
#include "IntFilter.h"


static void InitScreen ()
{
	ClearScreen();

	Print (
#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE
		" TrueCrypt Boot Loader "
#else
		" TrueCrypt Rescue Disk "
#endif
		VERSION_STRING "             Copyright (C) 2008 TrueCrypt Foundation\r\n");

	PrintRepeatedChar ('\xDC', TC_BIOS_MAX_CHARS_PER_LINE);

#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE
	if (CustomUserMessage[0])
	{
		PrintEndl();
		Print (CustomUserMessage);
	}
#endif

	PrintEndl (2);
}


static void PrintMainMenu ()
{
	if (PreventBootMenu)
		return;

	Print ("    Keyboard Controls:\r\n");
	Print ("    [Esc]  ");

#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE

	Print ((BootSectorFlags & TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE) != TC_HIDDEN_OS_CREATION_PHASE_NONE
		? "Boot Non-Hidden System (Boot Manager)"
		: "Skip Authentication (Boot Manager)");
	
#else // TC_WINDOWS_BOOT_RESCUE_DISK_MODE

	Print ("Skip Authentication (Boot Manager)");
	Print ("\r\n    [F8]   "); Print ("Repair Options");

#endif // TC_WINDOWS_BOOT_RESCUE_DISK_MODE

	PrintEndl (3);
}


static bool IsMenuKey (byte scanCode)
{
#ifdef TC_WINDOWS_BOOT_RESCUE_DISK_MODE
	return scanCode == TC_MENU_KEY_REPAIR;
#else
	return false;
#endif
}


static bool AskYesNo (const char *message)
{
	Print (message);
	Print ("? (y/n): ");
	while (true)
	{
		switch (GetKeyboardChar())
		{
		case 'y':
		case 'Y':
		case 'z':
		case 'Z':
			Print ("y\r\n");
			return true;

		case 'n':
		case 'N':
			Print ("n\r\n");
			return false;

		default:
			Beep();
		}
	}
}


static int AskSelection (const char *options[], size_t optionCount)
{
	for (int i = 0; i < optionCount; ++i)
	{
		Print ("["); Print (i + 1); Print ("]    ");
		Print (options[i]);
		PrintEndl();
	}
	Print ("[Esc]  Cancel\r\n\r\n");

	Print ("To select, press 1-9: ");

	char str;

	while (true)
	{
		if (GetString (&str, 1) == 0)
			return 0;

		if (str >= '1' && str <= optionCount + '0')
			return str - '0';

		Beep();
		PrintBackspace();
	}
}


static byte AskPassword (Password &password)
{
	size_t pos = 0;
	byte scanCode;
	byte asciiCode;

	Print ("Enter password");
	Print (PreventNormalSystemBoot ? " for hidden system:\r\n" : ": ");

	while (true)
	{
		asciiCode = GetKeyboardChar (&scanCode);

		switch (scanCode)
		{
		case TC_BIOS_KEY_ENTER:
			ClearBiosKeystrokeBuffer();
			PrintEndl();

			password.Length = pos;
			return scanCode;

		case TC_BIOS_KEY_BACKSPACE:
			if (pos > 0)
			{
				if (pos < MAX_PASSWORD)
					PrintBackspace();
				else
					PrintCharAtCursor (' ');

				--pos;
			}
			continue;

		default:
			if (scanCode == TC_BIOS_KEY_ESC || IsMenuKey (scanCode))
			{
				burn (password.Text, sizeof (password.Text));
				ClearBiosKeystrokeBuffer();

				PrintEndl();
				return scanCode;
			}
		}

		if (!IsPrintable (asciiCode) || pos == MAX_PASSWORD)
		{
			Beep();
			continue;
		}

		password.Text[pos++] = asciiCode;
		if (pos < MAX_PASSWORD)
			PrintChar ('*');
		else
			PrintCharAtCursor ('*');
	}
}


static void ExecuteBootSector (byte drive, byte *sectorBuffer)
{
	Print ("Booting...\r\n");
	CopyMemory (sectorBuffer, 0x0000, 0x7c00, TC_LB_SIZE);

	BootStarted = true;

	uint32 addr = 0x7c00;
	__asm
	{
		cli
		mov dl, drive
		xor ax, ax
		mov ds, ax
		mov es, ax
		mov ss, ax
		mov sp, 0xffff
		sti
		jmp cs:addr
	}
}


static bool OpenVolume (byte drive, Password &password, CRYPTO_INFO **cryptoInfo, uint32 *headerSaltCrc32, bool skipNormal, bool skipHidden)
{
	int volumeType;
	bool hiddenVolume;
	uint64 headerSec;
	
	AcquireSectorBuffer();

	for (volumeType = 1; volumeType <= 2; ++volumeType)
	{
		hiddenVolume = (volumeType == 2);

		if (hiddenVolume)
		{
			if (skipHidden || PartitionFollowingActive.Drive != drive || PartitionFollowingActive.SectorCount <= ActivePartition.SectorCount)
				continue;

			headerSec = PartitionFollowingActive.StartSector + TC_HIDDEN_VOLUME_HEADER_OFFSET / TC_LB_SIZE;
		}
		else
		{
			if (skipNormal)
				continue;

			headerSec.HighPart = 0;
			headerSec.LowPart = TC_BOOT_VOLUME_HEADER_SECTOR;
		}

		if (ReadSectors (SectorBuffer, drive, headerSec, 1) != BiosResultSuccess)
			continue;

		if (ReadVolumeHeader (!hiddenVolume, (char *) SectorBuffer, &password, cryptoInfo, nullptr) == ERR_SUCCESS)
		{
			// Prevent opening a non-system hidden volume
			if (hiddenVolume && !((*cryptoInfo)->HeaderFlags & TC_HEADER_FLAG_ENCRYPTED_SYSTEM))
			{
				crypto_close (*cryptoInfo);
				continue;
			}

			if (headerSaltCrc32)
				*headerSaltCrc32 = GetCrc32 (SectorBuffer, PKCS5_SALT_SIZE);

			break;
		}
	}

	ReleaseSectorBuffer();
	return volumeType != 3;
}


static bool CheckMemoryRequirements ()
{
	uint16 codeSeg;
	__asm mov codeSeg, cs
	if (codeSeg == TC_BOOT_LOADER_LOWMEM_SEGMENT)
	{
		PrintError ("BIOS reserved too much memory: ", true, false);

		uint16 memFree;
		__asm
		{
			push es
			xor ax, ax
			mov es, ax
			mov ax, es:[0x413]
			mov memFree, ax
			pop es
		}

		Print (memFree);

		Print ("\r\nThis is not a bug in TrueCrypt.\r\n"
			   "- Disable unneeded components (RAID, AHCI) in BIOS setup menu\r\n"
			   "  (invoked by pressing Del or F2 after turning on your computer)\r\n");
#ifndef TC_WINDOWS_BOOT_AES
		Print ("- Use the AES encryption algorithm to reduce memory requirements\r\n");
#endif
#ifdef TC_WINDOWS_BOOT_RESCUE_DISK_MODE
		Print ("- Boot from HDD\r\n");
#endif
		Print (TC_BOOT_STR_UPGRADE_BIOS);

		return false;
	}

	return true;
}


static bool MountVolume (byte drive, byte &exitKey, bool skipNormal, bool skipHidden)
{
	BootArguments *bootArguments = (BootArguments *) TC_BOOT_LOADER_ARGS_OFFSET;
	int incorrectPasswordCount = 0;

	EraseMemory (bootArguments, sizeof (*bootArguments));

	// Open volume header
	while (true)
	{
		exitKey = AskPassword (bootArguments->BootPassword);

		if (exitKey != TC_BIOS_KEY_ENTER)
			return false;

		if (OpenVolume (BootDrive, bootArguments->BootPassword, &BootCryptoInfo, &bootArguments->HeaderSaltCrc32, skipNormal, skipHidden))
			break;

		if (GetShiftFlags() & TC_BIOS_SHIFTMASK_CAPSLOCK)
			Print ("Warning: Caps Lock is on.\r\n");

		Print ("Incorrect password.\r\n\r\n");

		if (++incorrectPasswordCount == 4)
		{
#ifdef TC_WINDOWS_BOOT_RESCUE_DISK_MODE
			Print ("The key data may be damaged. Use 'Repair Options' > 'Restore key data'.\r\n\r\n");
#else
			Print ("If you are sure the password is correct, the key data may be damaged. Boot your\r\n"
				   "TrueCrypt Rescue Disk and select 'Repair Options' > 'Restore key data'.\r\n\r\n");
#endif
		}
	}

	// Setup boot arguments
	bootArguments->BootLoaderVersion = VERSION_NUM;
	bootArguments->CryptoInfoOffset = (uint16) BootCryptoInfo;
	bootArguments->CryptoInfoLength = sizeof (*BootCryptoInfo);
	
	if (BootCryptoInfo->hiddenVolume)
		bootArguments->HiddenSystemPartitionStart = PartitionFollowingActive.StartSector << TC_LB_SIZE_BIT_SHIFT_DIVISOR;

	TC_SET_BOOT_ARGUMENTS_SIGNATURE	(bootArguments->Signature);

	// Setup virtual encrypted partition
	if (BootCryptoInfo->EncryptedAreaLength.HighPart != 0 || BootCryptoInfo->EncryptedAreaLength.LowPart != 0)
	{
		EncryptedVirtualPartition.Drive = BootDrive;

		EncryptedVirtualPartition.StartSector = BootCryptoInfo->EncryptedAreaStart >> TC_LB_SIZE_BIT_SHIFT_DIVISOR;
		
		HiddenVolumeStartUnitNo = EncryptedVirtualPartition.StartSector;
		HiddenVolumeStartSector = PartitionFollowingActive.StartSector;
		HiddenVolumeStartSector += EncryptedVirtualPartition.StartSector;

		EncryptedVirtualPartition.SectorCount = BootCryptoInfo->EncryptedAreaLength >> TC_LB_SIZE_BIT_SHIFT_DIVISOR;

		EncryptedVirtualPartition.EndSector = EncryptedVirtualPartition.SectorCount - 1;
		EncryptedVirtualPartition.EndSector += EncryptedVirtualPartition.StartSector;
	}
	else
	{
		// Drive not encrypted
		EncryptedVirtualPartition.Drive = TC_INVALID_BIOS_DRIVE;
	}

	return true;
}


static byte BootEncryptedDrive ()
{
	BootArguments *bootArguments = (BootArguments *) TC_BOOT_LOADER_ARGS_OFFSET;
	byte exitKey;
	BootCryptoInfo = NULL;

	if (!GetActiveAndFollowingPartition (BootDrive))
		goto err;

	if (!MountVolume (BootDrive, exitKey, PreventNormalSystemBoot, false))
		return exitKey;
	
	if (!CheckMemoryRequirements ())
		goto err;

	if (BootCryptoInfo->hiddenVolume)
	{
		EncryptedVirtualPartition = ActivePartition;
		bootArguments->DecoySystemPartitionStart = ActivePartition.StartSector << TC_LB_SIZE_BIT_SHIFT_DIVISOR;
	}

	if (!InstallInterruptFilters())
		goto err;

	bootArguments->BootArgumentsCrc32 = GetCrc32 ((byte *) bootArguments, (byte *) &bootArguments->BootArgumentsCrc32 - (byte *) bootArguments);

	while (true)
	{
		// Execute boot sector of the active partition
		if (ReadSectors (SectorBuffer, ActivePartition.Drive, ActivePartition.StartSector, 1) == BiosResultSuccess)
		{
			if (*(uint16 *) (SectorBuffer + 510) != 0xaa55)
			{
				PrintError (TC_BOOT_STR_NO_BOOT_PARTITION);
				GetKeyboardChar();
			}

			ExecuteBootSector (ActivePartition.Drive, SectorBuffer);
		}

		GetKeyboardChar();
	}

err:
	if (BootCryptoInfo)
	{
		crypto_close (BootCryptoInfo);
		BootCryptoInfo = NULL;
	}

	EncryptedVirtualPartition.Drive = TC_INVALID_BIOS_DRIVE;
	EraseMemory ((void *) TC_BOOT_LOADER_ARGS_OFFSET, sizeof (BootArguments));

	byte scanCode;
	GetKeyboardChar (&scanCode);
	return scanCode;
}


static void BootMenu ()
{
	BiosResult result;
	Partition partitions[16];
	Partition bootablePartitions[9];
	size_t partitionCount;
	size_t bootablePartitionCount = 0;

	for (byte drive = TC_FIRST_BIOS_DRIVE; drive <= TC_LAST_BIOS_DRIVE; ++drive)
	{
		if (GetDrivePartitions (drive, partitions, array_capacity (partitions), partitionCount, false, nullptr, true) == BiosResultSuccess)
		{
			for (size_t i = 0; i < partitionCount; ++i)
			{
				const Partition &partition = partitions[i];
				result = ReadSectors (SectorBuffer, drive, partition.StartSector, 1);

				if (result == BiosResultSuccess && *(uint16 *) (SectorBuffer + TC_LB_SIZE - 2) == 0xaa55)
				{
					// Windows writes boot loader on all NTFS/FAT filesytems it creates and, therefore,
					// NTFS/FAT partitions must have the boot indicator set to be considered bootable.
					if (!partition.Active
						&& (*(uint32 *) (SectorBuffer + 3) == 0x5346544e  // 'NTFS'
							|| *(uint16 *) (SectorBuffer + 54) == 0x4146 && SectorBuffer[56] == 'T' // 'FAT'
							|| *(uint16 *) (SectorBuffer + 82) == 0x4146 && SectorBuffer[84] == 'T'))
					{
						continue;
					}

					// Bootable sector found
					if (bootablePartitionCount < array_capacity (bootablePartitions))
						bootablePartitions[bootablePartitionCount++] = partition;
				}
			}
		}
	}

	if (bootablePartitionCount < 1)
	{
		PrintError (TC_BOOT_STR_NO_BOOT_PARTITION);
		GetKeyboardChar();
		return;
	}

	char partChar;
	while (true)
	{
		InitScreen();
		Print ("Bootable Partitions:\r\n");
		PrintRepeatedChar ('\xC4', 20);
		Print ("\r\n");

		for (size_t i = 0; i < bootablePartitionCount; ++i)
		{
			const Partition &partition = bootablePartitions[i];
			Print ("["); Print (i + 1); Print ("]    ");
			Print ("Drive: "); Print (partition.Drive - TC_FIRST_BIOS_DRIVE);
			Print (", Partition: "); Print (partition.Number + 1);
			Print (", Size: "); PrintSectorCountInMB (partition.SectorCount); PrintEndl();
		}

		if (bootablePartitionCount == 1)
		{
			// There's only one bootable partition so we'll boot it directly instead of showing boot manager
			partChar = '1';
		}
		else
		{
			Print ("[Esc]  Cancel\r\n\r\n");
			Print ("Press 1-9 to select partition: ");

			if (GetString (&partChar, 1) == 0)
				return;

			PrintEndl();

			if (partChar < '1' || partChar > '0' + bootablePartitionCount)
			{
				Beep();
				continue;
			}
		}

		const Partition &partition = bootablePartitions[partChar - '0' - 1];

		if (ReadSectors (SectorBuffer, partition.Drive, partition.StartSector, 1) == BiosResultSuccess)
		{
			ExecuteBootSector (partition.Drive, SectorBuffer);
		}
	}
}


#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE

static bool CopyActivePartitionToHiddenVolume (byte drive, byte &exitKey)
{
	bool status = false;

	uint64 sectorsRemaining;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -