/* Derived from source code of TrueCrypt 7.1a, which is Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0. Modifications and additions to the original source code (contained in this file) and all other portions of this file are Copyright (c) 2013-2017 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #ifndef TC_HEADER_Common_BootEncryption #define TC_HEADER_Common_BootEncryption #include "Tcdefs.h" #include "Dlgcode.h" #include "Exception.h" #include "Platform/PlatformBase.h" #include "Volumes.h" #include #define SYSPARTITIONINFORMATION 0x62 typedef NTSTATUS (WINAPI *NtQuerySystemInformationFn)( SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength ); using namespace std; namespace VeraCrypt { class File { public: File () : Elevated (false), FileOpen (false), ReadOnly (false), FilePointerPosition(0), Handle(INVALID_HANDLE_VALUE), IsDevice(false), LastError(0) { } File (wstring path,bool readOnly = false, bool create = false); virtual ~File () { Close(); } bool IsOpened () const { return FileOpen;} void CheckOpened (const char* srcPos) { if (!FileOpen) { SetLastError (LastError); throw SystemException (srcPos);} } void Close (); DWORD Read (byte *buffer, DWORD size); void Write (byte *buffer, DWORD size); void SeekAt (int64 position); void GetFileSize (unsigned __int64& size); void GetFileSize (DWORD& dwSize); bool IoCtl(DWORD code, void* inBuf, DWORD inBufSize, void* outBuf, DWORD outBufSize); protected: bool Elevated; bool FileOpen; bool ReadOnly; uint64 FilePointerPosition; HANDLE Handle; bool IsDevice; wstring Path; DWORD LastError; BYTE ReadBuffer[4096]; }; class Device : public File { public: Device (wstring path,bool readOnly = false); virtual ~Device () {} }; class Buffer { public: Buffer (size_t size) : DataSize (size) { DataPtr = new byte[size]; if (!DataPtr) throw bad_alloc(); } ~Buffer () { delete[] DataPtr; } byte *Ptr () const { return DataPtr; } size_t Size () const { return DataSize; } void Resize (size_t newSize) { if (newSize > DataSize) { byte *tmp = new byte[newSize]; if (!tmp) throw bad_alloc(); memcpy (tmp, DataPtr, DataSize); delete [] DataPtr; DataPtr = tmp; } DataSize = newSize; } protected: byte *DataPtr; size_t DataSize; }; struct Partition { wstring DevicePath; PARTITION_INFORMATION Info; wstring MountPoint; size_t Number; BOOL IsGPT; wstring VolumeNameId; }; typedef list PartitionList; #pragma pack (push) #pragma pack(1) struct PartitionEntryMBR { byte BootIndicator; byte StartHead; byte StartCylSector; byte StartCylinder; byte Type; byte EndHead; byte EndSector; byte EndCylinder; uint32 StartLBA; uint32 SectorCountLBA; }; struct MBR { byte Code[446]; PartitionEntryMBR Partitions[4]; uint16 Signature; }; #pragma pack (pop) struct SystemDriveConfiguration { wstring DeviceKernelPath; wstring DevicePath; int DriveNumber; Partition DrivePartition; bool ExtraBootPartitionPresent; int64 InitialUnallocatedSpace; PartitionList Partitions; Partition SystemPartition; int64 TotalUnallocatedSpace; bool SystemLoaderPresent; }; class EfiBootConf { public: int passwordType; string passwordMsg; string passwordPicture; string hashMsg; int hashAlgo; int requestHash; string pimMsg; int pim; int requestPim; int authorizeVisible; int authorizeRetry; int bmlLockFlags; int bmlDriverEnabled; string actionSuccessValue; EfiBootConf(); static BOOL ReadConfigValue (char* configContent, const char *configKey, char *configValue, int maxValueSize); static int ReadConfigInteger (char* configContent, const char *configKey, int defaultValue); static char *ReadConfigString (char* configContent, const char *configKey, char *defaultValue, char *str, int maxLen); static BOOL WriteConfigString (FILE* configFile, char* configContent, const char *configKey, const char *configValue); static BOOL WriteConfigInteger (FILE* configFile, char* configContent, const char *configKey, int configValue); BOOL Load (const wchar_t* fileName); void Load (char* configContent); BOOL Save (const wchar_t* fileName, HWND hwnd); }; void GetVolumeESP(wstring& path); std::string ReadESPFile (LPCWSTR szFilePath, bool bSkipUTF8BOM); void WriteESPFile (LPCWSTR szFilePath, LPBYTE pbData, DWORD dwDataLen, bool bAddUTF8BOM); class EfiBoot { public: EfiBoot(); void MountBootPartition(WCHAR letter); void DismountBootPartition(); bool IsEfiBoot(); void DeleteStartExec(uint16 statrtOrderNum = 0xDC5B, wchar_t* type = NULL); void SetStartExec(wstring description, wstring execPath, uint16 statrtOrderNum = 0xDC5B, wchar_t* type = NULL, uint32 attr = 1); void SaveFile(const wchar_t* name, byte* data, DWORD size); void GetFileSize(const wchar_t* name, unsigned __int64& size); void ReadFile(const wchar_t* name, byte* data, DWORD size); void CopyFile(const wchar_t* name, const wchar_t* targetName); bool FileExists(const wchar_t* name); BOOL RenameFile(const wchar_t* name, wchar_t* nameNew, BOOL bForce); BOOL DelFile(const wchar_t* name); BOOL MkDir(const wchar_t* name, bool& bAlreadyExists); BOOL ReadConfig (const wchar_t* name, EfiBootConf& conf); BOOL UpdateConfig (const wchar_t* name, int pim, int hashAlgo, HWND hwndDlg); BOOL WriteConfig (const wchar_t* name, bool preserveUserConfig, int pim, int hashAlgo, const char* passPromptMsg, HWND hwndDlg); BOOL DelDir(const wchar_t* name); void SelectBootVolumeESP(); void SelectBootVolume(WCHAR* bootVolumePath); PSTORAGE_DEVICE_NUMBER GetStorageDeviceNumber () { return &sdn;} protected: bool m_bMounted; WCHAR EfiBootPartPath[3]; STORAGE_DEVICE_NUMBER sdn; PARTITION_INFORMATION_EX partInfo; WCHAR tempBuf[1024]; bool bBootVolumePathSelected; WCHAR BootVolumePath[MAX_PATH]; }; class BootEncryption { public: BootEncryption (HWND parent, bool postOOBE = false); ~BootEncryption (); enum FilterType { DriveFilter, VolumeFilter, DumpFilter }; void SetParentWindow (HWND parent) { ParentWindow = parent; } void AbortDecoyOSWipe (); void AbortSetup (); void AbortSetupWait (); void CallDriver (DWORD ioctl, void *input = nullptr, DWORD inputSize = 0, void *output = nullptr, DWORD outputSize = 0); int ChangePassword (Password *oldPassword, int old_pkcs5, int old_pim, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg); void CheckDecoyOSWipeResult (); void CheckEncryptionSetupResult (); void CheckRequirements (); void CheckRequirementsHiddenOS (); void CopyFileAdmin (const wstring &sourceFile, const wstring &destinationFile); void CreateRescueIsoImage (bool initialSetup, const wstring &isoImagePath); void Deinstall (bool displayWaitDialog = false); void DeleteFileAdmin (const wstring &file); DecoySystemWipeStatus GetDecoyOSWipeStatus (); DWORD GetDriverServiceStartType (); unsigned int GetHiddenOSCreationPhase (); uint16 GetInstalledBootLoaderVersion (); void GetInstalledBootLoaderFingerprint (byte fingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE]); Partition GetPartitionForHiddenOS (); bool IsBootLoaderOnDrive (wchar_t *devicePath); BootEncryptionStatus GetStatus (); void GetVolumeProperties (VOLUME_PROPERTIES_STRUCT *properties); SystemDriveConfiguration GetSystemDriveConfiguration (); void Install (bool hiddenSystem, int hashAlgo); void InstallBootLoader (Device& device, bool preserveUserConfig = false, bool hiddenOSCreation = false, int pim = -1, int hashAlg = -1); void InstallBootLoader (bool preserveUserConfig = false, bool hiddenOSCreation = false, int pim = -1, int hashAlg = -1); bool CheckBootloaderFingerprint (bool bSilent = false); void InvalidateCachedSysDriveProperties (); bool IsCDRecorderPresent (); bool IsHiddenSystemRunning (); bool IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly); void PrepareHiddenOSCreation (int ea, int mode, int pkcs5); void PrepareInstallation (bool systemPartitionOnly, Password &password, int ea, int mode, int pkcs5, int pim, const wstring &rescueIsoImagePath); void ProbeRealSystemDriveSize (); bool ReadBootSectorConfig (byte *config, size_t bufLength, byte *userConfig = nullptr, string *customUserMessage = nullptr, uint16 *bootLoaderVersion = nullptr); uint32 ReadDriverConfigurationFlags (); void RegisterBootDriver (bool hiddenSystem); void RegisterFilterDriver (bool registerDriver, FilterType filterType); void RegisterSystemFavoritesService (BOOL registerService); void RegisterSystemFavoritesService (BOOL registerService, BOOL noFileHandling); void UpdateSystemFavoritesService (); void RenameDeprecatedSystemLoaderBackup (); bool RestartComputer (BOOL bShutdown = FALSE); void InitialSecurityChecksForHiddenOS (); void RestrictPagingFilesToSystemPartition (); void SetDriverConfigurationFlag (uint32 flag, bool state); void SetDriverServiceStartType (DWORD startType); void SetHiddenOSCreationPhase (unsigned int newPhase); void StartDecryption (BOOL discardUnreadableEncryptedSectors); void StartDecoyOSWipe (WipeAlgorithmId wipeAlgorithm); void StartEncryption (WipeAlgorithmId wipeAlgorithm, bool zeroUnreadableSectors); bool SystemDriveContainsPartitionType (byte type); bool SystemDriveContainsExtendedPartition (); bool SystemDriveContainsNonStandardPartitions (); bool SystemPartitionCoversWholeDrive (); bool SystemDriveIsDynamic (); bool VerifyRescueDisk (); bool VerifyRescueDiskImage (const wchar_t* imageFile); void WipeHiddenOSCreationConfig (); void WriteBootDriveSector (uint64 offset, byte *data); void WriteBootSectorConfig (const byte newConfig[]); void WriteBootSectorUserConfig (byte userConfig, const string &customUserMessage, int pim, int hashAlg); void WriteEfiBootSectorUserConfig (byte userConfig, const string &customUserMessage, int pim, int hashAlg); void WriteLocalMachineRegistryDwordValue (wchar_t *keyPath, wchar_t *valueName, DWORD value); void GetEfiBootDeviceNumber (PSTORAGE_DEVICE_NUMBER pSdn); void BackupSystemLoader (); void RestoreSystemLoader (); static void UpdateSetupConfigFile (bool bForInstall); void GetSecureBootConfig (BOOL* pSecureBootEnabled, BOOL *pVeraCryptKeysLoaded); protected: static const uint32 RescueIsoImageSize = 1835008; // Size of ISO9660 image with bootable emulated 1.44MB floppy disk image void CreateBootLoaderInMemory (byte *buffer, size_t bufferSize, bool rescueDisk, bool hiddenOSCreation = false); void CreateVolumeHeader (uint64 volumeSize, uint64 encryptedAreaStart, Password *password, int ea, int mode, int pkcs5, int pim); wstring GetSystemLoaderBackupPath (); uint32 GetChecksum (byte *data, size_t size); DISK_GEOMETRY_EX GetDriveGeometry (int driveNumber); PartitionList GetDrivePartitions (int driveNumber); wstring GetRemarksOnHiddenOS (); wstring GetWindowsDirectory (); void RegisterFilter (bool registerFilter, FilterType filterType, const GUID *deviceClassGuid = nullptr); void InstallVolumeHeader (); HWND ParentWindow; SystemDriveConfiguration DriveConfig; int SelectedEncryptionAlgorithmId; int SelectedPrfAlgorithmId; Partition HiddenOSCandidatePartition; byte *RescueIsoImage; byte *RescueZipData; unsigned long RescueZipSize; byte RescueVolumeHeader[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE]; byte VolumeHeader[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE]; bool DriveConfigValid; bool RealSystemDriveSizeValid; bool RescueVolumeHeaderValid; bool VolumeHeaderValid; bool PostOOBEMode; }; } #define TC_ABORT_TRANSFORM_WAIT_INTERVAL 10 #define MIN_HIDDENOS_DECOY_PARTITION_SIZE_RATIO_NTFS 2.1 #define MIN_HIDDENOS_DECOY_PARTITION_SIZE_RATIO_FAT 1.05 #define TC_SYS_BOOT_LOADER_BACKUP_NAME L"Original System Loader" #define TC_SYS_BOOT_LOADER_BACKUP_NAME_LEGACY L"Original System Loader.bak" // Deprecated to prevent removal by some "cleaners" #define TC_SYSTEM_FAVORITES_SERVICE_NAME _T(TC_APP_NAME) L"SystemFavorites" #define TC_SYSTEM_FAVORITES_SERVICE_LOAD_ORDER_GROUP L"Event Log" #define TC_SYSTEM_FAVORITES_SERVICE_CMDLINE_OPTION L"/systemFavoritesService" #define VC_WINDOWS_UPGRADE_POSTOOBE_CMDLINE_OPTION L"/PostOOBE" #endif // TC_HEADER_Common_BootEncryption 283'>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
/*
 Derived from source code of TrueCrypt 7.1a, which is
 Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed
 by the TrueCrypt License 3.0.

 Modifications and additions to the original source code (contained in this file) 
 and all other portions of this file are Copyright (c) 2013-2016 IDRIX
 and are governed by the Apache License 2.0 the full text of which is
 contained in the file License.txt included in VeraCrypt binary and source
 code distribution packages.
*/

#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "Tcdefs.h"
#include "Keyfiles.h"
#include "Crc.h"

#include <io.h>
#include "Dlgcode.h"
#include "Language.h"
#include "SecurityToken.h"
#include "Common/resource.h"
#include "Platform/Finally.h"
#include "Platform/ForEach.h"
#ifdef TCMOUNT
#include "Mount/Mount.h"
#endif

#include <Strsafe.h>

using namespace VeraCrypt;

#define stat _stat
#define S_IFDIR _S_IFDIR


BOOL HiddenFilesPresentInKeyfilePath = FALSE;

#ifdef TCMOUNT
extern BOOL UsePreferences;
#endif

KeyFile *KeyFileAdd (KeyFile *firstKeyFile, KeyFile *keyFile)
{
	KeyFile *kf = firstKeyFile;

	if (firstKeyFile != NULL)
	{
		while (kf->Next)
			kf = kf->Next;

		kf->Next = keyFile;
	}
	else
		firstKeyFile = keyFile;

	keyFile->Next = NULL;

	return firstKeyFile;
}


// Returns first keyfile, NULL if last keyfile was removed
static KeyFile *KeyFileRemove (KeyFile *firstKeyFile, KeyFile *keyFile)
{
	KeyFile *prevkf = NULL, *kf = firstKeyFile;

	if (firstKeyFile == NULL) return NULL;
	do
	{
		if (kf == keyFile)
		{
			if (prevkf == NULL)
				firstKeyFile = kf->Next;
			else
				prevkf->Next = kf->Next;

			burn (keyFile, sizeof(*keyFile));	// wipe
			free (keyFile);
			break;
		}
		prevkf = kf;
	}
	while (kf = kf->Next);

	return firstKeyFile;
}


void KeyFileRemoveAll (KeyFile **firstKeyFile)
{
	KeyFile *kf = *firstKeyFile;
	while (kf != NULL)
	{
		KeyFile *d = kf;
		kf = kf->Next;
		burn (d, sizeof(*d));	// wipe
		free (d);
	}

	*firstKeyFile = NULL;
}


KeyFile *KeyFileClone (KeyFile *keyFile)
{
	KeyFile *clone = NULL;

	if (keyFile == NULL) return NULL;

	clone = (KeyFile *) malloc (sizeof (KeyFile));
	if (clone)
	{
		StringCbCopyW (clone->FileName, sizeof(clone->FileName), keyFile->FileName);
		clone->Next = NULL;
	}
	return clone;
}


void KeyFileCloneAll (KeyFile *firstKeyFile, KeyFile **outputKeyFile)
{
	if (outputKeyFile)
	{
		KeyFile *cloneFirstKeyFile = KeyFileClone (firstKeyFile);
		KeyFile *kf;

		// free output only if different from input
		if (*outputKeyFile != firstKeyFile)
			KeyFileRemoveAll (outputKeyFile);
		if (firstKeyFile)
		{
			kf = firstKeyFile->Next;
			while (kf != NULL)
			{
				KeyFileAdd (cloneFirstKeyFile, KeyFileClone (kf));
				kf = kf->Next;
			}

			*outputKeyFile = cloneFirstKeyFile;
		}
	}
}


static BOOL KeyFileProcess (unsigned __int8 *keyPool, KeyFile *keyFile)
{
	FILE *f;
	unsigned __int8 buffer[64 * 1024];
	unsigned __int32 crc = 0xffffffff;
	int writePos = 0;
	size_t bytesRead, totalRead = 0;
	int status = TRUE;

	HANDLE src;
	FILETIME ftCreationTime;
	FILETIME ftLastWriteTime;
	FILETIME ftLastAccessTime;

	BOOL bTimeStampValid = FALSE;

	/* Remember the last access time of the keyfile. It will be preserved in order to prevent
	an adversary from determining which file may have been used as keyfile. */
	src = CreateFile (keyFile->FileName,
		GENERIC_READ | GENERIC_WRITE,
		FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);

	if (src != INVALID_HANDLE_VALUE)
	{
		if (GetFileTime ((HANDLE) src, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime))
			bTimeStampValid = TRUE;
	}

	finally_do_arg (HANDLE, src,
	{
		if (finally_arg != INVALID_HANDLE_VALUE)
			CloseHandle (finally_arg);
	});

	f = _wfopen (keyFile->FileName, L"rb");
	if (f == NULL) return FALSE;

	while ((bytesRead = fread (buffer, 1, sizeof (buffer), f)) > 0)
	{
		size_t i;

		if (ferror (f))
		{
			status = FALSE;
			goto close;
		}

		for (i = 0; i < bytesRead; i++)
		{
			crc = UPDC32 (buffer[i], crc);

			keyPool[writePos++] += (unsigned __int8) (crc >> 24);
			keyPool[writePos++] += (unsigned __int8) (crc >> 16);
			keyPool[writePos++] += (unsigned __int8) (crc >> 8);
			keyPool[writePos++] += (unsigned __int8) crc;

			if (writePos >= KEYFILE_POOL_SIZE)
				writePos = 0;

			if (++totalRead >= KEYFILE_MAX_READ_LEN)
				goto close;
		}
	}

	if (ferror (f))
	{
		status = FALSE;
	}
	else if (totalRead == 0)
	{
		status = FALSE;
		SetLastError (ERROR_HANDLE_EOF); 
	}

close:
	DWORD err = GetLastError();
	fclose (f);

	if (bTimeStampValid && !IsFileOnReadOnlyFilesystem (keyFile->FileName))
	{
		// Restore the keyfile timestamp
		SetFileTime (src, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime);
	}

	SetLastError (err);
	return status;
}


BOOL KeyFilesApply (HWND hwndDlg, Password *password, KeyFile *firstKeyFile, const wchar_t* volumeFileName)
{
	return KeyFilesApplyWithPin (hwndDlg, password, nullptr, firstKeyFile, volumeFileName);
}

BOOL KeyFilesApplyWithPin (HWND hwndDlg, Password *password, char* pin, KeyFile *firstKeyFile, const wchar_t* volumeFileName)
{
	BOOL status = TRUE;
	KeyFile kfSubStruct;
	KeyFile *kf;
	KeyFile *kfSub = &kfSubStruct;
	static unsigned __int8 keyPool [KEYFILE_POOL_SIZE];
	size_t i;
	struct stat statStruct;
	wchar_t searchPath [TC_MAX_PATH*2];
	struct _wfinddata_t fBuf;
	intptr_t searchHandle;

	HiddenFilesPresentInKeyfilePath = FALSE;

	if (firstKeyFile == NULL) return TRUE;

	VirtualLock (keyPool, sizeof (keyPool));
	memset (keyPool, 0, sizeof (keyPool));

	for (kf = firstKeyFile; kf != NULL; kf = kf->Next)
	{
		// Determine whether it's a security token path
		try
		{
			if (SecurityToken::IsKeyfilePathValid (kf->FileName))
			{
				// Apply security token keyfile
				vector <byte> keyfileData;
				SecurityTokenKeyfilePath secPath (kf->FileName);
				SecurityToken::GetKeyfileData (SecurityTokenKeyfile (secPath, pin), pin, keyfileData);

				if (keyfileData.empty())
				{
					SetLastError (ERROR_HANDLE_EOF); 
					handleWin32Error (hwndDlg, SRC_POS);
					Error ("ERR_PROCESS_KEYFILE", hwndDlg);
					status = FALSE;
					continue;
				}

				unsigned __int32 crc = 0xffffffff;
				int writePos = 0;
				size_t totalRead = 0;

				for (size_t i = 0; i < keyfileData.size(); i++)
				{
					crc = UPDC32 (keyfileData[i], crc);

					keyPool[writePos++] += (unsigned __int8) (crc >> 24);
					keyPool[writePos++] += (unsigned __int8) (crc >> 16);
					keyPool[writePos++] += (unsigned __int8) (crc >> 8);
					keyPool[writePos++] += (unsigned __int8) crc;

					if (writePos >= KEYFILE_POOL_SIZE)
						writePos = 0;

					if (++totalRead >= KEYFILE_MAX_READ_LEN)
						break;
				}

				burn (&keyfileData.front(), keyfileData.size());
				continue;
			}
		}
		catch (Exception &e)
		{
			e.Show (NULL);
			return FALSE;
		}

		// Determine whether it's a path or a file
		if (_wstat (kf->FileName, &statStruct) != 0)
		{
			handleWin32Error (hwndDlg, SRC_POS);
			Error ("ERR_PROCESS_KEYFILE", hwndDlg);
			status = FALSE;
			continue;
		}

		if (statStruct.st_mode & S_IFDIR)		// If it's a directory
		{
			/* Find and process all keyfiles in the directory */
			int keyfileCount = 0;

			StringCbPrintfW (searchPath, sizeof (searchPath), L"%s\\*.*", kf->FileName);
			if ((searchHandle = _wfindfirst (searchPath, &fBuf)) == -1)
			{
				handleWin32Error (hwndDlg, SRC_POS);
				Error ("ERR_PROCESS_KEYFILE_PATH", hwndDlg);
				status = FALSE;
				continue;
			}

			do
			{
				WIN32_FILE_ATTRIBUTE_DATA fileAttributes;

				StringCbPrintfW (kfSub->FileName, sizeof(kfSub->FileName), L"%s%c%s", kf->FileName,
					L'\\',
					fBuf.name
					);				

				// Determine whether it's a path or a file
				if (_wstat (kfSub->FileName, &statStruct) != 0)
				{
					handleWin32Error (hwndDlg, SRC_POS);
					Error ("ERR_PROCESS_KEYFILE", hwndDlg);
					status = FALSE;
					continue;
				}
				else if (statStruct.st_mode & S_IFDIR)		// If it's a directory
				{
					// Prevent recursive folder scanning
					continue;	 
				}

				// Skip hidden files
				if (GetFileAttributesExW (kfSub->FileName, GetFileExInfoStandard, &fileAttributes)
					&& (fileAttributes.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0)
				{
					HiddenFilesPresentInKeyfilePath = TRUE;
					continue;	 
				}

				CorrectFileName (kfSub->FileName);
				if (volumeFileName && (_wcsicmp (volumeFileName, kfSub->FileName) == 0))
				{
					// skip if it is the current container file name
					continue;
				}

				++keyfileCount;

				// Apply keyfile to the pool
				if (!KeyFileProcess (keyPool, kfSub))
				{
					handleWin32Error (hwndDlg, SRC_POS);
					Error ("ERR_PROCESS_KEYFILE", hwndDlg);
					status = FALSE;
				}

			} while (_wfindnext (searchHandle, &fBuf) != -1);
			_findclose (searchHandle);

			burn (&kfSubStruct, sizeof (kfSubStruct));

			if (keyfileCount == 0)
			{
				ErrorDirect ((wstring (GetString ("ERR_KEYFILE_PATH_EMPTY")) + L"\n\n" + wstring (kf->FileName)).c_str(), hwndDlg);
				status = FALSE;
			}
		}
		// Apply keyfile to the pool
		else if (!KeyFileProcess (keyPool, kf))
		{
			handleWin32Error (hwndDlg, SRC_POS);
			Error ("ERR_PROCESS_KEYFILE", hwndDlg);
			status = FALSE;
		}
	}

	/* Mix the keyfile pool contents into the password */

	for (i = 0; i < sizeof (keyPool); i++)
	{
		if (i < password->Length)
			password->Text[i] += keyPool[i];
		else
			password->Text[i] = keyPool[i];
	}

	if (password->Length < (int)sizeof (keyPool))
        password->Length = sizeof (keyPool);

	burn (keyPool, sizeof (keyPool));

	return status;
}


static void LoadKeyList (HWND hwndDlg, KeyFile *firstKeyFile)
{
	KeyFile *kf;
	LVITEM LvItem;
	int line = 0;
	HWND hList = GetDlgItem (hwndDlg, IDC_KEYLIST);

	ListView_DeleteAllItems (hList);
	EnableWindow (GetDlgItem (hwndDlg, IDC_KEYREMOVE), FALSE);
	EnableWindow (GetDlgItem (hwndDlg, IDC_KEYREMOVEALL), firstKeyFile != NULL);
	SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, firstKeyFile != NULL);

	for (kf = firstKeyFile; kf != NULL; kf = kf->Next)
	{
		memset (&LvItem,0,sizeof(LvItem));
		LvItem.mask = LVIF_TEXT|LVIF_PARAM;
		LvItem.iItem = line++;
		LvItem.iSubItem = 0;
		LvItem.pszText = kf->FileName;
		LvItem.lParam = (LPARAM) kf;
		SendMessage (hList, LVM_INSERTITEM, 0, (LPARAM)&LvItem);
	}
}

#if KEYFILE_POOL_SIZE % 4 != 0
#error KEYFILE_POOL_SIZE must be a multiple of 4
#endif

BOOL CALLBACK KeyFilesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static KeyFilesDlgParam *param;
	static KeyFilesDlgParam origParam;

	WORD lw = LOWORD (wParam);

	switch (msg)
	{
	case WM_INITDIALOG:
		{
			LVCOLUMNW LvCol;
			HWND hList = GetDlgItem (hwndDlg, IDC_KEYLIST);

			param = (KeyFilesDlgParam *) lParam;
			origParam = *(KeyFilesDlgParam *) lParam;

			KeyFileCloneAll (param->FirstKeyFile, &param->FirstKeyFile);

			LocalizeDialog (hwndDlg, "IDD_KEYFILES");
			DragAcceptFiles (hwndDlg, TRUE);

			SendMessageW (hList,LVM_SETEXTENDEDLISTVIEWSTYLE,0,
				LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP
				); 

			memset (&LvCol,0,sizeof(LvCol));               
			LvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT;  
			LvCol.pszText = GetString ("KEYFILE");                           
			LvCol.cx = CompensateXDPI (374);
			LvCol.fmt = LVCFMT_LEFT;
			SendMessageW (hList, LVM_INSERTCOLUMNW, 0, (LPARAM)&LvCol);

			LoadKeyList (hwndDlg, param->FirstKeyFile);
			SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, param->EnableKeyFiles);
			
#ifdef TCMOUNT
			if (	(origParam.EnableKeyFiles == defaultKeyFilesParam.EnableKeyFiles)
				&&	(origParam.FirstKeyFile == defaultKeyFilesParam.FirstKeyFile)
				)
			{
				/* default keyfile dialog case */
				SetCheckBox (hwndDlg, IDC_KEYFILES_TRY_EMPTY_PASSWORD, bTryEmptyPasswordWhenKeyfileUsed);
				ShowWindow(GetDlgItem(hwndDlg, IDC_KEYFILES_TRY_EMPTY_PASSWORD), SW_SHOW);
			}
#endif

			SetWindowTextW(GetDlgItem(hwndDlg, IDT_KEYFILES_NOTE), GetString ("KEYFILES_NOTE"));

			ToHyperlink (hwndDlg, IDC_LINK_KEYFILES_INFO);
		}
		return 1;

	case WM_COMMAND:

		if (lw == IDC_KEYADD)
		{
			KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
			if (kf)
			{
				if (SelectMultipleFiles (hwndDlg, "SELECT_KEYFILE", kf->FileName, sizeof(kf->FileName),bHistory))
				{
					bool containerFileSkipped = false;
					do
					{
						CorrectFileName (kf->FileName);
						if (_wcsicmp (param->VolumeFileName, kf->FileName) == 0)
							containerFileSkipped = true;
						else
						{
							param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
							LoadKeyList (hwndDlg, param->FirstKeyFile);

							kf = (KeyFile *) malloc (sizeof (KeyFile));
						}
					} while (SelectMultipleFilesNext (kf->FileName, sizeof(kf->FileName)));

					if (containerFileSkipped)
					{
						Warning ("SELECTED_KEYFILE_IS_CONTAINER_FILE", hwndDlg);
					}
				}

				free (kf);
			}
			return 1;
		}

		if (lw == IDC_ADD_KEYFILE_PATH)
		{
			KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));

			if (BrowseDirectories (hwndDlg,"SELECT_KEYFILE_PATH", kf->FileName))
			{
				param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
				LoadKeyList (hwndDlg, param->FirstKeyFile);
			}
			else
			{
				free (kf);
			}
			return 1;
		}

		if (lw == IDC_TOKEN_FILES_ADD)
		{
			list <SecurityTokenKeyfilePath> selectedTokenKeyfiles;
			if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TOKEN_KEYFILES), hwndDlg, (DLGPROC) SecurityTokenKeyfileDlgProc, (LPARAM) &selectedTokenKeyfiles) == IDOK)
			{
				foreach (const SecurityTokenKeyfilePath &keyPath, selectedTokenKeyfiles)
				{
					KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
					if (kf)
					{
						StringCbCopyW (kf->FileName, sizeof (kf->FileName), wstring(keyPath).c_str ());

						param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
						LoadKeyList (hwndDlg, param->FirstKeyFile);
					}
				}
			}

			return 1;
		}

		if (lw == IDC_KEYREMOVE)
		{
			HWND list = GetDlgItem (hwndDlg, IDC_KEYLIST);
			LVITEM LvItem;
			memset (&LvItem, 0, sizeof(LvItem));
			LvItem.mask = LVIF_PARAM;   
			LvItem.iItem = -1;

			while (-1 != (LvItem.iItem = ListView_GetNextItem (list, LvItem.iItem, LVIS_SELECTED)))
			{
				ListView_GetItem (list, &LvItem);
				param->FirstKeyFile = KeyFileRemove (param->FirstKeyFile, (KeyFile *) LvItem.lParam);
			} 
			
			LoadKeyList (hwndDlg, param->FirstKeyFile);
 			return 1;
		}

		if (lw == IDC_KEYREMOVEALL)
		{
			KeyFileRemoveAll (&param->FirstKeyFile);
			LoadKeyList (hwndDlg, NULL);
			return 1;
		}

		if (lw == IDC_GENERATE_KEYFILE)
		{
			DialogBoxParamW (hInst, 
				MAKEINTRESOURCEW (IDD_KEYFILE_GENERATOR), hwndDlg,
				(DLGPROC) KeyfileGeneratorDlgProc, (LPARAM) 0);
			return 1;
		}

		if (lw == IDC_LINK_KEYFILES_INFO)
		{
			Applink ("keyfiles", TRUE, "");
			return 1;
		}

		if (lw == IDOK)
		{
			param->EnableKeyFiles = IsButtonChecked (GetDlgItem (hwndDlg, IDC_KEYFILES_ENABLE));

#ifdef TCMOUNT
			if (IsWindowVisible (GetDlgItem (hwndDlg, IDC_KEYFILES_TRY_EMPTY_PASSWORD)))
			{
				bTryEmptyPasswordWhenKeyfileUsed = IsButtonChecked (GetDlgItem (hwndDlg, IDC_KEYFILES_TRY_EMPTY_PASSWORD));

				if (UsePreferences)
				{
					WaitCursor ();
					SaveSettings (hwndDlg);
					NormalCursor ();
				}
			}
#endif
			EndDialog (hwndDlg, IDOK);
			return 1;
		}

		if (lw == IDCANCEL)
		{
			KeyFileRemoveAll (&param->FirstKeyFile);
			*param = origParam;

			EndDialog (hwndDlg, IDCLOSE);
			return 1;
		}
		break;

	case WM_DROPFILES:
		{
			HDROP hdrop = (HDROP) wParam;

			int i = 0, count = DragQueryFile (hdrop, 0xFFFFFFFF, NULL, 0);

			while (count-- > 0)
			{
				KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
				if (kf)
				{
					DragQueryFile (hdrop, i++, kf->FileName, ARRAYSIZE (kf->FileName));
					param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
					LoadKeyList (hwndDlg, param->FirstKeyFile);
				}
			}

			DragFinish (hdrop);
		}
		return 1;

	case WM_NOTIFY:
		if (((LPNMHDR) lParam)->code == LVN_ITEMCHANGED)
		{
			EnableWindow (GetDlgItem (hwndDlg, IDC_KEYREMOVE),
				ListView_GetNextItem (GetDlgItem (hwndDlg, IDC_KEYLIST), -1, LVIS_SELECTED) != -1);
			return 1;
		}
		break;

	case WM_CLOSE:
		KeyFileRemoveAll (&param->FirstKeyFile);
		*param = origParam;

		EndDialog (hwndDlg, IDCLOSE);
		return 1;

		break;

	}

	return 0;
}


#define IDM_KEYFILES_POPUP_ADD_FILES		9001
#define IDM_KEYFILES_POPUP_ADD_DIR			9002
#define IDM_KEYFILES_POPUP_ADD_TOKEN_FILES	9003

BOOL KeyfilesPopupMenu (HWND hwndDlg, POINT popupPosition, KeyFilesDlgParam *param)
{
	HMENU popup = CreatePopupMenu ();
	if (!popup)
		return FALSE;
	int sel;
	BOOL status = FALSE;

	AppendMenuW (popup, MF_STRING, IDM_KEYFILES_POPUP_ADD_FILES, GetString ("IDC_KEYADD"));
	AppendMenuW (popup, MF_STRING, IDM_KEYFILES_POPUP_ADD_DIR, GetString ("IDC_ADD_KEYFILE_PATH"));
	AppendMenuW (popup, MF_STRING, IDM_KEYFILES_POPUP_ADD_TOKEN_FILES, GetString ("IDC_TOKEN_FILES_ADD"));

	sel = TrackPopupMenu (popup, TPM_RETURNCMD | TPM_LEFTBUTTON, popupPosition.x, popupPosition.y, 0, hwndDlg, NULL);

	switch (sel)
	{
	case IDM_KEYFILES_POPUP_ADD_FILES:
		{
			KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
			if (kf)
			{
				if (SelectMultipleFiles (hwndDlg, "SELECT_KEYFILE", kf->FileName, sizeof(kf->FileName),bHistory))
				{
					do
					{
						param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
						kf = (KeyFile *) malloc (sizeof (KeyFile));
					} while (SelectMultipleFilesNext (kf->FileName, sizeof(kf->FileName)));

					param->EnableKeyFiles = TRUE;
					status = TRUE;
				}

				free (kf);
			}
		}
		break;

	case IDM_KEYFILES_POPUP_ADD_DIR:
		{
			KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
			if (kf)
			{
				if (BrowseDirectories (hwndDlg,"SELECT_KEYFILE_PATH", kf->FileName))
				{
					param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
					param->EnableKeyFiles = TRUE;
					status = TRUE;
				}
				else
				{
					free (kf);
				}
			}
		}
		break;

	case IDM_KEYFILES_POPUP_ADD_TOKEN_FILES:
		{
			list <SecurityTokenKeyfilePath> selectedTokenKeyfiles;
			if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TOKEN_KEYFILES), hwndDlg, (DLGPROC) SecurityTokenKeyfileDlgProc, (LPARAM) &selectedTokenKeyfiles) == IDOK)
			{
				foreach (const SecurityTokenKeyfilePath &keyPath, selectedTokenKeyfiles)
				{
					KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
					if (kf)
					{
						StringCbCopyW (kf->FileName, sizeof (kf->FileName), wstring (keyPath).c_str());

						param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
						param->EnableKeyFiles = TRUE;
						status = TRUE;
					}
				}
			}
		}
		break;
	}

	DestroyMenu (popup);
	return status;
}