From fc37cc4a02ed13d1a73b941a9f80975600fd1b99 Mon Sep 17 00:00:00 2001 From: David Foerster Date: Tue, 10 May 2016 20:20:14 +0200 Subject: Normalize all line terminators --- src/Boot/Windows/Bios.h | 64 +- src/Boot/Windows/Boot.vcproj | 492 +- src/Boot/Windows/BootCommon.h | 164 +- src/Boot/Windows/BootConfig.cpp | 204 +- src/Boot/Windows/BootConfig.h | 92 +- src/Boot/Windows/BootConsoleIo.cpp | 678 +- src/Boot/Windows/BootConsoleIo.h | 144 +- src/Boot/Windows/BootCrt.asm | 54 +- src/Boot/Windows/BootDebug.cpp | 362 +- src/Boot/Windows/BootDebug.h | 120 +- src/Boot/Windows/BootDefs.h | 398 +- src/Boot/Windows/BootDiskIo.cpp | 982 +- src/Boot/Windows/BootDiskIo.h | 240 +- src/Boot/Windows/BootEncryptedIo.cpp | 264 +- src/Boot/Windows/BootEncryptedIo.h | 44 +- src/Boot/Windows/BootMain.cpp | 2538 +- src/Boot/Windows/BootMain.h | 68 +- src/Boot/Windows/BootMemory.cpp | 172 +- src/Boot/Windows/BootMemory.h | 56 +- src/Boot/Windows/BootSector.asm | 488 +- src/Boot/Windows/BootStrings.h | 40 +- src/Boot/Windows/Decompressor.c | 130 +- src/Boot/Windows/IntFilter.cpp | 1290 +- src/Boot/Windows/IntFilter.h | 40 +- src/Boot/Windows/Makefile | 404 +- src/Boot/Windows/Platform.cpp | 460 +- src/Boot/Windows/Platform.h | 232 +- src/Build/Tools/MacOSX/nasm | Bin 1818752 -> 1818750 bytes src/Common/Apidrvr.h | 688 +- src/Common/BaseCom.cpp | 492 +- src/Common/BaseCom.h | 238 +- src/Common/BootEncryption.cpp | 5626 +- src/Common/BootEncryption.h | 510 +- src/Common/Cache.c | 230 +- src/Common/Cache.h | 50 +- src/Common/Cmdline.c | 368 +- src/Common/Cmdline.h | 86 +- src/Common/Combo.c | 516 +- src/Common/Combo.h | 58 +- src/Common/Common.h | 190 +- src/Common/Common.rc | 1206 +- src/Common/Crc.c | 270 +- src/Common/Crc.h | 74 +- src/Common/Crypto.c | 2116 +- src/Common/Crypto.h | 726 +- src/Common/Dictionary.c | 174 +- src/Common/Dictionary.h | 68 +- src/Common/Dlgcode.c | 23780 ++++----- src/Common/Dlgcode.h | 1186 +- src/Common/EncryptionThreadPool.c | 1022 +- src/Common/EncryptionThreadPool.h | 84 +- src/Common/Endian.c | 118 +- src/Common/Endian.h | 298 +- src/Common/Exception.h | 246 +- src/Common/Fat.c | 898 +- src/Common/Fat.h | 138 +- src/Common/Format.c | 2108 +- src/Common/Format.h | 152 +- src/Common/GfMul.c | 1536 +- src/Common/GfMul.h | 148 +- src/Common/Inflate.c | 2642 +- src/Common/Inflate.h | 102 +- src/Common/Keyfiles.c | 1556 +- src/Common/Keyfiles.h | 108 +- src/Common/Language.c | 1166 +- src/Common/Language.h | 86 +- src/Common/Language.xml | 2912 +- src/Common/Makefile | 2 +- src/Common/Password.c | 982 +- src/Common/Password.h | 104 +- src/Common/Pkcs5.c | 1918 +- src/Common/Pkcs5.h | 96 +- src/Common/Progress.c | 268 +- src/Common/Progress.h | 66 +- src/Common/Random.c | 1796 +- src/Common/Random.h | 152 +- src/Common/Registry.c | 598 +- src/Common/Registry.h | 74 +- src/Common/Resource.h | 422 +- src/Common/SecurityToken.cpp | 1570 +- src/Common/SecurityToken.h | 452 +- src/Common/Sources | 34 +- src/Common/Tcdefs.h | 646 +- src/Common/Tests.c | 2310 +- src/Common/Tests.h | 62 +- src/Common/Volumes.c | 2540 +- src/Common/Volumes.h | 310 +- src/Common/Wipe.c | 396 +- src/Common/Wipe.h | 90 +- src/Common/Xml.c | 536 +- src/Common/Xml.h | 58 +- src/Common/Xts.c | 1500 +- src/Common/Xts.h | 168 +- src/Crypto/Aes.h | 430 +- src/Crypto/AesSmall.c | 1906 +- src/Crypto/AesSmall.h | 338 +- src/Crypto/AesSmall_x86.asm | 2888 +- src/Crypto/Aes_hw_cpu.asm | 660 +- src/Crypto/Aes_hw_cpu.h | 48 +- src/Crypto/Aes_x64.asm | 1814 +- src/Crypto/Aes_x86.asm | 1292 +- src/Crypto/Aescrypt.c | 622 +- src/Crypto/Aeskey.c | 1146 +- src/Crypto/Aesopt.h | 1468 +- src/Crypto/Aestab.c | 856 +- src/Crypto/Aestab.h | 348 +- src/Crypto/Crypto.vcproj | 1034 +- src/Crypto/Makefile | 2 +- src/Crypto/Makefile.inc | 30 +- src/Crypto/Rmd160.c | 996 +- src/Crypto/Rmd160.h | 66 +- src/Crypto/Serpent.c | 1876 +- src/Crypto/Serpent.h | 40 +- src/Crypto/Sha2.c | 1506 +- src/Crypto/Sha2.h | 310 +- src/Crypto/Sha2Small.c | 468 +- src/Crypto/Sha2Small.h | 26 +- src/Crypto/Sources | 40 +- src/Crypto/Twofish.c | 1098 +- src/Crypto/Twofish.h | 112 +- src/Crypto/Whirlpool.h | 54 +- src/Crypto/cpu.c | 462 +- src/Crypto/cpu.h | 616 +- src/Driver/BuildDriver.cmd | 332 +- src/Driver/DriveFilter.c | 4306 +- src/Driver/DriveFilter.h | 180 +- src/Driver/Driver.rc | 202 +- src/Driver/Driver.vcproj | 796 +- src/Driver/DumpFilter.c | 496 +- src/Driver/DumpFilter.h | 50 +- src/Driver/EncryptedIoQueue.c | 2098 +- src/Driver/EncryptedIoQueue.h | 330 +- src/Driver/Makefile | 2 +- src/Driver/Ntdriver.c | 7126 +-- src/Driver/Ntdriver.h | 378 +- src/Driver/Ntvol.c | 1800 +- src/Driver/Ntvol.h | 44 +- src/Driver/Resource.h | 32 +- src/Driver/Sources | 42 +- src/Driver/VolumeFilter.c | 598 +- src/Driver/VolumeFilter.h | 46 +- src/ExpandVolume/DlgExpandVolume.cpp | 1552 +- src/ExpandVolume/ExpandVolume.c | 42 +- src/ExpandVolume/ExpandVolume.rc | 596 +- src/ExpandVolume/ExpandVolume.vcproj | 1954 +- src/ExpandVolume/InitDataArea.c | 30 +- src/ExpandVolume/InitDataArea.h | 24 +- src/ExpandVolume/WinMain.cpp | 846 +- src/ExpandVolume/resource.h | 294 +- src/Format/Format.manifest | 64 +- src/Format/Format.rc | 1494 +- src/Format/Format.vcproj | 2056 +- src/Format/FormatCom.cpp | 496 +- src/Format/FormatCom.h | 72 +- src/Format/FormatCom.idl | 106 +- src/Format/InPlace.c | 4586 +- src/Format/InPlace.h | 104 +- src/Format/Resource.h | 318 +- src/Format/Tcformat.c | 20466 ++++---- src/Format/Tcformat.h | 218 +- src/License.html | 358 +- src/License.txt | 1404 +- src/Main/Forms/Forms.cpp | 7050 +-- src/Main/Forms/Forms.h | 2194 +- src/Main/Forms/TrueCrypt.fbp | 57476 ++++++++++----------- src/Mount/Favorites.cpp | 2048 +- src/Mount/Favorites.h | 174 +- src/Mount/Hotkeys.c | 1222 +- src/Mount/Hotkeys.h | 104 +- src/Mount/MainCom.cpp | 588 +- src/Mount/MainCom.h | 70 +- src/Mount/MainCom.idl | 114 +- src/Mount/Mount.c | 22048 ++++---- src/Mount/Mount.h | 266 +- src/Mount/Mount.manifest | 64 +- src/Mount/Mount.rc | 1426 +- src/Mount/Mount.vcproj | 2054 +- src/Mount/Resource.h | 526 +- src/PKCS11/cryptoki.h | 132 +- src/PKCS11/pkcs11.h | 598 +- src/PKCS11/pkcs11f.h | 1824 +- src/PKCS11/pkcs11t.h | 3770 +- src/Platform/Buffer.cpp | 280 +- src/Platform/Buffer.h | 218 +- src/Platform/Directory.h | 46 +- src/Platform/Event.cpp | 82 +- src/Platform/Event.h | 160 +- src/Platform/Exception.cpp | 92 +- src/Platform/Exception.h | 208 +- src/Platform/File.h | 208 +- src/Platform/FileCommon.cpp | 162 +- src/Platform/FileStream.h | 104 +- src/Platform/FilesystemPath.h | 134 +- src/Platform/Finally.h | 80 +- src/Platform/ForEach.h | 224 +- src/Platform/Functor.h | 46 +- src/Platform/Memory.cpp | 104 +- src/Platform/Memory.h | 336 +- src/Platform/MemoryStream.cpp | 82 +- src/Platform/MemoryStream.h | 60 +- src/Platform/Mutex.h | 110 +- src/Platform/Platform.h | 44 +- src/Platform/Platform.make | 78 +- src/Platform/PlatformBase.h | 256 +- src/Platform/PlatformTest.cpp | 688 +- src/Platform/PlatformTest.h | 74 +- src/Platform/Serializable.cpp | 66 +- src/Platform/Serializable.h | 152 +- src/Platform/Serializer.cpp | 586 +- src/Platform/Serializer.h | 136 +- src/Platform/SerializerFactory.cpp | 96 +- src/Platform/SerializerFactory.h | 174 +- src/Platform/SharedPtr.h | 312 +- src/Platform/SharedVal.h | 130 +- src/Platform/Stream.h | 56 +- src/Platform/StringConverter.cpp | 810 +- src/Platform/StringConverter.h | 112 +- src/Platform/SyncEvent.h | 82 +- src/Platform/System.h | 20 +- src/Platform/SystemException.h | 80 +- src/Platform/SystemInfo.h | 44 +- src/Platform/SystemLog.h | 72 +- src/Platform/TextReader.cpp | 62 +- src/Platform/TextReader.h | 58 +- src/Platform/Thread.h | 136 +- src/Platform/Time.h | 48 +- src/Platform/User.h | 52 +- src/Readme.txt | 530 +- src/Release/Setup Files/LICENSE | 378 +- src/Release/Setup Files/License.txt | 1404 +- src/Release/Setup Files/NOTICE | 268 +- src/Resources/Icons/VeraCrypt-128x128.xpm | 2592 +- src/Resources/Icons/VeraCrypt-16x16.xpm | 210 +- src/Resources/Icons/VeraCrypt-256x256.xpm | 4058 +- src/Resources/Icons/VeraCrypt-48x48.xpm | 972 +- src/Setup/ComSetup.cpp | 206 +- src/Setup/ComSetup.h | 24 +- src/Setup/ComSetup.rgs | 182 +- src/Setup/Dir.c | 220 +- src/Setup/Dir.h | 46 +- src/Setup/Resource.h | 128 +- src/Setup/SelfExtract.c | 1576 +- src/Setup/SelfExtract.h | 86 +- src/Setup/Setup.c | 5264 +- src/Setup/Setup.h | 380 +- src/Setup/Setup.manifest | 64 +- src/Setup/Setup.rc | 654 +- src/Setup/Setup.vcproj | 968 +- src/Setup/Wizard.c | 2390 +- src/Setup/Wizard.h | 62 +- src/Signing/GlobalSign_R1Cross.cer | 52 +- src/Signing/GlobalSign_Root_CA_MS_Cross_Cert.crt | 60 +- src/Signing/Thawt_CodeSigning_CA.crt | 52 +- src/Signing/sign.bat | 54 +- src/Signing/sign_test.bat | 62 +- src/Signing/thawte_Primary_MS_Cross_Cert.cer | 64 +- src/VeraCrypt.sln | 948 +- 257 files changed, 147347 insertions(+), 147347 deletions(-) (limited to 'src') diff --git a/src/Boot/Windows/Bios.h b/src/Boot/Windows/Bios.h index 314b1a62..dd2da6be 100644 --- a/src/Boot/Windows/Bios.h +++ b/src/Boot/Windows/Bios.h @@ -1,32 +1,32 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Boot_Bios -#define TC_HEADER_Boot_Bios - -#include "Platform.h" - -#define TC_LB_SIZE_BIT_SHIFT_DIVISOR 9 - -#define TC_FIRST_BIOS_DRIVE 0x80 -#define TC_LAST_BIOS_DRIVE 0x8f -#define TC_INVALID_BIOS_DRIVE (TC_FIRST_BIOS_DRIVE - 1) - -enum -{ - BiosResultSuccess = 0x00, - BiosResultInvalidFunction = 0x01 -}; - -typedef byte BiosResult; - -#endif // TC_HEADER_Boot_Bios +/* + 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. +*/ + +#ifndef TC_HEADER_Boot_Bios +#define TC_HEADER_Boot_Bios + +#include "Platform.h" + +#define TC_LB_SIZE_BIT_SHIFT_DIVISOR 9 + +#define TC_FIRST_BIOS_DRIVE 0x80 +#define TC_LAST_BIOS_DRIVE 0x8f +#define TC_INVALID_BIOS_DRIVE (TC_FIRST_BIOS_DRIVE - 1) + +enum +{ + BiosResultSuccess = 0x00, + BiosResultInvalidFunction = 0x01 +}; + +typedef byte BiosResult; + +#endif // TC_HEADER_Boot_Bios diff --git a/src/Boot/Windows/Boot.vcproj b/src/Boot/Windows/Boot.vcproj index d0b40f1a..64ad48ec 100644 --- a/src/Boot/Windows/Boot.vcproj +++ b/src/Boot/Windows/Boot.vcproj @@ -1,246 +1,246 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Boot/Windows/BootCommon.h b/src/Boot/Windows/BootCommon.h index 4d91981b..1dc86560 100644 --- a/src/Boot/Windows/BootCommon.h +++ b/src/Boot/Windows/BootCommon.h @@ -1,82 +1,82 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Boot_BootCommon -#define TC_HEADER_Boot_BootCommon - -#include "Common/Password.h" -#include "BootDefs.h" - -// The user will be advised to upgrade the rescue disk if upgrading from the following or any previous version -#define TC_RESCUE_DISK_UPGRADE_NOTICE_MAX_VERSION 0x0117 - -#define TC_BOOT_LOADER_AREA_SIZE (TC_BOOT_LOADER_AREA_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS) - -#define TC_BOOT_VOLUME_HEADER_SECTOR (TC_BOOT_LOADER_AREA_SECTOR_COUNT - 1) -#define TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET (TC_BOOT_VOLUME_HEADER_SECTOR * TC_SECTOR_SIZE_BIOS) - -#define TC_CD_BOOTSECTOR_OFFSET 0xd000 -#define TC_CD_BOOT_LOADER_SECTOR 26 - -#define TC_ORIG_BOOT_LOADER_BACKUP_SECTOR TC_BOOT_LOADER_AREA_SECTOR_COUNT -#define TC_ORIG_BOOT_LOADER_BACKUP_SECTOR_OFFSET (TC_ORIG_BOOT_LOADER_BACKUP_SECTOR * TC_SECTOR_SIZE_BIOS) - -#define TC_BOOT_LOADER_BACKUP_RESCUE_DISK_SECTOR (TC_ORIG_BOOT_LOADER_BACKUP_SECTOR + TC_BOOT_LOADER_AREA_SECTOR_COUNT) -#define TC_BOOT_LOADER_BACKUP_RESCUE_DISK_SECTOR_OFFSET (TC_BOOT_LOADER_BACKUP_RESCUE_DISK_SECTOR * TC_SECTOR_SIZE_BIOS) - -#define TC_MBR_SECTOR 0 -#define TC_MAX_MBR_BOOT_CODE_SIZE 440 - -#define TC_MAX_EXTRA_BOOT_PARTITION_SIZE (512UL * 1024UL * 1024UL) - - -#pragma pack (1) - -typedef struct -{ - byte Flags; -} BootSectorConfiguration; - - -// Modifying this value can introduce incompatibility with previous versions -#define TC_BOOT_LOADER_ARGS_OFFSET 0x10 - -typedef struct -{ - // Modifying this structure can introduce incompatibility with previous versions - char Signature[8]; - uint16 BootLoaderVersion; - uint16 CryptoInfoOffset; - uint16 CryptoInfoLength; - uint32 HeaderSaltCrc32; - Password BootPassword; - uint64 HiddenSystemPartitionStart; - uint64 DecoySystemPartitionStart; - uint32 Flags; - uint32 BootDriveSignature; - - uint32 BootArgumentsCrc32; - -} BootArguments; - -// Modifying these values can introduce incompatibility with previous versions -#define TC_BOOT_ARGS_FLAG_EXTRA_BOOT_PARTITION 0x1 - -#pragma pack () - -// Boot arguments signature should not be defined as a static string -// Modifying these values can introduce incompatibility with previous versions -#define TC_SET_BOOT_ARGUMENTS_SIGNATURE(SG) do { SG[0] = 'T'; SG[1] = 'R'; SG[2] = 'U'; SG[3] = 'E'; SG[4] = 0x11; SG[5] = 0x23; SG[6] = 0x45; SG[7] = 0x66; } while (FALSE) -#define TC_IS_BOOT_ARGUMENTS_SIGNATURE(SG) (SG[0] == 'T' && SG[1] == 'R' && SG[2] == 'U' && SG[3] == 'E' && SG[4] == 0x11 && SG[5] == 0x23 && SG[6] == 0x45 && SG[7] == 0x66) - - -#endif // TC_HEADER_Boot_BootCommon +/* + 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. +*/ + +#ifndef TC_HEADER_Boot_BootCommon +#define TC_HEADER_Boot_BootCommon + +#include "Common/Password.h" +#include "BootDefs.h" + +// The user will be advised to upgrade the rescue disk if upgrading from the following or any previous version +#define TC_RESCUE_DISK_UPGRADE_NOTICE_MAX_VERSION 0x0117 + +#define TC_BOOT_LOADER_AREA_SIZE (TC_BOOT_LOADER_AREA_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS) + +#define TC_BOOT_VOLUME_HEADER_SECTOR (TC_BOOT_LOADER_AREA_SECTOR_COUNT - 1) +#define TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET (TC_BOOT_VOLUME_HEADER_SECTOR * TC_SECTOR_SIZE_BIOS) + +#define TC_CD_BOOTSECTOR_OFFSET 0xd000 +#define TC_CD_BOOT_LOADER_SECTOR 26 + +#define TC_ORIG_BOOT_LOADER_BACKUP_SECTOR TC_BOOT_LOADER_AREA_SECTOR_COUNT +#define TC_ORIG_BOOT_LOADER_BACKUP_SECTOR_OFFSET (TC_ORIG_BOOT_LOADER_BACKUP_SECTOR * TC_SECTOR_SIZE_BIOS) + +#define TC_BOOT_LOADER_BACKUP_RESCUE_DISK_SECTOR (TC_ORIG_BOOT_LOADER_BACKUP_SECTOR + TC_BOOT_LOADER_AREA_SECTOR_COUNT) +#define TC_BOOT_LOADER_BACKUP_RESCUE_DISK_SECTOR_OFFSET (TC_BOOT_LOADER_BACKUP_RESCUE_DISK_SECTOR * TC_SECTOR_SIZE_BIOS) + +#define TC_MBR_SECTOR 0 +#define TC_MAX_MBR_BOOT_CODE_SIZE 440 + +#define TC_MAX_EXTRA_BOOT_PARTITION_SIZE (512UL * 1024UL * 1024UL) + + +#pragma pack (1) + +typedef struct +{ + byte Flags; +} BootSectorConfiguration; + + +// Modifying this value can introduce incompatibility with previous versions +#define TC_BOOT_LOADER_ARGS_OFFSET 0x10 + +typedef struct +{ + // Modifying this structure can introduce incompatibility with previous versions + char Signature[8]; + uint16 BootLoaderVersion; + uint16 CryptoInfoOffset; + uint16 CryptoInfoLength; + uint32 HeaderSaltCrc32; + Password BootPassword; + uint64 HiddenSystemPartitionStart; + uint64 DecoySystemPartitionStart; + uint32 Flags; + uint32 BootDriveSignature; + + uint32 BootArgumentsCrc32; + +} BootArguments; + +// Modifying these values can introduce incompatibility with previous versions +#define TC_BOOT_ARGS_FLAG_EXTRA_BOOT_PARTITION 0x1 + +#pragma pack () + +// Boot arguments signature should not be defined as a static string +// Modifying these values can introduce incompatibility with previous versions +#define TC_SET_BOOT_ARGUMENTS_SIGNATURE(SG) do { SG[0] = 'T'; SG[1] = 'R'; SG[2] = 'U'; SG[3] = 'E'; SG[4] = 0x11; SG[5] = 0x23; SG[6] = 0x45; SG[7] = 0x66; } while (FALSE) +#define TC_IS_BOOT_ARGUMENTS_SIGNATURE(SG) (SG[0] == 'T' && SG[1] == 'R' && SG[2] == 'U' && SG[3] == 'E' && SG[4] == 0x11 && SG[5] == 0x23 && SG[6] == 0x45 && SG[7] == 0x66) + + +#endif // TC_HEADER_Boot_BootCommon diff --git a/src/Boot/Windows/BootConfig.cpp b/src/Boot/Windows/BootConfig.cpp index 63ebaf5e..75baf19e 100644 --- a/src/Boot/Windows/BootConfig.cpp +++ b/src/Boot/Windows/BootConfig.cpp @@ -1,102 +1,102 @@ -/* - 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 "BootConfig.h" - -byte BootSectorFlags; - -byte BootLoaderDrive; -byte BootDrive; -bool BootDriveGeometryValid = false; -bool PreventNormalSystemBoot = false; -bool PreventBootMenu = false; -char CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH + 1]; -uint32 OuterVolumeBackupHeaderCrc; - -bool BootStarted = false; - -DriveGeometry BootDriveGeometry; - -CRYPTO_INFO *BootCryptoInfo; -Partition EncryptedVirtualPartition; - -Partition ActivePartition; -Partition PartitionFollowingActive; -bool ExtraBootPartitionPresent = false; -uint64 PimValueOrHiddenVolumeStartUnitNo; // reuse this variable for stored PIM value to reduce memory usage -uint64 HiddenVolumeStartSector; - -#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE - -void ReadBootSectorUserConfiguration () -{ - byte userConfig; - - AcquireSectorBuffer(); - - if (ReadWriteMBR (false, BootLoaderDrive, true) != BiosResultSuccess) - goto ret; - - userConfig = SectorBuffer[TC_BOOT_SECTOR_USER_CONFIG_OFFSET]; - -#ifdef TC_WINDOWS_BOOT_AES - EnableHwEncryption (!(userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_HW_ENCRYPTION)); -#endif - - PreventBootMenu = (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_ESC); - - memcpy (CustomUserMessage, SectorBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); - CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH] = 0; - - if (userConfig & TC_BOOT_USER_CFG_FLAG_SILENT_MODE) - { - if (CustomUserMessage[0]) - { - InitVideoMode(); - Print (CustomUserMessage); - } - - DisableScreenOutput(); - } - - if (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM) - { - PimValueOrHiddenVolumeStartUnitNo.LowPart = 0; - memcpy (&PimValueOrHiddenVolumeStartUnitNo.LowPart, SectorBuffer + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, TC_BOOT_SECTOR_PIM_VALUE_SIZE); - } - else - PimValueOrHiddenVolumeStartUnitNo.LowPart = -1; - - OuterVolumeBackupHeaderCrc = *(uint32 *) (SectorBuffer + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET); - -ret: - ReleaseSectorBuffer(); -} - - -BiosResult UpdateBootSectorConfiguration (byte drive) -{ - AcquireSectorBuffer(); - - BiosResult result = ReadWriteMBR (false, drive); - if (result != BiosResultSuccess) - goto ret; - - SectorBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET] = BootSectorFlags; - result = ReadWriteMBR (true, drive); - -ret: - ReleaseSectorBuffer(); - return result; -} - -#endif // !TC_WINDOWS_BOOT_RESCUE_DISK_MODE +/* + 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 "BootConfig.h" + +byte BootSectorFlags; + +byte BootLoaderDrive; +byte BootDrive; +bool BootDriveGeometryValid = false; +bool PreventNormalSystemBoot = false; +bool PreventBootMenu = false; +char CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH + 1]; +uint32 OuterVolumeBackupHeaderCrc; + +bool BootStarted = false; + +DriveGeometry BootDriveGeometry; + +CRYPTO_INFO *BootCryptoInfo; +Partition EncryptedVirtualPartition; + +Partition ActivePartition; +Partition PartitionFollowingActive; +bool ExtraBootPartitionPresent = false; +uint64 PimValueOrHiddenVolumeStartUnitNo; // reuse this variable for stored PIM value to reduce memory usage +uint64 HiddenVolumeStartSector; + +#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE + +void ReadBootSectorUserConfiguration () +{ + byte userConfig; + + AcquireSectorBuffer(); + + if (ReadWriteMBR (false, BootLoaderDrive, true) != BiosResultSuccess) + goto ret; + + userConfig = SectorBuffer[TC_BOOT_SECTOR_USER_CONFIG_OFFSET]; + +#ifdef TC_WINDOWS_BOOT_AES + EnableHwEncryption (!(userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_HW_ENCRYPTION)); +#endif + + PreventBootMenu = (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_ESC); + + memcpy (CustomUserMessage, SectorBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); + CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH] = 0; + + if (userConfig & TC_BOOT_USER_CFG_FLAG_SILENT_MODE) + { + if (CustomUserMessage[0]) + { + InitVideoMode(); + Print (CustomUserMessage); + } + + DisableScreenOutput(); + } + + if (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM) + { + PimValueOrHiddenVolumeStartUnitNo.LowPart = 0; + memcpy (&PimValueOrHiddenVolumeStartUnitNo.LowPart, SectorBuffer + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, TC_BOOT_SECTOR_PIM_VALUE_SIZE); + } + else + PimValueOrHiddenVolumeStartUnitNo.LowPart = -1; + + OuterVolumeBackupHeaderCrc = *(uint32 *) (SectorBuffer + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET); + +ret: + ReleaseSectorBuffer(); +} + + +BiosResult UpdateBootSectorConfiguration (byte drive) +{ + AcquireSectorBuffer(); + + BiosResult result = ReadWriteMBR (false, drive); + if (result != BiosResultSuccess) + goto ret; + + SectorBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET] = BootSectorFlags; + result = ReadWriteMBR (true, drive); + +ret: + ReleaseSectorBuffer(); + return result; +} + +#endif // !TC_WINDOWS_BOOT_RESCUE_DISK_MODE diff --git a/src/Boot/Windows/BootConfig.h b/src/Boot/Windows/BootConfig.h index 0c5eee74..0a06a987 100644 --- a/src/Boot/Windows/BootConfig.h +++ b/src/Boot/Windows/BootConfig.h @@ -1,46 +1,46 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Boot_BootConfig -#define TC_HEADER_Boot_BootConfig - -#include "Crypto.h" -#include "Platform.h" -#include "BootDiskIo.h" - -extern byte BootSectorFlags; - -extern byte BootLoaderDrive; -extern byte BootDrive; -extern bool BootDriveGeometryValid; -extern DriveGeometry BootDriveGeometry; -extern bool PreventNormalSystemBoot; -extern bool PreventBootMenu; -extern char CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH + 1]; -extern uint32 OuterVolumeBackupHeaderCrc; - -extern bool BootStarted; - -extern CRYPTO_INFO *BootCryptoInfo; -extern Partition EncryptedVirtualPartition; - -extern Partition ActivePartition; -extern Partition PartitionFollowingActive; -extern bool ExtraBootPartitionPresent; -extern uint64 PimValueOrHiddenVolumeStartUnitNo; // reuse this variable for stored PIM value to reduce memory usage -extern uint64 HiddenVolumeStartSector; - - -void ReadBootSectorUserConfiguration (); -BiosResult UpdateBootSectorConfiguration (byte drive); - -#endif // TC_HEADER_Boot_BootConfig +/* + 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. +*/ + +#ifndef TC_HEADER_Boot_BootConfig +#define TC_HEADER_Boot_BootConfig + +#include "Crypto.h" +#include "Platform.h" +#include "BootDiskIo.h" + +extern byte BootSectorFlags; + +extern byte BootLoaderDrive; +extern byte BootDrive; +extern bool BootDriveGeometryValid; +extern DriveGeometry BootDriveGeometry; +extern bool PreventNormalSystemBoot; +extern bool PreventBootMenu; +extern char CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH + 1]; +extern uint32 OuterVolumeBackupHeaderCrc; + +extern bool BootStarted; + +extern CRYPTO_INFO *BootCryptoInfo; +extern Partition EncryptedVirtualPartition; + +extern Partition ActivePartition; +extern Partition PartitionFollowingActive; +extern bool ExtraBootPartitionPresent; +extern uint64 PimValueOrHiddenVolumeStartUnitNo; // reuse this variable for stored PIM value to reduce memory usage +extern uint64 HiddenVolumeStartSector; + + +void ReadBootSectorUserConfiguration (); +BiosResult UpdateBootSectorConfiguration (byte drive); + +#endif // TC_HEADER_Boot_BootConfig diff --git a/src/Boot/Windows/BootConsoleIo.cpp b/src/Boot/Windows/BootConsoleIo.cpp index 31b66673..8b5a1905 100644 --- a/src/Boot/Windows/BootConsoleIo.cpp +++ b/src/Boot/Windows/BootConsoleIo.cpp @@ -1,339 +1,339 @@ -/* - 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 "Platform.h" -#include "Bios.h" -#include "BootConsoleIo.h" -#include "BootDebug.h" -#include "BootStrings.h" - - -static int ScreenOutputDisabled = 0; - -void DisableScreenOutput () -{ - ++ScreenOutputDisabled; -} - - -void EnableScreenOutput () -{ - --ScreenOutputDisabled; -} - - -void PrintChar (char c) -{ -#ifdef TC_BOOT_TRACING_ENABLED - WriteDebugPort (c); -#endif - - if (ScreenOutputDisabled) - return; - - __asm - { - mov bx, 7 - mov al, c - mov ah, 0xe - int 0x10 - } -} - - -void PrintCharAtCursor (char c) -{ - if (ScreenOutputDisabled) - return; - - __asm - { - mov bx, 7 - mov al, c - mov cx, 1 - mov ah, 0xa - int 0x10 - } -} - - -void Print (const char *str) -{ - char c; - while (c = *str++) - PrintChar (c); -} - - -void Print (uint32 number) -{ - char str[12]; - int pos = 0; - while (number >= 10) - { - str[pos++] = (char) (number % 10) + '0'; - number /= 10; - } - str[pos] = (char) (number % 10) + '0'; - - while (pos >= 0) - PrintChar (str[pos--]); -} - - -void Print (const uint64 &number) -{ - if (number.HighPart == 0) - Print (number.LowPart); - else - PrintHex (number); -} - - -void PrintHex (byte b) -{ - PrintChar (((b >> 4) >= 0xA ? 'A' - 0xA : '0') + (b >> 4)); - PrintChar (((b & 0xF) >= 0xA ? 'A' - 0xA : '0') + (b & 0xF)); -} - - -void PrintHex (uint16 data) -{ - PrintHex (byte (data >> 8)); - PrintHex (byte (data)); -} - - -void PrintHex (uint32 data) -{ - PrintHex (uint16 (data >> 16)); - PrintHex (uint16 (data)); -} - - -void PrintHex (const uint64 &data) -{ - PrintHex (data.HighPart); - PrintHex (data.LowPart); -} - -void PrintRepeatedChar (char c, int n) -{ - while (n-- > 0) - PrintChar (c); -} - - -void PrintEndl () -{ - Print ("\r\n"); -} - - -void PrintEndl (int cnt) -{ - while (cnt-- > 0) - PrintEndl (); -} - - -void Beep () -{ - PrintChar (7); -} - - -void InitVideoMode () -{ - if (ScreenOutputDisabled) - return; - - __asm - { - // Text mode 80x25 - mov ax, 3 - int 0x10 - - // Page 0 - mov ax, 0x500 - int 0x10 - } -} - - -void ClearScreen () -{ - if (ScreenOutputDisabled) - return; - - __asm - { - // White text on black - mov bh, 7 - xor cx, cx - mov dx, 0x184f - mov ax, 0x600 - int 0x10 - - // Cursor at 0,0 - xor bh, bh - xor dx, dx - mov ah, 2 - int 0x10 - } -} - - -void PrintBackspace () -{ - PrintChar (TC_BIOS_CHAR_BACKSPACE); - PrintCharAtCursor (' '); -} - - -void PrintError (const char *message) -{ - Print (TC_BOOT_STR_ERROR); - Print (message); - PrintEndl(); - Beep(); -} - - -void PrintErrorNoEndl (const char *message) -{ - Print (TC_BOOT_STR_ERROR); - Print (message); - Beep(); -} - - -byte GetShiftFlags () -{ - byte flags; - __asm - { - mov ah, 2 - int 0x16 - mov flags, al - } - - return flags; -} - - -byte GetKeyboardChar () -{ - return GetKeyboardChar (nullptr); -} - - -byte GetKeyboardChar (byte *scanCode) -{ - // Work around potential BIOS bugs (Windows boot manager polls the keystroke buffer) - while (!IsKeyboardCharAvailable()); - - byte asciiCode; - byte scan; - __asm - { - mov ah, 0 - int 0x16 - mov asciiCode, al - mov scan, ah - } - - if (scanCode) - *scanCode = scan; - - return asciiCode; -} - - -bool IsKeyboardCharAvailable () -{ - bool available = false; - __asm - { - mov ah, 1 - int 0x16 - jz not_avail - mov available, true - not_avail: - } - - return available; -} - - -bool EscKeyPressed () -{ - if (IsKeyboardCharAvailable ()) - { - byte keyScanCode; - GetKeyboardChar (&keyScanCode); - return keyScanCode == TC_BIOS_KEY_ESC; - } - - return false; -} - - -void ClearBiosKeystrokeBuffer () -{ - __asm - { - push es - xor ax, ax - mov es, ax - mov di, 0x41e - mov cx, 32 - cld - rep stosb - pop es - } -} - - -bool IsPrintable (char c) -{ - return c >= ' ' && c <= '~'; -} - -bool IsDigit (char c) -{ - return c >= '0' && c <= '9'; -} - - -int GetString (char *buffer, size_t bufferSize) -{ - byte c; - byte scanCode; - size_t pos = 0; - - while (pos < bufferSize) - { - c = GetKeyboardChar (&scanCode); - - if (scanCode == TC_BIOS_KEY_ENTER) - break; - - if (scanCode == TC_BIOS_KEY_ESC) - return 0; - - buffer[pos++] = c; - PrintChar (IsPrintable (c) ? c : ' '); - } - - return pos; -} +/* + 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 "Platform.h" +#include "Bios.h" +#include "BootConsoleIo.h" +#include "BootDebug.h" +#include "BootStrings.h" + + +static int ScreenOutputDisabled = 0; + +void DisableScreenOutput () +{ + ++ScreenOutputDisabled; +} + + +void EnableScreenOutput () +{ + --ScreenOutputDisabled; +} + + +void PrintChar (char c) +{ +#ifdef TC_BOOT_TRACING_ENABLED + WriteDebugPort (c); +#endif + + if (ScreenOutputDisabled) + return; + + __asm + { + mov bx, 7 + mov al, c + mov ah, 0xe + int 0x10 + } +} + + +void PrintCharAtCursor (char c) +{ + if (ScreenOutputDisabled) + return; + + __asm + { + mov bx, 7 + mov al, c + mov cx, 1 + mov ah, 0xa + int 0x10 + } +} + + +void Print (const char *str) +{ + char c; + while (c = *str++) + PrintChar (c); +} + + +void Print (uint32 number) +{ + char str[12]; + int pos = 0; + while (number >= 10) + { + str[pos++] = (char) (number % 10) + '0'; + number /= 10; + } + str[pos] = (char) (number % 10) + '0'; + + while (pos >= 0) + PrintChar (str[pos--]); +} + + +void Print (const uint64 &number) +{ + if (number.HighPart == 0) + Print (number.LowPart); + else + PrintHex (number); +} + + +void PrintHex (byte b) +{ + PrintChar (((b >> 4) >= 0xA ? 'A' - 0xA : '0') + (b >> 4)); + PrintChar (((b & 0xF) >= 0xA ? 'A' - 0xA : '0') + (b & 0xF)); +} + + +void PrintHex (uint16 data) +{ + PrintHex (byte (data >> 8)); + PrintHex (byte (data)); +} + + +void PrintHex (uint32 data) +{ + PrintHex (uint16 (data >> 16)); + PrintHex (uint16 (data)); +} + + +void PrintHex (const uint64 &data) +{ + PrintHex (data.HighPart); + PrintHex (data.LowPart); +} + +void PrintRepeatedChar (char c, int n) +{ + while (n-- > 0) + PrintChar (c); +} + + +void PrintEndl () +{ + Print ("\r\n"); +} + + +void PrintEndl (int cnt) +{ + while (cnt-- > 0) + PrintEndl (); +} + + +void Beep () +{ + PrintChar (7); +} + + +void InitVideoMode () +{ + if (ScreenOutputDisabled) + return; + + __asm + { + // Text mode 80x25 + mov ax, 3 + int 0x10 + + // Page 0 + mov ax, 0x500 + int 0x10 + } +} + + +void ClearScreen () +{ + if (ScreenOutputDisabled) + return; + + __asm + { + // White text on black + mov bh, 7 + xor cx, cx + mov dx, 0x184f + mov ax, 0x600 + int 0x10 + + // Cursor at 0,0 + xor bh, bh + xor dx, dx + mov ah, 2 + int 0x10 + } +} + + +void PrintBackspace () +{ + PrintChar (TC_BIOS_CHAR_BACKSPACE); + PrintCharAtCursor (' '); +} + + +void PrintError (const char *message) +{ + Print (TC_BOOT_STR_ERROR); + Print (message); + PrintEndl(); + Beep(); +} + + +void PrintErrorNoEndl (const char *message) +{ + Print (TC_BOOT_STR_ERROR); + Print (message); + Beep(); +} + + +byte GetShiftFlags () +{ + byte flags; + __asm + { + mov ah, 2 + int 0x16 + mov flags, al + } + + return flags; +} + + +byte GetKeyboardChar () +{ + return GetKeyboardChar (nullptr); +} + + +byte GetKeyboardChar (byte *scanCode) +{ + // Work around potential BIOS bugs (Windows boot manager polls the keystroke buffer) + while (!IsKeyboardCharAvailable()); + + byte asciiCode; + byte scan; + __asm + { + mov ah, 0 + int 0x16 + mov asciiCode, al + mov scan, ah + } + + if (scanCode) + *scanCode = scan; + + return asciiCode; +} + + +bool IsKeyboardCharAvailable () +{ + bool available = false; + __asm + { + mov ah, 1 + int 0x16 + jz not_avail + mov available, true + not_avail: + } + + return available; +} + + +bool EscKeyPressed () +{ + if (IsKeyboardCharAvailable ()) + { + byte keyScanCode; + GetKeyboardChar (&keyScanCode); + return keyScanCode == TC_BIOS_KEY_ESC; + } + + return false; +} + + +void ClearBiosKeystrokeBuffer () +{ + __asm + { + push es + xor ax, ax + mov es, ax + mov di, 0x41e + mov cx, 32 + cld + rep stosb + pop es + } +} + + +bool IsPrintable (char c) +{ + return c >= ' ' && c <= '~'; +} + +bool IsDigit (char c) +{ + return c >= '0' && c <= '9'; +} + + +int GetString (char *buffer, size_t bufferSize) +{ + byte c; + byte scanCode; + size_t pos = 0; + + while (pos < bufferSize) + { + c = GetKeyboardChar (&scanCode); + + if (scanCode == TC_BIOS_KEY_ENTER) + break; + + if (scanCode == TC_BIOS_KEY_ESC) + return 0; + + buffer[pos++] = c; + PrintChar (IsPrintable (c) ? c : ' '); + } + + return pos; +} diff --git a/src/Boot/Windows/BootConsoleIo.h b/src/Boot/Windows/BootConsoleIo.h index 6af75c05..b95036d5 100644 --- a/src/Boot/Windows/BootConsoleIo.h +++ b/src/Boot/Windows/BootConsoleIo.h @@ -1,72 +1,72 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Boot_BootConsoleIo -#define TC_HEADER_Boot_BootConsoleIo - -#include "Platform.h" - -#define TC_DEBUG_PORT 0 - -#define TC_BIOS_KEY_ESC 1 -#define TC_BIOS_KEY_BACKSPACE 14 -#define TC_BIOS_KEY_ENTER 28 -#define TC_BIOS_KEY_F1 0x3b -#define TC_BIOS_KEY_F2 0x3c -#define TC_BIOS_KEY_F3 0x3d -#define TC_BIOS_KEY_F4 0x3e -#define TC_BIOS_KEY_F5 0x3f -#define TC_BIOS_KEY_F6 0x40 -#define TC_BIOS_KEY_F7 0x41 -#define TC_BIOS_KEY_F8 0x42 -#define TC_BIOS_KEY_F9 0x43 -#define TC_BIOS_KEY_F10 0x44 - -#define TC_BIOS_SHIFTMASK_CAPSLOCK (1 << 6) -#define TC_BIOS_SHIFTMASK_LSHIFT (1 << 1) -#define TC_BIOS_SHIFTMASK_RSHIFT (1 << 0) - -#define TC_BIOS_CHAR_BACKSPACE 8 - -#define TC_BIOS_MAX_CHARS_PER_LINE 80 - -void Beep (); -void ClearBiosKeystrokeBuffer (); -void ClearScreen (); -void DisableScreenOutput (); -void EnableScreenOutput (); -bool EscKeyPressed (); -byte GetKeyboardChar (); -byte GetKeyboardChar (byte *scanCode); -byte GetShiftFlags (); -int GetString (char *buffer, size_t bufferSize); -void InitVideoMode (); -bool IsKeyboardCharAvailable (); -bool IsPrintable (char c); -bool IsDigit (char c); -void Print (const char *str); -void Print (uint32 number); -void Print (const uint64 &number); -void PrintBackspace (); -void PrintChar (char c); -void PrintCharAtCursor (char c); -void PrintEndl (); -void PrintEndl (int cnt); -void PrintRepeatedChar (char c, int n); -void PrintError (const char *message); -void PrintErrorNoEndl (const char *message); -void PrintHex (byte b); -void PrintHex (uint16 data); -void PrintHex (uint32 data); -void PrintHex (const uint64 &data); - -#endif // TC_HEADER_Boot_BootConsoleIo +/* + 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. +*/ + +#ifndef TC_HEADER_Boot_BootConsoleIo +#define TC_HEADER_Boot_BootConsoleIo + +#include "Platform.h" + +#define TC_DEBUG_PORT 0 + +#define TC_BIOS_KEY_ESC 1 +#define TC_BIOS_KEY_BACKSPACE 14 +#define TC_BIOS_KEY_ENTER 28 +#define TC_BIOS_KEY_F1 0x3b +#define TC_BIOS_KEY_F2 0x3c +#define TC_BIOS_KEY_F3 0x3d +#define TC_BIOS_KEY_F4 0x3e +#define TC_BIOS_KEY_F5 0x3f +#define TC_BIOS_KEY_F6 0x40 +#define TC_BIOS_KEY_F7 0x41 +#define TC_BIOS_KEY_F8 0x42 +#define TC_BIOS_KEY_F9 0x43 +#define TC_BIOS_KEY_F10 0x44 + +#define TC_BIOS_SHIFTMASK_CAPSLOCK (1 << 6) +#define TC_BIOS_SHIFTMASK_LSHIFT (1 << 1) +#define TC_BIOS_SHIFTMASK_RSHIFT (1 << 0) + +#define TC_BIOS_CHAR_BACKSPACE 8 + +#define TC_BIOS_MAX_CHARS_PER_LINE 80 + +void Beep (); +void ClearBiosKeystrokeBuffer (); +void ClearScreen (); +void DisableScreenOutput (); +void EnableScreenOutput (); +bool EscKeyPressed (); +byte GetKeyboardChar (); +byte GetKeyboardChar (byte *scanCode); +byte GetShiftFlags (); +int GetString (char *buffer, size_t bufferSize); +void InitVideoMode (); +bool IsKeyboardCharAvailable (); +bool IsPrintable (char c); +bool IsDigit (char c); +void Print (const char *str); +void Print (uint32 number); +void Print (const uint64 &number); +void PrintBackspace (); +void PrintChar (char c); +void PrintCharAtCursor (char c); +void PrintEndl (); +void PrintEndl (int cnt); +void PrintRepeatedChar (char c, int n); +void PrintError (const char *message); +void PrintErrorNoEndl (const char *message); +void PrintHex (byte b); +void PrintHex (uint16 data); +void PrintHex (uint32 data); +void PrintHex (const uint64 &data); + +#endif // TC_HEADER_Boot_BootConsoleIo diff --git a/src/Boot/Windows/BootCrt.asm b/src/Boot/Windows/BootCrt.asm index e309fcb0..fd2c2ef0 100644 --- a/src/Boot/Windows/BootCrt.asm +++ b/src/Boot/Windows/BootCrt.asm @@ -1,27 +1,27 @@ -; -; 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. -; - -.MODEL tiny, C -.386 - -INCLUDE BootDefs.i - -EXTERNDEF main:NEAR - -_TEXT SEGMENT -ORG TC_COM_EXECUTABLE_OFFSET - -start: - jmp main - -_TEXT ENDS -END start +; +; 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. +; + +.MODEL tiny, C +.386 + +INCLUDE BootDefs.i + +EXTERNDEF main:NEAR + +_TEXT SEGMENT +ORG TC_COM_EXECUTABLE_OFFSET + +start: + jmp main + +_TEXT ENDS +END start diff --git a/src/Boot/Windows/BootDebug.cpp b/src/Boot/Windows/BootDebug.cpp index 0f33ed5a..2c796437 100644 --- a/src/Boot/Windows/BootDebug.cpp +++ b/src/Boot/Windows/BootDebug.cpp @@ -1,181 +1,181 @@ -/* - 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 "Platform.h" -#include "Bios.h" -#include "BootConsoleIo.h" -#include "BootDefs.h" -#include "BootDiskIo.h" -#include "BootDebug.h" - - -#ifdef TC_BOOT_TRACING_ENABLED - -void InitDebugPort () -{ - __asm - { - mov dx, TC_DEBUG_PORT - mov ah, 1 - int 0x17 - mov dx, TC_DEBUG_PORT - mov ah, 0xe2 - int 0x17 - } -} - - -void WriteDebugPort (byte dataByte) -{ - __asm - { - mov al, dataByte - mov dx, TC_DEBUG_PORT - mov ah, 0 - int 0x17 - } -} - -#endif // TC_BOOT_TRACING_ENABLED - - -#ifdef TC_BOOT_DEBUG_ENABLED - -extern "C" void PrintDebug (uint32 debugVal) -{ - Print (debugVal); - PrintEndl(); -} - - -void PrintVal (const char *message, const uint32 value, bool newLine, bool hex) -{ - Print (message); - Print (": "); - - if (hex) - PrintHex (value); - else - Print (value); - - if (newLine) - PrintEndl(); -} - - -void PrintVal (const char *message, const uint64 &value, bool newLine, bool hex) -{ - Print (message); - Print (": "); - PrintHex (value); - if (newLine) - PrintEndl(); -} - - -void PrintHexDump (byte *mem, size_t size, uint16 *memSegment) -{ - const size_t width = 16; - for (size_t pos = 0; pos < size; ) - { - for (int pass = 1; pass <= 2; ++pass) - { - size_t i; - for (i = 0; i < width && pos < size; ++i) - { - byte dataByte; - if (memSegment) - { - __asm - { - push es - mov si, ss:memSegment - mov es, ss:[si] - mov si, ss:mem - add si, pos - mov al, es:[si] - mov dataByte, al - pop es - } - pos++; - } - else - dataByte = mem[pos++]; - - if (pass == 1) - { - PrintHex (dataByte); - PrintChar (' '); - } - else - PrintChar (IsPrintable (dataByte) ? dataByte : '.'); - } - - if (pass == 1) - { - pos -= i; - PrintChar (' '); - } - } - - PrintEndl (); - } -} - - -void PrintHexDump (uint16 memSegment, uint16 memOffset, size_t size) -{ - PrintHexDump ((byte *) memOffset, size, &memSegment); -} - -#endif // TC_BOOT_DEBUG_ENABLED - - -#ifdef TC_BOOT_STACK_CHECKING_ENABLED - -extern "C" char end[]; - -static void PrintStackInfo () -{ - uint16 spReg; - __asm mov spReg, sp - - Print ("Stack: "); Print (TC_BOOT_LOADER_STACK_TOP - spReg); - Print ("/"); Print (TC_BOOT_LOADER_STACK_TOP - (uint16) end); -} - - -void CheckStack () -{ - uint16 spReg; - __asm mov spReg, sp - - if (*(uint32 *) end != 0x12345678UL || spReg < (uint16) end) - { - __asm cli - __asm mov sp, TC_BOOT_LOADER_STACK_TOP - - PrintError ("Stack overflow"); - TC_THROW_FATAL_EXCEPTION; - } -} - - -void InitStackChecker () -{ - *(uint32 *) end = 0x12345678UL; - - PrintStackInfo(); - PrintEndl(); -} - -#endif // TC_BOOT_STACK_CHECKING_ENABLED +/* + 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 "Platform.h" +#include "Bios.h" +#include "BootConsoleIo.h" +#include "BootDefs.h" +#include "BootDiskIo.h" +#include "BootDebug.h" + + +#ifdef TC_BOOT_TRACING_ENABLED + +void InitDebugPort () +{ + __asm + { + mov dx, TC_DEBUG_PORT + mov ah, 1 + int 0x17 + mov dx, TC_DEBUG_PORT + mov ah, 0xe2 + int 0x17 + } +} + + +void WriteDebugPort (byte dataByte) +{ + __asm + { + mov al, dataByte + mov dx, TC_DEBUG_PORT + mov ah, 0 + int 0x17 + } +} + +#endif // TC_BOOT_TRACING_ENABLED + + +#ifdef TC_BOOT_DEBUG_ENABLED + +extern "C" void PrintDebug (uint32 debugVal) +{ + Print (debugVal); + PrintEndl(); +} + + +void PrintVal (const char *message, const uint32 value, bool newLine, bool hex) +{ + Print (message); + Print (": "); + + if (hex) + PrintHex (value); + else + Print (value); + + if (newLine) + PrintEndl(); +} + + +void PrintVal (const char *message, const uint64 &value, bool newLine, bool hex) +{ + Print (message); + Print (": "); + PrintHex (value); + if (newLine) + PrintEndl(); +} + + +void PrintHexDump (byte *mem, size_t size, uint16 *memSegment) +{ + const size_t width = 16; + for (size_t pos = 0; pos < size; ) + { + for (int pass = 1; pass <= 2; ++pass) + { + size_t i; + for (i = 0; i < width && pos < size; ++i) + { + byte dataByte; + if (memSegment) + { + __asm + { + push es + mov si, ss:memSegment + mov es, ss:[si] + mov si, ss:mem + add si, pos + mov al, es:[si] + mov dataByte, al + pop es + } + pos++; + } + else + dataByte = mem[pos++]; + + if (pass == 1) + { + PrintHex (dataByte); + PrintChar (' '); + } + else + PrintChar (IsPrintable (dataByte) ? dataByte : '.'); + } + + if (pass == 1) + { + pos -= i; + PrintChar (' '); + } + } + + PrintEndl (); + } +} + + +void PrintHexDump (uint16 memSegment, uint16 memOffset, size_t size) +{ + PrintHexDump ((byte *) memOffset, size, &memSegment); +} + +#endif // TC_BOOT_DEBUG_ENABLED + + +#ifdef TC_BOOT_STACK_CHECKING_ENABLED + +extern "C" char end[]; + +static void PrintStackInfo () +{ + uint16 spReg; + __asm mov spReg, sp + + Print ("Stack: "); Print (TC_BOOT_LOADER_STACK_TOP - spReg); + Print ("/"); Print (TC_BOOT_LOADER_STACK_TOP - (uint16) end); +} + + +void CheckStack () +{ + uint16 spReg; + __asm mov spReg, sp + + if (*(uint32 *) end != 0x12345678UL || spReg < (uint16) end) + { + __asm cli + __asm mov sp, TC_BOOT_LOADER_STACK_TOP + + PrintError ("Stack overflow"); + TC_THROW_FATAL_EXCEPTION; + } +} + + +void InitStackChecker () +{ + *(uint32 *) end = 0x12345678UL; + + PrintStackInfo(); + PrintEndl(); +} + +#endif // TC_BOOT_STACK_CHECKING_ENABLED diff --git a/src/Boot/Windows/BootDebug.h b/src/Boot/Windows/BootDebug.h index 138dcf62..a10c7fec 100644 --- a/src/Boot/Windows/BootDebug.h +++ b/src/Boot/Windows/BootDebug.h @@ -1,60 +1,60 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Boot_BootDebug -#define TC_HEADER_Boot_BootDebug - -#include "Platform.h" -#include "BootConsoleIo.h" - -#if 0 -# define TC_BOOT_DEBUG_ENABLED -#endif - -#if 0 || defined (TC_BOOT_DEBUG_ENABLED) -# define TC_BOOT_STACK_CHECKING_ENABLED - extern "C" void CheckStack (); -#else -# define CheckStack() -#endif - -#if 0 -# define TC_BOOT_TRACING_ENABLED -# if 1 -# define TC_TRACE_INT13 -# endif -# if 0 -# define TC_TRACE_INT15 -# endif -#endif - -#ifdef TC_BOOT_DEBUG_ENABLED -# define trace_point do { Print(__FILE__); PrintChar (':'); Print (TC_TO_STRING (__LINE__)); PrintEndl(); } while (false) -# define trace_val(VAL) PrintVal (#VAL, VAL); -# define trace_hex(VAL) do { Print (#VAL), PrintChar (':'); PrintHex (VAL); PrintEndl(); } while (false) -# define assert(COND) do { if (!(COND)) { trace_point; __asm jmp $ } } while (false) -#else -# define trace_point -# define trace_val(VAL) -# define trace_hex(VAL) -# define assert(COND) -#endif - -void InitDebugPort (); -void InitStackChecker (); -void WriteDebugPort (byte dataByte); -void PrintHexDump (byte *mem, size_t size, uint16 *memSegment = nullptr); -void PrintHexDump (uint16 memSegment, uint16 memOffset, size_t size); -void PrintVal (const char *message, const uint32 value, bool newLine = true, bool hex = false); -void PrintVal (const char *message, const uint64 &value, bool newLine = true, bool hex = false); - -#endif // TC_HEADER_Boot_BootDebug +/* + 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. +*/ + +#ifndef TC_HEADER_Boot_BootDebug +#define TC_HEADER_Boot_BootDebug + +#include "Platform.h" +#include "BootConsoleIo.h" + +#if 0 +# define TC_BOOT_DEBUG_ENABLED +#endif + +#if 0 || defined (TC_BOOT_DEBUG_ENABLED) +# define TC_BOOT_STACK_CHECKING_ENABLED + extern "C" void CheckStack (); +#else +# define CheckStack() +#endif + +#if 0 +# define TC_BOOT_TRACING_ENABLED +# if 1 +# define TC_TRACE_INT13 +# endif +# if 0 +# define TC_TRACE_INT15 +# endif +#endif + +#ifdef TC_BOOT_DEBUG_ENABLED +# define trace_point do { Print(__FILE__); PrintChar (':'); Print (TC_TO_STRING (__LINE__)); PrintEndl(); } while (false) +# define trace_val(VAL) PrintVal (#VAL, VAL); +# define trace_hex(VAL) do { Print (#VAL), PrintChar (':'); PrintHex (VAL); PrintEndl(); } while (false) +# define assert(COND) do { if (!(COND)) { trace_point; __asm jmp $ } } while (false) +#else +# define trace_point +# define trace_val(VAL) +# define trace_hex(VAL) +# define assert(COND) +#endif + +void InitDebugPort (); +void InitStackChecker (); +void WriteDebugPort (byte dataByte); +void PrintHexDump (byte *mem, size_t size, uint16 *memSegment = nullptr); +void PrintHexDump (uint16 memSegment, uint16 memOffset, size_t size); +void PrintVal (const char *message, const uint32 value, bool newLine = true, bool hex = false); +void PrintVal (const char *message, const uint64 &value, bool newLine = true, bool hex = false); + +#endif // TC_HEADER_Boot_BootDebug diff --git a/src/Boot/Windows/BootDefs.h b/src/Boot/Windows/BootDefs.h index 69c57dbc..2e69d5a3 100644 --- a/src/Boot/Windows/BootDefs.h +++ b/src/Boot/Windows/BootDefs.h @@ -1,199 +1,199 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Boot_BootDefs -#define TC_HEADER_Boot_BootDefs - -// Total memory required (CODE + DATA + BSS + STACK + 0x100) in KBytes - determined from linker map. -#define TC__BOOT_MEMORY_REQUIRED 43 - -#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE -# undef TC__BOOT_MEMORY_REQUIRED - -# ifdef TC_WINDOWS_BOOT_AES -# ifdef TC_WINDOWS_BOOT_RESCUE_DISK_MODE -# define TC__BOOT_MEMORY_REQUIRED 31 -# else -# define TC__BOOT_MEMORY_REQUIRED 29 -# endif -# elif defined (TC_WINDOWS_BOOT_SERPENT) -# define TC__BOOT_MEMORY_REQUIRED 33 -# elif defined (TC_WINDOWS_BOOT_TWOFISH) -# define TC__BOOT_MEMORY_REQUIRED 41 -# endif - -#if 0 -# undef TC__BOOT_MEMORY_REQUIRED -# define TC__BOOT_MEMORY_REQUIRED 60 -#endif - -#endif - -// Modifying this value can introduce incompatibility with previous versions -#define TC__BOOT_LOADER_SEGMENT TC_HEX (9000) // Some buggy BIOS routines fail if CS bits 0-10 are not zero - -#if TC__BOOT_MEMORY_REQUIRED <= 32 -# define TC__BOOT_LOADER_SEGMENT_LOW (TC__BOOT_LOADER_SEGMENT - 32 * 1024 / 16) -#else -# define TC__BOOT_LOADER_SEGMENT_LOW (TC__BOOT_LOADER_SEGMENT - 64 * 1024 / 16) -#endif - -#define TC__COM_EXECUTABLE_OFFSET TC_HEX (100) - -#define TC__BOOT_LOADER_LOWMEM_SEGMENT TC_HEX (2000) -#define TC__BOOT_LOADER_BUFFER_SEGMENT TC_HEX (4000) -#define TC__BOOT_LOADER_ALT_SEGMENT TC_HEX (6000) - -#define TC__BOOT_LOADER_STACK_TOP (TC_BOOT_MEMORY_REQUIRED * TC_UNSIGNED (1024) - 4) - -#define TC__LB_SIZE 512 -#define TC__BOOT_LOADER_AREA_SECTOR_COUNT 63 - -#define TC__BOOT_SECTOR_VERSION_OFFSET 430 -#define TC__BOOT_SECTOR_LOADER_LENGTH_OFFSET 432 -#define TC__BOOT_SECTOR_LOADER_CHECKSUM_OFFSET 434 -#define TC__BOOT_SECTOR_USER_CONFIG_OFFSET 438 -#define TC__BOOT_SECTOR_CONFIG_OFFSET 439 // The last byte that is reserved for the boot loader - -#define TC__BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH 24 -#define TC__BOOT_SECTOR_USER_MESSAGE_OFFSET (TC__BOOT_SECTOR_VERSION_OFFSET - TC__BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH) - -#define TC__BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE 4 -#define TC__BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET (TC__BOOT_SECTOR_USER_MESSAGE_OFFSET - TC__BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE) - -#define TC__BOOT_SECTOR_PIM_VALUE_SIZE 2 -#define TC__BOOT_SECTOR_PIM_VALUE_OFFSET (TC__BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET - TC__BOOT_SECTOR_PIM_VALUE_SIZE) - -#define TC__BOOT_LOADER_DECOMPRESSOR_START_SECTOR 2 -#define TC__BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT 4 -#define TC__BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE 32768 -#define TC__BOOT_LOADER_COMPRESSED_BUFFER_OFFSET (TC_COM_EXECUTABLE_OFFSET + 3072) - -#define TC__BOOT_LOADER_START_SECTOR (TC_BOOT_LOADER_DECOMPRESSOR_START_SECTOR + TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT) -#define TC__MAX_BOOT_LOADER_SECTOR_COUNT (TC_BOOT_LOADER_AREA_SECTOR_COUNT - TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT - 2) -#define TC__MAX_BOOT_LOADER_DECOMPRESSED_SIZE ((TC_BOOT_LOADER_AREA_SECTOR_COUNT - 2) * TC_LB_SIZE) - -#define TC__BOOT_LOADER_BACKUP_SECTOR_COUNT 30 - -#define TC__GZIP_HEADER_SIZE 10 - -#define TC__BOOT_CFG_FLAG_AREA_SIZE 1 // In bytes - -// If you add more flags, revise TC__BOOT_CFG_FLAG_AREA_SIZE -#define TC__BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE TC_HEX (02) -#define TC__BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER TC_HEX (04) -#define TC__BOOT_CFG_FLAG_RESCUE_DISABLE_HW_ENCRYPTION TC_HEX (10) -#define TC__BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER TC_HEX (20) -#define TC__BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE (TC_HEX (40) + TC_HEX (80)) - -// Modifying the following values can introduce incompatibility with previous versions -#define TC__BOOT_USER_CFG_FLAG_SILENT_MODE TC_HEX (01) -#define TC__BOOT_USER_CFG_FLAG_DISABLE_ESC TC_HEX (02) -#define TC__BOOT_USER_CFG_FLAG_DISABLE_HW_ENCRYPTION TC_HEX (04) -#define TC__BOOT_USER_CFG_FLAG_DISABLE_PIM TC_HEX (08) - -// The following items are treated as a 2-bit value (apply TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE to obtain the value) -#define TC__HIDDEN_OS_CREATION_PHASE_NONE 0 -#define TC__HIDDEN_OS_CREATION_PHASE_CLONING TC_HEX (40) // The boot loader is to copy the content of the system partition to the hidden volume -#define TC__HIDDEN_OS_CREATION_PHASE_WIPING TC_HEX (80) // The boot loader has successfully copied the content of the system partition to the hidden volume. The original OS is to be wiped now. -#define TC__HIDDEN_OS_CREATION_PHASE_WIPED (TC_HEX (40) + TC_HEX (80)) // The original OS has been wiped. The user is required to install a new OS (decoy OS) on the system partition now. - - -#ifdef TC_ASM_PREPROCESS - -#define TC_HEX(N) 0##N##h -#define TC_UNSIGNED(N) N - -TC_BOOT_MEMORY_REQUIRED = TC__BOOT_MEMORY_REQUIRED -TC_BOOT_LOADER_SEGMENT = TC__BOOT_LOADER_SEGMENT -TC_BOOT_LOADER_SEGMENT_LOW = TC__BOOT_LOADER_SEGMENT_LOW -TC_COM_EXECUTABLE_OFFSET = TC__COM_EXECUTABLE_OFFSET -TC_BOOT_LOADER_LOWMEM_SEGMENT = TC__BOOT_LOADER_LOWMEM_SEGMENT -TC_BOOT_LOADER_BUFFER_SEGMENT = TC__BOOT_LOADER_BUFFER_SEGMENT -TC_BOOT_LOADER_ALT_SEGMENT = TC__BOOT_LOADER_ALT_SEGMENT -TC_BOOT_LOADER_STACK_TOP = TC__BOOT_LOADER_STACK_TOP -TC_LB_SIZE = TC__LB_SIZE -TC_BOOT_LOADER_AREA_SECTOR_COUNT = TC__BOOT_LOADER_AREA_SECTOR_COUNT -TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET = TC__BOOT_SECTOR_LOADER_LENGTH_OFFSET -TC_BOOT_SECTOR_LOADER_CHECKSUM_OFFSET = TC__BOOT_SECTOR_LOADER_CHECKSUM_OFFSET -TC_BOOT_SECTOR_CONFIG_OFFSET = TC__BOOT_SECTOR_CONFIG_OFFSET -TC_BOOT_SECTOR_USER_CONFIG_OFFSET = TC__BOOT_SECTOR_USER_CONFIG_OFFSET -TC_BOOT_LOADER_DECOMPRESSOR_START_SECTOR = TC__BOOT_LOADER_DECOMPRESSOR_START_SECTOR -TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT = TC__BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT -TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE = TC__BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE -TC_BOOT_LOADER_COMPRESSED_BUFFER_OFFSET = TC__BOOT_LOADER_COMPRESSED_BUFFER_OFFSET -TC_BOOT_LOADER_START_SECTOR = TC__BOOT_LOADER_START_SECTOR -TC_MAX_BOOT_LOADER_SECTOR_COUNT = TC__MAX_BOOT_LOADER_SECTOR_COUNT -TC_MAX_BOOT_LOADER_DECOMPRESSED_SIZE = TC__MAX_BOOT_LOADER_DECOMPRESSED_SIZE -TC_BOOT_LOADER_BACKUP_SECTOR_COUNT = TC__BOOT_LOADER_BACKUP_SECTOR_COUNT -TC_GZIP_HEADER_SIZE = TC__GZIP_HEADER_SIZE -TC_BOOT_CFG_FLAG_AREA_SIZE = TC__BOOT_CFG_FLAG_AREA_SIZE -TC_BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE = TC__BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE -TC_BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER = TC__BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER -TC_BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER = TC__BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER -TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE = TC__BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE -TC_BOOT_USER_CFG_FLAG_SILENT_MODE = TC__BOOT_USER_CFG_FLAG_SILENT_MODE -TC_HIDDEN_OS_CREATION_PHASE_NONE = TC__HIDDEN_OS_CREATION_PHASE_NONE -TC_HIDDEN_OS_CREATION_PHASE_CLONING = TC__HIDDEN_OS_CREATION_PHASE_CLONING -TC_HIDDEN_OS_CREATION_PHASE_WIPING = TC__HIDDEN_OS_CREATION_PHASE_WIPING -TC_HIDDEN_OS_CREATION_PHASE_WIPED = TC__HIDDEN_OS_CREATION_PHASE_WIPED - -#else // TC_ASM_PREPROCESS - -#define TC_HEX(N) 0x##N -#define TC_UNSIGNED(N) N##U - -#define TC_BOOT_MEMORY_REQUIRED TC__BOOT_MEMORY_REQUIRED -#define TC_BOOT_LOADER_SEGMENT TC__BOOT_LOADER_SEGMENT -#define TC_COM_EXECUTABLE_OFFSET TC__COM_EXECUTABLE_OFFSET -#define TC_BOOT_LOADER_LOWMEM_SEGMENT TC__BOOT_LOADER_LOWMEM_SEGMENT -#define TC_BOOT_LOADER_BUFFER_SEGMENT TC__BOOT_LOADER_BUFFER_SEGMENT -#define TC_BOOT_LOADER_ALT_SEGMENT TC__BOOT_LOADER_ALT_SEGMENT -#define TC_BOOT_LOADER_STACK_TOP (TC__BOOT_LOADER_STACK_TOP) -#define TC_BOOT_LOADER_AREA_SECTOR_COUNT TC__BOOT_LOADER_AREA_SECTOR_COUNT -#define TC_BOOT_SECTOR_USER_MESSAGE_OFFSET TC__BOOT_SECTOR_USER_MESSAGE_OFFSET -#define TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE TC__BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE -#define TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET TC__BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET -#define TC_BOOT_SECTOR_PIM_VALUE_SIZE TC__BOOT_SECTOR_PIM_VALUE_SIZE -#define TC_BOOT_SECTOR_PIM_VALUE_OFFSET TC__BOOT_SECTOR_PIM_VALUE_OFFSET -#define TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH TC__BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH -#define TC_BOOT_SECTOR_VERSION_OFFSET TC__BOOT_SECTOR_VERSION_OFFSET -#define TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET TC__BOOT_SECTOR_LOADER_LENGTH_OFFSET -#define TC_BOOT_SECTOR_LOADER_CHECKSUM_OFFSET TC__BOOT_SECTOR_LOADER_CHECKSUM_OFFSET -#define TC_BOOT_LOADER_DECOMPRESSOR_START_SECTOR TC__BOOT_LOADER_DECOMPRESSOR_START_SECTOR -#define TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT TC__BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT -#define TC_BOOT_SECTOR_CONFIG_OFFSET TC__BOOT_SECTOR_CONFIG_OFFSET -#define TC_BOOT_SECTOR_USER_CONFIG_OFFSET TC__BOOT_SECTOR_USER_CONFIG_OFFSET -#define TC_BOOT_LOADER_START_SECTOR TC__BOOT_LOADER_START_SECTOR -#define TC_LB_SIZE TC__LB_SIZE -#define TC_MAX_BOOT_LOADER_SECTOR_COUNT TC__MAX_BOOT_LOADER_SECTOR_COUNT -#define TC_MAX_BOOT_LOADER_DECOMPRESSED_SIZE TC__MAX_BOOT_LOADER_DECOMPRESSED_SIZE -#define TC_BOOT_LOADER_BACKUP_SECTOR_COUNT TC__BOOT_LOADER_BACKUP_SECTOR_COUNT -#define TC_GZIP_HEADER_SIZE TC__GZIP_HEADER_SIZE -#define TC_BOOT_CFG_FLAG_AREA_SIZE TC__BOOT_CFG_FLAG_AREA_SIZE -#define TC_BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE TC__BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE -#define TC_BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER TC__BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER -#define TC_BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER TC__BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER -#define TC_BOOT_CFG_FLAG_RESCUE_DISABLE_HW_ENCRYPTION TC__BOOT_CFG_FLAG_RESCUE_DISABLE_HW_ENCRYPTION -#define TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE TC__BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE -#define TC_BOOT_USER_CFG_FLAG_SILENT_MODE TC__BOOT_USER_CFG_FLAG_SILENT_MODE -#define TC_BOOT_USER_CFG_FLAG_DISABLE_ESC TC__BOOT_USER_CFG_FLAG_DISABLE_ESC -#define TC_BOOT_USER_CFG_FLAG_DISABLE_HW_ENCRYPTION TC__BOOT_USER_CFG_FLAG_DISABLE_HW_ENCRYPTION -#define TC_BOOT_USER_CFG_FLAG_DISABLE_PIM TC__BOOT_USER_CFG_FLAG_DISABLE_PIM -#define TC_HIDDEN_OS_CREATION_PHASE_NONE TC__HIDDEN_OS_CREATION_PHASE_NONE -#define TC_HIDDEN_OS_CREATION_PHASE_CLONING TC__HIDDEN_OS_CREATION_PHASE_CLONING -#define TC_HIDDEN_OS_CREATION_PHASE_WIPING TC__HIDDEN_OS_CREATION_PHASE_WIPING -#define TC_HIDDEN_OS_CREATION_PHASE_WIPED TC__HIDDEN_OS_CREATION_PHASE_WIPED - -#endif // TC_ASM_PREPROCESS - -#endif // TC_HEADER_Boot_BootDefs +/* + 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. +*/ + +#ifndef TC_HEADER_Boot_BootDefs +#define TC_HEADER_Boot_BootDefs + +// Total memory required (CODE + DATA + BSS + STACK + 0x100) in KBytes - determined from linker map. +#define TC__BOOT_MEMORY_REQUIRED 43 + +#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE +# undef TC__BOOT_MEMORY_REQUIRED + +# ifdef TC_WINDOWS_BOOT_AES +# ifdef TC_WINDOWS_BOOT_RESCUE_DISK_MODE +# define TC__BOOT_MEMORY_REQUIRED 31 +# else +# define TC__BOOT_MEMORY_REQUIRED 29 +# endif +# elif defined (TC_WINDOWS_BOOT_SERPENT) +# define TC__BOOT_MEMORY_REQUIRED 33 +# elif defined (TC_WINDOWS_BOOT_TWOFISH) +# define TC__BOOT_MEMORY_REQUIRED 41 +# endif + +#if 0 +# undef TC__BOOT_MEMORY_REQUIRED +# define TC__BOOT_MEMORY_REQUIRED 60 +#endif + +#endif + +// Modifying this value can introduce incompatibility with previous versions +#define TC__BOOT_LOADER_SEGMENT TC_HEX (9000) // Some buggy BIOS routines fail if CS bits 0-10 are not zero + +#if TC__BOOT_MEMORY_REQUIRED <= 32 +# define TC__BOOT_LOADER_SEGMENT_LOW (TC__BOOT_LOADER_SEGMENT - 32 * 1024 / 16) +#else +# define TC__BOOT_LOADER_SEGMENT_LOW (TC__BOOT_LOADER_SEGMENT - 64 * 1024 / 16) +#endif + +#define TC__COM_EXECUTABLE_OFFSET TC_HEX (100) + +#define TC__BOOT_LOADER_LOWMEM_SEGMENT TC_HEX (2000) +#define TC__BOOT_LOADER_BUFFER_SEGMENT TC_HEX (4000) +#define TC__BOOT_LOADER_ALT_SEGMENT TC_HEX (6000) + +#define TC__BOOT_LOADER_STACK_TOP (TC_BOOT_MEMORY_REQUIRED * TC_UNSIGNED (1024) - 4) + +#define TC__LB_SIZE 512 +#define TC__BOOT_LOADER_AREA_SECTOR_COUNT 63 + +#define TC__BOOT_SECTOR_VERSION_OFFSET 430 +#define TC__BOOT_SECTOR_LOADER_LENGTH_OFFSET 432 +#define TC__BOOT_SECTOR_LOADER_CHECKSUM_OFFSET 434 +#define TC__BOOT_SECTOR_USER_CONFIG_OFFSET 438 +#define TC__BOOT_SECTOR_CONFIG_OFFSET 439 // The last byte that is reserved for the boot loader + +#define TC__BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH 24 +#define TC__BOOT_SECTOR_USER_MESSAGE_OFFSET (TC__BOOT_SECTOR_VERSION_OFFSET - TC__BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH) + +#define TC__BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE 4 +#define TC__BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET (TC__BOOT_SECTOR_USER_MESSAGE_OFFSET - TC__BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE) + +#define TC__BOOT_SECTOR_PIM_VALUE_SIZE 2 +#define TC__BOOT_SECTOR_PIM_VALUE_OFFSET (TC__BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET - TC__BOOT_SECTOR_PIM_VALUE_SIZE) + +#define TC__BOOT_LOADER_DECOMPRESSOR_START_SECTOR 2 +#define TC__BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT 4 +#define TC__BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE 32768 +#define TC__BOOT_LOADER_COMPRESSED_BUFFER_OFFSET (TC_COM_EXECUTABLE_OFFSET + 3072) + +#define TC__BOOT_LOADER_START_SECTOR (TC_BOOT_LOADER_DECOMPRESSOR_START_SECTOR + TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT) +#define TC__MAX_BOOT_LOADER_SECTOR_COUNT (TC_BOOT_LOADER_AREA_SECTOR_COUNT - TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT - 2) +#define TC__MAX_BOOT_LOADER_DECOMPRESSED_SIZE ((TC_BOOT_LOADER_AREA_SECTOR_COUNT - 2) * TC_LB_SIZE) + +#define TC__BOOT_LOADER_BACKUP_SECTOR_COUNT 30 + +#define TC__GZIP_HEADER_SIZE 10 + +#define TC__BOOT_CFG_FLAG_AREA_SIZE 1 // In bytes + +// If you add more flags, revise TC__BOOT_CFG_FLAG_AREA_SIZE +#define TC__BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE TC_HEX (02) +#define TC__BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER TC_HEX (04) +#define TC__BOOT_CFG_FLAG_RESCUE_DISABLE_HW_ENCRYPTION TC_HEX (10) +#define TC__BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER TC_HEX (20) +#define TC__BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE (TC_HEX (40) + TC_HEX (80)) + +// Modifying the following values can introduce incompatibility with previous versions +#define TC__BOOT_USER_CFG_FLAG_SILENT_MODE TC_HEX (01) +#define TC__BOOT_USER_CFG_FLAG_DISABLE_ESC TC_HEX (02) +#define TC__BOOT_USER_CFG_FLAG_DISABLE_HW_ENCRYPTION TC_HEX (04) +#define TC__BOOT_USER_CFG_FLAG_DISABLE_PIM TC_HEX (08) + +// The following items are treated as a 2-bit value (apply TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE to obtain the value) +#define TC__HIDDEN_OS_CREATION_PHASE_NONE 0 +#define TC__HIDDEN_OS_CREATION_PHASE_CLONING TC_HEX (40) // The boot loader is to copy the content of the system partition to the hidden volume +#define TC__HIDDEN_OS_CREATION_PHASE_WIPING TC_HEX (80) // The boot loader has successfully copied the content of the system partition to the hidden volume. The original OS is to be wiped now. +#define TC__HIDDEN_OS_CREATION_PHASE_WIPED (TC_HEX (40) + TC_HEX (80)) // The original OS has been wiped. The user is required to install a new OS (decoy OS) on the system partition now. + + +#ifdef TC_ASM_PREPROCESS + +#define TC_HEX(N) 0##N##h +#define TC_UNSIGNED(N) N + +TC_BOOT_MEMORY_REQUIRED = TC__BOOT_MEMORY_REQUIRED +TC_BOOT_LOADER_SEGMENT = TC__BOOT_LOADER_SEGMENT +TC_BOOT_LOADER_SEGMENT_LOW = TC__BOOT_LOADER_SEGMENT_LOW +TC_COM_EXECUTABLE_OFFSET = TC__COM_EXECUTABLE_OFFSET +TC_BOOT_LOADER_LOWMEM_SEGMENT = TC__BOOT_LOADER_LOWMEM_SEGMENT +TC_BOOT_LOADER_BUFFER_SEGMENT = TC__BOOT_LOADER_BUFFER_SEGMENT +TC_BOOT_LOADER_ALT_SEGMENT = TC__BOOT_LOADER_ALT_SEGMENT +TC_BOOT_LOADER_STACK_TOP = TC__BOOT_LOADER_STACK_TOP +TC_LB_SIZE = TC__LB_SIZE +TC_BOOT_LOADER_AREA_SECTOR_COUNT = TC__BOOT_LOADER_AREA_SECTOR_COUNT +TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET = TC__BOOT_SECTOR_LOADER_LENGTH_OFFSET +TC_BOOT_SECTOR_LOADER_CHECKSUM_OFFSET = TC__BOOT_SECTOR_LOADER_CHECKSUM_OFFSET +TC_BOOT_SECTOR_CONFIG_OFFSET = TC__BOOT_SECTOR_CONFIG_OFFSET +TC_BOOT_SECTOR_USER_CONFIG_OFFSET = TC__BOOT_SECTOR_USER_CONFIG_OFFSET +TC_BOOT_LOADER_DECOMPRESSOR_START_SECTOR = TC__BOOT_LOADER_DECOMPRESSOR_START_SECTOR +TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT = TC__BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT +TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE = TC__BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE +TC_BOOT_LOADER_COMPRESSED_BUFFER_OFFSET = TC__BOOT_LOADER_COMPRESSED_BUFFER_OFFSET +TC_BOOT_LOADER_START_SECTOR = TC__BOOT_LOADER_START_SECTOR +TC_MAX_BOOT_LOADER_SECTOR_COUNT = TC__MAX_BOOT_LOADER_SECTOR_COUNT +TC_MAX_BOOT_LOADER_DECOMPRESSED_SIZE = TC__MAX_BOOT_LOADER_DECOMPRESSED_SIZE +TC_BOOT_LOADER_BACKUP_SECTOR_COUNT = TC__BOOT_LOADER_BACKUP_SECTOR_COUNT +TC_GZIP_HEADER_SIZE = TC__GZIP_HEADER_SIZE +TC_BOOT_CFG_FLAG_AREA_SIZE = TC__BOOT_CFG_FLAG_AREA_SIZE +TC_BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE = TC__BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE +TC_BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER = TC__BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER +TC_BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER = TC__BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER +TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE = TC__BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE +TC_BOOT_USER_CFG_FLAG_SILENT_MODE = TC__BOOT_USER_CFG_FLAG_SILENT_MODE +TC_HIDDEN_OS_CREATION_PHASE_NONE = TC__HIDDEN_OS_CREATION_PHASE_NONE +TC_HIDDEN_OS_CREATION_PHASE_CLONING = TC__HIDDEN_OS_CREATION_PHASE_CLONING +TC_HIDDEN_OS_CREATION_PHASE_WIPING = TC__HIDDEN_OS_CREATION_PHASE_WIPING +TC_HIDDEN_OS_CREATION_PHASE_WIPED = TC__HIDDEN_OS_CREATION_PHASE_WIPED + +#else // TC_ASM_PREPROCESS + +#define TC_HEX(N) 0x##N +#define TC_UNSIGNED(N) N##U + +#define TC_BOOT_MEMORY_REQUIRED TC__BOOT_MEMORY_REQUIRED +#define TC_BOOT_LOADER_SEGMENT TC__BOOT_LOADER_SEGMENT +#define TC_COM_EXECUTABLE_OFFSET TC__COM_EXECUTABLE_OFFSET +#define TC_BOOT_LOADER_LOWMEM_SEGMENT TC__BOOT_LOADER_LOWMEM_SEGMENT +#define TC_BOOT_LOADER_BUFFER_SEGMENT TC__BOOT_LOADER_BUFFER_SEGMENT +#define TC_BOOT_LOADER_ALT_SEGMENT TC__BOOT_LOADER_ALT_SEGMENT +#define TC_BOOT_LOADER_STACK_TOP (TC__BOOT_LOADER_STACK_TOP) +#define TC_BOOT_LOADER_AREA_SECTOR_COUNT TC__BOOT_LOADER_AREA_SECTOR_COUNT +#define TC_BOOT_SECTOR_USER_MESSAGE_OFFSET TC__BOOT_SECTOR_USER_MESSAGE_OFFSET +#define TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE TC__BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE +#define TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET TC__BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET +#define TC_BOOT_SECTOR_PIM_VALUE_SIZE TC__BOOT_SECTOR_PIM_VALUE_SIZE +#define TC_BOOT_SECTOR_PIM_VALUE_OFFSET TC__BOOT_SECTOR_PIM_VALUE_OFFSET +#define TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH TC__BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH +#define TC_BOOT_SECTOR_VERSION_OFFSET TC__BOOT_SECTOR_VERSION_OFFSET +#define TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET TC__BOOT_SECTOR_LOADER_LENGTH_OFFSET +#define TC_BOOT_SECTOR_LOADER_CHECKSUM_OFFSET TC__BOOT_SECTOR_LOADER_CHECKSUM_OFFSET +#define TC_BOOT_LOADER_DECOMPRESSOR_START_SECTOR TC__BOOT_LOADER_DECOMPRESSOR_START_SECTOR +#define TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT TC__BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT +#define TC_BOOT_SECTOR_CONFIG_OFFSET TC__BOOT_SECTOR_CONFIG_OFFSET +#define TC_BOOT_SECTOR_USER_CONFIG_OFFSET TC__BOOT_SECTOR_USER_CONFIG_OFFSET +#define TC_BOOT_LOADER_START_SECTOR TC__BOOT_LOADER_START_SECTOR +#define TC_LB_SIZE TC__LB_SIZE +#define TC_MAX_BOOT_LOADER_SECTOR_COUNT TC__MAX_BOOT_LOADER_SECTOR_COUNT +#define TC_MAX_BOOT_LOADER_DECOMPRESSED_SIZE TC__MAX_BOOT_LOADER_DECOMPRESSED_SIZE +#define TC_BOOT_LOADER_BACKUP_SECTOR_COUNT TC__BOOT_LOADER_BACKUP_SECTOR_COUNT +#define TC_GZIP_HEADER_SIZE TC__GZIP_HEADER_SIZE +#define TC_BOOT_CFG_FLAG_AREA_SIZE TC__BOOT_CFG_FLAG_AREA_SIZE +#define TC_BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE TC__BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE +#define TC_BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER TC__BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER +#define TC_BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER TC__BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER +#define TC_BOOT_CFG_FLAG_RESCUE_DISABLE_HW_ENCRYPTION TC__BOOT_CFG_FLAG_RESCUE_DISABLE_HW_ENCRYPTION +#define TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE TC__BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE +#define TC_BOOT_USER_CFG_FLAG_SILENT_MODE TC__BOOT_USER_CFG_FLAG_SILENT_MODE +#define TC_BOOT_USER_CFG_FLAG_DISABLE_ESC TC__BOOT_USER_CFG_FLAG_DISABLE_ESC +#define TC_BOOT_USER_CFG_FLAG_DISABLE_HW_ENCRYPTION TC__BOOT_USER_CFG_FLAG_DISABLE_HW_ENCRYPTION +#define TC_BOOT_USER_CFG_FLAG_DISABLE_PIM TC__BOOT_USER_CFG_FLAG_DISABLE_PIM +#define TC_HIDDEN_OS_CREATION_PHASE_NONE TC__HIDDEN_OS_CREATION_PHASE_NONE +#define TC_HIDDEN_OS_CREATION_PHASE_CLONING TC__HIDDEN_OS_CREATION_PHASE_CLONING +#define TC_HIDDEN_OS_CREATION_PHASE_WIPING TC__HIDDEN_OS_CREATION_PHASE_WIPING +#define TC_HIDDEN_OS_CREATION_PHASE_WIPED TC__HIDDEN_OS_CREATION_PHASE_WIPED + +#endif // TC_ASM_PREPROCESS + +#endif // TC_HEADER_Boot_BootDefs diff --git a/src/Boot/Windows/BootDiskIo.cpp b/src/Boot/Windows/BootDiskIo.cpp index 31917a64..bf3fe9fc 100644 --- a/src/Boot/Windows/BootDiskIo.cpp +++ b/src/Boot/Windows/BootDiskIo.cpp @@ -1,491 +1,491 @@ -/* - 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 "Bios.h" -#include "BootConsoleIo.h" -#include "BootConfig.h" -#include "BootDebug.h" -#include "BootDefs.h" -#include "BootDiskIo.h" -#include "BootStrings.h" - - -byte SectorBuffer[TC_LB_SIZE]; - -#ifdef TC_BOOT_DEBUG_ENABLED -static bool SectorBufferInUse = false; - -void AcquireSectorBuffer () -{ - if (SectorBufferInUse) - TC_THROW_FATAL_EXCEPTION; - - SectorBufferInUse = true; -} - - -void ReleaseSectorBuffer () -{ - SectorBufferInUse = false; -} - -#endif - - -bool IsLbaSupported (byte drive) -{ - static byte CachedDrive = TC_INVALID_BIOS_DRIVE; - static bool CachedStatus; - uint16 result = 0; - - if (CachedDrive == drive) - goto ret; - - __asm - { - mov bx, 0x55aa - mov dl, drive - mov ah, 0x41 - int 0x13 - jc err - mov result, bx - err: - } - - CachedDrive = drive; - CachedStatus = (result == 0xaa55); -ret: - return CachedStatus; -} - - -void PrintDiskError (BiosResult error, bool write, byte drive, const uint64 *sector, const ChsAddress *chs) -{ - PrintEndl(); - Print (write ? "Write" : "Read"); Print (" error:"); - Print (error); - Print (" Drive:"); - Print (drive ^ 0x80); - - if (sector) - { - Print (" Sector:"); - Print (*sector); - } - - if (chs) - { - Print (" CHS:"); - Print (*chs); - } - - PrintEndl(); - Beep(); -} - - -void Print (const ChsAddress &chs) -{ - Print (chs.Cylinder); - PrintChar ('/'); - Print (chs.Head); - PrintChar ('/'); - Print (chs.Sector); -} - - -void PrintSectorCountInMB (const uint64 §orCount) -{ - Print (sectorCount >> (TC_LB_SIZE_BIT_SHIFT_DIVISOR + 2)); Print (" MB "); -} - - -BiosResult ReadWriteSectors (bool write, uint16 bufferSegment, uint16 bufferOffset, byte drive, const ChsAddress &chs, byte sectorCount, bool silent) -{ - CheckStack(); - - byte cylinderLow = (byte) chs.Cylinder; - byte sector = chs.Sector; - sector |= byte (chs.Cylinder >> 2) & 0xc0; - byte function = write ? 0x03 : 0x02; - - BiosResult result; - byte tryCount = TC_MAX_BIOS_DISK_IO_RETRIES; - - do - { - result = BiosResultSuccess; - - __asm - { - push es - mov ax, bufferSegment - mov es, ax - mov bx, bufferOffset - mov dl, drive - mov ch, cylinderLow - mov si, chs - mov dh, [si].Head - mov cl, sector - mov al, sectorCount - mov ah, function - int 0x13 - jnc ok // If CF=0, ignore AH to prevent issues caused by potential bugs in BIOSes - mov result, ah - ok: - pop es - } - - if (result == BiosResultEccCorrected) - result = BiosResultSuccess; - - // Some BIOSes report I/O errors prematurely in some cases - } while (result != BiosResultSuccess && --tryCount != 0); - - if (!silent && result != BiosResultSuccess) - PrintDiskError (result, write, drive, nullptr, &chs); - - return result; -} - - -BiosResult ReadWriteSectors (bool write, byte *buffer, byte drive, const ChsAddress &chs, byte sectorCount, bool silent) -{ - uint16 codeSeg; - __asm mov codeSeg, cs - return ReadWriteSectors (write, codeSeg, (uint16) buffer, drive, chs, sectorCount, silent); -} - - -BiosResult ReadSectors (byte *buffer, byte drive, const ChsAddress &chs, byte sectorCount, bool silent) -{ - return ReadWriteSectors (false, buffer, drive, chs, sectorCount, silent); -} - - -BiosResult WriteSectors (byte *buffer, byte drive, const ChsAddress &chs, byte sectorCount, bool silent) -{ - return ReadWriteSectors (true, buffer, drive, chs, sectorCount, silent); -} - - -static BiosResult ReadWriteSectors (bool write, BiosLbaPacket &dapPacket, byte drive, const uint64 §or, uint16 sectorCount, bool silent) -{ - CheckStack(); - - if (!IsLbaSupported (drive)) - { - DriveGeometry geometry; - - BiosResult result = GetDriveGeometry (drive, geometry, silent); - if (result != BiosResultSuccess) - return result; - - ChsAddress chs; - LbaToChs (geometry, sector, chs); - return ReadWriteSectors (write, (uint16) (dapPacket.Buffer >> 16), (uint16) dapPacket.Buffer, drive, chs, sectorCount, silent); - } - - dapPacket.Size = sizeof (dapPacket); - dapPacket.Reserved = 0; - dapPacket.SectorCount = sectorCount; - dapPacket.Sector = sector; - - byte function = write ? 0x43 : 0x42; - - BiosResult result; - byte tryCount = TC_MAX_BIOS_DISK_IO_RETRIES; - - do - { - result = BiosResultSuccess; - - __asm - { - mov bx, 0x55aa - mov dl, drive - mov si, [dapPacket] - mov ah, function - xor al, al - int 0x13 - jnc ok // If CF=0, ignore AH to prevent issues caused by potential bugs in BIOSes - mov result, ah - ok: - } - - if (result == BiosResultEccCorrected) - result = BiosResultSuccess; - - // Some BIOSes report I/O errors prematurely in some cases - } while (result != BiosResultSuccess && --tryCount != 0); - - if (!silent && result != BiosResultSuccess) - PrintDiskError (result, write, drive, §or); - - return result; -} - - -static BiosResult ReadWriteSectors (bool write, byte *buffer, byte drive, const uint64 §or, uint16 sectorCount, bool silent) -{ - BiosLbaPacket dapPacket; - dapPacket.Buffer = (uint32) buffer; - return ReadWriteSectors (write, dapPacket, drive, sector, sectorCount, silent); -} - - -BiosResult ReadWriteSectors (bool write, uint16 bufferSegment, uint16 bufferOffset, byte drive, const uint64 §or, uint16 sectorCount, bool silent) -{ - BiosLbaPacket dapPacket; - dapPacket.Buffer = ((uint32) bufferSegment << 16) | bufferOffset; - return ReadWriteSectors (write, dapPacket, drive, sector, sectorCount, silent); -} - -BiosResult ReadSectors (uint16 bufferSegment, uint16 bufferOffset, byte drive, const uint64 §or, uint16 sectorCount, bool silent) -{ - return ReadWriteSectors (false, bufferSegment, bufferOffset, drive, sector, sectorCount, silent); -} - - -BiosResult ReadSectors (byte *buffer, byte drive, const uint64 §or, uint16 sectorCount, bool silent) -{ - BiosResult result; - uint16 codeSeg; - __asm mov codeSeg, cs - - result = ReadSectors (BootStarted ? codeSeg : TC_BOOT_LOADER_ALT_SEGMENT, (uint16) buffer, drive, sector, sectorCount, silent); - - // Alternative segment is used to prevent memory corruption caused by buggy BIOSes - if (!BootStarted) - CopyMemory (TC_BOOT_LOADER_ALT_SEGMENT, (uint16) buffer, buffer, sectorCount * TC_LB_SIZE); - - return result; -} - - -BiosResult WriteSectors (byte *buffer, byte drive, const uint64 §or, uint16 sectorCount, bool silent) -{ - return ReadWriteSectors (true, buffer, drive, sector, sectorCount, silent); -} - - -BiosResult GetDriveGeometry (byte drive, DriveGeometry &geometry, bool silent) -{ - CheckStack(); - - byte maxCylinderLow, maxHead, maxSector; - BiosResult result; - __asm - { - push es - mov dl, drive - mov ah, 0x08 - int 0x13 - - mov result, ah - mov maxCylinderLow, ch - mov maxSector, cl - mov maxHead, dh - pop es - } - - if (result == BiosResultSuccess) - { - geometry.Cylinders = (maxCylinderLow | (uint16 (maxSector & 0xc0) << 2)) + 1; - geometry.Heads = maxHead + 1; - geometry.Sectors = maxSector & ~0xc0; - } - else if (!silent) - { - Print ("Drive "); - Print (drive ^ 0x80); - Print (" not found: "); - PrintErrorNoEndl (""); - Print (result); - PrintEndl(); - } - - return result; -} - - -void ChsToLba (const DriveGeometry &geometry, const ChsAddress &chs, uint64 &lba) -{ - lba.HighPart = 0; - lba.LowPart = (uint32 (chs.Cylinder) * geometry.Heads + chs.Head) * geometry.Sectors + chs.Sector - 1; -} - - -void LbaToChs (const DriveGeometry &geometry, const uint64 &lba, ChsAddress &chs) -{ - chs.Sector = (byte) ((lba.LowPart % geometry.Sectors) + 1); - uint32 ch = lba.LowPart / geometry.Sectors; - chs.Head = (byte) (ch % geometry.Heads); - chs.Cylinder = (uint16) (ch / geometry.Heads); -} - - -void PartitionEntryMBRToPartition (const PartitionEntryMBR &partEntry, Partition &partition) -{ - partition.Active = partEntry.BootIndicator == 0x80; - partition.EndSector.HighPart = 0; - partition.EndSector.LowPart = partEntry.StartLBA + partEntry.SectorCountLBA - 1; - partition.SectorCount.HighPart = 0; - partition.SectorCount.LowPart = partEntry.SectorCountLBA; - partition.StartSector.HighPart = 0; - partition.StartSector.LowPart = partEntry.StartLBA; - partition.Type = partEntry.Type; -} - - -BiosResult ReadWriteMBR (bool write, byte drive, bool silent) -{ - uint64 mbrSector; - mbrSector.HighPart = 0; - mbrSector.LowPart = 0; - - if (write) - return WriteSectors (SectorBuffer, drive, mbrSector, 1, silent); - - return ReadSectors (SectorBuffer, drive, mbrSector, 1, silent); // Uses alternative segment -} - - -BiosResult GetDrivePartitions (byte drive, Partition *partitionArray, size_t partitionArrayCapacity, size_t &partitionCount, bool activeOnly, Partition *findPartitionFollowingThis, bool silent) -{ - Partition *followingPartition; - Partition tmpPartition; - - if (findPartitionFollowingThis) - { - assert (partitionArrayCapacity == 1); - partitionArrayCapacity = 0xff; - followingPartition = partitionArray; - partitionArray = &tmpPartition; - - followingPartition->Drive = TC_INVALID_BIOS_DRIVE; - followingPartition->StartSector.LowPart = 0xFFFFffffUL; - } - - AcquireSectorBuffer(); - BiosResult result = ReadWriteMBR (false, drive, silent); - ReleaseSectorBuffer(); - - partitionCount = 0; - - MBR *mbr = (MBR *) SectorBuffer; - if (result != BiosResultSuccess || mbr->Signature != 0xaa55) - return result; - - PartitionEntryMBR mbrPartitions[4]; - memcpy (mbrPartitions, mbr->Partitions, sizeof (mbrPartitions)); - size_t partitionArrayPos = 0, partitionNumber; - - for (partitionNumber = 0; - partitionNumber < array_capacity (mbrPartitions) && partitionArrayPos < partitionArrayCapacity; - ++partitionNumber) - { - const PartitionEntryMBR &partEntry = mbrPartitions[partitionNumber]; - - if (partEntry.SectorCountLBA > 0) - { - Partition &partition = partitionArray[partitionArrayPos]; - PartitionEntryMBRToPartition (partEntry, partition); - - if (activeOnly && !partition.Active) - continue; - - partition.Drive = drive; - partition.Number = partitionArrayPos; - - if (partEntry.Type == 0x5 || partEntry.Type == 0xf) // Extended partition - { - if (IsLbaSupported (drive)) - { - // Find all extended partitions - uint64 firstExtStartLBA = partition.StartSector; - uint64 extStartLBA = partition.StartSector; - MBR *extMbr = (MBR *) SectorBuffer; - - while (partitionArrayPos < partitionArrayCapacity && - (result = ReadSectors ((byte *) extMbr, drive, extStartLBA, 1, silent)) == BiosResultSuccess - && extMbr->Signature == 0xaa55) - { - if (extMbr->Partitions[0].SectorCountLBA > 0) - { - Partition &logPart = partitionArray[partitionArrayPos]; - PartitionEntryMBRToPartition (extMbr->Partitions[0], logPart); - logPart.Drive = drive; - - logPart.Number = partitionArrayPos; - logPart.Primary = false; - - logPart.StartSector.LowPart += extStartLBA.LowPart; - logPart.EndSector.LowPart += extStartLBA.LowPart; - - if (findPartitionFollowingThis) - { - if (logPart.StartSector.LowPart > findPartitionFollowingThis->EndSector.LowPart - && logPart.StartSector.LowPart < followingPartition->StartSector.LowPart) - { - *followingPartition = logPart; - } - } - else - ++partitionArrayPos; - } - - // Secondary extended - if (extMbr->Partitions[1].Type != 0x5 && extMbr->Partitions[1].Type == 0xf - || extMbr->Partitions[1].SectorCountLBA == 0) - break; - - extStartLBA.LowPart = extMbr->Partitions[1].StartLBA + firstExtStartLBA.LowPart; - } - } - } - else - { - partition.Primary = true; - - if (findPartitionFollowingThis) - { - if (partition.StartSector.LowPart > findPartitionFollowingThis->EndSector.LowPart - && partition.StartSector.LowPart < followingPartition->StartSector.LowPart) - { - *followingPartition = partition; - } - } - else - ++partitionArrayPos; - } - } - } - - partitionCount = partitionArrayPos; - return result; -} - - -bool GetActivePartition (byte drive) -{ - size_t partCount; - - if (GetDrivePartitions (drive, &ActivePartition, 1, partCount, true) != BiosResultSuccess || partCount < 1) - { - ActivePartition.Drive = TC_INVALID_BIOS_DRIVE; - PrintError (TC_BOOT_STR_NO_BOOT_PARTITION); - return false; - } - - return true; -} +/* + 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 "Bios.h" +#include "BootConsoleIo.h" +#include "BootConfig.h" +#include "BootDebug.h" +#include "BootDefs.h" +#include "BootDiskIo.h" +#include "BootStrings.h" + + +byte SectorBuffer[TC_LB_SIZE]; + +#ifdef TC_BOOT_DEBUG_ENABLED +static bool SectorBufferInUse = false; + +void AcquireSectorBuffer () +{ + if (SectorBufferInUse) + TC_THROW_FATAL_EXCEPTION; + + SectorBufferInUse = true; +} + + +void ReleaseSectorBuffer () +{ + SectorBufferInUse = false; +} + +#endif + + +bool IsLbaSupported (byte drive) +{ + static byte CachedDrive = TC_INVALID_BIOS_DRIVE; + static bool CachedStatus; + uint16 result = 0; + + if (CachedDrive == drive) + goto ret; + + __asm + { + mov bx, 0x55aa + mov dl, drive + mov ah, 0x41 + int 0x13 + jc err + mov result, bx + err: + } + + CachedDrive = drive; + CachedStatus = (result == 0xaa55); +ret: + return CachedStatus; +} + + +void PrintDiskError (BiosResult error, bool write, byte drive, const uint64 *sector, const ChsAddress *chs) +{ + PrintEndl(); + Print (write ? "Write" : "Read"); Print (" error:"); + Print (error); + Print (" Drive:"); + Print (drive ^ 0x80); + + if (sector) + { + Print (" Sector:"); + Print (*sector); + } + + if (chs) + { + Print (" CHS:"); + Print (*chs); + } + + PrintEndl(); + Beep(); +} + + +void Print (const ChsAddress &chs) +{ + Print (chs.Cylinder); + PrintChar ('/'); + Print (chs.Head); + PrintChar ('/'); + Print (chs.Sector); +} + + +void PrintSectorCountInMB (const uint64 §orCount) +{ + Print (sectorCount >> (TC_LB_SIZE_BIT_SHIFT_DIVISOR + 2)); Print (" MB "); +} + + +BiosResult ReadWriteSectors (bool write, uint16 bufferSegment, uint16 bufferOffset, byte drive, const ChsAddress &chs, byte sectorCount, bool silent) +{ + CheckStack(); + + byte cylinderLow = (byte) chs.Cylinder; + byte sector = chs.Sector; + sector |= byte (chs.Cylinder >> 2) & 0xc0; + byte function = write ? 0x03 : 0x02; + + BiosResult result; + byte tryCount = TC_MAX_BIOS_DISK_IO_RETRIES; + + do + { + result = BiosResultSuccess; + + __asm + { + push es + mov ax, bufferSegment + mov es, ax + mov bx, bufferOffset + mov dl, drive + mov ch, cylinderLow + mov si, chs + mov dh, [si].Head + mov cl, sector + mov al, sectorCount + mov ah, function + int 0x13 + jnc ok // If CF=0, ignore AH to prevent issues caused by potential bugs in BIOSes + mov result, ah + ok: + pop es + } + + if (result == BiosResultEccCorrected) + result = BiosResultSuccess; + + // Some BIOSes report I/O errors prematurely in some cases + } while (result != BiosResultSuccess && --tryCount != 0); + + if (!silent && result != BiosResultSuccess) + PrintDiskError (result, write, drive, nullptr, &chs); + + return result; +} + + +BiosResult ReadWriteSectors (bool write, byte *buffer, byte drive, const ChsAddress &chs, byte sectorCount, bool silent) +{ + uint16 codeSeg; + __asm mov codeSeg, cs + return ReadWriteSectors (write, codeSeg, (uint16) buffer, drive, chs, sectorCount, silent); +} + + +BiosResult ReadSectors (byte *buffer, byte drive, const ChsAddress &chs, byte sectorCount, bool silent) +{ + return ReadWriteSectors (false, buffer, drive, chs, sectorCount, silent); +} + + +BiosResult WriteSectors (byte *buffer, byte drive, const ChsAddress &chs, byte sectorCount, bool silent) +{ + return ReadWriteSectors (true, buffer, drive, chs, sectorCount, silent); +} + + +static BiosResult ReadWriteSectors (bool write, BiosLbaPacket &dapPacket, byte drive, const uint64 §or, uint16 sectorCount, bool silent) +{ + CheckStack(); + + if (!IsLbaSupported (drive)) + { + DriveGeometry geometry; + + BiosResult result = GetDriveGeometry (drive, geometry, silent); + if (result != BiosResultSuccess) + return result; + + ChsAddress chs; + LbaToChs (geometry, sector, chs); + return ReadWriteSectors (write, (uint16) (dapPacket.Buffer >> 16), (uint16) dapPacket.Buffer, drive, chs, sectorCount, silent); + } + + dapPacket.Size = sizeof (dapPacket); + dapPacket.Reserved = 0; + dapPacket.SectorCount = sectorCount; + dapPacket.Sector = sector; + + byte function = write ? 0x43 : 0x42; + + BiosResult result; + byte tryCount = TC_MAX_BIOS_DISK_IO_RETRIES; + + do + { + result = BiosResultSuccess; + + __asm + { + mov bx, 0x55aa + mov dl, drive + mov si, [dapPacket] + mov ah, function + xor al, al + int 0x13 + jnc ok // If CF=0, ignore AH to prevent issues caused by potential bugs in BIOSes + mov result, ah + ok: + } + + if (result == BiosResultEccCorrected) + result = BiosResultSuccess; + + // Some BIOSes report I/O errors prematurely in some cases + } while (result != BiosResultSuccess && --tryCount != 0); + + if (!silent && result != BiosResultSuccess) + PrintDiskError (result, write, drive, §or); + + return result; +} + + +static BiosResult ReadWriteSectors (bool write, byte *buffer, byte drive, const uint64 §or, uint16 sectorCount, bool silent) +{ + BiosLbaPacket dapPacket; + dapPacket.Buffer = (uint32) buffer; + return ReadWriteSectors (write, dapPacket, drive, sector, sectorCount, silent); +} + + +BiosResult ReadWriteSectors (bool write, uint16 bufferSegment, uint16 bufferOffset, byte drive, const uint64 §or, uint16 sectorCount, bool silent) +{ + BiosLbaPacket dapPacket; + dapPacket.Buffer = ((uint32) bufferSegment << 16) | bufferOffset; + return ReadWriteSectors (write, dapPacket, drive, sector, sectorCount, silent); +} + +BiosResult ReadSectors (uint16 bufferSegment, uint16 bufferOffset, byte drive, const uint64 §or, uint16 sectorCount, bool silent) +{ + return ReadWriteSectors (false, bufferSegment, bufferOffset, drive, sector, sectorCount, silent); +} + + +BiosResult ReadSectors (byte *buffer, byte drive, const uint64 §or, uint16 sectorCount, bool silent) +{ + BiosResult result; + uint16 codeSeg; + __asm mov codeSeg, cs + + result = ReadSectors (BootStarted ? codeSeg : TC_BOOT_LOADER_ALT_SEGMENT, (uint16) buffer, drive, sector, sectorCount, silent); + + // Alternative segment is used to prevent memory corruption caused by buggy BIOSes + if (!BootStarted) + CopyMemory (TC_BOOT_LOADER_ALT_SEGMENT, (uint16) buffer, buffer, sectorCount * TC_LB_SIZE); + + return result; +} + + +BiosResult WriteSectors (byte *buffer, byte drive, const uint64 §or, uint16 sectorCount, bool silent) +{ + return ReadWriteSectors (true, buffer, drive, sector, sectorCount, silent); +} + + +BiosResult GetDriveGeometry (byte drive, DriveGeometry &geometry, bool silent) +{ + CheckStack(); + + byte maxCylinderLow, maxHead, maxSector; + BiosResult result; + __asm + { + push es + mov dl, drive + mov ah, 0x08 + int 0x13 + + mov result, ah + mov maxCylinderLow, ch + mov maxSector, cl + mov maxHead, dh + pop es + } + + if (result == BiosResultSuccess) + { + geometry.Cylinders = (maxCylinderLow | (uint16 (maxSector & 0xc0) << 2)) + 1; + geometry.Heads = maxHead + 1; + geometry.Sectors = maxSector & ~0xc0; + } + else if (!silent) + { + Print ("Drive "); + Print (drive ^ 0x80); + Print (" not found: "); + PrintErrorNoEndl (""); + Print (result); + PrintEndl(); + } + + return result; +} + + +void ChsToLba (const DriveGeometry &geometry, const ChsAddress &chs, uint64 &lba) +{ + lba.HighPart = 0; + lba.LowPart = (uint32 (chs.Cylinder) * geometry.Heads + chs.Head) * geometry.Sectors + chs.Sector - 1; +} + + +void LbaToChs (const DriveGeometry &geometry, const uint64 &lba, ChsAddress &chs) +{ + chs.Sector = (byte) ((lba.LowPart % geometry.Sectors) + 1); + uint32 ch = lba.LowPart / geometry.Sectors; + chs.Head = (byte) (ch % geometry.Heads); + chs.Cylinder = (uint16) (ch / geometry.Heads); +} + + +void PartitionEntryMBRToPartition (const PartitionEntryMBR &partEntry, Partition &partition) +{ + partition.Active = partEntry.BootIndicator == 0x80; + partition.EndSector.HighPart = 0; + partition.EndSector.LowPart = partEntry.StartLBA + partEntry.SectorCountLBA - 1; + partition.SectorCount.HighPart = 0; + partition.SectorCount.LowPart = partEntry.SectorCountLBA; + partition.StartSector.HighPart = 0; + partition.StartSector.LowPart = partEntry.StartLBA; + partition.Type = partEntry.Type; +} + + +BiosResult ReadWriteMBR (bool write, byte drive, bool silent) +{ + uint64 mbrSector; + mbrSector.HighPart = 0; + mbrSector.LowPart = 0; + + if (write) + return WriteSectors (SectorBuffer, drive, mbrSector, 1, silent); + + return ReadSectors (SectorBuffer, drive, mbrSector, 1, silent); // Uses alternative segment +} + + +BiosResult GetDrivePartitions (byte drive, Partition *partitionArray, size_t partitionArrayCapacity, size_t &partitionCount, bool activeOnly, Partition *findPartitionFollowingThis, bool silent) +{ + Partition *followingPartition; + Partition tmpPartition; + + if (findPartitionFollowingThis) + { + assert (partitionArrayCapacity == 1); + partitionArrayCapacity = 0xff; + followingPartition = partitionArray; + partitionArray = &tmpPartition; + + followingPartition->Drive = TC_INVALID_BIOS_DRIVE; + followingPartition->StartSector.LowPart = 0xFFFFffffUL; + } + + AcquireSectorBuffer(); + BiosResult result = ReadWriteMBR (false, drive, silent); + ReleaseSectorBuffer(); + + partitionCount = 0; + + MBR *mbr = (MBR *) SectorBuffer; + if (result != BiosResultSuccess || mbr->Signature != 0xaa55) + return result; + + PartitionEntryMBR mbrPartitions[4]; + memcpy (mbrPartitions, mbr->Partitions, sizeof (mbrPartitions)); + size_t partitionArrayPos = 0, partitionNumber; + + for (partitionNumber = 0; + partitionNumber < array_capacity (mbrPartitions) && partitionArrayPos < partitionArrayCapacity; + ++partitionNumber) + { + const PartitionEntryMBR &partEntry = mbrPartitions[partitionNumber]; + + if (partEntry.SectorCountLBA > 0) + { + Partition &partition = partitionArray[partitionArrayPos]; + PartitionEntryMBRToPartition (partEntry, partition); + + if (activeOnly && !partition.Active) + continue; + + partition.Drive = drive; + partition.Number = partitionArrayPos; + + if (partEntry.Type == 0x5 || partEntry.Type == 0xf) // Extended partition + { + if (IsLbaSupported (drive)) + { + // Find all extended partitions + uint64 firstExtStartLBA = partition.StartSector; + uint64 extStartLBA = partition.StartSector; + MBR *extMbr = (MBR *) SectorBuffer; + + while (partitionArrayPos < partitionArrayCapacity && + (result = ReadSectors ((byte *) extMbr, drive, extStartLBA, 1, silent)) == BiosResultSuccess + && extMbr->Signature == 0xaa55) + { + if (extMbr->Partitions[0].SectorCountLBA > 0) + { + Partition &logPart = partitionArray[partitionArrayPos]; + PartitionEntryMBRToPartition (extMbr->Partitions[0], logPart); + logPart.Drive = drive; + + logPart.Number = partitionArrayPos; + logPart.Primary = false; + + logPart.StartSector.LowPart += extStartLBA.LowPart; + logPart.EndSector.LowPart += extStartLBA.LowPart; + + if (findPartitionFollowingThis) + { + if (logPart.StartSector.LowPart > findPartitionFollowingThis->EndSector.LowPart + && logPart.StartSector.LowPart < followingPartition->StartSector.LowPart) + { + *followingPartition = logPart; + } + } + else + ++partitionArrayPos; + } + + // Secondary extended + if (extMbr->Partitions[1].Type != 0x5 && extMbr->Partitions[1].Type == 0xf + || extMbr->Partitions[1].SectorCountLBA == 0) + break; + + extStartLBA.LowPart = extMbr->Partitions[1].StartLBA + firstExtStartLBA.LowPart; + } + } + } + else + { + partition.Primary = true; + + if (findPartitionFollowingThis) + { + if (partition.StartSector.LowPart > findPartitionFollowingThis->EndSector.LowPart + && partition.StartSector.LowPart < followingPartition->StartSector.LowPart) + { + *followingPartition = partition; + } + } + else + ++partitionArrayPos; + } + } + } + + partitionCount = partitionArrayPos; + return result; +} + + +bool GetActivePartition (byte drive) +{ + size_t partCount; + + if (GetDrivePartitions (drive, &ActivePartition, 1, partCount, true) != BiosResultSuccess || partCount < 1) + { + ActivePartition.Drive = TC_INVALID_BIOS_DRIVE; + PrintError (TC_BOOT_STR_NO_BOOT_PARTITION); + return false; + } + + return true; +} diff --git a/src/Boot/Windows/BootDiskIo.h b/src/Boot/Windows/BootDiskIo.h index d1c1ccff..b09220a8 100644 --- a/src/Boot/Windows/BootDiskIo.h +++ b/src/Boot/Windows/BootDiskIo.h @@ -1,120 +1,120 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Boot_BootDiskIo -#define TC_HEADER_Boot_BootDiskIo - -#include "Bios.h" -#include "BootDebug.h" -#include "BootDefs.h" - -#define TC_MAX_BIOS_DISK_IO_RETRIES 5 - -enum -{ - BiosResultEccCorrected = 0x11 -}; - -#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; -}; - -struct BiosLbaPacket -{ - byte Size; - byte Reserved; - uint16 SectorCount; - uint32 Buffer; - uint64 Sector; -}; - -#pragma pack() - - -struct ChsAddress -{ - uint16 Cylinder; - byte Head; - byte Sector; -}; - -struct Partition -{ - byte Number; - byte Drive; - bool Active; - uint64 EndSector; - bool Primary; - uint64 SectorCount; - uint64 StartSector; - byte Type; -}; - -struct DriveGeometry -{ - uint16 Cylinders; - byte Heads; - byte Sectors; -}; - - -#ifdef TC_BOOT_DEBUG_ENABLED -void AcquireSectorBuffer (); -void ReleaseSectorBuffer (); -#else -# define AcquireSectorBuffer() -# define ReleaseSectorBuffer() -#endif - -void ChsToLba (const DriveGeometry &geometry, const ChsAddress &chs, uint64 &lba); -bool GetActivePartition (byte drive); -BiosResult GetDriveGeometry (byte drive, DriveGeometry &geometry, bool silent = false); -BiosResult GetDrivePartitions (byte drive, Partition *partitionArray, size_t partitionArrayCapacity, size_t &partitionCount, bool activeOnly = false, Partition *findPartitionFollowingThis = nullptr, bool silent = false); -bool IsLbaSupported (byte drive); -void LbaToChs (const DriveGeometry &geometry, const uint64 &lba, ChsAddress &chs); -void Print (const ChsAddress &chs); -void PrintDiskError (BiosResult error, bool write, byte drive, const uint64 *sector, const ChsAddress *chs = nullptr); -void PrintSectorCountInMB (const uint64 §orCount); -BiosResult ReadWriteMBR (bool write, byte drive, bool silent = false); -BiosResult ReadSectors (uint16 bufferSegment, uint16 bufferOffset, byte drive, const uint64 §or, uint16 sectorCount, bool silent = false); -BiosResult ReadSectors (byte *buffer, byte drive, const uint64 §or, uint16 sectorCount, bool silent = false); -BiosResult ReadSectors (byte *buffer, byte drive, const ChsAddress &chs, byte sectorCount, bool silent = false); -BiosResult ReadWriteSectors (bool write, uint16 bufferSegment, uint16 bufferOffset, byte drive, const uint64 §or, uint16 sectorCount, bool silent); -BiosResult WriteSectors (byte *buffer, byte drive, const uint64 §or, uint16 sectorCount, bool silent = false); -BiosResult WriteSectors (byte *buffer, byte drive, const ChsAddress &chs, byte sectorCount, bool silent = false); - -extern byte SectorBuffer[TC_LB_SIZE]; - -#endif // TC_HEADER_Boot_BootDiskIo +/* + 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. +*/ + +#ifndef TC_HEADER_Boot_BootDiskIo +#define TC_HEADER_Boot_BootDiskIo + +#include "Bios.h" +#include "BootDebug.h" +#include "BootDefs.h" + +#define TC_MAX_BIOS_DISK_IO_RETRIES 5 + +enum +{ + BiosResultEccCorrected = 0x11 +}; + +#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; +}; + +struct BiosLbaPacket +{ + byte Size; + byte Reserved; + uint16 SectorCount; + uint32 Buffer; + uint64 Sector; +}; + +#pragma pack() + + +struct ChsAddress +{ + uint16 Cylinder; + byte Head; + byte Sector; +}; + +struct Partition +{ + byte Number; + byte Drive; + bool Active; + uint64 EndSector; + bool Primary; + uint64 SectorCount; + uint64 StartSector; + byte Type; +}; + +struct DriveGeometry +{ + uint16 Cylinders; + byte Heads; + byte Sectors; +}; + + +#ifdef TC_BOOT_DEBUG_ENABLED +void AcquireSectorBuffer (); +void ReleaseSectorBuffer (); +#else +# define AcquireSectorBuffer() +# define ReleaseSectorBuffer() +#endif + +void ChsToLba (const DriveGeometry &geometry, const ChsAddress &chs, uint64 &lba); +bool GetActivePartition (byte drive); +BiosResult GetDriveGeometry (byte drive, DriveGeometry &geometry, bool silent = false); +BiosResult GetDrivePartitions (byte drive, Partition *partitionArray, size_t partitionArrayCapacity, size_t &partitionCount, bool activeOnly = false, Partition *findPartitionFollowingThis = nullptr, bool silent = false); +bool IsLbaSupported (byte drive); +void LbaToChs (const DriveGeometry &geometry, const uint64 &lba, ChsAddress &chs); +void Print (const ChsAddress &chs); +void PrintDiskError (BiosResult error, bool write, byte drive, const uint64 *sector, const ChsAddress *chs = nullptr); +void PrintSectorCountInMB (const uint64 §orCount); +BiosResult ReadWriteMBR (bool write, byte drive, bool silent = false); +BiosResult ReadSectors (uint16 bufferSegment, uint16 bufferOffset, byte drive, const uint64 §or, uint16 sectorCount, bool silent = false); +BiosResult ReadSectors (byte *buffer, byte drive, const uint64 §or, uint16 sectorCount, bool silent = false); +BiosResult ReadSectors (byte *buffer, byte drive, const ChsAddress &chs, byte sectorCount, bool silent = false); +BiosResult ReadWriteSectors (bool write, uint16 bufferSegment, uint16 bufferOffset, byte drive, const uint64 §or, uint16 sectorCount, bool silent); +BiosResult WriteSectors (byte *buffer, byte drive, const uint64 §or, uint16 sectorCount, bool silent = false); +BiosResult WriteSectors (byte *buffer, byte drive, const ChsAddress &chs, byte sectorCount, bool silent = false); + +extern byte SectorBuffer[TC_LB_SIZE]; + +#endif // TC_HEADER_Boot_BootDiskIo diff --git a/src/Boot/Windows/BootEncryptedIo.cpp b/src/Boot/Windows/BootEncryptedIo.cpp index d130534f..84a4bf14 100644 --- a/src/Boot/Windows/BootEncryptedIo.cpp +++ b/src/Boot/Windows/BootEncryptedIo.cpp @@ -1,132 +1,132 @@ -/* - 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 "Crypto.h" -#include "Platform.h" -#include "BootConfig.h" -#include "BootDebug.h" -#include "BootDefs.h" -#include "BootDiskIo.h" -#include "BootEncryptedIo.h" - - -BiosResult ReadEncryptedSectors (uint16 destSegment, uint16 destOffset, byte drive, uint64 sector, uint16 sectorCount) -{ - BiosResult result; - bool decrypt = true; - - if (BootCryptoInfo->hiddenVolume) - { - if (ReadWritePartiallyCoversEncryptedArea (sector, sectorCount)) - return BiosResultInvalidFunction; - - if (sector >= EncryptedVirtualPartition.StartSector && sector <= EncryptedVirtualPartition.EndSector) - { - // Remap the request to the hidden volume - sector -= EncryptedVirtualPartition.StartSector; - sector += HiddenVolumeStartSector; - } - else - decrypt = false; - } - - result = ReadSectors (destSegment, destOffset, drive, sector, sectorCount); - - if (result != BiosResultSuccess || !decrypt) - return result; - - if (BootCryptoInfo->hiddenVolume) - { - // Convert sector number to data unit number of the hidden volume - sector -= HiddenVolumeStartSector; - sector += PimValueOrHiddenVolumeStartUnitNo; - } - - if (drive == EncryptedVirtualPartition.Drive) - { - while (sectorCount-- > 0) - { - if (BootCryptoInfo->hiddenVolume - || (sector >= EncryptedVirtualPartition.StartSector && sector <= EncryptedVirtualPartition.EndSector)) - { - AcquireSectorBuffer(); - CopyMemory (destSegment, destOffset, SectorBuffer, TC_LB_SIZE); - - DecryptDataUnits (SectorBuffer, §or, 1, BootCryptoInfo); - - CopyMemory (SectorBuffer, destSegment, destOffset, TC_LB_SIZE); - ReleaseSectorBuffer(); - } - - ++sector; - destOffset += TC_LB_SIZE; - } - } - - return result; -} - - -BiosResult WriteEncryptedSectors (uint16 sourceSegment, uint16 sourceOffset, byte drive, uint64 sector, uint16 sectorCount) -{ - BiosResult result = BiosResultSuccess; - AcquireSectorBuffer(); - uint64 dataUnitNo; - uint64 writeOffset; - - dataUnitNo = sector; - writeOffset.HighPart = 0; - writeOffset.LowPart = 0; - - if (BootCryptoInfo->hiddenVolume) - { - if (ReadWritePartiallyCoversEncryptedArea (sector, sectorCount)) - return BiosResultInvalidFunction; - - // Remap the request to the hidden volume - writeOffset = HiddenVolumeStartSector; - writeOffset -= EncryptedVirtualPartition.StartSector; - dataUnitNo -= EncryptedVirtualPartition.StartSector; - dataUnitNo += PimValueOrHiddenVolumeStartUnitNo; - } - - while (sectorCount-- > 0) - { - CopyMemory (sourceSegment, sourceOffset, SectorBuffer, TC_LB_SIZE); - - if (drive == EncryptedVirtualPartition.Drive && sector >= EncryptedVirtualPartition.StartSector && sector <= EncryptedVirtualPartition.EndSector) - { - EncryptDataUnits (SectorBuffer, &dataUnitNo, 1, BootCryptoInfo); - } - - result = WriteSectors (SectorBuffer, drive, sector + writeOffset, 1); - - if (result != BiosResultSuccess) - break; - - ++sector; - ++dataUnitNo; - sourceOffset += TC_LB_SIZE; - } - - ReleaseSectorBuffer(); - return result; -} - - -static bool ReadWritePartiallyCoversEncryptedArea (const uint64 §or, uint16 sectorCount) -{ - uint64 readWriteEnd = sector + --sectorCount; - - return ((sector < EncryptedVirtualPartition.StartSector && readWriteEnd >= EncryptedVirtualPartition.StartSector) - || (sector >= EncryptedVirtualPartition.StartSector && readWriteEnd > EncryptedVirtualPartition.EndSector)); -} +/* + 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 "Crypto.h" +#include "Platform.h" +#include "BootConfig.h" +#include "BootDebug.h" +#include "BootDefs.h" +#include "BootDiskIo.h" +#include "BootEncryptedIo.h" + + +BiosResult ReadEncryptedSectors (uint16 destSegment, uint16 destOffset, byte drive, uint64 sector, uint16 sectorCount) +{ + BiosResult result; + bool decrypt = true; + + if (BootCryptoInfo->hiddenVolume) + { + if (ReadWritePartiallyCoversEncryptedArea (sector, sectorCount)) + return BiosResultInvalidFunction; + + if (sector >= EncryptedVirtualPartition.StartSector && sector <= EncryptedVirtualPartition.EndSector) + { + // Remap the request to the hidden volume + sector -= EncryptedVirtualPartition.StartSector; + sector += HiddenVolumeStartSector; + } + else + decrypt = false; + } + + result = ReadSectors (destSegment, destOffset, drive, sector, sectorCount); + + if (result != BiosResultSuccess || !decrypt) + return result; + + if (BootCryptoInfo->hiddenVolume) + { + // Convert sector number to data unit number of the hidden volume + sector -= HiddenVolumeStartSector; + sector += PimValueOrHiddenVolumeStartUnitNo; + } + + if (drive == EncryptedVirtualPartition.Drive) + { + while (sectorCount-- > 0) + { + if (BootCryptoInfo->hiddenVolume + || (sector >= EncryptedVirtualPartition.StartSector && sector <= EncryptedVirtualPartition.EndSector)) + { + AcquireSectorBuffer(); + CopyMemory (destSegment, destOffset, SectorBuffer, TC_LB_SIZE); + + DecryptDataUnits (SectorBuffer, §or, 1, BootCryptoInfo); + + CopyMemory (SectorBuffer, destSegment, destOffset, TC_LB_SIZE); + ReleaseSectorBuffer(); + } + + ++sector; + destOffset += TC_LB_SIZE; + } + } + + return result; +} + + +BiosResult WriteEncryptedSectors (uint16 sourceSegment, uint16 sourceOffset, byte drive, uint64 sector, uint16 sectorCount) +{ + BiosResult result = BiosResultSuccess; + AcquireSectorBuffer(); + uint64 dataUnitNo; + uint64 writeOffset; + + dataUnitNo = sector; + writeOffset.HighPart = 0; + writeOffset.LowPart = 0; + + if (BootCryptoInfo->hiddenVolume) + { + if (ReadWritePartiallyCoversEncryptedArea (sector, sectorCount)) + return BiosResultInvalidFunction; + + // Remap the request to the hidden volume + writeOffset = HiddenVolumeStartSector; + writeOffset -= EncryptedVirtualPartition.StartSector; + dataUnitNo -= EncryptedVirtualPartition.StartSector; + dataUnitNo += PimValueOrHiddenVolumeStartUnitNo; + } + + while (sectorCount-- > 0) + { + CopyMemory (sourceSegment, sourceOffset, SectorBuffer, TC_LB_SIZE); + + if (drive == EncryptedVirtualPartition.Drive && sector >= EncryptedVirtualPartition.StartSector && sector <= EncryptedVirtualPartition.EndSector) + { + EncryptDataUnits (SectorBuffer, &dataUnitNo, 1, BootCryptoInfo); + } + + result = WriteSectors (SectorBuffer, drive, sector + writeOffset, 1); + + if (result != BiosResultSuccess) + break; + + ++sector; + ++dataUnitNo; + sourceOffset += TC_LB_SIZE; + } + + ReleaseSectorBuffer(); + return result; +} + + +static bool ReadWritePartiallyCoversEncryptedArea (const uint64 §or, uint16 sectorCount) +{ + uint64 readWriteEnd = sector + --sectorCount; + + return ((sector < EncryptedVirtualPartition.StartSector && readWriteEnd >= EncryptedVirtualPartition.StartSector) + || (sector >= EncryptedVirtualPartition.StartSector && readWriteEnd > EncryptedVirtualPartition.EndSector)); +} diff --git a/src/Boot/Windows/BootEncryptedIo.h b/src/Boot/Windows/BootEncryptedIo.h index 6cc375fa..6402e705 100644 --- a/src/Boot/Windows/BootEncryptedIo.h +++ b/src/Boot/Windows/BootEncryptedIo.h @@ -1,22 +1,22 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Boot_BootEncryptionIo -#define TC_HEADER_Boot_BootEncryptionIo - -#include "Platform.h" - -BiosResult ReadEncryptedSectors (uint16 destSegment, uint16 destOffset, byte drive, uint64 sector, uint16 sectorCount); -BiosResult WriteEncryptedSectors (uint16 sourceSegment, uint16 sourceOffset, byte drive, uint64 sector, uint16 sectorCount); -static bool ReadWritePartiallyCoversEncryptedArea (const uint64 §or, uint16 sectorCount); - -#endif // TC_HEADER_Boot_BootEncryptionIo +/* + 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. +*/ + +#ifndef TC_HEADER_Boot_BootEncryptionIo +#define TC_HEADER_Boot_BootEncryptionIo + +#include "Platform.h" + +BiosResult ReadEncryptedSectors (uint16 destSegment, uint16 destOffset, byte drive, uint64 sector, uint16 sectorCount); +BiosResult WriteEncryptedSectors (uint16 sourceSegment, uint16 sourceOffset, byte drive, uint64 sector, uint16 sectorCount); +static bool ReadWritePartiallyCoversEncryptedArea (const uint64 §or, uint16 sectorCount); + +#endif // TC_HEADER_Boot_BootEncryptionIo diff --git a/src/Boot/Windows/BootMain.cpp b/src/Boot/Windows/BootMain.cpp index 275c5762..24acd23f 100644 --- a/src/Boot/Windows/BootMain.cpp +++ b/src/Boot/Windows/BootMain.cpp @@ -1,1269 +1,1269 @@ -/* - 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 "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(); - - const char *title = -#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE - " VeraCrypt Boot Loader " -#else - " VeraCrypt Rescue Disk " -#endif - VERSION_STRING "\r\n"; - - Print (title); - - 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 (" [F5] Hide/Show Password and PIM\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, int& pim) -{ - size_t pos = 0; - byte scanCode; - byte asciiCode; - byte hidePassword = 1; - - pim = 0; - - Print ("Enter password"); - Print (PreventNormalSystemBoot ? " for hidden system:\r\n" : ": "); - - while (true) - { - asciiCode = GetKeyboardChar (&scanCode); - - switch (scanCode) - { - case TC_BIOS_KEY_ENTER: - password.Length = pos; - Print ("\r"); - if (!PreventNormalSystemBoot) - Print ("Enter password: "); - pos = 0; - while (pos < MAX_PASSWORD) - { - pos++; - if (pos < MAX_PASSWORD) - PrintChar ('*'); - else - PrintCharAtCursor ('*'); - } - - ClearBiosKeystrokeBuffer(); - PrintEndl(); - - break; - - case TC_BIOS_KEY_BACKSPACE: - if (pos > 0) - { - if (pos < MAX_PASSWORD) - PrintBackspace(); - else - PrintCharAtCursor (' '); - - --pos; - } - continue; - - case TC_BIOS_KEY_F5: - hidePassword ^= 0x01; - continue; - - default: - if (scanCode == TC_BIOS_KEY_ESC || IsMenuKey (scanCode)) - { - burn (password.Text, sizeof (password.Text)); - ClearBiosKeystrokeBuffer(); - - PrintEndl(); - return scanCode; - } - } - - if (TC_BIOS_KEY_ENTER == scanCode) - break; - - if (!IsPrintable (asciiCode) || pos == MAX_PASSWORD) - { - Beep(); - continue; - } - - password.Text[pos++] = asciiCode; - if (hidePassword) asciiCode = '*'; - if (pos < MAX_PASSWORD) - PrintChar (asciiCode); - else - PrintCharAtCursor (asciiCode); - } - -#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE - if (PimValueOrHiddenVolumeStartUnitNo.LowPart != -1) - { - pim = (int) PimValueOrHiddenVolumeStartUnitNo.LowPart; - // reset stored PIM value to allow requesting PIM next time in case the stored value is wrong - PimValueOrHiddenVolumeStartUnitNo.LowPart = -1; - return TC_BIOS_KEY_ENTER; - } - else -#endif - { - pos = 0; - Print ("PIM: "); - - while (true) - { - asciiCode = GetKeyboardChar (&scanCode); - - switch (scanCode) - { - case TC_BIOS_KEY_ENTER: - Print ("\rPIM: "); - pos =0; - while (pos < MAX_PIM) - { - PrintChar ('*'); - pos++; - } - - ClearBiosKeystrokeBuffer(); - PrintEndl(); - - return TC_BIOS_KEY_ENTER; - - case TC_BIOS_KEY_BACKSPACE: - if (pos > 0) - { - if (pos < MAX_PIM) - PrintBackspace(); - else - PrintCharAtCursor (' '); - - --pos; - pim /= 10; - } - continue; - - case TC_BIOS_KEY_F5: - hidePassword ^= 0x01; - continue; - - default: - if (scanCode == TC_BIOS_KEY_ESC || IsMenuKey (scanCode)) - { - burn (password.Text, sizeof (password.Text)); - ClearBiosKeystrokeBuffer(); - - PrintEndl(); - return scanCode; - } - } - - if (!IsDigit (asciiCode) || pos == MAX_PIM) - { - Beep(); - continue; - } - - pim = 10*pim + (asciiCode - '0'); - pos++; - - if (hidePassword) asciiCode = '*'; - if (pos < MAX_PIM) - PrintChar (asciiCode); - else - PrintCharAtCursor (asciiCode); - } - } -} - - -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 // Boot drive - mov dh, 0 - xor ax, ax - mov si, ax - mov ds, ax - mov es, ax - mov ss, ax - mov sp, 0x7c00 - sti - - jmp cs:addr - } -} - - -static bool OpenVolume (byte drive, Password &password, int pim, 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, pim, 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) - { - PrintErrorNoEndl ("BIOS reserved too much memory: "); - - uint16 memFree; - __asm - { - push es - xor ax, ax - mov es, ax - mov ax, es:[0x413] - mov memFree, ax - pop es - } - - Print (memFree); - PrintEndl(); - 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, pim = 0; - - EraseMemory (bootArguments, sizeof (*bootArguments)); - - // Open volume header - while (true) - { - exitKey = AskPassword (bootArguments->BootPassword, pim); - - if (exitKey != TC_BIOS_KEY_ENTER) - return false; - - Print ("Verifying password..."); - - if (OpenVolume (BootDrive, bootArguments->BootPassword, pim, &BootCryptoInfo, &bootArguments->HeaderSaltCrc32, skipNormal, skipHidden)) - { - Print ("OK\r\n"); - 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 ("If you are sure the password is correct, the key data may be damaged.\r\n" - "If so, 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" - "VeraCrypt 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); - bootArguments->Flags = (((uint32)pim) << 16); - - if (BootCryptoInfo->hiddenVolume) - bootArguments->HiddenSystemPartitionStart = PartitionFollowingActive.StartSector << TC_LB_SIZE_BIT_SHIFT_DIVISOR; - - if (ExtraBootPartitionPresent) - bootArguments->Flags |= TC_BOOT_ARGS_FLAG_EXTRA_BOOT_PARTITION; - - 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; - - PimValueOrHiddenVolumeStartUnitNo = 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 bool GetSystemPartitions (byte drive) -{ - size_t partCount; - - if (!GetActivePartition (drive)) - return false; - - // Find partition following the active one - GetDrivePartitions (drive, &PartitionFollowingActive, 1, partCount, false, &ActivePartition); - - // If there is an extra boot partition, use the partitions following it. - // The real boot partition is determined in BootEncryptedDrive(). - if (ActivePartition.SectorCount.HighPart == 0 && ActivePartition.SectorCount.LowPart <= TC_MAX_EXTRA_BOOT_PARTITION_SIZE / TC_LB_SIZE - && PartitionFollowingActive.Drive != TC_INVALID_BIOS_DRIVE) - { - ExtraBootPartitionPresent = true; - - ActivePartition = PartitionFollowingActive; - GetDrivePartitions (drive, &PartitionFollowingActive, 1, partCount, false, &ActivePartition); - } - - return true; -} - - -static byte BootEncryptedDrive () -{ - BootArguments *bootArguments = (BootArguments *) TC_BOOT_LOADER_ARGS_OFFSET; - byte exitKey; - BootCryptoInfo = NULL; - - if (!GetSystemPartitions (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 (ExtraBootPartitionPresent && !GetActivePartition (BootDrive)) - goto err; - - if (ReadWriteMBR (false, ActivePartition.Drive) != BiosResultSuccess) - goto err; - - bootArguments->BootDriveSignature = *(uint32 *) (SectorBuffer + 0x1b8); - - 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' - || *(uint32 *) (SectorBuffer + 3) == 0x41465845 && SectorBuffer[7] == 'T' // 'exFAT' - || *(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 CopySystemPartitionToHiddenVolume (byte drive, byte &exitKey) -{ - bool status = false; - - uint64 sectorsRemaining; - uint64 sectorOffset; - sectorOffset.LowPart = 0; - sectorOffset.HighPart = 0; - - int fragmentSectorCount = 0x7f; // Maximum safe value supported by BIOS - int statCount = 0; - - if (!CheckMemoryRequirements ()) - goto err; - - if (!GetSystemPartitions (drive)) - goto err; - - if (PartitionFollowingActive.Drive == TC_INVALID_BIOS_DRIVE) - TC_THROW_FATAL_EXCEPTION; - - // Check if BIOS can read the last sector of the hidden system - AcquireSectorBuffer(); - - if (ReadSectors (SectorBuffer, PartitionFollowingActive.Drive, PartitionFollowingActive.EndSector - (TC_VOLUME_HEADER_GROUP_SIZE / TC_LB_SIZE - 2), 1) != BiosResultSuccess - || GetCrc32 (SectorBuffer, sizeof (SectorBuffer)) != OuterVolumeBackupHeaderCrc) - { - PrintErrorNoEndl ("Your BIOS does not support large drives"); - Print (IsLbaSupported (PartitionFollowingActive.Drive) ? " due to a bug" : "\r\n- Enable LBA in BIOS"); - PrintEndl(); - Print (TC_BOOT_STR_UPGRADE_BIOS); - - ReleaseSectorBuffer(); - goto err; - } - - ReleaseSectorBuffer(); - - if (!MountVolume (drive, exitKey, true, false)) - return false; - - sectorsRemaining = EncryptedVirtualPartition.SectorCount; - - if (!(sectorsRemaining == ActivePartition.SectorCount)) - TC_THROW_FATAL_EXCEPTION; - - InitScreen(); - Print ("\r\nCopying system to hidden volume. To abort, press Esc.\r\n\r\n"); - - while (sectorsRemaining.HighPart != 0 || sectorsRemaining.LowPart != 0) - { - if (EscKeyPressed()) - { - Print ("\rIf aborted, copying will have to start from the beginning (if attempted again).\r\n"); - if (AskYesNo ("Abort")) - break; - } - - if (sectorsRemaining.HighPart == 0 && sectorsRemaining.LowPart < fragmentSectorCount) - fragmentSectorCount = (int) sectorsRemaining.LowPart; - - if (ReadWriteSectors (false, TC_BOOT_LOADER_BUFFER_SEGMENT, 0, drive, ActivePartition.StartSector + sectorOffset, fragmentSectorCount, false) != BiosResultSuccess) - { - Print ("To fix bad sectors: 1) Terminate 2) Encrypt and decrypt sys partition 3) Retry\r\n"); - crypto_close (BootCryptoInfo); - goto err; - } - - AcquireSectorBuffer(); - - for (int i = 0; i < fragmentSectorCount; ++i) - { - CopyMemory (TC_BOOT_LOADER_BUFFER_SEGMENT, i * TC_LB_SIZE, SectorBuffer, TC_LB_SIZE); - - uint64 s = PimValueOrHiddenVolumeStartUnitNo + sectorOffset + i; - EncryptDataUnits (SectorBuffer, &s, 1, BootCryptoInfo); - - CopyMemory (SectorBuffer, TC_BOOT_LOADER_BUFFER_SEGMENT, i * TC_LB_SIZE, TC_LB_SIZE); - } - - ReleaseSectorBuffer(); - - if (ReadWriteSectors (true, TC_BOOT_LOADER_BUFFER_SEGMENT, 0, drive, HiddenVolumeStartSector + sectorOffset, fragmentSectorCount, false) != BiosResultSuccess) - { - crypto_close (BootCryptoInfo); - goto err; - } - - sectorsRemaining = sectorsRemaining - fragmentSectorCount; - sectorOffset = sectorOffset + fragmentSectorCount; - - if (!(statCount++ & 0xf)) - { - Print ("\rRemaining: "); - PrintSectorCountInMB (sectorsRemaining); - } - } - - crypto_close (BootCryptoInfo); - - if (sectorsRemaining.HighPart == 0 && sectorsRemaining.LowPart == 0) - { - status = true; - Print ("\rCopying completed."); - } - - PrintEndl (2); - goto ret; - -err: - exitKey = TC_BIOS_KEY_ESC; - GetKeyboardChar(); - -ret: - EraseMemory ((void *) TC_BOOT_LOADER_ARGS_OFFSET, sizeof (BootArguments)); - return status; -} - - -#else // TC_WINDOWS_BOOT_RESCUE_DISK_MODE - - -static void DecryptDrive (byte drive) -{ - byte exitKey; - if (!MountVolume (drive, exitKey, false, true)) - return; - - BootArguments *bootArguments = (BootArguments *) TC_BOOT_LOADER_ARGS_OFFSET; - - bool headerUpdateRequired = false; - uint64 sectorsRemaining = EncryptedVirtualPartition.EndSector + 1 - EncryptedVirtualPartition.StartSector; - uint64 sector = EncryptedVirtualPartition.EndSector + 1; - - int fragmentSectorCount = 0x7f; // Maximum safe value supported by BIOS - int statCount = 0; - - bool skipBadSectors = false; - - Print ("\r\nUse only if Windows cannot start. Decryption under Windows is much faster\r\n" - "(in VeraCrypt, select 'System' > 'Permanently Decrypt').\r\n\r\n"); - - if (!AskYesNo ("Decrypt now")) - { - crypto_close (BootCryptoInfo); - goto ret; - } - - if (EncryptedVirtualPartition.Drive == TC_INVALID_BIOS_DRIVE) - { - // Drive already decrypted - sectorsRemaining.HighPart = 0; - sectorsRemaining.LowPart = 0; - } - else - { - Print ("\r\nTo safely interrupt and defer decryption, press Esc.\r\n" - "WARNING: You can turn off power only after you press Esc.\r\n\r\n"); - } - - while (sectorsRemaining.HighPart != 0 || sectorsRemaining.LowPart != 0) - { - if (EscKeyPressed()) - break; - - if (sectorsRemaining.HighPart == 0 && sectorsRemaining.LowPart < fragmentSectorCount) - fragmentSectorCount = (int) sectorsRemaining.LowPart; - - sector = sector - fragmentSectorCount; - - if (!(statCount++ & 0xf)) - { - Print ("\rRemaining: "); - PrintSectorCountInMB (sectorsRemaining); - } - - if (ReadWriteSectors (false, TC_BOOT_LOADER_BUFFER_SEGMENT, 0, drive, sector, fragmentSectorCount, skipBadSectors) == BiosResultSuccess) - { - AcquireSectorBuffer(); - - for (int i = 0; i < fragmentSectorCount; ++i) - { - CopyMemory (TC_BOOT_LOADER_BUFFER_SEGMENT, i * TC_LB_SIZE, SectorBuffer, TC_LB_SIZE); - - uint64 s = sector + i; - DecryptDataUnits (SectorBuffer, &s, 1, BootCryptoInfo); - - CopyMemory (SectorBuffer, TC_BOOT_LOADER_BUFFER_SEGMENT, i * TC_LB_SIZE, TC_LB_SIZE); - } - - ReleaseSectorBuffer(); - - if (ReadWriteSectors (true, TC_BOOT_LOADER_BUFFER_SEGMENT, 0, drive, sector, fragmentSectorCount, skipBadSectors) != BiosResultSuccess && !skipBadSectors) - goto askBadSectorSkip; - } - else if (!skipBadSectors) - goto askBadSectorSkip; - - sectorsRemaining = sectorsRemaining - fragmentSectorCount; - headerUpdateRequired = true; - continue; - -askBadSectorSkip: - if (!AskYesNo ("Skip all bad sectors")) - break; - - skipBadSectors = true; - sector = sector + fragmentSectorCount; - fragmentSectorCount = 1; - } - - crypto_close (BootCryptoInfo); - - if (headerUpdateRequired) - { - Print ("\rUpdating header..."); - - AcquireSectorBuffer(); - uint64 headerSector; - headerSector.HighPart = 0; - headerSector.LowPart = TC_BOOT_VOLUME_HEADER_SECTOR; - - // Update encrypted area size in volume header - - CRYPTO_INFO *headerCryptoInfo = crypto_open(); - while (ReadSectors (SectorBuffer, drive, headerSector, 1) != BiosResultSuccess); - - if (ReadVolumeHeader (TRUE, (char *) SectorBuffer, &bootArguments->BootPassword, (int) (bootArguments->Flags >> 16), NULL, headerCryptoInfo) == 0) - { - DecryptBuffer (SectorBuffer + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, headerCryptoInfo); - - uint64 encryptedAreaLength = sectorsRemaining << TC_LB_SIZE_BIT_SHIFT_DIVISOR; - - for (int i = 7; i >= 0; --i) - { - SectorBuffer[TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH + i] = (byte) encryptedAreaLength.LowPart; - encryptedAreaLength = encryptedAreaLength >> 8; - } - - uint32 headerCrc32 = GetCrc32 (SectorBuffer + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC); - - for (i = 3; i >= 0; --i) - { - SectorBuffer[TC_HEADER_OFFSET_HEADER_CRC + i] = (byte) headerCrc32; - headerCrc32 >>= 8; - } - - EncryptBuffer (SectorBuffer + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, headerCryptoInfo); - } - - crypto_close (headerCryptoInfo); - - while (WriteSectors (SectorBuffer, drive, headerSector, 1) != BiosResultSuccess); - ReleaseSectorBuffer(); - - Print ("Done!\r\n"); - } - - if (sectorsRemaining.HighPart == 0 && sectorsRemaining.LowPart == 0) - Print ("\rDrive decrypted.\r\n"); - else - Print ("\r\nDecryption deferred.\r\n"); - - GetKeyboardChar(); -ret: - EraseMemory (bootArguments, sizeof (*bootArguments)); -} - - -static void RepairMenu () -{ - DriveGeometry bootLoaderDriveGeometry; - - if (GetDriveGeometry (BootLoaderDrive, bootLoaderDriveGeometry, true) != BiosResultSuccess) - { - // Some BIOSes may fail to get the geometry of an emulated floppy drive - bootLoaderDriveGeometry.Cylinders = 80; - bootLoaderDriveGeometry.Heads = 2; - bootLoaderDriveGeometry.Sectors = 18; - } - - while (true) - { - InitScreen(); - Print ("Available "); Print ("Repair Options"); Print (":\r\n"); - PrintRepeatedChar ('\xC4', 25); - PrintEndl(); - - enum - { - RestoreNone = 0, - DecryptVolume, - RestoreTrueCryptLoader, - RestoreVolumeHeader, - RestoreOriginalSystemLoader - }; - - static const char *options[] = { "Permanently decrypt system partition/drive", "Restore VeraCrypt Boot Loader", "Restore key data (volume header)", "Restore original system loader" }; - - int selection = AskSelection (options, - (BootSectorFlags & TC_BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER) ? array_capacity (options) : array_capacity (options) - 1); - - PrintEndl(); - - switch (selection) - { - case RestoreNone: - return; - - case DecryptVolume: - DecryptDrive (BootDrive); - continue; - - case RestoreOriginalSystemLoader: - if (!AskYesNo ("Is the system partition/drive decrypted")) - { - Print ("Please decrypt it first.\r\n"); - GetKeyboardChar(); - continue; - } - break; - } - - bool writeConfirmed = false; - BiosResult result; - - uint64 sector; - sector.HighPart = 0; - ChsAddress chs; - - byte mbrPartTable[TC_LB_SIZE - TC_MAX_MBR_BOOT_CODE_SIZE]; - AcquireSectorBuffer(); - - for (int i = (selection == RestoreVolumeHeader ? TC_BOOT_VOLUME_HEADER_SECTOR : TC_MBR_SECTOR); - i < TC_BOOT_LOADER_AREA_SECTOR_COUNT; ++i) - { - sector.LowPart = i; - - if (selection == RestoreOriginalSystemLoader) - sector.LowPart += TC_ORIG_BOOT_LOADER_BACKUP_SECTOR; - else if (selection == RestoreTrueCryptLoader) - sector.LowPart += TC_BOOT_LOADER_BACKUP_RESCUE_DISK_SECTOR; - - // The backup medium may be a floppy-emulated bootable CD. The emulation may fail if LBA addressing is used. - // Therefore, only CHS addressing can be used. - LbaToChs (bootLoaderDriveGeometry, sector, chs); - sector.LowPart = i; - - if (i == TC_MBR_SECTOR) - { - // Read current partition table - result = ReadSectors (SectorBuffer, TC_FIRST_BIOS_DRIVE, sector, 1); - if (result != BiosResultSuccess) - goto err; - - memcpy (mbrPartTable, SectorBuffer + TC_MAX_MBR_BOOT_CODE_SIZE, sizeof (mbrPartTable)); - } - - result = ReadSectors (SectorBuffer, BootLoaderDrive, chs, 1); - if (result != BiosResultSuccess) - goto err; - - if (i == TC_MBR_SECTOR) - { - // Preserve current partition table - memcpy (SectorBuffer + TC_MAX_MBR_BOOT_CODE_SIZE, mbrPartTable, sizeof (mbrPartTable)); - } - - // Volume header - if (i == TC_BOOT_VOLUME_HEADER_SECTOR) - { - if (selection == RestoreTrueCryptLoader) - continue; - - if (selection == RestoreVolumeHeader) - { - while (true) - { - bool validHeaderPresent = false; - uint32 masterKeyScheduleCrc; - - Password password; - int pim; - byte exitKey = AskPassword (password, pim); - - if (exitKey != TC_BIOS_KEY_ENTER) - goto abort; - - CRYPTO_INFO *cryptoInfo; - - CopyMemory (SectorBuffer, TC_BOOT_LOADER_BUFFER_SEGMENT, 0, TC_LB_SIZE); - ReleaseSectorBuffer(); - - // Restore volume header only if the current one cannot be used - if (OpenVolume (TC_FIRST_BIOS_DRIVE, password, pim, &cryptoInfo, nullptr, false, true)) - { - validHeaderPresent = true; - masterKeyScheduleCrc = GetCrc32 (cryptoInfo->ks, sizeof (cryptoInfo->ks)); - crypto_close (cryptoInfo); - } - - AcquireSectorBuffer(); - CopyMemory (TC_BOOT_LOADER_BUFFER_SEGMENT, 0, SectorBuffer, TC_LB_SIZE); - - if (ReadVolumeHeader (TRUE, (char *) SectorBuffer, &password, pim, &cryptoInfo, nullptr) == 0) - { - if (validHeaderPresent) - { - if (masterKeyScheduleCrc == GetCrc32 (cryptoInfo->ks, sizeof (cryptoInfo->ks))) - { - Print ("Original header preserved.\r\n"); - goto err; - } - - Print ("WARNING: Drive 0 contains a valid header!\r\n"); - } - - crypto_close (cryptoInfo); - break; - } - - Print ("Incorrect password.\r\n\r\n"); - } - } - } - - if (!writeConfirmed && !AskYesNo ("Modify drive 0")) - goto abort; - writeConfirmed = true; - - if (WriteSectors (SectorBuffer, TC_FIRST_BIOS_DRIVE, sector, 1) != BiosResultSuccess) - goto err; - } -done: - switch (selection) - { - case RestoreTrueCryptLoader: - Print ("VeraCrypt Boot Loader"); - break; - - case RestoreVolumeHeader: - Print ("Header"); - break; - - case RestoreOriginalSystemLoader: - Print ("System loader"); - break; - } - Print (" restored.\r\n"); - -err: GetKeyboardChar(); -abort: ReleaseSectorBuffer(); - } -} - -#endif // TC_WINDOWS_BOOT_RESCUE_DISK_MODE - - -#ifndef DEBUG -extern "C" void _acrtused () { } // Required by linker -#endif - - -void main () -{ - __asm mov BootLoaderDrive, dl - __asm mov BootSectorFlags, dh - -#ifdef TC_BOOT_TRACING_ENABLED - InitDebugPort(); -#endif - -#ifdef TC_BOOT_STACK_CHECKING_ENABLED - InitStackChecker(); -#endif - -#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE - ReadBootSectorUserConfiguration(); -#elif defined (TC_WINDOWS_BOOT_AES) - EnableHwEncryption (!(BootSectorFlags & TC_BOOT_CFG_FLAG_RESCUE_DISABLE_HW_ENCRYPTION)); -#endif - - InitVideoMode(); - InitScreen(); - - // Determine boot drive - BootDrive = BootLoaderDrive; - if (BootDrive < TC_FIRST_BIOS_DRIVE) - BootDrive = TC_FIRST_BIOS_DRIVE; - - // Query boot drive geometry - if (GetDriveGeometry (BootDrive, BootDriveGeometry) != BiosResultSuccess) - { - BootDrive = TC_FIRST_BIOS_DRIVE; - if (GetDriveGeometry (BootDrive, BootDriveGeometry) != BiosResultSuccess) - { -#ifdef TC_WINDOWS_BOOT_RESCUE_DISK_MODE - Print ("- Connect system drive to (SATA) port 1\r\n"); -#endif - GetKeyboardChar(); - } - else - BootDriveGeometryValid = true; - } - else - BootDriveGeometryValid = true; - -#ifdef TC_WINDOWS_BOOT_RESCUE_DISK_MODE - - // Check whether the user is not using the Rescue Disk to create a hidden system - - if (ReadWriteMBR (false, BootDrive, true) == BiosResultSuccess - && *(uint32 *) (SectorBuffer + 6) == 0x61726556 - && *(uint32 *) (SectorBuffer + 10) == 0x70797243 - && (SectorBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET] & TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE) != TC_HIDDEN_OS_CREATION_PHASE_NONE) - { - PrintError ("It appears you are creating a hidden OS."); - if (AskYesNo ("Is this correct")) - { - Print ("Please remove the Rescue Disk from the drive and restart."); - while (true); - } - } - -#endif // TC_WINDOWS_BOOT_RESCUE_DISK_MODE - - - // Main menu - - while (true) - { - byte exitKey; - InitScreen(); - -#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE - - // Hidden system setup - byte hiddenSystemCreationPhase = BootSectorFlags & TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE; - - if (hiddenSystemCreationPhase != TC_HIDDEN_OS_CREATION_PHASE_NONE) - { - PreventNormalSystemBoot = true; - PrintMainMenu(); - - if (hiddenSystemCreationPhase == TC_HIDDEN_OS_CREATION_PHASE_CLONING) - { - if (CopySystemPartitionToHiddenVolume (BootDrive, exitKey)) - { - BootSectorFlags = (BootSectorFlags & ~TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE) | TC_HIDDEN_OS_CREATION_PHASE_WIPING; - UpdateBootSectorConfiguration (BootLoaderDrive); - } - else if (exitKey == TC_BIOS_KEY_ESC) - goto bootMenu; - else - continue; - } - } - else - PrintMainMenu(); - - exitKey = BootEncryptedDrive(); - -#else // TC_WINDOWS_BOOT_RESCUE_DISK_MODE - - PrintMainMenu(); - exitKey = BootEncryptedDrive(); - - if (exitKey == TC_MENU_KEY_REPAIR) - { - RepairMenu(); - continue; - } - -#endif // TC_WINDOWS_BOOT_RESCUE_DISK_MODE - -bootMenu: - if (!PreventBootMenu) - BootMenu(); - } -} +/* + 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 "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(); + + const char *title = +#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE + " VeraCrypt Boot Loader " +#else + " VeraCrypt Rescue Disk " +#endif + VERSION_STRING "\r\n"; + + Print (title); + + 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 (" [F5] Hide/Show Password and PIM\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, int& pim) +{ + size_t pos = 0; + byte scanCode; + byte asciiCode; + byte hidePassword = 1; + + pim = 0; + + Print ("Enter password"); + Print (PreventNormalSystemBoot ? " for hidden system:\r\n" : ": "); + + while (true) + { + asciiCode = GetKeyboardChar (&scanCode); + + switch (scanCode) + { + case TC_BIOS_KEY_ENTER: + password.Length = pos; + Print ("\r"); + if (!PreventNormalSystemBoot) + Print ("Enter password: "); + pos = 0; + while (pos < MAX_PASSWORD) + { + pos++; + if (pos < MAX_PASSWORD) + PrintChar ('*'); + else + PrintCharAtCursor ('*'); + } + + ClearBiosKeystrokeBuffer(); + PrintEndl(); + + break; + + case TC_BIOS_KEY_BACKSPACE: + if (pos > 0) + { + if (pos < MAX_PASSWORD) + PrintBackspace(); + else + PrintCharAtCursor (' '); + + --pos; + } + continue; + + case TC_BIOS_KEY_F5: + hidePassword ^= 0x01; + continue; + + default: + if (scanCode == TC_BIOS_KEY_ESC || IsMenuKey (scanCode)) + { + burn (password.Text, sizeof (password.Text)); + ClearBiosKeystrokeBuffer(); + + PrintEndl(); + return scanCode; + } + } + + if (TC_BIOS_KEY_ENTER == scanCode) + break; + + if (!IsPrintable (asciiCode) || pos == MAX_PASSWORD) + { + Beep(); + continue; + } + + password.Text[pos++] = asciiCode; + if (hidePassword) asciiCode = '*'; + if (pos < MAX_PASSWORD) + PrintChar (asciiCode); + else + PrintCharAtCursor (asciiCode); + } + +#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE + if (PimValueOrHiddenVolumeStartUnitNo.LowPart != -1) + { + pim = (int) PimValueOrHiddenVolumeStartUnitNo.LowPart; + // reset stored PIM value to allow requesting PIM next time in case the stored value is wrong + PimValueOrHiddenVolumeStartUnitNo.LowPart = -1; + return TC_BIOS_KEY_ENTER; + } + else +#endif + { + pos = 0; + Print ("PIM: "); + + while (true) + { + asciiCode = GetKeyboardChar (&scanCode); + + switch (scanCode) + { + case TC_BIOS_KEY_ENTER: + Print ("\rPIM: "); + pos =0; + while (pos < MAX_PIM) + { + PrintChar ('*'); + pos++; + } + + ClearBiosKeystrokeBuffer(); + PrintEndl(); + + return TC_BIOS_KEY_ENTER; + + case TC_BIOS_KEY_BACKSPACE: + if (pos > 0) + { + if (pos < MAX_PIM) + PrintBackspace(); + else + PrintCharAtCursor (' '); + + --pos; + pim /= 10; + } + continue; + + case TC_BIOS_KEY_F5: + hidePassword ^= 0x01; + continue; + + default: + if (scanCode == TC_BIOS_KEY_ESC || IsMenuKey (scanCode)) + { + burn (password.Text, sizeof (password.Text)); + ClearBiosKeystrokeBuffer(); + + PrintEndl(); + return scanCode; + } + } + + if (!IsDigit (asciiCode) || pos == MAX_PIM) + { + Beep(); + continue; + } + + pim = 10*pim + (asciiCode - '0'); + pos++; + + if (hidePassword) asciiCode = '*'; + if (pos < MAX_PIM) + PrintChar (asciiCode); + else + PrintCharAtCursor (asciiCode); + } + } +} + + +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 // Boot drive + mov dh, 0 + xor ax, ax + mov si, ax + mov ds, ax + mov es, ax + mov ss, ax + mov sp, 0x7c00 + sti + + jmp cs:addr + } +} + + +static bool OpenVolume (byte drive, Password &password, int pim, 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, pim, 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) + { + PrintErrorNoEndl ("BIOS reserved too much memory: "); + + uint16 memFree; + __asm + { + push es + xor ax, ax + mov es, ax + mov ax, es:[0x413] + mov memFree, ax + pop es + } + + Print (memFree); + PrintEndl(); + 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, pim = 0; + + EraseMemory (bootArguments, sizeof (*bootArguments)); + + // Open volume header + while (true) + { + exitKey = AskPassword (bootArguments->BootPassword, pim); + + if (exitKey != TC_BIOS_KEY_ENTER) + return false; + + Print ("Verifying password..."); + + if (OpenVolume (BootDrive, bootArguments->BootPassword, pim, &BootCryptoInfo, &bootArguments->HeaderSaltCrc32, skipNormal, skipHidden)) + { + Print ("OK\r\n"); + 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 ("If you are sure the password is correct, the key data may be damaged.\r\n" + "If so, 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" + "VeraCrypt 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); + bootArguments->Flags = (((uint32)pim) << 16); + + if (BootCryptoInfo->hiddenVolume) + bootArguments->HiddenSystemPartitionStart = PartitionFollowingActive.StartSector << TC_LB_SIZE_BIT_SHIFT_DIVISOR; + + if (ExtraBootPartitionPresent) + bootArguments->Flags |= TC_BOOT_ARGS_FLAG_EXTRA_BOOT_PARTITION; + + 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; + + PimValueOrHiddenVolumeStartUnitNo = 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 bool GetSystemPartitions (byte drive) +{ + size_t partCount; + + if (!GetActivePartition (drive)) + return false; + + // Find partition following the active one + GetDrivePartitions (drive, &PartitionFollowingActive, 1, partCount, false, &ActivePartition); + + // If there is an extra boot partition, use the partitions following it. + // The real boot partition is determined in BootEncryptedDrive(). + if (ActivePartition.SectorCount.HighPart == 0 && ActivePartition.SectorCount.LowPart <= TC_MAX_EXTRA_BOOT_PARTITION_SIZE / TC_LB_SIZE + && PartitionFollowingActive.Drive != TC_INVALID_BIOS_DRIVE) + { + ExtraBootPartitionPresent = true; + + ActivePartition = PartitionFollowingActive; + GetDrivePartitions (drive, &PartitionFollowingActive, 1, partCount, false, &ActivePartition); + } + + return true; +} + + +static byte BootEncryptedDrive () +{ + BootArguments *bootArguments = (BootArguments *) TC_BOOT_LOADER_ARGS_OFFSET; + byte exitKey; + BootCryptoInfo = NULL; + + if (!GetSystemPartitions (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 (ExtraBootPartitionPresent && !GetActivePartition (BootDrive)) + goto err; + + if (ReadWriteMBR (false, ActivePartition.Drive) != BiosResultSuccess) + goto err; + + bootArguments->BootDriveSignature = *(uint32 *) (SectorBuffer + 0x1b8); + + 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' + || *(uint32 *) (SectorBuffer + 3) == 0x41465845 && SectorBuffer[7] == 'T' // 'exFAT' + || *(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 CopySystemPartitionToHiddenVolume (byte drive, byte &exitKey) +{ + bool status = false; + + uint64 sectorsRemaining; + uint64 sectorOffset; + sectorOffset.LowPart = 0; + sectorOffset.HighPart = 0; + + int fragmentSectorCount = 0x7f; // Maximum safe value supported by BIOS + int statCount = 0; + + if (!CheckMemoryRequirements ()) + goto err; + + if (!GetSystemPartitions (drive)) + goto err; + + if (PartitionFollowingActive.Drive == TC_INVALID_BIOS_DRIVE) + TC_THROW_FATAL_EXCEPTION; + + // Check if BIOS can read the last sector of the hidden system + AcquireSectorBuffer(); + + if (ReadSectors (SectorBuffer, PartitionFollowingActive.Drive, PartitionFollowingActive.EndSector - (TC_VOLUME_HEADER_GROUP_SIZE / TC_LB_SIZE - 2), 1) != BiosResultSuccess + || GetCrc32 (SectorBuffer, sizeof (SectorBuffer)) != OuterVolumeBackupHeaderCrc) + { + PrintErrorNoEndl ("Your BIOS does not support large drives"); + Print (IsLbaSupported (PartitionFollowingActive.Drive) ? " due to a bug" : "\r\n- Enable LBA in BIOS"); + PrintEndl(); + Print (TC_BOOT_STR_UPGRADE_BIOS); + + ReleaseSectorBuffer(); + goto err; + } + + ReleaseSectorBuffer(); + + if (!MountVolume (drive, exitKey, true, false)) + return false; + + sectorsRemaining = EncryptedVirtualPartition.SectorCount; + + if (!(sectorsRemaining == ActivePartition.SectorCount)) + TC_THROW_FATAL_EXCEPTION; + + InitScreen(); + Print ("\r\nCopying system to hidden volume. To abort, press Esc.\r\n\r\n"); + + while (sectorsRemaining.HighPart != 0 || sectorsRemaining.LowPart != 0) + { + if (EscKeyPressed()) + { + Print ("\rIf aborted, copying will have to start from the beginning (if attempted again).\r\n"); + if (AskYesNo ("Abort")) + break; + } + + if (sectorsRemaining.HighPart == 0 && sectorsRemaining.LowPart < fragmentSectorCount) + fragmentSectorCount = (int) sectorsRemaining.LowPart; + + if (ReadWriteSectors (false, TC_BOOT_LOADER_BUFFER_SEGMENT, 0, drive, ActivePartition.StartSector + sectorOffset, fragmentSectorCount, false) != BiosResultSuccess) + { + Print ("To fix bad sectors: 1) Terminate 2) Encrypt and decrypt sys partition 3) Retry\r\n"); + crypto_close (BootCryptoInfo); + goto err; + } + + AcquireSectorBuffer(); + + for (int i = 0; i < fragmentSectorCount; ++i) + { + CopyMemory (TC_BOOT_LOADER_BUFFER_SEGMENT, i * TC_LB_SIZE, SectorBuffer, TC_LB_SIZE); + + uint64 s = PimValueOrHiddenVolumeStartUnitNo + sectorOffset + i; + EncryptDataUnits (SectorBuffer, &s, 1, BootCryptoInfo); + + CopyMemory (SectorBuffer, TC_BOOT_LOADER_BUFFER_SEGMENT, i * TC_LB_SIZE, TC_LB_SIZE); + } + + ReleaseSectorBuffer(); + + if (ReadWriteSectors (true, TC_BOOT_LOADER_BUFFER_SEGMENT, 0, drive, HiddenVolumeStartSector + sectorOffset, fragmentSectorCount, false) != BiosResultSuccess) + { + crypto_close (BootCryptoInfo); + goto err; + } + + sectorsRemaining = sectorsRemaining - fragmentSectorCount; + sectorOffset = sectorOffset + fragmentSectorCount; + + if (!(statCount++ & 0xf)) + { + Print ("\rRemaining: "); + PrintSectorCountInMB (sectorsRemaining); + } + } + + crypto_close (BootCryptoInfo); + + if (sectorsRemaining.HighPart == 0 && sectorsRemaining.LowPart == 0) + { + status = true; + Print ("\rCopying completed."); + } + + PrintEndl (2); + goto ret; + +err: + exitKey = TC_BIOS_KEY_ESC; + GetKeyboardChar(); + +ret: + EraseMemory ((void *) TC_BOOT_LOADER_ARGS_OFFSET, sizeof (BootArguments)); + return status; +} + + +#else // TC_WINDOWS_BOOT_RESCUE_DISK_MODE + + +static void DecryptDrive (byte drive) +{ + byte exitKey; + if (!MountVolume (drive, exitKey, false, true)) + return; + + BootArguments *bootArguments = (BootArguments *) TC_BOOT_LOADER_ARGS_OFFSET; + + bool headerUpdateRequired = false; + uint64 sectorsRemaining = EncryptedVirtualPartition.EndSector + 1 - EncryptedVirtualPartition.StartSector; + uint64 sector = EncryptedVirtualPartition.EndSector + 1; + + int fragmentSectorCount = 0x7f; // Maximum safe value supported by BIOS + int statCount = 0; + + bool skipBadSectors = false; + + Print ("\r\nUse only if Windows cannot start. Decryption under Windows is much faster\r\n" + "(in VeraCrypt, select 'System' > 'Permanently Decrypt').\r\n\r\n"); + + if (!AskYesNo ("Decrypt now")) + { + crypto_close (BootCryptoInfo); + goto ret; + } + + if (EncryptedVirtualPartition.Drive == TC_INVALID_BIOS_DRIVE) + { + // Drive already decrypted + sectorsRemaining.HighPart = 0; + sectorsRemaining.LowPart = 0; + } + else + { + Print ("\r\nTo safely interrupt and defer decryption, press Esc.\r\n" + "WARNING: You can turn off power only after you press Esc.\r\n\r\n"); + } + + while (sectorsRemaining.HighPart != 0 || sectorsRemaining.LowPart != 0) + { + if (EscKeyPressed()) + break; + + if (sectorsRemaining.HighPart == 0 && sectorsRemaining.LowPart < fragmentSectorCount) + fragmentSectorCount = (int) sectorsRemaining.LowPart; + + sector = sector - fragmentSectorCount; + + if (!(statCount++ & 0xf)) + { + Print ("\rRemaining: "); + PrintSectorCountInMB (sectorsRemaining); + } + + if (ReadWriteSectors (false, TC_BOOT_LOADER_BUFFER_SEGMENT, 0, drive, sector, fragmentSectorCount, skipBadSectors) == BiosResultSuccess) + { + AcquireSectorBuffer(); + + for (int i = 0; i < fragmentSectorCount; ++i) + { + CopyMemory (TC_BOOT_LOADER_BUFFER_SEGMENT, i * TC_LB_SIZE, SectorBuffer, TC_LB_SIZE); + + uint64 s = sector + i; + DecryptDataUnits (SectorBuffer, &s, 1, BootCryptoInfo); + + CopyMemory (SectorBuffer, TC_BOOT_LOADER_BUFFER_SEGMENT, i * TC_LB_SIZE, TC_LB_SIZE); + } + + ReleaseSectorBuffer(); + + if (ReadWriteSectors (true, TC_BOOT_LOADER_BUFFER_SEGMENT, 0, drive, sector, fragmentSectorCount, skipBadSectors) != BiosResultSuccess && !skipBadSectors) + goto askBadSectorSkip; + } + else if (!skipBadSectors) + goto askBadSectorSkip; + + sectorsRemaining = sectorsRemaining - fragmentSectorCount; + headerUpdateRequired = true; + continue; + +askBadSectorSkip: + if (!AskYesNo ("Skip all bad sectors")) + break; + + skipBadSectors = true; + sector = sector + fragmentSectorCount; + fragmentSectorCount = 1; + } + + crypto_close (BootCryptoInfo); + + if (headerUpdateRequired) + { + Print ("\rUpdating header..."); + + AcquireSectorBuffer(); + uint64 headerSector; + headerSector.HighPart = 0; + headerSector.LowPart = TC_BOOT_VOLUME_HEADER_SECTOR; + + // Update encrypted area size in volume header + + CRYPTO_INFO *headerCryptoInfo = crypto_open(); + while (ReadSectors (SectorBuffer, drive, headerSector, 1) != BiosResultSuccess); + + if (ReadVolumeHeader (TRUE, (char *) SectorBuffer, &bootArguments->BootPassword, (int) (bootArguments->Flags >> 16), NULL, headerCryptoInfo) == 0) + { + DecryptBuffer (SectorBuffer + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, headerCryptoInfo); + + uint64 encryptedAreaLength = sectorsRemaining << TC_LB_SIZE_BIT_SHIFT_DIVISOR; + + for (int i = 7; i >= 0; --i) + { + SectorBuffer[TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH + i] = (byte) encryptedAreaLength.LowPart; + encryptedAreaLength = encryptedAreaLength >> 8; + } + + uint32 headerCrc32 = GetCrc32 (SectorBuffer + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC); + + for (i = 3; i >= 0; --i) + { + SectorBuffer[TC_HEADER_OFFSET_HEADER_CRC + i] = (byte) headerCrc32; + headerCrc32 >>= 8; + } + + EncryptBuffer (SectorBuffer + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, headerCryptoInfo); + } + + crypto_close (headerCryptoInfo); + + while (WriteSectors (SectorBuffer, drive, headerSector, 1) != BiosResultSuccess); + ReleaseSectorBuffer(); + + Print ("Done!\r\n"); + } + + if (sectorsRemaining.HighPart == 0 && sectorsRemaining.LowPart == 0) + Print ("\rDrive decrypted.\r\n"); + else + Print ("\r\nDecryption deferred.\r\n"); + + GetKeyboardChar(); +ret: + EraseMemory (bootArguments, sizeof (*bootArguments)); +} + + +static void RepairMenu () +{ + DriveGeometry bootLoaderDriveGeometry; + + if (GetDriveGeometry (BootLoaderDrive, bootLoaderDriveGeometry, true) != BiosResultSuccess) + { + // Some BIOSes may fail to get the geometry of an emulated floppy drive + bootLoaderDriveGeometry.Cylinders = 80; + bootLoaderDriveGeometry.Heads = 2; + bootLoaderDriveGeometry.Sectors = 18; + } + + while (true) + { + InitScreen(); + Print ("Available "); Print ("Repair Options"); Print (":\r\n"); + PrintRepeatedChar ('\xC4', 25); + PrintEndl(); + + enum + { + RestoreNone = 0, + DecryptVolume, + RestoreTrueCryptLoader, + RestoreVolumeHeader, + RestoreOriginalSystemLoader + }; + + static const char *options[] = { "Permanently decrypt system partition/drive", "Restore VeraCrypt Boot Loader", "Restore key data (volume header)", "Restore original system loader" }; + + int selection = AskSelection (options, + (BootSectorFlags & TC_BOOT_CFG_FLAG_RESCUE_DISK_ORIG_SYS_LOADER) ? array_capacity (options) : array_capacity (options) - 1); + + PrintEndl(); + + switch (selection) + { + case RestoreNone: + return; + + case DecryptVolume: + DecryptDrive (BootDrive); + continue; + + case RestoreOriginalSystemLoader: + if (!AskYesNo ("Is the system partition/drive decrypted")) + { + Print ("Please decrypt it first.\r\n"); + GetKeyboardChar(); + continue; + } + break; + } + + bool writeConfirmed = false; + BiosResult result; + + uint64 sector; + sector.HighPart = 0; + ChsAddress chs; + + byte mbrPartTable[TC_LB_SIZE - TC_MAX_MBR_BOOT_CODE_SIZE]; + AcquireSectorBuffer(); + + for (int i = (selection == RestoreVolumeHeader ? TC_BOOT_VOLUME_HEADER_SECTOR : TC_MBR_SECTOR); + i < TC_BOOT_LOADER_AREA_SECTOR_COUNT; ++i) + { + sector.LowPart = i; + + if (selection == RestoreOriginalSystemLoader) + sector.LowPart += TC_ORIG_BOOT_LOADER_BACKUP_SECTOR; + else if (selection == RestoreTrueCryptLoader) + sector.LowPart += TC_BOOT_LOADER_BACKUP_RESCUE_DISK_SECTOR; + + // The backup medium may be a floppy-emulated bootable CD. The emulation may fail if LBA addressing is used. + // Therefore, only CHS addressing can be used. + LbaToChs (bootLoaderDriveGeometry, sector, chs); + sector.LowPart = i; + + if (i == TC_MBR_SECTOR) + { + // Read current partition table + result = ReadSectors (SectorBuffer, TC_FIRST_BIOS_DRIVE, sector, 1); + if (result != BiosResultSuccess) + goto err; + + memcpy (mbrPartTable, SectorBuffer + TC_MAX_MBR_BOOT_CODE_SIZE, sizeof (mbrPartTable)); + } + + result = ReadSectors (SectorBuffer, BootLoaderDrive, chs, 1); + if (result != BiosResultSuccess) + goto err; + + if (i == TC_MBR_SECTOR) + { + // Preserve current partition table + memcpy (SectorBuffer + TC_MAX_MBR_BOOT_CODE_SIZE, mbrPartTable, sizeof (mbrPartTable)); + } + + // Volume header + if (i == TC_BOOT_VOLUME_HEADER_SECTOR) + { + if (selection == RestoreTrueCryptLoader) + continue; + + if (selection == RestoreVolumeHeader) + { + while (true) + { + bool validHeaderPresent = false; + uint32 masterKeyScheduleCrc; + + Password password; + int pim; + byte exitKey = AskPassword (password, pim); + + if (exitKey != TC_BIOS_KEY_ENTER) + goto abort; + + CRYPTO_INFO *cryptoInfo; + + CopyMemory (SectorBuffer, TC_BOOT_LOADER_BUFFER_SEGMENT, 0, TC_LB_SIZE); + ReleaseSectorBuffer(); + + // Restore volume header only if the current one cannot be used + if (OpenVolume (TC_FIRST_BIOS_DRIVE, password, pim, &cryptoInfo, nullptr, false, true)) + { + validHeaderPresent = true; + masterKeyScheduleCrc = GetCrc32 (cryptoInfo->ks, sizeof (cryptoInfo->ks)); + crypto_close (cryptoInfo); + } + + AcquireSectorBuffer(); + CopyMemory (TC_BOOT_LOADER_BUFFER_SEGMENT, 0, SectorBuffer, TC_LB_SIZE); + + if (ReadVolumeHeader (TRUE, (char *) SectorBuffer, &password, pim, &cryptoInfo, nullptr) == 0) + { + if (validHeaderPresent) + { + if (masterKeyScheduleCrc == GetCrc32 (cryptoInfo->ks, sizeof (cryptoInfo->ks))) + { + Print ("Original header preserved.\r\n"); + goto err; + } + + Print ("WARNING: Drive 0 contains a valid header!\r\n"); + } + + crypto_close (cryptoInfo); + break; + } + + Print ("Incorrect password.\r\n\r\n"); + } + } + } + + if (!writeConfirmed && !AskYesNo ("Modify drive 0")) + goto abort; + writeConfirmed = true; + + if (WriteSectors (SectorBuffer, TC_FIRST_BIOS_DRIVE, sector, 1) != BiosResultSuccess) + goto err; + } +done: + switch (selection) + { + case RestoreTrueCryptLoader: + Print ("VeraCrypt Boot Loader"); + break; + + case RestoreVolumeHeader: + Print ("Header"); + break; + + case RestoreOriginalSystemLoader: + Print ("System loader"); + break; + } + Print (" restored.\r\n"); + +err: GetKeyboardChar(); +abort: ReleaseSectorBuffer(); + } +} + +#endif // TC_WINDOWS_BOOT_RESCUE_DISK_MODE + + +#ifndef DEBUG +extern "C" void _acrtused () { } // Required by linker +#endif + + +void main () +{ + __asm mov BootLoaderDrive, dl + __asm mov BootSectorFlags, dh + +#ifdef TC_BOOT_TRACING_ENABLED + InitDebugPort(); +#endif + +#ifdef TC_BOOT_STACK_CHECKING_ENABLED + InitStackChecker(); +#endif + +#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE + ReadBootSectorUserConfiguration(); +#elif defined (TC_WINDOWS_BOOT_AES) + EnableHwEncryption (!(BootSectorFlags & TC_BOOT_CFG_FLAG_RESCUE_DISABLE_HW_ENCRYPTION)); +#endif + + InitVideoMode(); + InitScreen(); + + // Determine boot drive + BootDrive = BootLoaderDrive; + if (BootDrive < TC_FIRST_BIOS_DRIVE) + BootDrive = TC_FIRST_BIOS_DRIVE; + + // Query boot drive geometry + if (GetDriveGeometry (BootDrive, BootDriveGeometry) != BiosResultSuccess) + { + BootDrive = TC_FIRST_BIOS_DRIVE; + if (GetDriveGeometry (BootDrive, BootDriveGeometry) != BiosResultSuccess) + { +#ifdef TC_WINDOWS_BOOT_RESCUE_DISK_MODE + Print ("- Connect system drive to (SATA) port 1\r\n"); +#endif + GetKeyboardChar(); + } + else + BootDriveGeometryValid = true; + } + else + BootDriveGeometryValid = true; + +#ifdef TC_WINDOWS_BOOT_RESCUE_DISK_MODE + + // Check whether the user is not using the Rescue Disk to create a hidden system + + if (ReadWriteMBR (false, BootDrive, true) == BiosResultSuccess + && *(uint32 *) (SectorBuffer + 6) == 0x61726556 + && *(uint32 *) (SectorBuffer + 10) == 0x70797243 + && (SectorBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET] & TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE) != TC_HIDDEN_OS_CREATION_PHASE_NONE) + { + PrintError ("It appears you are creating a hidden OS."); + if (AskYesNo ("Is this correct")) + { + Print ("Please remove the Rescue Disk from the drive and restart."); + while (true); + } + } + +#endif // TC_WINDOWS_BOOT_RESCUE_DISK_MODE + + + // Main menu + + while (true) + { + byte exitKey; + InitScreen(); + +#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE + + // Hidden system setup + byte hiddenSystemCreationPhase = BootSectorFlags & TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE; + + if (hiddenSystemCreationPhase != TC_HIDDEN_OS_CREATION_PHASE_NONE) + { + PreventNormalSystemBoot = true; + PrintMainMenu(); + + if (hiddenSystemCreationPhase == TC_HIDDEN_OS_CREATION_PHASE_CLONING) + { + if (CopySystemPartitionToHiddenVolume (BootDrive, exitKey)) + { + BootSectorFlags = (BootSectorFlags & ~TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE) | TC_HIDDEN_OS_CREATION_PHASE_WIPING; + UpdateBootSectorConfiguration (BootLoaderDrive); + } + else if (exitKey == TC_BIOS_KEY_ESC) + goto bootMenu; + else + continue; + } + } + else + PrintMainMenu(); + + exitKey = BootEncryptedDrive(); + +#else // TC_WINDOWS_BOOT_RESCUE_DISK_MODE + + PrintMainMenu(); + exitKey = BootEncryptedDrive(); + + if (exitKey == TC_MENU_KEY_REPAIR) + { + RepairMenu(); + continue; + } + +#endif // TC_WINDOWS_BOOT_RESCUE_DISK_MODE + +bootMenu: + if (!PreventBootMenu) + BootMenu(); + } +} diff --git a/src/Boot/Windows/BootMain.h b/src/Boot/Windows/BootMain.h index b6e75fa6..2f212a18 100644 --- a/src/Boot/Windows/BootMain.h +++ b/src/Boot/Windows/BootMain.h @@ -1,34 +1,34 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Boot_BootMain -#define TC_HEADER_Boot_BootMain - -#include "TCdefs.h" -#include "Platform.h" - -static byte AskPassword (Password &password, int& pim); -static int AskSelection (const char *options[], size_t optionCount); -static bool AskYesNo (const char *message); -static byte BootEncryptedDrive (); -static void BootMenu (); -static void ExecuteBootSector (byte drive, byte *sectorBuffer); -static void InitScreen (); -static bool IsMenuKey (byte scanCode); -static bool MountVolume (byte drive, byte &exitKey); -static bool OpenVolume (byte drive, Password &password, CRYPTO_INFO **cryptoInfo, uint32 *headerSaltCrc32 = nullptr, bool skipNormal = false, bool skipHidden = false); -static void PrintMainMenu (); -static void RepairMenu (); - -#define TC_MENU_KEY_REPAIR TC_BIOS_KEY_F8 - -#endif // TC_HEADER_Boot_BootMain +/* + 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. +*/ + +#ifndef TC_HEADER_Boot_BootMain +#define TC_HEADER_Boot_BootMain + +#include "TCdefs.h" +#include "Platform.h" + +static byte AskPassword (Password &password, int& pim); +static int AskSelection (const char *options[], size_t optionCount); +static bool AskYesNo (const char *message); +static byte BootEncryptedDrive (); +static void BootMenu (); +static void ExecuteBootSector (byte drive, byte *sectorBuffer); +static void InitScreen (); +static bool IsMenuKey (byte scanCode); +static bool MountVolume (byte drive, byte &exitKey); +static bool OpenVolume (byte drive, Password &password, CRYPTO_INFO **cryptoInfo, uint32 *headerSaltCrc32 = nullptr, bool skipNormal = false, bool skipHidden = false); +static void PrintMainMenu (); +static void RepairMenu (); + +#define TC_MENU_KEY_REPAIR TC_BIOS_KEY_F8 + +#endif // TC_HEADER_Boot_BootMain diff --git a/src/Boot/Windows/BootMemory.cpp b/src/Boot/Windows/BootMemory.cpp index c1dd3833..505b731a 100644 --- a/src/Boot/Windows/BootMemory.cpp +++ b/src/Boot/Windows/BootMemory.cpp @@ -1,86 +1,86 @@ -/* - 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 "BootDefs.h" -#include "BootMemory.h" - -static uint32 MemoryMapContValue; - -static bool GetMemoryMapEntry (BiosMemoryMapEntry &entry) -{ - static const uint32 function = 0x0000E820UL; - static const uint32 magic = 0x534D4150UL; - static const uint32 bufferSize = sizeof (BiosMemoryMapEntry); - - bool carry = false; - uint32 resultMagic; - uint32 resultSize; - - __asm - { - push es - - lea di, function - TC_ASM_MOV_EAX_DI - lea di, MemoryMapContValue - TC_ASM_MOV_EBX_DI - lea di, bufferSize - TC_ASM_MOV_ECX_DI - lea di, magic - TC_ASM_MOV_EDX_DI - lea di, MemoryMapContValue - TC_ASM_MOV_DI_ECX - - // Use alternative segment to prevent memory corruption caused by buggy BIOSes - push TC_BOOT_LOADER_ALT_SEGMENT - pop es - mov di, 0 - - int 0x15 - jnc no_carry - mov carry, true - no_carry: - - lea di, resultMagic - TC_ASM_MOV_DI_EAX - lea di, MemoryMapContValue - TC_ASM_MOV_DI_EBX - lea di, resultSize - TC_ASM_MOV_DI_ECX - - pop es - } - - CopyMemory (TC_BOOT_LOADER_ALT_SEGMENT, 0, &entry, sizeof (entry)); - - // BIOS may set CF at the end of the list - if (carry) - MemoryMapContValue = 0; - - return resultMagic == magic && resultSize == bufferSize; -} - - -bool GetFirstBiosMemoryMapEntry (BiosMemoryMapEntry &entry) -{ - MemoryMapContValue = 0; - return GetMemoryMapEntry (entry); -} - - -bool GetNextBiosMemoryMapEntry (BiosMemoryMapEntry &entry) -{ - if (MemoryMapContValue == 0) - return false; - - return GetMemoryMapEntry (entry); -} +/* + 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 "BootDefs.h" +#include "BootMemory.h" + +static uint32 MemoryMapContValue; + +static bool GetMemoryMapEntry (BiosMemoryMapEntry &entry) +{ + static const uint32 function = 0x0000E820UL; + static const uint32 magic = 0x534D4150UL; + static const uint32 bufferSize = sizeof (BiosMemoryMapEntry); + + bool carry = false; + uint32 resultMagic; + uint32 resultSize; + + __asm + { + push es + + lea di, function + TC_ASM_MOV_EAX_DI + lea di, MemoryMapContValue + TC_ASM_MOV_EBX_DI + lea di, bufferSize + TC_ASM_MOV_ECX_DI + lea di, magic + TC_ASM_MOV_EDX_DI + lea di, MemoryMapContValue + TC_ASM_MOV_DI_ECX + + // Use alternative segment to prevent memory corruption caused by buggy BIOSes + push TC_BOOT_LOADER_ALT_SEGMENT + pop es + mov di, 0 + + int 0x15 + jnc no_carry + mov carry, true + no_carry: + + lea di, resultMagic + TC_ASM_MOV_DI_EAX + lea di, MemoryMapContValue + TC_ASM_MOV_DI_EBX + lea di, resultSize + TC_ASM_MOV_DI_ECX + + pop es + } + + CopyMemory (TC_BOOT_LOADER_ALT_SEGMENT, 0, &entry, sizeof (entry)); + + // BIOS may set CF at the end of the list + if (carry) + MemoryMapContValue = 0; + + return resultMagic == magic && resultSize == bufferSize; +} + + +bool GetFirstBiosMemoryMapEntry (BiosMemoryMapEntry &entry) +{ + MemoryMapContValue = 0; + return GetMemoryMapEntry (entry); +} + + +bool GetNextBiosMemoryMapEntry (BiosMemoryMapEntry &entry) +{ + if (MemoryMapContValue == 0) + return false; + + return GetMemoryMapEntry (entry); +} diff --git a/src/Boot/Windows/BootMemory.h b/src/Boot/Windows/BootMemory.h index 0ed0470d..d4ad1561 100644 --- a/src/Boot/Windows/BootMemory.h +++ b/src/Boot/Windows/BootMemory.h @@ -1,28 +1,28 @@ -/* - 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 "Platform.h" -#include "Bios.h" - -#pragma pack(1) - -struct BiosMemoryMapEntry -{ - uint64 BaseAddress; - uint64 Length; - uint32 Type; -}; - -#pragma pack() - -bool GetFirstBiosMemoryMapEntry (BiosMemoryMapEntry &entry); -bool GetNextBiosMemoryMapEntry (BiosMemoryMapEntry &entry); +/* + 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 "Platform.h" +#include "Bios.h" + +#pragma pack(1) + +struct BiosMemoryMapEntry +{ + uint64 BaseAddress; + uint64 Length; + uint32 Type; +}; + +#pragma pack() + +bool GetFirstBiosMemoryMapEntry (BiosMemoryMapEntry &entry); +bool GetNextBiosMemoryMapEntry (BiosMemoryMapEntry &entry); diff --git a/src/Boot/Windows/BootSector.asm b/src/Boot/Windows/BootSector.asm index e0049d29..0518414f 100644 --- a/src/Boot/Windows/BootSector.asm +++ b/src/Boot/Windows/BootSector.asm @@ -1,244 +1,244 @@ -; -; 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. -; - -.MODEL tiny -.386 -_TEXT SEGMENT USE16 - -INCLUDE BootDefs.i - -ORG 7C00h ; Standard boot sector offset - -start: - ; BIOS executes boot sector from 0:7C00 or 7C0:0000 (default CD boot loader address). - ; Far jump to the next instruction sets IP to the standard offset 7C00. - db 0EAh ; jmp 0:main - dw main, 0 - -loader_name_msg: - db ' VeraCrypt Boot Loader', 13, 10, 0 - -main: - cli - xor ax, ax - mov ds, ax - mov ss, ax - mov sp, 7C00h - sti - - ; Display boot loader name - test byte ptr [start + TC_BOOT_SECTOR_USER_CONFIG_OFFSET], TC_BOOT_USER_CFG_FLAG_SILENT_MODE - jnz skip_loader_name_msg - - lea si, loader_name_msg - call print -skip_loader_name_msg: - - ; Determine boot loader segment - mov ax, TC_BOOT_LOADER_SEGMENT - - ; Check available memory - cmp word ptr [ds:413h], TC_BOOT_LOADER_SEGMENT / 1024 * 16 + TC_BOOT_MEMORY_REQUIRED - jge memory_ok - - mov ax, TC_BOOT_LOADER_SEGMENT_LOW - - cmp word ptr [ds:413h], TC_BOOT_LOADER_SEGMENT_LOW / 1024 * 16 + TC_BOOT_MEMORY_REQUIRED - jge memory_ok - - ; Insufficient memory - mov ax, TC_BOOT_LOADER_LOWMEM_SEGMENT - -memory_ok: - mov es, ax - - ; Clear BSS section - xor al, al - mov di, TC_COM_EXECUTABLE_OFFSET - mov cx, TC_BOOT_MEMORY_REQUIRED * 1024 - TC_COM_EXECUTABLE_OFFSET - 1 - cld - rep stosb - - mov ax, es - sub ax, TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE / 16 ; Decompressor segment - mov es, ax - - ; Load decompressor - mov cl, TC_BOOT_LOADER_DECOMPRESSOR_START_SECTOR -retry_backup: - mov al, TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT - mov bx, TC_COM_EXECUTABLE_OFFSET - call read_sectors - - ; Decompressor checksum - xor ebx, ebx - mov si, TC_COM_EXECUTABLE_OFFSET - mov cx, TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_LB_SIZE - call checksum - push ebx - - ; Load compressed boot loader - mov bx, TC_BOOT_LOADER_COMPRESSED_BUFFER_OFFSET - mov cl, TC_BOOT_LOADER_START_SECTOR - mov al, TC_MAX_BOOT_LOADER_SECTOR_COUNT - - test backup_loader_used, 1 - jz non_backup - mov al, TC_BOOT_LOADER_BACKUP_SECTOR_COUNT - TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT - mov cl, TC_BOOT_LOADER_START_SECTOR + TC_BOOT_LOADER_BACKUP_SECTOR_COUNT - -non_backup: - call read_sectors - - ; Boot loader checksum - pop ebx - mov si, TC_BOOT_LOADER_COMPRESSED_BUFFER_OFFSET - mov cx, word ptr [start + TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET] - call checksum - - ; Verify checksum - cmp ebx, dword ptr [start + TC_BOOT_SECTOR_LOADER_CHECKSUM_OFFSET] - je checksum_ok - - ; Checksum incorrect - try using backup if available - test backup_loader_used, 1 - jnz loader_damaged - - mov backup_loader_used, 1 - mov cl, TC_BOOT_LOADER_DECOMPRESSOR_START_SECTOR + TC_BOOT_LOADER_BACKUP_SECTOR_COUNT - - test TC_BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE, byte ptr [start + TC_BOOT_SECTOR_CONFIG_OFFSET] - jnz retry_backup - -loader_damaged: - lea si, loader_damaged_msg - call print - lea si, loader_name_msg - call print - jmp $ -checksum_ok: - - ; Set up decompressor segment - mov ax, es - mov ds, ax - cli - mov ss, ax - mov sp, TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE - sti - - push dx - - ; Decompress boot loader - mov cx, word ptr [start + TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET] - sub cx, TC_GZIP_HEADER_SIZE - push cx ; Compressed data size - push TC_BOOT_LOADER_COMPRESSED_BUFFER_OFFSET + TC_GZIP_HEADER_SIZE ; Compressed data - push TC_MAX_BOOT_LOADER_DECOMPRESSED_SIZE ; Output buffer size - push TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE + TC_COM_EXECUTABLE_OFFSET ; Output buffer - - push cs - push decompressor_ret - push es - push TC_COM_EXECUTABLE_OFFSET - retf -decompressor_ret: - - add sp, 8 - pop dx - - ; Restore boot sector segment - push cs - pop ds - - ; Check decompression result - test ax, ax - jz decompression_ok - - lea si, loader_damaged_msg - call print - jmp $ -decompression_ok: - - ; DH = boot sector flags - mov dh, byte ptr [start + TC_BOOT_SECTOR_CONFIG_OFFSET] - - ; Set up boot loader segment - mov ax, es - add ax, TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE / 16 - mov es, ax - mov ds, ax - cli - mov ss, ax - mov sp, TC_BOOT_LOADER_STACK_TOP - sti - - ; Execute boot loader - push es - push TC_COM_EXECUTABLE_OFFSET - retf - - ; Print string -print: - xor bx, bx - mov ah, 0eh - cld - -@@: lodsb - test al, al - jz print_end - - int 10h - jmp @B - -print_end: - ret - - ; Read sectors of the first cylinder -read_sectors: - mov ch, 0 ; Cylinder - mov dh, 0 ; Head - ; DL = drive number passed from BIOS - mov ah, 2 - int 13h - jnc read_ok - - lea si, disk_error_msg - call print -read_ok: - ret - - ; Calculate checksum -checksum: - push ds - push es - pop ds - xor eax, eax - cld - -@@: lodsb - add ebx, eax - rol ebx, 1 - loop @B - - pop ds - ret - -backup_loader_used db 0 - -disk_error_msg db 'Disk error', 13, 10, 7, 0 -loader_damaged_msg db 7, 'Loader damaged! Repair with Rescue Disk', 0 - -ORG 7C00h + 510 - dw 0AA55h ; Boot sector signature - -_TEXT ENDS -END start +; +; 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. +; + +.MODEL tiny +.386 +_TEXT SEGMENT USE16 + +INCLUDE BootDefs.i + +ORG 7C00h ; Standard boot sector offset + +start: + ; BIOS executes boot sector from 0:7C00 or 7C0:0000 (default CD boot loader address). + ; Far jump to the next instruction sets IP to the standard offset 7C00. + db 0EAh ; jmp 0:main + dw main, 0 + +loader_name_msg: + db ' VeraCrypt Boot Loader', 13, 10, 0 + +main: + cli + xor ax, ax + mov ds, ax + mov ss, ax + mov sp, 7C00h + sti + + ; Display boot loader name + test byte ptr [start + TC_BOOT_SECTOR_USER_CONFIG_OFFSET], TC_BOOT_USER_CFG_FLAG_SILENT_MODE + jnz skip_loader_name_msg + + lea si, loader_name_msg + call print +skip_loader_name_msg: + + ; Determine boot loader segment + mov ax, TC_BOOT_LOADER_SEGMENT + + ; Check available memory + cmp word ptr [ds:413h], TC_BOOT_LOADER_SEGMENT / 1024 * 16 + TC_BOOT_MEMORY_REQUIRED + jge memory_ok + + mov ax, TC_BOOT_LOADER_SEGMENT_LOW + + cmp word ptr [ds:413h], TC_BOOT_LOADER_SEGMENT_LOW / 1024 * 16 + TC_BOOT_MEMORY_REQUIRED + jge memory_ok + + ; Insufficient memory + mov ax, TC_BOOT_LOADER_LOWMEM_SEGMENT + +memory_ok: + mov es, ax + + ; Clear BSS section + xor al, al + mov di, TC_COM_EXECUTABLE_OFFSET + mov cx, TC_BOOT_MEMORY_REQUIRED * 1024 - TC_COM_EXECUTABLE_OFFSET - 1 + cld + rep stosb + + mov ax, es + sub ax, TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE / 16 ; Decompressor segment + mov es, ax + + ; Load decompressor + mov cl, TC_BOOT_LOADER_DECOMPRESSOR_START_SECTOR +retry_backup: + mov al, TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT + mov bx, TC_COM_EXECUTABLE_OFFSET + call read_sectors + + ; Decompressor checksum + xor ebx, ebx + mov si, TC_COM_EXECUTABLE_OFFSET + mov cx, TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_LB_SIZE + call checksum + push ebx + + ; Load compressed boot loader + mov bx, TC_BOOT_LOADER_COMPRESSED_BUFFER_OFFSET + mov cl, TC_BOOT_LOADER_START_SECTOR + mov al, TC_MAX_BOOT_LOADER_SECTOR_COUNT + + test backup_loader_used, 1 + jz non_backup + mov al, TC_BOOT_LOADER_BACKUP_SECTOR_COUNT - TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT + mov cl, TC_BOOT_LOADER_START_SECTOR + TC_BOOT_LOADER_BACKUP_SECTOR_COUNT + +non_backup: + call read_sectors + + ; Boot loader checksum + pop ebx + mov si, TC_BOOT_LOADER_COMPRESSED_BUFFER_OFFSET + mov cx, word ptr [start + TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET] + call checksum + + ; Verify checksum + cmp ebx, dword ptr [start + TC_BOOT_SECTOR_LOADER_CHECKSUM_OFFSET] + je checksum_ok + + ; Checksum incorrect - try using backup if available + test backup_loader_used, 1 + jnz loader_damaged + + mov backup_loader_used, 1 + mov cl, TC_BOOT_LOADER_DECOMPRESSOR_START_SECTOR + TC_BOOT_LOADER_BACKUP_SECTOR_COUNT + + test TC_BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE, byte ptr [start + TC_BOOT_SECTOR_CONFIG_OFFSET] + jnz retry_backup + +loader_damaged: + lea si, loader_damaged_msg + call print + lea si, loader_name_msg + call print + jmp $ +checksum_ok: + + ; Set up decompressor segment + mov ax, es + mov ds, ax + cli + mov ss, ax + mov sp, TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE + sti + + push dx + + ; Decompress boot loader + mov cx, word ptr [start + TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET] + sub cx, TC_GZIP_HEADER_SIZE + push cx ; Compressed data size + push TC_BOOT_LOADER_COMPRESSED_BUFFER_OFFSET + TC_GZIP_HEADER_SIZE ; Compressed data + push TC_MAX_BOOT_LOADER_DECOMPRESSED_SIZE ; Output buffer size + push TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE + TC_COM_EXECUTABLE_OFFSET ; Output buffer + + push cs + push decompressor_ret + push es + push TC_COM_EXECUTABLE_OFFSET + retf +decompressor_ret: + + add sp, 8 + pop dx + + ; Restore boot sector segment + push cs + pop ds + + ; Check decompression result + test ax, ax + jz decompression_ok + + lea si, loader_damaged_msg + call print + jmp $ +decompression_ok: + + ; DH = boot sector flags + mov dh, byte ptr [start + TC_BOOT_SECTOR_CONFIG_OFFSET] + + ; Set up boot loader segment + mov ax, es + add ax, TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE / 16 + mov es, ax + mov ds, ax + cli + mov ss, ax + mov sp, TC_BOOT_LOADER_STACK_TOP + sti + + ; Execute boot loader + push es + push TC_COM_EXECUTABLE_OFFSET + retf + + ; Print string +print: + xor bx, bx + mov ah, 0eh + cld + +@@: lodsb + test al, al + jz print_end + + int 10h + jmp @B + +print_end: + ret + + ; Read sectors of the first cylinder +read_sectors: + mov ch, 0 ; Cylinder + mov dh, 0 ; Head + ; DL = drive number passed from BIOS + mov ah, 2 + int 13h + jnc read_ok + + lea si, disk_error_msg + call print +read_ok: + ret + + ; Calculate checksum +checksum: + push ds + push es + pop ds + xor eax, eax + cld + +@@: lodsb + add ebx, eax + rol ebx, 1 + loop @B + + pop ds + ret + +backup_loader_used db 0 + +disk_error_msg db 'Disk error', 13, 10, 7, 0 +loader_damaged_msg db 7, 'Loader damaged! Repair with Rescue Disk', 0 + +ORG 7C00h + 510 + dw 0AA55h ; Boot sector signature + +_TEXT ENDS +END start diff --git a/src/Boot/Windows/BootStrings.h b/src/Boot/Windows/BootStrings.h index dcf197a1..99c4dc4f 100644 --- a/src/Boot/Windows/BootStrings.h +++ b/src/Boot/Windows/BootStrings.h @@ -1,20 +1,20 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Boot_BootStrings -#define TC_HEADER_Boot_BootStrings - -#define TC_BOOT_STR_ERROR "Error: " -#define TC_BOOT_STR_NO_BOOT_PARTITION "No bootable partition found" -#define TC_BOOT_STR_UPGRADE_BIOS "- Upgrade BIOS\r\n- Use a different motherboard model/brand\r\n" - -#endif // TC_HEADER_Boot_BootStrings +/* + 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. +*/ + +#ifndef TC_HEADER_Boot_BootStrings +#define TC_HEADER_Boot_BootStrings + +#define TC_BOOT_STR_ERROR "Error: " +#define TC_BOOT_STR_NO_BOOT_PARTITION "No bootable partition found" +#define TC_BOOT_STR_UPGRADE_BIOS "- Upgrade BIOS\r\n- Use a different motherboard model/brand\r\n" + +#endif // TC_HEADER_Boot_BootStrings diff --git a/src/Boot/Windows/Decompressor.c b/src/Boot/Windows/Decompressor.c index 475a501d..3bed8c67 100644 --- a/src/Boot/Windows/Decompressor.c +++ b/src/Boot/Windows/Decompressor.c @@ -83,7 +83,7 @@ local int stored(struct state *s) s->bitbuf = 0; s->bitcnt = 0; - if (s->incnt + 4 > s->inlen) + if (s->incnt + 4 > s->inlen) return 2; /* not enough input */ /* get length and check against its one's complement */ @@ -93,7 +93,7 @@ local int stored(struct state *s) s->in[s->incnt++] != ((~len >> 8) & 0xff)) return -2; /* didn't match complement! */ - if (s->incnt + len > s->inlen) + if (s->incnt + len > s->inlen) return 2; /* not enough input */ /* copy len bytes from in to out */ @@ -379,21 +379,21 @@ local int dynamic(struct state *s) lengths[index++] = symbol; else { /* repeat instruction */ len = 0; /* assume repeating zeros */ - switch(symbol) - { - case 16: { /* repeat last length 3..6 times */ - if (index == 0) return -5; /* no last length! */ - len = lengths[index - 1]; /* last length */ - symbol = 3 + bits(s, 2); - break; - } - case 17: /* repeat zero 3..10 times */ - symbol = 3 + bits(s, 3); - break; - default: /* == 18, repeat zero 11..138 times */ - symbol = 11 + bits(s, 7); - break; - } + switch(symbol) + { + case 16: { /* repeat last length 3..6 times */ + if (index == 0) return -5; /* no last length! */ + len = lengths[index - 1]; /* last length */ + symbol = 3 + bits(s, 2); + break; + } + case 17: /* repeat zero 3..10 times */ + symbol = 3 + bits(s, 3); + break; + default: /* == 18, repeat zero 11..138 times */ + symbol = 11 + bits(s, 7); + break; + } if ((index + symbol > nlen + ndist)) return -6; /* too many lengths! */ while (symbol--) /* repeat last or zero symbol times */ @@ -401,8 +401,8 @@ local int dynamic(struct state *s) } } - /* check for end-of-block code -- there better be one! */ - if (lengths[256] == 0) + /* check for end-of-block code -- there better be one! */ + if (lengths[256] == 0) return -9; /* build huffman table for literal/length codes */ @@ -423,50 +423,50 @@ local int dynamic(struct state *s) void _acrtused () { } // Decompress deflated data -int far main ( - unsigned char *dest, /* pointer to destination pointer */ - unsigned int destlen, /* amount of output space */ - unsigned char *source, /* pointer to source data pointer */ - unsigned int sourcelen) -{ - struct state s; /* input/output state */ - int last, type; /* block information */ - int err; /* return value */ - - /* initialize output state */ - s.out = dest; - s.outlen = destlen; /* ignored if dest is NIL */ - s.outcnt = 0; - - /* initialize input state */ - s.in = source; - s.inlen = sourcelen; - s.incnt = 0; - s.bitbuf = 0; - s.bitcnt = 0; - - /* process blocks until last block or error */ - do { - last = bits(&s, 1); /* one if last block */ - type = bits(&s, 2); /* block type 0..3 */ - switch(type) - { - case 0: - err = stored(&s); - break; - case 1: - err = fixed(&s); - break; - case 2: - err = dynamic(&s); - break; - default: - err = -1; /* type == 3, invalid */ - break; - } - - if (err != 0) break; /* return with error */ - } while (!last); - - return err; +int far main ( + unsigned char *dest, /* pointer to destination pointer */ + unsigned int destlen, /* amount of output space */ + unsigned char *source, /* pointer to source data pointer */ + unsigned int sourcelen) +{ + struct state s; /* input/output state */ + int last, type; /* block information */ + int err; /* return value */ + + /* initialize output state */ + s.out = dest; + s.outlen = destlen; /* ignored if dest is NIL */ + s.outcnt = 0; + + /* initialize input state */ + s.in = source; + s.inlen = sourcelen; + s.incnt = 0; + s.bitbuf = 0; + s.bitcnt = 0; + + /* process blocks until last block or error */ + do { + last = bits(&s, 1); /* one if last block */ + type = bits(&s, 2); /* block type 0..3 */ + switch(type) + { + case 0: + err = stored(&s); + break; + case 1: + err = fixed(&s); + break; + case 2: + err = dynamic(&s); + break; + default: + err = -1; /* type == 3, invalid */ + break; + } + + if (err != 0) break; /* return with error */ + } while (!last); + + return err; } diff --git a/src/Boot/Windows/IntFilter.cpp b/src/Boot/Windows/IntFilter.cpp index 0671c4d0..d9cd92df 100644 --- a/src/Boot/Windows/IntFilter.cpp +++ b/src/Boot/Windows/IntFilter.cpp @@ -1,645 +1,645 @@ -/* - 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 "Platform.h" -#include "BootMemory.h" -#include "BootConfig.h" -#include "BootConsoleIo.h" -#include "BootDebug.h" -#include "BootDefs.h" -#include "BootDiskIo.h" -#include "BootEncryptedIo.h" -#include "BootStrings.h" -#include "IntFilter.h" - -static uint32 OriginalInt13Handler; -static uint32 OriginalInt15Handler; - -static Registers IntRegisters; - - -bool Int13Filter () -{ - CheckStack(); - - Registers regs; - memcpy (®s, &IntRegisters, sizeof (regs)); - __asm sti - - static int ReEntryCount = -1; - ++ReEntryCount; - - byte function = (byte) (regs.AX >> 8); - -#ifdef TC_TRACE_INT13 - DisableScreenOutput(); - - PrintHex (function); - - Print (" EN:"); Print (ReEntryCount); - Print (" SS:"); PrintHex (regs.SS); - - uint16 spdbg; - __asm mov spdbg, sp - PrintChar (' '); - PrintHex (spdbg); - PrintChar ('<'); PrintHex (TC_BOOT_LOADER_STACK_TOP); - -#endif - - bool passOriginalRequest = true; - - switch (function) - { - case 0x2: // Read sectors - case 0x3: // Write sectors - { - byte drive = (byte) regs.DX; - - ChsAddress chs; - chs.Cylinder = ((regs.CX << 2) & 0x300) | (regs.CX >> 8); - chs.Head = regs.DX >> 8; - chs.Sector = regs.CX & 0x3f; - - byte sectorCount = (byte) regs.AX; - -#ifdef TC_TRACE_INT13 - PrintVal (": Drive", drive - TC_FIRST_BIOS_DRIVE, false); - Print (" Chs: "); Print (chs); -#endif - - uint64 sector; - if (drive == BootDrive) - { - if (!BootDriveGeometryValid) - TC_THROW_FATAL_EXCEPTION; - - ChsToLba (BootDriveGeometry, chs, sector); -#ifdef TC_TRACE_INT13 - PrintVal (" Sec", sector.LowPart, false); -#endif - } - -#ifdef TC_TRACE_INT13 - PrintVal (" Count", sectorCount, false); - Print (" Buf: "); PrintHex (regs.ES); PrintChar (':'); PrintHex (regs.BX); - PrintEndl(); -#endif - - if (ReEntryCount == 0 && drive == EncryptedVirtualPartition.Drive) - { - BiosResult result; - - if (function == 0x3) - result = WriteEncryptedSectors (regs.ES, regs.BX, drive, sector, sectorCount); - else - result = ReadEncryptedSectors (regs.ES, regs.BX, drive, sector, sectorCount); - - __asm cli - - memcpy (&IntRegisters, ®s, sizeof (regs)); - IntRegisters.AX = (uint16) result << 8; - - if (result == BiosResultSuccess) - { - IntRegisters.AX |= sectorCount; - IntRegisters.Flags &= ~TC_X86_CARRY_FLAG; - } - else - IntRegisters.Flags |= TC_X86_CARRY_FLAG; - - passOriginalRequest = false; - } - } - break; - - case 0x42: // Read sectors LBA - case 0x43: // Write sectors LBA - { - byte drive = (byte) regs.DX; - - BiosLbaPacket lba; - CopyMemory (regs.DS, regs.SI, (byte *) &lba, sizeof (lba)); - -#ifdef TC_TRACE_INT13 - PrintVal (": Drive", drive - TC_FIRST_BIOS_DRIVE, false); - PrintVal (" Sec", lba.Sector.LowPart, false); - PrintVal (" Count", lba.SectorCount, false); - PrintVal (" Buf", lba.Buffer, false, true); - PrintEndl(); -#endif - - if (ReEntryCount == 0 && drive == EncryptedVirtualPartition.Drive) - { - BiosResult result; - - uint16 segment = (uint16) (lba.Buffer >> 16); - uint16 offset = (uint16) lba.Buffer; - - if (function == 0x43) - result = WriteEncryptedSectors (segment, offset, drive, lba.Sector, lba.SectorCount); - else - result = ReadEncryptedSectors (segment, offset, drive, lba.Sector, lba.SectorCount); - - __asm cli - - memcpy (&IntRegisters, ®s, sizeof (regs)); - IntRegisters.AX = (IntRegisters.AX & 0xff) | ((uint16) result << 8); - - if (result == BiosResultSuccess) - IntRegisters.Flags &= ~TC_X86_CARRY_FLAG; - else - IntRegisters.Flags |= TC_X86_CARRY_FLAG; - - passOriginalRequest = false; - } - } - break; - - default: -#ifdef TC_TRACE_INT13 - PrintEndl(); -#endif - break; - } - -#ifdef TC_TRACE_INT13 - EnableScreenOutput(); -#endif - --ReEntryCount; - - return passOriginalRequest; -} - - -#define TC_MAX_MEMORY_MAP_SIZE 80 - -BiosMemoryMapEntry BiosMemoryMap[TC_MAX_MEMORY_MAP_SIZE]; -static size_t BiosMemoryMapSize; - - -static void CreateBootLoaderMemoryMapEntry (BiosMemoryMapEntry *newMapEntry, uint32 bootLoaderStart) -{ - newMapEntry->Type = 0x2; - newMapEntry->BaseAddress.HighPart = 0; - newMapEntry->BaseAddress.LowPart = bootLoaderStart; - newMapEntry->Length.HighPart = 0; - newMapEntry->Length.LowPart = TC_BOOT_MEMORY_REQUIRED * 1024UL; -} - - -static bool CreateNewBiosMemoryMap () -{ - // Create a new BIOS memory map presenting the memory area of the loader as reserved - - BiosMemoryMapSize = 0; - BiosMemoryMapEntry entry; - BiosMemoryMapEntry *newMapEntry = BiosMemoryMap; - - const BiosMemoryMapEntry *mapEnd = BiosMemoryMap + TC_MAX_MEMORY_MAP_SIZE; - - uint64 bootLoaderStart; - bootLoaderStart.HighPart = 0; - - uint16 codeSeg; - __asm mov codeSeg, cs - bootLoaderStart.LowPart = GetLinearAddress (codeSeg, 0); - - uint64 bootLoaderEnd; - bootLoaderEnd.HighPart = 0; - bootLoaderEnd.LowPart = bootLoaderStart.LowPart + TC_BOOT_MEMORY_REQUIRED * 1024UL; - - bool loaderEntryInserted = false; - - if (GetFirstBiosMemoryMapEntry (entry)) - { - do - { - uint64 entryEnd = entry.BaseAddress + entry.Length; - - if (entry.Type == 0x1 && RegionsIntersect (bootLoaderStart, TC_BOOT_MEMORY_REQUIRED * 1024UL, entry.BaseAddress, entryEnd - 1)) - { - // Free map entry covers the boot loader area - - if (entry.BaseAddress < bootLoaderStart) - { - // Create free entry below the boot loader area - if (newMapEntry >= mapEnd) - goto mapOverflow; - - *newMapEntry = entry; - newMapEntry->Length = bootLoaderStart - entry.BaseAddress; - ++newMapEntry; - } - - if (!loaderEntryInserted) - { - // Create reserved entry for the boot loader if it has not been done yet - if (newMapEntry >= mapEnd) - goto mapOverflow; - - CreateBootLoaderMemoryMapEntry (newMapEntry, bootLoaderStart.LowPart); - ++newMapEntry; - loaderEntryInserted = true; - } - - if (bootLoaderEnd < entryEnd) - { - // Create free entry above the boot loader area - if (newMapEntry >= mapEnd) - goto mapOverflow; - - newMapEntry->Type = 0x1; - newMapEntry->BaseAddress = bootLoaderEnd; - newMapEntry->Length = entryEnd - bootLoaderEnd; - ++newMapEntry; - } - } - else - { - if (newMapEntry >= mapEnd) - goto mapOverflow; - - if (!loaderEntryInserted && entry.BaseAddress > bootLoaderStart) - { - // Create reserved entry for the boot loader if it has not been done yet - CreateBootLoaderMemoryMapEntry (newMapEntry, bootLoaderStart.LowPart); - ++newMapEntry; - loaderEntryInserted = true; - } - - // Copy map entry - *newMapEntry++ = entry; - } - - } while (GetNextBiosMemoryMapEntry (entry)); - } - - BiosMemoryMapSize = newMapEntry - BiosMemoryMap; - return true; - -mapOverflow: - size_t overSize = 0; - while (GetNextBiosMemoryMapEntry (entry)) - { - ++overSize; - } - - PrintErrorNoEndl ("MMP:"); - Print (overSize); - PrintEndl(); - - return false; -} - - -bool Int15Filter () -{ - CheckStack(); - -#ifdef TC_TRACE_INT15 - DisableScreenOutput(); - - Print ("15-"); - PrintHex (IntRegisters.AX); - - Print (" SS:"); PrintHex (IntRegisters.SS); - - uint16 spdbg; - __asm mov spdbg, sp - PrintChar (' '); - PrintHex (spdbg); - PrintChar ('<'); PrintHex (TC_BOOT_LOADER_STACK_TOP); - - Print (" EAX:"); PrintHex (IntRegisters.EAX); - Print (" EBX:"); PrintHex (IntRegisters.EBX); - Print (" ECX:"); PrintHex (IntRegisters.ECX); - Print (" EDX:"); PrintHex (IntRegisters.EDX); - Print (" DI:"); PrintHex (IntRegisters.DI); - PrintEndl(); - -#endif - - if (IntRegisters.EBX >= BiosMemoryMapSize) - { - IntRegisters.Flags |= TC_X86_CARRY_FLAG; - IntRegisters.EBX = 0; - IntRegisters.AX = -1; - } - else - { - CopyMemory ((byte *) &BiosMemoryMap[IntRegisters.EBX], IntRegisters.ES, IntRegisters.DI, sizeof (BiosMemoryMap[0])); - - IntRegisters.Flags &= ~TC_X86_CARRY_FLAG; - IntRegisters.EAX = 0x534D4150UL; - - ++IntRegisters.EBX; - if (IntRegisters.EBX >= BiosMemoryMapSize) - IntRegisters.EBX = 0; - - IntRegisters.ECX = sizeof (BiosMemoryMap[0]); - } - - if (IntRegisters.EBX == 0 && !(BootSectorFlags & TC_BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER)) - { - // Uninstall filter when the modified map has been issued three times to prevent - // problems with hardware drivers on some notebooks running Windows XP. - - static int CompleteMapIssueCount = 0; - if (++CompleteMapIssueCount >= 3) - { - __asm - { - cli - push es - - lea si, OriginalInt15Handler - xor ax, ax - mov es, ax - mov di, 0x15 * 4 - - mov ax, [si] - mov es:[di], ax - mov ax, [si + 2] - mov es:[di + 2], ax - - pop es - sti - } - } - } - -#ifdef TC_TRACE_INT15 - BiosMemoryMapEntry entry; - CopyMemory (IntRegisters.ES, IntRegisters.DI, (byte *) &entry, sizeof (entry)); - PrintHex (entry.Type); PrintChar (' '); - PrintHex (entry.BaseAddress); PrintChar (' '); - PrintHex (entry.Length); PrintChar (' '); - PrintHex (entry.BaseAddress + entry.Length); PrintEndl(); - - Print ("EAX:"); PrintHex (IntRegisters.EAX); - Print (" EBX:"); PrintHex (IntRegisters.EBX); - Print (" ECX:"); PrintHex (IntRegisters.ECX); - Print (" EDX:"); PrintHex (IntRegisters.EDX); - Print (" DI:"); PrintHex (IntRegisters.DI); - Print (" FL:"); PrintHex (IntRegisters.Flags); - PrintEndl (2); -#endif - -#ifdef TC_TRACE_INT15 - EnableScreenOutput(); -#endif - return false; -} - - -void IntFilterEntry () -{ - // No automatic variables should be used in this scope as SS may change - static uint16 OrigStackPointer; - static uint16 OrigStackSegment; - - __asm - { - pushf - pushad - - cli - mov cs:IntRegisters.DI, di - - lea di, cs:IntRegisters.EAX - TC_ASM_EMIT4 (66,2E,89,05) // mov [cs:di], eax - lea di, cs:IntRegisters.EBX - TC_ASM_EMIT4 (66,2E,89,1D) // mov [cs:di], ebx - lea di, cs:IntRegisters.ECX - TC_ASM_EMIT4 (66,2E,89,0D) // mov [cs:di], ecx - lea di, cs:IntRegisters.EDX - TC_ASM_EMIT4 (66,2E,89,15) // mov [cs:di], edx - - mov ax, [bp + 8] - mov cs:IntRegisters.Flags, ax - - mov cs:IntRegisters.SI, si - mov si, [bp + 2] // Int number - - mov cs:IntRegisters.DS, ds - mov cs:IntRegisters.ES, es - mov cs:IntRegisters.SS, ss - - // Compiler assumes SS == DS - use our stack if this condition is not met - mov ax, ss - mov bx, cs - cmp ax, bx - jz stack_ok - - mov cs:OrigStackPointer, sp - mov cs:OrigStackSegment, ss - mov ax, cs - mov ss, ax - mov sp, TC_BOOT_LOADER_STACK_TOP - - stack_ok: - // DS = CS - push ds - push es - mov ax, cs - mov ds, ax - mov es, ax - - push si // Int number - - // Filter request - cmp si, 0x15 - je filter15 - cmp si, 0x13 - jne $ - - call Int13Filter - jmp s0 - - filter15: - call Int15Filter - - s0: - pop si // Int number - pop es - pop ds - - // Restore original SS:SP if our stack is empty - cli - mov bx, TC_BOOT_LOADER_STACK_TOP - cmp bx, sp - jnz stack_in_use - - mov ss, cs:OrigStackSegment - mov sp, cs:OrigStackPointer - stack_in_use: - - test ax, ax // passOriginalRequest - jnz pass_request - - // Return results of filtered request - popad - popf - mov ax, cs:IntRegisters.Flags - mov [bp + 8], ax - leave - - lea di, cs:IntRegisters.EAX - TC_ASM_EMIT4 (66,2E,8B,05) // mov eax, [cs:di] - lea di, cs:IntRegisters.EBX - TC_ASM_EMIT4 (66,2E,8B,1D) // mov ebx, [cs:di] - lea di, cs:IntRegisters.ECX - TC_ASM_EMIT4 (66,2E,8B,0D) // mov ecx, [cs:di] - lea di, cs:IntRegisters.EDX - TC_ASM_EMIT4 (66,2E,8B,15) // mov edx, [cs:di] - - mov di, cs:IntRegisters.DI - mov si, cs:IntRegisters.SI - mov es, cs:IntRegisters.ES - mov ds, cs:IntRegisters.DS - - sti - add sp, 2 - iret - - // Pass original request - pass_request: - sti - cmp si, 0x15 - je pass15 - cmp si, 0x13 - jne $ - - popad - popf - leave - add sp, 2 - jmp cs:OriginalInt13Handler - - pass15: - popad - popf - leave - add sp, 2 - jmp cs:OriginalInt15Handler - } -} - - -void Int13FilterEntry () -{ - __asm - { - leave - push 0x13 - jmp IntFilterEntry - } -} - - -static void Int15FilterEntry () -{ - __asm - { - pushf - cmp ax, 0xe820 // Get system memory map - je filter - - popf - leave - jmp cs:OriginalInt15Handler - - filter: - leave - push 0x15 - jmp IntFilterEntry - } -} - - -bool InstallInterruptFilters () -{ - -#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE - - // If the filters have already been installed, it usually indicates stack corruption - // and a consequent reentry of this routine without a system reset. - - uint32 currentInt13Handler; - CopyMemory (0, 0x13 * 4, ¤tInt13Handler, sizeof (currentInt13Handler)); - - if (currentInt13Handler == (uint32) Int13FilterEntry) - { - PrintError ("Memory corrupted"); - Print (TC_BOOT_STR_UPGRADE_BIOS); - - GetKeyboardChar(); - return true; - } - -#endif - - if (!CreateNewBiosMemoryMap()) - return false; - - __asm - { - cli - push es - - // Save original INT 13 handler - xor ax, ax - mov es, ax - - mov si, 0x13 * 4 - lea di, OriginalInt13Handler - - mov ax, es:[si] - mov [di], ax - mov ax, es:[si + 2] - mov [di + 2], ax - - // Install INT 13 filter - lea ax, Int13FilterEntry - mov es:[si], ax - mov es:[si + 2], cs - - // Save original INT 15 handler - mov si, 0x15 * 4 - lea di, OriginalInt15Handler - - mov ax, es:[si] - mov [di], ax - mov ax, es:[si + 2] - mov [di + 2], ax - - // Install INT 15 filter - lea ax, Int15FilterEntry - mov es:[si], ax - mov es:[si + 2], cs - - // If the BIOS does not support system memory map (INT15 0xe820), - // set amount of available memory to CS:0000 - 0:0000 - cmp BiosMemoryMapSize, 1 - jg mem_map_ok - mov ax, cs - shr ax, 10 - 4 // CS * 16 / 1024 - mov es:[0x413], ax // = KBytes available - mem_map_ok: - - pop es - sti - } - - return true; -} +/* + 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 "Platform.h" +#include "BootMemory.h" +#include "BootConfig.h" +#include "BootConsoleIo.h" +#include "BootDebug.h" +#include "BootDefs.h" +#include "BootDiskIo.h" +#include "BootEncryptedIo.h" +#include "BootStrings.h" +#include "IntFilter.h" + +static uint32 OriginalInt13Handler; +static uint32 OriginalInt15Handler; + +static Registers IntRegisters; + + +bool Int13Filter () +{ + CheckStack(); + + Registers regs; + memcpy (®s, &IntRegisters, sizeof (regs)); + __asm sti + + static int ReEntryCount = -1; + ++ReEntryCount; + + byte function = (byte) (regs.AX >> 8); + +#ifdef TC_TRACE_INT13 + DisableScreenOutput(); + + PrintHex (function); + + Print (" EN:"); Print (ReEntryCount); + Print (" SS:"); PrintHex (regs.SS); + + uint16 spdbg; + __asm mov spdbg, sp + PrintChar (' '); + PrintHex (spdbg); + PrintChar ('<'); PrintHex (TC_BOOT_LOADER_STACK_TOP); + +#endif + + bool passOriginalRequest = true; + + switch (function) + { + case 0x2: // Read sectors + case 0x3: // Write sectors + { + byte drive = (byte) regs.DX; + + ChsAddress chs; + chs.Cylinder = ((regs.CX << 2) & 0x300) | (regs.CX >> 8); + chs.Head = regs.DX >> 8; + chs.Sector = regs.CX & 0x3f; + + byte sectorCount = (byte) regs.AX; + +#ifdef TC_TRACE_INT13 + PrintVal (": Drive", drive - TC_FIRST_BIOS_DRIVE, false); + Print (" Chs: "); Print (chs); +#endif + + uint64 sector; + if (drive == BootDrive) + { + if (!BootDriveGeometryValid) + TC_THROW_FATAL_EXCEPTION; + + ChsToLba (BootDriveGeometry, chs, sector); +#ifdef TC_TRACE_INT13 + PrintVal (" Sec", sector.LowPart, false); +#endif + } + +#ifdef TC_TRACE_INT13 + PrintVal (" Count", sectorCount, false); + Print (" Buf: "); PrintHex (regs.ES); PrintChar (':'); PrintHex (regs.BX); + PrintEndl(); +#endif + + if (ReEntryCount == 0 && drive == EncryptedVirtualPartition.Drive) + { + BiosResult result; + + if (function == 0x3) + result = WriteEncryptedSectors (regs.ES, regs.BX, drive, sector, sectorCount); + else + result = ReadEncryptedSectors (regs.ES, regs.BX, drive, sector, sectorCount); + + __asm cli + + memcpy (&IntRegisters, ®s, sizeof (regs)); + IntRegisters.AX = (uint16) result << 8; + + if (result == BiosResultSuccess) + { + IntRegisters.AX |= sectorCount; + IntRegisters.Flags &= ~TC_X86_CARRY_FLAG; + } + else + IntRegisters.Flags |= TC_X86_CARRY_FLAG; + + passOriginalRequest = false; + } + } + break; + + case 0x42: // Read sectors LBA + case 0x43: // Write sectors LBA + { + byte drive = (byte) regs.DX; + + BiosLbaPacket lba; + CopyMemory (regs.DS, regs.SI, (byte *) &lba, sizeof (lba)); + +#ifdef TC_TRACE_INT13 + PrintVal (": Drive", drive - TC_FIRST_BIOS_DRIVE, false); + PrintVal (" Sec", lba.Sector.LowPart, false); + PrintVal (" Count", lba.SectorCount, false); + PrintVal (" Buf", lba.Buffer, false, true); + PrintEndl(); +#endif + + if (ReEntryCount == 0 && drive == EncryptedVirtualPartition.Drive) + { + BiosResult result; + + uint16 segment = (uint16) (lba.Buffer >> 16); + uint16 offset = (uint16) lba.Buffer; + + if (function == 0x43) + result = WriteEncryptedSectors (segment, offset, drive, lba.Sector, lba.SectorCount); + else + result = ReadEncryptedSectors (segment, offset, drive, lba.Sector, lba.SectorCount); + + __asm cli + + memcpy (&IntRegisters, ®s, sizeof (regs)); + IntRegisters.AX = (IntRegisters.AX & 0xff) | ((uint16) result << 8); + + if (result == BiosResultSuccess) + IntRegisters.Flags &= ~TC_X86_CARRY_FLAG; + else + IntRegisters.Flags |= TC_X86_CARRY_FLAG; + + passOriginalRequest = false; + } + } + break; + + default: +#ifdef TC_TRACE_INT13 + PrintEndl(); +#endif + break; + } + +#ifdef TC_TRACE_INT13 + EnableScreenOutput(); +#endif + --ReEntryCount; + + return passOriginalRequest; +} + + +#define TC_MAX_MEMORY_MAP_SIZE 80 + +BiosMemoryMapEntry BiosMemoryMap[TC_MAX_MEMORY_MAP_SIZE]; +static size_t BiosMemoryMapSize; + + +static void CreateBootLoaderMemoryMapEntry (BiosMemoryMapEntry *newMapEntry, uint32 bootLoaderStart) +{ + newMapEntry->Type = 0x2; + newMapEntry->BaseAddress.HighPart = 0; + newMapEntry->BaseAddress.LowPart = bootLoaderStart; + newMapEntry->Length.HighPart = 0; + newMapEntry->Length.LowPart = TC_BOOT_MEMORY_REQUIRED * 1024UL; +} + + +static bool CreateNewBiosMemoryMap () +{ + // Create a new BIOS memory map presenting the memory area of the loader as reserved + + BiosMemoryMapSize = 0; + BiosMemoryMapEntry entry; + BiosMemoryMapEntry *newMapEntry = BiosMemoryMap; + + const BiosMemoryMapEntry *mapEnd = BiosMemoryMap + TC_MAX_MEMORY_MAP_SIZE; + + uint64 bootLoaderStart; + bootLoaderStart.HighPart = 0; + + uint16 codeSeg; + __asm mov codeSeg, cs + bootLoaderStart.LowPart = GetLinearAddress (codeSeg, 0); + + uint64 bootLoaderEnd; + bootLoaderEnd.HighPart = 0; + bootLoaderEnd.LowPart = bootLoaderStart.LowPart + TC_BOOT_MEMORY_REQUIRED * 1024UL; + + bool loaderEntryInserted = false; + + if (GetFirstBiosMemoryMapEntry (entry)) + { + do + { + uint64 entryEnd = entry.BaseAddress + entry.Length; + + if (entry.Type == 0x1 && RegionsIntersect (bootLoaderStart, TC_BOOT_MEMORY_REQUIRED * 1024UL, entry.BaseAddress, entryEnd - 1)) + { + // Free map entry covers the boot loader area + + if (entry.BaseAddress < bootLoaderStart) + { + // Create free entry below the boot loader area + if (newMapEntry >= mapEnd) + goto mapOverflow; + + *newMapEntry = entry; + newMapEntry->Length = bootLoaderStart - entry.BaseAddress; + ++newMapEntry; + } + + if (!loaderEntryInserted) + { + // Create reserved entry for the boot loader if it has not been done yet + if (newMapEntry >= mapEnd) + goto mapOverflow; + + CreateBootLoaderMemoryMapEntry (newMapEntry, bootLoaderStart.LowPart); + ++newMapEntry; + loaderEntryInserted = true; + } + + if (bootLoaderEnd < entryEnd) + { + // Create free entry above the boot loader area + if (newMapEntry >= mapEnd) + goto mapOverflow; + + newMapEntry->Type = 0x1; + newMapEntry->BaseAddress = bootLoaderEnd; + newMapEntry->Length = entryEnd - bootLoaderEnd; + ++newMapEntry; + } + } + else + { + if (newMapEntry >= mapEnd) + goto mapOverflow; + + if (!loaderEntryInserted && entry.BaseAddress > bootLoaderStart) + { + // Create reserved entry for the boot loader if it has not been done yet + CreateBootLoaderMemoryMapEntry (newMapEntry, bootLoaderStart.LowPart); + ++newMapEntry; + loaderEntryInserted = true; + } + + // Copy map entry + *newMapEntry++ = entry; + } + + } while (GetNextBiosMemoryMapEntry (entry)); + } + + BiosMemoryMapSize = newMapEntry - BiosMemoryMap; + return true; + +mapOverflow: + size_t overSize = 0; + while (GetNextBiosMemoryMapEntry (entry)) + { + ++overSize; + } + + PrintErrorNoEndl ("MMP:"); + Print (overSize); + PrintEndl(); + + return false; +} + + +bool Int15Filter () +{ + CheckStack(); + +#ifdef TC_TRACE_INT15 + DisableScreenOutput(); + + Print ("15-"); + PrintHex (IntRegisters.AX); + + Print (" SS:"); PrintHex (IntRegisters.SS); + + uint16 spdbg; + __asm mov spdbg, sp + PrintChar (' '); + PrintHex (spdbg); + PrintChar ('<'); PrintHex (TC_BOOT_LOADER_STACK_TOP); + + Print (" EAX:"); PrintHex (IntRegisters.EAX); + Print (" EBX:"); PrintHex (IntRegisters.EBX); + Print (" ECX:"); PrintHex (IntRegisters.ECX); + Print (" EDX:"); PrintHex (IntRegisters.EDX); + Print (" DI:"); PrintHex (IntRegisters.DI); + PrintEndl(); + +#endif + + if (IntRegisters.EBX >= BiosMemoryMapSize) + { + IntRegisters.Flags |= TC_X86_CARRY_FLAG; + IntRegisters.EBX = 0; + IntRegisters.AX = -1; + } + else + { + CopyMemory ((byte *) &BiosMemoryMap[IntRegisters.EBX], IntRegisters.ES, IntRegisters.DI, sizeof (BiosMemoryMap[0])); + + IntRegisters.Flags &= ~TC_X86_CARRY_FLAG; + IntRegisters.EAX = 0x534D4150UL; + + ++IntRegisters.EBX; + if (IntRegisters.EBX >= BiosMemoryMapSize) + IntRegisters.EBX = 0; + + IntRegisters.ECX = sizeof (BiosMemoryMap[0]); + } + + if (IntRegisters.EBX == 0 && !(BootSectorFlags & TC_BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER)) + { + // Uninstall filter when the modified map has been issued three times to prevent + // problems with hardware drivers on some notebooks running Windows XP. + + static int CompleteMapIssueCount = 0; + if (++CompleteMapIssueCount >= 3) + { + __asm + { + cli + push es + + lea si, OriginalInt15Handler + xor ax, ax + mov es, ax + mov di, 0x15 * 4 + + mov ax, [si] + mov es:[di], ax + mov ax, [si + 2] + mov es:[di + 2], ax + + pop es + sti + } + } + } + +#ifdef TC_TRACE_INT15 + BiosMemoryMapEntry entry; + CopyMemory (IntRegisters.ES, IntRegisters.DI, (byte *) &entry, sizeof (entry)); + PrintHex (entry.Type); PrintChar (' '); + PrintHex (entry.BaseAddress); PrintChar (' '); + PrintHex (entry.Length); PrintChar (' '); + PrintHex (entry.BaseAddress + entry.Length); PrintEndl(); + + Print ("EAX:"); PrintHex (IntRegisters.EAX); + Print (" EBX:"); PrintHex (IntRegisters.EBX); + Print (" ECX:"); PrintHex (IntRegisters.ECX); + Print (" EDX:"); PrintHex (IntRegisters.EDX); + Print (" DI:"); PrintHex (IntRegisters.DI); + Print (" FL:"); PrintHex (IntRegisters.Flags); + PrintEndl (2); +#endif + +#ifdef TC_TRACE_INT15 + EnableScreenOutput(); +#endif + return false; +} + + +void IntFilterEntry () +{ + // No automatic variables should be used in this scope as SS may change + static uint16 OrigStackPointer; + static uint16 OrigStackSegment; + + __asm + { + pushf + pushad + + cli + mov cs:IntRegisters.DI, di + + lea di, cs:IntRegisters.EAX + TC_ASM_EMIT4 (66,2E,89,05) // mov [cs:di], eax + lea di, cs:IntRegisters.EBX + TC_ASM_EMIT4 (66,2E,89,1D) // mov [cs:di], ebx + lea di, cs:IntRegisters.ECX + TC_ASM_EMIT4 (66,2E,89,0D) // mov [cs:di], ecx + lea di, cs:IntRegisters.EDX + TC_ASM_EMIT4 (66,2E,89,15) // mov [cs:di], edx + + mov ax, [bp + 8] + mov cs:IntRegisters.Flags, ax + + mov cs:IntRegisters.SI, si + mov si, [bp + 2] // Int number + + mov cs:IntRegisters.DS, ds + mov cs:IntRegisters.ES, es + mov cs:IntRegisters.SS, ss + + // Compiler assumes SS == DS - use our stack if this condition is not met + mov ax, ss + mov bx, cs + cmp ax, bx + jz stack_ok + + mov cs:OrigStackPointer, sp + mov cs:OrigStackSegment, ss + mov ax, cs + mov ss, ax + mov sp, TC_BOOT_LOADER_STACK_TOP + + stack_ok: + // DS = CS + push ds + push es + mov ax, cs + mov ds, ax + mov es, ax + + push si // Int number + + // Filter request + cmp si, 0x15 + je filter15 + cmp si, 0x13 + jne $ + + call Int13Filter + jmp s0 + + filter15: + call Int15Filter + + s0: + pop si // Int number + pop es + pop ds + + // Restore original SS:SP if our stack is empty + cli + mov bx, TC_BOOT_LOADER_STACK_TOP + cmp bx, sp + jnz stack_in_use + + mov ss, cs:OrigStackSegment + mov sp, cs:OrigStackPointer + stack_in_use: + + test ax, ax // passOriginalRequest + jnz pass_request + + // Return results of filtered request + popad + popf + mov ax, cs:IntRegisters.Flags + mov [bp + 8], ax + leave + + lea di, cs:IntRegisters.EAX + TC_ASM_EMIT4 (66,2E,8B,05) // mov eax, [cs:di] + lea di, cs:IntRegisters.EBX + TC_ASM_EMIT4 (66,2E,8B,1D) // mov ebx, [cs:di] + lea di, cs:IntRegisters.ECX + TC_ASM_EMIT4 (66,2E,8B,0D) // mov ecx, [cs:di] + lea di, cs:IntRegisters.EDX + TC_ASM_EMIT4 (66,2E,8B,15) // mov edx, [cs:di] + + mov di, cs:IntRegisters.DI + mov si, cs:IntRegisters.SI + mov es, cs:IntRegisters.ES + mov ds, cs:IntRegisters.DS + + sti + add sp, 2 + iret + + // Pass original request + pass_request: + sti + cmp si, 0x15 + je pass15 + cmp si, 0x13 + jne $ + + popad + popf + leave + add sp, 2 + jmp cs:OriginalInt13Handler + + pass15: + popad + popf + leave + add sp, 2 + jmp cs:OriginalInt15Handler + } +} + + +void Int13FilterEntry () +{ + __asm + { + leave + push 0x13 + jmp IntFilterEntry + } +} + + +static void Int15FilterEntry () +{ + __asm + { + pushf + cmp ax, 0xe820 // Get system memory map + je filter + + popf + leave + jmp cs:OriginalInt15Handler + + filter: + leave + push 0x15 + jmp IntFilterEntry + } +} + + +bool InstallInterruptFilters () +{ + +#ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE + + // If the filters have already been installed, it usually indicates stack corruption + // and a consequent reentry of this routine without a system reset. + + uint32 currentInt13Handler; + CopyMemory (0, 0x13 * 4, ¤tInt13Handler, sizeof (currentInt13Handler)); + + if (currentInt13Handler == (uint32) Int13FilterEntry) + { + PrintError ("Memory corrupted"); + Print (TC_BOOT_STR_UPGRADE_BIOS); + + GetKeyboardChar(); + return true; + } + +#endif + + if (!CreateNewBiosMemoryMap()) + return false; + + __asm + { + cli + push es + + // Save original INT 13 handler + xor ax, ax + mov es, ax + + mov si, 0x13 * 4 + lea di, OriginalInt13Handler + + mov ax, es:[si] + mov [di], ax + mov ax, es:[si + 2] + mov [di + 2], ax + + // Install INT 13 filter + lea ax, Int13FilterEntry + mov es:[si], ax + mov es:[si + 2], cs + + // Save original INT 15 handler + mov si, 0x15 * 4 + lea di, OriginalInt15Handler + + mov ax, es:[si] + mov [di], ax + mov ax, es:[si + 2] + mov [di + 2], ax + + // Install INT 15 filter + lea ax, Int15FilterEntry + mov es:[si], ax + mov es:[si + 2], cs + + // If the BIOS does not support system memory map (INT15 0xe820), + // set amount of available memory to CS:0000 - 0:0000 + cmp BiosMemoryMapSize, 1 + jg mem_map_ok + mov ax, cs + shr ax, 10 - 4 // CS * 16 / 1024 + mov es:[0x413], ax // = KBytes available + mem_map_ok: + + pop es + sti + } + + return true; +} diff --git a/src/Boot/Windows/IntFilter.h b/src/Boot/Windows/IntFilter.h index af354802..1ef42512 100644 --- a/src/Boot/Windows/IntFilter.h +++ b/src/Boot/Windows/IntFilter.h @@ -1,20 +1,20 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Boot_IntFilter -#define TC_HEADER_Boot_IntFilter - -#include "Platform.h" - -bool InstallInterruptFilters (); - -#endif TC_HEADER_Boot_IntFilter +/* + 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. +*/ + +#ifndef TC_HEADER_Boot_IntFilter +#define TC_HEADER_Boot_IntFilter + +#include "Platform.h" + +bool InstallInterruptFilters (); + +#endif TC_HEADER_Boot_IntFilter diff --git a/src/Boot/Windows/Makefile b/src/Boot/Windows/Makefile index f9851051..65e668cb 100644 --- a/src/Boot/Windows/Makefile +++ b/src/Boot/Windows/Makefile @@ -1,202 +1,202 @@ -# -# 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. - -PROJ = BootLoader -.SILENT: - -!ifndef MSVC16_ROOT -!error Environment variable MSVC16_ROOT must point to the installation directory of MS Visual C++ 1.5 -!endif - -ENVPATH = $(PATH) - -CC = $(MSVC16_ROOT)\bin\cl.exe -LD = $(MSVC16_ROOT)\bin\link.exe - -AFLAGS = /nologo /omf - -CFLAGS = /nologo /W3 /Fc /I "$(MSVC16_ROOT)\Include" /I"..\..\.." /I"..\..\..\Common" /I"..\..\..\Crypto" -CFLAGS = $(CFLAGS) /D __int8=char /D __int16=int /D __int32=long /D BOOL=char /D FALSE=0 /D TRUE=1 -CFLAGS = $(CFLAGS) /D LITTLE_ENDIAN=1234 /D BYTE_ORDER=1234 /D TC_WINDOWS_BOOT /D TC_MINIMIZE_CODE_SIZE /D TC_NO_COMPILER_INT64 -CFLAGS = $(CFLAGS) /D malloc=malloc_NA - -LFLAGS = /NOLOGO /ONERROR:NOEXE /NOI /BATCH - -OBJDIR = Release - -!ifdef RESCUE_DISK -OBJDIR = Rescue -CFLAGS = $(CFLAGS) /D TC_WINDOWS_BOOT_RESCUE_DISK_MODE -!endif - -!ifdef SINGLE_CIPHER -OBJDIR = $(OBJDIR)_$(SINGLE_CIPHER) -CFLAGS = $(CFLAGS) /D TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE /D TC_WINDOWS_BOOT_$(SINGLE_CIPHER) -!endif - -!ifdef SINGLE_PRF -OBJDIR = $(OBJDIR)_$(SINGLE_PRF) -CFLAGS = $(CFLAGS) /D TC_WINDOWS_BOOT_$(SINGLE_PRF) -!else -CFLAGS = $(CFLAGS) /D TC_WINDOWS_BOOT_RIPEMD160 -!endif - -OUTDIR = $(OBJDIR) -TARGETEXT = com -TARGETS = $(OUTDIR)\BootDefs.i $(OUTDIR)\BootSector.bin $(OUTDIR)\Decompressor.com -CFLAGS = $(CFLAGS) /AT /Zl /f- /G3 /Oe /Os /Ob1 /OV0 /Gs /Gf /Gy /D NDEBUG -LFLAGS = $(LFLAGS) /NOD /NOE /TINY -OBJS = $(OUTDIR)\BootCrt.obj -LIBS = slibce - -!if 1 -SRCDIR = .. -!else -SRCDIR = $(MAKEDIR) -!endif - -TARGETS = $(TARGETS) $(OUTDIR)\$(PROJ).$(TARGETEXT) - -OBJS = $(OBJS) $(OUTDIR)\BootConfig.obj -OBJS = $(OBJS) $(OUTDIR)\BootConsoleIo.obj -OBJS = $(OBJS) $(OUTDIR)\BootDebug.obj -OBJS = $(OBJS) $(OUTDIR)\BootDiskIo.obj -OBJS = $(OBJS) $(OUTDIR)\BootEncryptedIo.obj -OBJS = $(OBJS) $(OUTDIR)\BootMain.obj -OBJS = $(OBJS) $(OUTDIR)\BootMemory.obj -OBJS = $(OBJS) $(OUTDIR)\IntFilter.obj -OBJS = $(OBJS) $(OUTDIR)\Platform.obj - -OBJS = $(OBJS) $(OUTDIR)\Crc.obj -OBJS = $(OBJS) $(OUTDIR)\Crypto.obj -OBJS = $(OBJS) $(OUTDIR)\Endian.obj -OBJS = $(OBJS) $(OUTDIR)\Pkcs5.obj -OBJS = $(OBJS) $(OUTDIR)\Volumes.obj -OBJS = $(OBJS) $(OUTDIR)\Xts.obj - -!if "$(SINGLE_PRF)" == "SHA2" -OBJS = $(OBJS) $(OUTDIR)\Sha2Small.obj -!else -OBJS = $(OBJS) $(OUTDIR)\Rmd160.obj -!endif - -!if !DEFINED (SINGLE_CIPHER) -OBJS = $(OBJS) $(OUTDIR)\AesSmall.obj -!else if "$(SINGLE_CIPHER)" == "AES" -OBJS = $(OBJS) $(OUTDIR)\Aes_hw_cpu.obj -OBJS = $(OBJS) $(OUTDIR)\AesSmall_x86.obj -OBJS = $(OBJS) $(OUTDIR)\Aestab.obj -!endif - -!if !DEFINED (SINGLE_CIPHER) || "$(SINGLE_CIPHER)" == "SERPENT" -OBJS = $(OBJS) $(OUTDIR)\Serpent.obj -!endif - -!if !DEFINED (SINGLE_CIPHER) || "$(SINGLE_CIPHER)" == "TWOFISH" -OBJS = $(OBJS) $(OUTDIR)\Twofish.obj -!endif - - -all: env $(TARGETS) - -env: - set INCLUDE=. - set LIB=. - set LIBPATH=. - -clean: - -del /q /s $(OBJDIR) >NUL: - - -.asm{$(OUTDIR)}.obj: - cd $(OBJDIR) - $(AS) $(AFLAGS) /c "$(SRCDIR)\$<" - cd .. - -{..\..\Crypto}.asm{$(OUTDIR)}.obj: - cd $(OBJDIR) - echo $(NUL: - -dd.exe conv=notrunc bs=512 if=BootSector.bin of=$(PROJ).flp 2>NUL: - cd .. - -$(OUTDIR)\Decompressor.com: $(OUTDIR)\BootCrt.obj $(OUTDIR)\Decompressor.obj - cd $(OBJDIR) - $(LD) $(LFLAGS) BootCrt.obj Decompressor.obj,Decompressor.com,Decompressor.map,$(MSVC16_ROOT)\lib\+slibce,, - -dd.exe conv=notrunc,sync bs=512 seek=1 if=Decompressor.com of=$(PROJ).flp 2>NUL: - cd .. - -$(OUTDIR)\$(PROJ).$(TARGETEXT): $(OBJS) - @echo Linking... - cd $(OBJDIR) - - echo >NUL: @<<$(PROJ).crf2 - -$(PROJ).$(TARGETEXT) -$(PROJ).map -$(MSVC16_ROOT)\lib\+ -$(LIBS) -; -<< - del $(PROJ).crf >NUL: 2>NUL: - for %F in ($(**F)) do @echo %F + >>$(PROJ).crf - type $(PROJ).crf2 >>$(PROJ).crf - - $(LD) $(LFLAGS) @$(PROJ).crf - del $(PROJ).crf $(PROJ).crf2 - -# Compress the Rescue Disk botloader for Cascades and Serpent since it is too big (size > 31232 bytes) -!if DEFINED(RESCUE_DISK) && (!DEFINED (SINGLE_CIPHER) || ("$(SINGLE_CIPHER)" == "SERPENT")) - upx $(PROJ).$(TARGETEXT) -!endif - gzip.exe -c -n --best $(PROJ).$(TARGETEXT) >$(PROJ).$(TARGETEXT).gz - -dd.exe conv=notrunc,sync bs=512 seek=5 if=$(PROJ).$(TARGETEXT).gz of=$(PROJ).flp 2>NUL: - cd .. +# +# 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. + +PROJ = BootLoader +.SILENT: + +!ifndef MSVC16_ROOT +!error Environment variable MSVC16_ROOT must point to the installation directory of MS Visual C++ 1.5 +!endif + +ENVPATH = $(PATH) + +CC = $(MSVC16_ROOT)\bin\cl.exe +LD = $(MSVC16_ROOT)\bin\link.exe + +AFLAGS = /nologo /omf + +CFLAGS = /nologo /W3 /Fc /I "$(MSVC16_ROOT)\Include" /I"..\..\.." /I"..\..\..\Common" /I"..\..\..\Crypto" +CFLAGS = $(CFLAGS) /D __int8=char /D __int16=int /D __int32=long /D BOOL=char /D FALSE=0 /D TRUE=1 +CFLAGS = $(CFLAGS) /D LITTLE_ENDIAN=1234 /D BYTE_ORDER=1234 /D TC_WINDOWS_BOOT /D TC_MINIMIZE_CODE_SIZE /D TC_NO_COMPILER_INT64 +CFLAGS = $(CFLAGS) /D malloc=malloc_NA + +LFLAGS = /NOLOGO /ONERROR:NOEXE /NOI /BATCH + +OBJDIR = Release + +!ifdef RESCUE_DISK +OBJDIR = Rescue +CFLAGS = $(CFLAGS) /D TC_WINDOWS_BOOT_RESCUE_DISK_MODE +!endif + +!ifdef SINGLE_CIPHER +OBJDIR = $(OBJDIR)_$(SINGLE_CIPHER) +CFLAGS = $(CFLAGS) /D TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE /D TC_WINDOWS_BOOT_$(SINGLE_CIPHER) +!endif + +!ifdef SINGLE_PRF +OBJDIR = $(OBJDIR)_$(SINGLE_PRF) +CFLAGS = $(CFLAGS) /D TC_WINDOWS_BOOT_$(SINGLE_PRF) +!else +CFLAGS = $(CFLAGS) /D TC_WINDOWS_BOOT_RIPEMD160 +!endif + +OUTDIR = $(OBJDIR) +TARGETEXT = com +TARGETS = $(OUTDIR)\BootDefs.i $(OUTDIR)\BootSector.bin $(OUTDIR)\Decompressor.com +CFLAGS = $(CFLAGS) /AT /Zl /f- /G3 /Oe /Os /Ob1 /OV0 /Gs /Gf /Gy /D NDEBUG +LFLAGS = $(LFLAGS) /NOD /NOE /TINY +OBJS = $(OUTDIR)\BootCrt.obj +LIBS = slibce + +!if 1 +SRCDIR = .. +!else +SRCDIR = $(MAKEDIR) +!endif + +TARGETS = $(TARGETS) $(OUTDIR)\$(PROJ).$(TARGETEXT) + +OBJS = $(OBJS) $(OUTDIR)\BootConfig.obj +OBJS = $(OBJS) $(OUTDIR)\BootConsoleIo.obj +OBJS = $(OBJS) $(OUTDIR)\BootDebug.obj +OBJS = $(OBJS) $(OUTDIR)\BootDiskIo.obj +OBJS = $(OBJS) $(OUTDIR)\BootEncryptedIo.obj +OBJS = $(OBJS) $(OUTDIR)\BootMain.obj +OBJS = $(OBJS) $(OUTDIR)\BootMemory.obj +OBJS = $(OBJS) $(OUTDIR)\IntFilter.obj +OBJS = $(OBJS) $(OUTDIR)\Platform.obj + +OBJS = $(OBJS) $(OUTDIR)\Crc.obj +OBJS = $(OBJS) $(OUTDIR)\Crypto.obj +OBJS = $(OBJS) $(OUTDIR)\Endian.obj +OBJS = $(OBJS) $(OUTDIR)\Pkcs5.obj +OBJS = $(OBJS) $(OUTDIR)\Volumes.obj +OBJS = $(OBJS) $(OUTDIR)\Xts.obj + +!if "$(SINGLE_PRF)" == "SHA2" +OBJS = $(OBJS) $(OUTDIR)\Sha2Small.obj +!else +OBJS = $(OBJS) $(OUTDIR)\Rmd160.obj +!endif + +!if !DEFINED (SINGLE_CIPHER) +OBJS = $(OBJS) $(OUTDIR)\AesSmall.obj +!else if "$(SINGLE_CIPHER)" == "AES" +OBJS = $(OBJS) $(OUTDIR)\Aes_hw_cpu.obj +OBJS = $(OBJS) $(OUTDIR)\AesSmall_x86.obj +OBJS = $(OBJS) $(OUTDIR)\Aestab.obj +!endif + +!if !DEFINED (SINGLE_CIPHER) || "$(SINGLE_CIPHER)" == "SERPENT" +OBJS = $(OBJS) $(OUTDIR)\Serpent.obj +!endif + +!if !DEFINED (SINGLE_CIPHER) || "$(SINGLE_CIPHER)" == "TWOFISH" +OBJS = $(OBJS) $(OUTDIR)\Twofish.obj +!endif + + +all: env $(TARGETS) + +env: + set INCLUDE=. + set LIB=. + set LIBPATH=. + +clean: + -del /q /s $(OBJDIR) >NUL: + + +.asm{$(OUTDIR)}.obj: + cd $(OBJDIR) + $(AS) $(AFLAGS) /c "$(SRCDIR)\$<" + cd .. + +{..\..\Crypto}.asm{$(OUTDIR)}.obj: + cd $(OBJDIR) + echo $(NUL: + -dd.exe conv=notrunc bs=512 if=BootSector.bin of=$(PROJ).flp 2>NUL: + cd .. + +$(OUTDIR)\Decompressor.com: $(OUTDIR)\BootCrt.obj $(OUTDIR)\Decompressor.obj + cd $(OBJDIR) + $(LD) $(LFLAGS) BootCrt.obj Decompressor.obj,Decompressor.com,Decompressor.map,$(MSVC16_ROOT)\lib\+slibce,, + -dd.exe conv=notrunc,sync bs=512 seek=1 if=Decompressor.com of=$(PROJ).flp 2>NUL: + cd .. + +$(OUTDIR)\$(PROJ).$(TARGETEXT): $(OBJS) + @echo Linking... + cd $(OBJDIR) + + echo >NUL: @<<$(PROJ).crf2 + +$(PROJ).$(TARGETEXT) +$(PROJ).map +$(MSVC16_ROOT)\lib\+ +$(LIBS) +; +<< + del $(PROJ).crf >NUL: 2>NUL: + for %F in ($(**F)) do @echo %F + >>$(PROJ).crf + type $(PROJ).crf2 >>$(PROJ).crf + + $(LD) $(LFLAGS) @$(PROJ).crf + del $(PROJ).crf $(PROJ).crf2 + +# Compress the Rescue Disk botloader for Cascades and Serpent since it is too big (size > 31232 bytes) +!if DEFINED(RESCUE_DISK) && (!DEFINED (SINGLE_CIPHER) || ("$(SINGLE_CIPHER)" == "SERPENT")) + upx $(PROJ).$(TARGETEXT) +!endif + gzip.exe -c -n --best $(PROJ).$(TARGETEXT) >$(PROJ).$(TARGETEXT).gz + -dd.exe conv=notrunc,sync bs=512 seek=5 if=$(PROJ).$(TARGETEXT).gz of=$(PROJ).flp 2>NUL: + cd .. diff --git a/src/Boot/Windows/Platform.cpp b/src/Boot/Windows/Platform.cpp index d9819cfa..316e71b3 100644 --- a/src/Boot/Windows/Platform.cpp +++ b/src/Boot/Windows/Platform.cpp @@ -1,230 +1,230 @@ -/* - 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 "Platform.h" -#include "BootConsoleIo.h" - - -uint64 operator+ (const uint64 &a, const uint64 &b) -{ - int carry = 0; - uint64 r; - - r.LowPart = a.LowPart + b.LowPart; - __asm - { - jnc nocarry - mov carry, 1 - nocarry: - } - - r.HighPart = a.HighPart + b.HighPart + carry; - - return r; -} - -uint64 operator+ (const uint64 &a, uint32 b) -{ - uint64 b64; - b64.HighPart = 0; - b64.LowPart = b; - return a + b64; -} - -uint64 &operator+= (uint64 &a, const uint64 &b) -{ - return a = a + b; -} - -uint64 operator- (const uint64 &a, const uint64 &b) -{ - int carry = 0; - uint64 r; - - r.LowPart = a.LowPart - b.LowPart; - __asm - { - jnc nocarry - mov carry, 1 - nocarry: - } - - r.HighPart = a.HighPart - b.HighPart - carry; - - return r; -} - -uint64 operator- (const uint64 &a, uint32 b) -{ - uint64 b64; - b64.HighPart = 0; - b64.LowPart = b; - return a - b64; -} - -uint64 &operator-= (uint64 &a, const uint64 &b) -{ - return a = a - b; -} - -uint64 operator>> (const uint64 &a, int shiftCount) -{ - uint64 r = a; - - while (shiftCount--) - { - r.LowPart >>= 1; - - if ((byte) r.HighPart & 1) - r.LowPart |= 0x80000000UL; - - r.HighPart >>= 1; - } - - return r; -} - -uint64 operator<< (const uint64 &a, int shiftCount) -{ - uint64 r = a; - - while (shiftCount--) - r += r; - - return r; -} - -uint64 &operator++ (uint64 &a) -{ - uint64 b; - b.HighPart = 0; - b.LowPart = 1; - - return a += b; -} - -bool operator== (const uint64 &a, const uint64 &b) -{ - return a.HighPart == b.HighPart && a.LowPart == b.LowPart; -} - -bool operator> (const uint64 &a, const uint64 &b) -{ - return (a.HighPart > b.HighPart) || (a.HighPart == b.HighPart && a.LowPart > b.LowPart); -} - -bool operator< (const uint64 &a, const uint64 &b) -{ - return (a.HighPart < b.HighPart) || (a.HighPart == b.HighPart && a.LowPart < b.LowPart); -} - -bool operator>= (const uint64 &a, const uint64 &b) -{ - return a > b || a == b; -} - -bool operator<= (const uint64 &a, const uint64 &b) -{ - return a < b || a == b; -} - -bool TestInt64 () -{ - uint64 a, b, c; - a.HighPart = 0x00112233UL; - a.LowPart = 0xabcd1234UL; - - b.HighPart = 0x00ffeeddUL; - b.LowPart = 0xffffFFFFUL; - - a += b; - a -= b; - - ++a; - - b = b + (uint32) 1UL; - - c = (a - ((a + b) >> 32) - (uint32) 1UL); - if (c.HighPart != 0x112233UL || c.LowPart != 0xAABC0123UL) - return false; - - c = c << 9; - return c.HighPart == 0x22446755UL && c.LowPart == 0x78024600UL; -} - - -void CopyMemory (void *source, uint16 destSegment, uint16 destOffset, uint16 blockSize) -{ - __asm - { - push es - mov si, ss:source - mov es, ss:destSegment - mov di, ss:destOffset - mov cx, ss:blockSize - cld - rep movsb - pop es - } -} - - -void CopyMemory (uint16 sourceSegment, uint16 sourceOffset, void *destination, uint16 blockSize) -{ - __asm - { - push ds - push es - mov ax, ds - mov es, ax - mov di, ss:destination - mov si, ss:sourceOffset - mov cx, ss:blockSize - mov ds, ss:sourceSegment - cld - rep movsb - pop es - pop ds - } -} - - -void EraseMemory (void *memory, int size) -{ - memset (memory, 0, size); -} - - -uint32 GetLinearAddress (uint16 segment, uint16 offset) -{ - return (uint32 (segment) << 4) + offset; -} - - -bool RegionsIntersect (const uint64 &start1, uint32 length1, const uint64 &start2, const uint64 &end2) -{ - uint64 end1 = start1 + length1 - 1UL; - uint64 intersectEnd = (end1 <= end2) ? end1 : end2; - - uint64 intersectStart = (start1 >= start2) ? start1 : start2; - if (intersectStart > intersectEnd) - return false; - - return (intersectEnd + 1UL - intersectStart).LowPart != 0; -} - - -void ThrowFatalException (int line) -{ - PrintChar ('#'); Print (line); - while (1); -} +/* + 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 "Platform.h" +#include "BootConsoleIo.h" + + +uint64 operator+ (const uint64 &a, const uint64 &b) +{ + int carry = 0; + uint64 r; + + r.LowPart = a.LowPart + b.LowPart; + __asm + { + jnc nocarry + mov carry, 1 + nocarry: + } + + r.HighPart = a.HighPart + b.HighPart + carry; + + return r; +} + +uint64 operator+ (const uint64 &a, uint32 b) +{ + uint64 b64; + b64.HighPart = 0; + b64.LowPart = b; + return a + b64; +} + +uint64 &operator+= (uint64 &a, const uint64 &b) +{ + return a = a + b; +} + +uint64 operator- (const uint64 &a, const uint64 &b) +{ + int carry = 0; + uint64 r; + + r.LowPart = a.LowPart - b.LowPart; + __asm + { + jnc nocarry + mov carry, 1 + nocarry: + } + + r.HighPart = a.HighPart - b.HighPart - carry; + + return r; +} + +uint64 operator- (const uint64 &a, uint32 b) +{ + uint64 b64; + b64.HighPart = 0; + b64.LowPart = b; + return a - b64; +} + +uint64 &operator-= (uint64 &a, const uint64 &b) +{ + return a = a - b; +} + +uint64 operator>> (const uint64 &a, int shiftCount) +{ + uint64 r = a; + + while (shiftCount--) + { + r.LowPart >>= 1; + + if ((byte) r.HighPart & 1) + r.LowPart |= 0x80000000UL; + + r.HighPart >>= 1; + } + + return r; +} + +uint64 operator<< (const uint64 &a, int shiftCount) +{ + uint64 r = a; + + while (shiftCount--) + r += r; + + return r; +} + +uint64 &operator++ (uint64 &a) +{ + uint64 b; + b.HighPart = 0; + b.LowPart = 1; + + return a += b; +} + +bool operator== (const uint64 &a, const uint64 &b) +{ + return a.HighPart == b.HighPart && a.LowPart == b.LowPart; +} + +bool operator> (const uint64 &a, const uint64 &b) +{ + return (a.HighPart > b.HighPart) || (a.HighPart == b.HighPart && a.LowPart > b.LowPart); +} + +bool operator< (const uint64 &a, const uint64 &b) +{ + return (a.HighPart < b.HighPart) || (a.HighPart == b.HighPart && a.LowPart < b.LowPart); +} + +bool operator>= (const uint64 &a, const uint64 &b) +{ + return a > b || a == b; +} + +bool operator<= (const uint64 &a, const uint64 &b) +{ + return a < b || a == b; +} + +bool TestInt64 () +{ + uint64 a, b, c; + a.HighPart = 0x00112233UL; + a.LowPart = 0xabcd1234UL; + + b.HighPart = 0x00ffeeddUL; + b.LowPart = 0xffffFFFFUL; + + a += b; + a -= b; + + ++a; + + b = b + (uint32) 1UL; + + c = (a - ((a + b) >> 32) - (uint32) 1UL); + if (c.HighPart != 0x112233UL || c.LowPart != 0xAABC0123UL) + return false; + + c = c << 9; + return c.HighPart == 0x22446755UL && c.LowPart == 0x78024600UL; +} + + +void CopyMemory (void *source, uint16 destSegment, uint16 destOffset, uint16 blockSize) +{ + __asm + { + push es + mov si, ss:source + mov es, ss:destSegment + mov di, ss:destOffset + mov cx, ss:blockSize + cld + rep movsb + pop es + } +} + + +void CopyMemory (uint16 sourceSegment, uint16 sourceOffset, void *destination, uint16 blockSize) +{ + __asm + { + push ds + push es + mov ax, ds + mov es, ax + mov di, ss:destination + mov si, ss:sourceOffset + mov cx, ss:blockSize + mov ds, ss:sourceSegment + cld + rep movsb + pop es + pop ds + } +} + + +void EraseMemory (void *memory, int size) +{ + memset (memory, 0, size); +} + + +uint32 GetLinearAddress (uint16 segment, uint16 offset) +{ + return (uint32 (segment) << 4) + offset; +} + + +bool RegionsIntersect (const uint64 &start1, uint32 length1, const uint64 &start2, const uint64 &end2) +{ + uint64 end1 = start1 + length1 - 1UL; + uint64 intersectEnd = (end1 <= end2) ? end1 : end2; + + uint64 intersectStart = (start1 >= start2) ? start1 : start2; + if (intersectStart > intersectEnd) + return false; + + return (intersectEnd + 1UL - intersectStart).LowPart != 0; +} + + +void ThrowFatalException (int line) +{ + PrintChar ('#'); Print (line); + while (1); +} diff --git a/src/Boot/Windows/Platform.h b/src/Boot/Windows/Platform.h index 2fa532ce..879b1c39 100644 --- a/src/Boot/Windows/Platform.h +++ b/src/Boot/Windows/Platform.h @@ -1,116 +1,116 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Boot_Platform -#define TC_HEADER_Boot_Platform - -#pragma warning (disable: 4018 4102 4704 4769) - -#include "TCdefs.h" -#include - -typedef char bool; -#define false 0 -#define true 1 - -#define nullptr 0 -#define NULL 0 - -typedef UINT64_STRUCT uint64; - -#define array_capacity(arr) (sizeof (arr) / sizeof ((arr)[0])) - -#define TC_TO_STRING2(n) #n -#define TC_TO_STRING(n) TC_TO_STRING2(n) - - -#define TC_X86_CARRY_FLAG 0x1 - -#define TC_ASM_EMIT(A,B) __asm _emit 0x##A __asm _emit 0x##B -#define TC_ASM_EMIT3(A,B,C) __asm _emit 0x##A __asm _emit 0x##B __asm _emit 0x##C -#define TC_ASM_EMIT4(A,B,C,D) __asm _emit 0x##A __asm _emit 0x##B __asm _emit 0x##C __asm _emit 0x##D - -#define TC_ASM_MOV_EAX_DI TC_ASM_EMIT3 (66, 8B, 05) -#define TC_ASM_MOV_EBX_DI TC_ASM_EMIT3 (66, 8B, 1D) -#define TC_ASM_MOV_ECX_DI TC_ASM_EMIT3 (66, 8B, 0D) -#define TC_ASM_MOV_EDX_DI TC_ASM_EMIT3 (66, 8B, 15) - -#define TC_ASM_MOV_DI_EAX TC_ASM_EMIT3 (66, 89, 05) -#define TC_ASM_MOV_DI_EBX TC_ASM_EMIT3 (66, 89, 1D) -#define TC_ASM_MOV_DI_ECX TC_ASM_EMIT3 (66, 89, 0D) -#define TC_ASM_MOV_DI_EDX TC_ASM_EMIT3 (66, 89, 15) - - -#pragma pack(1) - -struct Registers -{ - uint16 Flags; - - union - { - uint32 EAX; - struct { uint16 AX; uint16 EAXH; }; - }; - - union - { - uint32 EBX; - struct { uint16 BX; uint16 EBXH; }; - }; - - union - { - uint32 ECX; - struct { uint16 CX; uint16 ECXH; }; - }; - - union - { - uint32 EDX; - struct { uint16 DX; uint16 EDXH; }; - }; - - uint16 DI; - uint16 SI; - uint16 DS; - uint16 ES; - uint16 SS; -}; - -#pragma pack() - - -uint64 operator+ (const uint64 &a, const uint64 &b); -uint64 operator+ (const uint64 &a, uint32 b); -uint64 &operator+= (uint64 &a, const uint64 &b); -uint64 operator- (const uint64 &a, const uint64 &b); -uint64 operator- (const uint64 &a, uint32 b); -uint64 &operator-= (uint64 &a, const uint64 &b); -uint64 operator>> (const uint64 &a, int shiftCount); -uint64 operator<< (const uint64 &a, int shiftCount); -uint64 &operator++ (uint64 &a); -bool operator== (const uint64 &a, const uint64 &b); -bool operator> (const uint64 &a, const uint64 &b); -bool operator< (const uint64 &a, const uint64 &b); -bool operator>= (const uint64 &a, const uint64 &b); -bool operator<= (const uint64 &a, const uint64 &b); - -void CopyMemory (void *source, uint16 destSegment, uint16 destOffset, uint16 blockSize); -void CopyMemory (uint16 sourceSegment, uint16 sourceOffset, void *destination, uint16 blockSize); -extern "C" void EraseMemory (void *memory, int size); -uint32 GetLinearAddress (uint16 segment, uint16 offset); -bool RegionsIntersect (const uint64 &start1, uint32 length1, const uint64 &start2, const uint64 &end2); -bool TestInt64 (); -extern "C" void ThrowFatalException (int line); - -#endif // TC_HEADER_Boot_Platform +/* + 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. +*/ + +#ifndef TC_HEADER_Boot_Platform +#define TC_HEADER_Boot_Platform + +#pragma warning (disable: 4018 4102 4704 4769) + +#include "TCdefs.h" +#include + +typedef char bool; +#define false 0 +#define true 1 + +#define nullptr 0 +#define NULL 0 + +typedef UINT64_STRUCT uint64; + +#define array_capacity(arr) (sizeof (arr) / sizeof ((arr)[0])) + +#define TC_TO_STRING2(n) #n +#define TC_TO_STRING(n) TC_TO_STRING2(n) + + +#define TC_X86_CARRY_FLAG 0x1 + +#define TC_ASM_EMIT(A,B) __asm _emit 0x##A __asm _emit 0x##B +#define TC_ASM_EMIT3(A,B,C) __asm _emit 0x##A __asm _emit 0x##B __asm _emit 0x##C +#define TC_ASM_EMIT4(A,B,C,D) __asm _emit 0x##A __asm _emit 0x##B __asm _emit 0x##C __asm _emit 0x##D + +#define TC_ASM_MOV_EAX_DI TC_ASM_EMIT3 (66, 8B, 05) +#define TC_ASM_MOV_EBX_DI TC_ASM_EMIT3 (66, 8B, 1D) +#define TC_ASM_MOV_ECX_DI TC_ASM_EMIT3 (66, 8B, 0D) +#define TC_ASM_MOV_EDX_DI TC_ASM_EMIT3 (66, 8B, 15) + +#define TC_ASM_MOV_DI_EAX TC_ASM_EMIT3 (66, 89, 05) +#define TC_ASM_MOV_DI_EBX TC_ASM_EMIT3 (66, 89, 1D) +#define TC_ASM_MOV_DI_ECX TC_ASM_EMIT3 (66, 89, 0D) +#define TC_ASM_MOV_DI_EDX TC_ASM_EMIT3 (66, 89, 15) + + +#pragma pack(1) + +struct Registers +{ + uint16 Flags; + + union + { + uint32 EAX; + struct { uint16 AX; uint16 EAXH; }; + }; + + union + { + uint32 EBX; + struct { uint16 BX; uint16 EBXH; }; + }; + + union + { + uint32 ECX; + struct { uint16 CX; uint16 ECXH; }; + }; + + union + { + uint32 EDX; + struct { uint16 DX; uint16 EDXH; }; + }; + + uint16 DI; + uint16 SI; + uint16 DS; + uint16 ES; + uint16 SS; +}; + +#pragma pack() + + +uint64 operator+ (const uint64 &a, const uint64 &b); +uint64 operator+ (const uint64 &a, uint32 b); +uint64 &operator+= (uint64 &a, const uint64 &b); +uint64 operator- (const uint64 &a, const uint64 &b); +uint64 operator- (const uint64 &a, uint32 b); +uint64 &operator-= (uint64 &a, const uint64 &b); +uint64 operator>> (const uint64 &a, int shiftCount); +uint64 operator<< (const uint64 &a, int shiftCount); +uint64 &operator++ (uint64 &a); +bool operator== (const uint64 &a, const uint64 &b); +bool operator> (const uint64 &a, const uint64 &b); +bool operator< (const uint64 &a, const uint64 &b); +bool operator>= (const uint64 &a, const uint64 &b); +bool operator<= (const uint64 &a, const uint64 &b); + +void CopyMemory (void *source, uint16 destSegment, uint16 destOffset, uint16 blockSize); +void CopyMemory (uint16 sourceSegment, uint16 sourceOffset, void *destination, uint16 blockSize); +extern "C" void EraseMemory (void *memory, int size); +uint32 GetLinearAddress (uint16 segment, uint16 offset); +bool RegionsIntersect (const uint64 &start1, uint32 length1, const uint64 &start2, const uint64 &end2); +bool TestInt64 (); +extern "C" void ThrowFatalException (int line); + +#endif // TC_HEADER_Boot_Platform diff --git a/src/Build/Tools/MacOSX/nasm b/src/Build/Tools/MacOSX/nasm index 7d2c38ac..62a6702a 100755 Binary files a/src/Build/Tools/MacOSX/nasm and b/src/Build/Tools/MacOSX/nasm differ diff --git a/src/Common/Apidrvr.h b/src/Common/Apidrvr.h index f584582e..5ea89770 100644 --- a/src/Common/Apidrvr.h +++ b/src/Common/Apidrvr.h @@ -1,344 +1,344 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#pragma once - -#include "Tcdefs.h" -#include "Boot/Windows/BootDefs.h" -#include "Common.h" -#include "Crypto.h" -#include "Volumes.h" -#include "Wipe.h" - -#ifdef _WIN32 - -/* WARNING: Modifying the following values or their meanings can introduce incompatibility with previous versions. */ - -#define TC_IOCTL(CODE) (CTL_CODE (FILE_DEVICE_UNKNOWN, 0x800 + (CODE), METHOD_BUFFERED, FILE_ANY_ACCESS)) - -#define TC_IOCTL_GET_DRIVER_VERSION TC_IOCTL (1) -#define TC_IOCTL_GET_BOOT_LOADER_VERSION TC_IOCTL (2) -#define TC_IOCTL_MOUNT_VOLUME TC_IOCTL (3) -#define TC_IOCTL_DISMOUNT_VOLUME TC_IOCTL (4) -#define TC_IOCTL_DISMOUNT_ALL_VOLUMES TC_IOCTL (5) -#define TC_IOCTL_GET_MOUNTED_VOLUMES TC_IOCTL (6) -#define TC_IOCTL_GET_VOLUME_PROPERTIES TC_IOCTL (7) -#define TC_IOCTL_GET_DEVICE_REFCOUNT TC_IOCTL (8) -#define TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED TC_IOCTL (9) -#define TC_IOCTL_IS_ANY_VOLUME_MOUNTED TC_IOCTL (10) -#define TC_IOCTL_GET_PASSWORD_CACHE_STATUS TC_IOCTL (11) -#define TC_IOCTL_WIPE_PASSWORD_CACHE TC_IOCTL (12) -#define TC_IOCTL_OPEN_TEST TC_IOCTL (13) -#define TC_IOCTL_GET_DRIVE_PARTITION_INFO TC_IOCTL (14) -#define TC_IOCTL_GET_DRIVE_GEOMETRY TC_IOCTL (15) -#define TC_IOCTL_PROBE_REAL_DRIVE_SIZE TC_IOCTL (16) -#define TC_IOCTL_GET_RESOLVED_SYMLINK TC_IOCTL (17) -#define TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS TC_IOCTL (18) -#define TC_IOCTL_BOOT_ENCRYPTION_SETUP TC_IOCTL (19) -#define TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP TC_IOCTL (20) -#define TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT TC_IOCTL (21) -#define TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES TC_IOCTL (22) -#define TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER TC_IOCTL (23) -#define TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME TC_IOCTL (24) -#define TC_IOCTL_GET_PORTABLE_MODE_STATUS TC_IOCTL (25) -#define TC_IOCTL_SET_PORTABLE_MODE_STATUS TC_IOCTL (26) -#define TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING TC_IOCTL (27) -#define TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG TC_IOCTL (28) -#define TC_IOCTL_DISK_IS_WRITABLE TC_IOCTL (29) -#define TC_IOCTL_START_DECOY_SYSTEM_WIPE TC_IOCTL (30) -#define TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE TC_IOCTL (31) -#define TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS TC_IOCTL (32) -#define TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT TC_IOCTL (33) -#define TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR TC_IOCTL (34) -#define TC_IOCTL_GET_WARNING_FLAGS TC_IOCTL (35) -#define TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY TC_IOCTL (36) -#define TC_IOCTL_REREAD_DRIVER_CONFIG TC_IOCTL (37) -#define TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG TC_IOCTL (38) -#define VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT TC_IOCTL (39) - -// Legacy IOCTLs used before version 5.0 -#define TC_IOCTL_LEGACY_GET_DRIVER_VERSION 466968 -#define TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES 466948 - - -/* Start of driver interface structures, the size of these structures may - change between versions; so make sure you first send DRIVER_VERSION to - check that it's the correct device driver */ - -#pragma pack (push) -#pragma pack(1) - -typedef struct -{ - int nReturnCode; /* Return code back from driver */ - BOOL FilesystemDirty; - BOOL VolumeMountedReadOnlyAfterAccessDenied; - BOOL VolumeMountedReadOnlyAfterDeviceWriteProtected; - - wchar_t wszVolume[TC_MAX_PATH]; /* Volume to be mounted */ - Password VolumePassword; /* User password */ - BOOL bCache; /* Cache passwords in driver */ - int nDosDriveNo; /* Drive number to mount */ - uint32 BytesPerSector; - BOOL bMountReadOnly; /* Mount volume in read-only mode */ - BOOL bMountRemovable; /* Mount volume as removable media */ - BOOL bExclusiveAccess; /* Open host file/device in exclusive access mode */ - BOOL bMountManager; /* Announce volume to mount manager */ - BOOL bPreserveTimestamp; /* Preserve file container timestamp */ - BOOL bPartitionInInactiveSysEncScope; /* If TRUE, we are to attempt to mount a partition located on an encrypted system drive without pre-boot authentication. */ - int nPartitionInInactiveSysEncScopeDriveNo; /* If bPartitionInInactiveSysEncScope is TRUE, this contains the drive number of the system drive on which the partition is located. */ - BOOL SystemFavorite; - // Hidden volume protection - BOOL bProtectHiddenVolume; /* TRUE if the user wants the hidden volume within this volume to be protected against being overwritten (damaged) */ - Password ProtectedHidVolPassword; /* Password to the hidden volume to be protected against overwriting */ - BOOL UseBackupHeader; - BOOL RecoveryMode; - int pkcs5_prf; - int ProtectedHidVolPkcs5Prf; - BOOL bTrueCryptMode; - uint32 BytesPerPhysicalSector; - int VolumePim; - int ProtectedHidVolPim; - wchar_t wszLabel[33]; // maximum label length is 32 for NTFS and 11 for FAT32 - BOOL bIsNTFS; // output only - BOOL bDriverSetLabel; - BOOL bCachePim; -} MOUNT_STRUCT; - -typedef struct -{ - int nDosDriveNo; /* Drive letter to unmount */ - BOOL ignoreOpenFiles; - BOOL HiddenVolumeProtectionTriggered; - int nReturnCode; /* Return code back from driver */ -} UNMOUNT_STRUCT; - -typedef struct -{ - unsigned __int32 ulMountedDrives; /* Bitfield of all mounted drive letters */ - wchar_t wszVolume[26][TC_MAX_PATH]; /* Volume names of mounted volumes */ - wchar_t wszLabel[26][33]; /* Labels of mounted volumes */ - wchar_t volumeID[26][VOLUME_ID_SIZE]; /* IDs of mounted volumes */ - unsigned __int64 diskLength[26]; - int ea[26]; - int volumeType[26]; /* Volume type (e.g. PROP_VOL_TYPE_OUTER, PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED, etc.) */ - BOOL truecryptMode[26]; -} MOUNT_LIST_STRUCT; - -typedef struct -{ - int driveNo; - int uniqueId; - wchar_t wszVolume[TC_MAX_PATH]; - unsigned __int64 diskLength; - int ea; - int mode; - int pkcs5; - int pkcs5Iterations; - BOOL hiddenVolume; - BOOL readOnly; - BOOL removable; - BOOL partitionInInactiveSysEncScope; - uint32 volumeHeaderFlags; - unsigned __int64 totalBytesRead; - unsigned __int64 totalBytesWritten; - int hiddenVolProtection; /* Hidden volume protection status (e.g. HIDVOL_PROT_STATUS_NONE, HIDVOL_PROT_STATUS_ACTIVE, etc.) */ - int volFormatVersion; - int volumePim; - wchar_t wszLabel[33]; - BOOL bDriverSetLabel; - unsigned char volumeID[VOLUME_ID_SIZE]; -} VOLUME_PROPERTIES_STRUCT; - -typedef struct -{ - WCHAR symLinkName[TC_MAX_PATH]; - WCHAR targetName[TC_MAX_PATH]; -} RESOLVE_SYMLINK_STRUCT; - -typedef struct -{ - WCHAR deviceName[TC_MAX_PATH]; - PARTITION_INFORMATION partInfo; - BOOL IsGPT; - BOOL IsDynamic; -} -DISK_PARTITION_INFO_STRUCT; - -typedef struct -{ - WCHAR deviceName[TC_MAX_PATH]; - DISK_GEOMETRY diskGeometry; -} -DISK_GEOMETRY_STRUCT; - -typedef struct -{ - WCHAR DeviceName[TC_MAX_PATH]; - LARGE_INTEGER RealDriveSize; - BOOL TimeOut; -} ProbeRealDriveSizeRequest; - -typedef struct -{ - wchar_t wszFileName[TC_MAX_PATH]; // Volume to be "open tested" - BOOL bDetectTCBootLoader; // Whether the driver is to determine if the first sector contains a portion of the TrueCrypt Boot Loader - BOOL TCBootLoaderDetected; - BOOL DetectFilesystem; - BOOL FilesystemDetected; - BOOL bMatchVolumeID; - unsigned char volumeID[VOLUME_ID_SIZE]; - BOOL VolumeIDMatched; -} OPEN_TEST_STRUCT; - - -typedef enum -{ - SetupNone = 0, - SetupEncryption, - SetupDecryption -} BootEncryptionSetupMode; - - -typedef struct -{ - // New fields must be added at the end of the structure to maintain compatibility with previous versions - BOOL DeviceFilterActive; - - uint16 BootLoaderVersion; - - BOOL DriveMounted; - BOOL VolumeHeaderPresent; - BOOL DriveEncrypted; - - LARGE_INTEGER BootDriveLength; - - int64 ConfiguredEncryptedAreaStart; - int64 ConfiguredEncryptedAreaEnd; - int64 EncryptedAreaStart; - int64 EncryptedAreaEnd; - - uint32 VolumeHeaderSaltCrc32; - - BOOL SetupInProgress; - BootEncryptionSetupMode SetupMode; - BOOL TransformWaitingForIdle; - - uint32 HibernationPreventionCount; - - BOOL HiddenSystem; - int64 HiddenSystemPartitionStart; - - // Number of times the filter driver answered that an unencrypted volume - // is read-only (or mounted an outer/normal TrueCrypt volume as read only) - uint32 HiddenSysLeakProtectionCount; - -} BootEncryptionStatus; - - -typedef struct -{ - BootEncryptionSetupMode SetupMode; - WipeAlgorithmId WipeAlgorithm; - BOOL ZeroUnreadableSectors; - BOOL DiscardUnreadableEncryptedSectors; -} BootEncryptionSetupRequest; - - -typedef struct -{ - Password VolumePassword; - int pkcs5_prf; - int pim; -} ReopenBootVolumeHeaderRequest; - - -typedef struct -{ - char BootEncryptionAlgorithmName[256]; - char BootPrfAlgorithmName[256]; -} GetBootEncryptionAlgorithmNameRequest; - -typedef struct -{ - byte Fingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE]; -} BootLoaderFingerprintRequest; - -typedef struct -{ - wchar_t DevicePath[TC_MAX_PATH]; - byte Configuration; - BOOL DriveIsDynamic; - uint16 BootLoaderVersion; - byte UserConfiguration; - char CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH + 1]; -} GetSystemDriveConfigurationRequest; - -typedef struct -{ - WipeAlgorithmId WipeAlgorithm; - byte WipeKey[MASTER_KEYDATA_SIZE]; -} WipeDecoySystemRequest; - -typedef struct -{ - BOOL WipeInProgress; - WipeAlgorithmId WipeAlgorithm; - int64 WipedAreaEnd; -} DecoySystemWipeStatus; - -typedef struct -{ - LARGE_INTEGER Offset; - byte Data[TC_SECTOR_SIZE_BIOS]; -} WriteBootDriveSectorRequest; - -typedef struct -{ - BOOL PagingFileCreationPrevented; - BOOL SystemFavoriteVolumeDirty; -} GetWarningFlagsRequest; - -typedef struct -{ - struct _DriveFilterExtension *BootDriveFilterExtension; - BOOL HwEncryptionEnabled; -} GetSystemDriveDumpConfigRequest; - -#pragma pack (pop) - -#define DRIVER_STR WIDE - -#define TC_UNIQUE_ID_PREFIX "VeraCryptVolume" -#define TC_MOUNT_PREFIX L"\\Device\\VeraCryptVolume" - -#define NT_MOUNT_PREFIX DRIVER_STR("\\Device\\VeraCryptVolume") -#define NT_ROOT_PREFIX DRIVER_STR("\\Device\\VeraCrypt") -#define DOS_MOUNT_PREFIX_DEFAULT DRIVER_STR("\\DosDevices\\") -#define DOS_MOUNT_PREFIX_GLOBAL DRIVER_STR("\\GLOBAL??\\") // Use Global MS-DOS device names for sanity checks on drive letters -#define DOS_ROOT_PREFIX DRIVER_STR("\\DosDevices\\VeraCrypt") -#define WIN32_ROOT_PREFIX DRIVER_STR("\\\\.\\VeraCrypt") - -#define TC_DRIVER_CONFIG_REG_VALUE_NAME DRIVER_STR("VeraCryptConfig") -#define TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME DRIVER_STR("VeraCryptEncryptionFreeCpuCount") - -// WARNING: Modifying the following values can introduce incompatibility with previous versions. -#define TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD 0x1 -#define TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES 0x2 -#define TC_DRIVER_CONFIG_DISABLE_NONADMIN_SYS_FAVORITES_ACCESS 0x4 -#define TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION 0x8 -#define TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL 0x10 -#define TC_DRIVER_CONFIG_DISABLE_EVIL_MAID_ATTACK_DETECTION 0x20 -#define TC_DRIVER_CONFIG_CACHE_BOOT_PIM 0x40 - -#endif /* _WIN32 */ +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#pragma once + +#include "Tcdefs.h" +#include "Boot/Windows/BootDefs.h" +#include "Common.h" +#include "Crypto.h" +#include "Volumes.h" +#include "Wipe.h" + +#ifdef _WIN32 + +/* WARNING: Modifying the following values or their meanings can introduce incompatibility with previous versions. */ + +#define TC_IOCTL(CODE) (CTL_CODE (FILE_DEVICE_UNKNOWN, 0x800 + (CODE), METHOD_BUFFERED, FILE_ANY_ACCESS)) + +#define TC_IOCTL_GET_DRIVER_VERSION TC_IOCTL (1) +#define TC_IOCTL_GET_BOOT_LOADER_VERSION TC_IOCTL (2) +#define TC_IOCTL_MOUNT_VOLUME TC_IOCTL (3) +#define TC_IOCTL_DISMOUNT_VOLUME TC_IOCTL (4) +#define TC_IOCTL_DISMOUNT_ALL_VOLUMES TC_IOCTL (5) +#define TC_IOCTL_GET_MOUNTED_VOLUMES TC_IOCTL (6) +#define TC_IOCTL_GET_VOLUME_PROPERTIES TC_IOCTL (7) +#define TC_IOCTL_GET_DEVICE_REFCOUNT TC_IOCTL (8) +#define TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED TC_IOCTL (9) +#define TC_IOCTL_IS_ANY_VOLUME_MOUNTED TC_IOCTL (10) +#define TC_IOCTL_GET_PASSWORD_CACHE_STATUS TC_IOCTL (11) +#define TC_IOCTL_WIPE_PASSWORD_CACHE TC_IOCTL (12) +#define TC_IOCTL_OPEN_TEST TC_IOCTL (13) +#define TC_IOCTL_GET_DRIVE_PARTITION_INFO TC_IOCTL (14) +#define TC_IOCTL_GET_DRIVE_GEOMETRY TC_IOCTL (15) +#define TC_IOCTL_PROBE_REAL_DRIVE_SIZE TC_IOCTL (16) +#define TC_IOCTL_GET_RESOLVED_SYMLINK TC_IOCTL (17) +#define TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS TC_IOCTL (18) +#define TC_IOCTL_BOOT_ENCRYPTION_SETUP TC_IOCTL (19) +#define TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP TC_IOCTL (20) +#define TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT TC_IOCTL (21) +#define TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES TC_IOCTL (22) +#define TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER TC_IOCTL (23) +#define TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME TC_IOCTL (24) +#define TC_IOCTL_GET_PORTABLE_MODE_STATUS TC_IOCTL (25) +#define TC_IOCTL_SET_PORTABLE_MODE_STATUS TC_IOCTL (26) +#define TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING TC_IOCTL (27) +#define TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG TC_IOCTL (28) +#define TC_IOCTL_DISK_IS_WRITABLE TC_IOCTL (29) +#define TC_IOCTL_START_DECOY_SYSTEM_WIPE TC_IOCTL (30) +#define TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE TC_IOCTL (31) +#define TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS TC_IOCTL (32) +#define TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT TC_IOCTL (33) +#define TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR TC_IOCTL (34) +#define TC_IOCTL_GET_WARNING_FLAGS TC_IOCTL (35) +#define TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY TC_IOCTL (36) +#define TC_IOCTL_REREAD_DRIVER_CONFIG TC_IOCTL (37) +#define TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG TC_IOCTL (38) +#define VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT TC_IOCTL (39) + +// Legacy IOCTLs used before version 5.0 +#define TC_IOCTL_LEGACY_GET_DRIVER_VERSION 466968 +#define TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES 466948 + + +/* Start of driver interface structures, the size of these structures may + change between versions; so make sure you first send DRIVER_VERSION to + check that it's the correct device driver */ + +#pragma pack (push) +#pragma pack(1) + +typedef struct +{ + int nReturnCode; /* Return code back from driver */ + BOOL FilesystemDirty; + BOOL VolumeMountedReadOnlyAfterAccessDenied; + BOOL VolumeMountedReadOnlyAfterDeviceWriteProtected; + + wchar_t wszVolume[TC_MAX_PATH]; /* Volume to be mounted */ + Password VolumePassword; /* User password */ + BOOL bCache; /* Cache passwords in driver */ + int nDosDriveNo; /* Drive number to mount */ + uint32 BytesPerSector; + BOOL bMountReadOnly; /* Mount volume in read-only mode */ + BOOL bMountRemovable; /* Mount volume as removable media */ + BOOL bExclusiveAccess; /* Open host file/device in exclusive access mode */ + BOOL bMountManager; /* Announce volume to mount manager */ + BOOL bPreserveTimestamp; /* Preserve file container timestamp */ + BOOL bPartitionInInactiveSysEncScope; /* If TRUE, we are to attempt to mount a partition located on an encrypted system drive without pre-boot authentication. */ + int nPartitionInInactiveSysEncScopeDriveNo; /* If bPartitionInInactiveSysEncScope is TRUE, this contains the drive number of the system drive on which the partition is located. */ + BOOL SystemFavorite; + // Hidden volume protection + BOOL bProtectHiddenVolume; /* TRUE if the user wants the hidden volume within this volume to be protected against being overwritten (damaged) */ + Password ProtectedHidVolPassword; /* Password to the hidden volume to be protected against overwriting */ + BOOL UseBackupHeader; + BOOL RecoveryMode; + int pkcs5_prf; + int ProtectedHidVolPkcs5Prf; + BOOL bTrueCryptMode; + uint32 BytesPerPhysicalSector; + int VolumePim; + int ProtectedHidVolPim; + wchar_t wszLabel[33]; // maximum label length is 32 for NTFS and 11 for FAT32 + BOOL bIsNTFS; // output only + BOOL bDriverSetLabel; + BOOL bCachePim; +} MOUNT_STRUCT; + +typedef struct +{ + int nDosDriveNo; /* Drive letter to unmount */ + BOOL ignoreOpenFiles; + BOOL HiddenVolumeProtectionTriggered; + int nReturnCode; /* Return code back from driver */ +} UNMOUNT_STRUCT; + +typedef struct +{ + unsigned __int32 ulMountedDrives; /* Bitfield of all mounted drive letters */ + wchar_t wszVolume[26][TC_MAX_PATH]; /* Volume names of mounted volumes */ + wchar_t wszLabel[26][33]; /* Labels of mounted volumes */ + wchar_t volumeID[26][VOLUME_ID_SIZE]; /* IDs of mounted volumes */ + unsigned __int64 diskLength[26]; + int ea[26]; + int volumeType[26]; /* Volume type (e.g. PROP_VOL_TYPE_OUTER, PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED, etc.) */ + BOOL truecryptMode[26]; +} MOUNT_LIST_STRUCT; + +typedef struct +{ + int driveNo; + int uniqueId; + wchar_t wszVolume[TC_MAX_PATH]; + unsigned __int64 diskLength; + int ea; + int mode; + int pkcs5; + int pkcs5Iterations; + BOOL hiddenVolume; + BOOL readOnly; + BOOL removable; + BOOL partitionInInactiveSysEncScope; + uint32 volumeHeaderFlags; + unsigned __int64 totalBytesRead; + unsigned __int64 totalBytesWritten; + int hiddenVolProtection; /* Hidden volume protection status (e.g. HIDVOL_PROT_STATUS_NONE, HIDVOL_PROT_STATUS_ACTIVE, etc.) */ + int volFormatVersion; + int volumePim; + wchar_t wszLabel[33]; + BOOL bDriverSetLabel; + unsigned char volumeID[VOLUME_ID_SIZE]; +} VOLUME_PROPERTIES_STRUCT; + +typedef struct +{ + WCHAR symLinkName[TC_MAX_PATH]; + WCHAR targetName[TC_MAX_PATH]; +} RESOLVE_SYMLINK_STRUCT; + +typedef struct +{ + WCHAR deviceName[TC_MAX_PATH]; + PARTITION_INFORMATION partInfo; + BOOL IsGPT; + BOOL IsDynamic; +} +DISK_PARTITION_INFO_STRUCT; + +typedef struct +{ + WCHAR deviceName[TC_MAX_PATH]; + DISK_GEOMETRY diskGeometry; +} +DISK_GEOMETRY_STRUCT; + +typedef struct +{ + WCHAR DeviceName[TC_MAX_PATH]; + LARGE_INTEGER RealDriveSize; + BOOL TimeOut; +} ProbeRealDriveSizeRequest; + +typedef struct +{ + wchar_t wszFileName[TC_MAX_PATH]; // Volume to be "open tested" + BOOL bDetectTCBootLoader; // Whether the driver is to determine if the first sector contains a portion of the TrueCrypt Boot Loader + BOOL TCBootLoaderDetected; + BOOL DetectFilesystem; + BOOL FilesystemDetected; + BOOL bMatchVolumeID; + unsigned char volumeID[VOLUME_ID_SIZE]; + BOOL VolumeIDMatched; +} OPEN_TEST_STRUCT; + + +typedef enum +{ + SetupNone = 0, + SetupEncryption, + SetupDecryption +} BootEncryptionSetupMode; + + +typedef struct +{ + // New fields must be added at the end of the structure to maintain compatibility with previous versions + BOOL DeviceFilterActive; + + uint16 BootLoaderVersion; + + BOOL DriveMounted; + BOOL VolumeHeaderPresent; + BOOL DriveEncrypted; + + LARGE_INTEGER BootDriveLength; + + int64 ConfiguredEncryptedAreaStart; + int64 ConfiguredEncryptedAreaEnd; + int64 EncryptedAreaStart; + int64 EncryptedAreaEnd; + + uint32 VolumeHeaderSaltCrc32; + + BOOL SetupInProgress; + BootEncryptionSetupMode SetupMode; + BOOL TransformWaitingForIdle; + + uint32 HibernationPreventionCount; + + BOOL HiddenSystem; + int64 HiddenSystemPartitionStart; + + // Number of times the filter driver answered that an unencrypted volume + // is read-only (or mounted an outer/normal TrueCrypt volume as read only) + uint32 HiddenSysLeakProtectionCount; + +} BootEncryptionStatus; + + +typedef struct +{ + BootEncryptionSetupMode SetupMode; + WipeAlgorithmId WipeAlgorithm; + BOOL ZeroUnreadableSectors; + BOOL DiscardUnreadableEncryptedSectors; +} BootEncryptionSetupRequest; + + +typedef struct +{ + Password VolumePassword; + int pkcs5_prf; + int pim; +} ReopenBootVolumeHeaderRequest; + + +typedef struct +{ + char BootEncryptionAlgorithmName[256]; + char BootPrfAlgorithmName[256]; +} GetBootEncryptionAlgorithmNameRequest; + +typedef struct +{ + byte Fingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE]; +} BootLoaderFingerprintRequest; + +typedef struct +{ + wchar_t DevicePath[TC_MAX_PATH]; + byte Configuration; + BOOL DriveIsDynamic; + uint16 BootLoaderVersion; + byte UserConfiguration; + char CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH + 1]; +} GetSystemDriveConfigurationRequest; + +typedef struct +{ + WipeAlgorithmId WipeAlgorithm; + byte WipeKey[MASTER_KEYDATA_SIZE]; +} WipeDecoySystemRequest; + +typedef struct +{ + BOOL WipeInProgress; + WipeAlgorithmId WipeAlgorithm; + int64 WipedAreaEnd; +} DecoySystemWipeStatus; + +typedef struct +{ + LARGE_INTEGER Offset; + byte Data[TC_SECTOR_SIZE_BIOS]; +} WriteBootDriveSectorRequest; + +typedef struct +{ + BOOL PagingFileCreationPrevented; + BOOL SystemFavoriteVolumeDirty; +} GetWarningFlagsRequest; + +typedef struct +{ + struct _DriveFilterExtension *BootDriveFilterExtension; + BOOL HwEncryptionEnabled; +} GetSystemDriveDumpConfigRequest; + +#pragma pack (pop) + +#define DRIVER_STR WIDE + +#define TC_UNIQUE_ID_PREFIX "VeraCryptVolume" +#define TC_MOUNT_PREFIX L"\\Device\\VeraCryptVolume" + +#define NT_MOUNT_PREFIX DRIVER_STR("\\Device\\VeraCryptVolume") +#define NT_ROOT_PREFIX DRIVER_STR("\\Device\\VeraCrypt") +#define DOS_MOUNT_PREFIX_DEFAULT DRIVER_STR("\\DosDevices\\") +#define DOS_MOUNT_PREFIX_GLOBAL DRIVER_STR("\\GLOBAL??\\") // Use Global MS-DOS device names for sanity checks on drive letters +#define DOS_ROOT_PREFIX DRIVER_STR("\\DosDevices\\VeraCrypt") +#define WIN32_ROOT_PREFIX DRIVER_STR("\\\\.\\VeraCrypt") + +#define TC_DRIVER_CONFIG_REG_VALUE_NAME DRIVER_STR("VeraCryptConfig") +#define TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME DRIVER_STR("VeraCryptEncryptionFreeCpuCount") + +// WARNING: Modifying the following values can introduce incompatibility with previous versions. +#define TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD 0x1 +#define TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES 0x2 +#define TC_DRIVER_CONFIG_DISABLE_NONADMIN_SYS_FAVORITES_ACCESS 0x4 +#define TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION 0x8 +#define TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL 0x10 +#define TC_DRIVER_CONFIG_DISABLE_EVIL_MAID_ATTACK_DETECTION 0x20 +#define TC_DRIVER_CONFIG_CACHE_BOOT_PIM 0x40 + +#endif /* _WIN32 */ diff --git a/src/Common/BaseCom.cpp b/src/Common/BaseCom.cpp index 8e7d39ff..f6c55974 100644 --- a/src/Common/BaseCom.cpp +++ b/src/Common/BaseCom.cpp @@ -1,246 +1,246 @@ -/* - 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 -#include -#include -#include -#include "BaseCom.h" -#include "BootEncryption.h" -#include "Dlgcode.h" -#include "Registry.h" - -using namespace VeraCrypt; - -HRESULT CreateElevatedComObject (HWND hwnd, REFGUID guid, REFIID iid, void **ppv) -{ - WCHAR monikerName[1024]; - WCHAR clsid[1024]; - BIND_OPTS3 bo; - - StringFromGUID2 (guid, clsid, sizeof (clsid) / 2); - swprintf_s (monikerName, sizeof (monikerName) / 2, L"Elevation:Administrator!new:%s", clsid); - - memset (&bo, 0, sizeof (bo)); - bo.cbStruct = sizeof (bo); - bo.hwnd = hwnd; - bo.dwClassContext = CLSCTX_LOCAL_SERVER; - - // Prevent the GUI from being half-rendered when the UAC prompt "freezes" it - ProcessPaintMessages (hwnd, 5000); - - return CoGetObject (monikerName, &bo, iid, ppv); -} - - -BOOL ComGetInstanceBase (HWND hWnd, REFCLSID clsid, REFIID iid, void **tcServer) -{ - BOOL r; - - if (IsUacSupported ()) - { - while (true) - { - r = CreateElevatedComObject (hWnd, clsid, iid, tcServer) == S_OK; - if (r) - break; - else - { - if (IDRETRY == ErrorRetryCancel ("UAC_INIT_ERROR", hWnd)) - continue; - else - break; - } - } - } - else - { - r = CoCreateInstance (clsid, NULL, CLSCTX_LOCAL_SERVER, iid, tcServer) == S_OK; - if (!r) - Error ("UAC_INIT_ERROR", hWnd); - } - - return r; -} - - -DWORD BaseCom::CallDriver (DWORD ioctl, BSTR input, BSTR *output) -{ - try - { - BootEncryption bootEnc (NULL); - bootEnc.CallDriver (ioctl, - (BYTE *) input, !(BYTE *) input ? 0 : ((DWORD *) ((BYTE *) input))[-1], - (BYTE *) *output, !(BYTE *) *output ? 0 : ((DWORD *) ((BYTE *) *output))[-1]); - } - catch (SystemException &) - { - return GetLastError(); - } - catch (Exception &e) - { - e.Show (NULL); - return ERROR_EXCEPTION_IN_SERVICE; - } - catch (...) - { - return ERROR_EXCEPTION_IN_SERVICE; - } - - return ERROR_SUCCESS; -} - - -DWORD BaseCom::CopyFile (BSTR sourceFile, BSTR destinationFile) -{ - - if (!::CopyFileW (sourceFile, destinationFile, FALSE)) - return GetLastError(); - - return ERROR_SUCCESS; -} - - -DWORD BaseCom::DeleteFile (BSTR file) -{ - - if (!::DeleteFileW (file)) - return GetLastError(); - - return ERROR_SUCCESS; -} - - -BOOL BaseCom::IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) -{ - return ::IsPagingFileActive (checkNonWindowsPartitionsOnly); -} - - -DWORD BaseCom::ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone) -{ - try - { - auto_ptr file (device ? new Device (filePath, !write) : new File (filePath, !write)); - file->CheckOpened (SRC_POS); - file->SeekAt (offset); - - if (write) - { - file->Write ((BYTE *) *bufferBstr, size); - *sizeDone = size; - } - else - { - *sizeDone = file->Read ((BYTE *) *bufferBstr, size); - } - } - catch (SystemException &) - { - return GetLastError(); - } - catch (Exception &e) - { - e.Show (NULL); - return ERROR_EXCEPTION_IN_SERVICE; - } - catch (...) - { - return ERROR_EXCEPTION_IN_SERVICE; - } - - return ERROR_SUCCESS; -} - - -DWORD BaseCom::RegisterFilterDriver (BOOL registerDriver, int filterType) -{ - try - { - BootEncryption bootEnc (NULL); - bootEnc.RegisterFilterDriver (registerDriver ? true : false, (BootEncryption::FilterType) filterType); - } - catch (SystemException &) - { - return GetLastError(); - } - catch (Exception &e) - { - e.Show (NULL); - return ERROR_EXCEPTION_IN_SERVICE; - } - catch (...) - { - return ERROR_EXCEPTION_IN_SERVICE; - } - - return ERROR_SUCCESS; -} - - -DWORD BaseCom::RegisterSystemFavoritesService (BOOL registerService) -{ - try - { - BootEncryption bootEnc (NULL); - bootEnc.RegisterSystemFavoritesService (registerService); - } - catch (SystemException &) - { - return GetLastError(); - } - catch (Exception &e) - { - e.Show (NULL); - return ERROR_EXCEPTION_IN_SERVICE; - } - catch (...) - { - return ERROR_EXCEPTION_IN_SERVICE; - } - - return ERROR_SUCCESS; -} - - -DWORD BaseCom::SetDriverServiceStartType (DWORD startType) -{ - try - { - BootEncryption bootEnc (NULL); - bootEnc.SetDriverServiceStartType (startType); - } - catch (SystemException &) - { - return GetLastError(); - } - catch (Exception &e) - { - e.Show (NULL); - return ERROR_EXCEPTION_IN_SERVICE; - } - catch (...) - { - return ERROR_EXCEPTION_IN_SERVICE; - } - - return ERROR_SUCCESS; -} - - -DWORD BaseCom::WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value) -{ - if (!::WriteLocalMachineRegistryDword (keyPath, valueName, value)) - return GetLastError(); - - return ERROR_SUCCESS; -} +/* + 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 +#include +#include +#include +#include "BaseCom.h" +#include "BootEncryption.h" +#include "Dlgcode.h" +#include "Registry.h" + +using namespace VeraCrypt; + +HRESULT CreateElevatedComObject (HWND hwnd, REFGUID guid, REFIID iid, void **ppv) +{ + WCHAR monikerName[1024]; + WCHAR clsid[1024]; + BIND_OPTS3 bo; + + StringFromGUID2 (guid, clsid, sizeof (clsid) / 2); + swprintf_s (monikerName, sizeof (monikerName) / 2, L"Elevation:Administrator!new:%s", clsid); + + memset (&bo, 0, sizeof (bo)); + bo.cbStruct = sizeof (bo); + bo.hwnd = hwnd; + bo.dwClassContext = CLSCTX_LOCAL_SERVER; + + // Prevent the GUI from being half-rendered when the UAC prompt "freezes" it + ProcessPaintMessages (hwnd, 5000); + + return CoGetObject (monikerName, &bo, iid, ppv); +} + + +BOOL ComGetInstanceBase (HWND hWnd, REFCLSID clsid, REFIID iid, void **tcServer) +{ + BOOL r; + + if (IsUacSupported ()) + { + while (true) + { + r = CreateElevatedComObject (hWnd, clsid, iid, tcServer) == S_OK; + if (r) + break; + else + { + if (IDRETRY == ErrorRetryCancel ("UAC_INIT_ERROR", hWnd)) + continue; + else + break; + } + } + } + else + { + r = CoCreateInstance (clsid, NULL, CLSCTX_LOCAL_SERVER, iid, tcServer) == S_OK; + if (!r) + Error ("UAC_INIT_ERROR", hWnd); + } + + return r; +} + + +DWORD BaseCom::CallDriver (DWORD ioctl, BSTR input, BSTR *output) +{ + try + { + BootEncryption bootEnc (NULL); + bootEnc.CallDriver (ioctl, + (BYTE *) input, !(BYTE *) input ? 0 : ((DWORD *) ((BYTE *) input))[-1], + (BYTE *) *output, !(BYTE *) *output ? 0 : ((DWORD *) ((BYTE *) *output))[-1]); + } + catch (SystemException &) + { + return GetLastError(); + } + catch (Exception &e) + { + e.Show (NULL); + return ERROR_EXCEPTION_IN_SERVICE; + } + catch (...) + { + return ERROR_EXCEPTION_IN_SERVICE; + } + + return ERROR_SUCCESS; +} + + +DWORD BaseCom::CopyFile (BSTR sourceFile, BSTR destinationFile) +{ + + if (!::CopyFileW (sourceFile, destinationFile, FALSE)) + return GetLastError(); + + return ERROR_SUCCESS; +} + + +DWORD BaseCom::DeleteFile (BSTR file) +{ + + if (!::DeleteFileW (file)) + return GetLastError(); + + return ERROR_SUCCESS; +} + + +BOOL BaseCom::IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) +{ + return ::IsPagingFileActive (checkNonWindowsPartitionsOnly); +} + + +DWORD BaseCom::ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone) +{ + try + { + auto_ptr file (device ? new Device (filePath, !write) : new File (filePath, !write)); + file->CheckOpened (SRC_POS); + file->SeekAt (offset); + + if (write) + { + file->Write ((BYTE *) *bufferBstr, size); + *sizeDone = size; + } + else + { + *sizeDone = file->Read ((BYTE *) *bufferBstr, size); + } + } + catch (SystemException &) + { + return GetLastError(); + } + catch (Exception &e) + { + e.Show (NULL); + return ERROR_EXCEPTION_IN_SERVICE; + } + catch (...) + { + return ERROR_EXCEPTION_IN_SERVICE; + } + + return ERROR_SUCCESS; +} + + +DWORD BaseCom::RegisterFilterDriver (BOOL registerDriver, int filterType) +{ + try + { + BootEncryption bootEnc (NULL); + bootEnc.RegisterFilterDriver (registerDriver ? true : false, (BootEncryption::FilterType) filterType); + } + catch (SystemException &) + { + return GetLastError(); + } + catch (Exception &e) + { + e.Show (NULL); + return ERROR_EXCEPTION_IN_SERVICE; + } + catch (...) + { + return ERROR_EXCEPTION_IN_SERVICE; + } + + return ERROR_SUCCESS; +} + + +DWORD BaseCom::RegisterSystemFavoritesService (BOOL registerService) +{ + try + { + BootEncryption bootEnc (NULL); + bootEnc.RegisterSystemFavoritesService (registerService); + } + catch (SystemException &) + { + return GetLastError(); + } + catch (Exception &e) + { + e.Show (NULL); + return ERROR_EXCEPTION_IN_SERVICE; + } + catch (...) + { + return ERROR_EXCEPTION_IN_SERVICE; + } + + return ERROR_SUCCESS; +} + + +DWORD BaseCom::SetDriverServiceStartType (DWORD startType) +{ + try + { + BootEncryption bootEnc (NULL); + bootEnc.SetDriverServiceStartType (startType); + } + catch (SystemException &) + { + return GetLastError(); + } + catch (Exception &e) + { + e.Show (NULL); + return ERROR_EXCEPTION_IN_SERVICE; + } + catch (...) + { + return ERROR_EXCEPTION_IN_SERVICE; + } + + return ERROR_SUCCESS; +} + + +DWORD BaseCom::WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value) +{ + if (!::WriteLocalMachineRegistryDword (keyPath, valueName, value)) + return GetLastError(); + + return ERROR_SUCCESS; +} diff --git a/src/Common/BaseCom.h b/src/Common/BaseCom.h index 9f5b312a..97009410 100644 --- a/src/Common/BaseCom.h +++ b/src/Common/BaseCom.h @@ -1,119 +1,119 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_BASE_COM -#define TC_HEADER_BASE_COM - -#include - -template -class TrueCryptFactory : public IClassFactory -{ - -public: - TrueCryptFactory (DWORD messageThreadId) : - RefCount (1), ServerLockCount (0), MessageThreadId (messageThreadId) { } - - ~TrueCryptFactory () { } - - virtual ULONG STDMETHODCALLTYPE AddRef () - { - return InterlockedIncrement (&RefCount) - 1; - } - - virtual ULONG STDMETHODCALLTYPE Release () - { - ULONG r = InterlockedDecrement (&RefCount) + 1; - - if (r == 0) - delete this; - - return r; - } - - virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID riid, void **ppvObject) - { - if (riid == IID_IUnknown || riid == IID_IClassFactory) - *ppvObject = this; - else - { - *ppvObject = NULL; - return E_NOINTERFACE; - } - - AddRef (); - return S_OK; - } - - virtual HRESULT STDMETHODCALLTYPE CreateInstance (IUnknown *pUnkOuter, REFIID riid, void **ppvObject) - { - if (pUnkOuter != NULL) - return CLASS_E_NOAGGREGATION; - - TClass *tc = new TClass (MessageThreadId); - if (tc == NULL) - return E_OUTOFMEMORY; - - HRESULT hr = tc->QueryInterface (riid, ppvObject); - - if (hr) - delete tc; - - return hr; - } - - virtual HRESULT STDMETHODCALLTYPE LockServer (BOOL fLock) - { - if (fLock) - { - InterlockedIncrement (&ServerLockCount); - } - else - { - if (!InterlockedDecrement (&ServerLockCount)) - PostThreadMessage (MessageThreadId, WM_APP, 0, 0); - } - - return S_OK; - } - - virtual bool IsServerLocked () - { - return ServerLockCount > 0; - } - -protected: - DWORD MessageThreadId; - LONG RefCount; - LONG ServerLockCount; -}; - - -class BaseCom -{ -public: - static DWORD CallDriver (DWORD ioctl, BSTR input, BSTR *output); - static DWORD CopyFile (BSTR sourceFile, BSTR destinationFile); - static DWORD DeleteFile (BSTR file); - static BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly); - static DWORD ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone); - static DWORD RegisterFilterDriver (BOOL registerDriver, int filterType); - static DWORD RegisterSystemFavoritesService (BOOL registerService); - static DWORD SetDriverServiceStartType (DWORD startType); - static DWORD WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value); -}; - - -BOOL ComGetInstanceBase (HWND hWnd, REFCLSID clsid, REFIID iid, void **tcServer); -HRESULT CreateElevatedComObject (HWND hwnd, REFGUID guid, REFIID iid, void **ppv); - -#endif // TC_HEADER_BASE_COM +/* + 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. +*/ + +#ifndef TC_HEADER_BASE_COM +#define TC_HEADER_BASE_COM + +#include + +template +class TrueCryptFactory : public IClassFactory +{ + +public: + TrueCryptFactory (DWORD messageThreadId) : + RefCount (1), ServerLockCount (0), MessageThreadId (messageThreadId) { } + + ~TrueCryptFactory () { } + + virtual ULONG STDMETHODCALLTYPE AddRef () + { + return InterlockedIncrement (&RefCount) - 1; + } + + virtual ULONG STDMETHODCALLTYPE Release () + { + ULONG r = InterlockedDecrement (&RefCount) + 1; + + if (r == 0) + delete this; + + return r; + } + + virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID riid, void **ppvObject) + { + if (riid == IID_IUnknown || riid == IID_IClassFactory) + *ppvObject = this; + else + { + *ppvObject = NULL; + return E_NOINTERFACE; + } + + AddRef (); + return S_OK; + } + + virtual HRESULT STDMETHODCALLTYPE CreateInstance (IUnknown *pUnkOuter, REFIID riid, void **ppvObject) + { + if (pUnkOuter != NULL) + return CLASS_E_NOAGGREGATION; + + TClass *tc = new TClass (MessageThreadId); + if (tc == NULL) + return E_OUTOFMEMORY; + + HRESULT hr = tc->QueryInterface (riid, ppvObject); + + if (hr) + delete tc; + + return hr; + } + + virtual HRESULT STDMETHODCALLTYPE LockServer (BOOL fLock) + { + if (fLock) + { + InterlockedIncrement (&ServerLockCount); + } + else + { + if (!InterlockedDecrement (&ServerLockCount)) + PostThreadMessage (MessageThreadId, WM_APP, 0, 0); + } + + return S_OK; + } + + virtual bool IsServerLocked () + { + return ServerLockCount > 0; + } + +protected: + DWORD MessageThreadId; + LONG RefCount; + LONG ServerLockCount; +}; + + +class BaseCom +{ +public: + static DWORD CallDriver (DWORD ioctl, BSTR input, BSTR *output); + static DWORD CopyFile (BSTR sourceFile, BSTR destinationFile); + static DWORD DeleteFile (BSTR file); + static BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly); + static DWORD ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone); + static DWORD RegisterFilterDriver (BOOL registerDriver, int filterType); + static DWORD RegisterSystemFavoritesService (BOOL registerService); + static DWORD SetDriverServiceStartType (DWORD startType); + static DWORD WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value); +}; + + +BOOL ComGetInstanceBase (HWND hWnd, REFCLSID clsid, REFIID iid, void **tcServer); +HRESULT CreateElevatedComObject (HWND hwnd, REFGUID guid, REFIID iid, void **ppv); + +#endif // TC_HEADER_BASE_COM diff --git a/src/Common/BootEncryption.cpp b/src/Common/BootEncryption.cpp index 851d7622..73b64458 100644 --- a/src/Common/BootEncryption.cpp +++ b/src/Common/BootEncryption.cpp @@ -1,2813 +1,2813 @@ -/* - 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 "Tcdefs.h" -#include "Platform/Finally.h" -#include "Platform/ForEach.h" -#include -#include -#include -#include -#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 - -#include - -namespace VeraCrypt -{ -#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(SRC_POS); - } - } - - static void CopyFile (const wstring &sourceFile, const wstring &destinationFile) - { - Elevate(); - DWORD result; - CComBSTR sourceFileBstr, destinationFileBstr; - BSTR bstr = W2BSTR(sourceFile.c_str()); - if (bstr) - { - sourceFileBstr.Attach (bstr); - - bstr = W2BSTR(destinationFile.c_str()); - if (bstr) - { - destinationFileBstr.Attach (bstr); - result = ElevatedComInstance->CopyFile (sourceFileBstr, destinationFileBstr); - } - else - { - result = ERROR_OUTOFMEMORY; - } - } - else - { - result = ERROR_OUTOFMEMORY; - } - - if (result != ERROR_SUCCESS) - { - SetLastError (result); - throw SystemException(SRC_POS); - } - } - - static void DeleteFile (const wstring &file) - { - Elevate(); - CComBSTR fileBstr; - DWORD result; - BSTR bstr = W2BSTR(file.c_str()); - if (bstr) - { - fileBstr.Attach (bstr); - result = ElevatedComInstance->DeleteFile (fileBstr); - } - else - { - result = ERROR_OUTOFMEMORY; - } - - if (result != ERROR_SUCCESS) - { - SetLastError (result); - throw SystemException(SRC_POS); - } - } - - static void ReadWriteFile (BOOL write, BOOL device, const wstring &filePath, byte *buffer, uint64 offset, uint32 size, DWORD *sizeDone) - { - Elevate(); - - DWORD result; - CComBSTR bufferBstr, fileBstr; - if (bufferBstr.AppendBytes ((const char *) buffer, size) != S_OK) - throw ParameterIncorrect (SRC_POS); - BSTR bstr = W2BSTR(filePath.c_str()); - if (bstr) - { - fileBstr.Attach (bstr); - result = ElevatedComInstance->ReadWriteFile (write, device, fileBstr, &bufferBstr, offset, size, sizeDone); - } - else - { - result = ERROR_OUTOFMEMORY; - } - - if (result != ERROR_SUCCESS) - { - SetLastError (result); - throw SystemException(SRC_POS); - } - - if (!write) - memcpy (buffer, (BYTE *) bufferBstr.m_str, size); - } - - static BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) - { - Elevate(); - - return ElevatedComInstance->IsPagingFileActive (checkNonWindowsPartitionsOnly); - } - - static void WriteLocalMachineRegistryDwordValue (wchar_t *keyPath, wchar_t *valueName, DWORD value) - { - Elevate(); - DWORD result; - CComBSTR keyPathBstr, valueNameBstr; - BSTR bstr = W2BSTR(keyPath); - if (bstr) - { - keyPathBstr.Attach (bstr); - - bstr = W2BSTR(valueName); - if (bstr) - { - valueNameBstr.Attach (bstr); - - result = ElevatedComInstance->WriteLocalMachineRegistryDwordValue (keyPathBstr, valueNameBstr, value); - } - else - { - result = ERROR_OUTOFMEMORY; - } - } - else - { - result = ERROR_OUTOFMEMORY; - } - - if (result != ERROR_SUCCESS) - { - SetLastError (result); - throw SystemException(SRC_POS); - } - } - - 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(SRC_POS); - } - } - - static void RegisterSystemFavoritesService (BOOL registerService) - { - Elevate(); - - DWORD result = ElevatedComInstance->RegisterSystemFavoritesService (registerService); - if (result != ERROR_SUCCESS) - { - SetLastError (result); - throw SystemException(SRC_POS); - } - } - - 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(SRC_POS); - } - } - - protected: - static void Elevate () - { - if (IsAdmin()) - { - SetLastError (ERROR_ACCESS_DENIED); - throw SystemException(SRC_POS); - } - - 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 wstring &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 (wstring path, bool readOnly, bool create) : Elevated (false), FileOpen (false), LastError(0) - { - 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); - - if (Handle != INVALID_HANDLE_VALUE) - { - FileOpen = true; - } - else - { - LastError = GetLastError(); - if (LastError == ERROR_ACCESS_DENIED && IsUacSupported()) - { - Elevated = true; - FileOpen = true; - } - } - - FilePointerPosition = 0; - IsDevice = false; - Path = path; - } - - void File::Close () - { - if (Handle != INVALID_HANDLE_VALUE) - { - CloseHandle (Handle); - Handle = INVALID_HANDLE_VALUE; - } - - FileOpen = false; - } - - DWORD File::Read (byte *buffer, DWORD size) - { - DWORD bytesRead; - - if (!FileOpen) - { - SetLastError (LastError); - throw SystemException (SRC_POS); - } - - 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) - { - if (!FileOpen) - { - SetLastError (LastError); - throw SystemException (SRC_POS); - } - - 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; - - if (!FileOpen) - { - SetLastError (LastError); - throw SystemException (SRC_POS); - } - - 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 wstring &str) - { - MessageBox (parent, str.c_str(), NULL, 0); - } - - - Device::Device (wstring path, bool readOnly) - { - FileOpen = false; - Elevated = false; - - Handle = CreateFile ((wstring (L"\\\\.\\") + 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); - - if (Handle != INVALID_HANDLE_VALUE) - { - FileOpen = true; - } - else - { - LastError = GetLastError (); - if (LastError == ERROR_ACCESS_DENIED && IsUacSupported()) - { - Elevated = true; - FileOpen = true; - } - } - - FilePointerPosition = 0; - IsDevice = true; - Path = path; - } - - - BootEncryption::BootEncryption (HWND parent) - : DriveConfigValid (false), - ParentWindow (parent), - RealSystemDriveSizeValid (false), - RescueIsoImage (nullptr), - RescueVolumeHeaderValid (false), - SelectedEncryptionAlgorithmId (0), - SelectedPrfAlgorithmId (0), - VolumeHeaderValid (false) - { - HiddenOSCandidatePartition.IsGPT = FALSE; - HiddenOSCandidatePartition.Number = (size_t) -1; - DriveConfig.DriveNumber = -1; - DriveConfig.ExtraBootPartitionPresent = false; - DriveConfig.SystemLoaderPresent = false; - DriveConfig.InitialUnallocatedSpace = 0; - DriveConfig.TotalUnallocatedSpace = 0; - 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(), SRC_POS); - } - - 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(), SRC_POS); - } - - 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(), SRC_POS); - } - } - 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(), SRC_POS); - } - } - else - { - // No active partition on the system drive - throw ErrorException ("SYSTEM_PARTITION_NOT_ACTIVE", SRC_POS); - } - - HiddenOSCandidatePartition = candidatePartition; - return candidatePartition; - } - - - DWORD BootEncryption::GetDriverServiceStartType () - { - DWORD startType; - throw_sys_if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", L"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, L"veracrypt", 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. - wstring driverPath; - if (startOnBoot && !IsOSAtLeast (WIN_VISTA)) - { - wchar_t pathBuf[MAX_PATH]; - wchar_t filesystem[128]; - - wstring path (GetWindowsDirectory()); - path += L"\\drivers\\veracrypt.sys"; - - if (GetVolumePathName (path.c_str(), pathBuf, ARRAYSIZE (pathBuf)) - && GetVolumeInformation (pathBuf, NULL, 0, NULL, NULL, NULL, filesystem, ARRAYSIZE(filesystem)) - && wmemcmp (filesystem, L"FAT", 3) == 0) - { - throw_sys_if (GetShortPathName (path.c_str(), pathBuf, ARRAYSIZE (pathBuf)) == 0); - - // Convert absolute path to relative to the Windows directory - driverPath = pathBuf; - driverPath = driverPath.substr (driverPath.rfind (L"\\", driverPath.rfind (L"\\", driverPath.rfind (L"\\") - 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 ? L"Filter" : NULL, - NULL, NULL, NULL, NULL, NULL)); - - // ChangeServiceConfig() rejects SERVICE_BOOT_START with ERROR_INVALID_PARAMETER - throw_sys_if (!WriteLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", L"Start", startType)); - } - - - void BootEncryption::ProbeRealSystemDriveSize () - { - if (RealSystemDriveSizeValid) - return; - - GetSystemDriveConfiguration(); - - ProbeRealDriveSizeRequest request; - StringCchCopyW (request.DeviceName, ARRAYSIZE (request.DeviceName), 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) - { - wstringstream partPath; - partPath << L"\\Device\\Harddisk" << driveNumber << L"\\Partition" << partNumber; - - DISK_PARTITION_INFO_STRUCT diskPartInfo = {0}; - StringCchCopyW (diskPartInfo.deviceName, ARRAYSIZE (diskPartInfo.deviceName), partPath.str().c_str()); - - try - { - CallDriver (TC_IOCTL_GET_DRIVE_PARTITION_INFO, &diskPartInfo, sizeof (diskPartInfo), &diskPartInfo, sizeof (diskPartInfo)); - } - catch (...) - { - continue; - } - - if ( (diskPartInfo.IsGPT == TRUE || diskPartInfo.IsGPT == FALSE) - && (diskPartInfo.IsDynamic == TRUE || diskPartInfo.IsDynamic == FALSE) - && (diskPartInfo.partInfo.BootIndicator == TRUE || diskPartInfo.partInfo.BootIndicator == FALSE) - && (diskPartInfo.partInfo.RecognizedPartition == TRUE || diskPartInfo.partInfo.RecognizedPartition == FALSE) - && (diskPartInfo.partInfo.RewritePartition == TRUE || diskPartInfo.partInfo.RewritePartition == FALSE) - && (diskPartInfo.partInfo.StartingOffset.QuadPart >= 0) - && (diskPartInfo.partInfo.PartitionLength.QuadPart >= 0) - ) - { - Partition part; - part.DevicePath = partPath.str(); - part.Number = partNumber; - part.Info = diskPartInfo.partInfo; - part.IsGPT = diskPartInfo.IsGPT; - - // Mount point - int driveNumber = GetDiskDeviceDriveLetter ((wchar_t *) partPath.str().c_str()); - - if (driveNumber >= 0) - { - part.MountPoint += (wchar_t) (driveNumber + L'A'); - part.MountPoint += L":"; - } - - // Volume ID - wchar_t volumePath[TC_MAX_PATH]; - if (ResolveSymbolicLink ((wchar_t *) partPath.str().c_str(), volumePath, sizeof(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) - { - wstringstream devName; - devName << L"\\Device\\Harddisk" << driveNumber << L"\\Partition0"; - - DISK_GEOMETRY geometry; - throw_sys_if (!::GetDriveGeometry (devName.str().c_str(), &geometry)); - return geometry; - } - - - wstring BootEncryption::GetWindowsDirectory () - { - wchar_t buf[MAX_PATH]; - throw_sys_if (GetSystemDirectory (buf, ARRAYSIZE (buf)) == 0); - - return wstring (buf); - } - - - - uint16 BootEncryption::GetInstalledBootLoaderVersion () - { - uint16 version; - CallDriver (TC_IOCTL_GET_BOOT_LOADER_VERSION, NULL, 0, &version, sizeof (version)); - return version; - } - - void BootEncryption::GetInstalledBootLoaderFingerprint (byte fingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE]) - { - BootLoaderFingerprintRequest request; - CallDriver (VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT, NULL, 0, &request, sizeof (request)); - memcpy (fingerprint, request.Fingerprint, sizeof (request.Fingerprint)); - } - - // Note that this does not require admin rights (it just requires the driver to be running) - bool BootEncryption::IsBootLoaderOnDrive (wchar_t *devicePath) - { - try - { - OPEN_TEST_STRUCT openTestStruct; - memset (&openTestStruct, 0, sizeof (openTestStruct)); - DWORD dwResult; - - StringCchCopyW (&openTestStruct.wszFileName[0], ARRAYSIZE(openTestStruct.wszFileName),devicePath); - - 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); - device.CheckOpened (SRC_POS); - - byte mbrBuf[TC_SECTOR_SIZE_BIOS]; - device.SeekAt (0); - device.Read (mbrBuf, sizeof (mbrBuf)); - - MBR *mbr = reinterpret_cast (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; - StringCchCopyW (request.DevicePath, ARRAYSIZE (request.DevicePath), 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; - - wstring 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() - && (_waccess ((part.MountPoint + L"\\bootmgr").c_str(), 0) == 0 || _waccess ((part.MountPoint + L"\\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; - - wstringstream ss; - ss << L"PhysicalDrive" << driveNumber; - config.DevicePath = ss.str(); - - wstringstream kernelPath; - kernelPath << L"\\Device\\Harddisk" << driveNumber << L"\\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; - int pkcs5_prf = 0; - if (GetStatus().DriveMounted) - { - try - { - GetBootEncryptionAlgorithmNameRequest request; - // since we added new field to GetBootEncryptionAlgorithmNameRequest since version 1.0f - // we zero all the structure so that if we are talking to an older driver, the field - // BootPrfAlgorithmName will be an empty string - ZeroMemory(&request, sizeof(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; - - if (_stricmp(request.BootPrfAlgorithmName, "SHA-256") == 0) - pkcs5_prf = SHA256; - else if (_stricmp(request.BootPrfAlgorithmName, "RIPEMD-160") == 0) - pkcs5_prf = RIPEMD160; - else if (strlen(request.BootPrfAlgorithmName) == 0) // case of version < 1.0f - pkcs5_prf = RIPEMD160; - } - catch (...) - { - try - { - VOLUME_PROPERTIES_STRUCT properties; - GetVolumeProperties (&properties); - ea = properties.ea; - pkcs5_prf = properties.pkcs5; - } - catch (...) { } - } - } - else - { - if (SelectedEncryptionAlgorithmId == 0 || SelectedPrfAlgorithmId == 0) - throw ParameterIncorrect (SRC_POS); - - ea = SelectedEncryptionAlgorithmId; - pkcs5_prf = SelectedPrfAlgorithmId; - } - - // Only RIPEMD160 and SHA-256 are supported for boot loader - if (pkcs5_prf != RIPEMD160 && pkcs5_prf != SHA256) - throw ParameterIncorrect (SRC_POS); - - int bootSectorId = 0; - int bootLoaderId = 0; - - if (pkcs5_prf == SHA256) - { - bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_SHA2 : IDR_BOOT_SECTOR_SHA2; - bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_SHA2 : IDR_BOOT_LOADER_SHA2; - } - else - { - bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR : IDR_BOOT_SECTOR; - bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER : IDR_BOOT_LOADER; - } - - switch (ea) - { - case AES: - if (pkcs5_prf == SHA256) - { - bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_AES_SHA2 : IDR_BOOT_SECTOR_AES_SHA2; - bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_AES_SHA2 : IDR_BOOT_LOADER_AES_SHA2; - } - else - { - bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_AES : IDR_BOOT_SECTOR_AES; - bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_AES : IDR_BOOT_LOADER_AES; - } - break; - - case SERPENT: - if (pkcs5_prf == SHA256) - { - bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_SERPENT_SHA2 : IDR_BOOT_SECTOR_SERPENT_SHA2; - bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_SERPENT_SHA2 : IDR_BOOT_LOADER_SERPENT_SHA2; - } - else - { - bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_SERPENT : IDR_BOOT_SECTOR_SERPENT; - bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_SERPENT : IDR_BOOT_LOADER_SERPENT; - } - break; - - case TWOFISH: - if (pkcs5_prf == SHA256) - { - bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_TWOFISH_SHA2 : IDR_BOOT_SECTOR_TWOFISH_SHA2; - bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_TWOFISH_SHA2 : IDR_BOOT_LOADER_TWOFISH_SHA2; - } - else - { - bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_TWOFISH : IDR_BOOT_SECTOR_TWOFISH; - bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_TWOFISH : IDR_BOOT_LOADER_TWOFISH; - } - break; - } - - // Boot sector - DWORD size; - byte *bootSecResourceImg = MapResource (L"BIN", bootSectorId, &size); - if (!bootSecResourceImg || size != TC_SECTOR_SIZE_BIOS) - throw ParameterIncorrect (SRC_POS); - - memcpy (buffer, bootSecResourceImg, size); - - *(uint16 *) (buffer + TC_BOOT_SECTOR_VERSION_OFFSET) = BE16 (VERSION_NUM); - - if (IsOSAtLeast (WIN_VISTA)) - buffer[TC_BOOT_SECTOR_CONFIG_OFFSET] |= TC_BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER; - - if (rescueDisk && (ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION)) - buffer[TC_BOOT_SECTOR_CONFIG_OFFSET] |= TC_BOOT_CFG_FLAG_RESCUE_DISABLE_HW_ENCRYPTION; - - // Checksum of the backup header of the outer volume for the hidden system - if (hiddenOSCreation) - { - Device device (GetSystemDriveConfiguration().DevicePath); - device.CheckOpened (SRC_POS); - byte headerSector[TC_SECTOR_SIZE_BIOS]; - - device.SeekAt (HiddenOSCandidatePartition.Info.StartingOffset.QuadPart + HiddenOSCandidatePartition.Info.PartitionLength.QuadPart - TC_VOLUME_HEADER_GROUP_SIZE + TC_VOLUME_HEADER_EFFECTIVE_SIZE); - device.Read (headerSector, sizeof (headerSector)); - - *(uint32 *) (buffer + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET) = GetCrc32 (headerSector, sizeof (headerSector)); - } - - // Decompressor - byte *decompressor = MapResource (L"BIN", IDR_BOOT_LOADER_DECOMPRESSOR, &size); - if (!decompressor || size > TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS) - throw ParameterIncorrect (SRC_POS); - - memcpy (buffer + TC_SECTOR_SIZE_BIOS, decompressor, size); - - // Compressed boot loader - byte *bootLoader = MapResource (L"BIN", bootLoaderId, &size); - if (!bootLoader || size > TC_MAX_BOOT_LOADER_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS) - throw ParameterIncorrect (SRC_POS); - - memcpy (buffer + TC_SECTOR_SIZE_BIOS + TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS, bootLoader, size); - - // Boot loader and decompressor checksum - *(uint16 *) (buffer + TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET) = static_cast (size); - *(uint32 *) (buffer + TC_BOOT_SECTOR_LOADER_CHECKSUM_OFFSET) = GetChecksum (buffer + TC_SECTOR_SIZE_BIOS, - TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS + size); - - // Backup of decompressor and boot loader - if (size + TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS <= TC_BOOT_LOADER_BACKUP_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS) - { - memcpy (buffer + TC_SECTOR_SIZE_BIOS + TC_BOOT_LOADER_BACKUP_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS, - buffer + TC_SECTOR_SIZE_BIOS, TC_BOOT_LOADER_BACKUP_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS); - - buffer[TC_BOOT_SECTOR_CONFIG_OFFSET] |= TC_BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE; - } - else if (!rescueDisk && bootLoaderId != IDR_BOOT_LOADER && bootLoaderId != IDR_BOOT_LOADER_SHA2) - { - throw ParameterIncorrect (SRC_POS); - } - } - - - void BootEncryption::ReadBootSectorConfig (byte *config, size_t bufLength, byte *userConfig, string *customUserMessage, uint16 *bootLoaderVersion) - { - if (config && bufLength < TC_BOOT_CFG_FLAG_AREA_SIZE) - throw ParameterIncorrect (SRC_POS); - - GetSystemDriveConfigurationRequest request; - StringCchCopyW (request.DevicePath, ARRAYSIZE (request.DevicePath), GetSystemDriveConfiguration().DeviceKernelPath.c_str()); - - try - { - CallDriver (TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG, &request, sizeof (request), &request, sizeof (request)); - if (config) - *config = request.Configuration; - - if (userConfig) - *userConfig = request.UserConfiguration; - - if (customUserMessage) - { - request.CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH] = 0; - *customUserMessage = request.CustomUserMessage; - } - - if (bootLoaderVersion) - *bootLoaderVersion = request.BootLoaderVersion; - } - catch (...) - { - if (config) - *config = 0; - - if (userConfig) - *userConfig = 0; - - if (customUserMessage) - customUserMessage->clear(); - - if (bootLoaderVersion) - *bootLoaderVersion = 0; - } - } - - - void BootEncryption::WriteBootSectorConfig (const byte newConfig[]) - { - Device device (GetSystemDriveConfiguration().DevicePath); - device.CheckOpened (SRC_POS); - byte mbr[TC_SECTOR_SIZE_BIOS]; - - device.SeekAt (0); - device.Read (mbr, sizeof (mbr)); - - memcpy (mbr + TC_BOOT_SECTOR_CONFIG_OFFSET, newConfig, TC_BOOT_CFG_FLAG_AREA_SIZE); - - device.SeekAt (0); - device.Write (mbr, sizeof (mbr)); - - byte mbrVerificationBuf[TC_SECTOR_SIZE_BIOS]; - device.SeekAt (0); - device.Read (mbrVerificationBuf, sizeof (mbr)); - - if (memcmp (mbr, mbrVerificationBuf, sizeof (mbr)) != 0) - throw ErrorException ("ERROR_MBR_PROTECTED", SRC_POS); - } - - - void BootEncryption::WriteBootSectorUserConfig (byte userConfig, const string &customUserMessage, int pim) - { - Device device (GetSystemDriveConfiguration().DevicePath); - device.CheckOpened (SRC_POS); - byte mbr[TC_SECTOR_SIZE_BIOS]; - - device.SeekAt (0); - device.Read (mbr, sizeof (mbr)); - - if (!BufferContainsString (mbr, sizeof (mbr), TC_APP_NAME) - || BE16 (*(uint16 *) (mbr + TC_BOOT_SECTOR_VERSION_OFFSET)) != VERSION_NUM) - { - return; - } - - mbr[TC_BOOT_SECTOR_USER_CONFIG_OFFSET] = userConfig; - - memset (mbr + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, 0, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); - - if (!customUserMessage.empty()) - { - if (customUserMessage.size() > TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH) - throw ParameterIncorrect (SRC_POS); - - memcpy (mbr + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, customUserMessage.c_str(), customUserMessage.size()); - } - - if (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM) - { - // PIM for pre-boot authentication can be encoded on two bytes since its maximum - // value is 65535 (0xFFFF) - memcpy (mbr + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, &pim, TC_BOOT_SECTOR_PIM_VALUE_SIZE); - } - else - memset (mbr + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, 0, TC_BOOT_SECTOR_PIM_VALUE_SIZE); - - device.SeekAt (0); - device.Write (mbr, sizeof (mbr)); - - byte mbrVerificationBuf[TC_SECTOR_SIZE_BIOS]; - device.SeekAt (0); - device.Read (mbrVerificationBuf, sizeof (mbr)); - - if (memcmp (mbr, mbrVerificationBuf, sizeof (mbr)) != 0) - throw ErrorException ("ERROR_MBR_PROTECTED", SRC_POS); - } - - - unsigned int BootEncryption::GetHiddenOSCreationPhase () - { - byte configFlags [TC_BOOT_CFG_FLAG_AREA_SIZE]; - - ReadBootSectorConfig (configFlags, sizeof(configFlags)); - - return (configFlags[0] & TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE); - } - - - void BootEncryption::SetHiddenOSCreationPhase (unsigned int newPhase) - { -#if TC_BOOT_CFG_FLAG_AREA_SIZE != 1 -# error TC_BOOT_CFG_FLAG_AREA_SIZE != 1; revise GetHiddenOSCreationPhase() and SetHiddenOSCreationPhase() -#endif - byte configFlags [TC_BOOT_CFG_FLAG_AREA_SIZE]; - - ReadBootSectorConfig (configFlags, sizeof(configFlags)); - - configFlags[0] &= (byte) ~TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE; - - configFlags[0] |= newPhase; - - WriteBootSectorConfig (configFlags); - } - - -#ifndef SETUP - - void BootEncryption::StartDecoyOSWipe (WipeAlgorithmId wipeAlgorithm) - { - if (!IsHiddenOSRunning()) - throw ParameterIncorrect (SRC_POS); - - WipeDecoySystemRequest request; - ZeroMemory (&request, sizeof (request)); - - request.WipeAlgorithm = wipeAlgorithm; - - if (Randinit() != ERR_SUCCESS) - { - if (CryptoAPILastError == ERROR_SUCCESS) - throw RandInitFailed (SRC_POS, GetLastError ()); - else - throw CryptoApiFailed (SRC_POS, CryptoAPILastError); - } - - /* force the display of the random enriching dialog */ - SetRandomPoolEnrichedByUserStatus (FALSE); - - UserEnrichRandomPool (ParentWindow); - - if (!RandgetBytes (ParentWindow, request.WipeKey, sizeof (request.WipeKey), TRUE)) - throw ParameterIncorrect (SRC_POS); - - CallDriver (TC_IOCTL_START_DECOY_SYSTEM_WIPE, &request, sizeof (request), NULL, 0); - - burn (&request, sizeof (request)); - } - - - void BootEncryption::AbortDecoyOSWipe () - { - CallDriver (TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE); - } - - - DecoySystemWipeStatus BootEncryption::GetDecoyOSWipeStatus () - { - DecoySystemWipeStatus status; - CallDriver (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS, NULL, 0, &status, sizeof (status)); - return status; - } - - - void BootEncryption::CheckDecoyOSWipeResult () - { - CallDriver (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT); - } - - - void BootEncryption::WipeHiddenOSCreationConfig () - { - if (IsHiddenOSRunning()) - throw ParameterIncorrect (SRC_POS); - - if (Randinit() != ERR_SUCCESS) - { - if (CryptoAPILastError == ERROR_SUCCESS) - throw RandInitFailed (SRC_POS, GetLastError ()); - else - throw CryptoApiFailed (SRC_POS, CryptoAPILastError); - } - - Device device (GetSystemDriveConfiguration().DevicePath); - device.CheckOpened(SRC_POS); - byte mbr[TC_SECTOR_SIZE_BIOS]; - - device.SeekAt (0); - device.Read (mbr, sizeof (mbr)); - - finally_do_arg (BootEncryption *, this, - { - try - { - finally_arg->SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE); - } catch (...) { } - }); - -#if PRAND_DISK_WIPE_PASSES > RNG_POOL_SIZE -# error PRAND_DISK_WIPE_PASSES > RNG_POOL_SIZE -#endif - - byte randData[PRAND_DISK_WIPE_PASSES]; - if (!RandgetBytes (ParentWindow, randData, sizeof (randData), FALSE)) - throw ParameterIncorrect (SRC_POS); - - for (int wipePass = 0; wipePass < PRAND_DISK_WIPE_PASSES; wipePass++) - { - for (int i = 0; i < TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE; ++i) - { - mbr[TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET + i] = randData[wipePass]; - } - - mbr[TC_BOOT_SECTOR_CONFIG_OFFSET] &= (byte) ~TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE; - mbr[TC_BOOT_SECTOR_CONFIG_OFFSET] |= randData[wipePass] & TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE; - - if (wipePass == PRAND_DISK_WIPE_PASSES - 1) - memset (mbr + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET, 0, TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE); - - device.SeekAt (0); - device.Write (mbr, sizeof (mbr)); - } - - for (int wipePass = 0; wipePass < PRAND_DISK_WIPE_PASSES/4 + 1; wipePass++) - { - SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE); - SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_CLONING); - SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_WIPING); - SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_WIPED); - } - SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE); - } - -#endif // !SETUP - - - void BootEncryption::InstallBootLoader (bool preserveUserConfig, bool hiddenOSCreation) - { - Device device (GetSystemDriveConfiguration().DevicePath); - device.CheckOpened (SRC_POS); - - InstallBootLoader (device, preserveUserConfig, hiddenOSCreation); - } - - void BootEncryption::InstallBootLoader (Device& device, bool preserveUserConfig, bool hiddenOSCreation, int pim) - { - byte bootLoaderBuf[TC_BOOT_LOADER_AREA_SIZE - TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE] = {0}; - CreateBootLoaderInMemory (bootLoaderBuf, sizeof (bootLoaderBuf), false, hiddenOSCreation); - - // Write MBR - byte mbr[TC_SECTOR_SIZE_BIOS]; - - device.SeekAt (0); - device.Read (mbr, sizeof (mbr)); - - if (preserveUserConfig && BufferContainsString (mbr, sizeof (mbr), TC_APP_NAME)) - { - uint16 version = BE16 (*(uint16 *) (mbr + TC_BOOT_SECTOR_VERSION_OFFSET)); - if (version != 0) - { - bootLoaderBuf[TC_BOOT_SECTOR_USER_CONFIG_OFFSET] = mbr[TC_BOOT_SECTOR_USER_CONFIG_OFFSET]; - memcpy (bootLoaderBuf + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, mbr + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); - - if (bootLoaderBuf[TC_BOOT_SECTOR_USER_CONFIG_OFFSET] & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM) - { - if (pim >= 0) - { - memcpy (bootLoaderBuf + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, &pim, TC_BOOT_SECTOR_PIM_VALUE_SIZE); - } - else - memcpy (bootLoaderBuf + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, mbr + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, TC_BOOT_SECTOR_PIM_VALUE_SIZE); - } - } - } - - memcpy (mbr, bootLoaderBuf, TC_MAX_MBR_BOOT_CODE_SIZE); - - device.SeekAt (0); - device.Write (mbr, sizeof (mbr)); - - byte mbrVerificationBuf[TC_SECTOR_SIZE_BIOS]; - device.SeekAt (0); - device.Read (mbrVerificationBuf, sizeof (mbr)); - - if (memcmp (mbr, mbrVerificationBuf, sizeof (mbr)) != 0) - throw ErrorException ("ERROR_MBR_PROTECTED", SRC_POS); - - // Write boot loader - device.SeekAt (TC_SECTOR_SIZE_BIOS); - device.Write (bootLoaderBuf + TC_SECTOR_SIZE_BIOS, sizeof (bootLoaderBuf) - TC_SECTOR_SIZE_BIOS); - } - -#ifndef SETUP - bool BootEncryption::CheckBootloaderFingerprint (bool bSilent) - { - byte bootLoaderBuf[TC_BOOT_LOADER_AREA_SIZE - TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE] = {0}; - byte fingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE]; - byte expectedFingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE]; - bool bRet = false; - - try - { - // read bootloader fingerprint - GetInstalledBootLoaderFingerprint (fingerprint); - - // compute expected fingerprint - CreateBootLoaderInMemory (bootLoaderBuf, sizeof (bootLoaderBuf), false, false); - ::ComputeBootloaderFingerprint (bootLoaderBuf, sizeof (bootLoaderBuf), expectedFingerprint); - - // compare values - if (0 == memcmp (fingerprint, expectedFingerprint, sizeof (expectedFingerprint))) - { - bRet = true; - } - } - catch (SystemException &e) - { - if (!bSilent && (GetLastError () != ERROR_INVALID_IMAGE_HASH)) - e.Show (ParentWindow); - } - catch (Exception& e) - { - if (!bSilent) - e.Show (ParentWindow); - } - - return bRet; - } -#endif - - wstring BootEncryption::GetSystemLoaderBackupPath () - { - WCHAR pathBuf[MAX_PATH]; - - throw_sys_if (!SUCCEEDED (SHGetFolderPath (NULL, CSIDL_COMMON_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, pathBuf))); - - wstring path = wstring (pathBuf) + L"\\" _T(TC_APP_NAME); - CreateDirectory (path.c_str(), NULL); - - return path + L'\\' + TC_SYS_BOOT_LOADER_BACKUP_NAME; - } - - - void BootEncryption::RenameDeprecatedSystemLoaderBackup () - { - WCHAR pathBuf[MAX_PATH]; - - if (SUCCEEDED (SHGetFolderPath (NULL, CSIDL_COMMON_APPDATA, NULL, 0, pathBuf))) - { - wstring path = wstring (pathBuf) + L"\\" _T(TC_APP_NAME) + L'\\' + TC_SYS_BOOT_LOADER_BACKUP_NAME_LEGACY; - - if (FileExists (path.c_str()) && !FileExists (GetSystemLoaderBackupPath().c_str())) - throw_sys_if (_wrename (path.c_str(), GetSystemLoaderBackupPath().c_str()) != 0); - } - } - - -#ifndef SETUP - void BootEncryption::CreateRescueIsoImage (bool initialSetup, const wstring &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 - const char* szPrimVolDesc = "\001CD001\001"; - const char* szPrimVolLabel = "VeraCrypt Rescue Disk "; - memcpy (image + 0x8000, szPrimVolDesc, strlen(szPrimVolDesc) + 1); - memcpy (image + 0x7fff + 41, szPrimVolLabel, strlen(szPrimVolLabel) + 1); - *(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 - const char* szBootRecDesc = "CD001\001EL TORITO SPECIFICATION"; - memcpy (image + 0x8801, szBootRecDesc, strlen(szBootRecDesc) + 1); - image[0x8800 + 0x47] = 0x19; - - // Volume descriptor set terminator - const char* szVolDescTerm = "\377CD001\001"; - memcpy (image + 0x9000, szVolDescTerm, strlen(szVolDescTerm) + 1); - - // 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.CheckOpened (SRC_POS); - 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.CheckOpened (SRC_POS); - 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", ParentWindow); - } - - // 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::IsCDRecorderPresent () - { - ICDBurn* pICDBurn; - BOOL bHasRecorder = FALSE; - - if (SUCCEEDED( CoCreateInstance (CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) - { - if (pICDBurn->HasRecordableDrive (&bHasRecorder) != S_OK) - { - bHasRecorder = FALSE; - } - pICDBurn->Release(); - } - return bHasRecorder? true : false; - } - - - bool BootEncryption::VerifyRescueDisk () - { - if (!RescueIsoImage) - throw ParameterIncorrect (SRC_POS); - - for (WCHAR drive = L'Z'; drive >= L'C'; --drive) - { - try - { - WCHAR rootPath[4] = { drive, L':', L'\\', 0}; - UINT driveType = GetDriveType (rootPath); - // check that it is a CD/DVD drive or a removable media in case a bootable - // USB key was created from the rescue disk ISO file - if ((DRIVE_CDROM == driveType) || (DRIVE_REMOVABLE == driveType)) - { - rootPath[2] = 0; // remove trailing backslash - - Device driveDevice (rootPath, true); - driveDevice.CheckOpened (SRC_POS); - 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(), (DWORD) buffer.Size()); - if (bytesRead != buffer.Size()) - continue; - - if (memcmp (buffer.Ptr(), RescueIsoImage, buffer.Size()) == 0) - return true; - } - } - catch (...) { } - } - - return false; - } - - bool BootEncryption::VerifyRescueDiskIsoImage (const wchar_t* imageFile) - { - if (!RescueIsoImage) - throw ParameterIncorrect (SRC_POS); - - try - { - File isoFile (imageFile, true); - isoFile.CheckOpened (SRC_POS); - 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 = isoFile.Read (buffer.Ptr(), (DWORD) buffer.Size()); - if ( (bytesRead == buffer.Size()) - && (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, int pim) - { - PCRYPTO_INFO cryptoInfo = NULL; - - if (!IsRandomNumberGeneratorStarted()) - throw ParameterIncorrect (SRC_POS); - - throw_sys_if (CreateVolumeHeaderInMemory (ParentWindow, TRUE, (char *) VolumeHeader, ea, mode, password, pkcs5, pim, NULL, &cryptoInfo, - volumeSize, 0, encryptedAreaStart, 0, TC_SYSENC_KEYSCOPE_MIN_REQ_PROG_VERSION, TC_HEADER_FLAG_ENCRYPTED_SYSTEM, TC_SECTOR_SIZE_BIOS, 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)); - if (0 != ReadVolumeHeader (TRUE, (char *) RescueVolumeHeader, password, pkcs5, pim, FALSE, NULL, cryptoInfo)) - throw ParameterIncorrect (SRC_POS); - - DecryptBuffer (RescueVolumeHeader + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo); - - if (GetHeaderField32 (RescueVolumeHeader, TC_HEADER_OFFSET_MAGIC) != 0x56455241) - 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.CheckOpened (SRC_POS); - - 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); - device.CheckOpened (SRC_POS); - byte bootLoaderBuf[TC_BOOT_LOADER_AREA_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS]; - - 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", ParentWindow) == 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 * TC_SECTOR_SIZE_BIOS]; - - File backupFile (GetSystemLoaderBackupPath(), true); - backupFile.CheckOpened(SRC_POS); - if (backupFile.Read (bootLoaderBuf, sizeof (bootLoaderBuf)) != sizeof (bootLoaderBuf)) - throw ParameterIncorrect (SRC_POS); - - Device device (GetSystemDriveConfiguration().DevicePath); - device.CheckOpened (SRC_POS); - - // Preserve current partition table - byte mbr[TC_SECTOR_SIZE_BIOS]; - 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::RegisterFilter (bool registerFilter, FilterType filterType, const GUID *deviceClassGuid) - { - string filter; - string filterReg; - HKEY regKey; - - switch (filterType) - { - case DriveFilter: - case VolumeFilter: - filter = "veracrypt"; - filterReg = "UpperFilters"; - regKey = OpenDeviceClassRegKey (deviceClassGuid); - throw_sys_if (regKey == INVALID_HANDLE_VALUE); - - break; - - case DumpFilter: - if (!IsOSAtLeast (WIN_VISTA)) - return; - - filter = "veracrypt.sys"; - filterReg = "DumpFilters"; - SetLastError (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\CrashControl", 0, KEY_READ | KEY_WRITE, ®Key)); - throw_sys_if (GetLastError() != ERROR_SUCCESS); - - break; - - default: - throw ParameterIncorrect (SRC_POS); - } - - finally_do_arg (HKEY, regKey, { RegCloseKey (finally_arg); }); - - if (registerFilter && filterType != DumpFilter) - { - // Register class filter below all other filters in the stack - - size_t strSize = filter.size() + 1; - byte regKeyBuf[65536]; - DWORD size = (DWORD) (sizeof (regKeyBuf) - strSize); - - // SetupInstallFromInfSection() does not support prepending of values so we have to modify the registry directly - StringCchCopyA ((char *) regKeyBuf, ARRAYSIZE(regKeyBuf), filter.c_str()); - - if (RegQueryValueExA (regKey, filterReg.c_str(), NULL, NULL, regKeyBuf + strSize, &size) != ERROR_SUCCESS) - size = 1; - - SetLastError (RegSetValueExA (regKey, filterReg.c_str(), 0, REG_MULTI_SZ, regKeyBuf, (DWORD) strSize + size)); - throw_sys_if (GetLastError() != ERROR_SUCCESS); - } - else - { - RegisterDriverInf (registerFilter, filter, filterReg, ParentWindow, regKey); - } - } - - void BootEncryption::RegisterFilterDriver (bool registerDriver, FilterType filterType) - { - if (!IsAdmin() && IsUacSupported()) - { - Elevator::RegisterFilterDriver (registerDriver, filterType); - return; - } - - switch (filterType) - { - case DriveFilter: - RegisterFilter (registerDriver, filterType, &GUID_DEVCLASS_DISKDRIVE); - break; - - case VolumeFilter: - RegisterFilter (registerDriver, filterType, &GUID_DEVCLASS_VOLUME); - RegisterFilter (registerDriver, filterType, &GUID_DEVCLASS_FLOPPYDISK); - break; - - case DumpFilter: - RegisterFilter (registerDriver, filterType); - break; - - default: - throw ParameterIncorrect (SRC_POS); - } - } - - void BootEncryption::RegisterSystemFavoritesService (BOOL registerService, BOOL noFileHandling) - { - SC_HANDLE scm = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); - throw_sys_if (!scm); - finally_do_arg (SC_HANDLE, scm, { CloseServiceHandle (finally_arg); }); - - wstring servicePath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", false); - wstring serviceLegacyPath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", true); - - if (registerService) - { - try - { - RegisterSystemFavoritesService (FALSE, noFileHandling); - } - catch (...) { } - - if (!noFileHandling) - { - wchar_t appPath[TC_MAX_PATH]; - throw_sys_if (!GetModuleFileName (NULL, appPath, ARRAYSIZE (appPath))); - - throw_sys_if (!CopyFile (appPath, servicePath.c_str(), FALSE)); - } - - SC_HANDLE service = CreateService (scm, - TC_SYSTEM_FAVORITES_SERVICE_NAME, - _T(TC_APP_NAME) L" System Favorites", - SERVICE_ALL_ACCESS, - SERVICE_WIN32_OWN_PROCESS, - SERVICE_AUTO_START, - SERVICE_ERROR_NORMAL, - (wstring (L"\"") + servicePath + L"\" " TC_SYSTEM_FAVORITES_SERVICE_CMDLINE_OPTION).c_str(), - TC_SYSTEM_FAVORITES_SERVICE_LOAD_ORDER_GROUP, - NULL, - NULL, - NULL, - NULL); - - throw_sys_if (!service); - - SERVICE_DESCRIPTION description; - description.lpDescription = L"Mounts VeraCrypt system favorite volumes."; - ChangeServiceConfig2 (service, SERVICE_CONFIG_DESCRIPTION, &description); - - CloseServiceHandle (service); - - try - { - WriteLocalMachineRegistryString (L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Minimal\\" TC_SYSTEM_FAVORITES_SERVICE_NAME, NULL, L"Service", FALSE); - WriteLocalMachineRegistryString (L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Network\\" TC_SYSTEM_FAVORITES_SERVICE_NAME, NULL, L"Service", FALSE); - - SetDriverConfigurationFlag (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES, true); - } - catch (...) - { - try - { - RegisterSystemFavoritesService (FALSE, noFileHandling); - } - catch (...) { } - - throw; - } - } - else - { - SetDriverConfigurationFlag (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES, false); - - DeleteLocalMachineRegistryKey (L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Minimal", TC_SYSTEM_FAVORITES_SERVICE_NAME); - DeleteLocalMachineRegistryKey (L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Network", TC_SYSTEM_FAVORITES_SERVICE_NAME); - - SC_HANDLE service = OpenService (scm, TC_SYSTEM_FAVORITES_SERVICE_NAME, SERVICE_ALL_ACCESS); - throw_sys_if (!service); - - throw_sys_if (!DeleteService (service)); - CloseServiceHandle (service); - - if (!noFileHandling) - { - DeleteFile (servicePath.c_str()); - if (serviceLegacyPath != servicePath) - DeleteFile (serviceLegacyPath.c_str()); - } - } - } - - void BootEncryption::UpdateSystemFavoritesService () - { - SC_HANDLE scm = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); - throw_sys_if (!scm); - - finally_do_arg (SC_HANDLE, scm, { CloseServiceHandle (finally_arg); }); - - wstring servicePath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", false); - - // check if service exists - SC_HANDLE service = OpenService (scm, TC_SYSTEM_FAVORITES_SERVICE_NAME, SERVICE_ALL_ACCESS); - if (service) - { - finally_do_arg (SC_HANDLE, service, { CloseServiceHandle (finally_arg); }); - // ensure that its parameters are correct - throw_sys_if (!ChangeServiceConfig (service, - SERVICE_WIN32_OWN_PROCESS, - SERVICE_AUTO_START, - SERVICE_ERROR_NORMAL, - (wstring (L"\"") + servicePath + L"\" " TC_SYSTEM_FAVORITES_SERVICE_CMDLINE_OPTION).c_str(), - TC_SYSTEM_FAVORITES_SERVICE_LOAD_ORDER_GROUP, - NULL, - NULL, - NULL, - NULL, - _T(TC_APP_NAME) L" System Favorites")); - - } - else - { - RegisterSystemFavoritesService (TRUE, TRUE); - } - } - - void BootEncryption::SetDriverConfigurationFlag (uint32 flag, bool state) - { - DWORD configMap = ReadDriverConfigurationFlags(); - - if (state) - configMap |= flag; - else - configMap &= ~flag; -#ifdef SETUP - WriteLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_DRIVER_CONFIG_REG_VALUE_NAME, configMap); -#else - WriteLocalMachineRegistryDwordValue (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_DRIVER_CONFIG_REG_VALUE_NAME, configMap); -#endif - } - -#ifndef SETUP - - void BootEncryption::RegisterSystemFavoritesService (BOOL registerService) - { - if (!IsAdmin() && IsUacSupported()) - { - Elevator::RegisterSystemFavoritesService (registerService); - return; - } - - RegisterSystemFavoritesService (registerService, FALSE); - } - - void BootEncryption::CheckRequirements () - { - if (nCurrentOS == WIN_2000) - throw ErrorException ("SYS_ENCRYPTION_UNSUPPORTED_ON_CURRENT_OS", SRC_POS); - - if (CurrentOSMajor == 6 && CurrentOSMinor == 0 && CurrentOSServicePack < 1) - throw ErrorException ("SYS_ENCRYPTION_UNSUPPORTED_ON_VISTA_SP0", SRC_POS); - - if (IsNonInstallMode()) - throw ErrorException ("FEATURE_REQUIRES_INSTALLATION", SRC_POS); - - SystemDriveConfiguration config = GetSystemDriveConfiguration (); - - if (config.SystemPartition.IsGPT) - throw ErrorException ("GPT_BOOT_DRIVE_UNSUPPORTED", SRC_POS); - - if (SystemDriveIsDynamic()) - throw ErrorException ("SYSENC_UNSUPPORTED_FOR_DYNAMIC_DISK", SRC_POS); - - if (config.InitialUnallocatedSpace < TC_BOOT_LOADER_AREA_SIZE) - throw ErrorException ("NO_SPACE_FOR_BOOT_LOADER", SRC_POS); - - DISK_GEOMETRY geometry = GetDriveGeometry (config.DriveNumber); - - if (geometry.BytesPerSector != TC_SECTOR_SIZE_BIOS) - throw ErrorException ("SYSENC_UNSUPPORTED_SECTOR_SIZE_BIOS", SRC_POS); - - bool activePartitionFound = false; - if (!config.SystemPartition.IsGPT) - { - // Determine whether there is an Active partition on the system drive - foreach (const Partition &partition, config.Partitions) - { - if (partition.Info.BootIndicator) - { - activePartitionFound = true; - break; - } - } - } - - if (!config.SystemLoaderPresent || !activePartitionFound) - { - static bool confirmed = false; - - if (!confirmed && AskWarnNoYes ("WINDOWS_NOT_ON_BOOT_DRIVE_ERROR", ParentWindow) == IDNO) - throw UserAbort (SRC_POS); - - confirmed = true; - } - } - - - 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 () - { - wchar_t windowsDrive = (wchar_t) towupper (GetWindowsDirectory()[0]); - - // Paging files - bool pagingFilesOk = !IsPagingFileActive (TRUE); - - wchar_t pagingFileRegData[65536]; - DWORD pagingFileRegDataSize = sizeof (pagingFileRegData); - - if (ReadLocalMachineRegistryMultiString (L"System\\CurrentControlSet\\Control\\Session Manager\\Memory Management", L"PagingFiles", pagingFileRegData, &pagingFileRegDataSize) - && pagingFileRegDataSize > 8) - { - for (size_t i = 1; i < pagingFileRegDataSize/2 - 2; ++i) - { - if (wmemcmp (pagingFileRegData + i, L":\\", 2) == 0 && towupper (pagingFileRegData[i - 1]) != windowsDrive) - { - pagingFilesOk = false; - break; - } - } - } - - if (!pagingFilesOk) - { - if (AskWarnYesNoString ((wchar_t *) (wstring (GetString ("PAGING_FILE_NOT_ON_SYS_PARTITION")) - + GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION") - + L"\n\n\n" - + GetString ("RESTRICT_PAGING_FILES_TO_SYS_PARTITION") - ).c_str(), ParentWindow) == IDYES) - { - RestrictPagingFilesToSystemPartition(); - RestartComputer(); - AbortProcessSilent(); - } - - throw ErrorException (wstring (GetString ("PAGING_FILE_NOT_ON_SYS_PARTITION")) - + GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION"), SRC_POS); - } - - // User profile - wchar_t *configPath = GetConfigPath (L"dummy"); - if (configPath && towupper (configPath[0]) != windowsDrive) - { - throw ErrorException (wstring (GetString ("USER_PROFILE_NOT_ON_SYS_PARTITION")) - + GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION"), SRC_POS); - } - - // Temporary files - if (towupper (GetTempPathString()[0]) != windowsDrive) - { - throw ErrorException (wstring (GetString ("TEMP_NOT_ON_SYS_PARTITION")) - + GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION"), SRC_POS); - } - } - - - // This operation may take a long time when an antivirus is installed and its real-time protection enabled. - // Therefore, if calling it without the wizard displayed, it should be called with displayWaitDialog set to true. - void BootEncryption::Deinstall (bool displayWaitDialog) - { - BootEncryptionStatus encStatus = GetStatus(); - - if (encStatus.DriveEncrypted || encStatus.DriveMounted) - throw ParameterIncorrect (SRC_POS); - - SystemDriveConfiguration config = GetSystemDriveConfiguration (); - - if (encStatus.VolumeHeaderPresent) - { - // Verify CRC of header salt - Device device (config.DevicePath, true); - device.CheckOpened (SRC_POS); - byte header[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE]; - - device.SeekAt (TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET); - device.Read (header, sizeof (header)); - - if (encStatus.VolumeHeaderSaltCrc32 != GetCrc32 ((byte *) header, PKCS5_SALT_SIZE)) - throw ParameterIncorrect (SRC_POS); - } - - try - { - RegisterFilterDriver (false, DriveFilter); - RegisterFilterDriver (false, VolumeFilter); - RegisterFilterDriver (false, DumpFilter); - SetDriverServiceStartType (SERVICE_SYSTEM_START); - } - catch (...) - { - try - { - RegisterBootDriver (IsHiddenSystemRunning()); - } - catch (...) { } - - throw; - } - - SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE); // In case RestoreSystemLoader() fails - - try - { - RegisterSystemFavoritesService (false); - } - catch (...) { } - - try - { - if (displayWaitDialog) - DisplayStaticModelessWaitDlg (ParentWindow); - - finally_do_arg (bool, displayWaitDialog, { if (finally_arg) CloseStaticModelessWaitDlg(); }); - - RestoreSystemLoader (); - } - catch (Exception &e) - { - e.Show (ParentWindow); - throw ErrorException ("SYS_LOADER_RESTORE_FAILED", SRC_POS); - } - } - - - int BootEncryption::ChangePassword (Password *oldPassword, int old_pkcs5, int old_pim, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg) - { - BootEncryptionStatus encStatus = GetStatus(); - - if (encStatus.SetupInProgress || (wipePassCount <= 0)) - throw ParameterIncorrect (SRC_POS); - - SystemDriveConfiguration config = GetSystemDriveConfiguration (); - - char header[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE]; - Device device (config.DevicePath); - device.CheckOpened (SRC_POS); - - // Only one algorithm is currently supported - if (pkcs5 != 0) - throw ParameterIncorrect (SRC_POS); - - int64 headerOffset = TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET; - int64 backupHeaderOffset = -1; - - if (encStatus.HiddenSystem) - { - headerOffset = encStatus.HiddenSystemPartitionStart + TC_HIDDEN_VOLUME_HEADER_OFFSET; - - // Find hidden system partition - foreach (const Partition &partition, config.Partitions) - { - if (partition.Info.StartingOffset.QuadPart == encStatus.HiddenSystemPartitionStart) - { - backupHeaderOffset = partition.Info.StartingOffset.QuadPart + partition.Info.PartitionLength.QuadPart - TC_VOLUME_HEADER_SIZE; - break; - } - } - - if (backupHeaderOffset == -1) - throw ParameterIncorrect (SRC_POS); - } - - device.SeekAt (headerOffset); - device.Read ((byte *) header, sizeof (header)); - - PCRYPTO_INFO cryptoInfo = NULL; - - int status = ReadVolumeHeader (!encStatus.HiddenSystem, header, oldPassword, old_pkcs5, old_pim, FALSE, &cryptoInfo, NULL); - finally_do_arg (PCRYPTO_INFO, cryptoInfo, { if (finally_arg) crypto_close (finally_arg); }); - - if (status != 0) - { - handleError (hwndDlg, status, SRC_POS); - return status; - } - - // Change the PKCS-5 PRF if requested by user - if (pkcs5 != 0) - { - cryptoInfo->pkcs5 = pkcs5; - RandSetHashFunction (pkcs5); - } - - if (Randinit() != 0) - { - if (CryptoAPILastError == ERROR_SUCCESS) - throw RandInitFailed (SRC_POS, GetLastError ()); - else - throw CryptoApiFailed (SRC_POS, CryptoAPILastError); - } - finally_do ({ RandStop (FALSE); }); - - /* force the display of the random enriching dialog */ - SetRandomPoolEnrichedByUserStatus (FALSE); - - NormalCursor(); - UserEnrichRandomPool (hwndDlg); - WaitCursor(); - - /* The header will be re-encrypted wipePassCount times to prevent adversaries from using - techniques such as magnetic force microscopy or magnetic force scanning tunnelling microscopy - to recover the overwritten header. According to Peter Gutmann, data should be overwritten 22 - times (ideally, 35 times) using non-random patterns and pseudorandom data. However, as users might - impatiently interupt the process (etc.) we will not use the Gutmann's patterns but will write the - valid re-encrypted header, i.e. pseudorandom data, and there will be many more passes than Guttman - recommends. During each pass we will write a valid working header. Each pass will use the same master - key, and also the same header key, secondary key (XTS), etc., derived from the new password. The only - item that will be different for each pass will be the salt. This is sufficient to cause each "version" - of the header to differ substantially and in a random manner from the versions written during the - other passes. */ - - bool headerUpdated = false; - int result = ERR_SUCCESS; - - try - { - BOOL backupHeader = FALSE; - while (TRUE) - { - for (int wipePass = 0; wipePass < wipePassCount; wipePass++) - { - PCRYPTO_INFO tmpCryptoInfo = NULL; - - status = CreateVolumeHeaderInMemory (hwndDlg, !encStatus.HiddenSystem, - header, - cryptoInfo->ea, - cryptoInfo->mode, - newPassword, - cryptoInfo->pkcs5, - pim, - (char *) cryptoInfo->master_keydata, - &tmpCryptoInfo, - cryptoInfo->VolumeSize.Value, - cryptoInfo->hiddenVolumeSize, - cryptoInfo->EncryptedAreaStart.Value, - cryptoInfo->EncryptedAreaLength.Value, - cryptoInfo->RequiredProgramVersion, - cryptoInfo->HeaderFlags | TC_HEADER_FLAG_ENCRYPTED_SYSTEM, - cryptoInfo->SectorSize, - wipePass < wipePassCount - 1); - - if (tmpCryptoInfo) - crypto_close (tmpCryptoInfo); - - if (status != 0) - { - handleError (hwndDlg, status, SRC_POS); - return status; - } - - device.SeekAt (headerOffset); - device.Write ((byte *) header, sizeof (header)); - headerUpdated = true; - } - - if (!encStatus.HiddenSystem || backupHeader) - break; - - backupHeader = TRUE; - headerOffset = backupHeaderOffset; - } - } - catch (Exception &e) - { - e.Show (hwndDlg); - result = ERR_OS_ERROR; - } - - if (headerUpdated) - { - bool storedPimUpdateNeeded = false; - ReopenBootVolumeHeaderRequest reopenRequest; - reopenRequest.VolumePassword = *newPassword; - reopenRequest.pkcs5_prf = cryptoInfo->pkcs5; - reopenRequest.pim = pim; - finally_do_arg (ReopenBootVolumeHeaderRequest*, &reopenRequest, { burn (finally_arg, sizeof (*finally_arg)); }); - - if (old_pim != pim) - { - try - { - // check if PIM is stored in MBR - byte userConfig; - ReadBootSectorConfig (nullptr, 0, &userConfig); - if (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM) - storedPimUpdateNeeded = true; - } - catch (...) - {} - } - - try - { - // force update of bootloader if fingerprint doesn't match or if the stored PIM changed - if (storedPimUpdateNeeded || !CheckBootloaderFingerprint (true)) - InstallBootLoader (device, true, false, pim); - } - catch (...) - {} - - CallDriver (TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER, &reopenRequest, sizeof (reopenRequest)); - } - - return result; - } - - - void BootEncryption::CheckEncryptionSetupResult () - { - CallDriver (TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT); - } - - - void BootEncryption::Install (bool hiddenSystem) - { - BootEncryptionStatus encStatus = GetStatus(); - if (encStatus.DriveMounted) - throw ParameterIncorrect (SRC_POS); - - try - { - InstallBootLoader (false, hiddenSystem); - - if (!hiddenSystem) - InstallVolumeHeader (); - - RegisterBootDriver (hiddenSystem); - } - catch (Exception &) - { - try - { - RestoreSystemLoader (); - } - catch (Exception &e) - { - e.Show (ParentWindow); - } - - throw; - } - } - - - void BootEncryption::PrepareHiddenOSCreation (int ea, int mode, int pkcs5) - { - BootEncryptionStatus encStatus = GetStatus(); - if (encStatus.DriveMounted) - throw ParameterIncorrect (SRC_POS); - - CheckRequirements(); - BackupSystemLoader(); - - SelectedEncryptionAlgorithmId = ea; - SelectedPrfAlgorithmId = pkcs5; - } - - - void BootEncryption::PrepareInstallation (bool systemPartitionOnly, Password &password, int ea, int mode, int pkcs5, int pim, const wstring &rescueIsoImagePath) - { - BootEncryptionStatus encStatus = GetStatus(); - if (encStatus.DriveMounted) - throw ParameterIncorrect (SRC_POS); - - CheckRequirements (); - - SystemDriveConfiguration config = GetSystemDriveConfiguration(); - - // Some chipset drivers may prevent access to the last sector of the drive - if (!systemPartitionOnly) - { - DISK_GEOMETRY geometry = GetDriveGeometry (config.DriveNumber); - if ((geometry.BytesPerSector > 0) && (geometry.BytesPerSector < TC_MAX_VOLUME_SECTOR_SIZE)) - { - Buffer sector (geometry.BytesPerSector); - - Device device (config.DevicePath); - device.CheckOpened (SRC_POS); - - try - { - device.SeekAt (config.DrivePartition.Info.PartitionLength.QuadPart - geometry.BytesPerSector); - device.Read (sector.Ptr(), (DWORD) sector.Size()); - } - catch (SystemException &e) - { - if (e.ErrorCode != ERROR_CRC) - { - e.Show (ParentWindow); - Error ("WHOLE_DRIVE_ENCRYPTION_PREVENTED_BY_DRIVERS", ParentWindow); - throw UserAbort (SRC_POS); - } - } - } - } - - BackupSystemLoader (); - - uint64 volumeSize; - uint64 encryptedAreaStart; - - if (systemPartitionOnly) - { - volumeSize = config.SystemPartition.Info.PartitionLength.QuadPart; - encryptedAreaStart = config.SystemPartition.Info.StartingOffset.QuadPart; - } - else - { - volumeSize = config.DrivePartition.Info.PartitionLength.QuadPart - TC_BOOT_LOADER_AREA_SIZE; - encryptedAreaStart = config.DrivePartition.Info.StartingOffset.QuadPart + TC_BOOT_LOADER_AREA_SIZE; - } - - SelectedEncryptionAlgorithmId = ea; - SelectedPrfAlgorithmId = pkcs5; - CreateVolumeHeader (volumeSize, encryptedAreaStart, &password, ea, mode, pkcs5, pim); - - if (!rescueIsoImagePath.empty()) - CreateRescueIsoImage (true, rescueIsoImagePath); - } - - bool BootEncryption::IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) - { - if (!IsAdmin() && IsUacSupported()) - return Elevator::IsPagingFileActive (checkNonWindowsPartitionsOnly) ? true : false; - - return ::IsPagingFileActive (checkNonWindowsPartitionsOnly) ? true : false; - } - - void BootEncryption::RestrictPagingFilesToSystemPartition () - { - wchar_t pagingFiles[128] = {0}; - StringCchCopyW (pagingFiles, ARRAYSIZE(pagingFiles), L"X:\\pagefile.sys 0 0"); - pagingFiles[0] = GetWindowsDirectory()[0]; - - throw_sys_if (!WriteLocalMachineRegistryMultiString (L"System\\CurrentControlSet\\Control\\Session Manager\\Memory Management", L"PagingFiles", pagingFiles, (DWORD) (wcslen (pagingFiles) + 2) * sizeof (wchar_t))); - } - - void BootEncryption::WriteLocalMachineRegistryDwordValue (wchar_t *keyPath, wchar_t *valueName, DWORD value) - { - if (!IsAdmin() && IsUacSupported()) - { - Elevator::WriteLocalMachineRegistryDwordValue (keyPath, valueName, value); - return; - } - - throw_sys_if (!WriteLocalMachineRegistryDword (keyPath, valueName, value)); - } - - void BootEncryption::StartDecryption (BOOL discardUnreadableEncryptedSectors) - { - BootEncryptionStatus encStatus = GetStatus(); - - if (!encStatus.DeviceFilterActive || !encStatus.DriveMounted || encStatus.SetupInProgress) - throw ParameterIncorrect (SRC_POS); - - BootEncryptionSetupRequest request; - ZeroMemory (&request, sizeof (request)); - - request.SetupMode = SetupDecryption; - request.DiscardUnreadableEncryptedSectors = discardUnreadableEncryptedSectors; - - CallDriver (TC_IOCTL_BOOT_ENCRYPTION_SETUP, &request, sizeof (request), NULL, 0); - } - - void BootEncryption::StartEncryption (WipeAlgorithmId wipeAlgorithm, bool zeroUnreadableSectors) - { - BootEncryptionStatus encStatus = GetStatus(); - - if (!encStatus.DeviceFilterActive || !encStatus.DriveMounted || encStatus.SetupInProgress) - throw ParameterIncorrect (SRC_POS); - - BootEncryptionSetupRequest request; - ZeroMemory (&request, sizeof (request)); - - request.SetupMode = SetupEncryption; - request.WipeAlgorithm = wipeAlgorithm; - request.ZeroUnreadableSectors = zeroUnreadableSectors; - - CallDriver (TC_IOCTL_BOOT_ENCRYPTION_SETUP, &request, sizeof (request), NULL, 0); - } - - void BootEncryption::CopyFileAdmin (const wstring &sourceFile, const wstring &destinationFile) - { - if (!IsAdmin()) - { - if (!IsUacSupported()) - { - SetLastError (ERROR_ACCESS_DENIED); - throw SystemException(SRC_POS); - } - else - Elevator::CopyFile (sourceFile, destinationFile); - } - else - throw_sys_if (!::CopyFile (sourceFile.c_str(), destinationFile.c_str(), FALSE)); - } - - void BootEncryption::DeleteFileAdmin (const wstring &file) - { - if (!IsAdmin() && IsUacSupported()) - Elevator::DeleteFile (file); - else - throw_sys_if (!::DeleteFile (file.c_str())); - } - -#endif // !SETUP - - uint32 BootEncryption::ReadDriverConfigurationFlags () - { - DWORD configMap; - - if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_DRIVER_CONFIG_REG_VALUE_NAME, &configMap)) - configMap = 0; - - return configMap; - } - - void BootEncryption::WriteBootDriveSector (uint64 offset, byte *data) - { - WriteBootDriveSectorRequest request; - request.Offset.QuadPart = offset; - memcpy (request.Data, data, sizeof (request.Data)); - - CallDriver (TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR, &request, sizeof (request), NULL, 0); - } - - void BootEncryption::RegisterBootDriver (bool hiddenSystem) - { - SetDriverServiceStartType (SERVICE_BOOT_START); - - try - { - RegisterFilterDriver (false, DriveFilter); - RegisterFilterDriver (false, VolumeFilter); - RegisterFilterDriver (false, DumpFilter); - } - catch (...) { } - - try - { - RegisterFilterDriver (true, DriveFilter); - - if (hiddenSystem) - RegisterFilterDriver (true, VolumeFilter); - - RegisterFilterDriver (true, DumpFilter); - } - catch (...) - { - try { RegisterFilterDriver (false, DriveFilter); } catch (...) { } - try { RegisterFilterDriver (false, VolumeFilter); } catch (...) { } - try { RegisterFilterDriver (false, DumpFilter); } catch (...) { } - try { SetDriverServiceStartType (SERVICE_SYSTEM_START); } catch (...) { } - - throw; - } - } - - bool BootEncryption::RestartComputer (void) - { - return (::RestartComputer() != FALSE); - } -} +/* + 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 "Tcdefs.h" +#include "Platform/Finally.h" +#include "Platform/ForEach.h" +#include +#include +#include +#include +#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 + +#include + +namespace VeraCrypt +{ +#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(SRC_POS); + } + } + + static void CopyFile (const wstring &sourceFile, const wstring &destinationFile) + { + Elevate(); + DWORD result; + CComBSTR sourceFileBstr, destinationFileBstr; + BSTR bstr = W2BSTR(sourceFile.c_str()); + if (bstr) + { + sourceFileBstr.Attach (bstr); + + bstr = W2BSTR(destinationFile.c_str()); + if (bstr) + { + destinationFileBstr.Attach (bstr); + result = ElevatedComInstance->CopyFile (sourceFileBstr, destinationFileBstr); + } + else + { + result = ERROR_OUTOFMEMORY; + } + } + else + { + result = ERROR_OUTOFMEMORY; + } + + if (result != ERROR_SUCCESS) + { + SetLastError (result); + throw SystemException(SRC_POS); + } + } + + static void DeleteFile (const wstring &file) + { + Elevate(); + CComBSTR fileBstr; + DWORD result; + BSTR bstr = W2BSTR(file.c_str()); + if (bstr) + { + fileBstr.Attach (bstr); + result = ElevatedComInstance->DeleteFile (fileBstr); + } + else + { + result = ERROR_OUTOFMEMORY; + } + + if (result != ERROR_SUCCESS) + { + SetLastError (result); + throw SystemException(SRC_POS); + } + } + + static void ReadWriteFile (BOOL write, BOOL device, const wstring &filePath, byte *buffer, uint64 offset, uint32 size, DWORD *sizeDone) + { + Elevate(); + + DWORD result; + CComBSTR bufferBstr, fileBstr; + if (bufferBstr.AppendBytes ((const char *) buffer, size) != S_OK) + throw ParameterIncorrect (SRC_POS); + BSTR bstr = W2BSTR(filePath.c_str()); + if (bstr) + { + fileBstr.Attach (bstr); + result = ElevatedComInstance->ReadWriteFile (write, device, fileBstr, &bufferBstr, offset, size, sizeDone); + } + else + { + result = ERROR_OUTOFMEMORY; + } + + if (result != ERROR_SUCCESS) + { + SetLastError (result); + throw SystemException(SRC_POS); + } + + if (!write) + memcpy (buffer, (BYTE *) bufferBstr.m_str, size); + } + + static BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) + { + Elevate(); + + return ElevatedComInstance->IsPagingFileActive (checkNonWindowsPartitionsOnly); + } + + static void WriteLocalMachineRegistryDwordValue (wchar_t *keyPath, wchar_t *valueName, DWORD value) + { + Elevate(); + DWORD result; + CComBSTR keyPathBstr, valueNameBstr; + BSTR bstr = W2BSTR(keyPath); + if (bstr) + { + keyPathBstr.Attach (bstr); + + bstr = W2BSTR(valueName); + if (bstr) + { + valueNameBstr.Attach (bstr); + + result = ElevatedComInstance->WriteLocalMachineRegistryDwordValue (keyPathBstr, valueNameBstr, value); + } + else + { + result = ERROR_OUTOFMEMORY; + } + } + else + { + result = ERROR_OUTOFMEMORY; + } + + if (result != ERROR_SUCCESS) + { + SetLastError (result); + throw SystemException(SRC_POS); + } + } + + 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(SRC_POS); + } + } + + static void RegisterSystemFavoritesService (BOOL registerService) + { + Elevate(); + + DWORD result = ElevatedComInstance->RegisterSystemFavoritesService (registerService); + if (result != ERROR_SUCCESS) + { + SetLastError (result); + throw SystemException(SRC_POS); + } + } + + 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(SRC_POS); + } + } + + protected: + static void Elevate () + { + if (IsAdmin()) + { + SetLastError (ERROR_ACCESS_DENIED); + throw SystemException(SRC_POS); + } + + 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 wstring &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 (wstring path, bool readOnly, bool create) : Elevated (false), FileOpen (false), LastError(0) + { + 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); + + if (Handle != INVALID_HANDLE_VALUE) + { + FileOpen = true; + } + else + { + LastError = GetLastError(); + if (LastError == ERROR_ACCESS_DENIED && IsUacSupported()) + { + Elevated = true; + FileOpen = true; + } + } + + FilePointerPosition = 0; + IsDevice = false; + Path = path; + } + + void File::Close () + { + if (Handle != INVALID_HANDLE_VALUE) + { + CloseHandle (Handle); + Handle = INVALID_HANDLE_VALUE; + } + + FileOpen = false; + } + + DWORD File::Read (byte *buffer, DWORD size) + { + DWORD bytesRead; + + if (!FileOpen) + { + SetLastError (LastError); + throw SystemException (SRC_POS); + } + + 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) + { + if (!FileOpen) + { + SetLastError (LastError); + throw SystemException (SRC_POS); + } + + 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; + + if (!FileOpen) + { + SetLastError (LastError); + throw SystemException (SRC_POS); + } + + 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 wstring &str) + { + MessageBox (parent, str.c_str(), NULL, 0); + } + + + Device::Device (wstring path, bool readOnly) + { + FileOpen = false; + Elevated = false; + + Handle = CreateFile ((wstring (L"\\\\.\\") + 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); + + if (Handle != INVALID_HANDLE_VALUE) + { + FileOpen = true; + } + else + { + LastError = GetLastError (); + if (LastError == ERROR_ACCESS_DENIED && IsUacSupported()) + { + Elevated = true; + FileOpen = true; + } + } + + FilePointerPosition = 0; + IsDevice = true; + Path = path; + } + + + BootEncryption::BootEncryption (HWND parent) + : DriveConfigValid (false), + ParentWindow (parent), + RealSystemDriveSizeValid (false), + RescueIsoImage (nullptr), + RescueVolumeHeaderValid (false), + SelectedEncryptionAlgorithmId (0), + SelectedPrfAlgorithmId (0), + VolumeHeaderValid (false) + { + HiddenOSCandidatePartition.IsGPT = FALSE; + HiddenOSCandidatePartition.Number = (size_t) -1; + DriveConfig.DriveNumber = -1; + DriveConfig.ExtraBootPartitionPresent = false; + DriveConfig.SystemLoaderPresent = false; + DriveConfig.InitialUnallocatedSpace = 0; + DriveConfig.TotalUnallocatedSpace = 0; + 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(), SRC_POS); + } + + 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(), SRC_POS); + } + + 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(), SRC_POS); + } + } + 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(), SRC_POS); + } + } + else + { + // No active partition on the system drive + throw ErrorException ("SYSTEM_PARTITION_NOT_ACTIVE", SRC_POS); + } + + HiddenOSCandidatePartition = candidatePartition; + return candidatePartition; + } + + + DWORD BootEncryption::GetDriverServiceStartType () + { + DWORD startType; + throw_sys_if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", L"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, L"veracrypt", 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. + wstring driverPath; + if (startOnBoot && !IsOSAtLeast (WIN_VISTA)) + { + wchar_t pathBuf[MAX_PATH]; + wchar_t filesystem[128]; + + wstring path (GetWindowsDirectory()); + path += L"\\drivers\\veracrypt.sys"; + + if (GetVolumePathName (path.c_str(), pathBuf, ARRAYSIZE (pathBuf)) + && GetVolumeInformation (pathBuf, NULL, 0, NULL, NULL, NULL, filesystem, ARRAYSIZE(filesystem)) + && wmemcmp (filesystem, L"FAT", 3) == 0) + { + throw_sys_if (GetShortPathName (path.c_str(), pathBuf, ARRAYSIZE (pathBuf)) == 0); + + // Convert absolute path to relative to the Windows directory + driverPath = pathBuf; + driverPath = driverPath.substr (driverPath.rfind (L"\\", driverPath.rfind (L"\\", driverPath.rfind (L"\\") - 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 ? L"Filter" : NULL, + NULL, NULL, NULL, NULL, NULL)); + + // ChangeServiceConfig() rejects SERVICE_BOOT_START with ERROR_INVALID_PARAMETER + throw_sys_if (!WriteLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", L"Start", startType)); + } + + + void BootEncryption::ProbeRealSystemDriveSize () + { + if (RealSystemDriveSizeValid) + return; + + GetSystemDriveConfiguration(); + + ProbeRealDriveSizeRequest request; + StringCchCopyW (request.DeviceName, ARRAYSIZE (request.DeviceName), 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) + { + wstringstream partPath; + partPath << L"\\Device\\Harddisk" << driveNumber << L"\\Partition" << partNumber; + + DISK_PARTITION_INFO_STRUCT diskPartInfo = {0}; + StringCchCopyW (diskPartInfo.deviceName, ARRAYSIZE (diskPartInfo.deviceName), partPath.str().c_str()); + + try + { + CallDriver (TC_IOCTL_GET_DRIVE_PARTITION_INFO, &diskPartInfo, sizeof (diskPartInfo), &diskPartInfo, sizeof (diskPartInfo)); + } + catch (...) + { + continue; + } + + if ( (diskPartInfo.IsGPT == TRUE || diskPartInfo.IsGPT == FALSE) + && (diskPartInfo.IsDynamic == TRUE || diskPartInfo.IsDynamic == FALSE) + && (diskPartInfo.partInfo.BootIndicator == TRUE || diskPartInfo.partInfo.BootIndicator == FALSE) + && (diskPartInfo.partInfo.RecognizedPartition == TRUE || diskPartInfo.partInfo.RecognizedPartition == FALSE) + && (diskPartInfo.partInfo.RewritePartition == TRUE || diskPartInfo.partInfo.RewritePartition == FALSE) + && (diskPartInfo.partInfo.StartingOffset.QuadPart >= 0) + && (diskPartInfo.partInfo.PartitionLength.QuadPart >= 0) + ) + { + Partition part; + part.DevicePath = partPath.str(); + part.Number = partNumber; + part.Info = diskPartInfo.partInfo; + part.IsGPT = diskPartInfo.IsGPT; + + // Mount point + int driveNumber = GetDiskDeviceDriveLetter ((wchar_t *) partPath.str().c_str()); + + if (driveNumber >= 0) + { + part.MountPoint += (wchar_t) (driveNumber + L'A'); + part.MountPoint += L":"; + } + + // Volume ID + wchar_t volumePath[TC_MAX_PATH]; + if (ResolveSymbolicLink ((wchar_t *) partPath.str().c_str(), volumePath, sizeof(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) + { + wstringstream devName; + devName << L"\\Device\\Harddisk" << driveNumber << L"\\Partition0"; + + DISK_GEOMETRY geometry; + throw_sys_if (!::GetDriveGeometry (devName.str().c_str(), &geometry)); + return geometry; + } + + + wstring BootEncryption::GetWindowsDirectory () + { + wchar_t buf[MAX_PATH]; + throw_sys_if (GetSystemDirectory (buf, ARRAYSIZE (buf)) == 0); + + return wstring (buf); + } + + + + uint16 BootEncryption::GetInstalledBootLoaderVersion () + { + uint16 version; + CallDriver (TC_IOCTL_GET_BOOT_LOADER_VERSION, NULL, 0, &version, sizeof (version)); + return version; + } + + void BootEncryption::GetInstalledBootLoaderFingerprint (byte fingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE]) + { + BootLoaderFingerprintRequest request; + CallDriver (VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT, NULL, 0, &request, sizeof (request)); + memcpy (fingerprint, request.Fingerprint, sizeof (request.Fingerprint)); + } + + // Note that this does not require admin rights (it just requires the driver to be running) + bool BootEncryption::IsBootLoaderOnDrive (wchar_t *devicePath) + { + try + { + OPEN_TEST_STRUCT openTestStruct; + memset (&openTestStruct, 0, sizeof (openTestStruct)); + DWORD dwResult; + + StringCchCopyW (&openTestStruct.wszFileName[0], ARRAYSIZE(openTestStruct.wszFileName),devicePath); + + 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); + device.CheckOpened (SRC_POS); + + byte mbrBuf[TC_SECTOR_SIZE_BIOS]; + device.SeekAt (0); + device.Read (mbrBuf, sizeof (mbrBuf)); + + MBR *mbr = reinterpret_cast (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; + StringCchCopyW (request.DevicePath, ARRAYSIZE (request.DevicePath), 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; + + wstring 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() + && (_waccess ((part.MountPoint + L"\\bootmgr").c_str(), 0) == 0 || _waccess ((part.MountPoint + L"\\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; + + wstringstream ss; + ss << L"PhysicalDrive" << driveNumber; + config.DevicePath = ss.str(); + + wstringstream kernelPath; + kernelPath << L"\\Device\\Harddisk" << driveNumber << L"\\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; + int pkcs5_prf = 0; + if (GetStatus().DriveMounted) + { + try + { + GetBootEncryptionAlgorithmNameRequest request; + // since we added new field to GetBootEncryptionAlgorithmNameRequest since version 1.0f + // we zero all the structure so that if we are talking to an older driver, the field + // BootPrfAlgorithmName will be an empty string + ZeroMemory(&request, sizeof(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; + + if (_stricmp(request.BootPrfAlgorithmName, "SHA-256") == 0) + pkcs5_prf = SHA256; + else if (_stricmp(request.BootPrfAlgorithmName, "RIPEMD-160") == 0) + pkcs5_prf = RIPEMD160; + else if (strlen(request.BootPrfAlgorithmName) == 0) // case of version < 1.0f + pkcs5_prf = RIPEMD160; + } + catch (...) + { + try + { + VOLUME_PROPERTIES_STRUCT properties; + GetVolumeProperties (&properties); + ea = properties.ea; + pkcs5_prf = properties.pkcs5; + } + catch (...) { } + } + } + else + { + if (SelectedEncryptionAlgorithmId == 0 || SelectedPrfAlgorithmId == 0) + throw ParameterIncorrect (SRC_POS); + + ea = SelectedEncryptionAlgorithmId; + pkcs5_prf = SelectedPrfAlgorithmId; + } + + // Only RIPEMD160 and SHA-256 are supported for boot loader + if (pkcs5_prf != RIPEMD160 && pkcs5_prf != SHA256) + throw ParameterIncorrect (SRC_POS); + + int bootSectorId = 0; + int bootLoaderId = 0; + + if (pkcs5_prf == SHA256) + { + bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_SHA2 : IDR_BOOT_SECTOR_SHA2; + bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_SHA2 : IDR_BOOT_LOADER_SHA2; + } + else + { + bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR : IDR_BOOT_SECTOR; + bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER : IDR_BOOT_LOADER; + } + + switch (ea) + { + case AES: + if (pkcs5_prf == SHA256) + { + bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_AES_SHA2 : IDR_BOOT_SECTOR_AES_SHA2; + bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_AES_SHA2 : IDR_BOOT_LOADER_AES_SHA2; + } + else + { + bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_AES : IDR_BOOT_SECTOR_AES; + bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_AES : IDR_BOOT_LOADER_AES; + } + break; + + case SERPENT: + if (pkcs5_prf == SHA256) + { + bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_SERPENT_SHA2 : IDR_BOOT_SECTOR_SERPENT_SHA2; + bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_SERPENT_SHA2 : IDR_BOOT_LOADER_SERPENT_SHA2; + } + else + { + bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_SERPENT : IDR_BOOT_SECTOR_SERPENT; + bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_SERPENT : IDR_BOOT_LOADER_SERPENT; + } + break; + + case TWOFISH: + if (pkcs5_prf == SHA256) + { + bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_TWOFISH_SHA2 : IDR_BOOT_SECTOR_TWOFISH_SHA2; + bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_TWOFISH_SHA2 : IDR_BOOT_LOADER_TWOFISH_SHA2; + } + else + { + bootSectorId = rescueDisk ? IDR_RESCUE_BOOT_SECTOR_TWOFISH : IDR_BOOT_SECTOR_TWOFISH; + bootLoaderId = rescueDisk ? IDR_RESCUE_LOADER_TWOFISH : IDR_BOOT_LOADER_TWOFISH; + } + break; + } + + // Boot sector + DWORD size; + byte *bootSecResourceImg = MapResource (L"BIN", bootSectorId, &size); + if (!bootSecResourceImg || size != TC_SECTOR_SIZE_BIOS) + throw ParameterIncorrect (SRC_POS); + + memcpy (buffer, bootSecResourceImg, size); + + *(uint16 *) (buffer + TC_BOOT_SECTOR_VERSION_OFFSET) = BE16 (VERSION_NUM); + + if (IsOSAtLeast (WIN_VISTA)) + buffer[TC_BOOT_SECTOR_CONFIG_OFFSET] |= TC_BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER; + + if (rescueDisk && (ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION)) + buffer[TC_BOOT_SECTOR_CONFIG_OFFSET] |= TC_BOOT_CFG_FLAG_RESCUE_DISABLE_HW_ENCRYPTION; + + // Checksum of the backup header of the outer volume for the hidden system + if (hiddenOSCreation) + { + Device device (GetSystemDriveConfiguration().DevicePath); + device.CheckOpened (SRC_POS); + byte headerSector[TC_SECTOR_SIZE_BIOS]; + + device.SeekAt (HiddenOSCandidatePartition.Info.StartingOffset.QuadPart + HiddenOSCandidatePartition.Info.PartitionLength.QuadPart - TC_VOLUME_HEADER_GROUP_SIZE + TC_VOLUME_HEADER_EFFECTIVE_SIZE); + device.Read (headerSector, sizeof (headerSector)); + + *(uint32 *) (buffer + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET) = GetCrc32 (headerSector, sizeof (headerSector)); + } + + // Decompressor + byte *decompressor = MapResource (L"BIN", IDR_BOOT_LOADER_DECOMPRESSOR, &size); + if (!decompressor || size > TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS) + throw ParameterIncorrect (SRC_POS); + + memcpy (buffer + TC_SECTOR_SIZE_BIOS, decompressor, size); + + // Compressed boot loader + byte *bootLoader = MapResource (L"BIN", bootLoaderId, &size); + if (!bootLoader || size > TC_MAX_BOOT_LOADER_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS) + throw ParameterIncorrect (SRC_POS); + + memcpy (buffer + TC_SECTOR_SIZE_BIOS + TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS, bootLoader, size); + + // Boot loader and decompressor checksum + *(uint16 *) (buffer + TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET) = static_cast (size); + *(uint32 *) (buffer + TC_BOOT_SECTOR_LOADER_CHECKSUM_OFFSET) = GetChecksum (buffer + TC_SECTOR_SIZE_BIOS, + TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS + size); + + // Backup of decompressor and boot loader + if (size + TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS <= TC_BOOT_LOADER_BACKUP_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS) + { + memcpy (buffer + TC_SECTOR_SIZE_BIOS + TC_BOOT_LOADER_BACKUP_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS, + buffer + TC_SECTOR_SIZE_BIOS, TC_BOOT_LOADER_BACKUP_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS); + + buffer[TC_BOOT_SECTOR_CONFIG_OFFSET] |= TC_BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE; + } + else if (!rescueDisk && bootLoaderId != IDR_BOOT_LOADER && bootLoaderId != IDR_BOOT_LOADER_SHA2) + { + throw ParameterIncorrect (SRC_POS); + } + } + + + void BootEncryption::ReadBootSectorConfig (byte *config, size_t bufLength, byte *userConfig, string *customUserMessage, uint16 *bootLoaderVersion) + { + if (config && bufLength < TC_BOOT_CFG_FLAG_AREA_SIZE) + throw ParameterIncorrect (SRC_POS); + + GetSystemDriveConfigurationRequest request; + StringCchCopyW (request.DevicePath, ARRAYSIZE (request.DevicePath), GetSystemDriveConfiguration().DeviceKernelPath.c_str()); + + try + { + CallDriver (TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG, &request, sizeof (request), &request, sizeof (request)); + if (config) + *config = request.Configuration; + + if (userConfig) + *userConfig = request.UserConfiguration; + + if (customUserMessage) + { + request.CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH] = 0; + *customUserMessage = request.CustomUserMessage; + } + + if (bootLoaderVersion) + *bootLoaderVersion = request.BootLoaderVersion; + } + catch (...) + { + if (config) + *config = 0; + + if (userConfig) + *userConfig = 0; + + if (customUserMessage) + customUserMessage->clear(); + + if (bootLoaderVersion) + *bootLoaderVersion = 0; + } + } + + + void BootEncryption::WriteBootSectorConfig (const byte newConfig[]) + { + Device device (GetSystemDriveConfiguration().DevicePath); + device.CheckOpened (SRC_POS); + byte mbr[TC_SECTOR_SIZE_BIOS]; + + device.SeekAt (0); + device.Read (mbr, sizeof (mbr)); + + memcpy (mbr + TC_BOOT_SECTOR_CONFIG_OFFSET, newConfig, TC_BOOT_CFG_FLAG_AREA_SIZE); + + device.SeekAt (0); + device.Write (mbr, sizeof (mbr)); + + byte mbrVerificationBuf[TC_SECTOR_SIZE_BIOS]; + device.SeekAt (0); + device.Read (mbrVerificationBuf, sizeof (mbr)); + + if (memcmp (mbr, mbrVerificationBuf, sizeof (mbr)) != 0) + throw ErrorException ("ERROR_MBR_PROTECTED", SRC_POS); + } + + + void BootEncryption::WriteBootSectorUserConfig (byte userConfig, const string &customUserMessage, int pim) + { + Device device (GetSystemDriveConfiguration().DevicePath); + device.CheckOpened (SRC_POS); + byte mbr[TC_SECTOR_SIZE_BIOS]; + + device.SeekAt (0); + device.Read (mbr, sizeof (mbr)); + + if (!BufferContainsString (mbr, sizeof (mbr), TC_APP_NAME) + || BE16 (*(uint16 *) (mbr + TC_BOOT_SECTOR_VERSION_OFFSET)) != VERSION_NUM) + { + return; + } + + mbr[TC_BOOT_SECTOR_USER_CONFIG_OFFSET] = userConfig; + + memset (mbr + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, 0, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); + + if (!customUserMessage.empty()) + { + if (customUserMessage.size() > TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH) + throw ParameterIncorrect (SRC_POS); + + memcpy (mbr + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, customUserMessage.c_str(), customUserMessage.size()); + } + + if (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM) + { + // PIM for pre-boot authentication can be encoded on two bytes since its maximum + // value is 65535 (0xFFFF) + memcpy (mbr + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, &pim, TC_BOOT_SECTOR_PIM_VALUE_SIZE); + } + else + memset (mbr + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, 0, TC_BOOT_SECTOR_PIM_VALUE_SIZE); + + device.SeekAt (0); + device.Write (mbr, sizeof (mbr)); + + byte mbrVerificationBuf[TC_SECTOR_SIZE_BIOS]; + device.SeekAt (0); + device.Read (mbrVerificationBuf, sizeof (mbr)); + + if (memcmp (mbr, mbrVerificationBuf, sizeof (mbr)) != 0) + throw ErrorException ("ERROR_MBR_PROTECTED", SRC_POS); + } + + + unsigned int BootEncryption::GetHiddenOSCreationPhase () + { + byte configFlags [TC_BOOT_CFG_FLAG_AREA_SIZE]; + + ReadBootSectorConfig (configFlags, sizeof(configFlags)); + + return (configFlags[0] & TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE); + } + + + void BootEncryption::SetHiddenOSCreationPhase (unsigned int newPhase) + { +#if TC_BOOT_CFG_FLAG_AREA_SIZE != 1 +# error TC_BOOT_CFG_FLAG_AREA_SIZE != 1; revise GetHiddenOSCreationPhase() and SetHiddenOSCreationPhase() +#endif + byte configFlags [TC_BOOT_CFG_FLAG_AREA_SIZE]; + + ReadBootSectorConfig (configFlags, sizeof(configFlags)); + + configFlags[0] &= (byte) ~TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE; + + configFlags[0] |= newPhase; + + WriteBootSectorConfig (configFlags); + } + + +#ifndef SETUP + + void BootEncryption::StartDecoyOSWipe (WipeAlgorithmId wipeAlgorithm) + { + if (!IsHiddenOSRunning()) + throw ParameterIncorrect (SRC_POS); + + WipeDecoySystemRequest request; + ZeroMemory (&request, sizeof (request)); + + request.WipeAlgorithm = wipeAlgorithm; + + if (Randinit() != ERR_SUCCESS) + { + if (CryptoAPILastError == ERROR_SUCCESS) + throw RandInitFailed (SRC_POS, GetLastError ()); + else + throw CryptoApiFailed (SRC_POS, CryptoAPILastError); + } + + /* force the display of the random enriching dialog */ + SetRandomPoolEnrichedByUserStatus (FALSE); + + UserEnrichRandomPool (ParentWindow); + + if (!RandgetBytes (ParentWindow, request.WipeKey, sizeof (request.WipeKey), TRUE)) + throw ParameterIncorrect (SRC_POS); + + CallDriver (TC_IOCTL_START_DECOY_SYSTEM_WIPE, &request, sizeof (request), NULL, 0); + + burn (&request, sizeof (request)); + } + + + void BootEncryption::AbortDecoyOSWipe () + { + CallDriver (TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE); + } + + + DecoySystemWipeStatus BootEncryption::GetDecoyOSWipeStatus () + { + DecoySystemWipeStatus status; + CallDriver (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS, NULL, 0, &status, sizeof (status)); + return status; + } + + + void BootEncryption::CheckDecoyOSWipeResult () + { + CallDriver (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT); + } + + + void BootEncryption::WipeHiddenOSCreationConfig () + { + if (IsHiddenOSRunning()) + throw ParameterIncorrect (SRC_POS); + + if (Randinit() != ERR_SUCCESS) + { + if (CryptoAPILastError == ERROR_SUCCESS) + throw RandInitFailed (SRC_POS, GetLastError ()); + else + throw CryptoApiFailed (SRC_POS, CryptoAPILastError); + } + + Device device (GetSystemDriveConfiguration().DevicePath); + device.CheckOpened(SRC_POS); + byte mbr[TC_SECTOR_SIZE_BIOS]; + + device.SeekAt (0); + device.Read (mbr, sizeof (mbr)); + + finally_do_arg (BootEncryption *, this, + { + try + { + finally_arg->SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE); + } catch (...) { } + }); + +#if PRAND_DISK_WIPE_PASSES > RNG_POOL_SIZE +# error PRAND_DISK_WIPE_PASSES > RNG_POOL_SIZE +#endif + + byte randData[PRAND_DISK_WIPE_PASSES]; + if (!RandgetBytes (ParentWindow, randData, sizeof (randData), FALSE)) + throw ParameterIncorrect (SRC_POS); + + for (int wipePass = 0; wipePass < PRAND_DISK_WIPE_PASSES; wipePass++) + { + for (int i = 0; i < TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE; ++i) + { + mbr[TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET + i] = randData[wipePass]; + } + + mbr[TC_BOOT_SECTOR_CONFIG_OFFSET] &= (byte) ~TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE; + mbr[TC_BOOT_SECTOR_CONFIG_OFFSET] |= randData[wipePass] & TC_BOOT_CFG_MASK_HIDDEN_OS_CREATION_PHASE; + + if (wipePass == PRAND_DISK_WIPE_PASSES - 1) + memset (mbr + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET, 0, TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE); + + device.SeekAt (0); + device.Write (mbr, sizeof (mbr)); + } + + for (int wipePass = 0; wipePass < PRAND_DISK_WIPE_PASSES/4 + 1; wipePass++) + { + SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE); + SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_CLONING); + SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_WIPING); + SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_WIPED); + } + SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE); + } + +#endif // !SETUP + + + void BootEncryption::InstallBootLoader (bool preserveUserConfig, bool hiddenOSCreation) + { + Device device (GetSystemDriveConfiguration().DevicePath); + device.CheckOpened (SRC_POS); + + InstallBootLoader (device, preserveUserConfig, hiddenOSCreation); + } + + void BootEncryption::InstallBootLoader (Device& device, bool preserveUserConfig, bool hiddenOSCreation, int pim) + { + byte bootLoaderBuf[TC_BOOT_LOADER_AREA_SIZE - TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE] = {0}; + CreateBootLoaderInMemory (bootLoaderBuf, sizeof (bootLoaderBuf), false, hiddenOSCreation); + + // Write MBR + byte mbr[TC_SECTOR_SIZE_BIOS]; + + device.SeekAt (0); + device.Read (mbr, sizeof (mbr)); + + if (preserveUserConfig && BufferContainsString (mbr, sizeof (mbr), TC_APP_NAME)) + { + uint16 version = BE16 (*(uint16 *) (mbr + TC_BOOT_SECTOR_VERSION_OFFSET)); + if (version != 0) + { + bootLoaderBuf[TC_BOOT_SECTOR_USER_CONFIG_OFFSET] = mbr[TC_BOOT_SECTOR_USER_CONFIG_OFFSET]; + memcpy (bootLoaderBuf + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, mbr + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); + + if (bootLoaderBuf[TC_BOOT_SECTOR_USER_CONFIG_OFFSET] & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM) + { + if (pim >= 0) + { + memcpy (bootLoaderBuf + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, &pim, TC_BOOT_SECTOR_PIM_VALUE_SIZE); + } + else + memcpy (bootLoaderBuf + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, mbr + TC_BOOT_SECTOR_PIM_VALUE_OFFSET, TC_BOOT_SECTOR_PIM_VALUE_SIZE); + } + } + } + + memcpy (mbr, bootLoaderBuf, TC_MAX_MBR_BOOT_CODE_SIZE); + + device.SeekAt (0); + device.Write (mbr, sizeof (mbr)); + + byte mbrVerificationBuf[TC_SECTOR_SIZE_BIOS]; + device.SeekAt (0); + device.Read (mbrVerificationBuf, sizeof (mbr)); + + if (memcmp (mbr, mbrVerificationBuf, sizeof (mbr)) != 0) + throw ErrorException ("ERROR_MBR_PROTECTED", SRC_POS); + + // Write boot loader + device.SeekAt (TC_SECTOR_SIZE_BIOS); + device.Write (bootLoaderBuf + TC_SECTOR_SIZE_BIOS, sizeof (bootLoaderBuf) - TC_SECTOR_SIZE_BIOS); + } + +#ifndef SETUP + bool BootEncryption::CheckBootloaderFingerprint (bool bSilent) + { + byte bootLoaderBuf[TC_BOOT_LOADER_AREA_SIZE - TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE] = {0}; + byte fingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE]; + byte expectedFingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE]; + bool bRet = false; + + try + { + // read bootloader fingerprint + GetInstalledBootLoaderFingerprint (fingerprint); + + // compute expected fingerprint + CreateBootLoaderInMemory (bootLoaderBuf, sizeof (bootLoaderBuf), false, false); + ::ComputeBootloaderFingerprint (bootLoaderBuf, sizeof (bootLoaderBuf), expectedFingerprint); + + // compare values + if (0 == memcmp (fingerprint, expectedFingerprint, sizeof (expectedFingerprint))) + { + bRet = true; + } + } + catch (SystemException &e) + { + if (!bSilent && (GetLastError () != ERROR_INVALID_IMAGE_HASH)) + e.Show (ParentWindow); + } + catch (Exception& e) + { + if (!bSilent) + e.Show (ParentWindow); + } + + return bRet; + } +#endif + + wstring BootEncryption::GetSystemLoaderBackupPath () + { + WCHAR pathBuf[MAX_PATH]; + + throw_sys_if (!SUCCEEDED (SHGetFolderPath (NULL, CSIDL_COMMON_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, pathBuf))); + + wstring path = wstring (pathBuf) + L"\\" _T(TC_APP_NAME); + CreateDirectory (path.c_str(), NULL); + + return path + L'\\' + TC_SYS_BOOT_LOADER_BACKUP_NAME; + } + + + void BootEncryption::RenameDeprecatedSystemLoaderBackup () + { + WCHAR pathBuf[MAX_PATH]; + + if (SUCCEEDED (SHGetFolderPath (NULL, CSIDL_COMMON_APPDATA, NULL, 0, pathBuf))) + { + wstring path = wstring (pathBuf) + L"\\" _T(TC_APP_NAME) + L'\\' + TC_SYS_BOOT_LOADER_BACKUP_NAME_LEGACY; + + if (FileExists (path.c_str()) && !FileExists (GetSystemLoaderBackupPath().c_str())) + throw_sys_if (_wrename (path.c_str(), GetSystemLoaderBackupPath().c_str()) != 0); + } + } + + +#ifndef SETUP + void BootEncryption::CreateRescueIsoImage (bool initialSetup, const wstring &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 + const char* szPrimVolDesc = "\001CD001\001"; + const char* szPrimVolLabel = "VeraCrypt Rescue Disk "; + memcpy (image + 0x8000, szPrimVolDesc, strlen(szPrimVolDesc) + 1); + memcpy (image + 0x7fff + 41, szPrimVolLabel, strlen(szPrimVolLabel) + 1); + *(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 + const char* szBootRecDesc = "CD001\001EL TORITO SPECIFICATION"; + memcpy (image + 0x8801, szBootRecDesc, strlen(szBootRecDesc) + 1); + image[0x8800 + 0x47] = 0x19; + + // Volume descriptor set terminator + const char* szVolDescTerm = "\377CD001\001"; + memcpy (image + 0x9000, szVolDescTerm, strlen(szVolDescTerm) + 1); + + // 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.CheckOpened (SRC_POS); + 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.CheckOpened (SRC_POS); + 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", ParentWindow); + } + + // 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::IsCDRecorderPresent () + { + ICDBurn* pICDBurn; + BOOL bHasRecorder = FALSE; + + if (SUCCEEDED( CoCreateInstance (CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) + { + if (pICDBurn->HasRecordableDrive (&bHasRecorder) != S_OK) + { + bHasRecorder = FALSE; + } + pICDBurn->Release(); + } + return bHasRecorder? true : false; + } + + + bool BootEncryption::VerifyRescueDisk () + { + if (!RescueIsoImage) + throw ParameterIncorrect (SRC_POS); + + for (WCHAR drive = L'Z'; drive >= L'C'; --drive) + { + try + { + WCHAR rootPath[4] = { drive, L':', L'\\', 0}; + UINT driveType = GetDriveType (rootPath); + // check that it is a CD/DVD drive or a removable media in case a bootable + // USB key was created from the rescue disk ISO file + if ((DRIVE_CDROM == driveType) || (DRIVE_REMOVABLE == driveType)) + { + rootPath[2] = 0; // remove trailing backslash + + Device driveDevice (rootPath, true); + driveDevice.CheckOpened (SRC_POS); + 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(), (DWORD) buffer.Size()); + if (bytesRead != buffer.Size()) + continue; + + if (memcmp (buffer.Ptr(), RescueIsoImage, buffer.Size()) == 0) + return true; + } + } + catch (...) { } + } + + return false; + } + + bool BootEncryption::VerifyRescueDiskIsoImage (const wchar_t* imageFile) + { + if (!RescueIsoImage) + throw ParameterIncorrect (SRC_POS); + + try + { + File isoFile (imageFile, true); + isoFile.CheckOpened (SRC_POS); + 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 = isoFile.Read (buffer.Ptr(), (DWORD) buffer.Size()); + if ( (bytesRead == buffer.Size()) + && (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, int pim) + { + PCRYPTO_INFO cryptoInfo = NULL; + + if (!IsRandomNumberGeneratorStarted()) + throw ParameterIncorrect (SRC_POS); + + throw_sys_if (CreateVolumeHeaderInMemory (ParentWindow, TRUE, (char *) VolumeHeader, ea, mode, password, pkcs5, pim, NULL, &cryptoInfo, + volumeSize, 0, encryptedAreaStart, 0, TC_SYSENC_KEYSCOPE_MIN_REQ_PROG_VERSION, TC_HEADER_FLAG_ENCRYPTED_SYSTEM, TC_SECTOR_SIZE_BIOS, 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)); + if (0 != ReadVolumeHeader (TRUE, (char *) RescueVolumeHeader, password, pkcs5, pim, FALSE, NULL, cryptoInfo)) + throw ParameterIncorrect (SRC_POS); + + DecryptBuffer (RescueVolumeHeader + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo); + + if (GetHeaderField32 (RescueVolumeHeader, TC_HEADER_OFFSET_MAGIC) != 0x56455241) + 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.CheckOpened (SRC_POS); + + 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); + device.CheckOpened (SRC_POS); + byte bootLoaderBuf[TC_BOOT_LOADER_AREA_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS]; + + 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", ParentWindow) == 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 * TC_SECTOR_SIZE_BIOS]; + + File backupFile (GetSystemLoaderBackupPath(), true); + backupFile.CheckOpened(SRC_POS); + if (backupFile.Read (bootLoaderBuf, sizeof (bootLoaderBuf)) != sizeof (bootLoaderBuf)) + throw ParameterIncorrect (SRC_POS); + + Device device (GetSystemDriveConfiguration().DevicePath); + device.CheckOpened (SRC_POS); + + // Preserve current partition table + byte mbr[TC_SECTOR_SIZE_BIOS]; + 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::RegisterFilter (bool registerFilter, FilterType filterType, const GUID *deviceClassGuid) + { + string filter; + string filterReg; + HKEY regKey; + + switch (filterType) + { + case DriveFilter: + case VolumeFilter: + filter = "veracrypt"; + filterReg = "UpperFilters"; + regKey = OpenDeviceClassRegKey (deviceClassGuid); + throw_sys_if (regKey == INVALID_HANDLE_VALUE); + + break; + + case DumpFilter: + if (!IsOSAtLeast (WIN_VISTA)) + return; + + filter = "veracrypt.sys"; + filterReg = "DumpFilters"; + SetLastError (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\CrashControl", 0, KEY_READ | KEY_WRITE, ®Key)); + throw_sys_if (GetLastError() != ERROR_SUCCESS); + + break; + + default: + throw ParameterIncorrect (SRC_POS); + } + + finally_do_arg (HKEY, regKey, { RegCloseKey (finally_arg); }); + + if (registerFilter && filterType != DumpFilter) + { + // Register class filter below all other filters in the stack + + size_t strSize = filter.size() + 1; + byte regKeyBuf[65536]; + DWORD size = (DWORD) (sizeof (regKeyBuf) - strSize); + + // SetupInstallFromInfSection() does not support prepending of values so we have to modify the registry directly + StringCchCopyA ((char *) regKeyBuf, ARRAYSIZE(regKeyBuf), filter.c_str()); + + if (RegQueryValueExA (regKey, filterReg.c_str(), NULL, NULL, regKeyBuf + strSize, &size) != ERROR_SUCCESS) + size = 1; + + SetLastError (RegSetValueExA (regKey, filterReg.c_str(), 0, REG_MULTI_SZ, regKeyBuf, (DWORD) strSize + size)); + throw_sys_if (GetLastError() != ERROR_SUCCESS); + } + else + { + RegisterDriverInf (registerFilter, filter, filterReg, ParentWindow, regKey); + } + } + + void BootEncryption::RegisterFilterDriver (bool registerDriver, FilterType filterType) + { + if (!IsAdmin() && IsUacSupported()) + { + Elevator::RegisterFilterDriver (registerDriver, filterType); + return; + } + + switch (filterType) + { + case DriveFilter: + RegisterFilter (registerDriver, filterType, &GUID_DEVCLASS_DISKDRIVE); + break; + + case VolumeFilter: + RegisterFilter (registerDriver, filterType, &GUID_DEVCLASS_VOLUME); + RegisterFilter (registerDriver, filterType, &GUID_DEVCLASS_FLOPPYDISK); + break; + + case DumpFilter: + RegisterFilter (registerDriver, filterType); + break; + + default: + throw ParameterIncorrect (SRC_POS); + } + } + + void BootEncryption::RegisterSystemFavoritesService (BOOL registerService, BOOL noFileHandling) + { + SC_HANDLE scm = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); + throw_sys_if (!scm); + finally_do_arg (SC_HANDLE, scm, { CloseServiceHandle (finally_arg); }); + + wstring servicePath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", false); + wstring serviceLegacyPath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", true); + + if (registerService) + { + try + { + RegisterSystemFavoritesService (FALSE, noFileHandling); + } + catch (...) { } + + if (!noFileHandling) + { + wchar_t appPath[TC_MAX_PATH]; + throw_sys_if (!GetModuleFileName (NULL, appPath, ARRAYSIZE (appPath))); + + throw_sys_if (!CopyFile (appPath, servicePath.c_str(), FALSE)); + } + + SC_HANDLE service = CreateService (scm, + TC_SYSTEM_FAVORITES_SERVICE_NAME, + _T(TC_APP_NAME) L" System Favorites", + SERVICE_ALL_ACCESS, + SERVICE_WIN32_OWN_PROCESS, + SERVICE_AUTO_START, + SERVICE_ERROR_NORMAL, + (wstring (L"\"") + servicePath + L"\" " TC_SYSTEM_FAVORITES_SERVICE_CMDLINE_OPTION).c_str(), + TC_SYSTEM_FAVORITES_SERVICE_LOAD_ORDER_GROUP, + NULL, + NULL, + NULL, + NULL); + + throw_sys_if (!service); + + SERVICE_DESCRIPTION description; + description.lpDescription = L"Mounts VeraCrypt system favorite volumes."; + ChangeServiceConfig2 (service, SERVICE_CONFIG_DESCRIPTION, &description); + + CloseServiceHandle (service); + + try + { + WriteLocalMachineRegistryString (L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Minimal\\" TC_SYSTEM_FAVORITES_SERVICE_NAME, NULL, L"Service", FALSE); + WriteLocalMachineRegistryString (L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Network\\" TC_SYSTEM_FAVORITES_SERVICE_NAME, NULL, L"Service", FALSE); + + SetDriverConfigurationFlag (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES, true); + } + catch (...) + { + try + { + RegisterSystemFavoritesService (FALSE, noFileHandling); + } + catch (...) { } + + throw; + } + } + else + { + SetDriverConfigurationFlag (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES, false); + + DeleteLocalMachineRegistryKey (L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Minimal", TC_SYSTEM_FAVORITES_SERVICE_NAME); + DeleteLocalMachineRegistryKey (L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Network", TC_SYSTEM_FAVORITES_SERVICE_NAME); + + SC_HANDLE service = OpenService (scm, TC_SYSTEM_FAVORITES_SERVICE_NAME, SERVICE_ALL_ACCESS); + throw_sys_if (!service); + + throw_sys_if (!DeleteService (service)); + CloseServiceHandle (service); + + if (!noFileHandling) + { + DeleteFile (servicePath.c_str()); + if (serviceLegacyPath != servicePath) + DeleteFile (serviceLegacyPath.c_str()); + } + } + } + + void BootEncryption::UpdateSystemFavoritesService () + { + SC_HANDLE scm = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); + throw_sys_if (!scm); + + finally_do_arg (SC_HANDLE, scm, { CloseServiceHandle (finally_arg); }); + + wstring servicePath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", false); + + // check if service exists + SC_HANDLE service = OpenService (scm, TC_SYSTEM_FAVORITES_SERVICE_NAME, SERVICE_ALL_ACCESS); + if (service) + { + finally_do_arg (SC_HANDLE, service, { CloseServiceHandle (finally_arg); }); + // ensure that its parameters are correct + throw_sys_if (!ChangeServiceConfig (service, + SERVICE_WIN32_OWN_PROCESS, + SERVICE_AUTO_START, + SERVICE_ERROR_NORMAL, + (wstring (L"\"") + servicePath + L"\" " TC_SYSTEM_FAVORITES_SERVICE_CMDLINE_OPTION).c_str(), + TC_SYSTEM_FAVORITES_SERVICE_LOAD_ORDER_GROUP, + NULL, + NULL, + NULL, + NULL, + _T(TC_APP_NAME) L" System Favorites")); + + } + else + { + RegisterSystemFavoritesService (TRUE, TRUE); + } + } + + void BootEncryption::SetDriverConfigurationFlag (uint32 flag, bool state) + { + DWORD configMap = ReadDriverConfigurationFlags(); + + if (state) + configMap |= flag; + else + configMap &= ~flag; +#ifdef SETUP + WriteLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_DRIVER_CONFIG_REG_VALUE_NAME, configMap); +#else + WriteLocalMachineRegistryDwordValue (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_DRIVER_CONFIG_REG_VALUE_NAME, configMap); +#endif + } + +#ifndef SETUP + + void BootEncryption::RegisterSystemFavoritesService (BOOL registerService) + { + if (!IsAdmin() && IsUacSupported()) + { + Elevator::RegisterSystemFavoritesService (registerService); + return; + } + + RegisterSystemFavoritesService (registerService, FALSE); + } + + void BootEncryption::CheckRequirements () + { + if (nCurrentOS == WIN_2000) + throw ErrorException ("SYS_ENCRYPTION_UNSUPPORTED_ON_CURRENT_OS", SRC_POS); + + if (CurrentOSMajor == 6 && CurrentOSMinor == 0 && CurrentOSServicePack < 1) + throw ErrorException ("SYS_ENCRYPTION_UNSUPPORTED_ON_VISTA_SP0", SRC_POS); + + if (IsNonInstallMode()) + throw ErrorException ("FEATURE_REQUIRES_INSTALLATION", SRC_POS); + + SystemDriveConfiguration config = GetSystemDriveConfiguration (); + + if (config.SystemPartition.IsGPT) + throw ErrorException ("GPT_BOOT_DRIVE_UNSUPPORTED", SRC_POS); + + if (SystemDriveIsDynamic()) + throw ErrorException ("SYSENC_UNSUPPORTED_FOR_DYNAMIC_DISK", SRC_POS); + + if (config.InitialUnallocatedSpace < TC_BOOT_LOADER_AREA_SIZE) + throw ErrorException ("NO_SPACE_FOR_BOOT_LOADER", SRC_POS); + + DISK_GEOMETRY geometry = GetDriveGeometry (config.DriveNumber); + + if (geometry.BytesPerSector != TC_SECTOR_SIZE_BIOS) + throw ErrorException ("SYSENC_UNSUPPORTED_SECTOR_SIZE_BIOS", SRC_POS); + + bool activePartitionFound = false; + if (!config.SystemPartition.IsGPT) + { + // Determine whether there is an Active partition on the system drive + foreach (const Partition &partition, config.Partitions) + { + if (partition.Info.BootIndicator) + { + activePartitionFound = true; + break; + } + } + } + + if (!config.SystemLoaderPresent || !activePartitionFound) + { + static bool confirmed = false; + + if (!confirmed && AskWarnNoYes ("WINDOWS_NOT_ON_BOOT_DRIVE_ERROR", ParentWindow) == IDNO) + throw UserAbort (SRC_POS); + + confirmed = true; + } + } + + + 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 () + { + wchar_t windowsDrive = (wchar_t) towupper (GetWindowsDirectory()[0]); + + // Paging files + bool pagingFilesOk = !IsPagingFileActive (TRUE); + + wchar_t pagingFileRegData[65536]; + DWORD pagingFileRegDataSize = sizeof (pagingFileRegData); + + if (ReadLocalMachineRegistryMultiString (L"System\\CurrentControlSet\\Control\\Session Manager\\Memory Management", L"PagingFiles", pagingFileRegData, &pagingFileRegDataSize) + && pagingFileRegDataSize > 8) + { + for (size_t i = 1; i < pagingFileRegDataSize/2 - 2; ++i) + { + if (wmemcmp (pagingFileRegData + i, L":\\", 2) == 0 && towupper (pagingFileRegData[i - 1]) != windowsDrive) + { + pagingFilesOk = false; + break; + } + } + } + + if (!pagingFilesOk) + { + if (AskWarnYesNoString ((wchar_t *) (wstring (GetString ("PAGING_FILE_NOT_ON_SYS_PARTITION")) + + GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION") + + L"\n\n\n" + + GetString ("RESTRICT_PAGING_FILES_TO_SYS_PARTITION") + ).c_str(), ParentWindow) == IDYES) + { + RestrictPagingFilesToSystemPartition(); + RestartComputer(); + AbortProcessSilent(); + } + + throw ErrorException (wstring (GetString ("PAGING_FILE_NOT_ON_SYS_PARTITION")) + + GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION"), SRC_POS); + } + + // User profile + wchar_t *configPath = GetConfigPath (L"dummy"); + if (configPath && towupper (configPath[0]) != windowsDrive) + { + throw ErrorException (wstring (GetString ("USER_PROFILE_NOT_ON_SYS_PARTITION")) + + GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION"), SRC_POS); + } + + // Temporary files + if (towupper (GetTempPathString()[0]) != windowsDrive) + { + throw ErrorException (wstring (GetString ("TEMP_NOT_ON_SYS_PARTITION")) + + GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION"), SRC_POS); + } + } + + + // This operation may take a long time when an antivirus is installed and its real-time protection enabled. + // Therefore, if calling it without the wizard displayed, it should be called with displayWaitDialog set to true. + void BootEncryption::Deinstall (bool displayWaitDialog) + { + BootEncryptionStatus encStatus = GetStatus(); + + if (encStatus.DriveEncrypted || encStatus.DriveMounted) + throw ParameterIncorrect (SRC_POS); + + SystemDriveConfiguration config = GetSystemDriveConfiguration (); + + if (encStatus.VolumeHeaderPresent) + { + // Verify CRC of header salt + Device device (config.DevicePath, true); + device.CheckOpened (SRC_POS); + byte header[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE]; + + device.SeekAt (TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET); + device.Read (header, sizeof (header)); + + if (encStatus.VolumeHeaderSaltCrc32 != GetCrc32 ((byte *) header, PKCS5_SALT_SIZE)) + throw ParameterIncorrect (SRC_POS); + } + + try + { + RegisterFilterDriver (false, DriveFilter); + RegisterFilterDriver (false, VolumeFilter); + RegisterFilterDriver (false, DumpFilter); + SetDriverServiceStartType (SERVICE_SYSTEM_START); + } + catch (...) + { + try + { + RegisterBootDriver (IsHiddenSystemRunning()); + } + catch (...) { } + + throw; + } + + SetHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE); // In case RestoreSystemLoader() fails + + try + { + RegisterSystemFavoritesService (false); + } + catch (...) { } + + try + { + if (displayWaitDialog) + DisplayStaticModelessWaitDlg (ParentWindow); + + finally_do_arg (bool, displayWaitDialog, { if (finally_arg) CloseStaticModelessWaitDlg(); }); + + RestoreSystemLoader (); + } + catch (Exception &e) + { + e.Show (ParentWindow); + throw ErrorException ("SYS_LOADER_RESTORE_FAILED", SRC_POS); + } + } + + + int BootEncryption::ChangePassword (Password *oldPassword, int old_pkcs5, int old_pim, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg) + { + BootEncryptionStatus encStatus = GetStatus(); + + if (encStatus.SetupInProgress || (wipePassCount <= 0)) + throw ParameterIncorrect (SRC_POS); + + SystemDriveConfiguration config = GetSystemDriveConfiguration (); + + char header[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE]; + Device device (config.DevicePath); + device.CheckOpened (SRC_POS); + + // Only one algorithm is currently supported + if (pkcs5 != 0) + throw ParameterIncorrect (SRC_POS); + + int64 headerOffset = TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET; + int64 backupHeaderOffset = -1; + + if (encStatus.HiddenSystem) + { + headerOffset = encStatus.HiddenSystemPartitionStart + TC_HIDDEN_VOLUME_HEADER_OFFSET; + + // Find hidden system partition + foreach (const Partition &partition, config.Partitions) + { + if (partition.Info.StartingOffset.QuadPart == encStatus.HiddenSystemPartitionStart) + { + backupHeaderOffset = partition.Info.StartingOffset.QuadPart + partition.Info.PartitionLength.QuadPart - TC_VOLUME_HEADER_SIZE; + break; + } + } + + if (backupHeaderOffset == -1) + throw ParameterIncorrect (SRC_POS); + } + + device.SeekAt (headerOffset); + device.Read ((byte *) header, sizeof (header)); + + PCRYPTO_INFO cryptoInfo = NULL; + + int status = ReadVolumeHeader (!encStatus.HiddenSystem, header, oldPassword, old_pkcs5, old_pim, FALSE, &cryptoInfo, NULL); + finally_do_arg (PCRYPTO_INFO, cryptoInfo, { if (finally_arg) crypto_close (finally_arg); }); + + if (status != 0) + { + handleError (hwndDlg, status, SRC_POS); + return status; + } + + // Change the PKCS-5 PRF if requested by user + if (pkcs5 != 0) + { + cryptoInfo->pkcs5 = pkcs5; + RandSetHashFunction (pkcs5); + } + + if (Randinit() != 0) + { + if (CryptoAPILastError == ERROR_SUCCESS) + throw RandInitFailed (SRC_POS, GetLastError ()); + else + throw CryptoApiFailed (SRC_POS, CryptoAPILastError); + } + finally_do ({ RandStop (FALSE); }); + + /* force the display of the random enriching dialog */ + SetRandomPoolEnrichedByUserStatus (FALSE); + + NormalCursor(); + UserEnrichRandomPool (hwndDlg); + WaitCursor(); + + /* The header will be re-encrypted wipePassCount times to prevent adversaries from using + techniques such as magnetic force microscopy or magnetic force scanning tunnelling microscopy + to recover the overwritten header. According to Peter Gutmann, data should be overwritten 22 + times (ideally, 35 times) using non-random patterns and pseudorandom data. However, as users might + impatiently interupt the process (etc.) we will not use the Gutmann's patterns but will write the + valid re-encrypted header, i.e. pseudorandom data, and there will be many more passes than Guttman + recommends. During each pass we will write a valid working header. Each pass will use the same master + key, and also the same header key, secondary key (XTS), etc., derived from the new password. The only + item that will be different for each pass will be the salt. This is sufficient to cause each "version" + of the header to differ substantially and in a random manner from the versions written during the + other passes. */ + + bool headerUpdated = false; + int result = ERR_SUCCESS; + + try + { + BOOL backupHeader = FALSE; + while (TRUE) + { + for (int wipePass = 0; wipePass < wipePassCount; wipePass++) + { + PCRYPTO_INFO tmpCryptoInfo = NULL; + + status = CreateVolumeHeaderInMemory (hwndDlg, !encStatus.HiddenSystem, + header, + cryptoInfo->ea, + cryptoInfo->mode, + newPassword, + cryptoInfo->pkcs5, + pim, + (char *) cryptoInfo->master_keydata, + &tmpCryptoInfo, + cryptoInfo->VolumeSize.Value, + cryptoInfo->hiddenVolumeSize, + cryptoInfo->EncryptedAreaStart.Value, + cryptoInfo->EncryptedAreaLength.Value, + cryptoInfo->RequiredProgramVersion, + cryptoInfo->HeaderFlags | TC_HEADER_FLAG_ENCRYPTED_SYSTEM, + cryptoInfo->SectorSize, + wipePass < wipePassCount - 1); + + if (tmpCryptoInfo) + crypto_close (tmpCryptoInfo); + + if (status != 0) + { + handleError (hwndDlg, status, SRC_POS); + return status; + } + + device.SeekAt (headerOffset); + device.Write ((byte *) header, sizeof (header)); + headerUpdated = true; + } + + if (!encStatus.HiddenSystem || backupHeader) + break; + + backupHeader = TRUE; + headerOffset = backupHeaderOffset; + } + } + catch (Exception &e) + { + e.Show (hwndDlg); + result = ERR_OS_ERROR; + } + + if (headerUpdated) + { + bool storedPimUpdateNeeded = false; + ReopenBootVolumeHeaderRequest reopenRequest; + reopenRequest.VolumePassword = *newPassword; + reopenRequest.pkcs5_prf = cryptoInfo->pkcs5; + reopenRequest.pim = pim; + finally_do_arg (ReopenBootVolumeHeaderRequest*, &reopenRequest, { burn (finally_arg, sizeof (*finally_arg)); }); + + if (old_pim != pim) + { + try + { + // check if PIM is stored in MBR + byte userConfig; + ReadBootSectorConfig (nullptr, 0, &userConfig); + if (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM) + storedPimUpdateNeeded = true; + } + catch (...) + {} + } + + try + { + // force update of bootloader if fingerprint doesn't match or if the stored PIM changed + if (storedPimUpdateNeeded || !CheckBootloaderFingerprint (true)) + InstallBootLoader (device, true, false, pim); + } + catch (...) + {} + + CallDriver (TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER, &reopenRequest, sizeof (reopenRequest)); + } + + return result; + } + + + void BootEncryption::CheckEncryptionSetupResult () + { + CallDriver (TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT); + } + + + void BootEncryption::Install (bool hiddenSystem) + { + BootEncryptionStatus encStatus = GetStatus(); + if (encStatus.DriveMounted) + throw ParameterIncorrect (SRC_POS); + + try + { + InstallBootLoader (false, hiddenSystem); + + if (!hiddenSystem) + InstallVolumeHeader (); + + RegisterBootDriver (hiddenSystem); + } + catch (Exception &) + { + try + { + RestoreSystemLoader (); + } + catch (Exception &e) + { + e.Show (ParentWindow); + } + + throw; + } + } + + + void BootEncryption::PrepareHiddenOSCreation (int ea, int mode, int pkcs5) + { + BootEncryptionStatus encStatus = GetStatus(); + if (encStatus.DriveMounted) + throw ParameterIncorrect (SRC_POS); + + CheckRequirements(); + BackupSystemLoader(); + + SelectedEncryptionAlgorithmId = ea; + SelectedPrfAlgorithmId = pkcs5; + } + + + void BootEncryption::PrepareInstallation (bool systemPartitionOnly, Password &password, int ea, int mode, int pkcs5, int pim, const wstring &rescueIsoImagePath) + { + BootEncryptionStatus encStatus = GetStatus(); + if (encStatus.DriveMounted) + throw ParameterIncorrect (SRC_POS); + + CheckRequirements (); + + SystemDriveConfiguration config = GetSystemDriveConfiguration(); + + // Some chipset drivers may prevent access to the last sector of the drive + if (!systemPartitionOnly) + { + DISK_GEOMETRY geometry = GetDriveGeometry (config.DriveNumber); + if ((geometry.BytesPerSector > 0) && (geometry.BytesPerSector < TC_MAX_VOLUME_SECTOR_SIZE)) + { + Buffer sector (geometry.BytesPerSector); + + Device device (config.DevicePath); + device.CheckOpened (SRC_POS); + + try + { + device.SeekAt (config.DrivePartition.Info.PartitionLength.QuadPart - geometry.BytesPerSector); + device.Read (sector.Ptr(), (DWORD) sector.Size()); + } + catch (SystemException &e) + { + if (e.ErrorCode != ERROR_CRC) + { + e.Show (ParentWindow); + Error ("WHOLE_DRIVE_ENCRYPTION_PREVENTED_BY_DRIVERS", ParentWindow); + throw UserAbort (SRC_POS); + } + } + } + } + + BackupSystemLoader (); + + uint64 volumeSize; + uint64 encryptedAreaStart; + + if (systemPartitionOnly) + { + volumeSize = config.SystemPartition.Info.PartitionLength.QuadPart; + encryptedAreaStart = config.SystemPartition.Info.StartingOffset.QuadPart; + } + else + { + volumeSize = config.DrivePartition.Info.PartitionLength.QuadPart - TC_BOOT_LOADER_AREA_SIZE; + encryptedAreaStart = config.DrivePartition.Info.StartingOffset.QuadPart + TC_BOOT_LOADER_AREA_SIZE; + } + + SelectedEncryptionAlgorithmId = ea; + SelectedPrfAlgorithmId = pkcs5; + CreateVolumeHeader (volumeSize, encryptedAreaStart, &password, ea, mode, pkcs5, pim); + + if (!rescueIsoImagePath.empty()) + CreateRescueIsoImage (true, rescueIsoImagePath); + } + + bool BootEncryption::IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) + { + if (!IsAdmin() && IsUacSupported()) + return Elevator::IsPagingFileActive (checkNonWindowsPartitionsOnly) ? true : false; + + return ::IsPagingFileActive (checkNonWindowsPartitionsOnly) ? true : false; + } + + void BootEncryption::RestrictPagingFilesToSystemPartition () + { + wchar_t pagingFiles[128] = {0}; + StringCchCopyW (pagingFiles, ARRAYSIZE(pagingFiles), L"X:\\pagefile.sys 0 0"); + pagingFiles[0] = GetWindowsDirectory()[0]; + + throw_sys_if (!WriteLocalMachineRegistryMultiString (L"System\\CurrentControlSet\\Control\\Session Manager\\Memory Management", L"PagingFiles", pagingFiles, (DWORD) (wcslen (pagingFiles) + 2) * sizeof (wchar_t))); + } + + void BootEncryption::WriteLocalMachineRegistryDwordValue (wchar_t *keyPath, wchar_t *valueName, DWORD value) + { + if (!IsAdmin() && IsUacSupported()) + { + Elevator::WriteLocalMachineRegistryDwordValue (keyPath, valueName, value); + return; + } + + throw_sys_if (!WriteLocalMachineRegistryDword (keyPath, valueName, value)); + } + + void BootEncryption::StartDecryption (BOOL discardUnreadableEncryptedSectors) + { + BootEncryptionStatus encStatus = GetStatus(); + + if (!encStatus.DeviceFilterActive || !encStatus.DriveMounted || encStatus.SetupInProgress) + throw ParameterIncorrect (SRC_POS); + + BootEncryptionSetupRequest request; + ZeroMemory (&request, sizeof (request)); + + request.SetupMode = SetupDecryption; + request.DiscardUnreadableEncryptedSectors = discardUnreadableEncryptedSectors; + + CallDriver (TC_IOCTL_BOOT_ENCRYPTION_SETUP, &request, sizeof (request), NULL, 0); + } + + void BootEncryption::StartEncryption (WipeAlgorithmId wipeAlgorithm, bool zeroUnreadableSectors) + { + BootEncryptionStatus encStatus = GetStatus(); + + if (!encStatus.DeviceFilterActive || !encStatus.DriveMounted || encStatus.SetupInProgress) + throw ParameterIncorrect (SRC_POS); + + BootEncryptionSetupRequest request; + ZeroMemory (&request, sizeof (request)); + + request.SetupMode = SetupEncryption; + request.WipeAlgorithm = wipeAlgorithm; + request.ZeroUnreadableSectors = zeroUnreadableSectors; + + CallDriver (TC_IOCTL_BOOT_ENCRYPTION_SETUP, &request, sizeof (request), NULL, 0); + } + + void BootEncryption::CopyFileAdmin (const wstring &sourceFile, const wstring &destinationFile) + { + if (!IsAdmin()) + { + if (!IsUacSupported()) + { + SetLastError (ERROR_ACCESS_DENIED); + throw SystemException(SRC_POS); + } + else + Elevator::CopyFile (sourceFile, destinationFile); + } + else + throw_sys_if (!::CopyFile (sourceFile.c_str(), destinationFile.c_str(), FALSE)); + } + + void BootEncryption::DeleteFileAdmin (const wstring &file) + { + if (!IsAdmin() && IsUacSupported()) + Elevator::DeleteFile (file); + else + throw_sys_if (!::DeleteFile (file.c_str())); + } + +#endif // !SETUP + + uint32 BootEncryption::ReadDriverConfigurationFlags () + { + DWORD configMap; + + if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_DRIVER_CONFIG_REG_VALUE_NAME, &configMap)) + configMap = 0; + + return configMap; + } + + void BootEncryption::WriteBootDriveSector (uint64 offset, byte *data) + { + WriteBootDriveSectorRequest request; + request.Offset.QuadPart = offset; + memcpy (request.Data, data, sizeof (request.Data)); + + CallDriver (TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR, &request, sizeof (request), NULL, 0); + } + + void BootEncryption::RegisterBootDriver (bool hiddenSystem) + { + SetDriverServiceStartType (SERVICE_BOOT_START); + + try + { + RegisterFilterDriver (false, DriveFilter); + RegisterFilterDriver (false, VolumeFilter); + RegisterFilterDriver (false, DumpFilter); + } + catch (...) { } + + try + { + RegisterFilterDriver (true, DriveFilter); + + if (hiddenSystem) + RegisterFilterDriver (true, VolumeFilter); + + RegisterFilterDriver (true, DumpFilter); + } + catch (...) + { + try { RegisterFilterDriver (false, DriveFilter); } catch (...) { } + try { RegisterFilterDriver (false, VolumeFilter); } catch (...) { } + try { RegisterFilterDriver (false, DumpFilter); } catch (...) { } + try { SetDriverServiceStartType (SERVICE_SYSTEM_START); } catch (...) { } + + throw; + } + } + + bool BootEncryption::RestartComputer (void) + { + return (::RestartComputer() != FALSE); + } +} diff --git a/src/Common/BootEncryption.h b/src/Common/BootEncryption.h index a922d1fa..a89b2ec6 100644 --- a/src/Common/BootEncryption.h +++ b/src/Common/BootEncryption.h @@ -1,255 +1,255 @@ -/* - 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. -*/ - -#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" - -using namespace std; - -namespace VeraCrypt -{ - class File - { - public: - File () : Elevated (false), FileOpen (false), FilePointerPosition(0), Handle(INVALID_HANDLE_VALUE), IsDevice(false), LastError(0) { } - File (wstring path,bool readOnly = false, bool create = false); - virtual ~File () { Close(); } - - 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); - - protected: - bool Elevated; - bool FileOpen; - uint64 FilePointerPosition; - HANDLE Handle; - bool IsDevice; - wstring Path; - DWORD LastError; - }; - - - 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; } - - 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 BootEncryption - { - public: - BootEncryption (HWND parent); - ~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); - void InstallBootLoader (Device& device, bool preserveUserConfig = false, bool hiddenOSCreation = false, int pim = -1); - void InstallBootLoader (bool preserveUserConfig = false, bool hiddenOSCreation = false); - 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 (); - void 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 (void); - 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 VerifyRescueDiskIsoImage (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); - void WriteLocalMachineRegistryDwordValue (wchar_t *keyPath, wchar_t *valueName, DWORD value); - - protected: - static const uint32 RescueIsoImageSize = 1835008; // Size of ISO9660 image with bootable emulated 1.44MB floppy disk image - - void BackupSystemLoader (); - 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 GetDriveGeometry (int driveNumber); - PartitionList GetDrivePartitions (int driveNumber); - wstring GetRemarksOnHiddenOS (); - wstring GetWindowsDirectory (); - void RegisterFilter (bool registerFilter, FilterType filterType, const GUID *deviceClassGuid = nullptr); - void RestoreSystemLoader (); - void InstallVolumeHeader (); - - HWND ParentWindow; - SystemDriveConfiguration DriveConfig; - int SelectedEncryptionAlgorithmId; - int SelectedPrfAlgorithmId; - Partition HiddenOSCandidatePartition; - byte *RescueIsoImage; - byte RescueVolumeHeader[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE]; - byte VolumeHeader[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE]; - bool DriveConfigValid; - bool RealSystemDriveSizeValid; - bool RescueVolumeHeaderValid; - bool VolumeHeaderValid; - }; -} - -#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" - -#endif // TC_HEADER_Common_BootEncryption +/* + 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. +*/ + +#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" + +using namespace std; + +namespace VeraCrypt +{ + class File + { + public: + File () : Elevated (false), FileOpen (false), FilePointerPosition(0), Handle(INVALID_HANDLE_VALUE), IsDevice(false), LastError(0) { } + File (wstring path,bool readOnly = false, bool create = false); + virtual ~File () { Close(); } + + 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); + + protected: + bool Elevated; + bool FileOpen; + uint64 FilePointerPosition; + HANDLE Handle; + bool IsDevice; + wstring Path; + DWORD LastError; + }; + + + 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; } + + 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 BootEncryption + { + public: + BootEncryption (HWND parent); + ~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); + void InstallBootLoader (Device& device, bool preserveUserConfig = false, bool hiddenOSCreation = false, int pim = -1); + void InstallBootLoader (bool preserveUserConfig = false, bool hiddenOSCreation = false); + 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 (); + void 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 (void); + 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 VerifyRescueDiskIsoImage (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); + void WriteLocalMachineRegistryDwordValue (wchar_t *keyPath, wchar_t *valueName, DWORD value); + + protected: + static const uint32 RescueIsoImageSize = 1835008; // Size of ISO9660 image with bootable emulated 1.44MB floppy disk image + + void BackupSystemLoader (); + 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 GetDriveGeometry (int driveNumber); + PartitionList GetDrivePartitions (int driveNumber); + wstring GetRemarksOnHiddenOS (); + wstring GetWindowsDirectory (); + void RegisterFilter (bool registerFilter, FilterType filterType, const GUID *deviceClassGuid = nullptr); + void RestoreSystemLoader (); + void InstallVolumeHeader (); + + HWND ParentWindow; + SystemDriveConfiguration DriveConfig; + int SelectedEncryptionAlgorithmId; + int SelectedPrfAlgorithmId; + Partition HiddenOSCandidatePartition; + byte *RescueIsoImage; + byte RescueVolumeHeader[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE]; + byte VolumeHeader[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE]; + bool DriveConfigValid; + bool RealSystemDriveSizeValid; + bool RescueVolumeHeaderValid; + bool VolumeHeaderValid; + }; +} + +#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" + +#endif // TC_HEADER_Common_BootEncryption diff --git a/src/Common/Cache.c b/src/Common/Cache.c index e32896fa..ba6c6df8 100644 --- a/src/Common/Cache.c +++ b/src/Common/Cache.c @@ -1,115 +1,115 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" -#include "Crypto.h" -#include "Fat.h" -#include "Volumes.h" -#include "Apidrvr.h" -#include "Common.h" -#include "Cache.h" - -Password CachedPasswords[CACHE_SIZE]; -int CachedPim[CACHE_SIZE]; -int cacheEmpty = 1; -static int nPasswordIdx = 0; - -int ReadVolumeHeaderWCache (BOOL bBoot, BOOL bCache, BOOL bCachePim, char *header, Password *password, int pkcs5_prf, int pim, BOOL truecryptMode, PCRYPTO_INFO *retInfo) -{ - int nReturnCode = ERR_PASSWORD_WRONG; - int i, effectivePim; - - /* Attempt to recognize volume using mount password */ - if (password->Length > 0) - { - nReturnCode = ReadVolumeHeader (bBoot, header, password, pkcs5_prf, pim, truecryptMode, retInfo, NULL); - - /* Save mount passwords back into cache if asked to do so */ - if (bCache && (nReturnCode == 0 || nReturnCode == ERR_CIPHER_INIT_WEAK_KEY)) - { - for (i = 0; i < CACHE_SIZE; i++) - { - if (memcmp (&CachedPasswords[i], password, sizeof (Password)) == 0) - break; - } - - if (i == CACHE_SIZE) - { - /* Store the password */ - CachedPasswords[nPasswordIdx] = *password; - - /* Store also PIM if requested, otherwise set to default */ - if (bCachePim && (pim > 0)) - CachedPim[nPasswordIdx] = pim; - else - CachedPim[nPasswordIdx] = 0; - - /* Try another slot */ - nPasswordIdx = (nPasswordIdx + 1) % CACHE_SIZE; - - cacheEmpty = 0; - } - else if (bCachePim) - { - CachedPim[i] = pim > 0? pim : 0; - } - } - } - else if (!cacheEmpty) - { - /* Attempt to recognize volume using cached passwords */ - for (i = 0; i < CACHE_SIZE; i++) - { - if (CachedPasswords[i].Length > 0) - { - if (truecryptMode) - effectivePim = 0; - else if (pim == -1) - effectivePim = CachedPim[i]; - else - effectivePim = pim; - nReturnCode = ReadVolumeHeader (bBoot, header, &CachedPasswords[i], pkcs5_prf, effectivePim, truecryptMode, retInfo, NULL); - - if (nReturnCode != ERR_PASSWORD_WRONG) - break; - } - } - } - - return nReturnCode; -} - - -void AddPasswordToCache (Password *password, int pim) -{ - int i; - for (i = 0; i < CACHE_SIZE; i++) - { - if (memcmp (&CachedPasswords[i], password, sizeof (Password)) == 0) - return; - } - - CachedPasswords[nPasswordIdx] = *password; - CachedPim[nPasswordIdx] = pim > 0? pim : 0; - nPasswordIdx = (nPasswordIdx + 1) % CACHE_SIZE; - cacheEmpty = 0; -} - - -void WipeCache () -{ - burn (CachedPasswords, sizeof (CachedPasswords)); - burn (CachedPim, sizeof (CachedPim)); - nPasswordIdx = 0; - cacheEmpty = 1; -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" +#include "Crypto.h" +#include "Fat.h" +#include "Volumes.h" +#include "Apidrvr.h" +#include "Common.h" +#include "Cache.h" + +Password CachedPasswords[CACHE_SIZE]; +int CachedPim[CACHE_SIZE]; +int cacheEmpty = 1; +static int nPasswordIdx = 0; + +int ReadVolumeHeaderWCache (BOOL bBoot, BOOL bCache, BOOL bCachePim, char *header, Password *password, int pkcs5_prf, int pim, BOOL truecryptMode, PCRYPTO_INFO *retInfo) +{ + int nReturnCode = ERR_PASSWORD_WRONG; + int i, effectivePim; + + /* Attempt to recognize volume using mount password */ + if (password->Length > 0) + { + nReturnCode = ReadVolumeHeader (bBoot, header, password, pkcs5_prf, pim, truecryptMode, retInfo, NULL); + + /* Save mount passwords back into cache if asked to do so */ + if (bCache && (nReturnCode == 0 || nReturnCode == ERR_CIPHER_INIT_WEAK_KEY)) + { + for (i = 0; i < CACHE_SIZE; i++) + { + if (memcmp (&CachedPasswords[i], password, sizeof (Password)) == 0) + break; + } + + if (i == CACHE_SIZE) + { + /* Store the password */ + CachedPasswords[nPasswordIdx] = *password; + + /* Store also PIM if requested, otherwise set to default */ + if (bCachePim && (pim > 0)) + CachedPim[nPasswordIdx] = pim; + else + CachedPim[nPasswordIdx] = 0; + + /* Try another slot */ + nPasswordIdx = (nPasswordIdx + 1) % CACHE_SIZE; + + cacheEmpty = 0; + } + else if (bCachePim) + { + CachedPim[i] = pim > 0? pim : 0; + } + } + } + else if (!cacheEmpty) + { + /* Attempt to recognize volume using cached passwords */ + for (i = 0; i < CACHE_SIZE; i++) + { + if (CachedPasswords[i].Length > 0) + { + if (truecryptMode) + effectivePim = 0; + else if (pim == -1) + effectivePim = CachedPim[i]; + else + effectivePim = pim; + nReturnCode = ReadVolumeHeader (bBoot, header, &CachedPasswords[i], pkcs5_prf, effectivePim, truecryptMode, retInfo, NULL); + + if (nReturnCode != ERR_PASSWORD_WRONG) + break; + } + } + } + + return nReturnCode; +} + + +void AddPasswordToCache (Password *password, int pim) +{ + int i; + for (i = 0; i < CACHE_SIZE; i++) + { + if (memcmp (&CachedPasswords[i], password, sizeof (Password)) == 0) + return; + } + + CachedPasswords[nPasswordIdx] = *password; + CachedPim[nPasswordIdx] = pim > 0? pim : 0; + nPasswordIdx = (nPasswordIdx + 1) % CACHE_SIZE; + cacheEmpty = 0; +} + + +void WipeCache () +{ + burn (CachedPasswords, sizeof (CachedPasswords)); + burn (CachedPim, sizeof (CachedPim)); + nPasswordIdx = 0; + cacheEmpty = 1; +} diff --git a/src/Common/Cache.h b/src/Common/Cache.h index 05f0ba04..c4587d03 100644 --- a/src/Common/Cache.h +++ b/src/Common/Cache.h @@ -1,25 +1,25 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Common.h" - -#ifndef CACHE_SIZE -/* WARNING: Changing this value might not be safe (some items may be hard coded for 4)! Inspection necessary. */ -#define CACHE_SIZE 4 -#endif - -extern int cacheEmpty; - -void AddPasswordToCache (Password *password, int pim); -int ReadVolumeHeaderWCache (BOOL bBoot, BOOL bCache, BOOL bCachePim,char *header, Password *password, int pkcs5_prf, int pim, BOOL truecryptMode, PCRYPTO_INFO *retInfo); -void WipeCache (void); +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Common.h" + +#ifndef CACHE_SIZE +/* WARNING: Changing this value might not be safe (some items may be hard coded for 4)! Inspection necessary. */ +#define CACHE_SIZE 4 +#endif + +extern int cacheEmpty; + +void AddPasswordToCache (Password *password, int pim); +int ReadVolumeHeaderWCache (BOOL bBoot, BOOL bCache, BOOL bCachePim,char *header, Password *password, int pkcs5_prf, int pim, BOOL truecryptMode, PCRYPTO_INFO *retInfo); +void WipeCache (void); diff --git a/src/Common/Cmdline.c b/src/Common/Cmdline.c index 759c63f5..4a055c16 100644 --- a/src/Common/Cmdline.c +++ b/src/Common/Cmdline.c @@ -1,184 +1,184 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" - -#include -#include -#include "Cmdline.h" - -#include "Resource.h" -#include "Crypto.h" -#include "Apidrvr.h" -#include "Dlgcode.h" -#include "Language.h" -#include - -#ifndef SRC_POS -#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) -#endif - -/* Except in response to the WM_INITDIALOG message, the dialog box procedure - should return nonzero if it processes the message, and zero if it does - not. - see DialogProc */ -BOOL CALLBACK CommandHelpDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - UNREFERENCED_PARAMETER (lParam); /* remove warning */ - UNREFERENCED_PARAMETER (wParam); /* remove warning */ - - switch (msg) - { - case WM_INITDIALOG: - { - wchar_t * tmp = err_malloc(8192 * sizeof (wchar_t)); - wchar_t tmp2[MAX_PATH * 2]; - argumentspec *as; - int i; - - LocalizeDialog (hwndDlg, "IDD_COMMANDHELP_DLG"); - - as = (argumentspec*) lParam; - - *tmp = 0; - - StringCchCopyW (tmp, 8192, L"VeraCrypt " _T(VERSION_STRING)); -#ifdef _WIN64 - StringCchCatW (tmp, 8192, L" (64-bit)"); -#else - StringCchCatW (tmp, 8192, L" (32-bit)"); -#endif -#if (defined(_DEBUG) || defined(DEBUG)) - StringCchCatW (tmp, 8192, L" (debug)"); -#endif - - StringCchCatW (tmp, 8192, L"\n\nCommand line options:\n\n"); - for (i = 0; i < as->arg_cnt; i ++) - { - if (!as->args[i].Internal) - { - StringCchPrintfW(tmp2, MAX_PATH * 2, L"%s\t%s\n", as->args[i].short_name, as->args[i].long_name); - StringCchCatW(tmp, 8192, tmp2); - } - } - - StringCchCatW (tmp, 8192, L"\nExamples:\n\nMount a volume as X:\tveracrypt.exe /q /v volume.hc /l X\nDismount a volume X:\tveracrypt.exe /q /d X"); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_COMMANDHELP_TEXT), tmp); - - TCfree(tmp); - return 1; - } - - case WM_COMMAND: - EndDialog (hwndDlg, IDOK); - return 1; - case WM_CLOSE: - EndDialog (hwndDlg, 0); - return 1; - } - - return 0; -} - -int Win32CommandLine (wchar_t ***lpszArgs) -{ - int argumentCount; - int i; - - LPWSTR *arguments = CommandLineToArgvW (GetCommandLineW(), &argumentCount); - if (!arguments) - { - handleWin32Error (NULL, SRC_POS); - return 0; - } - - --argumentCount; - if (argumentCount < 1) - { - LocalFree (arguments); - return 0; - } - - *lpszArgs = malloc (sizeof (wchar_t *) * argumentCount); - if (!*lpszArgs) - AbortProcess ("OUTOFMEMORY"); - - for (i = 0; i < argumentCount; ++i) - { - wchar_t *arg = _wcsdup (arguments[i + 1]); - if (!arg) - AbortProcess ("OUTOFMEMORY"); - - (*lpszArgs)[i] = arg; - } - - LocalFree (arguments); - return argumentCount; -} - -int GetArgSepPosOffset (wchar_t *lpszArgument) -{ - if (lpszArgument[0] == L'/') - return 1; - - return 0; -} - -int GetArgumentID (argumentspec *as, wchar_t *lpszArgument) -{ - int i; - - for (i = 0; i < as->arg_cnt; i++) - { - if (_wcsicmp (as->args[i].long_name, lpszArgument) == 0) - { - return as->args[i].Id; - } - } - - for (i = 0; i < as->arg_cnt; i++) - { - if (as->args[i].short_name[0] == 0) - continue; - - if (_wcsicmp (as->args[i].short_name, lpszArgument) == 0) - { - return as->args[i].Id; - } - } - - - return -1; -} - -int GetArgumentValue (wchar_t **lpszCommandLineArgs, int *nArgIdx, - int nNoCommandLineArgs, wchar_t *lpszValue, int nValueSize) -{ - *lpszValue = 0; - - if (*nArgIdx + 1 < nNoCommandLineArgs) - { - int x = GetArgSepPosOffset (lpszCommandLineArgs[*nArgIdx + 1]); - if (x == 0) - { - /* Handles the case of space between parameter code - and value */ - StringCchCopyW (lpszValue, nValueSize, lpszCommandLineArgs[*nArgIdx + 1]); - lpszValue[nValueSize - 1] = 0; - (*nArgIdx)++; - return HAS_ARGUMENT; - } - } - - return HAS_NO_ARGUMENT; -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" + +#include +#include +#include "Cmdline.h" + +#include "Resource.h" +#include "Crypto.h" +#include "Apidrvr.h" +#include "Dlgcode.h" +#include "Language.h" +#include + +#ifndef SRC_POS +#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) +#endif + +/* Except in response to the WM_INITDIALOG message, the dialog box procedure + should return nonzero if it processes the message, and zero if it does + not. - see DialogProc */ +BOOL CALLBACK CommandHelpDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + UNREFERENCED_PARAMETER (lParam); /* remove warning */ + UNREFERENCED_PARAMETER (wParam); /* remove warning */ + + switch (msg) + { + case WM_INITDIALOG: + { + wchar_t * tmp = err_malloc(8192 * sizeof (wchar_t)); + wchar_t tmp2[MAX_PATH * 2]; + argumentspec *as; + int i; + + LocalizeDialog (hwndDlg, "IDD_COMMANDHELP_DLG"); + + as = (argumentspec*) lParam; + + *tmp = 0; + + StringCchCopyW (tmp, 8192, L"VeraCrypt " _T(VERSION_STRING)); +#ifdef _WIN64 + StringCchCatW (tmp, 8192, L" (64-bit)"); +#else + StringCchCatW (tmp, 8192, L" (32-bit)"); +#endif +#if (defined(_DEBUG) || defined(DEBUG)) + StringCchCatW (tmp, 8192, L" (debug)"); +#endif + + StringCchCatW (tmp, 8192, L"\n\nCommand line options:\n\n"); + for (i = 0; i < as->arg_cnt; i ++) + { + if (!as->args[i].Internal) + { + StringCchPrintfW(tmp2, MAX_PATH * 2, L"%s\t%s\n", as->args[i].short_name, as->args[i].long_name); + StringCchCatW(tmp, 8192, tmp2); + } + } + + StringCchCatW (tmp, 8192, L"\nExamples:\n\nMount a volume as X:\tveracrypt.exe /q /v volume.hc /l X\nDismount a volume X:\tveracrypt.exe /q /d X"); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_COMMANDHELP_TEXT), tmp); + + TCfree(tmp); + return 1; + } + + case WM_COMMAND: + EndDialog (hwndDlg, IDOK); + return 1; + case WM_CLOSE: + EndDialog (hwndDlg, 0); + return 1; + } + + return 0; +} + +int Win32CommandLine (wchar_t ***lpszArgs) +{ + int argumentCount; + int i; + + LPWSTR *arguments = CommandLineToArgvW (GetCommandLineW(), &argumentCount); + if (!arguments) + { + handleWin32Error (NULL, SRC_POS); + return 0; + } + + --argumentCount; + if (argumentCount < 1) + { + LocalFree (arguments); + return 0; + } + + *lpszArgs = malloc (sizeof (wchar_t *) * argumentCount); + if (!*lpszArgs) + AbortProcess ("OUTOFMEMORY"); + + for (i = 0; i < argumentCount; ++i) + { + wchar_t *arg = _wcsdup (arguments[i + 1]); + if (!arg) + AbortProcess ("OUTOFMEMORY"); + + (*lpszArgs)[i] = arg; + } + + LocalFree (arguments); + return argumentCount; +} + +int GetArgSepPosOffset (wchar_t *lpszArgument) +{ + if (lpszArgument[0] == L'/') + return 1; + + return 0; +} + +int GetArgumentID (argumentspec *as, wchar_t *lpszArgument) +{ + int i; + + for (i = 0; i < as->arg_cnt; i++) + { + if (_wcsicmp (as->args[i].long_name, lpszArgument) == 0) + { + return as->args[i].Id; + } + } + + for (i = 0; i < as->arg_cnt; i++) + { + if (as->args[i].short_name[0] == 0) + continue; + + if (_wcsicmp (as->args[i].short_name, lpszArgument) == 0) + { + return as->args[i].Id; + } + } + + + return -1; +} + +int GetArgumentValue (wchar_t **lpszCommandLineArgs, int *nArgIdx, + int nNoCommandLineArgs, wchar_t *lpszValue, int nValueSize) +{ + *lpszValue = 0; + + if (*nArgIdx + 1 < nNoCommandLineArgs) + { + int x = GetArgSepPosOffset (lpszCommandLineArgs[*nArgIdx + 1]); + if (x == 0) + { + /* Handles the case of space between parameter code + and value */ + StringCchCopyW (lpszValue, nValueSize, lpszCommandLineArgs[*nArgIdx + 1]); + lpszValue[nValueSize - 1] = 0; + (*nArgIdx)++; + return HAS_ARGUMENT; + } + } + + return HAS_NO_ARGUMENT; +} diff --git a/src/Common/Cmdline.h b/src/Common/Cmdline.h index 3088d563..51c173c6 100644 --- a/src/Common/Cmdline.h +++ b/src/Common/Cmdline.h @@ -1,43 +1,43 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifdef __cplusplus -extern "C" { -#endif - -#define HAS_ARGUMENT 1 -#define HAS_NO_ARGUMENT !HAS_ARGUMENT - -typedef struct argument_t -{ - int Id; - wchar_t long_name[32]; - wchar_t short_name[8]; - BOOL Internal; -} argument; - -typedef struct argumentspec_t -{ - argument *args; - int arg_cnt; -} argumentspec; - -BOOL CALLBACK CommandHelpDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); -int Win32CommandLine ( wchar_t ***lpszArgs ); -int GetArgSepPosOffset ( wchar_t *lpszArgument ); -int GetArgumentID ( argumentspec *as , wchar_t *lpszArgument ); -int GetArgumentValue ( wchar_t **lpszCommandLineArgs , int *nArgIdx , int nNoCommandLineArgs , wchar_t *lpszValue , int nValueSize ); - -#ifdef __cplusplus -} -#endif +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define HAS_ARGUMENT 1 +#define HAS_NO_ARGUMENT !HAS_ARGUMENT + +typedef struct argument_t +{ + int Id; + wchar_t long_name[32]; + wchar_t short_name[8]; + BOOL Internal; +} argument; + +typedef struct argumentspec_t +{ + argument *args; + int arg_cnt; +} argumentspec; + +BOOL CALLBACK CommandHelpDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); +int Win32CommandLine ( wchar_t ***lpszArgs ); +int GetArgSepPosOffset ( wchar_t *lpszArgument ); +int GetArgumentID ( argumentspec *as , wchar_t *lpszArgument ); +int GetArgumentValue ( wchar_t **lpszCommandLineArgs , int *nArgIdx , int nNoCommandLineArgs , wchar_t *lpszValue , int nValueSize ); + +#ifdef __cplusplus +} +#endif diff --git a/src/Common/Combo.c b/src/Common/Combo.c index 0340b23a..fe456853 100644 --- a/src/Common/Combo.c +++ b/src/Common/Combo.c @@ -1,258 +1,258 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" -#include "Combo.h" -#include "Dlgcode.h" -#include "Xml.h" - -#include - -#define SIZEOF_MRU_LIST 20 - -void AddComboItem (HWND hComboBox, const wchar_t *lpszFileName, BOOL saveHistory) -{ - LPARAM nIndex; - - if (!saveHistory) - { - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - SetWindowText (hComboBox, lpszFileName); - return; - } - - nIndex = SendMessage (hComboBox, CB_FINDSTRINGEXACT, (WPARAM) - 1, (LPARAM) & lpszFileName[0]); - - if (nIndex == CB_ERR && *lpszFileName) - { - time_t lTime = time (NULL); - nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) & lpszFileName[0]); - if (nIndex != CB_ERR) - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) lTime); - } - - if (nIndex != CB_ERR && *lpszFileName) - nIndex = SendMessage (hComboBox, CB_SETCURSEL, nIndex, 0); - - if (*lpszFileName == 0) - { - SendMessage (hComboBox, CB_SETCURSEL, (WPARAM) - 1, 0); - } -} - - -LPARAM MoveEditToCombo (HWND hComboBox, BOOL saveHistory) -{ - wchar_t szTmp[TC_MAX_PATH] = {0}; - - if (!saveHistory) - { - GetWindowText (hComboBox, szTmp, ARRAYSIZE (szTmp)); - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - SetWindowText (hComboBox, szTmp); - return 0; - } - - GetWindowText (hComboBox, szTmp, ARRAYSIZE (szTmp)); - - if (wcslen (szTmp) > 0) - { - LPARAM nIndex = SendMessage (hComboBox, CB_FINDSTRINGEXACT, (WPARAM) - 1, - (LPARAM) & szTmp[0]); - if (nIndex == CB_ERR) - { - time_t lTime = time (NULL); - nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) & szTmp[0]); - if (nIndex != CB_ERR) - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (DWORD) lTime); - } - else - { - time_t lTime = time (NULL); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (DWORD) lTime); - } - - return nIndex; - } - - return SendMessage (hComboBox, CB_GETCURSEL, 0, 0); -} - -int GetOrderComboIdx (HWND hComboBox, int *nIdxList, int nElems) -{ - int x = (int) SendMessage (hComboBox, CB_GETCOUNT, 0, 0); - if (x != CB_ERR) - { - int i, nHighIdx = CB_ERR; - time_t lHighTime = -1; - - for (i = 0; i < x; i++) - { - time_t lTime = SendMessage (hComboBox, CB_GETITEMDATA, (WPARAM) i, 0); - if (lTime > lHighTime) - { - int n; - for (n = 0; n < nElems; n++) - if (nIdxList[n] == i) - break; - if (n == nElems) - { - lHighTime = lTime; - nHighIdx = i; - } - } - } - - return nHighIdx; - } - - return CB_ERR; -} - -LPARAM UpdateComboOrder (HWND hComboBox) -{ - LPARAM nIndex; - - nIndex = SendMessage (hComboBox, CB_GETCURSEL, 0, 0); - - if (nIndex != CB_ERR) - { - time_t lTime = time (NULL); - nIndex = SendMessage (hComboBox, CB_SETITEMDATA, (WPARAM) nIndex, - (LPARAM) lTime); - } - - return nIndex; -} - -void LoadCombo (HWND hComboBox, BOOL bEnabled, BOOL bOnlyCheckModified, BOOL *pbModified) -{ - DWORD size; - char *history = LoadFile (GetConfigPath (TC_APPD_FILENAME_HISTORY), &size); - char *xml = history; - char volume[MAX_PATH]; - int i, nComboIdx[SIZEOF_MRU_LIST] = {0}; - int count = SendMessage (hComboBox, CB_GETCOUNT, 0, 0); - - if (xml == NULL) - { - // No history XML file but history is enabled - if (bEnabled && pbModified) - *pbModified = TRUE; - return; - } - - if (!bEnabled && bOnlyCheckModified) - { - // History is disable but there is a history XML file - if (pbModified) - *pbModified = TRUE; - free (history); - return; - } - - - /* combo list part:- get mru items */ - for (i = 0; i < SIZEOF_MRU_LIST; i++) - nComboIdx[i] = GetOrderComboIdx (hComboBox, &nComboIdx[0], i); - - i = 0; - while (xml = XmlFindElement (xml, "volume")) - { - wchar_t szTmp[MAX_PATH] = { 0 }; - wchar_t wszVolume[MAX_PATH] = {0}; - - if (i < count) - { - if (SendMessage (hComboBox, CB_GETLBTEXTLEN, nComboIdx[i], 0) < ARRAYSIZE (szTmp)) - SendMessage (hComboBox, CB_GETLBTEXT, nComboIdx[i], (LPARAM) & szTmp[0]); - } - - XmlGetNodeText (xml, volume, sizeof (volume)); - if (0 == MultiByteToWideChar (CP_UTF8, 0, volume, -1, wszVolume, MAX_PATH)) - wszVolume [0] = 0; - if (!bOnlyCheckModified) - AddComboItem (hComboBox, wszVolume, TRUE); - - if (pbModified && wcscmp (wszVolume, szTmp)) - *pbModified = TRUE; - - xml++; - i++; - } - - if (pbModified && (i != count)) - *pbModified = TRUE; - - if (!bOnlyCheckModified) - SendMessage (hComboBox, CB_SETCURSEL, 0, 0); - - free (history); -} - -void DumpCombo (HWND hComboBox, int bClear) -{ - FILE *f; - int i, nComboIdx[SIZEOF_MRU_LIST] = {0}; - - if (bClear) - { - DeleteFile (GetConfigPath (TC_APPD_FILENAME_HISTORY)); - return; - } - - f = _wfopen (GetConfigPath (TC_APPD_FILENAME_HISTORY), L"w,ccs=UTF-8"); - if (f == NULL) return; - - XmlWriteHeader (f); - fputws (L"\n\t", f); - - /* combo list part:- get mru items */ - for (i = 0; i < SIZEOF_MRU_LIST; i++) - nComboIdx[i] = GetOrderComboIdx (hComboBox, &nComboIdx[0], i); - - /* combo list part:- write out mru items */ - for (i = 0; i < SIZEOF_MRU_LIST; i++) - { - wchar_t szTmp[MAX_PATH] = { 0 }; - - if (SendMessage (hComboBox, CB_GETLBTEXTLEN, nComboIdx[i], 0) < ARRAYSIZE (szTmp)) - SendMessage (hComboBox, CB_GETLBTEXT, nComboIdx[i], (LPARAM) & szTmp[0]); - - if (szTmp[0] != 0) - { - wchar_t q[MAX_PATH * 2] = { 0 }; - XmlQuoteTextW (szTmp, q, ARRAYSIZE (q)); - - fwprintf (f, L"\n\t\t%s", q); - } - } - - fputws (L"\n\t", f); - XmlWriteFooter (f); - fclose (f); -} - -void ClearCombo (HWND hComboBox) -{ - int i; - for (i = 0; i < SIZEOF_MRU_LIST; i++) - { - SendMessage (hComboBox, CB_DELETESTRING, 0, 0); - } -} - -int IsComboEmpty (HWND hComboBox) -{ - return SendMessage (hComboBox, CB_GETCOUNT, 0, 0) < 1; -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" +#include "Combo.h" +#include "Dlgcode.h" +#include "Xml.h" + +#include + +#define SIZEOF_MRU_LIST 20 + +void AddComboItem (HWND hComboBox, const wchar_t *lpszFileName, BOOL saveHistory) +{ + LPARAM nIndex; + + if (!saveHistory) + { + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + SetWindowText (hComboBox, lpszFileName); + return; + } + + nIndex = SendMessage (hComboBox, CB_FINDSTRINGEXACT, (WPARAM) - 1, (LPARAM) & lpszFileName[0]); + + if (nIndex == CB_ERR && *lpszFileName) + { + time_t lTime = time (NULL); + nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) & lpszFileName[0]); + if (nIndex != CB_ERR) + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) lTime); + } + + if (nIndex != CB_ERR && *lpszFileName) + nIndex = SendMessage (hComboBox, CB_SETCURSEL, nIndex, 0); + + if (*lpszFileName == 0) + { + SendMessage (hComboBox, CB_SETCURSEL, (WPARAM) - 1, 0); + } +} + + +LPARAM MoveEditToCombo (HWND hComboBox, BOOL saveHistory) +{ + wchar_t szTmp[TC_MAX_PATH] = {0}; + + if (!saveHistory) + { + GetWindowText (hComboBox, szTmp, ARRAYSIZE (szTmp)); + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + SetWindowText (hComboBox, szTmp); + return 0; + } + + GetWindowText (hComboBox, szTmp, ARRAYSIZE (szTmp)); + + if (wcslen (szTmp) > 0) + { + LPARAM nIndex = SendMessage (hComboBox, CB_FINDSTRINGEXACT, (WPARAM) - 1, + (LPARAM) & szTmp[0]); + if (nIndex == CB_ERR) + { + time_t lTime = time (NULL); + nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) & szTmp[0]); + if (nIndex != CB_ERR) + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (DWORD) lTime); + } + else + { + time_t lTime = time (NULL); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (DWORD) lTime); + } + + return nIndex; + } + + return SendMessage (hComboBox, CB_GETCURSEL, 0, 0); +} + +int GetOrderComboIdx (HWND hComboBox, int *nIdxList, int nElems) +{ + int x = (int) SendMessage (hComboBox, CB_GETCOUNT, 0, 0); + if (x != CB_ERR) + { + int i, nHighIdx = CB_ERR; + time_t lHighTime = -1; + + for (i = 0; i < x; i++) + { + time_t lTime = SendMessage (hComboBox, CB_GETITEMDATA, (WPARAM) i, 0); + if (lTime > lHighTime) + { + int n; + for (n = 0; n < nElems; n++) + if (nIdxList[n] == i) + break; + if (n == nElems) + { + lHighTime = lTime; + nHighIdx = i; + } + } + } + + return nHighIdx; + } + + return CB_ERR; +} + +LPARAM UpdateComboOrder (HWND hComboBox) +{ + LPARAM nIndex; + + nIndex = SendMessage (hComboBox, CB_GETCURSEL, 0, 0); + + if (nIndex != CB_ERR) + { + time_t lTime = time (NULL); + nIndex = SendMessage (hComboBox, CB_SETITEMDATA, (WPARAM) nIndex, + (LPARAM) lTime); + } + + return nIndex; +} + +void LoadCombo (HWND hComboBox, BOOL bEnabled, BOOL bOnlyCheckModified, BOOL *pbModified) +{ + DWORD size; + char *history = LoadFile (GetConfigPath (TC_APPD_FILENAME_HISTORY), &size); + char *xml = history; + char volume[MAX_PATH]; + int i, nComboIdx[SIZEOF_MRU_LIST] = {0}; + int count = SendMessage (hComboBox, CB_GETCOUNT, 0, 0); + + if (xml == NULL) + { + // No history XML file but history is enabled + if (bEnabled && pbModified) + *pbModified = TRUE; + return; + } + + if (!bEnabled && bOnlyCheckModified) + { + // History is disable but there is a history XML file + if (pbModified) + *pbModified = TRUE; + free (history); + return; + } + + + /* combo list part:- get mru items */ + for (i = 0; i < SIZEOF_MRU_LIST; i++) + nComboIdx[i] = GetOrderComboIdx (hComboBox, &nComboIdx[0], i); + + i = 0; + while (xml = XmlFindElement (xml, "volume")) + { + wchar_t szTmp[MAX_PATH] = { 0 }; + wchar_t wszVolume[MAX_PATH] = {0}; + + if (i < count) + { + if (SendMessage (hComboBox, CB_GETLBTEXTLEN, nComboIdx[i], 0) < ARRAYSIZE (szTmp)) + SendMessage (hComboBox, CB_GETLBTEXT, nComboIdx[i], (LPARAM) & szTmp[0]); + } + + XmlGetNodeText (xml, volume, sizeof (volume)); + if (0 == MultiByteToWideChar (CP_UTF8, 0, volume, -1, wszVolume, MAX_PATH)) + wszVolume [0] = 0; + if (!bOnlyCheckModified) + AddComboItem (hComboBox, wszVolume, TRUE); + + if (pbModified && wcscmp (wszVolume, szTmp)) + *pbModified = TRUE; + + xml++; + i++; + } + + if (pbModified && (i != count)) + *pbModified = TRUE; + + if (!bOnlyCheckModified) + SendMessage (hComboBox, CB_SETCURSEL, 0, 0); + + free (history); +} + +void DumpCombo (HWND hComboBox, int bClear) +{ + FILE *f; + int i, nComboIdx[SIZEOF_MRU_LIST] = {0}; + + if (bClear) + { + DeleteFile (GetConfigPath (TC_APPD_FILENAME_HISTORY)); + return; + } + + f = _wfopen (GetConfigPath (TC_APPD_FILENAME_HISTORY), L"w,ccs=UTF-8"); + if (f == NULL) return; + + XmlWriteHeader (f); + fputws (L"\n\t", f); + + /* combo list part:- get mru items */ + for (i = 0; i < SIZEOF_MRU_LIST; i++) + nComboIdx[i] = GetOrderComboIdx (hComboBox, &nComboIdx[0], i); + + /* combo list part:- write out mru items */ + for (i = 0; i < SIZEOF_MRU_LIST; i++) + { + wchar_t szTmp[MAX_PATH] = { 0 }; + + if (SendMessage (hComboBox, CB_GETLBTEXTLEN, nComboIdx[i], 0) < ARRAYSIZE (szTmp)) + SendMessage (hComboBox, CB_GETLBTEXT, nComboIdx[i], (LPARAM) & szTmp[0]); + + if (szTmp[0] != 0) + { + wchar_t q[MAX_PATH * 2] = { 0 }; + XmlQuoteTextW (szTmp, q, ARRAYSIZE (q)); + + fwprintf (f, L"\n\t\t%s", q); + } + } + + fputws (L"\n\t", f); + XmlWriteFooter (f); + fclose (f); +} + +void ClearCombo (HWND hComboBox) +{ + int i; + for (i = 0; i < SIZEOF_MRU_LIST; i++) + { + SendMessage (hComboBox, CB_DELETESTRING, 0, 0); + } +} + +int IsComboEmpty (HWND hComboBox) +{ + return SendMessage (hComboBox, CB_GETCOUNT, 0, 0) < 1; +} diff --git a/src/Common/Combo.h b/src/Common/Combo.h index dd181294..cacbc413 100644 --- a/src/Common/Combo.h +++ b/src/Common/Combo.h @@ -1,29 +1,29 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifdef __cplusplus -extern "C" { -#endif - -void AddComboItem (HWND hComboBox, const wchar_t *lpszFileName, BOOL saveHistory); -LPARAM MoveEditToCombo (HWND hComboBox, BOOL saveHistory); -int GetOrderComboIdx ( HWND hComboBox , int *nIdxList , int nElems ); -LPARAM UpdateComboOrder ( HWND hComboBox ); -void LoadCombo (HWND hComboBox, BOOL bEnabled, BOOL bOnlyCheckModified, BOOL *pbModified); -void DumpCombo ( HWND hComboBox , int bClear ); -void ClearCombo (HWND hComboBox); -int IsComboEmpty (HWND hComboBox); - -#ifdef __cplusplus -} -#endif +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifdef __cplusplus +extern "C" { +#endif + +void AddComboItem (HWND hComboBox, const wchar_t *lpszFileName, BOOL saveHistory); +LPARAM MoveEditToCombo (HWND hComboBox, BOOL saveHistory); +int GetOrderComboIdx ( HWND hComboBox , int *nIdxList , int nElems ); +LPARAM UpdateComboOrder ( HWND hComboBox ); +void LoadCombo (HWND hComboBox, BOOL bEnabled, BOOL bOnlyCheckModified, BOOL *pbModified); +void DumpCombo ( HWND hComboBox , int bClear ); +void ClearCombo (HWND hComboBox); +int IsComboEmpty (HWND hComboBox); + +#ifdef __cplusplus +} +#endif diff --git a/src/Common/Common.h b/src/Common/Common.h index 180cbffb..05e2e12f 100644 --- a/src/Common/Common.h +++ b/src/Common/Common.h @@ -1,95 +1,95 @@ -/* - 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. -*/ - -#ifndef COMMON_H -#define COMMON_H - -#include "Crypto.h" - -#define MIN_MOUNTED_VOLUME_DRIVE_NUMBER ('A' - 'A') -#define MAX_MOUNTED_VOLUME_DRIVE_NUMBER ('Z' - 'A') - -#define MAX_HOST_DRIVE_NUMBER 64 -#define MAX_HOST_PARTITION_NUMBER 32 - -#define VOLUME_ID_SIZE SHA256_DIGESTSIZE - -typedef enum -{ - // IMPORTANT: If you add a new item here, update IsOSVersionAtLeast(). - - WIN_UNKNOWN = 0, - WIN_31, - WIN_95, - WIN_98, - WIN_ME, - WIN_NT3, - WIN_NT4, - WIN_2000, - WIN_XP, - WIN_XP64, - WIN_SERVER_2003, - WIN_VISTA, - WIN_SERVER_2008, - WIN_7, - WIN_SERVER_2008_R2, - WIN_8, - WIN_SERVER_2012, - WIN_8_1, - WIN_SERVER_2012_R2, - WIN_10, - WIN_SERVER_2016 -} OSVersionEnum; - -/* Volume types */ -enum -{ - TC_VOLUME_TYPE_NORMAL = 0, - TC_VOLUME_TYPE_HIDDEN, - TC_VOLUME_TYPE_COUNT -}; - -/* Prop volume types */ -enum -{ - PROP_VOL_TYPE_NORMAL = 0, - PROP_VOL_TYPE_HIDDEN, - PROP_VOL_TYPE_OUTER, /* Outer/normal (hidden volume protected) */ - PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED, /* Outer/normal (hidden volume protected AND write already prevented) */ - PROP_VOL_TYPE_SYSTEM, - PROP_NBR_VOLUME_TYPES -}; - -/* Hidden volume protection status */ -enum -{ - HIDVOL_PROT_STATUS_NONE = 0, - HIDVOL_PROT_STATUS_ACTIVE, - HIDVOL_PROT_STATUS_ACTION_TAKEN /* Active + action taken (write operation has already been denied) */ -}; - -typedef struct -{ - BOOL ReadOnly; - BOOL Removable; - BOOL ProtectHiddenVolume; - BOOL PreserveTimestamp; - BOOL PartitionInInactiveSysEncScope; /* If TRUE, we are to attempt to mount a partition located on an encrypted system drive without pre-boot authentication. */ - Password ProtectedHidVolPassword; /* Password of hidden volume to protect against overwriting */ - BOOL UseBackupHeader; - BOOL RecoveryMode; - int ProtectedHidVolPkcs5Prf; - int ProtectedHidVolPim; - wchar_t Label[33]; /* maximum label length is 32 for NTFS and 11 for FAT32 */ -} MountOptions; - -#endif +/* + 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. +*/ + +#ifndef COMMON_H +#define COMMON_H + +#include "Crypto.h" + +#define MIN_MOUNTED_VOLUME_DRIVE_NUMBER ('A' - 'A') +#define MAX_MOUNTED_VOLUME_DRIVE_NUMBER ('Z' - 'A') + +#define MAX_HOST_DRIVE_NUMBER 64 +#define MAX_HOST_PARTITION_NUMBER 32 + +#define VOLUME_ID_SIZE SHA256_DIGESTSIZE + +typedef enum +{ + // IMPORTANT: If you add a new item here, update IsOSVersionAtLeast(). + + WIN_UNKNOWN = 0, + WIN_31, + WIN_95, + WIN_98, + WIN_ME, + WIN_NT3, + WIN_NT4, + WIN_2000, + WIN_XP, + WIN_XP64, + WIN_SERVER_2003, + WIN_VISTA, + WIN_SERVER_2008, + WIN_7, + WIN_SERVER_2008_R2, + WIN_8, + WIN_SERVER_2012, + WIN_8_1, + WIN_SERVER_2012_R2, + WIN_10, + WIN_SERVER_2016 +} OSVersionEnum; + +/* Volume types */ +enum +{ + TC_VOLUME_TYPE_NORMAL = 0, + TC_VOLUME_TYPE_HIDDEN, + TC_VOLUME_TYPE_COUNT +}; + +/* Prop volume types */ +enum +{ + PROP_VOL_TYPE_NORMAL = 0, + PROP_VOL_TYPE_HIDDEN, + PROP_VOL_TYPE_OUTER, /* Outer/normal (hidden volume protected) */ + PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED, /* Outer/normal (hidden volume protected AND write already prevented) */ + PROP_VOL_TYPE_SYSTEM, + PROP_NBR_VOLUME_TYPES +}; + +/* Hidden volume protection status */ +enum +{ + HIDVOL_PROT_STATUS_NONE = 0, + HIDVOL_PROT_STATUS_ACTIVE, + HIDVOL_PROT_STATUS_ACTION_TAKEN /* Active + action taken (write operation has already been denied) */ +}; + +typedef struct +{ + BOOL ReadOnly; + BOOL Removable; + BOOL ProtectHiddenVolume; + BOOL PreserveTimestamp; + BOOL PartitionInInactiveSysEncScope; /* If TRUE, we are to attempt to mount a partition located on an encrypted system drive without pre-boot authentication. */ + Password ProtectedHidVolPassword; /* Password of hidden volume to protect against overwriting */ + BOOL UseBackupHeader; + BOOL RecoveryMode; + int ProtectedHidVolPkcs5Prf; + int ProtectedHidVolPim; + wchar_t Label[33]; /* maximum label length is 32 for NTFS and 11 for FAT32 */ +} MountOptions; + +#endif diff --git a/src/Common/Common.rc b/src/Common/Common.rc index a0dbd612..1e529c63 100644 --- a/src/Common/Common.rc +++ b/src/Common/Common.rc @@ -1,603 +1,603 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_ABOUT_DLG DIALOGEX 31, 51, 292, 199 -STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "About VeraCrypt" -CLASS "VeraCryptSplashDlg" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - EDITTEXT IDC_ABOUT_CREDITS,7,111,277,45,ES_MULTILINE | WS_VSCROLL | NOT WS_TABSTOP - DEFPUSHBUTTON "OK",IDOK,230,178,52,14 - LTEXT "",IDC_HOMEPAGE,18,87,117,9,SS_NOTIFY - LTEXT "",IDT_ABOUT_RELEASE,18,71,235,8 - CONTROL IDB_TEXTUAL_LOGO_BKG,IDC_ABOUT_BKG,"Static",SS_BITMAP,0,0,12,11,WS_EX_STATICEDGE - LTEXT "",IDT_ABOUT_VERSION,18,61,161,8 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,167,291,1,WS_EX_STATICEDGE - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,169,291,1,WS_EX_STATICEDGE - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,107,291,1,WS_EX_STATICEDGE - CONTROL "",IDC_ABOUT_LOGO_AREA,"Static",SS_GRAYRECT | NOT WS_VISIBLE,0,0,293,50,WS_EX_TRANSPARENT | WS_EX_STATICEDGE - CONTROL IDB_TEXTUAL_LOGO_96DPI,IDC_TEXTUAL_LOGO_IMG,"Static",SS_BITMAP,12,26,157,16 -END - -IDD_COMMANDHELP_DLG DIALOGEX 0, 0, 249, 289 -STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Command Line Help" -CLASS "VeraCryptCustomDlg" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - DEFPUSHBUTTON "OK",IDOK,93,267,59,14 - LTEXT "",IDC_COMMANDHELP_TEXT,20,7,208,256 -END - -IDD_RAWDEVICES_DLG DIALOGEX 0, 0, 305, 209 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Select a Partition or Device" -FONT 8, "MS Shell Dlg", 400, 0, 0x0 -BEGIN - CONTROL "",IDC_DEVICELIST,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_EDITLABELS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,7,291,178 - DEFPUSHBUTTON "OK",IDOK,192,190,50,14 - PUSHBUTTON "Cancel",IDCANCEL,248,190,50,14 -END - -IDD_MOUNT_OPTIONS DIALOGEX 0, 0, 277, 231 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - Mount Options" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "Mount volume as read-&only",IDC_MOUNT_READONLY,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,11,194,10 - CONTROL "Mount volume as removable &medium",IDC_MOUNT_REMOVABLE, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,25,195,10 - CONTROL "Use backup header embedded in &volume if available",IDC_USE_EMBEDDED_HEADER_BAK, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,39,257,11 - CONTROL "Mount partition &using system encryption without pre-boot authentication",IDC_MOUNT_SYSENC_PART_WITHOUT_PBA, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,53,259,11 - EDITTEXT IDC_VOLUME_LABEL,112,67,150,14,ES_AUTOHSCROLL - CONTROL "&Protect hidden volume against damage caused by writing to outer volume",IDC_PROTECT_HIDDEN_VOL, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,16,97,252,10 - EDITTEXT IDC_PASSWORD_PROT_HIDVOL,112,115,151,14,ES_PASSWORD | ES_AUTOHSCROLL - COMBOBOX IDC_PKCS5_PRF_ID,112,136,91,90,CBS_DROPDOWNLIST | WS_TABSTOP - EDITTEXT IDC_PIM,112,156,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER | NOT WS_VISIBLE - CONTROL "Use P&IM",IDC_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,112,161,97,10 - LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,158,159,112,8,NOT WS_VISIBLE - CONTROL "&Display password",IDC_SHOW_PASSWORD_MO,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,112,174,90,10 - CONTROL "U&se keyfiles",IDC_KEYFILES_ENABLE_HIDVOL_PROT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,112,187,90,10 - PUSHBUTTON "&Keyfiles...",IDC_KEYFILES_HIDVOL_PROT,204,183,60,14 - DEFPUSHBUTTON "OK",IDOK,211,7,60,14 - PUSHBUTTON "Cancel",IDCANCEL,211,24,60,14 - LTEXT "What is hidden volume protection?",IDC_LINK_HIDVOL_PROTECTION_INFO,16,202,247,10,SS_NOTIFY - RTEXT "P&assword to hidden volume:\n(if empty, cache is used)",IDT_HIDDEN_PROT_PASSWD,15,114,91,17,0,WS_EX_RIGHT - GROUPBOX "Hidden Volume Protection",IDT_HIDDEN_VOL_PROTECTION,6,83,265,136 - RTEXT "PKCS-5 PRF:",IDT_PKCS5_PRF,15,137,91,17 - RTEXT "Volume PIM:",IDT_PIM,15,159,91,17,NOT WS_VISIBLE - LTEXT "Volume Label in Windows:",IDT_VOLUME_LABEL,12,70,95,8 -END - -IDD_KEYFILES DIALOGEX 0, 0, 363, 251 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - Keyfiles" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "",IDC_KEYLIST,"SysListView32",LVS_REPORT | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,8,275,118 - PUSHBUTTON "Add &Files...",IDC_KEYADD,7,132,61,14 - PUSHBUTTON "Add &Path...",IDC_ADD_KEYFILE_PATH,79,132,61,14 - PUSHBUTTON "Add &Token Files...",IDC_TOKEN_FILES_ADD,151,132,65,14 - PUSHBUTTON "&Remove",IDC_KEYREMOVE,227,132,61,14 - PUSHBUTTON "Remove &All",IDC_KEYREMOVEALL,299,132,61,14 - CONTROL "U&se keyfiles",IDC_KEYFILES_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,232,105,11 - PUSHBUTTON "&Generate Random Keyfile...",IDC_GENERATE_KEYFILE,237,230,123,14 - DEFPUSHBUTTON "OK",IDOK,290,8,70,14 - PUSHBUTTON "Cancel",IDCANCEL,290,25,70,14 - LTEXT "",IDT_KEYFILES_NOTE,10,161,346,41,0,WS_EX_TRANSPARENT - LTEXT "WARNING: If you lose a keyfile or if any bit of its first 1024 kilobytes changes, it will be impossible to mount volumes that use the keyfile!",IDT_KEYFILE_WARNING,290,44,69,85,0,WS_EX_TRANSPARENT - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,2,154,361,1,WS_EX_STATICEDGE - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,2,209,361,1,WS_EX_STATICEDGE - LTEXT "More information on keyfiles",IDC_LINK_KEYFILES_INFO,119,233,113,10,SS_NOTIFY - CONTROL "Try first to mount with an empty password",IDC_KEYFILES_TRY_EMPTY_PASSWORD, - "Button",BS_AUTOCHECKBOX | NOT WS_VISIBLE | WS_TABSTOP,7,217,310,10 -END - -IDD_LANGUAGE DIALOGEX 0, 0, 209, 183 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - Language" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - LISTBOX IDC_LANGLIST,6,7,197,67,LBS_SORT | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP - EDITTEXT IDC_LANGPACK_CREDITS,6,108,197,28,ES_MULTILINE | ES_READONLY | WS_VSCROLL | NOT WS_TABSTOP - CTEXT "Download language pack",IDC_GET_LANG_PACKS,2,146,205,10,SS_NOTIFY - DEFPUSHBUTTON "OK",IDOK,97,165,50,14 - PUSHBUTTON "Cancel",IDCANCEL,153,165,50,14 - LTEXT "Translated by:",IDT_LANGPACK_AUTHORS,6,99,101,9,SS_NOTIFY,WS_EX_TRANSPARENT - RTEXT "",IDC_LANGPACK_VERSION,79,86,118,11 - GROUPBOX "Active language pack",IDT_ACTIVE_LANG_PACK,0,77,209,65 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,158,208,1,WS_EX_STATICEDGE -END - -IDD_BENCHMARK_DLG DIALOGEX 0, 0, 330, 223 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - Encryption Algorithm Benchmark" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - COMBOBOX IDC_BENCHMARK_BUFFER_SIZE,55,7,77,129,CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP - COMBOBOX IDC_BENCHMARK_SORT_METHOD,207,7,116,74,CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP - CONTROL "",IDC_RESULTS,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,37,249,160 - DEFPUSHBUTTON "Benchmark",IDC_PERFORM_BENCHMARK,265,37,58,14 - PUSHBUTTON "Close",IDCLOSE,265,55,58,14 - LTEXT "Hardware-accelerated AES:",IDC_HW_AES_LABEL_LINK,148,210,108,9,SS_NOTIFY,WS_EX_RIGHT - CONTROL "",IDC_HW_AES,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,262,209,57,11,WS_EX_STATICEDGE - LTEXT "Parallelization:",IDC_PARALLELIZATION_LABEL_LINK,4,210,67,9,SS_NOTIFY,WS_EX_RIGHT - CONTROL "",IDC_PARALLELIZATION,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,77,209,57,11,WS_EX_STATICEDGE - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,2,29,328,1,WS_EX_STATICEDGE - LTEXT "Buffer Size:",IDT_BUFFER_SIZE,0,9,53,8,0,WS_EX_RIGHT - LTEXT "Sort Method:",IDT_SORT_METHOD,135,9,70,8,0,WS_EX_RIGHT - LTEXT "Speed is affected by CPU load and storage device characteristics.\n\nThese tests take place in RAM.",IDT_BOX_BENCHMARK_INFO,266,81,57,116 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,2,205,328,1,WS_EX_STATICEDGE -END - -IDD_CIPHER_TEST_DLG DIALOGEX 0, 0, 326, 249 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - Test Vectors" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - COMBOBOX IDC_CIPHER,109,10,104,126,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP - EDITTEXT IDC_KEY,8,36,309,14,ES_AUTOHSCROLL - COMBOBOX IDC_KEY_SIZE,67,55,42,68,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP - EDITTEXT IDC_SECONDARY_KEY,8,93,309,14,ES_AUTOHSCROLL - EDITTEXT IDC_TEST_DATA_UNIT_NUMBER,8,118,84,14,ES_AUTOHSCROLL - CONTROL "XTS mode",IDC_XTS_MODE_ENABLED,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,221,12,95,10 - EDITTEXT IDC_PLAINTEXT,8,151,159,14,ES_AUTOHSCROLL - COMBOBOX IDC_PLAINTEXT_SIZE,258,151,36,30,CBS_DROPDOWNLIST | WS_DISABLED | WS_VSCROLL | WS_TABSTOP - EDITTEXT IDC_CIPHERTEXT,8,185,159,14,ES_AUTOHSCROLL - DEFPUSHBUTTON "&Encrypt",IDC_ENCRYPT,8,229,52,14 - PUSHBUTTON "&Decrypt",IDC_DECRYPT,65,229,52,14 - PUSHBUTTON "&Auto-Test All",IDC_AUTO,129,229,67,14,BS_MULTILINE - PUSHBUTTON "&Reset",IDC_RESET,208,229,52,14 - PUSHBUTTON "Close",IDCLOSE,266,229,52,14 - GROUPBOX "Key (hexadecimal)",IDT_TEST_KEY,1,26,323,49 - GROUPBOX "Plaintext (hexadecimal)",IDT_TEST_PLAINTEXT,1,140,323,33 - GROUPBOX "Ciphertext (hexadecimal)",IDT_TEST_CIPHERTEXT,1,174,323,33 - RTEXT "",IDC_TESTS_MESSAGE,50,213,178,10 - CONTROL "",IDC_REDTICK,"VCREDTICK",0x0,234,214,10,8 - RTEXT "Key size:",IDT_KEY,8,57,56,8 - RTEXT "Plaintext size:",IDT_PLAINTEXT,174,153,79,8 - LTEXT "bits",IDT_KEY_UNIT,114,57,45,8 - RTEXT "Cipher:",IDT_CIPHER,38,13,68,8 - LTEXT "bits",IDT_PLAINTEXT_SIZE_UNIT,298,153,22,8 - GROUPBOX "XTS mode",IDT_XTS_MODE,1,75,323,65 - LTEXT "Secondary key (hexadecimal)",IDT_SECONDARY_KEY,8,84,187,8 - LTEXT "Data unit number (64-bit hexadecimal, data unit size is 512 bytes)",IDT_TEST_DATA_UNIT_NUMBER,8,109,308,8 - RTEXT "Block number:",IDT_TEST_BLOCK_NUMBER,134,122,119,8 - COMBOBOX IDC_TEST_BLOCK_NUMBER,258,119,36,126,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP -END - -IDD_TEXT_INFO_DIALOG_BOX_DLG DIALOGEX 0, 0, 372, 220 -STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - DEFPUSHBUTTON "OK",IDOK,305,200,58,14 - PUSHBUTTON "&Print",IDC_PRINT,156,200,58,14 - CONTROL "",IDC_INFO_BOX_TEXT,"RichEdit20W",ES_MULTILINE | ES_READONLY | ES_NUMBER | WS_BORDER | WS_VSCROLL | WS_TABSTOP,5,6,361,188 -END - -IDD_KEYFILE_GENERATOR DIALOGEX 0, 0, 357, 362 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - Keyfile Generator" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - DEFPUSHBUTTON "Close",IDCLOSE,291,10,59,14 - COMBOBOX IDC_PRF_ID,97,49,91,90,CBS_DROPDOWNLIST | WS_TABSTOP - CONTROL "Display pool content",IDC_DISPLAY_POOL_CONTENTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,209,51,141,10 - EDITTEXT IDC_NUMBER_KEYFILES,124,278,51,14,ES_RIGHT | ES_AUTOHSCROLL | ES_NUMBER - EDITTEXT IDC_KEYFILES_SIZE,124,298,51,14,ES_RIGHT | ES_AUTOHSCROLL | ES_NUMBER - CONTROL "Random size ( 64 <-> 1048576 )",IDC_KEYFILES_RANDOM_SIZE, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,181,300,174,10 - EDITTEXT IDC_KEYFILES_BASE_NAME,124,318,141,14,ES_AUTOHSCROLL - PUSHBUTTON "Generate and Save Keyfile...",IDC_GENERATE_AND_SAVE_KEYFILE,124,336,141,14 - LTEXT "IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the keyfile.",IDT_KEYFILE_GENERATOR_NOTE,11,5,271,33 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,40,356,1,WS_EX_STATICEDGE - RTEXT "Mixing PRF:",IDT_PRF,7,51,85,10,SS_CENTERIMAGE - GROUPBOX "Current Pool Content",IDT_POOL_CONTENTS,6,70,344,170 - CTEXT "",IDC_POOL_CONTENTS,16,83,323,148,0,WS_EX_TRANSPARENT - RTEXT "Number of keyfiles:",IDT_NUMBER_KEYFILES,9,281,110,8 - RTEXT "Keyfiles base name:",IDT_KEYFILES_BASE_NAME,9,321,110,8 - RTEXT "Keyfiles size (in Bytes):",IDT_KEYFILES_SIZE,9,300,110,8 - CONTROL "",IDC_ENTROPY_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,18,255,321,12 - GROUPBOX "Randomness Collected From Mouse Movements",IDT_ENTROPY_BAR,6,244,344,29 -END - -IDD_MULTI_CHOICE_DLG DIALOGEX 0, 0, 167, 322 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - PUSHBUTTON "",IDC_CHOICE10,7,292,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE - PUSHBUTTON "",IDC_CHOICE9,7,268,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE - PUSHBUTTON "",IDC_CHOICE8,7,244,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE - PUSHBUTTON "",IDC_CHOICE7,7,220,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE - PUSHBUTTON "",IDC_CHOICE6,7,196,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE - PUSHBUTTON "",IDC_CHOICE5,7,172,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE - PUSHBUTTON "",IDC_CHOICE4,7,148,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE - PUSHBUTTON "",IDC_CHOICE3,7,124,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE - PUSHBUTTON "",IDC_CHOICE2,7,100,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE - PUSHBUTTON "",IDC_CHOICE1,7,76,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE - LTEXT "",IDC_MULTI_CHOICE_MSG,7,7,153,56,0,WS_EX_TRANSPARENT - CONTROL "",IDC_MC_DLG_HR2,"Static",SS_ETCHEDHORZ,0,69,168,1,WS_EX_STATICEDGE - CONTROL "",IDC_MC_DLG_HR1,"Static",SS_ETCHEDHORZ,0,1,168,1,WS_EX_STATICEDGE -END - -IDD_AUXILIARY_DLG DIALOGEX 0, 0, 426, 296 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_NOFAILCREATE | WS_POPUP -EXSTYLE WS_EX_TRANSPARENT -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - LTEXT "",IDC_ASPECT_RATIO_CALIBRATION_BOX,3,2,282,282,WS_DISABLED -END - -IDD_TOKEN_PASSWORD DIALOGEX 0, 0, 281, 47 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Security token password/PIN required" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - EDITTEXT IDC_TOKEN_PASSWORD,8,20,199,14,ES_PASSWORD | ES_AUTOHSCROLL - DEFPUSHBUTTON "OK",IDOK,215,7,59,14 - PUSHBUTTON "Cancel",IDCANCEL,215,25,59,14 - LTEXT "",IDT_TOKEN_PASSWORD_INFO,9,8,196,8 -END - -IDD_TOKEN_KEYFILES DIALOGEX 0, 0, 337, 185 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Security Token Keyfiles" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "",IDC_TOKEN_FILE_LIST,"SysListView32",LVS_REPORT | LVS_SHOWSELALWAYS | LVS_EDITLABELS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,7,256,152 - PUSHBUTTON "&Export...",IDC_EXPORT,7,164,55,14 - PUSHBUTTON "&Delete",IDC_DELETE,66,164,55,14 - PUSHBUTTON "&Import Keyfile to Token...",IDC_IMPORT_KEYFILE,126,164,137,14 - DEFPUSHBUTTON "OK",IDOK,271,7,59,14 - PUSHBUTTON "Cancel",IDCANCEL,271,25,59,14 -END - -IDD_NEW_TOKEN_KEYFILE DIALOGEX 0, 0, 239, 82 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "New Security Token Keyfile Properties" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - DEFPUSHBUTTON "OK",IDOK,128,61,50,14 - PUSHBUTTON "Cancel",IDCANCEL,183,61,50,14 - COMBOBOX IDC_SELECTED_TOKEN,77,13,140,43,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP - LTEXT "Security token:",IDT_SECURITY_TOKEN,11,15,62,8,0,WS_EX_RIGHT - LTEXT "Keyfile name:",IDT_TOKEN_KEYFILE_NAME,12,34,61,8,0,WS_EX_RIGHT - EDITTEXT IDC_TOKEN_KEYFILE_NAME,77,32,140,13,ES_AUTOHSCROLL - GROUPBOX "",IDC_STATIC,5,2,228,51 -END - -IDD_RANDOM_POOL_ENRICHMENT DIALOGEX 0, 0, 308, 301 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - Random Pool Enrichment" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - DEFPUSHBUTTON "&Continue",IDC_CONTINUE,119,278,71,14 - COMBOBOX IDC_PRF_ID,79,49,91,90,CBS_DROPDOWNLIST | WS_TABSTOP - LTEXT "IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases security. When done, click 'Continue'.",IDT_RANDOM_POOL_ENRICHMENT_NOTE,11,6,282,25 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,37,307,1,WS_EX_STATICEDGE - RTEXT "Mixing PRF:",IDT_PRF,6,51,67,10,SS_CENTERIMAGE - GROUPBOX "Current Pool Content",IDT_POOL_CONTENTS,6,70,296,170 - CONTROL "",IDC_POOL_CONTENTS,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,16,83,282,148,WS_EX_TRANSPARENT - CONTROL "Display pool content",IDC_DISPLAY_POOL_CONTENTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,191,51,111,10 - CONTROL "",IDC_ENTROPY_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,16,255,275,12 - GROUPBOX "Randomness Collected From Mouse Movements",IDT_ENTROPY_BAR,7,244,294,29 -END - -IDD_STATIC_MODELESS_WAIT_DLG DIALOGEX 0, 0, 292, 42 -STYLE DS_SYSMODAL | DS_SETFONT | DS_MODALFRAME | DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION -EXSTYLE WS_EX_TOPMOST | WS_EX_TOOLWINDOW -CAPTION "VeraCrypt" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - LTEXT "Please wait. This process may take a long time...",IDT_STATIC_MODELESS_WAIT_DLG_INFO,9,8,274,9 -END - -IDD_STATIC_MODAL_WAIT_DLG DIALOGEX 0, 0, 292, 74 -STYLE DS_SETFONT | DS_MODALFRAME | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION -CAPTION "VeraCrypt" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - CTEXT "Please wait...\nThis process may take a long time and VeraCrypt may seem unresponsive.",IDT_STATIC_MODAL_WAIT_DLG_INFO,9,11,274,33 - CONTROL "",IDC_WAIT_PROGRESS_BAR,"msctls_progress32",WS_BORDER,7,49,278,14 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_ABOUT_DLG, DIALOG - BEGIN - END - - IDD_COMMANDHELP_DLG, DIALOG - BEGIN - BOTTOMMARGIN, 281 - END - - IDD_RAWDEVICES_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 298 - TOPMARGIN, 7 - BOTTOMMARGIN, 205 - END - - IDD_MOUNT_OPTIONS, DIALOG - BEGIN - LEFTMARGIN, 7 - TOPMARGIN, 7 - BOTTOMMARGIN, 225 - END - - IDD_KEYFILES, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 345 - TOPMARGIN, 7 - BOTTOMMARGIN, 244 - END - - IDD_LANGUAGE, DIALOG - BEGIN - LEFTMARGIN, 6 - RIGHTMARGIN, 202 - TOPMARGIN, 7 - BOTTOMMARGIN, 176 - END - - IDD_BENCHMARK_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 323 - TOPMARGIN, 7 - BOTTOMMARGIN, 216 - END - - IDD_CIPHER_TEST_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 319 - TOPMARGIN, 7 - BOTTOMMARGIN, 242 - END - - IDD_TEXT_INFO_DIALOG_BOX_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 365 - TOPMARGIN, 7 - BOTTOMMARGIN, 213 - END - - IDD_KEYFILE_GENERATOR, DIALOG - BEGIN - LEFTMARGIN, 7 - TOPMARGIN, 7 - BOTTOMMARGIN, 358 - END - - IDD_MULTI_CHOICE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 160 - TOPMARGIN, 7 - BOTTOMMARGIN, 316 - END - - IDD_AUXILIARY_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 419 - TOPMARGIN, 7 - BOTTOMMARGIN, 289 - END - - IDD_TOKEN_PASSWORD, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 274 - TOPMARGIN, 7 - BOTTOMMARGIN, 40 - END - - IDD_TOKEN_KEYFILES, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 330 - TOPMARGIN, 7 - BOTTOMMARGIN, 178 - END - - IDD_NEW_TOKEN_KEYFILE, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 232 - TOPMARGIN, 7 - BOTTOMMARGIN, 75 - END - - IDD_RANDOM_POOL_ENRICHMENT, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 301 - TOPMARGIN, 7 - BOTTOMMARGIN, 298 - END - - IDD_STATIC_MODELESS_WAIT_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 285 - TOPMARGIN, 7 - BOTTOMMARGIN, 35 - END - - IDD_STATIC_MODAL_WAIT_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 285 - TOPMARGIN, 7 - BOTTOMMARGIN, 67 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// BIN -// - -IDR_BOOT_SECTOR BIN "..\\Boot\\Windows\\Release\\BootSector.bin" -IDR_BOOT_SECTOR_AES BIN "..\\Boot\\Windows\\Release_AES\\BootSector.bin" -IDR_BOOT_SECTOR_SERPENT BIN "..\\Boot\\Windows\\Release_Serpent\\BootSector.bin" -IDR_BOOT_SECTOR_TWOFISH BIN "..\\Boot\\Windows\\Release_Twofish\\BootSector.bin" -IDR_BOOT_LOADER_DECOMPRESSOR BIN "..\\Boot\\Windows\\Release\\Decompressor.com" -IDR_BOOT_LOADER BIN "..\\Boot\\Windows\\Release\\BootLoader.com.gz" -IDR_BOOT_LOADER_AES BIN "..\\Boot\\Windows\\Release_AES\\BootLoader.com.gz" -IDR_BOOT_LOADER_SERPENT BIN "..\\Boot\\Windows\\Release_Serpent\\BootLoader.com.gz" -IDR_BOOT_LOADER_TWOFISH BIN "..\\Boot\\Windows\\Release_Twofish\\BootLoader.com.gz" - -IDR_BOOT_SECTOR_SHA2 BIN "..\\Boot\\Windows\\Release_SHA2\\BootSector.bin" -IDR_BOOT_SECTOR_AES_SHA2 BIN "..\\Boot\\Windows\\Release_AES_SHA2\\BootSector.bin" -IDR_BOOT_SECTOR_SERPENT_SHA2 BIN "..\\Boot\\Windows\\Release_Serpent_SHA2\\BootSector.bin" -IDR_BOOT_SECTOR_TWOFISH_SHA2 BIN "..\\Boot\\Windows\\Release_Twofish_SHA2\\BootSector.bin" -IDR_BOOT_LOADER_SHA2 BIN "..\\Boot\\Windows\\Release_SHA2\\BootLoader.com.gz" -IDR_BOOT_LOADER_AES_SHA2 BIN "..\\Boot\\Windows\\Release_AES_SHA2\\BootLoader.com.gz" -IDR_BOOT_LOADER_SERPENT_SHA2 BIN "..\\Boot\\Windows\\Release_Serpent_SHA2\\BootLoader.com.gz" -IDR_BOOT_LOADER_TWOFISH_SHA2 BIN "..\\Boot\\Windows\\Release_Twofish_SHA2\\BootLoader.com.gz" - - -IDR_RESCUE_BOOT_SECTOR BIN "..\\Boot\\Windows\\Rescue\\BootSector.bin" -IDR_RESCUE_BOOT_SECTOR_AES BIN "..\\Boot\\Windows\\Rescue_AES\\BootSector.bin" -IDR_RESCUE_BOOT_SECTOR_SERPENT BIN "..\\Boot\\Windows\\Rescue_Serpent\\BootSector.bin" -IDR_RESCUE_BOOT_SECTOR_TWOFISH BIN "..\\Boot\\Windows\\Rescue_Twofish\\BootSector.bin" -IDR_RESCUE_LOADER BIN "..\\Boot\\Windows\\Rescue\\BootLoader.com.gz" -IDR_RESCUE_LOADER_AES BIN "..\\Boot\\Windows\\Rescue_AES\\BootLoader.com.gz" -IDR_RESCUE_LOADER_SERPENT BIN "..\\Boot\\Windows\\Rescue_Serpent\\BootLoader.com.gz" -IDR_RESCUE_LOADER_TWOFISH BIN "..\\Boot\\Windows\\Rescue_Twofish\\BootLoader.com.gz" - -IDR_RESCUE_BOOT_SECTOR_SHA2 BIN "..\\Boot\\Windows\\Rescue_SHA2\\BootSector.bin" -IDR_RESCUE_BOOT_SECTOR_AES_SHA2 BIN "..\\Boot\\Windows\\Rescue_AES_SHA2\\BootSector.bin" -IDR_RESCUE_BOOT_SECTOR_SERPENT_SHA2 BIN "..\\Boot\\Windows\\Rescue_Serpent_SHA2\\BootSector.bin" -IDR_RESCUE_BOOT_SECTOR_TWOFISH_SHA2 BIN "..\\Boot\\Windows\\Rescue_Twofish_SHA2\\BootSector.bin" -IDR_RESCUE_LOADER_SHA2 BIN "..\\Boot\\Windows\\Rescue_SHA2\\BootLoader.com.gz" -IDR_RESCUE_LOADER_AES_SHA2 BIN "..\\Boot\\Windows\\Rescue_AES_SHA2\\BootLoader.com.gz" -IDR_RESCUE_LOADER_SERPENT_SHA2 BIN "..\\Boot\\Windows\\Rescue_Serpent_SHA2\\BootLoader.com.gz" -IDR_RESCUE_LOADER_TWOFISH_SHA2 BIN "..\\Boot\\Windows\\Rescue_Twofish_SHA2\\BootLoader.com.gz" - -///////////////////////////////////////////////////////////////////////////// -// -// XML -// - -IDR_LANGUAGE XML "..\\Common\\Language.xml" - -///////////////////////////////////////////////////////////////////////////// -// -// HEADER -// - -IDR_COMMON_RSRC_HEADER HEADER "..\\Common\\Resource.h" - -///////////////////////////////////////////////////////////////////////////// -// -// TEXT -// - -IDR_LICENSE TEXT "..\\Resources\\Texts\\License.rtf" - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_TRUECRYPT_ICON ICON "..\\Common\\VeraCrypt.ico" -IDI_TRUECRYPT_VOL_ICON ICON "..\\Common\\VeraCrypt_volume.ico" -IDI_TRUECRYPT_MOUNTED_ICON ICON "..\\Common\\VeraCrypt_mounted.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_TEXTUAL_LOGO_BKG BITMAP "..\\Common\\Textual_logo_background.bmp" -IDB_TEXTUAL_LOGO_96DPI BITMAP "..\\Common\\Textual_logo_96dpi.bmp" -IDB_TEXTUAL_LOGO_288DPI BITMAP "..\\Common\\Textual_logo_288dpi.bmp" -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ABOUT_DLG DIALOGEX 31, 51, 292, 199 +STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "About VeraCrypt" +CLASS "VeraCryptSplashDlg" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + EDITTEXT IDC_ABOUT_CREDITS,7,111,277,45,ES_MULTILINE | WS_VSCROLL | NOT WS_TABSTOP + DEFPUSHBUTTON "OK",IDOK,230,178,52,14 + LTEXT "",IDC_HOMEPAGE,18,87,117,9,SS_NOTIFY + LTEXT "",IDT_ABOUT_RELEASE,18,71,235,8 + CONTROL IDB_TEXTUAL_LOGO_BKG,IDC_ABOUT_BKG,"Static",SS_BITMAP,0,0,12,11,WS_EX_STATICEDGE + LTEXT "",IDT_ABOUT_VERSION,18,61,161,8 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,167,291,1,WS_EX_STATICEDGE + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,169,291,1,WS_EX_STATICEDGE + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,107,291,1,WS_EX_STATICEDGE + CONTROL "",IDC_ABOUT_LOGO_AREA,"Static",SS_GRAYRECT | NOT WS_VISIBLE,0,0,293,50,WS_EX_TRANSPARENT | WS_EX_STATICEDGE + CONTROL IDB_TEXTUAL_LOGO_96DPI,IDC_TEXTUAL_LOGO_IMG,"Static",SS_BITMAP,12,26,157,16 +END + +IDD_COMMANDHELP_DLG DIALOGEX 0, 0, 249, 289 +STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Command Line Help" +CLASS "VeraCryptCustomDlg" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + DEFPUSHBUTTON "OK",IDOK,93,267,59,14 + LTEXT "",IDC_COMMANDHELP_TEXT,20,7,208,256 +END + +IDD_RAWDEVICES_DLG DIALOGEX 0, 0, 305, 209 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Select a Partition or Device" +FONT 8, "MS Shell Dlg", 400, 0, 0x0 +BEGIN + CONTROL "",IDC_DEVICELIST,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_EDITLABELS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,7,291,178 + DEFPUSHBUTTON "OK",IDOK,192,190,50,14 + PUSHBUTTON "Cancel",IDCANCEL,248,190,50,14 +END + +IDD_MOUNT_OPTIONS DIALOGEX 0, 0, 277, 231 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - Mount Options" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "Mount volume as read-&only",IDC_MOUNT_READONLY,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,11,194,10 + CONTROL "Mount volume as removable &medium",IDC_MOUNT_REMOVABLE, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,25,195,10 + CONTROL "Use backup header embedded in &volume if available",IDC_USE_EMBEDDED_HEADER_BAK, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,39,257,11 + CONTROL "Mount partition &using system encryption without pre-boot authentication",IDC_MOUNT_SYSENC_PART_WITHOUT_PBA, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,53,259,11 + EDITTEXT IDC_VOLUME_LABEL,112,67,150,14,ES_AUTOHSCROLL + CONTROL "&Protect hidden volume against damage caused by writing to outer volume",IDC_PROTECT_HIDDEN_VOL, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,16,97,252,10 + EDITTEXT IDC_PASSWORD_PROT_HIDVOL,112,115,151,14,ES_PASSWORD | ES_AUTOHSCROLL + COMBOBOX IDC_PKCS5_PRF_ID,112,136,91,90,CBS_DROPDOWNLIST | WS_TABSTOP + EDITTEXT IDC_PIM,112,156,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER | NOT WS_VISIBLE + CONTROL "Use P&IM",IDC_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,112,161,97,10 + LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,158,159,112,8,NOT WS_VISIBLE + CONTROL "&Display password",IDC_SHOW_PASSWORD_MO,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,112,174,90,10 + CONTROL "U&se keyfiles",IDC_KEYFILES_ENABLE_HIDVOL_PROT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,112,187,90,10 + PUSHBUTTON "&Keyfiles...",IDC_KEYFILES_HIDVOL_PROT,204,183,60,14 + DEFPUSHBUTTON "OK",IDOK,211,7,60,14 + PUSHBUTTON "Cancel",IDCANCEL,211,24,60,14 + LTEXT "What is hidden volume protection?",IDC_LINK_HIDVOL_PROTECTION_INFO,16,202,247,10,SS_NOTIFY + RTEXT "P&assword to hidden volume:\n(if empty, cache is used)",IDT_HIDDEN_PROT_PASSWD,15,114,91,17,0,WS_EX_RIGHT + GROUPBOX "Hidden Volume Protection",IDT_HIDDEN_VOL_PROTECTION,6,83,265,136 + RTEXT "PKCS-5 PRF:",IDT_PKCS5_PRF,15,137,91,17 + RTEXT "Volume PIM:",IDT_PIM,15,159,91,17,NOT WS_VISIBLE + LTEXT "Volume Label in Windows:",IDT_VOLUME_LABEL,12,70,95,8 +END + +IDD_KEYFILES DIALOGEX 0, 0, 363, 251 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - Keyfiles" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "",IDC_KEYLIST,"SysListView32",LVS_REPORT | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,8,275,118 + PUSHBUTTON "Add &Files...",IDC_KEYADD,7,132,61,14 + PUSHBUTTON "Add &Path...",IDC_ADD_KEYFILE_PATH,79,132,61,14 + PUSHBUTTON "Add &Token Files...",IDC_TOKEN_FILES_ADD,151,132,65,14 + PUSHBUTTON "&Remove",IDC_KEYREMOVE,227,132,61,14 + PUSHBUTTON "Remove &All",IDC_KEYREMOVEALL,299,132,61,14 + CONTROL "U&se keyfiles",IDC_KEYFILES_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,232,105,11 + PUSHBUTTON "&Generate Random Keyfile...",IDC_GENERATE_KEYFILE,237,230,123,14 + DEFPUSHBUTTON "OK",IDOK,290,8,70,14 + PUSHBUTTON "Cancel",IDCANCEL,290,25,70,14 + LTEXT "",IDT_KEYFILES_NOTE,10,161,346,41,0,WS_EX_TRANSPARENT + LTEXT "WARNING: If you lose a keyfile or if any bit of its first 1024 kilobytes changes, it will be impossible to mount volumes that use the keyfile!",IDT_KEYFILE_WARNING,290,44,69,85,0,WS_EX_TRANSPARENT + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,2,154,361,1,WS_EX_STATICEDGE + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,2,209,361,1,WS_EX_STATICEDGE + LTEXT "More information on keyfiles",IDC_LINK_KEYFILES_INFO,119,233,113,10,SS_NOTIFY + CONTROL "Try first to mount with an empty password",IDC_KEYFILES_TRY_EMPTY_PASSWORD, + "Button",BS_AUTOCHECKBOX | NOT WS_VISIBLE | WS_TABSTOP,7,217,310,10 +END + +IDD_LANGUAGE DIALOGEX 0, 0, 209, 183 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - Language" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + LISTBOX IDC_LANGLIST,6,7,197,67,LBS_SORT | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP + EDITTEXT IDC_LANGPACK_CREDITS,6,108,197,28,ES_MULTILINE | ES_READONLY | WS_VSCROLL | NOT WS_TABSTOP + CTEXT "Download language pack",IDC_GET_LANG_PACKS,2,146,205,10,SS_NOTIFY + DEFPUSHBUTTON "OK",IDOK,97,165,50,14 + PUSHBUTTON "Cancel",IDCANCEL,153,165,50,14 + LTEXT "Translated by:",IDT_LANGPACK_AUTHORS,6,99,101,9,SS_NOTIFY,WS_EX_TRANSPARENT + RTEXT "",IDC_LANGPACK_VERSION,79,86,118,11 + GROUPBOX "Active language pack",IDT_ACTIVE_LANG_PACK,0,77,209,65 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,158,208,1,WS_EX_STATICEDGE +END + +IDD_BENCHMARK_DLG DIALOGEX 0, 0, 330, 223 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - Encryption Algorithm Benchmark" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + COMBOBOX IDC_BENCHMARK_BUFFER_SIZE,55,7,77,129,CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP + COMBOBOX IDC_BENCHMARK_SORT_METHOD,207,7,116,74,CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP + CONTROL "",IDC_RESULTS,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,37,249,160 + DEFPUSHBUTTON "Benchmark",IDC_PERFORM_BENCHMARK,265,37,58,14 + PUSHBUTTON "Close",IDCLOSE,265,55,58,14 + LTEXT "Hardware-accelerated AES:",IDC_HW_AES_LABEL_LINK,148,210,108,9,SS_NOTIFY,WS_EX_RIGHT + CONTROL "",IDC_HW_AES,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,262,209,57,11,WS_EX_STATICEDGE + LTEXT "Parallelization:",IDC_PARALLELIZATION_LABEL_LINK,4,210,67,9,SS_NOTIFY,WS_EX_RIGHT + CONTROL "",IDC_PARALLELIZATION,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,77,209,57,11,WS_EX_STATICEDGE + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,2,29,328,1,WS_EX_STATICEDGE + LTEXT "Buffer Size:",IDT_BUFFER_SIZE,0,9,53,8,0,WS_EX_RIGHT + LTEXT "Sort Method:",IDT_SORT_METHOD,135,9,70,8,0,WS_EX_RIGHT + LTEXT "Speed is affected by CPU load and storage device characteristics.\n\nThese tests take place in RAM.",IDT_BOX_BENCHMARK_INFO,266,81,57,116 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,2,205,328,1,WS_EX_STATICEDGE +END + +IDD_CIPHER_TEST_DLG DIALOGEX 0, 0, 326, 249 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - Test Vectors" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + COMBOBOX IDC_CIPHER,109,10,104,126,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP + EDITTEXT IDC_KEY,8,36,309,14,ES_AUTOHSCROLL + COMBOBOX IDC_KEY_SIZE,67,55,42,68,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP + EDITTEXT IDC_SECONDARY_KEY,8,93,309,14,ES_AUTOHSCROLL + EDITTEXT IDC_TEST_DATA_UNIT_NUMBER,8,118,84,14,ES_AUTOHSCROLL + CONTROL "XTS mode",IDC_XTS_MODE_ENABLED,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,221,12,95,10 + EDITTEXT IDC_PLAINTEXT,8,151,159,14,ES_AUTOHSCROLL + COMBOBOX IDC_PLAINTEXT_SIZE,258,151,36,30,CBS_DROPDOWNLIST | WS_DISABLED | WS_VSCROLL | WS_TABSTOP + EDITTEXT IDC_CIPHERTEXT,8,185,159,14,ES_AUTOHSCROLL + DEFPUSHBUTTON "&Encrypt",IDC_ENCRYPT,8,229,52,14 + PUSHBUTTON "&Decrypt",IDC_DECRYPT,65,229,52,14 + PUSHBUTTON "&Auto-Test All",IDC_AUTO,129,229,67,14,BS_MULTILINE + PUSHBUTTON "&Reset",IDC_RESET,208,229,52,14 + PUSHBUTTON "Close",IDCLOSE,266,229,52,14 + GROUPBOX "Key (hexadecimal)",IDT_TEST_KEY,1,26,323,49 + GROUPBOX "Plaintext (hexadecimal)",IDT_TEST_PLAINTEXT,1,140,323,33 + GROUPBOX "Ciphertext (hexadecimal)",IDT_TEST_CIPHERTEXT,1,174,323,33 + RTEXT "",IDC_TESTS_MESSAGE,50,213,178,10 + CONTROL "",IDC_REDTICK,"VCREDTICK",0x0,234,214,10,8 + RTEXT "Key size:",IDT_KEY,8,57,56,8 + RTEXT "Plaintext size:",IDT_PLAINTEXT,174,153,79,8 + LTEXT "bits",IDT_KEY_UNIT,114,57,45,8 + RTEXT "Cipher:",IDT_CIPHER,38,13,68,8 + LTEXT "bits",IDT_PLAINTEXT_SIZE_UNIT,298,153,22,8 + GROUPBOX "XTS mode",IDT_XTS_MODE,1,75,323,65 + LTEXT "Secondary key (hexadecimal)",IDT_SECONDARY_KEY,8,84,187,8 + LTEXT "Data unit number (64-bit hexadecimal, data unit size is 512 bytes)",IDT_TEST_DATA_UNIT_NUMBER,8,109,308,8 + RTEXT "Block number:",IDT_TEST_BLOCK_NUMBER,134,122,119,8 + COMBOBOX IDC_TEST_BLOCK_NUMBER,258,119,36,126,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP +END + +IDD_TEXT_INFO_DIALOG_BOX_DLG DIALOGEX 0, 0, 372, 220 +STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + DEFPUSHBUTTON "OK",IDOK,305,200,58,14 + PUSHBUTTON "&Print",IDC_PRINT,156,200,58,14 + CONTROL "",IDC_INFO_BOX_TEXT,"RichEdit20W",ES_MULTILINE | ES_READONLY | ES_NUMBER | WS_BORDER | WS_VSCROLL | WS_TABSTOP,5,6,361,188 +END + +IDD_KEYFILE_GENERATOR DIALOGEX 0, 0, 357, 362 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - Keyfile Generator" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + DEFPUSHBUTTON "Close",IDCLOSE,291,10,59,14 + COMBOBOX IDC_PRF_ID,97,49,91,90,CBS_DROPDOWNLIST | WS_TABSTOP + CONTROL "Display pool content",IDC_DISPLAY_POOL_CONTENTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,209,51,141,10 + EDITTEXT IDC_NUMBER_KEYFILES,124,278,51,14,ES_RIGHT | ES_AUTOHSCROLL | ES_NUMBER + EDITTEXT IDC_KEYFILES_SIZE,124,298,51,14,ES_RIGHT | ES_AUTOHSCROLL | ES_NUMBER + CONTROL "Random size ( 64 <-> 1048576 )",IDC_KEYFILES_RANDOM_SIZE, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,181,300,174,10 + EDITTEXT IDC_KEYFILES_BASE_NAME,124,318,141,14,ES_AUTOHSCROLL + PUSHBUTTON "Generate and Save Keyfile...",IDC_GENERATE_AND_SAVE_KEYFILE,124,336,141,14 + LTEXT "IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the keyfile.",IDT_KEYFILE_GENERATOR_NOTE,11,5,271,33 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,40,356,1,WS_EX_STATICEDGE + RTEXT "Mixing PRF:",IDT_PRF,7,51,85,10,SS_CENTERIMAGE + GROUPBOX "Current Pool Content",IDT_POOL_CONTENTS,6,70,344,170 + CTEXT "",IDC_POOL_CONTENTS,16,83,323,148,0,WS_EX_TRANSPARENT + RTEXT "Number of keyfiles:",IDT_NUMBER_KEYFILES,9,281,110,8 + RTEXT "Keyfiles base name:",IDT_KEYFILES_BASE_NAME,9,321,110,8 + RTEXT "Keyfiles size (in Bytes):",IDT_KEYFILES_SIZE,9,300,110,8 + CONTROL "",IDC_ENTROPY_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,18,255,321,12 + GROUPBOX "Randomness Collected From Mouse Movements",IDT_ENTROPY_BAR,6,244,344,29 +END + +IDD_MULTI_CHOICE_DLG DIALOGEX 0, 0, 167, 322 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + PUSHBUTTON "",IDC_CHOICE10,7,292,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE + PUSHBUTTON "",IDC_CHOICE9,7,268,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE + PUSHBUTTON "",IDC_CHOICE8,7,244,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE + PUSHBUTTON "",IDC_CHOICE7,7,220,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE + PUSHBUTTON "",IDC_CHOICE6,7,196,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE + PUSHBUTTON "",IDC_CHOICE5,7,172,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE + PUSHBUTTON "",IDC_CHOICE4,7,148,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE + PUSHBUTTON "",IDC_CHOICE3,7,124,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE + PUSHBUTTON "",IDC_CHOICE2,7,100,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE + PUSHBUTTON "",IDC_CHOICE1,7,76,153,24,BS_CENTER | BS_MULTILINE,WS_EX_STATICEDGE + LTEXT "",IDC_MULTI_CHOICE_MSG,7,7,153,56,0,WS_EX_TRANSPARENT + CONTROL "",IDC_MC_DLG_HR2,"Static",SS_ETCHEDHORZ,0,69,168,1,WS_EX_STATICEDGE + CONTROL "",IDC_MC_DLG_HR1,"Static",SS_ETCHEDHORZ,0,1,168,1,WS_EX_STATICEDGE +END + +IDD_AUXILIARY_DLG DIALOGEX 0, 0, 426, 296 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_NOFAILCREATE | WS_POPUP +EXSTYLE WS_EX_TRANSPARENT +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + LTEXT "",IDC_ASPECT_RATIO_CALIBRATION_BOX,3,2,282,282,WS_DISABLED +END + +IDD_TOKEN_PASSWORD DIALOGEX 0, 0, 281, 47 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Security token password/PIN required" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + EDITTEXT IDC_TOKEN_PASSWORD,8,20,199,14,ES_PASSWORD | ES_AUTOHSCROLL + DEFPUSHBUTTON "OK",IDOK,215,7,59,14 + PUSHBUTTON "Cancel",IDCANCEL,215,25,59,14 + LTEXT "",IDT_TOKEN_PASSWORD_INFO,9,8,196,8 +END + +IDD_TOKEN_KEYFILES DIALOGEX 0, 0, 337, 185 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Security Token Keyfiles" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "",IDC_TOKEN_FILE_LIST,"SysListView32",LVS_REPORT | LVS_SHOWSELALWAYS | LVS_EDITLABELS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,7,256,152 + PUSHBUTTON "&Export...",IDC_EXPORT,7,164,55,14 + PUSHBUTTON "&Delete",IDC_DELETE,66,164,55,14 + PUSHBUTTON "&Import Keyfile to Token...",IDC_IMPORT_KEYFILE,126,164,137,14 + DEFPUSHBUTTON "OK",IDOK,271,7,59,14 + PUSHBUTTON "Cancel",IDCANCEL,271,25,59,14 +END + +IDD_NEW_TOKEN_KEYFILE DIALOGEX 0, 0, 239, 82 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "New Security Token Keyfile Properties" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + DEFPUSHBUTTON "OK",IDOK,128,61,50,14 + PUSHBUTTON "Cancel",IDCANCEL,183,61,50,14 + COMBOBOX IDC_SELECTED_TOKEN,77,13,140,43,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP + LTEXT "Security token:",IDT_SECURITY_TOKEN,11,15,62,8,0,WS_EX_RIGHT + LTEXT "Keyfile name:",IDT_TOKEN_KEYFILE_NAME,12,34,61,8,0,WS_EX_RIGHT + EDITTEXT IDC_TOKEN_KEYFILE_NAME,77,32,140,13,ES_AUTOHSCROLL + GROUPBOX "",IDC_STATIC,5,2,228,51 +END + +IDD_RANDOM_POOL_ENRICHMENT DIALOGEX 0, 0, 308, 301 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - Random Pool Enrichment" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + DEFPUSHBUTTON "&Continue",IDC_CONTINUE,119,278,71,14 + COMBOBOX IDC_PRF_ID,79,49,91,90,CBS_DROPDOWNLIST | WS_TABSTOP + LTEXT "IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases security. When done, click 'Continue'.",IDT_RANDOM_POOL_ENRICHMENT_NOTE,11,6,282,25 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,37,307,1,WS_EX_STATICEDGE + RTEXT "Mixing PRF:",IDT_PRF,6,51,67,10,SS_CENTERIMAGE + GROUPBOX "Current Pool Content",IDT_POOL_CONTENTS,6,70,296,170 + CONTROL "",IDC_POOL_CONTENTS,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,16,83,282,148,WS_EX_TRANSPARENT + CONTROL "Display pool content",IDC_DISPLAY_POOL_CONTENTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,191,51,111,10 + CONTROL "",IDC_ENTROPY_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,16,255,275,12 + GROUPBOX "Randomness Collected From Mouse Movements",IDT_ENTROPY_BAR,7,244,294,29 +END + +IDD_STATIC_MODELESS_WAIT_DLG DIALOGEX 0, 0, 292, 42 +STYLE DS_SYSMODAL | DS_SETFONT | DS_MODALFRAME | DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION +EXSTYLE WS_EX_TOPMOST | WS_EX_TOOLWINDOW +CAPTION "VeraCrypt" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + LTEXT "Please wait. This process may take a long time...",IDT_STATIC_MODELESS_WAIT_DLG_INFO,9,8,274,9 +END + +IDD_STATIC_MODAL_WAIT_DLG DIALOGEX 0, 0, 292, 74 +STYLE DS_SETFONT | DS_MODALFRAME | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION +CAPTION "VeraCrypt" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + CTEXT "Please wait...\nThis process may take a long time and VeraCrypt may seem unresponsive.",IDT_STATIC_MODAL_WAIT_DLG_INFO,9,11,274,33 + CONTROL "",IDC_WAIT_PROGRESS_BAR,"msctls_progress32",WS_BORDER,7,49,278,14 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_ABOUT_DLG, DIALOG + BEGIN + END + + IDD_COMMANDHELP_DLG, DIALOG + BEGIN + BOTTOMMARGIN, 281 + END + + IDD_RAWDEVICES_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 298 + TOPMARGIN, 7 + BOTTOMMARGIN, 205 + END + + IDD_MOUNT_OPTIONS, DIALOG + BEGIN + LEFTMARGIN, 7 + TOPMARGIN, 7 + BOTTOMMARGIN, 225 + END + + IDD_KEYFILES, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 345 + TOPMARGIN, 7 + BOTTOMMARGIN, 244 + END + + IDD_LANGUAGE, DIALOG + BEGIN + LEFTMARGIN, 6 + RIGHTMARGIN, 202 + TOPMARGIN, 7 + BOTTOMMARGIN, 176 + END + + IDD_BENCHMARK_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 323 + TOPMARGIN, 7 + BOTTOMMARGIN, 216 + END + + IDD_CIPHER_TEST_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 319 + TOPMARGIN, 7 + BOTTOMMARGIN, 242 + END + + IDD_TEXT_INFO_DIALOG_BOX_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 365 + TOPMARGIN, 7 + BOTTOMMARGIN, 213 + END + + IDD_KEYFILE_GENERATOR, DIALOG + BEGIN + LEFTMARGIN, 7 + TOPMARGIN, 7 + BOTTOMMARGIN, 358 + END + + IDD_MULTI_CHOICE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 160 + TOPMARGIN, 7 + BOTTOMMARGIN, 316 + END + + IDD_AUXILIARY_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 419 + TOPMARGIN, 7 + BOTTOMMARGIN, 289 + END + + IDD_TOKEN_PASSWORD, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 274 + TOPMARGIN, 7 + BOTTOMMARGIN, 40 + END + + IDD_TOKEN_KEYFILES, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 330 + TOPMARGIN, 7 + BOTTOMMARGIN, 178 + END + + IDD_NEW_TOKEN_KEYFILE, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 232 + TOPMARGIN, 7 + BOTTOMMARGIN, 75 + END + + IDD_RANDOM_POOL_ENRICHMENT, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 301 + TOPMARGIN, 7 + BOTTOMMARGIN, 298 + END + + IDD_STATIC_MODELESS_WAIT_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 285 + TOPMARGIN, 7 + BOTTOMMARGIN, 35 + END + + IDD_STATIC_MODAL_WAIT_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 285 + TOPMARGIN, 7 + BOTTOMMARGIN, 67 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// BIN +// + +IDR_BOOT_SECTOR BIN "..\\Boot\\Windows\\Release\\BootSector.bin" +IDR_BOOT_SECTOR_AES BIN "..\\Boot\\Windows\\Release_AES\\BootSector.bin" +IDR_BOOT_SECTOR_SERPENT BIN "..\\Boot\\Windows\\Release_Serpent\\BootSector.bin" +IDR_BOOT_SECTOR_TWOFISH BIN "..\\Boot\\Windows\\Release_Twofish\\BootSector.bin" +IDR_BOOT_LOADER_DECOMPRESSOR BIN "..\\Boot\\Windows\\Release\\Decompressor.com" +IDR_BOOT_LOADER BIN "..\\Boot\\Windows\\Release\\BootLoader.com.gz" +IDR_BOOT_LOADER_AES BIN "..\\Boot\\Windows\\Release_AES\\BootLoader.com.gz" +IDR_BOOT_LOADER_SERPENT BIN "..\\Boot\\Windows\\Release_Serpent\\BootLoader.com.gz" +IDR_BOOT_LOADER_TWOFISH BIN "..\\Boot\\Windows\\Release_Twofish\\BootLoader.com.gz" + +IDR_BOOT_SECTOR_SHA2 BIN "..\\Boot\\Windows\\Release_SHA2\\BootSector.bin" +IDR_BOOT_SECTOR_AES_SHA2 BIN "..\\Boot\\Windows\\Release_AES_SHA2\\BootSector.bin" +IDR_BOOT_SECTOR_SERPENT_SHA2 BIN "..\\Boot\\Windows\\Release_Serpent_SHA2\\BootSector.bin" +IDR_BOOT_SECTOR_TWOFISH_SHA2 BIN "..\\Boot\\Windows\\Release_Twofish_SHA2\\BootSector.bin" +IDR_BOOT_LOADER_SHA2 BIN "..\\Boot\\Windows\\Release_SHA2\\BootLoader.com.gz" +IDR_BOOT_LOADER_AES_SHA2 BIN "..\\Boot\\Windows\\Release_AES_SHA2\\BootLoader.com.gz" +IDR_BOOT_LOADER_SERPENT_SHA2 BIN "..\\Boot\\Windows\\Release_Serpent_SHA2\\BootLoader.com.gz" +IDR_BOOT_LOADER_TWOFISH_SHA2 BIN "..\\Boot\\Windows\\Release_Twofish_SHA2\\BootLoader.com.gz" + + +IDR_RESCUE_BOOT_SECTOR BIN "..\\Boot\\Windows\\Rescue\\BootSector.bin" +IDR_RESCUE_BOOT_SECTOR_AES BIN "..\\Boot\\Windows\\Rescue_AES\\BootSector.bin" +IDR_RESCUE_BOOT_SECTOR_SERPENT BIN "..\\Boot\\Windows\\Rescue_Serpent\\BootSector.bin" +IDR_RESCUE_BOOT_SECTOR_TWOFISH BIN "..\\Boot\\Windows\\Rescue_Twofish\\BootSector.bin" +IDR_RESCUE_LOADER BIN "..\\Boot\\Windows\\Rescue\\BootLoader.com.gz" +IDR_RESCUE_LOADER_AES BIN "..\\Boot\\Windows\\Rescue_AES\\BootLoader.com.gz" +IDR_RESCUE_LOADER_SERPENT BIN "..\\Boot\\Windows\\Rescue_Serpent\\BootLoader.com.gz" +IDR_RESCUE_LOADER_TWOFISH BIN "..\\Boot\\Windows\\Rescue_Twofish\\BootLoader.com.gz" + +IDR_RESCUE_BOOT_SECTOR_SHA2 BIN "..\\Boot\\Windows\\Rescue_SHA2\\BootSector.bin" +IDR_RESCUE_BOOT_SECTOR_AES_SHA2 BIN "..\\Boot\\Windows\\Rescue_AES_SHA2\\BootSector.bin" +IDR_RESCUE_BOOT_SECTOR_SERPENT_SHA2 BIN "..\\Boot\\Windows\\Rescue_Serpent_SHA2\\BootSector.bin" +IDR_RESCUE_BOOT_SECTOR_TWOFISH_SHA2 BIN "..\\Boot\\Windows\\Rescue_Twofish_SHA2\\BootSector.bin" +IDR_RESCUE_LOADER_SHA2 BIN "..\\Boot\\Windows\\Rescue_SHA2\\BootLoader.com.gz" +IDR_RESCUE_LOADER_AES_SHA2 BIN "..\\Boot\\Windows\\Rescue_AES_SHA2\\BootLoader.com.gz" +IDR_RESCUE_LOADER_SERPENT_SHA2 BIN "..\\Boot\\Windows\\Rescue_Serpent_SHA2\\BootLoader.com.gz" +IDR_RESCUE_LOADER_TWOFISH_SHA2 BIN "..\\Boot\\Windows\\Rescue_Twofish_SHA2\\BootLoader.com.gz" + +///////////////////////////////////////////////////////////////////////////// +// +// XML +// + +IDR_LANGUAGE XML "..\\Common\\Language.xml" + +///////////////////////////////////////////////////////////////////////////// +// +// HEADER +// + +IDR_COMMON_RSRC_HEADER HEADER "..\\Common\\Resource.h" + +///////////////////////////////////////////////////////////////////////////// +// +// TEXT +// + +IDR_LICENSE TEXT "..\\Resources\\Texts\\License.rtf" + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_TRUECRYPT_ICON ICON "..\\Common\\VeraCrypt.ico" +IDI_TRUECRYPT_VOL_ICON ICON "..\\Common\\VeraCrypt_volume.ico" +IDI_TRUECRYPT_MOUNTED_ICON ICON "..\\Common\\VeraCrypt_mounted.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Bitmap +// + +IDB_TEXTUAL_LOGO_BKG BITMAP "..\\Common\\Textual_logo_background.bmp" +IDB_TEXTUAL_LOGO_96DPI BITMAP "..\\Common\\Textual_logo_96dpi.bmp" +IDB_TEXTUAL_LOGO_288DPI BITMAP "..\\Common\\Textual_logo_288dpi.bmp" +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/src/Common/Crc.c b/src/Common/Crc.c index b66b86ca..ba8777e6 100644 --- a/src/Common/Crc.c +++ b/src/Common/Crc.c @@ -1,135 +1,135 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" -#include "Crc.h" -#include "Common/Endian.h" - -#ifndef TC_MINIMIZE_CODE_SIZE - -/* CRC polynomial 0x04c11db7 */ -unsigned __int32 crc_32_tab[]= -{ - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, - 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, - 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, - 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, - 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, - 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, - 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, - 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, - 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, - 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, - 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, - 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, - 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, - 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, - 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, - 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, - 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, - 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, - 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, - 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, - 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, - 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d -}; - -unsigned __int32 GetCrc32 (unsigned char *data, int length) -{ - unsigned __int32 CRC = 0xffffffff; - - while (length--) - { - CRC = (CRC >> 8) ^ crc_32_tab[ (CRC ^ *data++) & 0xFF ]; - } - - return CRC ^ 0xffffffff; -} - -unsigned __int32 crc32int (unsigned __int32 *data) -{ - unsigned char *d = (unsigned char *) data; - unsigned __int32 CRC = 0xffffffff; - - CRC = (CRC >> 8) ^ crc_32_tab[ (CRC ^ *d++) & 0xFF ]; - CRC = (CRC >> 8) ^ crc_32_tab[ (CRC ^ *d++) & 0xFF ]; - CRC = (CRC >> 8) ^ crc_32_tab[ (CRC ^ *d++) & 0xFF ]; - return (CRC >> 8) ^ crc_32_tab[ (CRC ^ *d) & 0xFF ] ^ 0xffffffff; -} - -#if BYTE_ORDER == LITTLE_ENDIAN -# define CRC_SELFTEST 0x6fcf9e13 -#else -# define CRC_SELFTEST 0xca87914d -#endif - -BOOL crc32_selftests (void) -{ - int i; - unsigned __int32 crc = 0xffffffff; - BOOL bSuccess = FALSE; - - for (i = 0; i < (int)sizeof(crc_32_tab); i++) - crc = UPDC32 (((unsigned char *) crc_32_tab)[i], crc); - - bSuccess = CRC_SELFTEST == (crc ^ 0xffffffff); - - bSuccess &= GetCrc32 ((unsigned char *)crc_32_tab, sizeof crc_32_tab) == CRC_SELFTEST; - - return bSuccess; -} - -#else // TC_MINIMIZE_CODE_SIZE - -unsigned __int32 GetCrc32 (unsigned char *data, int length) -{ - unsigned __int32 r = 0xFFFFFFFFUL; - int i, b; - - for (i = 0; i < length; ++i) - { - r ^= data[i]; - for (b = 0; b < 8; ++b) - { - if ((unsigned __int8) r & 1) - r = (r >> 1) ^ 0xEDB88320UL; - else - r >>= 1; - } - } - - return r ^ 0xFFFFFFFFUL; -} - -BOOL crc32_selftests () -{ - unsigned __int8 testData[32]; - unsigned __int8 i; - - for (i = 0; i < sizeof (testData); ++i) - testData[i] = i; - - return GetCrc32 (testData, sizeof (testData)) == 0x91267E8AUL; -} - -#endif // TC_MINIMIZE_CODE_SIZE +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" +#include "Crc.h" +#include "Common/Endian.h" + +#ifndef TC_MINIMIZE_CODE_SIZE + +/* CRC polynomial 0x04c11db7 */ +unsigned __int32 crc_32_tab[]= +{ + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, + 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, + 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, + 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, + 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, + 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, + 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, + 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, + 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, + 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, + 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, + 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, + 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, + 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, + 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, + 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, + 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, + 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, + 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, + 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, + 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, + 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, + 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d +}; + +unsigned __int32 GetCrc32 (unsigned char *data, int length) +{ + unsigned __int32 CRC = 0xffffffff; + + while (length--) + { + CRC = (CRC >> 8) ^ crc_32_tab[ (CRC ^ *data++) & 0xFF ]; + } + + return CRC ^ 0xffffffff; +} + +unsigned __int32 crc32int (unsigned __int32 *data) +{ + unsigned char *d = (unsigned char *) data; + unsigned __int32 CRC = 0xffffffff; + + CRC = (CRC >> 8) ^ crc_32_tab[ (CRC ^ *d++) & 0xFF ]; + CRC = (CRC >> 8) ^ crc_32_tab[ (CRC ^ *d++) & 0xFF ]; + CRC = (CRC >> 8) ^ crc_32_tab[ (CRC ^ *d++) & 0xFF ]; + return (CRC >> 8) ^ crc_32_tab[ (CRC ^ *d) & 0xFF ] ^ 0xffffffff; +} + +#if BYTE_ORDER == LITTLE_ENDIAN +# define CRC_SELFTEST 0x6fcf9e13 +#else +# define CRC_SELFTEST 0xca87914d +#endif + +BOOL crc32_selftests (void) +{ + int i; + unsigned __int32 crc = 0xffffffff; + BOOL bSuccess = FALSE; + + for (i = 0; i < (int)sizeof(crc_32_tab); i++) + crc = UPDC32 (((unsigned char *) crc_32_tab)[i], crc); + + bSuccess = CRC_SELFTEST == (crc ^ 0xffffffff); + + bSuccess &= GetCrc32 ((unsigned char *)crc_32_tab, sizeof crc_32_tab) == CRC_SELFTEST; + + return bSuccess; +} + +#else // TC_MINIMIZE_CODE_SIZE + +unsigned __int32 GetCrc32 (unsigned char *data, int length) +{ + unsigned __int32 r = 0xFFFFFFFFUL; + int i, b; + + for (i = 0; i < length; ++i) + { + r ^= data[i]; + for (b = 0; b < 8; ++b) + { + if ((unsigned __int8) r & 1) + r = (r >> 1) ^ 0xEDB88320UL; + else + r >>= 1; + } + } + + return r ^ 0xFFFFFFFFUL; +} + +BOOL crc32_selftests () +{ + unsigned __int8 testData[32]; + unsigned __int8 i; + + for (i = 0; i < sizeof (testData); ++i) + testData[i] = i; + + return GetCrc32 (testData, sizeof (testData)) == 0x91267E8AUL; +} + +#endif // TC_MINIMIZE_CODE_SIZE diff --git a/src/Common/Crc.h b/src/Common/Crc.h index 531a0383..c89a6191 100644 --- a/src/Common/Crc.h +++ b/src/Common/Crc.h @@ -1,37 +1,37 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifndef TC_HEADER_CRC -#define TC_HEADER_CRC - -#include "Tcdefs.h" - -#if defined(__cplusplus) -extern "C" -{ -#endif - -#define UPDC32(octet, crc)\ - (unsigned __int32)((crc_32_tab[(((unsigned __int32)(crc)) ^ ((unsigned char)(octet))) & 0xff] ^ (((unsigned __int32)(crc)) >> 8))) - -unsigned __int32 GetCrc32 (unsigned char *data, int length); -unsigned __int32 crc32int (unsigned __int32 *data); -BOOL crc32_selftests (void); - -extern unsigned __int32 crc_32_tab[]; - -#if defined(__cplusplus) -} -#endif - -#endif // TC_HEADER_CRC +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifndef TC_HEADER_CRC +#define TC_HEADER_CRC + +#include "Tcdefs.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif + +#define UPDC32(octet, crc)\ + (unsigned __int32)((crc_32_tab[(((unsigned __int32)(crc)) ^ ((unsigned char)(octet))) & 0xff] ^ (((unsigned __int32)(crc)) >> 8))) + +unsigned __int32 GetCrc32 (unsigned char *data, int length); +unsigned __int32 crc32int (unsigned __int32 *data); +BOOL crc32_selftests (void); + +extern unsigned __int32 crc_32_tab[]; + +#if defined(__cplusplus) +} +#endif + +#endif // TC_HEADER_CRC diff --git a/src/Common/Crypto.c b/src/Common/Crypto.c index d940a453..a524fd97 100644 --- a/src/Common/Crypto.c +++ b/src/Common/Crypto.c @@ -1,1058 +1,1058 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" -#include "Crypto.h" -#include "Xts.h" -#include "Crc.h" -#include "Common/Endian.h" -#include -#ifndef TC_WINDOWS_BOOT -#include "EncryptionThreadPool.h" -#endif -#include "Volumes.h" - -/* Update the following when adding a new cipher or EA: - - Crypto.h: - ID #define - MAX_EXPANDED_KEY #define - - Crypto.c: - Ciphers[] - EncryptionAlgorithms[] - CipherInit() - EncipherBlock() - DecipherBlock() - -*/ - -#ifndef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - -// Cipher configuration -static Cipher Ciphers[] = -{ -// Block Size Key Size Key Schedule Size -// ID Name (Bytes) (Bytes) (Bytes) -#ifdef TC_WINDOWS_BOOT - { AES, "AES", 16, 32, AES_KS }, - { SERPENT, "Serpent", 16, 32, 140*4 }, - { TWOFISH, "Twofish", 16, 32, TWOFISH_KS }, -#else - { AES, L"AES", 16, 32, AES_KS }, - { SERPENT, L"Serpent", 16, 32, 140*4 }, - { TWOFISH, L"Twofish", 16, 32, TWOFISH_KS }, -#endif - { 0, 0, 0, 0, 0 } -}; - - -// Encryption algorithm configuration -static EncryptionAlgorithm EncryptionAlgorithms[] = -{ - // Cipher(s) Modes FormatEnabled - -#ifndef TC_WINDOWS_BOOT - - { { 0, 0 }, { 0, 0}, 0 }, // Must be all-zero - { { AES, 0 }, { XTS, 0 }, 1 }, - { { SERPENT, 0 }, { XTS, 0 }, 1 }, - { { TWOFISH, 0 }, { XTS, 0 }, 1 }, - { { TWOFISH, AES, 0 }, { XTS, 0 }, 1 }, - { { SERPENT, TWOFISH, AES, 0 }, { XTS, 0 }, 1 }, - { { AES, SERPENT, 0 }, { XTS, 0 }, 1 }, - { { AES, TWOFISH, SERPENT, 0 }, { XTS, 0 }, 1 }, - { { SERPENT, TWOFISH, 0 }, { XTS, 0 }, 1 }, - { { 0, 0 }, { 0, 0}, 0 } // Must be all-zero - -#else // TC_WINDOWS_BOOT - - // Encryption algorithms available for boot drive encryption - { { 0, 0 }, { 0, 0 }, 0 }, // Must be all-zero - { { AES, 0 }, { XTS, 0 }, 1 }, - { { SERPENT, 0 }, { XTS, 0 }, 1 }, - { { TWOFISH, 0 }, { XTS, 0 }, 1 }, - { { TWOFISH, AES, 0 }, { XTS, 0 }, 1 }, - { { SERPENT, TWOFISH, AES, 0 }, { XTS, 0 }, 1 }, - { { AES, SERPENT, 0 }, { XTS, 0 }, 1 }, - { { AES, TWOFISH, SERPENT, 0 }, { XTS, 0 }, 1 }, - { { SERPENT, TWOFISH, 0 }, { XTS, 0 }, 1 }, - { { 0, 0 }, { 0, 0 }, 0 }, // Must be all-zero - -#endif - -}; - - -#ifndef TC_WINDOWS_BOOT -// Hash algorithms -static Hash Hashes[] = -{ // ID Name Deprecated System Encryption - { SHA512, L"SHA-512", FALSE, FALSE }, - { WHIRLPOOL, L"Whirlpool", FALSE, FALSE }, - { SHA256, L"SHA-256", FALSE, TRUE }, - { RIPEMD160, L"RIPEMD-160", TRUE, TRUE }, - { 0, 0, 0 } -}; -#endif - -/* Return values: 0 = success, ERR_CIPHER_INIT_FAILURE (fatal), ERR_CIPHER_INIT_WEAK_KEY (non-fatal) */ -int CipherInit (int cipher, unsigned char *key, unsigned __int8 *ks) -{ - int retVal = ERR_SUCCESS; - - switch (cipher) - { - case AES: -#ifndef TC_WINDOWS_BOOT - if (aes_encrypt_key256 (key, (aes_encrypt_ctx *) ks) != EXIT_SUCCESS) - return ERR_CIPHER_INIT_FAILURE; - - if (aes_decrypt_key256 (key, (aes_decrypt_ctx *) (ks + sizeof(aes_encrypt_ctx))) != EXIT_SUCCESS) - return ERR_CIPHER_INIT_FAILURE; -#else - if (aes_set_key (key, (length_type) CipherGetKeySize(AES), (aes_context *) ks) != 0) - return ERR_CIPHER_INIT_FAILURE; -#endif - break; - - case SERPENT: - serpent_set_key (key, ks); - break; - - case TWOFISH: - twofish_set_key ((TwofishInstance *)ks, (const u4byte *)key); - break; - - default: - // Unknown/wrong cipher ID - return ERR_CIPHER_INIT_FAILURE; - } - - return retVal; -} - -void EncipherBlock(int cipher, void *data, void *ks) -{ - switch (cipher) - { - case AES: - // In 32-bit kernel mode, due to KeSaveFloatingPointState() overhead, AES instructions can be used only when processing the whole data unit. -#if (defined (_WIN64) || !defined (TC_WINDOWS_DRIVER)) && !defined (TC_WINDOWS_BOOT) - if (IsAesHwCpuSupported()) - aes_hw_cpu_encrypt (ks, data); - else -#endif - aes_encrypt (data, data, ks); - break; - - case TWOFISH: twofish_encrypt (ks, data, data); break; - case SERPENT: serpent_encrypt (data, data, ks); break; - default: TC_THROW_FATAL_EXCEPTION; // Unknown/wrong ID - } -} - -#ifndef TC_WINDOWS_BOOT - -void EncipherBlocks (int cipher, void *dataPtr, void *ks, size_t blockCount) -{ - byte *data = dataPtr; -#if defined (TC_WINDOWS_DRIVER) && !defined (_WIN64) - KFLOATING_SAVE floatingPointState; -#endif - - if (cipher == AES - && (blockCount & (32 - 1)) == 0 - && IsAesHwCpuSupported() -#if defined (TC_WINDOWS_DRIVER) && !defined (_WIN64) - && NT_SUCCESS (KeSaveFloatingPointState (&floatingPointState)) -#endif - ) - { - while (blockCount > 0) - { - aes_hw_cpu_encrypt_32_blocks (ks, data); - - data += 32 * 16; - blockCount -= 32; - } - -#if defined (TC_WINDOWS_DRIVER) && !defined (_WIN64) - KeRestoreFloatingPointState (&floatingPointState); -#endif - } - else - { - size_t blockSize = CipherGetBlockSize (cipher); - while (blockCount-- > 0) - { - EncipherBlock (cipher, data, ks); - data += blockSize; - } - } -} - -#endif // !TC_WINDOWS_BOOT - -void DecipherBlock(int cipher, void *data, void *ks) -{ - switch (cipher) - { - case SERPENT: serpent_decrypt (data, data, ks); break; - case TWOFISH: twofish_decrypt (ks, data, data); break; -#ifndef TC_WINDOWS_BOOT - - case AES: -#if defined (_WIN64) || !defined (TC_WINDOWS_DRIVER) - if (IsAesHwCpuSupported()) - aes_hw_cpu_decrypt ((byte *) ks + sizeof (aes_encrypt_ctx), data); - else -#endif - aes_decrypt (data, data, (void *) ((char *) ks + sizeof(aes_encrypt_ctx))); - break; - -#else - case AES: aes_decrypt (data, data, ks); break; -#endif - default: TC_THROW_FATAL_EXCEPTION; // Unknown/wrong ID - } -} - -#ifndef TC_WINDOWS_BOOT - -void DecipherBlocks (int cipher, void *dataPtr, void *ks, size_t blockCount) -{ - byte *data = dataPtr; -#if defined (TC_WINDOWS_DRIVER) && !defined (_WIN64) - KFLOATING_SAVE floatingPointState; -#endif - - if (cipher == AES - && (blockCount & (32 - 1)) == 0 - && IsAesHwCpuSupported() -#if defined (TC_WINDOWS_DRIVER) && !defined (_WIN64) - && NT_SUCCESS (KeSaveFloatingPointState (&floatingPointState)) -#endif - ) - { - while (blockCount > 0) - { - aes_hw_cpu_decrypt_32_blocks ((byte *) ks + sizeof (aes_encrypt_ctx), data); - - data += 32 * 16; - blockCount -= 32; - } - -#if defined (TC_WINDOWS_DRIVER) && !defined (_WIN64) - KeRestoreFloatingPointState (&floatingPointState); -#endif - } - else - { - size_t blockSize = CipherGetBlockSize (cipher); - while (blockCount-- > 0) - { - DecipherBlock (cipher, data, ks); - data += blockSize; - } - } -} - -#endif // !TC_WINDOWS_BOOT - - -// Ciphers support - -Cipher *CipherGet (int id) -{ - int i; - for (i = 0; Ciphers[i].Id != 0; i++) - if (Ciphers[i].Id == id) - return &Ciphers[i]; - - return NULL; -} - -#ifndef TC_WINDOWS_BOOT -const wchar_t *CipherGetName (int cipherId) -{ - Cipher* pCipher = CipherGet (cipherId); - return pCipher? pCipher -> Name : L""; -} -#endif - -int CipherGetBlockSize (int cipherId) -{ -#ifdef TC_WINDOWS_BOOT - return CipherGet (cipherId) -> BlockSize; -#else - Cipher* pCipher = CipherGet (cipherId); - return pCipher? pCipher -> BlockSize : 0; -#endif -} - -int CipherGetKeySize (int cipherId) -{ -#ifdef TC_WINDOWS_BOOT - return CipherGet (cipherId) -> KeySize; -#else - Cipher* pCipher = CipherGet (cipherId); - return pCipher? pCipher -> KeySize : 0; -#endif -} - -int CipherGetKeyScheduleSize (int cipherId) -{ -#ifdef TC_WINDOWS_BOOT - return CipherGet (cipherId) -> KeyScheduleSize; -#else - Cipher* pCipher = CipherGet (cipherId); - return pCipher? pCipher -> KeyScheduleSize : 0; -#endif -} - -#ifndef TC_WINDOWS_BOOT - -BOOL CipherSupportsIntraDataUnitParallelization (int cipher) -{ - return cipher == AES && IsAesHwCpuSupported(); -} - -#endif - - -// Encryption algorithms support - -int EAGetFirst () -{ - return 1; -} - -// Returns number of EAs -int EAGetCount (void) -{ - int ea, count = 0; - - for (ea = EAGetFirst (); ea != 0; ea = EAGetNext (ea)) - { - count++; - } - return count; -} - -int EAGetNext (int previousEA) -{ - int id = previousEA + 1; - if (EncryptionAlgorithms[id].Ciphers[0] != 0) return id; - return 0; -} - - -// Return values: 0 = success, ERR_CIPHER_INIT_FAILURE (fatal), ERR_CIPHER_INIT_WEAK_KEY (non-fatal) -int EAInit (int ea, unsigned char *key, unsigned __int8 *ks) -{ - int c, retVal = ERR_SUCCESS; - - if (ea == 0) - return ERR_CIPHER_INIT_FAILURE; - - for (c = EAGetFirstCipher (ea); c != 0; c = EAGetNextCipher (ea, c)) - { - switch (CipherInit (c, key, ks)) - { - case ERR_CIPHER_INIT_FAILURE: - return ERR_CIPHER_INIT_FAILURE; - - case ERR_CIPHER_INIT_WEAK_KEY: - retVal = ERR_CIPHER_INIT_WEAK_KEY; // Non-fatal error - break; - } - - key += CipherGetKeySize (c); - ks += CipherGetKeyScheduleSize (c); - } - return retVal; -} - - -#ifndef TC_WINDOWS_BOOT - -BOOL EAInitMode (PCRYPTO_INFO ci) -{ - switch (ci->mode) - { - case XTS: - // Secondary key schedule - if (EAInit (ci->ea, ci->k2, ci->ks2) != ERR_SUCCESS) - return FALSE; - - /* Note: XTS mode could potentially be initialized with a weak key causing all blocks in one data unit - on the volume to be tweaked with zero tweaks (i.e. 512 bytes of the volume would be encrypted in ECB - mode). However, to create a TrueCrypt volume with such a weak key, each human being on Earth would have - to create approximately 11,378,125,361,078,862 (about eleven quadrillion) TrueCrypt volumes (provided - that the size of each of the volumes is 1024 terabytes). */ - break; - - default: - // Unknown/wrong ID - TC_THROW_FATAL_EXCEPTION; - } - return TRUE; -} - -static void EAGetDisplayName(wchar_t *buf, int ea, int i) -{ - wcscpy (buf, CipherGetName (i)); - if (i = EAGetPreviousCipher(ea, i)) - { - wcscat (buf, L"("); - EAGetDisplayName (&buf[wcslen(buf)], ea, i); - wcscat (buf, L")"); - } -} - -// Returns name of EA, cascaded cipher names are separated by hyphens -wchar_t *EAGetName (wchar_t *buf, int ea, int guiDisplay) -{ - if (guiDisplay) - { - EAGetDisplayName (buf, ea, EAGetLastCipher(ea)); - } - else - { - int i = EAGetLastCipher(ea); - wcscpy (buf, (i != 0) ? CipherGetName (i) : L"?"); - - while (i = EAGetPreviousCipher(ea, i)) - { - wcscat (buf, L"-"); - wcscat (buf, CipherGetName (i)); - } - } - return buf; -} - - -int EAGetByName (wchar_t *name) -{ - int ea = EAGetFirst (); - wchar_t n[128]; - - do - { - EAGetName (n, ea, 1); - if (_wcsicmp (n, name) == 0) - return ea; - } - while (ea = EAGetNext (ea)); - - return 0; -} - -#endif // TC_WINDOWS_BOOT - -// Returns sum of key sizes of all ciphers of the EA (in bytes) -int EAGetKeySize (int ea) -{ - int i = EAGetFirstCipher (ea); - int size = CipherGetKeySize (i); - - while (i = EAGetNextCipher (ea, i)) - { - size += CipherGetKeySize (i); - } - - return size; -} - - -// Returns the first mode of operation of EA -int EAGetFirstMode (int ea) -{ - return (EncryptionAlgorithms[ea].Modes[0]); -} - - -int EAGetNextMode (int ea, int previousModeId) -{ - int c, i = 0; - while (c = EncryptionAlgorithms[ea].Modes[i++]) - { - if (c == previousModeId) - return EncryptionAlgorithms[ea].Modes[i]; - } - - return 0; -} - - -#ifndef TC_WINDOWS_BOOT - -// Returns the name of the mode of operation of the whole EA -wchar_t *EAGetModeName (int ea, int mode, BOOL capitalLetters) -{ - switch (mode) - { - case XTS: - - return L"XTS"; - - } - return L"[unknown]"; -} - -#endif // TC_WINDOWS_BOOT - - -// Returns sum of key schedule sizes of all ciphers of the EA -int EAGetKeyScheduleSize (int ea) -{ - int i = EAGetFirstCipher(ea); - int size = CipherGetKeyScheduleSize (i); - - while (i = EAGetNextCipher(ea, i)) - { - size += CipherGetKeyScheduleSize (i); - } - - return size; -} - - -// Returns the largest key size needed by an EA for the specified mode of operation -int EAGetLargestKeyForMode (int mode) -{ - int ea, key = 0; - - for (ea = EAGetFirst (); ea != 0; ea = EAGetNext (ea)) - { - if (!EAIsModeSupported (ea, mode)) - continue; - - if (EAGetKeySize (ea) >= key) - key = EAGetKeySize (ea); - } - return key; -} - - -// Returns the largest key needed by any EA for any mode -int EAGetLargestKey () -{ - int ea, key = 0; - - for (ea = EAGetFirst (); ea != 0; ea = EAGetNext (ea)) - { - if (EAGetKeySize (ea) >= key) - key = EAGetKeySize (ea); - } - - return key; -} - - -// Returns number of ciphers in EA -int EAGetCipherCount (int ea) -{ - int i = 0; - while (EncryptionAlgorithms[ea].Ciphers[i++]); - - return i - 1; -} - - -int EAGetFirstCipher (int ea) -{ - return EncryptionAlgorithms[ea].Ciphers[0]; -} - - -int EAGetLastCipher (int ea) -{ - int c, i = 0; - while (c = EncryptionAlgorithms[ea].Ciphers[i++]); - - return EncryptionAlgorithms[ea].Ciphers[i - 2]; -} - - -int EAGetNextCipher (int ea, int previousCipherId) -{ - int c, i = 0; - while (c = EncryptionAlgorithms[ea].Ciphers[i++]) - { - if (c == previousCipherId) - return EncryptionAlgorithms[ea].Ciphers[i]; - } - - return 0; -} - - -int EAGetPreviousCipher (int ea, int previousCipherId) -{ - int c, i = 0; - - if (EncryptionAlgorithms[ea].Ciphers[i++] == previousCipherId) - return 0; - - while (c = EncryptionAlgorithms[ea].Ciphers[i++]) - { - if (c == previousCipherId) - return EncryptionAlgorithms[ea].Ciphers[i - 2]; - } - - return 0; -} - - -int EAIsFormatEnabled (int ea) -{ - return EncryptionAlgorithms[ea].FormatEnabled; -} - - -// Returns TRUE if the mode of operation is supported for the encryption algorithm -BOOL EAIsModeSupported (int ea, int testedMode) -{ - int mode; - - for (mode = EAGetFirstMode (ea); mode != 0; mode = EAGetNextMode (ea, mode)) - { - if (mode == testedMode) - return TRUE; - } - return FALSE; -} - -#ifndef TC_WINDOWS_BOOT -Hash *HashGet (int id) -{ - int i; - for (i = 0; Hashes[i].Id != 0; i++) - if (Hashes[i].Id == id) - return &Hashes[i]; - - return 0; -} - - -int HashGetIdByName (wchar_t *name) -{ - int i; - for (i = 0; Hashes[i].Id != 0; i++) - if (wcscmp (Hashes[i].Name, name) == 0) - return Hashes[i].Id; - - return 0; -} - -const wchar_t *HashGetName (int hashId) -{ - Hash* pHash = HashGet(hashId); - return pHash? pHash -> Name : L""; -} - -void HashGetName2 (wchar_t *buf, int hashId) -{ - Hash* pHash = HashGet(hashId); - if (pHash) - wcscpy(buf, pHash -> Name); - else - buf[0] = L'\0'; -} - -BOOL HashIsDeprecated (int hashId) -{ - Hash* pHash = HashGet(hashId); - return pHash? pHash -> Deprecated : FALSE; - -} - -BOOL HashForSystemEncryption (int hashId) -{ - Hash* pHash = HashGet(hashId); - return pHash? pHash -> SystemEncryption : FALSE; - -} - -// Returns the maximum number of bytes necessary to be generated by the PBKDF2 (PKCS #5) -int GetMaxPkcs5OutSize (void) -{ - int size = 32; - - size = max (size, EAGetLargestKeyForMode (XTS) * 2); // Sizes of primary + secondary keys - - return size; -} - -#endif - - -#endif // TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - - -#ifdef TC_WINDOWS_BOOT - -static byte CryptoInfoBufferInUse = 0; -CRYPTO_INFO CryptoInfoBuffer; - -#endif - -PCRYPTO_INFO crypto_open () -{ -#ifndef TC_WINDOWS_BOOT - - /* Do the crt allocation */ - PCRYPTO_INFO cryptoInfo = (PCRYPTO_INFO) TCalloc (sizeof (CRYPTO_INFO)); - if (cryptoInfo == NULL) - return NULL; - - memset (cryptoInfo, 0, sizeof (CRYPTO_INFO)); - -#ifndef DEVICE_DRIVER - VirtualLock (cryptoInfo, sizeof (CRYPTO_INFO)); -#endif - - cryptoInfo->ea = -1; - return cryptoInfo; - -#else // TC_WINDOWS_BOOT - -#if 0 - if (CryptoInfoBufferInUse) - TC_THROW_FATAL_EXCEPTION; -#endif - CryptoInfoBufferInUse = 1; - return &CryptoInfoBuffer; - -#endif // TC_WINDOWS_BOOT -} - -#ifndef TC_WINDOWS_BOOT -void crypto_loadkey (PKEY_INFO keyInfo, char *lpszUserKey, int nUserKeyLen) -{ - keyInfo->keyLength = nUserKeyLen; - burn (keyInfo->userKey, sizeof (keyInfo->userKey)); - memcpy (keyInfo->userKey, lpszUserKey, nUserKeyLen); -} -#endif - -void crypto_close (PCRYPTO_INFO cryptoInfo) -{ -#ifndef TC_WINDOWS_BOOT - - if (cryptoInfo != NULL) - { - burn (cryptoInfo, sizeof (CRYPTO_INFO)); -#ifndef DEVICE_DRIVER - VirtualUnlock (cryptoInfo, sizeof (CRYPTO_INFO)); -#endif - TCfree (cryptoInfo); - } - -#else // TC_WINDOWS_BOOT - - burn (&CryptoInfoBuffer, sizeof (CryptoInfoBuffer)); - CryptoInfoBufferInUse = FALSE; - -#endif // TC_WINDOWS_BOOT -} - - -#ifndef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - - - -// EncryptBuffer -// -// buf: data to be encrypted; the start of the buffer is assumed to be aligned with the start of a data unit. -// len: number of bytes to encrypt; must be divisible by the block size (for cascaded ciphers, divisible -// by the largest block size used within the cascade) -void EncryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo) -{ - switch (cryptoInfo->mode) - { - case XTS: - { - unsigned __int8 *ks = cryptoInfo->ks; - unsigned __int8 *ks2 = cryptoInfo->ks2; - UINT64_STRUCT dataUnitNo; - int cipher; - - // When encrypting/decrypting a buffer (typically a volume header) the sequential number - // of the first XTS data unit in the buffer is always 0 and the start of the buffer is - // always assumed to be aligned with the start of a data unit. - dataUnitNo.LowPart = 0; - dataUnitNo.HighPart = 0; - - for (cipher = EAGetFirstCipher (cryptoInfo->ea); - cipher != 0; - cipher = EAGetNextCipher (cryptoInfo->ea, cipher)) - { - EncryptBufferXTS (buf, len, &dataUnitNo, 0, ks, ks2, cipher); - - ks += CipherGetKeyScheduleSize (cipher); - ks2 += CipherGetKeyScheduleSize (cipher); - } - } - break; - - default: - // Unknown/wrong ID - TC_THROW_FATAL_EXCEPTION; - } -} - - -// buf: data to be encrypted -// unitNo: sequential number of the data unit with which the buffer starts -// nbrUnits: number of data units in the buffer -void EncryptDataUnits (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, uint32 nbrUnits, PCRYPTO_INFO ci) -#ifndef TC_WINDOWS_BOOT -{ - EncryptionThreadPoolDoWork (EncryptDataUnitsWork, buf, structUnitNo, nbrUnits, ci); -} - -void EncryptDataUnitsCurrentThread (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, TC_LARGEST_COMPILER_UINT nbrUnits, PCRYPTO_INFO ci) -#endif // !TC_WINDOWS_BOOT -{ - int ea = ci->ea; - unsigned __int8 *ks = ci->ks; - unsigned __int8 *ks2 = ci->ks2; - int cipher; - - switch (ci->mode) - { - case XTS: - for (cipher = EAGetFirstCipher (ea); cipher != 0; cipher = EAGetNextCipher (ea, cipher)) - { - EncryptBufferXTS (buf, - nbrUnits * ENCRYPTION_DATA_UNIT_SIZE, - structUnitNo, - 0, - ks, - ks2, - cipher); - - ks += CipherGetKeyScheduleSize (cipher); - ks2 += CipherGetKeyScheduleSize (cipher); - } - break; - - default: - // Unknown/wrong ID - TC_THROW_FATAL_EXCEPTION; - } -} - -// DecryptBuffer -// -// buf: data to be decrypted; the start of the buffer is assumed to be aligned with the start of a data unit. -// len: number of bytes to decrypt; must be divisible by the block size (for cascaded ciphers, divisible -// by the largest block size used within the cascade) -void DecryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo) -{ - switch (cryptoInfo->mode) - { - case XTS: - { - unsigned __int8 *ks = cryptoInfo->ks + EAGetKeyScheduleSize (cryptoInfo->ea); - unsigned __int8 *ks2 = cryptoInfo->ks2 + EAGetKeyScheduleSize (cryptoInfo->ea); - UINT64_STRUCT dataUnitNo; - int cipher; - - // When encrypting/decrypting a buffer (typically a volume header) the sequential number - // of the first XTS data unit in the buffer is always 0 and the start of the buffer is - // always assumed to be aligned with the start of the data unit 0. - dataUnitNo.LowPart = 0; - dataUnitNo.HighPart = 0; - - for (cipher = EAGetLastCipher (cryptoInfo->ea); - cipher != 0; - cipher = EAGetPreviousCipher (cryptoInfo->ea, cipher)) - { - ks -= CipherGetKeyScheduleSize (cipher); - ks2 -= CipherGetKeyScheduleSize (cipher); - - DecryptBufferXTS (buf, len, &dataUnitNo, 0, ks, ks2, cipher); - } - } - break; - - default: - // Unknown/wrong ID - TC_THROW_FATAL_EXCEPTION; - } -} - -// buf: data to be decrypted -// unitNo: sequential number of the data unit with which the buffer starts -// nbrUnits: number of data units in the buffer -void DecryptDataUnits (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, uint32 nbrUnits, PCRYPTO_INFO ci) -#ifndef TC_WINDOWS_BOOT -{ - EncryptionThreadPoolDoWork (DecryptDataUnitsWork, buf, structUnitNo, nbrUnits, ci); -} - -void DecryptDataUnitsCurrentThread (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, TC_LARGEST_COMPILER_UINT nbrUnits, PCRYPTO_INFO ci) -#endif // !TC_WINDOWS_BOOT -{ - int ea = ci->ea; - unsigned __int8 *ks = ci->ks; - unsigned __int8 *ks2 = ci->ks2; - int cipher; - - - switch (ci->mode) - { - case XTS: - ks += EAGetKeyScheduleSize (ea); - ks2 += EAGetKeyScheduleSize (ea); - - for (cipher = EAGetLastCipher (ea); cipher != 0; cipher = EAGetPreviousCipher (ea, cipher)) - { - ks -= CipherGetKeyScheduleSize (cipher); - ks2 -= CipherGetKeyScheduleSize (cipher); - - DecryptBufferXTS (buf, - nbrUnits * ENCRYPTION_DATA_UNIT_SIZE, - structUnitNo, - 0, - ks, - ks2, - cipher); - } - break; - - default: - // Unknown/wrong ID - TC_THROW_FATAL_EXCEPTION; - } -} - - -#else // TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - - -#if !defined (TC_WINDOWS_BOOT_AES) && !defined (TC_WINDOWS_BOOT_SERPENT) && !defined (TC_WINDOWS_BOOT_TWOFISH) -#error No cipher defined -#endif - -void EncipherBlock(int cipher, void *data, void *ks) -{ -#ifdef TC_WINDOWS_BOOT_AES - if (IsAesHwCpuSupported()) - aes_hw_cpu_encrypt ((byte *) ks, data); - else - aes_encrypt (data, data, ks); -#elif defined (TC_WINDOWS_BOOT_SERPENT) - serpent_encrypt (data, data, ks); -#elif defined (TC_WINDOWS_BOOT_TWOFISH) - twofish_encrypt (ks, data, data); -#endif -} - -void DecipherBlock(int cipher, void *data, void *ks) -{ -#ifdef TC_WINDOWS_BOOT_AES - if (IsAesHwCpuSupported()) - aes_hw_cpu_decrypt ((byte *) ks + sizeof (aes_encrypt_ctx) + 14 * 16, data); - else - aes_decrypt (data, data, (aes_decrypt_ctx *) ((byte *) ks + sizeof(aes_encrypt_ctx))); -#elif defined (TC_WINDOWS_BOOT_SERPENT) - serpent_decrypt (data, data, ks); -#elif defined (TC_WINDOWS_BOOT_TWOFISH) - twofish_decrypt (ks, data, data); -#endif -} - - -#ifdef TC_WINDOWS_BOOT_AES - -int EAInit (unsigned char *key, unsigned __int8 *ks) -{ - aes_init(); - - if (aes_encrypt_key256 (key, (aes_encrypt_ctx *) ks) != EXIT_SUCCESS) - return ERR_CIPHER_INIT_FAILURE; - if (aes_decrypt_key256 (key, (aes_decrypt_ctx *) (ks + sizeof (aes_encrypt_ctx))) != EXIT_SUCCESS) - return ERR_CIPHER_INIT_FAILURE; - - return ERR_SUCCESS; -} - -#endif - - -void EncryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo) -{ - UINT64_STRUCT dataUnitNo; - dataUnitNo.LowPart = 0; dataUnitNo.HighPart = 0; - EncryptBufferXTS (buf, len, &dataUnitNo, 0, cryptoInfo->ks, cryptoInfo->ks2, 1); -} - -void EncryptDataUnits (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, TC_LARGEST_COMPILER_UINT nbrUnits, PCRYPTO_INFO ci) -{ - EncryptBufferXTS (buf, nbrUnits * ENCRYPTION_DATA_UNIT_SIZE, structUnitNo, 0, ci->ks, ci->ks2, 1); -} - -void DecryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo) -{ - UINT64_STRUCT dataUnitNo; - dataUnitNo.LowPart = 0; dataUnitNo.HighPart = 0; - DecryptBufferXTS (buf, len, &dataUnitNo, 0, cryptoInfo->ks, cryptoInfo->ks2, 1); -} - -void DecryptDataUnits (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, TC_LARGEST_COMPILER_UINT nbrUnits, PCRYPTO_INFO ci) -{ - DecryptBufferXTS (buf, nbrUnits * ENCRYPTION_DATA_UNIT_SIZE, structUnitNo, 0, ci->ks, ci->ks2, 1); -} - -#endif // TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - - -#if !defined (TC_WINDOWS_BOOT) || defined (TC_WINDOWS_BOOT_AES) - -static BOOL HwEncryptionDisabled = FALSE; - -BOOL IsAesHwCpuSupported () -{ - static BOOL state = FALSE; - static BOOL stateValid = FALSE; - - if (!stateValid) - { - state = is_aes_hw_cpu_supported() ? TRUE : FALSE; - stateValid = TRUE; - } - - return state && !HwEncryptionDisabled; -} - -void EnableHwEncryption (BOOL enable) -{ -#if defined (TC_WINDOWS_BOOT) - if (enable) - aes_hw_cpu_enable_sse(); -#endif - - HwEncryptionDisabled = !enable; -} - -BOOL IsHwEncryptionEnabled () -{ - return !HwEncryptionDisabled; -} - -#endif // !TC_WINDOWS_BOOT +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" +#include "Crypto.h" +#include "Xts.h" +#include "Crc.h" +#include "Common/Endian.h" +#include +#ifndef TC_WINDOWS_BOOT +#include "EncryptionThreadPool.h" +#endif +#include "Volumes.h" + +/* Update the following when adding a new cipher or EA: + + Crypto.h: + ID #define + MAX_EXPANDED_KEY #define + + Crypto.c: + Ciphers[] + EncryptionAlgorithms[] + CipherInit() + EncipherBlock() + DecipherBlock() + +*/ + +#ifndef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + +// Cipher configuration +static Cipher Ciphers[] = +{ +// Block Size Key Size Key Schedule Size +// ID Name (Bytes) (Bytes) (Bytes) +#ifdef TC_WINDOWS_BOOT + { AES, "AES", 16, 32, AES_KS }, + { SERPENT, "Serpent", 16, 32, 140*4 }, + { TWOFISH, "Twofish", 16, 32, TWOFISH_KS }, +#else + { AES, L"AES", 16, 32, AES_KS }, + { SERPENT, L"Serpent", 16, 32, 140*4 }, + { TWOFISH, L"Twofish", 16, 32, TWOFISH_KS }, +#endif + { 0, 0, 0, 0, 0 } +}; + + +// Encryption algorithm configuration +static EncryptionAlgorithm EncryptionAlgorithms[] = +{ + // Cipher(s) Modes FormatEnabled + +#ifndef TC_WINDOWS_BOOT + + { { 0, 0 }, { 0, 0}, 0 }, // Must be all-zero + { { AES, 0 }, { XTS, 0 }, 1 }, + { { SERPENT, 0 }, { XTS, 0 }, 1 }, + { { TWOFISH, 0 }, { XTS, 0 }, 1 }, + { { TWOFISH, AES, 0 }, { XTS, 0 }, 1 }, + { { SERPENT, TWOFISH, AES, 0 }, { XTS, 0 }, 1 }, + { { AES, SERPENT, 0 }, { XTS, 0 }, 1 }, + { { AES, TWOFISH, SERPENT, 0 }, { XTS, 0 }, 1 }, + { { SERPENT, TWOFISH, 0 }, { XTS, 0 }, 1 }, + { { 0, 0 }, { 0, 0}, 0 } // Must be all-zero + +#else // TC_WINDOWS_BOOT + + // Encryption algorithms available for boot drive encryption + { { 0, 0 }, { 0, 0 }, 0 }, // Must be all-zero + { { AES, 0 }, { XTS, 0 }, 1 }, + { { SERPENT, 0 }, { XTS, 0 }, 1 }, + { { TWOFISH, 0 }, { XTS, 0 }, 1 }, + { { TWOFISH, AES, 0 }, { XTS, 0 }, 1 }, + { { SERPENT, TWOFISH, AES, 0 }, { XTS, 0 }, 1 }, + { { AES, SERPENT, 0 }, { XTS, 0 }, 1 }, + { { AES, TWOFISH, SERPENT, 0 }, { XTS, 0 }, 1 }, + { { SERPENT, TWOFISH, 0 }, { XTS, 0 }, 1 }, + { { 0, 0 }, { 0, 0 }, 0 }, // Must be all-zero + +#endif + +}; + + +#ifndef TC_WINDOWS_BOOT +// Hash algorithms +static Hash Hashes[] = +{ // ID Name Deprecated System Encryption + { SHA512, L"SHA-512", FALSE, FALSE }, + { WHIRLPOOL, L"Whirlpool", FALSE, FALSE }, + { SHA256, L"SHA-256", FALSE, TRUE }, + { RIPEMD160, L"RIPEMD-160", TRUE, TRUE }, + { 0, 0, 0 } +}; +#endif + +/* Return values: 0 = success, ERR_CIPHER_INIT_FAILURE (fatal), ERR_CIPHER_INIT_WEAK_KEY (non-fatal) */ +int CipherInit (int cipher, unsigned char *key, unsigned __int8 *ks) +{ + int retVal = ERR_SUCCESS; + + switch (cipher) + { + case AES: +#ifndef TC_WINDOWS_BOOT + if (aes_encrypt_key256 (key, (aes_encrypt_ctx *) ks) != EXIT_SUCCESS) + return ERR_CIPHER_INIT_FAILURE; + + if (aes_decrypt_key256 (key, (aes_decrypt_ctx *) (ks + sizeof(aes_encrypt_ctx))) != EXIT_SUCCESS) + return ERR_CIPHER_INIT_FAILURE; +#else + if (aes_set_key (key, (length_type) CipherGetKeySize(AES), (aes_context *) ks) != 0) + return ERR_CIPHER_INIT_FAILURE; +#endif + break; + + case SERPENT: + serpent_set_key (key, ks); + break; + + case TWOFISH: + twofish_set_key ((TwofishInstance *)ks, (const u4byte *)key); + break; + + default: + // Unknown/wrong cipher ID + return ERR_CIPHER_INIT_FAILURE; + } + + return retVal; +} + +void EncipherBlock(int cipher, void *data, void *ks) +{ + switch (cipher) + { + case AES: + // In 32-bit kernel mode, due to KeSaveFloatingPointState() overhead, AES instructions can be used only when processing the whole data unit. +#if (defined (_WIN64) || !defined (TC_WINDOWS_DRIVER)) && !defined (TC_WINDOWS_BOOT) + if (IsAesHwCpuSupported()) + aes_hw_cpu_encrypt (ks, data); + else +#endif + aes_encrypt (data, data, ks); + break; + + case TWOFISH: twofish_encrypt (ks, data, data); break; + case SERPENT: serpent_encrypt (data, data, ks); break; + default: TC_THROW_FATAL_EXCEPTION; // Unknown/wrong ID + } +} + +#ifndef TC_WINDOWS_BOOT + +void EncipherBlocks (int cipher, void *dataPtr, void *ks, size_t blockCount) +{ + byte *data = dataPtr; +#if defined (TC_WINDOWS_DRIVER) && !defined (_WIN64) + KFLOATING_SAVE floatingPointState; +#endif + + if (cipher == AES + && (blockCount & (32 - 1)) == 0 + && IsAesHwCpuSupported() +#if defined (TC_WINDOWS_DRIVER) && !defined (_WIN64) + && NT_SUCCESS (KeSaveFloatingPointState (&floatingPointState)) +#endif + ) + { + while (blockCount > 0) + { + aes_hw_cpu_encrypt_32_blocks (ks, data); + + data += 32 * 16; + blockCount -= 32; + } + +#if defined (TC_WINDOWS_DRIVER) && !defined (_WIN64) + KeRestoreFloatingPointState (&floatingPointState); +#endif + } + else + { + size_t blockSize = CipherGetBlockSize (cipher); + while (blockCount-- > 0) + { + EncipherBlock (cipher, data, ks); + data += blockSize; + } + } +} + +#endif // !TC_WINDOWS_BOOT + +void DecipherBlock(int cipher, void *data, void *ks) +{ + switch (cipher) + { + case SERPENT: serpent_decrypt (data, data, ks); break; + case TWOFISH: twofish_decrypt (ks, data, data); break; +#ifndef TC_WINDOWS_BOOT + + case AES: +#if defined (_WIN64) || !defined (TC_WINDOWS_DRIVER) + if (IsAesHwCpuSupported()) + aes_hw_cpu_decrypt ((byte *) ks + sizeof (aes_encrypt_ctx), data); + else +#endif + aes_decrypt (data, data, (void *) ((char *) ks + sizeof(aes_encrypt_ctx))); + break; + +#else + case AES: aes_decrypt (data, data, ks); break; +#endif + default: TC_THROW_FATAL_EXCEPTION; // Unknown/wrong ID + } +} + +#ifndef TC_WINDOWS_BOOT + +void DecipherBlocks (int cipher, void *dataPtr, void *ks, size_t blockCount) +{ + byte *data = dataPtr; +#if defined (TC_WINDOWS_DRIVER) && !defined (_WIN64) + KFLOATING_SAVE floatingPointState; +#endif + + if (cipher == AES + && (blockCount & (32 - 1)) == 0 + && IsAesHwCpuSupported() +#if defined (TC_WINDOWS_DRIVER) && !defined (_WIN64) + && NT_SUCCESS (KeSaveFloatingPointState (&floatingPointState)) +#endif + ) + { + while (blockCount > 0) + { + aes_hw_cpu_decrypt_32_blocks ((byte *) ks + sizeof (aes_encrypt_ctx), data); + + data += 32 * 16; + blockCount -= 32; + } + +#if defined (TC_WINDOWS_DRIVER) && !defined (_WIN64) + KeRestoreFloatingPointState (&floatingPointState); +#endif + } + else + { + size_t blockSize = CipherGetBlockSize (cipher); + while (blockCount-- > 0) + { + DecipherBlock (cipher, data, ks); + data += blockSize; + } + } +} + +#endif // !TC_WINDOWS_BOOT + + +// Ciphers support + +Cipher *CipherGet (int id) +{ + int i; + for (i = 0; Ciphers[i].Id != 0; i++) + if (Ciphers[i].Id == id) + return &Ciphers[i]; + + return NULL; +} + +#ifndef TC_WINDOWS_BOOT +const wchar_t *CipherGetName (int cipherId) +{ + Cipher* pCipher = CipherGet (cipherId); + return pCipher? pCipher -> Name : L""; +} +#endif + +int CipherGetBlockSize (int cipherId) +{ +#ifdef TC_WINDOWS_BOOT + return CipherGet (cipherId) -> BlockSize; +#else + Cipher* pCipher = CipherGet (cipherId); + return pCipher? pCipher -> BlockSize : 0; +#endif +} + +int CipherGetKeySize (int cipherId) +{ +#ifdef TC_WINDOWS_BOOT + return CipherGet (cipherId) -> KeySize; +#else + Cipher* pCipher = CipherGet (cipherId); + return pCipher? pCipher -> KeySize : 0; +#endif +} + +int CipherGetKeyScheduleSize (int cipherId) +{ +#ifdef TC_WINDOWS_BOOT + return CipherGet (cipherId) -> KeyScheduleSize; +#else + Cipher* pCipher = CipherGet (cipherId); + return pCipher? pCipher -> KeyScheduleSize : 0; +#endif +} + +#ifndef TC_WINDOWS_BOOT + +BOOL CipherSupportsIntraDataUnitParallelization (int cipher) +{ + return cipher == AES && IsAesHwCpuSupported(); +} + +#endif + + +// Encryption algorithms support + +int EAGetFirst () +{ + return 1; +} + +// Returns number of EAs +int EAGetCount (void) +{ + int ea, count = 0; + + for (ea = EAGetFirst (); ea != 0; ea = EAGetNext (ea)) + { + count++; + } + return count; +} + +int EAGetNext (int previousEA) +{ + int id = previousEA + 1; + if (EncryptionAlgorithms[id].Ciphers[0] != 0) return id; + return 0; +} + + +// Return values: 0 = success, ERR_CIPHER_INIT_FAILURE (fatal), ERR_CIPHER_INIT_WEAK_KEY (non-fatal) +int EAInit (int ea, unsigned char *key, unsigned __int8 *ks) +{ + int c, retVal = ERR_SUCCESS; + + if (ea == 0) + return ERR_CIPHER_INIT_FAILURE; + + for (c = EAGetFirstCipher (ea); c != 0; c = EAGetNextCipher (ea, c)) + { + switch (CipherInit (c, key, ks)) + { + case ERR_CIPHER_INIT_FAILURE: + return ERR_CIPHER_INIT_FAILURE; + + case ERR_CIPHER_INIT_WEAK_KEY: + retVal = ERR_CIPHER_INIT_WEAK_KEY; // Non-fatal error + break; + } + + key += CipherGetKeySize (c); + ks += CipherGetKeyScheduleSize (c); + } + return retVal; +} + + +#ifndef TC_WINDOWS_BOOT + +BOOL EAInitMode (PCRYPTO_INFO ci) +{ + switch (ci->mode) + { + case XTS: + // Secondary key schedule + if (EAInit (ci->ea, ci->k2, ci->ks2) != ERR_SUCCESS) + return FALSE; + + /* Note: XTS mode could potentially be initialized with a weak key causing all blocks in one data unit + on the volume to be tweaked with zero tweaks (i.e. 512 bytes of the volume would be encrypted in ECB + mode). However, to create a TrueCrypt volume with such a weak key, each human being on Earth would have + to create approximately 11,378,125,361,078,862 (about eleven quadrillion) TrueCrypt volumes (provided + that the size of each of the volumes is 1024 terabytes). */ + break; + + default: + // Unknown/wrong ID + TC_THROW_FATAL_EXCEPTION; + } + return TRUE; +} + +static void EAGetDisplayName(wchar_t *buf, int ea, int i) +{ + wcscpy (buf, CipherGetName (i)); + if (i = EAGetPreviousCipher(ea, i)) + { + wcscat (buf, L"("); + EAGetDisplayName (&buf[wcslen(buf)], ea, i); + wcscat (buf, L")"); + } +} + +// Returns name of EA, cascaded cipher names are separated by hyphens +wchar_t *EAGetName (wchar_t *buf, int ea, int guiDisplay) +{ + if (guiDisplay) + { + EAGetDisplayName (buf, ea, EAGetLastCipher(ea)); + } + else + { + int i = EAGetLastCipher(ea); + wcscpy (buf, (i != 0) ? CipherGetName (i) : L"?"); + + while (i = EAGetPreviousCipher(ea, i)) + { + wcscat (buf, L"-"); + wcscat (buf, CipherGetName (i)); + } + } + return buf; +} + + +int EAGetByName (wchar_t *name) +{ + int ea = EAGetFirst (); + wchar_t n[128]; + + do + { + EAGetName (n, ea, 1); + if (_wcsicmp (n, name) == 0) + return ea; + } + while (ea = EAGetNext (ea)); + + return 0; +} + +#endif // TC_WINDOWS_BOOT + +// Returns sum of key sizes of all ciphers of the EA (in bytes) +int EAGetKeySize (int ea) +{ + int i = EAGetFirstCipher (ea); + int size = CipherGetKeySize (i); + + while (i = EAGetNextCipher (ea, i)) + { + size += CipherGetKeySize (i); + } + + return size; +} + + +// Returns the first mode of operation of EA +int EAGetFirstMode (int ea) +{ + return (EncryptionAlgorithms[ea].Modes[0]); +} + + +int EAGetNextMode (int ea, int previousModeId) +{ + int c, i = 0; + while (c = EncryptionAlgorithms[ea].Modes[i++]) + { + if (c == previousModeId) + return EncryptionAlgorithms[ea].Modes[i]; + } + + return 0; +} + + +#ifndef TC_WINDOWS_BOOT + +// Returns the name of the mode of operation of the whole EA +wchar_t *EAGetModeName (int ea, int mode, BOOL capitalLetters) +{ + switch (mode) + { + case XTS: + + return L"XTS"; + + } + return L"[unknown]"; +} + +#endif // TC_WINDOWS_BOOT + + +// Returns sum of key schedule sizes of all ciphers of the EA +int EAGetKeyScheduleSize (int ea) +{ + int i = EAGetFirstCipher(ea); + int size = CipherGetKeyScheduleSize (i); + + while (i = EAGetNextCipher(ea, i)) + { + size += CipherGetKeyScheduleSize (i); + } + + return size; +} + + +// Returns the largest key size needed by an EA for the specified mode of operation +int EAGetLargestKeyForMode (int mode) +{ + int ea, key = 0; + + for (ea = EAGetFirst (); ea != 0; ea = EAGetNext (ea)) + { + if (!EAIsModeSupported (ea, mode)) + continue; + + if (EAGetKeySize (ea) >= key) + key = EAGetKeySize (ea); + } + return key; +} + + +// Returns the largest key needed by any EA for any mode +int EAGetLargestKey () +{ + int ea, key = 0; + + for (ea = EAGetFirst (); ea != 0; ea = EAGetNext (ea)) + { + if (EAGetKeySize (ea) >= key) + key = EAGetKeySize (ea); + } + + return key; +} + + +// Returns number of ciphers in EA +int EAGetCipherCount (int ea) +{ + int i = 0; + while (EncryptionAlgorithms[ea].Ciphers[i++]); + + return i - 1; +} + + +int EAGetFirstCipher (int ea) +{ + return EncryptionAlgorithms[ea].Ciphers[0]; +} + + +int EAGetLastCipher (int ea) +{ + int c, i = 0; + while (c = EncryptionAlgorithms[ea].Ciphers[i++]); + + return EncryptionAlgorithms[ea].Ciphers[i - 2]; +} + + +int EAGetNextCipher (int ea, int previousCipherId) +{ + int c, i = 0; + while (c = EncryptionAlgorithms[ea].Ciphers[i++]) + { + if (c == previousCipherId) + return EncryptionAlgorithms[ea].Ciphers[i]; + } + + return 0; +} + + +int EAGetPreviousCipher (int ea, int previousCipherId) +{ + int c, i = 0; + + if (EncryptionAlgorithms[ea].Ciphers[i++] == previousCipherId) + return 0; + + while (c = EncryptionAlgorithms[ea].Ciphers[i++]) + { + if (c == previousCipherId) + return EncryptionAlgorithms[ea].Ciphers[i - 2]; + } + + return 0; +} + + +int EAIsFormatEnabled (int ea) +{ + return EncryptionAlgorithms[ea].FormatEnabled; +} + + +// Returns TRUE if the mode of operation is supported for the encryption algorithm +BOOL EAIsModeSupported (int ea, int testedMode) +{ + int mode; + + for (mode = EAGetFirstMode (ea); mode != 0; mode = EAGetNextMode (ea, mode)) + { + if (mode == testedMode) + return TRUE; + } + return FALSE; +} + +#ifndef TC_WINDOWS_BOOT +Hash *HashGet (int id) +{ + int i; + for (i = 0; Hashes[i].Id != 0; i++) + if (Hashes[i].Id == id) + return &Hashes[i]; + + return 0; +} + + +int HashGetIdByName (wchar_t *name) +{ + int i; + for (i = 0; Hashes[i].Id != 0; i++) + if (wcscmp (Hashes[i].Name, name) == 0) + return Hashes[i].Id; + + return 0; +} + +const wchar_t *HashGetName (int hashId) +{ + Hash* pHash = HashGet(hashId); + return pHash? pHash -> Name : L""; +} + +void HashGetName2 (wchar_t *buf, int hashId) +{ + Hash* pHash = HashGet(hashId); + if (pHash) + wcscpy(buf, pHash -> Name); + else + buf[0] = L'\0'; +} + +BOOL HashIsDeprecated (int hashId) +{ + Hash* pHash = HashGet(hashId); + return pHash? pHash -> Deprecated : FALSE; + +} + +BOOL HashForSystemEncryption (int hashId) +{ + Hash* pHash = HashGet(hashId); + return pHash? pHash -> SystemEncryption : FALSE; + +} + +// Returns the maximum number of bytes necessary to be generated by the PBKDF2 (PKCS #5) +int GetMaxPkcs5OutSize (void) +{ + int size = 32; + + size = max (size, EAGetLargestKeyForMode (XTS) * 2); // Sizes of primary + secondary keys + + return size; +} + +#endif + + +#endif // TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + + +#ifdef TC_WINDOWS_BOOT + +static byte CryptoInfoBufferInUse = 0; +CRYPTO_INFO CryptoInfoBuffer; + +#endif + +PCRYPTO_INFO crypto_open () +{ +#ifndef TC_WINDOWS_BOOT + + /* Do the crt allocation */ + PCRYPTO_INFO cryptoInfo = (PCRYPTO_INFO) TCalloc (sizeof (CRYPTO_INFO)); + if (cryptoInfo == NULL) + return NULL; + + memset (cryptoInfo, 0, sizeof (CRYPTO_INFO)); + +#ifndef DEVICE_DRIVER + VirtualLock (cryptoInfo, sizeof (CRYPTO_INFO)); +#endif + + cryptoInfo->ea = -1; + return cryptoInfo; + +#else // TC_WINDOWS_BOOT + +#if 0 + if (CryptoInfoBufferInUse) + TC_THROW_FATAL_EXCEPTION; +#endif + CryptoInfoBufferInUse = 1; + return &CryptoInfoBuffer; + +#endif // TC_WINDOWS_BOOT +} + +#ifndef TC_WINDOWS_BOOT +void crypto_loadkey (PKEY_INFO keyInfo, char *lpszUserKey, int nUserKeyLen) +{ + keyInfo->keyLength = nUserKeyLen; + burn (keyInfo->userKey, sizeof (keyInfo->userKey)); + memcpy (keyInfo->userKey, lpszUserKey, nUserKeyLen); +} +#endif + +void crypto_close (PCRYPTO_INFO cryptoInfo) +{ +#ifndef TC_WINDOWS_BOOT + + if (cryptoInfo != NULL) + { + burn (cryptoInfo, sizeof (CRYPTO_INFO)); +#ifndef DEVICE_DRIVER + VirtualUnlock (cryptoInfo, sizeof (CRYPTO_INFO)); +#endif + TCfree (cryptoInfo); + } + +#else // TC_WINDOWS_BOOT + + burn (&CryptoInfoBuffer, sizeof (CryptoInfoBuffer)); + CryptoInfoBufferInUse = FALSE; + +#endif // TC_WINDOWS_BOOT +} + + +#ifndef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + + + +// EncryptBuffer +// +// buf: data to be encrypted; the start of the buffer is assumed to be aligned with the start of a data unit. +// len: number of bytes to encrypt; must be divisible by the block size (for cascaded ciphers, divisible +// by the largest block size used within the cascade) +void EncryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo) +{ + switch (cryptoInfo->mode) + { + case XTS: + { + unsigned __int8 *ks = cryptoInfo->ks; + unsigned __int8 *ks2 = cryptoInfo->ks2; + UINT64_STRUCT dataUnitNo; + int cipher; + + // When encrypting/decrypting a buffer (typically a volume header) the sequential number + // of the first XTS data unit in the buffer is always 0 and the start of the buffer is + // always assumed to be aligned with the start of a data unit. + dataUnitNo.LowPart = 0; + dataUnitNo.HighPart = 0; + + for (cipher = EAGetFirstCipher (cryptoInfo->ea); + cipher != 0; + cipher = EAGetNextCipher (cryptoInfo->ea, cipher)) + { + EncryptBufferXTS (buf, len, &dataUnitNo, 0, ks, ks2, cipher); + + ks += CipherGetKeyScheduleSize (cipher); + ks2 += CipherGetKeyScheduleSize (cipher); + } + } + break; + + default: + // Unknown/wrong ID + TC_THROW_FATAL_EXCEPTION; + } +} + + +// buf: data to be encrypted +// unitNo: sequential number of the data unit with which the buffer starts +// nbrUnits: number of data units in the buffer +void EncryptDataUnits (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, uint32 nbrUnits, PCRYPTO_INFO ci) +#ifndef TC_WINDOWS_BOOT +{ + EncryptionThreadPoolDoWork (EncryptDataUnitsWork, buf, structUnitNo, nbrUnits, ci); +} + +void EncryptDataUnitsCurrentThread (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, TC_LARGEST_COMPILER_UINT nbrUnits, PCRYPTO_INFO ci) +#endif // !TC_WINDOWS_BOOT +{ + int ea = ci->ea; + unsigned __int8 *ks = ci->ks; + unsigned __int8 *ks2 = ci->ks2; + int cipher; + + switch (ci->mode) + { + case XTS: + for (cipher = EAGetFirstCipher (ea); cipher != 0; cipher = EAGetNextCipher (ea, cipher)) + { + EncryptBufferXTS (buf, + nbrUnits * ENCRYPTION_DATA_UNIT_SIZE, + structUnitNo, + 0, + ks, + ks2, + cipher); + + ks += CipherGetKeyScheduleSize (cipher); + ks2 += CipherGetKeyScheduleSize (cipher); + } + break; + + default: + // Unknown/wrong ID + TC_THROW_FATAL_EXCEPTION; + } +} + +// DecryptBuffer +// +// buf: data to be decrypted; the start of the buffer is assumed to be aligned with the start of a data unit. +// len: number of bytes to decrypt; must be divisible by the block size (for cascaded ciphers, divisible +// by the largest block size used within the cascade) +void DecryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo) +{ + switch (cryptoInfo->mode) + { + case XTS: + { + unsigned __int8 *ks = cryptoInfo->ks + EAGetKeyScheduleSize (cryptoInfo->ea); + unsigned __int8 *ks2 = cryptoInfo->ks2 + EAGetKeyScheduleSize (cryptoInfo->ea); + UINT64_STRUCT dataUnitNo; + int cipher; + + // When encrypting/decrypting a buffer (typically a volume header) the sequential number + // of the first XTS data unit in the buffer is always 0 and the start of the buffer is + // always assumed to be aligned with the start of the data unit 0. + dataUnitNo.LowPart = 0; + dataUnitNo.HighPart = 0; + + for (cipher = EAGetLastCipher (cryptoInfo->ea); + cipher != 0; + cipher = EAGetPreviousCipher (cryptoInfo->ea, cipher)) + { + ks -= CipherGetKeyScheduleSize (cipher); + ks2 -= CipherGetKeyScheduleSize (cipher); + + DecryptBufferXTS (buf, len, &dataUnitNo, 0, ks, ks2, cipher); + } + } + break; + + default: + // Unknown/wrong ID + TC_THROW_FATAL_EXCEPTION; + } +} + +// buf: data to be decrypted +// unitNo: sequential number of the data unit with which the buffer starts +// nbrUnits: number of data units in the buffer +void DecryptDataUnits (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, uint32 nbrUnits, PCRYPTO_INFO ci) +#ifndef TC_WINDOWS_BOOT +{ + EncryptionThreadPoolDoWork (DecryptDataUnitsWork, buf, structUnitNo, nbrUnits, ci); +} + +void DecryptDataUnitsCurrentThread (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, TC_LARGEST_COMPILER_UINT nbrUnits, PCRYPTO_INFO ci) +#endif // !TC_WINDOWS_BOOT +{ + int ea = ci->ea; + unsigned __int8 *ks = ci->ks; + unsigned __int8 *ks2 = ci->ks2; + int cipher; + + + switch (ci->mode) + { + case XTS: + ks += EAGetKeyScheduleSize (ea); + ks2 += EAGetKeyScheduleSize (ea); + + for (cipher = EAGetLastCipher (ea); cipher != 0; cipher = EAGetPreviousCipher (ea, cipher)) + { + ks -= CipherGetKeyScheduleSize (cipher); + ks2 -= CipherGetKeyScheduleSize (cipher); + + DecryptBufferXTS (buf, + nbrUnits * ENCRYPTION_DATA_UNIT_SIZE, + structUnitNo, + 0, + ks, + ks2, + cipher); + } + break; + + default: + // Unknown/wrong ID + TC_THROW_FATAL_EXCEPTION; + } +} + + +#else // TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + + +#if !defined (TC_WINDOWS_BOOT_AES) && !defined (TC_WINDOWS_BOOT_SERPENT) && !defined (TC_WINDOWS_BOOT_TWOFISH) +#error No cipher defined +#endif + +void EncipherBlock(int cipher, void *data, void *ks) +{ +#ifdef TC_WINDOWS_BOOT_AES + if (IsAesHwCpuSupported()) + aes_hw_cpu_encrypt ((byte *) ks, data); + else + aes_encrypt (data, data, ks); +#elif defined (TC_WINDOWS_BOOT_SERPENT) + serpent_encrypt (data, data, ks); +#elif defined (TC_WINDOWS_BOOT_TWOFISH) + twofish_encrypt (ks, data, data); +#endif +} + +void DecipherBlock(int cipher, void *data, void *ks) +{ +#ifdef TC_WINDOWS_BOOT_AES + if (IsAesHwCpuSupported()) + aes_hw_cpu_decrypt ((byte *) ks + sizeof (aes_encrypt_ctx) + 14 * 16, data); + else + aes_decrypt (data, data, (aes_decrypt_ctx *) ((byte *) ks + sizeof(aes_encrypt_ctx))); +#elif defined (TC_WINDOWS_BOOT_SERPENT) + serpent_decrypt (data, data, ks); +#elif defined (TC_WINDOWS_BOOT_TWOFISH) + twofish_decrypt (ks, data, data); +#endif +} + + +#ifdef TC_WINDOWS_BOOT_AES + +int EAInit (unsigned char *key, unsigned __int8 *ks) +{ + aes_init(); + + if (aes_encrypt_key256 (key, (aes_encrypt_ctx *) ks) != EXIT_SUCCESS) + return ERR_CIPHER_INIT_FAILURE; + if (aes_decrypt_key256 (key, (aes_decrypt_ctx *) (ks + sizeof (aes_encrypt_ctx))) != EXIT_SUCCESS) + return ERR_CIPHER_INIT_FAILURE; + + return ERR_SUCCESS; +} + +#endif + + +void EncryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo) +{ + UINT64_STRUCT dataUnitNo; + dataUnitNo.LowPart = 0; dataUnitNo.HighPart = 0; + EncryptBufferXTS (buf, len, &dataUnitNo, 0, cryptoInfo->ks, cryptoInfo->ks2, 1); +} + +void EncryptDataUnits (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, TC_LARGEST_COMPILER_UINT nbrUnits, PCRYPTO_INFO ci) +{ + EncryptBufferXTS (buf, nbrUnits * ENCRYPTION_DATA_UNIT_SIZE, structUnitNo, 0, ci->ks, ci->ks2, 1); +} + +void DecryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo) +{ + UINT64_STRUCT dataUnitNo; + dataUnitNo.LowPart = 0; dataUnitNo.HighPart = 0; + DecryptBufferXTS (buf, len, &dataUnitNo, 0, cryptoInfo->ks, cryptoInfo->ks2, 1); +} + +void DecryptDataUnits (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, TC_LARGEST_COMPILER_UINT nbrUnits, PCRYPTO_INFO ci) +{ + DecryptBufferXTS (buf, nbrUnits * ENCRYPTION_DATA_UNIT_SIZE, structUnitNo, 0, ci->ks, ci->ks2, 1); +} + +#endif // TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + + +#if !defined (TC_WINDOWS_BOOT) || defined (TC_WINDOWS_BOOT_AES) + +static BOOL HwEncryptionDisabled = FALSE; + +BOOL IsAesHwCpuSupported () +{ + static BOOL state = FALSE; + static BOOL stateValid = FALSE; + + if (!stateValid) + { + state = is_aes_hw_cpu_supported() ? TRUE : FALSE; + stateValid = TRUE; + } + + return state && !HwEncryptionDisabled; +} + +void EnableHwEncryption (BOOL enable) +{ +#if defined (TC_WINDOWS_BOOT) + if (enable) + aes_hw_cpu_enable_sse(); +#endif + + HwEncryptionDisabled = !enable; +} + +BOOL IsHwEncryptionEnabled () +{ + return !HwEncryptionDisabled; +} + +#endif // !TC_WINDOWS_BOOT diff --git a/src/Common/Crypto.h b/src/Common/Crypto.h index e081dc60..96f0a9a6 100644 --- a/src/Common/Crypto.h +++ b/src/Common/Crypto.h @@ -1,363 +1,363 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -/* Update the following when adding a new cipher or EA: - - Crypto.h: - ID #define - MAX_EXPANDED_KEY #define - - Crypto.c: - Ciphers[] - EncryptionAlgorithms[] - CipherInit() - EncipherBlock() - DecipherBlock() - -*/ - -#ifndef CRYPTO_H -#define CRYPTO_H - -#include "Tcdefs.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// Encryption data unit size, which may differ from the sector size and must always be 512 -#define ENCRYPTION_DATA_UNIT_SIZE 512 - -// Size of the salt (in bytes) -#define PKCS5_SALT_SIZE 64 - -// Size of the volume header area containing concatenated master key(s) and secondary key(s) (XTS mode) -#define MASTER_KEYDATA_SIZE 256 - -// The first PRF to try when mounting -#define FIRST_PRF_ID 1 - -// Hash algorithms (pseudorandom functions). -enum -{ - SHA512 = FIRST_PRF_ID, - WHIRLPOOL, - SHA256, - RIPEMD160, - HASH_ENUM_END_ID -}; - -// The last PRF to try when mounting and also the number of implemented PRFs -#define LAST_PRF_ID (HASH_ENUM_END_ID - 1) - -#define RIPEMD160_BLOCKSIZE 64 -#define RIPEMD160_DIGESTSIZE 20 - -#define SHA256_BLOCKSIZE 64 -#define SHA256_DIGESTSIZE 32 - -#define SHA512_BLOCKSIZE 128 -#define SHA512_DIGESTSIZE 64 - -#define WHIRLPOOL_BLOCKSIZE 64 -#define WHIRLPOOL_DIGESTSIZE 64 - -#define MAX_DIGESTSIZE WHIRLPOOL_DIGESTSIZE - -#define DEFAULT_HASH_ALGORITHM FIRST_PRF_ID -#define DEFAULT_HASH_ALGORITHM_BOOT SHA256 - -// The mode of operation used for newly created volumes and first to try when mounting -#define FIRST_MODE_OF_OPERATION_ID 1 - -// Modes of operation -enum -{ - /* If you add/remove a mode, update the following: GetMaxPkcs5OutSize(), EAInitMode() */ - - XTS = FIRST_MODE_OF_OPERATION_ID, - MODE_ENUM_END_ID -}; - - -// The last mode of operation to try when mounting and also the number of implemented modes -#define LAST_MODE_OF_OPERATION (MODE_ENUM_END_ID - 1) - -// Ciphertext/plaintext block size for XTS mode (in bytes) -#define BYTES_PER_XTS_BLOCK 16 - -// Number of ciphertext/plaintext blocks per XTS data unit -#define BLOCKS_PER_XTS_DATA_UNIT (ENCRYPTION_DATA_UNIT_SIZE / BYTES_PER_XTS_BLOCK) - - -// Cipher IDs -enum -{ - NONE = 0, - AES, - SERPENT, - TWOFISH -}; - -typedef struct -{ - int Id; // Cipher ID -#ifdef TC_WINDOWS_BOOT - char *Name; // Name -#else - wchar_t *Name; // Name -#endif - int BlockSize; // Block size (bytes) - int KeySize; // Key size (bytes) - int KeyScheduleSize; // Scheduled key size (bytes) -} Cipher; - -typedef struct -{ - int Ciphers[4]; // Null terminated array of ciphers used by encryption algorithm - int Modes[LAST_MODE_OF_OPERATION + 1]; // Null terminated array of modes of operation - int FormatEnabled; -} EncryptionAlgorithm; - -#ifndef TC_WINDOWS_BOOT -typedef struct -{ - int Id; // Hash ID - wchar_t *Name; // Name - BOOL Deprecated; - BOOL SystemEncryption; // Available for system encryption -} Hash; -#endif - -// Maxium length of scheduled key -#if !defined (TC_WINDOWS_BOOT) || defined (TC_WINDOWS_BOOT_AES) -# define AES_KS (sizeof(aes_encrypt_ctx) + sizeof(aes_decrypt_ctx)) -#else -# define AES_KS (sizeof(aes_context)) -#endif -#define SERPENT_KS (140 * 4) - -#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - -# ifdef TC_WINDOWS_BOOT_AES -# define MAX_EXPANDED_KEY AES_KS -# elif defined (TC_WINDOWS_BOOT_SERPENT) -# define MAX_EXPANDED_KEY SERPENT_KS -# elif defined (TC_WINDOWS_BOOT_TWOFISH) -# define MAX_EXPANDED_KEY TWOFISH_KS -# endif - -#else - -#define MAX_EXPANDED_KEY (AES_KS + SERPENT_KS + TWOFISH_KS) - -#endif - -#ifdef DEBUG -# define PRAND_DISK_WIPE_PASSES 3 -#else -# define PRAND_DISK_WIPE_PASSES 256 -#endif - -/* specific value for volume header wipe used only when drive is fully wiped. */ -#define PRAND_HEADER_WIPE_PASSES 3 - -#if !defined (TC_WINDOWS_BOOT) || defined (TC_WINDOWS_BOOT_AES) -# include "Aes.h" -#else -# include "AesSmall.h" -#endif - -#include "Aes_hw_cpu.h" -#include "Serpent.h" -#include "Twofish.h" - -#include "Rmd160.h" -#ifndef TC_WINDOWS_BOOT -# include "Sha2.h" -# include "Whirlpool.h" -#endif - -#include "GfMul.h" -#include "Password.h" - -#ifndef TC_WINDOWS_BOOT - -#include "config.h" - -typedef struct keyInfo_t -{ - int noIterations; /* Number of times to iterate (PKCS-5) */ - int keyLength; /* Length of the key */ - uint64 dummy; /* Dummy field to ensure 16-byte alignment of this structure */ - __int8 salt[PKCS5_SALT_SIZE]; /* PKCS-5 salt */ - __int8 master_keydata[MASTER_KEYDATA_SIZE]; /* Concatenated master primary and secondary key(s) (XTS mode). For LRW (deprecated/legacy), it contains the tweak key before the master key(s). For CBC (deprecated/legacy), it contains the IV seed before the master key(s). */ - CRYPTOPP_ALIGN_DATA(16) __int8 userKey[MAX_PASSWORD]; /* Password (to which keyfiles may have been applied). WITHOUT +1 for the null terminator. */ -} KEY_INFO, *PKEY_INFO; - -#endif - -typedef struct CRYPTO_INFO_t -{ - int ea; /* Encryption algorithm ID */ - int mode; /* Mode of operation (e.g., XTS) */ - int pkcs5; /* PRF algorithm */ - - unsigned __int8 ks[MAX_EXPANDED_KEY]; /* Primary key schedule (if it is a cascade, it conatins multiple concatenated keys) */ - unsigned __int8 ks2[MAX_EXPANDED_KEY]; /* Secondary key schedule (if cascade, multiple concatenated) for XTS mode. */ - - BOOL hiddenVolume; // Indicates whether the volume is mounted/mountable as hidden volume - -#ifndef TC_WINDOWS_BOOT - uint16 HeaderVersion; - - GfCtx gf_ctx; - - unsigned __int8 master_keydata[MASTER_KEYDATA_SIZE]; /* This holds the volume header area containing concatenated master key(s) and secondary key(s) (XTS mode). For LRW (deprecated/legacy), it contains the tweak key before the master key(s). For CBC (deprecated/legacy), it contains the IV seed before the master key(s). */ - unsigned __int8 k2[MASTER_KEYDATA_SIZE]; /* For XTS, this contains the secondary key (if cascade, multiple concatenated). For LRW (deprecated/legacy), it contains the tweak key. For CBC (deprecated/legacy), it contains the IV seed. */ - unsigned __int8 salt[PKCS5_SALT_SIZE]; - int noIterations; - BOOL bTrueCryptMode; - int volumePim; - - uint64 volume_creation_time; // Legacy - uint64 header_creation_time; // Legacy - - BOOL bProtectHiddenVolume; // Indicates whether the volume contains a hidden volume to be protected against overwriting - BOOL bHiddenVolProtectionAction; // TRUE if a write operation has been denied by the driver in order to prevent the hidden volume from being overwritten (set to FALSE upon volume mount). - - uint64 volDataAreaOffset; // Absolute position, in bytes, of the first data sector of the volume. - - uint64 hiddenVolumeSize; // Size of the hidden volume excluding the header (in bytes). Set to 0 for standard volumes. - uint64 hiddenVolumeOffset; // Absolute position, in bytes, of the first hidden volume data sector within the host volume (provided that there is a hidden volume within). This must be set for all hidden volumes; in case of a normal volume, this variable is only used when protecting a hidden volume within it. - uint64 hiddenVolumeProtectedSize; - - BOOL bPartitionInInactiveSysEncScope; // If TRUE, the volume is a partition located on an encrypted system drive and mounted without pre-boot authentication. - - UINT64_STRUCT FirstDataUnitNo; // First data unit number of the volume. This is 0 for file-hosted and non-system partition-hosted volumes. For partitions within key scope of system encryption this reflects real physical offset within the device (this is used e.g. when such a partition is mounted as a regular volume without pre-boot authentication). - - uint16 RequiredProgramVersion; - BOOL LegacyVolume; - - uint32 SectorSize; - -#endif // !TC_WINDOWS_BOOT - - UINT64_STRUCT VolumeSize; - - UINT64_STRUCT EncryptedAreaStart; - UINT64_STRUCT EncryptedAreaLength; - - uint32 HeaderFlags; - -} CRYPTO_INFO, *PCRYPTO_INFO; - -#ifdef _WIN32 - -#pragma pack (push) -#pragma pack(1) - -typedef struct BOOT_CRYPTO_HEADER_t -{ - __int16 ea; /* Encryption algorithm ID */ - __int16 mode; /* Mode of operation (e.g., XTS) */ - __int16 pkcs5; /* PRF algorithm */ - -} BOOT_CRYPTO_HEADER, *PBOOT_CRYPTO_HEADER; - -#pragma pack (pop) - -#endif - -PCRYPTO_INFO crypto_open (void); -#ifndef TC_WINDOWS_BOOT -void crypto_loadkey (PKEY_INFO keyInfo, char *lpszUserKey, int nUserKeyLen); -#endif -void crypto_close (PCRYPTO_INFO cryptoInfo); - -int CipherGetBlockSize (int cipher); -int CipherGetKeySize (int cipher); -int CipherGetKeyScheduleSize (int cipher); -BOOL CipherSupportsIntraDataUnitParallelization (int cipher); - -#ifndef TC_WINDOWS_BOOT -const wchar_t * CipherGetName (int cipher); -#endif - -int CipherInit (int cipher, unsigned char *key, unsigned char *ks); -#ifndef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE -int EAInit (int ea, unsigned char *key, unsigned char *ks); -#else -int EAInit (unsigned char *key, unsigned char *ks); -#endif -BOOL EAInitMode (PCRYPTO_INFO ci); -void EncipherBlock(int cipher, void *data, void *ks); -void DecipherBlock(int cipher, void *data, void *ks); -#ifndef TC_WINDOWS_BOOT -void EncipherBlocks (int cipher, void *dataPtr, void *ks, size_t blockCount); -void DecipherBlocks (int cipher, void *dataPtr, void *ks, size_t blockCount); -#endif - -int EAGetFirst (); -int EAGetCount (void); -int EAGetNext (int previousEA); -#ifndef TC_WINDOWS_BOOT -wchar_t * EAGetName (wchar_t *buf, int ea, int guiDisplay); -int EAGetByName (wchar_t *name); -#endif -int EAGetKeySize (int ea); -int EAGetFirstMode (int ea); -int EAGetNextMode (int ea, int previousModeId); -#ifndef TC_WINDOWS_BOOT -wchar_t * EAGetModeName (int ea, int mode, BOOL capitalLetters); -#endif -int EAGetKeyScheduleSize (int ea); -int EAGetLargestKey (); -int EAGetLargestKeyForMode (int mode); - -int EAGetCipherCount (int ea); -int EAGetFirstCipher (int ea); -int EAGetLastCipher (int ea); -int EAGetNextCipher (int ea, int previousCipherId); -int EAGetPreviousCipher (int ea, int previousCipherId); -int EAIsFormatEnabled (int ea); -BOOL EAIsModeSupported (int ea, int testedMode); - - -#ifndef TC_WINDOWS_BOOT -const wchar_t *HashGetName (int hash_algo_id); - -Hash *HashGet (int id); -void HashGetName2 (wchar_t *buf, int hashId); -BOOL HashIsDeprecated (int hashId); -BOOL HashForSystemEncryption (int hashId); -int GetMaxPkcs5OutSize (void); -#endif - - -void EncryptDataUnits (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, uint32 nbrUnits, PCRYPTO_INFO ci); -void EncryptDataUnitsCurrentThread (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, TC_LARGEST_COMPILER_UINT nbrUnits, PCRYPTO_INFO ci); -void DecryptDataUnits (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, uint32 nbrUnits, PCRYPTO_INFO ci); -void DecryptDataUnitsCurrentThread (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, TC_LARGEST_COMPILER_UINT nbrUnits, PCRYPTO_INFO ci); -void EncryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo); -void DecryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo); - -BOOL IsAesHwCpuSupported (); -void EnableHwEncryption (BOOL enable); -BOOL IsHwEncryptionEnabled (); - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTO_H */ +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +/* Update the following when adding a new cipher or EA: + + Crypto.h: + ID #define + MAX_EXPANDED_KEY #define + + Crypto.c: + Ciphers[] + EncryptionAlgorithms[] + CipherInit() + EncipherBlock() + DecipherBlock() + +*/ + +#ifndef CRYPTO_H +#define CRYPTO_H + +#include "Tcdefs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// Encryption data unit size, which may differ from the sector size and must always be 512 +#define ENCRYPTION_DATA_UNIT_SIZE 512 + +// Size of the salt (in bytes) +#define PKCS5_SALT_SIZE 64 + +// Size of the volume header area containing concatenated master key(s) and secondary key(s) (XTS mode) +#define MASTER_KEYDATA_SIZE 256 + +// The first PRF to try when mounting +#define FIRST_PRF_ID 1 + +// Hash algorithms (pseudorandom functions). +enum +{ + SHA512 = FIRST_PRF_ID, + WHIRLPOOL, + SHA256, + RIPEMD160, + HASH_ENUM_END_ID +}; + +// The last PRF to try when mounting and also the number of implemented PRFs +#define LAST_PRF_ID (HASH_ENUM_END_ID - 1) + +#define RIPEMD160_BLOCKSIZE 64 +#define RIPEMD160_DIGESTSIZE 20 + +#define SHA256_BLOCKSIZE 64 +#define SHA256_DIGESTSIZE 32 + +#define SHA512_BLOCKSIZE 128 +#define SHA512_DIGESTSIZE 64 + +#define WHIRLPOOL_BLOCKSIZE 64 +#define WHIRLPOOL_DIGESTSIZE 64 + +#define MAX_DIGESTSIZE WHIRLPOOL_DIGESTSIZE + +#define DEFAULT_HASH_ALGORITHM FIRST_PRF_ID +#define DEFAULT_HASH_ALGORITHM_BOOT SHA256 + +// The mode of operation used for newly created volumes and first to try when mounting +#define FIRST_MODE_OF_OPERATION_ID 1 + +// Modes of operation +enum +{ + /* If you add/remove a mode, update the following: GetMaxPkcs5OutSize(), EAInitMode() */ + + XTS = FIRST_MODE_OF_OPERATION_ID, + MODE_ENUM_END_ID +}; + + +// The last mode of operation to try when mounting and also the number of implemented modes +#define LAST_MODE_OF_OPERATION (MODE_ENUM_END_ID - 1) + +// Ciphertext/plaintext block size for XTS mode (in bytes) +#define BYTES_PER_XTS_BLOCK 16 + +// Number of ciphertext/plaintext blocks per XTS data unit +#define BLOCKS_PER_XTS_DATA_UNIT (ENCRYPTION_DATA_UNIT_SIZE / BYTES_PER_XTS_BLOCK) + + +// Cipher IDs +enum +{ + NONE = 0, + AES, + SERPENT, + TWOFISH +}; + +typedef struct +{ + int Id; // Cipher ID +#ifdef TC_WINDOWS_BOOT + char *Name; // Name +#else + wchar_t *Name; // Name +#endif + int BlockSize; // Block size (bytes) + int KeySize; // Key size (bytes) + int KeyScheduleSize; // Scheduled key size (bytes) +} Cipher; + +typedef struct +{ + int Ciphers[4]; // Null terminated array of ciphers used by encryption algorithm + int Modes[LAST_MODE_OF_OPERATION + 1]; // Null terminated array of modes of operation + int FormatEnabled; +} EncryptionAlgorithm; + +#ifndef TC_WINDOWS_BOOT +typedef struct +{ + int Id; // Hash ID + wchar_t *Name; // Name + BOOL Deprecated; + BOOL SystemEncryption; // Available for system encryption +} Hash; +#endif + +// Maxium length of scheduled key +#if !defined (TC_WINDOWS_BOOT) || defined (TC_WINDOWS_BOOT_AES) +# define AES_KS (sizeof(aes_encrypt_ctx) + sizeof(aes_decrypt_ctx)) +#else +# define AES_KS (sizeof(aes_context)) +#endif +#define SERPENT_KS (140 * 4) + +#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + +# ifdef TC_WINDOWS_BOOT_AES +# define MAX_EXPANDED_KEY AES_KS +# elif defined (TC_WINDOWS_BOOT_SERPENT) +# define MAX_EXPANDED_KEY SERPENT_KS +# elif defined (TC_WINDOWS_BOOT_TWOFISH) +# define MAX_EXPANDED_KEY TWOFISH_KS +# endif + +#else + +#define MAX_EXPANDED_KEY (AES_KS + SERPENT_KS + TWOFISH_KS) + +#endif + +#ifdef DEBUG +# define PRAND_DISK_WIPE_PASSES 3 +#else +# define PRAND_DISK_WIPE_PASSES 256 +#endif + +/* specific value for volume header wipe used only when drive is fully wiped. */ +#define PRAND_HEADER_WIPE_PASSES 3 + +#if !defined (TC_WINDOWS_BOOT) || defined (TC_WINDOWS_BOOT_AES) +# include "Aes.h" +#else +# include "AesSmall.h" +#endif + +#include "Aes_hw_cpu.h" +#include "Serpent.h" +#include "Twofish.h" + +#include "Rmd160.h" +#ifndef TC_WINDOWS_BOOT +# include "Sha2.h" +# include "Whirlpool.h" +#endif + +#include "GfMul.h" +#include "Password.h" + +#ifndef TC_WINDOWS_BOOT + +#include "config.h" + +typedef struct keyInfo_t +{ + int noIterations; /* Number of times to iterate (PKCS-5) */ + int keyLength; /* Length of the key */ + uint64 dummy; /* Dummy field to ensure 16-byte alignment of this structure */ + __int8 salt[PKCS5_SALT_SIZE]; /* PKCS-5 salt */ + __int8 master_keydata[MASTER_KEYDATA_SIZE]; /* Concatenated master primary and secondary key(s) (XTS mode). For LRW (deprecated/legacy), it contains the tweak key before the master key(s). For CBC (deprecated/legacy), it contains the IV seed before the master key(s). */ + CRYPTOPP_ALIGN_DATA(16) __int8 userKey[MAX_PASSWORD]; /* Password (to which keyfiles may have been applied). WITHOUT +1 for the null terminator. */ +} KEY_INFO, *PKEY_INFO; + +#endif + +typedef struct CRYPTO_INFO_t +{ + int ea; /* Encryption algorithm ID */ + int mode; /* Mode of operation (e.g., XTS) */ + int pkcs5; /* PRF algorithm */ + + unsigned __int8 ks[MAX_EXPANDED_KEY]; /* Primary key schedule (if it is a cascade, it conatins multiple concatenated keys) */ + unsigned __int8 ks2[MAX_EXPANDED_KEY]; /* Secondary key schedule (if cascade, multiple concatenated) for XTS mode. */ + + BOOL hiddenVolume; // Indicates whether the volume is mounted/mountable as hidden volume + +#ifndef TC_WINDOWS_BOOT + uint16 HeaderVersion; + + GfCtx gf_ctx; + + unsigned __int8 master_keydata[MASTER_KEYDATA_SIZE]; /* This holds the volume header area containing concatenated master key(s) and secondary key(s) (XTS mode). For LRW (deprecated/legacy), it contains the tweak key before the master key(s). For CBC (deprecated/legacy), it contains the IV seed before the master key(s). */ + unsigned __int8 k2[MASTER_KEYDATA_SIZE]; /* For XTS, this contains the secondary key (if cascade, multiple concatenated). For LRW (deprecated/legacy), it contains the tweak key. For CBC (deprecated/legacy), it contains the IV seed. */ + unsigned __int8 salt[PKCS5_SALT_SIZE]; + int noIterations; + BOOL bTrueCryptMode; + int volumePim; + + uint64 volume_creation_time; // Legacy + uint64 header_creation_time; // Legacy + + BOOL bProtectHiddenVolume; // Indicates whether the volume contains a hidden volume to be protected against overwriting + BOOL bHiddenVolProtectionAction; // TRUE if a write operation has been denied by the driver in order to prevent the hidden volume from being overwritten (set to FALSE upon volume mount). + + uint64 volDataAreaOffset; // Absolute position, in bytes, of the first data sector of the volume. + + uint64 hiddenVolumeSize; // Size of the hidden volume excluding the header (in bytes). Set to 0 for standard volumes. + uint64 hiddenVolumeOffset; // Absolute position, in bytes, of the first hidden volume data sector within the host volume (provided that there is a hidden volume within). This must be set for all hidden volumes; in case of a normal volume, this variable is only used when protecting a hidden volume within it. + uint64 hiddenVolumeProtectedSize; + + BOOL bPartitionInInactiveSysEncScope; // If TRUE, the volume is a partition located on an encrypted system drive and mounted without pre-boot authentication. + + UINT64_STRUCT FirstDataUnitNo; // First data unit number of the volume. This is 0 for file-hosted and non-system partition-hosted volumes. For partitions within key scope of system encryption this reflects real physical offset within the device (this is used e.g. when such a partition is mounted as a regular volume without pre-boot authentication). + + uint16 RequiredProgramVersion; + BOOL LegacyVolume; + + uint32 SectorSize; + +#endif // !TC_WINDOWS_BOOT + + UINT64_STRUCT VolumeSize; + + UINT64_STRUCT EncryptedAreaStart; + UINT64_STRUCT EncryptedAreaLength; + + uint32 HeaderFlags; + +} CRYPTO_INFO, *PCRYPTO_INFO; + +#ifdef _WIN32 + +#pragma pack (push) +#pragma pack(1) + +typedef struct BOOT_CRYPTO_HEADER_t +{ + __int16 ea; /* Encryption algorithm ID */ + __int16 mode; /* Mode of operation (e.g., XTS) */ + __int16 pkcs5; /* PRF algorithm */ + +} BOOT_CRYPTO_HEADER, *PBOOT_CRYPTO_HEADER; + +#pragma pack (pop) + +#endif + +PCRYPTO_INFO crypto_open (void); +#ifndef TC_WINDOWS_BOOT +void crypto_loadkey (PKEY_INFO keyInfo, char *lpszUserKey, int nUserKeyLen); +#endif +void crypto_close (PCRYPTO_INFO cryptoInfo); + +int CipherGetBlockSize (int cipher); +int CipherGetKeySize (int cipher); +int CipherGetKeyScheduleSize (int cipher); +BOOL CipherSupportsIntraDataUnitParallelization (int cipher); + +#ifndef TC_WINDOWS_BOOT +const wchar_t * CipherGetName (int cipher); +#endif + +int CipherInit (int cipher, unsigned char *key, unsigned char *ks); +#ifndef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE +int EAInit (int ea, unsigned char *key, unsigned char *ks); +#else +int EAInit (unsigned char *key, unsigned char *ks); +#endif +BOOL EAInitMode (PCRYPTO_INFO ci); +void EncipherBlock(int cipher, void *data, void *ks); +void DecipherBlock(int cipher, void *data, void *ks); +#ifndef TC_WINDOWS_BOOT +void EncipherBlocks (int cipher, void *dataPtr, void *ks, size_t blockCount); +void DecipherBlocks (int cipher, void *dataPtr, void *ks, size_t blockCount); +#endif + +int EAGetFirst (); +int EAGetCount (void); +int EAGetNext (int previousEA); +#ifndef TC_WINDOWS_BOOT +wchar_t * EAGetName (wchar_t *buf, int ea, int guiDisplay); +int EAGetByName (wchar_t *name); +#endif +int EAGetKeySize (int ea); +int EAGetFirstMode (int ea); +int EAGetNextMode (int ea, int previousModeId); +#ifndef TC_WINDOWS_BOOT +wchar_t * EAGetModeName (int ea, int mode, BOOL capitalLetters); +#endif +int EAGetKeyScheduleSize (int ea); +int EAGetLargestKey (); +int EAGetLargestKeyForMode (int mode); + +int EAGetCipherCount (int ea); +int EAGetFirstCipher (int ea); +int EAGetLastCipher (int ea); +int EAGetNextCipher (int ea, int previousCipherId); +int EAGetPreviousCipher (int ea, int previousCipherId); +int EAIsFormatEnabled (int ea); +BOOL EAIsModeSupported (int ea, int testedMode); + + +#ifndef TC_WINDOWS_BOOT +const wchar_t *HashGetName (int hash_algo_id); + +Hash *HashGet (int id); +void HashGetName2 (wchar_t *buf, int hashId); +BOOL HashIsDeprecated (int hashId); +BOOL HashForSystemEncryption (int hashId); +int GetMaxPkcs5OutSize (void); +#endif + + +void EncryptDataUnits (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, uint32 nbrUnits, PCRYPTO_INFO ci); +void EncryptDataUnitsCurrentThread (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, TC_LARGEST_COMPILER_UINT nbrUnits, PCRYPTO_INFO ci); +void DecryptDataUnits (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, uint32 nbrUnits, PCRYPTO_INFO ci); +void DecryptDataUnitsCurrentThread (unsigned __int8 *buf, const UINT64_STRUCT *structUnitNo, TC_LARGEST_COMPILER_UINT nbrUnits, PCRYPTO_INFO ci); +void EncryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo); +void DecryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo); + +BOOL IsAesHwCpuSupported (); +void EnableHwEncryption (BOOL enable); +BOOL IsHwEncryptionEnabled (); + +#ifdef __cplusplus +} +#endif + +#endif /* CRYPTO_H */ diff --git a/src/Common/Dictionary.c b/src/Common/Dictionary.c index 41f447c2..34741951 100644 --- a/src/Common/Dictionary.c +++ b/src/Common/Dictionary.c @@ -1,88 +1,88 @@ -/* - 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 "../Common/Dictionary.h" -#include -#include -#include - -using namespace std; - -static map StringKeyMap; -static map IntKeyMap; - -static void *DataPool = NULL; -static size_t DataPoolSize = 0; - - -void AddDictionaryEntry (char *key, int intKey, void *value) -{ - try - { - if (key) - StringKeyMap[key] = value; - - if (intKey != 0) - IntKeyMap[intKey] = value; - } - catch (exception&) {} -} - - -void *GetDictionaryValue (const char *key) -{ - map ::const_iterator i = StringKeyMap.find (key); - - if (i == StringKeyMap.end()) - return NULL; - - return i->second; -} - - -void *GetDictionaryValueByInt (int intKey) -{ - map ::const_iterator i = IntKeyMap.find (intKey); - - if (i == IntKeyMap.end()) - return NULL; - - return i->second; -} - - -void *AddPoolData (void *data, size_t dataSize) -{ - if (DataPoolSize + dataSize > DATA_POOL_CAPACITY) return NULL; - - if (DataPool == NULL) - { - DataPool = malloc (DATA_POOL_CAPACITY); - if (DataPool == NULL) return NULL; - } - - memcpy ((BYTE *)DataPool + DataPoolSize, data, dataSize); - - // Ensure 32-bit alignment for next entries - dataSize = (dataSize + 3) & (~(size_t)3); - - DataPoolSize += dataSize; - return (BYTE *)DataPool + DataPoolSize - dataSize; -} - - -void ClearDictionaryPool () -{ - DataPoolSize = 0; - StringKeyMap.clear(); - IntKeyMap.clear(); +/* + 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 "../Common/Dictionary.h" +#include +#include +#include + +using namespace std; + +static map StringKeyMap; +static map IntKeyMap; + +static void *DataPool = NULL; +static size_t DataPoolSize = 0; + + +void AddDictionaryEntry (char *key, int intKey, void *value) +{ + try + { + if (key) + StringKeyMap[key] = value; + + if (intKey != 0) + IntKeyMap[intKey] = value; + } + catch (exception&) {} +} + + +void *GetDictionaryValue (const char *key) +{ + map ::const_iterator i = StringKeyMap.find (key); + + if (i == StringKeyMap.end()) + return NULL; + + return i->second; +} + + +void *GetDictionaryValueByInt (int intKey) +{ + map ::const_iterator i = IntKeyMap.find (intKey); + + if (i == IntKeyMap.end()) + return NULL; + + return i->second; +} + + +void *AddPoolData (void *data, size_t dataSize) +{ + if (DataPoolSize + dataSize > DATA_POOL_CAPACITY) return NULL; + + if (DataPool == NULL) + { + DataPool = malloc (DATA_POOL_CAPACITY); + if (DataPool == NULL) return NULL; + } + + memcpy ((BYTE *)DataPool + DataPoolSize, data, dataSize); + + // Ensure 32-bit alignment for next entries + dataSize = (dataSize + 3) & (~(size_t)3); + + DataPoolSize += dataSize; + return (BYTE *)DataPool + DataPoolSize - dataSize; +} + + +void ClearDictionaryPool () +{ + DataPoolSize = 0; + StringKeyMap.clear(); + IntKeyMap.clear(); } \ No newline at end of file diff --git a/src/Common/Dictionary.h b/src/Common/Dictionary.h index 5a4d086d..0fa9c7ee 100644 --- a/src/Common/Dictionary.h +++ b/src/Common/Dictionary.h @@ -1,34 +1,34 @@ -/* - 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. -*/ - -#ifndef DICTIONARY_H -#define DICTIONARY_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define DATA_POOL_CAPACITY 1000000 - -void AddDictionaryEntry (char *key, int intKey, void *value); -void *GetDictionaryValue (const char *key); -void *GetDictionaryValueByInt (int intKey); -void *AddPoolData (void *data, size_t dataSize); -void ClearDictionaryPool (); - -#ifdef __cplusplus -} -#endif - -#endif +/* + 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. +*/ + +#ifndef DICTIONARY_H +#define DICTIONARY_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define DATA_POOL_CAPACITY 1000000 + +void AddDictionaryEntry (char *key, int intKey, void *value); +void *GetDictionaryValue (const char *key); +void *GetDictionaryValueByInt (int intKey); +void *AddPoolData (void *data, size_t dataSize); +void ClearDictionaryPool (); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/Common/Dlgcode.c b/src/Common/Dlgcode.c index 97dd5247..ef6a942f 100644 --- a/src/Common/Dlgcode.c +++ b/src/Common/Dlgcode.c @@ -1,11890 +1,11890 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Resource.h" - -#include "Platform/Finally.h" -#include "Platform/ForEach.h" -#include "Apidrvr.h" -#include "BootEncryption.h" -#include "Combo.h" -#include "Crc.h" -#include "Crypto.h" -#include "Dictionary.h" -#include "Dlgcode.h" -#include "EncryptionThreadPool.h" -#include "Endian.h" -#include "Format/Inplace.h" -#include "Language.h" -#include "Keyfiles.h" -#include "Pkcs5.h" -#include "Random.h" -#include "Registry.h" -#include "SecurityToken.h" -#include "Tests.h" -#include "Volumes.h" -#include "Wipe.h" -#include "Xml.h" -#include "Xts.h" -#include "Boot/Windows/BootCommon.h" -#include "Progress.h" - -#ifdef TCMOUNT -#include "Mount/Mount.h" -#include "Mount/resource.h" -#endif - -#ifdef VOLFORMAT -#include "Format/Tcformat.h" -#endif - -#ifdef SETUP -#include "Setup/Setup.h" -#endif - -#include - -using namespace VeraCrypt; - -LONG DriverVersion; - -char *LastDialogId; -wchar_t szHelpFile[TC_MAX_PATH]; -wchar_t szHelpFile2[TC_MAX_PATH]; -wchar_t SecurityTokenLibraryPath[TC_MAX_PATH]; - -HFONT hFixedDigitFont = NULL; -HFONT hBoldFont = NULL; -HFONT hTitleFont = NULL; -HFONT hFixedFont = NULL; - -HFONT hUserFont = NULL; -HFONT hUserUnderlineFont = NULL; -HFONT hUserBoldFont = NULL; -HFONT hUserUnderlineBoldFont = NULL; - -HFONT WindowTitleBarFont; - -WCHAR EditPasswordChar = 0; - -int ScreenDPI = USER_DEFAULT_SCREEN_DPI; -double DPIScaleFactorX = 1; -double DPIScaleFactorY = 1; -double DlgAspectRatio = 1; - -HWND MainDlg = NULL; -wchar_t *lpszTitle = NULL; - -BOOL Silent = FALSE; -BOOL bPreserveTimestamp = TRUE; -BOOL bShowDisconnectedNetworkDrives = FALSE; -BOOL bHideWaitingDialog = FALSE; -BOOL bCmdHideWaitingDialog = FALSE; -BOOL bCmdHideWaitingDialogValid = FALSE; -BOOL bStartOnLogon = FALSE; -BOOL bMountDevicesOnLogon = FALSE; -BOOL bMountFavoritesOnLogon = FALSE; - -BOOL bHistory = FALSE; - -// Status of detection of hidden sectors (whole-system-drive encryption). -// 0 - Unknown/undetermined/completed, 1: Detection is or was in progress (but did not complete e.g. due to system crash). -int HiddenSectorDetectionStatus = 0; - -OSVersionEnum nCurrentOS = WIN_UNKNOWN; -int CurrentOSMajor = 0; -int CurrentOSMinor = 0; -int CurrentOSServicePack = 0; -BOOL RemoteSession = FALSE; -BOOL UacElevated = FALSE; - -BOOL bPortableModeConfirmed = FALSE; // TRUE if it is certain that the instance is running in portable mode - -BOOL bInPlaceEncNonSysPending = FALSE; // TRUE if the non-system in-place encryption config file indicates that one or more partitions are scheduled to be encrypted. This flag is set only when config files are loaded during app startup. - -/* Globals used by Mount and Format (separately per instance) */ -BOOL PimEnable = FALSE; -BOOL KeyFilesEnable = FALSE; -KeyFile *FirstKeyFile = NULL; -KeyFilesDlgParam defaultKeyFilesParam; - -BOOL IgnoreWmDeviceChange = FALSE; -BOOL DeviceChangeBroadcastDisabled = FALSE; -BOOL LastMountedVolumeDirty; -BOOL MountVolumesAsSystemFavorite = FALSE; -BOOL FavoriteMountOnArrivalInProgress = FALSE; -BOOL MultipleMountOperationInProgress = FALSE; - -BOOL WaitDialogDisplaying = FALSE; - -/* Handle to the device driver */ -HANDLE hDriver = INVALID_HANDLE_VALUE; - -/* This mutex is used to prevent multiple instances of the wizard or main app from dealing with system encryption */ -volatile HANDLE hSysEncMutex = NULL; - -/* This mutex is used for non-system in-place encryption but only for informative (non-blocking) purposes, -such as whether an app should prompt the user whether to resume scheduled process. */ -volatile HANDLE hNonSysInplaceEncMutex = NULL; - -/* This mutex is used to prevent multiple instances of the wizard or main app from trying to install or -register the driver or from trying to launch it in portable mode at the same time. */ -volatile HANDLE hDriverSetupMutex = NULL; - -/* This mutex is used to prevent users from running the main TrueCrypt app or the wizard while an instance -of the TrueCrypt installer is running (which is also useful for enforcing restart before the apps can be used). */ -volatile HANDLE hAppSetupMutex = NULL; - -/* Critical section used to protect access to global variables used in WNetGetConnection calls */ -CRITICAL_SECTION csWNetCalls; - -HINSTANCE hInst = NULL; -HCURSOR hCursor = NULL; - -ATOM hDlgClass, hSplashClass; - -/* This value may changed only by calling ChangeSystemEncryptionStatus(). Only the wizard can change it -(others may still read it though). */ -int SystemEncryptionStatus = SYSENC_STATUS_NONE; - -/* Only the wizard can change this value (others may only read it). */ -WipeAlgorithmId nWipeMode = TC_WIPE_NONE; - -BOOL bSysPartitionSelected = FALSE; /* TRUE if the user selected the system partition via the Select Device dialog */ -BOOL bSysDriveSelected = FALSE; /* TRUE if the user selected the system drive via the Select Device dialog */ - -/* To populate these arrays, call GetSysDevicePaths(). If they contain valid paths, bCachedSysDevicePathsValid is TRUE. */ -wchar_t SysPartitionDevicePath [TC_MAX_PATH]; -wchar_t SysDriveDevicePath [TC_MAX_PATH]; -wstring ExtraBootPartitionDevicePath; -char bCachedSysDevicePathsValid = FALSE; - -BOOL bHyperLinkBeingTracked = FALSE; - -int WrongPwdRetryCounter = 0; - -static FILE *ConfigFileHandle; -char *ConfigBuffer; - -BOOL SystemFileSelectorCallPending = FALSE; -DWORD SystemFileSelectorCallerThreadId; - -#define RANDPOOL_DISPLAY_REFRESH_INTERVAL 30 -#define RANDPOOL_DISPLAY_ROWS 16 -#define RANDPOOL_DISPLAY_COLUMNS 20 - -HMODULE hRichEditDll = NULL; -HMODULE hComctl32Dll = NULL; -HMODULE hSetupDll = NULL; -HMODULE hShlwapiDll = NULL; -HMODULE hProfApiDll = NULL; -HMODULE hUsp10Dll = NULL; -HMODULE hCryptSpDll = NULL; -HMODULE hUXThemeDll = NULL; -HMODULE hUserenvDll = NULL; -HMODULE hRsaenhDll = NULL; -HMODULE himm32dll = NULL; -HMODULE hMSCTFdll = NULL; -HMODULE hfltlibdll = NULL; -HMODULE hframedyndll = NULL; -HMODULE hpsapidll = NULL; -HMODULE hsecur32dll = NULL; -HMODULE hnetapi32dll = NULL; -HMODULE hauthzdll = NULL; -HMODULE hxmllitedll = NULL; -HMODULE hmprdll = NULL; -HMODULE hsppdll = NULL; -HMODULE vssapidll = NULL; -HMODULE hvsstracedll = NULL; -HMODULE hcfgmgr32dll = NULL; -HMODULE hdevobjdll = NULL; -HMODULE hpowrprofdll = NULL; -HMODULE hsspiclidll = NULL; -HMODULE hcryptbasedll = NULL; -HMODULE hdwmapidll = NULL; -HMODULE hmsasn1dll = NULL; -HMODULE hcrypt32dll = NULL; -HMODULE hbcryptdll = NULL; -HMODULE hbcryptprimitivesdll = NULL; -HMODULE hMsls31 = NULL; -HMODULE hntmartadll = NULL; -HMODULE hwinscarddll = NULL; - -#define FREE_DLL(h) if (h) { FreeLibrary (h); h = NULL;} - -typedef void (WINAPI *InitCommonControlsPtr)(void); -typedef HIMAGELIST (WINAPI *ImageList_CreatePtr)(int cx, int cy, UINT flags, int cInitial, int cGrow); -typedef int (WINAPI *ImageList_AddPtr)(HIMAGELIST himl, HBITMAP hbmImage, HBITMAP hbmMask); - -typedef VOID (WINAPI *SetupCloseInfFilePtr)(HINF InfHandle); -typedef HKEY (WINAPI *SetupDiOpenClassRegKeyPtr)(CONST GUID *ClassGuid,REGSAM samDesired); -typedef BOOL (WINAPI *SetupInstallFromInfSectionWPtr)(HWND,HINF,PCWSTR,UINT,HKEY,PCWSTR,UINT,PSP_FILE_CALLBACK_W,PVOID,HDEVINFO,PSP_DEVINFO_DATA); -typedef HINF (WINAPI *SetupOpenInfFileWPtr)(PCWSTR FileName,PCWSTR InfClass,DWORD InfStyle,PUINT ErrorLine); - -typedef LSTATUS (STDAPICALLTYPE *SHDeleteKeyWPtr)(HKEY hkey, LPCWSTR pszSubKey); - -typedef HRESULT (STDAPICALLTYPE *SHStrDupWPtr)(LPCWSTR psz, LPWSTR *ppwsz); - -// ChangeWindowMessageFilter -typedef BOOL (WINAPI *ChangeWindowMessageFilterPtr) (UINT, DWORD); - -ImageList_CreatePtr ImageList_CreateFn = NULL; -ImageList_AddPtr ImageList_AddFn = NULL; - -SetupCloseInfFilePtr SetupCloseInfFileFn = NULL; -SetupDiOpenClassRegKeyPtr SetupDiOpenClassRegKeyFn = NULL; -SetupInstallFromInfSectionWPtr SetupInstallFromInfSectionWFn = NULL; -SetupOpenInfFileWPtr SetupOpenInfFileWFn = NULL; -SHDeleteKeyWPtr SHDeleteKeyWFn = NULL; -SHStrDupWPtr SHStrDupWFn = NULL; -ChangeWindowMessageFilterPtr ChangeWindowMessageFilterFn = NULL; - -/* Windows dialog class */ -#define WINDOWS_DIALOG_CLASS L"#32770" - -/* Custom class names */ -#define TC_DLG_CLASS L"VeraCryptCustomDlg" -#define TC_SPLASH_CLASS L"VeraCryptSplashDlg" - -/* constant used by ChangeWindowMessageFilter calls */ -#ifndef MSGFLT_ADD -#define MSGFLT_ADD 1 -#endif - -/* undocumented message sent during drag-n-drop */ -#ifndef WM_COPYGLOBALDATA -#define WM_COPYGLOBALDATA 0x0049 -#endif - -/* Benchmarks */ - -#ifndef SETUP - -#define BENCHMARK_MAX_ITEMS 100 -#define BENCHMARK_DEFAULT_BUF_SIZE BYTES_PER_MB -#define HASH_FNC_BENCHMARKS FALSE // For development purposes only. Must be FALSE when building a public release. -#define PKCS5_BENCHMARKS FALSE // For development purposes only. Must be FALSE when building a public release. -#if PKCS5_BENCHMARKS && HASH_FNC_BENCHMARKS -#error PKCS5_BENCHMARKS and HASH_FNC_BENCHMARKS are both TRUE (at least one of them should be FALSE). -#endif - -enum -{ - BENCHMARK_SORT_BY_NAME = 0, - BENCHMARK_SORT_BY_SPEED -}; - -typedef struct -{ - int id; - wchar_t name[100]; - unsigned __int64 encSpeed; - unsigned __int64 decSpeed; - unsigned __int64 meanBytesPerSec; -} BENCHMARK_REC; - -BENCHMARK_REC benchmarkTable [BENCHMARK_MAX_ITEMS]; -int benchmarkTotalItems = 0; -int benchmarkBufferSize = BENCHMARK_DEFAULT_BUF_SIZE; -int benchmarkLastBufferSize = BENCHMARK_DEFAULT_BUF_SIZE; -int benchmarkSortMethod = BENCHMARK_SORT_BY_SPEED; -LARGE_INTEGER benchmarkPerformanceFrequency; - -#endif // #ifndef SETUP - - -typedef struct -{ - void *strings; - BOOL bold; - -} MULTI_CHOICE_DLGPROC_PARAMS; - - -void cleanup () -{ - /* Cleanup the GDI fonts */ - if (hFixedFont != NULL) - DeleteObject (hFixedFont); - if (hFixedDigitFont != NULL) - DeleteObject (hFixedDigitFont); - if (hBoldFont != NULL) - DeleteObject (hBoldFont); - if (hTitleFont != NULL) - DeleteObject (hTitleFont); - if (hUserFont != NULL) - DeleteObject (hUserFont); - if (hUserUnderlineFont != NULL) - DeleteObject (hUserUnderlineFont); - if (hUserBoldFont != NULL) - DeleteObject (hUserBoldFont); - if (hUserUnderlineBoldFont != NULL) - DeleteObject (hUserUnderlineBoldFont); - - /* Cleanup our dialog class */ - if (hDlgClass) - UnregisterClassW (TC_DLG_CLASS, hInst); - if (hSplashClass) - UnregisterClassW (TC_SPLASH_CLASS, hInst); - - /* Close the device driver handle */ - if (hDriver != INVALID_HANDLE_VALUE) - { - // Unload driver mode if possible (non-install mode) - if (IsNonInstallMode ()) - { - // If a dismount was forced in the lifetime of the driver, Windows may later prevent it to be loaded again from - // the same path. Therefore, the driver will not be unloaded even though it was loaded in non-install mode. - int driverUnloadDisabled; - DWORD dwResult; - - if (!DeviceIoControl (hDriver, TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED, NULL, 0, &driverUnloadDisabled, sizeof (driverUnloadDisabled), &dwResult, NULL)) - driverUnloadDisabled = 0; - - if (!driverUnloadDisabled) - DriverUnload (); - else - { - CloseHandle (hDriver); - hDriver = INVALID_HANDLE_VALUE; - } - } - else - { - CloseHandle (hDriver); - hDriver = INVALID_HANDLE_VALUE; - } - } - - if (ConfigBuffer != NULL) - { - free (ConfigBuffer); - ConfigBuffer = NULL; - } - - CoUninitialize (); - - CloseSysEncMutex (); - -#ifndef SETUP - try - { - if (SecurityToken::IsInitialized()) - SecurityToken::CloseLibrary(); - } - catch (...) { } - - EncryptionThreadPoolStop(); -#endif - - DeleteCriticalSection (&csWNetCalls); -} - - -void LowerCaseCopy (wchar_t *lpszDest, const wchar_t *lpszSource) -{ - size_t i = wcslen (lpszSource) + 1; - - lpszDest[i - 1] = 0; - while (--i > 0) - { - lpszDest[i - 1] = (wchar_t) towlower (lpszSource[i - 1]); - } - -} - -void UpperCaseCopy (wchar_t *lpszDest, size_t cbDest, const wchar_t *lpszSource) -{ - if (lpszDest && cbDest) - { - size_t i = wcslen (lpszSource); - if (i >= cbDest) - i = cbDest - 1; - - lpszDest[i] = 0; - i++; - while (--i > 0) - { - lpszDest[i - 1] = (wchar_t) towupper (lpszSource[i - 1]); - } - } -} - - -std::wstring ToUpperCase (const std::wstring &str) -{ - wstring u; - foreach (wchar_t c, str) - { - u += (wchar_t) towupper (c); - } - - return u; -} - -size_t TrimWhiteSpace(wchar_t *str) -{ - wchar_t *end, *ptr = str; - size_t out_size; - - if(!str || *str == 0) - return 0; - - // Trim leading space - while(iswspace(*ptr)) ptr++; - - if(*ptr == 0) // All spaces? - { - *str = 0; - return 0; - } - - // Trim trailing space - end = str + wcslen(str) - 1; - while(end > ptr && iswspace(*end)) end--; - end++; - - // Set output size to trimmed string length - out_size = (end - ptr); - - // Copy trimmed string and add null terminator - wmemmove(str, ptr, out_size); - str[out_size] = 0; - - return out_size; -} - -// check the validity of a file name -BOOL IsValidFileName(const wchar_t* str) -{ - static wchar_t invalidChars[9] = {L'<', L'>', L':', L'"', L'/', L'\\', L'|', L'?', L'*'}; - wchar_t c; - int i; - BOOL bNotDotOnly = FALSE; - while ((c = *str)) - { - if (c != L'.') - bNotDotOnly = TRUE; - for (i= 0; i < ARRAYSIZE(invalidChars); i++) - if (c == invalidChars[i]) - return FALSE; - str++; - } - - return bNotDotOnly; -} - -BOOL IsVolumeDeviceHosted (const wchar_t *lpszDiskFile) -{ - return wcsstr (lpszDiskFile, L"\\Device\\") == lpszDiskFile - || wcsstr (lpszDiskFile, L"\\DEVICE\\") == lpszDiskFile; -} - - -void CreateFullVolumePath (wchar_t *lpszDiskFile, size_t cbDiskFile, const wchar_t *lpszFileName, BOOL * bDevice) -{ - UpperCaseCopy (lpszDiskFile, cbDiskFile, lpszFileName); - - *bDevice = FALSE; - - if (wmemcmp (lpszDiskFile, L"\\DEVICE", 7) == 0) - { - *bDevice = TRUE; - } - - StringCbCopyW (lpszDiskFile, cbDiskFile, lpszFileName); - -#if _DEBUG - OutputDebugString (L"CreateFullVolumePath: "); - OutputDebugString (lpszDiskFile); - OutputDebugString (L"\n"); -#endif - -} - -int FakeDosNameForDevice (const wchar_t *lpszDiskFile , wchar_t *lpszDosDevice , size_t cbDosDevice, wchar_t *lpszCFDevice , size_t cbCFDevice, BOOL bNameOnly) -{ - BOOL bDosLinkCreated = TRUE; - StringCbPrintfW (lpszDosDevice, cbDosDevice,L"veracrypt%lu", GetCurrentProcessId ()); - - if (bNameOnly == FALSE) - bDosLinkCreated = DefineDosDevice (DDD_RAW_TARGET_PATH, lpszDosDevice, lpszDiskFile); - - if (bDosLinkCreated == FALSE) - return ERR_OS_ERROR; - else - StringCbPrintfW (lpszCFDevice, cbCFDevice,L"\\\\.\\%s", lpszDosDevice); - - return 0; -} - -int RemoveFakeDosName (wchar_t *lpszDiskFile, wchar_t *lpszDosDevice) -{ - BOOL bDosLinkRemoved = DefineDosDevice (DDD_RAW_TARGET_PATH | DDD_EXACT_MATCH_ON_REMOVE | - DDD_REMOVE_DEFINITION, lpszDosDevice, lpszDiskFile); - if (bDosLinkRemoved == FALSE) - { - return ERR_OS_ERROR; - } - - return 0; -} - - -void AbortProcessDirect (wchar_t *abortMsg) -{ - // Note that this function also causes localcleanup() to be called (see atexit()) - MessageBeep (MB_ICONEXCLAMATION); - MessageBoxW (NULL, abortMsg, lpszTitle, ICON_HAND); - FREE_DLL (hRichEditDll); - FREE_DLL (hComctl32Dll); - FREE_DLL (hSetupDll); - FREE_DLL (hShlwapiDll); - FREE_DLL (hProfApiDll); - FREE_DLL (hUsp10Dll); - FREE_DLL (hCryptSpDll); - FREE_DLL (hUXThemeDll); - FREE_DLL (hUserenvDll); - FREE_DLL (hRsaenhDll); - FREE_DLL (himm32dll); - FREE_DLL (hMSCTFdll); - FREE_DLL (hfltlibdll); - FREE_DLL (hframedyndll); - FREE_DLL (hpsapidll); - FREE_DLL (hsecur32dll); - FREE_DLL (hnetapi32dll); - FREE_DLL (hauthzdll); - FREE_DLL (hxmllitedll); - FREE_DLL (hmprdll); - FREE_DLL (hsppdll); - FREE_DLL (vssapidll); - FREE_DLL (hvsstracedll); - FREE_DLL (hCryptSpDll); - FREE_DLL (hcfgmgr32dll); - FREE_DLL (hdevobjdll); - FREE_DLL (hpowrprofdll); - FREE_DLL (hsspiclidll); - FREE_DLL (hcryptbasedll); - FREE_DLL (hdwmapidll); - FREE_DLL (hmsasn1dll); - FREE_DLL (hcrypt32dll); - FREE_DLL (hbcryptdll); - FREE_DLL (hbcryptprimitivesdll); - FREE_DLL (hMsls31); - FREE_DLL (hntmartadll); - FREE_DLL (hwinscarddll); - - exit (1); -} - -void AbortProcess (char *stringId) -{ - // Note that this function also causes localcleanup() to be called (see atexit()) - AbortProcessDirect (GetString (stringId)); -} - -void AbortProcessSilent (void) -{ - FREE_DLL (hRichEditDll); - FREE_DLL (hComctl32Dll); - FREE_DLL (hSetupDll); - FREE_DLL (hShlwapiDll); - FREE_DLL (hProfApiDll); - FREE_DLL (hUsp10Dll); - FREE_DLL (hCryptSpDll); - FREE_DLL (hUXThemeDll); - FREE_DLL (hUserenvDll); - FREE_DLL (hRsaenhDll); - FREE_DLL (himm32dll); - FREE_DLL (hMSCTFdll); - FREE_DLL (hfltlibdll); - FREE_DLL (hframedyndll); - FREE_DLL (hpsapidll); - FREE_DLL (hsecur32dll); - FREE_DLL (hnetapi32dll); - FREE_DLL (hauthzdll); - FREE_DLL (hxmllitedll); - FREE_DLL (hmprdll); - FREE_DLL (hsppdll); - FREE_DLL (vssapidll); - FREE_DLL (hvsstracedll); - FREE_DLL (hCryptSpDll); - FREE_DLL (hcfgmgr32dll); - FREE_DLL (hdevobjdll); - FREE_DLL (hpowrprofdll); - FREE_DLL (hsspiclidll); - FREE_DLL (hcryptbasedll); - FREE_DLL (hdwmapidll); - FREE_DLL (hmsasn1dll); - FREE_DLL (hcrypt32dll); - FREE_DLL (hbcryptdll); - FREE_DLL (hbcryptprimitivesdll); - FREE_DLL (hMsls31); - FREE_DLL (hntmartadll); - FREE_DLL (hwinscarddll); - - // Note that this function also causes localcleanup() to be called (see atexit()) - exit (1); -} - - -#pragma warning(push) -#pragma warning(disable:4702) - -void *err_malloc (size_t size) -{ - void *z = (void *) TCalloc (size); - if (z) - return z; - AbortProcess ("OUTOFMEMORY"); - return 0; -} - -#pragma warning(pop) - - -char *err_strdup (char *lpszText) -{ - size_t j = (strlen (lpszText) + 1) * sizeof (char); - char *z = (char *) err_malloc (j); - memmove (z, lpszText, j); - return z; -} - - -BOOL IsDiskReadError (DWORD error) -{ - return (error == ERROR_CRC - || error == ERROR_IO_DEVICE - || error == ERROR_BAD_CLUSTERS - || error == ERROR_SECTOR_NOT_FOUND - || error == ERROR_READ_FAULT - || error == ERROR_INVALID_FUNCTION // I/O error may be reported as ERROR_INVALID_FUNCTION by buggy chipset drivers - || error == ERROR_SEM_TIMEOUT); // I/O operation timeout may be reported as ERROR_SEM_TIMEOUT -} - - -BOOL IsDiskWriteError (DWORD error) -{ - return (error == ERROR_IO_DEVICE - || error == ERROR_BAD_CLUSTERS - || error == ERROR_SECTOR_NOT_FOUND - || error == ERROR_WRITE_FAULT - || error == ERROR_INVALID_FUNCTION // I/O error may be reported as ERROR_INVALID_FUNCTION by buggy chipset drivers - || error == ERROR_SEM_TIMEOUT); // I/O operation timeout may be reported as ERROR_SEM_TIMEOUT -} - - -BOOL IsDiskError (DWORD error) -{ - return IsDiskReadError (error) || IsDiskWriteError (error); -} - - -DWORD handleWin32Error (HWND hwndDlg, const char* srcPos) -{ - PWSTR lpMsgBuf; - DWORD dwError = GetLastError (); - wchar_t szErrorValue[32]; - wchar_t* pszDesc; - - if (Silent || dwError == 0 || dwError == ERROR_INVALID_WINDOW_HANDLE) - return dwError; - - // Access denied - if (dwError == ERROR_ACCESS_DENIED && !IsAdmin ()) - { - ErrorDirect ( AppendSrcPos (GetString ("ERR_ACCESS_DENIED"), srcPos).c_str (), hwndDlg); - SetLastError (dwError); // Preserve the original error code - return dwError; - } - - FormatMessageW ( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - dwError, - MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ - (PWSTR) &lpMsgBuf, - 0, - NULL - ); - - if (lpMsgBuf) - pszDesc = (wchar_t*) lpMsgBuf; - else - { - StringCchPrintfW (szErrorValue, ARRAYSIZE (szErrorValue), L"Error 0x%.8X", dwError); - pszDesc = szErrorValue; - } - - MessageBoxW (hwndDlg, AppendSrcPos (pszDesc, srcPos).c_str (), lpszTitle, ICON_HAND); - if (lpMsgBuf) LocalFree (lpMsgBuf); - - // User-friendly hardware error explanation - if (IsDiskError (dwError)) - Error ("ERR_HARDWARE_ERROR", hwndDlg); - - // Device not ready - if (dwError == ERROR_NOT_READY) - HandleDriveNotReadyError(hwndDlg); - - SetLastError (dwError); // Preserve the original error code - - return dwError; -} - -BOOL translateWin32Error (wchar_t *lpszMsgBuf, int nWSizeOfBuf) -{ - DWORD dwError = GetLastError (); - - if (FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, - MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ - lpszMsgBuf, nWSizeOfBuf, NULL)) - { - SetLastError (dwError); // Preserve the original error code - return TRUE; - } - - SetLastError (dwError); // Preserve the original error code - return FALSE; -} - -// If the user has a non-default screen DPI, all absolute font sizes must be -// converted using this function. -int CompensateDPIFont (int val) -{ - if (ScreenDPI == USER_DEFAULT_SCREEN_DPI) - return val; - else - { - double tmpVal = (double) val * DPIScaleFactorY * DlgAspectRatio * 0.999; - - if (tmpVal > 0) - return (int) floor(tmpVal); - else - return (int) ceil(tmpVal); - } -} - - -// If the user has a non-default screen DPI, some screen coordinates and sizes must -// be converted using this function -int CompensateXDPI (int val) -{ - if (ScreenDPI == USER_DEFAULT_SCREEN_DPI) - return val; - else - { - double tmpVal = (double) val * DPIScaleFactorX; - - if (tmpVal > 0) - return (int) floor(tmpVal); - else - return (int) ceil(tmpVal); - } -} - - -// If the user has a non-default screen DPI, some screen coordinates and sizes must -// be converted using this function -int CompensateYDPI (int val) -{ - if (ScreenDPI == USER_DEFAULT_SCREEN_DPI) - return val; - else - { - double tmpVal = (double) val * DPIScaleFactorY; - - if (tmpVal > 0) - return (int) floor(tmpVal); - else - return (int) ceil(tmpVal); - } -} - - -int GetTextGfxWidth (HWND hwndDlgItem, const wchar_t *text, HFONT hFont) -{ - SIZE sizes; - TEXTMETRIC textMetrics; - HDC hdc = GetDC (hwndDlgItem); - - SelectObject(hdc, (HGDIOBJ) hFont); - - GetTextExtentPoint32W (hdc, text, (int) wcslen (text), &sizes); - - GetTextMetrics(hdc, &textMetrics); // Necessary for non-TrueType raster fonts (tmOverhang) - - ReleaseDC (hwndDlgItem, hdc); - - return ((int) sizes.cx - (int) textMetrics.tmOverhang); -} - - -int GetTextGfxHeight (HWND hwndDlgItem, const wchar_t *text, HFONT hFont) -{ - SIZE sizes; - HDC hdc = GetDC (hwndDlgItem); - - SelectObject(hdc, (HGDIOBJ) hFont); - - GetTextExtentPoint32W (hdc, text, (int) wcslen (text), &sizes); - - ReleaseDC (hwndDlgItem, hdc); - - return ((int) sizes.cy); -} - - -std::wstring FitPathInGfxWidth (HWND hwnd, HFONT hFont, LONG width, const std::wstring &path) -{ - wstring newPath; - - RECT rect; - rect.left = 0; - rect.top = 0; - rect.right = width; - rect.bottom = LONG_MAX; - - HDC hdc = GetDC (hwnd); - SelectObject (hdc, (HGDIOBJ) hFont); - - wchar_t pathBuf[TC_MAX_PATH]; - StringCchCopyW (pathBuf, ARRAYSIZE (pathBuf), path.c_str()); - - if (DrawText (hdc, pathBuf, (int) path.size(), &rect, DT_CALCRECT | DT_MODIFYSTRING | DT_PATH_ELLIPSIS | DT_SINGLELINE) != 0) - newPath = pathBuf; - - ReleaseDC (hwnd, hdc); - return newPath; -} - - -static LRESULT CALLBACK HyperlinkProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - WNDPROC wp = (WNDPROC) GetWindowLongPtrW (hwnd, GWLP_USERDATA); - - switch (message) - { - case WM_SETCURSOR: - if (!bHyperLinkBeingTracked) - { - TRACKMOUSEEVENT trackMouseEvent; - - trackMouseEvent.cbSize = sizeof(trackMouseEvent); - trackMouseEvent.dwFlags = TME_LEAVE; - trackMouseEvent.hwndTrack = hwnd; - - bHyperLinkBeingTracked = TrackMouseEvent(&trackMouseEvent); - - HandCursor(); - } - return 0; - - case WM_MOUSELEAVE: - bHyperLinkBeingTracked = FALSE; - NormalCursor(); - return 0; - } - - return CallWindowProcW (wp, hwnd, message, wParam, lParam); -} - - -BOOL ToHyperlink (HWND hwndDlg, UINT ctrlId) -{ - return ToCustHyperlink (hwndDlg, ctrlId, hUserUnderlineFont); -} - - -BOOL ToCustHyperlink (HWND hwndDlg, UINT ctrlId, HFONT hFont) -{ - HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId); - - SendMessageW (hwndCtrl, WM_SETFONT, (WPARAM) hFont, 0); - - SetWindowLongPtrW (hwndCtrl, GWLP_USERDATA, (LONG_PTR) GetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC)); - SetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC, (LONG_PTR) HyperlinkProc); - - // Resize the field according to its actual size in pixels and move it if centered or right-aligned. - // This should be done again if the link text changes. - AccommodateTextField (hwndDlg, ctrlId, TRUE, hFont); - - return TRUE; -} - - -// Resizes a text field according to its actual width and height in pixels (font size is taken into account) and moves -// it accordingly if the field is centered or right-aligned. Should be used on all hyperlinks upon dialog init -// after localization (bFirstUpdate should be TRUE) and later whenever a hyperlink text changes (bFirstUpdate -// must be FALSE). -void AccommodateTextField (HWND hwndDlg, UINT ctrlId, BOOL bFirstUpdate, HFONT hFont) -{ - RECT rec, wrec, trec; - HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId); - int width, origWidth, height, origHeight; - int horizSubOffset, vertSubOffset, vertOffset, alignPosDiff = 0; - wchar_t text [MAX_URL_LENGTH]; - WINDOWINFO windowInfo; - BOOL bBorderlessWindow = !(GetWindowLongPtrW (hwndDlg, GWL_STYLE) & (WS_BORDER | WS_DLGFRAME)); - - // Resize the field according to its length and font size and move if centered or right-aligned - - GetWindowTextW (hwndCtrl, text, sizeof (text) / sizeof (wchar_t)); - - width = GetTextGfxWidth (hwndCtrl, text, hFont); - height = GetTextGfxHeight (hwndCtrl, text, hFont); - - GetClientRect (hwndCtrl, &rec); - origWidth = rec.right; - origHeight = rec.bottom; - - if (width >= 0 - && (!bFirstUpdate || origWidth > width)) // The original width of the field is the maximum allowed size - { - horizSubOffset = origWidth - width; - vertSubOffset = origHeight - height; - - // Window coords - GetWindowRect(hwndDlg, &wrec); - GetClientRect(hwndDlg, &trec); - - // Vertical "title bar" offset - vertOffset = wrec.bottom - wrec.top - trec.bottom - (bBorderlessWindow ? 0 : GetSystemMetrics(SM_CYFIXEDFRAME)); - - // Text field coords - GetWindowRect(hwndCtrl, &rec); - - // Alignment offset - windowInfo.cbSize = sizeof(windowInfo); - GetWindowInfo (hwndCtrl, &windowInfo); - - if (windowInfo.dwStyle & SS_CENTER) - alignPosDiff = horizSubOffset / 2; - else if (windowInfo.dwStyle & SS_RIGHT) - alignPosDiff = horizSubOffset; - - // Resize/move - if (alignPosDiff > 0) - { - // Resize and move the text field - MoveWindow (hwndCtrl, - rec.left - wrec.left - (bBorderlessWindow ? 0 : GetSystemMetrics(SM_CXFIXEDFRAME)) + alignPosDiff, - rec.top - wrec.top - vertOffset, - origWidth - horizSubOffset, - origHeight - vertSubOffset, - TRUE); - } - else - { - // Resize the text field - SetWindowPos (hwndCtrl, 0, 0, 0, - origWidth - horizSubOffset, - origHeight - vertSubOffset, - SWP_NOMOVE | SWP_NOZORDER); - } - - SetWindowPos (hwndCtrl, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - - InvalidateRect (hwndCtrl, NULL, TRUE); - } -} - -// Note that the user can still close the window by right-clicking its taskbar icon and selecting 'Close window', or by pressing Alt-F4, or using the Task Manager. -void DisableCloseButton (HWND hwndDlg) -{ - EnableMenuItem (GetSystemMenu (hwndDlg, FALSE), SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); -} - - -void EnableCloseButton (HWND hwndDlg) -{ - EnableMenuItem (GetSystemMenu (hwndDlg, FALSE), SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); -} - -// Protects an input field from having its content updated by a Paste action (call ToBootPwdField() to use this). -static LRESULT CALLBACK BootPwdFieldProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - WNDPROC wp = (WNDPROC) GetWindowLongPtrW (hwnd, GWLP_USERDATA); - - switch (message) - { - case WM_PASTE: - return 1; - } - - return CallWindowProcW (wp, hwnd, message, wParam, lParam); -} - - -// Protects an input field from having its content updated by a Paste action. Used for pre-boot password -// input fields (only the US keyboard layout is supported in pre-boot environment so we must prevent the -// user from pasting a password typed using a non-US keyboard layout). -void ToBootPwdField (HWND hwndDlg, UINT ctrlId) -{ - HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId); - - SetWindowLongPtrW (hwndCtrl, GWLP_USERDATA, (LONG_PTR) GetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC)); - SetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC, (LONG_PTR) BootPwdFieldProc); -} - - - -// This function currently serves the following purposes: -// - Determines scaling factors for current screen DPI and GUI aspect ratio. -// - Determines how Windows skews the GUI aspect ratio (which happens when the user has a non-default DPI). -// The determined values must be used when performing some GUI operations and calculations. -BOOL CALLBACK AuxiliaryDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - switch (msg) - { - case WM_INITDIALOG: - { - HDC hDC = GetDC (hwndDlg); - - if (hDC) - { - ScreenDPI = GetDeviceCaps (hDC, LOGPIXELSY); - ReleaseDC (hwndDlg, hDC); - } - - DPIScaleFactorX = 1; - DPIScaleFactorY = 1; - DlgAspectRatio = 1; - - if (ScreenDPI != USER_DEFAULT_SCREEN_DPI) - { - // Windows skews the GUI aspect ratio if the user has a non-default DPI. Hence, working with - // actual screen DPI is redundant and leads to incorrect results. What really matters here is - // how Windows actually renders our GUI. This is determined by comparing the expected and current - // sizes of a hidden calibration text field. - - RECT trec; - - trec.right = 0; - trec.bottom = 0; - - GetClientRect (GetDlgItem (hwndDlg, IDC_ASPECT_RATIO_CALIBRATION_BOX), &trec); - - if (trec.right != 0 && trec.bottom != 0) - { - // The size of the 282x282 IDC_ASPECT_RATIO_CALIBRATION_BOX rendered at the default DPI (96) is 423x458 - DPIScaleFactorX = (double) trec.right / 423; - DPIScaleFactorY = (double) trec.bottom / 458; - DlgAspectRatio = DPIScaleFactorX / DPIScaleFactorY; - } - } - - EndDialog (hwndDlg, 0); - return 1; - } - - case WM_CLOSE: - EndDialog (hwndDlg, 0); - return 1; - } - - return 0; -} - - -/* Except in response to the WM_INITDIALOG message, the dialog box procedure - should return nonzero if it processes the message, and zero if it does - not. - see DialogProc */ -BOOL CALLBACK AboutDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - static HBITMAP hbmTextualLogoBitmapRescaled = NULL; - - switch (msg) - { - case WM_INITDIALOG: - { - wchar_t szTmp[100]; - RECT rec; - - LocalizeDialog (hwndDlg, "IDD_ABOUT_DLG"); - - // Hyperlink - SetWindowText (GetDlgItem (hwndDlg, IDC_HOMEPAGE), L"www.idrix.fr"); - ToHyperlink (hwndDlg, IDC_HOMEPAGE); - - // Logo area background (must not keep aspect ratio; must retain Windows-imposed distortion) - GetClientRect (GetDlgItem (hwndDlg, IDC_ABOUT_LOGO_AREA), &rec); - SetWindowPos (GetDlgItem (hwndDlg, IDC_ABOUT_BKG), HWND_TOP, 0, 0, rec.right, rec.bottom, SWP_NOMOVE); - - // Resize the logo bitmap if the user has a non-default DPI - if (ScreenDPI != USER_DEFAULT_SCREEN_DPI) - { - // Logo (must recreate and keep the original aspect ratio as Windows distorts it) - hbmTextualLogoBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_TEXTUAL_LOGO_288DPI), - GetDlgItem (hwndDlg, IDC_TEXTUAL_LOGO_IMG), - 0, 0, 0, 0, FALSE, TRUE); - - SetWindowPos (GetDlgItem (hwndDlg, IDC_ABOUT_BKG), HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - } - - // Version - SendMessage (GetDlgItem (hwndDlg, IDT_ABOUT_VERSION), WM_SETFONT, (WPARAM) hUserBoldFont, 0); - StringCbPrintfW (szTmp, sizeof(szTmp), L"VeraCrypt %s", _T(VERSION_STRING)); -#ifdef _WIN64 - StringCbCatW (szTmp, sizeof(szTmp), L" (64-bit)"); -#else - StringCbCatW (szTmp, sizeof(szTmp), L" (32-bit)"); -#endif -#if (defined(_DEBUG) || defined(DEBUG)) - StringCbCatW (szTmp, sizeof(szTmp), L" (debug)"); -#endif - SetDlgItemText (hwndDlg, IDT_ABOUT_VERSION, szTmp); - SetDlgItemText (hwndDlg, IDT_ABOUT_RELEASE, TC_STR_RELEASED_BY); - - // Credits - SendMessage (GetDlgItem (hwndDlg, IDC_ABOUT_CREDITS), WM_SETFONT, (WPARAM) hUserFont, (LPARAM) 0); - SendMessage (hwndDlg, WM_APP, 0, 0); - return 1; - } - - case WM_APP: - SetWindowText (GetDlgItem (hwndDlg, IDC_ABOUT_CREDITS), - L"Based on TrueCrypt 7.1a, freely available at http://www.truecrypt.org/ .\r\n\r\n" - - L"Portions of this software:\r\n" - L"Copyright \xA9 2013-2016 IDRIX. All rights reserved.\r\n" - L"Copyright \xA9 2003-2012 TrueCrypt Developers Association. All Rights Reserved.\r\n" - L"Copyright \xA9 1998-2000 Paul Le Roux. All Rights Reserved.\r\n" - L"Copyright \xA9 1998-2008 Brian Gladman. All Rights Reserved.\r\n" - L"Copyright \xA9 2002-2004 Mark Adler. All Rights Reserved.\r\n\r\n" - - L"This software as a whole:\r\n" - L"Copyright \xA9 2013-2016 IDRIX. All rights reserved.\r\n\r\n" - - L"An IDRIX Release"); - - return 1; - - case WM_COMMAND: - if (lw == IDOK || lw == IDCANCEL) - { - PostMessage (hwndDlg, WM_CLOSE, 0, 0); - return 1; - } - - if (lw == IDC_HOMEPAGE) - { - Applink ("main", TRUE, ""); - return 1; - } - - // Disallow modification of credits - if (HIWORD (wParam) == EN_UPDATE) - { - SendMessage (hwndDlg, WM_APP, 0, 0); - return 1; - } - - return 0; - - case WM_CLOSE: - /* Delete buffered bitmaps (if any) */ - if (hbmTextualLogoBitmapRescaled != NULL) - { - DeleteObject ((HGDIOBJ) hbmTextualLogoBitmapRescaled); - hbmTextualLogoBitmapRescaled = NULL; - } - - EndDialog (hwndDlg, 0); - return 1; - } - - return 0; -} - - -static HWND StaticModelessWaitDlgHandle = NULL; - -// Call DisplayStaticModelessWaitDlg() to open this dialog and CloseStaticModelessWaitDlg() to close it. -static BOOL CALLBACK StaticModelessWaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - LocalizeDialog (hwndDlg, NULL); - - return 0; - } - - case WM_COMMAND: - - if (lw == IDOK || lw == IDCANCEL) - return 1; - - return 0; - - - case WM_CLOSE: - StaticModelessWaitDlgHandle = NULL; - EndDialog (hwndDlg, 0); - return 1; - } - - return 0; -} - - -// Opens a dialog window saying "Please wait..." which is not modal and does not need any GUI refresh after initialization. -void DisplayStaticModelessWaitDlg (HWND parent) -{ - if (StaticModelessWaitDlgHandle != NULL) - return; // Already shown - - StaticModelessWaitDlgHandle = CreateDialogParamW (hInst, MAKEINTRESOURCEW (IDD_STATIC_MODELESS_WAIT_DLG), parent, (DLGPROC) StaticModelessWaitDlgProc, (LPARAM) 0); - - ShowWindow (StaticModelessWaitDlgHandle, SW_SHOWNORMAL); - - // Allow synchronous use with the GUI being instantly and fully rendered - ProcessPaintMessages (StaticModelessWaitDlgHandle, 500); -} - - -void CloseStaticModelessWaitDlg (void) -{ - if (StaticModelessWaitDlgHandle == NULL) - return; // Not shown - - DestroyWindow (StaticModelessWaitDlgHandle); -} - - -BOOL IsButtonChecked (HWND hButton) -{ - if (SendMessage (hButton, BM_GETCHECK, 0, 0) == BST_CHECKED) - return TRUE; - else - return FALSE; -} - - -void CheckButton (HWND hButton) -{ - SendMessage (hButton, BM_SETCHECK, BST_CHECKED, 0); -} - - -void LeftPadString (wchar_t *szTmp, int len, int targetLen, wchar_t filler) -{ - int i; - - if (targetLen <= len) - return; - - for (i = targetLen-1; i >= (targetLen-len); i--) - szTmp [i] = szTmp [i-(targetLen-len)]; - - wmemset (szTmp, filler, targetLen-len); - szTmp [targetLen] = 0; -} - -/* InitDialog - initialize the applications main dialog, this function should - be called only once in the dialogs WM_INITDIALOG message handler */ -void InitDialog (HWND hwndDlg) -{ - NONCLIENTMETRICSW metric; - static BOOL aboutMenuAppended = FALSE; - - int nHeight; - LOGFONTW lf; - HMENU hMenu; - Font *font; - - /* Fonts */ - - memset (&lf, 0, sizeof(lf)); - - // Normal - font = GetFont ("font_normal"); - - metric.cbSize = sizeof (metric); - SystemParametersInfoW (SPI_GETNONCLIENTMETRICS, sizeof(metric), &metric, 0); - - WindowTitleBarFont = CreateFontIndirectW (&metric.lfCaptionFont); - - metric.lfMessageFont.lfHeight = CompensateDPIFont (!font ? -11 : -font->Size); - metric.lfMessageFont.lfWidth = 0; - - if (font && wcscmp (font->FaceName, L"default") != 0) - { - StringCbCopyW ((WCHAR *)metric.lfMessageFont.lfFaceName, sizeof (metric.lfMessageFont.lfFaceName), font->FaceName); - } - else if (IsOSAtLeast (WIN_VISTA)) - { - // Vista's new default font (size and spacing) breaks compatibility with Windows 2k/XP applications. - // Force use of Tahoma (as Microsoft does in many dialogs) until a native Vista look is implemented. - StringCbCopyW ((WCHAR *)metric.lfMessageFont.lfFaceName, sizeof (metric.lfMessageFont.lfFaceName), L"Tahoma"); - } - - hUserFont = CreateFontIndirectW (&metric.lfMessageFont); - - metric.lfMessageFont.lfUnderline = TRUE; - hUserUnderlineFont = CreateFontIndirectW (&metric.lfMessageFont); - - metric.lfMessageFont.lfUnderline = FALSE; - metric.lfMessageFont.lfWeight = FW_BOLD; - hUserBoldFont = CreateFontIndirectW (&metric.lfMessageFont); - - metric.lfMessageFont.lfUnderline = TRUE; - metric.lfMessageFont.lfWeight = FW_BOLD; - hUserUnderlineBoldFont = CreateFontIndirectW (&metric.lfMessageFont); - - // Fixed-size (hexadecimal digits) - nHeight = CompensateDPIFont (-12); - lf.lfHeight = nHeight; - lf.lfWidth = 0; - lf.lfEscapement = 0; - lf.lfOrientation = 0; - lf.lfWeight = FW_NORMAL; - lf.lfItalic = FALSE; - lf.lfUnderline = FALSE; - lf.lfStrikeOut = FALSE; - lf.lfCharSet = DEFAULT_CHARSET; - lf.lfOutPrecision = OUT_DEFAULT_PRECIS; - lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; - lf.lfQuality = PROOF_QUALITY; - lf.lfPitchAndFamily = FF_DONTCARE; - StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName), L"Courier New"); - hFixedDigitFont = CreateFontIndirectW (&lf); - if (hFixedDigitFont == NULL) - { - handleWin32Error (hwndDlg, SRC_POS); - AbortProcess ("NOFONT"); - } - - // Bold - font = GetFont ("font_bold"); - - nHeight = CompensateDPIFont (!font ? -13 : -font->Size); - lf.lfHeight = nHeight; - lf.lfWeight = FW_BLACK; - StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName), !font ? L"Arial" : font->FaceName); - hBoldFont = CreateFontIndirectW (&lf); - if (hBoldFont == NULL) - { - handleWin32Error (hwndDlg, SRC_POS); - AbortProcess ("NOFONT"); - } - - // Title - font = GetFont ("font_title"); - - nHeight = CompensateDPIFont (!font ? -21 : -font->Size); - lf.lfHeight = nHeight; - lf.lfWeight = FW_REGULAR; - StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName),!font ? L"Times New Roman" : font->FaceName); - hTitleFont = CreateFontIndirectW (&lf); - if (hTitleFont == NULL) - { - handleWin32Error (hwndDlg, SRC_POS); - AbortProcess ("NOFONT"); - } - - // Fixed-size - font = GetFont ("font_fixed"); - - nHeight = CompensateDPIFont (!font ? -12 : -font->Size); - lf.lfHeight = nHeight; - lf.lfWidth = 0; - lf.lfEscapement = 0; - lf.lfOrientation = 0; - lf.lfWeight = FW_NORMAL; - lf.lfItalic = FALSE; - lf.lfUnderline = FALSE; - lf.lfStrikeOut = FALSE; - lf.lfCharSet = DEFAULT_CHARSET; - lf.lfOutPrecision = OUT_DEFAULT_PRECIS; - lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; - lf.lfQuality = PROOF_QUALITY; - lf.lfPitchAndFamily = FF_DONTCARE; - StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName),!font ? L"Lucida Console" : font->FaceName); - hFixedFont = CreateFontIndirectW (&lf); - if (hFixedFont == NULL) - { - handleWin32Error (hwndDlg, SRC_POS); - AbortProcess ("NOFONT"); - } - - if (!aboutMenuAppended) - { - hMenu = GetSystemMenu (hwndDlg, FALSE); - AppendMenu (hMenu, MF_SEPARATOR, 0, L""); - AppendMenuW (hMenu, MF_ENABLED | MF_STRING, IDC_ABOUT, GetString ("ABOUTBOX")); - - aboutMenuAppended = TRUE; - } -} - - -// The parameter maxMessagesToProcess prevents endless processing of paint messages -void ProcessPaintMessages (HWND hwnd, int maxMessagesToProcess) -{ - MSG paintMsg; - int msgCounter = maxMessagesToProcess; - - while (PeekMessageW (&paintMsg, hwnd, 0, 0, PM_REMOVE | PM_QS_PAINT) != 0 && msgCounter-- > 0) - { - DispatchMessageW (&paintMsg); - } -} - - -HDC CreateMemBitmap (HINSTANCE hInstance, HWND hwnd, wchar_t *resource) -{ - HBITMAP picture = LoadBitmap (hInstance, resource); - HDC viewDC = GetDC (hwnd), dcMem; - - dcMem = CreateCompatibleDC (viewDC); - - SetMapMode (dcMem, MM_TEXT); - - SelectObject (dcMem, picture); - - DeleteObject (picture); - - ReleaseDC (hwnd, viewDC); - - return dcMem; -} - - -/* Renders the specified bitmap at the specified location and stretches it to fit (anti-aliasing is applied). -If bDirectRender is FALSE and both nWidth and nHeight are zero, the width and height of hwndDest are -retrieved and adjusted according to screen DPI (the width and height of the resultant image are adjusted the -same way); furthermore, if bKeepAspectRatio is TRUE, the smaller DPI factor of the two (i.e. horiz. or vert.) -is used both for horiz. and vert. scaling (note that the overall GUI aspect ratio changes irregularly in -both directions depending on the DPI). If bDirectRender is TRUE, bKeepAspectRatio is ignored. -This function returns a handle to the scaled bitmap. When the bitmap is no longer needed, it should be -deleted by calling DeleteObject() with the handle passed as the parameter. -Known Windows issues: -- For some reason, anti-aliasing is not applied if the source bitmap contains less than 16K pixels. -- Windows 2000 may produce slightly inaccurate colors even when source, buffer, and target are 24-bit true color. */ -HBITMAP RenderBitmap (wchar_t *resource, HWND hwndDest, int x, int y, int nWidth, int nHeight, BOOL bDirectRender, BOOL bKeepAspectRatio) -{ - LRESULT lResult = 0; - - HDC hdcSrc = CreateMemBitmap (hInst, hwndDest, resource); - if (!hdcSrc) - return NULL; - - HGDIOBJ picture = GetCurrentObject (hdcSrc, OBJ_BITMAP); - - HBITMAP hbmpRescaled = NULL; - BITMAP bitmap; - - HDC hdcRescaled; - - if (!bDirectRender && nWidth == 0 && nHeight == 0) - { - RECT rec; - - GetClientRect (hwndDest, &rec); - - if (bKeepAspectRatio) - { - if (DlgAspectRatio > 1) - { - // Do not fix this, it's correct. We use the Y scale factor intentionally for both - // directions to maintain aspect ratio (see above for more info). - nWidth = CompensateYDPI (rec.right); - nHeight = CompensateYDPI (rec.bottom); - } - else - { - // Do not fix this, it's correct. We use the X scale factor intentionally for both - // directions to maintain aspect ratio (see above for more info). - nWidth = CompensateXDPI (rec.right); - nHeight = CompensateXDPI (rec.bottom); - } - } - else - { - nWidth = CompensateXDPI (rec.right); - nHeight = CompensateYDPI (rec.bottom); - } - } - - GetObject (picture, sizeof (BITMAP), &bitmap); - - hdcRescaled = CreateCompatibleDC (hdcSrc); - - if (hdcRescaled) - { - hbmpRescaled = CreateCompatibleBitmap (hdcSrc, nWidth, nHeight); - - SelectObject (hdcRescaled, hbmpRescaled); - - /* Anti-aliasing mode (HALFTONE is the only anti-aliasing algorithm natively supported by Windows 2000. - TODO: GDI+ offers higher quality -- InterpolationModeHighQualityBicubic) */ - SetStretchBltMode (hdcRescaled, HALFTONE); - - StretchBlt (hdcRescaled, - 0, - 0, - nWidth, - nHeight, - hdcSrc, - 0, - 0, - bitmap.bmWidth, - bitmap.bmHeight, - SRCCOPY); - - DeleteDC (hdcSrc); - - if (bDirectRender) - { - HDC hdcDest = GetDC (hwndDest); - if (hdcDest) - { - BitBlt (hdcDest, x, y, nWidth, nHeight, hdcRescaled, 0, 0, SRCCOPY); - ReleaseDC (hwndDest, hdcDest); - } - } - else - { - lResult = SendMessage (hwndDest, (UINT) STM_SETIMAGE, (WPARAM) IMAGE_BITMAP, (LPARAM) (HANDLE) hbmpRescaled); - } - - if ((HGDIOBJ) lResult != NULL && (HGDIOBJ) lResult != (HGDIOBJ) hbmpRescaled) - DeleteObject ((HGDIOBJ) lResult); - - DeleteDC (hdcRescaled); - } - - return hbmpRescaled; -} - - -LRESULT CALLBACK -RedTick (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - if (uMsg == WM_CREATE) - { - } - else if (uMsg == WM_DESTROY) - { - } - else if (uMsg == WM_TIMER) - { - } - else if (uMsg == WM_PAINT) - { - PAINTSTRUCT tmp; - HPEN hPen; - HDC hDC; - BOOL bEndPaint; - RECT Rect; - - if (GetUpdateRect (hwnd, NULL, FALSE)) - { - hDC = BeginPaint (hwnd, &tmp); - bEndPaint = TRUE; - if (hDC == NULL) - return DefWindowProcW (hwnd, uMsg, wParam, lParam); - } - else - { - hDC = GetDC (hwnd); - bEndPaint = FALSE; - } - - GetClientRect (hwnd, &Rect); - - hPen = CreatePen (PS_SOLID, 2, RGB (0, 255, 0)); - if (hPen != NULL) - { - HGDIOBJ hObj = SelectObject (hDC, hPen); - WORD bx = LOWORD (GetDialogBaseUnits ()); - WORD by = HIWORD (GetDialogBaseUnits ()); - - MoveToEx (hDC, (Rect.right - Rect.left) / 2, Rect.bottom, NULL); - LineTo (hDC, Rect.right, Rect.top); - MoveToEx (hDC, (Rect.right - Rect.left) / 2, Rect.bottom, NULL); - - LineTo (hDC, (3 * bx) / 4, (2 * by) / 8); - - SelectObject (hDC, hObj); - DeleteObject (hPen); - } - - if (bEndPaint) - EndPaint (hwnd, &tmp); - else - ReleaseDC (hwnd, hDC); - - return TRUE; - } - - return DefWindowProcW (hwnd, uMsg, wParam, lParam); -} - -BOOL -RegisterRedTick (HINSTANCE hInstance) -{ - WNDCLASSW wc; - ULONG rc; - - memset(&wc, 0 , sizeof wc); - - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.cbClsExtra = 0; - wc.cbWndExtra = 4; - wc.hInstance = hInstance; - wc.hIcon = LoadIcon (NULL, IDI_APPLICATION); - wc.hCursor = NULL; - wc.hbrBackground = (HBRUSH) GetStockObject (LTGRAY_BRUSH); - wc.lpszClassName = L"VCREDTICK"; - wc.lpfnWndProc = &RedTick; - - rc = (ULONG) RegisterClassW (&wc); - - return rc == 0 ? FALSE : TRUE; -} - -BOOL -UnregisterRedTick (HINSTANCE hInstance) -{ - return UnregisterClassW (L"VCREDTICK", hInstance); -} - -LRESULT CALLBACK -SplashDlgProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - return DefDlgProcW (hwnd, uMsg, wParam, lParam); -} - -static int g_waitCursorCounter = 0; - -void -WaitCursor () -{ - static HCURSOR hcWait; - if (hcWait == NULL) - hcWait = LoadCursor (NULL, IDC_WAIT); - - if ((g_waitCursorCounter == 0) || (hCursor != hcWait)) - { - SetCursor (hcWait); - hCursor = hcWait; - } - g_waitCursorCounter++; -} - -void -NormalCursor () -{ - static HCURSOR hcArrow; - if (hcArrow == NULL) - hcArrow = LoadCursor (NULL, IDC_ARROW); - if (g_waitCursorCounter > 0) - g_waitCursorCounter--; - if (g_waitCursorCounter == 0) - { - SetCursor (hcArrow); - hCursor = NULL; - } -} - -void -ArrowWaitCursor () -{ - static HCURSOR hcArrowWait; - if (hcArrowWait == NULL) - hcArrowWait = LoadCursor (NULL, IDC_APPSTARTING); - if ((g_waitCursorCounter == 0) || (hCursor != hcArrowWait)) - { - SetCursor (hcArrowWait); - hCursor = hcArrowWait; - } - g_waitCursorCounter++; -} - -void HandCursor () -{ - static HCURSOR hcHand; - if (hcHand == NULL) - hcHand = LoadCursor (NULL, IDC_HAND); - SetCursor (hcHand); - hCursor = hcHand; -} - -void -AddComboPair (HWND hComboBox, const wchar_t *lpszItem, int value) -{ - LPARAM nIndex; - - nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) lpszItem); - nIndex = SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) value); -} - -void -SelectAlgo (HWND hComboBox, int *algo_id) -{ - LPARAM nCount = SendMessage (hComboBox, CB_GETCOUNT, 0, 0); - LPARAM x, i; - - for (i = 0; i < nCount; i++) - { - x = SendMessage (hComboBox, CB_GETITEMDATA, i, 0); - if (x == (LPARAM) *algo_id) - { - SendMessage (hComboBox, CB_SETCURSEL, i, 0); - return; - } - } - - /* Something went wrong ; couldn't find the requested algo id so we drop - back to a default */ - - *algo_id = (int) SendMessage (hComboBox, CB_GETITEMDATA, 0, 0); - - SendMessage (hComboBox, CB_SETCURSEL, 0, 0); - -} - -void PopulateWipeModeCombo (HWND hComboBox, BOOL bNA, BOOL bInPlaceEncryption, BOOL bHeaderWipe) -{ - if (bNA) - { - AddComboPair (hComboBox, GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE"), TC_WIPE_NONE); - } - else - { - if (!bHeaderWipe) - { - AddComboPair (hComboBox, GetString ("WIPE_MODE_NONE"), TC_WIPE_NONE); - } - - AddComboPair (hComboBox, GetString ("WIPE_MODE_1_RAND"), TC_WIPE_1_RAND); - AddComboPair (hComboBox, GetString ("WIPE_MODE_3_DOD_5220"), TC_WIPE_3_DOD_5220); - AddComboPair (hComboBox, GetString ("WIPE_MODE_7_DOD_5220"), TC_WIPE_7_DOD_5220); - AddComboPair (hComboBox, GetString ("WIPE_MODE_35_GUTMANN"), TC_WIPE_35_GUTMANN); - - if (bHeaderWipe) - AddComboPair (hComboBox, GetString ("WIPE_MODE_256"), TC_WIPE_256); // paranoid wipe for volume header - } -} - -wchar_t *GetWipeModeName (WipeAlgorithmId modeId) -{ - switch (modeId) - { - case TC_WIPE_NONE: - return GetString ("WIPE_MODE_NONE"); - - case TC_WIPE_1_RAND: - return GetString ("WIPE_MODE_1_RAND"); - - case TC_WIPE_3_DOD_5220: - return GetString ("WIPE_MODE_3_DOD_5220"); - - case TC_WIPE_7_DOD_5220: - return GetString ("WIPE_MODE_7_DOD_5220"); - - case TC_WIPE_35_GUTMANN: - return GetString ("WIPE_MODE_35_GUTMANN"); - - case TC_WIPE_256: - return GetString ("WIPE_MODE_256"); - - default: - return GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE"); - } -} - -wchar_t *GetPathType (const wchar_t *path, BOOL bUpperCase, BOOL *bIsPartition) -{ - if (wcsstr (path, L"Partition") - && wcsstr (path, L"Partition0") == NULL) - { - *bIsPartition = TRUE; - return GetString (bUpperCase ? "PARTITION_UPPER_CASE" : "PARTITION_LOWER_CASE"); - } - else if (wcsstr (path, L"HarddiskVolume")) - { - *bIsPartition = TRUE; - return GetString (bUpperCase ? "VOLUME_UPPER_CASE" : "VOLUME_LOWER_CASE"); - } - - *bIsPartition = FALSE; - return GetString (bUpperCase ? "DEVICE_UPPER_CASE" : "DEVICE_LOWER_CASE"); -} - -LRESULT CALLBACK CustomDlgProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - if (uMsg == WM_SETCURSOR && hCursor != NULL) - { - SetCursor (hCursor); - return TRUE; - } - - return DefDlgProcW (hwnd, uMsg, wParam, lParam); -} - -/* -static BOOL IsReturnAddress (DWORD64 address) -{ - static size_t codeEnd = 0; - byte *sp = (byte *) address; - - if (codeEnd == 0) - { - MEMORY_BASIC_INFORMATION mi; - if (VirtualQuery ((LPCVOID) 0x401000, &mi, sizeof (mi)) >= sizeof (mi)) - codeEnd = (size_t) mi.BaseAddress + mi.RegionSize; - } - - if (address < 0x401000 + 8 || address > codeEnd) - return FALSE; - - return sp[-5] == 0xe8 // call ADDR - || (sp[-6] == 0xff && sp[-5] == 0x15) // call [ADDR] - || (sp[-2] == 0xff && (sp[-1] & 0xf0) == 0xd0); // call REG -} -*/ - -typedef struct -{ - EXCEPTION_POINTERS *ExceptionPointers; - HANDLE ExceptionThread; - -} ExceptionHandlerThreadArgs; - - -void ExceptionHandlerThread (void *threadArg) -{ - ExceptionHandlerThreadArgs *args = (ExceptionHandlerThreadArgs *) threadArg; - - EXCEPTION_POINTERS *ep = args->ExceptionPointers; - //DWORD addr; - DWORD exCode = ep->ExceptionRecord->ExceptionCode; - // SYSTEM_INFO si; - // wchar_t msg[8192]; - // char modPath[MAX_PATH]; - // int crc = 0; - // char url[MAX_URL_LENGTH]; - // char lpack[128]; - // stringstream callStack; - // addr = (DWORD) ep->ExceptionRecord->ExceptionAddress; - // PDWORD sp = (PDWORD) ep->ContextRecord->Esp; - // int frameNumber = 0; - - switch (exCode) - { - case STATUS_IN_PAGE_ERROR: - case 0xeedfade: - // Exception not caused by VeraCrypt - MessageBoxW (0, GetString ("EXCEPTION_REPORT_EXT"), - GetString ("EXCEPTION_REPORT_TITLE"), - MB_ICONERROR | MB_OK | MB_SETFOREGROUND | MB_TOPMOST); - return; - } - - // Call stack -/* HMODULE dbgDll = LoadLibrary ("dbghelp.dll"); - if (dbgDll) - { - typedef DWORD (__stdcall *SymGetOptions_t) (); - typedef DWORD (__stdcall *SymSetOptions_t) (DWORD SymOptions); - typedef BOOL (__stdcall *SymInitialize_t) (HANDLE hProcess, PCSTR UserSearchPath, BOOL fInvadeProcess); - typedef BOOL (__stdcall *StackWalk64_t) (DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME64 StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress); - typedef BOOL (__stdcall * SymFromAddr_t) (HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol); - - SymGetOptions_t DbgHelpSymGetOptions = (SymGetOptions_t) GetProcAddress (dbgDll, "SymGetOptions"); - SymSetOptions_t DbgHelpSymSetOptions = (SymSetOptions_t) GetProcAddress (dbgDll, "SymSetOptions"); - SymInitialize_t DbgHelpSymInitialize = (SymInitialize_t) GetProcAddress (dbgDll, "SymInitialize"); - PFUNCTION_TABLE_ACCESS_ROUTINE64 DbgHelpSymFunctionTableAccess64 = (PFUNCTION_TABLE_ACCESS_ROUTINE64) GetProcAddress (dbgDll, "SymFunctionTableAccess64"); - PGET_MODULE_BASE_ROUTINE64 DbgHelpSymGetModuleBase64 = (PGET_MODULE_BASE_ROUTINE64) GetProcAddress (dbgDll, "SymGetModuleBase64"); - StackWalk64_t DbgHelpStackWalk64 = (StackWalk64_t) GetProcAddress (dbgDll, "StackWalk64"); - SymFromAddr_t DbgHelpSymFromAddr = (SymFromAddr_t) GetProcAddress (dbgDll, "SymFromAddr"); - - if (DbgHelpSymGetOptions && DbgHelpSymSetOptions && DbgHelpSymInitialize && DbgHelpSymFunctionTableAccess64 && DbgHelpSymGetModuleBase64 && DbgHelpStackWalk64 && DbgHelpSymFromAddr) - { - DbgHelpSymSetOptions (DbgHelpSymGetOptions() | SYMOPT_DEFERRED_LOADS | SYMOPT_ALLOW_ABSOLUTE_SYMBOLS | SYMOPT_NO_CPP); - - if (DbgHelpSymInitialize (GetCurrentProcess(), NULL, TRUE)) - { - STACKFRAME64 frame; - memset (&frame, 0, sizeof (frame)); - - frame.AddrPC.Offset = ep->ContextRecord->Eip; - frame.AddrPC.Mode = AddrModeFlat; - frame.AddrStack.Offset = ep->ContextRecord->Esp; - frame.AddrStack.Mode = AddrModeFlat; - frame.AddrFrame.Offset = ep->ContextRecord->Ebp; - frame.AddrFrame.Mode = AddrModeFlat; - - string lastSymbol; - - while (frameNumber < 32 && DbgHelpStackWalk64 (IMAGE_FILE_MACHINE_I386, GetCurrentProcess(), args->ExceptionThread, &frame, ep->ContextRecord, NULL, DbgHelpSymFunctionTableAccess64, DbgHelpSymGetModuleBase64, NULL)) - { - if (!frame.AddrPC.Offset) - continue; - - ULONG64 symbolBuffer[(sizeof (SYMBOL_INFO) + MAX_SYM_NAME * sizeof (TCHAR) + sizeof (ULONG64) - 1) / sizeof (ULONG64)]; - memset (symbolBuffer, 0, sizeof (symbolBuffer)); - - PSYMBOL_INFO symbol = (PSYMBOL_INFO) symbolBuffer; - symbol->SizeOfStruct = sizeof (SYMBOL_INFO); - symbol->MaxNameLen = MAX_SYM_NAME; - - if (DbgHelpSymFromAddr (GetCurrentProcess(), frame.AddrPC.Offset, NULL, symbol) && symbol->NameLen > 0) - { - for (size_t i = 0; i < symbol->NameLen; ++i) - { - if (!isalnum (symbol->Name[i])) - symbol->Name[i] = '_'; - } - - if (symbol->Name != lastSymbol) - callStack << "&st" << frameNumber++ << "=" << symbol->Name; - - lastSymbol = symbol->Name; - } - else if (frameNumber == 0 || IsReturnAddress (frame.AddrPC.Offset)) - { - callStack << "&st" << frameNumber++ << "=0x" << hex << frame.AddrPC.Offset << dec; - } - } - } - } - } - - // StackWalk64() may fail due to missing frame pointers - list retAddrs; - if (frameNumber == 0) - retAddrs.push_back (ep->ContextRecord->Eip); - - retAddrs.push_back (0); - - MEMORY_BASIC_INFORMATION mi; - VirtualQuery (sp, &mi, sizeof (mi)); - PDWORD stackTop = (PDWORD)((byte *) mi.BaseAddress + mi.RegionSize); - int i = 0; - - while (retAddrs.size() < 16 && &sp[i] < stackTop) - { - if (IsReturnAddress (sp[i])) - { - bool duplicate = false; - foreach (DWORD prevAddr, retAddrs) - { - if (sp[i] == prevAddr) - { - duplicate = true; - break; - } - } - - if (!duplicate) - retAddrs.push_back (sp[i]); - } - i++; - } - - if (retAddrs.size() > 1) - { - foreach (DWORD addr, retAddrs) - { - callStack << "&st" << frameNumber++ << "=0x" << hex << addr << dec; - } - } - - // Checksum of the module - if (GetModuleFileName (NULL, modPath, sizeof (modPath))) - { - HANDLE h = CreateFile (modPath, FILE_READ_DATA | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - if (h != INVALID_HANDLE_VALUE) - { - BY_HANDLE_FILE_INFORMATION fi; - if (GetFileInformationByHandle (h, &fi)) - { - char *buf = (char *) malloc (fi.nFileSizeLow); - if (buf) - { - DWORD bytesRead; - if (ReadFile (h, buf, fi.nFileSizeLow, &bytesRead, NULL) && bytesRead == fi.nFileSizeLow) - crc = GetCrc32 ((unsigned char *) buf, fi.nFileSizeLow); - free (buf); - } - } - CloseHandle (h); - } - } - - GetSystemInfo (&si); - - if (LocalizationActive) - sprintf_s (lpack, sizeof (lpack), "&langpack=%s_%s", GetPreferredLangId (), GetActiveLangPackVersion ()); - else - lpack[0] = 0; - - - sprintf (url, TC_APPLINK_SECURE "&dest=err-report%s&os=%s&osver=%d.%d.%d&arch=%s&cpus=%d&app=%s&cksum=%x&dlg=%s&err=%x&addr=%x" - , lpack - , GetWindowsEdition().c_str() - , CurrentOSMajor - , CurrentOSMinor - , CurrentOSServicePack - , Is64BitOs () ? "x64" : "x86" - , si.dwNumberOfProcessors -#ifdef TCMOUNT - ,"main" -#endif -#ifdef VOLFORMAT - ,"format" -#endif -#ifdef SETUP - ,"setup" -#endif - , crc - , LastDialogId ? LastDialogId : "-" - , exCode - , addr); - - string urlStr = url + callStack.str(); - - _snwprintf (msg, array_capacity (msg), GetString ("EXCEPTION_REPORT"), urlStr.c_str()); - - if (IDYES == MessageBoxW (0, msg, GetString ("EXCEPTION_REPORT_TITLE"), MB_ICONERROR | MB_YESNO | MB_DEFBUTTON1)) - ShellExecute (NULL, "open", urlStr.c_str(), NULL, NULL, SW_SHOWNORMAL); - else */ - UnhandledExceptionFilter (ep); -} - - -LONG __stdcall ExceptionHandler (EXCEPTION_POINTERS *ep) -{ - SetUnhandledExceptionFilter (NULL); - - if (SystemFileSelectorCallPending && SystemFileSelectorCallerThreadId == GetCurrentThreadId()) - { - MessageBoxW (NULL, GetString ("EXCEPTION_REPORT_EXT_FILESEL"), GetString ("EXCEPTION_REPORT_TITLE"), MB_ICONERROR | MB_OK | MB_SETFOREGROUND | MB_TOPMOST); - - UnhandledExceptionFilter (ep); - return EXCEPTION_EXECUTE_HANDLER; - } - - ExceptionHandlerThreadArgs args; - args.ExceptionPointers = ep; - args.ExceptionThread = GetCurrentThread(); - - WaitForSingleObject ((HANDLE) _beginthread (ExceptionHandlerThread, 0, &args), INFINITE); - - return EXCEPTION_EXECUTE_HANDLER; -} - - -void InvalidParameterHandler (const wchar_t *expression, const wchar_t *function, const wchar_t *file, unsigned int line, uintptr_t reserved) -{ - TC_THROW_FATAL_EXCEPTION; -} - - -static LRESULT CALLBACK NonInstallUacWndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - return DefWindowProcW (hWnd, message, wParam, lParam); -} - - -// Mutex handling to prevent multiple instances of the wizard or main app from dealing with system encryption. -// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). -BOOL CreateSysEncMutex (void) -{ - return TCCreateMutex (&hSysEncMutex, TC_MUTEX_NAME_SYSENC); -} - - -BOOL InstanceHasSysEncMutex (void) -{ - return (hSysEncMutex != NULL); -} - - -// Mutex handling to prevent multiple instances of the wizard from dealing with system encryption -void CloseSysEncMutex (void) -{ - TCCloseMutex (&hSysEncMutex); -} - - -// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). -BOOL CreateNonSysInplaceEncMutex (void) -{ - return TCCreateMutex (&hNonSysInplaceEncMutex, TC_MUTEX_NAME_NONSYS_INPLACE_ENC); -} - - -BOOL InstanceHasNonSysInplaceEncMutex (void) -{ - return (hNonSysInplaceEncMutex != NULL); -} - - -void CloseNonSysInplaceEncMutex (void) -{ - TCCloseMutex (&hNonSysInplaceEncMutex); -} - - -// Returns TRUE if another instance of the wizard is preparing, resuming or performing non-system in-place encryption -BOOL NonSysInplaceEncInProgressElsewhere (void) -{ - return (!InstanceHasNonSysInplaceEncMutex () - && MutexExistsOnSystem (TC_MUTEX_NAME_NONSYS_INPLACE_ENC)); -} - - -// Mutex handling to prevent multiple instances of the wizard or main app from trying to install -// or register the driver or from trying to launch it in portable mode at the same time. -// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). -BOOL CreateDriverSetupMutex (void) -{ - return TCCreateMutex (&hDriverSetupMutex, TC_MUTEX_NAME_DRIVER_SETUP); -} - - -void CloseDriverSetupMutex (void) -{ - TCCloseMutex (&hDriverSetupMutex); -} - - -BOOL CreateAppSetupMutex (void) -{ - return TCCreateMutex (&hAppSetupMutex, TC_MUTEX_NAME_APP_SETUP); -} - - -void CloseAppSetupMutex (void) -{ - TCCloseMutex (&hAppSetupMutex); -} - - -BOOL IsTrueCryptInstallerRunning (void) -{ - return (MutexExistsOnSystem (TC_MUTEX_NAME_APP_SETUP)); -} - - -// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). -BOOL TCCreateMutex (volatile HANDLE *hMutex, wchar_t *name) -{ - if (*hMutex != NULL) - return TRUE; // This instance already has the mutex - - *hMutex = CreateMutex (NULL, TRUE, name); - if (*hMutex == NULL) - { - // In multi-user configurations, the OS returns "Access is denied" here when a user attempts - // to acquire the mutex if another user already has. However, on Vista, "Access is denied" is - // returned also if the mutex is owned by a process with admin rights while we have none. - - return FALSE; - } - - if (GetLastError () == ERROR_ALREADY_EXISTS) - { - ReleaseMutex (*hMutex); - CloseHandle (*hMutex); - - *hMutex = NULL; - return FALSE; - } - - return TRUE; -} - - -void TCCloseMutex (volatile HANDLE *hMutex) -{ - if (*hMutex != NULL) - { - if (ReleaseMutex (*hMutex) - && CloseHandle (*hMutex)) - *hMutex = NULL; - } -} - - -// Returns TRUE if a process running on the system has the specified mutex (otherwise FALSE). -BOOL MutexExistsOnSystem (wchar_t *name) -{ - if (name[0] == 0) - return FALSE; - - HANDLE hMutex = OpenMutex (MUTEX_ALL_ACCESS, FALSE, name); - - if (hMutex == NULL) - { - if (GetLastError () == ERROR_FILE_NOT_FOUND) - return FALSE; - - if (GetLastError () == ERROR_ACCESS_DENIED) // On Vista, this is returned if the owner of the mutex is elevated while we are not - return TRUE; - - // The call failed and it is not certain whether the mutex exists or not - return FALSE; - } - - CloseHandle (hMutex); - return TRUE; -} - - -uint32 ReadDriverConfigurationFlags () -{ - DWORD configMap; - - if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_DRIVER_CONFIG_REG_VALUE_NAME, &configMap)) - configMap = 0; - - return configMap; -} - - -uint32 ReadEncryptionThreadPoolFreeCpuCountLimit () -{ - DWORD count; - - if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME, &count)) - count = 0; - - return count; -} - - -BOOL LoadSysEncSettings () -{ - BOOL status = TRUE; - DWORD size = 0; - char *sysEncCfgFileBuf = LoadFile (GetConfigPath (TC_APPD_FILENAME_SYSTEM_ENCRYPTION), &size); - char *xml = sysEncCfgFileBuf; - char paramName[100], paramVal[MAX_PATH]; - - // Defaults - int newSystemEncryptionStatus = SYSENC_STATUS_NONE; - WipeAlgorithmId newnWipeMode = TC_WIPE_NONE; - - if (!FileExists (GetConfigPath (TC_APPD_FILENAME_SYSTEM_ENCRYPTION))) - { - SystemEncryptionStatus = newSystemEncryptionStatus; - nWipeMode = newnWipeMode; - } - - if (xml == NULL) - { - return FALSE; - } - - while (xml = XmlFindElement (xml, "config")) - { - XmlGetAttributeText (xml, "key", paramName, sizeof (paramName)); - XmlGetNodeText (xml, paramVal, sizeof (paramVal)); - - if (strcmp (paramName, "SystemEncryptionStatus") == 0) - { - newSystemEncryptionStatus = atoi (paramVal); - } - else if (strcmp (paramName, "WipeMode") == 0) - { - newnWipeMode = (WipeAlgorithmId) atoi (paramVal); - } - - xml++; - } - - SystemEncryptionStatus = newSystemEncryptionStatus; - nWipeMode = newnWipeMode; - - free (sysEncCfgFileBuf); - return status; -} - - -// Returns the number of partitions where non-system in-place encryption is progress or had been in progress -// but was interrupted. In addition, via the passed pointer, returns the last selected wipe algorithm ID. -int LoadNonSysInPlaceEncSettings (WipeAlgorithmId *wipeAlgorithm) -{ - char *fileBuf = NULL; - char *fileBuf2 = NULL; - DWORD size, size2; - int count; - - *wipeAlgorithm = TC_WIPE_NONE; - - if (!FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC))) - return 0; - - if ((fileBuf = LoadFile (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC), &size)) == NULL) - return 0; - - if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE))) - { - if ((fileBuf2 = LoadFile (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE), &size2)) != NULL) - *wipeAlgorithm = (WipeAlgorithmId) atoi (fileBuf2); - } - - count = atoi (fileBuf); - - if (fileBuf != NULL) - TCfree (fileBuf); - - if (fileBuf2 != NULL) - TCfree (fileBuf2); - - return (count); -} - - -void RemoveNonSysInPlaceEncNotifications (void) -{ - if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC))) - _wremove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC)); - - if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE))) - _wremove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE)); - - if (!IsNonInstallMode () && SystemEncryptionStatus == SYSENC_STATUS_NONE) - ManageStartupSeqWiz (TRUE, L""); -} - - -void SavePostInstallTasksSettings (int command) -{ - FILE *f = NULL; - - if (IsNonInstallMode() && command != TC_POST_INSTALL_CFG_REMOVE_ALL) - return; - - switch (command) - { - case TC_POST_INSTALL_CFG_REMOVE_ALL: - _wremove (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL)); - _wremove (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES)); - break; - - case TC_POST_INSTALL_CFG_TUTORIAL: - f = _wfopen (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL), L"w"); - break; - - case TC_POST_INSTALL_CFG_RELEASE_NOTES: - f = _wfopen (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES), L"w"); - break; - - default: - return; - } - - if (f == NULL) - return; - - if (fputws (L"1", f) < 0) - { - // Error - fclose (f); - return; - } - - TCFlushFile (f); - - fclose (f); -} - - -void DoPostInstallTasks (HWND hwndDlg) -{ - BOOL bDone = FALSE; - - if (FileExists (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL))) - { - if (AskYesNo ("AFTER_INSTALL_TUTORIAL", hwndDlg) == IDYES) - Applink ("beginnerstutorial", TRUE, ""); - - bDone = TRUE; - } - - if (FileExists (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES))) - { - if (AskYesNo ("AFTER_UPGRADE_RELEASE_NOTES", hwndDlg) == IDYES) - Applink ("releasenotes", TRUE, ""); - - bDone = TRUE; - } - - if (bDone) - SavePostInstallTasksSettings (TC_POST_INSTALL_CFG_REMOVE_ALL); -} - - -void InitOSVersionInfo () -{ - OSVERSIONINFOEXW os; - os.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW); - - if (GetVersionExW ((LPOSVERSIONINFOW) &os) == FALSE) - AbortProcess ("NO_OS_VER"); - - CurrentOSMajor = os.dwMajorVersion; - CurrentOSMinor = os.dwMinorVersion; - CurrentOSServicePack = os.wServicePackMajor; - - if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 5 && CurrentOSMinor == 0) - nCurrentOS = WIN_2000; - else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 5 && CurrentOSMinor == 1) - nCurrentOS = WIN_XP; - else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 5 && CurrentOSMinor == 2) - { - if (os.wProductType == VER_NT_SERVER || os.wProductType == VER_NT_DOMAIN_CONTROLLER) - nCurrentOS = WIN_SERVER_2003; - else - nCurrentOS = WIN_XP64; - } - else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 6 && CurrentOSMinor == 0) - { - if (os.wProductType != VER_NT_WORKSTATION) - nCurrentOS = WIN_SERVER_2008; - else - nCurrentOS = WIN_VISTA; - } - else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 6 && CurrentOSMinor == 1) - nCurrentOS = ((os.wProductType != VER_NT_WORKSTATION) ? WIN_SERVER_2008_R2 : WIN_7); - else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 6 && CurrentOSMinor == 2) - nCurrentOS = ((os.wProductType != VER_NT_WORKSTATION) ? WIN_SERVER_2012 : WIN_8); - else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 6 && CurrentOSMinor == 3) - nCurrentOS = ((os.wProductType != VER_NT_WORKSTATION) ? WIN_SERVER_2012_R2 : WIN_8_1); - else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 10 && CurrentOSMinor == 0) - nCurrentOS = ((os.wProductType != VER_NT_WORKSTATION) ? WIN_SERVER_2016 : WIN_10); - else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 4) - nCurrentOS = WIN_NT4; - else if (os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && os.dwMajorVersion == 4 && os.dwMinorVersion == 0) - nCurrentOS = WIN_95; - else if (os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && os.dwMajorVersion == 4 && os.dwMinorVersion == 10) - nCurrentOS = WIN_98; - else if (os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && os.dwMajorVersion == 4 && os.dwMinorVersion == 90) - nCurrentOS = WIN_ME; - else if (os.dwPlatformId == VER_PLATFORM_WIN32s) - nCurrentOS = WIN_31; - else - nCurrentOS = WIN_UNKNOWN; -} - -static void LoadSystemDll (LPCTSTR szModuleName, HMODULE *pHandle, BOOL bIgnoreError, const char* srcPos) -{ - wchar_t dllPath[MAX_PATH]; - - /* Load dll explictely from System32 to avoid Dll hijacking attacks*/ - if (!GetSystemDirectory(dllPath, MAX_PATH)) - StringCbCopyW(dllPath, sizeof(dllPath), L"C:\\Windows\\System32"); - - StringCbCatW(dllPath, sizeof(dllPath), L"\\"); - StringCbCatW(dllPath, sizeof(dllPath), szModuleName); - - if (((*pHandle = LoadLibrary(dllPath)) == NULL) && !bIgnoreError) - { - // This error is fatal - handleWin32Error (NULL, srcPos); - AbortProcess ("INIT_DLL"); - } -} - -/* InitApp - initialize the application, this function is called once in the - applications WinMain function, but before the main dialog has been created */ -void InitApp (HINSTANCE hInstance, wchar_t *lpszCommandLine) -{ - WNDCLASSW wc; - char langId[6]; - InitCommonControlsPtr InitCommonControlsFn = NULL; - - InitOSVersionInfo(); - - InitializeCriticalSection (&csWNetCalls); - - LoadSystemDll (L"ntmarta.dll", &hntmartadll, TRUE, SRC_POS); - LoadSystemDll (L"MPR.DLL", &hmprdll, TRUE, SRC_POS); -#ifdef SETUP - if (IsOSAtLeast (WIN_7)) - { - LoadSystemDll (L"ProfApi.DLL", &hProfApiDll, TRUE, SRC_POS); - LoadSystemDll (L"cryptbase.dll", &hcryptbasedll, TRUE, SRC_POS); - LoadSystemDll (L"sspicli.dll", &hsspiclidll, TRUE, SRC_POS); - } -#endif - LoadSystemDll (L"psapi.dll", &hpsapidll, TRUE, SRC_POS); - LoadSystemDll (L"secur32.dll", &hsecur32dll, TRUE, SRC_POS); - LoadSystemDll (L"msasn1.dll", &hmsasn1dll, TRUE, SRC_POS); - LoadSystemDll (L"Usp10.DLL", &hUsp10Dll, TRUE, SRC_POS); - LoadSystemDll (L"UXTheme.dll", &hUXThemeDll, TRUE, SRC_POS); - - LoadSystemDll (L"msls31.dll", &hMsls31, TRUE, SRC_POS); - LoadSystemDll (L"SETUPAPI.DLL", &hSetupDll, FALSE, SRC_POS); - LoadSystemDll (L"SHLWAPI.DLL", &hShlwapiDll, FALSE, SRC_POS); - - LoadSystemDll (L"userenv.dll", &hUserenvDll, TRUE, SRC_POS); - LoadSystemDll (L"rsaenh.dll", &hRsaenhDll, TRUE, SRC_POS); - -#ifdef SETUP - if (nCurrentOS < WIN_7) - { - if (nCurrentOS == WIN_XP) - { - LoadSystemDll (L"imm32.dll", &himm32dll, TRUE, SRC_POS); - LoadSystemDll (L"MSCTF.dll", &hMSCTFdll, TRUE, SRC_POS); - LoadSystemDll (L"fltlib.dll", &hfltlibdll, TRUE, SRC_POS); - LoadSystemDll (L"wbem\\framedyn.dll", &hframedyndll, TRUE, SRC_POS); - } - - if (IsOSAtLeast (WIN_VISTA)) - { - LoadSystemDll (L"netapi32.dll", &hnetapi32dll, TRUE, SRC_POS); - LoadSystemDll (L"authz.dll", &hauthzdll, TRUE, SRC_POS); - LoadSystemDll (L"xmllite.dll", &hxmllitedll, TRUE, SRC_POS); - } - } - - if (IsOSAtLeast (WIN_VISTA)) - { - LoadSystemDll (L"spp.dll", &hsppdll, TRUE, SRC_POS); - LoadSystemDll (L"vssapi.dll", &vssapidll, TRUE, SRC_POS); - LoadSystemDll (L"vsstrace.dll", &hvsstracedll, TRUE, SRC_POS); - - if (IsOSAtLeast (WIN_7)) - { - LoadSystemDll (L"CryptSP.dll", &hCryptSpDll, TRUE, SRC_POS); - - LoadSystemDll (L"cfgmgr32.dll", &hcfgmgr32dll, TRUE, SRC_POS); - LoadSystemDll (L"devobj.dll", &hdevobjdll, TRUE, SRC_POS); - LoadSystemDll (L"powrprof.dll", &hpowrprofdll, TRUE, SRC_POS); - - LoadSystemDll (L"dwmapi.dll", &hdwmapidll, TRUE, SRC_POS); - - LoadSystemDll (L"crypt32.dll", &hcrypt32dll, TRUE, SRC_POS); - - LoadSystemDll (L"bcrypt.dll", &hbcryptdll, TRUE, SRC_POS); - LoadSystemDll (L"bcryptprimitives.dll", &hbcryptprimitivesdll, TRUE, SRC_POS); - } - } -#else - LoadSystemDll (L"WINSCARD.DLL", &hwinscarddll, TRUE, SRC_POS); -#endif - - LoadSystemDll (L"COMCTL32.DLL", &hComctl32Dll, FALSE, SRC_POS); - - // call InitCommonControls function - InitCommonControlsFn = (InitCommonControlsPtr) GetProcAddress (hComctl32Dll, "InitCommonControls"); - ImageList_AddFn = (ImageList_AddPtr) GetProcAddress (hComctl32Dll, "ImageList_Add"); - ImageList_CreateFn = (ImageList_CreatePtr) GetProcAddress (hComctl32Dll, "ImageList_Create"); - - if (InitCommonControlsFn && ImageList_AddFn && ImageList_CreateFn) - { - InitCommonControlsFn(); - } - else - AbortProcess ("INIT_DLL"); - - LoadSystemDll (L"Riched20.dll", &hRichEditDll, FALSE, SRC_POS); - - // Get SetupAPI functions pointers - SetupCloseInfFileFn = (SetupCloseInfFilePtr) GetProcAddress (hSetupDll, "SetupCloseInfFile"); - SetupDiOpenClassRegKeyFn = (SetupDiOpenClassRegKeyPtr) GetProcAddress (hSetupDll, "SetupDiOpenClassRegKey"); - SetupInstallFromInfSectionWFn = (SetupInstallFromInfSectionWPtr) GetProcAddress (hSetupDll, "SetupInstallFromInfSectionW"); - SetupOpenInfFileWFn = (SetupOpenInfFileWPtr) GetProcAddress (hSetupDll, "SetupOpenInfFileW"); - - if (!SetupCloseInfFileFn || !SetupDiOpenClassRegKeyFn || !SetupInstallFromInfSectionWFn || !SetupOpenInfFileWFn) - AbortProcess ("INIT_DLL"); - - // Get SHDeleteKeyW function pointer - SHDeleteKeyWFn = (SHDeleteKeyWPtr) GetProcAddress (hShlwapiDll, "SHDeleteKeyW"); - SHStrDupWFn = (SHStrDupWPtr) GetProcAddress (hShlwapiDll, "SHStrDupW"); - if (!SHDeleteKeyWFn || !SHStrDupWFn) - AbortProcess ("INIT_DLL"); - - if (IsOSAtLeast (WIN_VISTA)) - { - /* Get ChangeWindowMessageFilter used to enable some messages bypasss UIPI (User Interface Privilege Isolation) */ - ChangeWindowMessageFilterFn = (ChangeWindowMessageFilterPtr) GetProcAddress (GetModuleHandle (L"user32.dll"), "ChangeWindowMessageFilter"); - -#ifndef SETUP - /* enable drag-n-drop when we are running elevated */ - AllowMessageInUIPI (WM_DROPFILES); - AllowMessageInUIPI (WM_COPYDATA); - AllowMessageInUIPI (WM_COPYGLOBALDATA); -#endif - } - - /* Save the instance handle for later */ - hInst = hInstance; - - SetErrorMode (SetErrorMode (0) | SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX); - CoInitialize (NULL); - -#ifndef SETUP - // Application ID - typedef HRESULT (WINAPI *SetAppId_t) (PCWSTR appID); - SetAppId_t setAppId = (SetAppId_t) GetProcAddress (GetModuleHandle (L"shell32.dll"), "SetCurrentProcessExplicitAppUserModelID"); - - if (setAppId) - setAppId (TC_APPLICATION_ID); -#endif - - // Language - langId[0] = 0; - SetPreferredLangId (ConfigReadString ("Language", "", langId, sizeof (langId))); - - if (langId[0] == 0) - { - if (IsNonInstallMode ()) - { - // only support automatic use of a language file in portable mode - // this is achieved by placing a unique language XML file in the same - // place as portable VeraCrypt binaries. - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_LANGUAGE), NULL, - (DLGPROC) LanguageDlgProc, (LPARAM) 1); - } - else - { - // when installed, force using English as default language - SetPreferredLangId ("en"); - } - } - - LoadLanguageFile (); - -#ifndef SETUP - // UAC elevation moniker cannot be used in portable mode. - // A new instance of the application must be created with elevated privileges. - if (IsNonInstallMode () && !IsAdmin () && IsUacSupported ()) - { - wchar_t modPath[MAX_PATH], newCmdLine[4096]; - WNDCLASSEXW wcex; - HWND hWnd; - - if (wcsstr (lpszCommandLine, L"/q UAC ") == lpszCommandLine) - { - Error ("UAC_INIT_ERROR", NULL); - exit (1); - } - - memset (&wcex, 0, sizeof (wcex)); - wcex.cbSize = sizeof(WNDCLASSEX); - wcex.lpfnWndProc = (WNDPROC) NonInstallUacWndProc; - wcex.hInstance = hInstance; - wcex.lpszClassName = L"VeraCrypt"; - RegisterClassExW (&wcex); - - // A small transparent window is necessary to bring the new instance to foreground - hWnd = CreateWindowExW (WS_EX_TOOLWINDOW | WS_EX_LAYERED, - L"VeraCrypt", L"VeraCrypt", 0, - GetSystemMetrics (SM_CXSCREEN)/2, - GetSystemMetrics (SM_CYSCREEN)/2, - 1, 1, NULL, NULL, hInstance, NULL); - - SetLayeredWindowAttributes (hWnd, 0, 0, LWA_ALPHA); - ShowWindow (hWnd, SW_SHOWNORMAL); - - GetModuleFileNameW (NULL, modPath, ARRAYSIZE (modPath)); - - StringCbCopyW (newCmdLine, sizeof(newCmdLine), L"/q UAC "); - StringCbCatW (newCmdLine, sizeof (newCmdLine), lpszCommandLine); - - if ((int)ShellExecuteW (hWnd, L"runas", modPath, newCmdLine, NULL, SW_SHOWNORMAL) <= 32) - exit (1); - - Sleep (2000); - exit (0); - } -#endif - - SetUnhandledExceptionFilter (ExceptionHandler); - _set_invalid_parameter_handler (InvalidParameterHandler); - - RemoteSession = GetSystemMetrics (SM_REMOTESESSION) != 0; - - // OS version check - if (CurrentOSMajor < 5) - { - MessageBoxW (NULL, GetString ("UNSUPPORTED_OS"), lpszTitle, MB_ICONSTOP); - exit (1); - } - else - { - // Service pack check & warnings about critical MS issues - switch (nCurrentOS) - { - case WIN_2000: - if (CurrentOSServicePack < 3) - Warning ("LARGE_IDE_WARNING_2K", NULL); - else - { - DWORD val = 0, size = sizeof(val); - HKEY hkey; - - if (RegOpenKeyExW (HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Services\\Atapi\\Parameters", 0, KEY_READ, &hkey) == ERROR_SUCCESS) - { - if (RegQueryValueExW (hkey, L"EnableBigLba", 0, 0, (LPBYTE) &val, &size) != ERROR_SUCCESS - || val != 1) - { - Warning ("LARGE_IDE_WARNING_2K_REGISTRY", NULL); - } - RegCloseKey (hkey); - } - } - break; - - case WIN_XP: - if (CurrentOSServicePack < 1) - { - HKEY k; - // PE environment does not report version of SP - if (RegOpenKeyExW (HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Control\\minint", 0, KEY_READ, &k) != ERROR_SUCCESS) - Warning ("LARGE_IDE_WARNING_XP", NULL); - else - RegCloseKey (k); - } - break; - } - } - - /* Get the attributes for the standard dialog class */ - if ((GetClassInfoW (hInst, WINDOWS_DIALOG_CLASS, &wc)) == 0) - { - handleWin32Error (NULL, SRC_POS); - AbortProcess ("INIT_REGISTER"); - } - -#ifndef SETUP - wc.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_TRUECRYPT_ICON)); -#else -#include "../setup/resource.h" - wc.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_SETUP)); -#endif - wc.lpszClassName = TC_DLG_CLASS; - wc.lpfnWndProc = &CustomDlgProc; - wc.hCursor = LoadCursor (NULL, IDC_ARROW); - wc.cbWndExtra = DLGWINDOWEXTRA; - - hDlgClass = RegisterClassW (&wc); - if (hDlgClass == 0) - { - handleWin32Error (NULL, SRC_POS); - AbortProcess ("INIT_REGISTER"); - } - - wc.lpszClassName = TC_SPLASH_CLASS; - wc.lpfnWndProc = &SplashDlgProc; - wc.hCursor = LoadCursor (NULL, IDC_ARROW); - wc.cbWndExtra = DLGWINDOWEXTRA; - - hSplashClass = RegisterClassW (&wc); - if (hSplashClass == 0) - { - handleWin32Error (NULL, SRC_POS); - AbortProcess ("INIT_REGISTER"); - } - - // DPI and GUI aspect ratio - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_AUXILIARY_DLG), NULL, - (DLGPROC) AuxiliaryDlgProc, (LPARAM) 1); - - InitHelpFileName (); - -#ifndef SETUP - if (!EncryptionThreadPoolStart (ReadEncryptionThreadPoolFreeCpuCountLimit())) - { - handleWin32Error (NULL, SRC_POS); - FREE_DLL (hRichEditDll); - FREE_DLL (hComctl32Dll); - FREE_DLL (hSetupDll); - FREE_DLL (hShlwapiDll); - FREE_DLL (hProfApiDll); - FREE_DLL (hUsp10Dll); - FREE_DLL (hCryptSpDll); - FREE_DLL (hUXThemeDll); - FREE_DLL (hUserenvDll); - FREE_DLL (hRsaenhDll); - FREE_DLL (himm32dll); - FREE_DLL (hMSCTFdll); - FREE_DLL (hfltlibdll); - FREE_DLL (hframedyndll); - FREE_DLL (hpsapidll); - FREE_DLL (hsecur32dll); - FREE_DLL (hnetapi32dll); - FREE_DLL (hauthzdll); - FREE_DLL (hxmllitedll); - FREE_DLL (hmprdll); - FREE_DLL (hsppdll); - FREE_DLL (vssapidll); - FREE_DLL (hvsstracedll); - FREE_DLL (hCryptSpDll); - FREE_DLL (hcfgmgr32dll); - FREE_DLL (hdevobjdll); - FREE_DLL (hpowrprofdll); - FREE_DLL (hsspiclidll); - FREE_DLL (hcryptbasedll); - FREE_DLL (hdwmapidll); - FREE_DLL (hmsasn1dll); - FREE_DLL (hcrypt32dll); - FREE_DLL (hbcryptdll); - FREE_DLL (hbcryptprimitivesdll); - FREE_DLL (hMsls31); - FREE_DLL (hntmartadll); - FREE_DLL (hwinscarddll); - exit (1); - } -#endif -} - -void FinalizeApp (void) -{ - FREE_DLL (hRichEditDll); - FREE_DLL (hComctl32Dll); - FREE_DLL (hSetupDll); - FREE_DLL (hShlwapiDll); - FREE_DLL (hProfApiDll); - FREE_DLL (hUsp10Dll); - FREE_DLL (hCryptSpDll); - FREE_DLL (hUXThemeDll); - FREE_DLL (hUserenvDll); - FREE_DLL (hRsaenhDll); - FREE_DLL (himm32dll); - FREE_DLL (hMSCTFdll); - FREE_DLL (hfltlibdll); - FREE_DLL (hframedyndll); - FREE_DLL (hpsapidll); - FREE_DLL (hsecur32dll); - FREE_DLL (hnetapi32dll); - FREE_DLL (hauthzdll); - FREE_DLL (hxmllitedll); - FREE_DLL (hmprdll); - FREE_DLL (hsppdll); - FREE_DLL (vssapidll); - FREE_DLL (hvsstracedll); - FREE_DLL (hCryptSpDll); - FREE_DLL (hcfgmgr32dll); - FREE_DLL (hdevobjdll); - FREE_DLL (hpowrprofdll); - FREE_DLL (hsspiclidll); - FREE_DLL (hcryptbasedll); - FREE_DLL (hdwmapidll); - FREE_DLL (hmsasn1dll); - FREE_DLL (hcrypt32dll); - FREE_DLL (hbcryptdll); - FREE_DLL (hbcryptprimitivesdll); - FREE_DLL (hMsls31); - FREE_DLL (hntmartadll); - FREE_DLL (hwinscarddll); -} - -void InitHelpFileName (void) -{ - wchar_t *lpszTmp; - - GetModuleFileNameW (NULL, szHelpFile, ARRAYSIZE (szHelpFile)); - lpszTmp = wcsrchr (szHelpFile, L'\\'); - if (lpszTmp) - { - wchar_t szTemp[TC_MAX_PATH]; - - ++lpszTmp; - *lpszTmp = 0; // add null terminating character to prepare for append operations - - // Primary file name - if (strcmp (GetPreferredLangId(), "en") == 0 - || strlen(GetPreferredLangId()) == 0) - { - StringCbCatW (szHelpFile, sizeof(szHelpFile), L"VeraCrypt User Guide.pdf"); - } - else - { - StringCbPrintfW (szTemp, sizeof(szTemp), L"VeraCrypt User Guide.%S.pdf", GetPreferredLangId()); - StringCbCatW (szHelpFile, sizeof(szHelpFile), szTemp); - } - - // Secondary file name (used when localized documentation is not found). - GetModuleFileNameW (NULL, szHelpFile2, ARRAYSIZE (szHelpFile2)); - lpszTmp = wcsrchr (szHelpFile2, L'\\'); - if (lpszTmp) - { - ++lpszTmp; - *lpszTmp = 0; - StringCbCatW (szHelpFile2, sizeof(szHelpFile2), L"VeraCrypt User Guide.pdf"); - } - } -} - -BOOL OpenDevice (const wchar_t *lpszPath, OPEN_TEST_STRUCT *driver, BOOL detectFilesystem, BOOL matchVolumeID, const BYTE* pbVolumeID) -{ - DWORD dwResult; - BOOL bResult; - wchar_t wszFileName[TC_MAX_PATH]; - - StringCbCopyW (wszFileName, sizeof(wszFileName), lpszPath); - - memset (driver, 0, sizeof (OPEN_TEST_STRUCT)); - memcpy (driver->wszFileName, wszFileName, sizeof (wszFileName)); - - driver->bDetectTCBootLoader = FALSE; - driver->DetectFilesystem = detectFilesystem; - driver->bMatchVolumeID = matchVolumeID; - if (matchVolumeID && pbVolumeID) - memcpy (driver->volumeID, pbVolumeID, VOLUME_ID_SIZE); - - bResult = DeviceIoControl (hDriver, TC_IOCTL_OPEN_TEST, - driver, sizeof (OPEN_TEST_STRUCT), - driver, sizeof (OPEN_TEST_STRUCT), - &dwResult, NULL); - - // check variable driver - if ( bResult - && ( (driver->bDetectTCBootLoader != TRUE && driver->bDetectTCBootLoader != FALSE) || - (driver->TCBootLoaderDetected != TRUE && driver->TCBootLoaderDetected != FALSE) || - (driver->DetectFilesystem != TRUE && driver->DetectFilesystem != FALSE) || - (driver->FilesystemDetected != TRUE && driver->FilesystemDetected != FALSE) || - (wcscmp (wszFileName, driver->wszFileName)) - ) - ) - { - return FALSE; - } - - if (bResult == FALSE) - { - dwResult = GetLastError (); - - if (dwResult == ERROR_SHARING_VIOLATION || dwResult == ERROR_NOT_READY) - { - driver->TCBootLoaderDetected = FALSE; - driver->FilesystemDetected = FALSE; - driver->VolumeIDMatched = FALSE; - return TRUE; - } - else - return FALSE; - } - - return TRUE; -} - - -// Tells the driver that it's running in portable mode -void NotifyDriverOfPortableMode (void) -{ - if (hDriver != INVALID_HANDLE_VALUE) - { - DWORD dwResult; - - DeviceIoControl (hDriver, TC_IOCTL_SET_PORTABLE_MODE_STATUS, NULL, 0, NULL, 0, &dwResult, NULL); - } -} - - -BOOL GetDriveLabel (int driveNo, wchar_t *label, int labelSize) -{ - DWORD fileSystemFlags; - wchar_t root[] = { L'A' + (wchar_t) driveNo, L':', L'\\', 0 }; - - return GetVolumeInformationW (root, label, labelSize / 2, NULL, NULL, &fileSystemFlags, NULL, 0); -} - - -/* Stores the device path of the system partition in SysPartitionDevicePath and the device path of the system drive -in SysDriveDevicePath. -IMPORTANT: As this may take a very long time if called for the first time, it should be called only before performing - a dangerous operation (such as header backup restore or formatting a supposedly non-system device) never - at WM_INITDIALOG or any other GUI events -- instead call IsSystemDevicePath (path, hwndDlg, FALSE) for - very fast preliminary GUI checks; also note that right after the "Select Device" dialog exits with an OK - return code, you can use the global flags bSysPartitionSelected and bSysDriveSelected to see if the user - selected the system partition/device. -After this function completes successfully, the results are cached for the rest of the session and repeated -executions complete very fast. Returns TRUE if successful (otherwise FALSE). */ -BOOL GetSysDevicePaths (HWND hwndDlg) -{ - if (!bCachedSysDevicePathsValid - || wcslen (SysPartitionDevicePath) <= 1 - || wcslen (SysDriveDevicePath) <= 1) - { - foreach (const HostDevice &device, GetAvailableHostDevices (false, true)) - { - if (device.ContainsSystem) - StringCchCopyW (device.IsPartition ? SysPartitionDevicePath : SysDriveDevicePath, TC_MAX_PATH, device.Path.c_str()); - } - - if (IsOSAtLeast (WIN_7)) - { - // Find extra boot partition - foreach (const HostDevice &drive, GetAvailableHostDevices (false, false)) - { - if (drive.ContainsSystem) - { - foreach (const HostDevice &sysDrivePartition, drive.Partitions) - { - if (sysDrivePartition.Bootable) - { - if (sysDrivePartition.Size <= TC_MAX_EXTRA_BOOT_PARTITION_SIZE) - ExtraBootPartitionDevicePath = sysDrivePartition.Path; - break; - } - } - break; - } - } - } - - bCachedSysDevicePathsValid = 1; - } - - return (bCachedSysDevicePathsValid - && wcslen (SysPartitionDevicePath) > 1 - && wcslen (SysDriveDevicePath) > 1); -} - -/* Determines whether the device path is the path of the system partition or of the system drive (or neither). -If bReliableRequired is TRUE, very fast execution is guaranteed, but the results cannot be relied upon. -If it's FALSE and the function is called for the first time, execution may take up to one minute but the -results are reliable. -IMPORTANT: As the execution may take a very long time if called for the first time with bReliableRequired set - to TRUE, it should be called with bReliableRequired set to TRUE only before performing a dangerous - operation (such as header backup restore or formatting a supposedly non-system device) never at - WM_INITDIALOG or any other GUI events (use IsSystemDevicePath(path, hwndDlg, FALSE) for fast - preliminary GUI checks; also note that right after the "Select Device" dialog exits with an OK - return code, you can use the global flags bSysPartitionSelected and bSysDriveSelected to see if the - user selected the system partition/device). -After this function completes successfully, the results are cached for the rest of the session, bReliableRequired -is ignored (TRUE implied), repeated executions complete very fast, and the results are always reliable. -Return codes: -1 - it is the system partition path (e.g. \Device\Harddisk0\Partition1) -2 - it is the system drive path (e.g. \Device\Harddisk0\Partition0) -3 - it is the extra boot partition path -0 - it's not the system partition/drive path --1 - the result can't be determined, isn't reliable, or there was an error. */ -int IsSystemDevicePath (const wchar_t *path, HWND hwndDlg, BOOL bReliableRequired) -{ - if (!bCachedSysDevicePathsValid - && bReliableRequired) - { - if (!GetSysDevicePaths (hwndDlg)) - return -1; - } - - if (wcslen (SysPartitionDevicePath) <= 1 || wcslen (SysDriveDevicePath) <= 1) - return -1; - - if (!path) - return -1; - - if (wcsncmp (path, SysPartitionDevicePath, max (wcslen(path), wcslen(SysPartitionDevicePath))) == 0) - return 1; - else if (wcsncmp (path, SysDriveDevicePath, max (wcslen(path), wcslen(SysDriveDevicePath))) == 0) - return 2; - else if (ExtraBootPartitionDevicePath == path) - return 3; - - return 0; -} - - -/* Determines whether the path points to a non-system partition on the system drive. -IMPORTANT: As this may take a very long time if called for the first time, it should be called - only before performing a dangerous operation, never at WM_INITDIALOG or any other GUI events. -Return codes: -0 - it isn't a non-system partition on the system drive -1 - it's a non-system partition on the system drive --1 - the result can't be determined, isn't reliable, or there was an error. */ -int IsNonSysPartitionOnSysDrive (const wchar_t *path) -{ - wchar_t tmpPath [TC_MAX_PATH + 1]; - int pos; - - if (!GetSysDevicePaths (MainDlg)) - return -1; - - if (wcslen (SysPartitionDevicePath) <= 1 || wcslen (SysDriveDevicePath) <= 1) - return -1; - - if (wcsncmp (path, SysPartitionDevicePath, max (wcslen(path), wcslen(SysPartitionDevicePath))) == 0 - || wcsncmp (path, SysDriveDevicePath, max (wcslen(path), wcslen(SysDriveDevicePath))) == 0) - { - // It is the system partition/drive path (it isn't a non-system partition) - return 0; - } - - memset (tmpPath, 0, sizeof (tmpPath)); - wcsncpy (tmpPath, path, ARRAYSIZE (tmpPath) - 1); - - - pos = (int) FindString ((const char*) tmpPath, (const char*) L"Partition", (int) wcslen (tmpPath) * 2, (int) wcslen (L"Partition") * 2, 0); - - if (pos < 0) - return -1; - - pos /= 2; - pos += (int) strlen ("Partition"); - - if (pos + 1 > ARRAYSIZE (tmpPath) - 1) - return -1; - - tmpPath [pos] = L'0'; - tmpPath [pos + 1] = 0; - - if (wcsncmp (tmpPath, SysDriveDevicePath, max (wcslen(tmpPath), wcslen(SysDriveDevicePath))) == 0) - { - // It is a non-system partition on the system drive - return 1; - } - else - { - // The partition is not on the system drive - return 0; - } -} - - -wstring GetSysEncryptionPretestInfo2String (void) -{ - // This huge string is divided into smaller portions to make it easier for translators to - // re-translate it when a minor modification is made to it (the whole huge string will not be - // reverted to English, so they will have to translate only a small portion of it). - return (wstring (L"\n") - + GetString ("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_1") - + GetString ("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_2") - + GetString ("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_3") - + GetString ("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_4")); -} - - -wstring GetRescueDiskHelpString (void) -{ - // This huge string is divided into smaller portions to make it easier for translators to - // re-translate it when a minor modification is made to it (the whole huge string will not be - // reverted to English, so they will have to translate only a small portion of it). - return (wstring ( - GetString ("RESCUE_DISK_HELP_PORTION_1")) - + GetString ("RESCUE_DISK_HELP_PORTION_2") - + GetString ("RESCUE_DISK_HELP_PORTION_3") - + GetString ("RESCUE_DISK_HELP_PORTION_4") - + GetString ("RESCUE_DISK_HELP_PORTION_5") - + GetString ("RESCUE_DISK_HELP_PORTION_6") - + GetString ("RESCUE_DISK_HELP_PORTION_7") - + GetString ("RESCUE_DISK_HELP_PORTION_8") - + GetString ("RESCUE_DISK_HELP_PORTION_9")); -} - - -wstring GetDecoyOsInstructionsString (void) -{ - // This huge string is divided into smaller portions to make it easier for translators to - // re-translate it when a minor modification is made to it (the whole huge string will not be - // reverted to English, so they will have to translate only a small portion of it). - return (wstring ( - GetString ("DECOY_OS_INSTRUCTIONS_PORTION_1")) - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_2") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_3") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_4") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_5") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_6") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_7") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_8") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_9") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_10") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_11") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_12") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_13") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_14") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_15") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_16") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_17") - + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_18")); -} - - -INT_PTR TextInfoDialogBox (int nID) -{ - return DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TEXT_INFO_DIALOG_BOX_DLG), MainDlg, (DLGPROC) TextInfoDialogBoxDlgProc, (LPARAM) nID); -} - -BOOL CALLBACK TextInfoDialogBoxDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - static int nID = 0; - - switch (msg) - { - case WM_INITDIALOG: - { - nID = (int) lParam; - - // Left margin for rich edit text field - SendMessage (GetDlgItem (hwndDlg, IDC_INFO_BOX_TEXT), EM_SETMARGINS, (WPARAM) EC_LEFTMARGIN, (LPARAM) CompensateXDPI (4)); - - ShowWindow(GetDlgItem(hwndDlg, IDC_PRINT), SW_HIDE); - - switch (nID) - { - case TC_TBXID_LEGAL_NOTICES: - LocalizeDialog (hwndDlg, "LEGAL_NOTICES_DLG_TITLE"); - break; - - case TC_TBXID_SYS_ENCRYPTION_PRETEST: - LocalizeDialog (hwndDlg, NULL); - ShowWindow(GetDlgItem(hwndDlg, IDC_PRINT), SW_SHOW); - break; - - case TC_TBXID_SYS_ENC_RESCUE_DISK: - LocalizeDialog (hwndDlg, NULL); - ShowWindow(GetDlgItem(hwndDlg, IDC_PRINT), SW_SHOW); - break; - - case TC_TBXID_DECOY_OS_INSTRUCTIONS: - LocalizeDialog (hwndDlg, NULL); - ShowWindow(GetDlgItem(hwndDlg, IDC_PRINT), SW_SHOW); - break; - - case TC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS: - LocalizeDialog (hwndDlg, NULL); - ShowWindow(GetDlgItem(hwndDlg, IDC_PRINT), SW_SHOW); - break; - } - - SendMessage (hwndDlg, TC_APPMSG_LOAD_TEXT_BOX_CONTENT, 0, 0); - } - return 0; - - case WM_COMMAND: - if (lw == IDOK || lw == IDCANCEL) - { - NormalCursor (); - EndDialog (hwndDlg, 0); - return 1; - } - - if (lw == IDC_PRINT) - { - switch (nID) - { - case TC_TBXID_SYS_ENCRYPTION_PRETEST: - PrintHardCopyTextUTF16 ((wchar_t *) GetSysEncryptionPretestInfo2String ().c_str(), L"Pre-Boot Troubleshooting", GetSysEncryptionPretestInfo2String ().length () * 2); - break; - - case TC_TBXID_SYS_ENC_RESCUE_DISK: - PrintHardCopyTextUTF16 ((wchar_t *) GetRescueDiskHelpString ().c_str(), L"VeraCrypt Rescue Disk Help", GetRescueDiskHelpString ().length () * 2); - break; - - case TC_TBXID_DECOY_OS_INSTRUCTIONS: - PrintHardCopyTextUTF16 ((wchar_t *) GetDecoyOsInstructionsString ().c_str(), L"How to Create Decoy OS", GetDecoyOsInstructionsString ().length () * 2); - break; - - case TC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS: - PrintHardCopyTextUTF16 (GetString ("EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS"), L"How to Remove Extra Boot Partition", wcslen (GetString ("EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS")) * 2); - break; - } - return 1; - } - - return 0; - - case TC_APPMSG_LOAD_TEXT_BOX_CONTENT: - { - char *r = NULL; - - switch (nID) - { - case TC_TBXID_LEGAL_NOTICES: - LocalizeDialog (hwndDlg, "LEGAL_NOTICES_DLG_TITLE"); - r = GetLegalNotices (); - if (r != NULL) - { - SETTEXTEX TextInfo = {0}; - - TextInfo.flags = ST_SELECTION; - TextInfo.codepage = CP_ACP; - - SendMessage(GetDlgItem (hwndDlg, IDC_INFO_BOX_TEXT), EM_SETTEXTEX, (WPARAM)&TextInfo, (LPARAM)r); - free (r); - } - break; - - case TC_TBXID_SYS_ENCRYPTION_PRETEST: - LocalizeDialog (hwndDlg, NULL); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_INFO_BOX_TEXT), (wchar_t *) GetSysEncryptionPretestInfo2String ().c_str()); - break; - - case TC_TBXID_SYS_ENC_RESCUE_DISK: - LocalizeDialog (hwndDlg, NULL); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_INFO_BOX_TEXT), (wchar_t *) GetRescueDiskHelpString ().c_str()); - break; - - case TC_TBXID_DECOY_OS_INSTRUCTIONS: - LocalizeDialog (hwndDlg, NULL); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_INFO_BOX_TEXT), (wchar_t *) GetDecoyOsInstructionsString ().c_str()); - break; - - case TC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS: - LocalizeDialog (hwndDlg, NULL); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_INFO_BOX_TEXT), GetString ("EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS")); - break; - } - } - return 1; - - case WM_CLOSE: - NormalCursor (); - EndDialog (hwndDlg, 0); - return 1; - } - - return 0; -} - - -char * GetLegalNotices () -{ - static char *resource; - static DWORD size; - char *buf = NULL; - - if (resource == NULL) - resource = (char *) MapResource (L"Text", IDR_LICENSE, &size); - - if (resource != NULL) - { - buf = (char *) malloc (size + 1); - if (buf != NULL) - { - memcpy (buf, resource, size); - buf[size] = 0; - } - } - - return buf; -} - - -BOOL CALLBACK RawDevicesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - static wchar_t *lpszFileName; // This is actually a pointer to a GLOBAL array - static vector devices; - static map itemToDeviceMap; - - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - LVCOLUMNW LvCol; - HWND hList = GetDlgItem (hwndDlg, IDC_DEVICELIST); - RawDevicesDlgParam* pDlgParam = (RawDevicesDlgParam *) lParam; - - LocalizeDialog (hwndDlg, "IDD_RAWDEVICES_DLG"); - - SendMessage (hList,LVM_SETEXTENDEDLISTVIEWSTYLE,0, - LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_TWOCLICKACTIVATE|LVS_EX_LABELTIP - ); - - memset (&LvCol,0,sizeof(LvCol)); - LvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; - LvCol.pszText = GetString ("DEVICE"); - LvCol.cx = CompensateXDPI (186); - LvCol.fmt = LVCFMT_LEFT; - SendMessage (hList,LVM_INSERTCOLUMNW,0,(LPARAM)&LvCol); - - LvCol.pszText = GetString ("DRIVE"); - LvCol.cx = CompensateXDPI (38); - LvCol.fmt = LVCFMT_LEFT; - SendMessage (hList,LVM_INSERTCOLUMNW,1,(LPARAM)&LvCol); - - LvCol.pszText = GetString ("SIZE"); - LvCol.cx = CompensateXDPI (64); - LvCol.fmt = LVCFMT_RIGHT; - SendMessage (hList,LVM_INSERTCOLUMNW,2,(LPARAM)&LvCol); - - LvCol.pszText = GetString ("LABEL"); - LvCol.cx = CompensateXDPI (128); - LvCol.fmt = LVCFMT_LEFT; - SendMessage (hList,LVM_INSERTCOLUMNW,3,(LPARAM)&LvCol); - - devices.clear(); - itemToDeviceMap.clear(); - - if (pDlgParam->devices.empty()) - { - WaitCursor(); - devices = GetAvailableHostDevices (false, true, false); - NormalCursor(); - } - else - devices = pDlgParam->devices; - - if (devices.empty()) - { - MessageBoxW (hwndDlg, GetString ("RAWDEVICES"), lpszTitle, ICON_HAND); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - int line = 1; - LVITEM item; - memset (&item, 0, sizeof (item)); - item.mask = LVIF_TEXT; - - foreach (const HostDevice &device, devices) - { - item.iSubItem = 1; - - if (device.ContainsSystem) - { - if (device.IsPartition) - StringCbCopyW (SysPartitionDevicePath, sizeof (SysPartitionDevicePath), device.Path.c_str()); - else - StringCbCopyW (SysDriveDevicePath, sizeof (SysDriveDevicePath), device.Path.c_str()); - } - - // Path - if (!device.IsPartition || device.DynamicVolume) - { - if (!device.Floppy && (device.Size == 0) - && (device.IsPartition || device.Partitions.empty() || device.Partitions[0].Size == 0) - ) - continue; - - if (line > 1) - { - ListItemAdd (hList, item.iItem, L""); - item.iItem = line++; - } - - if (device.Floppy || device.DynamicVolume) - { - ListItemAdd (hList, item.iItem, (wchar_t *) device.Path.c_str()); - } - else - { - wchar_t s[1024]; - if (device.Removable) - StringCbPrintfW (s, sizeof(s), L"%s %d", GetString ("REMOVABLE_DISK"), device.SystemNumber); - else - StringCbPrintfW (s, sizeof(s), L"%s %d", GetString ("HARDDISK"), device.SystemNumber); - - if (!device.Partitions.empty()) - StringCbCatW (s, sizeof(s), L":"); - - ListItemAdd (hList, item.iItem, s); - } - } - else - { - ListItemAdd (hList, item.iItem, (wchar_t *) device.Path.c_str()); - } - - itemToDeviceMap[item.iItem] = device; - - // Size - if (device.Size != 0) - { - wchar_t size[100] = { 0 }; - GetSizeString (device.Size, size, sizeof(size)); - ListSubItemSet (hList, item.iItem, 2, size); - } - - // Mount point - if (!device.MountPoint.empty()) - ListSubItemSet (hList, item.iItem, 1, (wchar_t *) device.MountPoint.c_str()); - - // Label - if (!device.Name.empty()) - ListSubItemSet (hList, item.iItem, 3, (wchar_t *) device.Name.c_str()); -#ifdef TCMOUNT - else - { - bool useInExplorer = false; - wstring favoriteLabel = GetFavoriteVolumeLabel (device.Path, useInExplorer); - if (!favoriteLabel.empty()) - ListSubItemSet (hList, item.iItem, 3, (wchar_t *) favoriteLabel.c_str()); - } -#endif - - item.iItem = line++; - } - - SendMessageW(hList, LVM_SETCOLUMNWIDTH, 0, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); - SendMessageW(hList, LVM_SETCOLUMNWIDTH, 1, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); - SendMessageW(hList, LVM_SETCOLUMNWIDTH, 2, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); - SendMessageW(hList, LVM_SETCOLUMNWIDTH, 3, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); - - lpszFileName = pDlgParam->pszFileName; - -#ifdef VOLFORMAT - EnableWindow (GetDlgItem (hwndDlg, IDOK), FALSE); -#endif - return 1; - } - - case WM_COMMAND: - case WM_NOTIFY: - // catch non-device line selected - if (msg == WM_NOTIFY && ((LPNMHDR) lParam)->code == LVN_ITEMCHANGED && (((LPNMLISTVIEW) lParam)->uNewState & LVIS_FOCUSED )) - { - BOOL bEnableOkButton = FALSE; - LVITEM LvItem; - memset(&LvItem,0,sizeof(LvItem)); - LvItem.mask = LVIF_TEXT | LVIF_PARAM; - LvItem.iItem = ((LPNMLISTVIEW) lParam)->iItem; - LvItem.pszText = lpszFileName; - LvItem.cchTextMax = TC_MAX_PATH; - - lpszFileName[0] = 0; - SendMessage (GetDlgItem (hwndDlg, IDC_DEVICELIST), LVM_GETITEM, LvItem.iItem, (LPARAM) &LvItem); - if (lpszFileName[0] != 0 && lpszFileName[0] != ' ') - { - bEnableOkButton = TRUE; -#ifdef VOLFORMAT - if ( bInPlaceEncNonSysResumed && (WizardMode == WIZARD_MODE_NONSYS_DEVICE) - && LvItem.iItem != -1 && itemToDeviceMap.find (LvItem.iItem) != itemToDeviceMap.end() - ) - { - const HostDevice selectedDevice = itemToDeviceMap[LvItem.iItem]; - if (selectedDevice.ContainsSystem) - { - bEnableOkButton = FALSE; - } - } -#endif - } - EnableWindow (GetDlgItem ((HWND) hwndDlg, IDOK), bEnableOkButton); - - return 1; - } - - if (msg == WM_COMMAND && lw == IDOK || msg == WM_NOTIFY && ((NMHDR *)lParam)->code == LVN_ITEMACTIVATE) - { - int selectedItem = ListView_GetSelectionMark (GetDlgItem (hwndDlg, IDC_DEVICELIST)); - - if (selectedItem == -1 || itemToDeviceMap.find (selectedItem) == itemToDeviceMap.end()) - return 1; // non-device line selected - - const HostDevice selectedDevice = itemToDeviceMap[selectedItem]; - StringCchCopyW (lpszFileName, TC_MAX_PATH, selectedDevice.Path.c_str()); - -#ifdef VOLFORMAT - if (selectedDevice.ContainsSystem && selectedDevice.IsPartition) - { - if (WizardMode != WIZARD_MODE_SYS_DEVICE) - { - if (bInPlaceEncNonSysResumed && (WizardMode == WIZARD_MODE_NONSYS_DEVICE)) - { - // disable selection - return 1; - } - - if (AskYesNo ("CONFIRM_SYSTEM_ENCRYPTION_MODE", hwndDlg) == IDNO) - { - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - bSysPartitionSelected = TRUE; - bSysDriveSelected = FALSE; - lpszFileName[0] = 0; - SwitchWizardToSysEncMode (); - - NormalCursor (); - EndDialog (hwndDlg, IDOK); - return 1; - } - else - { - // This should never be the case because the Select Device dialog is not available in this wizard mode - bSysPartitionSelected = TRUE; - bSysDriveSelected = FALSE; - lpszFileName[0] = 0; - SwitchWizardToSysEncMode (); - NormalCursor (); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - } - - if (!(selectedDevice.ContainsSystem && !selectedDevice.IsPartition)) - { - if (bWarnDeviceFormatAdvanced - && !bHiddenVolDirect - && AskWarnNoYes("FORMAT_DEVICE_FOR_ADVANCED_ONLY", hwndDlg) == IDNO) - { - if (AskNoYes("CONFIRM_CHANGE_WIZARD_MODE_TO_FILE_CONTAINER", hwndDlg) == IDYES) - { - SwitchWizardToFileContainerMode (); - } - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - if (!bHiddenVolDirect) - bWarnDeviceFormatAdvanced = FALSE; - } - -#else // #ifdef VOLFORMAT - - bSysPartitionSelected = (selectedDevice.ContainsSystem && selectedDevice.IsPartition); - bSysDriveSelected = FALSE; - -#endif // #ifdef VOLFORMAT - - if (!selectedDevice.IsPartition && !selectedDevice.Floppy) - { - // Whole device selected - -#ifdef VOLFORMAT - if (selectedDevice.ContainsSystem && !selectedDevice.IsPartition) - { - if (WizardMode != WIZARD_MODE_SYS_DEVICE) - { - if (bInPlaceEncNonSysResumed && (WizardMode == WIZARD_MODE_NONSYS_DEVICE)) - { - // disable selection - return 1; - } - - if (AskYesNo ("CONFIRM_SYSTEM_ENCRYPTION_MODE", hwndDlg) == IDNO) - { - NormalCursor (); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - bSysDriveSelected = TRUE; - bSysPartitionSelected = FALSE; - lpszFileName[0] = 0; - SwitchWizardToSysEncMode (); - - NormalCursor (); - EndDialog (hwndDlg, IDOK); - return 1; - } - else - { - // This should never be the case because the Select Device dialog is not available in this wizard mode - bSysDriveSelected = TRUE; - bSysPartitionSelected = FALSE; - lpszFileName[0] = 0; - SwitchWizardToSysEncMode (); - NormalCursor (); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - } - - // Disallow format if the device contains partitions, but not if the partition is virtual or system - if (!selectedDevice.IsVirtualPartition - && !bHiddenVolDirect) - { - if (!selectedDevice.Partitions.empty()) - { - EnableWindow (GetDlgItem (hwndDlg, IDOK), FALSE); - Error ("DEVICE_PARTITIONS_ERR_W_INPLACE_ENC_NOTE", hwndDlg); - return 1; - } - - if (AskWarnNoYes ("WHOLE_NONSYS_DEVICE_ENC_CONFIRM", hwndDlg) == IDNO) - return 1; - } -#else // #ifdef VOLFORMAT - - bSysDriveSelected = (selectedDevice.ContainsSystem && !selectedDevice.IsPartition); - bSysPartitionSelected = FALSE; - -#endif // #ifdef VOLFORMAT - } - else - bSysDriveSelected = FALSE; - -#ifdef VOLFORMAT - bRemovableHostDevice = selectedDevice.Removable; -#endif - NormalCursor (); - EndDialog (hwndDlg, IDOK); - return 1; - } - - if ((msg == WM_COMMAND) && (lw == IDCANCEL)) - { - NormalCursor (); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - return 0; - } - return 0; -} - - -BOOL DoDriverInstall (HWND hwndDlg) -{ -#ifdef SETUP - if (SystemEncryptionUpdate) - return TRUE; -#endif - - SC_HANDLE hManager, hService = NULL; - BOOL bOK = FALSE, bRet; - - hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (hManager == NULL) - goto error; - -#ifdef SETUP - StatusMessage (hwndDlg, "INSTALLING_DRIVER"); -#endif - - hService = CreateService (hManager, L"veracrypt", L"veracrypt", - SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_SYSTEM_START, SERVICE_ERROR_NORMAL, - L"System32\\drivers\\veracrypt.sys", - NULL, NULL, NULL, NULL, NULL); - - if (hService == NULL) - goto error; - else - CloseServiceHandle (hService); - - hService = OpenService (hManager, L"veracrypt", SERVICE_ALL_ACCESS); - if (hService == NULL) - goto error; - -#ifdef SETUP - StatusMessage (hwndDlg, "STARTING_DRIVER"); -#endif - - bRet = StartService (hService, 0, NULL); - if (bRet == FALSE) - goto error; - - bOK = TRUE; - -error: - if (bOK == FALSE && GetLastError () != ERROR_SERVICE_ALREADY_RUNNING) - { - handleWin32Error (hwndDlg, SRC_POS); - MessageBoxW (hwndDlg, GetString ("DRIVER_INSTALL_FAILED"), lpszTitle, MB_ICONHAND); - } - else - bOK = TRUE; - - if (hService != NULL) - CloseServiceHandle (hService); - - if (hManager != NULL) - CloseServiceHandle (hManager); - - return bOK; -} - - -// Install and start driver service and mark it for removal (non-install mode) -static int DriverLoad () -{ - HANDLE file; - WIN32_FIND_DATA find; - SC_HANDLE hManager, hService = NULL; - wchar_t driverPath[TC_MAX_PATH*2]; - BOOL res; - wchar_t *tmp; - DWORD startType; - - if (ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", L"Start", &startType) && startType == SERVICE_BOOT_START) - return ERR_PARAMETER_INCORRECT; - - GetModuleFileName (NULL, driverPath, ARRAYSIZE (driverPath)); - tmp = wcsrchr (driverPath, L'\\'); - if (!tmp) - { - driverPath[0] = L'.'; - driverPath[1] = 0; - } - else - *tmp = 0; - - StringCbCatW (driverPath, sizeof(driverPath), !Is64BitOs () ? L"\\veracrypt.sys" : L"\\veracrypt-x64.sys"); - - file = FindFirstFile (driverPath, &find); - - if (file == INVALID_HANDLE_VALUE) - { - MessageBoxW (0, GetString ("DRIVER_NOT_FOUND"), lpszTitle, ICON_HAND); - return ERR_DONT_REPORT; - } - - FindClose (file); - - hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (hManager == NULL) - { - if (GetLastError () == ERROR_ACCESS_DENIED) - { - MessageBoxW (0, GetString ("ADMIN_PRIVILEGES_DRIVER"), lpszTitle, ICON_HAND); - return ERR_DONT_REPORT; - } - - return ERR_OS_ERROR; - } - - hService = OpenService (hManager, L"veracrypt", SERVICE_ALL_ACCESS); - if (hService != NULL) - { - // Remove stale service (driver is not loaded but service exists) - DeleteService (hService); - CloseServiceHandle (hService); - Sleep (500); - } - - hService = CreateService (hManager, L"veracrypt", L"veracrypt", - SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, - driverPath, NULL, NULL, NULL, NULL, NULL); - - if (hService == NULL) - { - CloseServiceHandle (hManager); - return ERR_OS_ERROR; - } - - res = StartService (hService, 0, NULL); - DeleteService (hService); - - CloseServiceHandle (hManager); - CloseServiceHandle (hService); - - return !res ? ERR_OS_ERROR : ERROR_SUCCESS; -} - - -BOOL DriverUnload () -{ - MOUNT_LIST_STRUCT driver; - int refCount; - int volumesMounted; - DWORD dwResult; - BOOL bResult; - - SC_HANDLE hManager, hService = NULL; - BOOL bRet; - SERVICE_STATUS status; - int x; - BOOL driverUnloaded = FALSE; - - if (hDriver == INVALID_HANDLE_VALUE) - return TRUE; - - try - { - if (BootEncryption (NULL).GetStatus().DeviceFilterActive) - return FALSE; - } - catch (...) { } - - // Test for mounted volumes - bResult = DeviceIoControl (hDriver, TC_IOCTL_IS_ANY_VOLUME_MOUNTED, NULL, 0, &volumesMounted, sizeof (volumesMounted), &dwResult, NULL); - - if (!bResult) - { - bResult = DeviceIoControl (hDriver, TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES, NULL, 0, &driver, sizeof (driver), &dwResult, NULL); - if (bResult) - volumesMounted = driver.ulMountedDrives; - } - - if (bResult) - { - if (volumesMounted != 0) - return FALSE; - } - else - return TRUE; - - // Test for any applications attached to driver - refCount = GetDriverRefCount (); - - if (refCount > 1) - return FALSE; - - CloseHandle (hDriver); - hDriver = INVALID_HANDLE_VALUE; - - // Stop driver service - - hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (hManager == NULL) - goto error; - - hService = OpenService (hManager, L"veracrypt", SERVICE_ALL_ACCESS); - if (hService == NULL) - goto error; - - bRet = QueryServiceStatus (hService, &status); - if (bRet != TRUE) - goto error; - - if (status.dwCurrentState != SERVICE_STOPPED) - { - ControlService (hService, SERVICE_CONTROL_STOP, &status); - - for (x = 0; x < 10; x++) - { - bRet = QueryServiceStatus (hService, &status); - if (bRet != TRUE) - goto error; - - if (status.dwCurrentState == SERVICE_STOPPED) - { - driverUnloaded = TRUE; - break; - } - - Sleep (200); - } - } - else - driverUnloaded = TRUE; - -error: - if (hService != NULL) - CloseServiceHandle (hService); - - if (hManager != NULL) - CloseServiceHandle (hManager); - - if (driverUnloaded) - { - hDriver = INVALID_HANDLE_VALUE; - return TRUE; - } - - return FALSE; -} - - -int DriverAttach (void) -{ - /* Try to open a handle to the device driver. It will be closed later. */ - -#ifndef SETUP - - int nLoadRetryCount = 0; -start: - -#endif - - hDriver = CreateFile (WIN32_ROOT_PREFIX, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (hDriver == INVALID_HANDLE_VALUE) - { -#ifndef SETUP - - LoadSysEncSettings (); - - if (!CreateDriverSetupMutex ()) - { - // Another instance is already attempting to install, register or start the driver - - while (!CreateDriverSetupMutex ()) - { - Sleep (100); // Wait until the other instance finishes - } - - // Try to open a handle to the driver again (keep the mutex in case the other instance failed) - goto start; - } - else - { - // No other instance is currently attempting to install, register or start the driver - - if (SystemEncryptionStatus != SYSENC_STATUS_NONE) - { - // This is an inconsistent state. The config file indicates system encryption should be - // active, but the driver is not running. This may happen e.g. when the pretest fails and - // the user selects "Last Known Good Configuration" from the Windows boot menu. - // To fix this, we're going to reinstall the driver, start it, and register it for boot. - - if (DoDriverInstall (NULL)) - { - Sleep (1000); - hDriver = CreateFile (WIN32_ROOT_PREFIX, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - try - { - BootEncryption bootEnc (NULL); - bootEnc.RegisterBootDriver (bootEnc.GetHiddenOSCreationPhase() != TC_HIDDEN_OS_CREATION_PHASE_NONE ? true : false); - } - catch (Exception &e) - { - e.Show (NULL); - } - } - - CloseDriverSetupMutex (); - } - else - { - // Attempt to load the driver (non-install/portable mode) -load: - BOOL res = DriverLoad (); - - CloseDriverSetupMutex (); - - if (res != ERROR_SUCCESS) - return res; - - bPortableModeConfirmed = TRUE; - - if (hDriver != INVALID_HANDLE_VALUE) - CloseHandle (hDriver); - hDriver = CreateFile (WIN32_ROOT_PREFIX, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - } - - if (bPortableModeConfirmed) - NotifyDriverOfPortableMode (); - } - -#endif // #ifndef SETUP - - if (hDriver == INVALID_HANDLE_VALUE) - return ERR_OS_ERROR; - } - - CloseDriverSetupMutex (); - - if (hDriver != INVALID_HANDLE_VALUE) - { - DWORD dwResult; - - BOOL bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVER_VERSION, NULL, 0, &DriverVersion, sizeof (DriverVersion), &dwResult, NULL); - - if (!bResult) - bResult = DeviceIoControl (hDriver, TC_IOCTL_LEGACY_GET_DRIVER_VERSION, NULL, 0, &DriverVersion, sizeof (DriverVersion), &dwResult, NULL); - -#ifndef SETUP // Don't check version during setup to allow removal of another version - if (bResult == FALSE) - { - return ERR_OS_ERROR; - } - else if (DriverVersion != VERSION_NUM) - { - // Unload an incompatbile version of the driver loaded in non-install mode and load the required version - if (IsNonInstallMode () && CreateDriverSetupMutex () && DriverUnload () && nLoadRetryCount++ < 3) - goto load; - - CloseDriverSetupMutex (); - CloseHandle (hDriver); - hDriver = INVALID_HANDLE_VALUE; - return ERR_DRIVER_VERSION; - } -#else - if (!bResult) - DriverVersion = 0; -#endif - } - - return 0; -} - - -void ResetCurrentDirectory () -{ - wchar_t p[MAX_PATH]; - if (!IsNonInstallMode () && SHGetFolderPath (NULL, CSIDL_PROFILE, NULL, 0, p) == ERROR_SUCCESS) - { - SetCurrentDirectory (p); - } - else - { - GetModPath (p, ARRAYSIZE (p)); - SetCurrentDirectory (p); - } -} - - -BOOL BrowseFiles (HWND hwndDlg, char *stringId, wchar_t *lpszFileName, BOOL keepHistory, BOOL saveMode, wchar_t *browseFilter) -{ - return BrowseFilesInDir (hwndDlg, stringId, NULL, lpszFileName, keepHistory, saveMode, browseFilter); -} - - -BOOL BrowseFilesInDir (HWND hwndDlg, char *stringId, wchar_t *initialDir, wchar_t *lpszFileName, BOOL keepHistory, BOOL saveMode, wchar_t *browseFilter, const wchar_t *initialFileName, const wchar_t *defaultExtension) -{ - OPENFILENAMEW ofn; - wchar_t file[TC_MAX_PATH] = { 0 }; - wchar_t filter[1024]; - BOOL status = FALSE; - - CoInitialize (NULL); - - ZeroMemory (&ofn, sizeof (ofn)); - *lpszFileName = 0; - - if (initialDir) - { - ofn.lpstrInitialDir = initialDir; - } - - if (initialFileName) - StringCchCopyW (file, array_capacity (file), initialFileName); - - ofn.lStructSize = sizeof (ofn); - ofn.hwndOwner = hwndDlg; - - StringCbPrintfW (filter, sizeof(filter), L"%ls (*.*)%c*.*%c%ls (*.hc)%c*.hc%c%c", - GetString ("ALL_FILES"), 0, 0, GetString ("TC_VOLUMES"), 0, 0, 0); - ofn.lpstrFilter = browseFilter ? browseFilter : filter; - ofn.nFilterIndex = 1; - ofn.lpstrFile = file; - ofn.nMaxFile = sizeof (file) / sizeof (file[0]); - ofn.lpstrTitle = GetString (stringId); - ofn.lpstrDefExt = defaultExtension; - ofn.Flags = OFN_HIDEREADONLY - | OFN_PATHMUSTEXIST - | (keepHistory ? 0 : OFN_DONTADDTORECENT) - | (saveMode ? OFN_OVERWRITEPROMPT : 0); - - if (!keepHistory) - CleanLastVisitedMRU (); - - SystemFileSelectorCallerThreadId = GetCurrentThreadId(); - SystemFileSelectorCallPending = TRUE; - - if (!saveMode) - { - if (!GetOpenFileNameW (&ofn)) - goto ret; - } - else - { - if (!GetSaveFileNameW (&ofn)) - goto ret; - } - - SystemFileSelectorCallPending = FALSE; - - StringCchCopyW (lpszFileName, MAX_PATH, file); - - if (!keepHistory) - CleanLastVisitedMRU (); - - status = TRUE; - -ret: - SystemFileSelectorCallPending = FALSE; - ResetCurrentDirectory(); - CoUninitialize(); - - return status; -} - - -static wchar_t SelectMultipleFilesPath[131072]; -static int SelectMultipleFilesOffset; - -BOOL SelectMultipleFiles (HWND hwndDlg, const char *stringId, wchar_t *lpszFileName, size_t cbFileName,BOOL keepHistory) -{ - OPENFILENAMEW ofn; - wchar_t filter[1024]; - BOOL status = FALSE; - - CoInitialize (NULL); - - ZeroMemory (&ofn, sizeof (ofn)); - - SelectMultipleFilesPath[0] = 0; - *lpszFileName = 0; - ofn.lStructSize = sizeof (ofn); - ofn.hwndOwner = hwndDlg; - StringCbPrintfW (filter, sizeof(filter), L"%ls (*.*)%c*.*%c%ls (*.hc)%c*.hc%c%c", - GetString ("ALL_FILES"), 0, 0, GetString ("TC_VOLUMES"), 0, 0, 0); - ofn.lpstrFilter = filter; - ofn.nFilterIndex = 1; - ofn.lpstrFile = SelectMultipleFilesPath; - ofn.nMaxFile = 0xffff * 2; // The size must not exceed 0xffff*2 due to a bug in Windows 2000 and XP SP1 - ofn.lpstrTitle = GetString (stringId); - ofn.Flags = OFN_HIDEREADONLY - | OFN_EXPLORER - | OFN_PATHMUSTEXIST - | OFN_ALLOWMULTISELECT - | (keepHistory ? 0 : OFN_DONTADDTORECENT); - - if (!keepHistory) - CleanLastVisitedMRU (); - - SystemFileSelectorCallerThreadId = GetCurrentThreadId(); - SystemFileSelectorCallPending = TRUE; - - if (!GetOpenFileNameW (&ofn)) - goto ret; - - SystemFileSelectorCallPending = FALSE; - - if (SelectMultipleFilesPath[ofn.nFileOffset - 1] != 0) - { - // Single file selected - StringCbCopyW (lpszFileName, cbFileName, SelectMultipleFilesPath); - SelectMultipleFilesOffset = 0; - SecureZeroMemory (SelectMultipleFilesPath, sizeof (SelectMultipleFilesPath)); - } - else - { - // Multiple files selected - SelectMultipleFilesOffset = ofn.nFileOffset; - SelectMultipleFilesNext (lpszFileName, cbFileName); - } - - if (!keepHistory) - CleanLastVisitedMRU (); - - status = TRUE; - -ret: - SystemFileSelectorCallPending = FALSE; - ResetCurrentDirectory(); - CoUninitialize(); - - return status; -} - - -BOOL SelectMultipleFilesNext (wchar_t *lpszFileName, size_t cbFileName) -{ - if (SelectMultipleFilesOffset == 0) - return FALSE; - - StringCbCopyW (lpszFileName, cbFileName,SelectMultipleFilesPath); - lpszFileName[TC_MAX_PATH - 1] = 0; - - if (lpszFileName[wcslen (lpszFileName) - 1] != L'\\') - StringCbCatW (lpszFileName, cbFileName,L"\\"); - - StringCbCatW (lpszFileName, cbFileName,SelectMultipleFilesPath + SelectMultipleFilesOffset); - - SelectMultipleFilesOffset += (int) wcslen (SelectMultipleFilesPath + SelectMultipleFilesOffset) + 1; - if (SelectMultipleFilesPath[SelectMultipleFilesOffset] == 0) - { - SelectMultipleFilesOffset = 0; - SecureZeroMemory (SelectMultipleFilesPath, sizeof (SelectMultipleFilesPath)); - } - - return TRUE; -} - - -static int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lp, LPARAM pData) -{ - switch(uMsg) { - case BFFM_INITIALIZED: - { - /* WParam is TRUE since we are passing a path. - It would be FALSE if we were passing a pidl. */ - SendMessageW (hwnd,BFFM_SETSELECTION,TRUE,(LPARAM)pData); - break; - } - - case BFFM_SELCHANGED: - { - wchar_t szDir[TC_MAX_PATH]; - - /* Set the status window to the currently selected path. */ - if (SHGetPathFromIDList((LPITEMIDLIST) lp ,szDir)) - { - SendMessage (hwnd,BFFM_SETSTATUSTEXT,0,(LPARAM)szDir); - } - break; - } - - default: - break; - } - - return 0; -} - - -BOOL BrowseDirectories (HWND hwndDlg, char *lpszTitle, wchar_t *dirName) -{ - BROWSEINFOW bi; - LPITEMIDLIST pidl; - LPMALLOC pMalloc; - BOOL bOK = FALSE; - - CoInitialize (NULL); - - if (SUCCEEDED (SHGetMalloc (&pMalloc))) - { - ZeroMemory (&bi, sizeof(bi)); - bi.hwndOwner = hwndDlg; - bi.pszDisplayName = 0; - bi.lpszTitle = GetString (lpszTitle); - bi.pidlRoot = 0; - bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT; - bi.lpfn = BrowseCallbackProc; - bi.lParam = (LPARAM)dirName; - - pidl = SHBrowseForFolderW (&bi); - if (pidl != NULL) - { - if (SHGetPathFromIDList(pidl, dirName)) - { - bOK = TRUE; - } - - pMalloc->Free (pidl); - pMalloc->Release(); - } - } - - CoUninitialize(); - - return bOK; -} - - -std::wstring GetWrongPasswordErrorMessage (HWND hwndDlg) -{ - WCHAR szTmp[8192]; - - StringCbPrintfW (szTmp, sizeof(szTmp), GetString (KeyFilesEnable ? "PASSWORD_OR_KEYFILE_WRONG" : "PASSWORD_WRONG")); - if (CheckCapsLock (hwndDlg, TRUE)) - StringCbCatW (szTmp, sizeof(szTmp), GetString ("PASSWORD_WRONG_CAPSLOCK_ON")); - -#ifdef TCMOUNT - wchar_t szDevicePath [TC_MAX_PATH+1] = {0}; - GetWindowText (GetDlgItem (MainDlg, IDC_VOLUME), szDevicePath, ARRAYSIZE (szDevicePath)); - - if (TCBootLoaderOnInactiveSysEncDrive (szDevicePath)) - { - StringCbPrintfW (szTmp, sizeof(szTmp), GetString (KeyFilesEnable ? "PASSWORD_OR_KEYFILE_OR_MODE_WRONG" : "PASSWORD_OR_MODE_WRONG")); - - if (CheckCapsLock (hwndDlg, TRUE)) - StringCbCatW (szTmp, sizeof(szTmp), GetString ("PASSWORD_WRONG_CAPSLOCK_ON")); - - StringCbCatW (szTmp, sizeof(szTmp), GetString ("SYSENC_MOUNT_WITHOUT_PBA_NOTE")); - } -#endif - - wstring msg = szTmp; - -#ifdef TCMOUNT - if (KeyFilesEnable && HiddenFilesPresentInKeyfilePath) - { - msg += GetString ("HIDDEN_FILES_PRESENT_IN_KEYFILE_PATH"); - HiddenFilesPresentInKeyfilePath = FALSE; - } -#endif - - return msg; -} - - -void handleError (HWND hwndDlg, int code, const char* srcPos) -{ - WCHAR szTmp[4096]; - - if (Silent) return; - - switch (code & 0x0000FFFF) - { - case ERR_OS_ERROR: - handleWin32Error (hwndDlg, srcPos); - break; - case ERR_OUTOFMEMORY: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("OUTOFMEMORY"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - - case ERR_PASSWORD_WRONG: - MessageBoxW (hwndDlg, AppendSrcPos (GetWrongPasswordErrorMessage (hwndDlg).c_str(), srcPos).c_str(), lpszTitle, MB_ICONWARNING); - break; - - case ERR_DRIVE_NOT_FOUND: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("NOT_FOUND"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_FILES_OPEN: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("OPENFILES_DRIVER"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_FILES_OPEN_LOCK: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("OPENFILES_LOCK"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_VOL_SIZE_WRONG: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("VOL_SIZE_WRONG"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_COMPRESSION_NOT_SUPPORTED: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("COMPRESSION_NOT_SUPPORTED"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_PASSWORD_CHANGE_VOL_TYPE: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("WRONG_VOL_TYPE"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_VOL_SEEKING: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("VOL_SEEKING"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_CIPHER_INIT_FAILURE: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("ERR_CIPHER_INIT_FAILURE"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_CIPHER_INIT_WEAK_KEY: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("ERR_CIPHER_INIT_WEAK_KEY"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_VOL_ALREADY_MOUNTED: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("VOL_ALREADY_MOUNTED"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_FILE_OPEN_FAILED: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("FILE_OPEN_FAILED"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_VOL_MOUNT_FAILED: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("VOL_MOUNT_FAILED"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_NO_FREE_DRIVES: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("NO_FREE_DRIVES"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - case ERR_ACCESS_DENIED: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("ACCESS_DENIED"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - - case ERR_DRIVER_VERSION: - Error ("DRIVER_VERSION", hwndDlg); - break; - - case ERR_NEW_VERSION_REQUIRED: - MessageBoxW (hwndDlg, AppendSrcPos (GetString ("NEW_VERSION_REQUIRED"), srcPos).c_str(), lpszTitle, ICON_HAND); - break; - - case ERR_SELF_TESTS_FAILED: - Error ("ERR_SELF_TESTS_FAILED", hwndDlg); - break; - - case ERR_VOL_FORMAT_BAD: - Error ("ERR_VOL_FORMAT_BAD", hwndDlg); - break; - - case ERR_ENCRYPTION_NOT_COMPLETED: - Error ("ERR_ENCRYPTION_NOT_COMPLETED", hwndDlg); - break; - - case ERR_NONSYS_INPLACE_ENC_INCOMPLETE: - Error ("ERR_NONSYS_INPLACE_ENC_INCOMPLETE", hwndDlg); - break; - - case ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG: - Error ("ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG", hwndDlg); - break; - - case ERR_PARAMETER_INCORRECT: - Error ("ERR_PARAMETER_INCORRECT", hwndDlg); - break; - - case ERR_USER_ABORT: - case ERR_DONT_REPORT: - // A non-error - break; - - case ERR_UNSUPPORTED_TRUECRYPT_FORMAT: - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("UNSUPPORTED_TRUECRYPT_FORMAT"), (code >> 24), (code >> 16) & 0x000000FF); - MessageBoxW (hwndDlg, AppendSrcPos (szTmp, srcPos).c_str(), lpszTitle, ICON_HAND); - break; - -#ifndef SETUP - case ERR_RAND_INIT_FAILED: - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("INIT_RAND"), SRC_POS, GetLastError ()); - MessageBoxW (hwndDlg, AppendSrcPos (szTmp, srcPos).c_str(), lpszTitle, MB_ICONERROR); - break; - - case ERR_CAPI_INIT_FAILED: - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CAPI_RAND"), SRC_POS, CryptoAPILastError); - MessageBoxW (hwndDlg, AppendSrcPos (szTmp, srcPos).c_str(), lpszTitle, MB_ICONERROR); - break; -#endif - - default: - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("ERR_UNKNOWN"), code); - MessageBoxW (hwndDlg, AppendSrcPos (szTmp, srcPos).c_str(), lpszTitle, ICON_HAND); - } -} - - -BOOL CheckFileStreamWriteErrors (HWND hwndDlg, FILE *file, const wchar_t *fileName) -{ - if (ferror (file)) - { - wchar_t s[TC_MAX_PATH]; - StringCbPrintfW (s, sizeof (s), GetString ("CANNOT_WRITE_FILE_X"), fileName); - ErrorDirect (s, hwndDlg); - - return FALSE; - } - - return TRUE; -} - - -static BOOL CALLBACK LocalizeDialogEnum( HWND hwnd, LPARAM font) -{ - // Localization of controls - - if (LocalizationActive) - { - int ctrlId = GetDlgCtrlID (hwnd); - if (ctrlId != 0) - { - WCHAR name[10] = { 0 }; - GetClassNameW (hwnd, name, array_capacity (name)); - - if (_wcsicmp (name, L"Button") == 0 || _wcsicmp (name, L"Static") == 0) - { - wchar_t *str = (wchar_t *) GetDictionaryValueByInt (ctrlId); - if (str != NULL) - SetWindowTextW (hwnd, str); - } - } - } - - // Font - SendMessageW (hwnd, WM_SETFONT, (WPARAM) font, 0); - - return TRUE; -} - -void LocalizeDialog (HWND hwnd, char *stringId) -{ - LastDialogId = stringId; - SetWindowLongPtrW (hwnd, GWLP_USERDATA, (LONG_PTR) 'VERA'); - SendMessageW (hwnd, WM_SETFONT, (WPARAM) hUserFont, 0); - - if (stringId == NULL) - SetWindowTextW (hwnd, L"VeraCrypt"); - else - SetWindowTextW (hwnd, GetString (stringId)); - - if (hUserFont != 0) - EnumChildWindows (hwnd, LocalizeDialogEnum, (LPARAM) hUserFont); -} - -void OpenVolumeExplorerWindow (int driveNo) -{ - wchar_t dosName[5]; - SHFILEINFO fInfo; - - StringCbPrintfW (dosName, sizeof(dosName), L"%c:\\", (wchar_t) driveNo + L'A'); - - // Force explorer to discover the drive - SHGetFileInfo (dosName, 0, &fInfo, sizeof (fInfo), 0); - - ShellExecute (NULL, L"open", dosName, NULL, NULL, SW_SHOWNORMAL); -} - -static BOOL explorerCloseSent; -static HWND explorerTopLevelWindow; - -static BOOL CALLBACK CloseVolumeExplorerWindowsChildEnum (HWND hwnd, LPARAM driveStr) -{ - WCHAR s[MAX_PATH]; - SendMessageW (hwnd, WM_GETTEXT, array_capacity (s), (LPARAM) s); - - if (wcsstr (s, (WCHAR *) driveStr) != NULL) - { - PostMessageW (explorerTopLevelWindow, WM_CLOSE, 0, 0); - explorerCloseSent = TRUE; - return FALSE; - } - - return TRUE; -} - -static BOOL CALLBACK CloseVolumeExplorerWindowsEnum (HWND hwnd, LPARAM driveNo) -{ - WCHAR driveStr[10]; - WCHAR s[MAX_PATH]; - - StringCbPrintfW (driveStr, sizeof(driveStr), L"%c:\\", driveNo + L'A'); - - GetClassNameW (hwnd, s, array_capacity (s)); - if (wcscmp (s, L"CabinetWClass") == 0) - { - GetWindowTextW (hwnd, s, array_capacity (s)); - if (wcsstr (s, driveStr) != NULL) - { - PostMessageW (hwnd, WM_CLOSE, 0, 0); - explorerCloseSent = TRUE; - return TRUE; - } - - explorerTopLevelWindow = hwnd; - EnumChildWindows (hwnd, CloseVolumeExplorerWindowsChildEnum, (LPARAM) driveStr); - } - - return TRUE; -} - -BOOL CloseVolumeExplorerWindows (HWND hwnd, int driveNo) -{ - if (driveNo >= 0) - { - explorerCloseSent = FALSE; - EnumWindows (CloseVolumeExplorerWindowsEnum, (LPARAM) driveNo); - } - - return explorerCloseSent; -} - -BOOL UpdateDriveCustomLabel (int driveNo, wchar_t* effectiveLabel, BOOL bSetValue) -{ - wchar_t wszRegPath[MAX_PATH]; - wchar_t driveStr[] = {L'A' + (wchar_t) driveNo, 0}; - HKEY hKey; - LSTATUS lStatus; - DWORD cbLabelLen = (DWORD) ((wcslen (effectiveLabel) + 1) * sizeof (wchar_t)); - BOOL bToBeDeleted = FALSE; - - StringCbPrintfW (wszRegPath, sizeof (wszRegPath), L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\DriveIcons\\%s\\DefaultLabel", driveStr); - - if (bSetValue) - lStatus = RegCreateKeyExW (HKEY_CURRENT_USER, wszRegPath, NULL, NULL, 0, - KEY_READ | KEY_WRITE | KEY_SET_VALUE, NULL, &hKey, NULL); - else - lStatus = RegOpenKeyExW (HKEY_CURRENT_USER, wszRegPath, 0, KEY_READ | KEY_WRITE | KEY_SET_VALUE, &hKey); - if (ERROR_SUCCESS == lStatus) - { - if (bSetValue) - lStatus = RegSetValueExW (hKey, NULL, NULL, REG_SZ, (LPCBYTE) effectiveLabel, cbLabelLen); - else - { - wchar_t storedLabel[34] = {0}; - DWORD cbStoredLen = sizeof (storedLabel) - 1, dwType; - lStatus = RegQueryValueExW (hKey, NULL, NULL, &dwType, (LPBYTE) storedLabel, &cbStoredLen); - if ((ERROR_SUCCESS == lStatus) && (REG_SZ == dwType) && (0 == wcscmp(storedLabel, effectiveLabel))) - { - // same label stored. mark key for deletion - bToBeDeleted = TRUE; - } - } - RegCloseKey (hKey); - } - - if (bToBeDeleted) - { - StringCbPrintfW (wszRegPath, sizeof (wszRegPath), L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\DriveIcons\\%s", driveStr); - lStatus = RegOpenKeyExW (HKEY_CURRENT_USER, wszRegPath, 0, KEY_READ | KEY_WRITE | KEY_SET_VALUE, &hKey); - if (ERROR_SUCCESS == lStatus) - { - lStatus = RegDeleteKeyW (hKey, L"DefaultLabel"); - RegCloseKey (hKey); - } - - // delete drive letter of nothing else is present under it - RegDeleteKeyW (HKEY_CURRENT_USER, wszRegPath); - - } - - return (ERROR_SUCCESS == lStatus)? TRUE : FALSE; -} - -wstring GetUserFriendlyVersionString (int version) -{ - wchar_t szTmp [64]; - StringCbPrintfW (szTmp, sizeof(szTmp), L"%x", version); - - wstring versionString (szTmp); - - versionString.insert (version > 0xfff ? 2 : 1,L"."); - - if (versionString[versionString.length()-1] == L'0') - versionString.erase (versionString.length()-1, 1); - - return (versionString); -} - -wstring IntToWideString (int val) -{ - wchar_t szTmp [64]; - StringCbPrintfW (szTmp, sizeof(szTmp), L"%d", val); - - return szTmp; -} - -wstring ArrayToHexWideString (const unsigned char* pbData, int cbData) -{ - static wchar_t* hexChar = L"0123456789ABCDEF"; - wstring result; - if (pbData) - { - for (int i = 0; i < cbData; i++) - { - result += hexChar[pbData[i] >> 4]; - result += hexChar[pbData[i] & 0x0F]; - } - } - - return result; -} - -bool HexToByte (wchar_t c, byte& b) -{ - bool bRet = true; - if (c >= L'0' && c <= L'9') - b = (byte) (c - L'0'); - else if (c >= L'a' && c <= L'z') - b = (byte) (c - L'a' + 10); - else if (c >= L'A' && c <= L'Z') - b = (byte) (c - L'A' + 10); - else - bRet = false; - - return bRet; -} - -bool HexWideStringToArray (const wchar_t* hexStr, std::vector& arr) -{ - byte b1, b2; - size_t i, len = wcslen (hexStr); - - arr.clear(); - if (len %2) - return false; - - for (i = 0; i < len/2; i++) - { - if (!HexToByte (*hexStr++, b1) || !HexToByte (*hexStr++, b2)) - return false; - arr.push_back (b1 << 4 | b2); - } - return true; -} - -wstring GetTempPathString () -{ - wchar_t tempPath[MAX_PATH]; - DWORD tempLen = ::GetTempPath (ARRAYSIZE (tempPath), tempPath); - if (tempLen == 0 || tempLen > ARRAYSIZE (tempPath)) - throw ParameterIncorrect (SRC_POS); - - return wstring (tempPath); -} - -void GetSizeString (unsigned __int64 size, wchar_t *str, size_t cbStr) -{ - static wchar_t *b, *kb, *mb, *gb, *tb, *pb; - static int serNo; - - if (b == NULL || serNo != LocalizationSerialNo) - { - serNo = LocalizationSerialNo; - kb = GetString ("KB"); - mb = GetString ("MB"); - gb = GetString ("GB"); - tb = GetString ("TB"); - pb = GetString ("PB"); - b = GetString ("BYTE"); - } - - if (size > 1024I64*1024*1024*1024*1024*99) - StringCbPrintfW (str, cbStr, L"%I64d %s", size/1024/1024/1024/1024/1024, pb); - else if (size > 1024I64*1024*1024*1024*1024) - StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(size/1024.0/1024/1024/1024/1024), pb); - else if (size > 1024I64*1024*1024*1024*99) - StringCbPrintfW (str, cbStr, L"%I64d %s",size/1024/1024/1024/1024, tb); - else if (size > 1024I64*1024*1024*1024) - StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(size/1024.0/1024/1024/1024), tb); - else if (size > 1024I64*1024*1024*99) - StringCbPrintfW (str, cbStr, L"%I64d %s",size/1024/1024/1024, gb); - else if (size > 1024I64*1024*1024) - StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(size/1024.0/1024/1024), gb); - else if (size > 1024I64*1024*99) - StringCbPrintfW (str, cbStr, L"%I64d %s", size/1024/1024, mb); - else if (size > 1024I64*1024) - StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(size/1024.0/1024), mb); - else if (size >= 1024I64) - StringCbPrintfW (str, cbStr, L"%I64d %s", size/1024, kb); - else - StringCbPrintfW (str, cbStr, L"%I64d %s", size, b); -} - -#ifndef SETUP -void GetSpeedString (unsigned __int64 speed, wchar_t *str, size_t cbStr) -{ - static wchar_t *b, *kb, *mb, *gb, *tb, *pb; - static int serNo; - - if (b == NULL || serNo != LocalizationSerialNo) - { - serNo = LocalizationSerialNo; - kb = GetString ("KB_PER_SEC"); - mb = GetString ("MB_PER_SEC"); - gb = GetString ("GB_PER_SEC"); - tb = GetString ("TB_PER_SEC"); - pb = GetString ("PB_PER_SEC"); - b = GetString ("B_PER_SEC"); - } - - if (speed > 1024I64*1024*1024*1024*1024*99) - StringCbPrintfW (str, cbStr, L"%I64d %s", speed/1024/1024/1024/1024/1024, pb); - else if (speed > 1024I64*1024*1024*1024*1024) - StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(speed/1024.0/1024/1024/1024/1024), pb); - else if (speed > 1024I64*1024*1024*1024*99) - StringCbPrintfW (str, cbStr, L"%I64d %s",speed/1024/1024/1024/1024, tb); - else if (speed > 1024I64*1024*1024*1024) - StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(speed/1024.0/1024/1024/1024), tb); - else if (speed > 1024I64*1024*1024*99) - StringCbPrintfW (str, cbStr, L"%I64d %s",speed/1024/1024/1024, gb); - else if (speed > 1024I64*1024*1024) - StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(speed/1024.0/1024/1024), gb); - else if (speed > 1024I64*1024*99) - StringCbPrintfW (str, cbStr, L"%I64d %s", speed/1024/1024, mb); - else if (speed > 1024I64*1024) - StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(speed/1024.0/1024), mb); - else if (speed > 1024I64) - StringCbPrintfW (str, cbStr, L"%I64d %s", speed/1024, kb); - else - StringCbPrintfW (str, cbStr, L"%I64d %s", speed, b); -} - -static void DisplayBenchmarkResults (HWND hwndDlg) -{ - wchar_t item1[100]={0}; - LVITEMW LvItem; - HWND hList = GetDlgItem (hwndDlg, IDC_RESULTS); - int ea, i; - BOOL unsorted = TRUE; - BENCHMARK_REC tmp_line; - - /* Sort the list */ - - switch (benchmarkSortMethod) - { - case BENCHMARK_SORT_BY_SPEED: - - while (unsorted) - { - unsorted = FALSE; - for (i = 0; i < benchmarkTotalItems - 1; i++) - { - if (benchmarkTable[i].meanBytesPerSec < benchmarkTable[i+1].meanBytesPerSec) - { - unsorted = TRUE; - memcpy (&tmp_line, &benchmarkTable[i], sizeof(BENCHMARK_REC)); - memcpy (&benchmarkTable[i], &benchmarkTable[i+1], sizeof(BENCHMARK_REC)); - memcpy (&benchmarkTable[i+1], &tmp_line, sizeof(BENCHMARK_REC)); - } - } - } - break; - - case BENCHMARK_SORT_BY_NAME: - - while (unsorted) - { - unsorted = FALSE; - for (i = 0; i < benchmarkTotalItems - 1; i++) - { - if (benchmarkTable[i].id > benchmarkTable[i+1].id) - { - unsorted = TRUE; - memcpy (&tmp_line, &benchmarkTable[i], sizeof(BENCHMARK_REC)); - memcpy (&benchmarkTable[i], &benchmarkTable[i+1], sizeof(BENCHMARK_REC)); - memcpy (&benchmarkTable[i+1], &tmp_line, sizeof(BENCHMARK_REC)); - } - } - } - break; - } - - /* Render the results */ - - SendMessage (hList,LVM_DELETEALLITEMS,0,(LPARAM)&LvItem); - - for (i = 0; i < benchmarkTotalItems; i++) - { - ea = benchmarkTable[i].id; - - memset (&LvItem,0,sizeof(LvItem)); - LvItem.mask = LVIF_TEXT; - LvItem.iItem = i; - LvItem.iSubItem = 0; - LvItem.pszText = (LPWSTR) benchmarkTable[i].name; - SendMessageW (hList, LVM_INSERTITEM, 0, (LPARAM)&LvItem); - -#if PKCS5_BENCHMARKS - wcscpy (item1, L"-"); -#else - GetSpeedString ((unsigned __int64) (benchmarkLastBufferSize / ((float) benchmarkTable[i].encSpeed / benchmarkPerformanceFrequency.QuadPart)), item1, sizeof(item1)); -#endif - LvItem.iSubItem = 1; - LvItem.pszText = item1; - - SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem); - -#if PKCS5_BENCHMARKS - wcscpy (item1, L"-"); -#else - GetSpeedString ((unsigned __int64) (benchmarkLastBufferSize / ((float) benchmarkTable[i].decSpeed / benchmarkPerformanceFrequency.QuadPart)), item1, sizeof(item1)); -#endif - LvItem.iSubItem = 2; - LvItem.pszText = item1; - - SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem); - -#if PKCS5_BENCHMARKS - swprintf (item1, L"%d t", benchmarkTable[i].encSpeed); -#else - GetSpeedString (benchmarkTable[i].meanBytesPerSec, item1, sizeof(item1)); -#endif - LvItem.iSubItem = 3; - LvItem.pszText = item1; - - SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem); - } - - SendMessageW(hList, LVM_SETCOLUMNWIDTH, 0, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); - SendMessageW(hList, LVM_SETCOLUMNWIDTH, 1, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); - SendMessageW(hList, LVM_SETCOLUMNWIDTH, 2, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); - SendMessageW(hList, LVM_SETCOLUMNWIDTH, 3, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); -} - -// specific implementation for support of benchmark operation in wait dialog mechanism - -typedef struct -{ - HWND hBenchDlg; - BOOL bStatus; -} BenchmarkThreadParam; - -static BOOL PerformBenchmark(HWND hBenchDlg, HWND hwndDlg); - -void CALLBACK BenchmarkThreadProc(void* pArg, HWND hwndDlg) -{ - BenchmarkThreadParam* pThreadParam = (BenchmarkThreadParam*) pArg; - - pThreadParam->bStatus = PerformBenchmark (pThreadParam->hBenchDlg, hwndDlg); -} - -static BOOL PerformBenchmark(HWND hBenchDlg, HWND hwndDlg) -{ - LARGE_INTEGER performanceCountStart, performanceCountEnd; - BYTE *lpTestBuffer; - PCRYPTO_INFO ci = NULL; - UINT64_STRUCT startDataUnitNo; - - startDataUnitNo.Value = 0; - -#if !(PKCS5_BENCHMARKS || HASH_FNC_BENCHMARKS) - ci = crypto_open (); - if (!ci) - return FALSE; -#endif - - if (QueryPerformanceFrequency (&benchmarkPerformanceFrequency) == 0) - { - if (ci) - crypto_close (ci); - MessageBoxW (hwndDlg, GetString ("ERR_PERF_COUNTER"), lpszTitle, ICON_HAND); - return FALSE; - } - - lpTestBuffer = (BYTE *) malloc(benchmarkBufferSize - (benchmarkBufferSize % 16)); - if (lpTestBuffer == NULL) - { - if (ci) - crypto_close (ci); - MessageBoxW (hwndDlg, GetString ("ERR_MEM_ALLOC"), lpszTitle, ICON_HAND); - return FALSE; - } - VirtualLock (lpTestBuffer, benchmarkBufferSize - (benchmarkBufferSize % 16)); - - WaitCursor (); - benchmarkTotalItems = 0; - -#if !(PKCS5_BENCHMARKS || HASH_FNC_BENCHMARKS) - // CPU "warm up" (an attempt to prevent skewed results on systems where CPU frequency - // gradually changes depending on CPU load). - ci->ea = EAGetFirst(); - if (!EAInit (ci->ea, ci->master_keydata, ci->ks)) - { - ci->mode = FIRST_MODE_OF_OPERATION_ID; - if (EAInitMode (ci)) - { - int i; - - for (i = 0; i < 10; i++) - { - EncryptDataUnits (lpTestBuffer, &startDataUnitNo, (TC_LARGEST_COMPILER_UINT) benchmarkBufferSize / ENCRYPTION_DATA_UNIT_SIZE, ci); - DecryptDataUnits (lpTestBuffer, &startDataUnitNo, (TC_LARGEST_COMPILER_UINT) benchmarkBufferSize / ENCRYPTION_DATA_UNIT_SIZE, ci); - } - } - } -#endif - -#if HASH_FNC_BENCHMARKS - - /* Measures the speed at which each of the hash algorithms processes the message to produce - a single digest. - - The hash algorithm benchmarks are included here for development purposes only. Do not enable - them when building a public release (the benchmark GUI strings wouldn't make sense). */ - - { - BYTE *digest [MAX_DIGESTSIZE]; - WHIRLPOOL_CTX wctx; - RMD160_CTX rctx; - sha512_ctx s2ctx; - sha256_ctx s256ctx; - int hid; - - for (hid = FIRST_PRF_ID; hid <= LAST_PRF_ID; hid++) - { - if (QueryPerformanceCounter (&performanceCountStart) == 0) - goto counter_error; - - switch (hid) - { - - case SHA512: - sha512_begin (&s2ctx); - sha512_hash (lpTestBuffer, benchmarkBufferSize, &s2ctx); - sha512_end ((unsigned char *) digest, &s2ctx); - break; - - case SHA256: - sha256_begin (&s256ctx); - sha256_hash (lpTestBuffer, benchmarkBufferSize, &s256ctx); - sha256_end ((unsigned char *) digest, &s256ctx); - break; - - case RIPEMD160: - RMD160Init(&rctx); - RMD160Update(&rctx, lpTestBuffer, benchmarkBufferSize); - RMD160Final((unsigned char *) digest, &rctx); - break; - - case WHIRLPOOL: - WHIRLPOOL_init (&wctx); - WHIRLPOOL_add (lpTestBuffer, benchmarkBufferSize * 8, &wctx); - WHIRLPOOL_finalize (&wctx, (unsigned char *) digest); - break; - } - - if (QueryPerformanceCounter (&performanceCountEnd) == 0) - goto counter_error; - - benchmarkTable[benchmarkTotalItems].encSpeed = performanceCountEnd.QuadPart - performanceCountStart.QuadPart; - - benchmarkTable[benchmarkTotalItems].decSpeed = benchmarkTable[benchmarkTotalItems].encSpeed; - benchmarkTable[benchmarkTotalItems].id = hid; - benchmarkTable[benchmarkTotalItems].meanBytesPerSec = ((unsigned __int64) (benchmarkBufferSize / ((float) benchmarkTable[benchmarkTotalItems].encSpeed / benchmarkPerformanceFrequency.QuadPart)) + (unsigned __int64) (benchmarkBufferSize / ((float) benchmarkTable[benchmarkTotalItems].decSpeed / benchmarkPerformanceFrequency.QuadPart))) / 2; - StringCbPrintfA (benchmarkTable[benchmarkTotalItems].name, sizeof(benchmarkTable[benchmarkTotalItems].name),"%s", HashGetName(hid)); - - benchmarkTotalItems++; - } - } - -#elif PKCS5_BENCHMARKS // #if HASH_FNC_BENCHMARKS - - /* Measures the time that it takes for the PKCS-5 routine to derive a header key using - each of the implemented PRF algorithms. - - The PKCS-5 benchmarks are included here for development purposes only. Do not enable - them when building a public release (the benchmark GUI strings wouldn't make sense). */ - { - int thid, i; - char dk[MASTER_KEYDATA_SIZE]; - char *tmp_salt = {"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF\x01\x23\x45\x67\x89\xAB\xCD\xEF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF\x01\x23\x45\x67\x89\xAB\xCD\xEF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF"}; - - for (thid = FIRST_PRF_ID; thid <= LAST_PRF_ID; thid++) - { - if (QueryPerformanceCounter (&performanceCountStart) == 0) - goto counter_error; - - for (i = 1; i <= 5; i++) - { - switch (thid) - { - - case SHA512: - /* PKCS-5 test with HMAC-SHA-512 used as the PRF */ - derive_key_sha512 ("passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, 0, FALSE, FALSE), dk, MASTER_KEYDATA_SIZE); - break; - - case SHA256: - /* PKCS-5 test with HMAC-SHA-256 used as the PRF */ - derive_key_sha256 ("passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, 0, FALSE, FALSE), dk, MASTER_KEYDATA_SIZE); - break; - - case RIPEMD160: - /* PKCS-5 test with HMAC-RIPEMD-160 used as the PRF */ - derive_key_ripemd160 ("passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, 0, FALSE, FALSE), dk, MASTER_KEYDATA_SIZE); - break; - - case WHIRLPOOL: - /* PKCS-5 test with HMAC-Whirlpool used as the PRF */ - derive_key_whirlpool ("passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, 0, FALSE, FALSE), dk, MASTER_KEYDATA_SIZE); - break; - } - } - - if (QueryPerformanceCounter (&performanceCountEnd) == 0) - goto counter_error; - - benchmarkTable[benchmarkTotalItems].encSpeed = performanceCountEnd.QuadPart - performanceCountStart.QuadPart; - benchmarkTable[benchmarkTotalItems].id = thid; - StringCbPrintfW (benchmarkTable[benchmarkTotalItems].name, sizeof(benchmarkTable[benchmarkTable[benchmarkTotalItems].name),L"%s", get_pkcs5_prf_name (thid)); - - benchmarkTotalItems++; - } - } - -#else // #elif PKCS5_BENCHMARKS - - /* Encryption algorithm benchmarks */ - - for (ci->ea = EAGetFirst(); ci->ea != 0; ci->ea = EAGetNext(ci->ea)) - { - if (!EAIsFormatEnabled (ci->ea)) - continue; - - if (ERR_CIPHER_INIT_FAILURE == EAInit (ci->ea, ci->master_keydata, ci->ks)) - goto counter_error; - - ci->mode = FIRST_MODE_OF_OPERATION_ID; - if (!EAInitMode (ci)) - goto counter_error; - - if (QueryPerformanceCounter (&performanceCountStart) == 0) - goto counter_error; - - EncryptDataUnits (lpTestBuffer, &startDataUnitNo, (TC_LARGEST_COMPILER_UINT) benchmarkBufferSize / ENCRYPTION_DATA_UNIT_SIZE, ci); - - if (QueryPerformanceCounter (&performanceCountEnd) == 0) - goto counter_error; - - benchmarkTable[benchmarkTotalItems].encSpeed = performanceCountEnd.QuadPart - performanceCountStart.QuadPart; - - if (QueryPerformanceCounter (&performanceCountStart) == 0) - goto counter_error; - - DecryptDataUnits (lpTestBuffer, &startDataUnitNo, (TC_LARGEST_COMPILER_UINT) benchmarkBufferSize / ENCRYPTION_DATA_UNIT_SIZE, ci); - - if (QueryPerformanceCounter (&performanceCountEnd) == 0) - goto counter_error; - - benchmarkTable[benchmarkTotalItems].decSpeed = performanceCountEnd.QuadPart - performanceCountStart.QuadPart; - benchmarkTable[benchmarkTotalItems].id = ci->ea; - benchmarkTable[benchmarkTotalItems].meanBytesPerSec = ((unsigned __int64) (benchmarkBufferSize / ((float) benchmarkTable[benchmarkTotalItems].encSpeed / benchmarkPerformanceFrequency.QuadPart)) + (unsigned __int64) (benchmarkBufferSize / ((float) benchmarkTable[benchmarkTotalItems].decSpeed / benchmarkPerformanceFrequency.QuadPart))) / 2; - EAGetName (benchmarkTable[benchmarkTotalItems].name, ci->ea, 1); - - benchmarkTotalItems++; - } - -#endif // #elif PKCS5_BENCHMARKS (#else) - - if (ci) - crypto_close (ci); - - VirtualUnlock (lpTestBuffer, benchmarkBufferSize - (benchmarkBufferSize % 16)); - - free(lpTestBuffer); - - benchmarkLastBufferSize = benchmarkBufferSize; - - DisplayBenchmarkResults(hBenchDlg); - - EnableWindow (GetDlgItem (hBenchDlg, IDC_PERFORM_BENCHMARK), TRUE); - EnableWindow (GetDlgItem (hBenchDlg, IDCLOSE), TRUE); - - NormalCursor (); - return TRUE; - -counter_error: - - if (ci) - crypto_close (ci); - - VirtualUnlock (lpTestBuffer, benchmarkBufferSize - (benchmarkBufferSize % 16)); - - free(lpTestBuffer); - - NormalCursor (); - - EnableWindow (GetDlgItem (hBenchDlg, IDC_PERFORM_BENCHMARK), TRUE); - EnableWindow (GetDlgItem (hBenchDlg, IDCLOSE), TRUE); - - MessageBoxW (hwndDlg, GetString ("ERR_PERF_COUNTER"), lpszTitle, ICON_HAND); - return FALSE; -} - - -BOOL CALLBACK BenchmarkDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - LPARAM nIndex; - HWND hCboxSortMethod = GetDlgItem (hwndDlg, IDC_BENCHMARK_SORT_METHOD); - HWND hCboxBufferSize = GetDlgItem (hwndDlg, IDC_BENCHMARK_BUFFER_SIZE); - - switch (msg) - { - case WM_INITDIALOG: - { - LVCOLUMNW LvCol; - wchar_t s[128]; - HWND hList = GetDlgItem (hwndDlg, IDC_RESULTS); - - LocalizeDialog (hwndDlg, "IDD_BENCHMARK_DLG"); - - benchmarkBufferSize = BENCHMARK_DEFAULT_BUF_SIZE; - benchmarkSortMethod = BENCHMARK_SORT_BY_SPEED; - - SendMessage (hList,LVM_SETEXTENDEDLISTVIEWSTYLE,0, - LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_LABELTIP - ); - - memset (&LvCol,0,sizeof(LvCol)); - LvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; - LvCol.pszText = GetString ("ALGORITHM"); - LvCol.cx = CompensateXDPI (114); - LvCol.fmt = LVCFMT_LEFT; - SendMessage (hList,LVM_INSERTCOLUMNW,0,(LPARAM)&LvCol); - - LvCol.pszText = GetString ("ENCRYPTION"); - LvCol.cx = CompensateXDPI (80); - LvCol.fmt = LVCFMT_RIGHT; - SendMessageW (hList,LVM_INSERTCOLUMNW,1,(LPARAM)&LvCol); - - LvCol.pszText = GetString ("DECRYPTION"); - LvCol.cx = CompensateXDPI (80); - LvCol.fmt = LVCFMT_RIGHT; - SendMessageW (hList,LVM_INSERTCOLUMNW,2,(LPARAM)&LvCol); - - LvCol.pszText = GetString ("MEAN"); - LvCol.cx = CompensateXDPI (80); - LvCol.fmt = LVCFMT_RIGHT; - SendMessageW (hList,LVM_INSERTCOLUMNW,3,(LPARAM)&LvCol); - - /* Combo boxes */ - - // Sort method - - SendMessage (hCboxSortMethod, CB_RESETCONTENT, 0, 0); - - nIndex = SendMessageW (hCboxSortMethod, CB_ADDSTRING, 0, (LPARAM) GetString ("ALPHABETICAL_CATEGORIZED")); - SendMessage (hCboxSortMethod, CB_SETITEMDATA, nIndex, (LPARAM) 0); - - nIndex = SendMessageW (hCboxSortMethod, CB_ADDSTRING, 0, (LPARAM) GetString ("MEAN_SPEED")); - SendMessage (hCboxSortMethod, CB_SETITEMDATA, nIndex, (LPARAM) 0); - - SendMessage (hCboxSortMethod, CB_SETCURSEL, 1, 0); // Default sort method - - // Buffer size - - SendMessage (hCboxBufferSize, CB_RESETCONTENT, 0, 0); - - StringCbPrintfW (s, sizeof(s), L"100 %s", GetString ("KB")); - nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); - SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 100 * BYTES_PER_KB); - - StringCbPrintfW (s, sizeof(s), L"500 %s", GetString ("KB")); - nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); - SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 500 * BYTES_PER_KB); - - StringCbPrintfW (s, sizeof(s), L"1 %s", GetString ("MB")); - nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); - SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 1 * BYTES_PER_MB); - - StringCbPrintfW (s, sizeof(s), L"5 %s", GetString ("MB")); - nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); - SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 5 * BYTES_PER_MB); - - StringCbPrintfW (s, sizeof(s), L"10 %s", GetString ("MB")); - nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); - SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 10 * BYTES_PER_MB); - - StringCbPrintfW (s, sizeof(s), L"50 %s", GetString ("MB")); - nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); - SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 50 * BYTES_PER_MB); - - StringCbPrintfW (s, sizeof(s), L"100 %s", GetString ("MB")); - nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); - SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 100 * BYTES_PER_MB); - - StringCbPrintfW (s, sizeof(s), L"200 %s", GetString ("MB")); - nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); - SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 200 * BYTES_PER_MB); - - StringCbPrintfW (s, sizeof(s), L"500 %s", GetString ("MB")); - nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); - SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 500 * BYTES_PER_MB); - - StringCbPrintfW (s, sizeof(s), L"1 %s", GetString ("GB")); - nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); - SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 1 * BYTES_PER_GB); - - SendMessage (hCboxBufferSize, CB_SETCURSEL, 5, 0); // Default buffer size - - - uint32 driverConfig = ReadDriverConfigurationFlags(); - - SetDlgItemTextW (hwndDlg, IDC_HW_AES, (wstring (L" ") + (GetString (is_aes_hw_cpu_supported() ? ((driverConfig & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? "UISTR_DISABLED" : "UISTR_YES") : "NOT_APPLICABLE_OR_NOT_AVAILABLE"))).c_str()); - - ToHyperlink (hwndDlg, IDC_HW_AES_LABEL_LINK); - - if (is_aes_hw_cpu_supported() && (driverConfig & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION)) - { - Warning ("DISABLED_HW_AES_AFFECTS_PERFORMANCE", hwndDlg); - } - - SYSTEM_INFO sysInfo; - GetSystemInfo (&sysInfo); - - size_t nbrThreads = GetEncryptionThreadCount(); - - wchar_t nbrThreadsStr [300]; - if (sysInfo.dwNumberOfProcessors < 2) - { - StringCbCopyW (nbrThreadsStr, sizeof(nbrThreadsStr), GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE")); - } - else if (nbrThreads < 2) - { - StringCbCopyW (nbrThreadsStr, sizeof(nbrThreadsStr), GetString ("UISTR_DISABLED")); - } - else - { - StringCbPrintfW (nbrThreadsStr, sizeof(nbrThreadsStr), GetString ("NUMBER_OF_THREADS"), nbrThreads); - } - - SetDlgItemTextW (hwndDlg, IDC_PARALLELIZATION, (wstring (L" ") + nbrThreadsStr).c_str()); - - ToHyperlink (hwndDlg, IDC_PARALLELIZATION_LABEL_LINK); - - if (nbrThreads < min (sysInfo.dwNumberOfProcessors, GetMaxEncryptionThreadCount()) - && sysInfo.dwNumberOfProcessors > 1) - { - Warning ("LIMITED_THREAD_COUNT_AFFECTS_PERFORMANCE", hwndDlg); - } - - return 1; - } - break; - - case WM_COMMAND: - - switch (lw) - { - case IDC_BENCHMARK_SORT_METHOD: - - nIndex = SendMessage (hCboxSortMethod, CB_GETCURSEL, 0, 0); - if (nIndex != benchmarkSortMethod) - { - benchmarkSortMethod = (int) nIndex; - DisplayBenchmarkResults (hwndDlg); - } - return 1; - - case IDC_PERFORM_BENCHMARK: - - nIndex = SendMessage (hCboxBufferSize, CB_GETCURSEL, 0, 0); - benchmarkBufferSize = (int) SendMessage (hCboxBufferSize, CB_GETITEMDATA, nIndex, 0); - - BenchmarkThreadParam threadParam; - threadParam.hBenchDlg = hwndDlg; - threadParam.bStatus = FALSE; - - WaitCursor (); - - ShowWaitDialog (hwndDlg, TRUE, BenchmarkThreadProc, &threadParam); - - NormalCursor (); - - if (threadParam.bStatus == FALSE) - { - EndDialog (hwndDlg, IDCLOSE); - } - return 1; - - case IDC_HW_AES_LABEL_LINK: - - Applink ("hwacceleration", TRUE, ""); - return 1; - - case IDC_PARALLELIZATION_LABEL_LINK: - - Applink ("parallelization", TRUE, ""); - return 1; - - case IDCLOSE: - case IDCANCEL: - - EndDialog (hwndDlg, IDCLOSE); - return 1; - } - return 0; - - break; - - case WM_CLOSE: - EndDialog (hwndDlg, IDCLOSE); - return 1; - - break; - - } - return 0; -} - - -static BOOL CALLBACK RandomPoolEnrichementDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - WORD hw = HIWORD (wParam); - static unsigned char randPool [RNG_POOL_SIZE]; - static unsigned char lastRandPool [RNG_POOL_SIZE]; - static unsigned char maskRandPool [RNG_POOL_SIZE]; - static BOOL bUseMask = FALSE; - static DWORD mouseEntropyGathered = 0xFFFFFFFF; - static DWORD mouseEventsInitialCount = 0; - /* max value of entropy needed to fill all random pool = 8 * RNG_POOL_SIZE = 2560 bits */ - static const DWORD maxEntropyLevel = RNG_POOL_SIZE * 8; - static HWND hEntropyBar = NULL; - static wchar_t outputDispBuffer [RNG_POOL_SIZE * 3 + RANDPOOL_DISPLAY_ROWS + 2]; - static BOOL bDisplayPoolContents = FALSE; - static BOOL bRandPoolDispAscii = FALSE; - int hash_algo = RandGetHashFunction(); - int hid; - - switch (msg) - { - case WM_INITDIALOG: - { - HWND hComboBox = GetDlgItem (hwndDlg, IDC_PRF_ID); - HCRYPTPROV hRngProv = NULL; - - VirtualLock (randPool, sizeof(randPool)); - VirtualLock (lastRandPool, sizeof(lastRandPool)); - VirtualLock (outputDispBuffer, sizeof(outputDispBuffer)); - VirtualLock (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); - VirtualLock (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); - VirtualLock (maskRandPool, sizeof(maskRandPool)); - - mouseEntropyGathered = 0xFFFFFFFF; - mouseEventsInitialCount = 0; - bUseMask = FALSE; - if (CryptAcquireContext (&hRngProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) - { - if (CryptGenRandom (hRngProv, sizeof (maskRandPool), maskRandPool)) - bUseMask = TRUE; - CryptReleaseContext (hRngProv, 0); - } - - LocalizeDialog (hwndDlg, "IDD_RANDOM_POOL_ENRICHMENT"); - - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - for (hid = FIRST_PRF_ID; hid <= LAST_PRF_ID; hid++) - { - if (!HashIsDeprecated (hid)) - AddComboPair (hComboBox, HashGetName(hid), hid); - } - SelectAlgo (hComboBox, &hash_algo); - - SetCheckBox (hwndDlg, IDC_DISPLAY_POOL_CONTENTS, bDisplayPoolContents); - - SetTimer (hwndDlg, 0xfd, RANDPOOL_DISPLAY_REFRESH_INTERVAL, NULL); - SendMessage (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); - - hEntropyBar = GetDlgItem (hwndDlg, IDC_ENTROPY_BAR); - SendMessage (hEntropyBar, PBM_SETRANGE32, 0, maxEntropyLevel); - SendMessage (hEntropyBar, PBM_SETSTEP, 1, 0); - SendMessage (hEntropyBar, PBM_SETSTATE, PBST_ERROR, 0); - return 1; - } - - case WM_TIMER: - { - wchar_t tmp[4]; - unsigned char tmpByte; - int col, row; - DWORD mouseEventsCounter; - - RandpeekBytes (hwndDlg, randPool, sizeof (randPool), &mouseEventsCounter); - - ProcessEntropyEstimate (hEntropyBar, &mouseEventsInitialCount, mouseEventsCounter, maxEntropyLevel, &mouseEntropyGathered); - - if (memcmp (lastRandPool, randPool, sizeof(lastRandPool)) != 0) - { - outputDispBuffer[0] = 0; - - for (row = 0; row < RANDPOOL_DISPLAY_ROWS; row++) - { - for (col = 0; col < RANDPOOL_DISPLAY_COLUMNS; col++) - { - if (bDisplayPoolContents) - { - tmpByte = randPool[row * RANDPOOL_DISPLAY_COLUMNS + col]; - StringCbPrintfW (tmp, sizeof(tmp), bRandPoolDispAscii ? ((tmpByte >= 32 && tmpByte < 255 && tmpByte != L'&') ? L" %c " : L" . ") : L"%02X ", tmpByte); - } - else if (bUseMask) - { - /* use mask to compute a randomized ascii representation */ - tmpByte = (randPool[row * RANDPOOL_DISPLAY_COLUMNS + col] - - lastRandPool[row * RANDPOOL_DISPLAY_COLUMNS + col]) ^ maskRandPool [row * RANDPOOL_DISPLAY_COLUMNS + col]; - tmp[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); - tmp[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); - tmp[2] = L' '; - tmp[3] = 0; - } - else - { - StringCbCopyW (tmp, sizeof(tmp), L"** "); - } - - StringCbCatW (outputDispBuffer, sizeof(outputDispBuffer), tmp); - } - StringCbCatW (outputDispBuffer, sizeof(outputDispBuffer), L"\n"); - } - SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), outputDispBuffer); - - memcpy (lastRandPool, randPool, sizeof(lastRandPool)); - } - return 1; - } - - case WM_COMMAND: - if (lw == IDC_CONTINUE) - lw = IDOK; - - if (lw == IDOK || lw == IDCLOSE || lw == IDCANCEL) - { - goto exit; - } - - if (lw == IDC_PRF_ID && hw == CBN_SELCHANGE) - { - hid = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PRF_ID), CB_GETCURSEL, 0, 0); - hash_algo = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PRF_ID), CB_GETITEMDATA, hid, 0); - RandSetHashFunction (hash_algo); - return 1; - } - - if (lw == IDC_DISPLAY_POOL_CONTENTS) - { - if (!(bDisplayPoolContents = GetCheckBox (hwndDlg, IDC_DISPLAY_POOL_CONTENTS))) - { - wchar_t tmp[RNG_POOL_SIZE+1]; - - wmemset (tmp, L' ', ARRAYSIZE(tmp)); - tmp [RNG_POOL_SIZE] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), tmp); - } - - return 1; - } - - return 0; - - case WM_CLOSE: - { - wchar_t tmp[RNG_POOL_SIZE+1]; -exit: - KillTimer (hwndDlg, 0xfd); - - burn (randPool, sizeof(randPool)); - burn (lastRandPool, sizeof(lastRandPool)); - burn (outputDispBuffer, sizeof(outputDispBuffer)); - burn (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); - burn (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); - burn (maskRandPool, sizeof(maskRandPool)); - - // Attempt to wipe the pool contents in the GUI text area - wmemset (tmp, L' ', RNG_POOL_SIZE); - tmp [RNG_POOL_SIZE] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), tmp); - - if (msg == WM_COMMAND && lw == IDOK) - EndDialog (hwndDlg, IDOK); - else - EndDialog (hwndDlg, IDCLOSE); - - return 1; - } - } - return 0; -} - -/* Randinit is always called before UserEnrichRandomPool, so we don't need - * the extra Randinit call here since it will always succeed but we keep it - * for clarity purposes - */ -void UserEnrichRandomPool (HWND hwndDlg) -{ - if ((0 == Randinit()) && !IsRandomPoolEnrichedByUser()) - { - INT_PTR result = DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_RANDOM_POOL_ENRICHMENT), hwndDlg ? hwndDlg : MainDlg, (DLGPROC) RandomPoolEnrichementDlgProc, (LPARAM) 0); - SetRandomPoolEnrichedByUserStatus (result == IDOK); - } -} - - -/* Except in response to the WM_INITDIALOG message, the dialog box procedure - should return nonzero if it processes the message, and zero if it does - not. - see DialogProc */ -BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - WORD hw = HIWORD (wParam); - static unsigned char randPool [RNG_POOL_SIZE]; - static unsigned char lastRandPool [RNG_POOL_SIZE]; - static unsigned char maskRandPool [RNG_POOL_SIZE]; - static BOOL bUseMask = FALSE; - static DWORD mouseEntropyGathered = 0xFFFFFFFF; - static DWORD mouseEventsInitialCount = 0; - /* max value of entropy needed to fill all random pool = 8 * RNG_POOL_SIZE = 2560 bits */ - static const DWORD maxEntropyLevel = RNG_POOL_SIZE * 8; - static HWND hEntropyBar = NULL; - static wchar_t outputDispBuffer [RNG_POOL_SIZE * 3 + RANDPOOL_DISPLAY_ROWS + 2]; - static BOOL bDisplayPoolContents = FALSE; - static BOOL bRandPoolDispAscii = FALSE; - int hash_algo = RandGetHashFunction(); - int hid; - - switch (msg) - { - case WM_INITDIALOG: - { - HWND hComboBox = GetDlgItem (hwndDlg, IDC_PRF_ID); - HCRYPTPROV hRngProv = NULL; - - VirtualLock (randPool, sizeof(randPool)); - VirtualLock (lastRandPool, sizeof(lastRandPool)); - VirtualLock (outputDispBuffer, sizeof(outputDispBuffer)); - VirtualLock (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); - VirtualLock (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); - VirtualLock (maskRandPool, sizeof(maskRandPool)); - - mouseEntropyGathered = 0xFFFFFFFF; - mouseEventsInitialCount = 0; - bUseMask = FALSE; - if (CryptAcquireContext (&hRngProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) - { - if (CryptGenRandom (hRngProv, sizeof (maskRandPool), maskRandPool)) - bUseMask = TRUE; - CryptReleaseContext (hRngProv, 0); - } - - LocalizeDialog (hwndDlg, "IDD_KEYFILE_GENERATOR"); - - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - for (hid = FIRST_PRF_ID; hid <= LAST_PRF_ID; hid++) - { - if (!HashIsDeprecated (hid)) - AddComboPair (hComboBox, HashGetName(hid), hid); - } - SelectAlgo (hComboBox, &hash_algo); - - SetCheckBox (hwndDlg, IDC_DISPLAY_POOL_CONTENTS, bDisplayPoolContents); - hEntropyBar = GetDlgItem (hwndDlg, IDC_ENTROPY_BAR); - SendMessage (hEntropyBar, PBM_SETRANGE32, 0, maxEntropyLevel); - SendMessage (hEntropyBar, PBM_SETSTEP, 1, 0); - SendMessage (hEntropyBar, PBM_SETSTATE, PBST_ERROR, 0); - -#ifndef VOLFORMAT - if (Randinit ()) - { - handleError (hwndDlg, (CryptoAPILastError == ERROR_SUCCESS)? ERR_RAND_INIT_FAILED : ERR_CAPI_INIT_FAILED, SRC_POS); - EndDialog (hwndDlg, IDCLOSE); - } -#endif - SetTimer (hwndDlg, 0xfd, RANDPOOL_DISPLAY_REFRESH_INTERVAL, NULL); - SendMessage (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); - // 9-digit limit for the number of keyfiles (more than enough!) - SendMessage (GetDlgItem (hwndDlg, IDC_NUMBER_KEYFILES), EM_SETLIMITTEXT, (WPARAM) 9, 0); - SetWindowText(GetDlgItem (hwndDlg, IDC_NUMBER_KEYFILES), L"1"); - // maximum keyfile size is 1048576, so limit the edit control to 7 characters - SendMessage (GetDlgItem (hwndDlg, IDC_KEYFILES_SIZE), EM_SETLIMITTEXT, (WPARAM) 7, 0); - SetWindowText(GetDlgItem (hwndDlg, IDC_KEYFILES_SIZE), L"64"); - // set the maximum length of the keyfile base name to (TC_MAX_PATH - 1) - SendMessage (GetDlgItem (hwndDlg, IDC_KEYFILES_BASE_NAME), EM_SETLIMITTEXT, (WPARAM) (TC_MAX_PATH - 1), 0); - return 1; - } - - case WM_TIMER: - { - wchar_t tmp[4]; - unsigned char tmpByte; - int col, row; - DWORD mouseEventsCounter; - - RandpeekBytes (hwndDlg, randPool, sizeof (randPool), &mouseEventsCounter); - - ProcessEntropyEstimate (hEntropyBar, &mouseEventsInitialCount, mouseEventsCounter, maxEntropyLevel, &mouseEntropyGathered); - - if (memcmp (lastRandPool, randPool, sizeof(lastRandPool)) != 0) - { - outputDispBuffer[0] = 0; - - for (row = 0; row < RANDPOOL_DISPLAY_ROWS; row++) - { - for (col = 0; col < RANDPOOL_DISPLAY_COLUMNS; col++) - { - if (bDisplayPoolContents) - { - tmpByte = randPool[row * RANDPOOL_DISPLAY_COLUMNS + col]; - StringCbPrintfW (tmp, sizeof(tmp), bRandPoolDispAscii ? ((tmpByte >= 32 && tmpByte < 255 && tmpByte != L'&') ? L" %c " : L" . ") : L"%02X ", tmpByte); - } - else if (bUseMask) - { - /* use mask to compute a randomized ASCII representation */ - tmpByte = (randPool[row * RANDPOOL_DISPLAY_COLUMNS + col] - - lastRandPool[row * RANDPOOL_DISPLAY_COLUMNS + col]) ^ maskRandPool [row * RANDPOOL_DISPLAY_COLUMNS + col]; - tmp[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); - tmp[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); - tmp[2] = L' '; - tmp[3] = 0; - } - else - { - StringCbCopyW (tmp, sizeof(tmp), L"** "); - } - - StringCbCatW (outputDispBuffer, sizeof(outputDispBuffer), tmp); - } - StringCbCatW (outputDispBuffer, sizeof(outputDispBuffer), L"\n"); - } - SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), outputDispBuffer); - - memcpy (lastRandPool, randPool, sizeof(lastRandPool)); - } - return 1; - } - - case WM_COMMAND: - - if (lw == IDCLOSE || lw == IDCANCEL) - { - goto exit; - } - - if (lw == IDC_PRF_ID && hw == CBN_SELCHANGE) - { - hid = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PRF_ID), CB_GETCURSEL, 0, 0); - hash_algo = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PRF_ID), CB_GETITEMDATA, hid, 0); - RandSetHashFunction (hash_algo); - return 1; - } - - if (lw == IDC_DISPLAY_POOL_CONTENTS) - { - if (!(bDisplayPoolContents = GetCheckBox (hwndDlg, IDC_DISPLAY_POOL_CONTENTS))) - { - wchar_t tmp[RNG_POOL_SIZE+1]; - - wmemset (tmp, L' ', ARRAYSIZE(tmp)); - tmp [RNG_POOL_SIZE] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), tmp); - } - return 1; - } - - if (lw == IDC_KEYFILES_RANDOM_SIZE) - { - EnableWindow(GetDlgItem (hwndDlg, IDC_KEYFILES_SIZE), !GetCheckBox (hwndDlg, IDC_KEYFILES_RANDOM_SIZE)); - } - - if (lw == IDC_GENERATE_AND_SAVE_KEYFILE) - { - wchar_t szNumber[16] = {0}; - wchar_t szFileBaseName[TC_MAX_PATH]; - wchar_t szDirName[TC_MAX_PATH]; - wchar_t szFileName [2*TC_MAX_PATH + 16]; - unsigned char *keyfile = NULL; - int fhKeyfile = -1, status; - long keyfilesCount = 0, keyfilesSize = 0, i; - wchar_t* fileExtensionPtr = 0; - wchar_t szSuffix[32]; - BOOL bRandomSize = GetCheckBox (hwndDlg, IDC_KEYFILES_RANDOM_SIZE); - - if (!GetWindowText(GetDlgItem (hwndDlg, IDC_NUMBER_KEYFILES), szNumber, ARRAYSIZE(szNumber))) - szNumber[0] = 0; - - keyfilesCount = wcstoul(szNumber, NULL, 0); - if (keyfilesCount <= 0 || keyfilesCount == LONG_MAX) - { - Warning("KEYFILE_INCORRECT_NUMBER", hwndDlg); - SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hwndDlg, IDC_NUMBER_KEYFILES), TRUE); - return 1; - } - - if (!bRandomSize) - { - if (!GetWindowText(GetDlgItem (hwndDlg, IDC_KEYFILES_SIZE), szNumber, ARRAYSIZE(szNumber))) - szNumber[0] = 0; - - keyfilesSize = wcstoul(szNumber, NULL, 0); - if (keyfilesSize < 64 || keyfilesSize > 1024*1024) - { - Warning("KEYFILE_INCORRECT_SIZE", hwndDlg); - SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hwndDlg, IDC_KEYFILES_SIZE), TRUE); - return 1; - } - } - - if (!GetWindowText(GetDlgItem (hwndDlg, IDC_KEYFILES_BASE_NAME), szFileBaseName, TC_MAX_PATH)) - szFileBaseName[0] = 0; - - // Trim trailing space - if (TrimWhiteSpace(szFileBaseName) == 0) - { - Warning("KEYFILE_EMPTY_BASE_NAME", hwndDlg); - SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hwndDlg, IDC_KEYFILES_BASE_NAME), TRUE); - return 1; - } - - if (!IsValidFileName(szFileBaseName)) - { - Warning("KEYFILE_INVALID_BASE_NAME", hwndDlg); - SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hwndDlg, IDC_KEYFILES_BASE_NAME), TRUE); - return 1; - } - - fileExtensionPtr = wcsrchr(szFileBaseName, L'.'); - - /* Select directory */ - if (!BrowseDirectories (hwndDlg, "SELECT_KEYFILE_GENERATION_DIRECTORY", szDirName)) - return 1; - - if (szDirName[wcslen(szDirName) - 1] != L'\\' && szDirName[wcslen(szDirName) - 1] != L'/') - StringCbCat(szDirName, sizeof(szDirName), L"\\"); - - WaitCursor(); - - keyfile = (unsigned char*) TCalloc( bRandomSize? KEYFILE_MAX_READ_LEN : keyfilesSize ); - - for (i= 0; i < keyfilesCount; i++) - { - StringCbCopyW(szFileName, sizeof(szFileName), szDirName); - - if (i > 0) - { - StringCbPrintfW(szSuffix, sizeof(szSuffix), L"_%d", i); - // Append the counter to the name - if (fileExtensionPtr) - { - StringCchCatN(szFileName, ARRAYSIZE(szFileName), szFileBaseName, (size_t) (fileExtensionPtr - szFileBaseName)); - StringCbCat(szFileName, sizeof(szFileName), szSuffix); - StringCbCat(szFileName, sizeof(szFileName), fileExtensionPtr); - } - else - { - StringCbCat(szFileName, sizeof(szFileName), szFileBaseName); - StringCbCat(szFileName, sizeof(szFileName), szSuffix); - } - } - else - StringCbCat(szFileName, sizeof(szFileName), szFileBaseName); - - // check if the file exists - if ((fhKeyfile = _wopen(szFileName, _O_RDONLY|_O_BINARY, _S_IREAD|_S_IWRITE)) != -1) - { - WCHAR s[4*TC_MAX_PATH] = {0}; - - _close (fhKeyfile); - - StringCbPrintfW (s, sizeof(s), GetString ("KEYFILE_ALREADY_EXISTS"), szFileName); - status = AskWarnNoYesString (s, hwndDlg); - if (status == IDNO) - { - TCfree(keyfile); - NormalCursor(); - return 1; - } - } - - /* Conceive the file */ - if ((fhKeyfile = _wopen(szFileName, _O_CREAT|_O_TRUNC|_O_WRONLY|_O_BINARY, _S_IREAD|_S_IWRITE)) == -1) - { - TCfree(keyfile); - NormalCursor(); - handleWin32Error (hwndDlg, SRC_POS); - return 1; - } - - if (bRandomSize) - { - /* Generate a random size */ - if (!RandgetBytes (hwndDlg, (unsigned char*) &keyfilesSize, sizeof(keyfilesSize), FALSE)) - { - _close (fhKeyfile); - DeleteFile (szFileName); - TCfree(keyfile); - NormalCursor(); - return 1; - } - - /* since keyfilesSize < 1024 * 1024, we mask with 0x000FFFFF */ - keyfilesSize = (long) (((unsigned long) keyfilesSize) & 0x000FFFFF); - - keyfilesSize %= ((KEYFILE_MAX_READ_LEN - 64) + 1); - keyfilesSize += 64; - } - - /* Generate the keyfile */ - if (!RandgetBytesFull (hwndDlg, keyfile, keyfilesSize, TRUE, TRUE)) - { - _close (fhKeyfile); - DeleteFile (szFileName); - TCfree(keyfile); - NormalCursor(); - return 1; - } - - /* Write the keyfile */ - status = _write (fhKeyfile, keyfile, keyfilesSize); - burn (keyfile, keyfilesSize); - _close (fhKeyfile); - - if (status == -1) - { - TCfree(keyfile); - NormalCursor(); - handleWin32Error (hwndDlg, SRC_POS); - return 1; - } - } - - TCfree(keyfile); - NormalCursor(); - - Info("KEYFILE_CREATED", hwndDlg); - - return 1; - } - return 0; - - case WM_CLOSE: - { - wchar_t tmp[RNG_POOL_SIZE+1]; -exit: - WaitCursor(); - KillTimer (hwndDlg, 0xfd); - -#ifndef VOLFORMAT - RandStop (FALSE); -#endif - /* Cleanup */ - - burn (randPool, sizeof(randPool)); - burn (lastRandPool, sizeof(lastRandPool)); - burn (outputDispBuffer, sizeof(outputDispBuffer)); - burn (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); - burn (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); - burn (maskRandPool, sizeof(maskRandPool)); - - // Attempt to wipe the pool contents in the GUI text area - wmemset (tmp, L' ', RNG_POOL_SIZE); - tmp [RNG_POOL_SIZE] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), tmp); - - EndDialog (hwndDlg, IDCLOSE); - NormalCursor (); - return 1; - } - } - return 0; -} - - - -/* Except in response to the WM_INITDIALOG message, the dialog box procedure -should return nonzero if it processes the message, and zero if it does -not. - see DialogProc */ -BOOL CALLBACK -CipherTestDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - static int idTestCipher = -1; /* Currently selected cipher for the test vector facility (none = -1). */ - static BOOL bXTSTestEnabled = FALSE; - - PCRYPTO_INFO ci; - WORD lw = LOWORD (wParam); - WORD hw = HIWORD (wParam); - - switch (uMsg) - { - case WM_INITDIALOG: - { - int ea; - wchar_t buf[100]; - - LocalizeDialog (hwndDlg, "IDD_CIPHER_TEST_DLG"); - - SendMessage(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), WM_SETFONT, (WPARAM)hBoldFont, MAKELPARAM(TRUE,0)); - SendMessage(GetDlgItem(hwndDlg, IDC_KEY), EM_LIMITTEXT, 128,0); - SendMessage(GetDlgItem(hwndDlg, IDC_KEY), WM_SETFONT, (WPARAM)hFixedDigitFont, MAKELPARAM(1,0)); - SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT), EM_LIMITTEXT,64,0); - SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT), WM_SETFONT, (WPARAM)hFixedDigitFont, MAKELPARAM(1,0)); - SendMessage(GetDlgItem(hwndDlg, IDC_CIPHERTEXT), EM_LIMITTEXT,64,0); - SendMessage(GetDlgItem(hwndDlg, IDC_CIPHERTEXT), WM_SETFONT, (WPARAM)hFixedDigitFont, MAKELPARAM(1,0)); - SendMessage(GetDlgItem(hwndDlg, IDC_SECONDARY_KEY), EM_LIMITTEXT, 128,0); - SendMessage(GetDlgItem(hwndDlg, IDC_SECONDARY_KEY), WM_SETFONT, (WPARAM)hFixedDigitFont, MAKELPARAM(1,0)); - SendMessage(GetDlgItem(hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), EM_LIMITTEXT,32,0); - SendMessage(GetDlgItem(hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), WM_SETFONT, (WPARAM)hFixedDigitFont, MAKELPARAM(1,0)); - SetCheckBox (hwndDlg, IDC_XTS_MODE_ENABLED, bXTSTestEnabled); - EnableWindow (GetDlgItem (hwndDlg, IDC_SECONDARY_KEY), bXTSTestEnabled); - EnableWindow (GetDlgItem (hwndDlg, IDT_SECONDARY_KEY), bXTSTestEnabled); - EnableWindow (GetDlgItem (hwndDlg, IDC_TEST_BLOCK_NUMBER), bXTSTestEnabled); - EnableWindow (GetDlgItem (hwndDlg, IDT_TEST_BLOCK_NUMBER), bXTSTestEnabled); - EnableWindow (GetDlgItem (hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), bXTSTestEnabled); - EnableWindow (GetDlgItem (hwndDlg, IDT_TEST_DATA_UNIT_NUMBER), bXTSTestEnabled); - - if (idTestCipher == -1) - idTestCipher = (int) lParam; - - SendMessage (GetDlgItem (hwndDlg, IDC_CIPHER), CB_RESETCONTENT, 0, 0); - for (ea = EAGetFirst (); ea != 0; ea = EAGetNext (ea)) - { - if (EAGetCipherCount (ea) == 1 && EAIsFormatEnabled (ea)) - AddComboPair (GetDlgItem (hwndDlg, IDC_CIPHER), EAGetName (buf, ea, 1), EAGetFirstCipher (ea)); - } - - ResetCipherTest(hwndDlg, idTestCipher); - - SelectAlgo (GetDlgItem (hwndDlg, IDC_CIPHER), &idTestCipher); - - return 1; - } - - case WM_COMMAND: - - if (hw == CBN_SELCHANGE && lw == IDC_CIPHER) - { - idTestCipher = (int) SendMessage (GetDlgItem (hwndDlg, IDC_CIPHER), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_CIPHER), CB_GETCURSEL, 0, 0), 0); - ResetCipherTest(hwndDlg, idTestCipher); - SendMessage (hwndDlg, WM_INITDIALOG, 0, 0); - return 1; - } - - if (hw == CBN_SELCHANGE && lw == IDC_KEY_SIZE) - { - // NOP - return 1; - } - - if (lw == IDC_RESET) - { - ResetCipherTest(hwndDlg, idTestCipher); - - return 1; - } - - if (lw == IDC_AUTO) - { - WaitCursor (); - if (!AutoTestAlgorithms()) - { - ShowWindow(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), SW_SHOWNORMAL); - SetWindowTextW(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), GetString ("TESTS_FAILED")); - } - else - { - ShowWindow(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), SW_SHOWNORMAL); - SetWindowTextW(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), GetString ("TESTS_PASSED")); - ShowWindow(GetDlgItem(hwndDlg, IDC_REDTICK), SW_SHOWNORMAL); - } - NormalCursor (); - - return 1; - - } - - if (lw == IDC_XTS_MODE_ENABLED) - { - bXTSTestEnabled = GetCheckBox (hwndDlg, IDC_XTS_MODE_ENABLED); - EnableWindow (GetDlgItem (hwndDlg, IDC_SECONDARY_KEY), bXTSTestEnabled); - EnableWindow (GetDlgItem (hwndDlg, IDT_SECONDARY_KEY), bXTSTestEnabled); - EnableWindow (GetDlgItem (hwndDlg, IDC_TEST_BLOCK_NUMBER), bXTSTestEnabled); - EnableWindow (GetDlgItem (hwndDlg, IDT_TEST_BLOCK_NUMBER), bXTSTestEnabled); - EnableWindow (GetDlgItem (hwndDlg, IDT_TEST_DATA_UNIT_NUMBER), bXTSTestEnabled); - EnableWindow (GetDlgItem (hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), bXTSTestEnabled); - if (bXTSTestEnabled) - SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_SETCURSEL, 0,0); - } - - if (lw == IDOK || lw == IDC_ENCRYPT || lw == IDC_DECRYPT) - { - char key[128+1], inputtext[128+1], secondaryKey[64+1], dataUnitNo[16+1]; - wchar_t szTmp[128+1]; - int ks, pt, n, tlen, blockNo = 0; - BOOL bEncrypt; - - ShowWindow(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), SW_HIDE); - ShowWindow(GetDlgItem(hwndDlg, IDC_REDTICK), SW_HIDE); - - ks = (int) SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_GETCURSEL, 0,0); - ks = (int) SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_GETITEMDATA, ks,0); - pt = (int) SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_GETITEMDATA, 0,0); - - bEncrypt = lw == IDC_ENCRYPT; - - memset(key,0,sizeof(key)); - memset(szTmp,0,sizeof(szTmp)); - n = GetWindowText(GetDlgItem(hwndDlg, IDC_KEY), szTmp, ARRAYSIZE(szTmp)); - if (n != ks * 2) - { - Warning ("TEST_KEY_SIZE", hwndDlg); - return 1; - } - - for (n = 0; n < ks; n ++) - { - wchar_t szTmp2[3], *ptr; - long x; - - szTmp2[2] = 0; - szTmp2[0] = szTmp[n * 2]; - szTmp2[1] = szTmp[n * 2 + 1]; - - x = wcstol(szTmp2, &ptr, 16); - - key[n] = (char) x; - } - - memset(inputtext, 0, sizeof(inputtext)); - memset(secondaryKey, 0, sizeof(secondaryKey)); - memset(dataUnitNo, 0, sizeof(dataUnitNo)); - memset(szTmp, 0, sizeof(szTmp)); - - if (bEncrypt) - { - n = GetWindowText(GetDlgItem(hwndDlg, IDC_PLAINTEXT), szTmp, ARRAYSIZE(szTmp)); - } - else - { - n = GetWindowText(GetDlgItem(hwndDlg, IDC_CIPHERTEXT), szTmp, ARRAYSIZE(szTmp)); - } - - if (n != pt * 2) - { - if (bEncrypt) - { - Warning ("TEST_PLAINTEXT_SIZE", hwndDlg); - return 1; - } - else - { - Warning ("TEST_CIPHERTEXT_SIZE", hwndDlg); - return 1; - } - } - - for (n = 0; n < pt; n ++) - { - wchar_t szTmp2[3], *ptr; - long x; - - szTmp2[2] = 0; - szTmp2[0] = szTmp[n * 2]; - szTmp2[1] = szTmp[n * 2 + 1]; - - x = wcstol(szTmp2, &ptr, 16); - - inputtext[n] = (char) x; - } - - // XTS - if (bXTSTestEnabled) - { - // Secondary key - - if (GetWindowText(GetDlgItem(hwndDlg, IDC_SECONDARY_KEY), szTmp, ARRAYSIZE(szTmp)) != 64) - { - Warning ("TEST_INCORRECT_SECONDARY_KEY_SIZE", hwndDlg); - return 1; - } - - for (n = 0; n < 64; n ++) - { - wchar_t szTmp2[3], *ptr; - long x; - - szTmp2[2] = 0; - szTmp2[0] = szTmp[n * 2]; - szTmp2[1] = szTmp[n * 2 + 1]; - - x = wcstol(szTmp2, &ptr, 16); - - secondaryKey[n] = (char) x; - } - - // Data unit number - - tlen = GetWindowText(GetDlgItem(hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), szTmp, ARRAYSIZE(szTmp)); - - if (tlen > 16 || tlen < 1) - { - Warning ("TEST_INCORRECT_TEST_DATA_UNIT_SIZE", hwndDlg); - return 1; - } - - LeftPadString (szTmp, tlen, 16, L'0'); - - for (n = 0; n < 16; n ++) - { - wchar_t szTmp2[3], *ptr; - long x; - - szTmp2[2] = 0; - szTmp2[0] = szTmp[n * 2]; - szTmp2[1] = szTmp[n * 2 + 1]; - - x = wcstol(szTmp2, &ptr, 16); - - dataUnitNo[n] = (char) x; - } - - // Block number - - blockNo = (int) SendMessage (GetDlgItem (hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_GETCURSEL, 0, 0), 0); - } // if (bXTSTestEnabled) - - - /* Perform the actual tests */ - - if (ks != CB_ERR && pt != CB_ERR) - { - char tmp[128]; - int tmpRetVal; - - /* Copy the plain/ciphertext */ - memcpy(tmp,inputtext, pt); - - if (bXTSTestEnabled) - { - UINT64_STRUCT structDataUnitNo; - - /* XTS mode */ - - ci = crypto_open (); - if (!ci) - return 1; - - ci->mode = XTS; - - for (ci->ea = EAGetFirst (); ci->ea != 0 ; ci->ea = EAGetNext (ci->ea)) - if (EAGetCipherCount (ci->ea) == 1 && EAGetFirstCipher (ci->ea) == idTestCipher) - break; - - if ((tmpRetVal = EAInit (ci->ea, (unsigned char *) key, ci->ks)) != ERR_SUCCESS) - { - handleError (hwndDlg, tmpRetVal, SRC_POS); - crypto_close (ci); - return 1; - } - - memcpy (&ci->k2, secondaryKey, sizeof (secondaryKey)); - if (!EAInitMode (ci)) - { - crypto_close (ci); - return 1; - } - - structDataUnitNo.Value = BE64(((unsigned __int64 *)dataUnitNo)[0]); - - if (bEncrypt) - EncryptBufferXTS ((unsigned char *) tmp, pt, &structDataUnitNo, blockNo, (unsigned char *) (ci->ks), (unsigned char *) ci->ks2, idTestCipher); - else - DecryptBufferXTS ((unsigned char *) tmp, pt, &structDataUnitNo, blockNo, (unsigned char *) (ci->ks), (unsigned char *) ci->ks2, idTestCipher); - - crypto_close (ci); - } - else - { - - CipherInit2(idTestCipher, key, ks_tmp, ks); - - if (bEncrypt) - { - EncipherBlock(idTestCipher, tmp, ks_tmp); - } - else - { - DecipherBlock(idTestCipher, tmp, ks_tmp); - } - - } - *szTmp = 0; - - for (n = 0; n < pt; n ++) - { - wchar_t szTmp2[3]; - StringCbPrintfW(szTmp2, sizeof(szTmp2), L"%02x", (int)((unsigned char)tmp[n])); - StringCbCatW(szTmp, sizeof(szTmp), szTmp2); - } - - if (bEncrypt) - SetWindowText(GetDlgItem(hwndDlg,IDC_CIPHERTEXT), szTmp); - else - SetWindowText(GetDlgItem(hwndDlg,IDC_PLAINTEXT), szTmp); - } - - return 1; - } - - if (lw == IDCLOSE || lw == IDCANCEL) - { - idTestCipher = -1; - EndDialog (hwndDlg, 0); - return 1; - } - break; - - case WM_CLOSE: - idTestCipher = -1; - EndDialog (hwndDlg, 0); - return 1; - } - - return 0; -} - -void -ResetCipherTest(HWND hwndDlg, int idTestCipher) -{ - int ndx; - - ShowWindow(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), SW_HIDE); - ShowWindow(GetDlgItem(hwndDlg, IDC_REDTICK), SW_HIDE); - - EnableWindow(GetDlgItem(hwndDlg,IDC_KEY_SIZE), FALSE); - - /* Setup the keysize and plaintext sizes for the selected cipher */ - - SendMessage (GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_RESETCONTENT, 0,0); - SendMessage (GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_RESETCONTENT, 0,0); - SendMessage (GetDlgItem(hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_RESETCONTENT, 0,0); - - ndx = (int) SendMessage (GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_ADDSTRING, 0,(LPARAM) L"64"); - SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_SETITEMDATA, ndx,(LPARAM) 8); - SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_SETCURSEL, ndx,0); - - for (ndx = 0; ndx < BLOCKS_PER_XTS_DATA_UNIT; ndx++) - { - wchar_t tmpStr [16]; - - StringCbPrintfW (tmpStr, sizeof(tmpStr), L"%d", ndx); - - ndx = (int) SendMessage (GetDlgItem(hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_ADDSTRING, 0,(LPARAM) tmpStr); - SendMessage(GetDlgItem(hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_SETITEMDATA, ndx,(LPARAM) ndx); - } - - SendMessage(GetDlgItem(hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_SETCURSEL, 0, 0); - - SetWindowText(GetDlgItem(hwndDlg, IDC_SECONDARY_KEY), L"0000000000000000000000000000000000000000000000000000000000000000"); - SetWindowText(GetDlgItem(hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), L"0"); - - SetWindowText(GetDlgItem(hwndDlg, IDC_PLAINTEXT), L"0000000000000000"); - SetWindowText(GetDlgItem(hwndDlg, IDC_CIPHERTEXT), L"0000000000000000"); - - if (idTestCipher == AES || idTestCipher == SERPENT || idTestCipher == TWOFISH) - { - ndx = (int) SendMessage (GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_ADDSTRING, 0,(LPARAM) L"256"); - SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_SETITEMDATA, ndx,(LPARAM) 32); - SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_SETCURSEL, ndx,0); - - SendMessage (GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_RESETCONTENT, 0,0); - ndx = (int) SendMessage (GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_ADDSTRING, 0,(LPARAM) L"128"); - SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_SETITEMDATA, ndx,(LPARAM) 16); - SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_SETCURSEL, ndx,0); - - SetWindowText(GetDlgItem(hwndDlg, IDC_KEY), L"0000000000000000000000000000000000000000000000000000000000000000"); - SetWindowText(GetDlgItem(hwndDlg, IDC_PLAINTEXT), L"00000000000000000000000000000000"); - SetWindowText(GetDlgItem(hwndDlg, IDC_CIPHERTEXT), L"00000000000000000000000000000000"); - } -} - -#endif // #ifndef SETUP - - -BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - int nChoiceIDs [MAX_MULTI_CHOICES+1] = { IDC_MULTI_CHOICE_MSG, IDC_CHOICE1, IDC_CHOICE2, IDC_CHOICE3, - IDC_CHOICE4, IDC_CHOICE5, IDC_CHOICE6, IDC_CHOICE7, IDC_CHOICE8, IDC_CHOICE9, IDC_CHOICE10 }; - int nBaseButtonWidth = 0; - int nBaseButtonHeight = 0; - int nActiveChoices = -1; - int nStr = 0; - int vertSubOffset, horizSubOffset, vertMsgHeightOffset; - int vertOffset = 0; - int nLongestButtonCaptionWidth = 6; - int nLongestButtonCaptionCharLen = 1; - int nTextGfxLineHeight = 0; - int nMainTextLenInChars = 0; - int newLineSeqCount = 0; - RECT rec, wrec, wtrec, trec; - BOOL bResolve; - - WORD lw = LOWORD (wParam); - - switch (uMsg) - { - case WM_INITDIALOG: - { - char **pStr = (char **) ((MULTI_CHOICE_DLGPROC_PARAMS *) lParam)->strings; - char **pStrOrig = pStr; - wchar_t **pwStr = (wchar_t **) ((MULTI_CHOICE_DLGPROC_PARAMS *) lParam)->strings; - wchar_t **pwStrOrig = pwStr; - - LocalizeDialog (hwndDlg, NULL); - - SetWindowPos (hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - SetWindowPos (hwndDlg, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - - bResolve = (*pStr == NULL); - - // Style - if (((MULTI_CHOICE_DLGPROC_PARAMS *) lParam)->bold) - { - SendMessage (GetDlgItem (hwndDlg, IDC_MULTI_CHOICE_MSG), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - } - - // Process the strings - pStr++; - pwStr++; - - do - { - if (*pStr != 0) - { - SetWindowTextW (GetDlgItem(hwndDlg, nChoiceIDs[nStr]), bResolve ? GetString(*pStr) : *pwStr); - - if (nStr > 0) - { - nLongestButtonCaptionWidth = max ( - GetTextGfxWidth (GetDlgItem(hwndDlg, IDC_CHOICE1), - bResolve ? GetString(*pStr) : *pwStr, - hUserFont), - nLongestButtonCaptionWidth); - - nLongestButtonCaptionCharLen = max (nLongestButtonCaptionCharLen, - (int) wcslen ((const wchar_t *) (bResolve ? GetString(*pStr) : *pwStr))); - } - - nActiveChoices++; - pStr++; - pwStr++; - } - else - { - ShowWindow(GetDlgItem(hwndDlg, nChoiceIDs[nStr]), SW_HIDE); - } - nStr++; - - } while (nStr < MAX_MULTI_CHOICES+1); - - // Length of main message in characters (not bytes) - nMainTextLenInChars = (int) wcslen ((const wchar_t *) (bResolve ? GetString(*(pStrOrig+1)) : *(pwStrOrig+1))); - - if (nMainTextLenInChars > 200 - && nMainTextLenInChars / nLongestButtonCaptionCharLen >= 10) - { - // As the main text is longer than 200 characters, we will "pad" the widest button caption with - // spaces (if it is not wide enough) so as to increase the width of the whole dialog window. - // Otherwise, it would look too tall (dialog boxes look better when they are more wide than tall). - nLongestButtonCaptionWidth = CompensateXDPI (max ( - nLongestButtonCaptionWidth, - min (350, nMainTextLenInChars))); - } - - // Get the window coords - GetWindowRect(hwndDlg, &wrec); - - // Get the base button size - GetClientRect(GetDlgItem(hwndDlg, IDC_CHOICE1), &rec); - nBaseButtonWidth = rec.right + 2; - nBaseButtonHeight = rec.bottom + 2; - - // Increase in width based on the gfx length of the widest button caption - horizSubOffset = min (CompensateXDPI (500), max (0, nLongestButtonCaptionWidth + CompensateXDPI (50) - nBaseButtonWidth)); - - // Vertical "title bar" offset - GetClientRect(hwndDlg, &wtrec); - vertOffset = wrec.bottom - wrec.top - wtrec.bottom - GetSystemMetrics(SM_CYFIXEDFRAME); - - // Height/width of the message text - GetClientRect(GetDlgItem(hwndDlg, IDC_MULTI_CHOICE_MSG), &trec); - - // Determine the number of newlines contained in the message text - { - int64 offset = -1; - - do - { - offset = FindString ((char *) (bResolve ? GetString(*(pStrOrig+1)) : *(pwStrOrig+1)), - (char *) L"\n", - nMainTextLenInChars * 2, - (int) wcslen (L"\n") * 2, - offset + 1); - - newLineSeqCount++; - - } while (offset != -1); - } - - nTextGfxLineHeight = GetTextGfxHeight (GetDlgItem(hwndDlg, IDC_MULTI_CHOICE_MSG), - bResolve ? GetString(*(pStrOrig+1)) : *(pwStrOrig+1), - hUserFont); - - vertMsgHeightOffset = ((GetTextGfxWidth (GetDlgItem(hwndDlg, IDC_MULTI_CHOICE_MSG), - bResolve ? GetString(*(pStrOrig+1)) : *(pwStrOrig+1), - hUserFont) / (trec.right + horizSubOffset) + 1) * nTextGfxLineHeight) - trec.bottom; - - vertMsgHeightOffset = min (CompensateYDPI (350), vertMsgHeightOffset + newLineSeqCount * nTextGfxLineHeight + (trec.bottom + vertMsgHeightOffset) / 10); // As reserve, we are adding 10% and the number of lines equal to the number of newlines in the message - - // Reduction in height according to the number of shown buttons - vertSubOffset = ((MAX_MULTI_CHOICES - nActiveChoices) * nBaseButtonHeight); - - if (horizSubOffset > 0 - || vertMsgHeightOffset > 0 - || vertOffset > 0) - { - // Resize/move each button if necessary - for (nStr = 1; nStr < MAX_MULTI_CHOICES+1; nStr++) - { - GetWindowRect(GetDlgItem(hwndDlg, nChoiceIDs[nStr]), &rec); - - MoveWindow (GetDlgItem(hwndDlg, nChoiceIDs[nStr]), - rec.left - wrec.left - GetSystemMetrics(SM_CXFIXEDFRAME), - rec.top - wrec.top - vertOffset + vertMsgHeightOffset, - nBaseButtonWidth + horizSubOffset, - nBaseButtonHeight, - TRUE); - } - - // Resize/move the remaining GUI elements - GetWindowRect(GetDlgItem(hwndDlg, IDC_MULTI_CHOICE_MSG), &rec); - GetClientRect(GetDlgItem(hwndDlg, IDC_MULTI_CHOICE_MSG), &trec); - MoveWindow (GetDlgItem(hwndDlg, IDC_MULTI_CHOICE_MSG), - rec.left - wrec.left - GetSystemMetrics(SM_CXFIXEDFRAME), - rec.top - wrec.top - vertOffset, - trec.right + 2 + horizSubOffset, - trec.bottom + 2 + vertMsgHeightOffset, - TRUE); - - GetWindowRect(GetDlgItem(hwndDlg, IDC_MC_DLG_HR1), &rec); - GetClientRect(GetDlgItem(hwndDlg, IDC_MC_DLG_HR1), &trec); - MoveWindow (GetDlgItem(hwndDlg, IDC_MC_DLG_HR1), - rec.left - wrec.left - GetSystemMetrics(SM_CXFIXEDFRAME), - rec.top - wrec.top - vertOffset, - trec.right + 2 + horizSubOffset, - trec.bottom + 2, - TRUE); - - GetWindowRect(GetDlgItem(hwndDlg, IDC_MC_DLG_HR2), &rec); - GetClientRect(GetDlgItem(hwndDlg, IDC_MC_DLG_HR2), &trec); - MoveWindow (GetDlgItem(hwndDlg, IDC_MC_DLG_HR2), - rec.left - wrec.left - GetSystemMetrics(SM_CXFIXEDFRAME), - rec.top - wrec.top - vertOffset + vertMsgHeightOffset, - trec.right + 2 + horizSubOffset, - trec.bottom + 2, - TRUE); - } - - // Resize the window according to number of shown buttons and the longest button caption - MoveWindow (hwndDlg, - wrec.left - horizSubOffset / 2, - wrec.top + vertSubOffset / 2 - vertMsgHeightOffset / 2, - wrec.right - wrec.left + horizSubOffset, - wrec.bottom - wrec.top - vertSubOffset + 1 + vertMsgHeightOffset, - TRUE); - - DisableCloseButton (hwndDlg); - - return 1; - } - - case WM_COMMAND: - - if (lw == IDCLOSE || lw == IDCANCEL) - { - EndDialog (hwndDlg, 0); - return 1; - } - - for (nStr = 1; nStr < MAX_MULTI_CHOICES+1; nStr++) - { - if (lw == nChoiceIDs[nStr]) - { - EndDialog (hwndDlg, nStr); - return 1; - } - } - break; - - case WM_CLOSE: - // This prevents the window from being closed by pressing Alt-F4 (the Close button is hidden). - // Note that the OS handles modal MessageBox() dialog windows the same way. - return 1; - } - - return 0; -} - - -BOOL CheckCapsLock (HWND hwnd, BOOL quiet) -{ - if ((GetKeyState(VK_CAPITAL) & 1) != 0) - { - if (!quiet) - { - MessageBoxW (hwnd, GetString ("CAPSLOCK_ON"), lpszTitle, MB_ICONEXCLAMATION); - } - return TRUE; - } - return FALSE; -} - - -// Checks whether the file extension is not used for executable files or similarly problematic, which often -// causes Windows and antivirus software to interfere with the container. -BOOL CheckFileExtension (wchar_t *fileName) -{ - int i = 0; - wchar_t *ext = wcsrchr (fileName, L'.'); - static wchar_t *problemFileExt[] = { - // These are protected by the Windows Resource Protection - L".asa", L".asp", L".aspx", L".ax", L".bas", L".bat", L".bin", L".cer", L".chm", L".clb", L".cmd", L".cnt", L".cnv", - L".com", L".cpl", L".cpx", L".crt", L".csh", L".dll", L".drv", L".dtd", L".exe", L".fxp", L".grp", L".h1s", L".hlp", - L".hta", L".ime", L".inf", L".ins", L".isp", L".its", L".js", L".jse", L".ksh", L".lnk", L".mad", L".maf", L".mag", - L".mam", L".man", L".maq", L".mar", L".mas", L".mat", L".mau", L".mav", L".maw", L".mda", L".mdb", L".mde", L".mdt", - L".mdw", L".mdz", L".msc", L".msi", L".msp", L".mst", L".mui", L".nls", L".ocx", L".ops", L".pal", L".pcd", L".pif", - L".prf", L".prg", L".pst", L".reg", L".scf", L".scr", L".sct", L".shb", L".shs", L".sys", L".tlb", L".tsp", L".url", - L".vb", L".vbe", L".vbs", L".vsmacros", L".vss", L".vst", L".vsw", L".ws", L".wsc", L".wsf", L".wsh", L".xsd", L".xsl", - // These additional file extensions are usually watched by antivirus programs - L".386", L".acm", L".ade", L".adp", L".ani", L".app", L".asd", L".asf", L".asx", L".awx", L".ax", L".boo", L".bz2", L".cdf", - L".class", L".dhtm", L".dhtml",L".dlo", L".emf", L".eml", L".flt", L".fot", L".gz", L".hlp", L".htm", L".html", L".ini", - L".j2k", L".jar", L".jff", L".jif", L".jmh", L".jng", L".jp2", L".jpe", L".jpeg", L".jpg", L".lsp", L".mod", L".nws", - L".obj", L".olb", L".osd", L".ov1", L".ov2", L".ov3", L".ovl", L".ovl", L".ovr", L".pdr", L".pgm", L".php", L".pkg", - L".pl", L".png", L".pot", L".pps", L".ppt", L".ps1", L".ps1xml", L".psc1", L".rar", L".rpl", L".rtf", L".sbf", L".script", L".sh", L".sha", L".shtm", - L".shtml", L".spl", L".swf", L".tar", L".tgz", L".tmp", L".ttf", L".vcs", L".vlm", L".vxd", L".vxo", L".wiz", L".wll", L".wmd", - L".wmf", L".wms", L".wmz", L".wpc", L".wsc", L".wsh", L".wwk", L".xhtm", L".xhtml", L".xl", L".xml", L".zip", L".7z", 0}; - - if (!ext) - return FALSE; - - while (problemFileExt[i]) - { - if (!_wcsicmp (ext, problemFileExt[i++])) - return TRUE; - } - - return FALSE; -} - -void CorrectFileName (wchar_t* fileName) -{ - /* replace '/' by '\' */ - size_t i, len = wcslen (fileName); - for (i = 0; i < len; i++) - { - if (fileName [i] == L'/') - fileName [i] = L'\\'; - } -} - -void IncreaseWrongPwdRetryCount (int count) -{ - WrongPwdRetryCounter += count; -} - - -void ResetWrongPwdRetryCount (void) -{ - WrongPwdRetryCounter = 0; -} - - -BOOL WrongPwdRetryCountOverLimit (void) -{ - return (WrongPwdRetryCounter > TC_TRY_HEADER_BAK_AFTER_NBR_WRONG_PWD_TRIES); -} - -DWORD GetUsedLogicalDrives (void) -{ - DWORD dwUsedDrives = GetLogicalDrives(); - if (!bShowDisconnectedNetworkDrives) - { - static DWORD g_dwLastMappedDrives = 0; - static time_t g_lastCallTime = 0; - - EnterCriticalSection (&csWNetCalls); - - finally_do ({ LeaveCriticalSection (&csWNetCalls); }); - - /* update values every 2 seconds to reduce CPU consumption */ - if ((time (NULL) - g_lastCallTime) > 2) - { - /* detect disconnected mapped network shares and removed - * their associated drives from the list - */ - WCHAR remotePath[512]; - WCHAR drive[3] = {L'A', L':', 0}; - DWORD dwLen, status; - g_dwLastMappedDrives = 0; - for (WCHAR i = 0; i <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; i++) - { - if ((dwUsedDrives & (1 << i)) == 0) - { - drive[0] = L'A' + i; - dwLen = ARRAYSIZE (remotePath); - status = WNetGetConnection (drive, remotePath, &dwLen); - if ((NO_ERROR == status) || (status == ERROR_CONNECTION_UNAVAIL)) - { - /* this is a mapped network share, mark it as used */ - g_dwLastMappedDrives |= (1 << i); - } - } - } - - g_lastCallTime = time (NULL); - } - - dwUsedDrives |= g_dwLastMappedDrives; - } - - return dwUsedDrives; -} - - -int GetFirstAvailableDrive () -{ - DWORD dwUsedDrives = GetUsedLogicalDrives(); - int i, drive; - - /* let A: and B: be used as last resort since they can introduce side effects */ - for (i = 2; i < 28; i++) - { - drive = (i < 26) ? i : (i - 26); - if (!(dwUsedDrives & 1 << drive)) - return i; - } - - return -1; -} - - -int GetLastAvailableDrive () -{ - DWORD dwUsedDrives = GetUsedLogicalDrives(); - int i; - - for (i = 25; i >= 0; i--) - { - if (!(dwUsedDrives & 1 << i)) - return i; - } - - return -1; -} - - -BOOL IsDriveAvailable (int driveNo) -{ - return (GetUsedLogicalDrives() & (1 << driveNo)) == 0; -} - - -BOOL IsDeviceMounted (wchar_t *deviceName) -{ - BOOL bResult = FALSE; - DWORD dwResult; - HANDLE dev = INVALID_HANDLE_VALUE; - - if ((dev = CreateFile (deviceName, - GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, - OPEN_EXISTING, - 0, - NULL)) != INVALID_HANDLE_VALUE) - { - bResult = DeviceIoControl (dev, FSCTL_IS_VOLUME_MOUNTED, NULL, 0, NULL, 0, &dwResult, NULL); - CloseHandle (dev); - } - - return bResult; -} - - -int DriverUnmountVolume (HWND hwndDlg, int nDosDriveNo, BOOL forced) -{ - UNMOUNT_STRUCT unmount; - DWORD dwResult; - VOLUME_PROPERTIES_STRUCT prop; - BOOL bResult; - WCHAR wszLabel[33] = {0}; - BOOL bDriverSetLabel = FALSE; - - memset (&prop, 0, sizeof(prop)); - prop.driveNo = nDosDriveNo; - - if ( DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL) - && prop.driveNo == nDosDriveNo - ) - { - memcpy (wszLabel, prop.wszLabel, sizeof (wszLabel)); - bDriverSetLabel = prop.bDriverSetLabel; - } - - unmount.nDosDriveNo = nDosDriveNo; - unmount.ignoreOpenFiles = forced; - - bResult = DeviceIoControl (hDriver, TC_IOCTL_DISMOUNT_VOLUME, &unmount, - sizeof (unmount), &unmount, sizeof (unmount), &dwResult, NULL); - - if (bResult == FALSE) - { - handleWin32Error (hwndDlg, SRC_POS); - return 1; - } - else if ((unmount.nReturnCode == ERR_SUCCESS) && bDriverSetLabel && wszLabel[0]) - UpdateDriveCustomLabel (nDosDriveNo, wszLabel, FALSE); - -#ifdef TCMOUNT - - if (unmount.nReturnCode == ERR_SUCCESS - && unmount.HiddenVolumeProtectionTriggered - && !VolumeNotificationsList.bHidVolDamagePrevReported [nDosDriveNo] - && !Silent) - { - wchar_t msg[4096]; - - VolumeNotificationsList.bHidVolDamagePrevReported [nDosDriveNo] = TRUE; - StringCbPrintfW (msg, sizeof(msg), GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), nDosDriveNo + L'A'); - SetForegroundWindow (hwndDlg); - MessageBoxW (hwndDlg, msg, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); - } - -#endif // #ifdef TCMOUNT - - return unmount.nReturnCode; -} - - -void BroadcastDeviceChange (WPARAM message, int nDosDriveNo, DWORD driveMap) -{ - DEV_BROADCAST_VOLUME dbv; - DWORD_PTR dwResult; - LONG eventId = 0; - int i; - - if (DeviceChangeBroadcastDisabled) - return; - - if (message == DBT_DEVICEARRIVAL) - eventId = SHCNE_DRIVEADD; - else if (message == DBT_DEVICEREMOVECOMPLETE) - eventId = SHCNE_DRIVEREMOVED; - else if (IsOSAtLeast (WIN_7) && message == DBT_DEVICEREMOVEPENDING) // Explorer on Windows 7 holds open handles of all drives when 'Computer' is expanded in navigation pane. SHCNE_DRIVEREMOVED must be used as DBT_DEVICEREMOVEPENDING is ignored. - eventId = SHCNE_DRIVEREMOVED; - - if (driveMap == 0) - driveMap = (1 << nDosDriveNo); - - if (eventId != 0) - { - for (i = 0; i < 26; i++) - { - if (driveMap & (1 << i)) - { - wchar_t root[] = { (wchar_t) i + L'A', L':', L'\\', 0 }; - SHChangeNotify (eventId, SHCNF_PATH, root, NULL); - - - } - } - } - - dbv.dbcv_size = sizeof (dbv); - dbv.dbcv_devicetype = DBT_DEVTYP_VOLUME; - dbv.dbcv_reserved = 0; - dbv.dbcv_unitmask = driveMap; - dbv.dbcv_flags = 0; - - UINT timeOut = 1000; - - // SHChangeNotify() works on Vista, so the Explorer does not require WM_DEVICECHANGE - if (CurrentOSMajor >= 6) - timeOut = 100; - - IgnoreWmDeviceChange = TRUE; - SendMessageTimeout (HWND_BROADCAST, WM_DEVICECHANGE, message, (LPARAM)(&dbv), SMTO_ABORTIFHUNG, timeOut, &dwResult); - - // Explorer prior Vista sometimes fails to register a new drive - if (CurrentOSMajor < 6 && message == DBT_DEVICEARRIVAL) - SendMessageTimeout (HWND_BROADCAST, WM_DEVICECHANGE, message, (LPARAM)(&dbv), SMTO_ABORTIFHUNG, 200, &dwResult); - - IgnoreWmDeviceChange = FALSE; -} - -BOOL GetPhysicalDriveAlignment(UINT nDriveNumber, STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR* pDesc) -{ - DWORD dwRet = NO_ERROR; - - if (!pDesc) - return FALSE; - - // Format physical drive path (may be '\\.\PhysicalDrive0', '\\.\PhysicalDrive1' and so on). - TCHAR strDrivePath[512]; - StringCbPrintf(strDrivePath, sizeof(strDrivePath), _T("\\\\.\\PhysicalDrive%u"), nDriveNumber); - - // Get a handle to physical drive - HANDLE hDevice = ::CreateFile(strDrivePath, 0, FILE_SHARE_READ, - NULL, OPEN_EXISTING, 0, NULL); - - if(INVALID_HANDLE_VALUE == hDevice) - return FALSE; - - // Set the input data structure - STORAGE_PROPERTY_QUERY storagePropertyQuery; - ZeroMemory(&storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY)); - storagePropertyQuery.PropertyId = StorageAccessAlignmentProperty; - storagePropertyQuery.QueryType = PropertyStandardQuery; - - // Get the necessary output buffer size - DWORD dwBytesReturned = 0; - BOOL bRet = ::DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY, - &storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY), - pDesc, sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR), - &dwBytesReturned, NULL); - dwRet = ::GetLastError(); - ::CloseHandle(hDevice); - - if (!bRet) - { - SetLastError (dwRet); - return FALSE; - } - else - return TRUE; -} - -/************************************************************/ - -// implementation of the generic wait dialog mechanism - -static UINT g_wmWaitDlg = ::RegisterWindowMessage(L"VeraCryptWaitDlgMessage"); - -typedef struct -{ - HWND hwnd; - void* pArg; - WaitThreadProc callback; -} WaitThreadParam; - -static void _cdecl WaitThread (void* pParam) -{ - WaitThreadParam* pThreadParam = (WaitThreadParam*) pParam; - - pThreadParam->callback(pThreadParam->pArg, pThreadParam->hwnd); - - /* close the wait dialog */ - PostMessage (pThreadParam->hwnd, g_wmWaitDlg, 0, 0); -} - -BOOL CALLBACK WaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - WaitThreadParam* thParam = (WaitThreadParam*) lParam; - - // set the progress bar type to MARQUEE (indefinite progress) - HWND hProgress = GetDlgItem (hwndDlg, IDC_WAIT_PROGRESS_BAR); - if (hProgress) - { - SetWindowLongPtrW (hProgress, GWL_STYLE, PBS_MARQUEE | GetWindowLongPtrW (hProgress, GWL_STYLE)); - ::SendMessageW(hProgress, PBM_SETMARQUEE, (WPARAM) TRUE, (LPARAM) 0); - } - - thParam->hwnd = hwndDlg; - - // For now, we don't have system menu is the resources but we leave this code - // if it is enabled in the future - HMENU hSysMenu = GetSystemMenu(hwndDlg, FALSE); - if (hSysMenu) - { - //disable the X - EnableMenuItem(hSysMenu,SC_CLOSE, MF_BYCOMMAND|MF_GRAYED); - - // set icons - HICON hIcon = (HICON)::LoadImage(hInst, MAKEINTRESOURCE(IDI_TRUECRYPT_ICON), IMAGE_ICON, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR); - ::SendMessage(hwndDlg, WM_SETICON, TRUE, (LPARAM)hIcon); - HICON hIconSmall = (HICON)::LoadImage(hInst, MAKEINTRESOURCE(IDI_TRUECRYPT_ICON), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR); - ::SendMessage(hwndDlg, WM_SETICON, FALSE, (LPARAM)hIconSmall); - } - - LocalizeDialog (hwndDlg, NULL); - _beginthread(WaitThread, 0, thParam); - return 0; - } - - case WM_COMMAND: - - if (lw == IDOK || lw == IDCANCEL) - return 1; - else - return 0; - - default: - if (msg == g_wmWaitDlg) - { - EndDialog (hwndDlg, IDOK); - return 1; - } - return 0; - } -} - - -void BringToForeground(HWND hWnd) -{ - if(!::IsWindow(hWnd)) return; - - DWORD lockTimeOut = 0; - HWND hCurrWnd = ::GetForegroundWindow(); - DWORD dwThisTID = ::GetCurrentThreadId(), - dwCurrTID = ::GetWindowThreadProcessId(hCurrWnd,0); - - if (hCurrWnd != hWnd) - { - if(dwThisTID != dwCurrTID) - { - ::AttachThreadInput(dwThisTID, dwCurrTID, TRUE); - - ::SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT,0,&lockTimeOut,0); - ::SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT,0,0,SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE); - - ::AllowSetForegroundWindow(ASFW_ANY); - } - - ::SetForegroundWindow(hWnd); - - if(dwThisTID != dwCurrTID) - { - ::SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT,0,(PVOID)lockTimeOut,SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE); - ::AttachThreadInput(dwThisTID, dwCurrTID, FALSE); - } - } - -#ifdef TCMOUNT - if (hWnd == MainDlg) - { - SetFocus (hWnd); - ::SendMessage(hWnd, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hWnd, IDC_DRIVELIST), 1L); - } -#endif -} - -void ShowWaitDialog(HWND hwnd, BOOL bUseHwndAsParent, WaitThreadProc callback, void* pArg) -{ - HWND hParent = (hwnd && bUseHwndAsParent)? hwnd : GetDesktopWindow(); - BOOL bEffectiveHideWaitingDialog = bCmdHideWaitingDialogValid? bCmdHideWaitingDialog : bHideWaitingDialog; - WaitThreadParam threadParam; - threadParam.callback = callback; - threadParam.pArg = pArg; - - if (WaitDialogDisplaying || bEffectiveHideWaitingDialog) - { - if (!WaitDialogDisplaying) WaitCursor (); - callback (pArg, hwnd); - if (!WaitDialogDisplaying) NormalCursor (); - } - else - { - BOOL bIsForeground = FALSE; - WaitDialogDisplaying = TRUE; - if (hwnd) - { - if (GetForegroundWindow () == hwnd) - bIsForeground = TRUE; - EnableWindow (hwnd, FALSE); - } - else - EnableWindow (MainDlg, FALSE); - finally_do_arg2 (HWND, hwnd, BOOL, bIsForeground, { if (finally_arg) {EnableWindow(finally_arg, TRUE); if (finally_arg2) BringToForeground (finally_arg);} else EnableWindow (MainDlg, TRUE);}); - - DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_STATIC_MODAL_WAIT_DLG), hParent, - (DLGPROC) WaitDlgProc, (LPARAM) &threadParam); - - WaitDialogDisplaying = FALSE; - } -} - -/************************************************************************/ - -static BOOL PerformMountIoctl (MOUNT_STRUCT* pmount, LPDWORD pdwResult, BOOL useVolumeID, BYTE volumeID[VOLUME_ID_SIZE]) -{ - if (useVolumeID) - { - wstring devicePath = FindDeviceByVolumeID (volumeID); - if (devicePath == L"") - { - if (pdwResult) - *pdwResult = 0; - SetLastError (ERROR_PATH_NOT_FOUND); - return FALSE; - } - else - { - BOOL bDevice = FALSE; - CreateFullVolumePath (pmount->wszVolume, sizeof(pmount->wszVolume), devicePath.c_str(), &bDevice); - } - } - - return DeviceIoControl (hDriver, TC_IOCTL_MOUNT_VOLUME, pmount, - sizeof (MOUNT_STRUCT), pmount, sizeof (MOUNT_STRUCT), pdwResult, NULL); -} - -// specific definitions and implementation for support of mount operation -// in wait dialog mechanism - -typedef struct -{ - MOUNT_STRUCT* pmount; - BOOL useVolumeID; - BYTE volumeID[VOLUME_ID_SIZE]; - BOOL* pbResult; - DWORD* pdwResult; - DWORD dwLastError; -} MountThreadParam; - -void CALLBACK MountWaitThreadProc(void* pArg, HWND ) -{ - MountThreadParam* pThreadParam = (MountThreadParam*) pArg; - - *(pThreadParam->pbResult) = PerformMountIoctl (pThreadParam->pmount, pThreadParam->pdwResult, pThreadParam->useVolumeID, pThreadParam->volumeID); - - pThreadParam->dwLastError = GetLastError (); -} - -/************************************************************************/ - -// Use only cached passwords if password = NULL -// -// Returns: -// -1 = user aborted mount / error -// 0 = mount failed -// 1 = mount OK -// 2 = mount OK in shared mode -// -// Note that some code calling this relies on the content of the mountOptions struct -// to remain unmodified (don't remove the 'const' without proper revision). - -int MountVolume (HWND hwndDlg, - int driveNo, - wchar_t *volumePath, - Password *password, - int pkcs5, - int pim, - BOOL truecryptMode, - BOOL cachePassword, - BOOL cachePim, - BOOL sharedAccess, - const MountOptions* const mountOptions, - BOOL quiet, - BOOL bReportWrongPassword) -{ - MOUNT_STRUCT mount; - DWORD dwResult, dwLastError = ERROR_SUCCESS; - BOOL bResult, bDevice; - wchar_t root[MAX_PATH]; - int favoriteMountOnArrivalRetryCount = 0; - BOOL useVolumeID = FALSE; - BYTE volumeID[VOLUME_ID_SIZE] = {0}; - -#ifdef TCMOUNT - if (mountOptions->PartitionInInactiveSysEncScope) - { - if (!CheckSysEncMountWithoutPBA (hwndDlg, volumePath, quiet)) - return -1; - } -#endif - - if (IsMountedVolume (volumePath)) - { - if (!quiet) - Error ("VOL_ALREADY_MOUNTED", hwndDlg); - return -1; - } - - if (!IsDriveAvailable (driveNo)) - { - if (!quiet) - Error ("DRIVE_LETTER_UNAVAILABLE", hwndDlg); - - return -1; - } - - // If using cached passwords, check cache status first - if (password == NULL && IsPasswordCacheEmpty ()) - return 0; - - ZeroMemory (&mount, sizeof (mount)); - mount.bExclusiveAccess = sharedAccess ? FALSE : TRUE; - mount.SystemFavorite = MountVolumesAsSystemFavorite; - mount.UseBackupHeader = mountOptions->UseBackupHeader; - mount.RecoveryMode = mountOptions->RecoveryMode; - StringCbCopyW (mount.wszLabel, sizeof (mount.wszLabel), mountOptions->Label); - -retry: - mount.nDosDriveNo = driveNo; - mount.bCache = cachePassword; - mount.bCachePim = cachePim; - - mount.bPartitionInInactiveSysEncScope = FALSE; - - if (password != NULL) - mount.VolumePassword = *password; - else - mount.VolumePassword.Length = 0; - - if (!mountOptions->ReadOnly && mountOptions->ProtectHiddenVolume) - { - mount.ProtectedHidVolPassword = mountOptions->ProtectedHidVolPassword; - mount.bProtectHiddenVolume = TRUE; - mount.ProtectedHidVolPkcs5Prf = mountOptions->ProtectedHidVolPkcs5Prf; - mount.ProtectedHidVolPim = mountOptions->ProtectedHidVolPim; - } - else - mount.bProtectHiddenVolume = FALSE; - - mount.bMountReadOnly = mountOptions->ReadOnly; - mount.bMountRemovable = mountOptions->Removable; - mount.bPreserveTimestamp = mountOptions->PreserveTimestamp; - - mount.bMountManager = TRUE; - mount.pkcs5_prf = pkcs5; - mount.bTrueCryptMode = truecryptMode; - mount.VolumePim = pim; - - // Windows 2000 mount manager causes problems with remounted volumes - if (CurrentOSMajor == 5 && CurrentOSMinor == 0) - mount.bMountManager = FALSE; - - wstring path = volumePath; - if (path.find (L"\\\\?\\") == 0) - { - // Remove \\?\ prefix - path = path.substr (4); - StringCchCopyW (volumePath, TC_MAX_PATH, path.c_str()); - } - - if (path.find (L"Volume{") == 0 && path.rfind (L"}\\") == path.size() - 2) - { - wstring resolvedPath = VolumeGuidPathToDevicePath (path); - - if (!resolvedPath.empty()) - StringCchCopyW (volumePath, TC_MAX_PATH, resolvedPath.c_str()); - } - - if ((path.length () >= 3) && (_wcsnicmp (path.c_str(), L"ID:", 3) == 0)) - { - std::vector arr; - if ( (path.length() == (3 + 2*VOLUME_ID_SIZE)) - && HexWideStringToArray (path.c_str() + 3, arr) - && (arr.size() == VOLUME_ID_SIZE) - ) - { - useVolumeID = TRUE; - bDevice = TRUE; - memcpy (volumeID, &arr[0], VOLUME_ID_SIZE); - } - else - { - if (!quiet) - Error ("VOLUME_ID_INVALID", hwndDlg); - - SetLastError (ERROR_INVALID_PARAMETER); - return -1; - } - } - else - CreateFullVolumePath (mount.wszVolume, sizeof(mount.wszVolume), volumePath, &bDevice); - - if (!bDevice) - { - // UNC path - if (path.find (L"\\\\") == 0) - { - StringCbCopyW (mount.wszVolume, sizeof (mount.wszVolume), (L"UNC" + path.substr (1)).c_str()); - } - - if (GetVolumePathName (volumePath, root, ARRAYSIZE (root) - 1)) - { - DWORD bps, flags, d; - if (GetDiskFreeSpace (root, &d, &bps, &d, &d)) - { - mount.BytesPerSector = bps; - mount.BytesPerPhysicalSector = bps; - } - - if (IsOSAtLeast (WIN_VISTA)) - { - if ( (wcslen(root) >= 2) - && (root[1] == L':') - && (towupper(root[0]) >= L'A' && towupper(root[0]) <= L'Z') - ) - { - wstring drivePath = L"\\\\.\\X:"; - HANDLE dev = INVALID_HANDLE_VALUE; - VOLUME_DISK_EXTENTS extents = {0}; - DWORD dwResult = 0; - drivePath[4] = root[0]; - - if ((dev = CreateFile (drivePath.c_str(),0, 0, NULL, OPEN_EXISTING, 0, NULL)) != INVALID_HANDLE_VALUE) - { - if (DeviceIoControl (dev, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &extents, sizeof(extents), &dwResult, NULL)) - { - if (extents.NumberOfDiskExtents > 0) - { - STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR desc; - if (GetPhysicalDriveAlignment (extents.Extents[0].DiskNumber, &desc)) - { - mount.BytesPerSector = desc.BytesPerLogicalSector; - mount.BytesPerPhysicalSector = desc.BytesPerPhysicalSector; - } - } - } - CloseHandle (dev); - } - } - } - - // Read-only host filesystem - if (!mount.bMountReadOnly && GetVolumeInformation (root, NULL, 0, NULL, &d, &flags, NULL, 0)) - mount.bMountReadOnly = (flags & FILE_READ_ONLY_VOLUME) != 0; - } - } - - if (mountOptions->PartitionInInactiveSysEncScope) - { - if (mount.wszVolume == NULL || swscanf_s ((const wchar_t *) mount.wszVolume, - WIDE("\\Device\\Harddisk%d\\Partition"), - &mount.nPartitionInInactiveSysEncScopeDriveNo, - sizeof(mount.nPartitionInInactiveSysEncScopeDriveNo)) != 1) - { - if (!quiet) - Warning ("NO_SYSENC_PARTITION_SELECTED", hwndDlg); - return -1; - } - - mount.bPartitionInInactiveSysEncScope = TRUE; - } - - if (!quiet) - { - MountThreadParam mountThreadParam; - mountThreadParam.pmount = &mount; - mountThreadParam.useVolumeID = useVolumeID; - memcpy (mountThreadParam.volumeID, volumeID, VOLUME_ID_SIZE); - mountThreadParam.pbResult = &bResult; - mountThreadParam.pdwResult = &dwResult; - mountThreadParam.dwLastError = ERROR_SUCCESS; - - ShowWaitDialog (hwndDlg, FALSE, MountWaitThreadProc, &mountThreadParam); - - dwLastError = mountThreadParam.dwLastError; - } - else - { - bResult = PerformMountIoctl (&mount, &dwResult, useVolumeID, volumeID); - - dwLastError = GetLastError (); - } - - burn (&mount.VolumePassword, sizeof (mount.VolumePassword)); - burn (&mount.ProtectedHidVolPassword, sizeof (mount.ProtectedHidVolPassword)); - burn (&mount.pkcs5_prf, sizeof (mount.pkcs5_prf)); - burn (&mount.bTrueCryptMode, sizeof (mount.bTrueCryptMode)); - burn (&mount.ProtectedHidVolPkcs5Prf, sizeof (mount.ProtectedHidVolPkcs5Prf)); - - SetLastError (dwLastError); - if (bResult == FALSE) - { - // Volume already open by another process - if (GetLastError () == ERROR_SHARING_VIOLATION) - { - if (FavoriteMountOnArrivalInProgress && ++favoriteMountOnArrivalRetryCount < 10) - { - Sleep (500); - goto retry; - } - - if (mount.bExclusiveAccess == FALSE) - { - if (!quiet) - Error ("FILE_IN_USE_FAILED", hwndDlg); - - return -1; - } - else - { - if (quiet) - { - mount.bExclusiveAccess = FALSE; - goto retry; - } - - // Ask user - if (IDYES == AskWarnNoYes ("FILE_IN_USE", hwndDlg)) - { - mount.bExclusiveAccess = FALSE; - goto retry; - } - } - - return -1; - } - - if (!quiet && (!MultipleMountOperationInProgress || GetLastError() != ERROR_NOT_READY)) - handleWin32Error (hwndDlg, SRC_POS); - - return -1; - } - - if (mount.nReturnCode != 0) - { - if (mount.nReturnCode == ERR_PASSWORD_WRONG) - { - // Do not report wrong password, if not instructed to - if (bReportWrongPassword) - { - IncreaseWrongPwdRetryCount (1); // We increase the count here only if bReportWrongPassword is TRUE, because "Auto-Mount All Devices" and other callers do it separately - - if (WrongPwdRetryCountOverLimit () - && !mount.UseBackupHeader) - { - // Retry using embedded header backup (if any) - mount.UseBackupHeader = TRUE; - goto retry; - } - - if (bDevice && mount.bProtectHiddenVolume) - { - int driveNo; - - if (swscanf (volumePath, L"\\Device\\Harddisk%d\\Partition", &driveNo) == 1) - { - OPEN_TEST_STRUCT openTestStruct; - memset (&openTestStruct, 0, sizeof (openTestStruct)); - - openTestStruct.bDetectTCBootLoader = TRUE; - StringCchPrintfW ((wchar_t *) openTestStruct.wszFileName, array_capacity (openTestStruct.wszFileName), L"\\Device\\Harddisk%d\\Partition0", driveNo); - - DWORD dwResult; - if (DeviceIoControl (hDriver, TC_IOCTL_OPEN_TEST, &openTestStruct, sizeof (OPEN_TEST_STRUCT), &openTestStruct, sizeof (OPEN_TEST_STRUCT), &dwResult, NULL) && openTestStruct.TCBootLoaderDetected) - WarningDirect ((GetWrongPasswordErrorMessage (hwndDlg) + L"\n\n" + GetString ("HIDDEN_VOL_PROT_PASSWORD_US_KEYB_LAYOUT")).c_str(), hwndDlg); - else - handleError (hwndDlg, mount.nReturnCode, SRC_POS); - } - } - else - handleError (hwndDlg, mount.nReturnCode, SRC_POS); - } - - return 0; - } - - if (!quiet) - handleError (hwndDlg, mount.nReturnCode, SRC_POS); - - return 0; - } - - // Mount successful - - if (mount.UseBackupHeader != mountOptions->UseBackupHeader - && mount.UseBackupHeader) - { - if (bReportWrongPassword && !Silent) - Warning ("HEADER_DAMAGED_AUTO_USED_HEADER_BAK", hwndDlg); - } - - LastMountedVolumeDirty = mount.FilesystemDirty; - - if (mount.FilesystemDirty) - { - wchar_t msg[1024]; - wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; - StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_VOLUME_DIRTY"), mountPoint); - - if (AskWarnYesNoStringTopmost (msg, hwndDlg) == IDYES) - CheckFilesystem (hwndDlg, driveNo, TRUE); - } - - if (mount.VolumeMountedReadOnlyAfterAccessDenied - && !Silent - && !bDevice - && !FileHasReadOnlyAttribute (volumePath) - && !IsFileOnReadOnlyFilesystem (volumePath)) - { - wchar_t msg[1024]; - wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; - StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_CONTAINER_FORCED_READ_ONLY"), mountPoint); - - WarningDirect (msg, hwndDlg); - } - - if (mount.VolumeMountedReadOnlyAfterAccessDenied - && !Silent - && bDevice) - { - wchar_t msg[1024]; - wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; - StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_DEVICE_FORCED_READ_ONLY"), mountPoint); - - WarningDirect (msg, hwndDlg); - } - - if (mount.VolumeMountedReadOnlyAfterDeviceWriteProtected - && !Silent - && wcsstr (volumePath, L"\\Device\\Harddisk") == volumePath) - { - wchar_t msg[1024]; - wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; - StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_DEVICE_FORCED_READ_ONLY_WRITE_PROTECTION"), mountPoint); - - WarningDirect (msg, hwndDlg); - - if (CurrentOSMajor >= 6 - && wcsstr (volumePath, L"\\Device\\HarddiskVolume") != volumePath - && AskNoYes ("ASK_REMOVE_DEVICE_WRITE_PROTECTION", hwndDlg) == IDYES) - { - RemoveDeviceWriteProtection (hwndDlg, volumePath); - } - } - - if (mount.wszLabel[0] && !mount.bDriverSetLabel) - { - // try setting the drive label on user-mode using registry - UpdateDriveCustomLabel (driveNo, mount.wszLabel, TRUE); - } - - ResetWrongPwdRetryCount (); - - BroadcastDeviceChange (DBT_DEVICEARRIVAL, driveNo, 0); - - if (mount.bExclusiveAccess == FALSE) - return 2; - - return 1; -} - -typedef struct -{ - int nDosDriveNo; - BOOL forced; - int dismountMaxRetries; - DWORD retryDelay; - int* presult; - DWORD dwLastError; -} UnmountThreadParam; - -void CALLBACK UnmountWaitThreadProc(void* pArg, HWND hwnd) -{ - UnmountThreadParam* pThreadParam = (UnmountThreadParam*) pArg; - int dismountMaxRetries = pThreadParam->dismountMaxRetries; - DWORD retryDelay = pThreadParam->retryDelay; - - do - { - *pThreadParam->presult = DriverUnmountVolume (hwnd, pThreadParam->nDosDriveNo, pThreadParam->forced); - - if (*pThreadParam->presult == ERR_FILES_OPEN) - Sleep (retryDelay); - else - break; - - } while (--dismountMaxRetries > 0); - - pThreadParam->dwLastError = GetLastError (); -} - -static BOOL UnmountVolumeBase (HWND hwndDlg, int nDosDriveNo, BOOL forceUnmount, BOOL ntfsFormatCase) -{ - int result; - BOOL forced = forceUnmount; - int dismountMaxRetries = ntfsFormatCase? 5 : UNMOUNT_MAX_AUTO_RETRIES; - DWORD retryDelay = ntfsFormatCase? 2000: UNMOUNT_AUTO_RETRY_DELAY; - UnmountThreadParam param; - -retry: - BroadcastDeviceChange (DBT_DEVICEREMOVEPENDING, nDosDriveNo, 0); - - param.nDosDriveNo = nDosDriveNo; - param.forced = forced; - param.dismountMaxRetries = dismountMaxRetries; - param.retryDelay = retryDelay; - param.presult = &result; - - if (Silent) - { - UnmountWaitThreadProc (¶m, hwndDlg); - } - else - { - ShowWaitDialog (hwndDlg, FALSE, UnmountWaitThreadProc, ¶m); - } - - SetLastError (param.dwLastError); - - if (result != 0) - { - if (result == ERR_FILES_OPEN && !Silent) - { - if (IDYES == AskWarnYesNoTopmost ("UNMOUNT_LOCK_FAILED", hwndDlg)) - { - forced = TRUE; - goto retry; - } - - if (IsOSAtLeast (WIN_7)) - { - // Undo SHCNE_DRIVEREMOVED - wchar_t root[] = { (wchar_t) nDosDriveNo + L'A', L':', L'\\', 0 }; - SHChangeNotify (SHCNE_DRIVEADD, SHCNF_PATH, root, NULL); - } - - return FALSE; - } - - Error ("UNMOUNT_FAILED", hwndDlg); - - return FALSE; - } - - BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, nDosDriveNo, 0); - - return TRUE; -} - -BOOL UnmountVolume (HWND hwndDlg, int nDosDriveNo, BOOL forceUnmount) -{ - return UnmountVolumeBase (hwndDlg, nDosDriveNo, forceUnmount, FALSE); -} - -BOOL UnmountVolumeAfterFormatExCall (HWND hwndDlg, int nDosDriveNo) -{ - return UnmountVolumeBase (hwndDlg, nDosDriveNo, FALSE, TRUE); -} - - -BOOL IsPasswordCacheEmpty (void) -{ - DWORD dw; - return !DeviceIoControl (hDriver, TC_IOCTL_GET_PASSWORD_CACHE_STATUS, 0, 0, 0, 0, &dw, 0); -} - -BOOL IsMountedVolumeID (BYTE volumeID[VOLUME_ID_SIZE]) -{ - MOUNT_LIST_STRUCT mlist; - DWORD dwResult; - int i; - - memset (&mlist, 0, sizeof (mlist)); - DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mlist, - sizeof (mlist), &mlist, sizeof (mlist), &dwResult, - NULL); - - for (i=0 ; i<26; i++) - if (0 == memcmp (mlist.volumeID[i], volumeID, VOLUME_ID_SIZE)) - return TRUE; - - return FALSE; -} - -BOOL IsMountedVolume (const wchar_t *volname) -{ - if ((wcslen (volname) == (3 + 2*VOLUME_ID_SIZE)) && _wcsnicmp (volname, L"ID:", 3) == 0) - { - /* Volume ID specified. Use it for matching mounted volumes. */ - std::vector arr; - if (HexWideStringToArray (&volname[3], arr) && (arr.size() == VOLUME_ID_SIZE)) - { - return IsMountedVolumeID (&arr[0]); - } - } - else - { - MOUNT_LIST_STRUCT mlist; - DWORD dwResult; - int i; - wchar_t volume[TC_MAX_PATH*2+16]; - - StringCbCopyW (volume, sizeof(volume), volname); - - if (wcsstr (volname, L"\\Device\\") != volname) - StringCbPrintfW(volume, sizeof(volume), L"\\??\\%s", volname); - - wstring resolvedPath = VolumeGuidPathToDevicePath (volname); - if (!resolvedPath.empty()) - StringCbCopyW (volume, sizeof (volume), resolvedPath.c_str()); - - memset (&mlist, 0, sizeof (mlist)); - DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mlist, - sizeof (mlist), &mlist, sizeof (mlist), &dwResult, - NULL); - - for (i=0 ; i<26; i++) - if (0 == _wcsicmp ((wchar_t *) mlist.wszVolume[i], volume)) - return TRUE; - } - - return FALSE; -} - - -int GetMountedVolumeDriveNo (wchar_t *volname) -{ - MOUNT_LIST_STRUCT mlist; - DWORD dwResult; - int i; - wchar_t volume[TC_MAX_PATH*2+16]; - - if (volname == NULL) - return -1; - - StringCbCopyW (volume, sizeof(volume), volname); - - if (wcsstr (volname, L"\\Device\\") != volname) - StringCbPrintfW (volume, sizeof(volume), L"\\??\\%s", volname); - - wstring resolvedPath = VolumeGuidPathToDevicePath (volname); - if (!resolvedPath.empty()) - StringCbCopyW (volume, sizeof (volume), resolvedPath.c_str()); - - memset (&mlist, 0, sizeof (mlist)); - DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mlist, - sizeof (mlist), &mlist, sizeof (mlist), &dwResult, - NULL); - - for (i=0 ; i<26; i++) - if (0 == _wcsicmp ((wchar_t *) mlist.wszVolume[i], (WCHAR *)volume)) - return i; - - return -1; -} - - -BOOL IsAdmin (void) -{ - return IsUserAnAdmin (); -} - - -BOOL IsBuiltInAdmin () -{ - HANDLE procToken; - DWORD size; - - if (!IsAdmin() || !OpenProcessToken (GetCurrentProcess(), TOKEN_QUERY, &procToken)) - return FALSE; - - finally_do_arg (HANDLE, procToken, { CloseHandle (finally_arg); }); - - if (GetTokenInformation (procToken, TokenUser, NULL, 0, &size) || GetLastError() != ERROR_INSUFFICIENT_BUFFER) - return FALSE; - - TOKEN_USER *tokenUser = (TOKEN_USER *) malloc (size); - if (!tokenUser) - return FALSE; - - finally_do_arg (void *, tokenUser, { free (finally_arg); }); - - if (!GetTokenInformation (procToken, TokenUser, tokenUser, size, &size)) - return FALSE; - - return IsWellKnownSid (tokenUser->User.Sid, WinAccountAdministratorSid); -} - - -BOOL IsUacSupported () -{ - HKEY hkey; - DWORD value = 1, size = sizeof (DWORD); - - if (!IsOSAtLeast (WIN_VISTA)) - return FALSE; - - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 0, KEY_READ, &hkey) == ERROR_SUCCESS) - { - if (RegQueryValueEx (hkey, L"EnableLUA", 0, 0, (LPBYTE) &value, &size) != ERROR_SUCCESS) - value = 1; - - RegCloseKey (hkey); - } - - return value != 0; -} - - -BOOL ResolveSymbolicLink (const wchar_t *symLinkName, PWSTR targetName, size_t cbTargetName) -{ - BOOL bResult; - DWORD dwResult; - RESOLVE_SYMLINK_STRUCT resolve; - - memset (&resolve, 0, sizeof(resolve)); - StringCbCopyW (resolve.symLinkName, sizeof(resolve.symLinkName), symLinkName); - - bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_RESOLVED_SYMLINK, &resolve, - sizeof (resolve), &resolve, sizeof (resolve), &dwResult, - NULL); - - StringCbCopyW (targetName, cbTargetName, resolve.targetName); - - return bResult; -} - - -BOOL GetPartitionInfo (const wchar_t *deviceName, PPARTITION_INFORMATION rpartInfo) -{ - BOOL bResult; - DWORD dwResult; - DISK_PARTITION_INFO_STRUCT dpi; - - memset (&dpi, 0, sizeof(dpi)); - StringCbCopyW ((PWSTR) &dpi.deviceName, sizeof(dpi.deviceName), deviceName); - - bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVE_PARTITION_INFO, &dpi, - sizeof (dpi), &dpi, sizeof (dpi), &dwResult, NULL); - - memcpy (rpartInfo, &dpi.partInfo, sizeof (PARTITION_INFORMATION)); - return bResult; -} - - -BOOL GetDeviceInfo (const wchar_t *deviceName, DISK_PARTITION_INFO_STRUCT *info) -{ - DWORD dwResult; - - memset (info, 0, sizeof(*info)); - StringCbCopyW ((PWSTR) &info->deviceName, sizeof(info->deviceName), deviceName); - - return DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVE_PARTITION_INFO, info, sizeof (*info), info, sizeof (*info), &dwResult, NULL); -} - - -BOOL GetDriveGeometry (const wchar_t *deviceName, PDISK_GEOMETRY diskGeometry) -{ - BOOL bResult; - DWORD dwResult; - DISK_GEOMETRY_STRUCT dg; - - memset (&dg, 0, sizeof(dg)); - StringCbCopyW ((PWSTR) &dg.deviceName, sizeof(dg.deviceName), deviceName); - - bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVE_GEOMETRY, &dg, - sizeof (dg), &dg, sizeof (dg), &dwResult, NULL); - - if (bResult && (dwResult == sizeof (dg)) && dg.diskGeometry.BytesPerSector) - { - memcpy (diskGeometry, &dg.diskGeometry, sizeof (DISK_GEOMETRY)); - return TRUE; - } - else - return FALSE; -} - -BOOL GetPhysicalDriveGeometry (int driveNumber, PDISK_GEOMETRY diskGeometry) -{ - HANDLE hDev; - BOOL bResult = FALSE; - TCHAR devicePath[MAX_PATH]; - - StringCchPrintfW (devicePath, ARRAYSIZE (devicePath), L"\\\\.\\PhysicalDrive%d", driveNumber); - - if ((hDev = CreateFileW (devicePath, 0, 0, NULL, OPEN_EXISTING, 0, NULL)) != INVALID_HANDLE_VALUE) - { - DWORD bytesRead = 0; - - ZeroMemory (diskGeometry, sizeof (DISK_GEOMETRY)); - - if ( DeviceIoControl (hDev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, diskGeometry, sizeof (DISK_GEOMETRY), &bytesRead, NULL) - && (bytesRead == sizeof (DISK_GEOMETRY)) - && diskGeometry->BytesPerSector) - { - bResult = TRUE; - } - - CloseHandle (hDev); - } - - return bResult; -} - - -// Returns drive letter number assigned to device (-1 if none) -int GetDiskDeviceDriveLetter (PWSTR deviceName) -{ - int i; - WCHAR link[MAX_PATH]; - WCHAR target[MAX_PATH]; - WCHAR device[MAX_PATH]; - - if (!ResolveSymbolicLink (deviceName, device, sizeof(device))) - StringCchCopyW (device, MAX_PATH, deviceName); - - for (i = 0; i < 26; i++) - { - WCHAR drive[] = { (WCHAR) i + L'A', L':', 0 }; - - StringCchCopyW (link, MAX_PATH, L"\\DosDevices\\"); - StringCchCatW (link, MAX_PATH, drive); - - if ( ResolveSymbolicLink (link, target, sizeof(target)) - && (wcscmp (device, target) == 0) - ) - { - return i; - } - } - - return -1; -} - - -// WARNING: This function does NOT provide 100% reliable results -- do NOT use it for critical/dangerous operations! -// Return values: 0 - filesystem does not appear empty, 1 - filesystem appears empty, -1 - an error occurred -int FileSystemAppearsEmpty (const wchar_t *devicePath) -{ - float percentFreeSpace = 0.0; - __int64 occupiedBytes = 0; - - if (GetStatsFreeSpaceOnPartition (devicePath, &percentFreeSpace, &occupiedBytes, TRUE) != -1) - { - if (occupiedBytes > BYTES_PER_GB && percentFreeSpace < 99.99 // "percentFreeSpace < 99.99" is needed because an NTFS filesystem larger than several terabytes can have more than 1GB of data in use, even if there are no files stored on it. - || percentFreeSpace < 88) // A 24-MB NTFS filesystem has 11.5% of space in use even if there are no files stored on it. - { - return 0; - } - else - return 1; - } - else - return -1; -} - - -// Returns the free space on the specified partition (volume) in bytes. If the 'occupiedBytes' pointer -// is not NULL, size of occupied space (in bytes) is written to the pointed location. In addition, if the -// 'percent' pointer is not NULL, % of free space is stored in the pointed location. If there's an error, -// returns -1. -__int64 GetStatsFreeSpaceOnPartition (const wchar_t *devicePath, float *percentFree, __int64 *occupiedBytes, BOOL silent) -{ - WCHAR devPath [MAX_PATH]; - int driveLetterNo = -1; - wchar_t szRootPath[4] = {0, L':', L'\\', 0}; - ULARGE_INTEGER freeSpaceSize; - ULARGE_INTEGER totalNumberOfBytes; - ULARGE_INTEGER totalNumberOfFreeBytes; - - StringCbCopyW (devPath, sizeof(devPath), devicePath); - - driveLetterNo = GetDiskDeviceDriveLetter (devPath); - szRootPath[0] = (wchar_t) driveLetterNo + L'A'; - - - if (!GetDiskFreeSpaceEx (szRootPath, &freeSpaceSize, &totalNumberOfBytes, &totalNumberOfFreeBytes)) - { - if (!silent) - { - handleWin32Error (MainDlg, SRC_POS); - Error ("CANNOT_CALC_SPACE", MainDlg); - } - - return -1; - } - - - if (percentFree != NULL || occupiedBytes != NULL) - { - // Determine occupied space and % of free space - - PARTITION_INFORMATION partitionInfo; - - if (!GetPartitionInfo (devicePath, &partitionInfo)) - { - if (!silent) - { - handleWin32Error (MainDlg, SRC_POS); - Error ("CANT_GET_VOLSIZE", MainDlg); - } - return -1; - } - - if (occupiedBytes != NULL) - *occupiedBytes = partitionInfo.PartitionLength.QuadPart - freeSpaceSize.QuadPart; - - if (percentFree != NULL) - *percentFree = (float) ((double) freeSpaceSize.QuadPart / (double) partitionInfo.PartitionLength.QuadPart * 100.0); - } - - return freeSpaceSize.QuadPart; -} - - -// Returns -1 if there's an error. -__int64 GetDeviceSize (const wchar_t *devicePath) -{ - PARTITION_INFORMATION partitionInfo; - - if (!GetPartitionInfo (devicePath, &partitionInfo)) - return -1; - - return partitionInfo.PartitionLength.QuadPart; -} - - -HANDLE DismountDrive (wchar_t *devName, wchar_t *devicePath) -{ - DWORD dwResult; - HANDLE hVolume; - BOOL bResult = FALSE; - int attempt = UNMOUNT_MAX_AUTO_RETRIES; - int driveLetterNo = -1; - WCHAR devPath [MAX_PATH]; - - StringCbCopyW (devPath, sizeof(devPath), devicePath); - driveLetterNo = GetDiskDeviceDriveLetter (devPath); - - - hVolume = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (hVolume == INVALID_HANDLE_VALUE) - return INVALID_HANDLE_VALUE; - - - // Try to lock the volume first so that dismount is not forced. - // If we fail, we will dismount anyway even if it needs to be forced. - - CloseVolumeExplorerWindows (MainDlg, driveLetterNo); - - while (!(bResult = DeviceIoControl (hVolume, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) - && attempt > 0) - { - Sleep (UNMOUNT_AUTO_RETRY_DELAY); - attempt--; - } - - - // Try to dismount the volume - - attempt = UNMOUNT_MAX_AUTO_RETRIES; - - while (!(bResult = DeviceIoControl (hVolume, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) - && attempt > 0) - { - Sleep (UNMOUNT_AUTO_RETRY_DELAY); - attempt--; - } - - if (!bResult) - CloseHandle (hVolume); - - return (bResult ? hVolume : INVALID_HANDLE_VALUE); -} - -// Returns -1 if the specified string is not found in the buffer. Otherwise, returns the -// offset of the first occurrence of the string. The string and the buffer may contain zeroes, -// which do NOT terminate them. -int64 FindString (const char *buf, const char *str, int64 bufLen, int64 strLen, int64 startOffset) -{ - if (buf == NULL - || str == NULL - || strLen > bufLen - || bufLen < 1 - || strLen < 1 - || startOffset > bufLen - strLen) - { - return -1; - } - - for (int64 i = startOffset; i <= bufLen - strLen; i++) - { - if (memcmp (buf + i, str, (size_t) strLen) == 0) - return i; - } - - return -1; -} - -// Returns TRUE if the file or directory exists (both may be enclosed in quotation marks). -BOOL FileExists (const wchar_t *filePathPtr) -{ - wchar_t filePath [TC_MAX_PATH * 2 + 1]; - - // Strip quotation marks (if any) - if (filePathPtr [0] == L'"') - { - StringCbCopyW (filePath, sizeof(filePath), filePathPtr + 1); - } - else - { - StringCbCopyW (filePath, sizeof(filePath), filePathPtr); - } - - // Strip quotation marks (if any) - if (filePath [wcslen (filePath) - 1] == L'"') - filePath [wcslen (filePath) - 1] = 0; - - return (_waccess (filePath, 0) != -1); -} - -// Searches the file from its end for the LAST occurrence of the string str. -// The string may contain zeroes, which do NOT terminate the string. -// If the string is found, its offset from the start of the file is returned. -// If the string isn't found or if any error occurs, -1 is returned. -__int64 FindStringInFile (const wchar_t *filePath, const char* str, int strLen) -{ - int bufSize = 64 * BYTES_PER_KB; - char *buffer = (char *) err_malloc (bufSize); - HANDLE src = NULL; - DWORD bytesRead; - BOOL readRetVal; - __int64 filePos = GetFileSize64 (filePath); - int bufPos = 0; - LARGE_INTEGER seekOffset, seekOffsetNew; - BOOL bExit = FALSE; - int filePosStep; - __int64 retVal = -1; - - if (filePos <= 0 - || buffer == NULL - || strLen > bufSize - || strLen < 1) - { - if (buffer) - free (buffer); - return -1; - } - - src = CreateFile (filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (src == INVALID_HANDLE_VALUE) - { - free (buffer); - return -1; - } - - filePosStep = bufSize - strLen + 1; - - do - { - filePos -= filePosStep; - - if (filePos < 0) - { - filePos = 0; - bExit = TRUE; - } - - seekOffset.QuadPart = filePos; - - if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0) - goto fsif_end; - - if ((readRetVal = ReadFile (src, buffer, bufSize, &bytesRead, NULL)) == 0 - || bytesRead == 0) - goto fsif_end; - - bufPos = bytesRead - strLen; - - while (bufPos > 0) - { - if (memcmp (buffer + bufPos, str, strLen) == 0) - { - // String found - retVal = filePos + bufPos; - goto fsif_end; - } - bufPos--; - } - - } while (!bExit); - -fsif_end: - CloseHandle (src); - free (buffer); - - return retVal; -} - -// System CopyFile() copies source file attributes (like FILE_ATTRIBUTE_ENCRYPTED) -// so we need to use our own copy function -BOOL TCCopyFileBase (HANDLE src, HANDLE dst) -{ - __int8 *buffer; - FILETIME fileTime; - DWORD bytesRead, bytesWritten; - BOOL res; - - buffer = (char *) malloc (64 * 1024); - if (!buffer) - { - CloseHandle (src); - CloseHandle (dst); - return FALSE; - } - - while (res = ReadFile (src, buffer, 64 * 1024, &bytesRead, NULL)) - { - if (bytesRead == 0) - { - res = 1; - break; - } - - if (!WriteFile (dst, buffer, bytesRead, &bytesWritten, NULL) - || bytesRead != bytesWritten) - { - res = 0; - break; - } - } - - if (GetFileTime (src, NULL, NULL, &fileTime)) - SetFileTime (dst, NULL, NULL, &fileTime); - - CloseHandle (src); - CloseHandle (dst); - - free (buffer); - return res != 0; -} - -BOOL TCCopyFile (wchar_t *sourceFileName, wchar_t *destinationFile) -{ - HANDLE src, dst; - - src = CreateFileW (sourceFileName, - GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (src == INVALID_HANDLE_VALUE) - return FALSE; - - dst = CreateFileW (destinationFile, - GENERIC_WRITE, - 0, NULL, CREATE_ALWAYS, 0, NULL); - - if (dst == INVALID_HANDLE_VALUE) - { - CloseHandle (src); - return FALSE; - } - - return TCCopyFileBase (src, dst); -} - -// If bAppend is TRUE, the buffer is appended to an existing file. If bAppend is FALSE, any existing file -// is replaced. If an error occurs, the incomplete file is deleted (provided that bAppend is FALSE). -BOOL SaveBufferToFile (const char *inputBuffer, const wchar_t *destinationFile, DWORD inputLength, BOOL bAppend, BOOL bRenameIfFailed) -{ - HANDLE dst; - DWORD bytesWritten; - BOOL res = TRUE; - DWORD dwLastError = 0; - - dst = CreateFile (destinationFile, - GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, bAppend ? OPEN_EXISTING : CREATE_ALWAYS, 0, NULL); - - dwLastError = GetLastError(); - if (!bAppend && bRenameIfFailed && (dst == INVALID_HANDLE_VALUE) && (GetLastError () == ERROR_SHARING_VIOLATION)) - { - wchar_t renamedPath[TC_MAX_PATH + 1]; - StringCbCopyW (renamedPath, sizeof(renamedPath), destinationFile); - StringCbCatW (renamedPath, sizeof(renamedPath), VC_FILENAME_RENAMED_SUFFIX); - - /* rename the locked file in order to be able to create a new one */ - if (MoveFileEx (destinationFile, renamedPath, MOVEFILE_REPLACE_EXISTING)) - { - dst = CreateFile (destinationFile, - GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL); - dwLastError = GetLastError(); - if (dst == INVALID_HANDLE_VALUE) - { - /* restore the original file name */ - MoveFileEx (renamedPath, destinationFile, MOVEFILE_REPLACE_EXISTING); - } - else - { - /* delete the renamed file when the machine reboots */ - MoveFileEx (renamedPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); - } - } - } - - if (dst == INVALID_HANDLE_VALUE) - { - SetLastError (dwLastError); - handleWin32Error (MainDlg, SRC_POS); - return FALSE; - } - - if (bAppend) - SetFilePointer (dst, 0, NULL, FILE_END); - - if (!WriteFile (dst, inputBuffer, inputLength, &bytesWritten, NULL) - || inputLength != bytesWritten) - { - res = FALSE; - } - - if (!res) - { - // If CREATE_ALWAYS is used, ERROR_ALREADY_EXISTS is returned after successful overwrite - // of an existing file (it's not an error) - if (! (GetLastError() == ERROR_ALREADY_EXISTS && !bAppend) ) - handleWin32Error (MainDlg, SRC_POS); - } - - CloseHandle (dst); - - if (!res && !bAppend) - _wremove (destinationFile); - - return res; -} - - -// Proper flush for Windows systems. Returns TRUE if successful. -BOOL TCFlushFile (FILE *f) -{ - HANDLE hf = (HANDLE) _get_osfhandle (_fileno (f)); - - fflush (f); - - if (hf == INVALID_HANDLE_VALUE) - return FALSE; - - return FlushFileBuffers (hf) != 0; -} - - -// Prints a UTF-16 text (note that this involves a real printer, not a screen). -// textByteLen - length of the text in bytes -// title - printed as part of the page header and used as the filename for a temporary file -BOOL PrintHardCopyTextUTF16 (wchar_t *text, wchar_t *title, size_t textByteLen) -{ - wchar_t cl [MAX_PATH*3] = {L"/p \""}; - wchar_t path [MAX_PATH * 2] = { 0 }; - wchar_t filename [MAX_PATH + 1] = { 0 }; - - StringCbCopyW (filename, sizeof(filename), title); - //strcat (filename, ".txt"); - - GetTempPath (ARRAYSIZE (path), path); - - if (!FileExists (path)) - { - StringCbCopyW (path, sizeof(path), GetConfigPath (filename)); - - if (wcslen(path) < 2) - return FALSE; - } - else - { - StringCbCatW (path, sizeof(path), filename); - } - - // Write the Unicode signature - if (!SaveBufferToFile ("\xFF\xFE", path, 2, FALSE, FALSE)) - { - _wremove (path); - return FALSE; - } - - // Write the actual text - if (!SaveBufferToFile ((char *) text, path, (DWORD) textByteLen, TRUE, FALSE)) - { - _wremove (path); - return FALSE; - } - - StringCbCatW (cl, sizeof(cl), path); - StringCbCatW (cl, sizeof(cl), L"\""); - - // Get the absolute path for notepad - if (GetWindowsDirectory(filename, MAX_PATH)) - { - if (filename[wcslen (filename) - 1] != L'\\') - StringCbCatW (filename, sizeof(filename), L"\\"); - StringCbCatW(filename, sizeof(filename), PRINT_TOOL); - } - else - StringCbCopyW(filename, sizeof(filename), L"C:\\Windows\\" PRINT_TOOL); - - WaitCursor (); - ShellExecute (NULL, L"open", filename, cl, NULL, SW_HIDE); - Sleep (6000); - NormalCursor(); - - _wremove (path); - - return TRUE; -} - - -BOOL IsNonInstallMode () -{ - HKEY hkey; - DWORD dw; - - if (bPortableModeConfirmed) - return TRUE; - - if (hDriver != INVALID_HANDLE_VALUE) - { - // The driver is running - if (DeviceIoControl (hDriver, TC_IOCTL_GET_PORTABLE_MODE_STATUS, NULL, 0, NULL, 0, &dw, 0)) - { - bPortableModeConfirmed = TRUE; - return TRUE; - } - else - { - // This is also returned if we fail to determine the status (it does not mean that portable mode is disproved). - return FALSE; - } - } - else - { - // The tests in this block are necessary because this function is in some cases called before DriverAttach(). - - HANDLE hDriverTmp = CreateFile (WIN32_ROOT_PREFIX, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (hDriverTmp == INVALID_HANDLE_VALUE) - { - // The driver was not found in the system path - - wchar_t path[MAX_PATH * 2] = { 0 }; - - // We can't use GetConfigPath() here because it would call us back (indirect recursion) - if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_APPDATA, NULL, 0, path))) - { - StringCbCatW (path, MAX_PATH * 2, L"\\VeraCrypt\\"); - StringCbCatW (path, MAX_PATH * 2, TC_APPD_FILENAME_SYSTEM_ENCRYPTION); - - if (FileExists (path)) - { - // To maintain consistency and safety, if the system encryption config file exits, we cannot - // allow portable mode. (This happens e.g. when the pretest fails and the user selects - // "Last Known Good Configuration" from the Windows boot menu.) - - // However, if UAC elevation is needed, we have to confirm portable mode first (after we are elevated, we won't). - if (!IsAdmin () && IsUacSupported ()) - return TRUE; - - return FALSE; - } - } - - // As the driver was not found in the system path, we can predict that we will run in portable mode - return TRUE; - } - else - CloseHandle (hDriverTmp); - } - - // The following test may be unreliable in some cases (e.g. after the user selects restore "Last Known Good - // Configuration" from the Windows boot menu). - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VeraCrypt", 0, KEY_READ | KEY_WOW64_32KEY, &hkey) == ERROR_SUCCESS) - { - RegCloseKey (hkey); - return FALSE; - } - else - return TRUE; -} - - -LRESULT SetCheckBox (HWND hwndDlg, int dlgItem, BOOL state) -{ - return SendDlgItemMessage (hwndDlg, dlgItem, BM_SETCHECK, state ? BST_CHECKED : BST_UNCHECKED, 0); -} - - -BOOL GetCheckBox (HWND hwndDlg, int dlgItem) -{ - return IsButtonChecked (GetDlgItem (hwndDlg, dlgItem)); -} - - -// Scroll the listview vertically so that the item with index of topMostVisibleItem is the topmost visible item. -void SetListScrollHPos (HWND hList, int topMostVisibleItem) -{ - int testedPos = 0; - - do - { - SendMessage (hList, LVM_SCROLL, 0, testedPos); - - } while (ListView_GetTopIndex (hList) < topMostVisibleItem && ++testedPos < 10000); -} - - -// Adds or removes TrueCrypt.exe to/from the system startup sequence (with appropriate command line arguments) -void ManageStartupSeq (void) -{ - if (!IsNonInstallMode ()) - { - wchar_t regk [64]; - - GetStartupRegKeyName (regk, sizeof(regk)); - - if (bStartOnLogon || bMountDevicesOnLogon || bMountFavoritesOnLogon) - { - wchar_t exe[MAX_PATH * 2] = { L'"' }; - - GetModuleFileName (NULL, exe + 1, ARRAYSIZE (exe) - 1); - -#ifdef VOLFORMAT - { - wchar_t *tmp = NULL; - - if (tmp = wcsrchr (exe, L'\\')) - { - *tmp = 0; - StringCbCatW (exe, MAX_PATH * 2, L"\\VeraCrypt.exe"); - } - } -#endif - StringCbCatW (exe, MAX_PATH * 2, L"\" /q preferences /a logon"); - - if (bMountDevicesOnLogon) StringCbCatW (exe, MAX_PATH * 2, L" /a devices"); - if (bMountFavoritesOnLogon) StringCbCatW (exe, MAX_PATH * 2, L" /a favorites"); - - WriteRegistryString (regk, L"VeraCrypt", exe); - } - else - DeleteRegistryValue (regk, L"VeraCrypt"); - } -} - - -// Adds or removes the VeraCrypt Volume Creation Wizard to/from the system startup sequence -void ManageStartupSeqWiz (BOOL bRemove, const wchar_t *arg) -{ - wchar_t regk [64]; - - GetStartupRegKeyName (regk, sizeof(regk)); - - if (!bRemove) - { - size_t exeSize = (MAX_PATH * 2) + 3 + 20 + wcslen (arg); // enough room for all concatenation operations - wchar_t* exe = (wchar_t*) calloc(1, exeSize * sizeof (wchar_t)); - exe[0] = L'"'; - GetModuleFileName (NULL, exe + 1, (DWORD) (exeSize - 1)); - -#ifndef VOLFORMAT - { - wchar_t *tmp = NULL; - - if (tmp = wcsrchr (exe, L'\\')) - { - *tmp = 0; - - StringCchCatW (exe, exeSize, L"\\VeraCrypt Format.exe"); - } - } -#endif - - if (wcslen (arg) > 0) - { - StringCchCatW (exe, exeSize, L"\" "); - StringCchCatW (exe, exeSize, arg); - } - - WriteRegistryString (regk, L"VeraCrypt Format", exe); - - free(exe); - } - else - DeleteRegistryValue (regk, L"VeraCrypt Format"); -} - - -// Delete the last used Windows file selector path for TrueCrypt from the registry -void CleanLastVisitedMRU (void) -{ - WCHAR exeFilename[MAX_PATH]; - WCHAR *strToMatch; - - WCHAR strTmp[4096]; - WCHAR regPath[128]; - WCHAR key[64]; - int id, len; - - GetModuleFileNameW (NULL, exeFilename, sizeof (exeFilename) / sizeof(exeFilename[0])); - strToMatch = wcsrchr (exeFilename, L'\\') + 1; - - StringCbPrintfW (regPath, sizeof(regPath), L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisited%sMRU", IsOSAtLeast (WIN_VISTA) ? L"Pidl" : L""); - - for (id = (IsOSAtLeast (WIN_VISTA) ? 0 : L'a'); id <= (IsOSAtLeast (WIN_VISTA) ? 1000 : L'z'); id++) - { - *strTmp = 0; - StringCbPrintfW (key, sizeof(key), (IsOSAtLeast (WIN_VISTA) ? L"%d" : L"%c"), id); - - if ((len = ReadRegistryBytes (regPath, key, (char *) strTmp, sizeof (strTmp))) > 0) - { - if (_wcsicmp (strTmp, strToMatch) == 0) - { - char buf[65536], bufout[sizeof (buf)]; - - // Overwrite the entry with zeroes while keeping its original size - memset (strTmp, 0, len); - if (!WriteRegistryBytes (regPath, key, (char *) strTmp, len)) - MessageBoxW (NULL, GetString ("CLEAN_WINMRU_FAILED"), lpszTitle, ICON_HAND); - - DeleteRegistryValue (regPath, key); - - // Remove ID from MRUList - if (IsOSAtLeast (WIN_VISTA)) - { - int *p = (int *)buf; - int *pout = (int *)bufout; - int l; - - l = len = ReadRegistryBytes (L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedPidlMRU", L"MRUListEx", buf, sizeof (buf)); - while (l > 0) - { - l -= sizeof (int); - - if (*p == id) - { - p++; - len -= sizeof (int); - continue; - } - *pout++ = *p++; - } - - WriteRegistryBytes (L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedPidlMRU", L"MRUListEx", bufout, len); - } - else - { - wchar_t *p = (wchar_t*) buf; - wchar_t *pout = (wchar_t*) bufout; - - ReadRegistryString (L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedMRU", L"MRUList", L"", (wchar_t*) buf, sizeof (buf)); - while (*p) - { - if (*p == id) - { - p++; - continue; - } - *pout++ = *p++; - } - *pout++ = 0; - - WriteRegistryString (L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedMRU", L"MRUList", (wchar_t*) bufout); - } - - break; - } - } - } -} - - -#ifndef SETUP -void ClearHistory (HWND hwndDlgItem) -{ - ArrowWaitCursor (); - - ClearCombo (hwndDlgItem); - DumpCombo (hwndDlgItem, TRUE); - - CleanLastVisitedMRU (); - - NormalCursor (); -} -#endif // #ifndef SETUP - - -LRESULT ListItemAdd (HWND list, int index, const wchar_t *string) -{ - LVITEM li; - memset (&li, 0, sizeof(li)); - - li.mask = LVIF_TEXT; - li.pszText = (wchar_t*) string; - li.iItem = index; - li.iSubItem = 0; - return ListView_InsertItem (list, &li); -} - - -LRESULT ListSubItemSet (HWND list, int index, int subIndex, const wchar_t *string) -{ - LVITEM li; - memset (&li, 0, sizeof(li)); - - li.mask = LVIF_TEXT; - li.pszText = (wchar_t*) string; - li.iItem = index; - li.iSubItem = subIndex; - return ListView_SetItem (list, &li); -} - - -BOOL GetMountList (MOUNT_LIST_STRUCT *list) -{ - DWORD dwResult; - - memset (list, 0, sizeof (*list)); - return DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, list, - sizeof (*list), list, sizeof (*list), &dwResult, - NULL); -} - - -int GetDriverRefCount () -{ - DWORD dwResult; - BOOL bResult; - int refCount; - - bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DEVICE_REFCOUNT, &refCount, sizeof (refCount), &refCount, - sizeof (refCount), &dwResult, NULL); - - if (bResult) - return refCount; - else - return -1; -} - -// Loads a 32-bit integer from the file at the specified file offset. The saved value is assumed to have been -// processed by mputLong(). The result is stored in *result. Returns TRUE if successful (otherwise FALSE). -BOOL LoadInt32 (const wchar_t *filePath, unsigned __int32 *result, __int64 fileOffset) -{ - DWORD bufSize = sizeof(__int32); - unsigned char *buffer = (unsigned char *) malloc (bufSize); - unsigned char *bufferPtr = buffer; - HANDLE src = NULL; - DWORD bytesRead; - LARGE_INTEGER seekOffset, seekOffsetNew; - BOOL retVal = FALSE; - - if (buffer == NULL) - return -1; - - src = CreateFile (filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (src == INVALID_HANDLE_VALUE) - { - free (buffer); - return FALSE; - } - - seekOffset.QuadPart = fileOffset; - - if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0) - goto fsif_end; - - if (ReadFile (src, buffer, bufSize, &bytesRead, NULL) == 0 - || bytesRead != bufSize) - goto fsif_end; - - - retVal = TRUE; - - *result = mgetLong(bufferPtr); - -fsif_end: - CloseHandle (src); - free (buffer); - - return retVal; -} - -// Loads a 16-bit integer from the file at the specified file offset. The saved value is assumed to have been -// processed by mputWord(). The result is stored in *result. Returns TRUE if successful (otherwise FALSE). -BOOL LoadInt16 (const wchar_t *filePath, int *result, __int64 fileOffset) -{ - DWORD bufSize = sizeof(__int16); - unsigned char *buffer = (unsigned char *) malloc (bufSize); - unsigned char *bufferPtr = buffer; - HANDLE src = NULL; - DWORD bytesRead; - LARGE_INTEGER seekOffset, seekOffsetNew; - BOOL retVal = FALSE; - - if (buffer == NULL) - return -1; - - src = CreateFile (filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (src == INVALID_HANDLE_VALUE) - { - free (buffer); - return FALSE; - } - - seekOffset.QuadPart = fileOffset; - - if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0) - goto fsif_end; - - if (ReadFile (src, buffer, bufSize, &bytesRead, NULL) == 0 - || bytesRead != bufSize) - goto fsif_end; - - - retVal = TRUE; - - *result = mgetWord(bufferPtr); - -fsif_end: - CloseHandle (src); - free (buffer); - - return retVal; -} - -// Returns NULL if there's any error. Although the buffer can contain binary data, it is always null-terminated. -char *LoadFile (const wchar_t *fileName, DWORD *size) -{ - char *buf; - DWORD fileSize = INVALID_FILE_SIZE; - HANDLE h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - if (h == INVALID_HANDLE_VALUE) - return NULL; - - if ((fileSize = GetFileSize (h, NULL)) == INVALID_FILE_SIZE) - { - CloseHandle (h); - return NULL; - } - - *size = fileSize; - buf = (char *) calloc (*size + 1, 1); - - if (buf == NULL) - { - CloseHandle (h); - return NULL; - } - - if (!ReadFile (h, buf, *size, size, NULL)) - { - free (buf); - buf = NULL; - } - - CloseHandle (h); - return buf; -} - - -// Returns NULL if there's any error. -char *LoadFileBlock (const wchar_t *fileName, __int64 fileOffset, DWORD count) -{ - char *buf; - DWORD bytesRead = 0; - LARGE_INTEGER seekOffset, seekOffsetNew; - BOOL bStatus; - - HANDLE h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - if (h == INVALID_HANDLE_VALUE) - return NULL; - - seekOffset.QuadPart = fileOffset; - - if (SetFilePointerEx (h, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0) - { - CloseHandle (h); - return NULL; - } - - buf = (char *) calloc (count, 1); - - if (buf == NULL) - { - CloseHandle (h); - return NULL; - } - - bStatus = ReadFile (h, buf, count, &bytesRead, NULL); - - CloseHandle (h); - - if (!bStatus || (bytesRead != count)) - { - free (buf); - return NULL; - } - - return buf; -} - - -// Returns -1 if there is an error, or the size of the file. -__int64 GetFileSize64 (const wchar_t *path) -{ - HANDLE h = CreateFile (path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - LARGE_INTEGER size; - __int64 retSize = -1; - - if (h) - { - if (GetFileSizeEx (h, &size)) - { - retSize = size.QuadPart; - } - - CloseHandle (h); - } - - return retSize; -} - - -wchar_t *GetModPath (wchar_t *path, int maxSize) -{ - GetModuleFileName (NULL, path, maxSize); - wchar_t* ptr = wcsrchr (path, L'\\'); - if (ptr) - ptr[1] = 0; - return path; -} - - -wchar_t *GetConfigPath (wchar_t *fileName) -{ - static wchar_t path[MAX_PATH * 2] = { 0 }; - - if (IsNonInstallMode ()) - { - GetModPath (path, ARRAYSIZE (path)); - StringCchCatW (path, (MAX_PATH * 2), fileName); - - return path; - } - - if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, path))) - { - StringCchCatW (path, (MAX_PATH * 2), L"\\VeraCrypt\\"); - CreateDirectory (path, NULL); - StringCchCatW (path, (MAX_PATH * 2), fileName); - } - else - path[0] = 0; - - return path; -} - - -wchar_t *GetProgramConfigPath (wchar_t *fileName) -{ - static wchar_t path[MAX_PATH * 2] = { 0 }; - - if (SUCCEEDED (SHGetFolderPath (NULL, CSIDL_COMMON_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, path))) - { - StringCchCatW (path, (MAX_PATH * 2), L"\\VeraCrypt\\"); - CreateDirectory (path, NULL); - StringCchCatW (path, (MAX_PATH * 2), fileName); - } - else - path[0] = 0; - - return path; -} - - -std::wstring GetServiceConfigPath (const wchar_t *fileName, bool useLegacy) -{ - wchar_t sysPath[TC_MAX_PATH]; - - if (Is64BitOs() && useLegacy) - { - typedef UINT (WINAPI *GetSystemWow64Directory_t) (LPWSTR lpBuffer, UINT uSize); - - GetSystemWow64Directory_t getSystemWow64Directory = (GetSystemWow64Directory_t) GetProcAddress (GetModuleHandle (L"kernel32"), "GetSystemWow64DirectoryW"); - getSystemWow64Directory (sysPath, ARRAYSIZE (sysPath)); - } - else - GetSystemDirectory (sysPath, ARRAYSIZE (sysPath)); - - return wstring (sysPath) + L"\\" + fileName; -} - - -// Returns 0 if an error occurs or the drive letter (as an upper-case char) of the system partition (e.g. 'C'); -wchar_t GetSystemDriveLetter (void) -{ - wchar_t systemDir [MAX_PATH]; - - if (GetSystemDirectory (systemDir, ARRAYSIZE (systemDir))) - return (wchar_t) (towupper (systemDir [0])); - else - return 0; -} - - -void TaskBarIconDisplayBalloonTooltip (HWND hwnd, wchar_t *headline, wchar_t *text, BOOL warning) -{ - if (nCurrentOS == WIN_2000) - { - MessageBoxW (MainDlg, text, headline, warning ? MB_ICONWARNING : MB_ICONINFORMATION); - return; - } - - NOTIFYICONDATAW tnid; - - ZeroMemory (&tnid, sizeof (tnid)); - - tnid.cbSize = sizeof (tnid); - tnid.hWnd = hwnd; - tnid.uID = IDI_TRUECRYPT_ICON; - //tnid.uVersion = (IsOSAtLeast (WIN_VISTA) ? NOTIFYICON_VERSION_4 : NOTIFYICON_VERSION); - - //Shell_NotifyIconW (NIM_SETVERSION, &tnid); - - tnid.uFlags = NIF_INFO; - tnid.dwInfoFlags = (warning ? NIIF_WARNING : NIIF_INFO); - tnid.uTimeout = (IsOSAtLeast (WIN_VISTA) ? 1000 : 5000); // in ms - - StringCbCopyW (tnid.szInfoTitle, sizeof(tnid.szInfoTitle), headline); - StringCbCopyW (tnid.szInfo, sizeof(tnid.szInfo),text); - - // Display the balloon tooltip quickly twice in a row to avoid the slow and unwanted "fade-in" phase - Shell_NotifyIconW (NIM_MODIFY, &tnid); - Shell_NotifyIconW (NIM_MODIFY, &tnid); -} - - -// Either of the pointers may be NULL -void InfoBalloon (char *headingStringId, char *textStringId, HWND hwnd) -{ - if (Silent) - return; - - TaskBarIconDisplayBalloonTooltip (hwnd, - headingStringId == NULL ? L"VeraCrypt" : GetString (headingStringId), - textStringId == NULL ? L" " : GetString (textStringId), - FALSE); -} - - -// Either of the pointers may be NULL -void InfoBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd) -{ - if (Silent) - return; - - TaskBarIconDisplayBalloonTooltip (hwnd, - headingString == NULL ? L"VeraCrypt" : headingString, - textString == NULL ? L" " : textString, - FALSE); -} - - -// Either of the pointers may be NULL -void WarningBalloon (char *headingStringId, char *textStringId, HWND hwnd) -{ - if (Silent) - return; - - TaskBarIconDisplayBalloonTooltip (hwnd, - headingStringId == NULL ? L"VeraCrypt" : GetString (headingStringId), - textStringId == NULL ? L" " : GetString (textStringId), - TRUE); -} - - -// Either of the pointers may be NULL -void WarningBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd) -{ - if (Silent) - return; - - TaskBarIconDisplayBalloonTooltip (hwnd, - headingString == NULL ? L"VeraCrypt" : headingString, - textString == NULL ? L" " : textString, - TRUE); -} - - -int Info (char *stringId, HWND hwnd) -{ - if (Silent) return 0; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONINFORMATION); -} - - -int InfoTopMost (char *stringId, HWND hwnd) -{ - if (Silent) return 0; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TOPMOST); -} - - -int InfoDirect (const wchar_t *msg, HWND hwnd) -{ - if (Silent) return 0; - return MessageBoxW (hwnd, msg, lpszTitle, MB_ICONINFORMATION); -} - - -int Warning (char *stringId, HWND hwnd) -{ - if (Silent) return 0; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING); -} - - -int WarningTopMost (char *stringId, HWND hwnd) -{ - if (Silent) return 0; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); -} - - -int WarningDirect (const wchar_t *warnMsg, HWND hwnd) -{ - if (Silent) return 0; - return MessageBoxW (hwnd, warnMsg, lpszTitle, MB_ICONWARNING); -} - - -int Error (char *stringId, HWND hwnd) -{ - if (Silent) return 0; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONERROR); -} - -int ErrorRetryCancel (char *stringId, HWND hwnd) -{ - if (Silent) return 0; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONERROR | MB_RETRYCANCEL); -} - -int ErrorTopMost (char *stringId, HWND hwnd) -{ - if (Silent) return 0; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); -} - - -int ErrorDirect (const wchar_t *errMsg, HWND hwnd) -{ - if (Silent) return 0; - return MessageBoxW (hwnd, errMsg, lpszTitle, MB_ICONERROR); -} - - -int AskYesNo (char *stringId, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON1); -} - - -int AskYesNoString (const wchar_t *str, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, str, lpszTitle, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON1); -} - - -int AskYesNoTopmost (char *stringId, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON1 | MB_SETFOREGROUND | MB_TOPMOST); -} - - -int AskNoYes (char *stringId, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2); -} - -int AskNoYesString (const wchar_t *string, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, string, lpszTitle, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2); -} - -int AskOkCancel (char *stringId, HWND hwnd) -{ - if (Silent) return IDCANCEL; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONQUESTION | MB_OKCANCEL | MB_DEFBUTTON1); -} - - -int AskWarnYesNo (char *stringId, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON1); -} - - -int AskWarnYesNoString (const wchar_t *string, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, string, lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON1); -} - - -int AskWarnYesNoTopmost (char *stringId, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON1 | MB_SETFOREGROUND | MB_TOPMOST); -} - - -int AskWarnYesNoStringTopmost (const wchar_t *string, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, string, lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON1 | MB_SETFOREGROUND | MB_TOPMOST); -} - - -int AskWarnNoYes (char *stringId, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2); -} - - -int AskWarnNoYesString (const wchar_t *string, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, string, lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2); -} - - -int AskWarnNoYesTopmost (char *stringId, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2 | MB_SETFOREGROUND | MB_TOPMOST); -} - - -int AskWarnOkCancel (char *stringId, HWND hwnd) -{ - if (Silent) return IDCANCEL; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1); -} - - -int AskWarnCancelOk (char *stringId, HWND hwnd) -{ - if (Silent) return IDCANCEL; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON2); -} - - -int AskErrYesNo (char *stringId, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONERROR | MB_YESNO | MB_DEFBUTTON1); -} - - -int AskErrNoYes (char *stringId, HWND hwnd) -{ - if (Silent) return IDNO; - return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONERROR | MB_YESNO | MB_DEFBUTTON2); -} - - -// The function accepts two input formats: -// Input format 1: {0, "MESSAGE_STRING_ID", "BUTTON_1_STRING_ID", ... "LAST_BUTTON_STRING_ID", 0}; -// Input format 2: {L"", L"Message text", L"Button caption 1", ... L"Last button caption", 0}; -// The second format is to be used if any of the strings contains format specification (e.g. %s, %d) or -// in any other cases where a string needs to be resolved before calling this function. -// The returned value is the ordinal number of the choice the user selected (1..MAX_MULTI_CHOICES) -int AskMultiChoice (void *strings[], BOOL bBold, HWND hwnd) -{ - MULTI_CHOICE_DLGPROC_PARAMS params; - - params.strings = &strings[0]; - params.bold = bBold; - - return (int) DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_MULTI_CHOICE_DLG), hwnd, - (DLGPROC) MultiChoiceDialogProc, (LPARAM) ¶ms); -} - - -BOOL ConfigWriteBegin () -{ - DWORD size; - if (ConfigFileHandle != NULL) - return FALSE; - - if (ConfigBuffer == NULL) - ConfigBuffer = LoadFile (GetConfigPath (TC_APPD_FILENAME_CONFIGURATION), &size); - - ConfigFileHandle = _wfopen (GetConfigPath (TC_APPD_FILENAME_CONFIGURATION), L"w,ccs=UTF-8"); - if (ConfigFileHandle == NULL) - { - free (ConfigBuffer); - ConfigBuffer = NULL; - return FALSE; - } - XmlWriteHeader (ConfigFileHandle); - fputws (L"\n\t", ConfigFileHandle); - - return TRUE; -} - - -BOOL ConfigWriteEnd (HWND hwnd) -{ - char *xml = ConfigBuffer; - char key[128], value[2048]; - - if (ConfigFileHandle == NULL) return FALSE; - - // Write unmodified values - while (xml && (xml = XmlFindElement (xml, "config"))) - { - XmlGetAttributeText (xml, "key", key, sizeof (key)); - XmlGetNodeText (xml, value, sizeof (value)); - - fwprintf (ConfigFileHandle, L"\n\t\t%hs", key, value); - xml++; - } - - fputws (L"\n\t", ConfigFileHandle); - XmlWriteFooter (ConfigFileHandle); - - TCFlushFile (ConfigFileHandle); - - CheckFileStreamWriteErrors (hwnd, ConfigFileHandle, TC_APPD_FILENAME_CONFIGURATION); - - fclose (ConfigFileHandle); - ConfigFileHandle = NULL; - - if (ConfigBuffer != NULL) - { - DWORD size; - free (ConfigBuffer); - ConfigBuffer = LoadFile (GetConfigPath (TC_APPD_FILENAME_CONFIGURATION), &size); - } - - return TRUE; -} - - -BOOL ConfigWriteString (char *configKey, char *configValue) -{ - char *c; - if (ConfigFileHandle == NULL) - return FALSE; - - // Mark previous config value as updated - if (ConfigBuffer != NULL) - { - c = XmlFindElementByAttributeValue (ConfigBuffer, "config", "key", configKey); - if (c != NULL) - c[1] = '!'; - } - - return 0 != fwprintf ( - ConfigFileHandle, L"\n\t\t%hs", - configKey, configValue); -} - -BOOL ConfigWriteStringW (char *configKey, wchar_t *configValue) -{ - char *c; - if (ConfigFileHandle == NULL) - return FALSE; - - // Mark previous config value as updated - if (ConfigBuffer != NULL) - { - c = XmlFindElementByAttributeValue (ConfigBuffer, "config", "key", configKey); - if (c != NULL) - c[1] = '!'; - } - - return 0 != fwprintf ( - ConfigFileHandle, L"\n\t\t%ls", - configKey, configValue); -} - -BOOL ConfigWriteInt (char *configKey, int configValue) -{ - char val[32]; - StringCbPrintfA (val, sizeof(val), "%d", configValue); - return ConfigWriteString (configKey, val); -} - - -static BOOL ConfigRead (char *configKey, char *configValue, int maxValueSize) -{ - DWORD size; - char *xml; - - if (ConfigBuffer == NULL) - ConfigBuffer = LoadFile (GetConfigPath (TC_APPD_FILENAME_CONFIGURATION), &size); - - xml = ConfigBuffer; - if (xml != NULL) - { - xml = XmlFindElementByAttributeValue (xml, "config", "key", configKey); - if (xml != NULL) - { - XmlGetNodeText (xml, configValue, maxValueSize); - return TRUE; - } - } - - return FALSE; -} - - -int ConfigReadInt (char *configKey, int defaultValue) -{ - char s[32]; - - if (ConfigRead (configKey, s, sizeof (s))) - return atoi (s); - else - return defaultValue; -} - - -char *ConfigReadString (char *configKey, char *defaultValue, char *str, int maxLen) -{ - if (ConfigRead (configKey, str, maxLen)) - return str; - else - { - StringCbCopyA (str, maxLen, defaultValue); - return defaultValue; - } -} - -void ConfigReadCompareInt(char *configKey, int defaultValue, int* pOutputValue, BOOL bOnlyCheckModified, BOOL* pbModified) -{ - int intValue = ConfigReadInt (configKey, defaultValue); - if (pOutputValue) - { - if (pbModified && (*pOutputValue != intValue)) - *pbModified = TRUE; - if (!bOnlyCheckModified) - *pOutputValue = intValue; - } -} - -void ConfigReadCompareString (char *configKey, char *defaultValue, char *str, int maxLen, BOOL bOnlyCheckModified, BOOL *pbModified) -{ - char *strValue = (char*) malloc (maxLen); - if (strValue) - { - memcpy (strValue, str, maxLen); - - ConfigReadString (configKey, defaultValue, strValue, maxLen); - - if (pbModified && strcmp (str, strValue)) - *pbModified = TRUE; - if (!bOnlyCheckModified) - memcpy(str, strValue, maxLen); - - free (strValue); - } - else - { - /* allocation failed. Suppose that value changed */ - if (pbModified) - *pbModified = TRUE; - if (!bOnlyCheckModified) - ConfigReadString (configKey, defaultValue, str, maxLen); - - } -} - -void OpenPageHelp (HWND hwndDlg, int nPage) -{ - int r = (int)ShellExecuteW (NULL, L"open", szHelpFile, NULL, NULL, SW_SHOWNORMAL); - - if (r == ERROR_FILE_NOT_FOUND) - { - // Try the secondary help file - r = (int)ShellExecuteW (NULL, L"open", szHelpFile2, NULL, NULL, SW_SHOWNORMAL); - - if (r == ERROR_FILE_NOT_FOUND) - { - OpenOnlineHelp (); - return; - } - } - - if (r == SE_ERR_NOASSOC) - { - if (AskYesNo ("HELP_READER_ERROR", MainDlg) == IDYES) - OpenOnlineHelp (); - } -} - - -void OpenOnlineHelp () -{ - Applink ("help", TRUE, ""); -} - - -#ifndef SETUP - -void RestoreDefaultKeyFilesParam (void) -{ - KeyFileRemoveAll (&FirstKeyFile); - if (defaultKeyFilesParam.FirstKeyFile != NULL) - { - KeyFileCloneAll (defaultKeyFilesParam.FirstKeyFile, &FirstKeyFile); - KeyFilesEnable = defaultKeyFilesParam.EnableKeyFiles; - } - else - KeyFilesEnable = FALSE; -} - - -BOOL LoadDefaultKeyFilesParam (void) -{ - BOOL status = TRUE; - DWORD size; - char *defaultKeyfilesFile = LoadFile (GetConfigPath (TC_APPD_FILENAME_DEFAULT_KEYFILES), &size); - char *xml = defaultKeyfilesFile; - KeyFile *kf; - - if (xml == NULL) - return FALSE; - - KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile); - - while (xml = XmlFindElement (xml, "keyfile")) - { - kf = (KeyFile *) malloc (sizeof (KeyFile)); - if (kf) - { - char fileName [MAX_PATH + 1]; - if (XmlGetNodeText (xml, fileName, sizeof (fileName)) != NULL) - { - std::wstring wszFileName = Utf8StringToWide(fileName); - StringCbCopyW (kf->FileName, sizeof (kf->FileName), wszFileName.c_str ()); - defaultKeyFilesParam.FirstKeyFile = KeyFileAdd (defaultKeyFilesParam.FirstKeyFile, kf); - } - else - free (kf); - } - else - { - KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile); - status = FALSE; - break; - } - - xml++; - } - - free (defaultKeyfilesFile); - if (status) - KeyFilesEnable = defaultKeyFilesParam.EnableKeyFiles; - - return status; -} - -#endif /* #ifndef SETUP */ - - -void Debug (char *format, ...) -{ - char buf[1024]; - va_list val; - - va_start(val, format); - StringCbVPrintfA (buf, sizeof (buf), format, val); - va_end(val); - - OutputDebugStringA (buf); -} - - -void DebugMsgBox (char *format, ...) -{ - char buf[1024]; - va_list val; - - va_start(val, format); - StringCbVPrintfA (buf, sizeof (buf), format, val); - va_end(val); - - MessageBoxA (MainDlg, buf, "VeraCrypt debug", 0); -} - - -BOOL IsOSAtLeast (OSVersionEnum reqMinOS) -{ - return IsOSVersionAtLeast (reqMinOS, 0); -} - - -// Returns TRUE if the operating system is at least reqMinOS and service pack at least reqMinServicePack. -// Example 1: IsOSVersionAtLeast (WIN_VISTA, 1) called under Windows 2008, returns TRUE. -// Example 2: IsOSVersionAtLeast (WIN_XP, 3) called under Windows XP SP1, returns FALSE. -// Example 3: IsOSVersionAtLeast (WIN_XP, 3) called under Windows Vista SP1, returns TRUE. -BOOL IsOSVersionAtLeast (OSVersionEnum reqMinOS, int reqMinServicePack) -{ - /* When updating this function, update IsOSAtLeast() in Ntdriver.c too. */ - - if (CurrentOSMajor <= 0) - TC_THROW_FATAL_EXCEPTION; - - int major = 0, minor = 0; - - switch (reqMinOS) - { - case WIN_2000: major = 5; minor = 0; break; - case WIN_XP: major = 5; minor = 1; break; - case WIN_SERVER_2003: major = 5; minor = 2; break; - case WIN_VISTA: major = 6; minor = 0; break; - case WIN_7: major = 6; minor = 1; break; - case WIN_8: major = 6; minor = 2; break; - case WIN_8_1: major = 6; minor = 3; break; - case WIN_10: major = 10; minor = 0; break; - - default: - TC_THROW_FATAL_EXCEPTION; - break; - } - - return ((CurrentOSMajor << 16 | CurrentOSMinor << 8 | CurrentOSServicePack) - >= (major << 16 | minor << 8 | reqMinServicePack)); -} - - -BOOL Is64BitOs () -{ -#ifdef _WIN64 - return TRUE; -#else - static BOOL isWow64 = FALSE; - static BOOL valid = FALSE; - typedef BOOL (__stdcall *LPFN_ISWOW64PROCESS ) (HANDLE hProcess,PBOOL Wow64Process); - LPFN_ISWOW64PROCESS fnIsWow64Process; - - if (valid) - return isWow64; - - fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle(L"kernel32"), "IsWow64Process"); - - if (fnIsWow64Process != NULL) - if (!fnIsWow64Process (GetCurrentProcess(), &isWow64)) - isWow64 = FALSE; - - valid = TRUE; - return isWow64; -#endif -} - - -BOOL IsServerOS () -{ - OSVERSIONINFOEXW osVer; - osVer.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW); - GetVersionExW ((LPOSVERSIONINFOW) &osVer); - - return (osVer.wProductType == VER_NT_SERVER || osVer.wProductType == VER_NT_DOMAIN_CONTROLLER); -} - - -// Returns TRUE, if the currently running operating system is installed in a hidden volume. If it's not, or if -// there's an error, returns FALSE. -BOOL IsHiddenOSRunning (void) -{ - static BOOL statusCached = FALSE; - static BOOL hiddenOSRunning; - - if (!statusCached) - { - try - { - hiddenOSRunning = BootEncryption (MainDlg).IsHiddenSystemRunning(); - } - catch (...) - { - hiddenOSRunning = FALSE; - } - - statusCached = TRUE; - } - - return hiddenOSRunning; -} - - -BOOL EnableWow64FsRedirection (BOOL enable) -{ - typedef BOOLEAN (__stdcall *Wow64EnableWow64FsRedirection_t) (BOOL enable); - Wow64EnableWow64FsRedirection_t wow64EnableWow64FsRedirection = (Wow64EnableWow64FsRedirection_t) GetProcAddress (GetModuleHandle (L"kernel32"), "Wow64EnableWow64FsRedirection"); - - if (!wow64EnableWow64FsRedirection) - return FALSE; - - return wow64EnableWow64FsRedirection (enable); -} - - -BOOL RestartComputer (void) -{ - TOKEN_PRIVILEGES tokenPrivil; - HANDLE hTkn; - - if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES, &hTkn)) - { - return false; - } - - LookupPrivilegeValue (NULL, SE_SHUTDOWN_NAME, &tokenPrivil.Privileges[0].Luid); - tokenPrivil.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - tokenPrivil.PrivilegeCount = 1; - - AdjustTokenPrivileges (hTkn, false, &tokenPrivil, 0, (PTOKEN_PRIVILEGES) NULL, 0); - if (GetLastError() != ERROR_SUCCESS) - { - CloseHandle(hTkn); - return false; - } - - if (!ExitWindowsEx (EWX_REBOOT, - SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED)) - { - CloseHandle(hTkn); - return false; - } - - CloseHandle(hTkn); - return true; -} - - -std::wstring GetWindowsEdition () -{ - wstring osname = L"win"; - - OSVERSIONINFOEXW osVer; - osVer.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW); - GetVersionExW ((LPOSVERSIONINFOW) &osVer); - - BOOL home = (osVer.wSuiteMask & VER_SUITE_PERSONAL); - BOOL server = (osVer.wProductType == VER_NT_SERVER || osVer.wProductType == VER_NT_DOMAIN_CONTROLLER); - - HKEY hkey; - wchar_t productName[300] = {0}; - DWORD productNameSize = sizeof (productName); - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS) - { - if (RegQueryValueEx (hkey, L"ProductName", 0, 0, (LPBYTE) &productName, &productNameSize) != ERROR_SUCCESS || productNameSize < 1) - productName[0] = 0; - - RegCloseKey (hkey); - } - - switch (nCurrentOS) - { - case WIN_2000: - osname += L"2000"; - break; - - case WIN_XP: - case WIN_XP64: - osname += L"xp"; - osname += home ? L"-home" : L"-pro"; - break; - - case WIN_SERVER_2003: - osname += L"2003"; - break; - - case WIN_VISTA: - osname += L"vista"; - break; - - case WIN_SERVER_2008: - osname += L"2008"; - break; - - case WIN_7: - osname += L"7"; - break; - - case WIN_SERVER_2008_R2: - osname += L"2008r2"; - break; - - default: - wstringstream s; - s << CurrentOSMajor << L"." << CurrentOSMinor; - osname += s.str(); - break; - } - - if (server) - osname += L"-server"; - - if (IsOSAtLeast (WIN_VISTA)) - { - if (home) - osname += L"-home"; - else if (wcsstr (productName, L"Standard") != 0) - osname += L"-standard"; - else if (wcsstr (productName, L"Professional") != 0) - osname += L"-pro"; - else if (wcsstr (productName, L"Business") != 0) - osname += L"-business"; - else if (wcsstr (productName, L"Enterprise") != 0) - osname += L"-enterprise"; - else if (wcsstr (productName, L"Datacenter") != 0) - osname += L"-datacenter"; - else if (wcsstr (productName, L"Ultimate") != 0) - osname += L"-ultimate"; - } - - if (GetSystemMetrics (SM_STARTER)) - osname += L"-starter"; - else if (wcsstr (productName, L"Basic") != 0) - osname += L"-basic"; - - if (Is64BitOs()) - osname += L"-x64"; - - if (CurrentOSServicePack > 0) - { - wstringstream s; - s << L"-sp" << CurrentOSServicePack; - osname += s.str(); - } - - return osname; -} - - -void Applink (char *dest, BOOL bSendOS, char *extraOutput) -{ - char url [MAX_URL_LENGTH]; - - ArrowWaitCursor (); - - // sprintf_s (url, sizeof (url), TC_APPLINK "%s%s&dest=%s", bSendOS ? ("&os=" + GetWindowsEdition()).c_str() : "", extraOutput, dest); - if (strcmp(dest, "donate") == 0) - { - StringCbCopyA (url, sizeof (url),"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5BCXVMTTNJDCY"); - } - else if (strcmp(dest, "main") == 0) - { - StringCbCopyA (url, sizeof (url),TC_HOMEPAGE); - } - else if (strcmp(dest,"localizations") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Language%20Packs"); - } - else if (strcmp(dest, "beginnerstutorial") == 0 || strcmp(dest,"tutorial") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Beginner%27s%20Tutorial"); - } - else if (strcmp(dest, "releasenotes") == 0 || strcmp(dest, "history") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Release%20Notes"); - } - else if (strcmp(dest, "hwacceleration") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Hardware%20Acceleration"); - } - else if (strcmp(dest, "parallelization") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Parallelization"); - } - else if (strcmp(dest, "help") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/documentation"); - } - else if (strcmp(dest, "keyfiles") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Keyfiles"); - } - else if (strcmp(dest, "introcontainer") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Creating%20New%20Volumes"); - } - else if (strcmp(dest, "introsysenc") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=System%20Encryption"); - } - else if (strcmp(dest, "hiddensysenc") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=VeraCrypt%20Hidden%20Operating%20System"); - } - else if (strcmp(dest, "sysencprogressinfo") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=System%20Encryption"); - } - else if (strcmp(dest, "hiddenvolume") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Hidden%20Volume"); - } - else if (strcmp(dest, "aes") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=AES"); - } - else if (strcmp(dest, "serpent") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Serpent"); - } - else if (strcmp(dest, "twofish") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Twofish"); - } - else if (strcmp(dest, "cascades") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Cascades"); - } - else if (strcmp(dest, "hashalgorithms") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Hash%20Algorithms"); - } - else if (strcmp(dest, "isoburning") == 0) - { - StringCbCopyA (url, sizeof (url),"https://cdburnerxp.se/en/home"); - } - else if (strcmp(dest, "sysfavorites") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=System%20Favorite%20Volumes"); - } - else if (strcmp(dest, "favorites") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Favorite%20Volumes"); - } - else if (strcmp(dest, "hiddenvolprotection") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Protection%20of%20Hidden%20Volumes"); - } - else if (strcmp(dest, "faq") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=FAQ"); - } - else if (strcmp(dest, "downloads") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Downloads"); - } - else if (strcmp(dest, "news") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=News"); - } - else if (strcmp(dest, "contact") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Contact"); - } - else if (strcmp(dest, "pim") == 0) - { - StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Personal%20Iterations%20Multiplier%20%28PIM%29"); - } - else - { - StringCbCopyA (url, sizeof (url),TC_APPLINK); - } - ShellExecuteA (NULL, "open", url, NULL, NULL, SW_SHOWNORMAL); - - Sleep (200); - NormalCursor (); -} - - -wchar_t *RelativePath2Absolute (wchar_t *szFileName) -{ - if (szFileName[0] != L'\\' - && wcschr (szFileName, L':') == 0 - && wcsstr (szFileName, L"Volume{") != szFileName) - { - wchar_t path[MAX_PATH*2]; - GetCurrentDirectory (MAX_PATH, path); - - if (path[wcslen (path) - 1] != L'\\') - StringCbCatW (path, (MAX_PATH * 2), L"\\"); - - StringCbCatW (path, (MAX_PATH * 2), szFileName); - StringCbCopyW (szFileName, MAX_PATH + 1, path); // szFileName size is always at least (MAX_PATH + 1) - } - - return szFileName; -} - - -void HandleDriveNotReadyError (HWND hwnd) -{ - HKEY hkey = 0; - DWORD value = 0, size = sizeof (DWORD); - - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Services\\MountMgr", - 0, KEY_READ, &hkey) != ERROR_SUCCESS) - return; - - if (RegQueryValueEx (hkey, L"NoAutoMount", 0, 0, (LPBYTE) &value, &size) == ERROR_SUCCESS - && value != 0) - { - Warning ("SYS_AUTOMOUNT_DISABLED", hwnd); - } - else if (nCurrentOS == WIN_VISTA && CurrentOSServicePack < 1) - Warning ("SYS_ASSIGN_DRIVE_LETTER", hwnd); - else - Warning ("DEVICE_NOT_READY_ERROR", hwnd); - - RegCloseKey (hkey); -} - - -BOOL CALLBACK CloseTCWindowsEnum (HWND hwnd, LPARAM lParam) -{ - LONG_PTR userDataVal = GetWindowLongPtrW (hwnd, GWLP_USERDATA); - if ((userDataVal == (LONG_PTR) 'VERA') || (userDataVal == (LONG_PTR) 'TRUE')) // Prior to 1.0e, 'TRUE' was used for VeraCrypt dialogs - { - wchar_t name[1024] = { 0 }; - GetWindowText (hwnd, name, ARRAYSIZE (name) - 1); - if (hwnd != MainDlg && wcsstr (name, L"VeraCrypt")) - { - PostMessage (hwnd, TC_APPMSG_CLOSE_BKG_TASK, 0, 0); - - PostMessage (hwnd, WM_CLOSE, 0, 0); - - if (lParam != 0) - *((BOOL *)lParam) = TRUE; - } - } - return TRUE; -} - -BOOL CALLBACK FindTCWindowEnum (HWND hwnd, LPARAM lParam) -{ - if (*(HWND *)lParam == hwnd) - return TRUE; - - LONG_PTR userDataVal = GetWindowLongPtrW (hwnd, GWLP_USERDATA); - if ((userDataVal == (LONG_PTR) 'VERA') || (userDataVal == (LONG_PTR) 'TRUE')) // Prior to 1.0e, 'TRUE' was used for VeraCrypt dialogs - { - wchar_t name[32] = { 0 }; - GetWindowText (hwnd, name, ARRAYSIZE (name) - 1); - if (hwnd != MainDlg && wcscmp (name, L"VeraCrypt") == 0) - { - if (lParam != 0) - *((HWND *)lParam) = hwnd; - } - } - return TRUE; -} - - -BYTE *MapResource (wchar_t *resourceType, int resourceId, PDWORD size) -{ - HGLOBAL hResL; - HRSRC hRes; - - hRes = FindResource (NULL, MAKEINTRESOURCE(resourceId), resourceType); - hResL = LoadResource (NULL, hRes); - - if (size != NULL) - *size = SizeofResource (NULL, hRes); - - return (BYTE *) LockResource (hResL); -} - - -void InconsistencyResolved (char *techInfo) -{ - wchar_t finalMsg[8024]; - - StringCbPrintfW (finalMsg, sizeof(finalMsg), GetString ("INCONSISTENCY_RESOLVED"), techInfo); - MessageBoxW (MainDlg, finalMsg, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); -} - - -void ReportUnexpectedState (char *techInfo) -{ - wchar_t finalMsg[8024]; - - StringCbPrintfW (finalMsg, sizeof(finalMsg), GetString ("UNEXPECTED_STATE"), techInfo); - MessageBoxW (MainDlg, finalMsg, lpszTitle, MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); -} - - -#ifndef SETUP - -int OpenVolume (OpenVolumeContext *context, const wchar_t *volumePath, Password *password, int pkcs5_prf, int pim, BOOL truecryptMode, BOOL write, BOOL preserveTimestamps, BOOL useBackupHeader) -{ - int status = ERR_PARAMETER_INCORRECT; - int volumeType; - wchar_t szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH]; - wchar_t szDosDevice[TC_MAX_PATH]; - char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; - LARGE_INTEGER headerOffset; - DWORD dwResult; - DISK_GEOMETRY deviceGeometry; - - context->VolumeIsOpen = FALSE; - context->CryptoInfo = NULL; - context->HostFileHandle = INVALID_HANDLE_VALUE; - context->TimestampsValid = FALSE; - - CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), volumePath, &context->IsDevice); - - if (context->IsDevice) - { - status = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice), szCFDevice, sizeof(szCFDevice), FALSE); - if (status != 0) - return status; - - preserveTimestamps = FALSE; - - if (!GetDriveGeometry (volumePath, &deviceGeometry)) - { - status = ERR_OS_ERROR; - goto error; - } - } - else - StringCbCopyW (szCFDevice, sizeof(szCFDevice), szDiskFile); - - if (preserveTimestamps) - write = TRUE; - - context->HostFileHandle = CreateFile (szCFDevice, GENERIC_READ | (write ? GENERIC_WRITE : 0), FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (context->HostFileHandle == INVALID_HANDLE_VALUE) - { - status = ERR_OS_ERROR; - goto error; - } - - if (context->IsDevice) - { - // Try to gain "raw" access to the partition in case there is a live filesystem on it (otherwise, - // the NTFS driver guards hidden sectors and prevents e.g. header backup restore after the user - // accidentally quick-formats a dismounted partition-hosted TrueCrypt volume as NTFS, etc.) - - DeviceIoControl (context->HostFileHandle, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, 0, NULL, 0, &dwResult, NULL); - } - - context->VolumeIsOpen = TRUE; - - // Remember the container modification/creation date and time - if (!context->IsDevice && preserveTimestamps) - { - if (GetFileTime (context->HostFileHandle, &context->CreationTime, &context->LastAccessTime, &context->LastWriteTime) == 0) - context->TimestampsValid = FALSE; - else - context->TimestampsValid = TRUE; - } - - // Determine host size - if (context->IsDevice) - { - PARTITION_INFORMATION diskInfo; - - if (GetPartitionInfo (volumePath, &diskInfo)) - { - context->HostSize = diskInfo.PartitionLength.QuadPart; - } - else - { - DISK_GEOMETRY driveInfo; - - if (!DeviceIoControl (context->HostFileHandle, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveInfo, sizeof (driveInfo), &dwResult, NULL)) - { - status = ERR_OS_ERROR; - goto error; - } - - context->HostSize = driveInfo.Cylinders.QuadPart * driveInfo.BytesPerSector * driveInfo.SectorsPerTrack * driveInfo.TracksPerCylinder; - } - - if (context->HostSize == 0) - { - status = ERR_VOL_SIZE_WRONG; - goto error; - } - } - else - { - LARGE_INTEGER fileSize; - if (!GetFileSizeEx (context->HostFileHandle, &fileSize)) - { - status = ERR_OS_ERROR; - goto error; - } - - context->HostSize = fileSize.QuadPart; - } - - for (volumeType = TC_VOLUME_TYPE_NORMAL; volumeType < TC_VOLUME_TYPE_COUNT; volumeType++) - { - // Seek the volume header - switch (volumeType) - { - case TC_VOLUME_TYPE_NORMAL: - headerOffset.QuadPart = useBackupHeader ? context->HostSize - TC_VOLUME_HEADER_GROUP_SIZE : TC_VOLUME_HEADER_OFFSET; - break; - - case TC_VOLUME_TYPE_HIDDEN: - if (TC_HIDDEN_VOLUME_HEADER_OFFSET + TC_VOLUME_HEADER_SIZE > context->HostSize) - continue; - - headerOffset.QuadPart = useBackupHeader ? context->HostSize - TC_VOLUME_HEADER_SIZE : TC_HIDDEN_VOLUME_HEADER_OFFSET; - break; - - } - - if (!SetFilePointerEx ((HANDLE) context->HostFileHandle, headerOffset, NULL, FILE_BEGIN)) - { - status = ERR_OS_ERROR; - goto error; - } - - // Read volume header - DWORD bytesRead; - if (!ReadEffectiveVolumeHeader (context->IsDevice, context->HostFileHandle, (byte *) buffer, &bytesRead)) - { - status = ERR_OS_ERROR; - goto error; - } - - if (bytesRead != sizeof (buffer) - && context->IsDevice) - { - // If FSCTL_ALLOW_EXTENDED_DASD_IO failed and there is a live filesystem on the partition, then the - // filesystem driver may report EOF when we are reading hidden sectors (when the filesystem is - // shorter than the partition). This can happen for example after the user quick-formats a dismounted - // partition-hosted TrueCrypt volume and then tries to read the embedded backup header. - - memset (buffer, 0, sizeof (buffer)); - } - - // Decrypt volume header - status = ReadVolumeHeader (FALSE, buffer, password, pkcs5_prf, pim, truecryptMode, &context->CryptoInfo, NULL); - - if (status == ERR_PASSWORD_WRONG) - continue; // Try next volume type - - break; - } - - if (status == ERR_SUCCESS) - return status; - -error: - DWORD sysError = GetLastError (); - - CloseVolume (context); - - SetLastError (sysError); - return status; -} - - -void CloseVolume (OpenVolumeContext *context) -{ - if (!context->VolumeIsOpen) - return; - - if (context->HostFileHandle != INVALID_HANDLE_VALUE) - { - if (context->TimestampsValid) - SetFileTime (context->HostFileHandle, &context->CreationTime, &context->LastAccessTime, &context->LastWriteTime); - - CloseHandle (context->HostFileHandle); - context->HostFileHandle = INVALID_HANDLE_VALUE; - } - - if (context->CryptoInfo) - { - crypto_close (context->CryptoInfo); - context->CryptoInfo = NULL; - } - - context->VolumeIsOpen = FALSE; -} - - -int ReEncryptVolumeHeader (HWND hwndDlg, char *buffer, BOOL bBoot, CRYPTO_INFO *cryptoInfo, Password *password, int pim, BOOL wipeMode) -{ - CRYPTO_INFO *newCryptoInfo = NULL; - - RandSetHashFunction (cryptoInfo->pkcs5); - - if (Randinit() != ERR_SUCCESS) - { - if (CryptoAPILastError == ERROR_SUCCESS) - return ERR_RAND_INIT_FAILED; - else - return ERR_CAPI_INIT_FAILED; - } - - UserEnrichRandomPool (NULL); - - int status = CreateVolumeHeaderInMemory (hwndDlg, bBoot, - buffer, - cryptoInfo->ea, - cryptoInfo->mode, - password, - cryptoInfo->pkcs5, - pim, - (char *) cryptoInfo->master_keydata, - &newCryptoInfo, - cryptoInfo->VolumeSize.Value, - cryptoInfo->hiddenVolume ? cryptoInfo->hiddenVolumeSize : 0, - cryptoInfo->EncryptedAreaStart.Value, - cryptoInfo->EncryptedAreaLength.Value, - cryptoInfo->RequiredProgramVersion, - cryptoInfo->HeaderFlags, - cryptoInfo->SectorSize, - wipeMode); - - if (newCryptoInfo != NULL) - crypto_close (newCryptoInfo); - - return status; -} - -#endif // !SETUP - - -BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) -{ - // GlobalMemoryStatusEx() cannot be used to determine if a paging file is active - - wchar_t data[65536]; - DWORD size = sizeof (data); - - if (IsPagingFileWildcardActive()) - return TRUE; - - if (ReadLocalMachineRegistryMultiString (L"System\\CurrentControlSet\\Control\\Session Manager\\Memory Management", L"PagingFiles", data, &size) - && size > 24 && !checkNonWindowsPartitionsOnly) - return TRUE; - - if (!IsAdmin()) - AbortProcess ("UAC_INIT_ERROR"); - - for (wchar_t drive = L'C'; drive <= L'Z'; ++drive) - { - // Query geometry of the drive first to prevent "no medium" pop-ups - wstring drivePath = L"\\\\.\\X:"; - drivePath[4] = drive; - - if (checkNonWindowsPartitionsOnly) - { - wchar_t sysDir[MAX_PATH]; - if (GetSystemDirectory (sysDir, ARRAYSIZE (sysDir)) != 0 && towupper (sysDir[0]) == drive) - continue; - } - - HANDLE handle = CreateFile (drivePath.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (handle == INVALID_HANDLE_VALUE) - continue; - - DISK_GEOMETRY driveInfo; - DWORD dwResult; - - if (!DeviceIoControl (handle, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveInfo, sizeof (driveInfo), &dwResult, NULL)) - { - CloseHandle (handle); - continue; - } - - CloseHandle (handle); - - // Test if a paging file exists and is locked by another process - wstring path = L"X:\\pagefile.sys"; - path[0] = drive; - - handle = CreateFile (path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); - - if (handle != INVALID_HANDLE_VALUE) - CloseHandle (handle); - else if (GetLastError() == ERROR_SHARING_VIOLATION) - return TRUE; - } - - return FALSE; -} - - -BOOL IsPagingFileWildcardActive () -{ - wchar_t pagingFiles[65536]; - DWORD size = sizeof (pagingFiles); - wchar_t *mmKey = L"System\\CurrentControlSet\\Control\\Session Manager\\Memory Management"; - - if (!ReadLocalMachineRegistryString (mmKey, L"PagingFiles", pagingFiles, &size)) - { - size = sizeof (pagingFiles); - if (!ReadLocalMachineRegistryMultiString (mmKey, L"PagingFiles", pagingFiles, &size)) - size = 0; - } - - return size > 0 && wcsstr (pagingFiles, L"?:\\") == pagingFiles; -} - - -BOOL DisablePagingFile () -{ - wchar_t empty[] = { 0, 0 }; - return WriteLocalMachineRegistryMultiString (L"System\\CurrentControlSet\\Control\\Session Manager\\Memory Management", L"PagingFiles", empty, sizeof (empty)); -} - - -std::wstring SingleStringToWide (const std::string &singleString) -{ - if (singleString.empty()) - return std::wstring(); - - WCHAR wbuf[65536]; - int wideLen = MultiByteToWideChar (CP_ACP, 0, singleString.c_str(), -1, wbuf, array_capacity (wbuf) - 1); - - // We don't throw exception here and only return empty string. - // All calls to this function use valid strings. - // throw_sys_if (wideLen == 0); - - wbuf[wideLen] = 0; - return wbuf; -} - - -std::wstring Utf8StringToWide (const std::string &utf8String) -{ - if (utf8String.empty()) - return std::wstring(); - - WCHAR wbuf[65536]; - int wideLen = MultiByteToWideChar (CP_UTF8, 0, utf8String.c_str(), -1, wbuf, array_capacity (wbuf) - 1); - throw_sys_if (wideLen == 0); - - wbuf[wideLen] = 0; - return wbuf; -} - - -std::string WideToUtf8String (const std::wstring &wideString) -{ - if (wideString.empty()) - return std::string(); - - char buf[65536]; - int len = WideCharToMultiByte (CP_UTF8, 0, wideString.c_str(), -1, buf, array_capacity (buf) - 1, NULL, NULL); - throw_sys_if (len == 0); - - buf[len] = 0; - return buf; -} - - -#ifndef SETUP - -BOOL CALLBACK SecurityTokenPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - static string *password; - - switch (msg) - { - case WM_INITDIALOG: - { - password = (string *) lParam; - LocalizeDialog (hwndDlg, "IDD_TOKEN_PASSWORD"); - - wchar_t s[1024]; - StringCbPrintfW (s, sizeof(s), GetString ("ENTER_TOKEN_PASSWORD"), Utf8StringToWide (password->c_str()).c_str()); - SetWindowTextW (GetDlgItem (hwndDlg, IDT_TOKEN_PASSWORD_INFO), s); - - SendMessage (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD), EM_LIMITTEXT, SecurityToken::MaxPasswordLength, 0); - - SetForegroundWindow (hwndDlg); - SetFocus (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD)); - } - return 0; - - case WM_COMMAND: - if (lw == IDCANCEL || lw == IDOK) - { - if (lw == IDOK) - { - wchar_t passwordWide[SecurityToken::MaxPasswordLength + 1]; - - if (GetWindowTextW (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD), passwordWide, SecurityToken::MaxPasswordLength + 1) == 0) - { - handleWin32Error (hwndDlg, SRC_POS); - break; - } - - char passwordUtf8[SecurityToken::MaxPasswordLength + 1]; - - int len = WideCharToMultiByte (CP_UTF8, 0, passwordWide, -1, passwordUtf8, array_capacity (passwordUtf8) - 1, nullptr, nullptr); - passwordUtf8[len] = 0; - *password = passwordUtf8; - - burn (passwordWide, sizeof (passwordWide)); - burn (passwordUtf8, sizeof (passwordUtf8)); - } - - // Attempt to wipe password stored in the input field buffer - wchar_t tmp[SecurityToken::MaxPasswordLength+1]; - wmemset (tmp, 'X', SecurityToken::MaxPasswordLength); - tmp[SecurityToken::MaxPasswordLength] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD), tmp); - - EndDialog (hwndDlg, lw); - } - return 1; - } - - return 0; -} - - -struct NewSecurityTokenKeyfileDlgProcParams -{ - CK_SLOT_ID SlotId; - string Name; -}; - -static BOOL CALLBACK NewSecurityTokenKeyfileDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - static NewSecurityTokenKeyfileDlgProcParams *newParams; - - WORD lw = LOWORD (wParam); - switch (msg) - { - case WM_INITDIALOG: - { - LocalizeDialog (hwndDlg, "IDD_NEW_TOKEN_KEYFILE"); - - newParams = (NewSecurityTokenKeyfileDlgProcParams *) lParam; - - WaitCursor(); - finally_do ({ NormalCursor(); }); - - list tokens; - - try - { - tokens = SecurityToken::GetAvailableTokens(); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - - if (tokens.empty()) - { - Error ("NO_TOKENS_FOUND", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - foreach (const SecurityTokenInfo &token, tokens) - { - wstringstream tokenLabel; - tokenLabel << L"[" << token.SlotId << L"] " << token.Label; - - AddComboPair (GetDlgItem (hwndDlg, IDC_SELECTED_TOKEN), tokenLabel.str().c_str(), token.SlotId); - } - - ComboBox_SetCurSel (GetDlgItem (hwndDlg, IDC_SELECTED_TOKEN), 0); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_TOKEN_KEYFILE_NAME), Utf8StringToWide (newParams->Name).c_str()); - return 1; - } - - case WM_COMMAND: - switch (lw) - { - case IDOK: - { - int selectedToken = ComboBox_GetCurSel (GetDlgItem (hwndDlg, IDC_SELECTED_TOKEN)); - if (selectedToken == CB_ERR) - { - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - newParams->SlotId = (CK_SLOT_ID) ComboBox_GetItemData (GetDlgItem (hwndDlg, IDC_SELECTED_TOKEN), selectedToken); - - wchar_t name[1024]; - if (GetWindowTextW (GetDlgItem (hwndDlg, IDC_TOKEN_KEYFILE_NAME), name, array_capacity (name)) != 0) - { - try - { - newParams->Name = WideToUtf8String (name); - } - catch (...) { } - } - - EndDialog (hwndDlg, IDOK); - return 1; - } - - case IDCANCEL: - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - if (HIWORD (wParam) == EN_CHANGE) - { - wchar_t name[2]; - EnableWindow (GetDlgItem (hwndDlg, IDOK), (GetWindowTextW (GetDlgItem (hwndDlg, IDC_TOKEN_KEYFILE_NAME), name, array_capacity (name)) != 0)); - return 1; - } - } - - return 0; -} - - -static void SecurityTokenKeyfileDlgFillList (HWND hwndDlg, const vector &keyfiles) -{ - HWND tokenListControl = GetDlgItem (hwndDlg, IDC_TOKEN_FILE_LIST); - LVITEMW lvItem; - int line = 0; - - ListView_DeleteAllItems (tokenListControl); - - foreach (const SecurityTokenKeyfile &keyfile, keyfiles) - { - memset (&lvItem, 0, sizeof(lvItem)); - lvItem.mask = LVIF_TEXT; - lvItem.iItem = line++; - - wstringstream s; - s << keyfile.SlotId; - - ListItemAdd (tokenListControl, lvItem.iItem, (wchar_t *) s.str().c_str()); - ListSubItemSet (tokenListControl, lvItem.iItem, 1, (wchar_t *) keyfile.Token.Label.c_str()); - ListSubItemSet (tokenListControl, lvItem.iItem, 2, (wchar_t *) keyfile.Id.c_str()); - } - - BOOL selected = (ListView_GetNextItem (GetDlgItem (hwndDlg, IDC_TOKEN_FILE_LIST), -1, LVIS_SELECTED) != -1); - EnableWindow (GetDlgItem (hwndDlg, IDC_EXPORT), selected); - EnableWindow (GetDlgItem (hwndDlg, IDC_DELETE), selected); -} - - -static list SecurityTokenKeyfileDlgGetSelected (HWND hwndDlg, const vector &keyfiles) -{ - HWND tokenListControl = GetDlgItem (hwndDlg, IDC_TOKEN_FILE_LIST); - list selectedKeyfiles; - - int itemId = -1; - while ((itemId = ListView_GetNextItem (tokenListControl, itemId, LVIS_SELECTED)) != -1) - { - selectedKeyfiles.push_back (keyfiles[itemId]); - } - - return selectedKeyfiles; -} - - -BOOL CALLBACK SecurityTokenKeyfileDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - static list *selectedTokenKeyfiles; - static vector keyfiles; - - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - selectedTokenKeyfiles = (list *) lParam; - - LVCOLUMNW LvCol; - HWND tokenListControl = GetDlgItem (hwndDlg, IDC_TOKEN_FILE_LIST); - - LocalizeDialog (hwndDlg, selectedTokenKeyfiles ? "SELECT_TOKEN_KEYFILES" : "IDD_TOKEN_KEYFILES"); - - SendMessage (tokenListControl,LVM_SETEXTENDEDLISTVIEWSTYLE, 0, - LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_TWOCLICKACTIVATE|LVS_EX_LABELTIP - ); - - memset (&LvCol, 0, sizeof(LvCol)); - LvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; - LvCol.pszText = GetString ("TOKEN_SLOT_ID"); - LvCol.cx = CompensateXDPI (40); - LvCol.fmt = LVCFMT_CENTER; - SendMessage (tokenListControl, LVM_INSERTCOLUMNW, 1, (LPARAM)&LvCol); - - LvCol.pszText = GetString ("TOKEN_NAME"); - LvCol.cx = CompensateXDPI (128); - LvCol.fmt = LVCFMT_LEFT; - SendMessage (tokenListControl, LVM_INSERTCOLUMNW, 2, (LPARAM)&LvCol); - - LvCol.pszText = GetString ("TOKEN_DATA_OBJECT_LABEL"); - LvCol.cx = CompensateXDPI (195); - LvCol.fmt = LVCFMT_LEFT; - SendMessage (tokenListControl, LVM_INSERTCOLUMNW, 3, (LPARAM)&LvCol); - - keyfiles.clear(); - - try - { - WaitCursor(); - finally_do ({ NormalCursor(); }); - - keyfiles = SecurityToken::GetAvailableKeyfiles(); - } - catch (UserAbort&) - { - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - catch (Exception &e) - { - e.Show (hwndDlg); - - if (keyfiles.empty()) - { - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - } - - SecurityTokenKeyfileDlgFillList (hwndDlg, keyfiles); - return 1; - } - - case WM_COMMAND: - case WM_NOTIFY: - if (msg == WM_COMMAND && lw == IDOK || msg == WM_NOTIFY && ((NMHDR *)lParam)->code == LVN_ITEMACTIVATE) - { - if (selectedTokenKeyfiles) - { - foreach (const SecurityTokenKeyfile &keyfile, SecurityTokenKeyfileDlgGetSelected (hwndDlg, keyfiles)) - { - selectedTokenKeyfiles->push_back (SecurityTokenKeyfilePath (keyfile)); - } - } - - EndDialog (hwndDlg, IDOK); - return 1; - } - - if (msg == WM_NOTIFY && ((LPNMHDR) lParam)->code == LVN_ITEMCHANGED) - { - BOOL selected = (ListView_GetNextItem (GetDlgItem (hwndDlg, IDC_TOKEN_FILE_LIST), -1, LVIS_SELECTED) != -1); - EnableWindow (GetDlgItem (hwndDlg, IDC_EXPORT), selected); - EnableWindow (GetDlgItem (hwndDlg, IDC_DELETE), selected); - return 1; - } - - if (msg == WM_COMMAND) - { - switch (lw) - { - case IDCANCEL: - EndDialog (hwndDlg, IDCANCEL); - return 1; - - case IDC_IMPORT_KEYFILE: - { - wchar_t keyfilePath[TC_MAX_PATH]; - - if (BrowseFiles (hwndDlg, "SELECT_KEYFILE", keyfilePath, bHistory, FALSE, NULL)) - { - DWORD keyfileSize; - byte *keyfileData = (byte *) LoadFile (keyfilePath, &keyfileSize); - if (!keyfileData) - { - handleWin32Error (hwndDlg, SRC_POS); - return 1; - } - - if (keyfileSize != 0) - { - NewSecurityTokenKeyfileDlgProcParams newParams; - newParams.Name = WideToUtf8String (keyfilePath); - - size_t lastBackSlash = newParams.Name.find_last_of ('\\'); - if (lastBackSlash != string::npos) - newParams.Name = newParams.Name.substr (lastBackSlash + 1); - - if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_NEW_TOKEN_KEYFILE), hwndDlg, (DLGPROC) NewSecurityTokenKeyfileDlgProc, (LPARAM) &newParams) == IDOK) - { - vector keyfileDataVector (keyfileSize); - memcpy (&keyfileDataVector.front(), keyfileData, keyfileSize); - - try - { - WaitCursor(); - finally_do ({ NormalCursor(); }); - - SecurityToken::CreateKeyfile (newParams.SlotId, keyfileDataVector, newParams.Name); - - keyfiles = SecurityToken::GetAvailableKeyfiles(); - SecurityTokenKeyfileDlgFillList (hwndDlg, keyfiles); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - - burn (&keyfileDataVector.front(), keyfileSize); - } - } - else - { - SetLastError (ERROR_HANDLE_EOF); - handleWin32Error (hwndDlg, SRC_POS); - } - - burn (keyfileData, keyfileSize); - TCfree (keyfileData); - } - - return 1; - } - - case IDC_EXPORT: - { - try - { - foreach (const SecurityTokenKeyfile &keyfile, SecurityTokenKeyfileDlgGetSelected (hwndDlg, keyfiles)) - { - wchar_t keyfilePath[TC_MAX_PATH]; - - if (!BrowseFiles (hwndDlg, "OPEN_TITLE", keyfilePath, bHistory, TRUE, NULL)) - break; - - { - WaitCursor(); - finally_do ({ NormalCursor(); }); - - vector keyfileData; - - SecurityToken::GetKeyfileData (keyfile, keyfileData); - - if (keyfileData.empty()) - { - SetLastError (ERROR_HANDLE_EOF); - handleWin32Error (hwndDlg, SRC_POS); - return 1; - } - - finally_do_arg (vector *, &keyfileData, { burn (&finally_arg->front(), finally_arg->size()); }); - - if (!SaveBufferToFile ((char *) &keyfileData.front(), keyfilePath, (DWORD) keyfileData.size(), FALSE, FALSE)) - throw SystemException (SRC_POS); - } - - Info ("KEYFILE_EXPORTED", hwndDlg); - } - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - - return 1; - } - - case IDC_DELETE: - { - if (AskNoYes ("CONFIRM_SEL_FILES_DELETE", hwndDlg) == IDNO) - return 1; - - try - { - WaitCursor(); - finally_do ({ NormalCursor(); }); - - foreach (const SecurityTokenKeyfile &keyfile, SecurityTokenKeyfileDlgGetSelected (hwndDlg, keyfiles)) - { - SecurityToken::DeleteKeyfile (keyfile); - } - - keyfiles = SecurityToken::GetAvailableKeyfiles(); - SecurityTokenKeyfileDlgFillList (hwndDlg, keyfiles); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - - return 1; - } - } - } - return 0; - } - return 0; -} - - -BOOL InitSecurityTokenLibrary (HWND hwndDlg) -{ - if (SecurityTokenLibraryPath[0] == 0) - { - Error ("NO_PKCS11_MODULE_SPECIFIED", hwndDlg); - return FALSE; - } - - struct PinRequestHandler : public GetPinFunctor - { - HWND m_hwnd; - PinRequestHandler(HWND hwnd) : m_hwnd(hwnd) {} - virtual void operator() (string &str) - { - HWND hParent = IsWindow (m_hwnd)? m_hwnd : GetActiveWindow(); - if (!hParent) - hParent = GetForegroundWindow (); - if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TOKEN_PASSWORD), hParent, (DLGPROC) SecurityTokenPasswordDlgProc, (LPARAM) &str) == IDCANCEL) - throw UserAbort (SRC_POS); - - if (hCursor != NULL) - SetCursor (hCursor); - } - }; - - struct WarningHandler : public SendExceptionFunctor - { - HWND m_hwnd; - WarningHandler(HWND hwnd) : m_hwnd(hwnd) {} - virtual void operator() (const Exception &e) - { - HWND hParent = IsWindow (m_hwnd)? m_hwnd : GetActiveWindow(); - if (!hParent) - hParent = GetForegroundWindow (); - e.Show (hParent); - } - }; - - try - { - SecurityToken::InitLibrary (SecurityTokenLibraryPath, auto_ptr (new PinRequestHandler(MainDlg)), auto_ptr (new WarningHandler(MainDlg))); - } - catch (Exception &e) - { - e.Show (hwndDlg); - Error ("PKCS11_MODULE_INIT_FAILED", hwndDlg); - return FALSE; - } - - return TRUE; -} - -#endif // !SETUP - -std::vector GetAvailableHostDevices (bool noDeviceProperties, bool singleList, bool noFloppy, bool detectUnencryptedFilesystems) -{ - vector devices; - size_t dev0; - - for (int devNumber = 0; devNumber < MAX_HOST_DRIVE_NUMBER; devNumber++) - { - for (int partNumber = 0; partNumber < MAX_HOST_PARTITION_NUMBER; partNumber++) - { - wstringstream strm; - strm << L"\\Device\\Harddisk" << devNumber << L"\\Partition" << partNumber; - wstring devPathStr (strm.str()); - const wchar_t *devPath = devPathStr.c_str(); - - OPEN_TEST_STRUCT openTest = {0}; - if (!OpenDevice (devPath, &openTest, detectUnencryptedFilesystems && partNumber != 0, FALSE, NULL)) - { - if (partNumber == 0) - break; - - continue; - } - - HostDevice device; - device.SystemNumber = devNumber; - device.Path = devPath; - - PARTITION_INFORMATION partInfo; - - if (GetPartitionInfo (devPath, &partInfo)) - { - device.Bootable = partInfo.BootIndicator ? true : false; - device.Size = partInfo.PartitionLength.QuadPart; - } - else - { - // retrieve size using DISK_GEOMETRY - DISK_GEOMETRY deviceGeometry = {0}; - if ( GetDriveGeometry (devPath, &deviceGeometry) - || ((partNumber == 0) && GetPhysicalDriveGeometry (devNumber, &deviceGeometry)) - ) - { - device.Size = deviceGeometry.Cylinders.QuadPart * (LONGLONG) deviceGeometry.BytesPerSector - * (LONGLONG) deviceGeometry.SectorsPerTrack * (LONGLONG) deviceGeometry.TracksPerCylinder; - } - } - - device.HasUnencryptedFilesystem = (detectUnencryptedFilesystems && openTest.FilesystemDetected) ? true : false; - - if (!noDeviceProperties) - { - DISK_GEOMETRY geometry; - - int driveNumber = GetDiskDeviceDriveLetter ((wchar_t *) devPathStr.c_str()); - - if (driveNumber >= 0) - { - device.MountPoint += (wchar_t) (driveNumber + L'A'); - device.MountPoint += L":"; - - wchar_t name[64]; - if (GetDriveLabel (driveNumber, name, sizeof (name))) - device.Name = name; - - if (GetSystemDriveLetter() == L'A' + driveNumber) - device.ContainsSystem = true; - } - - if (partNumber == 0 && GetDriveGeometry (devPath, &geometry)) - device.Removable = (geometry.MediaType == RemovableMedia); - } - - if (partNumber == 0) - { - devices.push_back (device); - dev0 = devices.size() - 1; - } - else - { - // System creates a virtual partition1 for some storage devices without - // partition table. We try to detect this case by comparing sizes of - // partition0 and partition1. If they match, no partition of the device - // is displayed to the user to avoid confusion. Drive letter assigned by - // system to partition1 is assigned partition0 - if (partNumber == 1 && devices[dev0].Size == device.Size) - { - devices[dev0].IsVirtualPartition = true; - devices[dev0].MountPoint = device.MountPoint; - devices[dev0].Name = device.Name; - devices[dev0].Path = device.Path; - devices[dev0].HasUnencryptedFilesystem = device.HasUnencryptedFilesystem; - break; - } - - device.IsPartition = true; - device.SystemNumber = partNumber; - device.Removable = devices[dev0].Removable; - - if (device.ContainsSystem) - devices[dev0].ContainsSystem = true; - - if (singleList) - devices.push_back (device); - - devices[dev0].Partitions.push_back (device); - } - } - } - - // Vista does not create partition links for dynamic volumes so it is necessary to scan \\Device\\HarddiskVolumeX devices - if (CurrentOSMajor >= 6) - { - for (int devNumber = 0; devNumber < 256; devNumber++) - { - wstringstream strm; - strm << L"\\Device\\HarddiskVolume" << devNumber; - wstring devPathStr (strm.str()); - const wchar_t *devPath = devPathStr.c_str(); - - OPEN_TEST_STRUCT openTest = {0}; - if (!OpenDevice (devPath, &openTest, detectUnencryptedFilesystems, FALSE, NULL)) - continue; - - DISK_PARTITION_INFO_STRUCT info; - if (GetDeviceInfo (devPath, &info) && info.IsDynamic) - { - HostDevice device; - device.DynamicVolume = true; - device.IsPartition = true; - device.SystemNumber = devNumber; - device.Path = devPath; - device.Size = info.partInfo.PartitionLength.QuadPart; - device.HasUnencryptedFilesystem = (detectUnencryptedFilesystems && openTest.FilesystemDetected) ? true : false; - - if (!noDeviceProperties) - { - int driveNumber = GetDiskDeviceDriveLetter ((wchar_t *) devPathStr.c_str()); - - if (driveNumber >= 0) - { - device.MountPoint += (wchar_t) (driveNumber + L'A'); - device.MountPoint += L":"; - - wchar_t name[64]; - if (GetDriveLabel (driveNumber, name, sizeof (name))) - device.Name = name; - - if (GetSystemDriveLetter() == L'A' + driveNumber) - device.ContainsSystem = true; - } - } - - devices.push_back (device); - } - } - } - - return devices; -} - -wstring FindDeviceByVolumeID (const BYTE volumeID [VOLUME_ID_SIZE]) -{ - /* if it is already mounted, get the real path name used for mounting */ - MOUNT_LIST_STRUCT mlist; - DWORD dwResult; - - memset (&mlist, 0, sizeof (mlist)); - DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mlist, - sizeof (mlist), &mlist, sizeof (mlist), &dwResult, - NULL); - - for (int i=0 ; i < 26; i++) - { - if (0 == memcmp (mlist.volumeID[i], volumeID, VOLUME_ID_SIZE)) - return mlist.wszVolume[i]; - } - - /* not mounted. Look for it in the local drives*/ - for (int devNumber = 0; devNumber < MAX_HOST_DRIVE_NUMBER; devNumber++) - { - for (int partNumber = 0; partNumber < MAX_HOST_PARTITION_NUMBER; partNumber++) - { - wstringstream strm; - strm << L"\\Device\\Harddisk" << devNumber << L"\\Partition" << partNumber; - wstring devPathStr (strm.str()); - const wchar_t *devPath = devPathStr.c_str(); - - OPEN_TEST_STRUCT openTest = {0}; - if (!OpenDevice (devPath, &openTest, FALSE, TRUE, volumeID)) - { - continue; - } - - if (openTest.VolumeIDMatched) - return devPath; - } - } - - return L""; -} - -BOOL FileHasReadOnlyAttribute (const wchar_t *path) -{ - DWORD attributes = GetFileAttributes (path); - return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_READONLY) != 0; -} - - -BOOL IsFileOnReadOnlyFilesystem (const wchar_t *path) -{ - wchar_t root[MAX_PATH]; - if (!GetVolumePathName (path, root, ARRAYSIZE (root))) - return FALSE; - - DWORD flags, d; - if (!GetVolumeInformation (root, NULL, 0, NULL, &d, &flags, NULL, 0)) - return FALSE; - - return (flags & FILE_READ_ONLY_VOLUME) ? TRUE : FALSE; -} - - -void CheckFilesystem (HWND hwndDlg, int driveNo, BOOL fixErrors) -{ - wchar_t msg[1024], param[1024], cmdPath[MAX_PATH]; - wchar_t driveRoot[] = { L'A' + (wchar_t) driveNo, L':', 0 }; - - if (fixErrors && AskWarnYesNo ("FILESYS_REPAIR_CONFIRM_BACKUP", hwndDlg) == IDNO) - return; - - StringCbPrintfW (msg, sizeof(msg), GetString (fixErrors ? "REPAIRING_FS" : "CHECKING_FS"), driveRoot); - StringCbPrintfW (param, sizeof(param), fixErrors ? L"/C echo %s & chkdsk %s /F /X & pause" : L"/C echo %s & chkdsk %s & pause", msg, driveRoot); - - if (GetSystemDirectoryW(cmdPath, MAX_PATH)) - { - StringCbCatW(cmdPath, sizeof(cmdPath), L"\\cmd.exe"); - } - else - StringCbCopyW(cmdPath, sizeof(cmdPath), L"C:\\Windows\\System32\\cmd.exe"); - - ShellExecuteW (NULL, (!IsAdmin() && IsUacSupported()) ? L"runas" : L"open", cmdPath, param, NULL, SW_SHOW); -} - - -BOOL BufferContainsString (const byte *buffer, size_t bufferSize, const char *str) -{ - size_t strLen = strlen (str); - - if (bufferSize < strLen) - return FALSE; - - bufferSize -= strLen; - - for (size_t i = 0; i < bufferSize; ++i) - { - if (memcmp (buffer + i, str, strLen) == 0) - return TRUE; - } - - return FALSE; -} - - -#ifndef SETUP - -int AskNonSysInPlaceEncryptionResume (HWND hwndDlg, BOOL *pbDecrypt) -{ - if (AskWarnYesNo ("NONSYS_INPLACE_ENC_RESUME_PROMPT", hwndDlg) == IDYES) - { - char *tmpStr[] = {0, - "CHOOSE_ENCRYPT_OR_DECRYPT", - "ENCRYPT", - "DECRYPT", - "IDCANCEL", - 0}; - - switch (AskMultiChoice ((void **) tmpStr, FALSE, hwndDlg)) - { - case 1: - *pbDecrypt = FALSE; - return IDYES; - case 2: - *pbDecrypt = TRUE; - return IDYES; - default: - break; - } - } - - char *multiChoiceStr[] = { 0, "ASK_NONSYS_INPLACE_ENC_NOTIFICATION_REMOVAL", "DO_NOT_PROMPT_ME", "KEEP_PROMPTING_ME", 0 }; - - switch (AskMultiChoice ((void **) multiChoiceStr, FALSE, hwndDlg)) - { - case 1: - RemoveNonSysInPlaceEncNotifications(); - Warning ("NONSYS_INPLACE_ENC_NOTIFICATION_REMOVAL_NOTE", hwndDlg); - break; - - default: - // NOP - break; - } - - return IDNO; -} - -#endif // !SETUP - - -BOOL RemoveDeviceWriteProtection (HWND hwndDlg, wchar_t *devicePath) -{ - int driveNumber; - int partitionNumber; - - wchar_t temp[MAX_PATH*2]; - wchar_t cmdBatch[MAX_PATH*2]; - wchar_t diskpartScript[MAX_PATH*2]; - - if (swscanf (devicePath, L"\\Device\\Harddisk%d\\Partition%d", &driveNumber, &partitionNumber) != 2) - return FALSE; - - if (GetTempPath (ARRAYSIZE (temp), temp) == 0) - return FALSE; - - StringCbPrintfW (cmdBatch, sizeof (cmdBatch), L"%s\\VeraCrypt_Write_Protection_Removal.cmd", temp); - StringCbPrintfW (diskpartScript, sizeof (diskpartScript), L"%s\\VeraCrypt_Write_Protection_Removal.diskpart", temp); - - FILE *f = _wfopen (cmdBatch, L"w"); - if (!f) - { - handleWin32Error (hwndDlg, SRC_POS); - return FALSE; - } - - fwprintf (f, L"@diskpart /s \"%s\"\n@pause\n@del \"%s\" \"%s\"", diskpartScript, diskpartScript, cmdBatch); - - CheckFileStreamWriteErrors (hwndDlg, f, cmdBatch); - fclose (f); - - f = _wfopen (diskpartScript, L"w"); - if (!f) - { - handleWin32Error (hwndDlg, SRC_POS); - DeleteFile (cmdBatch); - return FALSE; - } - - fwprintf (f, L"select disk %d\nattributes disk clear readonly\n", driveNumber); - - if (partitionNumber != 0) - fwprintf (f, L"select partition %d\nattributes volume clear readonly\n", partitionNumber); - - fwprintf (f, L"exit\n"); - - CheckFileStreamWriteErrors (hwndDlg, f, diskpartScript); - fclose (f); - - ShellExecute (NULL, (!IsAdmin() && IsUacSupported()) ? L"runas" : L"open", cmdBatch, NULL, NULL, SW_SHOW); - - return TRUE; -} - - -static LRESULT CALLBACK EnableElevatedCursorChangeWndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - return DefWindowProcW (hWnd, message, wParam, lParam); -} - - -void EnableElevatedCursorChange (HWND parent) -{ - // Create a transparent window to work around a UAC issue preventing change of the cursor - if (UacElevated) - { - const wchar_t *className = L"VeraCryptEnableElevatedCursorChange"; - WNDCLASSEXW winClass; - HWND hWnd; - - memset (&winClass, 0, sizeof (winClass)); - winClass.cbSize = sizeof (WNDCLASSEX); - winClass.lpfnWndProc = (WNDPROC) EnableElevatedCursorChangeWndProc; - winClass.hInstance = hInst; - winClass.lpszClassName = className; - RegisterClassExW (&winClass); - - hWnd = CreateWindowExW (WS_EX_TOOLWINDOW | WS_EX_LAYERED, className, L"VeraCrypt UAC", 0, 0, 0, GetSystemMetrics (SM_CXSCREEN), GetSystemMetrics (SM_CYSCREEN), parent, NULL, hInst, NULL); - if (hWnd) - { - SetLayeredWindowAttributes (hWnd, 0, 1, LWA_ALPHA); - ShowWindow (hWnd, SW_SHOWNORMAL); - - DestroyWindow (hWnd); - } - UnregisterClassW (className, hInst); - } -} - - -BOOL DisableFileCompression (HANDLE file) -{ - USHORT format; - DWORD bytesOut; - - if (!DeviceIoControl (file, FSCTL_GET_COMPRESSION, NULL, 0, &format, sizeof (format), &bytesOut, NULL)) - return FALSE; - - if (format == COMPRESSION_FORMAT_NONE) - return TRUE; - - format = COMPRESSION_FORMAT_NONE; - return DeviceIoControl (file, FSCTL_SET_COMPRESSION, &format, sizeof (format), NULL, 0, &bytesOut, NULL); -} - - -BOOL VolumePathExists (const wchar_t *volumePath) -{ - OPEN_TEST_STRUCT openTest = {0}; - wchar_t upperCasePath[TC_MAX_PATH + 1]; - - UpperCaseCopy (upperCasePath, sizeof(upperCasePath), volumePath); - - if (wcsstr (upperCasePath, L"\\DEVICE\\") == upperCasePath) - return OpenDevice (volumePath, &openTest, FALSE, FALSE, NULL); - - wstring path = volumePath; - if (path.find (L"\\\\?\\Volume{") == 0 && path.rfind (L"}\\") == path.size() - 2) - { - wchar_t devicePath[TC_MAX_PATH]; - if (QueryDosDevice (path.substr (4, path.size() - 5).c_str(), devicePath, TC_MAX_PATH) != 0) - return TRUE; - } - - if (_waccess (volumePath, 0) == 0) - return TRUE; - else - { - DWORD dwResult = GetLastError (); - if (dwResult == ERROR_SHARING_VIOLATION) - return TRUE; - else - return FALSE; - } -} - - -BOOL IsWindowsIsoBurnerAvailable () -{ - wchar_t path[MAX_PATH*2] = { 0 }; - - if (!IsOSAtLeast (WIN_7)) - { - return FALSE; - } - - if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_SYSTEM, NULL, 0, path))) - { - StringCbCatW (path, MAX_PATH*2, L"\\" ISO_BURNER_TOOL); - - return (FileExists (path)); - } - - return FALSE; -} - - -BOOL LaunchWindowsIsoBurner (HWND hwnd, const wchar_t *isoPath) -{ - wchar_t path[MAX_PATH*2] = { 0 }; - int r; - - if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_SYSTEM, NULL, 0, path))) - StringCbCatW (path, MAX_PATH*2, L"\\" ISO_BURNER_TOOL); - else - StringCbCopyW (path, MAX_PATH*2, L"C:\\Windows\\System32\\" ISO_BURNER_TOOL); - - r = (int) ShellExecute (hwnd, L"open", path, (wstring (L"\"") + isoPath + L"\"").c_str(), NULL, SW_SHOWNORMAL); - - if (r <= 32) - { - SetLastError (r); - handleWin32Error (hwnd, SRC_POS); - - return FALSE; - } - - return TRUE; -} - - -std::wstring VolumeGuidPathToDevicePath (std::wstring volumeGuidPath) -{ - if (volumeGuidPath.find (L"\\\\?\\") == 0) - volumeGuidPath = volumeGuidPath.substr (4); - - if (volumeGuidPath.find (L"Volume{") != 0 || volumeGuidPath.rfind (L"}\\") != volumeGuidPath.size() - 2) - return wstring(); - - wchar_t volDevPath[TC_MAX_PATH]; - if (QueryDosDevice (volumeGuidPath.substr (0, volumeGuidPath.size() - 1).c_str(), volDevPath, TC_MAX_PATH) == 0) - return wstring(); - - wstring partitionPath = HarddiskVolumePathToPartitionPath (volDevPath); - - return partitionPath.empty() ? volDevPath : partitionPath; -} - - -std::wstring HarddiskVolumePathToPartitionPath (const std::wstring &harddiskVolumePath) -{ - for (int driveNumber = 0; driveNumber < MAX_HOST_DRIVE_NUMBER; driveNumber++) - { - for (int partNumber = 0; partNumber < MAX_HOST_PARTITION_NUMBER; partNumber++) - { - wchar_t partitionPath[TC_MAX_PATH]; - StringCchPrintfW (partitionPath, ARRAYSIZE (partitionPath), L"\\Device\\Harddisk%d\\Partition%d", driveNumber, partNumber); - - wchar_t resolvedPath[TC_MAX_PATH]; - if (ResolveSymbolicLink (partitionPath, resolvedPath, sizeof(resolvedPath))) - { - if (harddiskVolumePath == resolvedPath) - return partitionPath; - } - else if (partNumber == 0) - break; - } - } - - return wstring(); -} - - -BOOL IsApplicationInstalled (const wchar_t *appName, BOOL b32bitApp) -{ - const wchar_t *uninstallRegName = L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; - BOOL installed = FALSE; - HKEY unistallKey; - LONG res = RegOpenKeyEx (HKEY_LOCAL_MACHINE, uninstallRegName, 0, KEY_READ | (b32bitApp? KEY_WOW64_32KEY: KEY_WOW64_64KEY), &unistallKey); - if (res != ERROR_SUCCESS) - { - SetLastError (res); - return FALSE; - } - - wchar_t regName[1024]; - DWORD regNameSize = sizeof (regName); - DWORD index = 0; - while (RegEnumKeyEx (unistallKey, index++, regName, ®NameSize, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) - { - if (wcsstr (regName, L"{") == regName) - { - regNameSize = sizeof (regName); - if (!ReadLocalMachineRegistryStringNonReflected ((wstring (uninstallRegName) + L"\\" + regName).c_str(), L"DisplayName", regName, ®NameSize, b32bitApp)) - regName[0] = 0; - } - - if (_wcsicmp (regName, appName) == 0) - { - installed = TRUE; - break; - } - - regNameSize = sizeof (regName); - } - - RegCloseKey (unistallKey); - return installed; -} - - -std::wstring FindLatestFileOrDirectory (const std::wstring &directory, const wchar_t *namePattern, bool findDirectory, bool findFile) -{ - wstring name; - ULARGE_INTEGER latestTime; - latestTime.QuadPart = 0; - WIN32_FIND_DATA findData; - - HANDLE find = FindFirstFile ((directory + L"\\" + namePattern).c_str(), &findData); - if (find != INVALID_HANDLE_VALUE) - { - do - { - if (wcscmp (findData.cFileName, L".") == 0 || wcscmp (findData.cFileName, L"..") == 0) - continue; - - ULARGE_INTEGER writeTime; - writeTime.LowPart = findData.ftLastWriteTime.dwLowDateTime; - writeTime.HighPart = findData.ftLastWriteTime.dwHighDateTime; - - if ((!findFile && !(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) - || (!findDirectory && (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))) - continue; - - if (latestTime.QuadPart < writeTime.QuadPart) - { - latestTime = writeTime; - name = findData.cFileName; - } - } - while (FindNextFile (find, &findData)); - - FindClose (find); - } - - if (name.empty()) - return name; - - return wstring (directory) + L"\\" + name; -} - -int GetPim (HWND hwndDlg, UINT ctrlId) -{ - int pim = 0; - HWND hCtrl = GetDlgItem (hwndDlg, ctrlId); - if (IsWindowEnabled (hCtrl) && IsWindowVisible (hCtrl)) - { - wchar_t szTmp[MAX_PIM + 1] = {0}; - if (GetDlgItemText (hwndDlg, ctrlId, szTmp, MAX_PIM + 1) > 0) - { - wchar_t* endPtr = NULL; - pim = wcstol(szTmp, &endPtr, 10); - if (pim < 0 || endPtr == szTmp || !endPtr || *endPtr != L'\0') - pim = 0; - } - } - return pim; -} - -void SetPim (HWND hwndDlg, UINT ctrlId, int pim) -{ - if (pim > 0) - { - wchar_t szTmp[MAX_PIM + 1]; - StringCbPrintfW (szTmp, sizeof(szTmp), L"%d", pim); - SetDlgItemText (hwndDlg, ctrlId, szTmp); - } - else - SetDlgItemText (hwndDlg, ctrlId, L""); -} - -BOOL GetPassword (HWND hwndDlg, UINT ctrlID, char* passValue, int bufSize, BOOL bShowError) -{ - wchar_t tmp [MAX_PASSWORD + 1]; - int utf8Len; - BOOL bRet = FALSE; - - GetWindowText (GetDlgItem (hwndDlg, ctrlID), tmp, ARRAYSIZE (tmp)); - utf8Len = WideCharToMultiByte (CP_UTF8, 0, tmp, -1, passValue, bufSize, NULL, NULL); - burn (tmp, sizeof (tmp)); - if (utf8Len > 0) - { - bRet = TRUE; - } - else - { - passValue [0] = 0; - if (bShowError) - { - SetFocus (GetDlgItem(hwndDlg, ctrlID)); - if (GetLastError () == ERROR_INSUFFICIENT_BUFFER) - Error ("PASSWORD_UTF8_TOO_LONG", hwndDlg); - else - Error ("PASSWORD_UTF8_INVALID", hwndDlg); - } - } - - return bRet; -} - -void SetPassword (HWND hwndDlg, UINT ctrlID, char* passValue) -{ - wchar_t tmp [MAX_PASSWORD + 1] = {0}; - MultiByteToWideChar (CP_UTF8, 0, passValue, -1, tmp, MAX_PASSWORD + 1); - SetWindowText ( GetDlgItem (hwndDlg, ctrlID), tmp); - burn (tmp, sizeof (tmp)); -} - -void HandleShowPasswordFieldAction (HWND hwndDlg, UINT checkBoxId, UINT edit1Id, UINT edit2Id) -{ - if ((EditPasswordChar == 0) && GetCheckBox (hwndDlg, checkBoxId)) - { - EditPasswordChar = (WCHAR) SendMessageW (GetDlgItem (hwndDlg, edit1Id), EM_GETPASSWORDCHAR, 0, 0); - } - - SendMessageW (GetDlgItem (hwndDlg, edit1Id), - EM_SETPASSWORDCHAR, - GetCheckBox (hwndDlg, checkBoxId) ? 0 : EditPasswordChar, - 0); - InvalidateRect (GetDlgItem (hwndDlg, edit1Id), NULL, TRUE); - - if (edit2Id) - { - SendMessageW (GetDlgItem (hwndDlg, edit2Id), - EM_SETPASSWORDCHAR, - GetCheckBox (hwndDlg, checkBoxId) ? 0 : EditPasswordChar, - 0); - InvalidateRect (GetDlgItem (hwndDlg, edit2Id), NULL, TRUE); - } -} - -void RegisterDriverInf (bool registerFilter, const string& filter, const string& filterReg, HWND ParentWindow, HKEY regKey) -{ - wstring infFileName = GetTempPathString() + L"\\veracrypt_driver_setup.inf"; - - File infFile (infFileName, false, true); - finally_do_arg (wstring, infFileName, { DeleteFile (finally_arg.c_str()); }); - - string infTxt = "[veracrypt]\r\n" - + string (registerFilter ? "Add" : "Del") + "Reg=veracrypt_reg\r\n\r\n" - "[veracrypt_reg]\r\n" - "HKR,,\"" + filterReg + "\",0x0001" + string (registerFilter ? "0008" : "8002") + ",\"" + filter + "\"\r\n"; - - infFile.Write ((byte *) infTxt.c_str(), (DWORD) infTxt.size()); - infFile.Close(); - - HINF hInf = SetupOpenInfFileWFn (infFileName.c_str(), NULL, INF_STYLE_OLDNT | INF_STYLE_WIN4, NULL); - throw_sys_if (hInf == INVALID_HANDLE_VALUE); - finally_do_arg (HINF, hInf, { SetupCloseInfFileFn (finally_arg); }); - - throw_sys_if (!SetupInstallFromInfSectionWFn (ParentWindow, hInf, L"veracrypt", SPINST_REGISTRY, regKey, NULL, 0, NULL, NULL, NULL, NULL)); -} - -HKEY OpenDeviceClassRegKey (const GUID *deviceClassGuid) -{ - return SetupDiOpenClassRegKeyFn (deviceClassGuid, KEY_READ | KEY_WRITE); -} - -LSTATUS DeleteRegistryKey (HKEY hKey, LPCTSTR keyName) -{ - return SHDeleteKeyWFn(hKey, keyName); -} - -HIMAGELIST CreateImageList(int cx, int cy, UINT flags, int cInitial, int cGrow) -{ - return ImageList_CreateFn(cx, cy, flags, cInitial, cGrow); -} - -int AddBitmapToImageList(HIMAGELIST himl, HBITMAP hbmImage, HBITMAP hbmMask) -{ - return ImageList_AddFn(himl, hbmImage, hbmMask); -} - -HRESULT VCStrDupW(LPCWSTR psz, LPWSTR *ppwsz) -{ - return SHStrDupWFn (psz, ppwsz); -} - - -void ProcessEntropyEstimate (HWND hProgress, DWORD* pdwInitialValue, DWORD dwCounter, DWORD dwMaxLevel, DWORD* pdwEntropy) -{ - /* conservative estimate: 1 mouse move event brings 1 bit of entropy - * https://security.stackexchange.com/questions/32844/for-how-much-time-should-i-randomly-move-the-mouse-for-generating-encryption-key/32848#32848 - */ - if (*pdwEntropy == 0xFFFFFFFF) - { - *pdwInitialValue = dwCounter; - *pdwEntropy = 0; - } - else - { - if ( *pdwEntropy < dwMaxLevel - && (dwCounter >= *pdwInitialValue) - && (dwCounter - *pdwInitialValue) <= dwMaxLevel) - *pdwEntropy = dwCounter - *pdwInitialValue; - else - *pdwEntropy = dwMaxLevel; - - if (IsOSAtLeast (WIN_VISTA)) - { - int state = PBST_ERROR; - if (*pdwEntropy >= (dwMaxLevel/2)) - state = PBST_NORMAL; - else if (*pdwEntropy >= (dwMaxLevel/4)) - state = PBST_PAUSED; - - SendMessage (hProgress, PBM_SETSTATE, state, 0); - } - - SendMessage (hProgress, PBM_SETPOS, - (WPARAM) (*pdwEntropy), - 0); - } -} - -void AllowMessageInUIPI (UINT msg) -{ - if (ChangeWindowMessageFilterFn) - { - ChangeWindowMessageFilterFn (msg, MSGFLT_ADD); - } -} - -BOOL IsRepeatedByteArray (byte value, const byte* buffer, size_t bufferSize) -{ - if (buffer && bufferSize) - { - size_t i; - for (i = 0; i < bufferSize; i++) - { - if (*buffer++ != value) - return FALSE; - } - return TRUE; - } - else - return FALSE; -} - -BOOL TranslateVolumeID (HWND hwndDlg, wchar_t* pathValue, size_t cchPathValue) -{ - BOOL bRet = TRUE; - size_t pathLen = pathValue? wcslen (pathValue) : 0; - if ((pathLen >= 3) && (_wcsnicmp (pathValue, L"ID:", 3) == 0)) - { - std::vector arr; - if ( (pathLen == (3 + 2*VOLUME_ID_SIZE)) - && HexWideStringToArray (pathValue + 3, arr) - && (arr.size() == VOLUME_ID_SIZE) - ) - { - std::wstring devicePath = FindDeviceByVolumeID (&arr[0]); - if (devicePath.length() > 0) - StringCchCopyW (pathValue, cchPathValue, devicePath.c_str()); - else - { - if (!Silent && !MultipleMountOperationInProgress) - Error ("VOLUME_ID_NOT_FOUND", hwndDlg); - SetLastError (ERROR_PATH_NOT_FOUND); - bRet = FALSE; - } - } - else - { - if (!Silent) - Error ("VOLUME_ID_INVALID", hwndDlg); - - SetLastError (ERROR_INVALID_PARAMETER); - bRet = FALSE; - } - } - - return bRet; -} - -BOOL CopyTextToClipboard (LPCWSTR txtValue) -{ - size_t txtLen = wcslen(txtValue); - HGLOBAL hdst; - LPWSTR dst; - BOOL bRet = FALSE; - - // Allocate string for cwd - hdst = GlobalAlloc(GMEM_MOVEABLE, (txtLen + 1) * sizeof(WCHAR)); - if (hdst) - { - dst = (LPWSTR)GlobalLock(hdst); - wmemcpy(dst, txtValue, txtLen + 1); - GlobalUnlock(hdst); - - if (OpenClipboard(NULL)) - { - EmptyClipboard(); - SetClipboardData(CF_UNICODETEXT, hdst); - CloseClipboard(); - } - } - - return bRet; -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Resource.h" + +#include "Platform/Finally.h" +#include "Platform/ForEach.h" +#include "Apidrvr.h" +#include "BootEncryption.h" +#include "Combo.h" +#include "Crc.h" +#include "Crypto.h" +#include "Dictionary.h" +#include "Dlgcode.h" +#include "EncryptionThreadPool.h" +#include "Endian.h" +#include "Format/Inplace.h" +#include "Language.h" +#include "Keyfiles.h" +#include "Pkcs5.h" +#include "Random.h" +#include "Registry.h" +#include "SecurityToken.h" +#include "Tests.h" +#include "Volumes.h" +#include "Wipe.h" +#include "Xml.h" +#include "Xts.h" +#include "Boot/Windows/BootCommon.h" +#include "Progress.h" + +#ifdef TCMOUNT +#include "Mount/Mount.h" +#include "Mount/resource.h" +#endif + +#ifdef VOLFORMAT +#include "Format/Tcformat.h" +#endif + +#ifdef SETUP +#include "Setup/Setup.h" +#endif + +#include + +using namespace VeraCrypt; + +LONG DriverVersion; + +char *LastDialogId; +wchar_t szHelpFile[TC_MAX_PATH]; +wchar_t szHelpFile2[TC_MAX_PATH]; +wchar_t SecurityTokenLibraryPath[TC_MAX_PATH]; + +HFONT hFixedDigitFont = NULL; +HFONT hBoldFont = NULL; +HFONT hTitleFont = NULL; +HFONT hFixedFont = NULL; + +HFONT hUserFont = NULL; +HFONT hUserUnderlineFont = NULL; +HFONT hUserBoldFont = NULL; +HFONT hUserUnderlineBoldFont = NULL; + +HFONT WindowTitleBarFont; + +WCHAR EditPasswordChar = 0; + +int ScreenDPI = USER_DEFAULT_SCREEN_DPI; +double DPIScaleFactorX = 1; +double DPIScaleFactorY = 1; +double DlgAspectRatio = 1; + +HWND MainDlg = NULL; +wchar_t *lpszTitle = NULL; + +BOOL Silent = FALSE; +BOOL bPreserveTimestamp = TRUE; +BOOL bShowDisconnectedNetworkDrives = FALSE; +BOOL bHideWaitingDialog = FALSE; +BOOL bCmdHideWaitingDialog = FALSE; +BOOL bCmdHideWaitingDialogValid = FALSE; +BOOL bStartOnLogon = FALSE; +BOOL bMountDevicesOnLogon = FALSE; +BOOL bMountFavoritesOnLogon = FALSE; + +BOOL bHistory = FALSE; + +// Status of detection of hidden sectors (whole-system-drive encryption). +// 0 - Unknown/undetermined/completed, 1: Detection is or was in progress (but did not complete e.g. due to system crash). +int HiddenSectorDetectionStatus = 0; + +OSVersionEnum nCurrentOS = WIN_UNKNOWN; +int CurrentOSMajor = 0; +int CurrentOSMinor = 0; +int CurrentOSServicePack = 0; +BOOL RemoteSession = FALSE; +BOOL UacElevated = FALSE; + +BOOL bPortableModeConfirmed = FALSE; // TRUE if it is certain that the instance is running in portable mode + +BOOL bInPlaceEncNonSysPending = FALSE; // TRUE if the non-system in-place encryption config file indicates that one or more partitions are scheduled to be encrypted. This flag is set only when config files are loaded during app startup. + +/* Globals used by Mount and Format (separately per instance) */ +BOOL PimEnable = FALSE; +BOOL KeyFilesEnable = FALSE; +KeyFile *FirstKeyFile = NULL; +KeyFilesDlgParam defaultKeyFilesParam; + +BOOL IgnoreWmDeviceChange = FALSE; +BOOL DeviceChangeBroadcastDisabled = FALSE; +BOOL LastMountedVolumeDirty; +BOOL MountVolumesAsSystemFavorite = FALSE; +BOOL FavoriteMountOnArrivalInProgress = FALSE; +BOOL MultipleMountOperationInProgress = FALSE; + +BOOL WaitDialogDisplaying = FALSE; + +/* Handle to the device driver */ +HANDLE hDriver = INVALID_HANDLE_VALUE; + +/* This mutex is used to prevent multiple instances of the wizard or main app from dealing with system encryption */ +volatile HANDLE hSysEncMutex = NULL; + +/* This mutex is used for non-system in-place encryption but only for informative (non-blocking) purposes, +such as whether an app should prompt the user whether to resume scheduled process. */ +volatile HANDLE hNonSysInplaceEncMutex = NULL; + +/* This mutex is used to prevent multiple instances of the wizard or main app from trying to install or +register the driver or from trying to launch it in portable mode at the same time. */ +volatile HANDLE hDriverSetupMutex = NULL; + +/* This mutex is used to prevent users from running the main TrueCrypt app or the wizard while an instance +of the TrueCrypt installer is running (which is also useful for enforcing restart before the apps can be used). */ +volatile HANDLE hAppSetupMutex = NULL; + +/* Critical section used to protect access to global variables used in WNetGetConnection calls */ +CRITICAL_SECTION csWNetCalls; + +HINSTANCE hInst = NULL; +HCURSOR hCursor = NULL; + +ATOM hDlgClass, hSplashClass; + +/* This value may changed only by calling ChangeSystemEncryptionStatus(). Only the wizard can change it +(others may still read it though). */ +int SystemEncryptionStatus = SYSENC_STATUS_NONE; + +/* Only the wizard can change this value (others may only read it). */ +WipeAlgorithmId nWipeMode = TC_WIPE_NONE; + +BOOL bSysPartitionSelected = FALSE; /* TRUE if the user selected the system partition via the Select Device dialog */ +BOOL bSysDriveSelected = FALSE; /* TRUE if the user selected the system drive via the Select Device dialog */ + +/* To populate these arrays, call GetSysDevicePaths(). If they contain valid paths, bCachedSysDevicePathsValid is TRUE. */ +wchar_t SysPartitionDevicePath [TC_MAX_PATH]; +wchar_t SysDriveDevicePath [TC_MAX_PATH]; +wstring ExtraBootPartitionDevicePath; +char bCachedSysDevicePathsValid = FALSE; + +BOOL bHyperLinkBeingTracked = FALSE; + +int WrongPwdRetryCounter = 0; + +static FILE *ConfigFileHandle; +char *ConfigBuffer; + +BOOL SystemFileSelectorCallPending = FALSE; +DWORD SystemFileSelectorCallerThreadId; + +#define RANDPOOL_DISPLAY_REFRESH_INTERVAL 30 +#define RANDPOOL_DISPLAY_ROWS 16 +#define RANDPOOL_DISPLAY_COLUMNS 20 + +HMODULE hRichEditDll = NULL; +HMODULE hComctl32Dll = NULL; +HMODULE hSetupDll = NULL; +HMODULE hShlwapiDll = NULL; +HMODULE hProfApiDll = NULL; +HMODULE hUsp10Dll = NULL; +HMODULE hCryptSpDll = NULL; +HMODULE hUXThemeDll = NULL; +HMODULE hUserenvDll = NULL; +HMODULE hRsaenhDll = NULL; +HMODULE himm32dll = NULL; +HMODULE hMSCTFdll = NULL; +HMODULE hfltlibdll = NULL; +HMODULE hframedyndll = NULL; +HMODULE hpsapidll = NULL; +HMODULE hsecur32dll = NULL; +HMODULE hnetapi32dll = NULL; +HMODULE hauthzdll = NULL; +HMODULE hxmllitedll = NULL; +HMODULE hmprdll = NULL; +HMODULE hsppdll = NULL; +HMODULE vssapidll = NULL; +HMODULE hvsstracedll = NULL; +HMODULE hcfgmgr32dll = NULL; +HMODULE hdevobjdll = NULL; +HMODULE hpowrprofdll = NULL; +HMODULE hsspiclidll = NULL; +HMODULE hcryptbasedll = NULL; +HMODULE hdwmapidll = NULL; +HMODULE hmsasn1dll = NULL; +HMODULE hcrypt32dll = NULL; +HMODULE hbcryptdll = NULL; +HMODULE hbcryptprimitivesdll = NULL; +HMODULE hMsls31 = NULL; +HMODULE hntmartadll = NULL; +HMODULE hwinscarddll = NULL; + +#define FREE_DLL(h) if (h) { FreeLibrary (h); h = NULL;} + +typedef void (WINAPI *InitCommonControlsPtr)(void); +typedef HIMAGELIST (WINAPI *ImageList_CreatePtr)(int cx, int cy, UINT flags, int cInitial, int cGrow); +typedef int (WINAPI *ImageList_AddPtr)(HIMAGELIST himl, HBITMAP hbmImage, HBITMAP hbmMask); + +typedef VOID (WINAPI *SetupCloseInfFilePtr)(HINF InfHandle); +typedef HKEY (WINAPI *SetupDiOpenClassRegKeyPtr)(CONST GUID *ClassGuid,REGSAM samDesired); +typedef BOOL (WINAPI *SetupInstallFromInfSectionWPtr)(HWND,HINF,PCWSTR,UINT,HKEY,PCWSTR,UINT,PSP_FILE_CALLBACK_W,PVOID,HDEVINFO,PSP_DEVINFO_DATA); +typedef HINF (WINAPI *SetupOpenInfFileWPtr)(PCWSTR FileName,PCWSTR InfClass,DWORD InfStyle,PUINT ErrorLine); + +typedef LSTATUS (STDAPICALLTYPE *SHDeleteKeyWPtr)(HKEY hkey, LPCWSTR pszSubKey); + +typedef HRESULT (STDAPICALLTYPE *SHStrDupWPtr)(LPCWSTR psz, LPWSTR *ppwsz); + +// ChangeWindowMessageFilter +typedef BOOL (WINAPI *ChangeWindowMessageFilterPtr) (UINT, DWORD); + +ImageList_CreatePtr ImageList_CreateFn = NULL; +ImageList_AddPtr ImageList_AddFn = NULL; + +SetupCloseInfFilePtr SetupCloseInfFileFn = NULL; +SetupDiOpenClassRegKeyPtr SetupDiOpenClassRegKeyFn = NULL; +SetupInstallFromInfSectionWPtr SetupInstallFromInfSectionWFn = NULL; +SetupOpenInfFileWPtr SetupOpenInfFileWFn = NULL; +SHDeleteKeyWPtr SHDeleteKeyWFn = NULL; +SHStrDupWPtr SHStrDupWFn = NULL; +ChangeWindowMessageFilterPtr ChangeWindowMessageFilterFn = NULL; + +/* Windows dialog class */ +#define WINDOWS_DIALOG_CLASS L"#32770" + +/* Custom class names */ +#define TC_DLG_CLASS L"VeraCryptCustomDlg" +#define TC_SPLASH_CLASS L"VeraCryptSplashDlg" + +/* constant used by ChangeWindowMessageFilter calls */ +#ifndef MSGFLT_ADD +#define MSGFLT_ADD 1 +#endif + +/* undocumented message sent during drag-n-drop */ +#ifndef WM_COPYGLOBALDATA +#define WM_COPYGLOBALDATA 0x0049 +#endif + +/* Benchmarks */ + +#ifndef SETUP + +#define BENCHMARK_MAX_ITEMS 100 +#define BENCHMARK_DEFAULT_BUF_SIZE BYTES_PER_MB +#define HASH_FNC_BENCHMARKS FALSE // For development purposes only. Must be FALSE when building a public release. +#define PKCS5_BENCHMARKS FALSE // For development purposes only. Must be FALSE when building a public release. +#if PKCS5_BENCHMARKS && HASH_FNC_BENCHMARKS +#error PKCS5_BENCHMARKS and HASH_FNC_BENCHMARKS are both TRUE (at least one of them should be FALSE). +#endif + +enum +{ + BENCHMARK_SORT_BY_NAME = 0, + BENCHMARK_SORT_BY_SPEED +}; + +typedef struct +{ + int id; + wchar_t name[100]; + unsigned __int64 encSpeed; + unsigned __int64 decSpeed; + unsigned __int64 meanBytesPerSec; +} BENCHMARK_REC; + +BENCHMARK_REC benchmarkTable [BENCHMARK_MAX_ITEMS]; +int benchmarkTotalItems = 0; +int benchmarkBufferSize = BENCHMARK_DEFAULT_BUF_SIZE; +int benchmarkLastBufferSize = BENCHMARK_DEFAULT_BUF_SIZE; +int benchmarkSortMethod = BENCHMARK_SORT_BY_SPEED; +LARGE_INTEGER benchmarkPerformanceFrequency; + +#endif // #ifndef SETUP + + +typedef struct +{ + void *strings; + BOOL bold; + +} MULTI_CHOICE_DLGPROC_PARAMS; + + +void cleanup () +{ + /* Cleanup the GDI fonts */ + if (hFixedFont != NULL) + DeleteObject (hFixedFont); + if (hFixedDigitFont != NULL) + DeleteObject (hFixedDigitFont); + if (hBoldFont != NULL) + DeleteObject (hBoldFont); + if (hTitleFont != NULL) + DeleteObject (hTitleFont); + if (hUserFont != NULL) + DeleteObject (hUserFont); + if (hUserUnderlineFont != NULL) + DeleteObject (hUserUnderlineFont); + if (hUserBoldFont != NULL) + DeleteObject (hUserBoldFont); + if (hUserUnderlineBoldFont != NULL) + DeleteObject (hUserUnderlineBoldFont); + + /* Cleanup our dialog class */ + if (hDlgClass) + UnregisterClassW (TC_DLG_CLASS, hInst); + if (hSplashClass) + UnregisterClassW (TC_SPLASH_CLASS, hInst); + + /* Close the device driver handle */ + if (hDriver != INVALID_HANDLE_VALUE) + { + // Unload driver mode if possible (non-install mode) + if (IsNonInstallMode ()) + { + // If a dismount was forced in the lifetime of the driver, Windows may later prevent it to be loaded again from + // the same path. Therefore, the driver will not be unloaded even though it was loaded in non-install mode. + int driverUnloadDisabled; + DWORD dwResult; + + if (!DeviceIoControl (hDriver, TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED, NULL, 0, &driverUnloadDisabled, sizeof (driverUnloadDisabled), &dwResult, NULL)) + driverUnloadDisabled = 0; + + if (!driverUnloadDisabled) + DriverUnload (); + else + { + CloseHandle (hDriver); + hDriver = INVALID_HANDLE_VALUE; + } + } + else + { + CloseHandle (hDriver); + hDriver = INVALID_HANDLE_VALUE; + } + } + + if (ConfigBuffer != NULL) + { + free (ConfigBuffer); + ConfigBuffer = NULL; + } + + CoUninitialize (); + + CloseSysEncMutex (); + +#ifndef SETUP + try + { + if (SecurityToken::IsInitialized()) + SecurityToken::CloseLibrary(); + } + catch (...) { } + + EncryptionThreadPoolStop(); +#endif + + DeleteCriticalSection (&csWNetCalls); +} + + +void LowerCaseCopy (wchar_t *lpszDest, const wchar_t *lpszSource) +{ + size_t i = wcslen (lpszSource) + 1; + + lpszDest[i - 1] = 0; + while (--i > 0) + { + lpszDest[i - 1] = (wchar_t) towlower (lpszSource[i - 1]); + } + +} + +void UpperCaseCopy (wchar_t *lpszDest, size_t cbDest, const wchar_t *lpszSource) +{ + if (lpszDest && cbDest) + { + size_t i = wcslen (lpszSource); + if (i >= cbDest) + i = cbDest - 1; + + lpszDest[i] = 0; + i++; + while (--i > 0) + { + lpszDest[i - 1] = (wchar_t) towupper (lpszSource[i - 1]); + } + } +} + + +std::wstring ToUpperCase (const std::wstring &str) +{ + wstring u; + foreach (wchar_t c, str) + { + u += (wchar_t) towupper (c); + } + + return u; +} + +size_t TrimWhiteSpace(wchar_t *str) +{ + wchar_t *end, *ptr = str; + size_t out_size; + + if(!str || *str == 0) + return 0; + + // Trim leading space + while(iswspace(*ptr)) ptr++; + + if(*ptr == 0) // All spaces? + { + *str = 0; + return 0; + } + + // Trim trailing space + end = str + wcslen(str) - 1; + while(end > ptr && iswspace(*end)) end--; + end++; + + // Set output size to trimmed string length + out_size = (end - ptr); + + // Copy trimmed string and add null terminator + wmemmove(str, ptr, out_size); + str[out_size] = 0; + + return out_size; +} + +// check the validity of a file name +BOOL IsValidFileName(const wchar_t* str) +{ + static wchar_t invalidChars[9] = {L'<', L'>', L':', L'"', L'/', L'\\', L'|', L'?', L'*'}; + wchar_t c; + int i; + BOOL bNotDotOnly = FALSE; + while ((c = *str)) + { + if (c != L'.') + bNotDotOnly = TRUE; + for (i= 0; i < ARRAYSIZE(invalidChars); i++) + if (c == invalidChars[i]) + return FALSE; + str++; + } + + return bNotDotOnly; +} + +BOOL IsVolumeDeviceHosted (const wchar_t *lpszDiskFile) +{ + return wcsstr (lpszDiskFile, L"\\Device\\") == lpszDiskFile + || wcsstr (lpszDiskFile, L"\\DEVICE\\") == lpszDiskFile; +} + + +void CreateFullVolumePath (wchar_t *lpszDiskFile, size_t cbDiskFile, const wchar_t *lpszFileName, BOOL * bDevice) +{ + UpperCaseCopy (lpszDiskFile, cbDiskFile, lpszFileName); + + *bDevice = FALSE; + + if (wmemcmp (lpszDiskFile, L"\\DEVICE", 7) == 0) + { + *bDevice = TRUE; + } + + StringCbCopyW (lpszDiskFile, cbDiskFile, lpszFileName); + +#if _DEBUG + OutputDebugString (L"CreateFullVolumePath: "); + OutputDebugString (lpszDiskFile); + OutputDebugString (L"\n"); +#endif + +} + +int FakeDosNameForDevice (const wchar_t *lpszDiskFile , wchar_t *lpszDosDevice , size_t cbDosDevice, wchar_t *lpszCFDevice , size_t cbCFDevice, BOOL bNameOnly) +{ + BOOL bDosLinkCreated = TRUE; + StringCbPrintfW (lpszDosDevice, cbDosDevice,L"veracrypt%lu", GetCurrentProcessId ()); + + if (bNameOnly == FALSE) + bDosLinkCreated = DefineDosDevice (DDD_RAW_TARGET_PATH, lpszDosDevice, lpszDiskFile); + + if (bDosLinkCreated == FALSE) + return ERR_OS_ERROR; + else + StringCbPrintfW (lpszCFDevice, cbCFDevice,L"\\\\.\\%s", lpszDosDevice); + + return 0; +} + +int RemoveFakeDosName (wchar_t *lpszDiskFile, wchar_t *lpszDosDevice) +{ + BOOL bDosLinkRemoved = DefineDosDevice (DDD_RAW_TARGET_PATH | DDD_EXACT_MATCH_ON_REMOVE | + DDD_REMOVE_DEFINITION, lpszDosDevice, lpszDiskFile); + if (bDosLinkRemoved == FALSE) + { + return ERR_OS_ERROR; + } + + return 0; +} + + +void AbortProcessDirect (wchar_t *abortMsg) +{ + // Note that this function also causes localcleanup() to be called (see atexit()) + MessageBeep (MB_ICONEXCLAMATION); + MessageBoxW (NULL, abortMsg, lpszTitle, ICON_HAND); + FREE_DLL (hRichEditDll); + FREE_DLL (hComctl32Dll); + FREE_DLL (hSetupDll); + FREE_DLL (hShlwapiDll); + FREE_DLL (hProfApiDll); + FREE_DLL (hUsp10Dll); + FREE_DLL (hCryptSpDll); + FREE_DLL (hUXThemeDll); + FREE_DLL (hUserenvDll); + FREE_DLL (hRsaenhDll); + FREE_DLL (himm32dll); + FREE_DLL (hMSCTFdll); + FREE_DLL (hfltlibdll); + FREE_DLL (hframedyndll); + FREE_DLL (hpsapidll); + FREE_DLL (hsecur32dll); + FREE_DLL (hnetapi32dll); + FREE_DLL (hauthzdll); + FREE_DLL (hxmllitedll); + FREE_DLL (hmprdll); + FREE_DLL (hsppdll); + FREE_DLL (vssapidll); + FREE_DLL (hvsstracedll); + FREE_DLL (hCryptSpDll); + FREE_DLL (hcfgmgr32dll); + FREE_DLL (hdevobjdll); + FREE_DLL (hpowrprofdll); + FREE_DLL (hsspiclidll); + FREE_DLL (hcryptbasedll); + FREE_DLL (hdwmapidll); + FREE_DLL (hmsasn1dll); + FREE_DLL (hcrypt32dll); + FREE_DLL (hbcryptdll); + FREE_DLL (hbcryptprimitivesdll); + FREE_DLL (hMsls31); + FREE_DLL (hntmartadll); + FREE_DLL (hwinscarddll); + + exit (1); +} + +void AbortProcess (char *stringId) +{ + // Note that this function also causes localcleanup() to be called (see atexit()) + AbortProcessDirect (GetString (stringId)); +} + +void AbortProcessSilent (void) +{ + FREE_DLL (hRichEditDll); + FREE_DLL (hComctl32Dll); + FREE_DLL (hSetupDll); + FREE_DLL (hShlwapiDll); + FREE_DLL (hProfApiDll); + FREE_DLL (hUsp10Dll); + FREE_DLL (hCryptSpDll); + FREE_DLL (hUXThemeDll); + FREE_DLL (hUserenvDll); + FREE_DLL (hRsaenhDll); + FREE_DLL (himm32dll); + FREE_DLL (hMSCTFdll); + FREE_DLL (hfltlibdll); + FREE_DLL (hframedyndll); + FREE_DLL (hpsapidll); + FREE_DLL (hsecur32dll); + FREE_DLL (hnetapi32dll); + FREE_DLL (hauthzdll); + FREE_DLL (hxmllitedll); + FREE_DLL (hmprdll); + FREE_DLL (hsppdll); + FREE_DLL (vssapidll); + FREE_DLL (hvsstracedll); + FREE_DLL (hCryptSpDll); + FREE_DLL (hcfgmgr32dll); + FREE_DLL (hdevobjdll); + FREE_DLL (hpowrprofdll); + FREE_DLL (hsspiclidll); + FREE_DLL (hcryptbasedll); + FREE_DLL (hdwmapidll); + FREE_DLL (hmsasn1dll); + FREE_DLL (hcrypt32dll); + FREE_DLL (hbcryptdll); + FREE_DLL (hbcryptprimitivesdll); + FREE_DLL (hMsls31); + FREE_DLL (hntmartadll); + FREE_DLL (hwinscarddll); + + // Note that this function also causes localcleanup() to be called (see atexit()) + exit (1); +} + + +#pragma warning(push) +#pragma warning(disable:4702) + +void *err_malloc (size_t size) +{ + void *z = (void *) TCalloc (size); + if (z) + return z; + AbortProcess ("OUTOFMEMORY"); + return 0; +} + +#pragma warning(pop) + + +char *err_strdup (char *lpszText) +{ + size_t j = (strlen (lpszText) + 1) * sizeof (char); + char *z = (char *) err_malloc (j); + memmove (z, lpszText, j); + return z; +} + + +BOOL IsDiskReadError (DWORD error) +{ + return (error == ERROR_CRC + || error == ERROR_IO_DEVICE + || error == ERROR_BAD_CLUSTERS + || error == ERROR_SECTOR_NOT_FOUND + || error == ERROR_READ_FAULT + || error == ERROR_INVALID_FUNCTION // I/O error may be reported as ERROR_INVALID_FUNCTION by buggy chipset drivers + || error == ERROR_SEM_TIMEOUT); // I/O operation timeout may be reported as ERROR_SEM_TIMEOUT +} + + +BOOL IsDiskWriteError (DWORD error) +{ + return (error == ERROR_IO_DEVICE + || error == ERROR_BAD_CLUSTERS + || error == ERROR_SECTOR_NOT_FOUND + || error == ERROR_WRITE_FAULT + || error == ERROR_INVALID_FUNCTION // I/O error may be reported as ERROR_INVALID_FUNCTION by buggy chipset drivers + || error == ERROR_SEM_TIMEOUT); // I/O operation timeout may be reported as ERROR_SEM_TIMEOUT +} + + +BOOL IsDiskError (DWORD error) +{ + return IsDiskReadError (error) || IsDiskWriteError (error); +} + + +DWORD handleWin32Error (HWND hwndDlg, const char* srcPos) +{ + PWSTR lpMsgBuf; + DWORD dwError = GetLastError (); + wchar_t szErrorValue[32]; + wchar_t* pszDesc; + + if (Silent || dwError == 0 || dwError == ERROR_INVALID_WINDOW_HANDLE) + return dwError; + + // Access denied + if (dwError == ERROR_ACCESS_DENIED && !IsAdmin ()) + { + ErrorDirect ( AppendSrcPos (GetString ("ERR_ACCESS_DENIED"), srcPos).c_str (), hwndDlg); + SetLastError (dwError); // Preserve the original error code + return dwError; + } + + FormatMessageW ( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + dwError, + MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ + (PWSTR) &lpMsgBuf, + 0, + NULL + ); + + if (lpMsgBuf) + pszDesc = (wchar_t*) lpMsgBuf; + else + { + StringCchPrintfW (szErrorValue, ARRAYSIZE (szErrorValue), L"Error 0x%.8X", dwError); + pszDesc = szErrorValue; + } + + MessageBoxW (hwndDlg, AppendSrcPos (pszDesc, srcPos).c_str (), lpszTitle, ICON_HAND); + if (lpMsgBuf) LocalFree (lpMsgBuf); + + // User-friendly hardware error explanation + if (IsDiskError (dwError)) + Error ("ERR_HARDWARE_ERROR", hwndDlg); + + // Device not ready + if (dwError == ERROR_NOT_READY) + HandleDriveNotReadyError(hwndDlg); + + SetLastError (dwError); // Preserve the original error code + + return dwError; +} + +BOOL translateWin32Error (wchar_t *lpszMsgBuf, int nWSizeOfBuf) +{ + DWORD dwError = GetLastError (); + + if (FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, + MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ + lpszMsgBuf, nWSizeOfBuf, NULL)) + { + SetLastError (dwError); // Preserve the original error code + return TRUE; + } + + SetLastError (dwError); // Preserve the original error code + return FALSE; +} + +// If the user has a non-default screen DPI, all absolute font sizes must be +// converted using this function. +int CompensateDPIFont (int val) +{ + if (ScreenDPI == USER_DEFAULT_SCREEN_DPI) + return val; + else + { + double tmpVal = (double) val * DPIScaleFactorY * DlgAspectRatio * 0.999; + + if (tmpVal > 0) + return (int) floor(tmpVal); + else + return (int) ceil(tmpVal); + } +} + + +// If the user has a non-default screen DPI, some screen coordinates and sizes must +// be converted using this function +int CompensateXDPI (int val) +{ + if (ScreenDPI == USER_DEFAULT_SCREEN_DPI) + return val; + else + { + double tmpVal = (double) val * DPIScaleFactorX; + + if (tmpVal > 0) + return (int) floor(tmpVal); + else + return (int) ceil(tmpVal); + } +} + + +// If the user has a non-default screen DPI, some screen coordinates and sizes must +// be converted using this function +int CompensateYDPI (int val) +{ + if (ScreenDPI == USER_DEFAULT_SCREEN_DPI) + return val; + else + { + double tmpVal = (double) val * DPIScaleFactorY; + + if (tmpVal > 0) + return (int) floor(tmpVal); + else + return (int) ceil(tmpVal); + } +} + + +int GetTextGfxWidth (HWND hwndDlgItem, const wchar_t *text, HFONT hFont) +{ + SIZE sizes; + TEXTMETRIC textMetrics; + HDC hdc = GetDC (hwndDlgItem); + + SelectObject(hdc, (HGDIOBJ) hFont); + + GetTextExtentPoint32W (hdc, text, (int) wcslen (text), &sizes); + + GetTextMetrics(hdc, &textMetrics); // Necessary for non-TrueType raster fonts (tmOverhang) + + ReleaseDC (hwndDlgItem, hdc); + + return ((int) sizes.cx - (int) textMetrics.tmOverhang); +} + + +int GetTextGfxHeight (HWND hwndDlgItem, const wchar_t *text, HFONT hFont) +{ + SIZE sizes; + HDC hdc = GetDC (hwndDlgItem); + + SelectObject(hdc, (HGDIOBJ) hFont); + + GetTextExtentPoint32W (hdc, text, (int) wcslen (text), &sizes); + + ReleaseDC (hwndDlgItem, hdc); + + return ((int) sizes.cy); +} + + +std::wstring FitPathInGfxWidth (HWND hwnd, HFONT hFont, LONG width, const std::wstring &path) +{ + wstring newPath; + + RECT rect; + rect.left = 0; + rect.top = 0; + rect.right = width; + rect.bottom = LONG_MAX; + + HDC hdc = GetDC (hwnd); + SelectObject (hdc, (HGDIOBJ) hFont); + + wchar_t pathBuf[TC_MAX_PATH]; + StringCchCopyW (pathBuf, ARRAYSIZE (pathBuf), path.c_str()); + + if (DrawText (hdc, pathBuf, (int) path.size(), &rect, DT_CALCRECT | DT_MODIFYSTRING | DT_PATH_ELLIPSIS | DT_SINGLELINE) != 0) + newPath = pathBuf; + + ReleaseDC (hwnd, hdc); + return newPath; +} + + +static LRESULT CALLBACK HyperlinkProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + WNDPROC wp = (WNDPROC) GetWindowLongPtrW (hwnd, GWLP_USERDATA); + + switch (message) + { + case WM_SETCURSOR: + if (!bHyperLinkBeingTracked) + { + TRACKMOUSEEVENT trackMouseEvent; + + trackMouseEvent.cbSize = sizeof(trackMouseEvent); + trackMouseEvent.dwFlags = TME_LEAVE; + trackMouseEvent.hwndTrack = hwnd; + + bHyperLinkBeingTracked = TrackMouseEvent(&trackMouseEvent); + + HandCursor(); + } + return 0; + + case WM_MOUSELEAVE: + bHyperLinkBeingTracked = FALSE; + NormalCursor(); + return 0; + } + + return CallWindowProcW (wp, hwnd, message, wParam, lParam); +} + + +BOOL ToHyperlink (HWND hwndDlg, UINT ctrlId) +{ + return ToCustHyperlink (hwndDlg, ctrlId, hUserUnderlineFont); +} + + +BOOL ToCustHyperlink (HWND hwndDlg, UINT ctrlId, HFONT hFont) +{ + HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId); + + SendMessageW (hwndCtrl, WM_SETFONT, (WPARAM) hFont, 0); + + SetWindowLongPtrW (hwndCtrl, GWLP_USERDATA, (LONG_PTR) GetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC)); + SetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC, (LONG_PTR) HyperlinkProc); + + // Resize the field according to its actual size in pixels and move it if centered or right-aligned. + // This should be done again if the link text changes. + AccommodateTextField (hwndDlg, ctrlId, TRUE, hFont); + + return TRUE; +} + + +// Resizes a text field according to its actual width and height in pixels (font size is taken into account) and moves +// it accordingly if the field is centered or right-aligned. Should be used on all hyperlinks upon dialog init +// after localization (bFirstUpdate should be TRUE) and later whenever a hyperlink text changes (bFirstUpdate +// must be FALSE). +void AccommodateTextField (HWND hwndDlg, UINT ctrlId, BOOL bFirstUpdate, HFONT hFont) +{ + RECT rec, wrec, trec; + HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId); + int width, origWidth, height, origHeight; + int horizSubOffset, vertSubOffset, vertOffset, alignPosDiff = 0; + wchar_t text [MAX_URL_LENGTH]; + WINDOWINFO windowInfo; + BOOL bBorderlessWindow = !(GetWindowLongPtrW (hwndDlg, GWL_STYLE) & (WS_BORDER | WS_DLGFRAME)); + + // Resize the field according to its length and font size and move if centered or right-aligned + + GetWindowTextW (hwndCtrl, text, sizeof (text) / sizeof (wchar_t)); + + width = GetTextGfxWidth (hwndCtrl, text, hFont); + height = GetTextGfxHeight (hwndCtrl, text, hFont); + + GetClientRect (hwndCtrl, &rec); + origWidth = rec.right; + origHeight = rec.bottom; + + if (width >= 0 + && (!bFirstUpdate || origWidth > width)) // The original width of the field is the maximum allowed size + { + horizSubOffset = origWidth - width; + vertSubOffset = origHeight - height; + + // Window coords + GetWindowRect(hwndDlg, &wrec); + GetClientRect(hwndDlg, &trec); + + // Vertical "title bar" offset + vertOffset = wrec.bottom - wrec.top - trec.bottom - (bBorderlessWindow ? 0 : GetSystemMetrics(SM_CYFIXEDFRAME)); + + // Text field coords + GetWindowRect(hwndCtrl, &rec); + + // Alignment offset + windowInfo.cbSize = sizeof(windowInfo); + GetWindowInfo (hwndCtrl, &windowInfo); + + if (windowInfo.dwStyle & SS_CENTER) + alignPosDiff = horizSubOffset / 2; + else if (windowInfo.dwStyle & SS_RIGHT) + alignPosDiff = horizSubOffset; + + // Resize/move + if (alignPosDiff > 0) + { + // Resize and move the text field + MoveWindow (hwndCtrl, + rec.left - wrec.left - (bBorderlessWindow ? 0 : GetSystemMetrics(SM_CXFIXEDFRAME)) + alignPosDiff, + rec.top - wrec.top - vertOffset, + origWidth - horizSubOffset, + origHeight - vertSubOffset, + TRUE); + } + else + { + // Resize the text field + SetWindowPos (hwndCtrl, 0, 0, 0, + origWidth - horizSubOffset, + origHeight - vertSubOffset, + SWP_NOMOVE | SWP_NOZORDER); + } + + SetWindowPos (hwndCtrl, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + + InvalidateRect (hwndCtrl, NULL, TRUE); + } +} + +// Note that the user can still close the window by right-clicking its taskbar icon and selecting 'Close window', or by pressing Alt-F4, or using the Task Manager. +void DisableCloseButton (HWND hwndDlg) +{ + EnableMenuItem (GetSystemMenu (hwndDlg, FALSE), SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); +} + + +void EnableCloseButton (HWND hwndDlg) +{ + EnableMenuItem (GetSystemMenu (hwndDlg, FALSE), SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); +} + +// Protects an input field from having its content updated by a Paste action (call ToBootPwdField() to use this). +static LRESULT CALLBACK BootPwdFieldProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + WNDPROC wp = (WNDPROC) GetWindowLongPtrW (hwnd, GWLP_USERDATA); + + switch (message) + { + case WM_PASTE: + return 1; + } + + return CallWindowProcW (wp, hwnd, message, wParam, lParam); +} + + +// Protects an input field from having its content updated by a Paste action. Used for pre-boot password +// input fields (only the US keyboard layout is supported in pre-boot environment so we must prevent the +// user from pasting a password typed using a non-US keyboard layout). +void ToBootPwdField (HWND hwndDlg, UINT ctrlId) +{ + HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId); + + SetWindowLongPtrW (hwndCtrl, GWLP_USERDATA, (LONG_PTR) GetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC)); + SetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC, (LONG_PTR) BootPwdFieldProc); +} + + + +// This function currently serves the following purposes: +// - Determines scaling factors for current screen DPI and GUI aspect ratio. +// - Determines how Windows skews the GUI aspect ratio (which happens when the user has a non-default DPI). +// The determined values must be used when performing some GUI operations and calculations. +BOOL CALLBACK AuxiliaryDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + switch (msg) + { + case WM_INITDIALOG: + { + HDC hDC = GetDC (hwndDlg); + + if (hDC) + { + ScreenDPI = GetDeviceCaps (hDC, LOGPIXELSY); + ReleaseDC (hwndDlg, hDC); + } + + DPIScaleFactorX = 1; + DPIScaleFactorY = 1; + DlgAspectRatio = 1; + + if (ScreenDPI != USER_DEFAULT_SCREEN_DPI) + { + // Windows skews the GUI aspect ratio if the user has a non-default DPI. Hence, working with + // actual screen DPI is redundant and leads to incorrect results. What really matters here is + // how Windows actually renders our GUI. This is determined by comparing the expected and current + // sizes of a hidden calibration text field. + + RECT trec; + + trec.right = 0; + trec.bottom = 0; + + GetClientRect (GetDlgItem (hwndDlg, IDC_ASPECT_RATIO_CALIBRATION_BOX), &trec); + + if (trec.right != 0 && trec.bottom != 0) + { + // The size of the 282x282 IDC_ASPECT_RATIO_CALIBRATION_BOX rendered at the default DPI (96) is 423x458 + DPIScaleFactorX = (double) trec.right / 423; + DPIScaleFactorY = (double) trec.bottom / 458; + DlgAspectRatio = DPIScaleFactorX / DPIScaleFactorY; + } + } + + EndDialog (hwndDlg, 0); + return 1; + } + + case WM_CLOSE: + EndDialog (hwndDlg, 0); + return 1; + } + + return 0; +} + + +/* Except in response to the WM_INITDIALOG message, the dialog box procedure + should return nonzero if it processes the message, and zero if it does + not. - see DialogProc */ +BOOL CALLBACK AboutDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + static HBITMAP hbmTextualLogoBitmapRescaled = NULL; + + switch (msg) + { + case WM_INITDIALOG: + { + wchar_t szTmp[100]; + RECT rec; + + LocalizeDialog (hwndDlg, "IDD_ABOUT_DLG"); + + // Hyperlink + SetWindowText (GetDlgItem (hwndDlg, IDC_HOMEPAGE), L"www.idrix.fr"); + ToHyperlink (hwndDlg, IDC_HOMEPAGE); + + // Logo area background (must not keep aspect ratio; must retain Windows-imposed distortion) + GetClientRect (GetDlgItem (hwndDlg, IDC_ABOUT_LOGO_AREA), &rec); + SetWindowPos (GetDlgItem (hwndDlg, IDC_ABOUT_BKG), HWND_TOP, 0, 0, rec.right, rec.bottom, SWP_NOMOVE); + + // Resize the logo bitmap if the user has a non-default DPI + if (ScreenDPI != USER_DEFAULT_SCREEN_DPI) + { + // Logo (must recreate and keep the original aspect ratio as Windows distorts it) + hbmTextualLogoBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_TEXTUAL_LOGO_288DPI), + GetDlgItem (hwndDlg, IDC_TEXTUAL_LOGO_IMG), + 0, 0, 0, 0, FALSE, TRUE); + + SetWindowPos (GetDlgItem (hwndDlg, IDC_ABOUT_BKG), HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + + // Version + SendMessage (GetDlgItem (hwndDlg, IDT_ABOUT_VERSION), WM_SETFONT, (WPARAM) hUserBoldFont, 0); + StringCbPrintfW (szTmp, sizeof(szTmp), L"VeraCrypt %s", _T(VERSION_STRING)); +#ifdef _WIN64 + StringCbCatW (szTmp, sizeof(szTmp), L" (64-bit)"); +#else + StringCbCatW (szTmp, sizeof(szTmp), L" (32-bit)"); +#endif +#if (defined(_DEBUG) || defined(DEBUG)) + StringCbCatW (szTmp, sizeof(szTmp), L" (debug)"); +#endif + SetDlgItemText (hwndDlg, IDT_ABOUT_VERSION, szTmp); + SetDlgItemText (hwndDlg, IDT_ABOUT_RELEASE, TC_STR_RELEASED_BY); + + // Credits + SendMessage (GetDlgItem (hwndDlg, IDC_ABOUT_CREDITS), WM_SETFONT, (WPARAM) hUserFont, (LPARAM) 0); + SendMessage (hwndDlg, WM_APP, 0, 0); + return 1; + } + + case WM_APP: + SetWindowText (GetDlgItem (hwndDlg, IDC_ABOUT_CREDITS), + L"Based on TrueCrypt 7.1a, freely available at http://www.truecrypt.org/ .\r\n\r\n" + + L"Portions of this software:\r\n" + L"Copyright \xA9 2013-2016 IDRIX. All rights reserved.\r\n" + L"Copyright \xA9 2003-2012 TrueCrypt Developers Association. All Rights Reserved.\r\n" + L"Copyright \xA9 1998-2000 Paul Le Roux. All Rights Reserved.\r\n" + L"Copyright \xA9 1998-2008 Brian Gladman. All Rights Reserved.\r\n" + L"Copyright \xA9 2002-2004 Mark Adler. All Rights Reserved.\r\n\r\n" + + L"This software as a whole:\r\n" + L"Copyright \xA9 2013-2016 IDRIX. All rights reserved.\r\n\r\n" + + L"An IDRIX Release"); + + return 1; + + case WM_COMMAND: + if (lw == IDOK || lw == IDCANCEL) + { + PostMessage (hwndDlg, WM_CLOSE, 0, 0); + return 1; + } + + if (lw == IDC_HOMEPAGE) + { + Applink ("main", TRUE, ""); + return 1; + } + + // Disallow modification of credits + if (HIWORD (wParam) == EN_UPDATE) + { + SendMessage (hwndDlg, WM_APP, 0, 0); + return 1; + } + + return 0; + + case WM_CLOSE: + /* Delete buffered bitmaps (if any) */ + if (hbmTextualLogoBitmapRescaled != NULL) + { + DeleteObject ((HGDIOBJ) hbmTextualLogoBitmapRescaled); + hbmTextualLogoBitmapRescaled = NULL; + } + + EndDialog (hwndDlg, 0); + return 1; + } + + return 0; +} + + +static HWND StaticModelessWaitDlgHandle = NULL; + +// Call DisplayStaticModelessWaitDlg() to open this dialog and CloseStaticModelessWaitDlg() to close it. +static BOOL CALLBACK StaticModelessWaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + LocalizeDialog (hwndDlg, NULL); + + return 0; + } + + case WM_COMMAND: + + if (lw == IDOK || lw == IDCANCEL) + return 1; + + return 0; + + + case WM_CLOSE: + StaticModelessWaitDlgHandle = NULL; + EndDialog (hwndDlg, 0); + return 1; + } + + return 0; +} + + +// Opens a dialog window saying "Please wait..." which is not modal and does not need any GUI refresh after initialization. +void DisplayStaticModelessWaitDlg (HWND parent) +{ + if (StaticModelessWaitDlgHandle != NULL) + return; // Already shown + + StaticModelessWaitDlgHandle = CreateDialogParamW (hInst, MAKEINTRESOURCEW (IDD_STATIC_MODELESS_WAIT_DLG), parent, (DLGPROC) StaticModelessWaitDlgProc, (LPARAM) 0); + + ShowWindow (StaticModelessWaitDlgHandle, SW_SHOWNORMAL); + + // Allow synchronous use with the GUI being instantly and fully rendered + ProcessPaintMessages (StaticModelessWaitDlgHandle, 500); +} + + +void CloseStaticModelessWaitDlg (void) +{ + if (StaticModelessWaitDlgHandle == NULL) + return; // Not shown + + DestroyWindow (StaticModelessWaitDlgHandle); +} + + +BOOL IsButtonChecked (HWND hButton) +{ + if (SendMessage (hButton, BM_GETCHECK, 0, 0) == BST_CHECKED) + return TRUE; + else + return FALSE; +} + + +void CheckButton (HWND hButton) +{ + SendMessage (hButton, BM_SETCHECK, BST_CHECKED, 0); +} + + +void LeftPadString (wchar_t *szTmp, int len, int targetLen, wchar_t filler) +{ + int i; + + if (targetLen <= len) + return; + + for (i = targetLen-1; i >= (targetLen-len); i--) + szTmp [i] = szTmp [i-(targetLen-len)]; + + wmemset (szTmp, filler, targetLen-len); + szTmp [targetLen] = 0; +} + +/* InitDialog - initialize the applications main dialog, this function should + be called only once in the dialogs WM_INITDIALOG message handler */ +void InitDialog (HWND hwndDlg) +{ + NONCLIENTMETRICSW metric; + static BOOL aboutMenuAppended = FALSE; + + int nHeight; + LOGFONTW lf; + HMENU hMenu; + Font *font; + + /* Fonts */ + + memset (&lf, 0, sizeof(lf)); + + // Normal + font = GetFont ("font_normal"); + + metric.cbSize = sizeof (metric); + SystemParametersInfoW (SPI_GETNONCLIENTMETRICS, sizeof(metric), &metric, 0); + + WindowTitleBarFont = CreateFontIndirectW (&metric.lfCaptionFont); + + metric.lfMessageFont.lfHeight = CompensateDPIFont (!font ? -11 : -font->Size); + metric.lfMessageFont.lfWidth = 0; + + if (font && wcscmp (font->FaceName, L"default") != 0) + { + StringCbCopyW ((WCHAR *)metric.lfMessageFont.lfFaceName, sizeof (metric.lfMessageFont.lfFaceName), font->FaceName); + } + else if (IsOSAtLeast (WIN_VISTA)) + { + // Vista's new default font (size and spacing) breaks compatibility with Windows 2k/XP applications. + // Force use of Tahoma (as Microsoft does in many dialogs) until a native Vista look is implemented. + StringCbCopyW ((WCHAR *)metric.lfMessageFont.lfFaceName, sizeof (metric.lfMessageFont.lfFaceName), L"Tahoma"); + } + + hUserFont = CreateFontIndirectW (&metric.lfMessageFont); + + metric.lfMessageFont.lfUnderline = TRUE; + hUserUnderlineFont = CreateFontIndirectW (&metric.lfMessageFont); + + metric.lfMessageFont.lfUnderline = FALSE; + metric.lfMessageFont.lfWeight = FW_BOLD; + hUserBoldFont = CreateFontIndirectW (&metric.lfMessageFont); + + metric.lfMessageFont.lfUnderline = TRUE; + metric.lfMessageFont.lfWeight = FW_BOLD; + hUserUnderlineBoldFont = CreateFontIndirectW (&metric.lfMessageFont); + + // Fixed-size (hexadecimal digits) + nHeight = CompensateDPIFont (-12); + lf.lfHeight = nHeight; + lf.lfWidth = 0; + lf.lfEscapement = 0; + lf.lfOrientation = 0; + lf.lfWeight = FW_NORMAL; + lf.lfItalic = FALSE; + lf.lfUnderline = FALSE; + lf.lfStrikeOut = FALSE; + lf.lfCharSet = DEFAULT_CHARSET; + lf.lfOutPrecision = OUT_DEFAULT_PRECIS; + lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; + lf.lfQuality = PROOF_QUALITY; + lf.lfPitchAndFamily = FF_DONTCARE; + StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName), L"Courier New"); + hFixedDigitFont = CreateFontIndirectW (&lf); + if (hFixedDigitFont == NULL) + { + handleWin32Error (hwndDlg, SRC_POS); + AbortProcess ("NOFONT"); + } + + // Bold + font = GetFont ("font_bold"); + + nHeight = CompensateDPIFont (!font ? -13 : -font->Size); + lf.lfHeight = nHeight; + lf.lfWeight = FW_BLACK; + StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName), !font ? L"Arial" : font->FaceName); + hBoldFont = CreateFontIndirectW (&lf); + if (hBoldFont == NULL) + { + handleWin32Error (hwndDlg, SRC_POS); + AbortProcess ("NOFONT"); + } + + // Title + font = GetFont ("font_title"); + + nHeight = CompensateDPIFont (!font ? -21 : -font->Size); + lf.lfHeight = nHeight; + lf.lfWeight = FW_REGULAR; + StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName),!font ? L"Times New Roman" : font->FaceName); + hTitleFont = CreateFontIndirectW (&lf); + if (hTitleFont == NULL) + { + handleWin32Error (hwndDlg, SRC_POS); + AbortProcess ("NOFONT"); + } + + // Fixed-size + font = GetFont ("font_fixed"); + + nHeight = CompensateDPIFont (!font ? -12 : -font->Size); + lf.lfHeight = nHeight; + lf.lfWidth = 0; + lf.lfEscapement = 0; + lf.lfOrientation = 0; + lf.lfWeight = FW_NORMAL; + lf.lfItalic = FALSE; + lf.lfUnderline = FALSE; + lf.lfStrikeOut = FALSE; + lf.lfCharSet = DEFAULT_CHARSET; + lf.lfOutPrecision = OUT_DEFAULT_PRECIS; + lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; + lf.lfQuality = PROOF_QUALITY; + lf.lfPitchAndFamily = FF_DONTCARE; + StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName),!font ? L"Lucida Console" : font->FaceName); + hFixedFont = CreateFontIndirectW (&lf); + if (hFixedFont == NULL) + { + handleWin32Error (hwndDlg, SRC_POS); + AbortProcess ("NOFONT"); + } + + if (!aboutMenuAppended) + { + hMenu = GetSystemMenu (hwndDlg, FALSE); + AppendMenu (hMenu, MF_SEPARATOR, 0, L""); + AppendMenuW (hMenu, MF_ENABLED | MF_STRING, IDC_ABOUT, GetString ("ABOUTBOX")); + + aboutMenuAppended = TRUE; + } +} + + +// The parameter maxMessagesToProcess prevents endless processing of paint messages +void ProcessPaintMessages (HWND hwnd, int maxMessagesToProcess) +{ + MSG paintMsg; + int msgCounter = maxMessagesToProcess; + + while (PeekMessageW (&paintMsg, hwnd, 0, 0, PM_REMOVE | PM_QS_PAINT) != 0 && msgCounter-- > 0) + { + DispatchMessageW (&paintMsg); + } +} + + +HDC CreateMemBitmap (HINSTANCE hInstance, HWND hwnd, wchar_t *resource) +{ + HBITMAP picture = LoadBitmap (hInstance, resource); + HDC viewDC = GetDC (hwnd), dcMem; + + dcMem = CreateCompatibleDC (viewDC); + + SetMapMode (dcMem, MM_TEXT); + + SelectObject (dcMem, picture); + + DeleteObject (picture); + + ReleaseDC (hwnd, viewDC); + + return dcMem; +} + + +/* Renders the specified bitmap at the specified location and stretches it to fit (anti-aliasing is applied). +If bDirectRender is FALSE and both nWidth and nHeight are zero, the width and height of hwndDest are +retrieved and adjusted according to screen DPI (the width and height of the resultant image are adjusted the +same way); furthermore, if bKeepAspectRatio is TRUE, the smaller DPI factor of the two (i.e. horiz. or vert.) +is used both for horiz. and vert. scaling (note that the overall GUI aspect ratio changes irregularly in +both directions depending on the DPI). If bDirectRender is TRUE, bKeepAspectRatio is ignored. +This function returns a handle to the scaled bitmap. When the bitmap is no longer needed, it should be +deleted by calling DeleteObject() with the handle passed as the parameter. +Known Windows issues: +- For some reason, anti-aliasing is not applied if the source bitmap contains less than 16K pixels. +- Windows 2000 may produce slightly inaccurate colors even when source, buffer, and target are 24-bit true color. */ +HBITMAP RenderBitmap (wchar_t *resource, HWND hwndDest, int x, int y, int nWidth, int nHeight, BOOL bDirectRender, BOOL bKeepAspectRatio) +{ + LRESULT lResult = 0; + + HDC hdcSrc = CreateMemBitmap (hInst, hwndDest, resource); + if (!hdcSrc) + return NULL; + + HGDIOBJ picture = GetCurrentObject (hdcSrc, OBJ_BITMAP); + + HBITMAP hbmpRescaled = NULL; + BITMAP bitmap; + + HDC hdcRescaled; + + if (!bDirectRender && nWidth == 0 && nHeight == 0) + { + RECT rec; + + GetClientRect (hwndDest, &rec); + + if (bKeepAspectRatio) + { + if (DlgAspectRatio > 1) + { + // Do not fix this, it's correct. We use the Y scale factor intentionally for both + // directions to maintain aspect ratio (see above for more info). + nWidth = CompensateYDPI (rec.right); + nHeight = CompensateYDPI (rec.bottom); + } + else + { + // Do not fix this, it's correct. We use the X scale factor intentionally for both + // directions to maintain aspect ratio (see above for more info). + nWidth = CompensateXDPI (rec.right); + nHeight = CompensateXDPI (rec.bottom); + } + } + else + { + nWidth = CompensateXDPI (rec.right); + nHeight = CompensateYDPI (rec.bottom); + } + } + + GetObject (picture, sizeof (BITMAP), &bitmap); + + hdcRescaled = CreateCompatibleDC (hdcSrc); + + if (hdcRescaled) + { + hbmpRescaled = CreateCompatibleBitmap (hdcSrc, nWidth, nHeight); + + SelectObject (hdcRescaled, hbmpRescaled); + + /* Anti-aliasing mode (HALFTONE is the only anti-aliasing algorithm natively supported by Windows 2000. + TODO: GDI+ offers higher quality -- InterpolationModeHighQualityBicubic) */ + SetStretchBltMode (hdcRescaled, HALFTONE); + + StretchBlt (hdcRescaled, + 0, + 0, + nWidth, + nHeight, + hdcSrc, + 0, + 0, + bitmap.bmWidth, + bitmap.bmHeight, + SRCCOPY); + + DeleteDC (hdcSrc); + + if (bDirectRender) + { + HDC hdcDest = GetDC (hwndDest); + if (hdcDest) + { + BitBlt (hdcDest, x, y, nWidth, nHeight, hdcRescaled, 0, 0, SRCCOPY); + ReleaseDC (hwndDest, hdcDest); + } + } + else + { + lResult = SendMessage (hwndDest, (UINT) STM_SETIMAGE, (WPARAM) IMAGE_BITMAP, (LPARAM) (HANDLE) hbmpRescaled); + } + + if ((HGDIOBJ) lResult != NULL && (HGDIOBJ) lResult != (HGDIOBJ) hbmpRescaled) + DeleteObject ((HGDIOBJ) lResult); + + DeleteDC (hdcRescaled); + } + + return hbmpRescaled; +} + + +LRESULT CALLBACK +RedTick (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + if (uMsg == WM_CREATE) + { + } + else if (uMsg == WM_DESTROY) + { + } + else if (uMsg == WM_TIMER) + { + } + else if (uMsg == WM_PAINT) + { + PAINTSTRUCT tmp; + HPEN hPen; + HDC hDC; + BOOL bEndPaint; + RECT Rect; + + if (GetUpdateRect (hwnd, NULL, FALSE)) + { + hDC = BeginPaint (hwnd, &tmp); + bEndPaint = TRUE; + if (hDC == NULL) + return DefWindowProcW (hwnd, uMsg, wParam, lParam); + } + else + { + hDC = GetDC (hwnd); + bEndPaint = FALSE; + } + + GetClientRect (hwnd, &Rect); + + hPen = CreatePen (PS_SOLID, 2, RGB (0, 255, 0)); + if (hPen != NULL) + { + HGDIOBJ hObj = SelectObject (hDC, hPen); + WORD bx = LOWORD (GetDialogBaseUnits ()); + WORD by = HIWORD (GetDialogBaseUnits ()); + + MoveToEx (hDC, (Rect.right - Rect.left) / 2, Rect.bottom, NULL); + LineTo (hDC, Rect.right, Rect.top); + MoveToEx (hDC, (Rect.right - Rect.left) / 2, Rect.bottom, NULL); + + LineTo (hDC, (3 * bx) / 4, (2 * by) / 8); + + SelectObject (hDC, hObj); + DeleteObject (hPen); + } + + if (bEndPaint) + EndPaint (hwnd, &tmp); + else + ReleaseDC (hwnd, hDC); + + return TRUE; + } + + return DefWindowProcW (hwnd, uMsg, wParam, lParam); +} + +BOOL +RegisterRedTick (HINSTANCE hInstance) +{ + WNDCLASSW wc; + ULONG rc; + + memset(&wc, 0 , sizeof wc); + + wc.style = CS_HREDRAW | CS_VREDRAW; + wc.cbClsExtra = 0; + wc.cbWndExtra = 4; + wc.hInstance = hInstance; + wc.hIcon = LoadIcon (NULL, IDI_APPLICATION); + wc.hCursor = NULL; + wc.hbrBackground = (HBRUSH) GetStockObject (LTGRAY_BRUSH); + wc.lpszClassName = L"VCREDTICK"; + wc.lpfnWndProc = &RedTick; + + rc = (ULONG) RegisterClassW (&wc); + + return rc == 0 ? FALSE : TRUE; +} + +BOOL +UnregisterRedTick (HINSTANCE hInstance) +{ + return UnregisterClassW (L"VCREDTICK", hInstance); +} + +LRESULT CALLBACK +SplashDlgProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + return DefDlgProcW (hwnd, uMsg, wParam, lParam); +} + +static int g_waitCursorCounter = 0; + +void +WaitCursor () +{ + static HCURSOR hcWait; + if (hcWait == NULL) + hcWait = LoadCursor (NULL, IDC_WAIT); + + if ((g_waitCursorCounter == 0) || (hCursor != hcWait)) + { + SetCursor (hcWait); + hCursor = hcWait; + } + g_waitCursorCounter++; +} + +void +NormalCursor () +{ + static HCURSOR hcArrow; + if (hcArrow == NULL) + hcArrow = LoadCursor (NULL, IDC_ARROW); + if (g_waitCursorCounter > 0) + g_waitCursorCounter--; + if (g_waitCursorCounter == 0) + { + SetCursor (hcArrow); + hCursor = NULL; + } +} + +void +ArrowWaitCursor () +{ + static HCURSOR hcArrowWait; + if (hcArrowWait == NULL) + hcArrowWait = LoadCursor (NULL, IDC_APPSTARTING); + if ((g_waitCursorCounter == 0) || (hCursor != hcArrowWait)) + { + SetCursor (hcArrowWait); + hCursor = hcArrowWait; + } + g_waitCursorCounter++; +} + +void HandCursor () +{ + static HCURSOR hcHand; + if (hcHand == NULL) + hcHand = LoadCursor (NULL, IDC_HAND); + SetCursor (hcHand); + hCursor = hcHand; +} + +void +AddComboPair (HWND hComboBox, const wchar_t *lpszItem, int value) +{ + LPARAM nIndex; + + nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) lpszItem); + nIndex = SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) value); +} + +void +SelectAlgo (HWND hComboBox, int *algo_id) +{ + LPARAM nCount = SendMessage (hComboBox, CB_GETCOUNT, 0, 0); + LPARAM x, i; + + for (i = 0; i < nCount; i++) + { + x = SendMessage (hComboBox, CB_GETITEMDATA, i, 0); + if (x == (LPARAM) *algo_id) + { + SendMessage (hComboBox, CB_SETCURSEL, i, 0); + return; + } + } + + /* Something went wrong ; couldn't find the requested algo id so we drop + back to a default */ + + *algo_id = (int) SendMessage (hComboBox, CB_GETITEMDATA, 0, 0); + + SendMessage (hComboBox, CB_SETCURSEL, 0, 0); + +} + +void PopulateWipeModeCombo (HWND hComboBox, BOOL bNA, BOOL bInPlaceEncryption, BOOL bHeaderWipe) +{ + if (bNA) + { + AddComboPair (hComboBox, GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE"), TC_WIPE_NONE); + } + else + { + if (!bHeaderWipe) + { + AddComboPair (hComboBox, GetString ("WIPE_MODE_NONE"), TC_WIPE_NONE); + } + + AddComboPair (hComboBox, GetString ("WIPE_MODE_1_RAND"), TC_WIPE_1_RAND); + AddComboPair (hComboBox, GetString ("WIPE_MODE_3_DOD_5220"), TC_WIPE_3_DOD_5220); + AddComboPair (hComboBox, GetString ("WIPE_MODE_7_DOD_5220"), TC_WIPE_7_DOD_5220); + AddComboPair (hComboBox, GetString ("WIPE_MODE_35_GUTMANN"), TC_WIPE_35_GUTMANN); + + if (bHeaderWipe) + AddComboPair (hComboBox, GetString ("WIPE_MODE_256"), TC_WIPE_256); // paranoid wipe for volume header + } +} + +wchar_t *GetWipeModeName (WipeAlgorithmId modeId) +{ + switch (modeId) + { + case TC_WIPE_NONE: + return GetString ("WIPE_MODE_NONE"); + + case TC_WIPE_1_RAND: + return GetString ("WIPE_MODE_1_RAND"); + + case TC_WIPE_3_DOD_5220: + return GetString ("WIPE_MODE_3_DOD_5220"); + + case TC_WIPE_7_DOD_5220: + return GetString ("WIPE_MODE_7_DOD_5220"); + + case TC_WIPE_35_GUTMANN: + return GetString ("WIPE_MODE_35_GUTMANN"); + + case TC_WIPE_256: + return GetString ("WIPE_MODE_256"); + + default: + return GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE"); + } +} + +wchar_t *GetPathType (const wchar_t *path, BOOL bUpperCase, BOOL *bIsPartition) +{ + if (wcsstr (path, L"Partition") + && wcsstr (path, L"Partition0") == NULL) + { + *bIsPartition = TRUE; + return GetString (bUpperCase ? "PARTITION_UPPER_CASE" : "PARTITION_LOWER_CASE"); + } + else if (wcsstr (path, L"HarddiskVolume")) + { + *bIsPartition = TRUE; + return GetString (bUpperCase ? "VOLUME_UPPER_CASE" : "VOLUME_LOWER_CASE"); + } + + *bIsPartition = FALSE; + return GetString (bUpperCase ? "DEVICE_UPPER_CASE" : "DEVICE_LOWER_CASE"); +} + +LRESULT CALLBACK CustomDlgProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + if (uMsg == WM_SETCURSOR && hCursor != NULL) + { + SetCursor (hCursor); + return TRUE; + } + + return DefDlgProcW (hwnd, uMsg, wParam, lParam); +} + +/* +static BOOL IsReturnAddress (DWORD64 address) +{ + static size_t codeEnd = 0; + byte *sp = (byte *) address; + + if (codeEnd == 0) + { + MEMORY_BASIC_INFORMATION mi; + if (VirtualQuery ((LPCVOID) 0x401000, &mi, sizeof (mi)) >= sizeof (mi)) + codeEnd = (size_t) mi.BaseAddress + mi.RegionSize; + } + + if (address < 0x401000 + 8 || address > codeEnd) + return FALSE; + + return sp[-5] == 0xe8 // call ADDR + || (sp[-6] == 0xff && sp[-5] == 0x15) // call [ADDR] + || (sp[-2] == 0xff && (sp[-1] & 0xf0) == 0xd0); // call REG +} +*/ + +typedef struct +{ + EXCEPTION_POINTERS *ExceptionPointers; + HANDLE ExceptionThread; + +} ExceptionHandlerThreadArgs; + + +void ExceptionHandlerThread (void *threadArg) +{ + ExceptionHandlerThreadArgs *args = (ExceptionHandlerThreadArgs *) threadArg; + + EXCEPTION_POINTERS *ep = args->ExceptionPointers; + //DWORD addr; + DWORD exCode = ep->ExceptionRecord->ExceptionCode; + // SYSTEM_INFO si; + // wchar_t msg[8192]; + // char modPath[MAX_PATH]; + // int crc = 0; + // char url[MAX_URL_LENGTH]; + // char lpack[128]; + // stringstream callStack; + // addr = (DWORD) ep->ExceptionRecord->ExceptionAddress; + // PDWORD sp = (PDWORD) ep->ContextRecord->Esp; + // int frameNumber = 0; + + switch (exCode) + { + case STATUS_IN_PAGE_ERROR: + case 0xeedfade: + // Exception not caused by VeraCrypt + MessageBoxW (0, GetString ("EXCEPTION_REPORT_EXT"), + GetString ("EXCEPTION_REPORT_TITLE"), + MB_ICONERROR | MB_OK | MB_SETFOREGROUND | MB_TOPMOST); + return; + } + + // Call stack +/* HMODULE dbgDll = LoadLibrary ("dbghelp.dll"); + if (dbgDll) + { + typedef DWORD (__stdcall *SymGetOptions_t) (); + typedef DWORD (__stdcall *SymSetOptions_t) (DWORD SymOptions); + typedef BOOL (__stdcall *SymInitialize_t) (HANDLE hProcess, PCSTR UserSearchPath, BOOL fInvadeProcess); + typedef BOOL (__stdcall *StackWalk64_t) (DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME64 StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress); + typedef BOOL (__stdcall * SymFromAddr_t) (HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol); + + SymGetOptions_t DbgHelpSymGetOptions = (SymGetOptions_t) GetProcAddress (dbgDll, "SymGetOptions"); + SymSetOptions_t DbgHelpSymSetOptions = (SymSetOptions_t) GetProcAddress (dbgDll, "SymSetOptions"); + SymInitialize_t DbgHelpSymInitialize = (SymInitialize_t) GetProcAddress (dbgDll, "SymInitialize"); + PFUNCTION_TABLE_ACCESS_ROUTINE64 DbgHelpSymFunctionTableAccess64 = (PFUNCTION_TABLE_ACCESS_ROUTINE64) GetProcAddress (dbgDll, "SymFunctionTableAccess64"); + PGET_MODULE_BASE_ROUTINE64 DbgHelpSymGetModuleBase64 = (PGET_MODULE_BASE_ROUTINE64) GetProcAddress (dbgDll, "SymGetModuleBase64"); + StackWalk64_t DbgHelpStackWalk64 = (StackWalk64_t) GetProcAddress (dbgDll, "StackWalk64"); + SymFromAddr_t DbgHelpSymFromAddr = (SymFromAddr_t) GetProcAddress (dbgDll, "SymFromAddr"); + + if (DbgHelpSymGetOptions && DbgHelpSymSetOptions && DbgHelpSymInitialize && DbgHelpSymFunctionTableAccess64 && DbgHelpSymGetModuleBase64 && DbgHelpStackWalk64 && DbgHelpSymFromAddr) + { + DbgHelpSymSetOptions (DbgHelpSymGetOptions() | SYMOPT_DEFERRED_LOADS | SYMOPT_ALLOW_ABSOLUTE_SYMBOLS | SYMOPT_NO_CPP); + + if (DbgHelpSymInitialize (GetCurrentProcess(), NULL, TRUE)) + { + STACKFRAME64 frame; + memset (&frame, 0, sizeof (frame)); + + frame.AddrPC.Offset = ep->ContextRecord->Eip; + frame.AddrPC.Mode = AddrModeFlat; + frame.AddrStack.Offset = ep->ContextRecord->Esp; + frame.AddrStack.Mode = AddrModeFlat; + frame.AddrFrame.Offset = ep->ContextRecord->Ebp; + frame.AddrFrame.Mode = AddrModeFlat; + + string lastSymbol; + + while (frameNumber < 32 && DbgHelpStackWalk64 (IMAGE_FILE_MACHINE_I386, GetCurrentProcess(), args->ExceptionThread, &frame, ep->ContextRecord, NULL, DbgHelpSymFunctionTableAccess64, DbgHelpSymGetModuleBase64, NULL)) + { + if (!frame.AddrPC.Offset) + continue; + + ULONG64 symbolBuffer[(sizeof (SYMBOL_INFO) + MAX_SYM_NAME * sizeof (TCHAR) + sizeof (ULONG64) - 1) / sizeof (ULONG64)]; + memset (symbolBuffer, 0, sizeof (symbolBuffer)); + + PSYMBOL_INFO symbol = (PSYMBOL_INFO) symbolBuffer; + symbol->SizeOfStruct = sizeof (SYMBOL_INFO); + symbol->MaxNameLen = MAX_SYM_NAME; + + if (DbgHelpSymFromAddr (GetCurrentProcess(), frame.AddrPC.Offset, NULL, symbol) && symbol->NameLen > 0) + { + for (size_t i = 0; i < symbol->NameLen; ++i) + { + if (!isalnum (symbol->Name[i])) + symbol->Name[i] = '_'; + } + + if (symbol->Name != lastSymbol) + callStack << "&st" << frameNumber++ << "=" << symbol->Name; + + lastSymbol = symbol->Name; + } + else if (frameNumber == 0 || IsReturnAddress (frame.AddrPC.Offset)) + { + callStack << "&st" << frameNumber++ << "=0x" << hex << frame.AddrPC.Offset << dec; + } + } + } + } + } + + // StackWalk64() may fail due to missing frame pointers + list retAddrs; + if (frameNumber == 0) + retAddrs.push_back (ep->ContextRecord->Eip); + + retAddrs.push_back (0); + + MEMORY_BASIC_INFORMATION mi; + VirtualQuery (sp, &mi, sizeof (mi)); + PDWORD stackTop = (PDWORD)((byte *) mi.BaseAddress + mi.RegionSize); + int i = 0; + + while (retAddrs.size() < 16 && &sp[i] < stackTop) + { + if (IsReturnAddress (sp[i])) + { + bool duplicate = false; + foreach (DWORD prevAddr, retAddrs) + { + if (sp[i] == prevAddr) + { + duplicate = true; + break; + } + } + + if (!duplicate) + retAddrs.push_back (sp[i]); + } + i++; + } + + if (retAddrs.size() > 1) + { + foreach (DWORD addr, retAddrs) + { + callStack << "&st" << frameNumber++ << "=0x" << hex << addr << dec; + } + } + + // Checksum of the module + if (GetModuleFileName (NULL, modPath, sizeof (modPath))) + { + HANDLE h = CreateFile (modPath, FILE_READ_DATA | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + if (h != INVALID_HANDLE_VALUE) + { + BY_HANDLE_FILE_INFORMATION fi; + if (GetFileInformationByHandle (h, &fi)) + { + char *buf = (char *) malloc (fi.nFileSizeLow); + if (buf) + { + DWORD bytesRead; + if (ReadFile (h, buf, fi.nFileSizeLow, &bytesRead, NULL) && bytesRead == fi.nFileSizeLow) + crc = GetCrc32 ((unsigned char *) buf, fi.nFileSizeLow); + free (buf); + } + } + CloseHandle (h); + } + } + + GetSystemInfo (&si); + + if (LocalizationActive) + sprintf_s (lpack, sizeof (lpack), "&langpack=%s_%s", GetPreferredLangId (), GetActiveLangPackVersion ()); + else + lpack[0] = 0; + + + sprintf (url, TC_APPLINK_SECURE "&dest=err-report%s&os=%s&osver=%d.%d.%d&arch=%s&cpus=%d&app=%s&cksum=%x&dlg=%s&err=%x&addr=%x" + , lpack + , GetWindowsEdition().c_str() + , CurrentOSMajor + , CurrentOSMinor + , CurrentOSServicePack + , Is64BitOs () ? "x64" : "x86" + , si.dwNumberOfProcessors +#ifdef TCMOUNT + ,"main" +#endif +#ifdef VOLFORMAT + ,"format" +#endif +#ifdef SETUP + ,"setup" +#endif + , crc + , LastDialogId ? LastDialogId : "-" + , exCode + , addr); + + string urlStr = url + callStack.str(); + + _snwprintf (msg, array_capacity (msg), GetString ("EXCEPTION_REPORT"), urlStr.c_str()); + + if (IDYES == MessageBoxW (0, msg, GetString ("EXCEPTION_REPORT_TITLE"), MB_ICONERROR | MB_YESNO | MB_DEFBUTTON1)) + ShellExecute (NULL, "open", urlStr.c_str(), NULL, NULL, SW_SHOWNORMAL); + else */ + UnhandledExceptionFilter (ep); +} + + +LONG __stdcall ExceptionHandler (EXCEPTION_POINTERS *ep) +{ + SetUnhandledExceptionFilter (NULL); + + if (SystemFileSelectorCallPending && SystemFileSelectorCallerThreadId == GetCurrentThreadId()) + { + MessageBoxW (NULL, GetString ("EXCEPTION_REPORT_EXT_FILESEL"), GetString ("EXCEPTION_REPORT_TITLE"), MB_ICONERROR | MB_OK | MB_SETFOREGROUND | MB_TOPMOST); + + UnhandledExceptionFilter (ep); + return EXCEPTION_EXECUTE_HANDLER; + } + + ExceptionHandlerThreadArgs args; + args.ExceptionPointers = ep; + args.ExceptionThread = GetCurrentThread(); + + WaitForSingleObject ((HANDLE) _beginthread (ExceptionHandlerThread, 0, &args), INFINITE); + + return EXCEPTION_EXECUTE_HANDLER; +} + + +void InvalidParameterHandler (const wchar_t *expression, const wchar_t *function, const wchar_t *file, unsigned int line, uintptr_t reserved) +{ + TC_THROW_FATAL_EXCEPTION; +} + + +static LRESULT CALLBACK NonInstallUacWndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + return DefWindowProcW (hWnd, message, wParam, lParam); +} + + +// Mutex handling to prevent multiple instances of the wizard or main app from dealing with system encryption. +// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). +BOOL CreateSysEncMutex (void) +{ + return TCCreateMutex (&hSysEncMutex, TC_MUTEX_NAME_SYSENC); +} + + +BOOL InstanceHasSysEncMutex (void) +{ + return (hSysEncMutex != NULL); +} + + +// Mutex handling to prevent multiple instances of the wizard from dealing with system encryption +void CloseSysEncMutex (void) +{ + TCCloseMutex (&hSysEncMutex); +} + + +// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). +BOOL CreateNonSysInplaceEncMutex (void) +{ + return TCCreateMutex (&hNonSysInplaceEncMutex, TC_MUTEX_NAME_NONSYS_INPLACE_ENC); +} + + +BOOL InstanceHasNonSysInplaceEncMutex (void) +{ + return (hNonSysInplaceEncMutex != NULL); +} + + +void CloseNonSysInplaceEncMutex (void) +{ + TCCloseMutex (&hNonSysInplaceEncMutex); +} + + +// Returns TRUE if another instance of the wizard is preparing, resuming or performing non-system in-place encryption +BOOL NonSysInplaceEncInProgressElsewhere (void) +{ + return (!InstanceHasNonSysInplaceEncMutex () + && MutexExistsOnSystem (TC_MUTEX_NAME_NONSYS_INPLACE_ENC)); +} + + +// Mutex handling to prevent multiple instances of the wizard or main app from trying to install +// or register the driver or from trying to launch it in portable mode at the same time. +// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). +BOOL CreateDriverSetupMutex (void) +{ + return TCCreateMutex (&hDriverSetupMutex, TC_MUTEX_NAME_DRIVER_SETUP); +} + + +void CloseDriverSetupMutex (void) +{ + TCCloseMutex (&hDriverSetupMutex); +} + + +BOOL CreateAppSetupMutex (void) +{ + return TCCreateMutex (&hAppSetupMutex, TC_MUTEX_NAME_APP_SETUP); +} + + +void CloseAppSetupMutex (void) +{ + TCCloseMutex (&hAppSetupMutex); +} + + +BOOL IsTrueCryptInstallerRunning (void) +{ + return (MutexExistsOnSystem (TC_MUTEX_NAME_APP_SETUP)); +} + + +// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). +BOOL TCCreateMutex (volatile HANDLE *hMutex, wchar_t *name) +{ + if (*hMutex != NULL) + return TRUE; // This instance already has the mutex + + *hMutex = CreateMutex (NULL, TRUE, name); + if (*hMutex == NULL) + { + // In multi-user configurations, the OS returns "Access is denied" here when a user attempts + // to acquire the mutex if another user already has. However, on Vista, "Access is denied" is + // returned also if the mutex is owned by a process with admin rights while we have none. + + return FALSE; + } + + if (GetLastError () == ERROR_ALREADY_EXISTS) + { + ReleaseMutex (*hMutex); + CloseHandle (*hMutex); + + *hMutex = NULL; + return FALSE; + } + + return TRUE; +} + + +void TCCloseMutex (volatile HANDLE *hMutex) +{ + if (*hMutex != NULL) + { + if (ReleaseMutex (*hMutex) + && CloseHandle (*hMutex)) + *hMutex = NULL; + } +} + + +// Returns TRUE if a process running on the system has the specified mutex (otherwise FALSE). +BOOL MutexExistsOnSystem (wchar_t *name) +{ + if (name[0] == 0) + return FALSE; + + HANDLE hMutex = OpenMutex (MUTEX_ALL_ACCESS, FALSE, name); + + if (hMutex == NULL) + { + if (GetLastError () == ERROR_FILE_NOT_FOUND) + return FALSE; + + if (GetLastError () == ERROR_ACCESS_DENIED) // On Vista, this is returned if the owner of the mutex is elevated while we are not + return TRUE; + + // The call failed and it is not certain whether the mutex exists or not + return FALSE; + } + + CloseHandle (hMutex); + return TRUE; +} + + +uint32 ReadDriverConfigurationFlags () +{ + DWORD configMap; + + if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_DRIVER_CONFIG_REG_VALUE_NAME, &configMap)) + configMap = 0; + + return configMap; +} + + +uint32 ReadEncryptionThreadPoolFreeCpuCountLimit () +{ + DWORD count; + + if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME, &count)) + count = 0; + + return count; +} + + +BOOL LoadSysEncSettings () +{ + BOOL status = TRUE; + DWORD size = 0; + char *sysEncCfgFileBuf = LoadFile (GetConfigPath (TC_APPD_FILENAME_SYSTEM_ENCRYPTION), &size); + char *xml = sysEncCfgFileBuf; + char paramName[100], paramVal[MAX_PATH]; + + // Defaults + int newSystemEncryptionStatus = SYSENC_STATUS_NONE; + WipeAlgorithmId newnWipeMode = TC_WIPE_NONE; + + if (!FileExists (GetConfigPath (TC_APPD_FILENAME_SYSTEM_ENCRYPTION))) + { + SystemEncryptionStatus = newSystemEncryptionStatus; + nWipeMode = newnWipeMode; + } + + if (xml == NULL) + { + return FALSE; + } + + while (xml = XmlFindElement (xml, "config")) + { + XmlGetAttributeText (xml, "key", paramName, sizeof (paramName)); + XmlGetNodeText (xml, paramVal, sizeof (paramVal)); + + if (strcmp (paramName, "SystemEncryptionStatus") == 0) + { + newSystemEncryptionStatus = atoi (paramVal); + } + else if (strcmp (paramName, "WipeMode") == 0) + { + newnWipeMode = (WipeAlgorithmId) atoi (paramVal); + } + + xml++; + } + + SystemEncryptionStatus = newSystemEncryptionStatus; + nWipeMode = newnWipeMode; + + free (sysEncCfgFileBuf); + return status; +} + + +// Returns the number of partitions where non-system in-place encryption is progress or had been in progress +// but was interrupted. In addition, via the passed pointer, returns the last selected wipe algorithm ID. +int LoadNonSysInPlaceEncSettings (WipeAlgorithmId *wipeAlgorithm) +{ + char *fileBuf = NULL; + char *fileBuf2 = NULL; + DWORD size, size2; + int count; + + *wipeAlgorithm = TC_WIPE_NONE; + + if (!FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC))) + return 0; + + if ((fileBuf = LoadFile (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC), &size)) == NULL) + return 0; + + if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE))) + { + if ((fileBuf2 = LoadFile (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE), &size2)) != NULL) + *wipeAlgorithm = (WipeAlgorithmId) atoi (fileBuf2); + } + + count = atoi (fileBuf); + + if (fileBuf != NULL) + TCfree (fileBuf); + + if (fileBuf2 != NULL) + TCfree (fileBuf2); + + return (count); +} + + +void RemoveNonSysInPlaceEncNotifications (void) +{ + if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC))) + _wremove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC)); + + if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE))) + _wremove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE)); + + if (!IsNonInstallMode () && SystemEncryptionStatus == SYSENC_STATUS_NONE) + ManageStartupSeqWiz (TRUE, L""); +} + + +void SavePostInstallTasksSettings (int command) +{ + FILE *f = NULL; + + if (IsNonInstallMode() && command != TC_POST_INSTALL_CFG_REMOVE_ALL) + return; + + switch (command) + { + case TC_POST_INSTALL_CFG_REMOVE_ALL: + _wremove (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL)); + _wremove (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES)); + break; + + case TC_POST_INSTALL_CFG_TUTORIAL: + f = _wfopen (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL), L"w"); + break; + + case TC_POST_INSTALL_CFG_RELEASE_NOTES: + f = _wfopen (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES), L"w"); + break; + + default: + return; + } + + if (f == NULL) + return; + + if (fputws (L"1", f) < 0) + { + // Error + fclose (f); + return; + } + + TCFlushFile (f); + + fclose (f); +} + + +void DoPostInstallTasks (HWND hwndDlg) +{ + BOOL bDone = FALSE; + + if (FileExists (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL))) + { + if (AskYesNo ("AFTER_INSTALL_TUTORIAL", hwndDlg) == IDYES) + Applink ("beginnerstutorial", TRUE, ""); + + bDone = TRUE; + } + + if (FileExists (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES))) + { + if (AskYesNo ("AFTER_UPGRADE_RELEASE_NOTES", hwndDlg) == IDYES) + Applink ("releasenotes", TRUE, ""); + + bDone = TRUE; + } + + if (bDone) + SavePostInstallTasksSettings (TC_POST_INSTALL_CFG_REMOVE_ALL); +} + + +void InitOSVersionInfo () +{ + OSVERSIONINFOEXW os; + os.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW); + + if (GetVersionExW ((LPOSVERSIONINFOW) &os) == FALSE) + AbortProcess ("NO_OS_VER"); + + CurrentOSMajor = os.dwMajorVersion; + CurrentOSMinor = os.dwMinorVersion; + CurrentOSServicePack = os.wServicePackMajor; + + if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 5 && CurrentOSMinor == 0) + nCurrentOS = WIN_2000; + else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 5 && CurrentOSMinor == 1) + nCurrentOS = WIN_XP; + else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 5 && CurrentOSMinor == 2) + { + if (os.wProductType == VER_NT_SERVER || os.wProductType == VER_NT_DOMAIN_CONTROLLER) + nCurrentOS = WIN_SERVER_2003; + else + nCurrentOS = WIN_XP64; + } + else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 6 && CurrentOSMinor == 0) + { + if (os.wProductType != VER_NT_WORKSTATION) + nCurrentOS = WIN_SERVER_2008; + else + nCurrentOS = WIN_VISTA; + } + else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 6 && CurrentOSMinor == 1) + nCurrentOS = ((os.wProductType != VER_NT_WORKSTATION) ? WIN_SERVER_2008_R2 : WIN_7); + else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 6 && CurrentOSMinor == 2) + nCurrentOS = ((os.wProductType != VER_NT_WORKSTATION) ? WIN_SERVER_2012 : WIN_8); + else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 6 && CurrentOSMinor == 3) + nCurrentOS = ((os.wProductType != VER_NT_WORKSTATION) ? WIN_SERVER_2012_R2 : WIN_8_1); + else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 10 && CurrentOSMinor == 0) + nCurrentOS = ((os.wProductType != VER_NT_WORKSTATION) ? WIN_SERVER_2016 : WIN_10); + else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 4) + nCurrentOS = WIN_NT4; + else if (os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && os.dwMajorVersion == 4 && os.dwMinorVersion == 0) + nCurrentOS = WIN_95; + else if (os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && os.dwMajorVersion == 4 && os.dwMinorVersion == 10) + nCurrentOS = WIN_98; + else if (os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && os.dwMajorVersion == 4 && os.dwMinorVersion == 90) + nCurrentOS = WIN_ME; + else if (os.dwPlatformId == VER_PLATFORM_WIN32s) + nCurrentOS = WIN_31; + else + nCurrentOS = WIN_UNKNOWN; +} + +static void LoadSystemDll (LPCTSTR szModuleName, HMODULE *pHandle, BOOL bIgnoreError, const char* srcPos) +{ + wchar_t dllPath[MAX_PATH]; + + /* Load dll explictely from System32 to avoid Dll hijacking attacks*/ + if (!GetSystemDirectory(dllPath, MAX_PATH)) + StringCbCopyW(dllPath, sizeof(dllPath), L"C:\\Windows\\System32"); + + StringCbCatW(dllPath, sizeof(dllPath), L"\\"); + StringCbCatW(dllPath, sizeof(dllPath), szModuleName); + + if (((*pHandle = LoadLibrary(dllPath)) == NULL) && !bIgnoreError) + { + // This error is fatal + handleWin32Error (NULL, srcPos); + AbortProcess ("INIT_DLL"); + } +} + +/* InitApp - initialize the application, this function is called once in the + applications WinMain function, but before the main dialog has been created */ +void InitApp (HINSTANCE hInstance, wchar_t *lpszCommandLine) +{ + WNDCLASSW wc; + char langId[6]; + InitCommonControlsPtr InitCommonControlsFn = NULL; + + InitOSVersionInfo(); + + InitializeCriticalSection (&csWNetCalls); + + LoadSystemDll (L"ntmarta.dll", &hntmartadll, TRUE, SRC_POS); + LoadSystemDll (L"MPR.DLL", &hmprdll, TRUE, SRC_POS); +#ifdef SETUP + if (IsOSAtLeast (WIN_7)) + { + LoadSystemDll (L"ProfApi.DLL", &hProfApiDll, TRUE, SRC_POS); + LoadSystemDll (L"cryptbase.dll", &hcryptbasedll, TRUE, SRC_POS); + LoadSystemDll (L"sspicli.dll", &hsspiclidll, TRUE, SRC_POS); + } +#endif + LoadSystemDll (L"psapi.dll", &hpsapidll, TRUE, SRC_POS); + LoadSystemDll (L"secur32.dll", &hsecur32dll, TRUE, SRC_POS); + LoadSystemDll (L"msasn1.dll", &hmsasn1dll, TRUE, SRC_POS); + LoadSystemDll (L"Usp10.DLL", &hUsp10Dll, TRUE, SRC_POS); + LoadSystemDll (L"UXTheme.dll", &hUXThemeDll, TRUE, SRC_POS); + + LoadSystemDll (L"msls31.dll", &hMsls31, TRUE, SRC_POS); + LoadSystemDll (L"SETUPAPI.DLL", &hSetupDll, FALSE, SRC_POS); + LoadSystemDll (L"SHLWAPI.DLL", &hShlwapiDll, FALSE, SRC_POS); + + LoadSystemDll (L"userenv.dll", &hUserenvDll, TRUE, SRC_POS); + LoadSystemDll (L"rsaenh.dll", &hRsaenhDll, TRUE, SRC_POS); + +#ifdef SETUP + if (nCurrentOS < WIN_7) + { + if (nCurrentOS == WIN_XP) + { + LoadSystemDll (L"imm32.dll", &himm32dll, TRUE, SRC_POS); + LoadSystemDll (L"MSCTF.dll", &hMSCTFdll, TRUE, SRC_POS); + LoadSystemDll (L"fltlib.dll", &hfltlibdll, TRUE, SRC_POS); + LoadSystemDll (L"wbem\\framedyn.dll", &hframedyndll, TRUE, SRC_POS); + } + + if (IsOSAtLeast (WIN_VISTA)) + { + LoadSystemDll (L"netapi32.dll", &hnetapi32dll, TRUE, SRC_POS); + LoadSystemDll (L"authz.dll", &hauthzdll, TRUE, SRC_POS); + LoadSystemDll (L"xmllite.dll", &hxmllitedll, TRUE, SRC_POS); + } + } + + if (IsOSAtLeast (WIN_VISTA)) + { + LoadSystemDll (L"spp.dll", &hsppdll, TRUE, SRC_POS); + LoadSystemDll (L"vssapi.dll", &vssapidll, TRUE, SRC_POS); + LoadSystemDll (L"vsstrace.dll", &hvsstracedll, TRUE, SRC_POS); + + if (IsOSAtLeast (WIN_7)) + { + LoadSystemDll (L"CryptSP.dll", &hCryptSpDll, TRUE, SRC_POS); + + LoadSystemDll (L"cfgmgr32.dll", &hcfgmgr32dll, TRUE, SRC_POS); + LoadSystemDll (L"devobj.dll", &hdevobjdll, TRUE, SRC_POS); + LoadSystemDll (L"powrprof.dll", &hpowrprofdll, TRUE, SRC_POS); + + LoadSystemDll (L"dwmapi.dll", &hdwmapidll, TRUE, SRC_POS); + + LoadSystemDll (L"crypt32.dll", &hcrypt32dll, TRUE, SRC_POS); + + LoadSystemDll (L"bcrypt.dll", &hbcryptdll, TRUE, SRC_POS); + LoadSystemDll (L"bcryptprimitives.dll", &hbcryptprimitivesdll, TRUE, SRC_POS); + } + } +#else + LoadSystemDll (L"WINSCARD.DLL", &hwinscarddll, TRUE, SRC_POS); +#endif + + LoadSystemDll (L"COMCTL32.DLL", &hComctl32Dll, FALSE, SRC_POS); + + // call InitCommonControls function + InitCommonControlsFn = (InitCommonControlsPtr) GetProcAddress (hComctl32Dll, "InitCommonControls"); + ImageList_AddFn = (ImageList_AddPtr) GetProcAddress (hComctl32Dll, "ImageList_Add"); + ImageList_CreateFn = (ImageList_CreatePtr) GetProcAddress (hComctl32Dll, "ImageList_Create"); + + if (InitCommonControlsFn && ImageList_AddFn && ImageList_CreateFn) + { + InitCommonControlsFn(); + } + else + AbortProcess ("INIT_DLL"); + + LoadSystemDll (L"Riched20.dll", &hRichEditDll, FALSE, SRC_POS); + + // Get SetupAPI functions pointers + SetupCloseInfFileFn = (SetupCloseInfFilePtr) GetProcAddress (hSetupDll, "SetupCloseInfFile"); + SetupDiOpenClassRegKeyFn = (SetupDiOpenClassRegKeyPtr) GetProcAddress (hSetupDll, "SetupDiOpenClassRegKey"); + SetupInstallFromInfSectionWFn = (SetupInstallFromInfSectionWPtr) GetProcAddress (hSetupDll, "SetupInstallFromInfSectionW"); + SetupOpenInfFileWFn = (SetupOpenInfFileWPtr) GetProcAddress (hSetupDll, "SetupOpenInfFileW"); + + if (!SetupCloseInfFileFn || !SetupDiOpenClassRegKeyFn || !SetupInstallFromInfSectionWFn || !SetupOpenInfFileWFn) + AbortProcess ("INIT_DLL"); + + // Get SHDeleteKeyW function pointer + SHDeleteKeyWFn = (SHDeleteKeyWPtr) GetProcAddress (hShlwapiDll, "SHDeleteKeyW"); + SHStrDupWFn = (SHStrDupWPtr) GetProcAddress (hShlwapiDll, "SHStrDupW"); + if (!SHDeleteKeyWFn || !SHStrDupWFn) + AbortProcess ("INIT_DLL"); + + if (IsOSAtLeast (WIN_VISTA)) + { + /* Get ChangeWindowMessageFilter used to enable some messages bypasss UIPI (User Interface Privilege Isolation) */ + ChangeWindowMessageFilterFn = (ChangeWindowMessageFilterPtr) GetProcAddress (GetModuleHandle (L"user32.dll"), "ChangeWindowMessageFilter"); + +#ifndef SETUP + /* enable drag-n-drop when we are running elevated */ + AllowMessageInUIPI (WM_DROPFILES); + AllowMessageInUIPI (WM_COPYDATA); + AllowMessageInUIPI (WM_COPYGLOBALDATA); +#endif + } + + /* Save the instance handle for later */ + hInst = hInstance; + + SetErrorMode (SetErrorMode (0) | SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX); + CoInitialize (NULL); + +#ifndef SETUP + // Application ID + typedef HRESULT (WINAPI *SetAppId_t) (PCWSTR appID); + SetAppId_t setAppId = (SetAppId_t) GetProcAddress (GetModuleHandle (L"shell32.dll"), "SetCurrentProcessExplicitAppUserModelID"); + + if (setAppId) + setAppId (TC_APPLICATION_ID); +#endif + + // Language + langId[0] = 0; + SetPreferredLangId (ConfigReadString ("Language", "", langId, sizeof (langId))); + + if (langId[0] == 0) + { + if (IsNonInstallMode ()) + { + // only support automatic use of a language file in portable mode + // this is achieved by placing a unique language XML file in the same + // place as portable VeraCrypt binaries. + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_LANGUAGE), NULL, + (DLGPROC) LanguageDlgProc, (LPARAM) 1); + } + else + { + // when installed, force using English as default language + SetPreferredLangId ("en"); + } + } + + LoadLanguageFile (); + +#ifndef SETUP + // UAC elevation moniker cannot be used in portable mode. + // A new instance of the application must be created with elevated privileges. + if (IsNonInstallMode () && !IsAdmin () && IsUacSupported ()) + { + wchar_t modPath[MAX_PATH], newCmdLine[4096]; + WNDCLASSEXW wcex; + HWND hWnd; + + if (wcsstr (lpszCommandLine, L"/q UAC ") == lpszCommandLine) + { + Error ("UAC_INIT_ERROR", NULL); + exit (1); + } + + memset (&wcex, 0, sizeof (wcex)); + wcex.cbSize = sizeof(WNDCLASSEX); + wcex.lpfnWndProc = (WNDPROC) NonInstallUacWndProc; + wcex.hInstance = hInstance; + wcex.lpszClassName = L"VeraCrypt"; + RegisterClassExW (&wcex); + + // A small transparent window is necessary to bring the new instance to foreground + hWnd = CreateWindowExW (WS_EX_TOOLWINDOW | WS_EX_LAYERED, + L"VeraCrypt", L"VeraCrypt", 0, + GetSystemMetrics (SM_CXSCREEN)/2, + GetSystemMetrics (SM_CYSCREEN)/2, + 1, 1, NULL, NULL, hInstance, NULL); + + SetLayeredWindowAttributes (hWnd, 0, 0, LWA_ALPHA); + ShowWindow (hWnd, SW_SHOWNORMAL); + + GetModuleFileNameW (NULL, modPath, ARRAYSIZE (modPath)); + + StringCbCopyW (newCmdLine, sizeof(newCmdLine), L"/q UAC "); + StringCbCatW (newCmdLine, sizeof (newCmdLine), lpszCommandLine); + + if ((int)ShellExecuteW (hWnd, L"runas", modPath, newCmdLine, NULL, SW_SHOWNORMAL) <= 32) + exit (1); + + Sleep (2000); + exit (0); + } +#endif + + SetUnhandledExceptionFilter (ExceptionHandler); + _set_invalid_parameter_handler (InvalidParameterHandler); + + RemoteSession = GetSystemMetrics (SM_REMOTESESSION) != 0; + + // OS version check + if (CurrentOSMajor < 5) + { + MessageBoxW (NULL, GetString ("UNSUPPORTED_OS"), lpszTitle, MB_ICONSTOP); + exit (1); + } + else + { + // Service pack check & warnings about critical MS issues + switch (nCurrentOS) + { + case WIN_2000: + if (CurrentOSServicePack < 3) + Warning ("LARGE_IDE_WARNING_2K", NULL); + else + { + DWORD val = 0, size = sizeof(val); + HKEY hkey; + + if (RegOpenKeyExW (HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Services\\Atapi\\Parameters", 0, KEY_READ, &hkey) == ERROR_SUCCESS) + { + if (RegQueryValueExW (hkey, L"EnableBigLba", 0, 0, (LPBYTE) &val, &size) != ERROR_SUCCESS + || val != 1) + { + Warning ("LARGE_IDE_WARNING_2K_REGISTRY", NULL); + } + RegCloseKey (hkey); + } + } + break; + + case WIN_XP: + if (CurrentOSServicePack < 1) + { + HKEY k; + // PE environment does not report version of SP + if (RegOpenKeyExW (HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Control\\minint", 0, KEY_READ, &k) != ERROR_SUCCESS) + Warning ("LARGE_IDE_WARNING_XP", NULL); + else + RegCloseKey (k); + } + break; + } + } + + /* Get the attributes for the standard dialog class */ + if ((GetClassInfoW (hInst, WINDOWS_DIALOG_CLASS, &wc)) == 0) + { + handleWin32Error (NULL, SRC_POS); + AbortProcess ("INIT_REGISTER"); + } + +#ifndef SETUP + wc.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_TRUECRYPT_ICON)); +#else +#include "../setup/resource.h" + wc.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_SETUP)); +#endif + wc.lpszClassName = TC_DLG_CLASS; + wc.lpfnWndProc = &CustomDlgProc; + wc.hCursor = LoadCursor (NULL, IDC_ARROW); + wc.cbWndExtra = DLGWINDOWEXTRA; + + hDlgClass = RegisterClassW (&wc); + if (hDlgClass == 0) + { + handleWin32Error (NULL, SRC_POS); + AbortProcess ("INIT_REGISTER"); + } + + wc.lpszClassName = TC_SPLASH_CLASS; + wc.lpfnWndProc = &SplashDlgProc; + wc.hCursor = LoadCursor (NULL, IDC_ARROW); + wc.cbWndExtra = DLGWINDOWEXTRA; + + hSplashClass = RegisterClassW (&wc); + if (hSplashClass == 0) + { + handleWin32Error (NULL, SRC_POS); + AbortProcess ("INIT_REGISTER"); + } + + // DPI and GUI aspect ratio + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_AUXILIARY_DLG), NULL, + (DLGPROC) AuxiliaryDlgProc, (LPARAM) 1); + + InitHelpFileName (); + +#ifndef SETUP + if (!EncryptionThreadPoolStart (ReadEncryptionThreadPoolFreeCpuCountLimit())) + { + handleWin32Error (NULL, SRC_POS); + FREE_DLL (hRichEditDll); + FREE_DLL (hComctl32Dll); + FREE_DLL (hSetupDll); + FREE_DLL (hShlwapiDll); + FREE_DLL (hProfApiDll); + FREE_DLL (hUsp10Dll); + FREE_DLL (hCryptSpDll); + FREE_DLL (hUXThemeDll); + FREE_DLL (hUserenvDll); + FREE_DLL (hRsaenhDll); + FREE_DLL (himm32dll); + FREE_DLL (hMSCTFdll); + FREE_DLL (hfltlibdll); + FREE_DLL (hframedyndll); + FREE_DLL (hpsapidll); + FREE_DLL (hsecur32dll); + FREE_DLL (hnetapi32dll); + FREE_DLL (hauthzdll); + FREE_DLL (hxmllitedll); + FREE_DLL (hmprdll); + FREE_DLL (hsppdll); + FREE_DLL (vssapidll); + FREE_DLL (hvsstracedll); + FREE_DLL (hCryptSpDll); + FREE_DLL (hcfgmgr32dll); + FREE_DLL (hdevobjdll); + FREE_DLL (hpowrprofdll); + FREE_DLL (hsspiclidll); + FREE_DLL (hcryptbasedll); + FREE_DLL (hdwmapidll); + FREE_DLL (hmsasn1dll); + FREE_DLL (hcrypt32dll); + FREE_DLL (hbcryptdll); + FREE_DLL (hbcryptprimitivesdll); + FREE_DLL (hMsls31); + FREE_DLL (hntmartadll); + FREE_DLL (hwinscarddll); + exit (1); + } +#endif +} + +void FinalizeApp (void) +{ + FREE_DLL (hRichEditDll); + FREE_DLL (hComctl32Dll); + FREE_DLL (hSetupDll); + FREE_DLL (hShlwapiDll); + FREE_DLL (hProfApiDll); + FREE_DLL (hUsp10Dll); + FREE_DLL (hCryptSpDll); + FREE_DLL (hUXThemeDll); + FREE_DLL (hUserenvDll); + FREE_DLL (hRsaenhDll); + FREE_DLL (himm32dll); + FREE_DLL (hMSCTFdll); + FREE_DLL (hfltlibdll); + FREE_DLL (hframedyndll); + FREE_DLL (hpsapidll); + FREE_DLL (hsecur32dll); + FREE_DLL (hnetapi32dll); + FREE_DLL (hauthzdll); + FREE_DLL (hxmllitedll); + FREE_DLL (hmprdll); + FREE_DLL (hsppdll); + FREE_DLL (vssapidll); + FREE_DLL (hvsstracedll); + FREE_DLL (hCryptSpDll); + FREE_DLL (hcfgmgr32dll); + FREE_DLL (hdevobjdll); + FREE_DLL (hpowrprofdll); + FREE_DLL (hsspiclidll); + FREE_DLL (hcryptbasedll); + FREE_DLL (hdwmapidll); + FREE_DLL (hmsasn1dll); + FREE_DLL (hcrypt32dll); + FREE_DLL (hbcryptdll); + FREE_DLL (hbcryptprimitivesdll); + FREE_DLL (hMsls31); + FREE_DLL (hntmartadll); + FREE_DLL (hwinscarddll); +} + +void InitHelpFileName (void) +{ + wchar_t *lpszTmp; + + GetModuleFileNameW (NULL, szHelpFile, ARRAYSIZE (szHelpFile)); + lpszTmp = wcsrchr (szHelpFile, L'\\'); + if (lpszTmp) + { + wchar_t szTemp[TC_MAX_PATH]; + + ++lpszTmp; + *lpszTmp = 0; // add null terminating character to prepare for append operations + + // Primary file name + if (strcmp (GetPreferredLangId(), "en") == 0 + || strlen(GetPreferredLangId()) == 0) + { + StringCbCatW (szHelpFile, sizeof(szHelpFile), L"VeraCrypt User Guide.pdf"); + } + else + { + StringCbPrintfW (szTemp, sizeof(szTemp), L"VeraCrypt User Guide.%S.pdf", GetPreferredLangId()); + StringCbCatW (szHelpFile, sizeof(szHelpFile), szTemp); + } + + // Secondary file name (used when localized documentation is not found). + GetModuleFileNameW (NULL, szHelpFile2, ARRAYSIZE (szHelpFile2)); + lpszTmp = wcsrchr (szHelpFile2, L'\\'); + if (lpszTmp) + { + ++lpszTmp; + *lpszTmp = 0; + StringCbCatW (szHelpFile2, sizeof(szHelpFile2), L"VeraCrypt User Guide.pdf"); + } + } +} + +BOOL OpenDevice (const wchar_t *lpszPath, OPEN_TEST_STRUCT *driver, BOOL detectFilesystem, BOOL matchVolumeID, const BYTE* pbVolumeID) +{ + DWORD dwResult; + BOOL bResult; + wchar_t wszFileName[TC_MAX_PATH]; + + StringCbCopyW (wszFileName, sizeof(wszFileName), lpszPath); + + memset (driver, 0, sizeof (OPEN_TEST_STRUCT)); + memcpy (driver->wszFileName, wszFileName, sizeof (wszFileName)); + + driver->bDetectTCBootLoader = FALSE; + driver->DetectFilesystem = detectFilesystem; + driver->bMatchVolumeID = matchVolumeID; + if (matchVolumeID && pbVolumeID) + memcpy (driver->volumeID, pbVolumeID, VOLUME_ID_SIZE); + + bResult = DeviceIoControl (hDriver, TC_IOCTL_OPEN_TEST, + driver, sizeof (OPEN_TEST_STRUCT), + driver, sizeof (OPEN_TEST_STRUCT), + &dwResult, NULL); + + // check variable driver + if ( bResult + && ( (driver->bDetectTCBootLoader != TRUE && driver->bDetectTCBootLoader != FALSE) || + (driver->TCBootLoaderDetected != TRUE && driver->TCBootLoaderDetected != FALSE) || + (driver->DetectFilesystem != TRUE && driver->DetectFilesystem != FALSE) || + (driver->FilesystemDetected != TRUE && driver->FilesystemDetected != FALSE) || + (wcscmp (wszFileName, driver->wszFileName)) + ) + ) + { + return FALSE; + } + + if (bResult == FALSE) + { + dwResult = GetLastError (); + + if (dwResult == ERROR_SHARING_VIOLATION || dwResult == ERROR_NOT_READY) + { + driver->TCBootLoaderDetected = FALSE; + driver->FilesystemDetected = FALSE; + driver->VolumeIDMatched = FALSE; + return TRUE; + } + else + return FALSE; + } + + return TRUE; +} + + +// Tells the driver that it's running in portable mode +void NotifyDriverOfPortableMode (void) +{ + if (hDriver != INVALID_HANDLE_VALUE) + { + DWORD dwResult; + + DeviceIoControl (hDriver, TC_IOCTL_SET_PORTABLE_MODE_STATUS, NULL, 0, NULL, 0, &dwResult, NULL); + } +} + + +BOOL GetDriveLabel (int driveNo, wchar_t *label, int labelSize) +{ + DWORD fileSystemFlags; + wchar_t root[] = { L'A' + (wchar_t) driveNo, L':', L'\\', 0 }; + + return GetVolumeInformationW (root, label, labelSize / 2, NULL, NULL, &fileSystemFlags, NULL, 0); +} + + +/* Stores the device path of the system partition in SysPartitionDevicePath and the device path of the system drive +in SysDriveDevicePath. +IMPORTANT: As this may take a very long time if called for the first time, it should be called only before performing + a dangerous operation (such as header backup restore or formatting a supposedly non-system device) never + at WM_INITDIALOG or any other GUI events -- instead call IsSystemDevicePath (path, hwndDlg, FALSE) for + very fast preliminary GUI checks; also note that right after the "Select Device" dialog exits with an OK + return code, you can use the global flags bSysPartitionSelected and bSysDriveSelected to see if the user + selected the system partition/device. +After this function completes successfully, the results are cached for the rest of the session and repeated +executions complete very fast. Returns TRUE if successful (otherwise FALSE). */ +BOOL GetSysDevicePaths (HWND hwndDlg) +{ + if (!bCachedSysDevicePathsValid + || wcslen (SysPartitionDevicePath) <= 1 + || wcslen (SysDriveDevicePath) <= 1) + { + foreach (const HostDevice &device, GetAvailableHostDevices (false, true)) + { + if (device.ContainsSystem) + StringCchCopyW (device.IsPartition ? SysPartitionDevicePath : SysDriveDevicePath, TC_MAX_PATH, device.Path.c_str()); + } + + if (IsOSAtLeast (WIN_7)) + { + // Find extra boot partition + foreach (const HostDevice &drive, GetAvailableHostDevices (false, false)) + { + if (drive.ContainsSystem) + { + foreach (const HostDevice &sysDrivePartition, drive.Partitions) + { + if (sysDrivePartition.Bootable) + { + if (sysDrivePartition.Size <= TC_MAX_EXTRA_BOOT_PARTITION_SIZE) + ExtraBootPartitionDevicePath = sysDrivePartition.Path; + break; + } + } + break; + } + } + } + + bCachedSysDevicePathsValid = 1; + } + + return (bCachedSysDevicePathsValid + && wcslen (SysPartitionDevicePath) > 1 + && wcslen (SysDriveDevicePath) > 1); +} + +/* Determines whether the device path is the path of the system partition or of the system drive (or neither). +If bReliableRequired is TRUE, very fast execution is guaranteed, but the results cannot be relied upon. +If it's FALSE and the function is called for the first time, execution may take up to one minute but the +results are reliable. +IMPORTANT: As the execution may take a very long time if called for the first time with bReliableRequired set + to TRUE, it should be called with bReliableRequired set to TRUE only before performing a dangerous + operation (such as header backup restore or formatting a supposedly non-system device) never at + WM_INITDIALOG or any other GUI events (use IsSystemDevicePath(path, hwndDlg, FALSE) for fast + preliminary GUI checks; also note that right after the "Select Device" dialog exits with an OK + return code, you can use the global flags bSysPartitionSelected and bSysDriveSelected to see if the + user selected the system partition/device). +After this function completes successfully, the results are cached for the rest of the session, bReliableRequired +is ignored (TRUE implied), repeated executions complete very fast, and the results are always reliable. +Return codes: +1 - it is the system partition path (e.g. \Device\Harddisk0\Partition1) +2 - it is the system drive path (e.g. \Device\Harddisk0\Partition0) +3 - it is the extra boot partition path +0 - it's not the system partition/drive path +-1 - the result can't be determined, isn't reliable, or there was an error. */ +int IsSystemDevicePath (const wchar_t *path, HWND hwndDlg, BOOL bReliableRequired) +{ + if (!bCachedSysDevicePathsValid + && bReliableRequired) + { + if (!GetSysDevicePaths (hwndDlg)) + return -1; + } + + if (wcslen (SysPartitionDevicePath) <= 1 || wcslen (SysDriveDevicePath) <= 1) + return -1; + + if (!path) + return -1; + + if (wcsncmp (path, SysPartitionDevicePath, max (wcslen(path), wcslen(SysPartitionDevicePath))) == 0) + return 1; + else if (wcsncmp (path, SysDriveDevicePath, max (wcslen(path), wcslen(SysDriveDevicePath))) == 0) + return 2; + else if (ExtraBootPartitionDevicePath == path) + return 3; + + return 0; +} + + +/* Determines whether the path points to a non-system partition on the system drive. +IMPORTANT: As this may take a very long time if called for the first time, it should be called + only before performing a dangerous operation, never at WM_INITDIALOG or any other GUI events. +Return codes: +0 - it isn't a non-system partition on the system drive +1 - it's a non-system partition on the system drive +-1 - the result can't be determined, isn't reliable, or there was an error. */ +int IsNonSysPartitionOnSysDrive (const wchar_t *path) +{ + wchar_t tmpPath [TC_MAX_PATH + 1]; + int pos; + + if (!GetSysDevicePaths (MainDlg)) + return -1; + + if (wcslen (SysPartitionDevicePath) <= 1 || wcslen (SysDriveDevicePath) <= 1) + return -1; + + if (wcsncmp (path, SysPartitionDevicePath, max (wcslen(path), wcslen(SysPartitionDevicePath))) == 0 + || wcsncmp (path, SysDriveDevicePath, max (wcslen(path), wcslen(SysDriveDevicePath))) == 0) + { + // It is the system partition/drive path (it isn't a non-system partition) + return 0; + } + + memset (tmpPath, 0, sizeof (tmpPath)); + wcsncpy (tmpPath, path, ARRAYSIZE (tmpPath) - 1); + + + pos = (int) FindString ((const char*) tmpPath, (const char*) L"Partition", (int) wcslen (tmpPath) * 2, (int) wcslen (L"Partition") * 2, 0); + + if (pos < 0) + return -1; + + pos /= 2; + pos += (int) strlen ("Partition"); + + if (pos + 1 > ARRAYSIZE (tmpPath) - 1) + return -1; + + tmpPath [pos] = L'0'; + tmpPath [pos + 1] = 0; + + if (wcsncmp (tmpPath, SysDriveDevicePath, max (wcslen(tmpPath), wcslen(SysDriveDevicePath))) == 0) + { + // It is a non-system partition on the system drive + return 1; + } + else + { + // The partition is not on the system drive + return 0; + } +} + + +wstring GetSysEncryptionPretestInfo2String (void) +{ + // This huge string is divided into smaller portions to make it easier for translators to + // re-translate it when a minor modification is made to it (the whole huge string will not be + // reverted to English, so they will have to translate only a small portion of it). + return (wstring (L"\n") + + GetString ("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_1") + + GetString ("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_2") + + GetString ("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_3") + + GetString ("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_4")); +} + + +wstring GetRescueDiskHelpString (void) +{ + // This huge string is divided into smaller portions to make it easier for translators to + // re-translate it when a minor modification is made to it (the whole huge string will not be + // reverted to English, so they will have to translate only a small portion of it). + return (wstring ( + GetString ("RESCUE_DISK_HELP_PORTION_1")) + + GetString ("RESCUE_DISK_HELP_PORTION_2") + + GetString ("RESCUE_DISK_HELP_PORTION_3") + + GetString ("RESCUE_DISK_HELP_PORTION_4") + + GetString ("RESCUE_DISK_HELP_PORTION_5") + + GetString ("RESCUE_DISK_HELP_PORTION_6") + + GetString ("RESCUE_DISK_HELP_PORTION_7") + + GetString ("RESCUE_DISK_HELP_PORTION_8") + + GetString ("RESCUE_DISK_HELP_PORTION_9")); +} + + +wstring GetDecoyOsInstructionsString (void) +{ + // This huge string is divided into smaller portions to make it easier for translators to + // re-translate it when a minor modification is made to it (the whole huge string will not be + // reverted to English, so they will have to translate only a small portion of it). + return (wstring ( + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_1")) + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_2") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_3") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_4") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_5") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_6") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_7") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_8") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_9") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_10") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_11") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_12") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_13") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_14") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_15") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_16") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_17") + + GetString ("DECOY_OS_INSTRUCTIONS_PORTION_18")); +} + + +INT_PTR TextInfoDialogBox (int nID) +{ + return DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TEXT_INFO_DIALOG_BOX_DLG), MainDlg, (DLGPROC) TextInfoDialogBoxDlgProc, (LPARAM) nID); +} + +BOOL CALLBACK TextInfoDialogBoxDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + static int nID = 0; + + switch (msg) + { + case WM_INITDIALOG: + { + nID = (int) lParam; + + // Left margin for rich edit text field + SendMessage (GetDlgItem (hwndDlg, IDC_INFO_BOX_TEXT), EM_SETMARGINS, (WPARAM) EC_LEFTMARGIN, (LPARAM) CompensateXDPI (4)); + + ShowWindow(GetDlgItem(hwndDlg, IDC_PRINT), SW_HIDE); + + switch (nID) + { + case TC_TBXID_LEGAL_NOTICES: + LocalizeDialog (hwndDlg, "LEGAL_NOTICES_DLG_TITLE"); + break; + + case TC_TBXID_SYS_ENCRYPTION_PRETEST: + LocalizeDialog (hwndDlg, NULL); + ShowWindow(GetDlgItem(hwndDlg, IDC_PRINT), SW_SHOW); + break; + + case TC_TBXID_SYS_ENC_RESCUE_DISK: + LocalizeDialog (hwndDlg, NULL); + ShowWindow(GetDlgItem(hwndDlg, IDC_PRINT), SW_SHOW); + break; + + case TC_TBXID_DECOY_OS_INSTRUCTIONS: + LocalizeDialog (hwndDlg, NULL); + ShowWindow(GetDlgItem(hwndDlg, IDC_PRINT), SW_SHOW); + break; + + case TC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS: + LocalizeDialog (hwndDlg, NULL); + ShowWindow(GetDlgItem(hwndDlg, IDC_PRINT), SW_SHOW); + break; + } + + SendMessage (hwndDlg, TC_APPMSG_LOAD_TEXT_BOX_CONTENT, 0, 0); + } + return 0; + + case WM_COMMAND: + if (lw == IDOK || lw == IDCANCEL) + { + NormalCursor (); + EndDialog (hwndDlg, 0); + return 1; + } + + if (lw == IDC_PRINT) + { + switch (nID) + { + case TC_TBXID_SYS_ENCRYPTION_PRETEST: + PrintHardCopyTextUTF16 ((wchar_t *) GetSysEncryptionPretestInfo2String ().c_str(), L"Pre-Boot Troubleshooting", GetSysEncryptionPretestInfo2String ().length () * 2); + break; + + case TC_TBXID_SYS_ENC_RESCUE_DISK: + PrintHardCopyTextUTF16 ((wchar_t *) GetRescueDiskHelpString ().c_str(), L"VeraCrypt Rescue Disk Help", GetRescueDiskHelpString ().length () * 2); + break; + + case TC_TBXID_DECOY_OS_INSTRUCTIONS: + PrintHardCopyTextUTF16 ((wchar_t *) GetDecoyOsInstructionsString ().c_str(), L"How to Create Decoy OS", GetDecoyOsInstructionsString ().length () * 2); + break; + + case TC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS: + PrintHardCopyTextUTF16 (GetString ("EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS"), L"How to Remove Extra Boot Partition", wcslen (GetString ("EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS")) * 2); + break; + } + return 1; + } + + return 0; + + case TC_APPMSG_LOAD_TEXT_BOX_CONTENT: + { + char *r = NULL; + + switch (nID) + { + case TC_TBXID_LEGAL_NOTICES: + LocalizeDialog (hwndDlg, "LEGAL_NOTICES_DLG_TITLE"); + r = GetLegalNotices (); + if (r != NULL) + { + SETTEXTEX TextInfo = {0}; + + TextInfo.flags = ST_SELECTION; + TextInfo.codepage = CP_ACP; + + SendMessage(GetDlgItem (hwndDlg, IDC_INFO_BOX_TEXT), EM_SETTEXTEX, (WPARAM)&TextInfo, (LPARAM)r); + free (r); + } + break; + + case TC_TBXID_SYS_ENCRYPTION_PRETEST: + LocalizeDialog (hwndDlg, NULL); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_INFO_BOX_TEXT), (wchar_t *) GetSysEncryptionPretestInfo2String ().c_str()); + break; + + case TC_TBXID_SYS_ENC_RESCUE_DISK: + LocalizeDialog (hwndDlg, NULL); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_INFO_BOX_TEXT), (wchar_t *) GetRescueDiskHelpString ().c_str()); + break; + + case TC_TBXID_DECOY_OS_INSTRUCTIONS: + LocalizeDialog (hwndDlg, NULL); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_INFO_BOX_TEXT), (wchar_t *) GetDecoyOsInstructionsString ().c_str()); + break; + + case TC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS: + LocalizeDialog (hwndDlg, NULL); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_INFO_BOX_TEXT), GetString ("EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS")); + break; + } + } + return 1; + + case WM_CLOSE: + NormalCursor (); + EndDialog (hwndDlg, 0); + return 1; + } + + return 0; +} + + +char * GetLegalNotices () +{ + static char *resource; + static DWORD size; + char *buf = NULL; + + if (resource == NULL) + resource = (char *) MapResource (L"Text", IDR_LICENSE, &size); + + if (resource != NULL) + { + buf = (char *) malloc (size + 1); + if (buf != NULL) + { + memcpy (buf, resource, size); + buf[size] = 0; + } + } + + return buf; +} + + +BOOL CALLBACK RawDevicesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + static wchar_t *lpszFileName; // This is actually a pointer to a GLOBAL array + static vector devices; + static map itemToDeviceMap; + + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + LVCOLUMNW LvCol; + HWND hList = GetDlgItem (hwndDlg, IDC_DEVICELIST); + RawDevicesDlgParam* pDlgParam = (RawDevicesDlgParam *) lParam; + + LocalizeDialog (hwndDlg, "IDD_RAWDEVICES_DLG"); + + SendMessage (hList,LVM_SETEXTENDEDLISTVIEWSTYLE,0, + LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_TWOCLICKACTIVATE|LVS_EX_LABELTIP + ); + + memset (&LvCol,0,sizeof(LvCol)); + LvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; + LvCol.pszText = GetString ("DEVICE"); + LvCol.cx = CompensateXDPI (186); + LvCol.fmt = LVCFMT_LEFT; + SendMessage (hList,LVM_INSERTCOLUMNW,0,(LPARAM)&LvCol); + + LvCol.pszText = GetString ("DRIVE"); + LvCol.cx = CompensateXDPI (38); + LvCol.fmt = LVCFMT_LEFT; + SendMessage (hList,LVM_INSERTCOLUMNW,1,(LPARAM)&LvCol); + + LvCol.pszText = GetString ("SIZE"); + LvCol.cx = CompensateXDPI (64); + LvCol.fmt = LVCFMT_RIGHT; + SendMessage (hList,LVM_INSERTCOLUMNW,2,(LPARAM)&LvCol); + + LvCol.pszText = GetString ("LABEL"); + LvCol.cx = CompensateXDPI (128); + LvCol.fmt = LVCFMT_LEFT; + SendMessage (hList,LVM_INSERTCOLUMNW,3,(LPARAM)&LvCol); + + devices.clear(); + itemToDeviceMap.clear(); + + if (pDlgParam->devices.empty()) + { + WaitCursor(); + devices = GetAvailableHostDevices (false, true, false); + NormalCursor(); + } + else + devices = pDlgParam->devices; + + if (devices.empty()) + { + MessageBoxW (hwndDlg, GetString ("RAWDEVICES"), lpszTitle, ICON_HAND); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + int line = 1; + LVITEM item; + memset (&item, 0, sizeof (item)); + item.mask = LVIF_TEXT; + + foreach (const HostDevice &device, devices) + { + item.iSubItem = 1; + + if (device.ContainsSystem) + { + if (device.IsPartition) + StringCbCopyW (SysPartitionDevicePath, sizeof (SysPartitionDevicePath), device.Path.c_str()); + else + StringCbCopyW (SysDriveDevicePath, sizeof (SysDriveDevicePath), device.Path.c_str()); + } + + // Path + if (!device.IsPartition || device.DynamicVolume) + { + if (!device.Floppy && (device.Size == 0) + && (device.IsPartition || device.Partitions.empty() || device.Partitions[0].Size == 0) + ) + continue; + + if (line > 1) + { + ListItemAdd (hList, item.iItem, L""); + item.iItem = line++; + } + + if (device.Floppy || device.DynamicVolume) + { + ListItemAdd (hList, item.iItem, (wchar_t *) device.Path.c_str()); + } + else + { + wchar_t s[1024]; + if (device.Removable) + StringCbPrintfW (s, sizeof(s), L"%s %d", GetString ("REMOVABLE_DISK"), device.SystemNumber); + else + StringCbPrintfW (s, sizeof(s), L"%s %d", GetString ("HARDDISK"), device.SystemNumber); + + if (!device.Partitions.empty()) + StringCbCatW (s, sizeof(s), L":"); + + ListItemAdd (hList, item.iItem, s); + } + } + else + { + ListItemAdd (hList, item.iItem, (wchar_t *) device.Path.c_str()); + } + + itemToDeviceMap[item.iItem] = device; + + // Size + if (device.Size != 0) + { + wchar_t size[100] = { 0 }; + GetSizeString (device.Size, size, sizeof(size)); + ListSubItemSet (hList, item.iItem, 2, size); + } + + // Mount point + if (!device.MountPoint.empty()) + ListSubItemSet (hList, item.iItem, 1, (wchar_t *) device.MountPoint.c_str()); + + // Label + if (!device.Name.empty()) + ListSubItemSet (hList, item.iItem, 3, (wchar_t *) device.Name.c_str()); +#ifdef TCMOUNT + else + { + bool useInExplorer = false; + wstring favoriteLabel = GetFavoriteVolumeLabel (device.Path, useInExplorer); + if (!favoriteLabel.empty()) + ListSubItemSet (hList, item.iItem, 3, (wchar_t *) favoriteLabel.c_str()); + } +#endif + + item.iItem = line++; + } + + SendMessageW(hList, LVM_SETCOLUMNWIDTH, 0, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); + SendMessageW(hList, LVM_SETCOLUMNWIDTH, 1, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); + SendMessageW(hList, LVM_SETCOLUMNWIDTH, 2, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); + SendMessageW(hList, LVM_SETCOLUMNWIDTH, 3, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); + + lpszFileName = pDlgParam->pszFileName; + +#ifdef VOLFORMAT + EnableWindow (GetDlgItem (hwndDlg, IDOK), FALSE); +#endif + return 1; + } + + case WM_COMMAND: + case WM_NOTIFY: + // catch non-device line selected + if (msg == WM_NOTIFY && ((LPNMHDR) lParam)->code == LVN_ITEMCHANGED && (((LPNMLISTVIEW) lParam)->uNewState & LVIS_FOCUSED )) + { + BOOL bEnableOkButton = FALSE; + LVITEM LvItem; + memset(&LvItem,0,sizeof(LvItem)); + LvItem.mask = LVIF_TEXT | LVIF_PARAM; + LvItem.iItem = ((LPNMLISTVIEW) lParam)->iItem; + LvItem.pszText = lpszFileName; + LvItem.cchTextMax = TC_MAX_PATH; + + lpszFileName[0] = 0; + SendMessage (GetDlgItem (hwndDlg, IDC_DEVICELIST), LVM_GETITEM, LvItem.iItem, (LPARAM) &LvItem); + if (lpszFileName[0] != 0 && lpszFileName[0] != ' ') + { + bEnableOkButton = TRUE; +#ifdef VOLFORMAT + if ( bInPlaceEncNonSysResumed && (WizardMode == WIZARD_MODE_NONSYS_DEVICE) + && LvItem.iItem != -1 && itemToDeviceMap.find (LvItem.iItem) != itemToDeviceMap.end() + ) + { + const HostDevice selectedDevice = itemToDeviceMap[LvItem.iItem]; + if (selectedDevice.ContainsSystem) + { + bEnableOkButton = FALSE; + } + } +#endif + } + EnableWindow (GetDlgItem ((HWND) hwndDlg, IDOK), bEnableOkButton); + + return 1; + } + + if (msg == WM_COMMAND && lw == IDOK || msg == WM_NOTIFY && ((NMHDR *)lParam)->code == LVN_ITEMACTIVATE) + { + int selectedItem = ListView_GetSelectionMark (GetDlgItem (hwndDlg, IDC_DEVICELIST)); + + if (selectedItem == -1 || itemToDeviceMap.find (selectedItem) == itemToDeviceMap.end()) + return 1; // non-device line selected + + const HostDevice selectedDevice = itemToDeviceMap[selectedItem]; + StringCchCopyW (lpszFileName, TC_MAX_PATH, selectedDevice.Path.c_str()); + +#ifdef VOLFORMAT + if (selectedDevice.ContainsSystem && selectedDevice.IsPartition) + { + if (WizardMode != WIZARD_MODE_SYS_DEVICE) + { + if (bInPlaceEncNonSysResumed && (WizardMode == WIZARD_MODE_NONSYS_DEVICE)) + { + // disable selection + return 1; + } + + if (AskYesNo ("CONFIRM_SYSTEM_ENCRYPTION_MODE", hwndDlg) == IDNO) + { + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + bSysPartitionSelected = TRUE; + bSysDriveSelected = FALSE; + lpszFileName[0] = 0; + SwitchWizardToSysEncMode (); + + NormalCursor (); + EndDialog (hwndDlg, IDOK); + return 1; + } + else + { + // This should never be the case because the Select Device dialog is not available in this wizard mode + bSysPartitionSelected = TRUE; + bSysDriveSelected = FALSE; + lpszFileName[0] = 0; + SwitchWizardToSysEncMode (); + NormalCursor (); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + } + + if (!(selectedDevice.ContainsSystem && !selectedDevice.IsPartition)) + { + if (bWarnDeviceFormatAdvanced + && !bHiddenVolDirect + && AskWarnNoYes("FORMAT_DEVICE_FOR_ADVANCED_ONLY", hwndDlg) == IDNO) + { + if (AskNoYes("CONFIRM_CHANGE_WIZARD_MODE_TO_FILE_CONTAINER", hwndDlg) == IDYES) + { + SwitchWizardToFileContainerMode (); + } + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + if (!bHiddenVolDirect) + bWarnDeviceFormatAdvanced = FALSE; + } + +#else // #ifdef VOLFORMAT + + bSysPartitionSelected = (selectedDevice.ContainsSystem && selectedDevice.IsPartition); + bSysDriveSelected = FALSE; + +#endif // #ifdef VOLFORMAT + + if (!selectedDevice.IsPartition && !selectedDevice.Floppy) + { + // Whole device selected + +#ifdef VOLFORMAT + if (selectedDevice.ContainsSystem && !selectedDevice.IsPartition) + { + if (WizardMode != WIZARD_MODE_SYS_DEVICE) + { + if (bInPlaceEncNonSysResumed && (WizardMode == WIZARD_MODE_NONSYS_DEVICE)) + { + // disable selection + return 1; + } + + if (AskYesNo ("CONFIRM_SYSTEM_ENCRYPTION_MODE", hwndDlg) == IDNO) + { + NormalCursor (); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + bSysDriveSelected = TRUE; + bSysPartitionSelected = FALSE; + lpszFileName[0] = 0; + SwitchWizardToSysEncMode (); + + NormalCursor (); + EndDialog (hwndDlg, IDOK); + return 1; + } + else + { + // This should never be the case because the Select Device dialog is not available in this wizard mode + bSysDriveSelected = TRUE; + bSysPartitionSelected = FALSE; + lpszFileName[0] = 0; + SwitchWizardToSysEncMode (); + NormalCursor (); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + } + + // Disallow format if the device contains partitions, but not if the partition is virtual or system + if (!selectedDevice.IsVirtualPartition + && !bHiddenVolDirect) + { + if (!selectedDevice.Partitions.empty()) + { + EnableWindow (GetDlgItem (hwndDlg, IDOK), FALSE); + Error ("DEVICE_PARTITIONS_ERR_W_INPLACE_ENC_NOTE", hwndDlg); + return 1; + } + + if (AskWarnNoYes ("WHOLE_NONSYS_DEVICE_ENC_CONFIRM", hwndDlg) == IDNO) + return 1; + } +#else // #ifdef VOLFORMAT + + bSysDriveSelected = (selectedDevice.ContainsSystem && !selectedDevice.IsPartition); + bSysPartitionSelected = FALSE; + +#endif // #ifdef VOLFORMAT + } + else + bSysDriveSelected = FALSE; + +#ifdef VOLFORMAT + bRemovableHostDevice = selectedDevice.Removable; +#endif + NormalCursor (); + EndDialog (hwndDlg, IDOK); + return 1; + } + + if ((msg == WM_COMMAND) && (lw == IDCANCEL)) + { + NormalCursor (); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + return 0; + } + return 0; +} + + +BOOL DoDriverInstall (HWND hwndDlg) +{ +#ifdef SETUP + if (SystemEncryptionUpdate) + return TRUE; +#endif + + SC_HANDLE hManager, hService = NULL; + BOOL bOK = FALSE, bRet; + + hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); + if (hManager == NULL) + goto error; + +#ifdef SETUP + StatusMessage (hwndDlg, "INSTALLING_DRIVER"); +#endif + + hService = CreateService (hManager, L"veracrypt", L"veracrypt", + SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_SYSTEM_START, SERVICE_ERROR_NORMAL, + L"System32\\drivers\\veracrypt.sys", + NULL, NULL, NULL, NULL, NULL); + + if (hService == NULL) + goto error; + else + CloseServiceHandle (hService); + + hService = OpenService (hManager, L"veracrypt", SERVICE_ALL_ACCESS); + if (hService == NULL) + goto error; + +#ifdef SETUP + StatusMessage (hwndDlg, "STARTING_DRIVER"); +#endif + + bRet = StartService (hService, 0, NULL); + if (bRet == FALSE) + goto error; + + bOK = TRUE; + +error: + if (bOK == FALSE && GetLastError () != ERROR_SERVICE_ALREADY_RUNNING) + { + handleWin32Error (hwndDlg, SRC_POS); + MessageBoxW (hwndDlg, GetString ("DRIVER_INSTALL_FAILED"), lpszTitle, MB_ICONHAND); + } + else + bOK = TRUE; + + if (hService != NULL) + CloseServiceHandle (hService); + + if (hManager != NULL) + CloseServiceHandle (hManager); + + return bOK; +} + + +// Install and start driver service and mark it for removal (non-install mode) +static int DriverLoad () +{ + HANDLE file; + WIN32_FIND_DATA find; + SC_HANDLE hManager, hService = NULL; + wchar_t driverPath[TC_MAX_PATH*2]; + BOOL res; + wchar_t *tmp; + DWORD startType; + + if (ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", L"Start", &startType) && startType == SERVICE_BOOT_START) + return ERR_PARAMETER_INCORRECT; + + GetModuleFileName (NULL, driverPath, ARRAYSIZE (driverPath)); + tmp = wcsrchr (driverPath, L'\\'); + if (!tmp) + { + driverPath[0] = L'.'; + driverPath[1] = 0; + } + else + *tmp = 0; + + StringCbCatW (driverPath, sizeof(driverPath), !Is64BitOs () ? L"\\veracrypt.sys" : L"\\veracrypt-x64.sys"); + + file = FindFirstFile (driverPath, &find); + + if (file == INVALID_HANDLE_VALUE) + { + MessageBoxW (0, GetString ("DRIVER_NOT_FOUND"), lpszTitle, ICON_HAND); + return ERR_DONT_REPORT; + } + + FindClose (file); + + hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); + if (hManager == NULL) + { + if (GetLastError () == ERROR_ACCESS_DENIED) + { + MessageBoxW (0, GetString ("ADMIN_PRIVILEGES_DRIVER"), lpszTitle, ICON_HAND); + return ERR_DONT_REPORT; + } + + return ERR_OS_ERROR; + } + + hService = OpenService (hManager, L"veracrypt", SERVICE_ALL_ACCESS); + if (hService != NULL) + { + // Remove stale service (driver is not loaded but service exists) + DeleteService (hService); + CloseServiceHandle (hService); + Sleep (500); + } + + hService = CreateService (hManager, L"veracrypt", L"veracrypt", + SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, + driverPath, NULL, NULL, NULL, NULL, NULL); + + if (hService == NULL) + { + CloseServiceHandle (hManager); + return ERR_OS_ERROR; + } + + res = StartService (hService, 0, NULL); + DeleteService (hService); + + CloseServiceHandle (hManager); + CloseServiceHandle (hService); + + return !res ? ERR_OS_ERROR : ERROR_SUCCESS; +} + + +BOOL DriverUnload () +{ + MOUNT_LIST_STRUCT driver; + int refCount; + int volumesMounted; + DWORD dwResult; + BOOL bResult; + + SC_HANDLE hManager, hService = NULL; + BOOL bRet; + SERVICE_STATUS status; + int x; + BOOL driverUnloaded = FALSE; + + if (hDriver == INVALID_HANDLE_VALUE) + return TRUE; + + try + { + if (BootEncryption (NULL).GetStatus().DeviceFilterActive) + return FALSE; + } + catch (...) { } + + // Test for mounted volumes + bResult = DeviceIoControl (hDriver, TC_IOCTL_IS_ANY_VOLUME_MOUNTED, NULL, 0, &volumesMounted, sizeof (volumesMounted), &dwResult, NULL); + + if (!bResult) + { + bResult = DeviceIoControl (hDriver, TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES, NULL, 0, &driver, sizeof (driver), &dwResult, NULL); + if (bResult) + volumesMounted = driver.ulMountedDrives; + } + + if (bResult) + { + if (volumesMounted != 0) + return FALSE; + } + else + return TRUE; + + // Test for any applications attached to driver + refCount = GetDriverRefCount (); + + if (refCount > 1) + return FALSE; + + CloseHandle (hDriver); + hDriver = INVALID_HANDLE_VALUE; + + // Stop driver service + + hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); + if (hManager == NULL) + goto error; + + hService = OpenService (hManager, L"veracrypt", SERVICE_ALL_ACCESS); + if (hService == NULL) + goto error; + + bRet = QueryServiceStatus (hService, &status); + if (bRet != TRUE) + goto error; + + if (status.dwCurrentState != SERVICE_STOPPED) + { + ControlService (hService, SERVICE_CONTROL_STOP, &status); + + for (x = 0; x < 10; x++) + { + bRet = QueryServiceStatus (hService, &status); + if (bRet != TRUE) + goto error; + + if (status.dwCurrentState == SERVICE_STOPPED) + { + driverUnloaded = TRUE; + break; + } + + Sleep (200); + } + } + else + driverUnloaded = TRUE; + +error: + if (hService != NULL) + CloseServiceHandle (hService); + + if (hManager != NULL) + CloseServiceHandle (hManager); + + if (driverUnloaded) + { + hDriver = INVALID_HANDLE_VALUE; + return TRUE; + } + + return FALSE; +} + + +int DriverAttach (void) +{ + /* Try to open a handle to the device driver. It will be closed later. */ + +#ifndef SETUP + + int nLoadRetryCount = 0; +start: + +#endif + + hDriver = CreateFile (WIN32_ROOT_PREFIX, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (hDriver == INVALID_HANDLE_VALUE) + { +#ifndef SETUP + + LoadSysEncSettings (); + + if (!CreateDriverSetupMutex ()) + { + // Another instance is already attempting to install, register or start the driver + + while (!CreateDriverSetupMutex ()) + { + Sleep (100); // Wait until the other instance finishes + } + + // Try to open a handle to the driver again (keep the mutex in case the other instance failed) + goto start; + } + else + { + // No other instance is currently attempting to install, register or start the driver + + if (SystemEncryptionStatus != SYSENC_STATUS_NONE) + { + // This is an inconsistent state. The config file indicates system encryption should be + // active, but the driver is not running. This may happen e.g. when the pretest fails and + // the user selects "Last Known Good Configuration" from the Windows boot menu. + // To fix this, we're going to reinstall the driver, start it, and register it for boot. + + if (DoDriverInstall (NULL)) + { + Sleep (1000); + hDriver = CreateFile (WIN32_ROOT_PREFIX, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + try + { + BootEncryption bootEnc (NULL); + bootEnc.RegisterBootDriver (bootEnc.GetHiddenOSCreationPhase() != TC_HIDDEN_OS_CREATION_PHASE_NONE ? true : false); + } + catch (Exception &e) + { + e.Show (NULL); + } + } + + CloseDriverSetupMutex (); + } + else + { + // Attempt to load the driver (non-install/portable mode) +load: + BOOL res = DriverLoad (); + + CloseDriverSetupMutex (); + + if (res != ERROR_SUCCESS) + return res; + + bPortableModeConfirmed = TRUE; + + if (hDriver != INVALID_HANDLE_VALUE) + CloseHandle (hDriver); + hDriver = CreateFile (WIN32_ROOT_PREFIX, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + } + + if (bPortableModeConfirmed) + NotifyDriverOfPortableMode (); + } + +#endif // #ifndef SETUP + + if (hDriver == INVALID_HANDLE_VALUE) + return ERR_OS_ERROR; + } + + CloseDriverSetupMutex (); + + if (hDriver != INVALID_HANDLE_VALUE) + { + DWORD dwResult; + + BOOL bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVER_VERSION, NULL, 0, &DriverVersion, sizeof (DriverVersion), &dwResult, NULL); + + if (!bResult) + bResult = DeviceIoControl (hDriver, TC_IOCTL_LEGACY_GET_DRIVER_VERSION, NULL, 0, &DriverVersion, sizeof (DriverVersion), &dwResult, NULL); + +#ifndef SETUP // Don't check version during setup to allow removal of another version + if (bResult == FALSE) + { + return ERR_OS_ERROR; + } + else if (DriverVersion != VERSION_NUM) + { + // Unload an incompatbile version of the driver loaded in non-install mode and load the required version + if (IsNonInstallMode () && CreateDriverSetupMutex () && DriverUnload () && nLoadRetryCount++ < 3) + goto load; + + CloseDriverSetupMutex (); + CloseHandle (hDriver); + hDriver = INVALID_HANDLE_VALUE; + return ERR_DRIVER_VERSION; + } +#else + if (!bResult) + DriverVersion = 0; +#endif + } + + return 0; +} + + +void ResetCurrentDirectory () +{ + wchar_t p[MAX_PATH]; + if (!IsNonInstallMode () && SHGetFolderPath (NULL, CSIDL_PROFILE, NULL, 0, p) == ERROR_SUCCESS) + { + SetCurrentDirectory (p); + } + else + { + GetModPath (p, ARRAYSIZE (p)); + SetCurrentDirectory (p); + } +} + + +BOOL BrowseFiles (HWND hwndDlg, char *stringId, wchar_t *lpszFileName, BOOL keepHistory, BOOL saveMode, wchar_t *browseFilter) +{ + return BrowseFilesInDir (hwndDlg, stringId, NULL, lpszFileName, keepHistory, saveMode, browseFilter); +} + + +BOOL BrowseFilesInDir (HWND hwndDlg, char *stringId, wchar_t *initialDir, wchar_t *lpszFileName, BOOL keepHistory, BOOL saveMode, wchar_t *browseFilter, const wchar_t *initialFileName, const wchar_t *defaultExtension) +{ + OPENFILENAMEW ofn; + wchar_t file[TC_MAX_PATH] = { 0 }; + wchar_t filter[1024]; + BOOL status = FALSE; + + CoInitialize (NULL); + + ZeroMemory (&ofn, sizeof (ofn)); + *lpszFileName = 0; + + if (initialDir) + { + ofn.lpstrInitialDir = initialDir; + } + + if (initialFileName) + StringCchCopyW (file, array_capacity (file), initialFileName); + + ofn.lStructSize = sizeof (ofn); + ofn.hwndOwner = hwndDlg; + + StringCbPrintfW (filter, sizeof(filter), L"%ls (*.*)%c*.*%c%ls (*.hc)%c*.hc%c%c", + GetString ("ALL_FILES"), 0, 0, GetString ("TC_VOLUMES"), 0, 0, 0); + ofn.lpstrFilter = browseFilter ? browseFilter : filter; + ofn.nFilterIndex = 1; + ofn.lpstrFile = file; + ofn.nMaxFile = sizeof (file) / sizeof (file[0]); + ofn.lpstrTitle = GetString (stringId); + ofn.lpstrDefExt = defaultExtension; + ofn.Flags = OFN_HIDEREADONLY + | OFN_PATHMUSTEXIST + | (keepHistory ? 0 : OFN_DONTADDTORECENT) + | (saveMode ? OFN_OVERWRITEPROMPT : 0); + + if (!keepHistory) + CleanLastVisitedMRU (); + + SystemFileSelectorCallerThreadId = GetCurrentThreadId(); + SystemFileSelectorCallPending = TRUE; + + if (!saveMode) + { + if (!GetOpenFileNameW (&ofn)) + goto ret; + } + else + { + if (!GetSaveFileNameW (&ofn)) + goto ret; + } + + SystemFileSelectorCallPending = FALSE; + + StringCchCopyW (lpszFileName, MAX_PATH, file); + + if (!keepHistory) + CleanLastVisitedMRU (); + + status = TRUE; + +ret: + SystemFileSelectorCallPending = FALSE; + ResetCurrentDirectory(); + CoUninitialize(); + + return status; +} + + +static wchar_t SelectMultipleFilesPath[131072]; +static int SelectMultipleFilesOffset; + +BOOL SelectMultipleFiles (HWND hwndDlg, const char *stringId, wchar_t *lpszFileName, size_t cbFileName,BOOL keepHistory) +{ + OPENFILENAMEW ofn; + wchar_t filter[1024]; + BOOL status = FALSE; + + CoInitialize (NULL); + + ZeroMemory (&ofn, sizeof (ofn)); + + SelectMultipleFilesPath[0] = 0; + *lpszFileName = 0; + ofn.lStructSize = sizeof (ofn); + ofn.hwndOwner = hwndDlg; + StringCbPrintfW (filter, sizeof(filter), L"%ls (*.*)%c*.*%c%ls (*.hc)%c*.hc%c%c", + GetString ("ALL_FILES"), 0, 0, GetString ("TC_VOLUMES"), 0, 0, 0); + ofn.lpstrFilter = filter; + ofn.nFilterIndex = 1; + ofn.lpstrFile = SelectMultipleFilesPath; + ofn.nMaxFile = 0xffff * 2; // The size must not exceed 0xffff*2 due to a bug in Windows 2000 and XP SP1 + ofn.lpstrTitle = GetString (stringId); + ofn.Flags = OFN_HIDEREADONLY + | OFN_EXPLORER + | OFN_PATHMUSTEXIST + | OFN_ALLOWMULTISELECT + | (keepHistory ? 0 : OFN_DONTADDTORECENT); + + if (!keepHistory) + CleanLastVisitedMRU (); + + SystemFileSelectorCallerThreadId = GetCurrentThreadId(); + SystemFileSelectorCallPending = TRUE; + + if (!GetOpenFileNameW (&ofn)) + goto ret; + + SystemFileSelectorCallPending = FALSE; + + if (SelectMultipleFilesPath[ofn.nFileOffset - 1] != 0) + { + // Single file selected + StringCbCopyW (lpszFileName, cbFileName, SelectMultipleFilesPath); + SelectMultipleFilesOffset = 0; + SecureZeroMemory (SelectMultipleFilesPath, sizeof (SelectMultipleFilesPath)); + } + else + { + // Multiple files selected + SelectMultipleFilesOffset = ofn.nFileOffset; + SelectMultipleFilesNext (lpszFileName, cbFileName); + } + + if (!keepHistory) + CleanLastVisitedMRU (); + + status = TRUE; + +ret: + SystemFileSelectorCallPending = FALSE; + ResetCurrentDirectory(); + CoUninitialize(); + + return status; +} + + +BOOL SelectMultipleFilesNext (wchar_t *lpszFileName, size_t cbFileName) +{ + if (SelectMultipleFilesOffset == 0) + return FALSE; + + StringCbCopyW (lpszFileName, cbFileName,SelectMultipleFilesPath); + lpszFileName[TC_MAX_PATH - 1] = 0; + + if (lpszFileName[wcslen (lpszFileName) - 1] != L'\\') + StringCbCatW (lpszFileName, cbFileName,L"\\"); + + StringCbCatW (lpszFileName, cbFileName,SelectMultipleFilesPath + SelectMultipleFilesOffset); + + SelectMultipleFilesOffset += (int) wcslen (SelectMultipleFilesPath + SelectMultipleFilesOffset) + 1; + if (SelectMultipleFilesPath[SelectMultipleFilesOffset] == 0) + { + SelectMultipleFilesOffset = 0; + SecureZeroMemory (SelectMultipleFilesPath, sizeof (SelectMultipleFilesPath)); + } + + return TRUE; +} + + +static int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lp, LPARAM pData) +{ + switch(uMsg) { + case BFFM_INITIALIZED: + { + /* WParam is TRUE since we are passing a path. + It would be FALSE if we were passing a pidl. */ + SendMessageW (hwnd,BFFM_SETSELECTION,TRUE,(LPARAM)pData); + break; + } + + case BFFM_SELCHANGED: + { + wchar_t szDir[TC_MAX_PATH]; + + /* Set the status window to the currently selected path. */ + if (SHGetPathFromIDList((LPITEMIDLIST) lp ,szDir)) + { + SendMessage (hwnd,BFFM_SETSTATUSTEXT,0,(LPARAM)szDir); + } + break; + } + + default: + break; + } + + return 0; +} + + +BOOL BrowseDirectories (HWND hwndDlg, char *lpszTitle, wchar_t *dirName) +{ + BROWSEINFOW bi; + LPITEMIDLIST pidl; + LPMALLOC pMalloc; + BOOL bOK = FALSE; + + CoInitialize (NULL); + + if (SUCCEEDED (SHGetMalloc (&pMalloc))) + { + ZeroMemory (&bi, sizeof(bi)); + bi.hwndOwner = hwndDlg; + bi.pszDisplayName = 0; + bi.lpszTitle = GetString (lpszTitle); + bi.pidlRoot = 0; + bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT; + bi.lpfn = BrowseCallbackProc; + bi.lParam = (LPARAM)dirName; + + pidl = SHBrowseForFolderW (&bi); + if (pidl != NULL) + { + if (SHGetPathFromIDList(pidl, dirName)) + { + bOK = TRUE; + } + + pMalloc->Free (pidl); + pMalloc->Release(); + } + } + + CoUninitialize(); + + return bOK; +} + + +std::wstring GetWrongPasswordErrorMessage (HWND hwndDlg) +{ + WCHAR szTmp[8192]; + + StringCbPrintfW (szTmp, sizeof(szTmp), GetString (KeyFilesEnable ? "PASSWORD_OR_KEYFILE_WRONG" : "PASSWORD_WRONG")); + if (CheckCapsLock (hwndDlg, TRUE)) + StringCbCatW (szTmp, sizeof(szTmp), GetString ("PASSWORD_WRONG_CAPSLOCK_ON")); + +#ifdef TCMOUNT + wchar_t szDevicePath [TC_MAX_PATH+1] = {0}; + GetWindowText (GetDlgItem (MainDlg, IDC_VOLUME), szDevicePath, ARRAYSIZE (szDevicePath)); + + if (TCBootLoaderOnInactiveSysEncDrive (szDevicePath)) + { + StringCbPrintfW (szTmp, sizeof(szTmp), GetString (KeyFilesEnable ? "PASSWORD_OR_KEYFILE_OR_MODE_WRONG" : "PASSWORD_OR_MODE_WRONG")); + + if (CheckCapsLock (hwndDlg, TRUE)) + StringCbCatW (szTmp, sizeof(szTmp), GetString ("PASSWORD_WRONG_CAPSLOCK_ON")); + + StringCbCatW (szTmp, sizeof(szTmp), GetString ("SYSENC_MOUNT_WITHOUT_PBA_NOTE")); + } +#endif + + wstring msg = szTmp; + +#ifdef TCMOUNT + if (KeyFilesEnable && HiddenFilesPresentInKeyfilePath) + { + msg += GetString ("HIDDEN_FILES_PRESENT_IN_KEYFILE_PATH"); + HiddenFilesPresentInKeyfilePath = FALSE; + } +#endif + + return msg; +} + + +void handleError (HWND hwndDlg, int code, const char* srcPos) +{ + WCHAR szTmp[4096]; + + if (Silent) return; + + switch (code & 0x0000FFFF) + { + case ERR_OS_ERROR: + handleWin32Error (hwndDlg, srcPos); + break; + case ERR_OUTOFMEMORY: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("OUTOFMEMORY"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + + case ERR_PASSWORD_WRONG: + MessageBoxW (hwndDlg, AppendSrcPos (GetWrongPasswordErrorMessage (hwndDlg).c_str(), srcPos).c_str(), lpszTitle, MB_ICONWARNING); + break; + + case ERR_DRIVE_NOT_FOUND: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("NOT_FOUND"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_FILES_OPEN: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("OPENFILES_DRIVER"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_FILES_OPEN_LOCK: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("OPENFILES_LOCK"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_VOL_SIZE_WRONG: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("VOL_SIZE_WRONG"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_COMPRESSION_NOT_SUPPORTED: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("COMPRESSION_NOT_SUPPORTED"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_PASSWORD_CHANGE_VOL_TYPE: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("WRONG_VOL_TYPE"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_VOL_SEEKING: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("VOL_SEEKING"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_CIPHER_INIT_FAILURE: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("ERR_CIPHER_INIT_FAILURE"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_CIPHER_INIT_WEAK_KEY: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("ERR_CIPHER_INIT_WEAK_KEY"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_VOL_ALREADY_MOUNTED: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("VOL_ALREADY_MOUNTED"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_FILE_OPEN_FAILED: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("FILE_OPEN_FAILED"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_VOL_MOUNT_FAILED: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("VOL_MOUNT_FAILED"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_NO_FREE_DRIVES: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("NO_FREE_DRIVES"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + case ERR_ACCESS_DENIED: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("ACCESS_DENIED"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + + case ERR_DRIVER_VERSION: + Error ("DRIVER_VERSION", hwndDlg); + break; + + case ERR_NEW_VERSION_REQUIRED: + MessageBoxW (hwndDlg, AppendSrcPos (GetString ("NEW_VERSION_REQUIRED"), srcPos).c_str(), lpszTitle, ICON_HAND); + break; + + case ERR_SELF_TESTS_FAILED: + Error ("ERR_SELF_TESTS_FAILED", hwndDlg); + break; + + case ERR_VOL_FORMAT_BAD: + Error ("ERR_VOL_FORMAT_BAD", hwndDlg); + break; + + case ERR_ENCRYPTION_NOT_COMPLETED: + Error ("ERR_ENCRYPTION_NOT_COMPLETED", hwndDlg); + break; + + case ERR_NONSYS_INPLACE_ENC_INCOMPLETE: + Error ("ERR_NONSYS_INPLACE_ENC_INCOMPLETE", hwndDlg); + break; + + case ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG: + Error ("ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG", hwndDlg); + break; + + case ERR_PARAMETER_INCORRECT: + Error ("ERR_PARAMETER_INCORRECT", hwndDlg); + break; + + case ERR_USER_ABORT: + case ERR_DONT_REPORT: + // A non-error + break; + + case ERR_UNSUPPORTED_TRUECRYPT_FORMAT: + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("UNSUPPORTED_TRUECRYPT_FORMAT"), (code >> 24), (code >> 16) & 0x000000FF); + MessageBoxW (hwndDlg, AppendSrcPos (szTmp, srcPos).c_str(), lpszTitle, ICON_HAND); + break; + +#ifndef SETUP + case ERR_RAND_INIT_FAILED: + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("INIT_RAND"), SRC_POS, GetLastError ()); + MessageBoxW (hwndDlg, AppendSrcPos (szTmp, srcPos).c_str(), lpszTitle, MB_ICONERROR); + break; + + case ERR_CAPI_INIT_FAILED: + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CAPI_RAND"), SRC_POS, CryptoAPILastError); + MessageBoxW (hwndDlg, AppendSrcPos (szTmp, srcPos).c_str(), lpszTitle, MB_ICONERROR); + break; +#endif + + default: + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("ERR_UNKNOWN"), code); + MessageBoxW (hwndDlg, AppendSrcPos (szTmp, srcPos).c_str(), lpszTitle, ICON_HAND); + } +} + + +BOOL CheckFileStreamWriteErrors (HWND hwndDlg, FILE *file, const wchar_t *fileName) +{ + if (ferror (file)) + { + wchar_t s[TC_MAX_PATH]; + StringCbPrintfW (s, sizeof (s), GetString ("CANNOT_WRITE_FILE_X"), fileName); + ErrorDirect (s, hwndDlg); + + return FALSE; + } + + return TRUE; +} + + +static BOOL CALLBACK LocalizeDialogEnum( HWND hwnd, LPARAM font) +{ + // Localization of controls + + if (LocalizationActive) + { + int ctrlId = GetDlgCtrlID (hwnd); + if (ctrlId != 0) + { + WCHAR name[10] = { 0 }; + GetClassNameW (hwnd, name, array_capacity (name)); + + if (_wcsicmp (name, L"Button") == 0 || _wcsicmp (name, L"Static") == 0) + { + wchar_t *str = (wchar_t *) GetDictionaryValueByInt (ctrlId); + if (str != NULL) + SetWindowTextW (hwnd, str); + } + } + } + + // Font + SendMessageW (hwnd, WM_SETFONT, (WPARAM) font, 0); + + return TRUE; +} + +void LocalizeDialog (HWND hwnd, char *stringId) +{ + LastDialogId = stringId; + SetWindowLongPtrW (hwnd, GWLP_USERDATA, (LONG_PTR) 'VERA'); + SendMessageW (hwnd, WM_SETFONT, (WPARAM) hUserFont, 0); + + if (stringId == NULL) + SetWindowTextW (hwnd, L"VeraCrypt"); + else + SetWindowTextW (hwnd, GetString (stringId)); + + if (hUserFont != 0) + EnumChildWindows (hwnd, LocalizeDialogEnum, (LPARAM) hUserFont); +} + +void OpenVolumeExplorerWindow (int driveNo) +{ + wchar_t dosName[5]; + SHFILEINFO fInfo; + + StringCbPrintfW (dosName, sizeof(dosName), L"%c:\\", (wchar_t) driveNo + L'A'); + + // Force explorer to discover the drive + SHGetFileInfo (dosName, 0, &fInfo, sizeof (fInfo), 0); + + ShellExecute (NULL, L"open", dosName, NULL, NULL, SW_SHOWNORMAL); +} + +static BOOL explorerCloseSent; +static HWND explorerTopLevelWindow; + +static BOOL CALLBACK CloseVolumeExplorerWindowsChildEnum (HWND hwnd, LPARAM driveStr) +{ + WCHAR s[MAX_PATH]; + SendMessageW (hwnd, WM_GETTEXT, array_capacity (s), (LPARAM) s); + + if (wcsstr (s, (WCHAR *) driveStr) != NULL) + { + PostMessageW (explorerTopLevelWindow, WM_CLOSE, 0, 0); + explorerCloseSent = TRUE; + return FALSE; + } + + return TRUE; +} + +static BOOL CALLBACK CloseVolumeExplorerWindowsEnum (HWND hwnd, LPARAM driveNo) +{ + WCHAR driveStr[10]; + WCHAR s[MAX_PATH]; + + StringCbPrintfW (driveStr, sizeof(driveStr), L"%c:\\", driveNo + L'A'); + + GetClassNameW (hwnd, s, array_capacity (s)); + if (wcscmp (s, L"CabinetWClass") == 0) + { + GetWindowTextW (hwnd, s, array_capacity (s)); + if (wcsstr (s, driveStr) != NULL) + { + PostMessageW (hwnd, WM_CLOSE, 0, 0); + explorerCloseSent = TRUE; + return TRUE; + } + + explorerTopLevelWindow = hwnd; + EnumChildWindows (hwnd, CloseVolumeExplorerWindowsChildEnum, (LPARAM) driveStr); + } + + return TRUE; +} + +BOOL CloseVolumeExplorerWindows (HWND hwnd, int driveNo) +{ + if (driveNo >= 0) + { + explorerCloseSent = FALSE; + EnumWindows (CloseVolumeExplorerWindowsEnum, (LPARAM) driveNo); + } + + return explorerCloseSent; +} + +BOOL UpdateDriveCustomLabel (int driveNo, wchar_t* effectiveLabel, BOOL bSetValue) +{ + wchar_t wszRegPath[MAX_PATH]; + wchar_t driveStr[] = {L'A' + (wchar_t) driveNo, 0}; + HKEY hKey; + LSTATUS lStatus; + DWORD cbLabelLen = (DWORD) ((wcslen (effectiveLabel) + 1) * sizeof (wchar_t)); + BOOL bToBeDeleted = FALSE; + + StringCbPrintfW (wszRegPath, sizeof (wszRegPath), L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\DriveIcons\\%s\\DefaultLabel", driveStr); + + if (bSetValue) + lStatus = RegCreateKeyExW (HKEY_CURRENT_USER, wszRegPath, NULL, NULL, 0, + KEY_READ | KEY_WRITE | KEY_SET_VALUE, NULL, &hKey, NULL); + else + lStatus = RegOpenKeyExW (HKEY_CURRENT_USER, wszRegPath, 0, KEY_READ | KEY_WRITE | KEY_SET_VALUE, &hKey); + if (ERROR_SUCCESS == lStatus) + { + if (bSetValue) + lStatus = RegSetValueExW (hKey, NULL, NULL, REG_SZ, (LPCBYTE) effectiveLabel, cbLabelLen); + else + { + wchar_t storedLabel[34] = {0}; + DWORD cbStoredLen = sizeof (storedLabel) - 1, dwType; + lStatus = RegQueryValueExW (hKey, NULL, NULL, &dwType, (LPBYTE) storedLabel, &cbStoredLen); + if ((ERROR_SUCCESS == lStatus) && (REG_SZ == dwType) && (0 == wcscmp(storedLabel, effectiveLabel))) + { + // same label stored. mark key for deletion + bToBeDeleted = TRUE; + } + } + RegCloseKey (hKey); + } + + if (bToBeDeleted) + { + StringCbPrintfW (wszRegPath, sizeof (wszRegPath), L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\DriveIcons\\%s", driveStr); + lStatus = RegOpenKeyExW (HKEY_CURRENT_USER, wszRegPath, 0, KEY_READ | KEY_WRITE | KEY_SET_VALUE, &hKey); + if (ERROR_SUCCESS == lStatus) + { + lStatus = RegDeleteKeyW (hKey, L"DefaultLabel"); + RegCloseKey (hKey); + } + + // delete drive letter of nothing else is present under it + RegDeleteKeyW (HKEY_CURRENT_USER, wszRegPath); + + } + + return (ERROR_SUCCESS == lStatus)? TRUE : FALSE; +} + +wstring GetUserFriendlyVersionString (int version) +{ + wchar_t szTmp [64]; + StringCbPrintfW (szTmp, sizeof(szTmp), L"%x", version); + + wstring versionString (szTmp); + + versionString.insert (version > 0xfff ? 2 : 1,L"."); + + if (versionString[versionString.length()-1] == L'0') + versionString.erase (versionString.length()-1, 1); + + return (versionString); +} + +wstring IntToWideString (int val) +{ + wchar_t szTmp [64]; + StringCbPrintfW (szTmp, sizeof(szTmp), L"%d", val); + + return szTmp; +} + +wstring ArrayToHexWideString (const unsigned char* pbData, int cbData) +{ + static wchar_t* hexChar = L"0123456789ABCDEF"; + wstring result; + if (pbData) + { + for (int i = 0; i < cbData; i++) + { + result += hexChar[pbData[i] >> 4]; + result += hexChar[pbData[i] & 0x0F]; + } + } + + return result; +} + +bool HexToByte (wchar_t c, byte& b) +{ + bool bRet = true; + if (c >= L'0' && c <= L'9') + b = (byte) (c - L'0'); + else if (c >= L'a' && c <= L'z') + b = (byte) (c - L'a' + 10); + else if (c >= L'A' && c <= L'Z') + b = (byte) (c - L'A' + 10); + else + bRet = false; + + return bRet; +} + +bool HexWideStringToArray (const wchar_t* hexStr, std::vector& arr) +{ + byte b1, b2; + size_t i, len = wcslen (hexStr); + + arr.clear(); + if (len %2) + return false; + + for (i = 0; i < len/2; i++) + { + if (!HexToByte (*hexStr++, b1) || !HexToByte (*hexStr++, b2)) + return false; + arr.push_back (b1 << 4 | b2); + } + return true; +} + +wstring GetTempPathString () +{ + wchar_t tempPath[MAX_PATH]; + DWORD tempLen = ::GetTempPath (ARRAYSIZE (tempPath), tempPath); + if (tempLen == 0 || tempLen > ARRAYSIZE (tempPath)) + throw ParameterIncorrect (SRC_POS); + + return wstring (tempPath); +} + +void GetSizeString (unsigned __int64 size, wchar_t *str, size_t cbStr) +{ + static wchar_t *b, *kb, *mb, *gb, *tb, *pb; + static int serNo; + + if (b == NULL || serNo != LocalizationSerialNo) + { + serNo = LocalizationSerialNo; + kb = GetString ("KB"); + mb = GetString ("MB"); + gb = GetString ("GB"); + tb = GetString ("TB"); + pb = GetString ("PB"); + b = GetString ("BYTE"); + } + + if (size > 1024I64*1024*1024*1024*1024*99) + StringCbPrintfW (str, cbStr, L"%I64d %s", size/1024/1024/1024/1024/1024, pb); + else if (size > 1024I64*1024*1024*1024*1024) + StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(size/1024.0/1024/1024/1024/1024), pb); + else if (size > 1024I64*1024*1024*1024*99) + StringCbPrintfW (str, cbStr, L"%I64d %s",size/1024/1024/1024/1024, tb); + else if (size > 1024I64*1024*1024*1024) + StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(size/1024.0/1024/1024/1024), tb); + else if (size > 1024I64*1024*1024*99) + StringCbPrintfW (str, cbStr, L"%I64d %s",size/1024/1024/1024, gb); + else if (size > 1024I64*1024*1024) + StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(size/1024.0/1024/1024), gb); + else if (size > 1024I64*1024*99) + StringCbPrintfW (str, cbStr, L"%I64d %s", size/1024/1024, mb); + else if (size > 1024I64*1024) + StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(size/1024.0/1024), mb); + else if (size >= 1024I64) + StringCbPrintfW (str, cbStr, L"%I64d %s", size/1024, kb); + else + StringCbPrintfW (str, cbStr, L"%I64d %s", size, b); +} + +#ifndef SETUP +void GetSpeedString (unsigned __int64 speed, wchar_t *str, size_t cbStr) +{ + static wchar_t *b, *kb, *mb, *gb, *tb, *pb; + static int serNo; + + if (b == NULL || serNo != LocalizationSerialNo) + { + serNo = LocalizationSerialNo; + kb = GetString ("KB_PER_SEC"); + mb = GetString ("MB_PER_SEC"); + gb = GetString ("GB_PER_SEC"); + tb = GetString ("TB_PER_SEC"); + pb = GetString ("PB_PER_SEC"); + b = GetString ("B_PER_SEC"); + } + + if (speed > 1024I64*1024*1024*1024*1024*99) + StringCbPrintfW (str, cbStr, L"%I64d %s", speed/1024/1024/1024/1024/1024, pb); + else if (speed > 1024I64*1024*1024*1024*1024) + StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(speed/1024.0/1024/1024/1024/1024), pb); + else if (speed > 1024I64*1024*1024*1024*99) + StringCbPrintfW (str, cbStr, L"%I64d %s",speed/1024/1024/1024/1024, tb); + else if (speed > 1024I64*1024*1024*1024) + StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(speed/1024.0/1024/1024/1024), tb); + else if (speed > 1024I64*1024*1024*99) + StringCbPrintfW (str, cbStr, L"%I64d %s",speed/1024/1024/1024, gb); + else if (speed > 1024I64*1024*1024) + StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(speed/1024.0/1024/1024), gb); + else if (speed > 1024I64*1024*99) + StringCbPrintfW (str, cbStr, L"%I64d %s", speed/1024/1024, mb); + else if (speed > 1024I64*1024) + StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(speed/1024.0/1024), mb); + else if (speed > 1024I64) + StringCbPrintfW (str, cbStr, L"%I64d %s", speed/1024, kb); + else + StringCbPrintfW (str, cbStr, L"%I64d %s", speed, b); +} + +static void DisplayBenchmarkResults (HWND hwndDlg) +{ + wchar_t item1[100]={0}; + LVITEMW LvItem; + HWND hList = GetDlgItem (hwndDlg, IDC_RESULTS); + int ea, i; + BOOL unsorted = TRUE; + BENCHMARK_REC tmp_line; + + /* Sort the list */ + + switch (benchmarkSortMethod) + { + case BENCHMARK_SORT_BY_SPEED: + + while (unsorted) + { + unsorted = FALSE; + for (i = 0; i < benchmarkTotalItems - 1; i++) + { + if (benchmarkTable[i].meanBytesPerSec < benchmarkTable[i+1].meanBytesPerSec) + { + unsorted = TRUE; + memcpy (&tmp_line, &benchmarkTable[i], sizeof(BENCHMARK_REC)); + memcpy (&benchmarkTable[i], &benchmarkTable[i+1], sizeof(BENCHMARK_REC)); + memcpy (&benchmarkTable[i+1], &tmp_line, sizeof(BENCHMARK_REC)); + } + } + } + break; + + case BENCHMARK_SORT_BY_NAME: + + while (unsorted) + { + unsorted = FALSE; + for (i = 0; i < benchmarkTotalItems - 1; i++) + { + if (benchmarkTable[i].id > benchmarkTable[i+1].id) + { + unsorted = TRUE; + memcpy (&tmp_line, &benchmarkTable[i], sizeof(BENCHMARK_REC)); + memcpy (&benchmarkTable[i], &benchmarkTable[i+1], sizeof(BENCHMARK_REC)); + memcpy (&benchmarkTable[i+1], &tmp_line, sizeof(BENCHMARK_REC)); + } + } + } + break; + } + + /* Render the results */ + + SendMessage (hList,LVM_DELETEALLITEMS,0,(LPARAM)&LvItem); + + for (i = 0; i < benchmarkTotalItems; i++) + { + ea = benchmarkTable[i].id; + + memset (&LvItem,0,sizeof(LvItem)); + LvItem.mask = LVIF_TEXT; + LvItem.iItem = i; + LvItem.iSubItem = 0; + LvItem.pszText = (LPWSTR) benchmarkTable[i].name; + SendMessageW (hList, LVM_INSERTITEM, 0, (LPARAM)&LvItem); + +#if PKCS5_BENCHMARKS + wcscpy (item1, L"-"); +#else + GetSpeedString ((unsigned __int64) (benchmarkLastBufferSize / ((float) benchmarkTable[i].encSpeed / benchmarkPerformanceFrequency.QuadPart)), item1, sizeof(item1)); +#endif + LvItem.iSubItem = 1; + LvItem.pszText = item1; + + SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem); + +#if PKCS5_BENCHMARKS + wcscpy (item1, L"-"); +#else + GetSpeedString ((unsigned __int64) (benchmarkLastBufferSize / ((float) benchmarkTable[i].decSpeed / benchmarkPerformanceFrequency.QuadPart)), item1, sizeof(item1)); +#endif + LvItem.iSubItem = 2; + LvItem.pszText = item1; + + SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem); + +#if PKCS5_BENCHMARKS + swprintf (item1, L"%d t", benchmarkTable[i].encSpeed); +#else + GetSpeedString (benchmarkTable[i].meanBytesPerSec, item1, sizeof(item1)); +#endif + LvItem.iSubItem = 3; + LvItem.pszText = item1; + + SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem); + } + + SendMessageW(hList, LVM_SETCOLUMNWIDTH, 0, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); + SendMessageW(hList, LVM_SETCOLUMNWIDTH, 1, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); + SendMessageW(hList, LVM_SETCOLUMNWIDTH, 2, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); + SendMessageW(hList, LVM_SETCOLUMNWIDTH, 3, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); +} + +// specific implementation for support of benchmark operation in wait dialog mechanism + +typedef struct +{ + HWND hBenchDlg; + BOOL bStatus; +} BenchmarkThreadParam; + +static BOOL PerformBenchmark(HWND hBenchDlg, HWND hwndDlg); + +void CALLBACK BenchmarkThreadProc(void* pArg, HWND hwndDlg) +{ + BenchmarkThreadParam* pThreadParam = (BenchmarkThreadParam*) pArg; + + pThreadParam->bStatus = PerformBenchmark (pThreadParam->hBenchDlg, hwndDlg); +} + +static BOOL PerformBenchmark(HWND hBenchDlg, HWND hwndDlg) +{ + LARGE_INTEGER performanceCountStart, performanceCountEnd; + BYTE *lpTestBuffer; + PCRYPTO_INFO ci = NULL; + UINT64_STRUCT startDataUnitNo; + + startDataUnitNo.Value = 0; + +#if !(PKCS5_BENCHMARKS || HASH_FNC_BENCHMARKS) + ci = crypto_open (); + if (!ci) + return FALSE; +#endif + + if (QueryPerformanceFrequency (&benchmarkPerformanceFrequency) == 0) + { + if (ci) + crypto_close (ci); + MessageBoxW (hwndDlg, GetString ("ERR_PERF_COUNTER"), lpszTitle, ICON_HAND); + return FALSE; + } + + lpTestBuffer = (BYTE *) malloc(benchmarkBufferSize - (benchmarkBufferSize % 16)); + if (lpTestBuffer == NULL) + { + if (ci) + crypto_close (ci); + MessageBoxW (hwndDlg, GetString ("ERR_MEM_ALLOC"), lpszTitle, ICON_HAND); + return FALSE; + } + VirtualLock (lpTestBuffer, benchmarkBufferSize - (benchmarkBufferSize % 16)); + + WaitCursor (); + benchmarkTotalItems = 0; + +#if !(PKCS5_BENCHMARKS || HASH_FNC_BENCHMARKS) + // CPU "warm up" (an attempt to prevent skewed results on systems where CPU frequency + // gradually changes depending on CPU load). + ci->ea = EAGetFirst(); + if (!EAInit (ci->ea, ci->master_keydata, ci->ks)) + { + ci->mode = FIRST_MODE_OF_OPERATION_ID; + if (EAInitMode (ci)) + { + int i; + + for (i = 0; i < 10; i++) + { + EncryptDataUnits (lpTestBuffer, &startDataUnitNo, (TC_LARGEST_COMPILER_UINT) benchmarkBufferSize / ENCRYPTION_DATA_UNIT_SIZE, ci); + DecryptDataUnits (lpTestBuffer, &startDataUnitNo, (TC_LARGEST_COMPILER_UINT) benchmarkBufferSize / ENCRYPTION_DATA_UNIT_SIZE, ci); + } + } + } +#endif + +#if HASH_FNC_BENCHMARKS + + /* Measures the speed at which each of the hash algorithms processes the message to produce + a single digest. + + The hash algorithm benchmarks are included here for development purposes only. Do not enable + them when building a public release (the benchmark GUI strings wouldn't make sense). */ + + { + BYTE *digest [MAX_DIGESTSIZE]; + WHIRLPOOL_CTX wctx; + RMD160_CTX rctx; + sha512_ctx s2ctx; + sha256_ctx s256ctx; + int hid; + + for (hid = FIRST_PRF_ID; hid <= LAST_PRF_ID; hid++) + { + if (QueryPerformanceCounter (&performanceCountStart) == 0) + goto counter_error; + + switch (hid) + { + + case SHA512: + sha512_begin (&s2ctx); + sha512_hash (lpTestBuffer, benchmarkBufferSize, &s2ctx); + sha512_end ((unsigned char *) digest, &s2ctx); + break; + + case SHA256: + sha256_begin (&s256ctx); + sha256_hash (lpTestBuffer, benchmarkBufferSize, &s256ctx); + sha256_end ((unsigned char *) digest, &s256ctx); + break; + + case RIPEMD160: + RMD160Init(&rctx); + RMD160Update(&rctx, lpTestBuffer, benchmarkBufferSize); + RMD160Final((unsigned char *) digest, &rctx); + break; + + case WHIRLPOOL: + WHIRLPOOL_init (&wctx); + WHIRLPOOL_add (lpTestBuffer, benchmarkBufferSize * 8, &wctx); + WHIRLPOOL_finalize (&wctx, (unsigned char *) digest); + break; + } + + if (QueryPerformanceCounter (&performanceCountEnd) == 0) + goto counter_error; + + benchmarkTable[benchmarkTotalItems].encSpeed = performanceCountEnd.QuadPart - performanceCountStart.QuadPart; + + benchmarkTable[benchmarkTotalItems].decSpeed = benchmarkTable[benchmarkTotalItems].encSpeed; + benchmarkTable[benchmarkTotalItems].id = hid; + benchmarkTable[benchmarkTotalItems].meanBytesPerSec = ((unsigned __int64) (benchmarkBufferSize / ((float) benchmarkTable[benchmarkTotalItems].encSpeed / benchmarkPerformanceFrequency.QuadPart)) + (unsigned __int64) (benchmarkBufferSize / ((float) benchmarkTable[benchmarkTotalItems].decSpeed / benchmarkPerformanceFrequency.QuadPart))) / 2; + StringCbPrintfA (benchmarkTable[benchmarkTotalItems].name, sizeof(benchmarkTable[benchmarkTotalItems].name),"%s", HashGetName(hid)); + + benchmarkTotalItems++; + } + } + +#elif PKCS5_BENCHMARKS // #if HASH_FNC_BENCHMARKS + + /* Measures the time that it takes for the PKCS-5 routine to derive a header key using + each of the implemented PRF algorithms. + + The PKCS-5 benchmarks are included here for development purposes only. Do not enable + them when building a public release (the benchmark GUI strings wouldn't make sense). */ + { + int thid, i; + char dk[MASTER_KEYDATA_SIZE]; + char *tmp_salt = {"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF\x01\x23\x45\x67\x89\xAB\xCD\xEF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF\x01\x23\x45\x67\x89\xAB\xCD\xEF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF"}; + + for (thid = FIRST_PRF_ID; thid <= LAST_PRF_ID; thid++) + { + if (QueryPerformanceCounter (&performanceCountStart) == 0) + goto counter_error; + + for (i = 1; i <= 5; i++) + { + switch (thid) + { + + case SHA512: + /* PKCS-5 test with HMAC-SHA-512 used as the PRF */ + derive_key_sha512 ("passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, 0, FALSE, FALSE), dk, MASTER_KEYDATA_SIZE); + break; + + case SHA256: + /* PKCS-5 test with HMAC-SHA-256 used as the PRF */ + derive_key_sha256 ("passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, 0, FALSE, FALSE), dk, MASTER_KEYDATA_SIZE); + break; + + case RIPEMD160: + /* PKCS-5 test with HMAC-RIPEMD-160 used as the PRF */ + derive_key_ripemd160 ("passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, 0, FALSE, FALSE), dk, MASTER_KEYDATA_SIZE); + break; + + case WHIRLPOOL: + /* PKCS-5 test with HMAC-Whirlpool used as the PRF */ + derive_key_whirlpool ("passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, 0, FALSE, FALSE), dk, MASTER_KEYDATA_SIZE); + break; + } + } + + if (QueryPerformanceCounter (&performanceCountEnd) == 0) + goto counter_error; + + benchmarkTable[benchmarkTotalItems].encSpeed = performanceCountEnd.QuadPart - performanceCountStart.QuadPart; + benchmarkTable[benchmarkTotalItems].id = thid; + StringCbPrintfW (benchmarkTable[benchmarkTotalItems].name, sizeof(benchmarkTable[benchmarkTable[benchmarkTotalItems].name),L"%s", get_pkcs5_prf_name (thid)); + + benchmarkTotalItems++; + } + } + +#else // #elif PKCS5_BENCHMARKS + + /* Encryption algorithm benchmarks */ + + for (ci->ea = EAGetFirst(); ci->ea != 0; ci->ea = EAGetNext(ci->ea)) + { + if (!EAIsFormatEnabled (ci->ea)) + continue; + + if (ERR_CIPHER_INIT_FAILURE == EAInit (ci->ea, ci->master_keydata, ci->ks)) + goto counter_error; + + ci->mode = FIRST_MODE_OF_OPERATION_ID; + if (!EAInitMode (ci)) + goto counter_error; + + if (QueryPerformanceCounter (&performanceCountStart) == 0) + goto counter_error; + + EncryptDataUnits (lpTestBuffer, &startDataUnitNo, (TC_LARGEST_COMPILER_UINT) benchmarkBufferSize / ENCRYPTION_DATA_UNIT_SIZE, ci); + + if (QueryPerformanceCounter (&performanceCountEnd) == 0) + goto counter_error; + + benchmarkTable[benchmarkTotalItems].encSpeed = performanceCountEnd.QuadPart - performanceCountStart.QuadPart; + + if (QueryPerformanceCounter (&performanceCountStart) == 0) + goto counter_error; + + DecryptDataUnits (lpTestBuffer, &startDataUnitNo, (TC_LARGEST_COMPILER_UINT) benchmarkBufferSize / ENCRYPTION_DATA_UNIT_SIZE, ci); + + if (QueryPerformanceCounter (&performanceCountEnd) == 0) + goto counter_error; + + benchmarkTable[benchmarkTotalItems].decSpeed = performanceCountEnd.QuadPart - performanceCountStart.QuadPart; + benchmarkTable[benchmarkTotalItems].id = ci->ea; + benchmarkTable[benchmarkTotalItems].meanBytesPerSec = ((unsigned __int64) (benchmarkBufferSize / ((float) benchmarkTable[benchmarkTotalItems].encSpeed / benchmarkPerformanceFrequency.QuadPart)) + (unsigned __int64) (benchmarkBufferSize / ((float) benchmarkTable[benchmarkTotalItems].decSpeed / benchmarkPerformanceFrequency.QuadPart))) / 2; + EAGetName (benchmarkTable[benchmarkTotalItems].name, ci->ea, 1); + + benchmarkTotalItems++; + } + +#endif // #elif PKCS5_BENCHMARKS (#else) + + if (ci) + crypto_close (ci); + + VirtualUnlock (lpTestBuffer, benchmarkBufferSize - (benchmarkBufferSize % 16)); + + free(lpTestBuffer); + + benchmarkLastBufferSize = benchmarkBufferSize; + + DisplayBenchmarkResults(hBenchDlg); + + EnableWindow (GetDlgItem (hBenchDlg, IDC_PERFORM_BENCHMARK), TRUE); + EnableWindow (GetDlgItem (hBenchDlg, IDCLOSE), TRUE); + + NormalCursor (); + return TRUE; + +counter_error: + + if (ci) + crypto_close (ci); + + VirtualUnlock (lpTestBuffer, benchmarkBufferSize - (benchmarkBufferSize % 16)); + + free(lpTestBuffer); + + NormalCursor (); + + EnableWindow (GetDlgItem (hBenchDlg, IDC_PERFORM_BENCHMARK), TRUE); + EnableWindow (GetDlgItem (hBenchDlg, IDCLOSE), TRUE); + + MessageBoxW (hwndDlg, GetString ("ERR_PERF_COUNTER"), lpszTitle, ICON_HAND); + return FALSE; +} + + +BOOL CALLBACK BenchmarkDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + LPARAM nIndex; + HWND hCboxSortMethod = GetDlgItem (hwndDlg, IDC_BENCHMARK_SORT_METHOD); + HWND hCboxBufferSize = GetDlgItem (hwndDlg, IDC_BENCHMARK_BUFFER_SIZE); + + switch (msg) + { + case WM_INITDIALOG: + { + LVCOLUMNW LvCol; + wchar_t s[128]; + HWND hList = GetDlgItem (hwndDlg, IDC_RESULTS); + + LocalizeDialog (hwndDlg, "IDD_BENCHMARK_DLG"); + + benchmarkBufferSize = BENCHMARK_DEFAULT_BUF_SIZE; + benchmarkSortMethod = BENCHMARK_SORT_BY_SPEED; + + SendMessage (hList,LVM_SETEXTENDEDLISTVIEWSTYLE,0, + LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_LABELTIP + ); + + memset (&LvCol,0,sizeof(LvCol)); + LvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; + LvCol.pszText = GetString ("ALGORITHM"); + LvCol.cx = CompensateXDPI (114); + LvCol.fmt = LVCFMT_LEFT; + SendMessage (hList,LVM_INSERTCOLUMNW,0,(LPARAM)&LvCol); + + LvCol.pszText = GetString ("ENCRYPTION"); + LvCol.cx = CompensateXDPI (80); + LvCol.fmt = LVCFMT_RIGHT; + SendMessageW (hList,LVM_INSERTCOLUMNW,1,(LPARAM)&LvCol); + + LvCol.pszText = GetString ("DECRYPTION"); + LvCol.cx = CompensateXDPI (80); + LvCol.fmt = LVCFMT_RIGHT; + SendMessageW (hList,LVM_INSERTCOLUMNW,2,(LPARAM)&LvCol); + + LvCol.pszText = GetString ("MEAN"); + LvCol.cx = CompensateXDPI (80); + LvCol.fmt = LVCFMT_RIGHT; + SendMessageW (hList,LVM_INSERTCOLUMNW,3,(LPARAM)&LvCol); + + /* Combo boxes */ + + // Sort method + + SendMessage (hCboxSortMethod, CB_RESETCONTENT, 0, 0); + + nIndex = SendMessageW (hCboxSortMethod, CB_ADDSTRING, 0, (LPARAM) GetString ("ALPHABETICAL_CATEGORIZED")); + SendMessage (hCboxSortMethod, CB_SETITEMDATA, nIndex, (LPARAM) 0); + + nIndex = SendMessageW (hCboxSortMethod, CB_ADDSTRING, 0, (LPARAM) GetString ("MEAN_SPEED")); + SendMessage (hCboxSortMethod, CB_SETITEMDATA, nIndex, (LPARAM) 0); + + SendMessage (hCboxSortMethod, CB_SETCURSEL, 1, 0); // Default sort method + + // Buffer size + + SendMessage (hCboxBufferSize, CB_RESETCONTENT, 0, 0); + + StringCbPrintfW (s, sizeof(s), L"100 %s", GetString ("KB")); + nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); + SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 100 * BYTES_PER_KB); + + StringCbPrintfW (s, sizeof(s), L"500 %s", GetString ("KB")); + nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); + SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 500 * BYTES_PER_KB); + + StringCbPrintfW (s, sizeof(s), L"1 %s", GetString ("MB")); + nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); + SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 1 * BYTES_PER_MB); + + StringCbPrintfW (s, sizeof(s), L"5 %s", GetString ("MB")); + nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); + SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 5 * BYTES_PER_MB); + + StringCbPrintfW (s, sizeof(s), L"10 %s", GetString ("MB")); + nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); + SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 10 * BYTES_PER_MB); + + StringCbPrintfW (s, sizeof(s), L"50 %s", GetString ("MB")); + nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); + SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 50 * BYTES_PER_MB); + + StringCbPrintfW (s, sizeof(s), L"100 %s", GetString ("MB")); + nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); + SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 100 * BYTES_PER_MB); + + StringCbPrintfW (s, sizeof(s), L"200 %s", GetString ("MB")); + nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); + SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 200 * BYTES_PER_MB); + + StringCbPrintfW (s, sizeof(s), L"500 %s", GetString ("MB")); + nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); + SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 500 * BYTES_PER_MB); + + StringCbPrintfW (s, sizeof(s), L"1 %s", GetString ("GB")); + nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s); + SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 1 * BYTES_PER_GB); + + SendMessage (hCboxBufferSize, CB_SETCURSEL, 5, 0); // Default buffer size + + + uint32 driverConfig = ReadDriverConfigurationFlags(); + + SetDlgItemTextW (hwndDlg, IDC_HW_AES, (wstring (L" ") + (GetString (is_aes_hw_cpu_supported() ? ((driverConfig & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? "UISTR_DISABLED" : "UISTR_YES") : "NOT_APPLICABLE_OR_NOT_AVAILABLE"))).c_str()); + + ToHyperlink (hwndDlg, IDC_HW_AES_LABEL_LINK); + + if (is_aes_hw_cpu_supported() && (driverConfig & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION)) + { + Warning ("DISABLED_HW_AES_AFFECTS_PERFORMANCE", hwndDlg); + } + + SYSTEM_INFO sysInfo; + GetSystemInfo (&sysInfo); + + size_t nbrThreads = GetEncryptionThreadCount(); + + wchar_t nbrThreadsStr [300]; + if (sysInfo.dwNumberOfProcessors < 2) + { + StringCbCopyW (nbrThreadsStr, sizeof(nbrThreadsStr), GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE")); + } + else if (nbrThreads < 2) + { + StringCbCopyW (nbrThreadsStr, sizeof(nbrThreadsStr), GetString ("UISTR_DISABLED")); + } + else + { + StringCbPrintfW (nbrThreadsStr, sizeof(nbrThreadsStr), GetString ("NUMBER_OF_THREADS"), nbrThreads); + } + + SetDlgItemTextW (hwndDlg, IDC_PARALLELIZATION, (wstring (L" ") + nbrThreadsStr).c_str()); + + ToHyperlink (hwndDlg, IDC_PARALLELIZATION_LABEL_LINK); + + if (nbrThreads < min (sysInfo.dwNumberOfProcessors, GetMaxEncryptionThreadCount()) + && sysInfo.dwNumberOfProcessors > 1) + { + Warning ("LIMITED_THREAD_COUNT_AFFECTS_PERFORMANCE", hwndDlg); + } + + return 1; + } + break; + + case WM_COMMAND: + + switch (lw) + { + case IDC_BENCHMARK_SORT_METHOD: + + nIndex = SendMessage (hCboxSortMethod, CB_GETCURSEL, 0, 0); + if (nIndex != benchmarkSortMethod) + { + benchmarkSortMethod = (int) nIndex; + DisplayBenchmarkResults (hwndDlg); + } + return 1; + + case IDC_PERFORM_BENCHMARK: + + nIndex = SendMessage (hCboxBufferSize, CB_GETCURSEL, 0, 0); + benchmarkBufferSize = (int) SendMessage (hCboxBufferSize, CB_GETITEMDATA, nIndex, 0); + + BenchmarkThreadParam threadParam; + threadParam.hBenchDlg = hwndDlg; + threadParam.bStatus = FALSE; + + WaitCursor (); + + ShowWaitDialog (hwndDlg, TRUE, BenchmarkThreadProc, &threadParam); + + NormalCursor (); + + if (threadParam.bStatus == FALSE) + { + EndDialog (hwndDlg, IDCLOSE); + } + return 1; + + case IDC_HW_AES_LABEL_LINK: + + Applink ("hwacceleration", TRUE, ""); + return 1; + + case IDC_PARALLELIZATION_LABEL_LINK: + + Applink ("parallelization", TRUE, ""); + return 1; + + case IDCLOSE: + case IDCANCEL: + + EndDialog (hwndDlg, IDCLOSE); + return 1; + } + return 0; + + break; + + case WM_CLOSE: + EndDialog (hwndDlg, IDCLOSE); + return 1; + + break; + + } + return 0; +} + + +static BOOL CALLBACK RandomPoolEnrichementDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + WORD hw = HIWORD (wParam); + static unsigned char randPool [RNG_POOL_SIZE]; + static unsigned char lastRandPool [RNG_POOL_SIZE]; + static unsigned char maskRandPool [RNG_POOL_SIZE]; + static BOOL bUseMask = FALSE; + static DWORD mouseEntropyGathered = 0xFFFFFFFF; + static DWORD mouseEventsInitialCount = 0; + /* max value of entropy needed to fill all random pool = 8 * RNG_POOL_SIZE = 2560 bits */ + static const DWORD maxEntropyLevel = RNG_POOL_SIZE * 8; + static HWND hEntropyBar = NULL; + static wchar_t outputDispBuffer [RNG_POOL_SIZE * 3 + RANDPOOL_DISPLAY_ROWS + 2]; + static BOOL bDisplayPoolContents = FALSE; + static BOOL bRandPoolDispAscii = FALSE; + int hash_algo = RandGetHashFunction(); + int hid; + + switch (msg) + { + case WM_INITDIALOG: + { + HWND hComboBox = GetDlgItem (hwndDlg, IDC_PRF_ID); + HCRYPTPROV hRngProv = NULL; + + VirtualLock (randPool, sizeof(randPool)); + VirtualLock (lastRandPool, sizeof(lastRandPool)); + VirtualLock (outputDispBuffer, sizeof(outputDispBuffer)); + VirtualLock (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); + VirtualLock (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); + VirtualLock (maskRandPool, sizeof(maskRandPool)); + + mouseEntropyGathered = 0xFFFFFFFF; + mouseEventsInitialCount = 0; + bUseMask = FALSE; + if (CryptAcquireContext (&hRngProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + { + if (CryptGenRandom (hRngProv, sizeof (maskRandPool), maskRandPool)) + bUseMask = TRUE; + CryptReleaseContext (hRngProv, 0); + } + + LocalizeDialog (hwndDlg, "IDD_RANDOM_POOL_ENRICHMENT"); + + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + for (hid = FIRST_PRF_ID; hid <= LAST_PRF_ID; hid++) + { + if (!HashIsDeprecated (hid)) + AddComboPair (hComboBox, HashGetName(hid), hid); + } + SelectAlgo (hComboBox, &hash_algo); + + SetCheckBox (hwndDlg, IDC_DISPLAY_POOL_CONTENTS, bDisplayPoolContents); + + SetTimer (hwndDlg, 0xfd, RANDPOOL_DISPLAY_REFRESH_INTERVAL, NULL); + SendMessage (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); + + hEntropyBar = GetDlgItem (hwndDlg, IDC_ENTROPY_BAR); + SendMessage (hEntropyBar, PBM_SETRANGE32, 0, maxEntropyLevel); + SendMessage (hEntropyBar, PBM_SETSTEP, 1, 0); + SendMessage (hEntropyBar, PBM_SETSTATE, PBST_ERROR, 0); + return 1; + } + + case WM_TIMER: + { + wchar_t tmp[4]; + unsigned char tmpByte; + int col, row; + DWORD mouseEventsCounter; + + RandpeekBytes (hwndDlg, randPool, sizeof (randPool), &mouseEventsCounter); + + ProcessEntropyEstimate (hEntropyBar, &mouseEventsInitialCount, mouseEventsCounter, maxEntropyLevel, &mouseEntropyGathered); + + if (memcmp (lastRandPool, randPool, sizeof(lastRandPool)) != 0) + { + outputDispBuffer[0] = 0; + + for (row = 0; row < RANDPOOL_DISPLAY_ROWS; row++) + { + for (col = 0; col < RANDPOOL_DISPLAY_COLUMNS; col++) + { + if (bDisplayPoolContents) + { + tmpByte = randPool[row * RANDPOOL_DISPLAY_COLUMNS + col]; + StringCbPrintfW (tmp, sizeof(tmp), bRandPoolDispAscii ? ((tmpByte >= 32 && tmpByte < 255 && tmpByte != L'&') ? L" %c " : L" . ") : L"%02X ", tmpByte); + } + else if (bUseMask) + { + /* use mask to compute a randomized ascii representation */ + tmpByte = (randPool[row * RANDPOOL_DISPLAY_COLUMNS + col] - + lastRandPool[row * RANDPOOL_DISPLAY_COLUMNS + col]) ^ maskRandPool [row * RANDPOOL_DISPLAY_COLUMNS + col]; + tmp[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); + tmp[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); + tmp[2] = L' '; + tmp[3] = 0; + } + else + { + StringCbCopyW (tmp, sizeof(tmp), L"** "); + } + + StringCbCatW (outputDispBuffer, sizeof(outputDispBuffer), tmp); + } + StringCbCatW (outputDispBuffer, sizeof(outputDispBuffer), L"\n"); + } + SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), outputDispBuffer); + + memcpy (lastRandPool, randPool, sizeof(lastRandPool)); + } + return 1; + } + + case WM_COMMAND: + if (lw == IDC_CONTINUE) + lw = IDOK; + + if (lw == IDOK || lw == IDCLOSE || lw == IDCANCEL) + { + goto exit; + } + + if (lw == IDC_PRF_ID && hw == CBN_SELCHANGE) + { + hid = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PRF_ID), CB_GETCURSEL, 0, 0); + hash_algo = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PRF_ID), CB_GETITEMDATA, hid, 0); + RandSetHashFunction (hash_algo); + return 1; + } + + if (lw == IDC_DISPLAY_POOL_CONTENTS) + { + if (!(bDisplayPoolContents = GetCheckBox (hwndDlg, IDC_DISPLAY_POOL_CONTENTS))) + { + wchar_t tmp[RNG_POOL_SIZE+1]; + + wmemset (tmp, L' ', ARRAYSIZE(tmp)); + tmp [RNG_POOL_SIZE] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), tmp); + } + + return 1; + } + + return 0; + + case WM_CLOSE: + { + wchar_t tmp[RNG_POOL_SIZE+1]; +exit: + KillTimer (hwndDlg, 0xfd); + + burn (randPool, sizeof(randPool)); + burn (lastRandPool, sizeof(lastRandPool)); + burn (outputDispBuffer, sizeof(outputDispBuffer)); + burn (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); + burn (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); + burn (maskRandPool, sizeof(maskRandPool)); + + // Attempt to wipe the pool contents in the GUI text area + wmemset (tmp, L' ', RNG_POOL_SIZE); + tmp [RNG_POOL_SIZE] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), tmp); + + if (msg == WM_COMMAND && lw == IDOK) + EndDialog (hwndDlg, IDOK); + else + EndDialog (hwndDlg, IDCLOSE); + + return 1; + } + } + return 0; +} + +/* Randinit is always called before UserEnrichRandomPool, so we don't need + * the extra Randinit call here since it will always succeed but we keep it + * for clarity purposes + */ +void UserEnrichRandomPool (HWND hwndDlg) +{ + if ((0 == Randinit()) && !IsRandomPoolEnrichedByUser()) + { + INT_PTR result = DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_RANDOM_POOL_ENRICHMENT), hwndDlg ? hwndDlg : MainDlg, (DLGPROC) RandomPoolEnrichementDlgProc, (LPARAM) 0); + SetRandomPoolEnrichedByUserStatus (result == IDOK); + } +} + + +/* Except in response to the WM_INITDIALOG message, the dialog box procedure + should return nonzero if it processes the message, and zero if it does + not. - see DialogProc */ +BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + WORD hw = HIWORD (wParam); + static unsigned char randPool [RNG_POOL_SIZE]; + static unsigned char lastRandPool [RNG_POOL_SIZE]; + static unsigned char maskRandPool [RNG_POOL_SIZE]; + static BOOL bUseMask = FALSE; + static DWORD mouseEntropyGathered = 0xFFFFFFFF; + static DWORD mouseEventsInitialCount = 0; + /* max value of entropy needed to fill all random pool = 8 * RNG_POOL_SIZE = 2560 bits */ + static const DWORD maxEntropyLevel = RNG_POOL_SIZE * 8; + static HWND hEntropyBar = NULL; + static wchar_t outputDispBuffer [RNG_POOL_SIZE * 3 + RANDPOOL_DISPLAY_ROWS + 2]; + static BOOL bDisplayPoolContents = FALSE; + static BOOL bRandPoolDispAscii = FALSE; + int hash_algo = RandGetHashFunction(); + int hid; + + switch (msg) + { + case WM_INITDIALOG: + { + HWND hComboBox = GetDlgItem (hwndDlg, IDC_PRF_ID); + HCRYPTPROV hRngProv = NULL; + + VirtualLock (randPool, sizeof(randPool)); + VirtualLock (lastRandPool, sizeof(lastRandPool)); + VirtualLock (outputDispBuffer, sizeof(outputDispBuffer)); + VirtualLock (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); + VirtualLock (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); + VirtualLock (maskRandPool, sizeof(maskRandPool)); + + mouseEntropyGathered = 0xFFFFFFFF; + mouseEventsInitialCount = 0; + bUseMask = FALSE; + if (CryptAcquireContext (&hRngProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + { + if (CryptGenRandom (hRngProv, sizeof (maskRandPool), maskRandPool)) + bUseMask = TRUE; + CryptReleaseContext (hRngProv, 0); + } + + LocalizeDialog (hwndDlg, "IDD_KEYFILE_GENERATOR"); + + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + for (hid = FIRST_PRF_ID; hid <= LAST_PRF_ID; hid++) + { + if (!HashIsDeprecated (hid)) + AddComboPair (hComboBox, HashGetName(hid), hid); + } + SelectAlgo (hComboBox, &hash_algo); + + SetCheckBox (hwndDlg, IDC_DISPLAY_POOL_CONTENTS, bDisplayPoolContents); + hEntropyBar = GetDlgItem (hwndDlg, IDC_ENTROPY_BAR); + SendMessage (hEntropyBar, PBM_SETRANGE32, 0, maxEntropyLevel); + SendMessage (hEntropyBar, PBM_SETSTEP, 1, 0); + SendMessage (hEntropyBar, PBM_SETSTATE, PBST_ERROR, 0); + +#ifndef VOLFORMAT + if (Randinit ()) + { + handleError (hwndDlg, (CryptoAPILastError == ERROR_SUCCESS)? ERR_RAND_INIT_FAILED : ERR_CAPI_INIT_FAILED, SRC_POS); + EndDialog (hwndDlg, IDCLOSE); + } +#endif + SetTimer (hwndDlg, 0xfd, RANDPOOL_DISPLAY_REFRESH_INTERVAL, NULL); + SendMessage (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); + // 9-digit limit for the number of keyfiles (more than enough!) + SendMessage (GetDlgItem (hwndDlg, IDC_NUMBER_KEYFILES), EM_SETLIMITTEXT, (WPARAM) 9, 0); + SetWindowText(GetDlgItem (hwndDlg, IDC_NUMBER_KEYFILES), L"1"); + // maximum keyfile size is 1048576, so limit the edit control to 7 characters + SendMessage (GetDlgItem (hwndDlg, IDC_KEYFILES_SIZE), EM_SETLIMITTEXT, (WPARAM) 7, 0); + SetWindowText(GetDlgItem (hwndDlg, IDC_KEYFILES_SIZE), L"64"); + // set the maximum length of the keyfile base name to (TC_MAX_PATH - 1) + SendMessage (GetDlgItem (hwndDlg, IDC_KEYFILES_BASE_NAME), EM_SETLIMITTEXT, (WPARAM) (TC_MAX_PATH - 1), 0); + return 1; + } + + case WM_TIMER: + { + wchar_t tmp[4]; + unsigned char tmpByte; + int col, row; + DWORD mouseEventsCounter; + + RandpeekBytes (hwndDlg, randPool, sizeof (randPool), &mouseEventsCounter); + + ProcessEntropyEstimate (hEntropyBar, &mouseEventsInitialCount, mouseEventsCounter, maxEntropyLevel, &mouseEntropyGathered); + + if (memcmp (lastRandPool, randPool, sizeof(lastRandPool)) != 0) + { + outputDispBuffer[0] = 0; + + for (row = 0; row < RANDPOOL_DISPLAY_ROWS; row++) + { + for (col = 0; col < RANDPOOL_DISPLAY_COLUMNS; col++) + { + if (bDisplayPoolContents) + { + tmpByte = randPool[row * RANDPOOL_DISPLAY_COLUMNS + col]; + StringCbPrintfW (tmp, sizeof(tmp), bRandPoolDispAscii ? ((tmpByte >= 32 && tmpByte < 255 && tmpByte != L'&') ? L" %c " : L" . ") : L"%02X ", tmpByte); + } + else if (bUseMask) + { + /* use mask to compute a randomized ASCII representation */ + tmpByte = (randPool[row * RANDPOOL_DISPLAY_COLUMNS + col] - + lastRandPool[row * RANDPOOL_DISPLAY_COLUMNS + col]) ^ maskRandPool [row * RANDPOOL_DISPLAY_COLUMNS + col]; + tmp[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); + tmp[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); + tmp[2] = L' '; + tmp[3] = 0; + } + else + { + StringCbCopyW (tmp, sizeof(tmp), L"** "); + } + + StringCbCatW (outputDispBuffer, sizeof(outputDispBuffer), tmp); + } + StringCbCatW (outputDispBuffer, sizeof(outputDispBuffer), L"\n"); + } + SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), outputDispBuffer); + + memcpy (lastRandPool, randPool, sizeof(lastRandPool)); + } + return 1; + } + + case WM_COMMAND: + + if (lw == IDCLOSE || lw == IDCANCEL) + { + goto exit; + } + + if (lw == IDC_PRF_ID && hw == CBN_SELCHANGE) + { + hid = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PRF_ID), CB_GETCURSEL, 0, 0); + hash_algo = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PRF_ID), CB_GETITEMDATA, hid, 0); + RandSetHashFunction (hash_algo); + return 1; + } + + if (lw == IDC_DISPLAY_POOL_CONTENTS) + { + if (!(bDisplayPoolContents = GetCheckBox (hwndDlg, IDC_DISPLAY_POOL_CONTENTS))) + { + wchar_t tmp[RNG_POOL_SIZE+1]; + + wmemset (tmp, L' ', ARRAYSIZE(tmp)); + tmp [RNG_POOL_SIZE] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), tmp); + } + return 1; + } + + if (lw == IDC_KEYFILES_RANDOM_SIZE) + { + EnableWindow(GetDlgItem (hwndDlg, IDC_KEYFILES_SIZE), !GetCheckBox (hwndDlg, IDC_KEYFILES_RANDOM_SIZE)); + } + + if (lw == IDC_GENERATE_AND_SAVE_KEYFILE) + { + wchar_t szNumber[16] = {0}; + wchar_t szFileBaseName[TC_MAX_PATH]; + wchar_t szDirName[TC_MAX_PATH]; + wchar_t szFileName [2*TC_MAX_PATH + 16]; + unsigned char *keyfile = NULL; + int fhKeyfile = -1, status; + long keyfilesCount = 0, keyfilesSize = 0, i; + wchar_t* fileExtensionPtr = 0; + wchar_t szSuffix[32]; + BOOL bRandomSize = GetCheckBox (hwndDlg, IDC_KEYFILES_RANDOM_SIZE); + + if (!GetWindowText(GetDlgItem (hwndDlg, IDC_NUMBER_KEYFILES), szNumber, ARRAYSIZE(szNumber))) + szNumber[0] = 0; + + keyfilesCount = wcstoul(szNumber, NULL, 0); + if (keyfilesCount <= 0 || keyfilesCount == LONG_MAX) + { + Warning("KEYFILE_INCORRECT_NUMBER", hwndDlg); + SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hwndDlg, IDC_NUMBER_KEYFILES), TRUE); + return 1; + } + + if (!bRandomSize) + { + if (!GetWindowText(GetDlgItem (hwndDlg, IDC_KEYFILES_SIZE), szNumber, ARRAYSIZE(szNumber))) + szNumber[0] = 0; + + keyfilesSize = wcstoul(szNumber, NULL, 0); + if (keyfilesSize < 64 || keyfilesSize > 1024*1024) + { + Warning("KEYFILE_INCORRECT_SIZE", hwndDlg); + SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hwndDlg, IDC_KEYFILES_SIZE), TRUE); + return 1; + } + } + + if (!GetWindowText(GetDlgItem (hwndDlg, IDC_KEYFILES_BASE_NAME), szFileBaseName, TC_MAX_PATH)) + szFileBaseName[0] = 0; + + // Trim trailing space + if (TrimWhiteSpace(szFileBaseName) == 0) + { + Warning("KEYFILE_EMPTY_BASE_NAME", hwndDlg); + SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hwndDlg, IDC_KEYFILES_BASE_NAME), TRUE); + return 1; + } + + if (!IsValidFileName(szFileBaseName)) + { + Warning("KEYFILE_INVALID_BASE_NAME", hwndDlg); + SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hwndDlg, IDC_KEYFILES_BASE_NAME), TRUE); + return 1; + } + + fileExtensionPtr = wcsrchr(szFileBaseName, L'.'); + + /* Select directory */ + if (!BrowseDirectories (hwndDlg, "SELECT_KEYFILE_GENERATION_DIRECTORY", szDirName)) + return 1; + + if (szDirName[wcslen(szDirName) - 1] != L'\\' && szDirName[wcslen(szDirName) - 1] != L'/') + StringCbCat(szDirName, sizeof(szDirName), L"\\"); + + WaitCursor(); + + keyfile = (unsigned char*) TCalloc( bRandomSize? KEYFILE_MAX_READ_LEN : keyfilesSize ); + + for (i= 0; i < keyfilesCount; i++) + { + StringCbCopyW(szFileName, sizeof(szFileName), szDirName); + + if (i > 0) + { + StringCbPrintfW(szSuffix, sizeof(szSuffix), L"_%d", i); + // Append the counter to the name + if (fileExtensionPtr) + { + StringCchCatN(szFileName, ARRAYSIZE(szFileName), szFileBaseName, (size_t) (fileExtensionPtr - szFileBaseName)); + StringCbCat(szFileName, sizeof(szFileName), szSuffix); + StringCbCat(szFileName, sizeof(szFileName), fileExtensionPtr); + } + else + { + StringCbCat(szFileName, sizeof(szFileName), szFileBaseName); + StringCbCat(szFileName, sizeof(szFileName), szSuffix); + } + } + else + StringCbCat(szFileName, sizeof(szFileName), szFileBaseName); + + // check if the file exists + if ((fhKeyfile = _wopen(szFileName, _O_RDONLY|_O_BINARY, _S_IREAD|_S_IWRITE)) != -1) + { + WCHAR s[4*TC_MAX_PATH] = {0}; + + _close (fhKeyfile); + + StringCbPrintfW (s, sizeof(s), GetString ("KEYFILE_ALREADY_EXISTS"), szFileName); + status = AskWarnNoYesString (s, hwndDlg); + if (status == IDNO) + { + TCfree(keyfile); + NormalCursor(); + return 1; + } + } + + /* Conceive the file */ + if ((fhKeyfile = _wopen(szFileName, _O_CREAT|_O_TRUNC|_O_WRONLY|_O_BINARY, _S_IREAD|_S_IWRITE)) == -1) + { + TCfree(keyfile); + NormalCursor(); + handleWin32Error (hwndDlg, SRC_POS); + return 1; + } + + if (bRandomSize) + { + /* Generate a random size */ + if (!RandgetBytes (hwndDlg, (unsigned char*) &keyfilesSize, sizeof(keyfilesSize), FALSE)) + { + _close (fhKeyfile); + DeleteFile (szFileName); + TCfree(keyfile); + NormalCursor(); + return 1; + } + + /* since keyfilesSize < 1024 * 1024, we mask with 0x000FFFFF */ + keyfilesSize = (long) (((unsigned long) keyfilesSize) & 0x000FFFFF); + + keyfilesSize %= ((KEYFILE_MAX_READ_LEN - 64) + 1); + keyfilesSize += 64; + } + + /* Generate the keyfile */ + if (!RandgetBytesFull (hwndDlg, keyfile, keyfilesSize, TRUE, TRUE)) + { + _close (fhKeyfile); + DeleteFile (szFileName); + TCfree(keyfile); + NormalCursor(); + return 1; + } + + /* Write the keyfile */ + status = _write (fhKeyfile, keyfile, keyfilesSize); + burn (keyfile, keyfilesSize); + _close (fhKeyfile); + + if (status == -1) + { + TCfree(keyfile); + NormalCursor(); + handleWin32Error (hwndDlg, SRC_POS); + return 1; + } + } + + TCfree(keyfile); + NormalCursor(); + + Info("KEYFILE_CREATED", hwndDlg); + + return 1; + } + return 0; + + case WM_CLOSE: + { + wchar_t tmp[RNG_POOL_SIZE+1]; +exit: + WaitCursor(); + KillTimer (hwndDlg, 0xfd); + +#ifndef VOLFORMAT + RandStop (FALSE); +#endif + /* Cleanup */ + + burn (randPool, sizeof(randPool)); + burn (lastRandPool, sizeof(lastRandPool)); + burn (outputDispBuffer, sizeof(outputDispBuffer)); + burn (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); + burn (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); + burn (maskRandPool, sizeof(maskRandPool)); + + // Attempt to wipe the pool contents in the GUI text area + wmemset (tmp, L' ', RNG_POOL_SIZE); + tmp [RNG_POOL_SIZE] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), tmp); + + EndDialog (hwndDlg, IDCLOSE); + NormalCursor (); + return 1; + } + } + return 0; +} + + + +/* Except in response to the WM_INITDIALOG message, the dialog box procedure +should return nonzero if it processes the message, and zero if it does +not. - see DialogProc */ +BOOL CALLBACK +CipherTestDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + static int idTestCipher = -1; /* Currently selected cipher for the test vector facility (none = -1). */ + static BOOL bXTSTestEnabled = FALSE; + + PCRYPTO_INFO ci; + WORD lw = LOWORD (wParam); + WORD hw = HIWORD (wParam); + + switch (uMsg) + { + case WM_INITDIALOG: + { + int ea; + wchar_t buf[100]; + + LocalizeDialog (hwndDlg, "IDD_CIPHER_TEST_DLG"); + + SendMessage(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), WM_SETFONT, (WPARAM)hBoldFont, MAKELPARAM(TRUE,0)); + SendMessage(GetDlgItem(hwndDlg, IDC_KEY), EM_LIMITTEXT, 128,0); + SendMessage(GetDlgItem(hwndDlg, IDC_KEY), WM_SETFONT, (WPARAM)hFixedDigitFont, MAKELPARAM(1,0)); + SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT), EM_LIMITTEXT,64,0); + SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT), WM_SETFONT, (WPARAM)hFixedDigitFont, MAKELPARAM(1,0)); + SendMessage(GetDlgItem(hwndDlg, IDC_CIPHERTEXT), EM_LIMITTEXT,64,0); + SendMessage(GetDlgItem(hwndDlg, IDC_CIPHERTEXT), WM_SETFONT, (WPARAM)hFixedDigitFont, MAKELPARAM(1,0)); + SendMessage(GetDlgItem(hwndDlg, IDC_SECONDARY_KEY), EM_LIMITTEXT, 128,0); + SendMessage(GetDlgItem(hwndDlg, IDC_SECONDARY_KEY), WM_SETFONT, (WPARAM)hFixedDigitFont, MAKELPARAM(1,0)); + SendMessage(GetDlgItem(hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), EM_LIMITTEXT,32,0); + SendMessage(GetDlgItem(hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), WM_SETFONT, (WPARAM)hFixedDigitFont, MAKELPARAM(1,0)); + SetCheckBox (hwndDlg, IDC_XTS_MODE_ENABLED, bXTSTestEnabled); + EnableWindow (GetDlgItem (hwndDlg, IDC_SECONDARY_KEY), bXTSTestEnabled); + EnableWindow (GetDlgItem (hwndDlg, IDT_SECONDARY_KEY), bXTSTestEnabled); + EnableWindow (GetDlgItem (hwndDlg, IDC_TEST_BLOCK_NUMBER), bXTSTestEnabled); + EnableWindow (GetDlgItem (hwndDlg, IDT_TEST_BLOCK_NUMBER), bXTSTestEnabled); + EnableWindow (GetDlgItem (hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), bXTSTestEnabled); + EnableWindow (GetDlgItem (hwndDlg, IDT_TEST_DATA_UNIT_NUMBER), bXTSTestEnabled); + + if (idTestCipher == -1) + idTestCipher = (int) lParam; + + SendMessage (GetDlgItem (hwndDlg, IDC_CIPHER), CB_RESETCONTENT, 0, 0); + for (ea = EAGetFirst (); ea != 0; ea = EAGetNext (ea)) + { + if (EAGetCipherCount (ea) == 1 && EAIsFormatEnabled (ea)) + AddComboPair (GetDlgItem (hwndDlg, IDC_CIPHER), EAGetName (buf, ea, 1), EAGetFirstCipher (ea)); + } + + ResetCipherTest(hwndDlg, idTestCipher); + + SelectAlgo (GetDlgItem (hwndDlg, IDC_CIPHER), &idTestCipher); + + return 1; + } + + case WM_COMMAND: + + if (hw == CBN_SELCHANGE && lw == IDC_CIPHER) + { + idTestCipher = (int) SendMessage (GetDlgItem (hwndDlg, IDC_CIPHER), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_CIPHER), CB_GETCURSEL, 0, 0), 0); + ResetCipherTest(hwndDlg, idTestCipher); + SendMessage (hwndDlg, WM_INITDIALOG, 0, 0); + return 1; + } + + if (hw == CBN_SELCHANGE && lw == IDC_KEY_SIZE) + { + // NOP + return 1; + } + + if (lw == IDC_RESET) + { + ResetCipherTest(hwndDlg, idTestCipher); + + return 1; + } + + if (lw == IDC_AUTO) + { + WaitCursor (); + if (!AutoTestAlgorithms()) + { + ShowWindow(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), SW_SHOWNORMAL); + SetWindowTextW(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), GetString ("TESTS_FAILED")); + } + else + { + ShowWindow(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), SW_SHOWNORMAL); + SetWindowTextW(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), GetString ("TESTS_PASSED")); + ShowWindow(GetDlgItem(hwndDlg, IDC_REDTICK), SW_SHOWNORMAL); + } + NormalCursor (); + + return 1; + + } + + if (lw == IDC_XTS_MODE_ENABLED) + { + bXTSTestEnabled = GetCheckBox (hwndDlg, IDC_XTS_MODE_ENABLED); + EnableWindow (GetDlgItem (hwndDlg, IDC_SECONDARY_KEY), bXTSTestEnabled); + EnableWindow (GetDlgItem (hwndDlg, IDT_SECONDARY_KEY), bXTSTestEnabled); + EnableWindow (GetDlgItem (hwndDlg, IDC_TEST_BLOCK_NUMBER), bXTSTestEnabled); + EnableWindow (GetDlgItem (hwndDlg, IDT_TEST_BLOCK_NUMBER), bXTSTestEnabled); + EnableWindow (GetDlgItem (hwndDlg, IDT_TEST_DATA_UNIT_NUMBER), bXTSTestEnabled); + EnableWindow (GetDlgItem (hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), bXTSTestEnabled); + if (bXTSTestEnabled) + SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_SETCURSEL, 0,0); + } + + if (lw == IDOK || lw == IDC_ENCRYPT || lw == IDC_DECRYPT) + { + char key[128+1], inputtext[128+1], secondaryKey[64+1], dataUnitNo[16+1]; + wchar_t szTmp[128+1]; + int ks, pt, n, tlen, blockNo = 0; + BOOL bEncrypt; + + ShowWindow(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), SW_HIDE); + ShowWindow(GetDlgItem(hwndDlg, IDC_REDTICK), SW_HIDE); + + ks = (int) SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_GETCURSEL, 0,0); + ks = (int) SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_GETITEMDATA, ks,0); + pt = (int) SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_GETITEMDATA, 0,0); + + bEncrypt = lw == IDC_ENCRYPT; + + memset(key,0,sizeof(key)); + memset(szTmp,0,sizeof(szTmp)); + n = GetWindowText(GetDlgItem(hwndDlg, IDC_KEY), szTmp, ARRAYSIZE(szTmp)); + if (n != ks * 2) + { + Warning ("TEST_KEY_SIZE", hwndDlg); + return 1; + } + + for (n = 0; n < ks; n ++) + { + wchar_t szTmp2[3], *ptr; + long x; + + szTmp2[2] = 0; + szTmp2[0] = szTmp[n * 2]; + szTmp2[1] = szTmp[n * 2 + 1]; + + x = wcstol(szTmp2, &ptr, 16); + + key[n] = (char) x; + } + + memset(inputtext, 0, sizeof(inputtext)); + memset(secondaryKey, 0, sizeof(secondaryKey)); + memset(dataUnitNo, 0, sizeof(dataUnitNo)); + memset(szTmp, 0, sizeof(szTmp)); + + if (bEncrypt) + { + n = GetWindowText(GetDlgItem(hwndDlg, IDC_PLAINTEXT), szTmp, ARRAYSIZE(szTmp)); + } + else + { + n = GetWindowText(GetDlgItem(hwndDlg, IDC_CIPHERTEXT), szTmp, ARRAYSIZE(szTmp)); + } + + if (n != pt * 2) + { + if (bEncrypt) + { + Warning ("TEST_PLAINTEXT_SIZE", hwndDlg); + return 1; + } + else + { + Warning ("TEST_CIPHERTEXT_SIZE", hwndDlg); + return 1; + } + } + + for (n = 0; n < pt; n ++) + { + wchar_t szTmp2[3], *ptr; + long x; + + szTmp2[2] = 0; + szTmp2[0] = szTmp[n * 2]; + szTmp2[1] = szTmp[n * 2 + 1]; + + x = wcstol(szTmp2, &ptr, 16); + + inputtext[n] = (char) x; + } + + // XTS + if (bXTSTestEnabled) + { + // Secondary key + + if (GetWindowText(GetDlgItem(hwndDlg, IDC_SECONDARY_KEY), szTmp, ARRAYSIZE(szTmp)) != 64) + { + Warning ("TEST_INCORRECT_SECONDARY_KEY_SIZE", hwndDlg); + return 1; + } + + for (n = 0; n < 64; n ++) + { + wchar_t szTmp2[3], *ptr; + long x; + + szTmp2[2] = 0; + szTmp2[0] = szTmp[n * 2]; + szTmp2[1] = szTmp[n * 2 + 1]; + + x = wcstol(szTmp2, &ptr, 16); + + secondaryKey[n] = (char) x; + } + + // Data unit number + + tlen = GetWindowText(GetDlgItem(hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), szTmp, ARRAYSIZE(szTmp)); + + if (tlen > 16 || tlen < 1) + { + Warning ("TEST_INCORRECT_TEST_DATA_UNIT_SIZE", hwndDlg); + return 1; + } + + LeftPadString (szTmp, tlen, 16, L'0'); + + for (n = 0; n < 16; n ++) + { + wchar_t szTmp2[3], *ptr; + long x; + + szTmp2[2] = 0; + szTmp2[0] = szTmp[n * 2]; + szTmp2[1] = szTmp[n * 2 + 1]; + + x = wcstol(szTmp2, &ptr, 16); + + dataUnitNo[n] = (char) x; + } + + // Block number + + blockNo = (int) SendMessage (GetDlgItem (hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_GETCURSEL, 0, 0), 0); + } // if (bXTSTestEnabled) + + + /* Perform the actual tests */ + + if (ks != CB_ERR && pt != CB_ERR) + { + char tmp[128]; + int tmpRetVal; + + /* Copy the plain/ciphertext */ + memcpy(tmp,inputtext, pt); + + if (bXTSTestEnabled) + { + UINT64_STRUCT structDataUnitNo; + + /* XTS mode */ + + ci = crypto_open (); + if (!ci) + return 1; + + ci->mode = XTS; + + for (ci->ea = EAGetFirst (); ci->ea != 0 ; ci->ea = EAGetNext (ci->ea)) + if (EAGetCipherCount (ci->ea) == 1 && EAGetFirstCipher (ci->ea) == idTestCipher) + break; + + if ((tmpRetVal = EAInit (ci->ea, (unsigned char *) key, ci->ks)) != ERR_SUCCESS) + { + handleError (hwndDlg, tmpRetVal, SRC_POS); + crypto_close (ci); + return 1; + } + + memcpy (&ci->k2, secondaryKey, sizeof (secondaryKey)); + if (!EAInitMode (ci)) + { + crypto_close (ci); + return 1; + } + + structDataUnitNo.Value = BE64(((unsigned __int64 *)dataUnitNo)[0]); + + if (bEncrypt) + EncryptBufferXTS ((unsigned char *) tmp, pt, &structDataUnitNo, blockNo, (unsigned char *) (ci->ks), (unsigned char *) ci->ks2, idTestCipher); + else + DecryptBufferXTS ((unsigned char *) tmp, pt, &structDataUnitNo, blockNo, (unsigned char *) (ci->ks), (unsigned char *) ci->ks2, idTestCipher); + + crypto_close (ci); + } + else + { + + CipherInit2(idTestCipher, key, ks_tmp, ks); + + if (bEncrypt) + { + EncipherBlock(idTestCipher, tmp, ks_tmp); + } + else + { + DecipherBlock(idTestCipher, tmp, ks_tmp); + } + + } + *szTmp = 0; + + for (n = 0; n < pt; n ++) + { + wchar_t szTmp2[3]; + StringCbPrintfW(szTmp2, sizeof(szTmp2), L"%02x", (int)((unsigned char)tmp[n])); + StringCbCatW(szTmp, sizeof(szTmp), szTmp2); + } + + if (bEncrypt) + SetWindowText(GetDlgItem(hwndDlg,IDC_CIPHERTEXT), szTmp); + else + SetWindowText(GetDlgItem(hwndDlg,IDC_PLAINTEXT), szTmp); + } + + return 1; + } + + if (lw == IDCLOSE || lw == IDCANCEL) + { + idTestCipher = -1; + EndDialog (hwndDlg, 0); + return 1; + } + break; + + case WM_CLOSE: + idTestCipher = -1; + EndDialog (hwndDlg, 0); + return 1; + } + + return 0; +} + +void +ResetCipherTest(HWND hwndDlg, int idTestCipher) +{ + int ndx; + + ShowWindow(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), SW_HIDE); + ShowWindow(GetDlgItem(hwndDlg, IDC_REDTICK), SW_HIDE); + + EnableWindow(GetDlgItem(hwndDlg,IDC_KEY_SIZE), FALSE); + + /* Setup the keysize and plaintext sizes for the selected cipher */ + + SendMessage (GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_RESETCONTENT, 0,0); + SendMessage (GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_RESETCONTENT, 0,0); + SendMessage (GetDlgItem(hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_RESETCONTENT, 0,0); + + ndx = (int) SendMessage (GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_ADDSTRING, 0,(LPARAM) L"64"); + SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_SETITEMDATA, ndx,(LPARAM) 8); + SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_SETCURSEL, ndx,0); + + for (ndx = 0; ndx < BLOCKS_PER_XTS_DATA_UNIT; ndx++) + { + wchar_t tmpStr [16]; + + StringCbPrintfW (tmpStr, sizeof(tmpStr), L"%d", ndx); + + ndx = (int) SendMessage (GetDlgItem(hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_ADDSTRING, 0,(LPARAM) tmpStr); + SendMessage(GetDlgItem(hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_SETITEMDATA, ndx,(LPARAM) ndx); + } + + SendMessage(GetDlgItem(hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_SETCURSEL, 0, 0); + + SetWindowText(GetDlgItem(hwndDlg, IDC_SECONDARY_KEY), L"0000000000000000000000000000000000000000000000000000000000000000"); + SetWindowText(GetDlgItem(hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), L"0"); + + SetWindowText(GetDlgItem(hwndDlg, IDC_PLAINTEXT), L"0000000000000000"); + SetWindowText(GetDlgItem(hwndDlg, IDC_CIPHERTEXT), L"0000000000000000"); + + if (idTestCipher == AES || idTestCipher == SERPENT || idTestCipher == TWOFISH) + { + ndx = (int) SendMessage (GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_ADDSTRING, 0,(LPARAM) L"256"); + SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_SETITEMDATA, ndx,(LPARAM) 32); + SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_SETCURSEL, ndx,0); + + SendMessage (GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_RESETCONTENT, 0,0); + ndx = (int) SendMessage (GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_ADDSTRING, 0,(LPARAM) L"128"); + SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_SETITEMDATA, ndx,(LPARAM) 16); + SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_SETCURSEL, ndx,0); + + SetWindowText(GetDlgItem(hwndDlg, IDC_KEY), L"0000000000000000000000000000000000000000000000000000000000000000"); + SetWindowText(GetDlgItem(hwndDlg, IDC_PLAINTEXT), L"00000000000000000000000000000000"); + SetWindowText(GetDlgItem(hwndDlg, IDC_CIPHERTEXT), L"00000000000000000000000000000000"); + } +} + +#endif // #ifndef SETUP + + +BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + int nChoiceIDs [MAX_MULTI_CHOICES+1] = { IDC_MULTI_CHOICE_MSG, IDC_CHOICE1, IDC_CHOICE2, IDC_CHOICE3, + IDC_CHOICE4, IDC_CHOICE5, IDC_CHOICE6, IDC_CHOICE7, IDC_CHOICE8, IDC_CHOICE9, IDC_CHOICE10 }; + int nBaseButtonWidth = 0; + int nBaseButtonHeight = 0; + int nActiveChoices = -1; + int nStr = 0; + int vertSubOffset, horizSubOffset, vertMsgHeightOffset; + int vertOffset = 0; + int nLongestButtonCaptionWidth = 6; + int nLongestButtonCaptionCharLen = 1; + int nTextGfxLineHeight = 0; + int nMainTextLenInChars = 0; + int newLineSeqCount = 0; + RECT rec, wrec, wtrec, trec; + BOOL bResolve; + + WORD lw = LOWORD (wParam); + + switch (uMsg) + { + case WM_INITDIALOG: + { + char **pStr = (char **) ((MULTI_CHOICE_DLGPROC_PARAMS *) lParam)->strings; + char **pStrOrig = pStr; + wchar_t **pwStr = (wchar_t **) ((MULTI_CHOICE_DLGPROC_PARAMS *) lParam)->strings; + wchar_t **pwStrOrig = pwStr; + + LocalizeDialog (hwndDlg, NULL); + + SetWindowPos (hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + SetWindowPos (hwndDlg, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + + bResolve = (*pStr == NULL); + + // Style + if (((MULTI_CHOICE_DLGPROC_PARAMS *) lParam)->bold) + { + SendMessage (GetDlgItem (hwndDlg, IDC_MULTI_CHOICE_MSG), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + } + + // Process the strings + pStr++; + pwStr++; + + do + { + if (*pStr != 0) + { + SetWindowTextW (GetDlgItem(hwndDlg, nChoiceIDs[nStr]), bResolve ? GetString(*pStr) : *pwStr); + + if (nStr > 0) + { + nLongestButtonCaptionWidth = max ( + GetTextGfxWidth (GetDlgItem(hwndDlg, IDC_CHOICE1), + bResolve ? GetString(*pStr) : *pwStr, + hUserFont), + nLongestButtonCaptionWidth); + + nLongestButtonCaptionCharLen = max (nLongestButtonCaptionCharLen, + (int) wcslen ((const wchar_t *) (bResolve ? GetString(*pStr) : *pwStr))); + } + + nActiveChoices++; + pStr++; + pwStr++; + } + else + { + ShowWindow(GetDlgItem(hwndDlg, nChoiceIDs[nStr]), SW_HIDE); + } + nStr++; + + } while (nStr < MAX_MULTI_CHOICES+1); + + // Length of main message in characters (not bytes) + nMainTextLenInChars = (int) wcslen ((const wchar_t *) (bResolve ? GetString(*(pStrOrig+1)) : *(pwStrOrig+1))); + + if (nMainTextLenInChars > 200 + && nMainTextLenInChars / nLongestButtonCaptionCharLen >= 10) + { + // As the main text is longer than 200 characters, we will "pad" the widest button caption with + // spaces (if it is not wide enough) so as to increase the width of the whole dialog window. + // Otherwise, it would look too tall (dialog boxes look better when they are more wide than tall). + nLongestButtonCaptionWidth = CompensateXDPI (max ( + nLongestButtonCaptionWidth, + min (350, nMainTextLenInChars))); + } + + // Get the window coords + GetWindowRect(hwndDlg, &wrec); + + // Get the base button size + GetClientRect(GetDlgItem(hwndDlg, IDC_CHOICE1), &rec); + nBaseButtonWidth = rec.right + 2; + nBaseButtonHeight = rec.bottom + 2; + + // Increase in width based on the gfx length of the widest button caption + horizSubOffset = min (CompensateXDPI (500), max (0, nLongestButtonCaptionWidth + CompensateXDPI (50) - nBaseButtonWidth)); + + // Vertical "title bar" offset + GetClientRect(hwndDlg, &wtrec); + vertOffset = wrec.bottom - wrec.top - wtrec.bottom - GetSystemMetrics(SM_CYFIXEDFRAME); + + // Height/width of the message text + GetClientRect(GetDlgItem(hwndDlg, IDC_MULTI_CHOICE_MSG), &trec); + + // Determine the number of newlines contained in the message text + { + int64 offset = -1; + + do + { + offset = FindString ((char *) (bResolve ? GetString(*(pStrOrig+1)) : *(pwStrOrig+1)), + (char *) L"\n", + nMainTextLenInChars * 2, + (int) wcslen (L"\n") * 2, + offset + 1); + + newLineSeqCount++; + + } while (offset != -1); + } + + nTextGfxLineHeight = GetTextGfxHeight (GetDlgItem(hwndDlg, IDC_MULTI_CHOICE_MSG), + bResolve ? GetString(*(pStrOrig+1)) : *(pwStrOrig+1), + hUserFont); + + vertMsgHeightOffset = ((GetTextGfxWidth (GetDlgItem(hwndDlg, IDC_MULTI_CHOICE_MSG), + bResolve ? GetString(*(pStrOrig+1)) : *(pwStrOrig+1), + hUserFont) / (trec.right + horizSubOffset) + 1) * nTextGfxLineHeight) - trec.bottom; + + vertMsgHeightOffset = min (CompensateYDPI (350), vertMsgHeightOffset + newLineSeqCount * nTextGfxLineHeight + (trec.bottom + vertMsgHeightOffset) / 10); // As reserve, we are adding 10% and the number of lines equal to the number of newlines in the message + + // Reduction in height according to the number of shown buttons + vertSubOffset = ((MAX_MULTI_CHOICES - nActiveChoices) * nBaseButtonHeight); + + if (horizSubOffset > 0 + || vertMsgHeightOffset > 0 + || vertOffset > 0) + { + // Resize/move each button if necessary + for (nStr = 1; nStr < MAX_MULTI_CHOICES+1; nStr++) + { + GetWindowRect(GetDlgItem(hwndDlg, nChoiceIDs[nStr]), &rec); + + MoveWindow (GetDlgItem(hwndDlg, nChoiceIDs[nStr]), + rec.left - wrec.left - GetSystemMetrics(SM_CXFIXEDFRAME), + rec.top - wrec.top - vertOffset + vertMsgHeightOffset, + nBaseButtonWidth + horizSubOffset, + nBaseButtonHeight, + TRUE); + } + + // Resize/move the remaining GUI elements + GetWindowRect(GetDlgItem(hwndDlg, IDC_MULTI_CHOICE_MSG), &rec); + GetClientRect(GetDlgItem(hwndDlg, IDC_MULTI_CHOICE_MSG), &trec); + MoveWindow (GetDlgItem(hwndDlg, IDC_MULTI_CHOICE_MSG), + rec.left - wrec.left - GetSystemMetrics(SM_CXFIXEDFRAME), + rec.top - wrec.top - vertOffset, + trec.right + 2 + horizSubOffset, + trec.bottom + 2 + vertMsgHeightOffset, + TRUE); + + GetWindowRect(GetDlgItem(hwndDlg, IDC_MC_DLG_HR1), &rec); + GetClientRect(GetDlgItem(hwndDlg, IDC_MC_DLG_HR1), &trec); + MoveWindow (GetDlgItem(hwndDlg, IDC_MC_DLG_HR1), + rec.left - wrec.left - GetSystemMetrics(SM_CXFIXEDFRAME), + rec.top - wrec.top - vertOffset, + trec.right + 2 + horizSubOffset, + trec.bottom + 2, + TRUE); + + GetWindowRect(GetDlgItem(hwndDlg, IDC_MC_DLG_HR2), &rec); + GetClientRect(GetDlgItem(hwndDlg, IDC_MC_DLG_HR2), &trec); + MoveWindow (GetDlgItem(hwndDlg, IDC_MC_DLG_HR2), + rec.left - wrec.left - GetSystemMetrics(SM_CXFIXEDFRAME), + rec.top - wrec.top - vertOffset + vertMsgHeightOffset, + trec.right + 2 + horizSubOffset, + trec.bottom + 2, + TRUE); + } + + // Resize the window according to number of shown buttons and the longest button caption + MoveWindow (hwndDlg, + wrec.left - horizSubOffset / 2, + wrec.top + vertSubOffset / 2 - vertMsgHeightOffset / 2, + wrec.right - wrec.left + horizSubOffset, + wrec.bottom - wrec.top - vertSubOffset + 1 + vertMsgHeightOffset, + TRUE); + + DisableCloseButton (hwndDlg); + + return 1; + } + + case WM_COMMAND: + + if (lw == IDCLOSE || lw == IDCANCEL) + { + EndDialog (hwndDlg, 0); + return 1; + } + + for (nStr = 1; nStr < MAX_MULTI_CHOICES+1; nStr++) + { + if (lw == nChoiceIDs[nStr]) + { + EndDialog (hwndDlg, nStr); + return 1; + } + } + break; + + case WM_CLOSE: + // This prevents the window from being closed by pressing Alt-F4 (the Close button is hidden). + // Note that the OS handles modal MessageBox() dialog windows the same way. + return 1; + } + + return 0; +} + + +BOOL CheckCapsLock (HWND hwnd, BOOL quiet) +{ + if ((GetKeyState(VK_CAPITAL) & 1) != 0) + { + if (!quiet) + { + MessageBoxW (hwnd, GetString ("CAPSLOCK_ON"), lpszTitle, MB_ICONEXCLAMATION); + } + return TRUE; + } + return FALSE; +} + + +// Checks whether the file extension is not used for executable files or similarly problematic, which often +// causes Windows and antivirus software to interfere with the container. +BOOL CheckFileExtension (wchar_t *fileName) +{ + int i = 0; + wchar_t *ext = wcsrchr (fileName, L'.'); + static wchar_t *problemFileExt[] = { + // These are protected by the Windows Resource Protection + L".asa", L".asp", L".aspx", L".ax", L".bas", L".bat", L".bin", L".cer", L".chm", L".clb", L".cmd", L".cnt", L".cnv", + L".com", L".cpl", L".cpx", L".crt", L".csh", L".dll", L".drv", L".dtd", L".exe", L".fxp", L".grp", L".h1s", L".hlp", + L".hta", L".ime", L".inf", L".ins", L".isp", L".its", L".js", L".jse", L".ksh", L".lnk", L".mad", L".maf", L".mag", + L".mam", L".man", L".maq", L".mar", L".mas", L".mat", L".mau", L".mav", L".maw", L".mda", L".mdb", L".mde", L".mdt", + L".mdw", L".mdz", L".msc", L".msi", L".msp", L".mst", L".mui", L".nls", L".ocx", L".ops", L".pal", L".pcd", L".pif", + L".prf", L".prg", L".pst", L".reg", L".scf", L".scr", L".sct", L".shb", L".shs", L".sys", L".tlb", L".tsp", L".url", + L".vb", L".vbe", L".vbs", L".vsmacros", L".vss", L".vst", L".vsw", L".ws", L".wsc", L".wsf", L".wsh", L".xsd", L".xsl", + // These additional file extensions are usually watched by antivirus programs + L".386", L".acm", L".ade", L".adp", L".ani", L".app", L".asd", L".asf", L".asx", L".awx", L".ax", L".boo", L".bz2", L".cdf", + L".class", L".dhtm", L".dhtml",L".dlo", L".emf", L".eml", L".flt", L".fot", L".gz", L".hlp", L".htm", L".html", L".ini", + L".j2k", L".jar", L".jff", L".jif", L".jmh", L".jng", L".jp2", L".jpe", L".jpeg", L".jpg", L".lsp", L".mod", L".nws", + L".obj", L".olb", L".osd", L".ov1", L".ov2", L".ov3", L".ovl", L".ovl", L".ovr", L".pdr", L".pgm", L".php", L".pkg", + L".pl", L".png", L".pot", L".pps", L".ppt", L".ps1", L".ps1xml", L".psc1", L".rar", L".rpl", L".rtf", L".sbf", L".script", L".sh", L".sha", L".shtm", + L".shtml", L".spl", L".swf", L".tar", L".tgz", L".tmp", L".ttf", L".vcs", L".vlm", L".vxd", L".vxo", L".wiz", L".wll", L".wmd", + L".wmf", L".wms", L".wmz", L".wpc", L".wsc", L".wsh", L".wwk", L".xhtm", L".xhtml", L".xl", L".xml", L".zip", L".7z", 0}; + + if (!ext) + return FALSE; + + while (problemFileExt[i]) + { + if (!_wcsicmp (ext, problemFileExt[i++])) + return TRUE; + } + + return FALSE; +} + +void CorrectFileName (wchar_t* fileName) +{ + /* replace '/' by '\' */ + size_t i, len = wcslen (fileName); + for (i = 0; i < len; i++) + { + if (fileName [i] == L'/') + fileName [i] = L'\\'; + } +} + +void IncreaseWrongPwdRetryCount (int count) +{ + WrongPwdRetryCounter += count; +} + + +void ResetWrongPwdRetryCount (void) +{ + WrongPwdRetryCounter = 0; +} + + +BOOL WrongPwdRetryCountOverLimit (void) +{ + return (WrongPwdRetryCounter > TC_TRY_HEADER_BAK_AFTER_NBR_WRONG_PWD_TRIES); +} + +DWORD GetUsedLogicalDrives (void) +{ + DWORD dwUsedDrives = GetLogicalDrives(); + if (!bShowDisconnectedNetworkDrives) + { + static DWORD g_dwLastMappedDrives = 0; + static time_t g_lastCallTime = 0; + + EnterCriticalSection (&csWNetCalls); + + finally_do ({ LeaveCriticalSection (&csWNetCalls); }); + + /* update values every 2 seconds to reduce CPU consumption */ + if ((time (NULL) - g_lastCallTime) > 2) + { + /* detect disconnected mapped network shares and removed + * their associated drives from the list + */ + WCHAR remotePath[512]; + WCHAR drive[3] = {L'A', L':', 0}; + DWORD dwLen, status; + g_dwLastMappedDrives = 0; + for (WCHAR i = 0; i <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; i++) + { + if ((dwUsedDrives & (1 << i)) == 0) + { + drive[0] = L'A' + i; + dwLen = ARRAYSIZE (remotePath); + status = WNetGetConnection (drive, remotePath, &dwLen); + if ((NO_ERROR == status) || (status == ERROR_CONNECTION_UNAVAIL)) + { + /* this is a mapped network share, mark it as used */ + g_dwLastMappedDrives |= (1 << i); + } + } + } + + g_lastCallTime = time (NULL); + } + + dwUsedDrives |= g_dwLastMappedDrives; + } + + return dwUsedDrives; +} + + +int GetFirstAvailableDrive () +{ + DWORD dwUsedDrives = GetUsedLogicalDrives(); + int i, drive; + + /* let A: and B: be used as last resort since they can introduce side effects */ + for (i = 2; i < 28; i++) + { + drive = (i < 26) ? i : (i - 26); + if (!(dwUsedDrives & 1 << drive)) + return i; + } + + return -1; +} + + +int GetLastAvailableDrive () +{ + DWORD dwUsedDrives = GetUsedLogicalDrives(); + int i; + + for (i = 25; i >= 0; i--) + { + if (!(dwUsedDrives & 1 << i)) + return i; + } + + return -1; +} + + +BOOL IsDriveAvailable (int driveNo) +{ + return (GetUsedLogicalDrives() & (1 << driveNo)) == 0; +} + + +BOOL IsDeviceMounted (wchar_t *deviceName) +{ + BOOL bResult = FALSE; + DWORD dwResult; + HANDLE dev = INVALID_HANDLE_VALUE; + + if ((dev = CreateFile (deviceName, + GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + 0, + NULL)) != INVALID_HANDLE_VALUE) + { + bResult = DeviceIoControl (dev, FSCTL_IS_VOLUME_MOUNTED, NULL, 0, NULL, 0, &dwResult, NULL); + CloseHandle (dev); + } + + return bResult; +} + + +int DriverUnmountVolume (HWND hwndDlg, int nDosDriveNo, BOOL forced) +{ + UNMOUNT_STRUCT unmount; + DWORD dwResult; + VOLUME_PROPERTIES_STRUCT prop; + BOOL bResult; + WCHAR wszLabel[33] = {0}; + BOOL bDriverSetLabel = FALSE; + + memset (&prop, 0, sizeof(prop)); + prop.driveNo = nDosDriveNo; + + if ( DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL) + && prop.driveNo == nDosDriveNo + ) + { + memcpy (wszLabel, prop.wszLabel, sizeof (wszLabel)); + bDriverSetLabel = prop.bDriverSetLabel; + } + + unmount.nDosDriveNo = nDosDriveNo; + unmount.ignoreOpenFiles = forced; + + bResult = DeviceIoControl (hDriver, TC_IOCTL_DISMOUNT_VOLUME, &unmount, + sizeof (unmount), &unmount, sizeof (unmount), &dwResult, NULL); + + if (bResult == FALSE) + { + handleWin32Error (hwndDlg, SRC_POS); + return 1; + } + else if ((unmount.nReturnCode == ERR_SUCCESS) && bDriverSetLabel && wszLabel[0]) + UpdateDriveCustomLabel (nDosDriveNo, wszLabel, FALSE); + +#ifdef TCMOUNT + + if (unmount.nReturnCode == ERR_SUCCESS + && unmount.HiddenVolumeProtectionTriggered + && !VolumeNotificationsList.bHidVolDamagePrevReported [nDosDriveNo] + && !Silent) + { + wchar_t msg[4096]; + + VolumeNotificationsList.bHidVolDamagePrevReported [nDosDriveNo] = TRUE; + StringCbPrintfW (msg, sizeof(msg), GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), nDosDriveNo + L'A'); + SetForegroundWindow (hwndDlg); + MessageBoxW (hwndDlg, msg, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); + } + +#endif // #ifdef TCMOUNT + + return unmount.nReturnCode; +} + + +void BroadcastDeviceChange (WPARAM message, int nDosDriveNo, DWORD driveMap) +{ + DEV_BROADCAST_VOLUME dbv; + DWORD_PTR dwResult; + LONG eventId = 0; + int i; + + if (DeviceChangeBroadcastDisabled) + return; + + if (message == DBT_DEVICEARRIVAL) + eventId = SHCNE_DRIVEADD; + else if (message == DBT_DEVICEREMOVECOMPLETE) + eventId = SHCNE_DRIVEREMOVED; + else if (IsOSAtLeast (WIN_7) && message == DBT_DEVICEREMOVEPENDING) // Explorer on Windows 7 holds open handles of all drives when 'Computer' is expanded in navigation pane. SHCNE_DRIVEREMOVED must be used as DBT_DEVICEREMOVEPENDING is ignored. + eventId = SHCNE_DRIVEREMOVED; + + if (driveMap == 0) + driveMap = (1 << nDosDriveNo); + + if (eventId != 0) + { + for (i = 0; i < 26; i++) + { + if (driveMap & (1 << i)) + { + wchar_t root[] = { (wchar_t) i + L'A', L':', L'\\', 0 }; + SHChangeNotify (eventId, SHCNF_PATH, root, NULL); + + + } + } + } + + dbv.dbcv_size = sizeof (dbv); + dbv.dbcv_devicetype = DBT_DEVTYP_VOLUME; + dbv.dbcv_reserved = 0; + dbv.dbcv_unitmask = driveMap; + dbv.dbcv_flags = 0; + + UINT timeOut = 1000; + + // SHChangeNotify() works on Vista, so the Explorer does not require WM_DEVICECHANGE + if (CurrentOSMajor >= 6) + timeOut = 100; + + IgnoreWmDeviceChange = TRUE; + SendMessageTimeout (HWND_BROADCAST, WM_DEVICECHANGE, message, (LPARAM)(&dbv), SMTO_ABORTIFHUNG, timeOut, &dwResult); + + // Explorer prior Vista sometimes fails to register a new drive + if (CurrentOSMajor < 6 && message == DBT_DEVICEARRIVAL) + SendMessageTimeout (HWND_BROADCAST, WM_DEVICECHANGE, message, (LPARAM)(&dbv), SMTO_ABORTIFHUNG, 200, &dwResult); + + IgnoreWmDeviceChange = FALSE; +} + +BOOL GetPhysicalDriveAlignment(UINT nDriveNumber, STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR* pDesc) +{ + DWORD dwRet = NO_ERROR; + + if (!pDesc) + return FALSE; + + // Format physical drive path (may be '\\.\PhysicalDrive0', '\\.\PhysicalDrive1' and so on). + TCHAR strDrivePath[512]; + StringCbPrintf(strDrivePath, sizeof(strDrivePath), _T("\\\\.\\PhysicalDrive%u"), nDriveNumber); + + // Get a handle to physical drive + HANDLE hDevice = ::CreateFile(strDrivePath, 0, FILE_SHARE_READ, + NULL, OPEN_EXISTING, 0, NULL); + + if(INVALID_HANDLE_VALUE == hDevice) + return FALSE; + + // Set the input data structure + STORAGE_PROPERTY_QUERY storagePropertyQuery; + ZeroMemory(&storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY)); + storagePropertyQuery.PropertyId = StorageAccessAlignmentProperty; + storagePropertyQuery.QueryType = PropertyStandardQuery; + + // Get the necessary output buffer size + DWORD dwBytesReturned = 0; + BOOL bRet = ::DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY, + &storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY), + pDesc, sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR), + &dwBytesReturned, NULL); + dwRet = ::GetLastError(); + ::CloseHandle(hDevice); + + if (!bRet) + { + SetLastError (dwRet); + return FALSE; + } + else + return TRUE; +} + +/************************************************************/ + +// implementation of the generic wait dialog mechanism + +static UINT g_wmWaitDlg = ::RegisterWindowMessage(L"VeraCryptWaitDlgMessage"); + +typedef struct +{ + HWND hwnd; + void* pArg; + WaitThreadProc callback; +} WaitThreadParam; + +static void _cdecl WaitThread (void* pParam) +{ + WaitThreadParam* pThreadParam = (WaitThreadParam*) pParam; + + pThreadParam->callback(pThreadParam->pArg, pThreadParam->hwnd); + + /* close the wait dialog */ + PostMessage (pThreadParam->hwnd, g_wmWaitDlg, 0, 0); +} + +BOOL CALLBACK WaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + WaitThreadParam* thParam = (WaitThreadParam*) lParam; + + // set the progress bar type to MARQUEE (indefinite progress) + HWND hProgress = GetDlgItem (hwndDlg, IDC_WAIT_PROGRESS_BAR); + if (hProgress) + { + SetWindowLongPtrW (hProgress, GWL_STYLE, PBS_MARQUEE | GetWindowLongPtrW (hProgress, GWL_STYLE)); + ::SendMessageW(hProgress, PBM_SETMARQUEE, (WPARAM) TRUE, (LPARAM) 0); + } + + thParam->hwnd = hwndDlg; + + // For now, we don't have system menu is the resources but we leave this code + // if it is enabled in the future + HMENU hSysMenu = GetSystemMenu(hwndDlg, FALSE); + if (hSysMenu) + { + //disable the X + EnableMenuItem(hSysMenu,SC_CLOSE, MF_BYCOMMAND|MF_GRAYED); + + // set icons + HICON hIcon = (HICON)::LoadImage(hInst, MAKEINTRESOURCE(IDI_TRUECRYPT_ICON), IMAGE_ICON, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR); + ::SendMessage(hwndDlg, WM_SETICON, TRUE, (LPARAM)hIcon); + HICON hIconSmall = (HICON)::LoadImage(hInst, MAKEINTRESOURCE(IDI_TRUECRYPT_ICON), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR); + ::SendMessage(hwndDlg, WM_SETICON, FALSE, (LPARAM)hIconSmall); + } + + LocalizeDialog (hwndDlg, NULL); + _beginthread(WaitThread, 0, thParam); + return 0; + } + + case WM_COMMAND: + + if (lw == IDOK || lw == IDCANCEL) + return 1; + else + return 0; + + default: + if (msg == g_wmWaitDlg) + { + EndDialog (hwndDlg, IDOK); + return 1; + } + return 0; + } +} + + +void BringToForeground(HWND hWnd) +{ + if(!::IsWindow(hWnd)) return; + + DWORD lockTimeOut = 0; + HWND hCurrWnd = ::GetForegroundWindow(); + DWORD dwThisTID = ::GetCurrentThreadId(), + dwCurrTID = ::GetWindowThreadProcessId(hCurrWnd,0); + + if (hCurrWnd != hWnd) + { + if(dwThisTID != dwCurrTID) + { + ::AttachThreadInput(dwThisTID, dwCurrTID, TRUE); + + ::SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT,0,&lockTimeOut,0); + ::SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT,0,0,SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE); + + ::AllowSetForegroundWindow(ASFW_ANY); + } + + ::SetForegroundWindow(hWnd); + + if(dwThisTID != dwCurrTID) + { + ::SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT,0,(PVOID)lockTimeOut,SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE); + ::AttachThreadInput(dwThisTID, dwCurrTID, FALSE); + } + } + +#ifdef TCMOUNT + if (hWnd == MainDlg) + { + SetFocus (hWnd); + ::SendMessage(hWnd, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hWnd, IDC_DRIVELIST), 1L); + } +#endif +} + +void ShowWaitDialog(HWND hwnd, BOOL bUseHwndAsParent, WaitThreadProc callback, void* pArg) +{ + HWND hParent = (hwnd && bUseHwndAsParent)? hwnd : GetDesktopWindow(); + BOOL bEffectiveHideWaitingDialog = bCmdHideWaitingDialogValid? bCmdHideWaitingDialog : bHideWaitingDialog; + WaitThreadParam threadParam; + threadParam.callback = callback; + threadParam.pArg = pArg; + + if (WaitDialogDisplaying || bEffectiveHideWaitingDialog) + { + if (!WaitDialogDisplaying) WaitCursor (); + callback (pArg, hwnd); + if (!WaitDialogDisplaying) NormalCursor (); + } + else + { + BOOL bIsForeground = FALSE; + WaitDialogDisplaying = TRUE; + if (hwnd) + { + if (GetForegroundWindow () == hwnd) + bIsForeground = TRUE; + EnableWindow (hwnd, FALSE); + } + else + EnableWindow (MainDlg, FALSE); + finally_do_arg2 (HWND, hwnd, BOOL, bIsForeground, { if (finally_arg) {EnableWindow(finally_arg, TRUE); if (finally_arg2) BringToForeground (finally_arg);} else EnableWindow (MainDlg, TRUE);}); + + DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_STATIC_MODAL_WAIT_DLG), hParent, + (DLGPROC) WaitDlgProc, (LPARAM) &threadParam); + + WaitDialogDisplaying = FALSE; + } +} + +/************************************************************************/ + +static BOOL PerformMountIoctl (MOUNT_STRUCT* pmount, LPDWORD pdwResult, BOOL useVolumeID, BYTE volumeID[VOLUME_ID_SIZE]) +{ + if (useVolumeID) + { + wstring devicePath = FindDeviceByVolumeID (volumeID); + if (devicePath == L"") + { + if (pdwResult) + *pdwResult = 0; + SetLastError (ERROR_PATH_NOT_FOUND); + return FALSE; + } + else + { + BOOL bDevice = FALSE; + CreateFullVolumePath (pmount->wszVolume, sizeof(pmount->wszVolume), devicePath.c_str(), &bDevice); + } + } + + return DeviceIoControl (hDriver, TC_IOCTL_MOUNT_VOLUME, pmount, + sizeof (MOUNT_STRUCT), pmount, sizeof (MOUNT_STRUCT), pdwResult, NULL); +} + +// specific definitions and implementation for support of mount operation +// in wait dialog mechanism + +typedef struct +{ + MOUNT_STRUCT* pmount; + BOOL useVolumeID; + BYTE volumeID[VOLUME_ID_SIZE]; + BOOL* pbResult; + DWORD* pdwResult; + DWORD dwLastError; +} MountThreadParam; + +void CALLBACK MountWaitThreadProc(void* pArg, HWND ) +{ + MountThreadParam* pThreadParam = (MountThreadParam*) pArg; + + *(pThreadParam->pbResult) = PerformMountIoctl (pThreadParam->pmount, pThreadParam->pdwResult, pThreadParam->useVolumeID, pThreadParam->volumeID); + + pThreadParam->dwLastError = GetLastError (); +} + +/************************************************************************/ + +// Use only cached passwords if password = NULL +// +// Returns: +// -1 = user aborted mount / error +// 0 = mount failed +// 1 = mount OK +// 2 = mount OK in shared mode +// +// Note that some code calling this relies on the content of the mountOptions struct +// to remain unmodified (don't remove the 'const' without proper revision). + +int MountVolume (HWND hwndDlg, + int driveNo, + wchar_t *volumePath, + Password *password, + int pkcs5, + int pim, + BOOL truecryptMode, + BOOL cachePassword, + BOOL cachePim, + BOOL sharedAccess, + const MountOptions* const mountOptions, + BOOL quiet, + BOOL bReportWrongPassword) +{ + MOUNT_STRUCT mount; + DWORD dwResult, dwLastError = ERROR_SUCCESS; + BOOL bResult, bDevice; + wchar_t root[MAX_PATH]; + int favoriteMountOnArrivalRetryCount = 0; + BOOL useVolumeID = FALSE; + BYTE volumeID[VOLUME_ID_SIZE] = {0}; + +#ifdef TCMOUNT + if (mountOptions->PartitionInInactiveSysEncScope) + { + if (!CheckSysEncMountWithoutPBA (hwndDlg, volumePath, quiet)) + return -1; + } +#endif + + if (IsMountedVolume (volumePath)) + { + if (!quiet) + Error ("VOL_ALREADY_MOUNTED", hwndDlg); + return -1; + } + + if (!IsDriveAvailable (driveNo)) + { + if (!quiet) + Error ("DRIVE_LETTER_UNAVAILABLE", hwndDlg); + + return -1; + } + + // If using cached passwords, check cache status first + if (password == NULL && IsPasswordCacheEmpty ()) + return 0; + + ZeroMemory (&mount, sizeof (mount)); + mount.bExclusiveAccess = sharedAccess ? FALSE : TRUE; + mount.SystemFavorite = MountVolumesAsSystemFavorite; + mount.UseBackupHeader = mountOptions->UseBackupHeader; + mount.RecoveryMode = mountOptions->RecoveryMode; + StringCbCopyW (mount.wszLabel, sizeof (mount.wszLabel), mountOptions->Label); + +retry: + mount.nDosDriveNo = driveNo; + mount.bCache = cachePassword; + mount.bCachePim = cachePim; + + mount.bPartitionInInactiveSysEncScope = FALSE; + + if (password != NULL) + mount.VolumePassword = *password; + else + mount.VolumePassword.Length = 0; + + if (!mountOptions->ReadOnly && mountOptions->ProtectHiddenVolume) + { + mount.ProtectedHidVolPassword = mountOptions->ProtectedHidVolPassword; + mount.bProtectHiddenVolume = TRUE; + mount.ProtectedHidVolPkcs5Prf = mountOptions->ProtectedHidVolPkcs5Prf; + mount.ProtectedHidVolPim = mountOptions->ProtectedHidVolPim; + } + else + mount.bProtectHiddenVolume = FALSE; + + mount.bMountReadOnly = mountOptions->ReadOnly; + mount.bMountRemovable = mountOptions->Removable; + mount.bPreserveTimestamp = mountOptions->PreserveTimestamp; + + mount.bMountManager = TRUE; + mount.pkcs5_prf = pkcs5; + mount.bTrueCryptMode = truecryptMode; + mount.VolumePim = pim; + + // Windows 2000 mount manager causes problems with remounted volumes + if (CurrentOSMajor == 5 && CurrentOSMinor == 0) + mount.bMountManager = FALSE; + + wstring path = volumePath; + if (path.find (L"\\\\?\\") == 0) + { + // Remove \\?\ prefix + path = path.substr (4); + StringCchCopyW (volumePath, TC_MAX_PATH, path.c_str()); + } + + if (path.find (L"Volume{") == 0 && path.rfind (L"}\\") == path.size() - 2) + { + wstring resolvedPath = VolumeGuidPathToDevicePath (path); + + if (!resolvedPath.empty()) + StringCchCopyW (volumePath, TC_MAX_PATH, resolvedPath.c_str()); + } + + if ((path.length () >= 3) && (_wcsnicmp (path.c_str(), L"ID:", 3) == 0)) + { + std::vector arr; + if ( (path.length() == (3 + 2*VOLUME_ID_SIZE)) + && HexWideStringToArray (path.c_str() + 3, arr) + && (arr.size() == VOLUME_ID_SIZE) + ) + { + useVolumeID = TRUE; + bDevice = TRUE; + memcpy (volumeID, &arr[0], VOLUME_ID_SIZE); + } + else + { + if (!quiet) + Error ("VOLUME_ID_INVALID", hwndDlg); + + SetLastError (ERROR_INVALID_PARAMETER); + return -1; + } + } + else + CreateFullVolumePath (mount.wszVolume, sizeof(mount.wszVolume), volumePath, &bDevice); + + if (!bDevice) + { + // UNC path + if (path.find (L"\\\\") == 0) + { + StringCbCopyW (mount.wszVolume, sizeof (mount.wszVolume), (L"UNC" + path.substr (1)).c_str()); + } + + if (GetVolumePathName (volumePath, root, ARRAYSIZE (root) - 1)) + { + DWORD bps, flags, d; + if (GetDiskFreeSpace (root, &d, &bps, &d, &d)) + { + mount.BytesPerSector = bps; + mount.BytesPerPhysicalSector = bps; + } + + if (IsOSAtLeast (WIN_VISTA)) + { + if ( (wcslen(root) >= 2) + && (root[1] == L':') + && (towupper(root[0]) >= L'A' && towupper(root[0]) <= L'Z') + ) + { + wstring drivePath = L"\\\\.\\X:"; + HANDLE dev = INVALID_HANDLE_VALUE; + VOLUME_DISK_EXTENTS extents = {0}; + DWORD dwResult = 0; + drivePath[4] = root[0]; + + if ((dev = CreateFile (drivePath.c_str(),0, 0, NULL, OPEN_EXISTING, 0, NULL)) != INVALID_HANDLE_VALUE) + { + if (DeviceIoControl (dev, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &extents, sizeof(extents), &dwResult, NULL)) + { + if (extents.NumberOfDiskExtents > 0) + { + STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR desc; + if (GetPhysicalDriveAlignment (extents.Extents[0].DiskNumber, &desc)) + { + mount.BytesPerSector = desc.BytesPerLogicalSector; + mount.BytesPerPhysicalSector = desc.BytesPerPhysicalSector; + } + } + } + CloseHandle (dev); + } + } + } + + // Read-only host filesystem + if (!mount.bMountReadOnly && GetVolumeInformation (root, NULL, 0, NULL, &d, &flags, NULL, 0)) + mount.bMountReadOnly = (flags & FILE_READ_ONLY_VOLUME) != 0; + } + } + + if (mountOptions->PartitionInInactiveSysEncScope) + { + if (mount.wszVolume == NULL || swscanf_s ((const wchar_t *) mount.wszVolume, + WIDE("\\Device\\Harddisk%d\\Partition"), + &mount.nPartitionInInactiveSysEncScopeDriveNo, + sizeof(mount.nPartitionInInactiveSysEncScopeDriveNo)) != 1) + { + if (!quiet) + Warning ("NO_SYSENC_PARTITION_SELECTED", hwndDlg); + return -1; + } + + mount.bPartitionInInactiveSysEncScope = TRUE; + } + + if (!quiet) + { + MountThreadParam mountThreadParam; + mountThreadParam.pmount = &mount; + mountThreadParam.useVolumeID = useVolumeID; + memcpy (mountThreadParam.volumeID, volumeID, VOLUME_ID_SIZE); + mountThreadParam.pbResult = &bResult; + mountThreadParam.pdwResult = &dwResult; + mountThreadParam.dwLastError = ERROR_SUCCESS; + + ShowWaitDialog (hwndDlg, FALSE, MountWaitThreadProc, &mountThreadParam); + + dwLastError = mountThreadParam.dwLastError; + } + else + { + bResult = PerformMountIoctl (&mount, &dwResult, useVolumeID, volumeID); + + dwLastError = GetLastError (); + } + + burn (&mount.VolumePassword, sizeof (mount.VolumePassword)); + burn (&mount.ProtectedHidVolPassword, sizeof (mount.ProtectedHidVolPassword)); + burn (&mount.pkcs5_prf, sizeof (mount.pkcs5_prf)); + burn (&mount.bTrueCryptMode, sizeof (mount.bTrueCryptMode)); + burn (&mount.ProtectedHidVolPkcs5Prf, sizeof (mount.ProtectedHidVolPkcs5Prf)); + + SetLastError (dwLastError); + if (bResult == FALSE) + { + // Volume already open by another process + if (GetLastError () == ERROR_SHARING_VIOLATION) + { + if (FavoriteMountOnArrivalInProgress && ++favoriteMountOnArrivalRetryCount < 10) + { + Sleep (500); + goto retry; + } + + if (mount.bExclusiveAccess == FALSE) + { + if (!quiet) + Error ("FILE_IN_USE_FAILED", hwndDlg); + + return -1; + } + else + { + if (quiet) + { + mount.bExclusiveAccess = FALSE; + goto retry; + } + + // Ask user + if (IDYES == AskWarnNoYes ("FILE_IN_USE", hwndDlg)) + { + mount.bExclusiveAccess = FALSE; + goto retry; + } + } + + return -1; + } + + if (!quiet && (!MultipleMountOperationInProgress || GetLastError() != ERROR_NOT_READY)) + handleWin32Error (hwndDlg, SRC_POS); + + return -1; + } + + if (mount.nReturnCode != 0) + { + if (mount.nReturnCode == ERR_PASSWORD_WRONG) + { + // Do not report wrong password, if not instructed to + if (bReportWrongPassword) + { + IncreaseWrongPwdRetryCount (1); // We increase the count here only if bReportWrongPassword is TRUE, because "Auto-Mount All Devices" and other callers do it separately + + if (WrongPwdRetryCountOverLimit () + && !mount.UseBackupHeader) + { + // Retry using embedded header backup (if any) + mount.UseBackupHeader = TRUE; + goto retry; + } + + if (bDevice && mount.bProtectHiddenVolume) + { + int driveNo; + + if (swscanf (volumePath, L"\\Device\\Harddisk%d\\Partition", &driveNo) == 1) + { + OPEN_TEST_STRUCT openTestStruct; + memset (&openTestStruct, 0, sizeof (openTestStruct)); + + openTestStruct.bDetectTCBootLoader = TRUE; + StringCchPrintfW ((wchar_t *) openTestStruct.wszFileName, array_capacity (openTestStruct.wszFileName), L"\\Device\\Harddisk%d\\Partition0", driveNo); + + DWORD dwResult; + if (DeviceIoControl (hDriver, TC_IOCTL_OPEN_TEST, &openTestStruct, sizeof (OPEN_TEST_STRUCT), &openTestStruct, sizeof (OPEN_TEST_STRUCT), &dwResult, NULL) && openTestStruct.TCBootLoaderDetected) + WarningDirect ((GetWrongPasswordErrorMessage (hwndDlg) + L"\n\n" + GetString ("HIDDEN_VOL_PROT_PASSWORD_US_KEYB_LAYOUT")).c_str(), hwndDlg); + else + handleError (hwndDlg, mount.nReturnCode, SRC_POS); + } + } + else + handleError (hwndDlg, mount.nReturnCode, SRC_POS); + } + + return 0; + } + + if (!quiet) + handleError (hwndDlg, mount.nReturnCode, SRC_POS); + + return 0; + } + + // Mount successful + + if (mount.UseBackupHeader != mountOptions->UseBackupHeader + && mount.UseBackupHeader) + { + if (bReportWrongPassword && !Silent) + Warning ("HEADER_DAMAGED_AUTO_USED_HEADER_BAK", hwndDlg); + } + + LastMountedVolumeDirty = mount.FilesystemDirty; + + if (mount.FilesystemDirty) + { + wchar_t msg[1024]; + wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; + StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_VOLUME_DIRTY"), mountPoint); + + if (AskWarnYesNoStringTopmost (msg, hwndDlg) == IDYES) + CheckFilesystem (hwndDlg, driveNo, TRUE); + } + + if (mount.VolumeMountedReadOnlyAfterAccessDenied + && !Silent + && !bDevice + && !FileHasReadOnlyAttribute (volumePath) + && !IsFileOnReadOnlyFilesystem (volumePath)) + { + wchar_t msg[1024]; + wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; + StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_CONTAINER_FORCED_READ_ONLY"), mountPoint); + + WarningDirect (msg, hwndDlg); + } + + if (mount.VolumeMountedReadOnlyAfterAccessDenied + && !Silent + && bDevice) + { + wchar_t msg[1024]; + wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; + StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_DEVICE_FORCED_READ_ONLY"), mountPoint); + + WarningDirect (msg, hwndDlg); + } + + if (mount.VolumeMountedReadOnlyAfterDeviceWriteProtected + && !Silent + && wcsstr (volumePath, L"\\Device\\Harddisk") == volumePath) + { + wchar_t msg[1024]; + wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; + StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_DEVICE_FORCED_READ_ONLY_WRITE_PROTECTION"), mountPoint); + + WarningDirect (msg, hwndDlg); + + if (CurrentOSMajor >= 6 + && wcsstr (volumePath, L"\\Device\\HarddiskVolume") != volumePath + && AskNoYes ("ASK_REMOVE_DEVICE_WRITE_PROTECTION", hwndDlg) == IDYES) + { + RemoveDeviceWriteProtection (hwndDlg, volumePath); + } + } + + if (mount.wszLabel[0] && !mount.bDriverSetLabel) + { + // try setting the drive label on user-mode using registry + UpdateDriveCustomLabel (driveNo, mount.wszLabel, TRUE); + } + + ResetWrongPwdRetryCount (); + + BroadcastDeviceChange (DBT_DEVICEARRIVAL, driveNo, 0); + + if (mount.bExclusiveAccess == FALSE) + return 2; + + return 1; +} + +typedef struct +{ + int nDosDriveNo; + BOOL forced; + int dismountMaxRetries; + DWORD retryDelay; + int* presult; + DWORD dwLastError; +} UnmountThreadParam; + +void CALLBACK UnmountWaitThreadProc(void* pArg, HWND hwnd) +{ + UnmountThreadParam* pThreadParam = (UnmountThreadParam*) pArg; + int dismountMaxRetries = pThreadParam->dismountMaxRetries; + DWORD retryDelay = pThreadParam->retryDelay; + + do + { + *pThreadParam->presult = DriverUnmountVolume (hwnd, pThreadParam->nDosDriveNo, pThreadParam->forced); + + if (*pThreadParam->presult == ERR_FILES_OPEN) + Sleep (retryDelay); + else + break; + + } while (--dismountMaxRetries > 0); + + pThreadParam->dwLastError = GetLastError (); +} + +static BOOL UnmountVolumeBase (HWND hwndDlg, int nDosDriveNo, BOOL forceUnmount, BOOL ntfsFormatCase) +{ + int result; + BOOL forced = forceUnmount; + int dismountMaxRetries = ntfsFormatCase? 5 : UNMOUNT_MAX_AUTO_RETRIES; + DWORD retryDelay = ntfsFormatCase? 2000: UNMOUNT_AUTO_RETRY_DELAY; + UnmountThreadParam param; + +retry: + BroadcastDeviceChange (DBT_DEVICEREMOVEPENDING, nDosDriveNo, 0); + + param.nDosDriveNo = nDosDriveNo; + param.forced = forced; + param.dismountMaxRetries = dismountMaxRetries; + param.retryDelay = retryDelay; + param.presult = &result; + + if (Silent) + { + UnmountWaitThreadProc (¶m, hwndDlg); + } + else + { + ShowWaitDialog (hwndDlg, FALSE, UnmountWaitThreadProc, ¶m); + } + + SetLastError (param.dwLastError); + + if (result != 0) + { + if (result == ERR_FILES_OPEN && !Silent) + { + if (IDYES == AskWarnYesNoTopmost ("UNMOUNT_LOCK_FAILED", hwndDlg)) + { + forced = TRUE; + goto retry; + } + + if (IsOSAtLeast (WIN_7)) + { + // Undo SHCNE_DRIVEREMOVED + wchar_t root[] = { (wchar_t) nDosDriveNo + L'A', L':', L'\\', 0 }; + SHChangeNotify (SHCNE_DRIVEADD, SHCNF_PATH, root, NULL); + } + + return FALSE; + } + + Error ("UNMOUNT_FAILED", hwndDlg); + + return FALSE; + } + + BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, nDosDriveNo, 0); + + return TRUE; +} + +BOOL UnmountVolume (HWND hwndDlg, int nDosDriveNo, BOOL forceUnmount) +{ + return UnmountVolumeBase (hwndDlg, nDosDriveNo, forceUnmount, FALSE); +} + +BOOL UnmountVolumeAfterFormatExCall (HWND hwndDlg, int nDosDriveNo) +{ + return UnmountVolumeBase (hwndDlg, nDosDriveNo, FALSE, TRUE); +} + + +BOOL IsPasswordCacheEmpty (void) +{ + DWORD dw; + return !DeviceIoControl (hDriver, TC_IOCTL_GET_PASSWORD_CACHE_STATUS, 0, 0, 0, 0, &dw, 0); +} + +BOOL IsMountedVolumeID (BYTE volumeID[VOLUME_ID_SIZE]) +{ + MOUNT_LIST_STRUCT mlist; + DWORD dwResult; + int i; + + memset (&mlist, 0, sizeof (mlist)); + DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mlist, + sizeof (mlist), &mlist, sizeof (mlist), &dwResult, + NULL); + + for (i=0 ; i<26; i++) + if (0 == memcmp (mlist.volumeID[i], volumeID, VOLUME_ID_SIZE)) + return TRUE; + + return FALSE; +} + +BOOL IsMountedVolume (const wchar_t *volname) +{ + if ((wcslen (volname) == (3 + 2*VOLUME_ID_SIZE)) && _wcsnicmp (volname, L"ID:", 3) == 0) + { + /* Volume ID specified. Use it for matching mounted volumes. */ + std::vector arr; + if (HexWideStringToArray (&volname[3], arr) && (arr.size() == VOLUME_ID_SIZE)) + { + return IsMountedVolumeID (&arr[0]); + } + } + else + { + MOUNT_LIST_STRUCT mlist; + DWORD dwResult; + int i; + wchar_t volume[TC_MAX_PATH*2+16]; + + StringCbCopyW (volume, sizeof(volume), volname); + + if (wcsstr (volname, L"\\Device\\") != volname) + StringCbPrintfW(volume, sizeof(volume), L"\\??\\%s", volname); + + wstring resolvedPath = VolumeGuidPathToDevicePath (volname); + if (!resolvedPath.empty()) + StringCbCopyW (volume, sizeof (volume), resolvedPath.c_str()); + + memset (&mlist, 0, sizeof (mlist)); + DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mlist, + sizeof (mlist), &mlist, sizeof (mlist), &dwResult, + NULL); + + for (i=0 ; i<26; i++) + if (0 == _wcsicmp ((wchar_t *) mlist.wszVolume[i], volume)) + return TRUE; + } + + return FALSE; +} + + +int GetMountedVolumeDriveNo (wchar_t *volname) +{ + MOUNT_LIST_STRUCT mlist; + DWORD dwResult; + int i; + wchar_t volume[TC_MAX_PATH*2+16]; + + if (volname == NULL) + return -1; + + StringCbCopyW (volume, sizeof(volume), volname); + + if (wcsstr (volname, L"\\Device\\") != volname) + StringCbPrintfW (volume, sizeof(volume), L"\\??\\%s", volname); + + wstring resolvedPath = VolumeGuidPathToDevicePath (volname); + if (!resolvedPath.empty()) + StringCbCopyW (volume, sizeof (volume), resolvedPath.c_str()); + + memset (&mlist, 0, sizeof (mlist)); + DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mlist, + sizeof (mlist), &mlist, sizeof (mlist), &dwResult, + NULL); + + for (i=0 ; i<26; i++) + if (0 == _wcsicmp ((wchar_t *) mlist.wszVolume[i], (WCHAR *)volume)) + return i; + + return -1; +} + + +BOOL IsAdmin (void) +{ + return IsUserAnAdmin (); +} + + +BOOL IsBuiltInAdmin () +{ + HANDLE procToken; + DWORD size; + + if (!IsAdmin() || !OpenProcessToken (GetCurrentProcess(), TOKEN_QUERY, &procToken)) + return FALSE; + + finally_do_arg (HANDLE, procToken, { CloseHandle (finally_arg); }); + + if (GetTokenInformation (procToken, TokenUser, NULL, 0, &size) || GetLastError() != ERROR_INSUFFICIENT_BUFFER) + return FALSE; + + TOKEN_USER *tokenUser = (TOKEN_USER *) malloc (size); + if (!tokenUser) + return FALSE; + + finally_do_arg (void *, tokenUser, { free (finally_arg); }); + + if (!GetTokenInformation (procToken, TokenUser, tokenUser, size, &size)) + return FALSE; + + return IsWellKnownSid (tokenUser->User.Sid, WinAccountAdministratorSid); +} + + +BOOL IsUacSupported () +{ + HKEY hkey; + DWORD value = 1, size = sizeof (DWORD); + + if (!IsOSAtLeast (WIN_VISTA)) + return FALSE; + + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 0, KEY_READ, &hkey) == ERROR_SUCCESS) + { + if (RegQueryValueEx (hkey, L"EnableLUA", 0, 0, (LPBYTE) &value, &size) != ERROR_SUCCESS) + value = 1; + + RegCloseKey (hkey); + } + + return value != 0; +} + + +BOOL ResolveSymbolicLink (const wchar_t *symLinkName, PWSTR targetName, size_t cbTargetName) +{ + BOOL bResult; + DWORD dwResult; + RESOLVE_SYMLINK_STRUCT resolve; + + memset (&resolve, 0, sizeof(resolve)); + StringCbCopyW (resolve.symLinkName, sizeof(resolve.symLinkName), symLinkName); + + bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_RESOLVED_SYMLINK, &resolve, + sizeof (resolve), &resolve, sizeof (resolve), &dwResult, + NULL); + + StringCbCopyW (targetName, cbTargetName, resolve.targetName); + + return bResult; +} + + +BOOL GetPartitionInfo (const wchar_t *deviceName, PPARTITION_INFORMATION rpartInfo) +{ + BOOL bResult; + DWORD dwResult; + DISK_PARTITION_INFO_STRUCT dpi; + + memset (&dpi, 0, sizeof(dpi)); + StringCbCopyW ((PWSTR) &dpi.deviceName, sizeof(dpi.deviceName), deviceName); + + bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVE_PARTITION_INFO, &dpi, + sizeof (dpi), &dpi, sizeof (dpi), &dwResult, NULL); + + memcpy (rpartInfo, &dpi.partInfo, sizeof (PARTITION_INFORMATION)); + return bResult; +} + + +BOOL GetDeviceInfo (const wchar_t *deviceName, DISK_PARTITION_INFO_STRUCT *info) +{ + DWORD dwResult; + + memset (info, 0, sizeof(*info)); + StringCbCopyW ((PWSTR) &info->deviceName, sizeof(info->deviceName), deviceName); + + return DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVE_PARTITION_INFO, info, sizeof (*info), info, sizeof (*info), &dwResult, NULL); +} + + +BOOL GetDriveGeometry (const wchar_t *deviceName, PDISK_GEOMETRY diskGeometry) +{ + BOOL bResult; + DWORD dwResult; + DISK_GEOMETRY_STRUCT dg; + + memset (&dg, 0, sizeof(dg)); + StringCbCopyW ((PWSTR) &dg.deviceName, sizeof(dg.deviceName), deviceName); + + bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVE_GEOMETRY, &dg, + sizeof (dg), &dg, sizeof (dg), &dwResult, NULL); + + if (bResult && (dwResult == sizeof (dg)) && dg.diskGeometry.BytesPerSector) + { + memcpy (diskGeometry, &dg.diskGeometry, sizeof (DISK_GEOMETRY)); + return TRUE; + } + else + return FALSE; +} + +BOOL GetPhysicalDriveGeometry (int driveNumber, PDISK_GEOMETRY diskGeometry) +{ + HANDLE hDev; + BOOL bResult = FALSE; + TCHAR devicePath[MAX_PATH]; + + StringCchPrintfW (devicePath, ARRAYSIZE (devicePath), L"\\\\.\\PhysicalDrive%d", driveNumber); + + if ((hDev = CreateFileW (devicePath, 0, 0, NULL, OPEN_EXISTING, 0, NULL)) != INVALID_HANDLE_VALUE) + { + DWORD bytesRead = 0; + + ZeroMemory (diskGeometry, sizeof (DISK_GEOMETRY)); + + if ( DeviceIoControl (hDev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, diskGeometry, sizeof (DISK_GEOMETRY), &bytesRead, NULL) + && (bytesRead == sizeof (DISK_GEOMETRY)) + && diskGeometry->BytesPerSector) + { + bResult = TRUE; + } + + CloseHandle (hDev); + } + + return bResult; +} + + +// Returns drive letter number assigned to device (-1 if none) +int GetDiskDeviceDriveLetter (PWSTR deviceName) +{ + int i; + WCHAR link[MAX_PATH]; + WCHAR target[MAX_PATH]; + WCHAR device[MAX_PATH]; + + if (!ResolveSymbolicLink (deviceName, device, sizeof(device))) + StringCchCopyW (device, MAX_PATH, deviceName); + + for (i = 0; i < 26; i++) + { + WCHAR drive[] = { (WCHAR) i + L'A', L':', 0 }; + + StringCchCopyW (link, MAX_PATH, L"\\DosDevices\\"); + StringCchCatW (link, MAX_PATH, drive); + + if ( ResolveSymbolicLink (link, target, sizeof(target)) + && (wcscmp (device, target) == 0) + ) + { + return i; + } + } + + return -1; +} + + +// WARNING: This function does NOT provide 100% reliable results -- do NOT use it for critical/dangerous operations! +// Return values: 0 - filesystem does not appear empty, 1 - filesystem appears empty, -1 - an error occurred +int FileSystemAppearsEmpty (const wchar_t *devicePath) +{ + float percentFreeSpace = 0.0; + __int64 occupiedBytes = 0; + + if (GetStatsFreeSpaceOnPartition (devicePath, &percentFreeSpace, &occupiedBytes, TRUE) != -1) + { + if (occupiedBytes > BYTES_PER_GB && percentFreeSpace < 99.99 // "percentFreeSpace < 99.99" is needed because an NTFS filesystem larger than several terabytes can have more than 1GB of data in use, even if there are no files stored on it. + || percentFreeSpace < 88) // A 24-MB NTFS filesystem has 11.5% of space in use even if there are no files stored on it. + { + return 0; + } + else + return 1; + } + else + return -1; +} + + +// Returns the free space on the specified partition (volume) in bytes. If the 'occupiedBytes' pointer +// is not NULL, size of occupied space (in bytes) is written to the pointed location. In addition, if the +// 'percent' pointer is not NULL, % of free space is stored in the pointed location. If there's an error, +// returns -1. +__int64 GetStatsFreeSpaceOnPartition (const wchar_t *devicePath, float *percentFree, __int64 *occupiedBytes, BOOL silent) +{ + WCHAR devPath [MAX_PATH]; + int driveLetterNo = -1; + wchar_t szRootPath[4] = {0, L':', L'\\', 0}; + ULARGE_INTEGER freeSpaceSize; + ULARGE_INTEGER totalNumberOfBytes; + ULARGE_INTEGER totalNumberOfFreeBytes; + + StringCbCopyW (devPath, sizeof(devPath), devicePath); + + driveLetterNo = GetDiskDeviceDriveLetter (devPath); + szRootPath[0] = (wchar_t) driveLetterNo + L'A'; + + + if (!GetDiskFreeSpaceEx (szRootPath, &freeSpaceSize, &totalNumberOfBytes, &totalNumberOfFreeBytes)) + { + if (!silent) + { + handleWin32Error (MainDlg, SRC_POS); + Error ("CANNOT_CALC_SPACE", MainDlg); + } + + return -1; + } + + + if (percentFree != NULL || occupiedBytes != NULL) + { + // Determine occupied space and % of free space + + PARTITION_INFORMATION partitionInfo; + + if (!GetPartitionInfo (devicePath, &partitionInfo)) + { + if (!silent) + { + handleWin32Error (MainDlg, SRC_POS); + Error ("CANT_GET_VOLSIZE", MainDlg); + } + return -1; + } + + if (occupiedBytes != NULL) + *occupiedBytes = partitionInfo.PartitionLength.QuadPart - freeSpaceSize.QuadPart; + + if (percentFree != NULL) + *percentFree = (float) ((double) freeSpaceSize.QuadPart / (double) partitionInfo.PartitionLength.QuadPart * 100.0); + } + + return freeSpaceSize.QuadPart; +} + + +// Returns -1 if there's an error. +__int64 GetDeviceSize (const wchar_t *devicePath) +{ + PARTITION_INFORMATION partitionInfo; + + if (!GetPartitionInfo (devicePath, &partitionInfo)) + return -1; + + return partitionInfo.PartitionLength.QuadPart; +} + + +HANDLE DismountDrive (wchar_t *devName, wchar_t *devicePath) +{ + DWORD dwResult; + HANDLE hVolume; + BOOL bResult = FALSE; + int attempt = UNMOUNT_MAX_AUTO_RETRIES; + int driveLetterNo = -1; + WCHAR devPath [MAX_PATH]; + + StringCbCopyW (devPath, sizeof(devPath), devicePath); + driveLetterNo = GetDiskDeviceDriveLetter (devPath); + + + hVolume = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (hVolume == INVALID_HANDLE_VALUE) + return INVALID_HANDLE_VALUE; + + + // Try to lock the volume first so that dismount is not forced. + // If we fail, we will dismount anyway even if it needs to be forced. + + CloseVolumeExplorerWindows (MainDlg, driveLetterNo); + + while (!(bResult = DeviceIoControl (hVolume, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) + && attempt > 0) + { + Sleep (UNMOUNT_AUTO_RETRY_DELAY); + attempt--; + } + + + // Try to dismount the volume + + attempt = UNMOUNT_MAX_AUTO_RETRIES; + + while (!(bResult = DeviceIoControl (hVolume, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) + && attempt > 0) + { + Sleep (UNMOUNT_AUTO_RETRY_DELAY); + attempt--; + } + + if (!bResult) + CloseHandle (hVolume); + + return (bResult ? hVolume : INVALID_HANDLE_VALUE); +} + +// Returns -1 if the specified string is not found in the buffer. Otherwise, returns the +// offset of the first occurrence of the string. The string and the buffer may contain zeroes, +// which do NOT terminate them. +int64 FindString (const char *buf, const char *str, int64 bufLen, int64 strLen, int64 startOffset) +{ + if (buf == NULL + || str == NULL + || strLen > bufLen + || bufLen < 1 + || strLen < 1 + || startOffset > bufLen - strLen) + { + return -1; + } + + for (int64 i = startOffset; i <= bufLen - strLen; i++) + { + if (memcmp (buf + i, str, (size_t) strLen) == 0) + return i; + } + + return -1; +} + +// Returns TRUE if the file or directory exists (both may be enclosed in quotation marks). +BOOL FileExists (const wchar_t *filePathPtr) +{ + wchar_t filePath [TC_MAX_PATH * 2 + 1]; + + // Strip quotation marks (if any) + if (filePathPtr [0] == L'"') + { + StringCbCopyW (filePath, sizeof(filePath), filePathPtr + 1); + } + else + { + StringCbCopyW (filePath, sizeof(filePath), filePathPtr); + } + + // Strip quotation marks (if any) + if (filePath [wcslen (filePath) - 1] == L'"') + filePath [wcslen (filePath) - 1] = 0; + + return (_waccess (filePath, 0) != -1); +} + +// Searches the file from its end for the LAST occurrence of the string str. +// The string may contain zeroes, which do NOT terminate the string. +// If the string is found, its offset from the start of the file is returned. +// If the string isn't found or if any error occurs, -1 is returned. +__int64 FindStringInFile (const wchar_t *filePath, const char* str, int strLen) +{ + int bufSize = 64 * BYTES_PER_KB; + char *buffer = (char *) err_malloc (bufSize); + HANDLE src = NULL; + DWORD bytesRead; + BOOL readRetVal; + __int64 filePos = GetFileSize64 (filePath); + int bufPos = 0; + LARGE_INTEGER seekOffset, seekOffsetNew; + BOOL bExit = FALSE; + int filePosStep; + __int64 retVal = -1; + + if (filePos <= 0 + || buffer == NULL + || strLen > bufSize + || strLen < 1) + { + if (buffer) + free (buffer); + return -1; + } + + src = CreateFile (filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (src == INVALID_HANDLE_VALUE) + { + free (buffer); + return -1; + } + + filePosStep = bufSize - strLen + 1; + + do + { + filePos -= filePosStep; + + if (filePos < 0) + { + filePos = 0; + bExit = TRUE; + } + + seekOffset.QuadPart = filePos; + + if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0) + goto fsif_end; + + if ((readRetVal = ReadFile (src, buffer, bufSize, &bytesRead, NULL)) == 0 + || bytesRead == 0) + goto fsif_end; + + bufPos = bytesRead - strLen; + + while (bufPos > 0) + { + if (memcmp (buffer + bufPos, str, strLen) == 0) + { + // String found + retVal = filePos + bufPos; + goto fsif_end; + } + bufPos--; + } + + } while (!bExit); + +fsif_end: + CloseHandle (src); + free (buffer); + + return retVal; +} + +// System CopyFile() copies source file attributes (like FILE_ATTRIBUTE_ENCRYPTED) +// so we need to use our own copy function +BOOL TCCopyFileBase (HANDLE src, HANDLE dst) +{ + __int8 *buffer; + FILETIME fileTime; + DWORD bytesRead, bytesWritten; + BOOL res; + + buffer = (char *) malloc (64 * 1024); + if (!buffer) + { + CloseHandle (src); + CloseHandle (dst); + return FALSE; + } + + while (res = ReadFile (src, buffer, 64 * 1024, &bytesRead, NULL)) + { + if (bytesRead == 0) + { + res = 1; + break; + } + + if (!WriteFile (dst, buffer, bytesRead, &bytesWritten, NULL) + || bytesRead != bytesWritten) + { + res = 0; + break; + } + } + + if (GetFileTime (src, NULL, NULL, &fileTime)) + SetFileTime (dst, NULL, NULL, &fileTime); + + CloseHandle (src); + CloseHandle (dst); + + free (buffer); + return res != 0; +} + +BOOL TCCopyFile (wchar_t *sourceFileName, wchar_t *destinationFile) +{ + HANDLE src, dst; + + src = CreateFileW (sourceFileName, + GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (src == INVALID_HANDLE_VALUE) + return FALSE; + + dst = CreateFileW (destinationFile, + GENERIC_WRITE, + 0, NULL, CREATE_ALWAYS, 0, NULL); + + if (dst == INVALID_HANDLE_VALUE) + { + CloseHandle (src); + return FALSE; + } + + return TCCopyFileBase (src, dst); +} + +// If bAppend is TRUE, the buffer is appended to an existing file. If bAppend is FALSE, any existing file +// is replaced. If an error occurs, the incomplete file is deleted (provided that bAppend is FALSE). +BOOL SaveBufferToFile (const char *inputBuffer, const wchar_t *destinationFile, DWORD inputLength, BOOL bAppend, BOOL bRenameIfFailed) +{ + HANDLE dst; + DWORD bytesWritten; + BOOL res = TRUE; + DWORD dwLastError = 0; + + dst = CreateFile (destinationFile, + GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, bAppend ? OPEN_EXISTING : CREATE_ALWAYS, 0, NULL); + + dwLastError = GetLastError(); + if (!bAppend && bRenameIfFailed && (dst == INVALID_HANDLE_VALUE) && (GetLastError () == ERROR_SHARING_VIOLATION)) + { + wchar_t renamedPath[TC_MAX_PATH + 1]; + StringCbCopyW (renamedPath, sizeof(renamedPath), destinationFile); + StringCbCatW (renamedPath, sizeof(renamedPath), VC_FILENAME_RENAMED_SUFFIX); + + /* rename the locked file in order to be able to create a new one */ + if (MoveFileEx (destinationFile, renamedPath, MOVEFILE_REPLACE_EXISTING)) + { + dst = CreateFile (destinationFile, + GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL); + dwLastError = GetLastError(); + if (dst == INVALID_HANDLE_VALUE) + { + /* restore the original file name */ + MoveFileEx (renamedPath, destinationFile, MOVEFILE_REPLACE_EXISTING); + } + else + { + /* delete the renamed file when the machine reboots */ + MoveFileEx (renamedPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); + } + } + } + + if (dst == INVALID_HANDLE_VALUE) + { + SetLastError (dwLastError); + handleWin32Error (MainDlg, SRC_POS); + return FALSE; + } + + if (bAppend) + SetFilePointer (dst, 0, NULL, FILE_END); + + if (!WriteFile (dst, inputBuffer, inputLength, &bytesWritten, NULL) + || inputLength != bytesWritten) + { + res = FALSE; + } + + if (!res) + { + // If CREATE_ALWAYS is used, ERROR_ALREADY_EXISTS is returned after successful overwrite + // of an existing file (it's not an error) + if (! (GetLastError() == ERROR_ALREADY_EXISTS && !bAppend) ) + handleWin32Error (MainDlg, SRC_POS); + } + + CloseHandle (dst); + + if (!res && !bAppend) + _wremove (destinationFile); + + return res; +} + + +// Proper flush for Windows systems. Returns TRUE if successful. +BOOL TCFlushFile (FILE *f) +{ + HANDLE hf = (HANDLE) _get_osfhandle (_fileno (f)); + + fflush (f); + + if (hf == INVALID_HANDLE_VALUE) + return FALSE; + + return FlushFileBuffers (hf) != 0; +} + + +// Prints a UTF-16 text (note that this involves a real printer, not a screen). +// textByteLen - length of the text in bytes +// title - printed as part of the page header and used as the filename for a temporary file +BOOL PrintHardCopyTextUTF16 (wchar_t *text, wchar_t *title, size_t textByteLen) +{ + wchar_t cl [MAX_PATH*3] = {L"/p \""}; + wchar_t path [MAX_PATH * 2] = { 0 }; + wchar_t filename [MAX_PATH + 1] = { 0 }; + + StringCbCopyW (filename, sizeof(filename), title); + //strcat (filename, ".txt"); + + GetTempPath (ARRAYSIZE (path), path); + + if (!FileExists (path)) + { + StringCbCopyW (path, sizeof(path), GetConfigPath (filename)); + + if (wcslen(path) < 2) + return FALSE; + } + else + { + StringCbCatW (path, sizeof(path), filename); + } + + // Write the Unicode signature + if (!SaveBufferToFile ("\xFF\xFE", path, 2, FALSE, FALSE)) + { + _wremove (path); + return FALSE; + } + + // Write the actual text + if (!SaveBufferToFile ((char *) text, path, (DWORD) textByteLen, TRUE, FALSE)) + { + _wremove (path); + return FALSE; + } + + StringCbCatW (cl, sizeof(cl), path); + StringCbCatW (cl, sizeof(cl), L"\""); + + // Get the absolute path for notepad + if (GetWindowsDirectory(filename, MAX_PATH)) + { + if (filename[wcslen (filename) - 1] != L'\\') + StringCbCatW (filename, sizeof(filename), L"\\"); + StringCbCatW(filename, sizeof(filename), PRINT_TOOL); + } + else + StringCbCopyW(filename, sizeof(filename), L"C:\\Windows\\" PRINT_TOOL); + + WaitCursor (); + ShellExecute (NULL, L"open", filename, cl, NULL, SW_HIDE); + Sleep (6000); + NormalCursor(); + + _wremove (path); + + return TRUE; +} + + +BOOL IsNonInstallMode () +{ + HKEY hkey; + DWORD dw; + + if (bPortableModeConfirmed) + return TRUE; + + if (hDriver != INVALID_HANDLE_VALUE) + { + // The driver is running + if (DeviceIoControl (hDriver, TC_IOCTL_GET_PORTABLE_MODE_STATUS, NULL, 0, NULL, 0, &dw, 0)) + { + bPortableModeConfirmed = TRUE; + return TRUE; + } + else + { + // This is also returned if we fail to determine the status (it does not mean that portable mode is disproved). + return FALSE; + } + } + else + { + // The tests in this block are necessary because this function is in some cases called before DriverAttach(). + + HANDLE hDriverTmp = CreateFile (WIN32_ROOT_PREFIX, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (hDriverTmp == INVALID_HANDLE_VALUE) + { + // The driver was not found in the system path + + wchar_t path[MAX_PATH * 2] = { 0 }; + + // We can't use GetConfigPath() here because it would call us back (indirect recursion) + if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_APPDATA, NULL, 0, path))) + { + StringCbCatW (path, MAX_PATH * 2, L"\\VeraCrypt\\"); + StringCbCatW (path, MAX_PATH * 2, TC_APPD_FILENAME_SYSTEM_ENCRYPTION); + + if (FileExists (path)) + { + // To maintain consistency and safety, if the system encryption config file exits, we cannot + // allow portable mode. (This happens e.g. when the pretest fails and the user selects + // "Last Known Good Configuration" from the Windows boot menu.) + + // However, if UAC elevation is needed, we have to confirm portable mode first (after we are elevated, we won't). + if (!IsAdmin () && IsUacSupported ()) + return TRUE; + + return FALSE; + } + } + + // As the driver was not found in the system path, we can predict that we will run in portable mode + return TRUE; + } + else + CloseHandle (hDriverTmp); + } + + // The following test may be unreliable in some cases (e.g. after the user selects restore "Last Known Good + // Configuration" from the Windows boot menu). + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VeraCrypt", 0, KEY_READ | KEY_WOW64_32KEY, &hkey) == ERROR_SUCCESS) + { + RegCloseKey (hkey); + return FALSE; + } + else + return TRUE; +} + + +LRESULT SetCheckBox (HWND hwndDlg, int dlgItem, BOOL state) +{ + return SendDlgItemMessage (hwndDlg, dlgItem, BM_SETCHECK, state ? BST_CHECKED : BST_UNCHECKED, 0); +} + + +BOOL GetCheckBox (HWND hwndDlg, int dlgItem) +{ + return IsButtonChecked (GetDlgItem (hwndDlg, dlgItem)); +} + + +// Scroll the listview vertically so that the item with index of topMostVisibleItem is the topmost visible item. +void SetListScrollHPos (HWND hList, int topMostVisibleItem) +{ + int testedPos = 0; + + do + { + SendMessage (hList, LVM_SCROLL, 0, testedPos); + + } while (ListView_GetTopIndex (hList) < topMostVisibleItem && ++testedPos < 10000); +} + + +// Adds or removes TrueCrypt.exe to/from the system startup sequence (with appropriate command line arguments) +void ManageStartupSeq (void) +{ + if (!IsNonInstallMode ()) + { + wchar_t regk [64]; + + GetStartupRegKeyName (regk, sizeof(regk)); + + if (bStartOnLogon || bMountDevicesOnLogon || bMountFavoritesOnLogon) + { + wchar_t exe[MAX_PATH * 2] = { L'"' }; + + GetModuleFileName (NULL, exe + 1, ARRAYSIZE (exe) - 1); + +#ifdef VOLFORMAT + { + wchar_t *tmp = NULL; + + if (tmp = wcsrchr (exe, L'\\')) + { + *tmp = 0; + StringCbCatW (exe, MAX_PATH * 2, L"\\VeraCrypt.exe"); + } + } +#endif + StringCbCatW (exe, MAX_PATH * 2, L"\" /q preferences /a logon"); + + if (bMountDevicesOnLogon) StringCbCatW (exe, MAX_PATH * 2, L" /a devices"); + if (bMountFavoritesOnLogon) StringCbCatW (exe, MAX_PATH * 2, L" /a favorites"); + + WriteRegistryString (regk, L"VeraCrypt", exe); + } + else + DeleteRegistryValue (regk, L"VeraCrypt"); + } +} + + +// Adds or removes the VeraCrypt Volume Creation Wizard to/from the system startup sequence +void ManageStartupSeqWiz (BOOL bRemove, const wchar_t *arg) +{ + wchar_t regk [64]; + + GetStartupRegKeyName (regk, sizeof(regk)); + + if (!bRemove) + { + size_t exeSize = (MAX_PATH * 2) + 3 + 20 + wcslen (arg); // enough room for all concatenation operations + wchar_t* exe = (wchar_t*) calloc(1, exeSize * sizeof (wchar_t)); + exe[0] = L'"'; + GetModuleFileName (NULL, exe + 1, (DWORD) (exeSize - 1)); + +#ifndef VOLFORMAT + { + wchar_t *tmp = NULL; + + if (tmp = wcsrchr (exe, L'\\')) + { + *tmp = 0; + + StringCchCatW (exe, exeSize, L"\\VeraCrypt Format.exe"); + } + } +#endif + + if (wcslen (arg) > 0) + { + StringCchCatW (exe, exeSize, L"\" "); + StringCchCatW (exe, exeSize, arg); + } + + WriteRegistryString (regk, L"VeraCrypt Format", exe); + + free(exe); + } + else + DeleteRegistryValue (regk, L"VeraCrypt Format"); +} + + +// Delete the last used Windows file selector path for TrueCrypt from the registry +void CleanLastVisitedMRU (void) +{ + WCHAR exeFilename[MAX_PATH]; + WCHAR *strToMatch; + + WCHAR strTmp[4096]; + WCHAR regPath[128]; + WCHAR key[64]; + int id, len; + + GetModuleFileNameW (NULL, exeFilename, sizeof (exeFilename) / sizeof(exeFilename[0])); + strToMatch = wcsrchr (exeFilename, L'\\') + 1; + + StringCbPrintfW (regPath, sizeof(regPath), L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisited%sMRU", IsOSAtLeast (WIN_VISTA) ? L"Pidl" : L""); + + for (id = (IsOSAtLeast (WIN_VISTA) ? 0 : L'a'); id <= (IsOSAtLeast (WIN_VISTA) ? 1000 : L'z'); id++) + { + *strTmp = 0; + StringCbPrintfW (key, sizeof(key), (IsOSAtLeast (WIN_VISTA) ? L"%d" : L"%c"), id); + + if ((len = ReadRegistryBytes (regPath, key, (char *) strTmp, sizeof (strTmp))) > 0) + { + if (_wcsicmp (strTmp, strToMatch) == 0) + { + char buf[65536], bufout[sizeof (buf)]; + + // Overwrite the entry with zeroes while keeping its original size + memset (strTmp, 0, len); + if (!WriteRegistryBytes (regPath, key, (char *) strTmp, len)) + MessageBoxW (NULL, GetString ("CLEAN_WINMRU_FAILED"), lpszTitle, ICON_HAND); + + DeleteRegistryValue (regPath, key); + + // Remove ID from MRUList + if (IsOSAtLeast (WIN_VISTA)) + { + int *p = (int *)buf; + int *pout = (int *)bufout; + int l; + + l = len = ReadRegistryBytes (L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedPidlMRU", L"MRUListEx", buf, sizeof (buf)); + while (l > 0) + { + l -= sizeof (int); + + if (*p == id) + { + p++; + len -= sizeof (int); + continue; + } + *pout++ = *p++; + } + + WriteRegistryBytes (L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedPidlMRU", L"MRUListEx", bufout, len); + } + else + { + wchar_t *p = (wchar_t*) buf; + wchar_t *pout = (wchar_t*) bufout; + + ReadRegistryString (L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedMRU", L"MRUList", L"", (wchar_t*) buf, sizeof (buf)); + while (*p) + { + if (*p == id) + { + p++; + continue; + } + *pout++ = *p++; + } + *pout++ = 0; + + WriteRegistryString (L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedMRU", L"MRUList", (wchar_t*) bufout); + } + + break; + } + } + } +} + + +#ifndef SETUP +void ClearHistory (HWND hwndDlgItem) +{ + ArrowWaitCursor (); + + ClearCombo (hwndDlgItem); + DumpCombo (hwndDlgItem, TRUE); + + CleanLastVisitedMRU (); + + NormalCursor (); +} +#endif // #ifndef SETUP + + +LRESULT ListItemAdd (HWND list, int index, const wchar_t *string) +{ + LVITEM li; + memset (&li, 0, sizeof(li)); + + li.mask = LVIF_TEXT; + li.pszText = (wchar_t*) string; + li.iItem = index; + li.iSubItem = 0; + return ListView_InsertItem (list, &li); +} + + +LRESULT ListSubItemSet (HWND list, int index, int subIndex, const wchar_t *string) +{ + LVITEM li; + memset (&li, 0, sizeof(li)); + + li.mask = LVIF_TEXT; + li.pszText = (wchar_t*) string; + li.iItem = index; + li.iSubItem = subIndex; + return ListView_SetItem (list, &li); +} + + +BOOL GetMountList (MOUNT_LIST_STRUCT *list) +{ + DWORD dwResult; + + memset (list, 0, sizeof (*list)); + return DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, list, + sizeof (*list), list, sizeof (*list), &dwResult, + NULL); +} + + +int GetDriverRefCount () +{ + DWORD dwResult; + BOOL bResult; + int refCount; + + bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DEVICE_REFCOUNT, &refCount, sizeof (refCount), &refCount, + sizeof (refCount), &dwResult, NULL); + + if (bResult) + return refCount; + else + return -1; +} + +// Loads a 32-bit integer from the file at the specified file offset. The saved value is assumed to have been +// processed by mputLong(). The result is stored in *result. Returns TRUE if successful (otherwise FALSE). +BOOL LoadInt32 (const wchar_t *filePath, unsigned __int32 *result, __int64 fileOffset) +{ + DWORD bufSize = sizeof(__int32); + unsigned char *buffer = (unsigned char *) malloc (bufSize); + unsigned char *bufferPtr = buffer; + HANDLE src = NULL; + DWORD bytesRead; + LARGE_INTEGER seekOffset, seekOffsetNew; + BOOL retVal = FALSE; + + if (buffer == NULL) + return -1; + + src = CreateFile (filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (src == INVALID_HANDLE_VALUE) + { + free (buffer); + return FALSE; + } + + seekOffset.QuadPart = fileOffset; + + if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0) + goto fsif_end; + + if (ReadFile (src, buffer, bufSize, &bytesRead, NULL) == 0 + || bytesRead != bufSize) + goto fsif_end; + + + retVal = TRUE; + + *result = mgetLong(bufferPtr); + +fsif_end: + CloseHandle (src); + free (buffer); + + return retVal; +} + +// Loads a 16-bit integer from the file at the specified file offset. The saved value is assumed to have been +// processed by mputWord(). The result is stored in *result. Returns TRUE if successful (otherwise FALSE). +BOOL LoadInt16 (const wchar_t *filePath, int *result, __int64 fileOffset) +{ + DWORD bufSize = sizeof(__int16); + unsigned char *buffer = (unsigned char *) malloc (bufSize); + unsigned char *bufferPtr = buffer; + HANDLE src = NULL; + DWORD bytesRead; + LARGE_INTEGER seekOffset, seekOffsetNew; + BOOL retVal = FALSE; + + if (buffer == NULL) + return -1; + + src = CreateFile (filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (src == INVALID_HANDLE_VALUE) + { + free (buffer); + return FALSE; + } + + seekOffset.QuadPart = fileOffset; + + if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0) + goto fsif_end; + + if (ReadFile (src, buffer, bufSize, &bytesRead, NULL) == 0 + || bytesRead != bufSize) + goto fsif_end; + + + retVal = TRUE; + + *result = mgetWord(bufferPtr); + +fsif_end: + CloseHandle (src); + free (buffer); + + return retVal; +} + +// Returns NULL if there's any error. Although the buffer can contain binary data, it is always null-terminated. +char *LoadFile (const wchar_t *fileName, DWORD *size) +{ + char *buf; + DWORD fileSize = INVALID_FILE_SIZE; + HANDLE h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + if (h == INVALID_HANDLE_VALUE) + return NULL; + + if ((fileSize = GetFileSize (h, NULL)) == INVALID_FILE_SIZE) + { + CloseHandle (h); + return NULL; + } + + *size = fileSize; + buf = (char *) calloc (*size + 1, 1); + + if (buf == NULL) + { + CloseHandle (h); + return NULL; + } + + if (!ReadFile (h, buf, *size, size, NULL)) + { + free (buf); + buf = NULL; + } + + CloseHandle (h); + return buf; +} + + +// Returns NULL if there's any error. +char *LoadFileBlock (const wchar_t *fileName, __int64 fileOffset, DWORD count) +{ + char *buf; + DWORD bytesRead = 0; + LARGE_INTEGER seekOffset, seekOffsetNew; + BOOL bStatus; + + HANDLE h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + if (h == INVALID_HANDLE_VALUE) + return NULL; + + seekOffset.QuadPart = fileOffset; + + if (SetFilePointerEx (h, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0) + { + CloseHandle (h); + return NULL; + } + + buf = (char *) calloc (count, 1); + + if (buf == NULL) + { + CloseHandle (h); + return NULL; + } + + bStatus = ReadFile (h, buf, count, &bytesRead, NULL); + + CloseHandle (h); + + if (!bStatus || (bytesRead != count)) + { + free (buf); + return NULL; + } + + return buf; +} + + +// Returns -1 if there is an error, or the size of the file. +__int64 GetFileSize64 (const wchar_t *path) +{ + HANDLE h = CreateFile (path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + LARGE_INTEGER size; + __int64 retSize = -1; + + if (h) + { + if (GetFileSizeEx (h, &size)) + { + retSize = size.QuadPart; + } + + CloseHandle (h); + } + + return retSize; +} + + +wchar_t *GetModPath (wchar_t *path, int maxSize) +{ + GetModuleFileName (NULL, path, maxSize); + wchar_t* ptr = wcsrchr (path, L'\\'); + if (ptr) + ptr[1] = 0; + return path; +} + + +wchar_t *GetConfigPath (wchar_t *fileName) +{ + static wchar_t path[MAX_PATH * 2] = { 0 }; + + if (IsNonInstallMode ()) + { + GetModPath (path, ARRAYSIZE (path)); + StringCchCatW (path, (MAX_PATH * 2), fileName); + + return path; + } + + if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, path))) + { + StringCchCatW (path, (MAX_PATH * 2), L"\\VeraCrypt\\"); + CreateDirectory (path, NULL); + StringCchCatW (path, (MAX_PATH * 2), fileName); + } + else + path[0] = 0; + + return path; +} + + +wchar_t *GetProgramConfigPath (wchar_t *fileName) +{ + static wchar_t path[MAX_PATH * 2] = { 0 }; + + if (SUCCEEDED (SHGetFolderPath (NULL, CSIDL_COMMON_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, path))) + { + StringCchCatW (path, (MAX_PATH * 2), L"\\VeraCrypt\\"); + CreateDirectory (path, NULL); + StringCchCatW (path, (MAX_PATH * 2), fileName); + } + else + path[0] = 0; + + return path; +} + + +std::wstring GetServiceConfigPath (const wchar_t *fileName, bool useLegacy) +{ + wchar_t sysPath[TC_MAX_PATH]; + + if (Is64BitOs() && useLegacy) + { + typedef UINT (WINAPI *GetSystemWow64Directory_t) (LPWSTR lpBuffer, UINT uSize); + + GetSystemWow64Directory_t getSystemWow64Directory = (GetSystemWow64Directory_t) GetProcAddress (GetModuleHandle (L"kernel32"), "GetSystemWow64DirectoryW"); + getSystemWow64Directory (sysPath, ARRAYSIZE (sysPath)); + } + else + GetSystemDirectory (sysPath, ARRAYSIZE (sysPath)); + + return wstring (sysPath) + L"\\" + fileName; +} + + +// Returns 0 if an error occurs or the drive letter (as an upper-case char) of the system partition (e.g. 'C'); +wchar_t GetSystemDriveLetter (void) +{ + wchar_t systemDir [MAX_PATH]; + + if (GetSystemDirectory (systemDir, ARRAYSIZE (systemDir))) + return (wchar_t) (towupper (systemDir [0])); + else + return 0; +} + + +void TaskBarIconDisplayBalloonTooltip (HWND hwnd, wchar_t *headline, wchar_t *text, BOOL warning) +{ + if (nCurrentOS == WIN_2000) + { + MessageBoxW (MainDlg, text, headline, warning ? MB_ICONWARNING : MB_ICONINFORMATION); + return; + } + + NOTIFYICONDATAW tnid; + + ZeroMemory (&tnid, sizeof (tnid)); + + tnid.cbSize = sizeof (tnid); + tnid.hWnd = hwnd; + tnid.uID = IDI_TRUECRYPT_ICON; + //tnid.uVersion = (IsOSAtLeast (WIN_VISTA) ? NOTIFYICON_VERSION_4 : NOTIFYICON_VERSION); + + //Shell_NotifyIconW (NIM_SETVERSION, &tnid); + + tnid.uFlags = NIF_INFO; + tnid.dwInfoFlags = (warning ? NIIF_WARNING : NIIF_INFO); + tnid.uTimeout = (IsOSAtLeast (WIN_VISTA) ? 1000 : 5000); // in ms + + StringCbCopyW (tnid.szInfoTitle, sizeof(tnid.szInfoTitle), headline); + StringCbCopyW (tnid.szInfo, sizeof(tnid.szInfo),text); + + // Display the balloon tooltip quickly twice in a row to avoid the slow and unwanted "fade-in" phase + Shell_NotifyIconW (NIM_MODIFY, &tnid); + Shell_NotifyIconW (NIM_MODIFY, &tnid); +} + + +// Either of the pointers may be NULL +void InfoBalloon (char *headingStringId, char *textStringId, HWND hwnd) +{ + if (Silent) + return; + + TaskBarIconDisplayBalloonTooltip (hwnd, + headingStringId == NULL ? L"VeraCrypt" : GetString (headingStringId), + textStringId == NULL ? L" " : GetString (textStringId), + FALSE); +} + + +// Either of the pointers may be NULL +void InfoBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd) +{ + if (Silent) + return; + + TaskBarIconDisplayBalloonTooltip (hwnd, + headingString == NULL ? L"VeraCrypt" : headingString, + textString == NULL ? L" " : textString, + FALSE); +} + + +// Either of the pointers may be NULL +void WarningBalloon (char *headingStringId, char *textStringId, HWND hwnd) +{ + if (Silent) + return; + + TaskBarIconDisplayBalloonTooltip (hwnd, + headingStringId == NULL ? L"VeraCrypt" : GetString (headingStringId), + textStringId == NULL ? L" " : GetString (textStringId), + TRUE); +} + + +// Either of the pointers may be NULL +void WarningBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd) +{ + if (Silent) + return; + + TaskBarIconDisplayBalloonTooltip (hwnd, + headingString == NULL ? L"VeraCrypt" : headingString, + textString == NULL ? L" " : textString, + TRUE); +} + + +int Info (char *stringId, HWND hwnd) +{ + if (Silent) return 0; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONINFORMATION); +} + + +int InfoTopMost (char *stringId, HWND hwnd) +{ + if (Silent) return 0; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TOPMOST); +} + + +int InfoDirect (const wchar_t *msg, HWND hwnd) +{ + if (Silent) return 0; + return MessageBoxW (hwnd, msg, lpszTitle, MB_ICONINFORMATION); +} + + +int Warning (char *stringId, HWND hwnd) +{ + if (Silent) return 0; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING); +} + + +int WarningTopMost (char *stringId, HWND hwnd) +{ + if (Silent) return 0; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); +} + + +int WarningDirect (const wchar_t *warnMsg, HWND hwnd) +{ + if (Silent) return 0; + return MessageBoxW (hwnd, warnMsg, lpszTitle, MB_ICONWARNING); +} + + +int Error (char *stringId, HWND hwnd) +{ + if (Silent) return 0; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONERROR); +} + +int ErrorRetryCancel (char *stringId, HWND hwnd) +{ + if (Silent) return 0; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONERROR | MB_RETRYCANCEL); +} + +int ErrorTopMost (char *stringId, HWND hwnd) +{ + if (Silent) return 0; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); +} + + +int ErrorDirect (const wchar_t *errMsg, HWND hwnd) +{ + if (Silent) return 0; + return MessageBoxW (hwnd, errMsg, lpszTitle, MB_ICONERROR); +} + + +int AskYesNo (char *stringId, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON1); +} + + +int AskYesNoString (const wchar_t *str, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, str, lpszTitle, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON1); +} + + +int AskYesNoTopmost (char *stringId, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON1 | MB_SETFOREGROUND | MB_TOPMOST); +} + + +int AskNoYes (char *stringId, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2); +} + +int AskNoYesString (const wchar_t *string, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, string, lpszTitle, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2); +} + +int AskOkCancel (char *stringId, HWND hwnd) +{ + if (Silent) return IDCANCEL; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONQUESTION | MB_OKCANCEL | MB_DEFBUTTON1); +} + + +int AskWarnYesNo (char *stringId, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON1); +} + + +int AskWarnYesNoString (const wchar_t *string, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, string, lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON1); +} + + +int AskWarnYesNoTopmost (char *stringId, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON1 | MB_SETFOREGROUND | MB_TOPMOST); +} + + +int AskWarnYesNoStringTopmost (const wchar_t *string, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, string, lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON1 | MB_SETFOREGROUND | MB_TOPMOST); +} + + +int AskWarnNoYes (char *stringId, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2); +} + + +int AskWarnNoYesString (const wchar_t *string, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, string, lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2); +} + + +int AskWarnNoYesTopmost (char *stringId, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2 | MB_SETFOREGROUND | MB_TOPMOST); +} + + +int AskWarnOkCancel (char *stringId, HWND hwnd) +{ + if (Silent) return IDCANCEL; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1); +} + + +int AskWarnCancelOk (char *stringId, HWND hwnd) +{ + if (Silent) return IDCANCEL; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON2); +} + + +int AskErrYesNo (char *stringId, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONERROR | MB_YESNO | MB_DEFBUTTON1); +} + + +int AskErrNoYes (char *stringId, HWND hwnd) +{ + if (Silent) return IDNO; + return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONERROR | MB_YESNO | MB_DEFBUTTON2); +} + + +// The function accepts two input formats: +// Input format 1: {0, "MESSAGE_STRING_ID", "BUTTON_1_STRING_ID", ... "LAST_BUTTON_STRING_ID", 0}; +// Input format 2: {L"", L"Message text", L"Button caption 1", ... L"Last button caption", 0}; +// The second format is to be used if any of the strings contains format specification (e.g. %s, %d) or +// in any other cases where a string needs to be resolved before calling this function. +// The returned value is the ordinal number of the choice the user selected (1..MAX_MULTI_CHOICES) +int AskMultiChoice (void *strings[], BOOL bBold, HWND hwnd) +{ + MULTI_CHOICE_DLGPROC_PARAMS params; + + params.strings = &strings[0]; + params.bold = bBold; + + return (int) DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_MULTI_CHOICE_DLG), hwnd, + (DLGPROC) MultiChoiceDialogProc, (LPARAM) ¶ms); +} + + +BOOL ConfigWriteBegin () +{ + DWORD size; + if (ConfigFileHandle != NULL) + return FALSE; + + if (ConfigBuffer == NULL) + ConfigBuffer = LoadFile (GetConfigPath (TC_APPD_FILENAME_CONFIGURATION), &size); + + ConfigFileHandle = _wfopen (GetConfigPath (TC_APPD_FILENAME_CONFIGURATION), L"w,ccs=UTF-8"); + if (ConfigFileHandle == NULL) + { + free (ConfigBuffer); + ConfigBuffer = NULL; + return FALSE; + } + XmlWriteHeader (ConfigFileHandle); + fputws (L"\n\t", ConfigFileHandle); + + return TRUE; +} + + +BOOL ConfigWriteEnd (HWND hwnd) +{ + char *xml = ConfigBuffer; + char key[128], value[2048]; + + if (ConfigFileHandle == NULL) return FALSE; + + // Write unmodified values + while (xml && (xml = XmlFindElement (xml, "config"))) + { + XmlGetAttributeText (xml, "key", key, sizeof (key)); + XmlGetNodeText (xml, value, sizeof (value)); + + fwprintf (ConfigFileHandle, L"\n\t\t%hs", key, value); + xml++; + } + + fputws (L"\n\t", ConfigFileHandle); + XmlWriteFooter (ConfigFileHandle); + + TCFlushFile (ConfigFileHandle); + + CheckFileStreamWriteErrors (hwnd, ConfigFileHandle, TC_APPD_FILENAME_CONFIGURATION); + + fclose (ConfigFileHandle); + ConfigFileHandle = NULL; + + if (ConfigBuffer != NULL) + { + DWORD size; + free (ConfigBuffer); + ConfigBuffer = LoadFile (GetConfigPath (TC_APPD_FILENAME_CONFIGURATION), &size); + } + + return TRUE; +} + + +BOOL ConfigWriteString (char *configKey, char *configValue) +{ + char *c; + if (ConfigFileHandle == NULL) + return FALSE; + + // Mark previous config value as updated + if (ConfigBuffer != NULL) + { + c = XmlFindElementByAttributeValue (ConfigBuffer, "config", "key", configKey); + if (c != NULL) + c[1] = '!'; + } + + return 0 != fwprintf ( + ConfigFileHandle, L"\n\t\t%hs", + configKey, configValue); +} + +BOOL ConfigWriteStringW (char *configKey, wchar_t *configValue) +{ + char *c; + if (ConfigFileHandle == NULL) + return FALSE; + + // Mark previous config value as updated + if (ConfigBuffer != NULL) + { + c = XmlFindElementByAttributeValue (ConfigBuffer, "config", "key", configKey); + if (c != NULL) + c[1] = '!'; + } + + return 0 != fwprintf ( + ConfigFileHandle, L"\n\t\t%ls", + configKey, configValue); +} + +BOOL ConfigWriteInt (char *configKey, int configValue) +{ + char val[32]; + StringCbPrintfA (val, sizeof(val), "%d", configValue); + return ConfigWriteString (configKey, val); +} + + +static BOOL ConfigRead (char *configKey, char *configValue, int maxValueSize) +{ + DWORD size; + char *xml; + + if (ConfigBuffer == NULL) + ConfigBuffer = LoadFile (GetConfigPath (TC_APPD_FILENAME_CONFIGURATION), &size); + + xml = ConfigBuffer; + if (xml != NULL) + { + xml = XmlFindElementByAttributeValue (xml, "config", "key", configKey); + if (xml != NULL) + { + XmlGetNodeText (xml, configValue, maxValueSize); + return TRUE; + } + } + + return FALSE; +} + + +int ConfigReadInt (char *configKey, int defaultValue) +{ + char s[32]; + + if (ConfigRead (configKey, s, sizeof (s))) + return atoi (s); + else + return defaultValue; +} + + +char *ConfigReadString (char *configKey, char *defaultValue, char *str, int maxLen) +{ + if (ConfigRead (configKey, str, maxLen)) + return str; + else + { + StringCbCopyA (str, maxLen, defaultValue); + return defaultValue; + } +} + +void ConfigReadCompareInt(char *configKey, int defaultValue, int* pOutputValue, BOOL bOnlyCheckModified, BOOL* pbModified) +{ + int intValue = ConfigReadInt (configKey, defaultValue); + if (pOutputValue) + { + if (pbModified && (*pOutputValue != intValue)) + *pbModified = TRUE; + if (!bOnlyCheckModified) + *pOutputValue = intValue; + } +} + +void ConfigReadCompareString (char *configKey, char *defaultValue, char *str, int maxLen, BOOL bOnlyCheckModified, BOOL *pbModified) +{ + char *strValue = (char*) malloc (maxLen); + if (strValue) + { + memcpy (strValue, str, maxLen); + + ConfigReadString (configKey, defaultValue, strValue, maxLen); + + if (pbModified && strcmp (str, strValue)) + *pbModified = TRUE; + if (!bOnlyCheckModified) + memcpy(str, strValue, maxLen); + + free (strValue); + } + else + { + /* allocation failed. Suppose that value changed */ + if (pbModified) + *pbModified = TRUE; + if (!bOnlyCheckModified) + ConfigReadString (configKey, defaultValue, str, maxLen); + + } +} + +void OpenPageHelp (HWND hwndDlg, int nPage) +{ + int r = (int)ShellExecuteW (NULL, L"open", szHelpFile, NULL, NULL, SW_SHOWNORMAL); + + if (r == ERROR_FILE_NOT_FOUND) + { + // Try the secondary help file + r = (int)ShellExecuteW (NULL, L"open", szHelpFile2, NULL, NULL, SW_SHOWNORMAL); + + if (r == ERROR_FILE_NOT_FOUND) + { + OpenOnlineHelp (); + return; + } + } + + if (r == SE_ERR_NOASSOC) + { + if (AskYesNo ("HELP_READER_ERROR", MainDlg) == IDYES) + OpenOnlineHelp (); + } +} + + +void OpenOnlineHelp () +{ + Applink ("help", TRUE, ""); +} + + +#ifndef SETUP + +void RestoreDefaultKeyFilesParam (void) +{ + KeyFileRemoveAll (&FirstKeyFile); + if (defaultKeyFilesParam.FirstKeyFile != NULL) + { + KeyFileCloneAll (defaultKeyFilesParam.FirstKeyFile, &FirstKeyFile); + KeyFilesEnable = defaultKeyFilesParam.EnableKeyFiles; + } + else + KeyFilesEnable = FALSE; +} + + +BOOL LoadDefaultKeyFilesParam (void) +{ + BOOL status = TRUE; + DWORD size; + char *defaultKeyfilesFile = LoadFile (GetConfigPath (TC_APPD_FILENAME_DEFAULT_KEYFILES), &size); + char *xml = defaultKeyfilesFile; + KeyFile *kf; + + if (xml == NULL) + return FALSE; + + KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile); + + while (xml = XmlFindElement (xml, "keyfile")) + { + kf = (KeyFile *) malloc (sizeof (KeyFile)); + if (kf) + { + char fileName [MAX_PATH + 1]; + if (XmlGetNodeText (xml, fileName, sizeof (fileName)) != NULL) + { + std::wstring wszFileName = Utf8StringToWide(fileName); + StringCbCopyW (kf->FileName, sizeof (kf->FileName), wszFileName.c_str ()); + defaultKeyFilesParam.FirstKeyFile = KeyFileAdd (defaultKeyFilesParam.FirstKeyFile, kf); + } + else + free (kf); + } + else + { + KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile); + status = FALSE; + break; + } + + xml++; + } + + free (defaultKeyfilesFile); + if (status) + KeyFilesEnable = defaultKeyFilesParam.EnableKeyFiles; + + return status; +} + +#endif /* #ifndef SETUP */ + + +void Debug (char *format, ...) +{ + char buf[1024]; + va_list val; + + va_start(val, format); + StringCbVPrintfA (buf, sizeof (buf), format, val); + va_end(val); + + OutputDebugStringA (buf); +} + + +void DebugMsgBox (char *format, ...) +{ + char buf[1024]; + va_list val; + + va_start(val, format); + StringCbVPrintfA (buf, sizeof (buf), format, val); + va_end(val); + + MessageBoxA (MainDlg, buf, "VeraCrypt debug", 0); +} + + +BOOL IsOSAtLeast (OSVersionEnum reqMinOS) +{ + return IsOSVersionAtLeast (reqMinOS, 0); +} + + +// Returns TRUE if the operating system is at least reqMinOS and service pack at least reqMinServicePack. +// Example 1: IsOSVersionAtLeast (WIN_VISTA, 1) called under Windows 2008, returns TRUE. +// Example 2: IsOSVersionAtLeast (WIN_XP, 3) called under Windows XP SP1, returns FALSE. +// Example 3: IsOSVersionAtLeast (WIN_XP, 3) called under Windows Vista SP1, returns TRUE. +BOOL IsOSVersionAtLeast (OSVersionEnum reqMinOS, int reqMinServicePack) +{ + /* When updating this function, update IsOSAtLeast() in Ntdriver.c too. */ + + if (CurrentOSMajor <= 0) + TC_THROW_FATAL_EXCEPTION; + + int major = 0, minor = 0; + + switch (reqMinOS) + { + case WIN_2000: major = 5; minor = 0; break; + case WIN_XP: major = 5; minor = 1; break; + case WIN_SERVER_2003: major = 5; minor = 2; break; + case WIN_VISTA: major = 6; minor = 0; break; + case WIN_7: major = 6; minor = 1; break; + case WIN_8: major = 6; minor = 2; break; + case WIN_8_1: major = 6; minor = 3; break; + case WIN_10: major = 10; minor = 0; break; + + default: + TC_THROW_FATAL_EXCEPTION; + break; + } + + return ((CurrentOSMajor << 16 | CurrentOSMinor << 8 | CurrentOSServicePack) + >= (major << 16 | minor << 8 | reqMinServicePack)); +} + + +BOOL Is64BitOs () +{ +#ifdef _WIN64 + return TRUE; +#else + static BOOL isWow64 = FALSE; + static BOOL valid = FALSE; + typedef BOOL (__stdcall *LPFN_ISWOW64PROCESS ) (HANDLE hProcess,PBOOL Wow64Process); + LPFN_ISWOW64PROCESS fnIsWow64Process; + + if (valid) + return isWow64; + + fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle(L"kernel32"), "IsWow64Process"); + + if (fnIsWow64Process != NULL) + if (!fnIsWow64Process (GetCurrentProcess(), &isWow64)) + isWow64 = FALSE; + + valid = TRUE; + return isWow64; +#endif +} + + +BOOL IsServerOS () +{ + OSVERSIONINFOEXW osVer; + osVer.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW); + GetVersionExW ((LPOSVERSIONINFOW) &osVer); + + return (osVer.wProductType == VER_NT_SERVER || osVer.wProductType == VER_NT_DOMAIN_CONTROLLER); +} + + +// Returns TRUE, if the currently running operating system is installed in a hidden volume. If it's not, or if +// there's an error, returns FALSE. +BOOL IsHiddenOSRunning (void) +{ + static BOOL statusCached = FALSE; + static BOOL hiddenOSRunning; + + if (!statusCached) + { + try + { + hiddenOSRunning = BootEncryption (MainDlg).IsHiddenSystemRunning(); + } + catch (...) + { + hiddenOSRunning = FALSE; + } + + statusCached = TRUE; + } + + return hiddenOSRunning; +} + + +BOOL EnableWow64FsRedirection (BOOL enable) +{ + typedef BOOLEAN (__stdcall *Wow64EnableWow64FsRedirection_t) (BOOL enable); + Wow64EnableWow64FsRedirection_t wow64EnableWow64FsRedirection = (Wow64EnableWow64FsRedirection_t) GetProcAddress (GetModuleHandle (L"kernel32"), "Wow64EnableWow64FsRedirection"); + + if (!wow64EnableWow64FsRedirection) + return FALSE; + + return wow64EnableWow64FsRedirection (enable); +} + + +BOOL RestartComputer (void) +{ + TOKEN_PRIVILEGES tokenPrivil; + HANDLE hTkn; + + if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES, &hTkn)) + { + return false; + } + + LookupPrivilegeValue (NULL, SE_SHUTDOWN_NAME, &tokenPrivil.Privileges[0].Luid); + tokenPrivil.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + tokenPrivil.PrivilegeCount = 1; + + AdjustTokenPrivileges (hTkn, false, &tokenPrivil, 0, (PTOKEN_PRIVILEGES) NULL, 0); + if (GetLastError() != ERROR_SUCCESS) + { + CloseHandle(hTkn); + return false; + } + + if (!ExitWindowsEx (EWX_REBOOT, + SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED)) + { + CloseHandle(hTkn); + return false; + } + + CloseHandle(hTkn); + return true; +} + + +std::wstring GetWindowsEdition () +{ + wstring osname = L"win"; + + OSVERSIONINFOEXW osVer; + osVer.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW); + GetVersionExW ((LPOSVERSIONINFOW) &osVer); + + BOOL home = (osVer.wSuiteMask & VER_SUITE_PERSONAL); + BOOL server = (osVer.wProductType == VER_NT_SERVER || osVer.wProductType == VER_NT_DOMAIN_CONTROLLER); + + HKEY hkey; + wchar_t productName[300] = {0}; + DWORD productNameSize = sizeof (productName); + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS) + { + if (RegQueryValueEx (hkey, L"ProductName", 0, 0, (LPBYTE) &productName, &productNameSize) != ERROR_SUCCESS || productNameSize < 1) + productName[0] = 0; + + RegCloseKey (hkey); + } + + switch (nCurrentOS) + { + case WIN_2000: + osname += L"2000"; + break; + + case WIN_XP: + case WIN_XP64: + osname += L"xp"; + osname += home ? L"-home" : L"-pro"; + break; + + case WIN_SERVER_2003: + osname += L"2003"; + break; + + case WIN_VISTA: + osname += L"vista"; + break; + + case WIN_SERVER_2008: + osname += L"2008"; + break; + + case WIN_7: + osname += L"7"; + break; + + case WIN_SERVER_2008_R2: + osname += L"2008r2"; + break; + + default: + wstringstream s; + s << CurrentOSMajor << L"." << CurrentOSMinor; + osname += s.str(); + break; + } + + if (server) + osname += L"-server"; + + if (IsOSAtLeast (WIN_VISTA)) + { + if (home) + osname += L"-home"; + else if (wcsstr (productName, L"Standard") != 0) + osname += L"-standard"; + else if (wcsstr (productName, L"Professional") != 0) + osname += L"-pro"; + else if (wcsstr (productName, L"Business") != 0) + osname += L"-business"; + else if (wcsstr (productName, L"Enterprise") != 0) + osname += L"-enterprise"; + else if (wcsstr (productName, L"Datacenter") != 0) + osname += L"-datacenter"; + else if (wcsstr (productName, L"Ultimate") != 0) + osname += L"-ultimate"; + } + + if (GetSystemMetrics (SM_STARTER)) + osname += L"-starter"; + else if (wcsstr (productName, L"Basic") != 0) + osname += L"-basic"; + + if (Is64BitOs()) + osname += L"-x64"; + + if (CurrentOSServicePack > 0) + { + wstringstream s; + s << L"-sp" << CurrentOSServicePack; + osname += s.str(); + } + + return osname; +} + + +void Applink (char *dest, BOOL bSendOS, char *extraOutput) +{ + char url [MAX_URL_LENGTH]; + + ArrowWaitCursor (); + + // sprintf_s (url, sizeof (url), TC_APPLINK "%s%s&dest=%s", bSendOS ? ("&os=" + GetWindowsEdition()).c_str() : "", extraOutput, dest); + if (strcmp(dest, "donate") == 0) + { + StringCbCopyA (url, sizeof (url),"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5BCXVMTTNJDCY"); + } + else if (strcmp(dest, "main") == 0) + { + StringCbCopyA (url, sizeof (url),TC_HOMEPAGE); + } + else if (strcmp(dest,"localizations") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Language%20Packs"); + } + else if (strcmp(dest, "beginnerstutorial") == 0 || strcmp(dest,"tutorial") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Beginner%27s%20Tutorial"); + } + else if (strcmp(dest, "releasenotes") == 0 || strcmp(dest, "history") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Release%20Notes"); + } + else if (strcmp(dest, "hwacceleration") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Hardware%20Acceleration"); + } + else if (strcmp(dest, "parallelization") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Parallelization"); + } + else if (strcmp(dest, "help") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/documentation"); + } + else if (strcmp(dest, "keyfiles") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Keyfiles"); + } + else if (strcmp(dest, "introcontainer") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Creating%20New%20Volumes"); + } + else if (strcmp(dest, "introsysenc") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=System%20Encryption"); + } + else if (strcmp(dest, "hiddensysenc") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=VeraCrypt%20Hidden%20Operating%20System"); + } + else if (strcmp(dest, "sysencprogressinfo") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=System%20Encryption"); + } + else if (strcmp(dest, "hiddenvolume") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Hidden%20Volume"); + } + else if (strcmp(dest, "aes") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=AES"); + } + else if (strcmp(dest, "serpent") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Serpent"); + } + else if (strcmp(dest, "twofish") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Twofish"); + } + else if (strcmp(dest, "cascades") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Cascades"); + } + else if (strcmp(dest, "hashalgorithms") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Hash%20Algorithms"); + } + else if (strcmp(dest, "isoburning") == 0) + { + StringCbCopyA (url, sizeof (url),"https://cdburnerxp.se/en/home"); + } + else if (strcmp(dest, "sysfavorites") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=System%20Favorite%20Volumes"); + } + else if (strcmp(dest, "favorites") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Favorite%20Volumes"); + } + else if (strcmp(dest, "hiddenvolprotection") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Protection%20of%20Hidden%20Volumes"); + } + else if (strcmp(dest, "faq") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=FAQ"); + } + else if (strcmp(dest, "downloads") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Downloads"); + } + else if (strcmp(dest, "news") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=News"); + } + else if (strcmp(dest, "contact") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Contact"); + } + else if (strcmp(dest, "pim") == 0) + { + StringCbCopyA (url, sizeof (url),"https://veracrypt.codeplex.com/wikipage?title=Personal%20Iterations%20Multiplier%20%28PIM%29"); + } + else + { + StringCbCopyA (url, sizeof (url),TC_APPLINK); + } + ShellExecuteA (NULL, "open", url, NULL, NULL, SW_SHOWNORMAL); + + Sleep (200); + NormalCursor (); +} + + +wchar_t *RelativePath2Absolute (wchar_t *szFileName) +{ + if (szFileName[0] != L'\\' + && wcschr (szFileName, L':') == 0 + && wcsstr (szFileName, L"Volume{") != szFileName) + { + wchar_t path[MAX_PATH*2]; + GetCurrentDirectory (MAX_PATH, path); + + if (path[wcslen (path) - 1] != L'\\') + StringCbCatW (path, (MAX_PATH * 2), L"\\"); + + StringCbCatW (path, (MAX_PATH * 2), szFileName); + StringCbCopyW (szFileName, MAX_PATH + 1, path); // szFileName size is always at least (MAX_PATH + 1) + } + + return szFileName; +} + + +void HandleDriveNotReadyError (HWND hwnd) +{ + HKEY hkey = 0; + DWORD value = 0, size = sizeof (DWORD); + + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Services\\MountMgr", + 0, KEY_READ, &hkey) != ERROR_SUCCESS) + return; + + if (RegQueryValueEx (hkey, L"NoAutoMount", 0, 0, (LPBYTE) &value, &size) == ERROR_SUCCESS + && value != 0) + { + Warning ("SYS_AUTOMOUNT_DISABLED", hwnd); + } + else if (nCurrentOS == WIN_VISTA && CurrentOSServicePack < 1) + Warning ("SYS_ASSIGN_DRIVE_LETTER", hwnd); + else + Warning ("DEVICE_NOT_READY_ERROR", hwnd); + + RegCloseKey (hkey); +} + + +BOOL CALLBACK CloseTCWindowsEnum (HWND hwnd, LPARAM lParam) +{ + LONG_PTR userDataVal = GetWindowLongPtrW (hwnd, GWLP_USERDATA); + if ((userDataVal == (LONG_PTR) 'VERA') || (userDataVal == (LONG_PTR) 'TRUE')) // Prior to 1.0e, 'TRUE' was used for VeraCrypt dialogs + { + wchar_t name[1024] = { 0 }; + GetWindowText (hwnd, name, ARRAYSIZE (name) - 1); + if (hwnd != MainDlg && wcsstr (name, L"VeraCrypt")) + { + PostMessage (hwnd, TC_APPMSG_CLOSE_BKG_TASK, 0, 0); + + PostMessage (hwnd, WM_CLOSE, 0, 0); + + if (lParam != 0) + *((BOOL *)lParam) = TRUE; + } + } + return TRUE; +} + +BOOL CALLBACK FindTCWindowEnum (HWND hwnd, LPARAM lParam) +{ + if (*(HWND *)lParam == hwnd) + return TRUE; + + LONG_PTR userDataVal = GetWindowLongPtrW (hwnd, GWLP_USERDATA); + if ((userDataVal == (LONG_PTR) 'VERA') || (userDataVal == (LONG_PTR) 'TRUE')) // Prior to 1.0e, 'TRUE' was used for VeraCrypt dialogs + { + wchar_t name[32] = { 0 }; + GetWindowText (hwnd, name, ARRAYSIZE (name) - 1); + if (hwnd != MainDlg && wcscmp (name, L"VeraCrypt") == 0) + { + if (lParam != 0) + *((HWND *)lParam) = hwnd; + } + } + return TRUE; +} + + +BYTE *MapResource (wchar_t *resourceType, int resourceId, PDWORD size) +{ + HGLOBAL hResL; + HRSRC hRes; + + hRes = FindResource (NULL, MAKEINTRESOURCE(resourceId), resourceType); + hResL = LoadResource (NULL, hRes); + + if (size != NULL) + *size = SizeofResource (NULL, hRes); + + return (BYTE *) LockResource (hResL); +} + + +void InconsistencyResolved (char *techInfo) +{ + wchar_t finalMsg[8024]; + + StringCbPrintfW (finalMsg, sizeof(finalMsg), GetString ("INCONSISTENCY_RESOLVED"), techInfo); + MessageBoxW (MainDlg, finalMsg, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); +} + + +void ReportUnexpectedState (char *techInfo) +{ + wchar_t finalMsg[8024]; + + StringCbPrintfW (finalMsg, sizeof(finalMsg), GetString ("UNEXPECTED_STATE"), techInfo); + MessageBoxW (MainDlg, finalMsg, lpszTitle, MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); +} + + +#ifndef SETUP + +int OpenVolume (OpenVolumeContext *context, const wchar_t *volumePath, Password *password, int pkcs5_prf, int pim, BOOL truecryptMode, BOOL write, BOOL preserveTimestamps, BOOL useBackupHeader) +{ + int status = ERR_PARAMETER_INCORRECT; + int volumeType; + wchar_t szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH]; + wchar_t szDosDevice[TC_MAX_PATH]; + char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; + LARGE_INTEGER headerOffset; + DWORD dwResult; + DISK_GEOMETRY deviceGeometry; + + context->VolumeIsOpen = FALSE; + context->CryptoInfo = NULL; + context->HostFileHandle = INVALID_HANDLE_VALUE; + context->TimestampsValid = FALSE; + + CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), volumePath, &context->IsDevice); + + if (context->IsDevice) + { + status = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice), szCFDevice, sizeof(szCFDevice), FALSE); + if (status != 0) + return status; + + preserveTimestamps = FALSE; + + if (!GetDriveGeometry (volumePath, &deviceGeometry)) + { + status = ERR_OS_ERROR; + goto error; + } + } + else + StringCbCopyW (szCFDevice, sizeof(szCFDevice), szDiskFile); + + if (preserveTimestamps) + write = TRUE; + + context->HostFileHandle = CreateFile (szCFDevice, GENERIC_READ | (write ? GENERIC_WRITE : 0), FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (context->HostFileHandle == INVALID_HANDLE_VALUE) + { + status = ERR_OS_ERROR; + goto error; + } + + if (context->IsDevice) + { + // Try to gain "raw" access to the partition in case there is a live filesystem on it (otherwise, + // the NTFS driver guards hidden sectors and prevents e.g. header backup restore after the user + // accidentally quick-formats a dismounted partition-hosted TrueCrypt volume as NTFS, etc.) + + DeviceIoControl (context->HostFileHandle, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, 0, NULL, 0, &dwResult, NULL); + } + + context->VolumeIsOpen = TRUE; + + // Remember the container modification/creation date and time + if (!context->IsDevice && preserveTimestamps) + { + if (GetFileTime (context->HostFileHandle, &context->CreationTime, &context->LastAccessTime, &context->LastWriteTime) == 0) + context->TimestampsValid = FALSE; + else + context->TimestampsValid = TRUE; + } + + // Determine host size + if (context->IsDevice) + { + PARTITION_INFORMATION diskInfo; + + if (GetPartitionInfo (volumePath, &diskInfo)) + { + context->HostSize = diskInfo.PartitionLength.QuadPart; + } + else + { + DISK_GEOMETRY driveInfo; + + if (!DeviceIoControl (context->HostFileHandle, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveInfo, sizeof (driveInfo), &dwResult, NULL)) + { + status = ERR_OS_ERROR; + goto error; + } + + context->HostSize = driveInfo.Cylinders.QuadPart * driveInfo.BytesPerSector * driveInfo.SectorsPerTrack * driveInfo.TracksPerCylinder; + } + + if (context->HostSize == 0) + { + status = ERR_VOL_SIZE_WRONG; + goto error; + } + } + else + { + LARGE_INTEGER fileSize; + if (!GetFileSizeEx (context->HostFileHandle, &fileSize)) + { + status = ERR_OS_ERROR; + goto error; + } + + context->HostSize = fileSize.QuadPart; + } + + for (volumeType = TC_VOLUME_TYPE_NORMAL; volumeType < TC_VOLUME_TYPE_COUNT; volumeType++) + { + // Seek the volume header + switch (volumeType) + { + case TC_VOLUME_TYPE_NORMAL: + headerOffset.QuadPart = useBackupHeader ? context->HostSize - TC_VOLUME_HEADER_GROUP_SIZE : TC_VOLUME_HEADER_OFFSET; + break; + + case TC_VOLUME_TYPE_HIDDEN: + if (TC_HIDDEN_VOLUME_HEADER_OFFSET + TC_VOLUME_HEADER_SIZE > context->HostSize) + continue; + + headerOffset.QuadPart = useBackupHeader ? context->HostSize - TC_VOLUME_HEADER_SIZE : TC_HIDDEN_VOLUME_HEADER_OFFSET; + break; + + } + + if (!SetFilePointerEx ((HANDLE) context->HostFileHandle, headerOffset, NULL, FILE_BEGIN)) + { + status = ERR_OS_ERROR; + goto error; + } + + // Read volume header + DWORD bytesRead; + if (!ReadEffectiveVolumeHeader (context->IsDevice, context->HostFileHandle, (byte *) buffer, &bytesRead)) + { + status = ERR_OS_ERROR; + goto error; + } + + if (bytesRead != sizeof (buffer) + && context->IsDevice) + { + // If FSCTL_ALLOW_EXTENDED_DASD_IO failed and there is a live filesystem on the partition, then the + // filesystem driver may report EOF when we are reading hidden sectors (when the filesystem is + // shorter than the partition). This can happen for example after the user quick-formats a dismounted + // partition-hosted TrueCrypt volume and then tries to read the embedded backup header. + + memset (buffer, 0, sizeof (buffer)); + } + + // Decrypt volume header + status = ReadVolumeHeader (FALSE, buffer, password, pkcs5_prf, pim, truecryptMode, &context->CryptoInfo, NULL); + + if (status == ERR_PASSWORD_WRONG) + continue; // Try next volume type + + break; + } + + if (status == ERR_SUCCESS) + return status; + +error: + DWORD sysError = GetLastError (); + + CloseVolume (context); + + SetLastError (sysError); + return status; +} + + +void CloseVolume (OpenVolumeContext *context) +{ + if (!context->VolumeIsOpen) + return; + + if (context->HostFileHandle != INVALID_HANDLE_VALUE) + { + if (context->TimestampsValid) + SetFileTime (context->HostFileHandle, &context->CreationTime, &context->LastAccessTime, &context->LastWriteTime); + + CloseHandle (context->HostFileHandle); + context->HostFileHandle = INVALID_HANDLE_VALUE; + } + + if (context->CryptoInfo) + { + crypto_close (context->CryptoInfo); + context->CryptoInfo = NULL; + } + + context->VolumeIsOpen = FALSE; +} + + +int ReEncryptVolumeHeader (HWND hwndDlg, char *buffer, BOOL bBoot, CRYPTO_INFO *cryptoInfo, Password *password, int pim, BOOL wipeMode) +{ + CRYPTO_INFO *newCryptoInfo = NULL; + + RandSetHashFunction (cryptoInfo->pkcs5); + + if (Randinit() != ERR_SUCCESS) + { + if (CryptoAPILastError == ERROR_SUCCESS) + return ERR_RAND_INIT_FAILED; + else + return ERR_CAPI_INIT_FAILED; + } + + UserEnrichRandomPool (NULL); + + int status = CreateVolumeHeaderInMemory (hwndDlg, bBoot, + buffer, + cryptoInfo->ea, + cryptoInfo->mode, + password, + cryptoInfo->pkcs5, + pim, + (char *) cryptoInfo->master_keydata, + &newCryptoInfo, + cryptoInfo->VolumeSize.Value, + cryptoInfo->hiddenVolume ? cryptoInfo->hiddenVolumeSize : 0, + cryptoInfo->EncryptedAreaStart.Value, + cryptoInfo->EncryptedAreaLength.Value, + cryptoInfo->RequiredProgramVersion, + cryptoInfo->HeaderFlags, + cryptoInfo->SectorSize, + wipeMode); + + if (newCryptoInfo != NULL) + crypto_close (newCryptoInfo); + + return status; +} + +#endif // !SETUP + + +BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) +{ + // GlobalMemoryStatusEx() cannot be used to determine if a paging file is active + + wchar_t data[65536]; + DWORD size = sizeof (data); + + if (IsPagingFileWildcardActive()) + return TRUE; + + if (ReadLocalMachineRegistryMultiString (L"System\\CurrentControlSet\\Control\\Session Manager\\Memory Management", L"PagingFiles", data, &size) + && size > 24 && !checkNonWindowsPartitionsOnly) + return TRUE; + + if (!IsAdmin()) + AbortProcess ("UAC_INIT_ERROR"); + + for (wchar_t drive = L'C'; drive <= L'Z'; ++drive) + { + // Query geometry of the drive first to prevent "no medium" pop-ups + wstring drivePath = L"\\\\.\\X:"; + drivePath[4] = drive; + + if (checkNonWindowsPartitionsOnly) + { + wchar_t sysDir[MAX_PATH]; + if (GetSystemDirectory (sysDir, ARRAYSIZE (sysDir)) != 0 && towupper (sysDir[0]) == drive) + continue; + } + + HANDLE handle = CreateFile (drivePath.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (handle == INVALID_HANDLE_VALUE) + continue; + + DISK_GEOMETRY driveInfo; + DWORD dwResult; + + if (!DeviceIoControl (handle, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveInfo, sizeof (driveInfo), &dwResult, NULL)) + { + CloseHandle (handle); + continue; + } + + CloseHandle (handle); + + // Test if a paging file exists and is locked by another process + wstring path = L"X:\\pagefile.sys"; + path[0] = drive; + + handle = CreateFile (path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); + + if (handle != INVALID_HANDLE_VALUE) + CloseHandle (handle); + else if (GetLastError() == ERROR_SHARING_VIOLATION) + return TRUE; + } + + return FALSE; +} + + +BOOL IsPagingFileWildcardActive () +{ + wchar_t pagingFiles[65536]; + DWORD size = sizeof (pagingFiles); + wchar_t *mmKey = L"System\\CurrentControlSet\\Control\\Session Manager\\Memory Management"; + + if (!ReadLocalMachineRegistryString (mmKey, L"PagingFiles", pagingFiles, &size)) + { + size = sizeof (pagingFiles); + if (!ReadLocalMachineRegistryMultiString (mmKey, L"PagingFiles", pagingFiles, &size)) + size = 0; + } + + return size > 0 && wcsstr (pagingFiles, L"?:\\") == pagingFiles; +} + + +BOOL DisablePagingFile () +{ + wchar_t empty[] = { 0, 0 }; + return WriteLocalMachineRegistryMultiString (L"System\\CurrentControlSet\\Control\\Session Manager\\Memory Management", L"PagingFiles", empty, sizeof (empty)); +} + + +std::wstring SingleStringToWide (const std::string &singleString) +{ + if (singleString.empty()) + return std::wstring(); + + WCHAR wbuf[65536]; + int wideLen = MultiByteToWideChar (CP_ACP, 0, singleString.c_str(), -1, wbuf, array_capacity (wbuf) - 1); + + // We don't throw exception here and only return empty string. + // All calls to this function use valid strings. + // throw_sys_if (wideLen == 0); + + wbuf[wideLen] = 0; + return wbuf; +} + + +std::wstring Utf8StringToWide (const std::string &utf8String) +{ + if (utf8String.empty()) + return std::wstring(); + + WCHAR wbuf[65536]; + int wideLen = MultiByteToWideChar (CP_UTF8, 0, utf8String.c_str(), -1, wbuf, array_capacity (wbuf) - 1); + throw_sys_if (wideLen == 0); + + wbuf[wideLen] = 0; + return wbuf; +} + + +std::string WideToUtf8String (const std::wstring &wideString) +{ + if (wideString.empty()) + return std::string(); + + char buf[65536]; + int len = WideCharToMultiByte (CP_UTF8, 0, wideString.c_str(), -1, buf, array_capacity (buf) - 1, NULL, NULL); + throw_sys_if (len == 0); + + buf[len] = 0; + return buf; +} + + +#ifndef SETUP + +BOOL CALLBACK SecurityTokenPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + static string *password; + + switch (msg) + { + case WM_INITDIALOG: + { + password = (string *) lParam; + LocalizeDialog (hwndDlg, "IDD_TOKEN_PASSWORD"); + + wchar_t s[1024]; + StringCbPrintfW (s, sizeof(s), GetString ("ENTER_TOKEN_PASSWORD"), Utf8StringToWide (password->c_str()).c_str()); + SetWindowTextW (GetDlgItem (hwndDlg, IDT_TOKEN_PASSWORD_INFO), s); + + SendMessage (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD), EM_LIMITTEXT, SecurityToken::MaxPasswordLength, 0); + + SetForegroundWindow (hwndDlg); + SetFocus (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD)); + } + return 0; + + case WM_COMMAND: + if (lw == IDCANCEL || lw == IDOK) + { + if (lw == IDOK) + { + wchar_t passwordWide[SecurityToken::MaxPasswordLength + 1]; + + if (GetWindowTextW (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD), passwordWide, SecurityToken::MaxPasswordLength + 1) == 0) + { + handleWin32Error (hwndDlg, SRC_POS); + break; + } + + char passwordUtf8[SecurityToken::MaxPasswordLength + 1]; + + int len = WideCharToMultiByte (CP_UTF8, 0, passwordWide, -1, passwordUtf8, array_capacity (passwordUtf8) - 1, nullptr, nullptr); + passwordUtf8[len] = 0; + *password = passwordUtf8; + + burn (passwordWide, sizeof (passwordWide)); + burn (passwordUtf8, sizeof (passwordUtf8)); + } + + // Attempt to wipe password stored in the input field buffer + wchar_t tmp[SecurityToken::MaxPasswordLength+1]; + wmemset (tmp, 'X', SecurityToken::MaxPasswordLength); + tmp[SecurityToken::MaxPasswordLength] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD), tmp); + + EndDialog (hwndDlg, lw); + } + return 1; + } + + return 0; +} + + +struct NewSecurityTokenKeyfileDlgProcParams +{ + CK_SLOT_ID SlotId; + string Name; +}; + +static BOOL CALLBACK NewSecurityTokenKeyfileDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + static NewSecurityTokenKeyfileDlgProcParams *newParams; + + WORD lw = LOWORD (wParam); + switch (msg) + { + case WM_INITDIALOG: + { + LocalizeDialog (hwndDlg, "IDD_NEW_TOKEN_KEYFILE"); + + newParams = (NewSecurityTokenKeyfileDlgProcParams *) lParam; + + WaitCursor(); + finally_do ({ NormalCursor(); }); + + list tokens; + + try + { + tokens = SecurityToken::GetAvailableTokens(); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + + if (tokens.empty()) + { + Error ("NO_TOKENS_FOUND", hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + foreach (const SecurityTokenInfo &token, tokens) + { + wstringstream tokenLabel; + tokenLabel << L"[" << token.SlotId << L"] " << token.Label; + + AddComboPair (GetDlgItem (hwndDlg, IDC_SELECTED_TOKEN), tokenLabel.str().c_str(), token.SlotId); + } + + ComboBox_SetCurSel (GetDlgItem (hwndDlg, IDC_SELECTED_TOKEN), 0); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_TOKEN_KEYFILE_NAME), Utf8StringToWide (newParams->Name).c_str()); + return 1; + } + + case WM_COMMAND: + switch (lw) + { + case IDOK: + { + int selectedToken = ComboBox_GetCurSel (GetDlgItem (hwndDlg, IDC_SELECTED_TOKEN)); + if (selectedToken == CB_ERR) + { + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + newParams->SlotId = (CK_SLOT_ID) ComboBox_GetItemData (GetDlgItem (hwndDlg, IDC_SELECTED_TOKEN), selectedToken); + + wchar_t name[1024]; + if (GetWindowTextW (GetDlgItem (hwndDlg, IDC_TOKEN_KEYFILE_NAME), name, array_capacity (name)) != 0) + { + try + { + newParams->Name = WideToUtf8String (name); + } + catch (...) { } + } + + EndDialog (hwndDlg, IDOK); + return 1; + } + + case IDCANCEL: + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + if (HIWORD (wParam) == EN_CHANGE) + { + wchar_t name[2]; + EnableWindow (GetDlgItem (hwndDlg, IDOK), (GetWindowTextW (GetDlgItem (hwndDlg, IDC_TOKEN_KEYFILE_NAME), name, array_capacity (name)) != 0)); + return 1; + } + } + + return 0; +} + + +static void SecurityTokenKeyfileDlgFillList (HWND hwndDlg, const vector &keyfiles) +{ + HWND tokenListControl = GetDlgItem (hwndDlg, IDC_TOKEN_FILE_LIST); + LVITEMW lvItem; + int line = 0; + + ListView_DeleteAllItems (tokenListControl); + + foreach (const SecurityTokenKeyfile &keyfile, keyfiles) + { + memset (&lvItem, 0, sizeof(lvItem)); + lvItem.mask = LVIF_TEXT; + lvItem.iItem = line++; + + wstringstream s; + s << keyfile.SlotId; + + ListItemAdd (tokenListControl, lvItem.iItem, (wchar_t *) s.str().c_str()); + ListSubItemSet (tokenListControl, lvItem.iItem, 1, (wchar_t *) keyfile.Token.Label.c_str()); + ListSubItemSet (tokenListControl, lvItem.iItem, 2, (wchar_t *) keyfile.Id.c_str()); + } + + BOOL selected = (ListView_GetNextItem (GetDlgItem (hwndDlg, IDC_TOKEN_FILE_LIST), -1, LVIS_SELECTED) != -1); + EnableWindow (GetDlgItem (hwndDlg, IDC_EXPORT), selected); + EnableWindow (GetDlgItem (hwndDlg, IDC_DELETE), selected); +} + + +static list SecurityTokenKeyfileDlgGetSelected (HWND hwndDlg, const vector &keyfiles) +{ + HWND tokenListControl = GetDlgItem (hwndDlg, IDC_TOKEN_FILE_LIST); + list selectedKeyfiles; + + int itemId = -1; + while ((itemId = ListView_GetNextItem (tokenListControl, itemId, LVIS_SELECTED)) != -1) + { + selectedKeyfiles.push_back (keyfiles[itemId]); + } + + return selectedKeyfiles; +} + + +BOOL CALLBACK SecurityTokenKeyfileDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + static list *selectedTokenKeyfiles; + static vector keyfiles; + + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + selectedTokenKeyfiles = (list *) lParam; + + LVCOLUMNW LvCol; + HWND tokenListControl = GetDlgItem (hwndDlg, IDC_TOKEN_FILE_LIST); + + LocalizeDialog (hwndDlg, selectedTokenKeyfiles ? "SELECT_TOKEN_KEYFILES" : "IDD_TOKEN_KEYFILES"); + + SendMessage (tokenListControl,LVM_SETEXTENDEDLISTVIEWSTYLE, 0, + LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_TWOCLICKACTIVATE|LVS_EX_LABELTIP + ); + + memset (&LvCol, 0, sizeof(LvCol)); + LvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; + LvCol.pszText = GetString ("TOKEN_SLOT_ID"); + LvCol.cx = CompensateXDPI (40); + LvCol.fmt = LVCFMT_CENTER; + SendMessage (tokenListControl, LVM_INSERTCOLUMNW, 1, (LPARAM)&LvCol); + + LvCol.pszText = GetString ("TOKEN_NAME"); + LvCol.cx = CompensateXDPI (128); + LvCol.fmt = LVCFMT_LEFT; + SendMessage (tokenListControl, LVM_INSERTCOLUMNW, 2, (LPARAM)&LvCol); + + LvCol.pszText = GetString ("TOKEN_DATA_OBJECT_LABEL"); + LvCol.cx = CompensateXDPI (195); + LvCol.fmt = LVCFMT_LEFT; + SendMessage (tokenListControl, LVM_INSERTCOLUMNW, 3, (LPARAM)&LvCol); + + keyfiles.clear(); + + try + { + WaitCursor(); + finally_do ({ NormalCursor(); }); + + keyfiles = SecurityToken::GetAvailableKeyfiles(); + } + catch (UserAbort&) + { + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + catch (Exception &e) + { + e.Show (hwndDlg); + + if (keyfiles.empty()) + { + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + } + + SecurityTokenKeyfileDlgFillList (hwndDlg, keyfiles); + return 1; + } + + case WM_COMMAND: + case WM_NOTIFY: + if (msg == WM_COMMAND && lw == IDOK || msg == WM_NOTIFY && ((NMHDR *)lParam)->code == LVN_ITEMACTIVATE) + { + if (selectedTokenKeyfiles) + { + foreach (const SecurityTokenKeyfile &keyfile, SecurityTokenKeyfileDlgGetSelected (hwndDlg, keyfiles)) + { + selectedTokenKeyfiles->push_back (SecurityTokenKeyfilePath (keyfile)); + } + } + + EndDialog (hwndDlg, IDOK); + return 1; + } + + if (msg == WM_NOTIFY && ((LPNMHDR) lParam)->code == LVN_ITEMCHANGED) + { + BOOL selected = (ListView_GetNextItem (GetDlgItem (hwndDlg, IDC_TOKEN_FILE_LIST), -1, LVIS_SELECTED) != -1); + EnableWindow (GetDlgItem (hwndDlg, IDC_EXPORT), selected); + EnableWindow (GetDlgItem (hwndDlg, IDC_DELETE), selected); + return 1; + } + + if (msg == WM_COMMAND) + { + switch (lw) + { + case IDCANCEL: + EndDialog (hwndDlg, IDCANCEL); + return 1; + + case IDC_IMPORT_KEYFILE: + { + wchar_t keyfilePath[TC_MAX_PATH]; + + if (BrowseFiles (hwndDlg, "SELECT_KEYFILE", keyfilePath, bHistory, FALSE, NULL)) + { + DWORD keyfileSize; + byte *keyfileData = (byte *) LoadFile (keyfilePath, &keyfileSize); + if (!keyfileData) + { + handleWin32Error (hwndDlg, SRC_POS); + return 1; + } + + if (keyfileSize != 0) + { + NewSecurityTokenKeyfileDlgProcParams newParams; + newParams.Name = WideToUtf8String (keyfilePath); + + size_t lastBackSlash = newParams.Name.find_last_of ('\\'); + if (lastBackSlash != string::npos) + newParams.Name = newParams.Name.substr (lastBackSlash + 1); + + if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_NEW_TOKEN_KEYFILE), hwndDlg, (DLGPROC) NewSecurityTokenKeyfileDlgProc, (LPARAM) &newParams) == IDOK) + { + vector keyfileDataVector (keyfileSize); + memcpy (&keyfileDataVector.front(), keyfileData, keyfileSize); + + try + { + WaitCursor(); + finally_do ({ NormalCursor(); }); + + SecurityToken::CreateKeyfile (newParams.SlotId, keyfileDataVector, newParams.Name); + + keyfiles = SecurityToken::GetAvailableKeyfiles(); + SecurityTokenKeyfileDlgFillList (hwndDlg, keyfiles); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + + burn (&keyfileDataVector.front(), keyfileSize); + } + } + else + { + SetLastError (ERROR_HANDLE_EOF); + handleWin32Error (hwndDlg, SRC_POS); + } + + burn (keyfileData, keyfileSize); + TCfree (keyfileData); + } + + return 1; + } + + case IDC_EXPORT: + { + try + { + foreach (const SecurityTokenKeyfile &keyfile, SecurityTokenKeyfileDlgGetSelected (hwndDlg, keyfiles)) + { + wchar_t keyfilePath[TC_MAX_PATH]; + + if (!BrowseFiles (hwndDlg, "OPEN_TITLE", keyfilePath, bHistory, TRUE, NULL)) + break; + + { + WaitCursor(); + finally_do ({ NormalCursor(); }); + + vector keyfileData; + + SecurityToken::GetKeyfileData (keyfile, keyfileData); + + if (keyfileData.empty()) + { + SetLastError (ERROR_HANDLE_EOF); + handleWin32Error (hwndDlg, SRC_POS); + return 1; + } + + finally_do_arg (vector *, &keyfileData, { burn (&finally_arg->front(), finally_arg->size()); }); + + if (!SaveBufferToFile ((char *) &keyfileData.front(), keyfilePath, (DWORD) keyfileData.size(), FALSE, FALSE)) + throw SystemException (SRC_POS); + } + + Info ("KEYFILE_EXPORTED", hwndDlg); + } + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + + return 1; + } + + case IDC_DELETE: + { + if (AskNoYes ("CONFIRM_SEL_FILES_DELETE", hwndDlg) == IDNO) + return 1; + + try + { + WaitCursor(); + finally_do ({ NormalCursor(); }); + + foreach (const SecurityTokenKeyfile &keyfile, SecurityTokenKeyfileDlgGetSelected (hwndDlg, keyfiles)) + { + SecurityToken::DeleteKeyfile (keyfile); + } + + keyfiles = SecurityToken::GetAvailableKeyfiles(); + SecurityTokenKeyfileDlgFillList (hwndDlg, keyfiles); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + + return 1; + } + } + } + return 0; + } + return 0; +} + + +BOOL InitSecurityTokenLibrary (HWND hwndDlg) +{ + if (SecurityTokenLibraryPath[0] == 0) + { + Error ("NO_PKCS11_MODULE_SPECIFIED", hwndDlg); + return FALSE; + } + + struct PinRequestHandler : public GetPinFunctor + { + HWND m_hwnd; + PinRequestHandler(HWND hwnd) : m_hwnd(hwnd) {} + virtual void operator() (string &str) + { + HWND hParent = IsWindow (m_hwnd)? m_hwnd : GetActiveWindow(); + if (!hParent) + hParent = GetForegroundWindow (); + if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TOKEN_PASSWORD), hParent, (DLGPROC) SecurityTokenPasswordDlgProc, (LPARAM) &str) == IDCANCEL) + throw UserAbort (SRC_POS); + + if (hCursor != NULL) + SetCursor (hCursor); + } + }; + + struct WarningHandler : public SendExceptionFunctor + { + HWND m_hwnd; + WarningHandler(HWND hwnd) : m_hwnd(hwnd) {} + virtual void operator() (const Exception &e) + { + HWND hParent = IsWindow (m_hwnd)? m_hwnd : GetActiveWindow(); + if (!hParent) + hParent = GetForegroundWindow (); + e.Show (hParent); + } + }; + + try + { + SecurityToken::InitLibrary (SecurityTokenLibraryPath, auto_ptr (new PinRequestHandler(MainDlg)), auto_ptr (new WarningHandler(MainDlg))); + } + catch (Exception &e) + { + e.Show (hwndDlg); + Error ("PKCS11_MODULE_INIT_FAILED", hwndDlg); + return FALSE; + } + + return TRUE; +} + +#endif // !SETUP + +std::vector GetAvailableHostDevices (bool noDeviceProperties, bool singleList, bool noFloppy, bool detectUnencryptedFilesystems) +{ + vector devices; + size_t dev0; + + for (int devNumber = 0; devNumber < MAX_HOST_DRIVE_NUMBER; devNumber++) + { + for (int partNumber = 0; partNumber < MAX_HOST_PARTITION_NUMBER; partNumber++) + { + wstringstream strm; + strm << L"\\Device\\Harddisk" << devNumber << L"\\Partition" << partNumber; + wstring devPathStr (strm.str()); + const wchar_t *devPath = devPathStr.c_str(); + + OPEN_TEST_STRUCT openTest = {0}; + if (!OpenDevice (devPath, &openTest, detectUnencryptedFilesystems && partNumber != 0, FALSE, NULL)) + { + if (partNumber == 0) + break; + + continue; + } + + HostDevice device; + device.SystemNumber = devNumber; + device.Path = devPath; + + PARTITION_INFORMATION partInfo; + + if (GetPartitionInfo (devPath, &partInfo)) + { + device.Bootable = partInfo.BootIndicator ? true : false; + device.Size = partInfo.PartitionLength.QuadPart; + } + else + { + // retrieve size using DISK_GEOMETRY + DISK_GEOMETRY deviceGeometry = {0}; + if ( GetDriveGeometry (devPath, &deviceGeometry) + || ((partNumber == 0) && GetPhysicalDriveGeometry (devNumber, &deviceGeometry)) + ) + { + device.Size = deviceGeometry.Cylinders.QuadPart * (LONGLONG) deviceGeometry.BytesPerSector + * (LONGLONG) deviceGeometry.SectorsPerTrack * (LONGLONG) deviceGeometry.TracksPerCylinder; + } + } + + device.HasUnencryptedFilesystem = (detectUnencryptedFilesystems && openTest.FilesystemDetected) ? true : false; + + if (!noDeviceProperties) + { + DISK_GEOMETRY geometry; + + int driveNumber = GetDiskDeviceDriveLetter ((wchar_t *) devPathStr.c_str()); + + if (driveNumber >= 0) + { + device.MountPoint += (wchar_t) (driveNumber + L'A'); + device.MountPoint += L":"; + + wchar_t name[64]; + if (GetDriveLabel (driveNumber, name, sizeof (name))) + device.Name = name; + + if (GetSystemDriveLetter() == L'A' + driveNumber) + device.ContainsSystem = true; + } + + if (partNumber == 0 && GetDriveGeometry (devPath, &geometry)) + device.Removable = (geometry.MediaType == RemovableMedia); + } + + if (partNumber == 0) + { + devices.push_back (device); + dev0 = devices.size() - 1; + } + else + { + // System creates a virtual partition1 for some storage devices without + // partition table. We try to detect this case by comparing sizes of + // partition0 and partition1. If they match, no partition of the device + // is displayed to the user to avoid confusion. Drive letter assigned by + // system to partition1 is assigned partition0 + if (partNumber == 1 && devices[dev0].Size == device.Size) + { + devices[dev0].IsVirtualPartition = true; + devices[dev0].MountPoint = device.MountPoint; + devices[dev0].Name = device.Name; + devices[dev0].Path = device.Path; + devices[dev0].HasUnencryptedFilesystem = device.HasUnencryptedFilesystem; + break; + } + + device.IsPartition = true; + device.SystemNumber = partNumber; + device.Removable = devices[dev0].Removable; + + if (device.ContainsSystem) + devices[dev0].ContainsSystem = true; + + if (singleList) + devices.push_back (device); + + devices[dev0].Partitions.push_back (device); + } + } + } + + // Vista does not create partition links for dynamic volumes so it is necessary to scan \\Device\\HarddiskVolumeX devices + if (CurrentOSMajor >= 6) + { + for (int devNumber = 0; devNumber < 256; devNumber++) + { + wstringstream strm; + strm << L"\\Device\\HarddiskVolume" << devNumber; + wstring devPathStr (strm.str()); + const wchar_t *devPath = devPathStr.c_str(); + + OPEN_TEST_STRUCT openTest = {0}; + if (!OpenDevice (devPath, &openTest, detectUnencryptedFilesystems, FALSE, NULL)) + continue; + + DISK_PARTITION_INFO_STRUCT info; + if (GetDeviceInfo (devPath, &info) && info.IsDynamic) + { + HostDevice device; + device.DynamicVolume = true; + device.IsPartition = true; + device.SystemNumber = devNumber; + device.Path = devPath; + device.Size = info.partInfo.PartitionLength.QuadPart; + device.HasUnencryptedFilesystem = (detectUnencryptedFilesystems && openTest.FilesystemDetected) ? true : false; + + if (!noDeviceProperties) + { + int driveNumber = GetDiskDeviceDriveLetter ((wchar_t *) devPathStr.c_str()); + + if (driveNumber >= 0) + { + device.MountPoint += (wchar_t) (driveNumber + L'A'); + device.MountPoint += L":"; + + wchar_t name[64]; + if (GetDriveLabel (driveNumber, name, sizeof (name))) + device.Name = name; + + if (GetSystemDriveLetter() == L'A' + driveNumber) + device.ContainsSystem = true; + } + } + + devices.push_back (device); + } + } + } + + return devices; +} + +wstring FindDeviceByVolumeID (const BYTE volumeID [VOLUME_ID_SIZE]) +{ + /* if it is already mounted, get the real path name used for mounting */ + MOUNT_LIST_STRUCT mlist; + DWORD dwResult; + + memset (&mlist, 0, sizeof (mlist)); + DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mlist, + sizeof (mlist), &mlist, sizeof (mlist), &dwResult, + NULL); + + for (int i=0 ; i < 26; i++) + { + if (0 == memcmp (mlist.volumeID[i], volumeID, VOLUME_ID_SIZE)) + return mlist.wszVolume[i]; + } + + /* not mounted. Look for it in the local drives*/ + for (int devNumber = 0; devNumber < MAX_HOST_DRIVE_NUMBER; devNumber++) + { + for (int partNumber = 0; partNumber < MAX_HOST_PARTITION_NUMBER; partNumber++) + { + wstringstream strm; + strm << L"\\Device\\Harddisk" << devNumber << L"\\Partition" << partNumber; + wstring devPathStr (strm.str()); + const wchar_t *devPath = devPathStr.c_str(); + + OPEN_TEST_STRUCT openTest = {0}; + if (!OpenDevice (devPath, &openTest, FALSE, TRUE, volumeID)) + { + continue; + } + + if (openTest.VolumeIDMatched) + return devPath; + } + } + + return L""; +} + +BOOL FileHasReadOnlyAttribute (const wchar_t *path) +{ + DWORD attributes = GetFileAttributes (path); + return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_READONLY) != 0; +} + + +BOOL IsFileOnReadOnlyFilesystem (const wchar_t *path) +{ + wchar_t root[MAX_PATH]; + if (!GetVolumePathName (path, root, ARRAYSIZE (root))) + return FALSE; + + DWORD flags, d; + if (!GetVolumeInformation (root, NULL, 0, NULL, &d, &flags, NULL, 0)) + return FALSE; + + return (flags & FILE_READ_ONLY_VOLUME) ? TRUE : FALSE; +} + + +void CheckFilesystem (HWND hwndDlg, int driveNo, BOOL fixErrors) +{ + wchar_t msg[1024], param[1024], cmdPath[MAX_PATH]; + wchar_t driveRoot[] = { L'A' + (wchar_t) driveNo, L':', 0 }; + + if (fixErrors && AskWarnYesNo ("FILESYS_REPAIR_CONFIRM_BACKUP", hwndDlg) == IDNO) + return; + + StringCbPrintfW (msg, sizeof(msg), GetString (fixErrors ? "REPAIRING_FS" : "CHECKING_FS"), driveRoot); + StringCbPrintfW (param, sizeof(param), fixErrors ? L"/C echo %s & chkdsk %s /F /X & pause" : L"/C echo %s & chkdsk %s & pause", msg, driveRoot); + + if (GetSystemDirectoryW(cmdPath, MAX_PATH)) + { + StringCbCatW(cmdPath, sizeof(cmdPath), L"\\cmd.exe"); + } + else + StringCbCopyW(cmdPath, sizeof(cmdPath), L"C:\\Windows\\System32\\cmd.exe"); + + ShellExecuteW (NULL, (!IsAdmin() && IsUacSupported()) ? L"runas" : L"open", cmdPath, param, NULL, SW_SHOW); +} + + +BOOL BufferContainsString (const byte *buffer, size_t bufferSize, const char *str) +{ + size_t strLen = strlen (str); + + if (bufferSize < strLen) + return FALSE; + + bufferSize -= strLen; + + for (size_t i = 0; i < bufferSize; ++i) + { + if (memcmp (buffer + i, str, strLen) == 0) + return TRUE; + } + + return FALSE; +} + + +#ifndef SETUP + +int AskNonSysInPlaceEncryptionResume (HWND hwndDlg, BOOL *pbDecrypt) +{ + if (AskWarnYesNo ("NONSYS_INPLACE_ENC_RESUME_PROMPT", hwndDlg) == IDYES) + { + char *tmpStr[] = {0, + "CHOOSE_ENCRYPT_OR_DECRYPT", + "ENCRYPT", + "DECRYPT", + "IDCANCEL", + 0}; + + switch (AskMultiChoice ((void **) tmpStr, FALSE, hwndDlg)) + { + case 1: + *pbDecrypt = FALSE; + return IDYES; + case 2: + *pbDecrypt = TRUE; + return IDYES; + default: + break; + } + } + + char *multiChoiceStr[] = { 0, "ASK_NONSYS_INPLACE_ENC_NOTIFICATION_REMOVAL", "DO_NOT_PROMPT_ME", "KEEP_PROMPTING_ME", 0 }; + + switch (AskMultiChoice ((void **) multiChoiceStr, FALSE, hwndDlg)) + { + case 1: + RemoveNonSysInPlaceEncNotifications(); + Warning ("NONSYS_INPLACE_ENC_NOTIFICATION_REMOVAL_NOTE", hwndDlg); + break; + + default: + // NOP + break; + } + + return IDNO; +} + +#endif // !SETUP + + +BOOL RemoveDeviceWriteProtection (HWND hwndDlg, wchar_t *devicePath) +{ + int driveNumber; + int partitionNumber; + + wchar_t temp[MAX_PATH*2]; + wchar_t cmdBatch[MAX_PATH*2]; + wchar_t diskpartScript[MAX_PATH*2]; + + if (swscanf (devicePath, L"\\Device\\Harddisk%d\\Partition%d", &driveNumber, &partitionNumber) != 2) + return FALSE; + + if (GetTempPath (ARRAYSIZE (temp), temp) == 0) + return FALSE; + + StringCbPrintfW (cmdBatch, sizeof (cmdBatch), L"%s\\VeraCrypt_Write_Protection_Removal.cmd", temp); + StringCbPrintfW (diskpartScript, sizeof (diskpartScript), L"%s\\VeraCrypt_Write_Protection_Removal.diskpart", temp); + + FILE *f = _wfopen (cmdBatch, L"w"); + if (!f) + { + handleWin32Error (hwndDlg, SRC_POS); + return FALSE; + } + + fwprintf (f, L"@diskpart /s \"%s\"\n@pause\n@del \"%s\" \"%s\"", diskpartScript, diskpartScript, cmdBatch); + + CheckFileStreamWriteErrors (hwndDlg, f, cmdBatch); + fclose (f); + + f = _wfopen (diskpartScript, L"w"); + if (!f) + { + handleWin32Error (hwndDlg, SRC_POS); + DeleteFile (cmdBatch); + return FALSE; + } + + fwprintf (f, L"select disk %d\nattributes disk clear readonly\n", driveNumber); + + if (partitionNumber != 0) + fwprintf (f, L"select partition %d\nattributes volume clear readonly\n", partitionNumber); + + fwprintf (f, L"exit\n"); + + CheckFileStreamWriteErrors (hwndDlg, f, diskpartScript); + fclose (f); + + ShellExecute (NULL, (!IsAdmin() && IsUacSupported()) ? L"runas" : L"open", cmdBatch, NULL, NULL, SW_SHOW); + + return TRUE; +} + + +static LRESULT CALLBACK EnableElevatedCursorChangeWndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + return DefWindowProcW (hWnd, message, wParam, lParam); +} + + +void EnableElevatedCursorChange (HWND parent) +{ + // Create a transparent window to work around a UAC issue preventing change of the cursor + if (UacElevated) + { + const wchar_t *className = L"VeraCryptEnableElevatedCursorChange"; + WNDCLASSEXW winClass; + HWND hWnd; + + memset (&winClass, 0, sizeof (winClass)); + winClass.cbSize = sizeof (WNDCLASSEX); + winClass.lpfnWndProc = (WNDPROC) EnableElevatedCursorChangeWndProc; + winClass.hInstance = hInst; + winClass.lpszClassName = className; + RegisterClassExW (&winClass); + + hWnd = CreateWindowExW (WS_EX_TOOLWINDOW | WS_EX_LAYERED, className, L"VeraCrypt UAC", 0, 0, 0, GetSystemMetrics (SM_CXSCREEN), GetSystemMetrics (SM_CYSCREEN), parent, NULL, hInst, NULL); + if (hWnd) + { + SetLayeredWindowAttributes (hWnd, 0, 1, LWA_ALPHA); + ShowWindow (hWnd, SW_SHOWNORMAL); + + DestroyWindow (hWnd); + } + UnregisterClassW (className, hInst); + } +} + + +BOOL DisableFileCompression (HANDLE file) +{ + USHORT format; + DWORD bytesOut; + + if (!DeviceIoControl (file, FSCTL_GET_COMPRESSION, NULL, 0, &format, sizeof (format), &bytesOut, NULL)) + return FALSE; + + if (format == COMPRESSION_FORMAT_NONE) + return TRUE; + + format = COMPRESSION_FORMAT_NONE; + return DeviceIoControl (file, FSCTL_SET_COMPRESSION, &format, sizeof (format), NULL, 0, &bytesOut, NULL); +} + + +BOOL VolumePathExists (const wchar_t *volumePath) +{ + OPEN_TEST_STRUCT openTest = {0}; + wchar_t upperCasePath[TC_MAX_PATH + 1]; + + UpperCaseCopy (upperCasePath, sizeof(upperCasePath), volumePath); + + if (wcsstr (upperCasePath, L"\\DEVICE\\") == upperCasePath) + return OpenDevice (volumePath, &openTest, FALSE, FALSE, NULL); + + wstring path = volumePath; + if (path.find (L"\\\\?\\Volume{") == 0 && path.rfind (L"}\\") == path.size() - 2) + { + wchar_t devicePath[TC_MAX_PATH]; + if (QueryDosDevice (path.substr (4, path.size() - 5).c_str(), devicePath, TC_MAX_PATH) != 0) + return TRUE; + } + + if (_waccess (volumePath, 0) == 0) + return TRUE; + else + { + DWORD dwResult = GetLastError (); + if (dwResult == ERROR_SHARING_VIOLATION) + return TRUE; + else + return FALSE; + } +} + + +BOOL IsWindowsIsoBurnerAvailable () +{ + wchar_t path[MAX_PATH*2] = { 0 }; + + if (!IsOSAtLeast (WIN_7)) + { + return FALSE; + } + + if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_SYSTEM, NULL, 0, path))) + { + StringCbCatW (path, MAX_PATH*2, L"\\" ISO_BURNER_TOOL); + + return (FileExists (path)); + } + + return FALSE; +} + + +BOOL LaunchWindowsIsoBurner (HWND hwnd, const wchar_t *isoPath) +{ + wchar_t path[MAX_PATH*2] = { 0 }; + int r; + + if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_SYSTEM, NULL, 0, path))) + StringCbCatW (path, MAX_PATH*2, L"\\" ISO_BURNER_TOOL); + else + StringCbCopyW (path, MAX_PATH*2, L"C:\\Windows\\System32\\" ISO_BURNER_TOOL); + + r = (int) ShellExecute (hwnd, L"open", path, (wstring (L"\"") + isoPath + L"\"").c_str(), NULL, SW_SHOWNORMAL); + + if (r <= 32) + { + SetLastError (r); + handleWin32Error (hwnd, SRC_POS); + + return FALSE; + } + + return TRUE; +} + + +std::wstring VolumeGuidPathToDevicePath (std::wstring volumeGuidPath) +{ + if (volumeGuidPath.find (L"\\\\?\\") == 0) + volumeGuidPath = volumeGuidPath.substr (4); + + if (volumeGuidPath.find (L"Volume{") != 0 || volumeGuidPath.rfind (L"}\\") != volumeGuidPath.size() - 2) + return wstring(); + + wchar_t volDevPath[TC_MAX_PATH]; + if (QueryDosDevice (volumeGuidPath.substr (0, volumeGuidPath.size() - 1).c_str(), volDevPath, TC_MAX_PATH) == 0) + return wstring(); + + wstring partitionPath = HarddiskVolumePathToPartitionPath (volDevPath); + + return partitionPath.empty() ? volDevPath : partitionPath; +} + + +std::wstring HarddiskVolumePathToPartitionPath (const std::wstring &harddiskVolumePath) +{ + for (int driveNumber = 0; driveNumber < MAX_HOST_DRIVE_NUMBER; driveNumber++) + { + for (int partNumber = 0; partNumber < MAX_HOST_PARTITION_NUMBER; partNumber++) + { + wchar_t partitionPath[TC_MAX_PATH]; + StringCchPrintfW (partitionPath, ARRAYSIZE (partitionPath), L"\\Device\\Harddisk%d\\Partition%d", driveNumber, partNumber); + + wchar_t resolvedPath[TC_MAX_PATH]; + if (ResolveSymbolicLink (partitionPath, resolvedPath, sizeof(resolvedPath))) + { + if (harddiskVolumePath == resolvedPath) + return partitionPath; + } + else if (partNumber == 0) + break; + } + } + + return wstring(); +} + + +BOOL IsApplicationInstalled (const wchar_t *appName, BOOL b32bitApp) +{ + const wchar_t *uninstallRegName = L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; + BOOL installed = FALSE; + HKEY unistallKey; + LONG res = RegOpenKeyEx (HKEY_LOCAL_MACHINE, uninstallRegName, 0, KEY_READ | (b32bitApp? KEY_WOW64_32KEY: KEY_WOW64_64KEY), &unistallKey); + if (res != ERROR_SUCCESS) + { + SetLastError (res); + return FALSE; + } + + wchar_t regName[1024]; + DWORD regNameSize = sizeof (regName); + DWORD index = 0; + while (RegEnumKeyEx (unistallKey, index++, regName, ®NameSize, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) + { + if (wcsstr (regName, L"{") == regName) + { + regNameSize = sizeof (regName); + if (!ReadLocalMachineRegistryStringNonReflected ((wstring (uninstallRegName) + L"\\" + regName).c_str(), L"DisplayName", regName, ®NameSize, b32bitApp)) + regName[0] = 0; + } + + if (_wcsicmp (regName, appName) == 0) + { + installed = TRUE; + break; + } + + regNameSize = sizeof (regName); + } + + RegCloseKey (unistallKey); + return installed; +} + + +std::wstring FindLatestFileOrDirectory (const std::wstring &directory, const wchar_t *namePattern, bool findDirectory, bool findFile) +{ + wstring name; + ULARGE_INTEGER latestTime; + latestTime.QuadPart = 0; + WIN32_FIND_DATA findData; + + HANDLE find = FindFirstFile ((directory + L"\\" + namePattern).c_str(), &findData); + if (find != INVALID_HANDLE_VALUE) + { + do + { + if (wcscmp (findData.cFileName, L".") == 0 || wcscmp (findData.cFileName, L"..") == 0) + continue; + + ULARGE_INTEGER writeTime; + writeTime.LowPart = findData.ftLastWriteTime.dwLowDateTime; + writeTime.HighPart = findData.ftLastWriteTime.dwHighDateTime; + + if ((!findFile && !(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) + || (!findDirectory && (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))) + continue; + + if (latestTime.QuadPart < writeTime.QuadPart) + { + latestTime = writeTime; + name = findData.cFileName; + } + } + while (FindNextFile (find, &findData)); + + FindClose (find); + } + + if (name.empty()) + return name; + + return wstring (directory) + L"\\" + name; +} + +int GetPim (HWND hwndDlg, UINT ctrlId) +{ + int pim = 0; + HWND hCtrl = GetDlgItem (hwndDlg, ctrlId); + if (IsWindowEnabled (hCtrl) && IsWindowVisible (hCtrl)) + { + wchar_t szTmp[MAX_PIM + 1] = {0}; + if (GetDlgItemText (hwndDlg, ctrlId, szTmp, MAX_PIM + 1) > 0) + { + wchar_t* endPtr = NULL; + pim = wcstol(szTmp, &endPtr, 10); + if (pim < 0 || endPtr == szTmp || !endPtr || *endPtr != L'\0') + pim = 0; + } + } + return pim; +} + +void SetPim (HWND hwndDlg, UINT ctrlId, int pim) +{ + if (pim > 0) + { + wchar_t szTmp[MAX_PIM + 1]; + StringCbPrintfW (szTmp, sizeof(szTmp), L"%d", pim); + SetDlgItemText (hwndDlg, ctrlId, szTmp); + } + else + SetDlgItemText (hwndDlg, ctrlId, L""); +} + +BOOL GetPassword (HWND hwndDlg, UINT ctrlID, char* passValue, int bufSize, BOOL bShowError) +{ + wchar_t tmp [MAX_PASSWORD + 1]; + int utf8Len; + BOOL bRet = FALSE; + + GetWindowText (GetDlgItem (hwndDlg, ctrlID), tmp, ARRAYSIZE (tmp)); + utf8Len = WideCharToMultiByte (CP_UTF8, 0, tmp, -1, passValue, bufSize, NULL, NULL); + burn (tmp, sizeof (tmp)); + if (utf8Len > 0) + { + bRet = TRUE; + } + else + { + passValue [0] = 0; + if (bShowError) + { + SetFocus (GetDlgItem(hwndDlg, ctrlID)); + if (GetLastError () == ERROR_INSUFFICIENT_BUFFER) + Error ("PASSWORD_UTF8_TOO_LONG", hwndDlg); + else + Error ("PASSWORD_UTF8_INVALID", hwndDlg); + } + } + + return bRet; +} + +void SetPassword (HWND hwndDlg, UINT ctrlID, char* passValue) +{ + wchar_t tmp [MAX_PASSWORD + 1] = {0}; + MultiByteToWideChar (CP_UTF8, 0, passValue, -1, tmp, MAX_PASSWORD + 1); + SetWindowText ( GetDlgItem (hwndDlg, ctrlID), tmp); + burn (tmp, sizeof (tmp)); +} + +void HandleShowPasswordFieldAction (HWND hwndDlg, UINT checkBoxId, UINT edit1Id, UINT edit2Id) +{ + if ((EditPasswordChar == 0) && GetCheckBox (hwndDlg, checkBoxId)) + { + EditPasswordChar = (WCHAR) SendMessageW (GetDlgItem (hwndDlg, edit1Id), EM_GETPASSWORDCHAR, 0, 0); + } + + SendMessageW (GetDlgItem (hwndDlg, edit1Id), + EM_SETPASSWORDCHAR, + GetCheckBox (hwndDlg, checkBoxId) ? 0 : EditPasswordChar, + 0); + InvalidateRect (GetDlgItem (hwndDlg, edit1Id), NULL, TRUE); + + if (edit2Id) + { + SendMessageW (GetDlgItem (hwndDlg, edit2Id), + EM_SETPASSWORDCHAR, + GetCheckBox (hwndDlg, checkBoxId) ? 0 : EditPasswordChar, + 0); + InvalidateRect (GetDlgItem (hwndDlg, edit2Id), NULL, TRUE); + } +} + +void RegisterDriverInf (bool registerFilter, const string& filter, const string& filterReg, HWND ParentWindow, HKEY regKey) +{ + wstring infFileName = GetTempPathString() + L"\\veracrypt_driver_setup.inf"; + + File infFile (infFileName, false, true); + finally_do_arg (wstring, infFileName, { DeleteFile (finally_arg.c_str()); }); + + string infTxt = "[veracrypt]\r\n" + + string (registerFilter ? "Add" : "Del") + "Reg=veracrypt_reg\r\n\r\n" + "[veracrypt_reg]\r\n" + "HKR,,\"" + filterReg + "\",0x0001" + string (registerFilter ? "0008" : "8002") + ",\"" + filter + "\"\r\n"; + + infFile.Write ((byte *) infTxt.c_str(), (DWORD) infTxt.size()); + infFile.Close(); + + HINF hInf = SetupOpenInfFileWFn (infFileName.c_str(), NULL, INF_STYLE_OLDNT | INF_STYLE_WIN4, NULL); + throw_sys_if (hInf == INVALID_HANDLE_VALUE); + finally_do_arg (HINF, hInf, { SetupCloseInfFileFn (finally_arg); }); + + throw_sys_if (!SetupInstallFromInfSectionWFn (ParentWindow, hInf, L"veracrypt", SPINST_REGISTRY, regKey, NULL, 0, NULL, NULL, NULL, NULL)); +} + +HKEY OpenDeviceClassRegKey (const GUID *deviceClassGuid) +{ + return SetupDiOpenClassRegKeyFn (deviceClassGuid, KEY_READ | KEY_WRITE); +} + +LSTATUS DeleteRegistryKey (HKEY hKey, LPCTSTR keyName) +{ + return SHDeleteKeyWFn(hKey, keyName); +} + +HIMAGELIST CreateImageList(int cx, int cy, UINT flags, int cInitial, int cGrow) +{ + return ImageList_CreateFn(cx, cy, flags, cInitial, cGrow); +} + +int AddBitmapToImageList(HIMAGELIST himl, HBITMAP hbmImage, HBITMAP hbmMask) +{ + return ImageList_AddFn(himl, hbmImage, hbmMask); +} + +HRESULT VCStrDupW(LPCWSTR psz, LPWSTR *ppwsz) +{ + return SHStrDupWFn (psz, ppwsz); +} + + +void ProcessEntropyEstimate (HWND hProgress, DWORD* pdwInitialValue, DWORD dwCounter, DWORD dwMaxLevel, DWORD* pdwEntropy) +{ + /* conservative estimate: 1 mouse move event brings 1 bit of entropy + * https://security.stackexchange.com/questions/32844/for-how-much-time-should-i-randomly-move-the-mouse-for-generating-encryption-key/32848#32848 + */ + if (*pdwEntropy == 0xFFFFFFFF) + { + *pdwInitialValue = dwCounter; + *pdwEntropy = 0; + } + else + { + if ( *pdwEntropy < dwMaxLevel + && (dwCounter >= *pdwInitialValue) + && (dwCounter - *pdwInitialValue) <= dwMaxLevel) + *pdwEntropy = dwCounter - *pdwInitialValue; + else + *pdwEntropy = dwMaxLevel; + + if (IsOSAtLeast (WIN_VISTA)) + { + int state = PBST_ERROR; + if (*pdwEntropy >= (dwMaxLevel/2)) + state = PBST_NORMAL; + else if (*pdwEntropy >= (dwMaxLevel/4)) + state = PBST_PAUSED; + + SendMessage (hProgress, PBM_SETSTATE, state, 0); + } + + SendMessage (hProgress, PBM_SETPOS, + (WPARAM) (*pdwEntropy), + 0); + } +} + +void AllowMessageInUIPI (UINT msg) +{ + if (ChangeWindowMessageFilterFn) + { + ChangeWindowMessageFilterFn (msg, MSGFLT_ADD); + } +} + +BOOL IsRepeatedByteArray (byte value, const byte* buffer, size_t bufferSize) +{ + if (buffer && bufferSize) + { + size_t i; + for (i = 0; i < bufferSize; i++) + { + if (*buffer++ != value) + return FALSE; + } + return TRUE; + } + else + return FALSE; +} + +BOOL TranslateVolumeID (HWND hwndDlg, wchar_t* pathValue, size_t cchPathValue) +{ + BOOL bRet = TRUE; + size_t pathLen = pathValue? wcslen (pathValue) : 0; + if ((pathLen >= 3) && (_wcsnicmp (pathValue, L"ID:", 3) == 0)) + { + std::vector arr; + if ( (pathLen == (3 + 2*VOLUME_ID_SIZE)) + && HexWideStringToArray (pathValue + 3, arr) + && (arr.size() == VOLUME_ID_SIZE) + ) + { + std::wstring devicePath = FindDeviceByVolumeID (&arr[0]); + if (devicePath.length() > 0) + StringCchCopyW (pathValue, cchPathValue, devicePath.c_str()); + else + { + if (!Silent && !MultipleMountOperationInProgress) + Error ("VOLUME_ID_NOT_FOUND", hwndDlg); + SetLastError (ERROR_PATH_NOT_FOUND); + bRet = FALSE; + } + } + else + { + if (!Silent) + Error ("VOLUME_ID_INVALID", hwndDlg); + + SetLastError (ERROR_INVALID_PARAMETER); + bRet = FALSE; + } + } + + return bRet; +} + +BOOL CopyTextToClipboard (LPCWSTR txtValue) +{ + size_t txtLen = wcslen(txtValue); + HGLOBAL hdst; + LPWSTR dst; + BOOL bRet = FALSE; + + // Allocate string for cwd + hdst = GlobalAlloc(GMEM_MOVEABLE, (txtLen + 1) * sizeof(WCHAR)); + if (hdst) + { + dst = (LPWSTR)GlobalLock(hdst); + wmemcpy(dst, txtValue, txtLen + 1); + GlobalUnlock(hdst); + + if (OpenClipboard(NULL)) + { + EmptyClipboard(); + SetClipboardData(CF_UNICODETEXT, hdst); + CloseClipboard(); + } + } + + return bRet; +} diff --git a/src/Common/Dlgcode.h b/src/Common/Dlgcode.h index cf9239e0..dd6eb801 100644 --- a/src/Common/Dlgcode.h +++ b/src/Common/Dlgcode.h @@ -1,593 +1,593 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifndef TC_HEADER_DLGCODE -#define TC_HEADER_DLGCODE - -#include "Common.h" -#include "Apidrvr.h" -#include "Keyfiles.h" -#include "Wipe.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* IDs for dynamically generated GUI elements */ -enum dynamic_gui_element_ids -{ - IDPM_CHECK_FILESYS = 500001, - IDPM_REPAIR_FILESYS, - IDPM_OPEN_VOLUME, - IDPM_SELECT_FILE_AND_MOUNT, - IDPM_SELECT_DEVICE_AND_MOUNT, - IDPM_ADD_TO_FAVORITES, - IDPM_ADD_TO_SYSTEM_FAVORITES, - IDM_SHOW_HIDE, - IDM_HOMEPAGE_SYSTRAY, - IDPM_COPY_VALUE_TO_CLIPBOARD -}; - -enum -{ - TC_TBXID_LEGAL_NOTICES, - TC_TBXID_SYS_ENCRYPTION_PRETEST, - TC_TBXID_SYS_ENC_RESCUE_DISK, - TC_TBXID_DECOY_OS_INSTRUCTIONS, - TC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS -}; - -#define TC_APPLICATION_ID L"IDRIX.VeraCrypt" - -#define TC_MUTEX_NAME_SYSENC L"Global\\VeraCrypt System Encryption Wizard" -#define TC_MUTEX_NAME_NONSYS_INPLACE_ENC L"Global\\VeraCrypt In-Place Encryption Wizard" -#define TC_MUTEX_NAME_APP_SETUP L"Global\\VeraCrypt Setup" -#define TC_MUTEX_NAME_DRIVER_SETUP L"Global\\VeraCrypt Driver Setup" - -#define IDC_ABOUT 0x7fff /* ID for AboutBox on system menu in wm_user range */ - -#define EXCL_ACCESS_MAX_AUTO_RETRIES 500 -#define EXCL_ACCESS_AUTO_RETRY_DELAY 10 - -#define UNMOUNT_MAX_AUTO_RETRIES 30 -#define UNMOUNT_AUTO_RETRY_DELAY 50 - -// After the user receives the "Incorrect password" error this number of times in a row, we should automatically -// try using the embedded header backup (if any). This ensures that the "Incorrect password" message is reported faster -// initially (most such errors are really caused by supplying an incorrect password, not by header corruption). -#define TC_TRY_HEADER_BAK_AFTER_NBR_WRONG_PWD_TRIES 2 - -#define MAX_MULTI_CHOICES 10 /* Maximum number of options for mutliple-choice dialog */ - -#define TC_APPD_FILENAME_CONFIGURATION L"Configuration.xml" -#define TC_APPD_FILENAME_SYSTEM_ENCRYPTION L"System Encryption.xml" -#define TC_APPD_FILENAME_DEFAULT_KEYFILES L"Default Keyfiles.xml" -#define TC_APPD_FILENAME_HISTORY L"History.xml" -#define TC_APPD_FILENAME_FAVORITE_VOLUMES L"Favorite Volumes.xml" -#define TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES _T(TC_APP_NAME) L" System Favorite Volumes.xml" -#define TC_APPD_FILENAME_NONSYS_INPLACE_ENC L"In-Place Encryption" -#define TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE L"In-Place Encryption Wipe Algo" -#define TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL L"Post-Install Task - Tutorial" -#define TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES L"Post-Install Task - Release Notes" - -#define VC_FILENAME_RENAMED_SUFFIX L"_old" - -#ifndef USER_DEFAULT_SCREEN_DPI -#define USER_DEFAULT_SCREEN_DPI 96 -#endif - -#if (USER_DEFAULT_SCREEN_DPI != 96) -# error Revision of GUI and graphics necessary, since everything assumes default screen DPI as 96 (note that 96 is the default on Windows 2000, XP, and Vista). -#endif - -enum -{ - TC_POST_INSTALL_CFG_REMOVE_ALL = 0, - TC_POST_INSTALL_CFG_TUTORIAL, - TC_POST_INSTALL_CFG_RELEASE_NOTES -}; - -extern char *LastDialogId; -extern char *ConfigBuffer; -extern wchar_t szHelpFile[TC_MAX_PATH]; -extern wchar_t szHelpFile2[TC_MAX_PATH]; -extern wchar_t SecurityTokenLibraryPath[TC_MAX_PATH]; -extern HFONT hFixedDigitFont; -extern HFONT hBoldFont; -extern HFONT hTitleFont; -extern HFONT hFixedFont; -extern HFONT hUserFont; -extern HFONT hUserUnderlineFont; -extern HFONT hUserBoldFont; -extern HFONT WindowTitleBarFont; -extern int ScreenDPI; -extern double DlgAspectRatio; -extern HWND MainDlg; -extern BOOL Silent; -extern BOOL bHistory; -extern BOOL bPreserveTimestamp; -extern BOOL bShowDisconnectedNetworkDrives; -extern BOOL bHideWaitingDialog; -extern BOOL bCmdHideWaitingDialog; -extern BOOL bCmdHideWaitingDialogValid; -extern BOOL bStartOnLogon; -extern BOOL bMountDevicesOnLogon; -extern BOOL bMountFavoritesOnLogon; -extern int HiddenSectorDetectionStatus; -extern wchar_t *lpszTitle; -extern OSVersionEnum nCurrentOS; -extern int CurrentOSMajor; -extern int CurrentOSMinor; -extern int CurrentOSServicePack; -extern BOOL RemoteSession; -extern HANDLE hDriver; -extern HINSTANCE hInst; -extern int SystemEncryptionStatus; -extern WipeAlgorithmId nWipeMode; -extern BOOL bSysPartitionSelected; -extern BOOL bSysDriveSelected; - -extern wchar_t SysPartitionDevicePath [TC_MAX_PATH]; -extern wchar_t SysDriveDevicePath [TC_MAX_PATH]; -extern char bCachedSysDevicePathsValid; - -extern BOOL bHyperLinkBeingTracked; -extern BOOL bInPlaceEncNonSysPending; - -extern BOOL PimEnable; -extern BOOL KeyFilesEnable; -extern KeyFile *FirstKeyFile; -extern KeyFilesDlgParam defaultKeyFilesParam; -extern BOOL UacElevated; -extern BOOL IgnoreWmDeviceChange; -extern BOOL DeviceChangeBroadcastDisabled; -extern BOOL LastMountedVolumeDirty; -extern BOOL MountVolumesAsSystemFavorite; -extern BOOL FavoriteMountOnArrivalInProgress; -extern BOOL MultipleMountOperationInProgress; - - -enum tc_app_msg_ids -{ - /* WARNING: Changing these values or their meanings may cause incompatibility with other versions - (for example, if a new version of the TrueCrypt installer needed to shut down this version of - TrueCrypt during upgrade, it could fail or do something unwanted because the signal value would - be incorrect). When adding a new constant, verify that the value is unique within this block and - that it is less than WM_APP+16383. */ - - // Common (inter-app) - TC_APPMSG_CLOSE_BKG_TASK = WM_APP + 4, // Changing this value will prevent smooth upgrades from pre-5.x versions - TC_APPMSG_SYSENC_CONFIG_UPDATE = WM_APP + 101, - TC_APPMSG_TASKBAR_ICON = WM_APP + 102, - TC_APPMSG_LOAD_TEXT_BOX_CONTENT = WM_APP + 103, - // Mount - TC_APPMSG_MOUNT_ENABLE_DISABLE_CONTROLS = WM_APP + 201, - TC_APPMSG_MOUNT_SHOW_WINDOW = WM_APP + 202, - TC_APPMSG_PREBOOT_PASSWORD_MODE = WM_APP + 203, - // Format - TC_APPMSG_VOL_TRANSFORM_THREAD_ENDED = WM_APP + 301, - TC_APPMSG_FORMAT_FINISHED = WM_APP + 302, - TC_APPMSG_FORMAT_USER_QUIT = WM_APP + 303, - TC_APPMSG_PERFORM_POST_WMINIT_TASKS = WM_APP + 304, - TC_APPMSG_PERFORM_POST_SYSENC_WMINIT_TASKS = WM_APP + 305, - TC_APPMSG_NONSYS_INPLACE_ENC_FINISHED = WM_APP + 306, - // Setup - TC_APPMSG_INSTALL_SUCCESS = WM_APP + 401, - TC_APPMSG_UNINSTALL_SUCCESS = WM_APP + 402, - TC_APPMSG_EXTRACTION_SUCCESS = WM_APP + 403, - TC_APPMSG_INSTALL_FAILURE = WM_APP + 404, - TC_APPMSG_UNINSTALL_FAILURE = WM_APP + 405, - TC_APPMSG_EXTRACTION_FAILURE = WM_APP + 406 -}; - -enum system_encryption_status -{ - /* WARNING: As these values are written to config files, if they or their meanings - are changed, incompatiblity with other versions may arise (upgrade, downgrade, etc.). - When adding a new constant, verify that the value is unique within this block. */ - SYSENC_STATUS_NONE = 0, - SYSENC_STATUS_PRETEST = 200, // This may also mean that the OS is to be (or has been) copied to a hidden volume (to create a hidden OS). - SYSENC_STATUS_ENCRYPTING = 400, - SYSENC_STATUS_DECRYPTING = 600 -}; - -enum vol_creation_wizard_modes -{ - WIZARD_MODE_FILE_CONTAINER = 0, - WIZARD_MODE_NONSYS_DEVICE, - WIZARD_MODE_SYS_DEVICE -}; - - -typedef struct -{ - BOOL VolumeIsOpen; - - CRYPTO_INFO *CryptoInfo; - BOOL IsDevice; - HANDLE HostFileHandle; - uint64 HostSize; - - BOOL TimestampsValid; - FILETIME CreationTime; - FILETIME LastWriteTime; - FILETIME LastAccessTime; - -} OpenVolumeContext; - - -#define DEFAULT_VOL_CREATION_WIZARD_MODE WIZARD_MODE_FILE_CONTAINER - -#define ICON_HAND MB_ICONHAND -#define YES_NO MB_YESNO - -#define ISO_BURNER_TOOL L"isoburn.exe" -#define PRINT_TOOL L"notepad.exe" - -void cleanup ( void ); -void LowerCaseCopy ( wchar_t *lpszDest , const wchar_t *lpszSource ); -void UpperCaseCopy ( wchar_t *lpszDest , size_t cbDest, const wchar_t *lpszSource ); -void CreateFullVolumePath ( wchar_t *lpszDiskFile , size_t cbDiskFile, const wchar_t *lpszFileName , BOOL *bDevice ); -int FakeDosNameForDevice ( const wchar_t *lpszDiskFile , wchar_t *lpszDosDevice , size_t cbDosDevice, wchar_t *lpszCFDevice , size_t cbCFDevice, BOOL bNameOnly ); -int RemoveFakeDosName ( wchar_t *lpszDiskFile , wchar_t *lpszDosDevice ); -void AbortProcessDirect ( wchar_t *abortMsg ); -void AbortProcess ( char *stringId ); -void AbortProcessSilent ( void ); -void *err_malloc ( size_t size ); -char *err_strdup ( char *lpszText ); -DWORD handleWin32Error ( HWND hwndDlg, const char* srcPos ); -BOOL IsDiskReadError (DWORD error); -BOOL IsDiskWriteError (DWORD error); -BOOL IsDiskError (DWORD error); -BOOL translateWin32Error ( wchar_t *lpszMsgBuf , int nWSizeOfBuf ); -BOOL CALLBACK AboutDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); -static BOOL CALLBACK StaticModelessWaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -void DisplayStaticModelessWaitDlg (HWND parent); -void CloseStaticModelessWaitDlg (void); -BOOL IsButtonChecked ( HWND hButton ); -void CheckButton ( HWND hButton ); -void LeftPadString (wchar_t *szTmp, int len, int targetLen, wchar_t filler); -void InitDialog ( HWND hwndDlg ); -void ProcessPaintMessages (HWND hwnd, int maxMessagesToProcess); -HDC CreateMemBitmap ( HINSTANCE hInstance , HWND hwnd , wchar_t *resource ); -HBITMAP RenderBitmap ( wchar_t *resource , HWND hwndDest , int x , int y , int nWidth , int nHeight , BOOL bDirectRender , BOOL bKeepAspectRatio); -LRESULT CALLBACK RedTick ( HWND hwnd , UINT uMsg , WPARAM wParam , LPARAM lParam ); -BOOL RegisterRedTick ( HINSTANCE hInstance ); -BOOL UnregisterRedTick ( HINSTANCE hInstance ); -LRESULT CALLBACK SplashDlgProc ( HWND hwnd , UINT uMsg , WPARAM wParam , LPARAM lParam ); -void WaitCursor ( void ); -void NormalCursor ( void ); -void ArrowWaitCursor ( void ); -void HandCursor (); -void AddComboPair (HWND hComboBox, const wchar_t *lpszItem, int value); -void SelectAlgo ( HWND hComboBox , int *nCipher ); -void PopulateWipeModeCombo (HWND hComboBox, BOOL bNA, BOOL bInPlaceEncryption, BOOL bHeaderWipe); -wchar_t *GetWipeModeName (WipeAlgorithmId modeId); -wchar_t *GetPathType (const wchar_t *path, BOOL bUpperCase, BOOL *bIsPartition); -LRESULT CALLBACK CustomDlgProc ( HWND hwnd , UINT uMsg , WPARAM wParam , LPARAM lParam ); -BOOL TCCreateMutex (volatile HANDLE *hMutex, wchar_t *name); -void TCCloseMutex (volatile HANDLE *hMutex); -BOOL MutexExistsOnSystem (wchar_t *name); -BOOL CreateSysEncMutex (void); -BOOL InstanceHasSysEncMutex (void); -void CloseSysEncMutex (void); -BOOL CreateNonSysInplaceEncMutex (void); -BOOL InstanceHasNonSysInplaceEncMutex (void); -void CloseNonSysInplaceEncMutex (void); -BOOL NonSysInplaceEncInProgressElsewhere (void); -BOOL CreateDriverSetupMutex (void); -void CloseDriverSetupMutex (void); -BOOL CreateAppSetupMutex (void); -BOOL InstanceHasAppSetupMutex (void); -void CloseAppSetupMutex (void); -BOOL IsTrueCryptInstallerRunning (void); -uint32 ReadDriverConfigurationFlags (); -uint32 ReadEncryptionThreadPoolFreeCpuCountLimit (); -BOOL LoadSysEncSettings (); -int LoadNonSysInPlaceEncSettings (WipeAlgorithmId *wipeAlgorithm); -void RemoveNonSysInPlaceEncNotifications (void); -void SavePostInstallTasksSettings (int command); -void DoPostInstallTasks (HWND hwndDlg); -void InitOSVersionInfo (); -void InitApp ( HINSTANCE hInstance, wchar_t *lpszCommandLine ); -void FinalizeApp (void); -void InitHelpFileName (void); -BOOL OpenDevice (const wchar_t *lpszPath, OPEN_TEST_STRUCT *driver, BOOL detectFilesystem, BOOL matchVolumeID, const BYTE* pbVolumeID); -void NotifyDriverOfPortableMode (void); -int GetAvailableFixedDisks ( HWND hComboBox , char *lpszRootPath ); -int GetAvailableRemovables ( HWND hComboBox , char *lpszRootPath ); -int IsSystemDevicePath (const wchar_t *path, HWND hwndDlg, BOOL bReliableRequired); -int IsNonSysPartitionOnSysDrive (const wchar_t *path); -BOOL CALLBACK RawDevicesDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); -INT_PTR TextInfoDialogBox (int nID); -BOOL CALLBACK TextInfoDialogBoxDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -char * GetLegalNotices (); -BOOL CALLBACK BenchmarkDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -void UserEnrichRandomPool (HWND hwndDlg); -BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); -int DriverAttach ( void ); -BOOL CALLBACK CipherTestDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); -void ResetCipherTest ( HWND hwndDlg , int idTestCipher ); -void ResetCurrentDirectory (); -BOOL BrowseFiles (HWND hwndDlg, char *stringId, wchar_t *lpszFileName, BOOL keepHistory, BOOL saveMode, wchar_t *browseFilter); -BOOL BrowseDirectories (HWND hWnd, char *lpszTitle, wchar_t *dirName); -void handleError ( HWND hwndDlg , int code, const char* srcPos ); -BOOL CheckFileStreamWriteErrors (HWND hwndDlg, FILE *file, const wchar_t *fileName); -void LocalizeDialog ( HWND hwnd, char *stringId ); -void OpenVolumeExplorerWindow (int driveNo); -static BOOL CALLBACK CloseVolumeExplorerWindowsEnum( HWND hwnd, LPARAM driveNo); -BOOL CloseVolumeExplorerWindows (HWND hwnd, int driveNo); -BOOL UpdateDriveCustomLabel (int driveNo, wchar_t* effectiveLabel, BOOL bSetValue); -BOOL CheckCapsLock (HWND hwnd, BOOL quiet); -BOOL CheckFileExtension (wchar_t *fileName); -void CorrectFileName (wchar_t* fileName); -void IncreaseWrongPwdRetryCount (int count); -void ResetWrongPwdRetryCount (void); -BOOL WrongPwdRetryCountOverLimit (void); -DWORD GetUsedLogicalDrives (void); -int GetFirstAvailableDrive (); -int GetLastAvailableDrive (); -BOOL IsDriveAvailable (int driveNo); -BOOL IsDeviceMounted (wchar_t *deviceName); -int DriverUnmountVolume (HWND hwndDlg, int nDosDriveNo, BOOL forced); -void BroadcastDeviceChange (WPARAM message, int nDosDriveNo, DWORD driveMap); -int MountVolume (HWND hwndDlg, int driveNo, wchar_t *volumePath, Password *password, int pkcs5, int pim, BOOL truecryptMode, BOOL cachePassword, BOOL cachePim, BOOL sharedAccess, const MountOptions* const mountOptions, BOOL quiet, BOOL bReportWrongPassword); -BOOL UnmountVolume (HWND hwndDlg , int nDosDriveNo, BOOL forceUnmount); -BOOL UnmountVolumeAfterFormatExCall (HWND hwndDlg, int nDosDriveNo); -BOOL IsPasswordCacheEmpty (void); -BOOL IsMountedVolumeID (BYTE volumeID[VOLUME_ID_SIZE]); -BOOL IsMountedVolume (const wchar_t *volname); -int GetMountedVolumeDriveNo (wchar_t *volname); -BOOL IsAdmin (void); -BOOL IsBuiltInAdmin (); -BOOL IsUacSupported (); -BOOL ResolveSymbolicLink (const wchar_t *symLinkName, PWSTR targetName, size_t cbTargetName); -int GetDiskDeviceDriveLetter (PWSTR deviceName); -int FileSystemAppearsEmpty (const wchar_t *devicePath); -__int64 GetStatsFreeSpaceOnPartition (const wchar_t *devicePath, float *percent, __int64 *occupiedBytes, BOOL silent); -__int64 GetDeviceSize (const wchar_t *devicePath); -HANDLE DismountDrive (wchar_t *devName, wchar_t *devicePath); -int64 FindString (const char *buf, const char *str, int64 bufLen, int64 strLen, int64 startOffset); -BOOL FileExists (const wchar_t *filePathPtr); -__int64 FindStringInFile (const wchar_t *filePath, const char *str, int strLen); -BOOL TCCopyFile (wchar_t *sourceFileName, wchar_t *destinationFile); -BOOL SaveBufferToFile (const char *inputBuffer, const wchar_t *destinationFile, DWORD inputLength, BOOL bAppend, BOOL bRenameIfFailed); -BOOL TCFlushFile (FILE *f); -BOOL PrintHardCopyTextUTF16 (wchar_t *text, wchar_t *title, size_t byteLen); -void GetSpeedString (unsigned __int64 speed, wchar_t *str, size_t cbStr); -BOOL IsNonInstallMode (); -BOOL DriverUnload (); -LRESULT SetCheckBox (HWND hwndDlg, int dlgItem, BOOL state); -BOOL GetCheckBox (HWND hwndDlg, int dlgItem); -void SetListScrollHPos (HWND hList, int topMostVisibleItem); -void ManageStartupSeq (void); -void ManageStartupSeqWiz (BOOL bRemove, const wchar_t *arg); -void CleanLastVisitedMRU (void); -void ClearHistory (HWND hwndDlgItem); -LRESULT ListItemAdd (HWND list, int index, const wchar_t *string); -LRESULT ListSubItemSet (HWND list, int index, int subIndex, const wchar_t *string); -BOOL GetMountList (MOUNT_LIST_STRUCT *list); -int GetDriverRefCount (); -void GetSizeString (unsigned __int64 size, wchar_t *str, size_t cbStr); -__int64 GetFileSize64 (const wchar_t *path); -BOOL LoadInt16 (const wchar_t *filePath, int *result, __int64 fileOffset); -BOOL LoadInt32 (const wchar_t *filePath, unsigned __int32 *result, __int64 fileOffset); -char *LoadFile (const wchar_t *fileName, DWORD *size); -char *LoadFileBlock (const wchar_t *fileName, __int64 fileOffset, DWORD count); -wchar_t *GetModPath (wchar_t *path, int maxSize); -wchar_t *GetConfigPath (wchar_t *fileName); -wchar_t *GetProgramConfigPath (wchar_t *fileName); -wchar_t GetSystemDriveLetter (void); -void OpenPageHelp (HWND hwndDlg, int nPage); -void TaskBarIconDisplayBalloonTooltip (HWND hwnd, wchar_t *headline, wchar_t *text, BOOL warning); -void InfoBalloon (char *headingStringId, char *textStringId, HWND hwnd); -void InfoBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd); -void WarningBalloon (char *headingStringId, char *textStringId, HWND hwnd); -void WarningBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd); -int Info (char *stringId, HWND hwnd); -int InfoTopMost (char *stringId, HWND hwnd); -int InfoDirect (const wchar_t *msg, HWND hwnd); -int Warning (char *stringId, HWND hwnd); -int WarningTopMost (char *stringId, HWND hwnd); -int WarningDirect (const wchar_t *warnMsg, HWND hwnd); -int Error (char *stringId, HWND hwnd); -int ErrorRetryCancel (char *stringId, HWND hwnd); -int ErrorDirect (const wchar_t *errMsg, HWND hwnd); -int ErrorTopMost (char *stringId, HWND hwnd); -int AskYesNo (char *stringId, HWND hwnd); -int AskYesNoString (const wchar_t *str, HWND hwnd); -int AskYesNoTopmost (char *stringId, HWND hwnd); -int AskNoYes (char *stringId, HWND hwnd); -int AskNoYesString (const wchar_t *string, HWND hwnd); -int AskOkCancel (char *stringId, HWND hwnd); -int AskWarnYesNo (char *stringId, HWND hwnd); -int AskWarnYesNoString (const wchar_t *string, HWND hwnd); -int AskWarnYesNoTopmost (char *stringId, HWND hwnd); -int AskWarnYesNoStringTopmost (const wchar_t *string, HWND hwnd); -int AskWarnNoYes (char *stringId, HWND hwnd); -int AskWarnNoYesString (const wchar_t *string, HWND hwnd); -int AskWarnNoYesTopmost (char *stringId, HWND hwnd); -int AskWarnOkCancel (char *stringId, HWND hwnd); -int AskWarnCancelOk (char *stringId, HWND hwnd); -int AskErrYesNo (char *stringId, HWND hwnd); -int AskErrNoYes (char *stringId, HWND hwnd); -int AskMultiChoice (void *strings[], BOOL bBold, HWND hwnd); -BOOL ConfigWriteBegin (); -BOOL ConfigWriteEnd (HWND hwnd); -BOOL ConfigWriteString (char *configKey, char *configValue); -BOOL ConfigWriteStringW (char *configKey, wchar_t *configValue); -BOOL ConfigWriteInt (char *configKey, int configValue); -int ConfigReadInt (char *configKey, int defaultValue); -char *ConfigReadString (char *configKey, char *defaultValue, char *str, int maxLen); -void ConfigReadCompareInt(char *configKey, int defaultValue, int* pOutputValue, BOOL bOnlyCheckModified, BOOL* pbModified); -void ConfigReadCompareString (char *configKey, char *defaultValue, char *str, int maxLen, BOOL bOnlyCheckModified, BOOL *pbModified); -void RestoreDefaultKeyFilesParam (void); -BOOL LoadDefaultKeyFilesParam (void); -void Debug (char *format, ...); -void DebugMsgBox (char *format, ...); -BOOL IsOSAtLeast (OSVersionEnum reqMinOS); -BOOL IsOSVersionAtLeast (OSVersionEnum reqMinOS, int reqMinServicePack); -BOOL Is64BitOs (); -BOOL IsServerOS (); -BOOL IsHiddenOSRunning (void); -BOOL EnableWow64FsRedirection (BOOL enable); -BOOL RestartComputer (void); -void Applink (char *dest, BOOL bSendOS, char *extraOutput); -wchar_t *RelativePath2Absolute (wchar_t *szFileName); -void HandleDriveNotReadyError (HWND hwnd); -BOOL CALLBACK CloseTCWindowsEnum( HWND hwnd, LPARAM lParam); -BOOL CALLBACK FindTCWindowEnum (HWND hwnd, LPARAM lParam); -BYTE *MapResource (wchar_t *resourceType, int resourceId, PDWORD size); -void InconsistencyResolved (char *msg); -void ReportUnexpectedState (char *techInfo); -BOOL SelectMultipleFiles (HWND hwndDlg, const char *stringId, wchar_t *lpszFileName, size_t cbFileName, BOOL keepHistory); -BOOL SelectMultipleFilesNext (wchar_t *lpszFileName, size_t cbFileName); -void OpenOnlineHelp (); -BOOL GetPartitionInfo (const wchar_t *deviceName, PPARTITION_INFORMATION rpartInfo); -BOOL GetDeviceInfo (const wchar_t *deviceName, DISK_PARTITION_INFO_STRUCT *info); -BOOL GetDriveGeometry (const wchar_t *deviceName, PDISK_GEOMETRY diskGeometry); -BOOL GetPhysicalDriveGeometry (int driveNumber, PDISK_GEOMETRY diskGeometry); -BOOL IsVolumeDeviceHosted (const wchar_t *lpszDiskFile); -int CompensateXDPI (int val); -int CompensateYDPI (int val); -int CompensateDPIFont (int val); -int GetTextGfxWidth (HWND hwndDlgItem, const wchar_t *text, HFONT hFont); -int GetTextGfxHeight (HWND hwndDlgItem, const wchar_t *text, HFONT hFont); -BOOL ToHyperlink (HWND hwndDlg, UINT ctrlId); -BOOL ToCustHyperlink (HWND hwndDlg, UINT ctrlId, HFONT hFont); -void DisableCloseButton (HWND hwndDlg); -void EnableCloseButton (HWND hwndDlg); -void ToBootPwdField (HWND hwndDlg, UINT ctrlId); -void AccommodateTextField (HWND hwndDlg, UINT ctrlId, BOOL bFirstUpdate, HFONT hFont); -BOOL GetDriveLabel (int driveNo, wchar_t *label, int labelSize); -BOOL GetSysDevicePaths (HWND hwndDlg); -BOOL DoDriverInstall (HWND hwndDlg); -int OpenVolume (OpenVolumeContext *context, const wchar_t *volumePath, Password *password, int pkcs5_prf, int pim, BOOL truecryptMode, BOOL write, BOOL preserveTimestamps, BOOL useBackupHeader); -void CloseVolume (OpenVolumeContext *context); -int ReEncryptVolumeHeader (HWND hwndDlg, char *buffer, BOOL bBoot, CRYPTO_INFO *cryptoInfo, Password *password, int pim, BOOL wipeMode); -BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly); -BOOL IsPagingFileWildcardActive (); -BOOL DisablePagingFile (); -BOOL CALLBACK SecurityTokenPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -BOOL CALLBACK SecurityTokenKeyfileDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -BOOL InitSecurityTokenLibrary (HWND hwndDlg); -BOOL FileHasReadOnlyAttribute (const wchar_t *path); -BOOL IsFileOnReadOnlyFilesystem (const wchar_t *path); -void CheckFilesystem (HWND hwndDlg, int driveNo, BOOL fixErrors); -BOOL BufferContainsString (const byte *buffer, size_t bufferSize, const char *str); -int AskNonSysInPlaceEncryptionResume (HWND hwndDlg, BOOL* pbDecrypt); -BOOL RemoveDeviceWriteProtection (HWND hwndDlg, wchar_t *devicePath); -void EnableElevatedCursorChange (HWND parent); -BOOL DisableFileCompression (HANDLE file); -BOOL VolumePathExists (const wchar_t *volumePath); -BOOL IsWindowsIsoBurnerAvailable (); -BOOL LaunchWindowsIsoBurner (HWND hwnd, const wchar_t *isoPath); -BOOL IsApplicationInstalled (const wchar_t *appName); -int GetPim (HWND hwndDlg, UINT ctrlId); -void SetPim (HWND hwndDlg, UINT ctrlId, int pim); -BOOL GetPassword (HWND hwndDlg, UINT ctrlID, char* passValue, int bufSize, BOOL bShowError); -void SetPassword (HWND hwndDlg, UINT ctrlID, char* passValue); -void HandleShowPasswordFieldAction (HWND hwndDlg, UINT checkBoxId, UINT edit1Id, UINT edit2Id); -HKEY OpenDeviceClassRegKey (const GUID *deviceClassGuid); -LSTATUS DeleteRegistryKey (HKEY, LPCTSTR); -HIMAGELIST CreateImageList(int cx, int cy, UINT flags, int cInitial, int cGrow); -int AddBitmapToImageList(HIMAGELIST himl, HBITMAP hbmImage, HBITMAP hbmMask); -HRESULT VCStrDupW(LPCWSTR psz, LPWSTR *ppwsz); -void ProcessEntropyEstimate (HWND hProgress, DWORD* pdwInitialValue, DWORD dwCounter, DWORD dwMaxLevel, DWORD* pdwEntropy); -void AllowMessageInUIPI (UINT msg); -BOOL IsRepeatedByteArray (byte value, const byte* buffer, size_t bufferSize); -BOOL TranslateVolumeID (HWND hwndDlg, wchar_t* pathValue, size_t cchPathValue); -BOOL CopyTextToClipboard (const wchar_t* txtValue); - -#ifdef __cplusplus -} - -#include -#include - -struct HostDevice -{ - HostDevice () - : - Bootable (false), - ContainsSystem (false), - DynamicVolume (false), - Floppy (false), - IsPartition (false), - IsVirtualPartition (false), - HasUnencryptedFilesystem (false), - Removable (false), - Size (0), - SystemNumber((uint32) -1) - { - } - - ~HostDevice () { } - - bool Bootable; - bool ContainsSystem; - bool DynamicVolume; - bool Floppy; - bool IsPartition; - bool IsVirtualPartition; - bool HasUnencryptedFilesystem; - std::wstring MountPoint; - std::wstring Name; - std::wstring Path; - bool Removable; - uint64 Size; - uint32 SystemNumber; - - std::vector Partitions; -}; - -struct RawDevicesDlgParam -{ - std::vector devices; - wchar_t *pszFileName; -}; - -BOOL BrowseFilesInDir (HWND hwndDlg, char *stringId, wchar_t *initialDir, wchar_t *lpszFileName, BOOL keepHistory, BOOL saveMode, wchar_t *browseFilter, const wchar_t *initialFileName = NULL, const wchar_t *defaultExtension = NULL); -std::wstring SingleStringToWide (const std::string &singleString); -std::wstring Utf8StringToWide (const std::string &utf8String); -std::string WideToUtf8String (const std::wstring &wideString); -std::vector GetAvailableHostDevices (bool noDeviceProperties = false, bool singleList = false, bool noFloppy = true, bool detectUnencryptedFilesystems = false); -std::wstring ToUpperCase (const std::wstring &str); -std::wstring GetWrongPasswordErrorMessage (HWND hwndDlg); -std::wstring GetWindowsEdition (); -std::wstring FitPathInGfxWidth (HWND hwnd, HFONT hFont, LONG width, const std::wstring &path); -std::wstring GetServiceConfigPath (const wchar_t *fileName, bool useLegacy); -std::wstring VolumeGuidPathToDevicePath (std::wstring volumeGuidPath); -std::wstring HarddiskVolumePathToPartitionPath (const std::wstring &harddiskVolumePath); -std::wstring FindLatestFileOrDirectory (const std::wstring &directory, const wchar_t *namePattern, bool findDirectory, bool findFile); -std::wstring GetUserFriendlyVersionString (int version); -std::wstring IntToWideString (int val); -std::wstring ArrayToHexWideString (const unsigned char* pbData, int cbData); -bool HexWideStringToArray (const wchar_t* hexStr, std::vector& arr); -std::wstring FindDeviceByVolumeID (const BYTE volumeID [VOLUME_ID_SIZE]); -void RegisterDriverInf (bool registerFilter, const std::string& filter, const std::string& filterReg, HWND ParentWindow, HKEY regKey); -std::wstring GetTempPathString (); -inline std::wstring AppendSrcPos (const wchar_t* msg, const char* srcPos) -{ - return std::wstring (msg? msg : L"") + L"\n\nSource: " + SingleStringToWide (srcPos); -} - -// Display a wait dialog while calling the provided callback with the given parameter -typedef void (CALLBACK* WaitThreadProc)(void* pArg, HWND hWaitDlg); -void BringToForeground(HWND hWnd); -void ShowWaitDialog(HWND hwnd, BOOL bUseHwndAsParent, WaitThreadProc callback, void* pArg); - -#endif // __cplusplus - -#endif // TC_HEADER_DLGCODE +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifndef TC_HEADER_DLGCODE +#define TC_HEADER_DLGCODE + +#include "Common.h" +#include "Apidrvr.h" +#include "Keyfiles.h" +#include "Wipe.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* IDs for dynamically generated GUI elements */ +enum dynamic_gui_element_ids +{ + IDPM_CHECK_FILESYS = 500001, + IDPM_REPAIR_FILESYS, + IDPM_OPEN_VOLUME, + IDPM_SELECT_FILE_AND_MOUNT, + IDPM_SELECT_DEVICE_AND_MOUNT, + IDPM_ADD_TO_FAVORITES, + IDPM_ADD_TO_SYSTEM_FAVORITES, + IDM_SHOW_HIDE, + IDM_HOMEPAGE_SYSTRAY, + IDPM_COPY_VALUE_TO_CLIPBOARD +}; + +enum +{ + TC_TBXID_LEGAL_NOTICES, + TC_TBXID_SYS_ENCRYPTION_PRETEST, + TC_TBXID_SYS_ENC_RESCUE_DISK, + TC_TBXID_DECOY_OS_INSTRUCTIONS, + TC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS +}; + +#define TC_APPLICATION_ID L"IDRIX.VeraCrypt" + +#define TC_MUTEX_NAME_SYSENC L"Global\\VeraCrypt System Encryption Wizard" +#define TC_MUTEX_NAME_NONSYS_INPLACE_ENC L"Global\\VeraCrypt In-Place Encryption Wizard" +#define TC_MUTEX_NAME_APP_SETUP L"Global\\VeraCrypt Setup" +#define TC_MUTEX_NAME_DRIVER_SETUP L"Global\\VeraCrypt Driver Setup" + +#define IDC_ABOUT 0x7fff /* ID for AboutBox on system menu in wm_user range */ + +#define EXCL_ACCESS_MAX_AUTO_RETRIES 500 +#define EXCL_ACCESS_AUTO_RETRY_DELAY 10 + +#define UNMOUNT_MAX_AUTO_RETRIES 30 +#define UNMOUNT_AUTO_RETRY_DELAY 50 + +// After the user receives the "Incorrect password" error this number of times in a row, we should automatically +// try using the embedded header backup (if any). This ensures that the "Incorrect password" message is reported faster +// initially (most such errors are really caused by supplying an incorrect password, not by header corruption). +#define TC_TRY_HEADER_BAK_AFTER_NBR_WRONG_PWD_TRIES 2 + +#define MAX_MULTI_CHOICES 10 /* Maximum number of options for mutliple-choice dialog */ + +#define TC_APPD_FILENAME_CONFIGURATION L"Configuration.xml" +#define TC_APPD_FILENAME_SYSTEM_ENCRYPTION L"System Encryption.xml" +#define TC_APPD_FILENAME_DEFAULT_KEYFILES L"Default Keyfiles.xml" +#define TC_APPD_FILENAME_HISTORY L"History.xml" +#define TC_APPD_FILENAME_FAVORITE_VOLUMES L"Favorite Volumes.xml" +#define TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES _T(TC_APP_NAME) L" System Favorite Volumes.xml" +#define TC_APPD_FILENAME_NONSYS_INPLACE_ENC L"In-Place Encryption" +#define TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE L"In-Place Encryption Wipe Algo" +#define TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL L"Post-Install Task - Tutorial" +#define TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES L"Post-Install Task - Release Notes" + +#define VC_FILENAME_RENAMED_SUFFIX L"_old" + +#ifndef USER_DEFAULT_SCREEN_DPI +#define USER_DEFAULT_SCREEN_DPI 96 +#endif + +#if (USER_DEFAULT_SCREEN_DPI != 96) +# error Revision of GUI and graphics necessary, since everything assumes default screen DPI as 96 (note that 96 is the default on Windows 2000, XP, and Vista). +#endif + +enum +{ + TC_POST_INSTALL_CFG_REMOVE_ALL = 0, + TC_POST_INSTALL_CFG_TUTORIAL, + TC_POST_INSTALL_CFG_RELEASE_NOTES +}; + +extern char *LastDialogId; +extern char *ConfigBuffer; +extern wchar_t szHelpFile[TC_MAX_PATH]; +extern wchar_t szHelpFile2[TC_MAX_PATH]; +extern wchar_t SecurityTokenLibraryPath[TC_MAX_PATH]; +extern HFONT hFixedDigitFont; +extern HFONT hBoldFont; +extern HFONT hTitleFont; +extern HFONT hFixedFont; +extern HFONT hUserFont; +extern HFONT hUserUnderlineFont; +extern HFONT hUserBoldFont; +extern HFONT WindowTitleBarFont; +extern int ScreenDPI; +extern double DlgAspectRatio; +extern HWND MainDlg; +extern BOOL Silent; +extern BOOL bHistory; +extern BOOL bPreserveTimestamp; +extern BOOL bShowDisconnectedNetworkDrives; +extern BOOL bHideWaitingDialog; +extern BOOL bCmdHideWaitingDialog; +extern BOOL bCmdHideWaitingDialogValid; +extern BOOL bStartOnLogon; +extern BOOL bMountDevicesOnLogon; +extern BOOL bMountFavoritesOnLogon; +extern int HiddenSectorDetectionStatus; +extern wchar_t *lpszTitle; +extern OSVersionEnum nCurrentOS; +extern int CurrentOSMajor; +extern int CurrentOSMinor; +extern int CurrentOSServicePack; +extern BOOL RemoteSession; +extern HANDLE hDriver; +extern HINSTANCE hInst; +extern int SystemEncryptionStatus; +extern WipeAlgorithmId nWipeMode; +extern BOOL bSysPartitionSelected; +extern BOOL bSysDriveSelected; + +extern wchar_t SysPartitionDevicePath [TC_MAX_PATH]; +extern wchar_t SysDriveDevicePath [TC_MAX_PATH]; +extern char bCachedSysDevicePathsValid; + +extern BOOL bHyperLinkBeingTracked; +extern BOOL bInPlaceEncNonSysPending; + +extern BOOL PimEnable; +extern BOOL KeyFilesEnable; +extern KeyFile *FirstKeyFile; +extern KeyFilesDlgParam defaultKeyFilesParam; +extern BOOL UacElevated; +extern BOOL IgnoreWmDeviceChange; +extern BOOL DeviceChangeBroadcastDisabled; +extern BOOL LastMountedVolumeDirty; +extern BOOL MountVolumesAsSystemFavorite; +extern BOOL FavoriteMountOnArrivalInProgress; +extern BOOL MultipleMountOperationInProgress; + + +enum tc_app_msg_ids +{ + /* WARNING: Changing these values or their meanings may cause incompatibility with other versions + (for example, if a new version of the TrueCrypt installer needed to shut down this version of + TrueCrypt during upgrade, it could fail or do something unwanted because the signal value would + be incorrect). When adding a new constant, verify that the value is unique within this block and + that it is less than WM_APP+16383. */ + + // Common (inter-app) + TC_APPMSG_CLOSE_BKG_TASK = WM_APP + 4, // Changing this value will prevent smooth upgrades from pre-5.x versions + TC_APPMSG_SYSENC_CONFIG_UPDATE = WM_APP + 101, + TC_APPMSG_TASKBAR_ICON = WM_APP + 102, + TC_APPMSG_LOAD_TEXT_BOX_CONTENT = WM_APP + 103, + // Mount + TC_APPMSG_MOUNT_ENABLE_DISABLE_CONTROLS = WM_APP + 201, + TC_APPMSG_MOUNT_SHOW_WINDOW = WM_APP + 202, + TC_APPMSG_PREBOOT_PASSWORD_MODE = WM_APP + 203, + // Format + TC_APPMSG_VOL_TRANSFORM_THREAD_ENDED = WM_APP + 301, + TC_APPMSG_FORMAT_FINISHED = WM_APP + 302, + TC_APPMSG_FORMAT_USER_QUIT = WM_APP + 303, + TC_APPMSG_PERFORM_POST_WMINIT_TASKS = WM_APP + 304, + TC_APPMSG_PERFORM_POST_SYSENC_WMINIT_TASKS = WM_APP + 305, + TC_APPMSG_NONSYS_INPLACE_ENC_FINISHED = WM_APP + 306, + // Setup + TC_APPMSG_INSTALL_SUCCESS = WM_APP + 401, + TC_APPMSG_UNINSTALL_SUCCESS = WM_APP + 402, + TC_APPMSG_EXTRACTION_SUCCESS = WM_APP + 403, + TC_APPMSG_INSTALL_FAILURE = WM_APP + 404, + TC_APPMSG_UNINSTALL_FAILURE = WM_APP + 405, + TC_APPMSG_EXTRACTION_FAILURE = WM_APP + 406 +}; + +enum system_encryption_status +{ + /* WARNING: As these values are written to config files, if they or their meanings + are changed, incompatiblity with other versions may arise (upgrade, downgrade, etc.). + When adding a new constant, verify that the value is unique within this block. */ + SYSENC_STATUS_NONE = 0, + SYSENC_STATUS_PRETEST = 200, // This may also mean that the OS is to be (or has been) copied to a hidden volume (to create a hidden OS). + SYSENC_STATUS_ENCRYPTING = 400, + SYSENC_STATUS_DECRYPTING = 600 +}; + +enum vol_creation_wizard_modes +{ + WIZARD_MODE_FILE_CONTAINER = 0, + WIZARD_MODE_NONSYS_DEVICE, + WIZARD_MODE_SYS_DEVICE +}; + + +typedef struct +{ + BOOL VolumeIsOpen; + + CRYPTO_INFO *CryptoInfo; + BOOL IsDevice; + HANDLE HostFileHandle; + uint64 HostSize; + + BOOL TimestampsValid; + FILETIME CreationTime; + FILETIME LastWriteTime; + FILETIME LastAccessTime; + +} OpenVolumeContext; + + +#define DEFAULT_VOL_CREATION_WIZARD_MODE WIZARD_MODE_FILE_CONTAINER + +#define ICON_HAND MB_ICONHAND +#define YES_NO MB_YESNO + +#define ISO_BURNER_TOOL L"isoburn.exe" +#define PRINT_TOOL L"notepad.exe" + +void cleanup ( void ); +void LowerCaseCopy ( wchar_t *lpszDest , const wchar_t *lpszSource ); +void UpperCaseCopy ( wchar_t *lpszDest , size_t cbDest, const wchar_t *lpszSource ); +void CreateFullVolumePath ( wchar_t *lpszDiskFile , size_t cbDiskFile, const wchar_t *lpszFileName , BOOL *bDevice ); +int FakeDosNameForDevice ( const wchar_t *lpszDiskFile , wchar_t *lpszDosDevice , size_t cbDosDevice, wchar_t *lpszCFDevice , size_t cbCFDevice, BOOL bNameOnly ); +int RemoveFakeDosName ( wchar_t *lpszDiskFile , wchar_t *lpszDosDevice ); +void AbortProcessDirect ( wchar_t *abortMsg ); +void AbortProcess ( char *stringId ); +void AbortProcessSilent ( void ); +void *err_malloc ( size_t size ); +char *err_strdup ( char *lpszText ); +DWORD handleWin32Error ( HWND hwndDlg, const char* srcPos ); +BOOL IsDiskReadError (DWORD error); +BOOL IsDiskWriteError (DWORD error); +BOOL IsDiskError (DWORD error); +BOOL translateWin32Error ( wchar_t *lpszMsgBuf , int nWSizeOfBuf ); +BOOL CALLBACK AboutDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); +static BOOL CALLBACK StaticModelessWaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +void DisplayStaticModelessWaitDlg (HWND parent); +void CloseStaticModelessWaitDlg (void); +BOOL IsButtonChecked ( HWND hButton ); +void CheckButton ( HWND hButton ); +void LeftPadString (wchar_t *szTmp, int len, int targetLen, wchar_t filler); +void InitDialog ( HWND hwndDlg ); +void ProcessPaintMessages (HWND hwnd, int maxMessagesToProcess); +HDC CreateMemBitmap ( HINSTANCE hInstance , HWND hwnd , wchar_t *resource ); +HBITMAP RenderBitmap ( wchar_t *resource , HWND hwndDest , int x , int y , int nWidth , int nHeight , BOOL bDirectRender , BOOL bKeepAspectRatio); +LRESULT CALLBACK RedTick ( HWND hwnd , UINT uMsg , WPARAM wParam , LPARAM lParam ); +BOOL RegisterRedTick ( HINSTANCE hInstance ); +BOOL UnregisterRedTick ( HINSTANCE hInstance ); +LRESULT CALLBACK SplashDlgProc ( HWND hwnd , UINT uMsg , WPARAM wParam , LPARAM lParam ); +void WaitCursor ( void ); +void NormalCursor ( void ); +void ArrowWaitCursor ( void ); +void HandCursor (); +void AddComboPair (HWND hComboBox, const wchar_t *lpszItem, int value); +void SelectAlgo ( HWND hComboBox , int *nCipher ); +void PopulateWipeModeCombo (HWND hComboBox, BOOL bNA, BOOL bInPlaceEncryption, BOOL bHeaderWipe); +wchar_t *GetWipeModeName (WipeAlgorithmId modeId); +wchar_t *GetPathType (const wchar_t *path, BOOL bUpperCase, BOOL *bIsPartition); +LRESULT CALLBACK CustomDlgProc ( HWND hwnd , UINT uMsg , WPARAM wParam , LPARAM lParam ); +BOOL TCCreateMutex (volatile HANDLE *hMutex, wchar_t *name); +void TCCloseMutex (volatile HANDLE *hMutex); +BOOL MutexExistsOnSystem (wchar_t *name); +BOOL CreateSysEncMutex (void); +BOOL InstanceHasSysEncMutex (void); +void CloseSysEncMutex (void); +BOOL CreateNonSysInplaceEncMutex (void); +BOOL InstanceHasNonSysInplaceEncMutex (void); +void CloseNonSysInplaceEncMutex (void); +BOOL NonSysInplaceEncInProgressElsewhere (void); +BOOL CreateDriverSetupMutex (void); +void CloseDriverSetupMutex (void); +BOOL CreateAppSetupMutex (void); +BOOL InstanceHasAppSetupMutex (void); +void CloseAppSetupMutex (void); +BOOL IsTrueCryptInstallerRunning (void); +uint32 ReadDriverConfigurationFlags (); +uint32 ReadEncryptionThreadPoolFreeCpuCountLimit (); +BOOL LoadSysEncSettings (); +int LoadNonSysInPlaceEncSettings (WipeAlgorithmId *wipeAlgorithm); +void RemoveNonSysInPlaceEncNotifications (void); +void SavePostInstallTasksSettings (int command); +void DoPostInstallTasks (HWND hwndDlg); +void InitOSVersionInfo (); +void InitApp ( HINSTANCE hInstance, wchar_t *lpszCommandLine ); +void FinalizeApp (void); +void InitHelpFileName (void); +BOOL OpenDevice (const wchar_t *lpszPath, OPEN_TEST_STRUCT *driver, BOOL detectFilesystem, BOOL matchVolumeID, const BYTE* pbVolumeID); +void NotifyDriverOfPortableMode (void); +int GetAvailableFixedDisks ( HWND hComboBox , char *lpszRootPath ); +int GetAvailableRemovables ( HWND hComboBox , char *lpszRootPath ); +int IsSystemDevicePath (const wchar_t *path, HWND hwndDlg, BOOL bReliableRequired); +int IsNonSysPartitionOnSysDrive (const wchar_t *path); +BOOL CALLBACK RawDevicesDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); +INT_PTR TextInfoDialogBox (int nID); +BOOL CALLBACK TextInfoDialogBoxDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +char * GetLegalNotices (); +BOOL CALLBACK BenchmarkDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +void UserEnrichRandomPool (HWND hwndDlg); +BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); +int DriverAttach ( void ); +BOOL CALLBACK CipherTestDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); +void ResetCipherTest ( HWND hwndDlg , int idTestCipher ); +void ResetCurrentDirectory (); +BOOL BrowseFiles (HWND hwndDlg, char *stringId, wchar_t *lpszFileName, BOOL keepHistory, BOOL saveMode, wchar_t *browseFilter); +BOOL BrowseDirectories (HWND hWnd, char *lpszTitle, wchar_t *dirName); +void handleError ( HWND hwndDlg , int code, const char* srcPos ); +BOOL CheckFileStreamWriteErrors (HWND hwndDlg, FILE *file, const wchar_t *fileName); +void LocalizeDialog ( HWND hwnd, char *stringId ); +void OpenVolumeExplorerWindow (int driveNo); +static BOOL CALLBACK CloseVolumeExplorerWindowsEnum( HWND hwnd, LPARAM driveNo); +BOOL CloseVolumeExplorerWindows (HWND hwnd, int driveNo); +BOOL UpdateDriveCustomLabel (int driveNo, wchar_t* effectiveLabel, BOOL bSetValue); +BOOL CheckCapsLock (HWND hwnd, BOOL quiet); +BOOL CheckFileExtension (wchar_t *fileName); +void CorrectFileName (wchar_t* fileName); +void IncreaseWrongPwdRetryCount (int count); +void ResetWrongPwdRetryCount (void); +BOOL WrongPwdRetryCountOverLimit (void); +DWORD GetUsedLogicalDrives (void); +int GetFirstAvailableDrive (); +int GetLastAvailableDrive (); +BOOL IsDriveAvailable (int driveNo); +BOOL IsDeviceMounted (wchar_t *deviceName); +int DriverUnmountVolume (HWND hwndDlg, int nDosDriveNo, BOOL forced); +void BroadcastDeviceChange (WPARAM message, int nDosDriveNo, DWORD driveMap); +int MountVolume (HWND hwndDlg, int driveNo, wchar_t *volumePath, Password *password, int pkcs5, int pim, BOOL truecryptMode, BOOL cachePassword, BOOL cachePim, BOOL sharedAccess, const MountOptions* const mountOptions, BOOL quiet, BOOL bReportWrongPassword); +BOOL UnmountVolume (HWND hwndDlg , int nDosDriveNo, BOOL forceUnmount); +BOOL UnmountVolumeAfterFormatExCall (HWND hwndDlg, int nDosDriveNo); +BOOL IsPasswordCacheEmpty (void); +BOOL IsMountedVolumeID (BYTE volumeID[VOLUME_ID_SIZE]); +BOOL IsMountedVolume (const wchar_t *volname); +int GetMountedVolumeDriveNo (wchar_t *volname); +BOOL IsAdmin (void); +BOOL IsBuiltInAdmin (); +BOOL IsUacSupported (); +BOOL ResolveSymbolicLink (const wchar_t *symLinkName, PWSTR targetName, size_t cbTargetName); +int GetDiskDeviceDriveLetter (PWSTR deviceName); +int FileSystemAppearsEmpty (const wchar_t *devicePath); +__int64 GetStatsFreeSpaceOnPartition (const wchar_t *devicePath, float *percent, __int64 *occupiedBytes, BOOL silent); +__int64 GetDeviceSize (const wchar_t *devicePath); +HANDLE DismountDrive (wchar_t *devName, wchar_t *devicePath); +int64 FindString (const char *buf, const char *str, int64 bufLen, int64 strLen, int64 startOffset); +BOOL FileExists (const wchar_t *filePathPtr); +__int64 FindStringInFile (const wchar_t *filePath, const char *str, int strLen); +BOOL TCCopyFile (wchar_t *sourceFileName, wchar_t *destinationFile); +BOOL SaveBufferToFile (const char *inputBuffer, const wchar_t *destinationFile, DWORD inputLength, BOOL bAppend, BOOL bRenameIfFailed); +BOOL TCFlushFile (FILE *f); +BOOL PrintHardCopyTextUTF16 (wchar_t *text, wchar_t *title, size_t byteLen); +void GetSpeedString (unsigned __int64 speed, wchar_t *str, size_t cbStr); +BOOL IsNonInstallMode (); +BOOL DriverUnload (); +LRESULT SetCheckBox (HWND hwndDlg, int dlgItem, BOOL state); +BOOL GetCheckBox (HWND hwndDlg, int dlgItem); +void SetListScrollHPos (HWND hList, int topMostVisibleItem); +void ManageStartupSeq (void); +void ManageStartupSeqWiz (BOOL bRemove, const wchar_t *arg); +void CleanLastVisitedMRU (void); +void ClearHistory (HWND hwndDlgItem); +LRESULT ListItemAdd (HWND list, int index, const wchar_t *string); +LRESULT ListSubItemSet (HWND list, int index, int subIndex, const wchar_t *string); +BOOL GetMountList (MOUNT_LIST_STRUCT *list); +int GetDriverRefCount (); +void GetSizeString (unsigned __int64 size, wchar_t *str, size_t cbStr); +__int64 GetFileSize64 (const wchar_t *path); +BOOL LoadInt16 (const wchar_t *filePath, int *result, __int64 fileOffset); +BOOL LoadInt32 (const wchar_t *filePath, unsigned __int32 *result, __int64 fileOffset); +char *LoadFile (const wchar_t *fileName, DWORD *size); +char *LoadFileBlock (const wchar_t *fileName, __int64 fileOffset, DWORD count); +wchar_t *GetModPath (wchar_t *path, int maxSize); +wchar_t *GetConfigPath (wchar_t *fileName); +wchar_t *GetProgramConfigPath (wchar_t *fileName); +wchar_t GetSystemDriveLetter (void); +void OpenPageHelp (HWND hwndDlg, int nPage); +void TaskBarIconDisplayBalloonTooltip (HWND hwnd, wchar_t *headline, wchar_t *text, BOOL warning); +void InfoBalloon (char *headingStringId, char *textStringId, HWND hwnd); +void InfoBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd); +void WarningBalloon (char *headingStringId, char *textStringId, HWND hwnd); +void WarningBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd); +int Info (char *stringId, HWND hwnd); +int InfoTopMost (char *stringId, HWND hwnd); +int InfoDirect (const wchar_t *msg, HWND hwnd); +int Warning (char *stringId, HWND hwnd); +int WarningTopMost (char *stringId, HWND hwnd); +int WarningDirect (const wchar_t *warnMsg, HWND hwnd); +int Error (char *stringId, HWND hwnd); +int ErrorRetryCancel (char *stringId, HWND hwnd); +int ErrorDirect (const wchar_t *errMsg, HWND hwnd); +int ErrorTopMost (char *stringId, HWND hwnd); +int AskYesNo (char *stringId, HWND hwnd); +int AskYesNoString (const wchar_t *str, HWND hwnd); +int AskYesNoTopmost (char *stringId, HWND hwnd); +int AskNoYes (char *stringId, HWND hwnd); +int AskNoYesString (const wchar_t *string, HWND hwnd); +int AskOkCancel (char *stringId, HWND hwnd); +int AskWarnYesNo (char *stringId, HWND hwnd); +int AskWarnYesNoString (const wchar_t *string, HWND hwnd); +int AskWarnYesNoTopmost (char *stringId, HWND hwnd); +int AskWarnYesNoStringTopmost (const wchar_t *string, HWND hwnd); +int AskWarnNoYes (char *stringId, HWND hwnd); +int AskWarnNoYesString (const wchar_t *string, HWND hwnd); +int AskWarnNoYesTopmost (char *stringId, HWND hwnd); +int AskWarnOkCancel (char *stringId, HWND hwnd); +int AskWarnCancelOk (char *stringId, HWND hwnd); +int AskErrYesNo (char *stringId, HWND hwnd); +int AskErrNoYes (char *stringId, HWND hwnd); +int AskMultiChoice (void *strings[], BOOL bBold, HWND hwnd); +BOOL ConfigWriteBegin (); +BOOL ConfigWriteEnd (HWND hwnd); +BOOL ConfigWriteString (char *configKey, char *configValue); +BOOL ConfigWriteStringW (char *configKey, wchar_t *configValue); +BOOL ConfigWriteInt (char *configKey, int configValue); +int ConfigReadInt (char *configKey, int defaultValue); +char *ConfigReadString (char *configKey, char *defaultValue, char *str, int maxLen); +void ConfigReadCompareInt(char *configKey, int defaultValue, int* pOutputValue, BOOL bOnlyCheckModified, BOOL* pbModified); +void ConfigReadCompareString (char *configKey, char *defaultValue, char *str, int maxLen, BOOL bOnlyCheckModified, BOOL *pbModified); +void RestoreDefaultKeyFilesParam (void); +BOOL LoadDefaultKeyFilesParam (void); +void Debug (char *format, ...); +void DebugMsgBox (char *format, ...); +BOOL IsOSAtLeast (OSVersionEnum reqMinOS); +BOOL IsOSVersionAtLeast (OSVersionEnum reqMinOS, int reqMinServicePack); +BOOL Is64BitOs (); +BOOL IsServerOS (); +BOOL IsHiddenOSRunning (void); +BOOL EnableWow64FsRedirection (BOOL enable); +BOOL RestartComputer (void); +void Applink (char *dest, BOOL bSendOS, char *extraOutput); +wchar_t *RelativePath2Absolute (wchar_t *szFileName); +void HandleDriveNotReadyError (HWND hwnd); +BOOL CALLBACK CloseTCWindowsEnum( HWND hwnd, LPARAM lParam); +BOOL CALLBACK FindTCWindowEnum (HWND hwnd, LPARAM lParam); +BYTE *MapResource (wchar_t *resourceType, int resourceId, PDWORD size); +void InconsistencyResolved (char *msg); +void ReportUnexpectedState (char *techInfo); +BOOL SelectMultipleFiles (HWND hwndDlg, const char *stringId, wchar_t *lpszFileName, size_t cbFileName, BOOL keepHistory); +BOOL SelectMultipleFilesNext (wchar_t *lpszFileName, size_t cbFileName); +void OpenOnlineHelp (); +BOOL GetPartitionInfo (const wchar_t *deviceName, PPARTITION_INFORMATION rpartInfo); +BOOL GetDeviceInfo (const wchar_t *deviceName, DISK_PARTITION_INFO_STRUCT *info); +BOOL GetDriveGeometry (const wchar_t *deviceName, PDISK_GEOMETRY diskGeometry); +BOOL GetPhysicalDriveGeometry (int driveNumber, PDISK_GEOMETRY diskGeometry); +BOOL IsVolumeDeviceHosted (const wchar_t *lpszDiskFile); +int CompensateXDPI (int val); +int CompensateYDPI (int val); +int CompensateDPIFont (int val); +int GetTextGfxWidth (HWND hwndDlgItem, const wchar_t *text, HFONT hFont); +int GetTextGfxHeight (HWND hwndDlgItem, const wchar_t *text, HFONT hFont); +BOOL ToHyperlink (HWND hwndDlg, UINT ctrlId); +BOOL ToCustHyperlink (HWND hwndDlg, UINT ctrlId, HFONT hFont); +void DisableCloseButton (HWND hwndDlg); +void EnableCloseButton (HWND hwndDlg); +void ToBootPwdField (HWND hwndDlg, UINT ctrlId); +void AccommodateTextField (HWND hwndDlg, UINT ctrlId, BOOL bFirstUpdate, HFONT hFont); +BOOL GetDriveLabel (int driveNo, wchar_t *label, int labelSize); +BOOL GetSysDevicePaths (HWND hwndDlg); +BOOL DoDriverInstall (HWND hwndDlg); +int OpenVolume (OpenVolumeContext *context, const wchar_t *volumePath, Password *password, int pkcs5_prf, int pim, BOOL truecryptMode, BOOL write, BOOL preserveTimestamps, BOOL useBackupHeader); +void CloseVolume (OpenVolumeContext *context); +int ReEncryptVolumeHeader (HWND hwndDlg, char *buffer, BOOL bBoot, CRYPTO_INFO *cryptoInfo, Password *password, int pim, BOOL wipeMode); +BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly); +BOOL IsPagingFileWildcardActive (); +BOOL DisablePagingFile (); +BOOL CALLBACK SecurityTokenPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +BOOL CALLBACK SecurityTokenKeyfileDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +BOOL InitSecurityTokenLibrary (HWND hwndDlg); +BOOL FileHasReadOnlyAttribute (const wchar_t *path); +BOOL IsFileOnReadOnlyFilesystem (const wchar_t *path); +void CheckFilesystem (HWND hwndDlg, int driveNo, BOOL fixErrors); +BOOL BufferContainsString (const byte *buffer, size_t bufferSize, const char *str); +int AskNonSysInPlaceEncryptionResume (HWND hwndDlg, BOOL* pbDecrypt); +BOOL RemoveDeviceWriteProtection (HWND hwndDlg, wchar_t *devicePath); +void EnableElevatedCursorChange (HWND parent); +BOOL DisableFileCompression (HANDLE file); +BOOL VolumePathExists (const wchar_t *volumePath); +BOOL IsWindowsIsoBurnerAvailable (); +BOOL LaunchWindowsIsoBurner (HWND hwnd, const wchar_t *isoPath); +BOOL IsApplicationInstalled (const wchar_t *appName); +int GetPim (HWND hwndDlg, UINT ctrlId); +void SetPim (HWND hwndDlg, UINT ctrlId, int pim); +BOOL GetPassword (HWND hwndDlg, UINT ctrlID, char* passValue, int bufSize, BOOL bShowError); +void SetPassword (HWND hwndDlg, UINT ctrlID, char* passValue); +void HandleShowPasswordFieldAction (HWND hwndDlg, UINT checkBoxId, UINT edit1Id, UINT edit2Id); +HKEY OpenDeviceClassRegKey (const GUID *deviceClassGuid); +LSTATUS DeleteRegistryKey (HKEY, LPCTSTR); +HIMAGELIST CreateImageList(int cx, int cy, UINT flags, int cInitial, int cGrow); +int AddBitmapToImageList(HIMAGELIST himl, HBITMAP hbmImage, HBITMAP hbmMask); +HRESULT VCStrDupW(LPCWSTR psz, LPWSTR *ppwsz); +void ProcessEntropyEstimate (HWND hProgress, DWORD* pdwInitialValue, DWORD dwCounter, DWORD dwMaxLevel, DWORD* pdwEntropy); +void AllowMessageInUIPI (UINT msg); +BOOL IsRepeatedByteArray (byte value, const byte* buffer, size_t bufferSize); +BOOL TranslateVolumeID (HWND hwndDlg, wchar_t* pathValue, size_t cchPathValue); +BOOL CopyTextToClipboard (const wchar_t* txtValue); + +#ifdef __cplusplus +} + +#include +#include + +struct HostDevice +{ + HostDevice () + : + Bootable (false), + ContainsSystem (false), + DynamicVolume (false), + Floppy (false), + IsPartition (false), + IsVirtualPartition (false), + HasUnencryptedFilesystem (false), + Removable (false), + Size (0), + SystemNumber((uint32) -1) + { + } + + ~HostDevice () { } + + bool Bootable; + bool ContainsSystem; + bool DynamicVolume; + bool Floppy; + bool IsPartition; + bool IsVirtualPartition; + bool HasUnencryptedFilesystem; + std::wstring MountPoint; + std::wstring Name; + std::wstring Path; + bool Removable; + uint64 Size; + uint32 SystemNumber; + + std::vector Partitions; +}; + +struct RawDevicesDlgParam +{ + std::vector devices; + wchar_t *pszFileName; +}; + +BOOL BrowseFilesInDir (HWND hwndDlg, char *stringId, wchar_t *initialDir, wchar_t *lpszFileName, BOOL keepHistory, BOOL saveMode, wchar_t *browseFilter, const wchar_t *initialFileName = NULL, const wchar_t *defaultExtension = NULL); +std::wstring SingleStringToWide (const std::string &singleString); +std::wstring Utf8StringToWide (const std::string &utf8String); +std::string WideToUtf8String (const std::wstring &wideString); +std::vector GetAvailableHostDevices (bool noDeviceProperties = false, bool singleList = false, bool noFloppy = true, bool detectUnencryptedFilesystems = false); +std::wstring ToUpperCase (const std::wstring &str); +std::wstring GetWrongPasswordErrorMessage (HWND hwndDlg); +std::wstring GetWindowsEdition (); +std::wstring FitPathInGfxWidth (HWND hwnd, HFONT hFont, LONG width, const std::wstring &path); +std::wstring GetServiceConfigPath (const wchar_t *fileName, bool useLegacy); +std::wstring VolumeGuidPathToDevicePath (std::wstring volumeGuidPath); +std::wstring HarddiskVolumePathToPartitionPath (const std::wstring &harddiskVolumePath); +std::wstring FindLatestFileOrDirectory (const std::wstring &directory, const wchar_t *namePattern, bool findDirectory, bool findFile); +std::wstring GetUserFriendlyVersionString (int version); +std::wstring IntToWideString (int val); +std::wstring ArrayToHexWideString (const unsigned char* pbData, int cbData); +bool HexWideStringToArray (const wchar_t* hexStr, std::vector& arr); +std::wstring FindDeviceByVolumeID (const BYTE volumeID [VOLUME_ID_SIZE]); +void RegisterDriverInf (bool registerFilter, const std::string& filter, const std::string& filterReg, HWND ParentWindow, HKEY regKey); +std::wstring GetTempPathString (); +inline std::wstring AppendSrcPos (const wchar_t* msg, const char* srcPos) +{ + return std::wstring (msg? msg : L"") + L"\n\nSource: " + SingleStringToWide (srcPos); +} + +// Display a wait dialog while calling the provided callback with the given parameter +typedef void (CALLBACK* WaitThreadProc)(void* pArg, HWND hWaitDlg); +void BringToForeground(HWND hWnd); +void ShowWaitDialog(HWND hwnd, BOOL bUseHwndAsParent, WaitThreadProc callback, void* pArg); + +#endif // __cplusplus + +#endif // TC_HEADER_DLGCODE diff --git a/src/Common/EncryptionThreadPool.c b/src/Common/EncryptionThreadPool.c index ec0d1f26..9cc641cc 100644 --- a/src/Common/EncryptionThreadPool.c +++ b/src/Common/EncryptionThreadPool.c @@ -1,511 +1,511 @@ -/* - 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 "EncryptionThreadPool.h" -#include "Pkcs5.h" -#ifdef DEVICE_DRIVER -#include "Driver/Ntdriver.h" -#endif - -#define TC_ENC_THREAD_POOL_MAX_THREAD_COUNT 64 -#define TC_ENC_THREAD_POOL_QUEUE_SIZE (TC_ENC_THREAD_POOL_MAX_THREAD_COUNT * 2) - -#ifdef DEVICE_DRIVER - -#define TC_THREAD_HANDLE PKTHREAD -#define TC_THREAD_PROC VOID - -#define TC_SET_EVENT(EVENT) KeSetEvent (&EVENT, IO_DISK_INCREMENT, FALSE) -#define TC_CLEAR_EVENT(EVENT) KeClearEvent (&EVENT) - -#define TC_MUTEX FAST_MUTEX -#define TC_ACQUIRE_MUTEX(MUTEX) ExAcquireFastMutex (MUTEX) -#define TC_RELEASE_MUTEX(MUTEX) ExReleaseFastMutex (MUTEX) - -#else // !DEVICE_DRIVER - -#define TC_THREAD_HANDLE HANDLE -#define TC_THREAD_PROC unsigned __stdcall - -#define TC_SET_EVENT(EVENT) SetEvent (EVENT) -#define TC_CLEAR_EVENT(EVENT) ResetEvent (EVENT) - -#define TC_MUTEX HANDLE -#define TC_ACQUIRE_MUTEX(MUTEX) WaitForSingleObject (*(MUTEX), INFINITE) -#define TC_RELEASE_MUTEX(MUTEX) ReleaseMutex (*(MUTEX)) - -#endif // !DEVICE_DRIVER - - -typedef enum -{ - WorkItemFree, - WorkItemReady, - WorkItemBusy -} WorkItemState; - - -typedef struct EncryptionThreadPoolWorkItemStruct -{ - WorkItemState State; - EncryptionThreadPoolWorkType Type; - - TC_EVENT ItemCompletedEvent; - - struct EncryptionThreadPoolWorkItemStruct *FirstFragment; - LONG OutstandingFragmentCount; - - union - { - struct - { - PCRYPTO_INFO CryptoInfo; - byte *Data; - UINT64_STRUCT StartUnitNo; - uint32 UnitCount; - - } Encryption; - - struct - { - TC_EVENT *CompletionEvent; - LONG *CompletionFlag; - char *DerivedKey; - int IterationCount; - TC_EVENT *NoOutstandingWorkItemEvent; - LONG *OutstandingWorkItemCount; - char *Password; - int PasswordLength; - int Pkcs5Prf; - char *Salt; - - } KeyDerivation; - }; - -} EncryptionThreadPoolWorkItem; - - -static volatile BOOL ThreadPoolRunning = FALSE; -static volatile BOOL StopPending = FALSE; - -static uint32 ThreadCount; -static TC_THREAD_HANDLE ThreadHandles[TC_ENC_THREAD_POOL_MAX_THREAD_COUNT]; - -static EncryptionThreadPoolWorkItem WorkItemQueue[TC_ENC_THREAD_POOL_QUEUE_SIZE]; - -static volatile int EnqueuePosition; -static volatile int DequeuePosition; - -static TC_MUTEX EnqueueMutex; -static TC_MUTEX DequeueMutex; - -static TC_EVENT WorkItemReadyEvent; -static TC_EVENT WorkItemCompletedEvent; - - -static WorkItemState GetWorkItemState (EncryptionThreadPoolWorkItem *workItem) -{ - return InterlockedExchangeAdd ((LONG *) &workItem->State, 0); -} - - -static void SetWorkItemState (EncryptionThreadPoolWorkItem *workItem, WorkItemState newState) -{ - InterlockedExchange ((LONG *) &workItem->State, (LONG) newState); -} - - -static TC_THREAD_PROC EncryptionThreadProc (void *threadArg) -{ - EncryptionThreadPoolWorkItem *workItem; - - while (!StopPending) - { - TC_ACQUIRE_MUTEX (&DequeueMutex); - - workItem = &WorkItemQueue[DequeuePosition++]; - - if (DequeuePosition >= TC_ENC_THREAD_POOL_QUEUE_SIZE) - DequeuePosition = 0; - - while (!StopPending && GetWorkItemState (workItem) != WorkItemReady) - { - TC_WAIT_EVENT (WorkItemReadyEvent); - } - - SetWorkItemState (workItem, WorkItemBusy); - - TC_RELEASE_MUTEX (&DequeueMutex); - - if (StopPending) - break; - - switch (workItem->Type) - { - case DecryptDataUnitsWork: - DecryptDataUnitsCurrentThread (workItem->Encryption.Data, &workItem->Encryption.StartUnitNo, workItem->Encryption.UnitCount, workItem->Encryption.CryptoInfo); - break; - - case EncryptDataUnitsWork: - EncryptDataUnitsCurrentThread (workItem->Encryption.Data, &workItem->Encryption.StartUnitNo, workItem->Encryption.UnitCount, workItem->Encryption.CryptoInfo); - break; - - case DeriveKeyWork: - switch (workItem->KeyDerivation.Pkcs5Prf) - { - case RIPEMD160: - derive_key_ripemd160 (workItem->KeyDerivation.Password, workItem->KeyDerivation.PasswordLength, workItem->KeyDerivation.Salt, PKCS5_SALT_SIZE, - workItem->KeyDerivation.IterationCount, workItem->KeyDerivation.DerivedKey, GetMaxPkcs5OutSize()); - break; - - case SHA512: - derive_key_sha512 (workItem->KeyDerivation.Password, workItem->KeyDerivation.PasswordLength, workItem->KeyDerivation.Salt, PKCS5_SALT_SIZE, - workItem->KeyDerivation.IterationCount, workItem->KeyDerivation.DerivedKey, GetMaxPkcs5OutSize()); - break; - - case WHIRLPOOL: - derive_key_whirlpool (workItem->KeyDerivation.Password, workItem->KeyDerivation.PasswordLength, workItem->KeyDerivation.Salt, PKCS5_SALT_SIZE, - workItem->KeyDerivation.IterationCount, workItem->KeyDerivation.DerivedKey, GetMaxPkcs5OutSize()); - break; - - case SHA256: - derive_key_sha256 (workItem->KeyDerivation.Password, workItem->KeyDerivation.PasswordLength, workItem->KeyDerivation.Salt, PKCS5_SALT_SIZE, - workItem->KeyDerivation.IterationCount, workItem->KeyDerivation.DerivedKey, GetMaxPkcs5OutSize()); - break; - - default: - TC_THROW_FATAL_EXCEPTION; - } - - InterlockedExchange (workItem->KeyDerivation.CompletionFlag, TRUE); - TC_SET_EVENT (*workItem->KeyDerivation.CompletionEvent); - - if (InterlockedDecrement (workItem->KeyDerivation.OutstandingWorkItemCount) == 0) - TC_SET_EVENT (*workItem->KeyDerivation.NoOutstandingWorkItemEvent); - - SetWorkItemState (workItem, WorkItemFree); - TC_SET_EVENT (WorkItemCompletedEvent); - continue; - - default: - TC_THROW_FATAL_EXCEPTION; - } - - if (workItem != workItem->FirstFragment) - { - SetWorkItemState (workItem, WorkItemFree); - TC_SET_EVENT (WorkItemCompletedEvent); - } - - if (InterlockedDecrement (&workItem->FirstFragment->OutstandingFragmentCount) == 0) - TC_SET_EVENT (workItem->FirstFragment->ItemCompletedEvent); - } - -#ifdef DEVICE_DRIVER - PsTerminateSystemThread (STATUS_SUCCESS); -#else - _endthreadex (0); - return 0; -#endif -} - - -BOOL EncryptionThreadPoolStart (size_t encryptionFreeCpuCount) -{ - size_t cpuCount, i; - - if (ThreadPoolRunning) - return TRUE; - -#ifdef DEVICE_DRIVER - cpuCount = GetCpuCount(); -#else - { - SYSTEM_INFO sysInfo; - GetSystemInfo (&sysInfo); - cpuCount = sysInfo.dwNumberOfProcessors; - } -#endif - - if (cpuCount > encryptionFreeCpuCount) - cpuCount -= encryptionFreeCpuCount; - - if (cpuCount < 2) - return TRUE; - - if (cpuCount > TC_ENC_THREAD_POOL_MAX_THREAD_COUNT) - cpuCount = TC_ENC_THREAD_POOL_MAX_THREAD_COUNT; - - StopPending = FALSE; - DequeuePosition = 0; - EnqueuePosition = 0; - -#ifdef DEVICE_DRIVER - KeInitializeEvent (&WorkItemReadyEvent, SynchronizationEvent, FALSE); - KeInitializeEvent (&WorkItemCompletedEvent, SynchronizationEvent, FALSE); -#else - WorkItemReadyEvent = CreateEvent (NULL, FALSE, FALSE, NULL); - if (!WorkItemReadyEvent) - return FALSE; - - WorkItemCompletedEvent = CreateEvent (NULL, FALSE, FALSE, NULL); - if (!WorkItemCompletedEvent) - return FALSE; -#endif - -#ifdef DEVICE_DRIVER - ExInitializeFastMutex (&DequeueMutex); - ExInitializeFastMutex (&EnqueueMutex); -#else - DequeueMutex = CreateMutex (NULL, FALSE, NULL); - if (!DequeueMutex) - return FALSE; - - EnqueueMutex = CreateMutex (NULL, FALSE, NULL); - if (!EnqueueMutex) - return FALSE; -#endif - - memset (WorkItemQueue, 0, sizeof (WorkItemQueue)); - - for (i = 0; i < sizeof (WorkItemQueue) / sizeof (WorkItemQueue[0]); ++i) - { - WorkItemQueue[i].State = WorkItemFree; - -#ifdef DEVICE_DRIVER - KeInitializeEvent (&WorkItemQueue[i].ItemCompletedEvent, SynchronizationEvent, FALSE); -#else - WorkItemQueue[i].ItemCompletedEvent = CreateEvent (NULL, FALSE, FALSE, NULL); - if (!WorkItemQueue[i].ItemCompletedEvent) - { - EncryptionThreadPoolStop(); - return FALSE; - } -#endif - } - - for (ThreadCount = 0; ThreadCount < cpuCount; ++ThreadCount) - { -#ifdef DEVICE_DRIVER - if (!NT_SUCCESS (TCStartThread (EncryptionThreadProc, NULL, &ThreadHandles[ThreadCount]))) -#else - if (!(ThreadHandles[ThreadCount] = (HANDLE) _beginthreadex (NULL, 0, EncryptionThreadProc, NULL, 0, NULL))) -#endif - { - EncryptionThreadPoolStop(); - return FALSE; - } - } - - ThreadPoolRunning = TRUE; - return TRUE; -} - - -void EncryptionThreadPoolStop () -{ - size_t i; - - if (!ThreadPoolRunning) - return; - - StopPending = TRUE; - TC_SET_EVENT (WorkItemReadyEvent); - - for (i = 0; i < ThreadCount; ++i) - { -#ifdef DEVICE_DRIVER - TCStopThread (ThreadHandles[i], &WorkItemReadyEvent); -#else - TC_WAIT_EVENT (ThreadHandles[i]); -#endif - } - - ThreadCount = 0; - -#ifndef DEVICE_DRIVER - CloseHandle (DequeueMutex); - CloseHandle (EnqueueMutex); - - CloseHandle (WorkItemReadyEvent); - CloseHandle (WorkItemCompletedEvent); - - for (i = 0; i < sizeof (WorkItemQueue) / sizeof (WorkItemQueue[0]); ++i) - { - if (WorkItemQueue[i].ItemCompletedEvent) - CloseHandle (WorkItemQueue[i].ItemCompletedEvent); - } -#endif - - ThreadPoolRunning = FALSE; -} - - -void EncryptionThreadPoolBeginKeyDerivation (TC_EVENT *completionEvent, TC_EVENT *noOutstandingWorkItemEvent, LONG *completionFlag, LONG *outstandingWorkItemCount, int pkcs5Prf, char *password, int passwordLength, char *salt, int iterationCount, char *derivedKey) -{ - EncryptionThreadPoolWorkItem *workItem; - - if (!ThreadPoolRunning) - TC_THROW_FATAL_EXCEPTION; - - TC_ACQUIRE_MUTEX (&EnqueueMutex); - - workItem = &WorkItemQueue[EnqueuePosition++]; - if (EnqueuePosition >= TC_ENC_THREAD_POOL_QUEUE_SIZE) - EnqueuePosition = 0; - - while (GetWorkItemState (workItem) != WorkItemFree) - { - TC_WAIT_EVENT (WorkItemCompletedEvent); - } - - workItem->Type = DeriveKeyWork; - workItem->KeyDerivation.CompletionEvent = completionEvent; - workItem->KeyDerivation.CompletionFlag = completionFlag; - workItem->KeyDerivation.DerivedKey = derivedKey; - workItem->KeyDerivation.IterationCount = iterationCount; - workItem->KeyDerivation.NoOutstandingWorkItemEvent = noOutstandingWorkItemEvent; - workItem->KeyDerivation.OutstandingWorkItemCount = outstandingWorkItemCount; - workItem->KeyDerivation.Password = password; - workItem->KeyDerivation.PasswordLength = passwordLength; - workItem->KeyDerivation.Pkcs5Prf = pkcs5Prf; - workItem->KeyDerivation.Salt = salt; - - InterlockedIncrement (outstandingWorkItemCount); - TC_CLEAR_EVENT (*noOutstandingWorkItemEvent); - - SetWorkItemState (workItem, WorkItemReady); - TC_SET_EVENT (WorkItemReadyEvent); - TC_RELEASE_MUTEX (&EnqueueMutex); -} - - -void EncryptionThreadPoolDoWork (EncryptionThreadPoolWorkType type, byte *data, const UINT64_STRUCT *startUnitNo, uint32 unitCount, PCRYPTO_INFO cryptoInfo) -{ - uint32 fragmentCount; - uint32 unitsPerFragment; - uint32 remainder; - - byte *fragmentData; - uint64 fragmentStartUnitNo; - - EncryptionThreadPoolWorkItem *workItem; - EncryptionThreadPoolWorkItem *firstFragmentWorkItem; - - if (unitCount == 0) - return; - - if (!ThreadPoolRunning || unitCount == 1) - { - switch (type) - { - case DecryptDataUnitsWork: - DecryptDataUnitsCurrentThread (data, startUnitNo, unitCount, cryptoInfo); - break; - - case EncryptDataUnitsWork: - EncryptDataUnitsCurrentThread (data, startUnitNo, unitCount, cryptoInfo); - break; - - default: - TC_THROW_FATAL_EXCEPTION; - } - - return; - } - - if (unitCount <= ThreadCount) - { - fragmentCount = unitCount; - unitsPerFragment = 1; - remainder = 0; - } - else - { - /* Note that it is not efficient to divide the data into fragments smaller than a few hundred bytes. - The reason is that the overhead associated with thread handling would in most cases make a multi-threaded - process actually slower than a single-threaded process. */ - - fragmentCount = ThreadCount; - unitsPerFragment = unitCount / ThreadCount; - remainder = unitCount % ThreadCount; - - if (remainder > 0) - ++unitsPerFragment; - } - - fragmentData = data; - fragmentStartUnitNo = startUnitNo->Value; - - TC_ACQUIRE_MUTEX (&EnqueueMutex); - firstFragmentWorkItem = &WorkItemQueue[EnqueuePosition]; - - while (GetWorkItemState (firstFragmentWorkItem) != WorkItemFree) - { - TC_WAIT_EVENT (WorkItemCompletedEvent); - } - - firstFragmentWorkItem->OutstandingFragmentCount = fragmentCount; - - while (fragmentCount-- > 0) - { - workItem = &WorkItemQueue[EnqueuePosition++]; - if (EnqueuePosition >= TC_ENC_THREAD_POOL_QUEUE_SIZE) - EnqueuePosition = 0; - - while (GetWorkItemState (workItem) != WorkItemFree) - { - TC_WAIT_EVENT (WorkItemCompletedEvent); - } - - workItem->Type = type; - workItem->FirstFragment = firstFragmentWorkItem; - - workItem->Encryption.CryptoInfo = cryptoInfo; - workItem->Encryption.Data = fragmentData; - workItem->Encryption.UnitCount = unitsPerFragment; - workItem->Encryption.StartUnitNo.Value = fragmentStartUnitNo; - - fragmentData += unitsPerFragment * ENCRYPTION_DATA_UNIT_SIZE; - fragmentStartUnitNo += unitsPerFragment; - - if (remainder > 0 && --remainder == 0) - --unitsPerFragment; - - SetWorkItemState (workItem, WorkItemReady); - TC_SET_EVENT (WorkItemReadyEvent); - } - - TC_RELEASE_MUTEX (&EnqueueMutex); - - TC_WAIT_EVENT (firstFragmentWorkItem->ItemCompletedEvent); - SetWorkItemState (firstFragmentWorkItem, WorkItemFree); - TC_SET_EVENT (WorkItemCompletedEvent); -} - - -size_t GetEncryptionThreadCount () -{ - return ThreadPoolRunning ? ThreadCount : 0; -} - - -size_t GetMaxEncryptionThreadCount () -{ - return TC_ENC_THREAD_POOL_MAX_THREAD_COUNT; -} - - -BOOL IsEncryptionThreadPoolRunning () -{ - return ThreadPoolRunning; -} +/* + 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 "EncryptionThreadPool.h" +#include "Pkcs5.h" +#ifdef DEVICE_DRIVER +#include "Driver/Ntdriver.h" +#endif + +#define TC_ENC_THREAD_POOL_MAX_THREAD_COUNT 64 +#define TC_ENC_THREAD_POOL_QUEUE_SIZE (TC_ENC_THREAD_POOL_MAX_THREAD_COUNT * 2) + +#ifdef DEVICE_DRIVER + +#define TC_THREAD_HANDLE PKTHREAD +#define TC_THREAD_PROC VOID + +#define TC_SET_EVENT(EVENT) KeSetEvent (&EVENT, IO_DISK_INCREMENT, FALSE) +#define TC_CLEAR_EVENT(EVENT) KeClearEvent (&EVENT) + +#define TC_MUTEX FAST_MUTEX +#define TC_ACQUIRE_MUTEX(MUTEX) ExAcquireFastMutex (MUTEX) +#define TC_RELEASE_MUTEX(MUTEX) ExReleaseFastMutex (MUTEX) + +#else // !DEVICE_DRIVER + +#define TC_THREAD_HANDLE HANDLE +#define TC_THREAD_PROC unsigned __stdcall + +#define TC_SET_EVENT(EVENT) SetEvent (EVENT) +#define TC_CLEAR_EVENT(EVENT) ResetEvent (EVENT) + +#define TC_MUTEX HANDLE +#define TC_ACQUIRE_MUTEX(MUTEX) WaitForSingleObject (*(MUTEX), INFINITE) +#define TC_RELEASE_MUTEX(MUTEX) ReleaseMutex (*(MUTEX)) + +#endif // !DEVICE_DRIVER + + +typedef enum +{ + WorkItemFree, + WorkItemReady, + WorkItemBusy +} WorkItemState; + + +typedef struct EncryptionThreadPoolWorkItemStruct +{ + WorkItemState State; + EncryptionThreadPoolWorkType Type; + + TC_EVENT ItemCompletedEvent; + + struct EncryptionThreadPoolWorkItemStruct *FirstFragment; + LONG OutstandingFragmentCount; + + union + { + struct + { + PCRYPTO_INFO CryptoInfo; + byte *Data; + UINT64_STRUCT StartUnitNo; + uint32 UnitCount; + + } Encryption; + + struct + { + TC_EVENT *CompletionEvent; + LONG *CompletionFlag; + char *DerivedKey; + int IterationCount; + TC_EVENT *NoOutstandingWorkItemEvent; + LONG *OutstandingWorkItemCount; + char *Password; + int PasswordLength; + int Pkcs5Prf; + char *Salt; + + } KeyDerivation; + }; + +} EncryptionThreadPoolWorkItem; + + +static volatile BOOL ThreadPoolRunning = FALSE; +static volatile BOOL StopPending = FALSE; + +static uint32 ThreadCount; +static TC_THREAD_HANDLE ThreadHandles[TC_ENC_THREAD_POOL_MAX_THREAD_COUNT]; + +static EncryptionThreadPoolWorkItem WorkItemQueue[TC_ENC_THREAD_POOL_QUEUE_SIZE]; + +static volatile int EnqueuePosition; +static volatile int DequeuePosition; + +static TC_MUTEX EnqueueMutex; +static TC_MUTEX DequeueMutex; + +static TC_EVENT WorkItemReadyEvent; +static TC_EVENT WorkItemCompletedEvent; + + +static WorkItemState GetWorkItemState (EncryptionThreadPoolWorkItem *workItem) +{ + return InterlockedExchangeAdd ((LONG *) &workItem->State, 0); +} + + +static void SetWorkItemState (EncryptionThreadPoolWorkItem *workItem, WorkItemState newState) +{ + InterlockedExchange ((LONG *) &workItem->State, (LONG) newState); +} + + +static TC_THREAD_PROC EncryptionThreadProc (void *threadArg) +{ + EncryptionThreadPoolWorkItem *workItem; + + while (!StopPending) + { + TC_ACQUIRE_MUTEX (&DequeueMutex); + + workItem = &WorkItemQueue[DequeuePosition++]; + + if (DequeuePosition >= TC_ENC_THREAD_POOL_QUEUE_SIZE) + DequeuePosition = 0; + + while (!StopPending && GetWorkItemState (workItem) != WorkItemReady) + { + TC_WAIT_EVENT (WorkItemReadyEvent); + } + + SetWorkItemState (workItem, WorkItemBusy); + + TC_RELEASE_MUTEX (&DequeueMutex); + + if (StopPending) + break; + + switch (workItem->Type) + { + case DecryptDataUnitsWork: + DecryptDataUnitsCurrentThread (workItem->Encryption.Data, &workItem->Encryption.StartUnitNo, workItem->Encryption.UnitCount, workItem->Encryption.CryptoInfo); + break; + + case EncryptDataUnitsWork: + EncryptDataUnitsCurrentThread (workItem->Encryption.Data, &workItem->Encryption.StartUnitNo, workItem->Encryption.UnitCount, workItem->Encryption.CryptoInfo); + break; + + case DeriveKeyWork: + switch (workItem->KeyDerivation.Pkcs5Prf) + { + case RIPEMD160: + derive_key_ripemd160 (workItem->KeyDerivation.Password, workItem->KeyDerivation.PasswordLength, workItem->KeyDerivation.Salt, PKCS5_SALT_SIZE, + workItem->KeyDerivation.IterationCount, workItem->KeyDerivation.DerivedKey, GetMaxPkcs5OutSize()); + break; + + case SHA512: + derive_key_sha512 (workItem->KeyDerivation.Password, workItem->KeyDerivation.PasswordLength, workItem->KeyDerivation.Salt, PKCS5_SALT_SIZE, + workItem->KeyDerivation.IterationCount, workItem->KeyDerivation.DerivedKey, GetMaxPkcs5OutSize()); + break; + + case WHIRLPOOL: + derive_key_whirlpool (workItem->KeyDerivation.Password, workItem->KeyDerivation.PasswordLength, workItem->KeyDerivation.Salt, PKCS5_SALT_SIZE, + workItem->KeyDerivation.IterationCount, workItem->KeyDerivation.DerivedKey, GetMaxPkcs5OutSize()); + break; + + case SHA256: + derive_key_sha256 (workItem->KeyDerivation.Password, workItem->KeyDerivation.PasswordLength, workItem->KeyDerivation.Salt, PKCS5_SALT_SIZE, + workItem->KeyDerivation.IterationCount, workItem->KeyDerivation.DerivedKey, GetMaxPkcs5OutSize()); + break; + + default: + TC_THROW_FATAL_EXCEPTION; + } + + InterlockedExchange (workItem->KeyDerivation.CompletionFlag, TRUE); + TC_SET_EVENT (*workItem->KeyDerivation.CompletionEvent); + + if (InterlockedDecrement (workItem->KeyDerivation.OutstandingWorkItemCount) == 0) + TC_SET_EVENT (*workItem->KeyDerivation.NoOutstandingWorkItemEvent); + + SetWorkItemState (workItem, WorkItemFree); + TC_SET_EVENT (WorkItemCompletedEvent); + continue; + + default: + TC_THROW_FATAL_EXCEPTION; + } + + if (workItem != workItem->FirstFragment) + { + SetWorkItemState (workItem, WorkItemFree); + TC_SET_EVENT (WorkItemCompletedEvent); + } + + if (InterlockedDecrement (&workItem->FirstFragment->OutstandingFragmentCount) == 0) + TC_SET_EVENT (workItem->FirstFragment->ItemCompletedEvent); + } + +#ifdef DEVICE_DRIVER + PsTerminateSystemThread (STATUS_SUCCESS); +#else + _endthreadex (0); + return 0; +#endif +} + + +BOOL EncryptionThreadPoolStart (size_t encryptionFreeCpuCount) +{ + size_t cpuCount, i; + + if (ThreadPoolRunning) + return TRUE; + +#ifdef DEVICE_DRIVER + cpuCount = GetCpuCount(); +#else + { + SYSTEM_INFO sysInfo; + GetSystemInfo (&sysInfo); + cpuCount = sysInfo.dwNumberOfProcessors; + } +#endif + + if (cpuCount > encryptionFreeCpuCount) + cpuCount -= encryptionFreeCpuCount; + + if (cpuCount < 2) + return TRUE; + + if (cpuCount > TC_ENC_THREAD_POOL_MAX_THREAD_COUNT) + cpuCount = TC_ENC_THREAD_POOL_MAX_THREAD_COUNT; + + StopPending = FALSE; + DequeuePosition = 0; + EnqueuePosition = 0; + +#ifdef DEVICE_DRIVER + KeInitializeEvent (&WorkItemReadyEvent, SynchronizationEvent, FALSE); + KeInitializeEvent (&WorkItemCompletedEvent, SynchronizationEvent, FALSE); +#else + WorkItemReadyEvent = CreateEvent (NULL, FALSE, FALSE, NULL); + if (!WorkItemReadyEvent) + return FALSE; + + WorkItemCompletedEvent = CreateEvent (NULL, FALSE, FALSE, NULL); + if (!WorkItemCompletedEvent) + return FALSE; +#endif + +#ifdef DEVICE_DRIVER + ExInitializeFastMutex (&DequeueMutex); + ExInitializeFastMutex (&EnqueueMutex); +#else + DequeueMutex = CreateMutex (NULL, FALSE, NULL); + if (!DequeueMutex) + return FALSE; + + EnqueueMutex = CreateMutex (NULL, FALSE, NULL); + if (!EnqueueMutex) + return FALSE; +#endif + + memset (WorkItemQueue, 0, sizeof (WorkItemQueue)); + + for (i = 0; i < sizeof (WorkItemQueue) / sizeof (WorkItemQueue[0]); ++i) + { + WorkItemQueue[i].State = WorkItemFree; + +#ifdef DEVICE_DRIVER + KeInitializeEvent (&WorkItemQueue[i].ItemCompletedEvent, SynchronizationEvent, FALSE); +#else + WorkItemQueue[i].ItemCompletedEvent = CreateEvent (NULL, FALSE, FALSE, NULL); + if (!WorkItemQueue[i].ItemCompletedEvent) + { + EncryptionThreadPoolStop(); + return FALSE; + } +#endif + } + + for (ThreadCount = 0; ThreadCount < cpuCount; ++ThreadCount) + { +#ifdef DEVICE_DRIVER + if (!NT_SUCCESS (TCStartThread (EncryptionThreadProc, NULL, &ThreadHandles[ThreadCount]))) +#else + if (!(ThreadHandles[ThreadCount] = (HANDLE) _beginthreadex (NULL, 0, EncryptionThreadProc, NULL, 0, NULL))) +#endif + { + EncryptionThreadPoolStop(); + return FALSE; + } + } + + ThreadPoolRunning = TRUE; + return TRUE; +} + + +void EncryptionThreadPoolStop () +{ + size_t i; + + if (!ThreadPoolRunning) + return; + + StopPending = TRUE; + TC_SET_EVENT (WorkItemReadyEvent); + + for (i = 0; i < ThreadCount; ++i) + { +#ifdef DEVICE_DRIVER + TCStopThread (ThreadHandles[i], &WorkItemReadyEvent); +#else + TC_WAIT_EVENT (ThreadHandles[i]); +#endif + } + + ThreadCount = 0; + +#ifndef DEVICE_DRIVER + CloseHandle (DequeueMutex); + CloseHandle (EnqueueMutex); + + CloseHandle (WorkItemReadyEvent); + CloseHandle (WorkItemCompletedEvent); + + for (i = 0; i < sizeof (WorkItemQueue) / sizeof (WorkItemQueue[0]); ++i) + { + if (WorkItemQueue[i].ItemCompletedEvent) + CloseHandle (WorkItemQueue[i].ItemCompletedEvent); + } +#endif + + ThreadPoolRunning = FALSE; +} + + +void EncryptionThreadPoolBeginKeyDerivation (TC_EVENT *completionEvent, TC_EVENT *noOutstandingWorkItemEvent, LONG *completionFlag, LONG *outstandingWorkItemCount, int pkcs5Prf, char *password, int passwordLength, char *salt, int iterationCount, char *derivedKey) +{ + EncryptionThreadPoolWorkItem *workItem; + + if (!ThreadPoolRunning) + TC_THROW_FATAL_EXCEPTION; + + TC_ACQUIRE_MUTEX (&EnqueueMutex); + + workItem = &WorkItemQueue[EnqueuePosition++]; + if (EnqueuePosition >= TC_ENC_THREAD_POOL_QUEUE_SIZE) + EnqueuePosition = 0; + + while (GetWorkItemState (workItem) != WorkItemFree) + { + TC_WAIT_EVENT (WorkItemCompletedEvent); + } + + workItem->Type = DeriveKeyWork; + workItem->KeyDerivation.CompletionEvent = completionEvent; + workItem->KeyDerivation.CompletionFlag = completionFlag; + workItem->KeyDerivation.DerivedKey = derivedKey; + workItem->KeyDerivation.IterationCount = iterationCount; + workItem->KeyDerivation.NoOutstandingWorkItemEvent = noOutstandingWorkItemEvent; + workItem->KeyDerivation.OutstandingWorkItemCount = outstandingWorkItemCount; + workItem->KeyDerivation.Password = password; + workItem->KeyDerivation.PasswordLength = passwordLength; + workItem->KeyDerivation.Pkcs5Prf = pkcs5Prf; + workItem->KeyDerivation.Salt = salt; + + InterlockedIncrement (outstandingWorkItemCount); + TC_CLEAR_EVENT (*noOutstandingWorkItemEvent); + + SetWorkItemState (workItem, WorkItemReady); + TC_SET_EVENT (WorkItemReadyEvent); + TC_RELEASE_MUTEX (&EnqueueMutex); +} + + +void EncryptionThreadPoolDoWork (EncryptionThreadPoolWorkType type, byte *data, const UINT64_STRUCT *startUnitNo, uint32 unitCount, PCRYPTO_INFO cryptoInfo) +{ + uint32 fragmentCount; + uint32 unitsPerFragment; + uint32 remainder; + + byte *fragmentData; + uint64 fragmentStartUnitNo; + + EncryptionThreadPoolWorkItem *workItem; + EncryptionThreadPoolWorkItem *firstFragmentWorkItem; + + if (unitCount == 0) + return; + + if (!ThreadPoolRunning || unitCount == 1) + { + switch (type) + { + case DecryptDataUnitsWork: + DecryptDataUnitsCurrentThread (data, startUnitNo, unitCount, cryptoInfo); + break; + + case EncryptDataUnitsWork: + EncryptDataUnitsCurrentThread (data, startUnitNo, unitCount, cryptoInfo); + break; + + default: + TC_THROW_FATAL_EXCEPTION; + } + + return; + } + + if (unitCount <= ThreadCount) + { + fragmentCount = unitCount; + unitsPerFragment = 1; + remainder = 0; + } + else + { + /* Note that it is not efficient to divide the data into fragments smaller than a few hundred bytes. + The reason is that the overhead associated with thread handling would in most cases make a multi-threaded + process actually slower than a single-threaded process. */ + + fragmentCount = ThreadCount; + unitsPerFragment = unitCount / ThreadCount; + remainder = unitCount % ThreadCount; + + if (remainder > 0) + ++unitsPerFragment; + } + + fragmentData = data; + fragmentStartUnitNo = startUnitNo->Value; + + TC_ACQUIRE_MUTEX (&EnqueueMutex); + firstFragmentWorkItem = &WorkItemQueue[EnqueuePosition]; + + while (GetWorkItemState (firstFragmentWorkItem) != WorkItemFree) + { + TC_WAIT_EVENT (WorkItemCompletedEvent); + } + + firstFragmentWorkItem->OutstandingFragmentCount = fragmentCount; + + while (fragmentCount-- > 0) + { + workItem = &WorkItemQueue[EnqueuePosition++]; + if (EnqueuePosition >= TC_ENC_THREAD_POOL_QUEUE_SIZE) + EnqueuePosition = 0; + + while (GetWorkItemState (workItem) != WorkItemFree) + { + TC_WAIT_EVENT (WorkItemCompletedEvent); + } + + workItem->Type = type; + workItem->FirstFragment = firstFragmentWorkItem; + + workItem->Encryption.CryptoInfo = cryptoInfo; + workItem->Encryption.Data = fragmentData; + workItem->Encryption.UnitCount = unitsPerFragment; + workItem->Encryption.StartUnitNo.Value = fragmentStartUnitNo; + + fragmentData += unitsPerFragment * ENCRYPTION_DATA_UNIT_SIZE; + fragmentStartUnitNo += unitsPerFragment; + + if (remainder > 0 && --remainder == 0) + --unitsPerFragment; + + SetWorkItemState (workItem, WorkItemReady); + TC_SET_EVENT (WorkItemReadyEvent); + } + + TC_RELEASE_MUTEX (&EnqueueMutex); + + TC_WAIT_EVENT (firstFragmentWorkItem->ItemCompletedEvent); + SetWorkItemState (firstFragmentWorkItem, WorkItemFree); + TC_SET_EVENT (WorkItemCompletedEvent); +} + + +size_t GetEncryptionThreadCount () +{ + return ThreadPoolRunning ? ThreadCount : 0; +} + + +size_t GetMaxEncryptionThreadCount () +{ + return TC_ENC_THREAD_POOL_MAX_THREAD_COUNT; +} + + +BOOL IsEncryptionThreadPoolRunning () +{ + return ThreadPoolRunning; +} diff --git a/src/Common/EncryptionThreadPool.h b/src/Common/EncryptionThreadPool.h index f34f7493..5ca131f5 100644 --- a/src/Common/EncryptionThreadPool.h +++ b/src/Common/EncryptionThreadPool.h @@ -1,42 +1,42 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_ENCRYPTION_THREAD_POOL -#define TC_HEADER_ENCRYPTION_THREAD_POOL - -#include "Tcdefs.h" -#include "Crypto.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum -{ - EncryptDataUnitsWork, - DecryptDataUnitsWork, - DeriveKeyWork -} EncryptionThreadPoolWorkType; - -void EncryptionThreadPoolBeginKeyDerivation (TC_EVENT *completionEvent, TC_EVENT *noOutstandingWorkItemEvent, LONG *completionFlag, LONG *outstandingWorkItemCount, int pkcs5Prf, char *password, int passwordLength, char *salt, int iterationCount, char *derivedKey); -void EncryptionThreadPoolDoWork (EncryptionThreadPoolWorkType type, byte *data, const UINT64_STRUCT *startUnitNo, uint32 unitCount, PCRYPTO_INFO cryptoInfo); -BOOL EncryptionThreadPoolStart (size_t encryptionFreeCpuCount); -void EncryptionThreadPoolStop (); -size_t GetEncryptionThreadCount (); -size_t GetMaxEncryptionThreadCount (); -BOOL IsEncryptionThreadPoolRunning (); - -#ifdef __cplusplus -} -#endif - -#endif // TC_HEADER_ENCRYPTION_THREAD_POOL +/* + 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. +*/ + +#ifndef TC_HEADER_ENCRYPTION_THREAD_POOL +#define TC_HEADER_ENCRYPTION_THREAD_POOL + +#include "Tcdefs.h" +#include "Crypto.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum +{ + EncryptDataUnitsWork, + DecryptDataUnitsWork, + DeriveKeyWork +} EncryptionThreadPoolWorkType; + +void EncryptionThreadPoolBeginKeyDerivation (TC_EVENT *completionEvent, TC_EVENT *noOutstandingWorkItemEvent, LONG *completionFlag, LONG *outstandingWorkItemCount, int pkcs5Prf, char *password, int passwordLength, char *salt, int iterationCount, char *derivedKey); +void EncryptionThreadPoolDoWork (EncryptionThreadPoolWorkType type, byte *data, const UINT64_STRUCT *startUnitNo, uint32 unitCount, PCRYPTO_INFO cryptoInfo); +BOOL EncryptionThreadPoolStart (size_t encryptionFreeCpuCount); +void EncryptionThreadPoolStop (); +size_t GetEncryptionThreadCount (); +size_t GetMaxEncryptionThreadCount (); +BOOL IsEncryptionThreadPoolRunning (); + +#ifdef __cplusplus +} +#endif + +#endif // TC_HEADER_ENCRYPTION_THREAD_POOL diff --git a/src/Common/Endian.c b/src/Common/Endian.c index 9cf16cce..44d96e40 100644 --- a/src/Common/Endian.c +++ b/src/Common/Endian.c @@ -1,59 +1,59 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" -#include "Common/Endian.h" - - -unsigned __int16 MirrorBytes16 (unsigned __int16 x) -{ - return (x << 8) | (x >> 8); -} - - -unsigned __int32 MirrorBytes32 (unsigned __int32 x) -{ - unsigned __int32 n = (unsigned __int8) x; - n <<= 8; n |= (unsigned __int8) (x >> 8); - n <<= 8; n |= (unsigned __int8) (x >> 16); - return (n << 8) | (unsigned __int8) (x >> 24); -} - -#ifndef TC_NO_COMPILER_INT64 -uint64 MirrorBytes64 (uint64 x) -{ - uint64 n = (unsigned __int8) x; - n <<= 8; n |= (unsigned __int8) (x >> 8); - n <<= 8; n |= (unsigned __int8) (x >> 16); - n <<= 8; n |= (unsigned __int8) (x >> 24); - n <<= 8; n |= (unsigned __int8) (x >> 32); - n <<= 8; n |= (unsigned __int8) (x >> 40); - n <<= 8; n |= (unsigned __int8) (x >> 48); - return (n << 8) | (unsigned __int8) (x >> 56); -} -#endif - -void -LongReverse (unsigned __int32 *buffer, unsigned byteCount) -{ - unsigned __int32 value; - - byteCount /= sizeof (unsigned __int32); - while (byteCount--) - { - value = *buffer; - value = ((value & 0xFF00FF00L) >> 8) | \ - ((value & 0x00FF00FFL) << 8); - *buffer++ = (value << 16) | (value >> 16); - } -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" +#include "Common/Endian.h" + + +unsigned __int16 MirrorBytes16 (unsigned __int16 x) +{ + return (x << 8) | (x >> 8); +} + + +unsigned __int32 MirrorBytes32 (unsigned __int32 x) +{ + unsigned __int32 n = (unsigned __int8) x; + n <<= 8; n |= (unsigned __int8) (x >> 8); + n <<= 8; n |= (unsigned __int8) (x >> 16); + return (n << 8) | (unsigned __int8) (x >> 24); +} + +#ifndef TC_NO_COMPILER_INT64 +uint64 MirrorBytes64 (uint64 x) +{ + uint64 n = (unsigned __int8) x; + n <<= 8; n |= (unsigned __int8) (x >> 8); + n <<= 8; n |= (unsigned __int8) (x >> 16); + n <<= 8; n |= (unsigned __int8) (x >> 24); + n <<= 8; n |= (unsigned __int8) (x >> 32); + n <<= 8; n |= (unsigned __int8) (x >> 40); + n <<= 8; n |= (unsigned __int8) (x >> 48); + return (n << 8) | (unsigned __int8) (x >> 56); +} +#endif + +void +LongReverse (unsigned __int32 *buffer, unsigned byteCount) +{ + unsigned __int32 value; + + byteCount /= sizeof (unsigned __int32); + while (byteCount--) + { + value = *buffer; + value = ((value & 0xFF00FF00L) >> 8) | \ + ((value & 0x00FF00FFL) << 8); + *buffer++ = (value << 16) | (value >> 16); + } +} diff --git a/src/Common/Endian.h b/src/Common/Endian.h index 0f35304e..7d97e5fb 100644 --- a/src/Common/Endian.h +++ b/src/Common/Endian.h @@ -1,149 +1,149 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifndef TC_ENDIAN_H -#define TC_ENDIAN_H - -#include "Common/Tcdefs.h" - -#if defined(__cplusplus) -extern "C" -{ -#endif - -#ifdef _WIN32 - -# ifndef LITTLE_ENDIAN -# define LITTLE_ENDIAN 1234 -# endif -# ifndef BYTE_ORDER -# define BYTE_ORDER LITTLE_ENDIAN -# endif - -#elif !defined(BYTE_ORDER) - -# ifdef TC_MACOSX -# include -# elif defined (TC_BSD) -# include -# elif defined (TC_SOLARIS) -# include -# define LITTLE_ENDIAN 1234 -# define BIG_ENDIAN 4321 -# ifdef _BIG_ENDIAN -# define BYTE_ORDER BIG_ENDIAN -# else -# define BYTE_ORDER LITTLE_ENDIAN -# endif -# else -# include -# endif - -# ifndef BYTE_ORDER -# ifndef __BYTE_ORDER -# error Byte order cannot be determined (BYTE_ORDER undefined) -# endif - -# define BYTE_ORDER __BYTE_ORDER -# endif - -# ifndef LITTLE_ENDIAN -# define LITTLE_ENDIAN __LITTLE_ENDIAN -# endif - -# ifndef BIG_ENDIAN -# define BIG_ENDIAN __BIG_ENDIAN -# endif - -#endif // !BYTE_ORDER - -/* Macros to read and write 16, 32, and 64-bit quantities in a portable manner. - These functions are implemented as macros rather than true functions as - the need to adjust the memory pointers makes them somewhat painful to call - in user code */ - -#define mputInt64(memPtr,data) \ - *memPtr++ = ( unsigned char ) ( ( ( data ) >> 56 ) & 0xFF ), \ - *memPtr++ = ( unsigned char ) ( ( ( data ) >> 48 ) & 0xFF ), \ - *memPtr++ = ( unsigned char ) ( ( ( data ) >> 40 ) & 0xFF ), \ - *memPtr++ = ( unsigned char ) ( ( ( data ) >> 32 ) & 0xFF ), \ - *memPtr++ = ( unsigned char ) ( ( ( data ) >> 24 ) & 0xFF ), \ - *memPtr++ = ( unsigned char ) ( ( ( data ) >> 16 ) & 0xFF ), \ - *memPtr++ = ( unsigned char ) ( ( ( data ) >> 8 ) & 0xFF ), \ - *memPtr++ = ( unsigned char ) ( ( data ) & 0xFF ) - -#define mputLong(memPtr,data) \ - *memPtr++ = ( unsigned char ) ( ( ( data ) >> 24 ) & 0xFF ), \ - *memPtr++ = ( unsigned char ) ( ( ( data ) >> 16 ) & 0xFF ), \ - *memPtr++ = ( unsigned char ) ( ( ( data ) >> 8 ) & 0xFF ), \ - *memPtr++ = ( unsigned char ) ( ( data ) & 0xFF ) - -#define mputWord(memPtr,data) \ - *memPtr++ = ( unsigned char ) ( ( ( data ) >> 8 ) & 0xFF ), \ - *memPtr++ = ( unsigned char ) ( ( data ) & 0xFF ) - -#define mputByte(memPtr,data) \ - *memPtr++ = ( unsigned char ) data - -#define mputBytes(memPtr,data,len) \ - memcpy (memPtr,data,len); \ - memPtr += len; - -#define mgetInt64(memPtr) \ - ( memPtr += 8, ( ( unsigned __int64 ) memPtr[ -8 ] << 56 ) | ( ( unsigned __int64 ) memPtr[ -7 ] << 48 ) | \ - ( ( unsigned __int64 ) memPtr[ -6 ] << 40 ) | ( ( unsigned __int64 ) memPtr[ -5 ] << 32 ) | \ - ( ( unsigned __int64 ) memPtr[ -4 ] << 24 ) | ( ( unsigned __int64 ) memPtr[ -3 ] << 16 ) | \ - ( ( unsigned __int64 ) memPtr[ -2 ] << 8 ) | ( unsigned __int64 ) memPtr[ -1 ] ) - -#define mgetLong(memPtr) \ - ( memPtr += 4, ( ( unsigned __int32 ) memPtr[ -4 ] << 24 ) | ( ( unsigned __int32 ) memPtr[ -3 ] << 16 ) | \ - ( ( unsigned __int32 ) memPtr[ -2 ] << 8 ) | ( unsigned __int32 ) memPtr[ -1 ] ) - -#define mgetWord(memPtr) \ - ( memPtr += 2, ((( unsigned short ) memPtr[ -2 ] << 8 ) | ( ( unsigned short ) memPtr[ -1 ] )) ) - -#define mgetByte(memPtr) \ - ( ( unsigned char ) *memPtr++ ) - -#if BYTE_ORDER == BIG_ENDIAN -# define LE16(x) MirrorBytes16(x) -# define LE32(x) MirrorBytes32(x) -# define LE64(x) MirrorBytes64(x) -#else -# define LE16(x) (x) -# define LE32(x) (x) -# define LE64(x) (x) -#endif - -#if BYTE_ORDER == LITTLE_ENDIAN -# define BE16(x) MirrorBytes16(x) -# define BE32(x) MirrorBytes32(x) -# define BE64(x) MirrorBytes64(x) -#else -# define BE16(x) (x) -# define BE32(x) (x) -# define BE64(x) (x) -#endif - -unsigned __int16 MirrorBytes16 (unsigned __int16 x); -unsigned __int32 MirrorBytes32 (unsigned __int32 x); -#ifndef TC_NO_COMPILER_INT64 -uint64 MirrorBytes64 (uint64 x); -#endif -void LongReverse ( unsigned __int32 *buffer , unsigned byteCount ); - -#if defined(__cplusplus) -} -#endif - -#endif /* TC_ENDIAN_H */ +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifndef TC_ENDIAN_H +#define TC_ENDIAN_H + +#include "Common/Tcdefs.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif + +#ifdef _WIN32 + +# ifndef LITTLE_ENDIAN +# define LITTLE_ENDIAN 1234 +# endif +# ifndef BYTE_ORDER +# define BYTE_ORDER LITTLE_ENDIAN +# endif + +#elif !defined(BYTE_ORDER) + +# ifdef TC_MACOSX +# include +# elif defined (TC_BSD) +# include +# elif defined (TC_SOLARIS) +# include +# define LITTLE_ENDIAN 1234 +# define BIG_ENDIAN 4321 +# ifdef _BIG_ENDIAN +# define BYTE_ORDER BIG_ENDIAN +# else +# define BYTE_ORDER LITTLE_ENDIAN +# endif +# else +# include +# endif + +# ifndef BYTE_ORDER +# ifndef __BYTE_ORDER +# error Byte order cannot be determined (BYTE_ORDER undefined) +# endif + +# define BYTE_ORDER __BYTE_ORDER +# endif + +# ifndef LITTLE_ENDIAN +# define LITTLE_ENDIAN __LITTLE_ENDIAN +# endif + +# ifndef BIG_ENDIAN +# define BIG_ENDIAN __BIG_ENDIAN +# endif + +#endif // !BYTE_ORDER + +/* Macros to read and write 16, 32, and 64-bit quantities in a portable manner. + These functions are implemented as macros rather than true functions as + the need to adjust the memory pointers makes them somewhat painful to call + in user code */ + +#define mputInt64(memPtr,data) \ + *memPtr++ = ( unsigned char ) ( ( ( data ) >> 56 ) & 0xFF ), \ + *memPtr++ = ( unsigned char ) ( ( ( data ) >> 48 ) & 0xFF ), \ + *memPtr++ = ( unsigned char ) ( ( ( data ) >> 40 ) & 0xFF ), \ + *memPtr++ = ( unsigned char ) ( ( ( data ) >> 32 ) & 0xFF ), \ + *memPtr++ = ( unsigned char ) ( ( ( data ) >> 24 ) & 0xFF ), \ + *memPtr++ = ( unsigned char ) ( ( ( data ) >> 16 ) & 0xFF ), \ + *memPtr++ = ( unsigned char ) ( ( ( data ) >> 8 ) & 0xFF ), \ + *memPtr++ = ( unsigned char ) ( ( data ) & 0xFF ) + +#define mputLong(memPtr,data) \ + *memPtr++ = ( unsigned char ) ( ( ( data ) >> 24 ) & 0xFF ), \ + *memPtr++ = ( unsigned char ) ( ( ( data ) >> 16 ) & 0xFF ), \ + *memPtr++ = ( unsigned char ) ( ( ( data ) >> 8 ) & 0xFF ), \ + *memPtr++ = ( unsigned char ) ( ( data ) & 0xFF ) + +#define mputWord(memPtr,data) \ + *memPtr++ = ( unsigned char ) ( ( ( data ) >> 8 ) & 0xFF ), \ + *memPtr++ = ( unsigned char ) ( ( data ) & 0xFF ) + +#define mputByte(memPtr,data) \ + *memPtr++ = ( unsigned char ) data + +#define mputBytes(memPtr,data,len) \ + memcpy (memPtr,data,len); \ + memPtr += len; + +#define mgetInt64(memPtr) \ + ( memPtr += 8, ( ( unsigned __int64 ) memPtr[ -8 ] << 56 ) | ( ( unsigned __int64 ) memPtr[ -7 ] << 48 ) | \ + ( ( unsigned __int64 ) memPtr[ -6 ] << 40 ) | ( ( unsigned __int64 ) memPtr[ -5 ] << 32 ) | \ + ( ( unsigned __int64 ) memPtr[ -4 ] << 24 ) | ( ( unsigned __int64 ) memPtr[ -3 ] << 16 ) | \ + ( ( unsigned __int64 ) memPtr[ -2 ] << 8 ) | ( unsigned __int64 ) memPtr[ -1 ] ) + +#define mgetLong(memPtr) \ + ( memPtr += 4, ( ( unsigned __int32 ) memPtr[ -4 ] << 24 ) | ( ( unsigned __int32 ) memPtr[ -3 ] << 16 ) | \ + ( ( unsigned __int32 ) memPtr[ -2 ] << 8 ) | ( unsigned __int32 ) memPtr[ -1 ] ) + +#define mgetWord(memPtr) \ + ( memPtr += 2, ((( unsigned short ) memPtr[ -2 ] << 8 ) | ( ( unsigned short ) memPtr[ -1 ] )) ) + +#define mgetByte(memPtr) \ + ( ( unsigned char ) *memPtr++ ) + +#if BYTE_ORDER == BIG_ENDIAN +# define LE16(x) MirrorBytes16(x) +# define LE32(x) MirrorBytes32(x) +# define LE64(x) MirrorBytes64(x) +#else +# define LE16(x) (x) +# define LE32(x) (x) +# define LE64(x) (x) +#endif + +#if BYTE_ORDER == LITTLE_ENDIAN +# define BE16(x) MirrorBytes16(x) +# define BE32(x) MirrorBytes32(x) +# define BE64(x) MirrorBytes64(x) +#else +# define BE16(x) (x) +# define BE32(x) (x) +# define BE64(x) (x) +#endif + +unsigned __int16 MirrorBytes16 (unsigned __int16 x); +unsigned __int32 MirrorBytes32 (unsigned __int32 x); +#ifndef TC_NO_COMPILER_INT64 +uint64 MirrorBytes64 (uint64 x); +#endif +void LongReverse ( unsigned __int32 *buffer , unsigned byteCount ); + +#if defined(__cplusplus) +} +#endif + +#endif /* TC_ENDIAN_H */ diff --git a/src/Common/Exception.h b/src/Common/Exception.h index f3635a1d..c4cd1b10 100644 --- a/src/Common/Exception.h +++ b/src/Common/Exception.h @@ -1,123 +1,123 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Common_Exception -#define TC_HEADER_Common_Exception - -#include "Platform/PlatformBase.h" -#include "Dlgcode.h" -#include "Language.h" -#include - -namespace VeraCrypt -{ - struct Exception - { - virtual void Show (HWND parent) const = 0; - }; - - struct SystemException : public Exception - { - SystemException (const char *srcPos) : ErrorCode (GetLastError()), SrcPos (srcPos) { } - - void Show (HWND parent) const - { - SetLastError (ErrorCode); - handleWin32Error (parent, SrcPos); - } - - DWORD ErrorCode; - const char *SrcPos; - }; - - struct ErrorException : public Exception - { - ErrorException (char *langId, const char *srcPos) : SrcPos (srcPos), ErrLangId (langId) { } - ErrorException (const wstring &errMsg, const char *srcPos) : SrcPos (srcPos), ErrLangId(NULL), ErrMsg (errMsg) { } - - void Show (HWND parent) const - { - if (ErrMsg.empty()) - ::ErrorDirect (AppendSrcPos (GetString (ErrLangId? ErrLangId : ""), SrcPos).c_str (), parent); - else - ::ErrorDirect (AppendSrcPos (ErrMsg.c_str(), SrcPos).c_str (), parent); - } - - const char *SrcPos; - char *ErrLangId; - wstring ErrMsg; - }; - - struct ParameterIncorrect : public Exception - { - ParameterIncorrect (const char *srcPos) : SrcPos (srcPos) { } - - void Show (HWND parent) const - { - string msgBody = "Parameter incorrect.\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n" + string (SrcPos) + ")"; - MessageBoxA (parent, msgBody.c_str(), "VeraCrypt", MB_ICONERROR | MB_SETFOREGROUND); - } - - const char *SrcPos; - }; - - struct RandInitFailed : public Exception - { - RandInitFailed (const char *srcPos, DWORD dwLastError) : SrcPos (srcPos), LastError (dwLastError) { } - - void Show (HWND parent) const - { - char szErrCode[16]; - StringCchPrintfA (szErrCode, ARRAYSIZE(szErrCode), "0x%.8X", LastError); - string msgBody = "The Random Generator initialization failed.\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n" + string (SrcPos) + "\nLast Error = " + string (szErrCode) + ")"; - MessageBoxA (parent, msgBody.c_str(), "VeraCrypt", MB_ICONERROR | MB_SETFOREGROUND); - } - - const char *SrcPos; - DWORD LastError; - }; - - struct CryptoApiFailed : public Exception - { - CryptoApiFailed (const char *srcPos, DWORD dwLastError) : SrcPos (srcPos), LastError (dwLastError) { } - - void Show (HWND parent) const - { - char szErrCode[16]; - StringCchPrintfA (szErrCode, ARRAYSIZE(szErrCode), "0x%.8X", LastError); - string msgBody = "Windows Crypto API failed.\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n" + string (SrcPos) + "\nLast Error = " + string (szErrCode) + ")"; - MessageBoxA (parent, msgBody.c_str(), "VeraCrypt", MB_ICONERROR | MB_SETFOREGROUND); - } - - const char *SrcPos; - DWORD LastError; - }; - - struct TimeOut : public Exception - { - TimeOut (const char *srcPos) : SrcPos (srcPos) { } - void Show (HWND parent) const { ErrorDirect (AppendSrcPos (L"Timeout", SrcPos).c_str (), parent); } - - const char *SrcPos; - }; - - struct UserAbort : public Exception - { - UserAbort (const char *srcPos) { } - void Show (HWND parent) const { } - }; -} - -#define throw_sys_if(condition) do { if (condition) throw SystemException( SRC_POS ); } while (false) - - -#endif // TC_HEADER_Common_Exception +/* + 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. +*/ + +#ifndef TC_HEADER_Common_Exception +#define TC_HEADER_Common_Exception + +#include "Platform/PlatformBase.h" +#include "Dlgcode.h" +#include "Language.h" +#include + +namespace VeraCrypt +{ + struct Exception + { + virtual void Show (HWND parent) const = 0; + }; + + struct SystemException : public Exception + { + SystemException (const char *srcPos) : ErrorCode (GetLastError()), SrcPos (srcPos) { } + + void Show (HWND parent) const + { + SetLastError (ErrorCode); + handleWin32Error (parent, SrcPos); + } + + DWORD ErrorCode; + const char *SrcPos; + }; + + struct ErrorException : public Exception + { + ErrorException (char *langId, const char *srcPos) : SrcPos (srcPos), ErrLangId (langId) { } + ErrorException (const wstring &errMsg, const char *srcPos) : SrcPos (srcPos), ErrLangId(NULL), ErrMsg (errMsg) { } + + void Show (HWND parent) const + { + if (ErrMsg.empty()) + ::ErrorDirect (AppendSrcPos (GetString (ErrLangId? ErrLangId : ""), SrcPos).c_str (), parent); + else + ::ErrorDirect (AppendSrcPos (ErrMsg.c_str(), SrcPos).c_str (), parent); + } + + const char *SrcPos; + char *ErrLangId; + wstring ErrMsg; + }; + + struct ParameterIncorrect : public Exception + { + ParameterIncorrect (const char *srcPos) : SrcPos (srcPos) { } + + void Show (HWND parent) const + { + string msgBody = "Parameter incorrect.\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n" + string (SrcPos) + ")"; + MessageBoxA (parent, msgBody.c_str(), "VeraCrypt", MB_ICONERROR | MB_SETFOREGROUND); + } + + const char *SrcPos; + }; + + struct RandInitFailed : public Exception + { + RandInitFailed (const char *srcPos, DWORD dwLastError) : SrcPos (srcPos), LastError (dwLastError) { } + + void Show (HWND parent) const + { + char szErrCode[16]; + StringCchPrintfA (szErrCode, ARRAYSIZE(szErrCode), "0x%.8X", LastError); + string msgBody = "The Random Generator initialization failed.\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n" + string (SrcPos) + "\nLast Error = " + string (szErrCode) + ")"; + MessageBoxA (parent, msgBody.c_str(), "VeraCrypt", MB_ICONERROR | MB_SETFOREGROUND); + } + + const char *SrcPos; + DWORD LastError; + }; + + struct CryptoApiFailed : public Exception + { + CryptoApiFailed (const char *srcPos, DWORD dwLastError) : SrcPos (srcPos), LastError (dwLastError) { } + + void Show (HWND parent) const + { + char szErrCode[16]; + StringCchPrintfA (szErrCode, ARRAYSIZE(szErrCode), "0x%.8X", LastError); + string msgBody = "Windows Crypto API failed.\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n" + string (SrcPos) + "\nLast Error = " + string (szErrCode) + ")"; + MessageBoxA (parent, msgBody.c_str(), "VeraCrypt", MB_ICONERROR | MB_SETFOREGROUND); + } + + const char *SrcPos; + DWORD LastError; + }; + + struct TimeOut : public Exception + { + TimeOut (const char *srcPos) : SrcPos (srcPos) { } + void Show (HWND parent) const { ErrorDirect (AppendSrcPos (L"Timeout", SrcPos).c_str (), parent); } + + const char *SrcPos; + }; + + struct UserAbort : public Exception + { + UserAbort (const char *srcPos) { } + void Show (HWND parent) const { } + }; +} + +#define throw_sys_if(condition) do { if (condition) throw SystemException( SRC_POS ); } while (false) + + +#endif // TC_HEADER_Common_Exception diff --git a/src/Common/Fat.c b/src/Common/Fat.c index 2a34674a..fadb80b1 100644 --- a/src/Common/Fat.c +++ b/src/Common/Fat.c @@ -1,449 +1,449 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 -#include -#include - -#include "Tcdefs.h" - -#include "Crypto.h" -#include "Common/Endian.h" -#include "Format.h" -#include "Fat.h" -#include "Progress.h" -#include "Random.h" -#include "Volumes.h" - -void -GetFatParams (fatparams * ft) -{ - uint64 volumeSize = (uint64) ft->num_sectors * ft->sector_size; - unsigned int fatsecs; - - if(ft->cluster_size == 0) // 'Default' cluster size - { - uint32 clusterSize; - - // Determine optimal cluster size to minimize FAT size (mounting delay), maximize number of files, keep 4 KB alignment, etc. - if (volumeSize >= 2 * BYTES_PER_TB) - clusterSize = 256 * BYTES_PER_KB; - else if (volumeSize >= 512 * BYTES_PER_GB) - clusterSize = 128 * BYTES_PER_KB; - else if (volumeSize >= 128 * BYTES_PER_GB) - clusterSize = 64 * BYTES_PER_KB; - else if (volumeSize >= 64 * BYTES_PER_GB) - clusterSize = 32 * BYTES_PER_KB; - else if (volumeSize >= 32 * BYTES_PER_GB) - clusterSize = 16 * BYTES_PER_KB; - else if (volumeSize >= 16 * BYTES_PER_GB) - clusterSize = 8 * BYTES_PER_KB; - else if (volumeSize >= 512 * BYTES_PER_MB) - clusterSize = 4 * BYTES_PER_KB; - else if (volumeSize >= 256 * BYTES_PER_MB) - clusterSize = 2 * BYTES_PER_KB; - else if (volumeSize >= 1 * BYTES_PER_MB) - clusterSize = 1 * BYTES_PER_KB; - else - clusterSize = 512; - - ft->cluster_size = clusterSize / ft->sector_size; - - if (ft->cluster_size == 0) - ft->cluster_size = 1; - - if (((unsigned __int64) ft->cluster_size * ft->sector_size) > TC_MAX_FAT_CLUSTER_SIZE) - ft->cluster_size = TC_MAX_FAT_CLUSTER_SIZE / ft->sector_size; - - if (ft->cluster_size > 128) - ft->cluster_size = 128; - } - - if (volumeSize <= TC_MAX_FAT_CLUSTER_SIZE * 4) - ft->cluster_size = 1; - - // Geometry always set to SECTORS/1/1 - ft->secs_track = 1; - ft->heads = 1; - - ft->dir_entries = 512; - ft->fats = 2; - ft->media = 0xf8; - ft->hidden = 0; - - ft->size_root_dir = ft->dir_entries * 32; - - // FAT12 - ft->size_fat = 12; - ft->reserved = 2; - fatsecs = ft->num_sectors - (ft->size_root_dir + ft->sector_size - 1) / ft->sector_size - ft->reserved; - ft->cluster_count = (int) (((unsigned __int64) fatsecs * ft->sector_size) / ((unsigned __int64) ft->cluster_size * ft->sector_size)); - ft->fat_length = (((ft->cluster_count * 3 + 1) >> 1) + ft->sector_size - 1) / ft->sector_size; - - if (ft->cluster_count >= 4085) // FAT16 - { - ft->size_fat = 16; - ft->reserved = 2; - fatsecs = ft->num_sectors - (ft->size_root_dir + ft->sector_size - 1) / ft->sector_size - ft->reserved; - ft->cluster_count = (int) (((__int64) fatsecs * ft->sector_size) / (ft->cluster_size * ft->sector_size)); - ft->fat_length = (ft->cluster_count * 2 + ft->sector_size - 1) / ft->sector_size; - } - - if(ft->cluster_count >= 65525) // FAT32 - { - ft->size_fat = 32; - ft->reserved = 32 - 1; - - do - { - ft->reserved++; - - fatsecs = ft->num_sectors - ft->reserved; - ft->size_root_dir = ft->cluster_size * ft->sector_size; - ft->cluster_count = (int) (((unsigned __int64) fatsecs * ft->sector_size) / (ft->cluster_size * ft->sector_size)); - ft->fat_length = (ft->cluster_count * 4 + ft->sector_size - 1) / ft->sector_size; - - // Align data area on TC_MAX_VOLUME_SECTOR_SIZE - - } while (ft->sector_size == TC_SECTOR_SIZE_LEGACY - && (ft->reserved * ft->sector_size + ft->fat_length * ft->fats * ft->sector_size) % TC_MAX_VOLUME_SECTOR_SIZE != 0); - } - - ft->cluster_count -= ft->fat_length * ft->fats / ft->cluster_size; - - if (ft->num_sectors >= 65536 || ft->size_fat == 32) - { - ft->sectors = 0; - ft->total_sect = ft->num_sectors; - } - else - { - ft->sectors = (uint16) ft->num_sectors; - ft->total_sect = 0; - } -} - -void -PutBoot (fatparams * ft, unsigned char *boot) -{ - int cnt = 0; - - boot[cnt++] = 0xeb; /* boot jump */ - boot[cnt++] = 0x3c; - boot[cnt++] = 0x90; - memcpy (boot + cnt, "MSDOS5.0", 8); /* system id */ - cnt += 8; - *(__int16 *)(boot + cnt) = LE16(ft->sector_size); /* bytes per sector */ - cnt += 2; - boot[cnt++] = (__int8) ft->cluster_size; /* sectors per cluster */ - *(__int16 *)(boot + cnt) = LE16(ft->reserved); /* reserved sectors */ - cnt += 2; - boot[cnt++] = (__int8) ft->fats; /* 2 fats */ - - if(ft->size_fat == 32) - { - boot[cnt++] = 0x00; - boot[cnt++] = 0x00; - } - else - { - *(__int16 *)(boot + cnt) = LE16(ft->dir_entries); /* 512 root entries */ - cnt += 2; - } - - *(__int16 *)(boot + cnt) = LE16(ft->sectors); /* # sectors */ - cnt += 2; - boot[cnt++] = (__int8) ft->media; /* media byte */ - - if(ft->size_fat == 32) - { - boot[cnt++] = 0x00; - boot[cnt++] = 0x00; - } - else - { - *(__int16 *)(boot + cnt) = LE16((uint16) ft->fat_length); /* fat size */ - cnt += 2; - } - - *(__int16 *)(boot + cnt) = LE16(ft->secs_track); /* # sectors per track */ - cnt += 2; - *(__int16 *)(boot + cnt) = LE16(ft->heads); /* # heads */ - cnt += 2; - *(__int32 *)(boot + cnt) = LE32(ft->hidden); /* # hidden sectors */ - cnt += 4; - *(__int32 *)(boot + cnt) = LE32(ft->total_sect); /* # huge sectors */ - cnt += 4; - - if(ft->size_fat == 32) - { - *(__int32 *)(boot + cnt) = LE32(ft->fat_length); cnt += 4; /* fat size 32 */ - boot[cnt++] = 0x00; /* ExtFlags */ - boot[cnt++] = 0x00; - boot[cnt++] = 0x00; /* FSVer */ - boot[cnt++] = 0x00; - boot[cnt++] = 0x02; /* RootClus */ - boot[cnt++] = 0x00; - boot[cnt++] = 0x00; - boot[cnt++] = 0x00; - boot[cnt++] = 0x01; /* FSInfo */ - boot[cnt++] = 0x00; - boot[cnt++] = 0x06; /* BkBootSec */ - boot[cnt++] = 0x00; - memset(boot+cnt, 0, 12); cnt+=12; /* Reserved */ - } - - boot[cnt++] = 0x00; /* drive number */ // FIXED 80 > 00 - boot[cnt++] = 0x00; /* reserved */ - boot[cnt++] = 0x29; /* boot sig */ - - memcpy (boot + cnt, ft->volume_id, 4); /* vol id */ - cnt += 4; - - memcpy (boot + cnt, ft->volume_name, 11); /* vol title */ - cnt += 11; - - switch(ft->size_fat) /* filesystem type */ - { - case 12: memcpy (boot + cnt, "FAT12 ", 8); break; - case 16: memcpy (boot + cnt, "FAT16 ", 8); break; - case 32: memcpy (boot + cnt, "FAT32 ", 8); break; - } - cnt += 8; - - memset (boot + cnt, 0, ft->size_fat==32 ? 420:448); /* boot code */ - cnt += ft->size_fat==32 ? 420:448; - boot[cnt++] = 0x55; - boot[cnt++] = 0xaa; /* boot sig */ -} - - -/* FAT32 FSInfo */ -static void PutFSInfo (unsigned char *sector, fatparams *ft) -{ - memset (sector, 0, ft->sector_size); - sector[3]=0x41; /* LeadSig */ - sector[2]=0x61; - sector[1]=0x52; - sector[0]=0x52; - sector[484+3]=0x61; /* StrucSig */ - sector[484+2]=0x41; - sector[484+1]=0x72; - sector[484+0]=0x72; - - // Free cluster count - *(uint32 *)(sector + 488) = LE32 (ft->cluster_count - ft->size_root_dir / ft->sector_size / ft->cluster_size); - - // Next free cluster - *(uint32 *)(sector + 492) = LE32 (2); - - sector[508+3]=0xaa; /* TrailSig */ - sector[508+2]=0x55; - sector[508+1]=0x00; - sector[508+0]=0x00; -} - - -int -FormatFat (void* hwndDlgPtr, unsigned __int64 startSector, fatparams * ft, void * dev, PCRYPTO_INFO cryptoInfo, BOOL quickFormat) -{ - int write_buf_cnt = 0; - char sector[TC_MAX_VOLUME_SECTOR_SIZE], *write_buf; - unsigned __int64 nSecNo = startSector; - int x, n; - int retVal; - char temporaryKey[MASTER_KEYDATA_SIZE]; - HWND hwndDlg = (HWND) hwndDlgPtr; - - LARGE_INTEGER startOffset; - LARGE_INTEGER newOffset; - - // Seek to start sector - startOffset.QuadPart = startSector * ft->sector_size; - if (!SetFilePointerEx ((HANDLE) dev, startOffset, &newOffset, FILE_BEGIN) - || newOffset.QuadPart != startOffset.QuadPart) - { - return ERR_VOL_SEEKING; - } - - /* Write the data area */ - - write_buf = (char *)TCalloc (FormatWriteBufferSize); - if (!write_buf) - return ERR_OUTOFMEMORY; - - memset (sector, 0, ft->sector_size); - - if (!RandgetBytes (hwndDlg, ft->volume_id, sizeof (ft->volume_id), FALSE)) - goto fail; - - PutBoot (ft, (unsigned char *) sector); - if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, - cryptoInfo) == FALSE) - goto fail; - - /* fat32 boot area */ - if (ft->size_fat == 32) - { - /* fsinfo */ - PutFSInfo((unsigned char *) sector, ft); - if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, - cryptoInfo) == FALSE) - goto fail; - - /* reserved */ - while (nSecNo - startSector < 6) - { - memset (sector, 0, ft->sector_size); - sector[508+3]=0xaa; /* TrailSig */ - sector[508+2]=0x55; - if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, - cryptoInfo) == FALSE) - goto fail; - } - - /* bootsector backup */ - memset (sector, 0, ft->sector_size); - PutBoot (ft, (unsigned char *) sector); - if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, - cryptoInfo) == FALSE) - goto fail; - - PutFSInfo((unsigned char *) sector, ft); - if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, - cryptoInfo) == FALSE) - goto fail; - } - - /* reserved */ - while (nSecNo - startSector < (unsigned int)ft->reserved) - { - memset (sector, 0, ft->sector_size); - if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, - cryptoInfo) == FALSE) - goto fail; - } - - /* write fat */ - for (x = 1; x <= ft->fats; x++) - { - for (n = 0; n < ft->fat_length; n++) - { - memset (sector, 0, ft->sector_size); - - if (n == 0) - { - unsigned char fat_sig[12]; - if (ft->size_fat == 32) - { - fat_sig[0] = (unsigned char) ft->media; - fat_sig[1] = fat_sig[2] = 0xff; - fat_sig[3] = 0x0f; - fat_sig[4] = fat_sig[5] = fat_sig[6] = 0xff; - fat_sig[7] = 0x0f; - fat_sig[8] = fat_sig[9] = fat_sig[10] = 0xff; - fat_sig[11] = 0x0f; - memcpy (sector, fat_sig, 12); - } - else if (ft->size_fat == 16) - { - fat_sig[0] = (unsigned char) ft->media; - fat_sig[1] = 0xff; - fat_sig[2] = 0xff; - fat_sig[3] = 0xff; - memcpy (sector, fat_sig, 4); - } - else if (ft->size_fat == 12) - { - fat_sig[0] = (unsigned char) ft->media; - fat_sig[1] = 0xff; - fat_sig[2] = 0xff; - fat_sig[3] = 0x00; - memcpy (sector, fat_sig, 4); - } - } - - if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, - cryptoInfo) == FALSE) - goto fail; - } - } - - - /* write rootdir */ - for (x = 0; x < ft->size_root_dir / ft->sector_size; x++) - { - memset (sector, 0, ft->sector_size); - if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, - cryptoInfo) == FALSE) - goto fail; - - } - - /* Fill the rest of the data area with random data */ - - if(!quickFormat) - { - if (!FlushFormatWriteBuffer (dev, write_buf, &write_buf_cnt, &nSecNo, cryptoInfo)) - goto fail; - - /* Generate a random temporary key set to be used for "dummy" encryption that will fill - the free disk space (data area) with random data. This is necessary for plausible - deniability of hidden volumes (and also reduces the amount of predictable plaintext - within the volume). */ - - // Temporary master key - if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (cryptoInfo->ea), FALSE)) - goto fail; - - // Temporary secondary key (XTS mode) - if (!RandgetBytes (hwndDlg, cryptoInfo->k2, sizeof cryptoInfo->k2, FALSE)) - goto fail; - - retVal = EAInit (cryptoInfo->ea, temporaryKey, cryptoInfo->ks); - if (retVal != ERR_SUCCESS) - { - burn (temporaryKey, sizeof(temporaryKey)); - return retVal; - } - if (!EAInitMode (cryptoInfo)) - { - burn (temporaryKey, sizeof(temporaryKey)); - return ERR_MODE_INIT_FAILED; - } - - x = ft->num_sectors - ft->reserved - ft->size_root_dir / ft->sector_size - ft->fat_length * 2; - while (x--) - { - if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, - cryptoInfo) == FALSE) - goto fail; - } - UpdateProgressBar (nSecNo * ft->sector_size); - } - else - UpdateProgressBar ((uint64) ft->num_sectors * ft->sector_size); - - if (!FlushFormatWriteBuffer (dev, write_buf, &write_buf_cnt, &nSecNo, cryptoInfo)) - goto fail; - - TCfree (write_buf); - burn (temporaryKey, sizeof(temporaryKey)); - return 0; - -fail: - - TCfree (write_buf); - burn (temporaryKey, sizeof(temporaryKey)); - return ERR_OS_ERROR; -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 +#include +#include + +#include "Tcdefs.h" + +#include "Crypto.h" +#include "Common/Endian.h" +#include "Format.h" +#include "Fat.h" +#include "Progress.h" +#include "Random.h" +#include "Volumes.h" + +void +GetFatParams (fatparams * ft) +{ + uint64 volumeSize = (uint64) ft->num_sectors * ft->sector_size; + unsigned int fatsecs; + + if(ft->cluster_size == 0) // 'Default' cluster size + { + uint32 clusterSize; + + // Determine optimal cluster size to minimize FAT size (mounting delay), maximize number of files, keep 4 KB alignment, etc. + if (volumeSize >= 2 * BYTES_PER_TB) + clusterSize = 256 * BYTES_PER_KB; + else if (volumeSize >= 512 * BYTES_PER_GB) + clusterSize = 128 * BYTES_PER_KB; + else if (volumeSize >= 128 * BYTES_PER_GB) + clusterSize = 64 * BYTES_PER_KB; + else if (volumeSize >= 64 * BYTES_PER_GB) + clusterSize = 32 * BYTES_PER_KB; + else if (volumeSize >= 32 * BYTES_PER_GB) + clusterSize = 16 * BYTES_PER_KB; + else if (volumeSize >= 16 * BYTES_PER_GB) + clusterSize = 8 * BYTES_PER_KB; + else if (volumeSize >= 512 * BYTES_PER_MB) + clusterSize = 4 * BYTES_PER_KB; + else if (volumeSize >= 256 * BYTES_PER_MB) + clusterSize = 2 * BYTES_PER_KB; + else if (volumeSize >= 1 * BYTES_PER_MB) + clusterSize = 1 * BYTES_PER_KB; + else + clusterSize = 512; + + ft->cluster_size = clusterSize / ft->sector_size; + + if (ft->cluster_size == 0) + ft->cluster_size = 1; + + if (((unsigned __int64) ft->cluster_size * ft->sector_size) > TC_MAX_FAT_CLUSTER_SIZE) + ft->cluster_size = TC_MAX_FAT_CLUSTER_SIZE / ft->sector_size; + + if (ft->cluster_size > 128) + ft->cluster_size = 128; + } + + if (volumeSize <= TC_MAX_FAT_CLUSTER_SIZE * 4) + ft->cluster_size = 1; + + // Geometry always set to SECTORS/1/1 + ft->secs_track = 1; + ft->heads = 1; + + ft->dir_entries = 512; + ft->fats = 2; + ft->media = 0xf8; + ft->hidden = 0; + + ft->size_root_dir = ft->dir_entries * 32; + + // FAT12 + ft->size_fat = 12; + ft->reserved = 2; + fatsecs = ft->num_sectors - (ft->size_root_dir + ft->sector_size - 1) / ft->sector_size - ft->reserved; + ft->cluster_count = (int) (((unsigned __int64) fatsecs * ft->sector_size) / ((unsigned __int64) ft->cluster_size * ft->sector_size)); + ft->fat_length = (((ft->cluster_count * 3 + 1) >> 1) + ft->sector_size - 1) / ft->sector_size; + + if (ft->cluster_count >= 4085) // FAT16 + { + ft->size_fat = 16; + ft->reserved = 2; + fatsecs = ft->num_sectors - (ft->size_root_dir + ft->sector_size - 1) / ft->sector_size - ft->reserved; + ft->cluster_count = (int) (((__int64) fatsecs * ft->sector_size) / (ft->cluster_size * ft->sector_size)); + ft->fat_length = (ft->cluster_count * 2 + ft->sector_size - 1) / ft->sector_size; + } + + if(ft->cluster_count >= 65525) // FAT32 + { + ft->size_fat = 32; + ft->reserved = 32 - 1; + + do + { + ft->reserved++; + + fatsecs = ft->num_sectors - ft->reserved; + ft->size_root_dir = ft->cluster_size * ft->sector_size; + ft->cluster_count = (int) (((unsigned __int64) fatsecs * ft->sector_size) / (ft->cluster_size * ft->sector_size)); + ft->fat_length = (ft->cluster_count * 4 + ft->sector_size - 1) / ft->sector_size; + + // Align data area on TC_MAX_VOLUME_SECTOR_SIZE + + } while (ft->sector_size == TC_SECTOR_SIZE_LEGACY + && (ft->reserved * ft->sector_size + ft->fat_length * ft->fats * ft->sector_size) % TC_MAX_VOLUME_SECTOR_SIZE != 0); + } + + ft->cluster_count -= ft->fat_length * ft->fats / ft->cluster_size; + + if (ft->num_sectors >= 65536 || ft->size_fat == 32) + { + ft->sectors = 0; + ft->total_sect = ft->num_sectors; + } + else + { + ft->sectors = (uint16) ft->num_sectors; + ft->total_sect = 0; + } +} + +void +PutBoot (fatparams * ft, unsigned char *boot) +{ + int cnt = 0; + + boot[cnt++] = 0xeb; /* boot jump */ + boot[cnt++] = 0x3c; + boot[cnt++] = 0x90; + memcpy (boot + cnt, "MSDOS5.0", 8); /* system id */ + cnt += 8; + *(__int16 *)(boot + cnt) = LE16(ft->sector_size); /* bytes per sector */ + cnt += 2; + boot[cnt++] = (__int8) ft->cluster_size; /* sectors per cluster */ + *(__int16 *)(boot + cnt) = LE16(ft->reserved); /* reserved sectors */ + cnt += 2; + boot[cnt++] = (__int8) ft->fats; /* 2 fats */ + + if(ft->size_fat == 32) + { + boot[cnt++] = 0x00; + boot[cnt++] = 0x00; + } + else + { + *(__int16 *)(boot + cnt) = LE16(ft->dir_entries); /* 512 root entries */ + cnt += 2; + } + + *(__int16 *)(boot + cnt) = LE16(ft->sectors); /* # sectors */ + cnt += 2; + boot[cnt++] = (__int8) ft->media; /* media byte */ + + if(ft->size_fat == 32) + { + boot[cnt++] = 0x00; + boot[cnt++] = 0x00; + } + else + { + *(__int16 *)(boot + cnt) = LE16((uint16) ft->fat_length); /* fat size */ + cnt += 2; + } + + *(__int16 *)(boot + cnt) = LE16(ft->secs_track); /* # sectors per track */ + cnt += 2; + *(__int16 *)(boot + cnt) = LE16(ft->heads); /* # heads */ + cnt += 2; + *(__int32 *)(boot + cnt) = LE32(ft->hidden); /* # hidden sectors */ + cnt += 4; + *(__int32 *)(boot + cnt) = LE32(ft->total_sect); /* # huge sectors */ + cnt += 4; + + if(ft->size_fat == 32) + { + *(__int32 *)(boot + cnt) = LE32(ft->fat_length); cnt += 4; /* fat size 32 */ + boot[cnt++] = 0x00; /* ExtFlags */ + boot[cnt++] = 0x00; + boot[cnt++] = 0x00; /* FSVer */ + boot[cnt++] = 0x00; + boot[cnt++] = 0x02; /* RootClus */ + boot[cnt++] = 0x00; + boot[cnt++] = 0x00; + boot[cnt++] = 0x00; + boot[cnt++] = 0x01; /* FSInfo */ + boot[cnt++] = 0x00; + boot[cnt++] = 0x06; /* BkBootSec */ + boot[cnt++] = 0x00; + memset(boot+cnt, 0, 12); cnt+=12; /* Reserved */ + } + + boot[cnt++] = 0x00; /* drive number */ // FIXED 80 > 00 + boot[cnt++] = 0x00; /* reserved */ + boot[cnt++] = 0x29; /* boot sig */ + + memcpy (boot + cnt, ft->volume_id, 4); /* vol id */ + cnt += 4; + + memcpy (boot + cnt, ft->volume_name, 11); /* vol title */ + cnt += 11; + + switch(ft->size_fat) /* filesystem type */ + { + case 12: memcpy (boot + cnt, "FAT12 ", 8); break; + case 16: memcpy (boot + cnt, "FAT16 ", 8); break; + case 32: memcpy (boot + cnt, "FAT32 ", 8); break; + } + cnt += 8; + + memset (boot + cnt, 0, ft->size_fat==32 ? 420:448); /* boot code */ + cnt += ft->size_fat==32 ? 420:448; + boot[cnt++] = 0x55; + boot[cnt++] = 0xaa; /* boot sig */ +} + + +/* FAT32 FSInfo */ +static void PutFSInfo (unsigned char *sector, fatparams *ft) +{ + memset (sector, 0, ft->sector_size); + sector[3]=0x41; /* LeadSig */ + sector[2]=0x61; + sector[1]=0x52; + sector[0]=0x52; + sector[484+3]=0x61; /* StrucSig */ + sector[484+2]=0x41; + sector[484+1]=0x72; + sector[484+0]=0x72; + + // Free cluster count + *(uint32 *)(sector + 488) = LE32 (ft->cluster_count - ft->size_root_dir / ft->sector_size / ft->cluster_size); + + // Next free cluster + *(uint32 *)(sector + 492) = LE32 (2); + + sector[508+3]=0xaa; /* TrailSig */ + sector[508+2]=0x55; + sector[508+1]=0x00; + sector[508+0]=0x00; +} + + +int +FormatFat (void* hwndDlgPtr, unsigned __int64 startSector, fatparams * ft, void * dev, PCRYPTO_INFO cryptoInfo, BOOL quickFormat) +{ + int write_buf_cnt = 0; + char sector[TC_MAX_VOLUME_SECTOR_SIZE], *write_buf; + unsigned __int64 nSecNo = startSector; + int x, n; + int retVal; + char temporaryKey[MASTER_KEYDATA_SIZE]; + HWND hwndDlg = (HWND) hwndDlgPtr; + + LARGE_INTEGER startOffset; + LARGE_INTEGER newOffset; + + // Seek to start sector + startOffset.QuadPart = startSector * ft->sector_size; + if (!SetFilePointerEx ((HANDLE) dev, startOffset, &newOffset, FILE_BEGIN) + || newOffset.QuadPart != startOffset.QuadPart) + { + return ERR_VOL_SEEKING; + } + + /* Write the data area */ + + write_buf = (char *)TCalloc (FormatWriteBufferSize); + if (!write_buf) + return ERR_OUTOFMEMORY; + + memset (sector, 0, ft->sector_size); + + if (!RandgetBytes (hwndDlg, ft->volume_id, sizeof (ft->volume_id), FALSE)) + goto fail; + + PutBoot (ft, (unsigned char *) sector); + if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, + cryptoInfo) == FALSE) + goto fail; + + /* fat32 boot area */ + if (ft->size_fat == 32) + { + /* fsinfo */ + PutFSInfo((unsigned char *) sector, ft); + if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, + cryptoInfo) == FALSE) + goto fail; + + /* reserved */ + while (nSecNo - startSector < 6) + { + memset (sector, 0, ft->sector_size); + sector[508+3]=0xaa; /* TrailSig */ + sector[508+2]=0x55; + if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, + cryptoInfo) == FALSE) + goto fail; + } + + /* bootsector backup */ + memset (sector, 0, ft->sector_size); + PutBoot (ft, (unsigned char *) sector); + if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, + cryptoInfo) == FALSE) + goto fail; + + PutFSInfo((unsigned char *) sector, ft); + if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, + cryptoInfo) == FALSE) + goto fail; + } + + /* reserved */ + while (nSecNo - startSector < (unsigned int)ft->reserved) + { + memset (sector, 0, ft->sector_size); + if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, + cryptoInfo) == FALSE) + goto fail; + } + + /* write fat */ + for (x = 1; x <= ft->fats; x++) + { + for (n = 0; n < ft->fat_length; n++) + { + memset (sector, 0, ft->sector_size); + + if (n == 0) + { + unsigned char fat_sig[12]; + if (ft->size_fat == 32) + { + fat_sig[0] = (unsigned char) ft->media; + fat_sig[1] = fat_sig[2] = 0xff; + fat_sig[3] = 0x0f; + fat_sig[4] = fat_sig[5] = fat_sig[6] = 0xff; + fat_sig[7] = 0x0f; + fat_sig[8] = fat_sig[9] = fat_sig[10] = 0xff; + fat_sig[11] = 0x0f; + memcpy (sector, fat_sig, 12); + } + else if (ft->size_fat == 16) + { + fat_sig[0] = (unsigned char) ft->media; + fat_sig[1] = 0xff; + fat_sig[2] = 0xff; + fat_sig[3] = 0xff; + memcpy (sector, fat_sig, 4); + } + else if (ft->size_fat == 12) + { + fat_sig[0] = (unsigned char) ft->media; + fat_sig[1] = 0xff; + fat_sig[2] = 0xff; + fat_sig[3] = 0x00; + memcpy (sector, fat_sig, 4); + } + } + + if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, + cryptoInfo) == FALSE) + goto fail; + } + } + + + /* write rootdir */ + for (x = 0; x < ft->size_root_dir / ft->sector_size; x++) + { + memset (sector, 0, ft->sector_size); + if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, + cryptoInfo) == FALSE) + goto fail; + + } + + /* Fill the rest of the data area with random data */ + + if(!quickFormat) + { + if (!FlushFormatWriteBuffer (dev, write_buf, &write_buf_cnt, &nSecNo, cryptoInfo)) + goto fail; + + /* Generate a random temporary key set to be used for "dummy" encryption that will fill + the free disk space (data area) with random data. This is necessary for plausible + deniability of hidden volumes (and also reduces the amount of predictable plaintext + within the volume). */ + + // Temporary master key + if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (cryptoInfo->ea), FALSE)) + goto fail; + + // Temporary secondary key (XTS mode) + if (!RandgetBytes (hwndDlg, cryptoInfo->k2, sizeof cryptoInfo->k2, FALSE)) + goto fail; + + retVal = EAInit (cryptoInfo->ea, temporaryKey, cryptoInfo->ks); + if (retVal != ERR_SUCCESS) + { + burn (temporaryKey, sizeof(temporaryKey)); + return retVal; + } + if (!EAInitMode (cryptoInfo)) + { + burn (temporaryKey, sizeof(temporaryKey)); + return ERR_MODE_INIT_FAILED; + } + + x = ft->num_sectors - ft->reserved - ft->size_root_dir / ft->sector_size - ft->fat_length * 2; + while (x--) + { + if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, + cryptoInfo) == FALSE) + goto fail; + } + UpdateProgressBar (nSecNo * ft->sector_size); + } + else + UpdateProgressBar ((uint64) ft->num_sectors * ft->sector_size); + + if (!FlushFormatWriteBuffer (dev, write_buf, &write_buf_cnt, &nSecNo, cryptoInfo)) + goto fail; + + TCfree (write_buf); + burn (temporaryKey, sizeof(temporaryKey)); + return 0; + +fail: + + TCfree (write_buf); + burn (temporaryKey, sizeof(temporaryKey)); + return ERR_OS_ERROR; +} diff --git a/src/Common/Fat.h b/src/Common/Fat.h index 76714046..b637f8ec 100644 --- a/src/Common/Fat.h +++ b/src/Common/Fat.h @@ -1,69 +1,69 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -typedef struct fatparams_t -{ - char volume_name[11]; - byte volume_id[4]; - unsigned int num_sectors; /* total number of sectors */ - int cluster_count; /* number of clusters */ - int size_root_dir; /* size of the root directory in bytes */ - int size_fat; /* size of FAT */ - int fats; - int media; - unsigned int cluster_size; - int fat_length; - uint16 dir_entries; - uint16 sector_size; - int hidden; - __int16 reserved; - uint16 sectors; - unsigned int total_sect; - - uint16 heads; - uint16 secs_track; - -} fatparams; - - -struct msdos_boot_sector -{ - unsigned char boot_jump[3]; /* Boot strap short or near jump */ - char system_id[8]; /* Name - can be used to special case - partition manager volumes */ - unsigned char sector_size[2]; /* bytes per logical sector */ - unsigned char cluster_size; /* sectors/cluster */ - unsigned short reserved;/* reserved sectors */ - unsigned char fats; /* number of FATs */ - unsigned char dir_entries[2]; /* root directory entries */ - unsigned char sectors[2]; /* number of sectors */ - unsigned char media; /* media code */ - unsigned short fat_length; /* sectors/FAT */ - unsigned short secs_track; /* sectors per track */ - unsigned short heads; /* number of heads */ - unsigned __int32 hidden; /* hidden sectors */ - unsigned __int32 total_sect; /* number of sectors (if sectors == 0) */ - unsigned char drive_number; /* BIOS drive number */ - unsigned char RESERVED; /* Unused */ - unsigned char ext_boot_sign; /* 0x29 if fields below exist (DOS 3.3+) */ - unsigned char volume_id[4]; /* Volume ID number */ - char volume_label[11]; /* Volume label */ - char fs_type[8]; /* Typically FAT12, FAT16, or FAT32 */ - unsigned char boot_code[448]; /* Boot code (or message) */ - unsigned short boot_sign; /* 0xAA55 */ -}; - - -void GetFatParams ( fatparams *ft ); -void PutBoot ( fatparams *ft , unsigned char *boot ); -int FormatFat (void* hwndDlg, unsigned __int64 startSector, fatparams * ft, void * dev, PCRYPTO_INFO cryptoInfo, BOOL quickFormat); +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +typedef struct fatparams_t +{ + char volume_name[11]; + byte volume_id[4]; + unsigned int num_sectors; /* total number of sectors */ + int cluster_count; /* number of clusters */ + int size_root_dir; /* size of the root directory in bytes */ + int size_fat; /* size of FAT */ + int fats; + int media; + unsigned int cluster_size; + int fat_length; + uint16 dir_entries; + uint16 sector_size; + int hidden; + __int16 reserved; + uint16 sectors; + unsigned int total_sect; + + uint16 heads; + uint16 secs_track; + +} fatparams; + + +struct msdos_boot_sector +{ + unsigned char boot_jump[3]; /* Boot strap short or near jump */ + char system_id[8]; /* Name - can be used to special case + partition manager volumes */ + unsigned char sector_size[2]; /* bytes per logical sector */ + unsigned char cluster_size; /* sectors/cluster */ + unsigned short reserved;/* reserved sectors */ + unsigned char fats; /* number of FATs */ + unsigned char dir_entries[2]; /* root directory entries */ + unsigned char sectors[2]; /* number of sectors */ + unsigned char media; /* media code */ + unsigned short fat_length; /* sectors/FAT */ + unsigned short secs_track; /* sectors per track */ + unsigned short heads; /* number of heads */ + unsigned __int32 hidden; /* hidden sectors */ + unsigned __int32 total_sect; /* number of sectors (if sectors == 0) */ + unsigned char drive_number; /* BIOS drive number */ + unsigned char RESERVED; /* Unused */ + unsigned char ext_boot_sign; /* 0x29 if fields below exist (DOS 3.3+) */ + unsigned char volume_id[4]; /* Volume ID number */ + char volume_label[11]; /* Volume label */ + char fs_type[8]; /* Typically FAT12, FAT16, or FAT32 */ + unsigned char boot_code[448]; /* Boot code (or message) */ + unsigned short boot_sign; /* 0xAA55 */ +}; + + +void GetFatParams ( fatparams *ft ); +void PutBoot ( fatparams *ft , unsigned char *boot ); +int FormatFat (void* hwndDlg, unsigned __int64 startSector, fatparams * ft, void * dev, PCRYPTO_INFO cryptoInfo, BOOL quickFormat); diff --git a/src/Common/Format.c b/src/Common/Format.c index fe12c041..43a96d04 100644 --- a/src/Common/Format.c +++ b/src/Common/Format.c @@ -1,810 +1,810 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 -#include - -#include "Tcdefs.h" - -#include "Common.h" -#include "Crypto.h" -#include "Fat.h" -#include "Format.h" -#include "Random.h" -#include "Volumes.h" - -#include "Apidrvr.h" -#include "Dlgcode.h" -#include "Language.h" -#include "Progress.h" -#include "Resource.h" -#include "Format/FormatCom.h" -#include "Format/Tcformat.h" - -#include - -#ifndef SRC_POS -#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) -#endif - -int FormatWriteBufferSize = 1024 * 1024; -static uint32 FormatSectorSize = 0; - - -uint64 GetVolumeDataAreaSize (BOOL hiddenVolume, uint64 volumeSize) -{ - uint64 reservedSize; - - if (hiddenVolume) - { - // Reserve free space at the end of the host filesystem. FAT file system fills the last sector with - // zeroes (marked as free; observed when quick format was performed using the OS format tool). - // Therefore, when the outer volume is mounted with hidden volume protection, such write operations - // (e.g. quick formatting the outer volume filesystem as FAT) would needlessly trigger hidden volume - // protection. - -#if TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE > 4096 -# error TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE too large for very small volumes. Revise the code. -#endif - -#if TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH < TC_MAX_VOLUME_SECTOR_SIZE -# error TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH too small. -#endif - - if (volumeSize < TC_VOLUME_SMALL_SIZE_THRESHOLD) - reservedSize = TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE; - else - reservedSize = TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH; // Ensure size of a hidden volume larger than TC_VOLUME_SMALL_SIZE_THRESHOLD is a multiple of the maximum supported sector size - } - else - { - reservedSize = TC_TOTAL_VOLUME_HEADERS_SIZE; - } - - if (volumeSize < reservedSize) - return 0; - - return volumeSize - reservedSize; -} - - -int TCFormatVolume (volatile FORMAT_VOL_PARAMETERS *volParams) -{ - int nStatus; - PCRYPTO_INFO cryptoInfo = NULL; - HANDLE dev = INVALID_HANDLE_VALUE; - DWORD dwError; - char header[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; - unsigned __int64 num_sectors, startSector; - fatparams ft; - FILETIME ftCreationTime; - FILETIME ftLastWriteTime; - FILETIME ftLastAccessTime; - BOOL bTimeStampValid = FALSE; - BOOL bInstantRetryOtherFilesys = FALSE; - WCHAR dosDev[TC_MAX_PATH] = { 0 }; - WCHAR devName[MAX_PATH] = { 0 }; - int driveLetter = -1; - WCHAR deviceName[MAX_PATH]; - uint64 dataOffset, dataAreaSize; - LARGE_INTEGER offset; - BOOL bFailedRequiredDASD = FALSE; - HWND hwndDlg = volParams->hwndDlg; - - FormatSectorSize = volParams->sectorSize; - - if (FormatSectorSize < TC_MIN_VOLUME_SECTOR_SIZE - || FormatSectorSize > TC_MAX_VOLUME_SECTOR_SIZE - || FormatSectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0) - { - Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg); - return ERR_DONT_REPORT; - } - - /* WARNING: Note that if Windows fails to format the volume as NTFS and the volume size is - less than the maximum FAT size, the user is asked within this function whether he wants to instantly - retry FAT format instead (to avoid having to re-create the whole container again). If the user - answers yes, some of the input parameters are modified, the code below 'begin_format' is re-executed - and some destructive operations that were performed during the first attempt must be (and are) skipped. - Therefore, whenever adding or modifying any potentially destructive operations below 'begin_format', - determine whether they (or their portions) need to be skipped during such a second attempt; if so, - use the 'bInstantRetryOtherFilesys' flag to skip them. */ - - if (volParams->hiddenVol) - { - dataOffset = volParams->hiddenVolHostSize - TC_VOLUME_HEADER_GROUP_SIZE - volParams->size; - } - else - { - if (volParams->size <= TC_TOTAL_VOLUME_HEADERS_SIZE) - return ERR_VOL_SIZE_WRONG; - - dataOffset = TC_VOLUME_DATA_OFFSET; - } - - dataAreaSize = GetVolumeDataAreaSize (volParams->hiddenVol, volParams->size); - - num_sectors = dataAreaSize / FormatSectorSize; - - if (volParams->bDevice) - { - StringCchCopyW (deviceName, ARRAYSIZE(deviceName), volParams->volumePath); - - driveLetter = GetDiskDeviceDriveLetter (deviceName); - } - - VirtualLock (header, sizeof (header)); - - nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE, - header, - volParams->ea, - FIRST_MODE_OF_OPERATION_ID, - volParams->password, - volParams->pkcs5, - volParams->pim, - NULL, - &cryptoInfo, - dataAreaSize, - volParams->hiddenVol ? dataAreaSize : 0, - dataOffset, - dataAreaSize, - 0, - volParams->headerFlags, - FormatSectorSize, - FALSE); - - if (nStatus != 0) - { - burn (header, sizeof (header)); - VirtualUnlock (header, sizeof (header)); - return nStatus; - } - -begin_format: - - if (volParams->bDevice) - { - /* Device-hosted volume */ - - DWORD dwResult; - int nPass; - - if (FakeDosNameForDevice (volParams->volumePath, dosDev, sizeof(dosDev), devName, sizeof(devName), FALSE) != 0) - return ERR_OS_ERROR; - - if (IsDeviceMounted (devName)) - { - if ((dev = DismountDrive (devName, volParams->volumePath)) == INVALID_HANDLE_VALUE) - { - Error ("FORMAT_CANT_DISMOUNT_FILESYS", hwndDlg); - nStatus = ERR_DONT_REPORT; - goto error; - } - - /* Gain "raw" access to the partition (it contains a live filesystem and the filesystem driver - would otherwise prevent us from writing to hidden sectors). */ - - if (!DeviceIoControl (dev, - FSCTL_ALLOW_EXTENDED_DASD_IO, - NULL, - 0, - NULL, - 0, - &dwResult, - NULL)) - { - bFailedRequiredDASD = TRUE; - } - } - else if (IsOSAtLeast (WIN_VISTA) && driveLetter == -1) - { - // Windows Vista doesn't allow overwriting sectors belonging to an unformatted partition - // to which no drive letter has been assigned under the system. This problem can be worked - // around by assigning a drive letter to the partition temporarily. - - wchar_t szDriveLetter[] = { L'A', L':', 0 }; - wchar_t rootPath[] = { L'A', L':', L'\\', 0 }; - wchar_t uniqVolName[MAX_PATH+1] = { 0 }; - int tmpDriveLetter = -1; - BOOL bResult = FALSE; - - tmpDriveLetter = GetFirstAvailableDrive (); - - if (tmpDriveLetter != -1) - { - rootPath[0] += (wchar_t) tmpDriveLetter; - szDriveLetter[0] += (wchar_t) tmpDriveLetter; - - if (DefineDosDevice (DDD_RAW_TARGET_PATH, szDriveLetter, volParams->volumePath)) - { - bResult = GetVolumeNameForVolumeMountPoint (rootPath, uniqVolName, MAX_PATH); - - DefineDosDevice (DDD_RAW_TARGET_PATH|DDD_REMOVE_DEFINITION|DDD_EXACT_MATCH_ON_REMOVE, - szDriveLetter, - volParams->volumePath); - - if (bResult - && SetVolumeMountPoint (rootPath, uniqVolName)) - { - // The drive letter can be removed now - DeleteVolumeMountPoint (rootPath); - } - } - } - } - - // For extra safety, we will try to gain "raw" access to the partition. Note that this should actually be - // redundant because if the filesystem was mounted, we already tried to obtain DASD above. If we failed, - // bFailedRequiredDASD was set to TRUE and therefore we will perform pseudo "quick format" below. However, - // for extra safety, in case IsDeviceMounted() failed to detect a live filesystem, we will blindly - // send FSCTL_ALLOW_EXTENDED_DASD_IO (possibly for a second time) without checking the result. - - DeviceIoControl (dev, - FSCTL_ALLOW_EXTENDED_DASD_IO, - NULL, - 0, - NULL, - 0, - &dwResult, - NULL); - - - // If DASD is needed but we failed to obtain it, perform open - 'quick format' - close - open - // so that the filesystem driver does not prevent us from formatting hidden sectors. - for (nPass = (bFailedRequiredDASD ? 0 : 1); nPass < 2; nPass++) - { - int retryCount; - - retryCount = 0; - - // Try exclusive access mode first - // Note that when exclusive access is denied, it is worth retrying (usually succeeds after a few tries). - while (dev == INVALID_HANDLE_VALUE && retryCount++ < EXCL_ACCESS_MAX_AUTO_RETRIES) - { - dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); - - if (retryCount > 1) - Sleep (EXCL_ACCESS_AUTO_RETRY_DELAY); - } - - if (dev == INVALID_HANDLE_VALUE) - { - // Exclusive access denied -- retry in shared mode - dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - if (dev != INVALID_HANDLE_VALUE) - { - if (!volParams->bForceOperation && (Silent || (IDNO == MessageBoxW (volParams->hwndDlg, GetString ("DEVICE_IN_USE_FORMAT"), lpszTitle, MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2)))) - { - nStatus = ERR_DONT_REPORT; - goto error; - } - } - else - { - handleWin32Error (volParams->hwndDlg, SRC_POS); - Error ("CANT_ACCESS_VOL", hwndDlg); - nStatus = ERR_DONT_REPORT; - goto error; - } - } - - if (volParams->hiddenVol || bInstantRetryOtherFilesys) - break; // The following "quick format" operation would damage the outer volume - - if (nPass == 0) - { - char buf [2 * TC_MAX_VOLUME_SECTOR_SIZE]; - DWORD bw; - - // Perform pseudo "quick format" so that the filesystem driver does not prevent us from - // formatting hidden sectors - memset (buf, 0, sizeof (buf)); - - if (!WriteFile (dev, buf, sizeof (buf), &bw, NULL)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - FlushFileBuffers (dev); - CloseHandle (dev); - dev = INVALID_HANDLE_VALUE; - } - } - - if (DeviceIoControl (dev, FSCTL_IS_VOLUME_MOUNTED, NULL, 0, NULL, 0, &dwResult, NULL)) - { - Error ("FORMAT_CANT_DISMOUNT_FILESYS", hwndDlg); - nStatus = ERR_DONT_REPORT; - goto error; - } - } - else - { - /* File-hosted volume */ - - dev = CreateFile (volParams->volumePath, GENERIC_READ | GENERIC_WRITE, - (volParams->hiddenVol || bInstantRetryOtherFilesys) ? (FILE_SHARE_READ | FILE_SHARE_WRITE) : 0, - NULL, (volParams->hiddenVol || bInstantRetryOtherFilesys) ? OPEN_EXISTING : CREATE_ALWAYS, 0, NULL); - - if (dev == INVALID_HANDLE_VALUE) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - DisableFileCompression (dev); - - if (!volParams->hiddenVol && !bInstantRetryOtherFilesys) - { - LARGE_INTEGER volumeSize; - volumeSize.QuadPart = dataAreaSize + TC_VOLUME_HEADER_GROUP_SIZE; - - if (volParams->sparseFileSwitch && volParams->quickFormat) - { - // Create as sparse file container - DWORD tmp; - if (!DeviceIoControl (dev, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &tmp, NULL)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - } - - // Preallocate the file - if (!SetFilePointerEx (dev, volumeSize, NULL, FILE_BEGIN) - || !SetEndOfFile (dev) - || SetFilePointer (dev, 0, NULL, FILE_BEGIN) != 0) - { - nStatus = ERR_OS_ERROR; - goto error; - } - } - } - - if (volParams->hiddenVol && !volParams->bDevice && bPreserveTimestamp) - { - if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0) - bTimeStampValid = FALSE; - else - bTimeStampValid = TRUE; - } - - if (volParams->hwndDlg && volParams->bGuiMode) KillTimer (volParams->hwndDlg, TIMER_ID_RANDVIEW); - - /* Volume header */ - - // Hidden volume setup - if (volParams->hiddenVol) - { - LARGE_INTEGER headerOffset; - - // Check hidden volume size - if (volParams->hiddenVolHostSize < TC_MIN_HIDDEN_VOLUME_HOST_SIZE || volParams->hiddenVolHostSize > TC_MAX_HIDDEN_VOLUME_HOST_SIZE) - { - nStatus = ERR_VOL_SIZE_WRONG; - goto error; - } - - // Seek to hidden volume header location - - headerOffset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET; - - if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - } - else if (bInstantRetryOtherFilesys) - { - // The previous file system format failed and the user wants to try again with a different file system. - // The volume header had been written successfully so we need to seek to the byte after the header. - - LARGE_INTEGER offset; - offset.QuadPart = TC_VOLUME_DATA_OFFSET; - if (!SetFilePointerEx ((HANDLE) dev, offset, NULL, FILE_BEGIN)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - } - - if (!bInstantRetryOtherFilesys) - { - // Write the volume header - if (!WriteEffectiveVolumeHeader (volParams->bDevice, dev, header)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - // To prevent fragmentation, write zeroes to reserved header sectors which are going to be filled with random data - if (!volParams->bDevice && !volParams->hiddenVol) - { - byte buf[TC_VOLUME_HEADER_GROUP_SIZE - TC_VOLUME_HEADER_EFFECTIVE_SIZE]; - DWORD bytesWritten; - ZeroMemory (buf, sizeof (buf)); - - if (!WriteFile (dev, buf, sizeof (buf), &bytesWritten, NULL)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - if (bytesWritten != sizeof (buf)) - { - nStatus = ERR_PARAMETER_INCORRECT; - goto error; - } - } - } - - if (volParams->hiddenVol) - { - // Calculate data area position of hidden volume - cryptoInfo->hiddenVolumeOffset = dataOffset; - - // Validate the offset - if (dataOffset % FormatSectorSize != 0) - { - nStatus = ERR_VOL_SIZE_WRONG; - goto error; - } - - volParams->quickFormat = TRUE; // To entirely format a hidden volume would be redundant - } - - /* Data area */ - startSector = dataOffset / FormatSectorSize; - - // Format filesystem - - switch (volParams->fileSystem) - { - case FILESYS_NONE: - case FILESYS_NTFS: - case FILESYS_EXFAT: - - if (volParams->bDevice && !StartFormatWriteThread()) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - nStatus = FormatNoFs (hwndDlg, startSector, num_sectors, dev, cryptoInfo, volParams->quickFormat); - - if (volParams->bDevice) - StopFormatWriteThread(); - - break; - - case FILESYS_FAT: - if (num_sectors > 0xFFFFffff) - { - nStatus = ERR_VOL_SIZE_WRONG; - goto error; - } - - // Calculate the fats, root dir etc - ft.num_sectors = (unsigned int) (num_sectors); - -#if TC_MAX_VOLUME_SECTOR_SIZE > 0xFFFF -#error TC_MAX_VOLUME_SECTOR_SIZE > 0xFFFF -#endif - - ft.sector_size = (uint16) FormatSectorSize; - ft.cluster_size = volParams->clusterSize; - memcpy (ft.volume_name, "NO NAME ", 11); - GetFatParams (&ft); - *(volParams->realClusterSize) = ft.cluster_size * FormatSectorSize; - - if (volParams->bDevice && !StartFormatWriteThread()) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - nStatus = FormatFat (hwndDlg, startSector, &ft, (void *) dev, cryptoInfo, volParams->quickFormat); - - if (volParams->bDevice) - StopFormatWriteThread(); - - break; - - default: - nStatus = ERR_PARAMETER_INCORRECT; - goto error; - } - - if (nStatus != ERR_SUCCESS) - goto error; - - // Write header backup - offset.QuadPart = volParams->hiddenVol ? volParams->hiddenVolHostSize - TC_HIDDEN_VOLUME_HEADER_OFFSET : dataAreaSize + TC_VOLUME_HEADER_GROUP_SIZE; - - if (!SetFilePointerEx ((HANDLE) dev, offset, NULL, FILE_BEGIN)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE, - header, - volParams->ea, - FIRST_MODE_OF_OPERATION_ID, - volParams->password, - volParams->pkcs5, - volParams->pim, - cryptoInfo->master_keydata, - &cryptoInfo, - dataAreaSize, - volParams->hiddenVol ? dataAreaSize : 0, - dataOffset, - dataAreaSize, - 0, - volParams->headerFlags, - FormatSectorSize, - FALSE); - - if (!WriteEffectiveVolumeHeader (volParams->bDevice, dev, header)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - // Fill reserved header sectors (including the backup header area) with random data - if (!volParams->hiddenVol) - { - nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, dataAreaSize, FALSE, FALSE); - - if (nStatus != ERR_SUCCESS) - goto error; - } - -#ifndef DEBUG - if (volParams->quickFormat && volParams->fileSystem != FILESYS_NTFS && volParams->fileSystem != FILESYS_EXFAT) - Sleep (500); // User-friendly GUI -#endif - -error: - dwError = GetLastError(); - - burn (header, sizeof (header)); - VirtualUnlock (header, sizeof (header)); - - if (dev != INVALID_HANDLE_VALUE) - { - if (!volParams->bDevice && !volParams->hiddenVol && nStatus != 0) - { - // Remove preallocated part before closing file handle if format failed - if (SetFilePointer (dev, 0, NULL, FILE_BEGIN) == 0) - SetEndOfFile (dev); - } - - FlushFileBuffers (dev); - - if (bTimeStampValid) - SetFileTime (dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime); - - CloseHandle (dev); - dev = INVALID_HANDLE_VALUE; - } - - if (nStatus != 0) - { - SetLastError(dwError); - goto fv_end; - } - - if (volParams->fileSystem == FILESYS_NTFS || volParams->fileSystem == FILESYS_EXFAT) - { - // Quick-format volume as NTFS - int driveNo = GetLastAvailableDrive (); - MountOptions mountOptions; - int retCode; - int fsType = (volParams->fileSystem == FILESYS_EXFAT)? FILESYS_EXFAT: FILESYS_NTFS; - - ZeroMemory (&mountOptions, sizeof (mountOptions)); - - if (driveNo == -1) - { - if (!Silent) - { - MessageBoxW (volParams->hwndDlg, GetString ("NO_FREE_DRIVES"), lpszTitle, ICON_HAND); - MessageBoxW (volParams->hwndDlg, GetString ("FORMAT_NTFS_STOP"), lpszTitle, ICON_HAND); - } - - nStatus = ERR_NO_FREE_DRIVES; - goto fv_end; - } - - mountOptions.ReadOnly = FALSE; - mountOptions.Removable = FALSE; - mountOptions.ProtectHiddenVolume = FALSE; - mountOptions.PreserveTimestamp = bPreserveTimestamp; - mountOptions.PartitionInInactiveSysEncScope = FALSE; - mountOptions.UseBackupHeader = FALSE; - - if (MountVolume (volParams->hwndDlg, driveNo, volParams->volumePath, volParams->password, volParams->pkcs5, volParams->pim, FALSE, FALSE, FALSE, TRUE, &mountOptions, FALSE, TRUE) < 1) - { - if (!Silent) - { - MessageBoxW (volParams->hwndDlg, GetString ("CANT_MOUNT_VOLUME"), lpszTitle, ICON_HAND); - MessageBoxW (volParams->hwndDlg, GetString ("FORMAT_NTFS_STOP"), lpszTitle, ICON_HAND); - } - nStatus = ERR_VOL_MOUNT_FAILED; - goto fv_end; - } - - if (!Silent && !IsAdmin () && IsUacSupported ()) - retCode = UacFormatFs (volParams->hwndDlg, driveNo, volParams->clusterSize, fsType); - else - retCode = FormatFs (driveNo, volParams->clusterSize, fsType); - - if (retCode != TRUE) - { - if (!UnmountVolumeAfterFormatExCall (volParams->hwndDlg, driveNo) && !Silent) - MessageBoxW (volParams->hwndDlg, GetString ("CANT_DISMOUNT_VOLUME"), lpszTitle, ICON_HAND); - - if (dataAreaSize <= TC_MAX_FAT_SECTOR_COUNT * FormatSectorSize) - { - if (AskErrYesNo ("FORMAT_NTFS_FAILED_ASK_FAT", hwndDlg) == IDYES) - { - // NTFS format failed and the user wants to try FAT format immediately - volParams->fileSystem = FILESYS_FAT; - bInstantRetryOtherFilesys = TRUE; - volParams->quickFormat = TRUE; // Volume has already been successfully TC-formatted - volParams->clusterSize = 0; // Default cluster size - goto begin_format; - } - } - else - Error ("FORMAT_NTFS_FAILED", hwndDlg); - - nStatus = ERR_DONT_REPORT; - goto fv_end; - } - - if (!UnmountVolumeAfterFormatExCall (volParams->hwndDlg, driveNo) && !Silent) - MessageBoxW (volParams->hwndDlg, GetString ("CANT_DISMOUNT_VOLUME"), lpszTitle, ICON_HAND); - } - -fv_end: - dwError = GetLastError(); - - if (dosDev[0]) - RemoveFakeDosName (volParams->volumePath, dosDev); - - crypto_close (cryptoInfo); - - SetLastError (dwError); - return nStatus; -} - - -int FormatNoFs (HWND hwndDlg, unsigned __int64 startSector, __int64 num_sectors, void * dev, PCRYPTO_INFO cryptoInfo, BOOL quickFormat) -{ - int write_buf_cnt = 0; - char sector[TC_MAX_VOLUME_SECTOR_SIZE], *write_buf; - unsigned __int64 nSecNo = startSector; - int retVal = 0; - DWORD err; - char temporaryKey[MASTER_KEYDATA_SIZE]; - char originalK2[MASTER_KEYDATA_SIZE]; - - LARGE_INTEGER startOffset; - LARGE_INTEGER newOffset; - - // Seek to start sector - startOffset.QuadPart = startSector * FormatSectorSize; - if (!SetFilePointerEx ((HANDLE) dev, startOffset, &newOffset, FILE_BEGIN) - || newOffset.QuadPart != startOffset.QuadPart) - { - return ERR_OS_ERROR; - } - - write_buf = (char *)TCalloc (FormatWriteBufferSize); - if (!write_buf) - return ERR_OUTOFMEMORY; - - VirtualLock (temporaryKey, sizeof (temporaryKey)); - VirtualLock (originalK2, sizeof (originalK2)); - - memset (sector, 0, sizeof (sector)); - - // Remember the original secondary key (XTS mode) before generating a temporary one - memcpy (originalK2, cryptoInfo->k2, sizeof (cryptoInfo->k2)); - - /* Fill the rest of the data area with random data */ - - if(!quickFormat) - { - /* Generate a random temporary key set to be used for "dummy" encryption that will fill - the free disk space (data area) with random data. This is necessary for plausible - deniability of hidden volumes. */ - - // Temporary master key - if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (cryptoInfo->ea), FALSE)) - goto fail; - - // Temporary secondary key (XTS mode) - if (!RandgetBytes (hwndDlg, cryptoInfo->k2, sizeof cryptoInfo->k2, FALSE)) - goto fail; - - retVal = EAInit (cryptoInfo->ea, temporaryKey, cryptoInfo->ks); - if (retVal != ERR_SUCCESS) - goto fail; - - if (!EAInitMode (cryptoInfo)) - { - retVal = ERR_MODE_INIT_FAILED; - goto fail; - } - - while (num_sectors--) - { - if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, - cryptoInfo) == FALSE) - goto fail; - } - - if (!FlushFormatWriteBuffer (dev, write_buf, &write_buf_cnt, &nSecNo, cryptoInfo)) - goto fail; - } - else - nSecNo = num_sectors; - - UpdateProgressBar (nSecNo * FormatSectorSize); - - // Restore the original secondary key (XTS mode) in case NTFS format fails and the user wants to try FAT immediately - memcpy (cryptoInfo->k2, originalK2, sizeof (cryptoInfo->k2)); - - // Reinitialize the encryption algorithm and mode in case NTFS format fails and the user wants to try FAT immediately - retVal = EAInit (cryptoInfo->ea, cryptoInfo->master_keydata, cryptoInfo->ks); - if (retVal != ERR_SUCCESS) - goto fail; - if (!EAInitMode (cryptoInfo)) - { - retVal = ERR_MODE_INIT_FAILED; - goto fail; - } - - burn (temporaryKey, sizeof(temporaryKey)); - burn (originalK2, sizeof(originalK2)); - VirtualUnlock (temporaryKey, sizeof (temporaryKey)); - VirtualUnlock (originalK2, sizeof (originalK2)); - TCfree (write_buf); - - return 0; - -fail: - err = GetLastError(); - - burn (temporaryKey, sizeof(temporaryKey)); - burn (originalK2, sizeof(originalK2)); - VirtualUnlock (temporaryKey, sizeof (temporaryKey)); - VirtualUnlock (originalK2, sizeof (originalK2)); - TCfree (write_buf); - - SetLastError (err); - return (retVal ? retVal : ERR_OS_ERROR); -} - - -volatile BOOLEAN FormatExError; - -BOOLEAN __stdcall FormatExCallback (int command, DWORD subCommand, PVOID parameter) +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 +#include + +#include "Tcdefs.h" + +#include "Common.h" +#include "Crypto.h" +#include "Fat.h" +#include "Format.h" +#include "Random.h" +#include "Volumes.h" + +#include "Apidrvr.h" +#include "Dlgcode.h" +#include "Language.h" +#include "Progress.h" +#include "Resource.h" +#include "Format/FormatCom.h" +#include "Format/Tcformat.h" + +#include + +#ifndef SRC_POS +#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) +#endif + +int FormatWriteBufferSize = 1024 * 1024; +static uint32 FormatSectorSize = 0; + + +uint64 GetVolumeDataAreaSize (BOOL hiddenVolume, uint64 volumeSize) +{ + uint64 reservedSize; + + if (hiddenVolume) + { + // Reserve free space at the end of the host filesystem. FAT file system fills the last sector with + // zeroes (marked as free; observed when quick format was performed using the OS format tool). + // Therefore, when the outer volume is mounted with hidden volume protection, such write operations + // (e.g. quick formatting the outer volume filesystem as FAT) would needlessly trigger hidden volume + // protection. + +#if TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE > 4096 +# error TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE too large for very small volumes. Revise the code. +#endif + +#if TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH < TC_MAX_VOLUME_SECTOR_SIZE +# error TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH too small. +#endif + + if (volumeSize < TC_VOLUME_SMALL_SIZE_THRESHOLD) + reservedSize = TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE; + else + reservedSize = TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH; // Ensure size of a hidden volume larger than TC_VOLUME_SMALL_SIZE_THRESHOLD is a multiple of the maximum supported sector size + } + else + { + reservedSize = TC_TOTAL_VOLUME_HEADERS_SIZE; + } + + if (volumeSize < reservedSize) + return 0; + + return volumeSize - reservedSize; +} + + +int TCFormatVolume (volatile FORMAT_VOL_PARAMETERS *volParams) +{ + int nStatus; + PCRYPTO_INFO cryptoInfo = NULL; + HANDLE dev = INVALID_HANDLE_VALUE; + DWORD dwError; + char header[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; + unsigned __int64 num_sectors, startSector; + fatparams ft; + FILETIME ftCreationTime; + FILETIME ftLastWriteTime; + FILETIME ftLastAccessTime; + BOOL bTimeStampValid = FALSE; + BOOL bInstantRetryOtherFilesys = FALSE; + WCHAR dosDev[TC_MAX_PATH] = { 0 }; + WCHAR devName[MAX_PATH] = { 0 }; + int driveLetter = -1; + WCHAR deviceName[MAX_PATH]; + uint64 dataOffset, dataAreaSize; + LARGE_INTEGER offset; + BOOL bFailedRequiredDASD = FALSE; + HWND hwndDlg = volParams->hwndDlg; + + FormatSectorSize = volParams->sectorSize; + + if (FormatSectorSize < TC_MIN_VOLUME_SECTOR_SIZE + || FormatSectorSize > TC_MAX_VOLUME_SECTOR_SIZE + || FormatSectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0) + { + Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg); + return ERR_DONT_REPORT; + } + + /* WARNING: Note that if Windows fails to format the volume as NTFS and the volume size is + less than the maximum FAT size, the user is asked within this function whether he wants to instantly + retry FAT format instead (to avoid having to re-create the whole container again). If the user + answers yes, some of the input parameters are modified, the code below 'begin_format' is re-executed + and some destructive operations that were performed during the first attempt must be (and are) skipped. + Therefore, whenever adding or modifying any potentially destructive operations below 'begin_format', + determine whether they (or their portions) need to be skipped during such a second attempt; if so, + use the 'bInstantRetryOtherFilesys' flag to skip them. */ + + if (volParams->hiddenVol) + { + dataOffset = volParams->hiddenVolHostSize - TC_VOLUME_HEADER_GROUP_SIZE - volParams->size; + } + else + { + if (volParams->size <= TC_TOTAL_VOLUME_HEADERS_SIZE) + return ERR_VOL_SIZE_WRONG; + + dataOffset = TC_VOLUME_DATA_OFFSET; + } + + dataAreaSize = GetVolumeDataAreaSize (volParams->hiddenVol, volParams->size); + + num_sectors = dataAreaSize / FormatSectorSize; + + if (volParams->bDevice) + { + StringCchCopyW (deviceName, ARRAYSIZE(deviceName), volParams->volumePath); + + driveLetter = GetDiskDeviceDriveLetter (deviceName); + } + + VirtualLock (header, sizeof (header)); + + nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE, + header, + volParams->ea, + FIRST_MODE_OF_OPERATION_ID, + volParams->password, + volParams->pkcs5, + volParams->pim, + NULL, + &cryptoInfo, + dataAreaSize, + volParams->hiddenVol ? dataAreaSize : 0, + dataOffset, + dataAreaSize, + 0, + volParams->headerFlags, + FormatSectorSize, + FALSE); + + if (nStatus != 0) + { + burn (header, sizeof (header)); + VirtualUnlock (header, sizeof (header)); + return nStatus; + } + +begin_format: + + if (volParams->bDevice) + { + /* Device-hosted volume */ + + DWORD dwResult; + int nPass; + + if (FakeDosNameForDevice (volParams->volumePath, dosDev, sizeof(dosDev), devName, sizeof(devName), FALSE) != 0) + return ERR_OS_ERROR; + + if (IsDeviceMounted (devName)) + { + if ((dev = DismountDrive (devName, volParams->volumePath)) == INVALID_HANDLE_VALUE) + { + Error ("FORMAT_CANT_DISMOUNT_FILESYS", hwndDlg); + nStatus = ERR_DONT_REPORT; + goto error; + } + + /* Gain "raw" access to the partition (it contains a live filesystem and the filesystem driver + would otherwise prevent us from writing to hidden sectors). */ + + if (!DeviceIoControl (dev, + FSCTL_ALLOW_EXTENDED_DASD_IO, + NULL, + 0, + NULL, + 0, + &dwResult, + NULL)) + { + bFailedRequiredDASD = TRUE; + } + } + else if (IsOSAtLeast (WIN_VISTA) && driveLetter == -1) + { + // Windows Vista doesn't allow overwriting sectors belonging to an unformatted partition + // to which no drive letter has been assigned under the system. This problem can be worked + // around by assigning a drive letter to the partition temporarily. + + wchar_t szDriveLetter[] = { L'A', L':', 0 }; + wchar_t rootPath[] = { L'A', L':', L'\\', 0 }; + wchar_t uniqVolName[MAX_PATH+1] = { 0 }; + int tmpDriveLetter = -1; + BOOL bResult = FALSE; + + tmpDriveLetter = GetFirstAvailableDrive (); + + if (tmpDriveLetter != -1) + { + rootPath[0] += (wchar_t) tmpDriveLetter; + szDriveLetter[0] += (wchar_t) tmpDriveLetter; + + if (DefineDosDevice (DDD_RAW_TARGET_PATH, szDriveLetter, volParams->volumePath)) + { + bResult = GetVolumeNameForVolumeMountPoint (rootPath, uniqVolName, MAX_PATH); + + DefineDosDevice (DDD_RAW_TARGET_PATH|DDD_REMOVE_DEFINITION|DDD_EXACT_MATCH_ON_REMOVE, + szDriveLetter, + volParams->volumePath); + + if (bResult + && SetVolumeMountPoint (rootPath, uniqVolName)) + { + // The drive letter can be removed now + DeleteVolumeMountPoint (rootPath); + } + } + } + } + + // For extra safety, we will try to gain "raw" access to the partition. Note that this should actually be + // redundant because if the filesystem was mounted, we already tried to obtain DASD above. If we failed, + // bFailedRequiredDASD was set to TRUE and therefore we will perform pseudo "quick format" below. However, + // for extra safety, in case IsDeviceMounted() failed to detect a live filesystem, we will blindly + // send FSCTL_ALLOW_EXTENDED_DASD_IO (possibly for a second time) without checking the result. + + DeviceIoControl (dev, + FSCTL_ALLOW_EXTENDED_DASD_IO, + NULL, + 0, + NULL, + 0, + &dwResult, + NULL); + + + // If DASD is needed but we failed to obtain it, perform open - 'quick format' - close - open + // so that the filesystem driver does not prevent us from formatting hidden sectors. + for (nPass = (bFailedRequiredDASD ? 0 : 1); nPass < 2; nPass++) + { + int retryCount; + + retryCount = 0; + + // Try exclusive access mode first + // Note that when exclusive access is denied, it is worth retrying (usually succeeds after a few tries). + while (dev == INVALID_HANDLE_VALUE && retryCount++ < EXCL_ACCESS_MAX_AUTO_RETRIES) + { + dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + + if (retryCount > 1) + Sleep (EXCL_ACCESS_AUTO_RETRY_DELAY); + } + + if (dev == INVALID_HANDLE_VALUE) + { + // Exclusive access denied -- retry in shared mode + dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + if (dev != INVALID_HANDLE_VALUE) + { + if (!volParams->bForceOperation && (Silent || (IDNO == MessageBoxW (volParams->hwndDlg, GetString ("DEVICE_IN_USE_FORMAT"), lpszTitle, MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2)))) + { + nStatus = ERR_DONT_REPORT; + goto error; + } + } + else + { + handleWin32Error (volParams->hwndDlg, SRC_POS); + Error ("CANT_ACCESS_VOL", hwndDlg); + nStatus = ERR_DONT_REPORT; + goto error; + } + } + + if (volParams->hiddenVol || bInstantRetryOtherFilesys) + break; // The following "quick format" operation would damage the outer volume + + if (nPass == 0) + { + char buf [2 * TC_MAX_VOLUME_SECTOR_SIZE]; + DWORD bw; + + // Perform pseudo "quick format" so that the filesystem driver does not prevent us from + // formatting hidden sectors + memset (buf, 0, sizeof (buf)); + + if (!WriteFile (dev, buf, sizeof (buf), &bw, NULL)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + FlushFileBuffers (dev); + CloseHandle (dev); + dev = INVALID_HANDLE_VALUE; + } + } + + if (DeviceIoControl (dev, FSCTL_IS_VOLUME_MOUNTED, NULL, 0, NULL, 0, &dwResult, NULL)) + { + Error ("FORMAT_CANT_DISMOUNT_FILESYS", hwndDlg); + nStatus = ERR_DONT_REPORT; + goto error; + } + } + else + { + /* File-hosted volume */ + + dev = CreateFile (volParams->volumePath, GENERIC_READ | GENERIC_WRITE, + (volParams->hiddenVol || bInstantRetryOtherFilesys) ? (FILE_SHARE_READ | FILE_SHARE_WRITE) : 0, + NULL, (volParams->hiddenVol || bInstantRetryOtherFilesys) ? OPEN_EXISTING : CREATE_ALWAYS, 0, NULL); + + if (dev == INVALID_HANDLE_VALUE) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + DisableFileCompression (dev); + + if (!volParams->hiddenVol && !bInstantRetryOtherFilesys) + { + LARGE_INTEGER volumeSize; + volumeSize.QuadPart = dataAreaSize + TC_VOLUME_HEADER_GROUP_SIZE; + + if (volParams->sparseFileSwitch && volParams->quickFormat) + { + // Create as sparse file container + DWORD tmp; + if (!DeviceIoControl (dev, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &tmp, NULL)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + } + + // Preallocate the file + if (!SetFilePointerEx (dev, volumeSize, NULL, FILE_BEGIN) + || !SetEndOfFile (dev) + || SetFilePointer (dev, 0, NULL, FILE_BEGIN) != 0) + { + nStatus = ERR_OS_ERROR; + goto error; + } + } + } + + if (volParams->hiddenVol && !volParams->bDevice && bPreserveTimestamp) + { + if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0) + bTimeStampValid = FALSE; + else + bTimeStampValid = TRUE; + } + + if (volParams->hwndDlg && volParams->bGuiMode) KillTimer (volParams->hwndDlg, TIMER_ID_RANDVIEW); + + /* Volume header */ + + // Hidden volume setup + if (volParams->hiddenVol) + { + LARGE_INTEGER headerOffset; + + // Check hidden volume size + if (volParams->hiddenVolHostSize < TC_MIN_HIDDEN_VOLUME_HOST_SIZE || volParams->hiddenVolHostSize > TC_MAX_HIDDEN_VOLUME_HOST_SIZE) + { + nStatus = ERR_VOL_SIZE_WRONG; + goto error; + } + + // Seek to hidden volume header location + + headerOffset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET; + + if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + } + else if (bInstantRetryOtherFilesys) + { + // The previous file system format failed and the user wants to try again with a different file system. + // The volume header had been written successfully so we need to seek to the byte after the header. + + LARGE_INTEGER offset; + offset.QuadPart = TC_VOLUME_DATA_OFFSET; + if (!SetFilePointerEx ((HANDLE) dev, offset, NULL, FILE_BEGIN)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + } + + if (!bInstantRetryOtherFilesys) + { + // Write the volume header + if (!WriteEffectiveVolumeHeader (volParams->bDevice, dev, header)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + // To prevent fragmentation, write zeroes to reserved header sectors which are going to be filled with random data + if (!volParams->bDevice && !volParams->hiddenVol) + { + byte buf[TC_VOLUME_HEADER_GROUP_SIZE - TC_VOLUME_HEADER_EFFECTIVE_SIZE]; + DWORD bytesWritten; + ZeroMemory (buf, sizeof (buf)); + + if (!WriteFile (dev, buf, sizeof (buf), &bytesWritten, NULL)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + if (bytesWritten != sizeof (buf)) + { + nStatus = ERR_PARAMETER_INCORRECT; + goto error; + } + } + } + + if (volParams->hiddenVol) + { + // Calculate data area position of hidden volume + cryptoInfo->hiddenVolumeOffset = dataOffset; + + // Validate the offset + if (dataOffset % FormatSectorSize != 0) + { + nStatus = ERR_VOL_SIZE_WRONG; + goto error; + } + + volParams->quickFormat = TRUE; // To entirely format a hidden volume would be redundant + } + + /* Data area */ + startSector = dataOffset / FormatSectorSize; + + // Format filesystem + + switch (volParams->fileSystem) + { + case FILESYS_NONE: + case FILESYS_NTFS: + case FILESYS_EXFAT: + + if (volParams->bDevice && !StartFormatWriteThread()) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + nStatus = FormatNoFs (hwndDlg, startSector, num_sectors, dev, cryptoInfo, volParams->quickFormat); + + if (volParams->bDevice) + StopFormatWriteThread(); + + break; + + case FILESYS_FAT: + if (num_sectors > 0xFFFFffff) + { + nStatus = ERR_VOL_SIZE_WRONG; + goto error; + } + + // Calculate the fats, root dir etc + ft.num_sectors = (unsigned int) (num_sectors); + +#if TC_MAX_VOLUME_SECTOR_SIZE > 0xFFFF +#error TC_MAX_VOLUME_SECTOR_SIZE > 0xFFFF +#endif + + ft.sector_size = (uint16) FormatSectorSize; + ft.cluster_size = volParams->clusterSize; + memcpy (ft.volume_name, "NO NAME ", 11); + GetFatParams (&ft); + *(volParams->realClusterSize) = ft.cluster_size * FormatSectorSize; + + if (volParams->bDevice && !StartFormatWriteThread()) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + nStatus = FormatFat (hwndDlg, startSector, &ft, (void *) dev, cryptoInfo, volParams->quickFormat); + + if (volParams->bDevice) + StopFormatWriteThread(); + + break; + + default: + nStatus = ERR_PARAMETER_INCORRECT; + goto error; + } + + if (nStatus != ERR_SUCCESS) + goto error; + + // Write header backup + offset.QuadPart = volParams->hiddenVol ? volParams->hiddenVolHostSize - TC_HIDDEN_VOLUME_HEADER_OFFSET : dataAreaSize + TC_VOLUME_HEADER_GROUP_SIZE; + + if (!SetFilePointerEx ((HANDLE) dev, offset, NULL, FILE_BEGIN)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE, + header, + volParams->ea, + FIRST_MODE_OF_OPERATION_ID, + volParams->password, + volParams->pkcs5, + volParams->pim, + cryptoInfo->master_keydata, + &cryptoInfo, + dataAreaSize, + volParams->hiddenVol ? dataAreaSize : 0, + dataOffset, + dataAreaSize, + 0, + volParams->headerFlags, + FormatSectorSize, + FALSE); + + if (!WriteEffectiveVolumeHeader (volParams->bDevice, dev, header)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + // Fill reserved header sectors (including the backup header area) with random data + if (!volParams->hiddenVol) + { + nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, dataAreaSize, FALSE, FALSE); + + if (nStatus != ERR_SUCCESS) + goto error; + } + +#ifndef DEBUG + if (volParams->quickFormat && volParams->fileSystem != FILESYS_NTFS && volParams->fileSystem != FILESYS_EXFAT) + Sleep (500); // User-friendly GUI +#endif + +error: + dwError = GetLastError(); + + burn (header, sizeof (header)); + VirtualUnlock (header, sizeof (header)); + + if (dev != INVALID_HANDLE_VALUE) + { + if (!volParams->bDevice && !volParams->hiddenVol && nStatus != 0) + { + // Remove preallocated part before closing file handle if format failed + if (SetFilePointer (dev, 0, NULL, FILE_BEGIN) == 0) + SetEndOfFile (dev); + } + + FlushFileBuffers (dev); + + if (bTimeStampValid) + SetFileTime (dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime); + + CloseHandle (dev); + dev = INVALID_HANDLE_VALUE; + } + + if (nStatus != 0) + { + SetLastError(dwError); + goto fv_end; + } + + if (volParams->fileSystem == FILESYS_NTFS || volParams->fileSystem == FILESYS_EXFAT) + { + // Quick-format volume as NTFS + int driveNo = GetLastAvailableDrive (); + MountOptions mountOptions; + int retCode; + int fsType = (volParams->fileSystem == FILESYS_EXFAT)? FILESYS_EXFAT: FILESYS_NTFS; + + ZeroMemory (&mountOptions, sizeof (mountOptions)); + + if (driveNo == -1) + { + if (!Silent) + { + MessageBoxW (volParams->hwndDlg, GetString ("NO_FREE_DRIVES"), lpszTitle, ICON_HAND); + MessageBoxW (volParams->hwndDlg, GetString ("FORMAT_NTFS_STOP"), lpszTitle, ICON_HAND); + } + + nStatus = ERR_NO_FREE_DRIVES; + goto fv_end; + } + + mountOptions.ReadOnly = FALSE; + mountOptions.Removable = FALSE; + mountOptions.ProtectHiddenVolume = FALSE; + mountOptions.PreserveTimestamp = bPreserveTimestamp; + mountOptions.PartitionInInactiveSysEncScope = FALSE; + mountOptions.UseBackupHeader = FALSE; + + if (MountVolume (volParams->hwndDlg, driveNo, volParams->volumePath, volParams->password, volParams->pkcs5, volParams->pim, FALSE, FALSE, FALSE, TRUE, &mountOptions, FALSE, TRUE) < 1) + { + if (!Silent) + { + MessageBoxW (volParams->hwndDlg, GetString ("CANT_MOUNT_VOLUME"), lpszTitle, ICON_HAND); + MessageBoxW (volParams->hwndDlg, GetString ("FORMAT_NTFS_STOP"), lpszTitle, ICON_HAND); + } + nStatus = ERR_VOL_MOUNT_FAILED; + goto fv_end; + } + + if (!Silent && !IsAdmin () && IsUacSupported ()) + retCode = UacFormatFs (volParams->hwndDlg, driveNo, volParams->clusterSize, fsType); + else + retCode = FormatFs (driveNo, volParams->clusterSize, fsType); + + if (retCode != TRUE) + { + if (!UnmountVolumeAfterFormatExCall (volParams->hwndDlg, driveNo) && !Silent) + MessageBoxW (volParams->hwndDlg, GetString ("CANT_DISMOUNT_VOLUME"), lpszTitle, ICON_HAND); + + if (dataAreaSize <= TC_MAX_FAT_SECTOR_COUNT * FormatSectorSize) + { + if (AskErrYesNo ("FORMAT_NTFS_FAILED_ASK_FAT", hwndDlg) == IDYES) + { + // NTFS format failed and the user wants to try FAT format immediately + volParams->fileSystem = FILESYS_FAT; + bInstantRetryOtherFilesys = TRUE; + volParams->quickFormat = TRUE; // Volume has already been successfully TC-formatted + volParams->clusterSize = 0; // Default cluster size + goto begin_format; + } + } + else + Error ("FORMAT_NTFS_FAILED", hwndDlg); + + nStatus = ERR_DONT_REPORT; + goto fv_end; + } + + if (!UnmountVolumeAfterFormatExCall (volParams->hwndDlg, driveNo) && !Silent) + MessageBoxW (volParams->hwndDlg, GetString ("CANT_DISMOUNT_VOLUME"), lpszTitle, ICON_HAND); + } + +fv_end: + dwError = GetLastError(); + + if (dosDev[0]) + RemoveFakeDosName (volParams->volumePath, dosDev); + + crypto_close (cryptoInfo); + + SetLastError (dwError); + return nStatus; +} + + +int FormatNoFs (HWND hwndDlg, unsigned __int64 startSector, __int64 num_sectors, void * dev, PCRYPTO_INFO cryptoInfo, BOOL quickFormat) +{ + int write_buf_cnt = 0; + char sector[TC_MAX_VOLUME_SECTOR_SIZE], *write_buf; + unsigned __int64 nSecNo = startSector; + int retVal = 0; + DWORD err; + char temporaryKey[MASTER_KEYDATA_SIZE]; + char originalK2[MASTER_KEYDATA_SIZE]; + + LARGE_INTEGER startOffset; + LARGE_INTEGER newOffset; + + // Seek to start sector + startOffset.QuadPart = startSector * FormatSectorSize; + if (!SetFilePointerEx ((HANDLE) dev, startOffset, &newOffset, FILE_BEGIN) + || newOffset.QuadPart != startOffset.QuadPart) + { + return ERR_OS_ERROR; + } + + write_buf = (char *)TCalloc (FormatWriteBufferSize); + if (!write_buf) + return ERR_OUTOFMEMORY; + + VirtualLock (temporaryKey, sizeof (temporaryKey)); + VirtualLock (originalK2, sizeof (originalK2)); + + memset (sector, 0, sizeof (sector)); + + // Remember the original secondary key (XTS mode) before generating a temporary one + memcpy (originalK2, cryptoInfo->k2, sizeof (cryptoInfo->k2)); + + /* Fill the rest of the data area with random data */ + + if(!quickFormat) + { + /* Generate a random temporary key set to be used for "dummy" encryption that will fill + the free disk space (data area) with random data. This is necessary for plausible + deniability of hidden volumes. */ + + // Temporary master key + if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (cryptoInfo->ea), FALSE)) + goto fail; + + // Temporary secondary key (XTS mode) + if (!RandgetBytes (hwndDlg, cryptoInfo->k2, sizeof cryptoInfo->k2, FALSE)) + goto fail; + + retVal = EAInit (cryptoInfo->ea, temporaryKey, cryptoInfo->ks); + if (retVal != ERR_SUCCESS) + goto fail; + + if (!EAInitMode (cryptoInfo)) + { + retVal = ERR_MODE_INIT_FAILED; + goto fail; + } + + while (num_sectors--) + { + if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, + cryptoInfo) == FALSE) + goto fail; + } + + if (!FlushFormatWriteBuffer (dev, write_buf, &write_buf_cnt, &nSecNo, cryptoInfo)) + goto fail; + } + else + nSecNo = num_sectors; + + UpdateProgressBar (nSecNo * FormatSectorSize); + + // Restore the original secondary key (XTS mode) in case NTFS format fails and the user wants to try FAT immediately + memcpy (cryptoInfo->k2, originalK2, sizeof (cryptoInfo->k2)); + + // Reinitialize the encryption algorithm and mode in case NTFS format fails and the user wants to try FAT immediately + retVal = EAInit (cryptoInfo->ea, cryptoInfo->master_keydata, cryptoInfo->ks); + if (retVal != ERR_SUCCESS) + goto fail; + if (!EAInitMode (cryptoInfo)) + { + retVal = ERR_MODE_INIT_FAILED; + goto fail; + } + + burn (temporaryKey, sizeof(temporaryKey)); + burn (originalK2, sizeof(originalK2)); + VirtualUnlock (temporaryKey, sizeof (temporaryKey)); + VirtualUnlock (originalK2, sizeof (originalK2)); + TCfree (write_buf); + + return 0; + +fail: + err = GetLastError(); + + burn (temporaryKey, sizeof(temporaryKey)); + burn (originalK2, sizeof(originalK2)); + VirtualUnlock (temporaryKey, sizeof (temporaryKey)); + VirtualUnlock (originalK2, sizeof (originalK2)); + TCfree (write_buf); + + SetLastError (err); + return (retVal ? retVal : ERR_OS_ERROR); +} + + +volatile BOOLEAN FormatExError; + +BOOLEAN __stdcall FormatExCallback (int command, DWORD subCommand, PVOID parameter) { if (FormatExError) return FALSE; @@ -859,250 +859,250 @@ BOOLEAN __stdcall FormatExCallback (int command, DWORD subCommand, PVOID paramet FormatExError = TRUE; break; } - return (FormatExError? FALSE : TRUE); -} - -BOOL FormatFs (int driveNo, int clusterSize, int fsType) -{ - wchar_t dllPath[MAX_PATH] = {0}; - WCHAR dir[8] = { (WCHAR) driveNo + L'A', 0 }; - PFORMATEX FormatEx; - HMODULE hModule; - int i; - WCHAR szFsFormat[16]; - WCHAR szLabel[2] = {0}; - switch (fsType) - { - case FILESYS_NTFS: - StringCchCopyW (szFsFormat, ARRAYSIZE (szFsFormat),L"NTFS"); - break; - case FILESYS_EXFAT: - StringCchCopyW (szFsFormat, ARRAYSIZE (szFsFormat),L"EXFAT"); - break; - default: - return FALSE; - } - - - if (GetSystemDirectory (dllPath, MAX_PATH)) - { - StringCchCatW(dllPath, ARRAYSIZE(dllPath), L"\\fmifs.dll"); - } - else - StringCchCopyW(dllPath, ARRAYSIZE(dllPath), L"C:\\Windows\\System32\\fmifs.dll"); - - hModule = LoadLibrary (dllPath); - - if (hModule == NULL) - return FALSE; - - if (!(FormatEx = (PFORMATEX) GetProcAddress (GetModuleHandle (L"fmifs.dll"), "FormatEx"))) - { - FreeLibrary (hModule); - return FALSE; - } - - StringCchCatW (dir, ARRAYSIZE(dir), L":\\"); - - FormatExError = TRUE; - - // Windows sometimes fails to format a volume (hosted on a removable medium) as NTFS. - // It often helps to retry several times. - for (i = 0; i < 50 && FormatExError; i++) - { - FormatExError = FALSE; - FormatEx (dir, FMIFS_HARDDISK, szFsFormat, szLabel, TRUE, clusterSize * FormatSectorSize, FormatExCallback); - } - - // The device may be referenced for some time after FormatEx() returns - Sleep (4000); - - FreeLibrary (hModule); - return FormatExError? FALSE : TRUE; -} - -BOOL FormatNtfs (int driveNo, int clusterSize) -{ - return FormatFs (driveNo, clusterSize, FILESYS_NTFS); -} - -BOOL WriteSector (void *dev, char *sector, - char *write_buf, int *write_buf_cnt, - __int64 *nSecNo, PCRYPTO_INFO cryptoInfo) -{ - static __int32 updateTime = 0; - - (*nSecNo)++; - - memcpy (write_buf + *write_buf_cnt, sector, FormatSectorSize); - (*write_buf_cnt) += FormatSectorSize; - - if (*write_buf_cnt == FormatWriteBufferSize && !FlushFormatWriteBuffer (dev, write_buf, write_buf_cnt, nSecNo, cryptoInfo)) - return FALSE; - - if (GetTickCount () - updateTime > 25) - { - if (UpdateProgressBar (*nSecNo * FormatSectorSize)) - return FALSE; - - updateTime = GetTickCount (); - } - - return TRUE; - -} - - -static volatile BOOL WriteThreadRunning; -static volatile BOOL WriteThreadExitRequested; -static HANDLE WriteThreadHandle; - -static byte *WriteThreadBuffer; -static HANDLE WriteBufferEmptyEvent; -static HANDLE WriteBufferFullEvent; - -static volatile HANDLE WriteRequestHandle; -static volatile int WriteRequestSize; -static volatile DWORD WriteRequestResult; - - -static void __cdecl FormatWriteThreadProc (void *arg) -{ - DWORD bytesWritten; - - SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_HIGHEST); - - while (!WriteThreadExitRequested) - { - if (WaitForSingleObject (WriteBufferFullEvent, INFINITE) == WAIT_FAILED) - { - handleWin32Error (NULL, SRC_POS); - break; - } - - if (WriteThreadExitRequested) - break; - - if (!WriteFile (WriteRequestHandle, WriteThreadBuffer, WriteRequestSize, &bytesWritten, NULL)) - WriteRequestResult = GetLastError(); - else - WriteRequestResult = ERROR_SUCCESS; - - if (!SetEvent (WriteBufferEmptyEvent)) - { - handleWin32Error (NULL, SRC_POS); - break; - } - } - - WriteThreadRunning = FALSE; - _endthread(); -} - - -static BOOL StartFormatWriteThread () -{ - DWORD sysErr; - - WriteBufferEmptyEvent = NULL; - WriteBufferFullEvent = NULL; - WriteThreadBuffer = NULL; - - WriteBufferEmptyEvent = CreateEvent (NULL, FALSE, TRUE, NULL); - if (!WriteBufferEmptyEvent) - goto err; - - WriteBufferFullEvent = CreateEvent (NULL, FALSE, FALSE, NULL); - if (!WriteBufferFullEvent) - goto err; - - WriteThreadBuffer = TCalloc (FormatWriteBufferSize); - if (!WriteThreadBuffer) - { - SetLastError (ERROR_OUTOFMEMORY); - goto err; - } - - WriteThreadExitRequested = FALSE; - WriteRequestResult = ERROR_SUCCESS; - - WriteThreadHandle = (HANDLE) _beginthread (FormatWriteThreadProc, 0, NULL); - if ((uintptr_t) WriteThreadHandle == -1L) - goto err; - - WriteThreadRunning = TRUE; - return TRUE; - -err: - sysErr = GetLastError(); - - if (WriteBufferEmptyEvent) - CloseHandle (WriteBufferEmptyEvent); - if (WriteBufferFullEvent) - CloseHandle (WriteBufferFullEvent); - if (WriteThreadBuffer) - TCfree (WriteThreadBuffer); - - SetLastError (sysErr); - return FALSE; -} - - -static void StopFormatWriteThread () -{ - if (WriteThreadRunning) - { - WaitForSingleObject (WriteBufferEmptyEvent, INFINITE); - - WriteThreadExitRequested = TRUE; - SetEvent (WriteBufferFullEvent); - - WaitForSingleObject (WriteThreadHandle, INFINITE); - } - - CloseHandle (WriteBufferEmptyEvent); - CloseHandle (WriteBufferFullEvent); - TCfree (WriteThreadBuffer); -} - - -BOOL FlushFormatWriteBuffer (void *dev, char *write_buf, int *write_buf_cnt, __int64 *nSecNo, PCRYPTO_INFO cryptoInfo) -{ - UINT64_STRUCT unitNo; - DWORD bytesWritten; - - if (*write_buf_cnt == 0) - return TRUE; - - unitNo.Value = (*nSecNo * FormatSectorSize - *write_buf_cnt) / ENCRYPTION_DATA_UNIT_SIZE; - - EncryptDataUnits (write_buf, &unitNo, *write_buf_cnt / ENCRYPTION_DATA_UNIT_SIZE, cryptoInfo); - - if (WriteThreadRunning) - { - if (WaitForSingleObject (WriteBufferEmptyEvent, INFINITE) == WAIT_FAILED) - return FALSE; - - if (WriteRequestResult != ERROR_SUCCESS) - { - SetEvent (WriteBufferEmptyEvent); - SetLastError (WriteRequestResult); - return FALSE; - } - - memcpy (WriteThreadBuffer, write_buf, *write_buf_cnt); - WriteRequestHandle = dev; - WriteRequestSize = *write_buf_cnt; - - if (!SetEvent (WriteBufferFullEvent)) - return FALSE; - } - else - { - if (!WriteFile ((HANDLE) dev, write_buf, *write_buf_cnt, &bytesWritten, NULL)) - return FALSE; - } - - *write_buf_cnt = 0; - return TRUE; -} + return (FormatExError? FALSE : TRUE); +} + +BOOL FormatFs (int driveNo, int clusterSize, int fsType) +{ + wchar_t dllPath[MAX_PATH] = {0}; + WCHAR dir[8] = { (WCHAR) driveNo + L'A', 0 }; + PFORMATEX FormatEx; + HMODULE hModule; + int i; + WCHAR szFsFormat[16]; + WCHAR szLabel[2] = {0}; + switch (fsType) + { + case FILESYS_NTFS: + StringCchCopyW (szFsFormat, ARRAYSIZE (szFsFormat),L"NTFS"); + break; + case FILESYS_EXFAT: + StringCchCopyW (szFsFormat, ARRAYSIZE (szFsFormat),L"EXFAT"); + break; + default: + return FALSE; + } + + + if (GetSystemDirectory (dllPath, MAX_PATH)) + { + StringCchCatW(dllPath, ARRAYSIZE(dllPath), L"\\fmifs.dll"); + } + else + StringCchCopyW(dllPath, ARRAYSIZE(dllPath), L"C:\\Windows\\System32\\fmifs.dll"); + + hModule = LoadLibrary (dllPath); + + if (hModule == NULL) + return FALSE; + + if (!(FormatEx = (PFORMATEX) GetProcAddress (GetModuleHandle (L"fmifs.dll"), "FormatEx"))) + { + FreeLibrary (hModule); + return FALSE; + } + + StringCchCatW (dir, ARRAYSIZE(dir), L":\\"); + + FormatExError = TRUE; + + // Windows sometimes fails to format a volume (hosted on a removable medium) as NTFS. + // It often helps to retry several times. + for (i = 0; i < 50 && FormatExError; i++) + { + FormatExError = FALSE; + FormatEx (dir, FMIFS_HARDDISK, szFsFormat, szLabel, TRUE, clusterSize * FormatSectorSize, FormatExCallback); + } + + // The device may be referenced for some time after FormatEx() returns + Sleep (4000); + + FreeLibrary (hModule); + return FormatExError? FALSE : TRUE; +} + +BOOL FormatNtfs (int driveNo, int clusterSize) +{ + return FormatFs (driveNo, clusterSize, FILESYS_NTFS); +} + +BOOL WriteSector (void *dev, char *sector, + char *write_buf, int *write_buf_cnt, + __int64 *nSecNo, PCRYPTO_INFO cryptoInfo) +{ + static __int32 updateTime = 0; + + (*nSecNo)++; + + memcpy (write_buf + *write_buf_cnt, sector, FormatSectorSize); + (*write_buf_cnt) += FormatSectorSize; + + if (*write_buf_cnt == FormatWriteBufferSize && !FlushFormatWriteBuffer (dev, write_buf, write_buf_cnt, nSecNo, cryptoInfo)) + return FALSE; + + if (GetTickCount () - updateTime > 25) + { + if (UpdateProgressBar (*nSecNo * FormatSectorSize)) + return FALSE; + + updateTime = GetTickCount (); + } + + return TRUE; + +} + + +static volatile BOOL WriteThreadRunning; +static volatile BOOL WriteThreadExitRequested; +static HANDLE WriteThreadHandle; + +static byte *WriteThreadBuffer; +static HANDLE WriteBufferEmptyEvent; +static HANDLE WriteBufferFullEvent; + +static volatile HANDLE WriteRequestHandle; +static volatile int WriteRequestSize; +static volatile DWORD WriteRequestResult; + + +static void __cdecl FormatWriteThreadProc (void *arg) +{ + DWORD bytesWritten; + + SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_HIGHEST); + + while (!WriteThreadExitRequested) + { + if (WaitForSingleObject (WriteBufferFullEvent, INFINITE) == WAIT_FAILED) + { + handleWin32Error (NULL, SRC_POS); + break; + } + + if (WriteThreadExitRequested) + break; + + if (!WriteFile (WriteRequestHandle, WriteThreadBuffer, WriteRequestSize, &bytesWritten, NULL)) + WriteRequestResult = GetLastError(); + else + WriteRequestResult = ERROR_SUCCESS; + + if (!SetEvent (WriteBufferEmptyEvent)) + { + handleWin32Error (NULL, SRC_POS); + break; + } + } + + WriteThreadRunning = FALSE; + _endthread(); +} + + +static BOOL StartFormatWriteThread () +{ + DWORD sysErr; + + WriteBufferEmptyEvent = NULL; + WriteBufferFullEvent = NULL; + WriteThreadBuffer = NULL; + + WriteBufferEmptyEvent = CreateEvent (NULL, FALSE, TRUE, NULL); + if (!WriteBufferEmptyEvent) + goto err; + + WriteBufferFullEvent = CreateEvent (NULL, FALSE, FALSE, NULL); + if (!WriteBufferFullEvent) + goto err; + + WriteThreadBuffer = TCalloc (FormatWriteBufferSize); + if (!WriteThreadBuffer) + { + SetLastError (ERROR_OUTOFMEMORY); + goto err; + } + + WriteThreadExitRequested = FALSE; + WriteRequestResult = ERROR_SUCCESS; + + WriteThreadHandle = (HANDLE) _beginthread (FormatWriteThreadProc, 0, NULL); + if ((uintptr_t) WriteThreadHandle == -1L) + goto err; + + WriteThreadRunning = TRUE; + return TRUE; + +err: + sysErr = GetLastError(); + + if (WriteBufferEmptyEvent) + CloseHandle (WriteBufferEmptyEvent); + if (WriteBufferFullEvent) + CloseHandle (WriteBufferFullEvent); + if (WriteThreadBuffer) + TCfree (WriteThreadBuffer); + + SetLastError (sysErr); + return FALSE; +} + + +static void StopFormatWriteThread () +{ + if (WriteThreadRunning) + { + WaitForSingleObject (WriteBufferEmptyEvent, INFINITE); + + WriteThreadExitRequested = TRUE; + SetEvent (WriteBufferFullEvent); + + WaitForSingleObject (WriteThreadHandle, INFINITE); + } + + CloseHandle (WriteBufferEmptyEvent); + CloseHandle (WriteBufferFullEvent); + TCfree (WriteThreadBuffer); +} + + +BOOL FlushFormatWriteBuffer (void *dev, char *write_buf, int *write_buf_cnt, __int64 *nSecNo, PCRYPTO_INFO cryptoInfo) +{ + UINT64_STRUCT unitNo; + DWORD bytesWritten; + + if (*write_buf_cnt == 0) + return TRUE; + + unitNo.Value = (*nSecNo * FormatSectorSize - *write_buf_cnt) / ENCRYPTION_DATA_UNIT_SIZE; + + EncryptDataUnits (write_buf, &unitNo, *write_buf_cnt / ENCRYPTION_DATA_UNIT_SIZE, cryptoInfo); + + if (WriteThreadRunning) + { + if (WaitForSingleObject (WriteBufferEmptyEvent, INFINITE) == WAIT_FAILED) + return FALSE; + + if (WriteRequestResult != ERROR_SUCCESS) + { + SetEvent (WriteBufferEmptyEvent); + SetLastError (WriteRequestResult); + return FALSE; + } + + memcpy (WriteThreadBuffer, write_buf, *write_buf_cnt); + WriteRequestHandle = dev; + WriteRequestSize = *write_buf_cnt; + + if (!SetEvent (WriteBufferFullEvent)) + return FALSE; + } + else + { + if (!WriteFile ((HANDLE) dev, write_buf, *write_buf_cnt, &bytesWritten, NULL)) + return FALSE; + } + + *write_buf_cnt = 0; + return TRUE; +} diff --git a/src/Common/Format.h b/src/Common/Format.h index 3aa764b0..de342b93 100644 --- a/src/Common/Format.h +++ b/src/Common/Format.h @@ -1,53 +1,53 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifndef TC_HEADER_Format -#define TC_HEADER_Format - -#include "Password.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// FMIFS -typedef BOOLEAN (__stdcall *PFMIFSCALLBACK)( int command, DWORD subCommand, PVOID parameter ); -typedef VOID (__stdcall *PFORMATEX)( PWCHAR DriveRoot, DWORD MediaFlag, PWCHAR Format, PWCHAR Label, BOOL QuickFormat, DWORD ClusterSize, PFMIFSCALLBACK Callback ); - -typedef struct -{ - BOOL bDevice; - BOOL hiddenVol; - wchar_t *volumePath; - unsigned __int64 size; - unsigned __int64 hiddenVolHostSize; - int ea; - int pkcs5; - uint32 headerFlags; - int fileSystem; - unsigned int clusterSize; - BOOL sparseFileSwitch; - BOOL quickFormat; - DWORD sectorSize; - int *realClusterSize; - Password *password; - int pim; - HWND hwndDlg; - BOOL bForceOperation; - BOOL bGuiMode; -} -FORMAT_VOL_PARAMETERS; - +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifndef TC_HEADER_Format +#define TC_HEADER_Format + +#include "Password.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// FMIFS +typedef BOOLEAN (__stdcall *PFMIFSCALLBACK)( int command, DWORD subCommand, PVOID parameter ); +typedef VOID (__stdcall *PFORMATEX)( PWCHAR DriveRoot, DWORD MediaFlag, PWCHAR Format, PWCHAR Label, BOOL QuickFormat, DWORD ClusterSize, PFMIFSCALLBACK Callback ); + +typedef struct +{ + BOOL bDevice; + BOOL hiddenVol; + wchar_t *volumePath; + unsigned __int64 size; + unsigned __int64 hiddenVolHostSize; + int ea; + int pkcs5; + uint32 headerFlags; + int fileSystem; + unsigned int clusterSize; + BOOL sparseFileSwitch; + BOOL quickFormat; + DWORD sectorSize; + int *realClusterSize; + Password *password; + int pim; + HWND hwndDlg; + BOOL bForceOperation; + BOOL bGuiMode; +} +FORMAT_VOL_PARAMETERS; + #define FMIFS_PROGRESS 0x00 #define FMIFS_DONE_WITH_STRUCTURE 0x01 #define FMIFS_INCOMPATIBLE_FILE_SYSTEM 0x03 @@ -66,29 +66,29 @@ FORMAT_VOL_PARAMETERS; #define FMIFS_NO_MEDIA_IN_DRIVE 0x14 #define FMIFS_DEVICE_NOT_READY 0x18 #define FMIFS_CHECKDISK_PROGRESS 0x19 -#define FMIFS_READ_ONLY_MODE 0x20 - -#define FMIFS_HARDDISK 0xC - -extern int FormatWriteBufferSize; - -int TCFormatVolume (volatile FORMAT_VOL_PARAMETERS *volParams); -BOOL FormatNtfs (int driveNo, int clusterSize); -BOOL FormatFs (int driveNo, int clusterSize, int fsType); -uint64 GetVolumeDataAreaSize (BOOL hiddenVolume, uint64 volumeSize); -int FormatNoFs (HWND hwndDlg, unsigned __int64 startSector, __int64 num_sectors, void *dev, PCRYPTO_INFO cryptoInfo, BOOL quickFormat); -BOOL WriteSector ( void *dev , char *sector , char *write_buf , int *write_buf_cnt , __int64 *nSecNo , PCRYPTO_INFO cryptoInfo ); -BOOL FlushFormatWriteBuffer (void *dev, char *write_buf, int *write_buf_cnt, __int64 *nSecNo, PCRYPTO_INFO cryptoInfo); -static BOOL StartFormatWriteThread (); -static void StopFormatWriteThread (); - -#define FILESYS_NONE 0 -#define FILESYS_FAT 1 -#define FILESYS_NTFS 2 -#define FILESYS_EXFAT 3 - -#ifdef __cplusplus -} -#endif - -#endif // TC_HEADER_Format +#define FMIFS_READ_ONLY_MODE 0x20 + +#define FMIFS_HARDDISK 0xC + +extern int FormatWriteBufferSize; + +int TCFormatVolume (volatile FORMAT_VOL_PARAMETERS *volParams); +BOOL FormatNtfs (int driveNo, int clusterSize); +BOOL FormatFs (int driveNo, int clusterSize, int fsType); +uint64 GetVolumeDataAreaSize (BOOL hiddenVolume, uint64 volumeSize); +int FormatNoFs (HWND hwndDlg, unsigned __int64 startSector, __int64 num_sectors, void *dev, PCRYPTO_INFO cryptoInfo, BOOL quickFormat); +BOOL WriteSector ( void *dev , char *sector , char *write_buf , int *write_buf_cnt , __int64 *nSecNo , PCRYPTO_INFO cryptoInfo ); +BOOL FlushFormatWriteBuffer (void *dev, char *write_buf, int *write_buf_cnt, __int64 *nSecNo, PCRYPTO_INFO cryptoInfo); +static BOOL StartFormatWriteThread (); +static void StopFormatWriteThread (); + +#define FILESYS_NONE 0 +#define FILESYS_FAT 1 +#define FILESYS_NTFS 2 +#define FILESYS_EXFAT 3 + +#ifdef __cplusplus +} +#endif + +#endif // TC_HEADER_Format diff --git a/src/Common/GfMul.c b/src/Common/GfMul.c index e933e56b..9cd74a89 100644 --- a/src/Common/GfMul.c +++ b/src/Common/GfMul.c @@ -1,768 +1,768 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 2003, Dr Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software is allowed (with or without - changes) provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue Date: 31/01/2004 - - My thanks to John Viega and David McGrew for their support in developing - this code and to David for testing it on a big-endain system. -*/ - -/* - --------------------------------------------------------------------------- - Portions Copyright (c) 2005 TrueCrypt Developers Association - - Changes: - - - Added multiplication in the finite field GF(2^128) optimized for - cases involving a 64-bit operand. - - - Added multiplication in the finite field GF(2^64). - - - Added MSB-first mode. - - - Added basic test algorithms. - - - Removed GCM. - --------------------------------------------------------------------------- -*/ - -#include -#include -#include "GfMul.h" -#include "Tcdefs.h" -#include "Common/Endian.h" - -/* BUFFER_ALIGN32 or BUFFER_ALIGN64 must be defined at this point to */ -/* enable faster operation by taking advantage of memory aligned values */ -/* NOTE: the BUFFER_ALIGN64 option has not been tested extensively */ - -#define BUFFER_ALIGN32 -#define UNROLL_LOOPS /* define to unroll some loops */ -#define IN_LINES /* define to use inline functions */ - /* in place of macros */ - -#define mode(x) GM_##x - -#if defined(__cplusplus) -extern "C" -{ -#endif - -typedef unsigned __int32 mode(32t); -typedef uint64 mode(64t); - -#define BRG_LITTLE_ENDIAN 1234 /* byte 0 is least significant (i386) */ -#define BRG_BIG_ENDIAN 4321 /* byte 0 is most significant (mc68k) */ - -#if BYTE_ORDER == LITTLE_ENDIAN -# define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN -#endif - -#if BYTE_ORDER == BIG_ENDIAN -# define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN -#endif - -#ifdef _MSC_VER -#pragma intrinsic(memcpy) -#define in_line __inline -#else -#define in_line -#endif - -#if 0 && defined(_MSC_VER) -#define rotl32 _lrotl -#define rotr32 _lrotr -#else -#define rotl32(x,n) (((x) << n) | ((x) >> (32 - n))) -#define rotr32(x,n) (((x) >> n) | ((x) << (32 - n))) -#endif - -#if !defined(bswap_32) -#define bswap_32(x) ((rotr32((x), 24) & 0x00ff00ff) | (rotr32((x), 8) & 0xff00ff00)) -#endif - -#if (PLATFORM_BYTE_ORDER == BRG_LITTLE_ENDIAN) -#define SWAP_BYTES -#else -#undef SWAP_BYTES -#endif - -#if defined(SWAP_BYTES) - -#if defined ( IN_LINES ) - -in_line void bsw_32(void * p, unsigned int n) -{ unsigned int i = n; - while(i--) - ((mode(32t)*)p)[i] = bswap_32(((mode(32t)*)p)[i]); -} - -#else - -#define bsw_32(p,n) \ - { int _i = (n); while(_i--) ((mode(32t)*)p)[_i] = bswap_32(((mode(32t)*)p)[_i]); } - -#endif - -#else -#define bsw_32(p,n) -#endif - -/* These values are used to detect long word alignment in order */ -/* to speed up some GCM buffer operations. This facility may */ -/* not work on some machines */ - -#define lp08(x) ((unsigned char*)(x)) -#define lp32(x) ((mode(32t)*)(x)) -#define lp64(x) ((mode(64t)*)(x)) - -#define A32_MASK 3 -#define A64_MASK 7 -#define aligned32(x) (!(((mode(32t))(x)) & A32_MASK)) -#define aligned64(x) (!(((mode(32t))(x)) & A64_MASK)) - -#if defined( BUFFER_ALIGN32 ) - -#define ADR_MASK A32_MASK -#define aligned aligned32 -#define lp lp32 -#define lp_inc 4 - -#if defined( IN_LINES ) - -in_line void move_block_aligned( void *p, const void *q) -{ - lp32(p)[0] = lp32(q)[0], lp32(p)[1] = lp32(q)[1], - lp32(p)[2] = lp32(q)[2], lp32(p)[3] = lp32(q)[3]; -} - -in_line void move_block_aligned64( void *p, const void *q) -{ - lp32(p)[0] = lp32(q)[0], lp32(p)[1] = lp32(q)[1]; -} - -in_line void xor_block_aligned( void *p, const void *q) -{ - lp32(p)[0] ^= lp32(q)[0], lp32(p)[1] ^= lp32(q)[1], - lp32(p)[2] ^= lp32(q)[2], lp32(p)[3] ^= lp32(q)[3]; -} - -in_line void xor_block_aligned64( void *p, const void *q) -{ - lp32(p)[0] ^= lp32(q)[0], lp32(p)[1] ^= lp32(q)[1]; -} - -#else - -#define move_block_aligned(p,q) \ - lp32(p)[0] = lp32(q)[0], lp32(p)[1] = lp32(q)[1], \ - lp32(p)[2] = lp32(q)[2], lp32(p)[3] = lp32(q)[3] - -#define xor_block_aligned(p,q) \ - lp32(p)[0] ^= lp32(q)[0], lp32(p)[1] ^= lp32(q)[1], \ - lp32(p)[2] ^= lp32(q)[2], lp32(p)[3] ^= lp32(q)[3] - -#endif - -#elif defined( BUFFER_ALIGN64 ) - -#define ADR_MASK A64_MASK -#define aligned aligned64 -#define lp lp64 -#define lp_inc 8 - -#define move_block_aligned(p,q) \ - lp64(p)[0] = lp64(q)[0], lp64(p)[1] = lp64(q)[1] - -#define xor_block_aligned(p,q) \ - lp64(p)[0] ^= lp64(q)[0], lp64(p)[1] ^= lp64(q)[1] - -#else -#define aligned(x) 0 -#endif - -#define move_block(p,q) memcpy((p), (q), BLOCK_LEN) - -#define xor_block(p,q) \ - lp08(p)[ 0] ^= lp08(q)[ 0], lp08(p)[ 1] ^= lp08(q)[ 1], \ - lp08(p)[ 2] ^= lp08(q)[ 2], lp08(p)[ 3] ^= lp08(q)[ 3], \ - lp08(p)[ 4] ^= lp08(q)[ 4], lp08(p)[ 5] ^= lp08(q)[ 5], \ - lp08(p)[ 6] ^= lp08(q)[ 6], lp08(p)[ 7] ^= lp08(q)[ 7], \ - lp08(p)[ 8] ^= lp08(q)[ 8], lp08(p)[ 9] ^= lp08(q)[ 9], \ - lp08(p)[10] ^= lp08(q)[10], lp08(p)[11] ^= lp08(q)[11], \ - lp08(p)[12] ^= lp08(q)[12], lp08(p)[13] ^= lp08(q)[13], \ - lp08(p)[14] ^= lp08(q)[14], lp08(p)[15] ^= lp08(q)[15] - - -#define gf_dat(q) {\ - q(0x00), q(0x01), q(0x02), q(0x03), q(0x04), q(0x05), q(0x06), q(0x07),\ - q(0x08), q(0x09), q(0x0a), q(0x0b), q(0x0c), q(0x0d), q(0x0e), q(0x0f),\ - q(0x10), q(0x11), q(0x12), q(0x13), q(0x14), q(0x15), q(0x16), q(0x17),\ - q(0x18), q(0x19), q(0x1a), q(0x1b), q(0x1c), q(0x1d), q(0x1e), q(0x1f),\ - q(0x20), q(0x21), q(0x22), q(0x23), q(0x24), q(0x25), q(0x26), q(0x27),\ - q(0x28), q(0x29), q(0x2a), q(0x2b), q(0x2c), q(0x2d), q(0x2e), q(0x2f),\ - q(0x30), q(0x31), q(0x32), q(0x33), q(0x34), q(0x35), q(0x36), q(0x37),\ - q(0x38), q(0x39), q(0x3a), q(0x3b), q(0x3c), q(0x3d), q(0x3e), q(0x3f),\ - q(0x40), q(0x41), q(0x42), q(0x43), q(0x44), q(0x45), q(0x46), q(0x47),\ - q(0x48), q(0x49), q(0x4a), q(0x4b), q(0x4c), q(0x4d), q(0x4e), q(0x4f),\ - q(0x50), q(0x51), q(0x52), q(0x53), q(0x54), q(0x55), q(0x56), q(0x57),\ - q(0x58), q(0x59), q(0x5a), q(0x5b), q(0x5c), q(0x5d), q(0x5e), q(0x5f),\ - q(0x60), q(0x61), q(0x62), q(0x63), q(0x64), q(0x65), q(0x66), q(0x67),\ - q(0x68), q(0x69), q(0x6a), q(0x6b), q(0x6c), q(0x6d), q(0x6e), q(0x6f),\ - q(0x70), q(0x71), q(0x72), q(0x73), q(0x74), q(0x75), q(0x76), q(0x77),\ - q(0x78), q(0x79), q(0x7a), q(0x7b), q(0x7c), q(0x7d), q(0x7e), q(0x7f),\ - q(0x80), q(0x81), q(0x82), q(0x83), q(0x84), q(0x85), q(0x86), q(0x87),\ - q(0x88), q(0x89), q(0x8a), q(0x8b), q(0x8c), q(0x8d), q(0x8e), q(0x8f),\ - q(0x90), q(0x91), q(0x92), q(0x93), q(0x94), q(0x95), q(0x96), q(0x97),\ - q(0x98), q(0x99), q(0x9a), q(0x9b), q(0x9c), q(0x9d), q(0x9e), q(0x9f),\ - q(0xa0), q(0xa1), q(0xa2), q(0xa3), q(0xa4), q(0xa5), q(0xa6), q(0xa7),\ - q(0xa8), q(0xa9), q(0xaa), q(0xab), q(0xac), q(0xad), q(0xae), q(0xaf),\ - q(0xb0), q(0xb1), q(0xb2), q(0xb3), q(0xb4), q(0xb5), q(0xb6), q(0xb7),\ - q(0xb8), q(0xb9), q(0xba), q(0xbb), q(0xbc), q(0xbd), q(0xbe), q(0xbf),\ - q(0xc0), q(0xc1), q(0xc2), q(0xc3), q(0xc4), q(0xc5), q(0xc6), q(0xc7),\ - q(0xc8), q(0xc9), q(0xca), q(0xcb), q(0xcc), q(0xcd), q(0xce), q(0xcf),\ - q(0xd0), q(0xd1), q(0xd2), q(0xd3), q(0xd4), q(0xd5), q(0xd6), q(0xd7),\ - q(0xd8), q(0xd9), q(0xda), q(0xdb), q(0xdc), q(0xdd), q(0xde), q(0xdf),\ - q(0xe0), q(0xe1), q(0xe2), q(0xe3), q(0xe4), q(0xe5), q(0xe6), q(0xe7),\ - q(0xe8), q(0xe9), q(0xea), q(0xeb), q(0xec), q(0xed), q(0xee), q(0xef),\ - q(0xf0), q(0xf1), q(0xf2), q(0xf3), q(0xf4), q(0xf5), q(0xf6), q(0xf7),\ - q(0xf8), q(0xf9), q(0xfa), q(0xfb), q(0xfc), q(0xfd), q(0xfe), q(0xff) } - -/* given the value i in 0..255 as the byte overflow when a a field */ -/* element in GHASH is multipled by x^8, this function will return */ -/* the values that are generated in the lo 16-bit word of the field */ -/* value by applying the modular polynomial. The values lo_byte and */ -/* hi_byte are returned via the macro xp_fun(lo_byte, hi_byte) so */ -/* that the values can be assembled into memory as required by a */ -/* suitable definition of this macro operating on the table above */ - -#define xp(i) xp_fun( \ - (i & 0x80 ? 0xe1 : 0) ^ (i & 0x40 ? 0x70 : 0) ^ \ - (i & 0x20 ? 0x38 : 0) ^ (i & 0x10 ? 0x1c : 0) ^ \ - (i & 0x08 ? 0x0e : 0) ^ (i & 0x04 ? 0x07 : 0) ^ \ - (i & 0x02 ? 0x03 : 0) ^ (i & 0x01 ? 0x01 : 0), \ - (i & 0x80 ? 0x00 : 0) ^ (i & 0x40 ? 0x80 : 0) ^ \ - (i & 0x20 ? 0x40 : 0) ^ (i & 0x10 ? 0x20 : 0) ^ \ - (i & 0x08 ? 0x10 : 0) ^ (i & 0x04 ? 0x08 : 0) ^ \ - (i & 0x02 ? 0x84 : 0) ^ (i & 0x01 ? 0xc2 : 0) ) - -#define xp64(i) xp_fun( \ - (i & 0x80 ? 0xd8 : 0) ^ (i & 0x40 ? 0x6c : 0) ^ \ - (i & 0x20 ? 0x36 : 0) ^ (i & 0x10 ? 0x1b : 0) ^ \ - (i & 0x08 ? 0x0d : 0) ^ (i & 0x04 ? 0x06 : 0) ^ \ - (i & 0x02 ? 0x03 : 0) ^ (i & 0x01 ? 0x01 : 0), \ - (i & 0x80 ? 0x00 : 0) ^ (i & 0x40 ? 0x00 : 0) ^ \ - (i & 0x20 ? 0x00 : 0) ^ (i & 0x10 ? 0x00 : 0) ^ \ - (i & 0x08 ? 0x80 : 0) ^ (i & 0x04 ? 0xc0 : 0) ^ \ - (i & 0x02 ? 0x60 : 0) ^ (i & 0x01 ? 0xb0 : 0) ) - -static mode(32t) gf_poly[2] = { 0, 0xe1000000 }; -static mode(32t) gf_poly64[2] = { 0, 0xd8000000 }; - -/* Multiply of a GF128 field element by x. The field element */ -/* is held in an array of bytes in which field bits 8n..8n + 7 */ -/* are held in byte[n], with lower indexed bits placed in the */ -/* more numerically significant bit positions in bytes. */ - -/* This function multiples a field element x, in the polynomial */ -/* field representation. It uses 32-bit word operations to gain */ -/* speed but compensates for machine endianess and hence works */ -/* correctly on both styles of machine */ - -in_line void mul_x(mode(32t) x[4]) -{ mode(32t) t; - - bsw_32(x, 4); - - /* at this point the filed element bits 0..127 are set out */ - /* as follows in 32-bit words (where the most significant */ - /* (ms) numeric bits are to the left) */ - /* */ - /* x[0] x[1] x[2] x[3] */ - /* ms ls ms ls ms ls ms ls */ - /* field: 0 ... 31 32 .. 63 64 .. 95 96 .. 127 */ - - t = gf_poly[x[3] & 1]; /* bit 127 of the element */ - x[3] = (x[3] >> 1) | (x[2] << 31); /* shift bits up by one */ - x[2] = (x[2] >> 1) | (x[1] << 31); /* position */ - x[1] = (x[1] >> 1) | (x[0] << 31); /* if bit 7 is 1 xor in */ - x[0] = (x[0] >> 1) ^ t; /* the field polynomial */ - bsw_32(x, 4); -} - -in_line void mul_x64(mode(32t) x[2]) -{ mode(32t) t; - - bsw_32(x, 2); - - /* at this point the filed element bits 0..127 are set out */ - /* as follows in 32-bit words (where the most significant */ - /* (ms) numeric bits are to the left) */ - /* */ - /* x[0] x[1] x[2] x[3] */ - /* ms ls ms ls ms ls ms ls */ - /* field: 0 ... 31 32 .. 63 64 .. 95 96 .. 127 */ - - t = gf_poly64[x[1] & 1]; /* bit 127 of the element */ - /* shift bits up by one */ - /* position */ - x[1] = (x[1] >> 1) | (x[0] << 31); /* if bit 7 is 1 xor in */ - x[0] = (x[0] >> 1) ^ t; /* the field polynomial */ - bsw_32(x, 2); -} - -/* Multiply of a GF128 field element by x^8 using 32-bit words */ -/* for speed - machine endianess matters here */ - -#if (PLATFORM_BYTE_ORDER == BRG_LITTLE_ENDIAN) - -#define xp_fun(x,y) ((mode(32t))(x)) | (((mode(32t))(y)) << 8) -static const unsigned __int16 gft_le[256] = gf_dat(xp); -static const unsigned __int16 gft_le64[256] = gf_dat(xp64); - -in_line void mul_lex8(mode(32t) x[4]) /* mutiply with long words */ -{ mode(32t) t = (x[3] >> 24); /* in little endian format */ - x[3] = (x[3] << 8) | (x[2] >> 24); - x[2] = (x[2] << 8) | (x[1] >> 24); - x[1] = (x[1] << 8) | (x[0] >> 24); - x[0] = (x[0] << 8) ^ gft_le[t]; -} - -in_line void mul_lex8_64(mode(32t) x[2]) /* mutiply with long words */ -{ mode(32t) t = (x[1] >> 24); /* in little endian format */ - x[1] = (x[1] << 8) | (x[0] >> 24); - x[0] = (x[0] << 8) ^ gft_le64[t]; -} - -#endif - -#if 1 || (PLATFORM_BYTE_ORDER == BRG_LITTLE_ENDIAN) - -#undef xp_fun -#define xp_fun(x,y) ((mode(32t))(y)) | (((mode(32t))(x)) << 8) -static const unsigned __int16 gft_be[256] = gf_dat(xp); -static const unsigned __int16 gft_be64[256] = gf_dat(xp64); - -in_line void mul_bex8(mode(32t) x[4]) /* mutiply with long words */ -{ mode(32t) t = (x[3] & 0xff); /* in big endian format */ - x[3] = (x[3] >> 8) | (x[2] << 24); - x[2] = (x[2] >> 8) | (x[1] << 24); - x[1] = (x[1] >> 8) | (x[0] << 24); - x[0] = (x[0] >> 8) ^ (((mode(32t))gft_be[t]) << 16); -} - -in_line void mul_bex8_64(mode(32t) x[2]) /* mutiply with long words */ -{ mode(32t) t = (x[1] & 0xff); /* in big endian format */ - x[1] = (x[1] >> 8) | (x[0] << 24); - x[0] = (x[0] >> 8) ^ (((mode(32t))gft_be64[t]) << 16); -} - -#endif - -/* hence choose the correct version for the machine endianess */ - -#if PLATFORM_BYTE_ORDER == BRG_BIG_ENDIAN -#define mul_x8 mul_bex8 -#define mul_x8_64 mul_bex8_64 -#else -#define mul_x8 mul_lex8 -#define mul_x8_64 mul_lex8_64 -#endif - -/* different versions of the general gf_mul function are provided */ -/* here. Sadly none are very fast :-( */ - -void GfMul128 (void *a, const void* b) -{ mode(32t) r[CBLK_LEN >> 2], p[8][CBLK_LEN >> 2]; - int i; - - move_block_aligned(p[0], b); - bsw_32(p[0], 4); - for(i = 0; i < 7; ++i) - { - p[i + 1][3] = (p[i][3] >> 1) | (p[i][2] << 31); - p[i + 1][2] = (p[i][2] >> 1) | (p[i][1] << 31); - p[i + 1][1] = (p[i][1] >> 1) | (p[i][0] << 31); - p[i + 1][0] = (p[i][0] >> 1) ^ gf_poly[p[i][3] & 1]; - } - - memset(r, 0, CBLK_LEN); - for(i = 0; i < 16; ++i) - { - if(i) mul_bex8(r); /* order is always big endian here */ - - if(((unsigned char*)a)[15 - i] & 0x80) - xor_block_aligned(r, p[0]); - if(((unsigned char*)a)[15 - i] & 0x40) - xor_block_aligned(r, p[1]); - if(((unsigned char*)a)[15 - i] & 0x20) - xor_block_aligned(r, p[2]); - if(((unsigned char*)a)[15 - i] & 0x10) - xor_block_aligned(r, p[3]); - if(((unsigned char*)a)[15 - i] & 0x08) - xor_block_aligned(r, p[4]); - if(((unsigned char*)a)[15 - i] & 0x04) - xor_block_aligned(r, p[5]); - if(((unsigned char*)a)[15 - i] & 0x02) - xor_block_aligned(r, p[6]); - if(((unsigned char*)a)[15 - i] & 0x01) - xor_block_aligned(r, p[7]); - } - bsw_32(r, 4); - move_block_aligned(a, r); -} - -#if defined( UNROLL_LOOPS ) - -#define xor_8k(i) \ - xor_block_aligned(r, ctx->gf_t8k[i + i][a[i] & 15]); \ - xor_block_aligned(r, ctx->gf_t8k[i + i + 1][a[i] >> 4]) - - -void GfMul128Tab (unsigned char a[CBLK_LEN], GfCtx8k *ctx) -{ unsigned __int32 r[CBLK_LEN >> 2]; - - move_block_aligned(r, ctx->gf_t8k[0][a[0] & 15]); - xor_block_aligned(r, ctx->gf_t8k[1][a[0] >> 4]); - xor_8k( 1); xor_8k( 2); xor_8k( 3); - xor_8k( 4); xor_8k( 5); xor_8k( 6); xor_8k( 7); - xor_8k( 8); xor_8k( 9); xor_8k(10); xor_8k(11); - xor_8k(12); xor_8k(13); xor_8k(14); xor_8k(15); - move_block_aligned(a, r); -} - -#else - -void GfMul128Tab (unsigned char a[CBLK_LEN], GfCtx8k *ctx) -{ unsigned __int32 r[CBLK_LEN >> 2], *p; - int i; - - p = ctx->gf_t8k[0][a[0] & 15]; - memcpy(r, p, CBLK_LEN); - p = ctx->gf_t8k[1][a[0] >> 4]; - xor_block_aligned(r, p); - for(i = 1; i < CBLK_LEN; ++i) - { - xor_block_aligned(r, ctx->gf_t8k[i + i][a[i] & 15]); - xor_block_aligned(r, ctx->gf_t8k[i + i + 1][a[i] >> 4]); - } - memcpy(a, r, CBLK_LEN); -} - -#endif - -void compile_8k_table(unsigned __int8 *a, GfCtx8k *ctx) -{ int i, j, k; - - memset(ctx->gf_t8k, 0, 32 * 16 * 16); - for(i = 0; i < 2 * CBLK_LEN; ++i) - { - if(i == 0) - { - memcpy(ctx->gf_t8k[1][8], a, CBLK_LEN); - for(j = 4; j > 0; j >>= 1) - { - memcpy(ctx->gf_t8k[1][j], ctx->gf_t8k[1][j + j], CBLK_LEN); - mul_x(ctx->gf_t8k[1][j]); - } - memcpy(ctx->gf_t8k[0][8], ctx->gf_t8k[1][1], CBLK_LEN); - mul_x(ctx->gf_t8k[0][8]); - for(j = 4; j > 0; j >>= 1) - { - memcpy(ctx->gf_t8k[0][j], ctx->gf_t8k[0][j + j], CBLK_LEN); - mul_x(ctx->gf_t8k[0][j]); - } - } - else if(i > 1) - for(j = 8; j > 0; j >>= 1) - { - memcpy(ctx->gf_t8k[i][j], ctx->gf_t8k[i - 2][j], CBLK_LEN); - mul_x8(ctx->gf_t8k[i][j]); - } - - for(j = 2; j < 16; j += j) - { - mode(32t) *pj = ctx->gf_t8k[i][j]; - mode(32t) *pk = ctx->gf_t8k[i][1]; - mode(32t) *pl = ctx->gf_t8k[i][j + 1]; - - for(k = 1; k < j; ++k) - { - *pl++ = pj[0] ^ *pk++; - *pl++ = pj[1] ^ *pk++; - *pl++ = pj[2] ^ *pk++; - *pl++ = pj[3] ^ *pk++; - } - } - } -} - - -void compile_4k_table64(unsigned __int8 *a, GfCtx4k64 *ctx) -{ int i, j, k; - - memset(ctx->gf_t4k, 0, sizeof(ctx->gf_t4k)); - for(i = 0; i < 2 * CBLK_LEN8; ++i) - { - if(i == 0) - { - memcpy(ctx->gf_t4k[1][8], a, CBLK_LEN8); - for(j = 4; j > 0; j >>= 1) - { - memcpy(ctx->gf_t4k[1][j], ctx->gf_t4k[1][j + j], CBLK_LEN8); - mul_x64(ctx->gf_t4k[1][j]); - } - memcpy(ctx->gf_t4k[0][8], ctx->gf_t4k[1][1], CBLK_LEN8); - mul_x64(ctx->gf_t4k[0][8]); - for(j = 4; j > 0; j >>= 1) - { - memcpy(ctx->gf_t4k[0][j], ctx->gf_t4k[0][j + j], CBLK_LEN8); - mul_x64(ctx->gf_t4k[0][j]); - } - } - else if(i > 1) - for(j = 8; j > 0; j >>= 1) - { - memcpy(ctx->gf_t4k[i][j], ctx->gf_t4k[i - 2][j], CBLK_LEN8); - mul_x8_64(ctx->gf_t4k[i][j]); - } - - for(j = 2; j < 16; j += j) - { - mode(32t) *pj = ctx->gf_t4k[i][j]; - mode(32t) *pk = ctx->gf_t4k[i][1]; - mode(32t) *pl = ctx->gf_t4k[i][j + 1]; - - for(k = 1; k < j; ++k) - { - *pl++ = pj[0] ^ *pk++; - *pl++ = pj[1] ^ *pk++; - *pl++ = pj[2] ^ *pk++; - *pl++ = pj[3] ^ *pk++; - } - } - } -} - -static int IsBitSet128 (unsigned int bit, unsigned __int8 *a) -{ - return a[(127 - bit) / 8] & (0x80 >> ((127 - bit) % 8)); -} - -static int IsBitSet64 (unsigned int bit, unsigned __int8 *a) -{ - return a[(63 - bit) / 8] & (0x80 >> ((63 - bit) % 8)); -} - -static void SetBit128 (unsigned int bit, unsigned __int8 *a) -{ - a[(127 - bit) / 8] |= 0x80 >> ((127 - bit) % 8); -} - -static void SetBit64 (unsigned int bit, unsigned __int8 *a) -{ - a[(63 - bit) / 8] |= 0x80 >> ((63 - bit) % 8); -} - -void MirrorBits128 (unsigned __int8 *a) -{ - unsigned __int8 t[128 / 8]; - int i; - memset (t,0,16); - for (i = 0; i < 128; i++) - { - if (IsBitSet128(i, a)) - SetBit128 (127 - i, t); - } - memcpy (a, t, sizeof (t)); - burn (t,sizeof (t)); -} - -void MirrorBits64 (unsigned __int8 *a) -{ - unsigned __int8 t[64 / 8]; - int i; - memset (t,0,8); - for (i = 0; i < 64; i++) - { - if (IsBitSet64(i, a)) - SetBit64 (63 - i, t); - } - memcpy (a, t, sizeof (t)); - burn (t,sizeof (t)); -} - -/* Allocate and initialize speed optimization table - for multiplication by 64-bit operand in MSB-first mode */ -int Gf128Tab64Init (unsigned __int8 *a, GfCtx *ctx) -{ - GfCtx8k *ctx8k; - unsigned __int8 am[16]; - int i, j; - - ctx8k = (GfCtx8k *) TCalloc (sizeof (GfCtx8k)); - if (!ctx8k) - return FALSE; - - memcpy (am, a, 16); - MirrorBits128 (am); - compile_8k_table (am, ctx8k); - - /* Convert 8k LSB-first table to 4k MSB-first */ - for (i = 16; i < 32; i++) - { - for (j = 0; j < 16; j++) - { - int jm = 0; - jm |= (j & 0x1) << 3; - jm |= (j & 0x2) << 1; - jm |= (j & 0x4) >> 1; - jm |= (j & 0x8) >> 3; - - memcpy (&ctx->gf_t128[i-16][jm], (unsigned char *)&ctx8k->gf_t8k[31-i][j], 16); - MirrorBits128 ((unsigned char *)&ctx->gf_t128[i-16][jm]); - } - } - - burn (ctx8k ,sizeof (*ctx8k)); - burn (am, sizeof (am)); - TCfree (ctx8k); - return TRUE; -} - - -#define xor_8kt64(i) \ - xor_block_aligned(r, ctx->gf_t128[i + i][a[i] & 15]); \ - xor_block_aligned(r, ctx->gf_t128[i + i + 1][a[i] >> 4]) - -/* Multiply a 128-bit number by a 64-bit number in the finite field GF(2^128) */ -void Gf128MulBy64Tab (unsigned __int8 a[8], unsigned __int8 p[16], GfCtx *ctx) -{ - unsigned __int32 r[CBLK_LEN >> 2]; - - move_block_aligned(r, ctx->gf_t128[7*2][a[7] & 15]); - xor_block_aligned(r, ctx->gf_t128[7*2+1][a[7] >> 4]); - - if (*(unsigned __int16 *)a) - { - xor_8kt64(0); - xor_8kt64(1); - } - if (a[2]) - { - xor_8kt64(2); - } - xor_8kt64(3); - xor_8kt64(4); - xor_8kt64(5); - xor_8kt64(6); - - move_block_aligned(p, r); -} - - - -/* Basic algorithms for testing of optimized algorithms */ - -static void xor128 (uint64 *a, uint64 *b) -{ - *a++ ^= *b++; - *a ^= *b; -} - -static void shl128 (unsigned __int8 *a) -{ - int i, x = 0, xx; - for (i = 15; i >= 0; i--) - { - xx = (a[i] & 0x80) >> 7; - a[i] = (char) ((a[i] << 1) | x); - x = xx; - } -} - -static void GfMul128Basic (unsigned __int8 *a, unsigned __int8 *b, unsigned __int8 *p) -{ - int i; - unsigned __int8 la[16]; - memcpy (la, a, 16); - memset (p, 0, 16); - - for (i = 0; i < 128; i++) - { - if (IsBitSet128 (i, b)) - xor128 ((uint64 *)p, (uint64 *)la); - - if (la[0] & 0x80) - { - shl128 (la); - la[15] ^= 0x87; - } - else - { - shl128 (la); - } - } -} - - -BOOL GfMulSelfTest () -{ - BOOL result = TRUE; - unsigned __int8 a[16]; - unsigned __int8 b[16]; - unsigned __int8 p1[16]; - unsigned __int8 p2[16]; - GfCtx *gfCtx = (GfCtx *) TCalloc (sizeof (GfCtx)); - int i, j; - - if (!gfCtx) - return FALSE; - - - /* GF(2^128) */ - for (i = 0; i < 0x100; i++) - { - for (j = 0; j < 16; j++) - { - a[j] = (unsigned __int8) i; - b[j] = j < 8 ? 0 : a[j] ^ 0xff; - } - - GfMul128Basic (a, b, p1); - - Gf128Tab64Init (a, gfCtx); - Gf128MulBy64Tab (b + 8, p2, gfCtx); - - if (memcmp (p1, p2, 16) != 0) - result = FALSE; - } - - TCfree (gfCtx); - return result; -} - -#if defined(__cplusplus) -} -#endif +/* + --------------------------------------------------------------------------- + Copyright (c) 2003, Dr Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software is allowed (with or without + changes) provided that: + + 1. source code distributions include the above copyright notice, this + list of conditions and the following disclaimer; + + 2. binary distributions include the above copyright notice, this list + of conditions and the following disclaimer in their documentation; + + 3. the name of the copyright holder is not used to endorse products + built using this software without specific written permission. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + Issue Date: 31/01/2004 + + My thanks to John Viega and David McGrew for their support in developing + this code and to David for testing it on a big-endain system. +*/ + +/* + --------------------------------------------------------------------------- + Portions Copyright (c) 2005 TrueCrypt Developers Association + + Changes: + + - Added multiplication in the finite field GF(2^128) optimized for + cases involving a 64-bit operand. + + - Added multiplication in the finite field GF(2^64). + + - Added MSB-first mode. + + - Added basic test algorithms. + + - Removed GCM. + --------------------------------------------------------------------------- +*/ + +#include +#include +#include "GfMul.h" +#include "Tcdefs.h" +#include "Common/Endian.h" + +/* BUFFER_ALIGN32 or BUFFER_ALIGN64 must be defined at this point to */ +/* enable faster operation by taking advantage of memory aligned values */ +/* NOTE: the BUFFER_ALIGN64 option has not been tested extensively */ + +#define BUFFER_ALIGN32 +#define UNROLL_LOOPS /* define to unroll some loops */ +#define IN_LINES /* define to use inline functions */ + /* in place of macros */ + +#define mode(x) GM_##x + +#if defined(__cplusplus) +extern "C" +{ +#endif + +typedef unsigned __int32 mode(32t); +typedef uint64 mode(64t); + +#define BRG_LITTLE_ENDIAN 1234 /* byte 0 is least significant (i386) */ +#define BRG_BIG_ENDIAN 4321 /* byte 0 is most significant (mc68k) */ + +#if BYTE_ORDER == LITTLE_ENDIAN +# define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN +#endif + +#if BYTE_ORDER == BIG_ENDIAN +# define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN +#endif + +#ifdef _MSC_VER +#pragma intrinsic(memcpy) +#define in_line __inline +#else +#define in_line +#endif + +#if 0 && defined(_MSC_VER) +#define rotl32 _lrotl +#define rotr32 _lrotr +#else +#define rotl32(x,n) (((x) << n) | ((x) >> (32 - n))) +#define rotr32(x,n) (((x) >> n) | ((x) << (32 - n))) +#endif + +#if !defined(bswap_32) +#define bswap_32(x) ((rotr32((x), 24) & 0x00ff00ff) | (rotr32((x), 8) & 0xff00ff00)) +#endif + +#if (PLATFORM_BYTE_ORDER == BRG_LITTLE_ENDIAN) +#define SWAP_BYTES +#else +#undef SWAP_BYTES +#endif + +#if defined(SWAP_BYTES) + +#if defined ( IN_LINES ) + +in_line void bsw_32(void * p, unsigned int n) +{ unsigned int i = n; + while(i--) + ((mode(32t)*)p)[i] = bswap_32(((mode(32t)*)p)[i]); +} + +#else + +#define bsw_32(p,n) \ + { int _i = (n); while(_i--) ((mode(32t)*)p)[_i] = bswap_32(((mode(32t)*)p)[_i]); } + +#endif + +#else +#define bsw_32(p,n) +#endif + +/* These values are used to detect long word alignment in order */ +/* to speed up some GCM buffer operations. This facility may */ +/* not work on some machines */ + +#define lp08(x) ((unsigned char*)(x)) +#define lp32(x) ((mode(32t)*)(x)) +#define lp64(x) ((mode(64t)*)(x)) + +#define A32_MASK 3 +#define A64_MASK 7 +#define aligned32(x) (!(((mode(32t))(x)) & A32_MASK)) +#define aligned64(x) (!(((mode(32t))(x)) & A64_MASK)) + +#if defined( BUFFER_ALIGN32 ) + +#define ADR_MASK A32_MASK +#define aligned aligned32 +#define lp lp32 +#define lp_inc 4 + +#if defined( IN_LINES ) + +in_line void move_block_aligned( void *p, const void *q) +{ + lp32(p)[0] = lp32(q)[0], lp32(p)[1] = lp32(q)[1], + lp32(p)[2] = lp32(q)[2], lp32(p)[3] = lp32(q)[3]; +} + +in_line void move_block_aligned64( void *p, const void *q) +{ + lp32(p)[0] = lp32(q)[0], lp32(p)[1] = lp32(q)[1]; +} + +in_line void xor_block_aligned( void *p, const void *q) +{ + lp32(p)[0] ^= lp32(q)[0], lp32(p)[1] ^= lp32(q)[1], + lp32(p)[2] ^= lp32(q)[2], lp32(p)[3] ^= lp32(q)[3]; +} + +in_line void xor_block_aligned64( void *p, const void *q) +{ + lp32(p)[0] ^= lp32(q)[0], lp32(p)[1] ^= lp32(q)[1]; +} + +#else + +#define move_block_aligned(p,q) \ + lp32(p)[0] = lp32(q)[0], lp32(p)[1] = lp32(q)[1], \ + lp32(p)[2] = lp32(q)[2], lp32(p)[3] = lp32(q)[3] + +#define xor_block_aligned(p,q) \ + lp32(p)[0] ^= lp32(q)[0], lp32(p)[1] ^= lp32(q)[1], \ + lp32(p)[2] ^= lp32(q)[2], lp32(p)[3] ^= lp32(q)[3] + +#endif + +#elif defined( BUFFER_ALIGN64 ) + +#define ADR_MASK A64_MASK +#define aligned aligned64 +#define lp lp64 +#define lp_inc 8 + +#define move_block_aligned(p,q) \ + lp64(p)[0] = lp64(q)[0], lp64(p)[1] = lp64(q)[1] + +#define xor_block_aligned(p,q) \ + lp64(p)[0] ^= lp64(q)[0], lp64(p)[1] ^= lp64(q)[1] + +#else +#define aligned(x) 0 +#endif + +#define move_block(p,q) memcpy((p), (q), BLOCK_LEN) + +#define xor_block(p,q) \ + lp08(p)[ 0] ^= lp08(q)[ 0], lp08(p)[ 1] ^= lp08(q)[ 1], \ + lp08(p)[ 2] ^= lp08(q)[ 2], lp08(p)[ 3] ^= lp08(q)[ 3], \ + lp08(p)[ 4] ^= lp08(q)[ 4], lp08(p)[ 5] ^= lp08(q)[ 5], \ + lp08(p)[ 6] ^= lp08(q)[ 6], lp08(p)[ 7] ^= lp08(q)[ 7], \ + lp08(p)[ 8] ^= lp08(q)[ 8], lp08(p)[ 9] ^= lp08(q)[ 9], \ + lp08(p)[10] ^= lp08(q)[10], lp08(p)[11] ^= lp08(q)[11], \ + lp08(p)[12] ^= lp08(q)[12], lp08(p)[13] ^= lp08(q)[13], \ + lp08(p)[14] ^= lp08(q)[14], lp08(p)[15] ^= lp08(q)[15] + + +#define gf_dat(q) {\ + q(0x00), q(0x01), q(0x02), q(0x03), q(0x04), q(0x05), q(0x06), q(0x07),\ + q(0x08), q(0x09), q(0x0a), q(0x0b), q(0x0c), q(0x0d), q(0x0e), q(0x0f),\ + q(0x10), q(0x11), q(0x12), q(0x13), q(0x14), q(0x15), q(0x16), q(0x17),\ + q(0x18), q(0x19), q(0x1a), q(0x1b), q(0x1c), q(0x1d), q(0x1e), q(0x1f),\ + q(0x20), q(0x21), q(0x22), q(0x23), q(0x24), q(0x25), q(0x26), q(0x27),\ + q(0x28), q(0x29), q(0x2a), q(0x2b), q(0x2c), q(0x2d), q(0x2e), q(0x2f),\ + q(0x30), q(0x31), q(0x32), q(0x33), q(0x34), q(0x35), q(0x36), q(0x37),\ + q(0x38), q(0x39), q(0x3a), q(0x3b), q(0x3c), q(0x3d), q(0x3e), q(0x3f),\ + q(0x40), q(0x41), q(0x42), q(0x43), q(0x44), q(0x45), q(0x46), q(0x47),\ + q(0x48), q(0x49), q(0x4a), q(0x4b), q(0x4c), q(0x4d), q(0x4e), q(0x4f),\ + q(0x50), q(0x51), q(0x52), q(0x53), q(0x54), q(0x55), q(0x56), q(0x57),\ + q(0x58), q(0x59), q(0x5a), q(0x5b), q(0x5c), q(0x5d), q(0x5e), q(0x5f),\ + q(0x60), q(0x61), q(0x62), q(0x63), q(0x64), q(0x65), q(0x66), q(0x67),\ + q(0x68), q(0x69), q(0x6a), q(0x6b), q(0x6c), q(0x6d), q(0x6e), q(0x6f),\ + q(0x70), q(0x71), q(0x72), q(0x73), q(0x74), q(0x75), q(0x76), q(0x77),\ + q(0x78), q(0x79), q(0x7a), q(0x7b), q(0x7c), q(0x7d), q(0x7e), q(0x7f),\ + q(0x80), q(0x81), q(0x82), q(0x83), q(0x84), q(0x85), q(0x86), q(0x87),\ + q(0x88), q(0x89), q(0x8a), q(0x8b), q(0x8c), q(0x8d), q(0x8e), q(0x8f),\ + q(0x90), q(0x91), q(0x92), q(0x93), q(0x94), q(0x95), q(0x96), q(0x97),\ + q(0x98), q(0x99), q(0x9a), q(0x9b), q(0x9c), q(0x9d), q(0x9e), q(0x9f),\ + q(0xa0), q(0xa1), q(0xa2), q(0xa3), q(0xa4), q(0xa5), q(0xa6), q(0xa7),\ + q(0xa8), q(0xa9), q(0xaa), q(0xab), q(0xac), q(0xad), q(0xae), q(0xaf),\ + q(0xb0), q(0xb1), q(0xb2), q(0xb3), q(0xb4), q(0xb5), q(0xb6), q(0xb7),\ + q(0xb8), q(0xb9), q(0xba), q(0xbb), q(0xbc), q(0xbd), q(0xbe), q(0xbf),\ + q(0xc0), q(0xc1), q(0xc2), q(0xc3), q(0xc4), q(0xc5), q(0xc6), q(0xc7),\ + q(0xc8), q(0xc9), q(0xca), q(0xcb), q(0xcc), q(0xcd), q(0xce), q(0xcf),\ + q(0xd0), q(0xd1), q(0xd2), q(0xd3), q(0xd4), q(0xd5), q(0xd6), q(0xd7),\ + q(0xd8), q(0xd9), q(0xda), q(0xdb), q(0xdc), q(0xdd), q(0xde), q(0xdf),\ + q(0xe0), q(0xe1), q(0xe2), q(0xe3), q(0xe4), q(0xe5), q(0xe6), q(0xe7),\ + q(0xe8), q(0xe9), q(0xea), q(0xeb), q(0xec), q(0xed), q(0xee), q(0xef),\ + q(0xf0), q(0xf1), q(0xf2), q(0xf3), q(0xf4), q(0xf5), q(0xf6), q(0xf7),\ + q(0xf8), q(0xf9), q(0xfa), q(0xfb), q(0xfc), q(0xfd), q(0xfe), q(0xff) } + +/* given the value i in 0..255 as the byte overflow when a a field */ +/* element in GHASH is multipled by x^8, this function will return */ +/* the values that are generated in the lo 16-bit word of the field */ +/* value by applying the modular polynomial. The values lo_byte and */ +/* hi_byte are returned via the macro xp_fun(lo_byte, hi_byte) so */ +/* that the values can be assembled into memory as required by a */ +/* suitable definition of this macro operating on the table above */ + +#define xp(i) xp_fun( \ + (i & 0x80 ? 0xe1 : 0) ^ (i & 0x40 ? 0x70 : 0) ^ \ + (i & 0x20 ? 0x38 : 0) ^ (i & 0x10 ? 0x1c : 0) ^ \ + (i & 0x08 ? 0x0e : 0) ^ (i & 0x04 ? 0x07 : 0) ^ \ + (i & 0x02 ? 0x03 : 0) ^ (i & 0x01 ? 0x01 : 0), \ + (i & 0x80 ? 0x00 : 0) ^ (i & 0x40 ? 0x80 : 0) ^ \ + (i & 0x20 ? 0x40 : 0) ^ (i & 0x10 ? 0x20 : 0) ^ \ + (i & 0x08 ? 0x10 : 0) ^ (i & 0x04 ? 0x08 : 0) ^ \ + (i & 0x02 ? 0x84 : 0) ^ (i & 0x01 ? 0xc2 : 0) ) + +#define xp64(i) xp_fun( \ + (i & 0x80 ? 0xd8 : 0) ^ (i & 0x40 ? 0x6c : 0) ^ \ + (i & 0x20 ? 0x36 : 0) ^ (i & 0x10 ? 0x1b : 0) ^ \ + (i & 0x08 ? 0x0d : 0) ^ (i & 0x04 ? 0x06 : 0) ^ \ + (i & 0x02 ? 0x03 : 0) ^ (i & 0x01 ? 0x01 : 0), \ + (i & 0x80 ? 0x00 : 0) ^ (i & 0x40 ? 0x00 : 0) ^ \ + (i & 0x20 ? 0x00 : 0) ^ (i & 0x10 ? 0x00 : 0) ^ \ + (i & 0x08 ? 0x80 : 0) ^ (i & 0x04 ? 0xc0 : 0) ^ \ + (i & 0x02 ? 0x60 : 0) ^ (i & 0x01 ? 0xb0 : 0) ) + +static mode(32t) gf_poly[2] = { 0, 0xe1000000 }; +static mode(32t) gf_poly64[2] = { 0, 0xd8000000 }; + +/* Multiply of a GF128 field element by x. The field element */ +/* is held in an array of bytes in which field bits 8n..8n + 7 */ +/* are held in byte[n], with lower indexed bits placed in the */ +/* more numerically significant bit positions in bytes. */ + +/* This function multiples a field element x, in the polynomial */ +/* field representation. It uses 32-bit word operations to gain */ +/* speed but compensates for machine endianess and hence works */ +/* correctly on both styles of machine */ + +in_line void mul_x(mode(32t) x[4]) +{ mode(32t) t; + + bsw_32(x, 4); + + /* at this point the filed element bits 0..127 are set out */ + /* as follows in 32-bit words (where the most significant */ + /* (ms) numeric bits are to the left) */ + /* */ + /* x[0] x[1] x[2] x[3] */ + /* ms ls ms ls ms ls ms ls */ + /* field: 0 ... 31 32 .. 63 64 .. 95 96 .. 127 */ + + t = gf_poly[x[3] & 1]; /* bit 127 of the element */ + x[3] = (x[3] >> 1) | (x[2] << 31); /* shift bits up by one */ + x[2] = (x[2] >> 1) | (x[1] << 31); /* position */ + x[1] = (x[1] >> 1) | (x[0] << 31); /* if bit 7 is 1 xor in */ + x[0] = (x[0] >> 1) ^ t; /* the field polynomial */ + bsw_32(x, 4); +} + +in_line void mul_x64(mode(32t) x[2]) +{ mode(32t) t; + + bsw_32(x, 2); + + /* at this point the filed element bits 0..127 are set out */ + /* as follows in 32-bit words (where the most significant */ + /* (ms) numeric bits are to the left) */ + /* */ + /* x[0] x[1] x[2] x[3] */ + /* ms ls ms ls ms ls ms ls */ + /* field: 0 ... 31 32 .. 63 64 .. 95 96 .. 127 */ + + t = gf_poly64[x[1] & 1]; /* bit 127 of the element */ + /* shift bits up by one */ + /* position */ + x[1] = (x[1] >> 1) | (x[0] << 31); /* if bit 7 is 1 xor in */ + x[0] = (x[0] >> 1) ^ t; /* the field polynomial */ + bsw_32(x, 2); +} + +/* Multiply of a GF128 field element by x^8 using 32-bit words */ +/* for speed - machine endianess matters here */ + +#if (PLATFORM_BYTE_ORDER == BRG_LITTLE_ENDIAN) + +#define xp_fun(x,y) ((mode(32t))(x)) | (((mode(32t))(y)) << 8) +static const unsigned __int16 gft_le[256] = gf_dat(xp); +static const unsigned __int16 gft_le64[256] = gf_dat(xp64); + +in_line void mul_lex8(mode(32t) x[4]) /* mutiply with long words */ +{ mode(32t) t = (x[3] >> 24); /* in little endian format */ + x[3] = (x[3] << 8) | (x[2] >> 24); + x[2] = (x[2] << 8) | (x[1] >> 24); + x[1] = (x[1] << 8) | (x[0] >> 24); + x[0] = (x[0] << 8) ^ gft_le[t]; +} + +in_line void mul_lex8_64(mode(32t) x[2]) /* mutiply with long words */ +{ mode(32t) t = (x[1] >> 24); /* in little endian format */ + x[1] = (x[1] << 8) | (x[0] >> 24); + x[0] = (x[0] << 8) ^ gft_le64[t]; +} + +#endif + +#if 1 || (PLATFORM_BYTE_ORDER == BRG_LITTLE_ENDIAN) + +#undef xp_fun +#define xp_fun(x,y) ((mode(32t))(y)) | (((mode(32t))(x)) << 8) +static const unsigned __int16 gft_be[256] = gf_dat(xp); +static const unsigned __int16 gft_be64[256] = gf_dat(xp64); + +in_line void mul_bex8(mode(32t) x[4]) /* mutiply with long words */ +{ mode(32t) t = (x[3] & 0xff); /* in big endian format */ + x[3] = (x[3] >> 8) | (x[2] << 24); + x[2] = (x[2] >> 8) | (x[1] << 24); + x[1] = (x[1] >> 8) | (x[0] << 24); + x[0] = (x[0] >> 8) ^ (((mode(32t))gft_be[t]) << 16); +} + +in_line void mul_bex8_64(mode(32t) x[2]) /* mutiply with long words */ +{ mode(32t) t = (x[1] & 0xff); /* in big endian format */ + x[1] = (x[1] >> 8) | (x[0] << 24); + x[0] = (x[0] >> 8) ^ (((mode(32t))gft_be64[t]) << 16); +} + +#endif + +/* hence choose the correct version for the machine endianess */ + +#if PLATFORM_BYTE_ORDER == BRG_BIG_ENDIAN +#define mul_x8 mul_bex8 +#define mul_x8_64 mul_bex8_64 +#else +#define mul_x8 mul_lex8 +#define mul_x8_64 mul_lex8_64 +#endif + +/* different versions of the general gf_mul function are provided */ +/* here. Sadly none are very fast :-( */ + +void GfMul128 (void *a, const void* b) +{ mode(32t) r[CBLK_LEN >> 2], p[8][CBLK_LEN >> 2]; + int i; + + move_block_aligned(p[0], b); + bsw_32(p[0], 4); + for(i = 0; i < 7; ++i) + { + p[i + 1][3] = (p[i][3] >> 1) | (p[i][2] << 31); + p[i + 1][2] = (p[i][2] >> 1) | (p[i][1] << 31); + p[i + 1][1] = (p[i][1] >> 1) | (p[i][0] << 31); + p[i + 1][0] = (p[i][0] >> 1) ^ gf_poly[p[i][3] & 1]; + } + + memset(r, 0, CBLK_LEN); + for(i = 0; i < 16; ++i) + { + if(i) mul_bex8(r); /* order is always big endian here */ + + if(((unsigned char*)a)[15 - i] & 0x80) + xor_block_aligned(r, p[0]); + if(((unsigned char*)a)[15 - i] & 0x40) + xor_block_aligned(r, p[1]); + if(((unsigned char*)a)[15 - i] & 0x20) + xor_block_aligned(r, p[2]); + if(((unsigned char*)a)[15 - i] & 0x10) + xor_block_aligned(r, p[3]); + if(((unsigned char*)a)[15 - i] & 0x08) + xor_block_aligned(r, p[4]); + if(((unsigned char*)a)[15 - i] & 0x04) + xor_block_aligned(r, p[5]); + if(((unsigned char*)a)[15 - i] & 0x02) + xor_block_aligned(r, p[6]); + if(((unsigned char*)a)[15 - i] & 0x01) + xor_block_aligned(r, p[7]); + } + bsw_32(r, 4); + move_block_aligned(a, r); +} + +#if defined( UNROLL_LOOPS ) + +#define xor_8k(i) \ + xor_block_aligned(r, ctx->gf_t8k[i + i][a[i] & 15]); \ + xor_block_aligned(r, ctx->gf_t8k[i + i + 1][a[i] >> 4]) + + +void GfMul128Tab (unsigned char a[CBLK_LEN], GfCtx8k *ctx) +{ unsigned __int32 r[CBLK_LEN >> 2]; + + move_block_aligned(r, ctx->gf_t8k[0][a[0] & 15]); + xor_block_aligned(r, ctx->gf_t8k[1][a[0] >> 4]); + xor_8k( 1); xor_8k( 2); xor_8k( 3); + xor_8k( 4); xor_8k( 5); xor_8k( 6); xor_8k( 7); + xor_8k( 8); xor_8k( 9); xor_8k(10); xor_8k(11); + xor_8k(12); xor_8k(13); xor_8k(14); xor_8k(15); + move_block_aligned(a, r); +} + +#else + +void GfMul128Tab (unsigned char a[CBLK_LEN], GfCtx8k *ctx) +{ unsigned __int32 r[CBLK_LEN >> 2], *p; + int i; + + p = ctx->gf_t8k[0][a[0] & 15]; + memcpy(r, p, CBLK_LEN); + p = ctx->gf_t8k[1][a[0] >> 4]; + xor_block_aligned(r, p); + for(i = 1; i < CBLK_LEN; ++i) + { + xor_block_aligned(r, ctx->gf_t8k[i + i][a[i] & 15]); + xor_block_aligned(r, ctx->gf_t8k[i + i + 1][a[i] >> 4]); + } + memcpy(a, r, CBLK_LEN); +} + +#endif + +void compile_8k_table(unsigned __int8 *a, GfCtx8k *ctx) +{ int i, j, k; + + memset(ctx->gf_t8k, 0, 32 * 16 * 16); + for(i = 0; i < 2 * CBLK_LEN; ++i) + { + if(i == 0) + { + memcpy(ctx->gf_t8k[1][8], a, CBLK_LEN); + for(j = 4; j > 0; j >>= 1) + { + memcpy(ctx->gf_t8k[1][j], ctx->gf_t8k[1][j + j], CBLK_LEN); + mul_x(ctx->gf_t8k[1][j]); + } + memcpy(ctx->gf_t8k[0][8], ctx->gf_t8k[1][1], CBLK_LEN); + mul_x(ctx->gf_t8k[0][8]); + for(j = 4; j > 0; j >>= 1) + { + memcpy(ctx->gf_t8k[0][j], ctx->gf_t8k[0][j + j], CBLK_LEN); + mul_x(ctx->gf_t8k[0][j]); + } + } + else if(i > 1) + for(j = 8; j > 0; j >>= 1) + { + memcpy(ctx->gf_t8k[i][j], ctx->gf_t8k[i - 2][j], CBLK_LEN); + mul_x8(ctx->gf_t8k[i][j]); + } + + for(j = 2; j < 16; j += j) + { + mode(32t) *pj = ctx->gf_t8k[i][j]; + mode(32t) *pk = ctx->gf_t8k[i][1]; + mode(32t) *pl = ctx->gf_t8k[i][j + 1]; + + for(k = 1; k < j; ++k) + { + *pl++ = pj[0] ^ *pk++; + *pl++ = pj[1] ^ *pk++; + *pl++ = pj[2] ^ *pk++; + *pl++ = pj[3] ^ *pk++; + } + } + } +} + + +void compile_4k_table64(unsigned __int8 *a, GfCtx4k64 *ctx) +{ int i, j, k; + + memset(ctx->gf_t4k, 0, sizeof(ctx->gf_t4k)); + for(i = 0; i < 2 * CBLK_LEN8; ++i) + { + if(i == 0) + { + memcpy(ctx->gf_t4k[1][8], a, CBLK_LEN8); + for(j = 4; j > 0; j >>= 1) + { + memcpy(ctx->gf_t4k[1][j], ctx->gf_t4k[1][j + j], CBLK_LEN8); + mul_x64(ctx->gf_t4k[1][j]); + } + memcpy(ctx->gf_t4k[0][8], ctx->gf_t4k[1][1], CBLK_LEN8); + mul_x64(ctx->gf_t4k[0][8]); + for(j = 4; j > 0; j >>= 1) + { + memcpy(ctx->gf_t4k[0][j], ctx->gf_t4k[0][j + j], CBLK_LEN8); + mul_x64(ctx->gf_t4k[0][j]); + } + } + else if(i > 1) + for(j = 8; j > 0; j >>= 1) + { + memcpy(ctx->gf_t4k[i][j], ctx->gf_t4k[i - 2][j], CBLK_LEN8); + mul_x8_64(ctx->gf_t4k[i][j]); + } + + for(j = 2; j < 16; j += j) + { + mode(32t) *pj = ctx->gf_t4k[i][j]; + mode(32t) *pk = ctx->gf_t4k[i][1]; + mode(32t) *pl = ctx->gf_t4k[i][j + 1]; + + for(k = 1; k < j; ++k) + { + *pl++ = pj[0] ^ *pk++; + *pl++ = pj[1] ^ *pk++; + *pl++ = pj[2] ^ *pk++; + *pl++ = pj[3] ^ *pk++; + } + } + } +} + +static int IsBitSet128 (unsigned int bit, unsigned __int8 *a) +{ + return a[(127 - bit) / 8] & (0x80 >> ((127 - bit) % 8)); +} + +static int IsBitSet64 (unsigned int bit, unsigned __int8 *a) +{ + return a[(63 - bit) / 8] & (0x80 >> ((63 - bit) % 8)); +} + +static void SetBit128 (unsigned int bit, unsigned __int8 *a) +{ + a[(127 - bit) / 8] |= 0x80 >> ((127 - bit) % 8); +} + +static void SetBit64 (unsigned int bit, unsigned __int8 *a) +{ + a[(63 - bit) / 8] |= 0x80 >> ((63 - bit) % 8); +} + +void MirrorBits128 (unsigned __int8 *a) +{ + unsigned __int8 t[128 / 8]; + int i; + memset (t,0,16); + for (i = 0; i < 128; i++) + { + if (IsBitSet128(i, a)) + SetBit128 (127 - i, t); + } + memcpy (a, t, sizeof (t)); + burn (t,sizeof (t)); +} + +void MirrorBits64 (unsigned __int8 *a) +{ + unsigned __int8 t[64 / 8]; + int i; + memset (t,0,8); + for (i = 0; i < 64; i++) + { + if (IsBitSet64(i, a)) + SetBit64 (63 - i, t); + } + memcpy (a, t, sizeof (t)); + burn (t,sizeof (t)); +} + +/* Allocate and initialize speed optimization table + for multiplication by 64-bit operand in MSB-first mode */ +int Gf128Tab64Init (unsigned __int8 *a, GfCtx *ctx) +{ + GfCtx8k *ctx8k; + unsigned __int8 am[16]; + int i, j; + + ctx8k = (GfCtx8k *) TCalloc (sizeof (GfCtx8k)); + if (!ctx8k) + return FALSE; + + memcpy (am, a, 16); + MirrorBits128 (am); + compile_8k_table (am, ctx8k); + + /* Convert 8k LSB-first table to 4k MSB-first */ + for (i = 16; i < 32; i++) + { + for (j = 0; j < 16; j++) + { + int jm = 0; + jm |= (j & 0x1) << 3; + jm |= (j & 0x2) << 1; + jm |= (j & 0x4) >> 1; + jm |= (j & 0x8) >> 3; + + memcpy (&ctx->gf_t128[i-16][jm], (unsigned char *)&ctx8k->gf_t8k[31-i][j], 16); + MirrorBits128 ((unsigned char *)&ctx->gf_t128[i-16][jm]); + } + } + + burn (ctx8k ,sizeof (*ctx8k)); + burn (am, sizeof (am)); + TCfree (ctx8k); + return TRUE; +} + + +#define xor_8kt64(i) \ + xor_block_aligned(r, ctx->gf_t128[i + i][a[i] & 15]); \ + xor_block_aligned(r, ctx->gf_t128[i + i + 1][a[i] >> 4]) + +/* Multiply a 128-bit number by a 64-bit number in the finite field GF(2^128) */ +void Gf128MulBy64Tab (unsigned __int8 a[8], unsigned __int8 p[16], GfCtx *ctx) +{ + unsigned __int32 r[CBLK_LEN >> 2]; + + move_block_aligned(r, ctx->gf_t128[7*2][a[7] & 15]); + xor_block_aligned(r, ctx->gf_t128[7*2+1][a[7] >> 4]); + + if (*(unsigned __int16 *)a) + { + xor_8kt64(0); + xor_8kt64(1); + } + if (a[2]) + { + xor_8kt64(2); + } + xor_8kt64(3); + xor_8kt64(4); + xor_8kt64(5); + xor_8kt64(6); + + move_block_aligned(p, r); +} + + + +/* Basic algorithms for testing of optimized algorithms */ + +static void xor128 (uint64 *a, uint64 *b) +{ + *a++ ^= *b++; + *a ^= *b; +} + +static void shl128 (unsigned __int8 *a) +{ + int i, x = 0, xx; + for (i = 15; i >= 0; i--) + { + xx = (a[i] & 0x80) >> 7; + a[i] = (char) ((a[i] << 1) | x); + x = xx; + } +} + +static void GfMul128Basic (unsigned __int8 *a, unsigned __int8 *b, unsigned __int8 *p) +{ + int i; + unsigned __int8 la[16]; + memcpy (la, a, 16); + memset (p, 0, 16); + + for (i = 0; i < 128; i++) + { + if (IsBitSet128 (i, b)) + xor128 ((uint64 *)p, (uint64 *)la); + + if (la[0] & 0x80) + { + shl128 (la); + la[15] ^= 0x87; + } + else + { + shl128 (la); + } + } +} + + +BOOL GfMulSelfTest () +{ + BOOL result = TRUE; + unsigned __int8 a[16]; + unsigned __int8 b[16]; + unsigned __int8 p1[16]; + unsigned __int8 p2[16]; + GfCtx *gfCtx = (GfCtx *) TCalloc (sizeof (GfCtx)); + int i, j; + + if (!gfCtx) + return FALSE; + + + /* GF(2^128) */ + for (i = 0; i < 0x100; i++) + { + for (j = 0; j < 16; j++) + { + a[j] = (unsigned __int8) i; + b[j] = j < 8 ? 0 : a[j] ^ 0xff; + } + + GfMul128Basic (a, b, p1); + + Gf128Tab64Init (a, gfCtx); + Gf128MulBy64Tab (b + 8, p2, gfCtx); + + if (memcmp (p1, p2, 16) != 0) + result = FALSE; + } + + TCfree (gfCtx); + return result; +} + +#if defined(__cplusplus) +} +#endif diff --git a/src/Common/GfMul.h b/src/Common/GfMul.h index 12dc864f..bc1ab435 100644 --- a/src/Common/GfMul.h +++ b/src/Common/GfMul.h @@ -1,74 +1,74 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 2003, Dr Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software is allowed (with or without - changes) provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue Date: 31/01/2004 -*/ - -/* Adapted for TrueCrypt */ - -#ifndef _GCM_H -#define _GCM_H - -#include "Tcdefs.h" - -#if defined(__cplusplus) -extern "C" -{ -#endif - -#define CBLK_LEN 16 /* encryption block length */ -#define CBLK_LEN8 8 - -typedef struct -{ - unsigned __int32 gf_t8k[CBLK_LEN * 2][16][CBLK_LEN / 4]; -} GfCtx8k; - -typedef struct -{ - unsigned __int32 gf_t4k[CBLK_LEN8 * 2][16][CBLK_LEN / 4]; -} GfCtx4k64; - -typedef struct -{ - /* union not used to support faster mounting */ - unsigned __int32 gf_t128[CBLK_LEN * 2 / 2][16][CBLK_LEN / 4]; - unsigned __int32 gf_t64[CBLK_LEN8 * 2][16][CBLK_LEN8 / 4]; -} GfCtx; - -typedef int ret_type; - -void GfMul128 (void *a, const void* b); -void GfMul128Tab(unsigned char a[16], GfCtx8k *ctx); -int Gf128Tab64Init (unsigned __int8 *a, GfCtx *ctx); -void Gf128MulBy64Tab (unsigned __int8 a[8], unsigned __int8 p[16], GfCtx *ctx); -void MirrorBits128 (unsigned __int8 *a); -void MirrorBits64 (unsigned __int8 *a); -BOOL GfMulSelfTest (); - -#if defined(__cplusplus) -} -#endif - -#endif +/* + --------------------------------------------------------------------------- + Copyright (c) 2003, Dr Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software is allowed (with or without + changes) provided that: + + 1. source code distributions include the above copyright notice, this + list of conditions and the following disclaimer; + + 2. binary distributions include the above copyright notice, this list + of conditions and the following disclaimer in their documentation; + + 3. the name of the copyright holder is not used to endorse products + built using this software without specific written permission. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + Issue Date: 31/01/2004 +*/ + +/* Adapted for TrueCrypt */ + +#ifndef _GCM_H +#define _GCM_H + +#include "Tcdefs.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif + +#define CBLK_LEN 16 /* encryption block length */ +#define CBLK_LEN8 8 + +typedef struct +{ + unsigned __int32 gf_t8k[CBLK_LEN * 2][16][CBLK_LEN / 4]; +} GfCtx8k; + +typedef struct +{ + unsigned __int32 gf_t4k[CBLK_LEN8 * 2][16][CBLK_LEN / 4]; +} GfCtx4k64; + +typedef struct +{ + /* union not used to support faster mounting */ + unsigned __int32 gf_t128[CBLK_LEN * 2 / 2][16][CBLK_LEN / 4]; + unsigned __int32 gf_t64[CBLK_LEN8 * 2][16][CBLK_LEN8 / 4]; +} GfCtx; + +typedef int ret_type; + +void GfMul128 (void *a, const void* b); +void GfMul128Tab(unsigned char a[16], GfCtx8k *ctx); +int Gf128Tab64Init (unsigned __int8 *a, GfCtx *ctx); +void Gf128MulBy64Tab (unsigned __int8 a[8], unsigned __int8 p[16], GfCtx *ctx); +void MirrorBits128 (unsigned __int8 *a); +void MirrorBits64 (unsigned __int8 *a); +BOOL GfMulSelfTest (); + +#if defined(__cplusplus) +} +#endif + +#endif diff --git a/src/Common/Inflate.c b/src/Common/Inflate.c index bf850e79..2d8c96b6 100644 --- a/src/Common/Inflate.c +++ b/src/Common/Inflate.c @@ -1,1321 +1,1321 @@ -/* inflate.c -- put in the public domain by Mark Adler */ - -/* Decompresses raw data compressed using the DEFLATE algorithm (RFC 1951) */ - -/* You can do whatever you like with this source file, though I would - prefer that if you modify it and redistribute it that you include - comments to that effect with your name and the date. Thank you. - - History: - vers date who what - ---- --------- -------------- ------------------------------------ - a ~~ Feb 92 M. Adler used full (large, one-step) lookup table - b1 21 Mar 92 M. Adler first version with partial lookup tables - b2 21 Mar 92 M. Adler fixed bug in fixed-code blocks - b3 22 Mar 92 M. Adler sped up match copies, cleaned up some - b4 25 Mar 92 M. Adler added prototypes; removed window[] (now - is the responsibility of unzip.h--also - changed name to slide[]), so needs diffs - for unzip.c and unzip.h (this allows - compiling in the small model on MSDOS); - fixed cast of q in huft_build(); - b5 26 Mar 92 M. Adler got rid of unintended macro recursion. - b6 27 Mar 92 M. Adler got rid of nextbyte() routine. fixed - bug in inflate_fixed(). - c1 30 Mar 92 M. Adler removed lbits, dbits environment variables. - changed BMAX to 16 for explode. Removed - OUTB usage, and replaced it with flush()-- - this was a 20% speed improvement! Added - an explode.c (to replace unimplod.c) that - uses the huft routines here. Removed - register union. - c2 4 Apr 92 M. Adler fixed bug for file sizes a multiple of 32k. - c3 10 Apr 92 M. Adler reduced memory of code tables made by - huft_build significantly (factor of two to - three). - c4 15 Apr 92 M. Adler added NOMEMCPY do kill use of memcpy(). - worked around a Turbo C optimization bug. - c5 21 Apr 92 M. Adler added the WSIZE #define to allow reducing - the 32K window size for specialized - applications. - c6 31 May 92 M. Adler added some typecasts to eliminate warnings - c7 27 Jun 92 G. Roelofs added some more typecasts (444: MSC bug). - c8 5 Oct 92 J-l. Gailly added ifdef'd code to deal with PKZIP bug. - c9 9 Oct 92 M. Adler removed a memory error message (~line 416). - c10 17 Oct 92 G. Roelofs changed ULONG/UWORD/byte to ulg/ush/uch, - removed old inflate, renamed inflate_entry - to inflate, added Mark's fix to a comment. - c10.5 14 Dec 92 M. Adler fix up error messages for incomplete trees. - c11 2 Jan 93 M. Adler fixed bug in detection of incomplete - tables, and removed assumption that EOB is - the longest code (bad assumption). - c12 3 Jan 93 M. Adler make tables for fixed blocks only once. - c13 5 Jan 93 M. Adler allow all zero length codes (pkzip 2.04c - outputs one zero length code for an empty - distance tree). - c14 12 Mar 93 M. Adler made inflate.c standalone with the - introduction of inflate.h. - c14b 16 Jul 93 G. Roelofs added (unsigned) typecast to w at 470. - c14c 19 Jul 93 J. Bush changed v[N_MAX], l[288], ll[28x+3x] arrays - to static for Amiga. - c14d 13 Aug 93 J-l. Gailly de-complicatified Mark's c[*p++]++ thing. - c14e 8 Oct 93 G. Roelofs changed memset() to memzero(). - c14f 22 Oct 93 G. Roelofs renamed quietflg to qflag; made Trace() - conditional; added inflate_free(). - c14g 28 Oct 93 G. Roelofs changed l/(lx+1) macro to pointer (Cray bug) - c14h 7 Dec 93 C. Ghisler huft_build() optimizations. - c14i 9 Jan 94 A. Verheijen set fixed_t{d,l} to NULL after freeing; - G. Roelofs check NEXTBYTE macro for EOF. - c14j 23 Jan 94 G. Roelofs removed Ghisler "optimizations"; ifdef'd - EOF check. - c14k 27 Feb 94 G. Roelofs added some typecasts to avoid warnings. - c14l 9 Apr 94 G. Roelofs fixed split comments on preprocessor lines - to avoid bug in Encore compiler. - c14m 7 Jul 94 P. Kienitz modified to allow assembler version of - inflate_codes() (define ASM_INFLATECODES) - c14n 22 Jul 94 G. Roelofs changed fprintf to macro for DLL versions - c14o 23 Aug 94 C. Spieler added a newline to a debug statement; - G. Roelofs added another typecast to avoid MSC warning - c14p 4 Oct 94 G. Roelofs added (voidp *) cast to free() argument - c14q 30 Oct 94 G. Roelofs changed fprintf macro to MESSAGE() - c14r 1 Nov 94 G. Roelofs fixed possible redefinition of CHECK_EOF - c14s 7 May 95 S. Maxwell OS/2 DLL globals stuff incorporated; - P. Kienitz "fixed" ASM_INFLATECODES macro/prototype - c14t 18 Aug 95 G. Roelofs added inflate() to use zlib functions; - changed voidp to zvoid; moved huft_build() - and huft_free() to end of file - c14u 1 Oct 95 G. Roelofs moved G into definition of MESSAGE macro - c14v 8 Nov 95 P. Kienitz changed ASM_INFLATECODES to use a regular - call with __G__ instead of a macro - c15 3 Aug 96 M. Adler fixed bomb-bug on random input data (Adobe) - c15b 24 Aug 96 M. Adler more fixes for random input data - c15c 28 Mar 97 G. Roelofs changed USE_ZLIB fatal exit code from - PK_MEM2 to PK_MEM3 - c16 20 Apr 97 J. Altman added memzero(v[]) in huft_build() - c16b 29 Mar 98 C. Spieler modified DLL code for slide redirection - - fork 12 Dec 07 Adapted for TrueCrypt - */ - - -/* - Inflate deflated (PKZIP's method 8 compressed) data. The compression - method searches for as much of the current string of bytes (up to a - length of 258) in the previous 32K bytes. If it doesn't find any - matches (of at least length 3), it codes the next byte. Otherwise, it - codes the length of the matched string and its distance backwards from - the current position. There is a single Huffman code that codes both - single bytes (called "literals") and match lengths. A second Huffman - code codes the distance information, which follows a length code. Each - length or distance code actually represents a base value and a number - of "extra" (sometimes zero) bits to get to add to the base value. At - the end of each deflated block is a special end-of-block (EOB) literal/ - length code. The decoding process is basically: get a literal/length - code; if EOB then done; if a literal, emit the decoded byte; if a - length then get the distance and emit the referred-to bytes from the - sliding window of previously emitted data. - - There are (currently) three kinds of inflate blocks: stored, fixed, and - dynamic. The compressor outputs a chunk of data at a time and decides - which method to use on a chunk-by-chunk basis. A chunk might typically - be 32K to 64K, uncompressed. If the chunk is uncompressible, then the - "stored" method is used. In this case, the bytes are simply stored as - is, eight bits per byte, with none of the above coding. The bytes are - preceded by a count, since there is no longer an EOB code. - - If the data are compressible, then either the fixed or dynamic methods - are used. In the dynamic method, the compressed data are preceded by - an encoding of the literal/length and distance Huffman codes that are - to be used to decode this block. The representation is itself Huffman - coded, and so is preceded by a description of that code. These code - descriptions take up a little space, and so for small blocks, there is - a predefined set of codes, called the fixed codes. The fixed method is - used if the block ends up smaller that way (usually for quite small - chunks); otherwise the dynamic method is used. In the latter case, the - codes are customized to the probabilities in the current block and so - can code it much better than the pre-determined fixed codes can. - - The Huffman codes themselves are decoded using a multi-level table - lookup, in order to maximize the speed of decoding plus the speed of - building the decoding tables. See the comments below that precede the - lbits and dbits tuning parameters. - - GRR: return values(?) - 0 OK - 1 incomplete table - 2 bad input - 3 not enough memory - */ - - -/* - Notes beyond the 1.93a appnote.txt: - - 1. Distance pointers never point before the beginning of the output - stream. - 2. Distance pointers can point back across blocks, up to 32k away. - 3. There is an implied maximum of 7 bits for the bit length table and - 15 bits for the actual data. - 4. If only one code exists, then it is encoded using one bit. (Zero - would be more efficient, but perhaps a little confusing.) If two - codes exist, they are coded using one bit each (0 and 1). - 5. There is no way of sending zero distance codes--a dummy must be - sent if there are none. (History: a pre 2.0 version of PKZIP would - store blocks with no distance codes, but this was discovered to be - too harsh a criterion.) Valid only for 1.93a. 2.04c does allow - zero distance codes, which is sent as one code of zero bits in - length. - 6. There are up to 286 literal/length codes. Code 256 represents the - end-of-block. Note however that the static length tree defines - 288 codes just to fill out the Huffman codes. Codes 286 and 287 - cannot be used though, since there is no length base or extra bits - defined for them. Similarily, there are up to 30 distance codes. - However, static trees define 32 codes (all 5 bits) to fill out the - Huffman codes, but the last two had better not show up in the data. - 7. Unzip can check dynamic Huffman blocks for complete code sets. - The exception is that a single code would not be complete (see #4). - 8. The five bits following the block type is really the number of - literal codes sent minus 257. - 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits - (1+6+6). Therefore, to output three times the length, you output - three codes (1+1+1), whereas to output four times the same length, - you only need two codes (1+3). Hmm. - 10. In the tree reconstruction algorithm, Code = Code + Increment - only if BitLength(i) is not zero. (Pretty obvious.) - 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19) - 12. Note: length code 284 can represent 227-258, but length code 285 - really is 258. The last length deserves its own, short code - since it gets used a lot in very redundant files. The length - 258 is special since 258 - 3 (the min match length) is 255. - 13. The literal/length and distance code bit lengths are read as a - single stream of lengths. It is possible (and advantageous) for - a repeat code (16, 17, or 18) to go across the boundary between - the two sets of lengths. - */ - - -/* #define DEBUG */ -#define INFMOD /* tell inflate.h to include code to be compiled */ -#include "inflate.h" - - -#ifndef WSIZE /* default is 32K */ -# define WSIZE 0x8000 /* window size--must be a power of two, and at least */ -#endif /* 32K for zip's deflate method */ - -#if (defined(DLL) && !defined(NO_SLIDE_REDIR)) -# define wsize G._wsize /* wsize is a variable */ -#else -# define wsize WSIZE /* wsize is a constant */ -#endif - - -#ifndef NEXTBYTE /* default is to simply get a byte from stdin */ -# define NEXTBYTE getchar() -#endif - -#ifndef MESSAGE /* only used twice, for fixed strings--NOT general-purpose */ -# define MESSAGE(str,len,flag) fprintf(stderr,(char *)(str)) -#endif - -#ifndef FLUSH /* default is to simply write the buffer to stdout */ -# define FLUSH(n) fwrite(redirSlide, 1, n, stdout) /* return value not used */ -#endif -/* Warning: the fwrite above might not work on 16-bit compilers, since - 0x8000 might be interpreted as -32,768 by the library function. */ - -#ifndef Trace -# ifdef DEBUG -# define Trace(x) fprintf x -# else -# define Trace(x) -# endif -#endif - -G_struct G; -uch redirSlide [WSIZE]; - -/*---------------------------------------------------------------------------*/ -#ifdef USE_ZLIB - - -/* - GRR: return values for both original inflate() and inflate() - 0 OK - 1 incomplete table(?) - 2 bad input - 3 not enough memory - */ - -/**************************/ -/* Function inflate() */ -/**************************/ - -int inflate(__G) /* decompress an inflated entry using the zlib routines */ - __GDEF -{ - int err=Z_OK; - -#if (defined(DLL) && !defined(NO_SLIDE_REDIR)) - if (G.redirect_slide) - wsize = G.redirect_size, redirSlide = G.redirect_buffer; - else - wsize = WSIZE, redirSlide = slide; -#endif - - G.dstrm.next_out = redirSlide; - G.dstrm.avail_out = wsize; - - G.dstrm.next_in = G.inptr; - G.dstrm.avail_in = G.incnt; - - if (!G.inflInit) { - unsigned i; - int windowBits; - - /* only need to test this stuff once */ - if (zlib_version[0] != ZLIB_VERSION[0]) { - Info(slide, 0x21, ((char *)slide, - "error: incompatible zlib version (expected %s, found %s)\n", - ZLIB_VERSION, zlib_version)); - return 3; - } else if (strcmp(zlib_version, ZLIB_VERSION) != 0) - Info(slide, 0x21, ((char *)slide, - "warning: different zlib version (expected %s, using %s)\n", - ZLIB_VERSION, zlib_version)); - - /* windowBits = log2(wsize) */ - for (i = ((unsigned)wsize * 2 - 1), windowBits = 0; - !(i & 1); i >>= 1, ++windowBits); - if ((unsigned)windowBits > (unsigned)15) - windowBits = 15; - else if (windowBits < 8) - windowBits = 8; - - G.dstrm.zalloc = (alloc_func)Z_NULL; - G.dstrm.zfree = (free_func)Z_NULL; - - Trace((stderr, "initializing inflate()\n")); - err = inflateInit2(&G.dstrm, -windowBits); - - if (err == Z_MEM_ERROR) - return 3; - else if (err != Z_OK) - Trace((stderr, "oops! (inflateInit2() err = %d)\n", err)); - G.inflInit = 1; - } - -#ifdef FUNZIP - while (err != Z_STREAM_END) { -#else /* !FUNZIP */ - while (G.csize > 0) { - Trace((stderr, "first loop: G.csize = %ld\n", G.csize)); -#endif /* ?FUNZIP */ - while (G.dstrm.avail_out > 0) { - err = inflate(&G.dstrm, Z_PARTIAL_FLUSH); - - if (err == Z_DATA_ERROR) - return 2; - else if (err == Z_MEM_ERROR) - return 3; - else if (err != Z_OK && err != Z_STREAM_END) - Trace((stderr, "oops! (inflate(first loop) err = %d)\n", err)); - -#ifdef FUNZIP - if (err == Z_STREAM_END) /* "END-of-entry-condition" ? */ -#else /* !FUNZIP */ - if (G.csize <= 0L) /* "END-of-entry-condition" ? */ -#endif /* ?FUNZIP */ - break; - - if (G.dstrm.avail_in <= 0) { - if (fillinbuf(__G) == 0) - return 2; /* no "END-condition" yet, but no more data */ - - G.dstrm.next_in = G.inptr; - G.dstrm.avail_in = G.incnt; - } - Trace((stderr, " avail_in = %d\n", G.dstrm.avail_in)); - } - FLUSH(wsize - G.dstrm.avail_out); /* flush slide[] */ - Trace((stderr, "inside loop: flushing %ld bytes (ptr diff = %ld)\n", - (long)(wsize - G.dstrm.avail_out), - (long)(G.dstrm.next_out-(Bytef *)redirSlide))); - G.dstrm.next_out = redirSlide; - G.dstrm.avail_out = wsize; - } - - /* no more input, so loop until we have all output */ - Trace((stderr, "beginning final loop: err = %d\n", err)); - while (err != Z_STREAM_END) { - err = inflate(&G.dstrm, Z_PARTIAL_FLUSH); - if (err == Z_DATA_ERROR) - return 2; - else if (err == Z_MEM_ERROR) - return 3; - else if (err == Z_BUF_ERROR) { /* DEBUG */ - Trace((stderr, "zlib inflate() did not detect stream end (%s, %s)\n" - , G.zipfn, G.filename)); - break; - } else if (err != Z_OK && err != Z_STREAM_END) { - Trace((stderr, "oops! (inflate(final loop) err = %d)\n", err)); - DESTROYGLOBALS() - EXIT(PK_MEM3); - } - FLUSH(wsize - G.dstrm.avail_out); /* final flush of slide[] */ - Trace((stderr, "final loop: flushing %ld bytes (ptr diff = %ld)\n", - (long)(wsize - G.dstrm.avail_out), - (long)(G.dstrm.next_out-(Bytef *)redirSlide))); - G.dstrm.next_out = redirSlide; - G.dstrm.avail_out = wsize; - } - Trace((stderr, "total in = %ld, total out = %ld\n", G.dstrm.total_in, - G.dstrm.total_out)); - - G.inptr = (uch *)G.dstrm.next_in; - G.incnt = (G.inbuf + INBUFSIZ) - G.inptr; /* reset for other routines */ - - err = inflateReset(&G.dstrm); - if (err != Z_OK) - Trace((stderr, "oops! (inflateReset() err = %d)\n", err)); - - return 0; -} - - -/*---------------------------------------------------------------------------*/ -#else /* !USE_ZLIB */ - - -/* Function prototypes */ -#ifndef OF -# ifdef __STDC__ -# define OF(a) a -# else -# define OF(a) () -# endif -#endif /* !OF */ -int inflate_codes OF((__GPRO__ struct huft *tl, struct huft *td, - int bl, int bd)); -static int inflate_stored OF((__GPRO)); -static int inflate_fixed OF((__GPRO)); -static int inflate_dynamic OF((__GPRO)); -static int inflate_block OF((__GPRO__ int *e)); - - -/* The inflate algorithm uses a sliding 32K byte window on the uncompressed - stream to find repeated byte strings. This is implemented here as a - circular buffer. The index is updated simply by incrementing and then - and'ing with 0x7fff (32K-1). */ -/* It is left to other modules to supply the 32K area. It is assumed - to be usable as if it were declared "uch slide[32768];" or as just - "uch *slide;" and then malloc'ed in the latter case. The definition - must be in unzip.h, included above. */ - - -/* unsigned wp; moved to globals.h */ /* current position in slide */ - - -/* Tables for deflate from PKZIP's appnote.txt. */ -static ZCONST unsigned border[] = { /* Order of the bit length code lengths */ - 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; -static ZCONST ush cplens[] = { /* Copy lengths for literal codes 257..285 */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; - /* note: see note #13 above about the 258 in this list. */ -static ZCONST ush cplext[] = { /* Extra bits for literal codes 257..285 */ - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, - 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */ -static ZCONST ush cpdist[] = { /* Copy offsets for distance codes 0..29 */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577}; -static ZCONST ush cpdext[] = { /* Extra bits for distance codes */ - 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, - 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, - 12, 12, 13, 13}; - - -/* moved to consts.h (included in unzip.c), resp. funzip.c */ -#if 1 -/* And'ing with mask_bits[n] masks the lower n bits */ -ZCONST ush near mask_bits[] = { - 0x0000, - 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, - 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff -}; -#endif /* 0 */ - - -/* Macros for inflate() bit peeking and grabbing. - The usage is: - - NEEDBITS(j) - x = b & mask_bits[j]; - DUMPBITS(j) - - where NEEDBITS makes sure that b has at least j bits in it, and - DUMPBITS removes the bits from b. The macros use the variable k - for the number of bits in b. Normally, b and k are register - variables for speed and are initialized at the begining of a - routine that uses these macros from a global bit buffer and count. - - In order to not ask for more bits than there are in the compressed - stream, the Huffman tables are constructed to only ask for just - enough bits to make up the end-of-block code (value 256). Then no - bytes need to be "returned" to the buffer at the end of the last - block. See the huft_build() routine. - */ - -/* These have been moved to globals.h */ -#if 0 -ulg bb; /* bit buffer */ -unsigned bk; /* bits in bit buffer */ -#endif - -#ifndef CHECK_EOF -# define CHECK_EOF /* default as of 5.13/5.2 */ -#endif - -#ifndef CHECK_EOF -# define NEEDBITS(n) {while(k<(n)){b|=((ulg)NEXTBYTE)<>=(n);k-=(n);} - - -/* - Huffman code decoding is performed using a multi-level table lookup. - The fastest way to decode is to simply build a lookup table whose - size is determined by the longest code. However, the time it takes - to build this table can also be a factor if the data being decoded - are not very long. The most common codes are necessarily the - shortest codes, so those codes dominate the decoding time, and hence - the speed. The idea is you can have a shorter table that decodes the - shorter, more probable codes, and then point to subsidiary tables for - the longer codes. The time it costs to decode the longer codes is - then traded against the time it takes to make longer tables. - - This results of this trade are in the variables lbits and dbits - below. lbits is the number of bits the first level table for literal/ - length codes can decode in one step, and dbits is the same thing for - the distance codes. Subsequent tables are also less than or equal to - those sizes. These values may be adjusted either when all of the - codes are shorter than that, in which case the longest code length in - bits is used, or when the shortest code is *longer* than the requested - table size, in which case the length of the shortest code in bits is - used. - - There are two different values for the two tables, since they code a - different number of possibilities each. The literal/length table - codes 286 possible values, or in a flat code, a little over eight - bits. The distance table codes 30 possible values, or a little less - than five bits, flat. The optimum values for speed end up being - about one bit more than those, so lbits is 8+1 and dbits is 5+1. - The optimum values may differ though from machine to machine, and - possibly even between compilers. Your mileage may vary. - */ - -static ZCONST int lbits = 9; /* bits in base literal/length lookup table */ -static ZCONST int dbits = 6; /* bits in base distance lookup table */ - - -#ifndef ASM_INFLATECODES - -#pragma warning(disable:4131) - -int inflate_codes(__G__ tl, td, bl, bd) - __GDEF -struct huft *tl, *td; /* literal/length and distance decoder tables */ -int bl, bd; /* number of bits decoded by tl[] and td[] */ -/* inflate (decompress) the codes in a deflated (compressed) block. - Return an error code or zero if it all goes ok. */ -{ - register unsigned e; /* table entry flag/number of extra bits */ - unsigned n, d; /* length and index for copy */ - unsigned w; /* current window position */ - struct huft *t; /* pointer to table entry */ - unsigned ml, md; /* masks for bl and bd bits */ - register ulg b; /* bit buffer */ - register unsigned k; /* number of bits in bit buffer */ - - - /* make local copies of globals */ - b = G.bb; /* initialize bit buffer */ - k = G.bk; - w = G.wp; /* initialize window position */ - - - /* inflate the coded data */ - ml = mask_bits[bl]; /* precompute masks for speed */ - md = mask_bits[bd]; - while (1) /* do until end of block */ - { - NEEDBITS((unsigned)bl) - if ((e = (t = tl + ((unsigned)b & ml))->e) > 16) - do { - if (e == 99) - return 1; - DUMPBITS(t->b) - e -= 16; - NEEDBITS(e) - } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16); - DUMPBITS(t->b) - if (e == 16) /* then it's a literal */ - { - redirSlide[w++] = (uch)t->v.n; - if (w == wsize) - { - FLUSH(w); - w = 0; - } - } - else /* it's an EOB or a length */ - { - /* exit if end of block */ - if (e == 15) - break; - - /* get length of block to copy */ - NEEDBITS(e) - n = t->v.n + ((unsigned)b & mask_bits[e]); - DUMPBITS(e); - - /* decode distance of block to copy */ - NEEDBITS((unsigned)bd) - if ((e = (t = td + ((unsigned)b & md))->e) > 16) - do { - if (e == 99) - return 1; - DUMPBITS(t->b) - e -= 16; - NEEDBITS(e) - } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16); - DUMPBITS(t->b) - NEEDBITS(e) - d = w - t->v.n - ((unsigned)b & mask_bits[e]); - DUMPBITS(e) - - /* do the copy */ - do { -#if (defined(DLL) && !defined(NO_SLIDE_REDIR)) - if (G.redirect_slide) {/* &= w/ wsize unnecessary & wrong if redirect */ - if (d >= wsize) - return 1; /* invalid compressed data */ - n -= (e = (e = wsize - (d > w ? d : w)) > n ? n : e); - } - else -#endif - n -= (e = (e = wsize - ((d &= wsize-1) > w ? d : w)) > n ? n : e); -#ifndef NOMEMCPY - if (w - d >= e) /* (this test assumes unsigned comparison) */ - { - memcpy(redirSlide + w, redirSlide + d, e); - w += e; - d += e; - } - else /* do it slowly to avoid memcpy() overlap */ -#endif /* !NOMEMCPY */ - do { - redirSlide[w++] = redirSlide[d++]; - } while (--e); - if (w == wsize) - { - FLUSH(w); - w = 0; - } - } while (n); - } - } - - - /* restore the globals from the locals */ - G.wp = w; /* restore global window pointer */ - G.bb = b; /* restore global bit buffer */ - G.bk = k; - - - /* done */ - return 0; -} - -#endif /* ASM_INFLATECODES */ - - - -static int inflate_stored(__G) - __GDEF -/* "decompress" an inflated type 0 (stored) block. */ -{ - unsigned n; /* number of bytes in block */ - unsigned w; /* current window position */ - register ulg b; /* bit buffer */ - register unsigned k; /* number of bits in bit buffer */ - - - /* make local copies of globals */ - Trace((stderr, "\nstored block")); - b = G.bb; /* initialize bit buffer */ - k = G.bk; - w = G.wp; /* initialize window position */ - - - /* go to byte boundary */ - n = k & 7; - DUMPBITS(n); - - - /* get the length and its complement */ - NEEDBITS(16) - n = ((unsigned)b & 0xffff); - DUMPBITS(16) - NEEDBITS(16) - if (n != (unsigned)((~b) & 0xffff)) - return 1; /* error in compressed data */ - DUMPBITS(16) - - - /* read and output the compressed data */ - while (n--) - { - NEEDBITS(8) - redirSlide[w++] = (uch)b; - if (w == wsize) - { - FLUSH(w); - w = 0; - } - DUMPBITS(8) - } - - - /* restore the globals from the locals */ - G.wp = w; /* restore global window pointer */ - G.bb = b; /* restore global bit buffer */ - G.bk = k; - return 0; -} - - -/* Globals for literal tables (built once) */ -/* Moved to globals.h */ -#if 0 -struct huft *fixed_tl = (struct huft *)NULL; -struct huft *fixed_td; -int fixed_bl, fixed_bd; -#endif - -static int inflate_fixed(__G) - __GDEF -/* decompress an inflated type 1 (fixed Huffman codes) block. We should - either replace this with a custom decoder, or at least precompute the - Huffman tables. */ -{ - /* if first time, set up tables for fixed blocks */ - Trace((stderr, "\nliteral block")); - if (G.fixed_tl == (struct huft *)NULL) - { - int i; /* temporary variable */ - unsigned l[288]; /* length list for huft_build */ - - /* literal table */ - for (i = 0; i < 144; i++) - l[i] = 8; - for (; i < 256; i++) - l[i] = 9; - for (; i < 280; i++) - l[i] = 7; - for (; i < 288; i++) /* make a complete, but wrong code set */ - l[i] = 8; - G.fixed_bl = 7; - if ((i = huft_build(__G__ l, 288, 257, cplens, cplext, - &G.fixed_tl, &G.fixed_bl)) != 0) - { - G.fixed_tl = (struct huft *)NULL; - return i; - } - - /* distance table */ - for (i = 0; i < 30; i++) /* make an incomplete code set */ - l[i] = 5; - G.fixed_bd = 5; - if ((i = huft_build(__G__ l, 30, 0, cpdist, cpdext, - &G.fixed_td, &G.fixed_bd)) > 1) - { - huft_free(G.fixed_tl); - G.fixed_tl = (struct huft *)NULL; - return i; - } - } - - /* decompress until an end-of-block code */ - return inflate_codes(__G__ G.fixed_tl, G.fixed_td, - G.fixed_bl, G.fixed_bd) != 0; -} - - - -static int inflate_dynamic(__G) - __GDEF -/* decompress an inflated type 2 (dynamic Huffman codes) block. */ -{ - int i; /* temporary variables */ - unsigned j; - unsigned l; /* last length */ - unsigned m; /* mask for bit lengths table */ - unsigned n; /* number of lengths to get */ - struct huft *tl; /* literal/length code table */ - struct huft *td; /* distance code table */ - int bl; /* lookup bits for tl */ - int bd; /* lookup bits for td */ - unsigned nb; /* number of bit length codes */ - unsigned nl; /* number of literal/length codes */ - unsigned nd; /* number of distance codes */ -#ifdef PKZIP_BUG_WORKAROUND - unsigned ll[288+32]; /* literal/length and distance code lengths */ -#else - unsigned ll[286+30]; /* literal/length and distance code lengths */ -#endif - register ulg b; /* bit buffer */ - register unsigned k; /* number of bits in bit buffer */ - - - /* make local bit buffer */ - Trace((stderr, "\ndynamic block")); - b = G.bb; - k = G.bk; - - - /* read in table lengths */ - NEEDBITS(5) - nl = 257 + ((unsigned)b & 0x1f); /* number of literal/length codes */ - DUMPBITS(5) - NEEDBITS(5) - nd = 1 + ((unsigned)b & 0x1f); /* number of distance codes */ - DUMPBITS(5) - NEEDBITS(4) - nb = 4 + ((unsigned)b & 0xf); /* number of bit length codes */ - DUMPBITS(4) -#ifdef PKZIP_BUG_WORKAROUND - if (nl > 288 || nd > 32) -#else - if (nl > 286 || nd > 30) -#endif - return 1; /* bad lengths */ - - - /* read in bit-length-code lengths */ - for (j = 0; j < nb; j++) - { - NEEDBITS(3) - ll[border[j]] = (unsigned)b & 7; - DUMPBITS(3) - } - for (; j < 19; j++) - ll[border[j]] = 0; - - - /* build decoding table for trees--single level, 7 bit lookup */ - bl = 7; - i = huft_build(__G__ ll, 19, 19, NULL, NULL, &tl, &bl); - if (bl == 0) /* no bit lengths */ - i = 1; - if (i) - { - if (i == 1) - huft_free(tl); - return i; /* incomplete code set */ - } - - - /* read in literal and distance code lengths */ - n = nl + nd; - m = mask_bits[bl]; - i = l = 0; - while ((unsigned)i < n) - { - NEEDBITS((unsigned)bl) - j = (td = tl + ((unsigned)b & m))->b; - DUMPBITS(j) - j = td->v.n; - if (j < 16) /* length of code in bits (0..15) */ - ll[i++] = l = j; /* save last length in l */ - else if (j == 16) /* repeat last length 3 to 6 times */ - { - NEEDBITS(2) - j = 3 + ((unsigned)b & 3); - DUMPBITS(2) - if ((unsigned)i + j > n) - { - huft_free(tl); - return 1; - } - while (j--) - ll[i++] = l; - } - else if (j == 17) /* 3 to 10 zero length codes */ - { - NEEDBITS(3) - j = 3 + ((unsigned)b & 7); - DUMPBITS(3) - if ((unsigned)i + j > n) - { - huft_free(tl); - return 1; - } - while (j--) - ll[i++] = 0; - l = 0; - } - else /* j == 18: 11 to 138 zero length codes */ - { - NEEDBITS(7) - j = 11 + ((unsigned)b & 0x7f); - DUMPBITS(7) - if ((unsigned)i + j > n) - { - huft_free(tl); - return 1; - } - while (j--) - ll[i++] = 0; - l = 0; - } - } - - - /* free decoding table for trees */ - huft_free(tl); - - - /* restore the global bit buffer */ - G.bb = b; - G.bk = k; - - - /* build the decoding tables for literal/length and distance codes */ - bl = lbits; - i = huft_build(__G__ ll, nl, 257, cplens, cplext, &tl, &bl); - if (bl == 0) /* no literals or lengths */ - i = 1; - if (i) - { - if (i == 1) { - //if (!uO.qflag) - MESSAGE((uch *)"(incomplete l-tree) ", 21L, 1); - huft_free(tl); - } - return i; /* incomplete code set */ - } - bd = dbits; - i = huft_build(__G__ ll + nl, nd, 0, cpdist, cpdext, &td, &bd); - if (bd == 0 && nl > 257) /* lengths but no distances */ - { - //if (!uO.qflag) - MESSAGE((uch *)"(incomplete d-tree) ", 21L, 1); - huft_free(tl); - huft_free(td); - return 1; - } - if (i == 1) { -#ifdef PKZIP_BUG_WORKAROUND - i = 0; -#else - //if (!uO.qflag) - MESSAGE((uch *)"(incomplete d-tree) ", 21L, 1); - huft_free(td); - td = NULL; -#endif - } - if (i) - { - huft_free(tl); - return i; - } - - - /* decompress until an end-of-block code */ - i = inflate_codes(__G__ tl, td, bl, bd); - - /* free the decoding tables, return */ - huft_free(tl); - huft_free(td); - - if (i) - return 1; - - return 0; -} - - - -static int inflate_block(__G__ e) - __GDEF - int *e; /* last block flag */ -/* decompress an inflated block */ -{ - unsigned t; /* block type */ - register ulg b; /* bit buffer */ - register unsigned k; /* number of bits in bit buffer */ - - - /* make local bit buffer */ - b = G.bb; - k = G.bk; - - - /* read in last block bit */ - NEEDBITS(1) - *e = (int)b & 1; - DUMPBITS(1) - - - /* read in block type */ - NEEDBITS(2) - t = (unsigned)b & 3; - DUMPBITS(2) - - - /* restore the global bit buffer */ - G.bb = b; - G.bk = k; - - - /* inflate that block type */ - if (t == 2) - return inflate_dynamic(__G); - if (t == 0) - return inflate_stored(__G); - if (t == 1) - return inflate_fixed(__G); - - - /* bad block type */ - return 2; -} - - - -int inflate(__G) - __GDEF -/* decompress an inflated entry */ -{ - int e; /* last block flag */ - int r; /* result code */ -//#ifdef DEBUG -// unsigned h = 0; /* maximum struct huft's malloc'ed */ -//#endif - -#if (defined(DLL) && !defined(NO_SLIDE_REDIR)) - if (G.redirect_slide) - wsize = G.redirect_size, redirSlide = G.redirect_buffer; - else - wsize = WSIZE, redirSlide = slide; /* how they're #defined if !DLL */ -#endif - - /* initialize window, bit buffer */ - G.wp = 0; - G.bk = 0; - G.bb = 0; - - - /* decompress until the last block */ - do { -//#ifdef DEBUG -// G.hufts = 0; -//#endif - if ((r = inflate_block(__G__ &e)) != 0) - return r; -//#ifdef DEBUG -// if (G.hufts > h) -// h = G.hufts; -//#endif - } while (!e); - - - /* flush out redirSlide */ - FLUSH(G.wp); - - - /* return success */ - //Trace((stderr, "\n%u bytes in Huffman tables (%d/entry)\n", - // h * sizeof(struct huft), sizeof(struct huft))); - return 0; -} - - - -int inflate_free(__G) - __GDEF -{ - if (G.fixed_tl != (struct huft *)NULL) - { - huft_free(G.fixed_td); - huft_free(G.fixed_tl); - G.fixed_td = G.fixed_tl = (struct huft *)NULL; - } - return 0; -} - -#endif /* ?USE_ZLIB */ - - -/* - * GRR: moved huft_build() and huft_free() down here; used by explode() - * and fUnZip regardless of whether USE_ZLIB defined or not - */ - - -/* If BMAX needs to be larger than 16, then h and x[] should be ulg. */ -#define BMAX 16 /* maximum bit length of any code (16 for explode) */ -#define N_MAX 288 /* maximum number of codes in any set */ - - -int huft_build( - __GDEF - ZCONST unsigned *b, /* code lengths in bits (all assumed <= BMAX) */ - unsigned n, /* number of codes (assumed <= N_MAX) */ - unsigned s, /* number of simple-valued codes (0..s-1) */ - ZCONST ush *d, /* list of base values for non-simple codes */ - ZCONST ush *e, /* list of extra bits for non-simple codes */ - struct huft **t, /* result: starting table */ - int *m /* maximum lookup bits, returns actual */ - ) -/* Given a list of code lengths and a maximum table size, make a set of - tables to decode that set of codes. Return zero on success, one if - the given code set is incomplete (the tables are still built in this - case), two if the input is invalid (all zero length codes or an - oversubscribed set of lengths), and three if not enough memory. - The code with value 256 is special, and the tables are constructed - so that no bits beyond that code are fetched when that code is - decoded. */ -{ - unsigned a; /* counter for codes of length k */ - unsigned c[BMAX+1]; /* bit length count table */ - unsigned el; /* length of EOB code (value 256) */ - unsigned f; /* i repeats in table every f entries */ - int g; /* maximum code length */ - int h; /* table level */ - register unsigned i; /* counter, current code */ - register unsigned j; /* counter */ - register int k; /* number of bits in current code */ - int lx[BMAX+1]; /* memory for l[-1..BMAX-1] */ - int *l = lx+1; /* stack of bits per table */ - register unsigned *p; /* pointer into c[], b[], or v[] */ - register struct huft *q; /* points to current table */ - struct huft r; /* table entry for structure assignment */ - struct huft *u[BMAX]; /* table stack */ - unsigned v[N_MAX]; /* values in order of bit length */ - register int w; /* bits before this table == (l * h) */ - unsigned x[BMAX+1]; /* bit offsets, then code stack */ - unsigned *xp; /* pointer into x */ - int y; /* number of dummy codes added */ - unsigned z; /* number of entries in current table */ - - - /* Generate counts for each bit length */ - el = n > 256 ? b[256] : BMAX; /* set length of EOB code, if any */ - memset(c, 0, sizeof(c)); - p = (unsigned *)b; i = n; - do { - c[*p]++; p++; /* assume all entries <= BMAX */ - } while (--i); - if (c[0] == n) /* null input--all zero length codes */ - { - *t = (struct huft *)NULL; - *m = 0; - return 0; - } - - - /* Find minimum and maximum length, bound *m by those */ - for (j = 1; j <= BMAX; j++) - if (c[j]) - break; - k = j; /* minimum code length */ - if ((unsigned)*m < j) - *m = j; - for (i = BMAX; i; i--) - if (c[i]) - break; - g = i; /* maximum code length */ - if ((unsigned)*m > i) - *m = i; - - - /* Adjust last length count to fill out codes, if needed */ - for (y = 1 << j; j < i; j++, y <<= 1) - if ((y -= c[j]) < 0) - return 2; /* bad input: more codes than bits */ - if ((y -= c[i]) < 0) - return 2; - c[i] += y; - - - /* Generate starting offsets into the value table for each length */ - x[1] = j = 0; - p = c + 1; xp = x + 2; - while (--i) { /* note that i == g from above */ - *xp++ = (j += *p++); - } - - - /* Make a table of values in order of bit lengths */ - memset(v, 0, sizeof(v)); - p = (unsigned *)b; i = 0; - do { - if ((j = *p++) != 0) - v[x[j]++] = i; - } while (++i < n); - n = x[g]; /* set n to length of v */ - - - /* Generate the Huffman codes and for each, make the table entries */ - x[0] = i = 0; /* first Huffman code is zero */ - p = v; /* grab values in bit order */ - h = -1; /* no tables yet--level -1 */ - w = l[-1] = 0; /* no bits decoded yet */ - u[0] = (struct huft *)NULL; /* just to keep compilers happy */ - q = (struct huft *)NULL; /* ditto */ - z = 0; /* ditto */ - - /* go through the bit lengths (k already is bits in shortest code) */ - for (; k <= g; k++) - { - a = c[k]; - while (a--) - { - /* here i is the Huffman code of length k bits for value *p */ - /* make tables up to required level */ - while (k > w + l[h]) - { - w += l[h++]; /* add bits already decoded */ - - /* compute minimum size table less than or equal to *m bits */ - z = (z = g - w) > (unsigned)*m ? *m : z; /* upper limit */ - if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */ - { /* too few codes for k-w bit table */ - f -= a + 1; /* deduct codes from patterns left */ - xp = c + k; - while (++j < z) /* try smaller tables up to z bits */ - { - if ((f <<= 1) <= *++xp) - break; /* enough codes to use up j bits */ - f -= *xp; /* else deduct codes from patterns */ - } - } - if ((unsigned)w + j > el && (unsigned)w < el) - j = el - w; /* make EOB code end at table */ - z = 1 << j; /* table entries for j-bit table */ - l[h] = j; /* set table size in stack */ - - /* allocate and link in new table */ - if ((q = (struct huft *)malloc((z + 1)*sizeof(struct huft))) == - (struct huft *)NULL) - { - if (h) - huft_free(u[0]); - return 3; /* not enough memory */ - } -//#ifdef DEBUG -// G.hufts += z + 1; /* track memory usage */ -//#endif - *t = q + 1; /* link to list for huft_free() */ - *(t = &(q->v.t)) = (struct huft *)NULL; - u[h] = ++q; /* table starts after link */ - - /* connect to last table, if there is one */ - if (h) - { - x[h] = i; /* save pattern for backing up */ - r.b = (uch)l[h-1]; /* bits to dump before this table */ - r.e = (uch)(16 + j); /* bits in this table */ - r.v.t = q; /* pointer to this table */ - j = (i & ((1 << w) - 1)) >> (w - l[h-1]); - u[h-1][j] = r; /* connect to last table */ - } - } - - /* set up table entry in r */ - r.b = (uch)(k - w); - if (p >= v + n) - r.e = 99; /* out of values--invalid code */ - else if (*p < s) - { - r.e = (uch)(*p < 256 ? 16 : 15); /* 256 is end-of-block code */ - r.v.n = (ush)*p++; /* simple code is just the value */ - } - else - { - r.e = (uch)e[*p - s]; /* non-simple--look up in lists */ - r.v.n = d[*p++ - s]; - } - - /* fill code-like entries with r */ - f = 1 << (k - w); - for (j = i >> w; j < z; j += f) - q[j] = r; - - /* backwards increment the k-bit code i */ - for (j = 1 << (k - 1); i & j; j >>= 1) - i ^= j; - i ^= j; - - /* backup over finished tables */ - while ((i & ((1 << w) - 1)) != x[h]) - w -= l[--h]; /* don't need to update q */ - } - } - - - /* return actual size of base table */ - *m = l[0]; - - - /* Return true (1) if we were given an incomplete table */ - return y != 0 && g != 1; -} - - - -int huft_free (struct huft *t) - /* table to free */ -/* Free the malloc'ed tables built by huft_build(), which makes a linked - list of the tables it made, with the links in a dummy first entry of - each table. */ -{ - register struct huft *p, *q; - - - /* Go through linked list, freeing from the malloced (t[-1]) address. */ - p = t; - while (p != (struct huft *)NULL) - { - q = (--p)->v.t; - free((zvoid *)p); - p = q; - } - return 0; -} - - -// Main public function. Decompresses raw data compressed using the DEFLATE algorithm (RFC 1951 - e.g. zlib, gzip). -// Returns 0 if decompression fails or, if successful, returns the size of the decompressed data. -int DecompressDeflatedData (char *out, char *in, int inLength) -{ - G.outbufptr = out; - G.inptr = in; - G.incnt = inLength; - G.outCounter = 0; - - if (inflate(__G) != 0) - { - // Error decompressing - return 0; - } - return G.outCounter; -} - +/* inflate.c -- put in the public domain by Mark Adler */ + +/* Decompresses raw data compressed using the DEFLATE algorithm (RFC 1951) */ + +/* You can do whatever you like with this source file, though I would + prefer that if you modify it and redistribute it that you include + comments to that effect with your name and the date. Thank you. + + History: + vers date who what + ---- --------- -------------- ------------------------------------ + a ~~ Feb 92 M. Adler used full (large, one-step) lookup table + b1 21 Mar 92 M. Adler first version with partial lookup tables + b2 21 Mar 92 M. Adler fixed bug in fixed-code blocks + b3 22 Mar 92 M. Adler sped up match copies, cleaned up some + b4 25 Mar 92 M. Adler added prototypes; removed window[] (now + is the responsibility of unzip.h--also + changed name to slide[]), so needs diffs + for unzip.c and unzip.h (this allows + compiling in the small model on MSDOS); + fixed cast of q in huft_build(); + b5 26 Mar 92 M. Adler got rid of unintended macro recursion. + b6 27 Mar 92 M. Adler got rid of nextbyte() routine. fixed + bug in inflate_fixed(). + c1 30 Mar 92 M. Adler removed lbits, dbits environment variables. + changed BMAX to 16 for explode. Removed + OUTB usage, and replaced it with flush()-- + this was a 20% speed improvement! Added + an explode.c (to replace unimplod.c) that + uses the huft routines here. Removed + register union. + c2 4 Apr 92 M. Adler fixed bug for file sizes a multiple of 32k. + c3 10 Apr 92 M. Adler reduced memory of code tables made by + huft_build significantly (factor of two to + three). + c4 15 Apr 92 M. Adler added NOMEMCPY do kill use of memcpy(). + worked around a Turbo C optimization bug. + c5 21 Apr 92 M. Adler added the WSIZE #define to allow reducing + the 32K window size for specialized + applications. + c6 31 May 92 M. Adler added some typecasts to eliminate warnings + c7 27 Jun 92 G. Roelofs added some more typecasts (444: MSC bug). + c8 5 Oct 92 J-l. Gailly added ifdef'd code to deal with PKZIP bug. + c9 9 Oct 92 M. Adler removed a memory error message (~line 416). + c10 17 Oct 92 G. Roelofs changed ULONG/UWORD/byte to ulg/ush/uch, + removed old inflate, renamed inflate_entry + to inflate, added Mark's fix to a comment. + c10.5 14 Dec 92 M. Adler fix up error messages for incomplete trees. + c11 2 Jan 93 M. Adler fixed bug in detection of incomplete + tables, and removed assumption that EOB is + the longest code (bad assumption). + c12 3 Jan 93 M. Adler make tables for fixed blocks only once. + c13 5 Jan 93 M. Adler allow all zero length codes (pkzip 2.04c + outputs one zero length code for an empty + distance tree). + c14 12 Mar 93 M. Adler made inflate.c standalone with the + introduction of inflate.h. + c14b 16 Jul 93 G. Roelofs added (unsigned) typecast to w at 470. + c14c 19 Jul 93 J. Bush changed v[N_MAX], l[288], ll[28x+3x] arrays + to static for Amiga. + c14d 13 Aug 93 J-l. Gailly de-complicatified Mark's c[*p++]++ thing. + c14e 8 Oct 93 G. Roelofs changed memset() to memzero(). + c14f 22 Oct 93 G. Roelofs renamed quietflg to qflag; made Trace() + conditional; added inflate_free(). + c14g 28 Oct 93 G. Roelofs changed l/(lx+1) macro to pointer (Cray bug) + c14h 7 Dec 93 C. Ghisler huft_build() optimizations. + c14i 9 Jan 94 A. Verheijen set fixed_t{d,l} to NULL after freeing; + G. Roelofs check NEXTBYTE macro for EOF. + c14j 23 Jan 94 G. Roelofs removed Ghisler "optimizations"; ifdef'd + EOF check. + c14k 27 Feb 94 G. Roelofs added some typecasts to avoid warnings. + c14l 9 Apr 94 G. Roelofs fixed split comments on preprocessor lines + to avoid bug in Encore compiler. + c14m 7 Jul 94 P. Kienitz modified to allow assembler version of + inflate_codes() (define ASM_INFLATECODES) + c14n 22 Jul 94 G. Roelofs changed fprintf to macro for DLL versions + c14o 23 Aug 94 C. Spieler added a newline to a debug statement; + G. Roelofs added another typecast to avoid MSC warning + c14p 4 Oct 94 G. Roelofs added (voidp *) cast to free() argument + c14q 30 Oct 94 G. Roelofs changed fprintf macro to MESSAGE() + c14r 1 Nov 94 G. Roelofs fixed possible redefinition of CHECK_EOF + c14s 7 May 95 S. Maxwell OS/2 DLL globals stuff incorporated; + P. Kienitz "fixed" ASM_INFLATECODES macro/prototype + c14t 18 Aug 95 G. Roelofs added inflate() to use zlib functions; + changed voidp to zvoid; moved huft_build() + and huft_free() to end of file + c14u 1 Oct 95 G. Roelofs moved G into definition of MESSAGE macro + c14v 8 Nov 95 P. Kienitz changed ASM_INFLATECODES to use a regular + call with __G__ instead of a macro + c15 3 Aug 96 M. Adler fixed bomb-bug on random input data (Adobe) + c15b 24 Aug 96 M. Adler more fixes for random input data + c15c 28 Mar 97 G. Roelofs changed USE_ZLIB fatal exit code from + PK_MEM2 to PK_MEM3 + c16 20 Apr 97 J. Altman added memzero(v[]) in huft_build() + c16b 29 Mar 98 C. Spieler modified DLL code for slide redirection + + fork 12 Dec 07 Adapted for TrueCrypt + */ + + +/* + Inflate deflated (PKZIP's method 8 compressed) data. The compression + method searches for as much of the current string of bytes (up to a + length of 258) in the previous 32K bytes. If it doesn't find any + matches (of at least length 3), it codes the next byte. Otherwise, it + codes the length of the matched string and its distance backwards from + the current position. There is a single Huffman code that codes both + single bytes (called "literals") and match lengths. A second Huffman + code codes the distance information, which follows a length code. Each + length or distance code actually represents a base value and a number + of "extra" (sometimes zero) bits to get to add to the base value. At + the end of each deflated block is a special end-of-block (EOB) literal/ + length code. The decoding process is basically: get a literal/length + code; if EOB then done; if a literal, emit the decoded byte; if a + length then get the distance and emit the referred-to bytes from the + sliding window of previously emitted data. + + There are (currently) three kinds of inflate blocks: stored, fixed, and + dynamic. The compressor outputs a chunk of data at a time and decides + which method to use on a chunk-by-chunk basis. A chunk might typically + be 32K to 64K, uncompressed. If the chunk is uncompressible, then the + "stored" method is used. In this case, the bytes are simply stored as + is, eight bits per byte, with none of the above coding. The bytes are + preceded by a count, since there is no longer an EOB code. + + If the data are compressible, then either the fixed or dynamic methods + are used. In the dynamic method, the compressed data are preceded by + an encoding of the literal/length and distance Huffman codes that are + to be used to decode this block. The representation is itself Huffman + coded, and so is preceded by a description of that code. These code + descriptions take up a little space, and so for small blocks, there is + a predefined set of codes, called the fixed codes. The fixed method is + used if the block ends up smaller that way (usually for quite small + chunks); otherwise the dynamic method is used. In the latter case, the + codes are customized to the probabilities in the current block and so + can code it much better than the pre-determined fixed codes can. + + The Huffman codes themselves are decoded using a multi-level table + lookup, in order to maximize the speed of decoding plus the speed of + building the decoding tables. See the comments below that precede the + lbits and dbits tuning parameters. + + GRR: return values(?) + 0 OK + 1 incomplete table + 2 bad input + 3 not enough memory + */ + + +/* + Notes beyond the 1.93a appnote.txt: + + 1. Distance pointers never point before the beginning of the output + stream. + 2. Distance pointers can point back across blocks, up to 32k away. + 3. There is an implied maximum of 7 bits for the bit length table and + 15 bits for the actual data. + 4. If only one code exists, then it is encoded using one bit. (Zero + would be more efficient, but perhaps a little confusing.) If two + codes exist, they are coded using one bit each (0 and 1). + 5. There is no way of sending zero distance codes--a dummy must be + sent if there are none. (History: a pre 2.0 version of PKZIP would + store blocks with no distance codes, but this was discovered to be + too harsh a criterion.) Valid only for 1.93a. 2.04c does allow + zero distance codes, which is sent as one code of zero bits in + length. + 6. There are up to 286 literal/length codes. Code 256 represents the + end-of-block. Note however that the static length tree defines + 288 codes just to fill out the Huffman codes. Codes 286 and 287 + cannot be used though, since there is no length base or extra bits + defined for them. Similarily, there are up to 30 distance codes. + However, static trees define 32 codes (all 5 bits) to fill out the + Huffman codes, but the last two had better not show up in the data. + 7. Unzip can check dynamic Huffman blocks for complete code sets. + The exception is that a single code would not be complete (see #4). + 8. The five bits following the block type is really the number of + literal codes sent minus 257. + 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits + (1+6+6). Therefore, to output three times the length, you output + three codes (1+1+1), whereas to output four times the same length, + you only need two codes (1+3). Hmm. + 10. In the tree reconstruction algorithm, Code = Code + Increment + only if BitLength(i) is not zero. (Pretty obvious.) + 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19) + 12. Note: length code 284 can represent 227-258, but length code 285 + really is 258. The last length deserves its own, short code + since it gets used a lot in very redundant files. The length + 258 is special since 258 - 3 (the min match length) is 255. + 13. The literal/length and distance code bit lengths are read as a + single stream of lengths. It is possible (and advantageous) for + a repeat code (16, 17, or 18) to go across the boundary between + the two sets of lengths. + */ + + +/* #define DEBUG */ +#define INFMOD /* tell inflate.h to include code to be compiled */ +#include "inflate.h" + + +#ifndef WSIZE /* default is 32K */ +# define WSIZE 0x8000 /* window size--must be a power of two, and at least */ +#endif /* 32K for zip's deflate method */ + +#if (defined(DLL) && !defined(NO_SLIDE_REDIR)) +# define wsize G._wsize /* wsize is a variable */ +#else +# define wsize WSIZE /* wsize is a constant */ +#endif + + +#ifndef NEXTBYTE /* default is to simply get a byte from stdin */ +# define NEXTBYTE getchar() +#endif + +#ifndef MESSAGE /* only used twice, for fixed strings--NOT general-purpose */ +# define MESSAGE(str,len,flag) fprintf(stderr,(char *)(str)) +#endif + +#ifndef FLUSH /* default is to simply write the buffer to stdout */ +# define FLUSH(n) fwrite(redirSlide, 1, n, stdout) /* return value not used */ +#endif +/* Warning: the fwrite above might not work on 16-bit compilers, since + 0x8000 might be interpreted as -32,768 by the library function. */ + +#ifndef Trace +# ifdef DEBUG +# define Trace(x) fprintf x +# else +# define Trace(x) +# endif +#endif + +G_struct G; +uch redirSlide [WSIZE]; + +/*---------------------------------------------------------------------------*/ +#ifdef USE_ZLIB + + +/* + GRR: return values for both original inflate() and inflate() + 0 OK + 1 incomplete table(?) + 2 bad input + 3 not enough memory + */ + +/**************************/ +/* Function inflate() */ +/**************************/ + +int inflate(__G) /* decompress an inflated entry using the zlib routines */ + __GDEF +{ + int err=Z_OK; + +#if (defined(DLL) && !defined(NO_SLIDE_REDIR)) + if (G.redirect_slide) + wsize = G.redirect_size, redirSlide = G.redirect_buffer; + else + wsize = WSIZE, redirSlide = slide; +#endif + + G.dstrm.next_out = redirSlide; + G.dstrm.avail_out = wsize; + + G.dstrm.next_in = G.inptr; + G.dstrm.avail_in = G.incnt; + + if (!G.inflInit) { + unsigned i; + int windowBits; + + /* only need to test this stuff once */ + if (zlib_version[0] != ZLIB_VERSION[0]) { + Info(slide, 0x21, ((char *)slide, + "error: incompatible zlib version (expected %s, found %s)\n", + ZLIB_VERSION, zlib_version)); + return 3; + } else if (strcmp(zlib_version, ZLIB_VERSION) != 0) + Info(slide, 0x21, ((char *)slide, + "warning: different zlib version (expected %s, using %s)\n", + ZLIB_VERSION, zlib_version)); + + /* windowBits = log2(wsize) */ + for (i = ((unsigned)wsize * 2 - 1), windowBits = 0; + !(i & 1); i >>= 1, ++windowBits); + if ((unsigned)windowBits > (unsigned)15) + windowBits = 15; + else if (windowBits < 8) + windowBits = 8; + + G.dstrm.zalloc = (alloc_func)Z_NULL; + G.dstrm.zfree = (free_func)Z_NULL; + + Trace((stderr, "initializing inflate()\n")); + err = inflateInit2(&G.dstrm, -windowBits); + + if (err == Z_MEM_ERROR) + return 3; + else if (err != Z_OK) + Trace((stderr, "oops! (inflateInit2() err = %d)\n", err)); + G.inflInit = 1; + } + +#ifdef FUNZIP + while (err != Z_STREAM_END) { +#else /* !FUNZIP */ + while (G.csize > 0) { + Trace((stderr, "first loop: G.csize = %ld\n", G.csize)); +#endif /* ?FUNZIP */ + while (G.dstrm.avail_out > 0) { + err = inflate(&G.dstrm, Z_PARTIAL_FLUSH); + + if (err == Z_DATA_ERROR) + return 2; + else if (err == Z_MEM_ERROR) + return 3; + else if (err != Z_OK && err != Z_STREAM_END) + Trace((stderr, "oops! (inflate(first loop) err = %d)\n", err)); + +#ifdef FUNZIP + if (err == Z_STREAM_END) /* "END-of-entry-condition" ? */ +#else /* !FUNZIP */ + if (G.csize <= 0L) /* "END-of-entry-condition" ? */ +#endif /* ?FUNZIP */ + break; + + if (G.dstrm.avail_in <= 0) { + if (fillinbuf(__G) == 0) + return 2; /* no "END-condition" yet, but no more data */ + + G.dstrm.next_in = G.inptr; + G.dstrm.avail_in = G.incnt; + } + Trace((stderr, " avail_in = %d\n", G.dstrm.avail_in)); + } + FLUSH(wsize - G.dstrm.avail_out); /* flush slide[] */ + Trace((stderr, "inside loop: flushing %ld bytes (ptr diff = %ld)\n", + (long)(wsize - G.dstrm.avail_out), + (long)(G.dstrm.next_out-(Bytef *)redirSlide))); + G.dstrm.next_out = redirSlide; + G.dstrm.avail_out = wsize; + } + + /* no more input, so loop until we have all output */ + Trace((stderr, "beginning final loop: err = %d\n", err)); + while (err != Z_STREAM_END) { + err = inflate(&G.dstrm, Z_PARTIAL_FLUSH); + if (err == Z_DATA_ERROR) + return 2; + else if (err == Z_MEM_ERROR) + return 3; + else if (err == Z_BUF_ERROR) { /* DEBUG */ + Trace((stderr, "zlib inflate() did not detect stream end (%s, %s)\n" + , G.zipfn, G.filename)); + break; + } else if (err != Z_OK && err != Z_STREAM_END) { + Trace((stderr, "oops! (inflate(final loop) err = %d)\n", err)); + DESTROYGLOBALS() + EXIT(PK_MEM3); + } + FLUSH(wsize - G.dstrm.avail_out); /* final flush of slide[] */ + Trace((stderr, "final loop: flushing %ld bytes (ptr diff = %ld)\n", + (long)(wsize - G.dstrm.avail_out), + (long)(G.dstrm.next_out-(Bytef *)redirSlide))); + G.dstrm.next_out = redirSlide; + G.dstrm.avail_out = wsize; + } + Trace((stderr, "total in = %ld, total out = %ld\n", G.dstrm.total_in, + G.dstrm.total_out)); + + G.inptr = (uch *)G.dstrm.next_in; + G.incnt = (G.inbuf + INBUFSIZ) - G.inptr; /* reset for other routines */ + + err = inflateReset(&G.dstrm); + if (err != Z_OK) + Trace((stderr, "oops! (inflateReset() err = %d)\n", err)); + + return 0; +} + + +/*---------------------------------------------------------------------------*/ +#else /* !USE_ZLIB */ + + +/* Function prototypes */ +#ifndef OF +# ifdef __STDC__ +# define OF(a) a +# else +# define OF(a) () +# endif +#endif /* !OF */ +int inflate_codes OF((__GPRO__ struct huft *tl, struct huft *td, + int bl, int bd)); +static int inflate_stored OF((__GPRO)); +static int inflate_fixed OF((__GPRO)); +static int inflate_dynamic OF((__GPRO)); +static int inflate_block OF((__GPRO__ int *e)); + + +/* The inflate algorithm uses a sliding 32K byte window on the uncompressed + stream to find repeated byte strings. This is implemented here as a + circular buffer. The index is updated simply by incrementing and then + and'ing with 0x7fff (32K-1). */ +/* It is left to other modules to supply the 32K area. It is assumed + to be usable as if it were declared "uch slide[32768];" or as just + "uch *slide;" and then malloc'ed in the latter case. The definition + must be in unzip.h, included above. */ + + +/* unsigned wp; moved to globals.h */ /* current position in slide */ + + +/* Tables for deflate from PKZIP's appnote.txt. */ +static ZCONST unsigned border[] = { /* Order of the bit length code lengths */ + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; +static ZCONST ush cplens[] = { /* Copy lengths for literal codes 257..285 */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + /* note: see note #13 above about the 258 in this list. */ +static ZCONST ush cplext[] = { /* Extra bits for literal codes 257..285 */ + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, + 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */ +static ZCONST ush cpdist[] = { /* Copy offsets for distance codes 0..29 */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577}; +static ZCONST ush cpdext[] = { /* Extra bits for distance codes */ + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, + 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, + 12, 12, 13, 13}; + + +/* moved to consts.h (included in unzip.c), resp. funzip.c */ +#if 1 +/* And'ing with mask_bits[n] masks the lower n bits */ +ZCONST ush near mask_bits[] = { + 0x0000, + 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, + 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff +}; +#endif /* 0 */ + + +/* Macros for inflate() bit peeking and grabbing. + The usage is: + + NEEDBITS(j) + x = b & mask_bits[j]; + DUMPBITS(j) + + where NEEDBITS makes sure that b has at least j bits in it, and + DUMPBITS removes the bits from b. The macros use the variable k + for the number of bits in b. Normally, b and k are register + variables for speed and are initialized at the begining of a + routine that uses these macros from a global bit buffer and count. + + In order to not ask for more bits than there are in the compressed + stream, the Huffman tables are constructed to only ask for just + enough bits to make up the end-of-block code (value 256). Then no + bytes need to be "returned" to the buffer at the end of the last + block. See the huft_build() routine. + */ + +/* These have been moved to globals.h */ +#if 0 +ulg bb; /* bit buffer */ +unsigned bk; /* bits in bit buffer */ +#endif + +#ifndef CHECK_EOF +# define CHECK_EOF /* default as of 5.13/5.2 */ +#endif + +#ifndef CHECK_EOF +# define NEEDBITS(n) {while(k<(n)){b|=((ulg)NEXTBYTE)<>=(n);k-=(n);} + + +/* + Huffman code decoding is performed using a multi-level table lookup. + The fastest way to decode is to simply build a lookup table whose + size is determined by the longest code. However, the time it takes + to build this table can also be a factor if the data being decoded + are not very long. The most common codes are necessarily the + shortest codes, so those codes dominate the decoding time, and hence + the speed. The idea is you can have a shorter table that decodes the + shorter, more probable codes, and then point to subsidiary tables for + the longer codes. The time it costs to decode the longer codes is + then traded against the time it takes to make longer tables. + + This results of this trade are in the variables lbits and dbits + below. lbits is the number of bits the first level table for literal/ + length codes can decode in one step, and dbits is the same thing for + the distance codes. Subsequent tables are also less than or equal to + those sizes. These values may be adjusted either when all of the + codes are shorter than that, in which case the longest code length in + bits is used, or when the shortest code is *longer* than the requested + table size, in which case the length of the shortest code in bits is + used. + + There are two different values for the two tables, since they code a + different number of possibilities each. The literal/length table + codes 286 possible values, or in a flat code, a little over eight + bits. The distance table codes 30 possible values, or a little less + than five bits, flat. The optimum values for speed end up being + about one bit more than those, so lbits is 8+1 and dbits is 5+1. + The optimum values may differ though from machine to machine, and + possibly even between compilers. Your mileage may vary. + */ + +static ZCONST int lbits = 9; /* bits in base literal/length lookup table */ +static ZCONST int dbits = 6; /* bits in base distance lookup table */ + + +#ifndef ASM_INFLATECODES + +#pragma warning(disable:4131) + +int inflate_codes(__G__ tl, td, bl, bd) + __GDEF +struct huft *tl, *td; /* literal/length and distance decoder tables */ +int bl, bd; /* number of bits decoded by tl[] and td[] */ +/* inflate (decompress) the codes in a deflated (compressed) block. + Return an error code or zero if it all goes ok. */ +{ + register unsigned e; /* table entry flag/number of extra bits */ + unsigned n, d; /* length and index for copy */ + unsigned w; /* current window position */ + struct huft *t; /* pointer to table entry */ + unsigned ml, md; /* masks for bl and bd bits */ + register ulg b; /* bit buffer */ + register unsigned k; /* number of bits in bit buffer */ + + + /* make local copies of globals */ + b = G.bb; /* initialize bit buffer */ + k = G.bk; + w = G.wp; /* initialize window position */ + + + /* inflate the coded data */ + ml = mask_bits[bl]; /* precompute masks for speed */ + md = mask_bits[bd]; + while (1) /* do until end of block */ + { + NEEDBITS((unsigned)bl) + if ((e = (t = tl + ((unsigned)b & ml))->e) > 16) + do { + if (e == 99) + return 1; + DUMPBITS(t->b) + e -= 16; + NEEDBITS(e) + } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16); + DUMPBITS(t->b) + if (e == 16) /* then it's a literal */ + { + redirSlide[w++] = (uch)t->v.n; + if (w == wsize) + { + FLUSH(w); + w = 0; + } + } + else /* it's an EOB or a length */ + { + /* exit if end of block */ + if (e == 15) + break; + + /* get length of block to copy */ + NEEDBITS(e) + n = t->v.n + ((unsigned)b & mask_bits[e]); + DUMPBITS(e); + + /* decode distance of block to copy */ + NEEDBITS((unsigned)bd) + if ((e = (t = td + ((unsigned)b & md))->e) > 16) + do { + if (e == 99) + return 1; + DUMPBITS(t->b) + e -= 16; + NEEDBITS(e) + } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16); + DUMPBITS(t->b) + NEEDBITS(e) + d = w - t->v.n - ((unsigned)b & mask_bits[e]); + DUMPBITS(e) + + /* do the copy */ + do { +#if (defined(DLL) && !defined(NO_SLIDE_REDIR)) + if (G.redirect_slide) {/* &= w/ wsize unnecessary & wrong if redirect */ + if (d >= wsize) + return 1; /* invalid compressed data */ + n -= (e = (e = wsize - (d > w ? d : w)) > n ? n : e); + } + else +#endif + n -= (e = (e = wsize - ((d &= wsize-1) > w ? d : w)) > n ? n : e); +#ifndef NOMEMCPY + if (w - d >= e) /* (this test assumes unsigned comparison) */ + { + memcpy(redirSlide + w, redirSlide + d, e); + w += e; + d += e; + } + else /* do it slowly to avoid memcpy() overlap */ +#endif /* !NOMEMCPY */ + do { + redirSlide[w++] = redirSlide[d++]; + } while (--e); + if (w == wsize) + { + FLUSH(w); + w = 0; + } + } while (n); + } + } + + + /* restore the globals from the locals */ + G.wp = w; /* restore global window pointer */ + G.bb = b; /* restore global bit buffer */ + G.bk = k; + + + /* done */ + return 0; +} + +#endif /* ASM_INFLATECODES */ + + + +static int inflate_stored(__G) + __GDEF +/* "decompress" an inflated type 0 (stored) block. */ +{ + unsigned n; /* number of bytes in block */ + unsigned w; /* current window position */ + register ulg b; /* bit buffer */ + register unsigned k; /* number of bits in bit buffer */ + + + /* make local copies of globals */ + Trace((stderr, "\nstored block")); + b = G.bb; /* initialize bit buffer */ + k = G.bk; + w = G.wp; /* initialize window position */ + + + /* go to byte boundary */ + n = k & 7; + DUMPBITS(n); + + + /* get the length and its complement */ + NEEDBITS(16) + n = ((unsigned)b & 0xffff); + DUMPBITS(16) + NEEDBITS(16) + if (n != (unsigned)((~b) & 0xffff)) + return 1; /* error in compressed data */ + DUMPBITS(16) + + + /* read and output the compressed data */ + while (n--) + { + NEEDBITS(8) + redirSlide[w++] = (uch)b; + if (w == wsize) + { + FLUSH(w); + w = 0; + } + DUMPBITS(8) + } + + + /* restore the globals from the locals */ + G.wp = w; /* restore global window pointer */ + G.bb = b; /* restore global bit buffer */ + G.bk = k; + return 0; +} + + +/* Globals for literal tables (built once) */ +/* Moved to globals.h */ +#if 0 +struct huft *fixed_tl = (struct huft *)NULL; +struct huft *fixed_td; +int fixed_bl, fixed_bd; +#endif + +static int inflate_fixed(__G) + __GDEF +/* decompress an inflated type 1 (fixed Huffman codes) block. We should + either replace this with a custom decoder, or at least precompute the + Huffman tables. */ +{ + /* if first time, set up tables for fixed blocks */ + Trace((stderr, "\nliteral block")); + if (G.fixed_tl == (struct huft *)NULL) + { + int i; /* temporary variable */ + unsigned l[288]; /* length list for huft_build */ + + /* literal table */ + for (i = 0; i < 144; i++) + l[i] = 8; + for (; i < 256; i++) + l[i] = 9; + for (; i < 280; i++) + l[i] = 7; + for (; i < 288; i++) /* make a complete, but wrong code set */ + l[i] = 8; + G.fixed_bl = 7; + if ((i = huft_build(__G__ l, 288, 257, cplens, cplext, + &G.fixed_tl, &G.fixed_bl)) != 0) + { + G.fixed_tl = (struct huft *)NULL; + return i; + } + + /* distance table */ + for (i = 0; i < 30; i++) /* make an incomplete code set */ + l[i] = 5; + G.fixed_bd = 5; + if ((i = huft_build(__G__ l, 30, 0, cpdist, cpdext, + &G.fixed_td, &G.fixed_bd)) > 1) + { + huft_free(G.fixed_tl); + G.fixed_tl = (struct huft *)NULL; + return i; + } + } + + /* decompress until an end-of-block code */ + return inflate_codes(__G__ G.fixed_tl, G.fixed_td, + G.fixed_bl, G.fixed_bd) != 0; +} + + + +static int inflate_dynamic(__G) + __GDEF +/* decompress an inflated type 2 (dynamic Huffman codes) block. */ +{ + int i; /* temporary variables */ + unsigned j; + unsigned l; /* last length */ + unsigned m; /* mask for bit lengths table */ + unsigned n; /* number of lengths to get */ + struct huft *tl; /* literal/length code table */ + struct huft *td; /* distance code table */ + int bl; /* lookup bits for tl */ + int bd; /* lookup bits for td */ + unsigned nb; /* number of bit length codes */ + unsigned nl; /* number of literal/length codes */ + unsigned nd; /* number of distance codes */ +#ifdef PKZIP_BUG_WORKAROUND + unsigned ll[288+32]; /* literal/length and distance code lengths */ +#else + unsigned ll[286+30]; /* literal/length and distance code lengths */ +#endif + register ulg b; /* bit buffer */ + register unsigned k; /* number of bits in bit buffer */ + + + /* make local bit buffer */ + Trace((stderr, "\ndynamic block")); + b = G.bb; + k = G.bk; + + + /* read in table lengths */ + NEEDBITS(5) + nl = 257 + ((unsigned)b & 0x1f); /* number of literal/length codes */ + DUMPBITS(5) + NEEDBITS(5) + nd = 1 + ((unsigned)b & 0x1f); /* number of distance codes */ + DUMPBITS(5) + NEEDBITS(4) + nb = 4 + ((unsigned)b & 0xf); /* number of bit length codes */ + DUMPBITS(4) +#ifdef PKZIP_BUG_WORKAROUND + if (nl > 288 || nd > 32) +#else + if (nl > 286 || nd > 30) +#endif + return 1; /* bad lengths */ + + + /* read in bit-length-code lengths */ + for (j = 0; j < nb; j++) + { + NEEDBITS(3) + ll[border[j]] = (unsigned)b & 7; + DUMPBITS(3) + } + for (; j < 19; j++) + ll[border[j]] = 0; + + + /* build decoding table for trees--single level, 7 bit lookup */ + bl = 7; + i = huft_build(__G__ ll, 19, 19, NULL, NULL, &tl, &bl); + if (bl == 0) /* no bit lengths */ + i = 1; + if (i) + { + if (i == 1) + huft_free(tl); + return i; /* incomplete code set */ + } + + + /* read in literal and distance code lengths */ + n = nl + nd; + m = mask_bits[bl]; + i = l = 0; + while ((unsigned)i < n) + { + NEEDBITS((unsigned)bl) + j = (td = tl + ((unsigned)b & m))->b; + DUMPBITS(j) + j = td->v.n; + if (j < 16) /* length of code in bits (0..15) */ + ll[i++] = l = j; /* save last length in l */ + else if (j == 16) /* repeat last length 3 to 6 times */ + { + NEEDBITS(2) + j = 3 + ((unsigned)b & 3); + DUMPBITS(2) + if ((unsigned)i + j > n) + { + huft_free(tl); + return 1; + } + while (j--) + ll[i++] = l; + } + else if (j == 17) /* 3 to 10 zero length codes */ + { + NEEDBITS(3) + j = 3 + ((unsigned)b & 7); + DUMPBITS(3) + if ((unsigned)i + j > n) + { + huft_free(tl); + return 1; + } + while (j--) + ll[i++] = 0; + l = 0; + } + else /* j == 18: 11 to 138 zero length codes */ + { + NEEDBITS(7) + j = 11 + ((unsigned)b & 0x7f); + DUMPBITS(7) + if ((unsigned)i + j > n) + { + huft_free(tl); + return 1; + } + while (j--) + ll[i++] = 0; + l = 0; + } + } + + + /* free decoding table for trees */ + huft_free(tl); + + + /* restore the global bit buffer */ + G.bb = b; + G.bk = k; + + + /* build the decoding tables for literal/length and distance codes */ + bl = lbits; + i = huft_build(__G__ ll, nl, 257, cplens, cplext, &tl, &bl); + if (bl == 0) /* no literals or lengths */ + i = 1; + if (i) + { + if (i == 1) { + //if (!uO.qflag) + MESSAGE((uch *)"(incomplete l-tree) ", 21L, 1); + huft_free(tl); + } + return i; /* incomplete code set */ + } + bd = dbits; + i = huft_build(__G__ ll + nl, nd, 0, cpdist, cpdext, &td, &bd); + if (bd == 0 && nl > 257) /* lengths but no distances */ + { + //if (!uO.qflag) + MESSAGE((uch *)"(incomplete d-tree) ", 21L, 1); + huft_free(tl); + huft_free(td); + return 1; + } + if (i == 1) { +#ifdef PKZIP_BUG_WORKAROUND + i = 0; +#else + //if (!uO.qflag) + MESSAGE((uch *)"(incomplete d-tree) ", 21L, 1); + huft_free(td); + td = NULL; +#endif + } + if (i) + { + huft_free(tl); + return i; + } + + + /* decompress until an end-of-block code */ + i = inflate_codes(__G__ tl, td, bl, bd); + + /* free the decoding tables, return */ + huft_free(tl); + huft_free(td); + + if (i) + return 1; + + return 0; +} + + + +static int inflate_block(__G__ e) + __GDEF + int *e; /* last block flag */ +/* decompress an inflated block */ +{ + unsigned t; /* block type */ + register ulg b; /* bit buffer */ + register unsigned k; /* number of bits in bit buffer */ + + + /* make local bit buffer */ + b = G.bb; + k = G.bk; + + + /* read in last block bit */ + NEEDBITS(1) + *e = (int)b & 1; + DUMPBITS(1) + + + /* read in block type */ + NEEDBITS(2) + t = (unsigned)b & 3; + DUMPBITS(2) + + + /* restore the global bit buffer */ + G.bb = b; + G.bk = k; + + + /* inflate that block type */ + if (t == 2) + return inflate_dynamic(__G); + if (t == 0) + return inflate_stored(__G); + if (t == 1) + return inflate_fixed(__G); + + + /* bad block type */ + return 2; +} + + + +int inflate(__G) + __GDEF +/* decompress an inflated entry */ +{ + int e; /* last block flag */ + int r; /* result code */ +//#ifdef DEBUG +// unsigned h = 0; /* maximum struct huft's malloc'ed */ +//#endif + +#if (defined(DLL) && !defined(NO_SLIDE_REDIR)) + if (G.redirect_slide) + wsize = G.redirect_size, redirSlide = G.redirect_buffer; + else + wsize = WSIZE, redirSlide = slide; /* how they're #defined if !DLL */ +#endif + + /* initialize window, bit buffer */ + G.wp = 0; + G.bk = 0; + G.bb = 0; + + + /* decompress until the last block */ + do { +//#ifdef DEBUG +// G.hufts = 0; +//#endif + if ((r = inflate_block(__G__ &e)) != 0) + return r; +//#ifdef DEBUG +// if (G.hufts > h) +// h = G.hufts; +//#endif + } while (!e); + + + /* flush out redirSlide */ + FLUSH(G.wp); + + + /* return success */ + //Trace((stderr, "\n%u bytes in Huffman tables (%d/entry)\n", + // h * sizeof(struct huft), sizeof(struct huft))); + return 0; +} + + + +int inflate_free(__G) + __GDEF +{ + if (G.fixed_tl != (struct huft *)NULL) + { + huft_free(G.fixed_td); + huft_free(G.fixed_tl); + G.fixed_td = G.fixed_tl = (struct huft *)NULL; + } + return 0; +} + +#endif /* ?USE_ZLIB */ + + +/* + * GRR: moved huft_build() and huft_free() down here; used by explode() + * and fUnZip regardless of whether USE_ZLIB defined or not + */ + + +/* If BMAX needs to be larger than 16, then h and x[] should be ulg. */ +#define BMAX 16 /* maximum bit length of any code (16 for explode) */ +#define N_MAX 288 /* maximum number of codes in any set */ + + +int huft_build( + __GDEF + ZCONST unsigned *b, /* code lengths in bits (all assumed <= BMAX) */ + unsigned n, /* number of codes (assumed <= N_MAX) */ + unsigned s, /* number of simple-valued codes (0..s-1) */ + ZCONST ush *d, /* list of base values for non-simple codes */ + ZCONST ush *e, /* list of extra bits for non-simple codes */ + struct huft **t, /* result: starting table */ + int *m /* maximum lookup bits, returns actual */ + ) +/* Given a list of code lengths and a maximum table size, make a set of + tables to decode that set of codes. Return zero on success, one if + the given code set is incomplete (the tables are still built in this + case), two if the input is invalid (all zero length codes or an + oversubscribed set of lengths), and three if not enough memory. + The code with value 256 is special, and the tables are constructed + so that no bits beyond that code are fetched when that code is + decoded. */ +{ + unsigned a; /* counter for codes of length k */ + unsigned c[BMAX+1]; /* bit length count table */ + unsigned el; /* length of EOB code (value 256) */ + unsigned f; /* i repeats in table every f entries */ + int g; /* maximum code length */ + int h; /* table level */ + register unsigned i; /* counter, current code */ + register unsigned j; /* counter */ + register int k; /* number of bits in current code */ + int lx[BMAX+1]; /* memory for l[-1..BMAX-1] */ + int *l = lx+1; /* stack of bits per table */ + register unsigned *p; /* pointer into c[], b[], or v[] */ + register struct huft *q; /* points to current table */ + struct huft r; /* table entry for structure assignment */ + struct huft *u[BMAX]; /* table stack */ + unsigned v[N_MAX]; /* values in order of bit length */ + register int w; /* bits before this table == (l * h) */ + unsigned x[BMAX+1]; /* bit offsets, then code stack */ + unsigned *xp; /* pointer into x */ + int y; /* number of dummy codes added */ + unsigned z; /* number of entries in current table */ + + + /* Generate counts for each bit length */ + el = n > 256 ? b[256] : BMAX; /* set length of EOB code, if any */ + memset(c, 0, sizeof(c)); + p = (unsigned *)b; i = n; + do { + c[*p]++; p++; /* assume all entries <= BMAX */ + } while (--i); + if (c[0] == n) /* null input--all zero length codes */ + { + *t = (struct huft *)NULL; + *m = 0; + return 0; + } + + + /* Find minimum and maximum length, bound *m by those */ + for (j = 1; j <= BMAX; j++) + if (c[j]) + break; + k = j; /* minimum code length */ + if ((unsigned)*m < j) + *m = j; + for (i = BMAX; i; i--) + if (c[i]) + break; + g = i; /* maximum code length */ + if ((unsigned)*m > i) + *m = i; + + + /* Adjust last length count to fill out codes, if needed */ + for (y = 1 << j; j < i; j++, y <<= 1) + if ((y -= c[j]) < 0) + return 2; /* bad input: more codes than bits */ + if ((y -= c[i]) < 0) + return 2; + c[i] += y; + + + /* Generate starting offsets into the value table for each length */ + x[1] = j = 0; + p = c + 1; xp = x + 2; + while (--i) { /* note that i == g from above */ + *xp++ = (j += *p++); + } + + + /* Make a table of values in order of bit lengths */ + memset(v, 0, sizeof(v)); + p = (unsigned *)b; i = 0; + do { + if ((j = *p++) != 0) + v[x[j]++] = i; + } while (++i < n); + n = x[g]; /* set n to length of v */ + + + /* Generate the Huffman codes and for each, make the table entries */ + x[0] = i = 0; /* first Huffman code is zero */ + p = v; /* grab values in bit order */ + h = -1; /* no tables yet--level -1 */ + w = l[-1] = 0; /* no bits decoded yet */ + u[0] = (struct huft *)NULL; /* just to keep compilers happy */ + q = (struct huft *)NULL; /* ditto */ + z = 0; /* ditto */ + + /* go through the bit lengths (k already is bits in shortest code) */ + for (; k <= g; k++) + { + a = c[k]; + while (a--) + { + /* here i is the Huffman code of length k bits for value *p */ + /* make tables up to required level */ + while (k > w + l[h]) + { + w += l[h++]; /* add bits already decoded */ + + /* compute minimum size table less than or equal to *m bits */ + z = (z = g - w) > (unsigned)*m ? *m : z; /* upper limit */ + if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */ + { /* too few codes for k-w bit table */ + f -= a + 1; /* deduct codes from patterns left */ + xp = c + k; + while (++j < z) /* try smaller tables up to z bits */ + { + if ((f <<= 1) <= *++xp) + break; /* enough codes to use up j bits */ + f -= *xp; /* else deduct codes from patterns */ + } + } + if ((unsigned)w + j > el && (unsigned)w < el) + j = el - w; /* make EOB code end at table */ + z = 1 << j; /* table entries for j-bit table */ + l[h] = j; /* set table size in stack */ + + /* allocate and link in new table */ + if ((q = (struct huft *)malloc((z + 1)*sizeof(struct huft))) == + (struct huft *)NULL) + { + if (h) + huft_free(u[0]); + return 3; /* not enough memory */ + } +//#ifdef DEBUG +// G.hufts += z + 1; /* track memory usage */ +//#endif + *t = q + 1; /* link to list for huft_free() */ + *(t = &(q->v.t)) = (struct huft *)NULL; + u[h] = ++q; /* table starts after link */ + + /* connect to last table, if there is one */ + if (h) + { + x[h] = i; /* save pattern for backing up */ + r.b = (uch)l[h-1]; /* bits to dump before this table */ + r.e = (uch)(16 + j); /* bits in this table */ + r.v.t = q; /* pointer to this table */ + j = (i & ((1 << w) - 1)) >> (w - l[h-1]); + u[h-1][j] = r; /* connect to last table */ + } + } + + /* set up table entry in r */ + r.b = (uch)(k - w); + if (p >= v + n) + r.e = 99; /* out of values--invalid code */ + else if (*p < s) + { + r.e = (uch)(*p < 256 ? 16 : 15); /* 256 is end-of-block code */ + r.v.n = (ush)*p++; /* simple code is just the value */ + } + else + { + r.e = (uch)e[*p - s]; /* non-simple--look up in lists */ + r.v.n = d[*p++ - s]; + } + + /* fill code-like entries with r */ + f = 1 << (k - w); + for (j = i >> w; j < z; j += f) + q[j] = r; + + /* backwards increment the k-bit code i */ + for (j = 1 << (k - 1); i & j; j >>= 1) + i ^= j; + i ^= j; + + /* backup over finished tables */ + while ((i & ((1 << w) - 1)) != x[h]) + w -= l[--h]; /* don't need to update q */ + } + } + + + /* return actual size of base table */ + *m = l[0]; + + + /* Return true (1) if we were given an incomplete table */ + return y != 0 && g != 1; +} + + + +int huft_free (struct huft *t) + /* table to free */ +/* Free the malloc'ed tables built by huft_build(), which makes a linked + list of the tables it made, with the links in a dummy first entry of + each table. */ +{ + register struct huft *p, *q; + + + /* Go through linked list, freeing from the malloced (t[-1]) address. */ + p = t; + while (p != (struct huft *)NULL) + { + q = (--p)->v.t; + free((zvoid *)p); + p = q; + } + return 0; +} + + +// Main public function. Decompresses raw data compressed using the DEFLATE algorithm (RFC 1951 - e.g. zlib, gzip). +// Returns 0 if decompression fails or, if successful, returns the size of the decompressed data. +int DecompressDeflatedData (char *out, char *in, int inLength) +{ + G.outbufptr = out; + G.inptr = in; + G.incnt = inLength; + G.outCounter = 0; + + if (inflate(__G) != 0) + { + // Error decompressing + return 0; + } + return G.outCounter; +} + diff --git a/src/Common/Inflate.h b/src/Common/Inflate.h index a0d4aa5b..c2810c82 100644 --- a/src/Common/Inflate.h +++ b/src/Common/Inflate.h @@ -1,51 +1,51 @@ -#include -#include - -#define WSIZE 0x8000 // Window size -#define ZCONST const -#define OF(p) p - -typedef unsigned long ulg; -typedef unsigned char uch; -typedef unsigned short ush; -typedef void zvoid; - -typedef struct huft -{ - uch b, e; - union - { - ush n; - struct huft *t; - }v; -}; - -typedef struct -{ - uch *inptr, *outbufptr; - int incnt; - int outCounter; - - struct huft *fixed_tl; - struct huft *fixed_td; - int fixed_bl, fixed_bd; - - unsigned bk, wp; - ulg bb; -} G_struct; - -#define __GPRO void -#define __GPRO__ -#define __G -#define __G__ -#define __GDEF - - -#define FLUSH(cnt) { memcpy (G.outbufptr, redirSlide, cnt); G.outbufptr += cnt; G.outCounter += cnt; } -#define NEXTBYTE (((G.incnt--) >= 0) ? (*G.inptr++) : EOF) - - -int huft_free(struct huft *t); -int huft_build(__GDEF ZCONST unsigned *b, unsigned n, unsigned s, ZCONST ush *d, ZCONST ush *e, struct huft **t, int *m); - -int DecompressDeflatedData (char *out, char *in, int inLength); +#include +#include + +#define WSIZE 0x8000 // Window size +#define ZCONST const +#define OF(p) p + +typedef unsigned long ulg; +typedef unsigned char uch; +typedef unsigned short ush; +typedef void zvoid; + +typedef struct huft +{ + uch b, e; + union + { + ush n; + struct huft *t; + }v; +}; + +typedef struct +{ + uch *inptr, *outbufptr; + int incnt; + int outCounter; + + struct huft *fixed_tl; + struct huft *fixed_td; + int fixed_bl, fixed_bd; + + unsigned bk, wp; + ulg bb; +} G_struct; + +#define __GPRO void +#define __GPRO__ +#define __G +#define __G__ +#define __GDEF + + +#define FLUSH(cnt) { memcpy (G.outbufptr, redirSlide, cnt); G.outbufptr += cnt; G.outCounter += cnt; } +#define NEXTBYTE (((G.incnt--) >= 0) ? (*G.inptr++) : EOF) + + +int huft_free(struct huft *t); +int huft_build(__GDEF ZCONST unsigned *b, unsigned n, unsigned s, ZCONST ush *d, ZCONST ush *e, struct huft **t, int *m); + +int DecompressDeflatedData (char *out, char *in, int inLength); diff --git a/src/Common/Keyfiles.c b/src/Common/Keyfiles.c index 8b3825d5..c59ab374 100644 --- a/src/Common/Keyfiles.c +++ b/src/Common/Keyfiles.c @@ -1,778 +1,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 -#include -#include -#include - -#include "Tcdefs.h" -#include "Keyfiles.h" -#include "Crc.h" - -#include -#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 - -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 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, ¶m->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 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 (¶m->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 (¶m->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 (¶m->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 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; -} +/* + 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 +#include +#include +#include + +#include "Tcdefs.h" +#include "Keyfiles.h" +#include "Crc.h" + +#include +#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 + +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 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, ¶m->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 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 (¶m->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 (¶m->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 (¶m->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 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; +} diff --git a/src/Common/Keyfiles.h b/src/Common/Keyfiles.h index 899cd9e4..dea906b1 100644 --- a/src/Common/Keyfiles.h +++ b/src/Common/Keyfiles.h @@ -1,54 +1,54 @@ -/* - 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. -*/ - -#ifndef KEYFILES_H -#define KEYFILES_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "Common.h" - -#define KEYFILE_POOL_SIZE 64 -#define KEYFILE_MAX_READ_LEN (1024*1024) - -typedef struct KeyFileStruct -{ - wchar_t FileName[MAX_PATH + 1]; - struct KeyFileStruct *Next; -} KeyFile; - -typedef struct -{ - wchar_t VolumeFileName[MAX_PATH + 1]; - BOOL EnableKeyFiles; - KeyFile *FirstKeyFile; -} KeyFilesDlgParam; - -KeyFile *KeyFileAdd (KeyFile *firstKeyFile, KeyFile *keyFile); -void KeyFileRemoveAll (KeyFile **firstKeyFile); -KeyFile *KeyFileClone (KeyFile *keyFile); -void KeyFileCloneAll (KeyFile *firstKeyFile, KeyFile **outputKeyFile); -BOOL KeyFilesApply (HWND hwndDlg, Password *password, KeyFile *firstKeyFilem, const wchar_t* volumeFileName); -BOOL KeyFilesApplyWithPin (HWND hwndDlg, Password *password, char* pin, KeyFile *firstKeyFilem, const wchar_t* volumeFileName); - -BOOL CALLBACK KeyFilesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -BOOL KeyfilesPopupMenu (HWND hwndDlg, POINT popupPosition, KeyFilesDlgParam *dialogParam); - -extern BOOL HiddenFilesPresentInKeyfilePath; - -#ifdef __cplusplus -} -#endif - -#endif /* #ifndef KEYFILES_H */ +/* + 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. +*/ + +#ifndef KEYFILES_H +#define KEYFILES_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "Common.h" + +#define KEYFILE_POOL_SIZE 64 +#define KEYFILE_MAX_READ_LEN (1024*1024) + +typedef struct KeyFileStruct +{ + wchar_t FileName[MAX_PATH + 1]; + struct KeyFileStruct *Next; +} KeyFile; + +typedef struct +{ + wchar_t VolumeFileName[MAX_PATH + 1]; + BOOL EnableKeyFiles; + KeyFile *FirstKeyFile; +} KeyFilesDlgParam; + +KeyFile *KeyFileAdd (KeyFile *firstKeyFile, KeyFile *keyFile); +void KeyFileRemoveAll (KeyFile **firstKeyFile); +KeyFile *KeyFileClone (KeyFile *keyFile); +void KeyFileCloneAll (KeyFile *firstKeyFile, KeyFile **outputKeyFile); +BOOL KeyFilesApply (HWND hwndDlg, Password *password, KeyFile *firstKeyFilem, const wchar_t* volumeFileName); +BOOL KeyFilesApplyWithPin (HWND hwndDlg, Password *password, char* pin, KeyFile *firstKeyFilem, const wchar_t* volumeFileName); + +BOOL CALLBACK KeyFilesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +BOOL KeyfilesPopupMenu (HWND hwndDlg, POINT popupPosition, KeyFilesDlgParam *dialogParam); + +extern BOOL HiddenFilesPresentInKeyfilePath; + +#ifdef __cplusplus +} +#endif + +#endif /* #ifndef KEYFILES_H */ diff --git a/src/Common/Language.c b/src/Common/Language.c index 44615e65..3d9b22d3 100644 --- a/src/Common/Language.c +++ b/src/Common/Language.c @@ -1,583 +1,583 @@ -/* - 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 "Language.h" -#include "Dlgcode.h" -#include "Dictionary.h" -#include "Tcdefs.h" -#include "Xml.h" - -#include "../Common/Resource.h" - -#ifdef TCMOUNT -#include "../Mount/Resource.h" -#endif - -#ifdef VOLFORMAT -#include "../Format/Resource.h" -#endif - -#ifdef SETUP -#include "../Setup/Resource.h" -#endif - -#include - -BOOL LocalizationActive; -int LocalizationSerialNo; - -wchar_t UnknownString[1024] = {0}; -static char *LanguageFileBuffer = NULL; -static HANDLE LanguageFileFindHandle = INVALID_HANDLE_VALUE; -static char PreferredLangId[6] = {0}; -static char *LanguageResource = NULL; -static DWORD LanguageResourceSize = 0; -static char *HeaderResource[2] = {NULL, NULL}; -static DWORD HeaderResourceSize[2] = {0, 0}; -static char ActiveLangPackVersion[6] = {0}; - -static char *MapFirstLanguageFile () -{ - if (LanguageFileFindHandle != INVALID_HANDLE_VALUE) - { - FindClose (LanguageFileFindHandle); - LanguageFileFindHandle = INVALID_HANDLE_VALUE; - } - - if (LanguageFileBuffer != NULL) - { - free (LanguageFileBuffer); - LanguageFileBuffer = NULL; - } - - if (LanguageResource == NULL) - { - DWORD size; - LanguageResource = MapResource (L"Xml", IDR_LANGUAGE, &size); - if (LanguageResource) - LanguageResourceSize = size; - } - - if (LanguageResource) - { - LanguageFileBuffer = malloc(LanguageResourceSize + 1); - if (LanguageFileBuffer) - { - memcpy (LanguageFileBuffer, LanguageResource, LanguageResourceSize); - LanguageFileBuffer[LanguageResourceSize] = 0; - } - } - - return LanguageFileBuffer; -} - - -static char *MapNextLanguageFile () -{ - wchar_t f[TC_MAX_PATH*2], *t; - WIN32_FIND_DATAW find; - HANDLE file; - DWORD read; - BOOL bStatus; - - /* free memory here to avoid leaks */ - if (LanguageFileBuffer != NULL) - { - free (LanguageFileBuffer); - LanguageFileBuffer = NULL; - } - - if (LanguageFileFindHandle == INVALID_HANDLE_VALUE) - { - GetModuleFileNameW (NULL, f, sizeof (f) / sizeof (f[0])); - t = wcsrchr (f, L'\\'); - if (t == NULL) return NULL; - - *t = 0; - StringCbCatW (f, sizeof(f), L"\\Language*.xml"); - - LanguageFileFindHandle = FindFirstFileW (f, &find); - } - else if (!FindNextFileW (LanguageFileFindHandle, &find)) - { - FindClose (LanguageFileFindHandle); - LanguageFileFindHandle = INVALID_HANDLE_VALUE; - return NULL; - } - - if (LanguageFileFindHandle == INVALID_HANDLE_VALUE) return NULL; - if (find.nFileSizeHigh != 0) return NULL; - - LanguageFileBuffer = malloc(find.nFileSizeLow + 1); - if (LanguageFileBuffer == NULL) return NULL; - - GetModuleFileNameW (NULL, f, sizeof (f) / sizeof(f[0])); - t = wcsrchr (f, L'\\'); - if (t == NULL) - { - free(LanguageFileBuffer); - LanguageFileBuffer = NULL; - return NULL; - } - - t[1] = 0; - StringCbCatW (f, sizeof(f),find.cFileName); - - file = CreateFileW (f, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); - if (file == INVALID_HANDLE_VALUE) - { - free(LanguageFileBuffer); - LanguageFileBuffer = NULL; - return NULL; - } - - bStatus = ReadFile (file, LanguageFileBuffer, find.nFileSizeLow, &read, NULL); - CloseHandle (file); - if (!bStatus || (read != find.nFileSizeLow)) - { - free(LanguageFileBuffer); - LanguageFileBuffer = NULL; - return NULL; - } - - LanguageFileBuffer [find.nFileSizeLow] = 0; // we have allocated (find.nFileSizeLow + 1) bytes - - return LanguageFileBuffer; -} - - -BOOL LoadLanguageFile () -{ - DWORD size; - BYTE *res; - char *xml, *header, *headerPtr; - char langId[6] = "en", attr[32768], key[128]; - BOOL defaultLangParsed = FALSE, langFound = FALSE; - WCHAR wattr[32768]; - int i, intKey, len; - - char *xmlElements[] = {"control", "string", 0}; - -#ifdef TCMOUNT - int headers[] = { IDR_COMMON_RSRC_HEADER, IDR_MOUNT_RSRC_HEADER, 0 }; -#endif - -#ifdef VOLFORMAT - int headers[] = { IDR_COMMON_RSRC_HEADER, IDR_FORMAT_RSRC_HEADER, 0 }; -#endif - -#ifdef SETUP - int headers[] = { IDR_COMMON_RSRC_HEADER, IDR_SETUP_RSRC_HEADER, 0 }; -#endif - - LocalizationActive = FALSE; - ActiveLangPackVersion[0] = 0; - ClearDictionaryPool (); - - if (PreferredLangId[0] != 0) - StringCbCopyA (langId, sizeof(langId), PreferredLangId); - - // Parse all available language files until preferred language is found - for (res = MapFirstLanguageFile (); res != NULL; res = MapNextLanguageFile ()) - { - xml = (char *) res; - xml = XmlFindElement (xml, "localization"); - if (!xml) - continue; - - // Required TrueCrypt version - XmlGetAttributeText (xml, "prog-version", attr, sizeof (attr)); - - // Check version of external language file - if (defaultLangParsed && strcmp (attr, VERSION_STRING) && strcmp (attr, "DEBUG")) - { - wchar_t m[2048]; - StringCbPrintfW (m, sizeof(m), L"The installed language pack is incompatible with this version of VeraCrypt (the language pack is for VeraCrypt %hs). A newer version may be available at www.idrix.fr.\n\nTo prevent this message from being displayed, do any of the following:\n\n- Select 'Settings' > 'Language'; then select 'English' and click 'OK'.\n\n- Remove or replace the language pack with a compatible version (the language pack may reside e.g. in 'C:\\Program Files\\VeraCrypt' or '%%LOCALAPPDATA%%\\VirtualStore\\Program Files\\VeraCrypt', etc.)", attr); - MessageBoxW (NULL, m, L"VeraCrypt", MB_ICONERROR); - continue; - } - - // Search language id in language file - if (defaultLangParsed) - { - while (xml = XmlFindElement (xml, "language")) - { - XmlGetAttributeText (xml, "langid", attr, sizeof (attr)); - if (strcmp (attr, langId) == 0) - { - XmlGetAttributeText (xml++, "version", ActiveLangPackVersion, sizeof (ActiveLangPackVersion)); - langFound = TRUE; - break; - } - xml++; - } - - if (!langFound) continue; - } - - // Create font dictionary - xml = (char *) res; - while (xml = XmlFindElement (xml, "font")) - { - XmlGetAttributeText (xml, "lang", attr, sizeof (attr)); - if (!defaultLangParsed - || strcmp (attr, langId) == 0) - { - Font font; - memset (&font, 0, sizeof (font)); - - XmlGetAttributeText (xml, "face", attr, sizeof (attr)); - - len = MultiByteToWideChar (CP_UTF8, 0, attr, -1, wattr, sizeof (wattr) / sizeof(wattr[0])); - font.FaceName = AddPoolData ((void *) wattr, len * 2); - - XmlGetAttributeText (xml, "size", attr, sizeof (attr)); - sscanf (attr, "%d", &font.Size); - - StringCbCopyA (attr, sizeof(attr), "font_"); - XmlGetAttributeText (xml, "class", attr + 5, sizeof (attr) - 5); - AddDictionaryEntry ( - AddPoolData ((void *) attr, strlen (attr) + 1), 0, - AddPoolData ((void *) &font, sizeof(font))); - } - - xml++; - } - - // Create string and control dictionaries - for (i = 0; xmlElements[i] != 0; i++) - { - xml = (char *) res; - while (xml = XmlFindElement (xml, xmlElements[i])) - { - void *key; - void *text; - - XmlGetAttributeText (xml, "lang", attr, sizeof (attr)); - if (!defaultLangParsed - || strcmp (attr, langId) == 0) - { - if (XmlGetAttributeText (xml, "key", attr, sizeof (attr))) - { - key = AddPoolData (attr, strlen (attr) + 1); - if (key == NULL) return FALSE; - - XmlGetNodeText (xml, attr, sizeof (attr)); - - // Parse \ escape sequences - { - char *in = attr, *out = attr; - while (*in) - { - if (*in == '\\') - { - in++; - switch (*in++) - { - case '\\': *out++ = '\\'; break; - case 't': *out++ = '\t'; break; - case 'n': *out++ = 13; *out++ = 10; break; - default: - MessageBoxA (0, key, "VeraCrypt: Unknown '\\' escape sequence in string", MB_ICONERROR); - return FALSE; - } - } - else - *out++ = *in++; - } - *out = 0; - } - - // UTF8 => wide char - len = MultiByteToWideChar (CP_UTF8, 0, attr, -1, wattr, sizeof (wattr) / sizeof(wattr[0])); - if (len == 0) - { - MessageBoxA (0, key, "VeraCrypt: Error while decoding UTF-8 string", MB_ICONERROR); - return FALSE; - } - - // Add to dictionary - text = AddPoolData ((void *) wattr, len * 2); - if (text == NULL) return FALSE; - - AddDictionaryEntry ((char *) key, 0, text); - } - } - - xml++; - } - } - - if (langFound) - break; - - if (!defaultLangParsed) - { - defaultLangParsed = TRUE; - if (langId[0] == 0 || strcmp (langId, "en") == 0) - break; - } - } - - LocalizationActive = langFound && strcmp (langId, "en") != 0; - LocalizationSerialNo++; - - // Create control ID dictionary - - // Default controls - AddDictionaryEntry (NULL, 1, GetString ("IDOK")); - AddDictionaryEntry (NULL, 2, GetString ("IDCANCEL")); - AddDictionaryEntry (NULL, 8, GetString ("IDCLOSE")); - AddDictionaryEntry (NULL, 9, GetString ("IDHELP")); - - for (i = 0; headers[i] != 0; i++) - { - if (HeaderResource[i] == NULL) - { - HeaderResource[i] = MapResource (L"Header", headers[i], &size); - if (HeaderResource[i]) - HeaderResourceSize[i] = size; - } - - headerPtr = NULL; - if (HeaderResource[i]) - { - headerPtr = (char*) malloc (HeaderResourceSize[i] + 1); - if (headerPtr) - { - memcpy (headerPtr, HeaderResource[i], HeaderResourceSize[i]); - headerPtr [HeaderResourceSize[i]] = 0; - } - } - - header = headerPtr; - if (header == NULL) return FALSE; - - do - { - if (sscanf (header, "#define %127s %d", key, &intKey) == 2) - { - WCHAR *str = GetString (key); - - if (str != UnknownString) - AddDictionaryEntry (NULL, intKey, str); - } - - } while ((header = strchr (header, '\n') + 1) != (char *) 1); - - free (headerPtr); - } - - return TRUE; -} - - -// lParam = 1: auto mode -BOOL CALLBACK LanguageDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - WORD hw = HIWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - char *xml; - char attr[2048], lastLangId[10]; - WCHAR wattr[2048]; - int len; - int langCount = 0; - BOOL defaultLangFound = FALSE; - - LocalizeDialog (hwndDlg, "IDD_LANGUAGE"); - ToHyperlink (hwndDlg, IDC_GET_LANG_PACKS); - - for (xml = MapFirstLanguageFile (); xml != NULL; xml = MapNextLanguageFile ()) - { - while (xml = XmlFindElement (xml, "language")) - { - XmlGetAttributeText (xml, "name", attr, sizeof (attr)); - len = MultiByteToWideChar (CP_UTF8, 0, attr, -1, wattr, sizeof (wattr) / sizeof(wattr[0])); - - if (len != 0 - && (!defaultLangFound || wcscmp (wattr, L"English") != 0)) - { - int i = (int) SendDlgItemMessageW (hwndDlg, IDC_LANGLIST, LB_ADDSTRING, 0, (LPARAM)wattr); - if (i >= 0) - { - int id; - - // Encode language id in LPARAM - XmlGetAttributeText (xml, "langid", attr, sizeof (attr)); - switch (strlen (attr)) - { - case 2: id = attr[0] | attr[1] << 8; break; - case 5: id = attr[0] | attr[1] << 8 | attr[3] << 16 | attr[4] << 24; break; - default: continue; - } - - if (!defaultLangFound) - defaultLangFound = TRUE; - - SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_SETITEMDATA, i, (LPARAM) id); - - if (strcmp (attr, PreferredLangId) == 0) - { - char credits [10000]; - WCHAR wcredits [10000]; - WCHAR wversion [20]; - wchar_t szVers [200]; - int nLen; - - SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_SETCURSEL, i, 0); - - // Language pack version - if (!ActiveLangPackVersion[0] || memcmp (ActiveLangPackVersion, "0.0.0", 5) == 0) - { - StringCbPrintfW (szVers, sizeof(szVers), GetString("LANG_PACK_VERSION"), L"--"); - } - else - { - nLen = MultiByteToWideChar (CP_UTF8, 0, ActiveLangPackVersion, -1, wversion, sizeof (wversion) / sizeof(wversion[0])); - if (nLen != 0) - StringCbPrintfW (szVers, sizeof(szVers),GetString("LANG_PACK_VERSION"), wversion); - } - SetWindowTextW (GetDlgItem (hwndDlg, IDC_LANGPACK_VERSION), szVers); - - // Translator credits - XmlGetAttributeText (xml, "translators", credits, sizeof (credits)); - nLen = MultiByteToWideChar (CP_UTF8, 0, credits, -1, wcredits, sizeof (wcredits) / sizeof(wcredits[0])); - if (nLen != 0) - { - SetWindowTextW (GetDlgItem (hwndDlg, IDC_LANGPACK_CREDITS), wcredits); - } - } - - StringCbCopyA (lastLangId, sizeof(lastLangId),attr); - langCount++; - } - } - - xml++; - } - } - - if (lParam == 1) - { - // Auto mode - if (langCount < 2) - EndDialog (hwndDlg, IDCANCEL); - - if (langCount == 2) - StringCbCopyA (PreferredLangId, sizeof(PreferredLangId), lastLangId); - - EndDialog (hwndDlg, IDOK); - } - - return 1; - } - - case WM_COMMAND: - - if (lw == IDOK || hw == LBN_DBLCLK) - { - int i = (int) SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_GETCURSEL, 0, 0); - - if (i >= 0) - { - int id = (int) SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_GETITEMDATA, i, 0); - - if (id != LB_ERR) - { - char l[6]; - - // Decode language id from LPARAM - l[0] = (char) id; - l[1] = (char) (id >> 8); - l[2] = 0; - - if ((id & 0xffff0000) != 0) - { - l[2] = '-'; - l[3] = (char) (id >> 16); - l[4] = id >> 24; - l[5] = 0; - } - - if (SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_GETCOUNT, 0, 0) > 1) - StringCbCopyA (PreferredLangId, sizeof(PreferredLangId), l); - } - } - - EndDialog (hwndDlg, IDOK); - return 1; - } - - if (lw == IDCANCEL) - { - EndDialog (hwndDlg, lw); - return 1; - } - - if (lw == IDC_GET_LANG_PACKS) - { - char tmpstr [256]; - - if (strlen (ActiveLangPackVersion) > 0 && strlen (GetPreferredLangId()) > 0) - StringCbPrintfA (tmpstr, sizeof(tmpstr), "&langpackversion=%s&lang=%s", ActiveLangPackVersion, GetPreferredLangId()); - else - tmpstr[0] = 0; - - Applink ("localizations", TRUE, tmpstr); - - return 1; - } - return 0; - } - - return 0; -} - - -char *GetPreferredLangId () -{ - return PreferredLangId; -} - - -void SetPreferredLangId (char *langId) -{ - StringCbCopyA (PreferredLangId, sizeof(PreferredLangId), langId); -} - - -char *GetActiveLangPackVersion () -{ - return ActiveLangPackVersion; -} - - -wchar_t *GetString (const char *stringId) -{ - WCHAR *str = (WCHAR *) GetDictionaryValue (stringId); - if (str != NULL) return str; - - StringCbPrintfW (UnknownString, sizeof(UnknownString), UNKNOWN_STRING_ID L"%hs" UNKNOWN_STRING_ID, stringId); - return UnknownString; -} - - -Font *GetFont (char *fontType) -{ - return (Font *) GetDictionaryValue (fontType); - -} +/* + 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 "Language.h" +#include "Dlgcode.h" +#include "Dictionary.h" +#include "Tcdefs.h" +#include "Xml.h" + +#include "../Common/Resource.h" + +#ifdef TCMOUNT +#include "../Mount/Resource.h" +#endif + +#ifdef VOLFORMAT +#include "../Format/Resource.h" +#endif + +#ifdef SETUP +#include "../Setup/Resource.h" +#endif + +#include + +BOOL LocalizationActive; +int LocalizationSerialNo; + +wchar_t UnknownString[1024] = {0}; +static char *LanguageFileBuffer = NULL; +static HANDLE LanguageFileFindHandle = INVALID_HANDLE_VALUE; +static char PreferredLangId[6] = {0}; +static char *LanguageResource = NULL; +static DWORD LanguageResourceSize = 0; +static char *HeaderResource[2] = {NULL, NULL}; +static DWORD HeaderResourceSize[2] = {0, 0}; +static char ActiveLangPackVersion[6] = {0}; + +static char *MapFirstLanguageFile () +{ + if (LanguageFileFindHandle != INVALID_HANDLE_VALUE) + { + FindClose (LanguageFileFindHandle); + LanguageFileFindHandle = INVALID_HANDLE_VALUE; + } + + if (LanguageFileBuffer != NULL) + { + free (LanguageFileBuffer); + LanguageFileBuffer = NULL; + } + + if (LanguageResource == NULL) + { + DWORD size; + LanguageResource = MapResource (L"Xml", IDR_LANGUAGE, &size); + if (LanguageResource) + LanguageResourceSize = size; + } + + if (LanguageResource) + { + LanguageFileBuffer = malloc(LanguageResourceSize + 1); + if (LanguageFileBuffer) + { + memcpy (LanguageFileBuffer, LanguageResource, LanguageResourceSize); + LanguageFileBuffer[LanguageResourceSize] = 0; + } + } + + return LanguageFileBuffer; +} + + +static char *MapNextLanguageFile () +{ + wchar_t f[TC_MAX_PATH*2], *t; + WIN32_FIND_DATAW find; + HANDLE file; + DWORD read; + BOOL bStatus; + + /* free memory here to avoid leaks */ + if (LanguageFileBuffer != NULL) + { + free (LanguageFileBuffer); + LanguageFileBuffer = NULL; + } + + if (LanguageFileFindHandle == INVALID_HANDLE_VALUE) + { + GetModuleFileNameW (NULL, f, sizeof (f) / sizeof (f[0])); + t = wcsrchr (f, L'\\'); + if (t == NULL) return NULL; + + *t = 0; + StringCbCatW (f, sizeof(f), L"\\Language*.xml"); + + LanguageFileFindHandle = FindFirstFileW (f, &find); + } + else if (!FindNextFileW (LanguageFileFindHandle, &find)) + { + FindClose (LanguageFileFindHandle); + LanguageFileFindHandle = INVALID_HANDLE_VALUE; + return NULL; + } + + if (LanguageFileFindHandle == INVALID_HANDLE_VALUE) return NULL; + if (find.nFileSizeHigh != 0) return NULL; + + LanguageFileBuffer = malloc(find.nFileSizeLow + 1); + if (LanguageFileBuffer == NULL) return NULL; + + GetModuleFileNameW (NULL, f, sizeof (f) / sizeof(f[0])); + t = wcsrchr (f, L'\\'); + if (t == NULL) + { + free(LanguageFileBuffer); + LanguageFileBuffer = NULL; + return NULL; + } + + t[1] = 0; + StringCbCatW (f, sizeof(f),find.cFileName); + + file = CreateFileW (f, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); + if (file == INVALID_HANDLE_VALUE) + { + free(LanguageFileBuffer); + LanguageFileBuffer = NULL; + return NULL; + } + + bStatus = ReadFile (file, LanguageFileBuffer, find.nFileSizeLow, &read, NULL); + CloseHandle (file); + if (!bStatus || (read != find.nFileSizeLow)) + { + free(LanguageFileBuffer); + LanguageFileBuffer = NULL; + return NULL; + } + + LanguageFileBuffer [find.nFileSizeLow] = 0; // we have allocated (find.nFileSizeLow + 1) bytes + + return LanguageFileBuffer; +} + + +BOOL LoadLanguageFile () +{ + DWORD size; + BYTE *res; + char *xml, *header, *headerPtr; + char langId[6] = "en", attr[32768], key[128]; + BOOL defaultLangParsed = FALSE, langFound = FALSE; + WCHAR wattr[32768]; + int i, intKey, len; + + char *xmlElements[] = {"control", "string", 0}; + +#ifdef TCMOUNT + int headers[] = { IDR_COMMON_RSRC_HEADER, IDR_MOUNT_RSRC_HEADER, 0 }; +#endif + +#ifdef VOLFORMAT + int headers[] = { IDR_COMMON_RSRC_HEADER, IDR_FORMAT_RSRC_HEADER, 0 }; +#endif + +#ifdef SETUP + int headers[] = { IDR_COMMON_RSRC_HEADER, IDR_SETUP_RSRC_HEADER, 0 }; +#endif + + LocalizationActive = FALSE; + ActiveLangPackVersion[0] = 0; + ClearDictionaryPool (); + + if (PreferredLangId[0] != 0) + StringCbCopyA (langId, sizeof(langId), PreferredLangId); + + // Parse all available language files until preferred language is found + for (res = MapFirstLanguageFile (); res != NULL; res = MapNextLanguageFile ()) + { + xml = (char *) res; + xml = XmlFindElement (xml, "localization"); + if (!xml) + continue; + + // Required TrueCrypt version + XmlGetAttributeText (xml, "prog-version", attr, sizeof (attr)); + + // Check version of external language file + if (defaultLangParsed && strcmp (attr, VERSION_STRING) && strcmp (attr, "DEBUG")) + { + wchar_t m[2048]; + StringCbPrintfW (m, sizeof(m), L"The installed language pack is incompatible with this version of VeraCrypt (the language pack is for VeraCrypt %hs). A newer version may be available at www.idrix.fr.\n\nTo prevent this message from being displayed, do any of the following:\n\n- Select 'Settings' > 'Language'; then select 'English' and click 'OK'.\n\n- Remove or replace the language pack with a compatible version (the language pack may reside e.g. in 'C:\\Program Files\\VeraCrypt' or '%%LOCALAPPDATA%%\\VirtualStore\\Program Files\\VeraCrypt', etc.)", attr); + MessageBoxW (NULL, m, L"VeraCrypt", MB_ICONERROR); + continue; + } + + // Search language id in language file + if (defaultLangParsed) + { + while (xml = XmlFindElement (xml, "language")) + { + XmlGetAttributeText (xml, "langid", attr, sizeof (attr)); + if (strcmp (attr, langId) == 0) + { + XmlGetAttributeText (xml++, "version", ActiveLangPackVersion, sizeof (ActiveLangPackVersion)); + langFound = TRUE; + break; + } + xml++; + } + + if (!langFound) continue; + } + + // Create font dictionary + xml = (char *) res; + while (xml = XmlFindElement (xml, "font")) + { + XmlGetAttributeText (xml, "lang", attr, sizeof (attr)); + if (!defaultLangParsed + || strcmp (attr, langId) == 0) + { + Font font; + memset (&font, 0, sizeof (font)); + + XmlGetAttributeText (xml, "face", attr, sizeof (attr)); + + len = MultiByteToWideChar (CP_UTF8, 0, attr, -1, wattr, sizeof (wattr) / sizeof(wattr[0])); + font.FaceName = AddPoolData ((void *) wattr, len * 2); + + XmlGetAttributeText (xml, "size", attr, sizeof (attr)); + sscanf (attr, "%d", &font.Size); + + StringCbCopyA (attr, sizeof(attr), "font_"); + XmlGetAttributeText (xml, "class", attr + 5, sizeof (attr) - 5); + AddDictionaryEntry ( + AddPoolData ((void *) attr, strlen (attr) + 1), 0, + AddPoolData ((void *) &font, sizeof(font))); + } + + xml++; + } + + // Create string and control dictionaries + for (i = 0; xmlElements[i] != 0; i++) + { + xml = (char *) res; + while (xml = XmlFindElement (xml, xmlElements[i])) + { + void *key; + void *text; + + XmlGetAttributeText (xml, "lang", attr, sizeof (attr)); + if (!defaultLangParsed + || strcmp (attr, langId) == 0) + { + if (XmlGetAttributeText (xml, "key", attr, sizeof (attr))) + { + key = AddPoolData (attr, strlen (attr) + 1); + if (key == NULL) return FALSE; + + XmlGetNodeText (xml, attr, sizeof (attr)); + + // Parse \ escape sequences + { + char *in = attr, *out = attr; + while (*in) + { + if (*in == '\\') + { + in++; + switch (*in++) + { + case '\\': *out++ = '\\'; break; + case 't': *out++ = '\t'; break; + case 'n': *out++ = 13; *out++ = 10; break; + default: + MessageBoxA (0, key, "VeraCrypt: Unknown '\\' escape sequence in string", MB_ICONERROR); + return FALSE; + } + } + else + *out++ = *in++; + } + *out = 0; + } + + // UTF8 => wide char + len = MultiByteToWideChar (CP_UTF8, 0, attr, -1, wattr, sizeof (wattr) / sizeof(wattr[0])); + if (len == 0) + { + MessageBoxA (0, key, "VeraCrypt: Error while decoding UTF-8 string", MB_ICONERROR); + return FALSE; + } + + // Add to dictionary + text = AddPoolData ((void *) wattr, len * 2); + if (text == NULL) return FALSE; + + AddDictionaryEntry ((char *) key, 0, text); + } + } + + xml++; + } + } + + if (langFound) + break; + + if (!defaultLangParsed) + { + defaultLangParsed = TRUE; + if (langId[0] == 0 || strcmp (langId, "en") == 0) + break; + } + } + + LocalizationActive = langFound && strcmp (langId, "en") != 0; + LocalizationSerialNo++; + + // Create control ID dictionary + + // Default controls + AddDictionaryEntry (NULL, 1, GetString ("IDOK")); + AddDictionaryEntry (NULL, 2, GetString ("IDCANCEL")); + AddDictionaryEntry (NULL, 8, GetString ("IDCLOSE")); + AddDictionaryEntry (NULL, 9, GetString ("IDHELP")); + + for (i = 0; headers[i] != 0; i++) + { + if (HeaderResource[i] == NULL) + { + HeaderResource[i] = MapResource (L"Header", headers[i], &size); + if (HeaderResource[i]) + HeaderResourceSize[i] = size; + } + + headerPtr = NULL; + if (HeaderResource[i]) + { + headerPtr = (char*) malloc (HeaderResourceSize[i] + 1); + if (headerPtr) + { + memcpy (headerPtr, HeaderResource[i], HeaderResourceSize[i]); + headerPtr [HeaderResourceSize[i]] = 0; + } + } + + header = headerPtr; + if (header == NULL) return FALSE; + + do + { + if (sscanf (header, "#define %127s %d", key, &intKey) == 2) + { + WCHAR *str = GetString (key); + + if (str != UnknownString) + AddDictionaryEntry (NULL, intKey, str); + } + + } while ((header = strchr (header, '\n') + 1) != (char *) 1); + + free (headerPtr); + } + + return TRUE; +} + + +// lParam = 1: auto mode +BOOL CALLBACK LanguageDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + WORD hw = HIWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + char *xml; + char attr[2048], lastLangId[10]; + WCHAR wattr[2048]; + int len; + int langCount = 0; + BOOL defaultLangFound = FALSE; + + LocalizeDialog (hwndDlg, "IDD_LANGUAGE"); + ToHyperlink (hwndDlg, IDC_GET_LANG_PACKS); + + for (xml = MapFirstLanguageFile (); xml != NULL; xml = MapNextLanguageFile ()) + { + while (xml = XmlFindElement (xml, "language")) + { + XmlGetAttributeText (xml, "name", attr, sizeof (attr)); + len = MultiByteToWideChar (CP_UTF8, 0, attr, -1, wattr, sizeof (wattr) / sizeof(wattr[0])); + + if (len != 0 + && (!defaultLangFound || wcscmp (wattr, L"English") != 0)) + { + int i = (int) SendDlgItemMessageW (hwndDlg, IDC_LANGLIST, LB_ADDSTRING, 0, (LPARAM)wattr); + if (i >= 0) + { + int id; + + // Encode language id in LPARAM + XmlGetAttributeText (xml, "langid", attr, sizeof (attr)); + switch (strlen (attr)) + { + case 2: id = attr[0] | attr[1] << 8; break; + case 5: id = attr[0] | attr[1] << 8 | attr[3] << 16 | attr[4] << 24; break; + default: continue; + } + + if (!defaultLangFound) + defaultLangFound = TRUE; + + SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_SETITEMDATA, i, (LPARAM) id); + + if (strcmp (attr, PreferredLangId) == 0) + { + char credits [10000]; + WCHAR wcredits [10000]; + WCHAR wversion [20]; + wchar_t szVers [200]; + int nLen; + + SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_SETCURSEL, i, 0); + + // Language pack version + if (!ActiveLangPackVersion[0] || memcmp (ActiveLangPackVersion, "0.0.0", 5) == 0) + { + StringCbPrintfW (szVers, sizeof(szVers), GetString("LANG_PACK_VERSION"), L"--"); + } + else + { + nLen = MultiByteToWideChar (CP_UTF8, 0, ActiveLangPackVersion, -1, wversion, sizeof (wversion) / sizeof(wversion[0])); + if (nLen != 0) + StringCbPrintfW (szVers, sizeof(szVers),GetString("LANG_PACK_VERSION"), wversion); + } + SetWindowTextW (GetDlgItem (hwndDlg, IDC_LANGPACK_VERSION), szVers); + + // Translator credits + XmlGetAttributeText (xml, "translators", credits, sizeof (credits)); + nLen = MultiByteToWideChar (CP_UTF8, 0, credits, -1, wcredits, sizeof (wcredits) / sizeof(wcredits[0])); + if (nLen != 0) + { + SetWindowTextW (GetDlgItem (hwndDlg, IDC_LANGPACK_CREDITS), wcredits); + } + } + + StringCbCopyA (lastLangId, sizeof(lastLangId),attr); + langCount++; + } + } + + xml++; + } + } + + if (lParam == 1) + { + // Auto mode + if (langCount < 2) + EndDialog (hwndDlg, IDCANCEL); + + if (langCount == 2) + StringCbCopyA (PreferredLangId, sizeof(PreferredLangId), lastLangId); + + EndDialog (hwndDlg, IDOK); + } + + return 1; + } + + case WM_COMMAND: + + if (lw == IDOK || hw == LBN_DBLCLK) + { + int i = (int) SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_GETCURSEL, 0, 0); + + if (i >= 0) + { + int id = (int) SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_GETITEMDATA, i, 0); + + if (id != LB_ERR) + { + char l[6]; + + // Decode language id from LPARAM + l[0] = (char) id; + l[1] = (char) (id >> 8); + l[2] = 0; + + if ((id & 0xffff0000) != 0) + { + l[2] = '-'; + l[3] = (char) (id >> 16); + l[4] = id >> 24; + l[5] = 0; + } + + if (SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_GETCOUNT, 0, 0) > 1) + StringCbCopyA (PreferredLangId, sizeof(PreferredLangId), l); + } + } + + EndDialog (hwndDlg, IDOK); + return 1; + } + + if (lw == IDCANCEL) + { + EndDialog (hwndDlg, lw); + return 1; + } + + if (lw == IDC_GET_LANG_PACKS) + { + char tmpstr [256]; + + if (strlen (ActiveLangPackVersion) > 0 && strlen (GetPreferredLangId()) > 0) + StringCbPrintfA (tmpstr, sizeof(tmpstr), "&langpackversion=%s&lang=%s", ActiveLangPackVersion, GetPreferredLangId()); + else + tmpstr[0] = 0; + + Applink ("localizations", TRUE, tmpstr); + + return 1; + } + return 0; + } + + return 0; +} + + +char *GetPreferredLangId () +{ + return PreferredLangId; +} + + +void SetPreferredLangId (char *langId) +{ + StringCbCopyA (PreferredLangId, sizeof(PreferredLangId), langId); +} + + +char *GetActiveLangPackVersion () +{ + return ActiveLangPackVersion; +} + + +wchar_t *GetString (const char *stringId) +{ + WCHAR *str = (WCHAR *) GetDictionaryValue (stringId); + if (str != NULL) return str; + + StringCbPrintfW (UnknownString, sizeof(UnknownString), UNKNOWN_STRING_ID L"%hs" UNKNOWN_STRING_ID, stringId); + return UnknownString; +} + + +Font *GetFont (char *fontType) +{ + return (Font *) GetDictionaryValue (fontType); + +} diff --git a/src/Common/Language.h b/src/Common/Language.h index 7bce30a3..4e4c1795 100644 --- a/src/Common/Language.h +++ b/src/Common/Language.h @@ -1,43 +1,43 @@ -/* - 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. -*/ - -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define UNKNOWN_STRING_ID L"[?]" - -extern BOOL LocalizationActive; -extern int LocalizationSerialNo; -extern wchar_t UnknownString[1024]; - -typedef struct -{ - wchar_t *FaceName; - int Size; -} Font; - -BOOL CALLBACK LanguageDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -wchar_t *GetString (const char *stringId); -Font *GetFont (char *fontType); -BOOL LoadLanguageFile (); -char *GetPreferredLangId (); -void SetPreferredLangId (char *langId); -char *GetActiveLangPackVersion (); - -#ifdef __cplusplus -} -#endif +/* + 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. +*/ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define UNKNOWN_STRING_ID L"[?]" + +extern BOOL LocalizationActive; +extern int LocalizationSerialNo; +extern wchar_t UnknownString[1024]; + +typedef struct +{ + wchar_t *FaceName; + int Size; +} Font; + +BOOL CALLBACK LanguageDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +wchar_t *GetString (const char *stringId); +Font *GetFont (char *fontType); +BOOL LoadLanguageFile (); +char *GetPreferredLangId (); +void SetPreferredLangId (char *langId); +char *GetActiveLangPackVersion (); + +#ifdef __cplusplus +} +#endif diff --git a/src/Common/Language.xml b/src/Common/Language.xml index add35c7a..99e260c0 100644 --- a/src/Common/Language.xml +++ b/src/Common/Language.xml @@ -1,1456 +1,1456 @@ - - - - - - - - - - - - Cancel - Install &for all users - Bro&wse... - Add VeraCrypt icon to &desktop - Donate now... - Associate the .hc file &extension with VeraCrypt - &Open the destination location when finished - Add VeraCrypt to &Start menu - Create System &Restore point - &Uninstall - &Extract - &Install - VeraCrypt Setup Wizard - Uninstall VeraCrypt - &Help - Please select or type the location where you want to place the extracted files: - Please select or type the location where you want to install the VeraCrypt program files. If the specified folder does not exist, it will be automatically created. - Click Uninstall to remove VeraCrypt from this system. - Abort - &Benchmark - &Test - Create encrypted volume and format it - Encrypt partition in place - Display generated keys (their portions) - Display pool content - Download CD/DVD recording software - Create an encrypted file container - &GB - &TB - More information - Hi&dden VeraCrypt volume - More information about hidden volumes - Direct mode - Normal mode - &KB - U&se keyfiles - Try first to mount with an empty password - Random size ( 64 <-> 1048576 ) - &Keyfiles... - Information on hash algorithms - More information - Information on PIM - &MB - More information - More information about system encryption - More information - Multi-Boot - Encrypt a non-system partition/drive - &Never save history - Open Outer Volume - &Pause - Use P&IM - Use PIM - Quick Format - &Display password - &Display password - &Display PIM - Single-boot - Standard VeraCrypt volume - Hi&dden - Normal - Encrypt the system partition or entire system drive - Encrypt the Windows system partition - Encrypt the whole drive - VeraCrypt Volume Creation Wizard - Cluster - IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the encryption keys. Then click Next to continue. - &Confirm: - Done - Drive letter: - Encryption Algorithm - Filesystem - Creates a virtual encrypted disk within a file. Recommended for inexperienced users. - Options - Hash Algorithm - Header Key: - Left - Master Key: - Select this option if there are two or more operating systems installed on this computer.\n\nFor example:\n- Windows XP and Windows XP\n- Windows XP and Windows Vista\n- Windows and Mac OS X\n- Windows and Linux\n- Windows, Linux and Mac OS X - Encrypts a non-system partition on any internal or external drive (e.g. a flash drive). Optionally, creates a hidden volume. - Current pool content (partial) - Pass - Password: - Volume PIM: - Volume PIM: - Progress: - Random Pool: - Select this option if there is only one operating system installed on this computer (even if it has multiple users). - Speed - Status - The keys, salt, and other data have been successfully generated. If you want to generate new keys, click Back and then Next. Otherwise, click Next to continue. - Encrypts the partition/drive where Windows is installed. Anyone who wants to gain access and use the system, read and write files, etc., will need to enter the correct password each time before Windows boots. Optionally, creates a hidden system. - Select this option to encrypt the partition where the currently running Windows operating system is installed. - Volume Label in Windows: - Wipe mode: - Close - Allow pre-boot &authentication to be bypassed by pressing the Esc key (enables boot manager) - Do nothing - &Auto-mount VeraCrypt volume (specified below) - &Start VeraCrypt - Auto-&Detect Library - &Cache pre-boot authentication password in driver memory (for mounting of non-system volumes) - Browse... - Browse... - Cache passwords and keyfil&es in memory - Exit when there are no mounted volumes - &Close token session (log out) after a volume is successfully mounted - Include VeraCrypt Volume Expander - Include VeraCrypt Volume Creation Wizard - Create - &Create Volume - Do not &show any texts in the pre-boot authentication screen (except the below custom message) - Disable "Evil Maid" attack detection - Accelerate AES encryption/decryption by using the AES instructions of the processor (if available) - Use keyfiles - Use keyfiles - E&xit - Help on favorite volumes - Do not mount selected volume when 'Mount Favorite Volumes' &hot key is pressed - Mount selected volume when its host device gets &connected - Mount selected volume upon log&on - Mount selected volume as read-o&nly - Mount selected volume as remo&vable medium - Move &Down - Move &Up - Open &Explorer window for selected volume when successfully mounted - &Remove - Use favorite label as Explorer drive label - Global Settings - Display balloon tooltip after successful hot-key dismount - Play system notification sound after successful hot-key dismount - Alt - Ctrl - Shift - Win - Assign - Remove - Keyfiles... - Do not use the following number of processors for encryption/decryption: - More information - More information - More Settings... - &Auto-Mount Devices - Mount Opti&ons... - Mount volume as read-&only - Keyfiles... - (Empty or 0 for default iterations) - (Empty or 0 for default iterations) - Enabled - Cache passwords in driver memory - Auto-dismount volume after no data has been read/written to it for - User logs off - User session locked - Entering power saving mode - Screen saver is launched - Force auto-dismount even if volume contains open files or directories - Mount all device-hosted VeraCrypt volumes - Start VeraCrypt Background Task - Mount volumes as read-only - Mount volumes as removable media - Open Explorer window for successfully mounted volume - Temporary Cache password during "Mount Favorite Volumes" operations - Use a different taskbar icon when there are mounted volumes - Wipe cached passwords on auto-dismount - Wipe cached passwords on exit - Preserve modification timestamp of file containers - Reset - Select D&evice... - Select &File... - Select &Library... - Display password - Display password - Open &Explorer window for mounted volume - &Cache password in driver memory - TrueCrypt Mode - Di&smount All - &Volume Properties... - Volume &Tools... - &Wipe Cache - VeraCrypt - Mount Parameters - VeraCrypt - Favorite Volumes - VeraCrypt - System-Wide Hot Keys - VeraCrypt - Change Password or Keyfiles - Enter VeraCrypt Volume Password - VeraCrypt - Performance and Driver Options - VeraCrypt - Preferences - VeraCrypt - System Encryption Settings - VeraCrypt - Security Token Preferences - VeraCrypt Traveler Disk Setup - VeraCrypt Volume Properties - About - Add/Remove Keyfiles to/from Volume... - Add Mounted Volume to Favorites... - Add Mounted Volume to System Favorites... - Analyze a System Crash... - Backup Volume Header... - Benchmark... - Set Header Key Derivation Algorithm... - Change Volume Password... - Set Header Key Derivation Algorithm... - Change Password... - Clear Volume History - Close All Security Token Sessions - Contact - Create Hidden Operating System... - Create Rescue Disk... - Create New Volume... - Permanently Decrypt... - Default Keyfiles... - Default Mount Parameters... - Donate now... - Encrypt System Partition/Drive... - Frequently Asked Questions - User's Guide - &Homepage - Hot Keys... - Keyfile Generator - Language... - Legal Notices - Manage Security Token Keyfiles... - Auto-Mount All Device-Hosted Volumes - Mount Favorite Volumes - Mount Without Pre-Boot &Authentication... - Mount Volume - Mount Volume with Options - News - Online Help - Beginner's Tutorial - Organize Favorite Volumes... - Organize System Favorite Volumes... - Performance/Driver Configuration - Permanently Decrypt System Partition/Drive - Preferences... - Refresh Drive Letters - Remove All Keyfiles from Volume... - Restore Volume Header... - Resume Interrupted Process - Select Device... - Select File... - Resume Interrupted Process - System Encryption... - Properties... - Settings... - System Favorite Volumes... - Downloads - Test Vectors... - Security Tokens... - Traveler Disk Setup... - Dismount All Mounted Volumes - Dismount Volume - Verify Rescue Disk - Verify Rescue Disk ISO Image - Version History - Volume Expander - Volume Properties - Volume Creation Wizard - VeraCrypt Website - Wipe Cached Passwords - OK - Hardware Acceleration - Shortcut - AutoRun Configuration (autorun.inf) - Auto-Dismount - Dismount all when: - Boot Loader Screen Options - Confirm Password: - Current - Display this custom message in the pre-boot authentication screen (24 characters maximum): - Default Mount Options - Hot Key Options - Driver Configuration - Enable extended disk control codes support - Label of selected favorite volume: - File Settings - Key to assign: - Processor (CPU) in this computer supports hardware acceleration for AES: - Actions to perform upon logon to Windows - minutes - Mount volume as drive letter: - Mount Settings - New - Password: - Thread-Based Parallelization - PKCS #11 Library Path - PKCS-5 PRF: - PKCS-5 PRF: - Password Cache - Security Options - VeraCrypt Background Task - VeraCrypt volume to mount (relative to traveler disk root): - Upon insertion of traveler disk: - Create traveler disk files at (traveler disk root directory): - Volume - Windows - Add &Path... - &Auto-Test All - &Continue - &Decrypt - &Delete - &Encrypt - &Export... - Generate and Save Keyfile... - &Generate Random Keyfile... - Download language pack - Hardware-accelerated AES: - &Import Keyfile to Token... - Add &Files... - U&se keyfiles - &Keyfiles... - &Remove - Remove &All - What is hidden volume protection? - More information on keyfiles - Mount volume as removable &medium - Mount partition &using system encryption without pre-boot authentication - Parallelization: - Benchmark - &Print - &Protect hidden volume against damage caused by writing to outer volume - &Reset - &Display password - Add &Token Files... - Use backup header embedded in &volume if available - XTS mode - About VeraCrypt - VeraCrypt - Encryption Algorithm Benchmark - VeraCrypt - Test Vectors - Command Line Help - VeraCrypt - Keyfiles - VeraCrypt - Keyfile Generator - VeraCrypt - Language - VeraCrypt - Mount Options - New Security Token Keyfile Properties - VeraCrypt - Random Pool Enrichment - Select a Partition or Device - VeraCrypt - Security Token Keyfiles - Security token password/PIN required - Active language pack - Speed is affected by CPU load and storage device characteristics.\n\nThese tests take place in RAM. - Buffer Size: - Cipher: - P&assword to hidden volume:\n(if empty, cache is used) - Hidden Volume Protection - Key size: - IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the keyfile. - WARNING: If you lose a keyfile or if any bit of its first 1024 kilobytes changes, it will be impossible to mount volumes that use the keyfile! - bits - Number of keyfiles: - Keyfiles size (in Bytes): - Keyfiles base name: - Translated by: - Plaintext size: - bits - Current Pool Content - Mixing PRF: - IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases security. When done, click 'Continue'. - Secondary key (hexadecimal) - Security token: - Sort Method: - Please wait. This process may take a long time... - Please wait...\nThis process may take a long time and VeraCrypt may seem unresponsive. - Block number: - Ciphertext (hexadecimal) - Data unit number (64-bit hexadecimal, data unit size is 512 bytes) - Key (hexadecimal) - Plaintext (hexadecimal) - Keyfile name: - XTS mode - S&ystem - &Volumes - Favor&ites - T&ools - Settin&gs - &Help - Home&page - - &About... - The read-only attribute on your old volume could not be changed. Please check the file access permissions. - Error: Access denied.\n\nThe partition you are trying to access is either 0 sectors long, or it is the boot device. - Administrator - In order to load the VeraCrypt driver, you need to be logged into an account with administrator privileges. - Please note that in order to encrypt, decrypt or format a partition/device you need to be logged into an account with administrator privileges.\n\nThis does not apply to file-hosted volumes. - In order to create a hidden volume you need to be logged into an account with administrator privileges.\n\nContinue? - Please note that in order to format the volume as NTFS/exFAT you need to be logged into an account with administrator privileges.\n\nWithout administrator privileges, you can format the volume as FAT. - FIPS-approved cipher (Rijndael, published in 1998) that may be used by U.S. government departments and agencies to protect classified information up to the Top Secret level. 256-bit key, 128-bit block, 14 rounds (AES-256). Mode of operation is XTS. - Volume is already mounted. - CAUTION: At least one encryption or hash algorithm failed the built-in automatic self-tests!\n\nVeraCrypt installation may be corrupted. - CAUTION: There is not enough data in the Random Number Generator pool to provide the requested amount of random data.\n\nYou should not proceed any further. Please select 'Report a Bug' from the Help menu, and report this error. - The drive is damaged (there is a physical defect on it) or a cable is damaged, or the memory is malfunctioning.\n\nPlease note that this is a problem with your hardware, not with VeraCrypt. Therefore, please do NOT report this as a bug/problem in VeraCrypt and please do NOT ask for help with this in the VeraCrypt Forums. Please contact your computer vendor's technical support team for assistance. Thank you.\n\nNote: If the error occurs repeatedly at the same place, it is very likely caused by a bad disk block, which should be possible to correct using third-party software (note that, in many cases, the 'chkdsk /r' command cannot correct it because it works only at the filesystem level; in some cases, the 'chkdsk' tool cannot even detect it). - If you are accessing a drive for removable media, please make sure that a medium is inserted in the drive. The drive/medium may also be damaged (there may be a physical defect on it) or a cable may be damaged/disconnected. - Your system appears to be using custom chipset drivers containing a bug that prevents encryption of the whole system drive.\n\nPlease try updating or uninstalling any custom (non-Microsoft) chipset drivers before proceeding. If it does not help, try encrypting the system partition only. - Invalid drive letter. - Invalid path. - Cancel - Cannot access device. Make sure the selected device exists and is not used by system. - Warning: Caps Lock is on. This may cause you to enter your password incorrectly. - Volume Type - It may happen that you are forced by somebody to reveal the password to an encrypted volume. There are many situations where you cannot refuse to reveal the password (for example, due to extortion). Using a so-called hidden volume allows you to solve such situations without revealing the password to your volume. - Select this option if you want to create a normal VeraCrypt volume. - Please note that if you wish an operating system to be installed in a hidden partition-hosted volume, then the entire system drive cannot be encrypted using a single key. - Outer Volume Encryption Options - Hidden Volume Encryption Options - Encryption Options - WARNING: Failed to clear the path of the last selected volume/keyfile (remembered by file selector)! - Error: The container has been compressed at the filesystem level. VeraCrypt does not support compressed containers (note that compression of encrypted data is ineffective and redundant).\n\nPlease disable compression for the container by following these steps:\n1) Right-click the container in Windows Explorer (not in VeraCrypt).\n2) Select 'Properties'.\n3) In the 'Properties' dialog box, click 'Advanced'.\n4) In the 'Advanced Attributes' dialog box, disable the option 'Compress contents to save disk space' and click 'OK'.\n5) In the 'Properties' dialog box, click 'OK'. - Failed to create volume %s - Size of %s is %.2f bytes - Size of %s is %.2f KB - Size of %s is %.2f MB - Size of %s is %.2f GB - Size of %s is %.2f TB - Size of %s is %.2f PB - WARNING: The device/partition is in use by the operating system or applications. Formatting the device/partition might cause data corruption and system instability.\n\nContinue? - Warning: The partition is in use by the operating system or applications. You should close any applications that might be using the partition (including antivirus software).\n\nContinue? - Error: The device/partition contains a file system that could not be dismounted. The file system may be in use by the operating system. Formatting the device/partition would very likely cause data corruption and system instability.\n\nTo solve this issue, we recommend that you first delete the partition and then recreate it without formatting. To do so, follow these steps:\n1) Right-click the 'Computer' (or 'My Computer') icon in the 'Start Menu' and select 'Manage'. The 'Computer Management' window should appear.\n2) In the 'Computer Management' window, select 'Storage' > 'Disk Management'.\n3) Right-click the partition you want to encrypt and select either 'Delete Partition', or 'Delete Volume', or 'Delete Logical Drive'.\n4) Click 'Yes'. If Windows asks you to restart the computer, do so. Then repeat the steps 1 and 2 and continue from the step 5.\n5) Right-click the unallocated/free space area and select either 'New Partition', or 'New Simple Volume', or 'New Logical Drive'.\n6) The 'New Partition Wizard' or 'New Simple Volume Wizard' window should appear now; follow its instructions. On the wizard page entitled 'Format Partition', select either 'Do not format this partition' or 'Do not format this volume'. In the same wizard, click 'Next' and then 'Finish'.\n7) Note that the device path you have selected in VeraCrypt may be wrong now. Therefore, exit the VeraCrypt Volume Creation Wizard (if it is still running) and then start it again.\n8) Try encrypting the device/partition again.\n\nIf VeraCrypt repeatedly fails to encrypt the device/partition, you may want to consider creating a file container instead. - Error: The filesystem could not be locked and/or dismounted. It may be in use by the operating system or applications (for example, antivirus software). Encrypting the partition might cause data corruption and system instability.\n\nPlease close any applications that might be using the filesystem (including antivirus software) and try again. If it does not help, please follow the below steps. - WARNING: Some of the mounted devices/partitions were already in use!\n\nIgnoring this can cause undesired results including system instability.\n\nWe strongly recommend that you close any application that might be using the devices/partitions. - The selected device contains partitions.\n\nFormatting the device might cause system instability and/or data corruption. Please either select a partition on the device, or remove all partitions on the device to enable VeraCrypt to format it safely. - The selected non-system device contains partitions.\n\nEncrypted device-hosted VeraCrypt volumes can be created within devices that do not contain any partitions (including hard disks and solid-state drives). A device that contains partitions can be entirely encrypted in place (using a single master key) only if it is the drive where Windows is installed and from which it boots.\n\nIf you want to encrypt the selected non-system device using a single master key, you will need to remove all partitions on the device first to enable VeraCrypt to format it safely (formatting a device that contains partitions might cause system instability and/or data corruption). Alternatively, you can encrypt each partition on the drive individually (each partition will be encrypted using a different master key).\n\nNote: If you want to remove all partitions from a GPT disk, you may need to convert it to a MBR disk (using e.g. the Computer Management tool) in order to remove hidden partitions. - Warning: If you encrypt the entire device (as opposed to encrypting only a partition on it), operating systems will consider the device as new, empty, and unformatted (as it will contain no partition table) and may spontaneously initialize the device (or ask you if you want to do so), which may damage the volume. Furthermore, it will not be possible to consistently mount the volume as favorite (e.g. when the drive number changes) or to assign a favorite-volume label to it.\n\nTo avoid that you may want to consider creating a partition on the device and encrypting the partition instead.\n\nAre you sure want to encrypt the entire device? - IMPORTANT: Please keep in mind that this volume can NOT be mounted/accessed using the drive letter %c:, which is currently assigned to it!\n\nTo mount this volume, click 'Auto-Mount Devices' in the main VeraCrypt window (alternatively, in the main VeraCrypt window, click 'Select Device', then select this partition/device, and click 'Mount'). The volume will be mounted to a different drive letter, which you select from the list in the main VeraCrypt window.\n\nThe original drive letter %c: should be used only in case you need to remove encryption from the partition/device (e.g., if you no longer need encryption). In such a case, right-click the drive letter %c: in the 'Computer' (or 'My Computer') list and select 'Format'. Otherwise, the drive letter %c: should never be used (unless you remove it, as described e.g. in the VeraCrypt FAQ, and assign it to another partition/device). - In-place encryption of non-system volumes is not supported on the version of the operating system you are currently using (it is supported only on Windows Vista and later versions of Windows).\n\nThe reason is that this version of Windows does not support shrinking of a filesystem (the filesystem needs to be shrunk to make space for the volume header and backup header). - The selected partition does not appear to contain an NTFS filesystem. Only partitions that contain an NTFS filesystem can be encrypted in place.\n\nNote: The reason is that Windows does not support shrinking of other types of filesystems (the filesystem needs to be shrunk to make space for the volume header and backup header). - The selected partition does not appear to contain an NTFS filesystem. Only partitions that contain an NTFS filesystem can be encrypted in place.\n\nIf you want to create an encrypted VeraCrypt volume within this partition, choose the option "Create encrypted volume and format it" (instead of the option "Encrypt partition in place"). - Error: The partition is too small. VeraCrypt cannot encrypt it in place. - To encrypt the data on this partition, please follow these steps:\n\n1) Create a VeraCrypt volume on an empty partition/device and then mount it.\n\n2) Copy all files from the partition that you originally wanted to encrypt to the mounted VeraCrypt volume (that has been created and mounted in step 1). That way, you will create a VeraCrypt-encrypted backup of the data.\n\n3) Create a VeraCrypt volume on the partition that you originally wanted to encrypt and make sure that (in the VeraCrypt wizard) you choose the option "Create encrypted volume and format it" (instead of the option "Encrypt partition in place"). Note that all data stored on the partition will be erased. After the volume is created, mount it.\n\n4) Copy all files from the mounted backup VeraCrypt volume (created and mounted in step 1) to the mounted VeraCrypt volume that has been created (and mounted) in step 3.\n\nAfter you complete these steps, the data will be encrypted and, in addition, there will be an encrypted backup of the data. - VeraCrypt can in-place encrypt only a partition, a dynamic volume, or an entire system drive.\n\nIf you want to create an encrypted VeraCrypt volume within the selected non-system device, choose the option "Create encrypted volume and format it" (instead of the option "Encrypt partition in place"). - Error: VeraCrypt can in-place encrypt only a partition, a dynamic volume, or an entire system drive. Please make sure the specified path is valid. - Error: Cannot shrink the filesystem (the filesystem needs to be shrunk to make space for the volume header and backup header).\n\nPossible causes and solutions:\n\n- Not enough free space on the volume. Please make sure no other application is writing to the filesystem.\n\n- Corrupted file system. Try to check it and fix any errors (right-click the corresponding drive letter in the 'Computer' list, then select Properties > Tools > 'Check Now', make sure the option 'Automatically fix file system errors' is enabled and click Start).\n\nIf the above steps do not help, please follow the below steps. - Error: There is not enough free space on the volume and so the filesystem cannot be shrunk (the filesystem needs to be shrunk to make space for the volume header and backup header).\n\nPlease delete any redundant files and empty the Recycle Bin so as to free at least 256 KB of space and then try again. Note that due to a Windows issue, the amount of free space reported by the Windows Explorer may be incorrect until the operating system is restarted. If restarting the system does not help, the file system may be corrupted. Try to check it and fix any errors (right-click the corresponding drive letter in the 'Computer' list, then select Properties > Tools > 'Check Now', make sure the option 'Automatically fix file system errors' is enabled and click Start).\n\nIf the above steps do not help, please follow the below steps. - Free space on drive %s is %.2f bytes. - Free space on drive %s is %.2f KB - Free space on drive %s is %.2f MB - Free space on drive %s is %.2f GB - Free space on drive %s is %.2f TB - Free space on drive %s is %.2f PB - Could not get available drive letters. - Error: VeraCrypt driver not found.\n\nPlease copy the files 'veracrypt.sys' and 'veracrypt-x64.sys' to the directory where the main VeraCrypt application (VeraCrypt.exe) is located. - Error: An incompatible version of the VeraCrypt driver is currently running.\n\nIf you are trying to run VeraCrypt in portable mode (i.e. without installing it) and a different version of VeraCrypt is already installed, you must uninstall it first (or upgrade it using the VeraCrypt installer). To uninstall it, follow these steps: On Windows Vista or later, select 'Start Menu' > Computer > 'Uninstall or change a program' > VeraCrypt > Uninstall; on Windows XP, select 'Start Menu' > Settings > 'Control Panel' > 'Add Or Remove Programs' > VeraCrypt > Remove.\n\nSimilarly, if you are trying to run VeraCrypt in portable mode (i.e. without installing it) and a different version of VeraCrypt is already running in portable mode, you must restart the system first and then run only this new version. - Error: Cipher initialization failure. - Error: A weak or a potentially weak key has been detected. The key will be discarded. Please try again. - A critical error has occurred and VeraCrypt must be terminated. If this is caused by a bug in VeraCrypt, we would like to fix it. To help us, you can send us an automatically generated error report containing the following items:\n\n- Program version\n- Operating system version\n- Type of CPU\n- VeraCrypt component name\n- Checksum of VeraCrypt executable\n- Symbolic name of dialog window\n- Error category\n- Error address\n- VeraCrypt call stack\n\nIf you select 'Yes', the following URL (which contains the entire error report) will be opened in your default Internet browser.\n\n%hs\n\nDo you want to send us the above error report? - A critical error has occurred in your system, which requires VeraCrypt to be terminated.\n\nNote that this error has not been caused by VeraCrypt (so the VeraCrypt developers cannot fix it). Please, check your system for possible problems (e.g., system configuration, network connection, failing hardware components). - A critical error has occurred in your system, which requires VeraCrypt to be terminated.\n\nIf this problem persists, you may want to try disabling or uninstalling applications that could potentially be causing this issue, such as antivirus or Internet security software, system "enhancers", "optimizers" or "tweakers", etc. If it does not help, you may want to try reinstalling your operating system (this problem may also be caused by malware). - VeraCrypt Critical Error - VeraCrypt detected that the operating system recently crashed. There are many potential reasons why the system could have crashed (for example, a failing hardware component, a bug in a device driver, etc.)\n\nDo you want VeraCrypt to check whether a bug in VeraCrypt could have caused the system crash? - Do you want VeraCrypt to continue detecting system crashes? - VeraCrypt found no system crash minidump file. - Do you want to delete the Windows crash dump file to free up disk space? - In order to analyze the system crash, VeraCrypt needs to install Microsoft Debugging Tools for Windows first.\n\nAfter you click OK, the Windows installer will download the Microsoft Debugging Tools installation package (16 MB) from a Microsoft server and install it (the Windows installer will be forwarded to the Microsoft server URL from the veracrypt.org server, which ensures that this feature works even if Microsoft changes the location of the installation package). - After you click OK, VeraCrypt will analyze the system crash. This may take up to several minutes. - Please make sure the environment variable 'PATH' includes the path to 'kd.exe' (Kernel Debugger). - It appears that VeraCrypt most likely did not cause the system crash. There are many potential reasons why the system could have crashed (for example, a failing hardware component, a bug in a device driver, etc.) - Results of the analysis indicate that updating the following driver might solve this issue: - To help us determine whether there is a bug in VeraCrypt, you can send us an automatically generated error report containing the following items:\n- Program version\n- Operating system version\n- Type of CPU\n- Error category\n- Driver name and version\n- System call stack\n\nIf you select 'Yes', the following URL (which contains the entire error report) will be opened in your default Internet browser. - Do you want to send us the above error report? - &Encrypt - &Decrypt - &Permanently Decrypt - Exit - Please create a logical drive for this extended partition, and then try again. - A VeraCrypt volume can reside in a file (called VeraCrypt container), which can reside on a hard disk, on a USB flash drive, etc. A VeraCrypt container is just like any normal file (it can be, for example, moved or deleted as any normal file). Click 'Select File' to choose a filename for the container and to select the location where you wish the container to be created.\n\nWARNING: If you select an existing file, VeraCrypt will NOT encrypt it; the file will be deleted and replaced with the newly created VeraCrypt container. You will be able to encrypt existing files (later on) by moving them to the VeraCrypt container that you are about to create now. - Select the location of the outer volume to be created (within this volume the hidden volume will be created later on).\n\nA VeraCrypt volume can reside in a file (called VeraCrypt container), which can reside on a hard disk, on a USB flash drive, etc. A VeraCrypt container can be moved or deleted as any normal file. Click 'Select File' to choose a filename for the container and to select the location where you wish the container to be created. If you select an existing file, VeraCrypt will NOT encrypt it; it will be deleted and replaced with the newly created container. You will be able to encrypt existing files (later on) by moving them to the VeraCrypt container you are about to create now. - Encrypted device-hosted VeraCrypt volumes can be created within partitions on hard disks, solid-state drives, USB memory sticks, and on any other supported storage devices. Partitions can also be encrypted in place.\n\nIn addition, encrypted device-hosted VeraCrypt volumes can be created within devices that do not contain any partitions (including hard disks and solid-state drives).\n\nNote: A device that contains partitions can be entirely encrypted in place (using a single key) only if it is the drive where Windows is installed and from which it boots. - A device-hosted VeraCrypt volume can be created within a hard disk partition, solid-state drive, USB memory stick, and other storage devices.\n\nWARNING: Note that the partition/device will be formatted and all data currently stored on it will be lost. - \nSelect the location of the outer volume to be created (within this volume the hidden volume will be created later on).\n\nOuter volumes can be created within partitions on hard disks, solid-state drives, USB memory sticks, and on any other supported storage devices. Outer volumes can also be created within devices that do not contain any partitions (including hard disks and solid-state drives).\n\nWARNING: Note that the partition/device will be formatted and all data currently stored on it will be lost. - \nSelect the location of the VeraCrypt volume within which you wish to create a hidden volume. - WARNING: The host file/device is already in use!\n\nIgnoring this can cause undesired results including system instability. All applications that might be using the host file/device (for example, antivirus or backup applications) should be closed before mounting the volume.\n\nContinue mounting? - Error: Cannot mount volume. The host file/device is already in use. Attempt to mount without exclusive access failed as well. - The file could not be opened. - Volume Location - Large Files - Do you intend to store files larger than 4 GB in this VeraCrypt volume? - Depending on your choice above, VeraCrypt will choose a suitable default file system for the VeraCrypt volume (you will be able to select a file system in the next step). - As you are creating an outer volume, you should consider choosing 'No'. If you choose 'Yes', the default filesystem will be NTFS, which is not as suitable for outer volumes as FAT/exFAT (for example, the maximum possible size of the hidden volume will be significantly greater if the outer volume is formatted as FAT/exFAT). Normally, FAT is the default for both hidden and normal volumes (so FAT volumes are not suspicious). However, if the user indicates intent to store files larger than 4 GB (which the FAT file system does not allow), then FAT is not the default. - Are you sure you want to choose 'Yes'? - Volume Creation Mode - This is the fastest way to create a partition-hosted or device-hosted VeraCrypt volume (in-place encryption, which is the other option, is slower because content of each sector has to be first read, encrypted, and then written). Any data currently stored on the selected partition/device will be lost (the data will NOT be encrypted; it will be overwritten with random data). If you want to encrypt existing data on a partition, choose the other option. - The entire selected partition and all data stored on it will be encrypted in place. If the partition is empty, you should choose the other option (the volume will be created much faster). - Note: - &Resume - &Defer - &Start - &Continue - &Format - &Wipe - Abort format? - Show more information - Do not show this again - The content of the partition/device has been successfully erased. - The content of the partition where the original system (of which the hidden system is a clone) resided has been successfully erased. - Please make sure the version of Windows you are going to install (on the wiped partition) is the same as the version of Windows you are currently running. This is required due to the fact that both systems will share a common boot partition. - The system partition/drive has been successfully encrypted.\n\nNote: If there are non-system VeraCrypt volumes that you need to have mounted automatically every time Windows starts, you can set it up by mounting each of them and selecting 'Favorites' > 'Add Mounted Volume to System Favorites'). - The system partition/drive has been successfully decrypted. - \n\nThe VeraCrypt volume has been created and is ready for use. If you wish to create another VeraCrypt volume, click Next. Otherwise, click Exit. - \n\nThe hidden VeraCrypt volume has been successfully created (the hidden operating system will reside within this hidden volume).\n\nClick Next to continue. - Volume Fully Encrypted - Volume Fully Decrypted - IMPORTANT: TO MOUNT THIS NEWLY CREATED VERACRYPT VOLUME AND TO ACCESS DATA STORED IN IT, CLICK 'Auto-Mount Devices' IN THE MAIN VERACRYPT WINDOW. After you enter the correct password (and/or supply correct keyfiles), the volume will be mounted to the drive letter you select from the list in the main VeraCrypt window (and you will be able to access the encrypted data via the selected drive letter).\n\nPLEASE REMEMBER OR WRITE DOWN THE ABOVE STEPS. YOU MUST FOLLOW THEM WHENEVER YOU WANT TO MOUNT THE VOLUME AND ACCESS DATA STORED IN IT. Alternatively, in the main VeraCrypt window, click 'Select Device', then select this partition/volume, and click 'Mount'.\n\nThe partition/volume has been successfully encrypted (it contains a fully encrypted VeraCrypt volume now) and is ready for use. - The VeraCrypt volume has been successfully decrypted. - The VeraCrypt volume has been successfully decrypted.\n\nPlease select a drive letter that you wish to assign to the decrypted volume and then click Finish.\n\nIMPORTANT: Until a drive letter is assigned to the decrypted volume, you will not be able to access data stored on the volume. - Warning: To be able to access the decrypted data, a drive letter needs to be assigned to the decrypted volume. However, no drive letter is currently available.\n\nPlease vacate a drive letter (for example, by disconnecting a USB flash drive or external hard drive, etc.) and then click OK. - The VeraCrypt volume has been successfully created. - Volume Created - IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the encryption keys. Then click Format to create the volume. - Click Format to create the outer volume. For more information, please refer to the documentation. - Outer Volume Format - Hidden Volume Format - Volume Format - Adobe Reader (or a compatible tool) is necessary to view or print the VeraCrypt User's Guide. Adobe Reader (freeware) can be downloaded at: www.adobe.com\n\nDo you want to view the online documentation instead? - If you select this option, the wizard will first help you create a normal VeraCrypt volume and then a hidden VeraCrypt volume within it. Inexperienced users should always select this option. - If you select this option, you will create a hidden volume within an existing VeraCrypt volume. It will be assumed that you have already created a VeraCrypt volume that is suitable to host the hidden volume. - Volume Creation Mode - Hidden Volume Created - The hidden VeraCrypt volume has been successfully created and is ready for use. If all the instructions have been followed and if the precautions and requirements listed in the section "Security Requirements and Precautions Pertaining to Hidden Volumes" in the VeraCrypt User's Guide are followed, it should be impossible to prove that the hidden volume exists, even when the outer volume is mounted.\n\nWARNING: IF YOU DO NOT PROTECT THE HIDDEN VOLUME (FOR INFORMATION ON HOW TO DO SO, REFER TO THE SECTION "PROTECTION OF HIDDEN VOLUMES AGAINST DAMAGE" IN THE VERACRYPT USER'S GUIDE), DO NOT WRITE TO THE OUTER VOLUME. OTHERWISE, YOU MAY OVERWRITE AND DAMAGE THE HIDDEN VOLUME! - You have started the hidden operating system. As you may have noticed, the hidden operating system appears to be installed on the same partition as the original operating system. However, in reality, it is installed within the partition behind it (in the hidden volume). All read and write operations are being transparently redirected from the original system partition to the hidden volume.\n\nNeither the operating system nor applications will know that data written to and read from the system partition are actually written to and read from the partition behind it (from/to a hidden volume). Any such data is encrypted and decrypted on the fly as usual (with an encryption key different from the one that will be used for the decoy operating system).\n\n\nPlease click Next to continue. - The outer volume has been created and mounted as drive %hc:. To this outer volume you should now copy some sensitive-looking files that you actually do NOT want to hide. They will be there for anyone forcing you to disclose the password for the first partition behind the system partition, where both the outer volume and the hidden volume (containing the hidden operating system) will reside. You will be able to reveal the password for this outer volume, and the existence of the hidden volume (and of the hidden operating system) will remain secret.\n\nIMPORTANT: The files you copy to the outer volume should not occupy more than %s. Otherwise, there may not be enough free space on the outer volume for the hidden volume (and you will not be able to continue). After you finish copying, click Next (do not dismount the volume). - Outer volume has been successfully created and mounted as drive %hc:. To this volume you should now copy some sensitive-looking files that you actually do NOT want to hide. The files will be there for anyone forcing you to disclose your password. You will reveal only the password for this outer volume, not for the hidden one. The files that you really care about will be stored in the hidden volume, which will be created later on. When you finish copying, click Next. Do not dismount the volume.\n\nNote: After you click Next, cluster bitmap of the outer volume will be scanned to determine the size of uninterrupted area of free space whose end is aligned with the end of the volume. This area will accommodate the hidden volume, so it will limit its maximum possible size. Cluster bitmap scanning ensures that no data on the outer volume are overwritten by the hidden volume. - Outer Volume Contents - \n\nIn the next steps, you will set the options for the outer volume (within which the hidden volume will be created later on). - \n\nIn the next steps, you will create a so-called outer VeraCrypt volume within the first partition behind the system partition (as was explained in one of the previous steps). - Outer Volume - In the following steps, you will set the options and password for the hidden volume, which will contain the hidden operating system.\n\nRemark: The cluster bitmap of the outer volume has been scanned in order to determine the size of uninterrupted area of free space whose end is aligned with the end of the outer volume. This area will accommodate the hidden volume, so it limits its maximum possible size. The maximum possible size of the hidden volume has been determined and confirmed to be greater than the size of the system partition (which is required, because the entire content of the system partition will need to be copied to the hidden volume). This ensures that no data currently stored on the outer volume will be overwritten by data written to the area of the hidden volume. - IMPORTANT: Please remember the algorithms that you select in this step. You will have to select the same algorithms for the decoy system. Otherwise, the hidden system will be inaccessible! (The decoy system must be encrypted with the same encryption algorithm as the hidden system.)\n\nNote: The reason is that the decoy system and the hidden system will share a single boot loader, which supports only a single algorithm, selected by the user (for each algorithm, there is a special version of the VeraCrypt Boot Loader). - \n\nThe volume cluster bitmap has been scanned and the maximum possible size of the hidden volume has been determined. In the next steps you will set the options, the size, and the password for the hidden volume. - Hidden Volume - The hidden volume is now protected against damage until the outer volume is dismounted.\n\nWARNING: If any data is attempted to be saved to the hidden volume area, VeraCrypt will start write-protecting the entire volume (both the outer and the hidden part) until it is dismounted. This may cause filesystem corruption on the outer volume, which (if repeated) might adversely affect plausible deniability of the hidden volume. Therefore, you should make every effort to avoid writing to the hidden volume area. Any data being saved to the hidden volume area will not be saved and will be lost. Windows may report this as a write error ("Delayed Write Failed" or "The parameter is incorrect"). - Each of the hidden volumes within the newly mounted volumes is now protected against damage until dismounted.\n\nWARNING: If any data is attempted to be saved to protected hidden volume area of any of these volumes, VeraCrypt will start write-protecting the entire volume (both the outer and the hidden part) until it is dismounted. This may cause filesystem corruption on the outer volume, which (if repeated) might adversely affect plausible deniability of the hidden volume. Therefore, you should make every effort to avoid writing to the hidden volume area. Any data being saved to protected hidden volume areas will not be saved and will be lost. Windows may report this as a write error ("Delayed Write Failed" or "The parameter is incorrect"). - WARNING: Data were attempted to be saved to the hidden volume area of the volume mounted as %c:! VeraCrypt prevented these data from being saved in order to protect the hidden volume. This may have caused filesystem corruption on the outer volume and Windows may have reported a write error ("Delayed Write Failed" or "The parameter is incorrect"). The entire volume (both the outer and the hidden part) will be write-protected until it is dismounted. If this is not the first time VeraCrypt has prevented data from being saved to the hidden volume area of this volume, plausible deniability of this hidden volume might be adversely affected (due to possible unusual correlated inconsistencies within the outer volume file system). Therefore, you should consider creating a new VeraCrypt volume (with Quick Format disabled) and moving files from this volume to the new volume; this volume should be securely erased (both the outer and the hidden part). We strongly recommend that you restart the operating system now. - You have indicated intent to store files larger than 4 GB on the volume. This requires the volume to be formatted as NTFS/exFAT, which, however, will not be possible. - Please note that when a hidden operating system is running, non-hidden VeraCrypt volumes cannot be formatted as NTFS/exFAT. The reason is that the volume would need to be temporarily mounted without write protection in order to allow the operating system to format it as NTFS (whereas formatting as FAT is performed by VeraCrypt, not by the operating system, and without mounting the volume). For further technical details, see below. You can create a non-hidden NTFS/exFAT volume from within the decoy operating system. - For security reasons, when a hidden operating system is running, hidden volumes can be created only in the 'direct' mode (because outer volumes must always be mounted as read-only). To create a hidden volume securely, follow these steps:\n\n1) Boot the decoy system.\n\n2) Create a normal VeraCrypt volume and, to this volume, copy some sensitive-looking files that you actually do NOT want to hide (the volume will become the outer volume).\n\n3) Boot the hidden system and start the VeraCrypt Volume Creation Wizard. If the volume is file-hosted, move it to the system partition or to another hidden volume (otherwise, the newly created hidden volume would be mounted as read-only and could not be formatted). Follow the instructions in the wizard so as to select the 'direct' hidden volume creation mode.\n\n4) In the wizard, select the volume you created in step 2 and then follow the instructions to create a hidden volume within it. - For security reasons, when a hidden operating system is running, local unencrypted filesystems and non-hidden VeraCrypt volumes are mounted as read-only (no data can be written to such filesystems or VeraCrypt volumes).\n\nData is allowed to be written to any filesystem that resides within a hidden VeraCrypt volume (provided that the hidden volume is not located in a container stored on an unencrypted filesystem or on any other read-only filesystem). - There are three main reasons why such countermeasures have been implemented:\n\n- It enables the creation of a secure platform for mounting of hidden VeraCrypt volumes. Note that we officially recommend that hidden volumes are mounted only when a hidden operating system is running. (For more information, see the subsection 'Security Requirements and Precautions Pertaining to Hidden Volumes' in the documentation.)\n\n- In some cases, it is possible to determine that, at a certain time, a particular filesystem was not mounted under (or that a particular file on the filesystem was not saved or accessed from within) a particular instance of an operating system (e.g. by analyzing and comparing filesystem journals, file timestamps, application logs, error logs, etc). This might indicate that a hidden operating system is installed on the computer. The countermeasures prevent these issues.\n\n- It prevents data corruption and allows safe hibernation. When Windows resumes from hibernation, it assumes that all mounted filesystems are in the same state as when the system entered hibernation. VeraCrypt ensures this by write-protecting any filesystem accessible both from within the decoy and hidden systems. Without such protection, the filesystem could become corrupted when mounted by one system while the other system is hibernated. - Note: If you need to securely transfer files from the decoy system to the hidden system, follow these steps:\n1) Start the decoy system.\n2) Save the files to an unencrypted volume or to an outer/normal VeraCrypt volume.\n3) Start the hidden system.\n4) If you saved the files to a VeraCrypt volume, mount it (it will be automatically mounted as read-only).\n5) Copy the files to the hidden system partition or to another hidden volume. - Your computer must be restarted.\n\nDo you want to restart it now? - An error occurred when obtaining the system encryption status. - No password specified in the command line. The volume can't be created. - No volume size specified in the command line. The volume can't be created. - The volume file size specified in the command line is incompatible with selected NTFS filesystem. - The volume file size specified in the command line is incompatible with selected FAT32 filesystem. - The filesystem on the target drive doesn't support creating sparse files which is required for dynamic volumes. - Only container files can be created through the command line. - The container file size specified in the command line is greater than the available disk free space. Volume can't be created. - The volume size specified in the command line is too small. The volume can't be created. - The volume size specified in the command line is too big. The volume can't be created. - Cannot initialize application components for system encryption. - Failed to initialize the random number generator!\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n%hs, Last Error = 0x%.8X) - Windows Crypto API failed!\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n%hs, Last Error = 0x%.8X) - Unable to initialize the application. Failed to register the Dialog class. - Error: Failed to load the Rich Edit system library. - VeraCrypt Volume Creation Wizard - Maximum possible hidden volume size for this volume is %.2f bytes. - Maximum possible hidden volume size for this volume is %.2f KB. - Maximum possible hidden volume size for this volume is %.2f MB. - Maximum possible hidden volume size for this volume is %.2f GB. - Maximum possible hidden volume size for this volume is %.2f TB. - Volume password/keyfiles cannot be changed while the volume is mounted. Please dismount the volume first. - The header key derivation algorithm cannot be changed while the volume is mounted. Please dismount the volume first. - &Mount - A newer version of VeraCrypt is required to mount this volume. - Error: Volume Creation Wizard not found.\n\nPlease make sure that the file 'VeraCrypt Format.exe' is in the folder from which 'VeraCrypt.exe' was launched. If it is not, please reinstall VeraCrypt, or locate 'VeraCrypt Format.exe' on your disk and run it. - Error: Volume Expander not found.\n\nPlease make sure that the file 'VeraCryptExpander.exe' is in the folder from which 'VeraCrypt.exe' was launched. If it is not, please reinstall VeraCrypt, or locate 'VeraCryptExpander.exe' on your disk and run it. - &Next > - &Finish - &Install - E&xtract - Unable to connect to the VeraCrypt device driver. VeraCrypt cannot work if the device driver is not running.\n\nPlease note that, due to a Windows issue, it may be necessary to log off or restart the system before the device driver can be loaded. - Error occurred when loading/preparing fonts. - The drive letter was not found or no drive letter was specified. - Error: Cannot assign drive letter.\n\nUntil a drive letter is assigned to the decrypted volume, you will not be able to access data stored on the volume.\n\nRetry? - Drive letter not available. - No file selected! - No drive letters available. - No free drive letter for the outer volume! Volume creation cannot continue. - Could not determine your operating system version or you are using an unsupported operating system. - No path selected! - Not enough free space for the hidden volume! Volume creation cannot continue. - Error: The files you copied to the outer volume occupy too much space. Therefore, there is not enough free space on the outer volume for the hidden volume.\n\nNote that the hidden volume must be as large as the system partition (the partition where the currently running operating system is installed). The reason is that the hidden operating system needs to be created by copying the content of the system partition to the hidden volume.\n\n\nThe process of creation of the hidden operating system cannot continue. - The driver is unable to dismount the volume. Some files located on the volume are probably still open. - Unable to lock the volume. There are still open files on the volume. Therefore, it cannot be dismounted. - VeraCrypt cannot lock the volume because it is in use by the system or applications (there may be open files on the volume).\n\nDo you want to force dismount on the volume? - Select a VeraCrypt Volume - Specify Path and File Name - Select PKCS #11 Library - Out of Memory - IMPORTANT: We strongly recommend that inexperienced users create a VeraCrypt file container on the selected device/partition, instead of attempting to encrypt the entire device/partition.\n\nWhen you create a VeraCrypt file container (as opposed to encrypting a device or partition) there is, for example, no risk of destroying a large number of files. Note that a VeraCrypt file container (even though it contains a virtual encrypted disk) is actually just like any normal file. For more information, see the chapter Beginner's Tutorial in the VeraCrypt User Guide.\n\nAre you sure you want to encrypt the entire device/partition? - WARNING: The file '%s' already exists!\n\nIMPORTANT: VERACRYPT WILL NOT ENCRYPT THE FILE, BUT IT WILL DELETE IT. Are you sure you want to delete the file and replace it with a new VeraCrypt container? - CAUTION: ALL FILES CURRENTLY STORED ON THE SELECTED %s '%s'%s WILL BE ERASED AND LOST (THEY WILL NOT BE ENCRYPTED)!\n\nAre you sure you want to proceed with format? - WARNING: You will not be able to mount the volume or access any files stored on it until it has been fully encrypted.\n\nAre you sure you want to start encrypting the selected %s '%s'%s? - WARNING: You will not be able to mount the volume or access any files stored on it until it has been fully decrypted.\n\nAre you sure you want to start decrypting the selected %s '%s'%s? - WARNING: Please note that if power supply is suddenly interrupted while encrypting/decrypting existing data in place, or when the operating system crashes due to a software error or hardware malfunction while VeraCrypt is encrypting/decrypting existing data in place, portions of the data will be corrupted or lost. Therefore, before you start encrypting/decrypting, please make sure that you have backup copies of the files you want to encrypt/decrypt.\n\nDo you have such a backup? - CAUTION: ANY FILES CURRENTLY STORED ON THE PARTITION '%s'%s (I.E. ON THE FIRST PARTITION BEHIND THE SYSTEM PARTITION) WILL BE ERASED AND LOST (THEY WILL NOT BE ENCRYPTED)!\n\nAre you sure you want to proceed with format? - WARNING: THE SELECTED PARTITION CONTAINS A LARGE AMOUNT OF DATA! Any files stored on the partition will be erased and lost (they will NOT be encrypted)! - Erase any files stored on the partition by creating a VeraCrypt volume within it - Password - PIM - Set Header Key Derivation Algorithm - Add/Remove Keyfiles to/from Volume - Remove All Keyfiles from Volume - Password, PIM and/or keyfile(s) successfully changed.\n\nIMPORTANT: Please make sure you have read the section 'Changing Passwords and Keyfiles' in the chapter 'Security Requirements and Precautions' in the VeraCrypt User Guide. - This volume is registered as a System Favorite and its PIM was changed.\nDo you want VeraCrypt to automatically update the System Favorite configuration (administrator privileges required)?\n\nPlease note that if you answer no, you'll have to update the System Favorite manually. - IMPORTANT: If you did not destroy your VeraCrypt Rescue Disk, your system partition/drive can still be decrypted using the old password (by booting the VeraCrypt Rescue Disk and entering the old password). You should create a new VeraCrypt Rescue Disk and then destroy the old one.\n\nDo you want to create a new VeraCrypt Rescue Disk? - Note that your VeraCrypt Rescue Disk still uses the previous algorithm. If you consider the previous algorithm insecure, you should create a new VeraCrypt Rescue Disk and then destroy the old one.\n\nDo you want to create a new VeraCrypt Rescue Disk? - Any kind of file (for example, .mp3, .jpg, .zip, .avi) may be used as a VeraCrypt keyfile. Note that VeraCrypt never modifies the keyfile contents. You can select more than one keyfile (the order does not matter). If you add a folder, all non-hidden files found in it will be used as keyfiles. Click 'Add Token Files' to select keyfiles stored on security tokens or smart cards (or to import keyfiles to security tokens or smart cards). - Keyfile(s) successfully added/removed. - Keyfile exported. - Header key derivation algorithm successfully set. - Please enter the password and/or keyfile(s) for the non-system volume where you want to resume the process of in-place encryption/decryption.\n\nRemark: After you click Next, VeraCrypt will attempt to find all non-system volumes where the process of encryption/decryption has been interrupted and where the VeraCrypt volume header can be deciphered using the supplied password and/or keyfile(s). If more than one such volume is found, you will need to select one of them in the next step. - Please select one of the listed volumes. The list contains each accessible non-system volume where the process of encryption/decryption has been interrupted and where the volume header was successfully deciphered using the supplied password and/or keyfile(s). - Please enter the password and/or keyfile(s) for the non-system VeraCrypt volume that you want to decrypt. - It is very important that you choose a good password. You should avoid choosing one that contains only a single word that can be found in a dictionary (or a combination of 2, 3, or 4 such words). It should not contain any names or dates of birth. It should not be easy to guess. A good password is a random combination of upper and lower case letters, numbers, and special characters, such as @ ^ = $ * + etc. We recommend choosing a password consisting of 20 or more characters (the longer, the better). The maximum possible length is 64 characters. - Please choose a password for the hidden volume. - Please choose a password for the hidden operating system (i.e. for the hidden volume). - IMPORTANT: The password that you choose for the hidden operating system in this step must be substantially different from the other two passwords (i.e. from the password for the outer volume and from the password for the decoy operating system). - Please enter the password for the volume within which you wish to create a hidden volume.\n\nAfter you click Next, VeraCrypt will attempt to mount the volume. As soon as the volume is mounted, its cluster bitmap will be scanned to determine the size of the uninterrupted area of free space (if there is any) whose end is aligned with the end of the volume. This area will accommodate the hidden volume and therefore will limit its maximum possible size. Cluster map scanning is necessary to ensure that no data on the outer volume will be overwritten by the hidden volume. - \nPlease choose a password for the outer volume. This will be the password that you will be able to reveal to an adversary if you are asked or forced to do so.\n\nIMPORTANT: The password must be substantially different from the one you will choose for the hidden volume.\n\nNote: The maximum possible password length is 64 characters. - Please choose a password for the outer volume. This will be the password you will be able to reveal to anyone forcing you to disclose the password for the first partition behind the system partition, where both the outer volume and the hidden volume (containing the hidden operating system) will reside. The existence of the hidden volume (and of the hidden operating system) will remain secret. Note that this password is not for the decoy operating system.\n\nIMPORTANT: The password must be substantially different from the one you will choose for the hidden volume (i.e. for the hidden operating system). - Outer Volume Password - Hidden Volume Password - Password for Hidden Operating System - WARNING: Short passwords are easy to crack using brute force techniques!\n\nWe recommend choosing a password consisting of 20 or more characters. Are you sure you want to use a short password? - Volume Password - Operation failed due to one or more of the following:\n - Incorrect password.\n - Incorrect Volume PIM number.\n - Incorrect PRF (hash).\n - Not a valid volume. - Operation failed due to one or more of the following:\n - Incorrect keyfile(s).\n - Incorrect password.\n - Incorrect Volume PIM number.\n - Incorrect PRF (hash).\n - Not a valid volume. - Operation failed due to one or more of the following:\n - Wrong mount mode.\n - Incorrect password.\n - Incorrect Volume PIM number.\n - Incorrect PRF (hash).\n - Not a valid volume. - Operation failed due to one or more of the following:\n - Wrong mount mode.\n - Incorrect keyfile(s).\n - Incorrect password.\n - Incorrect Volume PIM number.\n - Incorrect PRF (hash).\n - Not a valid volume. - Auto-mount failed due to one or more of the following:\n - Incorrect password.\n - Incorrect Volume PIM number.\n - Incorrect PRF (hash).\n - No valid volume found. - Auto-mount failed due to one or more of the following:\n - Incorrect keyfile(s).\n - Incorrect password.\n - Incorrect Volume PIM number.\n - Incorrect PRF (hash).\n - No valid volume found. - \n\nWarning: Caps Lock is on. This may cause you to enter your password incorrectly. - Remember Number to Mount Volume - Outer Volume PIM - Hidden Volume PIM - PIM for Hidden Operating System - PIM (Personal Iterations Multiplier) is a value that controls the number of iterations used by the header key derivation as follows:\n Iterations = 15000 + (PIM x 1000).\n\nWhen left empty or set to 0, VeraCrypt will use a default value (485) that ensures a high security.\n\nWhen the password is less than 20 characters, PIM can't be smaller than 485 in order to maintain a minimal security level.\nWhen the password is 20 characters or more, PIM can be set to any value.\n\nA PIM value larger than 485 will lead to slower mount. A small PIM value (less than 485) will lead to a quicker mount but it can reduce security if the password is not strong enough. - PIM (Personal Iterations Multiplier) is a value that controls the number of iterations used by the header key derivation as follows:\n Iterations = PIM x 2048.\n\nWhen left empty or set to 0, VeraCrypt will use a default value that ensures a high security.\n\nWhen the password is less than 20 characters, PIM can't be smaller than 98 in order to maintain a minimal security level.\nWhen the password is 20 characters or more, PIM can be set to any value.\n\nA PIM value larger than 98 will lead to slower boot. A small PIM value (less than 98) will lead to a quicker boot but it can reduce security if the password is not strong enough. - Remember Number to Boot System - You have chosen a PIM value that is larger than VeraCrypt default value.\nPlease note that this will lead to much slower mount/boot. - You have chosen a Personal Iterations Multiplier (PIM) that is smaller than the default VeraCrypt value. Please note that if your password is not strong enough, this could lead to a weaker security.\n\nDo you confirm that you are using a strong password? - Personal Iterations Multiplier (PIM) maximum value for system encryption is 65535. - Volume PIM - \n\nWARNING: Hidden file(s) have been found in a keyfile search path. Such hidden files cannot be used as keyfiles. If you need to use them as keyfiles, remove their 'Hidden' attribute (right-click each of them, select 'Properties', uncheck 'Hidden' and click OK). Note: Hidden files are visible only if the corresponding option is enabled (Computer > Organize > 'Folder and search options' > View). - If you are attempting to protect a hidden volume containing a hidden system, please make sure you are using the standard US keyboard layout when typing the password for the hidden volume. This is required due to the fact that the password needs to be typed in the pre-boot environment (before Windows starts) where non-US Windows keyboard layouts are not available. - VeraCrypt has not found any volume where the process of encryption/decryption of a non-system volume has been interrupted and where the volume header can be deciphered using the supplied password and/or keyfile(s).\n\nPlease make sure the password and/or keyfile(s) are correct and that the partition/volume is not being used by the system or applications (including antivirus software). - The selected partition/device is already fully encrypted.\nHeader Flags = 0x%.8X - The selected partition/device is not using in-place encryption.\nHeader Flags = 0x%.8X - \n\nNote: If you are attempting to mount a partition located on an encrypted system drive without pre-boot authentication or to mount the encrypted system partition of an operating system that is not running, you can do so by selecting 'System' > 'Mount Without Pre-Boot Authentication'. - In this mode, you cannot mount a partition located on a drive whose portion is within the key scope of active system encryption.\n\nBefore you can mount this partition in this mode, you need to either boot an operating system installed on a different drive (encrypted or unencrypted) or boot an unencrypted operating system. - VeraCrypt cannot decrypt an individual partition on an entirely encrypted system drive (you can decrypt only the entire system drive). - Warning: As the drive contains the VeraCrypt Boot Loader, it may be an entirely encrypted system drive. If it is, please note that VeraCrypt cannot decrypt an individual partition on an entirely encrypted system drive (you can decrypt only the entire system drive). If that is the case, you will be able to continue now but you will receive the 'Incorrect password' error message later. - < &Back - Unable to list raw devices installed on your system! - The volume '%s' exists, and is read-only. Are you sure you want to replace it? - Select destination directory - Select Keyfile - Select a keyfile search path. WARNING: Note that only the path will be remembered, not the filenames! - Select a directory where to store the keyfiles. - The current container file was selected as a keyfile. It will be skipped. - Designed by Ross Anderson, Eli Biham, and Lars Knudsen. Published in 1998. 256-bit key, 128-bit block. Mode of operation is XTS. Serpent was one of the AES finalists. - Please specify the size of the container you want to create.\n\nIf you create a dynamic (sparse-file) container, this parameter will specify its maximum possible size.\n\nNote that the minimum possible size of a FAT volume is 292 KB. The minimum possible size of an exFAT volume is 424 KB. The minimum possible size of an NTFS volume is 3792 KB. - Please specify the size of the outer volume to be created (you will first create the outer volume and then a hidden volume within it). The minimum possible size of a volume within which a hidden volume is intended to be created is 340 KB. - Please specify the size of the hidden volume to create. The minimum possible size of a hidden volume is 40 KB (or 3664 KB if it is formatted as NTFS). The maximum possible size you can specify for the hidden volume is displayed above. - Outer Volume Size - Hidden Volume Size - Please verify that the size of the selected device/partition shown above is correct and click Next. - The outer volume and the hidden volume (containing the hidden operating system) will reside within the above partition. It should be the first partition behind the system partition.\n\nPlease verify that the size of the partition and its number shown above are correct, and if they are, click Next. - \n\nNote that the minimum possible size of a volume within which a hidden volume is intended to be created is 340 KB. - Volume Size - Dynamic - CAUTION: SELF-TEST FAILED! - Self-tests of all algorithms passed - The data unit number that you supplied is too long or short. - The secondary key that you supplied is too long or short. - The test ciphertext you have supplied is too long or short. - The test key you have supplied is too long or short. - The test plaintext you have supplied is too long or short. - Two ciphers in a cascade operating in XTS mode. Each block is first encrypted with %s (%d-bit key) and then with %s (%d-bit key). Each cipher uses its own key. All keys are mutually independent. - Three ciphers in a cascade operating in XTS mode. Each block is first encrypted with %s (%d-bit key), then with %s (%d-bit key), and finally with %s (%d-bit key). Each cipher uses its own key. All keys are mutually independent. - Note that, depending on the operating system configuration, these auto-run and auto-mount features may work only when the traveler disk files are created on a non-writable CD/DVD-like medium. Also note that this is not a bug in VeraCrypt (it is a limitation of Windows). - VeraCrypt traveler disk has been successfully created.\n\nNote that you need administrator privileges to run VeraCrypt in portable mode. Also note that, after examining the registry file, it may be possible to tell that VeraCrypt was run on a Windows system even if it is run in portable mode. - VeraCrypt Traveler Disk - Designed by Bruce Schneier, John Kelsey, Doug Whiting, David Wagner, Chris Hall, and Niels Ferguson. Published in 1998. 256-bit key, 128-bit block. Mode of operation is XTS. Twofish was one of the AES finalists. - More information on %s - Unknown - An unspecified or unknown error occurred (%d). - Some volumes contain files or folders being used by applications or system.\n\nForce dismount? - &Dismount - Dismount failed! - Volume contains files or folders being used by applications or system.\n\nForce dismount? - No volume is mounted to the specified drive letter. - The volume you are trying to mount is already mounted. - An error occurred when attempting to mount volume. - Error seeking location within volume. - Error: Incorrect volume size. - WARNING: You should use Quick Format only in the following cases:\n\n1) The device contains no sensitive data and you do not need plausible deniability.\n2) The device has already been securely and fully encrypted.\n\nAre you sure you want to use Quick Format? - Dynamic container is a pre-allocated NTFS sparse file whose physical size (actual disk space used) grows as new data is added to it.\n\nWARNING: Performance of sparse-file-hosted volumes is significantly worse than performance of regular volumes. Sparse-file-hosted volumes are also less secure, because it is possible to tell which volume sectors are unused. Furthermore, sparse-file-hosted volumes cannot provide plausible deniability (host a hidden volume). Also note that if data is written to a sparse file container when there is not enough free space in the host file system, the encrypted file system may get corrupted.\n\nAre you sure you want to create a sparse-file-hosted volume? - Note that the size of the dynamic container reported by Windows and by VeraCrypt will always be equal to its maximum size. To find out current physical size of the container (actual disk space it uses), right-click the container file (in a Windows Explorer window, not in VeraCrypt), then select 'Properties' and see the 'Size on disk' value.\n\nAlso note that if you move a dynamic container to another volume or drive, the physical size of the container will be extended to the maximum. (You can prevent that by creating a new dynamic container in the destination location, mounting it and then moving the files from the old container to the new one.) - Password cache wiped - Passwords (and/or processed keyfile contents) stored in the VeraCrypt driver cache have been wiped. - VeraCrypt cannot change the password for a foreign volume. - Please select a free drive letter from the list. - Please select a mounted volume in the drive letter list. - Warning: Two different volumes/devices are currently selected (the first is selected in the drive letter list and the second is selected in the input field below the drive letter list).\n\nPlease confirm your choice: - Error: Cannot create autorun.inf - Error while processing keyfile! - Error processing keyfile path! - The keyfile path contains no files.\n\nPlease note that folders (and files they contain) found in keyfile search paths are ignored. - VeraCrypt does not support this operating system. - Error: VeraCrypt supports only stable versions of this operating system (beta/RC versions are not supported). - Error: Cannot allocate memory. - Error: Could not retrieve value of performance counter. - Error: Bad volume format. - Error: You supplied a password for a hidden volume (not for a normal volume). - For security reasons, a hidden volume cannot be created within a VeraCrypt volume containing a filesystem that has been encrypted in place (because the free space on the volume has not been filled with random data). - VeraCrypt - Legal Notices - All Files - VeraCrypt Volumes - Library Modules - NTFS/exFAT formatting cannot continue. - Cannot mount volume. - Cannot dismount volume. - Windows failed to format the volume as NTFS/exFAT.\n\nPlease select a different type of file system (if possible) and try again. Alternatively, you could leave the volume unformatted (select 'None' as the filesystem), exit this wizard, mount the volume, and then use either a system or a third-party tool to format the mounted volume (the volume will remain encrypted). - Windows failed to format the volume as NTFS/exFAT.\n\nDo you want to format the volume as FAT instead? - Default - partition - PARTITION - Device - device - DEVICE - Volume - volume - VOLUME - Label - The selected cluster size is too small for this volume size. A greater cluster size will be used instead. - Error: Cannot get volume size!\n\nMake sure the selected volume is not being used by the system or an application. - Hidden volumes must not be created within dynamic (sparse file) containers. To achieve plausible deniability, the hidden volume needs to be created within a non-dynamic container. - The VeraCrypt Volume Creation Wizard can create a hidden volume only within a FAT/exFAT or NTFS volume. - Under Windows 2000, the VeraCrypt Volume Creation Wizard can create a hidden volume only within a FAT volume. - Note: The FAT/exFAT file system is more suitable for outer volumes than the NTFS file system (for example, the maximum possible size of the hidden volume would very likely have been significantly greater if the outer volume had been formatted as FAT/exFAT). - Note that the FAT/exFAT file system is more suitable for outer volumes than the NTFS file system. For example, the maximum possible size of the hidden volume will very likely be significantly greater if the outer volume is formatted as FAT/exFAT (the reason is that the NTFS file system always stores internal data exactly in the middle of the volume and, therefore, the hidden volume can reside only in the second half of the outer volume).\n\nAre you sure you want to format the outer volume as NTFS? - Do you want to format the volume as FAT instead? - Note: This volume cannot be formatted as FAT, because it exceeds the maximum volume size supported by the FAT32 filesystem for the applicable sector size (2 TB for 512-byte sectors and 16 TB for 4096-byte sectors). - Error: The partition for the hidden operating system (i.e. the first partition behind the system partition) must be at least 5% larger than the system partition (the system partition is the one where the currently running operating system is installed). - Error: The partition for the hidden operating system (i.e. the first partition behind the system partition) must be at least 110% (2.1 times) larger than the system partition (the system partition is the one where the currently running operating system is installed). The reason is that the NTFS file system always stores internal data exactly in the middle of the volume and, therefore, the hidden volume (which is to contain a clone of the system partition) can reside only in the second half of the partition. - Error: If the outer volume is formatted as NTFS, it must be at least 110% (2.1 times) larger than the system partition. The reason is that the NTFS file system always stores internal data exactly in the middle of the volume and, therefore, the hidden volume (which is to contain a clone of the system partition) can reside only in the second half of the outer volume.\n\nNote: The outer volume needs to reside within the same partition as the hidden operating system (i.e. within the first partition behind the system partition). - Error: There is no partition behind the system partition.\n\nNote that before you can create a hidden operating system, you need to create a partition for it on the system drive. It must be the first partition behind the system partition and it must be at least 5% larger than the system partition (the system partition is the one where the currently running operating system is installed). However, if the outer volume (not to be confused with the system partition) is formatted as NTFS, the partition for the hidden operating system must be at least 110% (2.1 times) larger than the system partition (the reason is that the NTFS file system always stores internal data exactly in the middle of the volume and, therefore, the hidden volume, which is to contain a clone of the system partition, can reside only in the second half of the partition). - Remark: It is not practical (and therefore is not supported) to install operating systems in two VeraCrypt volumes that are embedded within a single partition, because using the outer operating system would often require data to be written to the area of the hidden operating system (and if such write operations were prevented using the hidden volume protection feature, it would inherently cause system crashes, i.e. 'Blue Screen' errors). - For information on how to create and manage partitions, please refer to the documentation supplied with your operating system or contact your computer vendor's technical support team for assistance. - Error: The currently running operating system is not installed on the boot partition (first Active partition). This is not supported. - You indicated that you intend to store files larger than 4 GB in this VeraCrypt volume. However, you chose the FAT file system, on which files larger than 4 GB cannot be stored.\n\nAre you sure you want to format the volume as FAT? - Error: VeraCrypt does not support in-place decryption of legacy non-system volumes created by VeraCrypt 1.0b or earlier.\n\nNote: You can still decrypt files stored on the volume by copying/moving them to any unencrypted volume. - Error: VeraCrypt cannot in-place decrypt a hidden VeraCrypt volume.\n\nNote: You can still decrypt files stored on the volume by copying/moving them to any unencrypted volume. - Warning: Note that VeraCrypt cannot in-place decrypt a volume that contains a hidden VeraCrypt volume (the hidden volume would be overwritten with pseudorandom data).\n\nPlease confirm that the volume you are about to decrypt contains no hidden volume.\n\nNote: If the volume contains a hidden volume but you do not mind losing the hidden volume, you can select Proceed (the outer volume will be safely decrypted). - The volume does not contain any hidden volume. Proceed. - The volume contains a hidden volume. Cancel. - Error: Cannot access the volume!\n\nMake sure that the selected volume exists, that it is not mounted or being used by the system or an application, that you have read/write permission for the volume, and that it is not write-protected. - Error: Cannot obtain volume properties. - Error: Cannot access the volume and/or obtain information about the volume.\n\nMake sure that the selected volume exists, that it is not being used by the system or applications, that you have read/write permission for the volume, and that it is not write-protected. - Error: Cannot access the volume and/or obtain information about the volume. Make sure that the selected volume exists, that it is not being used by the system or applications, that you have read/write permission for the volume, and that it is not write-protected.\n\nIf the problem persists, it might help to follow the below steps. - An error prevented VeraCrypt from encrypting the partition. Please try fixing any previously reported problems and then try again. If the problems persist, it might help to follow the below steps. - An error prevented VeraCrypt from resuming the process of encryption/decryption of the partition/volume.\n\nPlease try fixing any previously reported problems and then try resuming the process again if possible. Note that the volume cannot be mounted until it has been fully encrypted or fully decrypted. - An error prevented VeraCrypt from decrypting the volume. Please try fixing any previously reported problems and then try again if possible. - Error: Cannot dismount the outer volume!\n\nVolume cannot be dismounted if it contains files or folders being used by a program or the system.\n\nPlease close any program that might be using files or directories on the volume and click Retry. - Error: Cannot obtain information about the outer volume!\nVolume creation cannot continue. - Error: Cannot access the outer volume! Volume creation cannot continue. - Error: Cannot mount the outer volume! Volume creation cannot continue. - Error: Cannot get volume cluster bitmap! Volume creation cannot continue. - Alphabetical/Categorized - Mean Speed (Descending) - Algorithm - Encryption - Decryption - Mean - Drive - Size - Encryption Algorithm - Encryption Algorithm - Type - Value - Property - Location - bytes - Hidden - Outer - Normal - System - Hidden (system) - Read-Only - System drive - System drive (encrypting - %.2f%% done) - System drive (decrypting - %.2f%% done) - System drive (%.2f%% encrypted) - System partition - Hidden system partition - System partition (encrypting - %.2f%% done) - System partition (decrypting - %.2f%% done) - System partition (%.2f%% encrypted) - Yes (damage prevented!) - None - Primary Key Size - Secondary Key Size (XTS Mode) - Tweak Key Size (LRW Mode) - bits - Block Size - PKCS-5 PRF - PKCS-5 Iteration Count - Volume Created - Header Last Modified - (%I64d days ago) - Volume Format Version - Embedded Backup Header - VeraCrypt Boot Loader Version - First available - Removable Disk - Harddisk - Unchanged - Autodetection - Wizard Mode - Select one of the modes. If you are not sure which to select, use the default mode. - Select this option if you want to install VeraCrypt on this system. - Note: You can upgrade without decrypting even if the system partition/drive is encrypted or you use a hidden operating system. - If you select this option, all files will be extracted from this package but nothing will be installed on the system. Do not select it if you intend to encrypt the system partition or system drive. Selecting this option can be useful, for example, if you want to run VeraCrypt in so-called portable mode. VeraCrypt does not have to be installed on the operating system under which it is run. After all files are extracted, you can directly run the extracted file 'VeraCrypt.exe' (then VeraCrypt will run in portable mode). - Setup Options - Here you can set various options to control the installation process. - Installing - Please wait while VeraCrypt is being installed. - VeraCrypt has been successfully installed - VeraCrypt has been successfully upgraded - Please consider making a donation. You can click Finish anytime to close the installer. - Extraction Options - Here you can set various options to control the extraction process. - Please wait while files are being extracted. - Files successfully extracted - All files have been successfully extracted to the destination location. - If the specified folder does not exist, it will be automatically created. - The VeraCrypt program files will be upgraded in the location where VeraCrypt is installed. If you need to select a different location, please uninstall VeraCrypt first. - Do you want to view release notes for the current (latest stable) version of VeraCrypt? - If you have never used VeraCrypt before, we recommend that you read the chapter Beginner's Tutorial in the VeraCrypt User Guide. Do you want to view the tutorial? - Please select an action to perform from the following: - Repair/Reinstall - Upgrade - Uninstall - To successfully install/uninstall VeraCrypt, you must have administrator privileges. Do you want to continue? - VeraCrypt Installer is currently running on this system and performing or preparing installation or update of VeraCrypt. Before you proceed, please wait for it to finish or close it. If you cannot close it, please restart your computer before proceeding. - Installation failed. - Uninstallation failed. - This distribution package is damaged. Please try downloading it again (preferably from the official VeraCrypt website at https://veracrypt.codeplex.com). - Cannot write file %s - Extracting - Cannot read data from the package. - Cannot verify the integrity of this distribution package. - Extraction failed. - The installation has been rolled back. - VeraCrypt has been successfully installed. - VeraCrypt has been successfully updated. - VeraCrypt has been successfully upgraded. However, before you can start using it, the computer must be restarted.\n\nDo you want to restart it now? - Failed to upgrade VeraCrypt!\n\nIMPORTANT: Before you shut down or restart the system, we strongly recommend that you use System Restore (Windows Start menu > All programs > Accessories > System Tools > System Restore) to restore your system to the restore point named 'VeraCrypt installation'. If System Restore is not available, you should try installing the original or the new version of VeraCrypt again before you shut down or restart the system. - VeraCrypt has been successfully uninstalled.\n\nClick 'Finish' to remove the VeraCrypt installer and the folder %s. Note that the folder will not be removed if it contains any files that were not installed by the VeraCrypt installer or created by VeraCrypt. - Removing VeraCrypt registry entries - Adding registry entry - Removing application-specific data - Installing - Stopping - Removing - Adding icon - Creating System Restore point - Failed to create System Restore point! - Updating boot loader - Failed to install '%s'. %s\nDo you want to continue installing? - Failed to uninstall '%s'. %s\nDo you want to continue uninstalling? - Installation completed. - The folder '%s' could not be created - The VeraCrypt device driver cannot be unloaded.\n\nPlease close all open VeraCrypt windows first. If it does not help, please restart Windows and then try again. - All VeraCrypt volumes must be dismounted before installing or uninstalling VeraCrypt. - An obsolete version of VeraCrypt is currently installed on this system. It needs to be uninstalled before you can install this new version of VeraCrypt.\n\nAs soon as you close this message box, the uninstaller of the old version will be launched. Note that no volume will be decrypted when you uninstall VeraCrypt. After you uninstall the old version of VeraCrypt, run the installer of the new version of VeraCrypt again. - The installation of the registry entries has failed - The installation of the device driver has failed. Please restart Windows and then try installing VeraCrypt again. - Starting VeraCrypt device driver - Uninstallation of the device driver has failed. Please note that, due to a Windows issue, it may be necessary to log off or restart the system before the device driver can be uninstalled (or reinstalled). - Installing VeraCrypt device driver - Stopping VeraCrypt device driver - Uninstalling VeraCrypt device driver - Registration of the User Account Control support library failed. - Unregistration of the User Account Control support library failed. - Note about portable mode:\n\nPlease note that the operating system requires drivers to be registered with it before they can be started. Hence, the VeraCrypt driver is not (and cannot be) fully portable (whereas the VeraCrypt applications are fully portable, i.e. they do not have to be installed or registered with the operating system). Also note that VeraCrypt needs a driver to provide transparent on-the-fly encryption/decryption. - Note that if you decide to run VeraCrypt in portable mode (as opposed to running an installed copy of VeraCrypt), the system will ask you for permission to run VeraCrypt (UAC prompt) every time you attempt to run it.\n\nThe reason is that when you run VeraCrypt in portable mode, VeraCrypt needs to load and start the VeraCrypt device driver. VeraCrypt needs a device driver to provide transparent on-the-fly encryption/decryption, and users without administrator privileges cannot start device drivers in Windows. Therefore, the system will ask you for permission to run VeraCrypt with administrator privileges (UAC prompt).\n\nNote that if you install VeraCrypt on the system (as opposed to running VeraCrypt in portable mode), the system will NOT ask you for permission to run VeraCrypt (UAC prompt) every time you attempt to run it.\n\nAre you sure you want to extract the files? - Warning: This instance of the Volume Creation Wizard has administrator privileges.\n\nYour new volume may be created with permissions that will not allow you to write to the volume when it is mounted. If you want to avoid that, close this instance of the Volume Creation Wizard and launch a new one without administrator privileges.\n\nDo you want to close this instance of the Volume Creation Wizard? - Error: Cannot display license. - Outer(!) - days - hours - minutes - s - Open - Dismount - Show VeraCrypt - Hide VeraCrypt - Data Read since Mount - Data Written since Mount - Encrypted Portion - 100% (fully encrypted) - 0% (not encrypted) - %.3f%% - 100% - Waiting - Preparing - Resizing - Encrypting - Decrypting - Finalizing - Paused - Finished - Error - Device disconnected - System favorite volumes saved.\n\nTo enable mounting of system favorite volumes when the system starts, please select 'Settings' > 'System Favorite Volumes' > 'Mount system favorite volumes when Windows starts'. - The volume you are adding to favorites is neither a partition nor a dynamic volume. Therefore, VeraCrypt will be unable to mount this favorite volume if the device number changes. - The volume you are adding to favorites is a partition not recognized by Windows.\n\nVeraCrypt will be unable to mount this favorite volume if the device number changes. Please set the type of the partition to a type recognized by Windows (use the SETID command of the Windows 'diskpart' tool). Then add the partition to favorites again. - VeraCrypt Background Task is disabled or it is configured to exit when there are no mounted volumes (or VeraCrypt is running in portable mode). This may prevent your favorite volumes from being automatically mounted when devices hosting them get connected.\n\nNote: To enable the VeraCrypt Background Task, select Settings > Preferences and check the 'Enabled' checkbox in the section 'VeraCrypt Background Task'. - A container stored in a remote filesystem shared over a network cannot be automatically mounted when its host device gets connected. - The device displayed below is neither a partition nor a dynamic volume. Therefore, the volume hosted on the device cannot be automatically mounted when the device gets connected. - Please set the type of the partition displayed below to a type recognized by Windows (use the SETID command of the Windows 'diskpart' tool). Then remove the partition from favorites and add it again. This will enable the volume hosted on the device to be automatically mounted when the device gets connected. - The device displayed below is neither a partition nor a dynamic volume. Therefore, no label can be assigned to it. - Please set the type of the partition displayed below to a type recognized by Windows (use the SETID command of the Windows 'diskpart' tool). Then remove the partition from favorites and add it again. This will enable VeraCrypt to assign a label to the partition. - Due to a Windows limitation, a container stored in a remote filesystem shared over a network cannot be mounted as a system favorite volume (however, it can be mounted as a non-system favorite volume when a user logs on). - Enter password for %s - Enter password for '%s' - Enter password for the normal/outer volume - Enter password for the hidden volume - Enter password for the header stored in backup file - Keyfiles have been successfully created. - The number of keyfiles you supplied is invalid. - The keyfile size must be comprized between 64 and 1048576 bytes. - Please enter a name for the keyfile(s) to be generated - The base name of the keyfile(s) is invalid - The keyfile '%s' already exists.\nDo you want to overwrite it? The generation process will be stopped if you answer No. - WARNING: The header of this volume is damaged! VeraCrypt automatically used the backup of the volume header embedded in the volume.\n\nYou should repair the volume header by selecting 'Tools' > 'Restore Volume Header'. - Volume header backup has been successfully created.\n\nIMPORTANT: Restoring the volume header using this backup will also restore the current volume password. Moreover, if keyfile(s) are/is necessary to mount the volume, the same keyfile(s) will be necessary to mount the volume again when the volume header is restored.\n\nWARNING: This volume header backup may be used to restore the header ONLY of this particular volume. If you use this header backup to restore a header of a different volume, you will be able to mount the volume, but you will NOT be able to decrypt any data stored in the volume (because you will change its master key). - The volume header has been successfully restored.\n\nIMPORTANT: Please note that an old password may have been restored as well. Moreover, if keyfile(s) were/was necessary to mount the volume when the backup was created, the same keyfile(s) are now necessary to mount the volume again. - For security reasons, you will have to enter the correct password (and/or supply the correct keyfiles) for the volume.\n\nNote: If the volume contains a hidden volume, you will have to enter the correct password (and/or supply the correct keyfiles) for the outer volume first. Afterwards, if you choose to back up the header of the hidden volume, you will have to enter the correct password (and/or supply the correct keyfiles) for the hidden volume. - Are you sure you want to create volume header backup for %s?\n\nAfter you click Yes, you will prompted for a filename for the header backup.\n\nNote: Both the standard and the hidden volume headers will be re-encrypted using a new salt and stored in the backup file. If there is no hidden volume within this volume, the area reserved for the hidden volume header in the backup file will be filled with random data (to preserve plausible deniability). When restoring a volume header from the backup file, you will need to enter the correct password (and/or to supply the correct keyfiles) that was/were valid when the volume header backup was created. The password (and/or keyfiles) will also automatically determine the type of the volume header to restore, i.e. standard or hidden (note that VeraCrypt determines the type through the process of trial and error). - Are you sure you want to restore volume header of %s?\n\nWARNING: Restoring a volume header also restores the volume password that was valid when the backup was created. Moreover, if keyfile(s) were/was necessary to mount the volume when the backup was created, the same keyfile(s) will be necessary to mount the volume again after the volume header is restored.\n\nAfter you click Yes, you will select the header backup file. - Does the volume contain a hidden volume? - The volume contains a hidden volume - The volume does not contain a hidden volume - Please select the type of volume header backup you want to use: - Restore the volume header from the backup embedded in the volume - Restore the volume header from an external backup file - The size of the volume header backup file is incorrect. - There is no backup header embedded in this volume (note that only volumes created by VeraCrypt 6.0 or later contain embedded backup headers). - You are attempting to back up the header of the system partition/drive. This is not allowed. Backup/restore operations pertaining to the system partition/drive can be performed only using the VeraCrypt Rescue Disk.\n\nDo you want to create a VeraCrypt Rescue Disk? - You are attempting to restore the header of a virtual VeraCrypt volume but you selected the system partition/drive. This is not allowed. Backup/restore operations pertaining to the system partition/drive can be performed only using the VeraCrypt Rescue Disk.\n\nDo you want to create a VeraCrypt Rescue Disk? - After you click OK, you will select a filename for the new VeraCrypt Rescue Disk ISO image and the location where you wish to place it. - The Rescue Disk image has been created and stored in this file:\n%s\n\nNow you need to burn the Rescue Disk image to a CD or DVD.\n\nIMPORTANT: Note that the file must be written to the CD/DVD as an ISO disk image (not as an individual file). For information on how to do so, please refer to the documentation of your CD/DVD recording software.\n\nAfter you burn the Rescue Disk, select 'System' > 'Verify Rescue Disk' to verify that it has been correctly burned. - The Rescue Disk image has been created and stored in this file:\n%s\n\nNow you need to burn the Rescue Disk image to a CD or DVD.\n\nDo you want to launch the Microsoft Windows Disc Image Burner now?\n\nNote: After you burn the Rescue Disk, select 'System' > 'Verify Rescue Disk' to verify that it has been correctly burned. - Please insert your VeraCrypt Rescue Disk into your CD/DVD drive and click OK to verify it. - The VeraCrypt Rescue Disk has been successfully verified. - Cannot verify that the Rescue Disk has been correctly burned.\n\nIf you have burned the Rescue Disk, please eject and reinsert the CD/DVD; then try again. If this does not help, please try other CD/DVD recording software and/or medium.\n\nIf you attempted to verify a VeraCrypt Rescue Disk created for a different master key, password, salt, etc., please note that such Rescue Disk will always fail this verification. To create a new Rescue Disk fully compatible with your current configuration, select 'System' > 'Create Rescue Disk'. - The VeraCrypt Rescue Disk ISO image has been successfully verified. - The Rescue Disk ISO image verification failed.\n\nIf you attempted to verify a VeraCrypt Rescue Disk ISO image created for a different master key, password, salt, etc., please note that such Rescue Disk ISO image will always fail this verification. To create a new Rescue Disk ISO image fully compatible with your current configuration, select 'System' > 'Create Rescue Disk'. - Error creating VeraCrypt Rescue Disk. - VeraCrypt Rescue Disk cannot be created when a hidden operating system is running.\n\nTo create a VeraCrypt Rescue Disk, boot the decoy operating system and then select 'System' > 'Create Rescue Disk'. - Cannot verify that the Rescue Disk has been correctly burned.\n\nIf you have burned the Rescue Disk, please eject and reinsert the CD/DVD; then click Next to try again. If this does not help, please try another medium%s.\n\nIf you have not burned the Rescue Disk yet, please do so, and then click Next.\n\nIf you attempted to verify a VeraCrypt Rescue Disk created before you started this wizard, please note that such Rescue Disk cannot be used, because it was created for a different master key. You need to burn the newly generated Rescue Disk. - and/or other CD/DVD recording software - VeraCrypt - System Favorite Volumes - What are system favorite volumes? - The system partition/drive does not appear to be encrypted.\n\nSystem favorite volumes can be mounted using only a pre-boot authentication password. Therefore, to enable use of system favorite volumes, you need to encrypt the system partition/drive first. - Please dismount the volume before proceeding. - Error: Cannot set timer. - Check Filesystem - Repair Filesystem - Add to Favorites... - Add to System Favorites... - P&roperties... - Hidden Volume Protected - N/A - Yes - No - Disabled - 1 - 2 or more - Mode of Operation - Label: - Size: - Path: - Drive Letter: - Error: Password must contain only ASCII characters.\n\nNon-ASCII characters in password might cause the volume to be impossible to mount when your system configuration changes.\n\nThe following characters are allowed:\n\n ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \\ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ - Warning: Password contains non-ASCII characters. This may cause the volume to be impossible to mount when your system configuration changes.\n\nYou should replace all non-ASCII characters in the password with ASCII characters. To do so, click 'Volumes' -> 'Change Volume Password'.\n\nThe following are ASCII characters:\n\n ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \\ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ - WARNING: We strongly recommend that you avoid file extensions that are used for executable files (such as .exe, .sys, or .dll) and other similarly problematic file extensions. Using such file extensions causes Windows and antivirus software to interfere with the container, which adversely affects the performance of the volume and may also cause other serious problems.\n\nWe strongly recommend that you remove the file extension or change it (e.g., to '.hc').\n\nAre you sure you want to use the problematic file extension? - WARNING: This container has a file extension that is used for executable files (such as .exe, .sys, or .dll) or some other file extension that is similarly problematic. It will very likely cause Windows and antivirus software to interfere with the container, which will adversely affect the performance of the volume and may also cause other serious problems.\n\nWe strongly recommend that you remove the file extension of the container or change it (e.g., to '.hc') after you dismount the volume. - Homepage - WARNING: It appears that you have not applied any Service Pack to your Windows installation. You should not write to IDE disks larger than 128 GB under Windows XP to which you did not apply Service Pack 1 or later! If you do, data on the disk (no matter if it is a VeraCrypt volume or not) may get corrupted. Note that this is a limitation of Windows, not a bug in VeraCrypt. - WARNING: It appears that you have not applied Service Pack 3 or later to your Windows installation. You should not write to IDE disks larger than 128 GB under Windows 2000 to which you did not apply Service Pack 3 or later! If you do, data on the disk (no matter if it is a VeraCrypt volume or not) may get corrupted. Note that this is a limitation of Windows, not a bug in VeraCrypt.\n\nNote: You may also need to enable the 48-bit LBA support in the registry; for more information, see http://support.microsoft.com/kb/305098/EN-US - WARNING: 48-bit LBA ATAPI support is disabled on your system. Therefore, you should not write to IDE disks larger than 128 GB! If you do, data on the disk (no matter if it is a VeraCrypt volume or not) may get corrupted. Note that this is a limitation of Windows, not a limitation of VeraCrypt.\n\nTo enable the 48-bit LBA support, add the 'EnableBigLba' registry value in the registry key HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\atapi\\Parameters and set it to 1.\n\nFor more information, see http://support.microsoft.com/kb/305098 - Error: Files larger than 4 GB cannot be stored on a FAT32 file system. Therefore, file-hosted VeraCrypt volumes (containers) stored on a FAT32 file system cannot be larger than 4 GB.\n\nIf you need a larger volume, create it on an NTFS file system (or, if you use Windows Vista SP1 or later, on an exFAT file system) or, instead of creating a file-hosted volume, encrypt an entire partition or device. - Warning: Windows XP does not support files larger than 2048 GB (it will report that "Not enough storage is available"). Therefore, you cannot create a file-hosted VeraCrypt volume (container) larger than 2048 GB under Windows XP.\n\nNote that it is still possible to encrypt the entire drive or create a partition-hosted VeraCrypt volume larger than 2048 GB under Windows XP. - WARNING: If you want to be able to add more data/files to the outer volume in future, you should consider choosing a smaller size for the hidden volume.\n\nAre you sure you want to continue with the size you specified? - No volume selected.\n\nClick 'Select Device' or 'Select File' to select a VeraCrypt volume. - No partition selected.\n\nClick 'Select Device' to select a dismounted partition that normally requires pre-boot authentication (for example, a partition located on the encrypted system drive of another operating system, which is not running, or the encrypted system partition of another operating system).\n\nNote: The selected partition will be mounted as a regular VeraCrypt volume without pre-boot authentication. This is useful e.g. for backup or repair operations. - WARNING: If default keyfiles are set and enabled, volumes that are not using these keyfiles will be impossible to mount. Therefore, after you enable default keyfiles, keep in mind to uncheck the 'Use keyfiles' checkbox (below a password input field) whenever mounting such volumes.\n\nAre you sure you want to save the selected keyfiles/paths as default? - Auto-Mount Devices - Dismount All - Wipe Cache - Dismount All & Wipe Cache - Force Dismount All & Wipe Cache - Force Dismount All, Wipe Cache & Exit - Mount Favorite Volumes - Show/Hide Main VeraCrypt Window - (Click here and press a key) - Action - Shortcut - Error: This shortcut is reserved. Please choose a different shortcut. - Error: Shortcut already in use. - WARNING: One or more VeraCrypt system-wide hot keys will not work!\n\nPlease make sure that other applications and the operating system do not use the same shortcut(s) as VeraCrypt. - Paging file creation has been prevented.\n\nPlease note that, due to Windows issues, paging files cannot be located on non-system VeraCrypt volumes (including system favorite volumes). VeraCrypt supports creation of paging files only on an encrypted system partition/drive. - An error or incompatibility prevents VeraCrypt from encrypting the hibernation file. Therefore, hibernation has been prevented.\n\nNote: When a computer hibernates (or enters a power-saving mode), the content of its system memory is written to a hibernation storage file residing on the system drive. VeraCrypt would not be able to prevent encryption keys and the contents of sensitive files opened in RAM from being saved unencrypted to the hibernation storage file. - Hibernation has been prevented.\n\nVeraCrypt does not support hibernation on hidden operating systems that use an extra boot partition. Please note that the boot partition is shared by both the decoy and the hidden system. Therefore, in order to prevent data leaks and problems while resuming from hibernation, VeraCrypt has to prevent the hidden system from writing to the shared boot partition and from hibernating. - VeraCrypt volume mounted as %c: has been dismounted. - VeraCrypt volumes have been dismounted. - VeraCrypt volumes have been dismounted and password cache has been wiped. - Successfully dismounted - WARNING: If the VeraCrypt Background Task is disabled, the following functions will be disabled:\n\n1) Hot keys\n2) Auto-dismount (e.g., upon logoff, inadvertent host device removal, time-out, etc.)\n3) Auto-mount of favorite volumes\n4) Notifications (e.g., when damage to hidden volume is prevented)\n5) Tray icon\n\nNote: You can shut down the Background Task anytime by right-clicking the VeraCrypt tray icon and selecting 'Exit'.\n\nAre you sure you want to permanently disable the VeraCrypt Background Task? - WARNING: If this option is disabled, volumes containing open files/directories will not be possible to auto-dismount.\n\nAre you sure you want to disable this option? - WARNING: Volumes containing open files/directories will NOT be auto-dismounted.\n\nTo prevent this, enable the following option in this dialog window: 'Force auto-dismount even if volume contains open files or directories' - WARNING: When the notebook battery power is low, Windows may omit sending the appropriate messages to running applications when the computer is entering power saving mode. Therefore, VeraCrypt may fail to auto-dismount volumes in such cases. - You have scheduled the process of encryption/decryption of a partition/volume. The process has not been completed yet.\n\nDo you want to resume the process now? - You have scheduled the process of encryption or decryption of the system partition/drive. The process has not been completed yet.\n\nDo you want to start (resume) the process now? - Do you want to be prompted about whether you want to resume the currently scheduled processes of encryption/decryption of non-system partitions/volumes? - Yes, keep prompting me - No, do not prompt me - IMPORTANT: Keep in mind that you can resume the process of encryption/decryption of any non-system partition/volume by selecting 'Volumes' > 'Resume Interrupted Process' from the menu bar of the main VeraCrypt window. - You have scheduled the process of encryption or decryption of the system partition/drive. However, pre-boot authentication failed (or was bypassed).\n\nNote: If you decrypted the system partition/drive in the pre-boot environment, you may need to finalize the process by selecting 'System' > 'Permanently Decrypt System Partition/Drive' from the menu bar of the main VeraCrypt window. - WARNING: If VeraCrypt exits now, the following functions will be disabled:\n\n1) Hot keys\n2) Auto-dismount (e.g., upon logoff, inadvertent host device removal, time-out, etc.)\n3) Auto-mount of favorite volumes\n4) Notifications (e.g., when damage to hidden volume is prevented)\n\nNote: If you do not wish VeraCrypt to run in the background, disable the VeraCrypt Background Task in the Preferences (and, if necessary, disable the automatic start of VeraCrypt in the Preferences).\n\nAre you sure you want VeraCrypt to exit? - Exit? - VeraCrypt does not have sufficient information to determine whether to encrypt or decrypt. - VeraCrypt does not have sufficient information to determine whether to encrypt or decrypt.\n\nNote: If you decrypted the system partition/drive in the pre-boot environment, you may need to finalize the process by clicking Decrypt. - Note: When you are encrypting a non-system partition/volume in place and an error persistently prevents you from finishing the process, you will not be able to mount the volume (and access data stored on it) until you entirely DECRYPT the volume (i.e. reverse the process).\n\nIf you need to do so, follow these steps:\n1) Exit this wizard.\n2) In the main VeraCrypt window, select 'Volumes' > 'Resume Interrupted Process'.\n3) Select 'Decrypt'. - Do you want to interrupt and postpone the process of encryption/decryption of the partition/volume?\n\nNote: Keep in mind that the volume cannot be mounted until it has been fully encrypted or decrypted. You will be able to resume the process of encryption/decryption and it will continue from the point where it was stopped. You can do so, for example, by selecting 'Volumes' > 'Resume Interrupted Process' from the menu bar of the main VeraCrypt window. - Do you want to interrupt and postpone the process of encryption of the system partition/drive?\n\nNote: You will be able to resume the process and it will continue from the point it was stopped. You can do so, for example, by selecting 'System' > 'Resume Interrupted Process' from the menu bar of the main VeraCrypt window. If you want to permanently terminate or reverse the encryption process, select 'System' > 'Permanently Decrypt System Partition/Drive'. - Do you want to interrupt and postpone the process of decryption of the system partition/drive?\n\nNote: You will be able to resume the process and it will continue from the point it was stopped. You can do so, for example, by selecting 'System' > 'Resume Interrupted Process' from the menu bar of the main VeraCrypt window. If you want to reverse the decryption process (and start encrypting), select 'System' > 'Encrypt System Partition/Drive'. - Error: Failed to interrupt the process of encryption/decryption of the system partition/drive. - Error: Failed to interrupt the process of wiping. - Error: Failed to resume the process of encryption/decryption of the system partition/drive. - Error: Failed to start the process of wiping. - Inconsistency resolved.\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n%hs) - Error: Unexpected state.\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n%hs) - There is no interrupted process of encryption/decryption of the system partition/drive to resume.\n\nNote: If you want to resume an interrupted process of encryption/decryption of a non-system partition/volume, select 'Volumes' > 'Resume Interrupted Process'. - WARNING: VeraCrypt Background Task is disabled. After you exit VeraCrypt, you will not be notified if damage to hidden volume is prevented.\n\nNote: You may shut down the Background Task anytime by right-clicking the VeraCrypt tray icon and selecting 'Exit'.\n\nEnable VeraCrypt Background Task? - Language pack version: %s - Checking the file system on the VeraCrypt volume mounted as %s... - Attempting to repair the file system on the VeraCrypt volume mounted as %s... - Warning: This volume is encrypted with a legacy encryption algorithm.\n\nAll 64-bit-block encryption algorithms (e.g., Blowfish, CAST-128, or Triple DES) are deprecated. It will be possible to mount this volume using future versions of VeraCrypt. However, there will be no further enhancements to the implementations of these legacy encryption algorithms. We recommend that you create a new VeraCrypt volume encrypted with a 128-bit-block encryption algorithm (e.g., AES, Serpent, Twofish, etc.) and that you move all files from this volume to the new volume. - Your system is not configured to auto-mount new volumes. It may be impossible to mount device-hosted VeraCrypt volumes. Auto-mounting can be enabled by executing the following command and restarting the system.\n\nmountvol.exe /E - Please assign a drive letter to the partition/device before proceeding ('Control Panel' > 'System and Maintenance' > 'Administrative Tools' - 'Create and format hard disk partitions').\n\nNote that this is a requirement of the operating system. - Mount VeraCrypt volume - Dismount all VeraCrypt volumes - VeraCrypt failed to obtain Administrator privileges. - Access was denied by the operating system.\n\nPossible cause: The operating system requires that you have read/write permission (or administrator privileges) for certain folders, files, and devices, in order for you to be allowed to read and write data to/from them. Normally, a user without administrator privileges is allowed to create, read and modify files in his or her Documents folder. - Error: The drive uses an unsupported sector size.\n\nIt is currently not possible to create partition/device-hosted volumes on drives that use sectors larger than 4096 bytes. However, note that you can create file-hosted volumes (containers) on such drives. - It is currently not possible to encrypt a system installed on a disk that uses a sector size other than 512 bytes. - The VeraCrypt Boot Loader requires at least 32 KBytes of free space at the beginning of the system drive (the VeraCrypt Boot Loader needs to be stored in that area). Unfortunately, your drive does not meet this condition.\n\nPlease do NOT report this as a bug/problem in VeraCrypt. To solve this problem, you will need to repartition your disk and leave the first 32 KBytes of the disk free (in most cases, you will need to delete and recreate the first partition). We recommend that you use the Microsoft partition manager that is available e.g. when you are installing Windows. - The feature is not supported on the version of the operating system you are currently using. - VeraCrypt does not support encryption of a system partition/drive on the version of the operating system you are currently using. - Before you can encrypt the system partition/drive on Windows Vista, you need to install Service Pack 1 or higher for Windows Vista (no such Service Pack has been installed on this system yet).\n\nNote: Service Pack 1 for Windows Vista resolved an issue causing a shortage of free base memory during system boot. - VeraCrypt no longer supports encryption of the system partition/drive on Windows Vista with no Service Pack installed. Before upgrading VeraCrypt, please install Service Pack 1 or higher for Windows Vista. - Error: This feature requires VeraCrypt to be installed on the system (you are running VeraCrypt in portable mode).\n\nPlease install VeraCrypt and then try again. - WARNING: Windows does not appear to be installed on the drive from which it boots. This is not supported.\n\nYou should continue only if you are sure that Windows is installed on the drive from which it boots.\n\nDo you want to continue? - Your system drive has a GUID partition table (GPT). Currently, only drives with a MBR partition table are supported. - CAUTION: The VeraCrypt Boot Loader is already installed on your system drive!\n\nIt is possible that another system on your computer is already encrypted.\n\nWARNING: PROCEEDING WITH ENCRYPTION OF THE CURRENTLY RUNNING SYSTEM MAY MAKE OTHER SYSTEM(S) IMPOSSIBLE TO START AND RELATED DATA INACCESSIBLE.\n\nAre you sure you want to continue? - Failed to restore the original system loader.\n\nPlease use your VeraCrypt Rescue Disk ('Repair Options' > 'Restore original system loader') or Windows installation medium to replace the VeraCrypt Boot Loader with the Windows system loader. - The original system loader will not be stored on the Rescue Disk (probable cause: missing backup file). - Failed to write the MBR sector.\n\nYour BIOS may be configured to protect the MBR sector. Check your BIOS settings (press F2, Delete, or Esc, after powering on your computer) for MBR/antivirus protection. - WARNING: The verification of VeraCrypt bootloader fingerprint failed!\nYour disk may have been tampered with by an attacker ("Evil Maid" attack).\n\nThis warning can also be triggered if you restored VeraCrypt boot loader using an Rescue Disk generated using a different VeraCrypt version.\n\nYou are advised to change your password immediately which will also restore the correct VeraCrypt bootloader. It is recommended to reinstall VeraCrypt and to take measures to avoid access to this machine by untrusted entities. - The required version of the VeraCrypt Boot Loader is currently not installed. This may prevent some of the settings from being saved. - Note: In some situations, you may wish to prevent a person (adversary) that is watching you start the computer from knowing that you use VeraCrypt. The above options allow you to do that by customizing the VeraCrypt boot loader screen. If you enable the first option, no texts will be displayed by the boot loader (not even when you enter the wrong password). The computer will appear to be "frozen" while you can type your password. In addition, a custom message can be displayed to mislead the adversary. For example, fake error messages such as "Missing operating system" (which is normally displayed by the Windows boot loader if it finds no Windows boot partition). It is, however, important to note that if the adversary can analyze the content of the hard drive, he can still find out that it contains the VeraCrypt boot loader. - WARNING: Please keep in mind that if you enable this option, the VeraCrypt boot loader will not display any texts (not even when you enter the wrong password). The computer will appear to be "frozen" (unresponsive) while you can type your password (the cursor will NOT move and no asterisk will be displayed when you press a key).\n\nAre you sure you want to enable this option? - Your system partition/drive appears to be fully encrypted. - VeraCrypt does not support encrypting a system drive that has been converted to a dynamic disk. - The system drive contains extended (logical) partitions.\n\nYou can encrypt an entire system drive containing extended (logical) partitions only on Windows Vista and later versions of Windows. On Windows XP, you can encrypt an entire system drive provided that it contains only primary partitions.\n\nNote: You can still encrypt the system partition instead of the entire system drive (and, in addition to that, you can create partition-hosted VeraCrypt volumes within any non-system partitions on the drive). - WARNING: As you are running Windows XP/2003, after you start encrypting the drive, you must NOT create any extended (logical) partitions on it (you may create only primary partitions). Any extended (logical) partition on the drive would be inaccessible after you start encrypting (the drive currently does not contain any such partition).\n\nNote: If this limitation is not acceptable, you can go back and choose to encrypt only the system partition instead of the entire drive (and, in addition to that, you can create partition-hosted VeraCrypt volumes within any non-system partitions on the drive).\n\nAlternatively, if this limitation is not acceptable, you may want to consider upgrading to Windows Vista or a later version of Windows (you can encrypt an entire system drive containing extended/logical partitions only on Windows Vista or later). - Your system drive contains a non-standard partition.\n\nIf you are using a notebook, your system drive probably contains a special recovery partition. After the whole system drive is encrypted (including any recovery partition), your system might become unbootable if your computer is using an inappropriately designed BIOS. It would also be impossible to use any recovery partition until the system drive is decrypted. Therefore, we recommend that you encrypt only the system partition. - Do you want to encrypt the system partition instead of the entire drive?\n\nNote that you can create partition-hosted VeraCrypt volumes within any non-system partitions on the drive (in addition to encrypting the system partition). - As your system drive contains only a single partition that occupies the whole drive, it is preferable (more secure) to encrypt the entire drive including the free "slack" space that typically surrounds such a partition.\n\nDo you want to encrypt the entire system drive? - Your system is configured to store temporary files on a non-system partition.\n\nTemporary files may be stored only on the system partition. - Your user profile files are not stored on the system partition.\n\nUser profile files may be stored only on the system partition. - There is/are paging file(s) on non-system partitions.\n\nPaging files may be located only on the system partition. - Do you want to configure Windows to create paging files only on the Windows partition now?\n\nNote that if you click 'Yes', the computer will be restarted. Then start VeraCrypt and try creating the hidden OS again. - Otherwise, plausible deniability of the hidden operating system might be adversely affected.\n\nNote: If an adversary analyzed the content of such files (residing on a non-system partition), he might find out that you used this wizard in the hidden-system-creation mode (which might indicate the existence of a hidden operating system on your computer). Also note that any such files stored on the system partition will be securely erased by VeraCrypt during the process of creation of the hidden operating system. - WARNING: During the process of creation of the hidden operating system, you will be required to fully reinstall the currently running system (in order to create a decoy system securely).\n\nNote: The currently running operating system and the entire content of the system partition will be copied to the hidden volume (in order to create the hidden system).\n\n\nAre you sure you will be able to install Windows using a Windows Setup medium (or using a service partition)? - For security reasons, if the currently running operating system requires activation, it must be activated before proceeding. Note that the hidden operating system will be created by copying the content of the system partition to a hidden volume (so if this operating system is not activated, the hidden operating system will not be activated either). For more information, see the section "Security Requirements and Precautions Pertaining to Hidden Volumes" in the VeraCrypt User's Guide.\n\nImportant: Before proceeding, please make sure you have read the section "Security Requirements and Precautions Pertaining to Hidden Volumes" in the VeraCrypt User's Guide.\n\n\nDoes the currently running operating system meet the above condition? - Your system uses an extra boot partition. VeraCrypt does not support hibernation on hidden operating systems that use an extra boot partition (decoy systems can be hibernated without any problems).\n\nPlease note that the boot partition would be shared by both the decoy and the hidden system. Therefore, in order to prevent data leaks and problems while resuming from hibernation, VeraCrypt has to prevent the hidden system from writing to the shared boot partition and from hibernating.\n\n\nDo you want to continue? If you select 'No', instructions for removing the extra boot partition will be displayed. - \nThe extra boot partition can be removed before installing Windows. To do so, follow these steps:\n\n1) Boot your Windows installation disc.\n\n2) In the Windows installer screen, click 'Install now' > 'Custom (advanced)'.\n\n3) Click 'Drive Options'.\n\n4) Select the main system partition and delete it by clicking 'Delete' and 'OK'.\n\n5) Select the 'System Reserved' partition, click 'Extend', and increase its size so that the operating system can be installed to it.\n\n6) Click 'Apply' and 'OK'.\n\n7) Install Windows on the 'System Reserved' partition.\n\n\nShould an attacker ask why you removed the extra boot partition, you can answer that you wanted to prevent any possible data leaks to the unencrypted boot partition.\n\nNote: You can print this text by clicking the 'Print' button below. If you save a copy of this text or print it (strongly recommended, unless your printer stores copies of documents it prints on its internal drive), you should destroy any copies of it after removing the extra boot partition (otherwise, if such a copy was found, it might indicate that there is a hidden operating system on this computer). - Warning: There is unallocated space between the system partition and the first partition behind it. After you create the hidden operating system, you must not create any new partitions in that unallocated space. Otherwise, the hidden operating system will be impossible to boot (until you delete such newly created partitions). - This algorithm is currently not supported for system encryption. - This algorithm is not supported for TrueCrypt mode. - PIM (Personal Iterations Multiplier) not supported for TrueCrypt mode. - Password must contain 20 or more characters in order to use the specified PIM.\nShorter passwords can only be used if the PIM is 485 or greater. - Pre-boot authentication Password must contain 20 or more characters in order to use the specified PIM.\nShorter passwords can only be used if the PIM is 98 or greater. - Keyfiles are currently not supported for system encryption. - Warning: VeraCrypt could not restore the original keyboard layout. This may cause you to enter a password incorrectly. - Error: Cannot set the keyboard layout for VeraCrypt to the standard US keyboard layout.\n\nNote that the password needs to be typed in the pre-boot environment (before Windows starts) where non-US Windows keyboard layouts are not available. Therefore, the password must always be typed using the standard US keyboard layout. - As VeraCrypt temporarily changed the keyboard layout to the standard US keyboard layout, it is not possible to type characters by pressing keys while the right Alt key is held down. However, you can type most of such characters by pressing appropriate keys while the Shift key is held down. - VeraCrypt prevented change of keyboard layout. - Note: The password will need to be typed in the pre-boot environment (before Windows starts) where non-US Windows keyboard layouts are not available. Therefore, the password must always be typed using the standard US keyboard layout. However, it is important to note that you do NOT need a real US keyboard. VeraCrypt automatically ensures that you can safely type the password (right now and in the pre-boot environment) even if you do NOT have a real US keyboard. - Before you can encrypt the partition/drive, you must create a VeraCrypt Rescue Disk (VRD), which serves the following purposes:\n\n- If the VeraCrypt Boot Loader, master key, or other critical data gets damaged, the VRD allows you to restore it (note, however, that you will still have to enter the correct password then).\n\n- If Windows gets damaged and cannot start, the VRD allows you to permanently decrypt the partition/drive before Windows starts.\n\n- The VRD will contain a backup of the present content of the first drive track (which typically contains a system loader or boot manager) and will allow you to restore it if necessary.\n\nThe VeraCrypt Rescue Disk ISO image will be created in the location specified below. - After you click OK, Microsoft Windows Disc Image Burner will be launched. Please use it to burn the VeraCrypt Rescue Disk ISO image to a CD or DVD.\n\nAfter you do so, return to the VeraCrypt Volume Creation Wizard and follow its instructions. - The Rescue Disk image has been created and stored in this file:\n%s\n\nNow you need to burn it to a CD or DVD.\n\n%lsAfter you burn the Rescue Disk, click Next to verify that it has been correctly burned. - The Rescue Disk image has been created and stored in this file:\n%s\n\nNow you should either burn the image to a CD/DVD or move it to a safe location for later use.\n\n%lsClick Next to continue. - IMPORTANT: Note that the file must be written to the CD/DVD as an ISO disk image (not as an individual file). For information on how to do so, please refer to the documentation of your CD/DVD recording software. If you do not have any CD/DVD recording software that can write the ISO disk image to a CD/DVD, click the link below to download such free software.\n\n - Launch Microsoft Windows Disc Image Burner - WARNING: If you already created a VeraCrypt Rescue Disk in the past, it cannot be reused for this system partition/drive because it was created for a different master key! Every time you encrypt a system partition/drive, you must create a new VeraCrypt Rescue Disk for it even if you use the same password. - Error: Cannot save system encryption settings. - Cannot initiate the system encryption pretest. - Cannot initiate the process of creation of the hidden operating system. - Wipe Mode - On some types of storage media, when data is overwritten with other data, it may be possible to recover the overwritten data using techniques such as magnetic force microscopy. This also applies to data that are overwritten with their encrypted form (which happens when VeraCrypt initially encrypts an unencrypted partition or drive). According to some studies and governmental publications, recovery of overwritten data can be prevented (or made very difficult) by overwriting the data with pseudorandom and certain non-random data a certain number of times. Therefore, if you believe that an adversary might be able to use such techniques to recover the data you intend to encrypt, you may want to select one of the wipe modes (existing data will NOT be lost). Note that wiping will NOT be performed after the partition/drive is encrypted. When the partition/drive is fully encrypted, no unencrypted data is written to it. Any data being written to it is first encrypted on the fly in memory and only then is the (encrypted) data written to the disk. - On some types of storage media, when data is overwritten with other data (e.g. when the data is erased), it may be possible to recover the overwritten data using techniques such as magnetic force microscopy. According to some studies and governmental publications, recovery of overwritten data can be prevented (or made very difficult) by overwriting the data with pseudorandom and certain non-random data a certain number of times. Therefore, if you believe that an adversary might be able to use such techniques to recover the data that is to be erased, you may want to select one of the multi-pass wipe modes.\n\nNote: The more wipe passes you use, the longer it takes to erase the data. - Wiping - \nNote: You can interrupt the process of wiping, shut down your computer, start the hidden system again and then resume the process (this wizard will be launched automatically). However, if you interrupt it, the entire process of wiping will have to start from the beginning. - \n\nNote: If you interrupt the process of wiping and then attempt to resume it, the entire process will have to start from the beginning. - Do you want to abort the process of wiping? - Warning: The entire content of the selected partition/device will be erased and lost. - The entire content of the partition where the original system resides will be erased.\n\nNote: The entire content of the partition that is to be erased has been copied to this hidden system partition. - WARNING: Note that when you choose e.g. the 3-pass wipe mode, the time necessary to encrypt the partition/drive will be up to 4 times longer. Likewise, if you choose the 35-pass wipe mode, it will be up to 36 times longer (it might even take several weeks).\n\nHowever, please note that wiping will NOT be performed after the partition/drive is fully encrypted. When the partition/drive is fully encrypted, no unencrypted data is written to it. Any data being written to it is first encrypted on the fly in memory and only then is the (encrypted) data written to the disk (so the performance will NOT be affected).\n\nAre you sure you want to use the wipe mode? - None (fastest) - 1-pass (random data) - 3-pass (US DoD 5220.22-M) - 7-pass (US DoD 5220.22-M) - 35-pass ("Gutmann") - 256-pass - Number of Operating Systems - WARNING: Inexperienced users should never attempt to encrypt Windows in multi-boot configurations.\n\nContinue? - When creating/using a hidden operating system, VeraCrypt supports multi-boot configurations only when the following conditions are met:\n\n- The currently running operating system must be installed on the boot drive, which must not contain any other operating systems.\n\n- Operating systems installed on other drives must not use any boot loader residing on the drive on which the currently running operating system is installed.\n\nAre the above conditions met? - VeraCrypt does not support this multi-boot configuration when creating/using a hidden operating system. - Boot Drive - Is the currently running operating system installed on the boot drive?\n\nNote: Sometimes, Windows is not installed on the same drive as the Windows boot loader (boot partition). If that is the case, select 'No'. - VeraCrypt currently does not support encrypting an operating system that does not boot from the drive on which it is installed. - Number of System Drives - How many drives contain an operating system?\n\nNote: For example, if you have any operating system (e.g. Windows, Mac OS X, Linux, etc.) installed on your primary drive and any additional operating system installed on your secondary drive, select '2 or more'. - VeraCrypt currently does not support encrypting a whole drive that contains multiple operating systems.\n\nPossible Solutions:\n\n- You can still encrypt one of the systems if you go back and choose to encrypt only a single system partition (as opposed to choosing to encrypt the entire system drive).\n\n- Alternatively, you will be able to encrypt the entire drive if you move some of the systems to other drives leaving only one system on the drive you want to encrypt. - Multiple Systems on Single Drive - Are there any other operating systems installed on the drive on which the currently running operating system is installed?\n\nNote: For example, if the currently running operating system is installed on the drive #0, which contains several partitions, and if one of the partitions contains Windows and another partition contains any additional operating system (e.g. Windows, Mac OS X, Linux, etc.), select 'Yes'. - Non-Windows Boot Loader - Is a non-Windows boot loader (or boot manager) installed in the master boot record (MBR)?\n\nNote: For example, if the first track of the boot drive contains GRUB, LILO, XOSL, or some other non-Windows boot manager (or boot loader), select 'Yes'. - Multi-Boot - VeraCrypt currently does not support multi-boot configurations where a non-Windows boot loader is installed in the Master Boot Record.\n\nPossible Solutions:\n\n- If you use a boot manager to boot Windows and Linux, move the boot manager (typically, GRUB) from the Master Boot Record to a partition. Then start this wizard again and encrypt the system partition/drive. Note that the VeraCrypt Boot Loader will become your primary boot manager and it will allow you to launch the original boot manager (e.g. GRUB) as your secondary boot manager (by pressing Esc in the VeraCrypt Boot Loader screen) and thus you will be able boot Linux. - If the currently running operating system is installed on the boot partition, then, after you encrypt it, you will need to enter the correct password even if you want to start any other unencrypted Windows system(s) (as they will share a single encrypted Windows boot loader/manager).\n\nIn contrast, if the currently running operating system is not installed on the boot partition (or if the Windows boot loader/manager is not used by any other system), then, after you encrypt this system, you will not need to enter the correct password to boot the other unencrypted system(s) -- you will only need to press the Esc key to start the unencrypted system (if there are multiple unencrypted systems, you will also need to choose which system to start in the VeraCrypt Boot Manager menu).\n\nNote: Typically, the earliest installed Windows system is installed on the boot partition. - Encryption of Host Protected Area - At the end of many drives, there is an area that is normally hidden from the operating system (such areas are usually referred to as Host Protected Areas). However, some programs can read and write data from/to such areas.\n\nWARNING: Some computer manufacturers may use such areas to store tools and data for RAID, system recovery, system setup, diagnostic, or other purposes. If such tools or data must be accessible before booting, the hidden area should NOT be encrypted (choose 'No' above).\n\nDo you want VeraCrypt to detect and encrypt such a hidden area (if any) at the end of the system drive? - Type of System Encryption - Select this option if you merely want to encrypt the system partition or the entire system drive. - It may happen that you are forced by somebody to decrypt the operating system. There are many situations where you cannot refuse to do so (for example, due to extortion). If you select this option, you will create a hidden operating system whose existence should be impossible to prove (provided that certain guidelines are followed). Thus, you will not have to decrypt or reveal the password to the hidden operating system. For a detailed explanation, please click the link below. - It may happen that you are forced by somebody to decrypt the operating system. There are many situations where you cannot refuse to do so (for example, due to extortion).\n\nUsing this wizard, you can create a hidden operating system whose existence should be impossible to prove (provided that certain guidelines are followed). Thus, you will not have to decrypt or reveal the password for the hidden operating system. - Hidden Operating System - In the following steps, you will create two VeraCrypt volumes (outer and hidden) within the first partition behind the system partition. The hidden volume will contain the hidden operating system (OS). VeraCrypt will create the hidden OS by copying the content of the system partition (where the currently running OS is installed) to the hidden volume. To the outer volume, you will copy some sensitive looking files that you actually do NOT want to hide. They will be there for anyone forcing you to disclose the password for the hidden OS partition. You can reveal the password for the outer volume within the hidden OS partition (the existence of the hidden OS remains secret).\n\nFinally, on the system partition of the currently running OS, you will install a new OS, so-called decoy OS, and encrypt it. It must not contain sensitive data and will be there for anyone forcing you to reveal your pre-boot authentication password. In total, there will be three passwords. Two of them can be disclosed (for the decoy OS and outer volume). If you use the third one, the hidden OS will start. - Detecting Hidden Sectors - Please wait while VeraCrypt is detecting possible hidden sectors at the end of the system drive. Note that it may take a long time to complete.\n\nNote: In very rare cases, on some computers, the system may become unresponsive during this detection process. If it happens, restart the computer, start VeraCrypt, repeat the previous steps but skip this detection process. Note that this issue is not caused by a bug in VeraCrypt. - Area to Encrypt - Select this option if you want to encrypt the entire drive on which the currently running Windows system is installed. The whole drive, including all its partitions, will be encrypted except the first track where the VeraCrypt Boot Loader will reside. Anyone who wants to access a system installed on the drive, or files stored on the drive, will need to enter the correct password each time before the system starts. This option cannot be used to encrypt a secondary or external drive if Windows is not installed on it and does not boot from it. - Collecting Random Data - Keys Generated - VeraCrypt has found no CD/DVD burner connected to your computer. VeraCrypt needs a CD/DVD burner to burn a bootable VeraCrypt Rescue Disk containing a backup of the encryption keys, VeraCrypt boot loader, original system loader, etc.\n\nWe strongly recommend that you burn the VeraCrypt Rescue Disk. - I have no CD/DVD burner but I will store the Rescue Disk ISO image on a removable drive (e.g. USB flash drive). - I will connect a CD/DVD burner to my computer later. Terminate the process now. - A CD/DVD burner is connected to my computer now. Continue and write the Rescue Disk. - Please follow these steps:\n\n1) Connect a removable drive, such as a USB flash drive, to your computer now.\n\n2) Copy the VeraCrypt Rescue Disk image file (%s) to the removable drive.\n\nIn case you need to use the VeraCrypt Rescue Disk in the future, you will be able to connect your removable drive (containing the VeraCrypt Rescue Disk image) to a computer with a CD/DVD burner and create a bootable VeraCrypt Rescue Disk by burning the image to a CD or DVD. IMPORTANT: Note that the VeraCrypt Rescue Disk image file must be written to the CD/DVD as an ISO disk image (not as an individual file). - Rescue Disk Recording - Rescue Disk Created - System Encryption Pretest - Rescue Disk Verified - \nThe VeraCrypt Rescue Disk has been successfully verified. Please remove it from the drive now and store it in a safe place.\n\nClick Next to continue. - WARNING: During the next steps, the VeraCrypt Rescue Disk must not be in the drive. Otherwise, it will not be possible to complete the steps correctly.\n\nPlease remove it from the drive now and store it in a safe place. Then click OK. - Warning: Due to technical limitations of the pre-boot environment, texts displayed by VeraCrypt in the pre-boot environment (i.e. before Windows starts) cannot be localized. The VeraCrypt Boot Loader user interface is completely in English.\n\nContinue? - Before encrypting your system partition or drive, VeraCrypt needs to verify that everything works correctly.\n\nAfter you click Test, all the necessary components (for example, the pre-boot authentication component, i.e. the VeraCrypt Boot Loader) will be installed and your computer will be restarted. Then you will have to enter your password in the VeraCrypt Boot Loader screen that will appear before Windows starts. After Windows starts, you will be automatically informed about the result of this pretest.\n\nThe following device will be modified: Drive #%d\n\n\nIf you click Cancel now, nothing will be installed and the pretest will not be performed. - IMPORTANT NOTES -- PLEASE READ OR PRINT (click 'Print'):\n\nNote that none of your files will be encrypted before you successfully restart your computer and start Windows. Thus, if anything fails, your data will NOT be lost. However, if something does go wrong, you might encounter difficulties in starting Windows. Therefore, please read (and, if possible, print) the following guidelines on what to do if Windows cannot start after you restart the computer.\n\n - What to Do If Windows Cannot Start\n------------------------------------------------\n\nNote: These instructions are valid only if you have not started encrypting.\n\n- If Windows does not start after you enter the correct password (or if you repeatedly enter the correct password but VeraCrypt says that the password is incorrect), do not panic. Restart (power off and on) the computer, and in the VeraCrypt Boot Loader screen, press the Esc key on your keyboard (and if you have multiple systems, choose which to start). Then Windows should start (provided that it is not encrypted) and VeraCrypt will automatically ask whether you want to uninstall the pre-boot authentication component. Note that the previous steps do NOT work if the system partition/drive is encrypted (nobody can start Windows or access encrypted data on the drive without the correct password even if he or she follows the previous steps).\n\n - - If the previous steps do not help or if the VeraCrypt Boot Loader screen does not appear (before Windows starts), insert the VeraCrypt Rescue Disk into your CD/DVD drive and restart your computer. If the VeraCrypt Rescue Disk screen does not appear (or if you do not see the 'Repair Options' item in the 'Keyboard Controls' section of the VeraCrypt Rescue Disk screen), it is possible that your BIOS is configured to attempt to boot from hard drives before CD/DVD drives. If that is the case, restart your computer, press F2 or Delete (as soon as you see a BIOS start-up screen), and wait until a BIOS configuration screen appears. If no BIOS configuration screen appears, restart (reset) the computer again and start pressing F2 or Delete repeatedly as soon as you restart (reset) the computer. When a BIOS configuration screen appears, configure your BIOS to boot from the CD/DVD drive first (for information on how to do so, please refer to the documentation for your BIOS/motherboard or contact your computer vendor's technical support team for assistance). Then restart your computer. The VeraCrypt Rescue Disk screen should appear now. In the VeraCrypt Rescue Disk screen, select 'Repair Options' by pressing F8 on your keyboard. From the 'Repair Options' menu, select 'Restore original system loader'. Then remove the Rescue Disk from your CD/DVD drive and restart your computer. Windows should start normally (provided that it is not encrypted).\n\n - Note that the previous steps do NOT work if the system partition/drive is encrypted (nobody can start Windows or access encrypted data on the drive without the correct password even if he or she follows the previous steps).\n\n\nNote that even if you lose your VeraCrypt Rescue Disk and an attacker finds it, he or she will NOT be able to decrypt the system partition or drive without the correct password. - Pretest Completed - The pretest has been successfully completed.\n\nWARNING: Please note that if power supply is suddenly interrupted while encrypting existing data in place, or when the operating system crashes due to a software error or hardware malfunction while VeraCrypt is encrypting existing data in place, portions of the data will be corrupted or lost. Therefore, before you start encrypting, please make sure that you have backup copies of the files you want to encrypt. If you do not, please back up the files now (you can click Defer, back up the files, then run VeraCrypt again anytime, and select 'System' > 'Resume Interrupted Process' to start encrypting).\n\nWhen ready, click Encrypt to start encrypting. - You can click Pause or Defer anytime to interrupt the process of encryption or decryption, exit this wizard, restart or shut down your computer, and then resume the process, which will continue from the point it was stopped. To prevent slowdown when the system or applications write or read data from the system drive, VeraCrypt automatically waits until the data is written or read (see Status above) and then automatically continues encrypting or decrypting. - \n\nYou can click Pause or Defer anytime to interrupt the process of encryption, exit this wizard, restart or shut down your computer, and then resume the process, which will continue from the point it was stopped. Note that the volume cannot be mounted until it has been fully encrypted. - \n\nYou can click Pause or Defer anytime to interrupt the process of decryption, exit this wizard, restart or shut down the computer, and then resume the process, which will continue from the point where it was stopped. Note that the volume cannot be mounted until it has been fully decrypted. - Hidden System Started - Original System - Windows creates (typically, without your knowledge or consent) various log files, temporary files, etc., on the system partition. It also saves the content of RAM to hibernation and paging files located on the system partition. Therefore, if an adversary analyzed files stored on the partition where the original system (of which the hidden system is a clone) resides, he might find out, for example, that you used the VeraCrypt wizard in the hidden-system-creation mode (which might indicate the existence of a hidden operating system on your computer).\n\nTo prevent such issues, VeraCrypt will, in the next steps, securely erase the entire content of the partition where the original system resides. Afterwards, in order to achieve plausible deniability, you will need to install a new system on the partition and encrypt it. Thus you will create the decoy system and the whole process of creation of the hidden operating system will be completed. - The hidden operating system has been successfully created. However, before you can start using it (and achieve plausible deniability), you need to securely erase (using VeraCrypt) the entire content of the partition where the currently running operating system is installed. Before you can do that, you need to restart the computer and, in the VeraCrypt Boot Loader screen (which appears before Windows starts), enter the pre-boot authentication password for the hidden operating system. Then, after the hidden system starts, the VeraCrypt wizard will be launched automatically.\n\nNote: If you choose to terminate the process of creation of the hidden operating system now, you will NOT be able to resume the process and the hidden system will NOT be accessible (because the VeraCrypt Boot Loader will be removed). - You have scheduled the process of creation of a hidden operating system. The process has not been completed yet. To complete it, you need to restart the computer and, in the VeraCrypt Boot Loader screen (which appears before Windows starts), enter the password for the hidden operating system.\n\nNote: If you choose to terminate the process of creation of the hidden operating system now, you will NOT be able to resume the process. - Restart the computer and proceed - Permanently terminate the process of creation of the hidden operating system - Do nothing now and ask again later - \nIF POSSIBLE, PLEASE PRINT THIS TEXT (click 'Print' below).\n\n\nHow and When to Use VeraCrypt Rescue Disk (After Encrypting)\n-----------------------------------------------------------------------------------\n\n - I. How to Boot VeraCrypt Rescue Disk\n\nTo boot a VeraCrypt Rescue Disk, insert it into your CD/DVD drive and restart your computer. If the VeraCrypt Rescue Disk screen does not appear (or if you do not see the 'Repair Options' item in the 'Keyboard Controls' section of the screen), it is possible that your BIOS is configured to attempt to boot from hard drives before CD/DVD drives. If that is the case, restart your computer, press F2 or Delete (as soon as you see a BIOS start-up screen), and wait until a BIOS configuration screen appears. If no BIOS configuration screen appears, restart (reset) the computer again and start pressing F2 or Delete repeatedly as soon as you restart (reset) the computer. When a BIOS configuration screen appears, configure your BIOS to boot from the CD/DVD drive first (for information on how to do so, please refer to the documentation for your BIOS/motherboard or contact your computer vendor's technical support team for assistance). Then restart your computer. The VeraCrypt Rescue Disk screen should appear now. Note: In the VeraCrypt Rescue Disk screen, you can select 'Repair Options' by pressing F8 on your keyboard.\n\n\n - II. When and How to Use VeraCrypt Rescue Disk (After Encrypting)\n\n - 1) If the VeraCrypt Boot Loader screen does not appear after you start your computer (or if Windows does not boot), the VeraCrypt Boot Loader may be damaged. The VeraCrypt Rescue Disk allows you to restore it and thus to regain access to your encrypted system and data (however, note that you will still have to enter the correct password then). In the Rescue Disk screen, select 'Repair Options' > 'Restore VeraCrypt Boot Loader'. Then press 'Y' to confirm the action, remove the Rescue Disk from your CD/DVD drive and restart your computer.\n\n - 2) If you repeatedly enter the correct password but VeraCrypt says that the password is incorrect, the master key or other critical data may be damaged. The VeraCrypt Rescue Disk allows you to restore them and thus to regain access to your encrypted system and data (however, note that you will still have to enter the correct password then). In the Rescue Disk screen, select 'Repair Options' > 'Restore key data'. Then enter your password, press 'Y' to confirm the action, remove the Rescue Disk from your CD/DVD drive, and restart your computer.\n\n - 3) If the VeraCrypt Boot Loader is damaged, you can avoid running it by booting directly from the VeraCrypt Rescue Disk. Insert your Rescue Disk into your CD/DVD drive and then enter your password in the Rescue Disk screen.\n\n - 4) If Windows is damaged and cannot start, the VeraCrypt Rescue Disk allows you to permanently decrypt the partition/drive before Windows starts. In the Rescue Disk screen, select 'Repair Options' > 'Permanently decrypt system partition/drive'. Enter the correct password and wait until decryption is complete. Then you can e.g. boot your MS Windows setup CD/DVD to repair your Windows installation.\n\n - Note: Alternatively, if Windows is damaged (cannot start) and you need to repair it (or access files on it), you can avoid decrypting the system partition/drive by following these steps: If you have multiple operating systems installed on your computer, boot the one that does not require pre-boot authentication. If you do not have multiple operating systems installed on your computer, you can boot a WinPE or BartPE CD/DVD or you can connect your system drive as a secondary or external drive to another computer and then boot the operating system installed on the computer. After you boot a system, run VeraCrypt, click 'Select Device', select the affected system partition, click 'OK', select 'System' > 'Mount Without Pre-Boot Authentication', enter your pre-boot authentication password and click 'OK'. The partition will be mounted as a regular VeraCrypt volume (data will be on-the-fly decrypted/encrypted in RAM on access, as usual).\n\n\n - Note that even if you lose your VeraCrypt Rescue Disk and an attacker finds it, he or she will NOT be able to decrypt the system partition or drive without the correct password. - \n\nI M P O R T A N T -- PLEASE PRINT THIS TEXT IF POSSIBLE (click 'Print' below).\n\n\nNote: This text will be automatically displayed each time you start the hidden system until you start creating the decoy system.\n\n\n - How to Create Decoy System Safely and Securely\n----------------------------------------------------------------------------\n\nIn order to achieve plausible deniability, you need to create the decoy operating system now. To do so, follow these steps:\n\n - 1) For security reasons, shut down your computer and leave it powered off for at least several minutes (the longer, the better). This is required to clear the memory, which contains sensitive data. Then turn on the computer but do not boot the hidden system.\n\n - 2) Install Windows on the partition whose content has been erased (i.e. on the partition where the original system, of which the hidden system is a clone, was installed).\n\nIMPORTANT: WHEN YOU START INSTALLING THE DECOY SYSTEM, THE HIDDEN SYSTEM WILL *NOT* BE POSSIBLE TO BOOT (because the VeraCrypt Boot Loader will be erased by the Windows system installer). THIS IS NORMAL AND EXPECTED. PLEASE DO NOT PANIC. YOU WILL BE ABLE TO BOOT THE HIDDEN SYSTEM AGAIN AS SOON AS YOU START ENCRYPTING THE DECOY SYSTEM (because VeraCrypt will then automatically install the VeraCrypt Boot Loader on the system drive).\n\nImportant: The size of the decoy system partition must remain the same as the size of the hidden volume (this condition is now met). Moreover, you must not create any partition between the decoy system partition and the partition where the hidden system resides.\n\n - 3) Boot the decoy system (which you installed in step 2 and install VeraCrypt on it).\n\nKeep in mind that the decoy system must never contain any sensitive data.\n\n - 4) On the decoy system, run VeraCrypt and select 'System' > 'Encrypt System Partition/Drive'. The VeraCrypt Volume Creation Wizard window should appear.\n\nThe following steps apply to the VeraCrypt Volume Creation Wizard.\n\n - 5) In the VeraCrypt Volume Creation Wizard, do NOT select the 'Hidden' option. Leave the 'Normal' option selected and click 'Next'.\n\n - 6) Select the option 'Encrypt the Windows system partition' and then click 'Next'.\n\n - 7) If there are only the hidden system and the decoy system installed on the computer, select the option 'Single-boot' (if there are more than these two systems installed on the computer, select 'Multi-boot'). Then click 'Next'.\n\n - 8) IMPORTANT: In this step, FOR THE DECOY SYSTEM, YOU MUST SELECT THE SAME ENCRYPTION ALGORITHM AND HASH ALGORITHM THAT YOU SELECTED FOR THE HIDDEN SYSTEM! OTHERWISE, THE HIDDEN SYSTEM WILL BE INACCESSIBLE! In other words, the decoy system must be encrypted with the same encryption algorithm as the hidden system. Note: The reason is that the decoy system and the hidden system will share a single boot loader, which supports only a single algorithm, selected by the user (for each algorithm, there is a special version of the VeraCrypt Boot Loader).\n\n - 9) In this step, choose a password for the decoy operating system. This will be the password that you will be able to reveal to an adversary if you are asked or forced to disclose your pre-boot authentication password (the other password you can reveal is the one for the outer volume). The existence of the third password (i.e. of the pre-boot authentication password for the hidden operating system) will remain secret.\n\nImportant: The password you choose for the decoy system must be substantially different from the one you chose for the hidden volume (i.e. for the hidden operating system).\n\n - 10) Follow the remaining instructions in the wizard so as to encrypt the decoy operating system.\n\n\n\n - After Decoy System Is Created\n------------------------------------------------\n\nAfter you encrypt the decoy system, the whole process of creation of the hidden operating system will be completed and you will be able to use these three passwords:\n\n1) Pre-boot authentication password for the hidden operating system.\n\n2) Pre-boot authentication password for the decoy operating system.\n\n3) Password for the outer volume.\n\n - If you want to start the hidden operating system, you will just need to enter the password for the hidden operating system in the VeraCrypt Boot Loader screen (which appears after you turn on or restart your computer).\n\nIf you want to start the decoy operating system, you will just need to enter the password for the decoy operating system in the VeraCrypt Boot Loader screen.\n\nThe password for the decoy system can be disclosed to anyone forcing you to reveal your pre-boot authentication password. The existence of the hidden volume (and of the hidden operating system) will remain secret.\n\n - The third password (for the outer volume) can be disclosed to anyone forcing you to reveal the password for the first partition behind the system partition, where both the outer volume and the hidden volume (containing the hidden operating system) reside. The existence of the hidden volume (and of the hidden operating system) will remain secret.\n\n\n - If you revealed the password for the decoy system to an adversary and he asked you why the free space of the (decoy) system partition contains random data, you could answer, for example: "The partition previously contained a system encrypted by VeraCrypt, but I forgot the pre-boot authentication password (or the system was damaged and stopped booting), so I had to reinstall Windows and encrypt the partition again."\n\n\n - If all the instructions are followed and if the precautions and requirements listed in the section "Security Requirements and Precautions Pertaining to Hidden Volumes" in the VeraCrypt User's Guide are followed, it should be impossible to prove that the hidden volume and hidden operating system exist, even when the outer volume is mounted or when the decoy operating system is decrypted or started.\n\nIf you save a copy of this text or print it (strongly recommended, unless your printer stores copies of documents it prints on its internal drive), you should destroy any copies of it after you have created the decoy system and after you have understood all the information contained in the text (otherwise, if such a copy was found, it might indicate that there is a hidden operating system on this computer).\n\n - WARNING: IF YOU DO NOT PROTECT THE HIDDEN VOLUME (for information on how to do so, refer to the section "Protection of Hidden Volumes Against Damage" in the VeraCrypt User's Guide), DO NOT WRITE TO THE OUTER VOLUME (note that the decoy operating system is NOT installed in the outer volume). OTHERWISE, YOU MAY OVERWRITE AND DAMAGE THE HIDDEN VOLUME (AND THE HIDDEN OPERATING SYSTEM WITHIN IT)! - Operating System Cloning - In the next steps, VeraCrypt will create the hidden operating system by copying the content of the system partition to the hidden volume (data being copied will be encrypted on the fly with an encryption key different from the one that will be used for the decoy operating system).\n\nPlease note that the process will be performed in the pre-boot environment (before Windows starts) and it may take a long time to complete; several hours or even several days (depending on the size of the system partition and on the performance of your computer).\n\nYou will be able to interrupt the process, shut down your computer, start the operating system and then resume the process. However, if you interrupt it, the entire process of copying the system will have to start from the beginning (because the content of the system partition must not change during cloning). - Do you want to cancel the entire process of creation of the hidden operating system?\n\nNote: You will NOT be able to resume the process if you cancel it now. - Do you want to cancel the system encryption pretest? - The VeraCrypt system encryption pretest failed. Do you want to try again?\n\nIf you select 'No', the pre-boot authentication component will be uninstalled.\n\nNotes:\n\n- If the VeraCrypt Boot Loader did not ask you to enter the password before Windows started, it is possible that your operating system does not boot from the drive on which it is installed. This is not supported.\n\n- If you used an encryption algorithm other than AES and the pretest failed (and you entered the password), it may have been caused by an inappropriately designed driver. Select 'No', and try encrypting the system partition/drive again, but use the AES encryption algorithm (which has the lowest memory requirements).\n\n- For more possible causes and solutions, see: https://veracrypt.codeplex.com/wikipage?title=Troubleshooting - The system partition/drive does not appear to be encrypted (neither partially nor fully). - Your system partition/drive is encrypted (partially or fully).\n\nPlease decrypt your system partition/drive entirely before proceeding. To do so, select 'System' > 'Permanently Decrypt System Partition/Drive' from the menu bar of the main VeraCrypt window. - When the system partition/drive is encrypted (partially or fully), you cannot downgrade VeraCrypt (but you can upgrade it or reinstall the same version). - Your system partition/drive is currently being encrypted, decrypted, or otherwise modified. Please interrupt the encryption/decryption/modification process (or wait until it is complete) before proceeding. - An instance of the VeraCrypt Volume Creation Wizard is currently running on this system and performing or preparing encryption/decryption of the system partition/drive. Before you proceed, please wait for it to finish or close it. If you cannot close it, please restart your computer before proceeding. - The process of encryption or decryption of the system partition/drive has not been completed. Please wait until it is complete before proceeding. - Error: The process of encryption of the partition/drive has not been completed. It must be completed first. - Error: The process of encryption or decryption of the partition/volume has not been completed. It must be completed first.\n\nNote: To resume the process, select 'Volumes' > 'Resume Interrupted Process' from the menu bar of the main VeraCrypt window. - The password is correct, VeraCrypt has successfully decrypted the volume header and detected that this volume is a hidden system volume. However, you cannot modify the header of a hidden system volume this way.\n\nTo change the password for a hidden system volume, boot the operating system residing in the hidden volume, and then select 'System' > 'Change Password' from the menu bar of the main VeraCrypt window.\n\nTo set the header key derivation algorithm, boot the hidden operating system and then select 'System' > 'Set Header Key Derivation Algorithm'. - VeraCrypt does not support in-place decryption of a hidden system partition.\n\nNote: If you want to decrypt the decoy system partition, boot the decoy system, and then select 'System' > 'Permanently Decrypt System Partition/Drive' from the menu bar of the main VeraCrypt window. - Error: Incorrect/invalid parameter. - You have selected a partition or a device but the wizard mode you selected is suitable only for file containers.\n\nDo you want to change the wizard mode? - Do you want to create a VeraCrypt file container instead? - You have selected the system partition/drive (or the boot partition), but the wizard mode you selected is suitable only for non-system partitions/drives.\n\nDo you want to set up pre-boot authentication (which means that you will need to enter your password each time before Windows boots/starts) and encrypt the system partition/drive? - Are you sure you want to permanently decrypt the system partition/drive? - CAUTION: If you permanently decrypt the system partition/drive, unencrypted data will be written to it.\n\nAre you really sure you want to permanently decrypt the system partition/drive? - Are you sure you want to permanently decrypt the following volume? - CAUTION: If you permanently decrypt the VeraCrypt volume, unencrypted data will be written to the disk.\n\nAre you really sure you want to permanently decrypt the selected volume? - Warning: If you use a cascade of ciphers for system encryption, you may encounter the following issues:\n\n1) The VeraCrypt Boot Loader is larger than normal and, therefore, there is not enough space in the first drive track for a backup of the VeraCrypt Boot Loader. Hence, whenever it gets damaged (which often happens, for example, during inappropriately designed anti-piracy activation procedures of certain programs), you will need to use the VeraCrypt Rescue Disk to boot or to repair the VeraCrypt Boot Loader.\n\n2) On some computers, resuming from hibernation takes longer.\n\nThese potential issues can be prevented by choosing a non-cascade encryption algorithm (e.g. AES).\n\nAre you sure you want to use a cascade of ciphers? - If you encounter any of the previously described problems, decrypt the partition/drive (if it is encrypted) and then try encrypting it again using a non-cascade encryption algorithm (e.g. AES). - WARNING: For safety and security reasons, you should update VeraCrypt on the decoy operating system before you update it on the hidden operating system.\n\nTo do so, boot the decoy system and run the VeraCrypt installer from within it. Then boot the hidden system and run the installer from within it as well.\n\nNote: The decoy system and the hidden system share a single boot loader. If you upgraded VeraCrypt only on the hidden system (but not on the decoy system), the decoy system would contain a VeraCrypt driver and VeraCrypt applications whose version numbers are different from the version number of the VeraCrypt Boot Loader. Such a discrepancy might indicate that there is a hidden operating system on this computer.\n\n\nDo you want to continue? - The version number of the VeraCrypt Boot Loader that booted this operating system is different from the version number of the VeraCrypt driver (and of the VeraCrypt applications) installed on this system.\n\nYou should run the VeraCrypt installer (whose version number is the same as the one of the VeraCrypt Boot Loader) to update VeraCrypt on this operating system. - The version number of the VeraCrypt Boot Loader that booted this operating system is different from the version number of the VeraCrypt driver (and of the VeraCrypt applications) installed on this system. Note that older versions may contain bugs fixed in later versions.\n\nIf you did not boot from the VeraCrypt Rescue Disk, you should reinstall VeraCrypt or upgrade it to the latest stable version (the boot loader will be updated too).\n\nIf you booted from the VeraCrypt Rescue Disk, you should update it ('System' > 'Create Rescue Disk'). - The VeraCrypt Boot Loader has been upgraded.\n\nIt is strongly recommended that you create a new VeraCrypt Rescue Disk (which will contain the new version of the VeraCrypt Boot Loader) by selecting 'System' > 'Create Rescue Disk' after you restart your computer. - The VeraCrypt Boot Loader has been upgraded.\n\nIt is strongly recommended that you boot the decoy operating system and then create a new VeraCrypt Rescue Disk (which will contain the new version of the VeraCrypt Boot Loader) by selecting 'System' > 'Create Rescue Disk'. - Failed to upgrade the VeraCrypt Boot Loader. - VeraCrypt failed to detect the real size of the system drive and, therefore, the size reported by the operating system (which may be smaller than the real size) will be used. Also note that this is not a bug in VeraCrypt. - WARNING: It appears that VeraCrypt has already tried to detect hidden sectors on this system drive. If you encountered any problems during the previous detection process, you can avoid the problems by skipping the detection of hidden sectors now. Note that if you do so, VeraCrypt will use the size reported by the operating system (which may be smaller than the real size of the drive).\n\nNote that this issue is not caused by a bug in VeraCrypt. - Skip detection of hidden sectors (use the size reported by the operating system) - Try to detect hidden sectors again - Error: Content of one or more sectors on the disk cannot be read (probably due to a physical defect).\n\nThe process of in-place encryption can continue only when the sectors have been made readable again. VeraCrypt can attempt to make these sectors readable by writing zeros to the sectors (subsequently such all-zero blocks would be encrypted). However, note that any data stored in the unreadable sectors will be lost. If you want to avoid that, you can attempt to recover portions of the corrupted data using appropriate third-party tools.\n\nNote: In case of physically damaged sectors (as opposed to mere data corruption and checksum errors) most types of storage devices internally reallocate the sectors when data is attempted to be written to them (so the existing data in the damaged sectors may remain unencrypted on the drive).\n\nDo you want VeraCrypt to write zeroes to unreadable sectors? - Error: Content of one or more sectors on the disk cannot be read (probably due to a physical defect).\n\nTo be able to proceed with decryption, VeraCrypt will have to discard the content of the unreadable sectors (the content will be replaced with pseudorandom data). Please note that, before proceeding, you can attempt to recover portions of any corrupted data using appropriate third-party tools.\n\nDo you want VeraCrypt to discard data in the unreadable sectors now? - Note: VeraCrypt has replaced the content of %I64d unreadable sectors (%s) with encrypted all-zero plaintext blocks. - Note: VeraCrypt has replaced the content of %I64d unreadable sectors (%s) with pseudorandom data. - Enter password/PIN for token '%s': - In order to allow VeraCrypt to access a security token or smart card, you need to install a PKCS #11 software library for the token or smart card first. Such a library may be supplied with the device or it may be available for download from the website of the vendor or other third parties.\n\nAfter you install the library, you can either select it manually by clicking 'Select Library' or you can let VeraCrypt find and select it automatically by clicking 'Auto-Detect Library' (only the Windows system directory will be searched). - Note: For the filename and location of the PKCS #11 library installed for your security token or smart card, please refer to the documentation supplied with the token, card, or third-party software.\n\nClick 'OK' to select the path and filename. - In order to allow VeraCrypt to access a security token or smart card, you need to select a PKCS #11 software library for the token/card first. To do so, select 'Settings' > 'Security Tokens'. - Failed to initialize PKCS #11 security token library.\n\nPlease make sure the specified path and filename refer to a valid PKCS #11 library. To specify a PKCS #11 library path and filename, select 'Settings' > 'Security Tokens'. - No PKCS #11 library has been found in the Windows system directory.\n\nPlease make sure that a PKCS #11 library for your security token (or for your smart card) is installed (such a library may be supplied with the token/card or it may be available for download from the website of the vendor or other third parties). If it is installed in a directory other than the Windows system directory, click 'Select Library' to locate the library (e.g. in the folder where the software for the token/card is installed). - No security token found.\n\nPlease make sure your security token is connected to your computer and the correct device driver for your token is installed. - Security token keyfile not found. - A security token keyfile with the same name already exists. - Do you want to delete the selected files? - Security token keyfile path is invalid. - Security token error - Password for security token is incorrect. - The security token does not have enough memory/space to perform the requested operation.\n\nIf you are attempting to import a keyfile, you should select a smaller file or use a keyfile generated by VeraCrypt (select 'Tools' > 'Keyfile Generator'). - All open security token sessions have been closed. - Select Security Token Keyfiles - Slot - Token name - File name - IMPORTANT: Please note that pre-boot authentication passwords are always typed using the standard US keyboard layout. Therefore, a volume that uses a password typed using any other keyboard layout may be impossible to mount using a pre-boot authentication password (note that this is not a bug in VeraCrypt). To allow such a volume to be mounted using a pre-boot authentication password, follow these steps:\n\n1) Click 'Select File' or 'Select Device' and select the volume.\n2) Select 'Volumes' > 'Change Volume Password'.\n3) Enter the current password for the volume.\n4) Change the keyboard layout to English (US) by clicking the Language bar icon in the Windows taskbar and selecting 'EN English (United States)'.\n5) In VeraCrypt, in the field for the new password, type the pre-boot authentication password.\n6) Confirm the new password by retyping it in the confirmation field and click 'OK'.\nWARNING: Please keep in mind that if you follow these steps, the volume password will always have to be typed using the US keyboard layout (which is automatically ensured only in the pre-boot environment). - System favorite volumes will be mounted using the pre-boot authentication password. If any system favorite volume uses a different password, it will not be mounted. - Please note that if you need to prevent normal VeraCrypt volume actions (such as 'Dismount All', auto-dismount, etc.) from affecting system favorite volumes, you should enable the option 'Allow only administrators to view and dismount system favorite volumes in VeraCrypt'. In addition, when VeraCrypt is run without administrator privileges (the default on Windows Vista and later), system favorite volumes will not be displayed in the drive letter list in the main VeraCrypt application window. - IMPORTANT: Please keep in mind that if this option is enabled and VeraCrypt does not have administrator privileges, mounted system favorite volumes are NOT displayed in the VeraCrypt application window and they cannot be dismounted. Therefore, if you need e.g. to dismount a system favorite volume, please right-click the VeraCrypt icon (in the Start menu) and select 'Run as administrator' first. The same limitation applies to the 'Dismount All' function, 'Auto-Dismount' functions, 'Dismount All' hot keys, etc. - Note that this setting takes effect only after the operating system is restarted. - Error while parsing command line. - Rescue Disk - Select &File and Mount... - Select &Device and Mount... - Allow only administrators to view and dismount system favorite volumes in VeraCrypt - Mount system favorite volumes when Windows starts (in the initial phase of the startup procedure) - Warning: The filesystem on the volume mounted as '%s' was not cleanly dismounted and thus may contain errors. Using a corrupted filesystem can cause data loss or data corruption.\n\nNote: Before you physically remove or switch off a device (such as a USB flash drive or an external hard drive) where a mounted VeraCrypt volume resides, you should always dismount the VeraCrypt volume in VeraCrypt first.\n\n\nDo you want Windows to attempt to detect and fix errors (if any) on the filesystem? - Warning: One or more system favorite volumes were not cleanly dismounted and thus may contain filesystem errors. Please see the system event log for further details.\n\nUsing a corrupted filesystem can cause data loss or data corruption. You should check the affected system favorite volume(s) for errors (right-click each of them in VeraCrypt and select 'Repair Filesystem'). - Warning: Repairing a damaged filesystem using the Microsoft 'chkdsk' tool might cause loss of files in damaged areas. Therefore, it is recommended that you first back up the files stored on the VeraCrypt volume to another, healthy, VeraCrypt volume.\n\nDo you want to repair the filesystem now? - Volume '%s' has been mounted as read-only because write access was denied.\n\nPlease make sure the security permissions of the file container allow you to write to it (right-click the container and select Properties > Security).\n\nNote that, due to a Windows issue, you may see this warning even after setting the appropriate security permissions. This is not caused by a bug in VeraCrypt. A possible solution is to move your container to, e.g., your 'Documents' folder.\n\nIf you intend to keep your volume read-only, set the read-only attribute of the container (right-click the container and select Properties > Read-only), which will suppress this warning. - Volume '%s' had to be mounted as read-only because write access was denied.\n\nPlease make sure no other application (e.g. antivirus software) is accessing the partition/device on which the volume is hosted. - Volume '%s' has been mounted as read-only because the operating system reported the host device to be write-protected.\n\nPlease note that some custom chipset drivers have been reported to cause writable media to falsely appear write-protected. This problem is not caused by VeraCrypt. It may be solved by updating or uninstalling any custom (non-Microsoft) chipset drivers that are currently installed on this system. - Note that the Hyper-Threading technology provides multiple logical cores per a single physical core. When Hyper Threading is enabled, the number selected above represents the number of logical processors/cores. - %d threads - Note that hardware-accelerated AES is disabled, which will affect benchmark results (worse performance).\n\nTo enable hardware acceleration, select 'Settings' > 'Performance' and enable the corresponding option. - Note that the number of threads is currently limited, which will affect benchmark results (worse performance).\n\nTo utilize the full potential of the processor(s), select 'Settings' > 'Performance' and disable the corresponding option. - Do you want VeraCrypt to attempt to disable write protection of the partition/drive? - WARNING: This setting may degrade performance.\n\nAre you sure you want to use this setting? - Warning: VeraCrypt volume auto-dismounted - Before you physically remove or turn off a device containing a mounted volume, you should always dismount the volume in VeraCrypt first.\n\nUnexpected spontaneous dismount is usually caused by an intermittently failing cable, drive (enclosure), etc. - This volume was created with TrueCrypt %x.%x but VeraCrypt supports only TrueCrypt volumes created with TrueCrypt 6.x/7.x series - Test - Keyfile - Backspace - Tab - Clear - Enter - Pause - Caps Lock - Spacebar - Page Up - Page Down - End - Home - Left Arrow - Up Arrow - Right Arrow - Down Arrow - Select Key - Print Key - Execute Key - Print Screen - Insert - Delete - Applications Key - Sleep - Num Lock - Scroll Lock - Browser Back - Browser Forward - Browser Refresh - Browser Stop - Browser Search - Browser Favorites - Browser Home - Mute - Volume Down - Volume Up - Next Track - Previous Track - Stop Media - Play/Pause Media - Start Mail Key - Select Media Key - Application 1 - Application 2 - Attn - CrSel - ExSel - Play - Zoom - NumPad - Shift - Control - Alt - Win - B - KB - MB - GB - TB - PB - B/s - KB/s - MB/s - GB/s - TB/s - PB/s - … - Include &PIM when caching pre-boot authentication password - Include PIM when caching a password - Make disconnected network drives available for mounting - The entered password is too long: its UTF-8 representation exceeds 64 bytes. - The entered password contains Unicode characters that couldn't be converted to UTF-8 representation. - Error: Failed to load a system library. - The volume file size specified in the command line is incompatible with selected exFAT filesystem. - Randomness Collected From Mouse Movements - Volume ID: - Volume ID - Use Volume ID to mount favorite - The Volume ID value is invalid - No Volume with the specified ID was found on the system - Copy Value to Clipboard... - Do not request PIM in the pre-boot authentication screen (PIM value is stored unencrypted on disk) - WARNING: Please keep in mind that if you enable this option, the PIM value will be stored unencrypted on the disk.\n\nAre you sure you want to enable this option? - Personal Iterations Multiplier (PIM) maximum value is 2147468. - Skip Rescue Disk verification - Don't show wait message dialog when performing operations - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + Cancel + Install &for all users + Bro&wse... + Add VeraCrypt icon to &desktop + Donate now... + Associate the .hc file &extension with VeraCrypt + &Open the destination location when finished + Add VeraCrypt to &Start menu + Create System &Restore point + &Uninstall + &Extract + &Install + VeraCrypt Setup Wizard + Uninstall VeraCrypt + &Help + Please select or type the location where you want to place the extracted files: + Please select or type the location where you want to install the VeraCrypt program files. If the specified folder does not exist, it will be automatically created. + Click Uninstall to remove VeraCrypt from this system. + Abort + &Benchmark + &Test + Create encrypted volume and format it + Encrypt partition in place + Display generated keys (their portions) + Display pool content + Download CD/DVD recording software + Create an encrypted file container + &GB + &TB + More information + Hi&dden VeraCrypt volume + More information about hidden volumes + Direct mode + Normal mode + &KB + U&se keyfiles + Try first to mount with an empty password + Random size ( 64 <-> 1048576 ) + &Keyfiles... + Information on hash algorithms + More information + Information on PIM + &MB + More information + More information about system encryption + More information + Multi-Boot + Encrypt a non-system partition/drive + &Never save history + Open Outer Volume + &Pause + Use P&IM + Use PIM + Quick Format + &Display password + &Display password + &Display PIM + Single-boot + Standard VeraCrypt volume + Hi&dden + Normal + Encrypt the system partition or entire system drive + Encrypt the Windows system partition + Encrypt the whole drive + VeraCrypt Volume Creation Wizard + Cluster + IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the encryption keys. Then click Next to continue. + &Confirm: + Done + Drive letter: + Encryption Algorithm + Filesystem + Creates a virtual encrypted disk within a file. Recommended for inexperienced users. + Options + Hash Algorithm + Header Key: + Left + Master Key: + Select this option if there are two or more operating systems installed on this computer.\n\nFor example:\n- Windows XP and Windows XP\n- Windows XP and Windows Vista\n- Windows and Mac OS X\n- Windows and Linux\n- Windows, Linux and Mac OS X + Encrypts a non-system partition on any internal or external drive (e.g. a flash drive). Optionally, creates a hidden volume. + Current pool content (partial) + Pass + Password: + Volume PIM: + Volume PIM: + Progress: + Random Pool: + Select this option if there is only one operating system installed on this computer (even if it has multiple users). + Speed + Status + The keys, salt, and other data have been successfully generated. If you want to generate new keys, click Back and then Next. Otherwise, click Next to continue. + Encrypts the partition/drive where Windows is installed. Anyone who wants to gain access and use the system, read and write files, etc., will need to enter the correct password each time before Windows boots. Optionally, creates a hidden system. + Select this option to encrypt the partition where the currently running Windows operating system is installed. + Volume Label in Windows: + Wipe mode: + Close + Allow pre-boot &authentication to be bypassed by pressing the Esc key (enables boot manager) + Do nothing + &Auto-mount VeraCrypt volume (specified below) + &Start VeraCrypt + Auto-&Detect Library + &Cache pre-boot authentication password in driver memory (for mounting of non-system volumes) + Browse... + Browse... + Cache passwords and keyfil&es in memory + Exit when there are no mounted volumes + &Close token session (log out) after a volume is successfully mounted + Include VeraCrypt Volume Expander + Include VeraCrypt Volume Creation Wizard + Create + &Create Volume + Do not &show any texts in the pre-boot authentication screen (except the below custom message) + Disable "Evil Maid" attack detection + Accelerate AES encryption/decryption by using the AES instructions of the processor (if available) + Use keyfiles + Use keyfiles + E&xit + Help on favorite volumes + Do not mount selected volume when 'Mount Favorite Volumes' &hot key is pressed + Mount selected volume when its host device gets &connected + Mount selected volume upon log&on + Mount selected volume as read-o&nly + Mount selected volume as remo&vable medium + Move &Down + Move &Up + Open &Explorer window for selected volume when successfully mounted + &Remove + Use favorite label as Explorer drive label + Global Settings + Display balloon tooltip after successful hot-key dismount + Play system notification sound after successful hot-key dismount + Alt + Ctrl + Shift + Win + Assign + Remove + Keyfiles... + Do not use the following number of processors for encryption/decryption: + More information + More information + More Settings... + &Auto-Mount Devices + Mount Opti&ons... + Mount volume as read-&only + Keyfiles... + (Empty or 0 for default iterations) + (Empty or 0 for default iterations) + Enabled + Cache passwords in driver memory + Auto-dismount volume after no data has been read/written to it for + User logs off + User session locked + Entering power saving mode + Screen saver is launched + Force auto-dismount even if volume contains open files or directories + Mount all device-hosted VeraCrypt volumes + Start VeraCrypt Background Task + Mount volumes as read-only + Mount volumes as removable media + Open Explorer window for successfully mounted volume + Temporary Cache password during "Mount Favorite Volumes" operations + Use a different taskbar icon when there are mounted volumes + Wipe cached passwords on auto-dismount + Wipe cached passwords on exit + Preserve modification timestamp of file containers + Reset + Select D&evice... + Select &File... + Select &Library... + Display password + Display password + Open &Explorer window for mounted volume + &Cache password in driver memory + TrueCrypt Mode + Di&smount All + &Volume Properties... + Volume &Tools... + &Wipe Cache + VeraCrypt - Mount Parameters + VeraCrypt - Favorite Volumes + VeraCrypt - System-Wide Hot Keys + VeraCrypt + Change Password or Keyfiles + Enter VeraCrypt Volume Password + VeraCrypt - Performance and Driver Options + VeraCrypt - Preferences + VeraCrypt - System Encryption Settings + VeraCrypt - Security Token Preferences + VeraCrypt Traveler Disk Setup + VeraCrypt Volume Properties + About + Add/Remove Keyfiles to/from Volume... + Add Mounted Volume to Favorites... + Add Mounted Volume to System Favorites... + Analyze a System Crash... + Backup Volume Header... + Benchmark... + Set Header Key Derivation Algorithm... + Change Volume Password... + Set Header Key Derivation Algorithm... + Change Password... + Clear Volume History + Close All Security Token Sessions + Contact + Create Hidden Operating System... + Create Rescue Disk... + Create New Volume... + Permanently Decrypt... + Default Keyfiles... + Default Mount Parameters... + Donate now... + Encrypt System Partition/Drive... + Frequently Asked Questions + User's Guide + &Homepage + Hot Keys... + Keyfile Generator + Language... + Legal Notices + Manage Security Token Keyfiles... + Auto-Mount All Device-Hosted Volumes + Mount Favorite Volumes + Mount Without Pre-Boot &Authentication... + Mount Volume + Mount Volume with Options + News + Online Help + Beginner's Tutorial + Organize Favorite Volumes... + Organize System Favorite Volumes... + Performance/Driver Configuration + Permanently Decrypt System Partition/Drive + Preferences... + Refresh Drive Letters + Remove All Keyfiles from Volume... + Restore Volume Header... + Resume Interrupted Process + Select Device... + Select File... + Resume Interrupted Process + System Encryption... + Properties... + Settings... + System Favorite Volumes... + Downloads + Test Vectors... + Security Tokens... + Traveler Disk Setup... + Dismount All Mounted Volumes + Dismount Volume + Verify Rescue Disk + Verify Rescue Disk ISO Image + Version History + Volume Expander + Volume Properties + Volume Creation Wizard + VeraCrypt Website + Wipe Cached Passwords + OK + Hardware Acceleration + Shortcut + AutoRun Configuration (autorun.inf) + Auto-Dismount + Dismount all when: + Boot Loader Screen Options + Confirm Password: + Current + Display this custom message in the pre-boot authentication screen (24 characters maximum): + Default Mount Options + Hot Key Options + Driver Configuration + Enable extended disk control codes support + Label of selected favorite volume: + File Settings + Key to assign: + Processor (CPU) in this computer supports hardware acceleration for AES: + Actions to perform upon logon to Windows + minutes + Mount volume as drive letter: + Mount Settings + New + Password: + Thread-Based Parallelization + PKCS #11 Library Path + PKCS-5 PRF: + PKCS-5 PRF: + Password Cache + Security Options + VeraCrypt Background Task + VeraCrypt volume to mount (relative to traveler disk root): + Upon insertion of traveler disk: + Create traveler disk files at (traveler disk root directory): + Volume + Windows + Add &Path... + &Auto-Test All + &Continue + &Decrypt + &Delete + &Encrypt + &Export... + Generate and Save Keyfile... + &Generate Random Keyfile... + Download language pack + Hardware-accelerated AES: + &Import Keyfile to Token... + Add &Files... + U&se keyfiles + &Keyfiles... + &Remove + Remove &All + What is hidden volume protection? + More information on keyfiles + Mount volume as removable &medium + Mount partition &using system encryption without pre-boot authentication + Parallelization: + Benchmark + &Print + &Protect hidden volume against damage caused by writing to outer volume + &Reset + &Display password + Add &Token Files... + Use backup header embedded in &volume if available + XTS mode + About VeraCrypt + VeraCrypt - Encryption Algorithm Benchmark + VeraCrypt - Test Vectors + Command Line Help + VeraCrypt - Keyfiles + VeraCrypt - Keyfile Generator + VeraCrypt - Language + VeraCrypt - Mount Options + New Security Token Keyfile Properties + VeraCrypt - Random Pool Enrichment + Select a Partition or Device + VeraCrypt + Security Token Keyfiles + Security token password/PIN required + Active language pack + Speed is affected by CPU load and storage device characteristics.\n\nThese tests take place in RAM. + Buffer Size: + Cipher: + P&assword to hidden volume:\n(if empty, cache is used) + Hidden Volume Protection + Key size: + IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the keyfile. + WARNING: If you lose a keyfile or if any bit of its first 1024 kilobytes changes, it will be impossible to mount volumes that use the keyfile! + bits + Number of keyfiles: + Keyfiles size (in Bytes): + Keyfiles base name: + Translated by: + Plaintext size: + bits + Current Pool Content + Mixing PRF: + IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases security. When done, click 'Continue'. + Secondary key (hexadecimal) + Security token: + Sort Method: + Please wait. This process may take a long time... + Please wait...\nThis process may take a long time and VeraCrypt may seem unresponsive. + Block number: + Ciphertext (hexadecimal) + Data unit number (64-bit hexadecimal, data unit size is 512 bytes) + Key (hexadecimal) + Plaintext (hexadecimal) + Keyfile name: + XTS mode + S&ystem + &Volumes + Favor&ites + T&ools + Settin&gs + &Help + Home&page + + &About... + The read-only attribute on your old volume could not be changed. Please check the file access permissions. + Error: Access denied.\n\nThe partition you are trying to access is either 0 sectors long, or it is the boot device. + Administrator + In order to load the VeraCrypt driver, you need to be logged into an account with administrator privileges. + Please note that in order to encrypt, decrypt or format a partition/device you need to be logged into an account with administrator privileges.\n\nThis does not apply to file-hosted volumes. + In order to create a hidden volume you need to be logged into an account with administrator privileges.\n\nContinue? + Please note that in order to format the volume as NTFS/exFAT you need to be logged into an account with administrator privileges.\n\nWithout administrator privileges, you can format the volume as FAT. + FIPS-approved cipher (Rijndael, published in 1998) that may be used by U.S. government departments and agencies to protect classified information up to the Top Secret level. 256-bit key, 128-bit block, 14 rounds (AES-256). Mode of operation is XTS. + Volume is already mounted. + CAUTION: At least one encryption or hash algorithm failed the built-in automatic self-tests!\n\nVeraCrypt installation may be corrupted. + CAUTION: There is not enough data in the Random Number Generator pool to provide the requested amount of random data.\n\nYou should not proceed any further. Please select 'Report a Bug' from the Help menu, and report this error. + The drive is damaged (there is a physical defect on it) or a cable is damaged, or the memory is malfunctioning.\n\nPlease note that this is a problem with your hardware, not with VeraCrypt. Therefore, please do NOT report this as a bug/problem in VeraCrypt and please do NOT ask for help with this in the VeraCrypt Forums. Please contact your computer vendor's technical support team for assistance. Thank you.\n\nNote: If the error occurs repeatedly at the same place, it is very likely caused by a bad disk block, which should be possible to correct using third-party software (note that, in many cases, the 'chkdsk /r' command cannot correct it because it works only at the filesystem level; in some cases, the 'chkdsk' tool cannot even detect it). + If you are accessing a drive for removable media, please make sure that a medium is inserted in the drive. The drive/medium may also be damaged (there may be a physical defect on it) or a cable may be damaged/disconnected. + Your system appears to be using custom chipset drivers containing a bug that prevents encryption of the whole system drive.\n\nPlease try updating or uninstalling any custom (non-Microsoft) chipset drivers before proceeding. If it does not help, try encrypting the system partition only. + Invalid drive letter. + Invalid path. + Cancel + Cannot access device. Make sure the selected device exists and is not used by system. + Warning: Caps Lock is on. This may cause you to enter your password incorrectly. + Volume Type + It may happen that you are forced by somebody to reveal the password to an encrypted volume. There are many situations where you cannot refuse to reveal the password (for example, due to extortion). Using a so-called hidden volume allows you to solve such situations without revealing the password to your volume. + Select this option if you want to create a normal VeraCrypt volume. + Please note that if you wish an operating system to be installed in a hidden partition-hosted volume, then the entire system drive cannot be encrypted using a single key. + Outer Volume Encryption Options + Hidden Volume Encryption Options + Encryption Options + WARNING: Failed to clear the path of the last selected volume/keyfile (remembered by file selector)! + Error: The container has been compressed at the filesystem level. VeraCrypt does not support compressed containers (note that compression of encrypted data is ineffective and redundant).\n\nPlease disable compression for the container by following these steps:\n1) Right-click the container in Windows Explorer (not in VeraCrypt).\n2) Select 'Properties'.\n3) In the 'Properties' dialog box, click 'Advanced'.\n4) In the 'Advanced Attributes' dialog box, disable the option 'Compress contents to save disk space' and click 'OK'.\n5) In the 'Properties' dialog box, click 'OK'. + Failed to create volume %s + Size of %s is %.2f bytes + Size of %s is %.2f KB + Size of %s is %.2f MB + Size of %s is %.2f GB + Size of %s is %.2f TB + Size of %s is %.2f PB + WARNING: The device/partition is in use by the operating system or applications. Formatting the device/partition might cause data corruption and system instability.\n\nContinue? + Warning: The partition is in use by the operating system or applications. You should close any applications that might be using the partition (including antivirus software).\n\nContinue? + Error: The device/partition contains a file system that could not be dismounted. The file system may be in use by the operating system. Formatting the device/partition would very likely cause data corruption and system instability.\n\nTo solve this issue, we recommend that you first delete the partition and then recreate it without formatting. To do so, follow these steps:\n1) Right-click the 'Computer' (or 'My Computer') icon in the 'Start Menu' and select 'Manage'. The 'Computer Management' window should appear.\n2) In the 'Computer Management' window, select 'Storage' > 'Disk Management'.\n3) Right-click the partition you want to encrypt and select either 'Delete Partition', or 'Delete Volume', or 'Delete Logical Drive'.\n4) Click 'Yes'. If Windows asks you to restart the computer, do so. Then repeat the steps 1 and 2 and continue from the step 5.\n5) Right-click the unallocated/free space area and select either 'New Partition', or 'New Simple Volume', or 'New Logical Drive'.\n6) The 'New Partition Wizard' or 'New Simple Volume Wizard' window should appear now; follow its instructions. On the wizard page entitled 'Format Partition', select either 'Do not format this partition' or 'Do not format this volume'. In the same wizard, click 'Next' and then 'Finish'.\n7) Note that the device path you have selected in VeraCrypt may be wrong now. Therefore, exit the VeraCrypt Volume Creation Wizard (if it is still running) and then start it again.\n8) Try encrypting the device/partition again.\n\nIf VeraCrypt repeatedly fails to encrypt the device/partition, you may want to consider creating a file container instead. + Error: The filesystem could not be locked and/or dismounted. It may be in use by the operating system or applications (for example, antivirus software). Encrypting the partition might cause data corruption and system instability.\n\nPlease close any applications that might be using the filesystem (including antivirus software) and try again. If it does not help, please follow the below steps. + WARNING: Some of the mounted devices/partitions were already in use!\n\nIgnoring this can cause undesired results including system instability.\n\nWe strongly recommend that you close any application that might be using the devices/partitions. + The selected device contains partitions.\n\nFormatting the device might cause system instability and/or data corruption. Please either select a partition on the device, or remove all partitions on the device to enable VeraCrypt to format it safely. + The selected non-system device contains partitions.\n\nEncrypted device-hosted VeraCrypt volumes can be created within devices that do not contain any partitions (including hard disks and solid-state drives). A device that contains partitions can be entirely encrypted in place (using a single master key) only if it is the drive where Windows is installed and from which it boots.\n\nIf you want to encrypt the selected non-system device using a single master key, you will need to remove all partitions on the device first to enable VeraCrypt to format it safely (formatting a device that contains partitions might cause system instability and/or data corruption). Alternatively, you can encrypt each partition on the drive individually (each partition will be encrypted using a different master key).\n\nNote: If you want to remove all partitions from a GPT disk, you may need to convert it to a MBR disk (using e.g. the Computer Management tool) in order to remove hidden partitions. + Warning: If you encrypt the entire device (as opposed to encrypting only a partition on it), operating systems will consider the device as new, empty, and unformatted (as it will contain no partition table) and may spontaneously initialize the device (or ask you if you want to do so), which may damage the volume. Furthermore, it will not be possible to consistently mount the volume as favorite (e.g. when the drive number changes) or to assign a favorite-volume label to it.\n\nTo avoid that you may want to consider creating a partition on the device and encrypting the partition instead.\n\nAre you sure want to encrypt the entire device? + IMPORTANT: Please keep in mind that this volume can NOT be mounted/accessed using the drive letter %c:, which is currently assigned to it!\n\nTo mount this volume, click 'Auto-Mount Devices' in the main VeraCrypt window (alternatively, in the main VeraCrypt window, click 'Select Device', then select this partition/device, and click 'Mount'). The volume will be mounted to a different drive letter, which you select from the list in the main VeraCrypt window.\n\nThe original drive letter %c: should be used only in case you need to remove encryption from the partition/device (e.g., if you no longer need encryption). In such a case, right-click the drive letter %c: in the 'Computer' (or 'My Computer') list and select 'Format'. Otherwise, the drive letter %c: should never be used (unless you remove it, as described e.g. in the VeraCrypt FAQ, and assign it to another partition/device). + In-place encryption of non-system volumes is not supported on the version of the operating system you are currently using (it is supported only on Windows Vista and later versions of Windows).\n\nThe reason is that this version of Windows does not support shrinking of a filesystem (the filesystem needs to be shrunk to make space for the volume header and backup header). + The selected partition does not appear to contain an NTFS filesystem. Only partitions that contain an NTFS filesystem can be encrypted in place.\n\nNote: The reason is that Windows does not support shrinking of other types of filesystems (the filesystem needs to be shrunk to make space for the volume header and backup header). + The selected partition does not appear to contain an NTFS filesystem. Only partitions that contain an NTFS filesystem can be encrypted in place.\n\nIf you want to create an encrypted VeraCrypt volume within this partition, choose the option "Create encrypted volume and format it" (instead of the option "Encrypt partition in place"). + Error: The partition is too small. VeraCrypt cannot encrypt it in place. + To encrypt the data on this partition, please follow these steps:\n\n1) Create a VeraCrypt volume on an empty partition/device and then mount it.\n\n2) Copy all files from the partition that you originally wanted to encrypt to the mounted VeraCrypt volume (that has been created and mounted in step 1). That way, you will create a VeraCrypt-encrypted backup of the data.\n\n3) Create a VeraCrypt volume on the partition that you originally wanted to encrypt and make sure that (in the VeraCrypt wizard) you choose the option "Create encrypted volume and format it" (instead of the option "Encrypt partition in place"). Note that all data stored on the partition will be erased. After the volume is created, mount it.\n\n4) Copy all files from the mounted backup VeraCrypt volume (created and mounted in step 1) to the mounted VeraCrypt volume that has been created (and mounted) in step 3.\n\nAfter you complete these steps, the data will be encrypted and, in addition, there will be an encrypted backup of the data. + VeraCrypt can in-place encrypt only a partition, a dynamic volume, or an entire system drive.\n\nIf you want to create an encrypted VeraCrypt volume within the selected non-system device, choose the option "Create encrypted volume and format it" (instead of the option "Encrypt partition in place"). + Error: VeraCrypt can in-place encrypt only a partition, a dynamic volume, or an entire system drive. Please make sure the specified path is valid. + Error: Cannot shrink the filesystem (the filesystem needs to be shrunk to make space for the volume header and backup header).\n\nPossible causes and solutions:\n\n- Not enough free space on the volume. Please make sure no other application is writing to the filesystem.\n\n- Corrupted file system. Try to check it and fix any errors (right-click the corresponding drive letter in the 'Computer' list, then select Properties > Tools > 'Check Now', make sure the option 'Automatically fix file system errors' is enabled and click Start).\n\nIf the above steps do not help, please follow the below steps. + Error: There is not enough free space on the volume and so the filesystem cannot be shrunk (the filesystem needs to be shrunk to make space for the volume header and backup header).\n\nPlease delete any redundant files and empty the Recycle Bin so as to free at least 256 KB of space and then try again. Note that due to a Windows issue, the amount of free space reported by the Windows Explorer may be incorrect until the operating system is restarted. If restarting the system does not help, the file system may be corrupted. Try to check it and fix any errors (right-click the corresponding drive letter in the 'Computer' list, then select Properties > Tools > 'Check Now', make sure the option 'Automatically fix file system errors' is enabled and click Start).\n\nIf the above steps do not help, please follow the below steps. + Free space on drive %s is %.2f bytes. + Free space on drive %s is %.2f KB + Free space on drive %s is %.2f MB + Free space on drive %s is %.2f GB + Free space on drive %s is %.2f TB + Free space on drive %s is %.2f PB + Could not get available drive letters. + Error: VeraCrypt driver not found.\n\nPlease copy the files 'veracrypt.sys' and 'veracrypt-x64.sys' to the directory where the main VeraCrypt application (VeraCrypt.exe) is located. + Error: An incompatible version of the VeraCrypt driver is currently running.\n\nIf you are trying to run VeraCrypt in portable mode (i.e. without installing it) and a different version of VeraCrypt is already installed, you must uninstall it first (or upgrade it using the VeraCrypt installer). To uninstall it, follow these steps: On Windows Vista or later, select 'Start Menu' > Computer > 'Uninstall or change a program' > VeraCrypt > Uninstall; on Windows XP, select 'Start Menu' > Settings > 'Control Panel' > 'Add Or Remove Programs' > VeraCrypt > Remove.\n\nSimilarly, if you are trying to run VeraCrypt in portable mode (i.e. without installing it) and a different version of VeraCrypt is already running in portable mode, you must restart the system first and then run only this new version. + Error: Cipher initialization failure. + Error: A weak or a potentially weak key has been detected. The key will be discarded. Please try again. + A critical error has occurred and VeraCrypt must be terminated. If this is caused by a bug in VeraCrypt, we would like to fix it. To help us, you can send us an automatically generated error report containing the following items:\n\n- Program version\n- Operating system version\n- Type of CPU\n- VeraCrypt component name\n- Checksum of VeraCrypt executable\n- Symbolic name of dialog window\n- Error category\n- Error address\n- VeraCrypt call stack\n\nIf you select 'Yes', the following URL (which contains the entire error report) will be opened in your default Internet browser.\n\n%hs\n\nDo you want to send us the above error report? + A critical error has occurred in your system, which requires VeraCrypt to be terminated.\n\nNote that this error has not been caused by VeraCrypt (so the VeraCrypt developers cannot fix it). Please, check your system for possible problems (e.g., system configuration, network connection, failing hardware components). + A critical error has occurred in your system, which requires VeraCrypt to be terminated.\n\nIf this problem persists, you may want to try disabling or uninstalling applications that could potentially be causing this issue, such as antivirus or Internet security software, system "enhancers", "optimizers" or "tweakers", etc. If it does not help, you may want to try reinstalling your operating system (this problem may also be caused by malware). + VeraCrypt Critical Error + VeraCrypt detected that the operating system recently crashed. There are many potential reasons why the system could have crashed (for example, a failing hardware component, a bug in a device driver, etc.)\n\nDo you want VeraCrypt to check whether a bug in VeraCrypt could have caused the system crash? + Do you want VeraCrypt to continue detecting system crashes? + VeraCrypt found no system crash minidump file. + Do you want to delete the Windows crash dump file to free up disk space? + In order to analyze the system crash, VeraCrypt needs to install Microsoft Debugging Tools for Windows first.\n\nAfter you click OK, the Windows installer will download the Microsoft Debugging Tools installation package (16 MB) from a Microsoft server and install it (the Windows installer will be forwarded to the Microsoft server URL from the veracrypt.org server, which ensures that this feature works even if Microsoft changes the location of the installation package). + After you click OK, VeraCrypt will analyze the system crash. This may take up to several minutes. + Please make sure the environment variable 'PATH' includes the path to 'kd.exe' (Kernel Debugger). + It appears that VeraCrypt most likely did not cause the system crash. There are many potential reasons why the system could have crashed (for example, a failing hardware component, a bug in a device driver, etc.) + Results of the analysis indicate that updating the following driver might solve this issue: + To help us determine whether there is a bug in VeraCrypt, you can send us an automatically generated error report containing the following items:\n- Program version\n- Operating system version\n- Type of CPU\n- Error category\n- Driver name and version\n- System call stack\n\nIf you select 'Yes', the following URL (which contains the entire error report) will be opened in your default Internet browser. + Do you want to send us the above error report? + &Encrypt + &Decrypt + &Permanently Decrypt + Exit + Please create a logical drive for this extended partition, and then try again. + A VeraCrypt volume can reside in a file (called VeraCrypt container), which can reside on a hard disk, on a USB flash drive, etc. A VeraCrypt container is just like any normal file (it can be, for example, moved or deleted as any normal file). Click 'Select File' to choose a filename for the container and to select the location where you wish the container to be created.\n\nWARNING: If you select an existing file, VeraCrypt will NOT encrypt it; the file will be deleted and replaced with the newly created VeraCrypt container. You will be able to encrypt existing files (later on) by moving them to the VeraCrypt container that you are about to create now. + Select the location of the outer volume to be created (within this volume the hidden volume will be created later on).\n\nA VeraCrypt volume can reside in a file (called VeraCrypt container), which can reside on a hard disk, on a USB flash drive, etc. A VeraCrypt container can be moved or deleted as any normal file. Click 'Select File' to choose a filename for the container and to select the location where you wish the container to be created. If you select an existing file, VeraCrypt will NOT encrypt it; it will be deleted and replaced with the newly created container. You will be able to encrypt existing files (later on) by moving them to the VeraCrypt container you are about to create now. + Encrypted device-hosted VeraCrypt volumes can be created within partitions on hard disks, solid-state drives, USB memory sticks, and on any other supported storage devices. Partitions can also be encrypted in place.\n\nIn addition, encrypted device-hosted VeraCrypt volumes can be created within devices that do not contain any partitions (including hard disks and solid-state drives).\n\nNote: A device that contains partitions can be entirely encrypted in place (using a single key) only if it is the drive where Windows is installed and from which it boots. + A device-hosted VeraCrypt volume can be created within a hard disk partition, solid-state drive, USB memory stick, and other storage devices.\n\nWARNING: Note that the partition/device will be formatted and all data currently stored on it will be lost. + \nSelect the location of the outer volume to be created (within this volume the hidden volume will be created later on).\n\nOuter volumes can be created within partitions on hard disks, solid-state drives, USB memory sticks, and on any other supported storage devices. Outer volumes can also be created within devices that do not contain any partitions (including hard disks and solid-state drives).\n\nWARNING: Note that the partition/device will be formatted and all data currently stored on it will be lost. + \nSelect the location of the VeraCrypt volume within which you wish to create a hidden volume. + WARNING: The host file/device is already in use!\n\nIgnoring this can cause undesired results including system instability. All applications that might be using the host file/device (for example, antivirus or backup applications) should be closed before mounting the volume.\n\nContinue mounting? + Error: Cannot mount volume. The host file/device is already in use. Attempt to mount without exclusive access failed as well. + The file could not be opened. + Volume Location + Large Files + Do you intend to store files larger than 4 GB in this VeraCrypt volume? + Depending on your choice above, VeraCrypt will choose a suitable default file system for the VeraCrypt volume (you will be able to select a file system in the next step). + As you are creating an outer volume, you should consider choosing 'No'. If you choose 'Yes', the default filesystem will be NTFS, which is not as suitable for outer volumes as FAT/exFAT (for example, the maximum possible size of the hidden volume will be significantly greater if the outer volume is formatted as FAT/exFAT). Normally, FAT is the default for both hidden and normal volumes (so FAT volumes are not suspicious). However, if the user indicates intent to store files larger than 4 GB (which the FAT file system does not allow), then FAT is not the default. + Are you sure you want to choose 'Yes'? + Volume Creation Mode + This is the fastest way to create a partition-hosted or device-hosted VeraCrypt volume (in-place encryption, which is the other option, is slower because content of each sector has to be first read, encrypted, and then written). Any data currently stored on the selected partition/device will be lost (the data will NOT be encrypted; it will be overwritten with random data). If you want to encrypt existing data on a partition, choose the other option. + The entire selected partition and all data stored on it will be encrypted in place. If the partition is empty, you should choose the other option (the volume will be created much faster). + Note: + &Resume + &Defer + &Start + &Continue + &Format + &Wipe + Abort format? + Show more information + Do not show this again + The content of the partition/device has been successfully erased. + The content of the partition where the original system (of which the hidden system is a clone) resided has been successfully erased. + Please make sure the version of Windows you are going to install (on the wiped partition) is the same as the version of Windows you are currently running. This is required due to the fact that both systems will share a common boot partition. + The system partition/drive has been successfully encrypted.\n\nNote: If there are non-system VeraCrypt volumes that you need to have mounted automatically every time Windows starts, you can set it up by mounting each of them and selecting 'Favorites' > 'Add Mounted Volume to System Favorites'). + The system partition/drive has been successfully decrypted. + \n\nThe VeraCrypt volume has been created and is ready for use. If you wish to create another VeraCrypt volume, click Next. Otherwise, click Exit. + \n\nThe hidden VeraCrypt volume has been successfully created (the hidden operating system will reside within this hidden volume).\n\nClick Next to continue. + Volume Fully Encrypted + Volume Fully Decrypted + IMPORTANT: TO MOUNT THIS NEWLY CREATED VERACRYPT VOLUME AND TO ACCESS DATA STORED IN IT, CLICK 'Auto-Mount Devices' IN THE MAIN VERACRYPT WINDOW. After you enter the correct password (and/or supply correct keyfiles), the volume will be mounted to the drive letter you select from the list in the main VeraCrypt window (and you will be able to access the encrypted data via the selected drive letter).\n\nPLEASE REMEMBER OR WRITE DOWN THE ABOVE STEPS. YOU MUST FOLLOW THEM WHENEVER YOU WANT TO MOUNT THE VOLUME AND ACCESS DATA STORED IN IT. Alternatively, in the main VeraCrypt window, click 'Select Device', then select this partition/volume, and click 'Mount'.\n\nThe partition/volume has been successfully encrypted (it contains a fully encrypted VeraCrypt volume now) and is ready for use. + The VeraCrypt volume has been successfully decrypted. + The VeraCrypt volume has been successfully decrypted.\n\nPlease select a drive letter that you wish to assign to the decrypted volume and then click Finish.\n\nIMPORTANT: Until a drive letter is assigned to the decrypted volume, you will not be able to access data stored on the volume. + Warning: To be able to access the decrypted data, a drive letter needs to be assigned to the decrypted volume. However, no drive letter is currently available.\n\nPlease vacate a drive letter (for example, by disconnecting a USB flash drive or external hard drive, etc.) and then click OK. + The VeraCrypt volume has been successfully created. + Volume Created + IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the encryption keys. Then click Format to create the volume. + Click Format to create the outer volume. For more information, please refer to the documentation. + Outer Volume Format + Hidden Volume Format + Volume Format + Adobe Reader (or a compatible tool) is necessary to view or print the VeraCrypt User's Guide. Adobe Reader (freeware) can be downloaded at: www.adobe.com\n\nDo you want to view the online documentation instead? + If you select this option, the wizard will first help you create a normal VeraCrypt volume and then a hidden VeraCrypt volume within it. Inexperienced users should always select this option. + If you select this option, you will create a hidden volume within an existing VeraCrypt volume. It will be assumed that you have already created a VeraCrypt volume that is suitable to host the hidden volume. + Volume Creation Mode + Hidden Volume Created + The hidden VeraCrypt volume has been successfully created and is ready for use. If all the instructions have been followed and if the precautions and requirements listed in the section "Security Requirements and Precautions Pertaining to Hidden Volumes" in the VeraCrypt User's Guide are followed, it should be impossible to prove that the hidden volume exists, even when the outer volume is mounted.\n\nWARNING: IF YOU DO NOT PROTECT THE HIDDEN VOLUME (FOR INFORMATION ON HOW TO DO SO, REFER TO THE SECTION "PROTECTION OF HIDDEN VOLUMES AGAINST DAMAGE" IN THE VERACRYPT USER'S GUIDE), DO NOT WRITE TO THE OUTER VOLUME. OTHERWISE, YOU MAY OVERWRITE AND DAMAGE THE HIDDEN VOLUME! + You have started the hidden operating system. As you may have noticed, the hidden operating system appears to be installed on the same partition as the original operating system. However, in reality, it is installed within the partition behind it (in the hidden volume). All read and write operations are being transparently redirected from the original system partition to the hidden volume.\n\nNeither the operating system nor applications will know that data written to and read from the system partition are actually written to and read from the partition behind it (from/to a hidden volume). Any such data is encrypted and decrypted on the fly as usual (with an encryption key different from the one that will be used for the decoy operating system).\n\n\nPlease click Next to continue. + The outer volume has been created and mounted as drive %hc:. To this outer volume you should now copy some sensitive-looking files that you actually do NOT want to hide. They will be there for anyone forcing you to disclose the password for the first partition behind the system partition, where both the outer volume and the hidden volume (containing the hidden operating system) will reside. You will be able to reveal the password for this outer volume, and the existence of the hidden volume (and of the hidden operating system) will remain secret.\n\nIMPORTANT: The files you copy to the outer volume should not occupy more than %s. Otherwise, there may not be enough free space on the outer volume for the hidden volume (and you will not be able to continue). After you finish copying, click Next (do not dismount the volume). + Outer volume has been successfully created and mounted as drive %hc:. To this volume you should now copy some sensitive-looking files that you actually do NOT want to hide. The files will be there for anyone forcing you to disclose your password. You will reveal only the password for this outer volume, not for the hidden one. The files that you really care about will be stored in the hidden volume, which will be created later on. When you finish copying, click Next. Do not dismount the volume.\n\nNote: After you click Next, cluster bitmap of the outer volume will be scanned to determine the size of uninterrupted area of free space whose end is aligned with the end of the volume. This area will accommodate the hidden volume, so it will limit its maximum possible size. Cluster bitmap scanning ensures that no data on the outer volume are overwritten by the hidden volume. + Outer Volume Contents + \n\nIn the next steps, you will set the options for the outer volume (within which the hidden volume will be created later on). + \n\nIn the next steps, you will create a so-called outer VeraCrypt volume within the first partition behind the system partition (as was explained in one of the previous steps). + Outer Volume + In the following steps, you will set the options and password for the hidden volume, which will contain the hidden operating system.\n\nRemark: The cluster bitmap of the outer volume has been scanned in order to determine the size of uninterrupted area of free space whose end is aligned with the end of the outer volume. This area will accommodate the hidden volume, so it limits its maximum possible size. The maximum possible size of the hidden volume has been determined and confirmed to be greater than the size of the system partition (which is required, because the entire content of the system partition will need to be copied to the hidden volume). This ensures that no data currently stored on the outer volume will be overwritten by data written to the area of the hidden volume. + IMPORTANT: Please remember the algorithms that you select in this step. You will have to select the same algorithms for the decoy system. Otherwise, the hidden system will be inaccessible! (The decoy system must be encrypted with the same encryption algorithm as the hidden system.)\n\nNote: The reason is that the decoy system and the hidden system will share a single boot loader, which supports only a single algorithm, selected by the user (for each algorithm, there is a special version of the VeraCrypt Boot Loader). + \n\nThe volume cluster bitmap has been scanned and the maximum possible size of the hidden volume has been determined. In the next steps you will set the options, the size, and the password for the hidden volume. + Hidden Volume + The hidden volume is now protected against damage until the outer volume is dismounted.\n\nWARNING: If any data is attempted to be saved to the hidden volume area, VeraCrypt will start write-protecting the entire volume (both the outer and the hidden part) until it is dismounted. This may cause filesystem corruption on the outer volume, which (if repeated) might adversely affect plausible deniability of the hidden volume. Therefore, you should make every effort to avoid writing to the hidden volume area. Any data being saved to the hidden volume area will not be saved and will be lost. Windows may report this as a write error ("Delayed Write Failed" or "The parameter is incorrect"). + Each of the hidden volumes within the newly mounted volumes is now protected against damage until dismounted.\n\nWARNING: If any data is attempted to be saved to protected hidden volume area of any of these volumes, VeraCrypt will start write-protecting the entire volume (both the outer and the hidden part) until it is dismounted. This may cause filesystem corruption on the outer volume, which (if repeated) might adversely affect plausible deniability of the hidden volume. Therefore, you should make every effort to avoid writing to the hidden volume area. Any data being saved to protected hidden volume areas will not be saved and will be lost. Windows may report this as a write error ("Delayed Write Failed" or "The parameter is incorrect"). + WARNING: Data were attempted to be saved to the hidden volume area of the volume mounted as %c:! VeraCrypt prevented these data from being saved in order to protect the hidden volume. This may have caused filesystem corruption on the outer volume and Windows may have reported a write error ("Delayed Write Failed" or "The parameter is incorrect"). The entire volume (both the outer and the hidden part) will be write-protected until it is dismounted. If this is not the first time VeraCrypt has prevented data from being saved to the hidden volume area of this volume, plausible deniability of this hidden volume might be adversely affected (due to possible unusual correlated inconsistencies within the outer volume file system). Therefore, you should consider creating a new VeraCrypt volume (with Quick Format disabled) and moving files from this volume to the new volume; this volume should be securely erased (both the outer and the hidden part). We strongly recommend that you restart the operating system now. + You have indicated intent to store files larger than 4 GB on the volume. This requires the volume to be formatted as NTFS/exFAT, which, however, will not be possible. + Please note that when a hidden operating system is running, non-hidden VeraCrypt volumes cannot be formatted as NTFS/exFAT. The reason is that the volume would need to be temporarily mounted without write protection in order to allow the operating system to format it as NTFS (whereas formatting as FAT is performed by VeraCrypt, not by the operating system, and without mounting the volume). For further technical details, see below. You can create a non-hidden NTFS/exFAT volume from within the decoy operating system. + For security reasons, when a hidden operating system is running, hidden volumes can be created only in the 'direct' mode (because outer volumes must always be mounted as read-only). To create a hidden volume securely, follow these steps:\n\n1) Boot the decoy system.\n\n2) Create a normal VeraCrypt volume and, to this volume, copy some sensitive-looking files that you actually do NOT want to hide (the volume will become the outer volume).\n\n3) Boot the hidden system and start the VeraCrypt Volume Creation Wizard. If the volume is file-hosted, move it to the system partition or to another hidden volume (otherwise, the newly created hidden volume would be mounted as read-only and could not be formatted). Follow the instructions in the wizard so as to select the 'direct' hidden volume creation mode.\n\n4) In the wizard, select the volume you created in step 2 and then follow the instructions to create a hidden volume within it. + For security reasons, when a hidden operating system is running, local unencrypted filesystems and non-hidden VeraCrypt volumes are mounted as read-only (no data can be written to such filesystems or VeraCrypt volumes).\n\nData is allowed to be written to any filesystem that resides within a hidden VeraCrypt volume (provided that the hidden volume is not located in a container stored on an unencrypted filesystem or on any other read-only filesystem). + There are three main reasons why such countermeasures have been implemented:\n\n- It enables the creation of a secure platform for mounting of hidden VeraCrypt volumes. Note that we officially recommend that hidden volumes are mounted only when a hidden operating system is running. (For more information, see the subsection 'Security Requirements and Precautions Pertaining to Hidden Volumes' in the documentation.)\n\n- In some cases, it is possible to determine that, at a certain time, a particular filesystem was not mounted under (or that a particular file on the filesystem was not saved or accessed from within) a particular instance of an operating system (e.g. by analyzing and comparing filesystem journals, file timestamps, application logs, error logs, etc). This might indicate that a hidden operating system is installed on the computer. The countermeasures prevent these issues.\n\n- It prevents data corruption and allows safe hibernation. When Windows resumes from hibernation, it assumes that all mounted filesystems are in the same state as when the system entered hibernation. VeraCrypt ensures this by write-protecting any filesystem accessible both from within the decoy and hidden systems. Without such protection, the filesystem could become corrupted when mounted by one system while the other system is hibernated. + Note: If you need to securely transfer files from the decoy system to the hidden system, follow these steps:\n1) Start the decoy system.\n2) Save the files to an unencrypted volume or to an outer/normal VeraCrypt volume.\n3) Start the hidden system.\n4) If you saved the files to a VeraCrypt volume, mount it (it will be automatically mounted as read-only).\n5) Copy the files to the hidden system partition or to another hidden volume. + Your computer must be restarted.\n\nDo you want to restart it now? + An error occurred when obtaining the system encryption status. + No password specified in the command line. The volume can't be created. + No volume size specified in the command line. The volume can't be created. + The volume file size specified in the command line is incompatible with selected NTFS filesystem. + The volume file size specified in the command line is incompatible with selected FAT32 filesystem. + The filesystem on the target drive doesn't support creating sparse files which is required for dynamic volumes. + Only container files can be created through the command line. + The container file size specified in the command line is greater than the available disk free space. Volume can't be created. + The volume size specified in the command line is too small. The volume can't be created. + The volume size specified in the command line is too big. The volume can't be created. + Cannot initialize application components for system encryption. + Failed to initialize the random number generator!\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n%hs, Last Error = 0x%.8X) + Windows Crypto API failed!\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n%hs, Last Error = 0x%.8X) + Unable to initialize the application. Failed to register the Dialog class. + Error: Failed to load the Rich Edit system library. + VeraCrypt Volume Creation Wizard + Maximum possible hidden volume size for this volume is %.2f bytes. + Maximum possible hidden volume size for this volume is %.2f KB. + Maximum possible hidden volume size for this volume is %.2f MB. + Maximum possible hidden volume size for this volume is %.2f GB. + Maximum possible hidden volume size for this volume is %.2f TB. + Volume password/keyfiles cannot be changed while the volume is mounted. Please dismount the volume first. + The header key derivation algorithm cannot be changed while the volume is mounted. Please dismount the volume first. + &Mount + A newer version of VeraCrypt is required to mount this volume. + Error: Volume Creation Wizard not found.\n\nPlease make sure that the file 'VeraCrypt Format.exe' is in the folder from which 'VeraCrypt.exe' was launched. If it is not, please reinstall VeraCrypt, or locate 'VeraCrypt Format.exe' on your disk and run it. + Error: Volume Expander not found.\n\nPlease make sure that the file 'VeraCryptExpander.exe' is in the folder from which 'VeraCrypt.exe' was launched. If it is not, please reinstall VeraCrypt, or locate 'VeraCryptExpander.exe' on your disk and run it. + &Next > + &Finish + &Install + E&xtract + Unable to connect to the VeraCrypt device driver. VeraCrypt cannot work if the device driver is not running.\n\nPlease note that, due to a Windows issue, it may be necessary to log off or restart the system before the device driver can be loaded. + Error occurred when loading/preparing fonts. + The drive letter was not found or no drive letter was specified. + Error: Cannot assign drive letter.\n\nUntil a drive letter is assigned to the decrypted volume, you will not be able to access data stored on the volume.\n\nRetry? + Drive letter not available. + No file selected! + No drive letters available. + No free drive letter for the outer volume! Volume creation cannot continue. + Could not determine your operating system version or you are using an unsupported operating system. + No path selected! + Not enough free space for the hidden volume! Volume creation cannot continue. + Error: The files you copied to the outer volume occupy too much space. Therefore, there is not enough free space on the outer volume for the hidden volume.\n\nNote that the hidden volume must be as large as the system partition (the partition where the currently running operating system is installed). The reason is that the hidden operating system needs to be created by copying the content of the system partition to the hidden volume.\n\n\nThe process of creation of the hidden operating system cannot continue. + The driver is unable to dismount the volume. Some files located on the volume are probably still open. + Unable to lock the volume. There are still open files on the volume. Therefore, it cannot be dismounted. + VeraCrypt cannot lock the volume because it is in use by the system or applications (there may be open files on the volume).\n\nDo you want to force dismount on the volume? + Select a VeraCrypt Volume + Specify Path and File Name + Select PKCS #11 Library + Out of Memory + IMPORTANT: We strongly recommend that inexperienced users create a VeraCrypt file container on the selected device/partition, instead of attempting to encrypt the entire device/partition.\n\nWhen you create a VeraCrypt file container (as opposed to encrypting a device or partition) there is, for example, no risk of destroying a large number of files. Note that a VeraCrypt file container (even though it contains a virtual encrypted disk) is actually just like any normal file. For more information, see the chapter Beginner's Tutorial in the VeraCrypt User Guide.\n\nAre you sure you want to encrypt the entire device/partition? + WARNING: The file '%s' already exists!\n\nIMPORTANT: VERACRYPT WILL NOT ENCRYPT THE FILE, BUT IT WILL DELETE IT. Are you sure you want to delete the file and replace it with a new VeraCrypt container? + CAUTION: ALL FILES CURRENTLY STORED ON THE SELECTED %s '%s'%s WILL BE ERASED AND LOST (THEY WILL NOT BE ENCRYPTED)!\n\nAre you sure you want to proceed with format? + WARNING: You will not be able to mount the volume or access any files stored on it until it has been fully encrypted.\n\nAre you sure you want to start encrypting the selected %s '%s'%s? + WARNING: You will not be able to mount the volume or access any files stored on it until it has been fully decrypted.\n\nAre you sure you want to start decrypting the selected %s '%s'%s? + WARNING: Please note that if power supply is suddenly interrupted while encrypting/decrypting existing data in place, or when the operating system crashes due to a software error or hardware malfunction while VeraCrypt is encrypting/decrypting existing data in place, portions of the data will be corrupted or lost. Therefore, before you start encrypting/decrypting, please make sure that you have backup copies of the files you want to encrypt/decrypt.\n\nDo you have such a backup? + CAUTION: ANY FILES CURRENTLY STORED ON THE PARTITION '%s'%s (I.E. ON THE FIRST PARTITION BEHIND THE SYSTEM PARTITION) WILL BE ERASED AND LOST (THEY WILL NOT BE ENCRYPTED)!\n\nAre you sure you want to proceed with format? + WARNING: THE SELECTED PARTITION CONTAINS A LARGE AMOUNT OF DATA! Any files stored on the partition will be erased and lost (they will NOT be encrypted)! + Erase any files stored on the partition by creating a VeraCrypt volume within it + Password + PIM + Set Header Key Derivation Algorithm + Add/Remove Keyfiles to/from Volume + Remove All Keyfiles from Volume + Password, PIM and/or keyfile(s) successfully changed.\n\nIMPORTANT: Please make sure you have read the section 'Changing Passwords and Keyfiles' in the chapter 'Security Requirements and Precautions' in the VeraCrypt User Guide. + This volume is registered as a System Favorite and its PIM was changed.\nDo you want VeraCrypt to automatically update the System Favorite configuration (administrator privileges required)?\n\nPlease note that if you answer no, you'll have to update the System Favorite manually. + IMPORTANT: If you did not destroy your VeraCrypt Rescue Disk, your system partition/drive can still be decrypted using the old password (by booting the VeraCrypt Rescue Disk and entering the old password). You should create a new VeraCrypt Rescue Disk and then destroy the old one.\n\nDo you want to create a new VeraCrypt Rescue Disk? + Note that your VeraCrypt Rescue Disk still uses the previous algorithm. If you consider the previous algorithm insecure, you should create a new VeraCrypt Rescue Disk and then destroy the old one.\n\nDo you want to create a new VeraCrypt Rescue Disk? + Any kind of file (for example, .mp3, .jpg, .zip, .avi) may be used as a VeraCrypt keyfile. Note that VeraCrypt never modifies the keyfile contents. You can select more than one keyfile (the order does not matter). If you add a folder, all non-hidden files found in it will be used as keyfiles. Click 'Add Token Files' to select keyfiles stored on security tokens or smart cards (or to import keyfiles to security tokens or smart cards). + Keyfile(s) successfully added/removed. + Keyfile exported. + Header key derivation algorithm successfully set. + Please enter the password and/or keyfile(s) for the non-system volume where you want to resume the process of in-place encryption/decryption.\n\nRemark: After you click Next, VeraCrypt will attempt to find all non-system volumes where the process of encryption/decryption has been interrupted and where the VeraCrypt volume header can be deciphered using the supplied password and/or keyfile(s). If more than one such volume is found, you will need to select one of them in the next step. + Please select one of the listed volumes. The list contains each accessible non-system volume where the process of encryption/decryption has been interrupted and where the volume header was successfully deciphered using the supplied password and/or keyfile(s). + Please enter the password and/or keyfile(s) for the non-system VeraCrypt volume that you want to decrypt. + It is very important that you choose a good password. You should avoid choosing one that contains only a single word that can be found in a dictionary (or a combination of 2, 3, or 4 such words). It should not contain any names or dates of birth. It should not be easy to guess. A good password is a random combination of upper and lower case letters, numbers, and special characters, such as @ ^ = $ * + etc. We recommend choosing a password consisting of 20 or more characters (the longer, the better). The maximum possible length is 64 characters. + Please choose a password for the hidden volume. + Please choose a password for the hidden operating system (i.e. for the hidden volume). + IMPORTANT: The password that you choose for the hidden operating system in this step must be substantially different from the other two passwords (i.e. from the password for the outer volume and from the password for the decoy operating system). + Please enter the password for the volume within which you wish to create a hidden volume.\n\nAfter you click Next, VeraCrypt will attempt to mount the volume. As soon as the volume is mounted, its cluster bitmap will be scanned to determine the size of the uninterrupted area of free space (if there is any) whose end is aligned with the end of the volume. This area will accommodate the hidden volume and therefore will limit its maximum possible size. Cluster map scanning is necessary to ensure that no data on the outer volume will be overwritten by the hidden volume. + \nPlease choose a password for the outer volume. This will be the password that you will be able to reveal to an adversary if you are asked or forced to do so.\n\nIMPORTANT: The password must be substantially different from the one you will choose for the hidden volume.\n\nNote: The maximum possible password length is 64 characters. + Please choose a password for the outer volume. This will be the password you will be able to reveal to anyone forcing you to disclose the password for the first partition behind the system partition, where both the outer volume and the hidden volume (containing the hidden operating system) will reside. The existence of the hidden volume (and of the hidden operating system) will remain secret. Note that this password is not for the decoy operating system.\n\nIMPORTANT: The password must be substantially different from the one you will choose for the hidden volume (i.e. for the hidden operating system). + Outer Volume Password + Hidden Volume Password + Password for Hidden Operating System + WARNING: Short passwords are easy to crack using brute force techniques!\n\nWe recommend choosing a password consisting of 20 or more characters. Are you sure you want to use a short password? + Volume Password + Operation failed due to one or more of the following:\n - Incorrect password.\n - Incorrect Volume PIM number.\n - Incorrect PRF (hash).\n - Not a valid volume. + Operation failed due to one or more of the following:\n - Incorrect keyfile(s).\n - Incorrect password.\n - Incorrect Volume PIM number.\n - Incorrect PRF (hash).\n - Not a valid volume. + Operation failed due to one or more of the following:\n - Wrong mount mode.\n - Incorrect password.\n - Incorrect Volume PIM number.\n - Incorrect PRF (hash).\n - Not a valid volume. + Operation failed due to one or more of the following:\n - Wrong mount mode.\n - Incorrect keyfile(s).\n - Incorrect password.\n - Incorrect Volume PIM number.\n - Incorrect PRF (hash).\n - Not a valid volume. + Auto-mount failed due to one or more of the following:\n - Incorrect password.\n - Incorrect Volume PIM number.\n - Incorrect PRF (hash).\n - No valid volume found. + Auto-mount failed due to one or more of the following:\n - Incorrect keyfile(s).\n - Incorrect password.\n - Incorrect Volume PIM number.\n - Incorrect PRF (hash).\n - No valid volume found. + \n\nWarning: Caps Lock is on. This may cause you to enter your password incorrectly. + Remember Number to Mount Volume + Outer Volume PIM + Hidden Volume PIM + PIM for Hidden Operating System + PIM (Personal Iterations Multiplier) is a value that controls the number of iterations used by the header key derivation as follows:\n Iterations = 15000 + (PIM x 1000).\n\nWhen left empty or set to 0, VeraCrypt will use a default value (485) that ensures a high security.\n\nWhen the password is less than 20 characters, PIM can't be smaller than 485 in order to maintain a minimal security level.\nWhen the password is 20 characters or more, PIM can be set to any value.\n\nA PIM value larger than 485 will lead to slower mount. A small PIM value (less than 485) will lead to a quicker mount but it can reduce security if the password is not strong enough. + PIM (Personal Iterations Multiplier) is a value that controls the number of iterations used by the header key derivation as follows:\n Iterations = PIM x 2048.\n\nWhen left empty or set to 0, VeraCrypt will use a default value that ensures a high security.\n\nWhen the password is less than 20 characters, PIM can't be smaller than 98 in order to maintain a minimal security level.\nWhen the password is 20 characters or more, PIM can be set to any value.\n\nA PIM value larger than 98 will lead to slower boot. A small PIM value (less than 98) will lead to a quicker boot but it can reduce security if the password is not strong enough. + Remember Number to Boot System + You have chosen a PIM value that is larger than VeraCrypt default value.\nPlease note that this will lead to much slower mount/boot. + You have chosen a Personal Iterations Multiplier (PIM) that is smaller than the default VeraCrypt value. Please note that if your password is not strong enough, this could lead to a weaker security.\n\nDo you confirm that you are using a strong password? + Personal Iterations Multiplier (PIM) maximum value for system encryption is 65535. + Volume PIM + \n\nWARNING: Hidden file(s) have been found in a keyfile search path. Such hidden files cannot be used as keyfiles. If you need to use them as keyfiles, remove their 'Hidden' attribute (right-click each of them, select 'Properties', uncheck 'Hidden' and click OK). Note: Hidden files are visible only if the corresponding option is enabled (Computer > Organize > 'Folder and search options' > View). + If you are attempting to protect a hidden volume containing a hidden system, please make sure you are using the standard US keyboard layout when typing the password for the hidden volume. This is required due to the fact that the password needs to be typed in the pre-boot environment (before Windows starts) where non-US Windows keyboard layouts are not available. + VeraCrypt has not found any volume where the process of encryption/decryption of a non-system volume has been interrupted and where the volume header can be deciphered using the supplied password and/or keyfile(s).\n\nPlease make sure the password and/or keyfile(s) are correct and that the partition/volume is not being used by the system or applications (including antivirus software). + The selected partition/device is already fully encrypted.\nHeader Flags = 0x%.8X + The selected partition/device is not using in-place encryption.\nHeader Flags = 0x%.8X + \n\nNote: If you are attempting to mount a partition located on an encrypted system drive without pre-boot authentication or to mount the encrypted system partition of an operating system that is not running, you can do so by selecting 'System' > 'Mount Without Pre-Boot Authentication'. + In this mode, you cannot mount a partition located on a drive whose portion is within the key scope of active system encryption.\n\nBefore you can mount this partition in this mode, you need to either boot an operating system installed on a different drive (encrypted or unencrypted) or boot an unencrypted operating system. + VeraCrypt cannot decrypt an individual partition on an entirely encrypted system drive (you can decrypt only the entire system drive). + Warning: As the drive contains the VeraCrypt Boot Loader, it may be an entirely encrypted system drive. If it is, please note that VeraCrypt cannot decrypt an individual partition on an entirely encrypted system drive (you can decrypt only the entire system drive). If that is the case, you will be able to continue now but you will receive the 'Incorrect password' error message later. + < &Back + Unable to list raw devices installed on your system! + The volume '%s' exists, and is read-only. Are you sure you want to replace it? + Select destination directory + Select Keyfile + Select a keyfile search path. WARNING: Note that only the path will be remembered, not the filenames! + Select a directory where to store the keyfiles. + The current container file was selected as a keyfile. It will be skipped. + Designed by Ross Anderson, Eli Biham, and Lars Knudsen. Published in 1998. 256-bit key, 128-bit block. Mode of operation is XTS. Serpent was one of the AES finalists. + Please specify the size of the container you want to create.\n\nIf you create a dynamic (sparse-file) container, this parameter will specify its maximum possible size.\n\nNote that the minimum possible size of a FAT volume is 292 KB. The minimum possible size of an exFAT volume is 424 KB. The minimum possible size of an NTFS volume is 3792 KB. + Please specify the size of the outer volume to be created (you will first create the outer volume and then a hidden volume within it). The minimum possible size of a volume within which a hidden volume is intended to be created is 340 KB. + Please specify the size of the hidden volume to create. The minimum possible size of a hidden volume is 40 KB (or 3664 KB if it is formatted as NTFS). The maximum possible size you can specify for the hidden volume is displayed above. + Outer Volume Size + Hidden Volume Size + Please verify that the size of the selected device/partition shown above is correct and click Next. + The outer volume and the hidden volume (containing the hidden operating system) will reside within the above partition. It should be the first partition behind the system partition.\n\nPlease verify that the size of the partition and its number shown above are correct, and if they are, click Next. + \n\nNote that the minimum possible size of a volume within which a hidden volume is intended to be created is 340 KB. + Volume Size + Dynamic + CAUTION: SELF-TEST FAILED! + Self-tests of all algorithms passed + The data unit number that you supplied is too long or short. + The secondary key that you supplied is too long or short. + The test ciphertext you have supplied is too long or short. + The test key you have supplied is too long or short. + The test plaintext you have supplied is too long or short. + Two ciphers in a cascade operating in XTS mode. Each block is first encrypted with %s (%d-bit key) and then with %s (%d-bit key). Each cipher uses its own key. All keys are mutually independent. + Three ciphers in a cascade operating in XTS mode. Each block is first encrypted with %s (%d-bit key), then with %s (%d-bit key), and finally with %s (%d-bit key). Each cipher uses its own key. All keys are mutually independent. + Note that, depending on the operating system configuration, these auto-run and auto-mount features may work only when the traveler disk files are created on a non-writable CD/DVD-like medium. Also note that this is not a bug in VeraCrypt (it is a limitation of Windows). + VeraCrypt traveler disk has been successfully created.\n\nNote that you need administrator privileges to run VeraCrypt in portable mode. Also note that, after examining the registry file, it may be possible to tell that VeraCrypt was run on a Windows system even if it is run in portable mode. + VeraCrypt Traveler Disk + Designed by Bruce Schneier, John Kelsey, Doug Whiting, David Wagner, Chris Hall, and Niels Ferguson. Published in 1998. 256-bit key, 128-bit block. Mode of operation is XTS. Twofish was one of the AES finalists. + More information on %s + Unknown + An unspecified or unknown error occurred (%d). + Some volumes contain files or folders being used by applications or system.\n\nForce dismount? + &Dismount + Dismount failed! + Volume contains files or folders being used by applications or system.\n\nForce dismount? + No volume is mounted to the specified drive letter. + The volume you are trying to mount is already mounted. + An error occurred when attempting to mount volume. + Error seeking location within volume. + Error: Incorrect volume size. + WARNING: You should use Quick Format only in the following cases:\n\n1) The device contains no sensitive data and you do not need plausible deniability.\n2) The device has already been securely and fully encrypted.\n\nAre you sure you want to use Quick Format? + Dynamic container is a pre-allocated NTFS sparse file whose physical size (actual disk space used) grows as new data is added to it.\n\nWARNING: Performance of sparse-file-hosted volumes is significantly worse than performance of regular volumes. Sparse-file-hosted volumes are also less secure, because it is possible to tell which volume sectors are unused. Furthermore, sparse-file-hosted volumes cannot provide plausible deniability (host a hidden volume). Also note that if data is written to a sparse file container when there is not enough free space in the host file system, the encrypted file system may get corrupted.\n\nAre you sure you want to create a sparse-file-hosted volume? + Note that the size of the dynamic container reported by Windows and by VeraCrypt will always be equal to its maximum size. To find out current physical size of the container (actual disk space it uses), right-click the container file (in a Windows Explorer window, not in VeraCrypt), then select 'Properties' and see the 'Size on disk' value.\n\nAlso note that if you move a dynamic container to another volume or drive, the physical size of the container will be extended to the maximum. (You can prevent that by creating a new dynamic container in the destination location, mounting it and then moving the files from the old container to the new one.) + Password cache wiped + Passwords (and/or processed keyfile contents) stored in the VeraCrypt driver cache have been wiped. + VeraCrypt cannot change the password for a foreign volume. + Please select a free drive letter from the list. + Please select a mounted volume in the drive letter list. + Warning: Two different volumes/devices are currently selected (the first is selected in the drive letter list and the second is selected in the input field below the drive letter list).\n\nPlease confirm your choice: + Error: Cannot create autorun.inf + Error while processing keyfile! + Error processing keyfile path! + The keyfile path contains no files.\n\nPlease note that folders (and files they contain) found in keyfile search paths are ignored. + VeraCrypt does not support this operating system. + Error: VeraCrypt supports only stable versions of this operating system (beta/RC versions are not supported). + Error: Cannot allocate memory. + Error: Could not retrieve value of performance counter. + Error: Bad volume format. + Error: You supplied a password for a hidden volume (not for a normal volume). + For security reasons, a hidden volume cannot be created within a VeraCrypt volume containing a filesystem that has been encrypted in place (because the free space on the volume has not been filled with random data). + VeraCrypt - Legal Notices + All Files + VeraCrypt Volumes + Library Modules + NTFS/exFAT formatting cannot continue. + Cannot mount volume. + Cannot dismount volume. + Windows failed to format the volume as NTFS/exFAT.\n\nPlease select a different type of file system (if possible) and try again. Alternatively, you could leave the volume unformatted (select 'None' as the filesystem), exit this wizard, mount the volume, and then use either a system or a third-party tool to format the mounted volume (the volume will remain encrypted). + Windows failed to format the volume as NTFS/exFAT.\n\nDo you want to format the volume as FAT instead? + Default + partition + PARTITION + Device + device + DEVICE + Volume + volume + VOLUME + Label + The selected cluster size is too small for this volume size. A greater cluster size will be used instead. + Error: Cannot get volume size!\n\nMake sure the selected volume is not being used by the system or an application. + Hidden volumes must not be created within dynamic (sparse file) containers. To achieve plausible deniability, the hidden volume needs to be created within a non-dynamic container. + The VeraCrypt Volume Creation Wizard can create a hidden volume only within a FAT/exFAT or NTFS volume. + Under Windows 2000, the VeraCrypt Volume Creation Wizard can create a hidden volume only within a FAT volume. + Note: The FAT/exFAT file system is more suitable for outer volumes than the NTFS file system (for example, the maximum possible size of the hidden volume would very likely have been significantly greater if the outer volume had been formatted as FAT/exFAT). + Note that the FAT/exFAT file system is more suitable for outer volumes than the NTFS file system. For example, the maximum possible size of the hidden volume will very likely be significantly greater if the outer volume is formatted as FAT/exFAT (the reason is that the NTFS file system always stores internal data exactly in the middle of the volume and, therefore, the hidden volume can reside only in the second half of the outer volume).\n\nAre you sure you want to format the outer volume as NTFS? + Do you want to format the volume as FAT instead? + Note: This volume cannot be formatted as FAT, because it exceeds the maximum volume size supported by the FAT32 filesystem for the applicable sector size (2 TB for 512-byte sectors and 16 TB for 4096-byte sectors). + Error: The partition for the hidden operating system (i.e. the first partition behind the system partition) must be at least 5% larger than the system partition (the system partition is the one where the currently running operating system is installed). + Error: The partition for the hidden operating system (i.e. the first partition behind the system partition) must be at least 110% (2.1 times) larger than the system partition (the system partition is the one where the currently running operating system is installed). The reason is that the NTFS file system always stores internal data exactly in the middle of the volume and, therefore, the hidden volume (which is to contain a clone of the system partition) can reside only in the second half of the partition. + Error: If the outer volume is formatted as NTFS, it must be at least 110% (2.1 times) larger than the system partition. The reason is that the NTFS file system always stores internal data exactly in the middle of the volume and, therefore, the hidden volume (which is to contain a clone of the system partition) can reside only in the second half of the outer volume.\n\nNote: The outer volume needs to reside within the same partition as the hidden operating system (i.e. within the first partition behind the system partition). + Error: There is no partition behind the system partition.\n\nNote that before you can create a hidden operating system, you need to create a partition for it on the system drive. It must be the first partition behind the system partition and it must be at least 5% larger than the system partition (the system partition is the one where the currently running operating system is installed). However, if the outer volume (not to be confused with the system partition) is formatted as NTFS, the partition for the hidden operating system must be at least 110% (2.1 times) larger than the system partition (the reason is that the NTFS file system always stores internal data exactly in the middle of the volume and, therefore, the hidden volume, which is to contain a clone of the system partition, can reside only in the second half of the partition). + Remark: It is not practical (and therefore is not supported) to install operating systems in two VeraCrypt volumes that are embedded within a single partition, because using the outer operating system would often require data to be written to the area of the hidden operating system (and if such write operations were prevented using the hidden volume protection feature, it would inherently cause system crashes, i.e. 'Blue Screen' errors). + For information on how to create and manage partitions, please refer to the documentation supplied with your operating system or contact your computer vendor's technical support team for assistance. + Error: The currently running operating system is not installed on the boot partition (first Active partition). This is not supported. + You indicated that you intend to store files larger than 4 GB in this VeraCrypt volume. However, you chose the FAT file system, on which files larger than 4 GB cannot be stored.\n\nAre you sure you want to format the volume as FAT? + Error: VeraCrypt does not support in-place decryption of legacy non-system volumes created by VeraCrypt 1.0b or earlier.\n\nNote: You can still decrypt files stored on the volume by copying/moving them to any unencrypted volume. + Error: VeraCrypt cannot in-place decrypt a hidden VeraCrypt volume.\n\nNote: You can still decrypt files stored on the volume by copying/moving them to any unencrypted volume. + Warning: Note that VeraCrypt cannot in-place decrypt a volume that contains a hidden VeraCrypt volume (the hidden volume would be overwritten with pseudorandom data).\n\nPlease confirm that the volume you are about to decrypt contains no hidden volume.\n\nNote: If the volume contains a hidden volume but you do not mind losing the hidden volume, you can select Proceed (the outer volume will be safely decrypted). + The volume does not contain any hidden volume. Proceed. + The volume contains a hidden volume. Cancel. + Error: Cannot access the volume!\n\nMake sure that the selected volume exists, that it is not mounted or being used by the system or an application, that you have read/write permission for the volume, and that it is not write-protected. + Error: Cannot obtain volume properties. + Error: Cannot access the volume and/or obtain information about the volume.\n\nMake sure that the selected volume exists, that it is not being used by the system or applications, that you have read/write permission for the volume, and that it is not write-protected. + Error: Cannot access the volume and/or obtain information about the volume. Make sure that the selected volume exists, that it is not being used by the system or applications, that you have read/write permission for the volume, and that it is not write-protected.\n\nIf the problem persists, it might help to follow the below steps. + An error prevented VeraCrypt from encrypting the partition. Please try fixing any previously reported problems and then try again. If the problems persist, it might help to follow the below steps. + An error prevented VeraCrypt from resuming the process of encryption/decryption of the partition/volume.\n\nPlease try fixing any previously reported problems and then try resuming the process again if possible. Note that the volume cannot be mounted until it has been fully encrypted or fully decrypted. + An error prevented VeraCrypt from decrypting the volume. Please try fixing any previously reported problems and then try again if possible. + Error: Cannot dismount the outer volume!\n\nVolume cannot be dismounted if it contains files or folders being used by a program or the system.\n\nPlease close any program that might be using files or directories on the volume and click Retry. + Error: Cannot obtain information about the outer volume!\nVolume creation cannot continue. + Error: Cannot access the outer volume! Volume creation cannot continue. + Error: Cannot mount the outer volume! Volume creation cannot continue. + Error: Cannot get volume cluster bitmap! Volume creation cannot continue. + Alphabetical/Categorized + Mean Speed (Descending) + Algorithm + Encryption + Decryption + Mean + Drive + Size + Encryption Algorithm + Encryption Algorithm + Type + Value + Property + Location + bytes + Hidden + Outer + Normal + System + Hidden (system) + Read-Only + System drive + System drive (encrypting - %.2f%% done) + System drive (decrypting - %.2f%% done) + System drive (%.2f%% encrypted) + System partition + Hidden system partition + System partition (encrypting - %.2f%% done) + System partition (decrypting - %.2f%% done) + System partition (%.2f%% encrypted) + Yes (damage prevented!) + None + Primary Key Size + Secondary Key Size (XTS Mode) + Tweak Key Size (LRW Mode) + bits + Block Size + PKCS-5 PRF + PKCS-5 Iteration Count + Volume Created + Header Last Modified + (%I64d days ago) + Volume Format Version + Embedded Backup Header + VeraCrypt Boot Loader Version + First available + Removable Disk + Harddisk + Unchanged + Autodetection + Wizard Mode + Select one of the modes. If you are not sure which to select, use the default mode. + Select this option if you want to install VeraCrypt on this system. + Note: You can upgrade without decrypting even if the system partition/drive is encrypted or you use a hidden operating system. + If you select this option, all files will be extracted from this package but nothing will be installed on the system. Do not select it if you intend to encrypt the system partition or system drive. Selecting this option can be useful, for example, if you want to run VeraCrypt in so-called portable mode. VeraCrypt does not have to be installed on the operating system under which it is run. After all files are extracted, you can directly run the extracted file 'VeraCrypt.exe' (then VeraCrypt will run in portable mode). + Setup Options + Here you can set various options to control the installation process. + Installing + Please wait while VeraCrypt is being installed. + VeraCrypt has been successfully installed + VeraCrypt has been successfully upgraded + Please consider making a donation. You can click Finish anytime to close the installer. + Extraction Options + Here you can set various options to control the extraction process. + Please wait while files are being extracted. + Files successfully extracted + All files have been successfully extracted to the destination location. + If the specified folder does not exist, it will be automatically created. + The VeraCrypt program files will be upgraded in the location where VeraCrypt is installed. If you need to select a different location, please uninstall VeraCrypt first. + Do you want to view release notes for the current (latest stable) version of VeraCrypt? + If you have never used VeraCrypt before, we recommend that you read the chapter Beginner's Tutorial in the VeraCrypt User Guide. Do you want to view the tutorial? + Please select an action to perform from the following: + Repair/Reinstall + Upgrade + Uninstall + To successfully install/uninstall VeraCrypt, you must have administrator privileges. Do you want to continue? + VeraCrypt Installer is currently running on this system and performing or preparing installation or update of VeraCrypt. Before you proceed, please wait for it to finish or close it. If you cannot close it, please restart your computer before proceeding. + Installation failed. + Uninstallation failed. + This distribution package is damaged. Please try downloading it again (preferably from the official VeraCrypt website at https://veracrypt.codeplex.com). + Cannot write file %s + Extracting + Cannot read data from the package. + Cannot verify the integrity of this distribution package. + Extraction failed. + The installation has been rolled back. + VeraCrypt has been successfully installed. + VeraCrypt has been successfully updated. + VeraCrypt has been successfully upgraded. However, before you can start using it, the computer must be restarted.\n\nDo you want to restart it now? + Failed to upgrade VeraCrypt!\n\nIMPORTANT: Before you shut down or restart the system, we strongly recommend that you use System Restore (Windows Start menu > All programs > Accessories > System Tools > System Restore) to restore your system to the restore point named 'VeraCrypt installation'. If System Restore is not available, you should try installing the original or the new version of VeraCrypt again before you shut down or restart the system. + VeraCrypt has been successfully uninstalled.\n\nClick 'Finish' to remove the VeraCrypt installer and the folder %s. Note that the folder will not be removed if it contains any files that were not installed by the VeraCrypt installer or created by VeraCrypt. + Removing VeraCrypt registry entries + Adding registry entry + Removing application-specific data + Installing + Stopping + Removing + Adding icon + Creating System Restore point + Failed to create System Restore point! + Updating boot loader + Failed to install '%s'. %s\nDo you want to continue installing? + Failed to uninstall '%s'. %s\nDo you want to continue uninstalling? + Installation completed. + The folder '%s' could not be created + The VeraCrypt device driver cannot be unloaded.\n\nPlease close all open VeraCrypt windows first. If it does not help, please restart Windows and then try again. + All VeraCrypt volumes must be dismounted before installing or uninstalling VeraCrypt. + An obsolete version of VeraCrypt is currently installed on this system. It needs to be uninstalled before you can install this new version of VeraCrypt.\n\nAs soon as you close this message box, the uninstaller of the old version will be launched. Note that no volume will be decrypted when you uninstall VeraCrypt. After you uninstall the old version of VeraCrypt, run the installer of the new version of VeraCrypt again. + The installation of the registry entries has failed + The installation of the device driver has failed. Please restart Windows and then try installing VeraCrypt again. + Starting VeraCrypt device driver + Uninstallation of the device driver has failed. Please note that, due to a Windows issue, it may be necessary to log off or restart the system before the device driver can be uninstalled (or reinstalled). + Installing VeraCrypt device driver + Stopping VeraCrypt device driver + Uninstalling VeraCrypt device driver + Registration of the User Account Control support library failed. + Unregistration of the User Account Control support library failed. + Note about portable mode:\n\nPlease note that the operating system requires drivers to be registered with it before they can be started. Hence, the VeraCrypt driver is not (and cannot be) fully portable (whereas the VeraCrypt applications are fully portable, i.e. they do not have to be installed or registered with the operating system). Also note that VeraCrypt needs a driver to provide transparent on-the-fly encryption/decryption. + Note that if you decide to run VeraCrypt in portable mode (as opposed to running an installed copy of VeraCrypt), the system will ask you for permission to run VeraCrypt (UAC prompt) every time you attempt to run it.\n\nThe reason is that when you run VeraCrypt in portable mode, VeraCrypt needs to load and start the VeraCrypt device driver. VeraCrypt needs a device driver to provide transparent on-the-fly encryption/decryption, and users without administrator privileges cannot start device drivers in Windows. Therefore, the system will ask you for permission to run VeraCrypt with administrator privileges (UAC prompt).\n\nNote that if you install VeraCrypt on the system (as opposed to running VeraCrypt in portable mode), the system will NOT ask you for permission to run VeraCrypt (UAC prompt) every time you attempt to run it.\n\nAre you sure you want to extract the files? + Warning: This instance of the Volume Creation Wizard has administrator privileges.\n\nYour new volume may be created with permissions that will not allow you to write to the volume when it is mounted. If you want to avoid that, close this instance of the Volume Creation Wizard and launch a new one without administrator privileges.\n\nDo you want to close this instance of the Volume Creation Wizard? + Error: Cannot display license. + Outer(!) + days + hours + minutes + s + Open + Dismount + Show VeraCrypt + Hide VeraCrypt + Data Read since Mount + Data Written since Mount + Encrypted Portion + 100% (fully encrypted) + 0% (not encrypted) + %.3f%% + 100% + Waiting + Preparing + Resizing + Encrypting + Decrypting + Finalizing + Paused + Finished + Error + Device disconnected + System favorite volumes saved.\n\nTo enable mounting of system favorite volumes when the system starts, please select 'Settings' > 'System Favorite Volumes' > 'Mount system favorite volumes when Windows starts'. + The volume you are adding to favorites is neither a partition nor a dynamic volume. Therefore, VeraCrypt will be unable to mount this favorite volume if the device number changes. + The volume you are adding to favorites is a partition not recognized by Windows.\n\nVeraCrypt will be unable to mount this favorite volume if the device number changes. Please set the type of the partition to a type recognized by Windows (use the SETID command of the Windows 'diskpart' tool). Then add the partition to favorites again. + VeraCrypt Background Task is disabled or it is configured to exit when there are no mounted volumes (or VeraCrypt is running in portable mode). This may prevent your favorite volumes from being automatically mounted when devices hosting them get connected.\n\nNote: To enable the VeraCrypt Background Task, select Settings > Preferences and check the 'Enabled' checkbox in the section 'VeraCrypt Background Task'. + A container stored in a remote filesystem shared over a network cannot be automatically mounted when its host device gets connected. + The device displayed below is neither a partition nor a dynamic volume. Therefore, the volume hosted on the device cannot be automatically mounted when the device gets connected. + Please set the type of the partition displayed below to a type recognized by Windows (use the SETID command of the Windows 'diskpart' tool). Then remove the partition from favorites and add it again. This will enable the volume hosted on the device to be automatically mounted when the device gets connected. + The device displayed below is neither a partition nor a dynamic volume. Therefore, no label can be assigned to it. + Please set the type of the partition displayed below to a type recognized by Windows (use the SETID command of the Windows 'diskpart' tool). Then remove the partition from favorites and add it again. This will enable VeraCrypt to assign a label to the partition. + Due to a Windows limitation, a container stored in a remote filesystem shared over a network cannot be mounted as a system favorite volume (however, it can be mounted as a non-system favorite volume when a user logs on). + Enter password for %s + Enter password for '%s' + Enter password for the normal/outer volume + Enter password for the hidden volume + Enter password for the header stored in backup file + Keyfiles have been successfully created. + The number of keyfiles you supplied is invalid. + The keyfile size must be comprized between 64 and 1048576 bytes. + Please enter a name for the keyfile(s) to be generated + The base name of the keyfile(s) is invalid + The keyfile '%s' already exists.\nDo you want to overwrite it? The generation process will be stopped if you answer No. + WARNING: The header of this volume is damaged! VeraCrypt automatically used the backup of the volume header embedded in the volume.\n\nYou should repair the volume header by selecting 'Tools' > 'Restore Volume Header'. + Volume header backup has been successfully created.\n\nIMPORTANT: Restoring the volume header using this backup will also restore the current volume password. Moreover, if keyfile(s) are/is necessary to mount the volume, the same keyfile(s) will be necessary to mount the volume again when the volume header is restored.\n\nWARNING: This volume header backup may be used to restore the header ONLY of this particular volume. If you use this header backup to restore a header of a different volume, you will be able to mount the volume, but you will NOT be able to decrypt any data stored in the volume (because you will change its master key). + The volume header has been successfully restored.\n\nIMPORTANT: Please note that an old password may have been restored as well. Moreover, if keyfile(s) were/was necessary to mount the volume when the backup was created, the same keyfile(s) are now necessary to mount the volume again. + For security reasons, you will have to enter the correct password (and/or supply the correct keyfiles) for the volume.\n\nNote: If the volume contains a hidden volume, you will have to enter the correct password (and/or supply the correct keyfiles) for the outer volume first. Afterwards, if you choose to back up the header of the hidden volume, you will have to enter the correct password (and/or supply the correct keyfiles) for the hidden volume. + Are you sure you want to create volume header backup for %s?\n\nAfter you click Yes, you will prompted for a filename for the header backup.\n\nNote: Both the standard and the hidden volume headers will be re-encrypted using a new salt and stored in the backup file. If there is no hidden volume within this volume, the area reserved for the hidden volume header in the backup file will be filled with random data (to preserve plausible deniability). When restoring a volume header from the backup file, you will need to enter the correct password (and/or to supply the correct keyfiles) that was/were valid when the volume header backup was created. The password (and/or keyfiles) will also automatically determine the type of the volume header to restore, i.e. standard or hidden (note that VeraCrypt determines the type through the process of trial and error). + Are you sure you want to restore volume header of %s?\n\nWARNING: Restoring a volume header also restores the volume password that was valid when the backup was created. Moreover, if keyfile(s) were/was necessary to mount the volume when the backup was created, the same keyfile(s) will be necessary to mount the volume again after the volume header is restored.\n\nAfter you click Yes, you will select the header backup file. + Does the volume contain a hidden volume? + The volume contains a hidden volume + The volume does not contain a hidden volume + Please select the type of volume header backup you want to use: + Restore the volume header from the backup embedded in the volume + Restore the volume header from an external backup file + The size of the volume header backup file is incorrect. + There is no backup header embedded in this volume (note that only volumes created by VeraCrypt 6.0 or later contain embedded backup headers). + You are attempting to back up the header of the system partition/drive. This is not allowed. Backup/restore operations pertaining to the system partition/drive can be performed only using the VeraCrypt Rescue Disk.\n\nDo you want to create a VeraCrypt Rescue Disk? + You are attempting to restore the header of a virtual VeraCrypt volume but you selected the system partition/drive. This is not allowed. Backup/restore operations pertaining to the system partition/drive can be performed only using the VeraCrypt Rescue Disk.\n\nDo you want to create a VeraCrypt Rescue Disk? + After you click OK, you will select a filename for the new VeraCrypt Rescue Disk ISO image and the location where you wish to place it. + The Rescue Disk image has been created and stored in this file:\n%s\n\nNow you need to burn the Rescue Disk image to a CD or DVD.\n\nIMPORTANT: Note that the file must be written to the CD/DVD as an ISO disk image (not as an individual file). For information on how to do so, please refer to the documentation of your CD/DVD recording software.\n\nAfter you burn the Rescue Disk, select 'System' > 'Verify Rescue Disk' to verify that it has been correctly burned. + The Rescue Disk image has been created and stored in this file:\n%s\n\nNow you need to burn the Rescue Disk image to a CD or DVD.\n\nDo you want to launch the Microsoft Windows Disc Image Burner now?\n\nNote: After you burn the Rescue Disk, select 'System' > 'Verify Rescue Disk' to verify that it has been correctly burned. + Please insert your VeraCrypt Rescue Disk into your CD/DVD drive and click OK to verify it. + The VeraCrypt Rescue Disk has been successfully verified. + Cannot verify that the Rescue Disk has been correctly burned.\n\nIf you have burned the Rescue Disk, please eject and reinsert the CD/DVD; then try again. If this does not help, please try other CD/DVD recording software and/or medium.\n\nIf you attempted to verify a VeraCrypt Rescue Disk created for a different master key, password, salt, etc., please note that such Rescue Disk will always fail this verification. To create a new Rescue Disk fully compatible with your current configuration, select 'System' > 'Create Rescue Disk'. + The VeraCrypt Rescue Disk ISO image has been successfully verified. + The Rescue Disk ISO image verification failed.\n\nIf you attempted to verify a VeraCrypt Rescue Disk ISO image created for a different master key, password, salt, etc., please note that such Rescue Disk ISO image will always fail this verification. To create a new Rescue Disk ISO image fully compatible with your current configuration, select 'System' > 'Create Rescue Disk'. + Error creating VeraCrypt Rescue Disk. + VeraCrypt Rescue Disk cannot be created when a hidden operating system is running.\n\nTo create a VeraCrypt Rescue Disk, boot the decoy operating system and then select 'System' > 'Create Rescue Disk'. + Cannot verify that the Rescue Disk has been correctly burned.\n\nIf you have burned the Rescue Disk, please eject and reinsert the CD/DVD; then click Next to try again. If this does not help, please try another medium%s.\n\nIf you have not burned the Rescue Disk yet, please do so, and then click Next.\n\nIf you attempted to verify a VeraCrypt Rescue Disk created before you started this wizard, please note that such Rescue Disk cannot be used, because it was created for a different master key. You need to burn the newly generated Rescue Disk. + and/or other CD/DVD recording software + VeraCrypt - System Favorite Volumes + What are system favorite volumes? + The system partition/drive does not appear to be encrypted.\n\nSystem favorite volumes can be mounted using only a pre-boot authentication password. Therefore, to enable use of system favorite volumes, you need to encrypt the system partition/drive first. + Please dismount the volume before proceeding. + Error: Cannot set timer. + Check Filesystem + Repair Filesystem + Add to Favorites... + Add to System Favorites... + P&roperties... + Hidden Volume Protected + N/A + Yes + No + Disabled + 1 + 2 or more + Mode of Operation + Label: + Size: + Path: + Drive Letter: + Error: Password must contain only ASCII characters.\n\nNon-ASCII characters in password might cause the volume to be impossible to mount when your system configuration changes.\n\nThe following characters are allowed:\n\n ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \\ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ + Warning: Password contains non-ASCII characters. This may cause the volume to be impossible to mount when your system configuration changes.\n\nYou should replace all non-ASCII characters in the password with ASCII characters. To do so, click 'Volumes' -> 'Change Volume Password'.\n\nThe following are ASCII characters:\n\n ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \\ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ + WARNING: We strongly recommend that you avoid file extensions that are used for executable files (such as .exe, .sys, or .dll) and other similarly problematic file extensions. Using such file extensions causes Windows and antivirus software to interfere with the container, which adversely affects the performance of the volume and may also cause other serious problems.\n\nWe strongly recommend that you remove the file extension or change it (e.g., to '.hc').\n\nAre you sure you want to use the problematic file extension? + WARNING: This container has a file extension that is used for executable files (such as .exe, .sys, or .dll) or some other file extension that is similarly problematic. It will very likely cause Windows and antivirus software to interfere with the container, which will adversely affect the performance of the volume and may also cause other serious problems.\n\nWe strongly recommend that you remove the file extension of the container or change it (e.g., to '.hc') after you dismount the volume. + Homepage + WARNING: It appears that you have not applied any Service Pack to your Windows installation. You should not write to IDE disks larger than 128 GB under Windows XP to which you did not apply Service Pack 1 or later! If you do, data on the disk (no matter if it is a VeraCrypt volume or not) may get corrupted. Note that this is a limitation of Windows, not a bug in VeraCrypt. + WARNING: It appears that you have not applied Service Pack 3 or later to your Windows installation. You should not write to IDE disks larger than 128 GB under Windows 2000 to which you did not apply Service Pack 3 or later! If you do, data on the disk (no matter if it is a VeraCrypt volume or not) may get corrupted. Note that this is a limitation of Windows, not a bug in VeraCrypt.\n\nNote: You may also need to enable the 48-bit LBA support in the registry; for more information, see http://support.microsoft.com/kb/305098/EN-US + WARNING: 48-bit LBA ATAPI support is disabled on your system. Therefore, you should not write to IDE disks larger than 128 GB! If you do, data on the disk (no matter if it is a VeraCrypt volume or not) may get corrupted. Note that this is a limitation of Windows, not a limitation of VeraCrypt.\n\nTo enable the 48-bit LBA support, add the 'EnableBigLba' registry value in the registry key HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\atapi\\Parameters and set it to 1.\n\nFor more information, see http://support.microsoft.com/kb/305098 + Error: Files larger than 4 GB cannot be stored on a FAT32 file system. Therefore, file-hosted VeraCrypt volumes (containers) stored on a FAT32 file system cannot be larger than 4 GB.\n\nIf you need a larger volume, create it on an NTFS file system (or, if you use Windows Vista SP1 or later, on an exFAT file system) or, instead of creating a file-hosted volume, encrypt an entire partition or device. + Warning: Windows XP does not support files larger than 2048 GB (it will report that "Not enough storage is available"). Therefore, you cannot create a file-hosted VeraCrypt volume (container) larger than 2048 GB under Windows XP.\n\nNote that it is still possible to encrypt the entire drive or create a partition-hosted VeraCrypt volume larger than 2048 GB under Windows XP. + WARNING: If you want to be able to add more data/files to the outer volume in future, you should consider choosing a smaller size for the hidden volume.\n\nAre you sure you want to continue with the size you specified? + No volume selected.\n\nClick 'Select Device' or 'Select File' to select a VeraCrypt volume. + No partition selected.\n\nClick 'Select Device' to select a dismounted partition that normally requires pre-boot authentication (for example, a partition located on the encrypted system drive of another operating system, which is not running, or the encrypted system partition of another operating system).\n\nNote: The selected partition will be mounted as a regular VeraCrypt volume without pre-boot authentication. This is useful e.g. for backup or repair operations. + WARNING: If default keyfiles are set and enabled, volumes that are not using these keyfiles will be impossible to mount. Therefore, after you enable default keyfiles, keep in mind to uncheck the 'Use keyfiles' checkbox (below a password input field) whenever mounting such volumes.\n\nAre you sure you want to save the selected keyfiles/paths as default? + Auto-Mount Devices + Dismount All + Wipe Cache + Dismount All & Wipe Cache + Force Dismount All & Wipe Cache + Force Dismount All, Wipe Cache & Exit + Mount Favorite Volumes + Show/Hide Main VeraCrypt Window + (Click here and press a key) + Action + Shortcut + Error: This shortcut is reserved. Please choose a different shortcut. + Error: Shortcut already in use. + WARNING: One or more VeraCrypt system-wide hot keys will not work!\n\nPlease make sure that other applications and the operating system do not use the same shortcut(s) as VeraCrypt. + Paging file creation has been prevented.\n\nPlease note that, due to Windows issues, paging files cannot be located on non-system VeraCrypt volumes (including system favorite volumes). VeraCrypt supports creation of paging files only on an encrypted system partition/drive. + An error or incompatibility prevents VeraCrypt from encrypting the hibernation file. Therefore, hibernation has been prevented.\n\nNote: When a computer hibernates (or enters a power-saving mode), the content of its system memory is written to a hibernation storage file residing on the system drive. VeraCrypt would not be able to prevent encryption keys and the contents of sensitive files opened in RAM from being saved unencrypted to the hibernation storage file. + Hibernation has been prevented.\n\nVeraCrypt does not support hibernation on hidden operating systems that use an extra boot partition. Please note that the boot partition is shared by both the decoy and the hidden system. Therefore, in order to prevent data leaks and problems while resuming from hibernation, VeraCrypt has to prevent the hidden system from writing to the shared boot partition and from hibernating. + VeraCrypt volume mounted as %c: has been dismounted. + VeraCrypt volumes have been dismounted. + VeraCrypt volumes have been dismounted and password cache has been wiped. + Successfully dismounted + WARNING: If the VeraCrypt Background Task is disabled, the following functions will be disabled:\n\n1) Hot keys\n2) Auto-dismount (e.g., upon logoff, inadvertent host device removal, time-out, etc.)\n3) Auto-mount of favorite volumes\n4) Notifications (e.g., when damage to hidden volume is prevented)\n5) Tray icon\n\nNote: You can shut down the Background Task anytime by right-clicking the VeraCrypt tray icon and selecting 'Exit'.\n\nAre you sure you want to permanently disable the VeraCrypt Background Task? + WARNING: If this option is disabled, volumes containing open files/directories will not be possible to auto-dismount.\n\nAre you sure you want to disable this option? + WARNING: Volumes containing open files/directories will NOT be auto-dismounted.\n\nTo prevent this, enable the following option in this dialog window: 'Force auto-dismount even if volume contains open files or directories' + WARNING: When the notebook battery power is low, Windows may omit sending the appropriate messages to running applications when the computer is entering power saving mode. Therefore, VeraCrypt may fail to auto-dismount volumes in such cases. + You have scheduled the process of encryption/decryption of a partition/volume. The process has not been completed yet.\n\nDo you want to resume the process now? + You have scheduled the process of encryption or decryption of the system partition/drive. The process has not been completed yet.\n\nDo you want to start (resume) the process now? + Do you want to be prompted about whether you want to resume the currently scheduled processes of encryption/decryption of non-system partitions/volumes? + Yes, keep prompting me + No, do not prompt me + IMPORTANT: Keep in mind that you can resume the process of encryption/decryption of any non-system partition/volume by selecting 'Volumes' > 'Resume Interrupted Process' from the menu bar of the main VeraCrypt window. + You have scheduled the process of encryption or decryption of the system partition/drive. However, pre-boot authentication failed (or was bypassed).\n\nNote: If you decrypted the system partition/drive in the pre-boot environment, you may need to finalize the process by selecting 'System' > 'Permanently Decrypt System Partition/Drive' from the menu bar of the main VeraCrypt window. + WARNING: If VeraCrypt exits now, the following functions will be disabled:\n\n1) Hot keys\n2) Auto-dismount (e.g., upon logoff, inadvertent host device removal, time-out, etc.)\n3) Auto-mount of favorite volumes\n4) Notifications (e.g., when damage to hidden volume is prevented)\n\nNote: If you do not wish VeraCrypt to run in the background, disable the VeraCrypt Background Task in the Preferences (and, if necessary, disable the automatic start of VeraCrypt in the Preferences).\n\nAre you sure you want VeraCrypt to exit? + Exit? + VeraCrypt does not have sufficient information to determine whether to encrypt or decrypt. + VeraCrypt does not have sufficient information to determine whether to encrypt or decrypt.\n\nNote: If you decrypted the system partition/drive in the pre-boot environment, you may need to finalize the process by clicking Decrypt. + Note: When you are encrypting a non-system partition/volume in place and an error persistently prevents you from finishing the process, you will not be able to mount the volume (and access data stored on it) until you entirely DECRYPT the volume (i.e. reverse the process).\n\nIf you need to do so, follow these steps:\n1) Exit this wizard.\n2) In the main VeraCrypt window, select 'Volumes' > 'Resume Interrupted Process'.\n3) Select 'Decrypt'. + Do you want to interrupt and postpone the process of encryption/decryption of the partition/volume?\n\nNote: Keep in mind that the volume cannot be mounted until it has been fully encrypted or decrypted. You will be able to resume the process of encryption/decryption and it will continue from the point where it was stopped. You can do so, for example, by selecting 'Volumes' > 'Resume Interrupted Process' from the menu bar of the main VeraCrypt window. + Do you want to interrupt and postpone the process of encryption of the system partition/drive?\n\nNote: You will be able to resume the process and it will continue from the point it was stopped. You can do so, for example, by selecting 'System' > 'Resume Interrupted Process' from the menu bar of the main VeraCrypt window. If you want to permanently terminate or reverse the encryption process, select 'System' > 'Permanently Decrypt System Partition/Drive'. + Do you want to interrupt and postpone the process of decryption of the system partition/drive?\n\nNote: You will be able to resume the process and it will continue from the point it was stopped. You can do so, for example, by selecting 'System' > 'Resume Interrupted Process' from the menu bar of the main VeraCrypt window. If you want to reverse the decryption process (and start encrypting), select 'System' > 'Encrypt System Partition/Drive'. + Error: Failed to interrupt the process of encryption/decryption of the system partition/drive. + Error: Failed to interrupt the process of wiping. + Error: Failed to resume the process of encryption/decryption of the system partition/drive. + Error: Failed to start the process of wiping. + Inconsistency resolved.\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n%hs) + Error: Unexpected state.\n\n\n(If you report a bug in connection with this, please include the following technical information in the bug report:\n%hs) + There is no interrupted process of encryption/decryption of the system partition/drive to resume.\n\nNote: If you want to resume an interrupted process of encryption/decryption of a non-system partition/volume, select 'Volumes' > 'Resume Interrupted Process'. + WARNING: VeraCrypt Background Task is disabled. After you exit VeraCrypt, you will not be notified if damage to hidden volume is prevented.\n\nNote: You may shut down the Background Task anytime by right-clicking the VeraCrypt tray icon and selecting 'Exit'.\n\nEnable VeraCrypt Background Task? + Language pack version: %s + Checking the file system on the VeraCrypt volume mounted as %s... + Attempting to repair the file system on the VeraCrypt volume mounted as %s... + Warning: This volume is encrypted with a legacy encryption algorithm.\n\nAll 64-bit-block encryption algorithms (e.g., Blowfish, CAST-128, or Triple DES) are deprecated. It will be possible to mount this volume using future versions of VeraCrypt. However, there will be no further enhancements to the implementations of these legacy encryption algorithms. We recommend that you create a new VeraCrypt volume encrypted with a 128-bit-block encryption algorithm (e.g., AES, Serpent, Twofish, etc.) and that you move all files from this volume to the new volume. + Your system is not configured to auto-mount new volumes. It may be impossible to mount device-hosted VeraCrypt volumes. Auto-mounting can be enabled by executing the following command and restarting the system.\n\nmountvol.exe /E + Please assign a drive letter to the partition/device before proceeding ('Control Panel' > 'System and Maintenance' > 'Administrative Tools' - 'Create and format hard disk partitions').\n\nNote that this is a requirement of the operating system. + Mount VeraCrypt volume + Dismount all VeraCrypt volumes + VeraCrypt failed to obtain Administrator privileges. + Access was denied by the operating system.\n\nPossible cause: The operating system requires that you have read/write permission (or administrator privileges) for certain folders, files, and devices, in order for you to be allowed to read and write data to/from them. Normally, a user without administrator privileges is allowed to create, read and modify files in his or her Documents folder. + Error: The drive uses an unsupported sector size.\n\nIt is currently not possible to create partition/device-hosted volumes on drives that use sectors larger than 4096 bytes. However, note that you can create file-hosted volumes (containers) on such drives. + It is currently not possible to encrypt a system installed on a disk that uses a sector size other than 512 bytes. + The VeraCrypt Boot Loader requires at least 32 KBytes of free space at the beginning of the system drive (the VeraCrypt Boot Loader needs to be stored in that area). Unfortunately, your drive does not meet this condition.\n\nPlease do NOT report this as a bug/problem in VeraCrypt. To solve this problem, you will need to repartition your disk and leave the first 32 KBytes of the disk free (in most cases, you will need to delete and recreate the first partition). We recommend that you use the Microsoft partition manager that is available e.g. when you are installing Windows. + The feature is not supported on the version of the operating system you are currently using. + VeraCrypt does not support encryption of a system partition/drive on the version of the operating system you are currently using. + Before you can encrypt the system partition/drive on Windows Vista, you need to install Service Pack 1 or higher for Windows Vista (no such Service Pack has been installed on this system yet).\n\nNote: Service Pack 1 for Windows Vista resolved an issue causing a shortage of free base memory during system boot. + VeraCrypt no longer supports encryption of the system partition/drive on Windows Vista with no Service Pack installed. Before upgrading VeraCrypt, please install Service Pack 1 or higher for Windows Vista. + Error: This feature requires VeraCrypt to be installed on the system (you are running VeraCrypt in portable mode).\n\nPlease install VeraCrypt and then try again. + WARNING: Windows does not appear to be installed on the drive from which it boots. This is not supported.\n\nYou should continue only if you are sure that Windows is installed on the drive from which it boots.\n\nDo you want to continue? + Your system drive has a GUID partition table (GPT). Currently, only drives with a MBR partition table are supported. + CAUTION: The VeraCrypt Boot Loader is already installed on your system drive!\n\nIt is possible that another system on your computer is already encrypted.\n\nWARNING: PROCEEDING WITH ENCRYPTION OF THE CURRENTLY RUNNING SYSTEM MAY MAKE OTHER SYSTEM(S) IMPOSSIBLE TO START AND RELATED DATA INACCESSIBLE.\n\nAre you sure you want to continue? + Failed to restore the original system loader.\n\nPlease use your VeraCrypt Rescue Disk ('Repair Options' > 'Restore original system loader') or Windows installation medium to replace the VeraCrypt Boot Loader with the Windows system loader. + The original system loader will not be stored on the Rescue Disk (probable cause: missing backup file). + Failed to write the MBR sector.\n\nYour BIOS may be configured to protect the MBR sector. Check your BIOS settings (press F2, Delete, or Esc, after powering on your computer) for MBR/antivirus protection. + WARNING: The verification of VeraCrypt bootloader fingerprint failed!\nYour disk may have been tampered with by an attacker ("Evil Maid" attack).\n\nThis warning can also be triggered if you restored VeraCrypt boot loader using an Rescue Disk generated using a different VeraCrypt version.\n\nYou are advised to change your password immediately which will also restore the correct VeraCrypt bootloader. It is recommended to reinstall VeraCrypt and to take measures to avoid access to this machine by untrusted entities. + The required version of the VeraCrypt Boot Loader is currently not installed. This may prevent some of the settings from being saved. + Note: In some situations, you may wish to prevent a person (adversary) that is watching you start the computer from knowing that you use VeraCrypt. The above options allow you to do that by customizing the VeraCrypt boot loader screen. If you enable the first option, no texts will be displayed by the boot loader (not even when you enter the wrong password). The computer will appear to be "frozen" while you can type your password. In addition, a custom message can be displayed to mislead the adversary. For example, fake error messages such as "Missing operating system" (which is normally displayed by the Windows boot loader if it finds no Windows boot partition). It is, however, important to note that if the adversary can analyze the content of the hard drive, he can still find out that it contains the VeraCrypt boot loader. + WARNING: Please keep in mind that if you enable this option, the VeraCrypt boot loader will not display any texts (not even when you enter the wrong password). The computer will appear to be "frozen" (unresponsive) while you can type your password (the cursor will NOT move and no asterisk will be displayed when you press a key).\n\nAre you sure you want to enable this option? + Your system partition/drive appears to be fully encrypted. + VeraCrypt does not support encrypting a system drive that has been converted to a dynamic disk. + The system drive contains extended (logical) partitions.\n\nYou can encrypt an entire system drive containing extended (logical) partitions only on Windows Vista and later versions of Windows. On Windows XP, you can encrypt an entire system drive provided that it contains only primary partitions.\n\nNote: You can still encrypt the system partition instead of the entire system drive (and, in addition to that, you can create partition-hosted VeraCrypt volumes within any non-system partitions on the drive). + WARNING: As you are running Windows XP/2003, after you start encrypting the drive, you must NOT create any extended (logical) partitions on it (you may create only primary partitions). Any extended (logical) partition on the drive would be inaccessible after you start encrypting (the drive currently does not contain any such partition).\n\nNote: If this limitation is not acceptable, you can go back and choose to encrypt only the system partition instead of the entire drive (and, in addition to that, you can create partition-hosted VeraCrypt volumes within any non-system partitions on the drive).\n\nAlternatively, if this limitation is not acceptable, you may want to consider upgrading to Windows Vista or a later version of Windows (you can encrypt an entire system drive containing extended/logical partitions only on Windows Vista or later). + Your system drive contains a non-standard partition.\n\nIf you are using a notebook, your system drive probably contains a special recovery partition. After the whole system drive is encrypted (including any recovery partition), your system might become unbootable if your computer is using an inappropriately designed BIOS. It would also be impossible to use any recovery partition until the system drive is decrypted. Therefore, we recommend that you encrypt only the system partition. + Do you want to encrypt the system partition instead of the entire drive?\n\nNote that you can create partition-hosted VeraCrypt volumes within any non-system partitions on the drive (in addition to encrypting the system partition). + As your system drive contains only a single partition that occupies the whole drive, it is preferable (more secure) to encrypt the entire drive including the free "slack" space that typically surrounds such a partition.\n\nDo you want to encrypt the entire system drive? + Your system is configured to store temporary files on a non-system partition.\n\nTemporary files may be stored only on the system partition. + Your user profile files are not stored on the system partition.\n\nUser profile files may be stored only on the system partition. + There is/are paging file(s) on non-system partitions.\n\nPaging files may be located only on the system partition. + Do you want to configure Windows to create paging files only on the Windows partition now?\n\nNote that if you click 'Yes', the computer will be restarted. Then start VeraCrypt and try creating the hidden OS again. + Otherwise, plausible deniability of the hidden operating system might be adversely affected.\n\nNote: If an adversary analyzed the content of such files (residing on a non-system partition), he might find out that you used this wizard in the hidden-system-creation mode (which might indicate the existence of a hidden operating system on your computer). Also note that any such files stored on the system partition will be securely erased by VeraCrypt during the process of creation of the hidden operating system. + WARNING: During the process of creation of the hidden operating system, you will be required to fully reinstall the currently running system (in order to create a decoy system securely).\n\nNote: The currently running operating system and the entire content of the system partition will be copied to the hidden volume (in order to create the hidden system).\n\n\nAre you sure you will be able to install Windows using a Windows Setup medium (or using a service partition)? + For security reasons, if the currently running operating system requires activation, it must be activated before proceeding. Note that the hidden operating system will be created by copying the content of the system partition to a hidden volume (so if this operating system is not activated, the hidden operating system will not be activated either). For more information, see the section "Security Requirements and Precautions Pertaining to Hidden Volumes" in the VeraCrypt User's Guide.\n\nImportant: Before proceeding, please make sure you have read the section "Security Requirements and Precautions Pertaining to Hidden Volumes" in the VeraCrypt User's Guide.\n\n\nDoes the currently running operating system meet the above condition? + Your system uses an extra boot partition. VeraCrypt does not support hibernation on hidden operating systems that use an extra boot partition (decoy systems can be hibernated without any problems).\n\nPlease note that the boot partition would be shared by both the decoy and the hidden system. Therefore, in order to prevent data leaks and problems while resuming from hibernation, VeraCrypt has to prevent the hidden system from writing to the shared boot partition and from hibernating.\n\n\nDo you want to continue? If you select 'No', instructions for removing the extra boot partition will be displayed. + \nThe extra boot partition can be removed before installing Windows. To do so, follow these steps:\n\n1) Boot your Windows installation disc.\n\n2) In the Windows installer screen, click 'Install now' > 'Custom (advanced)'.\n\n3) Click 'Drive Options'.\n\n4) Select the main system partition and delete it by clicking 'Delete' and 'OK'.\n\n5) Select the 'System Reserved' partition, click 'Extend', and increase its size so that the operating system can be installed to it.\n\n6) Click 'Apply' and 'OK'.\n\n7) Install Windows on the 'System Reserved' partition.\n\n\nShould an attacker ask why you removed the extra boot partition, you can answer that you wanted to prevent any possible data leaks to the unencrypted boot partition.\n\nNote: You can print this text by clicking the 'Print' button below. If you save a copy of this text or print it (strongly recommended, unless your printer stores copies of documents it prints on its internal drive), you should destroy any copies of it after removing the extra boot partition (otherwise, if such a copy was found, it might indicate that there is a hidden operating system on this computer). + Warning: There is unallocated space between the system partition and the first partition behind it. After you create the hidden operating system, you must not create any new partitions in that unallocated space. Otherwise, the hidden operating system will be impossible to boot (until you delete such newly created partitions). + This algorithm is currently not supported for system encryption. + This algorithm is not supported for TrueCrypt mode. + PIM (Personal Iterations Multiplier) not supported for TrueCrypt mode. + Password must contain 20 or more characters in order to use the specified PIM.\nShorter passwords can only be used if the PIM is 485 or greater. + Pre-boot authentication Password must contain 20 or more characters in order to use the specified PIM.\nShorter passwords can only be used if the PIM is 98 or greater. + Keyfiles are currently not supported for system encryption. + Warning: VeraCrypt could not restore the original keyboard layout. This may cause you to enter a password incorrectly. + Error: Cannot set the keyboard layout for VeraCrypt to the standard US keyboard layout.\n\nNote that the password needs to be typed in the pre-boot environment (before Windows starts) where non-US Windows keyboard layouts are not available. Therefore, the password must always be typed using the standard US keyboard layout. + As VeraCrypt temporarily changed the keyboard layout to the standard US keyboard layout, it is not possible to type characters by pressing keys while the right Alt key is held down. However, you can type most of such characters by pressing appropriate keys while the Shift key is held down. + VeraCrypt prevented change of keyboard layout. + Note: The password will need to be typed in the pre-boot environment (before Windows starts) where non-US Windows keyboard layouts are not available. Therefore, the password must always be typed using the standard US keyboard layout. However, it is important to note that you do NOT need a real US keyboard. VeraCrypt automatically ensures that you can safely type the password (right now and in the pre-boot environment) even if you do NOT have a real US keyboard. + Before you can encrypt the partition/drive, you must create a VeraCrypt Rescue Disk (VRD), which serves the following purposes:\n\n- If the VeraCrypt Boot Loader, master key, or other critical data gets damaged, the VRD allows you to restore it (note, however, that you will still have to enter the correct password then).\n\n- If Windows gets damaged and cannot start, the VRD allows you to permanently decrypt the partition/drive before Windows starts.\n\n- The VRD will contain a backup of the present content of the first drive track (which typically contains a system loader or boot manager) and will allow you to restore it if necessary.\n\nThe VeraCrypt Rescue Disk ISO image will be created in the location specified below. + After you click OK, Microsoft Windows Disc Image Burner will be launched. Please use it to burn the VeraCrypt Rescue Disk ISO image to a CD or DVD.\n\nAfter you do so, return to the VeraCrypt Volume Creation Wizard and follow its instructions. + The Rescue Disk image has been created and stored in this file:\n%s\n\nNow you need to burn it to a CD or DVD.\n\n%lsAfter you burn the Rescue Disk, click Next to verify that it has been correctly burned. + The Rescue Disk image has been created and stored in this file:\n%s\n\nNow you should either burn the image to a CD/DVD or move it to a safe location for later use.\n\n%lsClick Next to continue. + IMPORTANT: Note that the file must be written to the CD/DVD as an ISO disk image (not as an individual file). For information on how to do so, please refer to the documentation of your CD/DVD recording software. If you do not have any CD/DVD recording software that can write the ISO disk image to a CD/DVD, click the link below to download such free software.\n\n + Launch Microsoft Windows Disc Image Burner + WARNING: If you already created a VeraCrypt Rescue Disk in the past, it cannot be reused for this system partition/drive because it was created for a different master key! Every time you encrypt a system partition/drive, you must create a new VeraCrypt Rescue Disk for it even if you use the same password. + Error: Cannot save system encryption settings. + Cannot initiate the system encryption pretest. + Cannot initiate the process of creation of the hidden operating system. + Wipe Mode + On some types of storage media, when data is overwritten with other data, it may be possible to recover the overwritten data using techniques such as magnetic force microscopy. This also applies to data that are overwritten with their encrypted form (which happens when VeraCrypt initially encrypts an unencrypted partition or drive). According to some studies and governmental publications, recovery of overwritten data can be prevented (or made very difficult) by overwriting the data with pseudorandom and certain non-random data a certain number of times. Therefore, if you believe that an adversary might be able to use such techniques to recover the data you intend to encrypt, you may want to select one of the wipe modes (existing data will NOT be lost). Note that wiping will NOT be performed after the partition/drive is encrypted. When the partition/drive is fully encrypted, no unencrypted data is written to it. Any data being written to it is first encrypted on the fly in memory and only then is the (encrypted) data written to the disk. + On some types of storage media, when data is overwritten with other data (e.g. when the data is erased), it may be possible to recover the overwritten data using techniques such as magnetic force microscopy. According to some studies and governmental publications, recovery of overwritten data can be prevented (or made very difficult) by overwriting the data with pseudorandom and certain non-random data a certain number of times. Therefore, if you believe that an adversary might be able to use such techniques to recover the data that is to be erased, you may want to select one of the multi-pass wipe modes.\n\nNote: The more wipe passes you use, the longer it takes to erase the data. + Wiping + \nNote: You can interrupt the process of wiping, shut down your computer, start the hidden system again and then resume the process (this wizard will be launched automatically). However, if you interrupt it, the entire process of wiping will have to start from the beginning. + \n\nNote: If you interrupt the process of wiping and then attempt to resume it, the entire process will have to start from the beginning. + Do you want to abort the process of wiping? + Warning: The entire content of the selected partition/device will be erased and lost. + The entire content of the partition where the original system resides will be erased.\n\nNote: The entire content of the partition that is to be erased has been copied to this hidden system partition. + WARNING: Note that when you choose e.g. the 3-pass wipe mode, the time necessary to encrypt the partition/drive will be up to 4 times longer. Likewise, if you choose the 35-pass wipe mode, it will be up to 36 times longer (it might even take several weeks).\n\nHowever, please note that wiping will NOT be performed after the partition/drive is fully encrypted. When the partition/drive is fully encrypted, no unencrypted data is written to it. Any data being written to it is first encrypted on the fly in memory and only then is the (encrypted) data written to the disk (so the performance will NOT be affected).\n\nAre you sure you want to use the wipe mode? + None (fastest) + 1-pass (random data) + 3-pass (US DoD 5220.22-M) + 7-pass (US DoD 5220.22-M) + 35-pass ("Gutmann") + 256-pass + Number of Operating Systems + WARNING: Inexperienced users should never attempt to encrypt Windows in multi-boot configurations.\n\nContinue? + When creating/using a hidden operating system, VeraCrypt supports multi-boot configurations only when the following conditions are met:\n\n- The currently running operating system must be installed on the boot drive, which must not contain any other operating systems.\n\n- Operating systems installed on other drives must not use any boot loader residing on the drive on which the currently running operating system is installed.\n\nAre the above conditions met? + VeraCrypt does not support this multi-boot configuration when creating/using a hidden operating system. + Boot Drive + Is the currently running operating system installed on the boot drive?\n\nNote: Sometimes, Windows is not installed on the same drive as the Windows boot loader (boot partition). If that is the case, select 'No'. + VeraCrypt currently does not support encrypting an operating system that does not boot from the drive on which it is installed. + Number of System Drives + How many drives contain an operating system?\n\nNote: For example, if you have any operating system (e.g. Windows, Mac OS X, Linux, etc.) installed on your primary drive and any additional operating system installed on your secondary drive, select '2 or more'. + VeraCrypt currently does not support encrypting a whole drive that contains multiple operating systems.\n\nPossible Solutions:\n\n- You can still encrypt one of the systems if you go back and choose to encrypt only a single system partition (as opposed to choosing to encrypt the entire system drive).\n\n- Alternatively, you will be able to encrypt the entire drive if you move some of the systems to other drives leaving only one system on the drive you want to encrypt. + Multiple Systems on Single Drive + Are there any other operating systems installed on the drive on which the currently running operating system is installed?\n\nNote: For example, if the currently running operating system is installed on the drive #0, which contains several partitions, and if one of the partitions contains Windows and another partition contains any additional operating system (e.g. Windows, Mac OS X, Linux, etc.), select 'Yes'. + Non-Windows Boot Loader + Is a non-Windows boot loader (or boot manager) installed in the master boot record (MBR)?\n\nNote: For example, if the first track of the boot drive contains GRUB, LILO, XOSL, or some other non-Windows boot manager (or boot loader), select 'Yes'. + Multi-Boot + VeraCrypt currently does not support multi-boot configurations where a non-Windows boot loader is installed in the Master Boot Record.\n\nPossible Solutions:\n\n- If you use a boot manager to boot Windows and Linux, move the boot manager (typically, GRUB) from the Master Boot Record to a partition. Then start this wizard again and encrypt the system partition/drive. Note that the VeraCrypt Boot Loader will become your primary boot manager and it will allow you to launch the original boot manager (e.g. GRUB) as your secondary boot manager (by pressing Esc in the VeraCrypt Boot Loader screen) and thus you will be able boot Linux. + If the currently running operating system is installed on the boot partition, then, after you encrypt it, you will need to enter the correct password even if you want to start any other unencrypted Windows system(s) (as they will share a single encrypted Windows boot loader/manager).\n\nIn contrast, if the currently running operating system is not installed on the boot partition (or if the Windows boot loader/manager is not used by any other system), then, after you encrypt this system, you will not need to enter the correct password to boot the other unencrypted system(s) -- you will only need to press the Esc key to start the unencrypted system (if there are multiple unencrypted systems, you will also need to choose which system to start in the VeraCrypt Boot Manager menu).\n\nNote: Typically, the earliest installed Windows system is installed on the boot partition. + Encryption of Host Protected Area + At the end of many drives, there is an area that is normally hidden from the operating system (such areas are usually referred to as Host Protected Areas). However, some programs can read and write data from/to such areas.\n\nWARNING: Some computer manufacturers may use such areas to store tools and data for RAID, system recovery, system setup, diagnostic, or other purposes. If such tools or data must be accessible before booting, the hidden area should NOT be encrypted (choose 'No' above).\n\nDo you want VeraCrypt to detect and encrypt such a hidden area (if any) at the end of the system drive? + Type of System Encryption + Select this option if you merely want to encrypt the system partition or the entire system drive. + It may happen that you are forced by somebody to decrypt the operating system. There are many situations where you cannot refuse to do so (for example, due to extortion). If you select this option, you will create a hidden operating system whose existence should be impossible to prove (provided that certain guidelines are followed). Thus, you will not have to decrypt or reveal the password to the hidden operating system. For a detailed explanation, please click the link below. + It may happen that you are forced by somebody to decrypt the operating system. There are many situations where you cannot refuse to do so (for example, due to extortion).\n\nUsing this wizard, you can create a hidden operating system whose existence should be impossible to prove (provided that certain guidelines are followed). Thus, you will not have to decrypt or reveal the password for the hidden operating system. + Hidden Operating System + In the following steps, you will create two VeraCrypt volumes (outer and hidden) within the first partition behind the system partition. The hidden volume will contain the hidden operating system (OS). VeraCrypt will create the hidden OS by copying the content of the system partition (where the currently running OS is installed) to the hidden volume. To the outer volume, you will copy some sensitive looking files that you actually do NOT want to hide. They will be there for anyone forcing you to disclose the password for the hidden OS partition. You can reveal the password for the outer volume within the hidden OS partition (the existence of the hidden OS remains secret).\n\nFinally, on the system partition of the currently running OS, you will install a new OS, so-called decoy OS, and encrypt it. It must not contain sensitive data and will be there for anyone forcing you to reveal your pre-boot authentication password. In total, there will be three passwords. Two of them can be disclosed (for the decoy OS and outer volume). If you use the third one, the hidden OS will start. + Detecting Hidden Sectors + Please wait while VeraCrypt is detecting possible hidden sectors at the end of the system drive. Note that it may take a long time to complete.\n\nNote: In very rare cases, on some computers, the system may become unresponsive during this detection process. If it happens, restart the computer, start VeraCrypt, repeat the previous steps but skip this detection process. Note that this issue is not caused by a bug in VeraCrypt. + Area to Encrypt + Select this option if you want to encrypt the entire drive on which the currently running Windows system is installed. The whole drive, including all its partitions, will be encrypted except the first track where the VeraCrypt Boot Loader will reside. Anyone who wants to access a system installed on the drive, or files stored on the drive, will need to enter the correct password each time before the system starts. This option cannot be used to encrypt a secondary or external drive if Windows is not installed on it and does not boot from it. + Collecting Random Data + Keys Generated + VeraCrypt has found no CD/DVD burner connected to your computer. VeraCrypt needs a CD/DVD burner to burn a bootable VeraCrypt Rescue Disk containing a backup of the encryption keys, VeraCrypt boot loader, original system loader, etc.\n\nWe strongly recommend that you burn the VeraCrypt Rescue Disk. + I have no CD/DVD burner but I will store the Rescue Disk ISO image on a removable drive (e.g. USB flash drive). + I will connect a CD/DVD burner to my computer later. Terminate the process now. + A CD/DVD burner is connected to my computer now. Continue and write the Rescue Disk. + Please follow these steps:\n\n1) Connect a removable drive, such as a USB flash drive, to your computer now.\n\n2) Copy the VeraCrypt Rescue Disk image file (%s) to the removable drive.\n\nIn case you need to use the VeraCrypt Rescue Disk in the future, you will be able to connect your removable drive (containing the VeraCrypt Rescue Disk image) to a computer with a CD/DVD burner and create a bootable VeraCrypt Rescue Disk by burning the image to a CD or DVD. IMPORTANT: Note that the VeraCrypt Rescue Disk image file must be written to the CD/DVD as an ISO disk image (not as an individual file). + Rescue Disk Recording + Rescue Disk Created + System Encryption Pretest + Rescue Disk Verified + \nThe VeraCrypt Rescue Disk has been successfully verified. Please remove it from the drive now and store it in a safe place.\n\nClick Next to continue. + WARNING: During the next steps, the VeraCrypt Rescue Disk must not be in the drive. Otherwise, it will not be possible to complete the steps correctly.\n\nPlease remove it from the drive now and store it in a safe place. Then click OK. + Warning: Due to technical limitations of the pre-boot environment, texts displayed by VeraCrypt in the pre-boot environment (i.e. before Windows starts) cannot be localized. The VeraCrypt Boot Loader user interface is completely in English.\n\nContinue? + Before encrypting your system partition or drive, VeraCrypt needs to verify that everything works correctly.\n\nAfter you click Test, all the necessary components (for example, the pre-boot authentication component, i.e. the VeraCrypt Boot Loader) will be installed and your computer will be restarted. Then you will have to enter your password in the VeraCrypt Boot Loader screen that will appear before Windows starts. After Windows starts, you will be automatically informed about the result of this pretest.\n\nThe following device will be modified: Drive #%d\n\n\nIf you click Cancel now, nothing will be installed and the pretest will not be performed. + IMPORTANT NOTES -- PLEASE READ OR PRINT (click 'Print'):\n\nNote that none of your files will be encrypted before you successfully restart your computer and start Windows. Thus, if anything fails, your data will NOT be lost. However, if something does go wrong, you might encounter difficulties in starting Windows. Therefore, please read (and, if possible, print) the following guidelines on what to do if Windows cannot start after you restart the computer.\n\n + What to Do If Windows Cannot Start\n------------------------------------------------\n\nNote: These instructions are valid only if you have not started encrypting.\n\n- If Windows does not start after you enter the correct password (or if you repeatedly enter the correct password but VeraCrypt says that the password is incorrect), do not panic. Restart (power off and on) the computer, and in the VeraCrypt Boot Loader screen, press the Esc key on your keyboard (and if you have multiple systems, choose which to start). Then Windows should start (provided that it is not encrypted) and VeraCrypt will automatically ask whether you want to uninstall the pre-boot authentication component. Note that the previous steps do NOT work if the system partition/drive is encrypted (nobody can start Windows or access encrypted data on the drive without the correct password even if he or she follows the previous steps).\n\n + - If the previous steps do not help or if the VeraCrypt Boot Loader screen does not appear (before Windows starts), insert the VeraCrypt Rescue Disk into your CD/DVD drive and restart your computer. If the VeraCrypt Rescue Disk screen does not appear (or if you do not see the 'Repair Options' item in the 'Keyboard Controls' section of the VeraCrypt Rescue Disk screen), it is possible that your BIOS is configured to attempt to boot from hard drives before CD/DVD drives. If that is the case, restart your computer, press F2 or Delete (as soon as you see a BIOS start-up screen), and wait until a BIOS configuration screen appears. If no BIOS configuration screen appears, restart (reset) the computer again and start pressing F2 or Delete repeatedly as soon as you restart (reset) the computer. When a BIOS configuration screen appears, configure your BIOS to boot from the CD/DVD drive first (for information on how to do so, please refer to the documentation for your BIOS/motherboard or contact your computer vendor's technical support team for assistance). Then restart your computer. The VeraCrypt Rescue Disk screen should appear now. In the VeraCrypt Rescue Disk screen, select 'Repair Options' by pressing F8 on your keyboard. From the 'Repair Options' menu, select 'Restore original system loader'. Then remove the Rescue Disk from your CD/DVD drive and restart your computer. Windows should start normally (provided that it is not encrypted).\n\n + Note that the previous steps do NOT work if the system partition/drive is encrypted (nobody can start Windows or access encrypted data on the drive without the correct password even if he or she follows the previous steps).\n\n\nNote that even if you lose your VeraCrypt Rescue Disk and an attacker finds it, he or she will NOT be able to decrypt the system partition or drive without the correct password. + Pretest Completed + The pretest has been successfully completed.\n\nWARNING: Please note that if power supply is suddenly interrupted while encrypting existing data in place, or when the operating system crashes due to a software error or hardware malfunction while VeraCrypt is encrypting existing data in place, portions of the data will be corrupted or lost. Therefore, before you start encrypting, please make sure that you have backup copies of the files you want to encrypt. If you do not, please back up the files now (you can click Defer, back up the files, then run VeraCrypt again anytime, and select 'System' > 'Resume Interrupted Process' to start encrypting).\n\nWhen ready, click Encrypt to start encrypting. + You can click Pause or Defer anytime to interrupt the process of encryption or decryption, exit this wizard, restart or shut down your computer, and then resume the process, which will continue from the point it was stopped. To prevent slowdown when the system or applications write or read data from the system drive, VeraCrypt automatically waits until the data is written or read (see Status above) and then automatically continues encrypting or decrypting. + \n\nYou can click Pause or Defer anytime to interrupt the process of encryption, exit this wizard, restart or shut down your computer, and then resume the process, which will continue from the point it was stopped. Note that the volume cannot be mounted until it has been fully encrypted. + \n\nYou can click Pause or Defer anytime to interrupt the process of decryption, exit this wizard, restart or shut down the computer, and then resume the process, which will continue from the point where it was stopped. Note that the volume cannot be mounted until it has been fully decrypted. + Hidden System Started + Original System + Windows creates (typically, without your knowledge or consent) various log files, temporary files, etc., on the system partition. It also saves the content of RAM to hibernation and paging files located on the system partition. Therefore, if an adversary analyzed files stored on the partition where the original system (of which the hidden system is a clone) resides, he might find out, for example, that you used the VeraCrypt wizard in the hidden-system-creation mode (which might indicate the existence of a hidden operating system on your computer).\n\nTo prevent such issues, VeraCrypt will, in the next steps, securely erase the entire content of the partition where the original system resides. Afterwards, in order to achieve plausible deniability, you will need to install a new system on the partition and encrypt it. Thus you will create the decoy system and the whole process of creation of the hidden operating system will be completed. + The hidden operating system has been successfully created. However, before you can start using it (and achieve plausible deniability), you need to securely erase (using VeraCrypt) the entire content of the partition where the currently running operating system is installed. Before you can do that, you need to restart the computer and, in the VeraCrypt Boot Loader screen (which appears before Windows starts), enter the pre-boot authentication password for the hidden operating system. Then, after the hidden system starts, the VeraCrypt wizard will be launched automatically.\n\nNote: If you choose to terminate the process of creation of the hidden operating system now, you will NOT be able to resume the process and the hidden system will NOT be accessible (because the VeraCrypt Boot Loader will be removed). + You have scheduled the process of creation of a hidden operating system. The process has not been completed yet. To complete it, you need to restart the computer and, in the VeraCrypt Boot Loader screen (which appears before Windows starts), enter the password for the hidden operating system.\n\nNote: If you choose to terminate the process of creation of the hidden operating system now, you will NOT be able to resume the process. + Restart the computer and proceed + Permanently terminate the process of creation of the hidden operating system + Do nothing now and ask again later + \nIF POSSIBLE, PLEASE PRINT THIS TEXT (click 'Print' below).\n\n\nHow and When to Use VeraCrypt Rescue Disk (After Encrypting)\n-----------------------------------------------------------------------------------\n\n + I. How to Boot VeraCrypt Rescue Disk\n\nTo boot a VeraCrypt Rescue Disk, insert it into your CD/DVD drive and restart your computer. If the VeraCrypt Rescue Disk screen does not appear (or if you do not see the 'Repair Options' item in the 'Keyboard Controls' section of the screen), it is possible that your BIOS is configured to attempt to boot from hard drives before CD/DVD drives. If that is the case, restart your computer, press F2 or Delete (as soon as you see a BIOS start-up screen), and wait until a BIOS configuration screen appears. If no BIOS configuration screen appears, restart (reset) the computer again and start pressing F2 or Delete repeatedly as soon as you restart (reset) the computer. When a BIOS configuration screen appears, configure your BIOS to boot from the CD/DVD drive first (for information on how to do so, please refer to the documentation for your BIOS/motherboard or contact your computer vendor's technical support team for assistance). Then restart your computer. The VeraCrypt Rescue Disk screen should appear now. Note: In the VeraCrypt Rescue Disk screen, you can select 'Repair Options' by pressing F8 on your keyboard.\n\n\n + II. When and How to Use VeraCrypt Rescue Disk (After Encrypting)\n\n + 1) If the VeraCrypt Boot Loader screen does not appear after you start your computer (or if Windows does not boot), the VeraCrypt Boot Loader may be damaged. The VeraCrypt Rescue Disk allows you to restore it and thus to regain access to your encrypted system and data (however, note that you will still have to enter the correct password then). In the Rescue Disk screen, select 'Repair Options' > 'Restore VeraCrypt Boot Loader'. Then press 'Y' to confirm the action, remove the Rescue Disk from your CD/DVD drive and restart your computer.\n\n + 2) If you repeatedly enter the correct password but VeraCrypt says that the password is incorrect, the master key or other critical data may be damaged. The VeraCrypt Rescue Disk allows you to restore them and thus to regain access to your encrypted system and data (however, note that you will still have to enter the correct password then). In the Rescue Disk screen, select 'Repair Options' > 'Restore key data'. Then enter your password, press 'Y' to confirm the action, remove the Rescue Disk from your CD/DVD drive, and restart your computer.\n\n + 3) If the VeraCrypt Boot Loader is damaged, you can avoid running it by booting directly from the VeraCrypt Rescue Disk. Insert your Rescue Disk into your CD/DVD drive and then enter your password in the Rescue Disk screen.\n\n + 4) If Windows is damaged and cannot start, the VeraCrypt Rescue Disk allows you to permanently decrypt the partition/drive before Windows starts. In the Rescue Disk screen, select 'Repair Options' > 'Permanently decrypt system partition/drive'. Enter the correct password and wait until decryption is complete. Then you can e.g. boot your MS Windows setup CD/DVD to repair your Windows installation.\n\n + Note: Alternatively, if Windows is damaged (cannot start) and you need to repair it (or access files on it), you can avoid decrypting the system partition/drive by following these steps: If you have multiple operating systems installed on your computer, boot the one that does not require pre-boot authentication. If you do not have multiple operating systems installed on your computer, you can boot a WinPE or BartPE CD/DVD or you can connect your system drive as a secondary or external drive to another computer and then boot the operating system installed on the computer. After you boot a system, run VeraCrypt, click 'Select Device', select the affected system partition, click 'OK', select 'System' > 'Mount Without Pre-Boot Authentication', enter your pre-boot authentication password and click 'OK'. The partition will be mounted as a regular VeraCrypt volume (data will be on-the-fly decrypted/encrypted in RAM on access, as usual).\n\n\n + Note that even if you lose your VeraCrypt Rescue Disk and an attacker finds it, he or she will NOT be able to decrypt the system partition or drive without the correct password. + \n\nI M P O R T A N T -- PLEASE PRINT THIS TEXT IF POSSIBLE (click 'Print' below).\n\n\nNote: This text will be automatically displayed each time you start the hidden system until you start creating the decoy system.\n\n\n + How to Create Decoy System Safely and Securely\n----------------------------------------------------------------------------\n\nIn order to achieve plausible deniability, you need to create the decoy operating system now. To do so, follow these steps:\n\n + 1) For security reasons, shut down your computer and leave it powered off for at least several minutes (the longer, the better). This is required to clear the memory, which contains sensitive data. Then turn on the computer but do not boot the hidden system.\n\n + 2) Install Windows on the partition whose content has been erased (i.e. on the partition where the original system, of which the hidden system is a clone, was installed).\n\nIMPORTANT: WHEN YOU START INSTALLING THE DECOY SYSTEM, THE HIDDEN SYSTEM WILL *NOT* BE POSSIBLE TO BOOT (because the VeraCrypt Boot Loader will be erased by the Windows system installer). THIS IS NORMAL AND EXPECTED. PLEASE DO NOT PANIC. YOU WILL BE ABLE TO BOOT THE HIDDEN SYSTEM AGAIN AS SOON AS YOU START ENCRYPTING THE DECOY SYSTEM (because VeraCrypt will then automatically install the VeraCrypt Boot Loader on the system drive).\n\nImportant: The size of the decoy system partition must remain the same as the size of the hidden volume (this condition is now met). Moreover, you must not create any partition between the decoy system partition and the partition where the hidden system resides.\n\n + 3) Boot the decoy system (which you installed in step 2 and install VeraCrypt on it).\n\nKeep in mind that the decoy system must never contain any sensitive data.\n\n + 4) On the decoy system, run VeraCrypt and select 'System' > 'Encrypt System Partition/Drive'. The VeraCrypt Volume Creation Wizard window should appear.\n\nThe following steps apply to the VeraCrypt Volume Creation Wizard.\n\n + 5) In the VeraCrypt Volume Creation Wizard, do NOT select the 'Hidden' option. Leave the 'Normal' option selected and click 'Next'.\n\n + 6) Select the option 'Encrypt the Windows system partition' and then click 'Next'.\n\n + 7) If there are only the hidden system and the decoy system installed on the computer, select the option 'Single-boot' (if there are more than these two systems installed on the computer, select 'Multi-boot'). Then click 'Next'.\n\n + 8) IMPORTANT: In this step, FOR THE DECOY SYSTEM, YOU MUST SELECT THE SAME ENCRYPTION ALGORITHM AND HASH ALGORITHM THAT YOU SELECTED FOR THE HIDDEN SYSTEM! OTHERWISE, THE HIDDEN SYSTEM WILL BE INACCESSIBLE! In other words, the decoy system must be encrypted with the same encryption algorithm as the hidden system. Note: The reason is that the decoy system and the hidden system will share a single boot loader, which supports only a single algorithm, selected by the user (for each algorithm, there is a special version of the VeraCrypt Boot Loader).\n\n + 9) In this step, choose a password for the decoy operating system. This will be the password that you will be able to reveal to an adversary if you are asked or forced to disclose your pre-boot authentication password (the other password you can reveal is the one for the outer volume). The existence of the third password (i.e. of the pre-boot authentication password for the hidden operating system) will remain secret.\n\nImportant: The password you choose for the decoy system must be substantially different from the one you chose for the hidden volume (i.e. for the hidden operating system).\n\n + 10) Follow the remaining instructions in the wizard so as to encrypt the decoy operating system.\n\n\n\n + After Decoy System Is Created\n------------------------------------------------\n\nAfter you encrypt the decoy system, the whole process of creation of the hidden operating system will be completed and you will be able to use these three passwords:\n\n1) Pre-boot authentication password for the hidden operating system.\n\n2) Pre-boot authentication password for the decoy operating system.\n\n3) Password for the outer volume.\n\n + If you want to start the hidden operating system, you will just need to enter the password for the hidden operating system in the VeraCrypt Boot Loader screen (which appears after you turn on or restart your computer).\n\nIf you want to start the decoy operating system, you will just need to enter the password for the decoy operating system in the VeraCrypt Boot Loader screen.\n\nThe password for the decoy system can be disclosed to anyone forcing you to reveal your pre-boot authentication password. The existence of the hidden volume (and of the hidden operating system) will remain secret.\n\n + The third password (for the outer volume) can be disclosed to anyone forcing you to reveal the password for the first partition behind the system partition, where both the outer volume and the hidden volume (containing the hidden operating system) reside. The existence of the hidden volume (and of the hidden operating system) will remain secret.\n\n\n + If you revealed the password for the decoy system to an adversary and he asked you why the free space of the (decoy) system partition contains random data, you could answer, for example: "The partition previously contained a system encrypted by VeraCrypt, but I forgot the pre-boot authentication password (or the system was damaged and stopped booting), so I had to reinstall Windows and encrypt the partition again."\n\n\n + If all the instructions are followed and if the precautions and requirements listed in the section "Security Requirements and Precautions Pertaining to Hidden Volumes" in the VeraCrypt User's Guide are followed, it should be impossible to prove that the hidden volume and hidden operating system exist, even when the outer volume is mounted or when the decoy operating system is decrypted or started.\n\nIf you save a copy of this text or print it (strongly recommended, unless your printer stores copies of documents it prints on its internal drive), you should destroy any copies of it after you have created the decoy system and after you have understood all the information contained in the text (otherwise, if such a copy was found, it might indicate that there is a hidden operating system on this computer).\n\n + WARNING: IF YOU DO NOT PROTECT THE HIDDEN VOLUME (for information on how to do so, refer to the section "Protection of Hidden Volumes Against Damage" in the VeraCrypt User's Guide), DO NOT WRITE TO THE OUTER VOLUME (note that the decoy operating system is NOT installed in the outer volume). OTHERWISE, YOU MAY OVERWRITE AND DAMAGE THE HIDDEN VOLUME (AND THE HIDDEN OPERATING SYSTEM WITHIN IT)! + Operating System Cloning + In the next steps, VeraCrypt will create the hidden operating system by copying the content of the system partition to the hidden volume (data being copied will be encrypted on the fly with an encryption key different from the one that will be used for the decoy operating system).\n\nPlease note that the process will be performed in the pre-boot environment (before Windows starts) and it may take a long time to complete; several hours or even several days (depending on the size of the system partition and on the performance of your computer).\n\nYou will be able to interrupt the process, shut down your computer, start the operating system and then resume the process. However, if you interrupt it, the entire process of copying the system will have to start from the beginning (because the content of the system partition must not change during cloning). + Do you want to cancel the entire process of creation of the hidden operating system?\n\nNote: You will NOT be able to resume the process if you cancel it now. + Do you want to cancel the system encryption pretest? + The VeraCrypt system encryption pretest failed. Do you want to try again?\n\nIf you select 'No', the pre-boot authentication component will be uninstalled.\n\nNotes:\n\n- If the VeraCrypt Boot Loader did not ask you to enter the password before Windows started, it is possible that your operating system does not boot from the drive on which it is installed. This is not supported.\n\n- If you used an encryption algorithm other than AES and the pretest failed (and you entered the password), it may have been caused by an inappropriately designed driver. Select 'No', and try encrypting the system partition/drive again, but use the AES encryption algorithm (which has the lowest memory requirements).\n\n- For more possible causes and solutions, see: https://veracrypt.codeplex.com/wikipage?title=Troubleshooting + The system partition/drive does not appear to be encrypted (neither partially nor fully). + Your system partition/drive is encrypted (partially or fully).\n\nPlease decrypt your system partition/drive entirely before proceeding. To do so, select 'System' > 'Permanently Decrypt System Partition/Drive' from the menu bar of the main VeraCrypt window. + When the system partition/drive is encrypted (partially or fully), you cannot downgrade VeraCrypt (but you can upgrade it or reinstall the same version). + Your system partition/drive is currently being encrypted, decrypted, or otherwise modified. Please interrupt the encryption/decryption/modification process (or wait until it is complete) before proceeding. + An instance of the VeraCrypt Volume Creation Wizard is currently running on this system and performing or preparing encryption/decryption of the system partition/drive. Before you proceed, please wait for it to finish or close it. If you cannot close it, please restart your computer before proceeding. + The process of encryption or decryption of the system partition/drive has not been completed. Please wait until it is complete before proceeding. + Error: The process of encryption of the partition/drive has not been completed. It must be completed first. + Error: The process of encryption or decryption of the partition/volume has not been completed. It must be completed first.\n\nNote: To resume the process, select 'Volumes' > 'Resume Interrupted Process' from the menu bar of the main VeraCrypt window. + The password is correct, VeraCrypt has successfully decrypted the volume header and detected that this volume is a hidden system volume. However, you cannot modify the header of a hidden system volume this way.\n\nTo change the password for a hidden system volume, boot the operating system residing in the hidden volume, and then select 'System' > 'Change Password' from the menu bar of the main VeraCrypt window.\n\nTo set the header key derivation algorithm, boot the hidden operating system and then select 'System' > 'Set Header Key Derivation Algorithm'. + VeraCrypt does not support in-place decryption of a hidden system partition.\n\nNote: If you want to decrypt the decoy system partition, boot the decoy system, and then select 'System' > 'Permanently Decrypt System Partition/Drive' from the menu bar of the main VeraCrypt window. + Error: Incorrect/invalid parameter. + You have selected a partition or a device but the wizard mode you selected is suitable only for file containers.\n\nDo you want to change the wizard mode? + Do you want to create a VeraCrypt file container instead? + You have selected the system partition/drive (or the boot partition), but the wizard mode you selected is suitable only for non-system partitions/drives.\n\nDo you want to set up pre-boot authentication (which means that you will need to enter your password each time before Windows boots/starts) and encrypt the system partition/drive? + Are you sure you want to permanently decrypt the system partition/drive? + CAUTION: If you permanently decrypt the system partition/drive, unencrypted data will be written to it.\n\nAre you really sure you want to permanently decrypt the system partition/drive? + Are you sure you want to permanently decrypt the following volume? + CAUTION: If you permanently decrypt the VeraCrypt volume, unencrypted data will be written to the disk.\n\nAre you really sure you want to permanently decrypt the selected volume? + Warning: If you use a cascade of ciphers for system encryption, you may encounter the following issues:\n\n1) The VeraCrypt Boot Loader is larger than normal and, therefore, there is not enough space in the first drive track for a backup of the VeraCrypt Boot Loader. Hence, whenever it gets damaged (which often happens, for example, during inappropriately designed anti-piracy activation procedures of certain programs), you will need to use the VeraCrypt Rescue Disk to boot or to repair the VeraCrypt Boot Loader.\n\n2) On some computers, resuming from hibernation takes longer.\n\nThese potential issues can be prevented by choosing a non-cascade encryption algorithm (e.g. AES).\n\nAre you sure you want to use a cascade of ciphers? + If you encounter any of the previously described problems, decrypt the partition/drive (if it is encrypted) and then try encrypting it again using a non-cascade encryption algorithm (e.g. AES). + WARNING: For safety and security reasons, you should update VeraCrypt on the decoy operating system before you update it on the hidden operating system.\n\nTo do so, boot the decoy system and run the VeraCrypt installer from within it. Then boot the hidden system and run the installer from within it as well.\n\nNote: The decoy system and the hidden system share a single boot loader. If you upgraded VeraCrypt only on the hidden system (but not on the decoy system), the decoy system would contain a VeraCrypt driver and VeraCrypt applications whose version numbers are different from the version number of the VeraCrypt Boot Loader. Such a discrepancy might indicate that there is a hidden operating system on this computer.\n\n\nDo you want to continue? + The version number of the VeraCrypt Boot Loader that booted this operating system is different from the version number of the VeraCrypt driver (and of the VeraCrypt applications) installed on this system.\n\nYou should run the VeraCrypt installer (whose version number is the same as the one of the VeraCrypt Boot Loader) to update VeraCrypt on this operating system. + The version number of the VeraCrypt Boot Loader that booted this operating system is different from the version number of the VeraCrypt driver (and of the VeraCrypt applications) installed on this system. Note that older versions may contain bugs fixed in later versions.\n\nIf you did not boot from the VeraCrypt Rescue Disk, you should reinstall VeraCrypt or upgrade it to the latest stable version (the boot loader will be updated too).\n\nIf you booted from the VeraCrypt Rescue Disk, you should update it ('System' > 'Create Rescue Disk'). + The VeraCrypt Boot Loader has been upgraded.\n\nIt is strongly recommended that you create a new VeraCrypt Rescue Disk (which will contain the new version of the VeraCrypt Boot Loader) by selecting 'System' > 'Create Rescue Disk' after you restart your computer. + The VeraCrypt Boot Loader has been upgraded.\n\nIt is strongly recommended that you boot the decoy operating system and then create a new VeraCrypt Rescue Disk (which will contain the new version of the VeraCrypt Boot Loader) by selecting 'System' > 'Create Rescue Disk'. + Failed to upgrade the VeraCrypt Boot Loader. + VeraCrypt failed to detect the real size of the system drive and, therefore, the size reported by the operating system (which may be smaller than the real size) will be used. Also note that this is not a bug in VeraCrypt. + WARNING: It appears that VeraCrypt has already tried to detect hidden sectors on this system drive. If you encountered any problems during the previous detection process, you can avoid the problems by skipping the detection of hidden sectors now. Note that if you do so, VeraCrypt will use the size reported by the operating system (which may be smaller than the real size of the drive).\n\nNote that this issue is not caused by a bug in VeraCrypt. + Skip detection of hidden sectors (use the size reported by the operating system) + Try to detect hidden sectors again + Error: Content of one or more sectors on the disk cannot be read (probably due to a physical defect).\n\nThe process of in-place encryption can continue only when the sectors have been made readable again. VeraCrypt can attempt to make these sectors readable by writing zeros to the sectors (subsequently such all-zero blocks would be encrypted). However, note that any data stored in the unreadable sectors will be lost. If you want to avoid that, you can attempt to recover portions of the corrupted data using appropriate third-party tools.\n\nNote: In case of physically damaged sectors (as opposed to mere data corruption and checksum errors) most types of storage devices internally reallocate the sectors when data is attempted to be written to them (so the existing data in the damaged sectors may remain unencrypted on the drive).\n\nDo you want VeraCrypt to write zeroes to unreadable sectors? + Error: Content of one or more sectors on the disk cannot be read (probably due to a physical defect).\n\nTo be able to proceed with decryption, VeraCrypt will have to discard the content of the unreadable sectors (the content will be replaced with pseudorandom data). Please note that, before proceeding, you can attempt to recover portions of any corrupted data using appropriate third-party tools.\n\nDo you want VeraCrypt to discard data in the unreadable sectors now? + Note: VeraCrypt has replaced the content of %I64d unreadable sectors (%s) with encrypted all-zero plaintext blocks. + Note: VeraCrypt has replaced the content of %I64d unreadable sectors (%s) with pseudorandom data. + Enter password/PIN for token '%s': + In order to allow VeraCrypt to access a security token or smart card, you need to install a PKCS #11 software library for the token or smart card first. Such a library may be supplied with the device or it may be available for download from the website of the vendor or other third parties.\n\nAfter you install the library, you can either select it manually by clicking 'Select Library' or you can let VeraCrypt find and select it automatically by clicking 'Auto-Detect Library' (only the Windows system directory will be searched). + Note: For the filename and location of the PKCS #11 library installed for your security token or smart card, please refer to the documentation supplied with the token, card, or third-party software.\n\nClick 'OK' to select the path and filename. + In order to allow VeraCrypt to access a security token or smart card, you need to select a PKCS #11 software library for the token/card first. To do so, select 'Settings' > 'Security Tokens'. + Failed to initialize PKCS #11 security token library.\n\nPlease make sure the specified path and filename refer to a valid PKCS #11 library. To specify a PKCS #11 library path and filename, select 'Settings' > 'Security Tokens'. + No PKCS #11 library has been found in the Windows system directory.\n\nPlease make sure that a PKCS #11 library for your security token (or for your smart card) is installed (such a library may be supplied with the token/card or it may be available for download from the website of the vendor or other third parties). If it is installed in a directory other than the Windows system directory, click 'Select Library' to locate the library (e.g. in the folder where the software for the token/card is installed). + No security token found.\n\nPlease make sure your security token is connected to your computer and the correct device driver for your token is installed. + Security token keyfile not found. + A security token keyfile with the same name already exists. + Do you want to delete the selected files? + Security token keyfile path is invalid. + Security token error + Password for security token is incorrect. + The security token does not have enough memory/space to perform the requested operation.\n\nIf you are attempting to import a keyfile, you should select a smaller file or use a keyfile generated by VeraCrypt (select 'Tools' > 'Keyfile Generator'). + All open security token sessions have been closed. + Select Security Token Keyfiles + Slot + Token name + File name + IMPORTANT: Please note that pre-boot authentication passwords are always typed using the standard US keyboard layout. Therefore, a volume that uses a password typed using any other keyboard layout may be impossible to mount using a pre-boot authentication password (note that this is not a bug in VeraCrypt). To allow such a volume to be mounted using a pre-boot authentication password, follow these steps:\n\n1) Click 'Select File' or 'Select Device' and select the volume.\n2) Select 'Volumes' > 'Change Volume Password'.\n3) Enter the current password for the volume.\n4) Change the keyboard layout to English (US) by clicking the Language bar icon in the Windows taskbar and selecting 'EN English (United States)'.\n5) In VeraCrypt, in the field for the new password, type the pre-boot authentication password.\n6) Confirm the new password by retyping it in the confirmation field and click 'OK'.\nWARNING: Please keep in mind that if you follow these steps, the volume password will always have to be typed using the US keyboard layout (which is automatically ensured only in the pre-boot environment). + System favorite volumes will be mounted using the pre-boot authentication password. If any system favorite volume uses a different password, it will not be mounted. + Please note that if you need to prevent normal VeraCrypt volume actions (such as 'Dismount All', auto-dismount, etc.) from affecting system favorite volumes, you should enable the option 'Allow only administrators to view and dismount system favorite volumes in VeraCrypt'. In addition, when VeraCrypt is run without administrator privileges (the default on Windows Vista and later), system favorite volumes will not be displayed in the drive letter list in the main VeraCrypt application window. + IMPORTANT: Please keep in mind that if this option is enabled and VeraCrypt does not have administrator privileges, mounted system favorite volumes are NOT displayed in the VeraCrypt application window and they cannot be dismounted. Therefore, if you need e.g. to dismount a system favorite volume, please right-click the VeraCrypt icon (in the Start menu) and select 'Run as administrator' first. The same limitation applies to the 'Dismount All' function, 'Auto-Dismount' functions, 'Dismount All' hot keys, etc. + Note that this setting takes effect only after the operating system is restarted. + Error while parsing command line. + Rescue Disk + Select &File and Mount... + Select &Device and Mount... + Allow only administrators to view and dismount system favorite volumes in VeraCrypt + Mount system favorite volumes when Windows starts (in the initial phase of the startup procedure) + Warning: The filesystem on the volume mounted as '%s' was not cleanly dismounted and thus may contain errors. Using a corrupted filesystem can cause data loss or data corruption.\n\nNote: Before you physically remove or switch off a device (such as a USB flash drive or an external hard drive) where a mounted VeraCrypt volume resides, you should always dismount the VeraCrypt volume in VeraCrypt first.\n\n\nDo you want Windows to attempt to detect and fix errors (if any) on the filesystem? + Warning: One or more system favorite volumes were not cleanly dismounted and thus may contain filesystem errors. Please see the system event log for further details.\n\nUsing a corrupted filesystem can cause data loss or data corruption. You should check the affected system favorite volume(s) for errors (right-click each of them in VeraCrypt and select 'Repair Filesystem'). + Warning: Repairing a damaged filesystem using the Microsoft 'chkdsk' tool might cause loss of files in damaged areas. Therefore, it is recommended that you first back up the files stored on the VeraCrypt volume to another, healthy, VeraCrypt volume.\n\nDo you want to repair the filesystem now? + Volume '%s' has been mounted as read-only because write access was denied.\n\nPlease make sure the security permissions of the file container allow you to write to it (right-click the container and select Properties > Security).\n\nNote that, due to a Windows issue, you may see this warning even after setting the appropriate security permissions. This is not caused by a bug in VeraCrypt. A possible solution is to move your container to, e.g., your 'Documents' folder.\n\nIf you intend to keep your volume read-only, set the read-only attribute of the container (right-click the container and select Properties > Read-only), which will suppress this warning. + Volume '%s' had to be mounted as read-only because write access was denied.\n\nPlease make sure no other application (e.g. antivirus software) is accessing the partition/device on which the volume is hosted. + Volume '%s' has been mounted as read-only because the operating system reported the host device to be write-protected.\n\nPlease note that some custom chipset drivers have been reported to cause writable media to falsely appear write-protected. This problem is not caused by VeraCrypt. It may be solved by updating or uninstalling any custom (non-Microsoft) chipset drivers that are currently installed on this system. + Note that the Hyper-Threading technology provides multiple logical cores per a single physical core. When Hyper Threading is enabled, the number selected above represents the number of logical processors/cores. + %d threads + Note that hardware-accelerated AES is disabled, which will affect benchmark results (worse performance).\n\nTo enable hardware acceleration, select 'Settings' > 'Performance' and enable the corresponding option. + Note that the number of threads is currently limited, which will affect benchmark results (worse performance).\n\nTo utilize the full potential of the processor(s), select 'Settings' > 'Performance' and disable the corresponding option. + Do you want VeraCrypt to attempt to disable write protection of the partition/drive? + WARNING: This setting may degrade performance.\n\nAre you sure you want to use this setting? + Warning: VeraCrypt volume auto-dismounted + Before you physically remove or turn off a device containing a mounted volume, you should always dismount the volume in VeraCrypt first.\n\nUnexpected spontaneous dismount is usually caused by an intermittently failing cable, drive (enclosure), etc. + This volume was created with TrueCrypt %x.%x but VeraCrypt supports only TrueCrypt volumes created with TrueCrypt 6.x/7.x series + Test + Keyfile + Backspace + Tab + Clear + Enter + Pause + Caps Lock + Spacebar + Page Up + Page Down + End + Home + Left Arrow + Up Arrow + Right Arrow + Down Arrow + Select Key + Print Key + Execute Key + Print Screen + Insert + Delete + Applications Key + Sleep + Num Lock + Scroll Lock + Browser Back + Browser Forward + Browser Refresh + Browser Stop + Browser Search + Browser Favorites + Browser Home + Mute + Volume Down + Volume Up + Next Track + Previous Track + Stop Media + Play/Pause Media + Start Mail Key + Select Media Key + Application 1 + Application 2 + Attn + CrSel + ExSel + Play + Zoom + NumPad + Shift + Control + Alt + Win + B + KB + MB + GB + TB + PB + B/s + KB/s + MB/s + GB/s + TB/s + PB/s + … + Include &PIM when caching pre-boot authentication password + Include PIM when caching a password + Make disconnected network drives available for mounting + The entered password is too long: its UTF-8 representation exceeds 64 bytes. + The entered password contains Unicode characters that couldn't be converted to UTF-8 representation. + Error: Failed to load a system library. + The volume file size specified in the command line is incompatible with selected exFAT filesystem. + Randomness Collected From Mouse Movements + Volume ID: + Volume ID + Use Volume ID to mount favorite + The Volume ID value is invalid + No Volume with the specified ID was found on the system + Copy Value to Clipboard... + Do not request PIM in the pre-boot authentication screen (PIM value is stored unencrypted on disk) + WARNING: Please keep in mind that if you enable this option, the PIM value will be stored unencrypted on the disk.\n\nAre you sure you want to enable this option? + Personal Iterations Multiplier (PIM) maximum value is 2147468. + Skip Rescue Disk verification + Don't show wait message dialog when performing operations + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Common/Makefile b/src/Common/Makefile index 53b9a3d6..5acbbd24 100644 --- a/src/Common/Makefile +++ b/src/Common/Makefile @@ -1 +1 @@ -!INCLUDE $(NTMAKEENV)\makefile.def +!INCLUDE $(NTMAKEENV)\makefile.def diff --git a/src/Common/Password.c b/src/Common/Password.c index 8a93065d..4d7c7952 100644 --- a/src/Common/Password.c +++ b/src/Common/Password.c @@ -1,491 +1,491 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" - -#include "Crypto.h" -#include "Volumes.h" -#include "Password.h" -#include "Dlgcode.h" -#include "Language.h" -#include "Pkcs5.h" -#include "Endian.h" -#include "Random.h" - -#include - -#ifndef SRC_POS -#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) -#endif - -void VerifyPasswordAndUpdate (HWND hwndDlg, HWND hButton, HWND hPassword, - HWND hVerify, unsigned char *szPassword, - char *szVerify, - BOOL keyFilesEnabled) -{ - wchar_t szTmp1[MAX_PASSWORD + 1]; - wchar_t szTmp2[MAX_PASSWORD + 1]; - char szTmp1Utf8[MAX_PASSWORD + 1]; - char szTmp2Utf8[MAX_PASSWORD + 1]; - int k = GetWindowTextLength (hPassword); - BOOL bEnable = FALSE; - int utf8Len1, utf8Len2; - - UNREFERENCED_PARAMETER (hwndDlg); /* Remove warning */ - - GetWindowText (hPassword, szTmp1, ARRAYSIZE (szTmp1)); - GetWindowText (hVerify, szTmp2, ARRAYSIZE (szTmp2)); - - utf8Len1 = WideCharToMultiByte (CP_UTF8, 0, szTmp1, -1, szTmp1Utf8, MAX_PASSWORD + 1, NULL, NULL); - utf8Len2 = WideCharToMultiByte (CP_UTF8, 0, szTmp2, -1, szTmp2Utf8, MAX_PASSWORD + 1, NULL, NULL); - - if (wcscmp (szTmp1, szTmp2) != 0) - bEnable = FALSE; - else if (utf8Len1 <= 0) - bEnable = FALSE; - else - { - if (k >= MIN_PASSWORD || keyFilesEnabled) - bEnable = TRUE; - else - bEnable = FALSE; - } - - if (szPassword != NULL) - { - if (utf8Len1 > 0) - memcpy (szPassword, szTmp1Utf8, sizeof (szTmp1Utf8)); - else - szPassword [0] = 0; - } - - if (szVerify != NULL) - { - if (utf8Len2 > 0) - memcpy (szVerify, szTmp2Utf8, sizeof (szTmp2Utf8)); - else - szVerify [0] = 0; - } - - burn (szTmp1, sizeof (szTmp1)); - burn (szTmp2, sizeof (szTmp2)); - burn (szTmp1Utf8, sizeof (szTmp1Utf8)); - burn (szTmp2Utf8, sizeof (szTmp2Utf8)); - - EnableWindow (hButton, bEnable); -} - - -BOOL CheckPasswordCharEncoding (HWND hPassword, Password *ptrPw) -{ - int i, len; - - if (hPassword == NULL) - { - if (ptrPw) - { - unsigned char *pw; - len = ptrPw->Length; - pw = (unsigned char *) ptrPw->Text; - - for (i = 0; i < len; i++) - { - if (pw[i] >= 0x7f || pw[i] < 0x20) // A non-ASCII or non-printable character? - return FALSE; - } - } - else - return FALSE; - } - else - { - wchar_t s[MAX_PASSWORD + 1]; - len = GetWindowTextLength (hPassword); - - if (len > MAX_PASSWORD) - return FALSE; - - GetWindowTextW (hPassword, s, sizeof (s) / sizeof (wchar_t)); - - for (i = 0; i < len; i++) - { - if (s[i] >= 0x7f || s[i] < 0x20) // A non-ASCII or non-printable character? - break; - } - - burn (s, sizeof(s)); - - if (i < len) - return FALSE; - } - - return TRUE; -} - - -BOOL CheckPasswordLength (HWND hwndDlg, unsigned __int32 passwordLength, int pim, BOOL bForBoot, BOOL bSkipPasswordWarning, BOOL bSkipPimWarning) -{ - BOOL bCustomPimSmall = ((pim != 0) && (pim < (bForBoot? 98 : 485)))? TRUE : FALSE; - if (passwordLength < PASSWORD_LEN_WARNING) - { - if (bCustomPimSmall) - { - Error (bForBoot? "BOOT_PIM_REQUIRE_LONG_PASSWORD": "PIM_REQUIRE_LONG_PASSWORD", hwndDlg); - return FALSE; - } - -#ifndef _DEBUG - if (!bSkipPasswordWarning && (MessageBoxW (hwndDlg, GetString ("PASSWORD_LENGTH_WARNING"), lpszTitle, MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2) != IDYES)) - return FALSE; -#endif - } -#ifndef _DEBUG - else if (bCustomPimSmall) - { - if (!bSkipPimWarning && AskWarnNoYes ("PIM_SMALL_WARNING", hwndDlg) != IDYES) - return FALSE; - } -#endif - - if ((pim != 0) && (pim > (bForBoot? 98 : 485))) - { - // warn that mount/boot will take more time - Warning ("PIM_LARGE_WARNING", hwndDlg); - - } - return TRUE; -} - -int ChangePwd (const wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg) -{ - int nDosLinkCreated = 1, nStatus = ERR_OS_ERROR; - wchar_t szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH]; - wchar_t szDosDevice[TC_MAX_PATH]; - char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; - PCRYPTO_INFO cryptoInfo = NULL, ci = NULL; - void *dev = INVALID_HANDLE_VALUE; - DWORD dwError; - DWORD bytesRead; - BOOL bDevice; - unsigned __int64 hostSize = 0; - int volumeType; - int wipePass; - FILETIME ftCreationTime; - FILETIME ftLastWriteTime; - FILETIME ftLastAccessTime; - BOOL bTimeStampValid = FALSE; - LARGE_INTEGER headerOffset; - BOOL backupHeader; - DISK_GEOMETRY driveInfo; - - if (oldPassword->Length == 0 || newPassword->Length == 0) return -1; - - if ((wipePassCount <= 0) || (truecryptMode && (old_pkcs5 == SHA256))) - { - nStatus = ERR_PARAMETER_INCORRECT; - handleError (hwndDlg, nStatus, SRC_POS); - return nStatus; - } - - if (!lpszVolume) - { - nStatus = ERR_OUTOFMEMORY; - handleError (hwndDlg, nStatus, SRC_POS); - return nStatus; - } - - WaitCursor (); - - CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), lpszVolume, &bDevice); - - if (bDevice == FALSE) - { - wcscpy (szCFDevice, szDiskFile); - } - else - { - nDosLinkCreated = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice), szCFDevice, sizeof(szCFDevice),FALSE); - - if (nDosLinkCreated != 0) - goto error; - } - - dev = CreateFile (szCFDevice, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (dev == INVALID_HANDLE_VALUE) - goto error; - - if (bDevice) - { - /* This is necessary to determine the hidden volume header offset */ - - if (dev == INVALID_HANDLE_VALUE) - { - goto error; - } - else - { - PARTITION_INFORMATION diskInfo; - DWORD dwResult; - BOOL bResult; - - bResult = DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, - &driveInfo, sizeof (driveInfo), &dwResult, NULL); - - if (!bResult) - goto error; - - bResult = GetPartitionInfo (lpszVolume, &diskInfo); - - if (bResult) - { - hostSize = diskInfo.PartitionLength.QuadPart; - } - else - { - hostSize = driveInfo.Cylinders.QuadPart * driveInfo.BytesPerSector * - driveInfo.SectorsPerTrack * driveInfo.TracksPerCylinder; - } - - if (hostSize == 0) - { - nStatus = ERR_VOL_SIZE_WRONG; - goto error; - } - } - } - else - { - LARGE_INTEGER fileSize; - if (!GetFileSizeEx (dev, &fileSize)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - hostSize = fileSize.QuadPart; - } - - if (Randinit ()) - { - if (CryptoAPILastError == ERROR_SUCCESS) - nStatus = ERR_RAND_INIT_FAILED; - else - nStatus = ERR_CAPI_INIT_FAILED; - goto error; - } - - SetRandomPoolEnrichedByUserStatus (FALSE); /* force the display of the random enriching dialog */ - - if (!bDevice && bPreserveTimestamp) - { - if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0) - bTimeStampValid = FALSE; - else - bTimeStampValid = TRUE; - } - - for (volumeType = TC_VOLUME_TYPE_NORMAL; volumeType < TC_VOLUME_TYPE_COUNT; volumeType++) - { - // Seek the volume header - switch (volumeType) - { - case TC_VOLUME_TYPE_NORMAL: - headerOffset.QuadPart = TC_VOLUME_HEADER_OFFSET; - break; - - case TC_VOLUME_TYPE_HIDDEN: - if (TC_HIDDEN_VOLUME_HEADER_OFFSET + TC_VOLUME_HEADER_SIZE > hostSize) - continue; - - headerOffset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET; - break; - - } - - if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - /* Read in volume header */ - if (!ReadEffectiveVolumeHeader (bDevice, dev, buffer, &bytesRead)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - if (bytesRead != sizeof (buffer)) - { - // Windows may report EOF when reading sectors from the last cluster of a device formatted as NTFS - memset (buffer, 0, sizeof (buffer)); - } - - /* Try to decrypt the header */ - - nStatus = ReadVolumeHeader (FALSE, buffer, oldPassword, old_pkcs5, old_pim, truecryptMode, &cryptoInfo, NULL); - if (nStatus == ERR_CIPHER_INIT_WEAK_KEY) - nStatus = 0; // We can ignore this error here - - if (nStatus == ERR_PASSWORD_WRONG) - { - continue; // Try next volume type - } - else if (nStatus != 0) - { - cryptoInfo = NULL; - goto error; - } - else - break; - } - - if (nStatus != 0) - { - cryptoInfo = NULL; - goto error; - } - - if (cryptoInfo->HeaderFlags & TC_HEADER_FLAG_ENCRYPTED_SYSTEM) - { - nStatus = ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG; - goto error; - } - - // Change the PKCS-5 PRF if requested by user - if (pkcs5 != 0) - cryptoInfo->pkcs5 = pkcs5; - - RandSetHashFunction (cryptoInfo->pkcs5); - - NormalCursor(); - UserEnrichRandomPool (hwndDlg); - EnableElevatedCursorChange (hwndDlg); - WaitCursor(); - - /* Re-encrypt the volume header */ - backupHeader = FALSE; - - while (TRUE) - { - /* The header will be re-encrypted wipePassCount times to prevent adversaries from using - techniques such as magnetic force microscopy or magnetic force scanning tunnelling microscopy - to recover the overwritten header. According to Peter Gutmann, data should be overwritten 22 - times (ideally, 35 times) using non-random patterns and pseudorandom data. However, as users might - impatiently interupt the process (etc.) we will not use the Gutmann's patterns but will write the - valid re-encrypted header, i.e. pseudorandom data, and there will be many more passes than Guttman - recommends. During each pass we will write a valid working header. Each pass will use the same master - key, and also the same header key, secondary key (XTS), etc., derived from the new password. The only - item that will be different for each pass will be the salt. This is sufficient to cause each "version" - of the header to differ substantially and in a random manner from the versions written during the - other passes. */ - - for (wipePass = 0; wipePass < wipePassCount; wipePass++) - { - // Prepare new volume header - nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE, - buffer, - cryptoInfo->ea, - cryptoInfo->mode, - newPassword, - cryptoInfo->pkcs5, - pim, - cryptoInfo->master_keydata, - &ci, - cryptoInfo->VolumeSize.Value, - (volumeType == TC_VOLUME_TYPE_HIDDEN) ? cryptoInfo->hiddenVolumeSize : 0, - cryptoInfo->EncryptedAreaStart.Value, - cryptoInfo->EncryptedAreaLength.Value, - truecryptMode? 0 : cryptoInfo->RequiredProgramVersion, - cryptoInfo->HeaderFlags, - cryptoInfo->SectorSize, - wipePass < wipePassCount - 1); - - if (ci != NULL) - crypto_close (ci); - - if (nStatus != 0) - goto error; - - if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - if (!WriteEffectiveVolumeHeader (bDevice, dev, buffer)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - if (bDevice - && !cryptoInfo->LegacyVolume - && !cryptoInfo->hiddenVolume - && cryptoInfo->HeaderVersion == 4 - && (cryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) != 0 - && (cryptoInfo->HeaderFlags & ~TC_HEADER_FLAG_NONSYS_INPLACE_ENC) == 0) - { - nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, cryptoInfo->VolumeSize.Value, !backupHeader, backupHeader); - if (nStatus != ERR_SUCCESS) - goto error; - } - - FlushFileBuffers (dev); - } - - if (backupHeader || cryptoInfo->LegacyVolume) - break; - - backupHeader = TRUE; - headerOffset.QuadPart += hostSize - TC_VOLUME_HEADER_GROUP_SIZE; - } - - /* Password successfully changed */ - nStatus = 0; - -error: - dwError = GetLastError (); - - burn (buffer, sizeof (buffer)); - - if (cryptoInfo != NULL) - crypto_close (cryptoInfo); - - if (bTimeStampValid) - SetFileTime (dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime); - - if (dev != INVALID_HANDLE_VALUE) - CloseHandle ((HANDLE) dev); - - if (nDosLinkCreated == 0) - RemoveFakeDosName (szDiskFile, szDosDevice); - - RandStop (FALSE); - NormalCursor (); - - SetLastError (dwError); - - if (nStatus == ERR_OS_ERROR && dwError == ERROR_ACCESS_DENIED - && bDevice - && !UacElevated - && IsUacSupported ()) - return nStatus; - - if (nStatus != 0) - handleError (hwndDlg, nStatus, SRC_POS); - - return nStatus; -} - +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" + +#include "Crypto.h" +#include "Volumes.h" +#include "Password.h" +#include "Dlgcode.h" +#include "Language.h" +#include "Pkcs5.h" +#include "Endian.h" +#include "Random.h" + +#include + +#ifndef SRC_POS +#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) +#endif + +void VerifyPasswordAndUpdate (HWND hwndDlg, HWND hButton, HWND hPassword, + HWND hVerify, unsigned char *szPassword, + char *szVerify, + BOOL keyFilesEnabled) +{ + wchar_t szTmp1[MAX_PASSWORD + 1]; + wchar_t szTmp2[MAX_PASSWORD + 1]; + char szTmp1Utf8[MAX_PASSWORD + 1]; + char szTmp2Utf8[MAX_PASSWORD + 1]; + int k = GetWindowTextLength (hPassword); + BOOL bEnable = FALSE; + int utf8Len1, utf8Len2; + + UNREFERENCED_PARAMETER (hwndDlg); /* Remove warning */ + + GetWindowText (hPassword, szTmp1, ARRAYSIZE (szTmp1)); + GetWindowText (hVerify, szTmp2, ARRAYSIZE (szTmp2)); + + utf8Len1 = WideCharToMultiByte (CP_UTF8, 0, szTmp1, -1, szTmp1Utf8, MAX_PASSWORD + 1, NULL, NULL); + utf8Len2 = WideCharToMultiByte (CP_UTF8, 0, szTmp2, -1, szTmp2Utf8, MAX_PASSWORD + 1, NULL, NULL); + + if (wcscmp (szTmp1, szTmp2) != 0) + bEnable = FALSE; + else if (utf8Len1 <= 0) + bEnable = FALSE; + else + { + if (k >= MIN_PASSWORD || keyFilesEnabled) + bEnable = TRUE; + else + bEnable = FALSE; + } + + if (szPassword != NULL) + { + if (utf8Len1 > 0) + memcpy (szPassword, szTmp1Utf8, sizeof (szTmp1Utf8)); + else + szPassword [0] = 0; + } + + if (szVerify != NULL) + { + if (utf8Len2 > 0) + memcpy (szVerify, szTmp2Utf8, sizeof (szTmp2Utf8)); + else + szVerify [0] = 0; + } + + burn (szTmp1, sizeof (szTmp1)); + burn (szTmp2, sizeof (szTmp2)); + burn (szTmp1Utf8, sizeof (szTmp1Utf8)); + burn (szTmp2Utf8, sizeof (szTmp2Utf8)); + + EnableWindow (hButton, bEnable); +} + + +BOOL CheckPasswordCharEncoding (HWND hPassword, Password *ptrPw) +{ + int i, len; + + if (hPassword == NULL) + { + if (ptrPw) + { + unsigned char *pw; + len = ptrPw->Length; + pw = (unsigned char *) ptrPw->Text; + + for (i = 0; i < len; i++) + { + if (pw[i] >= 0x7f || pw[i] < 0x20) // A non-ASCII or non-printable character? + return FALSE; + } + } + else + return FALSE; + } + else + { + wchar_t s[MAX_PASSWORD + 1]; + len = GetWindowTextLength (hPassword); + + if (len > MAX_PASSWORD) + return FALSE; + + GetWindowTextW (hPassword, s, sizeof (s) / sizeof (wchar_t)); + + for (i = 0; i < len; i++) + { + if (s[i] >= 0x7f || s[i] < 0x20) // A non-ASCII or non-printable character? + break; + } + + burn (s, sizeof(s)); + + if (i < len) + return FALSE; + } + + return TRUE; +} + + +BOOL CheckPasswordLength (HWND hwndDlg, unsigned __int32 passwordLength, int pim, BOOL bForBoot, BOOL bSkipPasswordWarning, BOOL bSkipPimWarning) +{ + BOOL bCustomPimSmall = ((pim != 0) && (pim < (bForBoot? 98 : 485)))? TRUE : FALSE; + if (passwordLength < PASSWORD_LEN_WARNING) + { + if (bCustomPimSmall) + { + Error (bForBoot? "BOOT_PIM_REQUIRE_LONG_PASSWORD": "PIM_REQUIRE_LONG_PASSWORD", hwndDlg); + return FALSE; + } + +#ifndef _DEBUG + if (!bSkipPasswordWarning && (MessageBoxW (hwndDlg, GetString ("PASSWORD_LENGTH_WARNING"), lpszTitle, MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2) != IDYES)) + return FALSE; +#endif + } +#ifndef _DEBUG + else if (bCustomPimSmall) + { + if (!bSkipPimWarning && AskWarnNoYes ("PIM_SMALL_WARNING", hwndDlg) != IDYES) + return FALSE; + } +#endif + + if ((pim != 0) && (pim > (bForBoot? 98 : 485))) + { + // warn that mount/boot will take more time + Warning ("PIM_LARGE_WARNING", hwndDlg); + + } + return TRUE; +} + +int ChangePwd (const wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg) +{ + int nDosLinkCreated = 1, nStatus = ERR_OS_ERROR; + wchar_t szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH]; + wchar_t szDosDevice[TC_MAX_PATH]; + char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; + PCRYPTO_INFO cryptoInfo = NULL, ci = NULL; + void *dev = INVALID_HANDLE_VALUE; + DWORD dwError; + DWORD bytesRead; + BOOL bDevice; + unsigned __int64 hostSize = 0; + int volumeType; + int wipePass; + FILETIME ftCreationTime; + FILETIME ftLastWriteTime; + FILETIME ftLastAccessTime; + BOOL bTimeStampValid = FALSE; + LARGE_INTEGER headerOffset; + BOOL backupHeader; + DISK_GEOMETRY driveInfo; + + if (oldPassword->Length == 0 || newPassword->Length == 0) return -1; + + if ((wipePassCount <= 0) || (truecryptMode && (old_pkcs5 == SHA256))) + { + nStatus = ERR_PARAMETER_INCORRECT; + handleError (hwndDlg, nStatus, SRC_POS); + return nStatus; + } + + if (!lpszVolume) + { + nStatus = ERR_OUTOFMEMORY; + handleError (hwndDlg, nStatus, SRC_POS); + return nStatus; + } + + WaitCursor (); + + CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), lpszVolume, &bDevice); + + if (bDevice == FALSE) + { + wcscpy (szCFDevice, szDiskFile); + } + else + { + nDosLinkCreated = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice), szCFDevice, sizeof(szCFDevice),FALSE); + + if (nDosLinkCreated != 0) + goto error; + } + + dev = CreateFile (szCFDevice, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (dev == INVALID_HANDLE_VALUE) + goto error; + + if (bDevice) + { + /* This is necessary to determine the hidden volume header offset */ + + if (dev == INVALID_HANDLE_VALUE) + { + goto error; + } + else + { + PARTITION_INFORMATION diskInfo; + DWORD dwResult; + BOOL bResult; + + bResult = DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, + &driveInfo, sizeof (driveInfo), &dwResult, NULL); + + if (!bResult) + goto error; + + bResult = GetPartitionInfo (lpszVolume, &diskInfo); + + if (bResult) + { + hostSize = diskInfo.PartitionLength.QuadPart; + } + else + { + hostSize = driveInfo.Cylinders.QuadPart * driveInfo.BytesPerSector * + driveInfo.SectorsPerTrack * driveInfo.TracksPerCylinder; + } + + if (hostSize == 0) + { + nStatus = ERR_VOL_SIZE_WRONG; + goto error; + } + } + } + else + { + LARGE_INTEGER fileSize; + if (!GetFileSizeEx (dev, &fileSize)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + hostSize = fileSize.QuadPart; + } + + if (Randinit ()) + { + if (CryptoAPILastError == ERROR_SUCCESS) + nStatus = ERR_RAND_INIT_FAILED; + else + nStatus = ERR_CAPI_INIT_FAILED; + goto error; + } + + SetRandomPoolEnrichedByUserStatus (FALSE); /* force the display of the random enriching dialog */ + + if (!bDevice && bPreserveTimestamp) + { + if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0) + bTimeStampValid = FALSE; + else + bTimeStampValid = TRUE; + } + + for (volumeType = TC_VOLUME_TYPE_NORMAL; volumeType < TC_VOLUME_TYPE_COUNT; volumeType++) + { + // Seek the volume header + switch (volumeType) + { + case TC_VOLUME_TYPE_NORMAL: + headerOffset.QuadPart = TC_VOLUME_HEADER_OFFSET; + break; + + case TC_VOLUME_TYPE_HIDDEN: + if (TC_HIDDEN_VOLUME_HEADER_OFFSET + TC_VOLUME_HEADER_SIZE > hostSize) + continue; + + headerOffset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET; + break; + + } + + if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + /* Read in volume header */ + if (!ReadEffectiveVolumeHeader (bDevice, dev, buffer, &bytesRead)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + if (bytesRead != sizeof (buffer)) + { + // Windows may report EOF when reading sectors from the last cluster of a device formatted as NTFS + memset (buffer, 0, sizeof (buffer)); + } + + /* Try to decrypt the header */ + + nStatus = ReadVolumeHeader (FALSE, buffer, oldPassword, old_pkcs5, old_pim, truecryptMode, &cryptoInfo, NULL); + if (nStatus == ERR_CIPHER_INIT_WEAK_KEY) + nStatus = 0; // We can ignore this error here + + if (nStatus == ERR_PASSWORD_WRONG) + { + continue; // Try next volume type + } + else if (nStatus != 0) + { + cryptoInfo = NULL; + goto error; + } + else + break; + } + + if (nStatus != 0) + { + cryptoInfo = NULL; + goto error; + } + + if (cryptoInfo->HeaderFlags & TC_HEADER_FLAG_ENCRYPTED_SYSTEM) + { + nStatus = ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG; + goto error; + } + + // Change the PKCS-5 PRF if requested by user + if (pkcs5 != 0) + cryptoInfo->pkcs5 = pkcs5; + + RandSetHashFunction (cryptoInfo->pkcs5); + + NormalCursor(); + UserEnrichRandomPool (hwndDlg); + EnableElevatedCursorChange (hwndDlg); + WaitCursor(); + + /* Re-encrypt the volume header */ + backupHeader = FALSE; + + while (TRUE) + { + /* The header will be re-encrypted wipePassCount times to prevent adversaries from using + techniques such as magnetic force microscopy or magnetic force scanning tunnelling microscopy + to recover the overwritten header. According to Peter Gutmann, data should be overwritten 22 + times (ideally, 35 times) using non-random patterns and pseudorandom data. However, as users might + impatiently interupt the process (etc.) we will not use the Gutmann's patterns but will write the + valid re-encrypted header, i.e. pseudorandom data, and there will be many more passes than Guttman + recommends. During each pass we will write a valid working header. Each pass will use the same master + key, and also the same header key, secondary key (XTS), etc., derived from the new password. The only + item that will be different for each pass will be the salt. This is sufficient to cause each "version" + of the header to differ substantially and in a random manner from the versions written during the + other passes. */ + + for (wipePass = 0; wipePass < wipePassCount; wipePass++) + { + // Prepare new volume header + nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE, + buffer, + cryptoInfo->ea, + cryptoInfo->mode, + newPassword, + cryptoInfo->pkcs5, + pim, + cryptoInfo->master_keydata, + &ci, + cryptoInfo->VolumeSize.Value, + (volumeType == TC_VOLUME_TYPE_HIDDEN) ? cryptoInfo->hiddenVolumeSize : 0, + cryptoInfo->EncryptedAreaStart.Value, + cryptoInfo->EncryptedAreaLength.Value, + truecryptMode? 0 : cryptoInfo->RequiredProgramVersion, + cryptoInfo->HeaderFlags, + cryptoInfo->SectorSize, + wipePass < wipePassCount - 1); + + if (ci != NULL) + crypto_close (ci); + + if (nStatus != 0) + goto error; + + if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + if (!WriteEffectiveVolumeHeader (bDevice, dev, buffer)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + if (bDevice + && !cryptoInfo->LegacyVolume + && !cryptoInfo->hiddenVolume + && cryptoInfo->HeaderVersion == 4 + && (cryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) != 0 + && (cryptoInfo->HeaderFlags & ~TC_HEADER_FLAG_NONSYS_INPLACE_ENC) == 0) + { + nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, cryptoInfo->VolumeSize.Value, !backupHeader, backupHeader); + if (nStatus != ERR_SUCCESS) + goto error; + } + + FlushFileBuffers (dev); + } + + if (backupHeader || cryptoInfo->LegacyVolume) + break; + + backupHeader = TRUE; + headerOffset.QuadPart += hostSize - TC_VOLUME_HEADER_GROUP_SIZE; + } + + /* Password successfully changed */ + nStatus = 0; + +error: + dwError = GetLastError (); + + burn (buffer, sizeof (buffer)); + + if (cryptoInfo != NULL) + crypto_close (cryptoInfo); + + if (bTimeStampValid) + SetFileTime (dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime); + + if (dev != INVALID_HANDLE_VALUE) + CloseHandle ((HANDLE) dev); + + if (nDosLinkCreated == 0) + RemoveFakeDosName (szDiskFile, szDosDevice); + + RandStop (FALSE); + NormalCursor (); + + SetLastError (dwError); + + if (nStatus == ERR_OS_ERROR && dwError == ERROR_ACCESS_DENIED + && bDevice + && !UacElevated + && IsUacSupported ()) + return nStatus; + + if (nStatus != 0) + handleError (hwndDlg, nStatus, SRC_POS); + + return nStatus; +} + diff --git a/src/Common/Password.h b/src/Common/Password.h index e2058cdb..8cc0b7ea 100644 --- a/src/Common/Password.h +++ b/src/Common/Password.h @@ -1,52 +1,52 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifndef PASSWORD_H -#define PASSWORD_H - -// User text input limits -#define MIN_PASSWORD 1 // Minimum possible password length -#define MAX_PASSWORD 64 // Maximum possible password length -#define MAX_PIM 7 // Maximum allowed digits in a PIM (enough for maximum value) -#define MAX_PIM_VALUE 2147468 // Maximum value to have a positive 32-bit result for formula 15000 + (PIM x 1000) -#define MAX_BOOT_PIM 5 // Maximum allowed digits in a PIM for boot (enough for 16-bit value) -#define MAX_BOOT_PIM_VALUE 65535 - -#define PASSWORD_LEN_WARNING 20 // Display a warning when a password is shorter than this - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct -{ - // Modifying this structure can introduce incompatibility with previous versions - unsigned __int32 Length; - unsigned char Text[MAX_PASSWORD + 1]; - char Pad[3]; // keep 64-bit alignment -} Password; - -#if defined(_WIN32) && !defined(TC_WINDOWS_DRIVER) - -void VerifyPasswordAndUpdate ( HWND hwndDlg , HWND hButton , HWND hPassword , HWND hVerify , unsigned char *szPassword , char *szVerify, BOOL keyFilesEnabled ); -BOOL CheckPasswordLength (HWND hwndDlg, unsigned __int32 passwordLength, int pim, BOOL bForBoot, BOOL bSkipPasswordWarning, BOOL bSkipPimWarning); -BOOL CheckPasswordCharEncoding (HWND hPassword, Password *ptrPw); -int ChangePwd (const wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg); - -#endif // defined(_WIN32) && !defined(TC_WINDOWS_DRIVER) - -#ifdef __cplusplus -} -#endif - -#endif // PASSWORD_H +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifndef PASSWORD_H +#define PASSWORD_H + +// User text input limits +#define MIN_PASSWORD 1 // Minimum possible password length +#define MAX_PASSWORD 64 // Maximum possible password length +#define MAX_PIM 7 // Maximum allowed digits in a PIM (enough for maximum value) +#define MAX_PIM_VALUE 2147468 // Maximum value to have a positive 32-bit result for formula 15000 + (PIM x 1000) +#define MAX_BOOT_PIM 5 // Maximum allowed digits in a PIM for boot (enough for 16-bit value) +#define MAX_BOOT_PIM_VALUE 65535 + +#define PASSWORD_LEN_WARNING 20 // Display a warning when a password is shorter than this + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct +{ + // Modifying this structure can introduce incompatibility with previous versions + unsigned __int32 Length; + unsigned char Text[MAX_PASSWORD + 1]; + char Pad[3]; // keep 64-bit alignment +} Password; + +#if defined(_WIN32) && !defined(TC_WINDOWS_DRIVER) + +void VerifyPasswordAndUpdate ( HWND hwndDlg , HWND hButton , HWND hPassword , HWND hVerify , unsigned char *szPassword , char *szVerify, BOOL keyFilesEnabled ); +BOOL CheckPasswordLength (HWND hwndDlg, unsigned __int32 passwordLength, int pim, BOOL bForBoot, BOOL bSkipPasswordWarning, BOOL bSkipPimWarning); +BOOL CheckPasswordCharEncoding (HWND hPassword, Password *ptrPw); +int ChangePwd (const wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg); + +#endif // defined(_WIN32) && !defined(TC_WINDOWS_DRIVER) + +#ifdef __cplusplus +} +#endif + +#endif // PASSWORD_H diff --git a/src/Common/Pkcs5.c b/src/Common/Pkcs5.c index 1dadb1e9..a71be573 100644 --- a/src/Common/Pkcs5.c +++ b/src/Common/Pkcs5.c @@ -1,960 +1,960 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" - -#include -#include -#include "Rmd160.h" -#ifndef TC_WINDOWS_BOOT -#include "Sha2.h" -#include "Whirlpool.h" -#include "misc.h" -#else -#pragma optimize ("t", on) -#include -#if defined( _MSC_VER ) -# ifndef DEBUG -# pragma intrinsic( memcpy ) -# pragma intrinsic( memset ) -# endif -#endif -#include "Sha2Small.h" -#endif -#include "Pkcs5.h" -#include "Crypto.h" - -void hmac_truncate - ( - char *d1, /* data to be truncated */ - char *d2, /* truncated data */ - int len /* length in bytes to keep */ -) -{ - int i; - for (i = 0; i < len; i++) - d2[i] = d1[i]; -} - -#if !defined(TC_WINDOWS_BOOT) || defined(TC_WINDOWS_BOOT_SHA2) - -typedef struct hmac_sha256_ctx_struct -{ - sha256_ctx ctx; - sha256_ctx inner_digest_ctx; /*pre-computed inner digest context */ - sha256_ctx outer_digest_ctx; /*pre-computed outer digest context */ - char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the SHA256 hash */ - char u[SHA256_DIGESTSIZE]; -} hmac_sha256_ctx; - -void hmac_sha256_internal -( - char *k, /* secret key. It's ensured to be always <= 32 bytes */ - int lk, /* length of the key in bytes */ - char *d, /* input data. d pointer is guaranteed to be at least 32-bytes long */ - int ld, /* length of input data in bytes */ - hmac_sha256_ctx* hmac /* HMAC-SHA256 context which holds temporary variables */ -) -{ - sha256_ctx* ctx = &(hmac->ctx); - - /**** Restore Precomputed Inner Digest Context ****/ - - memcpy (ctx, &(hmac->inner_digest_ctx), sizeof (sha256_ctx)); - - sha256_hash ((unsigned char *) d, ld, ctx); - - sha256_end ((unsigned char *) d, ctx); /* d = inner digest */ - - /**** Restore Precomputed Outer Digest Context ****/ - - memcpy (ctx, &(hmac->outer_digest_ctx), sizeof (sha256_ctx)); - - sha256_hash ((unsigned char *) d, SHA256_DIGESTSIZE, ctx); - - sha256_end ((unsigned char *) d, ctx); /* d = outer digest */ -} - -#ifndef TC_WINDOWS_BOOT -void hmac_sha256 -( - char *k, /* secret key */ - int lk, /* length of the key in bytes */ - char *d, /* data */ - int ld /* length of data in bytes */ -) -{ - hmac_sha256_ctx hmac; - sha256_ctx* ctx; - char* buf = hmac.k; - int b; - char key[SHA256_DIGESTSIZE]; - /* If the key is longer than the hash algorithm block size, - let key = sha256(key), as per HMAC specifications. */ - if (lk > SHA256_BLOCKSIZE) - { - sha256_ctx tctx; - - sha256_begin (&tctx); - sha256_hash ((unsigned char *) k, lk, &tctx); - sha256_end ((unsigned char *) key, &tctx); - - k = key; - lk = SHA256_DIGESTSIZE; - - burn (&tctx, sizeof(tctx)); // Prevent leaks - } - - /**** Precompute HMAC Inner Digest ****/ - - ctx = &(hmac.inner_digest_ctx); - sha256_begin (ctx); - - /* Pad the key for inner digest */ - for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x36); - memset (&buf[lk], 0x36, SHA256_BLOCKSIZE - lk); - - sha256_hash ((unsigned char *) buf, SHA256_BLOCKSIZE, ctx); - - /**** Precompute HMAC Outer Digest ****/ - - ctx = &(hmac.outer_digest_ctx); - sha256_begin (ctx); - - for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x5C); - memset (&buf[lk], 0x5C, SHA256_BLOCKSIZE - lk); - - sha256_hash ((unsigned char *) buf, SHA256_BLOCKSIZE, ctx); - - hmac_sha256_internal(k, lk, d, ld, &hmac); - /* Prevent leaks */ - burn(&hmac, sizeof(hmac)); - burn(key, sizeof(key)); -} -#endif - -static void derive_u_sha256 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, int b, hmac_sha256_ctx* hmac) -{ - char* k = hmac->k; - char* u = hmac->u; - uint32 c; - int i; - -#ifdef TC_WINDOWS_BOOT - /* In bootloader mode, least significant bit of iterations is a boolean (TRUE for boot derivation mode, FALSE otherwise) - * and the most significant 16 bits hold the pim value - * This enables us to save code space needed for implementing other features. - */ - c = iterations >> 16; - i = ((int) iterations) & 0x01; - if (i) - c = (c == 0)? 200000 : c << 11; - else - c = (c == 0)? 500000 : 15000 + c * 1000; -#else - c = iterations; -#endif - - /* iteration 1 */ - memcpy (k, salt, salt_len); /* salt */ - - /* big-endian block number */ - memset (&k[salt_len], 0, 3); - k[salt_len + 3] = (char) b; - - hmac_sha256_internal (pwd, pwd_len, k, salt_len + 4, hmac); - memcpy (u, k, SHA256_DIGESTSIZE); - - /* remaining iterations */ - while (c > 1) - { - hmac_sha256_internal (pwd, pwd_len, k, SHA256_DIGESTSIZE, hmac); - for (i = 0; i < SHA256_DIGESTSIZE; i++) - { - u[i] ^= k[i]; - } - c--; - } -} - - -void derive_key_sha256 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) -{ - hmac_sha256_ctx hmac; - sha256_ctx* ctx; - char* buf = hmac.k; - int b, l, r; -#ifndef TC_WINDOWS_BOOT - char key[SHA256_DIGESTSIZE]; - /* If the password is longer than the hash algorithm block size, - let pwd = sha256(pwd), as per HMAC specifications. */ - if (pwd_len > SHA256_BLOCKSIZE) - { - sha256_ctx tctx; - - sha256_begin (&tctx); - sha256_hash ((unsigned char *) pwd, pwd_len, &tctx); - sha256_end ((unsigned char *) key, &tctx); - - pwd = key; - pwd_len = SHA256_DIGESTSIZE; - - burn (&tctx, sizeof(tctx)); // Prevent leaks - } -#endif - - if (dklen % SHA256_DIGESTSIZE) - { - l = 1 + dklen / SHA256_DIGESTSIZE; - } - else - { - l = dklen / SHA256_DIGESTSIZE; - } - - r = dklen - (l - 1) * SHA256_DIGESTSIZE; - - /**** Precompute HMAC Inner Digest ****/ - - ctx = &(hmac.inner_digest_ctx); - sha256_begin (ctx); - - /* Pad the key for inner digest */ - for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x36); - memset (&buf[pwd_len], 0x36, SHA256_BLOCKSIZE - pwd_len); - - sha256_hash ((unsigned char *) buf, SHA256_BLOCKSIZE, ctx); - - /**** Precompute HMAC Outer Digest ****/ - - ctx = &(hmac.outer_digest_ctx); - sha256_begin (ctx); - - for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x5C); - memset (&buf[pwd_len], 0x5C, SHA256_BLOCKSIZE - pwd_len); - - sha256_hash ((unsigned char *) buf, SHA256_BLOCKSIZE, ctx); - - /* first l - 1 blocks */ - for (b = 1; b < l; b++) - { - derive_u_sha256 (pwd, pwd_len, salt, salt_len, iterations, b, &hmac); - memcpy (dk, hmac.u, SHA256_DIGESTSIZE); - dk += SHA256_DIGESTSIZE; - } - - /* last block */ - derive_u_sha256 (pwd, pwd_len, salt, salt_len, iterations, b, &hmac); - memcpy (dk, hmac.u, r); - - - /* Prevent possible leaks. */ - burn (&hmac, sizeof(hmac)); -#ifndef TC_WINDOWS_BOOT - burn (key, sizeof(key)); -#endif -} - -#endif - -#ifndef TC_WINDOWS_BOOT - -typedef struct hmac_sha512_ctx_struct -{ - sha512_ctx ctx; - sha512_ctx inner_digest_ctx; /*pre-computed inner digest context */ - sha512_ctx outer_digest_ctx; /*pre-computed outer digest context */ - char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the SHA512 hash */ - char u[SHA512_DIGESTSIZE]; -} hmac_sha512_ctx; - -void hmac_sha512_internal -( - char *k, /* secret key */ - int lk, /* length of the key in bytes */ - char *d, /* data and also output buffer of at least 64 bytes */ - int ld, /* length of data in bytes */ - hmac_sha512_ctx* hmac -) -{ - sha512_ctx* ctx = &(hmac->ctx); - - /**** Restore Precomputed Inner Digest Context ****/ - - memcpy (ctx, &(hmac->inner_digest_ctx), sizeof (sha512_ctx)); - - sha512_hash ((unsigned char *) d, ld, ctx); - - sha512_end ((unsigned char *) d, ctx); - - /**** Restore Precomputed Outer Digest Context ****/ - - memcpy (ctx, &(hmac->outer_digest_ctx), sizeof (sha512_ctx)); - - sha512_hash ((unsigned char *) d, SHA512_DIGESTSIZE, ctx); - - sha512_end ((unsigned char *) d, ctx); -} - -void hmac_sha512 -( - char *k, /* secret key */ - int lk, /* length of the key in bytes */ - char *d, /* data and also output buffer of at least 64 bytes */ - int ld /* length of data in bytes */ -) -{ - hmac_sha512_ctx hmac; - sha512_ctx* ctx; - char* buf = hmac.k; /* there is enough space to hold SHA512_BLOCKSIZE (128) bytes - * because k is followed by u in hmac_sha512_ctx - */ - int b; - char key[SHA512_DIGESTSIZE]; - - /* If the key is longer than the hash algorithm block size, - let key = sha512(key), as per HMAC specifications. */ - if (lk > SHA512_BLOCKSIZE) - { - sha512_ctx tctx; - - sha512_begin (&tctx); - sha512_hash ((unsigned char *) k, lk, &tctx); - sha512_end ((unsigned char *) key, &tctx); - - k = key; - lk = SHA512_DIGESTSIZE; - - burn (&tctx, sizeof(tctx)); // Prevent leaks - } - - /**** Precompute HMAC Inner Digest ****/ - - ctx = &(hmac.inner_digest_ctx); - sha512_begin (ctx); - - /* Pad the key for inner digest */ - for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x36); - memset (&buf[lk], 0x36, SHA512_BLOCKSIZE - lk); - - sha512_hash ((unsigned char *) buf, SHA512_BLOCKSIZE, ctx); - - /**** Precompute HMAC Outer Digest ****/ - - ctx = &(hmac.outer_digest_ctx); - sha512_begin (ctx); - - for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x5C); - memset (&buf[lk], 0x5C, SHA512_BLOCKSIZE - lk); - - sha512_hash ((unsigned char *) buf, SHA512_BLOCKSIZE, ctx); - - hmac_sha512_internal (k, lk, d, ld, &hmac); - - /* Prevent leaks */ - burn (&hmac, sizeof(hmac)); - burn (key, sizeof(key)); -} - -static void derive_u_sha512 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, int b, hmac_sha512_ctx* hmac) -{ - char* k = hmac->k; - char* u = hmac->u; - uint32 c, i; - - /* iteration 1 */ - memcpy (k, salt, salt_len); /* salt */ - /* big-endian block number */ - memset (&k[salt_len], 0, 3); - k[salt_len + 3] = (char) b; - - hmac_sha512_internal (pwd, pwd_len, k, salt_len + 4, hmac); - memcpy (u, k, SHA512_DIGESTSIZE); - - /* remaining iterations */ - for (c = 1; c < iterations; c++) - { - hmac_sha512_internal (pwd, pwd_len, k, SHA512_DIGESTSIZE, hmac); - for (i = 0; i < SHA512_DIGESTSIZE; i++) - { - u[i] ^= k[i]; - } - } -} - - -void derive_key_sha512 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) -{ - hmac_sha512_ctx hmac; - sha512_ctx* ctx; - char* buf = hmac.k; /* there is enough space to hold SHA512_BLOCKSIZE (128) bytes - * because k is followed by u in hmac_sha512_ctx - */ - int b, l, r; - char key[SHA512_DIGESTSIZE]; - - /* If the password is longer than the hash algorithm block size, - let pwd = sha512(pwd), as per HMAC specifications. */ - if (pwd_len > SHA512_BLOCKSIZE) - { - sha512_ctx tctx; - - sha512_begin (&tctx); - sha512_hash ((unsigned char *) pwd, pwd_len, &tctx); - sha512_end ((unsigned char *) key, &tctx); - - pwd = key; - pwd_len = SHA512_DIGESTSIZE; - - burn (&tctx, sizeof(tctx)); // Prevent leaks - } - - if (dklen % SHA512_DIGESTSIZE) - { - l = 1 + dklen / SHA512_DIGESTSIZE; - } - else - { - l = dklen / SHA512_DIGESTSIZE; - } - - r = dklen - (l - 1) * SHA512_DIGESTSIZE; - - /**** Precompute HMAC Inner Digest ****/ - - ctx = &(hmac.inner_digest_ctx); - sha512_begin (ctx); - - /* Pad the key for inner digest */ - for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x36); - memset (&buf[pwd_len], 0x36, SHA512_BLOCKSIZE - pwd_len); - - sha512_hash ((unsigned char *) buf, SHA512_BLOCKSIZE, ctx); - - /**** Precompute HMAC Outer Digest ****/ - - ctx = &(hmac.outer_digest_ctx); - sha512_begin (ctx); - - for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x5C); - memset (&buf[pwd_len], 0x5C, SHA512_BLOCKSIZE - pwd_len); - - sha512_hash ((unsigned char *) buf, SHA512_BLOCKSIZE, ctx); - - /* first l - 1 blocks */ - for (b = 1; b < l; b++) - { - derive_u_sha512 (pwd, pwd_len, salt, salt_len, iterations, b, &hmac); - memcpy (dk, hmac.u, SHA512_DIGESTSIZE); - dk += SHA512_DIGESTSIZE; - } - - /* last block */ - derive_u_sha512 (pwd, pwd_len, salt, salt_len, iterations, b, &hmac); - memcpy (dk, hmac.u, r); - - - /* Prevent possible leaks. */ - burn (&hmac, sizeof(hmac)); - burn (key, sizeof(key)); -} - -#endif // TC_WINDOWS_BOOT - -#if !defined(TC_WINDOWS_BOOT) || defined(TC_WINDOWS_BOOT_RIPEMD160) - -typedef struct hmac_ripemd160_ctx_struct -{ - RMD160_CTX context; - RMD160_CTX inner_digest_ctx; /*pre-computed inner digest context */ - RMD160_CTX outer_digest_ctx; /*pre-computed outer digest context */ - char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the RIPEMD-160 hash */ - char u[RIPEMD160_DIGESTSIZE]; -} hmac_ripemd160_ctx; - -void hmac_ripemd160_internal (char *key, int keylen, char *input_digest, int len, hmac_ripemd160_ctx* hmac) -{ - RMD160_CTX* context = &(hmac->context); - - /**** Restore Precomputed Inner Digest Context ****/ - - memcpy (context, &(hmac->inner_digest_ctx), sizeof (RMD160_CTX)); - - RMD160Update(context, (const unsigned char *) input_digest, len); /* then text of datagram */ - RMD160Final((unsigned char *) input_digest, context); /* finish up 1st pass */ - - /**** Restore Precomputed Outer Digest Context ****/ - - memcpy (context, &(hmac->outer_digest_ctx), sizeof (RMD160_CTX)); - - /* results of 1st hash */ - RMD160Update(context, (const unsigned char *) input_digest, RIPEMD160_DIGESTSIZE); - RMD160Final((unsigned char *) input_digest, context); /* finish up 2nd pass */ -} - -#ifndef TC_WINDOWS_BOOT -void hmac_ripemd160 (char *key, int keylen, char *input_digest, int len) -{ - hmac_ripemd160_ctx hmac; - RMD160_CTX* ctx; - unsigned char* k_pad = (unsigned char*) hmac.k; /* inner/outer padding - key XORd with ipad */ - unsigned char tk[RIPEMD160_DIGESTSIZE]; - int i; - - /* If the key is longer than the hash algorithm block size, - let key = ripemd160(key), as per HMAC specifications. */ - if (keylen > RIPEMD160_BLOCKSIZE) - { - RMD160_CTX tctx; - - RMD160Init(&tctx); - RMD160Update(&tctx, (const unsigned char *) key, keylen); - RMD160Final(tk, &tctx); - - key = (char *) tk; - keylen = RIPEMD160_DIGESTSIZE; - - burn (&tctx, sizeof(tctx)); // Prevent leaks - } - - /* perform inner RIPEMD-160 */ - ctx = &(hmac.inner_digest_ctx); - /* start out by storing key in pads */ - memset(k_pad, 0x36, 64); - /* XOR key with ipad and opad values */ - for (i=0; ik; - char* u = hmac->u; - uint32 c; - int i; - -#ifdef TC_WINDOWS_BOOT - /* In bootloader mode, least significant bit of iterations is a boolean (TRUE for boot derivation mode, FALSE otherwise) - * and the most significant 16 bits hold the pim value - * This enables us to save code space needed for implementing other features. - */ - c = iterations >> 16; - i = ((int) iterations) & 0x01; - if (i) - c = (c == 0)? 327661 : c << 11; - else - c = (c == 0)? 655331 : 15000 + c * 1000; -#else - c = iterations; -#endif - - /* iteration 1 */ - memcpy (k, salt, salt_len); /* salt */ - - /* big-endian block number */ - memset (&k[salt_len], 0, 3); - k[salt_len + 3] = (char) b; - - hmac_ripemd160_internal (pwd, pwd_len, k, salt_len + 4, hmac); - memcpy (u, k, RIPEMD160_DIGESTSIZE); - - /* remaining iterations */ - while ( c > 1) - { - hmac_ripemd160_internal (pwd, pwd_len, k, RIPEMD160_DIGESTSIZE, hmac); - for (i = 0; i < RIPEMD160_DIGESTSIZE; i++) - { - u[i] ^= k[i]; - } - c--; - } -} - -void derive_key_ripemd160 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) -{ - int b, l, r; - hmac_ripemd160_ctx hmac; - RMD160_CTX* ctx; - unsigned char* k_pad = (unsigned char*) hmac.k; -#ifndef TC_WINDOWS_BOOT - unsigned char tk[RIPEMD160_DIGESTSIZE]; - /* If the password is longer than the hash algorithm block size, - let password = ripemd160(password), as per HMAC specifications. */ - if (pwd_len > RIPEMD160_BLOCKSIZE) - { - RMD160_CTX tctx; - - RMD160Init(&tctx); - RMD160Update(&tctx, (const unsigned char *) pwd, pwd_len); - RMD160Final(tk, &tctx); - - pwd = (char *) tk; - pwd_len = RIPEMD160_DIGESTSIZE; - - burn (&tctx, sizeof(tctx)); // Prevent leaks - } -#endif - - if (dklen % RIPEMD160_DIGESTSIZE) - { - l = 1 + dklen / RIPEMD160_DIGESTSIZE; - } - else - { - l = dklen / RIPEMD160_DIGESTSIZE; - } - - r = dklen - (l - 1) * RIPEMD160_DIGESTSIZE; - - /* perform inner RIPEMD-160 */ - ctx = &(hmac.inner_digest_ctx); - /* start out by storing key in pads */ - memset(k_pad, 0x36, 64); - /* XOR key with ipad and opad values */ - for (b=0; bctx); - - /**** Restore Precomputed Inner Digest Context ****/ - - memcpy (ctx, &(hmac->inner_digest_ctx), sizeof (WHIRLPOOL_CTX)); - - WHIRLPOOL_add ((unsigned char *) d, ld * 8, ctx); - - WHIRLPOOL_finalize (ctx, (unsigned char *) d); - - /**** Restore Precomputed Outer Digest Context ****/ - - memcpy (ctx, &(hmac->outer_digest_ctx), sizeof (WHIRLPOOL_CTX)); - - WHIRLPOOL_add ((unsigned char *) d, WHIRLPOOL_DIGESTSIZE * 8, ctx); - - WHIRLPOOL_finalize (ctx, (unsigned char *) d); -} - -void hmac_whirlpool -( - char *k, /* secret key */ - int lk, /* length of the key in bytes */ - char *d, /* input data. d pointer is guaranteed to be at least 32-bytes long */ - int ld /* length of data in bytes */ -) -{ - hmac_whirlpool_ctx hmac; - WHIRLPOOL_CTX* ctx; - char* buf = hmac.k; - int b; - char key[WHIRLPOOL_DIGESTSIZE]; - /* If the key is longer than the hash algorithm block size, - let key = whirlpool(key), as per HMAC specifications. */ - if (lk > WHIRLPOOL_BLOCKSIZE) - { - WHIRLPOOL_CTX tctx; - - WHIRLPOOL_init (&tctx); - WHIRLPOOL_add ((unsigned char *) k, lk * 8, &tctx); - WHIRLPOOL_finalize (&tctx, (unsigned char *) key); - - k = key; - lk = WHIRLPOOL_DIGESTSIZE; - - burn (&tctx, sizeof(tctx)); // Prevent leaks - } - - /**** Precompute HMAC Inner Digest ****/ - - ctx = &(hmac.inner_digest_ctx); - WHIRLPOOL_init (ctx); - - /* Pad the key for inner digest */ - for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x36); - memset (&buf[lk], 0x36, WHIRLPOOL_BLOCKSIZE - lk); - - WHIRLPOOL_add ((unsigned char *) buf, WHIRLPOOL_BLOCKSIZE * 8, ctx); - - /**** Precompute HMAC Outer Digest ****/ - - ctx = &(hmac.outer_digest_ctx); - WHIRLPOOL_init (ctx); - - for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x5C); - memset (&buf[lk], 0x5C, WHIRLPOOL_BLOCKSIZE - lk); - - WHIRLPOOL_add ((unsigned char *) buf, WHIRLPOOL_BLOCKSIZE * 8, ctx); - - hmac_whirlpool_internal(k, lk, d, ld, &hmac); - /* Prevent leaks */ - burn(&hmac, sizeof(hmac)); -} - -static void derive_u_whirlpool (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, int b, hmac_whirlpool_ctx* hmac) -{ - char* u = hmac->u; - char* k = hmac->k; - uint32 c, i; - - /* iteration 1 */ - memcpy (k, salt, salt_len); /* salt */ - /* big-endian block number */ - memset (&k[salt_len], 0, 3); - k[salt_len + 3] = (char) b; - - hmac_whirlpool_internal (pwd, pwd_len, k, salt_len + 4, hmac); - memcpy (u, k, WHIRLPOOL_DIGESTSIZE); - - /* remaining iterations */ - for (c = 1; c < iterations; c++) - { - hmac_whirlpool_internal (pwd, pwd_len, k, WHIRLPOOL_DIGESTSIZE, hmac); - for (i = 0; i < WHIRLPOOL_DIGESTSIZE; i++) - { - u[i] ^= k[i]; - } - } -} - -void derive_key_whirlpool (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) -{ - hmac_whirlpool_ctx hmac; - WHIRLPOOL_CTX* ctx; - char* buf = hmac.k; - char key[WHIRLPOOL_DIGESTSIZE]; - int b, l, r; - /* If the password is longer than the hash algorithm block size, - let pwd = whirlpool(pwd), as per HMAC specifications. */ - if (pwd_len > WHIRLPOOL_BLOCKSIZE) - { - WHIRLPOOL_CTX tctx; - - WHIRLPOOL_init (&tctx); - WHIRLPOOL_add ((unsigned char *) pwd, pwd_len * 8, &tctx); - WHIRLPOOL_finalize (&tctx, (unsigned char *) key); - - pwd = key; - pwd_len = WHIRLPOOL_DIGESTSIZE; - - burn (&tctx, sizeof(tctx)); // Prevent leaks - } - - if (dklen % WHIRLPOOL_DIGESTSIZE) - { - l = 1 + dklen / WHIRLPOOL_DIGESTSIZE; - } - else - { - l = dklen / WHIRLPOOL_DIGESTSIZE; - } - - r = dklen - (l - 1) * WHIRLPOOL_DIGESTSIZE; - - /**** Precompute HMAC Inner Digest ****/ - - ctx = &(hmac.inner_digest_ctx); - WHIRLPOOL_init (ctx); - - /* Pad the key for inner digest */ - for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x36); - memset (&buf[pwd_len], 0x36, WHIRLPOOL_BLOCKSIZE - pwd_len); - - WHIRLPOOL_add ((unsigned char *) buf, WHIRLPOOL_BLOCKSIZE * 8, ctx); - - /**** Precompute HMAC Outer Digest ****/ - - ctx = &(hmac.outer_digest_ctx); - WHIRLPOOL_init (ctx); - - for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x5C); - memset (&buf[pwd_len], 0x5C, WHIRLPOOL_BLOCKSIZE - pwd_len); - - WHIRLPOOL_add ((unsigned char *) buf, WHIRLPOOL_BLOCKSIZE * 8, ctx); - - /* first l - 1 blocks */ - for (b = 1; b < l; b++) - { - derive_u_whirlpool (pwd, pwd_len, salt, salt_len, iterations, b, &hmac); - memcpy (dk, hmac.u, WHIRLPOOL_DIGESTSIZE); - dk += WHIRLPOOL_DIGESTSIZE; - } - - /* last block */ - derive_u_whirlpool (pwd, pwd_len, salt, salt_len, iterations, b, &hmac); - memcpy (dk, hmac.u, r); - - - /* Prevent possible leaks. */ - burn (&hmac, sizeof(hmac)); - burn (key, sizeof(key)); -} - - -wchar_t *get_pkcs5_prf_name (int pkcs5_prf_id) -{ - switch (pkcs5_prf_id) - { - case SHA512: - return L"HMAC-SHA-512"; - - case SHA256: - return L"HMAC-SHA-256"; - - case RIPEMD160: - return L"HMAC-RIPEMD-160"; - - case WHIRLPOOL: - return L"HMAC-Whirlpool"; - - default: - return L"(Unknown)"; - } -} - - - -int get_pkcs5_iteration_count (int pkcs5_prf_id, int pim, BOOL truecryptMode, BOOL bBoot) -{ - if ( (pim < 0) - || (truecryptMode && pim > 0) /* No PIM for TrueCrypt mode */ - ) - { - return 0; - } - - switch (pkcs5_prf_id) - { - - case RIPEMD160: - if (truecryptMode) - return bBoot ? 1000 : 2000; - else if (pim == 0) - return bBoot? 327661 : 655331; - else - { - return bBoot? pim * 2048 : 15000 + pim * 1000; - } - - case SHA512: - return truecryptMode? 1000 : ((pim == 0)? 500000 : 15000 + pim * 1000); - - case WHIRLPOOL: - return truecryptMode? 1000 : ((pim == 0)? 500000 : 15000 + pim * 1000); - - case SHA256: - if (truecryptMode) - return 0; // SHA-256 not supported by TrueCrypt - else if (pim == 0) - return bBoot? 200000 : 500000; - else - { - return bBoot? pim * 2048 : 15000 + pim * 1000; - } - - default: - TC_THROW_FATAL_EXCEPTION; // Unknown/wrong ID - } - return 0; -} - +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" + +#include +#include +#include "Rmd160.h" +#ifndef TC_WINDOWS_BOOT +#include "Sha2.h" +#include "Whirlpool.h" +#include "misc.h" +#else +#pragma optimize ("t", on) +#include +#if defined( _MSC_VER ) +# ifndef DEBUG +# pragma intrinsic( memcpy ) +# pragma intrinsic( memset ) +# endif +#endif +#include "Sha2Small.h" +#endif +#include "Pkcs5.h" +#include "Crypto.h" + +void hmac_truncate + ( + char *d1, /* data to be truncated */ + char *d2, /* truncated data */ + int len /* length in bytes to keep */ +) +{ + int i; + for (i = 0; i < len; i++) + d2[i] = d1[i]; +} + +#if !defined(TC_WINDOWS_BOOT) || defined(TC_WINDOWS_BOOT_SHA2) + +typedef struct hmac_sha256_ctx_struct +{ + sha256_ctx ctx; + sha256_ctx inner_digest_ctx; /*pre-computed inner digest context */ + sha256_ctx outer_digest_ctx; /*pre-computed outer digest context */ + char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the SHA256 hash */ + char u[SHA256_DIGESTSIZE]; +} hmac_sha256_ctx; + +void hmac_sha256_internal +( + char *k, /* secret key. It's ensured to be always <= 32 bytes */ + int lk, /* length of the key in bytes */ + char *d, /* input data. d pointer is guaranteed to be at least 32-bytes long */ + int ld, /* length of input data in bytes */ + hmac_sha256_ctx* hmac /* HMAC-SHA256 context which holds temporary variables */ +) +{ + sha256_ctx* ctx = &(hmac->ctx); + + /**** Restore Precomputed Inner Digest Context ****/ + + memcpy (ctx, &(hmac->inner_digest_ctx), sizeof (sha256_ctx)); + + sha256_hash ((unsigned char *) d, ld, ctx); + + sha256_end ((unsigned char *) d, ctx); /* d = inner digest */ + + /**** Restore Precomputed Outer Digest Context ****/ + + memcpy (ctx, &(hmac->outer_digest_ctx), sizeof (sha256_ctx)); + + sha256_hash ((unsigned char *) d, SHA256_DIGESTSIZE, ctx); + + sha256_end ((unsigned char *) d, ctx); /* d = outer digest */ +} + +#ifndef TC_WINDOWS_BOOT +void hmac_sha256 +( + char *k, /* secret key */ + int lk, /* length of the key in bytes */ + char *d, /* data */ + int ld /* length of data in bytes */ +) +{ + hmac_sha256_ctx hmac; + sha256_ctx* ctx; + char* buf = hmac.k; + int b; + char key[SHA256_DIGESTSIZE]; + /* If the key is longer than the hash algorithm block size, + let key = sha256(key), as per HMAC specifications. */ + if (lk > SHA256_BLOCKSIZE) + { + sha256_ctx tctx; + + sha256_begin (&tctx); + sha256_hash ((unsigned char *) k, lk, &tctx); + sha256_end ((unsigned char *) key, &tctx); + + k = key; + lk = SHA256_DIGESTSIZE; + + burn (&tctx, sizeof(tctx)); // Prevent leaks + } + + /**** Precompute HMAC Inner Digest ****/ + + ctx = &(hmac.inner_digest_ctx); + sha256_begin (ctx); + + /* Pad the key for inner digest */ + for (b = 0; b < lk; ++b) + buf[b] = (char) (k[b] ^ 0x36); + memset (&buf[lk], 0x36, SHA256_BLOCKSIZE - lk); + + sha256_hash ((unsigned char *) buf, SHA256_BLOCKSIZE, ctx); + + /**** Precompute HMAC Outer Digest ****/ + + ctx = &(hmac.outer_digest_ctx); + sha256_begin (ctx); + + for (b = 0; b < lk; ++b) + buf[b] = (char) (k[b] ^ 0x5C); + memset (&buf[lk], 0x5C, SHA256_BLOCKSIZE - lk); + + sha256_hash ((unsigned char *) buf, SHA256_BLOCKSIZE, ctx); + + hmac_sha256_internal(k, lk, d, ld, &hmac); + /* Prevent leaks */ + burn(&hmac, sizeof(hmac)); + burn(key, sizeof(key)); +} +#endif + +static void derive_u_sha256 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, int b, hmac_sha256_ctx* hmac) +{ + char* k = hmac->k; + char* u = hmac->u; + uint32 c; + int i; + +#ifdef TC_WINDOWS_BOOT + /* In bootloader mode, least significant bit of iterations is a boolean (TRUE for boot derivation mode, FALSE otherwise) + * and the most significant 16 bits hold the pim value + * This enables us to save code space needed for implementing other features. + */ + c = iterations >> 16; + i = ((int) iterations) & 0x01; + if (i) + c = (c == 0)? 200000 : c << 11; + else + c = (c == 0)? 500000 : 15000 + c * 1000; +#else + c = iterations; +#endif + + /* iteration 1 */ + memcpy (k, salt, salt_len); /* salt */ + + /* big-endian block number */ + memset (&k[salt_len], 0, 3); + k[salt_len + 3] = (char) b; + + hmac_sha256_internal (pwd, pwd_len, k, salt_len + 4, hmac); + memcpy (u, k, SHA256_DIGESTSIZE); + + /* remaining iterations */ + while (c > 1) + { + hmac_sha256_internal (pwd, pwd_len, k, SHA256_DIGESTSIZE, hmac); + for (i = 0; i < SHA256_DIGESTSIZE; i++) + { + u[i] ^= k[i]; + } + c--; + } +} + + +void derive_key_sha256 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) +{ + hmac_sha256_ctx hmac; + sha256_ctx* ctx; + char* buf = hmac.k; + int b, l, r; +#ifndef TC_WINDOWS_BOOT + char key[SHA256_DIGESTSIZE]; + /* If the password is longer than the hash algorithm block size, + let pwd = sha256(pwd), as per HMAC specifications. */ + if (pwd_len > SHA256_BLOCKSIZE) + { + sha256_ctx tctx; + + sha256_begin (&tctx); + sha256_hash ((unsigned char *) pwd, pwd_len, &tctx); + sha256_end ((unsigned char *) key, &tctx); + + pwd = key; + pwd_len = SHA256_DIGESTSIZE; + + burn (&tctx, sizeof(tctx)); // Prevent leaks + } +#endif + + if (dklen % SHA256_DIGESTSIZE) + { + l = 1 + dklen / SHA256_DIGESTSIZE; + } + else + { + l = dklen / SHA256_DIGESTSIZE; + } + + r = dklen - (l - 1) * SHA256_DIGESTSIZE; + + /**** Precompute HMAC Inner Digest ****/ + + ctx = &(hmac.inner_digest_ctx); + sha256_begin (ctx); + + /* Pad the key for inner digest */ + for (b = 0; b < pwd_len; ++b) + buf[b] = (char) (pwd[b] ^ 0x36); + memset (&buf[pwd_len], 0x36, SHA256_BLOCKSIZE - pwd_len); + + sha256_hash ((unsigned char *) buf, SHA256_BLOCKSIZE, ctx); + + /**** Precompute HMAC Outer Digest ****/ + + ctx = &(hmac.outer_digest_ctx); + sha256_begin (ctx); + + for (b = 0; b < pwd_len; ++b) + buf[b] = (char) (pwd[b] ^ 0x5C); + memset (&buf[pwd_len], 0x5C, SHA256_BLOCKSIZE - pwd_len); + + sha256_hash ((unsigned char *) buf, SHA256_BLOCKSIZE, ctx); + + /* first l - 1 blocks */ + for (b = 1; b < l; b++) + { + derive_u_sha256 (pwd, pwd_len, salt, salt_len, iterations, b, &hmac); + memcpy (dk, hmac.u, SHA256_DIGESTSIZE); + dk += SHA256_DIGESTSIZE; + } + + /* last block */ + derive_u_sha256 (pwd, pwd_len, salt, salt_len, iterations, b, &hmac); + memcpy (dk, hmac.u, r); + + + /* Prevent possible leaks. */ + burn (&hmac, sizeof(hmac)); +#ifndef TC_WINDOWS_BOOT + burn (key, sizeof(key)); +#endif +} + +#endif + +#ifndef TC_WINDOWS_BOOT + +typedef struct hmac_sha512_ctx_struct +{ + sha512_ctx ctx; + sha512_ctx inner_digest_ctx; /*pre-computed inner digest context */ + sha512_ctx outer_digest_ctx; /*pre-computed outer digest context */ + char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the SHA512 hash */ + char u[SHA512_DIGESTSIZE]; +} hmac_sha512_ctx; + +void hmac_sha512_internal +( + char *k, /* secret key */ + int lk, /* length of the key in bytes */ + char *d, /* data and also output buffer of at least 64 bytes */ + int ld, /* length of data in bytes */ + hmac_sha512_ctx* hmac +) +{ + sha512_ctx* ctx = &(hmac->ctx); + + /**** Restore Precomputed Inner Digest Context ****/ + + memcpy (ctx, &(hmac->inner_digest_ctx), sizeof (sha512_ctx)); + + sha512_hash ((unsigned char *) d, ld, ctx); + + sha512_end ((unsigned char *) d, ctx); + + /**** Restore Precomputed Outer Digest Context ****/ + + memcpy (ctx, &(hmac->outer_digest_ctx), sizeof (sha512_ctx)); + + sha512_hash ((unsigned char *) d, SHA512_DIGESTSIZE, ctx); + + sha512_end ((unsigned char *) d, ctx); +} + +void hmac_sha512 +( + char *k, /* secret key */ + int lk, /* length of the key in bytes */ + char *d, /* data and also output buffer of at least 64 bytes */ + int ld /* length of data in bytes */ +) +{ + hmac_sha512_ctx hmac; + sha512_ctx* ctx; + char* buf = hmac.k; /* there is enough space to hold SHA512_BLOCKSIZE (128) bytes + * because k is followed by u in hmac_sha512_ctx + */ + int b; + char key[SHA512_DIGESTSIZE]; + + /* If the key is longer than the hash algorithm block size, + let key = sha512(key), as per HMAC specifications. */ + if (lk > SHA512_BLOCKSIZE) + { + sha512_ctx tctx; + + sha512_begin (&tctx); + sha512_hash ((unsigned char *) k, lk, &tctx); + sha512_end ((unsigned char *) key, &tctx); + + k = key; + lk = SHA512_DIGESTSIZE; + + burn (&tctx, sizeof(tctx)); // Prevent leaks + } + + /**** Precompute HMAC Inner Digest ****/ + + ctx = &(hmac.inner_digest_ctx); + sha512_begin (ctx); + + /* Pad the key for inner digest */ + for (b = 0; b < lk; ++b) + buf[b] = (char) (k[b] ^ 0x36); + memset (&buf[lk], 0x36, SHA512_BLOCKSIZE - lk); + + sha512_hash ((unsigned char *) buf, SHA512_BLOCKSIZE, ctx); + + /**** Precompute HMAC Outer Digest ****/ + + ctx = &(hmac.outer_digest_ctx); + sha512_begin (ctx); + + for (b = 0; b < lk; ++b) + buf[b] = (char) (k[b] ^ 0x5C); + memset (&buf[lk], 0x5C, SHA512_BLOCKSIZE - lk); + + sha512_hash ((unsigned char *) buf, SHA512_BLOCKSIZE, ctx); + + hmac_sha512_internal (k, lk, d, ld, &hmac); + + /* Prevent leaks */ + burn (&hmac, sizeof(hmac)); + burn (key, sizeof(key)); +} + +static void derive_u_sha512 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, int b, hmac_sha512_ctx* hmac) +{ + char* k = hmac->k; + char* u = hmac->u; + uint32 c, i; + + /* iteration 1 */ + memcpy (k, salt, salt_len); /* salt */ + /* big-endian block number */ + memset (&k[salt_len], 0, 3); + k[salt_len + 3] = (char) b; + + hmac_sha512_internal (pwd, pwd_len, k, salt_len + 4, hmac); + memcpy (u, k, SHA512_DIGESTSIZE); + + /* remaining iterations */ + for (c = 1; c < iterations; c++) + { + hmac_sha512_internal (pwd, pwd_len, k, SHA512_DIGESTSIZE, hmac); + for (i = 0; i < SHA512_DIGESTSIZE; i++) + { + u[i] ^= k[i]; + } + } +} + + +void derive_key_sha512 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) +{ + hmac_sha512_ctx hmac; + sha512_ctx* ctx; + char* buf = hmac.k; /* there is enough space to hold SHA512_BLOCKSIZE (128) bytes + * because k is followed by u in hmac_sha512_ctx + */ + int b, l, r; + char key[SHA512_DIGESTSIZE]; + + /* If the password is longer than the hash algorithm block size, + let pwd = sha512(pwd), as per HMAC specifications. */ + if (pwd_len > SHA512_BLOCKSIZE) + { + sha512_ctx tctx; + + sha512_begin (&tctx); + sha512_hash ((unsigned char *) pwd, pwd_len, &tctx); + sha512_end ((unsigned char *) key, &tctx); + + pwd = key; + pwd_len = SHA512_DIGESTSIZE; + + burn (&tctx, sizeof(tctx)); // Prevent leaks + } + + if (dklen % SHA512_DIGESTSIZE) + { + l = 1 + dklen / SHA512_DIGESTSIZE; + } + else + { + l = dklen / SHA512_DIGESTSIZE; + } + + r = dklen - (l - 1) * SHA512_DIGESTSIZE; + + /**** Precompute HMAC Inner Digest ****/ + + ctx = &(hmac.inner_digest_ctx); + sha512_begin (ctx); + + /* Pad the key for inner digest */ + for (b = 0; b < pwd_len; ++b) + buf[b] = (char) (pwd[b] ^ 0x36); + memset (&buf[pwd_len], 0x36, SHA512_BLOCKSIZE - pwd_len); + + sha512_hash ((unsigned char *) buf, SHA512_BLOCKSIZE, ctx); + + /**** Precompute HMAC Outer Digest ****/ + + ctx = &(hmac.outer_digest_ctx); + sha512_begin (ctx); + + for (b = 0; b < pwd_len; ++b) + buf[b] = (char) (pwd[b] ^ 0x5C); + memset (&buf[pwd_len], 0x5C, SHA512_BLOCKSIZE - pwd_len); + + sha512_hash ((unsigned char *) buf, SHA512_BLOCKSIZE, ctx); + + /* first l - 1 blocks */ + for (b = 1; b < l; b++) + { + derive_u_sha512 (pwd, pwd_len, salt, salt_len, iterations, b, &hmac); + memcpy (dk, hmac.u, SHA512_DIGESTSIZE); + dk += SHA512_DIGESTSIZE; + } + + /* last block */ + derive_u_sha512 (pwd, pwd_len, salt, salt_len, iterations, b, &hmac); + memcpy (dk, hmac.u, r); + + + /* Prevent possible leaks. */ + burn (&hmac, sizeof(hmac)); + burn (key, sizeof(key)); +} + +#endif // TC_WINDOWS_BOOT + +#if !defined(TC_WINDOWS_BOOT) || defined(TC_WINDOWS_BOOT_RIPEMD160) + +typedef struct hmac_ripemd160_ctx_struct +{ + RMD160_CTX context; + RMD160_CTX inner_digest_ctx; /*pre-computed inner digest context */ + RMD160_CTX outer_digest_ctx; /*pre-computed outer digest context */ + char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the RIPEMD-160 hash */ + char u[RIPEMD160_DIGESTSIZE]; +} hmac_ripemd160_ctx; + +void hmac_ripemd160_internal (char *key, int keylen, char *input_digest, int len, hmac_ripemd160_ctx* hmac) +{ + RMD160_CTX* context = &(hmac->context); + + /**** Restore Precomputed Inner Digest Context ****/ + + memcpy (context, &(hmac->inner_digest_ctx), sizeof (RMD160_CTX)); + + RMD160Update(context, (const unsigned char *) input_digest, len); /* then text of datagram */ + RMD160Final((unsigned char *) input_digest, context); /* finish up 1st pass */ + + /**** Restore Precomputed Outer Digest Context ****/ + + memcpy (context, &(hmac->outer_digest_ctx), sizeof (RMD160_CTX)); + + /* results of 1st hash */ + RMD160Update(context, (const unsigned char *) input_digest, RIPEMD160_DIGESTSIZE); + RMD160Final((unsigned char *) input_digest, context); /* finish up 2nd pass */ +} + +#ifndef TC_WINDOWS_BOOT +void hmac_ripemd160 (char *key, int keylen, char *input_digest, int len) +{ + hmac_ripemd160_ctx hmac; + RMD160_CTX* ctx; + unsigned char* k_pad = (unsigned char*) hmac.k; /* inner/outer padding - key XORd with ipad */ + unsigned char tk[RIPEMD160_DIGESTSIZE]; + int i; + + /* If the key is longer than the hash algorithm block size, + let key = ripemd160(key), as per HMAC specifications. */ + if (keylen > RIPEMD160_BLOCKSIZE) + { + RMD160_CTX tctx; + + RMD160Init(&tctx); + RMD160Update(&tctx, (const unsigned char *) key, keylen); + RMD160Final(tk, &tctx); + + key = (char *) tk; + keylen = RIPEMD160_DIGESTSIZE; + + burn (&tctx, sizeof(tctx)); // Prevent leaks + } + + /* perform inner RIPEMD-160 */ + ctx = &(hmac.inner_digest_ctx); + /* start out by storing key in pads */ + memset(k_pad, 0x36, 64); + /* XOR key with ipad and opad values */ + for (i=0; ik; + char* u = hmac->u; + uint32 c; + int i; + +#ifdef TC_WINDOWS_BOOT + /* In bootloader mode, least significant bit of iterations is a boolean (TRUE for boot derivation mode, FALSE otherwise) + * and the most significant 16 bits hold the pim value + * This enables us to save code space needed for implementing other features. + */ + c = iterations >> 16; + i = ((int) iterations) & 0x01; + if (i) + c = (c == 0)? 327661 : c << 11; + else + c = (c == 0)? 655331 : 15000 + c * 1000; +#else + c = iterations; +#endif + + /* iteration 1 */ + memcpy (k, salt, salt_len); /* salt */ + + /* big-endian block number */ + memset (&k[salt_len], 0, 3); + k[salt_len + 3] = (char) b; + + hmac_ripemd160_internal (pwd, pwd_len, k, salt_len + 4, hmac); + memcpy (u, k, RIPEMD160_DIGESTSIZE); + + /* remaining iterations */ + while ( c > 1) + { + hmac_ripemd160_internal (pwd, pwd_len, k, RIPEMD160_DIGESTSIZE, hmac); + for (i = 0; i < RIPEMD160_DIGESTSIZE; i++) + { + u[i] ^= k[i]; + } + c--; + } +} + +void derive_key_ripemd160 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) +{ + int b, l, r; + hmac_ripemd160_ctx hmac; + RMD160_CTX* ctx; + unsigned char* k_pad = (unsigned char*) hmac.k; +#ifndef TC_WINDOWS_BOOT + unsigned char tk[RIPEMD160_DIGESTSIZE]; + /* If the password is longer than the hash algorithm block size, + let password = ripemd160(password), as per HMAC specifications. */ + if (pwd_len > RIPEMD160_BLOCKSIZE) + { + RMD160_CTX tctx; + + RMD160Init(&tctx); + RMD160Update(&tctx, (const unsigned char *) pwd, pwd_len); + RMD160Final(tk, &tctx); + + pwd = (char *) tk; + pwd_len = RIPEMD160_DIGESTSIZE; + + burn (&tctx, sizeof(tctx)); // Prevent leaks + } +#endif + + if (dklen % RIPEMD160_DIGESTSIZE) + { + l = 1 + dklen / RIPEMD160_DIGESTSIZE; + } + else + { + l = dklen / RIPEMD160_DIGESTSIZE; + } + + r = dklen - (l - 1) * RIPEMD160_DIGESTSIZE; + + /* perform inner RIPEMD-160 */ + ctx = &(hmac.inner_digest_ctx); + /* start out by storing key in pads */ + memset(k_pad, 0x36, 64); + /* XOR key with ipad and opad values */ + for (b=0; bctx); + + /**** Restore Precomputed Inner Digest Context ****/ + + memcpy (ctx, &(hmac->inner_digest_ctx), sizeof (WHIRLPOOL_CTX)); + + WHIRLPOOL_add ((unsigned char *) d, ld * 8, ctx); + + WHIRLPOOL_finalize (ctx, (unsigned char *) d); + + /**** Restore Precomputed Outer Digest Context ****/ + + memcpy (ctx, &(hmac->outer_digest_ctx), sizeof (WHIRLPOOL_CTX)); + + WHIRLPOOL_add ((unsigned char *) d, WHIRLPOOL_DIGESTSIZE * 8, ctx); + + WHIRLPOOL_finalize (ctx, (unsigned char *) d); +} + +void hmac_whirlpool +( + char *k, /* secret key */ + int lk, /* length of the key in bytes */ + char *d, /* input data. d pointer is guaranteed to be at least 32-bytes long */ + int ld /* length of data in bytes */ +) +{ + hmac_whirlpool_ctx hmac; + WHIRLPOOL_CTX* ctx; + char* buf = hmac.k; + int b; + char key[WHIRLPOOL_DIGESTSIZE]; + /* If the key is longer than the hash algorithm block size, + let key = whirlpool(key), as per HMAC specifications. */ + if (lk > WHIRLPOOL_BLOCKSIZE) + { + WHIRLPOOL_CTX tctx; + + WHIRLPOOL_init (&tctx); + WHIRLPOOL_add ((unsigned char *) k, lk * 8, &tctx); + WHIRLPOOL_finalize (&tctx, (unsigned char *) key); + + k = key; + lk = WHIRLPOOL_DIGESTSIZE; + + burn (&tctx, sizeof(tctx)); // Prevent leaks + } + + /**** Precompute HMAC Inner Digest ****/ + + ctx = &(hmac.inner_digest_ctx); + WHIRLPOOL_init (ctx); + + /* Pad the key for inner digest */ + for (b = 0; b < lk; ++b) + buf[b] = (char) (k[b] ^ 0x36); + memset (&buf[lk], 0x36, WHIRLPOOL_BLOCKSIZE - lk); + + WHIRLPOOL_add ((unsigned char *) buf, WHIRLPOOL_BLOCKSIZE * 8, ctx); + + /**** Precompute HMAC Outer Digest ****/ + + ctx = &(hmac.outer_digest_ctx); + WHIRLPOOL_init (ctx); + + for (b = 0; b < lk; ++b) + buf[b] = (char) (k[b] ^ 0x5C); + memset (&buf[lk], 0x5C, WHIRLPOOL_BLOCKSIZE - lk); + + WHIRLPOOL_add ((unsigned char *) buf, WHIRLPOOL_BLOCKSIZE * 8, ctx); + + hmac_whirlpool_internal(k, lk, d, ld, &hmac); + /* Prevent leaks */ + burn(&hmac, sizeof(hmac)); +} + +static void derive_u_whirlpool (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, int b, hmac_whirlpool_ctx* hmac) +{ + char* u = hmac->u; + char* k = hmac->k; + uint32 c, i; + + /* iteration 1 */ + memcpy (k, salt, salt_len); /* salt */ + /* big-endian block number */ + memset (&k[salt_len], 0, 3); + k[salt_len + 3] = (char) b; + + hmac_whirlpool_internal (pwd, pwd_len, k, salt_len + 4, hmac); + memcpy (u, k, WHIRLPOOL_DIGESTSIZE); + + /* remaining iterations */ + for (c = 1; c < iterations; c++) + { + hmac_whirlpool_internal (pwd, pwd_len, k, WHIRLPOOL_DIGESTSIZE, hmac); + for (i = 0; i < WHIRLPOOL_DIGESTSIZE; i++) + { + u[i] ^= k[i]; + } + } +} + +void derive_key_whirlpool (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) +{ + hmac_whirlpool_ctx hmac; + WHIRLPOOL_CTX* ctx; + char* buf = hmac.k; + char key[WHIRLPOOL_DIGESTSIZE]; + int b, l, r; + /* If the password is longer than the hash algorithm block size, + let pwd = whirlpool(pwd), as per HMAC specifications. */ + if (pwd_len > WHIRLPOOL_BLOCKSIZE) + { + WHIRLPOOL_CTX tctx; + + WHIRLPOOL_init (&tctx); + WHIRLPOOL_add ((unsigned char *) pwd, pwd_len * 8, &tctx); + WHIRLPOOL_finalize (&tctx, (unsigned char *) key); + + pwd = key; + pwd_len = WHIRLPOOL_DIGESTSIZE; + + burn (&tctx, sizeof(tctx)); // Prevent leaks + } + + if (dklen % WHIRLPOOL_DIGESTSIZE) + { + l = 1 + dklen / WHIRLPOOL_DIGESTSIZE; + } + else + { + l = dklen / WHIRLPOOL_DIGESTSIZE; + } + + r = dklen - (l - 1) * WHIRLPOOL_DIGESTSIZE; + + /**** Precompute HMAC Inner Digest ****/ + + ctx = &(hmac.inner_digest_ctx); + WHIRLPOOL_init (ctx); + + /* Pad the key for inner digest */ + for (b = 0; b < pwd_len; ++b) + buf[b] = (char) (pwd[b] ^ 0x36); + memset (&buf[pwd_len], 0x36, WHIRLPOOL_BLOCKSIZE - pwd_len); + + WHIRLPOOL_add ((unsigned char *) buf, WHIRLPOOL_BLOCKSIZE * 8, ctx); + + /**** Precompute HMAC Outer Digest ****/ + + ctx = &(hmac.outer_digest_ctx); + WHIRLPOOL_init (ctx); + + for (b = 0; b < pwd_len; ++b) + buf[b] = (char) (pwd[b] ^ 0x5C); + memset (&buf[pwd_len], 0x5C, WHIRLPOOL_BLOCKSIZE - pwd_len); + + WHIRLPOOL_add ((unsigned char *) buf, WHIRLPOOL_BLOCKSIZE * 8, ctx); + + /* first l - 1 blocks */ + for (b = 1; b < l; b++) + { + derive_u_whirlpool (pwd, pwd_len, salt, salt_len, iterations, b, &hmac); + memcpy (dk, hmac.u, WHIRLPOOL_DIGESTSIZE); + dk += WHIRLPOOL_DIGESTSIZE; + } + + /* last block */ + derive_u_whirlpool (pwd, pwd_len, salt, salt_len, iterations, b, &hmac); + memcpy (dk, hmac.u, r); + + + /* Prevent possible leaks. */ + burn (&hmac, sizeof(hmac)); + burn (key, sizeof(key)); +} + + +wchar_t *get_pkcs5_prf_name (int pkcs5_prf_id) +{ + switch (pkcs5_prf_id) + { + case SHA512: + return L"HMAC-SHA-512"; + + case SHA256: + return L"HMAC-SHA-256"; + + case RIPEMD160: + return L"HMAC-RIPEMD-160"; + + case WHIRLPOOL: + return L"HMAC-Whirlpool"; + + default: + return L"(Unknown)"; + } +} + + + +int get_pkcs5_iteration_count (int pkcs5_prf_id, int pim, BOOL truecryptMode, BOOL bBoot) +{ + if ( (pim < 0) + || (truecryptMode && pim > 0) /* No PIM for TrueCrypt mode */ + ) + { + return 0; + } + + switch (pkcs5_prf_id) + { + + case RIPEMD160: + if (truecryptMode) + return bBoot ? 1000 : 2000; + else if (pim == 0) + return bBoot? 327661 : 655331; + else + { + return bBoot? pim * 2048 : 15000 + pim * 1000; + } + + case SHA512: + return truecryptMode? 1000 : ((pim == 0)? 500000 : 15000 + pim * 1000); + + case WHIRLPOOL: + return truecryptMode? 1000 : ((pim == 0)? 500000 : 15000 + pim * 1000); + + case SHA256: + if (truecryptMode) + return 0; // SHA-256 not supported by TrueCrypt + else if (pim == 0) + return bBoot? 200000 : 500000; + else + { + return bBoot? pim * 2048 : 15000 + pim * 1000; + } + + default: + TC_THROW_FATAL_EXCEPTION; // Unknown/wrong ID + } + return 0; +} + #endif //!TC_WINDOWS_BOOT diff --git a/src/Common/Pkcs5.h b/src/Common/Pkcs5.h index b54e36f9..ec9bf434 100644 --- a/src/Common/Pkcs5.h +++ b/src/Common/Pkcs5.h @@ -1,48 +1,48 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifndef TC_HEADER_PKCS5 -#define TC_HEADER_PKCS5 - -#include "Tcdefs.h" - -#if defined(__cplusplus) -extern "C" -{ -#endif -/* output written to input_digest which must be at lease 20 bytes long */ -void hmac_ripemd160 (char *key, int keylen, char *input_digest, int len); -void derive_key_ripemd160 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); - -/* output written to d which must be at lease 32 bytes long */ -void hmac_sha256 (char *k, int lk, char *d, int ld); -void derive_key_sha256 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); - -#ifndef TC_WINDOWS_BOOT -/* output written to d which must be at lease 64 bytes long */ -void hmac_sha512 (char *k, int lk, char *d, int ld); -void derive_key_sha512 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); - -/* output written to d which must be at lease 64 bytes long */ -void hmac_whirlpool (char *k, int lk, char *d, int ld); -void derive_key_whirlpool (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); - -int get_pkcs5_iteration_count (int pkcs5_prf_id, int pim, BOOL truecryptMode, BOOL bBoot); -wchar_t *get_pkcs5_prf_name (int pkcs5_prf_id); -#endif - -#if defined(__cplusplus) -} -#endif - -#endif // TC_HEADER_PKCS5 +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifndef TC_HEADER_PKCS5 +#define TC_HEADER_PKCS5 + +#include "Tcdefs.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif +/* output written to input_digest which must be at lease 20 bytes long */ +void hmac_ripemd160 (char *key, int keylen, char *input_digest, int len); +void derive_key_ripemd160 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); + +/* output written to d which must be at lease 32 bytes long */ +void hmac_sha256 (char *k, int lk, char *d, int ld); +void derive_key_sha256 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); + +#ifndef TC_WINDOWS_BOOT +/* output written to d which must be at lease 64 bytes long */ +void hmac_sha512 (char *k, int lk, char *d, int ld); +void derive_key_sha512 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); + +/* output written to d which must be at lease 64 bytes long */ +void hmac_whirlpool (char *k, int lk, char *d, int ld); +void derive_key_whirlpool (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); + +int get_pkcs5_iteration_count (int pkcs5_prf_id, int pim, BOOL truecryptMode, BOOL bBoot); +wchar_t *get_pkcs5_prf_name (int pkcs5_prf_id); +#endif + +#if defined(__cplusplus) +} +#endif + +#endif // TC_HEADER_PKCS5 diff --git a/src/Common/Progress.c b/src/Common/Progress.c index 19bd2171..ceb528f2 100644 --- a/src/Common/Progress.c +++ b/src/Common/Progress.c @@ -1,134 +1,134 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" -#include "Language.h" -#include "Dlgcode.h" -#include "Progress.h" -#include "../Format/Tcformat.h" -#include "../Format/FormatCom.h" -#include "../Format/resource.h" - -#include - -static ULONG prevTime, startTime; -static __int64 TotalSize; -static __int64 resumedPointBytesDone; -static BOOL bProgressBarReverse = FALSE; -static BOOL bRWThroughput = FALSE; -static BOOL bShowStatus = FALSE; -static BOOL bPercentMode = FALSE; - -static wchar_t *seconds, *minutes, *hours, *days; - - -// If bIOThroughput is TRUE, the speed reflects the amount of data read AND written per second (rather than -// the speed of the "transform cursor"). -void InitProgressBar (__int64 totalBytes, __int64 bytesDone, BOOL bReverse, BOOL bIOThroughput, BOOL bDisplayStatus, BOOL bShowPercent) -{ - HWND hProgressBar = GetDlgItem (hCurPage, nPbar); - SendMessage (hProgressBar, PBM_SETRANGE32, 0, 10000); - SendMessage (hProgressBar, PBM_SETSTEP, 1, 0); - - bProgressBarReverse = bReverse; - bRWThroughput = bIOThroughput; - bShowStatus = bDisplayStatus; - bPercentMode = bShowPercent; - - seconds = GetString ("SECONDS"); - minutes = GetString ("MINUTES"); - hours = GetString ("HOURS"); - days = GetString ("DAYS"); - - prevTime = startTime = GetTickCount (); - TotalSize = totalBytes; - resumedPointBytesDone = bytesDone; -} - - -BOOL UpdateProgressBar (__int64 byteOffset) -{ - return UpdateProgressBarProc (byteOffset); -} - - -BOOL UpdateProgressBarProc (__int64 byteOffset) -{ - wchar_t text[100]; - wchar_t speed[100]; - HWND hProgressBar = GetDlgItem (hCurPage, nPbar); - int time = GetTickCount (); - int elapsed = (time - startTime) / 1000; - - uint64 bytesDone = (bProgressBarReverse ? (TotalSize - byteOffset) : byteOffset); - uint64 bytesPerSec = (bProgressBarReverse ? (resumedPointBytesDone - byteOffset) : (bytesDone - resumedPointBytesDone)) / (elapsed + 1); - - if (bPercentMode) - { - double perc = (double) (100.0 * (bProgressBarReverse ? ((double) (TotalSize - byteOffset)) : ((double) byteOffset)) / (TotalSize == 0 ? 0.0001 : ((double) TotalSize))); - - if (perc > 99.999999999) - StringCchCopyW (text,ARRAYSIZE(text), GetString ("PROCESSED_PORTION_100_PERCENT")); - else - StringCchPrintfW (text, ARRAYSIZE (text), GetString ("PROCESSED_PORTION_X_PERCENT"), perc); - - StringCchCatW (text, ARRAYSIZE(text), L" "); - } - else - { - GetSizeString (bytesDone, text, sizeof(text)); - if (bytesDone < (unsigned __int64) BYTES_PER_MB * 1000000) - StringCchPrintfW(text, ARRAYSIZE(text), L"%I64d %s ", bytesDone / BYTES_PER_MB, GetString ("MB")); - else if (bytesDone < (unsigned __int64) BYTES_PER_GB * 1000000) - StringCchPrintfW(text, ARRAYSIZE(text), L"%I64d %s ", bytesDone / BYTES_PER_GB, GetString ("GB")); - else if (bytesDone < (unsigned __int64) BYTES_PER_TB * 1000000) - StringCchPrintfW(text, ARRAYSIZE(text), L"%I64d %s ", bytesDone / BYTES_PER_TB, GetString ("TB")); - else - StringCchPrintfW(text, ARRAYSIZE(text), L"%I64d %s ", bytesDone / BYTES_PER_PB, GetString ("PB")); - } - - SetWindowTextW (GetDlgItem (hCurPage, IDC_BYTESWRITTEN), text); - - if (!bShowStatus) - { - GetSpeedString (bRWThroughput ? bytesPerSec*2 : bytesPerSec, speed, sizeof(speed)); - StringCchCatW (speed, ARRAYSIZE(speed), L" "); - SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), speed); - } - - if (byteOffset < TotalSize) - { - int64 sec = (int64) ((bProgressBarReverse ? byteOffset : (TotalSize - byteOffset)) / (bytesPerSec == 0 ? 0.001 : bytesPerSec)); - - if (bytesPerSec == 0 || sec > 60 * 60 * 24 * 999) - StringCchPrintfW (text, ARRAYSIZE(text), L"%s ", GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE")); - else if (sec >= 60 * 60 * 24 * 2) - StringCchPrintfW (text, ARRAYSIZE(text), L"%I64d %s ", sec / (60 * 24 * 60), days); - else if (sec >= 120 * 60) - StringCchPrintfW (text, ARRAYSIZE(text), L"%I64d %s ", sec / (60 * 60), hours); - else if (sec >= 120) - StringCchPrintfW (text, ARRAYSIZE(text), L"%I64d %s ", sec / 60, minutes); - else - StringCchPrintfW (text, ARRAYSIZE(text), L"%I64d %s ", sec, seconds); - - SetWindowTextW (GetDlgItem (hCurPage, IDC_TIMEREMAIN), text); - } - - prevTime = time; - - SendMessage (hProgressBar, PBM_SETPOS, - (int) (10000.0 * (bProgressBarReverse ? (TotalSize - byteOffset) : byteOffset) / (TotalSize == 0 ? 1 : TotalSize)), - 0); - - return bVolTransformThreadCancel; -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" +#include "Language.h" +#include "Dlgcode.h" +#include "Progress.h" +#include "../Format/Tcformat.h" +#include "../Format/FormatCom.h" +#include "../Format/resource.h" + +#include + +static ULONG prevTime, startTime; +static __int64 TotalSize; +static __int64 resumedPointBytesDone; +static BOOL bProgressBarReverse = FALSE; +static BOOL bRWThroughput = FALSE; +static BOOL bShowStatus = FALSE; +static BOOL bPercentMode = FALSE; + +static wchar_t *seconds, *minutes, *hours, *days; + + +// If bIOThroughput is TRUE, the speed reflects the amount of data read AND written per second (rather than +// the speed of the "transform cursor"). +void InitProgressBar (__int64 totalBytes, __int64 bytesDone, BOOL bReverse, BOOL bIOThroughput, BOOL bDisplayStatus, BOOL bShowPercent) +{ + HWND hProgressBar = GetDlgItem (hCurPage, nPbar); + SendMessage (hProgressBar, PBM_SETRANGE32, 0, 10000); + SendMessage (hProgressBar, PBM_SETSTEP, 1, 0); + + bProgressBarReverse = bReverse; + bRWThroughput = bIOThroughput; + bShowStatus = bDisplayStatus; + bPercentMode = bShowPercent; + + seconds = GetString ("SECONDS"); + minutes = GetString ("MINUTES"); + hours = GetString ("HOURS"); + days = GetString ("DAYS"); + + prevTime = startTime = GetTickCount (); + TotalSize = totalBytes; + resumedPointBytesDone = bytesDone; +} + + +BOOL UpdateProgressBar (__int64 byteOffset) +{ + return UpdateProgressBarProc (byteOffset); +} + + +BOOL UpdateProgressBarProc (__int64 byteOffset) +{ + wchar_t text[100]; + wchar_t speed[100]; + HWND hProgressBar = GetDlgItem (hCurPage, nPbar); + int time = GetTickCount (); + int elapsed = (time - startTime) / 1000; + + uint64 bytesDone = (bProgressBarReverse ? (TotalSize - byteOffset) : byteOffset); + uint64 bytesPerSec = (bProgressBarReverse ? (resumedPointBytesDone - byteOffset) : (bytesDone - resumedPointBytesDone)) / (elapsed + 1); + + if (bPercentMode) + { + double perc = (double) (100.0 * (bProgressBarReverse ? ((double) (TotalSize - byteOffset)) : ((double) byteOffset)) / (TotalSize == 0 ? 0.0001 : ((double) TotalSize))); + + if (perc > 99.999999999) + StringCchCopyW (text,ARRAYSIZE(text), GetString ("PROCESSED_PORTION_100_PERCENT")); + else + StringCchPrintfW (text, ARRAYSIZE (text), GetString ("PROCESSED_PORTION_X_PERCENT"), perc); + + StringCchCatW (text, ARRAYSIZE(text), L" "); + } + else + { + GetSizeString (bytesDone, text, sizeof(text)); + if (bytesDone < (unsigned __int64) BYTES_PER_MB * 1000000) + StringCchPrintfW(text, ARRAYSIZE(text), L"%I64d %s ", bytesDone / BYTES_PER_MB, GetString ("MB")); + else if (bytesDone < (unsigned __int64) BYTES_PER_GB * 1000000) + StringCchPrintfW(text, ARRAYSIZE(text), L"%I64d %s ", bytesDone / BYTES_PER_GB, GetString ("GB")); + else if (bytesDone < (unsigned __int64) BYTES_PER_TB * 1000000) + StringCchPrintfW(text, ARRAYSIZE(text), L"%I64d %s ", bytesDone / BYTES_PER_TB, GetString ("TB")); + else + StringCchPrintfW(text, ARRAYSIZE(text), L"%I64d %s ", bytesDone / BYTES_PER_PB, GetString ("PB")); + } + + SetWindowTextW (GetDlgItem (hCurPage, IDC_BYTESWRITTEN), text); + + if (!bShowStatus) + { + GetSpeedString (bRWThroughput ? bytesPerSec*2 : bytesPerSec, speed, sizeof(speed)); + StringCchCatW (speed, ARRAYSIZE(speed), L" "); + SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), speed); + } + + if (byteOffset < TotalSize) + { + int64 sec = (int64) ((bProgressBarReverse ? byteOffset : (TotalSize - byteOffset)) / (bytesPerSec == 0 ? 0.001 : bytesPerSec)); + + if (bytesPerSec == 0 || sec > 60 * 60 * 24 * 999) + StringCchPrintfW (text, ARRAYSIZE(text), L"%s ", GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE")); + else if (sec >= 60 * 60 * 24 * 2) + StringCchPrintfW (text, ARRAYSIZE(text), L"%I64d %s ", sec / (60 * 24 * 60), days); + else if (sec >= 120 * 60) + StringCchPrintfW (text, ARRAYSIZE(text), L"%I64d %s ", sec / (60 * 60), hours); + else if (sec >= 120) + StringCchPrintfW (text, ARRAYSIZE(text), L"%I64d %s ", sec / 60, minutes); + else + StringCchPrintfW (text, ARRAYSIZE(text), L"%I64d %s ", sec, seconds); + + SetWindowTextW (GetDlgItem (hCurPage, IDC_TIMEREMAIN), text); + } + + prevTime = time; + + SendMessage (hProgressBar, PBM_SETPOS, + (int) (10000.0 * (bProgressBarReverse ? (TotalSize - byteOffset) : byteOffset) / (TotalSize == 0 ? 1 : TotalSize)), + 0); + + return bVolTransformThreadCancel; +} diff --git a/src/Common/Progress.h b/src/Common/Progress.h index 9e80a086..f3579d69 100644 --- a/src/Common/Progress.h +++ b/src/Common/Progress.h @@ -1,33 +1,33 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef PBM_SETSTATE - -#define PBM_SETSTATE (WM_USER+16) // wParam = PBST_[State] (NORMAL, ERROR, PAUSED) -#define PBST_NORMAL 0x0001 -#define PBST_ERROR 0x0002 -#define PBST_PAUSED 0x0003 - -#endif - -void InitProgressBar (__int64 totalBytes, __int64 bytesDone, BOOL bReverse, BOOL bIOThroughput, BOOL bDisplayStatus, BOOL bShowPercent); -BOOL UpdateProgressBar (__int64 byteOffset); -BOOL UpdateProgressBarProc (__int64 byteOffset); - -#ifdef __cplusplus -} -#endif +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef PBM_SETSTATE + +#define PBM_SETSTATE (WM_USER+16) // wParam = PBST_[State] (NORMAL, ERROR, PAUSED) +#define PBST_NORMAL 0x0001 +#define PBST_ERROR 0x0002 +#define PBST_PAUSED 0x0003 + +#endif + +void InitProgressBar (__int64 totalBytes, __int64 bytesDone, BOOL bReverse, BOOL bIOThroughput, BOOL bDisplayStatus, BOOL bShowPercent); +BOOL UpdateProgressBar (__int64 byteOffset); +BOOL UpdateProgressBarProc (__int64 byteOffset); + +#ifdef __cplusplus +} +#endif diff --git a/src/Common/Random.c b/src/Common/Random.c index 21c18dad..56431262 100644 --- a/src/Common/Random.c +++ b/src/Common/Random.c @@ -1,898 +1,898 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" -#include "Crc.h" -#include "Random.h" -#include - -static unsigned __int8 buffer[RNG_POOL_SIZE]; -static unsigned char *pRandPool = NULL; -static BOOL bRandDidInit = FALSE; -static int nRandIndex = 0, randPoolReadIndex = 0; -static int HashFunction = DEFAULT_HASH_ALGORITHM; -static BOOL bDidSlowPoll = FALSE; -BOOL volatile bFastPollEnabled = TRUE; /* Used to reduce CPU load when performing benchmarks */ -BOOL volatile bRandmixEnabled = TRUE; /* Used to reduce CPU load when performing benchmarks */ -static BOOL RandomPoolEnrichedByUser = FALSE; -static HANDLE PeriodicFastPollThreadHandle = NULL; - -/* Macro to add a single byte to the pool */ -#define RandaddByte(x) {\ - if (nRandIndex == RNG_POOL_SIZE) nRandIndex = 0;\ - pRandPool[nRandIndex] = (unsigned char) ((unsigned char)x + pRandPool[nRandIndex]); \ - if (nRandIndex % RANDMIX_BYTE_INTERVAL == 0) Randmix();\ - nRandIndex++; \ - } - -/* Macro to add four bytes to the pool */ -#define RandaddInt32(x) RandAddInt((unsigned __int32)x); - -#ifdef _WIN64 -#define RandaddIntPtr(x) RandAddInt64((unsigned __int64)x); -#else -#define RandaddIntPtr(x) RandAddInt((unsigned __int32)x); -#endif - -void RandAddInt (unsigned __int32 x) -{ - RandaddByte(x); - RandaddByte((x >> 8)); - RandaddByte((x >> 16)); - RandaddByte((x >> 24)); -} - -void RandAddInt64 (unsigned __int64 x) -{ - RandaddByte(x); - RandaddByte((x >> 8)); - RandaddByte((x >> 16)); - RandaddByte((x >> 24)); - - RandaddByte((x >> 32)); - RandaddByte((x >> 40)); - RandaddByte((x >> 48)); - RandaddByte((x >> 56)); -} - -#include -#include "Dlgcode.h" - -#ifndef SRC_POS -#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) -#endif - -HHOOK hMouse = NULL; /* Mouse hook for the random number generator */ -HHOOK hKeyboard = NULL; /* Keyboard hook for the random number generator */ -DWORD ProcessedMouseEventsCounter = 0; - -/* Variables for thread control, the thread is used to gather up info about - the system in in the background */ -CRITICAL_SECTION critRandProt; /* The critical section */ -BOOL volatile bThreadTerminate = FALSE; /* This variable is shared among thread's so its made volatile */ - -/* Network library handle for the SlowPoll function */ -HANDLE hNetAPI32 = NULL; - -// CryptoAPI -BOOL CryptoAPIAvailable = FALSE; -DWORD CryptoAPILastError = ERROR_SUCCESS; -HCRYPTPROV hCryptProv; - - -/* Init the random number generator, setup the hooks, and start the thread */ -int Randinit () -{ - DWORD dwLastError = ERROR_SUCCESS; - if (GetMaxPkcs5OutSize() > RNG_POOL_SIZE) - TC_THROW_FATAL_EXCEPTION; - - if(bRandDidInit) - return 0; - - InitializeCriticalSection (&critRandProt); - - bRandDidInit = TRUE; - CryptoAPILastError = ERROR_SUCCESS; - ProcessedMouseEventsCounter = 0; - - if (pRandPool == NULL) - { - pRandPool = (unsigned char *) TCalloc (RANDOMPOOL_ALLOCSIZE); - if (pRandPool == NULL) - goto error; - - bDidSlowPoll = FALSE; - RandomPoolEnrichedByUser = FALSE; - - memset (pRandPool, 0, RANDOMPOOL_ALLOCSIZE); - VirtualLock (pRandPool, RANDOMPOOL_ALLOCSIZE); - } - - hKeyboard = SetWindowsHookEx (WH_KEYBOARD, (HOOKPROC)&KeyboardProc, NULL, GetCurrentThreadId ()); - if (hKeyboard == 0) handleWin32Error (0, SRC_POS); - - hMouse = SetWindowsHookEx (WH_MOUSE, (HOOKPROC)&MouseProc, NULL, GetCurrentThreadId ()); - if (hMouse == 0) - { - handleWin32Error (0, SRC_POS); - goto error; - } - - if (!CryptAcquireContext (&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) - { - CryptoAPIAvailable = FALSE; - CryptoAPILastError = GetLastError (); - goto error; - } - else - CryptoAPIAvailable = TRUE; - - if (!(PeriodicFastPollThreadHandle = (HANDLE) _beginthreadex (NULL, 0, PeriodicFastPollThreadProc, NULL, 0, NULL))) - goto error; - - return 0; - -error: - dwLastError = GetLastError(); - RandStop (TRUE); - SetLastError (dwLastError); - return 1; -} - -/* Close everything down, including the thread which is closed down by - setting a flag which eventually causes the thread function to exit */ -void RandStop (BOOL freePool) -{ - if (!bRandDidInit && freePool && pRandPool) - goto freePool; - - if (bRandDidInit == FALSE) - return; - - EnterCriticalSection (&critRandProt); - - if (hMouse != 0) - UnhookWindowsHookEx (hMouse); - if (hKeyboard != 0) - UnhookWindowsHookEx (hKeyboard); - - bThreadTerminate = TRUE; - - LeaveCriticalSection (&critRandProt); - - if (PeriodicFastPollThreadHandle) - WaitForSingleObject (PeriodicFastPollThreadHandle, INFINITE); - - if (hNetAPI32 != 0) - { - FreeLibrary (hNetAPI32); - hNetAPI32 = NULL; - } - - if (CryptoAPIAvailable) - { - CryptReleaseContext (hCryptProv, 0); - CryptoAPIAvailable = FALSE; - CryptoAPILastError = ERROR_SUCCESS; - } - - hMouse = NULL; - hKeyboard = NULL; - bThreadTerminate = FALSE; - DeleteCriticalSection (&critRandProt); - - bRandDidInit = FALSE; - -freePool: - if (freePool) - { - bDidSlowPoll = FALSE; - RandomPoolEnrichedByUser = FALSE; - - if (pRandPool != NULL) - { - burn (pRandPool, RANDOMPOOL_ALLOCSIZE); - TCfree (pRandPool); - pRandPool = NULL; - } - } -} - -BOOL IsRandomNumberGeneratorStarted () -{ - return bRandDidInit; -} - -void RandSetHashFunction (int hash_algo_id) -{ - if (HashIsDeprecated (hash_algo_id)) - hash_algo_id = DEFAULT_HASH_ALGORITHM; - - HashFunction = hash_algo_id; -} - -int RandGetHashFunction (void) -{ - return HashFunction; -} - -void SetRandomPoolEnrichedByUserStatus (BOOL enriched) -{ - RandomPoolEnrichedByUser = enriched; -} - -BOOL IsRandomPoolEnrichedByUser () -{ - return RandomPoolEnrichedByUser; -} - -/* The random pool mixing function */ -BOOL Randmix () -{ - if (bRandmixEnabled) - { - unsigned char hashOutputBuffer [MAX_DIGESTSIZE]; - WHIRLPOOL_CTX wctx; - RMD160_CTX rctx; - sha512_ctx sctx; - sha256_ctx s256ctx; - int poolIndex, digestIndex, digestSize; - - switch (HashFunction) - { - case RIPEMD160: - digestSize = RIPEMD160_DIGESTSIZE; - break; - - case SHA512: - digestSize = SHA512_DIGESTSIZE; - break; - - case SHA256: - digestSize = SHA256_DIGESTSIZE; - break; - - case WHIRLPOOL: - digestSize = WHIRLPOOL_DIGESTSIZE; - break; - - default: - TC_THROW_FATAL_EXCEPTION; - } - - if (RNG_POOL_SIZE % digestSize) - TC_THROW_FATAL_EXCEPTION; - - for (poolIndex = 0; poolIndex < RNG_POOL_SIZE; poolIndex += digestSize) - { - /* Compute the message digest of the entire pool using the selected hash function. */ - switch (HashFunction) - { - case RIPEMD160: - RMD160Init(&rctx); - RMD160Update(&rctx, pRandPool, RNG_POOL_SIZE); - RMD160Final(hashOutputBuffer, &rctx); - break; - - case SHA512: - sha512_begin (&sctx); - sha512_hash (pRandPool, RNG_POOL_SIZE, &sctx); - sha512_end (hashOutputBuffer, &sctx); - break; - - case SHA256: - sha256_begin (&s256ctx); - sha256_hash (pRandPool, RNG_POOL_SIZE, &s256ctx); - sha256_end (hashOutputBuffer, &s256ctx); - break; - - case WHIRLPOOL: - WHIRLPOOL_init (&wctx); - WHIRLPOOL_add (pRandPool, RNG_POOL_SIZE * 8, &wctx); - WHIRLPOOL_finalize (&wctx, hashOutputBuffer); - break; - - default: - // Unknown/wrong ID - TC_THROW_FATAL_EXCEPTION; - } - - /* XOR the resultant message digest to the pool at the poolIndex position. */ - for (digestIndex = 0; digestIndex < digestSize; digestIndex++) - { - pRandPool [poolIndex + digestIndex] ^= hashOutputBuffer [digestIndex]; - } - } - - /* Prevent leaks */ - burn (hashOutputBuffer, MAX_DIGESTSIZE); - switch (HashFunction) - { - case RIPEMD160: - burn (&rctx, sizeof(rctx)); - break; - - case SHA512: - burn (&sctx, sizeof(sctx)); - break; - - case SHA256: - burn (&s256ctx, sizeof(s256ctx)); - break; - - case WHIRLPOOL: - burn (&wctx, sizeof(wctx)); - break; - - default: - // Unknown/wrong ID - TC_THROW_FATAL_EXCEPTION; - } - } - return TRUE; -} - -/* Add a buffer to the pool */ -void RandaddBuf (void *buf, int len) -{ - int i; - for (i = 0; i < len; i++) - { - RandaddByte (((unsigned char *) buf)[i]); - } -} - -BOOL RandpeekBytes (void* hwndDlg, unsigned char *buf, int len, DWORD* mouseCounter) -{ - if (!bRandDidInit) - return FALSE; - - if (len > RNG_POOL_SIZE) - { - Error ("ERR_NOT_ENOUGH_RANDOM_DATA", (HWND) hwndDlg); - len = RNG_POOL_SIZE; - } - - EnterCriticalSection (&critRandProt); - *mouseCounter = ProcessedMouseEventsCounter; - memcpy (buf, pRandPool, len); - LeaveCriticalSection (&critRandProt); - - return TRUE; -} - - -/* Get len random bytes from the pool (max. RNG_POOL_SIZE bytes per a single call) */ -BOOL RandgetBytes (void* hwndDlg, unsigned char *buf, int len, BOOL forceSlowPoll) -{ - return RandgetBytesFull (hwndDlg, buf, len, forceSlowPoll, FALSE); -} - -/* Get len random bytes from the pool. - * If allowAnyLength is FALSE, then len must be less or equal to RNG_POOL_SIZE - * If allowAnyLength is TRUE, then len can have any positive value - */ -BOOL RandgetBytesFull ( void* hwndDlg, unsigned char *buf , int len, BOOL forceSlowPoll , BOOL allowAnyLength) -{ - int i, looplen; - BOOL ret = TRUE; - - if (!bRandDidInit || HashFunction == 0) - TC_THROW_FATAL_EXCEPTION; - - EnterCriticalSection (&critRandProt); - - if (bDidSlowPoll == FALSE || forceSlowPoll) - { - if (!SlowPoll ()) - { - handleError ((HWND) hwndDlg, ERR_CAPI_INIT_FAILED, SRC_POS); - ret = FALSE; - } - else - bDidSlowPoll = TRUE; - } - - if (!FastPoll ()) - { - handleError ((HWND) hwndDlg, ERR_CAPI_INIT_FAILED, SRC_POS); - ret = FALSE; - } - - /* There's never more than RNG_POOL_SIZE worth of randomess */ - if ( (!allowAnyLength) && (len > RNG_POOL_SIZE)) - { - Error ("ERR_NOT_ENOUGH_RANDOM_DATA", (HWND) hwndDlg); - len = RNG_POOL_SIZE; - LeaveCriticalSection (&critRandProt); - return FALSE; - } - - while (len > 0) - { - if (len > RNG_POOL_SIZE) - { - looplen = RNG_POOL_SIZE; - len -= RNG_POOL_SIZE; - } - else - { - looplen = len; - len = 0; - } - - // this loop number of bytes is copied from pool to output buffer, - // pool is rehashed, and output buffer is XORed with new data from pool - for (i = 0; i < looplen; i++) - { - buf[i] = pRandPool[randPoolReadIndex++]; - if (randPoolReadIndex == RNG_POOL_SIZE) randPoolReadIndex = 0; - } - - /* Invert the pool */ - for (i = 0; i < RNG_POOL_SIZE / 4; i++) - { - ((unsigned __int32 *) pRandPool)[i] = ~((unsigned __int32 *) pRandPool)[i]; - } - - // Mix the pool - if (!FastPoll ()) - ret = FALSE; - - // XOR the current pool content into the output buffer to prevent pool state leaks - for (i = 0; i < looplen; i++) - { - buf[i] ^= pRandPool[randPoolReadIndex++]; - if (randPoolReadIndex == RNG_POOL_SIZE) randPoolReadIndex = 0; - } - - // increment the pointer for the next loop - buf += looplen; - } - - LeaveCriticalSection (&critRandProt); - - if (!ret) - TC_THROW_FATAL_EXCEPTION; - - return ret; -} - -/* Capture the mouse, and as long as the event is not the same as the last - two events, add the crc of the event, and the crc of the time difference - between this event and the last + the current time to the pool. - The role of CRC-32 is merely to perform diffusion. Note that the output - of CRC-32 is subsequently processed using a cryptographically secure hash - algorithm. */ -LRESULT CALLBACK MouseProc (int nCode, WPARAM wParam, LPARAM lParam) -{ - static DWORD dwLastTimer; - static unsigned __int32 lastCrc, lastCrc2; - static POINT lastPoint; - MOUSEHOOKSTRUCT *lpMouse = (MOUSEHOOKSTRUCT *) lParam; - - if (nCode < 0) - return CallNextHookEx (hMouse, nCode, wParam, lParam); - else - { - DWORD dwTimer = GetTickCount (); - DWORD j = dwLastTimer - dwTimer; - unsigned __int32 crc = 0L; - int i; - POINT pt = lpMouse->pt; - - dwLastTimer = dwTimer; - - for (i = 0; i < sizeof (MOUSEHOOKSTRUCT); i++) - { - crc = UPDC32 (((unsigned char *) lpMouse)[i], crc); - } - - if (crc != lastCrc && crc != lastCrc2) - { - unsigned __int32 timeCrc = 0L; - - for (i = 0; i < 4; i++) - { - timeCrc = UPDC32 (((unsigned char *) &j)[i], timeCrc); - } - - for (i = 0; i < 4; i++) - { - timeCrc = UPDC32 (((unsigned char *) &dwTimer)[i], timeCrc); - } - - EnterCriticalSection (&critRandProt); - /* only count real mouse messages in entropy estimation */ - if ( (nCode == HC_ACTION) && (wParam == WM_MOUSEMOVE) - && ((pt.x != lastPoint.x) || (pt.y != lastPoint.y))) - { - ProcessedMouseEventsCounter++; - lastPoint = pt; - } - RandaddInt32 ((unsigned __int32) (crc + timeCrc)); - LeaveCriticalSection (&critRandProt); - } - lastCrc2 = lastCrc; - lastCrc = crc; - - } - return 0; -} - -/* Capture the keyboard, as long as the event is not the same as the last two - events, add the crc of the event to the pool along with the crc of the time - difference between this event and the last. The role of CRC-32 is merely to - perform diffusion. Note that the output of CRC-32 is subsequently processed - using a cryptographically secure hash algorithm. */ -LRESULT CALLBACK KeyboardProc (int nCode, WPARAM wParam, LPARAM lParam) -{ - static int lLastKey, lLastKey2; - static DWORD dwLastTimer; - int nKey = (lParam & 0x00ff0000) >> 16; - int nCapture = 0; - - if (nCode < 0) - return CallNextHookEx (hMouse, nCode, wParam, lParam); - - if ((lParam & 0x0000ffff) == 1 && !(lParam & 0x20000000) && - (lParam & 0x80000000)) - { - if (nKey != lLastKey) - nCapture = 1; /* Capture this key */ - else if (nKey != lLastKey2) - nCapture = 1; /* Allow for one repeat */ - } - if (nCapture) - { - DWORD dwTimer = GetTickCount (); - DWORD j = dwLastTimer - dwTimer; - unsigned __int32 timeCrc = 0L; - int i; - - dwLastTimer = dwTimer; - lLastKey2 = lLastKey; - lLastKey = nKey; - - for (i = 0; i < 4; i++) - { - timeCrc = UPDC32 (((unsigned char *) &j)[i], timeCrc); - } - - for (i = 0; i < 4; i++) - { - timeCrc = UPDC32 (((unsigned char *) &dwTimer)[i], timeCrc); - } - - EnterCriticalSection (&critRandProt); - RandaddInt32 ((unsigned __int32) (GetCrc32((unsigned char*) &lParam, sizeof(lParam)) + timeCrc)); - LeaveCriticalSection (&critRandProt); - } - - return CallNextHookEx (hMouse, nCode, wParam, lParam); -} - -/* This is the thread function which will poll the system for randomness */ -static unsigned __stdcall PeriodicFastPollThreadProc (void *dummy) -{ - UNREFERENCED_PARAMETER (dummy); /* Remove unused parameter warning */ - - for (;;) - { - EnterCriticalSection (&critRandProt); - - if (bThreadTerminate) - { - bThreadTerminate = FALSE; - LeaveCriticalSection (&critRandProt); - _endthreadex (0); - } - else if (bFastPollEnabled) - { - FastPoll (); - } - - LeaveCriticalSection (&critRandProt); - - Sleep (FASTPOLL_INTERVAL); - } -} - -/* Type definitions for function pointers to call NetAPI32 functions */ - -typedef - DWORD (WINAPI * NETSTATISTICSGET) (LPWSTR szServer, LPWSTR szService, - DWORD dwLevel, DWORD dwOptions, - LPBYTE * lpBuffer); -typedef - DWORD (WINAPI * NETAPIBUFFERSIZE) (LPVOID lpBuffer, LPDWORD cbBuffer); -typedef - DWORD (WINAPI * NETAPIBUFFERFREE) (LPVOID lpBuffer); - -NETSTATISTICSGET pNetStatisticsGet = NULL; -NETAPIBUFFERSIZE pNetApiBufferSize = NULL; -NETAPIBUFFERFREE pNetApiBufferFree = NULL; - - -/* This is the slowpoll function which gathers up network/hard drive - performance data for the random pool */ -BOOL SlowPoll (void) -{ - static int isWorkstation = -1; - static int cbPerfData = 0x10000; - HANDLE hDevice; - LPBYTE lpBuffer; - DWORD dwSize, status; - LPWSTR lpszLanW, lpszLanS; - int nDrive; - - /* Find out whether this is an NT server or workstation if necessary */ - if (isWorkstation == -1) - { - HKEY hKey; - - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, - L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", - 0, KEY_READ, &hKey) == ERROR_SUCCESS) - { - wchar_t szValue[32]; - dwSize = sizeof (szValue); - - isWorkstation = TRUE; - status = RegQueryValueEx (hKey, L"ProductType", 0, NULL, - (LPBYTE) szValue, &dwSize); - - if (status == ERROR_SUCCESS && _wcsicmp (szValue, L"WinNT")) - /* Note: There are (at least) three cases for - ProductType: WinNT = NT Workstation, - ServerNT = NT Server, LanmanNT = NT Server - acting as a Domain Controller */ - isWorkstation = FALSE; - - RegCloseKey (hKey); - } - } - /* Initialize the NetAPI32 function pointers if necessary */ - if (hNetAPI32 == NULL) - { - /* Obtain a handle to the module containing the Lan Manager - functions */ - wchar_t dllPath[MAX_PATH]; - if (GetSystemDirectory (dllPath, MAX_PATH)) - { - StringCchCatW(dllPath, ARRAYSIZE(dllPath), L"\\NETAPI32.DLL"); - } - else - StringCchCopyW(dllPath, ARRAYSIZE(dllPath), L"C:\\Windows\\System32\\NETAPI32.DLL"); - - hNetAPI32 = LoadLibrary (dllPath); - if (hNetAPI32 != NULL) - { - /* Now get pointers to the functions */ - pNetStatisticsGet = (NETSTATISTICSGET) GetProcAddress (hNetAPI32, - "NetStatisticsGet"); - pNetApiBufferSize = (NETAPIBUFFERSIZE) GetProcAddress (hNetAPI32, - "NetApiBufferSize"); - pNetApiBufferFree = (NETAPIBUFFERFREE) GetProcAddress (hNetAPI32, - "NetApiBufferFree"); - - /* Make sure we got valid pointers for every NetAPI32 - function */ - if (pNetStatisticsGet == NULL || - pNetApiBufferSize == NULL || - pNetApiBufferFree == NULL) - { - /* Free the library reference and reset the - static handle */ - FreeLibrary (hNetAPI32); - hNetAPI32 = NULL; - } - } - } - - /* Get network statistics. Note: Both NT Workstation and NT Server - by default will be running both the workstation and server - services. The heuristic below is probably useful though on the - assumption that the majority of the network traffic will be via - the appropriate service */ - lpszLanW = (LPWSTR) WIDE ("LanmanWorkstation"); - lpszLanS = (LPWSTR) WIDE ("LanmanServer"); - if (hNetAPI32 && - pNetStatisticsGet (NULL, - isWorkstation ? lpszLanW : lpszLanS, - 0, 0, &lpBuffer) == 0) - { - pNetApiBufferSize (lpBuffer, &dwSize); - RandaddBuf ((unsigned char *) lpBuffer, dwSize); - pNetApiBufferFree (lpBuffer); - } - - /* Get disk I/O statistics for all the hard drives */ - for (nDrive = 0;; nDrive++) - { - DISK_PERFORMANCE diskPerformance; - wchar_t szDevice[24]; - - /* Check whether we can access this device */ - StringCchPrintfW (szDevice, ARRAYSIZE(szDevice), L"\\\\.\\PhysicalDrive%d", nDrive); - hDevice = CreateFile (szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, 0, NULL); - if (hDevice == INVALID_HANDLE_VALUE) - break; - - - /* Note: This only works if you have turned on the disk - performance counters with 'diskperf -y'. These counters - are off by default */ - if (DeviceIoControl (hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0, - &diskPerformance, sizeof (DISK_PERFORMANCE), - &dwSize, NULL)) - { - RandaddBuf ((unsigned char *) &diskPerformance, dwSize); - } - CloseHandle (hDevice); - } - - // CryptoAPI: We always have a valid CryptoAPI context when we arrive here but - // we keep the check for clarity purpose - if ( !CryptoAPIAvailable ) - return FALSE; - if (CryptGenRandom (hCryptProv, sizeof (buffer), buffer)) - { - RandaddBuf (buffer, sizeof (buffer)); - - burn(buffer, sizeof (buffer)); - Randmix(); - return TRUE; - } - else - { - /* return error in case CryptGenRandom fails */ - CryptoAPILastError = GetLastError (); - return FALSE; - } -} - - -/* This is the fastpoll function which gathers up info by calling various api's */ -BOOL FastPoll (void) -{ - int nOriginalRandIndex = nRandIndex; - static BOOL addedFixedItems = FALSE; - FILETIME creationTime, exitTime, kernelTime, userTime; - SIZE_T minimumWorkingSetSize, maximumWorkingSetSize; - LARGE_INTEGER performanceCount; - MEMORYSTATUS memoryStatus; - HANDLE handle; - POINT point; - - /* Get various basic pieces of system information */ - RandaddIntPtr (GetActiveWindow ()); /* Handle of active window */ - RandaddIntPtr (GetCapture ()); /* Handle of window with mouse - capture */ - RandaddIntPtr (GetClipboardOwner ()); /* Handle of clipboard owner */ - RandaddIntPtr (GetClipboardViewer ()); /* Handle of start of - clpbd.viewer list */ - RandaddIntPtr (GetCurrentProcess ()); /* Pseudohandle of current - process */ - RandaddInt32 (GetCurrentProcessId ()); /* Current process ID */ - RandaddIntPtr (GetCurrentThread ()); /* Pseudohandle of current - thread */ - RandaddInt32 (GetCurrentThreadId ()); /* Current thread ID */ - RandaddInt32 (GetCurrentTime ()); /* Milliseconds since Windows - started */ - RandaddIntPtr (GetDesktopWindow ()); /* Handle of desktop window */ - RandaddIntPtr (GetFocus ()); /* Handle of window with kb.focus */ - RandaddInt32 (GetInputState ()); /* Whether sys.queue has any events */ - RandaddInt32 (GetMessagePos ()); /* Cursor pos.for last message */ - RandaddInt32 (GetMessageTime ()); /* 1 ms time for last message */ - RandaddIntPtr (GetOpenClipboardWindow ()); /* Handle of window with - clpbd.open */ - RandaddIntPtr (GetProcessHeap ()); /* Handle of process heap */ - RandaddIntPtr (GetProcessWindowStation ()); /* Handle of procs - window station */ - RandaddInt32 (GetQueueStatus (QS_ALLEVENTS)); /* Types of events in - input queue */ - - /* Get multiword system information */ - GetCaretPos (&point); /* Current caret position */ - RandaddBuf ((unsigned char *) &point, sizeof (POINT)); - GetCursorPos (&point); /* Current mouse cursor position */ - RandaddBuf ((unsigned char *) &point, sizeof (POINT)); - - /* Get percent of memory in use, bytes of physical memory, bytes of - free physical memory, bytes in paging file, free bytes in paging - file, user bytes of address space, and free user bytes */ - memoryStatus.dwLength = sizeof (MEMORYSTATUS); - GlobalMemoryStatus (&memoryStatus); - RandaddBuf ((unsigned char *) &memoryStatus, sizeof (MEMORYSTATUS)); - - /* Get thread and process creation time, exit time, time in kernel - mode, and time in user mode in 100ns intervals */ - handle = GetCurrentThread (); - GetThreadTimes (handle, &creationTime, &exitTime, &kernelTime, &userTime); - RandaddBuf ((unsigned char *) &creationTime, sizeof (FILETIME)); - RandaddBuf ((unsigned char *) &exitTime, sizeof (FILETIME)); - RandaddBuf ((unsigned char *) &kernelTime, sizeof (FILETIME)); - RandaddBuf ((unsigned char *) &userTime, sizeof (FILETIME)); - handle = GetCurrentProcess (); - GetProcessTimes (handle, &creationTime, &exitTime, &kernelTime, &userTime); - RandaddBuf ((unsigned char *) &creationTime, sizeof (FILETIME)); - RandaddBuf ((unsigned char *) &exitTime, sizeof (FILETIME)); - RandaddBuf ((unsigned char *) &kernelTime, sizeof (FILETIME)); - RandaddBuf ((unsigned char *) &userTime, sizeof (FILETIME)); - - /* Get the minimum and maximum working set size for the current - process */ - GetProcessWorkingSetSize (handle, &minimumWorkingSetSize, - &maximumWorkingSetSize); - RandaddIntPtr (minimumWorkingSetSize); - RandaddIntPtr (maximumWorkingSetSize); - - /* The following are fixed for the lifetime of the process so we only - add them once */ - if (addedFixedItems == 0) - { - STARTUPINFO startupInfo; - - /* Get name of desktop, console window title, new window - position and size, window flags, and handles for stdin, - stdout, and stderr */ - startupInfo.cb = sizeof (STARTUPINFO); - GetStartupInfo (&startupInfo); - RandaddBuf ((unsigned char *) &startupInfo, sizeof (STARTUPINFO)); - addedFixedItems = TRUE; - } - /* The docs say QPC can fail if appropriate hardware is not - available. It works on 486 & Pentium boxes, but hasn't been tested - for 386 or RISC boxes */ - if (QueryPerformanceCounter (&performanceCount)) - RandaddBuf ((unsigned char *) &performanceCount, sizeof (LARGE_INTEGER)); - else - { - /* Millisecond accuracy at best... */ - DWORD dwTicks = GetTickCount (); - RandaddBuf ((unsigned char *) &dwTicks, sizeof (dwTicks)); - } - - // CryptoAPI: We always have a valid CryptoAPI context when we arrive here but - // we keep the check for clarity purpose - if ( !CryptoAPIAvailable ) - return FALSE; - if (CryptGenRandom (hCryptProv, sizeof (buffer), buffer)) - { - RandaddBuf (buffer, sizeof (buffer)); - burn (buffer, sizeof(buffer)); - } - else - { - /* return error in case CryptGenRandom fails */ - CryptoAPILastError = GetLastError (); - return FALSE; - } - - /* Apply the pool mixing function */ - Randmix(); - - /* Restore the original pool cursor position. If this wasn't done, mouse coordinates - could be written to a limited area of the pool, especially when moving the mouse - uninterruptedly. The severity of the problem would depend on the length of data - written by FastPoll (if it was equal to the size of the pool, mouse coordinates - would be written only to a particular 4-byte area, whenever moving the mouse - uninterruptedly). */ - nRandIndex = nOriginalRandIndex; - - return TRUE; -} - +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" +#include "Crc.h" +#include "Random.h" +#include + +static unsigned __int8 buffer[RNG_POOL_SIZE]; +static unsigned char *pRandPool = NULL; +static BOOL bRandDidInit = FALSE; +static int nRandIndex = 0, randPoolReadIndex = 0; +static int HashFunction = DEFAULT_HASH_ALGORITHM; +static BOOL bDidSlowPoll = FALSE; +BOOL volatile bFastPollEnabled = TRUE; /* Used to reduce CPU load when performing benchmarks */ +BOOL volatile bRandmixEnabled = TRUE; /* Used to reduce CPU load when performing benchmarks */ +static BOOL RandomPoolEnrichedByUser = FALSE; +static HANDLE PeriodicFastPollThreadHandle = NULL; + +/* Macro to add a single byte to the pool */ +#define RandaddByte(x) {\ + if (nRandIndex == RNG_POOL_SIZE) nRandIndex = 0;\ + pRandPool[nRandIndex] = (unsigned char) ((unsigned char)x + pRandPool[nRandIndex]); \ + if (nRandIndex % RANDMIX_BYTE_INTERVAL == 0) Randmix();\ + nRandIndex++; \ + } + +/* Macro to add four bytes to the pool */ +#define RandaddInt32(x) RandAddInt((unsigned __int32)x); + +#ifdef _WIN64 +#define RandaddIntPtr(x) RandAddInt64((unsigned __int64)x); +#else +#define RandaddIntPtr(x) RandAddInt((unsigned __int32)x); +#endif + +void RandAddInt (unsigned __int32 x) +{ + RandaddByte(x); + RandaddByte((x >> 8)); + RandaddByte((x >> 16)); + RandaddByte((x >> 24)); +} + +void RandAddInt64 (unsigned __int64 x) +{ + RandaddByte(x); + RandaddByte((x >> 8)); + RandaddByte((x >> 16)); + RandaddByte((x >> 24)); + + RandaddByte((x >> 32)); + RandaddByte((x >> 40)); + RandaddByte((x >> 48)); + RandaddByte((x >> 56)); +} + +#include +#include "Dlgcode.h" + +#ifndef SRC_POS +#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) +#endif + +HHOOK hMouse = NULL; /* Mouse hook for the random number generator */ +HHOOK hKeyboard = NULL; /* Keyboard hook for the random number generator */ +DWORD ProcessedMouseEventsCounter = 0; + +/* Variables for thread control, the thread is used to gather up info about + the system in in the background */ +CRITICAL_SECTION critRandProt; /* The critical section */ +BOOL volatile bThreadTerminate = FALSE; /* This variable is shared among thread's so its made volatile */ + +/* Network library handle for the SlowPoll function */ +HANDLE hNetAPI32 = NULL; + +// CryptoAPI +BOOL CryptoAPIAvailable = FALSE; +DWORD CryptoAPILastError = ERROR_SUCCESS; +HCRYPTPROV hCryptProv; + + +/* Init the random number generator, setup the hooks, and start the thread */ +int Randinit () +{ + DWORD dwLastError = ERROR_SUCCESS; + if (GetMaxPkcs5OutSize() > RNG_POOL_SIZE) + TC_THROW_FATAL_EXCEPTION; + + if(bRandDidInit) + return 0; + + InitializeCriticalSection (&critRandProt); + + bRandDidInit = TRUE; + CryptoAPILastError = ERROR_SUCCESS; + ProcessedMouseEventsCounter = 0; + + if (pRandPool == NULL) + { + pRandPool = (unsigned char *) TCalloc (RANDOMPOOL_ALLOCSIZE); + if (pRandPool == NULL) + goto error; + + bDidSlowPoll = FALSE; + RandomPoolEnrichedByUser = FALSE; + + memset (pRandPool, 0, RANDOMPOOL_ALLOCSIZE); + VirtualLock (pRandPool, RANDOMPOOL_ALLOCSIZE); + } + + hKeyboard = SetWindowsHookEx (WH_KEYBOARD, (HOOKPROC)&KeyboardProc, NULL, GetCurrentThreadId ()); + if (hKeyboard == 0) handleWin32Error (0, SRC_POS); + + hMouse = SetWindowsHookEx (WH_MOUSE, (HOOKPROC)&MouseProc, NULL, GetCurrentThreadId ()); + if (hMouse == 0) + { + handleWin32Error (0, SRC_POS); + goto error; + } + + if (!CryptAcquireContext (&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + { + CryptoAPIAvailable = FALSE; + CryptoAPILastError = GetLastError (); + goto error; + } + else + CryptoAPIAvailable = TRUE; + + if (!(PeriodicFastPollThreadHandle = (HANDLE) _beginthreadex (NULL, 0, PeriodicFastPollThreadProc, NULL, 0, NULL))) + goto error; + + return 0; + +error: + dwLastError = GetLastError(); + RandStop (TRUE); + SetLastError (dwLastError); + return 1; +} + +/* Close everything down, including the thread which is closed down by + setting a flag which eventually causes the thread function to exit */ +void RandStop (BOOL freePool) +{ + if (!bRandDidInit && freePool && pRandPool) + goto freePool; + + if (bRandDidInit == FALSE) + return; + + EnterCriticalSection (&critRandProt); + + if (hMouse != 0) + UnhookWindowsHookEx (hMouse); + if (hKeyboard != 0) + UnhookWindowsHookEx (hKeyboard); + + bThreadTerminate = TRUE; + + LeaveCriticalSection (&critRandProt); + + if (PeriodicFastPollThreadHandle) + WaitForSingleObject (PeriodicFastPollThreadHandle, INFINITE); + + if (hNetAPI32 != 0) + { + FreeLibrary (hNetAPI32); + hNetAPI32 = NULL; + } + + if (CryptoAPIAvailable) + { + CryptReleaseContext (hCryptProv, 0); + CryptoAPIAvailable = FALSE; + CryptoAPILastError = ERROR_SUCCESS; + } + + hMouse = NULL; + hKeyboard = NULL; + bThreadTerminate = FALSE; + DeleteCriticalSection (&critRandProt); + + bRandDidInit = FALSE; + +freePool: + if (freePool) + { + bDidSlowPoll = FALSE; + RandomPoolEnrichedByUser = FALSE; + + if (pRandPool != NULL) + { + burn (pRandPool, RANDOMPOOL_ALLOCSIZE); + TCfree (pRandPool); + pRandPool = NULL; + } + } +} + +BOOL IsRandomNumberGeneratorStarted () +{ + return bRandDidInit; +} + +void RandSetHashFunction (int hash_algo_id) +{ + if (HashIsDeprecated (hash_algo_id)) + hash_algo_id = DEFAULT_HASH_ALGORITHM; + + HashFunction = hash_algo_id; +} + +int RandGetHashFunction (void) +{ + return HashFunction; +} + +void SetRandomPoolEnrichedByUserStatus (BOOL enriched) +{ + RandomPoolEnrichedByUser = enriched; +} + +BOOL IsRandomPoolEnrichedByUser () +{ + return RandomPoolEnrichedByUser; +} + +/* The random pool mixing function */ +BOOL Randmix () +{ + if (bRandmixEnabled) + { + unsigned char hashOutputBuffer [MAX_DIGESTSIZE]; + WHIRLPOOL_CTX wctx; + RMD160_CTX rctx; + sha512_ctx sctx; + sha256_ctx s256ctx; + int poolIndex, digestIndex, digestSize; + + switch (HashFunction) + { + case RIPEMD160: + digestSize = RIPEMD160_DIGESTSIZE; + break; + + case SHA512: + digestSize = SHA512_DIGESTSIZE; + break; + + case SHA256: + digestSize = SHA256_DIGESTSIZE; + break; + + case WHIRLPOOL: + digestSize = WHIRLPOOL_DIGESTSIZE; + break; + + default: + TC_THROW_FATAL_EXCEPTION; + } + + if (RNG_POOL_SIZE % digestSize) + TC_THROW_FATAL_EXCEPTION; + + for (poolIndex = 0; poolIndex < RNG_POOL_SIZE; poolIndex += digestSize) + { + /* Compute the message digest of the entire pool using the selected hash function. */ + switch (HashFunction) + { + case RIPEMD160: + RMD160Init(&rctx); + RMD160Update(&rctx, pRandPool, RNG_POOL_SIZE); + RMD160Final(hashOutputBuffer, &rctx); + break; + + case SHA512: + sha512_begin (&sctx); + sha512_hash (pRandPool, RNG_POOL_SIZE, &sctx); + sha512_end (hashOutputBuffer, &sctx); + break; + + case SHA256: + sha256_begin (&s256ctx); + sha256_hash (pRandPool, RNG_POOL_SIZE, &s256ctx); + sha256_end (hashOutputBuffer, &s256ctx); + break; + + case WHIRLPOOL: + WHIRLPOOL_init (&wctx); + WHIRLPOOL_add (pRandPool, RNG_POOL_SIZE * 8, &wctx); + WHIRLPOOL_finalize (&wctx, hashOutputBuffer); + break; + + default: + // Unknown/wrong ID + TC_THROW_FATAL_EXCEPTION; + } + + /* XOR the resultant message digest to the pool at the poolIndex position. */ + for (digestIndex = 0; digestIndex < digestSize; digestIndex++) + { + pRandPool [poolIndex + digestIndex] ^= hashOutputBuffer [digestIndex]; + } + } + + /* Prevent leaks */ + burn (hashOutputBuffer, MAX_DIGESTSIZE); + switch (HashFunction) + { + case RIPEMD160: + burn (&rctx, sizeof(rctx)); + break; + + case SHA512: + burn (&sctx, sizeof(sctx)); + break; + + case SHA256: + burn (&s256ctx, sizeof(s256ctx)); + break; + + case WHIRLPOOL: + burn (&wctx, sizeof(wctx)); + break; + + default: + // Unknown/wrong ID + TC_THROW_FATAL_EXCEPTION; + } + } + return TRUE; +} + +/* Add a buffer to the pool */ +void RandaddBuf (void *buf, int len) +{ + int i; + for (i = 0; i < len; i++) + { + RandaddByte (((unsigned char *) buf)[i]); + } +} + +BOOL RandpeekBytes (void* hwndDlg, unsigned char *buf, int len, DWORD* mouseCounter) +{ + if (!bRandDidInit) + return FALSE; + + if (len > RNG_POOL_SIZE) + { + Error ("ERR_NOT_ENOUGH_RANDOM_DATA", (HWND) hwndDlg); + len = RNG_POOL_SIZE; + } + + EnterCriticalSection (&critRandProt); + *mouseCounter = ProcessedMouseEventsCounter; + memcpy (buf, pRandPool, len); + LeaveCriticalSection (&critRandProt); + + return TRUE; +} + + +/* Get len random bytes from the pool (max. RNG_POOL_SIZE bytes per a single call) */ +BOOL RandgetBytes (void* hwndDlg, unsigned char *buf, int len, BOOL forceSlowPoll) +{ + return RandgetBytesFull (hwndDlg, buf, len, forceSlowPoll, FALSE); +} + +/* Get len random bytes from the pool. + * If allowAnyLength is FALSE, then len must be less or equal to RNG_POOL_SIZE + * If allowAnyLength is TRUE, then len can have any positive value + */ +BOOL RandgetBytesFull ( void* hwndDlg, unsigned char *buf , int len, BOOL forceSlowPoll , BOOL allowAnyLength) +{ + int i, looplen; + BOOL ret = TRUE; + + if (!bRandDidInit || HashFunction == 0) + TC_THROW_FATAL_EXCEPTION; + + EnterCriticalSection (&critRandProt); + + if (bDidSlowPoll == FALSE || forceSlowPoll) + { + if (!SlowPoll ()) + { + handleError ((HWND) hwndDlg, ERR_CAPI_INIT_FAILED, SRC_POS); + ret = FALSE; + } + else + bDidSlowPoll = TRUE; + } + + if (!FastPoll ()) + { + handleError ((HWND) hwndDlg, ERR_CAPI_INIT_FAILED, SRC_POS); + ret = FALSE; + } + + /* There's never more than RNG_POOL_SIZE worth of randomess */ + if ( (!allowAnyLength) && (len > RNG_POOL_SIZE)) + { + Error ("ERR_NOT_ENOUGH_RANDOM_DATA", (HWND) hwndDlg); + len = RNG_POOL_SIZE; + LeaveCriticalSection (&critRandProt); + return FALSE; + } + + while (len > 0) + { + if (len > RNG_POOL_SIZE) + { + looplen = RNG_POOL_SIZE; + len -= RNG_POOL_SIZE; + } + else + { + looplen = len; + len = 0; + } + + // this loop number of bytes is copied from pool to output buffer, + // pool is rehashed, and output buffer is XORed with new data from pool + for (i = 0; i < looplen; i++) + { + buf[i] = pRandPool[randPoolReadIndex++]; + if (randPoolReadIndex == RNG_POOL_SIZE) randPoolReadIndex = 0; + } + + /* Invert the pool */ + for (i = 0; i < RNG_POOL_SIZE / 4; i++) + { + ((unsigned __int32 *) pRandPool)[i] = ~((unsigned __int32 *) pRandPool)[i]; + } + + // Mix the pool + if (!FastPoll ()) + ret = FALSE; + + // XOR the current pool content into the output buffer to prevent pool state leaks + for (i = 0; i < looplen; i++) + { + buf[i] ^= pRandPool[randPoolReadIndex++]; + if (randPoolReadIndex == RNG_POOL_SIZE) randPoolReadIndex = 0; + } + + // increment the pointer for the next loop + buf += looplen; + } + + LeaveCriticalSection (&critRandProt); + + if (!ret) + TC_THROW_FATAL_EXCEPTION; + + return ret; +} + +/* Capture the mouse, and as long as the event is not the same as the last + two events, add the crc of the event, and the crc of the time difference + between this event and the last + the current time to the pool. + The role of CRC-32 is merely to perform diffusion. Note that the output + of CRC-32 is subsequently processed using a cryptographically secure hash + algorithm. */ +LRESULT CALLBACK MouseProc (int nCode, WPARAM wParam, LPARAM lParam) +{ + static DWORD dwLastTimer; + static unsigned __int32 lastCrc, lastCrc2; + static POINT lastPoint; + MOUSEHOOKSTRUCT *lpMouse = (MOUSEHOOKSTRUCT *) lParam; + + if (nCode < 0) + return CallNextHookEx (hMouse, nCode, wParam, lParam); + else + { + DWORD dwTimer = GetTickCount (); + DWORD j = dwLastTimer - dwTimer; + unsigned __int32 crc = 0L; + int i; + POINT pt = lpMouse->pt; + + dwLastTimer = dwTimer; + + for (i = 0; i < sizeof (MOUSEHOOKSTRUCT); i++) + { + crc = UPDC32 (((unsigned char *) lpMouse)[i], crc); + } + + if (crc != lastCrc && crc != lastCrc2) + { + unsigned __int32 timeCrc = 0L; + + for (i = 0; i < 4; i++) + { + timeCrc = UPDC32 (((unsigned char *) &j)[i], timeCrc); + } + + for (i = 0; i < 4; i++) + { + timeCrc = UPDC32 (((unsigned char *) &dwTimer)[i], timeCrc); + } + + EnterCriticalSection (&critRandProt); + /* only count real mouse messages in entropy estimation */ + if ( (nCode == HC_ACTION) && (wParam == WM_MOUSEMOVE) + && ((pt.x != lastPoint.x) || (pt.y != lastPoint.y))) + { + ProcessedMouseEventsCounter++; + lastPoint = pt; + } + RandaddInt32 ((unsigned __int32) (crc + timeCrc)); + LeaveCriticalSection (&critRandProt); + } + lastCrc2 = lastCrc; + lastCrc = crc; + + } + return 0; +} + +/* Capture the keyboard, as long as the event is not the same as the last two + events, add the crc of the event to the pool along with the crc of the time + difference between this event and the last. The role of CRC-32 is merely to + perform diffusion. Note that the output of CRC-32 is subsequently processed + using a cryptographically secure hash algorithm. */ +LRESULT CALLBACK KeyboardProc (int nCode, WPARAM wParam, LPARAM lParam) +{ + static int lLastKey, lLastKey2; + static DWORD dwLastTimer; + int nKey = (lParam & 0x00ff0000) >> 16; + int nCapture = 0; + + if (nCode < 0) + return CallNextHookEx (hMouse, nCode, wParam, lParam); + + if ((lParam & 0x0000ffff) == 1 && !(lParam & 0x20000000) && + (lParam & 0x80000000)) + { + if (nKey != lLastKey) + nCapture = 1; /* Capture this key */ + else if (nKey != lLastKey2) + nCapture = 1; /* Allow for one repeat */ + } + if (nCapture) + { + DWORD dwTimer = GetTickCount (); + DWORD j = dwLastTimer - dwTimer; + unsigned __int32 timeCrc = 0L; + int i; + + dwLastTimer = dwTimer; + lLastKey2 = lLastKey; + lLastKey = nKey; + + for (i = 0; i < 4; i++) + { + timeCrc = UPDC32 (((unsigned char *) &j)[i], timeCrc); + } + + for (i = 0; i < 4; i++) + { + timeCrc = UPDC32 (((unsigned char *) &dwTimer)[i], timeCrc); + } + + EnterCriticalSection (&critRandProt); + RandaddInt32 ((unsigned __int32) (GetCrc32((unsigned char*) &lParam, sizeof(lParam)) + timeCrc)); + LeaveCriticalSection (&critRandProt); + } + + return CallNextHookEx (hMouse, nCode, wParam, lParam); +} + +/* This is the thread function which will poll the system for randomness */ +static unsigned __stdcall PeriodicFastPollThreadProc (void *dummy) +{ + UNREFERENCED_PARAMETER (dummy); /* Remove unused parameter warning */ + + for (;;) + { + EnterCriticalSection (&critRandProt); + + if (bThreadTerminate) + { + bThreadTerminate = FALSE; + LeaveCriticalSection (&critRandProt); + _endthreadex (0); + } + else if (bFastPollEnabled) + { + FastPoll (); + } + + LeaveCriticalSection (&critRandProt); + + Sleep (FASTPOLL_INTERVAL); + } +} + +/* Type definitions for function pointers to call NetAPI32 functions */ + +typedef + DWORD (WINAPI * NETSTATISTICSGET) (LPWSTR szServer, LPWSTR szService, + DWORD dwLevel, DWORD dwOptions, + LPBYTE * lpBuffer); +typedef + DWORD (WINAPI * NETAPIBUFFERSIZE) (LPVOID lpBuffer, LPDWORD cbBuffer); +typedef + DWORD (WINAPI * NETAPIBUFFERFREE) (LPVOID lpBuffer); + +NETSTATISTICSGET pNetStatisticsGet = NULL; +NETAPIBUFFERSIZE pNetApiBufferSize = NULL; +NETAPIBUFFERFREE pNetApiBufferFree = NULL; + + +/* This is the slowpoll function which gathers up network/hard drive + performance data for the random pool */ +BOOL SlowPoll (void) +{ + static int isWorkstation = -1; + static int cbPerfData = 0x10000; + HANDLE hDevice; + LPBYTE lpBuffer; + DWORD dwSize, status; + LPWSTR lpszLanW, lpszLanS; + int nDrive; + + /* Find out whether this is an NT server or workstation if necessary */ + if (isWorkstation == -1) + { + HKEY hKey; + + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, + L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", + 0, KEY_READ, &hKey) == ERROR_SUCCESS) + { + wchar_t szValue[32]; + dwSize = sizeof (szValue); + + isWorkstation = TRUE; + status = RegQueryValueEx (hKey, L"ProductType", 0, NULL, + (LPBYTE) szValue, &dwSize); + + if (status == ERROR_SUCCESS && _wcsicmp (szValue, L"WinNT")) + /* Note: There are (at least) three cases for + ProductType: WinNT = NT Workstation, + ServerNT = NT Server, LanmanNT = NT Server + acting as a Domain Controller */ + isWorkstation = FALSE; + + RegCloseKey (hKey); + } + } + /* Initialize the NetAPI32 function pointers if necessary */ + if (hNetAPI32 == NULL) + { + /* Obtain a handle to the module containing the Lan Manager + functions */ + wchar_t dllPath[MAX_PATH]; + if (GetSystemDirectory (dllPath, MAX_PATH)) + { + StringCchCatW(dllPath, ARRAYSIZE(dllPath), L"\\NETAPI32.DLL"); + } + else + StringCchCopyW(dllPath, ARRAYSIZE(dllPath), L"C:\\Windows\\System32\\NETAPI32.DLL"); + + hNetAPI32 = LoadLibrary (dllPath); + if (hNetAPI32 != NULL) + { + /* Now get pointers to the functions */ + pNetStatisticsGet = (NETSTATISTICSGET) GetProcAddress (hNetAPI32, + "NetStatisticsGet"); + pNetApiBufferSize = (NETAPIBUFFERSIZE) GetProcAddress (hNetAPI32, + "NetApiBufferSize"); + pNetApiBufferFree = (NETAPIBUFFERFREE) GetProcAddress (hNetAPI32, + "NetApiBufferFree"); + + /* Make sure we got valid pointers for every NetAPI32 + function */ + if (pNetStatisticsGet == NULL || + pNetApiBufferSize == NULL || + pNetApiBufferFree == NULL) + { + /* Free the library reference and reset the + static handle */ + FreeLibrary (hNetAPI32); + hNetAPI32 = NULL; + } + } + } + + /* Get network statistics. Note: Both NT Workstation and NT Server + by default will be running both the workstation and server + services. The heuristic below is probably useful though on the + assumption that the majority of the network traffic will be via + the appropriate service */ + lpszLanW = (LPWSTR) WIDE ("LanmanWorkstation"); + lpszLanS = (LPWSTR) WIDE ("LanmanServer"); + if (hNetAPI32 && + pNetStatisticsGet (NULL, + isWorkstation ? lpszLanW : lpszLanS, + 0, 0, &lpBuffer) == 0) + { + pNetApiBufferSize (lpBuffer, &dwSize); + RandaddBuf ((unsigned char *) lpBuffer, dwSize); + pNetApiBufferFree (lpBuffer); + } + + /* Get disk I/O statistics for all the hard drives */ + for (nDrive = 0;; nDrive++) + { + DISK_PERFORMANCE diskPerformance; + wchar_t szDevice[24]; + + /* Check whether we can access this device */ + StringCchPrintfW (szDevice, ARRAYSIZE(szDevice), L"\\\\.\\PhysicalDrive%d", nDrive); + hDevice = CreateFile (szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, 0, NULL); + if (hDevice == INVALID_HANDLE_VALUE) + break; + + + /* Note: This only works if you have turned on the disk + performance counters with 'diskperf -y'. These counters + are off by default */ + if (DeviceIoControl (hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0, + &diskPerformance, sizeof (DISK_PERFORMANCE), + &dwSize, NULL)) + { + RandaddBuf ((unsigned char *) &diskPerformance, dwSize); + } + CloseHandle (hDevice); + } + + // CryptoAPI: We always have a valid CryptoAPI context when we arrive here but + // we keep the check for clarity purpose + if ( !CryptoAPIAvailable ) + return FALSE; + if (CryptGenRandom (hCryptProv, sizeof (buffer), buffer)) + { + RandaddBuf (buffer, sizeof (buffer)); + + burn(buffer, sizeof (buffer)); + Randmix(); + return TRUE; + } + else + { + /* return error in case CryptGenRandom fails */ + CryptoAPILastError = GetLastError (); + return FALSE; + } +} + + +/* This is the fastpoll function which gathers up info by calling various api's */ +BOOL FastPoll (void) +{ + int nOriginalRandIndex = nRandIndex; + static BOOL addedFixedItems = FALSE; + FILETIME creationTime, exitTime, kernelTime, userTime; + SIZE_T minimumWorkingSetSize, maximumWorkingSetSize; + LARGE_INTEGER performanceCount; + MEMORYSTATUS memoryStatus; + HANDLE handle; + POINT point; + + /* Get various basic pieces of system information */ + RandaddIntPtr (GetActiveWindow ()); /* Handle of active window */ + RandaddIntPtr (GetCapture ()); /* Handle of window with mouse + capture */ + RandaddIntPtr (GetClipboardOwner ()); /* Handle of clipboard owner */ + RandaddIntPtr (GetClipboardViewer ()); /* Handle of start of + clpbd.viewer list */ + RandaddIntPtr (GetCurrentProcess ()); /* Pseudohandle of current + process */ + RandaddInt32 (GetCurrentProcessId ()); /* Current process ID */ + RandaddIntPtr (GetCurrentThread ()); /* Pseudohandle of current + thread */ + RandaddInt32 (GetCurrentThreadId ()); /* Current thread ID */ + RandaddInt32 (GetCurrentTime ()); /* Milliseconds since Windows + started */ + RandaddIntPtr (GetDesktopWindow ()); /* Handle of desktop window */ + RandaddIntPtr (GetFocus ()); /* Handle of window with kb.focus */ + RandaddInt32 (GetInputState ()); /* Whether sys.queue has any events */ + RandaddInt32 (GetMessagePos ()); /* Cursor pos.for last message */ + RandaddInt32 (GetMessageTime ()); /* 1 ms time for last message */ + RandaddIntPtr (GetOpenClipboardWindow ()); /* Handle of window with + clpbd.open */ + RandaddIntPtr (GetProcessHeap ()); /* Handle of process heap */ + RandaddIntPtr (GetProcessWindowStation ()); /* Handle of procs + window station */ + RandaddInt32 (GetQueueStatus (QS_ALLEVENTS)); /* Types of events in + input queue */ + + /* Get multiword system information */ + GetCaretPos (&point); /* Current caret position */ + RandaddBuf ((unsigned char *) &point, sizeof (POINT)); + GetCursorPos (&point); /* Current mouse cursor position */ + RandaddBuf ((unsigned char *) &point, sizeof (POINT)); + + /* Get percent of memory in use, bytes of physical memory, bytes of + free physical memory, bytes in paging file, free bytes in paging + file, user bytes of address space, and free user bytes */ + memoryStatus.dwLength = sizeof (MEMORYSTATUS); + GlobalMemoryStatus (&memoryStatus); + RandaddBuf ((unsigned char *) &memoryStatus, sizeof (MEMORYSTATUS)); + + /* Get thread and process creation time, exit time, time in kernel + mode, and time in user mode in 100ns intervals */ + handle = GetCurrentThread (); + GetThreadTimes (handle, &creationTime, &exitTime, &kernelTime, &userTime); + RandaddBuf ((unsigned char *) &creationTime, sizeof (FILETIME)); + RandaddBuf ((unsigned char *) &exitTime, sizeof (FILETIME)); + RandaddBuf ((unsigned char *) &kernelTime, sizeof (FILETIME)); + RandaddBuf ((unsigned char *) &userTime, sizeof (FILETIME)); + handle = GetCurrentProcess (); + GetProcessTimes (handle, &creationTime, &exitTime, &kernelTime, &userTime); + RandaddBuf ((unsigned char *) &creationTime, sizeof (FILETIME)); + RandaddBuf ((unsigned char *) &exitTime, sizeof (FILETIME)); + RandaddBuf ((unsigned char *) &kernelTime, sizeof (FILETIME)); + RandaddBuf ((unsigned char *) &userTime, sizeof (FILETIME)); + + /* Get the minimum and maximum working set size for the current + process */ + GetProcessWorkingSetSize (handle, &minimumWorkingSetSize, + &maximumWorkingSetSize); + RandaddIntPtr (minimumWorkingSetSize); + RandaddIntPtr (maximumWorkingSetSize); + + /* The following are fixed for the lifetime of the process so we only + add them once */ + if (addedFixedItems == 0) + { + STARTUPINFO startupInfo; + + /* Get name of desktop, console window title, new window + position and size, window flags, and handles for stdin, + stdout, and stderr */ + startupInfo.cb = sizeof (STARTUPINFO); + GetStartupInfo (&startupInfo); + RandaddBuf ((unsigned char *) &startupInfo, sizeof (STARTUPINFO)); + addedFixedItems = TRUE; + } + /* The docs say QPC can fail if appropriate hardware is not + available. It works on 486 & Pentium boxes, but hasn't been tested + for 386 or RISC boxes */ + if (QueryPerformanceCounter (&performanceCount)) + RandaddBuf ((unsigned char *) &performanceCount, sizeof (LARGE_INTEGER)); + else + { + /* Millisecond accuracy at best... */ + DWORD dwTicks = GetTickCount (); + RandaddBuf ((unsigned char *) &dwTicks, sizeof (dwTicks)); + } + + // CryptoAPI: We always have a valid CryptoAPI context when we arrive here but + // we keep the check for clarity purpose + if ( !CryptoAPIAvailable ) + return FALSE; + if (CryptGenRandom (hCryptProv, sizeof (buffer), buffer)) + { + RandaddBuf (buffer, sizeof (buffer)); + burn (buffer, sizeof(buffer)); + } + else + { + /* return error in case CryptGenRandom fails */ + CryptoAPILastError = GetLastError (); + return FALSE; + } + + /* Apply the pool mixing function */ + Randmix(); + + /* Restore the original pool cursor position. If this wasn't done, mouse coordinates + could be written to a limited area of the pool, especially when moving the mouse + uninterruptedly. The severity of the problem would depend on the length of data + written by FastPoll (if it was equal to the size of the pool, mouse coordinates + would be written only to a particular 4-byte area, whenever moving the mouse + uninterruptedly). */ + nRandIndex = nOriginalRandIndex; + + return TRUE; +} + diff --git a/src/Common/Random.h b/src/Common/Random.h index 0d397091..ecf04ca3 100644 --- a/src/Common/Random.h +++ b/src/Common/Random.h @@ -1,76 +1,76 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Crypto.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* RNG defines & pool pointers */ -#define RNG_POOL_SIZE 320 // Must be divisible by the size of the output of each of the implemented hash functions. (in bytes) - -#if RNG_POOL_SIZE % SHA512_DIGESTSIZE || RNG_POOL_SIZE % WHIRLPOOL_DIGESTSIZE || RNG_POOL_SIZE % RIPEMD160_DIGESTSIZE -#error RNG_POOL_SIZE must be divisible by the size of the output of each of the implemented hash functions. -#endif - -#define RANDOMPOOL_ALLOCSIZE RNG_POOL_SIZE - -// After every RANDMIX_BYTE_INTERVAL-th byte written to the pool, the pool mixing function is applied to the entire pool -#define RANDMIX_BYTE_INTERVAL 16 - -// FastPoll interval (in milliseconds) -#define FASTPOLL_INTERVAL 500 - -void RandAddInt ( unsigned __int32 x ); -int Randinit ( void ); -void RandStop (BOOL freePool); -BOOL IsRandomNumberGeneratorStarted (); -void RandSetHashFunction ( int hash_algo_id ); -int RandGetHashFunction (void); -void SetRandomPoolEnrichedByUserStatus (BOOL enriched); -BOOL IsRandomPoolEnrichedByUser (); -BOOL Randmix ( void ); -void RandaddBuf ( void *buf , int len ); -BOOL FastPoll ( void ); -BOOL SlowPoll ( void ); - -/* Get len random bytes from the pool (max. RNG_POOL_SIZE bytes per a single call) */ -BOOL RandgetBytes ( void* hwndDlg, unsigned char *buf , int len, BOOL forceSlowPoll ); - -/* Get len random bytes from the pool. - * If allowAnyLength is FALSE, then len must be less or equal to RNG_POOL_SIZE - * If allowAnyLength is TRUE, then len can have any positive value - */ -BOOL RandgetBytesFull ( void* hwndDlg, unsigned char *buf , int len, BOOL forceSlowPoll , BOOL allowAnyLength); - -#ifdef _WIN32 - -extern BOOL volatile bFastPollEnabled; -extern BOOL volatile bRandmixEnabled; -extern DWORD CryptoAPILastError; -extern DWORD ProcessedMouseEventsCounter; - -BOOL RandpeekBytes ( void* hwndDlg, unsigned char *buf , int len, DWORD* mouseCounter ); -void RandAddInt64 ( unsigned __int64 x ); - -LRESULT CALLBACK MouseProc ( int nCode , WPARAM wParam , LPARAM lParam ); -LRESULT CALLBACK KeyboardProc ( int nCode , WPARAM wParam , LPARAM lParam ); -static unsigned __stdcall PeriodicFastPollThreadProc (void *dummy); - -#endif - -#ifdef __cplusplus -} -#endif +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Crypto.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* RNG defines & pool pointers */ +#define RNG_POOL_SIZE 320 // Must be divisible by the size of the output of each of the implemented hash functions. (in bytes) + +#if RNG_POOL_SIZE % SHA512_DIGESTSIZE || RNG_POOL_SIZE % WHIRLPOOL_DIGESTSIZE || RNG_POOL_SIZE % RIPEMD160_DIGESTSIZE +#error RNG_POOL_SIZE must be divisible by the size of the output of each of the implemented hash functions. +#endif + +#define RANDOMPOOL_ALLOCSIZE RNG_POOL_SIZE + +// After every RANDMIX_BYTE_INTERVAL-th byte written to the pool, the pool mixing function is applied to the entire pool +#define RANDMIX_BYTE_INTERVAL 16 + +// FastPoll interval (in milliseconds) +#define FASTPOLL_INTERVAL 500 + +void RandAddInt ( unsigned __int32 x ); +int Randinit ( void ); +void RandStop (BOOL freePool); +BOOL IsRandomNumberGeneratorStarted (); +void RandSetHashFunction ( int hash_algo_id ); +int RandGetHashFunction (void); +void SetRandomPoolEnrichedByUserStatus (BOOL enriched); +BOOL IsRandomPoolEnrichedByUser (); +BOOL Randmix ( void ); +void RandaddBuf ( void *buf , int len ); +BOOL FastPoll ( void ); +BOOL SlowPoll ( void ); + +/* Get len random bytes from the pool (max. RNG_POOL_SIZE bytes per a single call) */ +BOOL RandgetBytes ( void* hwndDlg, unsigned char *buf , int len, BOOL forceSlowPoll ); + +/* Get len random bytes from the pool. + * If allowAnyLength is FALSE, then len must be less or equal to RNG_POOL_SIZE + * If allowAnyLength is TRUE, then len can have any positive value + */ +BOOL RandgetBytesFull ( void* hwndDlg, unsigned char *buf , int len, BOOL forceSlowPoll , BOOL allowAnyLength); + +#ifdef _WIN32 + +extern BOOL volatile bFastPollEnabled; +extern BOOL volatile bRandmixEnabled; +extern DWORD CryptoAPILastError; +extern DWORD ProcessedMouseEventsCounter; + +BOOL RandpeekBytes ( void* hwndDlg, unsigned char *buf , int len, DWORD* mouseCounter ); +void RandAddInt64 ( unsigned __int64 x ); + +LRESULT CALLBACK MouseProc ( int nCode , WPARAM wParam , LPARAM lParam ); +LRESULT CALLBACK KeyboardProc ( int nCode , WPARAM wParam , LPARAM lParam ); +static unsigned __stdcall PeriodicFastPollThreadProc (void *dummy); + +#endif + +#ifdef __cplusplus +} +#endif diff --git a/src/Common/Registry.c b/src/Common/Registry.c index 4dc165f2..1e5883a2 100644 --- a/src/Common/Registry.c +++ b/src/Common/Registry.c @@ -1,300 +1,300 @@ -/* - 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 "Tcdefs.h" -#include "Registry.h" -#include - -BOOL ReadLocalMachineRegistryDword (wchar_t *subKey, wchar_t *name, DWORD *value) -{ - HKEY hkey = 0; - DWORD size = sizeof (*value); - DWORD type; - - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, subKey, 0, KEY_READ, &hkey) != ERROR_SUCCESS) - return FALSE; - - if (RegQueryValueEx (hkey, name, NULL, &type, (BYTE *) value, &size) != ERROR_SUCCESS) - { - RegCloseKey (hkey); - return FALSE; - } - - RegCloseKey (hkey); - return type == REG_DWORD; -} - -BOOL ReadLocalMachineRegistryMultiString (wchar_t *subKey, wchar_t *name, wchar_t *value, DWORD *size) -{ - HKEY hkey = 0; - DWORD type; - - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, subKey, 0, KEY_READ, &hkey) != ERROR_SUCCESS) - return FALSE; - - if (RegQueryValueEx (hkey, name, NULL, &type, (BYTE *) value, size) != ERROR_SUCCESS) - { - RegCloseKey (hkey); - return FALSE; - } - - RegCloseKey (hkey); - return type == REG_MULTI_SZ; -} - -BOOL ReadLocalMachineRegistryString (const wchar_t *subKey, wchar_t *name, wchar_t *str, DWORD *size) -{ - HKEY hkey = 0; - DWORD type; - - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, subKey, 0, KEY_READ, &hkey) != ERROR_SUCCESS) - return FALSE; - - if (RegQueryValueEx (hkey, name, NULL, &type, (BYTE *) str, size) != ERROR_SUCCESS) - { - RegCloseKey (hkey); - return FALSE; - } - - RegCloseKey (hkey); - return type == REG_SZ; -} - -BOOL ReadLocalMachineRegistryStringNonReflected (const wchar_t *subKey, wchar_t *name, wchar_t *str, DWORD *size, BOOL b32bitApp) -{ - HKEY hkey = 0; - DWORD type; - - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, subKey, 0, KEY_READ | (b32bitApp? KEY_WOW64_32KEY: KEY_WOW64_64KEY), &hkey) != ERROR_SUCCESS) - return FALSE; - - if (RegQueryValueEx (hkey, name, NULL, &type, (BYTE *) str, size) != ERROR_SUCCESS) - { - RegCloseKey (hkey); - return FALSE; - } - - RegCloseKey (hkey); - return type == REG_SZ; -} - -int ReadRegistryInt (wchar_t *subKey, wchar_t *name, int defaultValue) -{ - HKEY hkey = 0; - DWORD value, size = sizeof (DWORD); - - if (RegOpenKeyEx (HKEY_CURRENT_USER, subKey, - 0, KEY_READ, &hkey) != ERROR_SUCCESS) - return defaultValue; - - if (RegQueryValueEx (hkey, name, 0, 0, (LPBYTE) &value, &size) != ERROR_SUCCESS) - value = defaultValue; - - RegCloseKey (hkey); - return value; -} - -wchar_t *ReadRegistryString (wchar_t *subKey, wchar_t *name, wchar_t *defaultValue, wchar_t *str, int maxLen) -{ - HKEY hkey = 0; - wchar_t value[MAX_PATH*4]; - DWORD size = sizeof (value); - - str[maxLen/2-1] = 0; - StringCbCopyW (str, maxLen, defaultValue); - - ZeroMemory (value, sizeof value); - if (RegOpenKeyEx (HKEY_CURRENT_USER, subKey, - 0, KEY_READ, &hkey) == ERROR_SUCCESS) - if (RegQueryValueEx (hkey, name, 0, 0, (LPBYTE) value, &size) == ERROR_SUCCESS) - StringCbCopyW (str, maxLen,value); - - if (hkey) - RegCloseKey (hkey); - return str; -} - -DWORD ReadRegistryBytes (wchar_t *path, wchar_t *name, char *value, int maxLen) -{ - HKEY hkey = 0; - DWORD size = maxLen; - BOOL success = FALSE; - - if (RegOpenKeyEx (HKEY_CURRENT_USER, path, 0, KEY_READ, &hkey) != ERROR_SUCCESS) - return 0; - - success = (RegQueryValueEx (hkey, name, 0, 0, (LPBYTE) value, &size) == ERROR_SUCCESS); - RegCloseKey (hkey); - - return success ? size : 0; -} - -void WriteRegistryInt (wchar_t *subKey, wchar_t *name, int value) -{ - HKEY hkey = 0; - DWORD disp; - - if (RegCreateKeyEx (HKEY_CURRENT_USER, subKey, - 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &disp) != ERROR_SUCCESS) - return; - - RegSetValueEx (hkey, name, 0, REG_DWORD, (BYTE *) &value, sizeof value); - RegCloseKey (hkey); -} - -BOOL WriteLocalMachineRegistryDword (wchar_t *subKey, wchar_t *name, DWORD value) -{ - HKEY hkey = 0; - DWORD disp; - LONG status; - - if ((status = RegCreateKeyEx (HKEY_LOCAL_MACHINE, subKey, - 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &disp)) != ERROR_SUCCESS) - { - SetLastError (status); - return FALSE; - } - - if ((status = RegSetValueEx (hkey, name, 0, REG_DWORD, (BYTE *) &value, sizeof value)) != ERROR_SUCCESS) - { - RegCloseKey (hkey); - SetLastError (status); - return FALSE; - } - - RegCloseKey (hkey); - return TRUE; -} - -BOOL WriteLocalMachineRegistryMultiString (wchar_t *subKey, wchar_t *name, wchar_t *multiString, DWORD size) -{ - HKEY hkey = 0; - DWORD disp; - LONG status; - - if ((status = RegCreateKeyEx (HKEY_LOCAL_MACHINE, subKey, - 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &disp)) != ERROR_SUCCESS) - { - SetLastError (status); - return FALSE; - } - - if ((status = RegSetValueEx (hkey, name, 0, REG_MULTI_SZ, (BYTE *) multiString, size)) != ERROR_SUCCESS) - { - RegCloseKey (hkey); - SetLastError (status); - return FALSE; - } - - RegCloseKey (hkey); - return TRUE; -} - -BOOL WriteLocalMachineRegistryString (wchar_t *subKey, wchar_t *name, wchar_t *str, BOOL expandable) -{ - HKEY hkey = 0; - DWORD disp; - LONG status; - - if ((status = RegCreateKeyEx (HKEY_LOCAL_MACHINE, subKey, - 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &disp)) != ERROR_SUCCESS) - { - SetLastError (status); - return FALSE; - } - - if ((status = RegSetValueEx (hkey, name, 0, expandable ? REG_EXPAND_SZ : REG_SZ, (BYTE *) str, (DWORD) (wcslen (str) + 1) * sizeof (wchar_t))) != ERROR_SUCCESS) - { - RegCloseKey (hkey); - SetLastError (status); - return FALSE; - } - - RegCloseKey (hkey); - return TRUE; -} - -void WriteRegistryString (wchar_t *subKey, wchar_t *name, wchar_t *str) -{ - HKEY hkey = 0; - DWORD disp; - - if (RegCreateKeyEx (HKEY_CURRENT_USER, subKey, - 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &disp) != ERROR_SUCCESS) - return; - - RegSetValueEx (hkey, name, 0, REG_SZ, (BYTE *) str, (DWORD) (wcslen (str) + 1) * sizeof (wchar_t)); - RegCloseKey (hkey); -} - -BOOL WriteRegistryBytes (wchar_t *path, wchar_t *name, char *str, DWORD size) -{ - HKEY hkey = 0; - DWORD disp; - BOOL res; - - if (RegCreateKeyEx (HKEY_CURRENT_USER, path, - 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &disp) != ERROR_SUCCESS) - return FALSE; - - res = RegSetValueEx (hkey, name, 0, REG_BINARY, (BYTE *) str, size); - RegCloseKey (hkey); - return res == ERROR_SUCCESS; -} - -BOOL DeleteLocalMachineRegistryKey (wchar_t *parentKey, wchar_t *subKeyToDelete) -{ - LONG status; - HKEY hkey = 0; - - if ((status = RegOpenKeyEx (HKEY_LOCAL_MACHINE, parentKey, 0, KEY_WRITE, &hkey)) != ERROR_SUCCESS) - { - SetLastError (status); - return FALSE; - } - - if ((status = RegDeleteKey (hkey, subKeyToDelete)) != ERROR_SUCCESS) - { - RegCloseKey (hkey); - SetLastError (status); - return FALSE; - } - - RegCloseKey (hkey); - return TRUE; -} - -void DeleteRegistryValue (wchar_t *subKey, wchar_t *name) -{ - HKEY hkey = 0; - - if (RegOpenKeyEx (HKEY_CURRENT_USER, subKey, 0, KEY_WRITE, &hkey) != ERROR_SUCCESS) - return; - - RegDeleteValue (hkey, name); - RegCloseKey (hkey); -} - - -void GetStartupRegKeyName (wchar_t *regk, size_t cbRegk) -{ - // The string is split in order to prevent some antivirus packages from falsely reporting - // VeraCrypt.exe to contain a possible Trojan horse because of this string (heuristic scan). - StringCbPrintfW (regk, cbRegk,L"%s%s", L"Software\\Microsoft\\Windows\\Curren", L"tVersion\\Run"); -} - -void GetRestorePointRegKeyName (wchar_t *regk, size_t cbRegk) -{ - // The string is split in order to prevent some antivirus packages from falsely reporting - // VeraCrypt.exe to contain a possible Trojan horse because of this string (heuristic scan). - StringCbPrintfW (regk, cbRegk,L"%s%s%s%s", L"Software\\Microsoft\\Windows", L" NT\\Curren", L"tVersion\\Sy", L"stemRestore"); +/* + 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 "Tcdefs.h" +#include "Registry.h" +#include + +BOOL ReadLocalMachineRegistryDword (wchar_t *subKey, wchar_t *name, DWORD *value) +{ + HKEY hkey = 0; + DWORD size = sizeof (*value); + DWORD type; + + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, subKey, 0, KEY_READ, &hkey) != ERROR_SUCCESS) + return FALSE; + + if (RegQueryValueEx (hkey, name, NULL, &type, (BYTE *) value, &size) != ERROR_SUCCESS) + { + RegCloseKey (hkey); + return FALSE; + } + + RegCloseKey (hkey); + return type == REG_DWORD; +} + +BOOL ReadLocalMachineRegistryMultiString (wchar_t *subKey, wchar_t *name, wchar_t *value, DWORD *size) +{ + HKEY hkey = 0; + DWORD type; + + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, subKey, 0, KEY_READ, &hkey) != ERROR_SUCCESS) + return FALSE; + + if (RegQueryValueEx (hkey, name, NULL, &type, (BYTE *) value, size) != ERROR_SUCCESS) + { + RegCloseKey (hkey); + return FALSE; + } + + RegCloseKey (hkey); + return type == REG_MULTI_SZ; +} + +BOOL ReadLocalMachineRegistryString (const wchar_t *subKey, wchar_t *name, wchar_t *str, DWORD *size) +{ + HKEY hkey = 0; + DWORD type; + + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, subKey, 0, KEY_READ, &hkey) != ERROR_SUCCESS) + return FALSE; + + if (RegQueryValueEx (hkey, name, NULL, &type, (BYTE *) str, size) != ERROR_SUCCESS) + { + RegCloseKey (hkey); + return FALSE; + } + + RegCloseKey (hkey); + return type == REG_SZ; +} + +BOOL ReadLocalMachineRegistryStringNonReflected (const wchar_t *subKey, wchar_t *name, wchar_t *str, DWORD *size, BOOL b32bitApp) +{ + HKEY hkey = 0; + DWORD type; + + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, subKey, 0, KEY_READ | (b32bitApp? KEY_WOW64_32KEY: KEY_WOW64_64KEY), &hkey) != ERROR_SUCCESS) + return FALSE; + + if (RegQueryValueEx (hkey, name, NULL, &type, (BYTE *) str, size) != ERROR_SUCCESS) + { + RegCloseKey (hkey); + return FALSE; + } + + RegCloseKey (hkey); + return type == REG_SZ; +} + +int ReadRegistryInt (wchar_t *subKey, wchar_t *name, int defaultValue) +{ + HKEY hkey = 0; + DWORD value, size = sizeof (DWORD); + + if (RegOpenKeyEx (HKEY_CURRENT_USER, subKey, + 0, KEY_READ, &hkey) != ERROR_SUCCESS) + return defaultValue; + + if (RegQueryValueEx (hkey, name, 0, 0, (LPBYTE) &value, &size) != ERROR_SUCCESS) + value = defaultValue; + + RegCloseKey (hkey); + return value; +} + +wchar_t *ReadRegistryString (wchar_t *subKey, wchar_t *name, wchar_t *defaultValue, wchar_t *str, int maxLen) +{ + HKEY hkey = 0; + wchar_t value[MAX_PATH*4]; + DWORD size = sizeof (value); + + str[maxLen/2-1] = 0; + StringCbCopyW (str, maxLen, defaultValue); + + ZeroMemory (value, sizeof value); + if (RegOpenKeyEx (HKEY_CURRENT_USER, subKey, + 0, KEY_READ, &hkey) == ERROR_SUCCESS) + if (RegQueryValueEx (hkey, name, 0, 0, (LPBYTE) value, &size) == ERROR_SUCCESS) + StringCbCopyW (str, maxLen,value); + + if (hkey) + RegCloseKey (hkey); + return str; +} + +DWORD ReadRegistryBytes (wchar_t *path, wchar_t *name, char *value, int maxLen) +{ + HKEY hkey = 0; + DWORD size = maxLen; + BOOL success = FALSE; + + if (RegOpenKeyEx (HKEY_CURRENT_USER, path, 0, KEY_READ, &hkey) != ERROR_SUCCESS) + return 0; + + success = (RegQueryValueEx (hkey, name, 0, 0, (LPBYTE) value, &size) == ERROR_SUCCESS); + RegCloseKey (hkey); + + return success ? size : 0; +} + +void WriteRegistryInt (wchar_t *subKey, wchar_t *name, int value) +{ + HKEY hkey = 0; + DWORD disp; + + if (RegCreateKeyEx (HKEY_CURRENT_USER, subKey, + 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &disp) != ERROR_SUCCESS) + return; + + RegSetValueEx (hkey, name, 0, REG_DWORD, (BYTE *) &value, sizeof value); + RegCloseKey (hkey); +} + +BOOL WriteLocalMachineRegistryDword (wchar_t *subKey, wchar_t *name, DWORD value) +{ + HKEY hkey = 0; + DWORD disp; + LONG status; + + if ((status = RegCreateKeyEx (HKEY_LOCAL_MACHINE, subKey, + 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &disp)) != ERROR_SUCCESS) + { + SetLastError (status); + return FALSE; + } + + if ((status = RegSetValueEx (hkey, name, 0, REG_DWORD, (BYTE *) &value, sizeof value)) != ERROR_SUCCESS) + { + RegCloseKey (hkey); + SetLastError (status); + return FALSE; + } + + RegCloseKey (hkey); + return TRUE; +} + +BOOL WriteLocalMachineRegistryMultiString (wchar_t *subKey, wchar_t *name, wchar_t *multiString, DWORD size) +{ + HKEY hkey = 0; + DWORD disp; + LONG status; + + if ((status = RegCreateKeyEx (HKEY_LOCAL_MACHINE, subKey, + 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &disp)) != ERROR_SUCCESS) + { + SetLastError (status); + return FALSE; + } + + if ((status = RegSetValueEx (hkey, name, 0, REG_MULTI_SZ, (BYTE *) multiString, size)) != ERROR_SUCCESS) + { + RegCloseKey (hkey); + SetLastError (status); + return FALSE; + } + + RegCloseKey (hkey); + return TRUE; +} + +BOOL WriteLocalMachineRegistryString (wchar_t *subKey, wchar_t *name, wchar_t *str, BOOL expandable) +{ + HKEY hkey = 0; + DWORD disp; + LONG status; + + if ((status = RegCreateKeyEx (HKEY_LOCAL_MACHINE, subKey, + 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &disp)) != ERROR_SUCCESS) + { + SetLastError (status); + return FALSE; + } + + if ((status = RegSetValueEx (hkey, name, 0, expandable ? REG_EXPAND_SZ : REG_SZ, (BYTE *) str, (DWORD) (wcslen (str) + 1) * sizeof (wchar_t))) != ERROR_SUCCESS) + { + RegCloseKey (hkey); + SetLastError (status); + return FALSE; + } + + RegCloseKey (hkey); + return TRUE; +} + +void WriteRegistryString (wchar_t *subKey, wchar_t *name, wchar_t *str) +{ + HKEY hkey = 0; + DWORD disp; + + if (RegCreateKeyEx (HKEY_CURRENT_USER, subKey, + 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &disp) != ERROR_SUCCESS) + return; + + RegSetValueEx (hkey, name, 0, REG_SZ, (BYTE *) str, (DWORD) (wcslen (str) + 1) * sizeof (wchar_t)); + RegCloseKey (hkey); +} + +BOOL WriteRegistryBytes (wchar_t *path, wchar_t *name, char *str, DWORD size) +{ + HKEY hkey = 0; + DWORD disp; + BOOL res; + + if (RegCreateKeyEx (HKEY_CURRENT_USER, path, + 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &disp) != ERROR_SUCCESS) + return FALSE; + + res = RegSetValueEx (hkey, name, 0, REG_BINARY, (BYTE *) str, size); + RegCloseKey (hkey); + return res == ERROR_SUCCESS; +} + +BOOL DeleteLocalMachineRegistryKey (wchar_t *parentKey, wchar_t *subKeyToDelete) +{ + LONG status; + HKEY hkey = 0; + + if ((status = RegOpenKeyEx (HKEY_LOCAL_MACHINE, parentKey, 0, KEY_WRITE, &hkey)) != ERROR_SUCCESS) + { + SetLastError (status); + return FALSE; + } + + if ((status = RegDeleteKey (hkey, subKeyToDelete)) != ERROR_SUCCESS) + { + RegCloseKey (hkey); + SetLastError (status); + return FALSE; + } + + RegCloseKey (hkey); + return TRUE; +} + +void DeleteRegistryValue (wchar_t *subKey, wchar_t *name) +{ + HKEY hkey = 0; + + if (RegOpenKeyEx (HKEY_CURRENT_USER, subKey, 0, KEY_WRITE, &hkey) != ERROR_SUCCESS) + return; + + RegDeleteValue (hkey, name); + RegCloseKey (hkey); +} + + +void GetStartupRegKeyName (wchar_t *regk, size_t cbRegk) +{ + // The string is split in order to prevent some antivirus packages from falsely reporting + // VeraCrypt.exe to contain a possible Trojan horse because of this string (heuristic scan). + StringCbPrintfW (regk, cbRegk,L"%s%s", L"Software\\Microsoft\\Windows\\Curren", L"tVersion\\Run"); +} + +void GetRestorePointRegKeyName (wchar_t *regk, size_t cbRegk) +{ + // The string is split in order to prevent some antivirus packages from falsely reporting + // VeraCrypt.exe to contain a possible Trojan horse because of this string (heuristic scan). + StringCbPrintfW (regk, cbRegk,L"%s%s%s%s", L"Software\\Microsoft\\Windows", L" NT\\Curren", L"tVersion\\Sy", L"stemRestore"); } \ No newline at end of file diff --git a/src/Common/Registry.h b/src/Common/Registry.h index 692106c5..be80fa4d 100644 --- a/src/Common/Registry.h +++ b/src/Common/Registry.h @@ -1,37 +1,37 @@ -/* - 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. -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -BOOL ReadLocalMachineRegistryDword (wchar_t *subKey, wchar_t *name, DWORD *value); -BOOL ReadLocalMachineRegistryMultiString (wchar_t *subKey, wchar_t *name, wchar_t *value, DWORD *size); -BOOL ReadLocalMachineRegistryString (const wchar_t *subKey, wchar_t *name, wchar_t *value, DWORD *size); -BOOL ReadLocalMachineRegistryStringNonReflected (const wchar_t *subKey, wchar_t *name, wchar_t *str, DWORD *size, BOOL b32bitApp); -int ReadRegistryInt (wchar_t *subKey, wchar_t *name, int defaultValue); -wchar_t *ReadRegistryString (wchar_t *subKey, wchar_t *name, wchar_t *defaultValue, wchar_t *str, int maxLen); -DWORD ReadRegistryBytes (wchar_t *path, wchar_t *name, char *value, int maxLen); -void WriteRegistryInt (wchar_t *subKey, wchar_t *name, int value); -BOOL WriteLocalMachineRegistryDword (wchar_t *subKey, wchar_t *name, DWORD value); -BOOL WriteLocalMachineRegistryMultiString (wchar_t *subKey, wchar_t *name, wchar_t *multiString, DWORD size); -BOOL WriteLocalMachineRegistryString (wchar_t *subKey, wchar_t *name, wchar_t *str, BOOL expandable); -void WriteRegistryString (wchar_t *subKey, wchar_t *name, wchar_t *str); -BOOL WriteRegistryBytes (wchar_t *path, wchar_t *name, char *str, DWORD size); -BOOL DeleteLocalMachineRegistryKey (wchar_t *parentKey, wchar_t *subKeyToDelete); -void DeleteRegistryValue (wchar_t *subKey, wchar_t *name); -void GetStartupRegKeyName (wchar_t *regk, size_t cbRegk); -void GetRestorePointRegKeyName (wchar_t *regk, size_t cbRegk); - -#ifdef __cplusplus -} -#endif +/* + 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. +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +BOOL ReadLocalMachineRegistryDword (wchar_t *subKey, wchar_t *name, DWORD *value); +BOOL ReadLocalMachineRegistryMultiString (wchar_t *subKey, wchar_t *name, wchar_t *value, DWORD *size); +BOOL ReadLocalMachineRegistryString (const wchar_t *subKey, wchar_t *name, wchar_t *value, DWORD *size); +BOOL ReadLocalMachineRegistryStringNonReflected (const wchar_t *subKey, wchar_t *name, wchar_t *str, DWORD *size, BOOL b32bitApp); +int ReadRegistryInt (wchar_t *subKey, wchar_t *name, int defaultValue); +wchar_t *ReadRegistryString (wchar_t *subKey, wchar_t *name, wchar_t *defaultValue, wchar_t *str, int maxLen); +DWORD ReadRegistryBytes (wchar_t *path, wchar_t *name, char *value, int maxLen); +void WriteRegistryInt (wchar_t *subKey, wchar_t *name, int value); +BOOL WriteLocalMachineRegistryDword (wchar_t *subKey, wchar_t *name, DWORD value); +BOOL WriteLocalMachineRegistryMultiString (wchar_t *subKey, wchar_t *name, wchar_t *multiString, DWORD size); +BOOL WriteLocalMachineRegistryString (wchar_t *subKey, wchar_t *name, wchar_t *str, BOOL expandable); +void WriteRegistryString (wchar_t *subKey, wchar_t *name, wchar_t *str); +BOOL WriteRegistryBytes (wchar_t *path, wchar_t *name, char *str, DWORD size); +BOOL DeleteLocalMachineRegistryKey (wchar_t *parentKey, wchar_t *subKeyToDelete); +void DeleteRegistryValue (wchar_t *subKey, wchar_t *name); +void GetStartupRegKeyName (wchar_t *regk, size_t cbRegk); +void GetRestorePointRegKeyName (wchar_t *regk, size_t cbRegk); + +#ifdef __cplusplus +} +#endif diff --git a/src/Common/Resource.h b/src/Common/Resource.h index 8755f6c3..3eca197e 100644 --- a/src/Common/Resource.h +++ b/src/Common/Resource.h @@ -1,211 +1,211 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by Common.rc -// -#define IDI_TRUECRYPT_ICON 501 -#define IDI_TRUECRYPT_VOL_ICON 502 -#define IDD_BENCHMARK_DLG 503 -#define IDD_MOUNT_OPTIONS 504 -#define IDD_KEYFILES 505 -#define IDR_LANGUAGE 506 -#define IDI_TRUECRYPT 507 -#define IDD_ABOUT_DLG 508 -#define IDD_COMMANDHELP_DLG 509 -#define IDD_RAWDEVICES_DLG 510 -#define IDC_HOMEPAGE 511 -#define IDR_COMMON_RSRC_HEADER 512 -#define IDD_LANGUAGE 513 -#define IDD_CIPHER_TEST_DLG 514 -#define IDR_LICENSE 515 -#define IDD_AUXILIARY_DLG 516 -#define IDB_TEXTUAL_LOGO_BKG 517 -#define IDB_TEXTUAL_LOGO_96DPI 518 -#define IDB_TEXTUAL_LOGO_288DPI 519 -#define IDR_BOOT_SECTOR 520 -#define IDR_BOOT_SECTOR_AES 521 -#define IDR_BOOT_SECTOR_SERPENT 522 -#define IDR_BOOT_SECTOR_TWOFISH 523 -#define IDR_BOOT_LOADER_DECOMPRESSOR 524 -#define IDR_BOOT_LOADER 525 -#define IDR_BOOT_LOADER_AES 526 -#define IDR_BOOT_LOADER_SERPENT 527 -#define IDR_BOOT_LOADER_TWOFISH 528 -#define IDR_RESCUE_BOOT_SECTOR 529 -#define IDR_RESCUE_BOOT_SECTOR_AES 530 -#define IDR_RESCUE_BOOT_SECTOR_SERPENT 531 -#define IDR_RESCUE_BOOT_SECTOR_TWOFISH 532 -#define IDR_RESCUE_LOADER 533 -#define IDR_RESCUE_LOADER_AES 534 -#define IDR_RESCUE_LOADER_SERPENT 535 -#define IDR_RESCUE_LOADER_TWOFISH 536 -#define IDD_TOKEN_PASSWORD 537 -#define IDD_TOKEN_KEYFILES 538 -#define IDD_NEW_TOKEN_KEYFILE 539 -#define IDD_RANDOM_POOL_ENRICHMENT 540 -#define IDI_TRUECRYPT_MOUNTED_ICON 541 -#define IDR_BOOT_SECTOR_SHA2 542 -#define IDR_BOOT_SECTOR_AES_SHA2 543 -#define IDR_BOOT_SECTOR_SERPENT_SHA2 544 -#define IDR_BOOT_SECTOR_TWOFISH_SHA2 545 -#define IDR_BOOT_LOADER_SHA2 546 -#define IDR_BOOT_LOADER_AES_SHA2 547 -#define IDR_BOOT_LOADER_SERPENT_SHA2 548 -#define IDR_BOOT_LOADER_TWOFISH_SHA2 549 -#define IDR_RESCUE_BOOT_SECTOR_SHA2 550 -#define IDR_RESCUE_BOOT_SECTOR_AES_SHA2 551 -#define IDR_RESCUE_BOOT_SECTOR_SERPENT_SHA2 552 -#define IDR_RESCUE_BOOT_SECTOR_TWOFISH_SHA2 553 -#define IDR_RESCUE_LOADER_SHA2 554 -#define IDR_RESCUE_LOADER_AES_SHA2 555 -#define IDR_RESCUE_LOADER_SERPENT_SHA2 556 -#define IDR_RESCUE_LOADER_TWOFISH_SHA2 557 -#define IDC_HW_AES_LABEL_LINK 5000 -#define IDC_HW_AES 5001 -#define IDC_PARALLELIZATION_LABEL_LINK 5002 -#define IDC_PARALLELIZATION 5003 -#define IDT_TOKEN_PASSWORD 5004 -#define IDC_PRINT 5005 -#define IDC_KEY 5006 -#define IDC_PLAINTEXT 5007 -#define IDC_CIPHERTEXT 5008 -#define IDC_INFO_BOX_TEXT 5009 -#define IDC_SECONDARY_KEY 5010 -#define IDD_TEXT_INFO_DIALOG_BOX_DLG 5011 -#define IDC_TEST_DATA_UNIT_NUMBER 5012 -#define IDD_KEYFILE_GENERATOR 5013 -#define IDC_CIPHER 5014 -#define IDD_MULTI_CHOICE_DLG 5015 -#define IDC_TEST_BLOCK_NUMBER 5016 -#define IDD_STATIC_MODELESS_WAIT_DLG 5017 -#define IDC_POOL_CONTENTS 5018 -#define IDC_PRF_ID 5019 -#define IDC_KEY_SIZE 5020 -#define IDC_PLAINTEXT_SIZE 5021 -#define IDC_REDTICK 5022 -#define IDC_TESTS_MESSAGE 5023 -#define IDC_RESET 5024 -#define IDC_AUTO 5025 -#define IDC_DECRYPT 5026 -#define IDT_TEST_KEY 5027 -#define IDT_TEST_PLAINTEXT 5028 -#define IDT_PRF 5029 -#define IDT_XTS_MODE 5030 -#define IDT_TEST_CIPHERTEXT 5031 -#define IDT_KEY 5032 -#define IDT_PLAINTEXT 5033 -#define IDC_ENCRYPT 5034 -#define IDT_KEY_UNIT 5035 -#define IDT_CIPHER 5036 -#define IDT_PLAINTEXT_SIZE_UNIT 5037 -#define IDC_DEVICELIST 5038 -#define IDT_TEST_BLOCK_NUMBER 5039 -#define IDT_SECONDARY_KEY 5040 -#define IDC_PERFORM_BENCHMARK 5041 -#define IDT_TEST_DATA_UNIT_NUMBER 5042 -#define IDC_KEYFILES_HIDVOL_PROT 5043 -#define IDC_KEYLIST 5044 -#define IDC_ABOUT_BKG 5045 -#define IDT_ABOUT_VERSION 5046 -#define IDT_BOX_BENCHMARK_INFO 5047 -#define IDC_ABOUT_CREDITS 5048 -#define IDT_SORT_METHOD 5049 -#define IDC_MOUNT_READONLY 5050 -#define IDC_MOUNT_REMOVABLE 5051 -#define IDC_PROTECT_HIDDEN_VOL 5052 -#define IDC_COMMANDHELP_TEXT 5053 -#define IDC_USE_EMBEDDED_HEADER_BAK 5054 -#define IDC_MOUNT_SYSENC_PART_WITHOUT_PBA 5055 -#define IDT_HIDDEN_PROT_PASSWD 5056 -#define IDC_RESULTS 5057 -#define IDC_KEYADD 5058 -#define IDC_KEYREMOVE 5059 -#define IDC_KEYREMOVEALL 5060 -#define IDC_KEYFILES_ENABLE 5061 -#define IDT_HIDDEN_VOL_PROTECTION 5062 -#define IDC_ADD_KEYFILE_PATH 5063 -#define IDC_BENCHMARK_BUFFER_SIZE 5064 -#define IDC_SHOW_PASSWORD_MO 5065 -#define IDC_GENERATE_KEYFILE 5066 -#define IDC_BENCHMARK_SORT_METHOD 5067 -#define IDC_PASSWORD_PROT_HIDVOL 5068 -#define IDT_BUFFER_SIZE 5069 -#define IDC_LANGLIST 5070 -#define IDC_KEYFILES_ENABLE_HIDVOL_PROT 5071 -#define IDT_KEYFILES_NOTE 5072 -#define IDT_KEYFILE_WARNING 5073 -#define IDT_KEYFILE_GENERATOR_NOTE 5074 -#define IDC_GENERATE_AND_SAVE_KEYFILE 5075 -#define IDT_POOL_CONTENTS 5076 -#define IDC_GET_LANG_PACKS 5077 -#define IDT_LANGPACK_AUTHORS 5078 -#define IDC_LANGPACK_CREDITS 5079 -#define IDC_LANGPACK_VERSION 5080 -#define IDT_ACTIVE_LANG_PACK 5081 -#define IDC_DISPLAY_POOL_CONTENTS 5082 -#define IDC_XTS_MODE_ENABLED 5083 -#define IDC_MULTI_CHOICE_MSG 5084 -#define IDC_CHOICE1 5085 -#define IDC_CHOICE5 5086 -#define IDC_CHOICE2 5087 -#define IDC_CHOICE3 5088 -#define IDC_CHOICE4 5089 -#define IDC_CHOICE6 5090 -#define IDC_CHOICE7 5091 -#define IDC_CHOICE8 5092 -#define IDC_CHOICE9 5093 -#define IDC_CHOICE10 5094 -#define IDC_MC_DLG_HR1 5095 -#define IDC_MC_DLG_HR2 5096 -#define IDC_LINK_HIDVOL_PROTECTION_INFO 5097 -#define IDC_LINK_KEYFILES_INFO 5098 -#define IDC_TEXTUAL_LOGO_IMG 5099 -#define IDC_ASPECT_RATIO_CALIBRATION_BOX 5100 -#define IDC_ABOUT_LOGO_AREA 5101 -#define IDC_TOKEN_PASSWORD 5102 -#define IDC_TOKEN_FILE_LIST 5103 -#define IDC_TOKEN_FILES_ADD 5104 -#define IDC_EXPORT 5105 -#define IDC_DELETE 5106 -#define IDC_IMPORT_KEYFILE 5107 -#define IDC_SELECTED_TOKEN 5108 -#define IDT_SECURITY_TOKEN 5109 -#define IDT_TOKEN_KEYFILE_NAME 5110 -#define IDC_TOKEN_KEYFILE_NAME 5111 -#define IDT_TOKEN_PASSWORD_INFO 5112 -#define IDT_RANDOM_POOL_ENRICHMENT_NOTE 5113 -#define IDC_CONTINUE 5114 -#define IDT_ABOUT_RELEASE 5115 -#define IDT_STATIC_MODELESS_WAIT_DLG_INFO 5116 -#define IDT_NUMBER_KEYFILES 5117 -#define IDC_NUMBER_KEYFILES 5118 -#define IDT_KEYFILES_BASE_NAME 5119 -#define IDC_KEYFILES_BASE_NAME 5120 -#define IDC_KEYFILES_SIZE 5121 -#define IDC_KEYFILES_RANDOM_SIZE 5122 -#define IDT_KEYFILES_SIZE 5123 -#define IDD_STATIC_MODAL_WAIT_DLG 5124 -#define IDT_STATIC_MODAL_WAIT_DLG_INFO 5125 -#define IDC_WAIT_PROGRESS_BAR 5126 -#define IDC_PKCS5_PRF_ID 5127 -#define IDT_PKCS5_PRF 5128 -#define IDT_PIM 5129 -#define IDC_PIM 5130 -#define IDC_PIM_HELP 5131 -#define IDC_PIM_ENABLE 5132 -#define IDC_VOLUME_LABEL 5133 -#define IDT_VOLUME_LABEL 5134 -#define IDC_KEYFILES_TRY_EMPTY_PASSWORD 5135 -#define IDC_ENTROPY_BAR 5136 -#define IDT_ENTROPY_BAR 5137 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NO_MFC 1 -#define _APS_NEXT_RESOURCE_VALUE 558 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 5138 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Common.rc +// +#define IDI_TRUECRYPT_ICON 501 +#define IDI_TRUECRYPT_VOL_ICON 502 +#define IDD_BENCHMARK_DLG 503 +#define IDD_MOUNT_OPTIONS 504 +#define IDD_KEYFILES 505 +#define IDR_LANGUAGE 506 +#define IDI_TRUECRYPT 507 +#define IDD_ABOUT_DLG 508 +#define IDD_COMMANDHELP_DLG 509 +#define IDD_RAWDEVICES_DLG 510 +#define IDC_HOMEPAGE 511 +#define IDR_COMMON_RSRC_HEADER 512 +#define IDD_LANGUAGE 513 +#define IDD_CIPHER_TEST_DLG 514 +#define IDR_LICENSE 515 +#define IDD_AUXILIARY_DLG 516 +#define IDB_TEXTUAL_LOGO_BKG 517 +#define IDB_TEXTUAL_LOGO_96DPI 518 +#define IDB_TEXTUAL_LOGO_288DPI 519 +#define IDR_BOOT_SECTOR 520 +#define IDR_BOOT_SECTOR_AES 521 +#define IDR_BOOT_SECTOR_SERPENT 522 +#define IDR_BOOT_SECTOR_TWOFISH 523 +#define IDR_BOOT_LOADER_DECOMPRESSOR 524 +#define IDR_BOOT_LOADER 525 +#define IDR_BOOT_LOADER_AES 526 +#define IDR_BOOT_LOADER_SERPENT 527 +#define IDR_BOOT_LOADER_TWOFISH 528 +#define IDR_RESCUE_BOOT_SECTOR 529 +#define IDR_RESCUE_BOOT_SECTOR_AES 530 +#define IDR_RESCUE_BOOT_SECTOR_SERPENT 531 +#define IDR_RESCUE_BOOT_SECTOR_TWOFISH 532 +#define IDR_RESCUE_LOADER 533 +#define IDR_RESCUE_LOADER_AES 534 +#define IDR_RESCUE_LOADER_SERPENT 535 +#define IDR_RESCUE_LOADER_TWOFISH 536 +#define IDD_TOKEN_PASSWORD 537 +#define IDD_TOKEN_KEYFILES 538 +#define IDD_NEW_TOKEN_KEYFILE 539 +#define IDD_RANDOM_POOL_ENRICHMENT 540 +#define IDI_TRUECRYPT_MOUNTED_ICON 541 +#define IDR_BOOT_SECTOR_SHA2 542 +#define IDR_BOOT_SECTOR_AES_SHA2 543 +#define IDR_BOOT_SECTOR_SERPENT_SHA2 544 +#define IDR_BOOT_SECTOR_TWOFISH_SHA2 545 +#define IDR_BOOT_LOADER_SHA2 546 +#define IDR_BOOT_LOADER_AES_SHA2 547 +#define IDR_BOOT_LOADER_SERPENT_SHA2 548 +#define IDR_BOOT_LOADER_TWOFISH_SHA2 549 +#define IDR_RESCUE_BOOT_SECTOR_SHA2 550 +#define IDR_RESCUE_BOOT_SECTOR_AES_SHA2 551 +#define IDR_RESCUE_BOOT_SECTOR_SERPENT_SHA2 552 +#define IDR_RESCUE_BOOT_SECTOR_TWOFISH_SHA2 553 +#define IDR_RESCUE_LOADER_SHA2 554 +#define IDR_RESCUE_LOADER_AES_SHA2 555 +#define IDR_RESCUE_LOADER_SERPENT_SHA2 556 +#define IDR_RESCUE_LOADER_TWOFISH_SHA2 557 +#define IDC_HW_AES_LABEL_LINK 5000 +#define IDC_HW_AES 5001 +#define IDC_PARALLELIZATION_LABEL_LINK 5002 +#define IDC_PARALLELIZATION 5003 +#define IDT_TOKEN_PASSWORD 5004 +#define IDC_PRINT 5005 +#define IDC_KEY 5006 +#define IDC_PLAINTEXT 5007 +#define IDC_CIPHERTEXT 5008 +#define IDC_INFO_BOX_TEXT 5009 +#define IDC_SECONDARY_KEY 5010 +#define IDD_TEXT_INFO_DIALOG_BOX_DLG 5011 +#define IDC_TEST_DATA_UNIT_NUMBER 5012 +#define IDD_KEYFILE_GENERATOR 5013 +#define IDC_CIPHER 5014 +#define IDD_MULTI_CHOICE_DLG 5015 +#define IDC_TEST_BLOCK_NUMBER 5016 +#define IDD_STATIC_MODELESS_WAIT_DLG 5017 +#define IDC_POOL_CONTENTS 5018 +#define IDC_PRF_ID 5019 +#define IDC_KEY_SIZE 5020 +#define IDC_PLAINTEXT_SIZE 5021 +#define IDC_REDTICK 5022 +#define IDC_TESTS_MESSAGE 5023 +#define IDC_RESET 5024 +#define IDC_AUTO 5025 +#define IDC_DECRYPT 5026 +#define IDT_TEST_KEY 5027 +#define IDT_TEST_PLAINTEXT 5028 +#define IDT_PRF 5029 +#define IDT_XTS_MODE 5030 +#define IDT_TEST_CIPHERTEXT 5031 +#define IDT_KEY 5032 +#define IDT_PLAINTEXT 5033 +#define IDC_ENCRYPT 5034 +#define IDT_KEY_UNIT 5035 +#define IDT_CIPHER 5036 +#define IDT_PLAINTEXT_SIZE_UNIT 5037 +#define IDC_DEVICELIST 5038 +#define IDT_TEST_BLOCK_NUMBER 5039 +#define IDT_SECONDARY_KEY 5040 +#define IDC_PERFORM_BENCHMARK 5041 +#define IDT_TEST_DATA_UNIT_NUMBER 5042 +#define IDC_KEYFILES_HIDVOL_PROT 5043 +#define IDC_KEYLIST 5044 +#define IDC_ABOUT_BKG 5045 +#define IDT_ABOUT_VERSION 5046 +#define IDT_BOX_BENCHMARK_INFO 5047 +#define IDC_ABOUT_CREDITS 5048 +#define IDT_SORT_METHOD 5049 +#define IDC_MOUNT_READONLY 5050 +#define IDC_MOUNT_REMOVABLE 5051 +#define IDC_PROTECT_HIDDEN_VOL 5052 +#define IDC_COMMANDHELP_TEXT 5053 +#define IDC_USE_EMBEDDED_HEADER_BAK 5054 +#define IDC_MOUNT_SYSENC_PART_WITHOUT_PBA 5055 +#define IDT_HIDDEN_PROT_PASSWD 5056 +#define IDC_RESULTS 5057 +#define IDC_KEYADD 5058 +#define IDC_KEYREMOVE 5059 +#define IDC_KEYREMOVEALL 5060 +#define IDC_KEYFILES_ENABLE 5061 +#define IDT_HIDDEN_VOL_PROTECTION 5062 +#define IDC_ADD_KEYFILE_PATH 5063 +#define IDC_BENCHMARK_BUFFER_SIZE 5064 +#define IDC_SHOW_PASSWORD_MO 5065 +#define IDC_GENERATE_KEYFILE 5066 +#define IDC_BENCHMARK_SORT_METHOD 5067 +#define IDC_PASSWORD_PROT_HIDVOL 5068 +#define IDT_BUFFER_SIZE 5069 +#define IDC_LANGLIST 5070 +#define IDC_KEYFILES_ENABLE_HIDVOL_PROT 5071 +#define IDT_KEYFILES_NOTE 5072 +#define IDT_KEYFILE_WARNING 5073 +#define IDT_KEYFILE_GENERATOR_NOTE 5074 +#define IDC_GENERATE_AND_SAVE_KEYFILE 5075 +#define IDT_POOL_CONTENTS 5076 +#define IDC_GET_LANG_PACKS 5077 +#define IDT_LANGPACK_AUTHORS 5078 +#define IDC_LANGPACK_CREDITS 5079 +#define IDC_LANGPACK_VERSION 5080 +#define IDT_ACTIVE_LANG_PACK 5081 +#define IDC_DISPLAY_POOL_CONTENTS 5082 +#define IDC_XTS_MODE_ENABLED 5083 +#define IDC_MULTI_CHOICE_MSG 5084 +#define IDC_CHOICE1 5085 +#define IDC_CHOICE5 5086 +#define IDC_CHOICE2 5087 +#define IDC_CHOICE3 5088 +#define IDC_CHOICE4 5089 +#define IDC_CHOICE6 5090 +#define IDC_CHOICE7 5091 +#define IDC_CHOICE8 5092 +#define IDC_CHOICE9 5093 +#define IDC_CHOICE10 5094 +#define IDC_MC_DLG_HR1 5095 +#define IDC_MC_DLG_HR2 5096 +#define IDC_LINK_HIDVOL_PROTECTION_INFO 5097 +#define IDC_LINK_KEYFILES_INFO 5098 +#define IDC_TEXTUAL_LOGO_IMG 5099 +#define IDC_ASPECT_RATIO_CALIBRATION_BOX 5100 +#define IDC_ABOUT_LOGO_AREA 5101 +#define IDC_TOKEN_PASSWORD 5102 +#define IDC_TOKEN_FILE_LIST 5103 +#define IDC_TOKEN_FILES_ADD 5104 +#define IDC_EXPORT 5105 +#define IDC_DELETE 5106 +#define IDC_IMPORT_KEYFILE 5107 +#define IDC_SELECTED_TOKEN 5108 +#define IDT_SECURITY_TOKEN 5109 +#define IDT_TOKEN_KEYFILE_NAME 5110 +#define IDC_TOKEN_KEYFILE_NAME 5111 +#define IDT_TOKEN_PASSWORD_INFO 5112 +#define IDT_RANDOM_POOL_ENRICHMENT_NOTE 5113 +#define IDC_CONTINUE 5114 +#define IDT_ABOUT_RELEASE 5115 +#define IDT_STATIC_MODELESS_WAIT_DLG_INFO 5116 +#define IDT_NUMBER_KEYFILES 5117 +#define IDC_NUMBER_KEYFILES 5118 +#define IDT_KEYFILES_BASE_NAME 5119 +#define IDC_KEYFILES_BASE_NAME 5120 +#define IDC_KEYFILES_SIZE 5121 +#define IDC_KEYFILES_RANDOM_SIZE 5122 +#define IDT_KEYFILES_SIZE 5123 +#define IDD_STATIC_MODAL_WAIT_DLG 5124 +#define IDT_STATIC_MODAL_WAIT_DLG_INFO 5125 +#define IDC_WAIT_PROGRESS_BAR 5126 +#define IDC_PKCS5_PRF_ID 5127 +#define IDT_PKCS5_PRF 5128 +#define IDT_PIM 5129 +#define IDC_PIM 5130 +#define IDC_PIM_HELP 5131 +#define IDC_PIM_ENABLE 5132 +#define IDC_VOLUME_LABEL 5133 +#define IDT_VOLUME_LABEL 5134 +#define IDC_KEYFILES_TRY_EMPTY_PASSWORD 5135 +#define IDC_ENTROPY_BAR 5136 +#define IDT_ENTROPY_BAR 5137 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NO_MFC 1 +#define _APS_NEXT_RESOURCE_VALUE 558 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 5138 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/src/Common/SecurityToken.cpp b/src/Common/SecurityToken.cpp index db80ff0d..8909059d 100644 --- a/src/Common/SecurityToken.cpp +++ b/src/Common/SecurityToken.cpp @@ -1,787 +1,787 @@ -/* - 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 "Platform/Finally.h" -#include "Platform/ForEach.h" - -#if !defined (TC_WINDOWS) || defined (TC_PROTOTYPE) -# include "Platform/SerializerFactory.h" -# include "Platform/StringConverter.h" -# include "Platform/SystemException.h" -#else -# include "Dictionary.h" -# include "Language.h" -#endif - -#ifdef TC_UNIX -# include -#endif - -#include "SecurityToken.h" - -#ifndef burn -# define burn Memory::Erase -#endif - -using namespace std; - -namespace VeraCrypt -{ - SecurityTokenKeyfile::SecurityTokenKeyfile (const SecurityTokenKeyfilePath &path, char* pin) - { - wstring pathStr = path; - unsigned long slotId; - - if (swscanf (pathStr.c_str(), TC_SECURITY_TOKEN_KEYFILE_URL_PREFIX TC_SECURITY_TOKEN_KEYFILE_URL_SLOT L"/%lu", &slotId) != 1) - throw InvalidSecurityTokenKeyfilePath(); - - SlotId = slotId; - - size_t keyIdPos = pathStr.find (L"/" TC_SECURITY_TOKEN_KEYFILE_URL_FILE L"/"); - if (keyIdPos == wstring::npos) - throw InvalidSecurityTokenKeyfilePath(); - - Id = pathStr.substr (keyIdPos + wstring (L"/" TC_SECURITY_TOKEN_KEYFILE_URL_FILE L"/").size()); - - vector keyfiles = SecurityToken::GetAvailableKeyfiles (&SlotId, Id, pin); - - if (keyfiles.empty()) - throw SecurityTokenKeyfileNotFound(); - - *this = keyfiles.front(); - } - - SecurityTokenKeyfile::operator SecurityTokenKeyfilePath () const - { - wstringstream path; - path << TC_SECURITY_TOKEN_KEYFILE_URL_PREFIX TC_SECURITY_TOKEN_KEYFILE_URL_SLOT L"/" << SlotId << L"/" TC_SECURITY_TOKEN_KEYFILE_URL_FILE L"/" << Id; - return path.str(); - } - - void SecurityToken::CheckLibraryStatus () - { - if (!Initialized) - throw SecurityTokenLibraryNotInitialized(); - } - - void SecurityToken::CloseLibrary () - { - if (Initialized) - { - CloseAllSessions(); - Pkcs11Functions->C_Finalize (NULL_PTR); - -#ifdef TC_WINDOWS - FreeLibrary (Pkcs11LibraryHandle); -#else - dlclose (Pkcs11LibraryHandle); -#endif - Initialized = false; - } - } - - void SecurityToken::CloseAllSessions () throw () - { - if (!Initialized) - return; - - typedef pair SessionMapPair; - - foreach (SessionMapPair p, Sessions) - { - try - { - CloseSession (p.first); - } - catch (...) { } - } - } - - void SecurityToken::CloseSession (CK_SLOT_ID slotId) - { - if (Sessions.find (slotId) == Sessions.end()) - throw ParameterIncorrect (SRC_POS); - - Pkcs11Functions->C_CloseSession (Sessions[slotId].Handle); - Sessions.erase (Sessions.find (slotId)); - } - - void SecurityToken::CreateKeyfile (CK_SLOT_ID slotId, vector &keyfileData, const string &name) - { - if (name.empty()) - throw ParameterIncorrect (SRC_POS); - - LoginUserIfRequired (slotId); - - foreach (const SecurityTokenKeyfile &keyfile, GetAvailableKeyfiles (&slotId)) - { - if (keyfile.IdUtf8 == name) - throw SecurityTokenKeyfileAlreadyExists(); - } - - CK_OBJECT_CLASS dataClass = CKO_DATA; - CK_BBOOL trueVal = CK_TRUE; - - CK_ATTRIBUTE keyfileTemplate[] = - { - { CKA_CLASS, &dataClass, sizeof (dataClass) }, - { CKA_TOKEN, &trueVal, sizeof (trueVal) }, - { CKA_PRIVATE, &trueVal, sizeof (trueVal) }, - { CKA_LABEL, (CK_UTF8CHAR *) name.c_str(), (CK_ULONG) name.size() }, - { CKA_VALUE, &keyfileData.front(), (CK_ULONG) keyfileData.size() } - }; - - CK_OBJECT_HANDLE keyfileHandle; - - CK_RV status = Pkcs11Functions->C_CreateObject (Sessions[slotId].Handle, keyfileTemplate, array_capacity (keyfileTemplate), &keyfileHandle); - - switch (status) - { - case CKR_DATA_LEN_RANGE: - status = CKR_DEVICE_MEMORY; - break; - - case CKR_SESSION_READ_ONLY: - status = CKR_TOKEN_WRITE_PROTECTED; - break; - } - - if (status != CKR_OK) - throw Pkcs11Exception (status); - - // Some tokens report success even if the new object was truncated to fit in the available memory - vector objectData; - - GetObjectAttribute (slotId, keyfileHandle, CKA_VALUE, objectData); - finally_do_arg (vector *, &objectData, { if (!finally_arg->empty()) burn (&finally_arg->front(), finally_arg->size()); }); - - if (objectData.size() != keyfileData.size()) - { - Pkcs11Functions->C_DestroyObject (Sessions[slotId].Handle, keyfileHandle); - throw Pkcs11Exception (CKR_DEVICE_MEMORY); - } - } - - void SecurityToken::DeleteKeyfile (const SecurityTokenKeyfile &keyfile) - { - LoginUserIfRequired (keyfile.SlotId); - - CK_RV status = Pkcs11Functions->C_DestroyObject (Sessions[keyfile.SlotId].Handle, keyfile.Handle); - if (status != CKR_OK) - throw Pkcs11Exception (status); - } - - vector SecurityToken::GetAvailableKeyfiles (CK_SLOT_ID *slotIdFilter, const wstring keyfileIdFilter, char* pin) - { - bool unrecognizedTokenPresent = false; - vector keyfiles; - - foreach (const CK_SLOT_ID &slotId, GetTokenSlots()) - { - SecurityTokenInfo token; - - if (slotIdFilter && *slotIdFilter != slotId) - continue; - - try - { - LoginUserIfRequired (slotId, pin); - token = GetTokenInfo (slotId); - } - catch (UserAbort &) - { - continue; - } - catch (Pkcs11Exception &e) - { - if (e.GetErrorCode() == CKR_TOKEN_NOT_RECOGNIZED) - { - unrecognizedTokenPresent = true; - continue; - } - - throw; - } - - foreach (const CK_OBJECT_HANDLE &dataHandle, GetObjects (slotId, CKO_DATA)) - { - SecurityTokenKeyfile keyfile; - keyfile.Handle = dataHandle; - keyfile.SlotId = slotId; - keyfile.Token = token; - - vector privateAttrib; - GetObjectAttribute (slotId, dataHandle, CKA_PRIVATE, privateAttrib); - - if (privateAttrib.size() == sizeof (CK_BBOOL) && *(CK_BBOOL *) &privateAttrib.front() != CK_TRUE) - continue; - - vector label; - GetObjectAttribute (slotId, dataHandle, CKA_LABEL, label); - label.push_back (0); - - keyfile.IdUtf8 = (char *) &label.front(); - -#if defined (TC_WINDOWS) && !defined (TC_PROTOTYPE) - keyfile.Id = Utf8StringToWide ((const char *) &label.front()); -#else - keyfile.Id = StringConverter::ToWide ((const char *) &label.front()); -#endif - if (keyfile.Id.empty() || (!keyfileIdFilter.empty() && keyfileIdFilter != keyfile.Id)) - continue; - - keyfiles.push_back (keyfile); - - if (!keyfileIdFilter.empty()) - break; - } - } - - if (keyfiles.empty() && unrecognizedTokenPresent) - throw Pkcs11Exception (CKR_TOKEN_NOT_RECOGNIZED); - - return keyfiles; - } - - list SecurityToken::GetAvailableTokens () - { - bool unrecognizedTokenPresent = false; - list tokens; - - foreach (const CK_SLOT_ID &slotId, GetTokenSlots()) - { - try - { - tokens.push_back (GetTokenInfo (slotId)); - } - catch (Pkcs11Exception &e) - { - if (e.GetErrorCode() == CKR_TOKEN_NOT_RECOGNIZED) - { - unrecognizedTokenPresent = true; - continue; - } - - throw; - } - } - - if (tokens.empty() && unrecognizedTokenPresent) - throw Pkcs11Exception (CKR_TOKEN_NOT_RECOGNIZED); - - return tokens; - } - - SecurityTokenInfo SecurityToken::GetTokenInfo (CK_SLOT_ID slotId) - { - CK_TOKEN_INFO info; - CK_RV status = Pkcs11Functions->C_GetTokenInfo (slotId, &info); - if (status != CKR_OK) - throw Pkcs11Exception (status); - - SecurityTokenInfo token; - token.SlotId = slotId; - token.Flags = info.flags; - - char label[sizeof (info.label) + 1]; - memset (label, 0, sizeof (label)); - memcpy (label, info.label, sizeof (info.label)); - - token.LabelUtf8 = label; - - size_t lastSpace = token.LabelUtf8.find_last_not_of (' '); - if (lastSpace == string::npos) - token.LabelUtf8.clear(); - else - token.LabelUtf8 = token.LabelUtf8.substr (0, lastSpace + 1); - -#if defined (TC_WINDOWS) && !defined (TC_PROTOTYPE) - token.Label = Utf8StringToWide (token.LabelUtf8); -#else - token.Label = StringConverter::ToWide (token.LabelUtf8); -#endif - return token; - } - - void SecurityToken::GetKeyfileData (const SecurityTokenKeyfile &keyfile, vector &keyfileData) - { - GetKeyfileData (keyfile, nullptr, keyfileData); - } - - void SecurityToken::GetKeyfileData (const SecurityTokenKeyfile &keyfile, char* pin, vector &keyfileData) - { - LoginUserIfRequired (keyfile.SlotId, pin); - GetObjectAttribute (keyfile.SlotId, keyfile.Handle, CKA_VALUE, keyfileData); - } - - vector SecurityToken::GetObjects (CK_SLOT_ID slotId, CK_ATTRIBUTE_TYPE objectClass) - { - if (Sessions.find (slotId) == Sessions.end()) - throw ParameterIncorrect (SRC_POS); - - CK_ATTRIBUTE findTemplate; - findTemplate.type = CKA_CLASS; - findTemplate.pValue = &objectClass; - findTemplate.ulValueLen = sizeof (objectClass); - - CK_RV status = Pkcs11Functions->C_FindObjectsInit (Sessions[slotId].Handle, &findTemplate, 1); - if (status != CKR_OK) - throw Pkcs11Exception (status); - - finally_do_arg (CK_SLOT_ID, slotId, { Pkcs11Functions->C_FindObjectsFinal (Sessions[finally_arg].Handle); }); - - CK_ULONG objectCount; - vector objects; - - while (true) - { - CK_OBJECT_HANDLE object; - CK_RV status = Pkcs11Functions->C_FindObjects (Sessions[slotId].Handle, &object, 1, &objectCount); - if (status != CKR_OK) - throw Pkcs11Exception (status); - - if (objectCount != 1) - break; - - objects.push_back (object); - } - - return objects; - } - - void SecurityToken::GetObjectAttribute (CK_SLOT_ID slotId, CK_OBJECT_HANDLE tokenObject, CK_ATTRIBUTE_TYPE attributeType, vector &attributeValue) - { - attributeValue.clear(); - - if (Sessions.find (slotId) == Sessions.end()) - throw ParameterIncorrect (SRC_POS); - - CK_ATTRIBUTE attribute; - attribute.type = attributeType; - attribute.pValue = NULL_PTR; - - CK_RV status = Pkcs11Functions->C_GetAttributeValue (Sessions[slotId].Handle, tokenObject, &attribute, 1); - if (status != CKR_OK) - throw Pkcs11Exception (status); - - if (attribute.ulValueLen == 0) - return; - - attributeValue = vector (attribute.ulValueLen); - attribute.pValue = &attributeValue.front(); - - status = Pkcs11Functions->C_GetAttributeValue (Sessions[slotId].Handle, tokenObject, &attribute, 1); - if (status != CKR_OK) - throw Pkcs11Exception (status); - } - - list SecurityToken::GetTokenSlots () - { - CheckLibraryStatus(); - - list slots; - CK_ULONG slotCount; - - CK_RV status = Pkcs11Functions->C_GetSlotList (TRUE, NULL_PTR, &slotCount); - if (status != CKR_OK) - throw Pkcs11Exception (status); - - if (slotCount > 0) - { - vector slotArray (slotCount); - status = Pkcs11Functions->C_GetSlotList (TRUE, &slotArray.front(), &slotCount); - if (status != CKR_OK) - throw Pkcs11Exception (status); - - for (size_t i = 0; i < slotCount; i++) - { - CK_SLOT_INFO slotInfo; - status = Pkcs11Functions->C_GetSlotInfo (slotArray[i], &slotInfo); - - if (status != CKR_OK || !(slotInfo.flags & CKF_TOKEN_PRESENT)) - continue; - - slots.push_back (slotArray[i]); - } - } - - return slots; - } - - bool SecurityToken::IsKeyfilePathValid (const wstring &securityTokenKeyfilePath) - { - return securityTokenKeyfilePath.find (TC_SECURITY_TOKEN_KEYFILE_URL_PREFIX) == 0; - } - - void SecurityToken::Login (CK_SLOT_ID slotId, const char* pin) - { - if (Sessions.find (slotId) == Sessions.end()) - OpenSession (slotId); - else if (Sessions[slotId].UserLoggedIn) - return; - - size_t pinLen = pin? strlen (pin) : 0; - CK_RV status = Pkcs11Functions->C_Login (Sessions[slotId].Handle, CKU_USER, (CK_CHAR_PTR) pin, (CK_ULONG) pinLen); - - if (status != CKR_OK) - throw Pkcs11Exception (status); - - Sessions[slotId].UserLoggedIn = true; - } - - void SecurityToken::LoginUserIfRequired (CK_SLOT_ID slotId, char* cmdPin) - { - CheckLibraryStatus(); - CK_RV status; - - if (Sessions.find (slotId) == Sessions.end()) - { - OpenSession (slotId); - } - else - { - CK_SESSION_INFO sessionInfo; - status = Pkcs11Functions->C_GetSessionInfo (Sessions[slotId].Handle, &sessionInfo); - - if (status == CKR_OK) - { - Sessions[slotId].UserLoggedIn = (sessionInfo.state == CKS_RO_USER_FUNCTIONS || sessionInfo.state == CKS_RW_USER_FUNCTIONS); - } - else - { - try - { - CloseSession (slotId); - } - catch (...) { } - OpenSession (slotId); - } - } - - SecurityTokenInfo tokenInfo = GetTokenInfo (slotId); - - while (!Sessions[slotId].UserLoggedIn && (tokenInfo.Flags & CKF_LOGIN_REQUIRED)) - { - try - { - if (tokenInfo.Flags & CKF_PROTECTED_AUTHENTICATION_PATH) - { - status = Pkcs11Functions->C_Login (Sessions[slotId].Handle, CKU_USER, NULL_PTR, 0); - if (status != CKR_OK) - throw Pkcs11Exception (status); - } - else if (cmdPin && cmdPin [0]) - { - Login (slotId, cmdPin); - } - else - { - string pin = tokenInfo.LabelUtf8; - if (tokenInfo.Label.empty()) - { - stringstream s; - s << "#" << slotId; - pin = s.str(); - } - - finally_do_arg (string*, &pin, { burn ((void *) finally_arg->c_str(), finally_arg->size()); }); - - (*PinCallback) (pin); - Login (slotId, pin.c_str()); - } - - Sessions[slotId].UserLoggedIn = true; - } - catch (Pkcs11Exception &e) - { - CK_RV error = e.GetErrorCode(); - - if (error == CKR_USER_ALREADY_LOGGED_IN) - { - break; - } - else if (error == CKR_PIN_INCORRECT && !(tokenInfo.Flags & CKF_PROTECTED_AUTHENTICATION_PATH)) - { - if (cmdPin && cmdPin [0]) - { - // clear wrong PIN - size_t cmdPinLen = strlen (cmdPin); - burn (cmdPin, cmdPinLen); - } - (*WarningCallback) (Pkcs11Exception (CKR_PIN_INCORRECT)); - continue; - } - - throw; - } - } - } - -#ifdef TC_WINDOWS - void SecurityToken::InitLibrary (const wstring &pkcs11LibraryPath, auto_ptr pinCallback, auto_ptr warningCallback) -#else - void SecurityToken::InitLibrary (const string &pkcs11LibraryPath, auto_ptr pinCallback, auto_ptr warningCallback) -#endif - { - if (Initialized) - CloseLibrary(); - -#ifdef TC_WINDOWS +/* + 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 "Platform/Finally.h" +#include "Platform/ForEach.h" + +#if !defined (TC_WINDOWS) || defined (TC_PROTOTYPE) +# include "Platform/SerializerFactory.h" +# include "Platform/StringConverter.h" +# include "Platform/SystemException.h" +#else +# include "Dictionary.h" +# include "Language.h" +#endif + +#ifdef TC_UNIX +# include +#endif + +#include "SecurityToken.h" + +#ifndef burn +# define burn Memory::Erase +#endif + +using namespace std; + +namespace VeraCrypt +{ + SecurityTokenKeyfile::SecurityTokenKeyfile (const SecurityTokenKeyfilePath &path, char* pin) + { + wstring pathStr = path; + unsigned long slotId; + + if (swscanf (pathStr.c_str(), TC_SECURITY_TOKEN_KEYFILE_URL_PREFIX TC_SECURITY_TOKEN_KEYFILE_URL_SLOT L"/%lu", &slotId) != 1) + throw InvalidSecurityTokenKeyfilePath(); + + SlotId = slotId; + + size_t keyIdPos = pathStr.find (L"/" TC_SECURITY_TOKEN_KEYFILE_URL_FILE L"/"); + if (keyIdPos == wstring::npos) + throw InvalidSecurityTokenKeyfilePath(); + + Id = pathStr.substr (keyIdPos + wstring (L"/" TC_SECURITY_TOKEN_KEYFILE_URL_FILE L"/").size()); + + vector keyfiles = SecurityToken::GetAvailableKeyfiles (&SlotId, Id, pin); + + if (keyfiles.empty()) + throw SecurityTokenKeyfileNotFound(); + + *this = keyfiles.front(); + } + + SecurityTokenKeyfile::operator SecurityTokenKeyfilePath () const + { + wstringstream path; + path << TC_SECURITY_TOKEN_KEYFILE_URL_PREFIX TC_SECURITY_TOKEN_KEYFILE_URL_SLOT L"/" << SlotId << L"/" TC_SECURITY_TOKEN_KEYFILE_URL_FILE L"/" << Id; + return path.str(); + } + + void SecurityToken::CheckLibraryStatus () + { + if (!Initialized) + throw SecurityTokenLibraryNotInitialized(); + } + + void SecurityToken::CloseLibrary () + { + if (Initialized) + { + CloseAllSessions(); + Pkcs11Functions->C_Finalize (NULL_PTR); + +#ifdef TC_WINDOWS + FreeLibrary (Pkcs11LibraryHandle); +#else + dlclose (Pkcs11LibraryHandle); +#endif + Initialized = false; + } + } + + void SecurityToken::CloseAllSessions () throw () + { + if (!Initialized) + return; + + typedef pair SessionMapPair; + + foreach (SessionMapPair p, Sessions) + { + try + { + CloseSession (p.first); + } + catch (...) { } + } + } + + void SecurityToken::CloseSession (CK_SLOT_ID slotId) + { + if (Sessions.find (slotId) == Sessions.end()) + throw ParameterIncorrect (SRC_POS); + + Pkcs11Functions->C_CloseSession (Sessions[slotId].Handle); + Sessions.erase (Sessions.find (slotId)); + } + + void SecurityToken::CreateKeyfile (CK_SLOT_ID slotId, vector &keyfileData, const string &name) + { + if (name.empty()) + throw ParameterIncorrect (SRC_POS); + + LoginUserIfRequired (slotId); + + foreach (const SecurityTokenKeyfile &keyfile, GetAvailableKeyfiles (&slotId)) + { + if (keyfile.IdUtf8 == name) + throw SecurityTokenKeyfileAlreadyExists(); + } + + CK_OBJECT_CLASS dataClass = CKO_DATA; + CK_BBOOL trueVal = CK_TRUE; + + CK_ATTRIBUTE keyfileTemplate[] = + { + { CKA_CLASS, &dataClass, sizeof (dataClass) }, + { CKA_TOKEN, &trueVal, sizeof (trueVal) }, + { CKA_PRIVATE, &trueVal, sizeof (trueVal) }, + { CKA_LABEL, (CK_UTF8CHAR *) name.c_str(), (CK_ULONG) name.size() }, + { CKA_VALUE, &keyfileData.front(), (CK_ULONG) keyfileData.size() } + }; + + CK_OBJECT_HANDLE keyfileHandle; + + CK_RV status = Pkcs11Functions->C_CreateObject (Sessions[slotId].Handle, keyfileTemplate, array_capacity (keyfileTemplate), &keyfileHandle); + + switch (status) + { + case CKR_DATA_LEN_RANGE: + status = CKR_DEVICE_MEMORY; + break; + + case CKR_SESSION_READ_ONLY: + status = CKR_TOKEN_WRITE_PROTECTED; + break; + } + + if (status != CKR_OK) + throw Pkcs11Exception (status); + + // Some tokens report success even if the new object was truncated to fit in the available memory + vector objectData; + + GetObjectAttribute (slotId, keyfileHandle, CKA_VALUE, objectData); + finally_do_arg (vector *, &objectData, { if (!finally_arg->empty()) burn (&finally_arg->front(), finally_arg->size()); }); + + if (objectData.size() != keyfileData.size()) + { + Pkcs11Functions->C_DestroyObject (Sessions[slotId].Handle, keyfileHandle); + throw Pkcs11Exception (CKR_DEVICE_MEMORY); + } + } + + void SecurityToken::DeleteKeyfile (const SecurityTokenKeyfile &keyfile) + { + LoginUserIfRequired (keyfile.SlotId); + + CK_RV status = Pkcs11Functions->C_DestroyObject (Sessions[keyfile.SlotId].Handle, keyfile.Handle); + if (status != CKR_OK) + throw Pkcs11Exception (status); + } + + vector SecurityToken::GetAvailableKeyfiles (CK_SLOT_ID *slotIdFilter, const wstring keyfileIdFilter, char* pin) + { + bool unrecognizedTokenPresent = false; + vector keyfiles; + + foreach (const CK_SLOT_ID &slotId, GetTokenSlots()) + { + SecurityTokenInfo token; + + if (slotIdFilter && *slotIdFilter != slotId) + continue; + + try + { + LoginUserIfRequired (slotId, pin); + token = GetTokenInfo (slotId); + } + catch (UserAbort &) + { + continue; + } + catch (Pkcs11Exception &e) + { + if (e.GetErrorCode() == CKR_TOKEN_NOT_RECOGNIZED) + { + unrecognizedTokenPresent = true; + continue; + } + + throw; + } + + foreach (const CK_OBJECT_HANDLE &dataHandle, GetObjects (slotId, CKO_DATA)) + { + SecurityTokenKeyfile keyfile; + keyfile.Handle = dataHandle; + keyfile.SlotId = slotId; + keyfile.Token = token; + + vector privateAttrib; + GetObjectAttribute (slotId, dataHandle, CKA_PRIVATE, privateAttrib); + + if (privateAttrib.size() == sizeof (CK_BBOOL) && *(CK_BBOOL *) &privateAttrib.front() != CK_TRUE) + continue; + + vector label; + GetObjectAttribute (slotId, dataHandle, CKA_LABEL, label); + label.push_back (0); + + keyfile.IdUtf8 = (char *) &label.front(); + +#if defined (TC_WINDOWS) && !defined (TC_PROTOTYPE) + keyfile.Id = Utf8StringToWide ((const char *) &label.front()); +#else + keyfile.Id = StringConverter::ToWide ((const char *) &label.front()); +#endif + if (keyfile.Id.empty() || (!keyfileIdFilter.empty() && keyfileIdFilter != keyfile.Id)) + continue; + + keyfiles.push_back (keyfile); + + if (!keyfileIdFilter.empty()) + break; + } + } + + if (keyfiles.empty() && unrecognizedTokenPresent) + throw Pkcs11Exception (CKR_TOKEN_NOT_RECOGNIZED); + + return keyfiles; + } + + list SecurityToken::GetAvailableTokens () + { + bool unrecognizedTokenPresent = false; + list tokens; + + foreach (const CK_SLOT_ID &slotId, GetTokenSlots()) + { + try + { + tokens.push_back (GetTokenInfo (slotId)); + } + catch (Pkcs11Exception &e) + { + if (e.GetErrorCode() == CKR_TOKEN_NOT_RECOGNIZED) + { + unrecognizedTokenPresent = true; + continue; + } + + throw; + } + } + + if (tokens.empty() && unrecognizedTokenPresent) + throw Pkcs11Exception (CKR_TOKEN_NOT_RECOGNIZED); + + return tokens; + } + + SecurityTokenInfo SecurityToken::GetTokenInfo (CK_SLOT_ID slotId) + { + CK_TOKEN_INFO info; + CK_RV status = Pkcs11Functions->C_GetTokenInfo (slotId, &info); + if (status != CKR_OK) + throw Pkcs11Exception (status); + + SecurityTokenInfo token; + token.SlotId = slotId; + token.Flags = info.flags; + + char label[sizeof (info.label) + 1]; + memset (label, 0, sizeof (label)); + memcpy (label, info.label, sizeof (info.label)); + + token.LabelUtf8 = label; + + size_t lastSpace = token.LabelUtf8.find_last_not_of (' '); + if (lastSpace == string::npos) + token.LabelUtf8.clear(); + else + token.LabelUtf8 = token.LabelUtf8.substr (0, lastSpace + 1); + +#if defined (TC_WINDOWS) && !defined (TC_PROTOTYPE) + token.Label = Utf8StringToWide (token.LabelUtf8); +#else + token.Label = StringConverter::ToWide (token.LabelUtf8); +#endif + return token; + } + + void SecurityToken::GetKeyfileData (const SecurityTokenKeyfile &keyfile, vector &keyfileData) + { + GetKeyfileData (keyfile, nullptr, keyfileData); + } + + void SecurityToken::GetKeyfileData (const SecurityTokenKeyfile &keyfile, char* pin, vector &keyfileData) + { + LoginUserIfRequired (keyfile.SlotId, pin); + GetObjectAttribute (keyfile.SlotId, keyfile.Handle, CKA_VALUE, keyfileData); + } + + vector SecurityToken::GetObjects (CK_SLOT_ID slotId, CK_ATTRIBUTE_TYPE objectClass) + { + if (Sessions.find (slotId) == Sessions.end()) + throw ParameterIncorrect (SRC_POS); + + CK_ATTRIBUTE findTemplate; + findTemplate.type = CKA_CLASS; + findTemplate.pValue = &objectClass; + findTemplate.ulValueLen = sizeof (objectClass); + + CK_RV status = Pkcs11Functions->C_FindObjectsInit (Sessions[slotId].Handle, &findTemplate, 1); + if (status != CKR_OK) + throw Pkcs11Exception (status); + + finally_do_arg (CK_SLOT_ID, slotId, { Pkcs11Functions->C_FindObjectsFinal (Sessions[finally_arg].Handle); }); + + CK_ULONG objectCount; + vector objects; + + while (true) + { + CK_OBJECT_HANDLE object; + CK_RV status = Pkcs11Functions->C_FindObjects (Sessions[slotId].Handle, &object, 1, &objectCount); + if (status != CKR_OK) + throw Pkcs11Exception (status); + + if (objectCount != 1) + break; + + objects.push_back (object); + } + + return objects; + } + + void SecurityToken::GetObjectAttribute (CK_SLOT_ID slotId, CK_OBJECT_HANDLE tokenObject, CK_ATTRIBUTE_TYPE attributeType, vector &attributeValue) + { + attributeValue.clear(); + + if (Sessions.find (slotId) == Sessions.end()) + throw ParameterIncorrect (SRC_POS); + + CK_ATTRIBUTE attribute; + attribute.type = attributeType; + attribute.pValue = NULL_PTR; + + CK_RV status = Pkcs11Functions->C_GetAttributeValue (Sessions[slotId].Handle, tokenObject, &attribute, 1); + if (status != CKR_OK) + throw Pkcs11Exception (status); + + if (attribute.ulValueLen == 0) + return; + + attributeValue = vector (attribute.ulValueLen); + attribute.pValue = &attributeValue.front(); + + status = Pkcs11Functions->C_GetAttributeValue (Sessions[slotId].Handle, tokenObject, &attribute, 1); + if (status != CKR_OK) + throw Pkcs11Exception (status); + } + + list SecurityToken::GetTokenSlots () + { + CheckLibraryStatus(); + + list slots; + CK_ULONG slotCount; + + CK_RV status = Pkcs11Functions->C_GetSlotList (TRUE, NULL_PTR, &slotCount); + if (status != CKR_OK) + throw Pkcs11Exception (status); + + if (slotCount > 0) + { + vector slotArray (slotCount); + status = Pkcs11Functions->C_GetSlotList (TRUE, &slotArray.front(), &slotCount); + if (status != CKR_OK) + throw Pkcs11Exception (status); + + for (size_t i = 0; i < slotCount; i++) + { + CK_SLOT_INFO slotInfo; + status = Pkcs11Functions->C_GetSlotInfo (slotArray[i], &slotInfo); + + if (status != CKR_OK || !(slotInfo.flags & CKF_TOKEN_PRESENT)) + continue; + + slots.push_back (slotArray[i]); + } + } + + return slots; + } + + bool SecurityToken::IsKeyfilePathValid (const wstring &securityTokenKeyfilePath) + { + return securityTokenKeyfilePath.find (TC_SECURITY_TOKEN_KEYFILE_URL_PREFIX) == 0; + } + + void SecurityToken::Login (CK_SLOT_ID slotId, const char* pin) + { + if (Sessions.find (slotId) == Sessions.end()) + OpenSession (slotId); + else if (Sessions[slotId].UserLoggedIn) + return; + + size_t pinLen = pin? strlen (pin) : 0; + CK_RV status = Pkcs11Functions->C_Login (Sessions[slotId].Handle, CKU_USER, (CK_CHAR_PTR) pin, (CK_ULONG) pinLen); + + if (status != CKR_OK) + throw Pkcs11Exception (status); + + Sessions[slotId].UserLoggedIn = true; + } + + void SecurityToken::LoginUserIfRequired (CK_SLOT_ID slotId, char* cmdPin) + { + CheckLibraryStatus(); + CK_RV status; + + if (Sessions.find (slotId) == Sessions.end()) + { + OpenSession (slotId); + } + else + { + CK_SESSION_INFO sessionInfo; + status = Pkcs11Functions->C_GetSessionInfo (Sessions[slotId].Handle, &sessionInfo); + + if (status == CKR_OK) + { + Sessions[slotId].UserLoggedIn = (sessionInfo.state == CKS_RO_USER_FUNCTIONS || sessionInfo.state == CKS_RW_USER_FUNCTIONS); + } + else + { + try + { + CloseSession (slotId); + } + catch (...) { } + OpenSession (slotId); + } + } + + SecurityTokenInfo tokenInfo = GetTokenInfo (slotId); + + while (!Sessions[slotId].UserLoggedIn && (tokenInfo.Flags & CKF_LOGIN_REQUIRED)) + { + try + { + if (tokenInfo.Flags & CKF_PROTECTED_AUTHENTICATION_PATH) + { + status = Pkcs11Functions->C_Login (Sessions[slotId].Handle, CKU_USER, NULL_PTR, 0); + if (status != CKR_OK) + throw Pkcs11Exception (status); + } + else if (cmdPin && cmdPin [0]) + { + Login (slotId, cmdPin); + } + else + { + string pin = tokenInfo.LabelUtf8; + if (tokenInfo.Label.empty()) + { + stringstream s; + s << "#" << slotId; + pin = s.str(); + } + + finally_do_arg (string*, &pin, { burn ((void *) finally_arg->c_str(), finally_arg->size()); }); + + (*PinCallback) (pin); + Login (slotId, pin.c_str()); + } + + Sessions[slotId].UserLoggedIn = true; + } + catch (Pkcs11Exception &e) + { + CK_RV error = e.GetErrorCode(); + + if (error == CKR_USER_ALREADY_LOGGED_IN) + { + break; + } + else if (error == CKR_PIN_INCORRECT && !(tokenInfo.Flags & CKF_PROTECTED_AUTHENTICATION_PATH)) + { + if (cmdPin && cmdPin [0]) + { + // clear wrong PIN + size_t cmdPinLen = strlen (cmdPin); + burn (cmdPin, cmdPinLen); + } + (*WarningCallback) (Pkcs11Exception (CKR_PIN_INCORRECT)); + continue; + } + + throw; + } + } + } + +#ifdef TC_WINDOWS + void SecurityToken::InitLibrary (const wstring &pkcs11LibraryPath, auto_ptr pinCallback, auto_ptr warningCallback) +#else + void SecurityToken::InitLibrary (const string &pkcs11LibraryPath, auto_ptr pinCallback, auto_ptr warningCallback) +#endif + { + if (Initialized) + CloseLibrary(); + +#ifdef TC_WINDOWS Pkcs11LibraryHandle = LoadLibraryW (pkcs11LibraryPath.c_str()); - throw_sys_if (!Pkcs11LibraryHandle); -#else + throw_sys_if (!Pkcs11LibraryHandle); +#else Pkcs11LibraryHandle = dlopen (pkcs11LibraryPath.c_str(), RTLD_NOW | RTLD_LOCAL); - throw_sys_sub_if (!Pkcs11LibraryHandle, dlerror()); -#endif - - - typedef CK_RV (*C_GetFunctionList_t) (CK_FUNCTION_LIST_PTR_PTR ppFunctionList); -#ifdef TC_WINDOWS - C_GetFunctionList_t C_GetFunctionList = (C_GetFunctionList_t) GetProcAddress (Pkcs11LibraryHandle, "C_GetFunctionList"); -#else - C_GetFunctionList_t C_GetFunctionList = (C_GetFunctionList_t) dlsym (Pkcs11LibraryHandle, "C_GetFunctionList"); -#endif - - if (!C_GetFunctionList) - throw SecurityTokenLibraryNotInitialized(); - - CK_RV status = C_GetFunctionList (&Pkcs11Functions); - if (status != CKR_OK) - throw Pkcs11Exception (status); - - status = Pkcs11Functions->C_Initialize (NULL_PTR); - if (status != CKR_OK) - throw Pkcs11Exception (status); - - PinCallback = pinCallback; - WarningCallback = warningCallback; - - Initialized = true; - } - - void SecurityToken::OpenSession (CK_SLOT_ID slotId) - { - if (Sessions.find (slotId) != Sessions.end()) - return; - - CK_SESSION_HANDLE session; - - CK_FLAGS flags = CKF_SERIAL_SESSION; - - if (!(GetTokenInfo (slotId).Flags & CKF_WRITE_PROTECTED)) - flags |= CKF_RW_SESSION; - - CK_RV status = Pkcs11Functions->C_OpenSession (slotId, flags, NULL_PTR, NULL_PTR, &session); - if (status != CKR_OK) - throw Pkcs11Exception (status); - - Sessions[slotId].Handle = session; - } - - Pkcs11Exception::operator string () const - { - if (ErrorCode == CKR_OK) - return string(); - - static const struct - { - CK_RV ErrorCode; - const char *ErrorString; - } ErrorStrings[] = - { -# define TC_TOKEN_ERR(CODE) { CODE, #CODE }, - - TC_TOKEN_ERR (CKR_CANCEL) - TC_TOKEN_ERR (CKR_HOST_MEMORY) - TC_TOKEN_ERR (CKR_SLOT_ID_INVALID) - TC_TOKEN_ERR (CKR_GENERAL_ERROR) - TC_TOKEN_ERR (CKR_FUNCTION_FAILED) - TC_TOKEN_ERR (CKR_ARGUMENTS_BAD) - TC_TOKEN_ERR (CKR_NO_EVENT) - TC_TOKEN_ERR (CKR_NEED_TO_CREATE_THREADS) - TC_TOKEN_ERR (CKR_CANT_LOCK) - TC_TOKEN_ERR (CKR_ATTRIBUTE_READ_ONLY) - TC_TOKEN_ERR (CKR_ATTRIBUTE_SENSITIVE) - TC_TOKEN_ERR (CKR_ATTRIBUTE_TYPE_INVALID) - TC_TOKEN_ERR (CKR_ATTRIBUTE_VALUE_INVALID) - TC_TOKEN_ERR (CKR_DATA_INVALID) - TC_TOKEN_ERR (CKR_DATA_LEN_RANGE) - TC_TOKEN_ERR (CKR_DEVICE_ERROR) - TC_TOKEN_ERR (CKR_DEVICE_MEMORY) - TC_TOKEN_ERR (CKR_DEVICE_REMOVED) - TC_TOKEN_ERR (CKR_ENCRYPTED_DATA_INVALID) - TC_TOKEN_ERR (CKR_ENCRYPTED_DATA_LEN_RANGE) - TC_TOKEN_ERR (CKR_FUNCTION_CANCELED) - TC_TOKEN_ERR (CKR_FUNCTION_NOT_PARALLEL) - TC_TOKEN_ERR (CKR_FUNCTION_NOT_SUPPORTED) - TC_TOKEN_ERR (CKR_KEY_HANDLE_INVALID) - TC_TOKEN_ERR (CKR_KEY_SIZE_RANGE) - TC_TOKEN_ERR (CKR_KEY_TYPE_INCONSISTENT) - TC_TOKEN_ERR (CKR_KEY_NOT_NEEDED) - TC_TOKEN_ERR (CKR_KEY_CHANGED) - TC_TOKEN_ERR (CKR_KEY_NEEDED) - TC_TOKEN_ERR (CKR_KEY_INDIGESTIBLE) - TC_TOKEN_ERR (CKR_KEY_FUNCTION_NOT_PERMITTED) - TC_TOKEN_ERR (CKR_KEY_NOT_WRAPPABLE) - TC_TOKEN_ERR (CKR_KEY_UNEXTRACTABLE) - TC_TOKEN_ERR (CKR_MECHANISM_INVALID) - TC_TOKEN_ERR (CKR_MECHANISM_PARAM_INVALID) - TC_TOKEN_ERR (CKR_OBJECT_HANDLE_INVALID) - TC_TOKEN_ERR (CKR_OPERATION_ACTIVE) - TC_TOKEN_ERR (CKR_OPERATION_NOT_INITIALIZED) - TC_TOKEN_ERR (CKR_PIN_INCORRECT) - TC_TOKEN_ERR (CKR_PIN_INVALID) - TC_TOKEN_ERR (CKR_PIN_LEN_RANGE) - TC_TOKEN_ERR (CKR_PIN_EXPIRED) - TC_TOKEN_ERR (CKR_PIN_LOCKED) - TC_TOKEN_ERR (CKR_SESSION_CLOSED) - TC_TOKEN_ERR (CKR_SESSION_COUNT) - TC_TOKEN_ERR (CKR_SESSION_HANDLE_INVALID) - TC_TOKEN_ERR (CKR_SESSION_PARALLEL_NOT_SUPPORTED) - TC_TOKEN_ERR (CKR_SESSION_READ_ONLY) - TC_TOKEN_ERR (CKR_SESSION_EXISTS) - TC_TOKEN_ERR (CKR_SESSION_READ_ONLY_EXISTS) - TC_TOKEN_ERR (CKR_SESSION_READ_WRITE_SO_EXISTS) - TC_TOKEN_ERR (CKR_SIGNATURE_INVALID) - TC_TOKEN_ERR (CKR_SIGNATURE_LEN_RANGE) - TC_TOKEN_ERR (CKR_TEMPLATE_INCOMPLETE) - TC_TOKEN_ERR (CKR_TEMPLATE_INCONSISTENT) - TC_TOKEN_ERR (CKR_TOKEN_NOT_PRESENT) - TC_TOKEN_ERR (CKR_TOKEN_NOT_RECOGNIZED) - TC_TOKEN_ERR (CKR_TOKEN_WRITE_PROTECTED) - TC_TOKEN_ERR (CKR_UNWRAPPING_KEY_HANDLE_INVALID) - TC_TOKEN_ERR (CKR_UNWRAPPING_KEY_SIZE_RANGE) - TC_TOKEN_ERR (CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT) - TC_TOKEN_ERR (CKR_USER_ALREADY_LOGGED_IN) - TC_TOKEN_ERR (CKR_USER_NOT_LOGGED_IN) - TC_TOKEN_ERR (CKR_USER_PIN_NOT_INITIALIZED) - TC_TOKEN_ERR (CKR_USER_TYPE_INVALID) - TC_TOKEN_ERR (CKR_USER_ANOTHER_ALREADY_LOGGED_IN) - TC_TOKEN_ERR (CKR_USER_TOO_MANY_TYPES) - TC_TOKEN_ERR (CKR_WRAPPED_KEY_INVALID) - TC_TOKEN_ERR (CKR_WRAPPED_KEY_LEN_RANGE) - TC_TOKEN_ERR (CKR_WRAPPING_KEY_HANDLE_INVALID) - TC_TOKEN_ERR (CKR_WRAPPING_KEY_SIZE_RANGE) - TC_TOKEN_ERR (CKR_WRAPPING_KEY_TYPE_INCONSISTENT) - TC_TOKEN_ERR (CKR_RANDOM_SEED_NOT_SUPPORTED) - TC_TOKEN_ERR (CKR_RANDOM_NO_RNG) - TC_TOKEN_ERR (CKR_DOMAIN_PARAMS_INVALID) - TC_TOKEN_ERR (CKR_BUFFER_TOO_SMALL) - TC_TOKEN_ERR (CKR_SAVED_STATE_INVALID) - TC_TOKEN_ERR (CKR_INFORMATION_SENSITIVE) - TC_TOKEN_ERR (CKR_STATE_UNSAVEABLE) - TC_TOKEN_ERR (CKR_CRYPTOKI_NOT_INITIALIZED) - TC_TOKEN_ERR (CKR_CRYPTOKI_ALREADY_INITIALIZED) - TC_TOKEN_ERR (CKR_MUTEX_BAD) - TC_TOKEN_ERR (CKR_MUTEX_NOT_LOCKED) - TC_TOKEN_ERR (CKR_NEW_PIN_MODE) - TC_TOKEN_ERR (CKR_NEXT_OTP) - TC_TOKEN_ERR (CKR_FUNCTION_REJECTED) - -#undef TC_TOKEN_ERR - }; - - - for (size_t i = 0; i < array_capacity (ErrorStrings); ++i) - { - if (ErrorStrings[i].ErrorCode == ErrorCode) - return ErrorStrings[i].ErrorString; - } - - stringstream s; - s << "0x" << hex << ErrorCode; - return s.str(); - - } - -#ifdef TC_HEADER_Common_Exception - void Pkcs11Exception::Show (HWND parent) const - { - string errorString = string (*this); - - if (!errorString.empty()) - { - wstringstream subjectErrorCode; - if (SubjectErrorCodeValid) - subjectErrorCode << L": " << SubjectErrorCode; - - if (!GetDictionaryValue (errorString.c_str())) - { - if (errorString.find ("CKR_") == 0) - { - errorString = errorString.substr (4); - for (size_t i = 0; i < errorString.size(); ++i) - { - if (errorString[i] == '_') - errorString[i] = ' '; - } - } - wchar_t err[8192]; - StringCbPrintfW (err, sizeof(err),L"%s:\n\n%hs%s", GetString ("SECURITY_TOKEN_ERROR"), errorString.c_str(), subjectErrorCode.str().c_str()); - ErrorDirect (err, parent); - } - else - { - wstring err = GetString (errorString.c_str()); - - if (SubjectErrorCodeValid) - err += L"\n\nError code" + subjectErrorCode.str(); - - ErrorDirect (err.c_str(), parent); - } - } - } -#endif // TC_HEADER_Common_Exception - - auto_ptr SecurityToken::PinCallback; - auto_ptr SecurityToken::WarningCallback; - - bool SecurityToken::Initialized; - CK_FUNCTION_LIST_PTR SecurityToken::Pkcs11Functions; - map SecurityToken::Sessions; - -#ifdef TC_WINDOWS - HMODULE SecurityToken::Pkcs11LibraryHandle; -#else - void *SecurityToken::Pkcs11LibraryHandle; -#endif - -#ifdef TC_HEADER_Platform_Exception - - void Pkcs11Exception::Deserialize (shared_ptr stream) - { - Exception::Deserialize (stream); - Serializer sr (stream); - uint64 code; - sr.Deserialize ("ErrorCode", code); - sr.Deserialize ("SubjectErrorCodeValid", SubjectErrorCodeValid); - sr.Deserialize ("SubjectErrorCode", SubjectErrorCode); - ErrorCode = (CK_RV) code; - } - - void Pkcs11Exception::Serialize (shared_ptr stream) const - { - Exception::Serialize (stream); - Serializer sr (stream); - sr.Serialize ("ErrorCode", (uint64) ErrorCode); - sr.Serialize ("SubjectErrorCodeValid", SubjectErrorCodeValid); - sr.Serialize ("SubjectErrorCode", SubjectErrorCode); - } - -# define TC_EXCEPTION(TYPE) TC_SERIALIZER_FACTORY_ADD(TYPE) -# undef TC_EXCEPTION_NODECL -# define TC_EXCEPTION_NODECL(TYPE) TC_SERIALIZER_FACTORY_ADD(TYPE) - - TC_SERIALIZER_FACTORY_ADD_EXCEPTION_SET (SecurityTokenException); - -#endif -} + throw_sys_sub_if (!Pkcs11LibraryHandle, dlerror()); +#endif + + + typedef CK_RV (*C_GetFunctionList_t) (CK_FUNCTION_LIST_PTR_PTR ppFunctionList); +#ifdef TC_WINDOWS + C_GetFunctionList_t C_GetFunctionList = (C_GetFunctionList_t) GetProcAddress (Pkcs11LibraryHandle, "C_GetFunctionList"); +#else + C_GetFunctionList_t C_GetFunctionList = (C_GetFunctionList_t) dlsym (Pkcs11LibraryHandle, "C_GetFunctionList"); +#endif + + if (!C_GetFunctionList) + throw SecurityTokenLibraryNotInitialized(); + + CK_RV status = C_GetFunctionList (&Pkcs11Functions); + if (status != CKR_OK) + throw Pkcs11Exception (status); + + status = Pkcs11Functions->C_Initialize (NULL_PTR); + if (status != CKR_OK) + throw Pkcs11Exception (status); + + PinCallback = pinCallback; + WarningCallback = warningCallback; + + Initialized = true; + } + + void SecurityToken::OpenSession (CK_SLOT_ID slotId) + { + if (Sessions.find (slotId) != Sessions.end()) + return; + + CK_SESSION_HANDLE session; + + CK_FLAGS flags = CKF_SERIAL_SESSION; + + if (!(GetTokenInfo (slotId).Flags & CKF_WRITE_PROTECTED)) + flags |= CKF_RW_SESSION; + + CK_RV status = Pkcs11Functions->C_OpenSession (slotId, flags, NULL_PTR, NULL_PTR, &session); + if (status != CKR_OK) + throw Pkcs11Exception (status); + + Sessions[slotId].Handle = session; + } + + Pkcs11Exception::operator string () const + { + if (ErrorCode == CKR_OK) + return string(); + + static const struct + { + CK_RV ErrorCode; + const char *ErrorString; + } ErrorStrings[] = + { +# define TC_TOKEN_ERR(CODE) { CODE, #CODE }, + + TC_TOKEN_ERR (CKR_CANCEL) + TC_TOKEN_ERR (CKR_HOST_MEMORY) + TC_TOKEN_ERR (CKR_SLOT_ID_INVALID) + TC_TOKEN_ERR (CKR_GENERAL_ERROR) + TC_TOKEN_ERR (CKR_FUNCTION_FAILED) + TC_TOKEN_ERR (CKR_ARGUMENTS_BAD) + TC_TOKEN_ERR (CKR_NO_EVENT) + TC_TOKEN_ERR (CKR_NEED_TO_CREATE_THREADS) + TC_TOKEN_ERR (CKR_CANT_LOCK) + TC_TOKEN_ERR (CKR_ATTRIBUTE_READ_ONLY) + TC_TOKEN_ERR (CKR_ATTRIBUTE_SENSITIVE) + TC_TOKEN_ERR (CKR_ATTRIBUTE_TYPE_INVALID) + TC_TOKEN_ERR (CKR_ATTRIBUTE_VALUE_INVALID) + TC_TOKEN_ERR (CKR_DATA_INVALID) + TC_TOKEN_ERR (CKR_DATA_LEN_RANGE) + TC_TOKEN_ERR (CKR_DEVICE_ERROR) + TC_TOKEN_ERR (CKR_DEVICE_MEMORY) + TC_TOKEN_ERR (CKR_DEVICE_REMOVED) + TC_TOKEN_ERR (CKR_ENCRYPTED_DATA_INVALID) + TC_TOKEN_ERR (CKR_ENCRYPTED_DATA_LEN_RANGE) + TC_TOKEN_ERR (CKR_FUNCTION_CANCELED) + TC_TOKEN_ERR (CKR_FUNCTION_NOT_PARALLEL) + TC_TOKEN_ERR (CKR_FUNCTION_NOT_SUPPORTED) + TC_TOKEN_ERR (CKR_KEY_HANDLE_INVALID) + TC_TOKEN_ERR (CKR_KEY_SIZE_RANGE) + TC_TOKEN_ERR (CKR_KEY_TYPE_INCONSISTENT) + TC_TOKEN_ERR (CKR_KEY_NOT_NEEDED) + TC_TOKEN_ERR (CKR_KEY_CHANGED) + TC_TOKEN_ERR (CKR_KEY_NEEDED) + TC_TOKEN_ERR (CKR_KEY_INDIGESTIBLE) + TC_TOKEN_ERR (CKR_KEY_FUNCTION_NOT_PERMITTED) + TC_TOKEN_ERR (CKR_KEY_NOT_WRAPPABLE) + TC_TOKEN_ERR (CKR_KEY_UNEXTRACTABLE) + TC_TOKEN_ERR (CKR_MECHANISM_INVALID) + TC_TOKEN_ERR (CKR_MECHANISM_PARAM_INVALID) + TC_TOKEN_ERR (CKR_OBJECT_HANDLE_INVALID) + TC_TOKEN_ERR (CKR_OPERATION_ACTIVE) + TC_TOKEN_ERR (CKR_OPERATION_NOT_INITIALIZED) + TC_TOKEN_ERR (CKR_PIN_INCORRECT) + TC_TOKEN_ERR (CKR_PIN_INVALID) + TC_TOKEN_ERR (CKR_PIN_LEN_RANGE) + TC_TOKEN_ERR (CKR_PIN_EXPIRED) + TC_TOKEN_ERR (CKR_PIN_LOCKED) + TC_TOKEN_ERR (CKR_SESSION_CLOSED) + TC_TOKEN_ERR (CKR_SESSION_COUNT) + TC_TOKEN_ERR (CKR_SESSION_HANDLE_INVALID) + TC_TOKEN_ERR (CKR_SESSION_PARALLEL_NOT_SUPPORTED) + TC_TOKEN_ERR (CKR_SESSION_READ_ONLY) + TC_TOKEN_ERR (CKR_SESSION_EXISTS) + TC_TOKEN_ERR (CKR_SESSION_READ_ONLY_EXISTS) + TC_TOKEN_ERR (CKR_SESSION_READ_WRITE_SO_EXISTS) + TC_TOKEN_ERR (CKR_SIGNATURE_INVALID) + TC_TOKEN_ERR (CKR_SIGNATURE_LEN_RANGE) + TC_TOKEN_ERR (CKR_TEMPLATE_INCOMPLETE) + TC_TOKEN_ERR (CKR_TEMPLATE_INCONSISTENT) + TC_TOKEN_ERR (CKR_TOKEN_NOT_PRESENT) + TC_TOKEN_ERR (CKR_TOKEN_NOT_RECOGNIZED) + TC_TOKEN_ERR (CKR_TOKEN_WRITE_PROTECTED) + TC_TOKEN_ERR (CKR_UNWRAPPING_KEY_HANDLE_INVALID) + TC_TOKEN_ERR (CKR_UNWRAPPING_KEY_SIZE_RANGE) + TC_TOKEN_ERR (CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT) + TC_TOKEN_ERR (CKR_USER_ALREADY_LOGGED_IN) + TC_TOKEN_ERR (CKR_USER_NOT_LOGGED_IN) + TC_TOKEN_ERR (CKR_USER_PIN_NOT_INITIALIZED) + TC_TOKEN_ERR (CKR_USER_TYPE_INVALID) + TC_TOKEN_ERR (CKR_USER_ANOTHER_ALREADY_LOGGED_IN) + TC_TOKEN_ERR (CKR_USER_TOO_MANY_TYPES) + TC_TOKEN_ERR (CKR_WRAPPED_KEY_INVALID) + TC_TOKEN_ERR (CKR_WRAPPED_KEY_LEN_RANGE) + TC_TOKEN_ERR (CKR_WRAPPING_KEY_HANDLE_INVALID) + TC_TOKEN_ERR (CKR_WRAPPING_KEY_SIZE_RANGE) + TC_TOKEN_ERR (CKR_WRAPPING_KEY_TYPE_INCONSISTENT) + TC_TOKEN_ERR (CKR_RANDOM_SEED_NOT_SUPPORTED) + TC_TOKEN_ERR (CKR_RANDOM_NO_RNG) + TC_TOKEN_ERR (CKR_DOMAIN_PARAMS_INVALID) + TC_TOKEN_ERR (CKR_BUFFER_TOO_SMALL) + TC_TOKEN_ERR (CKR_SAVED_STATE_INVALID) + TC_TOKEN_ERR (CKR_INFORMATION_SENSITIVE) + TC_TOKEN_ERR (CKR_STATE_UNSAVEABLE) + TC_TOKEN_ERR (CKR_CRYPTOKI_NOT_INITIALIZED) + TC_TOKEN_ERR (CKR_CRYPTOKI_ALREADY_INITIALIZED) + TC_TOKEN_ERR (CKR_MUTEX_BAD) + TC_TOKEN_ERR (CKR_MUTEX_NOT_LOCKED) + TC_TOKEN_ERR (CKR_NEW_PIN_MODE) + TC_TOKEN_ERR (CKR_NEXT_OTP) + TC_TOKEN_ERR (CKR_FUNCTION_REJECTED) + +#undef TC_TOKEN_ERR + }; + + + for (size_t i = 0; i < array_capacity (ErrorStrings); ++i) + { + if (ErrorStrings[i].ErrorCode == ErrorCode) + return ErrorStrings[i].ErrorString; + } + + stringstream s; + s << "0x" << hex << ErrorCode; + return s.str(); + + } + +#ifdef TC_HEADER_Common_Exception + void Pkcs11Exception::Show (HWND parent) const + { + string errorString = string (*this); + + if (!errorString.empty()) + { + wstringstream subjectErrorCode; + if (SubjectErrorCodeValid) + subjectErrorCode << L": " << SubjectErrorCode; + + if (!GetDictionaryValue (errorString.c_str())) + { + if (errorString.find ("CKR_") == 0) + { + errorString = errorString.substr (4); + for (size_t i = 0; i < errorString.size(); ++i) + { + if (errorString[i] == '_') + errorString[i] = ' '; + } + } + wchar_t err[8192]; + StringCbPrintfW (err, sizeof(err),L"%s:\n\n%hs%s", GetString ("SECURITY_TOKEN_ERROR"), errorString.c_str(), subjectErrorCode.str().c_str()); + ErrorDirect (err, parent); + } + else + { + wstring err = GetString (errorString.c_str()); + + if (SubjectErrorCodeValid) + err += L"\n\nError code" + subjectErrorCode.str(); + + ErrorDirect (err.c_str(), parent); + } + } + } +#endif // TC_HEADER_Common_Exception + + auto_ptr SecurityToken::PinCallback; + auto_ptr SecurityToken::WarningCallback; + + bool SecurityToken::Initialized; + CK_FUNCTION_LIST_PTR SecurityToken::Pkcs11Functions; + map SecurityToken::Sessions; + +#ifdef TC_WINDOWS + HMODULE SecurityToken::Pkcs11LibraryHandle; +#else + void *SecurityToken::Pkcs11LibraryHandle; +#endif + +#ifdef TC_HEADER_Platform_Exception + + void Pkcs11Exception::Deserialize (shared_ptr stream) + { + Exception::Deserialize (stream); + Serializer sr (stream); + uint64 code; + sr.Deserialize ("ErrorCode", code); + sr.Deserialize ("SubjectErrorCodeValid", SubjectErrorCodeValid); + sr.Deserialize ("SubjectErrorCode", SubjectErrorCode); + ErrorCode = (CK_RV) code; + } + + void Pkcs11Exception::Serialize (shared_ptr stream) const + { + Exception::Serialize (stream); + Serializer sr (stream); + sr.Serialize ("ErrorCode", (uint64) ErrorCode); + sr.Serialize ("SubjectErrorCodeValid", SubjectErrorCodeValid); + sr.Serialize ("SubjectErrorCode", SubjectErrorCode); + } + +# define TC_EXCEPTION(TYPE) TC_SERIALIZER_FACTORY_ADD(TYPE) +# undef TC_EXCEPTION_NODECL +# define TC_EXCEPTION_NODECL(TYPE) TC_SERIALIZER_FACTORY_ADD(TYPE) + + TC_SERIALIZER_FACTORY_ADD_EXCEPTION_SET (SecurityTokenException); + +#endif +} diff --git a/src/Common/SecurityToken.h b/src/Common/SecurityToken.h index 9c6c47cf..00d543a2 100644 --- a/src/Common/SecurityToken.h +++ b/src/Common/SecurityToken.h @@ -1,226 +1,226 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Common_SecurityToken -#define TC_HEADER_Common_SecurityToken - -#include "Platform/PlatformBase.h" -#if defined (TC_WINDOWS) && !defined (TC_PROTOTYPE) -# include "Exception.h" -#else -# include "Platform/Exception.h" -#endif - -#ifndef NULL_PTR -# define NULL_PTR 0 -#endif -#define CK_PTR * -#define CK_CALLBACK_FUNCTION(RET_TYPE, NAME) RET_TYPE (* NAME) - -#ifdef TC_WINDOWS - -# include - -# define CK_DEFINE_FUNCTION(RET_TYPE, NAME) RET_TYPE __declspec(dllexport) NAME -# define CK_DECLARE_FUNCTION(RET_TYPE, NAME) RET_TYPE __declspec(dllimport) NAME -# define CK_DECLARE_FUNCTION_POINTER(RET_TYPE, NAME) RET_TYPE __declspec(dllimport) (* NAME) - -# pragma pack(push, cryptoki, 1) -# include -# pragma pack(pop, cryptoki) - -#else // !TC_WINDOWS - -# define CK_DEFINE_FUNCTION(RET_TYPE, NAME) RET_TYPE NAME -# define CK_DECLARE_FUNCTION(RET_TYPE, NAME) RET_TYPE NAME -# define CK_DECLARE_FUNCTION_POINTER(RET_TYPE, NAME) RET_TYPE (* NAME) - -# include - -#endif // !TC_WINDOWS - - -#define TC_SECURITY_TOKEN_KEYFILE_URL_PREFIX L"token://" -#define TC_SECURITY_TOKEN_KEYFILE_URL_SLOT L"slot" -#define TC_SECURITY_TOKEN_KEYFILE_URL_FILE L"file" - -namespace VeraCrypt -{ - struct SecurityTokenInfo - { - CK_SLOT_ID SlotId; - CK_FLAGS Flags; - wstring Label; - string LabelUtf8; - }; - - struct SecurityTokenKeyfilePath - { - SecurityTokenKeyfilePath () { } - SecurityTokenKeyfilePath (const wstring &path) : Path (path) { } - operator wstring () const { return Path; } - wstring Path; - }; - - struct SecurityTokenKeyfile - { - SecurityTokenKeyfile () : Handle(CK_INVALID_HANDLE), SlotId(CK_UNAVAILABLE_INFORMATION) { Token.SlotId = CK_UNAVAILABLE_INFORMATION; Token.Flags = 0; } - SecurityTokenKeyfile (const SecurityTokenKeyfilePath &path, char* pin = nullptr); - - operator SecurityTokenKeyfilePath () const; - - CK_OBJECT_HANDLE Handle; - wstring Id; - string IdUtf8; - CK_SLOT_ID SlotId; - SecurityTokenInfo Token; - }; - - struct Pkcs11Exception : public Exception - { - Pkcs11Exception (CK_RV errorCode = (CK_RV) -1) - : ErrorCode (errorCode), - SubjectErrorCodeValid (false), - SubjectErrorCode( (uint64) -1) - { - } - - Pkcs11Exception (CK_RV errorCode, uint64 subjectErrorCode) - : ErrorCode (errorCode), - SubjectErrorCodeValid (true), - SubjectErrorCode (subjectErrorCode) - { - } - -#ifdef TC_HEADER_Platform_Exception - virtual ~Pkcs11Exception () throw () { } - TC_SERIALIZABLE_EXCEPTION (Pkcs11Exception); -#else - void Show (HWND parent) const; -#endif - operator string () const; - CK_RV GetErrorCode () const { return ErrorCode; } - - protected: - CK_RV ErrorCode; - bool SubjectErrorCodeValid; - uint64 SubjectErrorCode; - }; - - -#ifdef TC_HEADER_Platform_Exception - -#define TC_EXCEPTION(NAME) TC_EXCEPTION_DECL(NAME,Exception) - -#undef TC_EXCEPTION_SET -#define TC_EXCEPTION_SET \ - TC_EXCEPTION_NODECL (Pkcs11Exception); \ - TC_EXCEPTION (InvalidSecurityTokenKeyfilePath); \ - TC_EXCEPTION (SecurityTokenLibraryNotInitialized); \ - TC_EXCEPTION (SecurityTokenKeyfileAlreadyExists); \ - TC_EXCEPTION (SecurityTokenKeyfileNotFound); - - TC_EXCEPTION_SET; - -#undef TC_EXCEPTION - -#else // !TC_HEADER_Platform_Exception - - struct SecurityTokenLibraryNotInitialized : public Exception - { - void Show (HWND parent) const { Error (SecurityTokenLibraryPath[0] == 0 ? "NO_PKCS11_MODULE_SPECIFIED" : "PKCS11_MODULE_INIT_FAILED", parent); } - }; - - struct InvalidSecurityTokenKeyfilePath : public Exception - { - void Show (HWND parent) const { Error ("INVALID_TOKEN_KEYFILE_PATH", parent); } - }; - - struct SecurityTokenKeyfileAlreadyExists : public Exception - { - void Show (HWND parent) const { Error ("TOKEN_KEYFILE_ALREADY_EXISTS", parent); } - }; - - struct SecurityTokenKeyfileNotFound : public Exception - { - void Show (HWND parent) const { Error ("TOKEN_KEYFILE_NOT_FOUND", parent); } - }; - -#endif // !TC_HEADER_Platform_Exception - - - struct Pkcs11Session - { - Pkcs11Session () : Handle (CK_UNAVAILABLE_INFORMATION), UserLoggedIn (false) { } - - CK_SESSION_HANDLE Handle; - bool UserLoggedIn; - }; - - struct GetPinFunctor - { - virtual ~GetPinFunctor () { } - virtual void operator() (string &str) = 0; - }; - - struct SendExceptionFunctor - { - virtual ~SendExceptionFunctor () { } - virtual void operator() (const Exception &e) = 0; - }; - - class SecurityToken - { - public: - static void CloseAllSessions () throw (); - static void CloseLibrary (); - static void CreateKeyfile (CK_SLOT_ID slotId, vector &keyfileData, const string &name); - static void DeleteKeyfile (const SecurityTokenKeyfile &keyfile); - static vector GetAvailableKeyfiles (CK_SLOT_ID *slotIdFilter = nullptr, const wstring keyfileIdFilter = wstring(), char* pin = nullptr); - static void GetKeyfileData (const SecurityTokenKeyfile &keyfile, vector &keyfileData); - static void GetKeyfileData (const SecurityTokenKeyfile &keyfile, char* pin, vector &keyfileData); - static list GetAvailableTokens (); - static SecurityTokenInfo GetTokenInfo (CK_SLOT_ID slotId); -#ifdef TC_WINDOWS - static void InitLibrary (const wstring &pkcs11LibraryPath, auto_ptr pinCallback, auto_ptr warningCallback); -#else - static void InitLibrary (const string &pkcs11LibraryPath, auto_ptr pinCallback, auto_ptr warningCallback); -#endif - static bool IsInitialized () { return Initialized; } - static bool IsKeyfilePathValid (const wstring &securityTokenKeyfilePath); - - static const size_t MaxPasswordLength = 128; - - protected: - static void CloseSession (CK_SLOT_ID slotId); - static vector GetObjects (CK_SLOT_ID slotId, CK_ATTRIBUTE_TYPE objectClass); - static void GetObjectAttribute (CK_SLOT_ID slotId, CK_OBJECT_HANDLE tokenObject, CK_ATTRIBUTE_TYPE attributeType, vector &attributeValue); - static list GetTokenSlots (); - static void Login (CK_SLOT_ID slotId, const char* pin); - static void LoginUserIfRequired (CK_SLOT_ID slotId, char* cmdPin = nullptr); - static void OpenSession (CK_SLOT_ID slotId); - static void CheckLibraryStatus (); - - static bool Initialized; - static auto_ptr PinCallback; - static CK_FUNCTION_LIST_PTR Pkcs11Functions; -#ifdef TC_WINDOWS - static HMODULE Pkcs11LibraryHandle; -#else - static void *Pkcs11LibraryHandle; -#endif - static map Sessions; - static auto_ptr WarningCallback; - }; -} - -#endif // TC_HEADER_Common_SecurityToken +/* + 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. +*/ + +#ifndef TC_HEADER_Common_SecurityToken +#define TC_HEADER_Common_SecurityToken + +#include "Platform/PlatformBase.h" +#if defined (TC_WINDOWS) && !defined (TC_PROTOTYPE) +# include "Exception.h" +#else +# include "Platform/Exception.h" +#endif + +#ifndef NULL_PTR +# define NULL_PTR 0 +#endif +#define CK_PTR * +#define CK_CALLBACK_FUNCTION(RET_TYPE, NAME) RET_TYPE (* NAME) + +#ifdef TC_WINDOWS + +# include + +# define CK_DEFINE_FUNCTION(RET_TYPE, NAME) RET_TYPE __declspec(dllexport) NAME +# define CK_DECLARE_FUNCTION(RET_TYPE, NAME) RET_TYPE __declspec(dllimport) NAME +# define CK_DECLARE_FUNCTION_POINTER(RET_TYPE, NAME) RET_TYPE __declspec(dllimport) (* NAME) + +# pragma pack(push, cryptoki, 1) +# include +# pragma pack(pop, cryptoki) + +#else // !TC_WINDOWS + +# define CK_DEFINE_FUNCTION(RET_TYPE, NAME) RET_TYPE NAME +# define CK_DECLARE_FUNCTION(RET_TYPE, NAME) RET_TYPE NAME +# define CK_DECLARE_FUNCTION_POINTER(RET_TYPE, NAME) RET_TYPE (* NAME) + +# include + +#endif // !TC_WINDOWS + + +#define TC_SECURITY_TOKEN_KEYFILE_URL_PREFIX L"token://" +#define TC_SECURITY_TOKEN_KEYFILE_URL_SLOT L"slot" +#define TC_SECURITY_TOKEN_KEYFILE_URL_FILE L"file" + +namespace VeraCrypt +{ + struct SecurityTokenInfo + { + CK_SLOT_ID SlotId; + CK_FLAGS Flags; + wstring Label; + string LabelUtf8; + }; + + struct SecurityTokenKeyfilePath + { + SecurityTokenKeyfilePath () { } + SecurityTokenKeyfilePath (const wstring &path) : Path (path) { } + operator wstring () const { return Path; } + wstring Path; + }; + + struct SecurityTokenKeyfile + { + SecurityTokenKeyfile () : Handle(CK_INVALID_HANDLE), SlotId(CK_UNAVAILABLE_INFORMATION) { Token.SlotId = CK_UNAVAILABLE_INFORMATION; Token.Flags = 0; } + SecurityTokenKeyfile (const SecurityTokenKeyfilePath &path, char* pin = nullptr); + + operator SecurityTokenKeyfilePath () const; + + CK_OBJECT_HANDLE Handle; + wstring Id; + string IdUtf8; + CK_SLOT_ID SlotId; + SecurityTokenInfo Token; + }; + + struct Pkcs11Exception : public Exception + { + Pkcs11Exception (CK_RV errorCode = (CK_RV) -1) + : ErrorCode (errorCode), + SubjectErrorCodeValid (false), + SubjectErrorCode( (uint64) -1) + { + } + + Pkcs11Exception (CK_RV errorCode, uint64 subjectErrorCode) + : ErrorCode (errorCode), + SubjectErrorCodeValid (true), + SubjectErrorCode (subjectErrorCode) + { + } + +#ifdef TC_HEADER_Platform_Exception + virtual ~Pkcs11Exception () throw () { } + TC_SERIALIZABLE_EXCEPTION (Pkcs11Exception); +#else + void Show (HWND parent) const; +#endif + operator string () const; + CK_RV GetErrorCode () const { return ErrorCode; } + + protected: + CK_RV ErrorCode; + bool SubjectErrorCodeValid; + uint64 SubjectErrorCode; + }; + + +#ifdef TC_HEADER_Platform_Exception + +#define TC_EXCEPTION(NAME) TC_EXCEPTION_DECL(NAME,Exception) + +#undef TC_EXCEPTION_SET +#define TC_EXCEPTION_SET \ + TC_EXCEPTION_NODECL (Pkcs11Exception); \ + TC_EXCEPTION (InvalidSecurityTokenKeyfilePath); \ + TC_EXCEPTION (SecurityTokenLibraryNotInitialized); \ + TC_EXCEPTION (SecurityTokenKeyfileAlreadyExists); \ + TC_EXCEPTION (SecurityTokenKeyfileNotFound); + + TC_EXCEPTION_SET; + +#undef TC_EXCEPTION + +#else // !TC_HEADER_Platform_Exception + + struct SecurityTokenLibraryNotInitialized : public Exception + { + void Show (HWND parent) const { Error (SecurityTokenLibraryPath[0] == 0 ? "NO_PKCS11_MODULE_SPECIFIED" : "PKCS11_MODULE_INIT_FAILED", parent); } + }; + + struct InvalidSecurityTokenKeyfilePath : public Exception + { + void Show (HWND parent) const { Error ("INVALID_TOKEN_KEYFILE_PATH", parent); } + }; + + struct SecurityTokenKeyfileAlreadyExists : public Exception + { + void Show (HWND parent) const { Error ("TOKEN_KEYFILE_ALREADY_EXISTS", parent); } + }; + + struct SecurityTokenKeyfileNotFound : public Exception + { + void Show (HWND parent) const { Error ("TOKEN_KEYFILE_NOT_FOUND", parent); } + }; + +#endif // !TC_HEADER_Platform_Exception + + + struct Pkcs11Session + { + Pkcs11Session () : Handle (CK_UNAVAILABLE_INFORMATION), UserLoggedIn (false) { } + + CK_SESSION_HANDLE Handle; + bool UserLoggedIn; + }; + + struct GetPinFunctor + { + virtual ~GetPinFunctor () { } + virtual void operator() (string &str) = 0; + }; + + struct SendExceptionFunctor + { + virtual ~SendExceptionFunctor () { } + virtual void operator() (const Exception &e) = 0; + }; + + class SecurityToken + { + public: + static void CloseAllSessions () throw (); + static void CloseLibrary (); + static void CreateKeyfile (CK_SLOT_ID slotId, vector &keyfileData, const string &name); + static void DeleteKeyfile (const SecurityTokenKeyfile &keyfile); + static vector GetAvailableKeyfiles (CK_SLOT_ID *slotIdFilter = nullptr, const wstring keyfileIdFilter = wstring(), char* pin = nullptr); + static void GetKeyfileData (const SecurityTokenKeyfile &keyfile, vector &keyfileData); + static void GetKeyfileData (const SecurityTokenKeyfile &keyfile, char* pin, vector &keyfileData); + static list GetAvailableTokens (); + static SecurityTokenInfo GetTokenInfo (CK_SLOT_ID slotId); +#ifdef TC_WINDOWS + static void InitLibrary (const wstring &pkcs11LibraryPath, auto_ptr pinCallback, auto_ptr warningCallback); +#else + static void InitLibrary (const string &pkcs11LibraryPath, auto_ptr pinCallback, auto_ptr warningCallback); +#endif + static bool IsInitialized () { return Initialized; } + static bool IsKeyfilePathValid (const wstring &securityTokenKeyfilePath); + + static const size_t MaxPasswordLength = 128; + + protected: + static void CloseSession (CK_SLOT_ID slotId); + static vector GetObjects (CK_SLOT_ID slotId, CK_ATTRIBUTE_TYPE objectClass); + static void GetObjectAttribute (CK_SLOT_ID slotId, CK_OBJECT_HANDLE tokenObject, CK_ATTRIBUTE_TYPE attributeType, vector &attributeValue); + static list GetTokenSlots (); + static void Login (CK_SLOT_ID slotId, const char* pin); + static void LoginUserIfRequired (CK_SLOT_ID slotId, char* cmdPin = nullptr); + static void OpenSession (CK_SLOT_ID slotId); + static void CheckLibraryStatus (); + + static bool Initialized; + static auto_ptr PinCallback; + static CK_FUNCTION_LIST_PTR Pkcs11Functions; +#ifdef TC_WINDOWS + static HMODULE Pkcs11LibraryHandle; +#else + static void *Pkcs11LibraryHandle; +#endif + static map Sessions; + static auto_ptr WarningCallback; + }; +} + +#endif // TC_HEADER_Common_SecurityToken diff --git a/src/Common/Sources b/src/Common/Sources index 98dbb93e..5e49829f 100644 --- a/src/Common/Sources +++ b/src/Common/Sources @@ -1,17 +1,17 @@ -TARGETNAME=Common -TARGETTYPE=DRIVER_LIBRARY - -INCLUDES = ..;../Crypto - -SOURCES = \ - Cache.c \ - Crc.c \ - Crypto.c \ - EncryptionThreadPool.c \ - Endian.c \ - GfMul.c \ - Pkcs5.c \ - Volumes.c \ - Xts.c \ - Tests.c \ - Wipe.c +TARGETNAME=Common +TARGETTYPE=DRIVER_LIBRARY + +INCLUDES = ..;../Crypto + +SOURCES = \ + Cache.c \ + Crc.c \ + Crypto.c \ + EncryptionThreadPool.c \ + Endian.c \ + GfMul.c \ + Pkcs5.c \ + Volumes.c \ + Xts.c \ + Tests.c \ + Wipe.c diff --git a/src/Common/Tcdefs.h b/src/Common/Tcdefs.h index 02744401..85cb01d0 100644 --- a/src/Common/Tcdefs.h +++ b/src/Common/Tcdefs.h @@ -1,323 +1,323 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifndef TCDEFS_H -#define TCDEFS_H - -#define TC_APP_NAME "VeraCrypt" - -// Version displayed to user -#define VERSION_STRING "1.17" - -// Version number to compare against driver -#define VERSION_NUM 0x0117 - -// Release date -#define TC_STR_RELEASE_DATE L"February 13th, 2016" -#define TC_RELEASE_DATE_YEAR 2016 -#define TC_RELEASE_DATE_MONTH 2 - -#define BYTES_PER_KB 1024LL -#define BYTES_PER_MB 1048576LL -#define BYTES_PER_GB 1073741824LL -#define BYTES_PER_TB 1099511627776LL -#define BYTES_PER_PB 1125899906842624LL - -/* GUI/driver errors */ - -#define WIDE(x) (LPWSTR)L##x - -#ifdef _MSC_VER - -typedef __int8 int8; -typedef __int16 int16; -typedef __int32 int32; -typedef unsigned __int8 byte; -typedef unsigned __int16 uint16; -typedef unsigned __int32 uint32; - -#ifdef TC_NO_COMPILER_INT64 -typedef unsigned __int32 TC_LARGEST_COMPILER_UINT; -#else -typedef unsigned __int64 TC_LARGEST_COMPILER_UINT; -typedef __int64 int64; -typedef unsigned __int64 uint64; -#define LL(x) x##ui64 -#endif - -#else // !_MSC_VER - -#include -#include - -typedef int8_t int8; -typedef int16_t int16; -typedef int32_t int32; -typedef int64_t int64; -typedef uint8_t byte; -typedef uint16_t uint16; -typedef uint32_t uint32; -typedef uint64_t uint64; - -#define LL(x) x##ULL - -#if UCHAR_MAX != 0xffU -#error UCHAR_MAX != 0xff -#endif -#define __int8 char - -#if USHRT_MAX != 0xffffU -#error USHRT_MAX != 0xffff -#endif -#define __int16 short - -#if UINT_MAX != 0xffffffffU -#error UINT_MAX != 0xffffffff -#endif -#define __int32 int - -typedef uint64 TC_LARGEST_COMPILER_UINT; - -#define BOOL int -#ifndef FALSE -#define FALSE 0 -#define TRUE 1 -#endif - -#endif // !_MSC_VER - -#define TC_INT_TYPES_DEFINED - -// Integer types required by Cryptolib -typedef unsigned __int8 uint_8t; -typedef unsigned __int16 uint_16t; -typedef unsigned __int32 uint_32t; -#ifndef TC_NO_COMPILER_INT64 -typedef uint64 uint_64t; -#endif - -typedef union -{ - struct - { - unsigned __int32 LowPart; - unsigned __int32 HighPart; - }; -#ifndef TC_NO_COMPILER_INT64 - uint64 Value; -#endif - -} UINT64_STRUCT; - -#ifndef __has_builtin // Optional of course -#define __has_builtin(x) 0 // Compatibility with non-clang compilers -#endif - -#ifdef TC_WINDOWS_BOOT - -# ifdef __cplusplus -extern "C" -# endif -void ThrowFatalException (int line); - -# define TC_THROW_FATAL_EXCEPTION ThrowFatalException (__LINE__) -#elif defined (TC_WINDOWS_DRIVER) -# define TC_THROW_FATAL_EXCEPTION KeBugCheckEx (SECURITY_SYSTEM, __LINE__, 0, 0, 'VC') -#elif (defined(__clang__) && __has_builtin(__builtin_trap)) \ - || (defined(__GNUC__ ) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3))) \ - || (__has_builtin(__builtin_trap)) -# define TC_THROW_FATAL_EXCEPTION __builtin_trap() -#else -# define TC_THROW_FATAL_EXCEPTION *(char *) 0 = 0 -#endif - -#ifdef __COVERITY__ -#undef TC_THROW_FATAL_EXCEPTION -#define TC_THROW_FATAL_EXCEPTION __coverity_panic__() -#endif - -#ifdef TC_WINDOWS_DRIVER - -#include -#include /* Standard header file for nt drivers */ -#include /* Standard I/O control codes */ - -#define TCalloc(size) ((void *) ExAllocatePoolWithTag( NonPagedPool, size, 'MMCV' )) -#define TCfree(memblock) ExFreePoolWithTag( memblock, 'MMCV' ) - -#define DEVICE_DRIVER - -#ifndef BOOL -typedef int BOOL; -#endif - -#ifndef TRUE -#define TRUE 1 -#endif - -#ifndef FALSE -#define FALSE !TRUE -#endif - -#else /* !TC_WINDOWS_DRIVER */ - -#define TCalloc malloc -#define TCfree free - -#ifdef _WIN32 - -#ifndef TC_LOCAL_WIN32_WINNT_OVERRIDE -# undef _WIN32_WINNT -# define _WIN32_WINNT 0x0501 /* Does not apply to the driver */ -#endif - -#include /* Windows header */ -#include /* The common controls */ -#include /* Process control */ -#include -#include /* For sprintf */ -#include - -#endif /* _WIN32 */ - -#endif /* !TC_WINDOWS_DRIVER */ - -#ifndef TC_TO_STRING -# define TC_TO_STRING2(n) #n -# define TC_TO_STRING(n) TC_TO_STRING2(n) -#endif - -#ifdef DEVICE_DRIVER -# if defined (DEBUG) || 0 -# if 1 // DbgPrintEx is not available on Windows 2000 -# define Dump DbgPrint -# else -# define Dump(...) DbgPrintEx (DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, __VA_ARGS__) -# endif -# define DumpMem(...) DumpMemory (__VA_ARGS__) -# else -# define Dump(...) -# define DumpMem(...) -# endif -#endif - -#if !defined (trace_msg) && !defined (TC_WINDOWS_BOOT) -# ifdef DEBUG -# ifdef DEVICE_DRIVER -# define trace_msg Dump -# elif defined (_WIN32) -# define trace_msg(...) do { char msg[2048]; StringCbPrintfA (msg, sizeof (msg), __VA_ARGS__); OutputDebugString (msg); } while (0) -# endif -# define trace_point trace_msg (__FUNCTION__ ":" TC_TO_STRING(__LINE__) "\n") -# else -# define trace_msg(...) -# define trace_point -# endif -#endif - -#ifdef DEVICE_DRIVER -# define TC_EVENT KEVENT -# define TC_WAIT_EVENT(EVENT) KeWaitForSingleObject (&EVENT, Executive, KernelMode, FALSE, NULL) -#elif defined (_WIN32) -# define TC_EVENT HANDLE -# define TC_WAIT_EVENT(EVENT) WaitForSingleObject (EVENT, INFINITE) -#endif - -#ifdef _WIN32 -#define burn(mem,size) do { volatile char *burnm = (volatile char *)(mem); size_t burnc = size; RtlSecureZeroMemory (mem, size); while (burnc--) *burnm++ = 0; } while (0) -#else -#define burn(mem,size) do { volatile char *burnm = (volatile char *)(mem); int burnc = size; while (burnc--) *burnm++ = 0; } while (0) -#endif - -// The size of the memory area to wipe is in bytes amd it must be a multiple of 8. -#ifndef TC_NO_COMPILER_INT64 -# define FAST_ERASE64(mem,size) do { volatile uint64 *burnm = (volatile uint64 *)(mem); int burnc = size >> 3; while (burnc--) *burnm++ = 0; } while (0) -#else -# define FAST_ERASE64(mem,size) do { volatile unsigned __int32 *burnm = (volatile unsigned __int32 *)(mem); int burnc = size >> 2; while (burnc--) *burnm++ = 0; } while (0) -#endif - -#ifdef TC_WINDOWS_BOOT -# ifndef max -# define max(a,b) (((a) > (b)) ? (a) : (b)) -# endif - -# ifdef __cplusplus -extern "C" -# endif -void EraseMemory (void *memory, int size); - -# undef burn -# define burn EraseMemory -#endif - -#ifdef MAX_PATH -#define TC_MAX_PATH MAX_PATH -#else -#define TC_MAX_PATH 260 /* Includes the null terminator */ -#endif - -#define TC_STR_RELEASED_BY L"Released by IDRIX on " TC_STR_RELEASE_DATE - -#define MAX_URL_LENGTH 2084 /* Internet Explorer limit. Includes the terminating null character. */ - -#define TC_HOMEPAGE "http://www.idrix.fr/" -#define TC_APPLINK "https://veracrypt.codeplex.com" -#define TC_APPLINK_SECURE "https://veracrypt.codeplex.com" - -enum -{ - /* WARNING: ADD ANY NEW CODES AT THE END (DO NOT INSERT THEM BETWEEN EXISTING). DO *NOT* DELETE ANY - EXISTING CODES! Changing these values or their meanings may cause incompatibility with other versions - (for example, if a new version of the TrueCrypt installer receives an error code from an installed - driver whose version is lower, it will report and interpret the error incorrectly). */ - - ERR_SUCCESS = 0, - ERR_OS_ERROR = 1, - ERR_OUTOFMEMORY = 2, - ERR_PASSWORD_WRONG = 3, - ERR_VOL_FORMAT_BAD = 4, - ERR_DRIVE_NOT_FOUND = 5, - ERR_FILES_OPEN = 6, - ERR_VOL_SIZE_WRONG = 7, - ERR_COMPRESSION_NOT_SUPPORTED = 8, - ERR_PASSWORD_CHANGE_VOL_TYPE = 9, - ERR_PASSWORD_CHANGE_VOL_VERSION = 10, - ERR_VOL_SEEKING = 11, - ERR_VOL_WRITING = 12, - ERR_FILES_OPEN_LOCK = 13, - ERR_VOL_READING = 14, - ERR_DRIVER_VERSION = 15, - ERR_NEW_VERSION_REQUIRED = 16, - ERR_CIPHER_INIT_FAILURE = 17, - ERR_CIPHER_INIT_WEAK_KEY = 18, - ERR_SELF_TESTS_FAILED = 19, - ERR_SECTOR_SIZE_INCOMPATIBLE = 20, - ERR_VOL_ALREADY_MOUNTED = 21, - ERR_NO_FREE_DRIVES = 22, - ERR_FILE_OPEN_FAILED = 23, - ERR_VOL_MOUNT_FAILED = 24, - DEPRECATED_ERR_INVALID_DEVICE = 25, - ERR_ACCESS_DENIED = 26, - ERR_MODE_INIT_FAILED = 27, - ERR_DONT_REPORT = 28, - ERR_ENCRYPTION_NOT_COMPLETED = 29, - ERR_PARAMETER_INCORRECT = 30, - ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG = 31, - ERR_NONSYS_INPLACE_ENC_INCOMPLETE = 32, - ERR_USER_ABORT = 33, - ERR_UNSUPPORTED_TRUECRYPT_FORMAT = 34, - ERR_RAND_INIT_FAILED = 35, - ERR_CAPI_INIT_FAILED = 36 -}; - -#endif // #ifndef TCDEFS_H +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifndef TCDEFS_H +#define TCDEFS_H + +#define TC_APP_NAME "VeraCrypt" + +// Version displayed to user +#define VERSION_STRING "1.17" + +// Version number to compare against driver +#define VERSION_NUM 0x0117 + +// Release date +#define TC_STR_RELEASE_DATE L"February 13th, 2016" +#define TC_RELEASE_DATE_YEAR 2016 +#define TC_RELEASE_DATE_MONTH 2 + +#define BYTES_PER_KB 1024LL +#define BYTES_PER_MB 1048576LL +#define BYTES_PER_GB 1073741824LL +#define BYTES_PER_TB 1099511627776LL +#define BYTES_PER_PB 1125899906842624LL + +/* GUI/driver errors */ + +#define WIDE(x) (LPWSTR)L##x + +#ifdef _MSC_VER + +typedef __int8 int8; +typedef __int16 int16; +typedef __int32 int32; +typedef unsigned __int8 byte; +typedef unsigned __int16 uint16; +typedef unsigned __int32 uint32; + +#ifdef TC_NO_COMPILER_INT64 +typedef unsigned __int32 TC_LARGEST_COMPILER_UINT; +#else +typedef unsigned __int64 TC_LARGEST_COMPILER_UINT; +typedef __int64 int64; +typedef unsigned __int64 uint64; +#define LL(x) x##ui64 +#endif + +#else // !_MSC_VER + +#include +#include + +typedef int8_t int8; +typedef int16_t int16; +typedef int32_t int32; +typedef int64_t int64; +typedef uint8_t byte; +typedef uint16_t uint16; +typedef uint32_t uint32; +typedef uint64_t uint64; + +#define LL(x) x##ULL + +#if UCHAR_MAX != 0xffU +#error UCHAR_MAX != 0xff +#endif +#define __int8 char + +#if USHRT_MAX != 0xffffU +#error USHRT_MAX != 0xffff +#endif +#define __int16 short + +#if UINT_MAX != 0xffffffffU +#error UINT_MAX != 0xffffffff +#endif +#define __int32 int + +typedef uint64 TC_LARGEST_COMPILER_UINT; + +#define BOOL int +#ifndef FALSE +#define FALSE 0 +#define TRUE 1 +#endif + +#endif // !_MSC_VER + +#define TC_INT_TYPES_DEFINED + +// Integer types required by Cryptolib +typedef unsigned __int8 uint_8t; +typedef unsigned __int16 uint_16t; +typedef unsigned __int32 uint_32t; +#ifndef TC_NO_COMPILER_INT64 +typedef uint64 uint_64t; +#endif + +typedef union +{ + struct + { + unsigned __int32 LowPart; + unsigned __int32 HighPart; + }; +#ifndef TC_NO_COMPILER_INT64 + uint64 Value; +#endif + +} UINT64_STRUCT; + +#ifndef __has_builtin // Optional of course +#define __has_builtin(x) 0 // Compatibility with non-clang compilers +#endif + +#ifdef TC_WINDOWS_BOOT + +# ifdef __cplusplus +extern "C" +# endif +void ThrowFatalException (int line); + +# define TC_THROW_FATAL_EXCEPTION ThrowFatalException (__LINE__) +#elif defined (TC_WINDOWS_DRIVER) +# define TC_THROW_FATAL_EXCEPTION KeBugCheckEx (SECURITY_SYSTEM, __LINE__, 0, 0, 'VC') +#elif (defined(__clang__) && __has_builtin(__builtin_trap)) \ + || (defined(__GNUC__ ) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3))) \ + || (__has_builtin(__builtin_trap)) +# define TC_THROW_FATAL_EXCEPTION __builtin_trap() +#else +# define TC_THROW_FATAL_EXCEPTION *(char *) 0 = 0 +#endif + +#ifdef __COVERITY__ +#undef TC_THROW_FATAL_EXCEPTION +#define TC_THROW_FATAL_EXCEPTION __coverity_panic__() +#endif + +#ifdef TC_WINDOWS_DRIVER + +#include +#include /* Standard header file for nt drivers */ +#include /* Standard I/O control codes */ + +#define TCalloc(size) ((void *) ExAllocatePoolWithTag( NonPagedPool, size, 'MMCV' )) +#define TCfree(memblock) ExFreePoolWithTag( memblock, 'MMCV' ) + +#define DEVICE_DRIVER + +#ifndef BOOL +typedef int BOOL; +#endif + +#ifndef TRUE +#define TRUE 1 +#endif + +#ifndef FALSE +#define FALSE !TRUE +#endif + +#else /* !TC_WINDOWS_DRIVER */ + +#define TCalloc malloc +#define TCfree free + +#ifdef _WIN32 + +#ifndef TC_LOCAL_WIN32_WINNT_OVERRIDE +# undef _WIN32_WINNT +# define _WIN32_WINNT 0x0501 /* Does not apply to the driver */ +#endif + +#include /* Windows header */ +#include /* The common controls */ +#include /* Process control */ +#include +#include /* For sprintf */ +#include + +#endif /* _WIN32 */ + +#endif /* !TC_WINDOWS_DRIVER */ + +#ifndef TC_TO_STRING +# define TC_TO_STRING2(n) #n +# define TC_TO_STRING(n) TC_TO_STRING2(n) +#endif + +#ifdef DEVICE_DRIVER +# if defined (DEBUG) || 0 +# if 1 // DbgPrintEx is not available on Windows 2000 +# define Dump DbgPrint +# else +# define Dump(...) DbgPrintEx (DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, __VA_ARGS__) +# endif +# define DumpMem(...) DumpMemory (__VA_ARGS__) +# else +# define Dump(...) +# define DumpMem(...) +# endif +#endif + +#if !defined (trace_msg) && !defined (TC_WINDOWS_BOOT) +# ifdef DEBUG +# ifdef DEVICE_DRIVER +# define trace_msg Dump +# elif defined (_WIN32) +# define trace_msg(...) do { char msg[2048]; StringCbPrintfA (msg, sizeof (msg), __VA_ARGS__); OutputDebugString (msg); } while (0) +# endif +# define trace_point trace_msg (__FUNCTION__ ":" TC_TO_STRING(__LINE__) "\n") +# else +# define trace_msg(...) +# define trace_point +# endif +#endif + +#ifdef DEVICE_DRIVER +# define TC_EVENT KEVENT +# define TC_WAIT_EVENT(EVENT) KeWaitForSingleObject (&EVENT, Executive, KernelMode, FALSE, NULL) +#elif defined (_WIN32) +# define TC_EVENT HANDLE +# define TC_WAIT_EVENT(EVENT) WaitForSingleObject (EVENT, INFINITE) +#endif + +#ifdef _WIN32 +#define burn(mem,size) do { volatile char *burnm = (volatile char *)(mem); size_t burnc = size; RtlSecureZeroMemory (mem, size); while (burnc--) *burnm++ = 0; } while (0) +#else +#define burn(mem,size) do { volatile char *burnm = (volatile char *)(mem); int burnc = size; while (burnc--) *burnm++ = 0; } while (0) +#endif + +// The size of the memory area to wipe is in bytes amd it must be a multiple of 8. +#ifndef TC_NO_COMPILER_INT64 +# define FAST_ERASE64(mem,size) do { volatile uint64 *burnm = (volatile uint64 *)(mem); int burnc = size >> 3; while (burnc--) *burnm++ = 0; } while (0) +#else +# define FAST_ERASE64(mem,size) do { volatile unsigned __int32 *burnm = (volatile unsigned __int32 *)(mem); int burnc = size >> 2; while (burnc--) *burnm++ = 0; } while (0) +#endif + +#ifdef TC_WINDOWS_BOOT +# ifndef max +# define max(a,b) (((a) > (b)) ? (a) : (b)) +# endif + +# ifdef __cplusplus +extern "C" +# endif +void EraseMemory (void *memory, int size); + +# undef burn +# define burn EraseMemory +#endif + +#ifdef MAX_PATH +#define TC_MAX_PATH MAX_PATH +#else +#define TC_MAX_PATH 260 /* Includes the null terminator */ +#endif + +#define TC_STR_RELEASED_BY L"Released by IDRIX on " TC_STR_RELEASE_DATE + +#define MAX_URL_LENGTH 2084 /* Internet Explorer limit. Includes the terminating null character. */ + +#define TC_HOMEPAGE "http://www.idrix.fr/" +#define TC_APPLINK "https://veracrypt.codeplex.com" +#define TC_APPLINK_SECURE "https://veracrypt.codeplex.com" + +enum +{ + /* WARNING: ADD ANY NEW CODES AT THE END (DO NOT INSERT THEM BETWEEN EXISTING). DO *NOT* DELETE ANY + EXISTING CODES! Changing these values or their meanings may cause incompatibility with other versions + (for example, if a new version of the TrueCrypt installer receives an error code from an installed + driver whose version is lower, it will report and interpret the error incorrectly). */ + + ERR_SUCCESS = 0, + ERR_OS_ERROR = 1, + ERR_OUTOFMEMORY = 2, + ERR_PASSWORD_WRONG = 3, + ERR_VOL_FORMAT_BAD = 4, + ERR_DRIVE_NOT_FOUND = 5, + ERR_FILES_OPEN = 6, + ERR_VOL_SIZE_WRONG = 7, + ERR_COMPRESSION_NOT_SUPPORTED = 8, + ERR_PASSWORD_CHANGE_VOL_TYPE = 9, + ERR_PASSWORD_CHANGE_VOL_VERSION = 10, + ERR_VOL_SEEKING = 11, + ERR_VOL_WRITING = 12, + ERR_FILES_OPEN_LOCK = 13, + ERR_VOL_READING = 14, + ERR_DRIVER_VERSION = 15, + ERR_NEW_VERSION_REQUIRED = 16, + ERR_CIPHER_INIT_FAILURE = 17, + ERR_CIPHER_INIT_WEAK_KEY = 18, + ERR_SELF_TESTS_FAILED = 19, + ERR_SECTOR_SIZE_INCOMPATIBLE = 20, + ERR_VOL_ALREADY_MOUNTED = 21, + ERR_NO_FREE_DRIVES = 22, + ERR_FILE_OPEN_FAILED = 23, + ERR_VOL_MOUNT_FAILED = 24, + DEPRECATED_ERR_INVALID_DEVICE = 25, + ERR_ACCESS_DENIED = 26, + ERR_MODE_INIT_FAILED = 27, + ERR_DONT_REPORT = 28, + ERR_ENCRYPTION_NOT_COMPLETED = 29, + ERR_PARAMETER_INCORRECT = 30, + ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG = 31, + ERR_NONSYS_INPLACE_ENC_INCOMPLETE = 32, + ERR_USER_ABORT = 33, + ERR_UNSUPPORTED_TRUECRYPT_FORMAT = 34, + ERR_RAND_INIT_FAILED = 35, + ERR_CAPI_INIT_FAILED = 36 +}; + +#endif // #ifndef TCDEFS_H diff --git a/src/Common/Tests.c b/src/Common/Tests.c index b1b67dfc..8dc72d2c 100644 --- a/src/Common/Tests.c +++ b/src/Common/Tests.c @@ -1,1155 +1,1155 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" -#include "Crc.h" -#include "Crypto.h" -#include "Common/Endian.h" -#include "Tests.h" -#include "Xts.h" -#include -#include "Pkcs5.h" - -typedef struct { - unsigned __int8 key1[32]; - unsigned __int8 key2[32]; - unsigned __int8 dataUnitNo[8]; - unsigned int blockNo; - unsigned __int8 plaintext[ENCRYPTION_DATA_UNIT_SIZE]; - unsigned __int8 ciphertext[ENCRYPTION_DATA_UNIT_SIZE]; -} XTS_TEST; - -#define XTS_TEST_COUNT 5 - -XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { -/* XTS-AES-256 */ -{ - // IEEE 1619 - Vector 10 - - { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, - { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, - { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff }, - 0, - { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff - }, - { - 0x1c, 0x3b, 0x3a, 0x10, 0x2f, 0x77, 0x03, 0x86, 0xe4, 0x83, 0x6c, 0x99, 0xe3, 0x70, 0xcf, 0x9b, 0xea, 0x00, 0x80, 0x3f, 0x5e, 0x48, 0x23, 0x57, 0xa4, 0xae, 0x12, 0xd4, 0x14, 0xa3, 0xe6, 0x3b, - 0x5d, 0x31, 0xe2, 0x76, 0xf8, 0xfe, 0x4a, 0x8d, 0x66, 0xb3, 0x17, 0xf9, 0xac, 0x68, 0x3f, 0x44, 0x68, 0x0a, 0x86, 0xac, 0x35, 0xad, 0xfc, 0x33, 0x45, 0xbe, 0xfe, 0xcb, 0x4b, 0xb1, 0x88, 0xfd, - 0x57, 0x76, 0x92, 0x6c, 0x49, 0xa3, 0x09, 0x5e, 0xb1, 0x08, 0xfd, 0x10, 0x98, 0xba, 0xec, 0x70, 0xaa, 0xa6, 0x69, 0x99, 0xa7, 0x2a, 0x82, 0xf2, 0x7d, 0x84, 0x8b, 0x21, 0xd4, 0xa7, 0x41, 0xb0, - 0xc5, 0xcd, 0x4d, 0x5f, 0xff, 0x9d, 0xac, 0x89, 0xae, 0xba, 0x12, 0x29, 0x61, 0xd0, 0x3a, 0x75, 0x71, 0x23, 0xe9, 0x87, 0x0f, 0x8a, 0xcf, 0x10, 0x00, 0x02, 0x08, 0x87, 0x89, 0x14, 0x29, 0xca, - 0x2a, 0x3e, 0x7a, 0x7d, 0x7d, 0xf7, 0xb1, 0x03, 0x55, 0x16, 0x5c, 0x8b, 0x9a, 0x6d, 0x0a, 0x7d, 0xe8, 0xb0, 0x62, 0xc4, 0x50, 0x0d, 0xc4, 0xcd, 0x12, 0x0c, 0x0f, 0x74, 0x18, 0xda, 0xe3, 0xd0, - 0xb5, 0x78, 0x1c, 0x34, 0x80, 0x3f, 0xa7, 0x54, 0x21, 0xc7, 0x90, 0xdf, 0xe1, 0xde, 0x18, 0x34, 0xf2, 0x80, 0xd7, 0x66, 0x7b, 0x32, 0x7f, 0x6c, 0x8c, 0xd7, 0x55, 0x7e, 0x12, 0xac, 0x3a, 0x0f, - 0x93, 0xec, 0x05, 0xc5, 0x2e, 0x04, 0x93, 0xef, 0x31, 0xa1, 0x2d, 0x3d, 0x92, 0x60, 0xf7, 0x9a, 0x28, 0x9d, 0x6a, 0x37, 0x9b, 0xc7, 0x0c, 0x50, 0x84, 0x14, 0x73, 0xd1, 0xa8, 0xcc, 0x81, 0xec, - 0x58, 0x3e, 0x96, 0x45, 0xe0, 0x7b, 0x8d, 0x96, 0x70, 0x65, 0x5b, 0xa5, 0xbb, 0xcf, 0xec, 0xc6, 0xdc, 0x39, 0x66, 0x38, 0x0a, 0xd8, 0xfe, 0xcb, 0x17, 0xb6, 0xba, 0x02, 0x46, 0x9a, 0x02, 0x0a, - 0x84, 0xe1, 0x8e, 0x8f, 0x84, 0x25, 0x20, 0x70, 0xc1, 0x3e, 0x9f, 0x1f, 0x28, 0x9b, 0xe5, 0x4f, 0xbc, 0x48, 0x14, 0x57, 0x77, 0x8f, 0x61, 0x60, 0x15, 0xe1, 0x32, 0x7a, 0x02, 0xb1, 0x40, 0xf1, - 0x50, 0x5e, 0xb3, 0x09, 0x32, 0x6d, 0x68, 0x37, 0x8f, 0x83, 0x74, 0x59, 0x5c, 0x84, 0x9d, 0x84, 0xf4, 0xc3, 0x33, 0xec, 0x44, 0x23, 0x88, 0x51, 0x43, 0xcb, 0x47, 0xbd, 0x71, 0xc5, 0xed, 0xae, - 0x9b, 0xe6, 0x9a, 0x2f, 0xfe, 0xce, 0xb1, 0xbe, 0xc9, 0xde, 0x24, 0x4f, 0xbe, 0x15, 0x99, 0x2b, 0x11, 0xb7, 0x7c, 0x04, 0x0f, 0x12, 0xbd, 0x8f, 0x6a, 0x97, 0x5a, 0x44, 0xa0, 0xf9, 0x0c, 0x29, - 0xa9, 0xab, 0xc3, 0xd4, 0xd8, 0x93, 0x92, 0x72, 0x84, 0xc5, 0x87, 0x54, 0xcc, 0xe2, 0x94, 0x52, 0x9f, 0x86, 0x14, 0xdc, 0xd2, 0xab, 0xa9, 0x91, 0x92, 0x5f, 0xed, 0xc4, 0xae, 0x74, 0xff, 0xac, - 0x6e, 0x33, 0x3b, 0x93, 0xeb, 0x4a, 0xff, 0x04, 0x79, 0xda, 0x9a, 0x41, 0x0e, 0x44, 0x50, 0xe0, 0xdd, 0x7a, 0xe4, 0xc6, 0xe2, 0x91, 0x09, 0x00, 0x57, 0x5d, 0xa4, 0x01, 0xfc, 0x07, 0x05, 0x9f, - 0x64, 0x5e, 0x8b, 0x7e, 0x9b, 0xfd, 0xef, 0x33, 0x94, 0x30, 0x54, 0xff, 0x84, 0x01, 0x14, 0x93, 0xc2, 0x7b, 0x34, 0x29, 0xea, 0xed, 0xb4, 0xed, 0x53, 0x76, 0x44, 0x1a, 0x77, 0xed, 0x43, 0x85, - 0x1a, 0xd7, 0x7f, 0x16, 0xf5, 0x41, 0xdf, 0xd2, 0x69, 0xd5, 0x0d, 0x6a, 0x5f, 0x14, 0xfb, 0x0a, 0xab, 0x1c, 0xbb, 0x4c, 0x15, 0x50, 0xbe, 0x97, 0xf7, 0xab, 0x40, 0x66, 0x19, 0x3c, 0x4c, 0xaa, - 0x77, 0x3d, 0xad, 0x38, 0x01, 0x4b, 0xd2, 0x09, 0x2f, 0xa7, 0x55, 0xc8, 0x24, 0xbb, 0x5e, 0x54, 0xc4, 0xf3, 0x6f, 0xfd, 0xa9, 0xfc, 0xea, 0x70, 0xb9, 0xc6, 0xe6, 0x93, 0xe1, 0x48, 0xc1, 0x51 - } -}, -{ - // IEEE 1619 - Vector 11 - - { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, - { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, - { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff }, - 0, - { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff - }, - { - 0x77, 0xa3, 0x12, 0x51, 0x61, 0x8a, 0x15, 0xe6, 0xb9, 0x2d, 0x1d, 0x66, 0xdf, 0xfe, 0x7b, 0x50, 0xb5, 0x0b, 0xad, 0x55, 0x23, 0x05, 0xba, 0x02, 0x17, 0xa6, 0x10, 0x68, 0x8e, 0xff, 0x7e, 0x11, - 0xe1, 0xd0, 0x22, 0x54, 0x38, 0xe0, 0x93, 0x24, 0x2d, 0x6d, 0xb2, 0x74, 0xfd, 0xe8, 0x01, 0xd4, 0xca, 0xe0, 0x6f, 0x20, 0x92, 0xc7, 0x28, 0xb2, 0x47, 0x85, 0x59, 0xdf, 0x58, 0xe8, 0x37, 0xc2, - 0x46, 0x9e, 0xe4, 0xa4, 0xfa, 0x79, 0x4e, 0x4b, 0xbc, 0x7f, 0x39, 0xbc, 0x02, 0x6e, 0x3c, 0xb7, 0x2c, 0x33, 0xb0, 0x88, 0x8f, 0x25, 0xb4, 0xac, 0xf5, 0x6a, 0x2a, 0x98, 0x04, 0xf1, 0xce, 0x6d, - 0x3d, 0x6e, 0x1d, 0xc6, 0xca, 0x18, 0x1d, 0x4b, 0x54, 0x61, 0x79, 0xd5, 0x55, 0x44, 0xaa, 0x77, 0x60, 0xc4, 0x0d, 0x06, 0x74, 0x15, 0x39, 0xc7, 0xe3, 0xcd, 0x9d, 0x2f, 0x66, 0x50, 0xb2, 0x01, - 0x3f, 0xd0, 0xee, 0xb8, 0xc2, 0xb8, 0xe3, 0xd8, 0xd2, 0x40, 0xcc, 0xae, 0x2d, 0x4c, 0x98, 0x32, 0x0a, 0x74, 0x42, 0xe1, 0xc8, 0xd7, 0x5a, 0x42, 0xd6, 0xe6, 0xcf, 0xa4, 0xc2, 0xec, 0xa1, 0x79, - 0x8d, 0x15, 0x8c, 0x7a, 0xec, 0xdf, 0x82, 0x49, 0x0f, 0x24, 0xbb, 0x9b, 0x38, 0xe1, 0x08, 0xbc, 0xda, 0x12, 0xc3, 0xfa, 0xf9, 0xa2, 0x11, 0x41, 0xc3, 0x61, 0x3b, 0x58, 0x36, 0x7f, 0x92, 0x2a, - 0xaa, 0x26, 0xcd, 0x22, 0xf2, 0x3d, 0x70, 0x8d, 0xae, 0x69, 0x9a, 0xd7, 0xcb, 0x40, 0xa8, 0xad, 0x0b, 0x6e, 0x27, 0x84, 0x97, 0x3d, 0xcb, 0x60, 0x56, 0x84, 0xc0, 0x8b, 0x8d, 0x69, 0x98, 0xc6, - 0x9a, 0xac, 0x04, 0x99, 0x21, 0x87, 0x1e, 0xbb, 0x65, 0x30, 0x1a, 0x46, 0x19, 0xca, 0x80, 0xec, 0xb4, 0x85, 0xa3, 0x1d, 0x74, 0x42, 0x23, 0xce, 0x8d, 0xdc, 0x23, 0x94, 0x82, 0x8d, 0x6a, 0x80, - 0x47, 0x0c, 0x09, 0x2f, 0x5b, 0xa4, 0x13, 0xc3, 0x37, 0x8f, 0xa6, 0x05, 0x42, 0x55, 0xc6, 0xf9, 0xdf, 0x44, 0x95, 0x86, 0x2b, 0xbb, 0x32, 0x87, 0x68, 0x1f, 0x93, 0x1b, 0x68, 0x7c, 0x88, 0x8a, - 0xbf, 0x84, 0x4d, 0xfc, 0x8f, 0xc2, 0x83, 0x31, 0xe5, 0x79, 0x92, 0x8c, 0xd1, 0x2b, 0xd2, 0x39, 0x0a, 0xe1, 0x23, 0xcf, 0x03, 0x81, 0x8d, 0x14, 0xde, 0xdd, 0xe5, 0xc0, 0xc2, 0x4c, 0x8a, 0xb0, - 0x18, 0xbf, 0xca, 0x75, 0xca, 0x09, 0x6f, 0x2d, 0x53, 0x1f, 0x3d, 0x16, 0x19, 0xe7, 0x85, 0xf1, 0xad, 0xa4, 0x37, 0xca, 0xb9, 0x2e, 0x98, 0x05, 0x58, 0xb3, 0xdc, 0xe1, 0x47, 0x4a, 0xfb, 0x75, - 0xbf, 0xed, 0xbf, 0x8f, 0xf5, 0x4c, 0xb2, 0x61, 0x8e, 0x02, 0x44, 0xc9, 0xac, 0x0d, 0x3c, 0x66, 0xfb, 0x51, 0x59, 0x8c, 0xd2, 0xdb, 0x11, 0xf9, 0xbe, 0x39, 0x79, 0x1a, 0xbe, 0x44, 0x7c, 0x63, - 0x09, 0x4f, 0x7c, 0x45, 0x3b, 0x7f, 0xf8, 0x7c, 0xb5, 0xbb, 0x36, 0xb7, 0xc7, 0x9e, 0xfb, 0x08, 0x72, 0xd1, 0x70, 0x58, 0xb8, 0x3b, 0x15, 0xab, 0x08, 0x66, 0xad, 0x8a, 0x58, 0x65, 0x6c, 0x5a, - 0x7e, 0x20, 0xdb, 0xdf, 0x30, 0x8b, 0x24, 0x61, 0xd9, 0x7c, 0x0e, 0xc0, 0x02, 0x4a, 0x27, 0x15, 0x05, 0x52, 0x49, 0xcf, 0x3b, 0x47, 0x8d, 0xdd, 0x47, 0x40, 0xde, 0x65, 0x4f, 0x75, 0xca, 0x68, - 0x6e, 0x0d, 0x73, 0x45, 0xc6, 0x9e, 0xd5, 0x0c, 0xdc, 0x2a, 0x8b, 0x33, 0x2b, 0x1f, 0x88, 0x24, 0x10, 0x8a, 0xc9, 0x37, 0xeb, 0x05, 0x05, 0x85, 0x60, 0x8e, 0xe7, 0x34, 0x09, 0x7f, 0xc0, 0x90, - 0x54, 0xfb, 0xff, 0x89, 0xee, 0xae, 0xea, 0x79, 0x1f, 0x4a, 0x7a, 0xb1, 0xf9, 0x86, 0x82, 0x94, 0xa4, 0xf9, 0xe2, 0x7b, 0x42, 0xaf, 0x81, 0x00, 0xcb, 0x9d, 0x59, 0xce, 0xf9, 0x64, 0x58, 0x03 - } -}, -{ - // IEEE 1619 - Vector 12 - - { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, - { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, - { 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff }, - 0, - { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff - }, - { - 0xe3, 0x87, 0xaa, 0xa5, 0x8b, 0xa4, 0x83, 0xaf, 0xa7, 0xe8, 0xeb, 0x46, 0x97, 0x78, 0x31, 0x7e, 0xcf, 0x4c, 0xf5, 0x73, 0xaa, 0x9d, 0x4e, 0xac, 0x23, 0xf2, 0xcd, 0xf9, 0x14, 0xe4, 0xe2, 0x00, - 0xa8, 0xb4, 0x90, 0xe4, 0x2e, 0xe6, 0x46, 0x80, 0x2d, 0xc6, 0xee, 0x2b, 0x47, 0x1b, 0x27, 0x81, 0x95, 0xd6, 0x09, 0x18, 0xec, 0xec, 0xb4, 0x4b, 0xf7, 0x99, 0x66, 0xf8, 0x3f, 0xab, 0xa0, 0x49, - 0x92, 0x98, 0xeb, 0xc6, 0x99, 0xc0, 0xc8, 0x63, 0x47, 0x15, 0xa3, 0x20, 0xbb, 0x4f, 0x07, 0x5d, 0x62, 0x2e, 0x74, 0xc8, 0xc9, 0x32, 0x00, 0x4f, 0x25, 0xb4, 0x1e, 0x36, 0x10, 0x25, 0xb5, 0xa8, - 0x78, 0x15, 0x39, 0x1f, 0x61, 0x08, 0xfc, 0x4a, 0xfa, 0x6a, 0x05, 0xd9, 0x30, 0x3c, 0x6b, 0xa6, 0x8a, 0x12, 0x8a, 0x55, 0x70, 0x5d, 0x41, 0x59, 0x85, 0x83, 0x2f, 0xde, 0xaa, 0xe6, 0xc8, 0xe1, - 0x91, 0x10, 0xe8, 0x4d, 0x1b, 0x1f, 0x19, 0x9a, 0x26, 0x92, 0x11, 0x9e, 0xdc, 0x96, 0x13, 0x26, 0x58, 0xf0, 0x9d, 0xa7, 0xc6, 0x23, 0xef, 0xce, 0xc7, 0x12, 0x53, 0x7a, 0x3d, 0x94, 0xc0, 0xbf, - 0x5d, 0x7e, 0x35, 0x2e, 0xc9, 0x4a, 0xe5, 0x79, 0x7f, 0xdb, 0x37, 0x7d, 0xc1, 0x55, 0x11, 0x50, 0x72, 0x1a, 0xdf, 0x15, 0xbd, 0x26, 0xa8, 0xef, 0xc2, 0xfc, 0xaa, 0xd5, 0x68, 0x81, 0xfa, 0x9e, - 0x62, 0x46, 0x2c, 0x28, 0xf3, 0x0a, 0xe1, 0xce, 0xac, 0xa9, 0x3c, 0x34, 0x5c, 0xf2, 0x43, 0xb7, 0x3f, 0x54, 0x2e, 0x20, 0x74, 0xa7, 0x05, 0xbd, 0x26, 0x43, 0xbb, 0x9f, 0x7c, 0xc7, 0x9b, 0xb6, - 0xe7, 0x09, 0x1e, 0xa6, 0xe2, 0x32, 0xdf, 0x0f, 0x9a, 0xd0, 0xd6, 0xcf, 0x50, 0x23, 0x27, 0x87, 0x6d, 0x82, 0x20, 0x7a, 0xbf, 0x21, 0x15, 0xcd, 0xac, 0xf6, 0xd5, 0xa4, 0x8f, 0x6c, 0x18, 0x79, - 0xa6, 0x5b, 0x11, 0x5f, 0x0f, 0x8b, 0x3c, 0xb3, 0xc5, 0x9d, 0x15, 0xdd, 0x8c, 0x76, 0x9b, 0xc0, 0x14, 0x79, 0x5a, 0x18, 0x37, 0xf3, 0x90, 0x1b, 0x58, 0x45, 0xeb, 0x49, 0x1a, 0xdf, 0xef, 0xe0, - 0x97, 0xb1, 0xfa, 0x30, 0xa1, 0x2f, 0xc1, 0xf6, 0x5b, 0xa2, 0x29, 0x05, 0x03, 0x15, 0x39, 0x97, 0x1a, 0x10, 0xf2, 0xf3, 0x6c, 0x32, 0x1b, 0xb5, 0x13, 0x31, 0xcd, 0xef, 0xb3, 0x9e, 0x39, 0x64, - 0xc7, 0xef, 0x07, 0x99, 0x94, 0xf5, 0xb6, 0x9b, 0x2e, 0xdd, 0x83, 0xa7, 0x1e, 0xf5, 0x49, 0x97, 0x1e, 0xe9, 0x3f, 0x44, 0xea, 0xc3, 0x93, 0x8f, 0xcd, 0xd6, 0x1d, 0x01, 0xfa, 0x71, 0x79, 0x9d, - 0xa3, 0xa8, 0x09, 0x1c, 0x4c, 0x48, 0xaa, 0x9e, 0xd2, 0x63, 0xff, 0x07, 0x49, 0xdf, 0x95, 0xd4, 0x4f, 0xef, 0x6a, 0x0b, 0xb5, 0x78, 0xec, 0x69, 0x45, 0x6a, 0xa5, 0x40, 0x8a, 0xe3, 0x2c, 0x7a, - 0xf0, 0x8a, 0xd7, 0xba, 0x89, 0x21, 0x28, 0x7e, 0x3b, 0xbe, 0xe3, 0x1b, 0x76, 0x7b, 0xe0, 0x6a, 0x0e, 0x70, 0x5c, 0x86, 0x4a, 0x76, 0x91, 0x37, 0xdf, 0x28, 0x29, 0x22, 0x83, 0xea, 0x81, 0xa2, - 0x48, 0x02, 0x41, 0xb4, 0x4d, 0x99, 0x21, 0xcd, 0xbe, 0xc1, 0xbc, 0x28, 0xdc, 0x1f, 0xda, 0x11, 0x4b, 0xd8, 0xe5, 0x21, 0x7a, 0xc9, 0xd8, 0xeb, 0xaf, 0xa7, 0x20, 0xe9, 0xda, 0x4f, 0x9a, 0xce, - 0x23, 0x1c, 0xc9, 0x49, 0xe5, 0xb9, 0x6f, 0xe7, 0x6f, 0xfc, 0x21, 0x06, 0x3f, 0xdd, 0xc8, 0x3a, 0x6b, 0x86, 0x79, 0xc0, 0x0d, 0x35, 0xe0, 0x95, 0x76, 0xa8, 0x75, 0x30, 0x5b, 0xed, 0x5f, 0x36, - 0xed, 0x24, 0x2c, 0x89, 0x00, 0xdd, 0x1f, 0xa9, 0x65, 0xbc, 0x95, 0x0d, 0xfc, 0xe0, 0x9b, 0x13, 0x22, 0x63, 0xa1, 0xee, 0xf5, 0x2d, 0xd6, 0x88, 0x8c, 0x30, 0x9f, 0x5a, 0x7d, 0x71, 0x28, 0x26 - } -}, -{ - // IEEE 1619 - Vector 13 - - { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, - { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, - { 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff }, - 0, - { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff - }, - { - 0xbf, 0x53, 0xd2, 0xda, 0xde, 0x78, 0xe8, 0x22, 0xa4, 0xd9, 0x49, 0xa9, 0xbc, 0x67, 0x66, 0xb0, 0x1b, 0x06, 0xa8, 0xef, 0x70, 0xd2, 0x67, 0x48, 0xc6, 0xa7, 0xfc, 0x36, 0xd8, 0x0a, 0xe4, 0xc5, - 0x52, 0x0f, 0x7c, 0x4a, 0xb0, 0xac, 0x85, 0x44, 0x42, 0x4f, 0xa4, 0x05, 0x16, 0x2f, 0xef, 0x5a, 0x6b, 0x7f, 0x22, 0x94, 0x98, 0x06, 0x36, 0x18, 0xd3, 0x9f, 0x00, 0x03, 0xcb, 0x5f, 0xb8, 0xd1, - 0xc8, 0x6b, 0x64, 0x34, 0x97, 0xda, 0x1f, 0xf9, 0x45, 0xc8, 0xd3, 0xbe, 0xde, 0xca, 0x4f, 0x47, 0x97, 0x02, 0xa7, 0xa7, 0x35, 0xf0, 0x43, 0xdd, 0xb1, 0xd6, 0xaa, 0xad, 0xe3, 0xc4, 0xa0, 0xac, - 0x7c, 0xa7, 0xf3, 0xfa, 0x52, 0x79, 0xbe, 0xf5, 0x6f, 0x82, 0xcd, 0x7a, 0x2f, 0x38, 0x67, 0x2e, 0x82, 0x48, 0x14, 0xe1, 0x07, 0x00, 0x30, 0x0a, 0x05, 0x5e, 0x16, 0x30, 0xb8, 0xf1, 0xcb, 0x0e, - 0x91, 0x9f, 0x5e, 0x94, 0x20, 0x10, 0xa4, 0x16, 0xe2, 0xbf, 0x48, 0xcb, 0x46, 0x99, 0x3d, 0x3c, 0xb6, 0xa5, 0x1c, 0x19, 0xba, 0xcf, 0x86, 0x47, 0x85, 0xa0, 0x0b, 0xc2, 0xec, 0xff, 0x15, 0xd3, - 0x50, 0x87, 0x5b, 0x24, 0x6e, 0xd5, 0x3e, 0x68, 0xbe, 0x6f, 0x55, 0xbd, 0x7e, 0x05, 0xcf, 0xc2, 0xb2, 0xed, 0x64, 0x32, 0x19, 0x8a, 0x64, 0x44, 0xb6, 0xd8, 0xc2, 0x47, 0xfa, 0xb9, 0x41, 0xf5, - 0x69, 0x76, 0x8b, 0x5c, 0x42, 0x93, 0x66, 0xf1, 0xd3, 0xf0, 0x0f, 0x03, 0x45, 0xb9, 0x61, 0x23, 0xd5, 0x62, 0x04, 0xc0, 0x1c, 0x63, 0xb2, 0x2c, 0xe7, 0x8b, 0xaf, 0x11, 0x6e, 0x52, 0x5e, 0xd9, - 0x0f, 0xde, 0xa3, 0x9f, 0xa4, 0x69, 0x49, 0x4d, 0x38, 0x66, 0xc3, 0x1e, 0x05, 0xf2, 0x95, 0xff, 0x21, 0xfe, 0xa8, 0xd4, 0xe6, 0xe1, 0x3d, 0x67, 0xe4, 0x7c, 0xe7, 0x22, 0xe9, 0x69, 0x8a, 0x1c, - 0x10, 0x48, 0xd6, 0x8e, 0xbc, 0xde, 0x76, 0xb8, 0x6f, 0xcf, 0x97, 0x6e, 0xab, 0x8a, 0xa9, 0x79, 0x02, 0x68, 0xb7, 0x06, 0x8e, 0x01, 0x7a, 0x8b, 0x9b, 0x74, 0x94, 0x09, 0x51, 0x4f, 0x10, 0x53, - 0x02, 0x7f, 0xd1, 0x6c, 0x37, 0x86, 0xea, 0x1b, 0xac, 0x5f, 0x15, 0xcb, 0x79, 0x71, 0x1e, 0xe2, 0xab, 0xe8, 0x2f, 0x5c, 0xf8, 0xb1, 0x3a, 0xe7, 0x30, 0x30, 0xef, 0x5b, 0x9e, 0x44, 0x57, 0xe7, - 0x5d, 0x13, 0x04, 0xf9, 0x88, 0xd6, 0x2d, 0xd6, 0xfc, 0x4b, 0x94, 0xed, 0x38, 0xba, 0x83, 0x1d, 0xa4, 0xb7, 0x63, 0x49, 0x71, 0xb6, 0xcd, 0x8e, 0xc3, 0x25, 0xd9, 0xc6, 0x1c, 0x00, 0xf1, 0xdf, - 0x73, 0x62, 0x7e, 0xd3, 0x74, 0x5a, 0x5e, 0x84, 0x89, 0xf3, 0xa9, 0x5c, 0x69, 0x63, 0x9c, 0x32, 0xcd, 0x6e, 0x1d, 0x53, 0x7a, 0x85, 0xf7, 0x5c, 0xc8, 0x44, 0x72, 0x6e, 0x8a, 0x72, 0xfc, 0x00, - 0x77, 0xad, 0x22, 0x00, 0x0f, 0x1d, 0x50, 0x78, 0xf6, 0xb8, 0x66, 0x31, 0x8c, 0x66, 0x8f, 0x1a, 0xd0, 0x3d, 0x5a, 0x5f, 0xce, 0xd5, 0x21, 0x9f, 0x2e, 0xab, 0xbd, 0x0a, 0xa5, 0xc0, 0xf4, 0x60, - 0xd1, 0x83, 0xf0, 0x44, 0x04, 0xa0, 0xd6, 0xf4, 0x69, 0x55, 0x8e, 0x81, 0xfa, 0xb2, 0x4a, 0x16, 0x79, 0x05, 0xab, 0x4c, 0x78, 0x78, 0x50, 0x2a, 0xd3, 0xe3, 0x8f, 0xdb, 0xe6, 0x2a, 0x41, 0x55, - 0x6c, 0xec, 0x37, 0x32, 0x57, 0x59, 0x53, 0x3c, 0xe8, 0xf2, 0x5f, 0x36, 0x7c, 0x87, 0xbb, 0x55, 0x78, 0xd6, 0x67, 0xae, 0x93, 0xf9, 0xe2, 0xfd, 0x99, 0xbc, 0xbc, 0x5f, 0x2f, 0xbb, 0xa8, 0x8c, - 0xf6, 0x51, 0x61, 0x39, 0x42, 0x0f, 0xcf, 0xf3, 0xb7, 0x36, 0x1d, 0x86, 0x32, 0x2c, 0x4b, 0xd8, 0x4c, 0x82, 0xf3, 0x35, 0xab, 0xb1, 0x52, 0xc4, 0xa9, 0x34, 0x11, 0x37, 0x3a, 0xaa, 0x82, 0x20 - } -}, -{ - // IEEE 1619 - Vector 14 - - /* This vector must always be the last one in XTS_vectors[] because TestSectorBufEncryption() relies on it. */ - - { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, - { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, - { 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff }, - 0, - { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff - }, - { - 0x64, 0x49, 0x7e, 0x5a, 0x83, 0x1e, 0x4a, 0x93, 0x2c, 0x09, 0xbe, 0x3e, 0x53, 0x93, 0x37, 0x6d, 0xaa, 0x59, 0x95, 0x48, 0xb8, 0x16, 0x03, 0x1d, 0x22, 0x4b, 0xbf, 0x50, 0xa8, 0x18, 0xed, 0x23, - 0x50, 0xea, 0xe7, 0xe9, 0x60, 0x87, 0xc8, 0xa0, 0xdb, 0x51, 0xad, 0x29, 0x0b, 0xd0, 0x0c, 0x1a, 0xc1, 0x62, 0x08, 0x57, 0x63, 0x5b, 0xf2, 0x46, 0xc1, 0x76, 0xab, 0x46, 0x3b, 0xe3, 0x0b, 0x80, - 0x8d, 0xa5, 0x48, 0x08, 0x1a, 0xc8, 0x47, 0xb1, 0x58, 0xe1, 0x26, 0x4b, 0xe2, 0x5b, 0xb0, 0x91, 0x0b, 0xbc, 0x92, 0x64, 0x71, 0x08, 0x08, 0x94, 0x15, 0xd4, 0x5f, 0xab, 0x1b, 0x3d, 0x26, 0x04, - 0xe8, 0xa8, 0xef, 0xf1, 0xae, 0x40, 0x20, 0xcf, 0xa3, 0x99, 0x36, 0xb6, 0x68, 0x27, 0xb2, 0x3f, 0x37, 0x1b, 0x92, 0x20, 0x0b, 0xe9, 0x02, 0x51, 0xe6, 0xd7, 0x3c, 0x5f, 0x86, 0xde, 0x5f, 0xd4, - 0xa9, 0x50, 0x78, 0x19, 0x33, 0xd7, 0x9a, 0x28, 0x27, 0x2b, 0x78, 0x2a, 0x2e, 0xc3, 0x13, 0xef, 0xdf, 0xcc, 0x06, 0x28, 0xf4, 0x3d, 0x74, 0x4c, 0x2d, 0xc2, 0xff, 0x3d, 0xcb, 0x66, 0x99, 0x9b, - 0x50, 0xc7, 0xca, 0x89, 0x5b, 0x0c, 0x64, 0x79, 0x1e, 0xea, 0xa5, 0xf2, 0x94, 0x99, 0xfb, 0x1c, 0x02, 0x6f, 0x84, 0xce, 0x5b, 0x5c, 0x72, 0xba, 0x10, 0x83, 0xcd, 0xdb, 0x5c, 0xe4, 0x54, 0x34, - 0x63, 0x16, 0x65, 0xc3, 0x33, 0xb6, 0x0b, 0x11, 0x59, 0x3f, 0xb2, 0x53, 0xc5, 0x17, 0x9a, 0x2c, 0x8d, 0xb8, 0x13, 0x78, 0x2a, 0x00, 0x48, 0x56, 0xa1, 0x65, 0x30, 0x11, 0xe9, 0x3f, 0xb6, 0xd8, - 0x76, 0xc1, 0x83, 0x66, 0xdd, 0x86, 0x83, 0xf5, 0x34, 0x12, 0xc0, 0xc1, 0x80, 0xf9, 0xc8, 0x48, 0x59, 0x2d, 0x59, 0x3f, 0x86, 0x09, 0xca, 0x73, 0x63, 0x17, 0xd3, 0x56, 0xe1, 0x3e, 0x2b, 0xff, - 0x3a, 0x9f, 0x59, 0xcd, 0x9a, 0xeb, 0x19, 0xcd, 0x48, 0x25, 0x93, 0xd8, 0xc4, 0x61, 0x28, 0xbb, 0x32, 0x42, 0x3b, 0x37, 0xa9, 0xad, 0xfb, 0x48, 0x2b, 0x99, 0x45, 0x3f, 0xbe, 0x25, 0xa4, 0x1b, - 0xf6, 0xfe, 0xb4, 0xaa, 0x0b, 0xef, 0x5e, 0xd2, 0x4b, 0xf7, 0x3c, 0x76, 0x29, 0x78, 0x02, 0x54, 0x82, 0xc1, 0x31, 0x15, 0xe4, 0x01, 0x5a, 0xac, 0x99, 0x2e, 0x56, 0x13, 0xa3, 0xb5, 0xc2, 0xf6, - 0x85, 0xb8, 0x47, 0x95, 0xcb, 0x6e, 0x9b, 0x26, 0x56, 0xd8, 0xc8, 0x81, 0x57, 0xe5, 0x2c, 0x42, 0xf9, 0x78, 0xd8, 0x63, 0x4c, 0x43, 0xd0, 0x6f, 0xea, 0x92, 0x8f, 0x28, 0x22, 0xe4, 0x65, 0xaa, - 0x65, 0x76, 0xe9, 0xbf, 0x41, 0x93, 0x84, 0x50, 0x6c, 0xc3, 0xce, 0x3c, 0x54, 0xac, 0x1a, 0x6f, 0x67, 0xdc, 0x66, 0xf3, 0xb3, 0x01, 0x91, 0xe6, 0x98, 0x38, 0x0b, 0xc9, 0x99, 0xb0, 0x5a, 0xbc, - 0xe1, 0x9d, 0xc0, 0xc6, 0xdc, 0xc2, 0xdd, 0x00, 0x1e, 0xc5, 0x35, 0xba, 0x18, 0xde, 0xb2, 0xdf, 0x1a, 0x10, 0x10, 0x23, 0x10, 0x83, 0x18, 0xc7, 0x5d, 0xc9, 0x86, 0x11, 0xa0, 0x9d, 0xc4, 0x8a, - 0x0a, 0xcd, 0xec, 0x67, 0x6f, 0xab, 0xdf, 0x22, 0x2f, 0x07, 0xe0, 0x26, 0xf0, 0x59, 0xb6, 0x72, 0xb5, 0x6e, 0x5c, 0xbc, 0x8e, 0x1d, 0x21, 0xbb, 0xd8, 0x67, 0xdd, 0x92, 0x72, 0x12, 0x05, 0x46, - 0x81, 0xd7, 0x0e, 0xa7, 0x37, 0x13, 0x4c, 0xdf, 0xce, 0x93, 0xb6, 0xf8, 0x2a, 0xe2, 0x24, 0x23, 0x27, 0x4e, 0x58, 0xa0, 0x82, 0x1c, 0xc5, 0x50, 0x2e, 0x2d, 0x0a, 0xb4, 0x58, 0x5e, 0x94, 0xde, - 0x69, 0x75, 0xbe, 0x5e, 0x0b, 0x4e, 0xfc, 0xe5, 0x1c, 0xd3, 0xe7, 0x0c, 0x25, 0xa1, 0xfb, 0xbb, 0xd6, 0x09, 0xd2, 0x73, 0xad, 0x5b, 0x0d, 0x59, 0x63, 0x1c, 0x53, 0x1f, 0x6a, 0x0a, 0x57, 0xb9 - } -} }; // XTS_TEST XTS_vectors[] - - -BOOL XTSAesTest (PCRYPTO_INFO ci) -{ - unsigned __int8 p[ENCRYPTION_DATA_UNIT_SIZE]; - UINT64_STRUCT dataUnitNo; - int i; - - for (i = 0; i < XTS_TEST_COUNT; i++) - { - ci->ea = EAGetByName (L"AES"); - if (ci->ea == 0) - return FALSE; - - ci->mode = XTS; - - if (EAInit (ci->ea, XTS_vectors[i].key1, ci->ks) != ERR_SUCCESS) - return FALSE; - - memcpy (&ci->k2, XTS_vectors[i].key2, sizeof (XTS_vectors[i].key2)); - - if (!EAInitMode (ci)) - return FALSE; - - memcpy (p, XTS_vectors[i].plaintext, sizeof (p)); - - dataUnitNo.Value = BE64 (*((unsigned __int64 *) XTS_vectors[i].dataUnitNo)); - - EncryptBufferXTS (p, sizeof (p), &dataUnitNo, XTS_vectors[i].blockNo, (unsigned char *) (ci->ks), (unsigned char *) ci->ks2, AES); - - if (memcmp (XTS_vectors[i].ciphertext, p, sizeof (p)) != 0) - return FALSE; - } - - return TRUE; -} - - -// AES ECB test vectors FIPS-197 - -#define AES_TEST_COUNT 1 - -typedef struct { - unsigned char key[32]; - unsigned char plaintext[16]; - unsigned char ciphertext[16]; - } AES_TEST; - -AES_TEST aes_ecb_vectors[AES_TEST_COUNT] = { -0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f, -0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f, - -0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff, - -0x8e,0xa2,0xb7,0xca,0x51,0x67,0x45,0xbf,0xea,0xfc,0x49,0x90,0x4b,0x49,0x60,0x89 -}; - -// Serpent ECB test vectors - -#define SERPENT_TEST_COUNT 1 - -typedef struct { - unsigned char key[32]; - unsigned char plaintext[16]; - unsigned char ciphertext[16]; - } SERPENT_TEST; - -SERPENT_TEST serpent_vectors[SERPENT_TEST_COUNT] = { -0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, -0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - -0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, -0xde, 0x26, 0x9f, 0xf8, 0x33, 0xe4, 0x32, 0xb8, 0x5b, 0x2e, 0x88, 0xd2, 0x70, 0x1c, 0xe7, 0x5c -}; - -// Twofish ECB test vectors - -#define TWOFISH_TEST_COUNT 1 - -typedef struct { - unsigned char key[32]; - unsigned char plaintext[16]; - unsigned char ciphertext[16]; - } TWOFISH_TEST; - -TWOFISH_TEST twofish_vectors[TWOFISH_TEST_COUNT] = { -0xD4, 0x3B, 0xB7, 0x55, 0x6E, 0xA3, 0x2E, 0x46, 0xF2, 0xA2, 0x82, 0xB7, 0xD4, 0x5B, 0x4E, 0x0D, -0x57, 0xFF, 0x73, 0x9D, 0x4D, 0xC9, 0x2C, 0x1B, 0xD7, 0xFC, 0x01, 0x70, 0x0C, 0xC8, 0x21, 0x6F, - -0x90, 0xAF, 0xE9, 0x1B, 0xB2, 0x88, 0x54, 0x4F, 0x2C, 0x32, 0xDC, 0x23, 0x9B, 0x26, 0x35, 0xE6, -0x6C, 0xB4, 0x56, 0x1C, 0x40, 0xBF, 0x0A, 0x97, 0x05, 0x93, 0x1C, 0xB6, 0xD4, 0x08, 0xE7, 0xFA -}; - -/* Test vectors from FIPS 198a, RFC 4231, RFC 2104, RFC 2202, and other sources. */ - -char *hmac_sha256_test_keys[] = -{ - "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b", - "Jefe", - "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", - "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", - "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", - "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", -}; - -char *hmac_sha256_test_data[] = -{ - "Hi There", - "what do ya want for nothing?", - "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd", - "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd", - "Test Using Larger Than Block-Size Key - Hash Key First", - "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.", -}; - -char *hmac_sha256_test_vectors[] = -{ - "\xb0\x34\x4c\x61\xd8\xdb\x38\x53\x5c\xa8\xaf\xce\xaf\x0b\xf1\x2b\x88\x1d\xc2\x00\xc9\x83\x3d\xa7\x26\xe9\x37\x6c\x2e\x32\xcf\xf7", - "\x5b\xdc\xc1\x46\xbf\x60\x75\x4e\x6a\x04\x24\x26\x08\x95\x75\xc7\x5a\x00\x3f\x08\x9d\x27\x39\x83\x9d\xec\x58\xb9\x64\xec\x38\x43", - "\x77\x3e\xa9\x1e\x36\x80\x0e\x46\x85\x4d\xb8\xeb\xd0\x91\x81\xa7\x29\x59\x09\x8b\x3e\xf8\xc1\x22\xd9\x63\x55\x14\xce\xd5\x65\xfe", - "\x82\x55\x8a\x38\x9a\x44\x3c\x0e\xa4\xcc\x81\x98\x99\xf2\x08\x3a\x85\xf0\xfa\xa3\xe5\x78\xf8\x07\x7a\x2e\x3f\xf4\x67\x29\x66\x5b", - "\x60\xe4\x31\x59\x1e\xe0\xb6\x7f\x0d\x8a\x26\xaa\xcb\xf5\xb7\x7f\x8e\x0b\xc6\x21\x37\x28\xc5\x14\x05\x46\x04\x0f\x0e\xe3\x7f\x54", - "\x9b\x09\xff\xa7\x1b\x94\x2f\xcb\x27\x63\x5f\xbc\xd5\xb0\xe9\x44\xbf\xdc\x63\x64\x4f\x07\x13\x93\x8a\x7f\x51\x53\x5c\x3a\x35\xe2", -}; - -char *hmac_sha512_test_keys[] = -{ - "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b", - "Jefe", - "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", - "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", - "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", - "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", -}; - -char *hmac_sha512_test_data[] = -{ - "Hi There", - "what do ya want for nothing?", - "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd", - "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd", - "Test Using Larger Than Block-Size Key - Hash Key First", - "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.", -}; - -char *hmac_sha512_test_vectors[] = -{ - "\x87\xaa\x7c\xde\xa5\xef\x61\x9d\x4f\xf0\xb4\x24\x1a\x1d\x6c\xb0\x23\x79\xf4\xe2\xce\x4e\xc2\x78\x7a\xd0\xb3\x05\x45\xe1\x7c\xde\xda\xa8\x33\xb7\xd6\xb8\xa7\x02\x03\x8b\x27\x4e\xae\xa3\xf4\xe4\xbe\x9d\x91\x4e\xeb\x61\xf1\x70\x2e\x69\x6c\x20\x3a\x12\x68\x54", - "\x16\x4b\x7a\x7b\xfc\xf8\x19\xe2\xe3\x95\xfb\xe7\x3b\x56\xe0\xa3\x87\xbd\x64\x22\x2e\x83\x1f\xd6\x10\x27\x0c\xd7\xea\x25\x05\x54\x97\x58\xbf\x75\xc0\x5a\x99\x4a\x6d\x03\x4f\x65\xf8\xf0\xe6\xfd\xca\xea\xb1\xa3\x4d\x4a\x6b\x4b\x63\x6e\x07\x0a\x38\xbc\xe7\x37", - "\xfa\x73\xb0\x08\x9d\x56\xa2\x84\xef\xb0\xf0\x75\x6c\x89\x0b\xe9\xb1\xb5\xdb\xdd\x8e\xe8\x1a\x36\x55\xf8\x3e\x33\xb2\x27\x9d\x39\xbf\x3e\x84\x82\x79\xa7\x22\xc8\x06\xb4\x85\xa4\x7e\x67\xc8\x07\xb9\x46\xa3\x37\xbe\xe8\x94\x26\x74\x27\x88\x59\xe1\x32\x92\xfb", - "\xb0\xba\x46\x56\x37\x45\x8c\x69\x90\xe5\xa8\xc5\xf6\x1d\x4a\xf7\xe5\x76\xd9\x7f\xf9\x4b\x87\x2d\xe7\x6f\x80\x50\x36\x1e\xe3\xdb\xa9\x1c\xa5\xc1\x1a\xa2\x5e\xb4\xd6\x79\x27\x5c\xc5\x78\x80\x63\xa5\xf1\x97\x41\x12\x0c\x4f\x2d\xe2\xad\xeb\xeb\x10\xa2\x98\xdd", - "\x80\xb2\x42\x63\xc7\xc1\xa3\xeb\xb7\x14\x93\xc1\xdd\x7b\xe8\xb4\x9b\x46\xd1\xf4\x1b\x4a\xee\xc1\x12\x1b\x01\x37\x83\xf8\xf3\x52\x6b\x56\xd0\x37\xe0\x5f\x25\x98\xbd\x0f\xd2\x21\x5d\x6a\x1e\x52\x95\xe6\x4f\x73\xf6\x3f\x0a\xec\x8b\x91\x5a\x98\x5d\x78\x65\x98", - "\xe3\x7b\x6a\x77\x5d\xc8\x7d\xba\xa4\xdf\xa9\xf9\x6e\x5e\x3f\xfd\xde\xbd\x71\xf8\x86\x72\x89\x86\x5d\xf5\xa3\x2d\x20\xcd\xc9\x44\xb6\x02\x2c\xac\x3c\x49\x82\xb1\x0d\x5e\xeb\x55\xc3\xe4\xde\x15\x13\x46\x76\xfb\x6d\xe0\x44\x60\x65\xc9\x74\x40\xfa\x8c\x6a\x58", -}; - -char *hmac_ripemd160_test_keys[] = -{ - "\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff\x01\x23\x45\x67", - "\x01\x23\x45\x67\x89\xab\xcd\xef\xfe\xdc\xba\x98\x76\x54\x32\x10\x00\x11\x22\x33", -}; - -char *hmac_ripemd160_test_data[] = -{ - "message digest", - "12345678901234567890123456789012345678901234567890123456789012345678901234567890", -}; - -char *hmac_ripemd160_test_vectors[] = -{ - "\xf8\x36\x62\xcc\x8d\x33\x9c\x22\x7e\x60\x0f\xcd\x63\x6c\x57\xd2\x57\x1b\x1c\x34", - "\x85\xf1\x64\x70\x3e\x61\xa6\x31\x31\xbe\x7e\x45\x95\x8e\x07\x94\x12\x39\x04\xf9", -}; - -char *hmac_whirlpool_test_key = -{ - "\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF\x01\x23\x45\x67\x89\xAB\xCD\xEF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF\x01\x23\x45\x67\x89\xAB\xCD\xEF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF" -}; - -char *hmac_whirlpool_test_data = -{ - "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" -}; - -char *hmac_whirlpool_test_vectors = -{ - "\x03\x91\xd2\x80\x00\xb6\x62\xbb\xb8\xe6\x23\x3e\xe8\x6c\xf2\xb2\x84\x74\x4c\x73" - "\x8b\x58\x00\xba\x28\x12\xed\x52\x6f\xe3\x15\x3a\xb1\xba\xe7\xe2\x36\xbe\x96\x54" - "\x49\x3f\x19\xfa\xce\xa6\x44\x1f\x60\xf5\xf0\x18\x93\x09\x11\xa5\xe5\xce\xd8\xf2" - "\x6a\xbf\xa4\x02" -}; - -unsigned char ks_tmp[MAX_EXPANDED_KEY]; - -void CipherInit2(int cipher, void* key, void* ks, int key_len) -{ - switch (cipher) - { - - case AES: - CipherInit(cipher,key,ks); - break; - - case SERPENT: - CipherInit(cipher,key,ks); - break; - - case TWOFISH: - CipherInit(cipher,key,ks); - break; - - default: - /* Unknown/wrong ID */ - TC_THROW_FATAL_EXCEPTION; - } -} - - -BOOL TestSectorBufEncryption (PCRYPTO_INFO ci) -{ - unsigned char buf [ENCRYPTION_DATA_UNIT_SIZE * 4]; - unsigned int i; - wchar_t name[64]; - unsigned __int32 crc; - UINT64_STRUCT unitNo; - uint32 nbrUnits; - unsigned __int64 writeOffset; - int testCase = 0; - int nTestsPerformed = 0; - - static unsigned char key1[] = - { - 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27, - 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92, - 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13 - }; - - - /* Encryption/decryption of data units (typically, volume data sectors) */ - - nbrUnits = sizeof (buf) / ENCRYPTION_DATA_UNIT_SIZE; - - ci->mode = XTS; // we only implement XTS - - /* The buffer can accommodate 4 data units and we'll test 4 cases by "scrolling". The data unit 0xFFFFFFFFFF - will "move" from the start of the buffer to its end. For a 512-byte data unit, the byte offset 562949953420800 - corresponds to the data unit 0xFFFFFFFFFF. */ - for (writeOffset = 562949953420800ULL; - writeOffset > 562949953420800ULL - nbrUnits * ENCRYPTION_DATA_UNIT_SIZE; - writeOffset -= ENCRYPTION_DATA_UNIT_SIZE) - { - unitNo.Value = writeOffset / ENCRYPTION_DATA_UNIT_SIZE; - - // Test all EAs that support this mode of operation - for (ci->ea = EAGetFirst (); ci->ea != 0; ci->ea = EAGetNext (ci->ea)) - { - if (!EAIsModeSupported (ci->ea, ci->mode)) - continue; - - EAGetName (name, ci->ea, 0); - - if (EAInit (ci->ea, key1, ci->ks) != ERR_SUCCESS) - return FALSE; - - for (i = 0; i < sizeof (ci->k2); i++) - ci->k2[i] = (unsigned char) i; - - memcpy (&ci->k2, XTS_vectors[XTS_TEST_COUNT-1].key2, sizeof (XTS_vectors[XTS_TEST_COUNT-1].key2)); - - if (!EAInitMode (ci)) - return FALSE; - - // Each data unit will contain the same plaintext - for (i = 0; i < nbrUnits; i++) - { - memcpy ((unsigned char *) buf + i * ENCRYPTION_DATA_UNIT_SIZE, - XTS_vectors[XTS_TEST_COUNT-1].plaintext, - ENCRYPTION_DATA_UNIT_SIZE); - } - - EncryptDataUnits (buf, &unitNo, nbrUnits, ci); - - crc = GetCrc32 (buf, sizeof (buf)); - - if (wcscmp (name, L"AES") == 0) - { - // Verify the ciphertext of the "moving" data unit using the IEEE test vector #14 - if (memcmp (XTS_vectors[XTS_TEST_COUNT-1].ciphertext, - (unsigned char *) buf + testCase * ENCRYPTION_DATA_UNIT_SIZE, - ENCRYPTION_DATA_UNIT_SIZE) != 0) - { - return FALSE; - } - - // CRC of all data units in the buffer for each test case - switch (testCase) - { - case 0: - if (crc != 0x888f2990) - return FALSE; - nTestsPerformed++; - break; - case 1: - if (crc != 0xea28ea34) - return FALSE; - nTestsPerformed++; - break; - case 2: - if (crc != 0xe058f5a2) - return FALSE; - nTestsPerformed++; - break; - case 3: - if (crc != 0x10473dc9) - return FALSE; - nTestsPerformed++; - break; - } - } - else if (wcscmp (name, L"Serpent") == 0) - { - switch (testCase) - { - case 0: - if (crc != 0x7edfecb3) - return FALSE; - nTestsPerformed++; - break; - case 1: - if (crc != 0x357baaaa) - return FALSE; - nTestsPerformed++; - break; - case 2: - if (crc != 0xc7b9fca5) - return FALSE; - nTestsPerformed++; - break; - case 3: - if (crc != 0xb5263e0c) - return FALSE; - nTestsPerformed++; - break; - } - } - else if (wcscmp (name, L"Twofish") == 0) - { - switch (testCase) - { - case 0: - if (crc != 0x91525124) - return FALSE; - nTestsPerformed++; - break; - case 1: - if (crc != 0x2895cc47) - return FALSE; - nTestsPerformed++; - break; - case 2: - if (crc != 0x6bee346d) - return FALSE; - nTestsPerformed++; - break; - case 3: - if (crc != 0xb1c45759) - return FALSE; - nTestsPerformed++; - break; - } - } - else if (wcscmp (name, L"AES-Twofish") == 0) - { - switch (testCase) - { - case 0: - if (crc != 0x6cea7fa2) - return FALSE; - nTestsPerformed++; - break; - case 1: - if (crc != 0x69052c4c) - return FALSE; - nTestsPerformed++; - break; - case 2: - if (crc != 0x88db8de5) - return FALSE; - nTestsPerformed++; - break; - case 3: - if (crc != 0xf16fd8c5) - return FALSE; - nTestsPerformed++; - break; - } - } - else if (wcscmp (name, L"AES-Twofish-Serpent") == 0) - { - switch (testCase) - { - case 0: - if (crc != 0xa2d7d82a) - return FALSE; - nTestsPerformed++; - break; - case 1: - if (crc != 0xdbf76412) - return FALSE; - nTestsPerformed++; - break; - case 2: - if (crc != 0xdf0ea03e) - return FALSE; - nTestsPerformed++; - break; - case 3: - if (crc != 0xdadedff7) - return FALSE; - nTestsPerformed++; - break; - } - } - else if (wcscmp (name, L"Serpent-AES") == 0) - { - switch (testCase) - { - case 0: - if (crc != 0x6dd133b3) - return FALSE; - nTestsPerformed++; - break; - case 1: - if (crc != 0x0e5717d2) - return FALSE; - nTestsPerformed++; - break; - case 2: - if (crc != 0x39f83cd9) - return FALSE; - nTestsPerformed++; - break; - case 3: - if (crc != 0x8a79fa2c) - return FALSE; - nTestsPerformed++; - break; - } - } - else if (wcscmp (name, L"Serpent-Twofish-AES") == 0) - { - switch (testCase) - { - case 0: - if (crc != 0xe536daf8) - return FALSE; - nTestsPerformed++; - break; - case 1: - if (crc != 0x3ae89e7f) - return FALSE; - nTestsPerformed++; - break; - case 2: - if (crc != 0x2cc1301a) - return FALSE; - nTestsPerformed++; - break; - case 3: - if (crc != 0xcac7bdc7) - return FALSE; - nTestsPerformed++; - break; - } - } - else if (wcscmp (name, L"Twofish-Serpent") == 0) - { - switch (testCase) - { - case 0: - if (crc != 0x2686c859) - return FALSE; - nTestsPerformed++; - break; - case 1: - if (crc != 0x8a201780) - return FALSE; - nTestsPerformed++; - break; - case 2: - if (crc != 0x8dd13796) - return FALSE; - nTestsPerformed++; - break; - case 3: - if (crc != 0xe95196cb) - return FALSE; - nTestsPerformed++; - break; - } - } - - if (crc == 0x9f5edd58) - return FALSE; - - DecryptDataUnits (buf, &unitNo, nbrUnits, ci); - - if (GetCrc32 (buf, sizeof (buf)) != 0x9f5edd58) - return FALSE; - - nTestsPerformed++; - } - testCase++; - } - - /* Encryption/decryption of a buffer (typically, a volume header) */ - - nbrUnits = sizeof (buf) / ENCRYPTION_DATA_UNIT_SIZE; - - // Test all EAs that support this mode of operation - for (ci->ea = EAGetFirst (); ci->ea != 0; ci->ea = EAGetNext (ci->ea)) - { - if (!EAIsModeSupported (ci->ea, ci->mode)) - continue; - - EAGetName (name, ci->ea, 0); - - if (EAInit (ci->ea, key1, ci->ks) != ERR_SUCCESS) - return FALSE; - - memcpy (&ci->k2, XTS_vectors[XTS_TEST_COUNT-1].key2, sizeof (XTS_vectors[XTS_TEST_COUNT-1].key2)); - - if (!EAInitMode (ci)) - return FALSE; - - // Each data unit will contain the same plaintext - for (i = 0; i < nbrUnits; i++) - { - memcpy ((unsigned char *) buf + i * ENCRYPTION_DATA_UNIT_SIZE, - XTS_vectors[XTS_TEST_COUNT-1].plaintext, - ENCRYPTION_DATA_UNIT_SIZE); - } - - EncryptBuffer (buf, sizeof (buf), ci); - - crc = GetCrc32 (buf, sizeof (buf)); - - if (wcscmp (name, L"AES") == 0) - { - if (crc != 0x33b91fab) - return FALSE; - nTestsPerformed++; - } - else if (wcscmp (name, L"Serpent") == 0) - { - if (crc != 0x3494d480) - return FALSE; - nTestsPerformed++; - } - else if (wcscmp (name, L"Twofish") == 0) - { - if (crc != 0xc4d65b46) - return FALSE; - nTestsPerformed++; - } - else if (wcscmp (name, L"AES-Twofish") == 0) - { - if (crc != 0x14ce7385) - return FALSE; - nTestsPerformed++; - } - else if (wcscmp (name, L"AES-Twofish-Serpent") == 0) - { - if (crc != 0x0ec81bf7) - return FALSE; - nTestsPerformed++; - } - else if (wcscmp (name, L"Serpent-AES") == 0) - { - if (crc != 0x42f919ad) - return FALSE; - nTestsPerformed++; - } - else if (wcscmp (name, L"Serpent-Twofish-AES") == 0) - { - if (crc != 0x208d5c58) - return FALSE; - nTestsPerformed++; - } - else if (wcscmp (name, L"Twofish-Serpent") == 0) - { - if (crc != 0xbe78cec1) - return FALSE; - nTestsPerformed++; - } - - if (crc == 0x9f5edd58) - return FALSE; - - DecryptBuffer (buf, sizeof (buf), ci); - - if (GetCrc32 (buf, sizeof (buf)) != 0x9f5edd58) - return FALSE; - - nTestsPerformed++; - } - - return (nTestsPerformed == 80); -} - -static BOOL DoAutoTestAlgorithms (void) -{ - PCRYPTO_INFO ci; - char key[32]; - unsigned char tmp[16]; - BOOL bFailed = FALSE; - int i; - - ci = crypto_open (); - if (!ci) - return FALSE; - - memset (ci, 0, sizeof (*ci)); - - /* AES */ - - for (i = 0; i < AES_TEST_COUNT; i++) - { - int cipher = AES; - memcpy(key, aes_ecb_vectors[i].key, 32); - memcpy(tmp, aes_ecb_vectors[i].plaintext, 16); - CipherInit(cipher, key, ks_tmp); - - EncipherBlock(cipher, tmp, ks_tmp); - if (memcmp(aes_ecb_vectors[i].ciphertext, tmp, 16) != 0) - break; - - DecipherBlock(cipher, tmp, ks_tmp); - if (memcmp(aes_ecb_vectors[i].plaintext, tmp, 16) != 0) - break; - } - if (i != AES_TEST_COUNT) - bFailed = TRUE; - - // AES EncipherBlocks()/DecipherBlocks() - { - byte testData[1024]; - uint32 origCrc; - size_t i; - - for (i = 0; i < sizeof (testData); ++i) - { - testData[i] = (byte) i; - } - - origCrc = GetCrc32 (testData, sizeof (testData)); - - CipherInit (AES, testData, ks_tmp); - EncipherBlocks (AES, testData, ks_tmp, sizeof (testData) / CipherGetBlockSize (AES)); - - if (GetCrc32 (testData, sizeof (testData)) != 0xb5cd5631) - bFailed = TRUE; - - DecipherBlocks (AES, testData, ks_tmp, sizeof (testData) / CipherGetBlockSize (AES)); - - if (origCrc != GetCrc32 (testData, sizeof (testData))) - bFailed = TRUE; - } - - /* Serpent */ - - for (i = 0; i < SERPENT_TEST_COUNT; i++) - { - int cipher = SERPENT; - memcpy(key, serpent_vectors[i].key, 32); - memcpy(tmp, serpent_vectors[i].plaintext, 16); - CipherInit(cipher, key, ks_tmp); - - EncipherBlock(cipher, tmp, ks_tmp); - if (memcmp(serpent_vectors[i].ciphertext, tmp, 16) != 0) - break; - - DecipherBlock(cipher, tmp, ks_tmp); - if (memcmp(serpent_vectors[i].plaintext, tmp, 16) != 0) - break; - } - if (i != SERPENT_TEST_COUNT) - bFailed = TRUE; - - - /* Twofish */ - - for (i = 0; i < TWOFISH_TEST_COUNT; i++) - { - int cipher = TWOFISH; - memcpy(key, twofish_vectors[i].key, 32); - memcpy(tmp, twofish_vectors[i].plaintext, 16); - CipherInit(cipher, key, ks_tmp); - - EncipherBlock(cipher, tmp, ks_tmp); - if (memcmp(twofish_vectors[i].ciphertext, tmp, 16) != 0) - break; - - DecipherBlock(cipher, tmp, ks_tmp); - if (memcmp(twofish_vectors[i].plaintext, tmp, 16) != 0) - break; - } - if (i != TWOFISH_TEST_COUNT) - bFailed = TRUE; - - - /* PKCS #5 and HMACs */ - if (!test_pkcs5 ()) - bFailed = TRUE; - - /* CRC-32 */ - if (!crc32_selftests ()) - bFailed = TRUE; - - /* GF multiplicator */ -#if 0 - if (!GfMulSelfTest ()) - bFailed = TRUE; -#endif - - /* XTS-AES */ - if (!XTSAesTest (ci)) - bFailed = TRUE; - - /* Sector and buffer related algorithms */ - if (!TestSectorBufEncryption (ci)) - bFailed = TRUE; - - crypto_close (ci); - return !bFailed; -} - - -BOOL AutoTestAlgorithms (void) -{ - BOOL result = TRUE; - BOOL hwEncryptionEnabled = IsHwEncryptionEnabled(); - - EnableHwEncryption (FALSE); - - if (!DoAutoTestAlgorithms()) - result = FALSE; - - EnableHwEncryption (TRUE); - - if (!DoAutoTestAlgorithms()) - result = FALSE; - - EnableHwEncryption (hwEncryptionEnabled); - return result; -} - -BOOL test_hmac_sha256 () -{ - unsigned int i; - int nTestsPerformed = 0; - - for (i = 0; i < sizeof (hmac_sha256_test_data) / sizeof(char *); i++) - { - char digest[1024]; /* large enough to hold digets and test vector inputs */ - memcpy (digest, hmac_sha256_test_data[i], strlen (hmac_sha256_test_data[i])); - hmac_sha256 (hmac_sha256_test_keys[i], (int) strlen (hmac_sha256_test_keys[i]), digest, (int) strlen (hmac_sha256_test_data[i])); - if (memcmp (digest, hmac_sha256_test_vectors[i], SHA256_DIGESTSIZE) != 0) - return FALSE; - else - nTestsPerformed++; - } - - return (nTestsPerformed == 6); -} - -BOOL test_hmac_sha512 () -{ - unsigned int i; - int nTestsPerformed = 0; - - for (i = 0; i < sizeof (hmac_sha512_test_data) / sizeof(char *); i++) - { - char digest[1024]; /* large enough to hold digets and test vector inputs */ - memcpy (digest, hmac_sha512_test_data[i], (int) strlen (hmac_sha512_test_data[i])); - hmac_sha512 (hmac_sha512_test_keys[i], (int) strlen (hmac_sha512_test_keys[i]), digest, (int) strlen (hmac_sha512_test_data[i])); - if (memcmp (digest, hmac_sha512_test_vectors[i], SHA512_DIGESTSIZE) != 0) - return FALSE; - else - nTestsPerformed++; - } - - return (nTestsPerformed == 6); -} - -BOOL test_hmac_ripemd160 () -{ - int nTestsPerformed = 0; - unsigned int i; - - for (i = 0; i < sizeof (hmac_ripemd160_test_data) / sizeof(char *); i++) - { - char digest[1024]; /* large enough to hold digets and test vector inputs */ - memcpy (digest, hmac_ripemd160_test_data[i], strlen (hmac_ripemd160_test_data[i])); - hmac_ripemd160 (hmac_ripemd160_test_keys[i], RIPEMD160_DIGESTSIZE, digest, (int) strlen (hmac_ripemd160_test_data[i])); - if (memcmp (digest, hmac_ripemd160_test_vectors[i], RIPEMD160_DIGESTSIZE) != 0) - return FALSE; - else - nTestsPerformed++; - } - - return (nTestsPerformed == 2); -} - -BOOL test_hmac_whirlpool () -{ - unsigned char digest[1024]; /* large enough to hold digets and test vector inputs */ - - memcpy (digest, hmac_whirlpool_test_data, strlen (hmac_whirlpool_test_data)); - hmac_whirlpool (hmac_whirlpool_test_key, 64, digest, (int) strlen (hmac_whirlpool_test_data)); - if (memcmp (digest, hmac_whirlpool_test_vectors, WHIRLPOOL_DIGESTSIZE) != 0) - return FALSE; - - return TRUE; -} - -BOOL test_pkcs5 () -{ - char dk[144]; - - /* HMAC-SHA-256 tests */ - if (!test_hmac_sha256()) - return FALSE; - - /* HMAC-SHA-512 tests */ - if (!test_hmac_sha512()) - return FALSE; - - /* HMAC-RIPEMD-160 tests */ - if (test_hmac_ripemd160() == FALSE) - return FALSE; - - /* HMAC-Whirlpool tests */ - if (test_hmac_whirlpool() == FALSE) - return FALSE; - - /* PKCS-5 test 1 with HMAC-SHA-256 used as the PRF (https://tools.ietf.org/html/draft-josefsson-scrypt-kdf-00) */ - derive_key_sha256 ("passwd", 6, "\x73\x61\x6C\x74", 4, 1, dk, 64); - if (memcmp (dk, "\x55\xac\x04\x6e\x56\xe3\x08\x9f\xec\x16\x91\xc2\x25\x44\xb6\x05\xf9\x41\x85\x21\x6d\xde\x04\x65\xe6\x8b\x9d\x57\xc2\x0d\xac\xbc\x49\xca\x9c\xcc\xf1\x79\xb6\x45\x99\x16\x64\xb3\x9d\x77\xef\x31\x7c\x71\xb8\x45\xb1\xe3\x0b\xd5\x09\x11\x20\x41\xd3\xa1\x97\x83", 64) != 0) - return FALSE; - - /* PKCS-5 test 2 with HMAC-SHA-256 used as the PRF (https://stackoverflow.com/questions/5130513/pbkdf2-hmac-sha2-test-vectors) */ - derive_key_sha256 ("password", 8, "\x73\x61\x6C\x74", 4, 2, dk, 32); - if (memcmp (dk, "\xae\x4d\x0c\x95\xaf\x6b\x46\xd3\x2d\x0a\xdf\xf9\x28\xf0\x6d\xd0\x2a\x30\x3f\x8e\xf3\xc2\x51\xdf\xd6\xe2\xd8\x5a\x95\x47\x4c\x43", 32) != 0) - return FALSE; - - /* PKCS-5 test 3 with HMAC-SHA-256 used as the PRF (MS CryptoAPI) */ - derive_key_sha256 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); - if (memcmp (dk, "\xf2\xa0\x4f\xb2", 4) != 0) - return FALSE; - - /* PKCS-5 test 4 with HMAC-SHA-256 used as the PRF (MS CryptoAPI) */ - derive_key_sha256 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 144); - if (memcmp (dk, "\xf2\xa0\x4f\xb2\xd3\xe9\xa5\xd8\x51\x0b\x5c\x06\xdf\x70\x8e\x24\xe9\xc7\xd9\x15\x3d\x22\xcd\xde\xb8\xa6\xdb\xfd\x71\x85\xc6\x99\x32\xc0\xee\x37\x27\xf7\x24\xcf\xea\xa6\xac\x73\xa1\x4c\x4e\x52\x9b\x94\xf3\x54\x06\xfc\x04\x65\xa1\x0a\x24\xfe\xf0\x98\x1d\xa6\x22\x28\xeb\x24\x55\x74\xce\x6a\x3a\x28\xe2\x04\x3a\x59\x13\xec\x3f\xf2\xdb\xcf\x58\xdd\x53\xd9\xf9\x17\xf6\xda\x74\x06\x3c\x0b\x66\xf5\x0f\xf5\x58\xa3\x27\x52\x8c\x5b\x07\x91\xd0\x81\xeb\xb6\xbc\x30\x69\x42\x71\xf2\xd7\x18\x42\xbe\xe8\x02\x93\x70\x66\xad\x35\x65\xbc\xf7\x96\x8e\x64\xf1\xc6\x92\xda\xe0\xdc\x1f\xb5\xf4", 144) != 0) - return FALSE; - - /* PKCS-5 test 1 with HMAC-SHA-512 used as the PRF */ - derive_key_sha512 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); - if (memcmp (dk, "\x13\x64\xae\xf8", 4) != 0) - return FALSE; - - /* PKCS-5 test 2 with HMAC-SHA-512 used as the PRF (derives a key longer than the underlying - hash output size and block size) */ - derive_key_sha512 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 144); - if (memcmp (dk, "\x13\x64\xae\xf8\x0d\xf5\x57\x6c\x30\xd5\x71\x4c\xa7\x75\x3f\xfd\x00\xe5\x25\x8b\x39\xc7\x44\x7f\xce\x23\x3d\x08\x75\xe0\x2f\x48\xd6\x30\xd7\x00\xb6\x24\xdb\xe0\x5a\xd7\x47\xef\x52\xca\xa6\x34\x83\x47\xe5\xcb\xe9\x87\xf1\x20\x59\x6a\xe6\xa9\xcf\x51\x78\xc6\xb6\x23\xa6\x74\x0d\xe8\x91\xbe\x1a\xd0\x28\xcc\xce\x16\x98\x9a\xbe\xfb\xdc\x78\xc9\xe1\x7d\x72\x67\xce\xe1\x61\x56\x5f\x96\x68\xe6\xe1\xdd\xf4\xbf\x1b\x80\xe0\x19\x1c\xf4\xc4\xd3\xdd\xd5\xd5\x57\x2d\x83\xc7\xa3\x37\x87\xf4\x4e\xe0\xf6\xd8\x6d\x65\xdc\xa0\x52\xa3\x13\xbe\x81\xfc\x30\xbe\x7d\x69\x58\x34\xb6\xdd\x41\xc6", 144) != 0) - return FALSE; - - /* PKCS-5 test 1 with HMAC-RIPEMD-160 used as the PRF */ - derive_key_ripemd160 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); - if (memcmp (dk, "\x7a\x3d\x7c\x03", 4) != 0) - return FALSE; - - /* PKCS-5 test 2 with HMAC-RIPEMD-160 used as the PRF (derives a key longer than the underlying hash) */ - derive_key_ripemd160 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 48); - if (memcmp (dk, "\x7a\x3d\x7c\x03\xe7\x26\x6b\xf8\x3d\x78\xfb\x29\xd2\x64\x1f\x56\xea\xf0\xe5\xf5\xcc\xc4\x3a\x31\xa8\x84\x70\xbf\xbd\x6f\x8e\x78\x24\x5a\xc0\x0a\xf6\xfa\xf0\xf6\xe9\x00\x47\x5f\x73\xce\xe1\x43", 48) != 0) - return FALSE; - - /* PKCS-5 test 1 with HMAC-Whirlpool used as the PRF */ - derive_key_whirlpool ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); - if (memcmp (dk, "\x50\x7c\x36\x6f", 4) != 0) - return FALSE; - - /* PKCS-5 test 2 with HMAC-Whirlpool used as the PRF (derives a key longer than the underlying hash) */ - derive_key_whirlpool ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 96); - if (memcmp (dk, "\x50\x7c\x36\x6f\xee\x10\x2e\x9a\xe2\x8a\xd5\x82\x72\x7d\x27\x0f\xe8\x4d\x7f\x68\x7a\xcf\xb5\xe7\x43\x67\xaa\x98\x93\x52\x2b\x09\x6e\x42\xdf\x2c\x59\x4a\x91\x6d\x7e\x10\xae\xb2\x1a\x89\x8f\xb9\x8f\xe6\x31\xa9\xd8\x9f\x98\x26\xf4\xda\xcd\x7d\x65\x65\xde\x10\x95\x91\xb4\x84\x26\xae\x43\xa1\x00\x5b\x1e\xb8\x38\x97\xa4\x1e\x4b\xd2\x65\x64\xbc\xfa\x1f\x35\x85\xdb\x4f\x97\x65\x6f\xbd\x24", 96) != 0) - return FALSE; - - return TRUE; -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" +#include "Crc.h" +#include "Crypto.h" +#include "Common/Endian.h" +#include "Tests.h" +#include "Xts.h" +#include +#include "Pkcs5.h" + +typedef struct { + unsigned __int8 key1[32]; + unsigned __int8 key2[32]; + unsigned __int8 dataUnitNo[8]; + unsigned int blockNo; + unsigned __int8 plaintext[ENCRYPTION_DATA_UNIT_SIZE]; + unsigned __int8 ciphertext[ENCRYPTION_DATA_UNIT_SIZE]; +} XTS_TEST; + +#define XTS_TEST_COUNT 5 + +XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { +/* XTS-AES-256 */ +{ + // IEEE 1619 - Vector 10 + + { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, + { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff }, + 0, + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + }, + { + 0x1c, 0x3b, 0x3a, 0x10, 0x2f, 0x77, 0x03, 0x86, 0xe4, 0x83, 0x6c, 0x99, 0xe3, 0x70, 0xcf, 0x9b, 0xea, 0x00, 0x80, 0x3f, 0x5e, 0x48, 0x23, 0x57, 0xa4, 0xae, 0x12, 0xd4, 0x14, 0xa3, 0xe6, 0x3b, + 0x5d, 0x31, 0xe2, 0x76, 0xf8, 0xfe, 0x4a, 0x8d, 0x66, 0xb3, 0x17, 0xf9, 0xac, 0x68, 0x3f, 0x44, 0x68, 0x0a, 0x86, 0xac, 0x35, 0xad, 0xfc, 0x33, 0x45, 0xbe, 0xfe, 0xcb, 0x4b, 0xb1, 0x88, 0xfd, + 0x57, 0x76, 0x92, 0x6c, 0x49, 0xa3, 0x09, 0x5e, 0xb1, 0x08, 0xfd, 0x10, 0x98, 0xba, 0xec, 0x70, 0xaa, 0xa6, 0x69, 0x99, 0xa7, 0x2a, 0x82, 0xf2, 0x7d, 0x84, 0x8b, 0x21, 0xd4, 0xa7, 0x41, 0xb0, + 0xc5, 0xcd, 0x4d, 0x5f, 0xff, 0x9d, 0xac, 0x89, 0xae, 0xba, 0x12, 0x29, 0x61, 0xd0, 0x3a, 0x75, 0x71, 0x23, 0xe9, 0x87, 0x0f, 0x8a, 0xcf, 0x10, 0x00, 0x02, 0x08, 0x87, 0x89, 0x14, 0x29, 0xca, + 0x2a, 0x3e, 0x7a, 0x7d, 0x7d, 0xf7, 0xb1, 0x03, 0x55, 0x16, 0x5c, 0x8b, 0x9a, 0x6d, 0x0a, 0x7d, 0xe8, 0xb0, 0x62, 0xc4, 0x50, 0x0d, 0xc4, 0xcd, 0x12, 0x0c, 0x0f, 0x74, 0x18, 0xda, 0xe3, 0xd0, + 0xb5, 0x78, 0x1c, 0x34, 0x80, 0x3f, 0xa7, 0x54, 0x21, 0xc7, 0x90, 0xdf, 0xe1, 0xde, 0x18, 0x34, 0xf2, 0x80, 0xd7, 0x66, 0x7b, 0x32, 0x7f, 0x6c, 0x8c, 0xd7, 0x55, 0x7e, 0x12, 0xac, 0x3a, 0x0f, + 0x93, 0xec, 0x05, 0xc5, 0x2e, 0x04, 0x93, 0xef, 0x31, 0xa1, 0x2d, 0x3d, 0x92, 0x60, 0xf7, 0x9a, 0x28, 0x9d, 0x6a, 0x37, 0x9b, 0xc7, 0x0c, 0x50, 0x84, 0x14, 0x73, 0xd1, 0xa8, 0xcc, 0x81, 0xec, + 0x58, 0x3e, 0x96, 0x45, 0xe0, 0x7b, 0x8d, 0x96, 0x70, 0x65, 0x5b, 0xa5, 0xbb, 0xcf, 0xec, 0xc6, 0xdc, 0x39, 0x66, 0x38, 0x0a, 0xd8, 0xfe, 0xcb, 0x17, 0xb6, 0xba, 0x02, 0x46, 0x9a, 0x02, 0x0a, + 0x84, 0xe1, 0x8e, 0x8f, 0x84, 0x25, 0x20, 0x70, 0xc1, 0x3e, 0x9f, 0x1f, 0x28, 0x9b, 0xe5, 0x4f, 0xbc, 0x48, 0x14, 0x57, 0x77, 0x8f, 0x61, 0x60, 0x15, 0xe1, 0x32, 0x7a, 0x02, 0xb1, 0x40, 0xf1, + 0x50, 0x5e, 0xb3, 0x09, 0x32, 0x6d, 0x68, 0x37, 0x8f, 0x83, 0x74, 0x59, 0x5c, 0x84, 0x9d, 0x84, 0xf4, 0xc3, 0x33, 0xec, 0x44, 0x23, 0x88, 0x51, 0x43, 0xcb, 0x47, 0xbd, 0x71, 0xc5, 0xed, 0xae, + 0x9b, 0xe6, 0x9a, 0x2f, 0xfe, 0xce, 0xb1, 0xbe, 0xc9, 0xde, 0x24, 0x4f, 0xbe, 0x15, 0x99, 0x2b, 0x11, 0xb7, 0x7c, 0x04, 0x0f, 0x12, 0xbd, 0x8f, 0x6a, 0x97, 0x5a, 0x44, 0xa0, 0xf9, 0x0c, 0x29, + 0xa9, 0xab, 0xc3, 0xd4, 0xd8, 0x93, 0x92, 0x72, 0x84, 0xc5, 0x87, 0x54, 0xcc, 0xe2, 0x94, 0x52, 0x9f, 0x86, 0x14, 0xdc, 0xd2, 0xab, 0xa9, 0x91, 0x92, 0x5f, 0xed, 0xc4, 0xae, 0x74, 0xff, 0xac, + 0x6e, 0x33, 0x3b, 0x93, 0xeb, 0x4a, 0xff, 0x04, 0x79, 0xda, 0x9a, 0x41, 0x0e, 0x44, 0x50, 0xe0, 0xdd, 0x7a, 0xe4, 0xc6, 0xe2, 0x91, 0x09, 0x00, 0x57, 0x5d, 0xa4, 0x01, 0xfc, 0x07, 0x05, 0x9f, + 0x64, 0x5e, 0x8b, 0x7e, 0x9b, 0xfd, 0xef, 0x33, 0x94, 0x30, 0x54, 0xff, 0x84, 0x01, 0x14, 0x93, 0xc2, 0x7b, 0x34, 0x29, 0xea, 0xed, 0xb4, 0xed, 0x53, 0x76, 0x44, 0x1a, 0x77, 0xed, 0x43, 0x85, + 0x1a, 0xd7, 0x7f, 0x16, 0xf5, 0x41, 0xdf, 0xd2, 0x69, 0xd5, 0x0d, 0x6a, 0x5f, 0x14, 0xfb, 0x0a, 0xab, 0x1c, 0xbb, 0x4c, 0x15, 0x50, 0xbe, 0x97, 0xf7, 0xab, 0x40, 0x66, 0x19, 0x3c, 0x4c, 0xaa, + 0x77, 0x3d, 0xad, 0x38, 0x01, 0x4b, 0xd2, 0x09, 0x2f, 0xa7, 0x55, 0xc8, 0x24, 0xbb, 0x5e, 0x54, 0xc4, 0xf3, 0x6f, 0xfd, 0xa9, 0xfc, 0xea, 0x70, 0xb9, 0xc6, 0xe6, 0x93, 0xe1, 0x48, 0xc1, 0x51 + } +}, +{ + // IEEE 1619 - Vector 11 + + { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, + { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff }, + 0, + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + }, + { + 0x77, 0xa3, 0x12, 0x51, 0x61, 0x8a, 0x15, 0xe6, 0xb9, 0x2d, 0x1d, 0x66, 0xdf, 0xfe, 0x7b, 0x50, 0xb5, 0x0b, 0xad, 0x55, 0x23, 0x05, 0xba, 0x02, 0x17, 0xa6, 0x10, 0x68, 0x8e, 0xff, 0x7e, 0x11, + 0xe1, 0xd0, 0x22, 0x54, 0x38, 0xe0, 0x93, 0x24, 0x2d, 0x6d, 0xb2, 0x74, 0xfd, 0xe8, 0x01, 0xd4, 0xca, 0xe0, 0x6f, 0x20, 0x92, 0xc7, 0x28, 0xb2, 0x47, 0x85, 0x59, 0xdf, 0x58, 0xe8, 0x37, 0xc2, + 0x46, 0x9e, 0xe4, 0xa4, 0xfa, 0x79, 0x4e, 0x4b, 0xbc, 0x7f, 0x39, 0xbc, 0x02, 0x6e, 0x3c, 0xb7, 0x2c, 0x33, 0xb0, 0x88, 0x8f, 0x25, 0xb4, 0xac, 0xf5, 0x6a, 0x2a, 0x98, 0x04, 0xf1, 0xce, 0x6d, + 0x3d, 0x6e, 0x1d, 0xc6, 0xca, 0x18, 0x1d, 0x4b, 0x54, 0x61, 0x79, 0xd5, 0x55, 0x44, 0xaa, 0x77, 0x60, 0xc4, 0x0d, 0x06, 0x74, 0x15, 0x39, 0xc7, 0xe3, 0xcd, 0x9d, 0x2f, 0x66, 0x50, 0xb2, 0x01, + 0x3f, 0xd0, 0xee, 0xb8, 0xc2, 0xb8, 0xe3, 0xd8, 0xd2, 0x40, 0xcc, 0xae, 0x2d, 0x4c, 0x98, 0x32, 0x0a, 0x74, 0x42, 0xe1, 0xc8, 0xd7, 0x5a, 0x42, 0xd6, 0xe6, 0xcf, 0xa4, 0xc2, 0xec, 0xa1, 0x79, + 0x8d, 0x15, 0x8c, 0x7a, 0xec, 0xdf, 0x82, 0x49, 0x0f, 0x24, 0xbb, 0x9b, 0x38, 0xe1, 0x08, 0xbc, 0xda, 0x12, 0xc3, 0xfa, 0xf9, 0xa2, 0x11, 0x41, 0xc3, 0x61, 0x3b, 0x58, 0x36, 0x7f, 0x92, 0x2a, + 0xaa, 0x26, 0xcd, 0x22, 0xf2, 0x3d, 0x70, 0x8d, 0xae, 0x69, 0x9a, 0xd7, 0xcb, 0x40, 0xa8, 0xad, 0x0b, 0x6e, 0x27, 0x84, 0x97, 0x3d, 0xcb, 0x60, 0x56, 0x84, 0xc0, 0x8b, 0x8d, 0x69, 0x98, 0xc6, + 0x9a, 0xac, 0x04, 0x99, 0x21, 0x87, 0x1e, 0xbb, 0x65, 0x30, 0x1a, 0x46, 0x19, 0xca, 0x80, 0xec, 0xb4, 0x85, 0xa3, 0x1d, 0x74, 0x42, 0x23, 0xce, 0x8d, 0xdc, 0x23, 0x94, 0x82, 0x8d, 0x6a, 0x80, + 0x47, 0x0c, 0x09, 0x2f, 0x5b, 0xa4, 0x13, 0xc3, 0x37, 0x8f, 0xa6, 0x05, 0x42, 0x55, 0xc6, 0xf9, 0xdf, 0x44, 0x95, 0x86, 0x2b, 0xbb, 0x32, 0x87, 0x68, 0x1f, 0x93, 0x1b, 0x68, 0x7c, 0x88, 0x8a, + 0xbf, 0x84, 0x4d, 0xfc, 0x8f, 0xc2, 0x83, 0x31, 0xe5, 0x79, 0x92, 0x8c, 0xd1, 0x2b, 0xd2, 0x39, 0x0a, 0xe1, 0x23, 0xcf, 0x03, 0x81, 0x8d, 0x14, 0xde, 0xdd, 0xe5, 0xc0, 0xc2, 0x4c, 0x8a, 0xb0, + 0x18, 0xbf, 0xca, 0x75, 0xca, 0x09, 0x6f, 0x2d, 0x53, 0x1f, 0x3d, 0x16, 0x19, 0xe7, 0x85, 0xf1, 0xad, 0xa4, 0x37, 0xca, 0xb9, 0x2e, 0x98, 0x05, 0x58, 0xb3, 0xdc, 0xe1, 0x47, 0x4a, 0xfb, 0x75, + 0xbf, 0xed, 0xbf, 0x8f, 0xf5, 0x4c, 0xb2, 0x61, 0x8e, 0x02, 0x44, 0xc9, 0xac, 0x0d, 0x3c, 0x66, 0xfb, 0x51, 0x59, 0x8c, 0xd2, 0xdb, 0x11, 0xf9, 0xbe, 0x39, 0x79, 0x1a, 0xbe, 0x44, 0x7c, 0x63, + 0x09, 0x4f, 0x7c, 0x45, 0x3b, 0x7f, 0xf8, 0x7c, 0xb5, 0xbb, 0x36, 0xb7, 0xc7, 0x9e, 0xfb, 0x08, 0x72, 0xd1, 0x70, 0x58, 0xb8, 0x3b, 0x15, 0xab, 0x08, 0x66, 0xad, 0x8a, 0x58, 0x65, 0x6c, 0x5a, + 0x7e, 0x20, 0xdb, 0xdf, 0x30, 0x8b, 0x24, 0x61, 0xd9, 0x7c, 0x0e, 0xc0, 0x02, 0x4a, 0x27, 0x15, 0x05, 0x52, 0x49, 0xcf, 0x3b, 0x47, 0x8d, 0xdd, 0x47, 0x40, 0xde, 0x65, 0x4f, 0x75, 0xca, 0x68, + 0x6e, 0x0d, 0x73, 0x45, 0xc6, 0x9e, 0xd5, 0x0c, 0xdc, 0x2a, 0x8b, 0x33, 0x2b, 0x1f, 0x88, 0x24, 0x10, 0x8a, 0xc9, 0x37, 0xeb, 0x05, 0x05, 0x85, 0x60, 0x8e, 0xe7, 0x34, 0x09, 0x7f, 0xc0, 0x90, + 0x54, 0xfb, 0xff, 0x89, 0xee, 0xae, 0xea, 0x79, 0x1f, 0x4a, 0x7a, 0xb1, 0xf9, 0x86, 0x82, 0x94, 0xa4, 0xf9, 0xe2, 0x7b, 0x42, 0xaf, 0x81, 0x00, 0xcb, 0x9d, 0x59, 0xce, 0xf9, 0x64, 0x58, 0x03 + } +}, +{ + // IEEE 1619 - Vector 12 + + { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, + { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, + { 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff }, + 0, + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + }, + { + 0xe3, 0x87, 0xaa, 0xa5, 0x8b, 0xa4, 0x83, 0xaf, 0xa7, 0xe8, 0xeb, 0x46, 0x97, 0x78, 0x31, 0x7e, 0xcf, 0x4c, 0xf5, 0x73, 0xaa, 0x9d, 0x4e, 0xac, 0x23, 0xf2, 0xcd, 0xf9, 0x14, 0xe4, 0xe2, 0x00, + 0xa8, 0xb4, 0x90, 0xe4, 0x2e, 0xe6, 0x46, 0x80, 0x2d, 0xc6, 0xee, 0x2b, 0x47, 0x1b, 0x27, 0x81, 0x95, 0xd6, 0x09, 0x18, 0xec, 0xec, 0xb4, 0x4b, 0xf7, 0x99, 0x66, 0xf8, 0x3f, 0xab, 0xa0, 0x49, + 0x92, 0x98, 0xeb, 0xc6, 0x99, 0xc0, 0xc8, 0x63, 0x47, 0x15, 0xa3, 0x20, 0xbb, 0x4f, 0x07, 0x5d, 0x62, 0x2e, 0x74, 0xc8, 0xc9, 0x32, 0x00, 0x4f, 0x25, 0xb4, 0x1e, 0x36, 0x10, 0x25, 0xb5, 0xa8, + 0x78, 0x15, 0x39, 0x1f, 0x61, 0x08, 0xfc, 0x4a, 0xfa, 0x6a, 0x05, 0xd9, 0x30, 0x3c, 0x6b, 0xa6, 0x8a, 0x12, 0x8a, 0x55, 0x70, 0x5d, 0x41, 0x59, 0x85, 0x83, 0x2f, 0xde, 0xaa, 0xe6, 0xc8, 0xe1, + 0x91, 0x10, 0xe8, 0x4d, 0x1b, 0x1f, 0x19, 0x9a, 0x26, 0x92, 0x11, 0x9e, 0xdc, 0x96, 0x13, 0x26, 0x58, 0xf0, 0x9d, 0xa7, 0xc6, 0x23, 0xef, 0xce, 0xc7, 0x12, 0x53, 0x7a, 0x3d, 0x94, 0xc0, 0xbf, + 0x5d, 0x7e, 0x35, 0x2e, 0xc9, 0x4a, 0xe5, 0x79, 0x7f, 0xdb, 0x37, 0x7d, 0xc1, 0x55, 0x11, 0x50, 0x72, 0x1a, 0xdf, 0x15, 0xbd, 0x26, 0xa8, 0xef, 0xc2, 0xfc, 0xaa, 0xd5, 0x68, 0x81, 0xfa, 0x9e, + 0x62, 0x46, 0x2c, 0x28, 0xf3, 0x0a, 0xe1, 0xce, 0xac, 0xa9, 0x3c, 0x34, 0x5c, 0xf2, 0x43, 0xb7, 0x3f, 0x54, 0x2e, 0x20, 0x74, 0xa7, 0x05, 0xbd, 0x26, 0x43, 0xbb, 0x9f, 0x7c, 0xc7, 0x9b, 0xb6, + 0xe7, 0x09, 0x1e, 0xa6, 0xe2, 0x32, 0xdf, 0x0f, 0x9a, 0xd0, 0xd6, 0xcf, 0x50, 0x23, 0x27, 0x87, 0x6d, 0x82, 0x20, 0x7a, 0xbf, 0x21, 0x15, 0xcd, 0xac, 0xf6, 0xd5, 0xa4, 0x8f, 0x6c, 0x18, 0x79, + 0xa6, 0x5b, 0x11, 0x5f, 0x0f, 0x8b, 0x3c, 0xb3, 0xc5, 0x9d, 0x15, 0xdd, 0x8c, 0x76, 0x9b, 0xc0, 0x14, 0x79, 0x5a, 0x18, 0x37, 0xf3, 0x90, 0x1b, 0x58, 0x45, 0xeb, 0x49, 0x1a, 0xdf, 0xef, 0xe0, + 0x97, 0xb1, 0xfa, 0x30, 0xa1, 0x2f, 0xc1, 0xf6, 0x5b, 0xa2, 0x29, 0x05, 0x03, 0x15, 0x39, 0x97, 0x1a, 0x10, 0xf2, 0xf3, 0x6c, 0x32, 0x1b, 0xb5, 0x13, 0x31, 0xcd, 0xef, 0xb3, 0x9e, 0x39, 0x64, + 0xc7, 0xef, 0x07, 0x99, 0x94, 0xf5, 0xb6, 0x9b, 0x2e, 0xdd, 0x83, 0xa7, 0x1e, 0xf5, 0x49, 0x97, 0x1e, 0xe9, 0x3f, 0x44, 0xea, 0xc3, 0x93, 0x8f, 0xcd, 0xd6, 0x1d, 0x01, 0xfa, 0x71, 0x79, 0x9d, + 0xa3, 0xa8, 0x09, 0x1c, 0x4c, 0x48, 0xaa, 0x9e, 0xd2, 0x63, 0xff, 0x07, 0x49, 0xdf, 0x95, 0xd4, 0x4f, 0xef, 0x6a, 0x0b, 0xb5, 0x78, 0xec, 0x69, 0x45, 0x6a, 0xa5, 0x40, 0x8a, 0xe3, 0x2c, 0x7a, + 0xf0, 0x8a, 0xd7, 0xba, 0x89, 0x21, 0x28, 0x7e, 0x3b, 0xbe, 0xe3, 0x1b, 0x76, 0x7b, 0xe0, 0x6a, 0x0e, 0x70, 0x5c, 0x86, 0x4a, 0x76, 0x91, 0x37, 0xdf, 0x28, 0x29, 0x22, 0x83, 0xea, 0x81, 0xa2, + 0x48, 0x02, 0x41, 0xb4, 0x4d, 0x99, 0x21, 0xcd, 0xbe, 0xc1, 0xbc, 0x28, 0xdc, 0x1f, 0xda, 0x11, 0x4b, 0xd8, 0xe5, 0x21, 0x7a, 0xc9, 0xd8, 0xeb, 0xaf, 0xa7, 0x20, 0xe9, 0xda, 0x4f, 0x9a, 0xce, + 0x23, 0x1c, 0xc9, 0x49, 0xe5, 0xb9, 0x6f, 0xe7, 0x6f, 0xfc, 0x21, 0x06, 0x3f, 0xdd, 0xc8, 0x3a, 0x6b, 0x86, 0x79, 0xc0, 0x0d, 0x35, 0xe0, 0x95, 0x76, 0xa8, 0x75, 0x30, 0x5b, 0xed, 0x5f, 0x36, + 0xed, 0x24, 0x2c, 0x89, 0x00, 0xdd, 0x1f, 0xa9, 0x65, 0xbc, 0x95, 0x0d, 0xfc, 0xe0, 0x9b, 0x13, 0x22, 0x63, 0xa1, 0xee, 0xf5, 0x2d, 0xd6, 0x88, 0x8c, 0x30, 0x9f, 0x5a, 0x7d, 0x71, 0x28, 0x26 + } +}, +{ + // IEEE 1619 - Vector 13 + + { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, + { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, + { 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff }, + 0, + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + }, + { + 0xbf, 0x53, 0xd2, 0xda, 0xde, 0x78, 0xe8, 0x22, 0xa4, 0xd9, 0x49, 0xa9, 0xbc, 0x67, 0x66, 0xb0, 0x1b, 0x06, 0xa8, 0xef, 0x70, 0xd2, 0x67, 0x48, 0xc6, 0xa7, 0xfc, 0x36, 0xd8, 0x0a, 0xe4, 0xc5, + 0x52, 0x0f, 0x7c, 0x4a, 0xb0, 0xac, 0x85, 0x44, 0x42, 0x4f, 0xa4, 0x05, 0x16, 0x2f, 0xef, 0x5a, 0x6b, 0x7f, 0x22, 0x94, 0x98, 0x06, 0x36, 0x18, 0xd3, 0x9f, 0x00, 0x03, 0xcb, 0x5f, 0xb8, 0xd1, + 0xc8, 0x6b, 0x64, 0x34, 0x97, 0xda, 0x1f, 0xf9, 0x45, 0xc8, 0xd3, 0xbe, 0xde, 0xca, 0x4f, 0x47, 0x97, 0x02, 0xa7, 0xa7, 0x35, 0xf0, 0x43, 0xdd, 0xb1, 0xd6, 0xaa, 0xad, 0xe3, 0xc4, 0xa0, 0xac, + 0x7c, 0xa7, 0xf3, 0xfa, 0x52, 0x79, 0xbe, 0xf5, 0x6f, 0x82, 0xcd, 0x7a, 0x2f, 0x38, 0x67, 0x2e, 0x82, 0x48, 0x14, 0xe1, 0x07, 0x00, 0x30, 0x0a, 0x05, 0x5e, 0x16, 0x30, 0xb8, 0xf1, 0xcb, 0x0e, + 0x91, 0x9f, 0x5e, 0x94, 0x20, 0x10, 0xa4, 0x16, 0xe2, 0xbf, 0x48, 0xcb, 0x46, 0x99, 0x3d, 0x3c, 0xb6, 0xa5, 0x1c, 0x19, 0xba, 0xcf, 0x86, 0x47, 0x85, 0xa0, 0x0b, 0xc2, 0xec, 0xff, 0x15, 0xd3, + 0x50, 0x87, 0x5b, 0x24, 0x6e, 0xd5, 0x3e, 0x68, 0xbe, 0x6f, 0x55, 0xbd, 0x7e, 0x05, 0xcf, 0xc2, 0xb2, 0xed, 0x64, 0x32, 0x19, 0x8a, 0x64, 0x44, 0xb6, 0xd8, 0xc2, 0x47, 0xfa, 0xb9, 0x41, 0xf5, + 0x69, 0x76, 0x8b, 0x5c, 0x42, 0x93, 0x66, 0xf1, 0xd3, 0xf0, 0x0f, 0x03, 0x45, 0xb9, 0x61, 0x23, 0xd5, 0x62, 0x04, 0xc0, 0x1c, 0x63, 0xb2, 0x2c, 0xe7, 0x8b, 0xaf, 0x11, 0x6e, 0x52, 0x5e, 0xd9, + 0x0f, 0xde, 0xa3, 0x9f, 0xa4, 0x69, 0x49, 0x4d, 0x38, 0x66, 0xc3, 0x1e, 0x05, 0xf2, 0x95, 0xff, 0x21, 0xfe, 0xa8, 0xd4, 0xe6, 0xe1, 0x3d, 0x67, 0xe4, 0x7c, 0xe7, 0x22, 0xe9, 0x69, 0x8a, 0x1c, + 0x10, 0x48, 0xd6, 0x8e, 0xbc, 0xde, 0x76, 0xb8, 0x6f, 0xcf, 0x97, 0x6e, 0xab, 0x8a, 0xa9, 0x79, 0x02, 0x68, 0xb7, 0x06, 0x8e, 0x01, 0x7a, 0x8b, 0x9b, 0x74, 0x94, 0x09, 0x51, 0x4f, 0x10, 0x53, + 0x02, 0x7f, 0xd1, 0x6c, 0x37, 0x86, 0xea, 0x1b, 0xac, 0x5f, 0x15, 0xcb, 0x79, 0x71, 0x1e, 0xe2, 0xab, 0xe8, 0x2f, 0x5c, 0xf8, 0xb1, 0x3a, 0xe7, 0x30, 0x30, 0xef, 0x5b, 0x9e, 0x44, 0x57, 0xe7, + 0x5d, 0x13, 0x04, 0xf9, 0x88, 0xd6, 0x2d, 0xd6, 0xfc, 0x4b, 0x94, 0xed, 0x38, 0xba, 0x83, 0x1d, 0xa4, 0xb7, 0x63, 0x49, 0x71, 0xb6, 0xcd, 0x8e, 0xc3, 0x25, 0xd9, 0xc6, 0x1c, 0x00, 0xf1, 0xdf, + 0x73, 0x62, 0x7e, 0xd3, 0x74, 0x5a, 0x5e, 0x84, 0x89, 0xf3, 0xa9, 0x5c, 0x69, 0x63, 0x9c, 0x32, 0xcd, 0x6e, 0x1d, 0x53, 0x7a, 0x85, 0xf7, 0x5c, 0xc8, 0x44, 0x72, 0x6e, 0x8a, 0x72, 0xfc, 0x00, + 0x77, 0xad, 0x22, 0x00, 0x0f, 0x1d, 0x50, 0x78, 0xf6, 0xb8, 0x66, 0x31, 0x8c, 0x66, 0x8f, 0x1a, 0xd0, 0x3d, 0x5a, 0x5f, 0xce, 0xd5, 0x21, 0x9f, 0x2e, 0xab, 0xbd, 0x0a, 0xa5, 0xc0, 0xf4, 0x60, + 0xd1, 0x83, 0xf0, 0x44, 0x04, 0xa0, 0xd6, 0xf4, 0x69, 0x55, 0x8e, 0x81, 0xfa, 0xb2, 0x4a, 0x16, 0x79, 0x05, 0xab, 0x4c, 0x78, 0x78, 0x50, 0x2a, 0xd3, 0xe3, 0x8f, 0xdb, 0xe6, 0x2a, 0x41, 0x55, + 0x6c, 0xec, 0x37, 0x32, 0x57, 0x59, 0x53, 0x3c, 0xe8, 0xf2, 0x5f, 0x36, 0x7c, 0x87, 0xbb, 0x55, 0x78, 0xd6, 0x67, 0xae, 0x93, 0xf9, 0xe2, 0xfd, 0x99, 0xbc, 0xbc, 0x5f, 0x2f, 0xbb, 0xa8, 0x8c, + 0xf6, 0x51, 0x61, 0x39, 0x42, 0x0f, 0xcf, 0xf3, 0xb7, 0x36, 0x1d, 0x86, 0x32, 0x2c, 0x4b, 0xd8, 0x4c, 0x82, 0xf3, 0x35, 0xab, 0xb1, 0x52, 0xc4, 0xa9, 0x34, 0x11, 0x37, 0x3a, 0xaa, 0x82, 0x20 + } +}, +{ + // IEEE 1619 - Vector 14 + + /* This vector must always be the last one in XTS_vectors[] because TestSectorBufEncryption() relies on it. */ + + { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, + { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, + { 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff }, + 0, + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + }, + { + 0x64, 0x49, 0x7e, 0x5a, 0x83, 0x1e, 0x4a, 0x93, 0x2c, 0x09, 0xbe, 0x3e, 0x53, 0x93, 0x37, 0x6d, 0xaa, 0x59, 0x95, 0x48, 0xb8, 0x16, 0x03, 0x1d, 0x22, 0x4b, 0xbf, 0x50, 0xa8, 0x18, 0xed, 0x23, + 0x50, 0xea, 0xe7, 0xe9, 0x60, 0x87, 0xc8, 0xa0, 0xdb, 0x51, 0xad, 0x29, 0x0b, 0xd0, 0x0c, 0x1a, 0xc1, 0x62, 0x08, 0x57, 0x63, 0x5b, 0xf2, 0x46, 0xc1, 0x76, 0xab, 0x46, 0x3b, 0xe3, 0x0b, 0x80, + 0x8d, 0xa5, 0x48, 0x08, 0x1a, 0xc8, 0x47, 0xb1, 0x58, 0xe1, 0x26, 0x4b, 0xe2, 0x5b, 0xb0, 0x91, 0x0b, 0xbc, 0x92, 0x64, 0x71, 0x08, 0x08, 0x94, 0x15, 0xd4, 0x5f, 0xab, 0x1b, 0x3d, 0x26, 0x04, + 0xe8, 0xa8, 0xef, 0xf1, 0xae, 0x40, 0x20, 0xcf, 0xa3, 0x99, 0x36, 0xb6, 0x68, 0x27, 0xb2, 0x3f, 0x37, 0x1b, 0x92, 0x20, 0x0b, 0xe9, 0x02, 0x51, 0xe6, 0xd7, 0x3c, 0x5f, 0x86, 0xde, 0x5f, 0xd4, + 0xa9, 0x50, 0x78, 0x19, 0x33, 0xd7, 0x9a, 0x28, 0x27, 0x2b, 0x78, 0x2a, 0x2e, 0xc3, 0x13, 0xef, 0xdf, 0xcc, 0x06, 0x28, 0xf4, 0x3d, 0x74, 0x4c, 0x2d, 0xc2, 0xff, 0x3d, 0xcb, 0x66, 0x99, 0x9b, + 0x50, 0xc7, 0xca, 0x89, 0x5b, 0x0c, 0x64, 0x79, 0x1e, 0xea, 0xa5, 0xf2, 0x94, 0x99, 0xfb, 0x1c, 0x02, 0x6f, 0x84, 0xce, 0x5b, 0x5c, 0x72, 0xba, 0x10, 0x83, 0xcd, 0xdb, 0x5c, 0xe4, 0x54, 0x34, + 0x63, 0x16, 0x65, 0xc3, 0x33, 0xb6, 0x0b, 0x11, 0x59, 0x3f, 0xb2, 0x53, 0xc5, 0x17, 0x9a, 0x2c, 0x8d, 0xb8, 0x13, 0x78, 0x2a, 0x00, 0x48, 0x56, 0xa1, 0x65, 0x30, 0x11, 0xe9, 0x3f, 0xb6, 0xd8, + 0x76, 0xc1, 0x83, 0x66, 0xdd, 0x86, 0x83, 0xf5, 0x34, 0x12, 0xc0, 0xc1, 0x80, 0xf9, 0xc8, 0x48, 0x59, 0x2d, 0x59, 0x3f, 0x86, 0x09, 0xca, 0x73, 0x63, 0x17, 0xd3, 0x56, 0xe1, 0x3e, 0x2b, 0xff, + 0x3a, 0x9f, 0x59, 0xcd, 0x9a, 0xeb, 0x19, 0xcd, 0x48, 0x25, 0x93, 0xd8, 0xc4, 0x61, 0x28, 0xbb, 0x32, 0x42, 0x3b, 0x37, 0xa9, 0xad, 0xfb, 0x48, 0x2b, 0x99, 0x45, 0x3f, 0xbe, 0x25, 0xa4, 0x1b, + 0xf6, 0xfe, 0xb4, 0xaa, 0x0b, 0xef, 0x5e, 0xd2, 0x4b, 0xf7, 0x3c, 0x76, 0x29, 0x78, 0x02, 0x54, 0x82, 0xc1, 0x31, 0x15, 0xe4, 0x01, 0x5a, 0xac, 0x99, 0x2e, 0x56, 0x13, 0xa3, 0xb5, 0xc2, 0xf6, + 0x85, 0xb8, 0x47, 0x95, 0xcb, 0x6e, 0x9b, 0x26, 0x56, 0xd8, 0xc8, 0x81, 0x57, 0xe5, 0x2c, 0x42, 0xf9, 0x78, 0xd8, 0x63, 0x4c, 0x43, 0xd0, 0x6f, 0xea, 0x92, 0x8f, 0x28, 0x22, 0xe4, 0x65, 0xaa, + 0x65, 0x76, 0xe9, 0xbf, 0x41, 0x93, 0x84, 0x50, 0x6c, 0xc3, 0xce, 0x3c, 0x54, 0xac, 0x1a, 0x6f, 0x67, 0xdc, 0x66, 0xf3, 0xb3, 0x01, 0x91, 0xe6, 0x98, 0x38, 0x0b, 0xc9, 0x99, 0xb0, 0x5a, 0xbc, + 0xe1, 0x9d, 0xc0, 0xc6, 0xdc, 0xc2, 0xdd, 0x00, 0x1e, 0xc5, 0x35, 0xba, 0x18, 0xde, 0xb2, 0xdf, 0x1a, 0x10, 0x10, 0x23, 0x10, 0x83, 0x18, 0xc7, 0x5d, 0xc9, 0x86, 0x11, 0xa0, 0x9d, 0xc4, 0x8a, + 0x0a, 0xcd, 0xec, 0x67, 0x6f, 0xab, 0xdf, 0x22, 0x2f, 0x07, 0xe0, 0x26, 0xf0, 0x59, 0xb6, 0x72, 0xb5, 0x6e, 0x5c, 0xbc, 0x8e, 0x1d, 0x21, 0xbb, 0xd8, 0x67, 0xdd, 0x92, 0x72, 0x12, 0x05, 0x46, + 0x81, 0xd7, 0x0e, 0xa7, 0x37, 0x13, 0x4c, 0xdf, 0xce, 0x93, 0xb6, 0xf8, 0x2a, 0xe2, 0x24, 0x23, 0x27, 0x4e, 0x58, 0xa0, 0x82, 0x1c, 0xc5, 0x50, 0x2e, 0x2d, 0x0a, 0xb4, 0x58, 0x5e, 0x94, 0xde, + 0x69, 0x75, 0xbe, 0x5e, 0x0b, 0x4e, 0xfc, 0xe5, 0x1c, 0xd3, 0xe7, 0x0c, 0x25, 0xa1, 0xfb, 0xbb, 0xd6, 0x09, 0xd2, 0x73, 0xad, 0x5b, 0x0d, 0x59, 0x63, 0x1c, 0x53, 0x1f, 0x6a, 0x0a, 0x57, 0xb9 + } +} }; // XTS_TEST XTS_vectors[] + + +BOOL XTSAesTest (PCRYPTO_INFO ci) +{ + unsigned __int8 p[ENCRYPTION_DATA_UNIT_SIZE]; + UINT64_STRUCT dataUnitNo; + int i; + + for (i = 0; i < XTS_TEST_COUNT; i++) + { + ci->ea = EAGetByName (L"AES"); + if (ci->ea == 0) + return FALSE; + + ci->mode = XTS; + + if (EAInit (ci->ea, XTS_vectors[i].key1, ci->ks) != ERR_SUCCESS) + return FALSE; + + memcpy (&ci->k2, XTS_vectors[i].key2, sizeof (XTS_vectors[i].key2)); + + if (!EAInitMode (ci)) + return FALSE; + + memcpy (p, XTS_vectors[i].plaintext, sizeof (p)); + + dataUnitNo.Value = BE64 (*((unsigned __int64 *) XTS_vectors[i].dataUnitNo)); + + EncryptBufferXTS (p, sizeof (p), &dataUnitNo, XTS_vectors[i].blockNo, (unsigned char *) (ci->ks), (unsigned char *) ci->ks2, AES); + + if (memcmp (XTS_vectors[i].ciphertext, p, sizeof (p)) != 0) + return FALSE; + } + + return TRUE; +} + + +// AES ECB test vectors FIPS-197 + +#define AES_TEST_COUNT 1 + +typedef struct { + unsigned char key[32]; + unsigned char plaintext[16]; + unsigned char ciphertext[16]; + } AES_TEST; + +AES_TEST aes_ecb_vectors[AES_TEST_COUNT] = { +0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f, +0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f, + +0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff, + +0x8e,0xa2,0xb7,0xca,0x51,0x67,0x45,0xbf,0xea,0xfc,0x49,0x90,0x4b,0x49,0x60,0x89 +}; + +// Serpent ECB test vectors + +#define SERPENT_TEST_COUNT 1 + +typedef struct { + unsigned char key[32]; + unsigned char plaintext[16]; + unsigned char ciphertext[16]; + } SERPENT_TEST; + +SERPENT_TEST serpent_vectors[SERPENT_TEST_COUNT] = { +0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, +0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + +0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, +0xde, 0x26, 0x9f, 0xf8, 0x33, 0xe4, 0x32, 0xb8, 0x5b, 0x2e, 0x88, 0xd2, 0x70, 0x1c, 0xe7, 0x5c +}; + +// Twofish ECB test vectors + +#define TWOFISH_TEST_COUNT 1 + +typedef struct { + unsigned char key[32]; + unsigned char plaintext[16]; + unsigned char ciphertext[16]; + } TWOFISH_TEST; + +TWOFISH_TEST twofish_vectors[TWOFISH_TEST_COUNT] = { +0xD4, 0x3B, 0xB7, 0x55, 0x6E, 0xA3, 0x2E, 0x46, 0xF2, 0xA2, 0x82, 0xB7, 0xD4, 0x5B, 0x4E, 0x0D, +0x57, 0xFF, 0x73, 0x9D, 0x4D, 0xC9, 0x2C, 0x1B, 0xD7, 0xFC, 0x01, 0x70, 0x0C, 0xC8, 0x21, 0x6F, + +0x90, 0xAF, 0xE9, 0x1B, 0xB2, 0x88, 0x54, 0x4F, 0x2C, 0x32, 0xDC, 0x23, 0x9B, 0x26, 0x35, 0xE6, +0x6C, 0xB4, 0x56, 0x1C, 0x40, 0xBF, 0x0A, 0x97, 0x05, 0x93, 0x1C, 0xB6, 0xD4, 0x08, 0xE7, 0xFA +}; + +/* Test vectors from FIPS 198a, RFC 4231, RFC 2104, RFC 2202, and other sources. */ + +char *hmac_sha256_test_keys[] = +{ + "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b", + "Jefe", + "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", + "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", + "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", + "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", +}; + +char *hmac_sha256_test_data[] = +{ + "Hi There", + "what do ya want for nothing?", + "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd", + "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd", + "Test Using Larger Than Block-Size Key - Hash Key First", + "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.", +}; + +char *hmac_sha256_test_vectors[] = +{ + "\xb0\x34\x4c\x61\xd8\xdb\x38\x53\x5c\xa8\xaf\xce\xaf\x0b\xf1\x2b\x88\x1d\xc2\x00\xc9\x83\x3d\xa7\x26\xe9\x37\x6c\x2e\x32\xcf\xf7", + "\x5b\xdc\xc1\x46\xbf\x60\x75\x4e\x6a\x04\x24\x26\x08\x95\x75\xc7\x5a\x00\x3f\x08\x9d\x27\x39\x83\x9d\xec\x58\xb9\x64\xec\x38\x43", + "\x77\x3e\xa9\x1e\x36\x80\x0e\x46\x85\x4d\xb8\xeb\xd0\x91\x81\xa7\x29\x59\x09\x8b\x3e\xf8\xc1\x22\xd9\x63\x55\x14\xce\xd5\x65\xfe", + "\x82\x55\x8a\x38\x9a\x44\x3c\x0e\xa4\xcc\x81\x98\x99\xf2\x08\x3a\x85\xf0\xfa\xa3\xe5\x78\xf8\x07\x7a\x2e\x3f\xf4\x67\x29\x66\x5b", + "\x60\xe4\x31\x59\x1e\xe0\xb6\x7f\x0d\x8a\x26\xaa\xcb\xf5\xb7\x7f\x8e\x0b\xc6\x21\x37\x28\xc5\x14\x05\x46\x04\x0f\x0e\xe3\x7f\x54", + "\x9b\x09\xff\xa7\x1b\x94\x2f\xcb\x27\x63\x5f\xbc\xd5\xb0\xe9\x44\xbf\xdc\x63\x64\x4f\x07\x13\x93\x8a\x7f\x51\x53\x5c\x3a\x35\xe2", +}; + +char *hmac_sha512_test_keys[] = +{ + "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b", + "Jefe", + "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", + "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", + "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", + "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", +}; + +char *hmac_sha512_test_data[] = +{ + "Hi There", + "what do ya want for nothing?", + "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd", + "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd", + "Test Using Larger Than Block-Size Key - Hash Key First", + "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.", +}; + +char *hmac_sha512_test_vectors[] = +{ + "\x87\xaa\x7c\xde\xa5\xef\x61\x9d\x4f\xf0\xb4\x24\x1a\x1d\x6c\xb0\x23\x79\xf4\xe2\xce\x4e\xc2\x78\x7a\xd0\xb3\x05\x45\xe1\x7c\xde\xda\xa8\x33\xb7\xd6\xb8\xa7\x02\x03\x8b\x27\x4e\xae\xa3\xf4\xe4\xbe\x9d\x91\x4e\xeb\x61\xf1\x70\x2e\x69\x6c\x20\x3a\x12\x68\x54", + "\x16\x4b\x7a\x7b\xfc\xf8\x19\xe2\xe3\x95\xfb\xe7\x3b\x56\xe0\xa3\x87\xbd\x64\x22\x2e\x83\x1f\xd6\x10\x27\x0c\xd7\xea\x25\x05\x54\x97\x58\xbf\x75\xc0\x5a\x99\x4a\x6d\x03\x4f\x65\xf8\xf0\xe6\xfd\xca\xea\xb1\xa3\x4d\x4a\x6b\x4b\x63\x6e\x07\x0a\x38\xbc\xe7\x37", + "\xfa\x73\xb0\x08\x9d\x56\xa2\x84\xef\xb0\xf0\x75\x6c\x89\x0b\xe9\xb1\xb5\xdb\xdd\x8e\xe8\x1a\x36\x55\xf8\x3e\x33\xb2\x27\x9d\x39\xbf\x3e\x84\x82\x79\xa7\x22\xc8\x06\xb4\x85\xa4\x7e\x67\xc8\x07\xb9\x46\xa3\x37\xbe\xe8\x94\x26\x74\x27\x88\x59\xe1\x32\x92\xfb", + "\xb0\xba\x46\x56\x37\x45\x8c\x69\x90\xe5\xa8\xc5\xf6\x1d\x4a\xf7\xe5\x76\xd9\x7f\xf9\x4b\x87\x2d\xe7\x6f\x80\x50\x36\x1e\xe3\xdb\xa9\x1c\xa5\xc1\x1a\xa2\x5e\xb4\xd6\x79\x27\x5c\xc5\x78\x80\x63\xa5\xf1\x97\x41\x12\x0c\x4f\x2d\xe2\xad\xeb\xeb\x10\xa2\x98\xdd", + "\x80\xb2\x42\x63\xc7\xc1\xa3\xeb\xb7\x14\x93\xc1\xdd\x7b\xe8\xb4\x9b\x46\xd1\xf4\x1b\x4a\xee\xc1\x12\x1b\x01\x37\x83\xf8\xf3\x52\x6b\x56\xd0\x37\xe0\x5f\x25\x98\xbd\x0f\xd2\x21\x5d\x6a\x1e\x52\x95\xe6\x4f\x73\xf6\x3f\x0a\xec\x8b\x91\x5a\x98\x5d\x78\x65\x98", + "\xe3\x7b\x6a\x77\x5d\xc8\x7d\xba\xa4\xdf\xa9\xf9\x6e\x5e\x3f\xfd\xde\xbd\x71\xf8\x86\x72\x89\x86\x5d\xf5\xa3\x2d\x20\xcd\xc9\x44\xb6\x02\x2c\xac\x3c\x49\x82\xb1\x0d\x5e\xeb\x55\xc3\xe4\xde\x15\x13\x46\x76\xfb\x6d\xe0\x44\x60\x65\xc9\x74\x40\xfa\x8c\x6a\x58", +}; + +char *hmac_ripemd160_test_keys[] = +{ + "\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff\x01\x23\x45\x67", + "\x01\x23\x45\x67\x89\xab\xcd\xef\xfe\xdc\xba\x98\x76\x54\x32\x10\x00\x11\x22\x33", +}; + +char *hmac_ripemd160_test_data[] = +{ + "message digest", + "12345678901234567890123456789012345678901234567890123456789012345678901234567890", +}; + +char *hmac_ripemd160_test_vectors[] = +{ + "\xf8\x36\x62\xcc\x8d\x33\x9c\x22\x7e\x60\x0f\xcd\x63\x6c\x57\xd2\x57\x1b\x1c\x34", + "\x85\xf1\x64\x70\x3e\x61\xa6\x31\x31\xbe\x7e\x45\x95\x8e\x07\x94\x12\x39\x04\xf9", +}; + +char *hmac_whirlpool_test_key = +{ + "\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF\x01\x23\x45\x67\x89\xAB\xCD\xEF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF\x01\x23\x45\x67\x89\xAB\xCD\xEF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF" +}; + +char *hmac_whirlpool_test_data = +{ + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" +}; + +char *hmac_whirlpool_test_vectors = +{ + "\x03\x91\xd2\x80\x00\xb6\x62\xbb\xb8\xe6\x23\x3e\xe8\x6c\xf2\xb2\x84\x74\x4c\x73" + "\x8b\x58\x00\xba\x28\x12\xed\x52\x6f\xe3\x15\x3a\xb1\xba\xe7\xe2\x36\xbe\x96\x54" + "\x49\x3f\x19\xfa\xce\xa6\x44\x1f\x60\xf5\xf0\x18\x93\x09\x11\xa5\xe5\xce\xd8\xf2" + "\x6a\xbf\xa4\x02" +}; + +unsigned char ks_tmp[MAX_EXPANDED_KEY]; + +void CipherInit2(int cipher, void* key, void* ks, int key_len) +{ + switch (cipher) + { + + case AES: + CipherInit(cipher,key,ks); + break; + + case SERPENT: + CipherInit(cipher,key,ks); + break; + + case TWOFISH: + CipherInit(cipher,key,ks); + break; + + default: + /* Unknown/wrong ID */ + TC_THROW_FATAL_EXCEPTION; + } +} + + +BOOL TestSectorBufEncryption (PCRYPTO_INFO ci) +{ + unsigned char buf [ENCRYPTION_DATA_UNIT_SIZE * 4]; + unsigned int i; + wchar_t name[64]; + unsigned __int32 crc; + UINT64_STRUCT unitNo; + uint32 nbrUnits; + unsigned __int64 writeOffset; + int testCase = 0; + int nTestsPerformed = 0; + + static unsigned char key1[] = + { + 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27, + 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92, + 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13 + }; + + + /* Encryption/decryption of data units (typically, volume data sectors) */ + + nbrUnits = sizeof (buf) / ENCRYPTION_DATA_UNIT_SIZE; + + ci->mode = XTS; // we only implement XTS + + /* The buffer can accommodate 4 data units and we'll test 4 cases by "scrolling". The data unit 0xFFFFFFFFFF + will "move" from the start of the buffer to its end. For a 512-byte data unit, the byte offset 562949953420800 + corresponds to the data unit 0xFFFFFFFFFF. */ + for (writeOffset = 562949953420800ULL; + writeOffset > 562949953420800ULL - nbrUnits * ENCRYPTION_DATA_UNIT_SIZE; + writeOffset -= ENCRYPTION_DATA_UNIT_SIZE) + { + unitNo.Value = writeOffset / ENCRYPTION_DATA_UNIT_SIZE; + + // Test all EAs that support this mode of operation + for (ci->ea = EAGetFirst (); ci->ea != 0; ci->ea = EAGetNext (ci->ea)) + { + if (!EAIsModeSupported (ci->ea, ci->mode)) + continue; + + EAGetName (name, ci->ea, 0); + + if (EAInit (ci->ea, key1, ci->ks) != ERR_SUCCESS) + return FALSE; + + for (i = 0; i < sizeof (ci->k2); i++) + ci->k2[i] = (unsigned char) i; + + memcpy (&ci->k2, XTS_vectors[XTS_TEST_COUNT-1].key2, sizeof (XTS_vectors[XTS_TEST_COUNT-1].key2)); + + if (!EAInitMode (ci)) + return FALSE; + + // Each data unit will contain the same plaintext + for (i = 0; i < nbrUnits; i++) + { + memcpy ((unsigned char *) buf + i * ENCRYPTION_DATA_UNIT_SIZE, + XTS_vectors[XTS_TEST_COUNT-1].plaintext, + ENCRYPTION_DATA_UNIT_SIZE); + } + + EncryptDataUnits (buf, &unitNo, nbrUnits, ci); + + crc = GetCrc32 (buf, sizeof (buf)); + + if (wcscmp (name, L"AES") == 0) + { + // Verify the ciphertext of the "moving" data unit using the IEEE test vector #14 + if (memcmp (XTS_vectors[XTS_TEST_COUNT-1].ciphertext, + (unsigned char *) buf + testCase * ENCRYPTION_DATA_UNIT_SIZE, + ENCRYPTION_DATA_UNIT_SIZE) != 0) + { + return FALSE; + } + + // CRC of all data units in the buffer for each test case + switch (testCase) + { + case 0: + if (crc != 0x888f2990) + return FALSE; + nTestsPerformed++; + break; + case 1: + if (crc != 0xea28ea34) + return FALSE; + nTestsPerformed++; + break; + case 2: + if (crc != 0xe058f5a2) + return FALSE; + nTestsPerformed++; + break; + case 3: + if (crc != 0x10473dc9) + return FALSE; + nTestsPerformed++; + break; + } + } + else if (wcscmp (name, L"Serpent") == 0) + { + switch (testCase) + { + case 0: + if (crc != 0x7edfecb3) + return FALSE; + nTestsPerformed++; + break; + case 1: + if (crc != 0x357baaaa) + return FALSE; + nTestsPerformed++; + break; + case 2: + if (crc != 0xc7b9fca5) + return FALSE; + nTestsPerformed++; + break; + case 3: + if (crc != 0xb5263e0c) + return FALSE; + nTestsPerformed++; + break; + } + } + else if (wcscmp (name, L"Twofish") == 0) + { + switch (testCase) + { + case 0: + if (crc != 0x91525124) + return FALSE; + nTestsPerformed++; + break; + case 1: + if (crc != 0x2895cc47) + return FALSE; + nTestsPerformed++; + break; + case 2: + if (crc != 0x6bee346d) + return FALSE; + nTestsPerformed++; + break; + case 3: + if (crc != 0xb1c45759) + return FALSE; + nTestsPerformed++; + break; + } + } + else if (wcscmp (name, L"AES-Twofish") == 0) + { + switch (testCase) + { + case 0: + if (crc != 0x6cea7fa2) + return FALSE; + nTestsPerformed++; + break; + case 1: + if (crc != 0x69052c4c) + return FALSE; + nTestsPerformed++; + break; + case 2: + if (crc != 0x88db8de5) + return FALSE; + nTestsPerformed++; + break; + case 3: + if (crc != 0xf16fd8c5) + return FALSE; + nTestsPerformed++; + break; + } + } + else if (wcscmp (name, L"AES-Twofish-Serpent") == 0) + { + switch (testCase) + { + case 0: + if (crc != 0xa2d7d82a) + return FALSE; + nTestsPerformed++; + break; + case 1: + if (crc != 0xdbf76412) + return FALSE; + nTestsPerformed++; + break; + case 2: + if (crc != 0xdf0ea03e) + return FALSE; + nTestsPerformed++; + break; + case 3: + if (crc != 0xdadedff7) + return FALSE; + nTestsPerformed++; + break; + } + } + else if (wcscmp (name, L"Serpent-AES") == 0) + { + switch (testCase) + { + case 0: + if (crc != 0x6dd133b3) + return FALSE; + nTestsPerformed++; + break; + case 1: + if (crc != 0x0e5717d2) + return FALSE; + nTestsPerformed++; + break; + case 2: + if (crc != 0x39f83cd9) + return FALSE; + nTestsPerformed++; + break; + case 3: + if (crc != 0x8a79fa2c) + return FALSE; + nTestsPerformed++; + break; + } + } + else if (wcscmp (name, L"Serpent-Twofish-AES") == 0) + { + switch (testCase) + { + case 0: + if (crc != 0xe536daf8) + return FALSE; + nTestsPerformed++; + break; + case 1: + if (crc != 0x3ae89e7f) + return FALSE; + nTestsPerformed++; + break; + case 2: + if (crc != 0x2cc1301a) + return FALSE; + nTestsPerformed++; + break; + case 3: + if (crc != 0xcac7bdc7) + return FALSE; + nTestsPerformed++; + break; + } + } + else if (wcscmp (name, L"Twofish-Serpent") == 0) + { + switch (testCase) + { + case 0: + if (crc != 0x2686c859) + return FALSE; + nTestsPerformed++; + break; + case 1: + if (crc != 0x8a201780) + return FALSE; + nTestsPerformed++; + break; + case 2: + if (crc != 0x8dd13796) + return FALSE; + nTestsPerformed++; + break; + case 3: + if (crc != 0xe95196cb) + return FALSE; + nTestsPerformed++; + break; + } + } + + if (crc == 0x9f5edd58) + return FALSE; + + DecryptDataUnits (buf, &unitNo, nbrUnits, ci); + + if (GetCrc32 (buf, sizeof (buf)) != 0x9f5edd58) + return FALSE; + + nTestsPerformed++; + } + testCase++; + } + + /* Encryption/decryption of a buffer (typically, a volume header) */ + + nbrUnits = sizeof (buf) / ENCRYPTION_DATA_UNIT_SIZE; + + // Test all EAs that support this mode of operation + for (ci->ea = EAGetFirst (); ci->ea != 0; ci->ea = EAGetNext (ci->ea)) + { + if (!EAIsModeSupported (ci->ea, ci->mode)) + continue; + + EAGetName (name, ci->ea, 0); + + if (EAInit (ci->ea, key1, ci->ks) != ERR_SUCCESS) + return FALSE; + + memcpy (&ci->k2, XTS_vectors[XTS_TEST_COUNT-1].key2, sizeof (XTS_vectors[XTS_TEST_COUNT-1].key2)); + + if (!EAInitMode (ci)) + return FALSE; + + // Each data unit will contain the same plaintext + for (i = 0; i < nbrUnits; i++) + { + memcpy ((unsigned char *) buf + i * ENCRYPTION_DATA_UNIT_SIZE, + XTS_vectors[XTS_TEST_COUNT-1].plaintext, + ENCRYPTION_DATA_UNIT_SIZE); + } + + EncryptBuffer (buf, sizeof (buf), ci); + + crc = GetCrc32 (buf, sizeof (buf)); + + if (wcscmp (name, L"AES") == 0) + { + if (crc != 0x33b91fab) + return FALSE; + nTestsPerformed++; + } + else if (wcscmp (name, L"Serpent") == 0) + { + if (crc != 0x3494d480) + return FALSE; + nTestsPerformed++; + } + else if (wcscmp (name, L"Twofish") == 0) + { + if (crc != 0xc4d65b46) + return FALSE; + nTestsPerformed++; + } + else if (wcscmp (name, L"AES-Twofish") == 0) + { + if (crc != 0x14ce7385) + return FALSE; + nTestsPerformed++; + } + else if (wcscmp (name, L"AES-Twofish-Serpent") == 0) + { + if (crc != 0x0ec81bf7) + return FALSE; + nTestsPerformed++; + } + else if (wcscmp (name, L"Serpent-AES") == 0) + { + if (crc != 0x42f919ad) + return FALSE; + nTestsPerformed++; + } + else if (wcscmp (name, L"Serpent-Twofish-AES") == 0) + { + if (crc != 0x208d5c58) + return FALSE; + nTestsPerformed++; + } + else if (wcscmp (name, L"Twofish-Serpent") == 0) + { + if (crc != 0xbe78cec1) + return FALSE; + nTestsPerformed++; + } + + if (crc == 0x9f5edd58) + return FALSE; + + DecryptBuffer (buf, sizeof (buf), ci); + + if (GetCrc32 (buf, sizeof (buf)) != 0x9f5edd58) + return FALSE; + + nTestsPerformed++; + } + + return (nTestsPerformed == 80); +} + +static BOOL DoAutoTestAlgorithms (void) +{ + PCRYPTO_INFO ci; + char key[32]; + unsigned char tmp[16]; + BOOL bFailed = FALSE; + int i; + + ci = crypto_open (); + if (!ci) + return FALSE; + + memset (ci, 0, sizeof (*ci)); + + /* AES */ + + for (i = 0; i < AES_TEST_COUNT; i++) + { + int cipher = AES; + memcpy(key, aes_ecb_vectors[i].key, 32); + memcpy(tmp, aes_ecb_vectors[i].plaintext, 16); + CipherInit(cipher, key, ks_tmp); + + EncipherBlock(cipher, tmp, ks_tmp); + if (memcmp(aes_ecb_vectors[i].ciphertext, tmp, 16) != 0) + break; + + DecipherBlock(cipher, tmp, ks_tmp); + if (memcmp(aes_ecb_vectors[i].plaintext, tmp, 16) != 0) + break; + } + if (i != AES_TEST_COUNT) + bFailed = TRUE; + + // AES EncipherBlocks()/DecipherBlocks() + { + byte testData[1024]; + uint32 origCrc; + size_t i; + + for (i = 0; i < sizeof (testData); ++i) + { + testData[i] = (byte) i; + } + + origCrc = GetCrc32 (testData, sizeof (testData)); + + CipherInit (AES, testData, ks_tmp); + EncipherBlocks (AES, testData, ks_tmp, sizeof (testData) / CipherGetBlockSize (AES)); + + if (GetCrc32 (testData, sizeof (testData)) != 0xb5cd5631) + bFailed = TRUE; + + DecipherBlocks (AES, testData, ks_tmp, sizeof (testData) / CipherGetBlockSize (AES)); + + if (origCrc != GetCrc32 (testData, sizeof (testData))) + bFailed = TRUE; + } + + /* Serpent */ + + for (i = 0; i < SERPENT_TEST_COUNT; i++) + { + int cipher = SERPENT; + memcpy(key, serpent_vectors[i].key, 32); + memcpy(tmp, serpent_vectors[i].plaintext, 16); + CipherInit(cipher, key, ks_tmp); + + EncipherBlock(cipher, tmp, ks_tmp); + if (memcmp(serpent_vectors[i].ciphertext, tmp, 16) != 0) + break; + + DecipherBlock(cipher, tmp, ks_tmp); + if (memcmp(serpent_vectors[i].plaintext, tmp, 16) != 0) + break; + } + if (i != SERPENT_TEST_COUNT) + bFailed = TRUE; + + + /* Twofish */ + + for (i = 0; i < TWOFISH_TEST_COUNT; i++) + { + int cipher = TWOFISH; + memcpy(key, twofish_vectors[i].key, 32); + memcpy(tmp, twofish_vectors[i].plaintext, 16); + CipherInit(cipher, key, ks_tmp); + + EncipherBlock(cipher, tmp, ks_tmp); + if (memcmp(twofish_vectors[i].ciphertext, tmp, 16) != 0) + break; + + DecipherBlock(cipher, tmp, ks_tmp); + if (memcmp(twofish_vectors[i].plaintext, tmp, 16) != 0) + break; + } + if (i != TWOFISH_TEST_COUNT) + bFailed = TRUE; + + + /* PKCS #5 and HMACs */ + if (!test_pkcs5 ()) + bFailed = TRUE; + + /* CRC-32 */ + if (!crc32_selftests ()) + bFailed = TRUE; + + /* GF multiplicator */ +#if 0 + if (!GfMulSelfTest ()) + bFailed = TRUE; +#endif + + /* XTS-AES */ + if (!XTSAesTest (ci)) + bFailed = TRUE; + + /* Sector and buffer related algorithms */ + if (!TestSectorBufEncryption (ci)) + bFailed = TRUE; + + crypto_close (ci); + return !bFailed; +} + + +BOOL AutoTestAlgorithms (void) +{ + BOOL result = TRUE; + BOOL hwEncryptionEnabled = IsHwEncryptionEnabled(); + + EnableHwEncryption (FALSE); + + if (!DoAutoTestAlgorithms()) + result = FALSE; + + EnableHwEncryption (TRUE); + + if (!DoAutoTestAlgorithms()) + result = FALSE; + + EnableHwEncryption (hwEncryptionEnabled); + return result; +} + +BOOL test_hmac_sha256 () +{ + unsigned int i; + int nTestsPerformed = 0; + + for (i = 0; i < sizeof (hmac_sha256_test_data) / sizeof(char *); i++) + { + char digest[1024]; /* large enough to hold digets and test vector inputs */ + memcpy (digest, hmac_sha256_test_data[i], strlen (hmac_sha256_test_data[i])); + hmac_sha256 (hmac_sha256_test_keys[i], (int) strlen (hmac_sha256_test_keys[i]), digest, (int) strlen (hmac_sha256_test_data[i])); + if (memcmp (digest, hmac_sha256_test_vectors[i], SHA256_DIGESTSIZE) != 0) + return FALSE; + else + nTestsPerformed++; + } + + return (nTestsPerformed == 6); +} + +BOOL test_hmac_sha512 () +{ + unsigned int i; + int nTestsPerformed = 0; + + for (i = 0; i < sizeof (hmac_sha512_test_data) / sizeof(char *); i++) + { + char digest[1024]; /* large enough to hold digets and test vector inputs */ + memcpy (digest, hmac_sha512_test_data[i], (int) strlen (hmac_sha512_test_data[i])); + hmac_sha512 (hmac_sha512_test_keys[i], (int) strlen (hmac_sha512_test_keys[i]), digest, (int) strlen (hmac_sha512_test_data[i])); + if (memcmp (digest, hmac_sha512_test_vectors[i], SHA512_DIGESTSIZE) != 0) + return FALSE; + else + nTestsPerformed++; + } + + return (nTestsPerformed == 6); +} + +BOOL test_hmac_ripemd160 () +{ + int nTestsPerformed = 0; + unsigned int i; + + for (i = 0; i < sizeof (hmac_ripemd160_test_data) / sizeof(char *); i++) + { + char digest[1024]; /* large enough to hold digets and test vector inputs */ + memcpy (digest, hmac_ripemd160_test_data[i], strlen (hmac_ripemd160_test_data[i])); + hmac_ripemd160 (hmac_ripemd160_test_keys[i], RIPEMD160_DIGESTSIZE, digest, (int) strlen (hmac_ripemd160_test_data[i])); + if (memcmp (digest, hmac_ripemd160_test_vectors[i], RIPEMD160_DIGESTSIZE) != 0) + return FALSE; + else + nTestsPerformed++; + } + + return (nTestsPerformed == 2); +} + +BOOL test_hmac_whirlpool () +{ + unsigned char digest[1024]; /* large enough to hold digets and test vector inputs */ + + memcpy (digest, hmac_whirlpool_test_data, strlen (hmac_whirlpool_test_data)); + hmac_whirlpool (hmac_whirlpool_test_key, 64, digest, (int) strlen (hmac_whirlpool_test_data)); + if (memcmp (digest, hmac_whirlpool_test_vectors, WHIRLPOOL_DIGESTSIZE) != 0) + return FALSE; + + return TRUE; +} + +BOOL test_pkcs5 () +{ + char dk[144]; + + /* HMAC-SHA-256 tests */ + if (!test_hmac_sha256()) + return FALSE; + + /* HMAC-SHA-512 tests */ + if (!test_hmac_sha512()) + return FALSE; + + /* HMAC-RIPEMD-160 tests */ + if (test_hmac_ripemd160() == FALSE) + return FALSE; + + /* HMAC-Whirlpool tests */ + if (test_hmac_whirlpool() == FALSE) + return FALSE; + + /* PKCS-5 test 1 with HMAC-SHA-256 used as the PRF (https://tools.ietf.org/html/draft-josefsson-scrypt-kdf-00) */ + derive_key_sha256 ("passwd", 6, "\x73\x61\x6C\x74", 4, 1, dk, 64); + if (memcmp (dk, "\x55\xac\x04\x6e\x56\xe3\x08\x9f\xec\x16\x91\xc2\x25\x44\xb6\x05\xf9\x41\x85\x21\x6d\xde\x04\x65\xe6\x8b\x9d\x57\xc2\x0d\xac\xbc\x49\xca\x9c\xcc\xf1\x79\xb6\x45\x99\x16\x64\xb3\x9d\x77\xef\x31\x7c\x71\xb8\x45\xb1\xe3\x0b\xd5\x09\x11\x20\x41\xd3\xa1\x97\x83", 64) != 0) + return FALSE; + + /* PKCS-5 test 2 with HMAC-SHA-256 used as the PRF (https://stackoverflow.com/questions/5130513/pbkdf2-hmac-sha2-test-vectors) */ + derive_key_sha256 ("password", 8, "\x73\x61\x6C\x74", 4, 2, dk, 32); + if (memcmp (dk, "\xae\x4d\x0c\x95\xaf\x6b\x46\xd3\x2d\x0a\xdf\xf9\x28\xf0\x6d\xd0\x2a\x30\x3f\x8e\xf3\xc2\x51\xdf\xd6\xe2\xd8\x5a\x95\x47\x4c\x43", 32) != 0) + return FALSE; + + /* PKCS-5 test 3 with HMAC-SHA-256 used as the PRF (MS CryptoAPI) */ + derive_key_sha256 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); + if (memcmp (dk, "\xf2\xa0\x4f\xb2", 4) != 0) + return FALSE; + + /* PKCS-5 test 4 with HMAC-SHA-256 used as the PRF (MS CryptoAPI) */ + derive_key_sha256 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 144); + if (memcmp (dk, "\xf2\xa0\x4f\xb2\xd3\xe9\xa5\xd8\x51\x0b\x5c\x06\xdf\x70\x8e\x24\xe9\xc7\xd9\x15\x3d\x22\xcd\xde\xb8\xa6\xdb\xfd\x71\x85\xc6\x99\x32\xc0\xee\x37\x27\xf7\x24\xcf\xea\xa6\xac\x73\xa1\x4c\x4e\x52\x9b\x94\xf3\x54\x06\xfc\x04\x65\xa1\x0a\x24\xfe\xf0\x98\x1d\xa6\x22\x28\xeb\x24\x55\x74\xce\x6a\x3a\x28\xe2\x04\x3a\x59\x13\xec\x3f\xf2\xdb\xcf\x58\xdd\x53\xd9\xf9\x17\xf6\xda\x74\x06\x3c\x0b\x66\xf5\x0f\xf5\x58\xa3\x27\x52\x8c\x5b\x07\x91\xd0\x81\xeb\xb6\xbc\x30\x69\x42\x71\xf2\xd7\x18\x42\xbe\xe8\x02\x93\x70\x66\xad\x35\x65\xbc\xf7\x96\x8e\x64\xf1\xc6\x92\xda\xe0\xdc\x1f\xb5\xf4", 144) != 0) + return FALSE; + + /* PKCS-5 test 1 with HMAC-SHA-512 used as the PRF */ + derive_key_sha512 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); + if (memcmp (dk, "\x13\x64\xae\xf8", 4) != 0) + return FALSE; + + /* PKCS-5 test 2 with HMAC-SHA-512 used as the PRF (derives a key longer than the underlying + hash output size and block size) */ + derive_key_sha512 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 144); + if (memcmp (dk, "\x13\x64\xae\xf8\x0d\xf5\x57\x6c\x30\xd5\x71\x4c\xa7\x75\x3f\xfd\x00\xe5\x25\x8b\x39\xc7\x44\x7f\xce\x23\x3d\x08\x75\xe0\x2f\x48\xd6\x30\xd7\x00\xb6\x24\xdb\xe0\x5a\xd7\x47\xef\x52\xca\xa6\x34\x83\x47\xe5\xcb\xe9\x87\xf1\x20\x59\x6a\xe6\xa9\xcf\x51\x78\xc6\xb6\x23\xa6\x74\x0d\xe8\x91\xbe\x1a\xd0\x28\xcc\xce\x16\x98\x9a\xbe\xfb\xdc\x78\xc9\xe1\x7d\x72\x67\xce\xe1\x61\x56\x5f\x96\x68\xe6\xe1\xdd\xf4\xbf\x1b\x80\xe0\x19\x1c\xf4\xc4\xd3\xdd\xd5\xd5\x57\x2d\x83\xc7\xa3\x37\x87\xf4\x4e\xe0\xf6\xd8\x6d\x65\xdc\xa0\x52\xa3\x13\xbe\x81\xfc\x30\xbe\x7d\x69\x58\x34\xb6\xdd\x41\xc6", 144) != 0) + return FALSE; + + /* PKCS-5 test 1 with HMAC-RIPEMD-160 used as the PRF */ + derive_key_ripemd160 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); + if (memcmp (dk, "\x7a\x3d\x7c\x03", 4) != 0) + return FALSE; + + /* PKCS-5 test 2 with HMAC-RIPEMD-160 used as the PRF (derives a key longer than the underlying hash) */ + derive_key_ripemd160 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 48); + if (memcmp (dk, "\x7a\x3d\x7c\x03\xe7\x26\x6b\xf8\x3d\x78\xfb\x29\xd2\x64\x1f\x56\xea\xf0\xe5\xf5\xcc\xc4\x3a\x31\xa8\x84\x70\xbf\xbd\x6f\x8e\x78\x24\x5a\xc0\x0a\xf6\xfa\xf0\xf6\xe9\x00\x47\x5f\x73\xce\xe1\x43", 48) != 0) + return FALSE; + + /* PKCS-5 test 1 with HMAC-Whirlpool used as the PRF */ + derive_key_whirlpool ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); + if (memcmp (dk, "\x50\x7c\x36\x6f", 4) != 0) + return FALSE; + + /* PKCS-5 test 2 with HMAC-Whirlpool used as the PRF (derives a key longer than the underlying hash) */ + derive_key_whirlpool ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 96); + if (memcmp (dk, "\x50\x7c\x36\x6f\xee\x10\x2e\x9a\xe2\x8a\xd5\x82\x72\x7d\x27\x0f\xe8\x4d\x7f\x68\x7a\xcf\xb5\xe7\x43\x67\xaa\x98\x93\x52\x2b\x09\x6e\x42\xdf\x2c\x59\x4a\x91\x6d\x7e\x10\xae\xb2\x1a\x89\x8f\xb9\x8f\xe6\x31\xa9\xd8\x9f\x98\x26\xf4\xda\xcd\x7d\x65\x65\xde\x10\x95\x91\xb4\x84\x26\xae\x43\xa1\x00\x5b\x1e\xb8\x38\x97\xa4\x1e\x4b\xd2\x65\x64\xbc\xfa\x1f\x35\x85\xdb\x4f\x97\x65\x6f\xbd\x24", 96) != 0) + return FALSE; + + return TRUE; +} diff --git a/src/Common/Tests.h b/src/Common/Tests.h index 6cb335b2..5e56ff55 100644 --- a/src/Common/Tests.h +++ b/src/Common/Tests.h @@ -1,31 +1,31 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifdef __cplusplus -extern "C" { -#endif - -extern unsigned char ks_tmp[MAX_EXPANDED_KEY]; - -void CipherInit2(int cipher, void* key, void* ks, int key_len); -BOOL test_hmac_sha512 (void); -BOOL test_hmac_ripemd160 (void); -BOOL test_hmac_whirlpool (void); -BOOL test_pkcs5 (void); -BOOL TestSectorBufEncryption (); -BOOL TestLegacySectorBufEncryption (); -BOOL AutoTestAlgorithms (void); - -#ifdef __cplusplus -} -#endif +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifdef __cplusplus +extern "C" { +#endif + +extern unsigned char ks_tmp[MAX_EXPANDED_KEY]; + +void CipherInit2(int cipher, void* key, void* ks, int key_len); +BOOL test_hmac_sha512 (void); +BOOL test_hmac_ripemd160 (void); +BOOL test_hmac_whirlpool (void); +BOOL test_pkcs5 (void); +BOOL TestSectorBufEncryption (); +BOOL TestLegacySectorBufEncryption (); +BOOL AutoTestAlgorithms (void); + +#ifdef __cplusplus +} +#endif diff --git a/src/Common/Volumes.c b/src/Common/Volumes.c index 955c7e48..d2a54b5c 100644 --- a/src/Common/Volumes.c +++ b/src/Common/Volumes.c @@ -1,1270 +1,1270 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" - -#ifndef TC_WINDOWS_BOOT -#include -#include -#include -#include -#include "EncryptionThreadPool.h" -#endif - -#include -#include -#include - -#ifndef DEVICE_DRIVER -#include "Random.h" -#endif - -#include "Crc.h" -#include "Crypto.h" -#include "Endian.h" -#include "Volumes.h" -#include "Pkcs5.h" - -#ifdef _WIN32 -#include -#include "../Boot/Windows/BootCommon.h" -#endif - -/* Volume header v5 structure (used since TrueCrypt 7.0): */ -// -// Offset Length Description -// ------------------------------------------ -// Unencrypted: -// 0 64 Salt -// Encrypted: -// 64 4 ASCII string 'VERA' -// 68 2 Header version -// 70 2 Required program version -// 72 4 CRC-32 checksum of the (decrypted) bytes 256-511 -// 76 16 Reserved (must contain zeroes) -// 92 8 Size of hidden volume in bytes (0 = normal volume) -// 100 8 Size of the volume in bytes (identical with field 92 for hidden volumes, valid if field 70 >= 0x600 or flag bit 0 == 1) -// 108 8 Byte offset of the start of the master key scope (valid if field 70 >= 0x600 or flag bit 0 == 1) -// 116 8 Size of the encrypted area within the master key scope (valid if field 70 >= 0x600 or flag bit 0 == 1) -// 124 4 Flags: bit 0 set = system encryption; bit 1 set = non-system in-place encryption, bits 2-31 are reserved (set to zero) -// 128 4 Sector size in bytes -// 132 120 Reserved (must contain zeroes) -// 252 4 CRC-32 checksum of the (decrypted) bytes 64-251 -// 256 256 Concatenated primary master key(s) and secondary master key(s) (XTS mode) - - -/* Deprecated/legacy volume header v4 structure (used by TrueCrypt 6.x): */ -// -// Offset Length Description -// ------------------------------------------ -// Unencrypted: -// 0 64 Salt -// Encrypted: -// 64 4 ASCII string 'VERA' -// 68 2 Header version -// 70 2 Required program version -// 72 4 CRC-32 checksum of the (decrypted) bytes 256-511 -// 76 16 Reserved (must contain zeroes) -// 92 8 Size of hidden volume in bytes (0 = normal volume) -// 100 8 Size of the volume in bytes (identical with field 92 for hidden volumes, valid if field 70 >= 0x600 or flag bit 0 == 1) -// 108 8 Byte offset of the start of the master key scope (valid if field 70 >= 0x600 or flag bit 0 == 1) -// 116 8 Size of the encrypted area within the master key scope (valid if field 70 >= 0x600 or flag bit 0 == 1) -// 124 4 Flags: bit 0 set = system encryption; bit 1 set = non-system in-place encryption, bits 2-31 are reserved -// 128 124 Reserved (must contain zeroes) -// 252 4 CRC-32 checksum of the (decrypted) bytes 64-251 -// 256 256 Concatenated primary master key(s) and secondary master key(s) (XTS mode) - - -/* Deprecated/legacy volume header v3 structure (used by TrueCrypt 5.x): */ -// -// Offset Length Description -// ------------------------------------------ -// Unencrypted: -// 0 64 Salt -// Encrypted: -// 64 4 ASCII string 'VERA' -// 68 2 Header version -// 70 2 Required program version -// 72 4 CRC-32 checksum of the (decrypted) bytes 256-511 -// 76 8 Volume creation time -// 84 8 Header creation time -// 92 8 Size of hidden volume in bytes (0 = normal volume) -// 100 8 Size of the volume in bytes (identical with field 92 for hidden volumes) -// 108 8 Start byte offset of the encrypted area of the volume -// 116 8 Size of the encrypted area of the volume in bytes -// 124 132 Reserved (must contain zeroes) -// 256 256 Concatenated primary master key(s) and secondary master key(s) (XTS mode) - - -/* Deprecated/legacy volume header v2 structure (used before TrueCrypt 5.0): */ -// -// Offset Length Description -// ------------------------------------------ -// Unencrypted: -// 0 64 Salt -// Encrypted: -// 64 4 ASCII string 'VERA' -// 68 2 Header version -// 70 2 Required program version -// 72 4 CRC-32 checksum of the (decrypted) bytes 256-511 -// 76 8 Volume creation time -// 84 8 Header creation time -// 92 8 Size of hidden volume in bytes (0 = normal volume) -// 100 156 Reserved (must contain zeroes) -// 256 32 For LRW (deprecated/legacy), secondary key -// For CBC (deprecated/legacy), data used to generate IV and whitening values -// 288 224 Master key(s) - - - -uint16 GetHeaderField16 (byte *header, int offset) -{ - return BE16 (*(uint16 *) (header + offset)); -} - - -uint32 GetHeaderField32 (byte *header, int offset) -{ - return BE32 (*(uint32 *) (header + offset)); -} - - -UINT64_STRUCT GetHeaderField64 (byte *header, int offset) -{ - UINT64_STRUCT uint64Struct; - -#ifndef TC_NO_COMPILER_INT64 - uint64Struct.Value = BE64 (*(uint64 *) (header + offset)); -#else - uint64Struct.HighPart = BE32 (*(uint32 *) (header + offset)); - uint64Struct.LowPart = BE32 (*(uint32 *) (header + offset + 4)); -#endif - return uint64Struct; -} - - -#ifndef TC_WINDOWS_BOOT - -typedef struct -{ - char DerivedKey[MASTER_KEYDATA_SIZE]; - BOOL Free; - LONG KeyReady; - int Pkcs5Prf; -} KeyDerivationWorkItem; - - -BOOL ReadVolumeHeaderRecoveryMode = FALSE; - -int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, int selected_pkcs5_prf, int pim, BOOL truecryptMode, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo) -{ - char header[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; - CRYPTOPP_ALIGN_DATA(16) KEY_INFO keyInfo; - PCRYPTO_INFO cryptoInfo; - char dk[MASTER_KEYDATA_SIZE]; - int enqPkcs5Prf, pkcs5_prf; - uint16 headerVersion; - int status = ERR_PARAMETER_INCORRECT; - int primaryKeyOffset; - - TC_EVENT keyDerivationCompletedEvent; - TC_EVENT noOutstandingWorkItemEvent; - KeyDerivationWorkItem *keyDerivationWorkItems; - KeyDerivationWorkItem *item; - int pkcs5PrfCount = LAST_PRF_ID - FIRST_PRF_ID + 1; - size_t encryptionThreadCount = GetEncryptionThreadCount(); - size_t queuedWorkItems = 0; - LONG outstandingWorkItemCount = 0; - int i; - - // if no PIM specified, use default value - if (pim < 0) - pim = 0; - - if (truecryptMode) - { - // SHA-256 not supported in TrueCrypt mode - if (selected_pkcs5_prf == SHA256) - return ERR_PARAMETER_INCORRECT; - pkcs5PrfCount--; // don't count SHA-256 in case of TrueCrypt mode - } - - if (retHeaderCryptoInfo != NULL) - { - cryptoInfo = retHeaderCryptoInfo; - } - else - { - if (!retInfo) - return ERR_PARAMETER_INCORRECT; - - cryptoInfo = *retInfo = crypto_open (); - if (cryptoInfo == NULL) - return ERR_OUTOFMEMORY; - } - - /* use thread pool only if no PRF was specified */ - if ((selected_pkcs5_prf == 0) && (encryptionThreadCount > 1)) - { - keyDerivationWorkItems = TCalloc (sizeof (KeyDerivationWorkItem) * pkcs5PrfCount); - if (!keyDerivationWorkItems) - return ERR_OUTOFMEMORY; - - for (i = 0; i < pkcs5PrfCount; ++i) - keyDerivationWorkItems[i].Free = TRUE; - -#ifdef DEVICE_DRIVER - KeInitializeEvent (&keyDerivationCompletedEvent, SynchronizationEvent, FALSE); - KeInitializeEvent (&noOutstandingWorkItemEvent, SynchronizationEvent, TRUE); -#else - keyDerivationCompletedEvent = CreateEvent (NULL, FALSE, FALSE, NULL); - if (!keyDerivationCompletedEvent) - { - TCfree (keyDerivationWorkItems); - return ERR_OUTOFMEMORY; - } - - noOutstandingWorkItemEvent = CreateEvent (NULL, FALSE, TRUE, NULL); - if (!noOutstandingWorkItemEvent) - { - CloseHandle (keyDerivationCompletedEvent); - TCfree (keyDerivationWorkItems); - return ERR_OUTOFMEMORY; - } -#endif - } - -#ifndef DEVICE_DRIVER - VirtualLock (&keyInfo, sizeof (keyInfo)); - VirtualLock (&dk, sizeof (dk)); -#endif - - crypto_loadkey (&keyInfo, password->Text, (int) password->Length); - - // PKCS5 is used to derive the primary header key(s) and secondary header key(s) (XTS mode) from the password - memcpy (keyInfo.salt, encryptedHeader + HEADER_SALT_OFFSET, PKCS5_SALT_SIZE); - - // Test all available PKCS5 PRFs - for (enqPkcs5Prf = FIRST_PRF_ID; enqPkcs5Prf <= LAST_PRF_ID || queuedWorkItems > 0; ++enqPkcs5Prf) - { - // if a PRF is specified, we skip all other PRFs - if (selected_pkcs5_prf != 0 && enqPkcs5Prf != selected_pkcs5_prf) - continue; - - // skip SHA-256 in case of TrueCrypt mode - if (truecryptMode && (enqPkcs5Prf == SHA256)) - continue; - - if ((selected_pkcs5_prf == 0) && (encryptionThreadCount > 1)) - { - // Enqueue key derivation on thread pool - if (queuedWorkItems < encryptionThreadCount && enqPkcs5Prf <= LAST_PRF_ID) - { - for (i = 0; i < pkcs5PrfCount; ++i) - { - item = &keyDerivationWorkItems[i]; - if (item->Free) - { - item->Free = FALSE; - item->KeyReady = FALSE; - item->Pkcs5Prf = enqPkcs5Prf; - - EncryptionThreadPoolBeginKeyDerivation (&keyDerivationCompletedEvent, &noOutstandingWorkItemEvent, - &item->KeyReady, &outstandingWorkItemCount, enqPkcs5Prf, keyInfo.userKey, - keyInfo.keyLength, keyInfo.salt, get_pkcs5_iteration_count (enqPkcs5Prf, pim, truecryptMode, bBoot), item->DerivedKey); - - ++queuedWorkItems; - break; - } - } - - if (enqPkcs5Prf < LAST_PRF_ID) - continue; - } - else - --enqPkcs5Prf; - - // Wait for completion of a key derivation - while (queuedWorkItems > 0) - { - for (i = 0; i < pkcs5PrfCount; ++i) - { - item = &keyDerivationWorkItems[i]; - if (!item->Free && InterlockedExchangeAdd (&item->KeyReady, 0) == TRUE) - { - pkcs5_prf = item->Pkcs5Prf; - keyInfo.noIterations = get_pkcs5_iteration_count (pkcs5_prf, pim, truecryptMode, bBoot); - memcpy (dk, item->DerivedKey, sizeof (dk)); - - item->Free = TRUE; - --queuedWorkItems; - goto KeyReady; - } - } - - if (queuedWorkItems > 0) - TC_WAIT_EVENT (keyDerivationCompletedEvent); - } - continue; -KeyReady: ; - } - else - { - pkcs5_prf = enqPkcs5Prf; - keyInfo.noIterations = get_pkcs5_iteration_count (enqPkcs5Prf, pim, truecryptMode, bBoot); - - switch (pkcs5_prf) - { - case RIPEMD160: - derive_key_ripemd160 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, - PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); - break; - - case SHA512: - derive_key_sha512 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, - PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); - break; - - case WHIRLPOOL: - derive_key_whirlpool (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, - PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); - break; - - case SHA256: - derive_key_sha256 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, - PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); - break; - - default: - // Unknown/wrong ID - TC_THROW_FATAL_EXCEPTION; - } - } - - // Test all available modes of operation - for (cryptoInfo->mode = FIRST_MODE_OF_OPERATION_ID; - cryptoInfo->mode <= LAST_MODE_OF_OPERATION; - cryptoInfo->mode++) - { - switch (cryptoInfo->mode) - { - - default: - primaryKeyOffset = 0; - } - - // Test all available encryption algorithms - for (cryptoInfo->ea = EAGetFirst (); - cryptoInfo->ea != 0; - cryptoInfo->ea = EAGetNext (cryptoInfo->ea)) - { - int blockSize; - - if (!EAIsModeSupported (cryptoInfo->ea, cryptoInfo->mode)) - continue; // This encryption algorithm has never been available with this mode of operation - - blockSize = CipherGetBlockSize (EAGetFirstCipher (cryptoInfo->ea)); - - status = EAInit (cryptoInfo->ea, dk + primaryKeyOffset, cryptoInfo->ks); - if (status == ERR_CIPHER_INIT_FAILURE) - goto err; - - // Init objects related to the mode of operation - - if (cryptoInfo->mode == XTS) - { - // Copy the secondary key (if cascade, multiple concatenated) - memcpy (cryptoInfo->k2, dk + EAGetKeySize (cryptoInfo->ea), EAGetKeySize (cryptoInfo->ea)); - - // Secondary key schedule - if (!EAInitMode (cryptoInfo)) - { - status = ERR_MODE_INIT_FAILED; - goto err; - } - } - else - { - continue; - } - - // Copy the header for decryption - memcpy (header, encryptedHeader, sizeof (header)); - - // Try to decrypt header - - DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo); - - // Magic 'VERA' or 'TRUE' depending if we are in TrueCrypt mode or not - if ((truecryptMode && GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x54525545) - || (!truecryptMode && GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x56455241) - ) - continue; - - // Header version - headerVersion = GetHeaderField16 (header, TC_HEADER_OFFSET_VERSION); - - if (headerVersion > VOLUME_HEADER_VERSION) - { - status = ERR_NEW_VERSION_REQUIRED; - goto err; - } - - // Check CRC of the header fields - if (!ReadVolumeHeaderRecoveryMode - && headerVersion >= 4 - && GetHeaderField32 (header, TC_HEADER_OFFSET_HEADER_CRC) != GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC)) - continue; - - // Required program version - cryptoInfo->RequiredProgramVersion = GetHeaderField16 (header, TC_HEADER_OFFSET_REQUIRED_VERSION); - if (truecryptMode) - { - if (cryptoInfo->RequiredProgramVersion < 0x600 || cryptoInfo->RequiredProgramVersion > 0x71a) - { - status = ERR_UNSUPPORTED_TRUECRYPT_FORMAT | (((int)cryptoInfo->RequiredProgramVersion) << 16); - goto err; - } - cryptoInfo->LegacyVolume = FALSE; - } - else - cryptoInfo->LegacyVolume = cryptoInfo->RequiredProgramVersion < 0x10b; - - // Check CRC of the key set - if (!ReadVolumeHeaderRecoveryMode - && GetHeaderField32 (header, TC_HEADER_OFFSET_KEY_AREA_CRC) != GetCrc32 (header + HEADER_MASTER_KEYDATA_OFFSET, MASTER_KEYDATA_SIZE)) - continue; - - // Now we have the correct password, cipher, hash algorithm, and volume type - - // Check the version required to handle this volume - if (!truecryptMode && (cryptoInfo->RequiredProgramVersion > VERSION_NUM)) - { - status = ERR_NEW_VERSION_REQUIRED; - goto err; - } - - // Header version - cryptoInfo->HeaderVersion = headerVersion; - - // Volume creation time (legacy) - cryptoInfo->volume_creation_time = GetHeaderField64 (header, TC_HEADER_OFFSET_VOLUME_CREATION_TIME).Value; - - // Header creation time (legacy) - cryptoInfo->header_creation_time = GetHeaderField64 (header, TC_HEADER_OFFSET_MODIFICATION_TIME).Value; - - // Hidden volume size (if any) - cryptoInfo->hiddenVolumeSize = GetHeaderField64 (header, TC_HEADER_OFFSET_HIDDEN_VOLUME_SIZE).Value; - - // Hidden volume status - cryptoInfo->hiddenVolume = (cryptoInfo->hiddenVolumeSize != 0); - - // Volume size - cryptoInfo->VolumeSize = GetHeaderField64 (header, TC_HEADER_OFFSET_VOLUME_SIZE); - - // Encrypted area size and length - cryptoInfo->EncryptedAreaStart = GetHeaderField64 (header, TC_HEADER_OFFSET_ENCRYPTED_AREA_START); - cryptoInfo->EncryptedAreaLength = GetHeaderField64 (header, TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH); - - // Flags - cryptoInfo->HeaderFlags = GetHeaderField32 (header, TC_HEADER_OFFSET_FLAGS); - - // Sector size - if (headerVersion >= 5) - cryptoInfo->SectorSize = GetHeaderField32 (header, TC_HEADER_OFFSET_SECTOR_SIZE); - else - cryptoInfo->SectorSize = TC_SECTOR_SIZE_LEGACY; - - if (cryptoInfo->SectorSize < TC_MIN_VOLUME_SECTOR_SIZE - || cryptoInfo->SectorSize > TC_MAX_VOLUME_SECTOR_SIZE - || cryptoInfo->SectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0) - { - status = ERR_PARAMETER_INCORRECT; - goto err; - } - - // Preserve scheduled header keys if requested - if (retHeaderCryptoInfo) - { - if (retInfo == NULL) - { - cryptoInfo->pkcs5 = pkcs5_prf; - cryptoInfo->noIterations = keyInfo.noIterations; - cryptoInfo->bTrueCryptMode = truecryptMode; - cryptoInfo->volumePim = pim; - goto ret; - } - - cryptoInfo = *retInfo = crypto_open (); - if (cryptoInfo == NULL) - { - status = ERR_OUTOFMEMORY; - goto err; - } - - memcpy (cryptoInfo, retHeaderCryptoInfo, sizeof (*cryptoInfo)); - } - - // Master key data - memcpy (keyInfo.master_keydata, header + HEADER_MASTER_KEYDATA_OFFSET, MASTER_KEYDATA_SIZE); - memcpy (cryptoInfo->master_keydata, keyInfo.master_keydata, MASTER_KEYDATA_SIZE); - - // PKCS #5 - memcpy (cryptoInfo->salt, keyInfo.salt, PKCS5_SALT_SIZE); - cryptoInfo->pkcs5 = pkcs5_prf; - cryptoInfo->noIterations = keyInfo.noIterations; - cryptoInfo->bTrueCryptMode = truecryptMode; - cryptoInfo->volumePim = pim; - - // Init the cipher with the decrypted master key - status = EAInit (cryptoInfo->ea, keyInfo.master_keydata + primaryKeyOffset, cryptoInfo->ks); - if (status == ERR_CIPHER_INIT_FAILURE) - goto err; - - switch (cryptoInfo->mode) - { - - default: - // The secondary master key (if cascade, multiple concatenated) - memcpy (cryptoInfo->k2, keyInfo.master_keydata + EAGetKeySize (cryptoInfo->ea), EAGetKeySize (cryptoInfo->ea)); - - } - - if (!EAInitMode (cryptoInfo)) - { - status = ERR_MODE_INIT_FAILED; - goto err; - } - - status = ERR_SUCCESS; - goto ret; - } - } - } - status = ERR_PASSWORD_WRONG; - -err: - if (cryptoInfo != retHeaderCryptoInfo) - { - crypto_close(cryptoInfo); - *retInfo = NULL; - } - -ret: - burn (&keyInfo, sizeof (keyInfo)); - burn (dk, sizeof(dk)); - -#ifndef DEVICE_DRIVER - VirtualUnlock (&keyInfo, sizeof (keyInfo)); - VirtualUnlock (&dk, sizeof (dk)); -#endif - - if ((selected_pkcs5_prf == 0) && (encryptionThreadCount > 1)) - { - TC_WAIT_EVENT (noOutstandingWorkItemEvent); - - burn (keyDerivationWorkItems, sizeof (KeyDerivationWorkItem) * pkcs5PrfCount); - TCfree (keyDerivationWorkItems); - -#ifndef DEVICE_DRIVER - CloseHandle (keyDerivationCompletedEvent); - CloseHandle (noOutstandingWorkItemEvent); -#endif - } - - return status; -} - -#ifdef _WIN32 -void ComputeBootloaderFingerprint (byte *bootLoaderBuf, unsigned int bootLoaderSize, byte* fingerprint) -{ - // compute Whirlpool+SHA512 fingerprint of bootloader including MBR - // we skip user configuration fields: - // TC_BOOT_SECTOR_PIM_VALUE_OFFSET = 400 - // TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET = 402 - // => TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE = 4 - // TC_BOOT_SECTOR_USER_MESSAGE_OFFSET = 406 - // => TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH = 24 - // TC_BOOT_SECTOR_USER_CONFIG_OFFSET = 438 - // - // we have: TC_BOOT_SECTOR_USER_MESSAGE_OFFSET = TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE - - WHIRLPOOL_CTX whirlpool; - sha512_ctx sha2; - - WHIRLPOOL_init (&whirlpool); - sha512_begin (&sha2); - - WHIRLPOOL_add (bootLoaderBuf, TC_BOOT_SECTOR_PIM_VALUE_OFFSET * 8, &whirlpool); - sha512_hash (bootLoaderBuf, TC_BOOT_SECTOR_PIM_VALUE_OFFSET, &sha2); - - WHIRLPOOL_add (bootLoaderBuf + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH, (TC_BOOT_SECTOR_USER_CONFIG_OFFSET - (TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH)) * 8, &whirlpool); - sha512_hash (bootLoaderBuf + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH, (TC_BOOT_SECTOR_USER_CONFIG_OFFSET - (TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH)), &sha2); - - WHIRLPOOL_add (bootLoaderBuf + TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1, (TC_MAX_MBR_BOOT_CODE_SIZE - (TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1)) * 8, &whirlpool); - sha512_hash (bootLoaderBuf + TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1, (TC_MAX_MBR_BOOT_CODE_SIZE - (TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1)), &sha2); - - WHIRLPOOL_add (bootLoaderBuf + TC_SECTOR_SIZE_BIOS, (bootLoaderSize - TC_SECTOR_SIZE_BIOS) * 8, &whirlpool); - sha512_hash (bootLoaderBuf + TC_SECTOR_SIZE_BIOS, (bootLoaderSize - TC_SECTOR_SIZE_BIOS), &sha2); - - WHIRLPOOL_finalize (&whirlpool, fingerprint); - sha512_end (&fingerprint [WHIRLPOOL_DIGESTSIZE], &sha2); -} -#endif - -#else // TC_WINDOWS_BOOT - -int ReadVolumeHeader (BOOL bBoot, char *header, Password *password, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo) -{ -#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - char dk[32 * 2]; // 2 * 256-bit key -#else - char dk[32 * 2 * 3]; // 6 * 256-bit key -#endif - - PCRYPTO_INFO cryptoInfo; - int status = ERR_SUCCESS; - uint32 iterations = pim; - iterations <<= 16; - iterations |= bBoot; - - if (retHeaderCryptoInfo != NULL) - cryptoInfo = retHeaderCryptoInfo; - else - cryptoInfo = *retInfo = crypto_open (); - - // PKCS5 PRF -#ifdef TC_WINDOWS_BOOT_SHA2 - derive_key_sha256 (password->Text, (int) password->Length, header + HEADER_SALT_OFFSET, - PKCS5_SALT_SIZE, iterations, dk, sizeof (dk)); -#else - derive_key_ripemd160 (password->Text, (int) password->Length, header + HEADER_SALT_OFFSET, - PKCS5_SALT_SIZE, iterations, dk, sizeof (dk)); -#endif - - // Mode of operation - cryptoInfo->mode = FIRST_MODE_OF_OPERATION_ID; - -#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - cryptoInfo->ea = 1; -#else - // Test all available encryption algorithms - for (cryptoInfo->ea = EAGetFirst (); cryptoInfo->ea != 0; cryptoInfo->ea = EAGetNext (cryptoInfo->ea)) -#endif - { -#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - #if defined (TC_WINDOWS_BOOT_SERPENT) - serpent_set_key (dk, cryptoInfo->ks); - #elif defined (TC_WINDOWS_BOOT_TWOFISH) - twofish_set_key ((TwofishInstance *) cryptoInfo->ks, (const u4byte *) dk); - #else - status = EAInit (dk, cryptoInfo->ks); - if (status == ERR_CIPHER_INIT_FAILURE) - goto err; - #endif -#else - status = EAInit (cryptoInfo->ea, dk, cryptoInfo->ks); - if (status == ERR_CIPHER_INIT_FAILURE) - goto err; -#endif - // Secondary key schedule -#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - #if defined (TC_WINDOWS_BOOT_SERPENT) - serpent_set_key (dk + 32, cryptoInfo->ks2); - #elif defined (TC_WINDOWS_BOOT_TWOFISH) - twofish_set_key ((TwofishInstance *)cryptoInfo->ks2, (const u4byte *) (dk + 32)); - #else - EAInit (dk + 32, cryptoInfo->ks2); - #endif -#else - EAInit (cryptoInfo->ea, dk + EAGetKeySize (cryptoInfo->ea), cryptoInfo->ks2); -#endif - - // Try to decrypt header - DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo); - - // Check magic 'VERA' and CRC-32 of header fields and master keydata - if (GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x56455241 - || (GetHeaderField16 (header, TC_HEADER_OFFSET_VERSION) >= 4 && GetHeaderField32 (header, TC_HEADER_OFFSET_HEADER_CRC) != GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC)) - || GetHeaderField32 (header, TC_HEADER_OFFSET_KEY_AREA_CRC) != GetCrc32 (header + HEADER_MASTER_KEYDATA_OFFSET, MASTER_KEYDATA_SIZE)) - { - EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo); -#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - status = ERR_PASSWORD_WRONG; - goto err; -#else - continue; -#endif - } - - // Header decrypted - status = 0; - - // Hidden volume status - cryptoInfo->VolumeSize = GetHeaderField64 (header, TC_HEADER_OFFSET_HIDDEN_VOLUME_SIZE); - cryptoInfo->hiddenVolume = (cryptoInfo->VolumeSize.LowPart != 0 || cryptoInfo->VolumeSize.HighPart != 0); - - // Volume size - cryptoInfo->VolumeSize = GetHeaderField64 (header, TC_HEADER_OFFSET_VOLUME_SIZE); - - // Encrypted area size and length - cryptoInfo->EncryptedAreaStart = GetHeaderField64 (header, TC_HEADER_OFFSET_ENCRYPTED_AREA_START); - cryptoInfo->EncryptedAreaLength = GetHeaderField64 (header, TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH); - - // Flags - cryptoInfo->HeaderFlags = GetHeaderField32 (header, TC_HEADER_OFFSET_FLAGS); - -#ifdef TC_WINDOWS_BOOT_SHA2 - cryptoInfo->pkcs5 = SHA256; -#else - cryptoInfo->pkcs5 = RIPEMD160; -#endif - - memcpy (dk, header + HEADER_MASTER_KEYDATA_OFFSET, sizeof (dk)); - EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo); - - if (retHeaderCryptoInfo) - goto ret; - - // Init the encryption algorithm with the decrypted master key -#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - #if defined (TC_WINDOWS_BOOT_SERPENT) - serpent_set_key (dk, cryptoInfo->ks); - #elif defined (TC_WINDOWS_BOOT_TWOFISH) - twofish_set_key ((TwofishInstance *) cryptoInfo->ks, (const u4byte *) dk); - #else - status = EAInit (dk, cryptoInfo->ks); - if (status == ERR_CIPHER_INIT_FAILURE) - goto err; - #endif -#else - status = EAInit (cryptoInfo->ea, dk, cryptoInfo->ks); - if (status == ERR_CIPHER_INIT_FAILURE) - goto err; -#endif - - // The secondary master key (if cascade, multiple concatenated) -#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - #if defined (TC_WINDOWS_BOOT_SERPENT) - serpent_set_key (dk + 32, cryptoInfo->ks2); - #elif defined (TC_WINDOWS_BOOT_TWOFISH) - twofish_set_key ((TwofishInstance *)cryptoInfo->ks2, (const u4byte *) (dk + 32)); - #else - EAInit (dk + 32, cryptoInfo->ks2); - #endif -#else - EAInit (cryptoInfo->ea, dk + EAGetKeySize (cryptoInfo->ea), cryptoInfo->ks2); -#endif - goto ret; - } - - status = ERR_PASSWORD_WRONG; - -err: - if (cryptoInfo != retHeaderCryptoInfo) - { - crypto_close(cryptoInfo); - *retInfo = NULL; - } - -ret: - burn (dk, sizeof(dk)); - return status; -} - -#endif // TC_WINDOWS_BOOT - - -#if !defined (DEVICE_DRIVER) && !defined (TC_WINDOWS_BOOT) - -#ifdef VOLFORMAT -# include "../Format/TcFormat.h" -# include "Dlgcode.h" -#endif - -// Creates a volume header in memory -int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, char *header, int ea, int mode, Password *password, - int pkcs5_prf, int pim, char *masterKeydata, PCRYPTO_INFO *retInfo, - unsigned __int64 volumeSize, unsigned __int64 hiddenVolumeSize, - unsigned __int64 encryptedAreaStart, unsigned __int64 encryptedAreaLength, uint16 requiredProgramVersion, uint32 headerFlags, uint32 sectorSize, BOOL bWipeMode) -{ - unsigned char *p = (unsigned char *) header; - static CRYPTOPP_ALIGN_DATA(16) KEY_INFO keyInfo; - - int nUserKeyLen = password->Length; - PCRYPTO_INFO cryptoInfo = crypto_open (); - static char dk[MASTER_KEYDATA_SIZE]; - int x; - int retVal = 0; - int primaryKeyOffset; - - if (cryptoInfo == NULL) - return ERR_OUTOFMEMORY; - - // if no PIM specified, use default value - if (pim < 0) - pim = 0; - - memset (header, 0, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - - VirtualLock (&keyInfo, sizeof (keyInfo)); - VirtualLock (&dk, sizeof (dk)); - - /* Encryption setup */ - - if (masterKeydata == NULL) - { - // We have no master key data (creating a new volume) so we'll use the TrueCrypt RNG to generate them - - int bytesNeeded; - - switch (mode) - { - - default: - bytesNeeded = EAGetKeySize (ea) * 2; // Size of primary + secondary key(s) - } - - if (!RandgetBytes (hwndDlg, keyInfo.master_keydata, bytesNeeded, TRUE)) - return ERR_CIPHER_INIT_WEAK_KEY; - } - else - { - // We already have existing master key data (the header is being re-encrypted) - memcpy (keyInfo.master_keydata, masterKeydata, MASTER_KEYDATA_SIZE); - } - - // User key - memcpy (keyInfo.userKey, password->Text, nUserKeyLen); - keyInfo.keyLength = nUserKeyLen; - keyInfo.noIterations = get_pkcs5_iteration_count (pkcs5_prf, pim, FALSE, bBoot); - - // User selected encryption algorithm - cryptoInfo->ea = ea; - - // User selected PRF - cryptoInfo->pkcs5 = pkcs5_prf; - cryptoInfo->bTrueCryptMode = FALSE; - cryptoInfo->noIterations = keyInfo.noIterations; - cryptoInfo->volumePim = pim; - - // Mode of operation - cryptoInfo->mode = mode; - - // Salt for header key derivation - if (!RandgetBytes (hwndDlg, keyInfo.salt, PKCS5_SALT_SIZE, !bWipeMode)) - return ERR_CIPHER_INIT_WEAK_KEY; - - // PBKDF2 (PKCS5) is used to derive primary header key(s) and secondary header key(s) (XTS) from the password/keyfiles - switch (pkcs5_prf) - { - case SHA512: - derive_key_sha512 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, - PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); - break; - - case SHA256: - derive_key_sha256 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, - PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); - break; - - case RIPEMD160: - derive_key_ripemd160 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, - PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); - break; - - case WHIRLPOOL: - derive_key_whirlpool (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, - PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); - break; - - default: - // Unknown/wrong ID - TC_THROW_FATAL_EXCEPTION; - } - - /* Header setup */ - - // Salt - mputBytes (p, keyInfo.salt, PKCS5_SALT_SIZE); - - // Magic - mputLong (p, 0x56455241); - - // Header version - mputWord (p, VOLUME_HEADER_VERSION); - cryptoInfo->HeaderVersion = VOLUME_HEADER_VERSION; - - // Required program version to handle this volume - mputWord (p, requiredProgramVersion != 0 ? requiredProgramVersion : TC_VOLUME_MIN_REQUIRED_PROGRAM_VERSION); - - // CRC of the master key data - x = GetCrc32(keyInfo.master_keydata, MASTER_KEYDATA_SIZE); - mputLong (p, x); - - // Reserved fields - p += 2 * 8; - - // Size of hidden volume (if any) - cryptoInfo->hiddenVolumeSize = hiddenVolumeSize; - mputInt64 (p, cryptoInfo->hiddenVolumeSize); - - cryptoInfo->hiddenVolume = cryptoInfo->hiddenVolumeSize != 0; - - // Volume size - cryptoInfo->VolumeSize.Value = volumeSize; - mputInt64 (p, volumeSize); - - // Encrypted area start - cryptoInfo->EncryptedAreaStart.Value = encryptedAreaStart; - mputInt64 (p, encryptedAreaStart); - - // Encrypted area size - cryptoInfo->EncryptedAreaLength.Value = encryptedAreaLength; - mputInt64 (p, encryptedAreaLength); - - // Flags - cryptoInfo->HeaderFlags = headerFlags; - mputLong (p, headerFlags); - - // Sector size - if (sectorSize < TC_MIN_VOLUME_SECTOR_SIZE - || sectorSize > TC_MAX_VOLUME_SECTOR_SIZE - || sectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0) - { - TC_THROW_FATAL_EXCEPTION; - } - - cryptoInfo->SectorSize = sectorSize; - mputLong (p, sectorSize); - - // CRC of the header fields - x = GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC); - p = header + TC_HEADER_OFFSET_HEADER_CRC; - mputLong (p, x); - - // The master key data - memcpy (header + HEADER_MASTER_KEYDATA_OFFSET, keyInfo.master_keydata, MASTER_KEYDATA_SIZE); - - - /* Header encryption */ - - switch (mode) - { - - default: - // The secondary key (if cascade, multiple concatenated) - memcpy (cryptoInfo->k2, dk + EAGetKeySize (cryptoInfo->ea), EAGetKeySize (cryptoInfo->ea)); - primaryKeyOffset = 0; - } - - retVal = EAInit (cryptoInfo->ea, dk + primaryKeyOffset, cryptoInfo->ks); - if (retVal != ERR_SUCCESS) - return retVal; - - // Mode of operation - if (!EAInitMode (cryptoInfo)) - return ERR_OUTOFMEMORY; - - - // Encrypt the entire header (except the salt) - EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, - HEADER_ENCRYPTED_DATA_SIZE, - cryptoInfo); - - - /* cryptoInfo setup for further use (disk format) */ - - // Init with the master key(s) - retVal = EAInit (cryptoInfo->ea, keyInfo.master_keydata + primaryKeyOffset, cryptoInfo->ks); - if (retVal != ERR_SUCCESS) - return retVal; - - memcpy (cryptoInfo->master_keydata, keyInfo.master_keydata, MASTER_KEYDATA_SIZE); - - switch (cryptoInfo->mode) - { - - default: - // The secondary master key (if cascade, multiple concatenated) - memcpy (cryptoInfo->k2, keyInfo.master_keydata + EAGetKeySize (cryptoInfo->ea), EAGetKeySize (cryptoInfo->ea)); - } - - // Mode of operation - if (!EAInitMode (cryptoInfo)) - return ERR_OUTOFMEMORY; - - -#ifdef VOLFORMAT - if (!bInPlaceEncNonSys && (showKeys || (bBoot && !masterKeydata))) - { - BOOL dots3 = FALSE; - int i, j; - - j = EAGetKeySize (ea); - - if (j > NBR_KEY_BYTES_TO_DISPLAY) - { - dots3 = TRUE; - j = NBR_KEY_BYTES_TO_DISPLAY; - } - - MasterKeyGUIView[0] = 0; - for (i = 0; i < j; i++) - { - wchar_t tmp2[8] = {0}; - StringCchPrintfW (tmp2, ARRAYSIZE(tmp2), L"%02X", (int) (unsigned char) keyInfo.master_keydata[i + primaryKeyOffset]); - StringCchCatW (MasterKeyGUIView, ARRAYSIZE(MasterKeyGUIView), tmp2); - } - - HeaderKeyGUIView[0] = 0; - for (i = 0; i < NBR_KEY_BYTES_TO_DISPLAY; i++) - { - wchar_t tmp2[8]; - StringCchPrintfW (tmp2, ARRAYSIZE(tmp2), L"%02X", (int) (unsigned char) dk[primaryKeyOffset + i]); - StringCchCatW (HeaderKeyGUIView, ARRAYSIZE(HeaderKeyGUIView), tmp2); - } - - if (dots3) - { - DisplayPortionsOfKeys (hHeaderKey, hMasterKey, HeaderKeyGUIView, MasterKeyGUIView, !showKeys); - } - else - { - SendMessage (hMasterKey, WM_SETTEXT, 0, (LPARAM) MasterKeyGUIView); - SendMessage (hHeaderKey, WM_SETTEXT, 0, (LPARAM) HeaderKeyGUIView); - } - } -#endif // #ifdef VOLFORMAT - - burn (dk, sizeof(dk)); - burn (&keyInfo, sizeof (keyInfo)); - - *retInfo = cryptoInfo; - return 0; -} - - -BOOL ReadEffectiveVolumeHeader (BOOL device, HANDLE fileHandle, byte *header, DWORD *bytesRead) -{ -#if TC_VOLUME_HEADER_EFFECTIVE_SIZE > TC_MAX_VOLUME_SECTOR_SIZE -#error TC_VOLUME_HEADER_EFFECTIVE_SIZE > TC_MAX_VOLUME_SECTOR_SIZE -#endif - - byte sectorBuffer[TC_MAX_VOLUME_SECTOR_SIZE]; - DISK_GEOMETRY geometry; - - if (!device) - return ReadFile (fileHandle, header, TC_VOLUME_HEADER_EFFECTIVE_SIZE, bytesRead, NULL); - - if (!DeviceIoControl (fileHandle, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &geometry, sizeof (geometry), bytesRead, NULL)) - return FALSE; - - if (geometry.BytesPerSector > sizeof (sectorBuffer) || geometry.BytesPerSector < TC_MIN_VOLUME_SECTOR_SIZE) - { - SetLastError (ERROR_INVALID_PARAMETER); - return FALSE; - } - - if (!ReadFile (fileHandle, sectorBuffer, max (TC_VOLUME_HEADER_EFFECTIVE_SIZE, geometry.BytesPerSector), bytesRead, NULL)) - return FALSE; - - memcpy (header, sectorBuffer, min (*bytesRead, TC_VOLUME_HEADER_EFFECTIVE_SIZE)); - - if (*bytesRead > TC_VOLUME_HEADER_EFFECTIVE_SIZE) - *bytesRead = TC_VOLUME_HEADER_EFFECTIVE_SIZE; - - return TRUE; -} - - -BOOL WriteEffectiveVolumeHeader (BOOL device, HANDLE fileHandle, byte *header) -{ -#if TC_VOLUME_HEADER_EFFECTIVE_SIZE > TC_MAX_VOLUME_SECTOR_SIZE -#error TC_VOLUME_HEADER_EFFECTIVE_SIZE > TC_MAX_VOLUME_SECTOR_SIZE -#endif - - byte sectorBuffer[TC_MAX_VOLUME_SECTOR_SIZE]; - DWORD bytesDone; - DISK_GEOMETRY geometry; - - if (!device) - { - if (!WriteFile (fileHandle, header, TC_VOLUME_HEADER_EFFECTIVE_SIZE, &bytesDone, NULL)) - return FALSE; - - if (bytesDone != TC_VOLUME_HEADER_EFFECTIVE_SIZE) - { - SetLastError (ERROR_INVALID_PARAMETER); - return FALSE; - } - - return TRUE; - } - - if (!DeviceIoControl (fileHandle, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &geometry, sizeof (geometry), &bytesDone, NULL)) - return FALSE; - - if (geometry.BytesPerSector > sizeof (sectorBuffer) || geometry.BytesPerSector < TC_MIN_VOLUME_SECTOR_SIZE) - { - SetLastError (ERROR_INVALID_PARAMETER); - return FALSE; - } - - if (geometry.BytesPerSector != TC_VOLUME_HEADER_EFFECTIVE_SIZE) - { - LARGE_INTEGER seekOffset; - - if (!ReadFile (fileHandle, sectorBuffer, geometry.BytesPerSector, &bytesDone, NULL)) - return FALSE; - - if (bytesDone != geometry.BytesPerSector) - { - SetLastError (ERROR_INVALID_PARAMETER); - return FALSE; - } - - seekOffset.QuadPart = -(int) bytesDone; - if (!SetFilePointerEx (fileHandle, seekOffset, NULL, FILE_CURRENT)) - return FALSE; - } - - memcpy (sectorBuffer, header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - - if (!WriteFile (fileHandle, sectorBuffer, geometry.BytesPerSector, &bytesDone, NULL)) - return FALSE; - - if (bytesDone != geometry.BytesPerSector) - { - SetLastError (ERROR_INVALID_PARAMETER); - return FALSE; - } - - return TRUE; -} - - -// Writes randomly generated data to unused/reserved header areas. -// When bPrimaryOnly is TRUE, then only the primary header area (not the backup header area) is filled with random data. -// When bBackupOnly is TRUE, only the backup header area (not the primary header area) is filled with random data. -int WriteRandomDataToReservedHeaderAreas (HWND hwndDlg, HANDLE dev, CRYPTO_INFO *cryptoInfo, uint64 dataAreaSize, BOOL bPrimaryOnly, BOOL bBackupOnly) -{ - char temporaryKey[MASTER_KEYDATA_SIZE]; - char originalK2[MASTER_KEYDATA_SIZE]; - - byte buf[TC_VOLUME_HEADER_GROUP_SIZE]; - - LARGE_INTEGER offset; - int nStatus = ERR_SUCCESS; - DWORD dwError; - DWORD bytesDone; - BOOL backupHeaders = bBackupOnly; - - if (bPrimaryOnly && bBackupOnly) - TC_THROW_FATAL_EXCEPTION; - - memcpy (originalK2, cryptoInfo->k2, sizeof (cryptoInfo->k2)); - - while (TRUE) - { - // Temporary keys - if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (cryptoInfo->ea), FALSE) - || !RandgetBytes (hwndDlg, cryptoInfo->k2, sizeof (cryptoInfo->k2), FALSE)) - { - nStatus = ERR_PARAMETER_INCORRECT; - goto final_seq; - } - - nStatus = EAInit (cryptoInfo->ea, temporaryKey, cryptoInfo->ks); - if (nStatus != ERR_SUCCESS) - goto final_seq; - - if (!EAInitMode (cryptoInfo)) - { - nStatus = ERR_MODE_INIT_FAILED; - goto final_seq; - } - - offset.QuadPart = backupHeaders ? dataAreaSize + TC_VOLUME_HEADER_GROUP_SIZE : TC_VOLUME_HEADER_OFFSET; - - if (!SetFilePointerEx (dev, offset, NULL, FILE_BEGIN)) - { - nStatus = ERR_OS_ERROR; - goto final_seq; - } - - if (!ReadFile (dev, buf, sizeof (buf), &bytesDone, NULL)) - { - nStatus = ERR_OS_ERROR; - goto final_seq; - } - - if (bytesDone < TC_VOLUME_HEADER_EFFECTIVE_SIZE) - { - SetLastError (ERROR_INVALID_PARAMETER); - nStatus = ERR_OS_ERROR; - goto final_seq; - } - - EncryptBuffer (buf + TC_VOLUME_HEADER_EFFECTIVE_SIZE, sizeof (buf) - TC_VOLUME_HEADER_EFFECTIVE_SIZE, cryptoInfo); - - if (!SetFilePointerEx (dev, offset, NULL, FILE_BEGIN)) - { - nStatus = ERR_OS_ERROR; - goto final_seq; - } - - if (!WriteFile (dev, buf, sizeof (buf), &bytesDone, NULL)) - { - nStatus = ERR_OS_ERROR; - goto final_seq; - } - - if (bytesDone != sizeof (buf)) - { - nStatus = ERR_PARAMETER_INCORRECT; - goto final_seq; - } - - if (backupHeaders || bPrimaryOnly) - break; - - backupHeaders = TRUE; - } - - memcpy (cryptoInfo->k2, originalK2, sizeof (cryptoInfo->k2)); - - nStatus = EAInit (cryptoInfo->ea, cryptoInfo->master_keydata, cryptoInfo->ks); - if (nStatus != ERR_SUCCESS) - goto final_seq; - - if (!EAInitMode (cryptoInfo)) - { - nStatus = ERR_MODE_INIT_FAILED; - goto final_seq; - } - -final_seq: - - dwError = GetLastError(); - - burn (temporaryKey, sizeof (temporaryKey)); - burn (originalK2, sizeof (originalK2)); - - if (nStatus != ERR_SUCCESS) - SetLastError (dwError); - - return nStatus; -} - -#endif // !defined (DEVICE_DRIVER) && !defined (TC_WINDOWS_BOOT) +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" + +#ifndef TC_WINDOWS_BOOT +#include +#include +#include +#include +#include "EncryptionThreadPool.h" +#endif + +#include +#include +#include + +#ifndef DEVICE_DRIVER +#include "Random.h" +#endif + +#include "Crc.h" +#include "Crypto.h" +#include "Endian.h" +#include "Volumes.h" +#include "Pkcs5.h" + +#ifdef _WIN32 +#include +#include "../Boot/Windows/BootCommon.h" +#endif + +/* Volume header v5 structure (used since TrueCrypt 7.0): */ +// +// Offset Length Description +// ------------------------------------------ +// Unencrypted: +// 0 64 Salt +// Encrypted: +// 64 4 ASCII string 'VERA' +// 68 2 Header version +// 70 2 Required program version +// 72 4 CRC-32 checksum of the (decrypted) bytes 256-511 +// 76 16 Reserved (must contain zeroes) +// 92 8 Size of hidden volume in bytes (0 = normal volume) +// 100 8 Size of the volume in bytes (identical with field 92 for hidden volumes, valid if field 70 >= 0x600 or flag bit 0 == 1) +// 108 8 Byte offset of the start of the master key scope (valid if field 70 >= 0x600 or flag bit 0 == 1) +// 116 8 Size of the encrypted area within the master key scope (valid if field 70 >= 0x600 or flag bit 0 == 1) +// 124 4 Flags: bit 0 set = system encryption; bit 1 set = non-system in-place encryption, bits 2-31 are reserved (set to zero) +// 128 4 Sector size in bytes +// 132 120 Reserved (must contain zeroes) +// 252 4 CRC-32 checksum of the (decrypted) bytes 64-251 +// 256 256 Concatenated primary master key(s) and secondary master key(s) (XTS mode) + + +/* Deprecated/legacy volume header v4 structure (used by TrueCrypt 6.x): */ +// +// Offset Length Description +// ------------------------------------------ +// Unencrypted: +// 0 64 Salt +// Encrypted: +// 64 4 ASCII string 'VERA' +// 68 2 Header version +// 70 2 Required program version +// 72 4 CRC-32 checksum of the (decrypted) bytes 256-511 +// 76 16 Reserved (must contain zeroes) +// 92 8 Size of hidden volume in bytes (0 = normal volume) +// 100 8 Size of the volume in bytes (identical with field 92 for hidden volumes, valid if field 70 >= 0x600 or flag bit 0 == 1) +// 108 8 Byte offset of the start of the master key scope (valid if field 70 >= 0x600 or flag bit 0 == 1) +// 116 8 Size of the encrypted area within the master key scope (valid if field 70 >= 0x600 or flag bit 0 == 1) +// 124 4 Flags: bit 0 set = system encryption; bit 1 set = non-system in-place encryption, bits 2-31 are reserved +// 128 124 Reserved (must contain zeroes) +// 252 4 CRC-32 checksum of the (decrypted) bytes 64-251 +// 256 256 Concatenated primary master key(s) and secondary master key(s) (XTS mode) + + +/* Deprecated/legacy volume header v3 structure (used by TrueCrypt 5.x): */ +// +// Offset Length Description +// ------------------------------------------ +// Unencrypted: +// 0 64 Salt +// Encrypted: +// 64 4 ASCII string 'VERA' +// 68 2 Header version +// 70 2 Required program version +// 72 4 CRC-32 checksum of the (decrypted) bytes 256-511 +// 76 8 Volume creation time +// 84 8 Header creation time +// 92 8 Size of hidden volume in bytes (0 = normal volume) +// 100 8 Size of the volume in bytes (identical with field 92 for hidden volumes) +// 108 8 Start byte offset of the encrypted area of the volume +// 116 8 Size of the encrypted area of the volume in bytes +// 124 132 Reserved (must contain zeroes) +// 256 256 Concatenated primary master key(s) and secondary master key(s) (XTS mode) + + +/* Deprecated/legacy volume header v2 structure (used before TrueCrypt 5.0): */ +// +// Offset Length Description +// ------------------------------------------ +// Unencrypted: +// 0 64 Salt +// Encrypted: +// 64 4 ASCII string 'VERA' +// 68 2 Header version +// 70 2 Required program version +// 72 4 CRC-32 checksum of the (decrypted) bytes 256-511 +// 76 8 Volume creation time +// 84 8 Header creation time +// 92 8 Size of hidden volume in bytes (0 = normal volume) +// 100 156 Reserved (must contain zeroes) +// 256 32 For LRW (deprecated/legacy), secondary key +// For CBC (deprecated/legacy), data used to generate IV and whitening values +// 288 224 Master key(s) + + + +uint16 GetHeaderField16 (byte *header, int offset) +{ + return BE16 (*(uint16 *) (header + offset)); +} + + +uint32 GetHeaderField32 (byte *header, int offset) +{ + return BE32 (*(uint32 *) (header + offset)); +} + + +UINT64_STRUCT GetHeaderField64 (byte *header, int offset) +{ + UINT64_STRUCT uint64Struct; + +#ifndef TC_NO_COMPILER_INT64 + uint64Struct.Value = BE64 (*(uint64 *) (header + offset)); +#else + uint64Struct.HighPart = BE32 (*(uint32 *) (header + offset)); + uint64Struct.LowPart = BE32 (*(uint32 *) (header + offset + 4)); +#endif + return uint64Struct; +} + + +#ifndef TC_WINDOWS_BOOT + +typedef struct +{ + char DerivedKey[MASTER_KEYDATA_SIZE]; + BOOL Free; + LONG KeyReady; + int Pkcs5Prf; +} KeyDerivationWorkItem; + + +BOOL ReadVolumeHeaderRecoveryMode = FALSE; + +int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, int selected_pkcs5_prf, int pim, BOOL truecryptMode, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo) +{ + char header[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; + CRYPTOPP_ALIGN_DATA(16) KEY_INFO keyInfo; + PCRYPTO_INFO cryptoInfo; + char dk[MASTER_KEYDATA_SIZE]; + int enqPkcs5Prf, pkcs5_prf; + uint16 headerVersion; + int status = ERR_PARAMETER_INCORRECT; + int primaryKeyOffset; + + TC_EVENT keyDerivationCompletedEvent; + TC_EVENT noOutstandingWorkItemEvent; + KeyDerivationWorkItem *keyDerivationWorkItems; + KeyDerivationWorkItem *item; + int pkcs5PrfCount = LAST_PRF_ID - FIRST_PRF_ID + 1; + size_t encryptionThreadCount = GetEncryptionThreadCount(); + size_t queuedWorkItems = 0; + LONG outstandingWorkItemCount = 0; + int i; + + // if no PIM specified, use default value + if (pim < 0) + pim = 0; + + if (truecryptMode) + { + // SHA-256 not supported in TrueCrypt mode + if (selected_pkcs5_prf == SHA256) + return ERR_PARAMETER_INCORRECT; + pkcs5PrfCount--; // don't count SHA-256 in case of TrueCrypt mode + } + + if (retHeaderCryptoInfo != NULL) + { + cryptoInfo = retHeaderCryptoInfo; + } + else + { + if (!retInfo) + return ERR_PARAMETER_INCORRECT; + + cryptoInfo = *retInfo = crypto_open (); + if (cryptoInfo == NULL) + return ERR_OUTOFMEMORY; + } + + /* use thread pool only if no PRF was specified */ + if ((selected_pkcs5_prf == 0) && (encryptionThreadCount > 1)) + { + keyDerivationWorkItems = TCalloc (sizeof (KeyDerivationWorkItem) * pkcs5PrfCount); + if (!keyDerivationWorkItems) + return ERR_OUTOFMEMORY; + + for (i = 0; i < pkcs5PrfCount; ++i) + keyDerivationWorkItems[i].Free = TRUE; + +#ifdef DEVICE_DRIVER + KeInitializeEvent (&keyDerivationCompletedEvent, SynchronizationEvent, FALSE); + KeInitializeEvent (&noOutstandingWorkItemEvent, SynchronizationEvent, TRUE); +#else + keyDerivationCompletedEvent = CreateEvent (NULL, FALSE, FALSE, NULL); + if (!keyDerivationCompletedEvent) + { + TCfree (keyDerivationWorkItems); + return ERR_OUTOFMEMORY; + } + + noOutstandingWorkItemEvent = CreateEvent (NULL, FALSE, TRUE, NULL); + if (!noOutstandingWorkItemEvent) + { + CloseHandle (keyDerivationCompletedEvent); + TCfree (keyDerivationWorkItems); + return ERR_OUTOFMEMORY; + } +#endif + } + +#ifndef DEVICE_DRIVER + VirtualLock (&keyInfo, sizeof (keyInfo)); + VirtualLock (&dk, sizeof (dk)); +#endif + + crypto_loadkey (&keyInfo, password->Text, (int) password->Length); + + // PKCS5 is used to derive the primary header key(s) and secondary header key(s) (XTS mode) from the password + memcpy (keyInfo.salt, encryptedHeader + HEADER_SALT_OFFSET, PKCS5_SALT_SIZE); + + // Test all available PKCS5 PRFs + for (enqPkcs5Prf = FIRST_PRF_ID; enqPkcs5Prf <= LAST_PRF_ID || queuedWorkItems > 0; ++enqPkcs5Prf) + { + // if a PRF is specified, we skip all other PRFs + if (selected_pkcs5_prf != 0 && enqPkcs5Prf != selected_pkcs5_prf) + continue; + + // skip SHA-256 in case of TrueCrypt mode + if (truecryptMode && (enqPkcs5Prf == SHA256)) + continue; + + if ((selected_pkcs5_prf == 0) && (encryptionThreadCount > 1)) + { + // Enqueue key derivation on thread pool + if (queuedWorkItems < encryptionThreadCount && enqPkcs5Prf <= LAST_PRF_ID) + { + for (i = 0; i < pkcs5PrfCount; ++i) + { + item = &keyDerivationWorkItems[i]; + if (item->Free) + { + item->Free = FALSE; + item->KeyReady = FALSE; + item->Pkcs5Prf = enqPkcs5Prf; + + EncryptionThreadPoolBeginKeyDerivation (&keyDerivationCompletedEvent, &noOutstandingWorkItemEvent, + &item->KeyReady, &outstandingWorkItemCount, enqPkcs5Prf, keyInfo.userKey, + keyInfo.keyLength, keyInfo.salt, get_pkcs5_iteration_count (enqPkcs5Prf, pim, truecryptMode, bBoot), item->DerivedKey); + + ++queuedWorkItems; + break; + } + } + + if (enqPkcs5Prf < LAST_PRF_ID) + continue; + } + else + --enqPkcs5Prf; + + // Wait for completion of a key derivation + while (queuedWorkItems > 0) + { + for (i = 0; i < pkcs5PrfCount; ++i) + { + item = &keyDerivationWorkItems[i]; + if (!item->Free && InterlockedExchangeAdd (&item->KeyReady, 0) == TRUE) + { + pkcs5_prf = item->Pkcs5Prf; + keyInfo.noIterations = get_pkcs5_iteration_count (pkcs5_prf, pim, truecryptMode, bBoot); + memcpy (dk, item->DerivedKey, sizeof (dk)); + + item->Free = TRUE; + --queuedWorkItems; + goto KeyReady; + } + } + + if (queuedWorkItems > 0) + TC_WAIT_EVENT (keyDerivationCompletedEvent); + } + continue; +KeyReady: ; + } + else + { + pkcs5_prf = enqPkcs5Prf; + keyInfo.noIterations = get_pkcs5_iteration_count (enqPkcs5Prf, pim, truecryptMode, bBoot); + + switch (pkcs5_prf) + { + case RIPEMD160: + derive_key_ripemd160 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, + PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); + break; + + case SHA512: + derive_key_sha512 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, + PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); + break; + + case WHIRLPOOL: + derive_key_whirlpool (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, + PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); + break; + + case SHA256: + derive_key_sha256 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, + PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); + break; + + default: + // Unknown/wrong ID + TC_THROW_FATAL_EXCEPTION; + } + } + + // Test all available modes of operation + for (cryptoInfo->mode = FIRST_MODE_OF_OPERATION_ID; + cryptoInfo->mode <= LAST_MODE_OF_OPERATION; + cryptoInfo->mode++) + { + switch (cryptoInfo->mode) + { + + default: + primaryKeyOffset = 0; + } + + // Test all available encryption algorithms + for (cryptoInfo->ea = EAGetFirst (); + cryptoInfo->ea != 0; + cryptoInfo->ea = EAGetNext (cryptoInfo->ea)) + { + int blockSize; + + if (!EAIsModeSupported (cryptoInfo->ea, cryptoInfo->mode)) + continue; // This encryption algorithm has never been available with this mode of operation + + blockSize = CipherGetBlockSize (EAGetFirstCipher (cryptoInfo->ea)); + + status = EAInit (cryptoInfo->ea, dk + primaryKeyOffset, cryptoInfo->ks); + if (status == ERR_CIPHER_INIT_FAILURE) + goto err; + + // Init objects related to the mode of operation + + if (cryptoInfo->mode == XTS) + { + // Copy the secondary key (if cascade, multiple concatenated) + memcpy (cryptoInfo->k2, dk + EAGetKeySize (cryptoInfo->ea), EAGetKeySize (cryptoInfo->ea)); + + // Secondary key schedule + if (!EAInitMode (cryptoInfo)) + { + status = ERR_MODE_INIT_FAILED; + goto err; + } + } + else + { + continue; + } + + // Copy the header for decryption + memcpy (header, encryptedHeader, sizeof (header)); + + // Try to decrypt header + + DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo); + + // Magic 'VERA' or 'TRUE' depending if we are in TrueCrypt mode or not + if ((truecryptMode && GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x54525545) + || (!truecryptMode && GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x56455241) + ) + continue; + + // Header version + headerVersion = GetHeaderField16 (header, TC_HEADER_OFFSET_VERSION); + + if (headerVersion > VOLUME_HEADER_VERSION) + { + status = ERR_NEW_VERSION_REQUIRED; + goto err; + } + + // Check CRC of the header fields + if (!ReadVolumeHeaderRecoveryMode + && headerVersion >= 4 + && GetHeaderField32 (header, TC_HEADER_OFFSET_HEADER_CRC) != GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC)) + continue; + + // Required program version + cryptoInfo->RequiredProgramVersion = GetHeaderField16 (header, TC_HEADER_OFFSET_REQUIRED_VERSION); + if (truecryptMode) + { + if (cryptoInfo->RequiredProgramVersion < 0x600 || cryptoInfo->RequiredProgramVersion > 0x71a) + { + status = ERR_UNSUPPORTED_TRUECRYPT_FORMAT | (((int)cryptoInfo->RequiredProgramVersion) << 16); + goto err; + } + cryptoInfo->LegacyVolume = FALSE; + } + else + cryptoInfo->LegacyVolume = cryptoInfo->RequiredProgramVersion < 0x10b; + + // Check CRC of the key set + if (!ReadVolumeHeaderRecoveryMode + && GetHeaderField32 (header, TC_HEADER_OFFSET_KEY_AREA_CRC) != GetCrc32 (header + HEADER_MASTER_KEYDATA_OFFSET, MASTER_KEYDATA_SIZE)) + continue; + + // Now we have the correct password, cipher, hash algorithm, and volume type + + // Check the version required to handle this volume + if (!truecryptMode && (cryptoInfo->RequiredProgramVersion > VERSION_NUM)) + { + status = ERR_NEW_VERSION_REQUIRED; + goto err; + } + + // Header version + cryptoInfo->HeaderVersion = headerVersion; + + // Volume creation time (legacy) + cryptoInfo->volume_creation_time = GetHeaderField64 (header, TC_HEADER_OFFSET_VOLUME_CREATION_TIME).Value; + + // Header creation time (legacy) + cryptoInfo->header_creation_time = GetHeaderField64 (header, TC_HEADER_OFFSET_MODIFICATION_TIME).Value; + + // Hidden volume size (if any) + cryptoInfo->hiddenVolumeSize = GetHeaderField64 (header, TC_HEADER_OFFSET_HIDDEN_VOLUME_SIZE).Value; + + // Hidden volume status + cryptoInfo->hiddenVolume = (cryptoInfo->hiddenVolumeSize != 0); + + // Volume size + cryptoInfo->VolumeSize = GetHeaderField64 (header, TC_HEADER_OFFSET_VOLUME_SIZE); + + // Encrypted area size and length + cryptoInfo->EncryptedAreaStart = GetHeaderField64 (header, TC_HEADER_OFFSET_ENCRYPTED_AREA_START); + cryptoInfo->EncryptedAreaLength = GetHeaderField64 (header, TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH); + + // Flags + cryptoInfo->HeaderFlags = GetHeaderField32 (header, TC_HEADER_OFFSET_FLAGS); + + // Sector size + if (headerVersion >= 5) + cryptoInfo->SectorSize = GetHeaderField32 (header, TC_HEADER_OFFSET_SECTOR_SIZE); + else + cryptoInfo->SectorSize = TC_SECTOR_SIZE_LEGACY; + + if (cryptoInfo->SectorSize < TC_MIN_VOLUME_SECTOR_SIZE + || cryptoInfo->SectorSize > TC_MAX_VOLUME_SECTOR_SIZE + || cryptoInfo->SectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0) + { + status = ERR_PARAMETER_INCORRECT; + goto err; + } + + // Preserve scheduled header keys if requested + if (retHeaderCryptoInfo) + { + if (retInfo == NULL) + { + cryptoInfo->pkcs5 = pkcs5_prf; + cryptoInfo->noIterations = keyInfo.noIterations; + cryptoInfo->bTrueCryptMode = truecryptMode; + cryptoInfo->volumePim = pim; + goto ret; + } + + cryptoInfo = *retInfo = crypto_open (); + if (cryptoInfo == NULL) + { + status = ERR_OUTOFMEMORY; + goto err; + } + + memcpy (cryptoInfo, retHeaderCryptoInfo, sizeof (*cryptoInfo)); + } + + // Master key data + memcpy (keyInfo.master_keydata, header + HEADER_MASTER_KEYDATA_OFFSET, MASTER_KEYDATA_SIZE); + memcpy (cryptoInfo->master_keydata, keyInfo.master_keydata, MASTER_KEYDATA_SIZE); + + // PKCS #5 + memcpy (cryptoInfo->salt, keyInfo.salt, PKCS5_SALT_SIZE); + cryptoInfo->pkcs5 = pkcs5_prf; + cryptoInfo->noIterations = keyInfo.noIterations; + cryptoInfo->bTrueCryptMode = truecryptMode; + cryptoInfo->volumePim = pim; + + // Init the cipher with the decrypted master key + status = EAInit (cryptoInfo->ea, keyInfo.master_keydata + primaryKeyOffset, cryptoInfo->ks); + if (status == ERR_CIPHER_INIT_FAILURE) + goto err; + + switch (cryptoInfo->mode) + { + + default: + // The secondary master key (if cascade, multiple concatenated) + memcpy (cryptoInfo->k2, keyInfo.master_keydata + EAGetKeySize (cryptoInfo->ea), EAGetKeySize (cryptoInfo->ea)); + + } + + if (!EAInitMode (cryptoInfo)) + { + status = ERR_MODE_INIT_FAILED; + goto err; + } + + status = ERR_SUCCESS; + goto ret; + } + } + } + status = ERR_PASSWORD_WRONG; + +err: + if (cryptoInfo != retHeaderCryptoInfo) + { + crypto_close(cryptoInfo); + *retInfo = NULL; + } + +ret: + burn (&keyInfo, sizeof (keyInfo)); + burn (dk, sizeof(dk)); + +#ifndef DEVICE_DRIVER + VirtualUnlock (&keyInfo, sizeof (keyInfo)); + VirtualUnlock (&dk, sizeof (dk)); +#endif + + if ((selected_pkcs5_prf == 0) && (encryptionThreadCount > 1)) + { + TC_WAIT_EVENT (noOutstandingWorkItemEvent); + + burn (keyDerivationWorkItems, sizeof (KeyDerivationWorkItem) * pkcs5PrfCount); + TCfree (keyDerivationWorkItems); + +#ifndef DEVICE_DRIVER + CloseHandle (keyDerivationCompletedEvent); + CloseHandle (noOutstandingWorkItemEvent); +#endif + } + + return status; +} + +#ifdef _WIN32 +void ComputeBootloaderFingerprint (byte *bootLoaderBuf, unsigned int bootLoaderSize, byte* fingerprint) +{ + // compute Whirlpool+SHA512 fingerprint of bootloader including MBR + // we skip user configuration fields: + // TC_BOOT_SECTOR_PIM_VALUE_OFFSET = 400 + // TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET = 402 + // => TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE = 4 + // TC_BOOT_SECTOR_USER_MESSAGE_OFFSET = 406 + // => TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH = 24 + // TC_BOOT_SECTOR_USER_CONFIG_OFFSET = 438 + // + // we have: TC_BOOT_SECTOR_USER_MESSAGE_OFFSET = TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE + + WHIRLPOOL_CTX whirlpool; + sha512_ctx sha2; + + WHIRLPOOL_init (&whirlpool); + sha512_begin (&sha2); + + WHIRLPOOL_add (bootLoaderBuf, TC_BOOT_SECTOR_PIM_VALUE_OFFSET * 8, &whirlpool); + sha512_hash (bootLoaderBuf, TC_BOOT_SECTOR_PIM_VALUE_OFFSET, &sha2); + + WHIRLPOOL_add (bootLoaderBuf + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH, (TC_BOOT_SECTOR_USER_CONFIG_OFFSET - (TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH)) * 8, &whirlpool); + sha512_hash (bootLoaderBuf + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH, (TC_BOOT_SECTOR_USER_CONFIG_OFFSET - (TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH)), &sha2); + + WHIRLPOOL_add (bootLoaderBuf + TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1, (TC_MAX_MBR_BOOT_CODE_SIZE - (TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1)) * 8, &whirlpool); + sha512_hash (bootLoaderBuf + TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1, (TC_MAX_MBR_BOOT_CODE_SIZE - (TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1)), &sha2); + + WHIRLPOOL_add (bootLoaderBuf + TC_SECTOR_SIZE_BIOS, (bootLoaderSize - TC_SECTOR_SIZE_BIOS) * 8, &whirlpool); + sha512_hash (bootLoaderBuf + TC_SECTOR_SIZE_BIOS, (bootLoaderSize - TC_SECTOR_SIZE_BIOS), &sha2); + + WHIRLPOOL_finalize (&whirlpool, fingerprint); + sha512_end (&fingerprint [WHIRLPOOL_DIGESTSIZE], &sha2); +} +#endif + +#else // TC_WINDOWS_BOOT + +int ReadVolumeHeader (BOOL bBoot, char *header, Password *password, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo) +{ +#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + char dk[32 * 2]; // 2 * 256-bit key +#else + char dk[32 * 2 * 3]; // 6 * 256-bit key +#endif + + PCRYPTO_INFO cryptoInfo; + int status = ERR_SUCCESS; + uint32 iterations = pim; + iterations <<= 16; + iterations |= bBoot; + + if (retHeaderCryptoInfo != NULL) + cryptoInfo = retHeaderCryptoInfo; + else + cryptoInfo = *retInfo = crypto_open (); + + // PKCS5 PRF +#ifdef TC_WINDOWS_BOOT_SHA2 + derive_key_sha256 (password->Text, (int) password->Length, header + HEADER_SALT_OFFSET, + PKCS5_SALT_SIZE, iterations, dk, sizeof (dk)); +#else + derive_key_ripemd160 (password->Text, (int) password->Length, header + HEADER_SALT_OFFSET, + PKCS5_SALT_SIZE, iterations, dk, sizeof (dk)); +#endif + + // Mode of operation + cryptoInfo->mode = FIRST_MODE_OF_OPERATION_ID; + +#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + cryptoInfo->ea = 1; +#else + // Test all available encryption algorithms + for (cryptoInfo->ea = EAGetFirst (); cryptoInfo->ea != 0; cryptoInfo->ea = EAGetNext (cryptoInfo->ea)) +#endif + { +#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + #if defined (TC_WINDOWS_BOOT_SERPENT) + serpent_set_key (dk, cryptoInfo->ks); + #elif defined (TC_WINDOWS_BOOT_TWOFISH) + twofish_set_key ((TwofishInstance *) cryptoInfo->ks, (const u4byte *) dk); + #else + status = EAInit (dk, cryptoInfo->ks); + if (status == ERR_CIPHER_INIT_FAILURE) + goto err; + #endif +#else + status = EAInit (cryptoInfo->ea, dk, cryptoInfo->ks); + if (status == ERR_CIPHER_INIT_FAILURE) + goto err; +#endif + // Secondary key schedule +#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + #if defined (TC_WINDOWS_BOOT_SERPENT) + serpent_set_key (dk + 32, cryptoInfo->ks2); + #elif defined (TC_WINDOWS_BOOT_TWOFISH) + twofish_set_key ((TwofishInstance *)cryptoInfo->ks2, (const u4byte *) (dk + 32)); + #else + EAInit (dk + 32, cryptoInfo->ks2); + #endif +#else + EAInit (cryptoInfo->ea, dk + EAGetKeySize (cryptoInfo->ea), cryptoInfo->ks2); +#endif + + // Try to decrypt header + DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo); + + // Check magic 'VERA' and CRC-32 of header fields and master keydata + if (GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x56455241 + || (GetHeaderField16 (header, TC_HEADER_OFFSET_VERSION) >= 4 && GetHeaderField32 (header, TC_HEADER_OFFSET_HEADER_CRC) != GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC)) + || GetHeaderField32 (header, TC_HEADER_OFFSET_KEY_AREA_CRC) != GetCrc32 (header + HEADER_MASTER_KEYDATA_OFFSET, MASTER_KEYDATA_SIZE)) + { + EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo); +#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + status = ERR_PASSWORD_WRONG; + goto err; +#else + continue; +#endif + } + + // Header decrypted + status = 0; + + // Hidden volume status + cryptoInfo->VolumeSize = GetHeaderField64 (header, TC_HEADER_OFFSET_HIDDEN_VOLUME_SIZE); + cryptoInfo->hiddenVolume = (cryptoInfo->VolumeSize.LowPart != 0 || cryptoInfo->VolumeSize.HighPart != 0); + + // Volume size + cryptoInfo->VolumeSize = GetHeaderField64 (header, TC_HEADER_OFFSET_VOLUME_SIZE); + + // Encrypted area size and length + cryptoInfo->EncryptedAreaStart = GetHeaderField64 (header, TC_HEADER_OFFSET_ENCRYPTED_AREA_START); + cryptoInfo->EncryptedAreaLength = GetHeaderField64 (header, TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH); + + // Flags + cryptoInfo->HeaderFlags = GetHeaderField32 (header, TC_HEADER_OFFSET_FLAGS); + +#ifdef TC_WINDOWS_BOOT_SHA2 + cryptoInfo->pkcs5 = SHA256; +#else + cryptoInfo->pkcs5 = RIPEMD160; +#endif + + memcpy (dk, header + HEADER_MASTER_KEYDATA_OFFSET, sizeof (dk)); + EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo); + + if (retHeaderCryptoInfo) + goto ret; + + // Init the encryption algorithm with the decrypted master key +#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + #if defined (TC_WINDOWS_BOOT_SERPENT) + serpent_set_key (dk, cryptoInfo->ks); + #elif defined (TC_WINDOWS_BOOT_TWOFISH) + twofish_set_key ((TwofishInstance *) cryptoInfo->ks, (const u4byte *) dk); + #else + status = EAInit (dk, cryptoInfo->ks); + if (status == ERR_CIPHER_INIT_FAILURE) + goto err; + #endif +#else + status = EAInit (cryptoInfo->ea, dk, cryptoInfo->ks); + if (status == ERR_CIPHER_INIT_FAILURE) + goto err; +#endif + + // The secondary master key (if cascade, multiple concatenated) +#ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE + #if defined (TC_WINDOWS_BOOT_SERPENT) + serpent_set_key (dk + 32, cryptoInfo->ks2); + #elif defined (TC_WINDOWS_BOOT_TWOFISH) + twofish_set_key ((TwofishInstance *)cryptoInfo->ks2, (const u4byte *) (dk + 32)); + #else + EAInit (dk + 32, cryptoInfo->ks2); + #endif +#else + EAInit (cryptoInfo->ea, dk + EAGetKeySize (cryptoInfo->ea), cryptoInfo->ks2); +#endif + goto ret; + } + + status = ERR_PASSWORD_WRONG; + +err: + if (cryptoInfo != retHeaderCryptoInfo) + { + crypto_close(cryptoInfo); + *retInfo = NULL; + } + +ret: + burn (dk, sizeof(dk)); + return status; +} + +#endif // TC_WINDOWS_BOOT + + +#if !defined (DEVICE_DRIVER) && !defined (TC_WINDOWS_BOOT) + +#ifdef VOLFORMAT +# include "../Format/TcFormat.h" +# include "Dlgcode.h" +#endif + +// Creates a volume header in memory +int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, char *header, int ea, int mode, Password *password, + int pkcs5_prf, int pim, char *masterKeydata, PCRYPTO_INFO *retInfo, + unsigned __int64 volumeSize, unsigned __int64 hiddenVolumeSize, + unsigned __int64 encryptedAreaStart, unsigned __int64 encryptedAreaLength, uint16 requiredProgramVersion, uint32 headerFlags, uint32 sectorSize, BOOL bWipeMode) +{ + unsigned char *p = (unsigned char *) header; + static CRYPTOPP_ALIGN_DATA(16) KEY_INFO keyInfo; + + int nUserKeyLen = password->Length; + PCRYPTO_INFO cryptoInfo = crypto_open (); + static char dk[MASTER_KEYDATA_SIZE]; + int x; + int retVal = 0; + int primaryKeyOffset; + + if (cryptoInfo == NULL) + return ERR_OUTOFMEMORY; + + // if no PIM specified, use default value + if (pim < 0) + pim = 0; + + memset (header, 0, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + + VirtualLock (&keyInfo, sizeof (keyInfo)); + VirtualLock (&dk, sizeof (dk)); + + /* Encryption setup */ + + if (masterKeydata == NULL) + { + // We have no master key data (creating a new volume) so we'll use the TrueCrypt RNG to generate them + + int bytesNeeded; + + switch (mode) + { + + default: + bytesNeeded = EAGetKeySize (ea) * 2; // Size of primary + secondary key(s) + } + + if (!RandgetBytes (hwndDlg, keyInfo.master_keydata, bytesNeeded, TRUE)) + return ERR_CIPHER_INIT_WEAK_KEY; + } + else + { + // We already have existing master key data (the header is being re-encrypted) + memcpy (keyInfo.master_keydata, masterKeydata, MASTER_KEYDATA_SIZE); + } + + // User key + memcpy (keyInfo.userKey, password->Text, nUserKeyLen); + keyInfo.keyLength = nUserKeyLen; + keyInfo.noIterations = get_pkcs5_iteration_count (pkcs5_prf, pim, FALSE, bBoot); + + // User selected encryption algorithm + cryptoInfo->ea = ea; + + // User selected PRF + cryptoInfo->pkcs5 = pkcs5_prf; + cryptoInfo->bTrueCryptMode = FALSE; + cryptoInfo->noIterations = keyInfo.noIterations; + cryptoInfo->volumePim = pim; + + // Mode of operation + cryptoInfo->mode = mode; + + // Salt for header key derivation + if (!RandgetBytes (hwndDlg, keyInfo.salt, PKCS5_SALT_SIZE, !bWipeMode)) + return ERR_CIPHER_INIT_WEAK_KEY; + + // PBKDF2 (PKCS5) is used to derive primary header key(s) and secondary header key(s) (XTS) from the password/keyfiles + switch (pkcs5_prf) + { + case SHA512: + derive_key_sha512 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, + PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); + break; + + case SHA256: + derive_key_sha256 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, + PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); + break; + + case RIPEMD160: + derive_key_ripemd160 (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, + PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); + break; + + case WHIRLPOOL: + derive_key_whirlpool (keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, + PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); + break; + + default: + // Unknown/wrong ID + TC_THROW_FATAL_EXCEPTION; + } + + /* Header setup */ + + // Salt + mputBytes (p, keyInfo.salt, PKCS5_SALT_SIZE); + + // Magic + mputLong (p, 0x56455241); + + // Header version + mputWord (p, VOLUME_HEADER_VERSION); + cryptoInfo->HeaderVersion = VOLUME_HEADER_VERSION; + + // Required program version to handle this volume + mputWord (p, requiredProgramVersion != 0 ? requiredProgramVersion : TC_VOLUME_MIN_REQUIRED_PROGRAM_VERSION); + + // CRC of the master key data + x = GetCrc32(keyInfo.master_keydata, MASTER_KEYDATA_SIZE); + mputLong (p, x); + + // Reserved fields + p += 2 * 8; + + // Size of hidden volume (if any) + cryptoInfo->hiddenVolumeSize = hiddenVolumeSize; + mputInt64 (p, cryptoInfo->hiddenVolumeSize); + + cryptoInfo->hiddenVolume = cryptoInfo->hiddenVolumeSize != 0; + + // Volume size + cryptoInfo->VolumeSize.Value = volumeSize; + mputInt64 (p, volumeSize); + + // Encrypted area start + cryptoInfo->EncryptedAreaStart.Value = encryptedAreaStart; + mputInt64 (p, encryptedAreaStart); + + // Encrypted area size + cryptoInfo->EncryptedAreaLength.Value = encryptedAreaLength; + mputInt64 (p, encryptedAreaLength); + + // Flags + cryptoInfo->HeaderFlags = headerFlags; + mputLong (p, headerFlags); + + // Sector size + if (sectorSize < TC_MIN_VOLUME_SECTOR_SIZE + || sectorSize > TC_MAX_VOLUME_SECTOR_SIZE + || sectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0) + { + TC_THROW_FATAL_EXCEPTION; + } + + cryptoInfo->SectorSize = sectorSize; + mputLong (p, sectorSize); + + // CRC of the header fields + x = GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC); + p = header + TC_HEADER_OFFSET_HEADER_CRC; + mputLong (p, x); + + // The master key data + memcpy (header + HEADER_MASTER_KEYDATA_OFFSET, keyInfo.master_keydata, MASTER_KEYDATA_SIZE); + + + /* Header encryption */ + + switch (mode) + { + + default: + // The secondary key (if cascade, multiple concatenated) + memcpy (cryptoInfo->k2, dk + EAGetKeySize (cryptoInfo->ea), EAGetKeySize (cryptoInfo->ea)); + primaryKeyOffset = 0; + } + + retVal = EAInit (cryptoInfo->ea, dk + primaryKeyOffset, cryptoInfo->ks); + if (retVal != ERR_SUCCESS) + return retVal; + + // Mode of operation + if (!EAInitMode (cryptoInfo)) + return ERR_OUTOFMEMORY; + + + // Encrypt the entire header (except the salt) + EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, + HEADER_ENCRYPTED_DATA_SIZE, + cryptoInfo); + + + /* cryptoInfo setup for further use (disk format) */ + + // Init with the master key(s) + retVal = EAInit (cryptoInfo->ea, keyInfo.master_keydata + primaryKeyOffset, cryptoInfo->ks); + if (retVal != ERR_SUCCESS) + return retVal; + + memcpy (cryptoInfo->master_keydata, keyInfo.master_keydata, MASTER_KEYDATA_SIZE); + + switch (cryptoInfo->mode) + { + + default: + // The secondary master key (if cascade, multiple concatenated) + memcpy (cryptoInfo->k2, keyInfo.master_keydata + EAGetKeySize (cryptoInfo->ea), EAGetKeySize (cryptoInfo->ea)); + } + + // Mode of operation + if (!EAInitMode (cryptoInfo)) + return ERR_OUTOFMEMORY; + + +#ifdef VOLFORMAT + if (!bInPlaceEncNonSys && (showKeys || (bBoot && !masterKeydata))) + { + BOOL dots3 = FALSE; + int i, j; + + j = EAGetKeySize (ea); + + if (j > NBR_KEY_BYTES_TO_DISPLAY) + { + dots3 = TRUE; + j = NBR_KEY_BYTES_TO_DISPLAY; + } + + MasterKeyGUIView[0] = 0; + for (i = 0; i < j; i++) + { + wchar_t tmp2[8] = {0}; + StringCchPrintfW (tmp2, ARRAYSIZE(tmp2), L"%02X", (int) (unsigned char) keyInfo.master_keydata[i + primaryKeyOffset]); + StringCchCatW (MasterKeyGUIView, ARRAYSIZE(MasterKeyGUIView), tmp2); + } + + HeaderKeyGUIView[0] = 0; + for (i = 0; i < NBR_KEY_BYTES_TO_DISPLAY; i++) + { + wchar_t tmp2[8]; + StringCchPrintfW (tmp2, ARRAYSIZE(tmp2), L"%02X", (int) (unsigned char) dk[primaryKeyOffset + i]); + StringCchCatW (HeaderKeyGUIView, ARRAYSIZE(HeaderKeyGUIView), tmp2); + } + + if (dots3) + { + DisplayPortionsOfKeys (hHeaderKey, hMasterKey, HeaderKeyGUIView, MasterKeyGUIView, !showKeys); + } + else + { + SendMessage (hMasterKey, WM_SETTEXT, 0, (LPARAM) MasterKeyGUIView); + SendMessage (hHeaderKey, WM_SETTEXT, 0, (LPARAM) HeaderKeyGUIView); + } + } +#endif // #ifdef VOLFORMAT + + burn (dk, sizeof(dk)); + burn (&keyInfo, sizeof (keyInfo)); + + *retInfo = cryptoInfo; + return 0; +} + + +BOOL ReadEffectiveVolumeHeader (BOOL device, HANDLE fileHandle, byte *header, DWORD *bytesRead) +{ +#if TC_VOLUME_HEADER_EFFECTIVE_SIZE > TC_MAX_VOLUME_SECTOR_SIZE +#error TC_VOLUME_HEADER_EFFECTIVE_SIZE > TC_MAX_VOLUME_SECTOR_SIZE +#endif + + byte sectorBuffer[TC_MAX_VOLUME_SECTOR_SIZE]; + DISK_GEOMETRY geometry; + + if (!device) + return ReadFile (fileHandle, header, TC_VOLUME_HEADER_EFFECTIVE_SIZE, bytesRead, NULL); + + if (!DeviceIoControl (fileHandle, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &geometry, sizeof (geometry), bytesRead, NULL)) + return FALSE; + + if (geometry.BytesPerSector > sizeof (sectorBuffer) || geometry.BytesPerSector < TC_MIN_VOLUME_SECTOR_SIZE) + { + SetLastError (ERROR_INVALID_PARAMETER); + return FALSE; + } + + if (!ReadFile (fileHandle, sectorBuffer, max (TC_VOLUME_HEADER_EFFECTIVE_SIZE, geometry.BytesPerSector), bytesRead, NULL)) + return FALSE; + + memcpy (header, sectorBuffer, min (*bytesRead, TC_VOLUME_HEADER_EFFECTIVE_SIZE)); + + if (*bytesRead > TC_VOLUME_HEADER_EFFECTIVE_SIZE) + *bytesRead = TC_VOLUME_HEADER_EFFECTIVE_SIZE; + + return TRUE; +} + + +BOOL WriteEffectiveVolumeHeader (BOOL device, HANDLE fileHandle, byte *header) +{ +#if TC_VOLUME_HEADER_EFFECTIVE_SIZE > TC_MAX_VOLUME_SECTOR_SIZE +#error TC_VOLUME_HEADER_EFFECTIVE_SIZE > TC_MAX_VOLUME_SECTOR_SIZE +#endif + + byte sectorBuffer[TC_MAX_VOLUME_SECTOR_SIZE]; + DWORD bytesDone; + DISK_GEOMETRY geometry; + + if (!device) + { + if (!WriteFile (fileHandle, header, TC_VOLUME_HEADER_EFFECTIVE_SIZE, &bytesDone, NULL)) + return FALSE; + + if (bytesDone != TC_VOLUME_HEADER_EFFECTIVE_SIZE) + { + SetLastError (ERROR_INVALID_PARAMETER); + return FALSE; + } + + return TRUE; + } + + if (!DeviceIoControl (fileHandle, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &geometry, sizeof (geometry), &bytesDone, NULL)) + return FALSE; + + if (geometry.BytesPerSector > sizeof (sectorBuffer) || geometry.BytesPerSector < TC_MIN_VOLUME_SECTOR_SIZE) + { + SetLastError (ERROR_INVALID_PARAMETER); + return FALSE; + } + + if (geometry.BytesPerSector != TC_VOLUME_HEADER_EFFECTIVE_SIZE) + { + LARGE_INTEGER seekOffset; + + if (!ReadFile (fileHandle, sectorBuffer, geometry.BytesPerSector, &bytesDone, NULL)) + return FALSE; + + if (bytesDone != geometry.BytesPerSector) + { + SetLastError (ERROR_INVALID_PARAMETER); + return FALSE; + } + + seekOffset.QuadPart = -(int) bytesDone; + if (!SetFilePointerEx (fileHandle, seekOffset, NULL, FILE_CURRENT)) + return FALSE; + } + + memcpy (sectorBuffer, header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + + if (!WriteFile (fileHandle, sectorBuffer, geometry.BytesPerSector, &bytesDone, NULL)) + return FALSE; + + if (bytesDone != geometry.BytesPerSector) + { + SetLastError (ERROR_INVALID_PARAMETER); + return FALSE; + } + + return TRUE; +} + + +// Writes randomly generated data to unused/reserved header areas. +// When bPrimaryOnly is TRUE, then only the primary header area (not the backup header area) is filled with random data. +// When bBackupOnly is TRUE, only the backup header area (not the primary header area) is filled with random data. +int WriteRandomDataToReservedHeaderAreas (HWND hwndDlg, HANDLE dev, CRYPTO_INFO *cryptoInfo, uint64 dataAreaSize, BOOL bPrimaryOnly, BOOL bBackupOnly) +{ + char temporaryKey[MASTER_KEYDATA_SIZE]; + char originalK2[MASTER_KEYDATA_SIZE]; + + byte buf[TC_VOLUME_HEADER_GROUP_SIZE]; + + LARGE_INTEGER offset; + int nStatus = ERR_SUCCESS; + DWORD dwError; + DWORD bytesDone; + BOOL backupHeaders = bBackupOnly; + + if (bPrimaryOnly && bBackupOnly) + TC_THROW_FATAL_EXCEPTION; + + memcpy (originalK2, cryptoInfo->k2, sizeof (cryptoInfo->k2)); + + while (TRUE) + { + // Temporary keys + if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (cryptoInfo->ea), FALSE) + || !RandgetBytes (hwndDlg, cryptoInfo->k2, sizeof (cryptoInfo->k2), FALSE)) + { + nStatus = ERR_PARAMETER_INCORRECT; + goto final_seq; + } + + nStatus = EAInit (cryptoInfo->ea, temporaryKey, cryptoInfo->ks); + if (nStatus != ERR_SUCCESS) + goto final_seq; + + if (!EAInitMode (cryptoInfo)) + { + nStatus = ERR_MODE_INIT_FAILED; + goto final_seq; + } + + offset.QuadPart = backupHeaders ? dataAreaSize + TC_VOLUME_HEADER_GROUP_SIZE : TC_VOLUME_HEADER_OFFSET; + + if (!SetFilePointerEx (dev, offset, NULL, FILE_BEGIN)) + { + nStatus = ERR_OS_ERROR; + goto final_seq; + } + + if (!ReadFile (dev, buf, sizeof (buf), &bytesDone, NULL)) + { + nStatus = ERR_OS_ERROR; + goto final_seq; + } + + if (bytesDone < TC_VOLUME_HEADER_EFFECTIVE_SIZE) + { + SetLastError (ERROR_INVALID_PARAMETER); + nStatus = ERR_OS_ERROR; + goto final_seq; + } + + EncryptBuffer (buf + TC_VOLUME_HEADER_EFFECTIVE_SIZE, sizeof (buf) - TC_VOLUME_HEADER_EFFECTIVE_SIZE, cryptoInfo); + + if (!SetFilePointerEx (dev, offset, NULL, FILE_BEGIN)) + { + nStatus = ERR_OS_ERROR; + goto final_seq; + } + + if (!WriteFile (dev, buf, sizeof (buf), &bytesDone, NULL)) + { + nStatus = ERR_OS_ERROR; + goto final_seq; + } + + if (bytesDone != sizeof (buf)) + { + nStatus = ERR_PARAMETER_INCORRECT; + goto final_seq; + } + + if (backupHeaders || bPrimaryOnly) + break; + + backupHeaders = TRUE; + } + + memcpy (cryptoInfo->k2, originalK2, sizeof (cryptoInfo->k2)); + + nStatus = EAInit (cryptoInfo->ea, cryptoInfo->master_keydata, cryptoInfo->ks); + if (nStatus != ERR_SUCCESS) + goto final_seq; + + if (!EAInitMode (cryptoInfo)) + { + nStatus = ERR_MODE_INIT_FAILED; + goto final_seq; + } + +final_seq: + + dwError = GetLastError(); + + burn (temporaryKey, sizeof (temporaryKey)); + burn (originalK2, sizeof (originalK2)); + + if (nStatus != ERR_SUCCESS) + SetLastError (dwError); + + return nStatus; +} + +#endif // !defined (DEVICE_DRIVER) && !defined (TC_WINDOWS_BOOT) diff --git a/src/Common/Volumes.h b/src/Common/Volumes.h index b0f295f3..43aaaf73 100644 --- a/src/Common/Volumes.h +++ b/src/Common/Volumes.h @@ -1,155 +1,155 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifndef TC_HEADER_Common_Volumes -#define TC_HEADER_Common_Volumes - -#ifdef __cplusplus -extern "C" { -#endif - -// Volume header version -#define VOLUME_HEADER_VERSION 0x0005 - -// Version number written to volume header during format; -// specifies the minimum program version required to mount the volume -#define TC_VOLUME_MIN_REQUIRED_PROGRAM_VERSION 0x010b - -// Version number written (encrypted) to the key data area of an encrypted system partition/drive; -// specifies the minimum program version required to decrypt the system partition/drive -#define TC_SYSENC_KEYSCOPE_MIN_REQ_PROG_VERSION 0x010b - -// Current volume format version (created by TrueCrypt 6.0+) -#define TC_VOLUME_FORMAT_VERSION 2 - -// Version number of volume format created by TrueCrypt 1.0-5.1a -#define TC_VOLUME_FORMAT_VERSION_PRE_6_0 1 - -// Volume header sizes -#define TC_VOLUME_HEADER_SIZE (64 * 1024L) -#define TC_VOLUME_HEADER_EFFECTIVE_SIZE 512 -#define TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE 512 -#define TC_VOLUME_HEADER_SIZE_LEGACY 512 - -#define TC_VOLUME_HEADER_GROUP_SIZE (2 * TC_VOLUME_HEADER_SIZE) -#define TC_TOTAL_VOLUME_HEADERS_SIZE (4 * TC_VOLUME_HEADER_SIZE) - -// Volume offsets -#define TC_VOLUME_HEADER_OFFSET 0 -#define TC_HIDDEN_VOLUME_HEADER_OFFSET TC_VOLUME_HEADER_SIZE - -// Sector sizes -#define TC_MIN_VOLUME_SECTOR_SIZE 512 -#define TC_MAX_VOLUME_SECTOR_SIZE 4096 -#define TC_SECTOR_SIZE_FILE_HOSTED_VOLUME 512 -#define TC_SECTOR_SIZE_LEGACY 512 - -// Sector size which can be safely assumed to be supported by all BIOSes -#define TC_SECTOR_SIZE_BIOS 512 - -#define TC_VOLUME_SMALL_SIZE_THRESHOLD (2 * BYTES_PER_MB) // Volume sizes below this threshold are considered small - -#define TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE TC_MAX_VOLUME_SECTOR_SIZE // FAT file system fills the last sector with zeroes (marked as free; observed when quick format was performed using the OS format tool). -#define TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH TC_VOLUME_HEADER_GROUP_SIZE // Reserved area size used for hidden volumes larger than TC_VOLUME_SMALL_SIZE_THRESHOLD - -#define TC_VOLUME_DATA_OFFSET TC_VOLUME_HEADER_GROUP_SIZE - -// The offset, in bytes, of the legacy hidden volume header position from the end of the file (a positive value). -#define TC_HIDDEN_VOLUME_HEADER_OFFSET_LEGACY (TC_VOLUME_HEADER_SIZE_LEGACY + TC_SECTOR_SIZE_LEGACY * 2) - -#define TC_MAX_128BIT_BLOCK_VOLUME_SIZE BYTES_PER_PB // Security bound (128-bit block XTS mode) - -// Filesystem size limits -#define TC_MIN_FAT_FS_SIZE (9 * TC_MAX_VOLUME_SECTOR_SIZE) -#define TC_MAX_FAT_SECTOR_COUNT 0x100000000ULL -#define TC_MIN_NTFS_FS_SIZE (884 * TC_MAX_VOLUME_SECTOR_SIZE) -#define TC_MAX_NTFS_FS_SIZE (128LL * BYTES_PER_TB) // NTFS volume can theoretically be up to 16 exabytes, but Windows XP and 2003 limit the size to that addressable with 32-bit clusters, i.e. max size is 128 TB (if 64-KB clusters are used). -#define TC_MAX_FAT_CLUSTER_SIZE (256 * BYTES_PER_KB) // Windows XP/Vista may crash when writing to a filesystem using clusters larger than 256 KB -#define TC_MIN_EXFAT_FS_SIZE (42 * TC_MAX_VOLUME_SECTOR_SIZE) -#define TC_MAX_EXFAT_FS_SIZE (128LL * BYTES_PER_PB) - -// Volume size limits -#define TC_MIN_VOLUME_SIZE (TC_TOTAL_VOLUME_HEADERS_SIZE + TC_MIN_FAT_FS_SIZE) -#define TC_MIN_VOLUME_SIZE_LEGACY (37 * TC_SECTOR_SIZE_LEGACY) -#define TC_MAX_VOLUME_SIZE_GENERAL 0x7fffFFFFffffFFFFLL // Signed 64-bit integer file offset values -#define TC_MAX_VOLUME_SIZE TC_MAX_128BIT_BLOCK_VOLUME_SIZE - -#define TC_MIN_HIDDEN_VOLUME_SIZE (TC_MIN_FAT_FS_SIZE + TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE) - -#define TC_MIN_HIDDEN_VOLUME_HOST_SIZE (TC_MIN_VOLUME_SIZE + TC_MIN_HIDDEN_VOLUME_SIZE + 2 * TC_MAX_VOLUME_SECTOR_SIZE) -#define TC_MAX_HIDDEN_VOLUME_HOST_SIZE (TC_MAX_NTFS_FS_SIZE - TC_TOTAL_VOLUME_HEADERS_SIZE) - -#ifndef TC_NO_COMPILER_INT64 -# if TC_MAX_VOLUME_SIZE > TC_MAX_VOLUME_SIZE_GENERAL -# error TC_MAX_VOLUME_SIZE > TC_MAX_VOLUME_SIZE_GENERAL -# endif -#endif - -#define HEADER_ENCRYPTED_DATA_SIZE (TC_VOLUME_HEADER_EFFECTIVE_SIZE - HEADER_ENCRYPTED_DATA_OFFSET) - -// Volume header field offsets -#define HEADER_SALT_OFFSET 0 -#define HEADER_ENCRYPTED_DATA_OFFSET PKCS5_SALT_SIZE -#define HEADER_MASTER_KEYDATA_OFFSET 256 - -#define TC_HEADER_OFFSET_MAGIC 64 -#define TC_HEADER_OFFSET_VERSION 68 -#define TC_HEADER_OFFSET_REQUIRED_VERSION 70 -#define TC_HEADER_OFFSET_KEY_AREA_CRC 72 -#define TC_HEADER_OFFSET_VOLUME_CREATION_TIME 76 -#define TC_HEADER_OFFSET_MODIFICATION_TIME 84 -#define TC_HEADER_OFFSET_HIDDEN_VOLUME_SIZE 92 -#define TC_HEADER_OFFSET_VOLUME_SIZE 100 -#define TC_HEADER_OFFSET_ENCRYPTED_AREA_START 108 -#define TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH 116 -#define TC_HEADER_OFFSET_FLAGS 124 -#define TC_HEADER_OFFSET_SECTOR_SIZE 128 -#define TC_HEADER_OFFSET_HEADER_CRC 252 - -// Volume header flags -#define TC_HEADER_FLAG_ENCRYPTED_SYSTEM 0x1 -#define TC_HEADER_FLAG_NONSYS_INPLACE_ENC 0x2 // The volume has been created (or is being encrypted/decrypted) using non-system in-place encryption - - -#ifndef TC_HEADER_Volume_VolumeHeader - -#include "Password.h" - -extern BOOL ReadVolumeHeaderRecoveryMode; - -uint16 GetHeaderField16 (byte *header, int offset); -uint32 GetHeaderField32 (byte *header, int offset); -UINT64_STRUCT GetHeaderField64 (byte *header, int offset); -#ifdef TC_WINDOWS_BOOT -int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo); -#else -int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, int pkcs5_prf, int pim, BOOL truecryptMode, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo); -#ifdef _WIN32 -void ComputeBootloaderFingerprint (byte *bootLoaderBuf, unsigned int bootLoaderSize, byte* fingerprint); -#endif -#endif - -#if !defined (DEVICE_DRIVER) && !defined (TC_WINDOWS_BOOT) -int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, char *encryptedHeader, int ea, int mode, Password *password, int pkcs5_prf, int pim, char *masterKeydata, PCRYPTO_INFO *retInfo, unsigned __int64 volumeSize, unsigned __int64 hiddenVolumeSize, unsigned __int64 encryptedAreaStart, unsigned __int64 encryptedAreaLength, uint16 requiredProgramVersion, uint32 headerFlags, uint32 sectorSize, BOOL bWipeMode); -BOOL ReadEffectiveVolumeHeader (BOOL device, HANDLE fileHandle, byte *header, DWORD *bytesRead); -BOOL WriteEffectiveVolumeHeader (BOOL device, HANDLE fileHandle, byte *header); -int WriteRandomDataToReservedHeaderAreas (HWND hwndDlg, HANDLE dev, CRYPTO_INFO *cryptoInfo, uint64 dataAreaSize, BOOL bPrimaryOnly, BOOL bBackupOnly); -#endif - -#endif // !TC_HEADER_Volume_VolumeHeader - -#ifdef __cplusplus -} -#endif - -#endif // TC_HEADER_Common_Volumes +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifndef TC_HEADER_Common_Volumes +#define TC_HEADER_Common_Volumes + +#ifdef __cplusplus +extern "C" { +#endif + +// Volume header version +#define VOLUME_HEADER_VERSION 0x0005 + +// Version number written to volume header during format; +// specifies the minimum program version required to mount the volume +#define TC_VOLUME_MIN_REQUIRED_PROGRAM_VERSION 0x010b + +// Version number written (encrypted) to the key data area of an encrypted system partition/drive; +// specifies the minimum program version required to decrypt the system partition/drive +#define TC_SYSENC_KEYSCOPE_MIN_REQ_PROG_VERSION 0x010b + +// Current volume format version (created by TrueCrypt 6.0+) +#define TC_VOLUME_FORMAT_VERSION 2 + +// Version number of volume format created by TrueCrypt 1.0-5.1a +#define TC_VOLUME_FORMAT_VERSION_PRE_6_0 1 + +// Volume header sizes +#define TC_VOLUME_HEADER_SIZE (64 * 1024L) +#define TC_VOLUME_HEADER_EFFECTIVE_SIZE 512 +#define TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE 512 +#define TC_VOLUME_HEADER_SIZE_LEGACY 512 + +#define TC_VOLUME_HEADER_GROUP_SIZE (2 * TC_VOLUME_HEADER_SIZE) +#define TC_TOTAL_VOLUME_HEADERS_SIZE (4 * TC_VOLUME_HEADER_SIZE) + +// Volume offsets +#define TC_VOLUME_HEADER_OFFSET 0 +#define TC_HIDDEN_VOLUME_HEADER_OFFSET TC_VOLUME_HEADER_SIZE + +// Sector sizes +#define TC_MIN_VOLUME_SECTOR_SIZE 512 +#define TC_MAX_VOLUME_SECTOR_SIZE 4096 +#define TC_SECTOR_SIZE_FILE_HOSTED_VOLUME 512 +#define TC_SECTOR_SIZE_LEGACY 512 + +// Sector size which can be safely assumed to be supported by all BIOSes +#define TC_SECTOR_SIZE_BIOS 512 + +#define TC_VOLUME_SMALL_SIZE_THRESHOLD (2 * BYTES_PER_MB) // Volume sizes below this threshold are considered small + +#define TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE TC_MAX_VOLUME_SECTOR_SIZE // FAT file system fills the last sector with zeroes (marked as free; observed when quick format was performed using the OS format tool). +#define TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH TC_VOLUME_HEADER_GROUP_SIZE // Reserved area size used for hidden volumes larger than TC_VOLUME_SMALL_SIZE_THRESHOLD + +#define TC_VOLUME_DATA_OFFSET TC_VOLUME_HEADER_GROUP_SIZE + +// The offset, in bytes, of the legacy hidden volume header position from the end of the file (a positive value). +#define TC_HIDDEN_VOLUME_HEADER_OFFSET_LEGACY (TC_VOLUME_HEADER_SIZE_LEGACY + TC_SECTOR_SIZE_LEGACY * 2) + +#define TC_MAX_128BIT_BLOCK_VOLUME_SIZE BYTES_PER_PB // Security bound (128-bit block XTS mode) + +// Filesystem size limits +#define TC_MIN_FAT_FS_SIZE (9 * TC_MAX_VOLUME_SECTOR_SIZE) +#define TC_MAX_FAT_SECTOR_COUNT 0x100000000ULL +#define TC_MIN_NTFS_FS_SIZE (884 * TC_MAX_VOLUME_SECTOR_SIZE) +#define TC_MAX_NTFS_FS_SIZE (128LL * BYTES_PER_TB) // NTFS volume can theoretically be up to 16 exabytes, but Windows XP and 2003 limit the size to that addressable with 32-bit clusters, i.e. max size is 128 TB (if 64-KB clusters are used). +#define TC_MAX_FAT_CLUSTER_SIZE (256 * BYTES_PER_KB) // Windows XP/Vista may crash when writing to a filesystem using clusters larger than 256 KB +#define TC_MIN_EXFAT_FS_SIZE (42 * TC_MAX_VOLUME_SECTOR_SIZE) +#define TC_MAX_EXFAT_FS_SIZE (128LL * BYTES_PER_PB) + +// Volume size limits +#define TC_MIN_VOLUME_SIZE (TC_TOTAL_VOLUME_HEADERS_SIZE + TC_MIN_FAT_FS_SIZE) +#define TC_MIN_VOLUME_SIZE_LEGACY (37 * TC_SECTOR_SIZE_LEGACY) +#define TC_MAX_VOLUME_SIZE_GENERAL 0x7fffFFFFffffFFFFLL // Signed 64-bit integer file offset values +#define TC_MAX_VOLUME_SIZE TC_MAX_128BIT_BLOCK_VOLUME_SIZE + +#define TC_MIN_HIDDEN_VOLUME_SIZE (TC_MIN_FAT_FS_SIZE + TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE) + +#define TC_MIN_HIDDEN_VOLUME_HOST_SIZE (TC_MIN_VOLUME_SIZE + TC_MIN_HIDDEN_VOLUME_SIZE + 2 * TC_MAX_VOLUME_SECTOR_SIZE) +#define TC_MAX_HIDDEN_VOLUME_HOST_SIZE (TC_MAX_NTFS_FS_SIZE - TC_TOTAL_VOLUME_HEADERS_SIZE) + +#ifndef TC_NO_COMPILER_INT64 +# if TC_MAX_VOLUME_SIZE > TC_MAX_VOLUME_SIZE_GENERAL +# error TC_MAX_VOLUME_SIZE > TC_MAX_VOLUME_SIZE_GENERAL +# endif +#endif + +#define HEADER_ENCRYPTED_DATA_SIZE (TC_VOLUME_HEADER_EFFECTIVE_SIZE - HEADER_ENCRYPTED_DATA_OFFSET) + +// Volume header field offsets +#define HEADER_SALT_OFFSET 0 +#define HEADER_ENCRYPTED_DATA_OFFSET PKCS5_SALT_SIZE +#define HEADER_MASTER_KEYDATA_OFFSET 256 + +#define TC_HEADER_OFFSET_MAGIC 64 +#define TC_HEADER_OFFSET_VERSION 68 +#define TC_HEADER_OFFSET_REQUIRED_VERSION 70 +#define TC_HEADER_OFFSET_KEY_AREA_CRC 72 +#define TC_HEADER_OFFSET_VOLUME_CREATION_TIME 76 +#define TC_HEADER_OFFSET_MODIFICATION_TIME 84 +#define TC_HEADER_OFFSET_HIDDEN_VOLUME_SIZE 92 +#define TC_HEADER_OFFSET_VOLUME_SIZE 100 +#define TC_HEADER_OFFSET_ENCRYPTED_AREA_START 108 +#define TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH 116 +#define TC_HEADER_OFFSET_FLAGS 124 +#define TC_HEADER_OFFSET_SECTOR_SIZE 128 +#define TC_HEADER_OFFSET_HEADER_CRC 252 + +// Volume header flags +#define TC_HEADER_FLAG_ENCRYPTED_SYSTEM 0x1 +#define TC_HEADER_FLAG_NONSYS_INPLACE_ENC 0x2 // The volume has been created (or is being encrypted/decrypted) using non-system in-place encryption + + +#ifndef TC_HEADER_Volume_VolumeHeader + +#include "Password.h" + +extern BOOL ReadVolumeHeaderRecoveryMode; + +uint16 GetHeaderField16 (byte *header, int offset); +uint32 GetHeaderField32 (byte *header, int offset); +UINT64_STRUCT GetHeaderField64 (byte *header, int offset); +#ifdef TC_WINDOWS_BOOT +int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo); +#else +int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, int pkcs5_prf, int pim, BOOL truecryptMode, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo); +#ifdef _WIN32 +void ComputeBootloaderFingerprint (byte *bootLoaderBuf, unsigned int bootLoaderSize, byte* fingerprint); +#endif +#endif + +#if !defined (DEVICE_DRIVER) && !defined (TC_WINDOWS_BOOT) +int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, char *encryptedHeader, int ea, int mode, Password *password, int pkcs5_prf, int pim, char *masterKeydata, PCRYPTO_INFO *retInfo, unsigned __int64 volumeSize, unsigned __int64 hiddenVolumeSize, unsigned __int64 encryptedAreaStart, unsigned __int64 encryptedAreaLength, uint16 requiredProgramVersion, uint32 headerFlags, uint32 sectorSize, BOOL bWipeMode); +BOOL ReadEffectiveVolumeHeader (BOOL device, HANDLE fileHandle, byte *header, DWORD *bytesRead); +BOOL WriteEffectiveVolumeHeader (BOOL device, HANDLE fileHandle, byte *header); +int WriteRandomDataToReservedHeaderAreas (HWND hwndDlg, HANDLE dev, CRYPTO_INFO *cryptoInfo, uint64 dataAreaSize, BOOL bPrimaryOnly, BOOL bBackupOnly); +#endif + +#endif // !TC_HEADER_Volume_VolumeHeader + +#ifdef __cplusplus +} +#endif + +#endif // TC_HEADER_Common_Volumes diff --git a/src/Common/Wipe.c b/src/Common/Wipe.c index 0dce3ace..83099547 100644 --- a/src/Common/Wipe.c +++ b/src/Common/Wipe.c @@ -1,198 +1,198 @@ -/* - 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 "Tcdefs.h" -#include "Wipe.h" - - -static BOOL Wipe1PseudoRandom (int pass, byte *buffer, size_t size) -{ - return FALSE; -} - - -// Fill buffer with wipe patterns defined in "National Industrial Security Program Operating Manual", US DoD 5220.22-M. -// Return: FALSE = buffer must be filled with random data - -static BOOL Wipe3Dod5220 (int pass, byte *buffer, size_t size) -{ - byte wipeChar; - - switch (pass) - { - case 1: - wipeChar = 0; - break; - - case 2: - wipeChar = 0xff; - break; - - default: - return FALSE; - } - - memset (buffer, wipeChar, size); - return TRUE; -} - - -static BOOL Wipe7Dod5220 (int pass, byte randChars[TC_WIPE_RAND_CHAR_COUNT], byte *buffer, size_t size) -{ - byte wipeChar; - - switch (pass) - { - case 1: - wipeChar = randChars[0]; - break; - - case 2: - wipeChar = ~randChars[0]; - break; - - case 4: - wipeChar = randChars[1]; - break; - - case 5: - wipeChar = randChars[2]; - break; - - case 6: - wipeChar = ~randChars[2]; - break; - - default: - return FALSE; - } - - memset (buffer, wipeChar, size); - return TRUE; -} - - -// Fill the buffer with wipe patterns defined in the paper "Secure Deletion of Data from Magnetic and Solid-State Memory" by Peter Gutmann. -// Return: FALSE = buffer must be filled with random data - -static BOOL Wipe35Gutmann (int pass, byte *buffer, size_t size) -{ - byte wipePat3[] = { 0x92, 0x49, 0x24 }; - int wipePat3Pos; - size_t i; - - switch (pass) - { - case 5: - memset (buffer, 0x55, size); - break; - - case 6: - memset (buffer, 0xaa, size); - break; - - case 7: - case 26: - case 29: - wipePat3Pos = 0; - goto wipe3; - - case 8: - case 27: - case 30: - wipePat3Pos = 1; - goto wipe3; - - case 9: - case 28: - case 31: - wipePat3Pos = 2; - goto wipe3; - -wipe3: - if (pass >= 29) - { - wipePat3[0] = ~wipePat3[0]; - wipePat3[1] = ~wipePat3[1]; - wipePat3[2] = ~wipePat3[2]; - } - - for (i = 0; i < size; ++i) - { - buffer[i] = wipePat3[wipePat3Pos++ % 3]; - } - break; - - default: - if (pass >= 10 && pass <= 25) - memset (buffer, (pass - 10) * 0x11, size); - else - return FALSE; - } - - return TRUE; -} - - -int GetWipePassCount (WipeAlgorithmId algorithm) -{ - switch (algorithm) - { - case TC_WIPE_1_RAND: - return 1; - - case TC_WIPE_3_DOD_5220: - return 3; - - case TC_WIPE_7_DOD_5220: - return 7; - - case TC_WIPE_35_GUTMANN: - return 35; - - case TC_WIPE_256: - return 256; - } - - return -1; // Prevent compiler warnings -} - - -BOOL WipeBuffer (WipeAlgorithmId algorithm, byte randChars[TC_WIPE_RAND_CHAR_COUNT], int pass, byte *buffer, size_t size) -{ - switch (algorithm) - { - case TC_WIPE_1_RAND: - case TC_WIPE_256: - return Wipe1PseudoRandom (pass, buffer, size); - - case TC_WIPE_3_DOD_5220: - return Wipe3Dod5220 (pass, buffer, size); - - case TC_WIPE_7_DOD_5220: - return Wipe7Dod5220 (pass, randChars, buffer, size); - - case TC_WIPE_35_GUTMANN: - return Wipe35Gutmann (pass, buffer, size); - - /* we will never reach here because all calls to WipeBuffer are preceeded - * by a call to GetWipePassCount that already checks the same algorithm - * parameters and in case of unsupported value an error is returned before - * calling WipeBuffer - */ - /* - default: - TC_THROW_FATAL_EXCEPTION;*/ - } - - return FALSE; // Prevent compiler warnings -} +/* + 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 "Tcdefs.h" +#include "Wipe.h" + + +static BOOL Wipe1PseudoRandom (int pass, byte *buffer, size_t size) +{ + return FALSE; +} + + +// Fill buffer with wipe patterns defined in "National Industrial Security Program Operating Manual", US DoD 5220.22-M. +// Return: FALSE = buffer must be filled with random data + +static BOOL Wipe3Dod5220 (int pass, byte *buffer, size_t size) +{ + byte wipeChar; + + switch (pass) + { + case 1: + wipeChar = 0; + break; + + case 2: + wipeChar = 0xff; + break; + + default: + return FALSE; + } + + memset (buffer, wipeChar, size); + return TRUE; +} + + +static BOOL Wipe7Dod5220 (int pass, byte randChars[TC_WIPE_RAND_CHAR_COUNT], byte *buffer, size_t size) +{ + byte wipeChar; + + switch (pass) + { + case 1: + wipeChar = randChars[0]; + break; + + case 2: + wipeChar = ~randChars[0]; + break; + + case 4: + wipeChar = randChars[1]; + break; + + case 5: + wipeChar = randChars[2]; + break; + + case 6: + wipeChar = ~randChars[2]; + break; + + default: + return FALSE; + } + + memset (buffer, wipeChar, size); + return TRUE; +} + + +// Fill the buffer with wipe patterns defined in the paper "Secure Deletion of Data from Magnetic and Solid-State Memory" by Peter Gutmann. +// Return: FALSE = buffer must be filled with random data + +static BOOL Wipe35Gutmann (int pass, byte *buffer, size_t size) +{ + byte wipePat3[] = { 0x92, 0x49, 0x24 }; + int wipePat3Pos; + size_t i; + + switch (pass) + { + case 5: + memset (buffer, 0x55, size); + break; + + case 6: + memset (buffer, 0xaa, size); + break; + + case 7: + case 26: + case 29: + wipePat3Pos = 0; + goto wipe3; + + case 8: + case 27: + case 30: + wipePat3Pos = 1; + goto wipe3; + + case 9: + case 28: + case 31: + wipePat3Pos = 2; + goto wipe3; + +wipe3: + if (pass >= 29) + { + wipePat3[0] = ~wipePat3[0]; + wipePat3[1] = ~wipePat3[1]; + wipePat3[2] = ~wipePat3[2]; + } + + for (i = 0; i < size; ++i) + { + buffer[i] = wipePat3[wipePat3Pos++ % 3]; + } + break; + + default: + if (pass >= 10 && pass <= 25) + memset (buffer, (pass - 10) * 0x11, size); + else + return FALSE; + } + + return TRUE; +} + + +int GetWipePassCount (WipeAlgorithmId algorithm) +{ + switch (algorithm) + { + case TC_WIPE_1_RAND: + return 1; + + case TC_WIPE_3_DOD_5220: + return 3; + + case TC_WIPE_7_DOD_5220: + return 7; + + case TC_WIPE_35_GUTMANN: + return 35; + + case TC_WIPE_256: + return 256; + } + + return -1; // Prevent compiler warnings +} + + +BOOL WipeBuffer (WipeAlgorithmId algorithm, byte randChars[TC_WIPE_RAND_CHAR_COUNT], int pass, byte *buffer, size_t size) +{ + switch (algorithm) + { + case TC_WIPE_1_RAND: + case TC_WIPE_256: + return Wipe1PseudoRandom (pass, buffer, size); + + case TC_WIPE_3_DOD_5220: + return Wipe3Dod5220 (pass, buffer, size); + + case TC_WIPE_7_DOD_5220: + return Wipe7Dod5220 (pass, randChars, buffer, size); + + case TC_WIPE_35_GUTMANN: + return Wipe35Gutmann (pass, buffer, size); + + /* we will never reach here because all calls to WipeBuffer are preceeded + * by a call to GetWipePassCount that already checks the same algorithm + * parameters and in case of unsupported value an error is returned before + * calling WipeBuffer + */ + /* + default: + TC_THROW_FATAL_EXCEPTION;*/ + } + + return FALSE; // Prevent compiler warnings +} diff --git a/src/Common/Wipe.h b/src/Common/Wipe.h index 82afe5fd..97011085 100644 --- a/src/Common/Wipe.h +++ b/src/Common/Wipe.h @@ -1,45 +1,45 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Common_Wipe -#define TC_HEADER_Common_Wipe - -#include "Tcdefs.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum -{ - /* WARNING: As these values are written to config files, if they or their meanings - are changed, incompatiblity with other versions may arise (upgrade, downgrade, etc.). - When adding a new constant, verify that the value is unique within this block. */ - TC_WIPE_NONE = 0, - TC_WIPE_1_RAND = 100, - TC_WIPE_3_DOD_5220 = 300, - TC_WIPE_7_DOD_5220 = 700, - TC_WIPE_35_GUTMANN = 3500, - TC_WIPE_256 = 25600 - -} WipeAlgorithmId; - -#define TC_WIPE_RAND_CHAR_COUNT 3 - -int GetWipePassCount (WipeAlgorithmId algorithm); -BOOL WipeBuffer (WipeAlgorithmId algorithm, byte randChars[TC_WIPE_RAND_CHAR_COUNT], int pass, byte *buffer, size_t size); - -#ifdef __cplusplus -} -#endif - -#endif // TC_HEADER_Common_Wipe +/* + 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. +*/ + +#ifndef TC_HEADER_Common_Wipe +#define TC_HEADER_Common_Wipe + +#include "Tcdefs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum +{ + /* WARNING: As these values are written to config files, if they or their meanings + are changed, incompatiblity with other versions may arise (upgrade, downgrade, etc.). + When adding a new constant, verify that the value is unique within this block. */ + TC_WIPE_NONE = 0, + TC_WIPE_1_RAND = 100, + TC_WIPE_3_DOD_5220 = 300, + TC_WIPE_7_DOD_5220 = 700, + TC_WIPE_35_GUTMANN = 3500, + TC_WIPE_256 = 25600 + +} WipeAlgorithmId; + +#define TC_WIPE_RAND_CHAR_COUNT 3 + +int GetWipePassCount (WipeAlgorithmId algorithm); +BOOL WipeBuffer (WipeAlgorithmId algorithm, byte randChars[TC_WIPE_RAND_CHAR_COUNT], int pass, byte *buffer, size_t size); + +#ifdef __cplusplus +} +#endif + +#endif // TC_HEADER_Common_Wipe diff --git a/src/Common/Xml.c b/src/Common/Xml.c index d6eb0276..60dd8266 100644 --- a/src/Common/Xml.c +++ b/src/Common/Xml.c @@ -1,268 +1,268 @@ -/* - 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 -#include -#include "Xml.h" - - -static BOOL BeginsWith (char *string, char *subString) -{ - while (*string++ == *subString++) - { - if (*subString == 0) return TRUE; - if (*string == 0) return FALSE; - } - - return FALSE; -} - - -char *XmlNextNode (char *xmlNode) -{ - char *t = xmlNode + 1; - while ((t = strchr (t, '<')) != NULL) - { - if (t[1] != '/') - return t; - - t++; - } - - return NULL; -} - - -char *XmlFindElement (char *xmlNode, char *nodeName) -{ - char *t = xmlNode; - size_t nameLen = strlen (nodeName); - - do - { - if (BeginsWith (t + 1, nodeName) - && (t[nameLen + 1] == '>' - || t[nameLen + 1] == ' ')) return t; - - } while (t = XmlNextNode (t)); - - return NULL; -} - - -char *XmlFindElementByAttributeValue (char *xml, char *nodeName, char *attrName, char *attrValue) -{ - char attr[2048]; - - while (xml = XmlFindElement (xml, nodeName)) - { - XmlGetAttributeText (xml, attrName, attr, sizeof (attr)); - if (strcmp (attr, attrValue) == 0) - return xml; - - xml++; - } - - return NULL; -} - - -char *XmlGetAttributeText (char *xmlNode, char *xmlAttrName, char *xmlAttrValue, int xmlAttrValueSize) -{ - char *t = xmlNode; - char *e = xmlNode; - int l = 0; - - xmlAttrValue[0] = 0; - if (t[0] != '<') return NULL; - - e = strchr (e, '>'); - if (e == NULL) return NULL; - - while ((t = strstr (t, xmlAttrName)) && t < e) - { - char *o = t + strlen (xmlAttrName); - if (t[-1] == ' ' - && - (BeginsWith (o, "=\"") - || BeginsWith (o, "= \"") - || BeginsWith (o, " =\"") - || BeginsWith (o, " = \"")) - ) - break; - - t++; - } - - if (t == NULL || t > e) return NULL; - - t = strchr (t, '"') + 1; - e = strchr (t, '"'); - l = (int)(e - t); - if (e == NULL || l > xmlAttrValueSize) return NULL; - - memcpy (xmlAttrValue, t, l); - xmlAttrValue[l] = 0; - - return xmlAttrValue; -} - - -char *XmlGetNodeText (char *xmlNode, char *xmlText, int xmlTextSize) -{ - char *t = xmlNode; - char *e = xmlNode + 1; - int l = 0, i = 0, j = 0; - - xmlText[0] = 0; - - if (t[0] != '<') - return NULL; - - t = strchr (t, '>') + 1; - if (t == (char *)1) return NULL; - - e = strchr (e, '<'); - if (e == NULL) return NULL; - - l = (int)(e - t); - if (e == NULL || l > xmlTextSize) return NULL; - - while (i < l) - { - if (BeginsWith (&t[i], "<")) - { - xmlText[j++] = '<'; - i += 4; - continue; - } - if (BeginsWith (&t[i], ">")) - { - xmlText[j++] = '>'; - i += 4; - continue; - } - if (BeginsWith (&t[i], "&")) - { - xmlText[j++] = '&'; - i += 5; - continue; - } - xmlText[j++] = t[i++]; - } - xmlText[j] = 0; - - return t; -} - - -char *XmlQuoteText (const char *textSrc, char *textDst, int textDstMaxSize) -{ - char *textDstLast = textDst + textDstMaxSize - 1; - - if (textDstMaxSize == 0) - return NULL; - - while (*textSrc != 0 && textDst <= textDstLast) - { - char c = *textSrc++; - switch (c) - { - case '&': - if (textDst + 6 > textDstLast) - return NULL; - strcpy (textDst, "&"); - textDst += 5; - continue; - - case '>': - if (textDst + 5 > textDstLast) - return NULL; - strcpy (textDst, ">"); - textDst += 4; - continue; - - case '<': - if (textDst + 5 > textDstLast) - return NULL; - strcpy (textDst, "<"); - textDst += 4; - continue; - - default: - *textDst++ = c; - } - } - - if (textDst > textDstLast) - return NULL; - - *textDst = 0; - return textDst; -} - -wchar_t *XmlQuoteTextW (const wchar_t *textSrc, wchar_t *textDst, int textDstMaxSize) -{ - wchar_t *textDstLast = textDst + textDstMaxSize - 1; - - if (textDstMaxSize == 0) - return NULL; - - while (*textSrc != 0 && textDst <= textDstLast) - { - wchar_t c = *textSrc++; - switch (c) - { - case L'&': - if (textDst + 6 > textDstLast) - return NULL; - wcscpy (textDst, L"&"); - textDst += 5; - continue; - - case L'>': - if (textDst + 5 > textDstLast) - return NULL; - wcscpy (textDst, L">"); - textDst += 4; - continue; - - case L'<': - if (textDst + 5 > textDstLast) - return NULL; - wcscpy (textDst, L"<"); - textDst += 4; - continue; - - default: - *textDst++ = c; - } - } - - if (textDst > textDstLast) - return NULL; - - *textDst = 0; - return textDst; -} - - -int XmlWriteHeader (FILE *file) -{ - return fputws (L"\n", file); -} - - -int XmlWriteFooter (FILE *file) -{ - return fputws (L"\n", file); -} +/* + 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 +#include +#include "Xml.h" + + +static BOOL BeginsWith (char *string, char *subString) +{ + while (*string++ == *subString++) + { + if (*subString == 0) return TRUE; + if (*string == 0) return FALSE; + } + + return FALSE; +} + + +char *XmlNextNode (char *xmlNode) +{ + char *t = xmlNode + 1; + while ((t = strchr (t, '<')) != NULL) + { + if (t[1] != '/') + return t; + + t++; + } + + return NULL; +} + + +char *XmlFindElement (char *xmlNode, char *nodeName) +{ + char *t = xmlNode; + size_t nameLen = strlen (nodeName); + + do + { + if (BeginsWith (t + 1, nodeName) + && (t[nameLen + 1] == '>' + || t[nameLen + 1] == ' ')) return t; + + } while (t = XmlNextNode (t)); + + return NULL; +} + + +char *XmlFindElementByAttributeValue (char *xml, char *nodeName, char *attrName, char *attrValue) +{ + char attr[2048]; + + while (xml = XmlFindElement (xml, nodeName)) + { + XmlGetAttributeText (xml, attrName, attr, sizeof (attr)); + if (strcmp (attr, attrValue) == 0) + return xml; + + xml++; + } + + return NULL; +} + + +char *XmlGetAttributeText (char *xmlNode, char *xmlAttrName, char *xmlAttrValue, int xmlAttrValueSize) +{ + char *t = xmlNode; + char *e = xmlNode; + int l = 0; + + xmlAttrValue[0] = 0; + if (t[0] != '<') return NULL; + + e = strchr (e, '>'); + if (e == NULL) return NULL; + + while ((t = strstr (t, xmlAttrName)) && t < e) + { + char *o = t + strlen (xmlAttrName); + if (t[-1] == ' ' + && + (BeginsWith (o, "=\"") + || BeginsWith (o, "= \"") + || BeginsWith (o, " =\"") + || BeginsWith (o, " = \"")) + ) + break; + + t++; + } + + if (t == NULL || t > e) return NULL; + + t = strchr (t, '"') + 1; + e = strchr (t, '"'); + l = (int)(e - t); + if (e == NULL || l > xmlAttrValueSize) return NULL; + + memcpy (xmlAttrValue, t, l); + xmlAttrValue[l] = 0; + + return xmlAttrValue; +} + + +char *XmlGetNodeText (char *xmlNode, char *xmlText, int xmlTextSize) +{ + char *t = xmlNode; + char *e = xmlNode + 1; + int l = 0, i = 0, j = 0; + + xmlText[0] = 0; + + if (t[0] != '<') + return NULL; + + t = strchr (t, '>') + 1; + if (t == (char *)1) return NULL; + + e = strchr (e, '<'); + if (e == NULL) return NULL; + + l = (int)(e - t); + if (e == NULL || l > xmlTextSize) return NULL; + + while (i < l) + { + if (BeginsWith (&t[i], "<")) + { + xmlText[j++] = '<'; + i += 4; + continue; + } + if (BeginsWith (&t[i], ">")) + { + xmlText[j++] = '>'; + i += 4; + continue; + } + if (BeginsWith (&t[i], "&")) + { + xmlText[j++] = '&'; + i += 5; + continue; + } + xmlText[j++] = t[i++]; + } + xmlText[j] = 0; + + return t; +} + + +char *XmlQuoteText (const char *textSrc, char *textDst, int textDstMaxSize) +{ + char *textDstLast = textDst + textDstMaxSize - 1; + + if (textDstMaxSize == 0) + return NULL; + + while (*textSrc != 0 && textDst <= textDstLast) + { + char c = *textSrc++; + switch (c) + { + case '&': + if (textDst + 6 > textDstLast) + return NULL; + strcpy (textDst, "&"); + textDst += 5; + continue; + + case '>': + if (textDst + 5 > textDstLast) + return NULL; + strcpy (textDst, ">"); + textDst += 4; + continue; + + case '<': + if (textDst + 5 > textDstLast) + return NULL; + strcpy (textDst, "<"); + textDst += 4; + continue; + + default: + *textDst++ = c; + } + } + + if (textDst > textDstLast) + return NULL; + + *textDst = 0; + return textDst; +} + +wchar_t *XmlQuoteTextW (const wchar_t *textSrc, wchar_t *textDst, int textDstMaxSize) +{ + wchar_t *textDstLast = textDst + textDstMaxSize - 1; + + if (textDstMaxSize == 0) + return NULL; + + while (*textSrc != 0 && textDst <= textDstLast) + { + wchar_t c = *textSrc++; + switch (c) + { + case L'&': + if (textDst + 6 > textDstLast) + return NULL; + wcscpy (textDst, L"&"); + textDst += 5; + continue; + + case L'>': + if (textDst + 5 > textDstLast) + return NULL; + wcscpy (textDst, L">"); + textDst += 4; + continue; + + case L'<': + if (textDst + 5 > textDstLast) + return NULL; + wcscpy (textDst, L"<"); + textDst += 4; + continue; + + default: + *textDst++ = c; + } + } + + if (textDst > textDstLast) + return NULL; + + *textDst = 0; + return textDst; +} + + +int XmlWriteHeader (FILE *file) +{ + return fputws (L"\n", file); +} + + +int XmlWriteFooter (FILE *file) +{ + return fputws (L"\n", file); +} diff --git a/src/Common/Xml.h b/src/Common/Xml.h index 55c02196..41daf40f 100644 --- a/src/Common/Xml.h +++ b/src/Common/Xml.h @@ -1,29 +1,29 @@ -/* - 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. -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -char *XmlNextNode (char *xmlNode); -char *XmlFindElement (char *xmlNode, char *nodeName); -char *XmlGetAttributeText (char *xmlNode, char *xmlAttrName, char *xmlAttrValue, int xmlAttrValueSize); -char *XmlGetNodeText (char *xmlNode, char *xmlText, int xmlTextSize); -int XmlWriteHeader (FILE *file); -int XmlWriteFooter (FILE *file); -char *XmlFindElementByAttributeValue (char *xml, char *nodeName, char *attrName, char *attrValue); -char *XmlQuoteText (const char *textSrc, char *textDst, int textDstMaxSize); -wchar_t *XmlQuoteTextW (const wchar_t *textSrc, wchar_t *textDst, int textDstMaxSize); - -#ifdef __cplusplus -} -#endif +/* + 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. +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +char *XmlNextNode (char *xmlNode); +char *XmlFindElement (char *xmlNode, char *nodeName); +char *XmlGetAttributeText (char *xmlNode, char *xmlAttrName, char *xmlAttrValue, int xmlAttrValueSize); +char *XmlGetNodeText (char *xmlNode, char *xmlText, int xmlTextSize); +int XmlWriteHeader (FILE *file); +int XmlWriteFooter (FILE *file); +char *XmlFindElementByAttributeValue (char *xml, char *nodeName, char *attrName, char *attrValue); +char *XmlQuoteText (const char *textSrc, char *textDst, int textDstMaxSize); +wchar_t *XmlQuoteTextW (const wchar_t *textSrc, wchar_t *textDst, int textDstMaxSize); + +#ifdef __cplusplus +} +#endif diff --git a/src/Common/Xts.c b/src/Common/Xts.c index c2fe125c..0bdb8271 100644 --- a/src/Common/Xts.c +++ b/src/Common/Xts.c @@ -1,750 +1,750 @@ -/* - 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. -*/ - -/* If native 64-bit data types are not available, define TC_NO_COMPILER_INT64. - -For big-endian platforms define BYTE_ORDER as BIG_ENDIAN. */ - - -#ifdef TC_MINIMIZE_CODE_SIZE -// Preboot/boot version -# ifndef TC_NO_COMPILER_INT64 -# define TC_NO_COMPILER_INT64 -# endif -# pragma optimize ("tl", on) -#endif - -#ifdef TC_NO_COMPILER_INT64 -# include -#endif - -#include "Xts.h" - - -#ifndef TC_NO_COMPILER_INT64 - -// length: number of bytes to encrypt; may be larger than one data unit and must be divisible by the cipher block size -// ks: the primary key schedule -// ks2: the secondary key schedule -// startDataUnitNo: The sequential number of the data unit with which the buffer starts. -// startCipherBlockNo: The sequential number of the first plaintext block to encrypt inside the data unit startDataUnitNo. -// When encrypting the data unit from its first block, startCipherBlockNo is 0. -// The startCipherBlockNo value applies only to the first data unit in the buffer; each successive -// data unit is encrypted from its first block. The start of the buffer does not have to be -// aligned with the start of a data unit. If it is aligned, startCipherBlockNo must be 0; if it -// is not aligned, startCipherBlockNo must reflect the misalignment accordingly. -void EncryptBufferXTS (unsigned __int8 *buffer, - TC_LARGEST_COMPILER_UINT length, - const UINT64_STRUCT *startDataUnitNo, - unsigned int startCipherBlockNo, - unsigned __int8 *ks, - unsigned __int8 *ks2, - int cipher) -{ - if (CipherSupportsIntraDataUnitParallelization (cipher)) - EncryptBufferXTSParallel (buffer, length, startDataUnitNo, startCipherBlockNo, ks, ks2, cipher); - else - EncryptBufferXTSNonParallel (buffer, length, startDataUnitNo, startCipherBlockNo, ks, ks2, cipher); -} - - -// Optimized for encryption algorithms supporting intra-data-unit parallelization -static void EncryptBufferXTSParallel (unsigned __int8 *buffer, - TC_LARGEST_COMPILER_UINT length, - const UINT64_STRUCT *startDataUnitNo, - unsigned int startCipherBlockNo, - unsigned __int8 *ks, - unsigned __int8 *ks2, - int cipher) -{ - unsigned __int8 finalCarry; - unsigned __int8 whiteningValues [ENCRYPTION_DATA_UNIT_SIZE]; - unsigned __int8 whiteningValue [BYTES_PER_XTS_BLOCK]; - unsigned __int8 byteBufUnitNo [BYTES_PER_XTS_BLOCK]; - unsigned __int64 *whiteningValuesPtr64 = (unsigned __int64 *) whiteningValues; - unsigned __int64 *whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; - unsigned __int64 *bufPtr = (unsigned __int64 *) buffer; - unsigned __int64 *dataUnitBufPtr; - unsigned int startBlock = startCipherBlockNo, endBlock, block; - unsigned __int64 *const finalInt64WhiteningValuesPtr = whiteningValuesPtr64 + sizeof (whiteningValues) / sizeof (*whiteningValuesPtr64) - 1; - TC_LARGEST_COMPILER_UINT blockCount, dataUnitNo; - - /* The encrypted data unit number (i.e. the resultant ciphertext block) is to be multiplied in the - finite field GF(2^128) by j-th power of n, where j is the sequential plaintext/ciphertext block - number and n is 2, a primitive element of GF(2^128). This can be (and is) simplified and implemented - as a left shift of the preceding whitening value by one bit (with carry propagating). In addition, if - the shift of the highest byte results in a carry, 135 is XORed into the lowest byte. The value 135 is - derived from the modulus of the Galois Field (x^128+x^7+x^2+x+1). */ - - // Convert the 64-bit data unit number into a little-endian 16-byte array. - // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. - dataUnitNo = startDataUnitNo->Value; - *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); - *((unsigned __int64 *) byteBufUnitNo + 1) = 0; - - if (length % BYTES_PER_XTS_BLOCK) - TC_THROW_FATAL_EXCEPTION; - - blockCount = length / BYTES_PER_XTS_BLOCK; - - // Process all blocks in the buffer - while (blockCount > 0) - { - if (blockCount < BLOCKS_PER_XTS_DATA_UNIT) - endBlock = startBlock + (unsigned int) blockCount; - else - endBlock = BLOCKS_PER_XTS_DATA_UNIT; - - whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; - whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; - - // Encrypt the data unit number using the secondary key (in order to generate the first - // whitening value for this data unit) - *whiteningValuePtr64 = *((unsigned __int64 *) byteBufUnitNo); - *(whiteningValuePtr64 + 1) = 0; - EncipherBlock (cipher, whiteningValue, ks2); - - // Generate subsequent whitening values for blocks in this data unit. Note that all generated 128-bit - // whitening values are stored in memory as a sequence of 64-bit integers in reverse order. - for (block = 0; block < endBlock; block++) - { - if (block >= startBlock) - { - *whiteningValuesPtr64-- = *whiteningValuePtr64++; - *whiteningValuesPtr64-- = *whiteningValuePtr64; - } - else - whiteningValuePtr64++; - - // Derive the next whitening value - -#if BYTE_ORDER == LITTLE_ENDIAN - - // Little-endian platforms - - finalCarry = - (*whiteningValuePtr64 & 0x8000000000000000) ? - 135 : 0; - - *whiteningValuePtr64-- <<= 1; - - if (*whiteningValuePtr64 & 0x8000000000000000) - *(whiteningValuePtr64 + 1) |= 1; - - *whiteningValuePtr64 <<= 1; -#else - - // Big-endian platforms - - finalCarry = - (*whiteningValuePtr64 & 0x80) ? - 135 : 0; - - *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); - - whiteningValuePtr64--; - - if (*whiteningValuePtr64 & 0x80) - *(whiteningValuePtr64 + 1) |= 0x0100000000000000; - - *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); -#endif - - whiteningValue[0] ^= finalCarry; - } - - dataUnitBufPtr = bufPtr; - whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; - - // Encrypt all blocks in this data unit - - for (block = startBlock; block < endBlock; block++) - { - // Pre-whitening - *bufPtr++ ^= *whiteningValuesPtr64--; - *bufPtr++ ^= *whiteningValuesPtr64--; - } - - // Actual encryption - EncipherBlocks (cipher, dataUnitBufPtr, ks, endBlock - startBlock); - - bufPtr = dataUnitBufPtr; - whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; - - for (block = startBlock; block < endBlock; block++) - { - // Post-whitening - *bufPtr++ ^= *whiteningValuesPtr64--; - *bufPtr++ ^= *whiteningValuesPtr64--; - } - - blockCount -= endBlock - startBlock; - startBlock = 0; - dataUnitNo++; - *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); - } - - FAST_ERASE64 (whiteningValue, sizeof (whiteningValue)); - FAST_ERASE64 (whiteningValues, sizeof (whiteningValues)); -} - - -// Optimized for encryption algorithms not supporting intra-data-unit parallelization -static void EncryptBufferXTSNonParallel (unsigned __int8 *buffer, - TC_LARGEST_COMPILER_UINT length, - const UINT64_STRUCT *startDataUnitNo, - unsigned int startCipherBlockNo, - unsigned __int8 *ks, - unsigned __int8 *ks2, - int cipher) -{ - unsigned __int8 finalCarry; - unsigned __int8 whiteningValue [BYTES_PER_XTS_BLOCK]; - unsigned __int8 byteBufUnitNo [BYTES_PER_XTS_BLOCK]; - unsigned __int64 *whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; - unsigned __int64 *bufPtr = (unsigned __int64 *) buffer; - unsigned int startBlock = startCipherBlockNo, endBlock, block; - TC_LARGEST_COMPILER_UINT blockCount, dataUnitNo; - - /* The encrypted data unit number (i.e. the resultant ciphertext block) is to be multiplied in the - finite field GF(2^128) by j-th power of n, where j is the sequential plaintext/ciphertext block - number and n is 2, a primitive element of GF(2^128). This can be (and is) simplified and implemented - as a left shift of the preceding whitening value by one bit (with carry propagating). In addition, if - the shift of the highest byte results in a carry, 135 is XORed into the lowest byte. The value 135 is - derived from the modulus of the Galois Field (x^128+x^7+x^2+x+1). */ - - // Convert the 64-bit data unit number into a little-endian 16-byte array. - // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. - dataUnitNo = startDataUnitNo->Value; - *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); - *((unsigned __int64 *) byteBufUnitNo + 1) = 0; - - if (length % BYTES_PER_XTS_BLOCK) - TC_THROW_FATAL_EXCEPTION; - - blockCount = length / BYTES_PER_XTS_BLOCK; - - // Process all blocks in the buffer - while (blockCount > 0) - { - if (blockCount < BLOCKS_PER_XTS_DATA_UNIT) - endBlock = startBlock + (unsigned int) blockCount; - else - endBlock = BLOCKS_PER_XTS_DATA_UNIT; - - whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; - - // Encrypt the data unit number using the secondary key (in order to generate the first - // whitening value for this data unit) - *whiteningValuePtr64 = *((unsigned __int64 *) byteBufUnitNo); - *(whiteningValuePtr64 + 1) = 0; - EncipherBlock (cipher, whiteningValue, ks2); - - // Generate (and apply) subsequent whitening values for blocks in this data unit and - // encrypt all relevant blocks in this data unit - for (block = 0; block < endBlock; block++) - { - if (block >= startBlock) - { - // Pre-whitening - *bufPtr++ ^= *whiteningValuePtr64++; - *bufPtr-- ^= *whiteningValuePtr64--; - - // Actual encryption - EncipherBlock (cipher, bufPtr, ks); - - // Post-whitening - *bufPtr++ ^= *whiteningValuePtr64++; - *bufPtr++ ^= *whiteningValuePtr64; - } - else - whiteningValuePtr64++; - - // Derive the next whitening value - -#if BYTE_ORDER == LITTLE_ENDIAN - - // Little-endian platforms - - finalCarry = - (*whiteningValuePtr64 & 0x8000000000000000) ? - 135 : 0; - - *whiteningValuePtr64-- <<= 1; - - if (*whiteningValuePtr64 & 0x8000000000000000) - *(whiteningValuePtr64 + 1) |= 1; - - *whiteningValuePtr64 <<= 1; -#else - - // Big-endian platforms - - finalCarry = - (*whiteningValuePtr64 & 0x80) ? - 135 : 0; - - *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); - - whiteningValuePtr64--; - - if (*whiteningValuePtr64 & 0x80) - *(whiteningValuePtr64 + 1) |= 0x0100000000000000; - - *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); -#endif - - whiteningValue[0] ^= finalCarry; - } - - blockCount -= endBlock - startBlock; - startBlock = 0; - dataUnitNo++; - *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); - } - - FAST_ERASE64 (whiteningValue, sizeof (whiteningValue)); -} - - -// For descriptions of the input parameters, see EncryptBufferXTS(). -void DecryptBufferXTS (unsigned __int8 *buffer, - TC_LARGEST_COMPILER_UINT length, - const UINT64_STRUCT *startDataUnitNo, - unsigned int startCipherBlockNo, - unsigned __int8 *ks, - unsigned __int8 *ks2, - int cipher) -{ - if (CipherSupportsIntraDataUnitParallelization (cipher)) - DecryptBufferXTSParallel (buffer, length, startDataUnitNo, startCipherBlockNo, ks, ks2, cipher); - else - DecryptBufferXTSNonParallel (buffer, length, startDataUnitNo, startCipherBlockNo, ks, ks2, cipher); -} - - -// Optimized for encryption algorithms supporting intra-data-unit parallelization -static void DecryptBufferXTSParallel (unsigned __int8 *buffer, - TC_LARGEST_COMPILER_UINT length, - const UINT64_STRUCT *startDataUnitNo, - unsigned int startCipherBlockNo, - unsigned __int8 *ks, - unsigned __int8 *ks2, - int cipher) -{ - unsigned __int8 finalCarry; - unsigned __int8 whiteningValues [ENCRYPTION_DATA_UNIT_SIZE]; - unsigned __int8 whiteningValue [BYTES_PER_XTS_BLOCK]; - unsigned __int8 byteBufUnitNo [BYTES_PER_XTS_BLOCK]; - unsigned __int64 *whiteningValuesPtr64 = (unsigned __int64 *) whiteningValues; - unsigned __int64 *whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; - unsigned __int64 *bufPtr = (unsigned __int64 *) buffer; - unsigned __int64 *dataUnitBufPtr; - unsigned int startBlock = startCipherBlockNo, endBlock, block; - unsigned __int64 *const finalInt64WhiteningValuesPtr = whiteningValuesPtr64 + sizeof (whiteningValues) / sizeof (*whiteningValuesPtr64) - 1; - TC_LARGEST_COMPILER_UINT blockCount, dataUnitNo; - - // Convert the 64-bit data unit number into a little-endian 16-byte array. - // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. - dataUnitNo = startDataUnitNo->Value; - *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); - *((unsigned __int64 *) byteBufUnitNo + 1) = 0; - - if (length % BYTES_PER_XTS_BLOCK) - TC_THROW_FATAL_EXCEPTION; - - blockCount = length / BYTES_PER_XTS_BLOCK; - - // Process all blocks in the buffer - while (blockCount > 0) - { - if (blockCount < BLOCKS_PER_XTS_DATA_UNIT) - endBlock = startBlock + (unsigned int) blockCount; - else - endBlock = BLOCKS_PER_XTS_DATA_UNIT; - - whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; - whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; - - // Encrypt the data unit number using the secondary key (in order to generate the first - // whitening value for this data unit) - *whiteningValuePtr64 = *((unsigned __int64 *) byteBufUnitNo); - *(whiteningValuePtr64 + 1) = 0; - EncipherBlock (cipher, whiteningValue, ks2); - - // Generate subsequent whitening values for blocks in this data unit. Note that all generated 128-bit - // whitening values are stored in memory as a sequence of 64-bit integers in reverse order. - for (block = 0; block < endBlock; block++) - { - if (block >= startBlock) - { - *whiteningValuesPtr64-- = *whiteningValuePtr64++; - *whiteningValuesPtr64-- = *whiteningValuePtr64; - } - else - whiteningValuePtr64++; - - // Derive the next whitening value - -#if BYTE_ORDER == LITTLE_ENDIAN - - // Little-endian platforms - - finalCarry = - (*whiteningValuePtr64 & 0x8000000000000000) ? - 135 : 0; - - *whiteningValuePtr64-- <<= 1; - - if (*whiteningValuePtr64 & 0x8000000000000000) - *(whiteningValuePtr64 + 1) |= 1; - - *whiteningValuePtr64 <<= 1; - -#else - // Big-endian platforms - - finalCarry = - (*whiteningValuePtr64 & 0x80) ? - 135 : 0; - - *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); - - whiteningValuePtr64--; - - if (*whiteningValuePtr64 & 0x80) - *(whiteningValuePtr64 + 1) |= 0x0100000000000000; - - *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); -#endif - - whiteningValue[0] ^= finalCarry; - } - - dataUnitBufPtr = bufPtr; - whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; - - // Decrypt blocks in this data unit - - for (block = startBlock; block < endBlock; block++) - { - *bufPtr++ ^= *whiteningValuesPtr64--; - *bufPtr++ ^= *whiteningValuesPtr64--; - } - - DecipherBlocks (cipher, dataUnitBufPtr, ks, endBlock - startBlock); - - bufPtr = dataUnitBufPtr; - whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; - - for (block = startBlock; block < endBlock; block++) - { - *bufPtr++ ^= *whiteningValuesPtr64--; - *bufPtr++ ^= *whiteningValuesPtr64--; - } - - blockCount -= endBlock - startBlock; - startBlock = 0; - dataUnitNo++; - - *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); - } - - FAST_ERASE64 (whiteningValue, sizeof (whiteningValue)); - FAST_ERASE64 (whiteningValues, sizeof (whiteningValues)); -} - - -// Optimized for encryption algorithms not supporting intra-data-unit parallelization -static void DecryptBufferXTSNonParallel (unsigned __int8 *buffer, - TC_LARGEST_COMPILER_UINT length, - const UINT64_STRUCT *startDataUnitNo, - unsigned int startCipherBlockNo, - unsigned __int8 *ks, - unsigned __int8 *ks2, - int cipher) -{ - unsigned __int8 finalCarry; - unsigned __int8 whiteningValue [BYTES_PER_XTS_BLOCK]; - unsigned __int8 byteBufUnitNo [BYTES_PER_XTS_BLOCK]; - unsigned __int64 *whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; - unsigned __int64 *bufPtr = (unsigned __int64 *) buffer; - unsigned int startBlock = startCipherBlockNo, endBlock, block; - TC_LARGEST_COMPILER_UINT blockCount, dataUnitNo; - - // Convert the 64-bit data unit number into a little-endian 16-byte array. - // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. - dataUnitNo = startDataUnitNo->Value; - *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); - *((unsigned __int64 *) byteBufUnitNo + 1) = 0; - - if (length % BYTES_PER_XTS_BLOCK) - TC_THROW_FATAL_EXCEPTION; - - blockCount = length / BYTES_PER_XTS_BLOCK; - - // Process all blocks in the buffer - while (blockCount > 0) - { - if (blockCount < BLOCKS_PER_XTS_DATA_UNIT) - endBlock = startBlock + (unsigned int) blockCount; - else - endBlock = BLOCKS_PER_XTS_DATA_UNIT; - - whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; - - // Encrypt the data unit number using the secondary key (in order to generate the first - // whitening value for this data unit) - *whiteningValuePtr64 = *((unsigned __int64 *) byteBufUnitNo); - *(whiteningValuePtr64 + 1) = 0; - EncipherBlock (cipher, whiteningValue, ks2); - - // Generate (and apply) subsequent whitening values for blocks in this data unit and - // decrypt all relevant blocks in this data unit - for (block = 0; block < endBlock; block++) - { - if (block >= startBlock) - { - // Post-whitening - *bufPtr++ ^= *whiteningValuePtr64++; - *bufPtr-- ^= *whiteningValuePtr64--; - - // Actual decryption - DecipherBlock (cipher, bufPtr, ks); - - // Pre-whitening - *bufPtr++ ^= *whiteningValuePtr64++; - *bufPtr++ ^= *whiteningValuePtr64; - } - else - whiteningValuePtr64++; - - // Derive the next whitening value - -#if BYTE_ORDER == LITTLE_ENDIAN - - // Little-endian platforms - - finalCarry = - (*whiteningValuePtr64 & 0x8000000000000000) ? - 135 : 0; - - *whiteningValuePtr64-- <<= 1; - - if (*whiteningValuePtr64 & 0x8000000000000000) - *(whiteningValuePtr64 + 1) |= 1; - - *whiteningValuePtr64 <<= 1; - -#else - // Big-endian platforms - - finalCarry = - (*whiteningValuePtr64 & 0x80) ? - 135 : 0; - - *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); - - whiteningValuePtr64--; - - if (*whiteningValuePtr64 & 0x80) - *(whiteningValuePtr64 + 1) |= 0x0100000000000000; - - *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); -#endif - - whiteningValue[0] ^= finalCarry; - } - - blockCount -= endBlock - startBlock; - startBlock = 0; - dataUnitNo++; - *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); - } - - FAST_ERASE64 (whiteningValue, sizeof (whiteningValue)); -} - - -#else // TC_NO_COMPILER_INT64 - -/* ---- The following code is to be used only when native 64-bit data types are not available. ---- */ - -#if BYTE_ORDER == BIG_ENDIAN -#error The TC_NO_COMPILER_INT64 version of the XTS code is not compatible with big-endian platforms -#endif - - -// Converts a 64-bit unsigned integer (passed as two 32-bit integers for compatibility with non-64-bit -// environments/platforms) into a little-endian 16-byte array. -static void Uint64ToLE16ByteArray (unsigned __int8 *byteBuf, unsigned __int32 highInt32, unsigned __int32 lowInt32) -{ - unsigned __int32 *bufPtr32 = (unsigned __int32 *) byteBuf; - - *bufPtr32++ = lowInt32; - *bufPtr32++ = highInt32; - - // We're converting a 64-bit number into a little-endian 16-byte array so we can zero the last 8 bytes - *bufPtr32++ = 0; - *bufPtr32 = 0; -} - - -// Encrypts or decrypts all blocks in the buffer in XTS mode. For descriptions of the input parameters, -// see the 64-bit version of EncryptBufferXTS(). -static void EncryptDecryptBufferXTS32 (const unsigned __int8 *buffer, - TC_LARGEST_COMPILER_UINT length, - const UINT64_STRUCT *startDataUnitNo, - unsigned int startBlock, - unsigned __int8 *ks, - unsigned __int8 *ks2, - int cipher, - BOOL decryption) -{ - TC_LARGEST_COMPILER_UINT blockCount; - UINT64_STRUCT dataUnitNo; - unsigned int block; - unsigned int endBlock; - unsigned __int8 byteBufUnitNo [BYTES_PER_XTS_BLOCK]; - unsigned __int8 whiteningValue [BYTES_PER_XTS_BLOCK]; - unsigned __int32 *bufPtr32 = (unsigned __int32 *) buffer; - unsigned __int32 *whiteningValuePtr32 = (unsigned __int32 *) whiteningValue; - unsigned __int8 finalCarry; - unsigned __int32 *const finalDwordWhiteningValuePtr = whiteningValuePtr32 + sizeof (whiteningValue) / sizeof (*whiteningValuePtr32) - 1; - - // Store the 64-bit data unit number in a way compatible with non-64-bit environments/platforms - dataUnitNo.HighPart = startDataUnitNo->HighPart; - dataUnitNo.LowPart = startDataUnitNo->LowPart; - - blockCount = length / BYTES_PER_XTS_BLOCK; - - // Convert the 64-bit data unit number into a little-endian 16-byte array. - // (Passed as two 32-bit integers for compatibility with non-64-bit environments/platforms.) - Uint64ToLE16ByteArray (byteBufUnitNo, dataUnitNo.HighPart, dataUnitNo.LowPart); - - // Generate whitening values for all blocks in the buffer - while (blockCount > 0) - { - if (blockCount < BLOCKS_PER_XTS_DATA_UNIT) - endBlock = startBlock + (unsigned int) blockCount; - else - endBlock = BLOCKS_PER_XTS_DATA_UNIT; - - // Encrypt the data unit number using the secondary key (in order to generate the first - // whitening value for this data unit) - memcpy (whiteningValue, byteBufUnitNo, BYTES_PER_XTS_BLOCK); - EncipherBlock (cipher, whiteningValue, ks2); - - // Generate (and apply) subsequent whitening values for blocks in this data unit and - // encrypt/decrypt all relevant blocks in this data unit - for (block = 0; block < endBlock; block++) - { - if (block >= startBlock) - { - whiteningValuePtr32 = (unsigned __int32 *) whiteningValue; - - // Whitening - *bufPtr32++ ^= *whiteningValuePtr32++; - *bufPtr32++ ^= *whiteningValuePtr32++; - *bufPtr32++ ^= *whiteningValuePtr32++; - *bufPtr32 ^= *whiteningValuePtr32; - - bufPtr32 -= BYTES_PER_XTS_BLOCK / sizeof (*bufPtr32) - 1; - - // Actual encryption/decryption - if (decryption) - DecipherBlock (cipher, bufPtr32, ks); - else - EncipherBlock (cipher, bufPtr32, ks); - - whiteningValuePtr32 = (unsigned __int32 *) whiteningValue; - - // Whitening - *bufPtr32++ ^= *whiteningValuePtr32++; - *bufPtr32++ ^= *whiteningValuePtr32++; - *bufPtr32++ ^= *whiteningValuePtr32++; - *bufPtr32++ ^= *whiteningValuePtr32; - } - - // Derive the next whitening value - - finalCarry = 0; - - for (whiteningValuePtr32 = finalDwordWhiteningValuePtr; - whiteningValuePtr32 >= (unsigned __int32 *) whiteningValue; - whiteningValuePtr32--) - { - if (*whiteningValuePtr32 & 0x80000000) // If the following shift results in a carry - { - if (whiteningValuePtr32 != finalDwordWhiteningValuePtr) // If not processing the highest double word - { - // A regular carry - *(whiteningValuePtr32 + 1) |= 1; - } - else - { - // The highest byte shift will result in a carry - finalCarry = 135; - } - } - - *whiteningValuePtr32 <<= 1; - } - - whiteningValue[0] ^= finalCarry; - } - - blockCount -= endBlock - startBlock; - startBlock = 0; - - // Increase the data unit number by one - if (!++dataUnitNo.LowPart) - { - dataUnitNo.HighPart++; - } - - // Convert the 64-bit data unit number into a little-endian 16-byte array. - Uint64ToLE16ByteArray (byteBufUnitNo, dataUnitNo.HighPart, dataUnitNo.LowPart); - } - - FAST_ERASE64 (whiteningValue, sizeof (whiteningValue)); -} - - -// For descriptions of the input parameters, see the 64-bit version of EncryptBufferXTS() above. -void EncryptBufferXTS (unsigned __int8 *buffer, - TC_LARGEST_COMPILER_UINT length, - const UINT64_STRUCT *startDataUnitNo, - unsigned int startCipherBlockNo, - unsigned __int8 *ks, - unsigned __int8 *ks2, - int cipher) -{ - // Encrypt all plaintext blocks in the buffer - EncryptDecryptBufferXTS32 (buffer, length, startDataUnitNo, startCipherBlockNo, ks, ks2, cipher, FALSE); -} - - -// For descriptions of the input parameters, see the 64-bit version of EncryptBufferXTS(). -void DecryptBufferXTS (unsigned __int8 *buffer, - TC_LARGEST_COMPILER_UINT length, - const UINT64_STRUCT *startDataUnitNo, - unsigned int startCipherBlockNo, - unsigned __int8 *ks, - unsigned __int8 *ks2, - int cipher) -{ - // Decrypt all ciphertext blocks in the buffer - EncryptDecryptBufferXTS32 (buffer, length, startDataUnitNo, startCipherBlockNo, ks, ks2, cipher, TRUE); -} - -#endif // TC_NO_COMPILER_INT64 +/* + 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. +*/ + +/* If native 64-bit data types are not available, define TC_NO_COMPILER_INT64. + +For big-endian platforms define BYTE_ORDER as BIG_ENDIAN. */ + + +#ifdef TC_MINIMIZE_CODE_SIZE +// Preboot/boot version +# ifndef TC_NO_COMPILER_INT64 +# define TC_NO_COMPILER_INT64 +# endif +# pragma optimize ("tl", on) +#endif + +#ifdef TC_NO_COMPILER_INT64 +# include +#endif + +#include "Xts.h" + + +#ifndef TC_NO_COMPILER_INT64 + +// length: number of bytes to encrypt; may be larger than one data unit and must be divisible by the cipher block size +// ks: the primary key schedule +// ks2: the secondary key schedule +// startDataUnitNo: The sequential number of the data unit with which the buffer starts. +// startCipherBlockNo: The sequential number of the first plaintext block to encrypt inside the data unit startDataUnitNo. +// When encrypting the data unit from its first block, startCipherBlockNo is 0. +// The startCipherBlockNo value applies only to the first data unit in the buffer; each successive +// data unit is encrypted from its first block. The start of the buffer does not have to be +// aligned with the start of a data unit. If it is aligned, startCipherBlockNo must be 0; if it +// is not aligned, startCipherBlockNo must reflect the misalignment accordingly. +void EncryptBufferXTS (unsigned __int8 *buffer, + TC_LARGEST_COMPILER_UINT length, + const UINT64_STRUCT *startDataUnitNo, + unsigned int startCipherBlockNo, + unsigned __int8 *ks, + unsigned __int8 *ks2, + int cipher) +{ + if (CipherSupportsIntraDataUnitParallelization (cipher)) + EncryptBufferXTSParallel (buffer, length, startDataUnitNo, startCipherBlockNo, ks, ks2, cipher); + else + EncryptBufferXTSNonParallel (buffer, length, startDataUnitNo, startCipherBlockNo, ks, ks2, cipher); +} + + +// Optimized for encryption algorithms supporting intra-data-unit parallelization +static void EncryptBufferXTSParallel (unsigned __int8 *buffer, + TC_LARGEST_COMPILER_UINT length, + const UINT64_STRUCT *startDataUnitNo, + unsigned int startCipherBlockNo, + unsigned __int8 *ks, + unsigned __int8 *ks2, + int cipher) +{ + unsigned __int8 finalCarry; + unsigned __int8 whiteningValues [ENCRYPTION_DATA_UNIT_SIZE]; + unsigned __int8 whiteningValue [BYTES_PER_XTS_BLOCK]; + unsigned __int8 byteBufUnitNo [BYTES_PER_XTS_BLOCK]; + unsigned __int64 *whiteningValuesPtr64 = (unsigned __int64 *) whiteningValues; + unsigned __int64 *whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; + unsigned __int64 *bufPtr = (unsigned __int64 *) buffer; + unsigned __int64 *dataUnitBufPtr; + unsigned int startBlock = startCipherBlockNo, endBlock, block; + unsigned __int64 *const finalInt64WhiteningValuesPtr = whiteningValuesPtr64 + sizeof (whiteningValues) / sizeof (*whiteningValuesPtr64) - 1; + TC_LARGEST_COMPILER_UINT blockCount, dataUnitNo; + + /* The encrypted data unit number (i.e. the resultant ciphertext block) is to be multiplied in the + finite field GF(2^128) by j-th power of n, where j is the sequential plaintext/ciphertext block + number and n is 2, a primitive element of GF(2^128). This can be (and is) simplified and implemented + as a left shift of the preceding whitening value by one bit (with carry propagating). In addition, if + the shift of the highest byte results in a carry, 135 is XORed into the lowest byte. The value 135 is + derived from the modulus of the Galois Field (x^128+x^7+x^2+x+1). */ + + // Convert the 64-bit data unit number into a little-endian 16-byte array. + // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. + dataUnitNo = startDataUnitNo->Value; + *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); + *((unsigned __int64 *) byteBufUnitNo + 1) = 0; + + if (length % BYTES_PER_XTS_BLOCK) + TC_THROW_FATAL_EXCEPTION; + + blockCount = length / BYTES_PER_XTS_BLOCK; + + // Process all blocks in the buffer + while (blockCount > 0) + { + if (blockCount < BLOCKS_PER_XTS_DATA_UNIT) + endBlock = startBlock + (unsigned int) blockCount; + else + endBlock = BLOCKS_PER_XTS_DATA_UNIT; + + whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; + whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; + + // Encrypt the data unit number using the secondary key (in order to generate the first + // whitening value for this data unit) + *whiteningValuePtr64 = *((unsigned __int64 *) byteBufUnitNo); + *(whiteningValuePtr64 + 1) = 0; + EncipherBlock (cipher, whiteningValue, ks2); + + // Generate subsequent whitening values for blocks in this data unit. Note that all generated 128-bit + // whitening values are stored in memory as a sequence of 64-bit integers in reverse order. + for (block = 0; block < endBlock; block++) + { + if (block >= startBlock) + { + *whiteningValuesPtr64-- = *whiteningValuePtr64++; + *whiteningValuesPtr64-- = *whiteningValuePtr64; + } + else + whiteningValuePtr64++; + + // Derive the next whitening value + +#if BYTE_ORDER == LITTLE_ENDIAN + + // Little-endian platforms + + finalCarry = + (*whiteningValuePtr64 & 0x8000000000000000) ? + 135 : 0; + + *whiteningValuePtr64-- <<= 1; + + if (*whiteningValuePtr64 & 0x8000000000000000) + *(whiteningValuePtr64 + 1) |= 1; + + *whiteningValuePtr64 <<= 1; +#else + + // Big-endian platforms + + finalCarry = + (*whiteningValuePtr64 & 0x80) ? + 135 : 0; + + *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); + + whiteningValuePtr64--; + + if (*whiteningValuePtr64 & 0x80) + *(whiteningValuePtr64 + 1) |= 0x0100000000000000; + + *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); +#endif + + whiteningValue[0] ^= finalCarry; + } + + dataUnitBufPtr = bufPtr; + whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; + + // Encrypt all blocks in this data unit + + for (block = startBlock; block < endBlock; block++) + { + // Pre-whitening + *bufPtr++ ^= *whiteningValuesPtr64--; + *bufPtr++ ^= *whiteningValuesPtr64--; + } + + // Actual encryption + EncipherBlocks (cipher, dataUnitBufPtr, ks, endBlock - startBlock); + + bufPtr = dataUnitBufPtr; + whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; + + for (block = startBlock; block < endBlock; block++) + { + // Post-whitening + *bufPtr++ ^= *whiteningValuesPtr64--; + *bufPtr++ ^= *whiteningValuesPtr64--; + } + + blockCount -= endBlock - startBlock; + startBlock = 0; + dataUnitNo++; + *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); + } + + FAST_ERASE64 (whiteningValue, sizeof (whiteningValue)); + FAST_ERASE64 (whiteningValues, sizeof (whiteningValues)); +} + + +// Optimized for encryption algorithms not supporting intra-data-unit parallelization +static void EncryptBufferXTSNonParallel (unsigned __int8 *buffer, + TC_LARGEST_COMPILER_UINT length, + const UINT64_STRUCT *startDataUnitNo, + unsigned int startCipherBlockNo, + unsigned __int8 *ks, + unsigned __int8 *ks2, + int cipher) +{ + unsigned __int8 finalCarry; + unsigned __int8 whiteningValue [BYTES_PER_XTS_BLOCK]; + unsigned __int8 byteBufUnitNo [BYTES_PER_XTS_BLOCK]; + unsigned __int64 *whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; + unsigned __int64 *bufPtr = (unsigned __int64 *) buffer; + unsigned int startBlock = startCipherBlockNo, endBlock, block; + TC_LARGEST_COMPILER_UINT blockCount, dataUnitNo; + + /* The encrypted data unit number (i.e. the resultant ciphertext block) is to be multiplied in the + finite field GF(2^128) by j-th power of n, where j is the sequential plaintext/ciphertext block + number and n is 2, a primitive element of GF(2^128). This can be (and is) simplified and implemented + as a left shift of the preceding whitening value by one bit (with carry propagating). In addition, if + the shift of the highest byte results in a carry, 135 is XORed into the lowest byte. The value 135 is + derived from the modulus of the Galois Field (x^128+x^7+x^2+x+1). */ + + // Convert the 64-bit data unit number into a little-endian 16-byte array. + // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. + dataUnitNo = startDataUnitNo->Value; + *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); + *((unsigned __int64 *) byteBufUnitNo + 1) = 0; + + if (length % BYTES_PER_XTS_BLOCK) + TC_THROW_FATAL_EXCEPTION; + + blockCount = length / BYTES_PER_XTS_BLOCK; + + // Process all blocks in the buffer + while (blockCount > 0) + { + if (blockCount < BLOCKS_PER_XTS_DATA_UNIT) + endBlock = startBlock + (unsigned int) blockCount; + else + endBlock = BLOCKS_PER_XTS_DATA_UNIT; + + whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; + + // Encrypt the data unit number using the secondary key (in order to generate the first + // whitening value for this data unit) + *whiteningValuePtr64 = *((unsigned __int64 *) byteBufUnitNo); + *(whiteningValuePtr64 + 1) = 0; + EncipherBlock (cipher, whiteningValue, ks2); + + // Generate (and apply) subsequent whitening values for blocks in this data unit and + // encrypt all relevant blocks in this data unit + for (block = 0; block < endBlock; block++) + { + if (block >= startBlock) + { + // Pre-whitening + *bufPtr++ ^= *whiteningValuePtr64++; + *bufPtr-- ^= *whiteningValuePtr64--; + + // Actual encryption + EncipherBlock (cipher, bufPtr, ks); + + // Post-whitening + *bufPtr++ ^= *whiteningValuePtr64++; + *bufPtr++ ^= *whiteningValuePtr64; + } + else + whiteningValuePtr64++; + + // Derive the next whitening value + +#if BYTE_ORDER == LITTLE_ENDIAN + + // Little-endian platforms + + finalCarry = + (*whiteningValuePtr64 & 0x8000000000000000) ? + 135 : 0; + + *whiteningValuePtr64-- <<= 1; + + if (*whiteningValuePtr64 & 0x8000000000000000) + *(whiteningValuePtr64 + 1) |= 1; + + *whiteningValuePtr64 <<= 1; +#else + + // Big-endian platforms + + finalCarry = + (*whiteningValuePtr64 & 0x80) ? + 135 : 0; + + *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); + + whiteningValuePtr64--; + + if (*whiteningValuePtr64 & 0x80) + *(whiteningValuePtr64 + 1) |= 0x0100000000000000; + + *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); +#endif + + whiteningValue[0] ^= finalCarry; + } + + blockCount -= endBlock - startBlock; + startBlock = 0; + dataUnitNo++; + *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); + } + + FAST_ERASE64 (whiteningValue, sizeof (whiteningValue)); +} + + +// For descriptions of the input parameters, see EncryptBufferXTS(). +void DecryptBufferXTS (unsigned __int8 *buffer, + TC_LARGEST_COMPILER_UINT length, + const UINT64_STRUCT *startDataUnitNo, + unsigned int startCipherBlockNo, + unsigned __int8 *ks, + unsigned __int8 *ks2, + int cipher) +{ + if (CipherSupportsIntraDataUnitParallelization (cipher)) + DecryptBufferXTSParallel (buffer, length, startDataUnitNo, startCipherBlockNo, ks, ks2, cipher); + else + DecryptBufferXTSNonParallel (buffer, length, startDataUnitNo, startCipherBlockNo, ks, ks2, cipher); +} + + +// Optimized for encryption algorithms supporting intra-data-unit parallelization +static void DecryptBufferXTSParallel (unsigned __int8 *buffer, + TC_LARGEST_COMPILER_UINT length, + const UINT64_STRUCT *startDataUnitNo, + unsigned int startCipherBlockNo, + unsigned __int8 *ks, + unsigned __int8 *ks2, + int cipher) +{ + unsigned __int8 finalCarry; + unsigned __int8 whiteningValues [ENCRYPTION_DATA_UNIT_SIZE]; + unsigned __int8 whiteningValue [BYTES_PER_XTS_BLOCK]; + unsigned __int8 byteBufUnitNo [BYTES_PER_XTS_BLOCK]; + unsigned __int64 *whiteningValuesPtr64 = (unsigned __int64 *) whiteningValues; + unsigned __int64 *whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; + unsigned __int64 *bufPtr = (unsigned __int64 *) buffer; + unsigned __int64 *dataUnitBufPtr; + unsigned int startBlock = startCipherBlockNo, endBlock, block; + unsigned __int64 *const finalInt64WhiteningValuesPtr = whiteningValuesPtr64 + sizeof (whiteningValues) / sizeof (*whiteningValuesPtr64) - 1; + TC_LARGEST_COMPILER_UINT blockCount, dataUnitNo; + + // Convert the 64-bit data unit number into a little-endian 16-byte array. + // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. + dataUnitNo = startDataUnitNo->Value; + *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); + *((unsigned __int64 *) byteBufUnitNo + 1) = 0; + + if (length % BYTES_PER_XTS_BLOCK) + TC_THROW_FATAL_EXCEPTION; + + blockCount = length / BYTES_PER_XTS_BLOCK; + + // Process all blocks in the buffer + while (blockCount > 0) + { + if (blockCount < BLOCKS_PER_XTS_DATA_UNIT) + endBlock = startBlock + (unsigned int) blockCount; + else + endBlock = BLOCKS_PER_XTS_DATA_UNIT; + + whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; + whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; + + // Encrypt the data unit number using the secondary key (in order to generate the first + // whitening value for this data unit) + *whiteningValuePtr64 = *((unsigned __int64 *) byteBufUnitNo); + *(whiteningValuePtr64 + 1) = 0; + EncipherBlock (cipher, whiteningValue, ks2); + + // Generate subsequent whitening values for blocks in this data unit. Note that all generated 128-bit + // whitening values are stored in memory as a sequence of 64-bit integers in reverse order. + for (block = 0; block < endBlock; block++) + { + if (block >= startBlock) + { + *whiteningValuesPtr64-- = *whiteningValuePtr64++; + *whiteningValuesPtr64-- = *whiteningValuePtr64; + } + else + whiteningValuePtr64++; + + // Derive the next whitening value + +#if BYTE_ORDER == LITTLE_ENDIAN + + // Little-endian platforms + + finalCarry = + (*whiteningValuePtr64 & 0x8000000000000000) ? + 135 : 0; + + *whiteningValuePtr64-- <<= 1; + + if (*whiteningValuePtr64 & 0x8000000000000000) + *(whiteningValuePtr64 + 1) |= 1; + + *whiteningValuePtr64 <<= 1; + +#else + // Big-endian platforms + + finalCarry = + (*whiteningValuePtr64 & 0x80) ? + 135 : 0; + + *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); + + whiteningValuePtr64--; + + if (*whiteningValuePtr64 & 0x80) + *(whiteningValuePtr64 + 1) |= 0x0100000000000000; + + *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); +#endif + + whiteningValue[0] ^= finalCarry; + } + + dataUnitBufPtr = bufPtr; + whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; + + // Decrypt blocks in this data unit + + for (block = startBlock; block < endBlock; block++) + { + *bufPtr++ ^= *whiteningValuesPtr64--; + *bufPtr++ ^= *whiteningValuesPtr64--; + } + + DecipherBlocks (cipher, dataUnitBufPtr, ks, endBlock - startBlock); + + bufPtr = dataUnitBufPtr; + whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; + + for (block = startBlock; block < endBlock; block++) + { + *bufPtr++ ^= *whiteningValuesPtr64--; + *bufPtr++ ^= *whiteningValuesPtr64--; + } + + blockCount -= endBlock - startBlock; + startBlock = 0; + dataUnitNo++; + + *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); + } + + FAST_ERASE64 (whiteningValue, sizeof (whiteningValue)); + FAST_ERASE64 (whiteningValues, sizeof (whiteningValues)); +} + + +// Optimized for encryption algorithms not supporting intra-data-unit parallelization +static void DecryptBufferXTSNonParallel (unsigned __int8 *buffer, + TC_LARGEST_COMPILER_UINT length, + const UINT64_STRUCT *startDataUnitNo, + unsigned int startCipherBlockNo, + unsigned __int8 *ks, + unsigned __int8 *ks2, + int cipher) +{ + unsigned __int8 finalCarry; + unsigned __int8 whiteningValue [BYTES_PER_XTS_BLOCK]; + unsigned __int8 byteBufUnitNo [BYTES_PER_XTS_BLOCK]; + unsigned __int64 *whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; + unsigned __int64 *bufPtr = (unsigned __int64 *) buffer; + unsigned int startBlock = startCipherBlockNo, endBlock, block; + TC_LARGEST_COMPILER_UINT blockCount, dataUnitNo; + + // Convert the 64-bit data unit number into a little-endian 16-byte array. + // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. + dataUnitNo = startDataUnitNo->Value; + *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); + *((unsigned __int64 *) byteBufUnitNo + 1) = 0; + + if (length % BYTES_PER_XTS_BLOCK) + TC_THROW_FATAL_EXCEPTION; + + blockCount = length / BYTES_PER_XTS_BLOCK; + + // Process all blocks in the buffer + while (blockCount > 0) + { + if (blockCount < BLOCKS_PER_XTS_DATA_UNIT) + endBlock = startBlock + (unsigned int) blockCount; + else + endBlock = BLOCKS_PER_XTS_DATA_UNIT; + + whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; + + // Encrypt the data unit number using the secondary key (in order to generate the first + // whitening value for this data unit) + *whiteningValuePtr64 = *((unsigned __int64 *) byteBufUnitNo); + *(whiteningValuePtr64 + 1) = 0; + EncipherBlock (cipher, whiteningValue, ks2); + + // Generate (and apply) subsequent whitening values for blocks in this data unit and + // decrypt all relevant blocks in this data unit + for (block = 0; block < endBlock; block++) + { + if (block >= startBlock) + { + // Post-whitening + *bufPtr++ ^= *whiteningValuePtr64++; + *bufPtr-- ^= *whiteningValuePtr64--; + + // Actual decryption + DecipherBlock (cipher, bufPtr, ks); + + // Pre-whitening + *bufPtr++ ^= *whiteningValuePtr64++; + *bufPtr++ ^= *whiteningValuePtr64; + } + else + whiteningValuePtr64++; + + // Derive the next whitening value + +#if BYTE_ORDER == LITTLE_ENDIAN + + // Little-endian platforms + + finalCarry = + (*whiteningValuePtr64 & 0x8000000000000000) ? + 135 : 0; + + *whiteningValuePtr64-- <<= 1; + + if (*whiteningValuePtr64 & 0x8000000000000000) + *(whiteningValuePtr64 + 1) |= 1; + + *whiteningValuePtr64 <<= 1; + +#else + // Big-endian platforms + + finalCarry = + (*whiteningValuePtr64 & 0x80) ? + 135 : 0; + + *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); + + whiteningValuePtr64--; + + if (*whiteningValuePtr64 & 0x80) + *(whiteningValuePtr64 + 1) |= 0x0100000000000000; + + *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); +#endif + + whiteningValue[0] ^= finalCarry; + } + + blockCount -= endBlock - startBlock; + startBlock = 0; + dataUnitNo++; + *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); + } + + FAST_ERASE64 (whiteningValue, sizeof (whiteningValue)); +} + + +#else // TC_NO_COMPILER_INT64 + +/* ---- The following code is to be used only when native 64-bit data types are not available. ---- */ + +#if BYTE_ORDER == BIG_ENDIAN +#error The TC_NO_COMPILER_INT64 version of the XTS code is not compatible with big-endian platforms +#endif + + +// Converts a 64-bit unsigned integer (passed as two 32-bit integers for compatibility with non-64-bit +// environments/platforms) into a little-endian 16-byte array. +static void Uint64ToLE16ByteArray (unsigned __int8 *byteBuf, unsigned __int32 highInt32, unsigned __int32 lowInt32) +{ + unsigned __int32 *bufPtr32 = (unsigned __int32 *) byteBuf; + + *bufPtr32++ = lowInt32; + *bufPtr32++ = highInt32; + + // We're converting a 64-bit number into a little-endian 16-byte array so we can zero the last 8 bytes + *bufPtr32++ = 0; + *bufPtr32 = 0; +} + + +// Encrypts or decrypts all blocks in the buffer in XTS mode. For descriptions of the input parameters, +// see the 64-bit version of EncryptBufferXTS(). +static void EncryptDecryptBufferXTS32 (const unsigned __int8 *buffer, + TC_LARGEST_COMPILER_UINT length, + const UINT64_STRUCT *startDataUnitNo, + unsigned int startBlock, + unsigned __int8 *ks, + unsigned __int8 *ks2, + int cipher, + BOOL decryption) +{ + TC_LARGEST_COMPILER_UINT blockCount; + UINT64_STRUCT dataUnitNo; + unsigned int block; + unsigned int endBlock; + unsigned __int8 byteBufUnitNo [BYTES_PER_XTS_BLOCK]; + unsigned __int8 whiteningValue [BYTES_PER_XTS_BLOCK]; + unsigned __int32 *bufPtr32 = (unsigned __int32 *) buffer; + unsigned __int32 *whiteningValuePtr32 = (unsigned __int32 *) whiteningValue; + unsigned __int8 finalCarry; + unsigned __int32 *const finalDwordWhiteningValuePtr = whiteningValuePtr32 + sizeof (whiteningValue) / sizeof (*whiteningValuePtr32) - 1; + + // Store the 64-bit data unit number in a way compatible with non-64-bit environments/platforms + dataUnitNo.HighPart = startDataUnitNo->HighPart; + dataUnitNo.LowPart = startDataUnitNo->LowPart; + + blockCount = length / BYTES_PER_XTS_BLOCK; + + // Convert the 64-bit data unit number into a little-endian 16-byte array. + // (Passed as two 32-bit integers for compatibility with non-64-bit environments/platforms.) + Uint64ToLE16ByteArray (byteBufUnitNo, dataUnitNo.HighPart, dataUnitNo.LowPart); + + // Generate whitening values for all blocks in the buffer + while (blockCount > 0) + { + if (blockCount < BLOCKS_PER_XTS_DATA_UNIT) + endBlock = startBlock + (unsigned int) blockCount; + else + endBlock = BLOCKS_PER_XTS_DATA_UNIT; + + // Encrypt the data unit number using the secondary key (in order to generate the first + // whitening value for this data unit) + memcpy (whiteningValue, byteBufUnitNo, BYTES_PER_XTS_BLOCK); + EncipherBlock (cipher, whiteningValue, ks2); + + // Generate (and apply) subsequent whitening values for blocks in this data unit and + // encrypt/decrypt all relevant blocks in this data unit + for (block = 0; block < endBlock; block++) + { + if (block >= startBlock) + { + whiteningValuePtr32 = (unsigned __int32 *) whiteningValue; + + // Whitening + *bufPtr32++ ^= *whiteningValuePtr32++; + *bufPtr32++ ^= *whiteningValuePtr32++; + *bufPtr32++ ^= *whiteningValuePtr32++; + *bufPtr32 ^= *whiteningValuePtr32; + + bufPtr32 -= BYTES_PER_XTS_BLOCK / sizeof (*bufPtr32) - 1; + + // Actual encryption/decryption + if (decryption) + DecipherBlock (cipher, bufPtr32, ks); + else + EncipherBlock (cipher, bufPtr32, ks); + + whiteningValuePtr32 = (unsigned __int32 *) whiteningValue; + + // Whitening + *bufPtr32++ ^= *whiteningValuePtr32++; + *bufPtr32++ ^= *whiteningValuePtr32++; + *bufPtr32++ ^= *whiteningValuePtr32++; + *bufPtr32++ ^= *whiteningValuePtr32; + } + + // Derive the next whitening value + + finalCarry = 0; + + for (whiteningValuePtr32 = finalDwordWhiteningValuePtr; + whiteningValuePtr32 >= (unsigned __int32 *) whiteningValue; + whiteningValuePtr32--) + { + if (*whiteningValuePtr32 & 0x80000000) // If the following shift results in a carry + { + if (whiteningValuePtr32 != finalDwordWhiteningValuePtr) // If not processing the highest double word + { + // A regular carry + *(whiteningValuePtr32 + 1) |= 1; + } + else + { + // The highest byte shift will result in a carry + finalCarry = 135; + } + } + + *whiteningValuePtr32 <<= 1; + } + + whiteningValue[0] ^= finalCarry; + } + + blockCount -= endBlock - startBlock; + startBlock = 0; + + // Increase the data unit number by one + if (!++dataUnitNo.LowPart) + { + dataUnitNo.HighPart++; + } + + // Convert the 64-bit data unit number into a little-endian 16-byte array. + Uint64ToLE16ByteArray (byteBufUnitNo, dataUnitNo.HighPart, dataUnitNo.LowPart); + } + + FAST_ERASE64 (whiteningValue, sizeof (whiteningValue)); +} + + +// For descriptions of the input parameters, see the 64-bit version of EncryptBufferXTS() above. +void EncryptBufferXTS (unsigned __int8 *buffer, + TC_LARGEST_COMPILER_UINT length, + const UINT64_STRUCT *startDataUnitNo, + unsigned int startCipherBlockNo, + unsigned __int8 *ks, + unsigned __int8 *ks2, + int cipher) +{ + // Encrypt all plaintext blocks in the buffer + EncryptDecryptBufferXTS32 (buffer, length, startDataUnitNo, startCipherBlockNo, ks, ks2, cipher, FALSE); +} + + +// For descriptions of the input parameters, see the 64-bit version of EncryptBufferXTS(). +void DecryptBufferXTS (unsigned __int8 *buffer, + TC_LARGEST_COMPILER_UINT length, + const UINT64_STRUCT *startDataUnitNo, + unsigned int startCipherBlockNo, + unsigned __int8 *ks, + unsigned __int8 *ks2, + int cipher) +{ + // Decrypt all ciphertext blocks in the buffer + EncryptDecryptBufferXTS32 (buffer, length, startDataUnitNo, startCipherBlockNo, ks, ks2, cipher, TRUE); +} + +#endif // TC_NO_COMPILER_INT64 diff --git a/src/Common/Xts.h b/src/Common/Xts.h index b984dd99..f4f4ab5b 100644 --- a/src/Common/Xts.h +++ b/src/Common/Xts.h @@ -1,84 +1,84 @@ -/* - 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. -*/ - -#ifndef XTS_H -#define XTS_H - -// Header files (optional) - -#include "Tcdefs.h" -#include "Common/Endian.h" -#include "Crypto.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// Macros - -#ifndef LITTLE_ENDIAN -# define LITTLE_ENDIAN 1 -#endif - -#ifndef BIG_ENDIAN -# define BIG_ENDIAN 2 -#endif - -#ifndef BYTE_ORDER -# define BYTE_ORDER LITTLE_ENDIAN -#endif - -#ifndef LE64 -# if BYTE_ORDER == LITTLE_ENDIAN -# define LE64(x) (x) -# endif -#endif - -// Custom data types - -#ifndef TC_LARGEST_COMPILER_UINT -# ifdef TC_NO_COMPILER_INT64 - typedef unsigned __int32 TC_LARGEST_COMPILER_UINT; -# else - typedef unsigned __int64 TC_LARGEST_COMPILER_UINT; -# endif -#endif - -#ifndef TCDEFS_H -typedef union -{ - struct - { - unsigned __int32 LowPart; - unsigned __int32 HighPart; - }; -# ifndef TC_NO_COMPILER_INT64 - unsigned __int64 Value; -# endif - -} UINT64_STRUCT; -#endif - -// Public function prototypes - -void EncryptBufferXTS (unsigned __int8 *buffer, TC_LARGEST_COMPILER_UINT length, const UINT64_STRUCT *startDataUnitNo, unsigned int startCipherBlockNo, unsigned __int8 *ks, unsigned __int8 *ks2, int cipher); -static void EncryptBufferXTSParallel (unsigned __int8 *buffer, TC_LARGEST_COMPILER_UINT length, const UINT64_STRUCT *startDataUnitNo, unsigned int startCipherBlockNo, unsigned __int8 *ks, unsigned __int8 *ks2, int cipher); -static void EncryptBufferXTSNonParallel (unsigned __int8 *buffer, TC_LARGEST_COMPILER_UINT length, const UINT64_STRUCT *startDataUnitNo, unsigned int startCipherBlockNo, unsigned __int8 *ks, unsigned __int8 *ks2, int cipher); -void DecryptBufferXTS (unsigned __int8 *buffer, TC_LARGEST_COMPILER_UINT length, const UINT64_STRUCT *startDataUnitNo, unsigned int startCipherBlockNo, unsigned __int8 *ks, unsigned __int8 *ks2, int cipher); -static void DecryptBufferXTSParallel (unsigned __int8 *buffer, TC_LARGEST_COMPILER_UINT length, const UINT64_STRUCT *startDataUnitNo, unsigned int startCipherBlockNo, unsigned __int8 *ks, unsigned __int8 *ks2, int cipher); -static void DecryptBufferXTSNonParallel (unsigned __int8 *buffer, TC_LARGEST_COMPILER_UINT length, const UINT64_STRUCT *startDataUnitNo, unsigned int startCipherBlockNo, unsigned __int8 *ks, unsigned __int8 *ks2, int cipher); - -#ifdef __cplusplus -} -#endif - -#endif // #ifndef XTS_H +/* + 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. +*/ + +#ifndef XTS_H +#define XTS_H + +// Header files (optional) + +#include "Tcdefs.h" +#include "Common/Endian.h" +#include "Crypto.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// Macros + +#ifndef LITTLE_ENDIAN +# define LITTLE_ENDIAN 1 +#endif + +#ifndef BIG_ENDIAN +# define BIG_ENDIAN 2 +#endif + +#ifndef BYTE_ORDER +# define BYTE_ORDER LITTLE_ENDIAN +#endif + +#ifndef LE64 +# if BYTE_ORDER == LITTLE_ENDIAN +# define LE64(x) (x) +# endif +#endif + +// Custom data types + +#ifndef TC_LARGEST_COMPILER_UINT +# ifdef TC_NO_COMPILER_INT64 + typedef unsigned __int32 TC_LARGEST_COMPILER_UINT; +# else + typedef unsigned __int64 TC_LARGEST_COMPILER_UINT; +# endif +#endif + +#ifndef TCDEFS_H +typedef union +{ + struct + { + unsigned __int32 LowPart; + unsigned __int32 HighPart; + }; +# ifndef TC_NO_COMPILER_INT64 + unsigned __int64 Value; +# endif + +} UINT64_STRUCT; +#endif + +// Public function prototypes + +void EncryptBufferXTS (unsigned __int8 *buffer, TC_LARGEST_COMPILER_UINT length, const UINT64_STRUCT *startDataUnitNo, unsigned int startCipherBlockNo, unsigned __int8 *ks, unsigned __int8 *ks2, int cipher); +static void EncryptBufferXTSParallel (unsigned __int8 *buffer, TC_LARGEST_COMPILER_UINT length, const UINT64_STRUCT *startDataUnitNo, unsigned int startCipherBlockNo, unsigned __int8 *ks, unsigned __int8 *ks2, int cipher); +static void EncryptBufferXTSNonParallel (unsigned __int8 *buffer, TC_LARGEST_COMPILER_UINT length, const UINT64_STRUCT *startDataUnitNo, unsigned int startCipherBlockNo, unsigned __int8 *ks, unsigned __int8 *ks2, int cipher); +void DecryptBufferXTS (unsigned __int8 *buffer, TC_LARGEST_COMPILER_UINT length, const UINT64_STRUCT *startDataUnitNo, unsigned int startCipherBlockNo, unsigned __int8 *ks, unsigned __int8 *ks2, int cipher); +static void DecryptBufferXTSParallel (unsigned __int8 *buffer, TC_LARGEST_COMPILER_UINT length, const UINT64_STRUCT *startDataUnitNo, unsigned int startCipherBlockNo, unsigned __int8 *ks, unsigned __int8 *ks2, int cipher); +static void DecryptBufferXTSNonParallel (unsigned __int8 *buffer, TC_LARGEST_COMPILER_UINT length, const UINT64_STRUCT *startDataUnitNo, unsigned int startCipherBlockNo, unsigned __int8 *ks, unsigned __int8 *ks2, int cipher); + +#ifdef __cplusplus +} +#endif + +#endif // #ifndef XTS_H diff --git a/src/Crypto/Aes.h b/src/Crypto/Aes.h index 7a1eff47..e12c6fc8 100644 --- a/src/Crypto/Aes.h +++ b/src/Crypto/Aes.h @@ -1,215 +1,215 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software is allowed (with or without - changes) provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue Date: 20/12/2007 - - This file contains the definitions required to use AES in C. See aesopt.h - for optimisation details. -*/ - -/* Adapted for TrueCrypt */ - -#ifndef _AES_H -#define _AES_H - -#include "Common/Tcdefs.h" - -#ifndef EXIT_SUCCESS -#define EXIT_SUCCESS 0 -#define EXIT_FAILURE 1 -#endif -#define INT_RETURN int - -#if defined(__cplusplus) -extern "C" -{ -#endif - -// #define AES_128 /* define if AES with 128 bit keys is needed */ -// #define AES_192 /* define if AES with 192 bit keys is needed */ -#define AES_256 /* define if AES with 256 bit keys is needed */ -// #define AES_VAR /* define if a variable key size is needed */ -// #define AES_MODES /* define if support is needed for modes */ - -/* The following must also be set in assembler files if being used */ - -#define AES_ENCRYPT /* if support for encryption is needed */ -#define AES_DECRYPT /* if support for decryption is needed */ -#define AES_ERR_CHK /* for parameter checks & error return codes */ -#define AES_REV_DKS /* define to reverse decryption key schedule */ - -#define AES_BLOCK_SIZE 16 /* the AES block size in bytes */ -#define N_COLS 4 /* the number of columns in the state */ - -/* The key schedule length is 11, 13 or 15 16-byte blocks for 128, */ -/* 192 or 256-bit keys respectively. That is 176, 208 or 240 bytes */ -/* or 44, 52 or 60 32-bit words. */ - -#if defined( AES_VAR ) || defined( AES_256 ) -#define KS_LENGTH 60 -#elif defined( AES_192 ) -#define KS_LENGTH 52 -#else -#define KS_LENGTH 44 -#endif - -#if defined( AES_ERR_CHK ) -#define AES_RETURN INT_RETURN -#else -#define AES_RETURN VOID_RETURN -#endif - -/* the character array 'inf' in the following structures is used */ -/* to hold AES context information. This AES code uses cx->inf.b[0] */ -/* to hold the number of rounds multiplied by 16. The other three */ -/* elements can be used by code that implements additional modes */ - -typedef union -{ uint_32t l; - uint_8t b[4]; -} aes_inf; - -typedef struct -{ uint_32t ks[KS_LENGTH]; - aes_inf inf; -} aes_encrypt_ctx; - -typedef struct -{ uint_32t ks[KS_LENGTH]; - aes_inf inf; -} aes_decrypt_ctx; - -/* This routine must be called before first use if non-static */ -/* tables are being used */ - -AES_RETURN aes_init(void); - -/* Key lengths in the range 16 <= key_len <= 32 are given in bytes, */ -/* those in the range 128 <= key_len <= 256 are given in bits */ - -#if defined( AES_ENCRYPT ) - -#if defined(AES_128) || defined(AES_VAR) -AES_RETURN aes_encrypt_key128(const unsigned char *key, aes_encrypt_ctx cx[1]); -#endif - -#if defined(AES_192) || defined(AES_VAR) -AES_RETURN aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1]); -#endif - -#if defined(AES_256) || defined(AES_VAR) -AES_RETURN aes_encrypt_key256(const unsigned char *key, aes_encrypt_ctx cx[1]); -#endif - -#if defined(AES_VAR) -AES_RETURN aes_encrypt_key(const unsigned char *key, int key_len, aes_encrypt_ctx cx[1]); -#endif - -AES_RETURN aes_encrypt(const unsigned char *in, unsigned char *out, const aes_encrypt_ctx cx[1]); - -#endif - -#if defined( AES_DECRYPT ) - -#if defined(AES_128) || defined(AES_VAR) -AES_RETURN aes_decrypt_key128(const unsigned char *key, aes_decrypt_ctx cx[1]); -#endif - -#if defined(AES_192) || defined(AES_VAR) -AES_RETURN aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1]); -#endif - -#if defined(AES_256) || defined(AES_VAR) -AES_RETURN aes_decrypt_key256(const unsigned char *key, aes_decrypt_ctx cx[1]); -#endif - -#if defined(AES_VAR) -AES_RETURN aes_decrypt_key(const unsigned char *key, int key_len, aes_decrypt_ctx cx[1]); -#endif - -AES_RETURN aes_decrypt(const unsigned char *in, unsigned char *out, const aes_decrypt_ctx cx[1]); - -#endif - -#if defined(AES_MODES) - -/* Multiple calls to the following subroutines for multiple block */ -/* ECB, CBC, CFB, OFB and CTR mode encryption can be used to handle */ -/* long messages incremantally provided that the context AND the iv */ -/* are preserved between all such calls. For the ECB and CBC modes */ -/* each individual call within a series of incremental calls must */ -/* process only full blocks (i.e. len must be a multiple of 16) but */ -/* the CFB, OFB and CTR mode calls can handle multiple incremental */ -/* calls of any length. Each mode is reset when a new AES key is */ -/* set but ECB and CBC operations can be reset without setting a */ -/* new key by setting a new IV value. To reset CFB, OFB and CTR */ -/* without setting the key, aes_mode_reset() must be called and the */ -/* IV must be set. NOTE: All these calls update the IV on exit so */ -/* this has to be reset if a new operation with the same IV as the */ -/* previous one is required (or decryption follows encryption with */ -/* the same IV array). */ - -AES_RETURN aes_test_alignment_detection(unsigned int n); - -AES_RETURN aes_ecb_encrypt(const unsigned char *ibuf, unsigned char *obuf, - int len, const aes_encrypt_ctx cx[1]); - -AES_RETURN aes_ecb_decrypt(const unsigned char *ibuf, unsigned char *obuf, - int len, const aes_decrypt_ctx cx[1]); - -AES_RETURN aes_cbc_encrypt(const unsigned char *ibuf, unsigned char *obuf, - int len, unsigned char *iv, const aes_encrypt_ctx cx[1]); - -AES_RETURN aes_cbc_decrypt(const unsigned char *ibuf, unsigned char *obuf, - int len, unsigned char *iv, const aes_decrypt_ctx cx[1]); - -AES_RETURN aes_mode_reset(aes_encrypt_ctx cx[1]); - -AES_RETURN aes_cfb_encrypt(const unsigned char *ibuf, unsigned char *obuf, - int len, unsigned char *iv, aes_encrypt_ctx cx[1]); - -AES_RETURN aes_cfb_decrypt(const unsigned char *ibuf, unsigned char *obuf, - int len, unsigned char *iv, aes_encrypt_ctx cx[1]); - -#define aes_ofb_encrypt aes_ofb_crypt -#define aes_ofb_decrypt aes_ofb_crypt - -AES_RETURN aes_ofb_crypt(const unsigned char *ibuf, unsigned char *obuf, - int len, unsigned char *iv, aes_encrypt_ctx cx[1]); - -typedef void cbuf_inc(unsigned char *cbuf); - -#define aes_ctr_encrypt aes_ctr_crypt -#define aes_ctr_decrypt aes_ctr_crypt - -AES_RETURN aes_ctr_crypt(const unsigned char *ibuf, unsigned char *obuf, - int len, unsigned char *cbuf, cbuf_inc ctr_inc, aes_encrypt_ctx cx[1]); - -#endif - -#if defined(__cplusplus) -} -#endif - -#endif +/* + --------------------------------------------------------------------------- + Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software is allowed (with or without + changes) provided that: + + 1. source code distributions include the above copyright notice, this + list of conditions and the following disclaimer; + + 2. binary distributions include the above copyright notice, this list + of conditions and the following disclaimer in their documentation; + + 3. the name of the copyright holder is not used to endorse products + built using this software without specific written permission. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + Issue Date: 20/12/2007 + + This file contains the definitions required to use AES in C. See aesopt.h + for optimisation details. +*/ + +/* Adapted for TrueCrypt */ + +#ifndef _AES_H +#define _AES_H + +#include "Common/Tcdefs.h" + +#ifndef EXIT_SUCCESS +#define EXIT_SUCCESS 0 +#define EXIT_FAILURE 1 +#endif +#define INT_RETURN int + +#if defined(__cplusplus) +extern "C" +{ +#endif + +// #define AES_128 /* define if AES with 128 bit keys is needed */ +// #define AES_192 /* define if AES with 192 bit keys is needed */ +#define AES_256 /* define if AES with 256 bit keys is needed */ +// #define AES_VAR /* define if a variable key size is needed */ +// #define AES_MODES /* define if support is needed for modes */ + +/* The following must also be set in assembler files if being used */ + +#define AES_ENCRYPT /* if support for encryption is needed */ +#define AES_DECRYPT /* if support for decryption is needed */ +#define AES_ERR_CHK /* for parameter checks & error return codes */ +#define AES_REV_DKS /* define to reverse decryption key schedule */ + +#define AES_BLOCK_SIZE 16 /* the AES block size in bytes */ +#define N_COLS 4 /* the number of columns in the state */ + +/* The key schedule length is 11, 13 or 15 16-byte blocks for 128, */ +/* 192 or 256-bit keys respectively. That is 176, 208 or 240 bytes */ +/* or 44, 52 or 60 32-bit words. */ + +#if defined( AES_VAR ) || defined( AES_256 ) +#define KS_LENGTH 60 +#elif defined( AES_192 ) +#define KS_LENGTH 52 +#else +#define KS_LENGTH 44 +#endif + +#if defined( AES_ERR_CHK ) +#define AES_RETURN INT_RETURN +#else +#define AES_RETURN VOID_RETURN +#endif + +/* the character array 'inf' in the following structures is used */ +/* to hold AES context information. This AES code uses cx->inf.b[0] */ +/* to hold the number of rounds multiplied by 16. The other three */ +/* elements can be used by code that implements additional modes */ + +typedef union +{ uint_32t l; + uint_8t b[4]; +} aes_inf; + +typedef struct +{ uint_32t ks[KS_LENGTH]; + aes_inf inf; +} aes_encrypt_ctx; + +typedef struct +{ uint_32t ks[KS_LENGTH]; + aes_inf inf; +} aes_decrypt_ctx; + +/* This routine must be called before first use if non-static */ +/* tables are being used */ + +AES_RETURN aes_init(void); + +/* Key lengths in the range 16 <= key_len <= 32 are given in bytes, */ +/* those in the range 128 <= key_len <= 256 are given in bits */ + +#if defined( AES_ENCRYPT ) + +#if defined(AES_128) || defined(AES_VAR) +AES_RETURN aes_encrypt_key128(const unsigned char *key, aes_encrypt_ctx cx[1]); +#endif + +#if defined(AES_192) || defined(AES_VAR) +AES_RETURN aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1]); +#endif + +#if defined(AES_256) || defined(AES_VAR) +AES_RETURN aes_encrypt_key256(const unsigned char *key, aes_encrypt_ctx cx[1]); +#endif + +#if defined(AES_VAR) +AES_RETURN aes_encrypt_key(const unsigned char *key, int key_len, aes_encrypt_ctx cx[1]); +#endif + +AES_RETURN aes_encrypt(const unsigned char *in, unsigned char *out, const aes_encrypt_ctx cx[1]); + +#endif + +#if defined( AES_DECRYPT ) + +#if defined(AES_128) || defined(AES_VAR) +AES_RETURN aes_decrypt_key128(const unsigned char *key, aes_decrypt_ctx cx[1]); +#endif + +#if defined(AES_192) || defined(AES_VAR) +AES_RETURN aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1]); +#endif + +#if defined(AES_256) || defined(AES_VAR) +AES_RETURN aes_decrypt_key256(const unsigned char *key, aes_decrypt_ctx cx[1]); +#endif + +#if defined(AES_VAR) +AES_RETURN aes_decrypt_key(const unsigned char *key, int key_len, aes_decrypt_ctx cx[1]); +#endif + +AES_RETURN aes_decrypt(const unsigned char *in, unsigned char *out, const aes_decrypt_ctx cx[1]); + +#endif + +#if defined(AES_MODES) + +/* Multiple calls to the following subroutines for multiple block */ +/* ECB, CBC, CFB, OFB and CTR mode encryption can be used to handle */ +/* long messages incremantally provided that the context AND the iv */ +/* are preserved between all such calls. For the ECB and CBC modes */ +/* each individual call within a series of incremental calls must */ +/* process only full blocks (i.e. len must be a multiple of 16) but */ +/* the CFB, OFB and CTR mode calls can handle multiple incremental */ +/* calls of any length. Each mode is reset when a new AES key is */ +/* set but ECB and CBC operations can be reset without setting a */ +/* new key by setting a new IV value. To reset CFB, OFB and CTR */ +/* without setting the key, aes_mode_reset() must be called and the */ +/* IV must be set. NOTE: All these calls update the IV on exit so */ +/* this has to be reset if a new operation with the same IV as the */ +/* previous one is required (or decryption follows encryption with */ +/* the same IV array). */ + +AES_RETURN aes_test_alignment_detection(unsigned int n); + +AES_RETURN aes_ecb_encrypt(const unsigned char *ibuf, unsigned char *obuf, + int len, const aes_encrypt_ctx cx[1]); + +AES_RETURN aes_ecb_decrypt(const unsigned char *ibuf, unsigned char *obuf, + int len, const aes_decrypt_ctx cx[1]); + +AES_RETURN aes_cbc_encrypt(const unsigned char *ibuf, unsigned char *obuf, + int len, unsigned char *iv, const aes_encrypt_ctx cx[1]); + +AES_RETURN aes_cbc_decrypt(const unsigned char *ibuf, unsigned char *obuf, + int len, unsigned char *iv, const aes_decrypt_ctx cx[1]); + +AES_RETURN aes_mode_reset(aes_encrypt_ctx cx[1]); + +AES_RETURN aes_cfb_encrypt(const unsigned char *ibuf, unsigned char *obuf, + int len, unsigned char *iv, aes_encrypt_ctx cx[1]); + +AES_RETURN aes_cfb_decrypt(const unsigned char *ibuf, unsigned char *obuf, + int len, unsigned char *iv, aes_encrypt_ctx cx[1]); + +#define aes_ofb_encrypt aes_ofb_crypt +#define aes_ofb_decrypt aes_ofb_crypt + +AES_RETURN aes_ofb_crypt(const unsigned char *ibuf, unsigned char *obuf, + int len, unsigned char *iv, aes_encrypt_ctx cx[1]); + +typedef void cbuf_inc(unsigned char *cbuf); + +#define aes_ctr_encrypt aes_ctr_crypt +#define aes_ctr_decrypt aes_ctr_crypt + +AES_RETURN aes_ctr_crypt(const unsigned char *ibuf, unsigned char *obuf, + int len, unsigned char *cbuf, cbuf_inc ctr_inc, aes_encrypt_ctx cx[1]); + +#endif + +#if defined(__cplusplus) +} +#endif + +#endif diff --git a/src/Crypto/AesSmall.c b/src/Crypto/AesSmall.c index 91c89873..10e7cf83 100644 --- a/src/Crypto/AesSmall.c +++ b/src/Crypto/AesSmall.c @@ -1,953 +1,953 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 1998-2006, Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software is allowed (with or without - changes) provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue 09/09/2006 - - This is an AES implementation that uses only 8-bit byte operations on the - cipher state (there are options to use 32-bit types if available). - - The combination of mix columns and byte substitution used here is based on - that developed by Karl Malbrain. His contribution is acknowledged. - */ - -/* Adapted for TrueCrypt: - - Macro-generated tables were replaced with static data to enable compiling - with MSVC++ 1.5 which runs out of resources when expanding large macros. -*/ - -#pragma optimize ("t", on) - -/* define if you have a fast memcpy function on your system */ -#if 1 -# define HAVE_MEMCPY -# include -# if defined( _MSC_VER ) -# ifndef DEBUG -# pragma intrinsic( memcpy ) -# endif -# endif -#endif - -/* define if you have fast 32-bit types on your system */ -#if 1 -# define HAVE_UINT_32T -#endif - -/* alternative versions (test for performance on your system) */ -#if 0 -# define VERSION_1 -#endif - -#include "AesSmall.h" - -#define WPOLY 0x011b -#define DPOLY 0x008d -#define f1(x) (x) -#define f2(x) ((x<<1) ^ (((x>>7) & 1) * WPOLY)) -#define f4(x) ((x<<2) ^ (((x>>6) & 1) * WPOLY) ^ (((x>>6) & 2) * WPOLY)) -#define f8(x) ((x<<3) ^ (((x>>5) & 1) * WPOLY) ^ (((x>>5) & 2) * WPOLY) \ - ^ (((x>>5) & 4) * WPOLY)) -#define d2(x) (((x) >> 1) ^ ((x) & 1 ? DPOLY : 0)) - -#define f3(x) (f2(x) ^ x) -#define f9(x) (f8(x) ^ x) -#define fb(x) (f8(x) ^ f2(x) ^ x) -#define fd(x) (f8(x) ^ f4(x) ^ x) -#define fe(x) (f8(x) ^ f4(x) ^ f2(x)) - -static const uint_8t s_box[256] = { - 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5, - 0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, - 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0, - 0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, - 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc, - 0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15, - 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a, - 0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75, - 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0, - 0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84, - 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b, - 0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf, - 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85, - 0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8, - 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5, - 0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2, - 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17, - 0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, - 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88, - 0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, - 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c, - 0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, - 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9, - 0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08, - 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6, - 0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a, - 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e, - 0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e, - 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94, - 0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, - 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68, - 0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16 -}; - -static const uint_8t inv_s_box[256] = { - 0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38, - 0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb, - 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87, - 0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb, - 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d, - 0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e, - 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2, - 0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25, - 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16, - 0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92, - 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda, - 0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84, - 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a, - 0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06, - 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02, - 0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b, - 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea, - 0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73, - 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85, - 0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e, - 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89, - 0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b, - 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20, - 0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4, - 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31, - 0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f, - 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d, - 0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef, - 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0, - 0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61, - 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26, - 0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d -}; - -static const uint_8t gfm2_s_box[256] = { - 0xc6,0xf8,0xee,0xf6,0xff,0xd6,0xde,0x91, - 0x60,0x02,0xce,0x56,0xe7,0xb5,0x4d,0xec, - 0x8f,0x1f,0x89,0xfa,0xef,0xb2,0x8e,0xfb, - 0x41,0xb3,0x5f,0x45,0x23,0x53,0xe4,0x9b, - 0x75,0xe1,0x3d,0x4c,0x6c,0x7e,0xf5,0x83, - 0x68,0x51,0xd1,0xf9,0xe2,0xab,0x62,0x2a, - 0x08,0x95,0x46,0x9d,0x30,0x37,0x0a,0x2f, - 0x0e,0x24,0x1b,0xdf,0xcd,0x4e,0x7f,0xea, - 0x12,0x1d,0x58,0x34,0x36,0xdc,0xb4,0x5b, - 0xa4,0x76,0xb7,0x7d,0x52,0xdd,0x5e,0x13, - 0xa6,0xb9,0x00,0xc1,0x40,0xe3,0x79,0xb6, - 0xd4,0x8d,0x67,0x72,0x94,0x98,0xb0,0x85, - 0xbb,0xc5,0x4f,0xed,0x86,0x9a,0x66,0x11, - 0x8a,0xe9,0x04,0xfe,0xa0,0x78,0x25,0x4b, - 0xa2,0x5d,0x80,0x05,0x3f,0x21,0x70,0xf1, - 0x63,0x77,0xaf,0x42,0x20,0xe5,0xfd,0xbf, - 0x81,0x18,0x26,0xc3,0xbe,0x35,0x88,0x2e, - 0x93,0x55,0xfc,0x7a,0xc8,0xba,0x32,0xe6, - 0xc0,0x19,0x9e,0xa3,0x44,0x54,0x3b,0x0b, - 0x8c,0xc7,0x6b,0x28,0xa7,0xbc,0x16,0xad, - 0xdb,0x64,0x74,0x14,0x92,0x0c,0x48,0xb8, - 0x9f,0xbd,0x43,0xc4,0x39,0x31,0xd3,0xf2, - 0xd5,0x8b,0x6e,0xda,0x01,0xb1,0x9c,0x49, - 0xd8,0xac,0xf3,0xcf,0xca,0xf4,0x47,0x10, - 0x6f,0xf0,0x4a,0x5c,0x38,0x57,0x73,0x97, - 0xcb,0xa1,0xe8,0x3e,0x96,0x61,0x0d,0x0f, - 0xe0,0x7c,0x71,0xcc,0x90,0x06,0xf7,0x1c, - 0xc2,0x6a,0xae,0x69,0x17,0x99,0x3a,0x27, - 0xd9,0xeb,0x2b,0x22,0xd2,0xa9,0x07,0x33, - 0x2d,0x3c,0x15,0xc9,0x87,0xaa,0x50,0xa5, - 0x03,0x59,0x09,0x1a,0x65,0xd7,0x84,0xd0, - 0x82,0x29,0x5a,0x1e,0x7b,0xa8,0x6d,0x2c -}; - -static const uint_8t gfm3_s_box[256] = { - 0xa5,0x84,0x99,0x8d,0x0d,0xbd,0xb1,0x54, - 0x50,0x03,0xa9,0x7d,0x19,0x62,0xe6,0x9a, - 0x45,0x9d,0x40,0x87,0x15,0xeb,0xc9,0x0b, - 0xec,0x67,0xfd,0xea,0xbf,0xf7,0x96,0x5b, - 0xc2,0x1c,0xae,0x6a,0x5a,0x41,0x02,0x4f, - 0x5c,0xf4,0x34,0x08,0x93,0x73,0x53,0x3f, - 0x0c,0x52,0x65,0x5e,0x28,0xa1,0x0f,0xb5, - 0x09,0x36,0x9b,0x3d,0x26,0x69,0xcd,0x9f, - 0x1b,0x9e,0x74,0x2e,0x2d,0xb2,0xee,0xfb, - 0xf6,0x4d,0x61,0xce,0x7b,0x3e,0x71,0x97, - 0xf5,0x68,0x00,0x2c,0x60,0x1f,0xc8,0xed, - 0xbe,0x46,0xd9,0x4b,0xde,0xd4,0xe8,0x4a, - 0x6b,0x2a,0xe5,0x16,0xc5,0xd7,0x55,0x94, - 0xcf,0x10,0x06,0x81,0xf0,0x44,0xba,0xe3, - 0xf3,0xfe,0xc0,0x8a,0xad,0xbc,0x48,0x04, - 0xdf,0xc1,0x75,0x63,0x30,0x1a,0x0e,0x6d, - 0x4c,0x14,0x35,0x2f,0xe1,0xa2,0xcc,0x39, - 0x57,0xf2,0x82,0x47,0xac,0xe7,0x2b,0x95, - 0xa0,0x98,0xd1,0x7f,0x66,0x7e,0xab,0x83, - 0xca,0x29,0xd3,0x3c,0x79,0xe2,0x1d,0x76, - 0x3b,0x56,0x4e,0x1e,0xdb,0x0a,0x6c,0xe4, - 0x5d,0x6e,0xef,0xa6,0xa8,0xa4,0x37,0x8b, - 0x32,0x43,0x59,0xb7,0x8c,0x64,0xd2,0xe0, - 0xb4,0xfa,0x07,0x25,0xaf,0x8e,0xe9,0x18, - 0xd5,0x88,0x6f,0x72,0x24,0xf1,0xc7,0x51, - 0x23,0x7c,0x9c,0x21,0xdd,0xdc,0x86,0x85, - 0x90,0x42,0xc4,0xaa,0xd8,0x05,0x01,0x12, - 0xa3,0x5f,0xf9,0xd0,0x91,0x58,0x27,0xb9, - 0x38,0x13,0xb3,0x33,0xbb,0x70,0x89,0xa7, - 0xb6,0x22,0x92,0x20,0x49,0xff,0x78,0x7a, - 0x8f,0xf8,0x80,0x17,0xda,0x31,0xc6,0xb8, - 0xc3,0xb0,0x77,0x11,0xcb,0xfc,0xd6,0x3a -}; - -static const uint_8t gfmul_9[256] = { - 0x00,0x09,0x12,0x1b,0x24,0x2d,0x36,0x3f, - 0x48,0x41,0x5a,0x53,0x6c,0x65,0x7e,0x77, - 0x90,0x99,0x82,0x8b,0xb4,0xbd,0xa6,0xaf, - 0xd8,0xd1,0xca,0xc3,0xfc,0xf5,0xee,0xe7, - 0x3b,0x32,0x29,0x20,0x1f,0x16,0x0d,0x04, - 0x73,0x7a,0x61,0x68,0x57,0x5e,0x45,0x4c, - 0xab,0xa2,0xb9,0xb0,0x8f,0x86,0x9d,0x94, - 0xe3,0xea,0xf1,0xf8,0xc7,0xce,0xd5,0xdc, - 0x76,0x7f,0x64,0x6d,0x52,0x5b,0x40,0x49, - 0x3e,0x37,0x2c,0x25,0x1a,0x13,0x08,0x01, - 0xe6,0xef,0xf4,0xfd,0xc2,0xcb,0xd0,0xd9, - 0xae,0xa7,0xbc,0xb5,0x8a,0x83,0x98,0x91, - 0x4d,0x44,0x5f,0x56,0x69,0x60,0x7b,0x72, - 0x05,0x0c,0x17,0x1e,0x21,0x28,0x33,0x3a, - 0xdd,0xd4,0xcf,0xc6,0xf9,0xf0,0xeb,0xe2, - 0x95,0x9c,0x87,0x8e,0xb1,0xb8,0xa3,0xaa, - 0xec,0xe5,0xfe,0xf7,0xc8,0xc1,0xda,0xd3, - 0xa4,0xad,0xb6,0xbf,0x80,0x89,0x92,0x9b, - 0x7c,0x75,0x6e,0x67,0x58,0x51,0x4a,0x43, - 0x34,0x3d,0x26,0x2f,0x10,0x19,0x02,0x0b, - 0xd7,0xde,0xc5,0xcc,0xf3,0xfa,0xe1,0xe8, - 0x9f,0x96,0x8d,0x84,0xbb,0xb2,0xa9,0xa0, - 0x47,0x4e,0x55,0x5c,0x63,0x6a,0x71,0x78, - 0x0f,0x06,0x1d,0x14,0x2b,0x22,0x39,0x30, - 0x9a,0x93,0x88,0x81,0xbe,0xb7,0xac,0xa5, - 0xd2,0xdb,0xc0,0xc9,0xf6,0xff,0xe4,0xed, - 0x0a,0x03,0x18,0x11,0x2e,0x27,0x3c,0x35, - 0x42,0x4b,0x50,0x59,0x66,0x6f,0x74,0x7d, - 0xa1,0xa8,0xb3,0xba,0x85,0x8c,0x97,0x9e, - 0xe9,0xe0,0xfb,0xf2,0xcd,0xc4,0xdf,0xd6, - 0x31,0x38,0x23,0x2a,0x15,0x1c,0x07,0x0e, - 0x79,0x70,0x6b,0x62,0x5d,0x54,0x4f,0x46 -}; - -static const uint_8t gfmul_b[256] = { - 0x00,0x0b,0x16,0x1d,0x2c,0x27,0x3a,0x31, - 0x58,0x53,0x4e,0x45,0x74,0x7f,0x62,0x69, - 0xb0,0xbb,0xa6,0xad,0x9c,0x97,0x8a,0x81, - 0xe8,0xe3,0xfe,0xf5,0xc4,0xcf,0xd2,0xd9, - 0x7b,0x70,0x6d,0x66,0x57,0x5c,0x41,0x4a, - 0x23,0x28,0x35,0x3e,0x0f,0x04,0x19,0x12, - 0xcb,0xc0,0xdd,0xd6,0xe7,0xec,0xf1,0xfa, - 0x93,0x98,0x85,0x8e,0xbf,0xb4,0xa9,0xa2, - 0xf6,0xfd,0xe0,0xeb,0xda,0xd1,0xcc,0xc7, - 0xae,0xa5,0xb8,0xb3,0x82,0x89,0x94,0x9f, - 0x46,0x4d,0x50,0x5b,0x6a,0x61,0x7c,0x77, - 0x1e,0x15,0x08,0x03,0x32,0x39,0x24,0x2f, - 0x8d,0x86,0x9b,0x90,0xa1,0xaa,0xb7,0xbc, - 0xd5,0xde,0xc3,0xc8,0xf9,0xf2,0xef,0xe4, - 0x3d,0x36,0x2b,0x20,0x11,0x1a,0x07,0x0c, - 0x65,0x6e,0x73,0x78,0x49,0x42,0x5f,0x54, - 0xf7,0xfc,0xe1,0xea,0xdb,0xd0,0xcd,0xc6, - 0xaf,0xa4,0xb9,0xb2,0x83,0x88,0x95,0x9e, - 0x47,0x4c,0x51,0x5a,0x6b,0x60,0x7d,0x76, - 0x1f,0x14,0x09,0x02,0x33,0x38,0x25,0x2e, - 0x8c,0x87,0x9a,0x91,0xa0,0xab,0xb6,0xbd, - 0xd4,0xdf,0xc2,0xc9,0xf8,0xf3,0xee,0xe5, - 0x3c,0x37,0x2a,0x21,0x10,0x1b,0x06,0x0d, - 0x64,0x6f,0x72,0x79,0x48,0x43,0x5e,0x55, - 0x01,0x0a,0x17,0x1c,0x2d,0x26,0x3b,0x30, - 0x59,0x52,0x4f,0x44,0x75,0x7e,0x63,0x68, - 0xb1,0xba,0xa7,0xac,0x9d,0x96,0x8b,0x80, - 0xe9,0xe2,0xff,0xf4,0xc5,0xce,0xd3,0xd8, - 0x7a,0x71,0x6c,0x67,0x56,0x5d,0x40,0x4b, - 0x22,0x29,0x34,0x3f,0x0e,0x05,0x18,0x13, - 0xca,0xc1,0xdc,0xd7,0xe6,0xed,0xf0,0xfb, - 0x92,0x99,0x84,0x8f,0xbe,0xb5,0xa8,0xa3 -}; - -static const uint_8t gfmul_d[256] = { - 0x00,0x0d,0x1a,0x17,0x34,0x39,0x2e,0x23, - 0x68,0x65,0x72,0x7f,0x5c,0x51,0x46,0x4b, - 0xd0,0xdd,0xca,0xc7,0xe4,0xe9,0xfe,0xf3, - 0xb8,0xb5,0xa2,0xaf,0x8c,0x81,0x96,0x9b, - 0xbb,0xb6,0xa1,0xac,0x8f,0x82,0x95,0x98, - 0xd3,0xde,0xc9,0xc4,0xe7,0xea,0xfd,0xf0, - 0x6b,0x66,0x71,0x7c,0x5f,0x52,0x45,0x48, - 0x03,0x0e,0x19,0x14,0x37,0x3a,0x2d,0x20, - 0x6d,0x60,0x77,0x7a,0x59,0x54,0x43,0x4e, - 0x05,0x08,0x1f,0x12,0x31,0x3c,0x2b,0x26, - 0xbd,0xb0,0xa7,0xaa,0x89,0x84,0x93,0x9e, - 0xd5,0xd8,0xcf,0xc2,0xe1,0xec,0xfb,0xf6, - 0xd6,0xdb,0xcc,0xc1,0xe2,0xef,0xf8,0xf5, - 0xbe,0xb3,0xa4,0xa9,0x8a,0x87,0x90,0x9d, - 0x06,0x0b,0x1c,0x11,0x32,0x3f,0x28,0x25, - 0x6e,0x63,0x74,0x79,0x5a,0x57,0x40,0x4d, - 0xda,0xd7,0xc0,0xcd,0xee,0xe3,0xf4,0xf9, - 0xb2,0xbf,0xa8,0xa5,0x86,0x8b,0x9c,0x91, - 0x0a,0x07,0x10,0x1d,0x3e,0x33,0x24,0x29, - 0x62,0x6f,0x78,0x75,0x56,0x5b,0x4c,0x41, - 0x61,0x6c,0x7b,0x76,0x55,0x58,0x4f,0x42, - 0x09,0x04,0x13,0x1e,0x3d,0x30,0x27,0x2a, - 0xb1,0xbc,0xab,0xa6,0x85,0x88,0x9f,0x92, - 0xd9,0xd4,0xc3,0xce,0xed,0xe0,0xf7,0xfa, - 0xb7,0xba,0xad,0xa0,0x83,0x8e,0x99,0x94, - 0xdf,0xd2,0xc5,0xc8,0xeb,0xe6,0xf1,0xfc, - 0x67,0x6a,0x7d,0x70,0x53,0x5e,0x49,0x44, - 0x0f,0x02,0x15,0x18,0x3b,0x36,0x21,0x2c, - 0x0c,0x01,0x16,0x1b,0x38,0x35,0x22,0x2f, - 0x64,0x69,0x7e,0x73,0x50,0x5d,0x4a,0x47, - 0xdc,0xd1,0xc6,0xcb,0xe8,0xe5,0xf2,0xff, - 0xb4,0xb9,0xae,0xa3,0x80,0x8d,0x9a,0x97 -}; - -static const uint_8t gfmul_e[256] = { - 0x00,0x0e,0x1c,0x12,0x38,0x36,0x24,0x2a, - 0x70,0x7e,0x6c,0x62,0x48,0x46,0x54,0x5a, - 0xe0,0xee,0xfc,0xf2,0xd8,0xd6,0xc4,0xca, - 0x90,0x9e,0x8c,0x82,0xa8,0xa6,0xb4,0xba, - 0xdb,0xd5,0xc7,0xc9,0xe3,0xed,0xff,0xf1, - 0xab,0xa5,0xb7,0xb9,0x93,0x9d,0x8f,0x81, - 0x3b,0x35,0x27,0x29,0x03,0x0d,0x1f,0x11, - 0x4b,0x45,0x57,0x59,0x73,0x7d,0x6f,0x61, - 0xad,0xa3,0xb1,0xbf,0x95,0x9b,0x89,0x87, - 0xdd,0xd3,0xc1,0xcf,0xe5,0xeb,0xf9,0xf7, - 0x4d,0x43,0x51,0x5f,0x75,0x7b,0x69,0x67, - 0x3d,0x33,0x21,0x2f,0x05,0x0b,0x19,0x17, - 0x76,0x78,0x6a,0x64,0x4e,0x40,0x52,0x5c, - 0x06,0x08,0x1a,0x14,0x3e,0x30,0x22,0x2c, - 0x96,0x98,0x8a,0x84,0xae,0xa0,0xb2,0xbc, - 0xe6,0xe8,0xfa,0xf4,0xde,0xd0,0xc2,0xcc, - 0x41,0x4f,0x5d,0x53,0x79,0x77,0x65,0x6b, - 0x31,0x3f,0x2d,0x23,0x09,0x07,0x15,0x1b, - 0xa1,0xaf,0xbd,0xb3,0x99,0x97,0x85,0x8b, - 0xd1,0xdf,0xcd,0xc3,0xe9,0xe7,0xf5,0xfb, - 0x9a,0x94,0x86,0x88,0xa2,0xac,0xbe,0xb0, - 0xea,0xe4,0xf6,0xf8,0xd2,0xdc,0xce,0xc0, - 0x7a,0x74,0x66,0x68,0x42,0x4c,0x5e,0x50, - 0x0a,0x04,0x16,0x18,0x32,0x3c,0x2e,0x20, - 0xec,0xe2,0xf0,0xfe,0xd4,0xda,0xc8,0xc6, - 0x9c,0x92,0x80,0x8e,0xa4,0xaa,0xb8,0xb6, - 0x0c,0x02,0x10,0x1e,0x34,0x3a,0x28,0x26, - 0x7c,0x72,0x60,0x6e,0x44,0x4a,0x58,0x56, - 0x37,0x39,0x2b,0x25,0x0f,0x01,0x13,0x1d, - 0x47,0x49,0x5b,0x55,0x7f,0x71,0x63,0x6d, - 0xd7,0xd9,0xcb,0xc5,0xef,0xe1,0xf3,0xfd, - 0xa7,0xa9,0xbb,0xb5,0x9f,0x91,0x83,0x8d -}; - -#if defined( HAVE_UINT_32T ) - typedef unsigned long uint_32t; -#endif - -#if defined( HAVE_MEMCPY ) -# define block_copy(d, s, l) memcpy(d, s, l) -# define block16_copy(d, s) memcpy(d, s, N_BLOCK) -#else -# define block_copy(d, s, l) copy_block(d, s, l) -# define block16_copy(d, s) copy_block16(d, s) -#endif - -/* block size 'nn' must be a multiple of four */ - -static void copy_block16( void *d, const void *s ) -{ -#if defined( HAVE_UINT_32T ) - ((uint_32t*)d)[ 0] = ((uint_32t*)s)[ 0]; - ((uint_32t*)d)[ 1] = ((uint_32t*)s)[ 1]; - ((uint_32t*)d)[ 2] = ((uint_32t*)s)[ 2]; - ((uint_32t*)d)[ 3] = ((uint_32t*)s)[ 3]; -#else - ((uint_8t*)d)[ 0] = ((uint_8t*)s)[ 0]; - ((uint_8t*)d)[ 1] = ((uint_8t*)s)[ 1]; - ((uint_8t*)d)[ 2] = ((uint_8t*)s)[ 2]; - ((uint_8t*)d)[ 3] = ((uint_8t*)s)[ 3]; - ((uint_8t*)d)[ 4] = ((uint_8t*)s)[ 4]; - ((uint_8t*)d)[ 5] = ((uint_8t*)s)[ 5]; - ((uint_8t*)d)[ 6] = ((uint_8t*)s)[ 6]; - ((uint_8t*)d)[ 7] = ((uint_8t*)s)[ 7]; - ((uint_8t*)d)[ 8] = ((uint_8t*)s)[ 8]; - ((uint_8t*)d)[ 9] = ((uint_8t*)s)[ 9]; - ((uint_8t*)d)[10] = ((uint_8t*)s)[10]; - ((uint_8t*)d)[11] = ((uint_8t*)s)[11]; - ((uint_8t*)d)[12] = ((uint_8t*)s)[12]; - ((uint_8t*)d)[13] = ((uint_8t*)s)[13]; - ((uint_8t*)d)[14] = ((uint_8t*)s)[14]; - ((uint_8t*)d)[15] = ((uint_8t*)s)[15]; -#endif -} - -static void copy_block( void * d, void *s, uint_8t nn ) -{ - while( nn-- ) - *((uint_8t*)d)++ = *((uint_8t*)s)++; -} - -static void xor_block( void *d, const void *s ) -{ -#if defined( HAVE_UINT_32T ) - ((uint_32t*)d)[ 0] ^= ((uint_32t*)s)[ 0]; - ((uint_32t*)d)[ 1] ^= ((uint_32t*)s)[ 1]; - ((uint_32t*)d)[ 2] ^= ((uint_32t*)s)[ 2]; - ((uint_32t*)d)[ 3] ^= ((uint_32t*)s)[ 3]; -#else - ((uint_8t*)d)[ 0] ^= ((uint_8t*)s)[ 0]; - ((uint_8t*)d)[ 1] ^= ((uint_8t*)s)[ 1]; - ((uint_8t*)d)[ 2] ^= ((uint_8t*)s)[ 2]; - ((uint_8t*)d)[ 3] ^= ((uint_8t*)s)[ 3]; - ((uint_8t*)d)[ 4] ^= ((uint_8t*)s)[ 4]; - ((uint_8t*)d)[ 5] ^= ((uint_8t*)s)[ 5]; - ((uint_8t*)d)[ 6] ^= ((uint_8t*)s)[ 6]; - ((uint_8t*)d)[ 7] ^= ((uint_8t*)s)[ 7]; - ((uint_8t*)d)[ 8] ^= ((uint_8t*)s)[ 8]; - ((uint_8t*)d)[ 9] ^= ((uint_8t*)s)[ 9]; - ((uint_8t*)d)[10] ^= ((uint_8t*)s)[10]; - ((uint_8t*)d)[11] ^= ((uint_8t*)s)[11]; - ((uint_8t*)d)[12] ^= ((uint_8t*)s)[12]; - ((uint_8t*)d)[13] ^= ((uint_8t*)s)[13]; - ((uint_8t*)d)[14] ^= ((uint_8t*)s)[14]; - ((uint_8t*)d)[15] ^= ((uint_8t*)s)[15]; -#endif -} - -static void copy_and_key( void *d, const void *s, const void *k ) -{ -#if defined( HAVE_UINT_32T ) - ((uint_32t*)d)[ 0] = ((uint_32t*)s)[ 0] ^ ((uint_32t*)k)[ 0]; - ((uint_32t*)d)[ 1] = ((uint_32t*)s)[ 1] ^ ((uint_32t*)k)[ 1]; - ((uint_32t*)d)[ 2] = ((uint_32t*)s)[ 2] ^ ((uint_32t*)k)[ 2]; - ((uint_32t*)d)[ 3] = ((uint_32t*)s)[ 3] ^ ((uint_32t*)k)[ 3]; -#elif 1 - ((uint_8t*)d)[ 0] = ((uint_8t*)s)[ 0] ^ ((uint_8t*)k)[ 0]; - ((uint_8t*)d)[ 1] = ((uint_8t*)s)[ 1] ^ ((uint_8t*)k)[ 1]; - ((uint_8t*)d)[ 2] = ((uint_8t*)s)[ 2] ^ ((uint_8t*)k)[ 2]; - ((uint_8t*)d)[ 3] = ((uint_8t*)s)[ 3] ^ ((uint_8t*)k)[ 3]; - ((uint_8t*)d)[ 4] = ((uint_8t*)s)[ 4] ^ ((uint_8t*)k)[ 4]; - ((uint_8t*)d)[ 5] = ((uint_8t*)s)[ 5] ^ ((uint_8t*)k)[ 5]; - ((uint_8t*)d)[ 6] = ((uint_8t*)s)[ 6] ^ ((uint_8t*)k)[ 6]; - ((uint_8t*)d)[ 7] = ((uint_8t*)s)[ 7] ^ ((uint_8t*)k)[ 7]; - ((uint_8t*)d)[ 8] = ((uint_8t*)s)[ 8] ^ ((uint_8t*)k)[ 8]; - ((uint_8t*)d)[ 9] = ((uint_8t*)s)[ 9] ^ ((uint_8t*)k)[ 9]; - ((uint_8t*)d)[10] = ((uint_8t*)s)[10] ^ ((uint_8t*)k)[10]; - ((uint_8t*)d)[11] = ((uint_8t*)s)[11] ^ ((uint_8t*)k)[11]; - ((uint_8t*)d)[12] = ((uint_8t*)s)[12] ^ ((uint_8t*)k)[12]; - ((uint_8t*)d)[13] = ((uint_8t*)s)[13] ^ ((uint_8t*)k)[13]; - ((uint_8t*)d)[14] = ((uint_8t*)s)[14] ^ ((uint_8t*)k)[14]; - ((uint_8t*)d)[15] = ((uint_8t*)s)[15] ^ ((uint_8t*)k)[15]; -#else - block16_copy(d, s); - xor_block(d, k); -#endif -} - -static void add_round_key( uint_8t d[N_BLOCK], const uint_8t k[N_BLOCK] ) -{ - xor_block(d, k); -} - -static void shift_sub_rows( uint_8t st[N_BLOCK] ) -{ uint_8t tt; - - st[ 0] = s_box[st[ 0]]; st[ 4] = s_box[st[ 4]]; - st[ 8] = s_box[st[ 8]]; st[12] = s_box[st[12]]; - - tt = st[1]; st[ 1] = s_box[st[ 5]]; st[ 5] = s_box[st[ 9]]; - st[ 9] = s_box[st[13]]; st[13] = s_box[ tt ]; - - tt = st[2]; st[ 2] = s_box[st[10]]; st[10] = s_box[ tt ]; - tt = st[6]; st[ 6] = s_box[st[14]]; st[14] = s_box[ tt ]; - - tt = st[15]; st[15] = s_box[st[11]]; st[11] = s_box[st[ 7]]; - st[ 7] = s_box[st[ 3]]; st[ 3] = s_box[ tt ]; -} - -static void inv_shift_sub_rows( uint_8t st[N_BLOCK] ) -{ uint_8t tt; - - st[ 0] = inv_s_box[st[ 0]]; st[ 4] = inv_s_box[st[ 4]]; - st[ 8] = inv_s_box[st[ 8]]; st[12] = inv_s_box[st[12]]; - - tt = st[13]; st[13] = inv_s_box[st[9]]; st[ 9] = inv_s_box[st[5]]; - st[ 5] = inv_s_box[st[1]]; st[ 1] = inv_s_box[ tt ]; - - tt = st[2]; st[ 2] = inv_s_box[st[10]]; st[10] = inv_s_box[ tt ]; - tt = st[6]; st[ 6] = inv_s_box[st[14]]; st[14] = inv_s_box[ tt ]; - - tt = st[3]; st[ 3] = inv_s_box[st[ 7]]; st[ 7] = inv_s_box[st[11]]; - st[11] = inv_s_box[st[15]]; st[15] = inv_s_box[ tt ]; -} - -#if defined( VERSION_1 ) - static void mix_sub_columns( uint_8t dt[N_BLOCK] ) - { uint_8t st[N_BLOCK]; - block16_copy(st, dt); -#else - static void mix_sub_columns( uint_8t dt[N_BLOCK], uint_8t st[N_BLOCK] ) - { -#endif - dt[ 0] = gfm2_s_box[st[0]] ^ gfm3_s_box[st[5]] ^ s_box[st[10]] ^ s_box[st[15]]; - dt[ 1] = s_box[st[0]] ^ gfm2_s_box[st[5]] ^ gfm3_s_box[st[10]] ^ s_box[st[15]]; - dt[ 2] = s_box[st[0]] ^ s_box[st[5]] ^ gfm2_s_box[st[10]] ^ gfm3_s_box[st[15]]; - dt[ 3] = gfm3_s_box[st[0]] ^ s_box[st[5]] ^ s_box[st[10]] ^ gfm2_s_box[st[15]]; - - dt[ 4] = gfm2_s_box[st[4]] ^ gfm3_s_box[st[9]] ^ s_box[st[14]] ^ s_box[st[3]]; - dt[ 5] = s_box[st[4]] ^ gfm2_s_box[st[9]] ^ gfm3_s_box[st[14]] ^ s_box[st[3]]; - dt[ 6] = s_box[st[4]] ^ s_box[st[9]] ^ gfm2_s_box[st[14]] ^ gfm3_s_box[st[3]]; - dt[ 7] = gfm3_s_box[st[4]] ^ s_box[st[9]] ^ s_box[st[14]] ^ gfm2_s_box[st[3]]; - - dt[ 8] = gfm2_s_box[st[8]] ^ gfm3_s_box[st[13]] ^ s_box[st[2]] ^ s_box[st[7]]; - dt[ 9] = s_box[st[8]] ^ gfm2_s_box[st[13]] ^ gfm3_s_box[st[2]] ^ s_box[st[7]]; - dt[10] = s_box[st[8]] ^ s_box[st[13]] ^ gfm2_s_box[st[2]] ^ gfm3_s_box[st[7]]; - dt[11] = gfm3_s_box[st[8]] ^ s_box[st[13]] ^ s_box[st[2]] ^ gfm2_s_box[st[7]]; - - dt[12] = gfm2_s_box[st[12]] ^ gfm3_s_box[st[1]] ^ s_box[st[6]] ^ s_box[st[11]]; - dt[13] = s_box[st[12]] ^ gfm2_s_box[st[1]] ^ gfm3_s_box[st[6]] ^ s_box[st[11]]; - dt[14] = s_box[st[12]] ^ s_box[st[1]] ^ gfm2_s_box[st[6]] ^ gfm3_s_box[st[11]]; - dt[15] = gfm3_s_box[st[12]] ^ s_box[st[1]] ^ s_box[st[6]] ^ gfm2_s_box[st[11]]; - } - -#if defined( VERSION_1 ) - static void inv_mix_sub_columns( uint_8t dt[N_BLOCK] ) - { uint_8t st[N_BLOCK]; - block16_copy(st, dt); -#else - static void inv_mix_sub_columns( uint_8t dt[N_BLOCK], uint_8t st[N_BLOCK] ) - { -#endif - dt[ 0] = inv_s_box[gfmul_e[st[ 0]] ^ gfmul_b[st[ 1]] ^ gfmul_d[st[ 2]] ^ gfmul_9[st[ 3]]]; - dt[ 5] = inv_s_box[gfmul_9[st[ 0]] ^ gfmul_e[st[ 1]] ^ gfmul_b[st[ 2]] ^ gfmul_d[st[ 3]]]; - dt[10] = inv_s_box[gfmul_d[st[ 0]] ^ gfmul_9[st[ 1]] ^ gfmul_e[st[ 2]] ^ gfmul_b[st[ 3]]]; - dt[15] = inv_s_box[gfmul_b[st[ 0]] ^ gfmul_d[st[ 1]] ^ gfmul_9[st[ 2]] ^ gfmul_e[st[ 3]]]; - - dt[ 4] = inv_s_box[gfmul_e[st[ 4]] ^ gfmul_b[st[ 5]] ^ gfmul_d[st[ 6]] ^ gfmul_9[st[ 7]]]; - dt[ 9] = inv_s_box[gfmul_9[st[ 4]] ^ gfmul_e[st[ 5]] ^ gfmul_b[st[ 6]] ^ gfmul_d[st[ 7]]]; - dt[14] = inv_s_box[gfmul_d[st[ 4]] ^ gfmul_9[st[ 5]] ^ gfmul_e[st[ 6]] ^ gfmul_b[st[ 7]]]; - dt[ 3] = inv_s_box[gfmul_b[st[ 4]] ^ gfmul_d[st[ 5]] ^ gfmul_9[st[ 6]] ^ gfmul_e[st[ 7]]]; - - dt[ 8] = inv_s_box[gfmul_e[st[ 8]] ^ gfmul_b[st[ 9]] ^ gfmul_d[st[10]] ^ gfmul_9[st[11]]]; - dt[13] = inv_s_box[gfmul_9[st[ 8]] ^ gfmul_e[st[ 9]] ^ gfmul_b[st[10]] ^ gfmul_d[st[11]]]; - dt[ 2] = inv_s_box[gfmul_d[st[ 8]] ^ gfmul_9[st[ 9]] ^ gfmul_e[st[10]] ^ gfmul_b[st[11]]]; - dt[ 7] = inv_s_box[gfmul_b[st[ 8]] ^ gfmul_d[st[ 9]] ^ gfmul_9[st[10]] ^ gfmul_e[st[11]]]; - - dt[12] = inv_s_box[gfmul_e[st[12]] ^ gfmul_b[st[13]] ^ gfmul_d[st[14]] ^ gfmul_9[st[15]]]; - dt[ 1] = inv_s_box[gfmul_9[st[12]] ^ gfmul_e[st[13]] ^ gfmul_b[st[14]] ^ gfmul_d[st[15]]]; - dt[ 6] = inv_s_box[gfmul_d[st[12]] ^ gfmul_9[st[13]] ^ gfmul_e[st[14]] ^ gfmul_b[st[15]]]; - dt[11] = inv_s_box[gfmul_b[st[12]] ^ gfmul_d[st[13]] ^ gfmul_9[st[14]] ^ gfmul_e[st[15]]]; - } - -#if defined( AES_ENC_PREKEYED ) || defined( AES_DEC_PREKEYED ) - -/* Set the cipher key for the pre-keyed version */ - -return_type aes_set_key( const unsigned char key[], length_type keylen, aes_context ctx[1] ) -{ - uint_8t cc, rc, hi; - - switch( keylen ) - { - case 16: - case 128: - keylen = 16; - break; - case 24: - case 192: - keylen = 24; - break; - case 32: - case 256: - keylen = 32; - break; - default: - ctx->rnd = 0; - return (return_type) -1; - } - block_copy(ctx->ksch, key, keylen); - hi = (keylen + 28) << 2; - ctx->rnd = (hi >> 4) - 1; - for( cc = keylen, rc = 1; cc < hi; cc += 4 ) - { uint_8t tt, t0, t1, t2, t3; - - t0 = ctx->ksch[cc - 4]; - t1 = ctx->ksch[cc - 3]; - t2 = ctx->ksch[cc - 2]; - t3 = ctx->ksch[cc - 1]; - if( cc % keylen == 0 ) - { - tt = t0; - t0 = s_box[t1] ^ rc; - t1 = s_box[t2]; - t2 = s_box[t3]; - t3 = s_box[tt]; - rc = f2(rc); - } - else if( keylen > 24 && cc % keylen == 16 ) - { - t0 = s_box[t0]; - t1 = s_box[t1]; - t2 = s_box[t2]; - t3 = s_box[t3]; - } - tt = cc - keylen; - ctx->ksch[cc + 0] = ctx->ksch[tt + 0] ^ t0; - ctx->ksch[cc + 1] = ctx->ksch[tt + 1] ^ t1; - ctx->ksch[cc + 2] = ctx->ksch[tt + 2] ^ t2; - ctx->ksch[cc + 3] = ctx->ksch[tt + 3] ^ t3; - } - return 0; -} - -#endif - -#if defined( AES_ENC_PREKEYED ) - -/* Encrypt a single block of 16 bytes */ - -return_type aes_encrypt( const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], const aes_context ctx[1] ) -{ - if( ctx->rnd ) - { - uint_8t s1[N_BLOCK], r; - copy_and_key( s1, in, ctx->ksch ); - - for( r = 1 ; r < ctx->rnd ; ++r ) -#if defined( VERSION_1 ) - { - mix_sub_columns( s1 ); - add_round_key( s1, ctx->ksch + r * N_BLOCK); - } -#else - { uint_8t s2[N_BLOCK]; - mix_sub_columns( s2, s1 ); - copy_and_key( s1, s2, ctx->ksch + r * N_BLOCK); - } -#endif - shift_sub_rows( s1 ); - copy_and_key( out, s1, ctx->ksch + r * N_BLOCK ); - } - else - return (return_type) -1; - return 0; -} - -#endif - -#if defined( AES_DEC_PREKEYED ) - -/* Decrypt a single block of 16 bytes */ - -return_type aes_decrypt( const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], const aes_context ctx[1] ) -{ - if( ctx->rnd ) - { - uint_8t s1[N_BLOCK], r; - copy_and_key( s1, in, ctx->ksch + ctx->rnd * N_BLOCK ); - inv_shift_sub_rows( s1 ); - - for( r = ctx->rnd ; --r ; ) -#if defined( VERSION_1 ) - { - add_round_key( s1, ctx->ksch + r * N_BLOCK ); - inv_mix_sub_columns( s1 ); - } -#else - { uint_8t s2[N_BLOCK]; - copy_and_key( s2, s1, ctx->ksch + r * N_BLOCK ); - inv_mix_sub_columns( s1, s2 ); - } -#endif - copy_and_key( out, s1, ctx->ksch ); - } - else - return (return_type) -1; - return 0; -} - -#endif - -#if defined( AES_ENC_128_OTFK ) - -/* The 'on the fly' encryption key update for for 128 bit keys */ - -static void update_encrypt_key_128( uint_8t k[N_BLOCK], uint_8t *rc ) -{ uint_8t cc; - - k[0] ^= s_box[k[13]] ^ *rc; - k[1] ^= s_box[k[14]]; - k[2] ^= s_box[k[15]]; - k[3] ^= s_box[k[12]]; - *rc = f2( *rc ); - - for(cc = 4; cc < 16; cc += 4 ) - { - k[cc + 0] ^= k[cc - 4]; - k[cc + 1] ^= k[cc - 3]; - k[cc + 2] ^= k[cc - 2]; - k[cc + 3] ^= k[cc - 1]; - } -} - -/* Encrypt a single block of 16 bytes with 'on the fly' 128 bit keying */ - -void aes_encrypt_128( const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], - const unsigned char key[N_BLOCK], unsigned char o_key[N_BLOCK] ) -{ uint_8t s1[N_BLOCK], r, rc = 1; - - if(o_key != key) - block16_copy( o_key, key ); - copy_and_key( s1, in, o_key ); - - for( r = 1 ; r < 10 ; ++r ) -#if defined( VERSION_1 ) - { - mix_sub_columns( s1 ); - update_encrypt_key_128( o_key, &rc ); - add_round_key( s1, o_key ); - } -#else - { uint_8t s2[N_BLOCK]; - mix_sub_columns( s2, s1 ); - update_encrypt_key_128( o_key, &rc ); - copy_and_key( s1, s2, o_key ); - } -#endif - - shift_sub_rows( s1 ); - update_encrypt_key_128( o_key, &rc ); - copy_and_key( out, s1, o_key ); -} - -#endif - -#if defined( AES_DEC_128_OTFK ) - -/* The 'on the fly' decryption key update for for 128 bit keys */ - -static void update_decrypt_key_128( uint_8t k[N_BLOCK], uint_8t *rc ) -{ uint_8t cc; - - for( cc = 12; cc > 0; cc -= 4 ) - { - k[cc + 0] ^= k[cc - 4]; - k[cc + 1] ^= k[cc - 3]; - k[cc + 2] ^= k[cc - 2]; - k[cc + 3] ^= k[cc - 1]; - } - *rc = d2(*rc); - k[0] ^= s_box[k[13]] ^ *rc; - k[1] ^= s_box[k[14]]; - k[2] ^= s_box[k[15]]; - k[3] ^= s_box[k[12]]; -} - -/* Decrypt a single block of 16 bytes with 'on the fly' 128 bit keying */ - -void aes_decrypt_128( const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], - const unsigned char key[N_BLOCK], unsigned char o_key[N_BLOCK] ) -{ - uint_8t s1[N_BLOCK], r, rc = 0x6c; - if(o_key != key) - block16_copy( o_key, key ); - - copy_and_key( s1, in, o_key ); - inv_shift_sub_rows( s1 ); - - for( r = 10 ; --r ; ) -#if defined( VERSION_1 ) - { - update_decrypt_key_128( o_key, &rc ); - add_round_key( s1, o_key ); - inv_mix_sub_columns( s1 ); - } -#else - { uint_8t s2[N_BLOCK]; - update_decrypt_key_128( o_key, &rc ); - copy_and_key( s2, s1, o_key ); - inv_mix_sub_columns( s1, s2 ); - } -#endif - update_decrypt_key_128( o_key, &rc ); - copy_and_key( out, s1, o_key ); -} - -#endif - -#if defined( AES_ENC_256_OTFK ) - -/* The 'on the fly' encryption key update for for 256 bit keys */ - -static void update_encrypt_key_256( uint_8t k[2 * N_BLOCK], uint_8t *rc ) -{ uint_8t cc; - - k[0] ^= s_box[k[29]] ^ *rc; - k[1] ^= s_box[k[30]]; - k[2] ^= s_box[k[31]]; - k[3] ^= s_box[k[28]]; - *rc = f2( *rc ); - - for(cc = 4; cc < 16; cc += 4) - { - k[cc + 0] ^= k[cc - 4]; - k[cc + 1] ^= k[cc - 3]; - k[cc + 2] ^= k[cc - 2]; - k[cc + 3] ^= k[cc - 1]; - } - - k[16] ^= s_box[k[12]]; - k[17] ^= s_box[k[13]]; - k[18] ^= s_box[k[14]]; - k[19] ^= s_box[k[15]]; - - for( cc = 20; cc < 32; cc += 4 ) - { - k[cc + 0] ^= k[cc - 4]; - k[cc + 1] ^= k[cc - 3]; - k[cc + 2] ^= k[cc - 2]; - k[cc + 3] ^= k[cc - 1]; - } -} - -/* Encrypt a single block of 16 bytes with 'on the fly' 256 bit keying */ - -void aes_encrypt_256( const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], - const unsigned char key[2 * N_BLOCK], unsigned char o_key[2 * N_BLOCK] ) -{ - uint_8t s1[N_BLOCK], r, rc = 1; - if(o_key != key) - { - block16_copy( o_key, key ); - block16_copy( o_key + 16, key + 16 ); - } - copy_and_key( s1, in, o_key ); - - for( r = 1 ; r < 14 ; ++r ) -#if defined( VERSION_1 ) - { - mix_sub_columns(s1); - if( r & 1 ) - add_round_key( s1, o_key + 16 ); - else - { - update_encrypt_key_256( o_key, &rc ); - add_round_key( s1, o_key ); - } - } -#else - { uint_8t s2[N_BLOCK]; - mix_sub_columns( s2, s1 ); - if( r & 1 ) - copy_and_key( s1, s2, o_key + 16 ); - else - { - update_encrypt_key_256( o_key, &rc ); - copy_and_key( s1, s2, o_key ); - } - } -#endif - - shift_sub_rows( s1 ); - update_encrypt_key_256( o_key, &rc ); - copy_and_key( out, s1, o_key ); -} - -#endif - -#if defined( AES_DEC_256_OTFK ) - -/* The 'on the fly' encryption key update for for 256 bit keys */ - -static void update_decrypt_key_256( uint_8t k[2 * N_BLOCK], uint_8t *rc ) -{ uint_8t cc; - - for(cc = 28; cc > 16; cc -= 4) - { - k[cc + 0] ^= k[cc - 4]; - k[cc + 1] ^= k[cc - 3]; - k[cc + 2] ^= k[cc - 2]; - k[cc + 3] ^= k[cc - 1]; - } - - k[16] ^= s_box[k[12]]; - k[17] ^= s_box[k[13]]; - k[18] ^= s_box[k[14]]; - k[19] ^= s_box[k[15]]; - - for(cc = 12; cc > 0; cc -= 4) - { - k[cc + 0] ^= k[cc - 4]; - k[cc + 1] ^= k[cc - 3]; - k[cc + 2] ^= k[cc - 2]; - k[cc + 3] ^= k[cc - 1]; - } - - *rc = d2(*rc); - k[0] ^= s_box[k[29]] ^ *rc; - k[1] ^= s_box[k[30]]; - k[2] ^= s_box[k[31]]; - k[3] ^= s_box[k[28]]; -} - -/* Decrypt a single block of 16 bytes with 'on the fly' - 256 bit keying -*/ -void aes_decrypt_256( const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], - const unsigned char key[2 * N_BLOCK], unsigned char o_key[2 * N_BLOCK] ) -{ - uint_8t s1[N_BLOCK], r, rc = 0x80; - - if(o_key != key) - { - block16_copy( o_key, key ); - block16_copy( o_key + 16, key + 16 ); - } - - copy_and_key( s1, in, o_key ); - inv_shift_sub_rows( s1 ); - - for( r = 14 ; --r ; ) -#if defined( VERSION_1 ) - { - if( ( r & 1 ) ) - { - update_decrypt_key_256( o_key, &rc ); - add_round_key( s1, o_key + 16 ); - } - else - add_round_key( s1, o_key ); - inv_mix_sub_columns( s1 ); - } -#else - { uint_8t s2[N_BLOCK]; - if( ( r & 1 ) ) - { - update_decrypt_key_256( o_key, &rc ); - copy_and_key( s2, s1, o_key + 16 ); - } - else - copy_and_key( s2, s1, o_key ); - inv_mix_sub_columns( s1, s2 ); - } -#endif - copy_and_key( out, s1, o_key ); -} - -#endif +/* + --------------------------------------------------------------------------- + Copyright (c) 1998-2006, Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software is allowed (with or without + changes) provided that: + + 1. source code distributions include the above copyright notice, this + list of conditions and the following disclaimer; + + 2. binary distributions include the above copyright notice, this list + of conditions and the following disclaimer in their documentation; + + 3. the name of the copyright holder is not used to endorse products + built using this software without specific written permission. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + Issue 09/09/2006 + + This is an AES implementation that uses only 8-bit byte operations on the + cipher state (there are options to use 32-bit types if available). + + The combination of mix columns and byte substitution used here is based on + that developed by Karl Malbrain. His contribution is acknowledged. + */ + +/* Adapted for TrueCrypt: + - Macro-generated tables were replaced with static data to enable compiling + with MSVC++ 1.5 which runs out of resources when expanding large macros. +*/ + +#pragma optimize ("t", on) + +/* define if you have a fast memcpy function on your system */ +#if 1 +# define HAVE_MEMCPY +# include +# if defined( _MSC_VER ) +# ifndef DEBUG +# pragma intrinsic( memcpy ) +# endif +# endif +#endif + +/* define if you have fast 32-bit types on your system */ +#if 1 +# define HAVE_UINT_32T +#endif + +/* alternative versions (test for performance on your system) */ +#if 0 +# define VERSION_1 +#endif + +#include "AesSmall.h" + +#define WPOLY 0x011b +#define DPOLY 0x008d +#define f1(x) (x) +#define f2(x) ((x<<1) ^ (((x>>7) & 1) * WPOLY)) +#define f4(x) ((x<<2) ^ (((x>>6) & 1) * WPOLY) ^ (((x>>6) & 2) * WPOLY)) +#define f8(x) ((x<<3) ^ (((x>>5) & 1) * WPOLY) ^ (((x>>5) & 2) * WPOLY) \ + ^ (((x>>5) & 4) * WPOLY)) +#define d2(x) (((x) >> 1) ^ ((x) & 1 ? DPOLY : 0)) + +#define f3(x) (f2(x) ^ x) +#define f9(x) (f8(x) ^ x) +#define fb(x) (f8(x) ^ f2(x) ^ x) +#define fd(x) (f8(x) ^ f4(x) ^ x) +#define fe(x) (f8(x) ^ f4(x) ^ f2(x)) + +static const uint_8t s_box[256] = { + 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5, + 0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, + 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0, + 0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, + 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc, + 0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15, + 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a, + 0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75, + 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0, + 0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84, + 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b, + 0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf, + 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85, + 0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8, + 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5, + 0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2, + 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17, + 0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, + 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88, + 0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, + 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c, + 0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, + 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9, + 0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08, + 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6, + 0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a, + 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e, + 0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e, + 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94, + 0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, + 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68, + 0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16 +}; + +static const uint_8t inv_s_box[256] = { + 0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38, + 0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb, + 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87, + 0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb, + 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d, + 0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e, + 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2, + 0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25, + 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16, + 0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92, + 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda, + 0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84, + 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a, + 0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06, + 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02, + 0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b, + 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea, + 0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73, + 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85, + 0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e, + 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89, + 0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b, + 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20, + 0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4, + 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31, + 0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f, + 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d, + 0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef, + 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0, + 0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61, + 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26, + 0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d +}; + +static const uint_8t gfm2_s_box[256] = { + 0xc6,0xf8,0xee,0xf6,0xff,0xd6,0xde,0x91, + 0x60,0x02,0xce,0x56,0xe7,0xb5,0x4d,0xec, + 0x8f,0x1f,0x89,0xfa,0xef,0xb2,0x8e,0xfb, + 0x41,0xb3,0x5f,0x45,0x23,0x53,0xe4,0x9b, + 0x75,0xe1,0x3d,0x4c,0x6c,0x7e,0xf5,0x83, + 0x68,0x51,0xd1,0xf9,0xe2,0xab,0x62,0x2a, + 0x08,0x95,0x46,0x9d,0x30,0x37,0x0a,0x2f, + 0x0e,0x24,0x1b,0xdf,0xcd,0x4e,0x7f,0xea, + 0x12,0x1d,0x58,0x34,0x36,0xdc,0xb4,0x5b, + 0xa4,0x76,0xb7,0x7d,0x52,0xdd,0x5e,0x13, + 0xa6,0xb9,0x00,0xc1,0x40,0xe3,0x79,0xb6, + 0xd4,0x8d,0x67,0x72,0x94,0x98,0xb0,0x85, + 0xbb,0xc5,0x4f,0xed,0x86,0x9a,0x66,0x11, + 0x8a,0xe9,0x04,0xfe,0xa0,0x78,0x25,0x4b, + 0xa2,0x5d,0x80,0x05,0x3f,0x21,0x70,0xf1, + 0x63,0x77,0xaf,0x42,0x20,0xe5,0xfd,0xbf, + 0x81,0x18,0x26,0xc3,0xbe,0x35,0x88,0x2e, + 0x93,0x55,0xfc,0x7a,0xc8,0xba,0x32,0xe6, + 0xc0,0x19,0x9e,0xa3,0x44,0x54,0x3b,0x0b, + 0x8c,0xc7,0x6b,0x28,0xa7,0xbc,0x16,0xad, + 0xdb,0x64,0x74,0x14,0x92,0x0c,0x48,0xb8, + 0x9f,0xbd,0x43,0xc4,0x39,0x31,0xd3,0xf2, + 0xd5,0x8b,0x6e,0xda,0x01,0xb1,0x9c,0x49, + 0xd8,0xac,0xf3,0xcf,0xca,0xf4,0x47,0x10, + 0x6f,0xf0,0x4a,0x5c,0x38,0x57,0x73,0x97, + 0xcb,0xa1,0xe8,0x3e,0x96,0x61,0x0d,0x0f, + 0xe0,0x7c,0x71,0xcc,0x90,0x06,0xf7,0x1c, + 0xc2,0x6a,0xae,0x69,0x17,0x99,0x3a,0x27, + 0xd9,0xeb,0x2b,0x22,0xd2,0xa9,0x07,0x33, + 0x2d,0x3c,0x15,0xc9,0x87,0xaa,0x50,0xa5, + 0x03,0x59,0x09,0x1a,0x65,0xd7,0x84,0xd0, + 0x82,0x29,0x5a,0x1e,0x7b,0xa8,0x6d,0x2c +}; + +static const uint_8t gfm3_s_box[256] = { + 0xa5,0x84,0x99,0x8d,0x0d,0xbd,0xb1,0x54, + 0x50,0x03,0xa9,0x7d,0x19,0x62,0xe6,0x9a, + 0x45,0x9d,0x40,0x87,0x15,0xeb,0xc9,0x0b, + 0xec,0x67,0xfd,0xea,0xbf,0xf7,0x96,0x5b, + 0xc2,0x1c,0xae,0x6a,0x5a,0x41,0x02,0x4f, + 0x5c,0xf4,0x34,0x08,0x93,0x73,0x53,0x3f, + 0x0c,0x52,0x65,0x5e,0x28,0xa1,0x0f,0xb5, + 0x09,0x36,0x9b,0x3d,0x26,0x69,0xcd,0x9f, + 0x1b,0x9e,0x74,0x2e,0x2d,0xb2,0xee,0xfb, + 0xf6,0x4d,0x61,0xce,0x7b,0x3e,0x71,0x97, + 0xf5,0x68,0x00,0x2c,0x60,0x1f,0xc8,0xed, + 0xbe,0x46,0xd9,0x4b,0xde,0xd4,0xe8,0x4a, + 0x6b,0x2a,0xe5,0x16,0xc5,0xd7,0x55,0x94, + 0xcf,0x10,0x06,0x81,0xf0,0x44,0xba,0xe3, + 0xf3,0xfe,0xc0,0x8a,0xad,0xbc,0x48,0x04, + 0xdf,0xc1,0x75,0x63,0x30,0x1a,0x0e,0x6d, + 0x4c,0x14,0x35,0x2f,0xe1,0xa2,0xcc,0x39, + 0x57,0xf2,0x82,0x47,0xac,0xe7,0x2b,0x95, + 0xa0,0x98,0xd1,0x7f,0x66,0x7e,0xab,0x83, + 0xca,0x29,0xd3,0x3c,0x79,0xe2,0x1d,0x76, + 0x3b,0x56,0x4e,0x1e,0xdb,0x0a,0x6c,0xe4, + 0x5d,0x6e,0xef,0xa6,0xa8,0xa4,0x37,0x8b, + 0x32,0x43,0x59,0xb7,0x8c,0x64,0xd2,0xe0, + 0xb4,0xfa,0x07,0x25,0xaf,0x8e,0xe9,0x18, + 0xd5,0x88,0x6f,0x72,0x24,0xf1,0xc7,0x51, + 0x23,0x7c,0x9c,0x21,0xdd,0xdc,0x86,0x85, + 0x90,0x42,0xc4,0xaa,0xd8,0x05,0x01,0x12, + 0xa3,0x5f,0xf9,0xd0,0x91,0x58,0x27,0xb9, + 0x38,0x13,0xb3,0x33,0xbb,0x70,0x89,0xa7, + 0xb6,0x22,0x92,0x20,0x49,0xff,0x78,0x7a, + 0x8f,0xf8,0x80,0x17,0xda,0x31,0xc6,0xb8, + 0xc3,0xb0,0x77,0x11,0xcb,0xfc,0xd6,0x3a +}; + +static const uint_8t gfmul_9[256] = { + 0x00,0x09,0x12,0x1b,0x24,0x2d,0x36,0x3f, + 0x48,0x41,0x5a,0x53,0x6c,0x65,0x7e,0x77, + 0x90,0x99,0x82,0x8b,0xb4,0xbd,0xa6,0xaf, + 0xd8,0xd1,0xca,0xc3,0xfc,0xf5,0xee,0xe7, + 0x3b,0x32,0x29,0x20,0x1f,0x16,0x0d,0x04, + 0x73,0x7a,0x61,0x68,0x57,0x5e,0x45,0x4c, + 0xab,0xa2,0xb9,0xb0,0x8f,0x86,0x9d,0x94, + 0xe3,0xea,0xf1,0xf8,0xc7,0xce,0xd5,0xdc, + 0x76,0x7f,0x64,0x6d,0x52,0x5b,0x40,0x49, + 0x3e,0x37,0x2c,0x25,0x1a,0x13,0x08,0x01, + 0xe6,0xef,0xf4,0xfd,0xc2,0xcb,0xd0,0xd9, + 0xae,0xa7,0xbc,0xb5,0x8a,0x83,0x98,0x91, + 0x4d,0x44,0x5f,0x56,0x69,0x60,0x7b,0x72, + 0x05,0x0c,0x17,0x1e,0x21,0x28,0x33,0x3a, + 0xdd,0xd4,0xcf,0xc6,0xf9,0xf0,0xeb,0xe2, + 0x95,0x9c,0x87,0x8e,0xb1,0xb8,0xa3,0xaa, + 0xec,0xe5,0xfe,0xf7,0xc8,0xc1,0xda,0xd3, + 0xa4,0xad,0xb6,0xbf,0x80,0x89,0x92,0x9b, + 0x7c,0x75,0x6e,0x67,0x58,0x51,0x4a,0x43, + 0x34,0x3d,0x26,0x2f,0x10,0x19,0x02,0x0b, + 0xd7,0xde,0xc5,0xcc,0xf3,0xfa,0xe1,0xe8, + 0x9f,0x96,0x8d,0x84,0xbb,0xb2,0xa9,0xa0, + 0x47,0x4e,0x55,0x5c,0x63,0x6a,0x71,0x78, + 0x0f,0x06,0x1d,0x14,0x2b,0x22,0x39,0x30, + 0x9a,0x93,0x88,0x81,0xbe,0xb7,0xac,0xa5, + 0xd2,0xdb,0xc0,0xc9,0xf6,0xff,0xe4,0xed, + 0x0a,0x03,0x18,0x11,0x2e,0x27,0x3c,0x35, + 0x42,0x4b,0x50,0x59,0x66,0x6f,0x74,0x7d, + 0xa1,0xa8,0xb3,0xba,0x85,0x8c,0x97,0x9e, + 0xe9,0xe0,0xfb,0xf2,0xcd,0xc4,0xdf,0xd6, + 0x31,0x38,0x23,0x2a,0x15,0x1c,0x07,0x0e, + 0x79,0x70,0x6b,0x62,0x5d,0x54,0x4f,0x46 +}; + +static const uint_8t gfmul_b[256] = { + 0x00,0x0b,0x16,0x1d,0x2c,0x27,0x3a,0x31, + 0x58,0x53,0x4e,0x45,0x74,0x7f,0x62,0x69, + 0xb0,0xbb,0xa6,0xad,0x9c,0x97,0x8a,0x81, + 0xe8,0xe3,0xfe,0xf5,0xc4,0xcf,0xd2,0xd9, + 0x7b,0x70,0x6d,0x66,0x57,0x5c,0x41,0x4a, + 0x23,0x28,0x35,0x3e,0x0f,0x04,0x19,0x12, + 0xcb,0xc0,0xdd,0xd6,0xe7,0xec,0xf1,0xfa, + 0x93,0x98,0x85,0x8e,0xbf,0xb4,0xa9,0xa2, + 0xf6,0xfd,0xe0,0xeb,0xda,0xd1,0xcc,0xc7, + 0xae,0xa5,0xb8,0xb3,0x82,0x89,0x94,0x9f, + 0x46,0x4d,0x50,0x5b,0x6a,0x61,0x7c,0x77, + 0x1e,0x15,0x08,0x03,0x32,0x39,0x24,0x2f, + 0x8d,0x86,0x9b,0x90,0xa1,0xaa,0xb7,0xbc, + 0xd5,0xde,0xc3,0xc8,0xf9,0xf2,0xef,0xe4, + 0x3d,0x36,0x2b,0x20,0x11,0x1a,0x07,0x0c, + 0x65,0x6e,0x73,0x78,0x49,0x42,0x5f,0x54, + 0xf7,0xfc,0xe1,0xea,0xdb,0xd0,0xcd,0xc6, + 0xaf,0xa4,0xb9,0xb2,0x83,0x88,0x95,0x9e, + 0x47,0x4c,0x51,0x5a,0x6b,0x60,0x7d,0x76, + 0x1f,0x14,0x09,0x02,0x33,0x38,0x25,0x2e, + 0x8c,0x87,0x9a,0x91,0xa0,0xab,0xb6,0xbd, + 0xd4,0xdf,0xc2,0xc9,0xf8,0xf3,0xee,0xe5, + 0x3c,0x37,0x2a,0x21,0x10,0x1b,0x06,0x0d, + 0x64,0x6f,0x72,0x79,0x48,0x43,0x5e,0x55, + 0x01,0x0a,0x17,0x1c,0x2d,0x26,0x3b,0x30, + 0x59,0x52,0x4f,0x44,0x75,0x7e,0x63,0x68, + 0xb1,0xba,0xa7,0xac,0x9d,0x96,0x8b,0x80, + 0xe9,0xe2,0xff,0xf4,0xc5,0xce,0xd3,0xd8, + 0x7a,0x71,0x6c,0x67,0x56,0x5d,0x40,0x4b, + 0x22,0x29,0x34,0x3f,0x0e,0x05,0x18,0x13, + 0xca,0xc1,0xdc,0xd7,0xe6,0xed,0xf0,0xfb, + 0x92,0x99,0x84,0x8f,0xbe,0xb5,0xa8,0xa3 +}; + +static const uint_8t gfmul_d[256] = { + 0x00,0x0d,0x1a,0x17,0x34,0x39,0x2e,0x23, + 0x68,0x65,0x72,0x7f,0x5c,0x51,0x46,0x4b, + 0xd0,0xdd,0xca,0xc7,0xe4,0xe9,0xfe,0xf3, + 0xb8,0xb5,0xa2,0xaf,0x8c,0x81,0x96,0x9b, + 0xbb,0xb6,0xa1,0xac,0x8f,0x82,0x95,0x98, + 0xd3,0xde,0xc9,0xc4,0xe7,0xea,0xfd,0xf0, + 0x6b,0x66,0x71,0x7c,0x5f,0x52,0x45,0x48, + 0x03,0x0e,0x19,0x14,0x37,0x3a,0x2d,0x20, + 0x6d,0x60,0x77,0x7a,0x59,0x54,0x43,0x4e, + 0x05,0x08,0x1f,0x12,0x31,0x3c,0x2b,0x26, + 0xbd,0xb0,0xa7,0xaa,0x89,0x84,0x93,0x9e, + 0xd5,0xd8,0xcf,0xc2,0xe1,0xec,0xfb,0xf6, + 0xd6,0xdb,0xcc,0xc1,0xe2,0xef,0xf8,0xf5, + 0xbe,0xb3,0xa4,0xa9,0x8a,0x87,0x90,0x9d, + 0x06,0x0b,0x1c,0x11,0x32,0x3f,0x28,0x25, + 0x6e,0x63,0x74,0x79,0x5a,0x57,0x40,0x4d, + 0xda,0xd7,0xc0,0xcd,0xee,0xe3,0xf4,0xf9, + 0xb2,0xbf,0xa8,0xa5,0x86,0x8b,0x9c,0x91, + 0x0a,0x07,0x10,0x1d,0x3e,0x33,0x24,0x29, + 0x62,0x6f,0x78,0x75,0x56,0x5b,0x4c,0x41, + 0x61,0x6c,0x7b,0x76,0x55,0x58,0x4f,0x42, + 0x09,0x04,0x13,0x1e,0x3d,0x30,0x27,0x2a, + 0xb1,0xbc,0xab,0xa6,0x85,0x88,0x9f,0x92, + 0xd9,0xd4,0xc3,0xce,0xed,0xe0,0xf7,0xfa, + 0xb7,0xba,0xad,0xa0,0x83,0x8e,0x99,0x94, + 0xdf,0xd2,0xc5,0xc8,0xeb,0xe6,0xf1,0xfc, + 0x67,0x6a,0x7d,0x70,0x53,0x5e,0x49,0x44, + 0x0f,0x02,0x15,0x18,0x3b,0x36,0x21,0x2c, + 0x0c,0x01,0x16,0x1b,0x38,0x35,0x22,0x2f, + 0x64,0x69,0x7e,0x73,0x50,0x5d,0x4a,0x47, + 0xdc,0xd1,0xc6,0xcb,0xe8,0xe5,0xf2,0xff, + 0xb4,0xb9,0xae,0xa3,0x80,0x8d,0x9a,0x97 +}; + +static const uint_8t gfmul_e[256] = { + 0x00,0x0e,0x1c,0x12,0x38,0x36,0x24,0x2a, + 0x70,0x7e,0x6c,0x62,0x48,0x46,0x54,0x5a, + 0xe0,0xee,0xfc,0xf2,0xd8,0xd6,0xc4,0xca, + 0x90,0x9e,0x8c,0x82,0xa8,0xa6,0xb4,0xba, + 0xdb,0xd5,0xc7,0xc9,0xe3,0xed,0xff,0xf1, + 0xab,0xa5,0xb7,0xb9,0x93,0x9d,0x8f,0x81, + 0x3b,0x35,0x27,0x29,0x03,0x0d,0x1f,0x11, + 0x4b,0x45,0x57,0x59,0x73,0x7d,0x6f,0x61, + 0xad,0xa3,0xb1,0xbf,0x95,0x9b,0x89,0x87, + 0xdd,0xd3,0xc1,0xcf,0xe5,0xeb,0xf9,0xf7, + 0x4d,0x43,0x51,0x5f,0x75,0x7b,0x69,0x67, + 0x3d,0x33,0x21,0x2f,0x05,0x0b,0x19,0x17, + 0x76,0x78,0x6a,0x64,0x4e,0x40,0x52,0x5c, + 0x06,0x08,0x1a,0x14,0x3e,0x30,0x22,0x2c, + 0x96,0x98,0x8a,0x84,0xae,0xa0,0xb2,0xbc, + 0xe6,0xe8,0xfa,0xf4,0xde,0xd0,0xc2,0xcc, + 0x41,0x4f,0x5d,0x53,0x79,0x77,0x65,0x6b, + 0x31,0x3f,0x2d,0x23,0x09,0x07,0x15,0x1b, + 0xa1,0xaf,0xbd,0xb3,0x99,0x97,0x85,0x8b, + 0xd1,0xdf,0xcd,0xc3,0xe9,0xe7,0xf5,0xfb, + 0x9a,0x94,0x86,0x88,0xa2,0xac,0xbe,0xb0, + 0xea,0xe4,0xf6,0xf8,0xd2,0xdc,0xce,0xc0, + 0x7a,0x74,0x66,0x68,0x42,0x4c,0x5e,0x50, + 0x0a,0x04,0x16,0x18,0x32,0x3c,0x2e,0x20, + 0xec,0xe2,0xf0,0xfe,0xd4,0xda,0xc8,0xc6, + 0x9c,0x92,0x80,0x8e,0xa4,0xaa,0xb8,0xb6, + 0x0c,0x02,0x10,0x1e,0x34,0x3a,0x28,0x26, + 0x7c,0x72,0x60,0x6e,0x44,0x4a,0x58,0x56, + 0x37,0x39,0x2b,0x25,0x0f,0x01,0x13,0x1d, + 0x47,0x49,0x5b,0x55,0x7f,0x71,0x63,0x6d, + 0xd7,0xd9,0xcb,0xc5,0xef,0xe1,0xf3,0xfd, + 0xa7,0xa9,0xbb,0xb5,0x9f,0x91,0x83,0x8d +}; + +#if defined( HAVE_UINT_32T ) + typedef unsigned long uint_32t; +#endif + +#if defined( HAVE_MEMCPY ) +# define block_copy(d, s, l) memcpy(d, s, l) +# define block16_copy(d, s) memcpy(d, s, N_BLOCK) +#else +# define block_copy(d, s, l) copy_block(d, s, l) +# define block16_copy(d, s) copy_block16(d, s) +#endif + +/* block size 'nn' must be a multiple of four */ + +static void copy_block16( void *d, const void *s ) +{ +#if defined( HAVE_UINT_32T ) + ((uint_32t*)d)[ 0] = ((uint_32t*)s)[ 0]; + ((uint_32t*)d)[ 1] = ((uint_32t*)s)[ 1]; + ((uint_32t*)d)[ 2] = ((uint_32t*)s)[ 2]; + ((uint_32t*)d)[ 3] = ((uint_32t*)s)[ 3]; +#else + ((uint_8t*)d)[ 0] = ((uint_8t*)s)[ 0]; + ((uint_8t*)d)[ 1] = ((uint_8t*)s)[ 1]; + ((uint_8t*)d)[ 2] = ((uint_8t*)s)[ 2]; + ((uint_8t*)d)[ 3] = ((uint_8t*)s)[ 3]; + ((uint_8t*)d)[ 4] = ((uint_8t*)s)[ 4]; + ((uint_8t*)d)[ 5] = ((uint_8t*)s)[ 5]; + ((uint_8t*)d)[ 6] = ((uint_8t*)s)[ 6]; + ((uint_8t*)d)[ 7] = ((uint_8t*)s)[ 7]; + ((uint_8t*)d)[ 8] = ((uint_8t*)s)[ 8]; + ((uint_8t*)d)[ 9] = ((uint_8t*)s)[ 9]; + ((uint_8t*)d)[10] = ((uint_8t*)s)[10]; + ((uint_8t*)d)[11] = ((uint_8t*)s)[11]; + ((uint_8t*)d)[12] = ((uint_8t*)s)[12]; + ((uint_8t*)d)[13] = ((uint_8t*)s)[13]; + ((uint_8t*)d)[14] = ((uint_8t*)s)[14]; + ((uint_8t*)d)[15] = ((uint_8t*)s)[15]; +#endif +} + +static void copy_block( void * d, void *s, uint_8t nn ) +{ + while( nn-- ) + *((uint_8t*)d)++ = *((uint_8t*)s)++; +} + +static void xor_block( void *d, const void *s ) +{ +#if defined( HAVE_UINT_32T ) + ((uint_32t*)d)[ 0] ^= ((uint_32t*)s)[ 0]; + ((uint_32t*)d)[ 1] ^= ((uint_32t*)s)[ 1]; + ((uint_32t*)d)[ 2] ^= ((uint_32t*)s)[ 2]; + ((uint_32t*)d)[ 3] ^= ((uint_32t*)s)[ 3]; +#else + ((uint_8t*)d)[ 0] ^= ((uint_8t*)s)[ 0]; + ((uint_8t*)d)[ 1] ^= ((uint_8t*)s)[ 1]; + ((uint_8t*)d)[ 2] ^= ((uint_8t*)s)[ 2]; + ((uint_8t*)d)[ 3] ^= ((uint_8t*)s)[ 3]; + ((uint_8t*)d)[ 4] ^= ((uint_8t*)s)[ 4]; + ((uint_8t*)d)[ 5] ^= ((uint_8t*)s)[ 5]; + ((uint_8t*)d)[ 6] ^= ((uint_8t*)s)[ 6]; + ((uint_8t*)d)[ 7] ^= ((uint_8t*)s)[ 7]; + ((uint_8t*)d)[ 8] ^= ((uint_8t*)s)[ 8]; + ((uint_8t*)d)[ 9] ^= ((uint_8t*)s)[ 9]; + ((uint_8t*)d)[10] ^= ((uint_8t*)s)[10]; + ((uint_8t*)d)[11] ^= ((uint_8t*)s)[11]; + ((uint_8t*)d)[12] ^= ((uint_8t*)s)[12]; + ((uint_8t*)d)[13] ^= ((uint_8t*)s)[13]; + ((uint_8t*)d)[14] ^= ((uint_8t*)s)[14]; + ((uint_8t*)d)[15] ^= ((uint_8t*)s)[15]; +#endif +} + +static void copy_and_key( void *d, const void *s, const void *k ) +{ +#if defined( HAVE_UINT_32T ) + ((uint_32t*)d)[ 0] = ((uint_32t*)s)[ 0] ^ ((uint_32t*)k)[ 0]; + ((uint_32t*)d)[ 1] = ((uint_32t*)s)[ 1] ^ ((uint_32t*)k)[ 1]; + ((uint_32t*)d)[ 2] = ((uint_32t*)s)[ 2] ^ ((uint_32t*)k)[ 2]; + ((uint_32t*)d)[ 3] = ((uint_32t*)s)[ 3] ^ ((uint_32t*)k)[ 3]; +#elif 1 + ((uint_8t*)d)[ 0] = ((uint_8t*)s)[ 0] ^ ((uint_8t*)k)[ 0]; + ((uint_8t*)d)[ 1] = ((uint_8t*)s)[ 1] ^ ((uint_8t*)k)[ 1]; + ((uint_8t*)d)[ 2] = ((uint_8t*)s)[ 2] ^ ((uint_8t*)k)[ 2]; + ((uint_8t*)d)[ 3] = ((uint_8t*)s)[ 3] ^ ((uint_8t*)k)[ 3]; + ((uint_8t*)d)[ 4] = ((uint_8t*)s)[ 4] ^ ((uint_8t*)k)[ 4]; + ((uint_8t*)d)[ 5] = ((uint_8t*)s)[ 5] ^ ((uint_8t*)k)[ 5]; + ((uint_8t*)d)[ 6] = ((uint_8t*)s)[ 6] ^ ((uint_8t*)k)[ 6]; + ((uint_8t*)d)[ 7] = ((uint_8t*)s)[ 7] ^ ((uint_8t*)k)[ 7]; + ((uint_8t*)d)[ 8] = ((uint_8t*)s)[ 8] ^ ((uint_8t*)k)[ 8]; + ((uint_8t*)d)[ 9] = ((uint_8t*)s)[ 9] ^ ((uint_8t*)k)[ 9]; + ((uint_8t*)d)[10] = ((uint_8t*)s)[10] ^ ((uint_8t*)k)[10]; + ((uint_8t*)d)[11] = ((uint_8t*)s)[11] ^ ((uint_8t*)k)[11]; + ((uint_8t*)d)[12] = ((uint_8t*)s)[12] ^ ((uint_8t*)k)[12]; + ((uint_8t*)d)[13] = ((uint_8t*)s)[13] ^ ((uint_8t*)k)[13]; + ((uint_8t*)d)[14] = ((uint_8t*)s)[14] ^ ((uint_8t*)k)[14]; + ((uint_8t*)d)[15] = ((uint_8t*)s)[15] ^ ((uint_8t*)k)[15]; +#else + block16_copy(d, s); + xor_block(d, k); +#endif +} + +static void add_round_key( uint_8t d[N_BLOCK], const uint_8t k[N_BLOCK] ) +{ + xor_block(d, k); +} + +static void shift_sub_rows( uint_8t st[N_BLOCK] ) +{ uint_8t tt; + + st[ 0] = s_box[st[ 0]]; st[ 4] = s_box[st[ 4]]; + st[ 8] = s_box[st[ 8]]; st[12] = s_box[st[12]]; + + tt = st[1]; st[ 1] = s_box[st[ 5]]; st[ 5] = s_box[st[ 9]]; + st[ 9] = s_box[st[13]]; st[13] = s_box[ tt ]; + + tt = st[2]; st[ 2] = s_box[st[10]]; st[10] = s_box[ tt ]; + tt = st[6]; st[ 6] = s_box[st[14]]; st[14] = s_box[ tt ]; + + tt = st[15]; st[15] = s_box[st[11]]; st[11] = s_box[st[ 7]]; + st[ 7] = s_box[st[ 3]]; st[ 3] = s_box[ tt ]; +} + +static void inv_shift_sub_rows( uint_8t st[N_BLOCK] ) +{ uint_8t tt; + + st[ 0] = inv_s_box[st[ 0]]; st[ 4] = inv_s_box[st[ 4]]; + st[ 8] = inv_s_box[st[ 8]]; st[12] = inv_s_box[st[12]]; + + tt = st[13]; st[13] = inv_s_box[st[9]]; st[ 9] = inv_s_box[st[5]]; + st[ 5] = inv_s_box[st[1]]; st[ 1] = inv_s_box[ tt ]; + + tt = st[2]; st[ 2] = inv_s_box[st[10]]; st[10] = inv_s_box[ tt ]; + tt = st[6]; st[ 6] = inv_s_box[st[14]]; st[14] = inv_s_box[ tt ]; + + tt = st[3]; st[ 3] = inv_s_box[st[ 7]]; st[ 7] = inv_s_box[st[11]]; + st[11] = inv_s_box[st[15]]; st[15] = inv_s_box[ tt ]; +} + +#if defined( VERSION_1 ) + static void mix_sub_columns( uint_8t dt[N_BLOCK] ) + { uint_8t st[N_BLOCK]; + block16_copy(st, dt); +#else + static void mix_sub_columns( uint_8t dt[N_BLOCK], uint_8t st[N_BLOCK] ) + { +#endif + dt[ 0] = gfm2_s_box[st[0]] ^ gfm3_s_box[st[5]] ^ s_box[st[10]] ^ s_box[st[15]]; + dt[ 1] = s_box[st[0]] ^ gfm2_s_box[st[5]] ^ gfm3_s_box[st[10]] ^ s_box[st[15]]; + dt[ 2] = s_box[st[0]] ^ s_box[st[5]] ^ gfm2_s_box[st[10]] ^ gfm3_s_box[st[15]]; + dt[ 3] = gfm3_s_box[st[0]] ^ s_box[st[5]] ^ s_box[st[10]] ^ gfm2_s_box[st[15]]; + + dt[ 4] = gfm2_s_box[st[4]] ^ gfm3_s_box[st[9]] ^ s_box[st[14]] ^ s_box[st[3]]; + dt[ 5] = s_box[st[4]] ^ gfm2_s_box[st[9]] ^ gfm3_s_box[st[14]] ^ s_box[st[3]]; + dt[ 6] = s_box[st[4]] ^ s_box[st[9]] ^ gfm2_s_box[st[14]] ^ gfm3_s_box[st[3]]; + dt[ 7] = gfm3_s_box[st[4]] ^ s_box[st[9]] ^ s_box[st[14]] ^ gfm2_s_box[st[3]]; + + dt[ 8] = gfm2_s_box[st[8]] ^ gfm3_s_box[st[13]] ^ s_box[st[2]] ^ s_box[st[7]]; + dt[ 9] = s_box[st[8]] ^ gfm2_s_box[st[13]] ^ gfm3_s_box[st[2]] ^ s_box[st[7]]; + dt[10] = s_box[st[8]] ^ s_box[st[13]] ^ gfm2_s_box[st[2]] ^ gfm3_s_box[st[7]]; + dt[11] = gfm3_s_box[st[8]] ^ s_box[st[13]] ^ s_box[st[2]] ^ gfm2_s_box[st[7]]; + + dt[12] = gfm2_s_box[st[12]] ^ gfm3_s_box[st[1]] ^ s_box[st[6]] ^ s_box[st[11]]; + dt[13] = s_box[st[12]] ^ gfm2_s_box[st[1]] ^ gfm3_s_box[st[6]] ^ s_box[st[11]]; + dt[14] = s_box[st[12]] ^ s_box[st[1]] ^ gfm2_s_box[st[6]] ^ gfm3_s_box[st[11]]; + dt[15] = gfm3_s_box[st[12]] ^ s_box[st[1]] ^ s_box[st[6]] ^ gfm2_s_box[st[11]]; + } + +#if defined( VERSION_1 ) + static void inv_mix_sub_columns( uint_8t dt[N_BLOCK] ) + { uint_8t st[N_BLOCK]; + block16_copy(st, dt); +#else + static void inv_mix_sub_columns( uint_8t dt[N_BLOCK], uint_8t st[N_BLOCK] ) + { +#endif + dt[ 0] = inv_s_box[gfmul_e[st[ 0]] ^ gfmul_b[st[ 1]] ^ gfmul_d[st[ 2]] ^ gfmul_9[st[ 3]]]; + dt[ 5] = inv_s_box[gfmul_9[st[ 0]] ^ gfmul_e[st[ 1]] ^ gfmul_b[st[ 2]] ^ gfmul_d[st[ 3]]]; + dt[10] = inv_s_box[gfmul_d[st[ 0]] ^ gfmul_9[st[ 1]] ^ gfmul_e[st[ 2]] ^ gfmul_b[st[ 3]]]; + dt[15] = inv_s_box[gfmul_b[st[ 0]] ^ gfmul_d[st[ 1]] ^ gfmul_9[st[ 2]] ^ gfmul_e[st[ 3]]]; + + dt[ 4] = inv_s_box[gfmul_e[st[ 4]] ^ gfmul_b[st[ 5]] ^ gfmul_d[st[ 6]] ^ gfmul_9[st[ 7]]]; + dt[ 9] = inv_s_box[gfmul_9[st[ 4]] ^ gfmul_e[st[ 5]] ^ gfmul_b[st[ 6]] ^ gfmul_d[st[ 7]]]; + dt[14] = inv_s_box[gfmul_d[st[ 4]] ^ gfmul_9[st[ 5]] ^ gfmul_e[st[ 6]] ^ gfmul_b[st[ 7]]]; + dt[ 3] = inv_s_box[gfmul_b[st[ 4]] ^ gfmul_d[st[ 5]] ^ gfmul_9[st[ 6]] ^ gfmul_e[st[ 7]]]; + + dt[ 8] = inv_s_box[gfmul_e[st[ 8]] ^ gfmul_b[st[ 9]] ^ gfmul_d[st[10]] ^ gfmul_9[st[11]]]; + dt[13] = inv_s_box[gfmul_9[st[ 8]] ^ gfmul_e[st[ 9]] ^ gfmul_b[st[10]] ^ gfmul_d[st[11]]]; + dt[ 2] = inv_s_box[gfmul_d[st[ 8]] ^ gfmul_9[st[ 9]] ^ gfmul_e[st[10]] ^ gfmul_b[st[11]]]; + dt[ 7] = inv_s_box[gfmul_b[st[ 8]] ^ gfmul_d[st[ 9]] ^ gfmul_9[st[10]] ^ gfmul_e[st[11]]]; + + dt[12] = inv_s_box[gfmul_e[st[12]] ^ gfmul_b[st[13]] ^ gfmul_d[st[14]] ^ gfmul_9[st[15]]]; + dt[ 1] = inv_s_box[gfmul_9[st[12]] ^ gfmul_e[st[13]] ^ gfmul_b[st[14]] ^ gfmul_d[st[15]]]; + dt[ 6] = inv_s_box[gfmul_d[st[12]] ^ gfmul_9[st[13]] ^ gfmul_e[st[14]] ^ gfmul_b[st[15]]]; + dt[11] = inv_s_box[gfmul_b[st[12]] ^ gfmul_d[st[13]] ^ gfmul_9[st[14]] ^ gfmul_e[st[15]]]; + } + +#if defined( AES_ENC_PREKEYED ) || defined( AES_DEC_PREKEYED ) + +/* Set the cipher key for the pre-keyed version */ + +return_type aes_set_key( const unsigned char key[], length_type keylen, aes_context ctx[1] ) +{ + uint_8t cc, rc, hi; + + switch( keylen ) + { + case 16: + case 128: + keylen = 16; + break; + case 24: + case 192: + keylen = 24; + break; + case 32: + case 256: + keylen = 32; + break; + default: + ctx->rnd = 0; + return (return_type) -1; + } + block_copy(ctx->ksch, key, keylen); + hi = (keylen + 28) << 2; + ctx->rnd = (hi >> 4) - 1; + for( cc = keylen, rc = 1; cc < hi; cc += 4 ) + { uint_8t tt, t0, t1, t2, t3; + + t0 = ctx->ksch[cc - 4]; + t1 = ctx->ksch[cc - 3]; + t2 = ctx->ksch[cc - 2]; + t3 = ctx->ksch[cc - 1]; + if( cc % keylen == 0 ) + { + tt = t0; + t0 = s_box[t1] ^ rc; + t1 = s_box[t2]; + t2 = s_box[t3]; + t3 = s_box[tt]; + rc = f2(rc); + } + else if( keylen > 24 && cc % keylen == 16 ) + { + t0 = s_box[t0]; + t1 = s_box[t1]; + t2 = s_box[t2]; + t3 = s_box[t3]; + } + tt = cc - keylen; + ctx->ksch[cc + 0] = ctx->ksch[tt + 0] ^ t0; + ctx->ksch[cc + 1] = ctx->ksch[tt + 1] ^ t1; + ctx->ksch[cc + 2] = ctx->ksch[tt + 2] ^ t2; + ctx->ksch[cc + 3] = ctx->ksch[tt + 3] ^ t3; + } + return 0; +} + +#endif + +#if defined( AES_ENC_PREKEYED ) + +/* Encrypt a single block of 16 bytes */ + +return_type aes_encrypt( const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], const aes_context ctx[1] ) +{ + if( ctx->rnd ) + { + uint_8t s1[N_BLOCK], r; + copy_and_key( s1, in, ctx->ksch ); + + for( r = 1 ; r < ctx->rnd ; ++r ) +#if defined( VERSION_1 ) + { + mix_sub_columns( s1 ); + add_round_key( s1, ctx->ksch + r * N_BLOCK); + } +#else + { uint_8t s2[N_BLOCK]; + mix_sub_columns( s2, s1 ); + copy_and_key( s1, s2, ctx->ksch + r * N_BLOCK); + } +#endif + shift_sub_rows( s1 ); + copy_and_key( out, s1, ctx->ksch + r * N_BLOCK ); + } + else + return (return_type) -1; + return 0; +} + +#endif + +#if defined( AES_DEC_PREKEYED ) + +/* Decrypt a single block of 16 bytes */ + +return_type aes_decrypt( const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], const aes_context ctx[1] ) +{ + if( ctx->rnd ) + { + uint_8t s1[N_BLOCK], r; + copy_and_key( s1, in, ctx->ksch + ctx->rnd * N_BLOCK ); + inv_shift_sub_rows( s1 ); + + for( r = ctx->rnd ; --r ; ) +#if defined( VERSION_1 ) + { + add_round_key( s1, ctx->ksch + r * N_BLOCK ); + inv_mix_sub_columns( s1 ); + } +#else + { uint_8t s2[N_BLOCK]; + copy_and_key( s2, s1, ctx->ksch + r * N_BLOCK ); + inv_mix_sub_columns( s1, s2 ); + } +#endif + copy_and_key( out, s1, ctx->ksch ); + } + else + return (return_type) -1; + return 0; +} + +#endif + +#if defined( AES_ENC_128_OTFK ) + +/* The 'on the fly' encryption key update for for 128 bit keys */ + +static void update_encrypt_key_128( uint_8t k[N_BLOCK], uint_8t *rc ) +{ uint_8t cc; + + k[0] ^= s_box[k[13]] ^ *rc; + k[1] ^= s_box[k[14]]; + k[2] ^= s_box[k[15]]; + k[3] ^= s_box[k[12]]; + *rc = f2( *rc ); + + for(cc = 4; cc < 16; cc += 4 ) + { + k[cc + 0] ^= k[cc - 4]; + k[cc + 1] ^= k[cc - 3]; + k[cc + 2] ^= k[cc - 2]; + k[cc + 3] ^= k[cc - 1]; + } +} + +/* Encrypt a single block of 16 bytes with 'on the fly' 128 bit keying */ + +void aes_encrypt_128( const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const unsigned char key[N_BLOCK], unsigned char o_key[N_BLOCK] ) +{ uint_8t s1[N_BLOCK], r, rc = 1; + + if(o_key != key) + block16_copy( o_key, key ); + copy_and_key( s1, in, o_key ); + + for( r = 1 ; r < 10 ; ++r ) +#if defined( VERSION_1 ) + { + mix_sub_columns( s1 ); + update_encrypt_key_128( o_key, &rc ); + add_round_key( s1, o_key ); + } +#else + { uint_8t s2[N_BLOCK]; + mix_sub_columns( s2, s1 ); + update_encrypt_key_128( o_key, &rc ); + copy_and_key( s1, s2, o_key ); + } +#endif + + shift_sub_rows( s1 ); + update_encrypt_key_128( o_key, &rc ); + copy_and_key( out, s1, o_key ); +} + +#endif + +#if defined( AES_DEC_128_OTFK ) + +/* The 'on the fly' decryption key update for for 128 bit keys */ + +static void update_decrypt_key_128( uint_8t k[N_BLOCK], uint_8t *rc ) +{ uint_8t cc; + + for( cc = 12; cc > 0; cc -= 4 ) + { + k[cc + 0] ^= k[cc - 4]; + k[cc + 1] ^= k[cc - 3]; + k[cc + 2] ^= k[cc - 2]; + k[cc + 3] ^= k[cc - 1]; + } + *rc = d2(*rc); + k[0] ^= s_box[k[13]] ^ *rc; + k[1] ^= s_box[k[14]]; + k[2] ^= s_box[k[15]]; + k[3] ^= s_box[k[12]]; +} + +/* Decrypt a single block of 16 bytes with 'on the fly' 128 bit keying */ + +void aes_decrypt_128( const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const unsigned char key[N_BLOCK], unsigned char o_key[N_BLOCK] ) +{ + uint_8t s1[N_BLOCK], r, rc = 0x6c; + if(o_key != key) + block16_copy( o_key, key ); + + copy_and_key( s1, in, o_key ); + inv_shift_sub_rows( s1 ); + + for( r = 10 ; --r ; ) +#if defined( VERSION_1 ) + { + update_decrypt_key_128( o_key, &rc ); + add_round_key( s1, o_key ); + inv_mix_sub_columns( s1 ); + } +#else + { uint_8t s2[N_BLOCK]; + update_decrypt_key_128( o_key, &rc ); + copy_and_key( s2, s1, o_key ); + inv_mix_sub_columns( s1, s2 ); + } +#endif + update_decrypt_key_128( o_key, &rc ); + copy_and_key( out, s1, o_key ); +} + +#endif + +#if defined( AES_ENC_256_OTFK ) + +/* The 'on the fly' encryption key update for for 256 bit keys */ + +static void update_encrypt_key_256( uint_8t k[2 * N_BLOCK], uint_8t *rc ) +{ uint_8t cc; + + k[0] ^= s_box[k[29]] ^ *rc; + k[1] ^= s_box[k[30]]; + k[2] ^= s_box[k[31]]; + k[3] ^= s_box[k[28]]; + *rc = f2( *rc ); + + for(cc = 4; cc < 16; cc += 4) + { + k[cc + 0] ^= k[cc - 4]; + k[cc + 1] ^= k[cc - 3]; + k[cc + 2] ^= k[cc - 2]; + k[cc + 3] ^= k[cc - 1]; + } + + k[16] ^= s_box[k[12]]; + k[17] ^= s_box[k[13]]; + k[18] ^= s_box[k[14]]; + k[19] ^= s_box[k[15]]; + + for( cc = 20; cc < 32; cc += 4 ) + { + k[cc + 0] ^= k[cc - 4]; + k[cc + 1] ^= k[cc - 3]; + k[cc + 2] ^= k[cc - 2]; + k[cc + 3] ^= k[cc - 1]; + } +} + +/* Encrypt a single block of 16 bytes with 'on the fly' 256 bit keying */ + +void aes_encrypt_256( const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const unsigned char key[2 * N_BLOCK], unsigned char o_key[2 * N_BLOCK] ) +{ + uint_8t s1[N_BLOCK], r, rc = 1; + if(o_key != key) + { + block16_copy( o_key, key ); + block16_copy( o_key + 16, key + 16 ); + } + copy_and_key( s1, in, o_key ); + + for( r = 1 ; r < 14 ; ++r ) +#if defined( VERSION_1 ) + { + mix_sub_columns(s1); + if( r & 1 ) + add_round_key( s1, o_key + 16 ); + else + { + update_encrypt_key_256( o_key, &rc ); + add_round_key( s1, o_key ); + } + } +#else + { uint_8t s2[N_BLOCK]; + mix_sub_columns( s2, s1 ); + if( r & 1 ) + copy_and_key( s1, s2, o_key + 16 ); + else + { + update_encrypt_key_256( o_key, &rc ); + copy_and_key( s1, s2, o_key ); + } + } +#endif + + shift_sub_rows( s1 ); + update_encrypt_key_256( o_key, &rc ); + copy_and_key( out, s1, o_key ); +} + +#endif + +#if defined( AES_DEC_256_OTFK ) + +/* The 'on the fly' encryption key update for for 256 bit keys */ + +static void update_decrypt_key_256( uint_8t k[2 * N_BLOCK], uint_8t *rc ) +{ uint_8t cc; + + for(cc = 28; cc > 16; cc -= 4) + { + k[cc + 0] ^= k[cc - 4]; + k[cc + 1] ^= k[cc - 3]; + k[cc + 2] ^= k[cc - 2]; + k[cc + 3] ^= k[cc - 1]; + } + + k[16] ^= s_box[k[12]]; + k[17] ^= s_box[k[13]]; + k[18] ^= s_box[k[14]]; + k[19] ^= s_box[k[15]]; + + for(cc = 12; cc > 0; cc -= 4) + { + k[cc + 0] ^= k[cc - 4]; + k[cc + 1] ^= k[cc - 3]; + k[cc + 2] ^= k[cc - 2]; + k[cc + 3] ^= k[cc - 1]; + } + + *rc = d2(*rc); + k[0] ^= s_box[k[29]] ^ *rc; + k[1] ^= s_box[k[30]]; + k[2] ^= s_box[k[31]]; + k[3] ^= s_box[k[28]]; +} + +/* Decrypt a single block of 16 bytes with 'on the fly' + 256 bit keying +*/ +void aes_decrypt_256( const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const unsigned char key[2 * N_BLOCK], unsigned char o_key[2 * N_BLOCK] ) +{ + uint_8t s1[N_BLOCK], r, rc = 0x80; + + if(o_key != key) + { + block16_copy( o_key, key ); + block16_copy( o_key + 16, key + 16 ); + } + + copy_and_key( s1, in, o_key ); + inv_shift_sub_rows( s1 ); + + for( r = 14 ; --r ; ) +#if defined( VERSION_1 ) + { + if( ( r & 1 ) ) + { + update_decrypt_key_256( o_key, &rc ); + add_round_key( s1, o_key + 16 ); + } + else + add_round_key( s1, o_key ); + inv_mix_sub_columns( s1 ); + } +#else + { uint_8t s2[N_BLOCK]; + if( ( r & 1 ) ) + { + update_decrypt_key_256( o_key, &rc ); + copy_and_key( s2, s1, o_key + 16 ); + } + else + copy_and_key( s2, s1, o_key ); + inv_mix_sub_columns( s1, s2 ); + } +#endif + copy_and_key( out, s1, o_key ); +} + +#endif diff --git a/src/Crypto/AesSmall.h b/src/Crypto/AesSmall.h index 516c6964..ebeb24ef 100644 --- a/src/Crypto/AesSmall.h +++ b/src/Crypto/AesSmall.h @@ -1,169 +1,169 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 1998-2006, Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software in both source and binary - form is allowed (with or without changes) provided that: - - 1. distributions of this source code include the above copyright - notice, this list of conditions and the following disclaimer; - - 2. distributions in binary form include the above copyright - notice, this list of conditions and the following disclaimer - in the documentation and/or other associated materials; - - 3. the copyright holder's name is not used to endorse products - built using this software without specific written permission. - - ALTERNATIVELY, provided that this notice is retained in full, this product - may be distributed under the terms of the GNU General Public License (GPL), - in which case the provisions of the GPL apply INSTEAD OF those given above. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue 09/09/2006 - - This is an AES implementation that uses only 8-bit byte operations on the - cipher state. - */ - -#ifndef AES_H -#define AES_H - -#if defined(__cplusplus) -extern "C" -{ -#endif - -/* This provides speed optimisation opportunities if 32-bit word - operations are available -*/ -#if 1 -# define HAVE_UINT_32T -#endif - -#if 1 -# define AES_ENC_PREKEYED /* AES encryption with a precomputed key schedule */ -#endif -#if 1 -# define AES_DEC_PREKEYED /* AES decryption with a precomputed key schedule */ -#endif -#if 0 -# define AES_ENC_128_OTFK /* AES encryption with 'on the fly' 128 bit keying */ -#endif -#if 0 -# define AES_DEC_128_OTFK /* AES decryption with 'on the fly' 128 bit keying */ -#endif -#if 0 -# define AES_ENC_256_OTFK /* AES encryption with 'on the fly' 256 bit keying */ -#endif -#if 0 -# define AES_DEC_256_OTFK /* AES decryption with 'on the fly' 256 bit keying */ -#endif - -#define N_ROW 4 -#define N_COL 4 -#define N_BLOCK (N_ROW * N_COL) -#define N_MAX_ROUNDS 14 - -typedef unsigned char uint_8t; - -typedef uint_8t return_type; -typedef uint_8t length_type; -typedef uint_8t uint_type; - -typedef unsigned char uint_8t; - -typedef struct -{ uint_8t ksch[(N_MAX_ROUNDS + 1) * N_BLOCK]; - uint_8t rnd; -} aes_context; - -/* The following calls are for a precomputed key schedule - - NOTE: If the length_type used for the key length is an - unsigned 8-bit character, a key length of 256 bits must - be entered as a length in bytes (valid inputs are hence - 128, 192, 16, 24 and 32). -*/ - -#if defined( AES_ENC_PREKEYED ) || defined( AES_DEC_PREKEYED ) - -return_type aes_set_key( const unsigned char key[], - length_type keylen, - aes_context ctx[1] ); -#endif - -#if defined( AES_ENC_PREKEYED ) - -return_type aes_encrypt( const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const aes_context ctx[1] ); -#endif - -#if defined( AES_DEC_PREKEYED ) - -return_type aes_decrypt( const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const aes_context ctx[1] ); -#endif - -/* The following calls are for 'on the fly' keying. In this case the - encryption and decryption keys are different. - - The encryption subroutines take a key in an array of bytes in - key[L] where L is 16, 24 or 32 bytes for key lengths of 128, - 192, and 256 bits respectively. They then encrypts the input - data, in[] with this key and put the reult in the output array - out[]. In addition, the second key array, o_key[L], is used - to output the key that is needed by the decryption subroutine - to reverse the encryption operation. The two key arrays can - be the same array but in this case the original key will be - overwritten. - - In the same way, the decryption subroutines output keys that - can be used to reverse their effect when used for encryption. - - Only 128 and 256 bit keys are supported in these 'on the fly' - modes. -*/ - -#if defined( AES_ENC_128_OTFK ) -void aes_encrypt_128( const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[N_BLOCK], - uint_8t o_key[N_BLOCK] ); -#endif - -#if defined( AES_DEC_128_OTFK ) -void aes_decrypt_128( const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[N_BLOCK], - unsigned char o_key[N_BLOCK] ); -#endif - -#if defined( AES_ENC_256_OTFK ) -void aes_encrypt_256( const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[2 * N_BLOCK], - unsigned char o_key[2 * N_BLOCK] ); -#endif - -#if defined( AES_DEC_256_OTFK ) -void aes_decrypt_256( const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[2 * N_BLOCK], - unsigned char o_key[2 * N_BLOCK] ); -#endif - -#if defined(__cplusplus) -} -#endif - -#endif +/* + --------------------------------------------------------------------------- + Copyright (c) 1998-2006, Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software in both source and binary + form is allowed (with or without changes) provided that: + + 1. distributions of this source code include the above copyright + notice, this list of conditions and the following disclaimer; + + 2. distributions in binary form include the above copyright + notice, this list of conditions and the following disclaimer + in the documentation and/or other associated materials; + + 3. the copyright holder's name is not used to endorse products + built using this software without specific written permission. + + ALTERNATIVELY, provided that this notice is retained in full, this product + may be distributed under the terms of the GNU General Public License (GPL), + in which case the provisions of the GPL apply INSTEAD OF those given above. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + Issue 09/09/2006 + + This is an AES implementation that uses only 8-bit byte operations on the + cipher state. + */ + +#ifndef AES_H +#define AES_H + +#if defined(__cplusplus) +extern "C" +{ +#endif + +/* This provides speed optimisation opportunities if 32-bit word + operations are available +*/ +#if 1 +# define HAVE_UINT_32T +#endif + +#if 1 +# define AES_ENC_PREKEYED /* AES encryption with a precomputed key schedule */ +#endif +#if 1 +# define AES_DEC_PREKEYED /* AES decryption with a precomputed key schedule */ +#endif +#if 0 +# define AES_ENC_128_OTFK /* AES encryption with 'on the fly' 128 bit keying */ +#endif +#if 0 +# define AES_DEC_128_OTFK /* AES decryption with 'on the fly' 128 bit keying */ +#endif +#if 0 +# define AES_ENC_256_OTFK /* AES encryption with 'on the fly' 256 bit keying */ +#endif +#if 0 +# define AES_DEC_256_OTFK /* AES decryption with 'on the fly' 256 bit keying */ +#endif + +#define N_ROW 4 +#define N_COL 4 +#define N_BLOCK (N_ROW * N_COL) +#define N_MAX_ROUNDS 14 + +typedef unsigned char uint_8t; + +typedef uint_8t return_type; +typedef uint_8t length_type; +typedef uint_8t uint_type; + +typedef unsigned char uint_8t; + +typedef struct +{ uint_8t ksch[(N_MAX_ROUNDS + 1) * N_BLOCK]; + uint_8t rnd; +} aes_context; + +/* The following calls are for a precomputed key schedule + + NOTE: If the length_type used for the key length is an + unsigned 8-bit character, a key length of 256 bits must + be entered as a length in bytes (valid inputs are hence + 128, 192, 16, 24 and 32). +*/ + +#if defined( AES_ENC_PREKEYED ) || defined( AES_DEC_PREKEYED ) + +return_type aes_set_key( const unsigned char key[], + length_type keylen, + aes_context ctx[1] ); +#endif + +#if defined( AES_ENC_PREKEYED ) + +return_type aes_encrypt( const unsigned char in[N_BLOCK], + unsigned char out[N_BLOCK], + const aes_context ctx[1] ); +#endif + +#if defined( AES_DEC_PREKEYED ) + +return_type aes_decrypt( const unsigned char in[N_BLOCK], + unsigned char out[N_BLOCK], + const aes_context ctx[1] ); +#endif + +/* The following calls are for 'on the fly' keying. In this case the + encryption and decryption keys are different. + + The encryption subroutines take a key in an array of bytes in + key[L] where L is 16, 24 or 32 bytes for key lengths of 128, + 192, and 256 bits respectively. They then encrypts the input + data, in[] with this key and put the reult in the output array + out[]. In addition, the second key array, o_key[L], is used + to output the key that is needed by the decryption subroutine + to reverse the encryption operation. The two key arrays can + be the same array but in this case the original key will be + overwritten. + + In the same way, the decryption subroutines output keys that + can be used to reverse their effect when used for encryption. + + Only 128 and 256 bit keys are supported in these 'on the fly' + modes. +*/ + +#if defined( AES_ENC_128_OTFK ) +void aes_encrypt_128( const unsigned char in[N_BLOCK], + unsigned char out[N_BLOCK], + const unsigned char key[N_BLOCK], + uint_8t o_key[N_BLOCK] ); +#endif + +#if defined( AES_DEC_128_OTFK ) +void aes_decrypt_128( const unsigned char in[N_BLOCK], + unsigned char out[N_BLOCK], + const unsigned char key[N_BLOCK], + unsigned char o_key[N_BLOCK] ); +#endif + +#if defined( AES_ENC_256_OTFK ) +void aes_encrypt_256( const unsigned char in[N_BLOCK], + unsigned char out[N_BLOCK], + const unsigned char key[2 * N_BLOCK], + unsigned char o_key[2 * N_BLOCK] ); +#endif + +#if defined( AES_DEC_256_OTFK ) +void aes_decrypt_256( const unsigned char in[N_BLOCK], + unsigned char out[N_BLOCK], + const unsigned char key[2 * N_BLOCK], + unsigned char o_key[2 * N_BLOCK] ); +#endif + +#if defined(__cplusplus) +} +#endif + +#endif diff --git a/src/Crypto/AesSmall_x86.asm b/src/Crypto/AesSmall_x86.asm index fe7dc47b..de32fc66 100644 --- a/src/Crypto/AesSmall_x86.asm +++ b/src/Crypto/AesSmall_x86.asm @@ -1,1444 +1,1444 @@ - -; --------------------------------------------------------------------------- -; Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. -; -; LICENSE TERMS -; -; The free distribution and use of this software is allowed (with or without -; changes) provided that: -; -; 1. source code distributions include the above copyright notice, this -; list of conditions and the following disclaimer; -; -; 2. binary distributions include the above copyright notice, this list -; of conditions and the following disclaimer in their documentation; -; -; 3. the name of the copyright holder is not used to endorse products -; built using this software without specific written permission. -; -; DISCLAIMER -; -; This software is provided 'as is' with no explicit or implied warranties -; in respect of its properties, including, but not limited to, correctness -; and/or fitness for purpose. -; --------------------------------------------------------------------------- -; Issue 20/12/2007 -; -; This code requires either ASM_X86_V2 or ASM_X86_V2C to be set in aesopt.h -; and the same define to be set here as well. If AES_V2C is set this file -; requires the C files aeskey.c and aestab.c for support. - -; An AES implementation for x86 processors using the YASM (or NASM) assembler. -; This is a full assembler implementation covering encryption, decryption and -; key scheduling. It uses 2k bytes of tables but its encryption and decryption -; performance is very close to that obtained using large tables. Key schedule -; expansion is slower for both encryption and decryption but this is likely to -; be offset by the much smaller load that this version places on the processor -; cache. I acknowledge the contribution made by Daniel Bernstein to aspects of -; the design of the AES round function used here. -; -; This code provides the standard AES block size (128 bits, 16 bytes) and the -; three standard AES key sizes (128, 192 and 256 bits). It has the same call -; interface as my C implementation. The ebx, esi, edi and ebp registers are -; preserved across calls but eax, ecx and edx and the artihmetic status flags -; are not. Although this is a full assembler implementation, it can be used -; in conjunction with my C code which provides faster key scheduling using -; large tables. In this case aeskey.c should be compiled with ASM_X86_V2C -; defined. It is also important that the defines below match those used in the -; C code. This code uses the VC++ register saving conentions; if it is used -; with another compiler, conventions for using and saving registers may need -; to be checked (and calling conventions). The YASM command line for the VC++ -; custom build step is: -; -; yasm -Xvc -f win32 -D -o "$(TargetDir)\$(InputName).obj" "$(InputPath)" -; -; For the cryptlib build this is (pcg): -; -; yasm -Xvc -f win32 -D ASM_X86_V2C -o aescrypt2.obj aes_x86_v2.asm -; -; where is ASM_X86_V2 or ASM_X86_V2C. The calling intefaces are: -; -; AES_RETURN aes_encrypt(const unsigned char in_blk[], -; unsigned char out_blk[], const aes_encrypt_ctx cx[1]); -; -; AES_RETURN aes_decrypt(const unsigned char in_blk[], -; unsigned char out_blk[], const aes_decrypt_ctx cx[1]); -; -; AES_RETURN aes_encrypt_key(const unsigned char key[], -; const aes_encrypt_ctx cx[1]); -; -; AES_RETURN aes_decrypt_key(const unsigned char key[], -; const aes_decrypt_ctx cx[1]); -; -; AES_RETURN aes_encrypt_key(const unsigned char key[], -; unsigned int len, const aes_decrypt_ctx cx[1]); -; -; AES_RETURN aes_decrypt_key(const unsigned char key[], -; unsigned int len, const aes_decrypt_ctx cx[1]); -; -; where is 128, 102 or 256. In the last two calls the length can be in -; either bits or bytes. - -; The DLL interface must use the _stdcall convention in which the number -; of bytes of parameter space is added after an @ to the sutine's name. -; We must also remove our parameters from the stack before return (see -; the do_exit macro). Define DLL_EXPORT for the Dynamic Link Library version. - -; -; Adapted for TrueCrypt: -; - All tables generated at run-time -; - Adapted for 16-bit environment -; - -CPU 386 -USE16 -SEGMENT _TEXT PUBLIC CLASS=CODE USE16 -SEGMENT _DATA PUBLIC CLASS=DATA USE16 - -GROUP DGROUP _TEXT _DATA - -extern _aes_dec_tab ; Aestab.c -extern _aes_enc_tab - -; %define DLL_EXPORT - -; The size of the code can be reduced by using functions for the encryption -; and decryption rounds in place of macro expansion - -%define REDUCE_CODE_SIZE - -; Comment in/out the following lines to obtain the desired subroutines. These -; selections MUST match those in the C header file aes.h - -; %define AES_128 ; define if AES with 128 bit keys is needed -; %define AES_192 ; define if AES with 192 bit keys is needed -%define AES_256 ; define if AES with 256 bit keys is needed -; %define AES_VAR ; define if a variable key size is needed -%define ENCRYPTION ; define if encryption is needed -%define DECRYPTION ; define if decryption is needed -; %define AES_REV_DKS ; define if key decryption schedule is reversed - -%ifndef ASM_X86_V2C -%define ENCRYPTION_KEY_SCHEDULE ; define if encryption key expansion is needed -%define DECRYPTION_KEY_SCHEDULE ; define if decryption key expansion is needed -%endif - -; The encryption key schedule has the following in memory layout where N is the -; number of rounds (10, 12 or 14): -; -; lo: | input key (round 0) | ; each round is four 32-bit words -; | encryption round 1 | -; | encryption round 2 | -; .... -; | encryption round N-1 | -; hi: | encryption round N | -; -; The decryption key schedule is normally set up so that it has the same -; layout as above by actually reversing the order of the encryption key -; schedule in memory (this happens when AES_REV_DKS is set): -; -; lo: | decryption round 0 | = | encryption round N | -; | decryption round 1 | = INV_MIX_COL[ | encryption round N-1 | ] -; | decryption round 2 | = INV_MIX_COL[ | encryption round N-2 | ] -; .... .... -; | decryption round N-1 | = INV_MIX_COL[ | encryption round 1 | ] -; hi: | decryption round N | = | input key (round 0) | -; -; with rounds except the first and last modified using inv_mix_column() -; But if AES_REV_DKS is NOT set the order of keys is left as it is for -; encryption so that it has to be accessed in reverse when used for -; decryption (although the inverse mix column modifications are done) -; -; lo: | decryption round 0 | = | input key (round 0) | -; | decryption round 1 | = INV_MIX_COL[ | encryption round 1 | ] -; | decryption round 2 | = INV_MIX_COL[ | encryption round 2 | ] -; .... .... -; | decryption round N-1 | = INV_MIX_COL[ | encryption round N-1 | ] -; hi: | decryption round N | = | encryption round N | -; -; This layout is faster when the assembler key scheduling provided here -; is used. -; -; End of user defines - -%ifdef AES_VAR -%ifndef AES_128 -%define AES_128 -%endif -%ifndef AES_192 -%define AES_192 -%endif -%ifndef AES_256 -%define AES_256 -%endif -%endif - -%ifdef AES_VAR -%define KS_LENGTH 60 -%elifdef AES_256 -%define KS_LENGTH 60 -%elifdef AES_192 -%define KS_LENGTH 52 -%else -%define KS_LENGTH 44 -%endif - -; These macros implement stack based local variables - -%macro save 2 - mov [esp+4*%1],%2 -%endmacro - -%macro restore 2 - mov %1,[esp+4*%2] -%endmacro - -%ifdef REDUCE_CODE_SIZE - %macro mf_call 1 - call %1 - %endmacro -%else - %macro mf_call 1 - %1 - %endmacro -%endif - -; the DLL has to implement the _stdcall calling interface on return -; In this case we have to take our parameters (3 4-byte pointers) -; off the stack - -%define parms 12 - -%macro do_name 1-2 parms -%ifndef DLL_EXPORT - global %1 -%1: -%else - global %1@%2 - export %1@%2 -%1@%2: -%endif -%endmacro - -%macro do_call 1-2 parms -%ifndef DLL_EXPORT - call %1 - add esp,%2 -%else - call %1@%2 -%endif -%endmacro - -%macro do_exit 0-1 parms -%ifdef DLL_EXPORT - ret %1 -%else - ret -%endif -%endmacro - -; finite field multiplies by {02}, {04} and {08} - -%define f2(x) ((x<<1)^(((x>>7)&1)*0x11b)) -%define f4(x) ((x<<2)^(((x>>6)&1)*0x11b)^(((x>>6)&2)*0x11b)) -%define f8(x) ((x<<3)^(((x>>5)&1)*0x11b)^(((x>>5)&2)*0x11b)^(((x>>5)&4)*0x11b)) - -; finite field multiplies required in table generation - -%define f3(x) (f2(x) ^ x) -%define f9(x) (f8(x) ^ x) -%define fb(x) (f8(x) ^ f2(x) ^ x) -%define fd(x) (f8(x) ^ f4(x) ^ x) -%define fe(x) (f8(x) ^ f4(x) ^ f2(x)) - -%define etab_0(x) [_aes_enc_tab+4+8*x] -%define etab_1(x) [_aes_enc_tab+3+8*x] -%define etab_2(x) [_aes_enc_tab+2+8*x] -%define etab_3(x) [_aes_enc_tab+1+8*x] -%define etab_b(x) byte [_aes_enc_tab+1+8*x] ; used with movzx for 0x000000xx -%define etab_w(x) word [_aes_enc_tab+8*x] ; used with movzx for 0x0000xx00 - -%define btab_0(x) [_aes_enc_tab+6+8*x] -%define btab_1(x) [_aes_enc_tab+5+8*x] -%define btab_2(x) [_aes_enc_tab+4+8*x] -%define btab_3(x) [_aes_enc_tab+3+8*x] - -; ROUND FUNCTION. Build column[2] on ESI and column[3] on EDI that have the -; round keys pre-loaded. Build column[0] in EBP and column[1] in EBX. -; -; Input: -; -; EAX column[0] -; EBX column[1] -; ECX column[2] -; EDX column[3] -; ESI column key[round][2] -; EDI column key[round][3] -; EBP scratch -; -; Output: -; -; EBP column[0] unkeyed -; EBX column[1] unkeyed -; ESI column[2] keyed -; EDI column[3] keyed -; EAX scratch -; ECX scratch -; EDX scratch - -%macro rnd_fun 2 - - rol ebx,16 - %1 esi, cl, 0, ebp - %1 esi, dh, 1, ebp - %1 esi, bh, 3, ebp - %1 edi, dl, 0, ebp - %1 edi, ah, 1, ebp - %1 edi, bl, 2, ebp - %2 ebp, al, 0, ebp - shr ebx,16 - and eax,0xffff0000 - or eax,ebx - shr edx,16 - %1 ebp, ah, 1, ebx - %1 ebp, dh, 3, ebx - %2 ebx, dl, 2, ebx - %1 ebx, ch, 1, edx - %1 ebx, al, 0, edx - shr eax,16 - shr ecx,16 - %1 ebp, cl, 2, edx - %1 edi, ch, 3, edx - %1 esi, al, 2, edx - %1 ebx, ah, 3, edx - -%endmacro - -; Basic MOV and XOR Operations for normal rounds - -%macro nr_xor 4 - movzx %4,%2 - xor %1,etab_%3(%4) -%endmacro - -%macro nr_mov 4 - movzx %4,%2 - mov %1,etab_%3(%4) -%endmacro - -; Basic MOV and XOR Operations for last round - -%if 1 - - %macro lr_xor 4 - movzx %4,%2 - movzx %4,etab_b(%4) - %if %3 != 0 - shl %4,8*%3 - %endif - xor %1,%4 - %endmacro - - %macro lr_mov 4 - movzx %4,%2 - movzx %1,etab_b(%4) - %if %3 != 0 - shl %1,8*%3 - %endif - %endmacro - -%else ; less effective but worth leaving as an option - - %macro lr_xor 4 - movzx %4,%2 - mov %4,btab_%3(%4) - and %4,0x000000ff << 8 * %3 - xor %1,%4 - %endmacro - - %macro lr_mov 4 - movzx %4,%2 - mov %1,btab_%3(%4) - and %1,0x000000ff << 8 * %3 - %endmacro - -%endif - -; Apply S-Box to the 4 bytes in a 32-bit word and rotate byte positions - -%ifdef REDUCE_CODE_SIZE - -l3s_col: - movzx ecx,al ; in eax - movzx ecx, etab_b(ecx) ; out eax - xor edx,ecx ; scratch ecx,edx - movzx ecx,ah - movzx ecx, etab_b(ecx) - shl ecx,8 - xor edx,ecx - shr eax,16 - movzx ecx,al - movzx ecx, etab_b(ecx) - shl ecx,16 - xor edx,ecx - movzx ecx,ah - movzx ecx, etab_b(ecx) - shl ecx,24 - xor edx,ecx - mov eax,edx - ret - -%else - -%macro l3s_col 0 - - movzx ecx,al ; in eax - movzx ecx, etab_b(ecx) ; out eax - xor edx,ecx ; scratch ecx,edx - movzx ecx,ah - movzx ecx, etab_b(ecx) - shl ecx,8 - xor edx,ecx - shr eax,16 - movzx ecx,al - movzx ecx, etab_b(ecx) - shl ecx,16 - xor edx,ecx - movzx ecx,ah - movzx ecx, etab_b(ecx) - shl ecx,24 - xor edx,ecx - mov eax,edx - -%endmacro - -%endif - -; offsets to parameters - -in_blk equ 2 ; input byte array address parameter -out_blk equ 4 ; output byte array address parameter -ctx equ 6 ; AES context structure -stk_spc equ 20 ; stack space - -%ifdef ENCRYPTION - -; %define ENCRYPTION_TABLE - -%ifdef REDUCE_CODE_SIZE - -enc_round: - sub sp, 2 - add ebp,16 - save 1,ebp - mov esi,[ebp+8] - mov edi,[ebp+12] - - rnd_fun nr_xor, nr_mov - - mov eax,ebp - mov ecx,esi - mov edx,edi - restore ebp,1 - xor eax,[ebp] - xor ebx,[ebp+4] - add sp, 2 - ret - -%else - -%macro enc_round 0 - - add ebp,16 - save 0,ebp - mov esi,[ebp+8] - mov edi,[ebp+12] - - rnd_fun nr_xor, nr_mov - - mov eax,ebp - mov ecx,esi - mov edx,edi - restore ebp,0 - xor eax,[ebp] - xor ebx,[ebp+4] - -%endmacro - -%endif - -%macro enc_last_round 0 - - add ebp,16 - save 0,ebp - mov esi,[ebp+8] - mov edi,[ebp+12] - - rnd_fun lr_xor, lr_mov - - mov eax,ebp - restore ebp,0 - xor eax,[ebp] - xor ebx,[ebp+4] - -%endmacro - - section _TEXT - -; AES Encryption Subroutine - - do_name _aes_encrypt,12 - - mov ax, sp - movzx esp, ax - - sub esp,stk_spc - mov [esp+16],ebp - mov [esp+12],ebx - mov [esp+ 8],esi - mov [esp+ 4],edi - - movzx esi,word [esp+in_blk+stk_spc] ; input pointer - mov eax,[esi ] - mov ebx,[esi+ 4] - mov ecx,[esi+ 8] - mov edx,[esi+12] - - movzx ebp,word [esp+ctx+stk_spc] ; key pointer - movzx edi,byte [ebp+4*KS_LENGTH] - xor eax,[ebp ] - xor ebx,[ebp+ 4] - xor ecx,[ebp+ 8] - xor edx,[ebp+12] - -; determine the number of rounds - -%ifndef AES_256 - cmp edi,10*16 - je .3 - cmp edi,12*16 - je .2 - cmp edi,14*16 - je .1 - mov eax,-1 - jmp .5 -%endif - -.1: mf_call enc_round - mf_call enc_round -.2: mf_call enc_round - mf_call enc_round -.3: mf_call enc_round - mf_call enc_round - mf_call enc_round - mf_call enc_round - mf_call enc_round - mf_call enc_round - mf_call enc_round - mf_call enc_round - mf_call enc_round - enc_last_round - - movzx edx,word [esp+out_blk+stk_spc] - mov [edx],eax - mov [edx+4],ebx - mov [edx+8],esi - mov [edx+12],edi - xor eax,eax - -.5: mov ebp,[esp+16] - mov ebx,[esp+12] - mov esi,[esp+ 8] - mov edi,[esp+ 4] - add esp,stk_spc - do_exit 12 - -%endif - -%macro f_key 2 - - push ecx - push edx - mov edx,esi - ror eax,8 - mf_call l3s_col - mov esi,eax - pop edx - pop ecx - xor esi,rc_val - - mov [ebp+%1*%2],esi - xor edi,esi - mov [ebp+%1*%2+4],edi - xor ecx,edi - mov [ebp+%1*%2+8],ecx - xor edx,ecx - mov [ebp+%1*%2+12],edx - mov eax,edx - -%if %2 == 24 - -%if %1 < 7 - xor eax,[ebp+%1*%2+16-%2] - mov [ebp+%1*%2+16],eax - xor eax,[ebp+%1*%2+20-%2] - mov [ebp+%1*%2+20],eax -%endif - -%elif %2 == 32 - -%if %1 < 6 - push ecx - push edx - mov edx,[ebp+%1*%2+16-%2] - mf_call l3s_col - pop edx - pop ecx - mov [ebp+%1*%2+16],eax - xor eax,[ebp+%1*%2+20-%2] - mov [ebp+%1*%2+20],eax - xor eax,[ebp+%1*%2+24-%2] - mov [ebp+%1*%2+24],eax - xor eax,[ebp+%1*%2+28-%2] - mov [ebp+%1*%2+28],eax -%endif - -%endif - -%assign rc_val f2(rc_val) - -%endmacro - -%ifdef ENCRYPTION_KEY_SCHEDULE - -%ifdef AES_128 - -%ifndef ENCRYPTION_TABLE -; %define ENCRYPTION_TABLE -%endif - -%assign rc_val 1 - - do_name _aes_encrypt_key128,8 - - push ebp - push ebx - push esi - push edi - - mov ebp,[esp+24] - mov [ebp+4*KS_LENGTH],dword 10*16 - mov ebx,[esp+20] - - mov esi,[ebx] - mov [ebp],esi - mov edi,[ebx+4] - mov [ebp+4],edi - mov ecx,[ebx+8] - mov [ebp+8],ecx - mov edx,[ebx+12] - mov [ebp+12],edx - add ebp,16 - mov eax,edx - - f_key 0,16 ; 11 * 4 = 44 unsigned longs - f_key 1,16 ; 4 + 4 * 10 generated = 44 - f_key 2,16 - f_key 3,16 - f_key 4,16 - f_key 5,16 - f_key 6,16 - f_key 7,16 - f_key 8,16 - f_key 9,16 - - pop edi - pop esi - pop ebx - pop ebp - xor eax,eax - do_exit 8 - -%endif - -%ifdef AES_192 - -%ifndef ENCRYPTION_TABLE -; %define ENCRYPTION_TABLE -%endif - -%assign rc_val 1 - - do_name _aes_encrypt_key192,8 - - push ebp - push ebx - push esi - push edi - - mov ebp,[esp+24] - mov [ebp+4*KS_LENGTH],dword 12 * 16 - mov ebx,[esp+20] - - mov esi,[ebx] - mov [ebp],esi - mov edi,[ebx+4] - mov [ebp+4],edi - mov ecx,[ebx+8] - mov [ebp+8],ecx - mov edx,[ebx+12] - mov [ebp+12],edx - mov eax,[ebx+16] - mov [ebp+16],eax - mov eax,[ebx+20] - mov [ebp+20],eax - add ebp,24 - - f_key 0,24 ; 13 * 4 = 52 unsigned longs - f_key 1,24 ; 6 + 6 * 8 generated = 54 - f_key 2,24 - f_key 3,24 - f_key 4,24 - f_key 5,24 - f_key 6,24 - f_key 7,24 - - pop edi - pop esi - pop ebx - pop ebp - xor eax,eax - do_exit 8 - -%endif - -%ifdef AES_256 - -%ifndef ENCRYPTION_TABLE -; %define ENCRYPTION_TABLE -%endif - -%assign rc_val 1 - - do_name _aes_encrypt_key256,8 - - mov ax, sp - movzx esp, ax - - push ebp - push ebx - push esi - push edi - - movzx ebp, word [esp+20] ; ks - mov [ebp+4*KS_LENGTH],dword 14 * 16 - movzx ebx, word [esp+18] ; key - - mov esi,[ebx] - mov [ebp],esi - mov edi,[ebx+4] - mov [ebp+4],edi - mov ecx,[ebx+8] - mov [ebp+8],ecx - mov edx,[ebx+12] - mov [ebp+12],edx - mov eax,[ebx+16] - mov [ebp+16],eax - mov eax,[ebx+20] - mov [ebp+20],eax - mov eax,[ebx+24] - mov [ebp+24],eax - mov eax,[ebx+28] - mov [ebp+28],eax - add ebp,32 - - f_key 0,32 ; 15 * 4 = 60 unsigned longs - f_key 1,32 ; 8 + 8 * 7 generated = 64 - f_key 2,32 - f_key 3,32 - f_key 4,32 - f_key 5,32 - f_key 6,32 - - pop edi - pop esi - pop ebx - pop ebp - xor eax,eax - do_exit 8 - -%endif - -%ifdef AES_VAR - -%ifndef ENCRYPTION_TABLE -; %define ENCRYPTION_TABLE -%endif - - do_name _aes_encrypt_key,12 - - mov ecx,[esp+4] - mov eax,[esp+8] - mov edx,[esp+12] - push edx - push ecx - - cmp eax,16 - je .1 - cmp eax,128 - je .1 - - cmp eax,24 - je .2 - cmp eax,192 - je .2 - - cmp eax,32 - je .3 - cmp eax,256 - je .3 - mov eax,-1 - add esp,8 - do_exit 12 - -.1: do_call _aes_encrypt_key128,8 - do_exit 12 -.2: do_call _aes_encrypt_key192,8 - do_exit 12 -.3: do_call _aes_encrypt_key256,8 - do_exit 12 - -%endif - -%endif - -%ifdef ENCRYPTION_TABLE - -; S-box data - 256 entries - - section _DATA - -%define u8(x) 0, x, x, f3(x), f2(x), x, x, f3(x) - -_aes_enc_tab: - db u8(0x63),u8(0x7c),u8(0x77),u8(0x7b),u8(0xf2),u8(0x6b),u8(0x6f),u8(0xc5) - db u8(0x30),u8(0x01),u8(0x67),u8(0x2b),u8(0xfe),u8(0xd7),u8(0xab),u8(0x76) - db u8(0xca),u8(0x82),u8(0xc9),u8(0x7d),u8(0xfa),u8(0x59),u8(0x47),u8(0xf0) - db u8(0xad),u8(0xd4),u8(0xa2),u8(0xaf),u8(0x9c),u8(0xa4),u8(0x72),u8(0xc0) - db u8(0xb7),u8(0xfd),u8(0x93),u8(0x26),u8(0x36),u8(0x3f),u8(0xf7),u8(0xcc) - db u8(0x34),u8(0xa5),u8(0xe5),u8(0xf1),u8(0x71),u8(0xd8),u8(0x31),u8(0x15) - db u8(0x04),u8(0xc7),u8(0x23),u8(0xc3),u8(0x18),u8(0x96),u8(0x05),u8(0x9a) - db u8(0x07),u8(0x12),u8(0x80),u8(0xe2),u8(0xeb),u8(0x27),u8(0xb2),u8(0x75) - db u8(0x09),u8(0x83),u8(0x2c),u8(0x1a),u8(0x1b),u8(0x6e),u8(0x5a),u8(0xa0) - db u8(0x52),u8(0x3b),u8(0xd6),u8(0xb3),u8(0x29),u8(0xe3),u8(0x2f),u8(0x84) - db u8(0x53),u8(0xd1),u8(0x00),u8(0xed),u8(0x20),u8(0xfc),u8(0xb1),u8(0x5b) - db u8(0x6a),u8(0xcb),u8(0xbe),u8(0x39),u8(0x4a),u8(0x4c),u8(0x58),u8(0xcf) - db u8(0xd0),u8(0xef),u8(0xaa),u8(0xfb),u8(0x43),u8(0x4d),u8(0x33),u8(0x85) - db u8(0x45),u8(0xf9),u8(0x02),u8(0x7f),u8(0x50),u8(0x3c),u8(0x9f),u8(0xa8) - db u8(0x51),u8(0xa3),u8(0x40),u8(0x8f),u8(0x92),u8(0x9d),u8(0x38),u8(0xf5) - db u8(0xbc),u8(0xb6),u8(0xda),u8(0x21),u8(0x10),u8(0xff),u8(0xf3),u8(0xd2) - db u8(0xcd),u8(0x0c),u8(0x13),u8(0xec),u8(0x5f),u8(0x97),u8(0x44),u8(0x17) - db u8(0xc4),u8(0xa7),u8(0x7e),u8(0x3d),u8(0x64),u8(0x5d),u8(0x19),u8(0x73) - db u8(0x60),u8(0x81),u8(0x4f),u8(0xdc),u8(0x22),u8(0x2a),u8(0x90),u8(0x88) - db u8(0x46),u8(0xee),u8(0xb8),u8(0x14),u8(0xde),u8(0x5e),u8(0x0b),u8(0xdb) - db u8(0xe0),u8(0x32),u8(0x3a),u8(0x0a),u8(0x49),u8(0x06),u8(0x24),u8(0x5c) - db u8(0xc2),u8(0xd3),u8(0xac),u8(0x62),u8(0x91),u8(0x95),u8(0xe4),u8(0x79) - db u8(0xe7),u8(0xc8),u8(0x37),u8(0x6d),u8(0x8d),u8(0xd5),u8(0x4e),u8(0xa9) - db u8(0x6c),u8(0x56),u8(0xf4),u8(0xea),u8(0x65),u8(0x7a),u8(0xae),u8(0x08) - db u8(0xba),u8(0x78),u8(0x25),u8(0x2e),u8(0x1c),u8(0xa6),u8(0xb4),u8(0xc6) - db u8(0xe8),u8(0xdd),u8(0x74),u8(0x1f),u8(0x4b),u8(0xbd),u8(0x8b),u8(0x8a) - db u8(0x70),u8(0x3e),u8(0xb5),u8(0x66),u8(0x48),u8(0x03),u8(0xf6),u8(0x0e) - db u8(0x61),u8(0x35),u8(0x57),u8(0xb9),u8(0x86),u8(0xc1),u8(0x1d),u8(0x9e) - db u8(0xe1),u8(0xf8),u8(0x98),u8(0x11),u8(0x69),u8(0xd9),u8(0x8e),u8(0x94) - db u8(0x9b),u8(0x1e),u8(0x87),u8(0xe9),u8(0xce),u8(0x55),u8(0x28),u8(0xdf) - db u8(0x8c),u8(0xa1),u8(0x89),u8(0x0d),u8(0xbf),u8(0xe6),u8(0x42),u8(0x68) - db u8(0x41),u8(0x99),u8(0x2d),u8(0x0f),u8(0xb0),u8(0x54),u8(0xbb),u8(0x16) - -%endif - -%ifdef DECRYPTION - -; %define DECRYPTION_TABLE - -%define dtab_0(x) [_aes_dec_tab+ 8*x] -%define dtab_1(x) [_aes_dec_tab+3+8*x] -%define dtab_2(x) [_aes_dec_tab+2+8*x] -%define dtab_3(x) [_aes_dec_tab+1+8*x] -%define dtab_x(x) byte [_aes_dec_tab+7+8*x] - -%macro irn_fun 2 - - rol eax,16 - %1 esi, cl, 0, ebp - %1 esi, bh, 1, ebp - %1 esi, al, 2, ebp - %1 edi, dl, 0, ebp - %1 edi, ch, 1, ebp - %1 edi, ah, 3, ebp - %2 ebp, bl, 0, ebp - shr eax,16 - and ebx,0xffff0000 - or ebx,eax - shr ecx,16 - %1 ebp, bh, 1, eax - %1 ebp, ch, 3, eax - %2 eax, cl, 2, ecx - %1 eax, bl, 0, ecx - %1 eax, dh, 1, ecx - shr ebx,16 - shr edx,16 - %1 esi, dh, 3, ecx - %1 ebp, dl, 2, ecx - %1 eax, bh, 3, ecx - %1 edi, bl, 2, ecx - -%endmacro - -; Basic MOV and XOR Operations for normal rounds - -%macro ni_xor 4 - movzx %4,%2 - xor %1,dtab_%3(%4) -%endmacro - -%macro ni_mov 4 - movzx %4,%2 - mov %1,dtab_%3(%4) -%endmacro - -; Basic MOV and XOR Operations for last round - -%macro li_xor 4 - movzx %4,%2 - movzx %4,dtab_x(%4) -%if %3 != 0 - shl %4,8*%3 -%endif - xor %1,%4 -%endmacro - -%macro li_mov 4 - movzx %4,%2 - movzx %1,dtab_x(%4) -%if %3 != 0 - shl %1,8*%3 -%endif -%endmacro - -%ifdef REDUCE_CODE_SIZE - -dec_round: - sub sp, 2 -%ifdef AES_REV_DKS - add ebp,16 -%else - sub ebp,16 -%endif - save 1,ebp - mov esi,[ebp+8] - mov edi,[ebp+12] - - irn_fun ni_xor, ni_mov - - mov ebx,ebp - mov ecx,esi - mov edx,edi - restore ebp,1 - xor eax,[ebp] - xor ebx,[ebp+4] - add sp, 2 - ret - -%else - -%macro dec_round 0 - -%ifdef AES_REV_DKS - add ebp,16 -%else - sub ebp,16 -%endif - save 0,ebp - mov esi,[ebp+8] - mov edi,[ebp+12] - - irn_fun ni_xor, ni_mov - - mov ebx,ebp - mov ecx,esi - mov edx,edi - restore ebp,0 - xor eax,[ebp] - xor ebx,[ebp+4] - -%endmacro - -%endif - -%macro dec_last_round 0 - -%ifdef AES_REV_DKS - add ebp,16 -%else - sub ebp,16 -%endif - save 0,ebp - mov esi,[ebp+8] - mov edi,[ebp+12] - - irn_fun li_xor, li_mov - - mov ebx,ebp - restore ebp,0 - xor eax,[ebp] - xor ebx,[ebp+4] - -%endmacro - - section _TEXT - -; AES Decryption Subroutine - - do_name _aes_decrypt,12 - - mov ax, sp - movzx esp, ax - - sub esp,stk_spc - mov [esp+16],ebp - mov [esp+12],ebx - mov [esp+ 8],esi - mov [esp+ 4],edi - -; input four columns and xor in first round key - - movzx esi,word [esp+in_blk+stk_spc] ; input pointer - mov eax,[esi ] - mov ebx,[esi+ 4] - mov ecx,[esi+ 8] - mov edx,[esi+12] - lea esi,[esi+16] - - movzx ebp, word [esp+ctx+stk_spc] ; key pointer - movzx edi,byte[ebp+4*KS_LENGTH] -%ifndef AES_REV_DKS ; if decryption key schedule is not reversed - lea ebp,[ebp+edi] ; we have to access it from the top down -%endif - xor eax,[ebp ] ; key schedule - xor ebx,[ebp+ 4] - xor ecx,[ebp+ 8] - xor edx,[ebp+12] - -; determine the number of rounds - -%ifndef AES_256 - cmp edi,10*16 - je .3 - cmp edi,12*16 - je .2 - cmp edi,14*16 - je .1 - mov eax,-1 - jmp .5 -%endif - -.1: mf_call dec_round - mf_call dec_round -.2: mf_call dec_round - mf_call dec_round -.3: mf_call dec_round - mf_call dec_round - mf_call dec_round - mf_call dec_round - mf_call dec_round - mf_call dec_round - mf_call dec_round - mf_call dec_round - mf_call dec_round - dec_last_round - -; move final values to the output array. - - movzx ebp,word [esp+out_blk+stk_spc] - mov [ebp],eax - mov [ebp+4],ebx - mov [ebp+8],esi - mov [ebp+12],edi - xor eax,eax - -.5: mov ebp,[esp+16] - mov ebx,[esp+12] - mov esi,[esp+ 8] - mov edi,[esp+ 4] - add esp,stk_spc - do_exit 12 - -%endif - -%ifdef REDUCE_CODE_SIZE - -inv_mix_col: - movzx ecx,dl ; input eax, edx - movzx ecx,etab_b(ecx) ; output eax - mov eax,dtab_0(ecx) ; used ecx - movzx ecx,dh - shr edx,16 - movzx ecx,etab_b(ecx) - xor eax,dtab_1(ecx) - movzx ecx,dl - movzx ecx,etab_b(ecx) - xor eax,dtab_2(ecx) - movzx ecx,dh - movzx ecx,etab_b(ecx) - xor eax,dtab_3(ecx) - ret - -%else - -%macro inv_mix_col 0 - - movzx ecx,dl ; input eax, edx - movzx ecx,etab_b(ecx) ; output eax - mov eax,dtab_0(ecx) ; used ecx - movzx ecx,dh - shr edx,16 - movzx ecx,etab_b(ecx) - xor eax,dtab_1(ecx) - movzx ecx,dl - movzx ecx,etab_b(ecx) - xor eax,dtab_2(ecx) - movzx ecx,dh - movzx ecx,etab_b(ecx) - xor eax,dtab_3(ecx) - -%endmacro - -%endif - -%ifdef DECRYPTION_KEY_SCHEDULE - -%ifdef AES_128 - -%ifndef DECRYPTION_TABLE -; %define DECRYPTION_TABLE -%endif - - do_name _aes_decrypt_key128,8 - - push ebp - push ebx - push esi - push edi - mov eax,[esp+24] ; context - mov edx,[esp+20] ; key - push eax - push edx - do_call _aes_encrypt_key128,8 ; generate expanded encryption key - mov eax,10*16 - mov esi,[esp+24] ; pointer to first round key - lea edi,[esi+eax] ; pointer to last round key - add esi,32 - ; the inverse mix column transformation - mov edx,[esi-16] ; needs to be applied to all round keys - mf_call inv_mix_col ; except first and last. Hence start by - mov [esi-16],eax ; transforming the four sub-keys in the - mov edx,[esi-12] ; second round key - mf_call inv_mix_col - mov [esi-12],eax ; transformations for subsequent rounds - mov edx,[esi-8] ; can then be made more efficient by - mf_call inv_mix_col ; noting that for three of the four sub-keys - mov [esi-8],eax ; in the encryption round key ek[r]: - mov edx,[esi-4] ; - mf_call inv_mix_col ; ek[r][n] = ek[r][n-1] ^ ek[r-1][n] - mov [esi-4],eax ; - ; where n is 1..3. Hence the corresponding -.0: mov edx,[esi] ; subkeys in the decryption round key dk[r] - mf_call inv_mix_col ; also obey since inv_mix_col is linear in - mov [esi],eax ; GF(256): - xor eax,[esi-12] ; - mov [esi+4],eax ; dk[r][n] = dk[r][n-1] ^ dk[r-1][n] - xor eax,[esi-8] ; - mov [esi+8],eax ; So we only need one inverse mix column - xor eax,[esi-4] ; operation (n = 0) for each four word cycle - mov [esi+12],eax ; in the expanded key. - add esi,16 - cmp edi,esi - jg .0 - jmp dec_end - -%endif - -%ifdef AES_192 - -%ifndef DECRYPTION_TABLE -; %define DECRYPTION_TABLE -%endif - - do_name _aes_decrypt_key192,8 - - push ebp - push ebx - push esi - push edi - mov eax,[esp+24] ; context - mov edx,[esp+20] ; key - push eax - push edx - do_call _aes_encrypt_key192,8 ; generate expanded encryption key - mov eax,12*16 - mov esi,[esp+24] ; first round key - lea edi,[esi+eax] ; last round key - add esi,48 ; the first 6 words are the key, of - ; which the top 2 words are part of - mov edx,[esi-32] ; the second round key and hence - mf_call inv_mix_col ; need to be modified. After this we - mov [esi-32],eax ; need to do a further six values prior - mov edx,[esi-28] ; to using a more efficient technique - mf_call inv_mix_col ; based on: - mov [esi-28],eax ; - ; dk[r][n] = dk[r][n-1] ^ dk[r-1][n] - mov edx,[esi-24] ; - mf_call inv_mix_col ; for n = 1 .. 5 where the key expansion - mov [esi-24],eax ; cycle is now 6 words long - mov edx,[esi-20] - mf_call inv_mix_col - mov [esi-20],eax - mov edx,[esi-16] - mf_call inv_mix_col - mov [esi-16],eax - mov edx,[esi-12] - mf_call inv_mix_col - mov [esi-12],eax - mov edx,[esi-8] - mf_call inv_mix_col - mov [esi-8],eax - mov edx,[esi-4] - mf_call inv_mix_col - mov [esi-4],eax - -.0: mov edx,[esi] ; the expanded key is 13 * 4 = 44 32-bit words - mf_call inv_mix_col ; of which 11 * 4 = 44 have to be modified - mov [esi],eax ; using inv_mix_col. We have already done 8 - xor eax,[esi-20] ; of these so 36 are left - hence we need - mov [esi+4],eax ; exactly 6 loops of six here - xor eax,[esi-16] - mov [esi+8],eax - xor eax,[esi-12] - mov [esi+12],eax - xor eax,[esi-8] - mov [esi+16],eax - xor eax,[esi-4] - mov [esi+20],eax - add esi,24 - cmp edi,esi - jg .0 - jmp dec_end - -%endif - -%ifdef AES_256 - -%ifndef DECRYPTION_TABLE -; %define DECRYPTION_TABLE -%endif - - do_name _aes_decrypt_key256,8 - - mov ax, sp - movzx esp, ax - push ebp - push ebx - push esi - push edi - - movzx eax, word [esp+20] ; ks - movzx edx, word [esp+18] ; key - push ax - push dx - do_call _aes_encrypt_key256,4 ; generate expanded encryption key - mov eax,14*16 - movzx esi, word [esp+20] ; ks - lea edi,[esi+eax] - add esi,64 - - mov edx,[esi-48] ; the primary key is 8 words, of which - mf_call inv_mix_col ; the top four require modification - mov [esi-48],eax - mov edx,[esi-44] - mf_call inv_mix_col - mov [esi-44],eax - mov edx,[esi-40] - mf_call inv_mix_col - mov [esi-40],eax - mov edx,[esi-36] - mf_call inv_mix_col - mov [esi-36],eax - - mov edx,[esi-32] ; the encryption key expansion cycle is - mf_call inv_mix_col ; now eight words long so we need to - mov [esi-32],eax ; start by doing one complete block - mov edx,[esi-28] - mf_call inv_mix_col - mov [esi-28],eax - mov edx,[esi-24] - mf_call inv_mix_col - mov [esi-24],eax - mov edx,[esi-20] - mf_call inv_mix_col - mov [esi-20],eax - mov edx,[esi-16] - mf_call inv_mix_col - mov [esi-16],eax - mov edx,[esi-12] - mf_call inv_mix_col - mov [esi-12],eax - mov edx,[esi-8] - mf_call inv_mix_col - mov [esi-8],eax - mov edx,[esi-4] - mf_call inv_mix_col - mov [esi-4],eax - -.0: mov edx,[esi] ; we can now speed up the remaining - mf_call inv_mix_col ; rounds by using the technique - mov [esi],eax ; outlined earlier. But note that - xor eax,[esi-28] ; there is one extra inverse mix - mov [esi+4],eax ; column operation as the 256 bit - xor eax,[esi-24] ; key has an extra non-linear step - mov [esi+8],eax ; for the midway element. - xor eax,[esi-20] - mov [esi+12],eax ; the expanded key is 15 * 4 = 60 - mov edx,[esi+16] ; 32-bit words of which 52 need to - mf_call inv_mix_col ; be modified. We have already done - mov [esi+16],eax ; 12 so 40 are left - which means - xor eax,[esi-12] ; that we need exactly 5 loops of 8 - mov [esi+20],eax - xor eax,[esi-8] - mov [esi+24],eax - xor eax,[esi-4] - mov [esi+28],eax - add esi,32 - cmp edi,esi - jg .0 - -%endif - -dec_end: - -%ifdef AES_REV_DKS - - movzx esi,word [esp+20] ; this reverses the order of the -.1: mov eax,[esi] ; round keys if required - mov ebx,[esi+4] - mov ebp,[edi] - mov edx,[edi+4] - mov [esi],ebp - mov [esi+4],edx - mov [edi],eax - mov [edi+4],ebx - - mov eax,[esi+8] - mov ebx,[esi+12] - mov ebp,[edi+8] - mov edx,[edi+12] - mov [esi+8],ebp - mov [esi+12],edx - mov [edi+8],eax - mov [edi+12],ebx - - add esi,16 - sub edi,16 - cmp edi,esi - jg .1 - -%endif - - pop edi - pop esi - pop ebx - pop ebp - xor eax,eax - do_exit 8 - -%ifdef AES_VAR - - do_name _aes_decrypt_key,12 - - mov ecx,[esp+4] - mov eax,[esp+8] - mov edx,[esp+12] - push edx - push ecx - - cmp eax,16 - je .1 - cmp eax,128 - je .1 - - cmp eax,24 - je .2 - cmp eax,192 - je .2 - - cmp eax,32 - je .3 - cmp eax,256 - je .3 - mov eax,-1 - add esp,8 - do_exit 12 - -.1: do_call _aes_decrypt_key128,8 - do_exit 12 -.2: do_call _aes_decrypt_key192,8 - do_exit 12 -.3: do_call _aes_decrypt_key256,8 - do_exit 12 - -%endif - -%endif - -%ifdef DECRYPTION_TABLE - -; Inverse S-box data - 256 entries - - section _DATA - -%define v8(x) fe(x), f9(x), fd(x), fb(x), fe(x), f9(x), fd(x), x - -_aes_dec_tab: - db v8(0x52),v8(0x09),v8(0x6a),v8(0xd5),v8(0x30),v8(0x36),v8(0xa5),v8(0x38) - db v8(0xbf),v8(0x40),v8(0xa3),v8(0x9e),v8(0x81),v8(0xf3),v8(0xd7),v8(0xfb) - db v8(0x7c),v8(0xe3),v8(0x39),v8(0x82),v8(0x9b),v8(0x2f),v8(0xff),v8(0x87) - db v8(0x34),v8(0x8e),v8(0x43),v8(0x44),v8(0xc4),v8(0xde),v8(0xe9),v8(0xcb) - db v8(0x54),v8(0x7b),v8(0x94),v8(0x32),v8(0xa6),v8(0xc2),v8(0x23),v8(0x3d) - db v8(0xee),v8(0x4c),v8(0x95),v8(0x0b),v8(0x42),v8(0xfa),v8(0xc3),v8(0x4e) - db v8(0x08),v8(0x2e),v8(0xa1),v8(0x66),v8(0x28),v8(0xd9),v8(0x24),v8(0xb2) - db v8(0x76),v8(0x5b),v8(0xa2),v8(0x49),v8(0x6d),v8(0x8b),v8(0xd1),v8(0x25) - db v8(0x72),v8(0xf8),v8(0xf6),v8(0x64),v8(0x86),v8(0x68),v8(0x98),v8(0x16) - db v8(0xd4),v8(0xa4),v8(0x5c),v8(0xcc),v8(0x5d),v8(0x65),v8(0xb6),v8(0x92) - db v8(0x6c),v8(0x70),v8(0x48),v8(0x50),v8(0xfd),v8(0xed),v8(0xb9),v8(0xda) - db v8(0x5e),v8(0x15),v8(0x46),v8(0x57),v8(0xa7),v8(0x8d),v8(0x9d),v8(0x84) - db v8(0x90),v8(0xd8),v8(0xab),v8(0x00),v8(0x8c),v8(0xbc),v8(0xd3),v8(0x0a) - db v8(0xf7),v8(0xe4),v8(0x58),v8(0x05),v8(0xb8),v8(0xb3),v8(0x45),v8(0x06) - db v8(0xd0),v8(0x2c),v8(0x1e),v8(0x8f),v8(0xca),v8(0x3f),v8(0x0f),v8(0x02) - db v8(0xc1),v8(0xaf),v8(0xbd),v8(0x03),v8(0x01),v8(0x13),v8(0x8a),v8(0x6b) - db v8(0x3a),v8(0x91),v8(0x11),v8(0x41),v8(0x4f),v8(0x67),v8(0xdc),v8(0xea) - db v8(0x97),v8(0xf2),v8(0xcf),v8(0xce),v8(0xf0),v8(0xb4),v8(0xe6),v8(0x73) - db v8(0x96),v8(0xac),v8(0x74),v8(0x22),v8(0xe7),v8(0xad),v8(0x35),v8(0x85) - db v8(0xe2),v8(0xf9),v8(0x37),v8(0xe8),v8(0x1c),v8(0x75),v8(0xdf),v8(0x6e) - db v8(0x47),v8(0xf1),v8(0x1a),v8(0x71),v8(0x1d),v8(0x29),v8(0xc5),v8(0x89) - db v8(0x6f),v8(0xb7),v8(0x62),v8(0x0e),v8(0xaa),v8(0x18),v8(0xbe),v8(0x1b) - db v8(0xfc),v8(0x56),v8(0x3e),v8(0x4b),v8(0xc6),v8(0xd2),v8(0x79),v8(0x20) - db v8(0x9a),v8(0xdb),v8(0xc0),v8(0xfe),v8(0x78),v8(0xcd),v8(0x5a),v8(0xf4) - db v8(0x1f),v8(0xdd),v8(0xa8),v8(0x33),v8(0x88),v8(0x07),v8(0xc7),v8(0x31) - db v8(0xb1),v8(0x12),v8(0x10),v8(0x59),v8(0x27),v8(0x80),v8(0xec),v8(0x5f) - db v8(0x60),v8(0x51),v8(0x7f),v8(0xa9),v8(0x19),v8(0xb5),v8(0x4a),v8(0x0d) - db v8(0x2d),v8(0xe5),v8(0x7a),v8(0x9f),v8(0x93),v8(0xc9),v8(0x9c),v8(0xef) - db v8(0xa0),v8(0xe0),v8(0x3b),v8(0x4d),v8(0xae),v8(0x2a),v8(0xf5),v8(0xb0) - db v8(0xc8),v8(0xeb),v8(0xbb),v8(0x3c),v8(0x83),v8(0x53),v8(0x99),v8(0x61) - db v8(0x17),v8(0x2b),v8(0x04),v8(0x7e),v8(0xba),v8(0x77),v8(0xd6),v8(0x26) - db v8(0xe1),v8(0x69),v8(0x14),v8(0x63),v8(0x55),v8(0x21),v8(0x0c),v8(0x7d) - -%endif + +; --------------------------------------------------------------------------- +; Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. +; +; LICENSE TERMS +; +; The free distribution and use of this software is allowed (with or without +; changes) provided that: +; +; 1. source code distributions include the above copyright notice, this +; list of conditions and the following disclaimer; +; +; 2. binary distributions include the above copyright notice, this list +; of conditions and the following disclaimer in their documentation; +; +; 3. the name of the copyright holder is not used to endorse products +; built using this software without specific written permission. +; +; DISCLAIMER +; +; This software is provided 'as is' with no explicit or implied warranties +; in respect of its properties, including, but not limited to, correctness +; and/or fitness for purpose. +; --------------------------------------------------------------------------- +; Issue 20/12/2007 +; +; This code requires either ASM_X86_V2 or ASM_X86_V2C to be set in aesopt.h +; and the same define to be set here as well. If AES_V2C is set this file +; requires the C files aeskey.c and aestab.c for support. + +; An AES implementation for x86 processors using the YASM (or NASM) assembler. +; This is a full assembler implementation covering encryption, decryption and +; key scheduling. It uses 2k bytes of tables but its encryption and decryption +; performance is very close to that obtained using large tables. Key schedule +; expansion is slower for both encryption and decryption but this is likely to +; be offset by the much smaller load that this version places on the processor +; cache. I acknowledge the contribution made by Daniel Bernstein to aspects of +; the design of the AES round function used here. +; +; This code provides the standard AES block size (128 bits, 16 bytes) and the +; three standard AES key sizes (128, 192 and 256 bits). It has the same call +; interface as my C implementation. The ebx, esi, edi and ebp registers are +; preserved across calls but eax, ecx and edx and the artihmetic status flags +; are not. Although this is a full assembler implementation, it can be used +; in conjunction with my C code which provides faster key scheduling using +; large tables. In this case aeskey.c should be compiled with ASM_X86_V2C +; defined. It is also important that the defines below match those used in the +; C code. This code uses the VC++ register saving conentions; if it is used +; with another compiler, conventions for using and saving registers may need +; to be checked (and calling conventions). The YASM command line for the VC++ +; custom build step is: +; +; yasm -Xvc -f win32 -D -o "$(TargetDir)\$(InputName).obj" "$(InputPath)" +; +; For the cryptlib build this is (pcg): +; +; yasm -Xvc -f win32 -D ASM_X86_V2C -o aescrypt2.obj aes_x86_v2.asm +; +; where is ASM_X86_V2 or ASM_X86_V2C. The calling intefaces are: +; +; AES_RETURN aes_encrypt(const unsigned char in_blk[], +; unsigned char out_blk[], const aes_encrypt_ctx cx[1]); +; +; AES_RETURN aes_decrypt(const unsigned char in_blk[], +; unsigned char out_blk[], const aes_decrypt_ctx cx[1]); +; +; AES_RETURN aes_encrypt_key(const unsigned char key[], +; const aes_encrypt_ctx cx[1]); +; +; AES_RETURN aes_decrypt_key(const unsigned char key[], +; const aes_decrypt_ctx cx[1]); +; +; AES_RETURN aes_encrypt_key(const unsigned char key[], +; unsigned int len, const aes_decrypt_ctx cx[1]); +; +; AES_RETURN aes_decrypt_key(const unsigned char key[], +; unsigned int len, const aes_decrypt_ctx cx[1]); +; +; where is 128, 102 or 256. In the last two calls the length can be in +; either bits or bytes. + +; The DLL interface must use the _stdcall convention in which the number +; of bytes of parameter space is added after an @ to the sutine's name. +; We must also remove our parameters from the stack before return (see +; the do_exit macro). Define DLL_EXPORT for the Dynamic Link Library version. + +; +; Adapted for TrueCrypt: +; - All tables generated at run-time +; - Adapted for 16-bit environment +; + +CPU 386 +USE16 +SEGMENT _TEXT PUBLIC CLASS=CODE USE16 +SEGMENT _DATA PUBLIC CLASS=DATA USE16 + +GROUP DGROUP _TEXT _DATA + +extern _aes_dec_tab ; Aestab.c +extern _aes_enc_tab + +; %define DLL_EXPORT + +; The size of the code can be reduced by using functions for the encryption +; and decryption rounds in place of macro expansion + +%define REDUCE_CODE_SIZE + +; Comment in/out the following lines to obtain the desired subroutines. These +; selections MUST match those in the C header file aes.h + +; %define AES_128 ; define if AES with 128 bit keys is needed +; %define AES_192 ; define if AES with 192 bit keys is needed +%define AES_256 ; define if AES with 256 bit keys is needed +; %define AES_VAR ; define if a variable key size is needed +%define ENCRYPTION ; define if encryption is needed +%define DECRYPTION ; define if decryption is needed +; %define AES_REV_DKS ; define if key decryption schedule is reversed + +%ifndef ASM_X86_V2C +%define ENCRYPTION_KEY_SCHEDULE ; define if encryption key expansion is needed +%define DECRYPTION_KEY_SCHEDULE ; define if decryption key expansion is needed +%endif + +; The encryption key schedule has the following in memory layout where N is the +; number of rounds (10, 12 or 14): +; +; lo: | input key (round 0) | ; each round is four 32-bit words +; | encryption round 1 | +; | encryption round 2 | +; .... +; | encryption round N-1 | +; hi: | encryption round N | +; +; The decryption key schedule is normally set up so that it has the same +; layout as above by actually reversing the order of the encryption key +; schedule in memory (this happens when AES_REV_DKS is set): +; +; lo: | decryption round 0 | = | encryption round N | +; | decryption round 1 | = INV_MIX_COL[ | encryption round N-1 | ] +; | decryption round 2 | = INV_MIX_COL[ | encryption round N-2 | ] +; .... .... +; | decryption round N-1 | = INV_MIX_COL[ | encryption round 1 | ] +; hi: | decryption round N | = | input key (round 0) | +; +; with rounds except the first and last modified using inv_mix_column() +; But if AES_REV_DKS is NOT set the order of keys is left as it is for +; encryption so that it has to be accessed in reverse when used for +; decryption (although the inverse mix column modifications are done) +; +; lo: | decryption round 0 | = | input key (round 0) | +; | decryption round 1 | = INV_MIX_COL[ | encryption round 1 | ] +; | decryption round 2 | = INV_MIX_COL[ | encryption round 2 | ] +; .... .... +; | decryption round N-1 | = INV_MIX_COL[ | encryption round N-1 | ] +; hi: | decryption round N | = | encryption round N | +; +; This layout is faster when the assembler key scheduling provided here +; is used. +; +; End of user defines + +%ifdef AES_VAR +%ifndef AES_128 +%define AES_128 +%endif +%ifndef AES_192 +%define AES_192 +%endif +%ifndef AES_256 +%define AES_256 +%endif +%endif + +%ifdef AES_VAR +%define KS_LENGTH 60 +%elifdef AES_256 +%define KS_LENGTH 60 +%elifdef AES_192 +%define KS_LENGTH 52 +%else +%define KS_LENGTH 44 +%endif + +; These macros implement stack based local variables + +%macro save 2 + mov [esp+4*%1],%2 +%endmacro + +%macro restore 2 + mov %1,[esp+4*%2] +%endmacro + +%ifdef REDUCE_CODE_SIZE + %macro mf_call 1 + call %1 + %endmacro +%else + %macro mf_call 1 + %1 + %endmacro +%endif + +; the DLL has to implement the _stdcall calling interface on return +; In this case we have to take our parameters (3 4-byte pointers) +; off the stack + +%define parms 12 + +%macro do_name 1-2 parms +%ifndef DLL_EXPORT + global %1 +%1: +%else + global %1@%2 + export %1@%2 +%1@%2: +%endif +%endmacro + +%macro do_call 1-2 parms +%ifndef DLL_EXPORT + call %1 + add esp,%2 +%else + call %1@%2 +%endif +%endmacro + +%macro do_exit 0-1 parms +%ifdef DLL_EXPORT + ret %1 +%else + ret +%endif +%endmacro + +; finite field multiplies by {02}, {04} and {08} + +%define f2(x) ((x<<1)^(((x>>7)&1)*0x11b)) +%define f4(x) ((x<<2)^(((x>>6)&1)*0x11b)^(((x>>6)&2)*0x11b)) +%define f8(x) ((x<<3)^(((x>>5)&1)*0x11b)^(((x>>5)&2)*0x11b)^(((x>>5)&4)*0x11b)) + +; finite field multiplies required in table generation + +%define f3(x) (f2(x) ^ x) +%define f9(x) (f8(x) ^ x) +%define fb(x) (f8(x) ^ f2(x) ^ x) +%define fd(x) (f8(x) ^ f4(x) ^ x) +%define fe(x) (f8(x) ^ f4(x) ^ f2(x)) + +%define etab_0(x) [_aes_enc_tab+4+8*x] +%define etab_1(x) [_aes_enc_tab+3+8*x] +%define etab_2(x) [_aes_enc_tab+2+8*x] +%define etab_3(x) [_aes_enc_tab+1+8*x] +%define etab_b(x) byte [_aes_enc_tab+1+8*x] ; used with movzx for 0x000000xx +%define etab_w(x) word [_aes_enc_tab+8*x] ; used with movzx for 0x0000xx00 + +%define btab_0(x) [_aes_enc_tab+6+8*x] +%define btab_1(x) [_aes_enc_tab+5+8*x] +%define btab_2(x) [_aes_enc_tab+4+8*x] +%define btab_3(x) [_aes_enc_tab+3+8*x] + +; ROUND FUNCTION. Build column[2] on ESI and column[3] on EDI that have the +; round keys pre-loaded. Build column[0] in EBP and column[1] in EBX. +; +; Input: +; +; EAX column[0] +; EBX column[1] +; ECX column[2] +; EDX column[3] +; ESI column key[round][2] +; EDI column key[round][3] +; EBP scratch +; +; Output: +; +; EBP column[0] unkeyed +; EBX column[1] unkeyed +; ESI column[2] keyed +; EDI column[3] keyed +; EAX scratch +; ECX scratch +; EDX scratch + +%macro rnd_fun 2 + + rol ebx,16 + %1 esi, cl, 0, ebp + %1 esi, dh, 1, ebp + %1 esi, bh, 3, ebp + %1 edi, dl, 0, ebp + %1 edi, ah, 1, ebp + %1 edi, bl, 2, ebp + %2 ebp, al, 0, ebp + shr ebx,16 + and eax,0xffff0000 + or eax,ebx + shr edx,16 + %1 ebp, ah, 1, ebx + %1 ebp, dh, 3, ebx + %2 ebx, dl, 2, ebx + %1 ebx, ch, 1, edx + %1 ebx, al, 0, edx + shr eax,16 + shr ecx,16 + %1 ebp, cl, 2, edx + %1 edi, ch, 3, edx + %1 esi, al, 2, edx + %1 ebx, ah, 3, edx + +%endmacro + +; Basic MOV and XOR Operations for normal rounds + +%macro nr_xor 4 + movzx %4,%2 + xor %1,etab_%3(%4) +%endmacro + +%macro nr_mov 4 + movzx %4,%2 + mov %1,etab_%3(%4) +%endmacro + +; Basic MOV and XOR Operations for last round + +%if 1 + + %macro lr_xor 4 + movzx %4,%2 + movzx %4,etab_b(%4) + %if %3 != 0 + shl %4,8*%3 + %endif + xor %1,%4 + %endmacro + + %macro lr_mov 4 + movzx %4,%2 + movzx %1,etab_b(%4) + %if %3 != 0 + shl %1,8*%3 + %endif + %endmacro + +%else ; less effective but worth leaving as an option + + %macro lr_xor 4 + movzx %4,%2 + mov %4,btab_%3(%4) + and %4,0x000000ff << 8 * %3 + xor %1,%4 + %endmacro + + %macro lr_mov 4 + movzx %4,%2 + mov %1,btab_%3(%4) + and %1,0x000000ff << 8 * %3 + %endmacro + +%endif + +; Apply S-Box to the 4 bytes in a 32-bit word and rotate byte positions + +%ifdef REDUCE_CODE_SIZE + +l3s_col: + movzx ecx,al ; in eax + movzx ecx, etab_b(ecx) ; out eax + xor edx,ecx ; scratch ecx,edx + movzx ecx,ah + movzx ecx, etab_b(ecx) + shl ecx,8 + xor edx,ecx + shr eax,16 + movzx ecx,al + movzx ecx, etab_b(ecx) + shl ecx,16 + xor edx,ecx + movzx ecx,ah + movzx ecx, etab_b(ecx) + shl ecx,24 + xor edx,ecx + mov eax,edx + ret + +%else + +%macro l3s_col 0 + + movzx ecx,al ; in eax + movzx ecx, etab_b(ecx) ; out eax + xor edx,ecx ; scratch ecx,edx + movzx ecx,ah + movzx ecx, etab_b(ecx) + shl ecx,8 + xor edx,ecx + shr eax,16 + movzx ecx,al + movzx ecx, etab_b(ecx) + shl ecx,16 + xor edx,ecx + movzx ecx,ah + movzx ecx, etab_b(ecx) + shl ecx,24 + xor edx,ecx + mov eax,edx + +%endmacro + +%endif + +; offsets to parameters + +in_blk equ 2 ; input byte array address parameter +out_blk equ 4 ; output byte array address parameter +ctx equ 6 ; AES context structure +stk_spc equ 20 ; stack space + +%ifdef ENCRYPTION + +; %define ENCRYPTION_TABLE + +%ifdef REDUCE_CODE_SIZE + +enc_round: + sub sp, 2 + add ebp,16 + save 1,ebp + mov esi,[ebp+8] + mov edi,[ebp+12] + + rnd_fun nr_xor, nr_mov + + mov eax,ebp + mov ecx,esi + mov edx,edi + restore ebp,1 + xor eax,[ebp] + xor ebx,[ebp+4] + add sp, 2 + ret + +%else + +%macro enc_round 0 + + add ebp,16 + save 0,ebp + mov esi,[ebp+8] + mov edi,[ebp+12] + + rnd_fun nr_xor, nr_mov + + mov eax,ebp + mov ecx,esi + mov edx,edi + restore ebp,0 + xor eax,[ebp] + xor ebx,[ebp+4] + +%endmacro + +%endif + +%macro enc_last_round 0 + + add ebp,16 + save 0,ebp + mov esi,[ebp+8] + mov edi,[ebp+12] + + rnd_fun lr_xor, lr_mov + + mov eax,ebp + restore ebp,0 + xor eax,[ebp] + xor ebx,[ebp+4] + +%endmacro + + section _TEXT + +; AES Encryption Subroutine + + do_name _aes_encrypt,12 + + mov ax, sp + movzx esp, ax + + sub esp,stk_spc + mov [esp+16],ebp + mov [esp+12],ebx + mov [esp+ 8],esi + mov [esp+ 4],edi + + movzx esi,word [esp+in_blk+stk_spc] ; input pointer + mov eax,[esi ] + mov ebx,[esi+ 4] + mov ecx,[esi+ 8] + mov edx,[esi+12] + + movzx ebp,word [esp+ctx+stk_spc] ; key pointer + movzx edi,byte [ebp+4*KS_LENGTH] + xor eax,[ebp ] + xor ebx,[ebp+ 4] + xor ecx,[ebp+ 8] + xor edx,[ebp+12] + +; determine the number of rounds + +%ifndef AES_256 + cmp edi,10*16 + je .3 + cmp edi,12*16 + je .2 + cmp edi,14*16 + je .1 + mov eax,-1 + jmp .5 +%endif + +.1: mf_call enc_round + mf_call enc_round +.2: mf_call enc_round + mf_call enc_round +.3: mf_call enc_round + mf_call enc_round + mf_call enc_round + mf_call enc_round + mf_call enc_round + mf_call enc_round + mf_call enc_round + mf_call enc_round + mf_call enc_round + enc_last_round + + movzx edx,word [esp+out_blk+stk_spc] + mov [edx],eax + mov [edx+4],ebx + mov [edx+8],esi + mov [edx+12],edi + xor eax,eax + +.5: mov ebp,[esp+16] + mov ebx,[esp+12] + mov esi,[esp+ 8] + mov edi,[esp+ 4] + add esp,stk_spc + do_exit 12 + +%endif + +%macro f_key 2 + + push ecx + push edx + mov edx,esi + ror eax,8 + mf_call l3s_col + mov esi,eax + pop edx + pop ecx + xor esi,rc_val + + mov [ebp+%1*%2],esi + xor edi,esi + mov [ebp+%1*%2+4],edi + xor ecx,edi + mov [ebp+%1*%2+8],ecx + xor edx,ecx + mov [ebp+%1*%2+12],edx + mov eax,edx + +%if %2 == 24 + +%if %1 < 7 + xor eax,[ebp+%1*%2+16-%2] + mov [ebp+%1*%2+16],eax + xor eax,[ebp+%1*%2+20-%2] + mov [ebp+%1*%2+20],eax +%endif + +%elif %2 == 32 + +%if %1 < 6 + push ecx + push edx + mov edx,[ebp+%1*%2+16-%2] + mf_call l3s_col + pop edx + pop ecx + mov [ebp+%1*%2+16],eax + xor eax,[ebp+%1*%2+20-%2] + mov [ebp+%1*%2+20],eax + xor eax,[ebp+%1*%2+24-%2] + mov [ebp+%1*%2+24],eax + xor eax,[ebp+%1*%2+28-%2] + mov [ebp+%1*%2+28],eax +%endif + +%endif + +%assign rc_val f2(rc_val) + +%endmacro + +%ifdef ENCRYPTION_KEY_SCHEDULE + +%ifdef AES_128 + +%ifndef ENCRYPTION_TABLE +; %define ENCRYPTION_TABLE +%endif + +%assign rc_val 1 + + do_name _aes_encrypt_key128,8 + + push ebp + push ebx + push esi + push edi + + mov ebp,[esp+24] + mov [ebp+4*KS_LENGTH],dword 10*16 + mov ebx,[esp+20] + + mov esi,[ebx] + mov [ebp],esi + mov edi,[ebx+4] + mov [ebp+4],edi + mov ecx,[ebx+8] + mov [ebp+8],ecx + mov edx,[ebx+12] + mov [ebp+12],edx + add ebp,16 + mov eax,edx + + f_key 0,16 ; 11 * 4 = 44 unsigned longs + f_key 1,16 ; 4 + 4 * 10 generated = 44 + f_key 2,16 + f_key 3,16 + f_key 4,16 + f_key 5,16 + f_key 6,16 + f_key 7,16 + f_key 8,16 + f_key 9,16 + + pop edi + pop esi + pop ebx + pop ebp + xor eax,eax + do_exit 8 + +%endif + +%ifdef AES_192 + +%ifndef ENCRYPTION_TABLE +; %define ENCRYPTION_TABLE +%endif + +%assign rc_val 1 + + do_name _aes_encrypt_key192,8 + + push ebp + push ebx + push esi + push edi + + mov ebp,[esp+24] + mov [ebp+4*KS_LENGTH],dword 12 * 16 + mov ebx,[esp+20] + + mov esi,[ebx] + mov [ebp],esi + mov edi,[ebx+4] + mov [ebp+4],edi + mov ecx,[ebx+8] + mov [ebp+8],ecx + mov edx,[ebx+12] + mov [ebp+12],edx + mov eax,[ebx+16] + mov [ebp+16],eax + mov eax,[ebx+20] + mov [ebp+20],eax + add ebp,24 + + f_key 0,24 ; 13 * 4 = 52 unsigned longs + f_key 1,24 ; 6 + 6 * 8 generated = 54 + f_key 2,24 + f_key 3,24 + f_key 4,24 + f_key 5,24 + f_key 6,24 + f_key 7,24 + + pop edi + pop esi + pop ebx + pop ebp + xor eax,eax + do_exit 8 + +%endif + +%ifdef AES_256 + +%ifndef ENCRYPTION_TABLE +; %define ENCRYPTION_TABLE +%endif + +%assign rc_val 1 + + do_name _aes_encrypt_key256,8 + + mov ax, sp + movzx esp, ax + + push ebp + push ebx + push esi + push edi + + movzx ebp, word [esp+20] ; ks + mov [ebp+4*KS_LENGTH],dword 14 * 16 + movzx ebx, word [esp+18] ; key + + mov esi,[ebx] + mov [ebp],esi + mov edi,[ebx+4] + mov [ebp+4],edi + mov ecx,[ebx+8] + mov [ebp+8],ecx + mov edx,[ebx+12] + mov [ebp+12],edx + mov eax,[ebx+16] + mov [ebp+16],eax + mov eax,[ebx+20] + mov [ebp+20],eax + mov eax,[ebx+24] + mov [ebp+24],eax + mov eax,[ebx+28] + mov [ebp+28],eax + add ebp,32 + + f_key 0,32 ; 15 * 4 = 60 unsigned longs + f_key 1,32 ; 8 + 8 * 7 generated = 64 + f_key 2,32 + f_key 3,32 + f_key 4,32 + f_key 5,32 + f_key 6,32 + + pop edi + pop esi + pop ebx + pop ebp + xor eax,eax + do_exit 8 + +%endif + +%ifdef AES_VAR + +%ifndef ENCRYPTION_TABLE +; %define ENCRYPTION_TABLE +%endif + + do_name _aes_encrypt_key,12 + + mov ecx,[esp+4] + mov eax,[esp+8] + mov edx,[esp+12] + push edx + push ecx + + cmp eax,16 + je .1 + cmp eax,128 + je .1 + + cmp eax,24 + je .2 + cmp eax,192 + je .2 + + cmp eax,32 + je .3 + cmp eax,256 + je .3 + mov eax,-1 + add esp,8 + do_exit 12 + +.1: do_call _aes_encrypt_key128,8 + do_exit 12 +.2: do_call _aes_encrypt_key192,8 + do_exit 12 +.3: do_call _aes_encrypt_key256,8 + do_exit 12 + +%endif + +%endif + +%ifdef ENCRYPTION_TABLE + +; S-box data - 256 entries + + section _DATA + +%define u8(x) 0, x, x, f3(x), f2(x), x, x, f3(x) + +_aes_enc_tab: + db u8(0x63),u8(0x7c),u8(0x77),u8(0x7b),u8(0xf2),u8(0x6b),u8(0x6f),u8(0xc5) + db u8(0x30),u8(0x01),u8(0x67),u8(0x2b),u8(0xfe),u8(0xd7),u8(0xab),u8(0x76) + db u8(0xca),u8(0x82),u8(0xc9),u8(0x7d),u8(0xfa),u8(0x59),u8(0x47),u8(0xf0) + db u8(0xad),u8(0xd4),u8(0xa2),u8(0xaf),u8(0x9c),u8(0xa4),u8(0x72),u8(0xc0) + db u8(0xb7),u8(0xfd),u8(0x93),u8(0x26),u8(0x36),u8(0x3f),u8(0xf7),u8(0xcc) + db u8(0x34),u8(0xa5),u8(0xe5),u8(0xf1),u8(0x71),u8(0xd8),u8(0x31),u8(0x15) + db u8(0x04),u8(0xc7),u8(0x23),u8(0xc3),u8(0x18),u8(0x96),u8(0x05),u8(0x9a) + db u8(0x07),u8(0x12),u8(0x80),u8(0xe2),u8(0xeb),u8(0x27),u8(0xb2),u8(0x75) + db u8(0x09),u8(0x83),u8(0x2c),u8(0x1a),u8(0x1b),u8(0x6e),u8(0x5a),u8(0xa0) + db u8(0x52),u8(0x3b),u8(0xd6),u8(0xb3),u8(0x29),u8(0xe3),u8(0x2f),u8(0x84) + db u8(0x53),u8(0xd1),u8(0x00),u8(0xed),u8(0x20),u8(0xfc),u8(0xb1),u8(0x5b) + db u8(0x6a),u8(0xcb),u8(0xbe),u8(0x39),u8(0x4a),u8(0x4c),u8(0x58),u8(0xcf) + db u8(0xd0),u8(0xef),u8(0xaa),u8(0xfb),u8(0x43),u8(0x4d),u8(0x33),u8(0x85) + db u8(0x45),u8(0xf9),u8(0x02),u8(0x7f),u8(0x50),u8(0x3c),u8(0x9f),u8(0xa8) + db u8(0x51),u8(0xa3),u8(0x40),u8(0x8f),u8(0x92),u8(0x9d),u8(0x38),u8(0xf5) + db u8(0xbc),u8(0xb6),u8(0xda),u8(0x21),u8(0x10),u8(0xff),u8(0xf3),u8(0xd2) + db u8(0xcd),u8(0x0c),u8(0x13),u8(0xec),u8(0x5f),u8(0x97),u8(0x44),u8(0x17) + db u8(0xc4),u8(0xa7),u8(0x7e),u8(0x3d),u8(0x64),u8(0x5d),u8(0x19),u8(0x73) + db u8(0x60),u8(0x81),u8(0x4f),u8(0xdc),u8(0x22),u8(0x2a),u8(0x90),u8(0x88) + db u8(0x46),u8(0xee),u8(0xb8),u8(0x14),u8(0xde),u8(0x5e),u8(0x0b),u8(0xdb) + db u8(0xe0),u8(0x32),u8(0x3a),u8(0x0a),u8(0x49),u8(0x06),u8(0x24),u8(0x5c) + db u8(0xc2),u8(0xd3),u8(0xac),u8(0x62),u8(0x91),u8(0x95),u8(0xe4),u8(0x79) + db u8(0xe7),u8(0xc8),u8(0x37),u8(0x6d),u8(0x8d),u8(0xd5),u8(0x4e),u8(0xa9) + db u8(0x6c),u8(0x56),u8(0xf4),u8(0xea),u8(0x65),u8(0x7a),u8(0xae),u8(0x08) + db u8(0xba),u8(0x78),u8(0x25),u8(0x2e),u8(0x1c),u8(0xa6),u8(0xb4),u8(0xc6) + db u8(0xe8),u8(0xdd),u8(0x74),u8(0x1f),u8(0x4b),u8(0xbd),u8(0x8b),u8(0x8a) + db u8(0x70),u8(0x3e),u8(0xb5),u8(0x66),u8(0x48),u8(0x03),u8(0xf6),u8(0x0e) + db u8(0x61),u8(0x35),u8(0x57),u8(0xb9),u8(0x86),u8(0xc1),u8(0x1d),u8(0x9e) + db u8(0xe1),u8(0xf8),u8(0x98),u8(0x11),u8(0x69),u8(0xd9),u8(0x8e),u8(0x94) + db u8(0x9b),u8(0x1e),u8(0x87),u8(0xe9),u8(0xce),u8(0x55),u8(0x28),u8(0xdf) + db u8(0x8c),u8(0xa1),u8(0x89),u8(0x0d),u8(0xbf),u8(0xe6),u8(0x42),u8(0x68) + db u8(0x41),u8(0x99),u8(0x2d),u8(0x0f),u8(0xb0),u8(0x54),u8(0xbb),u8(0x16) + +%endif + +%ifdef DECRYPTION + +; %define DECRYPTION_TABLE + +%define dtab_0(x) [_aes_dec_tab+ 8*x] +%define dtab_1(x) [_aes_dec_tab+3+8*x] +%define dtab_2(x) [_aes_dec_tab+2+8*x] +%define dtab_3(x) [_aes_dec_tab+1+8*x] +%define dtab_x(x) byte [_aes_dec_tab+7+8*x] + +%macro irn_fun 2 + + rol eax,16 + %1 esi, cl, 0, ebp + %1 esi, bh, 1, ebp + %1 esi, al, 2, ebp + %1 edi, dl, 0, ebp + %1 edi, ch, 1, ebp + %1 edi, ah, 3, ebp + %2 ebp, bl, 0, ebp + shr eax,16 + and ebx,0xffff0000 + or ebx,eax + shr ecx,16 + %1 ebp, bh, 1, eax + %1 ebp, ch, 3, eax + %2 eax, cl, 2, ecx + %1 eax, bl, 0, ecx + %1 eax, dh, 1, ecx + shr ebx,16 + shr edx,16 + %1 esi, dh, 3, ecx + %1 ebp, dl, 2, ecx + %1 eax, bh, 3, ecx + %1 edi, bl, 2, ecx + +%endmacro + +; Basic MOV and XOR Operations for normal rounds + +%macro ni_xor 4 + movzx %4,%2 + xor %1,dtab_%3(%4) +%endmacro + +%macro ni_mov 4 + movzx %4,%2 + mov %1,dtab_%3(%4) +%endmacro + +; Basic MOV and XOR Operations for last round + +%macro li_xor 4 + movzx %4,%2 + movzx %4,dtab_x(%4) +%if %3 != 0 + shl %4,8*%3 +%endif + xor %1,%4 +%endmacro + +%macro li_mov 4 + movzx %4,%2 + movzx %1,dtab_x(%4) +%if %3 != 0 + shl %1,8*%3 +%endif +%endmacro + +%ifdef REDUCE_CODE_SIZE + +dec_round: + sub sp, 2 +%ifdef AES_REV_DKS + add ebp,16 +%else + sub ebp,16 +%endif + save 1,ebp + mov esi,[ebp+8] + mov edi,[ebp+12] + + irn_fun ni_xor, ni_mov + + mov ebx,ebp + mov ecx,esi + mov edx,edi + restore ebp,1 + xor eax,[ebp] + xor ebx,[ebp+4] + add sp, 2 + ret + +%else + +%macro dec_round 0 + +%ifdef AES_REV_DKS + add ebp,16 +%else + sub ebp,16 +%endif + save 0,ebp + mov esi,[ebp+8] + mov edi,[ebp+12] + + irn_fun ni_xor, ni_mov + + mov ebx,ebp + mov ecx,esi + mov edx,edi + restore ebp,0 + xor eax,[ebp] + xor ebx,[ebp+4] + +%endmacro + +%endif + +%macro dec_last_round 0 + +%ifdef AES_REV_DKS + add ebp,16 +%else + sub ebp,16 +%endif + save 0,ebp + mov esi,[ebp+8] + mov edi,[ebp+12] + + irn_fun li_xor, li_mov + + mov ebx,ebp + restore ebp,0 + xor eax,[ebp] + xor ebx,[ebp+4] + +%endmacro + + section _TEXT + +; AES Decryption Subroutine + + do_name _aes_decrypt,12 + + mov ax, sp + movzx esp, ax + + sub esp,stk_spc + mov [esp+16],ebp + mov [esp+12],ebx + mov [esp+ 8],esi + mov [esp+ 4],edi + +; input four columns and xor in first round key + + movzx esi,word [esp+in_blk+stk_spc] ; input pointer + mov eax,[esi ] + mov ebx,[esi+ 4] + mov ecx,[esi+ 8] + mov edx,[esi+12] + lea esi,[esi+16] + + movzx ebp, word [esp+ctx+stk_spc] ; key pointer + movzx edi,byte[ebp+4*KS_LENGTH] +%ifndef AES_REV_DKS ; if decryption key schedule is not reversed + lea ebp,[ebp+edi] ; we have to access it from the top down +%endif + xor eax,[ebp ] ; key schedule + xor ebx,[ebp+ 4] + xor ecx,[ebp+ 8] + xor edx,[ebp+12] + +; determine the number of rounds + +%ifndef AES_256 + cmp edi,10*16 + je .3 + cmp edi,12*16 + je .2 + cmp edi,14*16 + je .1 + mov eax,-1 + jmp .5 +%endif + +.1: mf_call dec_round + mf_call dec_round +.2: mf_call dec_round + mf_call dec_round +.3: mf_call dec_round + mf_call dec_round + mf_call dec_round + mf_call dec_round + mf_call dec_round + mf_call dec_round + mf_call dec_round + mf_call dec_round + mf_call dec_round + dec_last_round + +; move final values to the output array. + + movzx ebp,word [esp+out_blk+stk_spc] + mov [ebp],eax + mov [ebp+4],ebx + mov [ebp+8],esi + mov [ebp+12],edi + xor eax,eax + +.5: mov ebp,[esp+16] + mov ebx,[esp+12] + mov esi,[esp+ 8] + mov edi,[esp+ 4] + add esp,stk_spc + do_exit 12 + +%endif + +%ifdef REDUCE_CODE_SIZE + +inv_mix_col: + movzx ecx,dl ; input eax, edx + movzx ecx,etab_b(ecx) ; output eax + mov eax,dtab_0(ecx) ; used ecx + movzx ecx,dh + shr edx,16 + movzx ecx,etab_b(ecx) + xor eax,dtab_1(ecx) + movzx ecx,dl + movzx ecx,etab_b(ecx) + xor eax,dtab_2(ecx) + movzx ecx,dh + movzx ecx,etab_b(ecx) + xor eax,dtab_3(ecx) + ret + +%else + +%macro inv_mix_col 0 + + movzx ecx,dl ; input eax, edx + movzx ecx,etab_b(ecx) ; output eax + mov eax,dtab_0(ecx) ; used ecx + movzx ecx,dh + shr edx,16 + movzx ecx,etab_b(ecx) + xor eax,dtab_1(ecx) + movzx ecx,dl + movzx ecx,etab_b(ecx) + xor eax,dtab_2(ecx) + movzx ecx,dh + movzx ecx,etab_b(ecx) + xor eax,dtab_3(ecx) + +%endmacro + +%endif + +%ifdef DECRYPTION_KEY_SCHEDULE + +%ifdef AES_128 + +%ifndef DECRYPTION_TABLE +; %define DECRYPTION_TABLE +%endif + + do_name _aes_decrypt_key128,8 + + push ebp + push ebx + push esi + push edi + mov eax,[esp+24] ; context + mov edx,[esp+20] ; key + push eax + push edx + do_call _aes_encrypt_key128,8 ; generate expanded encryption key + mov eax,10*16 + mov esi,[esp+24] ; pointer to first round key + lea edi,[esi+eax] ; pointer to last round key + add esi,32 + ; the inverse mix column transformation + mov edx,[esi-16] ; needs to be applied to all round keys + mf_call inv_mix_col ; except first and last. Hence start by + mov [esi-16],eax ; transforming the four sub-keys in the + mov edx,[esi-12] ; second round key + mf_call inv_mix_col + mov [esi-12],eax ; transformations for subsequent rounds + mov edx,[esi-8] ; can then be made more efficient by + mf_call inv_mix_col ; noting that for three of the four sub-keys + mov [esi-8],eax ; in the encryption round key ek[r]: + mov edx,[esi-4] ; + mf_call inv_mix_col ; ek[r][n] = ek[r][n-1] ^ ek[r-1][n] + mov [esi-4],eax ; + ; where n is 1..3. Hence the corresponding +.0: mov edx,[esi] ; subkeys in the decryption round key dk[r] + mf_call inv_mix_col ; also obey since inv_mix_col is linear in + mov [esi],eax ; GF(256): + xor eax,[esi-12] ; + mov [esi+4],eax ; dk[r][n] = dk[r][n-1] ^ dk[r-1][n] + xor eax,[esi-8] ; + mov [esi+8],eax ; So we only need one inverse mix column + xor eax,[esi-4] ; operation (n = 0) for each four word cycle + mov [esi+12],eax ; in the expanded key. + add esi,16 + cmp edi,esi + jg .0 + jmp dec_end + +%endif + +%ifdef AES_192 + +%ifndef DECRYPTION_TABLE +; %define DECRYPTION_TABLE +%endif + + do_name _aes_decrypt_key192,8 + + push ebp + push ebx + push esi + push edi + mov eax,[esp+24] ; context + mov edx,[esp+20] ; key + push eax + push edx + do_call _aes_encrypt_key192,8 ; generate expanded encryption key + mov eax,12*16 + mov esi,[esp+24] ; first round key + lea edi,[esi+eax] ; last round key + add esi,48 ; the first 6 words are the key, of + ; which the top 2 words are part of + mov edx,[esi-32] ; the second round key and hence + mf_call inv_mix_col ; need to be modified. After this we + mov [esi-32],eax ; need to do a further six values prior + mov edx,[esi-28] ; to using a more efficient technique + mf_call inv_mix_col ; based on: + mov [esi-28],eax ; + ; dk[r][n] = dk[r][n-1] ^ dk[r-1][n] + mov edx,[esi-24] ; + mf_call inv_mix_col ; for n = 1 .. 5 where the key expansion + mov [esi-24],eax ; cycle is now 6 words long + mov edx,[esi-20] + mf_call inv_mix_col + mov [esi-20],eax + mov edx,[esi-16] + mf_call inv_mix_col + mov [esi-16],eax + mov edx,[esi-12] + mf_call inv_mix_col + mov [esi-12],eax + mov edx,[esi-8] + mf_call inv_mix_col + mov [esi-8],eax + mov edx,[esi-4] + mf_call inv_mix_col + mov [esi-4],eax + +.0: mov edx,[esi] ; the expanded key is 13 * 4 = 44 32-bit words + mf_call inv_mix_col ; of which 11 * 4 = 44 have to be modified + mov [esi],eax ; using inv_mix_col. We have already done 8 + xor eax,[esi-20] ; of these so 36 are left - hence we need + mov [esi+4],eax ; exactly 6 loops of six here + xor eax,[esi-16] + mov [esi+8],eax + xor eax,[esi-12] + mov [esi+12],eax + xor eax,[esi-8] + mov [esi+16],eax + xor eax,[esi-4] + mov [esi+20],eax + add esi,24 + cmp edi,esi + jg .0 + jmp dec_end + +%endif + +%ifdef AES_256 + +%ifndef DECRYPTION_TABLE +; %define DECRYPTION_TABLE +%endif + + do_name _aes_decrypt_key256,8 + + mov ax, sp + movzx esp, ax + push ebp + push ebx + push esi + push edi + + movzx eax, word [esp+20] ; ks + movzx edx, word [esp+18] ; key + push ax + push dx + do_call _aes_encrypt_key256,4 ; generate expanded encryption key + mov eax,14*16 + movzx esi, word [esp+20] ; ks + lea edi,[esi+eax] + add esi,64 + + mov edx,[esi-48] ; the primary key is 8 words, of which + mf_call inv_mix_col ; the top four require modification + mov [esi-48],eax + mov edx,[esi-44] + mf_call inv_mix_col + mov [esi-44],eax + mov edx,[esi-40] + mf_call inv_mix_col + mov [esi-40],eax + mov edx,[esi-36] + mf_call inv_mix_col + mov [esi-36],eax + + mov edx,[esi-32] ; the encryption key expansion cycle is + mf_call inv_mix_col ; now eight words long so we need to + mov [esi-32],eax ; start by doing one complete block + mov edx,[esi-28] + mf_call inv_mix_col + mov [esi-28],eax + mov edx,[esi-24] + mf_call inv_mix_col + mov [esi-24],eax + mov edx,[esi-20] + mf_call inv_mix_col + mov [esi-20],eax + mov edx,[esi-16] + mf_call inv_mix_col + mov [esi-16],eax + mov edx,[esi-12] + mf_call inv_mix_col + mov [esi-12],eax + mov edx,[esi-8] + mf_call inv_mix_col + mov [esi-8],eax + mov edx,[esi-4] + mf_call inv_mix_col + mov [esi-4],eax + +.0: mov edx,[esi] ; we can now speed up the remaining + mf_call inv_mix_col ; rounds by using the technique + mov [esi],eax ; outlined earlier. But note that + xor eax,[esi-28] ; there is one extra inverse mix + mov [esi+4],eax ; column operation as the 256 bit + xor eax,[esi-24] ; key has an extra non-linear step + mov [esi+8],eax ; for the midway element. + xor eax,[esi-20] + mov [esi+12],eax ; the expanded key is 15 * 4 = 60 + mov edx,[esi+16] ; 32-bit words of which 52 need to + mf_call inv_mix_col ; be modified. We have already done + mov [esi+16],eax ; 12 so 40 are left - which means + xor eax,[esi-12] ; that we need exactly 5 loops of 8 + mov [esi+20],eax + xor eax,[esi-8] + mov [esi+24],eax + xor eax,[esi-4] + mov [esi+28],eax + add esi,32 + cmp edi,esi + jg .0 + +%endif + +dec_end: + +%ifdef AES_REV_DKS + + movzx esi,word [esp+20] ; this reverses the order of the +.1: mov eax,[esi] ; round keys if required + mov ebx,[esi+4] + mov ebp,[edi] + mov edx,[edi+4] + mov [esi],ebp + mov [esi+4],edx + mov [edi],eax + mov [edi+4],ebx + + mov eax,[esi+8] + mov ebx,[esi+12] + mov ebp,[edi+8] + mov edx,[edi+12] + mov [esi+8],ebp + mov [esi+12],edx + mov [edi+8],eax + mov [edi+12],ebx + + add esi,16 + sub edi,16 + cmp edi,esi + jg .1 + +%endif + + pop edi + pop esi + pop ebx + pop ebp + xor eax,eax + do_exit 8 + +%ifdef AES_VAR + + do_name _aes_decrypt_key,12 + + mov ecx,[esp+4] + mov eax,[esp+8] + mov edx,[esp+12] + push edx + push ecx + + cmp eax,16 + je .1 + cmp eax,128 + je .1 + + cmp eax,24 + je .2 + cmp eax,192 + je .2 + + cmp eax,32 + je .3 + cmp eax,256 + je .3 + mov eax,-1 + add esp,8 + do_exit 12 + +.1: do_call _aes_decrypt_key128,8 + do_exit 12 +.2: do_call _aes_decrypt_key192,8 + do_exit 12 +.3: do_call _aes_decrypt_key256,8 + do_exit 12 + +%endif + +%endif + +%ifdef DECRYPTION_TABLE + +; Inverse S-box data - 256 entries + + section _DATA + +%define v8(x) fe(x), f9(x), fd(x), fb(x), fe(x), f9(x), fd(x), x + +_aes_dec_tab: + db v8(0x52),v8(0x09),v8(0x6a),v8(0xd5),v8(0x30),v8(0x36),v8(0xa5),v8(0x38) + db v8(0xbf),v8(0x40),v8(0xa3),v8(0x9e),v8(0x81),v8(0xf3),v8(0xd7),v8(0xfb) + db v8(0x7c),v8(0xe3),v8(0x39),v8(0x82),v8(0x9b),v8(0x2f),v8(0xff),v8(0x87) + db v8(0x34),v8(0x8e),v8(0x43),v8(0x44),v8(0xc4),v8(0xde),v8(0xe9),v8(0xcb) + db v8(0x54),v8(0x7b),v8(0x94),v8(0x32),v8(0xa6),v8(0xc2),v8(0x23),v8(0x3d) + db v8(0xee),v8(0x4c),v8(0x95),v8(0x0b),v8(0x42),v8(0xfa),v8(0xc3),v8(0x4e) + db v8(0x08),v8(0x2e),v8(0xa1),v8(0x66),v8(0x28),v8(0xd9),v8(0x24),v8(0xb2) + db v8(0x76),v8(0x5b),v8(0xa2),v8(0x49),v8(0x6d),v8(0x8b),v8(0xd1),v8(0x25) + db v8(0x72),v8(0xf8),v8(0xf6),v8(0x64),v8(0x86),v8(0x68),v8(0x98),v8(0x16) + db v8(0xd4),v8(0xa4),v8(0x5c),v8(0xcc),v8(0x5d),v8(0x65),v8(0xb6),v8(0x92) + db v8(0x6c),v8(0x70),v8(0x48),v8(0x50),v8(0xfd),v8(0xed),v8(0xb9),v8(0xda) + db v8(0x5e),v8(0x15),v8(0x46),v8(0x57),v8(0xa7),v8(0x8d),v8(0x9d),v8(0x84) + db v8(0x90),v8(0xd8),v8(0xab),v8(0x00),v8(0x8c),v8(0xbc),v8(0xd3),v8(0x0a) + db v8(0xf7),v8(0xe4),v8(0x58),v8(0x05),v8(0xb8),v8(0xb3),v8(0x45),v8(0x06) + db v8(0xd0),v8(0x2c),v8(0x1e),v8(0x8f),v8(0xca),v8(0x3f),v8(0x0f),v8(0x02) + db v8(0xc1),v8(0xaf),v8(0xbd),v8(0x03),v8(0x01),v8(0x13),v8(0x8a),v8(0x6b) + db v8(0x3a),v8(0x91),v8(0x11),v8(0x41),v8(0x4f),v8(0x67),v8(0xdc),v8(0xea) + db v8(0x97),v8(0xf2),v8(0xcf),v8(0xce),v8(0xf0),v8(0xb4),v8(0xe6),v8(0x73) + db v8(0x96),v8(0xac),v8(0x74),v8(0x22),v8(0xe7),v8(0xad),v8(0x35),v8(0x85) + db v8(0xe2),v8(0xf9),v8(0x37),v8(0xe8),v8(0x1c),v8(0x75),v8(0xdf),v8(0x6e) + db v8(0x47),v8(0xf1),v8(0x1a),v8(0x71),v8(0x1d),v8(0x29),v8(0xc5),v8(0x89) + db v8(0x6f),v8(0xb7),v8(0x62),v8(0x0e),v8(0xaa),v8(0x18),v8(0xbe),v8(0x1b) + db v8(0xfc),v8(0x56),v8(0x3e),v8(0x4b),v8(0xc6),v8(0xd2),v8(0x79),v8(0x20) + db v8(0x9a),v8(0xdb),v8(0xc0),v8(0xfe),v8(0x78),v8(0xcd),v8(0x5a),v8(0xf4) + db v8(0x1f),v8(0xdd),v8(0xa8),v8(0x33),v8(0x88),v8(0x07),v8(0xc7),v8(0x31) + db v8(0xb1),v8(0x12),v8(0x10),v8(0x59),v8(0x27),v8(0x80),v8(0xec),v8(0x5f) + db v8(0x60),v8(0x51),v8(0x7f),v8(0xa9),v8(0x19),v8(0xb5),v8(0x4a),v8(0x0d) + db v8(0x2d),v8(0xe5),v8(0x7a),v8(0x9f),v8(0x93),v8(0xc9),v8(0x9c),v8(0xef) + db v8(0xa0),v8(0xe0),v8(0x3b),v8(0x4d),v8(0xae),v8(0x2a),v8(0xf5),v8(0xb0) + db v8(0xc8),v8(0xeb),v8(0xbb),v8(0x3c),v8(0x83),v8(0x53),v8(0x99),v8(0x61) + db v8(0x17),v8(0x2b),v8(0x04),v8(0x7e),v8(0xba),v8(0x77),v8(0xd6),v8(0x26) + db v8(0xe1),v8(0x69),v8(0x14),v8(0x63),v8(0x55),v8(0x21),v8(0x0c),v8(0x7d) + +%endif diff --git a/src/Crypto/Aes_hw_cpu.asm b/src/Crypto/Aes_hw_cpu.asm index 64c3bad8..53852665 100644 --- a/src/Crypto/Aes_hw_cpu.asm +++ b/src/Crypto/Aes_hw_cpu.asm @@ -1,330 +1,330 @@ -; -; Copyright (c) 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. -; - - -%ifidn __BITS__, 16 - %define R e -%elifidn __BITS__, 32 - %define R e -%elifidn __BITS__, 64 - %define R r -%endif - - -%macro export_function 1-2 0 - - %ifdef MS_STDCALL - global %1@%2 - export _%1@%2 - %1@%2: - %elifidn __BITS__, 16 - global _%1 - _%1: - %else - global %1 - %1: - %endif - -%endmacro - - -%macro aes_function_entry 1 - - ; void (const byte *ks, byte *data); - - export_function %1, 8 - - %ifidn __BITS__, 32 - mov ecx, [esp + 4 + 4 * 0] - mov edx, [esp + 4 + 4 * 1] - %elifidn __BITS__, 64 - %ifnidn __OUTPUT_FORMAT__, win64 - mov rcx, rdi - mov rdx, rsi - %endif - %endif - - ; ecx/rcx = ks - ; edx/rdx = data - -%endmacro - - -%macro aes_function_exit 0 - - ; void (const byte *, byte *); - - %ifdef MS_STDCALL - ret 8 - %else - ret - %endif - -%endmacro - - -%macro push_xmm 2 - sub rsp, 16 * (%2 - %1 + 1) - - %assign stackoffset 0 - %assign regnumber %1 - - %rep (%2 - %1 + 1) - movdqu [rsp + 16 * stackoffset], xmm%[regnumber] - - %assign stackoffset stackoffset+1 - %assign regnumber regnumber+1 - %endrep -%endmacro - - -%macro pop_xmm 2 - %assign stackoffset 0 - %assign regnumber %1 - - %rep (%2 - %1 + 1) - movdqu xmm%[regnumber], [rsp + 16 * stackoffset] - - %assign stackoffset stackoffset+1 - %assign regnumber regnumber+1 - %endrep - - add rsp, 16 * (%2 - %1 + 1) -%endmacro - - -%macro aes_hw_cpu 2 - %define OPERATION %1 - %define BLOCK_COUNT %2 - - ; Load data blocks - %assign block 1 - %rep BLOCK_COUNT - movdqu xmm%[block], [%[R]dx + 16 * (block - 1)] - %assign block block+1 - %endrep - - ; Encrypt/decrypt data blocks - %assign round 0 - %rep 15 - movdqu xmm0, [%[R]cx + 16 * round] - - %assign block 1 - %rep BLOCK_COUNT - - %if round = 0 - pxor xmm%[block], xmm0 - %else - %if round < 14 - aes%[OPERATION] xmm%[block], xmm0 - %else - aes%[OPERATION]last xmm%[block], xmm0 - %endif - %endif - - %assign block block+1 - %endrep - - %assign round round+1 - %endrep - - ; Store data blocks - %assign block 1 - %rep BLOCK_COUNT - movdqu [%[R]dx + 16 * (block - 1)], xmm%[block] - %assign block block+1 - %endrep - - %undef OPERATION - %undef BLOCK_COUNT -%endmacro - - -%macro aes_hw_cpu_32_blocks 1 - %define OPERATION_32_BLOCKS %1 - - %ifidn __BITS__, 64 - %define MAX_REG_BLOCK_COUNT 15 - %else - %define MAX_REG_BLOCK_COUNT 7 - %endif - - %ifidn __OUTPUT_FORMAT__, win64 - %if MAX_REG_BLOCK_COUNT > 5 - push_xmm 6, MAX_REG_BLOCK_COUNT - %endif - %endif - - mov eax, 32 / MAX_REG_BLOCK_COUNT - .1: - aes_hw_cpu %[OPERATION_32_BLOCKS], MAX_REG_BLOCK_COUNT - - add %[R]dx, 16 * MAX_REG_BLOCK_COUNT - dec eax - jnz .1 - - %if (32 % MAX_REG_BLOCK_COUNT) != 0 - aes_hw_cpu %[OPERATION_32_BLOCKS], (32 % MAX_REG_BLOCK_COUNT) - %endif - - %ifidn __OUTPUT_FORMAT__, win64 - %if MAX_REG_BLOCK_COUNT > 5 - pop_xmm 6, MAX_REG_BLOCK_COUNT - %endif - %endif - - %undef OPERATION_32_BLOCKS - %undef MAX_REG_BLOCK_COUNT -%endmacro - - -%ifidn __BITS__, 16 - - USE16 - SEGMENT _TEXT PUBLIC CLASS=CODE USE16 - SEGMENT _DATA PUBLIC CLASS=DATA USE16 - GROUP DGROUP _TEXT _DATA - SECTION _TEXT - -%else - - SECTION .text - -%endif - - -; void aes_hw_cpu_enable_sse (); - - export_function aes_hw_cpu_enable_sse - mov %[R]ax, cr4 - or ax, 1 << 9 - mov cr4, %[R]ax - ret - - -%ifidn __BITS__, 16 - - -; byte is_aes_hw_cpu_supported (); - - export_function is_aes_hw_cpu_supported - mov eax, 1 - cpuid - mov eax, ecx - shr eax, 25 - and al, 1 - ret - - -; void aes_hw_cpu_decrypt (const byte *ks, byte *data); - - export_function aes_hw_cpu_decrypt - mov ax, -16 - jmp aes_hw_cpu_encrypt_decrypt - -; void aes_hw_cpu_encrypt (const byte *ks, byte *data); - - export_function aes_hw_cpu_encrypt - mov ax, 16 - - aes_hw_cpu_encrypt_decrypt: - push bp - mov bp, sp - push di - push si - - mov si, [bp + 4] ; ks - mov di, [bp + 4 + 2] ; data - - movdqu xmm0, [si] - movdqu xmm1, [di] - - pxor xmm1, xmm0 - - mov cx, 13 - - .round1_13: - add si, ax - movdqu xmm0, [si] - - cmp ax, 0 - jl .decrypt - - aesenc xmm1, xmm0 - jmp .2 - .decrypt: - aesdec xmm1, xmm0 - .2: - loop .round1_13 - - add si, ax - movdqu xmm0, [si] - - cmp ax, 0 - jl .decrypt_last - - aesenclast xmm1, xmm0 - jmp .3 - .decrypt_last: - aesdeclast xmm1, xmm0 - .3: - movdqu [di], xmm1 - - pop si - pop di - pop bp - ret - - -%else ; __BITS__ != 16 - - -; byte is_aes_hw_cpu_supported (); - - export_function is_aes_hw_cpu_supported - push %[R]bx - - mov eax, 1 - cpuid - mov eax, ecx - shr eax, 25 - and eax, 1 - - pop %[R]bx - ret - - -; void aes_hw_cpu_decrypt (const byte *ks, byte *data); - - aes_function_entry aes_hw_cpu_decrypt - aes_hw_cpu dec, 1 - aes_function_exit - - -; void aes_hw_cpu_decrypt_32_blocks (const byte *ks, byte *data); - - aes_function_entry aes_hw_cpu_decrypt_32_blocks - aes_hw_cpu_32_blocks dec - aes_function_exit - - -; void aes_hw_cpu_encrypt (const byte *ks, byte *data); - - aes_function_entry aes_hw_cpu_encrypt - aes_hw_cpu enc, 1 - aes_function_exit - - -; void aes_hw_cpu_encrypt_32_blocks (const byte *ks, byte *data); - - aes_function_entry aes_hw_cpu_encrypt_32_blocks - aes_hw_cpu_32_blocks enc - aes_function_exit - - -%endif ; __BITS__ != 16 +; +; Copyright (c) 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. +; + + +%ifidn __BITS__, 16 + %define R e +%elifidn __BITS__, 32 + %define R e +%elifidn __BITS__, 64 + %define R r +%endif + + +%macro export_function 1-2 0 + + %ifdef MS_STDCALL + global %1@%2 + export _%1@%2 + %1@%2: + %elifidn __BITS__, 16 + global _%1 + _%1: + %else + global %1 + %1: + %endif + +%endmacro + + +%macro aes_function_entry 1 + + ; void (const byte *ks, byte *data); + + export_function %1, 8 + + %ifidn __BITS__, 32 + mov ecx, [esp + 4 + 4 * 0] + mov edx, [esp + 4 + 4 * 1] + %elifidn __BITS__, 64 + %ifnidn __OUTPUT_FORMAT__, win64 + mov rcx, rdi + mov rdx, rsi + %endif + %endif + + ; ecx/rcx = ks + ; edx/rdx = data + +%endmacro + + +%macro aes_function_exit 0 + + ; void (const byte *, byte *); + + %ifdef MS_STDCALL + ret 8 + %else + ret + %endif + +%endmacro + + +%macro push_xmm 2 + sub rsp, 16 * (%2 - %1 + 1) + + %assign stackoffset 0 + %assign regnumber %1 + + %rep (%2 - %1 + 1) + movdqu [rsp + 16 * stackoffset], xmm%[regnumber] + + %assign stackoffset stackoffset+1 + %assign regnumber regnumber+1 + %endrep +%endmacro + + +%macro pop_xmm 2 + %assign stackoffset 0 + %assign regnumber %1 + + %rep (%2 - %1 + 1) + movdqu xmm%[regnumber], [rsp + 16 * stackoffset] + + %assign stackoffset stackoffset+1 + %assign regnumber regnumber+1 + %endrep + + add rsp, 16 * (%2 - %1 + 1) +%endmacro + + +%macro aes_hw_cpu 2 + %define OPERATION %1 + %define BLOCK_COUNT %2 + + ; Load data blocks + %assign block 1 + %rep BLOCK_COUNT + movdqu xmm%[block], [%[R]dx + 16 * (block - 1)] + %assign block block+1 + %endrep + + ; Encrypt/decrypt data blocks + %assign round 0 + %rep 15 + movdqu xmm0, [%[R]cx + 16 * round] + + %assign block 1 + %rep BLOCK_COUNT + + %if round = 0 + pxor xmm%[block], xmm0 + %else + %if round < 14 + aes%[OPERATION] xmm%[block], xmm0 + %else + aes%[OPERATION]last xmm%[block], xmm0 + %endif + %endif + + %assign block block+1 + %endrep + + %assign round round+1 + %endrep + + ; Store data blocks + %assign block 1 + %rep BLOCK_COUNT + movdqu [%[R]dx + 16 * (block - 1)], xmm%[block] + %assign block block+1 + %endrep + + %undef OPERATION + %undef BLOCK_COUNT +%endmacro + + +%macro aes_hw_cpu_32_blocks 1 + %define OPERATION_32_BLOCKS %1 + + %ifidn __BITS__, 64 + %define MAX_REG_BLOCK_COUNT 15 + %else + %define MAX_REG_BLOCK_COUNT 7 + %endif + + %ifidn __OUTPUT_FORMAT__, win64 + %if MAX_REG_BLOCK_COUNT > 5 + push_xmm 6, MAX_REG_BLOCK_COUNT + %endif + %endif + + mov eax, 32 / MAX_REG_BLOCK_COUNT + .1: + aes_hw_cpu %[OPERATION_32_BLOCKS], MAX_REG_BLOCK_COUNT + + add %[R]dx, 16 * MAX_REG_BLOCK_COUNT + dec eax + jnz .1 + + %if (32 % MAX_REG_BLOCK_COUNT) != 0 + aes_hw_cpu %[OPERATION_32_BLOCKS], (32 % MAX_REG_BLOCK_COUNT) + %endif + + %ifidn __OUTPUT_FORMAT__, win64 + %if MAX_REG_BLOCK_COUNT > 5 + pop_xmm 6, MAX_REG_BLOCK_COUNT + %endif + %endif + + %undef OPERATION_32_BLOCKS + %undef MAX_REG_BLOCK_COUNT +%endmacro + + +%ifidn __BITS__, 16 + + USE16 + SEGMENT _TEXT PUBLIC CLASS=CODE USE16 + SEGMENT _DATA PUBLIC CLASS=DATA USE16 + GROUP DGROUP _TEXT _DATA + SECTION _TEXT + +%else + + SECTION .text + +%endif + + +; void aes_hw_cpu_enable_sse (); + + export_function aes_hw_cpu_enable_sse + mov %[R]ax, cr4 + or ax, 1 << 9 + mov cr4, %[R]ax + ret + + +%ifidn __BITS__, 16 + + +; byte is_aes_hw_cpu_supported (); + + export_function is_aes_hw_cpu_supported + mov eax, 1 + cpuid + mov eax, ecx + shr eax, 25 + and al, 1 + ret + + +; void aes_hw_cpu_decrypt (const byte *ks, byte *data); + + export_function aes_hw_cpu_decrypt + mov ax, -16 + jmp aes_hw_cpu_encrypt_decrypt + +; void aes_hw_cpu_encrypt (const byte *ks, byte *data); + + export_function aes_hw_cpu_encrypt + mov ax, 16 + + aes_hw_cpu_encrypt_decrypt: + push bp + mov bp, sp + push di + push si + + mov si, [bp + 4] ; ks + mov di, [bp + 4 + 2] ; data + + movdqu xmm0, [si] + movdqu xmm1, [di] + + pxor xmm1, xmm0 + + mov cx, 13 + + .round1_13: + add si, ax + movdqu xmm0, [si] + + cmp ax, 0 + jl .decrypt + + aesenc xmm1, xmm0 + jmp .2 + .decrypt: + aesdec xmm1, xmm0 + .2: + loop .round1_13 + + add si, ax + movdqu xmm0, [si] + + cmp ax, 0 + jl .decrypt_last + + aesenclast xmm1, xmm0 + jmp .3 + .decrypt_last: + aesdeclast xmm1, xmm0 + .3: + movdqu [di], xmm1 + + pop si + pop di + pop bp + ret + + +%else ; __BITS__ != 16 + + +; byte is_aes_hw_cpu_supported (); + + export_function is_aes_hw_cpu_supported + push %[R]bx + + mov eax, 1 + cpuid + mov eax, ecx + shr eax, 25 + and eax, 1 + + pop %[R]bx + ret + + +; void aes_hw_cpu_decrypt (const byte *ks, byte *data); + + aes_function_entry aes_hw_cpu_decrypt + aes_hw_cpu dec, 1 + aes_function_exit + + +; void aes_hw_cpu_decrypt_32_blocks (const byte *ks, byte *data); + + aes_function_entry aes_hw_cpu_decrypt_32_blocks + aes_hw_cpu_32_blocks dec + aes_function_exit + + +; void aes_hw_cpu_encrypt (const byte *ks, byte *data); + + aes_function_entry aes_hw_cpu_encrypt + aes_hw_cpu enc, 1 + aes_function_exit + + +; void aes_hw_cpu_encrypt_32_blocks (const byte *ks, byte *data); + + aes_function_entry aes_hw_cpu_encrypt_32_blocks + aes_hw_cpu_32_blocks enc + aes_function_exit + + +%endif ; __BITS__ != 16 diff --git a/src/Crypto/Aes_hw_cpu.h b/src/Crypto/Aes_hw_cpu.h index 2342b4c5..e2fed1a1 100644 --- a/src/Crypto/Aes_hw_cpu.h +++ b/src/Crypto/Aes_hw_cpu.h @@ -8,27 +8,27 @@ 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_Crypto_Aes_Hw_Cpu -#define TC_HEADER_Crypto_Aes_Hw_Cpu - -#include "Common/Tcdefs.h" - -#if defined(__cplusplus) -extern "C" -{ -#endif - -byte is_aes_hw_cpu_supported (); -void aes_hw_cpu_enable_sse (); -void aes_hw_cpu_decrypt (const byte *ks, byte *data); -void aes_hw_cpu_decrypt_32_blocks (const byte *ks, byte *data); -void aes_hw_cpu_encrypt (const byte *ks, byte *data); -void aes_hw_cpu_encrypt_32_blocks (const byte *ks, byte *data); - -#if defined(__cplusplus) -} -#endif - -#endif // TC_HEADER_Crypto_Aes_Hw_Cpu +*/ + +#ifndef TC_HEADER_Crypto_Aes_Hw_Cpu +#define TC_HEADER_Crypto_Aes_Hw_Cpu + +#include "Common/Tcdefs.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif + +byte is_aes_hw_cpu_supported (); +void aes_hw_cpu_enable_sse (); +void aes_hw_cpu_decrypt (const byte *ks, byte *data); +void aes_hw_cpu_decrypt_32_blocks (const byte *ks, byte *data); +void aes_hw_cpu_encrypt (const byte *ks, byte *data); +void aes_hw_cpu_encrypt_32_blocks (const byte *ks, byte *data); + +#if defined(__cplusplus) +} +#endif + +#endif // TC_HEADER_Crypto_Aes_Hw_Cpu diff --git a/src/Crypto/Aes_x64.asm b/src/Crypto/Aes_x64.asm index b29fdcac..06d57ac2 100644 --- a/src/Crypto/Aes_x64.asm +++ b/src/Crypto/Aes_x64.asm @@ -1,907 +1,907 @@ - -; --------------------------------------------------------------------------- -; Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. -; -; LICENSE TERMS -; -; The free distribution and use of this software is allowed (with or without -; changes) provided that: -; -; 1. source code distributions include the above copyright notice, this -; list of conditions and the following disclaimer; -; -; 2. binary distributions include the above copyright notice, this list -; of conditions and the following disclaimer in their documentation; -; -; 3. the name of the copyright holder is not used to endorse products -; built using this software without specific written permission. -; -; DISCLAIMER -; -; This software is provided 'as is' with no explicit or implied warranties -; in respect of its properties, including, but not limited to, correctness -; and/or fitness for purpose. -; --------------------------------------------------------------------------- -; Issue 20/12/2007 -; -; I am grateful to Dag Arne Osvik for many discussions of the techniques that -; can be used to optimise AES assembler code on AMD64/EM64T architectures. -; Some of the techniques used in this implementation are the result of -; suggestions made by him for which I am most grateful. - -; -; Adapted for TrueCrypt: -; - Compatibility with NASM -; - -; An AES implementation for AMD64 processors using the YASM assembler. This -; implemetation provides only encryption, decryption and hence requires key -; scheduling support in C. It uses 8k bytes of tables but its encryption and -; decryption performance is very close to that obtained using large tables. -; It can use either Windows or Gnu/Linux calling conventions, which are as -; follows: -; windows gnu/linux -; -; in_blk rcx rdi -; out_blk rdx rsi -; context (cx) r8 rdx -; -; preserved rsi - + rbx, rbp, rsp, r12, r13, r14 & r15 -; registers rdi - on both -; -; destroyed - rsi + rax, rcx, rdx, r8, r9, r10 & r11 -; registers - rdi on both -; -; The default convention is that for windows, the gnu/linux convention being -; used if __GNUC__ is defined. -; -; Define _SEH_ to include support for Win64 structured exception handling -; (this requires YASM version 0.6 or later). -; -; This code provides the standard AES block size (128 bits, 16 bytes) and the -; three standard AES key sizes (128, 192 and 256 bits). It has the same call -; interface as my C implementation. It uses the Microsoft C AMD64 calling -; conventions in which the three parameters are placed in rcx, rdx and r8 -; respectively. The rbx, rsi, rdi, rbp and r12..r15 registers are preserved. -; -; AES_RETURN aes_encrypt(const unsigned char in_blk[], -; unsigned char out_blk[], const aes_encrypt_ctx cx[1]); -; -; AES_RETURN aes_decrypt(const unsigned char in_blk[], -; unsigned char out_blk[], const aes_decrypt_ctx cx[1]); -; -; AES_RETURN aes_encrypt_key(const unsigned char key[], -; const aes_encrypt_ctx cx[1]); -; -; AES_RETURN aes_decrypt_key(const unsigned char key[], -; const aes_decrypt_ctx cx[1]); -; -; AES_RETURN aes_encrypt_key(const unsigned char key[], -; unsigned int len, const aes_decrypt_ctx cx[1]); -; -; AES_RETURN aes_decrypt_key(const unsigned char key[], -; unsigned int len, const aes_decrypt_ctx cx[1]); -; -; where is 128, 102 or 256. In the last two calls the length can be in -; either bits or bytes. -; -; Comment in/out the following lines to obtain the desired subroutines. These -; selections MUST match those in the C header file aes.h - -; %define AES_128 ; define if AES with 128 bit keys is needed -; %define AES_192 ; define if AES with 192 bit keys is needed -%define AES_256 ; define if AES with 256 bit keys is needed -; %define AES_VAR ; define if a variable key size is needed -%define ENCRYPTION ; define if encryption is needed -%define DECRYPTION ; define if decryption is needed -%define AES_REV_DKS ; define if key decryption schedule is reversed -%define LAST_ROUND_TABLES ; define for the faster version using extra tables - -; The encryption key schedule has the following in memory layout where N is the -; number of rounds (10, 12 or 14): -; -; lo: | input key (round 0) | ; each round is four 32-bit words -; | encryption round 1 | -; | encryption round 2 | -; .... -; | encryption round N-1 | -; hi: | encryption round N | -; -; The decryption key schedule is normally set up so that it has the same -; layout as above by actually reversing the order of the encryption key -; schedule in memory (this happens when AES_REV_DKS is set): -; -; lo: | decryption round 0 | = | encryption round N | -; | decryption round 1 | = INV_MIX_COL[ | encryption round N-1 | ] -; | decryption round 2 | = INV_MIX_COL[ | encryption round N-2 | ] -; .... .... -; | decryption round N-1 | = INV_MIX_COL[ | encryption round 1 | ] -; hi: | decryption round N | = | input key (round 0) | -; -; with rounds except the first and last modified using inv_mix_column() -; But if AES_REV_DKS is NOT set the order of keys is left as it is for -; encryption so that it has to be accessed in reverse when used for -; decryption (although the inverse mix column modifications are done) -; -; lo: | decryption round 0 | = | input key (round 0) | -; | decryption round 1 | = INV_MIX_COL[ | encryption round 1 | ] -; | decryption round 2 | = INV_MIX_COL[ | encryption round 2 | ] -; .... .... -; | decryption round N-1 | = INV_MIX_COL[ | encryption round N-1 | ] -; hi: | decryption round N | = | encryption round N | -; -; This layout is faster when the assembler key scheduling provided here -; is used. -; -; The DLL interface must use the _stdcall convention in which the number -; of bytes of parameter space is added after an @ to the sutine's name. -; We must also remove our parameters from the stack before return (see -; the do_exit macro). Define DLL_EXPORT for the Dynamic Link Library version. - -;%define DLL_EXPORT - -; End of user defines - -%ifdef AES_VAR -%ifndef AES_128 -%define AES_128 -%endif -%ifndef AES_192 -%define AES_192 -%endif -%ifndef AES_256 -%define AES_256 -%endif -%endif - -%ifdef AES_VAR -%define KS_LENGTH 60 -%elifdef AES_256 -%define KS_LENGTH 60 -%elifdef AES_192 -%define KS_LENGTH 52 -%else -%define KS_LENGTH 44 -%endif - -%define r0 rax -%define r1 rdx -%define r2 rcx -%define r3 rbx -%define r4 rsi -%define r5 rdi -%define r6 rbp -%define r7 rsp - -%define raxd eax -%define rdxd edx -%define rcxd ecx -%define rbxd ebx -%define rsid esi -%define rdid edi -%define rbpd ebp -%define rspd esp - -%define raxb al -%define rdxb dl -%define rcxb cl -%define rbxb bl -%define rsib sil -%define rdib dil -%define rbpb bpl -%define rspb spl - -%define r0h ah -%define r1h dh -%define r2h ch -%define r3h bh - -%define r0d eax -%define r1d edx -%define r2d ecx -%define r3d ebx - -; finite field multiplies by {02}, {04} and {08} - -%define f2(x) ((x<<1)^(((x>>7)&1)*0x11b)) -%define f4(x) ((x<<2)^(((x>>6)&1)*0x11b)^(((x>>6)&2)*0x11b)) -%define f8(x) ((x<<3)^(((x>>5)&1)*0x11b)^(((x>>5)&2)*0x11b)^(((x>>5)&4)*0x11b)) - -; finite field multiplies required in table generation - -%define f3(x) (f2(x) ^ x) -%define f9(x) (f8(x) ^ x) -%define fb(x) (f8(x) ^ f2(x) ^ x) -%define fd(x) (f8(x) ^ f4(x) ^ x) -%define fe(x) (f8(x) ^ f4(x) ^ f2(x)) - -; macro for expanding S-box data - -%macro enc_vals 1 - db %1(0x63),%1(0x7c),%1(0x77),%1(0x7b),%1(0xf2),%1(0x6b),%1(0x6f),%1(0xc5) - db %1(0x30),%1(0x01),%1(0x67),%1(0x2b),%1(0xfe),%1(0xd7),%1(0xab),%1(0x76) - db %1(0xca),%1(0x82),%1(0xc9),%1(0x7d),%1(0xfa),%1(0x59),%1(0x47),%1(0xf0) - db %1(0xad),%1(0xd4),%1(0xa2),%1(0xaf),%1(0x9c),%1(0xa4),%1(0x72),%1(0xc0) - db %1(0xb7),%1(0xfd),%1(0x93),%1(0x26),%1(0x36),%1(0x3f),%1(0xf7),%1(0xcc) - db %1(0x34),%1(0xa5),%1(0xe5),%1(0xf1),%1(0x71),%1(0xd8),%1(0x31),%1(0x15) - db %1(0x04),%1(0xc7),%1(0x23),%1(0xc3),%1(0x18),%1(0x96),%1(0x05),%1(0x9a) - db %1(0x07),%1(0x12),%1(0x80),%1(0xe2),%1(0xeb),%1(0x27),%1(0xb2),%1(0x75) - db %1(0x09),%1(0x83),%1(0x2c),%1(0x1a),%1(0x1b),%1(0x6e),%1(0x5a),%1(0xa0) - db %1(0x52),%1(0x3b),%1(0xd6),%1(0xb3),%1(0x29),%1(0xe3),%1(0x2f),%1(0x84) - db %1(0x53),%1(0xd1),%1(0x00),%1(0xed),%1(0x20),%1(0xfc),%1(0xb1),%1(0x5b) - db %1(0x6a),%1(0xcb),%1(0xbe),%1(0x39),%1(0x4a),%1(0x4c),%1(0x58),%1(0xcf) - db %1(0xd0),%1(0xef),%1(0xaa),%1(0xfb),%1(0x43),%1(0x4d),%1(0x33),%1(0x85) - db %1(0x45),%1(0xf9),%1(0x02),%1(0x7f),%1(0x50),%1(0x3c),%1(0x9f),%1(0xa8) - db %1(0x51),%1(0xa3),%1(0x40),%1(0x8f),%1(0x92),%1(0x9d),%1(0x38),%1(0xf5) - db %1(0xbc),%1(0xb6),%1(0xda),%1(0x21),%1(0x10),%1(0xff),%1(0xf3),%1(0xd2) - db %1(0xcd),%1(0x0c),%1(0x13),%1(0xec),%1(0x5f),%1(0x97),%1(0x44),%1(0x17) - db %1(0xc4),%1(0xa7),%1(0x7e),%1(0x3d),%1(0x64),%1(0x5d),%1(0x19),%1(0x73) - db %1(0x60),%1(0x81),%1(0x4f),%1(0xdc),%1(0x22),%1(0x2a),%1(0x90),%1(0x88) - db %1(0x46),%1(0xee),%1(0xb8),%1(0x14),%1(0xde),%1(0x5e),%1(0x0b),%1(0xdb) - db %1(0xe0),%1(0x32),%1(0x3a),%1(0x0a),%1(0x49),%1(0x06),%1(0x24),%1(0x5c) - db %1(0xc2),%1(0xd3),%1(0xac),%1(0x62),%1(0x91),%1(0x95),%1(0xe4),%1(0x79) - db %1(0xe7),%1(0xc8),%1(0x37),%1(0x6d),%1(0x8d),%1(0xd5),%1(0x4e),%1(0xa9) - db %1(0x6c),%1(0x56),%1(0xf4),%1(0xea),%1(0x65),%1(0x7a),%1(0xae),%1(0x08) - db %1(0xba),%1(0x78),%1(0x25),%1(0x2e),%1(0x1c),%1(0xa6),%1(0xb4),%1(0xc6) - db %1(0xe8),%1(0xdd),%1(0x74),%1(0x1f),%1(0x4b),%1(0xbd),%1(0x8b),%1(0x8a) - db %1(0x70),%1(0x3e),%1(0xb5),%1(0x66),%1(0x48),%1(0x03),%1(0xf6),%1(0x0e) - db %1(0x61),%1(0x35),%1(0x57),%1(0xb9),%1(0x86),%1(0xc1),%1(0x1d),%1(0x9e) - db %1(0xe1),%1(0xf8),%1(0x98),%1(0x11),%1(0x69),%1(0xd9),%1(0x8e),%1(0x94) - db %1(0x9b),%1(0x1e),%1(0x87),%1(0xe9),%1(0xce),%1(0x55),%1(0x28),%1(0xdf) - db %1(0x8c),%1(0xa1),%1(0x89),%1(0x0d),%1(0xbf),%1(0xe6),%1(0x42),%1(0x68) - db %1(0x41),%1(0x99),%1(0x2d),%1(0x0f),%1(0xb0),%1(0x54),%1(0xbb),%1(0x16) -%endmacro - -%macro dec_vals 1 - db %1(0x52),%1(0x09),%1(0x6a),%1(0xd5),%1(0x30),%1(0x36),%1(0xa5),%1(0x38) - db %1(0xbf),%1(0x40),%1(0xa3),%1(0x9e),%1(0x81),%1(0xf3),%1(0xd7),%1(0xfb) - db %1(0x7c),%1(0xe3),%1(0x39),%1(0x82),%1(0x9b),%1(0x2f),%1(0xff),%1(0x87) - db %1(0x34),%1(0x8e),%1(0x43),%1(0x44),%1(0xc4),%1(0xde),%1(0xe9),%1(0xcb) - db %1(0x54),%1(0x7b),%1(0x94),%1(0x32),%1(0xa6),%1(0xc2),%1(0x23),%1(0x3d) - db %1(0xee),%1(0x4c),%1(0x95),%1(0x0b),%1(0x42),%1(0xfa),%1(0xc3),%1(0x4e) - db %1(0x08),%1(0x2e),%1(0xa1),%1(0x66),%1(0x28),%1(0xd9),%1(0x24),%1(0xb2) - db %1(0x76),%1(0x5b),%1(0xa2),%1(0x49),%1(0x6d),%1(0x8b),%1(0xd1),%1(0x25) - db %1(0x72),%1(0xf8),%1(0xf6),%1(0x64),%1(0x86),%1(0x68),%1(0x98),%1(0x16) - db %1(0xd4),%1(0xa4),%1(0x5c),%1(0xcc),%1(0x5d),%1(0x65),%1(0xb6),%1(0x92) - db %1(0x6c),%1(0x70),%1(0x48),%1(0x50),%1(0xfd),%1(0xed),%1(0xb9),%1(0xda) - db %1(0x5e),%1(0x15),%1(0x46),%1(0x57),%1(0xa7),%1(0x8d),%1(0x9d),%1(0x84) - db %1(0x90),%1(0xd8),%1(0xab),%1(0x00),%1(0x8c),%1(0xbc),%1(0xd3),%1(0x0a) - db %1(0xf7),%1(0xe4),%1(0x58),%1(0x05),%1(0xb8),%1(0xb3),%1(0x45),%1(0x06) - db %1(0xd0),%1(0x2c),%1(0x1e),%1(0x8f),%1(0xca),%1(0x3f),%1(0x0f),%1(0x02) - db %1(0xc1),%1(0xaf),%1(0xbd),%1(0x03),%1(0x01),%1(0x13),%1(0x8a),%1(0x6b) - db %1(0x3a),%1(0x91),%1(0x11),%1(0x41),%1(0x4f),%1(0x67),%1(0xdc),%1(0xea) - db %1(0x97),%1(0xf2),%1(0xcf),%1(0xce),%1(0xf0),%1(0xb4),%1(0xe6),%1(0x73) - db %1(0x96),%1(0xac),%1(0x74),%1(0x22),%1(0xe7),%1(0xad),%1(0x35),%1(0x85) - db %1(0xe2),%1(0xf9),%1(0x37),%1(0xe8),%1(0x1c),%1(0x75),%1(0xdf),%1(0x6e) - db %1(0x47),%1(0xf1),%1(0x1a),%1(0x71),%1(0x1d),%1(0x29),%1(0xc5),%1(0x89) - db %1(0x6f),%1(0xb7),%1(0x62),%1(0x0e),%1(0xaa),%1(0x18),%1(0xbe),%1(0x1b) - db %1(0xfc),%1(0x56),%1(0x3e),%1(0x4b),%1(0xc6),%1(0xd2),%1(0x79),%1(0x20) - db %1(0x9a),%1(0xdb),%1(0xc0),%1(0xfe),%1(0x78),%1(0xcd),%1(0x5a),%1(0xf4) - db %1(0x1f),%1(0xdd),%1(0xa8),%1(0x33),%1(0x88),%1(0x07),%1(0xc7),%1(0x31) - db %1(0xb1),%1(0x12),%1(0x10),%1(0x59),%1(0x27),%1(0x80),%1(0xec),%1(0x5f) - db %1(0x60),%1(0x51),%1(0x7f),%1(0xa9),%1(0x19),%1(0xb5),%1(0x4a),%1(0x0d) - db %1(0x2d),%1(0xe5),%1(0x7a),%1(0x9f),%1(0x93),%1(0xc9),%1(0x9c),%1(0xef) - db %1(0xa0),%1(0xe0),%1(0x3b),%1(0x4d),%1(0xae),%1(0x2a),%1(0xf5),%1(0xb0) - db %1(0xc8),%1(0xeb),%1(0xbb),%1(0x3c),%1(0x83),%1(0x53),%1(0x99),%1(0x61) - db %1(0x17),%1(0x2b),%1(0x04),%1(0x7e),%1(0xba),%1(0x77),%1(0xd6),%1(0x26) - db %1(0xe1),%1(0x69),%1(0x14),%1(0x63),%1(0x55),%1(0x21),%1(0x0c),%1(0x7d) -%endmacro - -%define u8(x) f2(x), x, x, f3(x), f2(x), x, x, f3(x) -%define v8(x) fe(x), f9(x), fd(x), fb(x), fe(x), f9(x), fd(x), x -%define w8(x) x, 0, 0, 0, x, 0, 0, 0 - -%define tptr rbp ; table pointer -%define kptr r8 ; key schedule pointer -%define fofs 128 ; adjust offset in key schedule to keep |disp| < 128 -%define fk_ref(x,y) [kptr-16*x+fofs+4*y] -%ifdef AES_REV_DKS -%define rofs 128 -%define ik_ref(x,y) [kptr-16*x+rofs+4*y] -%else -%define rofs -128 -%define ik_ref(x,y) [kptr+16*x+rofs+4*y] -%endif - -%define tab_0(x) [tptr+8*x] -%define tab_1(x) [tptr+8*x+3] -%define tab_2(x) [tptr+8*x+2] -%define tab_3(x) [tptr+8*x+1] -%define tab_f(x) byte [tptr+8*x+1] -%define tab_i(x) byte [tptr+8*x+7] -%define t_ref(x,r) tab_ %+ x(r) - -%macro ff_rnd 5 ; normal forward round - mov %1d, fk_ref(%5,0) - mov %2d, fk_ref(%5,1) - mov %3d, fk_ref(%5,2) - mov %4d, fk_ref(%5,3) - - movzx esi, al - movzx edi, ah - shr eax, 16 - xor %1d, t_ref(0,rsi) - xor %4d, t_ref(1,rdi) - movzx esi, al - movzx edi, ah - xor %3d, t_ref(2,rsi) - xor %2d, t_ref(3,rdi) - - movzx esi, bl - movzx edi, bh - shr ebx, 16 - xor %2d, t_ref(0,rsi) - xor %1d, t_ref(1,rdi) - movzx esi, bl - movzx edi, bh - xor %4d, t_ref(2,rsi) - xor %3d, t_ref(3,rdi) - - movzx esi, cl - movzx edi, ch - shr ecx, 16 - xor %3d, t_ref(0,rsi) - xor %2d, t_ref(1,rdi) - movzx esi, cl - movzx edi, ch - xor %1d, t_ref(2,rsi) - xor %4d, t_ref(3,rdi) - - movzx esi, dl - movzx edi, dh - shr edx, 16 - xor %4d, t_ref(0,rsi) - xor %3d, t_ref(1,rdi) - movzx esi, dl - movzx edi, dh - xor %2d, t_ref(2,rsi) - xor %1d, t_ref(3,rdi) - - mov eax,%1d - mov ebx,%2d - mov ecx,%3d - mov edx,%4d -%endmacro - -%ifdef LAST_ROUND_TABLES - -%macro fl_rnd 5 ; last forward round - add tptr, 2048 - mov %1d, fk_ref(%5,0) - mov %2d, fk_ref(%5,1) - mov %3d, fk_ref(%5,2) - mov %4d, fk_ref(%5,3) - - movzx esi, al - movzx edi, ah - shr eax, 16 - xor %1d, t_ref(0,rsi) - xor %4d, t_ref(1,rdi) - movzx esi, al - movzx edi, ah - xor %3d, t_ref(2,rsi) - xor %2d, t_ref(3,rdi) - - movzx esi, bl - movzx edi, bh - shr ebx, 16 - xor %2d, t_ref(0,rsi) - xor %1d, t_ref(1,rdi) - movzx esi, bl - movzx edi, bh - xor %4d, t_ref(2,rsi) - xor %3d, t_ref(3,rdi) - - movzx esi, cl - movzx edi, ch - shr ecx, 16 - xor %3d, t_ref(0,rsi) - xor %2d, t_ref(1,rdi) - movzx esi, cl - movzx edi, ch - xor %1d, t_ref(2,rsi) - xor %4d, t_ref(3,rdi) - - movzx esi, dl - movzx edi, dh - shr edx, 16 - xor %4d, t_ref(0,rsi) - xor %3d, t_ref(1,rdi) - movzx esi, dl - movzx edi, dh - xor %2d, t_ref(2,rsi) - xor %1d, t_ref(3,rdi) -%endmacro - -%else - -%macro fl_rnd 5 ; last forward round - mov %1d, fk_ref(%5,0) - mov %2d, fk_ref(%5,1) - mov %3d, fk_ref(%5,2) - mov %4d, fk_ref(%5,3) - - movzx esi, al - movzx edi, ah - shr eax, 16 - movzx esi, t_ref(f,rsi) - movzx edi, t_ref(f,rdi) - xor %1d, esi - rol edi, 8 - xor %4d, edi - movzx esi, al - movzx edi, ah - movzx esi, t_ref(f,rsi) - movzx edi, t_ref(f,rdi) - rol esi, 16 - rol edi, 24 - xor %3d, esi - xor %2d, edi - - movzx esi, bl - movzx edi, bh - shr ebx, 16 - movzx esi, t_ref(f,rsi) - movzx edi, t_ref(f,rdi) - xor %2d, esi - rol edi, 8 - xor %1d, edi - movzx esi, bl - movzx edi, bh - movzx esi, t_ref(f,rsi) - movzx edi, t_ref(f,rdi) - rol esi, 16 - rol edi, 24 - xor %4d, esi - xor %3d, edi - - movzx esi, cl - movzx edi, ch - movzx esi, t_ref(f,rsi) - movzx edi, t_ref(f,rdi) - shr ecx, 16 - xor %3d, esi - rol edi, 8 - xor %2d, edi - movzx esi, cl - movzx edi, ch - movzx esi, t_ref(f,rsi) - movzx edi, t_ref(f,rdi) - rol esi, 16 - rol edi, 24 - xor %1d, esi - xor %4d, edi - - movzx esi, dl - movzx edi, dh - movzx esi, t_ref(f,rsi) - movzx edi, t_ref(f,rdi) - shr edx, 16 - xor %4d, esi - rol edi, 8 - xor %3d, edi - movzx esi, dl - movzx edi, dh - movzx esi, t_ref(f,rsi) - movzx edi, t_ref(f,rdi) - rol esi, 16 - rol edi, 24 - xor %2d, esi - xor %1d, edi -%endmacro - -%endif - -%macro ii_rnd 5 ; normal inverse round - mov %1d, ik_ref(%5,0) - mov %2d, ik_ref(%5,1) - mov %3d, ik_ref(%5,2) - mov %4d, ik_ref(%5,3) - - movzx esi, al - movzx edi, ah - shr eax, 16 - xor %1d, t_ref(0,rsi) - xor %2d, t_ref(1,rdi) - movzx esi, al - movzx edi, ah - xor %3d, t_ref(2,rsi) - xor %4d, t_ref(3,rdi) - - movzx esi, bl - movzx edi, bh - shr ebx, 16 - xor %2d, t_ref(0,rsi) - xor %3d, t_ref(1,rdi) - movzx esi, bl - movzx edi, bh - xor %4d, t_ref(2,rsi) - xor %1d, t_ref(3,rdi) - - movzx esi, cl - movzx edi, ch - shr ecx, 16 - xor %3d, t_ref(0,rsi) - xor %4d, t_ref(1,rdi) - movzx esi, cl - movzx edi, ch - xor %1d, t_ref(2,rsi) - xor %2d, t_ref(3,rdi) - - movzx esi, dl - movzx edi, dh - shr edx, 16 - xor %4d, t_ref(0,rsi) - xor %1d, t_ref(1,rdi) - movzx esi, dl - movzx edi, dh - xor %2d, t_ref(2,rsi) - xor %3d, t_ref(3,rdi) - - mov eax,%1d - mov ebx,%2d - mov ecx,%3d - mov edx,%4d -%endmacro - -%ifdef LAST_ROUND_TABLES - -%macro il_rnd 5 ; last inverse round - add tptr, 2048 - mov %1d, ik_ref(%5,0) - mov %2d, ik_ref(%5,1) - mov %3d, ik_ref(%5,2) - mov %4d, ik_ref(%5,3) - - movzx esi, al - movzx edi, ah - shr eax, 16 - xor %1d, t_ref(0,rsi) - xor %2d, t_ref(1,rdi) - movzx esi, al - movzx edi, ah - xor %3d, t_ref(2,rsi) - xor %4d, t_ref(3,rdi) - - movzx esi, bl - movzx edi, bh - shr ebx, 16 - xor %2d, t_ref(0,rsi) - xor %3d, t_ref(1,rdi) - movzx esi, bl - movzx edi, bh - xor %4d, t_ref(2,rsi) - xor %1d, t_ref(3,rdi) - - movzx esi, cl - movzx edi, ch - shr ecx, 16 - xor %3d, t_ref(0,rsi) - xor %4d, t_ref(1,rdi) - movzx esi, cl - movzx edi, ch - xor %1d, t_ref(2,rsi) - xor %2d, t_ref(3,rdi) - - movzx esi, dl - movzx edi, dh - shr edx, 16 - xor %4d, t_ref(0,rsi) - xor %1d, t_ref(1,rdi) - movzx esi, dl - movzx edi, dh - xor %2d, t_ref(2,rsi) - xor %3d, t_ref(3,rdi) -%endmacro - -%else - -%macro il_rnd 5 ; last inverse round - mov %1d, ik_ref(%5,0) - mov %2d, ik_ref(%5,1) - mov %3d, ik_ref(%5,2) - mov %4d, ik_ref(%5,3) - - movzx esi, al - movzx edi, ah - movzx esi, t_ref(i,rsi) - movzx edi, t_ref(i,rdi) - shr eax, 16 - xor %1d, esi - rol edi, 8 - xor %2d, edi - movzx esi, al - movzx edi, ah - movzx esi, t_ref(i,rsi) - movzx edi, t_ref(i,rdi) - rol esi, 16 - rol edi, 24 - xor %3d, esi - xor %4d, edi - - movzx esi, bl - movzx edi, bh - movzx esi, t_ref(i,rsi) - movzx edi, t_ref(i,rdi) - shr ebx, 16 - xor %2d, esi - rol edi, 8 - xor %3d, edi - movzx esi, bl - movzx edi, bh - movzx esi, t_ref(i,rsi) - movzx edi, t_ref(i,rdi) - rol esi, 16 - rol edi, 24 - xor %4d, esi - xor %1d, edi - - movzx esi, cl - movzx edi, ch - movzx esi, t_ref(i,rsi) - movzx edi, t_ref(i,rdi) - shr ecx, 16 - xor %3d, esi - rol edi, 8 - xor %4d, edi - movzx esi, cl - movzx edi, ch - movzx esi, t_ref(i,rsi) - movzx edi, t_ref(i,rdi) - rol esi, 16 - rol edi, 24 - xor %1d, esi - xor %2d, edi - - movzx esi, dl - movzx edi, dh - movzx esi, t_ref(i,rsi) - movzx edi, t_ref(i,rdi) - shr edx, 16 - xor %4d, esi - rol edi, 8 - xor %1d, edi - movzx esi, dl - movzx edi, dh - movzx esi, t_ref(i,rsi) - movzx edi, t_ref(i,rdi) - rol esi, 16 - rol edi, 24 - xor %2d, esi - xor %3d, edi -%endmacro - -%endif - -%ifdef ENCRYPTION - - global aes_encrypt -%ifdef DLL_EXPORT - export aes_encrypt -%endif - - section .data align=64 - align 64 -enc_tab: - enc_vals u8 -%ifdef LAST_ROUND_TABLES - enc_vals w8 -%endif - - section .text align=16 - align 16 - -%ifdef _SEH_ -proc_frame aes_encrypt - alloc_stack 7*8 ; 7 to align stack to 16 bytes - save_reg rsi,4*8 - save_reg rdi,5*8 - save_reg rbx,1*8 - save_reg rbp,2*8 - save_reg r12,3*8 -end_prologue - mov rdi, rcx ; input pointer - mov [rsp+0*8], rdx ; output pointer -%else - aes_encrypt: - %ifdef __GNUC__ - sub rsp, 4*8 ; gnu/linux binary interface - mov [rsp+0*8], rsi ; output pointer - mov r8, rdx ; context - %else - sub rsp, 6*8 ; windows binary interface - mov [rsp+4*8], rsi - mov [rsp+5*8], rdi - mov rdi, rcx ; input pointer - mov [rsp+0*8], rdx ; output pointer - %endif - mov [rsp+1*8], rbx ; input pointer in rdi - mov [rsp+2*8], rbp ; output pointer in [rsp] - mov [rsp+3*8], r12 ; context in r8 -%endif - - movzx esi, byte [kptr+4*KS_LENGTH] - lea tptr, [rel enc_tab] - sub kptr, fofs - - mov eax, [rdi+0*4] - mov ebx, [rdi+1*4] - mov ecx, [rdi+2*4] - mov edx, [rdi+3*4] - - xor eax, [kptr+fofs] - xor ebx, [kptr+fofs+4] - xor ecx, [kptr+fofs+8] - xor edx, [kptr+fofs+12] - - lea kptr,[kptr+rsi] - cmp esi, 10*16 - je .3 - cmp esi, 12*16 - je .2 - cmp esi, 14*16 - je .1 - mov rax, -1 - jmp .4 - -.1: ff_rnd r9, r10, r11, r12, 13 - ff_rnd r9, r10, r11, r12, 12 -.2: ff_rnd r9, r10, r11, r12, 11 - ff_rnd r9, r10, r11, r12, 10 -.3: ff_rnd r9, r10, r11, r12, 9 - ff_rnd r9, r10, r11, r12, 8 - ff_rnd r9, r10, r11, r12, 7 - ff_rnd r9, r10, r11, r12, 6 - ff_rnd r9, r10, r11, r12, 5 - ff_rnd r9, r10, r11, r12, 4 - ff_rnd r9, r10, r11, r12, 3 - ff_rnd r9, r10, r11, r12, 2 - ff_rnd r9, r10, r11, r12, 1 - fl_rnd r9, r10, r11, r12, 0 - - mov rbx, [rsp] - mov [rbx], r9d - mov [rbx+4], r10d - mov [rbx+8], r11d - mov [rbx+12], r12d - xor rax, rax -.4: - mov rbx, [rsp+1*8] - mov rbp, [rsp+2*8] - mov r12, [rsp+3*8] -%ifdef __GNUC__ - add rsp, 4*8 - ret -%else - mov rsi, [rsp+4*8] - mov rdi, [rsp+5*8] - %ifdef _SEH_ - add rsp, 7*8 - ret - endproc_frame - %else - add rsp, 6*8 - ret - %endif -%endif - -%endif - -%ifdef DECRYPTION - - global aes_decrypt -%ifdef DLL_EXPORT - export aes_decrypt -%endif - - section .data - align 64 -dec_tab: - dec_vals v8 -%ifdef LAST_ROUND_TABLES - dec_vals w8 -%endif - - section .text - align 16 - -%ifdef _SEH_ -proc_frame aes_decrypt - alloc_stack 7*8 ; 7 to align stack to 16 bytes - save_reg rsi,4*8 - save_reg rdi,5*8 - save_reg rbx,1*8 - save_reg rbp,2*8 - save_reg r12,3*8 -end_prologue - mov rdi, rcx ; input pointer - mov [rsp+0*8], rdx ; output pointer -%else - aes_decrypt: - %ifdef __GNUC__ - sub rsp, 4*8 ; gnu/linux binary interface - mov [rsp+0*8], rsi ; output pointer - mov r8, rdx ; context - %else - sub rsp, 6*8 ; windows binary interface - mov [rsp+4*8], rsi - mov [rsp+5*8], rdi - mov rdi, rcx ; input pointer - mov [rsp+0*8], rdx ; output pointer - %endif - mov [rsp+1*8], rbx ; input pointer in rdi - mov [rsp+2*8], rbp ; output pointer in [rsp] - mov [rsp+3*8], r12 ; context in r8 -%endif - - movzx esi,byte[kptr+4*KS_LENGTH] - lea tptr, [rel dec_tab] - sub kptr, rofs - - mov eax, [rdi+0*4] - mov ebx, [rdi+1*4] - mov ecx, [rdi+2*4] - mov edx, [rdi+3*4] - -%ifdef AES_REV_DKS - mov rdi, kptr - lea kptr,[kptr+rsi] -%else - lea rdi,[kptr+rsi] -%endif - - xor eax, [rdi+rofs] - xor ebx, [rdi+rofs+4] - xor ecx, [rdi+rofs+8] - xor edx, [rdi+rofs+12] - - cmp esi, 10*16 - je .3 - cmp esi, 12*16 - je .2 - cmp esi, 14*16 - je .1 - mov rax, -1 - jmp .4 - -.1: ii_rnd r9, r10, r11, r12, 13 - ii_rnd r9, r10, r11, r12, 12 -.2: ii_rnd r9, r10, r11, r12, 11 - ii_rnd r9, r10, r11, r12, 10 -.3: ii_rnd r9, r10, r11, r12, 9 - ii_rnd r9, r10, r11, r12, 8 - ii_rnd r9, r10, r11, r12, 7 - ii_rnd r9, r10, r11, r12, 6 - ii_rnd r9, r10, r11, r12, 5 - ii_rnd r9, r10, r11, r12, 4 - ii_rnd r9, r10, r11, r12, 3 - ii_rnd r9, r10, r11, r12, 2 - ii_rnd r9, r10, r11, r12, 1 - il_rnd r9, r10, r11, r12, 0 - - mov rbx, [rsp] - mov [rbx], r9d - mov [rbx+4], r10d - mov [rbx+8], r11d - mov [rbx+12], r12d - xor rax, rax -.4: mov rbx, [rsp+1*8] - mov rbp, [rsp+2*8] - mov r12, [rsp+3*8] -%ifdef __GNUC__ - add rsp, 4*8 - ret -%else - mov rsi, [rsp+4*8] - mov rdi, [rsp+5*8] - %ifdef _SEH_ - add rsp, 7*8 - ret - endproc_frame - %else - add rsp, 6*8 - ret - %endif -%endif - -%endif + +; --------------------------------------------------------------------------- +; Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. +; +; LICENSE TERMS +; +; The free distribution and use of this software is allowed (with or without +; changes) provided that: +; +; 1. source code distributions include the above copyright notice, this +; list of conditions and the following disclaimer; +; +; 2. binary distributions include the above copyright notice, this list +; of conditions and the following disclaimer in their documentation; +; +; 3. the name of the copyright holder is not used to endorse products +; built using this software without specific written permission. +; +; DISCLAIMER +; +; This software is provided 'as is' with no explicit or implied warranties +; in respect of its properties, including, but not limited to, correctness +; and/or fitness for purpose. +; --------------------------------------------------------------------------- +; Issue 20/12/2007 +; +; I am grateful to Dag Arne Osvik for many discussions of the techniques that +; can be used to optimise AES assembler code on AMD64/EM64T architectures. +; Some of the techniques used in this implementation are the result of +; suggestions made by him for which I am most grateful. + +; +; Adapted for TrueCrypt: +; - Compatibility with NASM +; + +; An AES implementation for AMD64 processors using the YASM assembler. This +; implemetation provides only encryption, decryption and hence requires key +; scheduling support in C. It uses 8k bytes of tables but its encryption and +; decryption performance is very close to that obtained using large tables. +; It can use either Windows or Gnu/Linux calling conventions, which are as +; follows: +; windows gnu/linux +; +; in_blk rcx rdi +; out_blk rdx rsi +; context (cx) r8 rdx +; +; preserved rsi - + rbx, rbp, rsp, r12, r13, r14 & r15 +; registers rdi - on both +; +; destroyed - rsi + rax, rcx, rdx, r8, r9, r10 & r11 +; registers - rdi on both +; +; The default convention is that for windows, the gnu/linux convention being +; used if __GNUC__ is defined. +; +; Define _SEH_ to include support for Win64 structured exception handling +; (this requires YASM version 0.6 or later). +; +; This code provides the standard AES block size (128 bits, 16 bytes) and the +; three standard AES key sizes (128, 192 and 256 bits). It has the same call +; interface as my C implementation. It uses the Microsoft C AMD64 calling +; conventions in which the three parameters are placed in rcx, rdx and r8 +; respectively. The rbx, rsi, rdi, rbp and r12..r15 registers are preserved. +; +; AES_RETURN aes_encrypt(const unsigned char in_blk[], +; unsigned char out_blk[], const aes_encrypt_ctx cx[1]); +; +; AES_RETURN aes_decrypt(const unsigned char in_blk[], +; unsigned char out_blk[], const aes_decrypt_ctx cx[1]); +; +; AES_RETURN aes_encrypt_key(const unsigned char key[], +; const aes_encrypt_ctx cx[1]); +; +; AES_RETURN aes_decrypt_key(const unsigned char key[], +; const aes_decrypt_ctx cx[1]); +; +; AES_RETURN aes_encrypt_key(const unsigned char key[], +; unsigned int len, const aes_decrypt_ctx cx[1]); +; +; AES_RETURN aes_decrypt_key(const unsigned char key[], +; unsigned int len, const aes_decrypt_ctx cx[1]); +; +; where is 128, 102 or 256. In the last two calls the length can be in +; either bits or bytes. +; +; Comment in/out the following lines to obtain the desired subroutines. These +; selections MUST match those in the C header file aes.h + +; %define AES_128 ; define if AES with 128 bit keys is needed +; %define AES_192 ; define if AES with 192 bit keys is needed +%define AES_256 ; define if AES with 256 bit keys is needed +; %define AES_VAR ; define if a variable key size is needed +%define ENCRYPTION ; define if encryption is needed +%define DECRYPTION ; define if decryption is needed +%define AES_REV_DKS ; define if key decryption schedule is reversed +%define LAST_ROUND_TABLES ; define for the faster version using extra tables + +; The encryption key schedule has the following in memory layout where N is the +; number of rounds (10, 12 or 14): +; +; lo: | input key (round 0) | ; each round is four 32-bit words +; | encryption round 1 | +; | encryption round 2 | +; .... +; | encryption round N-1 | +; hi: | encryption round N | +; +; The decryption key schedule is normally set up so that it has the same +; layout as above by actually reversing the order of the encryption key +; schedule in memory (this happens when AES_REV_DKS is set): +; +; lo: | decryption round 0 | = | encryption round N | +; | decryption round 1 | = INV_MIX_COL[ | encryption round N-1 | ] +; | decryption round 2 | = INV_MIX_COL[ | encryption round N-2 | ] +; .... .... +; | decryption round N-1 | = INV_MIX_COL[ | encryption round 1 | ] +; hi: | decryption round N | = | input key (round 0) | +; +; with rounds except the first and last modified using inv_mix_column() +; But if AES_REV_DKS is NOT set the order of keys is left as it is for +; encryption so that it has to be accessed in reverse when used for +; decryption (although the inverse mix column modifications are done) +; +; lo: | decryption round 0 | = | input key (round 0) | +; | decryption round 1 | = INV_MIX_COL[ | encryption round 1 | ] +; | decryption round 2 | = INV_MIX_COL[ | encryption round 2 | ] +; .... .... +; | decryption round N-1 | = INV_MIX_COL[ | encryption round N-1 | ] +; hi: | decryption round N | = | encryption round N | +; +; This layout is faster when the assembler key scheduling provided here +; is used. +; +; The DLL interface must use the _stdcall convention in which the number +; of bytes of parameter space is added after an @ to the sutine's name. +; We must also remove our parameters from the stack before return (see +; the do_exit macro). Define DLL_EXPORT for the Dynamic Link Library version. + +;%define DLL_EXPORT + +; End of user defines + +%ifdef AES_VAR +%ifndef AES_128 +%define AES_128 +%endif +%ifndef AES_192 +%define AES_192 +%endif +%ifndef AES_256 +%define AES_256 +%endif +%endif + +%ifdef AES_VAR +%define KS_LENGTH 60 +%elifdef AES_256 +%define KS_LENGTH 60 +%elifdef AES_192 +%define KS_LENGTH 52 +%else +%define KS_LENGTH 44 +%endif + +%define r0 rax +%define r1 rdx +%define r2 rcx +%define r3 rbx +%define r4 rsi +%define r5 rdi +%define r6 rbp +%define r7 rsp + +%define raxd eax +%define rdxd edx +%define rcxd ecx +%define rbxd ebx +%define rsid esi +%define rdid edi +%define rbpd ebp +%define rspd esp + +%define raxb al +%define rdxb dl +%define rcxb cl +%define rbxb bl +%define rsib sil +%define rdib dil +%define rbpb bpl +%define rspb spl + +%define r0h ah +%define r1h dh +%define r2h ch +%define r3h bh + +%define r0d eax +%define r1d edx +%define r2d ecx +%define r3d ebx + +; finite field multiplies by {02}, {04} and {08} + +%define f2(x) ((x<<1)^(((x>>7)&1)*0x11b)) +%define f4(x) ((x<<2)^(((x>>6)&1)*0x11b)^(((x>>6)&2)*0x11b)) +%define f8(x) ((x<<3)^(((x>>5)&1)*0x11b)^(((x>>5)&2)*0x11b)^(((x>>5)&4)*0x11b)) + +; finite field multiplies required in table generation + +%define f3(x) (f2(x) ^ x) +%define f9(x) (f8(x) ^ x) +%define fb(x) (f8(x) ^ f2(x) ^ x) +%define fd(x) (f8(x) ^ f4(x) ^ x) +%define fe(x) (f8(x) ^ f4(x) ^ f2(x)) + +; macro for expanding S-box data + +%macro enc_vals 1 + db %1(0x63),%1(0x7c),%1(0x77),%1(0x7b),%1(0xf2),%1(0x6b),%1(0x6f),%1(0xc5) + db %1(0x30),%1(0x01),%1(0x67),%1(0x2b),%1(0xfe),%1(0xd7),%1(0xab),%1(0x76) + db %1(0xca),%1(0x82),%1(0xc9),%1(0x7d),%1(0xfa),%1(0x59),%1(0x47),%1(0xf0) + db %1(0xad),%1(0xd4),%1(0xa2),%1(0xaf),%1(0x9c),%1(0xa4),%1(0x72),%1(0xc0) + db %1(0xb7),%1(0xfd),%1(0x93),%1(0x26),%1(0x36),%1(0x3f),%1(0xf7),%1(0xcc) + db %1(0x34),%1(0xa5),%1(0xe5),%1(0xf1),%1(0x71),%1(0xd8),%1(0x31),%1(0x15) + db %1(0x04),%1(0xc7),%1(0x23),%1(0xc3),%1(0x18),%1(0x96),%1(0x05),%1(0x9a) + db %1(0x07),%1(0x12),%1(0x80),%1(0xe2),%1(0xeb),%1(0x27),%1(0xb2),%1(0x75) + db %1(0x09),%1(0x83),%1(0x2c),%1(0x1a),%1(0x1b),%1(0x6e),%1(0x5a),%1(0xa0) + db %1(0x52),%1(0x3b),%1(0xd6),%1(0xb3),%1(0x29),%1(0xe3),%1(0x2f),%1(0x84) + db %1(0x53),%1(0xd1),%1(0x00),%1(0xed),%1(0x20),%1(0xfc),%1(0xb1),%1(0x5b) + db %1(0x6a),%1(0xcb),%1(0xbe),%1(0x39),%1(0x4a),%1(0x4c),%1(0x58),%1(0xcf) + db %1(0xd0),%1(0xef),%1(0xaa),%1(0xfb),%1(0x43),%1(0x4d),%1(0x33),%1(0x85) + db %1(0x45),%1(0xf9),%1(0x02),%1(0x7f),%1(0x50),%1(0x3c),%1(0x9f),%1(0xa8) + db %1(0x51),%1(0xa3),%1(0x40),%1(0x8f),%1(0x92),%1(0x9d),%1(0x38),%1(0xf5) + db %1(0xbc),%1(0xb6),%1(0xda),%1(0x21),%1(0x10),%1(0xff),%1(0xf3),%1(0xd2) + db %1(0xcd),%1(0x0c),%1(0x13),%1(0xec),%1(0x5f),%1(0x97),%1(0x44),%1(0x17) + db %1(0xc4),%1(0xa7),%1(0x7e),%1(0x3d),%1(0x64),%1(0x5d),%1(0x19),%1(0x73) + db %1(0x60),%1(0x81),%1(0x4f),%1(0xdc),%1(0x22),%1(0x2a),%1(0x90),%1(0x88) + db %1(0x46),%1(0xee),%1(0xb8),%1(0x14),%1(0xde),%1(0x5e),%1(0x0b),%1(0xdb) + db %1(0xe0),%1(0x32),%1(0x3a),%1(0x0a),%1(0x49),%1(0x06),%1(0x24),%1(0x5c) + db %1(0xc2),%1(0xd3),%1(0xac),%1(0x62),%1(0x91),%1(0x95),%1(0xe4),%1(0x79) + db %1(0xe7),%1(0xc8),%1(0x37),%1(0x6d),%1(0x8d),%1(0xd5),%1(0x4e),%1(0xa9) + db %1(0x6c),%1(0x56),%1(0xf4),%1(0xea),%1(0x65),%1(0x7a),%1(0xae),%1(0x08) + db %1(0xba),%1(0x78),%1(0x25),%1(0x2e),%1(0x1c),%1(0xa6),%1(0xb4),%1(0xc6) + db %1(0xe8),%1(0xdd),%1(0x74),%1(0x1f),%1(0x4b),%1(0xbd),%1(0x8b),%1(0x8a) + db %1(0x70),%1(0x3e),%1(0xb5),%1(0x66),%1(0x48),%1(0x03),%1(0xf6),%1(0x0e) + db %1(0x61),%1(0x35),%1(0x57),%1(0xb9),%1(0x86),%1(0xc1),%1(0x1d),%1(0x9e) + db %1(0xe1),%1(0xf8),%1(0x98),%1(0x11),%1(0x69),%1(0xd9),%1(0x8e),%1(0x94) + db %1(0x9b),%1(0x1e),%1(0x87),%1(0xe9),%1(0xce),%1(0x55),%1(0x28),%1(0xdf) + db %1(0x8c),%1(0xa1),%1(0x89),%1(0x0d),%1(0xbf),%1(0xe6),%1(0x42),%1(0x68) + db %1(0x41),%1(0x99),%1(0x2d),%1(0x0f),%1(0xb0),%1(0x54),%1(0xbb),%1(0x16) +%endmacro + +%macro dec_vals 1 + db %1(0x52),%1(0x09),%1(0x6a),%1(0xd5),%1(0x30),%1(0x36),%1(0xa5),%1(0x38) + db %1(0xbf),%1(0x40),%1(0xa3),%1(0x9e),%1(0x81),%1(0xf3),%1(0xd7),%1(0xfb) + db %1(0x7c),%1(0xe3),%1(0x39),%1(0x82),%1(0x9b),%1(0x2f),%1(0xff),%1(0x87) + db %1(0x34),%1(0x8e),%1(0x43),%1(0x44),%1(0xc4),%1(0xde),%1(0xe9),%1(0xcb) + db %1(0x54),%1(0x7b),%1(0x94),%1(0x32),%1(0xa6),%1(0xc2),%1(0x23),%1(0x3d) + db %1(0xee),%1(0x4c),%1(0x95),%1(0x0b),%1(0x42),%1(0xfa),%1(0xc3),%1(0x4e) + db %1(0x08),%1(0x2e),%1(0xa1),%1(0x66),%1(0x28),%1(0xd9),%1(0x24),%1(0xb2) + db %1(0x76),%1(0x5b),%1(0xa2),%1(0x49),%1(0x6d),%1(0x8b),%1(0xd1),%1(0x25) + db %1(0x72),%1(0xf8),%1(0xf6),%1(0x64),%1(0x86),%1(0x68),%1(0x98),%1(0x16) + db %1(0xd4),%1(0xa4),%1(0x5c),%1(0xcc),%1(0x5d),%1(0x65),%1(0xb6),%1(0x92) + db %1(0x6c),%1(0x70),%1(0x48),%1(0x50),%1(0xfd),%1(0xed),%1(0xb9),%1(0xda) + db %1(0x5e),%1(0x15),%1(0x46),%1(0x57),%1(0xa7),%1(0x8d),%1(0x9d),%1(0x84) + db %1(0x90),%1(0xd8),%1(0xab),%1(0x00),%1(0x8c),%1(0xbc),%1(0xd3),%1(0x0a) + db %1(0xf7),%1(0xe4),%1(0x58),%1(0x05),%1(0xb8),%1(0xb3),%1(0x45),%1(0x06) + db %1(0xd0),%1(0x2c),%1(0x1e),%1(0x8f),%1(0xca),%1(0x3f),%1(0x0f),%1(0x02) + db %1(0xc1),%1(0xaf),%1(0xbd),%1(0x03),%1(0x01),%1(0x13),%1(0x8a),%1(0x6b) + db %1(0x3a),%1(0x91),%1(0x11),%1(0x41),%1(0x4f),%1(0x67),%1(0xdc),%1(0xea) + db %1(0x97),%1(0xf2),%1(0xcf),%1(0xce),%1(0xf0),%1(0xb4),%1(0xe6),%1(0x73) + db %1(0x96),%1(0xac),%1(0x74),%1(0x22),%1(0xe7),%1(0xad),%1(0x35),%1(0x85) + db %1(0xe2),%1(0xf9),%1(0x37),%1(0xe8),%1(0x1c),%1(0x75),%1(0xdf),%1(0x6e) + db %1(0x47),%1(0xf1),%1(0x1a),%1(0x71),%1(0x1d),%1(0x29),%1(0xc5),%1(0x89) + db %1(0x6f),%1(0xb7),%1(0x62),%1(0x0e),%1(0xaa),%1(0x18),%1(0xbe),%1(0x1b) + db %1(0xfc),%1(0x56),%1(0x3e),%1(0x4b),%1(0xc6),%1(0xd2),%1(0x79),%1(0x20) + db %1(0x9a),%1(0xdb),%1(0xc0),%1(0xfe),%1(0x78),%1(0xcd),%1(0x5a),%1(0xf4) + db %1(0x1f),%1(0xdd),%1(0xa8),%1(0x33),%1(0x88),%1(0x07),%1(0xc7),%1(0x31) + db %1(0xb1),%1(0x12),%1(0x10),%1(0x59),%1(0x27),%1(0x80),%1(0xec),%1(0x5f) + db %1(0x60),%1(0x51),%1(0x7f),%1(0xa9),%1(0x19),%1(0xb5),%1(0x4a),%1(0x0d) + db %1(0x2d),%1(0xe5),%1(0x7a),%1(0x9f),%1(0x93),%1(0xc9),%1(0x9c),%1(0xef) + db %1(0xa0),%1(0xe0),%1(0x3b),%1(0x4d),%1(0xae),%1(0x2a),%1(0xf5),%1(0xb0) + db %1(0xc8),%1(0xeb),%1(0xbb),%1(0x3c),%1(0x83),%1(0x53),%1(0x99),%1(0x61) + db %1(0x17),%1(0x2b),%1(0x04),%1(0x7e),%1(0xba),%1(0x77),%1(0xd6),%1(0x26) + db %1(0xe1),%1(0x69),%1(0x14),%1(0x63),%1(0x55),%1(0x21),%1(0x0c),%1(0x7d) +%endmacro + +%define u8(x) f2(x), x, x, f3(x), f2(x), x, x, f3(x) +%define v8(x) fe(x), f9(x), fd(x), fb(x), fe(x), f9(x), fd(x), x +%define w8(x) x, 0, 0, 0, x, 0, 0, 0 + +%define tptr rbp ; table pointer +%define kptr r8 ; key schedule pointer +%define fofs 128 ; adjust offset in key schedule to keep |disp| < 128 +%define fk_ref(x,y) [kptr-16*x+fofs+4*y] +%ifdef AES_REV_DKS +%define rofs 128 +%define ik_ref(x,y) [kptr-16*x+rofs+4*y] +%else +%define rofs -128 +%define ik_ref(x,y) [kptr+16*x+rofs+4*y] +%endif + +%define tab_0(x) [tptr+8*x] +%define tab_1(x) [tptr+8*x+3] +%define tab_2(x) [tptr+8*x+2] +%define tab_3(x) [tptr+8*x+1] +%define tab_f(x) byte [tptr+8*x+1] +%define tab_i(x) byte [tptr+8*x+7] +%define t_ref(x,r) tab_ %+ x(r) + +%macro ff_rnd 5 ; normal forward round + mov %1d, fk_ref(%5,0) + mov %2d, fk_ref(%5,1) + mov %3d, fk_ref(%5,2) + mov %4d, fk_ref(%5,3) + + movzx esi, al + movzx edi, ah + shr eax, 16 + xor %1d, t_ref(0,rsi) + xor %4d, t_ref(1,rdi) + movzx esi, al + movzx edi, ah + xor %3d, t_ref(2,rsi) + xor %2d, t_ref(3,rdi) + + movzx esi, bl + movzx edi, bh + shr ebx, 16 + xor %2d, t_ref(0,rsi) + xor %1d, t_ref(1,rdi) + movzx esi, bl + movzx edi, bh + xor %4d, t_ref(2,rsi) + xor %3d, t_ref(3,rdi) + + movzx esi, cl + movzx edi, ch + shr ecx, 16 + xor %3d, t_ref(0,rsi) + xor %2d, t_ref(1,rdi) + movzx esi, cl + movzx edi, ch + xor %1d, t_ref(2,rsi) + xor %4d, t_ref(3,rdi) + + movzx esi, dl + movzx edi, dh + shr edx, 16 + xor %4d, t_ref(0,rsi) + xor %3d, t_ref(1,rdi) + movzx esi, dl + movzx edi, dh + xor %2d, t_ref(2,rsi) + xor %1d, t_ref(3,rdi) + + mov eax,%1d + mov ebx,%2d + mov ecx,%3d + mov edx,%4d +%endmacro + +%ifdef LAST_ROUND_TABLES + +%macro fl_rnd 5 ; last forward round + add tptr, 2048 + mov %1d, fk_ref(%5,0) + mov %2d, fk_ref(%5,1) + mov %3d, fk_ref(%5,2) + mov %4d, fk_ref(%5,3) + + movzx esi, al + movzx edi, ah + shr eax, 16 + xor %1d, t_ref(0,rsi) + xor %4d, t_ref(1,rdi) + movzx esi, al + movzx edi, ah + xor %3d, t_ref(2,rsi) + xor %2d, t_ref(3,rdi) + + movzx esi, bl + movzx edi, bh + shr ebx, 16 + xor %2d, t_ref(0,rsi) + xor %1d, t_ref(1,rdi) + movzx esi, bl + movzx edi, bh + xor %4d, t_ref(2,rsi) + xor %3d, t_ref(3,rdi) + + movzx esi, cl + movzx edi, ch + shr ecx, 16 + xor %3d, t_ref(0,rsi) + xor %2d, t_ref(1,rdi) + movzx esi, cl + movzx edi, ch + xor %1d, t_ref(2,rsi) + xor %4d, t_ref(3,rdi) + + movzx esi, dl + movzx edi, dh + shr edx, 16 + xor %4d, t_ref(0,rsi) + xor %3d, t_ref(1,rdi) + movzx esi, dl + movzx edi, dh + xor %2d, t_ref(2,rsi) + xor %1d, t_ref(3,rdi) +%endmacro + +%else + +%macro fl_rnd 5 ; last forward round + mov %1d, fk_ref(%5,0) + mov %2d, fk_ref(%5,1) + mov %3d, fk_ref(%5,2) + mov %4d, fk_ref(%5,3) + + movzx esi, al + movzx edi, ah + shr eax, 16 + movzx esi, t_ref(f,rsi) + movzx edi, t_ref(f,rdi) + xor %1d, esi + rol edi, 8 + xor %4d, edi + movzx esi, al + movzx edi, ah + movzx esi, t_ref(f,rsi) + movzx edi, t_ref(f,rdi) + rol esi, 16 + rol edi, 24 + xor %3d, esi + xor %2d, edi + + movzx esi, bl + movzx edi, bh + shr ebx, 16 + movzx esi, t_ref(f,rsi) + movzx edi, t_ref(f,rdi) + xor %2d, esi + rol edi, 8 + xor %1d, edi + movzx esi, bl + movzx edi, bh + movzx esi, t_ref(f,rsi) + movzx edi, t_ref(f,rdi) + rol esi, 16 + rol edi, 24 + xor %4d, esi + xor %3d, edi + + movzx esi, cl + movzx edi, ch + movzx esi, t_ref(f,rsi) + movzx edi, t_ref(f,rdi) + shr ecx, 16 + xor %3d, esi + rol edi, 8 + xor %2d, edi + movzx esi, cl + movzx edi, ch + movzx esi, t_ref(f,rsi) + movzx edi, t_ref(f,rdi) + rol esi, 16 + rol edi, 24 + xor %1d, esi + xor %4d, edi + + movzx esi, dl + movzx edi, dh + movzx esi, t_ref(f,rsi) + movzx edi, t_ref(f,rdi) + shr edx, 16 + xor %4d, esi + rol edi, 8 + xor %3d, edi + movzx esi, dl + movzx edi, dh + movzx esi, t_ref(f,rsi) + movzx edi, t_ref(f,rdi) + rol esi, 16 + rol edi, 24 + xor %2d, esi + xor %1d, edi +%endmacro + +%endif + +%macro ii_rnd 5 ; normal inverse round + mov %1d, ik_ref(%5,0) + mov %2d, ik_ref(%5,1) + mov %3d, ik_ref(%5,2) + mov %4d, ik_ref(%5,3) + + movzx esi, al + movzx edi, ah + shr eax, 16 + xor %1d, t_ref(0,rsi) + xor %2d, t_ref(1,rdi) + movzx esi, al + movzx edi, ah + xor %3d, t_ref(2,rsi) + xor %4d, t_ref(3,rdi) + + movzx esi, bl + movzx edi, bh + shr ebx, 16 + xor %2d, t_ref(0,rsi) + xor %3d, t_ref(1,rdi) + movzx esi, bl + movzx edi, bh + xor %4d, t_ref(2,rsi) + xor %1d, t_ref(3,rdi) + + movzx esi, cl + movzx edi, ch + shr ecx, 16 + xor %3d, t_ref(0,rsi) + xor %4d, t_ref(1,rdi) + movzx esi, cl + movzx edi, ch + xor %1d, t_ref(2,rsi) + xor %2d, t_ref(3,rdi) + + movzx esi, dl + movzx edi, dh + shr edx, 16 + xor %4d, t_ref(0,rsi) + xor %1d, t_ref(1,rdi) + movzx esi, dl + movzx edi, dh + xor %2d, t_ref(2,rsi) + xor %3d, t_ref(3,rdi) + + mov eax,%1d + mov ebx,%2d + mov ecx,%3d + mov edx,%4d +%endmacro + +%ifdef LAST_ROUND_TABLES + +%macro il_rnd 5 ; last inverse round + add tptr, 2048 + mov %1d, ik_ref(%5,0) + mov %2d, ik_ref(%5,1) + mov %3d, ik_ref(%5,2) + mov %4d, ik_ref(%5,3) + + movzx esi, al + movzx edi, ah + shr eax, 16 + xor %1d, t_ref(0,rsi) + xor %2d, t_ref(1,rdi) + movzx esi, al + movzx edi, ah + xor %3d, t_ref(2,rsi) + xor %4d, t_ref(3,rdi) + + movzx esi, bl + movzx edi, bh + shr ebx, 16 + xor %2d, t_ref(0,rsi) + xor %3d, t_ref(1,rdi) + movzx esi, bl + movzx edi, bh + xor %4d, t_ref(2,rsi) + xor %1d, t_ref(3,rdi) + + movzx esi, cl + movzx edi, ch + shr ecx, 16 + xor %3d, t_ref(0,rsi) + xor %4d, t_ref(1,rdi) + movzx esi, cl + movzx edi, ch + xor %1d, t_ref(2,rsi) + xor %2d, t_ref(3,rdi) + + movzx esi, dl + movzx edi, dh + shr edx, 16 + xor %4d, t_ref(0,rsi) + xor %1d, t_ref(1,rdi) + movzx esi, dl + movzx edi, dh + xor %2d, t_ref(2,rsi) + xor %3d, t_ref(3,rdi) +%endmacro + +%else + +%macro il_rnd 5 ; last inverse round + mov %1d, ik_ref(%5,0) + mov %2d, ik_ref(%5,1) + mov %3d, ik_ref(%5,2) + mov %4d, ik_ref(%5,3) + + movzx esi, al + movzx edi, ah + movzx esi, t_ref(i,rsi) + movzx edi, t_ref(i,rdi) + shr eax, 16 + xor %1d, esi + rol edi, 8 + xor %2d, edi + movzx esi, al + movzx edi, ah + movzx esi, t_ref(i,rsi) + movzx edi, t_ref(i,rdi) + rol esi, 16 + rol edi, 24 + xor %3d, esi + xor %4d, edi + + movzx esi, bl + movzx edi, bh + movzx esi, t_ref(i,rsi) + movzx edi, t_ref(i,rdi) + shr ebx, 16 + xor %2d, esi + rol edi, 8 + xor %3d, edi + movzx esi, bl + movzx edi, bh + movzx esi, t_ref(i,rsi) + movzx edi, t_ref(i,rdi) + rol esi, 16 + rol edi, 24 + xor %4d, esi + xor %1d, edi + + movzx esi, cl + movzx edi, ch + movzx esi, t_ref(i,rsi) + movzx edi, t_ref(i,rdi) + shr ecx, 16 + xor %3d, esi + rol edi, 8 + xor %4d, edi + movzx esi, cl + movzx edi, ch + movzx esi, t_ref(i,rsi) + movzx edi, t_ref(i,rdi) + rol esi, 16 + rol edi, 24 + xor %1d, esi + xor %2d, edi + + movzx esi, dl + movzx edi, dh + movzx esi, t_ref(i,rsi) + movzx edi, t_ref(i,rdi) + shr edx, 16 + xor %4d, esi + rol edi, 8 + xor %1d, edi + movzx esi, dl + movzx edi, dh + movzx esi, t_ref(i,rsi) + movzx edi, t_ref(i,rdi) + rol esi, 16 + rol edi, 24 + xor %2d, esi + xor %3d, edi +%endmacro + +%endif + +%ifdef ENCRYPTION + + global aes_encrypt +%ifdef DLL_EXPORT + export aes_encrypt +%endif + + section .data align=64 + align 64 +enc_tab: + enc_vals u8 +%ifdef LAST_ROUND_TABLES + enc_vals w8 +%endif + + section .text align=16 + align 16 + +%ifdef _SEH_ +proc_frame aes_encrypt + alloc_stack 7*8 ; 7 to align stack to 16 bytes + save_reg rsi,4*8 + save_reg rdi,5*8 + save_reg rbx,1*8 + save_reg rbp,2*8 + save_reg r12,3*8 +end_prologue + mov rdi, rcx ; input pointer + mov [rsp+0*8], rdx ; output pointer +%else + aes_encrypt: + %ifdef __GNUC__ + sub rsp, 4*8 ; gnu/linux binary interface + mov [rsp+0*8], rsi ; output pointer + mov r8, rdx ; context + %else + sub rsp, 6*8 ; windows binary interface + mov [rsp+4*8], rsi + mov [rsp+5*8], rdi + mov rdi, rcx ; input pointer + mov [rsp+0*8], rdx ; output pointer + %endif + mov [rsp+1*8], rbx ; input pointer in rdi + mov [rsp+2*8], rbp ; output pointer in [rsp] + mov [rsp+3*8], r12 ; context in r8 +%endif + + movzx esi, byte [kptr+4*KS_LENGTH] + lea tptr, [rel enc_tab] + sub kptr, fofs + + mov eax, [rdi+0*4] + mov ebx, [rdi+1*4] + mov ecx, [rdi+2*4] + mov edx, [rdi+3*4] + + xor eax, [kptr+fofs] + xor ebx, [kptr+fofs+4] + xor ecx, [kptr+fofs+8] + xor edx, [kptr+fofs+12] + + lea kptr,[kptr+rsi] + cmp esi, 10*16 + je .3 + cmp esi, 12*16 + je .2 + cmp esi, 14*16 + je .1 + mov rax, -1 + jmp .4 + +.1: ff_rnd r9, r10, r11, r12, 13 + ff_rnd r9, r10, r11, r12, 12 +.2: ff_rnd r9, r10, r11, r12, 11 + ff_rnd r9, r10, r11, r12, 10 +.3: ff_rnd r9, r10, r11, r12, 9 + ff_rnd r9, r10, r11, r12, 8 + ff_rnd r9, r10, r11, r12, 7 + ff_rnd r9, r10, r11, r12, 6 + ff_rnd r9, r10, r11, r12, 5 + ff_rnd r9, r10, r11, r12, 4 + ff_rnd r9, r10, r11, r12, 3 + ff_rnd r9, r10, r11, r12, 2 + ff_rnd r9, r10, r11, r12, 1 + fl_rnd r9, r10, r11, r12, 0 + + mov rbx, [rsp] + mov [rbx], r9d + mov [rbx+4], r10d + mov [rbx+8], r11d + mov [rbx+12], r12d + xor rax, rax +.4: + mov rbx, [rsp+1*8] + mov rbp, [rsp+2*8] + mov r12, [rsp+3*8] +%ifdef __GNUC__ + add rsp, 4*8 + ret +%else + mov rsi, [rsp+4*8] + mov rdi, [rsp+5*8] + %ifdef _SEH_ + add rsp, 7*8 + ret + endproc_frame + %else + add rsp, 6*8 + ret + %endif +%endif + +%endif + +%ifdef DECRYPTION + + global aes_decrypt +%ifdef DLL_EXPORT + export aes_decrypt +%endif + + section .data + align 64 +dec_tab: + dec_vals v8 +%ifdef LAST_ROUND_TABLES + dec_vals w8 +%endif + + section .text + align 16 + +%ifdef _SEH_ +proc_frame aes_decrypt + alloc_stack 7*8 ; 7 to align stack to 16 bytes + save_reg rsi,4*8 + save_reg rdi,5*8 + save_reg rbx,1*8 + save_reg rbp,2*8 + save_reg r12,3*8 +end_prologue + mov rdi, rcx ; input pointer + mov [rsp+0*8], rdx ; output pointer +%else + aes_decrypt: + %ifdef __GNUC__ + sub rsp, 4*8 ; gnu/linux binary interface + mov [rsp+0*8], rsi ; output pointer + mov r8, rdx ; context + %else + sub rsp, 6*8 ; windows binary interface + mov [rsp+4*8], rsi + mov [rsp+5*8], rdi + mov rdi, rcx ; input pointer + mov [rsp+0*8], rdx ; output pointer + %endif + mov [rsp+1*8], rbx ; input pointer in rdi + mov [rsp+2*8], rbp ; output pointer in [rsp] + mov [rsp+3*8], r12 ; context in r8 +%endif + + movzx esi,byte[kptr+4*KS_LENGTH] + lea tptr, [rel dec_tab] + sub kptr, rofs + + mov eax, [rdi+0*4] + mov ebx, [rdi+1*4] + mov ecx, [rdi+2*4] + mov edx, [rdi+3*4] + +%ifdef AES_REV_DKS + mov rdi, kptr + lea kptr,[kptr+rsi] +%else + lea rdi,[kptr+rsi] +%endif + + xor eax, [rdi+rofs] + xor ebx, [rdi+rofs+4] + xor ecx, [rdi+rofs+8] + xor edx, [rdi+rofs+12] + + cmp esi, 10*16 + je .3 + cmp esi, 12*16 + je .2 + cmp esi, 14*16 + je .1 + mov rax, -1 + jmp .4 + +.1: ii_rnd r9, r10, r11, r12, 13 + ii_rnd r9, r10, r11, r12, 12 +.2: ii_rnd r9, r10, r11, r12, 11 + ii_rnd r9, r10, r11, r12, 10 +.3: ii_rnd r9, r10, r11, r12, 9 + ii_rnd r9, r10, r11, r12, 8 + ii_rnd r9, r10, r11, r12, 7 + ii_rnd r9, r10, r11, r12, 6 + ii_rnd r9, r10, r11, r12, 5 + ii_rnd r9, r10, r11, r12, 4 + ii_rnd r9, r10, r11, r12, 3 + ii_rnd r9, r10, r11, r12, 2 + ii_rnd r9, r10, r11, r12, 1 + il_rnd r9, r10, r11, r12, 0 + + mov rbx, [rsp] + mov [rbx], r9d + mov [rbx+4], r10d + mov [rbx+8], r11d + mov [rbx+12], r12d + xor rax, rax +.4: mov rbx, [rsp+1*8] + mov rbp, [rsp+2*8] + mov r12, [rsp+3*8] +%ifdef __GNUC__ + add rsp, 4*8 + ret +%else + mov rsi, [rsp+4*8] + mov rdi, [rsp+5*8] + %ifdef _SEH_ + add rsp, 7*8 + ret + endproc_frame + %else + add rsp, 6*8 + ret + %endif +%endif + +%endif diff --git a/src/Crypto/Aes_x86.asm b/src/Crypto/Aes_x86.asm index 239da3e3..3825deee 100644 --- a/src/Crypto/Aes_x86.asm +++ b/src/Crypto/Aes_x86.asm @@ -1,646 +1,646 @@ - -; --------------------------------------------------------------------------- -; Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. -; -; LICENSE TERMS -; -; The free distribution and use of this software is allowed (with or without -; changes) provided that: -; -; 1. source code distributions include the above copyright notice, this -; list of conditions and the following disclaimer; -; -; 2. binary distributions include the above copyright notice, this list -; of conditions and the following disclaimer in their documentation; -; -; 3. the name of the copyright holder is not used to endorse products -; built using this software without specific written permission. -; -; DISCLAIMER -; -; This software is provided 'as is' with no explicit or implied warranties -; in respect of its properties, including, but not limited to, correctness -; and/or fitness for purpose. -; --------------------------------------------------------------------------- -; Issue 20/12/2007 -; -; This code requires ASM_X86_V1C to be set in aesopt.h. It requires the C files -; aeskey.c and aestab.c for support. - -; -; Adapted for TrueCrypt: -; - Compatibility with NASM and GCC -; - -; An AES implementation for x86 processors using the YASM (or NASM) assembler. -; This is an assembler implementation that covers encryption and decryption -; only and is intended as a replacement of the C file aescrypt.c. It hence -; requires the file aeskey.c for keying and aestab.c for the AES tables. It -; employs full tables rather than compressed tables. - -; This code provides the standard AES block size (128 bits, 16 bytes) and the -; three standard AES key sizes (128, 192 and 256 bits). It has the same call -; interface as my C implementation. The ebx, esi, edi and ebp registers are -; preserved across calls but eax, ecx and edx and the artihmetic status flags -; are not. It is also important that the defines below match those used in the -; C code. This code uses the VC++ register saving conentions; if it is used -; with another compiler, conventions for using and saving registers may need to -; be checked (and calling conventions). The YASM command line for the VC++ -; custom build step is: -; -; yasm -Xvc -f win32 -o "$(TargetDir)\$(InputName).obj" "$(InputPath)" -; -; The calling intefaces are: -; -; AES_RETURN aes_encrypt(const unsigned char in_blk[], -; unsigned char out_blk[], const aes_encrypt_ctx cx[1]); -; -; AES_RETURN aes_decrypt(const unsigned char in_blk[], -; unsigned char out_blk[], const aes_decrypt_ctx cx[1]); -; -; AES_RETURN aes_encrypt_key(const unsigned char key[], -; const aes_encrypt_ctx cx[1]); -; -; AES_RETURN aes_decrypt_key(const unsigned char key[], -; const aes_decrypt_ctx cx[1]); -; -; AES_RETURN aes_encrypt_key(const unsigned char key[], -; unsigned int len, const aes_decrypt_ctx cx[1]); -; -; AES_RETURN aes_decrypt_key(const unsigned char key[], -; unsigned int len, const aes_decrypt_ctx cx[1]); -; -; where is 128, 102 or 256. In the last two calls the length can be in -; either bits or bytes. -; -; Comment in/out the following lines to obtain the desired subroutines. These -; selections MUST match those in the C header file aes.h - -; %define AES_128 ; define if AES with 128 bit keys is needed -; %define AES_192 ; define if AES with 192 bit keys is needed -%define AES_256 ; define if AES with 256 bit keys is needed -; %define AES_VAR ; define if a variable key size is needed -%define ENCRYPTION ; define if encryption is needed -%define DECRYPTION ; define if decryption is needed -%define AES_REV_DKS ; define if key decryption schedule is reversed -%define LAST_ROUND_TABLES ; define if tables are to be used for last round - -; offsets to parameters - -in_blk equ 4 ; input byte array address parameter -out_blk equ 8 ; output byte array address parameter -ctx equ 12 ; AES context structure -stk_spc equ 20 ; stack space -%define parms 12 ; parameter space on stack - -; The encryption key schedule has the following in memory layout where N is the -; number of rounds (10, 12 or 14): -; -; lo: | input key (round 0) | ; each round is four 32-bit words -; | encryption round 1 | -; | encryption round 2 | -; .... -; | encryption round N-1 | -; hi: | encryption round N | -; -; The decryption key schedule is normally set up so that it has the same -; layout as above by actually reversing the order of the encryption key -; schedule in memory (this happens when AES_REV_DKS is set): -; -; lo: | decryption round 0 | = | encryption round N | -; | decryption round 1 | = INV_MIX_COL[ | encryption round N-1 | ] -; | decryption round 2 | = INV_MIX_COL[ | encryption round N-2 | ] -; .... .... -; | decryption round N-1 | = INV_MIX_COL[ | encryption round 1 | ] -; hi: | decryption round N | = | input key (round 0) | -; -; with rounds except the first and last modified using inv_mix_column() -; But if AES_REV_DKS is NOT set the order of keys is left as it is for -; encryption so that it has to be accessed in reverse when used for -; decryption (although the inverse mix column modifications are done) -; -; lo: | decryption round 0 | = | input key (round 0) | -; | decryption round 1 | = INV_MIX_COL[ | encryption round 1 | ] -; | decryption round 2 | = INV_MIX_COL[ | encryption round 2 | ] -; .... .... -; | decryption round N-1 | = INV_MIX_COL[ | encryption round N-1 | ] -; hi: | decryption round N | = | encryption round N | -; -; This layout is faster when the assembler key scheduling provided here -; is used. -; -; The DLL interface must use the _stdcall convention in which the number -; of bytes of parameter space is added after an @ to the sutine's name. -; We must also remove our parameters from the stack before return (see -; the do_exit macro). Define DLL_EXPORT for the Dynamic Link Library version. - -;%define DLL_EXPORT - -; End of user defines - -%ifdef AES_VAR -%ifndef AES_128 -%define AES_128 -%endif -%ifndef AES_192 -%define AES_192 -%endif -%ifndef AES_256 -%define AES_256 -%endif -%endif - -%ifdef AES_VAR -%define KS_LENGTH 60 -%elifdef AES_256 -%define KS_LENGTH 60 -%elifdef AES_192 -%define KS_LENGTH 52 -%else -%define KS_LENGTH 44 -%endif - -; These macros implement stack based local variables - -%macro save 2 - mov [esp+4*%1],%2 -%endmacro - -%macro restore 2 - mov %1,[esp+4*%2] -%endmacro - -; the DLL has to implement the _stdcall calling interface on return -; In this case we have to take our parameters (3 4-byte pointers) -; off the stack - -%macro do_name 1-2 parms -%ifndef DLL_EXPORT - align 32 - global %1 -%1: -%else - align 32 - global %1@%2 - export _%1@%2 -%1@%2: -%endif -%endmacro - -%macro do_call 1-2 parms -%ifndef DLL_EXPORT - call %1 - add esp,%2 -%else - call %1@%2 -%endif -%endmacro - -%macro do_exit 0-1 parms -%ifdef DLL_EXPORT - ret %1 -%else - ret -%endif -%endmacro - -%ifdef ENCRYPTION - - extern t_fn - -%define etab_0(x) [t_fn+4*x] -%define etab_1(x) [t_fn+1024+4*x] -%define etab_2(x) [t_fn+2048+4*x] -%define etab_3(x) [t_fn+3072+4*x] - -%ifdef LAST_ROUND_TABLES - - extern t_fl - -%define eltab_0(x) [t_fl+4*x] -%define eltab_1(x) [t_fl+1024+4*x] -%define eltab_2(x) [t_fl+2048+4*x] -%define eltab_3(x) [t_fl+3072+4*x] - -%else - -%define etab_b(x) byte [t_fn+3072+4*x] - -%endif - -; ROUND FUNCTION. Build column[2] on ESI and column[3] on EDI that have the -; round keys pre-loaded. Build column[0] in EBP and column[1] in EBX. -; -; Input: -; -; EAX column[0] -; EBX column[1] -; ECX column[2] -; EDX column[3] -; ESI column key[round][2] -; EDI column key[round][3] -; EBP scratch -; -; Output: -; -; EBP column[0] unkeyed -; EBX column[1] unkeyed -; ESI column[2] keyed -; EDI column[3] keyed -; EAX scratch -; ECX scratch -; EDX scratch - -%macro rnd_fun 2 - - rol ebx,16 - %1 esi, cl, 0, ebp - %1 esi, dh, 1, ebp - %1 esi, bh, 3, ebp - %1 edi, dl, 0, ebp - %1 edi, ah, 1, ebp - %1 edi, bl, 2, ebp - %2 ebp, al, 0, ebp - shr ebx,16 - and eax,0xffff0000 - or eax,ebx - shr edx,16 - %1 ebp, ah, 1, ebx - %1 ebp, dh, 3, ebx - %2 ebx, dl, 2, ebx - %1 ebx, ch, 1, edx - %1 ebx, al, 0, edx - shr eax,16 - shr ecx,16 - %1 ebp, cl, 2, edx - %1 edi, ch, 3, edx - %1 esi, al, 2, edx - %1 ebx, ah, 3, edx - -%endmacro - -; Basic MOV and XOR Operations for normal rounds - -%macro nr_xor 4 - movzx %4,%2 - xor %1,etab_%3(%4) -%endmacro - -%macro nr_mov 4 - movzx %4,%2 - mov %1,etab_%3(%4) -%endmacro - -; Basic MOV and XOR Operations for last round - -%ifdef LAST_ROUND_TABLES - - %macro lr_xor 4 - movzx %4,%2 - xor %1,eltab_%3(%4) - %endmacro - - %macro lr_mov 4 - movzx %4,%2 - mov %1,eltab_%3(%4) - %endmacro - -%else - - %macro lr_xor 4 - movzx %4,%2 - movzx %4,etab_b(%4) - %if %3 != 0 - shl %4,8*%3 - %endif - xor %1,%4 - %endmacro - - %macro lr_mov 4 - movzx %4,%2 - movzx %1,etab_b(%4) - %if %3 != 0 - shl %1,8*%3 - %endif - %endmacro - -%endif - -%macro enc_round 0 - - add ebp,16 - save 0,ebp - mov esi,[ebp+8] - mov edi,[ebp+12] - - rnd_fun nr_xor, nr_mov - - mov eax,ebp - mov ecx,esi - mov edx,edi - restore ebp,0 - xor eax,[ebp] - xor ebx,[ebp+4] - -%endmacro - -%macro enc_last_round 0 - - add ebp,16 - save 0,ebp - mov esi,[ebp+8] - mov edi,[ebp+12] - - rnd_fun lr_xor, lr_mov - - mov eax,ebp - restore ebp,0 - xor eax,[ebp] - xor ebx,[ebp+4] - -%endmacro - - section .text align=32 - -; AES Encryption Subroutine - - do_name aes_encrypt - - sub esp,stk_spc - mov [esp+16],ebp - mov [esp+12],ebx - mov [esp+ 8],esi - mov [esp+ 4],edi - - mov esi,[esp+in_blk+stk_spc] ; input pointer - mov eax,[esi ] - mov ebx,[esi+ 4] - mov ecx,[esi+ 8] - mov edx,[esi+12] - - mov ebp,[esp+ctx+stk_spc] ; key pointer - movzx edi,byte [ebp+4*KS_LENGTH] - xor eax,[ebp ] - xor ebx,[ebp+ 4] - xor ecx,[ebp+ 8] - xor edx,[ebp+12] - -; determine the number of rounds - - cmp edi,10*16 - je .3 - cmp edi,12*16 - je .2 - cmp edi,14*16 - je .1 - mov eax,-1 - jmp .5 - -.1: enc_round - enc_round -.2: enc_round - enc_round -.3: enc_round - enc_round - enc_round - enc_round - enc_round - enc_round - enc_round - enc_round - enc_round - enc_last_round - - mov edx,[esp+out_blk+stk_spc] - mov [edx],eax - mov [edx+4],ebx - mov [edx+8],esi - mov [edx+12],edi - xor eax,eax - -.5: mov ebp,[esp+16] - mov ebx,[esp+12] - mov esi,[esp+ 8] - mov edi,[esp+ 4] - add esp,stk_spc - do_exit - -%endif - -%ifdef DECRYPTION - - extern t_in - -%define dtab_0(x) [t_in+4*x] -%define dtab_1(x) [t_in+1024+4*x] -%define dtab_2(x) [t_in+2048+4*x] -%define dtab_3(x) [t_in+3072+4*x] - -%ifdef LAST_ROUND_TABLES - - extern t_il - -%define dltab_0(x) [t_il+4*x] -%define dltab_1(x) [t_il+1024+4*x] -%define dltab_2(x) [t_il+2048+4*x] -%define dltab_3(x) [t_il+3072+4*x] - -%else - - extern _t_ibox - -%define dtab_x(x) byte [_t_ibox+x] - -%endif - -%macro irn_fun 2 - - rol eax,16 - %1 esi, cl, 0, ebp - %1 esi, bh, 1, ebp - %1 esi, al, 2, ebp - %1 edi, dl, 0, ebp - %1 edi, ch, 1, ebp - %1 edi, ah, 3, ebp - %2 ebp, bl, 0, ebp - shr eax,16 - and ebx,0xffff0000 - or ebx,eax - shr ecx,16 - %1 ebp, bh, 1, eax - %1 ebp, ch, 3, eax - %2 eax, cl, 2, ecx - %1 eax, bl, 0, ecx - %1 eax, dh, 1, ecx - shr ebx,16 - shr edx,16 - %1 esi, dh, 3, ecx - %1 ebp, dl, 2, ecx - %1 eax, bh, 3, ecx - %1 edi, bl, 2, ecx - -%endmacro - -; Basic MOV and XOR Operations for normal rounds - -%macro ni_xor 4 - movzx %4,%2 - xor %1,dtab_%3(%4) -%endmacro - -%macro ni_mov 4 - movzx %4,%2 - mov %1,dtab_%3(%4) -%endmacro - -; Basic MOV and XOR Operations for last round - -%ifdef LAST_ROUND_TABLES - -%macro li_xor 4 - movzx %4,%2 - xor %1,dltab_%3(%4) -%endmacro - -%macro li_mov 4 - movzx %4,%2 - mov %1,dltab_%3(%4) -%endmacro - -%else - - %macro li_xor 4 - movzx %4,%2 - movzx %4,dtab_x(%4) - %if %3 != 0 - shl %4,8*%3 - %endif - xor %1,%4 - %endmacro - - %macro li_mov 4 - movzx %4,%2 - movzx %1,dtab_x(%4) - %if %3 != 0 - shl %1,8*%3 - %endif - %endmacro - -%endif - -%macro dec_round 0 - -%ifdef AES_REV_DKS - add ebp,16 -%else - sub ebp,16 -%endif - save 0,ebp - mov esi,[ebp+8] - mov edi,[ebp+12] - - irn_fun ni_xor, ni_mov - - mov ebx,ebp - mov ecx,esi - mov edx,edi - restore ebp,0 - xor eax,[ebp] - xor ebx,[ebp+4] - -%endmacro - -%macro dec_last_round 0 - -%ifdef AES_REV_DKS - add ebp,16 -%else - sub ebp,16 -%endif - save 0,ebp - mov esi,[ebp+8] - mov edi,[ebp+12] - - irn_fun li_xor, li_mov - - mov ebx,ebp - restore ebp,0 - xor eax,[ebp] - xor ebx,[ebp+4] - -%endmacro - - section .text - -; AES Decryption Subroutine - - do_name aes_decrypt - - sub esp,stk_spc - mov [esp+16],ebp - mov [esp+12],ebx - mov [esp+ 8],esi - mov [esp+ 4],edi - -; input four columns and xor in first round key - - mov esi,[esp+in_blk+stk_spc] ; input pointer - mov eax,[esi ] - mov ebx,[esi+ 4] - mov ecx,[esi+ 8] - mov edx,[esi+12] - lea esi,[esi+16] - - mov ebp,[esp+ctx+stk_spc] ; key pointer - movzx edi,byte[ebp+4*KS_LENGTH] -%ifndef AES_REV_DKS ; if decryption key schedule is not reversed - lea ebp,[ebp+edi] ; we have to access it from the top down -%endif - xor eax,[ebp ] ; key schedule - xor ebx,[ebp+ 4] - xor ecx,[ebp+ 8] - xor edx,[ebp+12] - -; determine the number of rounds - - cmp edi,10*16 - je .3 - cmp edi,12*16 - je .2 - cmp edi,14*16 - je .1 - mov eax,-1 - jmp .5 - -.1: dec_round - dec_round -.2: dec_round - dec_round -.3: dec_round - dec_round - dec_round - dec_round - dec_round - dec_round - dec_round - dec_round - dec_round - dec_last_round - -; move final values to the output array. - - mov ebp,[esp+out_blk+stk_spc] - mov [ebp],eax - mov [ebp+4],ebx - mov [ebp+8],esi - mov [ebp+12],edi - xor eax,eax - -.5: mov ebp,[esp+16] - mov ebx,[esp+12] - mov esi,[esp+ 8] - mov edi,[esp+ 4] - add esp,stk_spc - do_exit - -%endif + +; --------------------------------------------------------------------------- +; Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. +; +; LICENSE TERMS +; +; The free distribution and use of this software is allowed (with or without +; changes) provided that: +; +; 1. source code distributions include the above copyright notice, this +; list of conditions and the following disclaimer; +; +; 2. binary distributions include the above copyright notice, this list +; of conditions and the following disclaimer in their documentation; +; +; 3. the name of the copyright holder is not used to endorse products +; built using this software without specific written permission. +; +; DISCLAIMER +; +; This software is provided 'as is' with no explicit or implied warranties +; in respect of its properties, including, but not limited to, correctness +; and/or fitness for purpose. +; --------------------------------------------------------------------------- +; Issue 20/12/2007 +; +; This code requires ASM_X86_V1C to be set in aesopt.h. It requires the C files +; aeskey.c and aestab.c for support. + +; +; Adapted for TrueCrypt: +; - Compatibility with NASM and GCC +; + +; An AES implementation for x86 processors using the YASM (or NASM) assembler. +; This is an assembler implementation that covers encryption and decryption +; only and is intended as a replacement of the C file aescrypt.c. It hence +; requires the file aeskey.c for keying and aestab.c for the AES tables. It +; employs full tables rather than compressed tables. + +; This code provides the standard AES block size (128 bits, 16 bytes) and the +; three standard AES key sizes (128, 192 and 256 bits). It has the same call +; interface as my C implementation. The ebx, esi, edi and ebp registers are +; preserved across calls but eax, ecx and edx and the artihmetic status flags +; are not. It is also important that the defines below match those used in the +; C code. This code uses the VC++ register saving conentions; if it is used +; with another compiler, conventions for using and saving registers may need to +; be checked (and calling conventions). The YASM command line for the VC++ +; custom build step is: +; +; yasm -Xvc -f win32 -o "$(TargetDir)\$(InputName).obj" "$(InputPath)" +; +; The calling intefaces are: +; +; AES_RETURN aes_encrypt(const unsigned char in_blk[], +; unsigned char out_blk[], const aes_encrypt_ctx cx[1]); +; +; AES_RETURN aes_decrypt(const unsigned char in_blk[], +; unsigned char out_blk[], const aes_decrypt_ctx cx[1]); +; +; AES_RETURN aes_encrypt_key(const unsigned char key[], +; const aes_encrypt_ctx cx[1]); +; +; AES_RETURN aes_decrypt_key(const unsigned char key[], +; const aes_decrypt_ctx cx[1]); +; +; AES_RETURN aes_encrypt_key(const unsigned char key[], +; unsigned int len, const aes_decrypt_ctx cx[1]); +; +; AES_RETURN aes_decrypt_key(const unsigned char key[], +; unsigned int len, const aes_decrypt_ctx cx[1]); +; +; where is 128, 102 or 256. In the last two calls the length can be in +; either bits or bytes. +; +; Comment in/out the following lines to obtain the desired subroutines. These +; selections MUST match those in the C header file aes.h + +; %define AES_128 ; define if AES with 128 bit keys is needed +; %define AES_192 ; define if AES with 192 bit keys is needed +%define AES_256 ; define if AES with 256 bit keys is needed +; %define AES_VAR ; define if a variable key size is needed +%define ENCRYPTION ; define if encryption is needed +%define DECRYPTION ; define if decryption is needed +%define AES_REV_DKS ; define if key decryption schedule is reversed +%define LAST_ROUND_TABLES ; define if tables are to be used for last round + +; offsets to parameters + +in_blk equ 4 ; input byte array address parameter +out_blk equ 8 ; output byte array address parameter +ctx equ 12 ; AES context structure +stk_spc equ 20 ; stack space +%define parms 12 ; parameter space on stack + +; The encryption key schedule has the following in memory layout where N is the +; number of rounds (10, 12 or 14): +; +; lo: | input key (round 0) | ; each round is four 32-bit words +; | encryption round 1 | +; | encryption round 2 | +; .... +; | encryption round N-1 | +; hi: | encryption round N | +; +; The decryption key schedule is normally set up so that it has the same +; layout as above by actually reversing the order of the encryption key +; schedule in memory (this happens when AES_REV_DKS is set): +; +; lo: | decryption round 0 | = | encryption round N | +; | decryption round 1 | = INV_MIX_COL[ | encryption round N-1 | ] +; | decryption round 2 | = INV_MIX_COL[ | encryption round N-2 | ] +; .... .... +; | decryption round N-1 | = INV_MIX_COL[ | encryption round 1 | ] +; hi: | decryption round N | = | input key (round 0) | +; +; with rounds except the first and last modified using inv_mix_column() +; But if AES_REV_DKS is NOT set the order of keys is left as it is for +; encryption so that it has to be accessed in reverse when used for +; decryption (although the inverse mix column modifications are done) +; +; lo: | decryption round 0 | = | input key (round 0) | +; | decryption round 1 | = INV_MIX_COL[ | encryption round 1 | ] +; | decryption round 2 | = INV_MIX_COL[ | encryption round 2 | ] +; .... .... +; | decryption round N-1 | = INV_MIX_COL[ | encryption round N-1 | ] +; hi: | decryption round N | = | encryption round N | +; +; This layout is faster when the assembler key scheduling provided here +; is used. +; +; The DLL interface must use the _stdcall convention in which the number +; of bytes of parameter space is added after an @ to the sutine's name. +; We must also remove our parameters from the stack before return (see +; the do_exit macro). Define DLL_EXPORT for the Dynamic Link Library version. + +;%define DLL_EXPORT + +; End of user defines + +%ifdef AES_VAR +%ifndef AES_128 +%define AES_128 +%endif +%ifndef AES_192 +%define AES_192 +%endif +%ifndef AES_256 +%define AES_256 +%endif +%endif + +%ifdef AES_VAR +%define KS_LENGTH 60 +%elifdef AES_256 +%define KS_LENGTH 60 +%elifdef AES_192 +%define KS_LENGTH 52 +%else +%define KS_LENGTH 44 +%endif + +; These macros implement stack based local variables + +%macro save 2 + mov [esp+4*%1],%2 +%endmacro + +%macro restore 2 + mov %1,[esp+4*%2] +%endmacro + +; the DLL has to implement the _stdcall calling interface on return +; In this case we have to take our parameters (3 4-byte pointers) +; off the stack + +%macro do_name 1-2 parms +%ifndef DLL_EXPORT + align 32 + global %1 +%1: +%else + align 32 + global %1@%2 + export _%1@%2 +%1@%2: +%endif +%endmacro + +%macro do_call 1-2 parms +%ifndef DLL_EXPORT + call %1 + add esp,%2 +%else + call %1@%2 +%endif +%endmacro + +%macro do_exit 0-1 parms +%ifdef DLL_EXPORT + ret %1 +%else + ret +%endif +%endmacro + +%ifdef ENCRYPTION + + extern t_fn + +%define etab_0(x) [t_fn+4*x] +%define etab_1(x) [t_fn+1024+4*x] +%define etab_2(x) [t_fn+2048+4*x] +%define etab_3(x) [t_fn+3072+4*x] + +%ifdef LAST_ROUND_TABLES + + extern t_fl + +%define eltab_0(x) [t_fl+4*x] +%define eltab_1(x) [t_fl+1024+4*x] +%define eltab_2(x) [t_fl+2048+4*x] +%define eltab_3(x) [t_fl+3072+4*x] + +%else + +%define etab_b(x) byte [t_fn+3072+4*x] + +%endif + +; ROUND FUNCTION. Build column[2] on ESI and column[3] on EDI that have the +; round keys pre-loaded. Build column[0] in EBP and column[1] in EBX. +; +; Input: +; +; EAX column[0] +; EBX column[1] +; ECX column[2] +; EDX column[3] +; ESI column key[round][2] +; EDI column key[round][3] +; EBP scratch +; +; Output: +; +; EBP column[0] unkeyed +; EBX column[1] unkeyed +; ESI column[2] keyed +; EDI column[3] keyed +; EAX scratch +; ECX scratch +; EDX scratch + +%macro rnd_fun 2 + + rol ebx,16 + %1 esi, cl, 0, ebp + %1 esi, dh, 1, ebp + %1 esi, bh, 3, ebp + %1 edi, dl, 0, ebp + %1 edi, ah, 1, ebp + %1 edi, bl, 2, ebp + %2 ebp, al, 0, ebp + shr ebx,16 + and eax,0xffff0000 + or eax,ebx + shr edx,16 + %1 ebp, ah, 1, ebx + %1 ebp, dh, 3, ebx + %2 ebx, dl, 2, ebx + %1 ebx, ch, 1, edx + %1 ebx, al, 0, edx + shr eax,16 + shr ecx,16 + %1 ebp, cl, 2, edx + %1 edi, ch, 3, edx + %1 esi, al, 2, edx + %1 ebx, ah, 3, edx + +%endmacro + +; Basic MOV and XOR Operations for normal rounds + +%macro nr_xor 4 + movzx %4,%2 + xor %1,etab_%3(%4) +%endmacro + +%macro nr_mov 4 + movzx %4,%2 + mov %1,etab_%3(%4) +%endmacro + +; Basic MOV and XOR Operations for last round + +%ifdef LAST_ROUND_TABLES + + %macro lr_xor 4 + movzx %4,%2 + xor %1,eltab_%3(%4) + %endmacro + + %macro lr_mov 4 + movzx %4,%2 + mov %1,eltab_%3(%4) + %endmacro + +%else + + %macro lr_xor 4 + movzx %4,%2 + movzx %4,etab_b(%4) + %if %3 != 0 + shl %4,8*%3 + %endif + xor %1,%4 + %endmacro + + %macro lr_mov 4 + movzx %4,%2 + movzx %1,etab_b(%4) + %if %3 != 0 + shl %1,8*%3 + %endif + %endmacro + +%endif + +%macro enc_round 0 + + add ebp,16 + save 0,ebp + mov esi,[ebp+8] + mov edi,[ebp+12] + + rnd_fun nr_xor, nr_mov + + mov eax,ebp + mov ecx,esi + mov edx,edi + restore ebp,0 + xor eax,[ebp] + xor ebx,[ebp+4] + +%endmacro + +%macro enc_last_round 0 + + add ebp,16 + save 0,ebp + mov esi,[ebp+8] + mov edi,[ebp+12] + + rnd_fun lr_xor, lr_mov + + mov eax,ebp + restore ebp,0 + xor eax,[ebp] + xor ebx,[ebp+4] + +%endmacro + + section .text align=32 + +; AES Encryption Subroutine + + do_name aes_encrypt + + sub esp,stk_spc + mov [esp+16],ebp + mov [esp+12],ebx + mov [esp+ 8],esi + mov [esp+ 4],edi + + mov esi,[esp+in_blk+stk_spc] ; input pointer + mov eax,[esi ] + mov ebx,[esi+ 4] + mov ecx,[esi+ 8] + mov edx,[esi+12] + + mov ebp,[esp+ctx+stk_spc] ; key pointer + movzx edi,byte [ebp+4*KS_LENGTH] + xor eax,[ebp ] + xor ebx,[ebp+ 4] + xor ecx,[ebp+ 8] + xor edx,[ebp+12] + +; determine the number of rounds + + cmp edi,10*16 + je .3 + cmp edi,12*16 + je .2 + cmp edi,14*16 + je .1 + mov eax,-1 + jmp .5 + +.1: enc_round + enc_round +.2: enc_round + enc_round +.3: enc_round + enc_round + enc_round + enc_round + enc_round + enc_round + enc_round + enc_round + enc_round + enc_last_round + + mov edx,[esp+out_blk+stk_spc] + mov [edx],eax + mov [edx+4],ebx + mov [edx+8],esi + mov [edx+12],edi + xor eax,eax + +.5: mov ebp,[esp+16] + mov ebx,[esp+12] + mov esi,[esp+ 8] + mov edi,[esp+ 4] + add esp,stk_spc + do_exit + +%endif + +%ifdef DECRYPTION + + extern t_in + +%define dtab_0(x) [t_in+4*x] +%define dtab_1(x) [t_in+1024+4*x] +%define dtab_2(x) [t_in+2048+4*x] +%define dtab_3(x) [t_in+3072+4*x] + +%ifdef LAST_ROUND_TABLES + + extern t_il + +%define dltab_0(x) [t_il+4*x] +%define dltab_1(x) [t_il+1024+4*x] +%define dltab_2(x) [t_il+2048+4*x] +%define dltab_3(x) [t_il+3072+4*x] + +%else + + extern _t_ibox + +%define dtab_x(x) byte [_t_ibox+x] + +%endif + +%macro irn_fun 2 + + rol eax,16 + %1 esi, cl, 0, ebp + %1 esi, bh, 1, ebp + %1 esi, al, 2, ebp + %1 edi, dl, 0, ebp + %1 edi, ch, 1, ebp + %1 edi, ah, 3, ebp + %2 ebp, bl, 0, ebp + shr eax,16 + and ebx,0xffff0000 + or ebx,eax + shr ecx,16 + %1 ebp, bh, 1, eax + %1 ebp, ch, 3, eax + %2 eax, cl, 2, ecx + %1 eax, bl, 0, ecx + %1 eax, dh, 1, ecx + shr ebx,16 + shr edx,16 + %1 esi, dh, 3, ecx + %1 ebp, dl, 2, ecx + %1 eax, bh, 3, ecx + %1 edi, bl, 2, ecx + +%endmacro + +; Basic MOV and XOR Operations for normal rounds + +%macro ni_xor 4 + movzx %4,%2 + xor %1,dtab_%3(%4) +%endmacro + +%macro ni_mov 4 + movzx %4,%2 + mov %1,dtab_%3(%4) +%endmacro + +; Basic MOV and XOR Operations for last round + +%ifdef LAST_ROUND_TABLES + +%macro li_xor 4 + movzx %4,%2 + xor %1,dltab_%3(%4) +%endmacro + +%macro li_mov 4 + movzx %4,%2 + mov %1,dltab_%3(%4) +%endmacro + +%else + + %macro li_xor 4 + movzx %4,%2 + movzx %4,dtab_x(%4) + %if %3 != 0 + shl %4,8*%3 + %endif + xor %1,%4 + %endmacro + + %macro li_mov 4 + movzx %4,%2 + movzx %1,dtab_x(%4) + %if %3 != 0 + shl %1,8*%3 + %endif + %endmacro + +%endif + +%macro dec_round 0 + +%ifdef AES_REV_DKS + add ebp,16 +%else + sub ebp,16 +%endif + save 0,ebp + mov esi,[ebp+8] + mov edi,[ebp+12] + + irn_fun ni_xor, ni_mov + + mov ebx,ebp + mov ecx,esi + mov edx,edi + restore ebp,0 + xor eax,[ebp] + xor ebx,[ebp+4] + +%endmacro + +%macro dec_last_round 0 + +%ifdef AES_REV_DKS + add ebp,16 +%else + sub ebp,16 +%endif + save 0,ebp + mov esi,[ebp+8] + mov edi,[ebp+12] + + irn_fun li_xor, li_mov + + mov ebx,ebp + restore ebp,0 + xor eax,[ebp] + xor ebx,[ebp+4] + +%endmacro + + section .text + +; AES Decryption Subroutine + + do_name aes_decrypt + + sub esp,stk_spc + mov [esp+16],ebp + mov [esp+12],ebx + mov [esp+ 8],esi + mov [esp+ 4],edi + +; input four columns and xor in first round key + + mov esi,[esp+in_blk+stk_spc] ; input pointer + mov eax,[esi ] + mov ebx,[esi+ 4] + mov ecx,[esi+ 8] + mov edx,[esi+12] + lea esi,[esi+16] + + mov ebp,[esp+ctx+stk_spc] ; key pointer + movzx edi,byte[ebp+4*KS_LENGTH] +%ifndef AES_REV_DKS ; if decryption key schedule is not reversed + lea ebp,[ebp+edi] ; we have to access it from the top down +%endif + xor eax,[ebp ] ; key schedule + xor ebx,[ebp+ 4] + xor ecx,[ebp+ 8] + xor edx,[ebp+12] + +; determine the number of rounds + + cmp edi,10*16 + je .3 + cmp edi,12*16 + je .2 + cmp edi,14*16 + je .1 + mov eax,-1 + jmp .5 + +.1: dec_round + dec_round +.2: dec_round + dec_round +.3: dec_round + dec_round + dec_round + dec_round + dec_round + dec_round + dec_round + dec_round + dec_round + dec_last_round + +; move final values to the output array. + + mov ebp,[esp+out_blk+stk_spc] + mov [ebp],eax + mov [ebp+4],ebx + mov [ebp+8],esi + mov [ebp+12],edi + xor eax,eax + +.5: mov ebp,[esp+16] + mov ebx,[esp+12] + mov esi,[esp+ 8] + mov edi,[esp+ 4] + add esp,stk_spc + do_exit + +%endif diff --git a/src/Crypto/Aescrypt.c b/src/Crypto/Aescrypt.c index c77ec675..46175981 100644 --- a/src/Crypto/Aescrypt.c +++ b/src/Crypto/Aescrypt.c @@ -1,311 +1,311 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software is allowed (with or without - changes) provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue Date: 20/12/2007 -*/ - -#include "Aesopt.h" -#include "Aestab.h" - -#if defined(__cplusplus) -extern "C" -{ -#endif - -#define si(y,x,k,c) (s(y,c) = word_in(x, c) ^ (k)[c]) -#define so(y,x,c) word_out(y, c, s(x,c)) - -#if defined(ARRAYS) -#define locals(y,x) x[4],y[4] -#else -#define locals(y,x) x##0,x##1,x##2,x##3,y##0,y##1,y##2,y##3 -#endif - -#define l_copy(y, x) s(y,0) = s(x,0); s(y,1) = s(x,1); \ - s(y,2) = s(x,2); s(y,3) = s(x,3); -#define state_in(y,x,k) si(y,x,k,0); si(y,x,k,1); si(y,x,k,2); si(y,x,k,3) -#define state_out(y,x) so(y,x,0); so(y,x,1); so(y,x,2); so(y,x,3) -#define round(rm,y,x,k) rm(y,x,k,0); rm(y,x,k,1); rm(y,x,k,2); rm(y,x,k,3) - -#if ( FUNCS_IN_C & ENCRYPTION_IN_C ) - -/* Visual C++ .Net v7.1 provides the fastest encryption code when using - Pentium optimiation with small code but this is poor for decryption - so we need to control this with the following VC++ pragmas -*/ - -#if defined( _MSC_VER ) && !defined( _WIN64 ) -#pragma optimize( "s", on ) -#endif - -/* Given the column (c) of the output state variable, the following - macros give the input state variables which are needed in its - computation for each row (r) of the state. All the alternative - macros give the same end values but expand into different ways - of calculating these values. In particular the complex macro - used for dynamically variable block sizes is designed to expand - to a compile time constant whenever possible but will expand to - conditional clauses on some branches (I am grateful to Frank - Yellin for this construction) -*/ - -#define fwd_var(x,r,c)\ - ( r == 0 ? ( c == 0 ? s(x,0) : c == 1 ? s(x,1) : c == 2 ? s(x,2) : s(x,3))\ - : r == 1 ? ( c == 0 ? s(x,1) : c == 1 ? s(x,2) : c == 2 ? s(x,3) : s(x,0))\ - : r == 2 ? ( c == 0 ? s(x,2) : c == 1 ? s(x,3) : c == 2 ? s(x,0) : s(x,1))\ - : ( c == 0 ? s(x,3) : c == 1 ? s(x,0) : c == 2 ? s(x,1) : s(x,2))) - -#if defined(FT4_SET) -#undef dec_fmvars -#define fwd_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ four_tables(x,t_use(f,n),fwd_var,rf1,c)) -#elif defined(FT1_SET) -#undef dec_fmvars -#define fwd_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ one_table(x,upr,t_use(f,n),fwd_var,rf1,c)) -#else -#define fwd_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ fwd_mcol(no_table(x,t_use(s,box),fwd_var,rf1,c))) -#endif - -#if defined(FL4_SET) -#define fwd_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ four_tables(x,t_use(f,l),fwd_var,rf1,c)) -#elif defined(FL1_SET) -#define fwd_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ one_table(x,ups,t_use(f,l),fwd_var,rf1,c)) -#else -#define fwd_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ no_table(x,t_use(s,box),fwd_var,rf1,c)) -#endif - -AES_RETURN aes_encrypt(const unsigned char *in, unsigned char *out, const aes_encrypt_ctx cx[1]) -{ uint_32t locals(b0, b1); - const uint_32t *kp; -#if defined( dec_fmvars ) - dec_fmvars; /* declare variables for fwd_mcol() if needed */ -#endif - -#if defined( AES_ERR_CHK ) - if( cx->inf.b[0] != 10 * 16 && cx->inf.b[0] != 12 * 16 && cx->inf.b[0] != 14 * 16 ) - return EXIT_FAILURE; -#endif - - kp = cx->ks; - state_in(b0, in, kp); - -#if (ENC_UNROLL == FULL) - - switch(cx->inf.b[0]) - { - case 14 * 16: - round(fwd_rnd, b1, b0, kp + 1 * N_COLS); - round(fwd_rnd, b0, b1, kp + 2 * N_COLS); - kp += 2 * N_COLS; - case 12 * 16: - round(fwd_rnd, b1, b0, kp + 1 * N_COLS); - round(fwd_rnd, b0, b1, kp + 2 * N_COLS); - kp += 2 * N_COLS; - case 10 * 16: - round(fwd_rnd, b1, b0, kp + 1 * N_COLS); - round(fwd_rnd, b0, b1, kp + 2 * N_COLS); - round(fwd_rnd, b1, b0, kp + 3 * N_COLS); - round(fwd_rnd, b0, b1, kp + 4 * N_COLS); - round(fwd_rnd, b1, b0, kp + 5 * N_COLS); - round(fwd_rnd, b0, b1, kp + 6 * N_COLS); - round(fwd_rnd, b1, b0, kp + 7 * N_COLS); - round(fwd_rnd, b0, b1, kp + 8 * N_COLS); - round(fwd_rnd, b1, b0, kp + 9 * N_COLS); - round(fwd_lrnd, b0, b1, kp +10 * N_COLS); - } - -#else - -#if (ENC_UNROLL == PARTIAL) - { uint_32t rnd; - for(rnd = 0; rnd < (cx->inf.b[0] >> 5) - 1; ++rnd) - { - kp += N_COLS; - round(fwd_rnd, b1, b0, kp); - kp += N_COLS; - round(fwd_rnd, b0, b1, kp); - } - kp += N_COLS; - round(fwd_rnd, b1, b0, kp); -#else - { uint_32t rnd; - for(rnd = 0; rnd < (cx->inf.b[0] >> 4) - 1; ++rnd) - { - kp += N_COLS; - round(fwd_rnd, b1, b0, kp); - l_copy(b0, b1); - } -#endif - kp += N_COLS; - round(fwd_lrnd, b0, b1, kp); - } -#endif - - state_out(out, b0); - -#if defined( AES_ERR_CHK ) - return EXIT_SUCCESS; -#endif -} - -#endif - -#if ( FUNCS_IN_C & DECRYPTION_IN_C) - -/* Visual C++ .Net v7.1 provides the fastest encryption code when using - Pentium optimiation with small code but this is poor for decryption - so we need to control this with the following VC++ pragmas -*/ - -#if defined( _MSC_VER ) && !defined( _WIN64 ) -#pragma optimize( "t", on ) -#endif - -/* Given the column (c) of the output state variable, the following - macros give the input state variables which are needed in its - computation for each row (r) of the state. All the alternative - macros give the same end values but expand into different ways - of calculating these values. In particular the complex macro - used for dynamically variable block sizes is designed to expand - to a compile time constant whenever possible but will expand to - conditional clauses on some branches (I am grateful to Frank - Yellin for this construction) -*/ - -#define inv_var(x,r,c)\ - ( r == 0 ? ( c == 0 ? s(x,0) : c == 1 ? s(x,1) : c == 2 ? s(x,2) : s(x,3))\ - : r == 1 ? ( c == 0 ? s(x,3) : c == 1 ? s(x,0) : c == 2 ? s(x,1) : s(x,2))\ - : r == 2 ? ( c == 0 ? s(x,2) : c == 1 ? s(x,3) : c == 2 ? s(x,0) : s(x,1))\ - : ( c == 0 ? s(x,1) : c == 1 ? s(x,2) : c == 2 ? s(x,3) : s(x,0))) - -#if defined(IT4_SET) -#undef dec_imvars -#define inv_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ four_tables(x,t_use(i,n),inv_var,rf1,c)) -#elif defined(IT1_SET) -#undef dec_imvars -#define inv_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ one_table(x,upr,t_use(i,n),inv_var,rf1,c)) -#else -#define inv_rnd(y,x,k,c) (s(y,c) = inv_mcol((k)[c] ^ no_table(x,t_use(i,box),inv_var,rf1,c))) -#endif - -#if defined(IL4_SET) -#define inv_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ four_tables(x,t_use(i,l),inv_var,rf1,c)) -#elif defined(IL1_SET) -#define inv_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ one_table(x,ups,t_use(i,l),inv_var,rf1,c)) -#else -#define inv_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ no_table(x,t_use(i,box),inv_var,rf1,c)) -#endif - -/* This code can work with the decryption key schedule in the */ -/* order that is used for encrytpion (where the 1st decryption */ -/* round key is at the high end ot the schedule) or with a key */ -/* schedule that has been reversed to put the 1st decryption */ -/* round key at the low end of the schedule in memory (when */ -/* AES_REV_DKS is defined) */ - -#ifdef AES_REV_DKS -#define key_ofs 0 -#define rnd_key(n) (kp + n * N_COLS) -#else -#define key_ofs 1 -#define rnd_key(n) (kp - n * N_COLS) -#endif - -AES_RETURN aes_decrypt(const unsigned char *in, unsigned char *out, const aes_decrypt_ctx cx[1]) -{ uint_32t locals(b0, b1); -#if defined( dec_imvars ) - dec_imvars; /* declare variables for inv_mcol() if needed */ -#endif - const uint_32t *kp; - -#if defined( AES_ERR_CHK ) - if( cx->inf.b[0] != 10 * 16 && cx->inf.b[0] != 12 * 16 && cx->inf.b[0] != 14 * 16 ) - return EXIT_FAILURE; -#endif - - kp = cx->ks + (key_ofs ? (cx->inf.b[0] >> 2) : 0); - state_in(b0, in, kp); - -#if (DEC_UNROLL == FULL) - - kp = cx->ks + (key_ofs ? 0 : (cx->inf.b[0] >> 2)); - switch(cx->inf.b[0]) - { - case 14 * 16: - round(inv_rnd, b1, b0, rnd_key(-13)); - round(inv_rnd, b0, b1, rnd_key(-12)); - case 12 * 16: - round(inv_rnd, b1, b0, rnd_key(-11)); - round(inv_rnd, b0, b1, rnd_key(-10)); - case 10 * 16: - round(inv_rnd, b1, b0, rnd_key(-9)); - round(inv_rnd, b0, b1, rnd_key(-8)); - round(inv_rnd, b1, b0, rnd_key(-7)); - round(inv_rnd, b0, b1, rnd_key(-6)); - round(inv_rnd, b1, b0, rnd_key(-5)); - round(inv_rnd, b0, b1, rnd_key(-4)); - round(inv_rnd, b1, b0, rnd_key(-3)); - round(inv_rnd, b0, b1, rnd_key(-2)); - round(inv_rnd, b1, b0, rnd_key(-1)); - round(inv_lrnd, b0, b1, rnd_key( 0)); - } - -#else - -#if (DEC_UNROLL == PARTIAL) - { uint_32t rnd; - for(rnd = 0; rnd < (cx->inf.b[0] >> 5) - 1; ++rnd) - { - kp = rnd_key(1); - round(inv_rnd, b1, b0, kp); - kp = rnd_key(1); - round(inv_rnd, b0, b1, kp); - } - kp = rnd_key(1); - round(inv_rnd, b1, b0, kp); -#else - { uint_32t rnd; - for(rnd = 0; rnd < (cx->inf.b[0] >> 4) - 1; ++rnd) - { - kp = rnd_key(1); - round(inv_rnd, b1, b0, kp); - l_copy(b0, b1); - } -#endif - kp = rnd_key(1); - round(inv_lrnd, b0, b1, kp); - } -#endif - - state_out(out, b0); - -#if defined( AES_ERR_CHK ) - return EXIT_SUCCESS; -#endif -} - -#endif - -#if defined(__cplusplus) -} -#endif +/* + --------------------------------------------------------------------------- + Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software is allowed (with or without + changes) provided that: + + 1. source code distributions include the above copyright notice, this + list of conditions and the following disclaimer; + + 2. binary distributions include the above copyright notice, this list + of conditions and the following disclaimer in their documentation; + + 3. the name of the copyright holder is not used to endorse products + built using this software without specific written permission. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + Issue Date: 20/12/2007 +*/ + +#include "Aesopt.h" +#include "Aestab.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif + +#define si(y,x,k,c) (s(y,c) = word_in(x, c) ^ (k)[c]) +#define so(y,x,c) word_out(y, c, s(x,c)) + +#if defined(ARRAYS) +#define locals(y,x) x[4],y[4] +#else +#define locals(y,x) x##0,x##1,x##2,x##3,y##0,y##1,y##2,y##3 +#endif + +#define l_copy(y, x) s(y,0) = s(x,0); s(y,1) = s(x,1); \ + s(y,2) = s(x,2); s(y,3) = s(x,3); +#define state_in(y,x,k) si(y,x,k,0); si(y,x,k,1); si(y,x,k,2); si(y,x,k,3) +#define state_out(y,x) so(y,x,0); so(y,x,1); so(y,x,2); so(y,x,3) +#define round(rm,y,x,k) rm(y,x,k,0); rm(y,x,k,1); rm(y,x,k,2); rm(y,x,k,3) + +#if ( FUNCS_IN_C & ENCRYPTION_IN_C ) + +/* Visual C++ .Net v7.1 provides the fastest encryption code when using + Pentium optimiation with small code but this is poor for decryption + so we need to control this with the following VC++ pragmas +*/ + +#if defined( _MSC_VER ) && !defined( _WIN64 ) +#pragma optimize( "s", on ) +#endif + +/* Given the column (c) of the output state variable, the following + macros give the input state variables which are needed in its + computation for each row (r) of the state. All the alternative + macros give the same end values but expand into different ways + of calculating these values. In particular the complex macro + used for dynamically variable block sizes is designed to expand + to a compile time constant whenever possible but will expand to + conditional clauses on some branches (I am grateful to Frank + Yellin for this construction) +*/ + +#define fwd_var(x,r,c)\ + ( r == 0 ? ( c == 0 ? s(x,0) : c == 1 ? s(x,1) : c == 2 ? s(x,2) : s(x,3))\ + : r == 1 ? ( c == 0 ? s(x,1) : c == 1 ? s(x,2) : c == 2 ? s(x,3) : s(x,0))\ + : r == 2 ? ( c == 0 ? s(x,2) : c == 1 ? s(x,3) : c == 2 ? s(x,0) : s(x,1))\ + : ( c == 0 ? s(x,3) : c == 1 ? s(x,0) : c == 2 ? s(x,1) : s(x,2))) + +#if defined(FT4_SET) +#undef dec_fmvars +#define fwd_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ four_tables(x,t_use(f,n),fwd_var,rf1,c)) +#elif defined(FT1_SET) +#undef dec_fmvars +#define fwd_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ one_table(x,upr,t_use(f,n),fwd_var,rf1,c)) +#else +#define fwd_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ fwd_mcol(no_table(x,t_use(s,box),fwd_var,rf1,c))) +#endif + +#if defined(FL4_SET) +#define fwd_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ four_tables(x,t_use(f,l),fwd_var,rf1,c)) +#elif defined(FL1_SET) +#define fwd_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ one_table(x,ups,t_use(f,l),fwd_var,rf1,c)) +#else +#define fwd_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ no_table(x,t_use(s,box),fwd_var,rf1,c)) +#endif + +AES_RETURN aes_encrypt(const unsigned char *in, unsigned char *out, const aes_encrypt_ctx cx[1]) +{ uint_32t locals(b0, b1); + const uint_32t *kp; +#if defined( dec_fmvars ) + dec_fmvars; /* declare variables for fwd_mcol() if needed */ +#endif + +#if defined( AES_ERR_CHK ) + if( cx->inf.b[0] != 10 * 16 && cx->inf.b[0] != 12 * 16 && cx->inf.b[0] != 14 * 16 ) + return EXIT_FAILURE; +#endif + + kp = cx->ks; + state_in(b0, in, kp); + +#if (ENC_UNROLL == FULL) + + switch(cx->inf.b[0]) + { + case 14 * 16: + round(fwd_rnd, b1, b0, kp + 1 * N_COLS); + round(fwd_rnd, b0, b1, kp + 2 * N_COLS); + kp += 2 * N_COLS; + case 12 * 16: + round(fwd_rnd, b1, b0, kp + 1 * N_COLS); + round(fwd_rnd, b0, b1, kp + 2 * N_COLS); + kp += 2 * N_COLS; + case 10 * 16: + round(fwd_rnd, b1, b0, kp + 1 * N_COLS); + round(fwd_rnd, b0, b1, kp + 2 * N_COLS); + round(fwd_rnd, b1, b0, kp + 3 * N_COLS); + round(fwd_rnd, b0, b1, kp + 4 * N_COLS); + round(fwd_rnd, b1, b0, kp + 5 * N_COLS); + round(fwd_rnd, b0, b1, kp + 6 * N_COLS); + round(fwd_rnd, b1, b0, kp + 7 * N_COLS); + round(fwd_rnd, b0, b1, kp + 8 * N_COLS); + round(fwd_rnd, b1, b0, kp + 9 * N_COLS); + round(fwd_lrnd, b0, b1, kp +10 * N_COLS); + } + +#else + +#if (ENC_UNROLL == PARTIAL) + { uint_32t rnd; + for(rnd = 0; rnd < (cx->inf.b[0] >> 5) - 1; ++rnd) + { + kp += N_COLS; + round(fwd_rnd, b1, b0, kp); + kp += N_COLS; + round(fwd_rnd, b0, b1, kp); + } + kp += N_COLS; + round(fwd_rnd, b1, b0, kp); +#else + { uint_32t rnd; + for(rnd = 0; rnd < (cx->inf.b[0] >> 4) - 1; ++rnd) + { + kp += N_COLS; + round(fwd_rnd, b1, b0, kp); + l_copy(b0, b1); + } +#endif + kp += N_COLS; + round(fwd_lrnd, b0, b1, kp); + } +#endif + + state_out(out, b0); + +#if defined( AES_ERR_CHK ) + return EXIT_SUCCESS; +#endif +} + +#endif + +#if ( FUNCS_IN_C & DECRYPTION_IN_C) + +/* Visual C++ .Net v7.1 provides the fastest encryption code when using + Pentium optimiation with small code but this is poor for decryption + so we need to control this with the following VC++ pragmas +*/ + +#if defined( _MSC_VER ) && !defined( _WIN64 ) +#pragma optimize( "t", on ) +#endif + +/* Given the column (c) of the output state variable, the following + macros give the input state variables which are needed in its + computation for each row (r) of the state. All the alternative + macros give the same end values but expand into different ways + of calculating these values. In particular the complex macro + used for dynamically variable block sizes is designed to expand + to a compile time constant whenever possible but will expand to + conditional clauses on some branches (I am grateful to Frank + Yellin for this construction) +*/ + +#define inv_var(x,r,c)\ + ( r == 0 ? ( c == 0 ? s(x,0) : c == 1 ? s(x,1) : c == 2 ? s(x,2) : s(x,3))\ + : r == 1 ? ( c == 0 ? s(x,3) : c == 1 ? s(x,0) : c == 2 ? s(x,1) : s(x,2))\ + : r == 2 ? ( c == 0 ? s(x,2) : c == 1 ? s(x,3) : c == 2 ? s(x,0) : s(x,1))\ + : ( c == 0 ? s(x,1) : c == 1 ? s(x,2) : c == 2 ? s(x,3) : s(x,0))) + +#if defined(IT4_SET) +#undef dec_imvars +#define inv_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ four_tables(x,t_use(i,n),inv_var,rf1,c)) +#elif defined(IT1_SET) +#undef dec_imvars +#define inv_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ one_table(x,upr,t_use(i,n),inv_var,rf1,c)) +#else +#define inv_rnd(y,x,k,c) (s(y,c) = inv_mcol((k)[c] ^ no_table(x,t_use(i,box),inv_var,rf1,c))) +#endif + +#if defined(IL4_SET) +#define inv_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ four_tables(x,t_use(i,l),inv_var,rf1,c)) +#elif defined(IL1_SET) +#define inv_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ one_table(x,ups,t_use(i,l),inv_var,rf1,c)) +#else +#define inv_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ no_table(x,t_use(i,box),inv_var,rf1,c)) +#endif + +/* This code can work with the decryption key schedule in the */ +/* order that is used for encrytpion (where the 1st decryption */ +/* round key is at the high end ot the schedule) or with a key */ +/* schedule that has been reversed to put the 1st decryption */ +/* round key at the low end of the schedule in memory (when */ +/* AES_REV_DKS is defined) */ + +#ifdef AES_REV_DKS +#define key_ofs 0 +#define rnd_key(n) (kp + n * N_COLS) +#else +#define key_ofs 1 +#define rnd_key(n) (kp - n * N_COLS) +#endif + +AES_RETURN aes_decrypt(const unsigned char *in, unsigned char *out, const aes_decrypt_ctx cx[1]) +{ uint_32t locals(b0, b1); +#if defined( dec_imvars ) + dec_imvars; /* declare variables for inv_mcol() if needed */ +#endif + const uint_32t *kp; + +#if defined( AES_ERR_CHK ) + if( cx->inf.b[0] != 10 * 16 && cx->inf.b[0] != 12 * 16 && cx->inf.b[0] != 14 * 16 ) + return EXIT_FAILURE; +#endif + + kp = cx->ks + (key_ofs ? (cx->inf.b[0] >> 2) : 0); + state_in(b0, in, kp); + +#if (DEC_UNROLL == FULL) + + kp = cx->ks + (key_ofs ? 0 : (cx->inf.b[0] >> 2)); + switch(cx->inf.b[0]) + { + case 14 * 16: + round(inv_rnd, b1, b0, rnd_key(-13)); + round(inv_rnd, b0, b1, rnd_key(-12)); + case 12 * 16: + round(inv_rnd, b1, b0, rnd_key(-11)); + round(inv_rnd, b0, b1, rnd_key(-10)); + case 10 * 16: + round(inv_rnd, b1, b0, rnd_key(-9)); + round(inv_rnd, b0, b1, rnd_key(-8)); + round(inv_rnd, b1, b0, rnd_key(-7)); + round(inv_rnd, b0, b1, rnd_key(-6)); + round(inv_rnd, b1, b0, rnd_key(-5)); + round(inv_rnd, b0, b1, rnd_key(-4)); + round(inv_rnd, b1, b0, rnd_key(-3)); + round(inv_rnd, b0, b1, rnd_key(-2)); + round(inv_rnd, b1, b0, rnd_key(-1)); + round(inv_lrnd, b0, b1, rnd_key( 0)); + } + +#else + +#if (DEC_UNROLL == PARTIAL) + { uint_32t rnd; + for(rnd = 0; rnd < (cx->inf.b[0] >> 5) - 1; ++rnd) + { + kp = rnd_key(1); + round(inv_rnd, b1, b0, kp); + kp = rnd_key(1); + round(inv_rnd, b0, b1, kp); + } + kp = rnd_key(1); + round(inv_rnd, b1, b0, kp); +#else + { uint_32t rnd; + for(rnd = 0; rnd < (cx->inf.b[0] >> 4) - 1; ++rnd) + { + kp = rnd_key(1); + round(inv_rnd, b1, b0, kp); + l_copy(b0, b1); + } +#endif + kp = rnd_key(1); + round(inv_lrnd, b0, b1, kp); + } +#endif + + state_out(out, b0); + +#if defined( AES_ERR_CHK ) + return EXIT_SUCCESS; +#endif +} + +#endif + +#if defined(__cplusplus) +} +#endif diff --git a/src/Crypto/Aeskey.c b/src/Crypto/Aeskey.c index 948b9238..c9ab0269 100644 --- a/src/Crypto/Aeskey.c +++ b/src/Crypto/Aeskey.c @@ -1,573 +1,573 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software is allowed (with or without - changes) provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue Date: 20/12/2007 -*/ - -#include "Aesopt.h" -#include "Aestab.h" - -#ifdef USE_VIA_ACE_IF_PRESENT -# include "aes_via_ace.h" -#endif - -#if defined(__cplusplus) -extern "C" -{ -#endif - -/* Initialise the key schedule from the user supplied key. The key - length can be specified in bytes, with legal values of 16, 24 - and 32, or in bits, with legal values of 128, 192 and 256. These - values correspond with Nk values of 4, 6 and 8 respectively. - - The following macros implement a single cycle in the key - schedule generation process. The number of cycles needed - for each cx->n_col and nk value is: - - nk = 4 5 6 7 8 - ------------------------------ - cx->n_col = 4 10 9 8 7 7 - cx->n_col = 5 14 11 10 9 9 - cx->n_col = 6 19 15 12 11 11 - cx->n_col = 7 21 19 16 13 14 - cx->n_col = 8 29 23 19 17 14 -*/ - -#if (FUNCS_IN_C & ENC_KEYING_IN_C) - -#if defined(AES_128) || defined(AES_VAR) - -#define ke4(k,i) \ -{ k[4*(i)+4] = ss[0] ^= ls_box(ss[3],3) ^ t_use(r,c)[i]; \ - k[4*(i)+5] = ss[1] ^= ss[0]; \ - k[4*(i)+6] = ss[2] ^= ss[1]; \ - k[4*(i)+7] = ss[3] ^= ss[2]; \ -} - -AES_RETURN aes_encrypt_key128(const unsigned char *key, aes_encrypt_ctx cx[1]) -{ uint_32t ss[4]; - - cx->ks[0] = ss[0] = word_in(key, 0); - cx->ks[1] = ss[1] = word_in(key, 1); - cx->ks[2] = ss[2] = word_in(key, 2); - cx->ks[3] = ss[3] = word_in(key, 3); - -#if ENC_UNROLL == NONE - { uint_32t i; - for(i = 0; i < 9; ++i) - ke4(cx->ks, i); - } -#else - ke4(cx->ks, 0); ke4(cx->ks, 1); - ke4(cx->ks, 2); ke4(cx->ks, 3); - ke4(cx->ks, 4); ke4(cx->ks, 5); - ke4(cx->ks, 6); ke4(cx->ks, 7); - ke4(cx->ks, 8); -#endif - ke4(cx->ks, 9); - cx->inf.l = 0; - cx->inf.b[0] = 10 * 16; - -#ifdef USE_VIA_ACE_IF_PRESENT - if(VIA_ACE_AVAILABLE) - cx->inf.b[1] = 0xff; -#endif - -#if defined( AES_ERR_CHK ) - return EXIT_SUCCESS; -#endif -} - -#endif - -#if defined(AES_192) || defined(AES_VAR) - -#define kef6(k,i) \ -{ k[6*(i)+ 6] = ss[0] ^= ls_box(ss[5],3) ^ t_use(r,c)[i]; \ - k[6*(i)+ 7] = ss[1] ^= ss[0]; \ - k[6*(i)+ 8] = ss[2] ^= ss[1]; \ - k[6*(i)+ 9] = ss[3] ^= ss[2]; \ -} - -#define ke6(k,i) \ -{ kef6(k,i); \ - k[6*(i)+10] = ss[4] ^= ss[3]; \ - k[6*(i)+11] = ss[5] ^= ss[4]; \ -} - -AES_RETURN aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1]) -{ uint_32t ss[6]; - - cx->ks[0] = ss[0] = word_in(key, 0); - cx->ks[1] = ss[1] = word_in(key, 1); - cx->ks[2] = ss[2] = word_in(key, 2); - cx->ks[3] = ss[3] = word_in(key, 3); - cx->ks[4] = ss[4] = word_in(key, 4); - cx->ks[5] = ss[5] = word_in(key, 5); - -#if ENC_UNROLL == NONE - { uint_32t i; - for(i = 0; i < 7; ++i) - ke6(cx->ks, i); - } -#else - ke6(cx->ks, 0); ke6(cx->ks, 1); - ke6(cx->ks, 2); ke6(cx->ks, 3); - ke6(cx->ks, 4); ke6(cx->ks, 5); - ke6(cx->ks, 6); -#endif - kef6(cx->ks, 7); - cx->inf.l = 0; - cx->inf.b[0] = 12 * 16; - -#ifdef USE_VIA_ACE_IF_PRESENT - if(VIA_ACE_AVAILABLE) - cx->inf.b[1] = 0xff; -#endif - -#if defined( AES_ERR_CHK ) - return EXIT_SUCCESS; -#endif -} - -#endif - -#if defined(AES_256) || defined(AES_VAR) - -#define kef8(k,i) \ -{ k[8*(i)+ 8] = ss[0] ^= ls_box(ss[7],3) ^ t_use(r,c)[i]; \ - k[8*(i)+ 9] = ss[1] ^= ss[0]; \ - k[8*(i)+10] = ss[2] ^= ss[1]; \ - k[8*(i)+11] = ss[3] ^= ss[2]; \ -} - -#define ke8(k,i) \ -{ kef8(k,i); \ - k[8*(i)+12] = ss[4] ^= ls_box(ss[3],0); \ - k[8*(i)+13] = ss[5] ^= ss[4]; \ - k[8*(i)+14] = ss[6] ^= ss[5]; \ - k[8*(i)+15] = ss[7] ^= ss[6]; \ -} - -AES_RETURN aes_encrypt_key256(const unsigned char *key, aes_encrypt_ctx cx[1]) -{ uint_32t ss[8]; - - cx->ks[0] = ss[0] = word_in(key, 0); - cx->ks[1] = ss[1] = word_in(key, 1); - cx->ks[2] = ss[2] = word_in(key, 2); - cx->ks[3] = ss[3] = word_in(key, 3); - cx->ks[4] = ss[4] = word_in(key, 4); - cx->ks[5] = ss[5] = word_in(key, 5); - cx->ks[6] = ss[6] = word_in(key, 6); - cx->ks[7] = ss[7] = word_in(key, 7); - -#if ENC_UNROLL == NONE - { uint_32t i; - for(i = 0; i < 6; ++i) - ke8(cx->ks, i); - } -#else - ke8(cx->ks, 0); ke8(cx->ks, 1); - ke8(cx->ks, 2); ke8(cx->ks, 3); - ke8(cx->ks, 4); ke8(cx->ks, 5); -#endif - kef8(cx->ks, 6); - cx->inf.l = 0; - cx->inf.b[0] = 14 * 16; - -#ifdef USE_VIA_ACE_IF_PRESENT - if(VIA_ACE_AVAILABLE) - cx->inf.b[1] = 0xff; -#endif - -#if defined( AES_ERR_CHK ) - return EXIT_SUCCESS; -#endif -} - -#endif - -#if defined(AES_VAR) - -AES_RETURN aes_encrypt_key(const unsigned char *key, int key_len, aes_encrypt_ctx cx[1]) -{ - switch(key_len) - { -#if defined( AES_ERR_CHK ) - case 16: case 128: return aes_encrypt_key128(key, cx); - case 24: case 192: return aes_encrypt_key192(key, cx); - case 32: case 256: return aes_encrypt_key256(key, cx); - default: return EXIT_FAILURE; -#else - case 16: case 128: aes_encrypt_key128(key, cx); return; - case 24: case 192: aes_encrypt_key192(key, cx); return; - case 32: case 256: aes_encrypt_key256(key, cx); return; -#endif - } -} - -#endif - -#endif - -#if (FUNCS_IN_C & DEC_KEYING_IN_C) - -/* this is used to store the decryption round keys */ -/* in forward or reverse order */ - -#ifdef AES_REV_DKS -#define v(n,i) ((n) - (i) + 2 * ((i) & 3)) -#else -#define v(n,i) (i) -#endif - -#if DEC_ROUND == NO_TABLES -#define ff(x) (x) -#else -#define ff(x) inv_mcol(x) -#if defined( dec_imvars ) -#define d_vars dec_imvars -#endif -#endif - -#if defined(AES_128) || defined(AES_VAR) - -#define k4e(k,i) \ -{ k[v(40,(4*(i))+4)] = ss[0] ^= ls_box(ss[3],3) ^ t_use(r,c)[i]; \ - k[v(40,(4*(i))+5)] = ss[1] ^= ss[0]; \ - k[v(40,(4*(i))+6)] = ss[2] ^= ss[1]; \ - k[v(40,(4*(i))+7)] = ss[3] ^= ss[2]; \ -} - -#if 1 - -#define kdf4(k,i) \ -{ ss[0] = ss[0] ^ ss[2] ^ ss[1] ^ ss[3]; \ - ss[1] = ss[1] ^ ss[3]; \ - ss[2] = ss[2] ^ ss[3]; \ - ss[4] = ls_box(ss[(i+3) % 4], 3) ^ t_use(r,c)[i]; \ - ss[i % 4] ^= ss[4]; \ - ss[4] ^= k[v(40,(4*(i)))]; k[v(40,(4*(i))+4)] = ff(ss[4]); \ - ss[4] ^= k[v(40,(4*(i))+1)]; k[v(40,(4*(i))+5)] = ff(ss[4]); \ - ss[4] ^= k[v(40,(4*(i))+2)]; k[v(40,(4*(i))+6)] = ff(ss[4]); \ - ss[4] ^= k[v(40,(4*(i))+3)]; k[v(40,(4*(i))+7)] = ff(ss[4]); \ -} - -#define kd4(k,i) \ -{ ss[4] = ls_box(ss[(i+3) % 4], 3) ^ t_use(r,c)[i]; \ - ss[i % 4] ^= ss[4]; ss[4] = ff(ss[4]); \ - k[v(40,(4*(i))+4)] = ss[4] ^= k[v(40,(4*(i)))]; \ - k[v(40,(4*(i))+5)] = ss[4] ^= k[v(40,(4*(i))+1)]; \ - k[v(40,(4*(i))+6)] = ss[4] ^= k[v(40,(4*(i))+2)]; \ - k[v(40,(4*(i))+7)] = ss[4] ^= k[v(40,(4*(i))+3)]; \ -} - -#define kdl4(k,i) \ -{ ss[4] = ls_box(ss[(i+3) % 4], 3) ^ t_use(r,c)[i]; ss[i % 4] ^= ss[4]; \ - k[v(40,(4*(i))+4)] = (ss[0] ^= ss[1]) ^ ss[2] ^ ss[3]; \ - k[v(40,(4*(i))+5)] = ss[1] ^ ss[3]; \ - k[v(40,(4*(i))+6)] = ss[0]; \ - k[v(40,(4*(i))+7)] = ss[1]; \ -} - -#else - -#define kdf4(k,i) \ -{ ss[0] ^= ls_box(ss[3],3) ^ t_use(r,c)[i]; k[v(40,(4*(i))+ 4)] = ff(ss[0]); \ - ss[1] ^= ss[0]; k[v(40,(4*(i))+ 5)] = ff(ss[1]); \ - ss[2] ^= ss[1]; k[v(40,(4*(i))+ 6)] = ff(ss[2]); \ - ss[3] ^= ss[2]; k[v(40,(4*(i))+ 7)] = ff(ss[3]); \ -} - -#define kd4(k,i) \ -{ ss[4] = ls_box(ss[3],3) ^ t_use(r,c)[i]; \ - ss[0] ^= ss[4]; ss[4] = ff(ss[4]); k[v(40,(4*(i))+ 4)] = ss[4] ^= k[v(40,(4*(i)))]; \ - ss[1] ^= ss[0]; k[v(40,(4*(i))+ 5)] = ss[4] ^= k[v(40,(4*(i))+ 1)]; \ - ss[2] ^= ss[1]; k[v(40,(4*(i))+ 6)] = ss[4] ^= k[v(40,(4*(i))+ 2)]; \ - ss[3] ^= ss[2]; k[v(40,(4*(i))+ 7)] = ss[4] ^= k[v(40,(4*(i))+ 3)]; \ -} - -#define kdl4(k,i) \ -{ ss[0] ^= ls_box(ss[3],3) ^ t_use(r,c)[i]; k[v(40,(4*(i))+ 4)] = ss[0]; \ - ss[1] ^= ss[0]; k[v(40,(4*(i))+ 5)] = ss[1]; \ - ss[2] ^= ss[1]; k[v(40,(4*(i))+ 6)] = ss[2]; \ - ss[3] ^= ss[2]; k[v(40,(4*(i))+ 7)] = ss[3]; \ -} - -#endif - -AES_RETURN aes_decrypt_key128(const unsigned char *key, aes_decrypt_ctx cx[1]) -{ uint_32t ss[5]; -#if defined( d_vars ) - d_vars; -#endif - cx->ks[v(40,(0))] = ss[0] = word_in(key, 0); - cx->ks[v(40,(1))] = ss[1] = word_in(key, 1); - cx->ks[v(40,(2))] = ss[2] = word_in(key, 2); - cx->ks[v(40,(3))] = ss[3] = word_in(key, 3); - -#if DEC_UNROLL == NONE - { uint_32t i; - for(i = 0; i < 10; ++i) - k4e(cx->ks, i); -#if !(DEC_ROUND == NO_TABLES) - for(i = N_COLS; i < 10 * N_COLS; ++i) - cx->ks[i] = inv_mcol(cx->ks[i]); -#endif - } -#else - kdf4(cx->ks, 0); kd4(cx->ks, 1); - kd4(cx->ks, 2); kd4(cx->ks, 3); - kd4(cx->ks, 4); kd4(cx->ks, 5); - kd4(cx->ks, 6); kd4(cx->ks, 7); - kd4(cx->ks, 8); kdl4(cx->ks, 9); -#endif - cx->inf.l = 0; - cx->inf.b[0] = 10 * 16; - -#ifdef USE_VIA_ACE_IF_PRESENT - if(VIA_ACE_AVAILABLE) - cx->inf.b[1] = 0xff; -#endif - -#if defined( AES_ERR_CHK ) - return EXIT_SUCCESS; -#endif -} - -#endif - -#if defined(AES_192) || defined(AES_VAR) - -#define k6ef(k,i) \ -{ k[v(48,(6*(i))+ 6)] = ss[0] ^= ls_box(ss[5],3) ^ t_use(r,c)[i]; \ - k[v(48,(6*(i))+ 7)] = ss[1] ^= ss[0]; \ - k[v(48,(6*(i))+ 8)] = ss[2] ^= ss[1]; \ - k[v(48,(6*(i))+ 9)] = ss[3] ^= ss[2]; \ -} - -#define k6e(k,i) \ -{ k6ef(k,i); \ - k[v(48,(6*(i))+10)] = ss[4] ^= ss[3]; \ - k[v(48,(6*(i))+11)] = ss[5] ^= ss[4]; \ -} - -#define kdf6(k,i) \ -{ ss[0] ^= ls_box(ss[5],3) ^ t_use(r,c)[i]; k[v(48,(6*(i))+ 6)] = ff(ss[0]); \ - ss[1] ^= ss[0]; k[v(48,(6*(i))+ 7)] = ff(ss[1]); \ - ss[2] ^= ss[1]; k[v(48,(6*(i))+ 8)] = ff(ss[2]); \ - ss[3] ^= ss[2]; k[v(48,(6*(i))+ 9)] = ff(ss[3]); \ - ss[4] ^= ss[3]; k[v(48,(6*(i))+10)] = ff(ss[4]); \ - ss[5] ^= ss[4]; k[v(48,(6*(i))+11)] = ff(ss[5]); \ -} - -#define kd6(k,i) \ -{ ss[6] = ls_box(ss[5],3) ^ t_use(r,c)[i]; \ - ss[0] ^= ss[6]; ss[6] = ff(ss[6]); k[v(48,(6*(i))+ 6)] = ss[6] ^= k[v(48,(6*(i)))]; \ - ss[1] ^= ss[0]; k[v(48,(6*(i))+ 7)] = ss[6] ^= k[v(48,(6*(i))+ 1)]; \ - ss[2] ^= ss[1]; k[v(48,(6*(i))+ 8)] = ss[6] ^= k[v(48,(6*(i))+ 2)]; \ - ss[3] ^= ss[2]; k[v(48,(6*(i))+ 9)] = ss[6] ^= k[v(48,(6*(i))+ 3)]; \ - ss[4] ^= ss[3]; k[v(48,(6*(i))+10)] = ss[6] ^= k[v(48,(6*(i))+ 4)]; \ - ss[5] ^= ss[4]; k[v(48,(6*(i))+11)] = ss[6] ^= k[v(48,(6*(i))+ 5)]; \ -} - -#define kdl6(k,i) \ -{ ss[0] ^= ls_box(ss[5],3) ^ t_use(r,c)[i]; k[v(48,(6*(i))+ 6)] = ss[0]; \ - ss[1] ^= ss[0]; k[v(48,(6*(i))+ 7)] = ss[1]; \ - ss[2] ^= ss[1]; k[v(48,(6*(i))+ 8)] = ss[2]; \ - ss[3] ^= ss[2]; k[v(48,(6*(i))+ 9)] = ss[3]; \ -} - -AES_RETURN aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1]) -{ uint_32t ss[7]; -#if defined( d_vars ) - d_vars; -#endif - cx->ks[v(48,(0))] = ss[0] = word_in(key, 0); - cx->ks[v(48,(1))] = ss[1] = word_in(key, 1); - cx->ks[v(48,(2))] = ss[2] = word_in(key, 2); - cx->ks[v(48,(3))] = ss[3] = word_in(key, 3); - -#if DEC_UNROLL == NONE - cx->ks[v(48,(4))] = ss[4] = word_in(key, 4); - cx->ks[v(48,(5))] = ss[5] = word_in(key, 5); - { uint_32t i; - - for(i = 0; i < 7; ++i) - k6e(cx->ks, i); - k6ef(cx->ks, 7); -#if !(DEC_ROUND == NO_TABLES) - for(i = N_COLS; i < 12 * N_COLS; ++i) - cx->ks[i] = inv_mcol(cx->ks[i]); -#endif - } -#else - cx->ks[v(48,(4))] = ff(ss[4] = word_in(key, 4)); - cx->ks[v(48,(5))] = ff(ss[5] = word_in(key, 5)); - kdf6(cx->ks, 0); kd6(cx->ks, 1); - kd6(cx->ks, 2); kd6(cx->ks, 3); - kd6(cx->ks, 4); kd6(cx->ks, 5); - kd6(cx->ks, 6); kdl6(cx->ks, 7); -#endif - cx->inf.l = 0; - cx->inf.b[0] = 12 * 16; - -#ifdef USE_VIA_ACE_IF_PRESENT - if(VIA_ACE_AVAILABLE) - cx->inf.b[1] = 0xff; -#endif - -#if defined( AES_ERR_CHK ) - return EXIT_SUCCESS; -#endif -} - -#endif - -#if defined(AES_256) || defined(AES_VAR) - -#define k8ef(k,i) \ -{ k[v(56,(8*(i))+ 8)] = ss[0] ^= ls_box(ss[7],3) ^ t_use(r,c)[i]; \ - k[v(56,(8*(i))+ 9)] = ss[1] ^= ss[0]; \ - k[v(56,(8*(i))+10)] = ss[2] ^= ss[1]; \ - k[v(56,(8*(i))+11)] = ss[3] ^= ss[2]; \ -} - -#define k8e(k,i) \ -{ k8ef(k,i); \ - k[v(56,(8*(i))+12)] = ss[4] ^= ls_box(ss[3],0); \ - k[v(56,(8*(i))+13)] = ss[5] ^= ss[4]; \ - k[v(56,(8*(i))+14)] = ss[6] ^= ss[5]; \ - k[v(56,(8*(i))+15)] = ss[7] ^= ss[6]; \ -} - -#define kdf8(k,i) \ -{ ss[0] ^= ls_box(ss[7],3) ^ t_use(r,c)[i]; k[v(56,(8*(i))+ 8)] = ff(ss[0]); \ - ss[1] ^= ss[0]; k[v(56,(8*(i))+ 9)] = ff(ss[1]); \ - ss[2] ^= ss[1]; k[v(56,(8*(i))+10)] = ff(ss[2]); \ - ss[3] ^= ss[2]; k[v(56,(8*(i))+11)] = ff(ss[3]); \ - ss[4] ^= ls_box(ss[3],0); k[v(56,(8*(i))+12)] = ff(ss[4]); \ - ss[5] ^= ss[4]; k[v(56,(8*(i))+13)] = ff(ss[5]); \ - ss[6] ^= ss[5]; k[v(56,(8*(i))+14)] = ff(ss[6]); \ - ss[7] ^= ss[6]; k[v(56,(8*(i))+15)] = ff(ss[7]); \ -} - -#define kd8(k,i) \ -{ ss[8] = ls_box(ss[7],3) ^ t_use(r,c)[i]; \ - ss[0] ^= ss[8]; ss[8] = ff(ss[8]); k[v(56,(8*(i))+ 8)] = ss[8] ^= k[v(56,(8*(i)))]; \ - ss[1] ^= ss[0]; k[v(56,(8*(i))+ 9)] = ss[8] ^= k[v(56,(8*(i))+ 1)]; \ - ss[2] ^= ss[1]; k[v(56,(8*(i))+10)] = ss[8] ^= k[v(56,(8*(i))+ 2)]; \ - ss[3] ^= ss[2]; k[v(56,(8*(i))+11)] = ss[8] ^= k[v(56,(8*(i))+ 3)]; \ - ss[8] = ls_box(ss[3],0); \ - ss[4] ^= ss[8]; ss[8] = ff(ss[8]); k[v(56,(8*(i))+12)] = ss[8] ^= k[v(56,(8*(i))+ 4)]; \ - ss[5] ^= ss[4]; k[v(56,(8*(i))+13)] = ss[8] ^= k[v(56,(8*(i))+ 5)]; \ - ss[6] ^= ss[5]; k[v(56,(8*(i))+14)] = ss[8] ^= k[v(56,(8*(i))+ 6)]; \ - ss[7] ^= ss[6]; k[v(56,(8*(i))+15)] = ss[8] ^= k[v(56,(8*(i))+ 7)]; \ -} - -#define kdl8(k,i) \ -{ ss[0] ^= ls_box(ss[7],3) ^ t_use(r,c)[i]; k[v(56,(8*(i))+ 8)] = ss[0]; \ - ss[1] ^= ss[0]; k[v(56,(8*(i))+ 9)] = ss[1]; \ - ss[2] ^= ss[1]; k[v(56,(8*(i))+10)] = ss[2]; \ - ss[3] ^= ss[2]; k[v(56,(8*(i))+11)] = ss[3]; \ -} - -AES_RETURN aes_decrypt_key256(const unsigned char *key, aes_decrypt_ctx cx[1]) -{ uint_32t ss[9]; -#if defined( d_vars ) - d_vars; -#endif - cx->ks[v(56,(0))] = ss[0] = word_in(key, 0); - cx->ks[v(56,(1))] = ss[1] = word_in(key, 1); - cx->ks[v(56,(2))] = ss[2] = word_in(key, 2); - cx->ks[v(56,(3))] = ss[3] = word_in(key, 3); - -#if DEC_UNROLL == NONE - cx->ks[v(56,(4))] = ss[4] = word_in(key, 4); - cx->ks[v(56,(5))] = ss[5] = word_in(key, 5); - cx->ks[v(56,(6))] = ss[6] = word_in(key, 6); - cx->ks[v(56,(7))] = ss[7] = word_in(key, 7); - { uint_32t i; - - for(i = 0; i < 6; ++i) - k8e(cx->ks, i); - k8ef(cx->ks, 6); -#if !(DEC_ROUND == NO_TABLES) - for(i = N_COLS; i < 14 * N_COLS; ++i) - cx->ks[i] = inv_mcol(cx->ks[i]); - -#endif - } -#else - ss[4] = word_in(key, 4); cx->ks[v(56,(4))] = ff(ss[4]); - ss[5] = word_in(key, 5); cx->ks[v(56,(5))] = ff(ss[5]); - ss[6] = word_in(key, 6); cx->ks[v(56,(6))] = ff(ss[6]); - ss[7] = word_in(key, 7); cx->ks[v(56,(7))] = ff(ss[7]); - kdf8(cx->ks, 0); kd8(cx->ks, 1); - kd8(cx->ks, 2); kd8(cx->ks, 3); - kd8(cx->ks, 4); kd8(cx->ks, 5); - kdl8(cx->ks, 6); -#endif - cx->inf.l = 0; - cx->inf.b[0] = 14 * 16; - -#ifdef USE_VIA_ACE_IF_PRESENT - if(VIA_ACE_AVAILABLE) - cx->inf.b[1] = 0xff; -#endif - -#if defined( AES_ERR_CHK ) - return EXIT_SUCCESS; -#endif -} - -#endif - -#if defined(AES_VAR) - -AES_RETURN aes_decrypt_key(const unsigned char *key, int key_len, aes_decrypt_ctx cx[1]) -{ - switch(key_len) - { -#if defined( AES_ERR_CHK ) - case 16: case 128: return aes_decrypt_key128(key, cx); - case 24: case 192: return aes_decrypt_key192(key, cx); - case 32: case 256: return aes_decrypt_key256(key, cx); - default: return EXIT_FAILURE; -#else - case 16: case 128: aes_decrypt_key128(key, cx); return; - case 24: case 192: aes_decrypt_key192(key, cx); return; - case 32: case 256: aes_decrypt_key256(key, cx); return; -#endif - } -} - -#endif - -#endif - -#if defined(__cplusplus) -} -#endif +/* + --------------------------------------------------------------------------- + Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software is allowed (with or without + changes) provided that: + + 1. source code distributions include the above copyright notice, this + list of conditions and the following disclaimer; + + 2. binary distributions include the above copyright notice, this list + of conditions and the following disclaimer in their documentation; + + 3. the name of the copyright holder is not used to endorse products + built using this software without specific written permission. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + Issue Date: 20/12/2007 +*/ + +#include "Aesopt.h" +#include "Aestab.h" + +#ifdef USE_VIA_ACE_IF_PRESENT +# include "aes_via_ace.h" +#endif + +#if defined(__cplusplus) +extern "C" +{ +#endif + +/* Initialise the key schedule from the user supplied key. The key + length can be specified in bytes, with legal values of 16, 24 + and 32, or in bits, with legal values of 128, 192 and 256. These + values correspond with Nk values of 4, 6 and 8 respectively. + + The following macros implement a single cycle in the key + schedule generation process. The number of cycles needed + for each cx->n_col and nk value is: + + nk = 4 5 6 7 8 + ------------------------------ + cx->n_col = 4 10 9 8 7 7 + cx->n_col = 5 14 11 10 9 9 + cx->n_col = 6 19 15 12 11 11 + cx->n_col = 7 21 19 16 13 14 + cx->n_col = 8 29 23 19 17 14 +*/ + +#if (FUNCS_IN_C & ENC_KEYING_IN_C) + +#if defined(AES_128) || defined(AES_VAR) + +#define ke4(k,i) \ +{ k[4*(i)+4] = ss[0] ^= ls_box(ss[3],3) ^ t_use(r,c)[i]; \ + k[4*(i)+5] = ss[1] ^= ss[0]; \ + k[4*(i)+6] = ss[2] ^= ss[1]; \ + k[4*(i)+7] = ss[3] ^= ss[2]; \ +} + +AES_RETURN aes_encrypt_key128(const unsigned char *key, aes_encrypt_ctx cx[1]) +{ uint_32t ss[4]; + + cx->ks[0] = ss[0] = word_in(key, 0); + cx->ks[1] = ss[1] = word_in(key, 1); + cx->ks[2] = ss[2] = word_in(key, 2); + cx->ks[3] = ss[3] = word_in(key, 3); + +#if ENC_UNROLL == NONE + { uint_32t i; + for(i = 0; i < 9; ++i) + ke4(cx->ks, i); + } +#else + ke4(cx->ks, 0); ke4(cx->ks, 1); + ke4(cx->ks, 2); ke4(cx->ks, 3); + ke4(cx->ks, 4); ke4(cx->ks, 5); + ke4(cx->ks, 6); ke4(cx->ks, 7); + ke4(cx->ks, 8); +#endif + ke4(cx->ks, 9); + cx->inf.l = 0; + cx->inf.b[0] = 10 * 16; + +#ifdef USE_VIA_ACE_IF_PRESENT + if(VIA_ACE_AVAILABLE) + cx->inf.b[1] = 0xff; +#endif + +#if defined( AES_ERR_CHK ) + return EXIT_SUCCESS; +#endif +} + +#endif + +#if defined(AES_192) || defined(AES_VAR) + +#define kef6(k,i) \ +{ k[6*(i)+ 6] = ss[0] ^= ls_box(ss[5],3) ^ t_use(r,c)[i]; \ + k[6*(i)+ 7] = ss[1] ^= ss[0]; \ + k[6*(i)+ 8] = ss[2] ^= ss[1]; \ + k[6*(i)+ 9] = ss[3] ^= ss[2]; \ +} + +#define ke6(k,i) \ +{ kef6(k,i); \ + k[6*(i)+10] = ss[4] ^= ss[3]; \ + k[6*(i)+11] = ss[5] ^= ss[4]; \ +} + +AES_RETURN aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1]) +{ uint_32t ss[6]; + + cx->ks[0] = ss[0] = word_in(key, 0); + cx->ks[1] = ss[1] = word_in(key, 1); + cx->ks[2] = ss[2] = word_in(key, 2); + cx->ks[3] = ss[3] = word_in(key, 3); + cx->ks[4] = ss[4] = word_in(key, 4); + cx->ks[5] = ss[5] = word_in(key, 5); + +#if ENC_UNROLL == NONE + { uint_32t i; + for(i = 0; i < 7; ++i) + ke6(cx->ks, i); + } +#else + ke6(cx->ks, 0); ke6(cx->ks, 1); + ke6(cx->ks, 2); ke6(cx->ks, 3); + ke6(cx->ks, 4); ke6(cx->ks, 5); + ke6(cx->ks, 6); +#endif + kef6(cx->ks, 7); + cx->inf.l = 0; + cx->inf.b[0] = 12 * 16; + +#ifdef USE_VIA_ACE_IF_PRESENT + if(VIA_ACE_AVAILABLE) + cx->inf.b[1] = 0xff; +#endif + +#if defined( AES_ERR_CHK ) + return EXIT_SUCCESS; +#endif +} + +#endif + +#if defined(AES_256) || defined(AES_VAR) + +#define kef8(k,i) \ +{ k[8*(i)+ 8] = ss[0] ^= ls_box(ss[7],3) ^ t_use(r,c)[i]; \ + k[8*(i)+ 9] = ss[1] ^= ss[0]; \ + k[8*(i)+10] = ss[2] ^= ss[1]; \ + k[8*(i)+11] = ss[3] ^= ss[2]; \ +} + +#define ke8(k,i) \ +{ kef8(k,i); \ + k[8*(i)+12] = ss[4] ^= ls_box(ss[3],0); \ + k[8*(i)+13] = ss[5] ^= ss[4]; \ + k[8*(i)+14] = ss[6] ^= ss[5]; \ + k[8*(i)+15] = ss[7] ^= ss[6]; \ +} + +AES_RETURN aes_encrypt_key256(const unsigned char *key, aes_encrypt_ctx cx[1]) +{ uint_32t ss[8]; + + cx->ks[0] = ss[0] = word_in(key, 0); + cx->ks[1] = ss[1] = word_in(key, 1); + cx->ks[2] = ss[2] = word_in(key, 2); + cx->ks[3] = ss[3] = word_in(key, 3); + cx->ks[4] = ss[4] = word_in(key, 4); + cx->ks[5] = ss[5] = word_in(key, 5); + cx->ks[6] = ss[6] = word_in(key, 6); + cx->ks[7] = ss[7] = word_in(key, 7); + +#if ENC_UNROLL == NONE + { uint_32t i; + for(i = 0; i < 6; ++i) + ke8(cx->ks, i); + } +#else + ke8(cx->ks, 0); ke8(cx->ks, 1); + ke8(cx->ks, 2); ke8(cx->ks, 3); + ke8(cx->ks, 4); ke8(cx->ks, 5); +#endif + kef8(cx->ks, 6); + cx->inf.l = 0; + cx->inf.b[0] = 14 * 16; + +#ifdef USE_VIA_ACE_IF_PRESENT + if(VIA_ACE_AVAILABLE) + cx->inf.b[1] = 0xff; +#endif + +#if defined( AES_ERR_CHK ) + return EXIT_SUCCESS; +#endif +} + +#endif + +#if defined(AES_VAR) + +AES_RETURN aes_encrypt_key(const unsigned char *key, int key_len, aes_encrypt_ctx cx[1]) +{ + switch(key_len) + { +#if defined( AES_ERR_CHK ) + case 16: case 128: return aes_encrypt_key128(key, cx); + case 24: case 192: return aes_encrypt_key192(key, cx); + case 32: case 256: return aes_encrypt_key256(key, cx); + default: return EXIT_FAILURE; +#else + case 16: case 128: aes_encrypt_key128(key, cx); return; + case 24: case 192: aes_encrypt_key192(key, cx); return; + case 32: case 256: aes_encrypt_key256(key, cx); return; +#endif + } +} + +#endif + +#endif + +#if (FUNCS_IN_C & DEC_KEYING_IN_C) + +/* this is used to store the decryption round keys */ +/* in forward or reverse order */ + +#ifdef AES_REV_DKS +#define v(n,i) ((n) - (i) + 2 * ((i) & 3)) +#else +#define v(n,i) (i) +#endif + +#if DEC_ROUND == NO_TABLES +#define ff(x) (x) +#else +#define ff(x) inv_mcol(x) +#if defined( dec_imvars ) +#define d_vars dec_imvars +#endif +#endif + +#if defined(AES_128) || defined(AES_VAR) + +#define k4e(k,i) \ +{ k[v(40,(4*(i))+4)] = ss[0] ^= ls_box(ss[3],3) ^ t_use(r,c)[i]; \ + k[v(40,(4*(i))+5)] = ss[1] ^= ss[0]; \ + k[v(40,(4*(i))+6)] = ss[2] ^= ss[1]; \ + k[v(40,(4*(i))+7)] = ss[3] ^= ss[2]; \ +} + +#if 1 + +#define kdf4(k,i) \ +{ ss[0] = ss[0] ^ ss[2] ^ ss[1] ^ ss[3]; \ + ss[1] = ss[1] ^ ss[3]; \ + ss[2] = ss[2] ^ ss[3]; \ + ss[4] = ls_box(ss[(i+3) % 4], 3) ^ t_use(r,c)[i]; \ + ss[i % 4] ^= ss[4]; \ + ss[4] ^= k[v(40,(4*(i)))]; k[v(40,(4*(i))+4)] = ff(ss[4]); \ + ss[4] ^= k[v(40,(4*(i))+1)]; k[v(40,(4*(i))+5)] = ff(ss[4]); \ + ss[4] ^= k[v(40,(4*(i))+2)]; k[v(40,(4*(i))+6)] = ff(ss[4]); \ + ss[4] ^= k[v(40,(4*(i))+3)]; k[v(40,(4*(i))+7)] = ff(ss[4]); \ +} + +#define kd4(k,i) \ +{ ss[4] = ls_box(ss[(i+3) % 4], 3) ^ t_use(r,c)[i]; \ + ss[i % 4] ^= ss[4]; ss[4] = ff(ss[4]); \ + k[v(40,(4*(i))+4)] = ss[4] ^= k[v(40,(4*(i)))]; \ + k[v(40,(4*(i))+5)] = ss[4] ^= k[v(40,(4*(i))+1)]; \ + k[v(40,(4*(i))+6)] = ss[4] ^= k[v(40,(4*(i))+2)]; \ + k[v(40,(4*(i))+7)] = ss[4] ^= k[v(40,(4*(i))+3)]; \ +} + +#define kdl4(k,i) \ +{ ss[4] = ls_box(ss[(i+3) % 4], 3) ^ t_use(r,c)[i]; ss[i % 4] ^= ss[4]; \ + k[v(40,(4*(i))+4)] = (ss[0] ^= ss[1]) ^ ss[2] ^ ss[3]; \ + k[v(40,(4*(i))+5)] = ss[1] ^ ss[3]; \ + k[v(40,(4*(i))+6)] = ss[0]; \ + k[v(40,(4*(i))+7)] = ss[1]; \ +} + +#else + +#define kdf4(k,i) \ +{ ss[0] ^= ls_box(ss[3],3) ^ t_use(r,c)[i]; k[v(40,(4*(i))+ 4)] = ff(ss[0]); \ + ss[1] ^= ss[0]; k[v(40,(4*(i))+ 5)] = ff(ss[1]); \ + ss[2] ^= ss[1]; k[v(40,(4*(i))+ 6)] = ff(ss[2]); \ + ss[3] ^= ss[2]; k[v(40,(4*(i))+ 7)] = ff(ss[3]); \ +} + +#define kd4(k,i) \ +{ ss[4] = ls_box(ss[3],3) ^ t_use(r,c)[i]; \ + ss[0] ^= ss[4]; ss[4] = ff(ss[4]); k[v(40,(4*(i))+ 4)] = ss[4] ^= k[v(40,(4*(i)))]; \ + ss[1] ^= ss[0]; k[v(40,(4*(i))+ 5)] = ss[4] ^= k[v(40,(4*(i))+ 1)]; \ + ss[2] ^= ss[1]; k[v(40,(4*(i))+ 6)] = ss[4] ^= k[v(40,(4*(i))+ 2)]; \ + ss[3] ^= ss[2]; k[v(40,(4*(i))+ 7)] = ss[4] ^= k[v(40,(4*(i))+ 3)]; \ +} + +#define kdl4(k,i) \ +{ ss[0] ^= ls_box(ss[3],3) ^ t_use(r,c)[i]; k[v(40,(4*(i))+ 4)] = ss[0]; \ + ss[1] ^= ss[0]; k[v(40,(4*(i))+ 5)] = ss[1]; \ + ss[2] ^= ss[1]; k[v(40,(4*(i))+ 6)] = ss[2]; \ + ss[3] ^= ss[2]; k[v(40,(4*(i))+ 7)] = ss[3]; \ +} + +#endif + +AES_RETURN aes_decrypt_key128(const unsigned char *key, aes_decrypt_ctx cx[1]) +{ uint_32t ss[5]; +#if defined( d_vars ) + d_vars; +#endif + cx->ks[v(40,(0))] = ss[0] = word_in(key, 0); + cx->ks[v(40,(1))] = ss[1] = word_in(key, 1); + cx->ks[v(40,(2))] = ss[2] = word_in(key, 2); + cx->ks[v(40,(3))] = ss[3] = word_in(key, 3); + +#if DEC_UNROLL == NONE + { uint_32t i; + for(i = 0; i < 10; ++i) + k4e(cx->ks, i); +#if !(DEC_ROUND == NO_TABLES) + for(i = N_COLS; i < 10 * N_COLS; ++i) + cx->ks[i] = inv_mcol(cx->ks[i]); +#endif + } +#else + kdf4(cx->ks, 0); kd4(cx->ks, 1); + kd4(cx->ks, 2); kd4(cx->ks, 3); + kd4(cx->ks, 4); kd4(cx->ks, 5); + kd4(cx->ks, 6); kd4(cx->ks, 7); + kd4(cx->ks, 8); kdl4(cx->ks, 9); +#endif + cx->inf.l = 0; + cx->inf.b[0] = 10 * 16; + +#ifdef USE_VIA_ACE_IF_PRESENT + if(VIA_ACE_AVAILABLE) + cx->inf.b[1] = 0xff; +#endif + +#if defined( AES_ERR_CHK ) + return EXIT_SUCCESS; +#endif +} + +#endif + +#if defined(AES_192) || defined(AES_VAR) + +#define k6ef(k,i) \ +{ k[v(48,(6*(i))+ 6)] = ss[0] ^= ls_box(ss[5],3) ^ t_use(r,c)[i]; \ + k[v(48,(6*(i))+ 7)] = ss[1] ^= ss[0]; \ + k[v(48,(6*(i))+ 8)] = ss[2] ^= ss[1]; \ + k[v(48,(6*(i))+ 9)] = ss[3] ^= ss[2]; \ +} + +#define k6e(k,i) \ +{ k6ef(k,i); \ + k[v(48,(6*(i))+10)] = ss[4] ^= ss[3]; \ + k[v(48,(6*(i))+11)] = ss[5] ^= ss[4]; \ +} + +#define kdf6(k,i) \ +{ ss[0] ^= ls_box(ss[5],3) ^ t_use(r,c)[i]; k[v(48,(6*(i))+ 6)] = ff(ss[0]); \ + ss[1] ^= ss[0]; k[v(48,(6*(i))+ 7)] = ff(ss[1]); \ + ss[2] ^= ss[1]; k[v(48,(6*(i))+ 8)] = ff(ss[2]); \ + ss[3] ^= ss[2]; k[v(48,(6*(i))+ 9)] = ff(ss[3]); \ + ss[4] ^= ss[3]; k[v(48,(6*(i))+10)] = ff(ss[4]); \ + ss[5] ^= ss[4]; k[v(48,(6*(i))+11)] = ff(ss[5]); \ +} + +#define kd6(k,i) \ +{ ss[6] = ls_box(ss[5],3) ^ t_use(r,c)[i]; \ + ss[0] ^= ss[6]; ss[6] = ff(ss[6]); k[v(48,(6*(i))+ 6)] = ss[6] ^= k[v(48,(6*(i)))]; \ + ss[1] ^= ss[0]; k[v(48,(6*(i))+ 7)] = ss[6] ^= k[v(48,(6*(i))+ 1)]; \ + ss[2] ^= ss[1]; k[v(48,(6*(i))+ 8)] = ss[6] ^= k[v(48,(6*(i))+ 2)]; \ + ss[3] ^= ss[2]; k[v(48,(6*(i))+ 9)] = ss[6] ^= k[v(48,(6*(i))+ 3)]; \ + ss[4] ^= ss[3]; k[v(48,(6*(i))+10)] = ss[6] ^= k[v(48,(6*(i))+ 4)]; \ + ss[5] ^= ss[4]; k[v(48,(6*(i))+11)] = ss[6] ^= k[v(48,(6*(i))+ 5)]; \ +} + +#define kdl6(k,i) \ +{ ss[0] ^= ls_box(ss[5],3) ^ t_use(r,c)[i]; k[v(48,(6*(i))+ 6)] = ss[0]; \ + ss[1] ^= ss[0]; k[v(48,(6*(i))+ 7)] = ss[1]; \ + ss[2] ^= ss[1]; k[v(48,(6*(i))+ 8)] = ss[2]; \ + ss[3] ^= ss[2]; k[v(48,(6*(i))+ 9)] = ss[3]; \ +} + +AES_RETURN aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1]) +{ uint_32t ss[7]; +#if defined( d_vars ) + d_vars; +#endif + cx->ks[v(48,(0))] = ss[0] = word_in(key, 0); + cx->ks[v(48,(1))] = ss[1] = word_in(key, 1); + cx->ks[v(48,(2))] = ss[2] = word_in(key, 2); + cx->ks[v(48,(3))] = ss[3] = word_in(key, 3); + +#if DEC_UNROLL == NONE + cx->ks[v(48,(4))] = ss[4] = word_in(key, 4); + cx->ks[v(48,(5))] = ss[5] = word_in(key, 5); + { uint_32t i; + + for(i = 0; i < 7; ++i) + k6e(cx->ks, i); + k6ef(cx->ks, 7); +#if !(DEC_ROUND == NO_TABLES) + for(i = N_COLS; i < 12 * N_COLS; ++i) + cx->ks[i] = inv_mcol(cx->ks[i]); +#endif + } +#else + cx->ks[v(48,(4))] = ff(ss[4] = word_in(key, 4)); + cx->ks[v(48,(5))] = ff(ss[5] = word_in(key, 5)); + kdf6(cx->ks, 0); kd6(cx->ks, 1); + kd6(cx->ks, 2); kd6(cx->ks, 3); + kd6(cx->ks, 4); kd6(cx->ks, 5); + kd6(cx->ks, 6); kdl6(cx->ks, 7); +#endif + cx->inf.l = 0; + cx->inf.b[0] = 12 * 16; + +#ifdef USE_VIA_ACE_IF_PRESENT + if(VIA_ACE_AVAILABLE) + cx->inf.b[1] = 0xff; +#endif + +#if defined( AES_ERR_CHK ) + return EXIT_SUCCESS; +#endif +} + +#endif + +#if defined(AES_256) || defined(AES_VAR) + +#define k8ef(k,i) \ +{ k[v(56,(8*(i))+ 8)] = ss[0] ^= ls_box(ss[7],3) ^ t_use(r,c)[i]; \ + k[v(56,(8*(i))+ 9)] = ss[1] ^= ss[0]; \ + k[v(56,(8*(i))+10)] = ss[2] ^= ss[1]; \ + k[v(56,(8*(i))+11)] = ss[3] ^= ss[2]; \ +} + +#define k8e(k,i) \ +{ k8ef(k,i); \ + k[v(56,(8*(i))+12)] = ss[4] ^= ls_box(ss[3],0); \ + k[v(56,(8*(i))+13)] = ss[5] ^= ss[4]; \ + k[v(56,(8*(i))+14)] = ss[6] ^= ss[5]; \ + k[v(56,(8*(i))+15)] = ss[7] ^= ss[6]; \ +} + +#define kdf8(k,i) \ +{ ss[0] ^= ls_box(ss[7],3) ^ t_use(r,c)[i]; k[v(56,(8*(i))+ 8)] = ff(ss[0]); \ + ss[1] ^= ss[0]; k[v(56,(8*(i))+ 9)] = ff(ss[1]); \ + ss[2] ^= ss[1]; k[v(56,(8*(i))+10)] = ff(ss[2]); \ + ss[3] ^= ss[2]; k[v(56,(8*(i))+11)] = ff(ss[3]); \ + ss[4] ^= ls_box(ss[3],0); k[v(56,(8*(i))+12)] = ff(ss[4]); \ + ss[5] ^= ss[4]; k[v(56,(8*(i))+13)] = ff(ss[5]); \ + ss[6] ^= ss[5]; k[v(56,(8*(i))+14)] = ff(ss[6]); \ + ss[7] ^= ss[6]; k[v(56,(8*(i))+15)] = ff(ss[7]); \ +} + +#define kd8(k,i) \ +{ ss[8] = ls_box(ss[7],3) ^ t_use(r,c)[i]; \ + ss[0] ^= ss[8]; ss[8] = ff(ss[8]); k[v(56,(8*(i))+ 8)] = ss[8] ^= k[v(56,(8*(i)))]; \ + ss[1] ^= ss[0]; k[v(56,(8*(i))+ 9)] = ss[8] ^= k[v(56,(8*(i))+ 1)]; \ + ss[2] ^= ss[1]; k[v(56,(8*(i))+10)] = ss[8] ^= k[v(56,(8*(i))+ 2)]; \ + ss[3] ^= ss[2]; k[v(56,(8*(i))+11)] = ss[8] ^= k[v(56,(8*(i))+ 3)]; \ + ss[8] = ls_box(ss[3],0); \ + ss[4] ^= ss[8]; ss[8] = ff(ss[8]); k[v(56,(8*(i))+12)] = ss[8] ^= k[v(56,(8*(i))+ 4)]; \ + ss[5] ^= ss[4]; k[v(56,(8*(i))+13)] = ss[8] ^= k[v(56,(8*(i))+ 5)]; \ + ss[6] ^= ss[5]; k[v(56,(8*(i))+14)] = ss[8] ^= k[v(56,(8*(i))+ 6)]; \ + ss[7] ^= ss[6]; k[v(56,(8*(i))+15)] = ss[8] ^= k[v(56,(8*(i))+ 7)]; \ +} + +#define kdl8(k,i) \ +{ ss[0] ^= ls_box(ss[7],3) ^ t_use(r,c)[i]; k[v(56,(8*(i))+ 8)] = ss[0]; \ + ss[1] ^= ss[0]; k[v(56,(8*(i))+ 9)] = ss[1]; \ + ss[2] ^= ss[1]; k[v(56,(8*(i))+10)] = ss[2]; \ + ss[3] ^= ss[2]; k[v(56,(8*(i))+11)] = ss[3]; \ +} + +AES_RETURN aes_decrypt_key256(const unsigned char *key, aes_decrypt_ctx cx[1]) +{ uint_32t ss[9]; +#if defined( d_vars ) + d_vars; +#endif + cx->ks[v(56,(0))] = ss[0] = word_in(key, 0); + cx->ks[v(56,(1))] = ss[1] = word_in(key, 1); + cx->ks[v(56,(2))] = ss[2] = word_in(key, 2); + cx->ks[v(56,(3))] = ss[3] = word_in(key, 3); + +#if DEC_UNROLL == NONE + cx->ks[v(56,(4))] = ss[4] = word_in(key, 4); + cx->ks[v(56,(5))] = ss[5] = word_in(key, 5); + cx->ks[v(56,(6))] = ss[6] = word_in(key, 6); + cx->ks[v(56,(7))] = ss[7] = word_in(key, 7); + { uint_32t i; + + for(i = 0; i < 6; ++i) + k8e(cx->ks, i); + k8ef(cx->ks, 6); +#if !(DEC_ROUND == NO_TABLES) + for(i = N_COLS; i < 14 * N_COLS; ++i) + cx->ks[i] = inv_mcol(cx->ks[i]); + +#endif + } +#else + ss[4] = word_in(key, 4); cx->ks[v(56,(4))] = ff(ss[4]); + ss[5] = word_in(key, 5); cx->ks[v(56,(5))] = ff(ss[5]); + ss[6] = word_in(key, 6); cx->ks[v(56,(6))] = ff(ss[6]); + ss[7] = word_in(key, 7); cx->ks[v(56,(7))] = ff(ss[7]); + kdf8(cx->ks, 0); kd8(cx->ks, 1); + kd8(cx->ks, 2); kd8(cx->ks, 3); + kd8(cx->ks, 4); kd8(cx->ks, 5); + kdl8(cx->ks, 6); +#endif + cx->inf.l = 0; + cx->inf.b[0] = 14 * 16; + +#ifdef USE_VIA_ACE_IF_PRESENT + if(VIA_ACE_AVAILABLE) + cx->inf.b[1] = 0xff; +#endif + +#if defined( AES_ERR_CHK ) + return EXIT_SUCCESS; +#endif +} + +#endif + +#if defined(AES_VAR) + +AES_RETURN aes_decrypt_key(const unsigned char *key, int key_len, aes_decrypt_ctx cx[1]) +{ + switch(key_len) + { +#if defined( AES_ERR_CHK ) + case 16: case 128: return aes_decrypt_key128(key, cx); + case 24: case 192: return aes_decrypt_key192(key, cx); + case 32: case 256: return aes_decrypt_key256(key, cx); + default: return EXIT_FAILURE; +#else + case 16: case 128: aes_decrypt_key128(key, cx); return; + case 24: case 192: aes_decrypt_key192(key, cx); return; + case 32: case 256: aes_decrypt_key256(key, cx); return; +#endif + } +} + +#endif + +#endif + +#if defined(__cplusplus) +} +#endif diff --git a/src/Crypto/Aesopt.h b/src/Crypto/Aesopt.h index 1b793e43..cf7edbe2 100644 --- a/src/Crypto/Aesopt.h +++ b/src/Crypto/Aesopt.h @@ -1,734 +1,734 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software is allowed (with or without - changes) provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue Date: 20/12/2007 - - This file contains the compilation options for AES (Rijndael) and code - that is common across encryption, key scheduling and table generation. - - OPERATION - - These source code files implement the AES algorithm Rijndael designed by - Joan Daemen and Vincent Rijmen. This version is designed for the standard - block size of 16 bytes and for key sizes of 128, 192 and 256 bits (16, 24 - and 32 bytes). - - This version is designed for flexibility and speed using operations on - 32-bit words rather than operations on bytes. It can be compiled with - either big or little endian internal byte order but is faster when the - native byte order for the processor is used. - - THE CIPHER INTERFACE - - The cipher interface is implemented as an array of bytes in which lower - AES bit sequence indexes map to higher numeric significance within bytes. - - uint_8t (an unsigned 8-bit type) - uint_32t (an unsigned 32-bit type) - struct aes_encrypt_ctx (structure for the cipher encryption context) - struct aes_decrypt_ctx (structure for the cipher decryption context) - AES_RETURN the function return type - - C subroutine calls: - - AES_RETURN aes_encrypt_key128(const unsigned char *key, aes_encrypt_ctx cx[1]); - AES_RETURN aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1]); - AES_RETURN aes_encrypt_key256(const unsigned char *key, aes_encrypt_ctx cx[1]); - AES_RETURN aes_encrypt(const unsigned char *in, unsigned char *out, - const aes_encrypt_ctx cx[1]); - - AES_RETURN aes_decrypt_key128(const unsigned char *key, aes_decrypt_ctx cx[1]); - AES_RETURN aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1]); - AES_RETURN aes_decrypt_key256(const unsigned char *key, aes_decrypt_ctx cx[1]); - AES_RETURN aes_decrypt(const unsigned char *in, unsigned char *out, - const aes_decrypt_ctx cx[1]); - - IMPORTANT NOTE: If you are using this C interface with dynamic tables make sure that - you call aes_init() before AES is used so that the tables are initialised. - - C++ aes class subroutines: - - Class AESencrypt for encryption - - Construtors: - AESencrypt(void) - AESencrypt(const unsigned char *key) - 128 bit key - Members: - AES_RETURN key128(const unsigned char *key) - AES_RETURN key192(const unsigned char *key) - AES_RETURN key256(const unsigned char *key) - AES_RETURN encrypt(const unsigned char *in, unsigned char *out) const - - Class AESdecrypt for encryption - Construtors: - AESdecrypt(void) - AESdecrypt(const unsigned char *key) - 128 bit key - Members: - AES_RETURN key128(const unsigned char *key) - AES_RETURN key192(const unsigned char *key) - AES_RETURN key256(const unsigned char *key) - AES_RETURN decrypt(const unsigned char *in, unsigned char *out) const -*/ - -/* Adapted for TrueCrypt */ - -#if !defined( _AESOPT_H ) -#define _AESOPT_H - -#ifdef TC_WINDOWS_BOOT -#define ASM_X86_V2 -#endif - -#if defined( __cplusplus ) -#include "Aescpp.h" -#else -#include "Aes.h" -#endif - - -#include "Common/Endian.h" -#define IS_LITTLE_ENDIAN 1234 /* byte 0 is least significant (i386) */ -#define IS_BIG_ENDIAN 4321 /* byte 0 is most significant (mc68k) */ - -#if BYTE_ORDER == LITTLE_ENDIAN -# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN -#endif - -#if BYTE_ORDER == BIG_ENDIAN -# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN -#endif - - -/* CONFIGURATION - THE USE OF DEFINES - - Later in this section there are a number of defines that control the - operation of the code. In each section, the purpose of each define is - explained so that the relevant form can be included or excluded by - setting either 1's or 0's respectively on the branches of the related - #if clauses. The following local defines should not be changed. -*/ - -#define ENCRYPTION_IN_C 1 -#define DECRYPTION_IN_C 2 -#define ENC_KEYING_IN_C 4 -#define DEC_KEYING_IN_C 8 - -#define NO_TABLES 0 -#define ONE_TABLE 1 -#define FOUR_TABLES 4 -#define NONE 0 -#define PARTIAL 1 -#define FULL 2 - -/* --- START OF USER CONFIGURED OPTIONS --- */ - -/* 1. BYTE ORDER WITHIN 32 BIT WORDS - - The fundamental data processing units in Rijndael are 8-bit bytes. The - input, output and key input are all enumerated arrays of bytes in which - bytes are numbered starting at zero and increasing to one less than the - number of bytes in the array in question. This enumeration is only used - for naming bytes and does not imply any adjacency or order relationship - from one byte to another. When these inputs and outputs are considered - as bit sequences, bits 8*n to 8*n+7 of the bit sequence are mapped to - byte[n] with bit 8n+i in the sequence mapped to bit 7-i within the byte. - In this implementation bits are numbered from 0 to 7 starting at the - numerically least significant end of each byte (bit n represents 2^n). - - However, Rijndael can be implemented more efficiently using 32-bit - words by packing bytes into words so that bytes 4*n to 4*n+3 are placed - into word[n]. While in principle these bytes can be assembled into words - in any positions, this implementation only supports the two formats in - which bytes in adjacent positions within words also have adjacent byte - numbers. This order is called big-endian if the lowest numbered bytes - in words have the highest numeric significance and little-endian if the - opposite applies. - - This code can work in either order irrespective of the order used by the - machine on which it runs. Normally the internal byte order will be set - to the order of the processor on which the code is to be run but this - define can be used to reverse this in special situations - - WARNING: Assembler code versions rely on PLATFORM_BYTE_ORDER being set. - This define will hence be redefined later (in section 4) if necessary -*/ - -#if 1 -#define ALGORITHM_BYTE_ORDER PLATFORM_BYTE_ORDER -#elif 0 -#define ALGORITHM_BYTE_ORDER IS_LITTLE_ENDIAN -#elif 0 -#define ALGORITHM_BYTE_ORDER IS_BIG_ENDIAN -#else -#error The algorithm byte order is not defined -#endif - -/* 2. VIA ACE SUPPORT - - Define this option if support for the VIA ACE is required. This uses - inline assembler instructions and is only implemented for the Microsoft, - Intel and GCC compilers. If VIA ACE is known to be present, then defining - ASSUME_VIA_ACE_PRESENT will remove the ordinary encryption/decryption - code. If USE_VIA_ACE_IF_PRESENT is defined then VIA ACE will be used if - it is detected (both present and enabled) but the normal AES code will - also be present. - - When VIA ACE is to be used, all AES encryption contexts MUST be 16 byte - aligned; other input/output buffers do not need to be 16 byte aligned - but there are very large performance gains if this can be arranged. - VIA ACE also requires the decryption key schedule to be in reverse - order (which later checks below ensure). -*/ - -#if 0 && !defined( USE_VIA_ACE_IF_PRESENT ) -# define USE_VIA_ACE_IF_PRESENT -#endif - -#if 0 && !defined( ASSUME_VIA_ACE_PRESENT ) -# define ASSUME_VIA_ACE_PRESENT -# endif - -#if defined ( _WIN64 ) || defined( _WIN32_WCE ) || \ - defined( _MSC_VER ) && ( _MSC_VER <= 800 ) -# if defined( USE_VIA_ACE_IF_PRESENT ) -# undef USE_VIA_ACE_IF_PRESENT -# endif -# if defined( ASSUME_VIA_ACE_PRESENT ) -# undef ASSUME_VIA_ACE_PRESENT -# endif -#endif - -/* 3. ASSEMBLER SUPPORT - - This define (which can be on the command line) enables the use of the - assembler code routines for encryption, decryption and key scheduling - as follows: - - ASM_X86_V1C uses the assembler (aes_x86_v1.asm) with large tables for - encryption and decryption and but with key scheduling in C - ASM_X86_V2 uses assembler (aes_x86_v2.asm) with compressed tables for - encryption, decryption and key scheduling - ASM_X86_V2C uses assembler (aes_x86_v2.asm) with compressed tables for - encryption and decryption and but with key scheduling in C - ASM_AMD64_C uses assembler (aes_amd64.asm) with compressed tables for - encryption and decryption and but with key scheduling in C - - Change one 'if 0' below to 'if 1' to select the version or define - as a compilation option. -*/ - -#if 0 && !defined( ASM_X86_V1C ) -# define ASM_X86_V1C -#elif 0 && !defined( ASM_X86_V2 ) -# define ASM_X86_V2 -#elif 0 && !defined( ASM_X86_V2C ) -# define ASM_X86_V2C -#elif 0 && !defined( ASM_AMD64_C ) -# define ASM_AMD64_C -#endif - -#if (defined ( ASM_X86_V1C ) || defined( ASM_X86_V2 ) || defined( ASM_X86_V2C )) \ - && !defined( _M_IX86 ) || defined( ASM_AMD64_C ) && !defined( _M_X64 ) -//# error Assembler code is only available for x86 and AMD64 systems -#endif - -/* 4. FAST INPUT/OUTPUT OPERATIONS. - - On some machines it is possible to improve speed by transferring the - bytes in the input and output arrays to and from the internal 32-bit - variables by addressing these arrays as if they are arrays of 32-bit - words. On some machines this will always be possible but there may - be a large performance penalty if the byte arrays are not aligned on - the normal word boundaries. On other machines this technique will - lead to memory access errors when such 32-bit word accesses are not - properly aligned. The option SAFE_IO avoids such problems but will - often be slower on those machines that support misaligned access - (especially so if care is taken to align the input and output byte - arrays on 32-bit word boundaries). If SAFE_IO is not defined it is - assumed that access to byte arrays as if they are arrays of 32-bit - words will not cause problems when such accesses are misaligned. -*/ -#if 1 && !defined( _MSC_VER ) -#define SAFE_IO -#endif - -/* 5. LOOP UNROLLING - - The code for encryption and decrytpion cycles through a number of rounds - that can be implemented either in a loop or by expanding the code into a - long sequence of instructions, the latter producing a larger program but - one that will often be much faster. The latter is called loop unrolling. - There are also potential speed advantages in expanding two iterations in - a loop with half the number of iterations, which is called partial loop - unrolling. The following options allow partial or full loop unrolling - to be set independently for encryption and decryption -*/ -#if 1 -#define ENC_UNROLL FULL -#elif 0 -#define ENC_UNROLL PARTIAL -#else -#define ENC_UNROLL NONE -#endif - -#if 1 -#define DEC_UNROLL FULL -#elif 0 -#define DEC_UNROLL PARTIAL -#else -#define DEC_UNROLL NONE -#endif - -/* 6. FAST FINITE FIELD OPERATIONS - - If this section is included, tables are used to provide faster finite - field arithmetic (this has no effect if FIXED_TABLES is defined). -*/ -#if !defined (TC_WINDOWS_BOOT) -#define FF_TABLES -#endif - -/* 7. INTERNAL STATE VARIABLE FORMAT - - The internal state of Rijndael is stored in a number of local 32-bit - word varaibles which can be defined either as an array or as individual - names variables. Include this section if you want to store these local - varaibles in arrays. Otherwise individual local variables will be used. -*/ -#if 1 -#define ARRAYS -#endif - -/* 8. FIXED OR DYNAMIC TABLES - - When this section is included the tables used by the code are compiled - statically into the binary file. Otherwise the subroutine aes_init() - must be called to compute them before the code is first used. -*/ -#if !defined (TC_WINDOWS_BOOT) && !(defined( _MSC_VER ) && ( _MSC_VER <= 800 )) -#define FIXED_TABLES -#endif - -/* 9. TABLE ALIGNMENT - - On some sytsems speed will be improved by aligning the AES large lookup - tables on particular boundaries. This define should be set to a power of - two giving the desired alignment. It can be left undefined if alignment - is not needed. This option is specific to the Microsft VC++ compiler - - it seems to sometimes cause trouble for the VC++ version 6 compiler. -*/ - -#if 1 && defined( _MSC_VER ) && ( _MSC_VER >= 1300 ) -#define TABLE_ALIGN 32 -#endif - -/* 10. TABLE OPTIONS - - This cipher proceeds by repeating in a number of cycles known as 'rounds' - which are implemented by a round function which can optionally be speeded - up using tables. The basic tables are each 256 32-bit words, with either - one or four tables being required for each round function depending on - how much speed is required. The encryption and decryption round functions - are different and the last encryption and decrytpion round functions are - different again making four different round functions in all. - - This means that: - 1. Normal encryption and decryption rounds can each use either 0, 1 - or 4 tables and table spaces of 0, 1024 or 4096 bytes each. - 2. The last encryption and decryption rounds can also use either 0, 1 - or 4 tables and table spaces of 0, 1024 or 4096 bytes each. - - Include or exclude the appropriate definitions below to set the number - of tables used by this implementation. -*/ - -#if 1 /* set tables for the normal encryption round */ -#define ENC_ROUND FOUR_TABLES -#elif 0 -#define ENC_ROUND ONE_TABLE -#else -#define ENC_ROUND NO_TABLES -#endif - -#if 1 /* set tables for the last encryption round */ -#define LAST_ENC_ROUND FOUR_TABLES -#elif 0 -#define LAST_ENC_ROUND ONE_TABLE -#else -#define LAST_ENC_ROUND NO_TABLES -#endif - -#if 1 /* set tables for the normal decryption round */ -#define DEC_ROUND FOUR_TABLES -#elif 0 -#define DEC_ROUND ONE_TABLE -#else -#define DEC_ROUND NO_TABLES -#endif - -#if 1 /* set tables for the last decryption round */ -#define LAST_DEC_ROUND FOUR_TABLES -#elif 0 -#define LAST_DEC_ROUND ONE_TABLE -#else -#define LAST_DEC_ROUND NO_TABLES -#endif - -/* The decryption key schedule can be speeded up with tables in the same - way that the round functions can. Include or exclude the following - defines to set this requirement. -*/ -#if 1 -#define KEY_SCHED FOUR_TABLES -#elif 0 -#define KEY_SCHED ONE_TABLE -#else -#define KEY_SCHED NO_TABLES -#endif - -/* ---- END OF USER CONFIGURED OPTIONS ---- */ - -/* VIA ACE support is only available for VC++ and GCC */ - -#if !defined( _MSC_VER ) && !defined( __GNUC__ ) -# if defined( ASSUME_VIA_ACE_PRESENT ) -# undef ASSUME_VIA_ACE_PRESENT -# endif -# if defined( USE_VIA_ACE_IF_PRESENT ) -# undef USE_VIA_ACE_IF_PRESENT -# endif -#endif - -#if defined( ASSUME_VIA_ACE_PRESENT ) && !defined( USE_VIA_ACE_IF_PRESENT ) -#define USE_VIA_ACE_IF_PRESENT -#endif - -#if defined( USE_VIA_ACE_IF_PRESENT ) && !defined ( AES_REV_DKS ) -#define AES_REV_DKS -#endif - -/* Assembler support requires the use of platform byte order */ - -#if ( defined( ASM_X86_V1C ) || defined( ASM_X86_V2C ) || defined( ASM_AMD64_C ) ) \ - && (ALGORITHM_BYTE_ORDER != PLATFORM_BYTE_ORDER) -#undef ALGORITHM_BYTE_ORDER -#define ALGORITHM_BYTE_ORDER PLATFORM_BYTE_ORDER -#endif - -/* In this implementation the columns of the state array are each held in - 32-bit words. The state array can be held in various ways: in an array - of words, in a number of individual word variables or in a number of - processor registers. The following define maps a variable name x and - a column number c to the way the state array variable is to be held. - The first define below maps the state into an array x[c] whereas the - second form maps the state into a number of individual variables x0, - x1, etc. Another form could map individual state colums to machine - register names. -*/ - -#if defined( ARRAYS ) -#define s(x,c) x[c] -#else -#define s(x,c) x##c -#endif - -/* This implementation provides subroutines for encryption, decryption - and for setting the three key lengths (separately) for encryption - and decryption. Since not all functions are needed, masks are set - up here to determine which will be implemented in C -*/ - -#if !defined( AES_ENCRYPT ) -# define EFUNCS_IN_C 0 -#elif defined( ASSUME_VIA_ACE_PRESENT ) || defined( ASM_X86_V1C ) \ - || defined( ASM_X86_V2C ) || defined( ASM_AMD64_C ) -# define EFUNCS_IN_C ENC_KEYING_IN_C -#elif !defined( ASM_X86_V2 ) -# define EFUNCS_IN_C ( ENCRYPTION_IN_C | ENC_KEYING_IN_C ) -#else -# define EFUNCS_IN_C 0 -#endif - -#if !defined( AES_DECRYPT ) -# define DFUNCS_IN_C 0 -#elif defined( ASSUME_VIA_ACE_PRESENT ) || defined( ASM_X86_V1C ) \ - || defined( ASM_X86_V2C ) || defined( ASM_AMD64_C ) -# define DFUNCS_IN_C DEC_KEYING_IN_C -#elif !defined( ASM_X86_V2 ) -# define DFUNCS_IN_C ( DECRYPTION_IN_C | DEC_KEYING_IN_C ) -#else -# define DFUNCS_IN_C 0 -#endif - -#define FUNCS_IN_C ( EFUNCS_IN_C | DFUNCS_IN_C ) - -/* END OF CONFIGURATION OPTIONS */ - -#define RC_LENGTH (5 * (AES_BLOCK_SIZE / 4 - 2)) - -/* Disable or report errors on some combinations of options */ - -#if ENC_ROUND == NO_TABLES && LAST_ENC_ROUND != NO_TABLES -#undef LAST_ENC_ROUND -#define LAST_ENC_ROUND NO_TABLES -#elif ENC_ROUND == ONE_TABLE && LAST_ENC_ROUND == FOUR_TABLES -#undef LAST_ENC_ROUND -#define LAST_ENC_ROUND ONE_TABLE -#endif - -#if ENC_ROUND == NO_TABLES && ENC_UNROLL != NONE -#undef ENC_UNROLL -#define ENC_UNROLL NONE -#endif - -#if DEC_ROUND == NO_TABLES && LAST_DEC_ROUND != NO_TABLES -#undef LAST_DEC_ROUND -#define LAST_DEC_ROUND NO_TABLES -#elif DEC_ROUND == ONE_TABLE && LAST_DEC_ROUND == FOUR_TABLES -#undef LAST_DEC_ROUND -#define LAST_DEC_ROUND ONE_TABLE -#endif - -#if DEC_ROUND == NO_TABLES && DEC_UNROLL != NONE -#undef DEC_UNROLL -#define DEC_UNROLL NONE -#endif - -#if defined( bswap32 ) -#define aes_sw32 bswap32 -#elif defined( bswap_32 ) -#define aes_sw32 bswap_32 -#else -#define brot(x,n) (((uint_32t)(x) << n) | ((uint_32t)(x) >> (32 - n))) -#define aes_sw32(x) ((brot((x),8) & 0x00ff00ff) | (brot((x),24) & 0xff00ff00)) -#endif - -/* upr(x,n): rotates bytes within words by n positions, moving bytes to - higher index positions with wrap around into low positions - ups(x,n): moves bytes by n positions to higher index positions in - words but without wrap around - bval(x,n): extracts a byte from a word - - WARNING: The definitions given here are intended only for use with - unsigned variables and with shift counts that are compile - time constants -*/ - -#if ( ALGORITHM_BYTE_ORDER == IS_LITTLE_ENDIAN ) -#define upr(x,n) (((uint_32t)(x) << (8 * (n))) | ((uint_32t)(x) >> (32 - 8 * (n)))) -#define ups(x,n) ((uint_32t) (x) << (8 * (n))) -#define bval(x,n) ((uint_8t)((x) >> (8 * (n)))) -#define bytes2word(b0, b1, b2, b3) \ - (((uint_32t)(b3) << 24) | ((uint_32t)(b2) << 16) | ((uint_32t)(b1) << 8) | (b0)) -#endif - -#if ( ALGORITHM_BYTE_ORDER == IS_BIG_ENDIAN ) -#define upr(x,n) (((uint_32t)(x) >> (8 * (n))) | ((uint_32t)(x) << (32 - 8 * (n)))) -#define ups(x,n) ((uint_32t) (x) >> (8 * (n))) -#define bval(x,n) ((uint_8t)((x) >> (24 - 8 * (n)))) -#define bytes2word(b0, b1, b2, b3) \ - (((uint_32t)(b0) << 24) | ((uint_32t)(b1) << 16) | ((uint_32t)(b2) << 8) | (b3)) -#endif - -#if defined( SAFE_IO ) - -#define word_in(x,c) bytes2word(((const uint_8t*)(x)+4*c)[0], ((const uint_8t*)(x)+4*c)[1], \ - ((const uint_8t*)(x)+4*c)[2], ((const uint_8t*)(x)+4*c)[3]) -#define word_out(x,c,v) { ((uint_8t*)(x)+4*c)[0] = bval(v,0); ((uint_8t*)(x)+4*c)[1] = bval(v,1); \ - ((uint_8t*)(x)+4*c)[2] = bval(v,2); ((uint_8t*)(x)+4*c)[3] = bval(v,3); } - -#elif ( ALGORITHM_BYTE_ORDER == PLATFORM_BYTE_ORDER ) - -#define word_in(x,c) (*((uint_32t*)(x)+(c))) -#define word_out(x,c,v) (*((uint_32t*)(x)+(c)) = (v)) - -#else - -#define word_in(x,c) aes_sw32(*((uint_32t*)(x)+(c))) -#define word_out(x,c,v) (*((uint_32t*)(x)+(c)) = aes_sw32(v)) - -#endif - -/* the finite field modular polynomial and elements */ - -#define WPOLY 0x011b -#define BPOLY 0x1b - -/* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ - -#define m1 0x80808080 -#define m2 0x7f7f7f7f -#define gf_mulx(x) ((((x) & m2) << 1) ^ ((((x) & m1) >> 7) * BPOLY)) - -/* The following defines provide alternative definitions of gf_mulx that might - give improved performance if a fast 32-bit multiply is not available. Note - that a temporary variable u needs to be defined where gf_mulx is used. - -#define gf_mulx(x) (u = (x) & m1, u |= (u >> 1), ((x) & m2) << 1) ^ ((u >> 3) | (u >> 6)) -#define m4 (0x01010101 * BPOLY) -#define gf_mulx(x) (u = (x) & m1, ((x) & m2) << 1) ^ ((u - (u >> 7)) & m4) -*/ - -/* Work out which tables are needed for the different options */ - -#if defined( ASM_X86_V1C ) -#if defined( ENC_ROUND ) -#undef ENC_ROUND -#endif -#define ENC_ROUND FOUR_TABLES -#if defined( LAST_ENC_ROUND ) -#undef LAST_ENC_ROUND -#endif -#define LAST_ENC_ROUND FOUR_TABLES -#if defined( DEC_ROUND ) -#undef DEC_ROUND -#endif -#define DEC_ROUND FOUR_TABLES -#if defined( LAST_DEC_ROUND ) -#undef LAST_DEC_ROUND -#endif -#define LAST_DEC_ROUND FOUR_TABLES -#if defined( KEY_SCHED ) -#undef KEY_SCHED -#define KEY_SCHED FOUR_TABLES -#endif -#endif - -#if ( FUNCS_IN_C & ENCRYPTION_IN_C ) || defined( ASM_X86_V1C ) -#if ENC_ROUND == ONE_TABLE -#define FT1_SET -#elif ENC_ROUND == FOUR_TABLES -#define FT4_SET -#else -#define SBX_SET -#endif -#if LAST_ENC_ROUND == ONE_TABLE -#define FL1_SET -#elif LAST_ENC_ROUND == FOUR_TABLES -#define FL4_SET -#elif !defined( SBX_SET ) -#define SBX_SET -#endif -#endif - -#if ( FUNCS_IN_C & DECRYPTION_IN_C ) || defined( ASM_X86_V1C ) -#if DEC_ROUND == ONE_TABLE -#define IT1_SET -#elif DEC_ROUND == FOUR_TABLES -#define IT4_SET -#else -#define ISB_SET -#endif -#if LAST_DEC_ROUND == ONE_TABLE -#define IL1_SET -#elif LAST_DEC_ROUND == FOUR_TABLES -#define IL4_SET -#elif !defined(ISB_SET) -#define ISB_SET -#endif -#endif - -#if (FUNCS_IN_C & ENC_KEYING_IN_C) || (FUNCS_IN_C & DEC_KEYING_IN_C) -#if KEY_SCHED == ONE_TABLE -#define LS1_SET -#elif KEY_SCHED == FOUR_TABLES -#define LS4_SET -#elif !defined( SBX_SET ) -#define SBX_SET -#endif -#endif - -#if (FUNCS_IN_C & DEC_KEYING_IN_C) -#if KEY_SCHED == ONE_TABLE -#define IM1_SET -#elif KEY_SCHED == FOUR_TABLES -#define IM4_SET -#elif !defined( SBX_SET ) -#define SBX_SET -#endif -#endif - -/* generic definitions of Rijndael macros that use tables */ - -#define no_table(x,box,vf,rf,c) bytes2word( \ - box[bval(vf(x,0,c),rf(0,c))], \ - box[bval(vf(x,1,c),rf(1,c))], \ - box[bval(vf(x,2,c),rf(2,c))], \ - box[bval(vf(x,3,c),rf(3,c))]) - -#define one_table(x,op,tab,vf,rf,c) \ - ( tab[bval(vf(x,0,c),rf(0,c))] \ - ^ op(tab[bval(vf(x,1,c),rf(1,c))],1) \ - ^ op(tab[bval(vf(x,2,c),rf(2,c))],2) \ - ^ op(tab[bval(vf(x,3,c),rf(3,c))],3)) - -#define four_tables(x,tab,vf,rf,c) \ - ( tab[0][bval(vf(x,0,c),rf(0,c))] \ - ^ tab[1][bval(vf(x,1,c),rf(1,c))] \ - ^ tab[2][bval(vf(x,2,c),rf(2,c))] \ - ^ tab[3][bval(vf(x,3,c),rf(3,c))]) - -#define vf1(x,r,c) (x) -#define rf1(r,c) (r) -#define rf2(r,c) ((8+r-c)&3) - -/* perform forward and inverse column mix operation on four bytes in long word x in */ -/* parallel. NOTE: x must be a simple variable, NOT an expression in these macros. */ - -#if defined( FM4_SET ) /* not currently used */ -#define fwd_mcol(x) four_tables(x,t_use(f,m),vf1,rf1,0) -#elif defined( FM1_SET ) /* not currently used */ -#define fwd_mcol(x) one_table(x,upr,t_use(f,m),vf1,rf1,0) -#else -#define dec_fmvars uint_32t g2 -#define fwd_mcol(x) (g2 = gf_mulx(x), g2 ^ upr((x) ^ g2, 3) ^ upr((x), 2) ^ upr((x), 1)) -#endif - -#if defined( IM4_SET ) -#define inv_mcol(x) four_tables(x,t_use(i,m),vf1,rf1,0) -#elif defined( IM1_SET ) -#define inv_mcol(x) one_table(x,upr,t_use(i,m),vf1,rf1,0) -#else -#define dec_imvars uint_32t g2, g4, g9 -#define inv_mcol(x) (g2 = gf_mulx(x), g4 = gf_mulx(g2), g9 = (x) ^ gf_mulx(g4), g4 ^= g9, \ - (x) ^ g2 ^ g4 ^ upr(g2 ^ g9, 3) ^ upr(g4, 2) ^ upr(g9, 1)) -#endif - -#if defined( FL4_SET ) -#define ls_box(x,c) four_tables(x,t_use(f,l),vf1,rf2,c) -#elif defined( LS4_SET ) -#define ls_box(x,c) four_tables(x,t_use(l,s),vf1,rf2,c) -#elif defined( FL1_SET ) -#define ls_box(x,c) one_table(x,upr,t_use(f,l),vf1,rf2,c) -#elif defined( LS1_SET ) -#define ls_box(x,c) one_table(x,upr,t_use(l,s),vf1,rf2,c) -#else -#define ls_box(x,c) no_table(x,t_use(s,box),vf1,rf2,c) -#endif - -#if defined( ASM_X86_V1C ) && defined( AES_DECRYPT ) && !defined( ISB_SET ) -#define ISB_SET -#endif - -#endif +/* + --------------------------------------------------------------------------- + Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software is allowed (with or without + changes) provided that: + + 1. source code distributions include the above copyright notice, this + list of conditions and the following disclaimer; + + 2. binary distributions include the above copyright notice, this list + of conditions and the following disclaimer in their documentation; + + 3. the name of the copyright holder is not used to endorse products + built using this software without specific written permission. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + Issue Date: 20/12/2007 + + This file contains the compilation options for AES (Rijndael) and code + that is common across encryption, key scheduling and table generation. + + OPERATION + + These source code files implement the AES algorithm Rijndael designed by + Joan Daemen and Vincent Rijmen. This version is designed for the standard + block size of 16 bytes and for key sizes of 128, 192 and 256 bits (16, 24 + and 32 bytes). + + This version is designed for flexibility and speed using operations on + 32-bit words rather than operations on bytes. It can be compiled with + either big or little endian internal byte order but is faster when the + native byte order for the processor is used. + + THE CIPHER INTERFACE + + The cipher interface is implemented as an array of bytes in which lower + AES bit sequence indexes map to higher numeric significance within bytes. + + uint_8t (an unsigned 8-bit type) + uint_32t (an unsigned 32-bit type) + struct aes_encrypt_ctx (structure for the cipher encryption context) + struct aes_decrypt_ctx (structure for the cipher decryption context) + AES_RETURN the function return type + + C subroutine calls: + + AES_RETURN aes_encrypt_key128(const unsigned char *key, aes_encrypt_ctx cx[1]); + AES_RETURN aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1]); + AES_RETURN aes_encrypt_key256(const unsigned char *key, aes_encrypt_ctx cx[1]); + AES_RETURN aes_encrypt(const unsigned char *in, unsigned char *out, + const aes_encrypt_ctx cx[1]); + + AES_RETURN aes_decrypt_key128(const unsigned char *key, aes_decrypt_ctx cx[1]); + AES_RETURN aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1]); + AES_RETURN aes_decrypt_key256(const unsigned char *key, aes_decrypt_ctx cx[1]); + AES_RETURN aes_decrypt(const unsigned char *in, unsigned char *out, + const aes_decrypt_ctx cx[1]); + + IMPORTANT NOTE: If you are using this C interface with dynamic tables make sure that + you call aes_init() before AES is used so that the tables are initialised. + + C++ aes class subroutines: + + Class AESencrypt for encryption + + Construtors: + AESencrypt(void) + AESencrypt(const unsigned char *key) - 128 bit key + Members: + AES_RETURN key128(const unsigned char *key) + AES_RETURN key192(const unsigned char *key) + AES_RETURN key256(const unsigned char *key) + AES_RETURN encrypt(const unsigned char *in, unsigned char *out) const + + Class AESdecrypt for encryption + Construtors: + AESdecrypt(void) + AESdecrypt(const unsigned char *key) - 128 bit key + Members: + AES_RETURN key128(const unsigned char *key) + AES_RETURN key192(const unsigned char *key) + AES_RETURN key256(const unsigned char *key) + AES_RETURN decrypt(const unsigned char *in, unsigned char *out) const +*/ + +/* Adapted for TrueCrypt */ + +#if !defined( _AESOPT_H ) +#define _AESOPT_H + +#ifdef TC_WINDOWS_BOOT +#define ASM_X86_V2 +#endif + +#if defined( __cplusplus ) +#include "Aescpp.h" +#else +#include "Aes.h" +#endif + + +#include "Common/Endian.h" +#define IS_LITTLE_ENDIAN 1234 /* byte 0 is least significant (i386) */ +#define IS_BIG_ENDIAN 4321 /* byte 0 is most significant (mc68k) */ + +#if BYTE_ORDER == LITTLE_ENDIAN +# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN +#endif + +#if BYTE_ORDER == BIG_ENDIAN +# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN +#endif + + +/* CONFIGURATION - THE USE OF DEFINES + + Later in this section there are a number of defines that control the + operation of the code. In each section, the purpose of each define is + explained so that the relevant form can be included or excluded by + setting either 1's or 0's respectively on the branches of the related + #if clauses. The following local defines should not be changed. +*/ + +#define ENCRYPTION_IN_C 1 +#define DECRYPTION_IN_C 2 +#define ENC_KEYING_IN_C 4 +#define DEC_KEYING_IN_C 8 + +#define NO_TABLES 0 +#define ONE_TABLE 1 +#define FOUR_TABLES 4 +#define NONE 0 +#define PARTIAL 1 +#define FULL 2 + +/* --- START OF USER CONFIGURED OPTIONS --- */ + +/* 1. BYTE ORDER WITHIN 32 BIT WORDS + + The fundamental data processing units in Rijndael are 8-bit bytes. The + input, output and key input are all enumerated arrays of bytes in which + bytes are numbered starting at zero and increasing to one less than the + number of bytes in the array in question. This enumeration is only used + for naming bytes and does not imply any adjacency or order relationship + from one byte to another. When these inputs and outputs are considered + as bit sequences, bits 8*n to 8*n+7 of the bit sequence are mapped to + byte[n] with bit 8n+i in the sequence mapped to bit 7-i within the byte. + In this implementation bits are numbered from 0 to 7 starting at the + numerically least significant end of each byte (bit n represents 2^n). + + However, Rijndael can be implemented more efficiently using 32-bit + words by packing bytes into words so that bytes 4*n to 4*n+3 are placed + into word[n]. While in principle these bytes can be assembled into words + in any positions, this implementation only supports the two formats in + which bytes in adjacent positions within words also have adjacent byte + numbers. This order is called big-endian if the lowest numbered bytes + in words have the highest numeric significance and little-endian if the + opposite applies. + + This code can work in either order irrespective of the order used by the + machine on which it runs. Normally the internal byte order will be set + to the order of the processor on which the code is to be run but this + define can be used to reverse this in special situations + + WARNING: Assembler code versions rely on PLATFORM_BYTE_ORDER being set. + This define will hence be redefined later (in section 4) if necessary +*/ + +#if 1 +#define ALGORITHM_BYTE_ORDER PLATFORM_BYTE_ORDER +#elif 0 +#define ALGORITHM_BYTE_ORDER IS_LITTLE_ENDIAN +#elif 0 +#define ALGORITHM_BYTE_ORDER IS_BIG_ENDIAN +#else +#error The algorithm byte order is not defined +#endif + +/* 2. VIA ACE SUPPORT + + Define this option if support for the VIA ACE is required. This uses + inline assembler instructions and is only implemented for the Microsoft, + Intel and GCC compilers. If VIA ACE is known to be present, then defining + ASSUME_VIA_ACE_PRESENT will remove the ordinary encryption/decryption + code. If USE_VIA_ACE_IF_PRESENT is defined then VIA ACE will be used if + it is detected (both present and enabled) but the normal AES code will + also be present. + + When VIA ACE is to be used, all AES encryption contexts MUST be 16 byte + aligned; other input/output buffers do not need to be 16 byte aligned + but there are very large performance gains if this can be arranged. + VIA ACE also requires the decryption key schedule to be in reverse + order (which later checks below ensure). +*/ + +#if 0 && !defined( USE_VIA_ACE_IF_PRESENT ) +# define USE_VIA_ACE_IF_PRESENT +#endif + +#if 0 && !defined( ASSUME_VIA_ACE_PRESENT ) +# define ASSUME_VIA_ACE_PRESENT +# endif + +#if defined ( _WIN64 ) || defined( _WIN32_WCE ) || \ + defined( _MSC_VER ) && ( _MSC_VER <= 800 ) +# if defined( USE_VIA_ACE_IF_PRESENT ) +# undef USE_VIA_ACE_IF_PRESENT +# endif +# if defined( ASSUME_VIA_ACE_PRESENT ) +# undef ASSUME_VIA_ACE_PRESENT +# endif +#endif + +/* 3. ASSEMBLER SUPPORT + + This define (which can be on the command line) enables the use of the + assembler code routines for encryption, decryption and key scheduling + as follows: + + ASM_X86_V1C uses the assembler (aes_x86_v1.asm) with large tables for + encryption and decryption and but with key scheduling in C + ASM_X86_V2 uses assembler (aes_x86_v2.asm) with compressed tables for + encryption, decryption and key scheduling + ASM_X86_V2C uses assembler (aes_x86_v2.asm) with compressed tables for + encryption and decryption and but with key scheduling in C + ASM_AMD64_C uses assembler (aes_amd64.asm) with compressed tables for + encryption and decryption and but with key scheduling in C + + Change one 'if 0' below to 'if 1' to select the version or define + as a compilation option. +*/ + +#if 0 && !defined( ASM_X86_V1C ) +# define ASM_X86_V1C +#elif 0 && !defined( ASM_X86_V2 ) +# define ASM_X86_V2 +#elif 0 && !defined( ASM_X86_V2C ) +# define ASM_X86_V2C +#elif 0 && !defined( ASM_AMD64_C ) +# define ASM_AMD64_C +#endif + +#if (defined ( ASM_X86_V1C ) || defined( ASM_X86_V2 ) || defined( ASM_X86_V2C )) \ + && !defined( _M_IX86 ) || defined( ASM_AMD64_C ) && !defined( _M_X64 ) +//# error Assembler code is only available for x86 and AMD64 systems +#endif + +/* 4. FAST INPUT/OUTPUT OPERATIONS. + + On some machines it is possible to improve speed by transferring the + bytes in the input and output arrays to and from the internal 32-bit + variables by addressing these arrays as if they are arrays of 32-bit + words. On some machines this will always be possible but there may + be a large performance penalty if the byte arrays are not aligned on + the normal word boundaries. On other machines this technique will + lead to memory access errors when such 32-bit word accesses are not + properly aligned. The option SAFE_IO avoids such problems but will + often be slower on those machines that support misaligned access + (especially so if care is taken to align the input and output byte + arrays on 32-bit word boundaries). If SAFE_IO is not defined it is + assumed that access to byte arrays as if they are arrays of 32-bit + words will not cause problems when such accesses are misaligned. +*/ +#if 1 && !defined( _MSC_VER ) +#define SAFE_IO +#endif + +/* 5. LOOP UNROLLING + + The code for encryption and decrytpion cycles through a number of rounds + that can be implemented either in a loop or by expanding the code into a + long sequence of instructions, the latter producing a larger program but + one that will often be much faster. The latter is called loop unrolling. + There are also potential speed advantages in expanding two iterations in + a loop with half the number of iterations, which is called partial loop + unrolling. The following options allow partial or full loop unrolling + to be set independently for encryption and decryption +*/ +#if 1 +#define ENC_UNROLL FULL +#elif 0 +#define ENC_UNROLL PARTIAL +#else +#define ENC_UNROLL NONE +#endif + +#if 1 +#define DEC_UNROLL FULL +#elif 0 +#define DEC_UNROLL PARTIAL +#else +#define DEC_UNROLL NONE +#endif + +/* 6. FAST FINITE FIELD OPERATIONS + + If this section is included, tables are used to provide faster finite + field arithmetic (this has no effect if FIXED_TABLES is defined). +*/ +#if !defined (TC_WINDOWS_BOOT) +#define FF_TABLES +#endif + +/* 7. INTERNAL STATE VARIABLE FORMAT + + The internal state of Rijndael is stored in a number of local 32-bit + word varaibles which can be defined either as an array or as individual + names variables. Include this section if you want to store these local + varaibles in arrays. Otherwise individual local variables will be used. +*/ +#if 1 +#define ARRAYS +#endif + +/* 8. FIXED OR DYNAMIC TABLES + + When this section is included the tables used by the code are compiled + statically into the binary file. Otherwise the subroutine aes_init() + must be called to compute them before the code is first used. +*/ +#if !defined (TC_WINDOWS_BOOT) && !(defined( _MSC_VER ) && ( _MSC_VER <= 800 )) +#define FIXED_TABLES +#endif + +/* 9. TABLE ALIGNMENT + + On some sytsems speed will be improved by aligning the AES large lookup + tables on particular boundaries. This define should be set to a power of + two giving the desired alignment. It can be left undefined if alignment + is not needed. This option is specific to the Microsft VC++ compiler - + it seems to sometimes cause trouble for the VC++ version 6 compiler. +*/ + +#if 1 && defined( _MSC_VER ) && ( _MSC_VER >= 1300 ) +#define TABLE_ALIGN 32 +#endif + +/* 10. TABLE OPTIONS + + This cipher proceeds by repeating in a number of cycles known as 'rounds' + which are implemented by a round function which can optionally be speeded + up using tables. The basic tables are each 256 32-bit words, with either + one or four tables being required for each round function depending on + how much speed is required. The encryption and decryption round functions + are different and the last encryption and decrytpion round functions are + different again making four different round functions in all. + + This means that: + 1. Normal encryption and decryption rounds can each use either 0, 1 + or 4 tables and table spaces of 0, 1024 or 4096 bytes each. + 2. The last encryption and decryption rounds can also use either 0, 1 + or 4 tables and table spaces of 0, 1024 or 4096 bytes each. + + Include or exclude the appropriate definitions below to set the number + of tables used by this implementation. +*/ + +#if 1 /* set tables for the normal encryption round */ +#define ENC_ROUND FOUR_TABLES +#elif 0 +#define ENC_ROUND ONE_TABLE +#else +#define ENC_ROUND NO_TABLES +#endif + +#if 1 /* set tables for the last encryption round */ +#define LAST_ENC_ROUND FOUR_TABLES +#elif 0 +#define LAST_ENC_ROUND ONE_TABLE +#else +#define LAST_ENC_ROUND NO_TABLES +#endif + +#if 1 /* set tables for the normal decryption round */ +#define DEC_ROUND FOUR_TABLES +#elif 0 +#define DEC_ROUND ONE_TABLE +#else +#define DEC_ROUND NO_TABLES +#endif + +#if 1 /* set tables for the last decryption round */ +#define LAST_DEC_ROUND FOUR_TABLES +#elif 0 +#define LAST_DEC_ROUND ONE_TABLE +#else +#define LAST_DEC_ROUND NO_TABLES +#endif + +/* The decryption key schedule can be speeded up with tables in the same + way that the round functions can. Include or exclude the following + defines to set this requirement. +*/ +#if 1 +#define KEY_SCHED FOUR_TABLES +#elif 0 +#define KEY_SCHED ONE_TABLE +#else +#define KEY_SCHED NO_TABLES +#endif + +/* ---- END OF USER CONFIGURED OPTIONS ---- */ + +/* VIA ACE support is only available for VC++ and GCC */ + +#if !defined( _MSC_VER ) && !defined( __GNUC__ ) +# if defined( ASSUME_VIA_ACE_PRESENT ) +# undef ASSUME_VIA_ACE_PRESENT +# endif +# if defined( USE_VIA_ACE_IF_PRESENT ) +# undef USE_VIA_ACE_IF_PRESENT +# endif +#endif + +#if defined( ASSUME_VIA_ACE_PRESENT ) && !defined( USE_VIA_ACE_IF_PRESENT ) +#define USE_VIA_ACE_IF_PRESENT +#endif + +#if defined( USE_VIA_ACE_IF_PRESENT ) && !defined ( AES_REV_DKS ) +#define AES_REV_DKS +#endif + +/* Assembler support requires the use of platform byte order */ + +#if ( defined( ASM_X86_V1C ) || defined( ASM_X86_V2C ) || defined( ASM_AMD64_C ) ) \ + && (ALGORITHM_BYTE_ORDER != PLATFORM_BYTE_ORDER) +#undef ALGORITHM_BYTE_ORDER +#define ALGORITHM_BYTE_ORDER PLATFORM_BYTE_ORDER +#endif + +/* In this implementation the columns of the state array are each held in + 32-bit words. The state array can be held in various ways: in an array + of words, in a number of individual word variables or in a number of + processor registers. The following define maps a variable name x and + a column number c to the way the state array variable is to be held. + The first define below maps the state into an array x[c] whereas the + second form maps the state into a number of individual variables x0, + x1, etc. Another form could map individual state colums to machine + register names. +*/ + +#if defined( ARRAYS ) +#define s(x,c) x[c] +#else +#define s(x,c) x##c +#endif + +/* This implementation provides subroutines for encryption, decryption + and for setting the three key lengths (separately) for encryption + and decryption. Since not all functions are needed, masks are set + up here to determine which will be implemented in C +*/ + +#if !defined( AES_ENCRYPT ) +# define EFUNCS_IN_C 0 +#elif defined( ASSUME_VIA_ACE_PRESENT ) || defined( ASM_X86_V1C ) \ + || defined( ASM_X86_V2C ) || defined( ASM_AMD64_C ) +# define EFUNCS_IN_C ENC_KEYING_IN_C +#elif !defined( ASM_X86_V2 ) +# define EFUNCS_IN_C ( ENCRYPTION_IN_C | ENC_KEYING_IN_C ) +#else +# define EFUNCS_IN_C 0 +#endif + +#if !defined( AES_DECRYPT ) +# define DFUNCS_IN_C 0 +#elif defined( ASSUME_VIA_ACE_PRESENT ) || defined( ASM_X86_V1C ) \ + || defined( ASM_X86_V2C ) || defined( ASM_AMD64_C ) +# define DFUNCS_IN_C DEC_KEYING_IN_C +#elif !defined( ASM_X86_V2 ) +# define DFUNCS_IN_C ( DECRYPTION_IN_C | DEC_KEYING_IN_C ) +#else +# define DFUNCS_IN_C 0 +#endif + +#define FUNCS_IN_C ( EFUNCS_IN_C | DFUNCS_IN_C ) + +/* END OF CONFIGURATION OPTIONS */ + +#define RC_LENGTH (5 * (AES_BLOCK_SIZE / 4 - 2)) + +/* Disable or report errors on some combinations of options */ + +#if ENC_ROUND == NO_TABLES && LAST_ENC_ROUND != NO_TABLES +#undef LAST_ENC_ROUND +#define LAST_ENC_ROUND NO_TABLES +#elif ENC_ROUND == ONE_TABLE && LAST_ENC_ROUND == FOUR_TABLES +#undef LAST_ENC_ROUND +#define LAST_ENC_ROUND ONE_TABLE +#endif + +#if ENC_ROUND == NO_TABLES && ENC_UNROLL != NONE +#undef ENC_UNROLL +#define ENC_UNROLL NONE +#endif + +#if DEC_ROUND == NO_TABLES && LAST_DEC_ROUND != NO_TABLES +#undef LAST_DEC_ROUND +#define LAST_DEC_ROUND NO_TABLES +#elif DEC_ROUND == ONE_TABLE && LAST_DEC_ROUND == FOUR_TABLES +#undef LAST_DEC_ROUND +#define LAST_DEC_ROUND ONE_TABLE +#endif + +#if DEC_ROUND == NO_TABLES && DEC_UNROLL != NONE +#undef DEC_UNROLL +#define DEC_UNROLL NONE +#endif + +#if defined( bswap32 ) +#define aes_sw32 bswap32 +#elif defined( bswap_32 ) +#define aes_sw32 bswap_32 +#else +#define brot(x,n) (((uint_32t)(x) << n) | ((uint_32t)(x) >> (32 - n))) +#define aes_sw32(x) ((brot((x),8) & 0x00ff00ff) | (brot((x),24) & 0xff00ff00)) +#endif + +/* upr(x,n): rotates bytes within words by n positions, moving bytes to + higher index positions with wrap around into low positions + ups(x,n): moves bytes by n positions to higher index positions in + words but without wrap around + bval(x,n): extracts a byte from a word + + WARNING: The definitions given here are intended only for use with + unsigned variables and with shift counts that are compile + time constants +*/ + +#if ( ALGORITHM_BYTE_ORDER == IS_LITTLE_ENDIAN ) +#define upr(x,n) (((uint_32t)(x) << (8 * (n))) | ((uint_32t)(x) >> (32 - 8 * (n)))) +#define ups(x,n) ((uint_32t) (x) << (8 * (n))) +#define bval(x,n) ((uint_8t)((x) >> (8 * (n)))) +#define bytes2word(b0, b1, b2, b3) \ + (((uint_32t)(b3) << 24) | ((uint_32t)(b2) << 16) | ((uint_32t)(b1) << 8) | (b0)) +#endif + +#if ( ALGORITHM_BYTE_ORDER == IS_BIG_ENDIAN ) +#define upr(x,n) (((uint_32t)(x) >> (8 * (n))) | ((uint_32t)(x) << (32 - 8 * (n)))) +#define ups(x,n) ((uint_32t) (x) >> (8 * (n))) +#define bval(x,n) ((uint_8t)((x) >> (24 - 8 * (n)))) +#define bytes2word(b0, b1, b2, b3) \ + (((uint_32t)(b0) << 24) | ((uint_32t)(b1) << 16) | ((uint_32t)(b2) << 8) | (b3)) +#endif + +#if defined( SAFE_IO ) + +#define word_in(x,c) bytes2word(((const uint_8t*)(x)+4*c)[0], ((const uint_8t*)(x)+4*c)[1], \ + ((const uint_8t*)(x)+4*c)[2], ((const uint_8t*)(x)+4*c)[3]) +#define word_out(x,c,v) { ((uint_8t*)(x)+4*c)[0] = bval(v,0); ((uint_8t*)(x)+4*c)[1] = bval(v,1); \ + ((uint_8t*)(x)+4*c)[2] = bval(v,2); ((uint_8t*)(x)+4*c)[3] = bval(v,3); } + +#elif ( ALGORITHM_BYTE_ORDER == PLATFORM_BYTE_ORDER ) + +#define word_in(x,c) (*((uint_32t*)(x)+(c))) +#define word_out(x,c,v) (*((uint_32t*)(x)+(c)) = (v)) + +#else + +#define word_in(x,c) aes_sw32(*((uint_32t*)(x)+(c))) +#define word_out(x,c,v) (*((uint_32t*)(x)+(c)) = aes_sw32(v)) + +#endif + +/* the finite field modular polynomial and elements */ + +#define WPOLY 0x011b +#define BPOLY 0x1b + +/* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ + +#define m1 0x80808080 +#define m2 0x7f7f7f7f +#define gf_mulx(x) ((((x) & m2) << 1) ^ ((((x) & m1) >> 7) * BPOLY)) + +/* The following defines provide alternative definitions of gf_mulx that might + give improved performance if a fast 32-bit multiply is not available. Note + that a temporary variable u needs to be defined where gf_mulx is used. + +#define gf_mulx(x) (u = (x) & m1, u |= (u >> 1), ((x) & m2) << 1) ^ ((u >> 3) | (u >> 6)) +#define m4 (0x01010101 * BPOLY) +#define gf_mulx(x) (u = (x) & m1, ((x) & m2) << 1) ^ ((u - (u >> 7)) & m4) +*/ + +/* Work out which tables are needed for the different options */ + +#if defined( ASM_X86_V1C ) +#if defined( ENC_ROUND ) +#undef ENC_ROUND +#endif +#define ENC_ROUND FOUR_TABLES +#if defined( LAST_ENC_ROUND ) +#undef LAST_ENC_ROUND +#endif +#define LAST_ENC_ROUND FOUR_TABLES +#if defined( DEC_ROUND ) +#undef DEC_ROUND +#endif +#define DEC_ROUND FOUR_TABLES +#if defined( LAST_DEC_ROUND ) +#undef LAST_DEC_ROUND +#endif +#define LAST_DEC_ROUND FOUR_TABLES +#if defined( KEY_SCHED ) +#undef KEY_SCHED +#define KEY_SCHED FOUR_TABLES +#endif +#endif + +#if ( FUNCS_IN_C & ENCRYPTION_IN_C ) || defined( ASM_X86_V1C ) +#if ENC_ROUND == ONE_TABLE +#define FT1_SET +#elif ENC_ROUND == FOUR_TABLES +#define FT4_SET +#else +#define SBX_SET +#endif +#if LAST_ENC_ROUND == ONE_TABLE +#define FL1_SET +#elif LAST_ENC_ROUND == FOUR_TABLES +#define FL4_SET +#elif !defined( SBX_SET ) +#define SBX_SET +#endif +#endif + +#if ( FUNCS_IN_C & DECRYPTION_IN_C ) || defined( ASM_X86_V1C ) +#if DEC_ROUND == ONE_TABLE +#define IT1_SET +#elif DEC_ROUND == FOUR_TABLES +#define IT4_SET +#else +#define ISB_SET +#endif +#if LAST_DEC_ROUND == ONE_TABLE +#define IL1_SET +#elif LAST_DEC_ROUND == FOUR_TABLES +#define IL4_SET +#elif !defined(ISB_SET) +#define ISB_SET +#endif +#endif + +#if (FUNCS_IN_C & ENC_KEYING_IN_C) || (FUNCS_IN_C & DEC_KEYING_IN_C) +#if KEY_SCHED == ONE_TABLE +#define LS1_SET +#elif KEY_SCHED == FOUR_TABLES +#define LS4_SET +#elif !defined( SBX_SET ) +#define SBX_SET +#endif +#endif + +#if (FUNCS_IN_C & DEC_KEYING_IN_C) +#if KEY_SCHED == ONE_TABLE +#define IM1_SET +#elif KEY_SCHED == FOUR_TABLES +#define IM4_SET +#elif !defined( SBX_SET ) +#define SBX_SET +#endif +#endif + +/* generic definitions of Rijndael macros that use tables */ + +#define no_table(x,box,vf,rf,c) bytes2word( \ + box[bval(vf(x,0,c),rf(0,c))], \ + box[bval(vf(x,1,c),rf(1,c))], \ + box[bval(vf(x,2,c),rf(2,c))], \ + box[bval(vf(x,3,c),rf(3,c))]) + +#define one_table(x,op,tab,vf,rf,c) \ + ( tab[bval(vf(x,0,c),rf(0,c))] \ + ^ op(tab[bval(vf(x,1,c),rf(1,c))],1) \ + ^ op(tab[bval(vf(x,2,c),rf(2,c))],2) \ + ^ op(tab[bval(vf(x,3,c),rf(3,c))],3)) + +#define four_tables(x,tab,vf,rf,c) \ + ( tab[0][bval(vf(x,0,c),rf(0,c))] \ + ^ tab[1][bval(vf(x,1,c),rf(1,c))] \ + ^ tab[2][bval(vf(x,2,c),rf(2,c))] \ + ^ tab[3][bval(vf(x,3,c),rf(3,c))]) + +#define vf1(x,r,c) (x) +#define rf1(r,c) (r) +#define rf2(r,c) ((8+r-c)&3) + +/* perform forward and inverse column mix operation on four bytes in long word x in */ +/* parallel. NOTE: x must be a simple variable, NOT an expression in these macros. */ + +#if defined( FM4_SET ) /* not currently used */ +#define fwd_mcol(x) four_tables(x,t_use(f,m),vf1,rf1,0) +#elif defined( FM1_SET ) /* not currently used */ +#define fwd_mcol(x) one_table(x,upr,t_use(f,m),vf1,rf1,0) +#else +#define dec_fmvars uint_32t g2 +#define fwd_mcol(x) (g2 = gf_mulx(x), g2 ^ upr((x) ^ g2, 3) ^ upr((x), 2) ^ upr((x), 1)) +#endif + +#if defined( IM4_SET ) +#define inv_mcol(x) four_tables(x,t_use(i,m),vf1,rf1,0) +#elif defined( IM1_SET ) +#define inv_mcol(x) one_table(x,upr,t_use(i,m),vf1,rf1,0) +#else +#define dec_imvars uint_32t g2, g4, g9 +#define inv_mcol(x) (g2 = gf_mulx(x), g4 = gf_mulx(g2), g9 = (x) ^ gf_mulx(g4), g4 ^= g9, \ + (x) ^ g2 ^ g4 ^ upr(g2 ^ g9, 3) ^ upr(g4, 2) ^ upr(g9, 1)) +#endif + +#if defined( FL4_SET ) +#define ls_box(x,c) four_tables(x,t_use(f,l),vf1,rf2,c) +#elif defined( LS4_SET ) +#define ls_box(x,c) four_tables(x,t_use(l,s),vf1,rf2,c) +#elif defined( FL1_SET ) +#define ls_box(x,c) one_table(x,upr,t_use(f,l),vf1,rf2,c) +#elif defined( LS1_SET ) +#define ls_box(x,c) one_table(x,upr,t_use(l,s),vf1,rf2,c) +#else +#define ls_box(x,c) no_table(x,t_use(s,box),vf1,rf2,c) +#endif + +#if defined( ASM_X86_V1C ) && defined( AES_DECRYPT ) && !defined( ISB_SET ) +#define ISB_SET +#endif + +#endif diff --git a/src/Crypto/Aestab.c b/src/Crypto/Aestab.c index 2fd53789..1effb6f6 100644 --- a/src/Crypto/Aestab.c +++ b/src/Crypto/Aestab.c @@ -1,428 +1,428 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software is allowed (with or without - changes) provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue Date: 20/12/2007 -*/ - -/* Adapted for TrueCrypt: - - Added run-time table generator for Aes_x86_v2.asm -*/ - -#define DO_TABLES - -#include "Aes.h" -#include "Aesopt.h" - -#if defined(FIXED_TABLES) - -#define sb_data(w) {\ - w(0x63), w(0x7c), w(0x77), w(0x7b), w(0xf2), w(0x6b), w(0x6f), w(0xc5),\ - w(0x30), w(0x01), w(0x67), w(0x2b), w(0xfe), w(0xd7), w(0xab), w(0x76),\ - w(0xca), w(0x82), w(0xc9), w(0x7d), w(0xfa), w(0x59), w(0x47), w(0xf0),\ - w(0xad), w(0xd4), w(0xa2), w(0xaf), w(0x9c), w(0xa4), w(0x72), w(0xc0),\ - w(0xb7), w(0xfd), w(0x93), w(0x26), w(0x36), w(0x3f), w(0xf7), w(0xcc),\ - w(0x34), w(0xa5), w(0xe5), w(0xf1), w(0x71), w(0xd8), w(0x31), w(0x15),\ - w(0x04), w(0xc7), w(0x23), w(0xc3), w(0x18), w(0x96), w(0x05), w(0x9a),\ - w(0x07), w(0x12), w(0x80), w(0xe2), w(0xeb), w(0x27), w(0xb2), w(0x75),\ - w(0x09), w(0x83), w(0x2c), w(0x1a), w(0x1b), w(0x6e), w(0x5a), w(0xa0),\ - w(0x52), w(0x3b), w(0xd6), w(0xb3), w(0x29), w(0xe3), w(0x2f), w(0x84),\ - w(0x53), w(0xd1), w(0x00), w(0xed), w(0x20), w(0xfc), w(0xb1), w(0x5b),\ - w(0x6a), w(0xcb), w(0xbe), w(0x39), w(0x4a), w(0x4c), w(0x58), w(0xcf),\ - w(0xd0), w(0xef), w(0xaa), w(0xfb), w(0x43), w(0x4d), w(0x33), w(0x85),\ - w(0x45), w(0xf9), w(0x02), w(0x7f), w(0x50), w(0x3c), w(0x9f), w(0xa8),\ - w(0x51), w(0xa3), w(0x40), w(0x8f), w(0x92), w(0x9d), w(0x38), w(0xf5),\ - w(0xbc), w(0xb6), w(0xda), w(0x21), w(0x10), w(0xff), w(0xf3), w(0xd2),\ - w(0xcd), w(0x0c), w(0x13), w(0xec), w(0x5f), w(0x97), w(0x44), w(0x17),\ - w(0xc4), w(0xa7), w(0x7e), w(0x3d), w(0x64), w(0x5d), w(0x19), w(0x73),\ - w(0x60), w(0x81), w(0x4f), w(0xdc), w(0x22), w(0x2a), w(0x90), w(0x88),\ - w(0x46), w(0xee), w(0xb8), w(0x14), w(0xde), w(0x5e), w(0x0b), w(0xdb),\ - w(0xe0), w(0x32), w(0x3a), w(0x0a), w(0x49), w(0x06), w(0x24), w(0x5c),\ - w(0xc2), w(0xd3), w(0xac), w(0x62), w(0x91), w(0x95), w(0xe4), w(0x79),\ - w(0xe7), w(0xc8), w(0x37), w(0x6d), w(0x8d), w(0xd5), w(0x4e), w(0xa9),\ - w(0x6c), w(0x56), w(0xf4), w(0xea), w(0x65), w(0x7a), w(0xae), w(0x08),\ - w(0xba), w(0x78), w(0x25), w(0x2e), w(0x1c), w(0xa6), w(0xb4), w(0xc6),\ - w(0xe8), w(0xdd), w(0x74), w(0x1f), w(0x4b), w(0xbd), w(0x8b), w(0x8a),\ - w(0x70), w(0x3e), w(0xb5), w(0x66), w(0x48), w(0x03), w(0xf6), w(0x0e),\ - w(0x61), w(0x35), w(0x57), w(0xb9), w(0x86), w(0xc1), w(0x1d), w(0x9e),\ - w(0xe1), w(0xf8), w(0x98), w(0x11), w(0x69), w(0xd9), w(0x8e), w(0x94),\ - w(0x9b), w(0x1e), w(0x87), w(0xe9), w(0xce), w(0x55), w(0x28), w(0xdf),\ - w(0x8c), w(0xa1), w(0x89), w(0x0d), w(0xbf), w(0xe6), w(0x42), w(0x68),\ - w(0x41), w(0x99), w(0x2d), w(0x0f), w(0xb0), w(0x54), w(0xbb), w(0x16) } - -#define isb_data(w) {\ - w(0x52), w(0x09), w(0x6a), w(0xd5), w(0x30), w(0x36), w(0xa5), w(0x38),\ - w(0xbf), w(0x40), w(0xa3), w(0x9e), w(0x81), w(0xf3), w(0xd7), w(0xfb),\ - w(0x7c), w(0xe3), w(0x39), w(0x82), w(0x9b), w(0x2f), w(0xff), w(0x87),\ - w(0x34), w(0x8e), w(0x43), w(0x44), w(0xc4), w(0xde), w(0xe9), w(0xcb),\ - w(0x54), w(0x7b), w(0x94), w(0x32), w(0xa6), w(0xc2), w(0x23), w(0x3d),\ - w(0xee), w(0x4c), w(0x95), w(0x0b), w(0x42), w(0xfa), w(0xc3), w(0x4e),\ - w(0x08), w(0x2e), w(0xa1), w(0x66), w(0x28), w(0xd9), w(0x24), w(0xb2),\ - w(0x76), w(0x5b), w(0xa2), w(0x49), w(0x6d), w(0x8b), w(0xd1), w(0x25),\ - w(0x72), w(0xf8), w(0xf6), w(0x64), w(0x86), w(0x68), w(0x98), w(0x16),\ - w(0xd4), w(0xa4), w(0x5c), w(0xcc), w(0x5d), w(0x65), w(0xb6), w(0x92),\ - w(0x6c), w(0x70), w(0x48), w(0x50), w(0xfd), w(0xed), w(0xb9), w(0xda),\ - w(0x5e), w(0x15), w(0x46), w(0x57), w(0xa7), w(0x8d), w(0x9d), w(0x84),\ - w(0x90), w(0xd8), w(0xab), w(0x00), w(0x8c), w(0xbc), w(0xd3), w(0x0a),\ - w(0xf7), w(0xe4), w(0x58), w(0x05), w(0xb8), w(0xb3), w(0x45), w(0x06),\ - w(0xd0), w(0x2c), w(0x1e), w(0x8f), w(0xca), w(0x3f), w(0x0f), w(0x02),\ - w(0xc1), w(0xaf), w(0xbd), w(0x03), w(0x01), w(0x13), w(0x8a), w(0x6b),\ - w(0x3a), w(0x91), w(0x11), w(0x41), w(0x4f), w(0x67), w(0xdc), w(0xea),\ - w(0x97), w(0xf2), w(0xcf), w(0xce), w(0xf0), w(0xb4), w(0xe6), w(0x73),\ - w(0x96), w(0xac), w(0x74), w(0x22), w(0xe7), w(0xad), w(0x35), w(0x85),\ - w(0xe2), w(0xf9), w(0x37), w(0xe8), w(0x1c), w(0x75), w(0xdf), w(0x6e),\ - w(0x47), w(0xf1), w(0x1a), w(0x71), w(0x1d), w(0x29), w(0xc5), w(0x89),\ - w(0x6f), w(0xb7), w(0x62), w(0x0e), w(0xaa), w(0x18), w(0xbe), w(0x1b),\ - w(0xfc), w(0x56), w(0x3e), w(0x4b), w(0xc6), w(0xd2), w(0x79), w(0x20),\ - w(0x9a), w(0xdb), w(0xc0), w(0xfe), w(0x78), w(0xcd), w(0x5a), w(0xf4),\ - w(0x1f), w(0xdd), w(0xa8), w(0x33), w(0x88), w(0x07), w(0xc7), w(0x31),\ - w(0xb1), w(0x12), w(0x10), w(0x59), w(0x27), w(0x80), w(0xec), w(0x5f),\ - w(0x60), w(0x51), w(0x7f), w(0xa9), w(0x19), w(0xb5), w(0x4a), w(0x0d),\ - w(0x2d), w(0xe5), w(0x7a), w(0x9f), w(0x93), w(0xc9), w(0x9c), w(0xef),\ - w(0xa0), w(0xe0), w(0x3b), w(0x4d), w(0xae), w(0x2a), w(0xf5), w(0xb0),\ - w(0xc8), w(0xeb), w(0xbb), w(0x3c), w(0x83), w(0x53), w(0x99), w(0x61),\ - w(0x17), w(0x2b), w(0x04), w(0x7e), w(0xba), w(0x77), w(0xd6), w(0x26),\ - w(0xe1), w(0x69), w(0x14), w(0x63), w(0x55), w(0x21), w(0x0c), w(0x7d) } - -#define mm_data(w) {\ - w(0x00), w(0x01), w(0x02), w(0x03), w(0x04), w(0x05), w(0x06), w(0x07),\ - w(0x08), w(0x09), w(0x0a), w(0x0b), w(0x0c), w(0x0d), w(0x0e), w(0x0f),\ - w(0x10), w(0x11), w(0x12), w(0x13), w(0x14), w(0x15), w(0x16), w(0x17),\ - w(0x18), w(0x19), w(0x1a), w(0x1b), w(0x1c), w(0x1d), w(0x1e), w(0x1f),\ - w(0x20), w(0x21), w(0x22), w(0x23), w(0x24), w(0x25), w(0x26), w(0x27),\ - w(0x28), w(0x29), w(0x2a), w(0x2b), w(0x2c), w(0x2d), w(0x2e), w(0x2f),\ - w(0x30), w(0x31), w(0x32), w(0x33), w(0x34), w(0x35), w(0x36), w(0x37),\ - w(0x38), w(0x39), w(0x3a), w(0x3b), w(0x3c), w(0x3d), w(0x3e), w(0x3f),\ - w(0x40), w(0x41), w(0x42), w(0x43), w(0x44), w(0x45), w(0x46), w(0x47),\ - w(0x48), w(0x49), w(0x4a), w(0x4b), w(0x4c), w(0x4d), w(0x4e), w(0x4f),\ - w(0x50), w(0x51), w(0x52), w(0x53), w(0x54), w(0x55), w(0x56), w(0x57),\ - w(0x58), w(0x59), w(0x5a), w(0x5b), w(0x5c), w(0x5d), w(0x5e), w(0x5f),\ - w(0x60), w(0x61), w(0x62), w(0x63), w(0x64), w(0x65), w(0x66), w(0x67),\ - w(0x68), w(0x69), w(0x6a), w(0x6b), w(0x6c), w(0x6d), w(0x6e), w(0x6f),\ - w(0x70), w(0x71), w(0x72), w(0x73), w(0x74), w(0x75), w(0x76), w(0x77),\ - w(0x78), w(0x79), w(0x7a), w(0x7b), w(0x7c), w(0x7d), w(0x7e), w(0x7f),\ - w(0x80), w(0x81), w(0x82), w(0x83), w(0x84), w(0x85), w(0x86), w(0x87),\ - w(0x88), w(0x89), w(0x8a), w(0x8b), w(0x8c), w(0x8d), w(0x8e), w(0x8f),\ - w(0x90), w(0x91), w(0x92), w(0x93), w(0x94), w(0x95), w(0x96), w(0x97),\ - w(0x98), w(0x99), w(0x9a), w(0x9b), w(0x9c), w(0x9d), w(0x9e), w(0x9f),\ - w(0xa0), w(0xa1), w(0xa2), w(0xa3), w(0xa4), w(0xa5), w(0xa6), w(0xa7),\ - w(0xa8), w(0xa9), w(0xaa), w(0xab), w(0xac), w(0xad), w(0xae), w(0xaf),\ - w(0xb0), w(0xb1), w(0xb2), w(0xb3), w(0xb4), w(0xb5), w(0xb6), w(0xb7),\ - w(0xb8), w(0xb9), w(0xba), w(0xbb), w(0xbc), w(0xbd), w(0xbe), w(0xbf),\ - w(0xc0), w(0xc1), w(0xc2), w(0xc3), w(0xc4), w(0xc5), w(0xc6), w(0xc7),\ - w(0xc8), w(0xc9), w(0xca), w(0xcb), w(0xcc), w(0xcd), w(0xce), w(0xcf),\ - w(0xd0), w(0xd1), w(0xd2), w(0xd3), w(0xd4), w(0xd5), w(0xd6), w(0xd7),\ - w(0xd8), w(0xd9), w(0xda), w(0xdb), w(0xdc), w(0xdd), w(0xde), w(0xdf),\ - w(0xe0), w(0xe1), w(0xe2), w(0xe3), w(0xe4), w(0xe5), w(0xe6), w(0xe7),\ - w(0xe8), w(0xe9), w(0xea), w(0xeb), w(0xec), w(0xed), w(0xee), w(0xef),\ - w(0xf0), w(0xf1), w(0xf2), w(0xf3), w(0xf4), w(0xf5), w(0xf6), w(0xf7),\ - w(0xf8), w(0xf9), w(0xfa), w(0xfb), w(0xfc), w(0xfd), w(0xfe), w(0xff) } - -#define rc_data(w) {\ - w(0x01), w(0x02), w(0x04), w(0x08), w(0x10),w(0x20), w(0x40), w(0x80),\ - w(0x1b), w(0x36) } - -#define h0(x) (x) - -#define w0(p) bytes2word(p, 0, 0, 0) -#define w1(p) bytes2word(0, p, 0, 0) -#define w2(p) bytes2word(0, 0, p, 0) -#define w3(p) bytes2word(0, 0, 0, p) - -#define u0(p) bytes2word(f2(p), p, p, f3(p)) -#define u1(p) bytes2word(f3(p), f2(p), p, p) -#define u2(p) bytes2word(p, f3(p), f2(p), p) -#define u3(p) bytes2word(p, p, f3(p), f2(p)) - -#define v0(p) bytes2word(fe(p), f9(p), fd(p), fb(p)) -#define v1(p) bytes2word(fb(p), fe(p), f9(p), fd(p)) -#define v2(p) bytes2word(fd(p), fb(p), fe(p), f9(p)) -#define v3(p) bytes2word(f9(p), fd(p), fb(p), fe(p)) - -#endif - -#if defined(FIXED_TABLES) || !defined(FF_TABLES) - -#define f2(x) ((x<<1) ^ (((x>>7) & 1) * WPOLY)) -#define f4(x) ((x<<2) ^ (((x>>6) & 1) * WPOLY) ^ (((x>>6) & 2) * WPOLY)) -#define f8(x) ((x<<3) ^ (((x>>5) & 1) * WPOLY) ^ (((x>>5) & 2) * WPOLY) \ - ^ (((x>>5) & 4) * WPOLY)) -#define f3(x) (f2(x) ^ x) -#define f9(x) (f8(x) ^ x) -#define fb(x) (f8(x) ^ f2(x) ^ x) -#define fd(x) (f8(x) ^ f4(x) ^ x) -#define fe(x) (f8(x) ^ f4(x) ^ f2(x)) - -#else - -#define f2(x) ((x) ? pow[log[x] + 0x19] : 0) -#define f3(x) ((x) ? pow[log[x] + 0x01] : 0) -#define f9(x) ((x) ? pow[log[x] + 0xc7] : 0) -#define fb(x) ((x) ? pow[log[x] + 0x68] : 0) -#define fd(x) ((x) ? pow[log[x] + 0xee] : 0) -#define fe(x) ((x) ? pow[log[x] + 0xdf] : 0) -#define fi(x) ((x) ? pow[ 255 - log[x]] : 0) - -#endif - -#include "Aestab.h" - -#if defined(__cplusplus) -extern "C" -{ -#endif - -#if defined(FIXED_TABLES) - -/* implemented in case of wrong call for fixed tables */ - -AES_RETURN aes_init(void) -{ - return EXIT_SUCCESS; -} - -#else /* dynamic table generation */ - -#if !defined(FF_TABLES) - -/* Generate the tables for the dynamic table option - - It will generally be sensible to use tables to compute finite - field multiplies and inverses but where memory is scarse this - code might sometimes be better. But it only has effect during - initialisation so its pretty unimportant in overall terms. -*/ - -/* return 2 ^ (n - 1) where n is the bit number of the highest bit - set in x with x in the range 1 < x < 0x00000200. This form is - used so that locals within fi can be bytes rather than words -*/ - -static uint_8t hibit(const uint_32t x) -{ uint_8t r = (uint_8t)((x >> 1) | (x >> 2)); - - r |= (r >> 2); - r |= (r >> 4); - return (r + 1) >> 1; -} - -/* return the inverse of the finite field element x */ - -static uint_8t fi(const uint_8t x) -{ uint_8t p1 = x, p2 = BPOLY, n1 = hibit(x), n2 = 0x80, v1 = 1, v2 = 0; - - if(x < 2) return x; - - for(;;) - { - if(!n1) return v1; - - while(n2 >= n1) - { - n2 /= n1; p2 ^= p1 * n2; v2 ^= v1 * n2; n2 = hibit(p2); - } - - if(!n2) return v2; - - while(n1 >= n2) - { - n1 /= n2; p1 ^= p2 * n1; v1 ^= v2 * n1; n1 = hibit(p1); - } - } -} - -#endif - -/* The forward and inverse affine transformations used in the S-box */ - -#define fwd_affine(x) \ - (w = (uint_32t)x, w ^= (w<<1)^(w<<2)^(w<<3)^(w<<4), 0x63^(uint_8t)(w^(w>>8))) - -#define inv_affine(x) \ - (w = (uint_32t)x, w = (w<<1)^(w<<3)^(w<<6), 0x05^(uint_8t)(w^(w>>8))) - -static int init = 0; - -#ifdef TC_WINDOWS_BOOT - -#pragma optimize ("l", on) -uint_8t aes_enc_tab[256][8]; -uint_8t aes_dec_tab[256][8]; - -#endif - -AES_RETURN aes_init(void) -{ uint_32t i, w; - -#ifdef TC_WINDOWS_BOOT - - if (init) - return EXIT_SUCCESS; - - for (i = 0; i < 256; ++i) - { - uint_8t x = fwd_affine(fi((uint_8t)i)); - aes_enc_tab[i][0] = 0; - aes_enc_tab[i][1] = x; - aes_enc_tab[i][2] = x; - aes_enc_tab[i][3] = f3(x); - aes_enc_tab[i][4] = f2(x); - aes_enc_tab[i][5] = x; - aes_enc_tab[i][6] = x; - aes_enc_tab[i][7] = f3(x); - - x = fi((uint_8t)inv_affine((uint_8t)i)); - aes_dec_tab[i][0] = fe(x); - aes_dec_tab[i][1] = f9(x); - aes_dec_tab[i][2] = fd(x); - aes_dec_tab[i][3] = fb(x); - aes_dec_tab[i][4] = fe(x); - aes_dec_tab[i][5] = f9(x); - aes_dec_tab[i][6] = fd(x); - aes_dec_tab[i][7] = x; - } - -#else // TC_WINDOWS_BOOT - -#if defined(FF_TABLES) - - uint_8t pow[512], log[256]; - - if(init) - return EXIT_SUCCESS; - /* log and power tables for GF(2^8) finite field with - WPOLY as modular polynomial - the simplest primitive - root is 0x03, used here to generate the tables - */ - - i = 0; w = 1; - do - { - pow[i] = (uint_8t)w; - pow[i + 255] = (uint_8t)w; - log[w] = (uint_8t)i++; - w ^= (w << 1) ^ (w & 0x80 ? WPOLY : 0); - } - while (w != 1); - -#else - if(init) - return EXIT_SUCCESS; -#endif - - for(i = 0, w = 1; i < RC_LENGTH; ++i) - { - t_set(r,c)[i] = bytes2word(w, 0, 0, 0); - w = f2(w); - } - - for(i = 0; i < 256; ++i) - { uint_8t b; - - b = fwd_affine(fi((uint_8t)i)); - w = bytes2word(f2(b), b, b, f3(b)); - -#if defined( SBX_SET ) - t_set(s,box)[i] = b; -#endif - -#if defined( FT1_SET ) /* tables for a normal encryption round */ - t_set(f,n)[i] = w; -#endif -#if defined( FT4_SET ) - t_set(f,n)[0][i] = w; - t_set(f,n)[1][i] = upr(w,1); - t_set(f,n)[2][i] = upr(w,2); - t_set(f,n)[3][i] = upr(w,3); -#endif - w = bytes2word(b, 0, 0, 0); - -#if defined( FL1_SET ) /* tables for last encryption round (may also */ - t_set(f,l)[i] = w; /* be used in the key schedule) */ -#endif -#if defined( FL4_SET ) - t_set(f,l)[0][i] = w; - t_set(f,l)[1][i] = upr(w,1); - t_set(f,l)[2][i] = upr(w,2); - t_set(f,l)[3][i] = upr(w,3); -#endif - -#if defined( LS1_SET ) /* table for key schedule if t_set(f,l) above is*/ - t_set(l,s)[i] = w; /* not of the required form */ -#endif -#if defined( LS4_SET ) - t_set(l,s)[0][i] = w; - t_set(l,s)[1][i] = upr(w,1); - t_set(l,s)[2][i] = upr(w,2); - t_set(l,s)[3][i] = upr(w,3); -#endif - - b = fi(inv_affine((uint_8t)i)); - w = bytes2word(fe(b), f9(b), fd(b), fb(b)); - -#if defined( IM1_SET ) /* tables for the inverse mix column operation */ - t_set(i,m)[b] = w; -#endif -#if defined( IM4_SET ) - t_set(i,m)[0][b] = w; - t_set(i,m)[1][b] = upr(w,1); - t_set(i,m)[2][b] = upr(w,2); - t_set(i,m)[3][b] = upr(w,3); -#endif - -#if defined( ISB_SET ) - t_set(i,box)[i] = b; -#endif -#if defined( IT1_SET ) /* tables for a normal decryption round */ - t_set(i,n)[i] = w; -#endif -#if defined( IT4_SET ) - t_set(i,n)[0][i] = w; - t_set(i,n)[1][i] = upr(w,1); - t_set(i,n)[2][i] = upr(w,2); - t_set(i,n)[3][i] = upr(w,3); -#endif - w = bytes2word(b, 0, 0, 0); -#if defined( IL1_SET ) /* tables for last decryption round */ - t_set(i,l)[i] = w; -#endif -#if defined( IL4_SET ) - t_set(i,l)[0][i] = w; - t_set(i,l)[1][i] = upr(w,1); - t_set(i,l)[2][i] = upr(w,2); - t_set(i,l)[3][i] = upr(w,3); -#endif - } - -#endif // TC_WINDOWS_BOOT - - init = 1; - return EXIT_SUCCESS; -} - -#endif - -#if defined(__cplusplus) -} -#endif - +/* + --------------------------------------------------------------------------- + Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software is allowed (with or without + changes) provided that: + + 1. source code distributions include the above copyright notice, this + list of conditions and the following disclaimer; + + 2. binary distributions include the above copyright notice, this list + of conditions and the following disclaimer in their documentation; + + 3. the name of the copyright holder is not used to endorse products + built using this software without specific written permission. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + Issue Date: 20/12/2007 +*/ + +/* Adapted for TrueCrypt: + - Added run-time table generator for Aes_x86_v2.asm +*/ + +#define DO_TABLES + +#include "Aes.h" +#include "Aesopt.h" + +#if defined(FIXED_TABLES) + +#define sb_data(w) {\ + w(0x63), w(0x7c), w(0x77), w(0x7b), w(0xf2), w(0x6b), w(0x6f), w(0xc5),\ + w(0x30), w(0x01), w(0x67), w(0x2b), w(0xfe), w(0xd7), w(0xab), w(0x76),\ + w(0xca), w(0x82), w(0xc9), w(0x7d), w(0xfa), w(0x59), w(0x47), w(0xf0),\ + w(0xad), w(0xd4), w(0xa2), w(0xaf), w(0x9c), w(0xa4), w(0x72), w(0xc0),\ + w(0xb7), w(0xfd), w(0x93), w(0x26), w(0x36), w(0x3f), w(0xf7), w(0xcc),\ + w(0x34), w(0xa5), w(0xe5), w(0xf1), w(0x71), w(0xd8), w(0x31), w(0x15),\ + w(0x04), w(0xc7), w(0x23), w(0xc3), w(0x18), w(0x96), w(0x05), w(0x9a),\ + w(0x07), w(0x12), w(0x80), w(0xe2), w(0xeb), w(0x27), w(0xb2), w(0x75),\ + w(0x09), w(0x83), w(0x2c), w(0x1a), w(0x1b), w(0x6e), w(0x5a), w(0xa0),\ + w(0x52), w(0x3b), w(0xd6), w(0xb3), w(0x29), w(0xe3), w(0x2f), w(0x84),\ + w(0x53), w(0xd1), w(0x00), w(0xed), w(0x20), w(0xfc), w(0xb1), w(0x5b),\ + w(0x6a), w(0xcb), w(0xbe), w(0x39), w(0x4a), w(0x4c), w(0x58), w(0xcf),\ + w(0xd0), w(0xef), w(0xaa), w(0xfb), w(0x43), w(0x4d), w(0x33), w(0x85),\ + w(0x45), w(0xf9), w(0x02), w(0x7f), w(0x50), w(0x3c), w(0x9f), w(0xa8),\ + w(0x51), w(0xa3), w(0x40), w(0x8f), w(0x92), w(0x9d), w(0x38), w(0xf5),\ + w(0xbc), w(0xb6), w(0xda), w(0x21), w(0x10), w(0xff), w(0xf3), w(0xd2),\ + w(0xcd), w(0x0c), w(0x13), w(0xec), w(0x5f), w(0x97), w(0x44), w(0x17),\ + w(0xc4), w(0xa7), w(0x7e), w(0x3d), w(0x64), w(0x5d), w(0x19), w(0x73),\ + w(0x60), w(0x81), w(0x4f), w(0xdc), w(0x22), w(0x2a), w(0x90), w(0x88),\ + w(0x46), w(0xee), w(0xb8), w(0x14), w(0xde), w(0x5e), w(0x0b), w(0xdb),\ + w(0xe0), w(0x32), w(0x3a), w(0x0a), w(0x49), w(0x06), w(0x24), w(0x5c),\ + w(0xc2), w(0xd3), w(0xac), w(0x62), w(0x91), w(0x95), w(0xe4), w(0x79),\ + w(0xe7), w(0xc8), w(0x37), w(0x6d), w(0x8d), w(0xd5), w(0x4e), w(0xa9),\ + w(0x6c), w(0x56), w(0xf4), w(0xea), w(0x65), w(0x7a), w(0xae), w(0x08),\ + w(0xba), w(0x78), w(0x25), w(0x2e), w(0x1c), w(0xa6), w(0xb4), w(0xc6),\ + w(0xe8), w(0xdd), w(0x74), w(0x1f), w(0x4b), w(0xbd), w(0x8b), w(0x8a),\ + w(0x70), w(0x3e), w(0xb5), w(0x66), w(0x48), w(0x03), w(0xf6), w(0x0e),\ + w(0x61), w(0x35), w(0x57), w(0xb9), w(0x86), w(0xc1), w(0x1d), w(0x9e),\ + w(0xe1), w(0xf8), w(0x98), w(0x11), w(0x69), w(0xd9), w(0x8e), w(0x94),\ + w(0x9b), w(0x1e), w(0x87), w(0xe9), w(0xce), w(0x55), w(0x28), w(0xdf),\ + w(0x8c), w(0xa1), w(0x89), w(0x0d), w(0xbf), w(0xe6), w(0x42), w(0x68),\ + w(0x41), w(0x99), w(0x2d), w(0x0f), w(0xb0), w(0x54), w(0xbb), w(0x16) } + +#define isb_data(w) {\ + w(0x52), w(0x09), w(0x6a), w(0xd5), w(0x30), w(0x36), w(0xa5), w(0x38),\ + w(0xbf), w(0x40), w(0xa3), w(0x9e), w(0x81), w(0xf3), w(0xd7), w(0xfb),\ + w(0x7c), w(0xe3), w(0x39), w(0x82), w(0x9b), w(0x2f), w(0xff), w(0x87),\ + w(0x34), w(0x8e), w(0x43), w(0x44), w(0xc4), w(0xde), w(0xe9), w(0xcb),\ + w(0x54), w(0x7b), w(0x94), w(0x32), w(0xa6), w(0xc2), w(0x23), w(0x3d),\ + w(0xee), w(0x4c), w(0x95), w(0x0b), w(0x42), w(0xfa), w(0xc3), w(0x4e),\ + w(0x08), w(0x2e), w(0xa1), w(0x66), w(0x28), w(0xd9), w(0x24), w(0xb2),\ + w(0x76), w(0x5b), w(0xa2), w(0x49), w(0x6d), w(0x8b), w(0xd1), w(0x25),\ + w(0x72), w(0xf8), w(0xf6), w(0x64), w(0x86), w(0x68), w(0x98), w(0x16),\ + w(0xd4), w(0xa4), w(0x5c), w(0xcc), w(0x5d), w(0x65), w(0xb6), w(0x92),\ + w(0x6c), w(0x70), w(0x48), w(0x50), w(0xfd), w(0xed), w(0xb9), w(0xda),\ + w(0x5e), w(0x15), w(0x46), w(0x57), w(0xa7), w(0x8d), w(0x9d), w(0x84),\ + w(0x90), w(0xd8), w(0xab), w(0x00), w(0x8c), w(0xbc), w(0xd3), w(0x0a),\ + w(0xf7), w(0xe4), w(0x58), w(0x05), w(0xb8), w(0xb3), w(0x45), w(0x06),\ + w(0xd0), w(0x2c), w(0x1e), w(0x8f), w(0xca), w(0x3f), w(0x0f), w(0x02),\ + w(0xc1), w(0xaf), w(0xbd), w(0x03), w(0x01), w(0x13), w(0x8a), w(0x6b),\ + w(0x3a), w(0x91), w(0x11), w(0x41), w(0x4f), w(0x67), w(0xdc), w(0xea),\ + w(0x97), w(0xf2), w(0xcf), w(0xce), w(0xf0), w(0xb4), w(0xe6), w(0x73),\ + w(0x96), w(0xac), w(0x74), w(0x22), w(0xe7), w(0xad), w(0x35), w(0x85),\ + w(0xe2), w(0xf9), w(0x37), w(0xe8), w(0x1c), w(0x75), w(0xdf), w(0x6e),\ + w(0x47), w(0xf1), w(0x1a), w(0x71), w(0x1d), w(0x29), w(0xc5), w(0x89),\ + w(0x6f), w(0xb7), w(0x62), w(0x0e), w(0xaa), w(0x18), w(0xbe), w(0x1b),\ + w(0xfc), w(0x56), w(0x3e), w(0x4b), w(0xc6), w(0xd2), w(0x79), w(0x20),\ + w(0x9a), w(0xdb), w(0xc0), w(0xfe), w(0x78), w(0xcd), w(0x5a), w(0xf4),\ + w(0x1f), w(0xdd), w(0xa8), w(0x33), w(0x88), w(0x07), w(0xc7), w(0x31),\ + w(0xb1), w(0x12), w(0x10), w(0x59), w(0x27), w(0x80), w(0xec), w(0x5f),\ + w(0x60), w(0x51), w(0x7f), w(0xa9), w(0x19), w(0xb5), w(0x4a), w(0x0d),\ + w(0x2d), w(0xe5), w(0x7a), w(0x9f), w(0x93), w(0xc9), w(0x9c), w(0xef),\ + w(0xa0), w(0xe0), w(0x3b), w(0x4d), w(0xae), w(0x2a), w(0xf5), w(0xb0),\ + w(0xc8), w(0xeb), w(0xbb), w(0x3c), w(0x83), w(0x53), w(0x99), w(0x61),\ + w(0x17), w(0x2b), w(0x04), w(0x7e), w(0xba), w(0x77), w(0xd6), w(0x26),\ + w(0xe1), w(0x69), w(0x14), w(0x63), w(0x55), w(0x21), w(0x0c), w(0x7d) } + +#define mm_data(w) {\ + w(0x00), w(0x01), w(0x02), w(0x03), w(0x04), w(0x05), w(0x06), w(0x07),\ + w(0x08), w(0x09), w(0x0a), w(0x0b), w(0x0c), w(0x0d), w(0x0e), w(0x0f),\ + w(0x10), w(0x11), w(0x12), w(0x13), w(0x14), w(0x15), w(0x16), w(0x17),\ + w(0x18), w(0x19), w(0x1a), w(0x1b), w(0x1c), w(0x1d), w(0x1e), w(0x1f),\ + w(0x20), w(0x21), w(0x22), w(0x23), w(0x24), w(0x25), w(0x26), w(0x27),\ + w(0x28), w(0x29), w(0x2a), w(0x2b), w(0x2c), w(0x2d), w(0x2e), w(0x2f),\ + w(0x30), w(0x31), w(0x32), w(0x33), w(0x34), w(0x35), w(0x36), w(0x37),\ + w(0x38), w(0x39), w(0x3a), w(0x3b), w(0x3c), w(0x3d), w(0x3e), w(0x3f),\ + w(0x40), w(0x41), w(0x42), w(0x43), w(0x44), w(0x45), w(0x46), w(0x47),\ + w(0x48), w(0x49), w(0x4a), w(0x4b), w(0x4c), w(0x4d), w(0x4e), w(0x4f),\ + w(0x50), w(0x51), w(0x52), w(0x53), w(0x54), w(0x55), w(0x56), w(0x57),\ + w(0x58), w(0x59), w(0x5a), w(0x5b), w(0x5c), w(0x5d), w(0x5e), w(0x5f),\ + w(0x60), w(0x61), w(0x62), w(0x63), w(0x64), w(0x65), w(0x66), w(0x67),\ + w(0x68), w(0x69), w(0x6a), w(0x6b), w(0x6c), w(0x6d), w(0x6e), w(0x6f),\ + w(0x70), w(0x71), w(0x72), w(0x73), w(0x74), w(0x75), w(0x76), w(0x77),\ + w(0x78), w(0x79), w(0x7a), w(0x7b), w(0x7c), w(0x7d), w(0x7e), w(0x7f),\ + w(0x80), w(0x81), w(0x82), w(0x83), w(0x84), w(0x85), w(0x86), w(0x87),\ + w(0x88), w(0x89), w(0x8a), w(0x8b), w(0x8c), w(0x8d), w(0x8e), w(0x8f),\ + w(0x90), w(0x91), w(0x92), w(0x93), w(0x94), w(0x95), w(0x96), w(0x97),\ + w(0x98), w(0x99), w(0x9a), w(0x9b), w(0x9c), w(0x9d), w(0x9e), w(0x9f),\ + w(0xa0), w(0xa1), w(0xa2), w(0xa3), w(0xa4), w(0xa5), w(0xa6), w(0xa7),\ + w(0xa8), w(0xa9), w(0xaa), w(0xab), w(0xac), w(0xad), w(0xae), w(0xaf),\ + w(0xb0), w(0xb1), w(0xb2), w(0xb3), w(0xb4), w(0xb5), w(0xb6), w(0xb7),\ + w(0xb8), w(0xb9), w(0xba), w(0xbb), w(0xbc), w(0xbd), w(0xbe), w(0xbf),\ + w(0xc0), w(0xc1), w(0xc2), w(0xc3), w(0xc4), w(0xc5), w(0xc6), w(0xc7),\ + w(0xc8), w(0xc9), w(0xca), w(0xcb), w(0xcc), w(0xcd), w(0xce), w(0xcf),\ + w(0xd0), w(0xd1), w(0xd2), w(0xd3), w(0xd4), w(0xd5), w(0xd6), w(0xd7),\ + w(0xd8), w(0xd9), w(0xda), w(0xdb), w(0xdc), w(0xdd), w(0xde), w(0xdf),\ + w(0xe0), w(0xe1), w(0xe2), w(0xe3), w(0xe4), w(0xe5), w(0xe6), w(0xe7),\ + w(0xe8), w(0xe9), w(0xea), w(0xeb), w(0xec), w(0xed), w(0xee), w(0xef),\ + w(0xf0), w(0xf1), w(0xf2), w(0xf3), w(0xf4), w(0xf5), w(0xf6), w(0xf7),\ + w(0xf8), w(0xf9), w(0xfa), w(0xfb), w(0xfc), w(0xfd), w(0xfe), w(0xff) } + +#define rc_data(w) {\ + w(0x01), w(0x02), w(0x04), w(0x08), w(0x10),w(0x20), w(0x40), w(0x80),\ + w(0x1b), w(0x36) } + +#define h0(x) (x) + +#define w0(p) bytes2word(p, 0, 0, 0) +#define w1(p) bytes2word(0, p, 0, 0) +#define w2(p) bytes2word(0, 0, p, 0) +#define w3(p) bytes2word(0, 0, 0, p) + +#define u0(p) bytes2word(f2(p), p, p, f3(p)) +#define u1(p) bytes2word(f3(p), f2(p), p, p) +#define u2(p) bytes2word(p, f3(p), f2(p), p) +#define u3(p) bytes2word(p, p, f3(p), f2(p)) + +#define v0(p) bytes2word(fe(p), f9(p), fd(p), fb(p)) +#define v1(p) bytes2word(fb(p), fe(p), f9(p), fd(p)) +#define v2(p) bytes2word(fd(p), fb(p), fe(p), f9(p)) +#define v3(p) bytes2word(f9(p), fd(p), fb(p), fe(p)) + +#endif + +#if defined(FIXED_TABLES) || !defined(FF_TABLES) + +#define f2(x) ((x<<1) ^ (((x>>7) & 1) * WPOLY)) +#define f4(x) ((x<<2) ^ (((x>>6) & 1) * WPOLY) ^ (((x>>6) & 2) * WPOLY)) +#define f8(x) ((x<<3) ^ (((x>>5) & 1) * WPOLY) ^ (((x>>5) & 2) * WPOLY) \ + ^ (((x>>5) & 4) * WPOLY)) +#define f3(x) (f2(x) ^ x) +#define f9(x) (f8(x) ^ x) +#define fb(x) (f8(x) ^ f2(x) ^ x) +#define fd(x) (f8(x) ^ f4(x) ^ x) +#define fe(x) (f8(x) ^ f4(x) ^ f2(x)) + +#else + +#define f2(x) ((x) ? pow[log[x] + 0x19] : 0) +#define f3(x) ((x) ? pow[log[x] + 0x01] : 0) +#define f9(x) ((x) ? pow[log[x] + 0xc7] : 0) +#define fb(x) ((x) ? pow[log[x] + 0x68] : 0) +#define fd(x) ((x) ? pow[log[x] + 0xee] : 0) +#define fe(x) ((x) ? pow[log[x] + 0xdf] : 0) +#define fi(x) ((x) ? pow[ 255 - log[x]] : 0) + +#endif + +#include "Aestab.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif + +#if defined(FIXED_TABLES) + +/* implemented in case of wrong call for fixed tables */ + +AES_RETURN aes_init(void) +{ + return EXIT_SUCCESS; +} + +#else /* dynamic table generation */ + +#if !defined(FF_TABLES) + +/* Generate the tables for the dynamic table option + + It will generally be sensible to use tables to compute finite + field multiplies and inverses but where memory is scarse this + code might sometimes be better. But it only has effect during + initialisation so its pretty unimportant in overall terms. +*/ + +/* return 2 ^ (n - 1) where n is the bit number of the highest bit + set in x with x in the range 1 < x < 0x00000200. This form is + used so that locals within fi can be bytes rather than words +*/ + +static uint_8t hibit(const uint_32t x) +{ uint_8t r = (uint_8t)((x >> 1) | (x >> 2)); + + r |= (r >> 2); + r |= (r >> 4); + return (r + 1) >> 1; +} + +/* return the inverse of the finite field element x */ + +static uint_8t fi(const uint_8t x) +{ uint_8t p1 = x, p2 = BPOLY, n1 = hibit(x), n2 = 0x80, v1 = 1, v2 = 0; + + if(x < 2) return x; + + for(;;) + { + if(!n1) return v1; + + while(n2 >= n1) + { + n2 /= n1; p2 ^= p1 * n2; v2 ^= v1 * n2; n2 = hibit(p2); + } + + if(!n2) return v2; + + while(n1 >= n2) + { + n1 /= n2; p1 ^= p2 * n1; v1 ^= v2 * n1; n1 = hibit(p1); + } + } +} + +#endif + +/* The forward and inverse affine transformations used in the S-box */ + +#define fwd_affine(x) \ + (w = (uint_32t)x, w ^= (w<<1)^(w<<2)^(w<<3)^(w<<4), 0x63^(uint_8t)(w^(w>>8))) + +#define inv_affine(x) \ + (w = (uint_32t)x, w = (w<<1)^(w<<3)^(w<<6), 0x05^(uint_8t)(w^(w>>8))) + +static int init = 0; + +#ifdef TC_WINDOWS_BOOT + +#pragma optimize ("l", on) +uint_8t aes_enc_tab[256][8]; +uint_8t aes_dec_tab[256][8]; + +#endif + +AES_RETURN aes_init(void) +{ uint_32t i, w; + +#ifdef TC_WINDOWS_BOOT + + if (init) + return EXIT_SUCCESS; + + for (i = 0; i < 256; ++i) + { + uint_8t x = fwd_affine(fi((uint_8t)i)); + aes_enc_tab[i][0] = 0; + aes_enc_tab[i][1] = x; + aes_enc_tab[i][2] = x; + aes_enc_tab[i][3] = f3(x); + aes_enc_tab[i][4] = f2(x); + aes_enc_tab[i][5] = x; + aes_enc_tab[i][6] = x; + aes_enc_tab[i][7] = f3(x); + + x = fi((uint_8t)inv_affine((uint_8t)i)); + aes_dec_tab[i][0] = fe(x); + aes_dec_tab[i][1] = f9(x); + aes_dec_tab[i][2] = fd(x); + aes_dec_tab[i][3] = fb(x); + aes_dec_tab[i][4] = fe(x); + aes_dec_tab[i][5] = f9(x); + aes_dec_tab[i][6] = fd(x); + aes_dec_tab[i][7] = x; + } + +#else // TC_WINDOWS_BOOT + +#if defined(FF_TABLES) + + uint_8t pow[512], log[256]; + + if(init) + return EXIT_SUCCESS; + /* log and power tables for GF(2^8) finite field with + WPOLY as modular polynomial - the simplest primitive + root is 0x03, used here to generate the tables + */ + + i = 0; w = 1; + do + { + pow[i] = (uint_8t)w; + pow[i + 255] = (uint_8t)w; + log[w] = (uint_8t)i++; + w ^= (w << 1) ^ (w & 0x80 ? WPOLY : 0); + } + while (w != 1); + +#else + if(init) + return EXIT_SUCCESS; +#endif + + for(i = 0, w = 1; i < RC_LENGTH; ++i) + { + t_set(r,c)[i] = bytes2word(w, 0, 0, 0); + w = f2(w); + } + + for(i = 0; i < 256; ++i) + { uint_8t b; + + b = fwd_affine(fi((uint_8t)i)); + w = bytes2word(f2(b), b, b, f3(b)); + +#if defined( SBX_SET ) + t_set(s,box)[i] = b; +#endif + +#if defined( FT1_SET ) /* tables for a normal encryption round */ + t_set(f,n)[i] = w; +#endif +#if defined( FT4_SET ) + t_set(f,n)[0][i] = w; + t_set(f,n)[1][i] = upr(w,1); + t_set(f,n)[2][i] = upr(w,2); + t_set(f,n)[3][i] = upr(w,3); +#endif + w = bytes2word(b, 0, 0, 0); + +#if defined( FL1_SET ) /* tables for last encryption round (may also */ + t_set(f,l)[i] = w; /* be used in the key schedule) */ +#endif +#if defined( FL4_SET ) + t_set(f,l)[0][i] = w; + t_set(f,l)[1][i] = upr(w,1); + t_set(f,l)[2][i] = upr(w,2); + t_set(f,l)[3][i] = upr(w,3); +#endif + +#if defined( LS1_SET ) /* table for key schedule if t_set(f,l) above is*/ + t_set(l,s)[i] = w; /* not of the required form */ +#endif +#if defined( LS4_SET ) + t_set(l,s)[0][i] = w; + t_set(l,s)[1][i] = upr(w,1); + t_set(l,s)[2][i] = upr(w,2); + t_set(l,s)[3][i] = upr(w,3); +#endif + + b = fi(inv_affine((uint_8t)i)); + w = bytes2word(fe(b), f9(b), fd(b), fb(b)); + +#if defined( IM1_SET ) /* tables for the inverse mix column operation */ + t_set(i,m)[b] = w; +#endif +#if defined( IM4_SET ) + t_set(i,m)[0][b] = w; + t_set(i,m)[1][b] = upr(w,1); + t_set(i,m)[2][b] = upr(w,2); + t_set(i,m)[3][b] = upr(w,3); +#endif + +#if defined( ISB_SET ) + t_set(i,box)[i] = b; +#endif +#if defined( IT1_SET ) /* tables for a normal decryption round */ + t_set(i,n)[i] = w; +#endif +#if defined( IT4_SET ) + t_set(i,n)[0][i] = w; + t_set(i,n)[1][i] = upr(w,1); + t_set(i,n)[2][i] = upr(w,2); + t_set(i,n)[3][i] = upr(w,3); +#endif + w = bytes2word(b, 0, 0, 0); +#if defined( IL1_SET ) /* tables for last decryption round */ + t_set(i,l)[i] = w; +#endif +#if defined( IL4_SET ) + t_set(i,l)[0][i] = w; + t_set(i,l)[1][i] = upr(w,1); + t_set(i,l)[2][i] = upr(w,2); + t_set(i,l)[3][i] = upr(w,3); +#endif + } + +#endif // TC_WINDOWS_BOOT + + init = 1; + return EXIT_SUCCESS; +} + +#endif + +#if defined(__cplusplus) +} +#endif + diff --git a/src/Crypto/Aestab.h b/src/Crypto/Aestab.h index 2ad1b034..e52e0057 100644 --- a/src/Crypto/Aestab.h +++ b/src/Crypto/Aestab.h @@ -1,174 +1,174 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software is allowed (with or without - changes) provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue Date: 20/12/2007 - - This file contains the code for declaring the tables needed to implement - AES. The file aesopt.h is assumed to be included before this header file. - If there are no global variables, the definitions here can be used to put - the AES tables in a structure so that a pointer can then be added to the - AES context to pass them to the AES routines that need them. If this - facility is used, the calling program has to ensure that this pointer is - managed appropriately. In particular, the value of the t_dec(in,it) item - in the table structure must be set to zero in order to ensure that the - tables are initialised. In practice the three code sequences in aeskey.c - that control the calls to aes_init() and the aes_init() routine itself will - have to be changed for a specific implementation. If global variables are - available it will generally be preferable to use them with the precomputed - FIXED_TABLES option that uses static global tables. - - The following defines can be used to control the way the tables - are defined, initialised and used in embedded environments that - require special features for these purposes - - the 't_dec' construction is used to declare fixed table arrays - the 't_set' construction is used to set fixed table values - the 't_use' construction is used to access fixed table values - - 256 byte tables: - - t_xxx(s,box) => forward S box - t_xxx(i,box) => inverse S box - - 256 32-bit word OR 4 x 256 32-bit word tables: - - t_xxx(f,n) => forward normal round - t_xxx(f,l) => forward last round - t_xxx(i,n) => inverse normal round - t_xxx(i,l) => inverse last round - t_xxx(l,s) => key schedule table - t_xxx(i,m) => key schedule table - - Other variables and tables: - - t_xxx(r,c) => the rcon table -*/ - -#if !defined( _AESTAB_H ) -#define _AESTAB_H - -#define t_dec(m,n) t_##m##n -#define t_set(m,n) t_##m##n -#define t_use(m,n) t_##m##n - -#if defined(FIXED_TABLES) -# if !defined( __GNUC__ ) && (defined( __MSDOS__ ) || defined( __WIN16__ )) -/* make tables far data to avoid using too much DGROUP space (PG) */ -# define CONST const far -# else -# define CONST const -# endif -#else -# define CONST -#endif - -#if defined(__cplusplus) -# define EXTERN extern "C" -#elif defined(DO_TABLES) -# define EXTERN -#else -# define EXTERN extern -#endif - -#if defined(_MSC_VER) && defined(TABLE_ALIGN) -#define ALIGN __declspec(align(TABLE_ALIGN)) -#else -#define ALIGN -#endif - -#if defined( __WATCOMC__ ) && ( __WATCOMC__ >= 1100 ) -# define XP_DIR __cdecl -#else -# define XP_DIR -#endif - -#if defined(DO_TABLES) && defined(FIXED_TABLES) -#define d_1(t,n,b,e) EXTERN ALIGN CONST XP_DIR t n[256] = b(e) -#define d_4(t,n,b,e,f,g,h) EXTERN ALIGN CONST XP_DIR t n[4][256] = { b(e), b(f), b(g), b(h) } -EXTERN ALIGN CONST uint_32t t_dec(r,c)[RC_LENGTH] = rc_data(w0); -#else -#define d_1(t,n,b,e) EXTERN ALIGN CONST XP_DIR t n[256] -#define d_4(t,n,b,e,f,g,h) EXTERN ALIGN CONST XP_DIR t n[4][256] -EXTERN ALIGN CONST uint_32t t_dec(r,c)[RC_LENGTH]; -#endif - -#if defined( SBX_SET ) - d_1(uint_8t, t_dec(s,box), sb_data, h0); -#endif -#if defined( ISB_SET ) - d_1(uint_8t, t_dec(i,box), isb_data, h0); -#endif - -#if defined( FT1_SET ) - d_1(uint_32t, t_dec(f,n), sb_data, u0); -#endif -#if defined( FT4_SET ) - d_4(uint_32t, t_dec(f,n), sb_data, u0, u1, u2, u3); -#endif - -#if defined( FL1_SET ) - d_1(uint_32t, t_dec(f,l), sb_data, w0); -#endif -#if defined( FL4_SET ) - d_4(uint_32t, t_dec(f,l), sb_data, w0, w1, w2, w3); -#endif - -#if defined( IT1_SET ) - d_1(uint_32t, t_dec(i,n), isb_data, v0); -#endif -#if defined( IT4_SET ) - d_4(uint_32t, t_dec(i,n), isb_data, v0, v1, v2, v3); -#endif - -#if defined( IL1_SET ) - d_1(uint_32t, t_dec(i,l), isb_data, w0); -#endif -#if defined( IL4_SET ) - d_4(uint_32t, t_dec(i,l), isb_data, w0, w1, w2, w3); -#endif - -#if defined( LS1_SET ) -#if defined( FL1_SET ) -#undef LS1_SET -#else - d_1(uint_32t, t_dec(l,s), sb_data, w0); -#endif -#endif - -#if defined( LS4_SET ) -#if defined( FL4_SET ) -#undef LS4_SET -#else - d_4(uint_32t, t_dec(l,s), sb_data, w0, w1, w2, w3); -#endif -#endif - -#if defined( IM1_SET ) - d_1(uint_32t, t_dec(i,m), mm_data, v0); -#endif -#if defined( IM4_SET ) - d_4(uint_32t, t_dec(i,m), mm_data, v0, v1, v2, v3); -#endif - -#endif +/* + --------------------------------------------------------------------------- + Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software is allowed (with or without + changes) provided that: + + 1. source code distributions include the above copyright notice, this + list of conditions and the following disclaimer; + + 2. binary distributions include the above copyright notice, this list + of conditions and the following disclaimer in their documentation; + + 3. the name of the copyright holder is not used to endorse products + built using this software without specific written permission. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + Issue Date: 20/12/2007 + + This file contains the code for declaring the tables needed to implement + AES. The file aesopt.h is assumed to be included before this header file. + If there are no global variables, the definitions here can be used to put + the AES tables in a structure so that a pointer can then be added to the + AES context to pass them to the AES routines that need them. If this + facility is used, the calling program has to ensure that this pointer is + managed appropriately. In particular, the value of the t_dec(in,it) item + in the table structure must be set to zero in order to ensure that the + tables are initialised. In practice the three code sequences in aeskey.c + that control the calls to aes_init() and the aes_init() routine itself will + have to be changed for a specific implementation. If global variables are + available it will generally be preferable to use them with the precomputed + FIXED_TABLES option that uses static global tables. + + The following defines can be used to control the way the tables + are defined, initialised and used in embedded environments that + require special features for these purposes + + the 't_dec' construction is used to declare fixed table arrays + the 't_set' construction is used to set fixed table values + the 't_use' construction is used to access fixed table values + + 256 byte tables: + + t_xxx(s,box) => forward S box + t_xxx(i,box) => inverse S box + + 256 32-bit word OR 4 x 256 32-bit word tables: + + t_xxx(f,n) => forward normal round + t_xxx(f,l) => forward last round + t_xxx(i,n) => inverse normal round + t_xxx(i,l) => inverse last round + t_xxx(l,s) => key schedule table + t_xxx(i,m) => key schedule table + + Other variables and tables: + + t_xxx(r,c) => the rcon table +*/ + +#if !defined( _AESTAB_H ) +#define _AESTAB_H + +#define t_dec(m,n) t_##m##n +#define t_set(m,n) t_##m##n +#define t_use(m,n) t_##m##n + +#if defined(FIXED_TABLES) +# if !defined( __GNUC__ ) && (defined( __MSDOS__ ) || defined( __WIN16__ )) +/* make tables far data to avoid using too much DGROUP space (PG) */ +# define CONST const far +# else +# define CONST const +# endif +#else +# define CONST +#endif + +#if defined(__cplusplus) +# define EXTERN extern "C" +#elif defined(DO_TABLES) +# define EXTERN +#else +# define EXTERN extern +#endif + +#if defined(_MSC_VER) && defined(TABLE_ALIGN) +#define ALIGN __declspec(align(TABLE_ALIGN)) +#else +#define ALIGN +#endif + +#if defined( __WATCOMC__ ) && ( __WATCOMC__ >= 1100 ) +# define XP_DIR __cdecl +#else +# define XP_DIR +#endif + +#if defined(DO_TABLES) && defined(FIXED_TABLES) +#define d_1(t,n,b,e) EXTERN ALIGN CONST XP_DIR t n[256] = b(e) +#define d_4(t,n,b,e,f,g,h) EXTERN ALIGN CONST XP_DIR t n[4][256] = { b(e), b(f), b(g), b(h) } +EXTERN ALIGN CONST uint_32t t_dec(r,c)[RC_LENGTH] = rc_data(w0); +#else +#define d_1(t,n,b,e) EXTERN ALIGN CONST XP_DIR t n[256] +#define d_4(t,n,b,e,f,g,h) EXTERN ALIGN CONST XP_DIR t n[4][256] +EXTERN ALIGN CONST uint_32t t_dec(r,c)[RC_LENGTH]; +#endif + +#if defined( SBX_SET ) + d_1(uint_8t, t_dec(s,box), sb_data, h0); +#endif +#if defined( ISB_SET ) + d_1(uint_8t, t_dec(i,box), isb_data, h0); +#endif + +#if defined( FT1_SET ) + d_1(uint_32t, t_dec(f,n), sb_data, u0); +#endif +#if defined( FT4_SET ) + d_4(uint_32t, t_dec(f,n), sb_data, u0, u1, u2, u3); +#endif + +#if defined( FL1_SET ) + d_1(uint_32t, t_dec(f,l), sb_data, w0); +#endif +#if defined( FL4_SET ) + d_4(uint_32t, t_dec(f,l), sb_data, w0, w1, w2, w3); +#endif + +#if defined( IT1_SET ) + d_1(uint_32t, t_dec(i,n), isb_data, v0); +#endif +#if defined( IT4_SET ) + d_4(uint_32t, t_dec(i,n), isb_data, v0, v1, v2, v3); +#endif + +#if defined( IL1_SET ) + d_1(uint_32t, t_dec(i,l), isb_data, w0); +#endif +#if defined( IL4_SET ) + d_4(uint_32t, t_dec(i,l), isb_data, w0, w1, w2, w3); +#endif + +#if defined( LS1_SET ) +#if defined( FL1_SET ) +#undef LS1_SET +#else + d_1(uint_32t, t_dec(l,s), sb_data, w0); +#endif +#endif + +#if defined( LS4_SET ) +#if defined( FL4_SET ) +#undef LS4_SET +#else + d_4(uint_32t, t_dec(l,s), sb_data, w0, w1, w2, w3); +#endif +#endif + +#if defined( IM1_SET ) + d_1(uint_32t, t_dec(i,m), mm_data, v0); +#endif +#if defined( IM4_SET ) + d_4(uint_32t, t_dec(i,m), mm_data, v0, v1, v2, v3); +#endif + +#endif diff --git a/src/Crypto/Crypto.vcproj b/src/Crypto/Crypto.vcproj index 24b012c5..50f67a11 100644 --- a/src/Crypto/Crypto.vcproj +++ b/src/Crypto/Crypto.vcproj @@ -1,517 +1,517 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Crypto/Makefile b/src/Crypto/Makefile index 53b9a3d6..5acbbd24 100644 --- a/src/Crypto/Makefile +++ b/src/Crypto/Makefile @@ -1 +1 @@ -!INCLUDE $(NTMAKEENV)\makefile.def +!INCLUDE $(NTMAKEENV)\makefile.def diff --git a/src/Crypto/Makefile.inc b/src/Crypto/Makefile.inc index 51c4f46d..955f2a76 100644 --- a/src/Crypto/Makefile.inc +++ b/src/Crypto/Makefile.inc @@ -1,15 +1,15 @@ -TC_ASFLAGS = -Xvc -Ox - -!if "$(TC_ARCH)" == "x86" -TC_ASFLAGS = $(TC_ASFLAGS) -f win32 --prefix _ -D MS_STDCALL -D DLL_EXPORT -!else -TC_ASFLAGS = $(TC_ASFLAGS) -f win64 -!endif - -TC_ASM_ERR_LOG = ..\Driver\build_errors_asm.log - -"$(OBJ_PATH)\$(O)\Aes_$(TC_ARCH).obj": Aes_$(TC_ARCH).asm - nasm.exe $(TC_ASFLAGS) -o "$@" -l "$(OBJ_PATH)\$(O)\Aes_$(TC_ARCH).lst" Aes_$(TC_ARCH).asm 2>$(TC_ASM_ERR_LOG) - -"$(OBJ_PATH)\$(O)\Aes_hw_cpu.obj": Aes_hw_cpu.asm - nasm.exe $(TC_ASFLAGS) -o "$@" -l "$(OBJ_PATH)\$(O)\Aes_hw_cpu.lst" Aes_hw_cpu.asm 2>$(TC_ASM_ERR_LOG) +TC_ASFLAGS = -Xvc -Ox + +!if "$(TC_ARCH)" == "x86" +TC_ASFLAGS = $(TC_ASFLAGS) -f win32 --prefix _ -D MS_STDCALL -D DLL_EXPORT +!else +TC_ASFLAGS = $(TC_ASFLAGS) -f win64 +!endif + +TC_ASM_ERR_LOG = ..\Driver\build_errors_asm.log + +"$(OBJ_PATH)\$(O)\Aes_$(TC_ARCH).obj": Aes_$(TC_ARCH).asm + nasm.exe $(TC_ASFLAGS) -o "$@" -l "$(OBJ_PATH)\$(O)\Aes_$(TC_ARCH).lst" Aes_$(TC_ARCH).asm 2>$(TC_ASM_ERR_LOG) + +"$(OBJ_PATH)\$(O)\Aes_hw_cpu.obj": Aes_hw_cpu.asm + nasm.exe $(TC_ASFLAGS) -o "$@" -l "$(OBJ_PATH)\$(O)\Aes_hw_cpu.lst" Aes_hw_cpu.asm 2>$(TC_ASM_ERR_LOG) diff --git a/src/Crypto/Rmd160.c b/src/Crypto/Rmd160.c index f94f5e08..75a34c3e 100644 --- a/src/Crypto/Rmd160.c +++ b/src/Crypto/Rmd160.c @@ -1,498 +1,498 @@ -// RIPEMD-160 written and placed in the public domain by Wei Dai - -/* - * This code implements the MD4 message-digest algorithm. - * The algorithm is due to Ron Rivest. This code was - * written by Colin Plumb in 1993, no copyright is claimed. - * This code is in the public domain; do with it what you wish. - */ - -/* Adapted for TrueCrypt */ -/* Adapted for VeraCrypt */ - -#include -#include "Common/Tcdefs.h" -#include "Common/Endian.h" -#include "Rmd160.h" - -#define F(x, y, z) (x ^ y ^ z) -#define G(x, y, z) (z ^ (x & (y^z))) -#define H(x, y, z) (z ^ (x | ~y)) -#define I(x, y, z) (y ^ (z & (x^y))) -#define J(x, y, z) (x ^ (y | ~z)) - -#define PUT_64BIT_LE(cp, value) do { \ - (cp)[7] = (byte) ((value) >> 56); \ - (cp)[6] = (byte) ((value) >> 48); \ - (cp)[5] = (byte) ((value) >> 40); \ - (cp)[4] = (byte) ((value) >> 32); \ - (cp)[3] = (byte) ((value) >> 24); \ - (cp)[2] = (byte) ((value) >> 16); \ - (cp)[1] = (byte) ((value) >> 8); \ - (cp)[0] = (byte) (value); } while (0) - -#define PUT_32BIT_LE(cp, value) do { \ - (cp)[3] = (byte) ((value) >> 24); \ - (cp)[2] = (byte) ((value) >> 16); \ - (cp)[1] = (byte) ((value) >> 8); \ - (cp)[0] = (byte) (value); } while (0) - -#ifndef TC_MINIMIZE_CODE_SIZE - -static byte PADDING[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -#else - -static byte PADDING[64]; - -#endif - -void RMD160Init (RMD160_CTX *ctx) -{ - ctx->count = 0; - ctx->state[0] = 0x67452301; - ctx->state[1] = 0xefcdab89; - ctx->state[2] = 0x98badcfe; - ctx->state[3] = 0x10325476; - ctx->state[4] = 0xc3d2e1f0; - PADDING[0] = 0x80; -} - -/* -* Update context to reflect the concatenation of another buffer full -* of bytes. -*/ -void RMD160Update (RMD160_CTX *ctx, const unsigned char *input, unsigned __int32 lenArg) -{ -#ifndef TC_WINDOWS_BOOT - uint64 len = lenArg; -#else - uint32 len = lenArg; -#endif - unsigned int have, need; - - /* Check how many bytes we already have and how many more we need. */ - have = (unsigned int) ((ctx->count) & (RIPEMD160_BLOCK_LENGTH - 1)); - need = RIPEMD160_BLOCK_LENGTH - have; - - /* Update bitcount */ - ctx->count += len; - - if (len >= need) { - if (have != 0) { - memcpy (ctx->buffer + have, input, (size_t) need); - RMD160Transform ((uint32 *) ctx->state, (const uint32 *) ctx->buffer); - input += need; - len -= need; - have = 0; - } - - /* Process data in RIPEMD160_BLOCK_LENGTH-byte chunks. */ - while (len >= RIPEMD160_BLOCK_LENGTH) { - RMD160Transform ((uint32 *) ctx->state, (const uint32 *) input); - input += RIPEMD160_BLOCK_LENGTH; - len -= RIPEMD160_BLOCK_LENGTH; - } - } - - /* Handle any remaining bytes of data. */ - if (len != 0) - memcpy (ctx->buffer + have, input, (size_t) len); -} - -/* -* Pad pad to 64-byte boundary with the bit pattern -* 1 0* (64-bit count of bits processed, MSB-first) -*/ -static void RMD160Pad(RMD160_CTX *ctx) -{ - byte count[8]; - uint32 padlen; - - /* Convert count to 8 bytes in little endian order. */ - -#ifndef TC_WINDOWS_BOOT - uint64 bitcount = ctx->count << 3; - PUT_64BIT_LE(count, bitcount); -#else - *(uint32 *) (count + 4) = 0; - *(uint32 *) (count + 0) = ctx->count << 3; -#endif - - /* Pad out to 56 mod 64. */ - padlen = RIPEMD160_BLOCK_LENGTH - - (uint32)((ctx->count) & (RIPEMD160_BLOCK_LENGTH - 1)); - if (padlen < 1 + 8) - padlen += RIPEMD160_BLOCK_LENGTH; - RMD160Update(ctx, PADDING, padlen - 8); /* padlen - 8 <= 64 */ - RMD160Update(ctx, count, 8); -} - -/* -* Final wrapup--call RMD160Pad, fill in digest and zero out ctx. -*/ -void RMD160Final(unsigned char *digest, RMD160_CTX *ctx) -{ - int i; - - RMD160Pad(ctx); - if (digest) { - for (i = 0; i < 5; i++) - PUT_32BIT_LE(digest + i * 4, ctx->state[i]); -#ifndef TC_WINDOWS_BOOT - burn (ctx, sizeof(*ctx)); -#endif - } -} - - -#ifndef TC_MINIMIZE_CODE_SIZE - -#define word32 unsigned __int32 - -#define k0 0 -#define k1 0x5a827999UL -#define k2 0x6ed9eba1UL -#define k3 0x8f1bbcdcUL -#define k4 0xa953fd4eUL -#define k5 0x50a28be6UL -#define k6 0x5c4dd124UL -#define k7 0x6d703ef3UL -#define k8 0x7a6d76e9UL -#define k9 0 - -static word32 rotlFixed (word32 x, unsigned int y) -{ - return (word32)((x<>(sizeof(word32)*8-y))); -} - -#define Subround(f, a, b, c, d, e, x, s, k) \ - a += f(b, c, d) + x + k;\ - a = rotlFixed((word32)a, s) + e;\ - c = rotlFixed((word32)c, 10U) - -void RMD160Transform (unsigned __int32 *digest, const unsigned __int32 *data) -{ -#if BYTE_ORDER == LITTLE_ENDIAN - const word32 *X = data; -#else - word32 X[16]; - int i; -#endif - - word32 a1, b1, c1, d1, e1, a2, b2, c2, d2, e2; - a1 = a2 = digest[0]; - b1 = b2 = digest[1]; - c1 = c2 = digest[2]; - d1 = d2 = digest[3]; - e1 = e2 = digest[4]; - -#if BYTE_ORDER == BIG_ENDIAN - for (i = 0; i < 16; i++) - { - X[i] = LE32 (data[i]); - } -#endif - - Subround(F, a1, b1, c1, d1, e1, X[ 0], 11, k0); - Subround(F, e1, a1, b1, c1, d1, X[ 1], 14, k0); - Subround(F, d1, e1, a1, b1, c1, X[ 2], 15, k0); - Subround(F, c1, d1, e1, a1, b1, X[ 3], 12, k0); - Subround(F, b1, c1, d1, e1, a1, X[ 4], 5, k0); - Subround(F, a1, b1, c1, d1, e1, X[ 5], 8, k0); - Subround(F, e1, a1, b1, c1, d1, X[ 6], 7, k0); - Subround(F, d1, e1, a1, b1, c1, X[ 7], 9, k0); - Subround(F, c1, d1, e1, a1, b1, X[ 8], 11, k0); - Subround(F, b1, c1, d1, e1, a1, X[ 9], 13, k0); - Subround(F, a1, b1, c1, d1, e1, X[10], 14, k0); - Subround(F, e1, a1, b1, c1, d1, X[11], 15, k0); - Subround(F, d1, e1, a1, b1, c1, X[12], 6, k0); - Subround(F, c1, d1, e1, a1, b1, X[13], 7, k0); - Subround(F, b1, c1, d1, e1, a1, X[14], 9, k0); - Subround(F, a1, b1, c1, d1, e1, X[15], 8, k0); - - Subround(G, e1, a1, b1, c1, d1, X[ 7], 7, k1); - Subround(G, d1, e1, a1, b1, c1, X[ 4], 6, k1); - Subround(G, c1, d1, e1, a1, b1, X[13], 8, k1); - Subround(G, b1, c1, d1, e1, a1, X[ 1], 13, k1); - Subround(G, a1, b1, c1, d1, e1, X[10], 11, k1); - Subround(G, e1, a1, b1, c1, d1, X[ 6], 9, k1); - Subround(G, d1, e1, a1, b1, c1, X[15], 7, k1); - Subround(G, c1, d1, e1, a1, b1, X[ 3], 15, k1); - Subround(G, b1, c1, d1, e1, a1, X[12], 7, k1); - Subround(G, a1, b1, c1, d1, e1, X[ 0], 12, k1); - Subround(G, e1, a1, b1, c1, d1, X[ 9], 15, k1); - Subround(G, d1, e1, a1, b1, c1, X[ 5], 9, k1); - Subround(G, c1, d1, e1, a1, b1, X[ 2], 11, k1); - Subround(G, b1, c1, d1, e1, a1, X[14], 7, k1); - Subround(G, a1, b1, c1, d1, e1, X[11], 13, k1); - Subround(G, e1, a1, b1, c1, d1, X[ 8], 12, k1); - - Subround(H, d1, e1, a1, b1, c1, X[ 3], 11, k2); - Subround(H, c1, d1, e1, a1, b1, X[10], 13, k2); - Subround(H, b1, c1, d1, e1, a1, X[14], 6, k2); - Subround(H, a1, b1, c1, d1, e1, X[ 4], 7, k2); - Subround(H, e1, a1, b1, c1, d1, X[ 9], 14, k2); - Subround(H, d1, e1, a1, b1, c1, X[15], 9, k2); - Subround(H, c1, d1, e1, a1, b1, X[ 8], 13, k2); - Subround(H, b1, c1, d1, e1, a1, X[ 1], 15, k2); - Subround(H, a1, b1, c1, d1, e1, X[ 2], 14, k2); - Subround(H, e1, a1, b1, c1, d1, X[ 7], 8, k2); - Subround(H, d1, e1, a1, b1, c1, X[ 0], 13, k2); - Subround(H, c1, d1, e1, a1, b1, X[ 6], 6, k2); - Subround(H, b1, c1, d1, e1, a1, X[13], 5, k2); - Subround(H, a1, b1, c1, d1, e1, X[11], 12, k2); - Subround(H, e1, a1, b1, c1, d1, X[ 5], 7, k2); - Subround(H, d1, e1, a1, b1, c1, X[12], 5, k2); - - Subround(I, c1, d1, e1, a1, b1, X[ 1], 11, k3); - Subround(I, b1, c1, d1, e1, a1, X[ 9], 12, k3); - Subround(I, a1, b1, c1, d1, e1, X[11], 14, k3); - Subround(I, e1, a1, b1, c1, d1, X[10], 15, k3); - Subround(I, d1, e1, a1, b1, c1, X[ 0], 14, k3); - Subround(I, c1, d1, e1, a1, b1, X[ 8], 15, k3); - Subround(I, b1, c1, d1, e1, a1, X[12], 9, k3); - Subround(I, a1, b1, c1, d1, e1, X[ 4], 8, k3); - Subround(I, e1, a1, b1, c1, d1, X[13], 9, k3); - Subround(I, d1, e1, a1, b1, c1, X[ 3], 14, k3); - Subround(I, c1, d1, e1, a1, b1, X[ 7], 5, k3); - Subround(I, b1, c1, d1, e1, a1, X[15], 6, k3); - Subround(I, a1, b1, c1, d1, e1, X[14], 8, k3); - Subround(I, e1, a1, b1, c1, d1, X[ 5], 6, k3); - Subround(I, d1, e1, a1, b1, c1, X[ 6], 5, k3); - Subround(I, c1, d1, e1, a1, b1, X[ 2], 12, k3); - - Subround(J, b1, c1, d1, e1, a1, X[ 4], 9, k4); - Subround(J, a1, b1, c1, d1, e1, X[ 0], 15, k4); - Subround(J, e1, a1, b1, c1, d1, X[ 5], 5, k4); - Subround(J, d1, e1, a1, b1, c1, X[ 9], 11, k4); - Subround(J, c1, d1, e1, a1, b1, X[ 7], 6, k4); - Subround(J, b1, c1, d1, e1, a1, X[12], 8, k4); - Subround(J, a1, b1, c1, d1, e1, X[ 2], 13, k4); - Subround(J, e1, a1, b1, c1, d1, X[10], 12, k4); - Subround(J, d1, e1, a1, b1, c1, X[14], 5, k4); - Subround(J, c1, d1, e1, a1, b1, X[ 1], 12, k4); - Subround(J, b1, c1, d1, e1, a1, X[ 3], 13, k4); - Subround(J, a1, b1, c1, d1, e1, X[ 8], 14, k4); - Subround(J, e1, a1, b1, c1, d1, X[11], 11, k4); - Subround(J, d1, e1, a1, b1, c1, X[ 6], 8, k4); - Subround(J, c1, d1, e1, a1, b1, X[15], 5, k4); - Subround(J, b1, c1, d1, e1, a1, X[13], 6, k4); - - Subround(J, a2, b2, c2, d2, e2, X[ 5], 8, k5); - Subround(J, e2, a2, b2, c2, d2, X[14], 9, k5); - Subround(J, d2, e2, a2, b2, c2, X[ 7], 9, k5); - Subround(J, c2, d2, e2, a2, b2, X[ 0], 11, k5); - Subround(J, b2, c2, d2, e2, a2, X[ 9], 13, k5); - Subround(J, a2, b2, c2, d2, e2, X[ 2], 15, k5); - Subround(J, e2, a2, b2, c2, d2, X[11], 15, k5); - Subround(J, d2, e2, a2, b2, c2, X[ 4], 5, k5); - Subround(J, c2, d2, e2, a2, b2, X[13], 7, k5); - Subround(J, b2, c2, d2, e2, a2, X[ 6], 7, k5); - Subround(J, a2, b2, c2, d2, e2, X[15], 8, k5); - Subround(J, e2, a2, b2, c2, d2, X[ 8], 11, k5); - Subround(J, d2, e2, a2, b2, c2, X[ 1], 14, k5); - Subround(J, c2, d2, e2, a2, b2, X[10], 14, k5); - Subround(J, b2, c2, d2, e2, a2, X[ 3], 12, k5); - Subround(J, a2, b2, c2, d2, e2, X[12], 6, k5); - - Subround(I, e2, a2, b2, c2, d2, X[ 6], 9, k6); - Subround(I, d2, e2, a2, b2, c2, X[11], 13, k6); - Subround(I, c2, d2, e2, a2, b2, X[ 3], 15, k6); - Subround(I, b2, c2, d2, e2, a2, X[ 7], 7, k6); - Subround(I, a2, b2, c2, d2, e2, X[ 0], 12, k6); - Subround(I, e2, a2, b2, c2, d2, X[13], 8, k6); - Subround(I, d2, e2, a2, b2, c2, X[ 5], 9, k6); - Subround(I, c2, d2, e2, a2, b2, X[10], 11, k6); - Subround(I, b2, c2, d2, e2, a2, X[14], 7, k6); - Subround(I, a2, b2, c2, d2, e2, X[15], 7, k6); - Subround(I, e2, a2, b2, c2, d2, X[ 8], 12, k6); - Subround(I, d2, e2, a2, b2, c2, X[12], 7, k6); - Subround(I, c2, d2, e2, a2, b2, X[ 4], 6, k6); - Subround(I, b2, c2, d2, e2, a2, X[ 9], 15, k6); - Subround(I, a2, b2, c2, d2, e2, X[ 1], 13, k6); - Subround(I, e2, a2, b2, c2, d2, X[ 2], 11, k6); - - Subround(H, d2, e2, a2, b2, c2, X[15], 9, k7); - Subround(H, c2, d2, e2, a2, b2, X[ 5], 7, k7); - Subround(H, b2, c2, d2, e2, a2, X[ 1], 15, k7); - Subround(H, a2, b2, c2, d2, e2, X[ 3], 11, k7); - Subround(H, e2, a2, b2, c2, d2, X[ 7], 8, k7); - Subround(H, d2, e2, a2, b2, c2, X[14], 6, k7); - Subround(H, c2, d2, e2, a2, b2, X[ 6], 6, k7); - Subround(H, b2, c2, d2, e2, a2, X[ 9], 14, k7); - Subround(H, a2, b2, c2, d2, e2, X[11], 12, k7); - Subround(H, e2, a2, b2, c2, d2, X[ 8], 13, k7); - Subround(H, d2, e2, a2, b2, c2, X[12], 5, k7); - Subround(H, c2, d2, e2, a2, b2, X[ 2], 14, k7); - Subround(H, b2, c2, d2, e2, a2, X[10], 13, k7); - Subround(H, a2, b2, c2, d2, e2, X[ 0], 13, k7); - Subround(H, e2, a2, b2, c2, d2, X[ 4], 7, k7); - Subround(H, d2, e2, a2, b2, c2, X[13], 5, k7); - - Subround(G, c2, d2, e2, a2, b2, X[ 8], 15, k8); - Subround(G, b2, c2, d2, e2, a2, X[ 6], 5, k8); - Subround(G, a2, b2, c2, d2, e2, X[ 4], 8, k8); - Subround(G, e2, a2, b2, c2, d2, X[ 1], 11, k8); - Subround(G, d2, e2, a2, b2, c2, X[ 3], 14, k8); - Subround(G, c2, d2, e2, a2, b2, X[11], 14, k8); - Subround(G, b2, c2, d2, e2, a2, X[15], 6, k8); - Subround(G, a2, b2, c2, d2, e2, X[ 0], 14, k8); - Subround(G, e2, a2, b2, c2, d2, X[ 5], 6, k8); - Subround(G, d2, e2, a2, b2, c2, X[12], 9, k8); - Subround(G, c2, d2, e2, a2, b2, X[ 2], 12, k8); - Subround(G, b2, c2, d2, e2, a2, X[13], 9, k8); - Subround(G, a2, b2, c2, d2, e2, X[ 9], 12, k8); - Subround(G, e2, a2, b2, c2, d2, X[ 7], 5, k8); - Subround(G, d2, e2, a2, b2, c2, X[10], 15, k8); - Subround(G, c2, d2, e2, a2, b2, X[14], 8, k8); - - Subround(F, b2, c2, d2, e2, a2, X[12], 8, k9); - Subround(F, a2, b2, c2, d2, e2, X[15], 5, k9); - Subround(F, e2, a2, b2, c2, d2, X[10], 12, k9); - Subround(F, d2, e2, a2, b2, c2, X[ 4], 9, k9); - Subround(F, c2, d2, e2, a2, b2, X[ 1], 12, k9); - Subround(F, b2, c2, d2, e2, a2, X[ 5], 5, k9); - Subround(F, a2, b2, c2, d2, e2, X[ 8], 14, k9); - Subround(F, e2, a2, b2, c2, d2, X[ 7], 6, k9); - Subround(F, d2, e2, a2, b2, c2, X[ 6], 8, k9); - Subround(F, c2, d2, e2, a2, b2, X[ 2], 13, k9); - Subround(F, b2, c2, d2, e2, a2, X[13], 6, k9); - Subround(F, a2, b2, c2, d2, e2, X[14], 5, k9); - Subround(F, e2, a2, b2, c2, d2, X[ 0], 15, k9); - Subround(F, d2, e2, a2, b2, c2, X[ 3], 13, k9); - Subround(F, c2, d2, e2, a2, b2, X[ 9], 11, k9); - Subround(F, b2, c2, d2, e2, a2, X[11], 11, k9); - - c1 = digest[1] + c1 + d2; - digest[1] = digest[2] + d1 + e2; - digest[2] = digest[3] + e1 + a2; - digest[3] = digest[4] + a1 + b2; - digest[4] = digest[0] + b1 + c2; - digest[0] = c1; -} - -#else // TC_MINIMIZE_CODE_SIZE - -/* - 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. -*/ - -#pragma optimize ("tl", on) - -typedef unsigned __int32 uint32; -typedef unsigned __int8 byte; - -#include -#pragma intrinsic (_lrotl) - -static const byte OrderTab[] = { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13, - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -}; - -static const byte RolTab[] = { - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6, - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -}; - -static const uint32 KTab[] = { - 0x00000000UL, - 0x5A827999UL, - 0x6ED9EBA1UL, - 0x8F1BBCDCUL, - 0xA953FD4EUL, - 0x50A28BE6UL, - 0x5C4DD124UL, - 0x6D703EF3UL, - 0x7A6D76E9UL, - 0x00000000UL -}; - - -void RMD160Transform (unsigned __int32 *state, const unsigned __int32 *data) -{ - uint32 a, b, c, d, e; - uint32 a2, b2, c2, d2, e2; - byte pos; - uint32 tmp; - - a = state[0]; - b = state[1]; - c = state[2]; - d = state[3]; - e = state[4]; - - for (pos = 0; pos < 160; ++pos) - { - tmp = a + data[OrderTab[pos]] + KTab[pos >> 4]; - - switch (pos >> 4) - { - case 0: case 9: tmp += F (b, c, d); break; - case 1: case 8: tmp += G (b, c, d); break; - case 2: case 7: tmp += H (b, c, d); break; - case 3: case 6: tmp += I (b, c, d); break; - case 4: case 5: tmp += J (b, c, d); break; - } - - tmp = _lrotl (tmp, RolTab[pos]) + e; - a = e; - e = d; - d = _lrotl (c, 10); - c = b; - b = tmp; - - if (pos == 79) - { - a2 = a; - b2 = b; - c2 = c; - d2 = d; - e2 = e; - - a = state[0]; - b = state[1]; - c = state[2]; - d = state[3]; - e = state[4]; - } - } - - tmp = state[1] + c2 + d; - state[1] = state[2] + d2 + e; - state[2] = state[3] + e2 + a; - state[3] = state[4] + a2 + b; - state[4] = state[0] + b2 + c; - state[0] = tmp; -} - -#endif // TC_MINIMIZE_CODE_SIZE +// RIPEMD-160 written and placed in the public domain by Wei Dai + +/* + * This code implements the MD4 message-digest algorithm. + * The algorithm is due to Ron Rivest. This code was + * written by Colin Plumb in 1993, no copyright is claimed. + * This code is in the public domain; do with it what you wish. + */ + +/* Adapted for TrueCrypt */ +/* Adapted for VeraCrypt */ + +#include +#include "Common/Tcdefs.h" +#include "Common/Endian.h" +#include "Rmd160.h" + +#define F(x, y, z) (x ^ y ^ z) +#define G(x, y, z) (z ^ (x & (y^z))) +#define H(x, y, z) (z ^ (x | ~y)) +#define I(x, y, z) (y ^ (z & (x^y))) +#define J(x, y, z) (x ^ (y | ~z)) + +#define PUT_64BIT_LE(cp, value) do { \ + (cp)[7] = (byte) ((value) >> 56); \ + (cp)[6] = (byte) ((value) >> 48); \ + (cp)[5] = (byte) ((value) >> 40); \ + (cp)[4] = (byte) ((value) >> 32); \ + (cp)[3] = (byte) ((value) >> 24); \ + (cp)[2] = (byte) ((value) >> 16); \ + (cp)[1] = (byte) ((value) >> 8); \ + (cp)[0] = (byte) (value); } while (0) + +#define PUT_32BIT_LE(cp, value) do { \ + (cp)[3] = (byte) ((value) >> 24); \ + (cp)[2] = (byte) ((value) >> 16); \ + (cp)[1] = (byte) ((value) >> 8); \ + (cp)[0] = (byte) (value); } while (0) + +#ifndef TC_MINIMIZE_CODE_SIZE + +static byte PADDING[64] = { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +#else + +static byte PADDING[64]; + +#endif + +void RMD160Init (RMD160_CTX *ctx) +{ + ctx->count = 0; + ctx->state[0] = 0x67452301; + ctx->state[1] = 0xefcdab89; + ctx->state[2] = 0x98badcfe; + ctx->state[3] = 0x10325476; + ctx->state[4] = 0xc3d2e1f0; + PADDING[0] = 0x80; +} + +/* +* Update context to reflect the concatenation of another buffer full +* of bytes. +*/ +void RMD160Update (RMD160_CTX *ctx, const unsigned char *input, unsigned __int32 lenArg) +{ +#ifndef TC_WINDOWS_BOOT + uint64 len = lenArg; +#else + uint32 len = lenArg; +#endif + unsigned int have, need; + + /* Check how many bytes we already have and how many more we need. */ + have = (unsigned int) ((ctx->count) & (RIPEMD160_BLOCK_LENGTH - 1)); + need = RIPEMD160_BLOCK_LENGTH - have; + + /* Update bitcount */ + ctx->count += len; + + if (len >= need) { + if (have != 0) { + memcpy (ctx->buffer + have, input, (size_t) need); + RMD160Transform ((uint32 *) ctx->state, (const uint32 *) ctx->buffer); + input += need; + len -= need; + have = 0; + } + + /* Process data in RIPEMD160_BLOCK_LENGTH-byte chunks. */ + while (len >= RIPEMD160_BLOCK_LENGTH) { + RMD160Transform ((uint32 *) ctx->state, (const uint32 *) input); + input += RIPEMD160_BLOCK_LENGTH; + len -= RIPEMD160_BLOCK_LENGTH; + } + } + + /* Handle any remaining bytes of data. */ + if (len != 0) + memcpy (ctx->buffer + have, input, (size_t) len); +} + +/* +* Pad pad to 64-byte boundary with the bit pattern +* 1 0* (64-bit count of bits processed, MSB-first) +*/ +static void RMD160Pad(RMD160_CTX *ctx) +{ + byte count[8]; + uint32 padlen; + + /* Convert count to 8 bytes in little endian order. */ + +#ifndef TC_WINDOWS_BOOT + uint64 bitcount = ctx->count << 3; + PUT_64BIT_LE(count, bitcount); +#else + *(uint32 *) (count + 4) = 0; + *(uint32 *) (count + 0) = ctx->count << 3; +#endif + + /* Pad out to 56 mod 64. */ + padlen = RIPEMD160_BLOCK_LENGTH - + (uint32)((ctx->count) & (RIPEMD160_BLOCK_LENGTH - 1)); + if (padlen < 1 + 8) + padlen += RIPEMD160_BLOCK_LENGTH; + RMD160Update(ctx, PADDING, padlen - 8); /* padlen - 8 <= 64 */ + RMD160Update(ctx, count, 8); +} + +/* +* Final wrapup--call RMD160Pad, fill in digest and zero out ctx. +*/ +void RMD160Final(unsigned char *digest, RMD160_CTX *ctx) +{ + int i; + + RMD160Pad(ctx); + if (digest) { + for (i = 0; i < 5; i++) + PUT_32BIT_LE(digest + i * 4, ctx->state[i]); +#ifndef TC_WINDOWS_BOOT + burn (ctx, sizeof(*ctx)); +#endif + } +} + + +#ifndef TC_MINIMIZE_CODE_SIZE + +#define word32 unsigned __int32 + +#define k0 0 +#define k1 0x5a827999UL +#define k2 0x6ed9eba1UL +#define k3 0x8f1bbcdcUL +#define k4 0xa953fd4eUL +#define k5 0x50a28be6UL +#define k6 0x5c4dd124UL +#define k7 0x6d703ef3UL +#define k8 0x7a6d76e9UL +#define k9 0 + +static word32 rotlFixed (word32 x, unsigned int y) +{ + return (word32)((x<>(sizeof(word32)*8-y))); +} + +#define Subround(f, a, b, c, d, e, x, s, k) \ + a += f(b, c, d) + x + k;\ + a = rotlFixed((word32)a, s) + e;\ + c = rotlFixed((word32)c, 10U) + +void RMD160Transform (unsigned __int32 *digest, const unsigned __int32 *data) +{ +#if BYTE_ORDER == LITTLE_ENDIAN + const word32 *X = data; +#else + word32 X[16]; + int i; +#endif + + word32 a1, b1, c1, d1, e1, a2, b2, c2, d2, e2; + a1 = a2 = digest[0]; + b1 = b2 = digest[1]; + c1 = c2 = digest[2]; + d1 = d2 = digest[3]; + e1 = e2 = digest[4]; + +#if BYTE_ORDER == BIG_ENDIAN + for (i = 0; i < 16; i++) + { + X[i] = LE32 (data[i]); + } +#endif + + Subround(F, a1, b1, c1, d1, e1, X[ 0], 11, k0); + Subround(F, e1, a1, b1, c1, d1, X[ 1], 14, k0); + Subround(F, d1, e1, a1, b1, c1, X[ 2], 15, k0); + Subround(F, c1, d1, e1, a1, b1, X[ 3], 12, k0); + Subround(F, b1, c1, d1, e1, a1, X[ 4], 5, k0); + Subround(F, a1, b1, c1, d1, e1, X[ 5], 8, k0); + Subround(F, e1, a1, b1, c1, d1, X[ 6], 7, k0); + Subround(F, d1, e1, a1, b1, c1, X[ 7], 9, k0); + Subround(F, c1, d1, e1, a1, b1, X[ 8], 11, k0); + Subround(F, b1, c1, d1, e1, a1, X[ 9], 13, k0); + Subround(F, a1, b1, c1, d1, e1, X[10], 14, k0); + Subround(F, e1, a1, b1, c1, d1, X[11], 15, k0); + Subround(F, d1, e1, a1, b1, c1, X[12], 6, k0); + Subround(F, c1, d1, e1, a1, b1, X[13], 7, k0); + Subround(F, b1, c1, d1, e1, a1, X[14], 9, k0); + Subround(F, a1, b1, c1, d1, e1, X[15], 8, k0); + + Subround(G, e1, a1, b1, c1, d1, X[ 7], 7, k1); + Subround(G, d1, e1, a1, b1, c1, X[ 4], 6, k1); + Subround(G, c1, d1, e1, a1, b1, X[13], 8, k1); + Subround(G, b1, c1, d1, e1, a1, X[ 1], 13, k1); + Subround(G, a1, b1, c1, d1, e1, X[10], 11, k1); + Subround(G, e1, a1, b1, c1, d1, X[ 6], 9, k1); + Subround(G, d1, e1, a1, b1, c1, X[15], 7, k1); + Subround(G, c1, d1, e1, a1, b1, X[ 3], 15, k1); + Subround(G, b1, c1, d1, e1, a1, X[12], 7, k1); + Subround(G, a1, b1, c1, d1, e1, X[ 0], 12, k1); + Subround(G, e1, a1, b1, c1, d1, X[ 9], 15, k1); + Subround(G, d1, e1, a1, b1, c1, X[ 5], 9, k1); + Subround(G, c1, d1, e1, a1, b1, X[ 2], 11, k1); + Subround(G, b1, c1, d1, e1, a1, X[14], 7, k1); + Subround(G, a1, b1, c1, d1, e1, X[11], 13, k1); + Subround(G, e1, a1, b1, c1, d1, X[ 8], 12, k1); + + Subround(H, d1, e1, a1, b1, c1, X[ 3], 11, k2); + Subround(H, c1, d1, e1, a1, b1, X[10], 13, k2); + Subround(H, b1, c1, d1, e1, a1, X[14], 6, k2); + Subround(H, a1, b1, c1, d1, e1, X[ 4], 7, k2); + Subround(H, e1, a1, b1, c1, d1, X[ 9], 14, k2); + Subround(H, d1, e1, a1, b1, c1, X[15], 9, k2); + Subround(H, c1, d1, e1, a1, b1, X[ 8], 13, k2); + Subround(H, b1, c1, d1, e1, a1, X[ 1], 15, k2); + Subround(H, a1, b1, c1, d1, e1, X[ 2], 14, k2); + Subround(H, e1, a1, b1, c1, d1, X[ 7], 8, k2); + Subround(H, d1, e1, a1, b1, c1, X[ 0], 13, k2); + Subround(H, c1, d1, e1, a1, b1, X[ 6], 6, k2); + Subround(H, b1, c1, d1, e1, a1, X[13], 5, k2); + Subround(H, a1, b1, c1, d1, e1, X[11], 12, k2); + Subround(H, e1, a1, b1, c1, d1, X[ 5], 7, k2); + Subround(H, d1, e1, a1, b1, c1, X[12], 5, k2); + + Subround(I, c1, d1, e1, a1, b1, X[ 1], 11, k3); + Subround(I, b1, c1, d1, e1, a1, X[ 9], 12, k3); + Subround(I, a1, b1, c1, d1, e1, X[11], 14, k3); + Subround(I, e1, a1, b1, c1, d1, X[10], 15, k3); + Subround(I, d1, e1, a1, b1, c1, X[ 0], 14, k3); + Subround(I, c1, d1, e1, a1, b1, X[ 8], 15, k3); + Subround(I, b1, c1, d1, e1, a1, X[12], 9, k3); + Subround(I, a1, b1, c1, d1, e1, X[ 4], 8, k3); + Subround(I, e1, a1, b1, c1, d1, X[13], 9, k3); + Subround(I, d1, e1, a1, b1, c1, X[ 3], 14, k3); + Subround(I, c1, d1, e1, a1, b1, X[ 7], 5, k3); + Subround(I, b1, c1, d1, e1, a1, X[15], 6, k3); + Subround(I, a1, b1, c1, d1, e1, X[14], 8, k3); + Subround(I, e1, a1, b1, c1, d1, X[ 5], 6, k3); + Subround(I, d1, e1, a1, b1, c1, X[ 6], 5, k3); + Subround(I, c1, d1, e1, a1, b1, X[ 2], 12, k3); + + Subround(J, b1, c1, d1, e1, a1, X[ 4], 9, k4); + Subround(J, a1, b1, c1, d1, e1, X[ 0], 15, k4); + Subround(J, e1, a1, b1, c1, d1, X[ 5], 5, k4); + Subround(J, d1, e1, a1, b1, c1, X[ 9], 11, k4); + Subround(J, c1, d1, e1, a1, b1, X[ 7], 6, k4); + Subround(J, b1, c1, d1, e1, a1, X[12], 8, k4); + Subround(J, a1, b1, c1, d1, e1, X[ 2], 13, k4); + Subround(J, e1, a1, b1, c1, d1, X[10], 12, k4); + Subround(J, d1, e1, a1, b1, c1, X[14], 5, k4); + Subround(J, c1, d1, e1, a1, b1, X[ 1], 12, k4); + Subround(J, b1, c1, d1, e1, a1, X[ 3], 13, k4); + Subround(J, a1, b1, c1, d1, e1, X[ 8], 14, k4); + Subround(J, e1, a1, b1, c1, d1, X[11], 11, k4); + Subround(J, d1, e1, a1, b1, c1, X[ 6], 8, k4); + Subround(J, c1, d1, e1, a1, b1, X[15], 5, k4); + Subround(J, b1, c1, d1, e1, a1, X[13], 6, k4); + + Subround(J, a2, b2, c2, d2, e2, X[ 5], 8, k5); + Subround(J, e2, a2, b2, c2, d2, X[14], 9, k5); + Subround(J, d2, e2, a2, b2, c2, X[ 7], 9, k5); + Subround(J, c2, d2, e2, a2, b2, X[ 0], 11, k5); + Subround(J, b2, c2, d2, e2, a2, X[ 9], 13, k5); + Subround(J, a2, b2, c2, d2, e2, X[ 2], 15, k5); + Subround(J, e2, a2, b2, c2, d2, X[11], 15, k5); + Subround(J, d2, e2, a2, b2, c2, X[ 4], 5, k5); + Subround(J, c2, d2, e2, a2, b2, X[13], 7, k5); + Subround(J, b2, c2, d2, e2, a2, X[ 6], 7, k5); + Subround(J, a2, b2, c2, d2, e2, X[15], 8, k5); + Subround(J, e2, a2, b2, c2, d2, X[ 8], 11, k5); + Subround(J, d2, e2, a2, b2, c2, X[ 1], 14, k5); + Subround(J, c2, d2, e2, a2, b2, X[10], 14, k5); + Subround(J, b2, c2, d2, e2, a2, X[ 3], 12, k5); + Subround(J, a2, b2, c2, d2, e2, X[12], 6, k5); + + Subround(I, e2, a2, b2, c2, d2, X[ 6], 9, k6); + Subround(I, d2, e2, a2, b2, c2, X[11], 13, k6); + Subround(I, c2, d2, e2, a2, b2, X[ 3], 15, k6); + Subround(I, b2, c2, d2, e2, a2, X[ 7], 7, k6); + Subround(I, a2, b2, c2, d2, e2, X[ 0], 12, k6); + Subround(I, e2, a2, b2, c2, d2, X[13], 8, k6); + Subround(I, d2, e2, a2, b2, c2, X[ 5], 9, k6); + Subround(I, c2, d2, e2, a2, b2, X[10], 11, k6); + Subround(I, b2, c2, d2, e2, a2, X[14], 7, k6); + Subround(I, a2, b2, c2, d2, e2, X[15], 7, k6); + Subround(I, e2, a2, b2, c2, d2, X[ 8], 12, k6); + Subround(I, d2, e2, a2, b2, c2, X[12], 7, k6); + Subround(I, c2, d2, e2, a2, b2, X[ 4], 6, k6); + Subround(I, b2, c2, d2, e2, a2, X[ 9], 15, k6); + Subround(I, a2, b2, c2, d2, e2, X[ 1], 13, k6); + Subround(I, e2, a2, b2, c2, d2, X[ 2], 11, k6); + + Subround(H, d2, e2, a2, b2, c2, X[15], 9, k7); + Subround(H, c2, d2, e2, a2, b2, X[ 5], 7, k7); + Subround(H, b2, c2, d2, e2, a2, X[ 1], 15, k7); + Subround(H, a2, b2, c2, d2, e2, X[ 3], 11, k7); + Subround(H, e2, a2, b2, c2, d2, X[ 7], 8, k7); + Subround(H, d2, e2, a2, b2, c2, X[14], 6, k7); + Subround(H, c2, d2, e2, a2, b2, X[ 6], 6, k7); + Subround(H, b2, c2, d2, e2, a2, X[ 9], 14, k7); + Subround(H, a2, b2, c2, d2, e2, X[11], 12, k7); + Subround(H, e2, a2, b2, c2, d2, X[ 8], 13, k7); + Subround(H, d2, e2, a2, b2, c2, X[12], 5, k7); + Subround(H, c2, d2, e2, a2, b2, X[ 2], 14, k7); + Subround(H, b2, c2, d2, e2, a2, X[10], 13, k7); + Subround(H, a2, b2, c2, d2, e2, X[ 0], 13, k7); + Subround(H, e2, a2, b2, c2, d2, X[ 4], 7, k7); + Subround(H, d2, e2, a2, b2, c2, X[13], 5, k7); + + Subround(G, c2, d2, e2, a2, b2, X[ 8], 15, k8); + Subround(G, b2, c2, d2, e2, a2, X[ 6], 5, k8); + Subround(G, a2, b2, c2, d2, e2, X[ 4], 8, k8); + Subround(G, e2, a2, b2, c2, d2, X[ 1], 11, k8); + Subround(G, d2, e2, a2, b2, c2, X[ 3], 14, k8); + Subround(G, c2, d2, e2, a2, b2, X[11], 14, k8); + Subround(G, b2, c2, d2, e2, a2, X[15], 6, k8); + Subround(G, a2, b2, c2, d2, e2, X[ 0], 14, k8); + Subround(G, e2, a2, b2, c2, d2, X[ 5], 6, k8); + Subround(G, d2, e2, a2, b2, c2, X[12], 9, k8); + Subround(G, c2, d2, e2, a2, b2, X[ 2], 12, k8); + Subround(G, b2, c2, d2, e2, a2, X[13], 9, k8); + Subround(G, a2, b2, c2, d2, e2, X[ 9], 12, k8); + Subround(G, e2, a2, b2, c2, d2, X[ 7], 5, k8); + Subround(G, d2, e2, a2, b2, c2, X[10], 15, k8); + Subround(G, c2, d2, e2, a2, b2, X[14], 8, k8); + + Subround(F, b2, c2, d2, e2, a2, X[12], 8, k9); + Subround(F, a2, b2, c2, d2, e2, X[15], 5, k9); + Subround(F, e2, a2, b2, c2, d2, X[10], 12, k9); + Subround(F, d2, e2, a2, b2, c2, X[ 4], 9, k9); + Subround(F, c2, d2, e2, a2, b2, X[ 1], 12, k9); + Subround(F, b2, c2, d2, e2, a2, X[ 5], 5, k9); + Subround(F, a2, b2, c2, d2, e2, X[ 8], 14, k9); + Subround(F, e2, a2, b2, c2, d2, X[ 7], 6, k9); + Subround(F, d2, e2, a2, b2, c2, X[ 6], 8, k9); + Subround(F, c2, d2, e2, a2, b2, X[ 2], 13, k9); + Subround(F, b2, c2, d2, e2, a2, X[13], 6, k9); + Subround(F, a2, b2, c2, d2, e2, X[14], 5, k9); + Subround(F, e2, a2, b2, c2, d2, X[ 0], 15, k9); + Subround(F, d2, e2, a2, b2, c2, X[ 3], 13, k9); + Subround(F, c2, d2, e2, a2, b2, X[ 9], 11, k9); + Subround(F, b2, c2, d2, e2, a2, X[11], 11, k9); + + c1 = digest[1] + c1 + d2; + digest[1] = digest[2] + d1 + e2; + digest[2] = digest[3] + e1 + a2; + digest[3] = digest[4] + a1 + b2; + digest[4] = digest[0] + b1 + c2; + digest[0] = c1; +} + +#else // TC_MINIMIZE_CODE_SIZE + +/* + 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. +*/ + +#pragma optimize ("tl", on) + +typedef unsigned __int32 uint32; +typedef unsigned __int8 byte; + +#include +#pragma intrinsic (_lrotl) + +static const byte OrderTab[] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13, + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +}; + +static const byte RolTab[] = { + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6, + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +}; + +static const uint32 KTab[] = { + 0x00000000UL, + 0x5A827999UL, + 0x6ED9EBA1UL, + 0x8F1BBCDCUL, + 0xA953FD4EUL, + 0x50A28BE6UL, + 0x5C4DD124UL, + 0x6D703EF3UL, + 0x7A6D76E9UL, + 0x00000000UL +}; + + +void RMD160Transform (unsigned __int32 *state, const unsigned __int32 *data) +{ + uint32 a, b, c, d, e; + uint32 a2, b2, c2, d2, e2; + byte pos; + uint32 tmp; + + a = state[0]; + b = state[1]; + c = state[2]; + d = state[3]; + e = state[4]; + + for (pos = 0; pos < 160; ++pos) + { + tmp = a + data[OrderTab[pos]] + KTab[pos >> 4]; + + switch (pos >> 4) + { + case 0: case 9: tmp += F (b, c, d); break; + case 1: case 8: tmp += G (b, c, d); break; + case 2: case 7: tmp += H (b, c, d); break; + case 3: case 6: tmp += I (b, c, d); break; + case 4: case 5: tmp += J (b, c, d); break; + } + + tmp = _lrotl (tmp, RolTab[pos]) + e; + a = e; + e = d; + d = _lrotl (c, 10); + c = b; + b = tmp; + + if (pos == 79) + { + a2 = a; + b2 = b; + c2 = c; + d2 = d; + e2 = e; + + a = state[0]; + b = state[1]; + c = state[2]; + d = state[3]; + e = state[4]; + } + } + + tmp = state[1] + c2 + d; + state[1] = state[2] + d2 + e; + state[2] = state[3] + e2 + a; + state[3] = state[4] + a2 + b; + state[4] = state[0] + b2 + c; + state[0] = tmp; +} + +#endif // TC_MINIMIZE_CODE_SIZE diff --git a/src/Crypto/Rmd160.h b/src/Crypto/Rmd160.h index 4dfa38f1..81b5d6f0 100644 --- a/src/Crypto/Rmd160.h +++ b/src/Crypto/Rmd160.h @@ -1,33 +1,33 @@ -#ifndef TC_HEADER_Crypto_Ripemd160 -#define TC_HEADER_Crypto_Ripemd160 - -#include "Common/Tcdefs.h" - -#if defined(__cplusplus) -extern "C" -{ -#endif - -#define RIPEMD160_BLOCK_LENGTH 64 - -typedef struct RMD160Context -{ - unsigned __int32 state[5]; -#ifndef TC_WINDOWS_BOOT - uint64 count; -#else - uint32 count; -#endif - unsigned char buffer[RIPEMD160_BLOCK_LENGTH]; -} RMD160_CTX; - -void RMD160Init (RMD160_CTX *ctx); -void RMD160Transform (unsigned __int32 *state, const unsigned __int32 *data); -void RMD160Update (RMD160_CTX *ctx, const unsigned char *input, unsigned __int32 len); -void RMD160Final (unsigned char *digest, RMD160_CTX *ctx); - -#if defined(__cplusplus) -} -#endif - -#endif // TC_HEADER_Crypto_Ripemd160 +#ifndef TC_HEADER_Crypto_Ripemd160 +#define TC_HEADER_Crypto_Ripemd160 + +#include "Common/Tcdefs.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif + +#define RIPEMD160_BLOCK_LENGTH 64 + +typedef struct RMD160Context +{ + unsigned __int32 state[5]; +#ifndef TC_WINDOWS_BOOT + uint64 count; +#else + uint32 count; +#endif + unsigned char buffer[RIPEMD160_BLOCK_LENGTH]; +} RMD160_CTX; + +void RMD160Init (RMD160_CTX *ctx); +void RMD160Transform (unsigned __int32 *state, const unsigned __int32 *data); +void RMD160Update (RMD160_CTX *ctx, const unsigned char *input, unsigned __int32 len); +void RMD160Final (unsigned char *digest, RMD160_CTX *ctx); + +#if defined(__cplusplus) +} +#endif + +#endif // TC_HEADER_Crypto_Ripemd160 diff --git a/src/Crypto/Serpent.c b/src/Crypto/Serpent.c index 87d710c4..a8c528de 100644 --- a/src/Crypto/Serpent.c +++ b/src/Crypto/Serpent.c @@ -1,938 +1,938 @@ -// serpent.cpp - written and placed in the public domain by Wei Dai - -/* Adapted for TrueCrypt */ -/* Adapted for VeraCrypt */ - -#ifdef TC_WINDOWS_BOOT -#pragma optimize ("t", on) -#endif - -#include "Serpent.h" -#include "Common/Endian.h" - -#include - -#if defined(_WIN32) && !defined(_DEBUG) -#include -#define rotlFixed _rotl -#define rotrFixed _rotr -#else -#define rotlFixed(x,n) (((x) << (n)) | ((x) >> (32 - (n)))) -#define rotrFixed(x,n) (((x) >> (n)) | ((x) << (32 - (n)))) -#endif - -// linear transformation -#define LT(i,a,b,c,d,e) {\ - a = rotlFixed(a, 13); \ - c = rotlFixed(c, 3); \ - d = rotlFixed(d ^ c ^ (a << 3), 7); \ - b = rotlFixed(b ^ a ^ c, 1); \ - a = rotlFixed(a ^ b ^ d, 5); \ - c = rotlFixed(c ^ d ^ (b << 7), 22);} - -// inverse linear transformation -#define ILT(i,a,b,c,d,e) {\ - c = rotrFixed(c, 22); \ - a = rotrFixed(a, 5); \ - c ^= d ^ (b << 7); \ - a ^= b ^ d; \ - b = rotrFixed(b, 1); \ - d = rotrFixed(d, 7) ^ c ^ (a << 3); \ - b ^= a ^ c; \ - c = rotrFixed(c, 3); \ - a = rotrFixed(a, 13);} - -// order of output from S-box functions -#define beforeS0(f) f(0,a,b,c,d,e) -#define afterS0(f) f(1,b,e,c,a,d) -#define afterS1(f) f(2,c,b,a,e,d) -#define afterS2(f) f(3,a,e,b,d,c) -#define afterS3(f) f(4,e,b,d,c,a) -#define afterS4(f) f(5,b,a,e,c,d) -#define afterS5(f) f(6,a,c,b,e,d) -#define afterS6(f) f(7,a,c,d,b,e) -#define afterS7(f) f(8,d,e,b,a,c) - -// order of output from inverse S-box functions -#define beforeI7(f) f(8,a,b,c,d,e) -#define afterI7(f) f(7,d,a,b,e,c) -#define afterI6(f) f(6,a,b,c,e,d) -#define afterI5(f) f(5,b,d,e,c,a) -#define afterI4(f) f(4,b,c,e,a,d) -#define afterI3(f) f(3,a,b,e,c,d) -#define afterI2(f) f(2,b,d,e,c,a) -#define afterI1(f) f(1,a,b,c,e,d) -#define afterI0(f) f(0,a,d,b,e,c) - -// The instruction sequences for the S-box functions -// come from Dag Arne Osvik's paper "Speeding up Serpent". - -#define S0(i, r0, r1, r2, r3, r4) \ - { \ - r3 ^= r0; \ - r4 = r1; \ - r1 &= r3; \ - r4 ^= r2; \ - r1 ^= r0; \ - r0 |= r3; \ - r0 ^= r4; \ - r4 ^= r3; \ - r3 ^= r2; \ - r2 |= r1; \ - r2 ^= r4; \ - r4 = ~r4; \ - r4 |= r1; \ - r1 ^= r3; \ - r1 ^= r4; \ - r3 |= r0; \ - r1 ^= r3; \ - r4 ^= r3; \ - } - -#define I0(i, r0, r1, r2, r3, r4) \ - { \ - r2 = ~r2; \ - r4 = r1; \ - r1 |= r0; \ - r4 = ~r4; \ - r1 ^= r2; \ - r2 |= r4; \ - r1 ^= r3; \ - r0 ^= r4; \ - r2 ^= r0; \ - r0 &= r3; \ - r4 ^= r0; \ - r0 |= r1; \ - r0 ^= r2; \ - r3 ^= r4; \ - r2 ^= r1; \ - r3 ^= r0; \ - r3 ^= r1; \ - r2 &= r3; \ - r4 ^= r2; \ - } - -#define S1(i, r0, r1, r2, r3, r4) \ - { \ - r0 = ~r0; \ - r2 = ~r2; \ - r4 = r0; \ - r0 &= r1; \ - r2 ^= r0; \ - r0 |= r3; \ - r3 ^= r2; \ - r1 ^= r0; \ - r0 ^= r4; \ - r4 |= r1; \ - r1 ^= r3; \ - r2 |= r0; \ - r2 &= r4; \ - r0 ^= r1; \ - r1 &= r2; \ - r1 ^= r0; \ - r0 &= r2; \ - r0 ^= r4; \ - } - -#define I1(i, r0, r1, r2, r3, r4) \ - { \ - r4 = r1; \ - r1 ^= r3; \ - r3 &= r1; \ - r4 ^= r2; \ - r3 ^= r0; \ - r0 |= r1; \ - r2 ^= r3; \ - r0 ^= r4; \ - r0 |= r2; \ - r1 ^= r3; \ - r0 ^= r1; \ - r1 |= r3; \ - r1 ^= r0; \ - r4 = ~r4; \ - r4 ^= r1; \ - r1 |= r0; \ - r1 ^= r0; \ - r1 |= r4; \ - r3 ^= r1; \ - } - -#define S2(i, r0, r1, r2, r3, r4) \ - { \ - r4 = r0; \ - r0 &= r2; \ - r0 ^= r3; \ - r2 ^= r1; \ - r2 ^= r0; \ - r3 |= r4; \ - r3 ^= r1; \ - r4 ^= r2; \ - r1 = r3; \ - r3 |= r4; \ - r3 ^= r0; \ - r0 &= r1; \ - r4 ^= r0; \ - r1 ^= r3; \ - r1 ^= r4; \ - r4 = ~r4; \ - } - -#define I2(i, r0, r1, r2, r3, r4) \ - { \ - r2 ^= r3; \ - r3 ^= r0; \ - r4 = r3; \ - r3 &= r2; \ - r3 ^= r1; \ - r1 |= r2; \ - r1 ^= r4; \ - r4 &= r3; \ - r2 ^= r3; \ - r4 &= r0; \ - r4 ^= r2; \ - r2 &= r1; \ - r2 |= r0; \ - r3 = ~r3; \ - r2 ^= r3; \ - r0 ^= r3; \ - r0 &= r1; \ - r3 ^= r4; \ - r3 ^= r0; \ - } - -#define S3(i, r0, r1, r2, r3, r4) \ - { \ - r4 = r0; \ - r0 |= r3; \ - r3 ^= r1; \ - r1 &= r4; \ - r4 ^= r2; \ - r2 ^= r3; \ - r3 &= r0; \ - r4 |= r1; \ - r3 ^= r4; \ - r0 ^= r1; \ - r4 &= r0; \ - r1 ^= r3; \ - r4 ^= r2; \ - r1 |= r0; \ - r1 ^= r2; \ - r0 ^= r3; \ - r2 = r1; \ - r1 |= r3; \ - r1 ^= r0; \ - } - -#define I3(i, r0, r1, r2, r3, r4) \ - { \ - r4 = r2; \ - r2 ^= r1; \ - r1 &= r2; \ - r1 ^= r0; \ - r0 &= r4; \ - r4 ^= r3; \ - r3 |= r1; \ - r3 ^= r2; \ - r0 ^= r4; \ - r2 ^= r0; \ - r0 |= r3; \ - r0 ^= r1; \ - r4 ^= r2; \ - r2 &= r3; \ - r1 |= r3; \ - r1 ^= r2; \ - r4 ^= r0; \ - r2 ^= r4; \ - } - -#define S4(i, r0, r1, r2, r3, r4) \ - { \ - r1 ^= r3; \ - r3 = ~r3; \ - r2 ^= r3; \ - r3 ^= r0; \ - r4 = r1; \ - r1 &= r3; \ - r1 ^= r2; \ - r4 ^= r3; \ - r0 ^= r4; \ - r2 &= r4; \ - r2 ^= r0; \ - r0 &= r1; \ - r3 ^= r0; \ - r4 |= r1; \ - r4 ^= r0; \ - r0 |= r3; \ - r0 ^= r2; \ - r2 &= r3; \ - r0 = ~r0; \ - r4 ^= r2; \ - } - -#define I4(i, r0, r1, r2, r3, r4) \ - { \ - r4 = r2; \ - r2 &= r3; \ - r2 ^= r1; \ - r1 |= r3; \ - r1 &= r0; \ - r4 ^= r2; \ - r4 ^= r1; \ - r1 &= r2; \ - r0 = ~r0; \ - r3 ^= r4; \ - r1 ^= r3; \ - r3 &= r0; \ - r3 ^= r2; \ - r0 ^= r1; \ - r2 &= r0; \ - r3 ^= r0; \ - r2 ^= r4; \ - r2 |= r3; \ - r3 ^= r0; \ - r2 ^= r1; \ - } - -#define S5(i, r0, r1, r2, r3, r4) \ - { \ - r0 ^= r1; \ - r1 ^= r3; \ - r3 = ~r3; \ - r4 = r1; \ - r1 &= r0; \ - r2 ^= r3; \ - r1 ^= r2; \ - r2 |= r4; \ - r4 ^= r3; \ - r3 &= r1; \ - r3 ^= r0; \ - r4 ^= r1; \ - r4 ^= r2; \ - r2 ^= r0; \ - r0 &= r3; \ - r2 = ~r2; \ - r0 ^= r4; \ - r4 |= r3; \ - r2 ^= r4; \ - } - -#define I5(i, r0, r1, r2, r3, r4) \ - { \ - r1 = ~r1; \ - r4 = r3; \ - r2 ^= r1; \ - r3 |= r0; \ - r3 ^= r2; \ - r2 |= r1; \ - r2 &= r0; \ - r4 ^= r3; \ - r2 ^= r4; \ - r4 |= r0; \ - r4 ^= r1; \ - r1 &= r2; \ - r1 ^= r3; \ - r4 ^= r2; \ - r3 &= r4; \ - r4 ^= r1; \ - r3 ^= r0; \ - r3 ^= r4; \ - r4 = ~r4; \ - } - -#define S6(i, r0, r1, r2, r3, r4) \ - { \ - r2 = ~r2; \ - r4 = r3; \ - r3 &= r0; \ - r0 ^= r4; \ - r3 ^= r2; \ - r2 |= r4; \ - r1 ^= r3; \ - r2 ^= r0; \ - r0 |= r1; \ - r2 ^= r1; \ - r4 ^= r0; \ - r0 |= r3; \ - r0 ^= r2; \ - r4 ^= r3; \ - r4 ^= r0; \ - r3 = ~r3; \ - r2 &= r4; \ - r2 ^= r3; \ - } - -#define I6(i, r0, r1, r2, r3, r4) \ - { \ - r0 ^= r2; \ - r4 = r2; \ - r2 &= r0; \ - r4 ^= r3; \ - r2 = ~r2; \ - r3 ^= r1; \ - r2 ^= r3; \ - r4 |= r0; \ - r0 ^= r2; \ - r3 ^= r4; \ - r4 ^= r1; \ - r1 &= r3; \ - r1 ^= r0; \ - r0 ^= r3; \ - r0 |= r2; \ - r3 ^= r1; \ - r4 ^= r0; \ - } - -#define S7(i, r0, r1, r2, r3, r4) \ - { \ - r4 = r2; \ - r2 &= r1; \ - r2 ^= r3; \ - r3 &= r1; \ - r4 ^= r2; \ - r2 ^= r1; \ - r1 ^= r0; \ - r0 |= r4; \ - r0 ^= r2; \ - r3 ^= r1; \ - r2 ^= r3; \ - r3 &= r0; \ - r3 ^= r4; \ - r4 ^= r2; \ - r2 &= r0; \ - r4 = ~r4; \ - r2 ^= r4; \ - r4 &= r0; \ - r1 ^= r3; \ - r4 ^= r1; \ - } - -#define I7(i, r0, r1, r2, r3, r4) \ - { \ - r4 = r2; \ - r2 ^= r0; \ - r0 &= r3; \ - r2 = ~r2; \ - r4 |= r3; \ - r3 ^= r1; \ - r1 |= r0; \ - r0 ^= r2; \ - r2 &= r4; \ - r1 ^= r2; \ - r2 ^= r0; \ - r0 |= r2; \ - r3 &= r4; \ - r0 ^= r3; \ - r4 ^= r1; \ - r3 ^= r4; \ - r4 |= r0; \ - r3 ^= r2; \ - r4 ^= r2; \ - } - -// key xor -#define KX(r, a, b, c, d, e) {\ - a ^= k[4 * r + 0]; \ - b ^= k[4 * r + 1]; \ - c ^= k[4 * r + 2]; \ - d ^= k[4 * r + 3];} - - -#ifdef TC_MINIMIZE_CODE_SIZE - -static void S0f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ - *r3 ^= *r0; - *r4 = *r1; - *r1 &= *r3; - *r4 ^= *r2; - *r1 ^= *r0; - *r0 |= *r3; - *r0 ^= *r4; - *r4 ^= *r3; - *r3 ^= *r2; - *r2 |= *r1; - *r2 ^= *r4; - *r4 = ~*r4; - *r4 |= *r1; - *r1 ^= *r3; - *r1 ^= *r4; - *r3 |= *r0; - *r1 ^= *r3; - *r4 ^= *r3; -} - -static void S1f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ - *r0 = ~*r0; - *r2 = ~*r2; - *r4 = *r0; - *r0 &= *r1; - *r2 ^= *r0; - *r0 |= *r3; - *r3 ^= *r2; - *r1 ^= *r0; - *r0 ^= *r4; - *r4 |= *r1; - *r1 ^= *r3; - *r2 |= *r0; - *r2 &= *r4; - *r0 ^= *r1; - *r1 &= *r2; - *r1 ^= *r0; - *r0 &= *r2; - *r0 ^= *r4; -} - -static void S2f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ - *r4 = *r0; - *r0 &= *r2; - *r0 ^= *r3; - *r2 ^= *r1; - *r2 ^= *r0; - *r3 |= *r4; - *r3 ^= *r1; - *r4 ^= *r2; - *r1 = *r3; - *r3 |= *r4; - *r3 ^= *r0; - *r0 &= *r1; - *r4 ^= *r0; - *r1 ^= *r3; - *r1 ^= *r4; - *r4 = ~*r4; -} - -static void S3f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ - *r4 = *r0; - *r0 |= *r3; - *r3 ^= *r1; - *r1 &= *r4; - *r4 ^= *r2; - *r2 ^= *r3; - *r3 &= *r0; - *r4 |= *r1; - *r3 ^= *r4; - *r0 ^= *r1; - *r4 &= *r0; - *r1 ^= *r3; - *r4 ^= *r2; - *r1 |= *r0; - *r1 ^= *r2; - *r0 ^= *r3; - *r2 = *r1; - *r1 |= *r3; - *r1 ^= *r0; -} - -static void S4f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ - *r1 ^= *r3; - *r3 = ~*r3; - *r2 ^= *r3; - *r3 ^= *r0; - *r4 = *r1; - *r1 &= *r3; - *r1 ^= *r2; - *r4 ^= *r3; - *r0 ^= *r4; - *r2 &= *r4; - *r2 ^= *r0; - *r0 &= *r1; - *r3 ^= *r0; - *r4 |= *r1; - *r4 ^= *r0; - *r0 |= *r3; - *r0 ^= *r2; - *r2 &= *r3; - *r0 = ~*r0; - *r4 ^= *r2; -} - -static void S5f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ - *r0 ^= *r1; - *r1 ^= *r3; - *r3 = ~*r3; - *r4 = *r1; - *r1 &= *r0; - *r2 ^= *r3; - *r1 ^= *r2; - *r2 |= *r4; - *r4 ^= *r3; - *r3 &= *r1; - *r3 ^= *r0; - *r4 ^= *r1; - *r4 ^= *r2; - *r2 ^= *r0; - *r0 &= *r3; - *r2 = ~*r2; - *r0 ^= *r4; - *r4 |= *r3; - *r2 ^= *r4; -} - -static void S6f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ - *r2 = ~*r2; - *r4 = *r3; - *r3 &= *r0; - *r0 ^= *r4; - *r3 ^= *r2; - *r2 |= *r4; - *r1 ^= *r3; - *r2 ^= *r0; - *r0 |= *r1; - *r2 ^= *r1; - *r4 ^= *r0; - *r0 |= *r3; - *r0 ^= *r2; - *r4 ^= *r3; - *r4 ^= *r0; - *r3 = ~*r3; - *r2 &= *r4; - *r2 ^= *r3; -} - -static void S7f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ - *r4 = *r2; - *r2 &= *r1; - *r2 ^= *r3; - *r3 &= *r1; - *r4 ^= *r2; - *r2 ^= *r1; - *r1 ^= *r0; - *r0 |= *r4; - *r0 ^= *r2; - *r3 ^= *r1; - *r2 ^= *r3; - *r3 &= *r0; - *r3 ^= *r4; - *r4 ^= *r2; - *r2 &= *r0; - *r4 = ~*r4; - *r2 ^= *r4; - *r4 &= *r0; - *r1 ^= *r3; - *r4 ^= *r1; -} - -static void KXf (const unsigned __int32 *k, unsigned int r, unsigned __int32 *a, unsigned __int32 *b, unsigned __int32 *c, unsigned __int32 *d) -{ - *a ^= k[r]; - *b ^= k[r + 1]; - *c ^= k[r + 2]; - *d ^= k[r + 3]; -} - -#endif // TC_MINIMIZE_CODE_SIZE - -#ifndef TC_MINIMIZE_CODE_SIZE - -void serpent_set_key(const unsigned __int8 userKey[],unsigned __int8 *ks) -{ - unsigned __int32 a,b,c,d,e; - unsigned __int32 *k = (unsigned __int32 *)ks; - unsigned __int32 t; - int i; - - for (i = 0; i < 8; i++) - k[i] = LE32(((unsigned __int32*)userKey)[i]); - - k += 8; - t = k[-1]; - for (i = 0; i < 132; ++i) - k[i] = t = rotlFixed(k[i-8] ^ k[i-5] ^ k[i-3] ^ t ^ 0x9e3779b9 ^ i, 11); - k -= 20; - -#define LK(r, a, b, c, d, e) {\ - a = k[(8-r)*4 + 0]; \ - b = k[(8-r)*4 + 1]; \ - c = k[(8-r)*4 + 2]; \ - d = k[(8-r)*4 + 3];} - -#define SK(r, a, b, c, d, e) {\ - k[(8-r)*4 + 4] = a; \ - k[(8-r)*4 + 5] = b; \ - k[(8-r)*4 + 6] = c; \ - k[(8-r)*4 + 7] = d;} \ - - for (i=0; i<4; i++) - { - afterS2(LK); afterS2(S3); afterS3(SK); - afterS1(LK); afterS1(S2); afterS2(SK); - afterS0(LK); afterS0(S1); afterS1(SK); - beforeS0(LK); beforeS0(S0); afterS0(SK); - k += 8*4; - afterS6(LK); afterS6(S7); afterS7(SK); - afterS5(LK); afterS5(S6); afterS6(SK); - afterS4(LK); afterS4(S5); afterS5(SK); - afterS3(LK); afterS3(S4); afterS4(SK); - } - afterS2(LK); afterS2(S3); afterS3(SK); -} - -#else // TC_MINIMIZE_CODE_SIZE - -static void LKf (unsigned __int32 *k, unsigned int r, unsigned __int32 *a, unsigned __int32 *b, unsigned __int32 *c, unsigned __int32 *d) -{ - *a = k[r]; - *b = k[r + 1]; - *c = k[r + 2]; - *d = k[r + 3]; -} - -static void SKf (unsigned __int32 *k, unsigned int r, unsigned __int32 *a, unsigned __int32 *b, unsigned __int32 *c, unsigned __int32 *d) -{ - k[r + 4] = *a; - k[r + 5] = *b; - k[r + 6] = *c; - k[r + 7] = *d; -} - -void serpent_set_key(const unsigned __int8 userKey[], unsigned __int8 *ks) -{ - unsigned __int32 a,b,c,d,e; - unsigned __int32 *k = (unsigned __int32 *)ks; - unsigned __int32 t; - int i; - - for (i = 0; i < 8; i++) - k[i] = LE32(((unsigned __int32*)userKey)[i]); - - k += 8; - t = k[-1]; - for (i = 0; i < 132; ++i) - k[i] = t = rotlFixed(k[i-8] ^ k[i-5] ^ k[i-3] ^ t ^ 0x9e3779b9 ^ i, 11); - k -= 20; - - for (i=0; i<4; i++) - { - LKf (k, 20, &a, &e, &b, &d); S3f (&a, &e, &b, &d, &c); SKf (k, 16, &e, &b, &d, &c); - LKf (k, 24, &c, &b, &a, &e); S2f (&c, &b, &a, &e, &d); SKf (k, 20, &a, &e, &b, &d); - LKf (k, 28, &b, &e, &c, &a); S1f (&b, &e, &c, &a, &d); SKf (k, 24, &c, &b, &a, &e); - LKf (k, 32, &a, &b, &c, &d); S0f (&a, &b, &c, &d, &e); SKf (k, 28, &b, &e, &c, &a); - k += 8*4; - LKf (k, 4, &a, &c, &d, &b); S7f (&a, &c, &d, &b, &e); SKf (k, 0, &d, &e, &b, &a); - LKf (k, 8, &a, &c, &b, &e); S6f (&a, &c, &b, &e, &d); SKf (k, 4, &a, &c, &d, &b); - LKf (k, 12, &b, &a, &e, &c); S5f (&b, &a, &e, &c, &d); SKf (k, 8, &a, &c, &b, &e); - LKf (k, 16, &e, &b, &d, &c); S4f (&e, &b, &d, &c, &a); SKf (k, 12, &b, &a, &e, &c); - } - LKf (k, 20, &a, &e, &b, &d); S3f (&a, &e, &b, &d, &c); SKf (k, 16, &e, &b, &d, &c); -} - -#endif // TC_MINIMIZE_CODE_SIZE - - -#ifndef TC_MINIMIZE_CODE_SIZE - -void serpent_encrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, unsigned __int8 *ks) -{ - unsigned __int32 a, b, c, d, e; - unsigned int i=1; - const unsigned __int32 *k = (unsigned __int32 *)ks + 8; - unsigned __int32 *in = (unsigned __int32 *) inBlock; - unsigned __int32 *out = (unsigned __int32 *) outBlock; - - a = LE32(in[0]); - b = LE32(in[1]); - c = LE32(in[2]); - d = LE32(in[3]); - - do - { - beforeS0(KX); beforeS0(S0); afterS0(LT); - afterS0(KX); afterS0(S1); afterS1(LT); - afterS1(KX); afterS1(S2); afterS2(LT); - afterS2(KX); afterS2(S3); afterS3(LT); - afterS3(KX); afterS3(S4); afterS4(LT); - afterS4(KX); afterS4(S5); afterS5(LT); - afterS5(KX); afterS5(S6); afterS6(LT); - afterS6(KX); afterS6(S7); - - if (i == 4) - break; - - ++i; - c = b; - b = e; - e = d; - d = a; - a = e; - k += 32; - beforeS0(LT); - } - while (1); - - afterS7(KX); - - out[0] = LE32(d); - out[1] = LE32(e); - out[2] = LE32(b); - out[3] = LE32(a); -} - -#else // TC_MINIMIZE_CODE_SIZE - -typedef unsigned __int32 uint32; - -static void LTf (uint32 *a, uint32 *b, uint32 *c, uint32 *d) -{ - *a = rotlFixed(*a, 13); - *c = rotlFixed(*c, 3); - *d = rotlFixed(*d ^ *c ^ (*a << 3), 7); - *b = rotlFixed(*b ^ *a ^ *c, 1); - *a = rotlFixed(*a ^ *b ^ *d, 5); - *c = rotlFixed(*c ^ *d ^ (*b << 7), 22); -} - -void serpent_encrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, unsigned __int8 *ks) -{ - unsigned __int32 a, b, c, d, e; - unsigned int i=1; - const unsigned __int32 *k = (unsigned __int32 *)ks + 8; - unsigned __int32 *in = (unsigned __int32 *) inBlock; - unsigned __int32 *out = (unsigned __int32 *) outBlock; - - a = LE32(in[0]); - b = LE32(in[1]); - c = LE32(in[2]); - d = LE32(in[3]); - - do - { - KXf (k, 0, &a, &b, &c, &d); S0f (&a, &b, &c, &d, &e); LTf (&b, &e, &c, &a); - KXf (k, 4, &b, &e, &c, &a); S1f (&b, &e, &c, &a, &d); LTf (&c, &b, &a, &e); - KXf (k, 8, &c, &b, &a, &e); S2f (&c, &b, &a, &e, &d); LTf (&a, &e, &b, &d); - KXf (k, 12, &a, &e, &b, &d); S3f (&a, &e, &b, &d, &c); LTf (&e, &b, &d, &c); - KXf (k, 16, &e, &b, &d, &c); S4f (&e, &b, &d, &c, &a); LTf (&b, &a, &e, &c); - KXf (k, 20, &b, &a, &e, &c); S5f (&b, &a, &e, &c, &d); LTf (&a, &c, &b, &e); - KXf (k, 24, &a, &c, &b, &e); S6f (&a, &c, &b, &e, &d); LTf (&a, &c, &d, &b); - KXf (k, 28, &a, &c, &d, &b); S7f (&a, &c, &d, &b, &e); - - if (i == 4) - break; - - ++i; - c = b; - b = e; - e = d; - d = a; - a = e; - k += 32; - LTf (&a,&b,&c,&d); - } - while (1); - - KXf (k, 32, &d, &e, &b, &a); - - out[0] = LE32(d); - out[1] = LE32(e); - out[2] = LE32(b); - out[3] = LE32(a); -} - -#endif // TC_MINIMIZE_CODE_SIZE - -#if !defined (TC_MINIMIZE_CODE_SIZE) - -void serpent_decrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, unsigned __int8 *ks) -{ - unsigned __int32 a, b, c, d, e; - const unsigned __int32 *k = (unsigned __int32 *)ks + 104; - unsigned int i=4; - unsigned __int32 *in = (unsigned __int32 *) inBlock; - unsigned __int32 *out = (unsigned __int32 *) outBlock; - - a = LE32(in[0]); - b = LE32(in[1]); - c = LE32(in[2]); - d = LE32(in[3]); - - beforeI7(KX); - goto start; - - do - { - c = b; - b = d; - d = e; - k -= 32; - beforeI7(ILT); -start: - beforeI7(I7); afterI7(KX); - afterI7(ILT); afterI7(I6); afterI6(KX); - afterI6(ILT); afterI6(I5); afterI5(KX); - afterI5(ILT); afterI5(I4); afterI4(KX); - afterI4(ILT); afterI4(I3); afterI3(KX); - afterI3(ILT); afterI3(I2); afterI2(KX); - afterI2(ILT); afterI2(I1); afterI1(KX); - afterI1(ILT); afterI1(I0); afterI0(KX); - } - while (--i != 0); - - out[0] = LE32(a); - out[1] = LE32(d); - out[2] = LE32(b); - out[3] = LE32(e); -} - -#else // TC_MINIMIZE_CODE_SIZE - -static void ILTf (uint32 *a, uint32 *b, uint32 *c, uint32 *d) -{ - *c = rotrFixed(*c, 22); - *a = rotrFixed(*a, 5); - *c ^= *d ^ (*b << 7); - *a ^= *b ^ *d; - *b = rotrFixed(*b, 1); - *d = rotrFixed(*d, 7) ^ *c ^ (*a << 3); - *b ^= *a ^ *c; - *c = rotrFixed(*c, 3); - *a = rotrFixed(*a, 13); -} - -void serpent_decrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, unsigned __int8 *ks) -{ - unsigned __int32 a, b, c, d, e; - const unsigned __int32 *k = (unsigned __int32 *)ks + 104; - unsigned int i=4; - unsigned __int32 *in = (unsigned __int32 *) inBlock; - unsigned __int32 *out = (unsigned __int32 *) outBlock; - - a = LE32(in[0]); - b = LE32(in[1]); - c = LE32(in[2]); - d = LE32(in[3]); - - KXf (k, 32, &a, &b, &c, &d); - goto start; - - do - { - c = b; - b = d; - d = e; - k -= 32; - beforeI7(ILT); -start: - beforeI7(I7); KXf (k, 28, &d, &a, &b, &e); - ILTf (&d, &a, &b, &e); afterI7(I6); KXf (k, 24, &a, &b, &c, &e); - ILTf (&a, &b, &c, &e); afterI6(I5); KXf (k, 20, &b, &d, &e, &c); - ILTf (&b, &d, &e, &c); afterI5(I4); KXf (k, 16, &b, &c, &e, &a); - ILTf (&b, &c, &e, &a); afterI4(I3); KXf (k, 12, &a, &b, &e, &c); - ILTf (&a, &b, &e, &c); afterI3(I2); KXf (k, 8, &b, &d, &e, &c); - ILTf (&b, &d, &e, &c); afterI2(I1); KXf (k, 4, &a, &b, &c, &e); - ILTf (&a, &b, &c, &e); afterI1(I0); KXf (k, 0, &a, &d, &b, &e); - } - while (--i != 0); - - out[0] = LE32(a); - out[1] = LE32(d); - out[2] = LE32(b); - out[3] = LE32(e); -} - -#endif // TC_MINIMIZE_CODE_SIZE +// serpent.cpp - written and placed in the public domain by Wei Dai + +/* Adapted for TrueCrypt */ +/* Adapted for VeraCrypt */ + +#ifdef TC_WINDOWS_BOOT +#pragma optimize ("t", on) +#endif + +#include "Serpent.h" +#include "Common/Endian.h" + +#include + +#if defined(_WIN32) && !defined(_DEBUG) +#include +#define rotlFixed _rotl +#define rotrFixed _rotr +#else +#define rotlFixed(x,n) (((x) << (n)) | ((x) >> (32 - (n)))) +#define rotrFixed(x,n) (((x) >> (n)) | ((x) << (32 - (n)))) +#endif + +// linear transformation +#define LT(i,a,b,c,d,e) {\ + a = rotlFixed(a, 13); \ + c = rotlFixed(c, 3); \ + d = rotlFixed(d ^ c ^ (a << 3), 7); \ + b = rotlFixed(b ^ a ^ c, 1); \ + a = rotlFixed(a ^ b ^ d, 5); \ + c = rotlFixed(c ^ d ^ (b << 7), 22);} + +// inverse linear transformation +#define ILT(i,a,b,c,d,e) {\ + c = rotrFixed(c, 22); \ + a = rotrFixed(a, 5); \ + c ^= d ^ (b << 7); \ + a ^= b ^ d; \ + b = rotrFixed(b, 1); \ + d = rotrFixed(d, 7) ^ c ^ (a << 3); \ + b ^= a ^ c; \ + c = rotrFixed(c, 3); \ + a = rotrFixed(a, 13);} + +// order of output from S-box functions +#define beforeS0(f) f(0,a,b,c,d,e) +#define afterS0(f) f(1,b,e,c,a,d) +#define afterS1(f) f(2,c,b,a,e,d) +#define afterS2(f) f(3,a,e,b,d,c) +#define afterS3(f) f(4,e,b,d,c,a) +#define afterS4(f) f(5,b,a,e,c,d) +#define afterS5(f) f(6,a,c,b,e,d) +#define afterS6(f) f(7,a,c,d,b,e) +#define afterS7(f) f(8,d,e,b,a,c) + +// order of output from inverse S-box functions +#define beforeI7(f) f(8,a,b,c,d,e) +#define afterI7(f) f(7,d,a,b,e,c) +#define afterI6(f) f(6,a,b,c,e,d) +#define afterI5(f) f(5,b,d,e,c,a) +#define afterI4(f) f(4,b,c,e,a,d) +#define afterI3(f) f(3,a,b,e,c,d) +#define afterI2(f) f(2,b,d,e,c,a) +#define afterI1(f) f(1,a,b,c,e,d) +#define afterI0(f) f(0,a,d,b,e,c) + +// The instruction sequences for the S-box functions +// come from Dag Arne Osvik's paper "Speeding up Serpent". + +#define S0(i, r0, r1, r2, r3, r4) \ + { \ + r3 ^= r0; \ + r4 = r1; \ + r1 &= r3; \ + r4 ^= r2; \ + r1 ^= r0; \ + r0 |= r3; \ + r0 ^= r4; \ + r4 ^= r3; \ + r3 ^= r2; \ + r2 |= r1; \ + r2 ^= r4; \ + r4 = ~r4; \ + r4 |= r1; \ + r1 ^= r3; \ + r1 ^= r4; \ + r3 |= r0; \ + r1 ^= r3; \ + r4 ^= r3; \ + } + +#define I0(i, r0, r1, r2, r3, r4) \ + { \ + r2 = ~r2; \ + r4 = r1; \ + r1 |= r0; \ + r4 = ~r4; \ + r1 ^= r2; \ + r2 |= r4; \ + r1 ^= r3; \ + r0 ^= r4; \ + r2 ^= r0; \ + r0 &= r3; \ + r4 ^= r0; \ + r0 |= r1; \ + r0 ^= r2; \ + r3 ^= r4; \ + r2 ^= r1; \ + r3 ^= r0; \ + r3 ^= r1; \ + r2 &= r3; \ + r4 ^= r2; \ + } + +#define S1(i, r0, r1, r2, r3, r4) \ + { \ + r0 = ~r0; \ + r2 = ~r2; \ + r4 = r0; \ + r0 &= r1; \ + r2 ^= r0; \ + r0 |= r3; \ + r3 ^= r2; \ + r1 ^= r0; \ + r0 ^= r4; \ + r4 |= r1; \ + r1 ^= r3; \ + r2 |= r0; \ + r2 &= r4; \ + r0 ^= r1; \ + r1 &= r2; \ + r1 ^= r0; \ + r0 &= r2; \ + r0 ^= r4; \ + } + +#define I1(i, r0, r1, r2, r3, r4) \ + { \ + r4 = r1; \ + r1 ^= r3; \ + r3 &= r1; \ + r4 ^= r2; \ + r3 ^= r0; \ + r0 |= r1; \ + r2 ^= r3; \ + r0 ^= r4; \ + r0 |= r2; \ + r1 ^= r3; \ + r0 ^= r1; \ + r1 |= r3; \ + r1 ^= r0; \ + r4 = ~r4; \ + r4 ^= r1; \ + r1 |= r0; \ + r1 ^= r0; \ + r1 |= r4; \ + r3 ^= r1; \ + } + +#define S2(i, r0, r1, r2, r3, r4) \ + { \ + r4 = r0; \ + r0 &= r2; \ + r0 ^= r3; \ + r2 ^= r1; \ + r2 ^= r0; \ + r3 |= r4; \ + r3 ^= r1; \ + r4 ^= r2; \ + r1 = r3; \ + r3 |= r4; \ + r3 ^= r0; \ + r0 &= r1; \ + r4 ^= r0; \ + r1 ^= r3; \ + r1 ^= r4; \ + r4 = ~r4; \ + } + +#define I2(i, r0, r1, r2, r3, r4) \ + { \ + r2 ^= r3; \ + r3 ^= r0; \ + r4 = r3; \ + r3 &= r2; \ + r3 ^= r1; \ + r1 |= r2; \ + r1 ^= r4; \ + r4 &= r3; \ + r2 ^= r3; \ + r4 &= r0; \ + r4 ^= r2; \ + r2 &= r1; \ + r2 |= r0; \ + r3 = ~r3; \ + r2 ^= r3; \ + r0 ^= r3; \ + r0 &= r1; \ + r3 ^= r4; \ + r3 ^= r0; \ + } + +#define S3(i, r0, r1, r2, r3, r4) \ + { \ + r4 = r0; \ + r0 |= r3; \ + r3 ^= r1; \ + r1 &= r4; \ + r4 ^= r2; \ + r2 ^= r3; \ + r3 &= r0; \ + r4 |= r1; \ + r3 ^= r4; \ + r0 ^= r1; \ + r4 &= r0; \ + r1 ^= r3; \ + r4 ^= r2; \ + r1 |= r0; \ + r1 ^= r2; \ + r0 ^= r3; \ + r2 = r1; \ + r1 |= r3; \ + r1 ^= r0; \ + } + +#define I3(i, r0, r1, r2, r3, r4) \ + { \ + r4 = r2; \ + r2 ^= r1; \ + r1 &= r2; \ + r1 ^= r0; \ + r0 &= r4; \ + r4 ^= r3; \ + r3 |= r1; \ + r3 ^= r2; \ + r0 ^= r4; \ + r2 ^= r0; \ + r0 |= r3; \ + r0 ^= r1; \ + r4 ^= r2; \ + r2 &= r3; \ + r1 |= r3; \ + r1 ^= r2; \ + r4 ^= r0; \ + r2 ^= r4; \ + } + +#define S4(i, r0, r1, r2, r3, r4) \ + { \ + r1 ^= r3; \ + r3 = ~r3; \ + r2 ^= r3; \ + r3 ^= r0; \ + r4 = r1; \ + r1 &= r3; \ + r1 ^= r2; \ + r4 ^= r3; \ + r0 ^= r4; \ + r2 &= r4; \ + r2 ^= r0; \ + r0 &= r1; \ + r3 ^= r0; \ + r4 |= r1; \ + r4 ^= r0; \ + r0 |= r3; \ + r0 ^= r2; \ + r2 &= r3; \ + r0 = ~r0; \ + r4 ^= r2; \ + } + +#define I4(i, r0, r1, r2, r3, r4) \ + { \ + r4 = r2; \ + r2 &= r3; \ + r2 ^= r1; \ + r1 |= r3; \ + r1 &= r0; \ + r4 ^= r2; \ + r4 ^= r1; \ + r1 &= r2; \ + r0 = ~r0; \ + r3 ^= r4; \ + r1 ^= r3; \ + r3 &= r0; \ + r3 ^= r2; \ + r0 ^= r1; \ + r2 &= r0; \ + r3 ^= r0; \ + r2 ^= r4; \ + r2 |= r3; \ + r3 ^= r0; \ + r2 ^= r1; \ + } + +#define S5(i, r0, r1, r2, r3, r4) \ + { \ + r0 ^= r1; \ + r1 ^= r3; \ + r3 = ~r3; \ + r4 = r1; \ + r1 &= r0; \ + r2 ^= r3; \ + r1 ^= r2; \ + r2 |= r4; \ + r4 ^= r3; \ + r3 &= r1; \ + r3 ^= r0; \ + r4 ^= r1; \ + r4 ^= r2; \ + r2 ^= r0; \ + r0 &= r3; \ + r2 = ~r2; \ + r0 ^= r4; \ + r4 |= r3; \ + r2 ^= r4; \ + } + +#define I5(i, r0, r1, r2, r3, r4) \ + { \ + r1 = ~r1; \ + r4 = r3; \ + r2 ^= r1; \ + r3 |= r0; \ + r3 ^= r2; \ + r2 |= r1; \ + r2 &= r0; \ + r4 ^= r3; \ + r2 ^= r4; \ + r4 |= r0; \ + r4 ^= r1; \ + r1 &= r2; \ + r1 ^= r3; \ + r4 ^= r2; \ + r3 &= r4; \ + r4 ^= r1; \ + r3 ^= r0; \ + r3 ^= r4; \ + r4 = ~r4; \ + } + +#define S6(i, r0, r1, r2, r3, r4) \ + { \ + r2 = ~r2; \ + r4 = r3; \ + r3 &= r0; \ + r0 ^= r4; \ + r3 ^= r2; \ + r2 |= r4; \ + r1 ^= r3; \ + r2 ^= r0; \ + r0 |= r1; \ + r2 ^= r1; \ + r4 ^= r0; \ + r0 |= r3; \ + r0 ^= r2; \ + r4 ^= r3; \ + r4 ^= r0; \ + r3 = ~r3; \ + r2 &= r4; \ + r2 ^= r3; \ + } + +#define I6(i, r0, r1, r2, r3, r4) \ + { \ + r0 ^= r2; \ + r4 = r2; \ + r2 &= r0; \ + r4 ^= r3; \ + r2 = ~r2; \ + r3 ^= r1; \ + r2 ^= r3; \ + r4 |= r0; \ + r0 ^= r2; \ + r3 ^= r4; \ + r4 ^= r1; \ + r1 &= r3; \ + r1 ^= r0; \ + r0 ^= r3; \ + r0 |= r2; \ + r3 ^= r1; \ + r4 ^= r0; \ + } + +#define S7(i, r0, r1, r2, r3, r4) \ + { \ + r4 = r2; \ + r2 &= r1; \ + r2 ^= r3; \ + r3 &= r1; \ + r4 ^= r2; \ + r2 ^= r1; \ + r1 ^= r0; \ + r0 |= r4; \ + r0 ^= r2; \ + r3 ^= r1; \ + r2 ^= r3; \ + r3 &= r0; \ + r3 ^= r4; \ + r4 ^= r2; \ + r2 &= r0; \ + r4 = ~r4; \ + r2 ^= r4; \ + r4 &= r0; \ + r1 ^= r3; \ + r4 ^= r1; \ + } + +#define I7(i, r0, r1, r2, r3, r4) \ + { \ + r4 = r2; \ + r2 ^= r0; \ + r0 &= r3; \ + r2 = ~r2; \ + r4 |= r3; \ + r3 ^= r1; \ + r1 |= r0; \ + r0 ^= r2; \ + r2 &= r4; \ + r1 ^= r2; \ + r2 ^= r0; \ + r0 |= r2; \ + r3 &= r4; \ + r0 ^= r3; \ + r4 ^= r1; \ + r3 ^= r4; \ + r4 |= r0; \ + r3 ^= r2; \ + r4 ^= r2; \ + } + +// key xor +#define KX(r, a, b, c, d, e) {\ + a ^= k[4 * r + 0]; \ + b ^= k[4 * r + 1]; \ + c ^= k[4 * r + 2]; \ + d ^= k[4 * r + 3];} + + +#ifdef TC_MINIMIZE_CODE_SIZE + +static void S0f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) +{ + *r3 ^= *r0; + *r4 = *r1; + *r1 &= *r3; + *r4 ^= *r2; + *r1 ^= *r0; + *r0 |= *r3; + *r0 ^= *r4; + *r4 ^= *r3; + *r3 ^= *r2; + *r2 |= *r1; + *r2 ^= *r4; + *r4 = ~*r4; + *r4 |= *r1; + *r1 ^= *r3; + *r1 ^= *r4; + *r3 |= *r0; + *r1 ^= *r3; + *r4 ^= *r3; +} + +static void S1f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) +{ + *r0 = ~*r0; + *r2 = ~*r2; + *r4 = *r0; + *r0 &= *r1; + *r2 ^= *r0; + *r0 |= *r3; + *r3 ^= *r2; + *r1 ^= *r0; + *r0 ^= *r4; + *r4 |= *r1; + *r1 ^= *r3; + *r2 |= *r0; + *r2 &= *r4; + *r0 ^= *r1; + *r1 &= *r2; + *r1 ^= *r0; + *r0 &= *r2; + *r0 ^= *r4; +} + +static void S2f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) +{ + *r4 = *r0; + *r0 &= *r2; + *r0 ^= *r3; + *r2 ^= *r1; + *r2 ^= *r0; + *r3 |= *r4; + *r3 ^= *r1; + *r4 ^= *r2; + *r1 = *r3; + *r3 |= *r4; + *r3 ^= *r0; + *r0 &= *r1; + *r4 ^= *r0; + *r1 ^= *r3; + *r1 ^= *r4; + *r4 = ~*r4; +} + +static void S3f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) +{ + *r4 = *r0; + *r0 |= *r3; + *r3 ^= *r1; + *r1 &= *r4; + *r4 ^= *r2; + *r2 ^= *r3; + *r3 &= *r0; + *r4 |= *r1; + *r3 ^= *r4; + *r0 ^= *r1; + *r4 &= *r0; + *r1 ^= *r3; + *r4 ^= *r2; + *r1 |= *r0; + *r1 ^= *r2; + *r0 ^= *r3; + *r2 = *r1; + *r1 |= *r3; + *r1 ^= *r0; +} + +static void S4f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) +{ + *r1 ^= *r3; + *r3 = ~*r3; + *r2 ^= *r3; + *r3 ^= *r0; + *r4 = *r1; + *r1 &= *r3; + *r1 ^= *r2; + *r4 ^= *r3; + *r0 ^= *r4; + *r2 &= *r4; + *r2 ^= *r0; + *r0 &= *r1; + *r3 ^= *r0; + *r4 |= *r1; + *r4 ^= *r0; + *r0 |= *r3; + *r0 ^= *r2; + *r2 &= *r3; + *r0 = ~*r0; + *r4 ^= *r2; +} + +static void S5f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) +{ + *r0 ^= *r1; + *r1 ^= *r3; + *r3 = ~*r3; + *r4 = *r1; + *r1 &= *r0; + *r2 ^= *r3; + *r1 ^= *r2; + *r2 |= *r4; + *r4 ^= *r3; + *r3 &= *r1; + *r3 ^= *r0; + *r4 ^= *r1; + *r4 ^= *r2; + *r2 ^= *r0; + *r0 &= *r3; + *r2 = ~*r2; + *r0 ^= *r4; + *r4 |= *r3; + *r2 ^= *r4; +} + +static void S6f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) +{ + *r2 = ~*r2; + *r4 = *r3; + *r3 &= *r0; + *r0 ^= *r4; + *r3 ^= *r2; + *r2 |= *r4; + *r1 ^= *r3; + *r2 ^= *r0; + *r0 |= *r1; + *r2 ^= *r1; + *r4 ^= *r0; + *r0 |= *r3; + *r0 ^= *r2; + *r4 ^= *r3; + *r4 ^= *r0; + *r3 = ~*r3; + *r2 &= *r4; + *r2 ^= *r3; +} + +static void S7f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) +{ + *r4 = *r2; + *r2 &= *r1; + *r2 ^= *r3; + *r3 &= *r1; + *r4 ^= *r2; + *r2 ^= *r1; + *r1 ^= *r0; + *r0 |= *r4; + *r0 ^= *r2; + *r3 ^= *r1; + *r2 ^= *r3; + *r3 &= *r0; + *r3 ^= *r4; + *r4 ^= *r2; + *r2 &= *r0; + *r4 = ~*r4; + *r2 ^= *r4; + *r4 &= *r0; + *r1 ^= *r3; + *r4 ^= *r1; +} + +static void KXf (const unsigned __int32 *k, unsigned int r, unsigned __int32 *a, unsigned __int32 *b, unsigned __int32 *c, unsigned __int32 *d) +{ + *a ^= k[r]; + *b ^= k[r + 1]; + *c ^= k[r + 2]; + *d ^= k[r + 3]; +} + +#endif // TC_MINIMIZE_CODE_SIZE + +#ifndef TC_MINIMIZE_CODE_SIZE + +void serpent_set_key(const unsigned __int8 userKey[],unsigned __int8 *ks) +{ + unsigned __int32 a,b,c,d,e; + unsigned __int32 *k = (unsigned __int32 *)ks; + unsigned __int32 t; + int i; + + for (i = 0; i < 8; i++) + k[i] = LE32(((unsigned __int32*)userKey)[i]); + + k += 8; + t = k[-1]; + for (i = 0; i < 132; ++i) + k[i] = t = rotlFixed(k[i-8] ^ k[i-5] ^ k[i-3] ^ t ^ 0x9e3779b9 ^ i, 11); + k -= 20; + +#define LK(r, a, b, c, d, e) {\ + a = k[(8-r)*4 + 0]; \ + b = k[(8-r)*4 + 1]; \ + c = k[(8-r)*4 + 2]; \ + d = k[(8-r)*4 + 3];} + +#define SK(r, a, b, c, d, e) {\ + k[(8-r)*4 + 4] = a; \ + k[(8-r)*4 + 5] = b; \ + k[(8-r)*4 + 6] = c; \ + k[(8-r)*4 + 7] = d;} \ + + for (i=0; i<4; i++) + { + afterS2(LK); afterS2(S3); afterS3(SK); + afterS1(LK); afterS1(S2); afterS2(SK); + afterS0(LK); afterS0(S1); afterS1(SK); + beforeS0(LK); beforeS0(S0); afterS0(SK); + k += 8*4; + afterS6(LK); afterS6(S7); afterS7(SK); + afterS5(LK); afterS5(S6); afterS6(SK); + afterS4(LK); afterS4(S5); afterS5(SK); + afterS3(LK); afterS3(S4); afterS4(SK); + } + afterS2(LK); afterS2(S3); afterS3(SK); +} + +#else // TC_MINIMIZE_CODE_SIZE + +static void LKf (unsigned __int32 *k, unsigned int r, unsigned __int32 *a, unsigned __int32 *b, unsigned __int32 *c, unsigned __int32 *d) +{ + *a = k[r]; + *b = k[r + 1]; + *c = k[r + 2]; + *d = k[r + 3]; +} + +static void SKf (unsigned __int32 *k, unsigned int r, unsigned __int32 *a, unsigned __int32 *b, unsigned __int32 *c, unsigned __int32 *d) +{ + k[r + 4] = *a; + k[r + 5] = *b; + k[r + 6] = *c; + k[r + 7] = *d; +} + +void serpent_set_key(const unsigned __int8 userKey[], unsigned __int8 *ks) +{ + unsigned __int32 a,b,c,d,e; + unsigned __int32 *k = (unsigned __int32 *)ks; + unsigned __int32 t; + int i; + + for (i = 0; i < 8; i++) + k[i] = LE32(((unsigned __int32*)userKey)[i]); + + k += 8; + t = k[-1]; + for (i = 0; i < 132; ++i) + k[i] = t = rotlFixed(k[i-8] ^ k[i-5] ^ k[i-3] ^ t ^ 0x9e3779b9 ^ i, 11); + k -= 20; + + for (i=0; i<4; i++) + { + LKf (k, 20, &a, &e, &b, &d); S3f (&a, &e, &b, &d, &c); SKf (k, 16, &e, &b, &d, &c); + LKf (k, 24, &c, &b, &a, &e); S2f (&c, &b, &a, &e, &d); SKf (k, 20, &a, &e, &b, &d); + LKf (k, 28, &b, &e, &c, &a); S1f (&b, &e, &c, &a, &d); SKf (k, 24, &c, &b, &a, &e); + LKf (k, 32, &a, &b, &c, &d); S0f (&a, &b, &c, &d, &e); SKf (k, 28, &b, &e, &c, &a); + k += 8*4; + LKf (k, 4, &a, &c, &d, &b); S7f (&a, &c, &d, &b, &e); SKf (k, 0, &d, &e, &b, &a); + LKf (k, 8, &a, &c, &b, &e); S6f (&a, &c, &b, &e, &d); SKf (k, 4, &a, &c, &d, &b); + LKf (k, 12, &b, &a, &e, &c); S5f (&b, &a, &e, &c, &d); SKf (k, 8, &a, &c, &b, &e); + LKf (k, 16, &e, &b, &d, &c); S4f (&e, &b, &d, &c, &a); SKf (k, 12, &b, &a, &e, &c); + } + LKf (k, 20, &a, &e, &b, &d); S3f (&a, &e, &b, &d, &c); SKf (k, 16, &e, &b, &d, &c); +} + +#endif // TC_MINIMIZE_CODE_SIZE + + +#ifndef TC_MINIMIZE_CODE_SIZE + +void serpent_encrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, unsigned __int8 *ks) +{ + unsigned __int32 a, b, c, d, e; + unsigned int i=1; + const unsigned __int32 *k = (unsigned __int32 *)ks + 8; + unsigned __int32 *in = (unsigned __int32 *) inBlock; + unsigned __int32 *out = (unsigned __int32 *) outBlock; + + a = LE32(in[0]); + b = LE32(in[1]); + c = LE32(in[2]); + d = LE32(in[3]); + + do + { + beforeS0(KX); beforeS0(S0); afterS0(LT); + afterS0(KX); afterS0(S1); afterS1(LT); + afterS1(KX); afterS1(S2); afterS2(LT); + afterS2(KX); afterS2(S3); afterS3(LT); + afterS3(KX); afterS3(S4); afterS4(LT); + afterS4(KX); afterS4(S5); afterS5(LT); + afterS5(KX); afterS5(S6); afterS6(LT); + afterS6(KX); afterS6(S7); + + if (i == 4) + break; + + ++i; + c = b; + b = e; + e = d; + d = a; + a = e; + k += 32; + beforeS0(LT); + } + while (1); + + afterS7(KX); + + out[0] = LE32(d); + out[1] = LE32(e); + out[2] = LE32(b); + out[3] = LE32(a); +} + +#else // TC_MINIMIZE_CODE_SIZE + +typedef unsigned __int32 uint32; + +static void LTf (uint32 *a, uint32 *b, uint32 *c, uint32 *d) +{ + *a = rotlFixed(*a, 13); + *c = rotlFixed(*c, 3); + *d = rotlFixed(*d ^ *c ^ (*a << 3), 7); + *b = rotlFixed(*b ^ *a ^ *c, 1); + *a = rotlFixed(*a ^ *b ^ *d, 5); + *c = rotlFixed(*c ^ *d ^ (*b << 7), 22); +} + +void serpent_encrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, unsigned __int8 *ks) +{ + unsigned __int32 a, b, c, d, e; + unsigned int i=1; + const unsigned __int32 *k = (unsigned __int32 *)ks + 8; + unsigned __int32 *in = (unsigned __int32 *) inBlock; + unsigned __int32 *out = (unsigned __int32 *) outBlock; + + a = LE32(in[0]); + b = LE32(in[1]); + c = LE32(in[2]); + d = LE32(in[3]); + + do + { + KXf (k, 0, &a, &b, &c, &d); S0f (&a, &b, &c, &d, &e); LTf (&b, &e, &c, &a); + KXf (k, 4, &b, &e, &c, &a); S1f (&b, &e, &c, &a, &d); LTf (&c, &b, &a, &e); + KXf (k, 8, &c, &b, &a, &e); S2f (&c, &b, &a, &e, &d); LTf (&a, &e, &b, &d); + KXf (k, 12, &a, &e, &b, &d); S3f (&a, &e, &b, &d, &c); LTf (&e, &b, &d, &c); + KXf (k, 16, &e, &b, &d, &c); S4f (&e, &b, &d, &c, &a); LTf (&b, &a, &e, &c); + KXf (k, 20, &b, &a, &e, &c); S5f (&b, &a, &e, &c, &d); LTf (&a, &c, &b, &e); + KXf (k, 24, &a, &c, &b, &e); S6f (&a, &c, &b, &e, &d); LTf (&a, &c, &d, &b); + KXf (k, 28, &a, &c, &d, &b); S7f (&a, &c, &d, &b, &e); + + if (i == 4) + break; + + ++i; + c = b; + b = e; + e = d; + d = a; + a = e; + k += 32; + LTf (&a,&b,&c,&d); + } + while (1); + + KXf (k, 32, &d, &e, &b, &a); + + out[0] = LE32(d); + out[1] = LE32(e); + out[2] = LE32(b); + out[3] = LE32(a); +} + +#endif // TC_MINIMIZE_CODE_SIZE + +#if !defined (TC_MINIMIZE_CODE_SIZE) + +void serpent_decrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, unsigned __int8 *ks) +{ + unsigned __int32 a, b, c, d, e; + const unsigned __int32 *k = (unsigned __int32 *)ks + 104; + unsigned int i=4; + unsigned __int32 *in = (unsigned __int32 *) inBlock; + unsigned __int32 *out = (unsigned __int32 *) outBlock; + + a = LE32(in[0]); + b = LE32(in[1]); + c = LE32(in[2]); + d = LE32(in[3]); + + beforeI7(KX); + goto start; + + do + { + c = b; + b = d; + d = e; + k -= 32; + beforeI7(ILT); +start: + beforeI7(I7); afterI7(KX); + afterI7(ILT); afterI7(I6); afterI6(KX); + afterI6(ILT); afterI6(I5); afterI5(KX); + afterI5(ILT); afterI5(I4); afterI4(KX); + afterI4(ILT); afterI4(I3); afterI3(KX); + afterI3(ILT); afterI3(I2); afterI2(KX); + afterI2(ILT); afterI2(I1); afterI1(KX); + afterI1(ILT); afterI1(I0); afterI0(KX); + } + while (--i != 0); + + out[0] = LE32(a); + out[1] = LE32(d); + out[2] = LE32(b); + out[3] = LE32(e); +} + +#else // TC_MINIMIZE_CODE_SIZE + +static void ILTf (uint32 *a, uint32 *b, uint32 *c, uint32 *d) +{ + *c = rotrFixed(*c, 22); + *a = rotrFixed(*a, 5); + *c ^= *d ^ (*b << 7); + *a ^= *b ^ *d; + *b = rotrFixed(*b, 1); + *d = rotrFixed(*d, 7) ^ *c ^ (*a << 3); + *b ^= *a ^ *c; + *c = rotrFixed(*c, 3); + *a = rotrFixed(*a, 13); +} + +void serpent_decrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, unsigned __int8 *ks) +{ + unsigned __int32 a, b, c, d, e; + const unsigned __int32 *k = (unsigned __int32 *)ks + 104; + unsigned int i=4; + unsigned __int32 *in = (unsigned __int32 *) inBlock; + unsigned __int32 *out = (unsigned __int32 *) outBlock; + + a = LE32(in[0]); + b = LE32(in[1]); + c = LE32(in[2]); + d = LE32(in[3]); + + KXf (k, 32, &a, &b, &c, &d); + goto start; + + do + { + c = b; + b = d; + d = e; + k -= 32; + beforeI7(ILT); +start: + beforeI7(I7); KXf (k, 28, &d, &a, &b, &e); + ILTf (&d, &a, &b, &e); afterI7(I6); KXf (k, 24, &a, &b, &c, &e); + ILTf (&a, &b, &c, &e); afterI6(I5); KXf (k, 20, &b, &d, &e, &c); + ILTf (&b, &d, &e, &c); afterI5(I4); KXf (k, 16, &b, &c, &e, &a); + ILTf (&b, &c, &e, &a); afterI4(I3); KXf (k, 12, &a, &b, &e, &c); + ILTf (&a, &b, &e, &c); afterI3(I2); KXf (k, 8, &b, &d, &e, &c); + ILTf (&b, &d, &e, &c); afterI2(I1); KXf (k, 4, &a, &b, &c, &e); + ILTf (&a, &b, &c, &e); afterI1(I0); KXf (k, 0, &a, &d, &b, &e); + } + while (--i != 0); + + out[0] = LE32(a); + out[1] = LE32(d); + out[2] = LE32(b); + out[3] = LE32(e); +} + +#endif // TC_MINIMIZE_CODE_SIZE diff --git a/src/Crypto/Serpent.h b/src/Crypto/Serpent.h index b88ddc4d..0f4ab787 100644 --- a/src/Crypto/Serpent.h +++ b/src/Crypto/Serpent.h @@ -1,20 +1,20 @@ -#ifndef HEADER_Crypto_Serpent -#define HEADER_Crypto_Serpent - -#include "Common/Tcdefs.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -/* userKey is always 32-bytes long */ -void serpent_set_key(const unsigned __int8 userKey[], unsigned __int8 *ks); -void serpent_encrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, unsigned __int8 *ks); -void serpent_decrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, unsigned __int8 *ks); - -#ifdef __cplusplus -} -#endif - -#endif // HEADER_Crypto_Serpent +#ifndef HEADER_Crypto_Serpent +#define HEADER_Crypto_Serpent + +#include "Common/Tcdefs.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* userKey is always 32-bytes long */ +void serpent_set_key(const unsigned __int8 userKey[], unsigned __int8 *ks); +void serpent_encrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, unsigned __int8 *ks); +void serpent_decrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, unsigned __int8 *ks); + +#ifdef __cplusplus +} +#endif + +#endif // HEADER_Crypto_Serpent diff --git a/src/Crypto/Sha2.c b/src/Crypto/Sha2.c index f1a9850a..02680eb5 100644 --- a/src/Crypto/Sha2.c +++ b/src/Crypto/Sha2.c @@ -1,753 +1,753 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 2002, Dr Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software is allowed (with or without - changes) provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue Date: 01/08/2005 - - This is a byte oriented version of SHA2 that operates on arrays of bytes - stored in memory. This code implements sha256, sha384 and sha512 but the - latter two functions rely on efficient 64-bit integer operations that - may not be very efficient on 32-bit machines - - The sha256 functions use a type 'sha256_ctx' to hold details of the - current hash state and uses the following three calls: - - void sha256_begin(sha256_ctx ctx[1]) - void sha256_hash(const unsigned char data[], - unsigned long len, sha256_ctx ctx[1]) - void sha_end1(unsigned char hval[], sha256_ctx ctx[1]) - - The first subroutine initialises a hash computation by setting up the - context in the sha256_ctx context. The second subroutine hashes 8-bit - bytes from array data[] into the hash state withinh sha256_ctx context, - the number of bytes to be hashed being given by the the unsigned long - integer len. The third subroutine completes the hash calculation and - places the resulting digest value in the array of 8-bit bytes hval[]. - - The sha384 and sha512 functions are similar and use the interfaces: - - void sha384_begin(sha384_ctx ctx[1]); - void sha384_hash(const unsigned char data[], - unsigned long len, sha384_ctx ctx[1]); - void sha384_end(unsigned char hval[], sha384_ctx ctx[1]); - - void sha512_begin(sha512_ctx ctx[1]); - void sha512_hash(const unsigned char data[], - unsigned long len, sha512_ctx ctx[1]); - void sha512_end(unsigned char hval[], sha512_ctx ctx[1]); - - In addition there is a function sha2 that can be used to call all these - functions using a call with a hash length parameter as follows: - - int sha2_begin(unsigned long len, sha2_ctx ctx[1]); - void sha2_hash(const unsigned char data[], - unsigned long len, sha2_ctx ctx[1]); - void sha2_end(unsigned char hval[], sha2_ctx ctx[1]); - - My thanks to Erik Andersen for testing this code - on big-endian systems and for his assistance with corrections -*/ - -#include "Common/Endian.h" -#include "Crypto/misc.h" -#define PLATFORM_BYTE_ORDER BYTE_ORDER -#define IS_LITTLE_ENDIAN LITTLE_ENDIAN - -#if 0 -#define UNROLL_SHA2 /* for SHA2 loop unroll */ -#endif - -#include /* for memcpy() etc. */ - -#include "Sha2.h" - -#if defined(__cplusplus) -extern "C" -{ -#endif - -#if defined( _MSC_VER ) && ( _MSC_VER > 800 ) -#pragma intrinsic(memcpy) -#endif - -#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN) -#define SWAP_BYTES -#else -#undef SWAP_BYTES -#endif - -#if 0 - -#define ch(x,y,z) (((x) & (y)) ^ (~(x) & (z))) -#define maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) - -#else /* Thanks to Rich Schroeppel and Colin Plumb for the following */ - -#define ch(x,y,z) ((z) ^ ((x) & ((y) ^ (z)))) -#define maj(x,y,z) (((x) & (y)) | ((z) & ((x) ^ (y)))) - -#endif - -/* round transforms for SHA256 and SHA512 compression functions */ - -#define vf(n,i) v[(n - i) & 7] - -#define hf(i) (p[i & 15] += \ - g_1(p[(i + 14) & 15]) + p[(i + 9) & 15] + g_0(p[(i + 1) & 15])) - -#define v_cycle(i,j) \ - vf(7,i) += (j ? hf(i) : p[i]) + k_0[i+j] \ - + s_1(vf(4,i)) + ch(vf(4,i),vf(5,i),vf(6,i)); \ - vf(3,i) += vf(7,i); \ - vf(7,i) += s_0(vf(0,i))+ maj(vf(0,i),vf(1,i),vf(2,i)) - -#if defined(SHA_224) || defined(SHA_256) - -#define SHA256_MASK (SHA256_BLOCK_SIZE - 1) - -#if defined(SWAP_BYTES) -#define bsw_32(p,n) \ - { int _i = (n); while(_i--) ((uint_32t*)p)[_i] = bswap_32(((uint_32t*)p)[_i]); } -#else -#define bsw_32(p,n) -#endif - -#define s_0(x) (rotr32((x), 2) ^ rotr32((x), 13) ^ rotr32((x), 22)) -#define s_1(x) (rotr32((x), 6) ^ rotr32((x), 11) ^ rotr32((x), 25)) -#define g_0(x) (rotr32((x), 7) ^ rotr32((x), 18) ^ ((x) >> 3)) -#define g_1(x) (rotr32((x), 17) ^ rotr32((x), 19) ^ ((x) >> 10)) -#define k_0 k256 - -/* rotated SHA256 round definition. Rather than swapping variables as in */ -/* FIPS-180, different variables are 'rotated' on each round, returning */ -/* to their starting positions every eight rounds */ - -#define q(n) v##n - -#define one_cycle(a,b,c,d,e,f,g,h,k,w) \ - q(h) += s_1(q(e)) + ch(q(e), q(f), q(g)) + k + w; \ - q(d) += q(h); q(h) += s_0(q(a)) + maj(q(a), q(b), q(c)) - -/* SHA256 mixing data */ - -const uint_32t k256[64] = -{ 0x428a2f98ul, 0x71374491ul, 0xb5c0fbcful, 0xe9b5dba5ul, - 0x3956c25bul, 0x59f111f1ul, 0x923f82a4ul, 0xab1c5ed5ul, - 0xd807aa98ul, 0x12835b01ul, 0x243185beul, 0x550c7dc3ul, - 0x72be5d74ul, 0x80deb1feul, 0x9bdc06a7ul, 0xc19bf174ul, - 0xe49b69c1ul, 0xefbe4786ul, 0x0fc19dc6ul, 0x240ca1ccul, - 0x2de92c6ful, 0x4a7484aaul, 0x5cb0a9dcul, 0x76f988daul, - 0x983e5152ul, 0xa831c66dul, 0xb00327c8ul, 0xbf597fc7ul, - 0xc6e00bf3ul, 0xd5a79147ul, 0x06ca6351ul, 0x14292967ul, - 0x27b70a85ul, 0x2e1b2138ul, 0x4d2c6dfcul, 0x53380d13ul, - 0x650a7354ul, 0x766a0abbul, 0x81c2c92eul, 0x92722c85ul, - 0xa2bfe8a1ul, 0xa81a664bul, 0xc24b8b70ul, 0xc76c51a3ul, - 0xd192e819ul, 0xd6990624ul, 0xf40e3585ul, 0x106aa070ul, - 0x19a4c116ul, 0x1e376c08ul, 0x2748774cul, 0x34b0bcb5ul, - 0x391c0cb3ul, 0x4ed8aa4aul, 0x5b9cca4ful, 0x682e6ff3ul, - 0x748f82eeul, 0x78a5636ful, 0x84c87814ul, 0x8cc70208ul, - 0x90befffaul, 0xa4506cebul, 0xbef9a3f7ul, 0xc67178f2ul, -}; - -/* Compile 64 bytes of hash data into SHA256 digest value */ -/* NOTE: this routine assumes that the byte order in the */ -/* ctx->wbuf[] at this point is such that low address bytes */ -/* in the ORIGINAL byte stream will go into the high end of */ -/* words on BOTH big and little endian systems */ - -VOID_RETURN sha256_compile(sha256_ctx ctx[1]) -{ -#if !defined(UNROLL_SHA2) - - uint_32t j, *p = ctx->wbuf, v[8]; - - memcpy(v, ctx->hash, 8 * sizeof(uint_32t)); - - for(j = 0; j < 64; j += 16) - { - v_cycle( 0, j); v_cycle( 1, j); - v_cycle( 2, j); v_cycle( 3, j); - v_cycle( 4, j); v_cycle( 5, j); - v_cycle( 6, j); v_cycle( 7, j); - v_cycle( 8, j); v_cycle( 9, j); - v_cycle(10, j); v_cycle(11, j); - v_cycle(12, j); v_cycle(13, j); - v_cycle(14, j); v_cycle(15, j); - } - - ctx->hash[0] += v[0]; ctx->hash[1] += v[1]; - ctx->hash[2] += v[2]; ctx->hash[3] += v[3]; - ctx->hash[4] += v[4]; ctx->hash[5] += v[5]; - ctx->hash[6] += v[6]; ctx->hash[7] += v[7]; - -#else - - uint_32t *p = ctx->wbuf,v0,v1,v2,v3,v4,v5,v6,v7; - - v0 = ctx->hash[0]; v1 = ctx->hash[1]; - v2 = ctx->hash[2]; v3 = ctx->hash[3]; - v4 = ctx->hash[4]; v5 = ctx->hash[5]; - v6 = ctx->hash[6]; v7 = ctx->hash[7]; - - one_cycle(0,1,2,3,4,5,6,7,k256[ 0],p[ 0]); - one_cycle(7,0,1,2,3,4,5,6,k256[ 1],p[ 1]); - one_cycle(6,7,0,1,2,3,4,5,k256[ 2],p[ 2]); - one_cycle(5,6,7,0,1,2,3,4,k256[ 3],p[ 3]); - one_cycle(4,5,6,7,0,1,2,3,k256[ 4],p[ 4]); - one_cycle(3,4,5,6,7,0,1,2,k256[ 5],p[ 5]); - one_cycle(2,3,4,5,6,7,0,1,k256[ 6],p[ 6]); - one_cycle(1,2,3,4,5,6,7,0,k256[ 7],p[ 7]); - one_cycle(0,1,2,3,4,5,6,7,k256[ 8],p[ 8]); - one_cycle(7,0,1,2,3,4,5,6,k256[ 9],p[ 9]); - one_cycle(6,7,0,1,2,3,4,5,k256[10],p[10]); - one_cycle(5,6,7,0,1,2,3,4,k256[11],p[11]); - one_cycle(4,5,6,7,0,1,2,3,k256[12],p[12]); - one_cycle(3,4,5,6,7,0,1,2,k256[13],p[13]); - one_cycle(2,3,4,5,6,7,0,1,k256[14],p[14]); - one_cycle(1,2,3,4,5,6,7,0,k256[15],p[15]); - - one_cycle(0,1,2,3,4,5,6,7,k256[16],hf( 0)); - one_cycle(7,0,1,2,3,4,5,6,k256[17],hf( 1)); - one_cycle(6,7,0,1,2,3,4,5,k256[18],hf( 2)); - one_cycle(5,6,7,0,1,2,3,4,k256[19],hf( 3)); - one_cycle(4,5,6,7,0,1,2,3,k256[20],hf( 4)); - one_cycle(3,4,5,6,7,0,1,2,k256[21],hf( 5)); - one_cycle(2,3,4,5,6,7,0,1,k256[22],hf( 6)); - one_cycle(1,2,3,4,5,6,7,0,k256[23],hf( 7)); - one_cycle(0,1,2,3,4,5,6,7,k256[24],hf( 8)); - one_cycle(7,0,1,2,3,4,5,6,k256[25],hf( 9)); - one_cycle(6,7,0,1,2,3,4,5,k256[26],hf(10)); - one_cycle(5,6,7,0,1,2,3,4,k256[27],hf(11)); - one_cycle(4,5,6,7,0,1,2,3,k256[28],hf(12)); - one_cycle(3,4,5,6,7,0,1,2,k256[29],hf(13)); - one_cycle(2,3,4,5,6,7,0,1,k256[30],hf(14)); - one_cycle(1,2,3,4,5,6,7,0,k256[31],hf(15)); - - one_cycle(0,1,2,3,4,5,6,7,k256[32],hf( 0)); - one_cycle(7,0,1,2,3,4,5,6,k256[33],hf( 1)); - one_cycle(6,7,0,1,2,3,4,5,k256[34],hf( 2)); - one_cycle(5,6,7,0,1,2,3,4,k256[35],hf( 3)); - one_cycle(4,5,6,7,0,1,2,3,k256[36],hf( 4)); - one_cycle(3,4,5,6,7,0,1,2,k256[37],hf( 5)); - one_cycle(2,3,4,5,6,7,0,1,k256[38],hf( 6)); - one_cycle(1,2,3,4,5,6,7,0,k256[39],hf( 7)); - one_cycle(0,1,2,3,4,5,6,7,k256[40],hf( 8)); - one_cycle(7,0,1,2,3,4,5,6,k256[41],hf( 9)); - one_cycle(6,7,0,1,2,3,4,5,k256[42],hf(10)); - one_cycle(5,6,7,0,1,2,3,4,k256[43],hf(11)); - one_cycle(4,5,6,7,0,1,2,3,k256[44],hf(12)); - one_cycle(3,4,5,6,7,0,1,2,k256[45],hf(13)); - one_cycle(2,3,4,5,6,7,0,1,k256[46],hf(14)); - one_cycle(1,2,3,4,5,6,7,0,k256[47],hf(15)); - - one_cycle(0,1,2,3,4,5,6,7,k256[48],hf( 0)); - one_cycle(7,0,1,2,3,4,5,6,k256[49],hf( 1)); - one_cycle(6,7,0,1,2,3,4,5,k256[50],hf( 2)); - one_cycle(5,6,7,0,1,2,3,4,k256[51],hf( 3)); - one_cycle(4,5,6,7,0,1,2,3,k256[52],hf( 4)); - one_cycle(3,4,5,6,7,0,1,2,k256[53],hf( 5)); - one_cycle(2,3,4,5,6,7,0,1,k256[54],hf( 6)); - one_cycle(1,2,3,4,5,6,7,0,k256[55],hf( 7)); - one_cycle(0,1,2,3,4,5,6,7,k256[56],hf( 8)); - one_cycle(7,0,1,2,3,4,5,6,k256[57],hf( 9)); - one_cycle(6,7,0,1,2,3,4,5,k256[58],hf(10)); - one_cycle(5,6,7,0,1,2,3,4,k256[59],hf(11)); - one_cycle(4,5,6,7,0,1,2,3,k256[60],hf(12)); - one_cycle(3,4,5,6,7,0,1,2,k256[61],hf(13)); - one_cycle(2,3,4,5,6,7,0,1,k256[62],hf(14)); - one_cycle(1,2,3,4,5,6,7,0,k256[63],hf(15)); - - ctx->hash[0] += v0; ctx->hash[1] += v1; - ctx->hash[2] += v2; ctx->hash[3] += v3; - ctx->hash[4] += v4; ctx->hash[5] += v5; - ctx->hash[6] += v6; ctx->hash[7] += v7; -#endif -} - -/* SHA256 hash data in an array of bytes into hash buffer */ -/* and call the hash_compile function as required. */ - -VOID_RETURN sha256_hash(const unsigned char data[], unsigned long len, sha256_ctx ctx[1]) -{ uint_32t pos = (uint_32t)(ctx->count[0] & SHA256_MASK), - space = SHA256_BLOCK_SIZE - pos; - const unsigned char *sp = data; - - if((ctx->count[0] += len) < len) - ++(ctx->count[1]); - - while(len >= space) /* tranfer whole blocks while possible */ - { - memcpy(((unsigned char*)ctx->wbuf) + pos, sp, space); - sp += space; len -= space; space = SHA256_BLOCK_SIZE; pos = 0; - bsw_32(ctx->wbuf, SHA256_BLOCK_SIZE >> 2) - sha256_compile(ctx); - } - - memcpy(((unsigned char*)ctx->wbuf) + pos, sp, len); -} - -/* SHA256 Final padding and digest calculation */ - -static void sha_end1(unsigned char hval[], sha256_ctx ctx[1], const unsigned int hlen) -{ uint_32t i = (uint_32t)(ctx->count[0] & SHA256_MASK); - - /* put bytes in the buffer in an order in which references to */ - /* 32-bit words will put bytes with lower addresses into the */ - /* top of 32 bit words on BOTH big and little endian machines */ - bsw_32(ctx->wbuf, (i + 3) >> 2) - - /* we now need to mask valid bytes and add the padding which is */ - /* a single 1 bit and as many zero bits as necessary. Note that */ - /* we can always add the first padding byte here because the */ - /* buffer always has at least one empty slot */ - ctx->wbuf[i >> 2] &= 0xffffff80 << 8 * (~i & 3); - ctx->wbuf[i >> 2] |= 0x00000080 << 8 * (~i & 3); - - /* we need 9 or more empty positions, one for the padding byte */ - /* (above) and eight for the length count. If there is not */ - /* enough space pad and empty the buffer */ - if(i > SHA256_BLOCK_SIZE - 9) - { - if(i < 60) ctx->wbuf[15] = 0; - sha256_compile(ctx); - i = 0; - } - else /* compute a word index for the empty buffer positions */ - i = (i >> 2) + 1; - - while(i < 14) /* and zero pad all but last two positions */ - ctx->wbuf[i++] = 0; - - /* the following 32-bit length fields are assembled in the */ - /* wrong byte order on little endian machines but this is */ - /* corrected later since they are only ever used as 32-bit */ - /* word values. */ - ctx->wbuf[14] = (ctx->count[1] << 3) | (ctx->count[0] >> 29); - ctx->wbuf[15] = ctx->count[0] << 3; - sha256_compile(ctx); - - /* extract the hash value as bytes in case the hash buffer is */ - /* mislaigned for 32-bit words */ - for(i = 0; i < hlen; ++i) - hval[i] = (unsigned char)(ctx->hash[i >> 2] >> (8 * (~i & 3))); -} - -#endif - -#if defined(SHA_224) - -const uint_32t i224[8] = -{ - 0xc1059ed8ul, 0x367cd507ul, 0x3070dd17ul, 0xf70e5939ul, - 0xffc00b31ul, 0x68581511ul, 0x64f98fa7ul, 0xbefa4fa4ul -}; - -VOID_RETURN sha224_begin(sha224_ctx ctx[1]) -{ - ctx->count[0] = ctx->count[1] = 0; - memcpy(ctx->hash, i224, 8 * sizeof(uint_32t)); -} - -VOID_RETURN sha224_end(unsigned char hval[], sha224_ctx ctx[1]) -{ - sha_end1(hval, ctx, SHA224_DIGEST_SIZE); -} - -VOID_RETURN sha224(unsigned char hval[], const unsigned char data[], unsigned long len) -{ sha224_ctx cx[1]; - - sha224_begin(cx); - sha224_hash(data, len, cx); - sha_end1(hval, cx, SHA224_DIGEST_SIZE); -} - -#endif - -#if defined(SHA_256) - -const uint_32t i256[8] = -{ - 0x6a09e667ul, 0xbb67ae85ul, 0x3c6ef372ul, 0xa54ff53aul, - 0x510e527ful, 0x9b05688cul, 0x1f83d9abul, 0x5be0cd19ul -}; - -VOID_RETURN sha256_begin(sha256_ctx ctx[1]) -{ - ctx->count[0] = ctx->count[1] = 0; - memcpy(ctx->hash, i256, 8 * sizeof(uint_32t)); -} - -VOID_RETURN sha256_end(unsigned char hval[], sha256_ctx ctx[1]) -{ - sha_end1(hval, ctx, SHA256_DIGEST_SIZE); -} - -VOID_RETURN sha256(unsigned char hval[], const unsigned char data[], unsigned long len) -{ sha256_ctx cx[1]; - - sha256_begin(cx); - sha256_hash(data, len, cx); - sha_end1(hval, cx, SHA256_DIGEST_SIZE); -} - -#endif - -#if defined(SHA_384) || defined(SHA_512) - -#define SHA512_MASK (SHA512_BLOCK_SIZE - 1) - -#if defined(SWAP_BYTES) -#define bsw_64(p,n) \ - { int _i = (n); while(_i--) ((uint_64t*)p)[_i] = bswap_64(((uint_64t*)p)[_i]); } -#else -#define bsw_64(p,n) -#endif - -/* SHA512 mixing function definitions */ - -#ifdef s_0 -# undef s_0 -# undef s_1 -# undef g_0 -# undef g_1 -# undef k_0 -#endif - -#define s_0(x) (rotr64((x), 28) ^ rotr64((x), 34) ^ rotr64((x), 39)) -#define s_1(x) (rotr64((x), 14) ^ rotr64((x), 18) ^ rotr64((x), 41)) -#define g_0(x) (rotr64((x), 1) ^ rotr64((x), 8) ^ ((x) >> 7)) -#define g_1(x) (rotr64((x), 19) ^ rotr64((x), 61) ^ ((x) >> 6)) -#define k_0 k512 - -/* SHA384/SHA512 mixing data */ - -const uint_64t k512[80] = -{ - li_64(428a2f98d728ae22), li_64(7137449123ef65cd), - li_64(b5c0fbcfec4d3b2f), li_64(e9b5dba58189dbbc), - li_64(3956c25bf348b538), li_64(59f111f1b605d019), - li_64(923f82a4af194f9b), li_64(ab1c5ed5da6d8118), - li_64(d807aa98a3030242), li_64(12835b0145706fbe), - li_64(243185be4ee4b28c), li_64(550c7dc3d5ffb4e2), - li_64(72be5d74f27b896f), li_64(80deb1fe3b1696b1), - li_64(9bdc06a725c71235), li_64(c19bf174cf692694), - li_64(e49b69c19ef14ad2), li_64(efbe4786384f25e3), - li_64(0fc19dc68b8cd5b5), li_64(240ca1cc77ac9c65), - li_64(2de92c6f592b0275), li_64(4a7484aa6ea6e483), - li_64(5cb0a9dcbd41fbd4), li_64(76f988da831153b5), - li_64(983e5152ee66dfab), li_64(a831c66d2db43210), - li_64(b00327c898fb213f), li_64(bf597fc7beef0ee4), - li_64(c6e00bf33da88fc2), li_64(d5a79147930aa725), - li_64(06ca6351e003826f), li_64(142929670a0e6e70), - li_64(27b70a8546d22ffc), li_64(2e1b21385c26c926), - li_64(4d2c6dfc5ac42aed), li_64(53380d139d95b3df), - li_64(650a73548baf63de), li_64(766a0abb3c77b2a8), - li_64(81c2c92e47edaee6), li_64(92722c851482353b), - li_64(a2bfe8a14cf10364), li_64(a81a664bbc423001), - li_64(c24b8b70d0f89791), li_64(c76c51a30654be30), - li_64(d192e819d6ef5218), li_64(d69906245565a910), - li_64(f40e35855771202a), li_64(106aa07032bbd1b8), - li_64(19a4c116b8d2d0c8), li_64(1e376c085141ab53), - li_64(2748774cdf8eeb99), li_64(34b0bcb5e19b48a8), - li_64(391c0cb3c5c95a63), li_64(4ed8aa4ae3418acb), - li_64(5b9cca4f7763e373), li_64(682e6ff3d6b2b8a3), - li_64(748f82ee5defb2fc), li_64(78a5636f43172f60), - li_64(84c87814a1f0ab72), li_64(8cc702081a6439ec), - li_64(90befffa23631e28), li_64(a4506cebde82bde9), - li_64(bef9a3f7b2c67915), li_64(c67178f2e372532b), - li_64(ca273eceea26619c), li_64(d186b8c721c0c207), - li_64(eada7dd6cde0eb1e), li_64(f57d4f7fee6ed178), - li_64(06f067aa72176fba), li_64(0a637dc5a2c898a6), - li_64(113f9804bef90dae), li_64(1b710b35131c471b), - li_64(28db77f523047d84), li_64(32caab7b40c72493), - li_64(3c9ebe0a15c9bebc), li_64(431d67c49c100d4c), - li_64(4cc5d4becb3e42b6), li_64(597f299cfc657e2a), - li_64(5fcb6fab3ad6faec), li_64(6c44198c4a475817) -}; - -/* Compile 128 bytes of hash data into SHA384/512 digest */ -/* NOTE: this routine assumes that the byte order in the */ -/* ctx->wbuf[] at this point is such that low address bytes */ -/* in the ORIGINAL byte stream will go into the high end of */ -/* words on BOTH big and little endian systems */ - -VOID_RETURN sha512_compile(sha512_ctx ctx[1]) -{ uint_64t v[8], *p = ctx->wbuf; - uint_32t j; - - memcpy(v, ctx->hash, 8 * sizeof(uint_64t)); - - for(j = 0; j < 80; j += 16) - { - v_cycle( 0, j); v_cycle( 1, j); - v_cycle( 2, j); v_cycle( 3, j); - v_cycle( 4, j); v_cycle( 5, j); - v_cycle( 6, j); v_cycle( 7, j); - v_cycle( 8, j); v_cycle( 9, j); - v_cycle(10, j); v_cycle(11, j); - v_cycle(12, j); v_cycle(13, j); - v_cycle(14, j); v_cycle(15, j); - } - - ctx->hash[0] += v[0]; ctx->hash[1] += v[1]; - ctx->hash[2] += v[2]; ctx->hash[3] += v[3]; - ctx->hash[4] += v[4]; ctx->hash[5] += v[5]; - ctx->hash[6] += v[6]; ctx->hash[7] += v[7]; -} - -/* Compile 128 bytes of hash data into SHA256 digest value */ -/* NOTE: this routine assumes that the byte order in the */ -/* ctx->wbuf[] at this point is in such an order that low */ -/* address bytes in the ORIGINAL byte stream placed in this */ -/* buffer will now go to the high end of words on BOTH big */ -/* and little endian systems */ - -VOID_RETURN sha512_hash(const unsigned char data[], unsigned long len, sha512_ctx ctx[1]) -{ uint_32t pos = (uint_32t)(ctx->count[0] & SHA512_MASK), - space = SHA512_BLOCK_SIZE - pos; - const unsigned char *sp = data; - - if((ctx->count[0] += len) < len) - ++(ctx->count[1]); - - while(len >= space) /* tranfer whole blocks while possible */ - { - memcpy(((unsigned char*)ctx->wbuf) + pos, sp, space); - sp += space; len -= space; space = SHA512_BLOCK_SIZE; pos = 0; - bsw_64(ctx->wbuf, SHA512_BLOCK_SIZE >> 3); - sha512_compile(ctx); - } - - memcpy(((unsigned char*)ctx->wbuf) + pos, sp, len); -} - -/* SHA384/512 Final padding and digest calculation */ - -static void sha_end2(unsigned char hval[], sha512_ctx ctx[1], const unsigned int hlen) -{ uint_32t i = (uint_32t)(ctx->count[0] & SHA512_MASK); - - /* put bytes in the buffer in an order in which references to */ - /* 32-bit words will put bytes with lower addresses into the */ - /* top of 32 bit words on BOTH big and little endian machines */ - bsw_64(ctx->wbuf, (i + 7) >> 3); - - /* we now need to mask valid bytes and add the padding which is */ - /* a single 1 bit and as many zero bits as necessary. Note that */ - /* we can always add the first padding byte here because the */ - /* buffer always has at least one empty slot */ - ctx->wbuf[i >> 3] &= li_64(ffffffffffffff00) << 8 * (~i & 7); - ctx->wbuf[i >> 3] |= li_64(0000000000000080) << 8 * (~i & 7); - - /* we need 17 or more empty byte positions, one for the padding */ - /* byte (above) and sixteen for the length count. If there is */ - /* not enough space pad and empty the buffer */ - if(i > SHA512_BLOCK_SIZE - 17) - { - if(i < 120) ctx->wbuf[15] = 0; - sha512_compile(ctx); - i = 0; - } - else - i = (i >> 3) + 1; - - while(i < 14) - ctx->wbuf[i++] = 0; - - /* the following 64-bit length fields are assembled in the */ - /* wrong byte order on little endian machines but this is */ - /* corrected later since they are only ever used as 64-bit */ - /* word values. */ - ctx->wbuf[14] = (ctx->count[1] << 3) | (ctx->count[0] >> 61); - ctx->wbuf[15] = ctx->count[0] << 3; - sha512_compile(ctx); - - /* extract the hash value as bytes in case the hash buffer is */ - /* misaligned for 32-bit words */ - for(i = 0; i < hlen; ++i) - hval[i] = (unsigned char)(ctx->hash[i >> 3] >> (8 * (~i & 7))); -} - -#endif - -#if defined(SHA_384) - -/* SHA384 initialisation data */ - -const uint_64t i384[80] = -{ - li_64(cbbb9d5dc1059ed8), li_64(629a292a367cd507), - li_64(9159015a3070dd17), li_64(152fecd8f70e5939), - li_64(67332667ffc00b31), li_64(8eb44a8768581511), - li_64(db0c2e0d64f98fa7), li_64(47b5481dbefa4fa4) -}; - -VOID_RETURN sha384_begin(sha384_ctx ctx[1]) -{ - ctx->count[0] = ctx->count[1] = 0; - memcpy(ctx->hash, i384, 8 * sizeof(uint_64t)); -} - -VOID_RETURN sha384_end(unsigned char hval[], sha384_ctx ctx[1]) -{ - sha_end2(hval, ctx, SHA384_DIGEST_SIZE); -} - -VOID_RETURN sha384(unsigned char hval[], const unsigned char data[], unsigned long len) -{ sha384_ctx cx[1]; - - sha384_begin(cx); - sha384_hash(data, len, cx); - sha_end2(hval, cx, SHA384_DIGEST_SIZE); -} - -#endif - -#if defined(SHA_512) - -/* SHA512 initialisation data */ - -const uint_64t i512[80] = -{ - li_64(6a09e667f3bcc908), li_64(bb67ae8584caa73b), - li_64(3c6ef372fe94f82b), li_64(a54ff53a5f1d36f1), - li_64(510e527fade682d1), li_64(9b05688c2b3e6c1f), - li_64(1f83d9abfb41bd6b), li_64(5be0cd19137e2179) -}; - -VOID_RETURN sha512_begin(sha512_ctx ctx[1]) -{ - ctx->count[0] = ctx->count[1] = 0; - memcpy(ctx->hash, i512, 8 * sizeof(uint_64t)); -} - -VOID_RETURN sha512_end(unsigned char hval[], sha512_ctx ctx[1]) -{ - sha_end2(hval, ctx, SHA512_DIGEST_SIZE); -} - -VOID_RETURN sha512(unsigned char hval[], const unsigned char data[], unsigned long len) -{ sha512_ctx cx[1]; - - sha512_begin(cx); - sha512_hash(data, len, cx); - sha_end2(hval, cx, SHA512_DIGEST_SIZE); -} - -#endif - -#if defined(SHA_2) - -#define CTX_224(x) ((x)->uu->ctx256) -#define CTX_256(x) ((x)->uu->ctx256) -#define CTX_384(x) ((x)->uu->ctx512) -#define CTX_512(x) ((x)->uu->ctx512) - -/* SHA2 initialisation */ - -INT_RETURN sha2_begin(unsigned long len, sha2_ctx ctx[1]) -{ - switch(len) - { -#if defined(SHA_224) - case 224: - case 28: CTX_256(ctx)->count[0] = CTX_256(ctx)->count[1] = 0; - memcpy(CTX_256(ctx)->hash, i224, 32); - ctx->sha2_len = 28; return EXIT_SUCCESS; -#endif -#if defined(SHA_256) - case 256: - case 32: CTX_256(ctx)->count[0] = CTX_256(ctx)->count[1] = 0; - memcpy(CTX_256(ctx)->hash, i256, 32); - ctx->sha2_len = 32; return EXIT_SUCCESS; -#endif -#if defined(SHA_384) - case 384: - case 48: CTX_384(ctx)->count[0] = CTX_384(ctx)->count[1] = 0; - memcpy(CTX_384(ctx)->hash, i384, 64); - ctx->sha2_len = 48; return EXIT_SUCCESS; -#endif -#if defined(SHA_512) - case 512: - case 64: CTX_512(ctx)->count[0] = CTX_512(ctx)->count[1] = 0; - memcpy(CTX_512(ctx)->hash, i512, 64); - ctx->sha2_len = 64; return EXIT_SUCCESS; -#endif - default: return EXIT_FAILURE; - } -} - -VOID_RETURN sha2_hash(const unsigned char data[], unsigned long len, sha2_ctx ctx[1]) -{ - switch(ctx->sha2_len) - { -#if defined(SHA_224) - case 28: sha224_hash(data, len, CTX_224(ctx)); return; -#endif -#if defined(SHA_256) - case 32: sha256_hash(data, len, CTX_256(ctx)); return; -#endif -#if defined(SHA_384) - case 48: sha384_hash(data, len, CTX_384(ctx)); return; -#endif -#if defined(SHA_512) - case 64: sha512_hash(data, len, CTX_512(ctx)); return; -#endif - } -} - -VOID_RETURN sha2_end(unsigned char hval[], sha2_ctx ctx[1]) -{ - switch(ctx->sha2_len) - { -#if defined(SHA_224) - case 28: sha_end1(hval, CTX_224(ctx), SHA224_DIGEST_SIZE); return; -#endif -#if defined(SHA_256) - case 32: sha_end1(hval, CTX_256(ctx), SHA256_DIGEST_SIZE); return; -#endif -#if defined(SHA_384) - case 48: sha_end2(hval, CTX_384(ctx), SHA384_DIGEST_SIZE); return; -#endif -#if defined(SHA_512) - case 64: sha_end2(hval, CTX_512(ctx), SHA512_DIGEST_SIZE); return; -#endif - } -} - -INT_RETURN sha2(unsigned char hval[], unsigned long size, - const unsigned char data[], unsigned long len) -{ sha2_ctx cx[1]; - - if(sha2_begin(size, cx) == EXIT_SUCCESS) - { - sha2_hash(data, len, cx); sha2_end(hval, cx); return EXIT_SUCCESS; - } - else - return EXIT_FAILURE; -} - -#endif - -#if defined(__cplusplus) -} -#endif +/* + --------------------------------------------------------------------------- + Copyright (c) 2002, Dr Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software is allowed (with or without + changes) provided that: + + 1. source code distributions include the above copyright notice, this + list of conditions and the following disclaimer; + + 2. binary distributions include the above copyright notice, this list + of conditions and the following disclaimer in their documentation; + + 3. the name of the copyright holder is not used to endorse products + built using this software without specific written permission. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + Issue Date: 01/08/2005 + + This is a byte oriented version of SHA2 that operates on arrays of bytes + stored in memory. This code implements sha256, sha384 and sha512 but the + latter two functions rely on efficient 64-bit integer operations that + may not be very efficient on 32-bit machines + + The sha256 functions use a type 'sha256_ctx' to hold details of the + current hash state and uses the following three calls: + + void sha256_begin(sha256_ctx ctx[1]) + void sha256_hash(const unsigned char data[], + unsigned long len, sha256_ctx ctx[1]) + void sha_end1(unsigned char hval[], sha256_ctx ctx[1]) + + The first subroutine initialises a hash computation by setting up the + context in the sha256_ctx context. The second subroutine hashes 8-bit + bytes from array data[] into the hash state withinh sha256_ctx context, + the number of bytes to be hashed being given by the the unsigned long + integer len. The third subroutine completes the hash calculation and + places the resulting digest value in the array of 8-bit bytes hval[]. + + The sha384 and sha512 functions are similar and use the interfaces: + + void sha384_begin(sha384_ctx ctx[1]); + void sha384_hash(const unsigned char data[], + unsigned long len, sha384_ctx ctx[1]); + void sha384_end(unsigned char hval[], sha384_ctx ctx[1]); + + void sha512_begin(sha512_ctx ctx[1]); + void sha512_hash(const unsigned char data[], + unsigned long len, sha512_ctx ctx[1]); + void sha512_end(unsigned char hval[], sha512_ctx ctx[1]); + + In addition there is a function sha2 that can be used to call all these + functions using a call with a hash length parameter as follows: + + int sha2_begin(unsigned long len, sha2_ctx ctx[1]); + void sha2_hash(const unsigned char data[], + unsigned long len, sha2_ctx ctx[1]); + void sha2_end(unsigned char hval[], sha2_ctx ctx[1]); + + My thanks to Erik Andersen for testing this code + on big-endian systems and for his assistance with corrections +*/ + +#include "Common/Endian.h" +#include "Crypto/misc.h" +#define PLATFORM_BYTE_ORDER BYTE_ORDER +#define IS_LITTLE_ENDIAN LITTLE_ENDIAN + +#if 0 +#define UNROLL_SHA2 /* for SHA2 loop unroll */ +#endif + +#include /* for memcpy() etc. */ + +#include "Sha2.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif + +#if defined( _MSC_VER ) && ( _MSC_VER > 800 ) +#pragma intrinsic(memcpy) +#endif + +#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN) +#define SWAP_BYTES +#else +#undef SWAP_BYTES +#endif + +#if 0 + +#define ch(x,y,z) (((x) & (y)) ^ (~(x) & (z))) +#define maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) + +#else /* Thanks to Rich Schroeppel and Colin Plumb for the following */ + +#define ch(x,y,z) ((z) ^ ((x) & ((y) ^ (z)))) +#define maj(x,y,z) (((x) & (y)) | ((z) & ((x) ^ (y)))) + +#endif + +/* round transforms for SHA256 and SHA512 compression functions */ + +#define vf(n,i) v[(n - i) & 7] + +#define hf(i) (p[i & 15] += \ + g_1(p[(i + 14) & 15]) + p[(i + 9) & 15] + g_0(p[(i + 1) & 15])) + +#define v_cycle(i,j) \ + vf(7,i) += (j ? hf(i) : p[i]) + k_0[i+j] \ + + s_1(vf(4,i)) + ch(vf(4,i),vf(5,i),vf(6,i)); \ + vf(3,i) += vf(7,i); \ + vf(7,i) += s_0(vf(0,i))+ maj(vf(0,i),vf(1,i),vf(2,i)) + +#if defined(SHA_224) || defined(SHA_256) + +#define SHA256_MASK (SHA256_BLOCK_SIZE - 1) + +#if defined(SWAP_BYTES) +#define bsw_32(p,n) \ + { int _i = (n); while(_i--) ((uint_32t*)p)[_i] = bswap_32(((uint_32t*)p)[_i]); } +#else +#define bsw_32(p,n) +#endif + +#define s_0(x) (rotr32((x), 2) ^ rotr32((x), 13) ^ rotr32((x), 22)) +#define s_1(x) (rotr32((x), 6) ^ rotr32((x), 11) ^ rotr32((x), 25)) +#define g_0(x) (rotr32((x), 7) ^ rotr32((x), 18) ^ ((x) >> 3)) +#define g_1(x) (rotr32((x), 17) ^ rotr32((x), 19) ^ ((x) >> 10)) +#define k_0 k256 + +/* rotated SHA256 round definition. Rather than swapping variables as in */ +/* FIPS-180, different variables are 'rotated' on each round, returning */ +/* to their starting positions every eight rounds */ + +#define q(n) v##n + +#define one_cycle(a,b,c,d,e,f,g,h,k,w) \ + q(h) += s_1(q(e)) + ch(q(e), q(f), q(g)) + k + w; \ + q(d) += q(h); q(h) += s_0(q(a)) + maj(q(a), q(b), q(c)) + +/* SHA256 mixing data */ + +const uint_32t k256[64] = +{ 0x428a2f98ul, 0x71374491ul, 0xb5c0fbcful, 0xe9b5dba5ul, + 0x3956c25bul, 0x59f111f1ul, 0x923f82a4ul, 0xab1c5ed5ul, + 0xd807aa98ul, 0x12835b01ul, 0x243185beul, 0x550c7dc3ul, + 0x72be5d74ul, 0x80deb1feul, 0x9bdc06a7ul, 0xc19bf174ul, + 0xe49b69c1ul, 0xefbe4786ul, 0x0fc19dc6ul, 0x240ca1ccul, + 0x2de92c6ful, 0x4a7484aaul, 0x5cb0a9dcul, 0x76f988daul, + 0x983e5152ul, 0xa831c66dul, 0xb00327c8ul, 0xbf597fc7ul, + 0xc6e00bf3ul, 0xd5a79147ul, 0x06ca6351ul, 0x14292967ul, + 0x27b70a85ul, 0x2e1b2138ul, 0x4d2c6dfcul, 0x53380d13ul, + 0x650a7354ul, 0x766a0abbul, 0x81c2c92eul, 0x92722c85ul, + 0xa2bfe8a1ul, 0xa81a664bul, 0xc24b8b70ul, 0xc76c51a3ul, + 0xd192e819ul, 0xd6990624ul, 0xf40e3585ul, 0x106aa070ul, + 0x19a4c116ul, 0x1e376c08ul, 0x2748774cul, 0x34b0bcb5ul, + 0x391c0cb3ul, 0x4ed8aa4aul, 0x5b9cca4ful, 0x682e6ff3ul, + 0x748f82eeul, 0x78a5636ful, 0x84c87814ul, 0x8cc70208ul, + 0x90befffaul, 0xa4506cebul, 0xbef9a3f7ul, 0xc67178f2ul, +}; + +/* Compile 64 bytes of hash data into SHA256 digest value */ +/* NOTE: this routine assumes that the byte order in the */ +/* ctx->wbuf[] at this point is such that low address bytes */ +/* in the ORIGINAL byte stream will go into the high end of */ +/* words on BOTH big and little endian systems */ + +VOID_RETURN sha256_compile(sha256_ctx ctx[1]) +{ +#if !defined(UNROLL_SHA2) + + uint_32t j, *p = ctx->wbuf, v[8]; + + memcpy(v, ctx->hash, 8 * sizeof(uint_32t)); + + for(j = 0; j < 64; j += 16) + { + v_cycle( 0, j); v_cycle( 1, j); + v_cycle( 2, j); v_cycle( 3, j); + v_cycle( 4, j); v_cycle( 5, j); + v_cycle( 6, j); v_cycle( 7, j); + v_cycle( 8, j); v_cycle( 9, j); + v_cycle(10, j); v_cycle(11, j); + v_cycle(12, j); v_cycle(13, j); + v_cycle(14, j); v_cycle(15, j); + } + + ctx->hash[0] += v[0]; ctx->hash[1] += v[1]; + ctx->hash[2] += v[2]; ctx->hash[3] += v[3]; + ctx->hash[4] += v[4]; ctx->hash[5] += v[5]; + ctx->hash[6] += v[6]; ctx->hash[7] += v[7]; + +#else + + uint_32t *p = ctx->wbuf,v0,v1,v2,v3,v4,v5,v6,v7; + + v0 = ctx->hash[0]; v1 = ctx->hash[1]; + v2 = ctx->hash[2]; v3 = ctx->hash[3]; + v4 = ctx->hash[4]; v5 = ctx->hash[5]; + v6 = ctx->hash[6]; v7 = ctx->hash[7]; + + one_cycle(0,1,2,3,4,5,6,7,k256[ 0],p[ 0]); + one_cycle(7,0,1,2,3,4,5,6,k256[ 1],p[ 1]); + one_cycle(6,7,0,1,2,3,4,5,k256[ 2],p[ 2]); + one_cycle(5,6,7,0,1,2,3,4,k256[ 3],p[ 3]); + one_cycle(4,5,6,7,0,1,2,3,k256[ 4],p[ 4]); + one_cycle(3,4,5,6,7,0,1,2,k256[ 5],p[ 5]); + one_cycle(2,3,4,5,6,7,0,1,k256[ 6],p[ 6]); + one_cycle(1,2,3,4,5,6,7,0,k256[ 7],p[ 7]); + one_cycle(0,1,2,3,4,5,6,7,k256[ 8],p[ 8]); + one_cycle(7,0,1,2,3,4,5,6,k256[ 9],p[ 9]); + one_cycle(6,7,0,1,2,3,4,5,k256[10],p[10]); + one_cycle(5,6,7,0,1,2,3,4,k256[11],p[11]); + one_cycle(4,5,6,7,0,1,2,3,k256[12],p[12]); + one_cycle(3,4,5,6,7,0,1,2,k256[13],p[13]); + one_cycle(2,3,4,5,6,7,0,1,k256[14],p[14]); + one_cycle(1,2,3,4,5,6,7,0,k256[15],p[15]); + + one_cycle(0,1,2,3,4,5,6,7,k256[16],hf( 0)); + one_cycle(7,0,1,2,3,4,5,6,k256[17],hf( 1)); + one_cycle(6,7,0,1,2,3,4,5,k256[18],hf( 2)); + one_cycle(5,6,7,0,1,2,3,4,k256[19],hf( 3)); + one_cycle(4,5,6,7,0,1,2,3,k256[20],hf( 4)); + one_cycle(3,4,5,6,7,0,1,2,k256[21],hf( 5)); + one_cycle(2,3,4,5,6,7,0,1,k256[22],hf( 6)); + one_cycle(1,2,3,4,5,6,7,0,k256[23],hf( 7)); + one_cycle(0,1,2,3,4,5,6,7,k256[24],hf( 8)); + one_cycle(7,0,1,2,3,4,5,6,k256[25],hf( 9)); + one_cycle(6,7,0,1,2,3,4,5,k256[26],hf(10)); + one_cycle(5,6,7,0,1,2,3,4,k256[27],hf(11)); + one_cycle(4,5,6,7,0,1,2,3,k256[28],hf(12)); + one_cycle(3,4,5,6,7,0,1,2,k256[29],hf(13)); + one_cycle(2,3,4,5,6,7,0,1,k256[30],hf(14)); + one_cycle(1,2,3,4,5,6,7,0,k256[31],hf(15)); + + one_cycle(0,1,2,3,4,5,6,7,k256[32],hf( 0)); + one_cycle(7,0,1,2,3,4,5,6,k256[33],hf( 1)); + one_cycle(6,7,0,1,2,3,4,5,k256[34],hf( 2)); + one_cycle(5,6,7,0,1,2,3,4,k256[35],hf( 3)); + one_cycle(4,5,6,7,0,1,2,3,k256[36],hf( 4)); + one_cycle(3,4,5,6,7,0,1,2,k256[37],hf( 5)); + one_cycle(2,3,4,5,6,7,0,1,k256[38],hf( 6)); + one_cycle(1,2,3,4,5,6,7,0,k256[39],hf( 7)); + one_cycle(0,1,2,3,4,5,6,7,k256[40],hf( 8)); + one_cycle(7,0,1,2,3,4,5,6,k256[41],hf( 9)); + one_cycle(6,7,0,1,2,3,4,5,k256[42],hf(10)); + one_cycle(5,6,7,0,1,2,3,4,k256[43],hf(11)); + one_cycle(4,5,6,7,0,1,2,3,k256[44],hf(12)); + one_cycle(3,4,5,6,7,0,1,2,k256[45],hf(13)); + one_cycle(2,3,4,5,6,7,0,1,k256[46],hf(14)); + one_cycle(1,2,3,4,5,6,7,0,k256[47],hf(15)); + + one_cycle(0,1,2,3,4,5,6,7,k256[48],hf( 0)); + one_cycle(7,0,1,2,3,4,5,6,k256[49],hf( 1)); + one_cycle(6,7,0,1,2,3,4,5,k256[50],hf( 2)); + one_cycle(5,6,7,0,1,2,3,4,k256[51],hf( 3)); + one_cycle(4,5,6,7,0,1,2,3,k256[52],hf( 4)); + one_cycle(3,4,5,6,7,0,1,2,k256[53],hf( 5)); + one_cycle(2,3,4,5,6,7,0,1,k256[54],hf( 6)); + one_cycle(1,2,3,4,5,6,7,0,k256[55],hf( 7)); + one_cycle(0,1,2,3,4,5,6,7,k256[56],hf( 8)); + one_cycle(7,0,1,2,3,4,5,6,k256[57],hf( 9)); + one_cycle(6,7,0,1,2,3,4,5,k256[58],hf(10)); + one_cycle(5,6,7,0,1,2,3,4,k256[59],hf(11)); + one_cycle(4,5,6,7,0,1,2,3,k256[60],hf(12)); + one_cycle(3,4,5,6,7,0,1,2,k256[61],hf(13)); + one_cycle(2,3,4,5,6,7,0,1,k256[62],hf(14)); + one_cycle(1,2,3,4,5,6,7,0,k256[63],hf(15)); + + ctx->hash[0] += v0; ctx->hash[1] += v1; + ctx->hash[2] += v2; ctx->hash[3] += v3; + ctx->hash[4] += v4; ctx->hash[5] += v5; + ctx->hash[6] += v6; ctx->hash[7] += v7; +#endif +} + +/* SHA256 hash data in an array of bytes into hash buffer */ +/* and call the hash_compile function as required. */ + +VOID_RETURN sha256_hash(const unsigned char data[], unsigned long len, sha256_ctx ctx[1]) +{ uint_32t pos = (uint_32t)(ctx->count[0] & SHA256_MASK), + space = SHA256_BLOCK_SIZE - pos; + const unsigned char *sp = data; + + if((ctx->count[0] += len) < len) + ++(ctx->count[1]); + + while(len >= space) /* tranfer whole blocks while possible */ + { + memcpy(((unsigned char*)ctx->wbuf) + pos, sp, space); + sp += space; len -= space; space = SHA256_BLOCK_SIZE; pos = 0; + bsw_32(ctx->wbuf, SHA256_BLOCK_SIZE >> 2) + sha256_compile(ctx); + } + + memcpy(((unsigned char*)ctx->wbuf) + pos, sp, len); +} + +/* SHA256 Final padding and digest calculation */ + +static void sha_end1(unsigned char hval[], sha256_ctx ctx[1], const unsigned int hlen) +{ uint_32t i = (uint_32t)(ctx->count[0] & SHA256_MASK); + + /* put bytes in the buffer in an order in which references to */ + /* 32-bit words will put bytes with lower addresses into the */ + /* top of 32 bit words on BOTH big and little endian machines */ + bsw_32(ctx->wbuf, (i + 3) >> 2) + + /* we now need to mask valid bytes and add the padding which is */ + /* a single 1 bit and as many zero bits as necessary. Note that */ + /* we can always add the first padding byte here because the */ + /* buffer always has at least one empty slot */ + ctx->wbuf[i >> 2] &= 0xffffff80 << 8 * (~i & 3); + ctx->wbuf[i >> 2] |= 0x00000080 << 8 * (~i & 3); + + /* we need 9 or more empty positions, one for the padding byte */ + /* (above) and eight for the length count. If there is not */ + /* enough space pad and empty the buffer */ + if(i > SHA256_BLOCK_SIZE - 9) + { + if(i < 60) ctx->wbuf[15] = 0; + sha256_compile(ctx); + i = 0; + } + else /* compute a word index for the empty buffer positions */ + i = (i >> 2) + 1; + + while(i < 14) /* and zero pad all but last two positions */ + ctx->wbuf[i++] = 0; + + /* the following 32-bit length fields are assembled in the */ + /* wrong byte order on little endian machines but this is */ + /* corrected later since they are only ever used as 32-bit */ + /* word values. */ + ctx->wbuf[14] = (ctx->count[1] << 3) | (ctx->count[0] >> 29); + ctx->wbuf[15] = ctx->count[0] << 3; + sha256_compile(ctx); + + /* extract the hash value as bytes in case the hash buffer is */ + /* mislaigned for 32-bit words */ + for(i = 0; i < hlen; ++i) + hval[i] = (unsigned char)(ctx->hash[i >> 2] >> (8 * (~i & 3))); +} + +#endif + +#if defined(SHA_224) + +const uint_32t i224[8] = +{ + 0xc1059ed8ul, 0x367cd507ul, 0x3070dd17ul, 0xf70e5939ul, + 0xffc00b31ul, 0x68581511ul, 0x64f98fa7ul, 0xbefa4fa4ul +}; + +VOID_RETURN sha224_begin(sha224_ctx ctx[1]) +{ + ctx->count[0] = ctx->count[1] = 0; + memcpy(ctx->hash, i224, 8 * sizeof(uint_32t)); +} + +VOID_RETURN sha224_end(unsigned char hval[], sha224_ctx ctx[1]) +{ + sha_end1(hval, ctx, SHA224_DIGEST_SIZE); +} + +VOID_RETURN sha224(unsigned char hval[], const unsigned char data[], unsigned long len) +{ sha224_ctx cx[1]; + + sha224_begin(cx); + sha224_hash(data, len, cx); + sha_end1(hval, cx, SHA224_DIGEST_SIZE); +} + +#endif + +#if defined(SHA_256) + +const uint_32t i256[8] = +{ + 0x6a09e667ul, 0xbb67ae85ul, 0x3c6ef372ul, 0xa54ff53aul, + 0x510e527ful, 0x9b05688cul, 0x1f83d9abul, 0x5be0cd19ul +}; + +VOID_RETURN sha256_begin(sha256_ctx ctx[1]) +{ + ctx->count[0] = ctx->count[1] = 0; + memcpy(ctx->hash, i256, 8 * sizeof(uint_32t)); +} + +VOID_RETURN sha256_end(unsigned char hval[], sha256_ctx ctx[1]) +{ + sha_end1(hval, ctx, SHA256_DIGEST_SIZE); +} + +VOID_RETURN sha256(unsigned char hval[], const unsigned char data[], unsigned long len) +{ sha256_ctx cx[1]; + + sha256_begin(cx); + sha256_hash(data, len, cx); + sha_end1(hval, cx, SHA256_DIGEST_SIZE); +} + +#endif + +#if defined(SHA_384) || defined(SHA_512) + +#define SHA512_MASK (SHA512_BLOCK_SIZE - 1) + +#if defined(SWAP_BYTES) +#define bsw_64(p,n) \ + { int _i = (n); while(_i--) ((uint_64t*)p)[_i] = bswap_64(((uint_64t*)p)[_i]); } +#else +#define bsw_64(p,n) +#endif + +/* SHA512 mixing function definitions */ + +#ifdef s_0 +# undef s_0 +# undef s_1 +# undef g_0 +# undef g_1 +# undef k_0 +#endif + +#define s_0(x) (rotr64((x), 28) ^ rotr64((x), 34) ^ rotr64((x), 39)) +#define s_1(x) (rotr64((x), 14) ^ rotr64((x), 18) ^ rotr64((x), 41)) +#define g_0(x) (rotr64((x), 1) ^ rotr64((x), 8) ^ ((x) >> 7)) +#define g_1(x) (rotr64((x), 19) ^ rotr64((x), 61) ^ ((x) >> 6)) +#define k_0 k512 + +/* SHA384/SHA512 mixing data */ + +const uint_64t k512[80] = +{ + li_64(428a2f98d728ae22), li_64(7137449123ef65cd), + li_64(b5c0fbcfec4d3b2f), li_64(e9b5dba58189dbbc), + li_64(3956c25bf348b538), li_64(59f111f1b605d019), + li_64(923f82a4af194f9b), li_64(ab1c5ed5da6d8118), + li_64(d807aa98a3030242), li_64(12835b0145706fbe), + li_64(243185be4ee4b28c), li_64(550c7dc3d5ffb4e2), + li_64(72be5d74f27b896f), li_64(80deb1fe3b1696b1), + li_64(9bdc06a725c71235), li_64(c19bf174cf692694), + li_64(e49b69c19ef14ad2), li_64(efbe4786384f25e3), + li_64(0fc19dc68b8cd5b5), li_64(240ca1cc77ac9c65), + li_64(2de92c6f592b0275), li_64(4a7484aa6ea6e483), + li_64(5cb0a9dcbd41fbd4), li_64(76f988da831153b5), + li_64(983e5152ee66dfab), li_64(a831c66d2db43210), + li_64(b00327c898fb213f), li_64(bf597fc7beef0ee4), + li_64(c6e00bf33da88fc2), li_64(d5a79147930aa725), + li_64(06ca6351e003826f), li_64(142929670a0e6e70), + li_64(27b70a8546d22ffc), li_64(2e1b21385c26c926), + li_64(4d2c6dfc5ac42aed), li_64(53380d139d95b3df), + li_64(650a73548baf63de), li_64(766a0abb3c77b2a8), + li_64(81c2c92e47edaee6), li_64(92722c851482353b), + li_64(a2bfe8a14cf10364), li_64(a81a664bbc423001), + li_64(c24b8b70d0f89791), li_64(c76c51a30654be30), + li_64(d192e819d6ef5218), li_64(d69906245565a910), + li_64(f40e35855771202a), li_64(106aa07032bbd1b8), + li_64(19a4c116b8d2d0c8), li_64(1e376c085141ab53), + li_64(2748774cdf8eeb99), li_64(34b0bcb5e19b48a8), + li_64(391c0cb3c5c95a63), li_64(4ed8aa4ae3418acb), + li_64(5b9cca4f7763e373), li_64(682e6ff3d6b2b8a3), + li_64(748f82ee5defb2fc), li_64(78a5636f43172f60), + li_64(84c87814a1f0ab72), li_64(8cc702081a6439ec), + li_64(90befffa23631e28), li_64(a4506cebde82bde9), + li_64(bef9a3f7b2c67915), li_64(c67178f2e372532b), + li_64(ca273eceea26619c), li_64(d186b8c721c0c207), + li_64(eada7dd6cde0eb1e), li_64(f57d4f7fee6ed178), + li_64(06f067aa72176fba), li_64(0a637dc5a2c898a6), + li_64(113f9804bef90dae), li_64(1b710b35131c471b), + li_64(28db77f523047d84), li_64(32caab7b40c72493), + li_64(3c9ebe0a15c9bebc), li_64(431d67c49c100d4c), + li_64(4cc5d4becb3e42b6), li_64(597f299cfc657e2a), + li_64(5fcb6fab3ad6faec), li_64(6c44198c4a475817) +}; + +/* Compile 128 bytes of hash data into SHA384/512 digest */ +/* NOTE: this routine assumes that the byte order in the */ +/* ctx->wbuf[] at this point is such that low address bytes */ +/* in the ORIGINAL byte stream will go into the high end of */ +/* words on BOTH big and little endian systems */ + +VOID_RETURN sha512_compile(sha512_ctx ctx[1]) +{ uint_64t v[8], *p = ctx->wbuf; + uint_32t j; + + memcpy(v, ctx->hash, 8 * sizeof(uint_64t)); + + for(j = 0; j < 80; j += 16) + { + v_cycle( 0, j); v_cycle( 1, j); + v_cycle( 2, j); v_cycle( 3, j); + v_cycle( 4, j); v_cycle( 5, j); + v_cycle( 6, j); v_cycle( 7, j); + v_cycle( 8, j); v_cycle( 9, j); + v_cycle(10, j); v_cycle(11, j); + v_cycle(12, j); v_cycle(13, j); + v_cycle(14, j); v_cycle(15, j); + } + + ctx->hash[0] += v[0]; ctx->hash[1] += v[1]; + ctx->hash[2] += v[2]; ctx->hash[3] += v[3]; + ctx->hash[4] += v[4]; ctx->hash[5] += v[5]; + ctx->hash[6] += v[6]; ctx->hash[7] += v[7]; +} + +/* Compile 128 bytes of hash data into SHA256 digest value */ +/* NOTE: this routine assumes that the byte order in the */ +/* ctx->wbuf[] at this point is in such an order that low */ +/* address bytes in the ORIGINAL byte stream placed in this */ +/* buffer will now go to the high end of words on BOTH big */ +/* and little endian systems */ + +VOID_RETURN sha512_hash(const unsigned char data[], unsigned long len, sha512_ctx ctx[1]) +{ uint_32t pos = (uint_32t)(ctx->count[0] & SHA512_MASK), + space = SHA512_BLOCK_SIZE - pos; + const unsigned char *sp = data; + + if((ctx->count[0] += len) < len) + ++(ctx->count[1]); + + while(len >= space) /* tranfer whole blocks while possible */ + { + memcpy(((unsigned char*)ctx->wbuf) + pos, sp, space); + sp += space; len -= space; space = SHA512_BLOCK_SIZE; pos = 0; + bsw_64(ctx->wbuf, SHA512_BLOCK_SIZE >> 3); + sha512_compile(ctx); + } + + memcpy(((unsigned char*)ctx->wbuf) + pos, sp, len); +} + +/* SHA384/512 Final padding and digest calculation */ + +static void sha_end2(unsigned char hval[], sha512_ctx ctx[1], const unsigned int hlen) +{ uint_32t i = (uint_32t)(ctx->count[0] & SHA512_MASK); + + /* put bytes in the buffer in an order in which references to */ + /* 32-bit words will put bytes with lower addresses into the */ + /* top of 32 bit words on BOTH big and little endian machines */ + bsw_64(ctx->wbuf, (i + 7) >> 3); + + /* we now need to mask valid bytes and add the padding which is */ + /* a single 1 bit and as many zero bits as necessary. Note that */ + /* we can always add the first padding byte here because the */ + /* buffer always has at least one empty slot */ + ctx->wbuf[i >> 3] &= li_64(ffffffffffffff00) << 8 * (~i & 7); + ctx->wbuf[i >> 3] |= li_64(0000000000000080) << 8 * (~i & 7); + + /* we need 17 or more empty byte positions, one for the padding */ + /* byte (above) and sixteen for the length count. If there is */ + /* not enough space pad and empty the buffer */ + if(i > SHA512_BLOCK_SIZE - 17) + { + if(i < 120) ctx->wbuf[15] = 0; + sha512_compile(ctx); + i = 0; + } + else + i = (i >> 3) + 1; + + while(i < 14) + ctx->wbuf[i++] = 0; + + /* the following 64-bit length fields are assembled in the */ + /* wrong byte order on little endian machines but this is */ + /* corrected later since they are only ever used as 64-bit */ + /* word values. */ + ctx->wbuf[14] = (ctx->count[1] << 3) | (ctx->count[0] >> 61); + ctx->wbuf[15] = ctx->count[0] << 3; + sha512_compile(ctx); + + /* extract the hash value as bytes in case the hash buffer is */ + /* misaligned for 32-bit words */ + for(i = 0; i < hlen; ++i) + hval[i] = (unsigned char)(ctx->hash[i >> 3] >> (8 * (~i & 7))); +} + +#endif + +#if defined(SHA_384) + +/* SHA384 initialisation data */ + +const uint_64t i384[80] = +{ + li_64(cbbb9d5dc1059ed8), li_64(629a292a367cd507), + li_64(9159015a3070dd17), li_64(152fecd8f70e5939), + li_64(67332667ffc00b31), li_64(8eb44a8768581511), + li_64(db0c2e0d64f98fa7), li_64(47b5481dbefa4fa4) +}; + +VOID_RETURN sha384_begin(sha384_ctx ctx[1]) +{ + ctx->count[0] = ctx->count[1] = 0; + memcpy(ctx->hash, i384, 8 * sizeof(uint_64t)); +} + +VOID_RETURN sha384_end(unsigned char hval[], sha384_ctx ctx[1]) +{ + sha_end2(hval, ctx, SHA384_DIGEST_SIZE); +} + +VOID_RETURN sha384(unsigned char hval[], const unsigned char data[], unsigned long len) +{ sha384_ctx cx[1]; + + sha384_begin(cx); + sha384_hash(data, len, cx); + sha_end2(hval, cx, SHA384_DIGEST_SIZE); +} + +#endif + +#if defined(SHA_512) + +/* SHA512 initialisation data */ + +const uint_64t i512[80] = +{ + li_64(6a09e667f3bcc908), li_64(bb67ae8584caa73b), + li_64(3c6ef372fe94f82b), li_64(a54ff53a5f1d36f1), + li_64(510e527fade682d1), li_64(9b05688c2b3e6c1f), + li_64(1f83d9abfb41bd6b), li_64(5be0cd19137e2179) +}; + +VOID_RETURN sha512_begin(sha512_ctx ctx[1]) +{ + ctx->count[0] = ctx->count[1] = 0; + memcpy(ctx->hash, i512, 8 * sizeof(uint_64t)); +} + +VOID_RETURN sha512_end(unsigned char hval[], sha512_ctx ctx[1]) +{ + sha_end2(hval, ctx, SHA512_DIGEST_SIZE); +} + +VOID_RETURN sha512(unsigned char hval[], const unsigned char data[], unsigned long len) +{ sha512_ctx cx[1]; + + sha512_begin(cx); + sha512_hash(data, len, cx); + sha_end2(hval, cx, SHA512_DIGEST_SIZE); +} + +#endif + +#if defined(SHA_2) + +#define CTX_224(x) ((x)->uu->ctx256) +#define CTX_256(x) ((x)->uu->ctx256) +#define CTX_384(x) ((x)->uu->ctx512) +#define CTX_512(x) ((x)->uu->ctx512) + +/* SHA2 initialisation */ + +INT_RETURN sha2_begin(unsigned long len, sha2_ctx ctx[1]) +{ + switch(len) + { +#if defined(SHA_224) + case 224: + case 28: CTX_256(ctx)->count[0] = CTX_256(ctx)->count[1] = 0; + memcpy(CTX_256(ctx)->hash, i224, 32); + ctx->sha2_len = 28; return EXIT_SUCCESS; +#endif +#if defined(SHA_256) + case 256: + case 32: CTX_256(ctx)->count[0] = CTX_256(ctx)->count[1] = 0; + memcpy(CTX_256(ctx)->hash, i256, 32); + ctx->sha2_len = 32; return EXIT_SUCCESS; +#endif +#if defined(SHA_384) + case 384: + case 48: CTX_384(ctx)->count[0] = CTX_384(ctx)->count[1] = 0; + memcpy(CTX_384(ctx)->hash, i384, 64); + ctx->sha2_len = 48; return EXIT_SUCCESS; +#endif +#if defined(SHA_512) + case 512: + case 64: CTX_512(ctx)->count[0] = CTX_512(ctx)->count[1] = 0; + memcpy(CTX_512(ctx)->hash, i512, 64); + ctx->sha2_len = 64; return EXIT_SUCCESS; +#endif + default: return EXIT_FAILURE; + } +} + +VOID_RETURN sha2_hash(const unsigned char data[], unsigned long len, sha2_ctx ctx[1]) +{ + switch(ctx->sha2_len) + { +#if defined(SHA_224) + case 28: sha224_hash(data, len, CTX_224(ctx)); return; +#endif +#if defined(SHA_256) + case 32: sha256_hash(data, len, CTX_256(ctx)); return; +#endif +#if defined(SHA_384) + case 48: sha384_hash(data, len, CTX_384(ctx)); return; +#endif +#if defined(SHA_512) + case 64: sha512_hash(data, len, CTX_512(ctx)); return; +#endif + } +} + +VOID_RETURN sha2_end(unsigned char hval[], sha2_ctx ctx[1]) +{ + switch(ctx->sha2_len) + { +#if defined(SHA_224) + case 28: sha_end1(hval, CTX_224(ctx), SHA224_DIGEST_SIZE); return; +#endif +#if defined(SHA_256) + case 32: sha_end1(hval, CTX_256(ctx), SHA256_DIGEST_SIZE); return; +#endif +#if defined(SHA_384) + case 48: sha_end2(hval, CTX_384(ctx), SHA384_DIGEST_SIZE); return; +#endif +#if defined(SHA_512) + case 64: sha_end2(hval, CTX_512(ctx), SHA512_DIGEST_SIZE); return; +#endif + } +} + +INT_RETURN sha2(unsigned char hval[], unsigned long size, + const unsigned char data[], unsigned long len) +{ sha2_ctx cx[1]; + + if(sha2_begin(size, cx) == EXIT_SUCCESS) + { + sha2_hash(data, len, cx); sha2_end(hval, cx); return EXIT_SUCCESS; + } + else + return EXIT_FAILURE; +} + +#endif + +#if defined(__cplusplus) +} +#endif diff --git a/src/Crypto/Sha2.h b/src/Crypto/Sha2.h index 64379d17..6d0aeb0f 100644 --- a/src/Crypto/Sha2.h +++ b/src/Crypto/Sha2.h @@ -1,155 +1,155 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 2002, Dr Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software is allowed (with or without - changes) provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - Issue Date: 01/08/2005 -*/ - -#ifndef _SHA2_H -#define _SHA2_H - -#include "Common/Tcdefs.h" -#include "Common/Endian.h" - -#define SHA_64BIT - -/* define the hash functions that you need */ -#define SHA_2 /* for dynamic hash length */ -#define SHA_224 -#define SHA_256 -#ifdef SHA_64BIT -# define SHA_384 -# define SHA_512 -# define NEED_UINT_64T -#endif - -#ifndef EXIT_SUCCESS -#define EXIT_SUCCESS 0 -#define EXIT_FAILURE 1 -#endif - -#define li_64(h) 0x##h##ull - -#define VOID_RETURN void -#define INT_RETURN int - -#if defined(__cplusplus) -extern "C" -{ -#endif - -/* Note that the following function prototypes are the same */ -/* for both the bit and byte oriented implementations. But */ -/* the length fields are in bytes or bits as is appropriate */ -/* for the version used. Bit sequences are arrays of bytes */ -/* in which bit sequence indexes increase from the most to */ -/* the least significant end of each byte */ - -#define SHA224_DIGEST_SIZE 28 -#define SHA224_BLOCK_SIZE 64 -#define SHA256_DIGEST_SIZE 32 -#define SHA256_BLOCK_SIZE 64 - -/* type to hold the SHA256 (and SHA224) context */ - -typedef struct -{ uint_32t count[2]; - uint_32t hash[8]; - uint_32t wbuf[16]; -} sha256_ctx; - -typedef sha256_ctx sha224_ctx; - -VOID_RETURN sha256_compile(sha256_ctx ctx[1]); - -VOID_RETURN sha224_begin(sha224_ctx ctx[1]); -#define sha224_hash sha256_hash -VOID_RETURN sha224_end(unsigned char hval[], sha224_ctx ctx[1]); -VOID_RETURN sha224(unsigned char hval[], const unsigned char data[], unsigned long len); - -VOID_RETURN sha256_begin(sha256_ctx ctx[1]); -VOID_RETURN sha256_hash(const unsigned char data[], unsigned long len, sha256_ctx ctx[1]); -VOID_RETURN sha256_end(unsigned char hval[], sha256_ctx ctx[1]); -VOID_RETURN sha256(unsigned char hval[], const unsigned char data[], unsigned long len); - -#ifndef SHA_64BIT - -typedef struct -{ union - { sha256_ctx ctx256[1]; - } uu[1]; - uint_32t sha2_len; -} sha2_ctx; - -#define SHA2_MAX_DIGEST_SIZE SHA256_DIGEST_SIZE - -#else - -#define SHA384_DIGEST_SIZE 48 -#define SHA384_BLOCK_SIZE 128 -#define SHA512_DIGEST_SIZE 64 -#define SHA512_BLOCK_SIZE 128 -#define SHA2_MAX_DIGEST_SIZE SHA512_DIGEST_SIZE - -/* type to hold the SHA384 (and SHA512) context */ - -typedef struct -{ uint_64t count[2]; - uint_64t hash[8]; - uint_64t wbuf[16]; -} sha512_ctx; - -typedef sha512_ctx sha384_ctx; - -typedef struct -{ union - { sha256_ctx ctx256[1]; - sha512_ctx ctx512[1]; - } uu[1]; - uint_32t sha2_len; -} sha2_ctx; - -VOID_RETURN sha512_compile(sha512_ctx ctx[1]); - -VOID_RETURN sha384_begin(sha384_ctx ctx[1]); -#define sha384_hash sha512_hash -VOID_RETURN sha384_end(unsigned char hval[], sha384_ctx ctx[1]); -VOID_RETURN sha384(unsigned char hval[], const unsigned char data[], unsigned long len); - -VOID_RETURN sha512_begin(sha512_ctx ctx[1]); -VOID_RETURN sha512_hash(const unsigned char data[], unsigned long len, sha512_ctx ctx[1]); -VOID_RETURN sha512_end(unsigned char hval[], sha512_ctx ctx[1]); -VOID_RETURN sha512(unsigned char hval[], const unsigned char data[], unsigned long len); - -INT_RETURN sha2_begin(unsigned long size, sha2_ctx ctx[1]); -VOID_RETURN sha2_hash(const unsigned char data[], unsigned long len, sha2_ctx ctx[1]); -VOID_RETURN sha2_end(unsigned char hval[], sha2_ctx ctx[1]); -INT_RETURN sha2(unsigned char hval[], unsigned long size, const unsigned char data[], unsigned long len); - -#endif - -#if defined(__cplusplus) -} -#endif - -#endif +/* + --------------------------------------------------------------------------- + Copyright (c) 2002, Dr Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software is allowed (with or without + changes) provided that: + + 1. source code distributions include the above copyright notice, this + list of conditions and the following disclaimer; + + 2. binary distributions include the above copyright notice, this list + of conditions and the following disclaimer in their documentation; + + 3. the name of the copyright holder is not used to endorse products + built using this software without specific written permission. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + Issue Date: 01/08/2005 +*/ + +#ifndef _SHA2_H +#define _SHA2_H + +#include "Common/Tcdefs.h" +#include "Common/Endian.h" + +#define SHA_64BIT + +/* define the hash functions that you need */ +#define SHA_2 /* for dynamic hash length */ +#define SHA_224 +#define SHA_256 +#ifdef SHA_64BIT +# define SHA_384 +# define SHA_512 +# define NEED_UINT_64T +#endif + +#ifndef EXIT_SUCCESS +#define EXIT_SUCCESS 0 +#define EXIT_FAILURE 1 +#endif + +#define li_64(h) 0x##h##ull + +#define VOID_RETURN void +#define INT_RETURN int + +#if defined(__cplusplus) +extern "C" +{ +#endif + +/* Note that the following function prototypes are the same */ +/* for both the bit and byte oriented implementations. But */ +/* the length fields are in bytes or bits as is appropriate */ +/* for the version used. Bit sequences are arrays of bytes */ +/* in which bit sequence indexes increase from the most to */ +/* the least significant end of each byte */ + +#define SHA224_DIGEST_SIZE 28 +#define SHA224_BLOCK_SIZE 64 +#define SHA256_DIGEST_SIZE 32 +#define SHA256_BLOCK_SIZE 64 + +/* type to hold the SHA256 (and SHA224) context */ + +typedef struct +{ uint_32t count[2]; + uint_32t hash[8]; + uint_32t wbuf[16]; +} sha256_ctx; + +typedef sha256_ctx sha224_ctx; + +VOID_RETURN sha256_compile(sha256_ctx ctx[1]); + +VOID_RETURN sha224_begin(sha224_ctx ctx[1]); +#define sha224_hash sha256_hash +VOID_RETURN sha224_end(unsigned char hval[], sha224_ctx ctx[1]); +VOID_RETURN sha224(unsigned char hval[], const unsigned char data[], unsigned long len); + +VOID_RETURN sha256_begin(sha256_ctx ctx[1]); +VOID_RETURN sha256_hash(const unsigned char data[], unsigned long len, sha256_ctx ctx[1]); +VOID_RETURN sha256_end(unsigned char hval[], sha256_ctx ctx[1]); +VOID_RETURN sha256(unsigned char hval[], const unsigned char data[], unsigned long len); + +#ifndef SHA_64BIT + +typedef struct +{ union + { sha256_ctx ctx256[1]; + } uu[1]; + uint_32t sha2_len; +} sha2_ctx; + +#define SHA2_MAX_DIGEST_SIZE SHA256_DIGEST_SIZE + +#else + +#define SHA384_DIGEST_SIZE 48 +#define SHA384_BLOCK_SIZE 128 +#define SHA512_DIGEST_SIZE 64 +#define SHA512_BLOCK_SIZE 128 +#define SHA2_MAX_DIGEST_SIZE SHA512_DIGEST_SIZE + +/* type to hold the SHA384 (and SHA512) context */ + +typedef struct +{ uint_64t count[2]; + uint_64t hash[8]; + uint_64t wbuf[16]; +} sha512_ctx; + +typedef sha512_ctx sha384_ctx; + +typedef struct +{ union + { sha256_ctx ctx256[1]; + sha512_ctx ctx512[1]; + } uu[1]; + uint_32t sha2_len; +} sha2_ctx; + +VOID_RETURN sha512_compile(sha512_ctx ctx[1]); + +VOID_RETURN sha384_begin(sha384_ctx ctx[1]); +#define sha384_hash sha512_hash +VOID_RETURN sha384_end(unsigned char hval[], sha384_ctx ctx[1]); +VOID_RETURN sha384(unsigned char hval[], const unsigned char data[], unsigned long len); + +VOID_RETURN sha512_begin(sha512_ctx ctx[1]); +VOID_RETURN sha512_hash(const unsigned char data[], unsigned long len, sha512_ctx ctx[1]); +VOID_RETURN sha512_end(unsigned char hval[], sha512_ctx ctx[1]); +VOID_RETURN sha512(unsigned char hval[], const unsigned char data[], unsigned long len); + +INT_RETURN sha2_begin(unsigned long size, sha2_ctx ctx[1]); +VOID_RETURN sha2_hash(const unsigned char data[], unsigned long len, sha2_ctx ctx[1]); +VOID_RETURN sha2_end(unsigned char hval[], sha2_ctx ctx[1]); +INT_RETURN sha2(unsigned char hval[], unsigned long size, const unsigned char data[], unsigned long len); + +#endif + +#if defined(__cplusplus) +} +#endif + +#endif diff --git a/src/Crypto/Sha2Small.c b/src/Crypto/Sha2Small.c index 9acd1b83..539ff05d 100644 --- a/src/Crypto/Sha2Small.c +++ b/src/Crypto/Sha2Small.c @@ -10,237 +10,237 @@ * */ -/* Adapted for VeraCrypt */ - -#include -#include "Common/Tcdefs.h" -#include "Common/Endian.h" -#include "Sha2Small.h" - -#pragma optimize ("tl", on) - -typedef unsigned __int32 uint32; -typedef unsigned __int8 byte; - -#include -#pragma intrinsic(_lrotr) -#define RORc(x,n) _lrotr(x,n) - -/******************************************************************************/ - -/* - The K array - */ - -static const uint32 K[64] = { - 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, - 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, - 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, - 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, - 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, - 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, - 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, - 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, - 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, - 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, - 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, - 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, - 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL -}; - -/* - Various logical functions - */ -#define Ch(x,y,z) (z ^ (x & (y ^ z))) -#define Maj(x,y,z) (((x | y) & z) | (x & y)) -#define S(x, n) RORc((x),(n)) -#define R(x, n) ((x)>>(n)) -#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22)) -#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25)) -#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3)) -#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10)) - -#define STORE32H(x, y, i) { \ -(y)[i] = (unsigned char)(((x)>>24)); \ -(y)[i+1] = (unsigned char)(((x)>>16)); \ -(y)[i+2] = (unsigned char)(((x)>>8)); \ -(y)[i+3] = (unsigned char)((x)); \ -} - -#define LOAD32H(x, y, i) { \ -x = ((unsigned long)((y)[i])<<24) | \ -((unsigned long)((y)[i+1])<<16) | \ -((unsigned long)((y)[i+2])<<8) | \ -((unsigned long)((y)[i+3])); \ -} - -/* - compress 512-bits - */ -static void sha256_compress(sha256_ctx * ctx, unsigned char *buf) -{ - - uint32 S[8], W[64], t0, t1; - uint32 t, w2, w15; - int i; - -/* - copy state into S - */ - for (i = 0; i < 8; i++) { - S[i] = ctx->state[i]; - } - -/* - copy the state into 512-bits into W[0..15] - */ - for (i = 0; i < 16; i++) { - LOAD32H(W[i], buf , (4*i)); - } - -/* - fill W[16..63] - */ - for (i = 16; i < 64; i++) { - w2 = W[i - 2]; - w15 = W[i - 15]; - W[i] = Gamma1(w2) + W[i - 7] + Gamma0(w15) + W[i - 16]; - } - -/* - Compress - */ - -#define RND(a,b,c,d,e,f,g,h,i) \ - t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \ - t1 = Sigma0(a) + Maj(a, b, c); \ - d += t0; \ - h = t0 + t1; - - for (i = 0; i < 64; ++i) { - RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i); - t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4]; - S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t; - } - -/* - feedback - */ - for (i = 0; i < 8; i++) { - ctx->state[i] += S[i]; - } - -} - -/* - init the sha256 state - */ -VOID_RETURN sha256_begin(sha256_ctx* ctx) -{ - ctx->curlen = 0; - ctx->state[0] = 0x6A09E667UL; - ctx->state[1] = 0xBB67AE85UL; - ctx->state[2] = 0x3C6EF372UL; - ctx->state[3] = 0xA54FF53AUL; - ctx->state[4] = 0x510E527FUL; - ctx->state[5] = 0x9B05688CUL; - ctx->state[6] = 0x1F83D9ABUL; - ctx->state[7] = 0x5BE0CD19UL; - ctx->highLength = 0; - ctx->lowLength = 0; -} - -VOID_RETURN sha256_hash(unsigned char* data, unsigned int len, sha256_ctx* ctx) -{ - uint32 n; - while (len > 0) { - if (ctx->curlen == 0 && len >= 64) { - sha256_compress(ctx, (unsigned char *)data); - - n = ctx->lowLength + 512; - if (n < ctx->lowLength) { - ctx->highLength++; - } - ctx->lowLength = n; - data += 64; - len -= 64; - } else { - n = min(len, 64 - ctx->curlen); - memcpy(ctx->buf + ctx->curlen, data, (size_t)n); - ctx->curlen += (unsigned int) n; - data += (unsigned int) n; - len -= (unsigned int) n; - - if (ctx->curlen == 64) { - sha256_compress (ctx, ctx->buf); - - n = ctx->lowLength + 512; - if (n < ctx->lowLength) { - ctx->highLength++; - } - ctx->lowLength = n; - ctx->curlen = 0; - } - } - } - return; -} - -VOID_RETURN sha256_end(unsigned char* hval, sha256_ctx* ctx) -{ - int i; - uint32 n; - -/* - increase the length of the message - */ - - n = ctx->lowLength + (ctx->curlen << 3); - if (n < ctx->lowLength) { - ctx->highLength++; - } - ctx->highLength += (ctx->curlen >> 29); - ctx->lowLength = n; - -/* - append the '1' bit - */ - ctx->buf[ctx->curlen++] = (unsigned char)0x80; - -/* - if the length is currently above 56 bytes we append zeros then compress. - Then we can fall back to padding zeros and length encoding like normal. - */ - if (ctx->curlen > 56) { - while (ctx->curlen < 64) { - ctx->buf[ctx->curlen++] = (unsigned char)0; - } - sha256_compress(ctx, ctx->buf); - ctx->curlen = 0; - } - -/* - pad upto 56 bytes of zeroes - */ - while (ctx->curlen < 56) { - ctx->buf[ctx->curlen++] = (unsigned char)0; - } - -/* - store length - */ - - STORE32H(ctx->highLength, ctx->buf, 56); - STORE32H(ctx->lowLength, ctx->buf, 60); - - sha256_compress(ctx, ctx->buf); - -/* - copy output - */ - for (i = 0; i < 8; i++) { - STORE32H(ctx->state[i], hval, (4*i)); - } -} - -/******************************************************************************/ +/* Adapted for VeraCrypt */ + +#include +#include "Common/Tcdefs.h" +#include "Common/Endian.h" +#include "Sha2Small.h" + +#pragma optimize ("tl", on) + +typedef unsigned __int32 uint32; +typedef unsigned __int8 byte; + +#include +#pragma intrinsic(_lrotr) +#define RORc(x,n) _lrotr(x,n) + +/******************************************************************************/ + +/* + The K array + */ + +static const uint32 K[64] = { + 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, + 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, + 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, + 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, + 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, + 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, + 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, + 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, + 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, + 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, + 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, + 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, + 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL +}; + +/* + Various logical functions + */ +#define Ch(x,y,z) (z ^ (x & (y ^ z))) +#define Maj(x,y,z) (((x | y) & z) | (x & y)) +#define S(x, n) RORc((x),(n)) +#define R(x, n) ((x)>>(n)) +#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22)) +#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25)) +#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3)) +#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10)) + +#define STORE32H(x, y, i) { \ +(y)[i] = (unsigned char)(((x)>>24)); \ +(y)[i+1] = (unsigned char)(((x)>>16)); \ +(y)[i+2] = (unsigned char)(((x)>>8)); \ +(y)[i+3] = (unsigned char)((x)); \ +} + +#define LOAD32H(x, y, i) { \ +x = ((unsigned long)((y)[i])<<24) | \ +((unsigned long)((y)[i+1])<<16) | \ +((unsigned long)((y)[i+2])<<8) | \ +((unsigned long)((y)[i+3])); \ +} + +/* + compress 512-bits + */ +static void sha256_compress(sha256_ctx * ctx, unsigned char *buf) +{ + + uint32 S[8], W[64], t0, t1; + uint32 t, w2, w15; + int i; + +/* + copy state into S + */ + for (i = 0; i < 8; i++) { + S[i] = ctx->state[i]; + } + +/* + copy the state into 512-bits into W[0..15] + */ + for (i = 0; i < 16; i++) { + LOAD32H(W[i], buf , (4*i)); + } + +/* + fill W[16..63] + */ + for (i = 16; i < 64; i++) { + w2 = W[i - 2]; + w15 = W[i - 15]; + W[i] = Gamma1(w2) + W[i - 7] + Gamma0(w15) + W[i - 16]; + } + +/* + Compress + */ + +#define RND(a,b,c,d,e,f,g,h,i) \ + t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \ + t1 = Sigma0(a) + Maj(a, b, c); \ + d += t0; \ + h = t0 + t1; + + for (i = 0; i < 64; ++i) { + RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i); + t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4]; + S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t; + } + +/* + feedback + */ + for (i = 0; i < 8; i++) { + ctx->state[i] += S[i]; + } + +} + +/* + init the sha256 state + */ +VOID_RETURN sha256_begin(sha256_ctx* ctx) +{ + ctx->curlen = 0; + ctx->state[0] = 0x6A09E667UL; + ctx->state[1] = 0xBB67AE85UL; + ctx->state[2] = 0x3C6EF372UL; + ctx->state[3] = 0xA54FF53AUL; + ctx->state[4] = 0x510E527FUL; + ctx->state[5] = 0x9B05688CUL; + ctx->state[6] = 0x1F83D9ABUL; + ctx->state[7] = 0x5BE0CD19UL; + ctx->highLength = 0; + ctx->lowLength = 0; +} + +VOID_RETURN sha256_hash(unsigned char* data, unsigned int len, sha256_ctx* ctx) +{ + uint32 n; + while (len > 0) { + if (ctx->curlen == 0 && len >= 64) { + sha256_compress(ctx, (unsigned char *)data); + + n = ctx->lowLength + 512; + if (n < ctx->lowLength) { + ctx->highLength++; + } + ctx->lowLength = n; + data += 64; + len -= 64; + } else { + n = min(len, 64 - ctx->curlen); + memcpy(ctx->buf + ctx->curlen, data, (size_t)n); + ctx->curlen += (unsigned int) n; + data += (unsigned int) n; + len -= (unsigned int) n; + + if (ctx->curlen == 64) { + sha256_compress (ctx, ctx->buf); + + n = ctx->lowLength + 512; + if (n < ctx->lowLength) { + ctx->highLength++; + } + ctx->lowLength = n; + ctx->curlen = 0; + } + } + } + return; +} + +VOID_RETURN sha256_end(unsigned char* hval, sha256_ctx* ctx) +{ + int i; + uint32 n; + +/* + increase the length of the message + */ + + n = ctx->lowLength + (ctx->curlen << 3); + if (n < ctx->lowLength) { + ctx->highLength++; + } + ctx->highLength += (ctx->curlen >> 29); + ctx->lowLength = n; + +/* + append the '1' bit + */ + ctx->buf[ctx->curlen++] = (unsigned char)0x80; + +/* + if the length is currently above 56 bytes we append zeros then compress. + Then we can fall back to padding zeros and length encoding like normal. + */ + if (ctx->curlen > 56) { + while (ctx->curlen < 64) { + ctx->buf[ctx->curlen++] = (unsigned char)0; + } + sha256_compress(ctx, ctx->buf); + ctx->curlen = 0; + } + +/* + pad upto 56 bytes of zeroes + */ + while (ctx->curlen < 56) { + ctx->buf[ctx->curlen++] = (unsigned char)0; + } + +/* + store length + */ + + STORE32H(ctx->highLength, ctx->buf, 56); + STORE32H(ctx->lowLength, ctx->buf, 60); + + sha256_compress(ctx, ctx->buf); + +/* + copy output + */ + for (i = 0; i < 8; i++) { + STORE32H(ctx->state[i], hval, (4*i)); + } +} + +/******************************************************************************/ diff --git a/src/Crypto/Sha2Small.h b/src/Crypto/Sha2Small.h index 2b79eaf4..1b5c106e 100644 --- a/src/Crypto/Sha2Small.h +++ b/src/Crypto/Sha2Small.h @@ -12,21 +12,21 @@ /* Adapted for VeraCrypt */ -#ifndef _SHA2_SMALL_H +#ifndef _SHA2_SMALL_H #define _SHA2_SMALL_H -#include "Common/Tcdefs.h" +#include "Common/Tcdefs.h" #include "Common/Endian.h" -#define SHA256_DIGEST_SIZE 32 +#define SHA256_DIGEST_SIZE 32 #define SHA256_BLOCK_SIZE 64 -#define VOID_RETURN void -#define INT_RETURN int - -#if defined(__cplusplus) -extern "C" -{ +#define VOID_RETURN void +#define INT_RETURN int + +#if defined(__cplusplus) +extern "C" +{ #endif typedef struct { @@ -40,12 +40,12 @@ typedef struct { /******************************************************************************/ -VOID_RETURN sha256_begin(sha256_ctx* ctx); -VOID_RETURN sha256_hash(unsigned char* data, unsigned int len, sha256_ctx* ctx); +VOID_RETURN sha256_begin(sha256_ctx* ctx); +VOID_RETURN sha256_hash(unsigned char* data, unsigned int len, sha256_ctx* ctx); VOID_RETURN sha256_end(unsigned char* hval, sha256_ctx* ctx); -#if defined(__cplusplus) -} +#if defined(__cplusplus) +} #endif /******************************************************************************/ diff --git a/src/Crypto/Sources b/src/Crypto/Sources index 9b1b988c..6eb7b7b4 100644 --- a/src/Crypto/Sources +++ b/src/Crypto/Sources @@ -1,20 +1,20 @@ -TARGETNAME=Crypto -TARGETTYPE=DRIVER_LIBRARY - -INCLUDES = .. - -NTTARGETFILES = \ - "$(OBJ_PATH)\$(O)\Aes_$(TC_ARCH).obj" \ - "$(OBJ_PATH)\$(O)\Aes_hw_cpu.obj" - -SOURCES = \ - Aes_$(TC_ARCH).asm \ - Aes_hw_cpu.asm \ - Aeskey.c \ - Aestab.c \ - cpu.c \ - Rmd160.c \ - Serpent.c \ - Sha2.c \ - Twofish.c \ - Whirlpool.c +TARGETNAME=Crypto +TARGETTYPE=DRIVER_LIBRARY + +INCLUDES = .. + +NTTARGETFILES = \ + "$(OBJ_PATH)\$(O)\Aes_$(TC_ARCH).obj" \ + "$(OBJ_PATH)\$(O)\Aes_hw_cpu.obj" + +SOURCES = \ + Aes_$(TC_ARCH).asm \ + Aes_hw_cpu.asm \ + Aeskey.c \ + Aestab.c \ + cpu.c \ + Rmd160.c \ + Serpent.c \ + Sha2.c \ + Twofish.c \ + Whirlpool.c diff --git a/src/Crypto/Twofish.c b/src/Crypto/Twofish.c index 2273ac5e..7c58c91e 100644 --- a/src/Crypto/Twofish.c +++ b/src/Crypto/Twofish.c @@ -1,549 +1,549 @@ -/* - --------------------------------------------------------------------------- - Copyright (c) 1999, Dr Brian Gladman, Worcester, UK. All rights reserved. - - LICENSE TERMS - - The free distribution and use of this software is allowed (with or without - changes) provided that: - - 1. source code distributions include the above copyright notice, this - list of conditions and the following disclaimer; - - 2. binary distributions include the above copyright notice, this list - of conditions and the following disclaimer in their documentation; - - 3. the name of the copyright holder is not used to endorse products - built using this software without specific written permission. - - DISCLAIMER - - This software is provided 'as is' with no explicit or implied warranties - in respect of its properties, including, but not limited to, correctness - and/or fitness for purpose. - --------------------------------------------------------------------------- - - My thanks to Doug Whiting and Niels Ferguson for comments that led - to improvements in this implementation. - - Issue Date: 14th January 1999 -*/ - -/* Adapted for TrueCrypt */ -/* Adapted for VeraCrypt */ - - -#ifdef TC_WINDOWS_BOOT -#pragma optimize ("tl", on) -#endif - -#include "Twofish.h" -#include "Common/Endian.h" - -#define Q_TABLES -#define M_TABLE - -#if !defined (TC_MINIMIZE_CODE_SIZE) || defined (TC_WINDOWS_BOOT_TWOFISH) -# define MK_TABLE -# define ONE_STEP -#endif - -/* finite field arithmetic for GF(2**8) with the modular */ -/* polynomial x^8 + x^6 + x^5 + x^3 + 1 (0x169) */ - -#define G_M 0x0169 - -static u1byte tab_5b[4] = { 0, G_M >> 2, G_M >> 1, (G_M >> 1) ^ (G_M >> 2) }; -static u1byte tab_ef[4] = { 0, (G_M >> 1) ^ (G_M >> 2), G_M >> 1, G_M >> 2 }; - -#define ffm_01(x) (x) -#define ffm_5b(x) ((x) ^ ((x) >> 2) ^ tab_5b[(x) & 3]) -#define ffm_ef(x) ((x) ^ ((x) >> 1) ^ ((x) >> 2) ^ tab_ef[(x) & 3]) - -static u1byte ror4[16] = { 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15 }; -static u1byte ashx[16] = { 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7 }; - -static u1byte qt0[2][16] = -{ { 8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4 }, - { 2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5 } -}; - -static u1byte qt1[2][16] = -{ { 14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13 }, - { 1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8 } -}; - -static u1byte qt2[2][16] = -{ { 11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1 }, - { 4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15 } -}; - -static u1byte qt3[2][16] = -{ { 13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10 }, - { 11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10 } -}; - -static u1byte qp(const u4byte n, const u1byte x) -{ u1byte a0, a1, a2, a3, a4, b0, b1, b2, b3, b4; - - a0 = x >> 4; b0 = x & 15; - a1 = a0 ^ b0; b1 = ror4[b0] ^ ashx[a0]; - a2 = qt0[n][a1]; b2 = qt1[n][b1]; - a3 = a2 ^ b2; b3 = ror4[b2] ^ ashx[a2]; - a4 = qt2[n][a3]; b4 = qt3[n][b3]; - return (b4 << 4) | a4; -}; - -#ifdef Q_TABLES - -static u4byte qt_gen = 0; -static u1byte q_tab[2][256]; - -#define q(n,x) q_tab[n][x] - -static void gen_qtab(void) -{ u4byte i; - - for(i = 0; i < 256; ++i) - { - q(0,i) = qp(0, (u1byte)i); - q(1,i) = qp(1, (u1byte)i); - } -}; - -#else - -#define q(n,x) qp(n, x) - -#endif - -#ifdef M_TABLE - -static u4byte mt_gen = 0; -static u4byte m_tab[4][256]; - -static void gen_mtab(void) -{ u4byte i, f01, f5b, fef; - - for(i = 0; i < 256; ++i) - { - f01 = q(1,i); f5b = ffm_5b(f01); fef = ffm_ef(f01); - m_tab[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); - m_tab[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); - - f01 = q(0,i); f5b = ffm_5b(f01); fef = ffm_ef(f01); - m_tab[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); - m_tab[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); - } -}; - -#define mds(n,x) m_tab[n][x] - -#else - -#define fm_00 ffm_01 -#define fm_10 ffm_5b -#define fm_20 ffm_ef -#define fm_30 ffm_ef -#define q_0(x) q(1,x) - -#define fm_01 ffm_ef -#define fm_11 ffm_ef -#define fm_21 ffm_5b -#define fm_31 ffm_01 -#define q_1(x) q(0,x) - -#define fm_02 ffm_5b -#define fm_12 ffm_ef -#define fm_22 ffm_01 -#define fm_32 ffm_ef -#define q_2(x) q(1,x) - -#define fm_03 ffm_5b -#define fm_13 ffm_01 -#define fm_23 ffm_ef -#define fm_33 ffm_5b -#define q_3(x) q(0,x) - -#define f_0(n,x) ((u4byte)fm_0##n(x)) -#define f_1(n,x) ((u4byte)fm_1##n(x) << 8) -#define f_2(n,x) ((u4byte)fm_2##n(x) << 16) -#define f_3(n,x) ((u4byte)fm_3##n(x) << 24) - -#define mds(n,x) f_0(n,q_##n(x)) ^ f_1(n,q_##n(x)) ^ f_2(n,q_##n(x)) ^ f_3(n,q_##n(x)) - -#endif - -static u4byte h_fun(TwofishInstance *instance, const u4byte x, const u4byte key[]) -{ u4byte b0, b1, b2, b3; - -#ifndef M_TABLE - u4byte m5b_b0, m5b_b1, m5b_b2, m5b_b3; - u4byte mef_b0, mef_b1, mef_b2, mef_b3; -#endif - - b0 = extract_byte(x, 0); b1 = extract_byte(x, 1); b2 = extract_byte(x, 2); b3 = extract_byte(x, 3); - - switch(instance->k_len) - { - case 4: b0 = q(1, (u1byte) b0) ^ extract_byte(key[3],0); - b1 = q(0, (u1byte) b1) ^ extract_byte(key[3],1); - b2 = q(0, (u1byte) b2) ^ extract_byte(key[3],2); - b3 = q(1, (u1byte) b3) ^ extract_byte(key[3],3); - case 3: b0 = q(1, (u1byte) b0) ^ extract_byte(key[2],0); - b1 = q(1, (u1byte) b1) ^ extract_byte(key[2],1); - b2 = q(0, (u1byte) b2) ^ extract_byte(key[2],2); - b3 = q(0, (u1byte) b3) ^ extract_byte(key[2],3); - case 2: b0 = q(0, (u1byte) (q(0, (u1byte) b0) ^ extract_byte(key[1],0))) ^ extract_byte(key[0],0); - b1 = q(0, (u1byte) (q(1, (u1byte) b1) ^ extract_byte(key[1],1))) ^ extract_byte(key[0],1); - b2 = q(1, (u1byte) (q(0, (u1byte) b2) ^ extract_byte(key[1],2))) ^ extract_byte(key[0],2); - b3 = q(1, (u1byte) (q(1, (u1byte) b3) ^ extract_byte(key[1],3))) ^ extract_byte(key[0],3); - } -#ifdef M_TABLE - - return mds(0, b0) ^ mds(1, b1) ^ mds(2, b2) ^ mds(3, b3); - -#else - - b0 = q(1, (u1byte) b0); b1 = q(0, (u1byte) b1); b2 = q(1, (u1byte) b2); b3 = q(0, (u1byte) b3); - m5b_b0 = ffm_5b(b0); m5b_b1 = ffm_5b(b1); m5b_b2 = ffm_5b(b2); m5b_b3 = ffm_5b(b3); - mef_b0 = ffm_ef(b0); mef_b1 = ffm_ef(b1); mef_b2 = ffm_ef(b2); mef_b3 = ffm_ef(b3); - b0 ^= mef_b1 ^ m5b_b2 ^ m5b_b3; b3 ^= m5b_b0 ^ mef_b1 ^ mef_b2; - b2 ^= mef_b0 ^ m5b_b1 ^ mef_b3; b1 ^= mef_b0 ^ mef_b2 ^ m5b_b3; - - return b0 | (b3 << 8) | (b2 << 16) | (b1 << 24); - -#endif -}; - -#ifdef MK_TABLE - -#ifdef ONE_STEP -//u4byte mk_tab[4][256]; -#else -static u1byte sb[4][256]; -#endif - -#define q20(x) q(0,q(0,x) ^ extract_byte(key[1],0)) ^ extract_byte(key[0],0) -#define q21(x) q(0,q(1,x) ^ extract_byte(key[1],1)) ^ extract_byte(key[0],1) -#define q22(x) q(1,q(0,x) ^ extract_byte(key[1],2)) ^ extract_byte(key[0],2) -#define q23(x) q(1,q(1,x) ^ extract_byte(key[1],3)) ^ extract_byte(key[0],3) - -#define q30(x) q(0,q(0,q(1, x) ^ extract_byte(key[2],0)) ^ extract_byte(key[1],0)) ^ extract_byte(key[0],0) -#define q31(x) q(0,q(1,q(1, x) ^ extract_byte(key[2],1)) ^ extract_byte(key[1],1)) ^ extract_byte(key[0],1) -#define q32(x) q(1,q(0,q(0, x) ^ extract_byte(key[2],2)) ^ extract_byte(key[1],2)) ^ extract_byte(key[0],2) -#define q33(x) q(1,q(1,q(0, x) ^ extract_byte(key[2],3)) ^ extract_byte(key[1],3)) ^ extract_byte(key[0],3) - -#define q40(x) q(0,q(0,q(1, q(1, x) ^ extract_byte(key[3],0)) ^ extract_byte(key[2],0)) ^ extract_byte(key[1],0)) ^ extract_byte(key[0],0) -#define q41(x) q(0,q(1,q(1, q(0, x) ^ extract_byte(key[3],1)) ^ extract_byte(key[2],1)) ^ extract_byte(key[1],1)) ^ extract_byte(key[0],1) -#define q42(x) q(1,q(0,q(0, q(0, x) ^ extract_byte(key[3],2)) ^ extract_byte(key[2],2)) ^ extract_byte(key[1],2)) ^ extract_byte(key[0],2) -#define q43(x) q(1,q(1,q(0, q(1, x) ^ extract_byte(key[3],3)) ^ extract_byte(key[2],3)) ^ extract_byte(key[1],3)) ^ extract_byte(key[0],3) - -static void gen_mk_tab(TwofishInstance *instance, u4byte key[]) -{ u4byte i; - u1byte by; - - u4byte *mk_tab = instance->mk_tab; - - switch(instance->k_len) - { - case 2: for(i = 0; i < 256; ++i) - { - by = (u1byte)i; -#ifdef ONE_STEP - mk_tab[0 + 4*i] = mds(0, q20(by)); mk_tab[1 + 4*i] = mds(1, q21(by)); - mk_tab[2 + 4*i] = mds(2, q22(by)); mk_tab[3 + 4*i] = mds(3, q23(by)); -#else - sb[0][i] = q20(by); sb[1][i] = q21(by); - sb[2][i] = q22(by); sb[3][i] = q23(by); -#endif - } - break; - - case 3: for(i = 0; i < 256; ++i) - { - by = (u1byte)i; -#ifdef ONE_STEP - mk_tab[0 + 4*i] = mds(0, q30(by)); mk_tab[1 + 4*i] = mds(1, q31(by)); - mk_tab[2 + 4*i] = mds(2, q32(by)); mk_tab[3 + 4*i] = mds(3, q33(by)); -#else - sb[0][i] = q30(by); sb[1][i] = q31(by); - sb[2][i] = q32(by); sb[3][i] = q33(by); -#endif - } - break; - - case 4: for(i = 0; i < 256; ++i) - { - by = (u1byte)i; -#ifdef ONE_STEP - mk_tab[0 + 4*i] = mds(0, q40(by)); mk_tab[1 + 4*i] = mds(1, q41(by)); - mk_tab[2 + 4*i] = mds(2, q42(by)); mk_tab[3 + 4*i] = mds(3, q43(by)); -#else - sb[0][i] = q40(by); sb[1][i] = q41(by); - sb[2][i] = q42(by); sb[3][i] = q43(by); -#endif - } - } -}; - -# ifdef ONE_STEP -# define g0_fun(x) ( mk_tab[0 + 4*extract_byte(x,0)] ^ mk_tab[1 + 4*extract_byte(x,1)] \ - ^ mk_tab[2 + 4*extract_byte(x,2)] ^ mk_tab[3 + 4*extract_byte(x,3)] ) -# define g1_fun(x) ( mk_tab[0 + 4*extract_byte(x,3)] ^ mk_tab[1 + 4*extract_byte(x,0)] \ - ^ mk_tab[2 + 4*extract_byte(x,1)] ^ mk_tab[3 + 4*extract_byte(x,2)] ) - - -# else -# define g0_fun(x) ( mds(0, sb[0][extract_byte(x,0)]) ^ mds(1, sb[1][extract_byte(x,1)]) \ - ^ mds(2, sb[2][extract_byte(x,2)]) ^ mds(3, sb[3][extract_byte(x,3)]) ) -# define g1_fun(x) ( mds(0, sb[0][extract_byte(x,3)]) ^ mds(1, sb[1][extract_byte(x,0)]) \ - ^ mds(2, sb[2][extract_byte(x,1)]) ^ mds(3, sb[3][extract_byte(x,2)]) ) -# endif - -#else - -#define g0_fun(x) h_fun(instance, x, instance->s_key) -#define g1_fun(x) h_fun(instance, rotl(x,8), instance->s_key) - -#endif - -/* The (12,8) Reed Soloman code has the generator polynomial - - g(x) = x^4 + (a + 1/a) * x^3 + a * x^2 + (a + 1/a) * x + 1 - -where the coefficients are in the finite field GF(2^8) with a -modular polynomial a^8 + a^6 + a^3 + a^2 + 1. To generate the -remainder we have to start with a 12th order polynomial with our -eight input bytes as the coefficients of the 4th to 11th terms. -That is: - - m[7] * x^11 + m[6] * x^10 ... + m[0] * x^4 + 0 * x^3 +... + 0 - -We then multiply the generator polynomial by m[7] * x^7 and subtract -it - xor in GF(2^8) - from the above to eliminate the x^7 term (the -artihmetic on the coefficients is done in GF(2^8). We then multiply -the generator polynomial by x^6 * coeff(x^10) and use this to remove -the x^10 term. We carry on in this way until the x^4 term is removed -so that we are left with: - - r[3] * x^3 + r[2] * x^2 + r[1] 8 x^1 + r[0] - -which give the resulting 4 bytes of the remainder. This is equivalent -to the matrix multiplication in the Twofish description but much faster -to implement. - -*/ - -#define G_MOD 0x0000014d - -static u4byte mds_rem(u4byte p0, u4byte p1) -{ u4byte i, t, u; - - for(i = 0; i < 8; ++i) - { - t = p1 >> 24; // get most significant coefficient - - p1 = (p1 << 8) | (p0 >> 24); p0 <<= 8; // shift others up - - // multiply t by a (the primitive element - i.e. left shift) - - u = (t << 1); - - if(t & 0x80) // subtract modular polynomial on overflow - - u ^= G_MOD; - - p1 ^= t ^ (u << 16); // remove t * (a * x^2 + 1) - - u ^= (t >> 1); // form u = a * t + t / a = t * (a + 1 / a); - - if(t & 0x01) // add the modular polynomial on underflow - - u ^= G_MOD >> 1; - - p1 ^= (u << 24) | (u << 8); // remove t * (a + 1/a) * (x^3 + x) - } - - return p1; -}; - -/* initialise the key schedule from the user supplied key */ - -u4byte *twofish_set_key(TwofishInstance *instance, const u4byte in_key[]) -{ u4byte i, a, b, me_key[4], mo_key[4]; - u4byte *l_key, *s_key; - - l_key = instance->l_key; - s_key = instance->s_key; - -#ifdef Q_TABLES - if(!qt_gen) - { - gen_qtab(); qt_gen = 1; - } -#endif - -#ifdef M_TABLE - if(!mt_gen) - { - gen_mtab(); mt_gen = 1; - } -#endif - - instance->k_len = 4; - - for(i = 0; i < instance->k_len; ++i) - { - a = LE32(in_key[i + i]); me_key[i] = a; - b = LE32(in_key[i + i + 1]); mo_key[i] = b; - s_key[instance->k_len - i - 1] = mds_rem(a, b); - } - - for(i = 0; i < 40; i += 2) - { - a = 0x01010101 * i; b = a + 0x01010101; - a = h_fun(instance, a, me_key); - b = rotl(h_fun(instance, b, mo_key), 8); - l_key[i] = a + b; - l_key[i + 1] = rotl(a + 2 * b, 9); - } - -#ifdef MK_TABLE - gen_mk_tab(instance, s_key); -#endif - - return l_key; -}; - -/* encrypt a block of text */ - -#ifndef TC_MINIMIZE_CODE_SIZE - -#define f_rnd(i) \ - t1 = g1_fun(blk[1]); t0 = g0_fun(blk[0]); \ - blk[2] = rotr(blk[2] ^ (t0 + t1 + l_key[4 * (i) + 8]), 1); \ - blk[3] = rotl(blk[3], 1) ^ (t0 + 2 * t1 + l_key[4 * (i) + 9]); \ - t1 = g1_fun(blk[3]); t0 = g0_fun(blk[2]); \ - blk[0] = rotr(blk[0] ^ (t0 + t1 + l_key[4 * (i) + 10]), 1); \ - blk[1] = rotl(blk[1], 1) ^ (t0 + 2 * t1 + l_key[4 * (i) + 11]) - -void twofish_encrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte out_blk[]) -{ u4byte t0, t1, blk[4]; - - u4byte *l_key = instance->l_key; - u4byte *mk_tab = instance->mk_tab; - - blk[0] = LE32(in_blk[0]) ^ l_key[0]; - blk[1] = LE32(in_blk[1]) ^ l_key[1]; - blk[2] = LE32(in_blk[2]) ^ l_key[2]; - blk[3] = LE32(in_blk[3]) ^ l_key[3]; - - f_rnd(0); f_rnd(1); f_rnd(2); f_rnd(3); - f_rnd(4); f_rnd(5); f_rnd(6); f_rnd(7); - - out_blk[0] = LE32(blk[2] ^ l_key[4]); - out_blk[1] = LE32(blk[3] ^ l_key[5]); - out_blk[2] = LE32(blk[0] ^ l_key[6]); - out_blk[3] = LE32(blk[1] ^ l_key[7]); -}; - -#else // TC_MINIMIZE_CODE_SIZE - -void twofish_encrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte out_blk[]) -{ u4byte t0, t1, blk[4]; - - u4byte *l_key = instance->l_key; -#ifdef TC_WINDOWS_BOOT_TWOFISH - u4byte *mk_tab = instance->mk_tab; -#endif - int i; - - blk[0] = LE32(in_blk[0]) ^ l_key[0]; - blk[1] = LE32(in_blk[1]) ^ l_key[1]; - blk[2] = LE32(in_blk[2]) ^ l_key[2]; - blk[3] = LE32(in_blk[3]) ^ l_key[3]; - - for (i = 0; i <= 7; ++i) - { - t1 = g1_fun(blk[1]); t0 = g0_fun(blk[0]); - blk[2] = rotr(blk[2] ^ (t0 + t1 + l_key[4 * (i) + 8]), 1); - blk[3] = rotl(blk[3], 1) ^ (t0 + 2 * t1 + l_key[4 * (i) + 9]); - t1 = g1_fun(blk[3]); t0 = g0_fun(blk[2]); - blk[0] = rotr(blk[0] ^ (t0 + t1 + l_key[4 * (i) + 10]), 1); - blk[1] = rotl(blk[1], 1) ^ (t0 + 2 * t1 + l_key[4 * (i) + 11]); - } - - out_blk[0] = LE32(blk[2] ^ l_key[4]); - out_blk[1] = LE32(blk[3] ^ l_key[5]); - out_blk[2] = LE32(blk[0] ^ l_key[6]); - out_blk[3] = LE32(blk[1] ^ l_key[7]); -}; - -#endif // TC_MINIMIZE_CODE_SIZE - -/* decrypt a block of text */ - -#ifndef TC_MINIMIZE_CODE_SIZE - -#define i_rnd(i) \ - t1 = g1_fun(blk[1]); t0 = g0_fun(blk[0]); \ - blk[2] = rotl(blk[2], 1) ^ (t0 + t1 + l_key[4 * (i) + 10]); \ - blk[3] = rotr(blk[3] ^ (t0 + 2 * t1 + l_key[4 * (i) + 11]), 1); \ - t1 = g1_fun(blk[3]); t0 = g0_fun(blk[2]); \ - blk[0] = rotl(blk[0], 1) ^ (t0 + t1 + l_key[4 * (i) + 8]); \ - blk[1] = rotr(blk[1] ^ (t0 + 2 * t1 + l_key[4 * (i) + 9]), 1) - -void twofish_decrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte out_blk[4]) -{ u4byte t0, t1, blk[4]; - - u4byte *l_key = instance->l_key; - u4byte *mk_tab = instance->mk_tab; - - blk[0] = LE32(in_blk[0]) ^ l_key[4]; - blk[1] = LE32(in_blk[1]) ^ l_key[5]; - blk[2] = LE32(in_blk[2]) ^ l_key[6]; - blk[3] = LE32(in_blk[3]) ^ l_key[7]; - - i_rnd(7); i_rnd(6); i_rnd(5); i_rnd(4); - i_rnd(3); i_rnd(2); i_rnd(1); i_rnd(0); - - out_blk[0] = LE32(blk[2] ^ l_key[0]); - out_blk[1] = LE32(blk[3] ^ l_key[1]); - out_blk[2] = LE32(blk[0] ^ l_key[2]); - out_blk[3] = LE32(blk[1] ^ l_key[3]); -}; - -#else // TC_MINIMIZE_CODE_SIZE - -void twofish_decrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte out_blk[4]) -{ u4byte t0, t1, blk[4]; - - u4byte *l_key = instance->l_key; -#ifdef TC_WINDOWS_BOOT_TWOFISH - u4byte *mk_tab = instance->mk_tab; -#endif - int i; - - blk[0] = LE32(in_blk[0]) ^ l_key[4]; - blk[1] = LE32(in_blk[1]) ^ l_key[5]; - blk[2] = LE32(in_blk[2]) ^ l_key[6]; - blk[3] = LE32(in_blk[3]) ^ l_key[7]; - - for (i = 7; i >= 0; --i) - { - t1 = g1_fun(blk[1]); t0 = g0_fun(blk[0]); - blk[2] = rotl(blk[2], 1) ^ (t0 + t1 + l_key[4 * (i) + 10]); - blk[3] = rotr(blk[3] ^ (t0 + 2 * t1 + l_key[4 * (i) + 11]), 1); - t1 = g1_fun(blk[3]); t0 = g0_fun(blk[2]); - blk[0] = rotl(blk[0], 1) ^ (t0 + t1 + l_key[4 * (i) + 8]); - blk[1] = rotr(blk[1] ^ (t0 + 2 * t1 + l_key[4 * (i) + 9]), 1); - } - - out_blk[0] = LE32(blk[2] ^ l_key[0]); - out_blk[1] = LE32(blk[3] ^ l_key[1]); - out_blk[2] = LE32(blk[0] ^ l_key[2]); - out_blk[3] = LE32(blk[1] ^ l_key[3]); -}; - -#endif // TC_MINIMIZE_CODE_SIZE +/* + --------------------------------------------------------------------------- + Copyright (c) 1999, Dr Brian Gladman, Worcester, UK. All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software is allowed (with or without + changes) provided that: + + 1. source code distributions include the above copyright notice, this + list of conditions and the following disclaimer; + + 2. binary distributions include the above copyright notice, this list + of conditions and the following disclaimer in their documentation; + + 3. the name of the copyright holder is not used to endorse products + built using this software without specific written permission. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + --------------------------------------------------------------------------- + + My thanks to Doug Whiting and Niels Ferguson for comments that led + to improvements in this implementation. + + Issue Date: 14th January 1999 +*/ + +/* Adapted for TrueCrypt */ +/* Adapted for VeraCrypt */ + + +#ifdef TC_WINDOWS_BOOT +#pragma optimize ("tl", on) +#endif + +#include "Twofish.h" +#include "Common/Endian.h" + +#define Q_TABLES +#define M_TABLE + +#if !defined (TC_MINIMIZE_CODE_SIZE) || defined (TC_WINDOWS_BOOT_TWOFISH) +# define MK_TABLE +# define ONE_STEP +#endif + +/* finite field arithmetic for GF(2**8) with the modular */ +/* polynomial x^8 + x^6 + x^5 + x^3 + 1 (0x169) */ + +#define G_M 0x0169 + +static u1byte tab_5b[4] = { 0, G_M >> 2, G_M >> 1, (G_M >> 1) ^ (G_M >> 2) }; +static u1byte tab_ef[4] = { 0, (G_M >> 1) ^ (G_M >> 2), G_M >> 1, G_M >> 2 }; + +#define ffm_01(x) (x) +#define ffm_5b(x) ((x) ^ ((x) >> 2) ^ tab_5b[(x) & 3]) +#define ffm_ef(x) ((x) ^ ((x) >> 1) ^ ((x) >> 2) ^ tab_ef[(x) & 3]) + +static u1byte ror4[16] = { 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15 }; +static u1byte ashx[16] = { 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7 }; + +static u1byte qt0[2][16] = +{ { 8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4 }, + { 2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5 } +}; + +static u1byte qt1[2][16] = +{ { 14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13 }, + { 1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8 } +}; + +static u1byte qt2[2][16] = +{ { 11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1 }, + { 4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15 } +}; + +static u1byte qt3[2][16] = +{ { 13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10 }, + { 11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10 } +}; + +static u1byte qp(const u4byte n, const u1byte x) +{ u1byte a0, a1, a2, a3, a4, b0, b1, b2, b3, b4; + + a0 = x >> 4; b0 = x & 15; + a1 = a0 ^ b0; b1 = ror4[b0] ^ ashx[a0]; + a2 = qt0[n][a1]; b2 = qt1[n][b1]; + a3 = a2 ^ b2; b3 = ror4[b2] ^ ashx[a2]; + a4 = qt2[n][a3]; b4 = qt3[n][b3]; + return (b4 << 4) | a4; +}; + +#ifdef Q_TABLES + +static u4byte qt_gen = 0; +static u1byte q_tab[2][256]; + +#define q(n,x) q_tab[n][x] + +static void gen_qtab(void) +{ u4byte i; + + for(i = 0; i < 256; ++i) + { + q(0,i) = qp(0, (u1byte)i); + q(1,i) = qp(1, (u1byte)i); + } +}; + +#else + +#define q(n,x) qp(n, x) + +#endif + +#ifdef M_TABLE + +static u4byte mt_gen = 0; +static u4byte m_tab[4][256]; + +static void gen_mtab(void) +{ u4byte i, f01, f5b, fef; + + for(i = 0; i < 256; ++i) + { + f01 = q(1,i); f5b = ffm_5b(f01); fef = ffm_ef(f01); + m_tab[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); + m_tab[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); + + f01 = q(0,i); f5b = ffm_5b(f01); fef = ffm_ef(f01); + m_tab[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); + m_tab[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); + } +}; + +#define mds(n,x) m_tab[n][x] + +#else + +#define fm_00 ffm_01 +#define fm_10 ffm_5b +#define fm_20 ffm_ef +#define fm_30 ffm_ef +#define q_0(x) q(1,x) + +#define fm_01 ffm_ef +#define fm_11 ffm_ef +#define fm_21 ffm_5b +#define fm_31 ffm_01 +#define q_1(x) q(0,x) + +#define fm_02 ffm_5b +#define fm_12 ffm_ef +#define fm_22 ffm_01 +#define fm_32 ffm_ef +#define q_2(x) q(1,x) + +#define fm_03 ffm_5b +#define fm_13 ffm_01 +#define fm_23 ffm_ef +#define fm_33 ffm_5b +#define q_3(x) q(0,x) + +#define f_0(n,x) ((u4byte)fm_0##n(x)) +#define f_1(n,x) ((u4byte)fm_1##n(x) << 8) +#define f_2(n,x) ((u4byte)fm_2##n(x) << 16) +#define f_3(n,x) ((u4byte)fm_3##n(x) << 24) + +#define mds(n,x) f_0(n,q_##n(x)) ^ f_1(n,q_##n(x)) ^ f_2(n,q_##n(x)) ^ f_3(n,q_##n(x)) + +#endif + +static u4byte h_fun(TwofishInstance *instance, const u4byte x, const u4byte key[]) +{ u4byte b0, b1, b2, b3; + +#ifndef M_TABLE + u4byte m5b_b0, m5b_b1, m5b_b2, m5b_b3; + u4byte mef_b0, mef_b1, mef_b2, mef_b3; +#endif + + b0 = extract_byte(x, 0); b1 = extract_byte(x, 1); b2 = extract_byte(x, 2); b3 = extract_byte(x, 3); + + switch(instance->k_len) + { + case 4: b0 = q(1, (u1byte) b0) ^ extract_byte(key[3],0); + b1 = q(0, (u1byte) b1) ^ extract_byte(key[3],1); + b2 = q(0, (u1byte) b2) ^ extract_byte(key[3],2); + b3 = q(1, (u1byte) b3) ^ extract_byte(key[3],3); + case 3: b0 = q(1, (u1byte) b0) ^ extract_byte(key[2],0); + b1 = q(1, (u1byte) b1) ^ extract_byte(key[2],1); + b2 = q(0, (u1byte) b2) ^ extract_byte(key[2],2); + b3 = q(0, (u1byte) b3) ^ extract_byte(key[2],3); + case 2: b0 = q(0, (u1byte) (q(0, (u1byte) b0) ^ extract_byte(key[1],0))) ^ extract_byte(key[0],0); + b1 = q(0, (u1byte) (q(1, (u1byte) b1) ^ extract_byte(key[1],1))) ^ extract_byte(key[0],1); + b2 = q(1, (u1byte) (q(0, (u1byte) b2) ^ extract_byte(key[1],2))) ^ extract_byte(key[0],2); + b3 = q(1, (u1byte) (q(1, (u1byte) b3) ^ extract_byte(key[1],3))) ^ extract_byte(key[0],3); + } +#ifdef M_TABLE + + return mds(0, b0) ^ mds(1, b1) ^ mds(2, b2) ^ mds(3, b3); + +#else + + b0 = q(1, (u1byte) b0); b1 = q(0, (u1byte) b1); b2 = q(1, (u1byte) b2); b3 = q(0, (u1byte) b3); + m5b_b0 = ffm_5b(b0); m5b_b1 = ffm_5b(b1); m5b_b2 = ffm_5b(b2); m5b_b3 = ffm_5b(b3); + mef_b0 = ffm_ef(b0); mef_b1 = ffm_ef(b1); mef_b2 = ffm_ef(b2); mef_b3 = ffm_ef(b3); + b0 ^= mef_b1 ^ m5b_b2 ^ m5b_b3; b3 ^= m5b_b0 ^ mef_b1 ^ mef_b2; + b2 ^= mef_b0 ^ m5b_b1 ^ mef_b3; b1 ^= mef_b0 ^ mef_b2 ^ m5b_b3; + + return b0 | (b3 << 8) | (b2 << 16) | (b1 << 24); + +#endif +}; + +#ifdef MK_TABLE + +#ifdef ONE_STEP +//u4byte mk_tab[4][256]; +#else +static u1byte sb[4][256]; +#endif + +#define q20(x) q(0,q(0,x) ^ extract_byte(key[1],0)) ^ extract_byte(key[0],0) +#define q21(x) q(0,q(1,x) ^ extract_byte(key[1],1)) ^ extract_byte(key[0],1) +#define q22(x) q(1,q(0,x) ^ extract_byte(key[1],2)) ^ extract_byte(key[0],2) +#define q23(x) q(1,q(1,x) ^ extract_byte(key[1],3)) ^ extract_byte(key[0],3) + +#define q30(x) q(0,q(0,q(1, x) ^ extract_byte(key[2],0)) ^ extract_byte(key[1],0)) ^ extract_byte(key[0],0) +#define q31(x) q(0,q(1,q(1, x) ^ extract_byte(key[2],1)) ^ extract_byte(key[1],1)) ^ extract_byte(key[0],1) +#define q32(x) q(1,q(0,q(0, x) ^ extract_byte(key[2],2)) ^ extract_byte(key[1],2)) ^ extract_byte(key[0],2) +#define q33(x) q(1,q(1,q(0, x) ^ extract_byte(key[2],3)) ^ extract_byte(key[1],3)) ^ extract_byte(key[0],3) + +#define q40(x) q(0,q(0,q(1, q(1, x) ^ extract_byte(key[3],0)) ^ extract_byte(key[2],0)) ^ extract_byte(key[1],0)) ^ extract_byte(key[0],0) +#define q41(x) q(0,q(1,q(1, q(0, x) ^ extract_byte(key[3],1)) ^ extract_byte(key[2],1)) ^ extract_byte(key[1],1)) ^ extract_byte(key[0],1) +#define q42(x) q(1,q(0,q(0, q(0, x) ^ extract_byte(key[3],2)) ^ extract_byte(key[2],2)) ^ extract_byte(key[1],2)) ^ extract_byte(key[0],2) +#define q43(x) q(1,q(1,q(0, q(1, x) ^ extract_byte(key[3],3)) ^ extract_byte(key[2],3)) ^ extract_byte(key[1],3)) ^ extract_byte(key[0],3) + +static void gen_mk_tab(TwofishInstance *instance, u4byte key[]) +{ u4byte i; + u1byte by; + + u4byte *mk_tab = instance->mk_tab; + + switch(instance->k_len) + { + case 2: for(i = 0; i < 256; ++i) + { + by = (u1byte)i; +#ifdef ONE_STEP + mk_tab[0 + 4*i] = mds(0, q20(by)); mk_tab[1 + 4*i] = mds(1, q21(by)); + mk_tab[2 + 4*i] = mds(2, q22(by)); mk_tab[3 + 4*i] = mds(3, q23(by)); +#else + sb[0][i] = q20(by); sb[1][i] = q21(by); + sb[2][i] = q22(by); sb[3][i] = q23(by); +#endif + } + break; + + case 3: for(i = 0; i < 256; ++i) + { + by = (u1byte)i; +#ifdef ONE_STEP + mk_tab[0 + 4*i] = mds(0, q30(by)); mk_tab[1 + 4*i] = mds(1, q31(by)); + mk_tab[2 + 4*i] = mds(2, q32(by)); mk_tab[3 + 4*i] = mds(3, q33(by)); +#else + sb[0][i] = q30(by); sb[1][i] = q31(by); + sb[2][i] = q32(by); sb[3][i] = q33(by); +#endif + } + break; + + case 4: for(i = 0; i < 256; ++i) + { + by = (u1byte)i; +#ifdef ONE_STEP + mk_tab[0 + 4*i] = mds(0, q40(by)); mk_tab[1 + 4*i] = mds(1, q41(by)); + mk_tab[2 + 4*i] = mds(2, q42(by)); mk_tab[3 + 4*i] = mds(3, q43(by)); +#else + sb[0][i] = q40(by); sb[1][i] = q41(by); + sb[2][i] = q42(by); sb[3][i] = q43(by); +#endif + } + } +}; + +# ifdef ONE_STEP +# define g0_fun(x) ( mk_tab[0 + 4*extract_byte(x,0)] ^ mk_tab[1 + 4*extract_byte(x,1)] \ + ^ mk_tab[2 + 4*extract_byte(x,2)] ^ mk_tab[3 + 4*extract_byte(x,3)] ) +# define g1_fun(x) ( mk_tab[0 + 4*extract_byte(x,3)] ^ mk_tab[1 + 4*extract_byte(x,0)] \ + ^ mk_tab[2 + 4*extract_byte(x,1)] ^ mk_tab[3 + 4*extract_byte(x,2)] ) + + +# else +# define g0_fun(x) ( mds(0, sb[0][extract_byte(x,0)]) ^ mds(1, sb[1][extract_byte(x,1)]) \ + ^ mds(2, sb[2][extract_byte(x,2)]) ^ mds(3, sb[3][extract_byte(x,3)]) ) +# define g1_fun(x) ( mds(0, sb[0][extract_byte(x,3)]) ^ mds(1, sb[1][extract_byte(x,0)]) \ + ^ mds(2, sb[2][extract_byte(x,1)]) ^ mds(3, sb[3][extract_byte(x,2)]) ) +# endif + +#else + +#define g0_fun(x) h_fun(instance, x, instance->s_key) +#define g1_fun(x) h_fun(instance, rotl(x,8), instance->s_key) + +#endif + +/* The (12,8) Reed Soloman code has the generator polynomial + + g(x) = x^4 + (a + 1/a) * x^3 + a * x^2 + (a + 1/a) * x + 1 + +where the coefficients are in the finite field GF(2^8) with a +modular polynomial a^8 + a^6 + a^3 + a^2 + 1. To generate the +remainder we have to start with a 12th order polynomial with our +eight input bytes as the coefficients of the 4th to 11th terms. +That is: + + m[7] * x^11 + m[6] * x^10 ... + m[0] * x^4 + 0 * x^3 +... + 0 + +We then multiply the generator polynomial by m[7] * x^7 and subtract +it - xor in GF(2^8) - from the above to eliminate the x^7 term (the +artihmetic on the coefficients is done in GF(2^8). We then multiply +the generator polynomial by x^6 * coeff(x^10) and use this to remove +the x^10 term. We carry on in this way until the x^4 term is removed +so that we are left with: + + r[3] * x^3 + r[2] * x^2 + r[1] 8 x^1 + r[0] + +which give the resulting 4 bytes of the remainder. This is equivalent +to the matrix multiplication in the Twofish description but much faster +to implement. + +*/ + +#define G_MOD 0x0000014d + +static u4byte mds_rem(u4byte p0, u4byte p1) +{ u4byte i, t, u; + + for(i = 0; i < 8; ++i) + { + t = p1 >> 24; // get most significant coefficient + + p1 = (p1 << 8) | (p0 >> 24); p0 <<= 8; // shift others up + + // multiply t by a (the primitive element - i.e. left shift) + + u = (t << 1); + + if(t & 0x80) // subtract modular polynomial on overflow + + u ^= G_MOD; + + p1 ^= t ^ (u << 16); // remove t * (a * x^2 + 1) + + u ^= (t >> 1); // form u = a * t + t / a = t * (a + 1 / a); + + if(t & 0x01) // add the modular polynomial on underflow + + u ^= G_MOD >> 1; + + p1 ^= (u << 24) | (u << 8); // remove t * (a + 1/a) * (x^3 + x) + } + + return p1; +}; + +/* initialise the key schedule from the user supplied key */ + +u4byte *twofish_set_key(TwofishInstance *instance, const u4byte in_key[]) +{ u4byte i, a, b, me_key[4], mo_key[4]; + u4byte *l_key, *s_key; + + l_key = instance->l_key; + s_key = instance->s_key; + +#ifdef Q_TABLES + if(!qt_gen) + { + gen_qtab(); qt_gen = 1; + } +#endif + +#ifdef M_TABLE + if(!mt_gen) + { + gen_mtab(); mt_gen = 1; + } +#endif + + instance->k_len = 4; + + for(i = 0; i < instance->k_len; ++i) + { + a = LE32(in_key[i + i]); me_key[i] = a; + b = LE32(in_key[i + i + 1]); mo_key[i] = b; + s_key[instance->k_len - i - 1] = mds_rem(a, b); + } + + for(i = 0; i < 40; i += 2) + { + a = 0x01010101 * i; b = a + 0x01010101; + a = h_fun(instance, a, me_key); + b = rotl(h_fun(instance, b, mo_key), 8); + l_key[i] = a + b; + l_key[i + 1] = rotl(a + 2 * b, 9); + } + +#ifdef MK_TABLE + gen_mk_tab(instance, s_key); +#endif + + return l_key; +}; + +/* encrypt a block of text */ + +#ifndef TC_MINIMIZE_CODE_SIZE + +#define f_rnd(i) \ + t1 = g1_fun(blk[1]); t0 = g0_fun(blk[0]); \ + blk[2] = rotr(blk[2] ^ (t0 + t1 + l_key[4 * (i) + 8]), 1); \ + blk[3] = rotl(blk[3], 1) ^ (t0 + 2 * t1 + l_key[4 * (i) + 9]); \ + t1 = g1_fun(blk[3]); t0 = g0_fun(blk[2]); \ + blk[0] = rotr(blk[0] ^ (t0 + t1 + l_key[4 * (i) + 10]), 1); \ + blk[1] = rotl(blk[1], 1) ^ (t0 + 2 * t1 + l_key[4 * (i) + 11]) + +void twofish_encrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte out_blk[]) +{ u4byte t0, t1, blk[4]; + + u4byte *l_key = instance->l_key; + u4byte *mk_tab = instance->mk_tab; + + blk[0] = LE32(in_blk[0]) ^ l_key[0]; + blk[1] = LE32(in_blk[1]) ^ l_key[1]; + blk[2] = LE32(in_blk[2]) ^ l_key[2]; + blk[3] = LE32(in_blk[3]) ^ l_key[3]; + + f_rnd(0); f_rnd(1); f_rnd(2); f_rnd(3); + f_rnd(4); f_rnd(5); f_rnd(6); f_rnd(7); + + out_blk[0] = LE32(blk[2] ^ l_key[4]); + out_blk[1] = LE32(blk[3] ^ l_key[5]); + out_blk[2] = LE32(blk[0] ^ l_key[6]); + out_blk[3] = LE32(blk[1] ^ l_key[7]); +}; + +#else // TC_MINIMIZE_CODE_SIZE + +void twofish_encrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte out_blk[]) +{ u4byte t0, t1, blk[4]; + + u4byte *l_key = instance->l_key; +#ifdef TC_WINDOWS_BOOT_TWOFISH + u4byte *mk_tab = instance->mk_tab; +#endif + int i; + + blk[0] = LE32(in_blk[0]) ^ l_key[0]; + blk[1] = LE32(in_blk[1]) ^ l_key[1]; + blk[2] = LE32(in_blk[2]) ^ l_key[2]; + blk[3] = LE32(in_blk[3]) ^ l_key[3]; + + for (i = 0; i <= 7; ++i) + { + t1 = g1_fun(blk[1]); t0 = g0_fun(blk[0]); + blk[2] = rotr(blk[2] ^ (t0 + t1 + l_key[4 * (i) + 8]), 1); + blk[3] = rotl(blk[3], 1) ^ (t0 + 2 * t1 + l_key[4 * (i) + 9]); + t1 = g1_fun(blk[3]); t0 = g0_fun(blk[2]); + blk[0] = rotr(blk[0] ^ (t0 + t1 + l_key[4 * (i) + 10]), 1); + blk[1] = rotl(blk[1], 1) ^ (t0 + 2 * t1 + l_key[4 * (i) + 11]); + } + + out_blk[0] = LE32(blk[2] ^ l_key[4]); + out_blk[1] = LE32(blk[3] ^ l_key[5]); + out_blk[2] = LE32(blk[0] ^ l_key[6]); + out_blk[3] = LE32(blk[1] ^ l_key[7]); +}; + +#endif // TC_MINIMIZE_CODE_SIZE + +/* decrypt a block of text */ + +#ifndef TC_MINIMIZE_CODE_SIZE + +#define i_rnd(i) \ + t1 = g1_fun(blk[1]); t0 = g0_fun(blk[0]); \ + blk[2] = rotl(blk[2], 1) ^ (t0 + t1 + l_key[4 * (i) + 10]); \ + blk[3] = rotr(blk[3] ^ (t0 + 2 * t1 + l_key[4 * (i) + 11]), 1); \ + t1 = g1_fun(blk[3]); t0 = g0_fun(blk[2]); \ + blk[0] = rotl(blk[0], 1) ^ (t0 + t1 + l_key[4 * (i) + 8]); \ + blk[1] = rotr(blk[1] ^ (t0 + 2 * t1 + l_key[4 * (i) + 9]), 1) + +void twofish_decrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte out_blk[4]) +{ u4byte t0, t1, blk[4]; + + u4byte *l_key = instance->l_key; + u4byte *mk_tab = instance->mk_tab; + + blk[0] = LE32(in_blk[0]) ^ l_key[4]; + blk[1] = LE32(in_blk[1]) ^ l_key[5]; + blk[2] = LE32(in_blk[2]) ^ l_key[6]; + blk[3] = LE32(in_blk[3]) ^ l_key[7]; + + i_rnd(7); i_rnd(6); i_rnd(5); i_rnd(4); + i_rnd(3); i_rnd(2); i_rnd(1); i_rnd(0); + + out_blk[0] = LE32(blk[2] ^ l_key[0]); + out_blk[1] = LE32(blk[3] ^ l_key[1]); + out_blk[2] = LE32(blk[0] ^ l_key[2]); + out_blk[3] = LE32(blk[1] ^ l_key[3]); +}; + +#else // TC_MINIMIZE_CODE_SIZE + +void twofish_decrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte out_blk[4]) +{ u4byte t0, t1, blk[4]; + + u4byte *l_key = instance->l_key; +#ifdef TC_WINDOWS_BOOT_TWOFISH + u4byte *mk_tab = instance->mk_tab; +#endif + int i; + + blk[0] = LE32(in_blk[0]) ^ l_key[4]; + blk[1] = LE32(in_blk[1]) ^ l_key[5]; + blk[2] = LE32(in_blk[2]) ^ l_key[6]; + blk[3] = LE32(in_blk[3]) ^ l_key[7]; + + for (i = 7; i >= 0; --i) + { + t1 = g1_fun(blk[1]); t0 = g0_fun(blk[0]); + blk[2] = rotl(blk[2], 1) ^ (t0 + t1 + l_key[4 * (i) + 10]); + blk[3] = rotr(blk[3] ^ (t0 + 2 * t1 + l_key[4 * (i) + 11]), 1); + t1 = g1_fun(blk[3]); t0 = g0_fun(blk[2]); + blk[0] = rotl(blk[0], 1) ^ (t0 + t1 + l_key[4 * (i) + 8]); + blk[1] = rotr(blk[1] ^ (t0 + 2 * t1 + l_key[4 * (i) + 9]), 1); + } + + out_blk[0] = LE32(blk[2] ^ l_key[0]); + out_blk[1] = LE32(blk[3] ^ l_key[1]); + out_blk[2] = LE32(blk[0] ^ l_key[2]); + out_blk[3] = LE32(blk[1] ^ l_key[3]); +}; + +#endif // TC_MINIMIZE_CODE_SIZE diff --git a/src/Crypto/Twofish.h b/src/Crypto/Twofish.h index ed400257..1011608e 100644 --- a/src/Crypto/Twofish.h +++ b/src/Crypto/Twofish.h @@ -1,56 +1,56 @@ -#ifndef TWOFISH_H -#define TWOFISH_H - -#include "Common/Tcdefs.h" - -#if defined(__cplusplus) -extern "C" -{ -#endif - -#ifndef u4byte -#define u4byte unsigned __int32 -#endif -#ifndef u1byte -#define u1byte unsigned char -#endif - -#ifndef extract_byte -#define extract_byte(x,n) ((u1byte)((x) >> (8 * n))) -#endif - -#ifndef rotl - -#ifdef _WIN32 -#include -#pragma intrinsic(_lrotr,_lrotl) -#define rotr(x,n) _lrotr(x,n) -#define rotl(x,n) _lrotl(x,n) -#else -#define rotr(x,n) (((x)>>(n))|((x)<<(32-(n)))) -#define rotl(x,n) (((x)<<(n))|((x)>>(32-(n)))) -#endif - -#endif -typedef struct -{ - u4byte l_key[40]; - u4byte s_key[4]; -#if !defined (TC_MINIMIZE_CODE_SIZE) || defined (TC_WINDOWS_BOOT_TWOFISH) - u4byte mk_tab[4 * 256]; -#endif - u4byte k_len; -} TwofishInstance; - -#define TWOFISH_KS sizeof(TwofishInstance) - -/* in_key must be 32-bytes long */ -u4byte * twofish_set_key(TwofishInstance *instance, const u4byte in_key[]); -void twofish_encrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte out_blk[]); -void twofish_decrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte out_blk[4]); - -#if defined(__cplusplus) -} -#endif - -#endif // TWOFISH_H +#ifndef TWOFISH_H +#define TWOFISH_H + +#include "Common/Tcdefs.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif + +#ifndef u4byte +#define u4byte unsigned __int32 +#endif +#ifndef u1byte +#define u1byte unsigned char +#endif + +#ifndef extract_byte +#define extract_byte(x,n) ((u1byte)((x) >> (8 * n))) +#endif + +#ifndef rotl + +#ifdef _WIN32 +#include +#pragma intrinsic(_lrotr,_lrotl) +#define rotr(x,n) _lrotr(x,n) +#define rotl(x,n) _lrotl(x,n) +#else +#define rotr(x,n) (((x)>>(n))|((x)<<(32-(n)))) +#define rotl(x,n) (((x)<<(n))|((x)>>(32-(n)))) +#endif + +#endif +typedef struct +{ + u4byte l_key[40]; + u4byte s_key[4]; +#if !defined (TC_MINIMIZE_CODE_SIZE) || defined (TC_WINDOWS_BOOT_TWOFISH) + u4byte mk_tab[4 * 256]; +#endif + u4byte k_len; +} TwofishInstance; + +#define TWOFISH_KS sizeof(TwofishInstance) + +/* in_key must be 32-bytes long */ +u4byte * twofish_set_key(TwofishInstance *instance, const u4byte in_key[]); +void twofish_encrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte out_blk[]); +void twofish_decrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte out_blk[4]); + +#if defined(__cplusplus) +} +#endif + +#endif // TWOFISH_H diff --git a/src/Crypto/Whirlpool.h b/src/Crypto/Whirlpool.h index df8aa7ac..9e771935 100644 --- a/src/Crypto/Whirlpool.h +++ b/src/Crypto/Whirlpool.h @@ -1,27 +1,27 @@ -#ifndef WHIRLPOOL_H -#define WHIRLPOOL_H 1 - -#include "Common/Tcdefs.h" -#include "config.h" - -typedef struct WHIRLPOOL_CTX { - uint64 countLo; - uint64 countHi; - CRYPTOPP_ALIGN_DATA(16) uint64 data[8]; - CRYPTOPP_ALIGN_DATA(16) uint64 state[8]; -} WHIRLPOOL_CTX; - -// ------------- -#if defined(__cplusplus) -extern "C" { -#endif - -void WHIRLPOOL_add(const unsigned char * source, unsigned __int32 sourceBits, WHIRLPOOL_CTX * const ctx); -void WHIRLPOOL_finalize(WHIRLPOOL_CTX* const ctx, unsigned char * result); -void WHIRLPOOL_init(WHIRLPOOL_CTX* const ctx); - -#if defined(__cplusplus) -} -#endif - -#endif /* WHIRLPOOL_H */ +#ifndef WHIRLPOOL_H +#define WHIRLPOOL_H 1 + +#include "Common/Tcdefs.h" +#include "config.h" + +typedef struct WHIRLPOOL_CTX { + uint64 countLo; + uint64 countHi; + CRYPTOPP_ALIGN_DATA(16) uint64 data[8]; + CRYPTOPP_ALIGN_DATA(16) uint64 state[8]; +} WHIRLPOOL_CTX; + +// ------------- +#if defined(__cplusplus) +extern "C" { +#endif + +void WHIRLPOOL_add(const unsigned char * source, unsigned __int32 sourceBits, WHIRLPOOL_CTX * const ctx); +void WHIRLPOOL_finalize(WHIRLPOOL_CTX* const ctx, unsigned char * result); +void WHIRLPOOL_init(WHIRLPOOL_CTX* const ctx); + +#if defined(__cplusplus) +} +#endif + +#endif /* WHIRLPOOL_H */ diff --git a/src/Crypto/cpu.c b/src/Crypto/cpu.c index 58a131af..4274a8ae 100644 --- a/src/Crypto/cpu.c +++ b/src/Crypto/cpu.c @@ -1,231 +1,231 @@ -/* cpu.c - written and placed in the public domain by Wei Dai */ - -#include "cpu.h" -#include "misc.h" - -#ifndef EXCEPTION_EXECUTE_HANDLER -#define EXCEPTION_EXECUTE_HANDLER 1 -#endif - -#ifndef CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY -#include -#include -#endif - -#if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE -#include -#endif - -#ifdef CRYPTOPP_CPUID_AVAILABLE - -#if _MSC_VER >= 1400 && CRYPTOPP_BOOL_X64 - -int CpuId(uint32 input, uint32 output[4]) -{ - __cpuid((int *)output, input); - return 1; -} - -#else - -#ifndef CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY - -#if defined(__cplusplus) -extern "C" { -#endif - -typedef void (*SigHandler)(int); - -static jmp_buf s_jmpNoCPUID; -static void SigIllHandlerCPUID(int p) -{ - longjmp(s_jmpNoCPUID, 1); -} - -#if CRYPTOPP_BOOL_X64 == 0 -static jmp_buf s_jmpNoSSE2; -static void SigIllHandlerSSE2(int p) -{ - longjmp(s_jmpNoSSE2, 1); -} -#endif - -#if defined(__cplusplus) -} -#endif -#endif - -int CpuId(uint32 input, uint32 output[4]) -{ -#ifdef CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY - __try - { - __asm - { - mov eax, input - mov ecx, 0 - cpuid - mov edi, output - mov [edi], eax - mov [edi+4], ebx - mov [edi+8], ecx - mov [edi+12], edx - } - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - return 0; - } - - // function 0 returns the highest basic function understood in EAX - if(input == 0) - return !!output[0]? 1 : 0; - - return 1; -#else - // longjmp and clobber warnings. Volatile is required. - // http://github.com/weidai11/cryptopp/issues/24 - // http://stackoverflow.com/q/7721854 - volatile int result = 1; - - SigHandler oldHandler = signal(SIGILL, SigIllHandlerCPUID); - if (oldHandler == SIG_ERR) - result = 0; - - if (setjmp(s_jmpNoCPUID)) - result = 0; - else - { - asm volatile - ( - // save ebx in case -fPIC is being used - // TODO: this might need an early clobber on EDI. -#if CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64 - "pushq %%rbx; cpuid; mov %%ebx, %%edi; popq %%rbx" -#else - "push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx" -#endif - : "=a" (output[0]), "=D" (output[1]), "=c" (output[2]), "=d" (output[3]) - : "a" (input), "c" (0) - ); - } - - signal(SIGILL, oldHandler); - return result; -#endif -} - -#endif - -static int TrySSE2() -{ -#if CRYPTOPP_BOOL_X64 - return 1; -#elif defined(CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY) - __try - { -#if CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE - AS2(por xmm0, xmm0) // executing SSE2 instruction -#elif CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE - __m128i x = _mm_setzero_si128(); - return _mm_cvtsi128_si32(x) == 0 ? 1 : 0; -#endif - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - return 0; - } - return 1; -#else - // longjmp and clobber warnings. Volatile is required. - // http://github.com/weidai11/cryptopp/issues/24 - // http://stackoverflow.com/q/7721854 - volatile int result = 1; - - SigHandler oldHandler = signal(SIGILL, SigIllHandlerSSE2); - if (oldHandler == SIG_ERR) - return 0; - - if (setjmp(s_jmpNoSSE2)) - result = 1; - else - { -#if CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE - __asm __volatile ("por %xmm0, %xmm0"); -#elif CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE - __m128i x = _mm_setzero_si128(); - result = _mm_cvtsi128_si32(x) == 0? 1 : 0; -#endif - } - - signal(SIGILL, oldHandler); - return result; -#endif -} - -int g_x86DetectionDone = 0; -int g_hasISSE = 0, g_hasSSE2 = 0, g_hasSSSE3 = 0, g_hasMMX = 0, g_hasAESNI = 0, g_hasCLMUL = 0, g_isP4 = 0; -uint32 g_cacheLineSize = CRYPTOPP_L1_CACHE_LINE_SIZE; - -VC_INLINE int IsIntel(const uint32 output[4]) -{ - // This is the "GenuineIntel" string - return (output[1] /*EBX*/ == 0x756e6547) && - (output[2] /*ECX*/ == 0x6c65746e) && - (output[3] /*EDX*/ == 0x49656e69); -} - -VC_INLINE int IsAMD(const uint32 output[4]) -{ - // This is the "AuthenticAMD" string - return (output[1] /*EBX*/ == 0x68747541) && - (output[2] /*ECX*/ == 0x69746E65) && - (output[3] /*EDX*/ == 0x444D4163); -} - -void DetectX86Features() -{ - uint32 cpuid[4], cpuid1[4]; - if (!CpuId(0, cpuid)) - return; - if (!CpuId(1, cpuid1)) - return; - - g_hasMMX = (cpuid1[3] & (1 << 23)) != 0; - if ((cpuid1[3] & (1 << 26)) != 0) - g_hasSSE2 = TrySSE2(); - g_hasSSSE3 = g_hasSSE2 && (cpuid1[2] & (1<<9)); - g_hasAESNI = g_hasSSE2 && (cpuid1[2] & (1<<25)); - g_hasCLMUL = g_hasSSE2 && (cpuid1[2] & (1<<1)); - - if ((cpuid1[3] & (1 << 25)) != 0) - g_hasISSE = 1; - else - { - uint32 cpuid2[4]; - CpuId(0x080000000, cpuid2); - if (cpuid2[0] >= 0x080000001) - { - CpuId(0x080000001, cpuid2); - g_hasISSE = (cpuid2[3] & (1 << 22)) != 0; - } - } - - if (IsIntel(cpuid)) - { - g_isP4 = ((cpuid1[0] >> 8) & 0xf) == 0xf; - g_cacheLineSize = 8 * GETBYTE(cpuid1[1], 1); - } - else if (IsAMD(cpuid)) - { - CpuId(0x80000005, cpuid); - g_cacheLineSize = GETBYTE(cpuid[2], 0); - } - - if (!g_cacheLineSize) - g_cacheLineSize = CRYPTOPP_L1_CACHE_LINE_SIZE; - - *((volatile int*)&g_x86DetectionDone) = 1; -} - -#endif +/* cpu.c - written and placed in the public domain by Wei Dai */ + +#include "cpu.h" +#include "misc.h" + +#ifndef EXCEPTION_EXECUTE_HANDLER +#define EXCEPTION_EXECUTE_HANDLER 1 +#endif + +#ifndef CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY +#include +#include +#endif + +#if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE +#include +#endif + +#ifdef CRYPTOPP_CPUID_AVAILABLE + +#if _MSC_VER >= 1400 && CRYPTOPP_BOOL_X64 + +int CpuId(uint32 input, uint32 output[4]) +{ + __cpuid((int *)output, input); + return 1; +} + +#else + +#ifndef CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY + +#if defined(__cplusplus) +extern "C" { +#endif + +typedef void (*SigHandler)(int); + +static jmp_buf s_jmpNoCPUID; +static void SigIllHandlerCPUID(int p) +{ + longjmp(s_jmpNoCPUID, 1); +} + +#if CRYPTOPP_BOOL_X64 == 0 +static jmp_buf s_jmpNoSSE2; +static void SigIllHandlerSSE2(int p) +{ + longjmp(s_jmpNoSSE2, 1); +} +#endif + +#if defined(__cplusplus) +} +#endif +#endif + +int CpuId(uint32 input, uint32 output[4]) +{ +#ifdef CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY + __try + { + __asm + { + mov eax, input + mov ecx, 0 + cpuid + mov edi, output + mov [edi], eax + mov [edi+4], ebx + mov [edi+8], ecx + mov [edi+12], edx + } + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + return 0; + } + + // function 0 returns the highest basic function understood in EAX + if(input == 0) + return !!output[0]? 1 : 0; + + return 1; +#else + // longjmp and clobber warnings. Volatile is required. + // http://github.com/weidai11/cryptopp/issues/24 + // http://stackoverflow.com/q/7721854 + volatile int result = 1; + + SigHandler oldHandler = signal(SIGILL, SigIllHandlerCPUID); + if (oldHandler == SIG_ERR) + result = 0; + + if (setjmp(s_jmpNoCPUID)) + result = 0; + else + { + asm volatile + ( + // save ebx in case -fPIC is being used + // TODO: this might need an early clobber on EDI. +#if CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64 + "pushq %%rbx; cpuid; mov %%ebx, %%edi; popq %%rbx" +#else + "push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx" +#endif + : "=a" (output[0]), "=D" (output[1]), "=c" (output[2]), "=d" (output[3]) + : "a" (input), "c" (0) + ); + } + + signal(SIGILL, oldHandler); + return result; +#endif +} + +#endif + +static int TrySSE2() +{ +#if CRYPTOPP_BOOL_X64 + return 1; +#elif defined(CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY) + __try + { +#if CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE + AS2(por xmm0, xmm0) // executing SSE2 instruction +#elif CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE + __m128i x = _mm_setzero_si128(); + return _mm_cvtsi128_si32(x) == 0 ? 1 : 0; +#endif + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + return 0; + } + return 1; +#else + // longjmp and clobber warnings. Volatile is required. + // http://github.com/weidai11/cryptopp/issues/24 + // http://stackoverflow.com/q/7721854 + volatile int result = 1; + + SigHandler oldHandler = signal(SIGILL, SigIllHandlerSSE2); + if (oldHandler == SIG_ERR) + return 0; + + if (setjmp(s_jmpNoSSE2)) + result = 1; + else + { +#if CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE + __asm __volatile ("por %xmm0, %xmm0"); +#elif CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE + __m128i x = _mm_setzero_si128(); + result = _mm_cvtsi128_si32(x) == 0? 1 : 0; +#endif + } + + signal(SIGILL, oldHandler); + return result; +#endif +} + +int g_x86DetectionDone = 0; +int g_hasISSE = 0, g_hasSSE2 = 0, g_hasSSSE3 = 0, g_hasMMX = 0, g_hasAESNI = 0, g_hasCLMUL = 0, g_isP4 = 0; +uint32 g_cacheLineSize = CRYPTOPP_L1_CACHE_LINE_SIZE; + +VC_INLINE int IsIntel(const uint32 output[4]) +{ + // This is the "GenuineIntel" string + return (output[1] /*EBX*/ == 0x756e6547) && + (output[2] /*ECX*/ == 0x6c65746e) && + (output[3] /*EDX*/ == 0x49656e69); +} + +VC_INLINE int IsAMD(const uint32 output[4]) +{ + // This is the "AuthenticAMD" string + return (output[1] /*EBX*/ == 0x68747541) && + (output[2] /*ECX*/ == 0x69746E65) && + (output[3] /*EDX*/ == 0x444D4163); +} + +void DetectX86Features() +{ + uint32 cpuid[4], cpuid1[4]; + if (!CpuId(0, cpuid)) + return; + if (!CpuId(1, cpuid1)) + return; + + g_hasMMX = (cpuid1[3] & (1 << 23)) != 0; + if ((cpuid1[3] & (1 << 26)) != 0) + g_hasSSE2 = TrySSE2(); + g_hasSSSE3 = g_hasSSE2 && (cpuid1[2] & (1<<9)); + g_hasAESNI = g_hasSSE2 && (cpuid1[2] & (1<<25)); + g_hasCLMUL = g_hasSSE2 && (cpuid1[2] & (1<<1)); + + if ((cpuid1[3] & (1 << 25)) != 0) + g_hasISSE = 1; + else + { + uint32 cpuid2[4]; + CpuId(0x080000000, cpuid2); + if (cpuid2[0] >= 0x080000001) + { + CpuId(0x080000001, cpuid2); + g_hasISSE = (cpuid2[3] & (1 << 22)) != 0; + } + } + + if (IsIntel(cpuid)) + { + g_isP4 = ((cpuid1[0] >> 8) & 0xf) == 0xf; + g_cacheLineSize = 8 * GETBYTE(cpuid1[1], 1); + } + else if (IsAMD(cpuid)) + { + CpuId(0x80000005, cpuid); + g_cacheLineSize = GETBYTE(cpuid[2], 0); + } + + if (!g_cacheLineSize) + g_cacheLineSize = CRYPTOPP_L1_CACHE_LINE_SIZE; + + *((volatile int*)&g_x86DetectionDone) = 1; +} + +#endif diff --git a/src/Crypto/cpu.h b/src/Crypto/cpu.h index da8d14cb..7ef509ec 100644 --- a/src/Crypto/cpu.h +++ b/src/Crypto/cpu.h @@ -1,308 +1,308 @@ -#ifndef CRYPTOPP_CPU_H -#define CRYPTOPP_CPU_H - -#include "Common/Tcdefs.h" -#include "config.h" - -#ifdef CRYPTOPP_GENERATE_X64_MASM - -#define CRYPTOPP_X86_ASM_AVAILABLE -#define CRYPTOPP_BOOL_X64 1 -#define CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE 1 - -#else - -#if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE -#include -#endif - -#if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE -#if defined(__SSSE3__) || defined(__INTEL_COMPILER) -#ifdef TC_WINDOWS_DRIVER -extern __m128i _mm_shuffle_epi8 (__m128i a, __m128i b); -#else -#include -#endif -#endif - -#if defined(__SSE4_1__) || defined(__INTEL_COMPILER) -#ifdef TC_WINDOWS_DRIVER -extern int _mm_extract_epi32(__m128i src, const int ndx); -extern __m128i _mm_insert_epi32(__m128i dst, int s, const int ndx); -#else -#include -#endif -#endif - -#if (defined(__AES__) && defined(__PCLMUL__)) || defined(__INTEL_COMPILER) -#ifdef TC_WINDOWS_DRIVER -extern __m128i _mm_clmulepi64_si128(__m128i v1, __m128i v2, - const int imm8); -extern __m128i _mm_aeskeygenassist_si128(__m128i ckey, const int rcon); -extern __m128i _mm_aesimc_si128(__m128i v); -extern __m128i _mm_aesenc_si128(__m128i v, __m128i rkey); -extern __m128i _mm_aesenclast_si128(__m128i v, __m128i rkey); -extern __m128i _mm_aesdec_si128(__m128i v, __m128i rkey); -extern __m128i _mm_aesdeclast_si128(__m128i v, __m128i rkey); -#else -#include -#endif -#endif -#endif - -#if CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64 - -#define CRYPTOPP_CPUID_AVAILABLE - -#if defined(__cplusplus) -extern "C" { -#endif - -// these should not be used directly -extern int g_x86DetectionDone; -extern int g_hasSSSE3; -extern int g_hasAESNI; -extern int g_hasCLMUL; -extern int g_isP4; -extern uint32 g_cacheLineSize; -void DetectX86Features(); // must be called at the start of the program/driver -int CpuId(uint32 input, uint32 *output); - -#if CRYPTOPP_BOOL_X64 -#define HasSSE2() 1 -#define HasISSE() 1 -#define HasMMX() 1 -#else - -extern int g_hasSSE2; -extern int g_hasISSE; -extern int g_hasMMX; - -#define HasSSE2() g_hasSSE2 -#define HasISSE() g_hasISSE -#define HasMMX() g_hasMMX - -#endif - -#define HasSSSE3() g_hasSSSE3 -#define HasAESNI() g_hasAESNI -#define HasCLMUL() g_hasCLMUL -#define IsP4() g_isP4 -#define GetCacheLineSize() g_cacheLineSize - -#if defined(__cplusplus) -} -#endif - -#else - -#define GetCacheLineSize() CRYPTOPP_L1_CACHE_LINE_SIZE - -#endif - -#endif - -#ifdef CRYPTOPP_GENERATE_X64_MASM - #define AS1(x) x*newline* - #define AS2(x, y) x, y*newline* - #define AS3(x, y, z) x, y, z*newline* - #define ASS(x, y, a, b, c, d) x, y, a*64+b*16+c*4+d*newline* - #define ASL(x) label##x:*newline* - #define ASJ(x, y, z) x label##y*newline* - #define ASC(x, y) x label##y*newline* - #define AS_HEX(y) 0##y##h -#elif defined(_MSC_VER) || defined(__BORLANDC__) - #define CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY - #define AS1(x) __asm {x} - #define AS2(x, y) __asm {x, y} - #define AS3(x, y, z) __asm {x, y, z} - #define ASS(x, y, a, b, c, d) __asm {x, y, (a)*64+(b)*16+(c)*4+(d)} - #define ASL(x) __asm {label##x:} - #define ASJ(x, y, z) __asm {x label##y} - #define ASC(x, y) __asm {x label##y} - #define CRYPTOPP_NAKED __declspec(naked) - #define AS_HEX(y) 0x##y -#else - #define CRYPTOPP_GNU_STYLE_INLINE_ASSEMBLY - - #if defined(CRYPTOPP_CLANG_VERSION) || defined(CRYPTOPP_APPLE_CLANG_VERSION) - #define NEW_LINE "\n" - #define INTEL_PREFIX ".intel_syntax;" - #define INTEL_NOPREFIX ".intel_syntax;" - #define ATT_PREFIX ".att_syntax;" - #define ATT_NOPREFIX ".att_syntax;" - #else - #define NEW_LINE - #define INTEL_PREFIX ".intel_syntax prefix;" - #define INTEL_NOPREFIX ".intel_syntax noprefix;" - #define ATT_PREFIX ".att_syntax prefix;" - #define ATT_NOPREFIX ".att_syntax noprefix;" - #endif - - // define these in two steps to allow arguments to be expanded - #define GNU_AS1(x) #x ";" NEW_LINE - #define GNU_AS2(x, y) #x ", " #y ";" NEW_LINE - #define GNU_AS3(x, y, z) #x ", " #y ", " #z ";" NEW_LINE - #define GNU_ASL(x) "\n" #x ":" NEW_LINE - #define GNU_ASJ(x, y, z) #x " " #y #z ";" NEW_LINE - #define AS1(x) GNU_AS1(x) - #define AS2(x, y) GNU_AS2(x, y) - #define AS3(x, y, z) GNU_AS3(x, y, z) - #define ASS(x, y, a, b, c, d) #x ", " #y ", " #a "*64+" #b "*16+" #c "*4+" #d ";" - #define ASL(x) GNU_ASL(x) - #define ASJ(x, y, z) GNU_ASJ(x, y, z) - #define ASC(x, y) #x " " #y ";" - #define CRYPTOPP_NAKED - #define AS_HEX(y) 0x##y -#endif - -#define IF0(y) -#define IF1(y) y - -// Should be confined to GCC, but its used to help manage Clang 3.4 compiler error. -// Also see LLVM Bug 24232, http://llvm.org/bugs/show_bug.cgi?id=24232 . -#ifndef INTEL_PREFIX -#define INTEL_PREFIX -#endif -#ifndef INTEL_NOPREFIX -#define INTEL_NOPREFIX -#endif -#ifndef ATT_PREFIX -#define ATT_PREFIX -#endif -#ifndef ATT_NOPREFIX -#define ATT_NOPREFIX -#endif - -#ifdef CRYPTOPP_GENERATE_X64_MASM -#define ASM_MOD(x, y) ((x) MOD (y)) -#define XMMWORD_PTR XMMWORD PTR -#else -// GNU assembler doesn't seem to have mod operator -#define ASM_MOD(x, y) ((x)-((x)/(y))*(y)) -// GAS 2.15 doesn't support XMMWORD PTR. it seems necessary only for MASM -#define XMMWORD_PTR -#endif - -#if CRYPTOPP_BOOL_X86 - #define AS_REG_1 ecx - #define AS_REG_2 edx - #define AS_REG_3 esi - #define AS_REG_4 edi - #define AS_REG_5 eax - #define AS_REG_6 ebx - #define AS_REG_7 ebp - #define AS_REG_1d ecx - #define AS_REG_2d edx - #define AS_REG_3d esi - #define AS_REG_4d edi - #define AS_REG_5d eax - #define AS_REG_6d ebx - #define AS_REG_7d ebp - #define WORD_SZ 4 - #define WORD_REG(x) e##x - #define WORD_PTR DWORD PTR - #define AS_PUSH_IF86(x) AS1(push e##x) - #define AS_POP_IF86(x) AS1(pop e##x) - #define AS_JCXZ jecxz -#elif CRYPTOPP_BOOL_X32 - #define AS_REG_1 ecx - #define AS_REG_2 edx - #define AS_REG_3 r8d - #define AS_REG_4 r9d - #define AS_REG_5 eax - #define AS_REG_6 r10d - #define AS_REG_7 r11d - #define AS_REG_1d ecx - #define AS_REG_2d edx - #define AS_REG_3d r8d - #define AS_REG_4d r9d - #define AS_REG_5d eax - #define AS_REG_6d r10d - #define AS_REG_7d r11d - #define WORD_SZ 4 - #define WORD_REG(x) e##x - #define WORD_PTR DWORD PTR - #define AS_PUSH_IF86(x) AS1(push r##x) - #define AS_POP_IF86(x) AS1(pop r##x) - #define AS_JCXZ jecxz -#elif CRYPTOPP_BOOL_X64 - #ifdef CRYPTOPP_GENERATE_X64_MASM - #define AS_REG_1 rcx - #define AS_REG_2 rdx - #define AS_REG_3 r8 - #define AS_REG_4 r9 - #define AS_REG_5 rax - #define AS_REG_6 r10 - #define AS_REG_7 r11 - #define AS_REG_1d ecx - #define AS_REG_2d edx - #define AS_REG_3d r8d - #define AS_REG_4d r9d - #define AS_REG_5d eax - #define AS_REG_6d r10d - #define AS_REG_7d r11d - #else - #define AS_REG_1 rdi - #define AS_REG_2 rsi - #define AS_REG_3 rdx - #define AS_REG_4 rcx - #define AS_REG_5 r8 - #define AS_REG_6 r9 - #define AS_REG_7 r10 - #define AS_REG_1d edi - #define AS_REG_2d esi - #define AS_REG_3d edx - #define AS_REG_4d ecx - #define AS_REG_5d r8d - #define AS_REG_6d r9d - #define AS_REG_7d r10d - #endif - #define WORD_SZ 8 - #define WORD_REG(x) r##x - #define WORD_PTR QWORD PTR - #define AS_PUSH_IF86(x) - #define AS_POP_IF86(x) - #define AS_JCXZ jrcxz -#endif - -// helper macro for stream cipher output -#define AS_XMM_OUTPUT4(labelPrefix, inputPtr, outputPtr, x0, x1, x2, x3, t, p0, p1, p2, p3, increment)\ - AS2( test inputPtr, inputPtr)\ - ASC( jz, labelPrefix##3)\ - AS2( test inputPtr, 15)\ - ASC( jnz, labelPrefix##7)\ - AS2( pxor xmm##x0, [inputPtr+p0*16])\ - AS2( pxor xmm##x1, [inputPtr+p1*16])\ - AS2( pxor xmm##x2, [inputPtr+p2*16])\ - AS2( pxor xmm##x3, [inputPtr+p3*16])\ - AS2( add inputPtr, increment*16)\ - ASC( jmp, labelPrefix##3)\ - ASL(labelPrefix##7)\ - AS2( movdqu xmm##t, [inputPtr+p0*16])\ - AS2( pxor xmm##x0, xmm##t)\ - AS2( movdqu xmm##t, [inputPtr+p1*16])\ - AS2( pxor xmm##x1, xmm##t)\ - AS2( movdqu xmm##t, [inputPtr+p2*16])\ - AS2( pxor xmm##x2, xmm##t)\ - AS2( movdqu xmm##t, [inputPtr+p3*16])\ - AS2( pxor xmm##x3, xmm##t)\ - AS2( add inputPtr, increment*16)\ - ASL(labelPrefix##3)\ - AS2( test outputPtr, 15)\ - ASC( jnz, labelPrefix##8)\ - AS2( movdqa [outputPtr+p0*16], xmm##x0)\ - AS2( movdqa [outputPtr+p1*16], xmm##x1)\ - AS2( movdqa [outputPtr+p2*16], xmm##x2)\ - AS2( movdqa [outputPtr+p3*16], xmm##x3)\ - ASC( jmp, labelPrefix##9)\ - ASL(labelPrefix##8)\ - AS2( movdqu [outputPtr+p0*16], xmm##x0)\ - AS2( movdqu [outputPtr+p1*16], xmm##x1)\ - AS2( movdqu [outputPtr+p2*16], xmm##x2)\ - AS2( movdqu [outputPtr+p3*16], xmm##x3)\ - ASL(labelPrefix##9)\ - AS2( add outputPtr, increment*16) - - -#endif +#ifndef CRYPTOPP_CPU_H +#define CRYPTOPP_CPU_H + +#include "Common/Tcdefs.h" +#include "config.h" + +#ifdef CRYPTOPP_GENERATE_X64_MASM + +#define CRYPTOPP_X86_ASM_AVAILABLE +#define CRYPTOPP_BOOL_X64 1 +#define CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE 1 + +#else + +#if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE +#include +#endif + +#if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE +#if defined(__SSSE3__) || defined(__INTEL_COMPILER) +#ifdef TC_WINDOWS_DRIVER +extern __m128i _mm_shuffle_epi8 (__m128i a, __m128i b); +#else +#include +#endif +#endif + +#if defined(__SSE4_1__) || defined(__INTEL_COMPILER) +#ifdef TC_WINDOWS_DRIVER +extern int _mm_extract_epi32(__m128i src, const int ndx); +extern __m128i _mm_insert_epi32(__m128i dst, int s, const int ndx); +#else +#include +#endif +#endif + +#if (defined(__AES__) && defined(__PCLMUL__)) || defined(__INTEL_COMPILER) +#ifdef TC_WINDOWS_DRIVER +extern __m128i _mm_clmulepi64_si128(__m128i v1, __m128i v2, + const int imm8); +extern __m128i _mm_aeskeygenassist_si128(__m128i ckey, const int rcon); +extern __m128i _mm_aesimc_si128(__m128i v); +extern __m128i _mm_aesenc_si128(__m128i v, __m128i rkey); +extern __m128i _mm_aesenclast_si128(__m128i v, __m128i rkey); +extern __m128i _mm_aesdec_si128(__m128i v, __m128i rkey); +extern __m128i _mm_aesdeclast_si128(__m128i v, __m128i rkey); +#else +#include +#endif +#endif +#endif + +#if CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64 + +#define CRYPTOPP_CPUID_AVAILABLE + +#if defined(__cplusplus) +extern "C" { +#endif + +// these should not be used directly +extern int g_x86DetectionDone; +extern int g_hasSSSE3; +extern int g_hasAESNI; +extern int g_hasCLMUL; +extern int g_isP4; +extern uint32 g_cacheLineSize; +void DetectX86Features(); // must be called at the start of the program/driver +int CpuId(uint32 input, uint32 *output); + +#if CRYPTOPP_BOOL_X64 +#define HasSSE2() 1 +#define HasISSE() 1 +#define HasMMX() 1 +#else + +extern int g_hasSSE2; +extern int g_hasISSE; +extern int g_hasMMX; + +#define HasSSE2() g_hasSSE2 +#define HasISSE() g_hasISSE +#define HasMMX() g_hasMMX + +#endif + +#define HasSSSE3() g_hasSSSE3 +#define HasAESNI() g_hasAESNI +#define HasCLMUL() g_hasCLMUL +#define IsP4() g_isP4 +#define GetCacheLineSize() g_cacheLineSize + +#if defined(__cplusplus) +} +#endif + +#else + +#define GetCacheLineSize() CRYPTOPP_L1_CACHE_LINE_SIZE + +#endif + +#endif + +#ifdef CRYPTOPP_GENERATE_X64_MASM + #define AS1(x) x*newline* + #define AS2(x, y) x, y*newline* + #define AS3(x, y, z) x, y, z*newline* + #define ASS(x, y, a, b, c, d) x, y, a*64+b*16+c*4+d*newline* + #define ASL(x) label##x:*newline* + #define ASJ(x, y, z) x label##y*newline* + #define ASC(x, y) x label##y*newline* + #define AS_HEX(y) 0##y##h +#elif defined(_MSC_VER) || defined(__BORLANDC__) + #define CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY + #define AS1(x) __asm {x} + #define AS2(x, y) __asm {x, y} + #define AS3(x, y, z) __asm {x, y, z} + #define ASS(x, y, a, b, c, d) __asm {x, y, (a)*64+(b)*16+(c)*4+(d)} + #define ASL(x) __asm {label##x:} + #define ASJ(x, y, z) __asm {x label##y} + #define ASC(x, y) __asm {x label##y} + #define CRYPTOPP_NAKED __declspec(naked) + #define AS_HEX(y) 0x##y +#else + #define CRYPTOPP_GNU_STYLE_INLINE_ASSEMBLY + + #if defined(CRYPTOPP_CLANG_VERSION) || defined(CRYPTOPP_APPLE_CLANG_VERSION) + #define NEW_LINE "\n" + #define INTEL_PREFIX ".intel_syntax;" + #define INTEL_NOPREFIX ".intel_syntax;" + #define ATT_PREFIX ".att_syntax;" + #define ATT_NOPREFIX ".att_syntax;" + #else + #define NEW_LINE + #define INTEL_PREFIX ".intel_syntax prefix;" + #define INTEL_NOPREFIX ".intel_syntax noprefix;" + #define ATT_PREFIX ".att_syntax prefix;" + #define ATT_NOPREFIX ".att_syntax noprefix;" + #endif + + // define these in two steps to allow arguments to be expanded + #define GNU_AS1(x) #x ";" NEW_LINE + #define GNU_AS2(x, y) #x ", " #y ";" NEW_LINE + #define GNU_AS3(x, y, z) #x ", " #y ", " #z ";" NEW_LINE + #define GNU_ASL(x) "\n" #x ":" NEW_LINE + #define GNU_ASJ(x, y, z) #x " " #y #z ";" NEW_LINE + #define AS1(x) GNU_AS1(x) + #define AS2(x, y) GNU_AS2(x, y) + #define AS3(x, y, z) GNU_AS3(x, y, z) + #define ASS(x, y, a, b, c, d) #x ", " #y ", " #a "*64+" #b "*16+" #c "*4+" #d ";" + #define ASL(x) GNU_ASL(x) + #define ASJ(x, y, z) GNU_ASJ(x, y, z) + #define ASC(x, y) #x " " #y ";" + #define CRYPTOPP_NAKED + #define AS_HEX(y) 0x##y +#endif + +#define IF0(y) +#define IF1(y) y + +// Should be confined to GCC, but its used to help manage Clang 3.4 compiler error. +// Also see LLVM Bug 24232, http://llvm.org/bugs/show_bug.cgi?id=24232 . +#ifndef INTEL_PREFIX +#define INTEL_PREFIX +#endif +#ifndef INTEL_NOPREFIX +#define INTEL_NOPREFIX +#endif +#ifndef ATT_PREFIX +#define ATT_PREFIX +#endif +#ifndef ATT_NOPREFIX +#define ATT_NOPREFIX +#endif + +#ifdef CRYPTOPP_GENERATE_X64_MASM +#define ASM_MOD(x, y) ((x) MOD (y)) +#define XMMWORD_PTR XMMWORD PTR +#else +// GNU assembler doesn't seem to have mod operator +#define ASM_MOD(x, y) ((x)-((x)/(y))*(y)) +// GAS 2.15 doesn't support XMMWORD PTR. it seems necessary only for MASM +#define XMMWORD_PTR +#endif + +#if CRYPTOPP_BOOL_X86 + #define AS_REG_1 ecx + #define AS_REG_2 edx + #define AS_REG_3 esi + #define AS_REG_4 edi + #define AS_REG_5 eax + #define AS_REG_6 ebx + #define AS_REG_7 ebp + #define AS_REG_1d ecx + #define AS_REG_2d edx + #define AS_REG_3d esi + #define AS_REG_4d edi + #define AS_REG_5d eax + #define AS_REG_6d ebx + #define AS_REG_7d ebp + #define WORD_SZ 4 + #define WORD_REG(x) e##x + #define WORD_PTR DWORD PTR + #define AS_PUSH_IF86(x) AS1(push e##x) + #define AS_POP_IF86(x) AS1(pop e##x) + #define AS_JCXZ jecxz +#elif CRYPTOPP_BOOL_X32 + #define AS_REG_1 ecx + #define AS_REG_2 edx + #define AS_REG_3 r8d + #define AS_REG_4 r9d + #define AS_REG_5 eax + #define AS_REG_6 r10d + #define AS_REG_7 r11d + #define AS_REG_1d ecx + #define AS_REG_2d edx + #define AS_REG_3d r8d + #define AS_REG_4d r9d + #define AS_REG_5d eax + #define AS_REG_6d r10d + #define AS_REG_7d r11d + #define WORD_SZ 4 + #define WORD_REG(x) e##x + #define WORD_PTR DWORD PTR + #define AS_PUSH_IF86(x) AS1(push r##x) + #define AS_POP_IF86(x) AS1(pop r##x) + #define AS_JCXZ jecxz +#elif CRYPTOPP_BOOL_X64 + #ifdef CRYPTOPP_GENERATE_X64_MASM + #define AS_REG_1 rcx + #define AS_REG_2 rdx + #define AS_REG_3 r8 + #define AS_REG_4 r9 + #define AS_REG_5 rax + #define AS_REG_6 r10 + #define AS_REG_7 r11 + #define AS_REG_1d ecx + #define AS_REG_2d edx + #define AS_REG_3d r8d + #define AS_REG_4d r9d + #define AS_REG_5d eax + #define AS_REG_6d r10d + #define AS_REG_7d r11d + #else + #define AS_REG_1 rdi + #define AS_REG_2 rsi + #define AS_REG_3 rdx + #define AS_REG_4 rcx + #define AS_REG_5 r8 + #define AS_REG_6 r9 + #define AS_REG_7 r10 + #define AS_REG_1d edi + #define AS_REG_2d esi + #define AS_REG_3d edx + #define AS_REG_4d ecx + #define AS_REG_5d r8d + #define AS_REG_6d r9d + #define AS_REG_7d r10d + #endif + #define WORD_SZ 8 + #define WORD_REG(x) r##x + #define WORD_PTR QWORD PTR + #define AS_PUSH_IF86(x) + #define AS_POP_IF86(x) + #define AS_JCXZ jrcxz +#endif + +// helper macro for stream cipher output +#define AS_XMM_OUTPUT4(labelPrefix, inputPtr, outputPtr, x0, x1, x2, x3, t, p0, p1, p2, p3, increment)\ + AS2( test inputPtr, inputPtr)\ + ASC( jz, labelPrefix##3)\ + AS2( test inputPtr, 15)\ + ASC( jnz, labelPrefix##7)\ + AS2( pxor xmm##x0, [inputPtr+p0*16])\ + AS2( pxor xmm##x1, [inputPtr+p1*16])\ + AS2( pxor xmm##x2, [inputPtr+p2*16])\ + AS2( pxor xmm##x3, [inputPtr+p3*16])\ + AS2( add inputPtr, increment*16)\ + ASC( jmp, labelPrefix##3)\ + ASL(labelPrefix##7)\ + AS2( movdqu xmm##t, [inputPtr+p0*16])\ + AS2( pxor xmm##x0, xmm##t)\ + AS2( movdqu xmm##t, [inputPtr+p1*16])\ + AS2( pxor xmm##x1, xmm##t)\ + AS2( movdqu xmm##t, [inputPtr+p2*16])\ + AS2( pxor xmm##x2, xmm##t)\ + AS2( movdqu xmm##t, [inputPtr+p3*16])\ + AS2( pxor xmm##x3, xmm##t)\ + AS2( add inputPtr, increment*16)\ + ASL(labelPrefix##3)\ + AS2( test outputPtr, 15)\ + ASC( jnz, labelPrefix##8)\ + AS2( movdqa [outputPtr+p0*16], xmm##x0)\ + AS2( movdqa [outputPtr+p1*16], xmm##x1)\ + AS2( movdqa [outputPtr+p2*16], xmm##x2)\ + AS2( movdqa [outputPtr+p3*16], xmm##x3)\ + ASC( jmp, labelPrefix##9)\ + ASL(labelPrefix##8)\ + AS2( movdqu [outputPtr+p0*16], xmm##x0)\ + AS2( movdqu [outputPtr+p1*16], xmm##x1)\ + AS2( movdqu [outputPtr+p2*16], xmm##x2)\ + AS2( movdqu [outputPtr+p3*16], xmm##x3)\ + ASL(labelPrefix##9)\ + AS2( add outputPtr, increment*16) + + +#endif diff --git a/src/Driver/BuildDriver.cmd b/src/Driver/BuildDriver.cmd index 99fe554b..bfeee2db 100644 --- a/src/Driver/BuildDriver.cmd +++ b/src/Driver/BuildDriver.cmd @@ -1,166 +1,166 @@ -:: -:: 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. -:: - -:: Usage: BuildDriver <-build|-rebuild|-clean> <-release|-debug> <-x86|-x64> [dir2] ... - -@echo off -set TC_ARG_CMD=%~1 -shift -set TC_ARG_TYPE=%~1 -shift -set TC_ARG_ARCH=%~1 -shift - - -:: Windows Driver Kit build number - -set TC_WINDDK_BUILD=7600.16385.1 - - -:: Check for spaces in the current directory path - -cd | find " " >NUL: - -if %ERRORLEVEL% == 0 ( - echo BuildDriver.cmd: error: MS Build does not support building of projects stored in a path containing spaces. >&2 - exit /B 1 -) - - -:: Build options - -set TC_C_DEFINES=-D_WIN32 -DTC_WINDOWS_DRIVER -set TC_C_FLAGS=-nologo -I.. -set TC_C_WARNING_LEVEL=-W4 -set TC_C_DISABLED_WARNINGS=-wd4057 -wd4100 -wd4127 -wd4152 -wd4201 -wd4701 -wd4702 -wd4706 -set TC_LIBRARIAN_FLAGS=-nologo -set TC_LINKER_FLAGS=-nologo -set TC_TEST_SIGN=0 - - -:: Windows Driver Kit root - -set TC_WINDDK_ROOT=%SYSTEMDRIVE%\WinDDK\%TC_WINDDK_BUILD% -if exist "%TC_WINDDK_ROOT%\bin\setenv.bat" goto ddk_found - -set TC_WINDDK_ROOT=%WINDDK_ROOT%\%TC_WINDDK_BUILD% -if exist "%TC_WINDDK_ROOT%\bin\setenv.bat" goto ddk_found - -set TC_WINDDK_ROOT=%WINDDK_ROOT% -if exist "%TC_WINDDK_ROOT%\bin\setenv.bat" goto ddk_found - -echo BuildDriver.cmd: error: Windows Driver Development Kit not found in the default directory. Set WINDDK_ROOT environment variable to point to your Windows DDK installation directory. >&2 -exit /B 1 - -:ddk_found - - -:: CPU architecture - -if "%TC_ARG_ARCH%"=="-x64" ( - set TC_BUILD_ARCH=x64 WNET - set TC_BUILD_ARCH_DIR=amd64 - set TC_ARCH=x64 - set TC_ARCH_SUFFIX=-x64 - set TC_C_DISABLED_WARNINGS=%TC_C_DISABLED_WARNINGS% -wd4328 -wd4366 - set TC_LINKER_FLAGS=%TC_LINKER_FLAGS% -LTCG - if defined TC_KERNEL_TEST_CERTIFICATE_NAME set TC_TEST_SIGN=1 -) else ( - set TC_BUILD_ARCH=WXP - set TC_BUILD_ARCH_DIR=i386 - set TC_ARCH=x86 - set TC_ARCH_SUFFIX= -) - - -:: Build type - -if "%TC_ARG_TYPE%"=="-debug" ( - set TC_BUILD_TYPE=chk - set TC_C_DEFINES=%TC_C_DEFINES% -DDEBUG -D_DEBUG - set TC_BUILD_ALT_DIR=_driver_debug - set TC_COPY_DIR="..\Debug" -) else ( - set TC_BUILD_TYPE=fre - set TC_BUILD_ALT_DIR=_driver_release - set TC_COPY_DIR="..\Release" - set TC_TEST_SIGN=0 -) - - -:: WDK environment - -pushd . -call %TC_WINDDK_ROOT%\bin\setenv %TC_WINDDK_ROOT% %TC_BUILD_TYPE% %TC_BUILD_ARCH% no_oacr || exit /B %errorlevel% -popd - - -:: Build - -if "%TC_ARG_CMD%"=="-rebuild" (set TC_BUILD_OPTS=-c -Z) - -pushd . -:build_dirs - - if "%~1"=="" goto done - cd /D "%~1" || exit /B %errorlevel% - - if "%TC_ARG_CMD%"=="-clean" ( - rd /s /q obj%TC_BUILD_ALT_DIR%\%TC_BUILD_ARCH_DIR% 2>NUL: - rd /q obj%TC_BUILD_ALT_DIR% 2>NUL: - ) else ( - - set USER_C_FLAGS=%TC_C_FLAGS% %TC_C_DISABLED_WARNINGS% -FAcs -Fa%~1\obj%TC_BUILD_ALT_DIR%\%TC_BUILD_ARCH_DIR%\ - set MSC_WARNING_LEVEL=%TC_C_WARNING_LEVEL% - set C_DEFINES=%TC_C_DEFINES% - set RCOPTIONS=/I %MFC_INC_PATH% - set LIBRARIAN_FLAGS=%TC_LIBRARIAN_FLAGS% - set LINKER_FLAGS=%TC_LINKER_FLAGS% - set BUILD_ALT_DIR=%TC_BUILD_ALT_DIR% - - build %TC_BUILD_OPTS% -w -nmake /S -nmake /C 2>build_errors.log 1>&2 - - if errorlevel 1 ( - type build_errors.log - type build_errors_asm.log 2>NUL: - exit /B 1 - ) - del /q build_errors.log build_errors_asm.log build%BUILD_ALT_DIR%.* 2>NUL: - ) - - shift - -goto build_dirs -:done -popd - - -if "%TC_ARG_CMD%"=="-clean" exit /B 0 - -md "%TC_COPY_DIR%\Setup Files" >NUL: 2>NUL: -copy /B /Y obj%TC_BUILD_ALT_DIR%\%TC_BUILD_ARCH_DIR%\veracrypt.sys "%TC_COPY_DIR%\Setup Files\veracrypt%TC_ARCH_SUFFIX%.sys" >NUL: - -if errorlevel 1 ( - echo BuildDriver.cmd: error: Cannot copy target. >&2 - exit /B 1 -) - -if %TC_TEST_SIGN% equ 1 ( - signtool sign /s "%TC_KERNEL_TEST_CERTIFICATE_STORE%" /n "%TC_KERNEL_TEST_CERTIFICATE_NAME%" "%TC_COPY_DIR%\Setup Files\veracrypt%TC_ARCH_SUFFIX%.sys" >NUL: - - if errorlevel 1 ( - echo BuildDriver.cmd: error: Cannot test-sign target. >&2 - exit /B 1 - ) -) - -exit /B 0 +:: +:: 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. +:: + +:: Usage: BuildDriver <-build|-rebuild|-clean> <-release|-debug> <-x86|-x64> [dir2] ... + +@echo off +set TC_ARG_CMD=%~1 +shift +set TC_ARG_TYPE=%~1 +shift +set TC_ARG_ARCH=%~1 +shift + + +:: Windows Driver Kit build number + +set TC_WINDDK_BUILD=7600.16385.1 + + +:: Check for spaces in the current directory path + +cd | find " " >NUL: + +if %ERRORLEVEL% == 0 ( + echo BuildDriver.cmd: error: MS Build does not support building of projects stored in a path containing spaces. >&2 + exit /B 1 +) + + +:: Build options + +set TC_C_DEFINES=-D_WIN32 -DTC_WINDOWS_DRIVER +set TC_C_FLAGS=-nologo -I.. +set TC_C_WARNING_LEVEL=-W4 +set TC_C_DISABLED_WARNINGS=-wd4057 -wd4100 -wd4127 -wd4152 -wd4201 -wd4701 -wd4702 -wd4706 +set TC_LIBRARIAN_FLAGS=-nologo +set TC_LINKER_FLAGS=-nologo +set TC_TEST_SIGN=0 + + +:: Windows Driver Kit root + +set TC_WINDDK_ROOT=%SYSTEMDRIVE%\WinDDK\%TC_WINDDK_BUILD% +if exist "%TC_WINDDK_ROOT%\bin\setenv.bat" goto ddk_found + +set TC_WINDDK_ROOT=%WINDDK_ROOT%\%TC_WINDDK_BUILD% +if exist "%TC_WINDDK_ROOT%\bin\setenv.bat" goto ddk_found + +set TC_WINDDK_ROOT=%WINDDK_ROOT% +if exist "%TC_WINDDK_ROOT%\bin\setenv.bat" goto ddk_found + +echo BuildDriver.cmd: error: Windows Driver Development Kit not found in the default directory. Set WINDDK_ROOT environment variable to point to your Windows DDK installation directory. >&2 +exit /B 1 + +:ddk_found + + +:: CPU architecture + +if "%TC_ARG_ARCH%"=="-x64" ( + set TC_BUILD_ARCH=x64 WNET + set TC_BUILD_ARCH_DIR=amd64 + set TC_ARCH=x64 + set TC_ARCH_SUFFIX=-x64 + set TC_C_DISABLED_WARNINGS=%TC_C_DISABLED_WARNINGS% -wd4328 -wd4366 + set TC_LINKER_FLAGS=%TC_LINKER_FLAGS% -LTCG + if defined TC_KERNEL_TEST_CERTIFICATE_NAME set TC_TEST_SIGN=1 +) else ( + set TC_BUILD_ARCH=WXP + set TC_BUILD_ARCH_DIR=i386 + set TC_ARCH=x86 + set TC_ARCH_SUFFIX= +) + + +:: Build type + +if "%TC_ARG_TYPE%"=="-debug" ( + set TC_BUILD_TYPE=chk + set TC_C_DEFINES=%TC_C_DEFINES% -DDEBUG -D_DEBUG + set TC_BUILD_ALT_DIR=_driver_debug + set TC_COPY_DIR="..\Debug" +) else ( + set TC_BUILD_TYPE=fre + set TC_BUILD_ALT_DIR=_driver_release + set TC_COPY_DIR="..\Release" + set TC_TEST_SIGN=0 +) + + +:: WDK environment + +pushd . +call %TC_WINDDK_ROOT%\bin\setenv %TC_WINDDK_ROOT% %TC_BUILD_TYPE% %TC_BUILD_ARCH% no_oacr || exit /B %errorlevel% +popd + + +:: Build + +if "%TC_ARG_CMD%"=="-rebuild" (set TC_BUILD_OPTS=-c -Z) + +pushd . +:build_dirs + + if "%~1"=="" goto done + cd /D "%~1" || exit /B %errorlevel% + + if "%TC_ARG_CMD%"=="-clean" ( + rd /s /q obj%TC_BUILD_ALT_DIR%\%TC_BUILD_ARCH_DIR% 2>NUL: + rd /q obj%TC_BUILD_ALT_DIR% 2>NUL: + ) else ( + + set USER_C_FLAGS=%TC_C_FLAGS% %TC_C_DISABLED_WARNINGS% -FAcs -Fa%~1\obj%TC_BUILD_ALT_DIR%\%TC_BUILD_ARCH_DIR%\ + set MSC_WARNING_LEVEL=%TC_C_WARNING_LEVEL% + set C_DEFINES=%TC_C_DEFINES% + set RCOPTIONS=/I %MFC_INC_PATH% + set LIBRARIAN_FLAGS=%TC_LIBRARIAN_FLAGS% + set LINKER_FLAGS=%TC_LINKER_FLAGS% + set BUILD_ALT_DIR=%TC_BUILD_ALT_DIR% + + build %TC_BUILD_OPTS% -w -nmake /S -nmake /C 2>build_errors.log 1>&2 + + if errorlevel 1 ( + type build_errors.log + type build_errors_asm.log 2>NUL: + exit /B 1 + ) + del /q build_errors.log build_errors_asm.log build%BUILD_ALT_DIR%.* 2>NUL: + ) + + shift + +goto build_dirs +:done +popd + + +if "%TC_ARG_CMD%"=="-clean" exit /B 0 + +md "%TC_COPY_DIR%\Setup Files" >NUL: 2>NUL: +copy /B /Y obj%TC_BUILD_ALT_DIR%\%TC_BUILD_ARCH_DIR%\veracrypt.sys "%TC_COPY_DIR%\Setup Files\veracrypt%TC_ARCH_SUFFIX%.sys" >NUL: + +if errorlevel 1 ( + echo BuildDriver.cmd: error: Cannot copy target. >&2 + exit /B 1 +) + +if %TC_TEST_SIGN% equ 1 ( + signtool sign /s "%TC_KERNEL_TEST_CERTIFICATE_STORE%" /n "%TC_KERNEL_TEST_CERTIFICATE_NAME%" "%TC_COPY_DIR%\Setup Files\veracrypt%TC_ARCH_SUFFIX%.sys" >NUL: + + if errorlevel 1 ( + echo BuildDriver.cmd: error: Cannot test-sign target. >&2 + exit /B 1 + ) +) + +exit /B 0 diff --git a/src/Driver/DriveFilter.c b/src/Driver/DriveFilter.c index a8752a5f..c090ee8c 100644 --- a/src/Driver/DriveFilter.c +++ b/src/Driver/DriveFilter.c @@ -1,2153 +1,2153 @@ -/* - 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 "TCdefs.h" -#include -#include -#include -#include "Cache.h" -#include "Crc.h" -#include "Crypto.h" -#include "Apidrvr.h" -#include "EncryptedIoQueue.h" -#include "Common/Endian.h" -#include "Ntdriver.h" -#include "Ntvol.h" -#include "Volumes.h" -#include "VolumeFilter.h" -#include "Wipe.h" -#include "DriveFilter.h" -#include "Boot/Windows/BootCommon.h" - -static BOOL DeviceFilterActive = FALSE; - -BOOL BootArgsValid = FALSE; -BootArguments BootArgs; -static uint16 BootLoaderSegment; -static BOOL BootDriveSignatureValid = FALSE; - -static KMUTEX MountMutex; - -static volatile BOOL BootDriveFound = FALSE; -static DriveFilterExtension *BootDriveFilterExtension = NULL; -static LARGE_INTEGER BootDriveLength; -static byte BootLoaderFingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE]; - -static BOOL CrashDumpEnabled = FALSE; -static BOOL HibernationEnabled = FALSE; - -static BOOL LegacyHibernationDriverFilterActive = FALSE; -static byte *HibernationWriteBuffer = NULL; -static MDL *HibernationWriteBufferMdl = NULL; - -static uint32 HibernationPreventionCount = 0; - -static BootEncryptionSetupRequest SetupRequest; -static volatile BOOL SetupInProgress = FALSE; -PKTHREAD EncryptionSetupThread = NULL; -static volatile BOOL EncryptionSetupThreadAbortRequested; -static KSPIN_LOCK SetupStatusSpinLock; -static int64 SetupStatusEncryptedAreaEnd; -static BOOL TransformWaitingForIdle; -static NTSTATUS SetupResult; - -static WipeDecoySystemRequest WipeDecoyRequest; -static volatile BOOL DecoySystemWipeInProgress = FALSE; -static volatile BOOL DecoySystemWipeThreadAbortRequested; -static KSPIN_LOCK DecoySystemWipeStatusSpinLock; -static int64 DecoySystemWipedAreaEnd; -PKTHREAD DecoySystemWipeThread = NULL; -static NTSTATUS DecoySystemWipeResult; - - -NTSTATUS LoadBootArguments () -{ - NTSTATUS status = STATUS_UNSUCCESSFUL; - PHYSICAL_ADDRESS bootArgsAddr; - byte *mappedBootArgs; - uint16 bootLoaderSegment; - - KeInitializeMutex (&MountMutex, 0); - - for (bootLoaderSegment = TC_BOOT_LOADER_SEGMENT; - bootLoaderSegment >= TC_BOOT_LOADER_SEGMENT - 64 * 1024 / 16 && status != STATUS_SUCCESS; - bootLoaderSegment -= 32 * 1024 / 16) - { - bootArgsAddr.QuadPart = (bootLoaderSegment << 4) + TC_BOOT_LOADER_ARGS_OFFSET; - Dump ("Checking BootArguments at 0x%x\n", bootArgsAddr.LowPart); - - mappedBootArgs = MmMapIoSpace (bootArgsAddr, sizeof (BootArguments), MmCached); - if (!mappedBootArgs) - return STATUS_INSUFFICIENT_RESOURCES; - - if (TC_IS_BOOT_ARGUMENTS_SIGNATURE (mappedBootArgs)) - { - BootArguments *bootArguments = (BootArguments *) mappedBootArgs; - Dump ("BootArguments found at 0x%x\n", bootArgsAddr.LowPart); - - DumpMem (mappedBootArgs, sizeof (BootArguments)); - - if (bootArguments->BootLoaderVersion == VERSION_NUM - && bootArguments->BootArgumentsCrc32 != GetCrc32 ((byte *) bootArguments, (int) ((byte *) &bootArguments->BootArgumentsCrc32 - (byte *) bootArguments))) - { - Dump ("BootArguments CRC incorrect\n"); - TC_BUG_CHECK (STATUS_CRC_ERROR); - } - - // Sanity check: for valid boot argument, the password is less than 64 bytes long - if (bootArguments->BootPassword.Length <= MAX_PASSWORD) - { - BootLoaderSegment = bootLoaderSegment; - - BootArgs = *bootArguments; - BootArgsValid = TRUE; - burn (bootArguments, sizeof (*bootArguments)); - - BootDriveSignatureValid = TRUE; - - Dump ("BootLoaderVersion = %x\n", (int) BootArgs.BootLoaderVersion); - Dump ("HeaderSaltCrc32 = %x\n", (int) BootArgs.HeaderSaltCrc32); - Dump ("CryptoInfoOffset = %x\n", (int) BootArgs.CryptoInfoOffset); - Dump ("CryptoInfoLength = %d\n", (int) BootArgs.CryptoInfoLength); - Dump ("HiddenSystemPartitionStart = %I64u\n", BootArgs.HiddenSystemPartitionStart); - Dump ("DecoySystemPartitionStart = %I64u\n", BootArgs.DecoySystemPartitionStart); - Dump ("Flags = %x\n", BootArgs.Flags); - Dump ("BootDriveSignature = %x\n", BootArgs.BootDriveSignature); - Dump ("BootArgumentsCrc32 = %x\n", BootArgs.BootArgumentsCrc32); - - if (CacheBootPassword && BootArgs.BootPassword.Length > 0) - { - int pim = CacheBootPim? (int) (BootArgs.Flags >> 16) : 0; - AddPasswordToCache (&BootArgs.BootPassword, pim); - } - - // clear fingerprint - burn (BootLoaderFingerprint, sizeof (BootLoaderFingerprint)); - - status = STATUS_SUCCESS; - } - } - - MmUnmapIoSpace (mappedBootArgs, sizeof (BootArguments)); - } - - return status; -} - - -NTSTATUS DriveFilterAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo) -{ - DriveFilterExtension *Extension; - NTSTATUS status; - PDEVICE_OBJECT filterDeviceObject = NULL; - PDEVICE_OBJECT attachedDeviceObject; - - Dump ("DriveFilterAddDevice pdo=%p\n", pdo); - - attachedDeviceObject = IoGetAttachedDeviceReference (pdo); - status = IoCreateDevice (driverObject, sizeof (DriveFilterExtension), NULL, attachedDeviceObject->DeviceType, 0, FALSE, &filterDeviceObject); - - ObDereferenceObject (attachedDeviceObject); - - if (!NT_SUCCESS (status)) - { - filterDeviceObject = NULL; - goto err; - } - - Extension = (DriveFilterExtension *) filterDeviceObject->DeviceExtension; - memset (Extension, 0, sizeof (DriveFilterExtension)); - - status = IoAttachDeviceToDeviceStackSafe (filterDeviceObject, pdo, &(Extension->LowerDeviceObject)); - if (!NT_SUCCESS (status)) - { - goto err; - } - - if (!Extension->LowerDeviceObject) - { - status = STATUS_DEVICE_REMOVED; - goto err; - } - - Extension->IsDriveFilterDevice = Extension->Queue.IsFilterDevice = TRUE; - Extension->DeviceObject = Extension->Queue.DeviceObject = filterDeviceObject; - Extension->Pdo = pdo; - - Extension->Queue.LowerDeviceObject = Extension->LowerDeviceObject; - IoInitializeRemoveLock (&Extension->Queue.RemoveLock, 'LRCV', 0, 0); - - Extension->ConfiguredEncryptedAreaStart = -1; - Extension->ConfiguredEncryptedAreaEnd = -1; - Extension->Queue.EncryptedAreaStart = -1; - Extension->Queue.EncryptedAreaEnd = -1; - Extension->Queue.EncryptedAreaEndUpdatePending = FALSE; - - filterDeviceObject->Flags |= Extension->LowerDeviceObject->Flags & (DO_DIRECT_IO | DO_BUFFERED_IO | DO_POWER_PAGABLE); - filterDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; - - DeviceFilterActive = TRUE; - return status; - -err: - if (filterDeviceObject) - { - if (Extension->LowerDeviceObject) - IoDetachDevice (Extension->LowerDeviceObject); - - IoDeleteDevice (filterDeviceObject); - } - - return status; -} - - -static void DismountDrive (DriveFilterExtension *Extension, BOOL stopIoQueue) -{ - Dump ("Dismounting drive\n"); - ASSERT (Extension->DriveMounted); - - if (stopIoQueue && EncryptedIoQueueIsRunning (&Extension->Queue)) - EncryptedIoQueueStop (&Extension->Queue); - - crypto_close (Extension->Queue.CryptoInfo); - Extension->Queue.CryptoInfo = NULL; - - crypto_close (Extension->HeaderCryptoInfo); - Extension->HeaderCryptoInfo = NULL; - - Extension->DriveMounted = FALSE; -} - -static void ComputeBootLoaderFingerprint(PDEVICE_OBJECT LowerDeviceObject, byte* ioBuffer /* ioBuffer must be at least 512 bytes long */) -{ - NTSTATUS status; - LARGE_INTEGER offset; - WHIRLPOOL_CTX whirlpool; - sha512_ctx sha2; - ULONG bytesToRead, remainingBytes, bootloaderTotalSize = TC_BOOT_LOADER_AREA_SIZE - TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE; - - // clear fingerprint - burn (BootLoaderFingerprint, sizeof (BootLoaderFingerprint)); - - // compute Whirlpool+SHA512 fingerprint of bootloader including MBR - // we skip user configuration fields: - // TC_BOOT_SECTOR_PIM_VALUE_OFFSET = 400 - // TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET = 402 - // => TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE = 4 - // TC_BOOT_SECTOR_USER_MESSAGE_OFFSET = 406 - // => TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH = 24 - // TC_BOOT_SECTOR_USER_CONFIG_OFFSET = 438 - // - // we have: TC_BOOT_SECTOR_USER_MESSAGE_OFFSET = TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE - - WHIRLPOOL_init (&whirlpool); - sha512_begin (&sha2); - // read the first 512 bytes - offset.QuadPart = 0; - - status = TCReadDevice (LowerDeviceObject, ioBuffer, offset, TC_SECTOR_SIZE_BIOS); - if (NT_SUCCESS (status)) - { - WHIRLPOOL_add (ioBuffer, TC_BOOT_SECTOR_PIM_VALUE_OFFSET * 8, &whirlpool); - WHIRLPOOL_add (ioBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH, (TC_BOOT_SECTOR_USER_CONFIG_OFFSET - (TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH)) * 8, &whirlpool); - WHIRLPOOL_add (ioBuffer + TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1, (TC_MAX_MBR_BOOT_CODE_SIZE - (TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1)) * 8, &whirlpool); - - sha512_hash (ioBuffer, TC_BOOT_SECTOR_PIM_VALUE_OFFSET, &sha2); - sha512_hash (ioBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH, (TC_BOOT_SECTOR_USER_CONFIG_OFFSET - (TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH)), &sha2); - sha512_hash (ioBuffer + TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1, (TC_MAX_MBR_BOOT_CODE_SIZE - (TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1)), &sha2); - - // we has the reste of the bootloader, 512 bytes at a time - offset.QuadPart = TC_SECTOR_SIZE_BIOS; - remainingBytes = bootloaderTotalSize - TC_SECTOR_SIZE_BIOS; - - while (NT_SUCCESS (status) && (remainingBytes > 0)) - { - bytesToRead = (remainingBytes >= TC_SECTOR_SIZE_BIOS)? TC_SECTOR_SIZE_BIOS : remainingBytes; - status = TCReadDevice (LowerDeviceObject, ioBuffer, offset, bytesToRead); - if (NT_SUCCESS (status)) - { - remainingBytes -= bytesToRead; - offset.QuadPart += bytesToRead; - WHIRLPOOL_add (ioBuffer, bytesToRead * 8, &whirlpool); - sha512_hash (ioBuffer, bytesToRead, &sha2); - } - else - { - Dump ("TCReadDevice error %x during ComputeBootLoaderFingerprint call\n", status); - break; - } - } - - if (NT_SUCCESS (status)) - { - WHIRLPOOL_finalize (&whirlpool, BootLoaderFingerprint); - sha512_end (&BootLoaderFingerprint [WHIRLPOOL_DIGESTSIZE], &sha2); - } - } - else - { - Dump ("TCReadDevice error %x during ComputeBootLoaderFingerprint call\n", status); - } -} - - -static NTSTATUS MountDrive (DriveFilterExtension *Extension, Password *password, uint32 *headerSaltCrc32) -{ - BOOL hiddenVolume = (BootArgs.HiddenSystemPartitionStart != 0); - int64 hiddenHeaderOffset = BootArgs.HiddenSystemPartitionStart + TC_HIDDEN_VOLUME_HEADER_OFFSET; - NTSTATUS status; - LARGE_INTEGER offset; - char *header; - int pkcs5_prf = 0, pim = 0; - byte *mappedCryptoInfo = NULL; - - Dump ("MountDrive pdo=%p\n", Extension->Pdo); - ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL); - - // Check boot drive signature first (header CRC search could fail if a user restored the header to a non-boot drive) - if (BootDriveSignatureValid) - { - byte mbr[TC_SECTOR_SIZE_BIOS]; - - offset.QuadPart = 0; - status = TCReadDevice (Extension->LowerDeviceObject, mbr, offset, TC_SECTOR_SIZE_BIOS); - - if (NT_SUCCESS (status) && BootArgs.BootDriveSignature != *(uint32 *) (mbr + 0x1b8)) - return STATUS_UNSUCCESSFUL; - } - - header = TCalloc (TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); - if (!header) - return STATUS_INSUFFICIENT_RESOURCES; - - offset.QuadPart = hiddenVolume ? hiddenHeaderOffset : TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET; - Dump ("Reading volume header at %I64u\n", offset.QuadPart); - - status = TCReadDevice (Extension->LowerDeviceObject, header, offset, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); - if (!NT_SUCCESS (status)) - { - Dump ("TCReadDevice error %x\n", status); - goto ret; - } - - if (headerSaltCrc32) - { - uint32 saltCrc = GetCrc32 (header, PKCS5_SALT_SIZE); - - if (saltCrc != *headerSaltCrc32) - { - status = STATUS_UNSUCCESSFUL; - goto ret; - } - - Extension->VolumeHeaderSaltCrc32 = saltCrc; - } - - Extension->HeaderCryptoInfo = crypto_open(); - if (!Extension->HeaderCryptoInfo) - { - status = STATUS_INSUFFICIENT_RESOURCES; - goto ret; - } - - if (BootArgs.CryptoInfoLength > 0) - { - PHYSICAL_ADDRESS cryptoInfoAddress; - - cryptoInfoAddress.QuadPart = (BootLoaderSegment << 4) + BootArgs.CryptoInfoOffset; -#ifdef DEBUG - Dump ("Wiping memory %x %d\n", cryptoInfoAddress.LowPart, BootArgs.CryptoInfoLength); -#endif - mappedCryptoInfo = MmMapIoSpace (cryptoInfoAddress, BootArgs.CryptoInfoLength, MmCached); - if (mappedCryptoInfo) - { - /* Get the parameters used for booting to speed up driver startup and avoid testing irrelevant PRFs */ - BOOT_CRYPTO_HEADER* pBootCryptoInfo = (BOOT_CRYPTO_HEADER*) mappedCryptoInfo; - Hash* pHash = HashGet(pBootCryptoInfo->pkcs5); - if (pHash && pHash->SystemEncryption) - pkcs5_prf = pBootCryptoInfo->pkcs5; - } - } - - pim = (int) (BootArgs.Flags >> 16); - - if (ReadVolumeHeader (!hiddenVolume, header, password, pkcs5_prf, pim, FALSE, &Extension->Queue.CryptoInfo, Extension->HeaderCryptoInfo) == 0) - { - // Header decrypted - status = STATUS_SUCCESS; - Dump ("Header decrypted\n"); - - // calculate Fingerprint - ComputeBootLoaderFingerprint (Extension->LowerDeviceObject, header); - - if (Extension->Queue.CryptoInfo->hiddenVolume) - { - int64 hiddenPartitionOffset = BootArgs.HiddenSystemPartitionStart; - Dump ("Hidden volume start offset = %I64d\n", Extension->Queue.CryptoInfo->EncryptedAreaStart.Value + hiddenPartitionOffset); - - Extension->HiddenSystem = TRUE; - - Extension->Queue.RemapEncryptedArea = TRUE; - Extension->Queue.RemappedAreaOffset = hiddenPartitionOffset + Extension->Queue.CryptoInfo->EncryptedAreaStart.Value - BootArgs.DecoySystemPartitionStart; - Extension->Queue.RemappedAreaDataUnitOffset = Extension->Queue.CryptoInfo->EncryptedAreaStart.Value / ENCRYPTION_DATA_UNIT_SIZE - BootArgs.DecoySystemPartitionStart / ENCRYPTION_DATA_UNIT_SIZE; - - Extension->Queue.CryptoInfo->EncryptedAreaStart.Value = BootArgs.DecoySystemPartitionStart; - - if (Extension->Queue.CryptoInfo->VolumeSize.Value > hiddenPartitionOffset - BootArgs.DecoySystemPartitionStart) - TC_THROW_FATAL_EXCEPTION; - - Dump ("RemappedAreaOffset = %I64d\n", Extension->Queue.RemappedAreaOffset); - Dump ("RemappedAreaDataUnitOffset = %I64d\n", Extension->Queue.RemappedAreaDataUnitOffset); - } - else - { - Extension->HiddenSystem = FALSE; - Extension->Queue.RemapEncryptedArea = FALSE; - } - - Extension->ConfiguredEncryptedAreaStart = Extension->Queue.CryptoInfo->EncryptedAreaStart.Value; - Extension->ConfiguredEncryptedAreaEnd = Extension->Queue.CryptoInfo->EncryptedAreaStart.Value + Extension->Queue.CryptoInfo->VolumeSize.Value - 1; - - Extension->Queue.EncryptedAreaStart = Extension->Queue.CryptoInfo->EncryptedAreaStart.Value; - Extension->Queue.EncryptedAreaEnd = Extension->Queue.CryptoInfo->EncryptedAreaStart.Value + Extension->Queue.CryptoInfo->EncryptedAreaLength.Value - 1; - - if (Extension->Queue.CryptoInfo->EncryptedAreaLength.Value == 0) - { - Extension->Queue.EncryptedAreaStart = -1; - Extension->Queue.EncryptedAreaEnd = -1; - } - - Dump ("Loaded: ConfiguredEncryptedAreaStart=%I64d (%I64d) ConfiguredEncryptedAreaEnd=%I64d (%I64d)\n", Extension->ConfiguredEncryptedAreaStart / 1024 / 1024, Extension->ConfiguredEncryptedAreaStart, Extension->ConfiguredEncryptedAreaEnd / 1024 / 1024, Extension->ConfiguredEncryptedAreaEnd); - Dump ("Loaded: EncryptedAreaStart=%I64d (%I64d) EncryptedAreaEnd=%I64d (%I64d)\n", Extension->Queue.EncryptedAreaStart / 1024 / 1024, Extension->Queue.EncryptedAreaStart, Extension->Queue.EncryptedAreaEnd / 1024 / 1024, Extension->Queue.EncryptedAreaEnd); - - // Erase boot loader scheduled keys - if (mappedCryptoInfo) - { - burn (mappedCryptoInfo, BootArgs.CryptoInfoLength); - MmUnmapIoSpace (mappedCryptoInfo, BootArgs.CryptoInfoLength); - BootArgs.CryptoInfoLength = 0; - } - - BootDriveFilterExtension = Extension; - BootDriveFound = Extension->BootDrive = Extension->DriveMounted = Extension->VolumeHeaderPresent = TRUE; - BootDriveFilterExtension->MagicNumber = TC_BOOT_DRIVE_FILTER_EXTENSION_MAGIC_NUMBER; - - burn (&BootArgs.BootPassword, sizeof (BootArgs.BootPassword)); - - { - STORAGE_DEVICE_NUMBER storageDeviceNumber; - status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &storageDeviceNumber, sizeof (storageDeviceNumber)); - - if (!NT_SUCCESS (status)) - { - Dump ("Failed to get drive number - error %x\n", status); - Extension->SystemStorageDeviceNumberValid = FALSE; - } - else - { - Extension->SystemStorageDeviceNumber = storageDeviceNumber.DeviceNumber; - Extension->SystemStorageDeviceNumberValid = TRUE; - } - } - - status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &BootDriveLength, sizeof (BootDriveLength)); - - if (!NT_SUCCESS (status)) - { - Dump ("Failed to get drive length - error %x\n", status); - BootDriveLength.QuadPart = 0; - Extension->Queue.MaxReadAheadOffset.QuadPart = 0; - } - else - Extension->Queue.MaxReadAheadOffset = BootDriveLength; - - status = EncryptedIoQueueStart (&Extension->Queue); - if (!NT_SUCCESS (status)) - TC_BUG_CHECK (status); - - if (IsOSAtLeast (WIN_VISTA)) - { - CrashDumpEnabled = TRUE; - HibernationEnabled = TRUE; - } - else if (!LegacyHibernationDriverFilterActive) - StartLegacyHibernationDriverFilter(); - - // Hidden system hibernation is not supported if an extra boot partition is present as the system is not allowed to update the boot partition - if (IsHiddenSystemRunning() && (BootArgs.Flags & TC_BOOT_ARGS_FLAG_EXTRA_BOOT_PARTITION)) - { - CrashDumpEnabled = FALSE; - HibernationEnabled = FALSE; - } - } - else - { - Dump ("Header not decrypted\n"); - crypto_close (Extension->HeaderCryptoInfo); - Extension->HeaderCryptoInfo = NULL; - - status = STATUS_UNSUCCESSFUL; - } - -ret: - TCfree (header); - return status; -} - - -static NTSTATUS SaveDriveVolumeHeader (DriveFilterExtension *Extension) -{ - NTSTATUS status = STATUS_SUCCESS; - LARGE_INTEGER offset; - byte *header; - - header = TCalloc (TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); - if (!header) - return STATUS_INSUFFICIENT_RESOURCES; - - offset.QuadPart = TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET; - - status = TCReadDevice (Extension->LowerDeviceObject, header, offset, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); - if (!NT_SUCCESS (status)) - { - Dump ("TCReadDevice error %x", status); - goto ret; - } - - Dump ("Saving: ConfiguredEncryptedAreaStart=%I64d (%I64d) ConfiguredEncryptedAreaEnd=%I64d (%I64d)\n", Extension->ConfiguredEncryptedAreaStart / 1024 / 1024, Extension->ConfiguredEncryptedAreaStart, Extension->ConfiguredEncryptedAreaEnd / 1024 / 1024, Extension->ConfiguredEncryptedAreaEnd); - Dump ("Saving: EncryptedAreaStart=%I64d (%I64d) EncryptedAreaEnd=%I64d (%I64d)\n", Extension->Queue.EncryptedAreaStart / 1024 / 1024, Extension->Queue.EncryptedAreaStart, Extension->Queue.EncryptedAreaEnd / 1024 / 1024, Extension->Queue.EncryptedAreaEnd); - - if (Extension->Queue.EncryptedAreaStart == -1 || Extension->Queue.EncryptedAreaEnd == -1 - || Extension->Queue.EncryptedAreaEnd <= Extension->Queue.EncryptedAreaStart) - { - if (SetupRequest.SetupMode == SetupDecryption) - { - memset (header, 0, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); - Extension->VolumeHeaderPresent = FALSE; - } - } - else - { - uint32 headerCrc32; - uint64 encryptedAreaLength = Extension->Queue.EncryptedAreaEnd + 1 - Extension->Queue.EncryptedAreaStart; - byte *fieldPos = header + TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH; - - DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, Extension->HeaderCryptoInfo); - - if (GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x56455241) - { - Dump ("Header not decrypted"); - status = STATUS_UNKNOWN_REVISION; - goto ret; - } - - mputInt64 (fieldPos, encryptedAreaLength); - - headerCrc32 = GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC); - fieldPos = header + TC_HEADER_OFFSET_HEADER_CRC; - mputLong (fieldPos, headerCrc32); - - EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, Extension->HeaderCryptoInfo); - } - - status = TCWriteDevice (Extension->LowerDeviceObject, header, offset, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); - if (!NT_SUCCESS (status)) - { - Dump ("TCWriteDevice error %x", status); - goto ret; - } - -ret: - TCfree (header); - return status; -} - - -static NTSTATUS PassIrp (PDEVICE_OBJECT deviceObject, PIRP irp) -{ - IoSkipCurrentIrpStackLocation (irp); - return IoCallDriver (deviceObject, irp); -} - - -static NTSTATUS PassFilteredIrp (PDEVICE_OBJECT deviceObject, PIRP irp, PIO_COMPLETION_ROUTINE completionRoutine, PVOID completionRoutineArg) -{ - IoCopyCurrentIrpStackLocationToNext (irp); - - if (completionRoutine) - IoSetCompletionRoutine (irp, completionRoutine, completionRoutineArg, TRUE, TRUE, TRUE); - - return IoCallDriver (deviceObject, irp); -} - - -static NTSTATUS OnDeviceUsageNotificationCompleted (PDEVICE_OBJECT filterDeviceObject, PIRP Irp, DriveFilterExtension *Extension) -{ - if (Irp->PendingReturned) - IoMarkIrpPending (Irp); - - if (!(Extension->LowerDeviceObject->Flags & DO_POWER_PAGABLE)) - filterDeviceObject->Flags &= ~DO_POWER_PAGABLE; - - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return STATUS_CONTINUE_COMPLETION; -} - - -static BOOL IsVolumeDevice (PDEVICE_OBJECT deviceObject) -{ - VOLUME_NUMBER volNumber; - VOLUME_DISK_EXTENTS extents[2]; - NTSTATUS extentStatus = SendDeviceIoControlRequest (deviceObject, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, extents, sizeof (extents)); - - return NT_SUCCESS (SendDeviceIoControlRequest (deviceObject, IOCTL_VOLUME_SUPPORTS_ONLINE_OFFLINE, NULL, 0, NULL, 0)) - || NT_SUCCESS (SendDeviceIoControlRequest (deviceObject, IOCTL_VOLUME_IS_OFFLINE, NULL, 0, NULL, 0)) - || NT_SUCCESS (SendDeviceIoControlRequest (deviceObject, IOCTL_VOLUME_IS_IO_CAPABLE, NULL, 0, NULL, 0)) - || NT_SUCCESS (SendDeviceIoControlRequest (deviceObject, IOCTL_VOLUME_IS_PARTITION, NULL, 0, NULL, 0)) - || NT_SUCCESS (SendDeviceIoControlRequest (deviceObject, IOCTL_VOLUME_QUERY_VOLUME_NUMBER, NULL, 0, &volNumber, sizeof (volNumber))) - || NT_SUCCESS (extentStatus) || extentStatus == STATUS_BUFFER_OVERFLOW || extentStatus == STATUS_BUFFER_TOO_SMALL; -} - - -static void CheckDeviceTypeAndMount (DriveFilterExtension *filterExtension) -{ - if (BootArgsValid) - { - // Windows sometimes merges a removable drive PDO and its volume PDO to a single PDO having no volume interface (GUID_DEVINTERFACE_VOLUME). - // Therefore, we need to test whether the device supports volume IOCTLs. - if (VolumeClassFilterRegistered - && BootArgs.HiddenSystemPartitionStart != 0 - && IsVolumeDevice (filterExtension->LowerDeviceObject)) - { - Dump ("Drive and volume merged pdo=%p", filterExtension->Pdo); - - filterExtension->IsVolumeFilterDevice = TRUE; - filterExtension->IsDriveFilterDevice = FALSE; - } - else - { - NTSTATUS status = KeWaitForMutexObject (&MountMutex, Executive, KernelMode, FALSE, NULL); - if (!NT_SUCCESS (status)) - TC_BUG_CHECK (status); - - if (!BootDriveFound) - MountDrive (filterExtension, &BootArgs.BootPassword, &BootArgs.HeaderSaltCrc32); - - KeReleaseMutex (&MountMutex, FALSE); - } - } -} - - -static VOID MountDriveWorkItemRoutine (PDEVICE_OBJECT deviceObject, DriveFilterExtension *filterExtension) -{ - CheckDeviceTypeAndMount (filterExtension); - KeSetEvent (&filterExtension->MountWorkItemCompletedEvent, IO_NO_INCREMENT, FALSE); -} - - -static NTSTATUS OnStartDeviceCompleted (PDEVICE_OBJECT filterDeviceObject, PIRP Irp, DriveFilterExtension *Extension) -{ - if (Irp->PendingReturned) - IoMarkIrpPending (Irp); - - if (Extension->LowerDeviceObject->Characteristics & FILE_REMOVABLE_MEDIA) - filterDeviceObject->Characteristics |= FILE_REMOVABLE_MEDIA; - - if (KeGetCurrentIrql() == PASSIVE_LEVEL) - { - CheckDeviceTypeAndMount (Extension); - } - else - { - PIO_WORKITEM workItem = IoAllocateWorkItem (filterDeviceObject); - if (!workItem) - { - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return STATUS_INSUFFICIENT_RESOURCES; - } - - KeInitializeEvent (&Extension->MountWorkItemCompletedEvent, SynchronizationEvent, FALSE); - IoQueueWorkItem (workItem, MountDriveWorkItemRoutine, DelayedWorkQueue, Extension); - - KeWaitForSingleObject (&Extension->MountWorkItemCompletedEvent, Executive, KernelMode, FALSE, NULL); - IoFreeWorkItem (workItem); - } - - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return STATUS_CONTINUE_COMPLETION; -} - - -static NTSTATUS DispatchPnp (PDEVICE_OBJECT DeviceObject, PIRP Irp, DriveFilterExtension *Extension, PIO_STACK_LOCATION irpSp) -{ - NTSTATUS status; - - status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); - if (!NT_SUCCESS (status)) - return TCCompleteIrp (Irp, status, 0); - - switch (irpSp->MinorFunction) - { - case IRP_MN_START_DEVICE: - Dump ("IRP_MN_START_DEVICE pdo=%p\n", Extension->Pdo); - return PassFilteredIrp (Extension->LowerDeviceObject, Irp, OnStartDeviceCompleted, Extension); - - - case IRP_MN_DEVICE_USAGE_NOTIFICATION: - Dump ("IRP_MN_DEVICE_USAGE_NOTIFICATION type=%d\n", (int) irpSp->Parameters.UsageNotification.Type); - - { - PDEVICE_OBJECT attachedDevice = IoGetAttachedDeviceReference (DeviceObject); - - if (attachedDevice == DeviceObject || (attachedDevice->Flags & DO_POWER_PAGABLE)) - DeviceObject->Flags |= DO_POWER_PAGABLE; - - ObDereferenceObject (attachedDevice); - } - - // Prevent creation of hibernation and crash dump files if required - if (irpSp->Parameters.UsageNotification.InPath - && ( - (irpSp->Parameters.UsageNotification.Type == DeviceUsageTypeDumpFile && !CrashDumpEnabled) - || (irpSp->Parameters.UsageNotification.Type == DeviceUsageTypeHibernation && !HibernationEnabled) - ) - ) - { - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - - if (irpSp->Parameters.UsageNotification.Type == DeviceUsageTypeHibernation) - ++HibernationPreventionCount; - - Dump ("Preventing dump type=%d\n", (int) irpSp->Parameters.UsageNotification.Type); - return TCCompleteIrp (Irp, STATUS_UNSUCCESSFUL, 0); - } - - return PassFilteredIrp (Extension->LowerDeviceObject, Irp, OnDeviceUsageNotificationCompleted, Extension); - - - case IRP_MN_REMOVE_DEVICE: - Dump ("IRP_MN_REMOVE_DEVICE pdo=%p\n", Extension->Pdo); - - IoReleaseRemoveLockAndWait (&Extension->Queue.RemoveLock, Irp); - status = PassIrp (Extension->LowerDeviceObject, Irp); - - IoDetachDevice (Extension->LowerDeviceObject); - - if (Extension->DriveMounted) - DismountDrive (Extension, TRUE); - - if (Extension->BootDrive) - { - BootDriveFound = FALSE; - BootDriveFilterExtension = NULL; - } - - IoDeleteDevice (DeviceObject); - return status; - - - default: - status = PassIrp (Extension->LowerDeviceObject, Irp); - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - } - return status; -} - - -static NTSTATUS DispatchPower (PDEVICE_OBJECT DeviceObject, PIRP Irp, DriveFilterExtension *Extension, PIO_STACK_LOCATION irpSp) -{ - NTSTATUS status; - Dump ("IRP_MJ_POWER minor=%d type=%d shutdown=%d\n", (int) irpSp->MinorFunction, (int) irpSp->Parameters.Power.Type, (int) irpSp->Parameters.Power.ShutdownType); - - if (SetupInProgress - && irpSp->MinorFunction == IRP_MN_SET_POWER - && irpSp->Parameters.Power.ShutdownType == PowerActionHibernate) - { - while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES); - } - -#if 0 // Dismount of the system drive is disabled until there is a way to do it without causing system errors (see the documentation for more info) - if (DriverShuttingDown - && Extension->BootDrive - && Extension->DriveMounted - && irpSp->MinorFunction == IRP_MN_SET_POWER - && irpSp->Parameters.Power.Type == DevicePowerState) - { - DismountDrive (Extension, TRUE); - } -#endif // 0 - - PoStartNextPowerIrp (Irp); - - status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); - if (!NT_SUCCESS (status)) - return TCCompleteIrp (Irp, status, 0); - - IoSkipCurrentIrpStackLocation (Irp); - status = PoCallDriver (Extension->LowerDeviceObject, Irp); - - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return status; -} - - -NTSTATUS DriveFilterDispatchIrp (PDEVICE_OBJECT DeviceObject, PIRP Irp) -{ - DriveFilterExtension *Extension = (DriveFilterExtension *) DeviceObject->DeviceExtension; - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); - NTSTATUS status; - - ASSERT (!Extension->bRootDevice && Extension->IsDriveFilterDevice); - - switch (irpSp->MajorFunction) - { - case IRP_MJ_READ: - case IRP_MJ_WRITE: - if (Extension->BootDrive) - { - status = EncryptedIoQueueAddIrp (&Extension->Queue, Irp); - - if (status != STATUS_PENDING) - TCCompleteDiskIrp (Irp, status, 0); - - return status; - } - break; - - case IRP_MJ_PNP: - return DispatchPnp (DeviceObject, Irp, Extension, irpSp); - - case IRP_MJ_POWER: - return DispatchPower (DeviceObject, Irp, Extension, irpSp); - } - - status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); - if (!NT_SUCCESS (status)) - return TCCompleteIrp (Irp, status, 0); - - status = PassIrp (Extension->LowerDeviceObject, Irp); - - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return status; -} - - -void ReopenBootVolumeHeader (PIRP irp, PIO_STACK_LOCATION irpSp) -{ - LARGE_INTEGER offset; - char *header; - ReopenBootVolumeHeaderRequest *request = (ReopenBootVolumeHeaderRequest *) irp->AssociatedIrp.SystemBuffer; - - irp->IoStatus.Information = 0; - - if (!IoIsSystemThread (PsGetCurrentThread()) && !UserCanAccessDriveDevice()) - { - irp->IoStatus.Status = STATUS_ACCESS_DENIED; - return; - } - - if (!ValidateIOBufferSize (irp, sizeof (ReopenBootVolumeHeaderRequest), ValidateInput)) - return; - - if (!BootDriveFound || !BootDriveFilterExtension || !BootDriveFilterExtension->DriveMounted || !BootDriveFilterExtension->HeaderCryptoInfo - || request->VolumePassword.Length > MAX_PASSWORD - || request->pkcs5_prf < 0 - || request->pkcs5_prf > LAST_PRF_ID - || request->pim < 0 - || request->pim > 65535 - ) - { - irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - goto wipe; - } - - header = TCalloc (TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); - if (!header) - { - irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; - goto wipe; - } - - if (BootDriveFilterExtension->HiddenSystem) - offset.QuadPart = BootArgs.HiddenSystemPartitionStart + TC_HIDDEN_VOLUME_HEADER_OFFSET; - else - offset.QuadPart = TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET; - - irp->IoStatus.Status = TCReadDevice (BootDriveFilterExtension->LowerDeviceObject, header, offset, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); - if (!NT_SUCCESS (irp->IoStatus.Status)) - { - Dump ("TCReadDevice error %x\n", irp->IoStatus.Status); - goto ret; - } - - if (ReadVolumeHeader (!BootDriveFilterExtension->HiddenSystem, header, &request->VolumePassword, request->pkcs5_prf, request->pim, FALSE, NULL, BootDriveFilterExtension->HeaderCryptoInfo) == 0) - { - Dump ("Header reopened\n"); - ComputeBootLoaderFingerprint (BootDriveFilterExtension->LowerDeviceObject, header); - - BootDriveFilterExtension->Queue.CryptoInfo->header_creation_time = BootDriveFilterExtension->HeaderCryptoInfo->header_creation_time; - BootDriveFilterExtension->Queue.CryptoInfo->pkcs5 = BootDriveFilterExtension->HeaderCryptoInfo->pkcs5; - BootDriveFilterExtension->Queue.CryptoInfo->noIterations = BootDriveFilterExtension->HeaderCryptoInfo->noIterations; - BootDriveFilterExtension->Queue.CryptoInfo->volumePim = BootDriveFilterExtension->HeaderCryptoInfo->volumePim; - - irp->IoStatus.Status = STATUS_SUCCESS; - } - else - { - crypto_close (BootDriveFilterExtension->HeaderCryptoInfo); - BootDriveFilterExtension->HeaderCryptoInfo = NULL; - - Dump ("Header not reopened\n"); - irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - } - -ret: - TCfree (header); -wipe: - burn (request, sizeof (*request)); -} - - -// Legacy Windows XP/2003 hibernation dump filter - -typedef NTSTATUS (*HiberDriverWriteFunctionA) (ULONG arg0, PLARGE_INTEGER writeOffset, PMDL dataMdl, PVOID arg3); -typedef NTSTATUS (*HiberDriverWriteFunctionB) (PLARGE_INTEGER writeOffset, PMDL dataMdl); - -typedef struct -{ -#ifdef _WIN64 - byte FieldPad1[64]; - HiberDriverWriteFunctionB WriteFunctionB; - byte FieldPad2[56]; -#else - byte FieldPad1[48]; - HiberDriverWriteFunctionB WriteFunctionB; - byte FieldPad2[32]; -#endif - HiberDriverWriteFunctionA WriteFunctionA; - byte FieldPad3[24]; - LARGE_INTEGER PartitionStartOffset; -} HiberDriverContext; - -typedef NTSTATUS (*HiberDriverEntry) (PVOID arg0, HiberDriverContext *hiberDriverContext); - -typedef struct -{ - LIST_ENTRY ModuleList; -#ifdef _WIN64 - byte FieldPad1[32]; -#else - byte FieldPad1[16]; -#endif - PVOID ModuleBaseAddress; - HiberDriverEntry ModuleEntryAddress; -#ifdef _WIN64 - byte FieldPad2[24]; -#else - byte FieldPad2[12]; -#endif - UNICODE_STRING ModuleName; -} ModuleTableItem; - - -#define TC_MAX_HIBER_FILTER_COUNT 3 -static int LastHiberFilterNumber = 0; - -static HiberDriverEntry OriginalHiberDriverEntries[TC_MAX_HIBER_FILTER_COUNT]; -static HiberDriverWriteFunctionA OriginalHiberDriverWriteFunctionsA[TC_MAX_HIBER_FILTER_COUNT]; -static HiberDriverWriteFunctionB OriginalHiberDriverWriteFunctionsB[TC_MAX_HIBER_FILTER_COUNT]; - -static LARGE_INTEGER HiberPartitionOffset; - - -static NTSTATUS HiberDriverWriteFunctionFilter (int filterNumber, PLARGE_INTEGER writeOffset, PMDL dataMdl, BOOL writeB, ULONG arg0WriteA, PVOID arg3WriteA) -{ - MDL *encryptedDataMdl = dataMdl; - - if (writeOffset && dataMdl && BootDriveFilterExtension && BootDriveFilterExtension->DriveMounted) - { - ULONG dataLength = MmGetMdlByteCount (dataMdl); - - if (dataMdl->MappedSystemVa && dataLength > 0) - { - uint64 offset = HiberPartitionOffset.QuadPart + writeOffset->QuadPart; - uint64 intersectStart; - uint32 intersectLength; - - if (dataLength > TC_HIBERNATION_WRITE_BUFFER_SIZE) - TC_BUG_CHECK (STATUS_BUFFER_OVERFLOW); - - if ((dataLength & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0) - TC_BUG_CHECK (STATUS_INVALID_PARAMETER); - - if ((offset & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0) - TC_BUG_CHECK (STATUS_INVALID_PARAMETER); - - GetIntersection (offset, - dataLength, - BootDriveFilterExtension->Queue.EncryptedAreaStart, - BootDriveFilterExtension->Queue.EncryptedAreaEnd, - &intersectStart, - &intersectLength); - - if (intersectLength > 0) - { - UINT64_STRUCT dataUnit; - dataUnit.Value = intersectStart / ENCRYPTION_DATA_UNIT_SIZE; - - memcpy (HibernationWriteBuffer, dataMdl->MappedSystemVa, dataLength); - - if (BootDriveFilterExtension->Queue.RemapEncryptedArea) - dataUnit.Value += BootDriveFilterExtension->Queue.RemappedAreaDataUnitOffset; - - EncryptDataUnitsCurrentThread (HibernationWriteBuffer + (intersectStart - offset), - &dataUnit, - intersectLength / ENCRYPTION_DATA_UNIT_SIZE, - BootDriveFilterExtension->Queue.CryptoInfo); - - encryptedDataMdl = HibernationWriteBufferMdl; - MmInitializeMdl (encryptedDataMdl, HibernationWriteBuffer, dataLength); - encryptedDataMdl->MdlFlags = dataMdl->MdlFlags; - } - } - } - - if (writeB) - return (*OriginalHiberDriverWriteFunctionsB[filterNumber]) (writeOffset, encryptedDataMdl); - - return (*OriginalHiberDriverWriteFunctionsA[filterNumber]) (arg0WriteA, writeOffset, encryptedDataMdl, arg3WriteA); -} - - -static NTSTATUS HiberDriverWriteFunctionAFilter0 (ULONG arg0, PLARGE_INTEGER writeOffset, PMDL dataMdl, PVOID arg3) -{ - return HiberDriverWriteFunctionFilter (0, writeOffset, dataMdl, FALSE, arg0, arg3); -} - -static NTSTATUS HiberDriverWriteFunctionAFilter1 (ULONG arg0, PLARGE_INTEGER writeOffset, PMDL dataMdl, PVOID arg3) -{ - return HiberDriverWriteFunctionFilter (1, writeOffset, dataMdl, FALSE, arg0, arg3); -} - -static NTSTATUS HiberDriverWriteFunctionAFilter2 (ULONG arg0, PLARGE_INTEGER writeOffset, PMDL dataMdl, PVOID arg3) -{ - return HiberDriverWriteFunctionFilter (2, writeOffset, dataMdl, FALSE, arg0, arg3); -} - - -static NTSTATUS HiberDriverWriteFunctionBFilter0 (PLARGE_INTEGER writeOffset, PMDL dataMdl) -{ - return HiberDriverWriteFunctionFilter (0, writeOffset, dataMdl, TRUE, 0, NULL); -} - -static NTSTATUS HiberDriverWriteFunctionBFilter1 (PLARGE_INTEGER writeOffset, PMDL dataMdl) -{ - return HiberDriverWriteFunctionFilter (1, writeOffset, dataMdl, TRUE, 0, NULL); -} - -static NTSTATUS HiberDriverWriteFunctionBFilter2 (PLARGE_INTEGER writeOffset, PMDL dataMdl) -{ - return HiberDriverWriteFunctionFilter (2, writeOffset, dataMdl, TRUE, 0, NULL); -} - - -static NTSTATUS HiberDriverEntryFilter (int filterNumber, PVOID arg0, HiberDriverContext *hiberDriverContext) -{ - BOOL filterInstalled = FALSE; - NTSTATUS status; - - if (!OriginalHiberDriverEntries[filterNumber]) - return STATUS_UNSUCCESSFUL; - - status = (*OriginalHiberDriverEntries[filterNumber]) (arg0, hiberDriverContext); - - if (!NT_SUCCESS (status) || !hiberDriverContext) - return status; - - if (SetupInProgress) - TC_BUG_CHECK (STATUS_INVALID_PARAMETER); - - if (hiberDriverContext->WriteFunctionA) - { - Dump ("Filtering WriteFunctionA %d\n", filterNumber); - OriginalHiberDriverWriteFunctionsA[filterNumber] = hiberDriverContext->WriteFunctionA; - - switch (filterNumber) - { - case 0: hiberDriverContext->WriteFunctionA = HiberDriverWriteFunctionAFilter0; break; - case 1: hiberDriverContext->WriteFunctionA = HiberDriverWriteFunctionAFilter1; break; - case 2: hiberDriverContext->WriteFunctionA = HiberDriverWriteFunctionAFilter2; break; - default: TC_THROW_FATAL_EXCEPTION; - } - - filterInstalled = TRUE; - } - - if (hiberDriverContext->WriteFunctionB) - { - Dump ("Filtering WriteFunctionB %d\n", filterNumber); - OriginalHiberDriverWriteFunctionsB[filterNumber] = hiberDriverContext->WriteFunctionB; - - switch (filterNumber) - { - case 0: hiberDriverContext->WriteFunctionB = HiberDriverWriteFunctionBFilter0; break; - case 1: hiberDriverContext->WriteFunctionB = HiberDriverWriteFunctionBFilter1; break; - case 2: hiberDriverContext->WriteFunctionB = HiberDriverWriteFunctionBFilter2; break; - default: TC_THROW_FATAL_EXCEPTION; - } - - filterInstalled = TRUE; - } - - if (filterInstalled && hiberDriverContext->PartitionStartOffset.QuadPart != 0) - { - HiberPartitionOffset = hiberDriverContext->PartitionStartOffset; - - if (BootDriveFilterExtension->Queue.RemapEncryptedArea) - hiberDriverContext->PartitionStartOffset.QuadPart += BootDriveFilterExtension->Queue.RemappedAreaOffset; - } - - return STATUS_SUCCESS; -} - - -static NTSTATUS HiberDriverEntryFilter0 (PVOID arg0, HiberDriverContext *hiberDriverContext) -{ - return HiberDriverEntryFilter (0, arg0, hiberDriverContext); -} - - -static NTSTATUS HiberDriverEntryFilter1 (PVOID arg0, HiberDriverContext *hiberDriverContext) -{ - return HiberDriverEntryFilter (1, arg0, hiberDriverContext); -} - - -static NTSTATUS HiberDriverEntryFilter2 (PVOID arg0, HiberDriverContext *hiberDriverContext) -{ - return HiberDriverEntryFilter (2, arg0, hiberDriverContext); -} - - -static VOID LoadImageNotifyRoutine (PUNICODE_STRING fullImageName, HANDLE processId, PIMAGE_INFO imageInfo) -{ - ModuleTableItem *moduleItem; - LIST_ENTRY *listEntry; - KIRQL origIrql; - - if (!imageInfo || !imageInfo->SystemModeImage || !imageInfo->ImageBase || !TCDriverObject->DriverSection) - return; - - moduleItem = *(ModuleTableItem **) TCDriverObject->DriverSection; - if (!moduleItem || !moduleItem->ModuleList.Flink) - return; - - // Search loaded system modules for hibernation driver - origIrql = KeRaiseIrqlToDpcLevel(); - - for (listEntry = moduleItem->ModuleList.Flink->Blink; - listEntry && listEntry != TCDriverObject->DriverSection; - listEntry = listEntry->Flink) - { - moduleItem = CONTAINING_RECORD (listEntry, ModuleTableItem, ModuleList); - - if (moduleItem && imageInfo->ImageBase == moduleItem->ModuleBaseAddress) - { - if (moduleItem->ModuleName.Buffer && moduleItem->ModuleName.Length >= 5 * sizeof (wchar_t)) - { - if (memcmp (moduleItem->ModuleName.Buffer, L"hiber", 5 * sizeof (wchar_t)) == 0 - || memcmp (moduleItem->ModuleName.Buffer, L"Hiber", 5 * sizeof (wchar_t)) == 0 - || memcmp (moduleItem->ModuleName.Buffer, L"HIBER", 5 * sizeof (wchar_t)) == 0) - { - HiberDriverEntry filterEntry; - - switch (LastHiberFilterNumber) - { - case 0: filterEntry = HiberDriverEntryFilter0; break; - case 1: filterEntry = HiberDriverEntryFilter1; break; - case 2: filterEntry = HiberDriverEntryFilter2; break; - default: TC_THROW_FATAL_EXCEPTION; - } - - if (moduleItem->ModuleEntryAddress != filterEntry) - { - // Install filter - OriginalHiberDriverEntries[LastHiberFilterNumber] = moduleItem->ModuleEntryAddress; - moduleItem->ModuleEntryAddress = filterEntry; - - if (++LastHiberFilterNumber > TC_MAX_HIBER_FILTER_COUNT - 1) - LastHiberFilterNumber = 0; - } - } - } - break; - } - } - - KeLowerIrql (origIrql); -} - - -void StartLegacyHibernationDriverFilter () -{ - PHYSICAL_ADDRESS highestAcceptableWriteBufferAddr; - NTSTATUS status; - - ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL); - ASSERT (!IsOSAtLeast (WIN_VISTA)); - - if (!TCDriverObject->DriverSection || !*(ModuleTableItem **) TCDriverObject->DriverSection) - goto err; - - // All buffers required for hibernation must be allocated here -#ifdef _WIN64 - highestAcceptableWriteBufferAddr.QuadPart = 0x7FFffffFFFFULL; -#else - highestAcceptableWriteBufferAddr.QuadPart = 0xffffFFFFULL; -#endif - - HibernationWriteBuffer = MmAllocateContiguousMemory (TC_HIBERNATION_WRITE_BUFFER_SIZE, highestAcceptableWriteBufferAddr); - if (!HibernationWriteBuffer) - goto err; - - HibernationWriteBufferMdl = IoAllocateMdl (HibernationWriteBuffer, TC_HIBERNATION_WRITE_BUFFER_SIZE, FALSE, FALSE, NULL); - if (!HibernationWriteBufferMdl) - goto err; - - MmBuildMdlForNonPagedPool (HibernationWriteBufferMdl); - - status = PsSetLoadImageNotifyRoutine (LoadImageNotifyRoutine); - if (!NT_SUCCESS (status)) - goto err; - - LegacyHibernationDriverFilterActive = TRUE; - CrashDumpEnabled = FALSE; - HibernationEnabled = TRUE; - return; - -err: - LegacyHibernationDriverFilterActive = FALSE; - CrashDumpEnabled = FALSE; - HibernationEnabled = FALSE; - - if (HibernationWriteBufferMdl) - { - IoFreeMdl (HibernationWriteBufferMdl); - HibernationWriteBufferMdl = NULL; - } - - if (HibernationWriteBuffer) - { - MmFreeContiguousMemory (HibernationWriteBuffer); - HibernationWriteBuffer = NULL; - } -} - - -static VOID SetupThreadProc (PVOID threadArg) -{ - DriveFilterExtension *Extension = BootDriveFilterExtension; - - LARGE_INTEGER offset; - UINT64_STRUCT dataUnit; - ULONG setupBlockSize = TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE; - BOOL headerUpdateRequired = FALSE; - int64 bytesWrittenSinceHeaderUpdate = 0; - - byte *buffer = NULL; - byte *wipeBuffer = NULL; - byte wipeRandChars[TC_WIPE_RAND_CHAR_COUNT]; - byte wipeRandCharsUpdate[TC_WIPE_RAND_CHAR_COUNT]; - - KIRQL irql; - NTSTATUS status; - - // generate real random values for wipeRandChars and - // wipeRandCharsUpdate instead of relying on uninitialized stack memory - LARGE_INTEGER iSeed; - KeQuerySystemTime( &iSeed ); - if (KeGetCurrentIrql() < DISPATCH_LEVEL) - { - ULONG ulRandom; - ulRandom = RtlRandomEx( &iSeed.LowPart ); - memcpy (wipeRandChars, &ulRandom, TC_WIPE_RAND_CHAR_COUNT); - ulRandom = RtlRandomEx( &ulRandom ); - memcpy (wipeRandCharsUpdate, &ulRandom, TC_WIPE_RAND_CHAR_COUNT); - burn (&ulRandom, sizeof(ulRandom)); - } - else - { - byte digest[SHA512_DIGESTSIZE]; - sha512_ctx tctx; - sha512_begin (&tctx); - sha512_hash ((unsigned char *) &(iSeed.QuadPart), sizeof(iSeed.QuadPart), &tctx); - sha512_end (digest, &tctx); - - memcpy (wipeRandChars, digest, TC_WIPE_RAND_CHAR_COUNT); - memcpy (wipeRandCharsUpdate, &digest[SHA512_DIGESTSIZE - TC_WIPE_RAND_CHAR_COUNT], TC_WIPE_RAND_CHAR_COUNT); - - burn (digest, SHA512_DIGESTSIZE); - burn (&tctx, sizeof (tctx)); - } - - burn (&iSeed, sizeof(iSeed)); - - SetupResult = STATUS_UNSUCCESSFUL; - - // Make sure volume header can be updated - if (Extension->HeaderCryptoInfo == NULL) - { - SetupResult = STATUS_INVALID_PARAMETER; - goto ret; - } - - buffer = TCalloc (TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); - if (!buffer) - { - SetupResult = STATUS_INSUFFICIENT_RESOURCES; - goto ret; - } - - if (SetupRequest.SetupMode == SetupEncryption && SetupRequest.WipeAlgorithm != TC_WIPE_NONE) - { - wipeBuffer = TCalloc (TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); - if (!wipeBuffer) - { - SetupResult = STATUS_INSUFFICIENT_RESOURCES; - goto ret; - } - } - - while (!NT_SUCCESS (EncryptedIoQueueHoldWhenIdle (&Extension->Queue, 1000))) - { - if (EncryptionSetupThreadAbortRequested) - goto abort; - - TransformWaitingForIdle = TRUE; - } - TransformWaitingForIdle = FALSE; - - switch (SetupRequest.SetupMode) - { - case SetupEncryption: - Dump ("Encrypting...\n"); - if (Extension->Queue.EncryptedAreaStart == -1 || Extension->Queue.EncryptedAreaEnd == -1) - { - // Start encryption - Extension->Queue.EncryptedAreaStart = Extension->ConfiguredEncryptedAreaStart; - Extension->Queue.EncryptedAreaEnd = -1; - offset.QuadPart = Extension->ConfiguredEncryptedAreaStart; - } - else - { - // Resume aborted encryption - if (Extension->Queue.EncryptedAreaEnd == Extension->ConfiguredEncryptedAreaEnd) - goto err; - - offset.QuadPart = Extension->Queue.EncryptedAreaEnd + 1; - } - - break; - - case SetupDecryption: - Dump ("Decrypting...\n"); - if (Extension->Queue.EncryptedAreaStart == -1 || Extension->Queue.EncryptedAreaEnd == -1) - { - SetupResult = STATUS_SUCCESS; - goto abort; - } - - offset.QuadPart = Extension->Queue.EncryptedAreaEnd + 1; - break; - - default: - goto err; - } - - EncryptedIoQueueResumeFromHold (&Extension->Queue); - - Dump ("EncryptedAreaStart=%I64d\n", Extension->Queue.EncryptedAreaStart); - Dump ("EncryptedAreaEnd=%I64d\n", Extension->Queue.EncryptedAreaEnd); - Dump ("ConfiguredEncryptedAreaStart=%I64d\n", Extension->ConfiguredEncryptedAreaStart); - Dump ("ConfiguredEncryptedAreaEnd=%I64d\n", Extension->ConfiguredEncryptedAreaEnd); - Dump ("offset=%I64d\n", offset.QuadPart); - Dump ("EncryptedAreaStart=%I64d (%I64d) EncryptedAreaEnd=%I64d\n", Extension->Queue.EncryptedAreaStart / 1024 / 1024, Extension->Queue.EncryptedAreaStart, Extension->Queue.EncryptedAreaEnd / 1024 / 1024); - - while (!EncryptionSetupThreadAbortRequested) - { - if (SetupRequest.SetupMode == SetupEncryption) - { - if (offset.QuadPart + setupBlockSize > Extension->ConfiguredEncryptedAreaEnd + 1) - setupBlockSize = (ULONG) (Extension->ConfiguredEncryptedAreaEnd + 1 - offset.QuadPart); - - if (offset.QuadPart > Extension->ConfiguredEncryptedAreaEnd) - break; - } - else - { - if (offset.QuadPart - setupBlockSize < Extension->Queue.EncryptedAreaStart) - setupBlockSize = (ULONG) (offset.QuadPart - Extension->Queue.EncryptedAreaStart); - - offset.QuadPart -= setupBlockSize; - - if (setupBlockSize == 0 || offset.QuadPart < Extension->Queue.EncryptedAreaStart) - break; - } - - while (!NT_SUCCESS (EncryptedIoQueueHoldWhenIdle (&Extension->Queue, 500))) - { - if (EncryptionSetupThreadAbortRequested) - goto abort; - - TransformWaitingForIdle = TRUE; - } - TransformWaitingForIdle = FALSE; - - status = TCReadDevice (BootDriveFilterExtension->LowerDeviceObject, buffer, offset, setupBlockSize); - if (!NT_SUCCESS (status)) - { - Dump ("TCReadDevice error %x offset=%I64d\n", status, offset.QuadPart); - - if (SetupRequest.ZeroUnreadableSectors && SetupRequest.SetupMode == SetupEncryption) - { - // Zero unreadable sectors - uint64 zeroedSectorCount; - - status = ZeroUnreadableSectors (BootDriveFilterExtension->LowerDeviceObject, offset, setupBlockSize, &zeroedSectorCount); - if (!NT_SUCCESS (status)) - { - SetupResult = status; - goto err; - } - - // Retry read - status = TCReadDevice (BootDriveFilterExtension->LowerDeviceObject, buffer, offset, setupBlockSize); - if (!NT_SUCCESS (status)) - { - SetupResult = status; - goto err; - } - } - else if (SetupRequest.DiscardUnreadableEncryptedSectors && SetupRequest.SetupMode == SetupDecryption) - { - // Discard unreadable encrypted sectors - uint64 badSectorCount; - - status = ReadDeviceSkipUnreadableSectors (BootDriveFilterExtension->LowerDeviceObject, buffer, offset, setupBlockSize, &badSectorCount); - if (!NT_SUCCESS (status)) - { - SetupResult = status; - goto err; - } - } - else - { - SetupResult = status; - goto err; - } - } - - dataUnit.Value = offset.QuadPart / ENCRYPTION_DATA_UNIT_SIZE; - - if (SetupRequest.SetupMode == SetupEncryption) - { - EncryptDataUnits (buffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); - - if (SetupRequest.WipeAlgorithm != TC_WIPE_NONE) - { - byte wipePass; - int wipePassCount = GetWipePassCount (SetupRequest.WipeAlgorithm); - if (wipePassCount <= 0) - { - SetupResult = STATUS_INVALID_PARAMETER; - goto err; - } - - for (wipePass = 1; wipePass <= wipePassCount; ++wipePass) - { - if (!WipeBuffer (SetupRequest.WipeAlgorithm, wipeRandChars, wipePass, wipeBuffer, setupBlockSize)) - { - ULONG i; - for (i = 0; i < setupBlockSize; ++i) - { - wipeBuffer[i] = buffer[i] + wipePass; - } - - EncryptDataUnits (wipeBuffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); - memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate)); - } - - status = TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, wipeBuffer, offset, setupBlockSize); - if (!NT_SUCCESS (status)) - { - // Undo failed write operation - DecryptDataUnits (buffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); - TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, buffer, offset, setupBlockSize); - - SetupResult = status; - goto err; - } - } - - memcpy (wipeRandChars, wipeRandCharsUpdate, sizeof (wipeRandCharsUpdate)); - } - } - else - { - DecryptDataUnits (buffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); - } - - status = TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, buffer, offset, setupBlockSize); - if (!NT_SUCCESS (status)) - { - Dump ("TCWriteDevice error %x\n", status); - - // Undo failed write operation - if (SetupRequest.SetupMode == SetupEncryption) - DecryptDataUnits (buffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); - else - EncryptDataUnits (buffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); - - TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, buffer, offset, setupBlockSize); - - SetupResult = status; - goto err; - } - - if (SetupRequest.SetupMode == SetupEncryption) - offset.QuadPart += setupBlockSize; - - Extension->Queue.EncryptedAreaEndUpdatePending = TRUE; - Extension->Queue.EncryptedAreaEnd = offset.QuadPart - 1; - Extension->Queue.EncryptedAreaEndUpdatePending = FALSE; - - headerUpdateRequired = TRUE; - - EncryptedIoQueueResumeFromHold (&Extension->Queue); - - KeAcquireSpinLock (&SetupStatusSpinLock, &irql); - SetupStatusEncryptedAreaEnd = Extension->Queue.EncryptedAreaEnd; - KeReleaseSpinLock (&SetupStatusSpinLock, irql); - - // Update volume header - bytesWrittenSinceHeaderUpdate += setupBlockSize; - if (bytesWrittenSinceHeaderUpdate >= TC_ENCRYPTION_SETUP_HEADER_UPDATE_THRESHOLD) - { - status = SaveDriveVolumeHeader (Extension); - ASSERT (NT_SUCCESS (status)); - if (NT_SUCCESS (status)) - { - headerUpdateRequired = FALSE; - bytesWrittenSinceHeaderUpdate = 0; - } - } - } - -abort: - SetupResult = STATUS_SUCCESS; -err: - - if (Extension->Queue.EncryptedAreaEnd == -1) - Extension->Queue.EncryptedAreaStart = -1; - - if (EncryptedIoQueueIsSuspended (&Extension->Queue)) - EncryptedIoQueueResumeFromHold (&Extension->Queue); - - if (SetupRequest.SetupMode == SetupDecryption && Extension->Queue.EncryptedAreaStart >= Extension->Queue.EncryptedAreaEnd) - { - while (!NT_SUCCESS (EncryptedIoQueueHoldWhenIdle (&Extension->Queue, 0))); - - Extension->ConfiguredEncryptedAreaStart = Extension->ConfiguredEncryptedAreaEnd = -1; - Extension->Queue.EncryptedAreaStart = Extension->Queue.EncryptedAreaEnd = -1; - - EncryptedIoQueueResumeFromHold (&Extension->Queue); - - headerUpdateRequired = TRUE; - } - - Dump ("Setup completed: EncryptedAreaStart=%I64d (%I64d) EncryptedAreaEnd=%I64d (%I64d)\n", Extension->Queue.EncryptedAreaStart / 1024 / 1024, Extension->Queue.EncryptedAreaStart, Extension->Queue.EncryptedAreaEnd / 1024 / 1024, Extension->Queue.EncryptedAreaEnd); - - if (headerUpdateRequired) - { - status = SaveDriveVolumeHeader (Extension); - - if (!NT_SUCCESS (status) && NT_SUCCESS (SetupResult)) - SetupResult = status; - } - - if (SetupRequest.SetupMode == SetupDecryption && Extension->ConfiguredEncryptedAreaEnd == -1 && Extension->DriveMounted) - { - while (!RootDeviceControlMutexAcquireNoWait() && !EncryptionSetupThreadAbortRequested) - { - TCSleep (10); - } - - // Disable hibernation (resume would fail due to a change in the system memory map) - HibernationEnabled = FALSE; - - DismountDrive (Extension, FALSE); - - if (!EncryptionSetupThreadAbortRequested) - RootDeviceControlMutexRelease(); - } - -ret: - if (buffer) - { - burn (buffer, TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); - TCfree (buffer); - } - if (wipeBuffer) - { - burn (wipeBuffer, TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); - TCfree (wipeBuffer); - } - - burn (wipeRandChars, TC_WIPE_RAND_CHAR_COUNT); - burn (wipeRandCharsUpdate, TC_WIPE_RAND_CHAR_COUNT); - - SetupInProgress = FALSE; - PsTerminateSystemThread (SetupResult); -} - - -NTSTATUS StartBootEncryptionSetup (PDEVICE_OBJECT DeviceObject, PIRP irp, PIO_STACK_LOCATION irpSp) -{ - NTSTATUS status; - - if (!UserCanAccessDriveDevice()) - return STATUS_ACCESS_DENIED; - - if (SetupInProgress || !BootDriveFound || !BootDriveFilterExtension - || !BootDriveFilterExtension->DriveMounted - || BootDriveFilterExtension->HiddenSystem - || irpSp->Parameters.DeviceIoControl.InputBufferLength < sizeof (BootEncryptionSetupRequest)) - return STATUS_INVALID_PARAMETER; - - if (EncryptionSetupThread) - AbortBootEncryptionSetup(); - - SetupRequest = *(BootEncryptionSetupRequest *) irp->AssociatedIrp.SystemBuffer; - - EncryptionSetupThreadAbortRequested = FALSE; - KeInitializeSpinLock (&SetupStatusSpinLock); - SetupStatusEncryptedAreaEnd = BootDriveFilterExtension ? BootDriveFilterExtension->Queue.EncryptedAreaEnd : -1; - - SetupInProgress = TRUE; - status = TCStartThread (SetupThreadProc, DeviceObject, &EncryptionSetupThread); - - if (!NT_SUCCESS (status)) - SetupInProgress = FALSE; - - return status; -} - - -void GetBootDriveVolumeProperties (PIRP irp, PIO_STACK_LOCATION irpSp) -{ - if (ValidateIOBufferSize (irp, sizeof (VOLUME_PROPERTIES_STRUCT), ValidateOutput)) - { - DriveFilterExtension *Extension = BootDriveFilterExtension; - VOLUME_PROPERTIES_STRUCT *prop = (VOLUME_PROPERTIES_STRUCT *) irp->AssociatedIrp.SystemBuffer; - memset (prop, 0, sizeof (*prop)); - - if (!BootDriveFound || !Extension || !Extension->DriveMounted) - { - irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - irp->IoStatus.Information = 0; - } - else - { - prop->hiddenVolume = Extension->Queue.CryptoInfo->hiddenVolume; - prop->diskLength = Extension->ConfiguredEncryptedAreaEnd + 1 - Extension->ConfiguredEncryptedAreaStart; - prop->ea = Extension->Queue.CryptoInfo->ea; - prop->mode = Extension->Queue.CryptoInfo->mode; - prop->pkcs5 = Extension->Queue.CryptoInfo->pkcs5; - prop->pkcs5Iterations = Extension->Queue.CryptoInfo->noIterations; - prop->volumePim = Extension->Queue.CryptoInfo->volumePim; -#if 0 - prop->volumeCreationTime = Extension->Queue.CryptoInfo->volume_creation_time; - prop->headerCreationTime = Extension->Queue.CryptoInfo->header_creation_time; -#endif - prop->volFormatVersion = Extension->Queue.CryptoInfo->LegacyVolume ? TC_VOLUME_FORMAT_VERSION_PRE_6_0 : TC_VOLUME_FORMAT_VERSION; - - prop->totalBytesRead = Extension->Queue.TotalBytesRead; - prop->totalBytesWritten = Extension->Queue.TotalBytesWritten; - - irp->IoStatus.Information = sizeof (VOLUME_PROPERTIES_STRUCT); - irp->IoStatus.Status = STATUS_SUCCESS; - } - } -} - - -void GetBootEncryptionStatus (PIRP irp, PIO_STACK_LOCATION irpSp) -{ - /* IMPORTANT: Do NOT add any potentially time-consuming operations to this function. */ - - if (ValidateIOBufferSize (irp, sizeof (BootEncryptionStatus), ValidateOutput)) - { - DriveFilterExtension *Extension = BootDriveFilterExtension; - BootEncryptionStatus *bootEncStatus = (BootEncryptionStatus *) irp->AssociatedIrp.SystemBuffer; - memset (bootEncStatus, 0, sizeof (*bootEncStatus)); - - if (BootArgsValid) - bootEncStatus->BootLoaderVersion = BootArgs.BootLoaderVersion; - - bootEncStatus->DeviceFilterActive = DeviceFilterActive; - bootEncStatus->SetupInProgress = SetupInProgress; - bootEncStatus->SetupMode = SetupRequest.SetupMode; - bootEncStatus->TransformWaitingForIdle = TransformWaitingForIdle; - - if (!BootDriveFound || !Extension || !Extension->DriveMounted) - { - bootEncStatus->DriveEncrypted = FALSE; - bootEncStatus->DriveMounted = FALSE; - bootEncStatus->VolumeHeaderPresent = FALSE; - } - else - { - bootEncStatus->DriveMounted = Extension->DriveMounted; - bootEncStatus->VolumeHeaderPresent = Extension->VolumeHeaderPresent; - bootEncStatus->DriveEncrypted = Extension->Queue.EncryptedAreaStart != -1; - bootEncStatus->BootDriveLength = BootDriveLength; - - bootEncStatus->ConfiguredEncryptedAreaStart = Extension->ConfiguredEncryptedAreaStart; - bootEncStatus->ConfiguredEncryptedAreaEnd = Extension->ConfiguredEncryptedAreaEnd; - bootEncStatus->EncryptedAreaStart = Extension->Queue.EncryptedAreaStart; - - if (SetupInProgress) - { - KIRQL irql; - KeAcquireSpinLock (&SetupStatusSpinLock, &irql); - bootEncStatus->EncryptedAreaEnd = SetupStatusEncryptedAreaEnd; - KeReleaseSpinLock (&SetupStatusSpinLock, irql); - } - else - bootEncStatus->EncryptedAreaEnd = Extension->Queue.EncryptedAreaEnd; - - bootEncStatus->VolumeHeaderSaltCrc32 = Extension->VolumeHeaderSaltCrc32; - bootEncStatus->HibernationPreventionCount = HibernationPreventionCount; - bootEncStatus->HiddenSysLeakProtectionCount = HiddenSysLeakProtectionCount; - - bootEncStatus->HiddenSystem = Extension->HiddenSystem; - - if (Extension->HiddenSystem) - bootEncStatus->HiddenSystemPartitionStart = BootArgs.HiddenSystemPartitionStart; - } - - irp->IoStatus.Information = sizeof (BootEncryptionStatus); - irp->IoStatus.Status = STATUS_SUCCESS; - } -} - - -void GetBootLoaderVersion (PIRP irp, PIO_STACK_LOCATION irpSp) -{ - if (ValidateIOBufferSize (irp, sizeof (uint16), ValidateOutput)) - { - if (BootArgsValid) - { - *(uint16 *) irp->AssociatedIrp.SystemBuffer = BootArgs.BootLoaderVersion; - irp->IoStatus.Information = sizeof (uint16); - irp->IoStatus.Status = STATUS_SUCCESS; - } - else - { - irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - irp->IoStatus.Information = 0; - } - } -} - -void GetBootLoaderFingerprint (PIRP irp, PIO_STACK_LOCATION irpSp) -{ - if (ValidateIOBufferSize (irp, sizeof (BootLoaderFingerprintRequest), ValidateOutput)) - { - irp->IoStatus.Information = 0; - if (BootArgsValid && BootDriveFound && BootDriveFilterExtension && BootDriveFilterExtension->DriveMounted && BootDriveFilterExtension->HeaderCryptoInfo) - { - BootLoaderFingerprintRequest *bootLoaderFingerprint = (BootLoaderFingerprintRequest *) irp->AssociatedIrp.SystemBuffer; - - /* compute the fingerprint again and check if it is the same as the one retrieved during boot */ - char *header = TCalloc (TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); - if (!header) - { - irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; - } - else - { - memcpy (bootLoaderFingerprint->Fingerprint, BootLoaderFingerprint, sizeof (BootLoaderFingerprint)); - ComputeBootLoaderFingerprint (BootDriveFilterExtension->LowerDeviceObject, header); - - burn (header, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); - TCfree (header); - - if (0 == memcmp (bootLoaderFingerprint->Fingerprint, BootLoaderFingerprint, sizeof (BootLoaderFingerprint))) - { - irp->IoStatus.Information = sizeof (BootLoaderFingerprintRequest); - irp->IoStatus.Status = STATUS_SUCCESS; - } - else - { - /* fingerprint mismatch.*/ - irp->IoStatus.Status = STATUS_INVALID_IMAGE_HASH; - } - } - } - else - { - irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - } - } -} - -void GetBootEncryptionAlgorithmName (PIRP irp, PIO_STACK_LOCATION irpSp) -{ - if (ValidateIOBufferSize (irp, sizeof (GetBootEncryptionAlgorithmNameRequest), ValidateOutput)) - { - if (BootDriveFilterExtension && BootDriveFilterExtension->DriveMounted) - { - wchar_t BootEncryptionAlgorithmNameW[256]; - wchar_t BootPrfAlgorithmNameW[256]; - GetBootEncryptionAlgorithmNameRequest *request = (GetBootEncryptionAlgorithmNameRequest *) irp->AssociatedIrp.SystemBuffer; - EAGetName (BootEncryptionAlgorithmNameW, BootDriveFilterExtension->Queue.CryptoInfo->ea, 0); - HashGetName2 (BootPrfAlgorithmNameW, BootDriveFilterExtension->Queue.CryptoInfo->pkcs5); - - RtlStringCbPrintfA (request->BootEncryptionAlgorithmName, sizeof (request->BootEncryptionAlgorithmName), "%S", BootEncryptionAlgorithmNameW); - RtlStringCbPrintfA (request->BootPrfAlgorithmName, sizeof (request->BootPrfAlgorithmName), "%S", BootPrfAlgorithmNameW); - - irp->IoStatus.Information = sizeof (GetBootEncryptionAlgorithmNameRequest); - irp->IoStatus.Status = STATUS_SUCCESS; - } - else - { - irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - irp->IoStatus.Information = 0; - } - } -} - - -NTSTATUS GetSetupResult() -{ - return SetupResult; -} - - -BOOL IsBootDriveMounted () -{ - return BootDriveFilterExtension && BootDriveFilterExtension->DriveMounted; -} - - -BOOL IsBootEncryptionSetupInProgress () -{ - return SetupInProgress; -} - - -BOOL IsHiddenSystemRunning () -{ - return BootDriveFilterExtension && BootDriveFilterExtension->HiddenSystem; -} - - -DriveFilterExtension *GetBootDriveFilterExtension () -{ - return BootDriveFilterExtension; -} - - -CRYPTO_INFO *GetSystemDriveCryptoInfo () -{ - return BootDriveFilterExtension->Queue.CryptoInfo; -} - - -NTSTATUS AbortBootEncryptionSetup () -{ - if (!IoIsSystemThread (PsGetCurrentThread()) && !UserCanAccessDriveDevice()) - return STATUS_ACCESS_DENIED; - - if (EncryptionSetupThread) - { - EncryptionSetupThreadAbortRequested = TRUE; - - TCStopThread (EncryptionSetupThread, NULL); - EncryptionSetupThread = NULL; - } - - return STATUS_SUCCESS; -} - - -static VOID DecoySystemWipeThreadProc (PVOID threadArg) -{ - DriveFilterExtension *Extension = BootDriveFilterExtension; - - LARGE_INTEGER offset; - UINT64_STRUCT dataUnit; - ULONG wipeBlockSize = TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE; - - CRYPTO_INFO *wipeCryptoInfo = NULL; - byte *wipeBuffer = NULL; - byte *wipeRandBuffer = NULL; - byte wipeRandChars[TC_WIPE_RAND_CHAR_COUNT]; - int wipePass, wipePassCount; - int ea = Extension->Queue.CryptoInfo->ea; - - KIRQL irql; - NTSTATUS status; - - DecoySystemWipeResult = STATUS_UNSUCCESSFUL; - - wipeBuffer = TCalloc (TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); - if (!wipeBuffer) - { - DecoySystemWipeResult = STATUS_INSUFFICIENT_RESOURCES; - goto ret; - } - - wipeRandBuffer = TCalloc (TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); - if (!wipeRandBuffer) - { - DecoySystemWipeResult = STATUS_INSUFFICIENT_RESOURCES; - goto ret; - } - - wipeCryptoInfo = crypto_open(); - if (!wipeCryptoInfo) - { - DecoySystemWipeResult = STATUS_INSUFFICIENT_RESOURCES; - goto ret; - } - - wipeCryptoInfo->ea = ea; - wipeCryptoInfo->mode = Extension->Queue.CryptoInfo->mode; - - if (EAInit (ea, WipeDecoyRequest.WipeKey, wipeCryptoInfo->ks) != ERR_SUCCESS) - { - DecoySystemWipeResult = STATUS_INVALID_PARAMETER; - goto ret; - } - - memcpy (wipeCryptoInfo->k2, WipeDecoyRequest.WipeKey + EAGetKeySize (ea), EAGetKeySize (ea)); - - if (!EAInitMode (wipeCryptoInfo)) - { - DecoySystemWipeResult = STATUS_INVALID_PARAMETER; - goto err; - } - - EncryptDataUnits (wipeRandBuffer, &dataUnit, wipeBlockSize / ENCRYPTION_DATA_UNIT_SIZE, wipeCryptoInfo); - memcpy (wipeRandChars, wipeRandBuffer, sizeof (wipeRandChars)); - - burn (WipeDecoyRequest.WipeKey, sizeof (WipeDecoyRequest.WipeKey)); - - offset.QuadPart = Extension->ConfiguredEncryptedAreaStart; - - Dump ("Wiping decoy system: start offset = %I64d\n", offset.QuadPart); - - while (!DecoySystemWipeThreadAbortRequested) - { - if (offset.QuadPart + wipeBlockSize > Extension->ConfiguredEncryptedAreaEnd + 1) - wipeBlockSize = (ULONG) (Extension->ConfiguredEncryptedAreaEnd + 1 - offset.QuadPart); - - if (offset.QuadPart > Extension->ConfiguredEncryptedAreaEnd) - break; - - wipePassCount = GetWipePassCount (WipeDecoyRequest.WipeAlgorithm); - if (wipePassCount <= 0) - { - DecoySystemWipeResult = STATUS_INVALID_PARAMETER; - goto err; - } - - for (wipePass = 1; wipePass <= wipePassCount; ++wipePass) - { - if (!WipeBuffer (WipeDecoyRequest.WipeAlgorithm, wipeRandChars, wipePass, wipeBuffer, wipeBlockSize)) - { - dataUnit.Value = offset.QuadPart / ENCRYPTION_DATA_UNIT_SIZE; - EncryptDataUnits (wipeRandBuffer, &dataUnit, wipeBlockSize / ENCRYPTION_DATA_UNIT_SIZE, wipeCryptoInfo); - memcpy (wipeBuffer, wipeRandBuffer, wipeBlockSize); - } - - while (!NT_SUCCESS (EncryptedIoQueueHoldWhenIdle (&Extension->Queue, 500))) - { - if (DecoySystemWipeThreadAbortRequested) - goto abort; - } - - status = TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, wipeBuffer, offset, wipeBlockSize); - - if (!NT_SUCCESS (status)) - { - DecoySystemWipeResult = status; - goto err; - } - - EncryptedIoQueueResumeFromHold (&Extension->Queue); - } - - offset.QuadPart += wipeBlockSize; - - KeAcquireSpinLock (&DecoySystemWipeStatusSpinLock, &irql); - DecoySystemWipedAreaEnd = offset.QuadPart - 1; - KeReleaseSpinLock (&DecoySystemWipeStatusSpinLock, irql); - } - -abort: - DecoySystemWipeResult = STATUS_SUCCESS; -err: - - if (EncryptedIoQueueIsSuspended (&Extension->Queue)) - EncryptedIoQueueResumeFromHold (&Extension->Queue); - - Dump ("Wipe end: DecoySystemWipedAreaEnd=%I64d (%I64d)\n", DecoySystemWipedAreaEnd, DecoySystemWipedAreaEnd / 1024 / 1024); - -ret: - if (wipeCryptoInfo) - crypto_close (wipeCryptoInfo); - - if (wipeRandBuffer) - TCfree (wipeRandBuffer); - - if (wipeBuffer) - TCfree (wipeBuffer); - - DecoySystemWipeInProgress = FALSE; - PsTerminateSystemThread (DecoySystemWipeResult); -} - - -NTSTATUS StartDecoySystemWipe (PDEVICE_OBJECT DeviceObject, PIRP irp, PIO_STACK_LOCATION irpSp) -{ - NTSTATUS status; - WipeDecoySystemRequest *request; - - if (!UserCanAccessDriveDevice()) - return STATUS_ACCESS_DENIED; - - if (!IsHiddenSystemRunning() - || irpSp->Parameters.DeviceIoControl.InputBufferLength < sizeof (WipeDecoySystemRequest)) - return STATUS_INVALID_PARAMETER; - - if (DecoySystemWipeInProgress) - return STATUS_SUCCESS; - - if (DecoySystemWipeThread) - AbortDecoySystemWipe(); - - request = (WipeDecoySystemRequest *) irp->AssociatedIrp.SystemBuffer; - WipeDecoyRequest = *request; - - burn (request->WipeKey, sizeof (request->WipeKey)); - - DecoySystemWipeThreadAbortRequested = FALSE; - KeInitializeSpinLock (&DecoySystemWipeStatusSpinLock); - DecoySystemWipedAreaEnd = BootDriveFilterExtension->ConfiguredEncryptedAreaStart; - - DecoySystemWipeInProgress = TRUE; - status = TCStartThread (DecoySystemWipeThreadProc, DeviceObject, &DecoySystemWipeThread); - - if (!NT_SUCCESS (status)) - DecoySystemWipeInProgress = FALSE; - - return status; -} - - -BOOL IsDecoySystemWipeInProgress() -{ - return DecoySystemWipeInProgress; -} - - -void GetDecoySystemWipeStatus (PIRP irp, PIO_STACK_LOCATION irpSp) -{ - if (ValidateIOBufferSize (irp, sizeof (DecoySystemWipeStatus), ValidateOutput)) - { - DecoySystemWipeStatus *wipeStatus = (DecoySystemWipeStatus *) irp->AssociatedIrp.SystemBuffer; - - if (!IsHiddenSystemRunning()) - { - irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - irp->IoStatus.Information = 0; - } - else - { - wipeStatus->WipeInProgress = DecoySystemWipeInProgress; - wipeStatus->WipeAlgorithm = WipeDecoyRequest.WipeAlgorithm; - - if (DecoySystemWipeInProgress) - { - KIRQL irql; - KeAcquireSpinLock (&DecoySystemWipeStatusSpinLock, &irql); - wipeStatus->WipedAreaEnd = DecoySystemWipedAreaEnd; - KeReleaseSpinLock (&DecoySystemWipeStatusSpinLock, irql); - } - else - wipeStatus->WipedAreaEnd = DecoySystemWipedAreaEnd; - - irp->IoStatus.Information = sizeof (DecoySystemWipeStatus); - irp->IoStatus.Status = STATUS_SUCCESS; - } - } -} - - -NTSTATUS GetDecoySystemWipeResult() -{ - return DecoySystemWipeResult; -} - - -NTSTATUS AbortDecoySystemWipe () -{ - if (!IoIsSystemThread (PsGetCurrentThread()) && !UserCanAccessDriveDevice()) - return STATUS_ACCESS_DENIED; - - if (DecoySystemWipeThread) - { - DecoySystemWipeThreadAbortRequested = TRUE; - - TCStopThread (DecoySystemWipeThread, NULL); - DecoySystemWipeThread = NULL; - } - - return STATUS_SUCCESS; -} - - -uint64 GetBootDriveLength () -{ - return BootDriveLength.QuadPart; -} - - -NTSTATUS WriteBootDriveSector (PIRP irp, PIO_STACK_LOCATION irpSp) -{ - WriteBootDriveSectorRequest *request; - - if (!UserCanAccessDriveDevice()) - return STATUS_ACCESS_DENIED; - - if (!BootDriveFilterExtension - || irpSp->Parameters.DeviceIoControl.InputBufferLength < sizeof (WriteBootDriveSectorRequest)) - return STATUS_INVALID_PARAMETER; - - request = (WriteBootDriveSectorRequest *) irp->AssociatedIrp.SystemBuffer; - return TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, request->Data, request->Offset, sizeof (request->Data)); -} +/* + 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 "TCdefs.h" +#include +#include +#include +#include "Cache.h" +#include "Crc.h" +#include "Crypto.h" +#include "Apidrvr.h" +#include "EncryptedIoQueue.h" +#include "Common/Endian.h" +#include "Ntdriver.h" +#include "Ntvol.h" +#include "Volumes.h" +#include "VolumeFilter.h" +#include "Wipe.h" +#include "DriveFilter.h" +#include "Boot/Windows/BootCommon.h" + +static BOOL DeviceFilterActive = FALSE; + +BOOL BootArgsValid = FALSE; +BootArguments BootArgs; +static uint16 BootLoaderSegment; +static BOOL BootDriveSignatureValid = FALSE; + +static KMUTEX MountMutex; + +static volatile BOOL BootDriveFound = FALSE; +static DriveFilterExtension *BootDriveFilterExtension = NULL; +static LARGE_INTEGER BootDriveLength; +static byte BootLoaderFingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE]; + +static BOOL CrashDumpEnabled = FALSE; +static BOOL HibernationEnabled = FALSE; + +static BOOL LegacyHibernationDriverFilterActive = FALSE; +static byte *HibernationWriteBuffer = NULL; +static MDL *HibernationWriteBufferMdl = NULL; + +static uint32 HibernationPreventionCount = 0; + +static BootEncryptionSetupRequest SetupRequest; +static volatile BOOL SetupInProgress = FALSE; +PKTHREAD EncryptionSetupThread = NULL; +static volatile BOOL EncryptionSetupThreadAbortRequested; +static KSPIN_LOCK SetupStatusSpinLock; +static int64 SetupStatusEncryptedAreaEnd; +static BOOL TransformWaitingForIdle; +static NTSTATUS SetupResult; + +static WipeDecoySystemRequest WipeDecoyRequest; +static volatile BOOL DecoySystemWipeInProgress = FALSE; +static volatile BOOL DecoySystemWipeThreadAbortRequested; +static KSPIN_LOCK DecoySystemWipeStatusSpinLock; +static int64 DecoySystemWipedAreaEnd; +PKTHREAD DecoySystemWipeThread = NULL; +static NTSTATUS DecoySystemWipeResult; + + +NTSTATUS LoadBootArguments () +{ + NTSTATUS status = STATUS_UNSUCCESSFUL; + PHYSICAL_ADDRESS bootArgsAddr; + byte *mappedBootArgs; + uint16 bootLoaderSegment; + + KeInitializeMutex (&MountMutex, 0); + + for (bootLoaderSegment = TC_BOOT_LOADER_SEGMENT; + bootLoaderSegment >= TC_BOOT_LOADER_SEGMENT - 64 * 1024 / 16 && status != STATUS_SUCCESS; + bootLoaderSegment -= 32 * 1024 / 16) + { + bootArgsAddr.QuadPart = (bootLoaderSegment << 4) + TC_BOOT_LOADER_ARGS_OFFSET; + Dump ("Checking BootArguments at 0x%x\n", bootArgsAddr.LowPart); + + mappedBootArgs = MmMapIoSpace (bootArgsAddr, sizeof (BootArguments), MmCached); + if (!mappedBootArgs) + return STATUS_INSUFFICIENT_RESOURCES; + + if (TC_IS_BOOT_ARGUMENTS_SIGNATURE (mappedBootArgs)) + { + BootArguments *bootArguments = (BootArguments *) mappedBootArgs; + Dump ("BootArguments found at 0x%x\n", bootArgsAddr.LowPart); + + DumpMem (mappedBootArgs, sizeof (BootArguments)); + + if (bootArguments->BootLoaderVersion == VERSION_NUM + && bootArguments->BootArgumentsCrc32 != GetCrc32 ((byte *) bootArguments, (int) ((byte *) &bootArguments->BootArgumentsCrc32 - (byte *) bootArguments))) + { + Dump ("BootArguments CRC incorrect\n"); + TC_BUG_CHECK (STATUS_CRC_ERROR); + } + + // Sanity check: for valid boot argument, the password is less than 64 bytes long + if (bootArguments->BootPassword.Length <= MAX_PASSWORD) + { + BootLoaderSegment = bootLoaderSegment; + + BootArgs = *bootArguments; + BootArgsValid = TRUE; + burn (bootArguments, sizeof (*bootArguments)); + + BootDriveSignatureValid = TRUE; + + Dump ("BootLoaderVersion = %x\n", (int) BootArgs.BootLoaderVersion); + Dump ("HeaderSaltCrc32 = %x\n", (int) BootArgs.HeaderSaltCrc32); + Dump ("CryptoInfoOffset = %x\n", (int) BootArgs.CryptoInfoOffset); + Dump ("CryptoInfoLength = %d\n", (int) BootArgs.CryptoInfoLength); + Dump ("HiddenSystemPartitionStart = %I64u\n", BootArgs.HiddenSystemPartitionStart); + Dump ("DecoySystemPartitionStart = %I64u\n", BootArgs.DecoySystemPartitionStart); + Dump ("Flags = %x\n", BootArgs.Flags); + Dump ("BootDriveSignature = %x\n", BootArgs.BootDriveSignature); + Dump ("BootArgumentsCrc32 = %x\n", BootArgs.BootArgumentsCrc32); + + if (CacheBootPassword && BootArgs.BootPassword.Length > 0) + { + int pim = CacheBootPim? (int) (BootArgs.Flags >> 16) : 0; + AddPasswordToCache (&BootArgs.BootPassword, pim); + } + + // clear fingerprint + burn (BootLoaderFingerprint, sizeof (BootLoaderFingerprint)); + + status = STATUS_SUCCESS; + } + } + + MmUnmapIoSpace (mappedBootArgs, sizeof (BootArguments)); + } + + return status; +} + + +NTSTATUS DriveFilterAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo) +{ + DriveFilterExtension *Extension; + NTSTATUS status; + PDEVICE_OBJECT filterDeviceObject = NULL; + PDEVICE_OBJECT attachedDeviceObject; + + Dump ("DriveFilterAddDevice pdo=%p\n", pdo); + + attachedDeviceObject = IoGetAttachedDeviceReference (pdo); + status = IoCreateDevice (driverObject, sizeof (DriveFilterExtension), NULL, attachedDeviceObject->DeviceType, 0, FALSE, &filterDeviceObject); + + ObDereferenceObject (attachedDeviceObject); + + if (!NT_SUCCESS (status)) + { + filterDeviceObject = NULL; + goto err; + } + + Extension = (DriveFilterExtension *) filterDeviceObject->DeviceExtension; + memset (Extension, 0, sizeof (DriveFilterExtension)); + + status = IoAttachDeviceToDeviceStackSafe (filterDeviceObject, pdo, &(Extension->LowerDeviceObject)); + if (!NT_SUCCESS (status)) + { + goto err; + } + + if (!Extension->LowerDeviceObject) + { + status = STATUS_DEVICE_REMOVED; + goto err; + } + + Extension->IsDriveFilterDevice = Extension->Queue.IsFilterDevice = TRUE; + Extension->DeviceObject = Extension->Queue.DeviceObject = filterDeviceObject; + Extension->Pdo = pdo; + + Extension->Queue.LowerDeviceObject = Extension->LowerDeviceObject; + IoInitializeRemoveLock (&Extension->Queue.RemoveLock, 'LRCV', 0, 0); + + Extension->ConfiguredEncryptedAreaStart = -1; + Extension->ConfiguredEncryptedAreaEnd = -1; + Extension->Queue.EncryptedAreaStart = -1; + Extension->Queue.EncryptedAreaEnd = -1; + Extension->Queue.EncryptedAreaEndUpdatePending = FALSE; + + filterDeviceObject->Flags |= Extension->LowerDeviceObject->Flags & (DO_DIRECT_IO | DO_BUFFERED_IO | DO_POWER_PAGABLE); + filterDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; + + DeviceFilterActive = TRUE; + return status; + +err: + if (filterDeviceObject) + { + if (Extension->LowerDeviceObject) + IoDetachDevice (Extension->LowerDeviceObject); + + IoDeleteDevice (filterDeviceObject); + } + + return status; +} + + +static void DismountDrive (DriveFilterExtension *Extension, BOOL stopIoQueue) +{ + Dump ("Dismounting drive\n"); + ASSERT (Extension->DriveMounted); + + if (stopIoQueue && EncryptedIoQueueIsRunning (&Extension->Queue)) + EncryptedIoQueueStop (&Extension->Queue); + + crypto_close (Extension->Queue.CryptoInfo); + Extension->Queue.CryptoInfo = NULL; + + crypto_close (Extension->HeaderCryptoInfo); + Extension->HeaderCryptoInfo = NULL; + + Extension->DriveMounted = FALSE; +} + +static void ComputeBootLoaderFingerprint(PDEVICE_OBJECT LowerDeviceObject, byte* ioBuffer /* ioBuffer must be at least 512 bytes long */) +{ + NTSTATUS status; + LARGE_INTEGER offset; + WHIRLPOOL_CTX whirlpool; + sha512_ctx sha2; + ULONG bytesToRead, remainingBytes, bootloaderTotalSize = TC_BOOT_LOADER_AREA_SIZE - TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE; + + // clear fingerprint + burn (BootLoaderFingerprint, sizeof (BootLoaderFingerprint)); + + // compute Whirlpool+SHA512 fingerprint of bootloader including MBR + // we skip user configuration fields: + // TC_BOOT_SECTOR_PIM_VALUE_OFFSET = 400 + // TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET = 402 + // => TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE = 4 + // TC_BOOT_SECTOR_USER_MESSAGE_OFFSET = 406 + // => TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH = 24 + // TC_BOOT_SECTOR_USER_CONFIG_OFFSET = 438 + // + // we have: TC_BOOT_SECTOR_USER_MESSAGE_OFFSET = TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE + + WHIRLPOOL_init (&whirlpool); + sha512_begin (&sha2); + // read the first 512 bytes + offset.QuadPart = 0; + + status = TCReadDevice (LowerDeviceObject, ioBuffer, offset, TC_SECTOR_SIZE_BIOS); + if (NT_SUCCESS (status)) + { + WHIRLPOOL_add (ioBuffer, TC_BOOT_SECTOR_PIM_VALUE_OFFSET * 8, &whirlpool); + WHIRLPOOL_add (ioBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH, (TC_BOOT_SECTOR_USER_CONFIG_OFFSET - (TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH)) * 8, &whirlpool); + WHIRLPOOL_add (ioBuffer + TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1, (TC_MAX_MBR_BOOT_CODE_SIZE - (TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1)) * 8, &whirlpool); + + sha512_hash (ioBuffer, TC_BOOT_SECTOR_PIM_VALUE_OFFSET, &sha2); + sha512_hash (ioBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH, (TC_BOOT_SECTOR_USER_CONFIG_OFFSET - (TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH)), &sha2); + sha512_hash (ioBuffer + TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1, (TC_MAX_MBR_BOOT_CODE_SIZE - (TC_BOOT_SECTOR_USER_CONFIG_OFFSET + 1)), &sha2); + + // we has the reste of the bootloader, 512 bytes at a time + offset.QuadPart = TC_SECTOR_SIZE_BIOS; + remainingBytes = bootloaderTotalSize - TC_SECTOR_SIZE_BIOS; + + while (NT_SUCCESS (status) && (remainingBytes > 0)) + { + bytesToRead = (remainingBytes >= TC_SECTOR_SIZE_BIOS)? TC_SECTOR_SIZE_BIOS : remainingBytes; + status = TCReadDevice (LowerDeviceObject, ioBuffer, offset, bytesToRead); + if (NT_SUCCESS (status)) + { + remainingBytes -= bytesToRead; + offset.QuadPart += bytesToRead; + WHIRLPOOL_add (ioBuffer, bytesToRead * 8, &whirlpool); + sha512_hash (ioBuffer, bytesToRead, &sha2); + } + else + { + Dump ("TCReadDevice error %x during ComputeBootLoaderFingerprint call\n", status); + break; + } + } + + if (NT_SUCCESS (status)) + { + WHIRLPOOL_finalize (&whirlpool, BootLoaderFingerprint); + sha512_end (&BootLoaderFingerprint [WHIRLPOOL_DIGESTSIZE], &sha2); + } + } + else + { + Dump ("TCReadDevice error %x during ComputeBootLoaderFingerprint call\n", status); + } +} + + +static NTSTATUS MountDrive (DriveFilterExtension *Extension, Password *password, uint32 *headerSaltCrc32) +{ + BOOL hiddenVolume = (BootArgs.HiddenSystemPartitionStart != 0); + int64 hiddenHeaderOffset = BootArgs.HiddenSystemPartitionStart + TC_HIDDEN_VOLUME_HEADER_OFFSET; + NTSTATUS status; + LARGE_INTEGER offset; + char *header; + int pkcs5_prf = 0, pim = 0; + byte *mappedCryptoInfo = NULL; + + Dump ("MountDrive pdo=%p\n", Extension->Pdo); + ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL); + + // Check boot drive signature first (header CRC search could fail if a user restored the header to a non-boot drive) + if (BootDriveSignatureValid) + { + byte mbr[TC_SECTOR_SIZE_BIOS]; + + offset.QuadPart = 0; + status = TCReadDevice (Extension->LowerDeviceObject, mbr, offset, TC_SECTOR_SIZE_BIOS); + + if (NT_SUCCESS (status) && BootArgs.BootDriveSignature != *(uint32 *) (mbr + 0x1b8)) + return STATUS_UNSUCCESSFUL; + } + + header = TCalloc (TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); + if (!header) + return STATUS_INSUFFICIENT_RESOURCES; + + offset.QuadPart = hiddenVolume ? hiddenHeaderOffset : TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET; + Dump ("Reading volume header at %I64u\n", offset.QuadPart); + + status = TCReadDevice (Extension->LowerDeviceObject, header, offset, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); + if (!NT_SUCCESS (status)) + { + Dump ("TCReadDevice error %x\n", status); + goto ret; + } + + if (headerSaltCrc32) + { + uint32 saltCrc = GetCrc32 (header, PKCS5_SALT_SIZE); + + if (saltCrc != *headerSaltCrc32) + { + status = STATUS_UNSUCCESSFUL; + goto ret; + } + + Extension->VolumeHeaderSaltCrc32 = saltCrc; + } + + Extension->HeaderCryptoInfo = crypto_open(); + if (!Extension->HeaderCryptoInfo) + { + status = STATUS_INSUFFICIENT_RESOURCES; + goto ret; + } + + if (BootArgs.CryptoInfoLength > 0) + { + PHYSICAL_ADDRESS cryptoInfoAddress; + + cryptoInfoAddress.QuadPart = (BootLoaderSegment << 4) + BootArgs.CryptoInfoOffset; +#ifdef DEBUG + Dump ("Wiping memory %x %d\n", cryptoInfoAddress.LowPart, BootArgs.CryptoInfoLength); +#endif + mappedCryptoInfo = MmMapIoSpace (cryptoInfoAddress, BootArgs.CryptoInfoLength, MmCached); + if (mappedCryptoInfo) + { + /* Get the parameters used for booting to speed up driver startup and avoid testing irrelevant PRFs */ + BOOT_CRYPTO_HEADER* pBootCryptoInfo = (BOOT_CRYPTO_HEADER*) mappedCryptoInfo; + Hash* pHash = HashGet(pBootCryptoInfo->pkcs5); + if (pHash && pHash->SystemEncryption) + pkcs5_prf = pBootCryptoInfo->pkcs5; + } + } + + pim = (int) (BootArgs.Flags >> 16); + + if (ReadVolumeHeader (!hiddenVolume, header, password, pkcs5_prf, pim, FALSE, &Extension->Queue.CryptoInfo, Extension->HeaderCryptoInfo) == 0) + { + // Header decrypted + status = STATUS_SUCCESS; + Dump ("Header decrypted\n"); + + // calculate Fingerprint + ComputeBootLoaderFingerprint (Extension->LowerDeviceObject, header); + + if (Extension->Queue.CryptoInfo->hiddenVolume) + { + int64 hiddenPartitionOffset = BootArgs.HiddenSystemPartitionStart; + Dump ("Hidden volume start offset = %I64d\n", Extension->Queue.CryptoInfo->EncryptedAreaStart.Value + hiddenPartitionOffset); + + Extension->HiddenSystem = TRUE; + + Extension->Queue.RemapEncryptedArea = TRUE; + Extension->Queue.RemappedAreaOffset = hiddenPartitionOffset + Extension->Queue.CryptoInfo->EncryptedAreaStart.Value - BootArgs.DecoySystemPartitionStart; + Extension->Queue.RemappedAreaDataUnitOffset = Extension->Queue.CryptoInfo->EncryptedAreaStart.Value / ENCRYPTION_DATA_UNIT_SIZE - BootArgs.DecoySystemPartitionStart / ENCRYPTION_DATA_UNIT_SIZE; + + Extension->Queue.CryptoInfo->EncryptedAreaStart.Value = BootArgs.DecoySystemPartitionStart; + + if (Extension->Queue.CryptoInfo->VolumeSize.Value > hiddenPartitionOffset - BootArgs.DecoySystemPartitionStart) + TC_THROW_FATAL_EXCEPTION; + + Dump ("RemappedAreaOffset = %I64d\n", Extension->Queue.RemappedAreaOffset); + Dump ("RemappedAreaDataUnitOffset = %I64d\n", Extension->Queue.RemappedAreaDataUnitOffset); + } + else + { + Extension->HiddenSystem = FALSE; + Extension->Queue.RemapEncryptedArea = FALSE; + } + + Extension->ConfiguredEncryptedAreaStart = Extension->Queue.CryptoInfo->EncryptedAreaStart.Value; + Extension->ConfiguredEncryptedAreaEnd = Extension->Queue.CryptoInfo->EncryptedAreaStart.Value + Extension->Queue.CryptoInfo->VolumeSize.Value - 1; + + Extension->Queue.EncryptedAreaStart = Extension->Queue.CryptoInfo->EncryptedAreaStart.Value; + Extension->Queue.EncryptedAreaEnd = Extension->Queue.CryptoInfo->EncryptedAreaStart.Value + Extension->Queue.CryptoInfo->EncryptedAreaLength.Value - 1; + + if (Extension->Queue.CryptoInfo->EncryptedAreaLength.Value == 0) + { + Extension->Queue.EncryptedAreaStart = -1; + Extension->Queue.EncryptedAreaEnd = -1; + } + + Dump ("Loaded: ConfiguredEncryptedAreaStart=%I64d (%I64d) ConfiguredEncryptedAreaEnd=%I64d (%I64d)\n", Extension->ConfiguredEncryptedAreaStart / 1024 / 1024, Extension->ConfiguredEncryptedAreaStart, Extension->ConfiguredEncryptedAreaEnd / 1024 / 1024, Extension->ConfiguredEncryptedAreaEnd); + Dump ("Loaded: EncryptedAreaStart=%I64d (%I64d) EncryptedAreaEnd=%I64d (%I64d)\n", Extension->Queue.EncryptedAreaStart / 1024 / 1024, Extension->Queue.EncryptedAreaStart, Extension->Queue.EncryptedAreaEnd / 1024 / 1024, Extension->Queue.EncryptedAreaEnd); + + // Erase boot loader scheduled keys + if (mappedCryptoInfo) + { + burn (mappedCryptoInfo, BootArgs.CryptoInfoLength); + MmUnmapIoSpace (mappedCryptoInfo, BootArgs.CryptoInfoLength); + BootArgs.CryptoInfoLength = 0; + } + + BootDriveFilterExtension = Extension; + BootDriveFound = Extension->BootDrive = Extension->DriveMounted = Extension->VolumeHeaderPresent = TRUE; + BootDriveFilterExtension->MagicNumber = TC_BOOT_DRIVE_FILTER_EXTENSION_MAGIC_NUMBER; + + burn (&BootArgs.BootPassword, sizeof (BootArgs.BootPassword)); + + { + STORAGE_DEVICE_NUMBER storageDeviceNumber; + status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &storageDeviceNumber, sizeof (storageDeviceNumber)); + + if (!NT_SUCCESS (status)) + { + Dump ("Failed to get drive number - error %x\n", status); + Extension->SystemStorageDeviceNumberValid = FALSE; + } + else + { + Extension->SystemStorageDeviceNumber = storageDeviceNumber.DeviceNumber; + Extension->SystemStorageDeviceNumberValid = TRUE; + } + } + + status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &BootDriveLength, sizeof (BootDriveLength)); + + if (!NT_SUCCESS (status)) + { + Dump ("Failed to get drive length - error %x\n", status); + BootDriveLength.QuadPart = 0; + Extension->Queue.MaxReadAheadOffset.QuadPart = 0; + } + else + Extension->Queue.MaxReadAheadOffset = BootDriveLength; + + status = EncryptedIoQueueStart (&Extension->Queue); + if (!NT_SUCCESS (status)) + TC_BUG_CHECK (status); + + if (IsOSAtLeast (WIN_VISTA)) + { + CrashDumpEnabled = TRUE; + HibernationEnabled = TRUE; + } + else if (!LegacyHibernationDriverFilterActive) + StartLegacyHibernationDriverFilter(); + + // Hidden system hibernation is not supported if an extra boot partition is present as the system is not allowed to update the boot partition + if (IsHiddenSystemRunning() && (BootArgs.Flags & TC_BOOT_ARGS_FLAG_EXTRA_BOOT_PARTITION)) + { + CrashDumpEnabled = FALSE; + HibernationEnabled = FALSE; + } + } + else + { + Dump ("Header not decrypted\n"); + crypto_close (Extension->HeaderCryptoInfo); + Extension->HeaderCryptoInfo = NULL; + + status = STATUS_UNSUCCESSFUL; + } + +ret: + TCfree (header); + return status; +} + + +static NTSTATUS SaveDriveVolumeHeader (DriveFilterExtension *Extension) +{ + NTSTATUS status = STATUS_SUCCESS; + LARGE_INTEGER offset; + byte *header; + + header = TCalloc (TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); + if (!header) + return STATUS_INSUFFICIENT_RESOURCES; + + offset.QuadPart = TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET; + + status = TCReadDevice (Extension->LowerDeviceObject, header, offset, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); + if (!NT_SUCCESS (status)) + { + Dump ("TCReadDevice error %x", status); + goto ret; + } + + Dump ("Saving: ConfiguredEncryptedAreaStart=%I64d (%I64d) ConfiguredEncryptedAreaEnd=%I64d (%I64d)\n", Extension->ConfiguredEncryptedAreaStart / 1024 / 1024, Extension->ConfiguredEncryptedAreaStart, Extension->ConfiguredEncryptedAreaEnd / 1024 / 1024, Extension->ConfiguredEncryptedAreaEnd); + Dump ("Saving: EncryptedAreaStart=%I64d (%I64d) EncryptedAreaEnd=%I64d (%I64d)\n", Extension->Queue.EncryptedAreaStart / 1024 / 1024, Extension->Queue.EncryptedAreaStart, Extension->Queue.EncryptedAreaEnd / 1024 / 1024, Extension->Queue.EncryptedAreaEnd); + + if (Extension->Queue.EncryptedAreaStart == -1 || Extension->Queue.EncryptedAreaEnd == -1 + || Extension->Queue.EncryptedAreaEnd <= Extension->Queue.EncryptedAreaStart) + { + if (SetupRequest.SetupMode == SetupDecryption) + { + memset (header, 0, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); + Extension->VolumeHeaderPresent = FALSE; + } + } + else + { + uint32 headerCrc32; + uint64 encryptedAreaLength = Extension->Queue.EncryptedAreaEnd + 1 - Extension->Queue.EncryptedAreaStart; + byte *fieldPos = header + TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH; + + DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, Extension->HeaderCryptoInfo); + + if (GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x56455241) + { + Dump ("Header not decrypted"); + status = STATUS_UNKNOWN_REVISION; + goto ret; + } + + mputInt64 (fieldPos, encryptedAreaLength); + + headerCrc32 = GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC); + fieldPos = header + TC_HEADER_OFFSET_HEADER_CRC; + mputLong (fieldPos, headerCrc32); + + EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, Extension->HeaderCryptoInfo); + } + + status = TCWriteDevice (Extension->LowerDeviceObject, header, offset, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); + if (!NT_SUCCESS (status)) + { + Dump ("TCWriteDevice error %x", status); + goto ret; + } + +ret: + TCfree (header); + return status; +} + + +static NTSTATUS PassIrp (PDEVICE_OBJECT deviceObject, PIRP irp) +{ + IoSkipCurrentIrpStackLocation (irp); + return IoCallDriver (deviceObject, irp); +} + + +static NTSTATUS PassFilteredIrp (PDEVICE_OBJECT deviceObject, PIRP irp, PIO_COMPLETION_ROUTINE completionRoutine, PVOID completionRoutineArg) +{ + IoCopyCurrentIrpStackLocationToNext (irp); + + if (completionRoutine) + IoSetCompletionRoutine (irp, completionRoutine, completionRoutineArg, TRUE, TRUE, TRUE); + + return IoCallDriver (deviceObject, irp); +} + + +static NTSTATUS OnDeviceUsageNotificationCompleted (PDEVICE_OBJECT filterDeviceObject, PIRP Irp, DriveFilterExtension *Extension) +{ + if (Irp->PendingReturned) + IoMarkIrpPending (Irp); + + if (!(Extension->LowerDeviceObject->Flags & DO_POWER_PAGABLE)) + filterDeviceObject->Flags &= ~DO_POWER_PAGABLE; + + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return STATUS_CONTINUE_COMPLETION; +} + + +static BOOL IsVolumeDevice (PDEVICE_OBJECT deviceObject) +{ + VOLUME_NUMBER volNumber; + VOLUME_DISK_EXTENTS extents[2]; + NTSTATUS extentStatus = SendDeviceIoControlRequest (deviceObject, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, extents, sizeof (extents)); + + return NT_SUCCESS (SendDeviceIoControlRequest (deviceObject, IOCTL_VOLUME_SUPPORTS_ONLINE_OFFLINE, NULL, 0, NULL, 0)) + || NT_SUCCESS (SendDeviceIoControlRequest (deviceObject, IOCTL_VOLUME_IS_OFFLINE, NULL, 0, NULL, 0)) + || NT_SUCCESS (SendDeviceIoControlRequest (deviceObject, IOCTL_VOLUME_IS_IO_CAPABLE, NULL, 0, NULL, 0)) + || NT_SUCCESS (SendDeviceIoControlRequest (deviceObject, IOCTL_VOLUME_IS_PARTITION, NULL, 0, NULL, 0)) + || NT_SUCCESS (SendDeviceIoControlRequest (deviceObject, IOCTL_VOLUME_QUERY_VOLUME_NUMBER, NULL, 0, &volNumber, sizeof (volNumber))) + || NT_SUCCESS (extentStatus) || extentStatus == STATUS_BUFFER_OVERFLOW || extentStatus == STATUS_BUFFER_TOO_SMALL; +} + + +static void CheckDeviceTypeAndMount (DriveFilterExtension *filterExtension) +{ + if (BootArgsValid) + { + // Windows sometimes merges a removable drive PDO and its volume PDO to a single PDO having no volume interface (GUID_DEVINTERFACE_VOLUME). + // Therefore, we need to test whether the device supports volume IOCTLs. + if (VolumeClassFilterRegistered + && BootArgs.HiddenSystemPartitionStart != 0 + && IsVolumeDevice (filterExtension->LowerDeviceObject)) + { + Dump ("Drive and volume merged pdo=%p", filterExtension->Pdo); + + filterExtension->IsVolumeFilterDevice = TRUE; + filterExtension->IsDriveFilterDevice = FALSE; + } + else + { + NTSTATUS status = KeWaitForMutexObject (&MountMutex, Executive, KernelMode, FALSE, NULL); + if (!NT_SUCCESS (status)) + TC_BUG_CHECK (status); + + if (!BootDriveFound) + MountDrive (filterExtension, &BootArgs.BootPassword, &BootArgs.HeaderSaltCrc32); + + KeReleaseMutex (&MountMutex, FALSE); + } + } +} + + +static VOID MountDriveWorkItemRoutine (PDEVICE_OBJECT deviceObject, DriveFilterExtension *filterExtension) +{ + CheckDeviceTypeAndMount (filterExtension); + KeSetEvent (&filterExtension->MountWorkItemCompletedEvent, IO_NO_INCREMENT, FALSE); +} + + +static NTSTATUS OnStartDeviceCompleted (PDEVICE_OBJECT filterDeviceObject, PIRP Irp, DriveFilterExtension *Extension) +{ + if (Irp->PendingReturned) + IoMarkIrpPending (Irp); + + if (Extension->LowerDeviceObject->Characteristics & FILE_REMOVABLE_MEDIA) + filterDeviceObject->Characteristics |= FILE_REMOVABLE_MEDIA; + + if (KeGetCurrentIrql() == PASSIVE_LEVEL) + { + CheckDeviceTypeAndMount (Extension); + } + else + { + PIO_WORKITEM workItem = IoAllocateWorkItem (filterDeviceObject); + if (!workItem) + { + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return STATUS_INSUFFICIENT_RESOURCES; + } + + KeInitializeEvent (&Extension->MountWorkItemCompletedEvent, SynchronizationEvent, FALSE); + IoQueueWorkItem (workItem, MountDriveWorkItemRoutine, DelayedWorkQueue, Extension); + + KeWaitForSingleObject (&Extension->MountWorkItemCompletedEvent, Executive, KernelMode, FALSE, NULL); + IoFreeWorkItem (workItem); + } + + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return STATUS_CONTINUE_COMPLETION; +} + + +static NTSTATUS DispatchPnp (PDEVICE_OBJECT DeviceObject, PIRP Irp, DriveFilterExtension *Extension, PIO_STACK_LOCATION irpSp) +{ + NTSTATUS status; + + status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); + if (!NT_SUCCESS (status)) + return TCCompleteIrp (Irp, status, 0); + + switch (irpSp->MinorFunction) + { + case IRP_MN_START_DEVICE: + Dump ("IRP_MN_START_DEVICE pdo=%p\n", Extension->Pdo); + return PassFilteredIrp (Extension->LowerDeviceObject, Irp, OnStartDeviceCompleted, Extension); + + + case IRP_MN_DEVICE_USAGE_NOTIFICATION: + Dump ("IRP_MN_DEVICE_USAGE_NOTIFICATION type=%d\n", (int) irpSp->Parameters.UsageNotification.Type); + + { + PDEVICE_OBJECT attachedDevice = IoGetAttachedDeviceReference (DeviceObject); + + if (attachedDevice == DeviceObject || (attachedDevice->Flags & DO_POWER_PAGABLE)) + DeviceObject->Flags |= DO_POWER_PAGABLE; + + ObDereferenceObject (attachedDevice); + } + + // Prevent creation of hibernation and crash dump files if required + if (irpSp->Parameters.UsageNotification.InPath + && ( + (irpSp->Parameters.UsageNotification.Type == DeviceUsageTypeDumpFile && !CrashDumpEnabled) + || (irpSp->Parameters.UsageNotification.Type == DeviceUsageTypeHibernation && !HibernationEnabled) + ) + ) + { + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + + if (irpSp->Parameters.UsageNotification.Type == DeviceUsageTypeHibernation) + ++HibernationPreventionCount; + + Dump ("Preventing dump type=%d\n", (int) irpSp->Parameters.UsageNotification.Type); + return TCCompleteIrp (Irp, STATUS_UNSUCCESSFUL, 0); + } + + return PassFilteredIrp (Extension->LowerDeviceObject, Irp, OnDeviceUsageNotificationCompleted, Extension); + + + case IRP_MN_REMOVE_DEVICE: + Dump ("IRP_MN_REMOVE_DEVICE pdo=%p\n", Extension->Pdo); + + IoReleaseRemoveLockAndWait (&Extension->Queue.RemoveLock, Irp); + status = PassIrp (Extension->LowerDeviceObject, Irp); + + IoDetachDevice (Extension->LowerDeviceObject); + + if (Extension->DriveMounted) + DismountDrive (Extension, TRUE); + + if (Extension->BootDrive) + { + BootDriveFound = FALSE; + BootDriveFilterExtension = NULL; + } + + IoDeleteDevice (DeviceObject); + return status; + + + default: + status = PassIrp (Extension->LowerDeviceObject, Irp); + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + } + return status; +} + + +static NTSTATUS DispatchPower (PDEVICE_OBJECT DeviceObject, PIRP Irp, DriveFilterExtension *Extension, PIO_STACK_LOCATION irpSp) +{ + NTSTATUS status; + Dump ("IRP_MJ_POWER minor=%d type=%d shutdown=%d\n", (int) irpSp->MinorFunction, (int) irpSp->Parameters.Power.Type, (int) irpSp->Parameters.Power.ShutdownType); + + if (SetupInProgress + && irpSp->MinorFunction == IRP_MN_SET_POWER + && irpSp->Parameters.Power.ShutdownType == PowerActionHibernate) + { + while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES); + } + +#if 0 // Dismount of the system drive is disabled until there is a way to do it without causing system errors (see the documentation for more info) + if (DriverShuttingDown + && Extension->BootDrive + && Extension->DriveMounted + && irpSp->MinorFunction == IRP_MN_SET_POWER + && irpSp->Parameters.Power.Type == DevicePowerState) + { + DismountDrive (Extension, TRUE); + } +#endif // 0 + + PoStartNextPowerIrp (Irp); + + status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); + if (!NT_SUCCESS (status)) + return TCCompleteIrp (Irp, status, 0); + + IoSkipCurrentIrpStackLocation (Irp); + status = PoCallDriver (Extension->LowerDeviceObject, Irp); + + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return status; +} + + +NTSTATUS DriveFilterDispatchIrp (PDEVICE_OBJECT DeviceObject, PIRP Irp) +{ + DriveFilterExtension *Extension = (DriveFilterExtension *) DeviceObject->DeviceExtension; + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); + NTSTATUS status; + + ASSERT (!Extension->bRootDevice && Extension->IsDriveFilterDevice); + + switch (irpSp->MajorFunction) + { + case IRP_MJ_READ: + case IRP_MJ_WRITE: + if (Extension->BootDrive) + { + status = EncryptedIoQueueAddIrp (&Extension->Queue, Irp); + + if (status != STATUS_PENDING) + TCCompleteDiskIrp (Irp, status, 0); + + return status; + } + break; + + case IRP_MJ_PNP: + return DispatchPnp (DeviceObject, Irp, Extension, irpSp); + + case IRP_MJ_POWER: + return DispatchPower (DeviceObject, Irp, Extension, irpSp); + } + + status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); + if (!NT_SUCCESS (status)) + return TCCompleteIrp (Irp, status, 0); + + status = PassIrp (Extension->LowerDeviceObject, Irp); + + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return status; +} + + +void ReopenBootVolumeHeader (PIRP irp, PIO_STACK_LOCATION irpSp) +{ + LARGE_INTEGER offset; + char *header; + ReopenBootVolumeHeaderRequest *request = (ReopenBootVolumeHeaderRequest *) irp->AssociatedIrp.SystemBuffer; + + irp->IoStatus.Information = 0; + + if (!IoIsSystemThread (PsGetCurrentThread()) && !UserCanAccessDriveDevice()) + { + irp->IoStatus.Status = STATUS_ACCESS_DENIED; + return; + } + + if (!ValidateIOBufferSize (irp, sizeof (ReopenBootVolumeHeaderRequest), ValidateInput)) + return; + + if (!BootDriveFound || !BootDriveFilterExtension || !BootDriveFilterExtension->DriveMounted || !BootDriveFilterExtension->HeaderCryptoInfo + || request->VolumePassword.Length > MAX_PASSWORD + || request->pkcs5_prf < 0 + || request->pkcs5_prf > LAST_PRF_ID + || request->pim < 0 + || request->pim > 65535 + ) + { + irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + goto wipe; + } + + header = TCalloc (TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); + if (!header) + { + irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; + goto wipe; + } + + if (BootDriveFilterExtension->HiddenSystem) + offset.QuadPart = BootArgs.HiddenSystemPartitionStart + TC_HIDDEN_VOLUME_HEADER_OFFSET; + else + offset.QuadPart = TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET; + + irp->IoStatus.Status = TCReadDevice (BootDriveFilterExtension->LowerDeviceObject, header, offset, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); + if (!NT_SUCCESS (irp->IoStatus.Status)) + { + Dump ("TCReadDevice error %x\n", irp->IoStatus.Status); + goto ret; + } + + if (ReadVolumeHeader (!BootDriveFilterExtension->HiddenSystem, header, &request->VolumePassword, request->pkcs5_prf, request->pim, FALSE, NULL, BootDriveFilterExtension->HeaderCryptoInfo) == 0) + { + Dump ("Header reopened\n"); + ComputeBootLoaderFingerprint (BootDriveFilterExtension->LowerDeviceObject, header); + + BootDriveFilterExtension->Queue.CryptoInfo->header_creation_time = BootDriveFilterExtension->HeaderCryptoInfo->header_creation_time; + BootDriveFilterExtension->Queue.CryptoInfo->pkcs5 = BootDriveFilterExtension->HeaderCryptoInfo->pkcs5; + BootDriveFilterExtension->Queue.CryptoInfo->noIterations = BootDriveFilterExtension->HeaderCryptoInfo->noIterations; + BootDriveFilterExtension->Queue.CryptoInfo->volumePim = BootDriveFilterExtension->HeaderCryptoInfo->volumePim; + + irp->IoStatus.Status = STATUS_SUCCESS; + } + else + { + crypto_close (BootDriveFilterExtension->HeaderCryptoInfo); + BootDriveFilterExtension->HeaderCryptoInfo = NULL; + + Dump ("Header not reopened\n"); + irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + } + +ret: + TCfree (header); +wipe: + burn (request, sizeof (*request)); +} + + +// Legacy Windows XP/2003 hibernation dump filter + +typedef NTSTATUS (*HiberDriverWriteFunctionA) (ULONG arg0, PLARGE_INTEGER writeOffset, PMDL dataMdl, PVOID arg3); +typedef NTSTATUS (*HiberDriverWriteFunctionB) (PLARGE_INTEGER writeOffset, PMDL dataMdl); + +typedef struct +{ +#ifdef _WIN64 + byte FieldPad1[64]; + HiberDriverWriteFunctionB WriteFunctionB; + byte FieldPad2[56]; +#else + byte FieldPad1[48]; + HiberDriverWriteFunctionB WriteFunctionB; + byte FieldPad2[32]; +#endif + HiberDriverWriteFunctionA WriteFunctionA; + byte FieldPad3[24]; + LARGE_INTEGER PartitionStartOffset; +} HiberDriverContext; + +typedef NTSTATUS (*HiberDriverEntry) (PVOID arg0, HiberDriverContext *hiberDriverContext); + +typedef struct +{ + LIST_ENTRY ModuleList; +#ifdef _WIN64 + byte FieldPad1[32]; +#else + byte FieldPad1[16]; +#endif + PVOID ModuleBaseAddress; + HiberDriverEntry ModuleEntryAddress; +#ifdef _WIN64 + byte FieldPad2[24]; +#else + byte FieldPad2[12]; +#endif + UNICODE_STRING ModuleName; +} ModuleTableItem; + + +#define TC_MAX_HIBER_FILTER_COUNT 3 +static int LastHiberFilterNumber = 0; + +static HiberDriverEntry OriginalHiberDriverEntries[TC_MAX_HIBER_FILTER_COUNT]; +static HiberDriverWriteFunctionA OriginalHiberDriverWriteFunctionsA[TC_MAX_HIBER_FILTER_COUNT]; +static HiberDriverWriteFunctionB OriginalHiberDriverWriteFunctionsB[TC_MAX_HIBER_FILTER_COUNT]; + +static LARGE_INTEGER HiberPartitionOffset; + + +static NTSTATUS HiberDriverWriteFunctionFilter (int filterNumber, PLARGE_INTEGER writeOffset, PMDL dataMdl, BOOL writeB, ULONG arg0WriteA, PVOID arg3WriteA) +{ + MDL *encryptedDataMdl = dataMdl; + + if (writeOffset && dataMdl && BootDriveFilterExtension && BootDriveFilterExtension->DriveMounted) + { + ULONG dataLength = MmGetMdlByteCount (dataMdl); + + if (dataMdl->MappedSystemVa && dataLength > 0) + { + uint64 offset = HiberPartitionOffset.QuadPart + writeOffset->QuadPart; + uint64 intersectStart; + uint32 intersectLength; + + if (dataLength > TC_HIBERNATION_WRITE_BUFFER_SIZE) + TC_BUG_CHECK (STATUS_BUFFER_OVERFLOW); + + if ((dataLength & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0) + TC_BUG_CHECK (STATUS_INVALID_PARAMETER); + + if ((offset & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0) + TC_BUG_CHECK (STATUS_INVALID_PARAMETER); + + GetIntersection (offset, + dataLength, + BootDriveFilterExtension->Queue.EncryptedAreaStart, + BootDriveFilterExtension->Queue.EncryptedAreaEnd, + &intersectStart, + &intersectLength); + + if (intersectLength > 0) + { + UINT64_STRUCT dataUnit; + dataUnit.Value = intersectStart / ENCRYPTION_DATA_UNIT_SIZE; + + memcpy (HibernationWriteBuffer, dataMdl->MappedSystemVa, dataLength); + + if (BootDriveFilterExtension->Queue.RemapEncryptedArea) + dataUnit.Value += BootDriveFilterExtension->Queue.RemappedAreaDataUnitOffset; + + EncryptDataUnitsCurrentThread (HibernationWriteBuffer + (intersectStart - offset), + &dataUnit, + intersectLength / ENCRYPTION_DATA_UNIT_SIZE, + BootDriveFilterExtension->Queue.CryptoInfo); + + encryptedDataMdl = HibernationWriteBufferMdl; + MmInitializeMdl (encryptedDataMdl, HibernationWriteBuffer, dataLength); + encryptedDataMdl->MdlFlags = dataMdl->MdlFlags; + } + } + } + + if (writeB) + return (*OriginalHiberDriverWriteFunctionsB[filterNumber]) (writeOffset, encryptedDataMdl); + + return (*OriginalHiberDriverWriteFunctionsA[filterNumber]) (arg0WriteA, writeOffset, encryptedDataMdl, arg3WriteA); +} + + +static NTSTATUS HiberDriverWriteFunctionAFilter0 (ULONG arg0, PLARGE_INTEGER writeOffset, PMDL dataMdl, PVOID arg3) +{ + return HiberDriverWriteFunctionFilter (0, writeOffset, dataMdl, FALSE, arg0, arg3); +} + +static NTSTATUS HiberDriverWriteFunctionAFilter1 (ULONG arg0, PLARGE_INTEGER writeOffset, PMDL dataMdl, PVOID arg3) +{ + return HiberDriverWriteFunctionFilter (1, writeOffset, dataMdl, FALSE, arg0, arg3); +} + +static NTSTATUS HiberDriverWriteFunctionAFilter2 (ULONG arg0, PLARGE_INTEGER writeOffset, PMDL dataMdl, PVOID arg3) +{ + return HiberDriverWriteFunctionFilter (2, writeOffset, dataMdl, FALSE, arg0, arg3); +} + + +static NTSTATUS HiberDriverWriteFunctionBFilter0 (PLARGE_INTEGER writeOffset, PMDL dataMdl) +{ + return HiberDriverWriteFunctionFilter (0, writeOffset, dataMdl, TRUE, 0, NULL); +} + +static NTSTATUS HiberDriverWriteFunctionBFilter1 (PLARGE_INTEGER writeOffset, PMDL dataMdl) +{ + return HiberDriverWriteFunctionFilter (1, writeOffset, dataMdl, TRUE, 0, NULL); +} + +static NTSTATUS HiberDriverWriteFunctionBFilter2 (PLARGE_INTEGER writeOffset, PMDL dataMdl) +{ + return HiberDriverWriteFunctionFilter (2, writeOffset, dataMdl, TRUE, 0, NULL); +} + + +static NTSTATUS HiberDriverEntryFilter (int filterNumber, PVOID arg0, HiberDriverContext *hiberDriverContext) +{ + BOOL filterInstalled = FALSE; + NTSTATUS status; + + if (!OriginalHiberDriverEntries[filterNumber]) + return STATUS_UNSUCCESSFUL; + + status = (*OriginalHiberDriverEntries[filterNumber]) (arg0, hiberDriverContext); + + if (!NT_SUCCESS (status) || !hiberDriverContext) + return status; + + if (SetupInProgress) + TC_BUG_CHECK (STATUS_INVALID_PARAMETER); + + if (hiberDriverContext->WriteFunctionA) + { + Dump ("Filtering WriteFunctionA %d\n", filterNumber); + OriginalHiberDriverWriteFunctionsA[filterNumber] = hiberDriverContext->WriteFunctionA; + + switch (filterNumber) + { + case 0: hiberDriverContext->WriteFunctionA = HiberDriverWriteFunctionAFilter0; break; + case 1: hiberDriverContext->WriteFunctionA = HiberDriverWriteFunctionAFilter1; break; + case 2: hiberDriverContext->WriteFunctionA = HiberDriverWriteFunctionAFilter2; break; + default: TC_THROW_FATAL_EXCEPTION; + } + + filterInstalled = TRUE; + } + + if (hiberDriverContext->WriteFunctionB) + { + Dump ("Filtering WriteFunctionB %d\n", filterNumber); + OriginalHiberDriverWriteFunctionsB[filterNumber] = hiberDriverContext->WriteFunctionB; + + switch (filterNumber) + { + case 0: hiberDriverContext->WriteFunctionB = HiberDriverWriteFunctionBFilter0; break; + case 1: hiberDriverContext->WriteFunctionB = HiberDriverWriteFunctionBFilter1; break; + case 2: hiberDriverContext->WriteFunctionB = HiberDriverWriteFunctionBFilter2; break; + default: TC_THROW_FATAL_EXCEPTION; + } + + filterInstalled = TRUE; + } + + if (filterInstalled && hiberDriverContext->PartitionStartOffset.QuadPart != 0) + { + HiberPartitionOffset = hiberDriverContext->PartitionStartOffset; + + if (BootDriveFilterExtension->Queue.RemapEncryptedArea) + hiberDriverContext->PartitionStartOffset.QuadPart += BootDriveFilterExtension->Queue.RemappedAreaOffset; + } + + return STATUS_SUCCESS; +} + + +static NTSTATUS HiberDriverEntryFilter0 (PVOID arg0, HiberDriverContext *hiberDriverContext) +{ + return HiberDriverEntryFilter (0, arg0, hiberDriverContext); +} + + +static NTSTATUS HiberDriverEntryFilter1 (PVOID arg0, HiberDriverContext *hiberDriverContext) +{ + return HiberDriverEntryFilter (1, arg0, hiberDriverContext); +} + + +static NTSTATUS HiberDriverEntryFilter2 (PVOID arg0, HiberDriverContext *hiberDriverContext) +{ + return HiberDriverEntryFilter (2, arg0, hiberDriverContext); +} + + +static VOID LoadImageNotifyRoutine (PUNICODE_STRING fullImageName, HANDLE processId, PIMAGE_INFO imageInfo) +{ + ModuleTableItem *moduleItem; + LIST_ENTRY *listEntry; + KIRQL origIrql; + + if (!imageInfo || !imageInfo->SystemModeImage || !imageInfo->ImageBase || !TCDriverObject->DriverSection) + return; + + moduleItem = *(ModuleTableItem **) TCDriverObject->DriverSection; + if (!moduleItem || !moduleItem->ModuleList.Flink) + return; + + // Search loaded system modules for hibernation driver + origIrql = KeRaiseIrqlToDpcLevel(); + + for (listEntry = moduleItem->ModuleList.Flink->Blink; + listEntry && listEntry != TCDriverObject->DriverSection; + listEntry = listEntry->Flink) + { + moduleItem = CONTAINING_RECORD (listEntry, ModuleTableItem, ModuleList); + + if (moduleItem && imageInfo->ImageBase == moduleItem->ModuleBaseAddress) + { + if (moduleItem->ModuleName.Buffer && moduleItem->ModuleName.Length >= 5 * sizeof (wchar_t)) + { + if (memcmp (moduleItem->ModuleName.Buffer, L"hiber", 5 * sizeof (wchar_t)) == 0 + || memcmp (moduleItem->ModuleName.Buffer, L"Hiber", 5 * sizeof (wchar_t)) == 0 + || memcmp (moduleItem->ModuleName.Buffer, L"HIBER", 5 * sizeof (wchar_t)) == 0) + { + HiberDriverEntry filterEntry; + + switch (LastHiberFilterNumber) + { + case 0: filterEntry = HiberDriverEntryFilter0; break; + case 1: filterEntry = HiberDriverEntryFilter1; break; + case 2: filterEntry = HiberDriverEntryFilter2; break; + default: TC_THROW_FATAL_EXCEPTION; + } + + if (moduleItem->ModuleEntryAddress != filterEntry) + { + // Install filter + OriginalHiberDriverEntries[LastHiberFilterNumber] = moduleItem->ModuleEntryAddress; + moduleItem->ModuleEntryAddress = filterEntry; + + if (++LastHiberFilterNumber > TC_MAX_HIBER_FILTER_COUNT - 1) + LastHiberFilterNumber = 0; + } + } + } + break; + } + } + + KeLowerIrql (origIrql); +} + + +void StartLegacyHibernationDriverFilter () +{ + PHYSICAL_ADDRESS highestAcceptableWriteBufferAddr; + NTSTATUS status; + + ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL); + ASSERT (!IsOSAtLeast (WIN_VISTA)); + + if (!TCDriverObject->DriverSection || !*(ModuleTableItem **) TCDriverObject->DriverSection) + goto err; + + // All buffers required for hibernation must be allocated here +#ifdef _WIN64 + highestAcceptableWriteBufferAddr.QuadPart = 0x7FFffffFFFFULL; +#else + highestAcceptableWriteBufferAddr.QuadPart = 0xffffFFFFULL; +#endif + + HibernationWriteBuffer = MmAllocateContiguousMemory (TC_HIBERNATION_WRITE_BUFFER_SIZE, highestAcceptableWriteBufferAddr); + if (!HibernationWriteBuffer) + goto err; + + HibernationWriteBufferMdl = IoAllocateMdl (HibernationWriteBuffer, TC_HIBERNATION_WRITE_BUFFER_SIZE, FALSE, FALSE, NULL); + if (!HibernationWriteBufferMdl) + goto err; + + MmBuildMdlForNonPagedPool (HibernationWriteBufferMdl); + + status = PsSetLoadImageNotifyRoutine (LoadImageNotifyRoutine); + if (!NT_SUCCESS (status)) + goto err; + + LegacyHibernationDriverFilterActive = TRUE; + CrashDumpEnabled = FALSE; + HibernationEnabled = TRUE; + return; + +err: + LegacyHibernationDriverFilterActive = FALSE; + CrashDumpEnabled = FALSE; + HibernationEnabled = FALSE; + + if (HibernationWriteBufferMdl) + { + IoFreeMdl (HibernationWriteBufferMdl); + HibernationWriteBufferMdl = NULL; + } + + if (HibernationWriteBuffer) + { + MmFreeContiguousMemory (HibernationWriteBuffer); + HibernationWriteBuffer = NULL; + } +} + + +static VOID SetupThreadProc (PVOID threadArg) +{ + DriveFilterExtension *Extension = BootDriveFilterExtension; + + LARGE_INTEGER offset; + UINT64_STRUCT dataUnit; + ULONG setupBlockSize = TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE; + BOOL headerUpdateRequired = FALSE; + int64 bytesWrittenSinceHeaderUpdate = 0; + + byte *buffer = NULL; + byte *wipeBuffer = NULL; + byte wipeRandChars[TC_WIPE_RAND_CHAR_COUNT]; + byte wipeRandCharsUpdate[TC_WIPE_RAND_CHAR_COUNT]; + + KIRQL irql; + NTSTATUS status; + + // generate real random values for wipeRandChars and + // wipeRandCharsUpdate instead of relying on uninitialized stack memory + LARGE_INTEGER iSeed; + KeQuerySystemTime( &iSeed ); + if (KeGetCurrentIrql() < DISPATCH_LEVEL) + { + ULONG ulRandom; + ulRandom = RtlRandomEx( &iSeed.LowPart ); + memcpy (wipeRandChars, &ulRandom, TC_WIPE_RAND_CHAR_COUNT); + ulRandom = RtlRandomEx( &ulRandom ); + memcpy (wipeRandCharsUpdate, &ulRandom, TC_WIPE_RAND_CHAR_COUNT); + burn (&ulRandom, sizeof(ulRandom)); + } + else + { + byte digest[SHA512_DIGESTSIZE]; + sha512_ctx tctx; + sha512_begin (&tctx); + sha512_hash ((unsigned char *) &(iSeed.QuadPart), sizeof(iSeed.QuadPart), &tctx); + sha512_end (digest, &tctx); + + memcpy (wipeRandChars, digest, TC_WIPE_RAND_CHAR_COUNT); + memcpy (wipeRandCharsUpdate, &digest[SHA512_DIGESTSIZE - TC_WIPE_RAND_CHAR_COUNT], TC_WIPE_RAND_CHAR_COUNT); + + burn (digest, SHA512_DIGESTSIZE); + burn (&tctx, sizeof (tctx)); + } + + burn (&iSeed, sizeof(iSeed)); + + SetupResult = STATUS_UNSUCCESSFUL; + + // Make sure volume header can be updated + if (Extension->HeaderCryptoInfo == NULL) + { + SetupResult = STATUS_INVALID_PARAMETER; + goto ret; + } + + buffer = TCalloc (TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); + if (!buffer) + { + SetupResult = STATUS_INSUFFICIENT_RESOURCES; + goto ret; + } + + if (SetupRequest.SetupMode == SetupEncryption && SetupRequest.WipeAlgorithm != TC_WIPE_NONE) + { + wipeBuffer = TCalloc (TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); + if (!wipeBuffer) + { + SetupResult = STATUS_INSUFFICIENT_RESOURCES; + goto ret; + } + } + + while (!NT_SUCCESS (EncryptedIoQueueHoldWhenIdle (&Extension->Queue, 1000))) + { + if (EncryptionSetupThreadAbortRequested) + goto abort; + + TransformWaitingForIdle = TRUE; + } + TransformWaitingForIdle = FALSE; + + switch (SetupRequest.SetupMode) + { + case SetupEncryption: + Dump ("Encrypting...\n"); + if (Extension->Queue.EncryptedAreaStart == -1 || Extension->Queue.EncryptedAreaEnd == -1) + { + // Start encryption + Extension->Queue.EncryptedAreaStart = Extension->ConfiguredEncryptedAreaStart; + Extension->Queue.EncryptedAreaEnd = -1; + offset.QuadPart = Extension->ConfiguredEncryptedAreaStart; + } + else + { + // Resume aborted encryption + if (Extension->Queue.EncryptedAreaEnd == Extension->ConfiguredEncryptedAreaEnd) + goto err; + + offset.QuadPart = Extension->Queue.EncryptedAreaEnd + 1; + } + + break; + + case SetupDecryption: + Dump ("Decrypting...\n"); + if (Extension->Queue.EncryptedAreaStart == -1 || Extension->Queue.EncryptedAreaEnd == -1) + { + SetupResult = STATUS_SUCCESS; + goto abort; + } + + offset.QuadPart = Extension->Queue.EncryptedAreaEnd + 1; + break; + + default: + goto err; + } + + EncryptedIoQueueResumeFromHold (&Extension->Queue); + + Dump ("EncryptedAreaStart=%I64d\n", Extension->Queue.EncryptedAreaStart); + Dump ("EncryptedAreaEnd=%I64d\n", Extension->Queue.EncryptedAreaEnd); + Dump ("ConfiguredEncryptedAreaStart=%I64d\n", Extension->ConfiguredEncryptedAreaStart); + Dump ("ConfiguredEncryptedAreaEnd=%I64d\n", Extension->ConfiguredEncryptedAreaEnd); + Dump ("offset=%I64d\n", offset.QuadPart); + Dump ("EncryptedAreaStart=%I64d (%I64d) EncryptedAreaEnd=%I64d\n", Extension->Queue.EncryptedAreaStart / 1024 / 1024, Extension->Queue.EncryptedAreaStart, Extension->Queue.EncryptedAreaEnd / 1024 / 1024); + + while (!EncryptionSetupThreadAbortRequested) + { + if (SetupRequest.SetupMode == SetupEncryption) + { + if (offset.QuadPart + setupBlockSize > Extension->ConfiguredEncryptedAreaEnd + 1) + setupBlockSize = (ULONG) (Extension->ConfiguredEncryptedAreaEnd + 1 - offset.QuadPart); + + if (offset.QuadPart > Extension->ConfiguredEncryptedAreaEnd) + break; + } + else + { + if (offset.QuadPart - setupBlockSize < Extension->Queue.EncryptedAreaStart) + setupBlockSize = (ULONG) (offset.QuadPart - Extension->Queue.EncryptedAreaStart); + + offset.QuadPart -= setupBlockSize; + + if (setupBlockSize == 0 || offset.QuadPart < Extension->Queue.EncryptedAreaStart) + break; + } + + while (!NT_SUCCESS (EncryptedIoQueueHoldWhenIdle (&Extension->Queue, 500))) + { + if (EncryptionSetupThreadAbortRequested) + goto abort; + + TransformWaitingForIdle = TRUE; + } + TransformWaitingForIdle = FALSE; + + status = TCReadDevice (BootDriveFilterExtension->LowerDeviceObject, buffer, offset, setupBlockSize); + if (!NT_SUCCESS (status)) + { + Dump ("TCReadDevice error %x offset=%I64d\n", status, offset.QuadPart); + + if (SetupRequest.ZeroUnreadableSectors && SetupRequest.SetupMode == SetupEncryption) + { + // Zero unreadable sectors + uint64 zeroedSectorCount; + + status = ZeroUnreadableSectors (BootDriveFilterExtension->LowerDeviceObject, offset, setupBlockSize, &zeroedSectorCount); + if (!NT_SUCCESS (status)) + { + SetupResult = status; + goto err; + } + + // Retry read + status = TCReadDevice (BootDriveFilterExtension->LowerDeviceObject, buffer, offset, setupBlockSize); + if (!NT_SUCCESS (status)) + { + SetupResult = status; + goto err; + } + } + else if (SetupRequest.DiscardUnreadableEncryptedSectors && SetupRequest.SetupMode == SetupDecryption) + { + // Discard unreadable encrypted sectors + uint64 badSectorCount; + + status = ReadDeviceSkipUnreadableSectors (BootDriveFilterExtension->LowerDeviceObject, buffer, offset, setupBlockSize, &badSectorCount); + if (!NT_SUCCESS (status)) + { + SetupResult = status; + goto err; + } + } + else + { + SetupResult = status; + goto err; + } + } + + dataUnit.Value = offset.QuadPart / ENCRYPTION_DATA_UNIT_SIZE; + + if (SetupRequest.SetupMode == SetupEncryption) + { + EncryptDataUnits (buffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); + + if (SetupRequest.WipeAlgorithm != TC_WIPE_NONE) + { + byte wipePass; + int wipePassCount = GetWipePassCount (SetupRequest.WipeAlgorithm); + if (wipePassCount <= 0) + { + SetupResult = STATUS_INVALID_PARAMETER; + goto err; + } + + for (wipePass = 1; wipePass <= wipePassCount; ++wipePass) + { + if (!WipeBuffer (SetupRequest.WipeAlgorithm, wipeRandChars, wipePass, wipeBuffer, setupBlockSize)) + { + ULONG i; + for (i = 0; i < setupBlockSize; ++i) + { + wipeBuffer[i] = buffer[i] + wipePass; + } + + EncryptDataUnits (wipeBuffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); + memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate)); + } + + status = TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, wipeBuffer, offset, setupBlockSize); + if (!NT_SUCCESS (status)) + { + // Undo failed write operation + DecryptDataUnits (buffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); + TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, buffer, offset, setupBlockSize); + + SetupResult = status; + goto err; + } + } + + memcpy (wipeRandChars, wipeRandCharsUpdate, sizeof (wipeRandCharsUpdate)); + } + } + else + { + DecryptDataUnits (buffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); + } + + status = TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, buffer, offset, setupBlockSize); + if (!NT_SUCCESS (status)) + { + Dump ("TCWriteDevice error %x\n", status); + + // Undo failed write operation + if (SetupRequest.SetupMode == SetupEncryption) + DecryptDataUnits (buffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); + else + EncryptDataUnits (buffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); + + TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, buffer, offset, setupBlockSize); + + SetupResult = status; + goto err; + } + + if (SetupRequest.SetupMode == SetupEncryption) + offset.QuadPart += setupBlockSize; + + Extension->Queue.EncryptedAreaEndUpdatePending = TRUE; + Extension->Queue.EncryptedAreaEnd = offset.QuadPart - 1; + Extension->Queue.EncryptedAreaEndUpdatePending = FALSE; + + headerUpdateRequired = TRUE; + + EncryptedIoQueueResumeFromHold (&Extension->Queue); + + KeAcquireSpinLock (&SetupStatusSpinLock, &irql); + SetupStatusEncryptedAreaEnd = Extension->Queue.EncryptedAreaEnd; + KeReleaseSpinLock (&SetupStatusSpinLock, irql); + + // Update volume header + bytesWrittenSinceHeaderUpdate += setupBlockSize; + if (bytesWrittenSinceHeaderUpdate >= TC_ENCRYPTION_SETUP_HEADER_UPDATE_THRESHOLD) + { + status = SaveDriveVolumeHeader (Extension); + ASSERT (NT_SUCCESS (status)); + if (NT_SUCCESS (status)) + { + headerUpdateRequired = FALSE; + bytesWrittenSinceHeaderUpdate = 0; + } + } + } + +abort: + SetupResult = STATUS_SUCCESS; +err: + + if (Extension->Queue.EncryptedAreaEnd == -1) + Extension->Queue.EncryptedAreaStart = -1; + + if (EncryptedIoQueueIsSuspended (&Extension->Queue)) + EncryptedIoQueueResumeFromHold (&Extension->Queue); + + if (SetupRequest.SetupMode == SetupDecryption && Extension->Queue.EncryptedAreaStart >= Extension->Queue.EncryptedAreaEnd) + { + while (!NT_SUCCESS (EncryptedIoQueueHoldWhenIdle (&Extension->Queue, 0))); + + Extension->ConfiguredEncryptedAreaStart = Extension->ConfiguredEncryptedAreaEnd = -1; + Extension->Queue.EncryptedAreaStart = Extension->Queue.EncryptedAreaEnd = -1; + + EncryptedIoQueueResumeFromHold (&Extension->Queue); + + headerUpdateRequired = TRUE; + } + + Dump ("Setup completed: EncryptedAreaStart=%I64d (%I64d) EncryptedAreaEnd=%I64d (%I64d)\n", Extension->Queue.EncryptedAreaStart / 1024 / 1024, Extension->Queue.EncryptedAreaStart, Extension->Queue.EncryptedAreaEnd / 1024 / 1024, Extension->Queue.EncryptedAreaEnd); + + if (headerUpdateRequired) + { + status = SaveDriveVolumeHeader (Extension); + + if (!NT_SUCCESS (status) && NT_SUCCESS (SetupResult)) + SetupResult = status; + } + + if (SetupRequest.SetupMode == SetupDecryption && Extension->ConfiguredEncryptedAreaEnd == -1 && Extension->DriveMounted) + { + while (!RootDeviceControlMutexAcquireNoWait() && !EncryptionSetupThreadAbortRequested) + { + TCSleep (10); + } + + // Disable hibernation (resume would fail due to a change in the system memory map) + HibernationEnabled = FALSE; + + DismountDrive (Extension, FALSE); + + if (!EncryptionSetupThreadAbortRequested) + RootDeviceControlMutexRelease(); + } + +ret: + if (buffer) + { + burn (buffer, TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); + TCfree (buffer); + } + if (wipeBuffer) + { + burn (wipeBuffer, TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); + TCfree (wipeBuffer); + } + + burn (wipeRandChars, TC_WIPE_RAND_CHAR_COUNT); + burn (wipeRandCharsUpdate, TC_WIPE_RAND_CHAR_COUNT); + + SetupInProgress = FALSE; + PsTerminateSystemThread (SetupResult); +} + + +NTSTATUS StartBootEncryptionSetup (PDEVICE_OBJECT DeviceObject, PIRP irp, PIO_STACK_LOCATION irpSp) +{ + NTSTATUS status; + + if (!UserCanAccessDriveDevice()) + return STATUS_ACCESS_DENIED; + + if (SetupInProgress || !BootDriveFound || !BootDriveFilterExtension + || !BootDriveFilterExtension->DriveMounted + || BootDriveFilterExtension->HiddenSystem + || irpSp->Parameters.DeviceIoControl.InputBufferLength < sizeof (BootEncryptionSetupRequest)) + return STATUS_INVALID_PARAMETER; + + if (EncryptionSetupThread) + AbortBootEncryptionSetup(); + + SetupRequest = *(BootEncryptionSetupRequest *) irp->AssociatedIrp.SystemBuffer; + + EncryptionSetupThreadAbortRequested = FALSE; + KeInitializeSpinLock (&SetupStatusSpinLock); + SetupStatusEncryptedAreaEnd = BootDriveFilterExtension ? BootDriveFilterExtension->Queue.EncryptedAreaEnd : -1; + + SetupInProgress = TRUE; + status = TCStartThread (SetupThreadProc, DeviceObject, &EncryptionSetupThread); + + if (!NT_SUCCESS (status)) + SetupInProgress = FALSE; + + return status; +} + + +void GetBootDriveVolumeProperties (PIRP irp, PIO_STACK_LOCATION irpSp) +{ + if (ValidateIOBufferSize (irp, sizeof (VOLUME_PROPERTIES_STRUCT), ValidateOutput)) + { + DriveFilterExtension *Extension = BootDriveFilterExtension; + VOLUME_PROPERTIES_STRUCT *prop = (VOLUME_PROPERTIES_STRUCT *) irp->AssociatedIrp.SystemBuffer; + memset (prop, 0, sizeof (*prop)); + + if (!BootDriveFound || !Extension || !Extension->DriveMounted) + { + irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + irp->IoStatus.Information = 0; + } + else + { + prop->hiddenVolume = Extension->Queue.CryptoInfo->hiddenVolume; + prop->diskLength = Extension->ConfiguredEncryptedAreaEnd + 1 - Extension->ConfiguredEncryptedAreaStart; + prop->ea = Extension->Queue.CryptoInfo->ea; + prop->mode = Extension->Queue.CryptoInfo->mode; + prop->pkcs5 = Extension->Queue.CryptoInfo->pkcs5; + prop->pkcs5Iterations = Extension->Queue.CryptoInfo->noIterations; + prop->volumePim = Extension->Queue.CryptoInfo->volumePim; +#if 0 + prop->volumeCreationTime = Extension->Queue.CryptoInfo->volume_creation_time; + prop->headerCreationTime = Extension->Queue.CryptoInfo->header_creation_time; +#endif + prop->volFormatVersion = Extension->Queue.CryptoInfo->LegacyVolume ? TC_VOLUME_FORMAT_VERSION_PRE_6_0 : TC_VOLUME_FORMAT_VERSION; + + prop->totalBytesRead = Extension->Queue.TotalBytesRead; + prop->totalBytesWritten = Extension->Queue.TotalBytesWritten; + + irp->IoStatus.Information = sizeof (VOLUME_PROPERTIES_STRUCT); + irp->IoStatus.Status = STATUS_SUCCESS; + } + } +} + + +void GetBootEncryptionStatus (PIRP irp, PIO_STACK_LOCATION irpSp) +{ + /* IMPORTANT: Do NOT add any potentially time-consuming operations to this function. */ + + if (ValidateIOBufferSize (irp, sizeof (BootEncryptionStatus), ValidateOutput)) + { + DriveFilterExtension *Extension = BootDriveFilterExtension; + BootEncryptionStatus *bootEncStatus = (BootEncryptionStatus *) irp->AssociatedIrp.SystemBuffer; + memset (bootEncStatus, 0, sizeof (*bootEncStatus)); + + if (BootArgsValid) + bootEncStatus->BootLoaderVersion = BootArgs.BootLoaderVersion; + + bootEncStatus->DeviceFilterActive = DeviceFilterActive; + bootEncStatus->SetupInProgress = SetupInProgress; + bootEncStatus->SetupMode = SetupRequest.SetupMode; + bootEncStatus->TransformWaitingForIdle = TransformWaitingForIdle; + + if (!BootDriveFound || !Extension || !Extension->DriveMounted) + { + bootEncStatus->DriveEncrypted = FALSE; + bootEncStatus->DriveMounted = FALSE; + bootEncStatus->VolumeHeaderPresent = FALSE; + } + else + { + bootEncStatus->DriveMounted = Extension->DriveMounted; + bootEncStatus->VolumeHeaderPresent = Extension->VolumeHeaderPresent; + bootEncStatus->DriveEncrypted = Extension->Queue.EncryptedAreaStart != -1; + bootEncStatus->BootDriveLength = BootDriveLength; + + bootEncStatus->ConfiguredEncryptedAreaStart = Extension->ConfiguredEncryptedAreaStart; + bootEncStatus->ConfiguredEncryptedAreaEnd = Extension->ConfiguredEncryptedAreaEnd; + bootEncStatus->EncryptedAreaStart = Extension->Queue.EncryptedAreaStart; + + if (SetupInProgress) + { + KIRQL irql; + KeAcquireSpinLock (&SetupStatusSpinLock, &irql); + bootEncStatus->EncryptedAreaEnd = SetupStatusEncryptedAreaEnd; + KeReleaseSpinLock (&SetupStatusSpinLock, irql); + } + else + bootEncStatus->EncryptedAreaEnd = Extension->Queue.EncryptedAreaEnd; + + bootEncStatus->VolumeHeaderSaltCrc32 = Extension->VolumeHeaderSaltCrc32; + bootEncStatus->HibernationPreventionCount = HibernationPreventionCount; + bootEncStatus->HiddenSysLeakProtectionCount = HiddenSysLeakProtectionCount; + + bootEncStatus->HiddenSystem = Extension->HiddenSystem; + + if (Extension->HiddenSystem) + bootEncStatus->HiddenSystemPartitionStart = BootArgs.HiddenSystemPartitionStart; + } + + irp->IoStatus.Information = sizeof (BootEncryptionStatus); + irp->IoStatus.Status = STATUS_SUCCESS; + } +} + + +void GetBootLoaderVersion (PIRP irp, PIO_STACK_LOCATION irpSp) +{ + if (ValidateIOBufferSize (irp, sizeof (uint16), ValidateOutput)) + { + if (BootArgsValid) + { + *(uint16 *) irp->AssociatedIrp.SystemBuffer = BootArgs.BootLoaderVersion; + irp->IoStatus.Information = sizeof (uint16); + irp->IoStatus.Status = STATUS_SUCCESS; + } + else + { + irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + irp->IoStatus.Information = 0; + } + } +} + +void GetBootLoaderFingerprint (PIRP irp, PIO_STACK_LOCATION irpSp) +{ + if (ValidateIOBufferSize (irp, sizeof (BootLoaderFingerprintRequest), ValidateOutput)) + { + irp->IoStatus.Information = 0; + if (BootArgsValid && BootDriveFound && BootDriveFilterExtension && BootDriveFilterExtension->DriveMounted && BootDriveFilterExtension->HeaderCryptoInfo) + { + BootLoaderFingerprintRequest *bootLoaderFingerprint = (BootLoaderFingerprintRequest *) irp->AssociatedIrp.SystemBuffer; + + /* compute the fingerprint again and check if it is the same as the one retrieved during boot */ + char *header = TCalloc (TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); + if (!header) + { + irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; + } + else + { + memcpy (bootLoaderFingerprint->Fingerprint, BootLoaderFingerprint, sizeof (BootLoaderFingerprint)); + ComputeBootLoaderFingerprint (BootDriveFilterExtension->LowerDeviceObject, header); + + burn (header, TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); + TCfree (header); + + if (0 == memcmp (bootLoaderFingerprint->Fingerprint, BootLoaderFingerprint, sizeof (BootLoaderFingerprint))) + { + irp->IoStatus.Information = sizeof (BootLoaderFingerprintRequest); + irp->IoStatus.Status = STATUS_SUCCESS; + } + else + { + /* fingerprint mismatch.*/ + irp->IoStatus.Status = STATUS_INVALID_IMAGE_HASH; + } + } + } + else + { + irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + } + } +} + +void GetBootEncryptionAlgorithmName (PIRP irp, PIO_STACK_LOCATION irpSp) +{ + if (ValidateIOBufferSize (irp, sizeof (GetBootEncryptionAlgorithmNameRequest), ValidateOutput)) + { + if (BootDriveFilterExtension && BootDriveFilterExtension->DriveMounted) + { + wchar_t BootEncryptionAlgorithmNameW[256]; + wchar_t BootPrfAlgorithmNameW[256]; + GetBootEncryptionAlgorithmNameRequest *request = (GetBootEncryptionAlgorithmNameRequest *) irp->AssociatedIrp.SystemBuffer; + EAGetName (BootEncryptionAlgorithmNameW, BootDriveFilterExtension->Queue.CryptoInfo->ea, 0); + HashGetName2 (BootPrfAlgorithmNameW, BootDriveFilterExtension->Queue.CryptoInfo->pkcs5); + + RtlStringCbPrintfA (request->BootEncryptionAlgorithmName, sizeof (request->BootEncryptionAlgorithmName), "%S", BootEncryptionAlgorithmNameW); + RtlStringCbPrintfA (request->BootPrfAlgorithmName, sizeof (request->BootPrfAlgorithmName), "%S", BootPrfAlgorithmNameW); + + irp->IoStatus.Information = sizeof (GetBootEncryptionAlgorithmNameRequest); + irp->IoStatus.Status = STATUS_SUCCESS; + } + else + { + irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + irp->IoStatus.Information = 0; + } + } +} + + +NTSTATUS GetSetupResult() +{ + return SetupResult; +} + + +BOOL IsBootDriveMounted () +{ + return BootDriveFilterExtension && BootDriveFilterExtension->DriveMounted; +} + + +BOOL IsBootEncryptionSetupInProgress () +{ + return SetupInProgress; +} + + +BOOL IsHiddenSystemRunning () +{ + return BootDriveFilterExtension && BootDriveFilterExtension->HiddenSystem; +} + + +DriveFilterExtension *GetBootDriveFilterExtension () +{ + return BootDriveFilterExtension; +} + + +CRYPTO_INFO *GetSystemDriveCryptoInfo () +{ + return BootDriveFilterExtension->Queue.CryptoInfo; +} + + +NTSTATUS AbortBootEncryptionSetup () +{ + if (!IoIsSystemThread (PsGetCurrentThread()) && !UserCanAccessDriveDevice()) + return STATUS_ACCESS_DENIED; + + if (EncryptionSetupThread) + { + EncryptionSetupThreadAbortRequested = TRUE; + + TCStopThread (EncryptionSetupThread, NULL); + EncryptionSetupThread = NULL; + } + + return STATUS_SUCCESS; +} + + +static VOID DecoySystemWipeThreadProc (PVOID threadArg) +{ + DriveFilterExtension *Extension = BootDriveFilterExtension; + + LARGE_INTEGER offset; + UINT64_STRUCT dataUnit; + ULONG wipeBlockSize = TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE; + + CRYPTO_INFO *wipeCryptoInfo = NULL; + byte *wipeBuffer = NULL; + byte *wipeRandBuffer = NULL; + byte wipeRandChars[TC_WIPE_RAND_CHAR_COUNT]; + int wipePass, wipePassCount; + int ea = Extension->Queue.CryptoInfo->ea; + + KIRQL irql; + NTSTATUS status; + + DecoySystemWipeResult = STATUS_UNSUCCESSFUL; + + wipeBuffer = TCalloc (TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); + if (!wipeBuffer) + { + DecoySystemWipeResult = STATUS_INSUFFICIENT_RESOURCES; + goto ret; + } + + wipeRandBuffer = TCalloc (TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); + if (!wipeRandBuffer) + { + DecoySystemWipeResult = STATUS_INSUFFICIENT_RESOURCES; + goto ret; + } + + wipeCryptoInfo = crypto_open(); + if (!wipeCryptoInfo) + { + DecoySystemWipeResult = STATUS_INSUFFICIENT_RESOURCES; + goto ret; + } + + wipeCryptoInfo->ea = ea; + wipeCryptoInfo->mode = Extension->Queue.CryptoInfo->mode; + + if (EAInit (ea, WipeDecoyRequest.WipeKey, wipeCryptoInfo->ks) != ERR_SUCCESS) + { + DecoySystemWipeResult = STATUS_INVALID_PARAMETER; + goto ret; + } + + memcpy (wipeCryptoInfo->k2, WipeDecoyRequest.WipeKey + EAGetKeySize (ea), EAGetKeySize (ea)); + + if (!EAInitMode (wipeCryptoInfo)) + { + DecoySystemWipeResult = STATUS_INVALID_PARAMETER; + goto err; + } + + EncryptDataUnits (wipeRandBuffer, &dataUnit, wipeBlockSize / ENCRYPTION_DATA_UNIT_SIZE, wipeCryptoInfo); + memcpy (wipeRandChars, wipeRandBuffer, sizeof (wipeRandChars)); + + burn (WipeDecoyRequest.WipeKey, sizeof (WipeDecoyRequest.WipeKey)); + + offset.QuadPart = Extension->ConfiguredEncryptedAreaStart; + + Dump ("Wiping decoy system: start offset = %I64d\n", offset.QuadPart); + + while (!DecoySystemWipeThreadAbortRequested) + { + if (offset.QuadPart + wipeBlockSize > Extension->ConfiguredEncryptedAreaEnd + 1) + wipeBlockSize = (ULONG) (Extension->ConfiguredEncryptedAreaEnd + 1 - offset.QuadPart); + + if (offset.QuadPart > Extension->ConfiguredEncryptedAreaEnd) + break; + + wipePassCount = GetWipePassCount (WipeDecoyRequest.WipeAlgorithm); + if (wipePassCount <= 0) + { + DecoySystemWipeResult = STATUS_INVALID_PARAMETER; + goto err; + } + + for (wipePass = 1; wipePass <= wipePassCount; ++wipePass) + { + if (!WipeBuffer (WipeDecoyRequest.WipeAlgorithm, wipeRandChars, wipePass, wipeBuffer, wipeBlockSize)) + { + dataUnit.Value = offset.QuadPart / ENCRYPTION_DATA_UNIT_SIZE; + EncryptDataUnits (wipeRandBuffer, &dataUnit, wipeBlockSize / ENCRYPTION_DATA_UNIT_SIZE, wipeCryptoInfo); + memcpy (wipeBuffer, wipeRandBuffer, wipeBlockSize); + } + + while (!NT_SUCCESS (EncryptedIoQueueHoldWhenIdle (&Extension->Queue, 500))) + { + if (DecoySystemWipeThreadAbortRequested) + goto abort; + } + + status = TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, wipeBuffer, offset, wipeBlockSize); + + if (!NT_SUCCESS (status)) + { + DecoySystemWipeResult = status; + goto err; + } + + EncryptedIoQueueResumeFromHold (&Extension->Queue); + } + + offset.QuadPart += wipeBlockSize; + + KeAcquireSpinLock (&DecoySystemWipeStatusSpinLock, &irql); + DecoySystemWipedAreaEnd = offset.QuadPart - 1; + KeReleaseSpinLock (&DecoySystemWipeStatusSpinLock, irql); + } + +abort: + DecoySystemWipeResult = STATUS_SUCCESS; +err: + + if (EncryptedIoQueueIsSuspended (&Extension->Queue)) + EncryptedIoQueueResumeFromHold (&Extension->Queue); + + Dump ("Wipe end: DecoySystemWipedAreaEnd=%I64d (%I64d)\n", DecoySystemWipedAreaEnd, DecoySystemWipedAreaEnd / 1024 / 1024); + +ret: + if (wipeCryptoInfo) + crypto_close (wipeCryptoInfo); + + if (wipeRandBuffer) + TCfree (wipeRandBuffer); + + if (wipeBuffer) + TCfree (wipeBuffer); + + DecoySystemWipeInProgress = FALSE; + PsTerminateSystemThread (DecoySystemWipeResult); +} + + +NTSTATUS StartDecoySystemWipe (PDEVICE_OBJECT DeviceObject, PIRP irp, PIO_STACK_LOCATION irpSp) +{ + NTSTATUS status; + WipeDecoySystemRequest *request; + + if (!UserCanAccessDriveDevice()) + return STATUS_ACCESS_DENIED; + + if (!IsHiddenSystemRunning() + || irpSp->Parameters.DeviceIoControl.InputBufferLength < sizeof (WipeDecoySystemRequest)) + return STATUS_INVALID_PARAMETER; + + if (DecoySystemWipeInProgress) + return STATUS_SUCCESS; + + if (DecoySystemWipeThread) + AbortDecoySystemWipe(); + + request = (WipeDecoySystemRequest *) irp->AssociatedIrp.SystemBuffer; + WipeDecoyRequest = *request; + + burn (request->WipeKey, sizeof (request->WipeKey)); + + DecoySystemWipeThreadAbortRequested = FALSE; + KeInitializeSpinLock (&DecoySystemWipeStatusSpinLock); + DecoySystemWipedAreaEnd = BootDriveFilterExtension->ConfiguredEncryptedAreaStart; + + DecoySystemWipeInProgress = TRUE; + status = TCStartThread (DecoySystemWipeThreadProc, DeviceObject, &DecoySystemWipeThread); + + if (!NT_SUCCESS (status)) + DecoySystemWipeInProgress = FALSE; + + return status; +} + + +BOOL IsDecoySystemWipeInProgress() +{ + return DecoySystemWipeInProgress; +} + + +void GetDecoySystemWipeStatus (PIRP irp, PIO_STACK_LOCATION irpSp) +{ + if (ValidateIOBufferSize (irp, sizeof (DecoySystemWipeStatus), ValidateOutput)) + { + DecoySystemWipeStatus *wipeStatus = (DecoySystemWipeStatus *) irp->AssociatedIrp.SystemBuffer; + + if (!IsHiddenSystemRunning()) + { + irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + irp->IoStatus.Information = 0; + } + else + { + wipeStatus->WipeInProgress = DecoySystemWipeInProgress; + wipeStatus->WipeAlgorithm = WipeDecoyRequest.WipeAlgorithm; + + if (DecoySystemWipeInProgress) + { + KIRQL irql; + KeAcquireSpinLock (&DecoySystemWipeStatusSpinLock, &irql); + wipeStatus->WipedAreaEnd = DecoySystemWipedAreaEnd; + KeReleaseSpinLock (&DecoySystemWipeStatusSpinLock, irql); + } + else + wipeStatus->WipedAreaEnd = DecoySystemWipedAreaEnd; + + irp->IoStatus.Information = sizeof (DecoySystemWipeStatus); + irp->IoStatus.Status = STATUS_SUCCESS; + } + } +} + + +NTSTATUS GetDecoySystemWipeResult() +{ + return DecoySystemWipeResult; +} + + +NTSTATUS AbortDecoySystemWipe () +{ + if (!IoIsSystemThread (PsGetCurrentThread()) && !UserCanAccessDriveDevice()) + return STATUS_ACCESS_DENIED; + + if (DecoySystemWipeThread) + { + DecoySystemWipeThreadAbortRequested = TRUE; + + TCStopThread (DecoySystemWipeThread, NULL); + DecoySystemWipeThread = NULL; + } + + return STATUS_SUCCESS; +} + + +uint64 GetBootDriveLength () +{ + return BootDriveLength.QuadPart; +} + + +NTSTATUS WriteBootDriveSector (PIRP irp, PIO_STACK_LOCATION irpSp) +{ + WriteBootDriveSectorRequest *request; + + if (!UserCanAccessDriveDevice()) + return STATUS_ACCESS_DENIED; + + if (!BootDriveFilterExtension + || irpSp->Parameters.DeviceIoControl.InputBufferLength < sizeof (WriteBootDriveSectorRequest)) + return STATUS_INVALID_PARAMETER; + + request = (WriteBootDriveSectorRequest *) irp->AssociatedIrp.SystemBuffer; + return TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, request->Data, request->Offset, sizeof (request->Data)); +} diff --git a/src/Driver/DriveFilter.h b/src/Driver/DriveFilter.h index 50dcabfd..e0c1bdff 100644 --- a/src/Driver/DriveFilter.h +++ b/src/Driver/DriveFilter.h @@ -1,90 +1,90 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_DRIVER_DRIVE_FILTER -#define TC_HEADER_DRIVER_DRIVE_FILTER - -#include "TCdefs.h" -#include "Boot/Windows/BootCommon.h" -#include "EncryptedIoQueue.h" - -typedef struct _DriveFilterExtension -{ - BOOL bRootDevice; - BOOL IsVolumeDevice; - BOOL IsDriveFilterDevice; - BOOL IsVolumeFilterDevice; - uint64 MagicNumber; - - PDEVICE_OBJECT DeviceObject; - PDEVICE_OBJECT LowerDeviceObject; - PDEVICE_OBJECT Pdo; - - ULONG SystemStorageDeviceNumber; - BOOL SystemStorageDeviceNumberValid; - - int64 ConfiguredEncryptedAreaStart; - int64 ConfiguredEncryptedAreaEnd; - - uint32 VolumeHeaderSaltCrc32; - EncryptedIoQueue Queue; - - BOOL BootDrive; - BOOL VolumeHeaderPresent; - BOOL DriveMounted; - - KEVENT MountWorkItemCompletedEvent; - - CRYPTO_INFO *HeaderCryptoInfo; - BOOL HiddenSystem; - -} DriveFilterExtension; - -#define TC_BOOT_DRIVE_FILTER_EXTENSION_MAGIC_NUMBER 0x5645524142455854 - -extern BOOL BootArgsValid; -extern BootArguments BootArgs; -extern PKTHREAD EncryptionSetupThread; -extern PKTHREAD DecoySystemWipeThread; - -NTSTATUS AbortBootEncryptionSetup (); -NTSTATUS DriveFilterAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo); -NTSTATUS DriveFilterDispatchIrp (PDEVICE_OBJECT DeviceObject, PIRP Irp); -void GetBootDriveVolumeProperties (PIRP irp, PIO_STACK_LOCATION irpSp); -void GetBootEncryptionAlgorithmName (PIRP irp, PIO_STACK_LOCATION irpSp); -void GetBootEncryptionStatus (PIRP irp, PIO_STACK_LOCATION irpSp); -void GetBootLoaderVersion (PIRP irp, PIO_STACK_LOCATION irpSp); -void GetBootLoaderFingerprint (PIRP irp, PIO_STACK_LOCATION irpSp); -NTSTATUS GetSetupResult (); -DriveFilterExtension *GetBootDriveFilterExtension (); -CRYPTO_INFO *GetSystemDriveCryptoInfo (); -BOOL IsBootDriveMounted (); -BOOL IsBootEncryptionSetupInProgress (); -BOOL IsHiddenSystemRunning (); -NTSTATUS LoadBootArguments (); -static NTSTATUS SaveDriveVolumeHeader (DriveFilterExtension *Extension); -NTSTATUS StartBootEncryptionSetup (PDEVICE_OBJECT DeviceObject, PIRP irp, PIO_STACK_LOCATION irpSp); -void ReopenBootVolumeHeader (PIRP irp, PIO_STACK_LOCATION irpSp); -NTSTATUS StartDecoySystemWipe (PDEVICE_OBJECT DeviceObject, PIRP irp, PIO_STACK_LOCATION irpSp); -void StartLegacyHibernationDriverFilter (); -NTSTATUS AbortDecoySystemWipe (); -BOOL IsDecoySystemWipeInProgress(); -NTSTATUS GetDecoySystemWipeResult(); -void GetDecoySystemWipeStatus (PIRP irp, PIO_STACK_LOCATION irpSp); -uint64 GetBootDriveLength (); -NTSTATUS WriteBootDriveSector (PIRP irp, PIO_STACK_LOCATION irpSp); - -#define TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE (1536 * 1024) -#define TC_ENCRYPTION_SETUP_HEADER_UPDATE_THRESHOLD (64 * 1024 * 1024) -#define TC_HIBERNATION_WRITE_BUFFER_SIZE (128 * 1024) - -#endif // TC_HEADER_DRIVER_DRIVE_FILTER +/* + 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. +*/ + +#ifndef TC_HEADER_DRIVER_DRIVE_FILTER +#define TC_HEADER_DRIVER_DRIVE_FILTER + +#include "TCdefs.h" +#include "Boot/Windows/BootCommon.h" +#include "EncryptedIoQueue.h" + +typedef struct _DriveFilterExtension +{ + BOOL bRootDevice; + BOOL IsVolumeDevice; + BOOL IsDriveFilterDevice; + BOOL IsVolumeFilterDevice; + uint64 MagicNumber; + + PDEVICE_OBJECT DeviceObject; + PDEVICE_OBJECT LowerDeviceObject; + PDEVICE_OBJECT Pdo; + + ULONG SystemStorageDeviceNumber; + BOOL SystemStorageDeviceNumberValid; + + int64 ConfiguredEncryptedAreaStart; + int64 ConfiguredEncryptedAreaEnd; + + uint32 VolumeHeaderSaltCrc32; + EncryptedIoQueue Queue; + + BOOL BootDrive; + BOOL VolumeHeaderPresent; + BOOL DriveMounted; + + KEVENT MountWorkItemCompletedEvent; + + CRYPTO_INFO *HeaderCryptoInfo; + BOOL HiddenSystem; + +} DriveFilterExtension; + +#define TC_BOOT_DRIVE_FILTER_EXTENSION_MAGIC_NUMBER 0x5645524142455854 + +extern BOOL BootArgsValid; +extern BootArguments BootArgs; +extern PKTHREAD EncryptionSetupThread; +extern PKTHREAD DecoySystemWipeThread; + +NTSTATUS AbortBootEncryptionSetup (); +NTSTATUS DriveFilterAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo); +NTSTATUS DriveFilterDispatchIrp (PDEVICE_OBJECT DeviceObject, PIRP Irp); +void GetBootDriveVolumeProperties (PIRP irp, PIO_STACK_LOCATION irpSp); +void GetBootEncryptionAlgorithmName (PIRP irp, PIO_STACK_LOCATION irpSp); +void GetBootEncryptionStatus (PIRP irp, PIO_STACK_LOCATION irpSp); +void GetBootLoaderVersion (PIRP irp, PIO_STACK_LOCATION irpSp); +void GetBootLoaderFingerprint (PIRP irp, PIO_STACK_LOCATION irpSp); +NTSTATUS GetSetupResult (); +DriveFilterExtension *GetBootDriveFilterExtension (); +CRYPTO_INFO *GetSystemDriveCryptoInfo (); +BOOL IsBootDriveMounted (); +BOOL IsBootEncryptionSetupInProgress (); +BOOL IsHiddenSystemRunning (); +NTSTATUS LoadBootArguments (); +static NTSTATUS SaveDriveVolumeHeader (DriveFilterExtension *Extension); +NTSTATUS StartBootEncryptionSetup (PDEVICE_OBJECT DeviceObject, PIRP irp, PIO_STACK_LOCATION irpSp); +void ReopenBootVolumeHeader (PIRP irp, PIO_STACK_LOCATION irpSp); +NTSTATUS StartDecoySystemWipe (PDEVICE_OBJECT DeviceObject, PIRP irp, PIO_STACK_LOCATION irpSp); +void StartLegacyHibernationDriverFilter (); +NTSTATUS AbortDecoySystemWipe (); +BOOL IsDecoySystemWipeInProgress(); +NTSTATUS GetDecoySystemWipeResult(); +void GetDecoySystemWipeStatus (PIRP irp, PIO_STACK_LOCATION irpSp); +uint64 GetBootDriveLength (); +NTSTATUS WriteBootDriveSector (PIRP irp, PIO_STACK_LOCATION irpSp); + +#define TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE (1536 * 1024) +#define TC_ENCRYPTION_SETUP_HEADER_UPDATE_THRESHOLD (64 * 1024 * 1024) +#define TC_HIBERNATION_WRITE_BUFFER_SIZE (128 * 1024) + +#endif // TC_HEADER_DRIVER_DRIVE_FILTER diff --git a/src/Driver/Driver.rc b/src/Driver/Driver.rc index d9591d51..51030c5c 100644 --- a/src/Driver/Driver.rc +++ b/src/Driver/Driver.rc @@ -1,101 +1,101 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,17,22,0 - PRODUCTVERSION 1,17,22,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x3L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "IDRIX" - VALUE "FileDescription", "VeraCrypt Driver" - VALUE "FileVersion", "1.17" - VALUE "LegalTrademarks", "VeraCrypt" - VALUE "OriginalFilename", "veracrypt.sys" - VALUE "ProductName", "VeraCrypt" - VALUE "ProductVersion", "1.17" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,17,22,0 + PRODUCTVERSION 1,17,22,0 + FILEFLAGSMASK 0x17L +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x3L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "IDRIX" + VALUE "FileDescription", "VeraCrypt Driver" + VALUE "FileVersion", "1.17" + VALUE "LegalTrademarks", "VeraCrypt" + VALUE "OriginalFilename", "veracrypt.sys" + VALUE "ProductName", "VeraCrypt" + VALUE "ProductVersion", "1.17" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/src/Driver/Driver.vcproj b/src/Driver/Driver.vcproj index 8d28d753..4c474c36 100644 --- a/src/Driver/Driver.vcproj +++ b/src/Driver/Driver.vcproj @@ -1,398 +1,398 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Driver/DumpFilter.c b/src/Driver/DumpFilter.c index 16d1d37c..d67b1654 100644 --- a/src/Driver/DumpFilter.c +++ b/src/Driver/DumpFilter.c @@ -1,248 +1,248 @@ -/* - 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 "DumpFilter.h" -#include "DriveFilter.h" -#include "Ntdriver.h" -#include "Tests.h" - -static DriveFilterExtension *BootDriveFilterExtension = NULL; -static LARGE_INTEGER DumpPartitionOffset; -static byte *WriteFilterBuffer = NULL; -static SIZE_T WriteFilterBufferSize; - - -NTSTATUS DumpFilterEntry (PFILTER_EXTENSION filterExtension, PFILTER_INITIALIZATION_DATA filterInitData) -{ - GetSystemDriveDumpConfigRequest dumpConfig; - PHYSICAL_ADDRESS highestAcceptableWriteBufferAddr; - STORAGE_DEVICE_NUMBER storageDeviceNumber; - PARTITION_INFORMATION partitionInfo; - LONG version; - NTSTATUS status; - - Dump ("DumpFilterEntry type=%d\n", filterExtension->DumpType); - - filterInitData->MajorVersion = DUMP_FILTER_MAJOR_VERSION; - filterInitData->MinorVersion = DUMP_FILTER_MINOR_VERSION; - filterInitData->Flags |= DUMP_FILTER_CRITICAL; - - // Check driver version of the main device - status = TCDeviceIoControl (NT_ROOT_PREFIX, TC_IOCTL_GET_DRIVER_VERSION, NULL, 0, &version, sizeof (version)); - if (!NT_SUCCESS (status)) - goto err; - - if (version != VERSION_NUM) - { - status = STATUS_INVALID_PARAMETER; - goto err; - } - - // Get dump configuration from the main device - status = TCDeviceIoControl (NT_ROOT_PREFIX, TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG, NULL, 0, &dumpConfig, sizeof (dumpConfig)); - if (!NT_SUCCESS (status)) - goto err; - - BootDriveFilterExtension = dumpConfig.BootDriveFilterExtension; - - if (BootDriveFilterExtension->MagicNumber != TC_BOOT_DRIVE_FILTER_EXTENSION_MAGIC_NUMBER) - { - status = STATUS_CRC_ERROR; - goto err; - } - - // KeSaveFloatingPointState() may generate a bug check during crash dump -#if !defined (_WIN64) - if (filterExtension->DumpType == DumpTypeCrashdump) - dumpConfig.HwEncryptionEnabled = FALSE; -#endif - - EnableHwEncryption (dumpConfig.HwEncryptionEnabled); - - if (!AutoTestAlgorithms()) - { - status = STATUS_INVALID_PARAMETER; - goto err; - } - - // Check dump volume is located on the system drive - status = SendDeviceIoControlRequest (filterExtension->DeviceObject, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &storageDeviceNumber, sizeof (storageDeviceNumber)); - if (!NT_SUCCESS (status)) - goto err; - - if (!BootDriveFilterExtension->SystemStorageDeviceNumberValid) - { - status = STATUS_INVALID_PARAMETER; - goto err; - } - - if (storageDeviceNumber.DeviceNumber != BootDriveFilterExtension->SystemStorageDeviceNumber) - { - status = STATUS_ACCESS_DENIED; - goto err; - } - - // Check dump volume is located within the scope of system encryption - status = SendDeviceIoControlRequest (filterExtension->DeviceObject, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &partitionInfo, sizeof (partitionInfo)); - if (!NT_SUCCESS (status)) - goto err; - - DumpPartitionOffset = partitionInfo.StartingOffset; - - if (DumpPartitionOffset.QuadPart < BootDriveFilterExtension->ConfiguredEncryptedAreaStart - || DumpPartitionOffset.QuadPart > BootDriveFilterExtension->ConfiguredEncryptedAreaEnd) - { - status = STATUS_ACCESS_DENIED; - goto err; - } - - // Allocate buffer for encryption - if (filterInitData->MaxPagesPerWrite == 0) - { - status = STATUS_INVALID_PARAMETER; - goto err; - } - - WriteFilterBufferSize = filterInitData->MaxPagesPerWrite * PAGE_SIZE; - -#ifdef _WIN64 - highestAcceptableWriteBufferAddr.QuadPart = 0x7FFffffFFFFLL; -#else - highestAcceptableWriteBufferAddr.QuadPart = 0xffffFFFFLL; -#endif - - WriteFilterBuffer = MmAllocateContiguousMemory (WriteFilterBufferSize, highestAcceptableWriteBufferAddr); - if (!WriteFilterBuffer) - { - status = STATUS_INSUFFICIENT_RESOURCES; - goto err; - } - - filterInitData->DumpStart = DumpFilterStart; - filterInitData->DumpWrite = DumpFilterWrite; - filterInitData->DumpFinish = DumpFilterFinish; - filterInitData->DumpUnload = DumpFilterUnload; - - Dump ("Dump filter loaded type=%d\n", filterExtension->DumpType); - return STATUS_SUCCESS; - -err: - Dump ("DumpFilterEntry error %x\n", status); - return status; -} - - -static NTSTATUS DumpFilterStart (PFILTER_EXTENSION filterExtension) -{ - Dump ("DumpFilterStart type=%d\n", filterExtension->DumpType); - - if (BootDriveFilterExtension->MagicNumber != TC_BOOT_DRIVE_FILTER_EXTENSION_MAGIC_NUMBER) - TC_BUG_CHECK (STATUS_CRC_ERROR); - - return BootDriveFilterExtension->DriveMounted ? STATUS_SUCCESS : STATUS_UNSUCCESSFUL; -} - - -static NTSTATUS DumpFilterWrite (PFILTER_EXTENSION filterExtension, PLARGE_INTEGER diskWriteOffset, PMDL writeMdl) -{ - ULONG dataLength = MmGetMdlByteCount (writeMdl); - uint64 offset = DumpPartitionOffset.QuadPart + diskWriteOffset->QuadPart; - uint64 intersectStart; - uint32 intersectLength; - PVOID writeBuffer; - CSHORT origMdlFlags; - - if (BootDriveFilterExtension->MagicNumber != TC_BOOT_DRIVE_FILTER_EXTENSION_MAGIC_NUMBER) - TC_BUG_CHECK (STATUS_CRC_ERROR); - - if (BootDriveFilterExtension->Queue.EncryptedAreaEndUpdatePending) // Hibernation should always abort the setup thread - TC_BUG_CHECK (STATUS_INVALID_PARAMETER); - - if (BootDriveFilterExtension->Queue.EncryptedAreaStart == -1 || BootDriveFilterExtension->Queue.EncryptedAreaEnd == -1) - return STATUS_SUCCESS; - - if (dataLength > WriteFilterBufferSize) - TC_BUG_CHECK (STATUS_BUFFER_OVERFLOW); // Bug check is required as returning an error does not prevent data from being written to disk - - if ((dataLength & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0) - TC_BUG_CHECK (STATUS_INVALID_PARAMETER); - - if ((offset & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0) - TC_BUG_CHECK (STATUS_INVALID_PARAMETER); - - writeBuffer = MmGetSystemAddressForMdlSafe (writeMdl, HighPagePriority); - if (!writeBuffer) - TC_BUG_CHECK (STATUS_INSUFFICIENT_RESOURCES); - - memcpy (WriteFilterBuffer, writeBuffer, dataLength); - - GetIntersection (offset, - dataLength, - BootDriveFilterExtension->Queue.EncryptedAreaStart, - BootDriveFilterExtension->Queue.EncryptedAreaEnd, - &intersectStart, - &intersectLength); - - if (intersectLength > 0) - { - UINT64_STRUCT dataUnit; - dataUnit.Value = intersectStart / ENCRYPTION_DATA_UNIT_SIZE; - - if (BootDriveFilterExtension->Queue.RemapEncryptedArea) - { - diskWriteOffset->QuadPart += BootDriveFilterExtension->Queue.RemappedAreaOffset; - dataUnit.Value += BootDriveFilterExtension->Queue.RemappedAreaDataUnitOffset; - } - - EncryptDataUnitsCurrentThread (WriteFilterBuffer + (intersectStart - offset), - &dataUnit, - intersectLength / ENCRYPTION_DATA_UNIT_SIZE, - BootDriveFilterExtension->Queue.CryptoInfo); - } - - origMdlFlags = writeMdl->MdlFlags; - - MmInitializeMdl (writeMdl, WriteFilterBuffer, dataLength); - MmBuildMdlForNonPagedPool (writeMdl); - - // Instead of using MmGetSystemAddressForMdlSafe(), some buggy custom storage drivers may directly test MDL_MAPPED_TO_SYSTEM_VA flag, - // disregarding the fact that other MDL flags may be set by the system or a dump filter (e.g. MDL_SOURCE_IS_NONPAGED_POOL flag only). - // Therefore, to work around this issue, the original flags will be restored even if they do not match the new MDL. - // MS BitLocker also uses this hack/workaround (it should be safe to use until the MDL structure is changed). - - writeMdl->MdlFlags = origMdlFlags; - - return STATUS_SUCCESS; -} - - -static NTSTATUS DumpFilterFinish (PFILTER_EXTENSION filterExtension) -{ - Dump ("DumpFilterFinish type=%d\n", filterExtension->DumpType); - - return STATUS_SUCCESS; -} - - -static NTSTATUS DumpFilterUnload (PFILTER_EXTENSION filterExtension) -{ - Dump ("DumpFilterUnload type=%d\n", filterExtension->DumpType); - - if (WriteFilterBuffer) - { - memset (WriteFilterBuffer, 0, WriteFilterBufferSize); - MmFreeContiguousMemory (WriteFilterBuffer); - WriteFilterBuffer = NULL; - } - - return STATUS_SUCCESS; -} +/* + 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 "DumpFilter.h" +#include "DriveFilter.h" +#include "Ntdriver.h" +#include "Tests.h" + +static DriveFilterExtension *BootDriveFilterExtension = NULL; +static LARGE_INTEGER DumpPartitionOffset; +static byte *WriteFilterBuffer = NULL; +static SIZE_T WriteFilterBufferSize; + + +NTSTATUS DumpFilterEntry (PFILTER_EXTENSION filterExtension, PFILTER_INITIALIZATION_DATA filterInitData) +{ + GetSystemDriveDumpConfigRequest dumpConfig; + PHYSICAL_ADDRESS highestAcceptableWriteBufferAddr; + STORAGE_DEVICE_NUMBER storageDeviceNumber; + PARTITION_INFORMATION partitionInfo; + LONG version; + NTSTATUS status; + + Dump ("DumpFilterEntry type=%d\n", filterExtension->DumpType); + + filterInitData->MajorVersion = DUMP_FILTER_MAJOR_VERSION; + filterInitData->MinorVersion = DUMP_FILTER_MINOR_VERSION; + filterInitData->Flags |= DUMP_FILTER_CRITICAL; + + // Check driver version of the main device + status = TCDeviceIoControl (NT_ROOT_PREFIX, TC_IOCTL_GET_DRIVER_VERSION, NULL, 0, &version, sizeof (version)); + if (!NT_SUCCESS (status)) + goto err; + + if (version != VERSION_NUM) + { + status = STATUS_INVALID_PARAMETER; + goto err; + } + + // Get dump configuration from the main device + status = TCDeviceIoControl (NT_ROOT_PREFIX, TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG, NULL, 0, &dumpConfig, sizeof (dumpConfig)); + if (!NT_SUCCESS (status)) + goto err; + + BootDriveFilterExtension = dumpConfig.BootDriveFilterExtension; + + if (BootDriveFilterExtension->MagicNumber != TC_BOOT_DRIVE_FILTER_EXTENSION_MAGIC_NUMBER) + { + status = STATUS_CRC_ERROR; + goto err; + } + + // KeSaveFloatingPointState() may generate a bug check during crash dump +#if !defined (_WIN64) + if (filterExtension->DumpType == DumpTypeCrashdump) + dumpConfig.HwEncryptionEnabled = FALSE; +#endif + + EnableHwEncryption (dumpConfig.HwEncryptionEnabled); + + if (!AutoTestAlgorithms()) + { + status = STATUS_INVALID_PARAMETER; + goto err; + } + + // Check dump volume is located on the system drive + status = SendDeviceIoControlRequest (filterExtension->DeviceObject, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &storageDeviceNumber, sizeof (storageDeviceNumber)); + if (!NT_SUCCESS (status)) + goto err; + + if (!BootDriveFilterExtension->SystemStorageDeviceNumberValid) + { + status = STATUS_INVALID_PARAMETER; + goto err; + } + + if (storageDeviceNumber.DeviceNumber != BootDriveFilterExtension->SystemStorageDeviceNumber) + { + status = STATUS_ACCESS_DENIED; + goto err; + } + + // Check dump volume is located within the scope of system encryption + status = SendDeviceIoControlRequest (filterExtension->DeviceObject, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &partitionInfo, sizeof (partitionInfo)); + if (!NT_SUCCESS (status)) + goto err; + + DumpPartitionOffset = partitionInfo.StartingOffset; + + if (DumpPartitionOffset.QuadPart < BootDriveFilterExtension->ConfiguredEncryptedAreaStart + || DumpPartitionOffset.QuadPart > BootDriveFilterExtension->ConfiguredEncryptedAreaEnd) + { + status = STATUS_ACCESS_DENIED; + goto err; + } + + // Allocate buffer for encryption + if (filterInitData->MaxPagesPerWrite == 0) + { + status = STATUS_INVALID_PARAMETER; + goto err; + } + + WriteFilterBufferSize = filterInitData->MaxPagesPerWrite * PAGE_SIZE; + +#ifdef _WIN64 + highestAcceptableWriteBufferAddr.QuadPart = 0x7FFffffFFFFLL; +#else + highestAcceptableWriteBufferAddr.QuadPart = 0xffffFFFFLL; +#endif + + WriteFilterBuffer = MmAllocateContiguousMemory (WriteFilterBufferSize, highestAcceptableWriteBufferAddr); + if (!WriteFilterBuffer) + { + status = STATUS_INSUFFICIENT_RESOURCES; + goto err; + } + + filterInitData->DumpStart = DumpFilterStart; + filterInitData->DumpWrite = DumpFilterWrite; + filterInitData->DumpFinish = DumpFilterFinish; + filterInitData->DumpUnload = DumpFilterUnload; + + Dump ("Dump filter loaded type=%d\n", filterExtension->DumpType); + return STATUS_SUCCESS; + +err: + Dump ("DumpFilterEntry error %x\n", status); + return status; +} + + +static NTSTATUS DumpFilterStart (PFILTER_EXTENSION filterExtension) +{ + Dump ("DumpFilterStart type=%d\n", filterExtension->DumpType); + + if (BootDriveFilterExtension->MagicNumber != TC_BOOT_DRIVE_FILTER_EXTENSION_MAGIC_NUMBER) + TC_BUG_CHECK (STATUS_CRC_ERROR); + + return BootDriveFilterExtension->DriveMounted ? STATUS_SUCCESS : STATUS_UNSUCCESSFUL; +} + + +static NTSTATUS DumpFilterWrite (PFILTER_EXTENSION filterExtension, PLARGE_INTEGER diskWriteOffset, PMDL writeMdl) +{ + ULONG dataLength = MmGetMdlByteCount (writeMdl); + uint64 offset = DumpPartitionOffset.QuadPart + diskWriteOffset->QuadPart; + uint64 intersectStart; + uint32 intersectLength; + PVOID writeBuffer; + CSHORT origMdlFlags; + + if (BootDriveFilterExtension->MagicNumber != TC_BOOT_DRIVE_FILTER_EXTENSION_MAGIC_NUMBER) + TC_BUG_CHECK (STATUS_CRC_ERROR); + + if (BootDriveFilterExtension->Queue.EncryptedAreaEndUpdatePending) // Hibernation should always abort the setup thread + TC_BUG_CHECK (STATUS_INVALID_PARAMETER); + + if (BootDriveFilterExtension->Queue.EncryptedAreaStart == -1 || BootDriveFilterExtension->Queue.EncryptedAreaEnd == -1) + return STATUS_SUCCESS; + + if (dataLength > WriteFilterBufferSize) + TC_BUG_CHECK (STATUS_BUFFER_OVERFLOW); // Bug check is required as returning an error does not prevent data from being written to disk + + if ((dataLength & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0) + TC_BUG_CHECK (STATUS_INVALID_PARAMETER); + + if ((offset & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0) + TC_BUG_CHECK (STATUS_INVALID_PARAMETER); + + writeBuffer = MmGetSystemAddressForMdlSafe (writeMdl, HighPagePriority); + if (!writeBuffer) + TC_BUG_CHECK (STATUS_INSUFFICIENT_RESOURCES); + + memcpy (WriteFilterBuffer, writeBuffer, dataLength); + + GetIntersection (offset, + dataLength, + BootDriveFilterExtension->Queue.EncryptedAreaStart, + BootDriveFilterExtension->Queue.EncryptedAreaEnd, + &intersectStart, + &intersectLength); + + if (intersectLength > 0) + { + UINT64_STRUCT dataUnit; + dataUnit.Value = intersectStart / ENCRYPTION_DATA_UNIT_SIZE; + + if (BootDriveFilterExtension->Queue.RemapEncryptedArea) + { + diskWriteOffset->QuadPart += BootDriveFilterExtension->Queue.RemappedAreaOffset; + dataUnit.Value += BootDriveFilterExtension->Queue.RemappedAreaDataUnitOffset; + } + + EncryptDataUnitsCurrentThread (WriteFilterBuffer + (intersectStart - offset), + &dataUnit, + intersectLength / ENCRYPTION_DATA_UNIT_SIZE, + BootDriveFilterExtension->Queue.CryptoInfo); + } + + origMdlFlags = writeMdl->MdlFlags; + + MmInitializeMdl (writeMdl, WriteFilterBuffer, dataLength); + MmBuildMdlForNonPagedPool (writeMdl); + + // Instead of using MmGetSystemAddressForMdlSafe(), some buggy custom storage drivers may directly test MDL_MAPPED_TO_SYSTEM_VA flag, + // disregarding the fact that other MDL flags may be set by the system or a dump filter (e.g. MDL_SOURCE_IS_NONPAGED_POOL flag only). + // Therefore, to work around this issue, the original flags will be restored even if they do not match the new MDL. + // MS BitLocker also uses this hack/workaround (it should be safe to use until the MDL structure is changed). + + writeMdl->MdlFlags = origMdlFlags; + + return STATUS_SUCCESS; +} + + +static NTSTATUS DumpFilterFinish (PFILTER_EXTENSION filterExtension) +{ + Dump ("DumpFilterFinish type=%d\n", filterExtension->DumpType); + + return STATUS_SUCCESS; +} + + +static NTSTATUS DumpFilterUnload (PFILTER_EXTENSION filterExtension) +{ + Dump ("DumpFilterUnload type=%d\n", filterExtension->DumpType); + + if (WriteFilterBuffer) + { + memset (WriteFilterBuffer, 0, WriteFilterBufferSize); + MmFreeContiguousMemory (WriteFilterBuffer); + WriteFilterBuffer = NULL; + } + + return STATUS_SUCCESS; +} diff --git a/src/Driver/DumpFilter.h b/src/Driver/DumpFilter.h index f288107e..ea6599a5 100644 --- a/src/Driver/DumpFilter.h +++ b/src/Driver/DumpFilter.h @@ -1,25 +1,25 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_DRIVER_DUMP_FILTER -#define TC_HEADER_DRIVER_DUMP_FILTER - -#include "Tcdefs.h" -#include - -NTSTATUS DumpFilterEntry (PFILTER_EXTENSION filterExtension, PFILTER_INITIALIZATION_DATA filterInitData); -static NTSTATUS DumpFilterStart (PFILTER_EXTENSION filterExtension); -static NTSTATUS DumpFilterWrite (PFILTER_EXTENSION filterExtension, PLARGE_INTEGER diskWriteOffset, PMDL writeMdl); -static NTSTATUS DumpFilterFinish (PFILTER_EXTENSION filterExtension); -static NTSTATUS DumpFilterUnload (PFILTER_EXTENSION filterExtension); - -#endif // TC_HEADER_DRIVER_DUMP_FILTER +/* + 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. +*/ + +#ifndef TC_HEADER_DRIVER_DUMP_FILTER +#define TC_HEADER_DRIVER_DUMP_FILTER + +#include "Tcdefs.h" +#include + +NTSTATUS DumpFilterEntry (PFILTER_EXTENSION filterExtension, PFILTER_INITIALIZATION_DATA filterInitData); +static NTSTATUS DumpFilterStart (PFILTER_EXTENSION filterExtension); +static NTSTATUS DumpFilterWrite (PFILTER_EXTENSION filterExtension, PLARGE_INTEGER diskWriteOffset, PMDL writeMdl); +static NTSTATUS DumpFilterFinish (PFILTER_EXTENSION filterExtension); +static NTSTATUS DumpFilterUnload (PFILTER_EXTENSION filterExtension); + +#endif // TC_HEADER_DRIVER_DUMP_FILTER diff --git a/src/Driver/EncryptedIoQueue.c b/src/Driver/EncryptedIoQueue.c index 1f57ad5c..637f8504 100644 --- a/src/Driver/EncryptedIoQueue.c +++ b/src/Driver/EncryptedIoQueue.c @@ -1,1049 +1,1049 @@ -/* - 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 "TCdefs.h" -#include "Apidrvr.h" -#include "Ntdriver.h" -#include "DriveFilter.h" -#include "EncryptedIoQueue.h" -#include "EncryptionThreadPool.h" -#include "Volumes.h" -#include - - -static void AcquireBufferPoolMutex (EncryptedIoQueue *queue) -{ - NTSTATUS status; - - status = KeWaitForMutexObject (&queue->BufferPoolMutex, Executive, KernelMode, FALSE, NULL); - if (!NT_SUCCESS (status)) - TC_BUG_CHECK (status); -} - - -static void ReleaseBufferPoolMutex (EncryptedIoQueue *queue) -{ - KeReleaseMutex (&queue->BufferPoolMutex, FALSE); -} - - -static void *GetPoolBuffer (EncryptedIoQueue *queue, ULONG requestedSize) -{ - EncryptedIoQueueBuffer *buffer; - void *bufferAddress = NULL; - BOOL requestedSizePresentInPool = FALSE; - - while (TRUE) - { - AcquireBufferPoolMutex (queue); - - for (buffer = queue->FirstPoolBuffer; ; buffer = buffer->NextBuffer) - { - if (buffer && buffer->Size == requestedSize) - { - requestedSizePresentInPool = TRUE; - - if (!buffer->InUse) - { - // Reuse a free buffer - buffer->InUse = TRUE; - bufferAddress = buffer->Address; - break; - } - } - - if (!buffer || !buffer->NextBuffer) - { - EncryptedIoQueueBuffer *newBuffer; - - if (requestedSizePresentInPool && !queue->StartPending) - break; - - // Allocate a new buffer - newBuffer = TCalloc (sizeof (EncryptedIoQueueBuffer)); - if (!newBuffer) - { - bufferAddress = NULL; - break; - } - - bufferAddress = TCalloc (requestedSize); - if (bufferAddress) - { - newBuffer->NextBuffer = NULL; - newBuffer->Address = bufferAddress; - newBuffer->Size = requestedSize; - newBuffer->InUse = TRUE; - - if (!buffer) - queue->FirstPoolBuffer = newBuffer; - else - buffer->NextBuffer = newBuffer; - } - else - TCfree (newBuffer); - - break; - } - } - - ReleaseBufferPoolMutex (queue); - - if (bufferAddress || !requestedSizePresentInPool || queue->StartPending) - break; - - KeWaitForSingleObject (&queue->PoolBufferFreeEvent, Executive, KernelMode, FALSE, NULL); - } - - return bufferAddress; -} - - -static void ReleasePoolBuffer (EncryptedIoQueue *queue, void *address) -{ - EncryptedIoQueueBuffer *buffer; - AcquireBufferPoolMutex (queue); - - for (buffer = queue->FirstPoolBuffer; buffer != NULL; buffer = buffer->NextBuffer) - { - if (buffer->Address == address) - { - ASSERT (buffer->InUse); - - buffer->InUse = FALSE; - break; - } - } - - ReleaseBufferPoolMutex (queue); - KeSetEvent (&queue->PoolBufferFreeEvent, IO_DISK_INCREMENT, FALSE); -} - - -static void FreePoolBuffers (EncryptedIoQueue *queue) -{ - EncryptedIoQueueBuffer *buffer; - AcquireBufferPoolMutex (queue); - - for (buffer = queue->FirstPoolBuffer; buffer != NULL; ) - { - EncryptedIoQueueBuffer *nextBuffer = buffer->NextBuffer; - - ASSERT (!buffer->InUse || queue->StartPending); - - TCfree (buffer->Address); - TCfree (buffer); - - buffer = nextBuffer; - } - - queue->FirstPoolBuffer = NULL; - ReleaseBufferPoolMutex (queue); -} - - -static void DecrementOutstandingIoCount (EncryptedIoQueue *queue) -{ - if (InterlockedDecrement (&queue->OutstandingIoCount) == 0 && (queue->SuspendPending || queue->StopPending)) - KeSetEvent (&queue->NoOutstandingIoEvent, IO_DISK_INCREMENT, FALSE); -} - - -static void OnItemCompleted (EncryptedIoQueueItem *item, BOOL freeItem) -{ - DecrementOutstandingIoCount (item->Queue); - IoReleaseRemoveLock (&item->Queue->RemoveLock, item->OriginalIrp); - - if (NT_SUCCESS (item->Status)) - { - if (item->Write) - item->Queue->TotalBytesWritten += item->OriginalLength; - else - item->Queue->TotalBytesRead += item->OriginalLength; - } - - if (freeItem) - ReleasePoolBuffer (item->Queue, item); -} - - -static NTSTATUS CompleteOriginalIrp (EncryptedIoQueueItem *item, NTSTATUS status, ULONG_PTR information) -{ -#ifdef TC_TRACE_IO_QUEUE - Dump ("< %I64d [%I64d] %c status=%x info=%I64d\n", item->OriginalIrpOffset, GetElapsedTime (&item->Queue->LastPerformanceCounter), item->Write ? 'W' : 'R', status, (int64) information); -#endif - - TCCompleteDiskIrp (item->OriginalIrp, status, information); - - item->Status = status; - OnItemCompleted (item, TRUE); - - return status; -} - - -static void AcquireFragmentBuffer (EncryptedIoQueue *queue, byte *buffer) -{ - NTSTATUS status = STATUS_INVALID_PARAMETER; - - if (buffer == queue->FragmentBufferA) - { - status = KeWaitForSingleObject (&queue->FragmentBufferAFreeEvent, Executive, KernelMode, FALSE, NULL); - } - else if (buffer == queue->FragmentBufferB) - { - status = KeWaitForSingleObject (&queue->FragmentBufferBFreeEvent, Executive, KernelMode, FALSE, NULL); - } - - if (!NT_SUCCESS (status)) - TC_BUG_CHECK (status); -} - - -static void ReleaseFragmentBuffer (EncryptedIoQueue *queue, byte *buffer) -{ - if (buffer == queue->FragmentBufferA) - { - KeSetEvent (&queue->FragmentBufferAFreeEvent, IO_DISK_INCREMENT, FALSE); - } - else if (buffer == queue->FragmentBufferB) - { - KeSetEvent (&queue->FragmentBufferBFreeEvent, IO_DISK_INCREMENT, FALSE); - } - else - { - TC_BUG_CHECK (STATUS_INVALID_PARAMETER); - } -} - - -static VOID CompletionThreadProc (PVOID threadArg) -{ - EncryptedIoQueue *queue = (EncryptedIoQueue *) threadArg; - PLIST_ENTRY listEntry; - EncryptedIoRequest *request; - UINT64_STRUCT dataUnit; - - if (IsEncryptionThreadPoolRunning()) - KeSetPriorityThread (KeGetCurrentThread(), LOW_REALTIME_PRIORITY); - - while (!queue->ThreadExitRequested) - { - if (!NT_SUCCESS (KeWaitForSingleObject (&queue->CompletionThreadQueueNotEmptyEvent, Executive, KernelMode, FALSE, NULL))) - continue; - - if (queue->ThreadExitRequested) - break; - - while ((listEntry = ExInterlockedRemoveHeadList (&queue->CompletionThreadQueue, &queue->CompletionThreadQueueLock))) - { - request = CONTAINING_RECORD (listEntry, EncryptedIoRequest, CompletionListEntry); - - if (request->EncryptedLength > 0 && NT_SUCCESS (request->Item->Status)) - { - ASSERT (request->EncryptedOffset + request->EncryptedLength <= request->Offset.QuadPart + request->Length); - dataUnit.Value = (request->Offset.QuadPart + request->EncryptedOffset) / ENCRYPTION_DATA_UNIT_SIZE; - - if (queue->CryptoInfo->bPartitionInInactiveSysEncScope) - dataUnit.Value += queue->CryptoInfo->FirstDataUnitNo.Value; - else if (queue->RemapEncryptedArea) - dataUnit.Value += queue->RemappedAreaDataUnitOffset; - - DecryptDataUnits (request->Data + request->EncryptedOffset, &dataUnit, request->EncryptedLength / ENCRYPTION_DATA_UNIT_SIZE, queue->CryptoInfo); - } - - if (request->CompleteOriginalIrp) - { - CompleteOriginalIrp (request->Item, request->Item->Status, - NT_SUCCESS (request->Item->Status) ? request->Item->OriginalLength : 0); - } - - ReleasePoolBuffer (queue, request); - } - } - - PsTerminateSystemThread (STATUS_SUCCESS); -} - - -static NTSTATUS TCCachedRead (EncryptedIoQueue *queue, IO_STATUS_BLOCK *ioStatus, PVOID buffer, LARGE_INTEGER offset, ULONG length) -{ - queue->LastReadOffset = offset; - queue->LastReadLength = length; - - if (queue->ReadAheadBufferValid && queue->ReadAheadOffset.QuadPart == offset.QuadPart && queue->ReadAheadLength >= length) - { - memcpy (buffer, queue->ReadAheadBuffer, length); - - if (!queue->IsFilterDevice) - { - ioStatus->Information = length; - ioStatus->Status = STATUS_SUCCESS; - } - - return STATUS_SUCCESS; - } - - if (queue->IsFilterDevice) - return TCReadDevice (queue->LowerDeviceObject, buffer, offset, length); - - return ZwReadFile (queue->HostFileHandle, NULL, NULL, NULL, ioStatus, buffer, length, &offset, NULL); -} - - -static VOID IoThreadProc (PVOID threadArg) -{ - EncryptedIoQueue *queue = (EncryptedIoQueue *) threadArg; - PLIST_ENTRY listEntry; - EncryptedIoRequest *request; - - KeSetPriorityThread (KeGetCurrentThread(), LOW_REALTIME_PRIORITY); - - if (!queue->IsFilterDevice && queue->SecurityClientContext) - { -#ifdef DEBUG - NTSTATUS status = -#endif - SeImpersonateClientEx (queue->SecurityClientContext, NULL); - ASSERT (NT_SUCCESS (status)); - } - - while (!queue->ThreadExitRequested) - { - if (!NT_SUCCESS (KeWaitForSingleObject (&queue->IoThreadQueueNotEmptyEvent, Executive, KernelMode, FALSE, NULL))) - continue; - - if (queue->ThreadExitRequested) - break; - - while ((listEntry = ExInterlockedRemoveHeadList (&queue->IoThreadQueue, &queue->IoThreadQueueLock))) - { - InterlockedDecrement (&queue->IoThreadPendingRequestCount); - request = CONTAINING_RECORD (listEntry, EncryptedIoRequest, ListEntry); - -#ifdef TC_TRACE_IO_QUEUE - Dump ("%c %I64d [%I64d] roff=%I64d rlen=%d\n", request->Item->Write ? 'W' : 'R', request->Item->OriginalIrpOffset.QuadPart, GetElapsedTime (&queue->LastPerformanceCounter), request->Offset.QuadPart, request->Length); -#endif - - // Perform IO request if no preceding request of the item failed - if (NT_SUCCESS (request->Item->Status)) - { - if (queue->IsFilterDevice) - { - if (queue->RemapEncryptedArea && request->EncryptedLength > 0) - { - if (request->EncryptedLength != request->Length) - { - // Up to three subfragments may be required to handle a partially remapped fragment - int subFragment; - byte *subFragmentData = request->Data; - - for (subFragment = 0 ; subFragment < 3; ++subFragment) - { - LARGE_INTEGER subFragmentOffset; - ULONG subFragmentLength; - subFragmentOffset.QuadPart = request->Offset.QuadPart; - - switch (subFragment) - { - case 0: - subFragmentLength = (ULONG) request->EncryptedOffset; - break; - - case 1: - subFragmentOffset.QuadPart += request->EncryptedOffset + queue->RemappedAreaOffset; - subFragmentLength = request->EncryptedLength; - break; - - case 2: - subFragmentOffset.QuadPart += request->EncryptedOffset + request->EncryptedLength; - subFragmentLength = (ULONG) (request->Length - (request->EncryptedOffset + request->EncryptedLength)); - break; - } - - if (subFragmentLength > 0) - { - if (request->Item->Write) - request->Item->Status = TCWriteDevice (queue->LowerDeviceObject, subFragmentData, subFragmentOffset, subFragmentLength); - else - request->Item->Status = TCCachedRead (queue, NULL, subFragmentData, subFragmentOffset, subFragmentLength); - - subFragmentData += subFragmentLength; - } - } - } - else - { - // Remap the fragment - LARGE_INTEGER remappedOffset; - remappedOffset.QuadPart = request->Offset.QuadPart + queue->RemappedAreaOffset; - - if (request->Item->Write) - request->Item->Status = TCWriteDevice (queue->LowerDeviceObject, request->Data, remappedOffset, request->Length); - else - request->Item->Status = TCCachedRead (queue, NULL, request->Data, remappedOffset, request->Length); - } - } - else - { - if (request->Item->Write) - request->Item->Status = TCWriteDevice (queue->LowerDeviceObject, request->Data, request->Offset, request->Length); - else - request->Item->Status = TCCachedRead (queue, NULL, request->Data, request->Offset, request->Length); - } - } - else - { - IO_STATUS_BLOCK ioStatus; - - if (request->Item->Write) - request->Item->Status = ZwWriteFile (queue->HostFileHandle, NULL, NULL, NULL, &ioStatus, request->Data, request->Length, &request->Offset, NULL); - else - request->Item->Status = TCCachedRead (queue, &ioStatus, request->Data, request->Offset, request->Length); - - if (NT_SUCCESS (request->Item->Status) && ioStatus.Information != request->Length) - request->Item->Status = STATUS_END_OF_FILE; - } - } - - if (request->Item->Write) - { - queue->ReadAheadBufferValid = FALSE; - - ReleaseFragmentBuffer (queue, request->Data); - - if (request->CompleteOriginalIrp) - { - CompleteOriginalIrp (request->Item, request->Item->Status, - NT_SUCCESS (request->Item->Status) ? request->Item->OriginalLength : 0); - } - - ReleasePoolBuffer (queue, request); - } - else - { - BOOL readAhead = FALSE; - - if (NT_SUCCESS (request->Item->Status)) - memcpy (request->OrigDataBufferFragment, request->Data, request->Length); - - ReleaseFragmentBuffer (queue, request->Data); - request->Data = request->OrigDataBufferFragment; - - if (request->CompleteOriginalIrp - && queue->LastReadLength > 0 - && NT_SUCCESS (request->Item->Status) - && InterlockedExchangeAdd (&queue->IoThreadPendingRequestCount, 0) == 0) - { - readAhead = TRUE; - InterlockedIncrement (&queue->OutstandingIoCount); - } - - ExInterlockedInsertTailList (&queue->CompletionThreadQueue, &request->CompletionListEntry, &queue->CompletionThreadQueueLock); - KeSetEvent (&queue->CompletionThreadQueueNotEmptyEvent, IO_DISK_INCREMENT, FALSE); - - if (readAhead) - { - queue->ReadAheadBufferValid = FALSE; - queue->ReadAheadOffset.QuadPart = queue->LastReadOffset.QuadPart + queue->LastReadLength; - queue->ReadAheadLength = queue->LastReadLength; - - if (queue->ReadAheadOffset.QuadPart + queue->ReadAheadLength <= queue->MaxReadAheadOffset.QuadPart) - { -#ifdef TC_TRACE_IO_QUEUE - Dump ("A %I64d [%I64d] roff=%I64d rlen=%d\n", request->Item->OriginalIrpOffset.QuadPart, GetElapsedTime (&queue->LastPerformanceCounter), queue->ReadAheadOffset, queue->ReadAheadLength); -#endif - if (queue->IsFilterDevice) - { - queue->ReadAheadBufferValid = NT_SUCCESS (TCReadDevice (queue->LowerDeviceObject, queue->ReadAheadBuffer, queue->ReadAheadOffset, queue->ReadAheadLength)); - } - else - { - IO_STATUS_BLOCK ioStatus; - queue->ReadAheadBufferValid = NT_SUCCESS (ZwReadFile (queue->HostFileHandle, NULL, NULL, NULL, &ioStatus, queue->ReadAheadBuffer, queue->ReadAheadLength, &queue->ReadAheadOffset, NULL)); - queue->ReadAheadLength = (ULONG) ioStatus.Information; - } - } - - DecrementOutstandingIoCount (queue); - } - } - } - } - - PsTerminateSystemThread (STATUS_SUCCESS); -} - - -static VOID MainThreadProc (PVOID threadArg) -{ - EncryptedIoQueue *queue = (EncryptedIoQueue *) threadArg; - PLIST_ENTRY listEntry; - EncryptedIoQueueItem *item; - - LARGE_INTEGER fragmentOffset; - ULONG dataRemaining; - PUCHAR activeFragmentBuffer = queue->FragmentBufferA; - PUCHAR dataBuffer; - EncryptedIoRequest *request; - uint64 intersectStart; - uint32 intersectLength; - ULONGLONG addResult; - HRESULT hResult; - - if (IsEncryptionThreadPoolRunning()) - KeSetPriorityThread (KeGetCurrentThread(), LOW_REALTIME_PRIORITY); - - while (!queue->ThreadExitRequested) - { - if (!NT_SUCCESS (KeWaitForSingleObject (&queue->MainThreadQueueNotEmptyEvent, Executive, KernelMode, FALSE, NULL))) - continue; - - while ((listEntry = ExInterlockedRemoveHeadList (&queue->MainThreadQueue, &queue->MainThreadQueueLock))) - { - PIRP irp = CONTAINING_RECORD (listEntry, IRP, Tail.Overlay.ListEntry); - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (irp); - - if (queue->Suspended) - KeWaitForSingleObject (&queue->QueueResumedEvent, Executive, KernelMode, FALSE, NULL); - - item = GetPoolBuffer (queue, sizeof (EncryptedIoQueueItem)); - if (!item) - { - TCCompleteDiskIrp (irp, STATUS_INSUFFICIENT_RESOURCES, 0); - DecrementOutstandingIoCount (queue); - IoReleaseRemoveLock (&queue->RemoveLock, irp); - - continue; - } - - item->Queue = queue; - item->OriginalIrp = irp; - item->Status = STATUS_SUCCESS; - - IoSetCancelRoutine (irp, NULL); - if (irp->Cancel) - { - CompleteOriginalIrp (item, STATUS_CANCELLED, 0); - continue; - } - - switch (irpSp->MajorFunction) - { - case IRP_MJ_READ: - item->Write = FALSE; - item->OriginalOffset = irpSp->Parameters.Read.ByteOffset; - item->OriginalLength = irpSp->Parameters.Read.Length; - break; - - case IRP_MJ_WRITE: - item->Write = TRUE; - item->OriginalOffset = irpSp->Parameters.Write.ByteOffset; - item->OriginalLength = irpSp->Parameters.Write.Length; - break; - - default: - CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0); - continue; - } - -#ifdef TC_TRACE_IO_QUEUE - item->OriginalIrpOffset = item->OriginalOffset; -#endif - - // Handle misaligned read operations to work around a bug in Windows System Assessment Tool which does not follow FILE_FLAG_NO_BUFFERING requirements when benchmarking disk devices - if (queue->IsFilterDevice - && !item->Write - && item->OriginalLength > 0 - && (item->OriginalLength & (ENCRYPTION_DATA_UNIT_SIZE - 1)) == 0 - && (item->OriginalOffset.QuadPart & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0) - { - byte *buffer; - ULONG alignedLength; - LARGE_INTEGER alignedOffset; - hResult = ULongAdd(item->OriginalLength, ENCRYPTION_DATA_UNIT_SIZE, &alignedLength); - if (hResult != S_OK) - { - CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0); - continue; - } - - alignedOffset.QuadPart = item->OriginalOffset.QuadPart & ~((LONGLONG) ENCRYPTION_DATA_UNIT_SIZE - 1); - - buffer = TCalloc (alignedLength); - if (!buffer) - { - CompleteOriginalIrp (item, STATUS_INSUFFICIENT_RESOURCES, 0); - continue; - } - - item->Status = TCReadDevice (queue->LowerDeviceObject, buffer, alignedOffset, alignedLength); - - if (NT_SUCCESS (item->Status)) - { - UINT64_STRUCT dataUnit; - - dataBuffer = (PUCHAR) MmGetSystemAddressForMdlSafe (irp->MdlAddress, HighPagePriority); - if (!dataBuffer) - { - TCfree (buffer); - CompleteOriginalIrp (item, STATUS_INSUFFICIENT_RESOURCES, 0); - continue; - } - - if (queue->EncryptedAreaStart != -1 && queue->EncryptedAreaEnd != -1) - { - GetIntersection (alignedOffset.QuadPart, alignedLength, queue->EncryptedAreaStart, queue->EncryptedAreaEnd, &intersectStart, &intersectLength); - if (intersectLength > 0) - { - dataUnit.Value = intersectStart / ENCRYPTION_DATA_UNIT_SIZE; - DecryptDataUnits (buffer + (intersectStart - alignedOffset.QuadPart), &dataUnit, intersectLength / ENCRYPTION_DATA_UNIT_SIZE, queue->CryptoInfo); - } - } - - memcpy (dataBuffer, buffer + (item->OriginalOffset.LowPart & (ENCRYPTION_DATA_UNIT_SIZE - 1)), item->OriginalLength); - } - - TCfree (buffer); - CompleteOriginalIrp (item, item->Status, NT_SUCCESS (item->Status) ? item->OriginalLength : 0); - continue; - } - - // Validate offset and length - if (item->OriginalLength == 0 - || (item->OriginalLength & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0 - || (item->OriginalOffset.QuadPart & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0 - || ( !queue->IsFilterDevice && - ( (S_OK != ULongLongAdd(item->OriginalOffset.QuadPart, item->OriginalLength, &addResult)) - || (addResult > (ULONGLONG) queue->VirtualDeviceLength) - ) - ) - ) - { - CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0); - continue; - } - -#ifdef TC_TRACE_IO_QUEUE - Dump ("Q %I64d [%I64d] %c len=%d\n", item->OriginalOffset.QuadPart, GetElapsedTime (&queue->LastPerformanceCounter), item->Write ? 'W' : 'R', item->OriginalLength); -#endif - - if (!queue->IsFilterDevice) - { - // Adjust the offset for host file or device - if (queue->CryptoInfo->hiddenVolume) - hResult = ULongLongAdd(item->OriginalOffset.QuadPart, queue->CryptoInfo->hiddenVolumeOffset, &addResult); - else - hResult = ULongLongAdd(item->OriginalOffset.QuadPart, queue->CryptoInfo->volDataAreaOffset, &addResult); - - if (hResult != S_OK) - { - CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0); - continue; - } - else - item->OriginalOffset.QuadPart = addResult; - - // Hidden volume protection - if (item->Write && queue->CryptoInfo->bProtectHiddenVolume) - { - // If there has already been a write operation denied in order to protect the - // hidden volume (since the volume mount time) - if (queue->CryptoInfo->bHiddenVolProtectionAction) - { - // Do not allow writing to this volume anymore. This is to fake a complete volume - // or system failure (otherwise certain kinds of inconsistency within the file - // system could indicate that this volume has used hidden volume protection). - CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0); - continue; - } - - // Verify that no byte is going to be written to the hidden volume area - if (RegionsOverlap ((unsigned __int64) item->OriginalOffset.QuadPart, - (unsigned __int64) item->OriginalOffset.QuadPart + item->OriginalLength - 1, - queue->CryptoInfo->hiddenVolumeOffset, - (unsigned __int64) queue->CryptoInfo->hiddenVolumeOffset + queue->CryptoInfo->hiddenVolumeProtectedSize - 1)) - { - Dump ("Hidden volume protection triggered: write %I64d-%I64d (protected %I64d-%I64d)\n", item->OriginalOffset.QuadPart, item->OriginalOffset.QuadPart + item->OriginalLength - 1, queue->CryptoInfo->hiddenVolumeOffset, queue->CryptoInfo->hiddenVolumeOffset + queue->CryptoInfo->hiddenVolumeProtectedSize - 1); - queue->CryptoInfo->bHiddenVolProtectionAction = TRUE; - - // Deny this write operation to prevent the hidden volume from being overwritten - CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0); - continue; - } - } - } - else if (item->Write - && RegionsOverlap (item->OriginalOffset.QuadPart, item->OriginalOffset.QuadPart + item->OriginalLength - 1, TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET, TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET + TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE - 1)) - { - // Prevent inappropriately designed software from damaging important data that may be out of sync with the backup on the Rescue Disk (such as the end of the encrypted area). - Dump ("Preventing write to the system encryption key data area\n"); - CompleteOriginalIrp (item, STATUS_MEDIA_WRITE_PROTECTED, 0); - continue; - } - else if (item->Write && IsHiddenSystemRunning() - && (RegionsOverlap (item->OriginalOffset.QuadPart, item->OriginalOffset.QuadPart + item->OriginalLength - 1, TC_SECTOR_SIZE_BIOS, TC_BOOT_LOADER_AREA_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS - 1) - || RegionsOverlap (item->OriginalOffset.QuadPart, item->OriginalOffset.QuadPart + item->OriginalLength - 1, GetBootDriveLength(), _I64_MAX))) - { - Dump ("Preventing write to boot loader or host protected area\n"); - CompleteOriginalIrp (item, STATUS_MEDIA_WRITE_PROTECTED, 0); - continue; - } - - dataBuffer = (PUCHAR) MmGetSystemAddressForMdlSafe (irp->MdlAddress, HighPagePriority); - - if (dataBuffer == NULL) - { - CompleteOriginalIrp (item, STATUS_INSUFFICIENT_RESOURCES, 0); - continue; - } - - // Divide data block to fragments to enable efficient overlapping of encryption and IO operations - - dataRemaining = item->OriginalLength; - fragmentOffset = item->OriginalOffset; - - while (dataRemaining > 0) - { - BOOL isLastFragment = dataRemaining <= TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; - - ULONG dataFragmentLength = isLastFragment ? dataRemaining : TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; - activeFragmentBuffer = (activeFragmentBuffer == queue->FragmentBufferA ? queue->FragmentBufferB : queue->FragmentBufferA); - - InterlockedIncrement (&queue->IoThreadPendingRequestCount); - - // Create IO request - request = GetPoolBuffer (queue, sizeof (EncryptedIoRequest)); - if (!request) - { - CompleteOriginalIrp (item, STATUS_INSUFFICIENT_RESOURCES, 0); - break; - } - request->Item = item; - request->CompleteOriginalIrp = isLastFragment; - request->Offset = fragmentOffset; - request->Data = activeFragmentBuffer; - request->OrigDataBufferFragment = dataBuffer; - request->Length = dataFragmentLength; - - if (queue->IsFilterDevice) - { - if (queue->EncryptedAreaStart == -1 || queue->EncryptedAreaEnd == -1) - { - request->EncryptedLength = 0; - } - else - { - // Get intersection of data fragment with encrypted area - GetIntersection (fragmentOffset.QuadPart, dataFragmentLength, queue->EncryptedAreaStart, queue->EncryptedAreaEnd, &intersectStart, &intersectLength); - - request->EncryptedOffset = intersectStart - fragmentOffset.QuadPart; - request->EncryptedLength = intersectLength; - } - } - else - { - request->EncryptedOffset = 0; - request->EncryptedLength = dataFragmentLength; - } - - AcquireFragmentBuffer (queue, activeFragmentBuffer); - - if (item->Write) - { - // Encrypt data - memcpy (activeFragmentBuffer, dataBuffer, dataFragmentLength); - - if (request->EncryptedLength > 0) - { - UINT64_STRUCT dataUnit; - ASSERT (request->EncryptedOffset + request->EncryptedLength <= request->Offset.QuadPart + request->Length); - - dataUnit.Value = (request->Offset.QuadPart + request->EncryptedOffset) / ENCRYPTION_DATA_UNIT_SIZE; - - if (queue->CryptoInfo->bPartitionInInactiveSysEncScope) - dataUnit.Value += queue->CryptoInfo->FirstDataUnitNo.Value; - else if (queue->RemapEncryptedArea) - dataUnit.Value += queue->RemappedAreaDataUnitOffset; - - EncryptDataUnits (activeFragmentBuffer + request->EncryptedOffset, &dataUnit, request->EncryptedLength / ENCRYPTION_DATA_UNIT_SIZE, queue->CryptoInfo); - } - } - - // Queue IO request - ExInterlockedInsertTailList (&queue->IoThreadQueue, &request->ListEntry, &queue->IoThreadQueueLock); - KeSetEvent (&queue->IoThreadQueueNotEmptyEvent, IO_DISK_INCREMENT, FALSE); - - if (isLastFragment) - break; - - dataRemaining -= TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; - dataBuffer += TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; - fragmentOffset.QuadPart += TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; - } - } - } - - PsTerminateSystemThread (STATUS_SUCCESS); -} - - -NTSTATUS EncryptedIoQueueAddIrp (EncryptedIoQueue *queue, PIRP irp) -{ - NTSTATUS status; - - InterlockedIncrement (&queue->OutstandingIoCount); - if (queue->StopPending) - { - Dump ("STATUS_DEVICE_NOT_READY out=%d\n", queue->OutstandingIoCount); - status = STATUS_DEVICE_NOT_READY; - goto err; - } - - status = IoAcquireRemoveLock (&queue->RemoveLock, irp); - if (!NT_SUCCESS (status)) - goto err; - -#ifdef TC_TRACE_IO_QUEUE - { - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (irp); - Dump ("* %I64d [%I64d] %c len=%d out=%d\n", irpSp->MajorFunction == IRP_MJ_WRITE ? irpSp->Parameters.Write.ByteOffset : irpSp->Parameters.Read.ByteOffset, GetElapsedTime (&queue->LastPerformanceCounter), irpSp->MajorFunction == IRP_MJ_WRITE ? 'W' : 'R', irpSp->MajorFunction == IRP_MJ_WRITE ? irpSp->Parameters.Write.Length : irpSp->Parameters.Read.Length, queue->OutstandingIoCount); - } -#endif - - IoMarkIrpPending (irp); - - ExInterlockedInsertTailList (&queue->MainThreadQueue, &irp->Tail.Overlay.ListEntry, &queue->MainThreadQueueLock); - KeSetEvent (&queue->MainThreadQueueNotEmptyEvent, IO_DISK_INCREMENT, FALSE); - - return STATUS_PENDING; - -err: - DecrementOutstandingIoCount (queue); - return status; -} - - -NTSTATUS EncryptedIoQueueHoldWhenIdle (EncryptedIoQueue *queue, int64 timeout) -{ - NTSTATUS status; - ASSERT (!queue->Suspended); - - queue->SuspendPending = TRUE; - - while (TRUE) - { - while (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) > 0) - { - LARGE_INTEGER waitTimeout; - - waitTimeout.QuadPart = timeout * -10000; - status = KeWaitForSingleObject (&queue->NoOutstandingIoEvent, Executive, KernelMode, FALSE, timeout != 0 ? &waitTimeout : NULL); - - if (status == STATUS_TIMEOUT) - status = STATUS_UNSUCCESSFUL; - - if (!NT_SUCCESS (status)) - { - queue->SuspendPending = FALSE; - return status; - } - - TCSleep (1); - if (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) > 0) - { - queue->SuspendPending = FALSE; - return STATUS_UNSUCCESSFUL; - } - } - - KeClearEvent (&queue->QueueResumedEvent); - queue->Suspended = TRUE; - - if (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) == 0) - break; - - queue->Suspended = FALSE; - KeSetEvent (&queue->QueueResumedEvent, IO_DISK_INCREMENT, FALSE); - } - - queue->ReadAheadBufferValid = FALSE; - - queue->SuspendPending = FALSE; - return STATUS_SUCCESS; -} - - -BOOL EncryptedIoQueueIsSuspended (EncryptedIoQueue *queue) -{ - return queue->Suspended; -} - - -BOOL EncryptedIoQueueIsRunning (EncryptedIoQueue *queue) -{ - return !queue->StopPending; -} - - -NTSTATUS EncryptedIoQueueResumeFromHold (EncryptedIoQueue *queue) -{ - ASSERT (queue->Suspended); - - queue->Suspended = FALSE; - KeSetEvent (&queue->QueueResumedEvent, IO_DISK_INCREMENT, FALSE); - - return STATUS_SUCCESS; -} - - -NTSTATUS EncryptedIoQueueStart (EncryptedIoQueue *queue) -{ - NTSTATUS status; - EncryptedIoQueueBuffer *buffer; - int i; - - queue->StartPending = TRUE; - queue->ThreadExitRequested = FALSE; - - queue->OutstandingIoCount = 0; - queue->IoThreadPendingRequestCount = 0; - - queue->FirstPoolBuffer = NULL; - KeInitializeMutex (&queue->BufferPoolMutex, 0); - - KeInitializeEvent (&queue->NoOutstandingIoEvent, SynchronizationEvent, FALSE); - KeInitializeEvent (&queue->PoolBufferFreeEvent, SynchronizationEvent, FALSE); - KeInitializeEvent (&queue->QueueResumedEvent, SynchronizationEvent, FALSE); - - queue->FragmentBufferA = TCalloc (TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE); - if (!queue->FragmentBufferA) - goto noMemory; - - queue->FragmentBufferB = TCalloc (TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE); - if (!queue->FragmentBufferB) - goto noMemory; - - KeInitializeEvent (&queue->FragmentBufferAFreeEvent, SynchronizationEvent, TRUE); - KeInitializeEvent (&queue->FragmentBufferBFreeEvent, SynchronizationEvent, TRUE); - - queue->ReadAheadBufferValid = FALSE; - queue->ReadAheadBuffer = TCalloc (TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE); - if (!queue->ReadAheadBuffer) - goto noMemory; - - // Preallocate buffers - for (i = 0; i < TC_ENC_IO_QUEUE_PREALLOCATED_IO_REQUEST_COUNT; ++i) - { - if (i < TC_ENC_IO_QUEUE_PREALLOCATED_ITEM_COUNT && !GetPoolBuffer (queue, sizeof (EncryptedIoQueueItem))) - goto noMemory; - - if (!GetPoolBuffer (queue, sizeof (EncryptedIoRequest))) - goto noMemory; - } - - for (buffer = queue->FirstPoolBuffer; buffer != NULL; buffer = buffer->NextBuffer) - { - buffer->InUse = FALSE; - } - - // Main thread - InitializeListHead (&queue->MainThreadQueue); - KeInitializeSpinLock (&queue->MainThreadQueueLock); - KeInitializeEvent (&queue->MainThreadQueueNotEmptyEvent, SynchronizationEvent, FALSE); - - status = TCStartThread (MainThreadProc, queue, &queue->MainThread); - if (!NT_SUCCESS (status)) - goto err; - - // IO thread - InitializeListHead (&queue->IoThreadQueue); - KeInitializeSpinLock (&queue->IoThreadQueueLock); - KeInitializeEvent (&queue->IoThreadQueueNotEmptyEvent, SynchronizationEvent, FALSE); - - status = TCStartThread (IoThreadProc, queue, &queue->IoThread); - if (!NT_SUCCESS (status)) - { - queue->ThreadExitRequested = TRUE; - TCStopThread (queue->MainThread, &queue->MainThreadQueueNotEmptyEvent); - goto err; - } - - // Completion thread - InitializeListHead (&queue->CompletionThreadQueue); - KeInitializeSpinLock (&queue->CompletionThreadQueueLock); - KeInitializeEvent (&queue->CompletionThreadQueueNotEmptyEvent, SynchronizationEvent, FALSE); - - status = TCStartThread (CompletionThreadProc, queue, &queue->CompletionThread); - if (!NT_SUCCESS (status)) - { - queue->ThreadExitRequested = TRUE; - TCStopThread (queue->MainThread, &queue->MainThreadQueueNotEmptyEvent); - TCStopThread (queue->IoThread, &queue->IoThreadQueueNotEmptyEvent); - goto err; - } - -#ifdef TC_TRACE_IO_QUEUE - GetElapsedTimeInit (&queue->LastPerformanceCounter); -#endif - - queue->StopPending = FALSE; - queue->StartPending = FALSE; - - Dump ("Queue started\n"); - return STATUS_SUCCESS; - -noMemory: - status = STATUS_INSUFFICIENT_RESOURCES; - -err: - if (queue->FragmentBufferA) - TCfree (queue->FragmentBufferA); - if (queue->FragmentBufferB) - TCfree (queue->FragmentBufferB); - if (queue->ReadAheadBuffer) - TCfree (queue->ReadAheadBuffer); - - FreePoolBuffers (queue); - - queue->StartPending = FALSE; - return status; -} - - -NTSTATUS EncryptedIoQueueStop (EncryptedIoQueue *queue) -{ - ASSERT (!queue->StopPending); - queue->StopPending = TRUE; - - while (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) > 0) - { - KeWaitForSingleObject (&queue->NoOutstandingIoEvent, Executive, KernelMode, FALSE, NULL); - } - - Dump ("Queue stopping out=%d\n", queue->OutstandingIoCount); - - queue->ThreadExitRequested = TRUE; - - TCStopThread (queue->MainThread, &queue->MainThreadQueueNotEmptyEvent); - TCStopThread (queue->IoThread, &queue->IoThreadQueueNotEmptyEvent); - TCStopThread (queue->CompletionThread, &queue->CompletionThreadQueueNotEmptyEvent); - - TCfree (queue->FragmentBufferA); - TCfree (queue->FragmentBufferB); - TCfree (queue->ReadAheadBuffer); - - FreePoolBuffers (queue); - - Dump ("Queue stopped out=%d\n", queue->OutstandingIoCount); - return STATUS_SUCCESS; -} +/* + 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 "TCdefs.h" +#include "Apidrvr.h" +#include "Ntdriver.h" +#include "DriveFilter.h" +#include "EncryptedIoQueue.h" +#include "EncryptionThreadPool.h" +#include "Volumes.h" +#include + + +static void AcquireBufferPoolMutex (EncryptedIoQueue *queue) +{ + NTSTATUS status; + + status = KeWaitForMutexObject (&queue->BufferPoolMutex, Executive, KernelMode, FALSE, NULL); + if (!NT_SUCCESS (status)) + TC_BUG_CHECK (status); +} + + +static void ReleaseBufferPoolMutex (EncryptedIoQueue *queue) +{ + KeReleaseMutex (&queue->BufferPoolMutex, FALSE); +} + + +static void *GetPoolBuffer (EncryptedIoQueue *queue, ULONG requestedSize) +{ + EncryptedIoQueueBuffer *buffer; + void *bufferAddress = NULL; + BOOL requestedSizePresentInPool = FALSE; + + while (TRUE) + { + AcquireBufferPoolMutex (queue); + + for (buffer = queue->FirstPoolBuffer; ; buffer = buffer->NextBuffer) + { + if (buffer && buffer->Size == requestedSize) + { + requestedSizePresentInPool = TRUE; + + if (!buffer->InUse) + { + // Reuse a free buffer + buffer->InUse = TRUE; + bufferAddress = buffer->Address; + break; + } + } + + if (!buffer || !buffer->NextBuffer) + { + EncryptedIoQueueBuffer *newBuffer; + + if (requestedSizePresentInPool && !queue->StartPending) + break; + + // Allocate a new buffer + newBuffer = TCalloc (sizeof (EncryptedIoQueueBuffer)); + if (!newBuffer) + { + bufferAddress = NULL; + break; + } + + bufferAddress = TCalloc (requestedSize); + if (bufferAddress) + { + newBuffer->NextBuffer = NULL; + newBuffer->Address = bufferAddress; + newBuffer->Size = requestedSize; + newBuffer->InUse = TRUE; + + if (!buffer) + queue->FirstPoolBuffer = newBuffer; + else + buffer->NextBuffer = newBuffer; + } + else + TCfree (newBuffer); + + break; + } + } + + ReleaseBufferPoolMutex (queue); + + if (bufferAddress || !requestedSizePresentInPool || queue->StartPending) + break; + + KeWaitForSingleObject (&queue->PoolBufferFreeEvent, Executive, KernelMode, FALSE, NULL); + } + + return bufferAddress; +} + + +static void ReleasePoolBuffer (EncryptedIoQueue *queue, void *address) +{ + EncryptedIoQueueBuffer *buffer; + AcquireBufferPoolMutex (queue); + + for (buffer = queue->FirstPoolBuffer; buffer != NULL; buffer = buffer->NextBuffer) + { + if (buffer->Address == address) + { + ASSERT (buffer->InUse); + + buffer->InUse = FALSE; + break; + } + } + + ReleaseBufferPoolMutex (queue); + KeSetEvent (&queue->PoolBufferFreeEvent, IO_DISK_INCREMENT, FALSE); +} + + +static void FreePoolBuffers (EncryptedIoQueue *queue) +{ + EncryptedIoQueueBuffer *buffer; + AcquireBufferPoolMutex (queue); + + for (buffer = queue->FirstPoolBuffer; buffer != NULL; ) + { + EncryptedIoQueueBuffer *nextBuffer = buffer->NextBuffer; + + ASSERT (!buffer->InUse || queue->StartPending); + + TCfree (buffer->Address); + TCfree (buffer); + + buffer = nextBuffer; + } + + queue->FirstPoolBuffer = NULL; + ReleaseBufferPoolMutex (queue); +} + + +static void DecrementOutstandingIoCount (EncryptedIoQueue *queue) +{ + if (InterlockedDecrement (&queue->OutstandingIoCount) == 0 && (queue->SuspendPending || queue->StopPending)) + KeSetEvent (&queue->NoOutstandingIoEvent, IO_DISK_INCREMENT, FALSE); +} + + +static void OnItemCompleted (EncryptedIoQueueItem *item, BOOL freeItem) +{ + DecrementOutstandingIoCount (item->Queue); + IoReleaseRemoveLock (&item->Queue->RemoveLock, item->OriginalIrp); + + if (NT_SUCCESS (item->Status)) + { + if (item->Write) + item->Queue->TotalBytesWritten += item->OriginalLength; + else + item->Queue->TotalBytesRead += item->OriginalLength; + } + + if (freeItem) + ReleasePoolBuffer (item->Queue, item); +} + + +static NTSTATUS CompleteOriginalIrp (EncryptedIoQueueItem *item, NTSTATUS status, ULONG_PTR information) +{ +#ifdef TC_TRACE_IO_QUEUE + Dump ("< %I64d [%I64d] %c status=%x info=%I64d\n", item->OriginalIrpOffset, GetElapsedTime (&item->Queue->LastPerformanceCounter), item->Write ? 'W' : 'R', status, (int64) information); +#endif + + TCCompleteDiskIrp (item->OriginalIrp, status, information); + + item->Status = status; + OnItemCompleted (item, TRUE); + + return status; +} + + +static void AcquireFragmentBuffer (EncryptedIoQueue *queue, byte *buffer) +{ + NTSTATUS status = STATUS_INVALID_PARAMETER; + + if (buffer == queue->FragmentBufferA) + { + status = KeWaitForSingleObject (&queue->FragmentBufferAFreeEvent, Executive, KernelMode, FALSE, NULL); + } + else if (buffer == queue->FragmentBufferB) + { + status = KeWaitForSingleObject (&queue->FragmentBufferBFreeEvent, Executive, KernelMode, FALSE, NULL); + } + + if (!NT_SUCCESS (status)) + TC_BUG_CHECK (status); +} + + +static void ReleaseFragmentBuffer (EncryptedIoQueue *queue, byte *buffer) +{ + if (buffer == queue->FragmentBufferA) + { + KeSetEvent (&queue->FragmentBufferAFreeEvent, IO_DISK_INCREMENT, FALSE); + } + else if (buffer == queue->FragmentBufferB) + { + KeSetEvent (&queue->FragmentBufferBFreeEvent, IO_DISK_INCREMENT, FALSE); + } + else + { + TC_BUG_CHECK (STATUS_INVALID_PARAMETER); + } +} + + +static VOID CompletionThreadProc (PVOID threadArg) +{ + EncryptedIoQueue *queue = (EncryptedIoQueue *) threadArg; + PLIST_ENTRY listEntry; + EncryptedIoRequest *request; + UINT64_STRUCT dataUnit; + + if (IsEncryptionThreadPoolRunning()) + KeSetPriorityThread (KeGetCurrentThread(), LOW_REALTIME_PRIORITY); + + while (!queue->ThreadExitRequested) + { + if (!NT_SUCCESS (KeWaitForSingleObject (&queue->CompletionThreadQueueNotEmptyEvent, Executive, KernelMode, FALSE, NULL))) + continue; + + if (queue->ThreadExitRequested) + break; + + while ((listEntry = ExInterlockedRemoveHeadList (&queue->CompletionThreadQueue, &queue->CompletionThreadQueueLock))) + { + request = CONTAINING_RECORD (listEntry, EncryptedIoRequest, CompletionListEntry); + + if (request->EncryptedLength > 0 && NT_SUCCESS (request->Item->Status)) + { + ASSERT (request->EncryptedOffset + request->EncryptedLength <= request->Offset.QuadPart + request->Length); + dataUnit.Value = (request->Offset.QuadPart + request->EncryptedOffset) / ENCRYPTION_DATA_UNIT_SIZE; + + if (queue->CryptoInfo->bPartitionInInactiveSysEncScope) + dataUnit.Value += queue->CryptoInfo->FirstDataUnitNo.Value; + else if (queue->RemapEncryptedArea) + dataUnit.Value += queue->RemappedAreaDataUnitOffset; + + DecryptDataUnits (request->Data + request->EncryptedOffset, &dataUnit, request->EncryptedLength / ENCRYPTION_DATA_UNIT_SIZE, queue->CryptoInfo); + } + + if (request->CompleteOriginalIrp) + { + CompleteOriginalIrp (request->Item, request->Item->Status, + NT_SUCCESS (request->Item->Status) ? request->Item->OriginalLength : 0); + } + + ReleasePoolBuffer (queue, request); + } + } + + PsTerminateSystemThread (STATUS_SUCCESS); +} + + +static NTSTATUS TCCachedRead (EncryptedIoQueue *queue, IO_STATUS_BLOCK *ioStatus, PVOID buffer, LARGE_INTEGER offset, ULONG length) +{ + queue->LastReadOffset = offset; + queue->LastReadLength = length; + + if (queue->ReadAheadBufferValid && queue->ReadAheadOffset.QuadPart == offset.QuadPart && queue->ReadAheadLength >= length) + { + memcpy (buffer, queue->ReadAheadBuffer, length); + + if (!queue->IsFilterDevice) + { + ioStatus->Information = length; + ioStatus->Status = STATUS_SUCCESS; + } + + return STATUS_SUCCESS; + } + + if (queue->IsFilterDevice) + return TCReadDevice (queue->LowerDeviceObject, buffer, offset, length); + + return ZwReadFile (queue->HostFileHandle, NULL, NULL, NULL, ioStatus, buffer, length, &offset, NULL); +} + + +static VOID IoThreadProc (PVOID threadArg) +{ + EncryptedIoQueue *queue = (EncryptedIoQueue *) threadArg; + PLIST_ENTRY listEntry; + EncryptedIoRequest *request; + + KeSetPriorityThread (KeGetCurrentThread(), LOW_REALTIME_PRIORITY); + + if (!queue->IsFilterDevice && queue->SecurityClientContext) + { +#ifdef DEBUG + NTSTATUS status = +#endif + SeImpersonateClientEx (queue->SecurityClientContext, NULL); + ASSERT (NT_SUCCESS (status)); + } + + while (!queue->ThreadExitRequested) + { + if (!NT_SUCCESS (KeWaitForSingleObject (&queue->IoThreadQueueNotEmptyEvent, Executive, KernelMode, FALSE, NULL))) + continue; + + if (queue->ThreadExitRequested) + break; + + while ((listEntry = ExInterlockedRemoveHeadList (&queue->IoThreadQueue, &queue->IoThreadQueueLock))) + { + InterlockedDecrement (&queue->IoThreadPendingRequestCount); + request = CONTAINING_RECORD (listEntry, EncryptedIoRequest, ListEntry); + +#ifdef TC_TRACE_IO_QUEUE + Dump ("%c %I64d [%I64d] roff=%I64d rlen=%d\n", request->Item->Write ? 'W' : 'R', request->Item->OriginalIrpOffset.QuadPart, GetElapsedTime (&queue->LastPerformanceCounter), request->Offset.QuadPart, request->Length); +#endif + + // Perform IO request if no preceding request of the item failed + if (NT_SUCCESS (request->Item->Status)) + { + if (queue->IsFilterDevice) + { + if (queue->RemapEncryptedArea && request->EncryptedLength > 0) + { + if (request->EncryptedLength != request->Length) + { + // Up to three subfragments may be required to handle a partially remapped fragment + int subFragment; + byte *subFragmentData = request->Data; + + for (subFragment = 0 ; subFragment < 3; ++subFragment) + { + LARGE_INTEGER subFragmentOffset; + ULONG subFragmentLength; + subFragmentOffset.QuadPart = request->Offset.QuadPart; + + switch (subFragment) + { + case 0: + subFragmentLength = (ULONG) request->EncryptedOffset; + break; + + case 1: + subFragmentOffset.QuadPart += request->EncryptedOffset + queue->RemappedAreaOffset; + subFragmentLength = request->EncryptedLength; + break; + + case 2: + subFragmentOffset.QuadPart += request->EncryptedOffset + request->EncryptedLength; + subFragmentLength = (ULONG) (request->Length - (request->EncryptedOffset + request->EncryptedLength)); + break; + } + + if (subFragmentLength > 0) + { + if (request->Item->Write) + request->Item->Status = TCWriteDevice (queue->LowerDeviceObject, subFragmentData, subFragmentOffset, subFragmentLength); + else + request->Item->Status = TCCachedRead (queue, NULL, subFragmentData, subFragmentOffset, subFragmentLength); + + subFragmentData += subFragmentLength; + } + } + } + else + { + // Remap the fragment + LARGE_INTEGER remappedOffset; + remappedOffset.QuadPart = request->Offset.QuadPart + queue->RemappedAreaOffset; + + if (request->Item->Write) + request->Item->Status = TCWriteDevice (queue->LowerDeviceObject, request->Data, remappedOffset, request->Length); + else + request->Item->Status = TCCachedRead (queue, NULL, request->Data, remappedOffset, request->Length); + } + } + else + { + if (request->Item->Write) + request->Item->Status = TCWriteDevice (queue->LowerDeviceObject, request->Data, request->Offset, request->Length); + else + request->Item->Status = TCCachedRead (queue, NULL, request->Data, request->Offset, request->Length); + } + } + else + { + IO_STATUS_BLOCK ioStatus; + + if (request->Item->Write) + request->Item->Status = ZwWriteFile (queue->HostFileHandle, NULL, NULL, NULL, &ioStatus, request->Data, request->Length, &request->Offset, NULL); + else + request->Item->Status = TCCachedRead (queue, &ioStatus, request->Data, request->Offset, request->Length); + + if (NT_SUCCESS (request->Item->Status) && ioStatus.Information != request->Length) + request->Item->Status = STATUS_END_OF_FILE; + } + } + + if (request->Item->Write) + { + queue->ReadAheadBufferValid = FALSE; + + ReleaseFragmentBuffer (queue, request->Data); + + if (request->CompleteOriginalIrp) + { + CompleteOriginalIrp (request->Item, request->Item->Status, + NT_SUCCESS (request->Item->Status) ? request->Item->OriginalLength : 0); + } + + ReleasePoolBuffer (queue, request); + } + else + { + BOOL readAhead = FALSE; + + if (NT_SUCCESS (request->Item->Status)) + memcpy (request->OrigDataBufferFragment, request->Data, request->Length); + + ReleaseFragmentBuffer (queue, request->Data); + request->Data = request->OrigDataBufferFragment; + + if (request->CompleteOriginalIrp + && queue->LastReadLength > 0 + && NT_SUCCESS (request->Item->Status) + && InterlockedExchangeAdd (&queue->IoThreadPendingRequestCount, 0) == 0) + { + readAhead = TRUE; + InterlockedIncrement (&queue->OutstandingIoCount); + } + + ExInterlockedInsertTailList (&queue->CompletionThreadQueue, &request->CompletionListEntry, &queue->CompletionThreadQueueLock); + KeSetEvent (&queue->CompletionThreadQueueNotEmptyEvent, IO_DISK_INCREMENT, FALSE); + + if (readAhead) + { + queue->ReadAheadBufferValid = FALSE; + queue->ReadAheadOffset.QuadPart = queue->LastReadOffset.QuadPart + queue->LastReadLength; + queue->ReadAheadLength = queue->LastReadLength; + + if (queue->ReadAheadOffset.QuadPart + queue->ReadAheadLength <= queue->MaxReadAheadOffset.QuadPart) + { +#ifdef TC_TRACE_IO_QUEUE + Dump ("A %I64d [%I64d] roff=%I64d rlen=%d\n", request->Item->OriginalIrpOffset.QuadPart, GetElapsedTime (&queue->LastPerformanceCounter), queue->ReadAheadOffset, queue->ReadAheadLength); +#endif + if (queue->IsFilterDevice) + { + queue->ReadAheadBufferValid = NT_SUCCESS (TCReadDevice (queue->LowerDeviceObject, queue->ReadAheadBuffer, queue->ReadAheadOffset, queue->ReadAheadLength)); + } + else + { + IO_STATUS_BLOCK ioStatus; + queue->ReadAheadBufferValid = NT_SUCCESS (ZwReadFile (queue->HostFileHandle, NULL, NULL, NULL, &ioStatus, queue->ReadAheadBuffer, queue->ReadAheadLength, &queue->ReadAheadOffset, NULL)); + queue->ReadAheadLength = (ULONG) ioStatus.Information; + } + } + + DecrementOutstandingIoCount (queue); + } + } + } + } + + PsTerminateSystemThread (STATUS_SUCCESS); +} + + +static VOID MainThreadProc (PVOID threadArg) +{ + EncryptedIoQueue *queue = (EncryptedIoQueue *) threadArg; + PLIST_ENTRY listEntry; + EncryptedIoQueueItem *item; + + LARGE_INTEGER fragmentOffset; + ULONG dataRemaining; + PUCHAR activeFragmentBuffer = queue->FragmentBufferA; + PUCHAR dataBuffer; + EncryptedIoRequest *request; + uint64 intersectStart; + uint32 intersectLength; + ULONGLONG addResult; + HRESULT hResult; + + if (IsEncryptionThreadPoolRunning()) + KeSetPriorityThread (KeGetCurrentThread(), LOW_REALTIME_PRIORITY); + + while (!queue->ThreadExitRequested) + { + if (!NT_SUCCESS (KeWaitForSingleObject (&queue->MainThreadQueueNotEmptyEvent, Executive, KernelMode, FALSE, NULL))) + continue; + + while ((listEntry = ExInterlockedRemoveHeadList (&queue->MainThreadQueue, &queue->MainThreadQueueLock))) + { + PIRP irp = CONTAINING_RECORD (listEntry, IRP, Tail.Overlay.ListEntry); + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (irp); + + if (queue->Suspended) + KeWaitForSingleObject (&queue->QueueResumedEvent, Executive, KernelMode, FALSE, NULL); + + item = GetPoolBuffer (queue, sizeof (EncryptedIoQueueItem)); + if (!item) + { + TCCompleteDiskIrp (irp, STATUS_INSUFFICIENT_RESOURCES, 0); + DecrementOutstandingIoCount (queue); + IoReleaseRemoveLock (&queue->RemoveLock, irp); + + continue; + } + + item->Queue = queue; + item->OriginalIrp = irp; + item->Status = STATUS_SUCCESS; + + IoSetCancelRoutine (irp, NULL); + if (irp->Cancel) + { + CompleteOriginalIrp (item, STATUS_CANCELLED, 0); + continue; + } + + switch (irpSp->MajorFunction) + { + case IRP_MJ_READ: + item->Write = FALSE; + item->OriginalOffset = irpSp->Parameters.Read.ByteOffset; + item->OriginalLength = irpSp->Parameters.Read.Length; + break; + + case IRP_MJ_WRITE: + item->Write = TRUE; + item->OriginalOffset = irpSp->Parameters.Write.ByteOffset; + item->OriginalLength = irpSp->Parameters.Write.Length; + break; + + default: + CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0); + continue; + } + +#ifdef TC_TRACE_IO_QUEUE + item->OriginalIrpOffset = item->OriginalOffset; +#endif + + // Handle misaligned read operations to work around a bug in Windows System Assessment Tool which does not follow FILE_FLAG_NO_BUFFERING requirements when benchmarking disk devices + if (queue->IsFilterDevice + && !item->Write + && item->OriginalLength > 0 + && (item->OriginalLength & (ENCRYPTION_DATA_UNIT_SIZE - 1)) == 0 + && (item->OriginalOffset.QuadPart & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0) + { + byte *buffer; + ULONG alignedLength; + LARGE_INTEGER alignedOffset; + hResult = ULongAdd(item->OriginalLength, ENCRYPTION_DATA_UNIT_SIZE, &alignedLength); + if (hResult != S_OK) + { + CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0); + continue; + } + + alignedOffset.QuadPart = item->OriginalOffset.QuadPart & ~((LONGLONG) ENCRYPTION_DATA_UNIT_SIZE - 1); + + buffer = TCalloc (alignedLength); + if (!buffer) + { + CompleteOriginalIrp (item, STATUS_INSUFFICIENT_RESOURCES, 0); + continue; + } + + item->Status = TCReadDevice (queue->LowerDeviceObject, buffer, alignedOffset, alignedLength); + + if (NT_SUCCESS (item->Status)) + { + UINT64_STRUCT dataUnit; + + dataBuffer = (PUCHAR) MmGetSystemAddressForMdlSafe (irp->MdlAddress, HighPagePriority); + if (!dataBuffer) + { + TCfree (buffer); + CompleteOriginalIrp (item, STATUS_INSUFFICIENT_RESOURCES, 0); + continue; + } + + if (queue->EncryptedAreaStart != -1 && queue->EncryptedAreaEnd != -1) + { + GetIntersection (alignedOffset.QuadPart, alignedLength, queue->EncryptedAreaStart, queue->EncryptedAreaEnd, &intersectStart, &intersectLength); + if (intersectLength > 0) + { + dataUnit.Value = intersectStart / ENCRYPTION_DATA_UNIT_SIZE; + DecryptDataUnits (buffer + (intersectStart - alignedOffset.QuadPart), &dataUnit, intersectLength / ENCRYPTION_DATA_UNIT_SIZE, queue->CryptoInfo); + } + } + + memcpy (dataBuffer, buffer + (item->OriginalOffset.LowPart & (ENCRYPTION_DATA_UNIT_SIZE - 1)), item->OriginalLength); + } + + TCfree (buffer); + CompleteOriginalIrp (item, item->Status, NT_SUCCESS (item->Status) ? item->OriginalLength : 0); + continue; + } + + // Validate offset and length + if (item->OriginalLength == 0 + || (item->OriginalLength & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0 + || (item->OriginalOffset.QuadPart & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0 + || ( !queue->IsFilterDevice && + ( (S_OK != ULongLongAdd(item->OriginalOffset.QuadPart, item->OriginalLength, &addResult)) + || (addResult > (ULONGLONG) queue->VirtualDeviceLength) + ) + ) + ) + { + CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0); + continue; + } + +#ifdef TC_TRACE_IO_QUEUE + Dump ("Q %I64d [%I64d] %c len=%d\n", item->OriginalOffset.QuadPart, GetElapsedTime (&queue->LastPerformanceCounter), item->Write ? 'W' : 'R', item->OriginalLength); +#endif + + if (!queue->IsFilterDevice) + { + // Adjust the offset for host file or device + if (queue->CryptoInfo->hiddenVolume) + hResult = ULongLongAdd(item->OriginalOffset.QuadPart, queue->CryptoInfo->hiddenVolumeOffset, &addResult); + else + hResult = ULongLongAdd(item->OriginalOffset.QuadPart, queue->CryptoInfo->volDataAreaOffset, &addResult); + + if (hResult != S_OK) + { + CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0); + continue; + } + else + item->OriginalOffset.QuadPart = addResult; + + // Hidden volume protection + if (item->Write && queue->CryptoInfo->bProtectHiddenVolume) + { + // If there has already been a write operation denied in order to protect the + // hidden volume (since the volume mount time) + if (queue->CryptoInfo->bHiddenVolProtectionAction) + { + // Do not allow writing to this volume anymore. This is to fake a complete volume + // or system failure (otherwise certain kinds of inconsistency within the file + // system could indicate that this volume has used hidden volume protection). + CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0); + continue; + } + + // Verify that no byte is going to be written to the hidden volume area + if (RegionsOverlap ((unsigned __int64) item->OriginalOffset.QuadPart, + (unsigned __int64) item->OriginalOffset.QuadPart + item->OriginalLength - 1, + queue->CryptoInfo->hiddenVolumeOffset, + (unsigned __int64) queue->CryptoInfo->hiddenVolumeOffset + queue->CryptoInfo->hiddenVolumeProtectedSize - 1)) + { + Dump ("Hidden volume protection triggered: write %I64d-%I64d (protected %I64d-%I64d)\n", item->OriginalOffset.QuadPart, item->OriginalOffset.QuadPart + item->OriginalLength - 1, queue->CryptoInfo->hiddenVolumeOffset, queue->CryptoInfo->hiddenVolumeOffset + queue->CryptoInfo->hiddenVolumeProtectedSize - 1); + queue->CryptoInfo->bHiddenVolProtectionAction = TRUE; + + // Deny this write operation to prevent the hidden volume from being overwritten + CompleteOriginalIrp (item, STATUS_INVALID_PARAMETER, 0); + continue; + } + } + } + else if (item->Write + && RegionsOverlap (item->OriginalOffset.QuadPart, item->OriginalOffset.QuadPart + item->OriginalLength - 1, TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET, TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET + TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE - 1)) + { + // Prevent inappropriately designed software from damaging important data that may be out of sync with the backup on the Rescue Disk (such as the end of the encrypted area). + Dump ("Preventing write to the system encryption key data area\n"); + CompleteOriginalIrp (item, STATUS_MEDIA_WRITE_PROTECTED, 0); + continue; + } + else if (item->Write && IsHiddenSystemRunning() + && (RegionsOverlap (item->OriginalOffset.QuadPart, item->OriginalOffset.QuadPart + item->OriginalLength - 1, TC_SECTOR_SIZE_BIOS, TC_BOOT_LOADER_AREA_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS - 1) + || RegionsOverlap (item->OriginalOffset.QuadPart, item->OriginalOffset.QuadPart + item->OriginalLength - 1, GetBootDriveLength(), _I64_MAX))) + { + Dump ("Preventing write to boot loader or host protected area\n"); + CompleteOriginalIrp (item, STATUS_MEDIA_WRITE_PROTECTED, 0); + continue; + } + + dataBuffer = (PUCHAR) MmGetSystemAddressForMdlSafe (irp->MdlAddress, HighPagePriority); + + if (dataBuffer == NULL) + { + CompleteOriginalIrp (item, STATUS_INSUFFICIENT_RESOURCES, 0); + continue; + } + + // Divide data block to fragments to enable efficient overlapping of encryption and IO operations + + dataRemaining = item->OriginalLength; + fragmentOffset = item->OriginalOffset; + + while (dataRemaining > 0) + { + BOOL isLastFragment = dataRemaining <= TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; + + ULONG dataFragmentLength = isLastFragment ? dataRemaining : TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; + activeFragmentBuffer = (activeFragmentBuffer == queue->FragmentBufferA ? queue->FragmentBufferB : queue->FragmentBufferA); + + InterlockedIncrement (&queue->IoThreadPendingRequestCount); + + // Create IO request + request = GetPoolBuffer (queue, sizeof (EncryptedIoRequest)); + if (!request) + { + CompleteOriginalIrp (item, STATUS_INSUFFICIENT_RESOURCES, 0); + break; + } + request->Item = item; + request->CompleteOriginalIrp = isLastFragment; + request->Offset = fragmentOffset; + request->Data = activeFragmentBuffer; + request->OrigDataBufferFragment = dataBuffer; + request->Length = dataFragmentLength; + + if (queue->IsFilterDevice) + { + if (queue->EncryptedAreaStart == -1 || queue->EncryptedAreaEnd == -1) + { + request->EncryptedLength = 0; + } + else + { + // Get intersection of data fragment with encrypted area + GetIntersection (fragmentOffset.QuadPart, dataFragmentLength, queue->EncryptedAreaStart, queue->EncryptedAreaEnd, &intersectStart, &intersectLength); + + request->EncryptedOffset = intersectStart - fragmentOffset.QuadPart; + request->EncryptedLength = intersectLength; + } + } + else + { + request->EncryptedOffset = 0; + request->EncryptedLength = dataFragmentLength; + } + + AcquireFragmentBuffer (queue, activeFragmentBuffer); + + if (item->Write) + { + // Encrypt data + memcpy (activeFragmentBuffer, dataBuffer, dataFragmentLength); + + if (request->EncryptedLength > 0) + { + UINT64_STRUCT dataUnit; + ASSERT (request->EncryptedOffset + request->EncryptedLength <= request->Offset.QuadPart + request->Length); + + dataUnit.Value = (request->Offset.QuadPart + request->EncryptedOffset) / ENCRYPTION_DATA_UNIT_SIZE; + + if (queue->CryptoInfo->bPartitionInInactiveSysEncScope) + dataUnit.Value += queue->CryptoInfo->FirstDataUnitNo.Value; + else if (queue->RemapEncryptedArea) + dataUnit.Value += queue->RemappedAreaDataUnitOffset; + + EncryptDataUnits (activeFragmentBuffer + request->EncryptedOffset, &dataUnit, request->EncryptedLength / ENCRYPTION_DATA_UNIT_SIZE, queue->CryptoInfo); + } + } + + // Queue IO request + ExInterlockedInsertTailList (&queue->IoThreadQueue, &request->ListEntry, &queue->IoThreadQueueLock); + KeSetEvent (&queue->IoThreadQueueNotEmptyEvent, IO_DISK_INCREMENT, FALSE); + + if (isLastFragment) + break; + + dataRemaining -= TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; + dataBuffer += TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; + fragmentOffset.QuadPart += TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; + } + } + } + + PsTerminateSystemThread (STATUS_SUCCESS); +} + + +NTSTATUS EncryptedIoQueueAddIrp (EncryptedIoQueue *queue, PIRP irp) +{ + NTSTATUS status; + + InterlockedIncrement (&queue->OutstandingIoCount); + if (queue->StopPending) + { + Dump ("STATUS_DEVICE_NOT_READY out=%d\n", queue->OutstandingIoCount); + status = STATUS_DEVICE_NOT_READY; + goto err; + } + + status = IoAcquireRemoveLock (&queue->RemoveLock, irp); + if (!NT_SUCCESS (status)) + goto err; + +#ifdef TC_TRACE_IO_QUEUE + { + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (irp); + Dump ("* %I64d [%I64d] %c len=%d out=%d\n", irpSp->MajorFunction == IRP_MJ_WRITE ? irpSp->Parameters.Write.ByteOffset : irpSp->Parameters.Read.ByteOffset, GetElapsedTime (&queue->LastPerformanceCounter), irpSp->MajorFunction == IRP_MJ_WRITE ? 'W' : 'R', irpSp->MajorFunction == IRP_MJ_WRITE ? irpSp->Parameters.Write.Length : irpSp->Parameters.Read.Length, queue->OutstandingIoCount); + } +#endif + + IoMarkIrpPending (irp); + + ExInterlockedInsertTailList (&queue->MainThreadQueue, &irp->Tail.Overlay.ListEntry, &queue->MainThreadQueueLock); + KeSetEvent (&queue->MainThreadQueueNotEmptyEvent, IO_DISK_INCREMENT, FALSE); + + return STATUS_PENDING; + +err: + DecrementOutstandingIoCount (queue); + return status; +} + + +NTSTATUS EncryptedIoQueueHoldWhenIdle (EncryptedIoQueue *queue, int64 timeout) +{ + NTSTATUS status; + ASSERT (!queue->Suspended); + + queue->SuspendPending = TRUE; + + while (TRUE) + { + while (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) > 0) + { + LARGE_INTEGER waitTimeout; + + waitTimeout.QuadPart = timeout * -10000; + status = KeWaitForSingleObject (&queue->NoOutstandingIoEvent, Executive, KernelMode, FALSE, timeout != 0 ? &waitTimeout : NULL); + + if (status == STATUS_TIMEOUT) + status = STATUS_UNSUCCESSFUL; + + if (!NT_SUCCESS (status)) + { + queue->SuspendPending = FALSE; + return status; + } + + TCSleep (1); + if (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) > 0) + { + queue->SuspendPending = FALSE; + return STATUS_UNSUCCESSFUL; + } + } + + KeClearEvent (&queue->QueueResumedEvent); + queue->Suspended = TRUE; + + if (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) == 0) + break; + + queue->Suspended = FALSE; + KeSetEvent (&queue->QueueResumedEvent, IO_DISK_INCREMENT, FALSE); + } + + queue->ReadAheadBufferValid = FALSE; + + queue->SuspendPending = FALSE; + return STATUS_SUCCESS; +} + + +BOOL EncryptedIoQueueIsSuspended (EncryptedIoQueue *queue) +{ + return queue->Suspended; +} + + +BOOL EncryptedIoQueueIsRunning (EncryptedIoQueue *queue) +{ + return !queue->StopPending; +} + + +NTSTATUS EncryptedIoQueueResumeFromHold (EncryptedIoQueue *queue) +{ + ASSERT (queue->Suspended); + + queue->Suspended = FALSE; + KeSetEvent (&queue->QueueResumedEvent, IO_DISK_INCREMENT, FALSE); + + return STATUS_SUCCESS; +} + + +NTSTATUS EncryptedIoQueueStart (EncryptedIoQueue *queue) +{ + NTSTATUS status; + EncryptedIoQueueBuffer *buffer; + int i; + + queue->StartPending = TRUE; + queue->ThreadExitRequested = FALSE; + + queue->OutstandingIoCount = 0; + queue->IoThreadPendingRequestCount = 0; + + queue->FirstPoolBuffer = NULL; + KeInitializeMutex (&queue->BufferPoolMutex, 0); + + KeInitializeEvent (&queue->NoOutstandingIoEvent, SynchronizationEvent, FALSE); + KeInitializeEvent (&queue->PoolBufferFreeEvent, SynchronizationEvent, FALSE); + KeInitializeEvent (&queue->QueueResumedEvent, SynchronizationEvent, FALSE); + + queue->FragmentBufferA = TCalloc (TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE); + if (!queue->FragmentBufferA) + goto noMemory; + + queue->FragmentBufferB = TCalloc (TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE); + if (!queue->FragmentBufferB) + goto noMemory; + + KeInitializeEvent (&queue->FragmentBufferAFreeEvent, SynchronizationEvent, TRUE); + KeInitializeEvent (&queue->FragmentBufferBFreeEvent, SynchronizationEvent, TRUE); + + queue->ReadAheadBufferValid = FALSE; + queue->ReadAheadBuffer = TCalloc (TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE); + if (!queue->ReadAheadBuffer) + goto noMemory; + + // Preallocate buffers + for (i = 0; i < TC_ENC_IO_QUEUE_PREALLOCATED_IO_REQUEST_COUNT; ++i) + { + if (i < TC_ENC_IO_QUEUE_PREALLOCATED_ITEM_COUNT && !GetPoolBuffer (queue, sizeof (EncryptedIoQueueItem))) + goto noMemory; + + if (!GetPoolBuffer (queue, sizeof (EncryptedIoRequest))) + goto noMemory; + } + + for (buffer = queue->FirstPoolBuffer; buffer != NULL; buffer = buffer->NextBuffer) + { + buffer->InUse = FALSE; + } + + // Main thread + InitializeListHead (&queue->MainThreadQueue); + KeInitializeSpinLock (&queue->MainThreadQueueLock); + KeInitializeEvent (&queue->MainThreadQueueNotEmptyEvent, SynchronizationEvent, FALSE); + + status = TCStartThread (MainThreadProc, queue, &queue->MainThread); + if (!NT_SUCCESS (status)) + goto err; + + // IO thread + InitializeListHead (&queue->IoThreadQueue); + KeInitializeSpinLock (&queue->IoThreadQueueLock); + KeInitializeEvent (&queue->IoThreadQueueNotEmptyEvent, SynchronizationEvent, FALSE); + + status = TCStartThread (IoThreadProc, queue, &queue->IoThread); + if (!NT_SUCCESS (status)) + { + queue->ThreadExitRequested = TRUE; + TCStopThread (queue->MainThread, &queue->MainThreadQueueNotEmptyEvent); + goto err; + } + + // Completion thread + InitializeListHead (&queue->CompletionThreadQueue); + KeInitializeSpinLock (&queue->CompletionThreadQueueLock); + KeInitializeEvent (&queue->CompletionThreadQueueNotEmptyEvent, SynchronizationEvent, FALSE); + + status = TCStartThread (CompletionThreadProc, queue, &queue->CompletionThread); + if (!NT_SUCCESS (status)) + { + queue->ThreadExitRequested = TRUE; + TCStopThread (queue->MainThread, &queue->MainThreadQueueNotEmptyEvent); + TCStopThread (queue->IoThread, &queue->IoThreadQueueNotEmptyEvent); + goto err; + } + +#ifdef TC_TRACE_IO_QUEUE + GetElapsedTimeInit (&queue->LastPerformanceCounter); +#endif + + queue->StopPending = FALSE; + queue->StartPending = FALSE; + + Dump ("Queue started\n"); + return STATUS_SUCCESS; + +noMemory: + status = STATUS_INSUFFICIENT_RESOURCES; + +err: + if (queue->FragmentBufferA) + TCfree (queue->FragmentBufferA); + if (queue->FragmentBufferB) + TCfree (queue->FragmentBufferB); + if (queue->ReadAheadBuffer) + TCfree (queue->ReadAheadBuffer); + + FreePoolBuffers (queue); + + queue->StartPending = FALSE; + return status; +} + + +NTSTATUS EncryptedIoQueueStop (EncryptedIoQueue *queue) +{ + ASSERT (!queue->StopPending); + queue->StopPending = TRUE; + + while (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) > 0) + { + KeWaitForSingleObject (&queue->NoOutstandingIoEvent, Executive, KernelMode, FALSE, NULL); + } + + Dump ("Queue stopping out=%d\n", queue->OutstandingIoCount); + + queue->ThreadExitRequested = TRUE; + + TCStopThread (queue->MainThread, &queue->MainThreadQueueNotEmptyEvent); + TCStopThread (queue->IoThread, &queue->IoThreadQueueNotEmptyEvent); + TCStopThread (queue->CompletionThread, &queue->CompletionThreadQueueNotEmptyEvent); + + TCfree (queue->FragmentBufferA); + TCfree (queue->FragmentBufferB); + TCfree (queue->ReadAheadBuffer); + + FreePoolBuffers (queue); + + Dump ("Queue stopped out=%d\n", queue->OutstandingIoCount); + return STATUS_SUCCESS; +} diff --git a/src/Driver/EncryptedIoQueue.h b/src/Driver/EncryptedIoQueue.h index de9fce07..044009b7 100644 --- a/src/Driver/EncryptedIoQueue.h +++ b/src/Driver/EncryptedIoQueue.h @@ -1,165 +1,165 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_DRIVER_ENCRYPTED_IO_QUEUE -#define TC_HEADER_DRIVER_ENCRYPTED_IO_QUEUE - -#include "TCdefs.h" -#include "Apidrvr.h" - -#if 0 -# define TC_TRACE_IO_QUEUE -#endif - -#define TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE (256 * 1024) - -#define TC_ENC_IO_QUEUE_PREALLOCATED_ITEM_COUNT 8 -#define TC_ENC_IO_QUEUE_PREALLOCATED_IO_REQUEST_COUNT 16 - - -typedef struct EncryptedIoQueueBufferStruct -{ - struct EncryptedIoQueueBufferStruct *NextBuffer; - - void *Address; - ULONG Size; - BOOL InUse; - -} EncryptedIoQueueBuffer; - - -typedef struct -{ - PDEVICE_OBJECT DeviceObject; - - KMUTEX BufferPoolMutex; - EncryptedIoQueueBuffer *FirstPoolBuffer; - - CRYPTO_INFO *CryptoInfo; - - // File-handle-based IO - HANDLE HostFileHandle; - int64 VirtualDeviceLength; - SECURITY_CLIENT_CONTEXT *SecurityClientContext; - - // Filter device - BOOL IsFilterDevice; - PDEVICE_OBJECT LowerDeviceObject; - int64 EncryptedAreaStart; - volatile int64 EncryptedAreaEnd; - volatile BOOL EncryptedAreaEndUpdatePending; - BOOL RemapEncryptedArea; - int64 RemappedAreaOffset; - int64 RemappedAreaDataUnitOffset; - IO_REMOVE_LOCK RemoveLock; - - // Main tread - PKTHREAD MainThread; - LIST_ENTRY MainThreadQueue; - KSPIN_LOCK MainThreadQueueLock; - KEVENT MainThreadQueueNotEmptyEvent; - - // IO thread - PKTHREAD IoThread; - LIST_ENTRY IoThreadQueue; - KSPIN_LOCK IoThreadQueueLock; - KEVENT IoThreadQueueNotEmptyEvent; - - // Completion thread - PKTHREAD CompletionThread; - LIST_ENTRY CompletionThreadQueue; - KSPIN_LOCK CompletionThreadQueueLock; - KEVENT CompletionThreadQueueNotEmptyEvent; - - // Fragment buffers - byte *FragmentBufferA; - byte *FragmentBufferB; - KEVENT FragmentBufferAFreeEvent; - KEVENT FragmentBufferBFreeEvent; - - // Read-ahead buffer - BOOL ReadAheadBufferValid; - LARGE_INTEGER LastReadOffset; - ULONG LastReadLength; - LARGE_INTEGER ReadAheadOffset; - ULONG ReadAheadLength; - byte *ReadAheadBuffer; - LARGE_INTEGER MaxReadAheadOffset; - - LONG OutstandingIoCount; - KEVENT NoOutstandingIoEvent; - LONG IoThreadPendingRequestCount; - - KEVENT PoolBufferFreeEvent; - - __int64 TotalBytesRead; - __int64 TotalBytesWritten; - - volatile BOOL StartPending; - volatile BOOL ThreadExitRequested; - - volatile BOOL Suspended; - volatile BOOL SuspendPending; - volatile BOOL StopPending; - - KEVENT QueueResumedEvent; - -#ifdef TC_TRACE_IO_QUEUE - LARGE_INTEGER LastPerformanceCounter; -#endif - -} EncryptedIoQueue; - - -typedef struct -{ - EncryptedIoQueue *Queue; - PIRP OriginalIrp; - BOOL Write; - ULONG OriginalLength; - LARGE_INTEGER OriginalOffset; - NTSTATUS Status; - -#ifdef TC_TRACE_IO_QUEUE - LARGE_INTEGER OriginalIrpOffset; -#endif - -} EncryptedIoQueueItem; - - -typedef struct -{ - EncryptedIoQueueItem *Item; - - BOOL CompleteOriginalIrp; - LARGE_INTEGER Offset; - ULONG Length; - int64 EncryptedOffset; - ULONG EncryptedLength; - byte *Data; - byte *OrigDataBufferFragment; - - LIST_ENTRY ListEntry; - LIST_ENTRY CompletionListEntry; -} EncryptedIoRequest; - - -NTSTATUS EncryptedIoQueueAddIrp (EncryptedIoQueue *queue, PIRP irp); -BOOL EncryptedIoQueueIsRunning (EncryptedIoQueue *queue); -BOOL EncryptedIoQueueIsSuspended (EncryptedIoQueue *queue); -NTSTATUS EncryptedIoQueueResumeFromHold (EncryptedIoQueue *queue); -NTSTATUS EncryptedIoQueueStart (EncryptedIoQueue *queue); -NTSTATUS EncryptedIoQueueStop (EncryptedIoQueue *queue); -NTSTATUS EncryptedIoQueueHoldWhenIdle (EncryptedIoQueue *queue, int64 timeout); - - -#endif // TC_HEADER_DRIVER_ENCRYPTED_IO_QUEUE +/* + 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. +*/ + +#ifndef TC_HEADER_DRIVER_ENCRYPTED_IO_QUEUE +#define TC_HEADER_DRIVER_ENCRYPTED_IO_QUEUE + +#include "TCdefs.h" +#include "Apidrvr.h" + +#if 0 +# define TC_TRACE_IO_QUEUE +#endif + +#define TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE (256 * 1024) + +#define TC_ENC_IO_QUEUE_PREALLOCATED_ITEM_COUNT 8 +#define TC_ENC_IO_QUEUE_PREALLOCATED_IO_REQUEST_COUNT 16 + + +typedef struct EncryptedIoQueueBufferStruct +{ + struct EncryptedIoQueueBufferStruct *NextBuffer; + + void *Address; + ULONG Size; + BOOL InUse; + +} EncryptedIoQueueBuffer; + + +typedef struct +{ + PDEVICE_OBJECT DeviceObject; + + KMUTEX BufferPoolMutex; + EncryptedIoQueueBuffer *FirstPoolBuffer; + + CRYPTO_INFO *CryptoInfo; + + // File-handle-based IO + HANDLE HostFileHandle; + int64 VirtualDeviceLength; + SECURITY_CLIENT_CONTEXT *SecurityClientContext; + + // Filter device + BOOL IsFilterDevice; + PDEVICE_OBJECT LowerDeviceObject; + int64 EncryptedAreaStart; + volatile int64 EncryptedAreaEnd; + volatile BOOL EncryptedAreaEndUpdatePending; + BOOL RemapEncryptedArea; + int64 RemappedAreaOffset; + int64 RemappedAreaDataUnitOffset; + IO_REMOVE_LOCK RemoveLock; + + // Main tread + PKTHREAD MainThread; + LIST_ENTRY MainThreadQueue; + KSPIN_LOCK MainThreadQueueLock; + KEVENT MainThreadQueueNotEmptyEvent; + + // IO thread + PKTHREAD IoThread; + LIST_ENTRY IoThreadQueue; + KSPIN_LOCK IoThreadQueueLock; + KEVENT IoThreadQueueNotEmptyEvent; + + // Completion thread + PKTHREAD CompletionThread; + LIST_ENTRY CompletionThreadQueue; + KSPIN_LOCK CompletionThreadQueueLock; + KEVENT CompletionThreadQueueNotEmptyEvent; + + // Fragment buffers + byte *FragmentBufferA; + byte *FragmentBufferB; + KEVENT FragmentBufferAFreeEvent; + KEVENT FragmentBufferBFreeEvent; + + // Read-ahead buffer + BOOL ReadAheadBufferValid; + LARGE_INTEGER LastReadOffset; + ULONG LastReadLength; + LARGE_INTEGER ReadAheadOffset; + ULONG ReadAheadLength; + byte *ReadAheadBuffer; + LARGE_INTEGER MaxReadAheadOffset; + + LONG OutstandingIoCount; + KEVENT NoOutstandingIoEvent; + LONG IoThreadPendingRequestCount; + + KEVENT PoolBufferFreeEvent; + + __int64 TotalBytesRead; + __int64 TotalBytesWritten; + + volatile BOOL StartPending; + volatile BOOL ThreadExitRequested; + + volatile BOOL Suspended; + volatile BOOL SuspendPending; + volatile BOOL StopPending; + + KEVENT QueueResumedEvent; + +#ifdef TC_TRACE_IO_QUEUE + LARGE_INTEGER LastPerformanceCounter; +#endif + +} EncryptedIoQueue; + + +typedef struct +{ + EncryptedIoQueue *Queue; + PIRP OriginalIrp; + BOOL Write; + ULONG OriginalLength; + LARGE_INTEGER OriginalOffset; + NTSTATUS Status; + +#ifdef TC_TRACE_IO_QUEUE + LARGE_INTEGER OriginalIrpOffset; +#endif + +} EncryptedIoQueueItem; + + +typedef struct +{ + EncryptedIoQueueItem *Item; + + BOOL CompleteOriginalIrp; + LARGE_INTEGER Offset; + ULONG Length; + int64 EncryptedOffset; + ULONG EncryptedLength; + byte *Data; + byte *OrigDataBufferFragment; + + LIST_ENTRY ListEntry; + LIST_ENTRY CompletionListEntry; +} EncryptedIoRequest; + + +NTSTATUS EncryptedIoQueueAddIrp (EncryptedIoQueue *queue, PIRP irp); +BOOL EncryptedIoQueueIsRunning (EncryptedIoQueue *queue); +BOOL EncryptedIoQueueIsSuspended (EncryptedIoQueue *queue); +NTSTATUS EncryptedIoQueueResumeFromHold (EncryptedIoQueue *queue); +NTSTATUS EncryptedIoQueueStart (EncryptedIoQueue *queue); +NTSTATUS EncryptedIoQueueStop (EncryptedIoQueue *queue); +NTSTATUS EncryptedIoQueueHoldWhenIdle (EncryptedIoQueue *queue, int64 timeout); + + +#endif // TC_HEADER_DRIVER_ENCRYPTED_IO_QUEUE diff --git a/src/Driver/Makefile b/src/Driver/Makefile index 53b9a3d6..5acbbd24 100644 --- a/src/Driver/Makefile +++ b/src/Driver/Makefile @@ -1 +1 @@ -!INCLUDE $(NTMAKEENV)\makefile.def +!INCLUDE $(NTMAKEENV)\makefile.def diff --git a/src/Driver/Ntdriver.c b/src/Driver/Ntdriver.c index eeea7815..c771b3ce 100644 --- a/src/Driver/Ntdriver.c +++ b/src/Driver/Ntdriver.c @@ -1,3563 +1,3563 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "TCdefs.h" -#include -#include "Crypto.h" -#include "Fat.h" -#include "Tests.h" -#include "cpu.h" - -#include "Apidrvr.h" -#include "Boot/Windows/BootDefs.h" -#include "EncryptedIoQueue.h" -#include "EncryptionThreadPool.h" -#include "Ntdriver.h" -#include "Ntvol.h" -#include "DriveFilter.h" -#include "DumpFilter.h" -#include "Cache.h" -#include "Volumes.h" -#include "VolumeFilter.h" - -#include -#include -#include -#include -#include - -#include -#include - -/* Init section, which is thrown away as soon as DriverEntry returns */ -#pragma alloc_text(INIT,DriverEntry) -#pragma alloc_text(INIT,TCCreateRootDeviceObject) - -PDRIVER_OBJECT TCDriverObject; -PDEVICE_OBJECT RootDeviceObject = NULL; -static KMUTEX RootDeviceControlMutex; -BOOL DriverShuttingDown = FALSE; -BOOL SelfTestsPassed; -int LastUniqueVolumeId; -ULONG OsMajorVersion = 0; -ULONG OsMinorVersion; -BOOL DriverUnloadDisabled = FALSE; -BOOL PortableMode = FALSE; -BOOL VolumeClassFilterRegistered = FALSE; -BOOL CacheBootPassword = FALSE; -BOOL CacheBootPim = FALSE; -BOOL NonAdminSystemFavoritesAccessDisabled = FALSE; -static size_t EncryptionThreadPoolFreeCpuCountLimit = 0; -static BOOL SystemFavoriteVolumeDirty = FALSE; -static BOOL PagingFileCreationPrevented = FALSE; -static BOOL EnableExtendedIoctlSupport = FALSE; - -PDEVICE_OBJECT VirtualVolumeDeviceObjects[MAX_MOUNTED_VOLUME_DRIVE_NUMBER + 1]; - - -NTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) -{ - PKEY_VALUE_PARTIAL_INFORMATION startKeyValue; - LONG version; - int i; - - Dump ("DriverEntry " TC_APP_NAME " " VERSION_STRING "\n"); - - DetectX86Features (); - - PsGetVersion (&OsMajorVersion, &OsMinorVersion, NULL, NULL); - - // Load dump filter if the main driver is already loaded - if (NT_SUCCESS (TCDeviceIoControl (NT_ROOT_PREFIX, TC_IOCTL_GET_DRIVER_VERSION, NULL, 0, &version, sizeof (version)))) - return DumpFilterEntry ((PFILTER_EXTENSION) DriverObject, (PFILTER_INITIALIZATION_DATA) RegistryPath); - - TCDriverObject = DriverObject; - memset (VirtualVolumeDeviceObjects, 0, sizeof (VirtualVolumeDeviceObjects)); - - ReadRegistryConfigFlags (TRUE); - EncryptionThreadPoolStart (EncryptionThreadPoolFreeCpuCountLimit); - SelfTestsPassed = AutoTestAlgorithms(); - - // Enable device class filters and load boot arguments if the driver is set to start at system boot - - if (NT_SUCCESS (TCReadRegistryKey (RegistryPath, L"Start", &startKeyValue))) - { - if (startKeyValue->Type == REG_DWORD && *((uint32 *) startKeyValue->Data) == SERVICE_BOOT_START) - { - if (!SelfTestsPassed) - TC_BUG_CHECK (STATUS_INVALID_PARAMETER); - - LoadBootArguments(); - VolumeClassFilterRegistered = IsVolumeClassFilterRegistered(); - - DriverObject->DriverExtension->AddDevice = DriverAddDevice; - } - - TCfree (startKeyValue); - } - - for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; ++i) - { - DriverObject->MajorFunction[i] = TCDispatchQueueIRP; - } - - DriverObject->DriverUnload = TCUnloadDriver; - return TCCreateRootDeviceObject (DriverObject); -} - - -NTSTATUS DriverAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo) -{ -#ifdef DEBUG - char nameInfoBuffer[128]; - POBJECT_NAME_INFORMATION nameInfo = (POBJECT_NAME_INFORMATION) nameInfoBuffer; - ULONG nameInfoSize; - Dump ("AddDevice pdo=%p type=%x name=%ws\n", pdo, pdo->DeviceType, NT_SUCCESS (ObQueryNameString (pdo, nameInfo, sizeof (nameInfoBuffer), &nameInfoSize)) ? nameInfo->Name.Buffer : L"?"); -#endif - - if (VolumeClassFilterRegistered && BootArgsValid && BootArgs.HiddenSystemPartitionStart != 0) - { - PWSTR interfaceLinks = NULL; - if (NT_SUCCESS (IoGetDeviceInterfaces (&GUID_DEVINTERFACE_VOLUME, pdo, DEVICE_INTERFACE_INCLUDE_NONACTIVE, &interfaceLinks)) && interfaceLinks) - { - if (interfaceLinks[0] != UNICODE_NULL) - { - Dump ("Volume pdo=%p interface=%ws\n", pdo, interfaceLinks); - ExFreePool (interfaceLinks); - - return VolumeFilterAddDevice (driverObject, pdo); - } - - ExFreePool (interfaceLinks); - } - } - - return DriveFilterAddDevice (driverObject, pdo); -} - - -// Dumps a memory region to debug output -void DumpMemory (void *mem, int size) -{ - unsigned char str[20]; - unsigned char *m = mem; - int i,j; - - for (j = 0; j < size / 8; j++) - { - memset (str,0,sizeof str); - for (i = 0; i < 8; i++) - { - if (m[i] > ' ' && m[i] <= '~') - str[i]=m[i]; - else - str[i]='.'; - } - - Dump ("0x%08p %02x %02x %02x %02x %02x %02x %02x %02x %s\n", - m, m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], str); - - m+=8; - } -} - - -BOOL ValidateIOBufferSize (PIRP irp, size_t requiredBufferSize, ValidateIOBufferSizeType type) -{ - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (irp); - BOOL input = (type == ValidateInput || type == ValidateInputOutput); - BOOL output = (type == ValidateOutput || type == ValidateInputOutput); - - if ((input && irpSp->Parameters.DeviceIoControl.InputBufferLength < requiredBufferSize) - || (output && irpSp->Parameters.DeviceIoControl.OutputBufferLength < requiredBufferSize)) - { - Dump ("STATUS_BUFFER_TOO_SMALL ioctl=0x%x,%d in=%d out=%d reqsize=%d insize=%d outsize=%d\n", (int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16), (int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2), input, output, requiredBufferSize, irpSp->Parameters.DeviceIoControl.InputBufferLength, irpSp->Parameters.DeviceIoControl.OutputBufferLength); - - irp->IoStatus.Status = STATUS_BUFFER_TOO_SMALL; - irp->IoStatus.Information = 0; - return FALSE; - } - - if (!input && output) - memset (irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength); - - return TRUE; -} - - -PDEVICE_OBJECT GetVirtualVolumeDeviceObject (int driveNumber) -{ - if (driveNumber < MIN_MOUNTED_VOLUME_DRIVE_NUMBER || driveNumber > MAX_MOUNTED_VOLUME_DRIVE_NUMBER) - return NULL; - - return VirtualVolumeDeviceObjects[driveNumber]; -} - - -/* TCDispatchQueueIRP queues any IRP's so that they can be processed later - by the thread -- or in some cases handles them immediately! */ -NTSTATUS TCDispatchQueueIRP (PDEVICE_OBJECT DeviceObject, PIRP Irp) -{ - PEXTENSION Extension = (PEXTENSION) DeviceObject->DeviceExtension; - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); - NTSTATUS ntStatus; - -#ifdef _DEBUG - if (irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL && (Extension->bRootDevice || Extension->IsVolumeDevice)) - { - switch (irpSp->Parameters.DeviceIoControl.IoControlCode) - { - case TC_IOCTL_GET_MOUNTED_VOLUMES: - case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: - case TC_IOCTL_GET_PORTABLE_MODE_STATUS: - case TC_IOCTL_SET_PORTABLE_MODE_STATUS: - case TC_IOCTL_OPEN_TEST: - case TC_IOCTL_GET_RESOLVED_SYMLINK: - case TC_IOCTL_GET_DEVICE_REFCOUNT: - case TC_IOCTL_GET_DRIVE_PARTITION_INFO: - case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: - case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: - case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS: - case TC_IOCTL_GET_WARNING_FLAGS: - case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: - case IOCTL_DISK_CHECK_VERIFY: - break; - - default: - Dump ("%ls (0x%x %d)\n", - TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode), - (int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16), - (int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2)); - } - } -#endif - - if (!Extension->bRootDevice) - { - // Drive filter IRP - if (Extension->IsDriveFilterDevice) - return DriveFilterDispatchIrp (DeviceObject, Irp); - - // Volume filter IRP - if (Extension->IsVolumeFilterDevice) - return VolumeFilterDispatchIrp (DeviceObject, Irp); - } - - switch (irpSp->MajorFunction) - { - case IRP_MJ_CLOSE: - case IRP_MJ_CREATE: - case IRP_MJ_CLEANUP: - return COMPLETE_IRP (DeviceObject, Irp, STATUS_SUCCESS, 0); - - case IRP_MJ_SHUTDOWN: - if (Extension->bRootDevice) - { - Dump ("Driver shutting down\n"); - DriverShuttingDown = TRUE; - - if (EncryptionSetupThread) - while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES); - - if (DecoySystemWipeThread) - while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES); - - OnShutdownPending(); - } - - return COMPLETE_IRP (DeviceObject, Irp, STATUS_SUCCESS, 0); - - case IRP_MJ_FLUSH_BUFFERS: - case IRP_MJ_READ: - case IRP_MJ_WRITE: - case IRP_MJ_DEVICE_CONTROL: - - if (Extension->bRootDevice) - { - if (irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL) - { - NTSTATUS status = KeWaitForMutexObject (&RootDeviceControlMutex, Executive, KernelMode, FALSE, NULL); - if (!NT_SUCCESS (status)) - return status; - - status = ProcessMainDeviceControlIrp (DeviceObject, Extension, Irp); - - KeReleaseMutex (&RootDeviceControlMutex, FALSE); - return status; - } - break; - } - - if (Extension->bShuttingDown) - { - Dump ("Device %d shutting down: STATUS_DELETE_PENDING\n", Extension->nDosDriveNo); - return TCCompleteDiskIrp (Irp, STATUS_DELETE_PENDING, 0); - } - - if (Extension->bRemovable - && (DeviceObject->Flags & DO_VERIFY_VOLUME) - && !(irpSp->Flags & SL_OVERRIDE_VERIFY_VOLUME) - && irpSp->MajorFunction != IRP_MJ_FLUSH_BUFFERS) - { - Dump ("Removable device %d has DO_VERIFY_VOLUME flag: STATUS_DEVICE_NOT_READY\n", Extension->nDosDriveNo); - return TCCompleteDiskIrp (Irp, STATUS_DEVICE_NOT_READY, 0); - } - - switch (irpSp->MajorFunction) - { - case IRP_MJ_READ: - case IRP_MJ_WRITE: - ntStatus = EncryptedIoQueueAddIrp (&Extension->Queue, Irp); - - if (ntStatus != STATUS_PENDING) - TCCompleteDiskIrp (Irp, ntStatus, 0); - - return ntStatus; - - case IRP_MJ_DEVICE_CONTROL: - ntStatus = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); - if (!NT_SUCCESS (ntStatus)) - return TCCompleteIrp (Irp, ntStatus, 0); - - IoMarkIrpPending (Irp); - - ExInterlockedInsertTailList (&Extension->ListEntry, &Irp->Tail.Overlay.ListEntry, &Extension->ListSpinLock); - KeReleaseSemaphore (&Extension->RequestSemaphore, IO_DISK_INCREMENT, 1, FALSE); - - return STATUS_PENDING; - - case IRP_MJ_FLUSH_BUFFERS: - return TCCompleteDiskIrp (Irp, STATUS_SUCCESS, 0); - } - - break; - - case IRP_MJ_PNP: - if (!Extension->bRootDevice - && Extension->IsVolumeDevice - && irpSp->MinorFunction == IRP_MN_DEVICE_USAGE_NOTIFICATION - && irpSp->Parameters.UsageNotification.Type == DeviceUsageTypePaging - && irpSp->Parameters.UsageNotification.InPath) - { - PagingFileCreationPrevented = TRUE; - return TCCompleteIrp (Irp, STATUS_UNSUCCESSFUL, 0); - } - break; - } - - return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); -} - -NTSTATUS TCCreateRootDeviceObject (PDRIVER_OBJECT DriverObject) -{ - UNICODE_STRING Win32NameString, ntUnicodeString; - WCHAR dosname[32], ntname[32]; - PDEVICE_OBJECT DeviceObject; - NTSTATUS ntStatus; - BOOL *bRootExtension; - - Dump ("TCCreateRootDeviceObject BEGIN\n"); - ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL); - - RtlStringCbCopyW (dosname, sizeof(dosname),(LPWSTR) DOS_ROOT_PREFIX); - RtlStringCbCopyW (ntname, sizeof(ntname),(LPWSTR) NT_ROOT_PREFIX); - RtlInitUnicodeString (&ntUnicodeString, ntname); - RtlInitUnicodeString (&Win32NameString, dosname); - - Dump ("Creating root device nt=%ls dos=%ls\n", ntname, dosname); - - ntStatus = IoCreateDevice ( - DriverObject, - sizeof (BOOL), - &ntUnicodeString, - FILE_DEVICE_UNKNOWN, - FILE_DEVICE_SECURE_OPEN, - FALSE, - &DeviceObject); - - if (!NT_SUCCESS (ntStatus)) - { - Dump ("TCCreateRootDeviceObject NTSTATUS = 0x%08x END\n", ntStatus); - return ntStatus;/* Failed to create DeviceObject */ - } - - DeviceObject->Flags |= DO_DIRECT_IO; - DeviceObject->AlignmentRequirement = FILE_WORD_ALIGNMENT; - - /* Setup the device extension */ - bRootExtension = (BOOL *) DeviceObject->DeviceExtension; - *bRootExtension = TRUE; - - KeInitializeMutex (&RootDeviceControlMutex, 0); - - ntStatus = IoCreateSymbolicLink (&Win32NameString, &ntUnicodeString); - - if (!NT_SUCCESS (ntStatus)) - { - Dump ("TCCreateRootDeviceObject NTSTATUS = 0x%08x END\n", ntStatus); - IoDeleteDevice (DeviceObject); - return ntStatus; - } - - IoRegisterShutdownNotification (DeviceObject); - RootDeviceObject = DeviceObject; - - Dump ("TCCreateRootDeviceObject STATUS_SUCCESS END\n"); - return STATUS_SUCCESS; -} - -NTSTATUS TCCreateDeviceObject (PDRIVER_OBJECT DriverObject, - PDEVICE_OBJECT * ppDeviceObject, - MOUNT_STRUCT * mount) -{ - UNICODE_STRING ntUnicodeString; - WCHAR ntname[32]; - PEXTENSION Extension; - NTSTATUS ntStatus; - ULONG devChars = 0; -#if defined (DEBUG) - WCHAR dosname[32]; -#endif - - Dump ("TCCreateDeviceObject BEGIN\n"); - ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL); - - TCGetNTNameFromNumber (ntname, sizeof(ntname),mount->nDosDriveNo); - RtlInitUnicodeString (&ntUnicodeString, ntname); -#if defined (DEBUG) - TCGetDosNameFromNumber (dosname, sizeof(dosname),mount->nDosDriveNo, DeviceNamespaceDefault); -#endif - - devChars = FILE_DEVICE_SECURE_OPEN; - devChars |= mount->bMountReadOnly ? FILE_READ_ONLY_DEVICE : 0; - devChars |= mount->bMountRemovable ? FILE_REMOVABLE_MEDIA : 0; - - Dump ("Creating device nt=%ls dos=%ls\n", ntname, dosname); - - ntStatus = IoCreateDevice ( - DriverObject, /* Our Driver Object */ - sizeof (EXTENSION), /* Size of state information */ - &ntUnicodeString, /* Device name "\Device\Name" */ - FILE_DEVICE_DISK, /* Device type */ - devChars, /* Device characteristics */ - FALSE, /* Exclusive device */ - ppDeviceObject); /* Returned ptr to Device Object */ - - if (!NT_SUCCESS (ntStatus)) - { - Dump ("TCCreateDeviceObject NTSTATUS = 0x%08x END\n", ntStatus); - return ntStatus;/* Failed to create DeviceObject */ - } - /* Initialize device object and extension. */ - - (*ppDeviceObject)->Flags |= DO_DIRECT_IO; - (*ppDeviceObject)->StackSize += 6; // Reduce occurrence of NO_MORE_IRP_STACK_LOCATIONS bug check caused by buggy drivers - - /* Setup the device extension */ - Extension = (PEXTENSION) (*ppDeviceObject)->DeviceExtension; - memset (Extension, 0, sizeof (EXTENSION)); - - Extension->IsVolumeDevice = TRUE; - Extension->nDosDriveNo = mount->nDosDriveNo; - Extension->bRemovable = mount->bMountRemovable; - Extension->PartitionInInactiveSysEncScope = mount->bPartitionInInactiveSysEncScope; - Extension->SystemFavorite = mount->SystemFavorite; - - KeInitializeEvent (&Extension->keCreateEvent, SynchronizationEvent, FALSE); - KeInitializeSemaphore (&Extension->RequestSemaphore, 0L, MAXLONG); - KeInitializeSpinLock (&Extension->ListSpinLock); - InitializeListHead (&Extension->ListEntry); - IoInitializeRemoveLock (&Extension->Queue.RemoveLock, 'LRCV', 0, 0); - - VirtualVolumeDeviceObjects[mount->nDosDriveNo] = *ppDeviceObject; - - Dump ("TCCreateDeviceObject STATUS_SUCCESS END\n"); - - return STATUS_SUCCESS; -} - - -BOOL RootDeviceControlMutexAcquireNoWait () -{ - NTSTATUS status; - LARGE_INTEGER timeout; - timeout.QuadPart = 0; - - status = KeWaitForMutexObject (&RootDeviceControlMutex, Executive, KernelMode, FALSE, &timeout); - return NT_SUCCESS (status) && status != STATUS_TIMEOUT; -} - - -void RootDeviceControlMutexRelease () -{ - KeReleaseMutex (&RootDeviceControlMutex, FALSE); -} - - -NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp) -{ - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); - - switch (irpSp->Parameters.DeviceIoControl.IoControlCode) - { - - case IOCTL_MOUNTDEV_QUERY_DEVICE_NAME: - if (!ValidateIOBufferSize (Irp, sizeof (MOUNTDEV_NAME), ValidateOutput)) - { - Irp->IoStatus.Information = sizeof (MOUNTDEV_NAME); - Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; - } - else - { - ULONG outLength; - UNICODE_STRING ntUnicodeString; - WCHAR ntName[256]; - PMOUNTDEV_NAME outputBuffer = (PMOUNTDEV_NAME) Irp->AssociatedIrp.SystemBuffer; - - TCGetNTNameFromNumber (ntName, sizeof(ntName),Extension->nDosDriveNo); - RtlInitUnicodeString (&ntUnicodeString, ntName); - - outputBuffer->NameLength = ntUnicodeString.Length; - outLength = ntUnicodeString.Length + sizeof(USHORT); - - if (irpSp->Parameters.DeviceIoControl.OutputBufferLength < outLength) - { - Irp->IoStatus.Information = sizeof (MOUNTDEV_NAME); - Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; - - break; - } - - RtlCopyMemory ((PCHAR)outputBuffer->Name,ntUnicodeString.Buffer, ntUnicodeString.Length); - - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = outLength; - - Dump ("name = %ls\n",ntName); - } - break; - - case IOCTL_MOUNTDEV_QUERY_UNIQUE_ID: - if (!ValidateIOBufferSize (Irp, sizeof (MOUNTDEV_UNIQUE_ID), ValidateOutput)) - { - Irp->IoStatus.Information = sizeof (MOUNTDEV_UNIQUE_ID); - Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; - } - else - { - ULONG outLength; - UCHAR volId[128], tmp[] = { 0,0 }; - PMOUNTDEV_UNIQUE_ID outputBuffer = (PMOUNTDEV_UNIQUE_ID) Irp->AssociatedIrp.SystemBuffer; - - RtlStringCbCopyA (volId, sizeof(volId),TC_UNIQUE_ID_PREFIX); - tmp[0] = 'A' + (UCHAR) Extension->nDosDriveNo; - RtlStringCbCatA (volId, sizeof(volId),tmp); - - outputBuffer->UniqueIdLength = (USHORT) strlen (volId); - outLength = (ULONG) (strlen (volId) + sizeof (USHORT)); - - if (irpSp->Parameters.DeviceIoControl.OutputBufferLength < outLength) - { - Irp->IoStatus.Information = sizeof (MOUNTDEV_UNIQUE_ID); - Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; - break; - } - - RtlCopyMemory ((PCHAR)outputBuffer->UniqueId, volId, strlen (volId)); - - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = outLength; - - Dump ("id = %s\n",volId); - } - break; - - case IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME: - { - ULONG outLength; - UNICODE_STRING ntUnicodeString; - WCHAR ntName[256]; - PMOUNTDEV_SUGGESTED_LINK_NAME outputBuffer = (PMOUNTDEV_SUGGESTED_LINK_NAME) Irp->AssociatedIrp.SystemBuffer; - - if (!ValidateIOBufferSize (Irp, sizeof (MOUNTDEV_SUGGESTED_LINK_NAME), ValidateOutput)) - { - Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - Irp->IoStatus.Information = 0; - break; - } - - TCGetDosNameFromNumber (ntName, sizeof(ntName),Extension->nDosDriveNo, DeviceNamespaceDefault); - RtlInitUnicodeString (&ntUnicodeString, ntName); - - outLength = FIELD_OFFSET(MOUNTDEV_SUGGESTED_LINK_NAME,Name) + ntUnicodeString.Length; - - outputBuffer->UseOnlyIfThereAreNoOtherLinks = FALSE; - outputBuffer->NameLength = ntUnicodeString.Length; - - if(irpSp->Parameters.DeviceIoControl.OutputBufferLength < outLength) - { - Irp->IoStatus.Information = sizeof (MOUNTDEV_SUGGESTED_LINK_NAME); - Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; - break; - } - - RtlCopyMemory ((PCHAR)outputBuffer->Name,ntUnicodeString.Buffer, ntUnicodeString.Length); - - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = outLength; - - Dump ("link = %ls\n",ntName); - } - break; - - case IOCTL_DISK_GET_MEDIA_TYPES: - case IOCTL_DISK_GET_DRIVE_GEOMETRY: - /* Return the drive geometry for the disk. Note that we - return values which were made up to suit the disk size. */ - if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY), ValidateOutput)) - { - PDISK_GEOMETRY outputBuffer = (PDISK_GEOMETRY) - Irp->AssociatedIrp.SystemBuffer; - - outputBuffer->MediaType = Extension->bRemovable ? RemovableMedia : FixedMedia; - outputBuffer->Cylinders.QuadPart = Extension->NumberOfCylinders; - outputBuffer->TracksPerCylinder = Extension->TracksPerCylinder; - outputBuffer->SectorsPerTrack = Extension->SectorsPerTrack; - outputBuffer->BytesPerSector = Extension->BytesPerSector; - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (DISK_GEOMETRY); - } - break; - - case IOCTL_STORAGE_QUERY_PROPERTY: - if (EnableExtendedIoctlSupport) - { - if (ValidateIOBufferSize (Irp, sizeof (STORAGE_PROPERTY_QUERY), ValidateInput)) - { - PSTORAGE_PROPERTY_QUERY pStoragePropQuery = (PSTORAGE_PROPERTY_QUERY) Irp->AssociatedIrp.SystemBuffer; - STORAGE_QUERY_TYPE type = pStoragePropQuery->QueryType; - - /* return error if an unsupported type is encountered */ - Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; - Irp->IoStatus.Information = 0; - - if ( (pStoragePropQuery->PropertyId == StorageAccessAlignmentProperty) - || (pStoragePropQuery->PropertyId == StorageDeviceProperty) - ) - { - if (type == PropertyExistsQuery) - { - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = 0; - } - else if (type == PropertyStandardQuery) - { - switch (pStoragePropQuery->PropertyId) - { - case StorageDeviceProperty: - { - if (ValidateIOBufferSize (Irp, sizeof (STORAGE_DEVICE_DESCRIPTOR), ValidateOutput)) - { - PSTORAGE_DEVICE_DESCRIPTOR outputBuffer = (PSTORAGE_DEVICE_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; - - outputBuffer->Version = sizeof(STORAGE_DEVICE_DESCRIPTOR); - outputBuffer->Size = sizeof(STORAGE_DEVICE_DESCRIPTOR); - outputBuffer->DeviceType = FILE_DEVICE_DISK; - outputBuffer->RemovableMedia = Extension->bRemovable? TRUE : FALSE; - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (STORAGE_DEVICE_DESCRIPTOR); - } - } - break; - case StorageAccessAlignmentProperty: - { - if (ValidateIOBufferSize (Irp, sizeof (STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR), ValidateOutput)) - { - PSTORAGE_ACCESS_ALIGNMENT_DESCRIPTOR outputBuffer = (PSTORAGE_ACCESS_ALIGNMENT_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; - - outputBuffer->Version = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR); - outputBuffer->Size = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR); - outputBuffer->BytesPerLogicalSector = Extension->BytesPerSector; - outputBuffer->BytesPerPhysicalSector = Extension->HostBytesPerPhysicalSector; - outputBuffer->BytesOffsetForSectorAlignment = Extension->BytesOffsetForSectorAlignment; - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR); - } - } - break; - } - } - } - } - } - else - return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); - - break; - - case IOCTL_DISK_GET_PARTITION_INFO: - if (ValidateIOBufferSize (Irp, sizeof (PARTITION_INFORMATION), ValidateOutput)) - { - PPARTITION_INFORMATION outputBuffer = (PPARTITION_INFORMATION) - Irp->AssociatedIrp.SystemBuffer; - - outputBuffer->PartitionType = Extension->PartitionType; - outputBuffer->BootIndicator = FALSE; - outputBuffer->RecognizedPartition = TRUE; - outputBuffer->RewritePartition = FALSE; - outputBuffer->StartingOffset.QuadPart = Extension->BytesPerSector; - outputBuffer->PartitionLength.QuadPart= Extension->DiskLength; - outputBuffer->HiddenSectors = 0; - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION); - } - break; - - case IOCTL_DISK_GET_PARTITION_INFO_EX: - if (ValidateIOBufferSize (Irp, sizeof (PARTITION_INFORMATION_EX), ValidateOutput)) - { - PPARTITION_INFORMATION_EX outputBuffer = (PPARTITION_INFORMATION_EX) Irp->AssociatedIrp.SystemBuffer; - - outputBuffer->PartitionStyle = PARTITION_STYLE_MBR; - outputBuffer->RewritePartition = FALSE; - outputBuffer->StartingOffset.QuadPart = Extension->BytesPerSector; - outputBuffer->PartitionLength.QuadPart= Extension->DiskLength; - outputBuffer->Mbr.PartitionType = Extension->PartitionType; - outputBuffer->Mbr.BootIndicator = FALSE; - outputBuffer->Mbr.RecognizedPartition = TRUE; - outputBuffer->Mbr.HiddenSectors = 0; - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION_EX); - } - break; - - case IOCTL_DISK_GET_DRIVE_LAYOUT: - if (ValidateIOBufferSize (Irp, sizeof (DRIVE_LAYOUT_INFORMATION), ValidateOutput)) - { - PDRIVE_LAYOUT_INFORMATION outputBuffer = (PDRIVE_LAYOUT_INFORMATION) - Irp->AssociatedIrp.SystemBuffer; - - outputBuffer->PartitionCount = 1; - outputBuffer->Signature = 0; - - outputBuffer->PartitionEntry->PartitionType = Extension->PartitionType; - outputBuffer->PartitionEntry->BootIndicator = FALSE; - outputBuffer->PartitionEntry->RecognizedPartition = TRUE; - outputBuffer->PartitionEntry->RewritePartition = FALSE; - outputBuffer->PartitionEntry->StartingOffset.QuadPart = Extension->BytesPerSector; - outputBuffer->PartitionEntry->PartitionLength.QuadPart = Extension->DiskLength; - outputBuffer->PartitionEntry->HiddenSectors = 0; - - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION); - } - break; - - case IOCTL_DISK_GET_LENGTH_INFO: - if (!ValidateIOBufferSize (Irp, sizeof (GET_LENGTH_INFORMATION), ValidateOutput)) - { - Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; - Irp->IoStatus.Information = sizeof (GET_LENGTH_INFORMATION); - } - else - { - PGET_LENGTH_INFORMATION outputBuffer = (PGET_LENGTH_INFORMATION) Irp->AssociatedIrp.SystemBuffer; - - outputBuffer->Length.QuadPart = Extension->DiskLength; - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (GET_LENGTH_INFORMATION); - } - break; - - case IOCTL_DISK_VERIFY: - if (ValidateIOBufferSize (Irp, sizeof (VERIFY_INFORMATION), ValidateInput)) - { - HRESULT hResult; - ULONGLONG ullStartingOffset, ullNewOffset, ullEndOffset; - PVERIFY_INFORMATION pVerifyInformation; - pVerifyInformation = (PVERIFY_INFORMATION) Irp->AssociatedIrp.SystemBuffer; - - ullStartingOffset = (ULONGLONG) pVerifyInformation->StartingOffset.QuadPart; - hResult = ULongLongAdd(ullStartingOffset, - (ULONGLONG) Extension->cryptoInfo->hiddenVolume ? Extension->cryptoInfo->hiddenVolumeOffset : Extension->cryptoInfo->volDataAreaOffset, - &ullNewOffset); - if (hResult != S_OK) - Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - else if (S_OK != ULongLongAdd(ullStartingOffset, (ULONGLONG) pVerifyInformation->Length, &ullEndOffset)) - Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - else if (ullEndOffset > (ULONGLONG) Extension->DiskLength) - Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - else - { - IO_STATUS_BLOCK ioStatus; - PVOID buffer = TCalloc (max (pVerifyInformation->Length, PAGE_SIZE)); - - if (!buffer) - { - Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; - } - else - { - LARGE_INTEGER offset = pVerifyInformation->StartingOffset; - offset.QuadPart = ullNewOffset; - - Irp->IoStatus.Status = ZwReadFile (Extension->hDeviceFile, NULL, NULL, NULL, &ioStatus, buffer, pVerifyInformation->Length, &offset, NULL); - TCfree (buffer); - - if (NT_SUCCESS (Irp->IoStatus.Status) && ioStatus.Information != pVerifyInformation->Length) - Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - } - } - - Irp->IoStatus.Information = 0; - } - break; - - case IOCTL_DISK_CHECK_VERIFY: - case IOCTL_STORAGE_CHECK_VERIFY: - { - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = 0; - - if (irpSp->Parameters.DeviceIoControl.OutputBufferLength >= sizeof (ULONG)) - { - *((ULONG *) Irp->AssociatedIrp.SystemBuffer) = 0; - Irp->IoStatus.Information = sizeof (ULONG); - } - } - break; - - case IOCTL_DISK_IS_WRITABLE: - { - if (Extension->bReadOnly) - Irp->IoStatus.Status = STATUS_MEDIA_WRITE_PROTECTED; - else - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = 0; - - } - break; - - case IOCTL_VOLUME_ONLINE: - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = 0; - break; - - case IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS: - - // Vista's filesystem defragmenter fails if IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS does not succeed. - if (!(OsMajorVersion == 6 && OsMinorVersion == 0)) - { - Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; - Irp->IoStatus.Information = 0; - } - else if (ValidateIOBufferSize (Irp, sizeof (VOLUME_DISK_EXTENTS), ValidateOutput)) - { - VOLUME_DISK_EXTENTS *extents = (VOLUME_DISK_EXTENTS *) Irp->AssociatedIrp.SystemBuffer; - - // No extent data can be returned as this is not a physical drive. - memset (extents, 0, sizeof (*extents)); - extents->NumberOfDiskExtents = 0; - - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (*extents); - } - break; - - default: - return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); - } - -#ifdef DEBUG - if (!NT_SUCCESS (Irp->IoStatus.Status)) - { - Dump ("IOCTL error 0x%08x (0x%x %d)\n", - Irp->IoStatus.Status, - (int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16), - (int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2)); - } -#endif - - return TCCompleteDiskIrp (Irp, Irp->IoStatus.Status, Irp->IoStatus.Information); -} - - -NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp) -{ - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); - NTSTATUS ntStatus; - - switch (irpSp->Parameters.DeviceIoControl.IoControlCode) - { - case TC_IOCTL_GET_DRIVER_VERSION: - case TC_IOCTL_LEGACY_GET_DRIVER_VERSION: - if (ValidateIOBufferSize (Irp, sizeof (LONG), ValidateOutput)) - { - LONG tmp = VERSION_NUM; - memcpy (Irp->AssociatedIrp.SystemBuffer, &tmp, 4); - Irp->IoStatus.Information = sizeof (LONG); - Irp->IoStatus.Status = STATUS_SUCCESS; - } - break; - - case TC_IOCTL_GET_DEVICE_REFCOUNT: - if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) - { - *(int *) Irp->AssociatedIrp.SystemBuffer = DeviceObject->ReferenceCount; - Irp->IoStatus.Information = sizeof (int); - Irp->IoStatus.Status = STATUS_SUCCESS; - } - break; - - case TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED: - if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) - { - LONG deviceObjectCount = 0; - - *(int *) Irp->AssociatedIrp.SystemBuffer = DriverUnloadDisabled; - - if (IoEnumerateDeviceObjectList (TCDriverObject, NULL, 0, &deviceObjectCount) == STATUS_BUFFER_TOO_SMALL && deviceObjectCount > 1) - *(int *) Irp->AssociatedIrp.SystemBuffer = TRUE; - - Irp->IoStatus.Information = sizeof (int); - Irp->IoStatus.Status = STATUS_SUCCESS; - } - break; - - case TC_IOCTL_IS_ANY_VOLUME_MOUNTED: - if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) - { - int drive; - *(int *) Irp->AssociatedIrp.SystemBuffer = 0; - - for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) - { - if (GetVirtualVolumeDeviceObject (drive)) - { - *(int *) Irp->AssociatedIrp.SystemBuffer = 1; - break; - } - } - - if (IsBootDriveMounted()) - *(int *) Irp->AssociatedIrp.SystemBuffer = 1; - - Irp->IoStatus.Information = sizeof (int); - Irp->IoStatus.Status = STATUS_SUCCESS; - } - break; - - case TC_IOCTL_OPEN_TEST: - { - OPEN_TEST_STRUCT *opentest = (OPEN_TEST_STRUCT *) Irp->AssociatedIrp.SystemBuffer; - OBJECT_ATTRIBUTES ObjectAttributes; - HANDLE NtFileHandle; - UNICODE_STRING FullFileName; - IO_STATUS_BLOCK IoStatus; - LARGE_INTEGER offset; - ACCESS_MASK access = FILE_READ_ATTRIBUTES; - - if (!ValidateIOBufferSize (Irp, sizeof (OPEN_TEST_STRUCT), ValidateInputOutput)) - break; - - EnsureNullTerminatedString (opentest->wszFileName, sizeof (opentest->wszFileName)); - RtlInitUnicodeString (&FullFileName, opentest->wszFileName); - - InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); - - if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bMatchVolumeID) - access |= FILE_READ_DATA; - - ntStatus = ZwCreateFile (&NtFileHandle, - SYNCHRONIZE | access, &ObjectAttributes, &IoStatus, NULL, - 0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); - - if (NT_SUCCESS (ntStatus)) - { - opentest->TCBootLoaderDetected = FALSE; - opentest->FilesystemDetected = FALSE; - opentest->VolumeIDMatched = FALSE; - - if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bMatchVolumeID) - { - byte *readBuffer = TCalloc (TC_MAX_VOLUME_SECTOR_SIZE); - if (!readBuffer) - { - ntStatus = STATUS_INSUFFICIENT_RESOURCES; - } - else - { - if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem) - { - // Determine if the first sector contains a portion of the VeraCrypt Boot Loader - - offset.QuadPart = 0; - - ntStatus = ZwReadFile (NtFileHandle, - NULL, - NULL, - NULL, - &IoStatus, - readBuffer, - TC_MAX_VOLUME_SECTOR_SIZE, - &offset, - NULL); - - if (NT_SUCCESS (ntStatus)) - { - size_t i; - - if (opentest->bDetectTCBootLoader && IoStatus.Information >= TC_SECTOR_SIZE_BIOS) - { - // Search for the string "VeraCrypt" - for (i = 0; i < TC_SECTOR_SIZE_BIOS - strlen (TC_APP_NAME); ++i) - { - if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0) - { - opentest->TCBootLoaderDetected = TRUE; - break; - } - } - } - - if (opentest->DetectFilesystem && IoStatus.Information >= sizeof (int64)) - { - switch (BE64 (*(uint64 *) readBuffer)) - { - case 0xEB52904E54465320: // NTFS - case 0xEB3C904D53444F53: // FAT16 - case 0xEB58904D53444F53: // FAT32 - case 0xEB76904558464154: // exFAT - - opentest->FilesystemDetected = TRUE; - break; - } - } - } - } - - if (opentest->bMatchVolumeID) - { - int volumeType; - BYTE volumeID[VOLUME_ID_SIZE]; - - // Go through all volume types (e.g., normal, hidden) - for (volumeType = TC_VOLUME_TYPE_NORMAL; - volumeType < TC_VOLUME_TYPE_COUNT; - volumeType++) - { - /* Read the volume header */ - switch (volumeType) - { - case TC_VOLUME_TYPE_NORMAL: - offset.QuadPart = TC_VOLUME_HEADER_OFFSET; - break; - - case TC_VOLUME_TYPE_HIDDEN: - - offset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET; - break; - } - - ntStatus = ZwReadFile (NtFileHandle, - NULL, - NULL, - NULL, - &IoStatus, - readBuffer, - TC_MAX_VOLUME_SECTOR_SIZE, - &offset, - NULL); - - if (NT_SUCCESS (ntStatus)) - { - /* compute the ID of this volume: SHA-256 of the effective header */ - sha256 (volumeID, readBuffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - - if (0 == memcmp (volumeID, opentest->volumeID, VOLUME_ID_SIZE)) - { - opentest->VolumeIDMatched = TRUE; - break; - } - } - } - } - - TCfree (readBuffer); - } - } - - ZwClose (NtFileHandle); - Dump ("Open test on file %ls success.\n", opentest->wszFileName); - } - else - { -#if 0 - Dump ("Open test on file %ls failed NTSTATUS 0x%08x\n", opentest->wszFileName, ntStatus); -#endif - } - - Irp->IoStatus.Information = NT_SUCCESS (ntStatus) ? sizeof (OPEN_TEST_STRUCT) : 0; - Irp->IoStatus.Status = ntStatus; - } - break; - - case TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG: - { - GetSystemDriveConfigurationRequest *request = (GetSystemDriveConfigurationRequest *) Irp->AssociatedIrp.SystemBuffer; - OBJECT_ATTRIBUTES ObjectAttributes; - HANDLE NtFileHandle; - UNICODE_STRING FullFileName; - IO_STATUS_BLOCK IoStatus; - LARGE_INTEGER offset; - byte readBuffer [TC_SECTOR_SIZE_BIOS]; - - if (!ValidateIOBufferSize (Irp, sizeof (GetSystemDriveConfigurationRequest), ValidateInputOutput)) - break; - - EnsureNullTerminatedString (request->DevicePath, sizeof (request->DevicePath)); - RtlInitUnicodeString (&FullFileName, request->DevicePath); - - InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); - - ntStatus = ZwCreateFile (&NtFileHandle, - SYNCHRONIZE | GENERIC_READ, &ObjectAttributes, &IoStatus, NULL, - FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT | FILE_RANDOM_ACCESS, NULL, 0); - - if (NT_SUCCESS (ntStatus)) - { - // Determine if the first sector contains a portion of the VeraCrypt Boot Loader - offset.QuadPart = 0; // MBR - - ntStatus = ZwReadFile (NtFileHandle, - NULL, - NULL, - NULL, - &IoStatus, - readBuffer, - sizeof(readBuffer), - &offset, - NULL); - - if (NT_SUCCESS (ntStatus)) - { - size_t i; - - // Check for dynamic drive - request->DriveIsDynamic = FALSE; - - if (readBuffer[510] == 0x55 && readBuffer[511] == 0xaa) - { - int i; - for (i = 0; i < 4; ++i) - { - if (readBuffer[446 + i * 16 + 4] == PARTITION_LDM) - { - request->DriveIsDynamic = TRUE; - break; - } - } - } - - request->BootLoaderVersion = 0; - request->Configuration = 0; - request->UserConfiguration = 0; - request->CustomUserMessage[0] = 0; - - // Search for the string "VeraCrypt" - for (i = 0; i < sizeof (readBuffer) - strlen (TC_APP_NAME); ++i) - { - if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0) - { - request->BootLoaderVersion = BE16 (*(uint16 *) (readBuffer + TC_BOOT_SECTOR_VERSION_OFFSET)); - request->Configuration = readBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET]; - - if (request->BootLoaderVersion != 0 && request->BootLoaderVersion <= VERSION_NUM) - { - request->UserConfiguration = readBuffer[TC_BOOT_SECTOR_USER_CONFIG_OFFSET]; - memcpy (request->CustomUserMessage, readBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); - } - break; - } - } - - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (*request); - } - else - { - Irp->IoStatus.Status = ntStatus; - Irp->IoStatus.Information = 0; - } - - ZwClose (NtFileHandle); - - } - else - { - Irp->IoStatus.Status = ntStatus; - Irp->IoStatus.Information = 0; - } - } - break; - - case TC_IOCTL_WIPE_PASSWORD_CACHE: - WipeCache (); - - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = 0; - break; - - case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: - Irp->IoStatus.Status = cacheEmpty ? STATUS_PIPE_EMPTY : STATUS_SUCCESS; - Irp->IoStatus.Information = 0; - break; - - case TC_IOCTL_SET_PORTABLE_MODE_STATUS: - if (!UserCanAccessDriveDevice()) - { - Irp->IoStatus.Status = STATUS_ACCESS_DENIED; - Irp->IoStatus.Information = 0; - } - else - { - PortableMode = TRUE; - Dump ("Setting portable mode\n"); - } - break; - - case TC_IOCTL_GET_PORTABLE_MODE_STATUS: - Irp->IoStatus.Status = PortableMode ? STATUS_SUCCESS : STATUS_PIPE_EMPTY; - Irp->IoStatus.Information = 0; - break; - - case TC_IOCTL_GET_MOUNTED_VOLUMES: - - if (ValidateIOBufferSize (Irp, sizeof (MOUNT_LIST_STRUCT), ValidateOutput)) - { - MOUNT_LIST_STRUCT *list = (MOUNT_LIST_STRUCT *) Irp->AssociatedIrp.SystemBuffer; - PDEVICE_OBJECT ListDevice; - int drive; - - list->ulMountedDrives = 0; - - for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) - { - PEXTENSION ListExtension; - - ListDevice = GetVirtualVolumeDeviceObject (drive); - if (!ListDevice) - continue; - - ListExtension = (PEXTENSION) ListDevice->DeviceExtension; - if (IsVolumeAccessibleByCurrentUser (ListExtension)) - { - list->ulMountedDrives |= (1 << ListExtension->nDosDriveNo); - RtlStringCbCopyW (list->wszVolume[ListExtension->nDosDriveNo], sizeof(list->wszVolume[ListExtension->nDosDriveNo]),ListExtension->wszVolume); - RtlStringCbCopyW (list->wszLabel[ListExtension->nDosDriveNo], sizeof(list->wszLabel[ListExtension->nDosDriveNo]),ListExtension->wszLabel); - memcpy (list->volumeID[ListExtension->nDosDriveNo], ListExtension->volumeID, VOLUME_ID_SIZE); - list->diskLength[ListExtension->nDosDriveNo] = ListExtension->DiskLength; - list->ea[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->ea; - if (ListExtension->cryptoInfo->hiddenVolume) - list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_HIDDEN; // Hidden volume - else if (ListExtension->cryptoInfo->bHiddenVolProtectionAction) - list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED; // Normal/outer volume (hidden volume protected AND write already prevented) - else if (ListExtension->cryptoInfo->bProtectHiddenVolume) - list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER; // Normal/outer volume (hidden volume protected) - else - list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_NORMAL; // Normal volume - list->truecryptMode[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->bTrueCryptMode; - } - } - - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (MOUNT_LIST_STRUCT); - } - break; - - case TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES: - if (ValidateIOBufferSize (Irp, sizeof (uint32), ValidateOutput)) - { - // Prevent the user from downgrading to versions lower than 5.0 by faking mounted volumes. - // The user could render the system unbootable by downgrading when boot encryption - // is active or being set up. - - memset (Irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength); - *(uint32 *) Irp->AssociatedIrp.SystemBuffer = 0xffffFFFF; - - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = irpSp->Parameters.DeviceIoControl.OutputBufferLength; - } - break; - - case TC_IOCTL_GET_VOLUME_PROPERTIES: - if (ValidateIOBufferSize (Irp, sizeof (VOLUME_PROPERTIES_STRUCT), ValidateInputOutput)) - { - VOLUME_PROPERTIES_STRUCT *prop = (VOLUME_PROPERTIES_STRUCT *) Irp->AssociatedIrp.SystemBuffer; - PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (prop->driveNo); - - Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - Irp->IoStatus.Information = 0; - - if (ListDevice) - { - PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; - if (IsVolumeAccessibleByCurrentUser (ListExtension)) - { - prop->uniqueId = ListExtension->UniqueVolumeId; - RtlStringCbCopyW (prop->wszVolume, sizeof(prop->wszVolume),ListExtension->wszVolume); - RtlStringCbCopyW (prop->wszLabel, sizeof(prop->wszLabel),ListExtension->wszLabel); - memcpy (prop->volumeID, ListExtension->volumeID, VOLUME_ID_SIZE); - prop->bDriverSetLabel = ListExtension->bDriverSetLabel; - prop->diskLength = ListExtension->DiskLength; - prop->ea = ListExtension->cryptoInfo->ea; - prop->mode = ListExtension->cryptoInfo->mode; - prop->pkcs5 = ListExtension->cryptoInfo->pkcs5; - prop->pkcs5Iterations = ListExtension->cryptoInfo->noIterations; - prop->volumePim = ListExtension->cryptoInfo->volumePim; -#if 0 - prop->volumeCreationTime = ListExtension->cryptoInfo->volume_creation_time; - prop->headerCreationTime = ListExtension->cryptoInfo->header_creation_time; -#endif - prop->volumeHeaderFlags = ListExtension->cryptoInfo->HeaderFlags; - prop->readOnly = ListExtension->bReadOnly; - prop->removable = ListExtension->bRemovable; - prop->partitionInInactiveSysEncScope = ListExtension->PartitionInInactiveSysEncScope; - prop->hiddenVolume = ListExtension->cryptoInfo->hiddenVolume; - - if (ListExtension->cryptoInfo->bProtectHiddenVolume) - prop->hiddenVolProtection = ListExtension->cryptoInfo->bHiddenVolProtectionAction ? HIDVOL_PROT_STATUS_ACTION_TAKEN : HIDVOL_PROT_STATUS_ACTIVE; - else - prop->hiddenVolProtection = HIDVOL_PROT_STATUS_NONE; - - prop->totalBytesRead = ListExtension->Queue.TotalBytesRead; - prop->totalBytesWritten = ListExtension->Queue.TotalBytesWritten; - - prop->volFormatVersion = ListExtension->cryptoInfo->LegacyVolume ? TC_VOLUME_FORMAT_VERSION_PRE_6_0 : TC_VOLUME_FORMAT_VERSION; - - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (VOLUME_PROPERTIES_STRUCT); - } - } - } - break; - - case TC_IOCTL_GET_RESOLVED_SYMLINK: - if (ValidateIOBufferSize (Irp, sizeof (RESOLVE_SYMLINK_STRUCT), ValidateInputOutput)) - { - RESOLVE_SYMLINK_STRUCT *resolve = (RESOLVE_SYMLINK_STRUCT *) Irp->AssociatedIrp.SystemBuffer; - { - NTSTATUS ntStatus; - - EnsureNullTerminatedString (resolve->symLinkName, sizeof (resolve->symLinkName)); - - ntStatus = SymbolicLinkToTarget (resolve->symLinkName, - resolve->targetName, - sizeof (resolve->targetName)); - - Irp->IoStatus.Information = sizeof (RESOLVE_SYMLINK_STRUCT); - Irp->IoStatus.Status = ntStatus; - } - } - break; - - case TC_IOCTL_GET_DRIVE_PARTITION_INFO: - if (ValidateIOBufferSize (Irp, sizeof (DISK_PARTITION_INFO_STRUCT), ValidateInputOutput)) - { - DISK_PARTITION_INFO_STRUCT *info = (DISK_PARTITION_INFO_STRUCT *) Irp->AssociatedIrp.SystemBuffer; - { - PARTITION_INFORMATION_EX pi; - NTSTATUS ntStatus; - - EnsureNullTerminatedString (info->deviceName, sizeof (info->deviceName)); - - ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &pi, sizeof (pi)); - if (NT_SUCCESS(ntStatus)) - { - memset (&info->partInfo, 0, sizeof (info->partInfo)); - - info->partInfo.PartitionLength = pi.PartitionLength; - info->partInfo.PartitionNumber = pi.PartitionNumber; - info->partInfo.StartingOffset = pi.StartingOffset; - - if (pi.PartitionStyle == PARTITION_STYLE_MBR) - { - info->partInfo.PartitionType = pi.Mbr.PartitionType; - info->partInfo.BootIndicator = pi.Mbr.BootIndicator; - } - - info->IsGPT = pi.PartitionStyle == PARTITION_STYLE_GPT; - } - else - { - // Windows 2000 does not support IOCTL_DISK_GET_PARTITION_INFO_EX - ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &info->partInfo, sizeof (info->partInfo)); - info->IsGPT = FALSE; - } - - if (!NT_SUCCESS (ntStatus)) - { - GET_LENGTH_INFORMATION lengthInfo; - ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &lengthInfo, sizeof (lengthInfo)); - - if (NT_SUCCESS (ntStatus)) - { - memset (&info->partInfo, 0, sizeof (info->partInfo)); - info->partInfo.PartitionLength = lengthInfo.Length; - } - } - - info->IsDynamic = FALSE; - - if (NT_SUCCESS (ntStatus) && OsMajorVersion >= 6) - { -# define IOCTL_VOLUME_IS_DYNAMIC CTL_CODE(IOCTL_VOLUME_BASE, 18, METHOD_BUFFERED, FILE_ANY_ACCESS) - if (!NT_SUCCESS (TCDeviceIoControl (info->deviceName, IOCTL_VOLUME_IS_DYNAMIC, NULL, 0, &info->IsDynamic, sizeof (info->IsDynamic)))) - info->IsDynamic = FALSE; - } - - Irp->IoStatus.Information = sizeof (DISK_PARTITION_INFO_STRUCT); - Irp->IoStatus.Status = ntStatus; - } - } - break; - - case TC_IOCTL_GET_DRIVE_GEOMETRY: - if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_STRUCT), ValidateInputOutput)) - { - DISK_GEOMETRY_STRUCT *g = (DISK_GEOMETRY_STRUCT *) Irp->AssociatedIrp.SystemBuffer; - { - NTSTATUS ntStatus; - - EnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName)); - - ntStatus = TCDeviceIoControl (g->deviceName, - IOCTL_DISK_GET_DRIVE_GEOMETRY, - NULL, 0, &g->diskGeometry, sizeof (g->diskGeometry)); - - Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_STRUCT); - Irp->IoStatus.Status = ntStatus; - } - } - break; - - case TC_IOCTL_PROBE_REAL_DRIVE_SIZE: - if (ValidateIOBufferSize (Irp, sizeof (ProbeRealDriveSizeRequest), ValidateInputOutput)) - { - ProbeRealDriveSizeRequest *request = (ProbeRealDriveSizeRequest *) Irp->AssociatedIrp.SystemBuffer; - NTSTATUS status; - UNICODE_STRING name; - PFILE_OBJECT fileObject; - PDEVICE_OBJECT deviceObject; - - EnsureNullTerminatedString (request->DeviceName, sizeof (request->DeviceName)); - - RtlInitUnicodeString (&name, request->DeviceName); - status = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject); - if (!NT_SUCCESS (status)) - { - Irp->IoStatus.Information = 0; - Irp->IoStatus.Status = status; - break; - } - - status = ProbeRealDriveSize (deviceObject, &request->RealDriveSize); - ObDereferenceObject (fileObject); - - if (status == STATUS_TIMEOUT) - { - request->TimeOut = TRUE; - Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest); - Irp->IoStatus.Status = STATUS_SUCCESS; - } - else if (!NT_SUCCESS (status)) - { - Irp->IoStatus.Information = 0; - Irp->IoStatus.Status = status; - } - else - { - request->TimeOut = FALSE; - Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest); - Irp->IoStatus.Status = status; - } - } - break; - - case TC_IOCTL_MOUNT_VOLUME: - if (ValidateIOBufferSize (Irp, sizeof (MOUNT_STRUCT), ValidateInputOutput)) - { - MOUNT_STRUCT *mount = (MOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; - - if (mount->VolumePassword.Length > MAX_PASSWORD || mount->ProtectedHidVolPassword.Length > MAX_PASSWORD - || mount->pkcs5_prf < 0 || mount->pkcs5_prf > LAST_PRF_ID - || mount->VolumePim < -1 || mount->VolumePim == INT_MAX - || mount->ProtectedHidVolPkcs5Prf < 0 || mount->ProtectedHidVolPkcs5Prf > LAST_PRF_ID - || (mount->bTrueCryptMode != FALSE && mount->bTrueCryptMode != TRUE) - ) - { - Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - Irp->IoStatus.Information = 0; - break; - } - - EnsureNullTerminatedString (mount->wszVolume, sizeof (mount->wszVolume)); - EnsureNullTerminatedString (mount->wszLabel, sizeof (mount->wszLabel)); - - Irp->IoStatus.Information = sizeof (MOUNT_STRUCT); - Irp->IoStatus.Status = MountDevice (DeviceObject, mount); - - burn (&mount->VolumePassword, sizeof (mount->VolumePassword)); - burn (&mount->ProtectedHidVolPassword, sizeof (mount->ProtectedHidVolPassword)); - burn (&mount->pkcs5_prf, sizeof (mount->pkcs5_prf)); - burn (&mount->VolumePim, sizeof (mount->VolumePim)); - burn (&mount->bTrueCryptMode, sizeof (mount->bTrueCryptMode)); - burn (&mount->ProtectedHidVolPkcs5Prf, sizeof (mount->ProtectedHidVolPkcs5Prf)); - burn (&mount->ProtectedHidVolPim, sizeof (mount->ProtectedHidVolPim)); - } - break; - - case TC_IOCTL_DISMOUNT_VOLUME: - if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput)) - { - UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; - PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (unmount->nDosDriveNo); - - unmount->nReturnCode = ERR_DRIVE_NOT_FOUND; - - if (ListDevice) - { - PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; - - if (IsVolumeAccessibleByCurrentUser (ListExtension)) - unmount->nReturnCode = UnmountDevice (unmount, ListDevice, unmount->ignoreOpenFiles); - } - - Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT); - Irp->IoStatus.Status = STATUS_SUCCESS; - } - break; - - case TC_IOCTL_DISMOUNT_ALL_VOLUMES: - if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput)) - { - UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; - - unmount->nReturnCode = UnmountAllDevices (unmount, unmount->ignoreOpenFiles); - - Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT); - Irp->IoStatus.Status = STATUS_SUCCESS; - } - break; - - case TC_IOCTL_BOOT_ENCRYPTION_SETUP: - Irp->IoStatus.Status = StartBootEncryptionSetup (DeviceObject, Irp, irpSp); - Irp->IoStatus.Information = 0; - break; - - case TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP: - Irp->IoStatus.Status = AbortBootEncryptionSetup(); - Irp->IoStatus.Information = 0; - break; - - case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: - GetBootEncryptionStatus (Irp, irpSp); - break; - - case TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT: - Irp->IoStatus.Information = 0; - Irp->IoStatus.Status = GetSetupResult(); - break; - - case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: - GetBootDriveVolumeProperties (Irp, irpSp); - break; - - case TC_IOCTL_GET_BOOT_LOADER_VERSION: - GetBootLoaderVersion (Irp, irpSp); - break; - - case TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER: - ReopenBootVolumeHeader (Irp, irpSp); - break; - - case VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT: - GetBootLoaderFingerprint (Irp, irpSp); - break; - - case TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME: - GetBootEncryptionAlgorithmName (Irp, irpSp); - break; - - case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: - if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) - { - *(int *) Irp->AssociatedIrp.SystemBuffer = IsHiddenSystemRunning() ? 1 : 0; - Irp->IoStatus.Information = sizeof (int); - Irp->IoStatus.Status = STATUS_SUCCESS; - } - break; - - case TC_IOCTL_START_DECOY_SYSTEM_WIPE: - Irp->IoStatus.Status = StartDecoySystemWipe (DeviceObject, Irp, irpSp); - Irp->IoStatus.Information = 0; - break; - - case TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE: - Irp->IoStatus.Status = AbortDecoySystemWipe(); - Irp->IoStatus.Information = 0; - break; - - case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT: - Irp->IoStatus.Status = GetDecoySystemWipeResult(); - Irp->IoStatus.Information = 0; - break; - - case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS: - GetDecoySystemWipeStatus (Irp, irpSp); - break; - - case TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR: - Irp->IoStatus.Status = WriteBootDriveSector (Irp, irpSp); - Irp->IoStatus.Information = 0; - break; - - case TC_IOCTL_GET_WARNING_FLAGS: - if (ValidateIOBufferSize (Irp, sizeof (GetWarningFlagsRequest), ValidateOutput)) - { - GetWarningFlagsRequest *flags = (GetWarningFlagsRequest *) Irp->AssociatedIrp.SystemBuffer; - - flags->PagingFileCreationPrevented = PagingFileCreationPrevented; - PagingFileCreationPrevented = FALSE; - flags->SystemFavoriteVolumeDirty = SystemFavoriteVolumeDirty; - SystemFavoriteVolumeDirty = FALSE; - - Irp->IoStatus.Information = sizeof (GetWarningFlagsRequest); - Irp->IoStatus.Status = STATUS_SUCCESS; - } - break; - - case TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY: - if (UserCanAccessDriveDevice()) - { - SystemFavoriteVolumeDirty = TRUE; - Irp->IoStatus.Status = STATUS_SUCCESS; - } - else - Irp->IoStatus.Status = STATUS_ACCESS_DENIED; - - Irp->IoStatus.Information = 0; - break; - - case TC_IOCTL_REREAD_DRIVER_CONFIG: - Irp->IoStatus.Status = ReadRegistryConfigFlags (FALSE); - Irp->IoStatus.Information = 0; - break; - - case TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG: - if ( (ValidateIOBufferSize (Irp, sizeof (GetSystemDriveDumpConfigRequest), ValidateOutput)) - && (Irp->RequestorMode == KernelMode) - ) - { - GetSystemDriveDumpConfigRequest *request = (GetSystemDriveDumpConfigRequest *) Irp->AssociatedIrp.SystemBuffer; - - request->BootDriveFilterExtension = GetBootDriveFilterExtension(); - if (IsBootDriveMounted() && request->BootDriveFilterExtension) - { - request->HwEncryptionEnabled = IsHwEncryptionEnabled(); - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (*request); - } - else - { - Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; - Irp->IoStatus.Information = 0; - } - } - break; - - default: - return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); - } - - -#ifdef DEBUG - if (!NT_SUCCESS (Irp->IoStatus.Status)) - { - switch (irpSp->Parameters.DeviceIoControl.IoControlCode) - { - case TC_IOCTL_GET_MOUNTED_VOLUMES: - case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: - case TC_IOCTL_GET_PORTABLE_MODE_STATUS: - case TC_IOCTL_SET_PORTABLE_MODE_STATUS: - case TC_IOCTL_OPEN_TEST: - case TC_IOCTL_GET_RESOLVED_SYMLINK: - case TC_IOCTL_GET_DRIVE_PARTITION_INFO: - case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: - case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: - case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: - break; - - default: - Dump ("IOCTL error 0x%08x\n", Irp->IoStatus.Status); - } - } -#endif - - return TCCompleteIrp (Irp, Irp->IoStatus.Status, Irp->IoStatus.Information); -} - - -NTSTATUS TCStartThread (PKSTART_ROUTINE threadProc, PVOID threadArg, PKTHREAD *kThread) -{ - return TCStartThreadInProcess (threadProc, threadArg, kThread, NULL); -} - - -NTSTATUS TCStartThreadInProcess (PKSTART_ROUTINE threadProc, PVOID threadArg, PKTHREAD *kThread, PEPROCESS process) -{ - NTSTATUS status; - HANDLE threadHandle; - HANDLE processHandle = NULL; - OBJECT_ATTRIBUTES threadObjAttributes; - - if (process) - { - status = ObOpenObjectByPointer (process, OBJ_KERNEL_HANDLE, NULL, 0, NULL, KernelMode, &processHandle); - if (!NT_SUCCESS (status)) - return status; - } - - InitializeObjectAttributes (&threadObjAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); - - status = PsCreateSystemThread (&threadHandle, THREAD_ALL_ACCESS, &threadObjAttributes, processHandle, NULL, threadProc, threadArg); - if (!NT_SUCCESS (status)) - return status; - - status = ObReferenceObjectByHandle (threadHandle, THREAD_ALL_ACCESS, NULL, KernelMode, (PVOID *) kThread, NULL); - if (!NT_SUCCESS (status)) - { - ZwClose (threadHandle); - *kThread = NULL; - return status; - } - - if (processHandle) - ZwClose (processHandle); - - ZwClose (threadHandle); - return STATUS_SUCCESS; -} - - -void TCStopThread (PKTHREAD kThread, PKEVENT wakeUpEvent) -{ - if (wakeUpEvent) - KeSetEvent (wakeUpEvent, 0, FALSE); - - KeWaitForSingleObject (kThread, Executive, KernelMode, FALSE, NULL); - ObDereferenceObject (kThread); -} - - -NTSTATUS TCStartVolumeThread (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, MOUNT_STRUCT * mount) -{ - PTHREAD_BLOCK pThreadBlock = TCalloc (sizeof (THREAD_BLOCK)); - HANDLE hThread; - NTSTATUS ntStatus; - OBJECT_ATTRIBUTES threadObjAttributes; - SECURITY_QUALITY_OF_SERVICE qos; - - Dump ("Starting thread...\n"); - - if (pThreadBlock == NULL) - { - return STATUS_INSUFFICIENT_RESOURCES; - } - else - { - pThreadBlock->DeviceObject = DeviceObject; - pThreadBlock->mount = mount; - } - - qos.Length = sizeof (qos); - qos.ContextTrackingMode = SECURITY_STATIC_TRACKING; - qos.EffectiveOnly = TRUE; - qos.ImpersonationLevel = SecurityImpersonation; - - ntStatus = SeCreateClientSecurity (PsGetCurrentThread(), &qos, FALSE, &Extension->SecurityClientContext); - if (!NT_SUCCESS (ntStatus)) - goto ret; - - Extension->SecurityClientContextValid = TRUE; - - Extension->bThreadShouldQuit = FALSE; - - InitializeObjectAttributes (&threadObjAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); - - ntStatus = PsCreateSystemThread (&hThread, - THREAD_ALL_ACCESS, - &threadObjAttributes, - NULL, - NULL, - VolumeThreadProc, - pThreadBlock); - - if (!NT_SUCCESS (ntStatus)) - { - Dump ("PsCreateSystemThread Failed END\n"); - goto ret; - } - - ntStatus = ObReferenceObjectByHandle (hThread, - THREAD_ALL_ACCESS, - NULL, - KernelMode, - &Extension->peThread, - NULL); - - ZwClose (hThread); - - if (!NT_SUCCESS (ntStatus)) - goto ret; - - Dump ("Waiting for thread to initialize...\n"); - - KeWaitForSingleObject (&Extension->keCreateEvent, - Executive, - KernelMode, - FALSE, - NULL); - - Dump ("Waiting completed! Thread returns 0x%08x\n", pThreadBlock->ntCreateStatus); - ntStatus = pThreadBlock->ntCreateStatus; - -ret: - TCfree (pThreadBlock); - return ntStatus; -} - -void TCStopVolumeThread (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension) -{ - NTSTATUS ntStatus; - - UNREFERENCED_PARAMETER (DeviceObject); /* Remove compiler warning */ - - Dump ("Signalling thread to quit...\n"); - - Extension->bThreadShouldQuit = TRUE; - - KeReleaseSemaphore (&Extension->RequestSemaphore, - 0, - 1, - TRUE); - - ntStatus = KeWaitForSingleObject (Extension->peThread, - Executive, - KernelMode, - FALSE, - NULL); - - ASSERT (NT_SUCCESS (ntStatus)); - - ObDereferenceObject (Extension->peThread); - Extension->peThread = NULL; - - Dump ("Thread exited\n"); -} - - -// Suspend current thread for a number of milliseconds -void TCSleep (int milliSeconds) -{ - PKTIMER timer = (PKTIMER) TCalloc (sizeof (KTIMER)); - LARGE_INTEGER duetime; - - if (!timer) - return; - - duetime.QuadPart = (__int64) milliSeconds * -10000; - KeInitializeTimerEx(timer, NotificationTimer); - KeSetTimerEx(timer, duetime, 0, NULL); - - KeWaitForSingleObject (timer, Executive, KernelMode, FALSE, NULL); - - TCfree (timer); -} - -BOOL IsDeviceName(wchar_t wszVolume[TC_MAX_PATH]) -{ - if ( (wszVolume[0] == '\\') - && (wszVolume[1] == 'D' || wszVolume[1] == 'd') - && (wszVolume[2] == 'E' || wszVolume[2] == 'e') - && (wszVolume[3] == 'V' || wszVolume[3] == 'v') - && (wszVolume[4] == 'I' || wszVolume[4] == 'i') - && (wszVolume[5] == 'C' || wszVolume[5] == 'c') - && (wszVolume[6] == 'E' || wszVolume[6] == 'e') - ) - { - return TRUE; - } - else - return FALSE; -} - -/* VolumeThreadProc does all the work of processing IRP's, and dispatching them - to either the ReadWrite function or the DeviceControl function */ -VOID VolumeThreadProc (PVOID Context) -{ - PTHREAD_BLOCK pThreadBlock = (PTHREAD_BLOCK) Context; - PDEVICE_OBJECT DeviceObject = pThreadBlock->DeviceObject; - PEXTENSION Extension = (PEXTENSION) DeviceObject->DeviceExtension; - BOOL bDevice; - - /* Set thread priority to lowest realtime level. */ - KeSetPriorityThread (KeGetCurrentThread (), LOW_REALTIME_PRIORITY); - - Dump ("Mount THREAD OPENING VOLUME BEGIN\n"); - - if ( !IsDeviceName (pThreadBlock->mount->wszVolume)) - { - RtlStringCbCopyW (pThreadBlock->wszMountVolume, sizeof(pThreadBlock->wszMountVolume),WIDE ("\\??\\")); - RtlStringCbCatW (pThreadBlock->wszMountVolume, sizeof(pThreadBlock->wszMountVolume),pThreadBlock->mount->wszVolume); - bDevice = FALSE; - } - else - { - pThreadBlock->wszMountVolume[0] = 0; - RtlStringCbCatW (pThreadBlock->wszMountVolume, sizeof(pThreadBlock->wszMountVolume),pThreadBlock->mount->wszVolume); - bDevice = TRUE; - } - - Dump ("Mount THREAD request for File %ls DriveNumber %d Device = %d\n", - pThreadBlock->wszMountVolume, pThreadBlock->mount->nDosDriveNo, bDevice); - - pThreadBlock->ntCreateStatus = TCOpenVolume (DeviceObject, - Extension, - pThreadBlock->mount, - pThreadBlock->wszMountVolume, - bDevice); - - if (!NT_SUCCESS (pThreadBlock->ntCreateStatus) || pThreadBlock->mount->nReturnCode != 0) - { - KeSetEvent (&Extension->keCreateEvent, 0, FALSE); - PsTerminateSystemThread (STATUS_SUCCESS); - } - - // Start IO queue - Extension->Queue.IsFilterDevice = FALSE; - Extension->Queue.DeviceObject = DeviceObject; - Extension->Queue.CryptoInfo = Extension->cryptoInfo; - Extension->Queue.HostFileHandle = Extension->hDeviceFile; - Extension->Queue.VirtualDeviceLength = Extension->DiskLength; - Extension->Queue.MaxReadAheadOffset.QuadPart = Extension->HostLength; - - if (Extension->SecurityClientContextValid) - Extension->Queue.SecurityClientContext = &Extension->SecurityClientContext; - else - Extension->Queue.SecurityClientContext = NULL; - - pThreadBlock->ntCreateStatus = EncryptedIoQueueStart (&Extension->Queue); - - if (!NT_SUCCESS (pThreadBlock->ntCreateStatus)) - { - TCCloseVolume (DeviceObject, Extension); - - pThreadBlock->mount->nReturnCode = ERR_OS_ERROR; - KeSetEvent (&Extension->keCreateEvent, 0, FALSE); - PsTerminateSystemThread (STATUS_SUCCESS); - } - - KeSetEvent (&Extension->keCreateEvent, 0, FALSE); - /* From this point on pThreadBlock cannot be used as it will have been released! */ - pThreadBlock = NULL; - - for (;;) - { - /* Wait for a request from the dispatch routines. */ - KeWaitForSingleObject ((PVOID) & Extension->RequestSemaphore, Executive, KernelMode, FALSE, NULL); - - for (;;) - { - PIO_STACK_LOCATION irpSp; - PLIST_ENTRY request; - PIRP irp; - - request = ExInterlockedRemoveHeadList (&Extension->ListEntry, &Extension->ListSpinLock); - if (request == NULL) - break; - - irp = CONTAINING_RECORD (request, IRP, Tail.Overlay.ListEntry); - irpSp = IoGetCurrentIrpStackLocation (irp); - - ASSERT (irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL); - - ProcessVolumeDeviceControlIrp (DeviceObject, Extension, irp); - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, irp); - } - - if (Extension->bThreadShouldQuit) - { - Dump ("Closing volume\n"); - EncryptedIoQueueStop (&Extension->Queue); - - TCCloseVolume (DeviceObject, Extension); - PsTerminateSystemThread (STATUS_SUCCESS); - } - } -} - -void TCGetNTNameFromNumber (LPWSTR ntname, int cbNtName, int nDriveNo) -{ - WCHAR tmp[2] = - {0, 0}; - int j = nDriveNo + (WCHAR) 'A'; - - tmp[0] = (short) j; - RtlStringCbCopyW (ntname, cbNtName,(LPWSTR) NT_MOUNT_PREFIX); - RtlStringCbCatW (ntname, cbNtName, tmp); -} - -void TCGetDosNameFromNumber (LPWSTR dosname,int cbDosName, int nDriveNo, DeviceNamespaceType namespaceType) -{ - WCHAR tmp[3] = - {0, ':', 0}; - int j = nDriveNo + (WCHAR) 'A'; - - tmp[0] = (short) j; - - if (DeviceNamespaceGlobal == namespaceType) - { - RtlStringCbCopyW (dosname, cbDosName, (LPWSTR) DOS_MOUNT_PREFIX_GLOBAL); - } - else - { - RtlStringCbCopyW (dosname, cbDosName, (LPWSTR) DOS_MOUNT_PREFIX_DEFAULT); - } - - RtlStringCbCatW (dosname, cbDosName, tmp); -} - -#ifdef _DEBUG -LPWSTR TCTranslateCode (ULONG ulCode) -{ - switch (ulCode) - { -#define TC_CASE_RET_NAME(CODE) case CODE : return L###CODE - - TC_CASE_RET_NAME (TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP); - TC_CASE_RET_NAME (TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE); - TC_CASE_RET_NAME (TC_IOCTL_BOOT_ENCRYPTION_SETUP); - TC_CASE_RET_NAME (TC_IOCTL_DISMOUNT_ALL_VOLUMES); - TC_CASE_RET_NAME (TC_IOCTL_DISMOUNT_VOLUME); - TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES); - TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME); - TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT); - TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS); - TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_LOADER_VERSION); - TC_CASE_RET_NAME (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT); - TC_CASE_RET_NAME (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS); - TC_CASE_RET_NAME (TC_IOCTL_GET_DEVICE_REFCOUNT); - TC_CASE_RET_NAME (TC_IOCTL_GET_DRIVE_GEOMETRY); - TC_CASE_RET_NAME (TC_IOCTL_GET_DRIVE_PARTITION_INFO); - TC_CASE_RET_NAME (TC_IOCTL_GET_DRIVER_VERSION); - TC_CASE_RET_NAME (TC_IOCTL_GET_MOUNTED_VOLUMES); - TC_CASE_RET_NAME (TC_IOCTL_GET_PASSWORD_CACHE_STATUS); - TC_CASE_RET_NAME (TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG); - TC_CASE_RET_NAME (TC_IOCTL_GET_PORTABLE_MODE_STATUS); - TC_CASE_RET_NAME (TC_IOCTL_SET_PORTABLE_MODE_STATUS); - TC_CASE_RET_NAME (TC_IOCTL_GET_RESOLVED_SYMLINK); - TC_CASE_RET_NAME (TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG); - TC_CASE_RET_NAME (TC_IOCTL_GET_VOLUME_PROPERTIES); - TC_CASE_RET_NAME (TC_IOCTL_GET_WARNING_FLAGS); - TC_CASE_RET_NAME (TC_IOCTL_DISK_IS_WRITABLE); - TC_CASE_RET_NAME (TC_IOCTL_IS_ANY_VOLUME_MOUNTED); - TC_CASE_RET_NAME (TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED); - TC_CASE_RET_NAME (TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING); - TC_CASE_RET_NAME (TC_IOCTL_MOUNT_VOLUME); - TC_CASE_RET_NAME (TC_IOCTL_OPEN_TEST); - TC_CASE_RET_NAME (TC_IOCTL_PROBE_REAL_DRIVE_SIZE); - TC_CASE_RET_NAME (TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER); - TC_CASE_RET_NAME (TC_IOCTL_REREAD_DRIVER_CONFIG); - TC_CASE_RET_NAME (TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY); - TC_CASE_RET_NAME (TC_IOCTL_START_DECOY_SYSTEM_WIPE); - TC_CASE_RET_NAME (TC_IOCTL_WIPE_PASSWORD_CACHE); - TC_CASE_RET_NAME (TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR); - - TC_CASE_RET_NAME (IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS); - -#undef TC_CASE_RET_NAME - } - - if (ulCode == IOCTL_DISK_GET_DRIVE_GEOMETRY) - return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_GEOMETRY"); - else if (ulCode == IOCTL_DISK_GET_DRIVE_GEOMETRY_EX) - return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_GEOMETRY_EX"); - else if (ulCode == IOCTL_MOUNTDEV_QUERY_DEVICE_NAME) - return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_DEVICE_NAME"); - else if (ulCode == IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME) - return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME"); - else if (ulCode == IOCTL_MOUNTDEV_QUERY_UNIQUE_ID) - return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_UNIQUE_ID"); - else if (ulCode == IOCTL_VOLUME_ONLINE) - return (LPWSTR) _T ("IOCTL_VOLUME_ONLINE"); - else if (ulCode == IOCTL_MOUNTDEV_LINK_CREATED) - return (LPWSTR) _T ("IOCTL_MOUNTDEV_LINK_CREATED"); - else if (ulCode == IOCTL_MOUNTDEV_LINK_DELETED) - return (LPWSTR) _T ("IOCTL_MOUNTDEV_LINK_DELETED"); - else if (ulCode == IOCTL_MOUNTMGR_QUERY_POINTS) - return (LPWSTR) _T ("IOCTL_MOUNTMGR_QUERY_POINTS"); - else if (ulCode == IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_CREATED) - return (LPWSTR) _T ("IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_CREATED"); - else if (ulCode == IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_DELETED) - return (LPWSTR) _T ("IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_DELETED"); - else if (ulCode == IOCTL_DISK_GET_LENGTH_INFO) - return (LPWSTR) _T ("IOCTL_DISK_GET_LENGTH_INFO"); - else if (ulCode == IOCTL_STORAGE_GET_DEVICE_NUMBER) - return (LPWSTR) _T ("IOCTL_STORAGE_GET_DEVICE_NUMBER"); - else if (ulCode == IOCTL_DISK_GET_PARTITION_INFO) - return (LPWSTR) _T ("IOCTL_DISK_GET_PARTITION_INFO"); - else if (ulCode == IOCTL_DISK_GET_PARTITION_INFO_EX) - return (LPWSTR) _T ("IOCTL_DISK_GET_PARTITION_INFO_EX"); - else if (ulCode == IOCTL_DISK_SET_PARTITION_INFO) - return (LPWSTR) _T ("IOCTL_DISK_SET_PARTITION_INFO"); - else if (ulCode == IOCTL_DISK_GET_DRIVE_LAYOUT) - return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_LAYOUT"); - else if (ulCode == IOCTL_DISK_SET_DRIVE_LAYOUT_EX) - return (LPWSTR) _T ("IOCTL_DISK_SET_DRIVE_LAYOUT_EX"); - else if (ulCode == IOCTL_DISK_VERIFY) - return (LPWSTR) _T ("IOCTL_DISK_VERIFY"); - else if (ulCode == IOCTL_DISK_FORMAT_TRACKS) - return (LPWSTR) _T ("IOCTL_DISK_FORMAT_TRACKS"); - else if (ulCode == IOCTL_DISK_REASSIGN_BLOCKS) - return (LPWSTR) _T ("IOCTL_DISK_REASSIGN_BLOCKS"); - else if (ulCode == IOCTL_DISK_PERFORMANCE) - return (LPWSTR) _T ("IOCTL_DISK_PERFORMANCE"); - else if (ulCode == IOCTL_DISK_IS_WRITABLE) - return (LPWSTR) _T ("IOCTL_DISK_IS_WRITABLE"); - else if (ulCode == IOCTL_DISK_LOGGING) - return (LPWSTR) _T ("IOCTL_DISK_LOGGING"); - else if (ulCode == IOCTL_DISK_FORMAT_TRACKS_EX) - return (LPWSTR) _T ("IOCTL_DISK_FORMAT_TRACKS_EX"); - else if (ulCode == IOCTL_DISK_HISTOGRAM_STRUCTURE) - return (LPWSTR) _T ("IOCTL_DISK_HISTOGRAM_STRUCTURE"); - else if (ulCode == IOCTL_DISK_HISTOGRAM_DATA) - return (LPWSTR) _T ("IOCTL_DISK_HISTOGRAM_DATA"); - else if (ulCode == IOCTL_DISK_HISTOGRAM_RESET) - return (LPWSTR) _T ("IOCTL_DISK_HISTOGRAM_RESET"); - else if (ulCode == IOCTL_DISK_REQUEST_STRUCTURE) - return (LPWSTR) _T ("IOCTL_DISK_REQUEST_STRUCTURE"); - else if (ulCode == IOCTL_DISK_REQUEST_DATA) - return (LPWSTR) _T ("IOCTL_DISK_REQUEST_DATA"); - else if (ulCode == IOCTL_DISK_CONTROLLER_NUMBER) - return (LPWSTR) _T ("IOCTL_DISK_CONTROLLER_NUMBER"); - else if (ulCode == SMART_GET_VERSION) - return (LPWSTR) _T ("SMART_GET_VERSION"); - else if (ulCode == SMART_SEND_DRIVE_COMMAND) - return (LPWSTR) _T ("SMART_SEND_DRIVE_COMMAND"); - else if (ulCode == SMART_RCV_DRIVE_DATA) - return (LPWSTR) _T ("SMART_RCV_DRIVE_DATA"); - else if (ulCode == IOCTL_DISK_INTERNAL_SET_VERIFY) - return (LPWSTR) _T ("IOCTL_DISK_INTERNAL_SET_VERIFY"); - else if (ulCode == IOCTL_DISK_INTERNAL_CLEAR_VERIFY) - return (LPWSTR) _T ("IOCTL_DISK_INTERNAL_CLEAR_VERIFY"); - else if (ulCode == IOCTL_DISK_CHECK_VERIFY) - return (LPWSTR) _T ("IOCTL_DISK_CHECK_VERIFY"); - else if (ulCode == IOCTL_DISK_MEDIA_REMOVAL) - return (LPWSTR) _T ("IOCTL_DISK_MEDIA_REMOVAL"); - else if (ulCode == IOCTL_DISK_EJECT_MEDIA) - return (LPWSTR) _T ("IOCTL_DISK_EJECT_MEDIA"); - else if (ulCode == IOCTL_DISK_LOAD_MEDIA) - return (LPWSTR) _T ("IOCTL_DISK_LOAD_MEDIA"); - else if (ulCode == IOCTL_DISK_RESERVE) - return (LPWSTR) _T ("IOCTL_DISK_RESERVE"); - else if (ulCode == IOCTL_DISK_RELEASE) - return (LPWSTR) _T ("IOCTL_DISK_RELEASE"); - else if (ulCode == IOCTL_DISK_FIND_NEW_DEVICES) - return (LPWSTR) _T ("IOCTL_DISK_FIND_NEW_DEVICES"); - else if (ulCode == IOCTL_DISK_GET_MEDIA_TYPES) - return (LPWSTR) _T ("IOCTL_DISK_GET_MEDIA_TYPES"); - else if (ulCode == IOCTL_STORAGE_SET_HOTPLUG_INFO) - return (LPWSTR) _T ("IOCTL_STORAGE_SET_HOTPLUG_INFO"); - else if (ulCode == IRP_MJ_READ) - return (LPWSTR) _T ("IRP_MJ_READ"); - else if (ulCode == IRP_MJ_WRITE) - return (LPWSTR) _T ("IRP_MJ_WRITE"); - else if (ulCode == IRP_MJ_CREATE) - return (LPWSTR) _T ("IRP_MJ_CREATE"); - else if (ulCode == IRP_MJ_CLOSE) - return (LPWSTR) _T ("IRP_MJ_CLOSE"); - else if (ulCode == IRP_MJ_CLEANUP) - return (LPWSTR) _T ("IRP_MJ_CLEANUP"); - else if (ulCode == IRP_MJ_FLUSH_BUFFERS) - return (LPWSTR) _T ("IRP_MJ_FLUSH_BUFFERS"); - else if (ulCode == IRP_MJ_SHUTDOWN) - return (LPWSTR) _T ("IRP_MJ_SHUTDOWN"); - else if (ulCode == IRP_MJ_DEVICE_CONTROL) - return (LPWSTR) _T ("IRP_MJ_DEVICE_CONTROL"); - else - { - return (LPWSTR) _T ("IOCTL"); - } -} - -#endif - -void TCDeleteDeviceObject (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension) -{ - UNICODE_STRING Win32NameString; - NTSTATUS ntStatus; - - Dump ("TCDeleteDeviceObject BEGIN\n"); - - if (Extension->bRootDevice) - { - RtlInitUnicodeString (&Win32NameString, (LPWSTR) DOS_ROOT_PREFIX); - ntStatus = IoDeleteSymbolicLink (&Win32NameString); - if (!NT_SUCCESS (ntStatus)) - Dump ("IoDeleteSymbolicLink failed ntStatus = 0x%08x\n", ntStatus); - - RootDeviceObject = NULL; - } - else - { - if (Extension->peThread != NULL) - TCStopVolumeThread (DeviceObject, Extension); - - if (Extension->UserSid) - TCfree (Extension->UserSid); - - if (Extension->SecurityClientContextValid) - { - if (OsMajorVersion == 5 && OsMinorVersion == 0) - { - ObDereferenceObject (Extension->SecurityClientContext.ClientToken); - } - else - { - // Windows 2000 does not support PsDereferenceImpersonationToken() used by SeDeleteClientSecurity(). - // TODO: Use only SeDeleteClientSecurity() once support for Windows 2000 is dropped. - - VOID (*PsDereferenceImpersonationTokenD) (PACCESS_TOKEN ImpersonationToken); - UNICODE_STRING name; - RtlInitUnicodeString (&name, L"PsDereferenceImpersonationToken"); - - PsDereferenceImpersonationTokenD = MmGetSystemRoutineAddress (&name); - if (!PsDereferenceImpersonationTokenD) - TC_BUG_CHECK (STATUS_NOT_IMPLEMENTED); - -# define PsDereferencePrimaryToken -# define PsDereferenceImpersonationToken PsDereferenceImpersonationTokenD - - SeDeleteClientSecurity (&Extension->SecurityClientContext); - -# undef PsDereferencePrimaryToken -# undef PsDereferenceImpersonationToken - } - } - - VirtualVolumeDeviceObjects[Extension->nDosDriveNo] = NULL; - } - - IoDeleteDevice (DeviceObject); - - Dump ("TCDeleteDeviceObject END\n"); -} - - -VOID TCUnloadDriver (PDRIVER_OBJECT DriverObject) -{ - Dump ("TCUnloadDriver BEGIN\n"); - - OnShutdownPending(); - - if (IsBootDriveMounted()) - TC_BUG_CHECK (STATUS_INVALID_DEVICE_STATE); - - EncryptionThreadPoolStop(); - TCDeleteDeviceObject (RootDeviceObject, (PEXTENSION) RootDeviceObject->DeviceExtension); - - Dump ("TCUnloadDriver END\n"); -} - - -void OnShutdownPending () -{ - UNMOUNT_STRUCT unmount; - memset (&unmount, 0, sizeof (unmount)); - unmount.ignoreOpenFiles = TRUE; - - while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_DISMOUNT_ALL_VOLUMES, &unmount, sizeof (unmount), &unmount, sizeof (unmount)) == STATUS_INSUFFICIENT_RESOURCES || unmount.HiddenVolumeProtectionTriggered) - unmount.HiddenVolumeProtectionTriggered = FALSE; - - while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES); -} - - -NTSTATUS TCDeviceIoControl (PWSTR deviceName, ULONG IoControlCode, void *InputBuffer, ULONG InputBufferSize, void *OutputBuffer, ULONG OutputBufferSize) -{ - IO_STATUS_BLOCK ioStatusBlock; - NTSTATUS ntStatus; - PIRP irp; - PFILE_OBJECT fileObject; - PDEVICE_OBJECT deviceObject; - KEVENT event; - UNICODE_STRING name; - - RtlInitUnicodeString(&name, deviceName); - ntStatus = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject); - - if (!NT_SUCCESS (ntStatus)) - return ntStatus; - - KeInitializeEvent(&event, NotificationEvent, FALSE); - - irp = IoBuildDeviceIoControlRequest (IoControlCode, - deviceObject, - InputBuffer, InputBufferSize, - OutputBuffer, OutputBufferSize, - FALSE, - &event, - &ioStatusBlock); - - if (irp == NULL) - { - Dump ("IRP allocation failed\n"); - ntStatus = STATUS_INSUFFICIENT_RESOURCES; - goto ret; - } - - IoGetNextIrpStackLocation (irp)->FileObject = fileObject; - - ntStatus = IoCallDriver (deviceObject, irp); - if (ntStatus == STATUS_PENDING) - { - KeWaitForSingleObject (&event, Executive, KernelMode, FALSE, NULL); - ntStatus = ioStatusBlock.Status; - } - -ret: - ObDereferenceObject (fileObject); - return ntStatus; -} - - -typedef struct -{ - PDEVICE_OBJECT deviceObject; ULONG ioControlCode; void *inputBuffer; int inputBufferSize; void *outputBuffer; int outputBufferSize; - NTSTATUS Status; - KEVENT WorkItemCompletedEvent; -} SendDeviceIoControlRequestWorkItemArgs; - - -static VOID SendDeviceIoControlRequestWorkItemRoutine (PDEVICE_OBJECT rootDeviceObject, SendDeviceIoControlRequestWorkItemArgs *arg) -{ - arg->Status = SendDeviceIoControlRequest (arg->deviceObject, arg->ioControlCode, arg->inputBuffer, arg->inputBufferSize, arg->outputBuffer, arg->outputBufferSize); - KeSetEvent (&arg->WorkItemCompletedEvent, IO_NO_INCREMENT, FALSE); -} - - -NTSTATUS SendDeviceIoControlRequest (PDEVICE_OBJECT deviceObject, ULONG ioControlCode, void *inputBuffer, int inputBufferSize, void *outputBuffer, int outputBufferSize) -{ - IO_STATUS_BLOCK ioStatusBlock; - NTSTATUS status; - PIRP irp; - KEVENT event; - - if (KeGetCurrentIrql() > APC_LEVEL) - { - SendDeviceIoControlRequestWorkItemArgs args; - - PIO_WORKITEM workItem = IoAllocateWorkItem (RootDeviceObject); - if (!workItem) - return STATUS_INSUFFICIENT_RESOURCES; - - args.deviceObject = deviceObject; - args.ioControlCode = ioControlCode; - args.inputBuffer = inputBuffer; - args.inputBufferSize = inputBufferSize; - args.outputBuffer = outputBuffer; - args.outputBufferSize = outputBufferSize; - - KeInitializeEvent (&args.WorkItemCompletedEvent, SynchronizationEvent, FALSE); - IoQueueWorkItem (workItem, SendDeviceIoControlRequestWorkItemRoutine, DelayedWorkQueue, &args); - - KeWaitForSingleObject (&args.WorkItemCompletedEvent, Executive, KernelMode, FALSE, NULL); - IoFreeWorkItem (workItem); - - return args.Status; - } - - KeInitializeEvent (&event, NotificationEvent, FALSE); - - irp = IoBuildDeviceIoControlRequest (ioControlCode, deviceObject, inputBuffer, inputBufferSize, - outputBuffer, outputBufferSize, FALSE, &event, &ioStatusBlock); - - if (!irp) - return STATUS_INSUFFICIENT_RESOURCES; - - ObReferenceObject (deviceObject); - - status = IoCallDriver (deviceObject, irp); - if (status == STATUS_PENDING) - { - KeWaitForSingleObject (&event, Executive, KernelMode, FALSE, NULL); - status = ioStatusBlock.Status; - } - - ObDereferenceObject (deviceObject); - return status; -} - - -NTSTATUS ProbeRealDriveSize (PDEVICE_OBJECT driveDeviceObject, LARGE_INTEGER *driveSize) -{ - NTSTATUS status; - LARGE_INTEGER sysLength; - LARGE_INTEGER offset; - byte *sectorBuffer; - ULONGLONG startTime; - - if (!UserCanAccessDriveDevice()) - return STATUS_ACCESS_DENIED; - - sectorBuffer = TCalloc (TC_SECTOR_SIZE_BIOS); - if (!sectorBuffer) - return STATUS_INSUFFICIENT_RESOURCES; - - status = SendDeviceIoControlRequest (driveDeviceObject, IOCTL_DISK_GET_LENGTH_INFO, - NULL, 0, &sysLength, sizeof (sysLength)); - - if (!NT_SUCCESS (status)) - { - Dump ("Failed to get drive size - error %x\n", status); - TCfree (sectorBuffer); - return status; - } - - startTime = KeQueryInterruptTime (); - for (offset.QuadPart = sysLength.QuadPart; ; offset.QuadPart += TC_SECTOR_SIZE_BIOS) - { - status = TCReadDevice (driveDeviceObject, sectorBuffer, offset, TC_SECTOR_SIZE_BIOS); - - if (NT_SUCCESS (status)) - status = TCWriteDevice (driveDeviceObject, sectorBuffer, offset, TC_SECTOR_SIZE_BIOS); - - if (!NT_SUCCESS (status)) - { - driveSize->QuadPart = offset.QuadPart; - Dump ("Real drive size = %I64d bytes (%I64d hidden)\n", driveSize->QuadPart, driveSize->QuadPart - sysLength.QuadPart); - TCfree (sectorBuffer); - return STATUS_SUCCESS; - } - - if (KeQueryInterruptTime() - startTime > 3ULL * 60 * 1000 * 1000 * 10) - { - // Abort if probing for more than 3 minutes - driveSize->QuadPart = sysLength.QuadPart; - TCfree (sectorBuffer); - return STATUS_TIMEOUT; - } - } -} - - -NTSTATUS TCOpenFsVolume (PEXTENSION Extension, PHANDLE volumeHandle, PFILE_OBJECT * fileObject) -{ - NTSTATUS ntStatus; - OBJECT_ATTRIBUTES objectAttributes; - UNICODE_STRING fullFileName; - IO_STATUS_BLOCK ioStatus; - WCHAR volumeName[TC_MAX_PATH]; - - TCGetNTNameFromNumber (volumeName, sizeof(volumeName),Extension->nDosDriveNo); - RtlInitUnicodeString (&fullFileName, volumeName); - InitializeObjectAttributes (&objectAttributes, &fullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); - - ntStatus = ZwCreateFile (volumeHandle, - SYNCHRONIZE | GENERIC_READ, - &objectAttributes, - &ioStatus, - NULL, - FILE_ATTRIBUTE_NORMAL, - FILE_SHARE_READ | FILE_SHARE_WRITE, - FILE_OPEN, - FILE_SYNCHRONOUS_IO_NONALERT, - NULL, - 0); - - Dump ("Volume %ls open NTSTATUS 0x%08x\n", volumeName, ntStatus); - - if (!NT_SUCCESS (ntStatus)) - return ntStatus; - - ntStatus = ObReferenceObjectByHandle (*volumeHandle, - FILE_READ_DATA, - NULL, - KernelMode, - fileObject, - NULL); - - if (!NT_SUCCESS (ntStatus)) - ZwClose (*volumeHandle); - - return ntStatus; -} - - -void TCCloseFsVolume (HANDLE volumeHandle, PFILE_OBJECT fileObject) -{ - ObDereferenceObject (fileObject); - ZwClose (volumeHandle); -} - - -static NTSTATUS TCReadWriteDevice (BOOL write, PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length) -{ - NTSTATUS status; - IO_STATUS_BLOCK ioStatusBlock; - PIRP irp; - KEVENT completionEvent; - - ASSERT (KeGetCurrentIrql() <= APC_LEVEL); - - KeInitializeEvent (&completionEvent, NotificationEvent, FALSE); - irp = IoBuildSynchronousFsdRequest (write ? IRP_MJ_WRITE : IRP_MJ_READ, deviceObject, buffer, length, &offset, &completionEvent, &ioStatusBlock); - if (!irp) - return STATUS_INSUFFICIENT_RESOURCES; - - ObReferenceObject (deviceObject); - status = IoCallDriver (deviceObject, irp); - - if (status == STATUS_PENDING) - { - status = KeWaitForSingleObject (&completionEvent, Executive, KernelMode, FALSE, NULL); - if (NT_SUCCESS (status)) - status = ioStatusBlock.Status; - } - - ObDereferenceObject (deviceObject); - return status; -} - - -NTSTATUS TCReadDevice (PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length) -{ - return TCReadWriteDevice (FALSE, deviceObject, buffer, offset, length); -} - - -NTSTATUS TCWriteDevice (PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length) -{ - return TCReadWriteDevice (TRUE, deviceObject, buffer, offset, length); -} - - -NTSTATUS TCFsctlCall (PFILE_OBJECT fileObject, LONG IoControlCode, - void *InputBuffer, int InputBufferSize, void *OutputBuffer, int OutputBufferSize) -{ - IO_STATUS_BLOCK ioStatusBlock; - NTSTATUS ntStatus; - PIRP irp; - KEVENT event; - PIO_STACK_LOCATION stack; - PDEVICE_OBJECT deviceObject = IoGetRelatedDeviceObject (fileObject); - - KeInitializeEvent(&event, NotificationEvent, FALSE); - - irp = IoBuildDeviceIoControlRequest (IoControlCode, - deviceObject, - InputBuffer, InputBufferSize, - OutputBuffer, OutputBufferSize, - FALSE, - &event, - &ioStatusBlock); - - if (irp == NULL) - return STATUS_INSUFFICIENT_RESOURCES; - - stack = IoGetNextIrpStackLocation(irp); - - stack->MajorFunction = IRP_MJ_FILE_SYSTEM_CONTROL; - stack->MinorFunction = IRP_MN_USER_FS_REQUEST; - stack->FileObject = fileObject; - - ntStatus = IoCallDriver (deviceObject, irp); - if (ntStatus == STATUS_PENDING) - { - KeWaitForSingleObject (&event, Executive, KernelMode, FALSE, NULL); - ntStatus = ioStatusBlock.Status; - } - - return ntStatus; -} - - -NTSTATUS CreateDriveLink (int nDosDriveNo) -{ - WCHAR dev[128], link[128]; - UNICODE_STRING deviceName, symLink; - NTSTATUS ntStatus; - - TCGetNTNameFromNumber (dev, sizeof(dev),nDosDriveNo); - TCGetDosNameFromNumber (link, sizeof(link),nDosDriveNo, DeviceNamespaceDefault); - - RtlInitUnicodeString (&deviceName, dev); - RtlInitUnicodeString (&symLink, link); - - ntStatus = IoCreateSymbolicLink (&symLink, &deviceName); - Dump ("IoCreateSymbolicLink returned %X\n", ntStatus); - return ntStatus; -} - - -NTSTATUS RemoveDriveLink (int nDosDriveNo) -{ - WCHAR link[256]; - UNICODE_STRING symLink; - NTSTATUS ntStatus; - - TCGetDosNameFromNumber (link, sizeof(link),nDosDriveNo, DeviceNamespaceDefault); - RtlInitUnicodeString (&symLink, link); - - ntStatus = IoDeleteSymbolicLink (&symLink); - Dump ("IoDeleteSymbolicLink returned %X\n", ntStatus); - return ntStatus; -} - - -NTSTATUS MountManagerMount (MOUNT_STRUCT *mount) -{ - NTSTATUS ntStatus; - WCHAR arrVolume[256]; - char buf[200]; - PMOUNTMGR_TARGET_NAME in = (PMOUNTMGR_TARGET_NAME) buf; - PMOUNTMGR_CREATE_POINT_INPUT point = (PMOUNTMGR_CREATE_POINT_INPUT) buf; - - TCGetNTNameFromNumber (arrVolume, sizeof(arrVolume),mount->nDosDriveNo); - in->DeviceNameLength = (USHORT) wcslen (arrVolume) * 2; - RtlStringCbCopyW(in->DeviceName, sizeof(buf) - sizeof(in->DeviceNameLength),arrVolume); - - ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION, - in, (ULONG) (sizeof (in->DeviceNameLength) + wcslen (arrVolume) * 2), 0, 0); - - memset (buf, 0, sizeof buf); - TCGetDosNameFromNumber ((PWSTR) &point[1], sizeof(buf) - sizeof(MOUNTMGR_CREATE_POINT_INPUT),mount->nDosDriveNo, DeviceNamespaceDefault); - - point->SymbolicLinkNameOffset = sizeof (MOUNTMGR_CREATE_POINT_INPUT); - point->SymbolicLinkNameLength = (USHORT) wcslen ((PWSTR) &point[1]) * 2; - - point->DeviceNameOffset = point->SymbolicLinkNameOffset + point->SymbolicLinkNameLength; - TCGetNTNameFromNumber ((PWSTR) (buf + point->DeviceNameOffset), sizeof(buf) - point->DeviceNameOffset,mount->nDosDriveNo); - point->DeviceNameLength = (USHORT) wcslen ((PWSTR) (buf + point->DeviceNameOffset)) * 2; - - ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_CREATE_POINT, point, - point->DeviceNameOffset + point->DeviceNameLength, 0, 0); - - return ntStatus; -} - - -NTSTATUS MountManagerUnmount (int nDosDriveNo) -{ - NTSTATUS ntStatus; - char buf[256], out[300]; - PMOUNTMGR_MOUNT_POINT in = (PMOUNTMGR_MOUNT_POINT) buf; - - memset (buf, 0, sizeof buf); - - TCGetDosNameFromNumber ((PWSTR) &in[1], sizeof(buf) - sizeof(MOUNTMGR_MOUNT_POINT),nDosDriveNo, DeviceNamespaceDefault); - - // Only symbolic link can be deleted with IOCTL_MOUNTMGR_DELETE_POINTS. If any other entry is specified, the mount manager will ignore subsequent IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION for the same volume ID. - in->SymbolicLinkNameOffset = sizeof (MOUNTMGR_MOUNT_POINT); - in->SymbolicLinkNameLength = (USHORT) wcslen ((PWCHAR) &in[1]) * 2; - - ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_DELETE_POINTS, - in, sizeof(MOUNTMGR_MOUNT_POINT) + in->SymbolicLinkNameLength, out, sizeof out); - - Dump ("IOCTL_MOUNTMGR_DELETE_POINTS returned 0x%08x\n", ntStatus); - - return ntStatus; -} - - -NTSTATUS MountDevice (PDEVICE_OBJECT DeviceObject, MOUNT_STRUCT *mount) -{ - PDEVICE_OBJECT NewDeviceObject; - NTSTATUS ntStatus; - - // Make sure the user is asking for a reasonable nDosDriveNo - if (mount->nDosDriveNo >= 0 && mount->nDosDriveNo <= 25 - && IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceDefault) // drive letter must not exist both locally and globally - && IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceGlobal) - ) - { - Dump ("Mount request looks valid\n"); - } - else - { - Dump ("WARNING: MOUNT DRIVE LETTER INVALID\n"); - mount->nReturnCode = ERR_DRIVE_NOT_FOUND; - return ERR_DRIVE_NOT_FOUND; - } - - if (!SelfTestsPassed) - { - mount->nReturnCode = ERR_SELF_TESTS_FAILED; - return ERR_SELF_TESTS_FAILED; - } - - ntStatus = TCCreateDeviceObject (DeviceObject->DriverObject, &NewDeviceObject, mount); - - if (!NT_SUCCESS (ntStatus)) - { - Dump ("Mount CREATE DEVICE ERROR, ntStatus = 0x%08x\n", ntStatus); - return ntStatus; - } - else - { - PEXTENSION NewExtension = (PEXTENSION) NewDeviceObject->DeviceExtension; - SECURITY_SUBJECT_CONTEXT subContext; - PACCESS_TOKEN accessToken; - - SeCaptureSubjectContext (&subContext); - SeLockSubjectContext(&subContext); - if (subContext.ClientToken && subContext.ImpersonationLevel >= SecurityImpersonation) - accessToken = subContext.ClientToken; - else - accessToken = subContext.PrimaryToken; - - if (!accessToken) - { - ntStatus = STATUS_INVALID_PARAMETER; - } - else - { - PTOKEN_USER tokenUser; - - ntStatus = SeQueryInformationToken (accessToken, TokenUser, &tokenUser); - if (NT_SUCCESS (ntStatus)) - { - ULONG sidLength = RtlLengthSid (tokenUser->User.Sid); - - NewExtension->UserSid = TCalloc (sidLength); - if (!NewExtension->UserSid) - ntStatus = STATUS_INSUFFICIENT_RESOURCES; - else - ntStatus = RtlCopySid (sidLength, NewExtension->UserSid, tokenUser->User.Sid); - - ExFreePool (tokenUser); // Documented in newer versions of WDK - } - } - - SeUnlockSubjectContext(&subContext); - SeReleaseSubjectContext (&subContext); - - if (NT_SUCCESS (ntStatus)) - ntStatus = TCStartVolumeThread (NewDeviceObject, NewExtension, mount); - - if (!NT_SUCCESS (ntStatus)) - { - Dump ("Mount FAILURE NT ERROR, ntStatus = 0x%08x\n", ntStatus); - TCDeleteDeviceObject (NewDeviceObject, NewExtension); - return ntStatus; - } - else - { - if (mount->nReturnCode == 0) - { - HANDLE volumeHandle; - PFILE_OBJECT volumeFileObject; - ULONG labelLen = (ULONG) wcslen (mount->wszLabel); - BOOL bIsNTFS = FALSE; - ULONG labelMaxLen, labelEffectiveLen; - - Dump ("Mount SUCCESS TC code = 0x%08x READ-ONLY = %d\n", mount->nReturnCode, NewExtension->bReadOnly); - - if (NewExtension->bReadOnly) - NewDeviceObject->Characteristics |= FILE_READ_ONLY_DEVICE; - - NewDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; - - NewExtension->UniqueVolumeId = LastUniqueVolumeId++; - - // check again that the drive letter is available globally and locally - if ( !IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceDefault) - || !IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceGlobal) - ) - { - TCDeleteDeviceObject (NewDeviceObject, NewExtension); - mount->nReturnCode = ERR_DRIVE_NOT_FOUND; - return ERR_DRIVE_NOT_FOUND; - } - - if (mount->bMountManager) - MountManagerMount (mount); - - NewExtension->bMountManager = mount->bMountManager; - - // We create symbolic link even if mount manager is notified of - // arriving volume as it apparently sometimes fails to create the link - CreateDriveLink (mount->nDosDriveNo); - - mount->FilesystemDirty = FALSE; - - if (NT_SUCCESS (TCOpenFsVolume (NewExtension, &volumeHandle, &volumeFileObject))) - { - __try - { - ULONG fsStatus; - - if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_IS_VOLUME_DIRTY, NULL, 0, &fsStatus, sizeof (fsStatus))) - && (fsStatus & VOLUME_IS_DIRTY)) - { - mount->FilesystemDirty = TRUE; - } - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - mount->FilesystemDirty = TRUE; - } - - // detect if the filesystem is NTFS or FAT - __try - { - NTFS_VOLUME_DATA_BUFFER ntfsData; - if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsData, sizeof (ntfsData)))) - { - bIsNTFS = TRUE; - } - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - bIsNTFS = FALSE; - } - - NewExtension->bIsNTFS = bIsNTFS; - mount->bIsNTFS = bIsNTFS; - - if (labelLen > 0) - { - if (bIsNTFS) - labelMaxLen = 32; // NTFS maximum label length - else - labelMaxLen = 11; // FAT maximum label length - - // calculate label effective length - labelEffectiveLen = labelLen > labelMaxLen? labelMaxLen : labelLen; - - // correct the label in the device - memset (&NewExtension->wszLabel[labelEffectiveLen], 0, 33 - labelEffectiveLen); - memcpy (mount->wszLabel, NewExtension->wszLabel, 33); - - // set the volume label - __try - { - IO_STATUS_BLOCK ioblock; - ULONG labelInfoSize = sizeof(FILE_FS_LABEL_INFORMATION) + (labelEffectiveLen * sizeof(WCHAR)); - FILE_FS_LABEL_INFORMATION* labelInfo = (FILE_FS_LABEL_INFORMATION*) TCalloc (labelInfoSize); - labelInfo->VolumeLabelLength = labelEffectiveLen * sizeof(WCHAR); - memcpy (labelInfo->VolumeLabel, mount->wszLabel, labelInfo->VolumeLabelLength); - - if (STATUS_SUCCESS == ZwSetVolumeInformationFile (volumeHandle, &ioblock, labelInfo, labelInfoSize, FileFsLabelInformation)) - { - mount->bDriverSetLabel = TRUE; - NewExtension->bDriverSetLabel = TRUE; - } - - TCfree(labelInfo); - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - - } - } - - TCCloseFsVolume (volumeHandle, volumeFileObject); - } - } - else - { - Dump ("Mount FAILURE TC code = 0x%08x\n", mount->nReturnCode); - TCDeleteDeviceObject (NewDeviceObject, NewExtension); - } - - return STATUS_SUCCESS; - } - } -} - -NTSTATUS UnmountDevice (UNMOUNT_STRUCT *unmountRequest, PDEVICE_OBJECT deviceObject, BOOL ignoreOpenFiles) -{ - PEXTENSION extension = deviceObject->DeviceExtension; - NTSTATUS ntStatus; - HANDLE volumeHandle; - PFILE_OBJECT volumeFileObject; - - Dump ("UnmountDevice %d\n", extension->nDosDriveNo); - - ntStatus = TCOpenFsVolume (extension, &volumeHandle, &volumeFileObject); - - if (NT_SUCCESS (ntStatus)) - { - int dismountRetry; - - // Dismounting a writable NTFS filesystem prevents the driver from being unloaded on Windows 7 - if (IsOSAtLeast (WIN_7) && !extension->bReadOnly) - { - NTFS_VOLUME_DATA_BUFFER ntfsData; - - if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsData, sizeof (ntfsData)))) - DriverUnloadDisabled = TRUE; - } - - // Lock volume - ntStatus = TCFsctlCall (volumeFileObject, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0); - Dump ("FSCTL_LOCK_VOLUME returned %X\n", ntStatus); - - if (!NT_SUCCESS (ntStatus) && !ignoreOpenFiles) - { - TCCloseFsVolume (volumeHandle, volumeFileObject); - return ERR_FILES_OPEN; - } - - // Dismount volume - for (dismountRetry = 0; dismountRetry < 200; ++dismountRetry) - { - ntStatus = TCFsctlCall (volumeFileObject, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0); - Dump ("FSCTL_DISMOUNT_VOLUME returned %X\n", ntStatus); - - if (NT_SUCCESS (ntStatus) || ntStatus == STATUS_VOLUME_DISMOUNTED) - break; - - if (!ignoreOpenFiles) - { - TCCloseFsVolume (volumeHandle, volumeFileObject); - return ERR_FILES_OPEN; - } - - TCSleep (100); - } - } - else - { - // Volume cannot be opened => force dismount if allowed - if (!ignoreOpenFiles) - return ERR_FILES_OPEN; - else - volumeHandle = NULL; - } - - if (extension->bMountManager) - MountManagerUnmount (extension->nDosDriveNo); - - // We always remove symbolic link as mount manager might fail to do so - RemoveDriveLink (extension->nDosDriveNo); - - extension->bShuttingDown = TRUE; - - ntStatus = IoAcquireRemoveLock (&extension->Queue.RemoveLock, NULL); - ASSERT (NT_SUCCESS (ntStatus)); - IoReleaseRemoveLockAndWait (&extension->Queue.RemoveLock, NULL); - - if (volumeHandle != NULL) - TCCloseFsVolume (volumeHandle, volumeFileObject); - - if (unmountRequest) - { - PCRYPTO_INFO cryptoInfo = ((PEXTENSION) deviceObject->DeviceExtension)->cryptoInfo; - unmountRequest->HiddenVolumeProtectionTriggered = (cryptoInfo->bProtectHiddenVolume && cryptoInfo->bHiddenVolProtectionAction); - } - - TCDeleteDeviceObject (deviceObject, (PEXTENSION) deviceObject->DeviceExtension); - return 0; -} - - -static PDEVICE_OBJECT FindVolumeWithHighestUniqueId (int maxUniqueId) -{ - PDEVICE_OBJECT highestIdDevice = NULL; - int highestId = -1; - int drive; - - for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) - { - PDEVICE_OBJECT device = GetVirtualVolumeDeviceObject (drive); - if (device) - { - PEXTENSION extension = (PEXTENSION) device->DeviceExtension; - if (extension->UniqueVolumeId > highestId && extension->UniqueVolumeId <= maxUniqueId) - { - highestId = extension->UniqueVolumeId; - highestIdDevice = device; - } - } - } - - return highestIdDevice; -} - - -NTSTATUS UnmountAllDevices (UNMOUNT_STRUCT *unmountRequest, BOOL ignoreOpenFiles) -{ - NTSTATUS status = 0; - PDEVICE_OBJECT ListDevice; - int maxUniqueId = LastUniqueVolumeId; - - Dump ("Unmounting all volumes\n"); - - if (unmountRequest) - unmountRequest->HiddenVolumeProtectionTriggered = FALSE; - - // Dismount volumes in the reverse order they were mounted to properly dismount nested volumes - while ((ListDevice = FindVolumeWithHighestUniqueId (maxUniqueId)) != NULL) - { - PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; - maxUniqueId = ListExtension->UniqueVolumeId - 1; - - if (IsVolumeAccessibleByCurrentUser (ListExtension)) - { - NTSTATUS ntStatus; - - if (unmountRequest) - unmountRequest->nDosDriveNo = ListExtension->nDosDriveNo; - - ntStatus = UnmountDevice (unmountRequest, ListDevice, ignoreOpenFiles); - status = ntStatus == 0 ? status : ntStatus; - - if (unmountRequest && unmountRequest->HiddenVolumeProtectionTriggered) - break; - } - } - - return status; -} - -// Resolves symbolic link name to its target name -NTSTATUS SymbolicLinkToTarget (PWSTR symlinkName, PWSTR targetName, USHORT maxTargetNameLength) -{ - NTSTATUS ntStatus; - OBJECT_ATTRIBUTES objectAttributes; - UNICODE_STRING fullFileName; - HANDLE handle; - - RtlInitUnicodeString (&fullFileName, symlinkName); - InitializeObjectAttributes (&objectAttributes, &fullFileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); - - ntStatus = ZwOpenSymbolicLinkObject (&handle, GENERIC_READ, &objectAttributes); - - if (NT_SUCCESS (ntStatus)) - { - UNICODE_STRING target; - target.Buffer = targetName; - target.Length = 0; - target.MaximumLength = maxTargetNameLength; - memset (targetName, 0, maxTargetNameLength); - - ntStatus = ZwQuerySymbolicLinkObject (handle, &target, NULL); - - ZwClose (handle); - } - - return ntStatus; -} - - -// Checks if two regions overlap (borders are parts of regions) -BOOL RegionsOverlap (unsigned __int64 start1, unsigned __int64 end1, unsigned __int64 start2, unsigned __int64 end2) -{ - return (start1 < start2) ? (end1 >= start2) : (start1 <= end2); -} - - -void GetIntersection (uint64 start1, uint32 length1, uint64 start2, uint64 end2, uint64 *intersectStart, uint32 *intersectLength) -{ - uint64 end1 = start1 + length1 - 1; - uint64 intersectEnd = (end1 <= end2) ? end1 : end2; - - *intersectStart = (start1 >= start2) ? start1 : start2; - *intersectLength = (uint32) ((*intersectStart > intersectEnd) ? 0 : intersectEnd + 1 - *intersectStart); - - if (*intersectLength == 0) - *intersectStart = start1; -} - - -BOOL IsAccessibleByUser (PUNICODE_STRING objectFileName, BOOL readOnly) -{ - OBJECT_ATTRIBUTES fileObjAttributes; - IO_STATUS_BLOCK ioStatusBlock; - HANDLE fileHandle; - NTSTATUS status; - - ASSERT (!IoIsSystemThread (PsGetCurrentThread())); - - InitializeObjectAttributes (&fileObjAttributes, objectFileName, OBJ_CASE_INSENSITIVE | OBJ_FORCE_ACCESS_CHECK | OBJ_KERNEL_HANDLE, NULL, NULL); - - status = ZwCreateFile (&fileHandle, - readOnly ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE, - &fileObjAttributes, - &ioStatusBlock, - NULL, - FILE_ATTRIBUTE_NORMAL, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - FILE_OPEN, - FILE_SYNCHRONOUS_IO_NONALERT, - NULL, - 0); - - if (NT_SUCCESS (status)) - { - ZwClose (fileHandle); - return TRUE; - } - - return FALSE; -} - - -BOOL UserCanAccessDriveDevice () -{ - UNICODE_STRING name; - RtlInitUnicodeString (&name, L"\\Device\\MountPointManager"); - - return IsAccessibleByUser (&name, FALSE); -} - -BOOL IsDriveLetterAvailable (int nDosDriveNo, DeviceNamespaceType namespaceType) -{ - OBJECT_ATTRIBUTES objectAttributes; - UNICODE_STRING objectName; - WCHAR link[128]; - HANDLE handle; - NTSTATUS ntStatus; - - TCGetDosNameFromNumber (link, sizeof(link),nDosDriveNo, namespaceType); - RtlInitUnicodeString (&objectName, link); - InitializeObjectAttributes (&objectAttributes, &objectName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); - - if (NT_SUCCESS (ntStatus = ZwOpenSymbolicLinkObject (&handle, GENERIC_READ, &objectAttributes))) - { - ZwClose (handle); - return FALSE; - } - - return (ntStatus == STATUS_OBJECT_NAME_NOT_FOUND)? TRUE : FALSE; -} - - -NTSTATUS TCCompleteIrp (PIRP irp, NTSTATUS status, ULONG_PTR information) -{ - irp->IoStatus.Status = status; - irp->IoStatus.Information = information; - IoCompleteRequest (irp, IO_NO_INCREMENT); - return status; -} - - -NTSTATUS TCCompleteDiskIrp (PIRP irp, NTSTATUS status, ULONG_PTR information) -{ - irp->IoStatus.Status = status; - irp->IoStatus.Information = information; - IoCompleteRequest (irp, NT_SUCCESS (status) ? IO_DISK_INCREMENT : IO_NO_INCREMENT); - return status; -} - - -size_t GetCpuCount () -{ - KAFFINITY activeCpuMap = KeQueryActiveProcessors(); - size_t mapSize = sizeof (activeCpuMap) * 8; - size_t cpuCount = 0; - - while (mapSize--) - { - if (activeCpuMap & 1) - ++cpuCount; - - activeCpuMap >>= 1; - } - - if (cpuCount == 0) - return 1; - - return cpuCount; -} - - -void EnsureNullTerminatedString (wchar_t *str, size_t maxSizeInBytes) -{ - ASSERT ((maxSizeInBytes & 1) == 0); - str[maxSizeInBytes / sizeof (wchar_t) - 1] = 0; -} - - -void *AllocateMemoryWithTimeout (size_t size, int retryDelay, int timeout) -{ - LARGE_INTEGER waitInterval; - waitInterval.QuadPart = retryDelay * -10000; - - ASSERT (KeGetCurrentIrql() <= APC_LEVEL); - ASSERT (retryDelay > 0 && retryDelay <= timeout); - - while (TRUE) - { - void *memory = TCalloc (size); - if (memory) - return memory; - - timeout -= retryDelay; - if (timeout <= 0) - break; - - KeDelayExecutionThread (KernelMode, FALSE, &waitInterval); - } - - return NULL; -} - - -NTSTATUS TCReadRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, PKEY_VALUE_PARTIAL_INFORMATION *keyData) -{ - OBJECT_ATTRIBUTES regObjAttribs; - HANDLE regKeyHandle; - NTSTATUS status; - UNICODE_STRING valName; - ULONG size = 0; - ULONG resultSize; - - InitializeObjectAttributes (®ObjAttribs, keyPath, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); - status = ZwOpenKey (®KeyHandle, KEY_READ, ®ObjAttribs); - if (!NT_SUCCESS (status)) - return status; - - RtlInitUnicodeString (&valName, keyValueName); - status = ZwQueryValueKey (regKeyHandle, &valName, KeyValuePartialInformation, NULL, 0, &size); - - if (!NT_SUCCESS (status) && status != STATUS_BUFFER_OVERFLOW && status != STATUS_BUFFER_TOO_SMALL) - { - ZwClose (regKeyHandle); - return status; - } - - if (size == 0) - { - ZwClose (regKeyHandle); - return STATUS_NO_DATA_DETECTED; - } - - *keyData = (PKEY_VALUE_PARTIAL_INFORMATION) TCalloc (size); - if (!*keyData) - { - ZwClose (regKeyHandle); - return STATUS_INSUFFICIENT_RESOURCES; - } - - status = ZwQueryValueKey (regKeyHandle, &valName, KeyValuePartialInformation, *keyData, size, &resultSize); - - ZwClose (regKeyHandle); - return status; -} - - -NTSTATUS TCWriteRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, ULONG keyValueType, void *valueData, ULONG valueSize) -{ - OBJECT_ATTRIBUTES regObjAttribs; - HANDLE regKeyHandle; - NTSTATUS status; - UNICODE_STRING valName; - - InitializeObjectAttributes (®ObjAttribs, keyPath, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); - status = ZwOpenKey (®KeyHandle, KEY_READ | KEY_WRITE, ®ObjAttribs); - if (!NT_SUCCESS (status)) - return status; - - RtlInitUnicodeString (&valName, keyValueName); - - status = ZwSetValueKey (regKeyHandle, &valName, 0, keyValueType, valueData, valueSize); - - ZwClose (regKeyHandle); - return status; -} - - -BOOL IsVolumeClassFilterRegistered () -{ - UNICODE_STRING name; - NTSTATUS status; - BOOL registered = FALSE; - - PKEY_VALUE_PARTIAL_INFORMATION data; - - RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{71A27CDD-812A-11D0-BEC7-08002BE2092F}"); - status = TCReadRegistryKey (&name, L"UpperFilters", &data); - - if (NT_SUCCESS (status)) - { - if (data->Type == REG_MULTI_SZ && data->DataLength >= 9 * sizeof (wchar_t)) - { - // Search for the string "veracrypt" - ULONG i; - for (i = 0; i <= data->DataLength - 9 * sizeof (wchar_t); ++i) - { - if (memcmp (data->Data + i, L"veracrypt", 9 * sizeof (wchar_t)) == 0) - { - Dump ("Volume class filter active\n"); - registered = TRUE; - break; - } - } - } - - TCfree (data); - } - - return registered; -} - - -NTSTATUS ReadRegistryConfigFlags (BOOL driverEntry) -{ - PKEY_VALUE_PARTIAL_INFORMATION data; - UNICODE_STRING name; - NTSTATUS status; - uint32 flags = 0; - - RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\veracrypt"); - status = TCReadRegistryKey (&name, TC_DRIVER_CONFIG_REG_VALUE_NAME, &data); - - if (NT_SUCCESS (status)) - { - if (data->Type == REG_DWORD) - { - flags = *(uint32 *) data->Data; - Dump ("Configuration flags = 0x%x\n", flags); - - if (driverEntry) - { - if (flags & (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD | TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES)) - CacheBootPassword = TRUE; - - if (flags & TC_DRIVER_CONFIG_DISABLE_NONADMIN_SYS_FAVORITES_ACCESS) - NonAdminSystemFavoritesAccessDisabled = TRUE; - - if (flags & TC_DRIVER_CONFIG_CACHE_BOOT_PIM) - CacheBootPim = TRUE; - } - - EnableHwEncryption ((flags & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? FALSE : TRUE); - - EnableExtendedIoctlSupport = (flags & TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL)? TRUE : FALSE; - } - else - status = STATUS_INVALID_PARAMETER; - - TCfree (data); - } - - if (driverEntry && NT_SUCCESS (TCReadRegistryKey (&name, TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME, &data))) - { - if (data->Type == REG_DWORD) - EncryptionThreadPoolFreeCpuCountLimit = *(uint32 *) data->Data; - - TCfree (data); - } - - return status; -} - - -NTSTATUS WriteRegistryConfigFlags (uint32 flags) -{ - UNICODE_STRING name; - RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\veracrypt"); - - return TCWriteRegistryKey (&name, TC_DRIVER_CONFIG_REG_VALUE_NAME, REG_DWORD, &flags, sizeof (flags)); -} - - -NTSTATUS GetDeviceSectorSize (PDEVICE_OBJECT deviceObject, ULONG *bytesPerSector) -{ - NTSTATUS status; - DISK_GEOMETRY geometry; - - status = SendDeviceIoControlRequest (deviceObject, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &geometry, sizeof (geometry)); - - if (!NT_SUCCESS (status)) - return status; - - *bytesPerSector = geometry.BytesPerSector; - return STATUS_SUCCESS; -} - - -NTSTATUS ZeroUnreadableSectors (PDEVICE_OBJECT deviceObject, LARGE_INTEGER startOffset, ULONG size, uint64 *zeroedSectorCount) -{ - NTSTATUS status; - ULONG sectorSize; - ULONG sectorCount; - byte *sectorBuffer = NULL; - - *zeroedSectorCount = 0; - - status = GetDeviceSectorSize (deviceObject, §orSize); - if (!NT_SUCCESS (status)) - return status; - - sectorBuffer = TCalloc (sectorSize); - if (!sectorBuffer) - return STATUS_INSUFFICIENT_RESOURCES; - - for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount, startOffset.QuadPart += sectorSize) - { - status = TCReadDevice (deviceObject, sectorBuffer, startOffset, sectorSize); - if (!NT_SUCCESS (status)) - { - Dump ("Zeroing sector at %I64d\n", startOffset.QuadPart); - memset (sectorBuffer, 0, sectorSize); - - status = TCWriteDevice (deviceObject, sectorBuffer, startOffset, sectorSize); - if (!NT_SUCCESS (status)) - goto err; - - ++(*zeroedSectorCount); - } - } - - status = STATUS_SUCCESS; - -err: - if (sectorBuffer) - TCfree (sectorBuffer); - - return status; -} - - -NTSTATUS ReadDeviceSkipUnreadableSectors (PDEVICE_OBJECT deviceObject, byte *buffer, LARGE_INTEGER startOffset, ULONG size, uint64 *badSectorCount) -{ - NTSTATUS status; - ULONG sectorSize; - ULONG sectorCount; - - *badSectorCount = 0; - - status = GetDeviceSectorSize (deviceObject, §orSize); - if (!NT_SUCCESS (status)) - return status; - - for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount, startOffset.QuadPart += sectorSize, buffer += sectorSize) - { - status = TCReadDevice (deviceObject, buffer, startOffset, sectorSize); - if (!NT_SUCCESS (status)) - { - Dump ("Skipping bad sector at %I64d\n", startOffset.QuadPart); - memset (buffer, 0, sectorSize); - ++(*badSectorCount); - } - } - - return STATUS_SUCCESS; -} - - -BOOL IsVolumeAccessibleByCurrentUser (PEXTENSION volumeDeviceExtension) -{ - SECURITY_SUBJECT_CONTEXT subContext; - PACCESS_TOKEN accessToken; - PTOKEN_USER tokenUser; - BOOL result = FALSE; - - if (IoIsSystemThread (PsGetCurrentThread()) - || UserCanAccessDriveDevice() - || !volumeDeviceExtension->UserSid - || (volumeDeviceExtension->SystemFavorite && !NonAdminSystemFavoritesAccessDisabled)) - { - return TRUE; - } - - SeCaptureSubjectContext (&subContext); - SeLockSubjectContext(&subContext); - if (subContext.ClientToken && subContext.ImpersonationLevel >= SecurityImpersonation) - accessToken = subContext.ClientToken; - else - accessToken = subContext.PrimaryToken; - - if (!accessToken) - goto ret; - - if (SeTokenIsAdmin (accessToken)) - { - result = TRUE; - goto ret; - } - - if (!NT_SUCCESS (SeQueryInformationToken (accessToken, TokenUser, &tokenUser))) - goto ret; - - result = RtlEqualSid (volumeDeviceExtension->UserSid, tokenUser->User.Sid); - ExFreePool (tokenUser); // Documented in newer versions of WDK - -ret: - SeUnlockSubjectContext(&subContext); - SeReleaseSubjectContext (&subContext); - return result; -} - - -void GetElapsedTimeInit (LARGE_INTEGER *lastPerfCounter) -{ - *lastPerfCounter = KeQueryPerformanceCounter (NULL); -} - - -// Returns elapsed time in microseconds since last call -int64 GetElapsedTime (LARGE_INTEGER *lastPerfCounter) -{ - LARGE_INTEGER freq; - LARGE_INTEGER counter = KeQueryPerformanceCounter (&freq); - - int64 elapsed = (counter.QuadPart - lastPerfCounter->QuadPart) * 1000000LL / freq.QuadPart; - *lastPerfCounter = counter; - - return elapsed; -} - - -BOOL IsOSAtLeast (OSVersionEnum reqMinOS) -{ - /* When updating this function, update IsOSVersionAtLeast() in Dlgcode.c too. */ - - ULONG major = 0, minor = 0; - - ASSERT (OsMajorVersion != 0); - - switch (reqMinOS) - { - case WIN_2000: major = 5; minor = 0; break; - case WIN_XP: major = 5; minor = 1; break; - case WIN_SERVER_2003: major = 5; minor = 2; break; - case WIN_VISTA: major = 6; minor = 0; break; - case WIN_7: major = 6; minor = 1; break; - case WIN_8: major = 6; minor = 2; break; - case WIN_8_1: major = 6; minor = 3; break; - case WIN_10: major = 10; minor = 0; break; - - default: - TC_THROW_FATAL_EXCEPTION; - break; - } - - return ((OsMajorVersion << 16 | OsMinorVersion << 8) - >= (major << 16 | minor << 8)); -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "TCdefs.h" +#include +#include "Crypto.h" +#include "Fat.h" +#include "Tests.h" +#include "cpu.h" + +#include "Apidrvr.h" +#include "Boot/Windows/BootDefs.h" +#include "EncryptedIoQueue.h" +#include "EncryptionThreadPool.h" +#include "Ntdriver.h" +#include "Ntvol.h" +#include "DriveFilter.h" +#include "DumpFilter.h" +#include "Cache.h" +#include "Volumes.h" +#include "VolumeFilter.h" + +#include +#include +#include +#include +#include + +#include +#include + +/* Init section, which is thrown away as soon as DriverEntry returns */ +#pragma alloc_text(INIT,DriverEntry) +#pragma alloc_text(INIT,TCCreateRootDeviceObject) + +PDRIVER_OBJECT TCDriverObject; +PDEVICE_OBJECT RootDeviceObject = NULL; +static KMUTEX RootDeviceControlMutex; +BOOL DriverShuttingDown = FALSE; +BOOL SelfTestsPassed; +int LastUniqueVolumeId; +ULONG OsMajorVersion = 0; +ULONG OsMinorVersion; +BOOL DriverUnloadDisabled = FALSE; +BOOL PortableMode = FALSE; +BOOL VolumeClassFilterRegistered = FALSE; +BOOL CacheBootPassword = FALSE; +BOOL CacheBootPim = FALSE; +BOOL NonAdminSystemFavoritesAccessDisabled = FALSE; +static size_t EncryptionThreadPoolFreeCpuCountLimit = 0; +static BOOL SystemFavoriteVolumeDirty = FALSE; +static BOOL PagingFileCreationPrevented = FALSE; +static BOOL EnableExtendedIoctlSupport = FALSE; + +PDEVICE_OBJECT VirtualVolumeDeviceObjects[MAX_MOUNTED_VOLUME_DRIVE_NUMBER + 1]; + + +NTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) +{ + PKEY_VALUE_PARTIAL_INFORMATION startKeyValue; + LONG version; + int i; + + Dump ("DriverEntry " TC_APP_NAME " " VERSION_STRING "\n"); + + DetectX86Features (); + + PsGetVersion (&OsMajorVersion, &OsMinorVersion, NULL, NULL); + + // Load dump filter if the main driver is already loaded + if (NT_SUCCESS (TCDeviceIoControl (NT_ROOT_PREFIX, TC_IOCTL_GET_DRIVER_VERSION, NULL, 0, &version, sizeof (version)))) + return DumpFilterEntry ((PFILTER_EXTENSION) DriverObject, (PFILTER_INITIALIZATION_DATA) RegistryPath); + + TCDriverObject = DriverObject; + memset (VirtualVolumeDeviceObjects, 0, sizeof (VirtualVolumeDeviceObjects)); + + ReadRegistryConfigFlags (TRUE); + EncryptionThreadPoolStart (EncryptionThreadPoolFreeCpuCountLimit); + SelfTestsPassed = AutoTestAlgorithms(); + + // Enable device class filters and load boot arguments if the driver is set to start at system boot + + if (NT_SUCCESS (TCReadRegistryKey (RegistryPath, L"Start", &startKeyValue))) + { + if (startKeyValue->Type == REG_DWORD && *((uint32 *) startKeyValue->Data) == SERVICE_BOOT_START) + { + if (!SelfTestsPassed) + TC_BUG_CHECK (STATUS_INVALID_PARAMETER); + + LoadBootArguments(); + VolumeClassFilterRegistered = IsVolumeClassFilterRegistered(); + + DriverObject->DriverExtension->AddDevice = DriverAddDevice; + } + + TCfree (startKeyValue); + } + + for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; ++i) + { + DriverObject->MajorFunction[i] = TCDispatchQueueIRP; + } + + DriverObject->DriverUnload = TCUnloadDriver; + return TCCreateRootDeviceObject (DriverObject); +} + + +NTSTATUS DriverAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo) +{ +#ifdef DEBUG + char nameInfoBuffer[128]; + POBJECT_NAME_INFORMATION nameInfo = (POBJECT_NAME_INFORMATION) nameInfoBuffer; + ULONG nameInfoSize; + Dump ("AddDevice pdo=%p type=%x name=%ws\n", pdo, pdo->DeviceType, NT_SUCCESS (ObQueryNameString (pdo, nameInfo, sizeof (nameInfoBuffer), &nameInfoSize)) ? nameInfo->Name.Buffer : L"?"); +#endif + + if (VolumeClassFilterRegistered && BootArgsValid && BootArgs.HiddenSystemPartitionStart != 0) + { + PWSTR interfaceLinks = NULL; + if (NT_SUCCESS (IoGetDeviceInterfaces (&GUID_DEVINTERFACE_VOLUME, pdo, DEVICE_INTERFACE_INCLUDE_NONACTIVE, &interfaceLinks)) && interfaceLinks) + { + if (interfaceLinks[0] != UNICODE_NULL) + { + Dump ("Volume pdo=%p interface=%ws\n", pdo, interfaceLinks); + ExFreePool (interfaceLinks); + + return VolumeFilterAddDevice (driverObject, pdo); + } + + ExFreePool (interfaceLinks); + } + } + + return DriveFilterAddDevice (driverObject, pdo); +} + + +// Dumps a memory region to debug output +void DumpMemory (void *mem, int size) +{ + unsigned char str[20]; + unsigned char *m = mem; + int i,j; + + for (j = 0; j < size / 8; j++) + { + memset (str,0,sizeof str); + for (i = 0; i < 8; i++) + { + if (m[i] > ' ' && m[i] <= '~') + str[i]=m[i]; + else + str[i]='.'; + } + + Dump ("0x%08p %02x %02x %02x %02x %02x %02x %02x %02x %s\n", + m, m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], str); + + m+=8; + } +} + + +BOOL ValidateIOBufferSize (PIRP irp, size_t requiredBufferSize, ValidateIOBufferSizeType type) +{ + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (irp); + BOOL input = (type == ValidateInput || type == ValidateInputOutput); + BOOL output = (type == ValidateOutput || type == ValidateInputOutput); + + if ((input && irpSp->Parameters.DeviceIoControl.InputBufferLength < requiredBufferSize) + || (output && irpSp->Parameters.DeviceIoControl.OutputBufferLength < requiredBufferSize)) + { + Dump ("STATUS_BUFFER_TOO_SMALL ioctl=0x%x,%d in=%d out=%d reqsize=%d insize=%d outsize=%d\n", (int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16), (int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2), input, output, requiredBufferSize, irpSp->Parameters.DeviceIoControl.InputBufferLength, irpSp->Parameters.DeviceIoControl.OutputBufferLength); + + irp->IoStatus.Status = STATUS_BUFFER_TOO_SMALL; + irp->IoStatus.Information = 0; + return FALSE; + } + + if (!input && output) + memset (irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength); + + return TRUE; +} + + +PDEVICE_OBJECT GetVirtualVolumeDeviceObject (int driveNumber) +{ + if (driveNumber < MIN_MOUNTED_VOLUME_DRIVE_NUMBER || driveNumber > MAX_MOUNTED_VOLUME_DRIVE_NUMBER) + return NULL; + + return VirtualVolumeDeviceObjects[driveNumber]; +} + + +/* TCDispatchQueueIRP queues any IRP's so that they can be processed later + by the thread -- or in some cases handles them immediately! */ +NTSTATUS TCDispatchQueueIRP (PDEVICE_OBJECT DeviceObject, PIRP Irp) +{ + PEXTENSION Extension = (PEXTENSION) DeviceObject->DeviceExtension; + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); + NTSTATUS ntStatus; + +#ifdef _DEBUG + if (irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL && (Extension->bRootDevice || Extension->IsVolumeDevice)) + { + switch (irpSp->Parameters.DeviceIoControl.IoControlCode) + { + case TC_IOCTL_GET_MOUNTED_VOLUMES: + case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: + case TC_IOCTL_GET_PORTABLE_MODE_STATUS: + case TC_IOCTL_SET_PORTABLE_MODE_STATUS: + case TC_IOCTL_OPEN_TEST: + case TC_IOCTL_GET_RESOLVED_SYMLINK: + case TC_IOCTL_GET_DEVICE_REFCOUNT: + case TC_IOCTL_GET_DRIVE_PARTITION_INFO: + case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: + case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: + case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS: + case TC_IOCTL_GET_WARNING_FLAGS: + case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: + case IOCTL_DISK_CHECK_VERIFY: + break; + + default: + Dump ("%ls (0x%x %d)\n", + TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode), + (int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16), + (int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2)); + } + } +#endif + + if (!Extension->bRootDevice) + { + // Drive filter IRP + if (Extension->IsDriveFilterDevice) + return DriveFilterDispatchIrp (DeviceObject, Irp); + + // Volume filter IRP + if (Extension->IsVolumeFilterDevice) + return VolumeFilterDispatchIrp (DeviceObject, Irp); + } + + switch (irpSp->MajorFunction) + { + case IRP_MJ_CLOSE: + case IRP_MJ_CREATE: + case IRP_MJ_CLEANUP: + return COMPLETE_IRP (DeviceObject, Irp, STATUS_SUCCESS, 0); + + case IRP_MJ_SHUTDOWN: + if (Extension->bRootDevice) + { + Dump ("Driver shutting down\n"); + DriverShuttingDown = TRUE; + + if (EncryptionSetupThread) + while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES); + + if (DecoySystemWipeThread) + while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES); + + OnShutdownPending(); + } + + return COMPLETE_IRP (DeviceObject, Irp, STATUS_SUCCESS, 0); + + case IRP_MJ_FLUSH_BUFFERS: + case IRP_MJ_READ: + case IRP_MJ_WRITE: + case IRP_MJ_DEVICE_CONTROL: + + if (Extension->bRootDevice) + { + if (irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL) + { + NTSTATUS status = KeWaitForMutexObject (&RootDeviceControlMutex, Executive, KernelMode, FALSE, NULL); + if (!NT_SUCCESS (status)) + return status; + + status = ProcessMainDeviceControlIrp (DeviceObject, Extension, Irp); + + KeReleaseMutex (&RootDeviceControlMutex, FALSE); + return status; + } + break; + } + + if (Extension->bShuttingDown) + { + Dump ("Device %d shutting down: STATUS_DELETE_PENDING\n", Extension->nDosDriveNo); + return TCCompleteDiskIrp (Irp, STATUS_DELETE_PENDING, 0); + } + + if (Extension->bRemovable + && (DeviceObject->Flags & DO_VERIFY_VOLUME) + && !(irpSp->Flags & SL_OVERRIDE_VERIFY_VOLUME) + && irpSp->MajorFunction != IRP_MJ_FLUSH_BUFFERS) + { + Dump ("Removable device %d has DO_VERIFY_VOLUME flag: STATUS_DEVICE_NOT_READY\n", Extension->nDosDriveNo); + return TCCompleteDiskIrp (Irp, STATUS_DEVICE_NOT_READY, 0); + } + + switch (irpSp->MajorFunction) + { + case IRP_MJ_READ: + case IRP_MJ_WRITE: + ntStatus = EncryptedIoQueueAddIrp (&Extension->Queue, Irp); + + if (ntStatus != STATUS_PENDING) + TCCompleteDiskIrp (Irp, ntStatus, 0); + + return ntStatus; + + case IRP_MJ_DEVICE_CONTROL: + ntStatus = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); + if (!NT_SUCCESS (ntStatus)) + return TCCompleteIrp (Irp, ntStatus, 0); + + IoMarkIrpPending (Irp); + + ExInterlockedInsertTailList (&Extension->ListEntry, &Irp->Tail.Overlay.ListEntry, &Extension->ListSpinLock); + KeReleaseSemaphore (&Extension->RequestSemaphore, IO_DISK_INCREMENT, 1, FALSE); + + return STATUS_PENDING; + + case IRP_MJ_FLUSH_BUFFERS: + return TCCompleteDiskIrp (Irp, STATUS_SUCCESS, 0); + } + + break; + + case IRP_MJ_PNP: + if (!Extension->bRootDevice + && Extension->IsVolumeDevice + && irpSp->MinorFunction == IRP_MN_DEVICE_USAGE_NOTIFICATION + && irpSp->Parameters.UsageNotification.Type == DeviceUsageTypePaging + && irpSp->Parameters.UsageNotification.InPath) + { + PagingFileCreationPrevented = TRUE; + return TCCompleteIrp (Irp, STATUS_UNSUCCESSFUL, 0); + } + break; + } + + return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); +} + +NTSTATUS TCCreateRootDeviceObject (PDRIVER_OBJECT DriverObject) +{ + UNICODE_STRING Win32NameString, ntUnicodeString; + WCHAR dosname[32], ntname[32]; + PDEVICE_OBJECT DeviceObject; + NTSTATUS ntStatus; + BOOL *bRootExtension; + + Dump ("TCCreateRootDeviceObject BEGIN\n"); + ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL); + + RtlStringCbCopyW (dosname, sizeof(dosname),(LPWSTR) DOS_ROOT_PREFIX); + RtlStringCbCopyW (ntname, sizeof(ntname),(LPWSTR) NT_ROOT_PREFIX); + RtlInitUnicodeString (&ntUnicodeString, ntname); + RtlInitUnicodeString (&Win32NameString, dosname); + + Dump ("Creating root device nt=%ls dos=%ls\n", ntname, dosname); + + ntStatus = IoCreateDevice ( + DriverObject, + sizeof (BOOL), + &ntUnicodeString, + FILE_DEVICE_UNKNOWN, + FILE_DEVICE_SECURE_OPEN, + FALSE, + &DeviceObject); + + if (!NT_SUCCESS (ntStatus)) + { + Dump ("TCCreateRootDeviceObject NTSTATUS = 0x%08x END\n", ntStatus); + return ntStatus;/* Failed to create DeviceObject */ + } + + DeviceObject->Flags |= DO_DIRECT_IO; + DeviceObject->AlignmentRequirement = FILE_WORD_ALIGNMENT; + + /* Setup the device extension */ + bRootExtension = (BOOL *) DeviceObject->DeviceExtension; + *bRootExtension = TRUE; + + KeInitializeMutex (&RootDeviceControlMutex, 0); + + ntStatus = IoCreateSymbolicLink (&Win32NameString, &ntUnicodeString); + + if (!NT_SUCCESS (ntStatus)) + { + Dump ("TCCreateRootDeviceObject NTSTATUS = 0x%08x END\n", ntStatus); + IoDeleteDevice (DeviceObject); + return ntStatus; + } + + IoRegisterShutdownNotification (DeviceObject); + RootDeviceObject = DeviceObject; + + Dump ("TCCreateRootDeviceObject STATUS_SUCCESS END\n"); + return STATUS_SUCCESS; +} + +NTSTATUS TCCreateDeviceObject (PDRIVER_OBJECT DriverObject, + PDEVICE_OBJECT * ppDeviceObject, + MOUNT_STRUCT * mount) +{ + UNICODE_STRING ntUnicodeString; + WCHAR ntname[32]; + PEXTENSION Extension; + NTSTATUS ntStatus; + ULONG devChars = 0; +#if defined (DEBUG) + WCHAR dosname[32]; +#endif + + Dump ("TCCreateDeviceObject BEGIN\n"); + ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL); + + TCGetNTNameFromNumber (ntname, sizeof(ntname),mount->nDosDriveNo); + RtlInitUnicodeString (&ntUnicodeString, ntname); +#if defined (DEBUG) + TCGetDosNameFromNumber (dosname, sizeof(dosname),mount->nDosDriveNo, DeviceNamespaceDefault); +#endif + + devChars = FILE_DEVICE_SECURE_OPEN; + devChars |= mount->bMountReadOnly ? FILE_READ_ONLY_DEVICE : 0; + devChars |= mount->bMountRemovable ? FILE_REMOVABLE_MEDIA : 0; + + Dump ("Creating device nt=%ls dos=%ls\n", ntname, dosname); + + ntStatus = IoCreateDevice ( + DriverObject, /* Our Driver Object */ + sizeof (EXTENSION), /* Size of state information */ + &ntUnicodeString, /* Device name "\Device\Name" */ + FILE_DEVICE_DISK, /* Device type */ + devChars, /* Device characteristics */ + FALSE, /* Exclusive device */ + ppDeviceObject); /* Returned ptr to Device Object */ + + if (!NT_SUCCESS (ntStatus)) + { + Dump ("TCCreateDeviceObject NTSTATUS = 0x%08x END\n", ntStatus); + return ntStatus;/* Failed to create DeviceObject */ + } + /* Initialize device object and extension. */ + + (*ppDeviceObject)->Flags |= DO_DIRECT_IO; + (*ppDeviceObject)->StackSize += 6; // Reduce occurrence of NO_MORE_IRP_STACK_LOCATIONS bug check caused by buggy drivers + + /* Setup the device extension */ + Extension = (PEXTENSION) (*ppDeviceObject)->DeviceExtension; + memset (Extension, 0, sizeof (EXTENSION)); + + Extension->IsVolumeDevice = TRUE; + Extension->nDosDriveNo = mount->nDosDriveNo; + Extension->bRemovable = mount->bMountRemovable; + Extension->PartitionInInactiveSysEncScope = mount->bPartitionInInactiveSysEncScope; + Extension->SystemFavorite = mount->SystemFavorite; + + KeInitializeEvent (&Extension->keCreateEvent, SynchronizationEvent, FALSE); + KeInitializeSemaphore (&Extension->RequestSemaphore, 0L, MAXLONG); + KeInitializeSpinLock (&Extension->ListSpinLock); + InitializeListHead (&Extension->ListEntry); + IoInitializeRemoveLock (&Extension->Queue.RemoveLock, 'LRCV', 0, 0); + + VirtualVolumeDeviceObjects[mount->nDosDriveNo] = *ppDeviceObject; + + Dump ("TCCreateDeviceObject STATUS_SUCCESS END\n"); + + return STATUS_SUCCESS; +} + + +BOOL RootDeviceControlMutexAcquireNoWait () +{ + NTSTATUS status; + LARGE_INTEGER timeout; + timeout.QuadPart = 0; + + status = KeWaitForMutexObject (&RootDeviceControlMutex, Executive, KernelMode, FALSE, &timeout); + return NT_SUCCESS (status) && status != STATUS_TIMEOUT; +} + + +void RootDeviceControlMutexRelease () +{ + KeReleaseMutex (&RootDeviceControlMutex, FALSE); +} + + +NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp) +{ + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); + + switch (irpSp->Parameters.DeviceIoControl.IoControlCode) + { + + case IOCTL_MOUNTDEV_QUERY_DEVICE_NAME: + if (!ValidateIOBufferSize (Irp, sizeof (MOUNTDEV_NAME), ValidateOutput)) + { + Irp->IoStatus.Information = sizeof (MOUNTDEV_NAME); + Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; + } + else + { + ULONG outLength; + UNICODE_STRING ntUnicodeString; + WCHAR ntName[256]; + PMOUNTDEV_NAME outputBuffer = (PMOUNTDEV_NAME) Irp->AssociatedIrp.SystemBuffer; + + TCGetNTNameFromNumber (ntName, sizeof(ntName),Extension->nDosDriveNo); + RtlInitUnicodeString (&ntUnicodeString, ntName); + + outputBuffer->NameLength = ntUnicodeString.Length; + outLength = ntUnicodeString.Length + sizeof(USHORT); + + if (irpSp->Parameters.DeviceIoControl.OutputBufferLength < outLength) + { + Irp->IoStatus.Information = sizeof (MOUNTDEV_NAME); + Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; + + break; + } + + RtlCopyMemory ((PCHAR)outputBuffer->Name,ntUnicodeString.Buffer, ntUnicodeString.Length); + + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = outLength; + + Dump ("name = %ls\n",ntName); + } + break; + + case IOCTL_MOUNTDEV_QUERY_UNIQUE_ID: + if (!ValidateIOBufferSize (Irp, sizeof (MOUNTDEV_UNIQUE_ID), ValidateOutput)) + { + Irp->IoStatus.Information = sizeof (MOUNTDEV_UNIQUE_ID); + Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; + } + else + { + ULONG outLength; + UCHAR volId[128], tmp[] = { 0,0 }; + PMOUNTDEV_UNIQUE_ID outputBuffer = (PMOUNTDEV_UNIQUE_ID) Irp->AssociatedIrp.SystemBuffer; + + RtlStringCbCopyA (volId, sizeof(volId),TC_UNIQUE_ID_PREFIX); + tmp[0] = 'A' + (UCHAR) Extension->nDosDriveNo; + RtlStringCbCatA (volId, sizeof(volId),tmp); + + outputBuffer->UniqueIdLength = (USHORT) strlen (volId); + outLength = (ULONG) (strlen (volId) + sizeof (USHORT)); + + if (irpSp->Parameters.DeviceIoControl.OutputBufferLength < outLength) + { + Irp->IoStatus.Information = sizeof (MOUNTDEV_UNIQUE_ID); + Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; + break; + } + + RtlCopyMemory ((PCHAR)outputBuffer->UniqueId, volId, strlen (volId)); + + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = outLength; + + Dump ("id = %s\n",volId); + } + break; + + case IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME: + { + ULONG outLength; + UNICODE_STRING ntUnicodeString; + WCHAR ntName[256]; + PMOUNTDEV_SUGGESTED_LINK_NAME outputBuffer = (PMOUNTDEV_SUGGESTED_LINK_NAME) Irp->AssociatedIrp.SystemBuffer; + + if (!ValidateIOBufferSize (Irp, sizeof (MOUNTDEV_SUGGESTED_LINK_NAME), ValidateOutput)) + { + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + break; + } + + TCGetDosNameFromNumber (ntName, sizeof(ntName),Extension->nDosDriveNo, DeviceNamespaceDefault); + RtlInitUnicodeString (&ntUnicodeString, ntName); + + outLength = FIELD_OFFSET(MOUNTDEV_SUGGESTED_LINK_NAME,Name) + ntUnicodeString.Length; + + outputBuffer->UseOnlyIfThereAreNoOtherLinks = FALSE; + outputBuffer->NameLength = ntUnicodeString.Length; + + if(irpSp->Parameters.DeviceIoControl.OutputBufferLength < outLength) + { + Irp->IoStatus.Information = sizeof (MOUNTDEV_SUGGESTED_LINK_NAME); + Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; + break; + } + + RtlCopyMemory ((PCHAR)outputBuffer->Name,ntUnicodeString.Buffer, ntUnicodeString.Length); + + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = outLength; + + Dump ("link = %ls\n",ntName); + } + break; + + case IOCTL_DISK_GET_MEDIA_TYPES: + case IOCTL_DISK_GET_DRIVE_GEOMETRY: + /* Return the drive geometry for the disk. Note that we + return values which were made up to suit the disk size. */ + if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY), ValidateOutput)) + { + PDISK_GEOMETRY outputBuffer = (PDISK_GEOMETRY) + Irp->AssociatedIrp.SystemBuffer; + + outputBuffer->MediaType = Extension->bRemovable ? RemovableMedia : FixedMedia; + outputBuffer->Cylinders.QuadPart = Extension->NumberOfCylinders; + outputBuffer->TracksPerCylinder = Extension->TracksPerCylinder; + outputBuffer->SectorsPerTrack = Extension->SectorsPerTrack; + outputBuffer->BytesPerSector = Extension->BytesPerSector; + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (DISK_GEOMETRY); + } + break; + + case IOCTL_STORAGE_QUERY_PROPERTY: + if (EnableExtendedIoctlSupport) + { + if (ValidateIOBufferSize (Irp, sizeof (STORAGE_PROPERTY_QUERY), ValidateInput)) + { + PSTORAGE_PROPERTY_QUERY pStoragePropQuery = (PSTORAGE_PROPERTY_QUERY) Irp->AssociatedIrp.SystemBuffer; + STORAGE_QUERY_TYPE type = pStoragePropQuery->QueryType; + + /* return error if an unsupported type is encountered */ + Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; + Irp->IoStatus.Information = 0; + + if ( (pStoragePropQuery->PropertyId == StorageAccessAlignmentProperty) + || (pStoragePropQuery->PropertyId == StorageDeviceProperty) + ) + { + if (type == PropertyExistsQuery) + { + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = 0; + } + else if (type == PropertyStandardQuery) + { + switch (pStoragePropQuery->PropertyId) + { + case StorageDeviceProperty: + { + if (ValidateIOBufferSize (Irp, sizeof (STORAGE_DEVICE_DESCRIPTOR), ValidateOutput)) + { + PSTORAGE_DEVICE_DESCRIPTOR outputBuffer = (PSTORAGE_DEVICE_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; + + outputBuffer->Version = sizeof(STORAGE_DEVICE_DESCRIPTOR); + outputBuffer->Size = sizeof(STORAGE_DEVICE_DESCRIPTOR); + outputBuffer->DeviceType = FILE_DEVICE_DISK; + outputBuffer->RemovableMedia = Extension->bRemovable? TRUE : FALSE; + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (STORAGE_DEVICE_DESCRIPTOR); + } + } + break; + case StorageAccessAlignmentProperty: + { + if (ValidateIOBufferSize (Irp, sizeof (STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR), ValidateOutput)) + { + PSTORAGE_ACCESS_ALIGNMENT_DESCRIPTOR outputBuffer = (PSTORAGE_ACCESS_ALIGNMENT_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; + + outputBuffer->Version = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR); + outputBuffer->Size = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR); + outputBuffer->BytesPerLogicalSector = Extension->BytesPerSector; + outputBuffer->BytesPerPhysicalSector = Extension->HostBytesPerPhysicalSector; + outputBuffer->BytesOffsetForSectorAlignment = Extension->BytesOffsetForSectorAlignment; + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR); + } + } + break; + } + } + } + } + } + else + return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); + + break; + + case IOCTL_DISK_GET_PARTITION_INFO: + if (ValidateIOBufferSize (Irp, sizeof (PARTITION_INFORMATION), ValidateOutput)) + { + PPARTITION_INFORMATION outputBuffer = (PPARTITION_INFORMATION) + Irp->AssociatedIrp.SystemBuffer; + + outputBuffer->PartitionType = Extension->PartitionType; + outputBuffer->BootIndicator = FALSE; + outputBuffer->RecognizedPartition = TRUE; + outputBuffer->RewritePartition = FALSE; + outputBuffer->StartingOffset.QuadPart = Extension->BytesPerSector; + outputBuffer->PartitionLength.QuadPart= Extension->DiskLength; + outputBuffer->HiddenSectors = 0; + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION); + } + break; + + case IOCTL_DISK_GET_PARTITION_INFO_EX: + if (ValidateIOBufferSize (Irp, sizeof (PARTITION_INFORMATION_EX), ValidateOutput)) + { + PPARTITION_INFORMATION_EX outputBuffer = (PPARTITION_INFORMATION_EX) Irp->AssociatedIrp.SystemBuffer; + + outputBuffer->PartitionStyle = PARTITION_STYLE_MBR; + outputBuffer->RewritePartition = FALSE; + outputBuffer->StartingOffset.QuadPart = Extension->BytesPerSector; + outputBuffer->PartitionLength.QuadPart= Extension->DiskLength; + outputBuffer->Mbr.PartitionType = Extension->PartitionType; + outputBuffer->Mbr.BootIndicator = FALSE; + outputBuffer->Mbr.RecognizedPartition = TRUE; + outputBuffer->Mbr.HiddenSectors = 0; + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION_EX); + } + break; + + case IOCTL_DISK_GET_DRIVE_LAYOUT: + if (ValidateIOBufferSize (Irp, sizeof (DRIVE_LAYOUT_INFORMATION), ValidateOutput)) + { + PDRIVE_LAYOUT_INFORMATION outputBuffer = (PDRIVE_LAYOUT_INFORMATION) + Irp->AssociatedIrp.SystemBuffer; + + outputBuffer->PartitionCount = 1; + outputBuffer->Signature = 0; + + outputBuffer->PartitionEntry->PartitionType = Extension->PartitionType; + outputBuffer->PartitionEntry->BootIndicator = FALSE; + outputBuffer->PartitionEntry->RecognizedPartition = TRUE; + outputBuffer->PartitionEntry->RewritePartition = FALSE; + outputBuffer->PartitionEntry->StartingOffset.QuadPart = Extension->BytesPerSector; + outputBuffer->PartitionEntry->PartitionLength.QuadPart = Extension->DiskLength; + outputBuffer->PartitionEntry->HiddenSectors = 0; + + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (PARTITION_INFORMATION); + } + break; + + case IOCTL_DISK_GET_LENGTH_INFO: + if (!ValidateIOBufferSize (Irp, sizeof (GET_LENGTH_INFORMATION), ValidateOutput)) + { + Irp->IoStatus.Status = STATUS_BUFFER_OVERFLOW; + Irp->IoStatus.Information = sizeof (GET_LENGTH_INFORMATION); + } + else + { + PGET_LENGTH_INFORMATION outputBuffer = (PGET_LENGTH_INFORMATION) Irp->AssociatedIrp.SystemBuffer; + + outputBuffer->Length.QuadPart = Extension->DiskLength; + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (GET_LENGTH_INFORMATION); + } + break; + + case IOCTL_DISK_VERIFY: + if (ValidateIOBufferSize (Irp, sizeof (VERIFY_INFORMATION), ValidateInput)) + { + HRESULT hResult; + ULONGLONG ullStartingOffset, ullNewOffset, ullEndOffset; + PVERIFY_INFORMATION pVerifyInformation; + pVerifyInformation = (PVERIFY_INFORMATION) Irp->AssociatedIrp.SystemBuffer; + + ullStartingOffset = (ULONGLONG) pVerifyInformation->StartingOffset.QuadPart; + hResult = ULongLongAdd(ullStartingOffset, + (ULONGLONG) Extension->cryptoInfo->hiddenVolume ? Extension->cryptoInfo->hiddenVolumeOffset : Extension->cryptoInfo->volDataAreaOffset, + &ullNewOffset); + if (hResult != S_OK) + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + else if (S_OK != ULongLongAdd(ullStartingOffset, (ULONGLONG) pVerifyInformation->Length, &ullEndOffset)) + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + else if (ullEndOffset > (ULONGLONG) Extension->DiskLength) + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + else + { + IO_STATUS_BLOCK ioStatus; + PVOID buffer = TCalloc (max (pVerifyInformation->Length, PAGE_SIZE)); + + if (!buffer) + { + Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; + } + else + { + LARGE_INTEGER offset = pVerifyInformation->StartingOffset; + offset.QuadPart = ullNewOffset; + + Irp->IoStatus.Status = ZwReadFile (Extension->hDeviceFile, NULL, NULL, NULL, &ioStatus, buffer, pVerifyInformation->Length, &offset, NULL); + TCfree (buffer); + + if (NT_SUCCESS (Irp->IoStatus.Status) && ioStatus.Information != pVerifyInformation->Length) + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + } + } + + Irp->IoStatus.Information = 0; + } + break; + + case IOCTL_DISK_CHECK_VERIFY: + case IOCTL_STORAGE_CHECK_VERIFY: + { + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = 0; + + if (irpSp->Parameters.DeviceIoControl.OutputBufferLength >= sizeof (ULONG)) + { + *((ULONG *) Irp->AssociatedIrp.SystemBuffer) = 0; + Irp->IoStatus.Information = sizeof (ULONG); + } + } + break; + + case IOCTL_DISK_IS_WRITABLE: + { + if (Extension->bReadOnly) + Irp->IoStatus.Status = STATUS_MEDIA_WRITE_PROTECTED; + else + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = 0; + + } + break; + + case IOCTL_VOLUME_ONLINE: + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = 0; + break; + + case IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS: + + // Vista's filesystem defragmenter fails if IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS does not succeed. + if (!(OsMajorVersion == 6 && OsMinorVersion == 0)) + { + Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; + Irp->IoStatus.Information = 0; + } + else if (ValidateIOBufferSize (Irp, sizeof (VOLUME_DISK_EXTENTS), ValidateOutput)) + { + VOLUME_DISK_EXTENTS *extents = (VOLUME_DISK_EXTENTS *) Irp->AssociatedIrp.SystemBuffer; + + // No extent data can be returned as this is not a physical drive. + memset (extents, 0, sizeof (*extents)); + extents->NumberOfDiskExtents = 0; + + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (*extents); + } + break; + + default: + return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); + } + +#ifdef DEBUG + if (!NT_SUCCESS (Irp->IoStatus.Status)) + { + Dump ("IOCTL error 0x%08x (0x%x %d)\n", + Irp->IoStatus.Status, + (int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16), + (int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2)); + } +#endif + + return TCCompleteDiskIrp (Irp, Irp->IoStatus.Status, Irp->IoStatus.Information); +} + + +NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp) +{ + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); + NTSTATUS ntStatus; + + switch (irpSp->Parameters.DeviceIoControl.IoControlCode) + { + case TC_IOCTL_GET_DRIVER_VERSION: + case TC_IOCTL_LEGACY_GET_DRIVER_VERSION: + if (ValidateIOBufferSize (Irp, sizeof (LONG), ValidateOutput)) + { + LONG tmp = VERSION_NUM; + memcpy (Irp->AssociatedIrp.SystemBuffer, &tmp, 4); + Irp->IoStatus.Information = sizeof (LONG); + Irp->IoStatus.Status = STATUS_SUCCESS; + } + break; + + case TC_IOCTL_GET_DEVICE_REFCOUNT: + if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) + { + *(int *) Irp->AssociatedIrp.SystemBuffer = DeviceObject->ReferenceCount; + Irp->IoStatus.Information = sizeof (int); + Irp->IoStatus.Status = STATUS_SUCCESS; + } + break; + + case TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED: + if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) + { + LONG deviceObjectCount = 0; + + *(int *) Irp->AssociatedIrp.SystemBuffer = DriverUnloadDisabled; + + if (IoEnumerateDeviceObjectList (TCDriverObject, NULL, 0, &deviceObjectCount) == STATUS_BUFFER_TOO_SMALL && deviceObjectCount > 1) + *(int *) Irp->AssociatedIrp.SystemBuffer = TRUE; + + Irp->IoStatus.Information = sizeof (int); + Irp->IoStatus.Status = STATUS_SUCCESS; + } + break; + + case TC_IOCTL_IS_ANY_VOLUME_MOUNTED: + if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) + { + int drive; + *(int *) Irp->AssociatedIrp.SystemBuffer = 0; + + for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) + { + if (GetVirtualVolumeDeviceObject (drive)) + { + *(int *) Irp->AssociatedIrp.SystemBuffer = 1; + break; + } + } + + if (IsBootDriveMounted()) + *(int *) Irp->AssociatedIrp.SystemBuffer = 1; + + Irp->IoStatus.Information = sizeof (int); + Irp->IoStatus.Status = STATUS_SUCCESS; + } + break; + + case TC_IOCTL_OPEN_TEST: + { + OPEN_TEST_STRUCT *opentest = (OPEN_TEST_STRUCT *) Irp->AssociatedIrp.SystemBuffer; + OBJECT_ATTRIBUTES ObjectAttributes; + HANDLE NtFileHandle; + UNICODE_STRING FullFileName; + IO_STATUS_BLOCK IoStatus; + LARGE_INTEGER offset; + ACCESS_MASK access = FILE_READ_ATTRIBUTES; + + if (!ValidateIOBufferSize (Irp, sizeof (OPEN_TEST_STRUCT), ValidateInputOutput)) + break; + + EnsureNullTerminatedString (opentest->wszFileName, sizeof (opentest->wszFileName)); + RtlInitUnicodeString (&FullFileName, opentest->wszFileName); + + InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); + + if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bMatchVolumeID) + access |= FILE_READ_DATA; + + ntStatus = ZwCreateFile (&NtFileHandle, + SYNCHRONIZE | access, &ObjectAttributes, &IoStatus, NULL, + 0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); + + if (NT_SUCCESS (ntStatus)) + { + opentest->TCBootLoaderDetected = FALSE; + opentest->FilesystemDetected = FALSE; + opentest->VolumeIDMatched = FALSE; + + if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bMatchVolumeID) + { + byte *readBuffer = TCalloc (TC_MAX_VOLUME_SECTOR_SIZE); + if (!readBuffer) + { + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + } + else + { + if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem) + { + // Determine if the first sector contains a portion of the VeraCrypt Boot Loader + + offset.QuadPart = 0; + + ntStatus = ZwReadFile (NtFileHandle, + NULL, + NULL, + NULL, + &IoStatus, + readBuffer, + TC_MAX_VOLUME_SECTOR_SIZE, + &offset, + NULL); + + if (NT_SUCCESS (ntStatus)) + { + size_t i; + + if (opentest->bDetectTCBootLoader && IoStatus.Information >= TC_SECTOR_SIZE_BIOS) + { + // Search for the string "VeraCrypt" + for (i = 0; i < TC_SECTOR_SIZE_BIOS - strlen (TC_APP_NAME); ++i) + { + if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0) + { + opentest->TCBootLoaderDetected = TRUE; + break; + } + } + } + + if (opentest->DetectFilesystem && IoStatus.Information >= sizeof (int64)) + { + switch (BE64 (*(uint64 *) readBuffer)) + { + case 0xEB52904E54465320: // NTFS + case 0xEB3C904D53444F53: // FAT16 + case 0xEB58904D53444F53: // FAT32 + case 0xEB76904558464154: // exFAT + + opentest->FilesystemDetected = TRUE; + break; + } + } + } + } + + if (opentest->bMatchVolumeID) + { + int volumeType; + BYTE volumeID[VOLUME_ID_SIZE]; + + // Go through all volume types (e.g., normal, hidden) + for (volumeType = TC_VOLUME_TYPE_NORMAL; + volumeType < TC_VOLUME_TYPE_COUNT; + volumeType++) + { + /* Read the volume header */ + switch (volumeType) + { + case TC_VOLUME_TYPE_NORMAL: + offset.QuadPart = TC_VOLUME_HEADER_OFFSET; + break; + + case TC_VOLUME_TYPE_HIDDEN: + + offset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET; + break; + } + + ntStatus = ZwReadFile (NtFileHandle, + NULL, + NULL, + NULL, + &IoStatus, + readBuffer, + TC_MAX_VOLUME_SECTOR_SIZE, + &offset, + NULL); + + if (NT_SUCCESS (ntStatus)) + { + /* compute the ID of this volume: SHA-256 of the effective header */ + sha256 (volumeID, readBuffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + + if (0 == memcmp (volumeID, opentest->volumeID, VOLUME_ID_SIZE)) + { + opentest->VolumeIDMatched = TRUE; + break; + } + } + } + } + + TCfree (readBuffer); + } + } + + ZwClose (NtFileHandle); + Dump ("Open test on file %ls success.\n", opentest->wszFileName); + } + else + { +#if 0 + Dump ("Open test on file %ls failed NTSTATUS 0x%08x\n", opentest->wszFileName, ntStatus); +#endif + } + + Irp->IoStatus.Information = NT_SUCCESS (ntStatus) ? sizeof (OPEN_TEST_STRUCT) : 0; + Irp->IoStatus.Status = ntStatus; + } + break; + + case TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG: + { + GetSystemDriveConfigurationRequest *request = (GetSystemDriveConfigurationRequest *) Irp->AssociatedIrp.SystemBuffer; + OBJECT_ATTRIBUTES ObjectAttributes; + HANDLE NtFileHandle; + UNICODE_STRING FullFileName; + IO_STATUS_BLOCK IoStatus; + LARGE_INTEGER offset; + byte readBuffer [TC_SECTOR_SIZE_BIOS]; + + if (!ValidateIOBufferSize (Irp, sizeof (GetSystemDriveConfigurationRequest), ValidateInputOutput)) + break; + + EnsureNullTerminatedString (request->DevicePath, sizeof (request->DevicePath)); + RtlInitUnicodeString (&FullFileName, request->DevicePath); + + InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); + + ntStatus = ZwCreateFile (&NtFileHandle, + SYNCHRONIZE | GENERIC_READ, &ObjectAttributes, &IoStatus, NULL, + FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT | FILE_RANDOM_ACCESS, NULL, 0); + + if (NT_SUCCESS (ntStatus)) + { + // Determine if the first sector contains a portion of the VeraCrypt Boot Loader + offset.QuadPart = 0; // MBR + + ntStatus = ZwReadFile (NtFileHandle, + NULL, + NULL, + NULL, + &IoStatus, + readBuffer, + sizeof(readBuffer), + &offset, + NULL); + + if (NT_SUCCESS (ntStatus)) + { + size_t i; + + // Check for dynamic drive + request->DriveIsDynamic = FALSE; + + if (readBuffer[510] == 0x55 && readBuffer[511] == 0xaa) + { + int i; + for (i = 0; i < 4; ++i) + { + if (readBuffer[446 + i * 16 + 4] == PARTITION_LDM) + { + request->DriveIsDynamic = TRUE; + break; + } + } + } + + request->BootLoaderVersion = 0; + request->Configuration = 0; + request->UserConfiguration = 0; + request->CustomUserMessage[0] = 0; + + // Search for the string "VeraCrypt" + for (i = 0; i < sizeof (readBuffer) - strlen (TC_APP_NAME); ++i) + { + if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0) + { + request->BootLoaderVersion = BE16 (*(uint16 *) (readBuffer + TC_BOOT_SECTOR_VERSION_OFFSET)); + request->Configuration = readBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET]; + + if (request->BootLoaderVersion != 0 && request->BootLoaderVersion <= VERSION_NUM) + { + request->UserConfiguration = readBuffer[TC_BOOT_SECTOR_USER_CONFIG_OFFSET]; + memcpy (request->CustomUserMessage, readBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); + } + break; + } + } + + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (*request); + } + else + { + Irp->IoStatus.Status = ntStatus; + Irp->IoStatus.Information = 0; + } + + ZwClose (NtFileHandle); + + } + else + { + Irp->IoStatus.Status = ntStatus; + Irp->IoStatus.Information = 0; + } + } + break; + + case TC_IOCTL_WIPE_PASSWORD_CACHE: + WipeCache (); + + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = 0; + break; + + case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: + Irp->IoStatus.Status = cacheEmpty ? STATUS_PIPE_EMPTY : STATUS_SUCCESS; + Irp->IoStatus.Information = 0; + break; + + case TC_IOCTL_SET_PORTABLE_MODE_STATUS: + if (!UserCanAccessDriveDevice()) + { + Irp->IoStatus.Status = STATUS_ACCESS_DENIED; + Irp->IoStatus.Information = 0; + } + else + { + PortableMode = TRUE; + Dump ("Setting portable mode\n"); + } + break; + + case TC_IOCTL_GET_PORTABLE_MODE_STATUS: + Irp->IoStatus.Status = PortableMode ? STATUS_SUCCESS : STATUS_PIPE_EMPTY; + Irp->IoStatus.Information = 0; + break; + + case TC_IOCTL_GET_MOUNTED_VOLUMES: + + if (ValidateIOBufferSize (Irp, sizeof (MOUNT_LIST_STRUCT), ValidateOutput)) + { + MOUNT_LIST_STRUCT *list = (MOUNT_LIST_STRUCT *) Irp->AssociatedIrp.SystemBuffer; + PDEVICE_OBJECT ListDevice; + int drive; + + list->ulMountedDrives = 0; + + for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) + { + PEXTENSION ListExtension; + + ListDevice = GetVirtualVolumeDeviceObject (drive); + if (!ListDevice) + continue; + + ListExtension = (PEXTENSION) ListDevice->DeviceExtension; + if (IsVolumeAccessibleByCurrentUser (ListExtension)) + { + list->ulMountedDrives |= (1 << ListExtension->nDosDriveNo); + RtlStringCbCopyW (list->wszVolume[ListExtension->nDosDriveNo], sizeof(list->wszVolume[ListExtension->nDosDriveNo]),ListExtension->wszVolume); + RtlStringCbCopyW (list->wszLabel[ListExtension->nDosDriveNo], sizeof(list->wszLabel[ListExtension->nDosDriveNo]),ListExtension->wszLabel); + memcpy (list->volumeID[ListExtension->nDosDriveNo], ListExtension->volumeID, VOLUME_ID_SIZE); + list->diskLength[ListExtension->nDosDriveNo] = ListExtension->DiskLength; + list->ea[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->ea; + if (ListExtension->cryptoInfo->hiddenVolume) + list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_HIDDEN; // Hidden volume + else if (ListExtension->cryptoInfo->bHiddenVolProtectionAction) + list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED; // Normal/outer volume (hidden volume protected AND write already prevented) + else if (ListExtension->cryptoInfo->bProtectHiddenVolume) + list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER; // Normal/outer volume (hidden volume protected) + else + list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_NORMAL; // Normal volume + list->truecryptMode[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->bTrueCryptMode; + } + } + + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (MOUNT_LIST_STRUCT); + } + break; + + case TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES: + if (ValidateIOBufferSize (Irp, sizeof (uint32), ValidateOutput)) + { + // Prevent the user from downgrading to versions lower than 5.0 by faking mounted volumes. + // The user could render the system unbootable by downgrading when boot encryption + // is active or being set up. + + memset (Irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength); + *(uint32 *) Irp->AssociatedIrp.SystemBuffer = 0xffffFFFF; + + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = irpSp->Parameters.DeviceIoControl.OutputBufferLength; + } + break; + + case TC_IOCTL_GET_VOLUME_PROPERTIES: + if (ValidateIOBufferSize (Irp, sizeof (VOLUME_PROPERTIES_STRUCT), ValidateInputOutput)) + { + VOLUME_PROPERTIES_STRUCT *prop = (VOLUME_PROPERTIES_STRUCT *) Irp->AssociatedIrp.SystemBuffer; + PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (prop->driveNo); + + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + + if (ListDevice) + { + PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; + if (IsVolumeAccessibleByCurrentUser (ListExtension)) + { + prop->uniqueId = ListExtension->UniqueVolumeId; + RtlStringCbCopyW (prop->wszVolume, sizeof(prop->wszVolume),ListExtension->wszVolume); + RtlStringCbCopyW (prop->wszLabel, sizeof(prop->wszLabel),ListExtension->wszLabel); + memcpy (prop->volumeID, ListExtension->volumeID, VOLUME_ID_SIZE); + prop->bDriverSetLabel = ListExtension->bDriverSetLabel; + prop->diskLength = ListExtension->DiskLength; + prop->ea = ListExtension->cryptoInfo->ea; + prop->mode = ListExtension->cryptoInfo->mode; + prop->pkcs5 = ListExtension->cryptoInfo->pkcs5; + prop->pkcs5Iterations = ListExtension->cryptoInfo->noIterations; + prop->volumePim = ListExtension->cryptoInfo->volumePim; +#if 0 + prop->volumeCreationTime = ListExtension->cryptoInfo->volume_creation_time; + prop->headerCreationTime = ListExtension->cryptoInfo->header_creation_time; +#endif + prop->volumeHeaderFlags = ListExtension->cryptoInfo->HeaderFlags; + prop->readOnly = ListExtension->bReadOnly; + prop->removable = ListExtension->bRemovable; + prop->partitionInInactiveSysEncScope = ListExtension->PartitionInInactiveSysEncScope; + prop->hiddenVolume = ListExtension->cryptoInfo->hiddenVolume; + + if (ListExtension->cryptoInfo->bProtectHiddenVolume) + prop->hiddenVolProtection = ListExtension->cryptoInfo->bHiddenVolProtectionAction ? HIDVOL_PROT_STATUS_ACTION_TAKEN : HIDVOL_PROT_STATUS_ACTIVE; + else + prop->hiddenVolProtection = HIDVOL_PROT_STATUS_NONE; + + prop->totalBytesRead = ListExtension->Queue.TotalBytesRead; + prop->totalBytesWritten = ListExtension->Queue.TotalBytesWritten; + + prop->volFormatVersion = ListExtension->cryptoInfo->LegacyVolume ? TC_VOLUME_FORMAT_VERSION_PRE_6_0 : TC_VOLUME_FORMAT_VERSION; + + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (VOLUME_PROPERTIES_STRUCT); + } + } + } + break; + + case TC_IOCTL_GET_RESOLVED_SYMLINK: + if (ValidateIOBufferSize (Irp, sizeof (RESOLVE_SYMLINK_STRUCT), ValidateInputOutput)) + { + RESOLVE_SYMLINK_STRUCT *resolve = (RESOLVE_SYMLINK_STRUCT *) Irp->AssociatedIrp.SystemBuffer; + { + NTSTATUS ntStatus; + + EnsureNullTerminatedString (resolve->symLinkName, sizeof (resolve->symLinkName)); + + ntStatus = SymbolicLinkToTarget (resolve->symLinkName, + resolve->targetName, + sizeof (resolve->targetName)); + + Irp->IoStatus.Information = sizeof (RESOLVE_SYMLINK_STRUCT); + Irp->IoStatus.Status = ntStatus; + } + } + break; + + case TC_IOCTL_GET_DRIVE_PARTITION_INFO: + if (ValidateIOBufferSize (Irp, sizeof (DISK_PARTITION_INFO_STRUCT), ValidateInputOutput)) + { + DISK_PARTITION_INFO_STRUCT *info = (DISK_PARTITION_INFO_STRUCT *) Irp->AssociatedIrp.SystemBuffer; + { + PARTITION_INFORMATION_EX pi; + NTSTATUS ntStatus; + + EnsureNullTerminatedString (info->deviceName, sizeof (info->deviceName)); + + ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &pi, sizeof (pi)); + if (NT_SUCCESS(ntStatus)) + { + memset (&info->partInfo, 0, sizeof (info->partInfo)); + + info->partInfo.PartitionLength = pi.PartitionLength; + info->partInfo.PartitionNumber = pi.PartitionNumber; + info->partInfo.StartingOffset = pi.StartingOffset; + + if (pi.PartitionStyle == PARTITION_STYLE_MBR) + { + info->partInfo.PartitionType = pi.Mbr.PartitionType; + info->partInfo.BootIndicator = pi.Mbr.BootIndicator; + } + + info->IsGPT = pi.PartitionStyle == PARTITION_STYLE_GPT; + } + else + { + // Windows 2000 does not support IOCTL_DISK_GET_PARTITION_INFO_EX + ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &info->partInfo, sizeof (info->partInfo)); + info->IsGPT = FALSE; + } + + if (!NT_SUCCESS (ntStatus)) + { + GET_LENGTH_INFORMATION lengthInfo; + ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &lengthInfo, sizeof (lengthInfo)); + + if (NT_SUCCESS (ntStatus)) + { + memset (&info->partInfo, 0, sizeof (info->partInfo)); + info->partInfo.PartitionLength = lengthInfo.Length; + } + } + + info->IsDynamic = FALSE; + + if (NT_SUCCESS (ntStatus) && OsMajorVersion >= 6) + { +# define IOCTL_VOLUME_IS_DYNAMIC CTL_CODE(IOCTL_VOLUME_BASE, 18, METHOD_BUFFERED, FILE_ANY_ACCESS) + if (!NT_SUCCESS (TCDeviceIoControl (info->deviceName, IOCTL_VOLUME_IS_DYNAMIC, NULL, 0, &info->IsDynamic, sizeof (info->IsDynamic)))) + info->IsDynamic = FALSE; + } + + Irp->IoStatus.Information = sizeof (DISK_PARTITION_INFO_STRUCT); + Irp->IoStatus.Status = ntStatus; + } + } + break; + + case TC_IOCTL_GET_DRIVE_GEOMETRY: + if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_STRUCT), ValidateInputOutput)) + { + DISK_GEOMETRY_STRUCT *g = (DISK_GEOMETRY_STRUCT *) Irp->AssociatedIrp.SystemBuffer; + { + NTSTATUS ntStatus; + + EnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName)); + + ntStatus = TCDeviceIoControl (g->deviceName, + IOCTL_DISK_GET_DRIVE_GEOMETRY, + NULL, 0, &g->diskGeometry, sizeof (g->diskGeometry)); + + Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_STRUCT); + Irp->IoStatus.Status = ntStatus; + } + } + break; + + case TC_IOCTL_PROBE_REAL_DRIVE_SIZE: + if (ValidateIOBufferSize (Irp, sizeof (ProbeRealDriveSizeRequest), ValidateInputOutput)) + { + ProbeRealDriveSizeRequest *request = (ProbeRealDriveSizeRequest *) Irp->AssociatedIrp.SystemBuffer; + NTSTATUS status; + UNICODE_STRING name; + PFILE_OBJECT fileObject; + PDEVICE_OBJECT deviceObject; + + EnsureNullTerminatedString (request->DeviceName, sizeof (request->DeviceName)); + + RtlInitUnicodeString (&name, request->DeviceName); + status = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject); + if (!NT_SUCCESS (status)) + { + Irp->IoStatus.Information = 0; + Irp->IoStatus.Status = status; + break; + } + + status = ProbeRealDriveSize (deviceObject, &request->RealDriveSize); + ObDereferenceObject (fileObject); + + if (status == STATUS_TIMEOUT) + { + request->TimeOut = TRUE; + Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest); + Irp->IoStatus.Status = STATUS_SUCCESS; + } + else if (!NT_SUCCESS (status)) + { + Irp->IoStatus.Information = 0; + Irp->IoStatus.Status = status; + } + else + { + request->TimeOut = FALSE; + Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest); + Irp->IoStatus.Status = status; + } + } + break; + + case TC_IOCTL_MOUNT_VOLUME: + if (ValidateIOBufferSize (Irp, sizeof (MOUNT_STRUCT), ValidateInputOutput)) + { + MOUNT_STRUCT *mount = (MOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; + + if (mount->VolumePassword.Length > MAX_PASSWORD || mount->ProtectedHidVolPassword.Length > MAX_PASSWORD + || mount->pkcs5_prf < 0 || mount->pkcs5_prf > LAST_PRF_ID + || mount->VolumePim < -1 || mount->VolumePim == INT_MAX + || mount->ProtectedHidVolPkcs5Prf < 0 || mount->ProtectedHidVolPkcs5Prf > LAST_PRF_ID + || (mount->bTrueCryptMode != FALSE && mount->bTrueCryptMode != TRUE) + ) + { + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + break; + } + + EnsureNullTerminatedString (mount->wszVolume, sizeof (mount->wszVolume)); + EnsureNullTerminatedString (mount->wszLabel, sizeof (mount->wszLabel)); + + Irp->IoStatus.Information = sizeof (MOUNT_STRUCT); + Irp->IoStatus.Status = MountDevice (DeviceObject, mount); + + burn (&mount->VolumePassword, sizeof (mount->VolumePassword)); + burn (&mount->ProtectedHidVolPassword, sizeof (mount->ProtectedHidVolPassword)); + burn (&mount->pkcs5_prf, sizeof (mount->pkcs5_prf)); + burn (&mount->VolumePim, sizeof (mount->VolumePim)); + burn (&mount->bTrueCryptMode, sizeof (mount->bTrueCryptMode)); + burn (&mount->ProtectedHidVolPkcs5Prf, sizeof (mount->ProtectedHidVolPkcs5Prf)); + burn (&mount->ProtectedHidVolPim, sizeof (mount->ProtectedHidVolPim)); + } + break; + + case TC_IOCTL_DISMOUNT_VOLUME: + if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput)) + { + UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; + PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (unmount->nDosDriveNo); + + unmount->nReturnCode = ERR_DRIVE_NOT_FOUND; + + if (ListDevice) + { + PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; + + if (IsVolumeAccessibleByCurrentUser (ListExtension)) + unmount->nReturnCode = UnmountDevice (unmount, ListDevice, unmount->ignoreOpenFiles); + } + + Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT); + Irp->IoStatus.Status = STATUS_SUCCESS; + } + break; + + case TC_IOCTL_DISMOUNT_ALL_VOLUMES: + if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput)) + { + UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; + + unmount->nReturnCode = UnmountAllDevices (unmount, unmount->ignoreOpenFiles); + + Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT); + Irp->IoStatus.Status = STATUS_SUCCESS; + } + break; + + case TC_IOCTL_BOOT_ENCRYPTION_SETUP: + Irp->IoStatus.Status = StartBootEncryptionSetup (DeviceObject, Irp, irpSp); + Irp->IoStatus.Information = 0; + break; + + case TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP: + Irp->IoStatus.Status = AbortBootEncryptionSetup(); + Irp->IoStatus.Information = 0; + break; + + case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: + GetBootEncryptionStatus (Irp, irpSp); + break; + + case TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT: + Irp->IoStatus.Information = 0; + Irp->IoStatus.Status = GetSetupResult(); + break; + + case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: + GetBootDriveVolumeProperties (Irp, irpSp); + break; + + case TC_IOCTL_GET_BOOT_LOADER_VERSION: + GetBootLoaderVersion (Irp, irpSp); + break; + + case TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER: + ReopenBootVolumeHeader (Irp, irpSp); + break; + + case VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT: + GetBootLoaderFingerprint (Irp, irpSp); + break; + + case TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME: + GetBootEncryptionAlgorithmName (Irp, irpSp); + break; + + case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: + if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) + { + *(int *) Irp->AssociatedIrp.SystemBuffer = IsHiddenSystemRunning() ? 1 : 0; + Irp->IoStatus.Information = sizeof (int); + Irp->IoStatus.Status = STATUS_SUCCESS; + } + break; + + case TC_IOCTL_START_DECOY_SYSTEM_WIPE: + Irp->IoStatus.Status = StartDecoySystemWipe (DeviceObject, Irp, irpSp); + Irp->IoStatus.Information = 0; + break; + + case TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE: + Irp->IoStatus.Status = AbortDecoySystemWipe(); + Irp->IoStatus.Information = 0; + break; + + case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT: + Irp->IoStatus.Status = GetDecoySystemWipeResult(); + Irp->IoStatus.Information = 0; + break; + + case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS: + GetDecoySystemWipeStatus (Irp, irpSp); + break; + + case TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR: + Irp->IoStatus.Status = WriteBootDriveSector (Irp, irpSp); + Irp->IoStatus.Information = 0; + break; + + case TC_IOCTL_GET_WARNING_FLAGS: + if (ValidateIOBufferSize (Irp, sizeof (GetWarningFlagsRequest), ValidateOutput)) + { + GetWarningFlagsRequest *flags = (GetWarningFlagsRequest *) Irp->AssociatedIrp.SystemBuffer; + + flags->PagingFileCreationPrevented = PagingFileCreationPrevented; + PagingFileCreationPrevented = FALSE; + flags->SystemFavoriteVolumeDirty = SystemFavoriteVolumeDirty; + SystemFavoriteVolumeDirty = FALSE; + + Irp->IoStatus.Information = sizeof (GetWarningFlagsRequest); + Irp->IoStatus.Status = STATUS_SUCCESS; + } + break; + + case TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY: + if (UserCanAccessDriveDevice()) + { + SystemFavoriteVolumeDirty = TRUE; + Irp->IoStatus.Status = STATUS_SUCCESS; + } + else + Irp->IoStatus.Status = STATUS_ACCESS_DENIED; + + Irp->IoStatus.Information = 0; + break; + + case TC_IOCTL_REREAD_DRIVER_CONFIG: + Irp->IoStatus.Status = ReadRegistryConfigFlags (FALSE); + Irp->IoStatus.Information = 0; + break; + + case TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG: + if ( (ValidateIOBufferSize (Irp, sizeof (GetSystemDriveDumpConfigRequest), ValidateOutput)) + && (Irp->RequestorMode == KernelMode) + ) + { + GetSystemDriveDumpConfigRequest *request = (GetSystemDriveDumpConfigRequest *) Irp->AssociatedIrp.SystemBuffer; + + request->BootDriveFilterExtension = GetBootDriveFilterExtension(); + if (IsBootDriveMounted() && request->BootDriveFilterExtension) + { + request->HwEncryptionEnabled = IsHwEncryptionEnabled(); + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (*request); + } + else + { + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + } + } + break; + + default: + return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); + } + + +#ifdef DEBUG + if (!NT_SUCCESS (Irp->IoStatus.Status)) + { + switch (irpSp->Parameters.DeviceIoControl.IoControlCode) + { + case TC_IOCTL_GET_MOUNTED_VOLUMES: + case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: + case TC_IOCTL_GET_PORTABLE_MODE_STATUS: + case TC_IOCTL_SET_PORTABLE_MODE_STATUS: + case TC_IOCTL_OPEN_TEST: + case TC_IOCTL_GET_RESOLVED_SYMLINK: + case TC_IOCTL_GET_DRIVE_PARTITION_INFO: + case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: + case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: + case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: + break; + + default: + Dump ("IOCTL error 0x%08x\n", Irp->IoStatus.Status); + } + } +#endif + + return TCCompleteIrp (Irp, Irp->IoStatus.Status, Irp->IoStatus.Information); +} + + +NTSTATUS TCStartThread (PKSTART_ROUTINE threadProc, PVOID threadArg, PKTHREAD *kThread) +{ + return TCStartThreadInProcess (threadProc, threadArg, kThread, NULL); +} + + +NTSTATUS TCStartThreadInProcess (PKSTART_ROUTINE threadProc, PVOID threadArg, PKTHREAD *kThread, PEPROCESS process) +{ + NTSTATUS status; + HANDLE threadHandle; + HANDLE processHandle = NULL; + OBJECT_ATTRIBUTES threadObjAttributes; + + if (process) + { + status = ObOpenObjectByPointer (process, OBJ_KERNEL_HANDLE, NULL, 0, NULL, KernelMode, &processHandle); + if (!NT_SUCCESS (status)) + return status; + } + + InitializeObjectAttributes (&threadObjAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); + + status = PsCreateSystemThread (&threadHandle, THREAD_ALL_ACCESS, &threadObjAttributes, processHandle, NULL, threadProc, threadArg); + if (!NT_SUCCESS (status)) + return status; + + status = ObReferenceObjectByHandle (threadHandle, THREAD_ALL_ACCESS, NULL, KernelMode, (PVOID *) kThread, NULL); + if (!NT_SUCCESS (status)) + { + ZwClose (threadHandle); + *kThread = NULL; + return status; + } + + if (processHandle) + ZwClose (processHandle); + + ZwClose (threadHandle); + return STATUS_SUCCESS; +} + + +void TCStopThread (PKTHREAD kThread, PKEVENT wakeUpEvent) +{ + if (wakeUpEvent) + KeSetEvent (wakeUpEvent, 0, FALSE); + + KeWaitForSingleObject (kThread, Executive, KernelMode, FALSE, NULL); + ObDereferenceObject (kThread); +} + + +NTSTATUS TCStartVolumeThread (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, MOUNT_STRUCT * mount) +{ + PTHREAD_BLOCK pThreadBlock = TCalloc (sizeof (THREAD_BLOCK)); + HANDLE hThread; + NTSTATUS ntStatus; + OBJECT_ATTRIBUTES threadObjAttributes; + SECURITY_QUALITY_OF_SERVICE qos; + + Dump ("Starting thread...\n"); + + if (pThreadBlock == NULL) + { + return STATUS_INSUFFICIENT_RESOURCES; + } + else + { + pThreadBlock->DeviceObject = DeviceObject; + pThreadBlock->mount = mount; + } + + qos.Length = sizeof (qos); + qos.ContextTrackingMode = SECURITY_STATIC_TRACKING; + qos.EffectiveOnly = TRUE; + qos.ImpersonationLevel = SecurityImpersonation; + + ntStatus = SeCreateClientSecurity (PsGetCurrentThread(), &qos, FALSE, &Extension->SecurityClientContext); + if (!NT_SUCCESS (ntStatus)) + goto ret; + + Extension->SecurityClientContextValid = TRUE; + + Extension->bThreadShouldQuit = FALSE; + + InitializeObjectAttributes (&threadObjAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); + + ntStatus = PsCreateSystemThread (&hThread, + THREAD_ALL_ACCESS, + &threadObjAttributes, + NULL, + NULL, + VolumeThreadProc, + pThreadBlock); + + if (!NT_SUCCESS (ntStatus)) + { + Dump ("PsCreateSystemThread Failed END\n"); + goto ret; + } + + ntStatus = ObReferenceObjectByHandle (hThread, + THREAD_ALL_ACCESS, + NULL, + KernelMode, + &Extension->peThread, + NULL); + + ZwClose (hThread); + + if (!NT_SUCCESS (ntStatus)) + goto ret; + + Dump ("Waiting for thread to initialize...\n"); + + KeWaitForSingleObject (&Extension->keCreateEvent, + Executive, + KernelMode, + FALSE, + NULL); + + Dump ("Waiting completed! Thread returns 0x%08x\n", pThreadBlock->ntCreateStatus); + ntStatus = pThreadBlock->ntCreateStatus; + +ret: + TCfree (pThreadBlock); + return ntStatus; +} + +void TCStopVolumeThread (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension) +{ + NTSTATUS ntStatus; + + UNREFERENCED_PARAMETER (DeviceObject); /* Remove compiler warning */ + + Dump ("Signalling thread to quit...\n"); + + Extension->bThreadShouldQuit = TRUE; + + KeReleaseSemaphore (&Extension->RequestSemaphore, + 0, + 1, + TRUE); + + ntStatus = KeWaitForSingleObject (Extension->peThread, + Executive, + KernelMode, + FALSE, + NULL); + + ASSERT (NT_SUCCESS (ntStatus)); + + ObDereferenceObject (Extension->peThread); + Extension->peThread = NULL; + + Dump ("Thread exited\n"); +} + + +// Suspend current thread for a number of milliseconds +void TCSleep (int milliSeconds) +{ + PKTIMER timer = (PKTIMER) TCalloc (sizeof (KTIMER)); + LARGE_INTEGER duetime; + + if (!timer) + return; + + duetime.QuadPart = (__int64) milliSeconds * -10000; + KeInitializeTimerEx(timer, NotificationTimer); + KeSetTimerEx(timer, duetime, 0, NULL); + + KeWaitForSingleObject (timer, Executive, KernelMode, FALSE, NULL); + + TCfree (timer); +} + +BOOL IsDeviceName(wchar_t wszVolume[TC_MAX_PATH]) +{ + if ( (wszVolume[0] == '\\') + && (wszVolume[1] == 'D' || wszVolume[1] == 'd') + && (wszVolume[2] == 'E' || wszVolume[2] == 'e') + && (wszVolume[3] == 'V' || wszVolume[3] == 'v') + && (wszVolume[4] == 'I' || wszVolume[4] == 'i') + && (wszVolume[5] == 'C' || wszVolume[5] == 'c') + && (wszVolume[6] == 'E' || wszVolume[6] == 'e') + ) + { + return TRUE; + } + else + return FALSE; +} + +/* VolumeThreadProc does all the work of processing IRP's, and dispatching them + to either the ReadWrite function or the DeviceControl function */ +VOID VolumeThreadProc (PVOID Context) +{ + PTHREAD_BLOCK pThreadBlock = (PTHREAD_BLOCK) Context; + PDEVICE_OBJECT DeviceObject = pThreadBlock->DeviceObject; + PEXTENSION Extension = (PEXTENSION) DeviceObject->DeviceExtension; + BOOL bDevice; + + /* Set thread priority to lowest realtime level. */ + KeSetPriorityThread (KeGetCurrentThread (), LOW_REALTIME_PRIORITY); + + Dump ("Mount THREAD OPENING VOLUME BEGIN\n"); + + if ( !IsDeviceName (pThreadBlock->mount->wszVolume)) + { + RtlStringCbCopyW (pThreadBlock->wszMountVolume, sizeof(pThreadBlock->wszMountVolume),WIDE ("\\??\\")); + RtlStringCbCatW (pThreadBlock->wszMountVolume, sizeof(pThreadBlock->wszMountVolume),pThreadBlock->mount->wszVolume); + bDevice = FALSE; + } + else + { + pThreadBlock->wszMountVolume[0] = 0; + RtlStringCbCatW (pThreadBlock->wszMountVolume, sizeof(pThreadBlock->wszMountVolume),pThreadBlock->mount->wszVolume); + bDevice = TRUE; + } + + Dump ("Mount THREAD request for File %ls DriveNumber %d Device = %d\n", + pThreadBlock->wszMountVolume, pThreadBlock->mount->nDosDriveNo, bDevice); + + pThreadBlock->ntCreateStatus = TCOpenVolume (DeviceObject, + Extension, + pThreadBlock->mount, + pThreadBlock->wszMountVolume, + bDevice); + + if (!NT_SUCCESS (pThreadBlock->ntCreateStatus) || pThreadBlock->mount->nReturnCode != 0) + { + KeSetEvent (&Extension->keCreateEvent, 0, FALSE); + PsTerminateSystemThread (STATUS_SUCCESS); + } + + // Start IO queue + Extension->Queue.IsFilterDevice = FALSE; + Extension->Queue.DeviceObject = DeviceObject; + Extension->Queue.CryptoInfo = Extension->cryptoInfo; + Extension->Queue.HostFileHandle = Extension->hDeviceFile; + Extension->Queue.VirtualDeviceLength = Extension->DiskLength; + Extension->Queue.MaxReadAheadOffset.QuadPart = Extension->HostLength; + + if (Extension->SecurityClientContextValid) + Extension->Queue.SecurityClientContext = &Extension->SecurityClientContext; + else + Extension->Queue.SecurityClientContext = NULL; + + pThreadBlock->ntCreateStatus = EncryptedIoQueueStart (&Extension->Queue); + + if (!NT_SUCCESS (pThreadBlock->ntCreateStatus)) + { + TCCloseVolume (DeviceObject, Extension); + + pThreadBlock->mount->nReturnCode = ERR_OS_ERROR; + KeSetEvent (&Extension->keCreateEvent, 0, FALSE); + PsTerminateSystemThread (STATUS_SUCCESS); + } + + KeSetEvent (&Extension->keCreateEvent, 0, FALSE); + /* From this point on pThreadBlock cannot be used as it will have been released! */ + pThreadBlock = NULL; + + for (;;) + { + /* Wait for a request from the dispatch routines. */ + KeWaitForSingleObject ((PVOID) & Extension->RequestSemaphore, Executive, KernelMode, FALSE, NULL); + + for (;;) + { + PIO_STACK_LOCATION irpSp; + PLIST_ENTRY request; + PIRP irp; + + request = ExInterlockedRemoveHeadList (&Extension->ListEntry, &Extension->ListSpinLock); + if (request == NULL) + break; + + irp = CONTAINING_RECORD (request, IRP, Tail.Overlay.ListEntry); + irpSp = IoGetCurrentIrpStackLocation (irp); + + ASSERT (irpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL); + + ProcessVolumeDeviceControlIrp (DeviceObject, Extension, irp); + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, irp); + } + + if (Extension->bThreadShouldQuit) + { + Dump ("Closing volume\n"); + EncryptedIoQueueStop (&Extension->Queue); + + TCCloseVolume (DeviceObject, Extension); + PsTerminateSystemThread (STATUS_SUCCESS); + } + } +} + +void TCGetNTNameFromNumber (LPWSTR ntname, int cbNtName, int nDriveNo) +{ + WCHAR tmp[2] = + {0, 0}; + int j = nDriveNo + (WCHAR) 'A'; + + tmp[0] = (short) j; + RtlStringCbCopyW (ntname, cbNtName,(LPWSTR) NT_MOUNT_PREFIX); + RtlStringCbCatW (ntname, cbNtName, tmp); +} + +void TCGetDosNameFromNumber (LPWSTR dosname,int cbDosName, int nDriveNo, DeviceNamespaceType namespaceType) +{ + WCHAR tmp[3] = + {0, ':', 0}; + int j = nDriveNo + (WCHAR) 'A'; + + tmp[0] = (short) j; + + if (DeviceNamespaceGlobal == namespaceType) + { + RtlStringCbCopyW (dosname, cbDosName, (LPWSTR) DOS_MOUNT_PREFIX_GLOBAL); + } + else + { + RtlStringCbCopyW (dosname, cbDosName, (LPWSTR) DOS_MOUNT_PREFIX_DEFAULT); + } + + RtlStringCbCatW (dosname, cbDosName, tmp); +} + +#ifdef _DEBUG +LPWSTR TCTranslateCode (ULONG ulCode) +{ + switch (ulCode) + { +#define TC_CASE_RET_NAME(CODE) case CODE : return L###CODE + + TC_CASE_RET_NAME (TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP); + TC_CASE_RET_NAME (TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE); + TC_CASE_RET_NAME (TC_IOCTL_BOOT_ENCRYPTION_SETUP); + TC_CASE_RET_NAME (TC_IOCTL_DISMOUNT_ALL_VOLUMES); + TC_CASE_RET_NAME (TC_IOCTL_DISMOUNT_VOLUME); + TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES); + TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME); + TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT); + TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS); + TC_CASE_RET_NAME (TC_IOCTL_GET_BOOT_LOADER_VERSION); + TC_CASE_RET_NAME (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT); + TC_CASE_RET_NAME (TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS); + TC_CASE_RET_NAME (TC_IOCTL_GET_DEVICE_REFCOUNT); + TC_CASE_RET_NAME (TC_IOCTL_GET_DRIVE_GEOMETRY); + TC_CASE_RET_NAME (TC_IOCTL_GET_DRIVE_PARTITION_INFO); + TC_CASE_RET_NAME (TC_IOCTL_GET_DRIVER_VERSION); + TC_CASE_RET_NAME (TC_IOCTL_GET_MOUNTED_VOLUMES); + TC_CASE_RET_NAME (TC_IOCTL_GET_PASSWORD_CACHE_STATUS); + TC_CASE_RET_NAME (TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG); + TC_CASE_RET_NAME (TC_IOCTL_GET_PORTABLE_MODE_STATUS); + TC_CASE_RET_NAME (TC_IOCTL_SET_PORTABLE_MODE_STATUS); + TC_CASE_RET_NAME (TC_IOCTL_GET_RESOLVED_SYMLINK); + TC_CASE_RET_NAME (TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG); + TC_CASE_RET_NAME (TC_IOCTL_GET_VOLUME_PROPERTIES); + TC_CASE_RET_NAME (TC_IOCTL_GET_WARNING_FLAGS); + TC_CASE_RET_NAME (TC_IOCTL_DISK_IS_WRITABLE); + TC_CASE_RET_NAME (TC_IOCTL_IS_ANY_VOLUME_MOUNTED); + TC_CASE_RET_NAME (TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED); + TC_CASE_RET_NAME (TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING); + TC_CASE_RET_NAME (TC_IOCTL_MOUNT_VOLUME); + TC_CASE_RET_NAME (TC_IOCTL_OPEN_TEST); + TC_CASE_RET_NAME (TC_IOCTL_PROBE_REAL_DRIVE_SIZE); + TC_CASE_RET_NAME (TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER); + TC_CASE_RET_NAME (TC_IOCTL_REREAD_DRIVER_CONFIG); + TC_CASE_RET_NAME (TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY); + TC_CASE_RET_NAME (TC_IOCTL_START_DECOY_SYSTEM_WIPE); + TC_CASE_RET_NAME (TC_IOCTL_WIPE_PASSWORD_CACHE); + TC_CASE_RET_NAME (TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR); + + TC_CASE_RET_NAME (IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS); + +#undef TC_CASE_RET_NAME + } + + if (ulCode == IOCTL_DISK_GET_DRIVE_GEOMETRY) + return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_GEOMETRY"); + else if (ulCode == IOCTL_DISK_GET_DRIVE_GEOMETRY_EX) + return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_GEOMETRY_EX"); + else if (ulCode == IOCTL_MOUNTDEV_QUERY_DEVICE_NAME) + return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_DEVICE_NAME"); + else if (ulCode == IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME) + return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME"); + else if (ulCode == IOCTL_MOUNTDEV_QUERY_UNIQUE_ID) + return (LPWSTR) _T ("IOCTL_MOUNTDEV_QUERY_UNIQUE_ID"); + else if (ulCode == IOCTL_VOLUME_ONLINE) + return (LPWSTR) _T ("IOCTL_VOLUME_ONLINE"); + else if (ulCode == IOCTL_MOUNTDEV_LINK_CREATED) + return (LPWSTR) _T ("IOCTL_MOUNTDEV_LINK_CREATED"); + else if (ulCode == IOCTL_MOUNTDEV_LINK_DELETED) + return (LPWSTR) _T ("IOCTL_MOUNTDEV_LINK_DELETED"); + else if (ulCode == IOCTL_MOUNTMGR_QUERY_POINTS) + return (LPWSTR) _T ("IOCTL_MOUNTMGR_QUERY_POINTS"); + else if (ulCode == IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_CREATED) + return (LPWSTR) _T ("IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_CREATED"); + else if (ulCode == IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_DELETED) + return (LPWSTR) _T ("IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_DELETED"); + else if (ulCode == IOCTL_DISK_GET_LENGTH_INFO) + return (LPWSTR) _T ("IOCTL_DISK_GET_LENGTH_INFO"); + else if (ulCode == IOCTL_STORAGE_GET_DEVICE_NUMBER) + return (LPWSTR) _T ("IOCTL_STORAGE_GET_DEVICE_NUMBER"); + else if (ulCode == IOCTL_DISK_GET_PARTITION_INFO) + return (LPWSTR) _T ("IOCTL_DISK_GET_PARTITION_INFO"); + else if (ulCode == IOCTL_DISK_GET_PARTITION_INFO_EX) + return (LPWSTR) _T ("IOCTL_DISK_GET_PARTITION_INFO_EX"); + else if (ulCode == IOCTL_DISK_SET_PARTITION_INFO) + return (LPWSTR) _T ("IOCTL_DISK_SET_PARTITION_INFO"); + else if (ulCode == IOCTL_DISK_GET_DRIVE_LAYOUT) + return (LPWSTR) _T ("IOCTL_DISK_GET_DRIVE_LAYOUT"); + else if (ulCode == IOCTL_DISK_SET_DRIVE_LAYOUT_EX) + return (LPWSTR) _T ("IOCTL_DISK_SET_DRIVE_LAYOUT_EX"); + else if (ulCode == IOCTL_DISK_VERIFY) + return (LPWSTR) _T ("IOCTL_DISK_VERIFY"); + else if (ulCode == IOCTL_DISK_FORMAT_TRACKS) + return (LPWSTR) _T ("IOCTL_DISK_FORMAT_TRACKS"); + else if (ulCode == IOCTL_DISK_REASSIGN_BLOCKS) + return (LPWSTR) _T ("IOCTL_DISK_REASSIGN_BLOCKS"); + else if (ulCode == IOCTL_DISK_PERFORMANCE) + return (LPWSTR) _T ("IOCTL_DISK_PERFORMANCE"); + else if (ulCode == IOCTL_DISK_IS_WRITABLE) + return (LPWSTR) _T ("IOCTL_DISK_IS_WRITABLE"); + else if (ulCode == IOCTL_DISK_LOGGING) + return (LPWSTR) _T ("IOCTL_DISK_LOGGING"); + else if (ulCode == IOCTL_DISK_FORMAT_TRACKS_EX) + return (LPWSTR) _T ("IOCTL_DISK_FORMAT_TRACKS_EX"); + else if (ulCode == IOCTL_DISK_HISTOGRAM_STRUCTURE) + return (LPWSTR) _T ("IOCTL_DISK_HISTOGRAM_STRUCTURE"); + else if (ulCode == IOCTL_DISK_HISTOGRAM_DATA) + return (LPWSTR) _T ("IOCTL_DISK_HISTOGRAM_DATA"); + else if (ulCode == IOCTL_DISK_HISTOGRAM_RESET) + return (LPWSTR) _T ("IOCTL_DISK_HISTOGRAM_RESET"); + else if (ulCode == IOCTL_DISK_REQUEST_STRUCTURE) + return (LPWSTR) _T ("IOCTL_DISK_REQUEST_STRUCTURE"); + else if (ulCode == IOCTL_DISK_REQUEST_DATA) + return (LPWSTR) _T ("IOCTL_DISK_REQUEST_DATA"); + else if (ulCode == IOCTL_DISK_CONTROLLER_NUMBER) + return (LPWSTR) _T ("IOCTL_DISK_CONTROLLER_NUMBER"); + else if (ulCode == SMART_GET_VERSION) + return (LPWSTR) _T ("SMART_GET_VERSION"); + else if (ulCode == SMART_SEND_DRIVE_COMMAND) + return (LPWSTR) _T ("SMART_SEND_DRIVE_COMMAND"); + else if (ulCode == SMART_RCV_DRIVE_DATA) + return (LPWSTR) _T ("SMART_RCV_DRIVE_DATA"); + else if (ulCode == IOCTL_DISK_INTERNAL_SET_VERIFY) + return (LPWSTR) _T ("IOCTL_DISK_INTERNAL_SET_VERIFY"); + else if (ulCode == IOCTL_DISK_INTERNAL_CLEAR_VERIFY) + return (LPWSTR) _T ("IOCTL_DISK_INTERNAL_CLEAR_VERIFY"); + else if (ulCode == IOCTL_DISK_CHECK_VERIFY) + return (LPWSTR) _T ("IOCTL_DISK_CHECK_VERIFY"); + else if (ulCode == IOCTL_DISK_MEDIA_REMOVAL) + return (LPWSTR) _T ("IOCTL_DISK_MEDIA_REMOVAL"); + else if (ulCode == IOCTL_DISK_EJECT_MEDIA) + return (LPWSTR) _T ("IOCTL_DISK_EJECT_MEDIA"); + else if (ulCode == IOCTL_DISK_LOAD_MEDIA) + return (LPWSTR) _T ("IOCTL_DISK_LOAD_MEDIA"); + else if (ulCode == IOCTL_DISK_RESERVE) + return (LPWSTR) _T ("IOCTL_DISK_RESERVE"); + else if (ulCode == IOCTL_DISK_RELEASE) + return (LPWSTR) _T ("IOCTL_DISK_RELEASE"); + else if (ulCode == IOCTL_DISK_FIND_NEW_DEVICES) + return (LPWSTR) _T ("IOCTL_DISK_FIND_NEW_DEVICES"); + else if (ulCode == IOCTL_DISK_GET_MEDIA_TYPES) + return (LPWSTR) _T ("IOCTL_DISK_GET_MEDIA_TYPES"); + else if (ulCode == IOCTL_STORAGE_SET_HOTPLUG_INFO) + return (LPWSTR) _T ("IOCTL_STORAGE_SET_HOTPLUG_INFO"); + else if (ulCode == IRP_MJ_READ) + return (LPWSTR) _T ("IRP_MJ_READ"); + else if (ulCode == IRP_MJ_WRITE) + return (LPWSTR) _T ("IRP_MJ_WRITE"); + else if (ulCode == IRP_MJ_CREATE) + return (LPWSTR) _T ("IRP_MJ_CREATE"); + else if (ulCode == IRP_MJ_CLOSE) + return (LPWSTR) _T ("IRP_MJ_CLOSE"); + else if (ulCode == IRP_MJ_CLEANUP) + return (LPWSTR) _T ("IRP_MJ_CLEANUP"); + else if (ulCode == IRP_MJ_FLUSH_BUFFERS) + return (LPWSTR) _T ("IRP_MJ_FLUSH_BUFFERS"); + else if (ulCode == IRP_MJ_SHUTDOWN) + return (LPWSTR) _T ("IRP_MJ_SHUTDOWN"); + else if (ulCode == IRP_MJ_DEVICE_CONTROL) + return (LPWSTR) _T ("IRP_MJ_DEVICE_CONTROL"); + else + { + return (LPWSTR) _T ("IOCTL"); + } +} + +#endif + +void TCDeleteDeviceObject (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension) +{ + UNICODE_STRING Win32NameString; + NTSTATUS ntStatus; + + Dump ("TCDeleteDeviceObject BEGIN\n"); + + if (Extension->bRootDevice) + { + RtlInitUnicodeString (&Win32NameString, (LPWSTR) DOS_ROOT_PREFIX); + ntStatus = IoDeleteSymbolicLink (&Win32NameString); + if (!NT_SUCCESS (ntStatus)) + Dump ("IoDeleteSymbolicLink failed ntStatus = 0x%08x\n", ntStatus); + + RootDeviceObject = NULL; + } + else + { + if (Extension->peThread != NULL) + TCStopVolumeThread (DeviceObject, Extension); + + if (Extension->UserSid) + TCfree (Extension->UserSid); + + if (Extension->SecurityClientContextValid) + { + if (OsMajorVersion == 5 && OsMinorVersion == 0) + { + ObDereferenceObject (Extension->SecurityClientContext.ClientToken); + } + else + { + // Windows 2000 does not support PsDereferenceImpersonationToken() used by SeDeleteClientSecurity(). + // TODO: Use only SeDeleteClientSecurity() once support for Windows 2000 is dropped. + + VOID (*PsDereferenceImpersonationTokenD) (PACCESS_TOKEN ImpersonationToken); + UNICODE_STRING name; + RtlInitUnicodeString (&name, L"PsDereferenceImpersonationToken"); + + PsDereferenceImpersonationTokenD = MmGetSystemRoutineAddress (&name); + if (!PsDereferenceImpersonationTokenD) + TC_BUG_CHECK (STATUS_NOT_IMPLEMENTED); + +# define PsDereferencePrimaryToken +# define PsDereferenceImpersonationToken PsDereferenceImpersonationTokenD + + SeDeleteClientSecurity (&Extension->SecurityClientContext); + +# undef PsDereferencePrimaryToken +# undef PsDereferenceImpersonationToken + } + } + + VirtualVolumeDeviceObjects[Extension->nDosDriveNo] = NULL; + } + + IoDeleteDevice (DeviceObject); + + Dump ("TCDeleteDeviceObject END\n"); +} + + +VOID TCUnloadDriver (PDRIVER_OBJECT DriverObject) +{ + Dump ("TCUnloadDriver BEGIN\n"); + + OnShutdownPending(); + + if (IsBootDriveMounted()) + TC_BUG_CHECK (STATUS_INVALID_DEVICE_STATE); + + EncryptionThreadPoolStop(); + TCDeleteDeviceObject (RootDeviceObject, (PEXTENSION) RootDeviceObject->DeviceExtension); + + Dump ("TCUnloadDriver END\n"); +} + + +void OnShutdownPending () +{ + UNMOUNT_STRUCT unmount; + memset (&unmount, 0, sizeof (unmount)); + unmount.ignoreOpenFiles = TRUE; + + while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_DISMOUNT_ALL_VOLUMES, &unmount, sizeof (unmount), &unmount, sizeof (unmount)) == STATUS_INSUFFICIENT_RESOURCES || unmount.HiddenVolumeProtectionTriggered) + unmount.HiddenVolumeProtectionTriggered = FALSE; + + while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES); +} + + +NTSTATUS TCDeviceIoControl (PWSTR deviceName, ULONG IoControlCode, void *InputBuffer, ULONG InputBufferSize, void *OutputBuffer, ULONG OutputBufferSize) +{ + IO_STATUS_BLOCK ioStatusBlock; + NTSTATUS ntStatus; + PIRP irp; + PFILE_OBJECT fileObject; + PDEVICE_OBJECT deviceObject; + KEVENT event; + UNICODE_STRING name; + + RtlInitUnicodeString(&name, deviceName); + ntStatus = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject); + + if (!NT_SUCCESS (ntStatus)) + return ntStatus; + + KeInitializeEvent(&event, NotificationEvent, FALSE); + + irp = IoBuildDeviceIoControlRequest (IoControlCode, + deviceObject, + InputBuffer, InputBufferSize, + OutputBuffer, OutputBufferSize, + FALSE, + &event, + &ioStatusBlock); + + if (irp == NULL) + { + Dump ("IRP allocation failed\n"); + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + goto ret; + } + + IoGetNextIrpStackLocation (irp)->FileObject = fileObject; + + ntStatus = IoCallDriver (deviceObject, irp); + if (ntStatus == STATUS_PENDING) + { + KeWaitForSingleObject (&event, Executive, KernelMode, FALSE, NULL); + ntStatus = ioStatusBlock.Status; + } + +ret: + ObDereferenceObject (fileObject); + return ntStatus; +} + + +typedef struct +{ + PDEVICE_OBJECT deviceObject; ULONG ioControlCode; void *inputBuffer; int inputBufferSize; void *outputBuffer; int outputBufferSize; + NTSTATUS Status; + KEVENT WorkItemCompletedEvent; +} SendDeviceIoControlRequestWorkItemArgs; + + +static VOID SendDeviceIoControlRequestWorkItemRoutine (PDEVICE_OBJECT rootDeviceObject, SendDeviceIoControlRequestWorkItemArgs *arg) +{ + arg->Status = SendDeviceIoControlRequest (arg->deviceObject, arg->ioControlCode, arg->inputBuffer, arg->inputBufferSize, arg->outputBuffer, arg->outputBufferSize); + KeSetEvent (&arg->WorkItemCompletedEvent, IO_NO_INCREMENT, FALSE); +} + + +NTSTATUS SendDeviceIoControlRequest (PDEVICE_OBJECT deviceObject, ULONG ioControlCode, void *inputBuffer, int inputBufferSize, void *outputBuffer, int outputBufferSize) +{ + IO_STATUS_BLOCK ioStatusBlock; + NTSTATUS status; + PIRP irp; + KEVENT event; + + if (KeGetCurrentIrql() > APC_LEVEL) + { + SendDeviceIoControlRequestWorkItemArgs args; + + PIO_WORKITEM workItem = IoAllocateWorkItem (RootDeviceObject); + if (!workItem) + return STATUS_INSUFFICIENT_RESOURCES; + + args.deviceObject = deviceObject; + args.ioControlCode = ioControlCode; + args.inputBuffer = inputBuffer; + args.inputBufferSize = inputBufferSize; + args.outputBuffer = outputBuffer; + args.outputBufferSize = outputBufferSize; + + KeInitializeEvent (&args.WorkItemCompletedEvent, SynchronizationEvent, FALSE); + IoQueueWorkItem (workItem, SendDeviceIoControlRequestWorkItemRoutine, DelayedWorkQueue, &args); + + KeWaitForSingleObject (&args.WorkItemCompletedEvent, Executive, KernelMode, FALSE, NULL); + IoFreeWorkItem (workItem); + + return args.Status; + } + + KeInitializeEvent (&event, NotificationEvent, FALSE); + + irp = IoBuildDeviceIoControlRequest (ioControlCode, deviceObject, inputBuffer, inputBufferSize, + outputBuffer, outputBufferSize, FALSE, &event, &ioStatusBlock); + + if (!irp) + return STATUS_INSUFFICIENT_RESOURCES; + + ObReferenceObject (deviceObject); + + status = IoCallDriver (deviceObject, irp); + if (status == STATUS_PENDING) + { + KeWaitForSingleObject (&event, Executive, KernelMode, FALSE, NULL); + status = ioStatusBlock.Status; + } + + ObDereferenceObject (deviceObject); + return status; +} + + +NTSTATUS ProbeRealDriveSize (PDEVICE_OBJECT driveDeviceObject, LARGE_INTEGER *driveSize) +{ + NTSTATUS status; + LARGE_INTEGER sysLength; + LARGE_INTEGER offset; + byte *sectorBuffer; + ULONGLONG startTime; + + if (!UserCanAccessDriveDevice()) + return STATUS_ACCESS_DENIED; + + sectorBuffer = TCalloc (TC_SECTOR_SIZE_BIOS); + if (!sectorBuffer) + return STATUS_INSUFFICIENT_RESOURCES; + + status = SendDeviceIoControlRequest (driveDeviceObject, IOCTL_DISK_GET_LENGTH_INFO, + NULL, 0, &sysLength, sizeof (sysLength)); + + if (!NT_SUCCESS (status)) + { + Dump ("Failed to get drive size - error %x\n", status); + TCfree (sectorBuffer); + return status; + } + + startTime = KeQueryInterruptTime (); + for (offset.QuadPart = sysLength.QuadPart; ; offset.QuadPart += TC_SECTOR_SIZE_BIOS) + { + status = TCReadDevice (driveDeviceObject, sectorBuffer, offset, TC_SECTOR_SIZE_BIOS); + + if (NT_SUCCESS (status)) + status = TCWriteDevice (driveDeviceObject, sectorBuffer, offset, TC_SECTOR_SIZE_BIOS); + + if (!NT_SUCCESS (status)) + { + driveSize->QuadPart = offset.QuadPart; + Dump ("Real drive size = %I64d bytes (%I64d hidden)\n", driveSize->QuadPart, driveSize->QuadPart - sysLength.QuadPart); + TCfree (sectorBuffer); + return STATUS_SUCCESS; + } + + if (KeQueryInterruptTime() - startTime > 3ULL * 60 * 1000 * 1000 * 10) + { + // Abort if probing for more than 3 minutes + driveSize->QuadPart = sysLength.QuadPart; + TCfree (sectorBuffer); + return STATUS_TIMEOUT; + } + } +} + + +NTSTATUS TCOpenFsVolume (PEXTENSION Extension, PHANDLE volumeHandle, PFILE_OBJECT * fileObject) +{ + NTSTATUS ntStatus; + OBJECT_ATTRIBUTES objectAttributes; + UNICODE_STRING fullFileName; + IO_STATUS_BLOCK ioStatus; + WCHAR volumeName[TC_MAX_PATH]; + + TCGetNTNameFromNumber (volumeName, sizeof(volumeName),Extension->nDosDriveNo); + RtlInitUnicodeString (&fullFileName, volumeName); + InitializeObjectAttributes (&objectAttributes, &fullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); + + ntStatus = ZwCreateFile (volumeHandle, + SYNCHRONIZE | GENERIC_READ, + &objectAttributes, + &ioStatus, + NULL, + FILE_ATTRIBUTE_NORMAL, + FILE_SHARE_READ | FILE_SHARE_WRITE, + FILE_OPEN, + FILE_SYNCHRONOUS_IO_NONALERT, + NULL, + 0); + + Dump ("Volume %ls open NTSTATUS 0x%08x\n", volumeName, ntStatus); + + if (!NT_SUCCESS (ntStatus)) + return ntStatus; + + ntStatus = ObReferenceObjectByHandle (*volumeHandle, + FILE_READ_DATA, + NULL, + KernelMode, + fileObject, + NULL); + + if (!NT_SUCCESS (ntStatus)) + ZwClose (*volumeHandle); + + return ntStatus; +} + + +void TCCloseFsVolume (HANDLE volumeHandle, PFILE_OBJECT fileObject) +{ + ObDereferenceObject (fileObject); + ZwClose (volumeHandle); +} + + +static NTSTATUS TCReadWriteDevice (BOOL write, PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length) +{ + NTSTATUS status; + IO_STATUS_BLOCK ioStatusBlock; + PIRP irp; + KEVENT completionEvent; + + ASSERT (KeGetCurrentIrql() <= APC_LEVEL); + + KeInitializeEvent (&completionEvent, NotificationEvent, FALSE); + irp = IoBuildSynchronousFsdRequest (write ? IRP_MJ_WRITE : IRP_MJ_READ, deviceObject, buffer, length, &offset, &completionEvent, &ioStatusBlock); + if (!irp) + return STATUS_INSUFFICIENT_RESOURCES; + + ObReferenceObject (deviceObject); + status = IoCallDriver (deviceObject, irp); + + if (status == STATUS_PENDING) + { + status = KeWaitForSingleObject (&completionEvent, Executive, KernelMode, FALSE, NULL); + if (NT_SUCCESS (status)) + status = ioStatusBlock.Status; + } + + ObDereferenceObject (deviceObject); + return status; +} + + +NTSTATUS TCReadDevice (PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length) +{ + return TCReadWriteDevice (FALSE, deviceObject, buffer, offset, length); +} + + +NTSTATUS TCWriteDevice (PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length) +{ + return TCReadWriteDevice (TRUE, deviceObject, buffer, offset, length); +} + + +NTSTATUS TCFsctlCall (PFILE_OBJECT fileObject, LONG IoControlCode, + void *InputBuffer, int InputBufferSize, void *OutputBuffer, int OutputBufferSize) +{ + IO_STATUS_BLOCK ioStatusBlock; + NTSTATUS ntStatus; + PIRP irp; + KEVENT event; + PIO_STACK_LOCATION stack; + PDEVICE_OBJECT deviceObject = IoGetRelatedDeviceObject (fileObject); + + KeInitializeEvent(&event, NotificationEvent, FALSE); + + irp = IoBuildDeviceIoControlRequest (IoControlCode, + deviceObject, + InputBuffer, InputBufferSize, + OutputBuffer, OutputBufferSize, + FALSE, + &event, + &ioStatusBlock); + + if (irp == NULL) + return STATUS_INSUFFICIENT_RESOURCES; + + stack = IoGetNextIrpStackLocation(irp); + + stack->MajorFunction = IRP_MJ_FILE_SYSTEM_CONTROL; + stack->MinorFunction = IRP_MN_USER_FS_REQUEST; + stack->FileObject = fileObject; + + ntStatus = IoCallDriver (deviceObject, irp); + if (ntStatus == STATUS_PENDING) + { + KeWaitForSingleObject (&event, Executive, KernelMode, FALSE, NULL); + ntStatus = ioStatusBlock.Status; + } + + return ntStatus; +} + + +NTSTATUS CreateDriveLink (int nDosDriveNo) +{ + WCHAR dev[128], link[128]; + UNICODE_STRING deviceName, symLink; + NTSTATUS ntStatus; + + TCGetNTNameFromNumber (dev, sizeof(dev),nDosDriveNo); + TCGetDosNameFromNumber (link, sizeof(link),nDosDriveNo, DeviceNamespaceDefault); + + RtlInitUnicodeString (&deviceName, dev); + RtlInitUnicodeString (&symLink, link); + + ntStatus = IoCreateSymbolicLink (&symLink, &deviceName); + Dump ("IoCreateSymbolicLink returned %X\n", ntStatus); + return ntStatus; +} + + +NTSTATUS RemoveDriveLink (int nDosDriveNo) +{ + WCHAR link[256]; + UNICODE_STRING symLink; + NTSTATUS ntStatus; + + TCGetDosNameFromNumber (link, sizeof(link),nDosDriveNo, DeviceNamespaceDefault); + RtlInitUnicodeString (&symLink, link); + + ntStatus = IoDeleteSymbolicLink (&symLink); + Dump ("IoDeleteSymbolicLink returned %X\n", ntStatus); + return ntStatus; +} + + +NTSTATUS MountManagerMount (MOUNT_STRUCT *mount) +{ + NTSTATUS ntStatus; + WCHAR arrVolume[256]; + char buf[200]; + PMOUNTMGR_TARGET_NAME in = (PMOUNTMGR_TARGET_NAME) buf; + PMOUNTMGR_CREATE_POINT_INPUT point = (PMOUNTMGR_CREATE_POINT_INPUT) buf; + + TCGetNTNameFromNumber (arrVolume, sizeof(arrVolume),mount->nDosDriveNo); + in->DeviceNameLength = (USHORT) wcslen (arrVolume) * 2; + RtlStringCbCopyW(in->DeviceName, sizeof(buf) - sizeof(in->DeviceNameLength),arrVolume); + + ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION, + in, (ULONG) (sizeof (in->DeviceNameLength) + wcslen (arrVolume) * 2), 0, 0); + + memset (buf, 0, sizeof buf); + TCGetDosNameFromNumber ((PWSTR) &point[1], sizeof(buf) - sizeof(MOUNTMGR_CREATE_POINT_INPUT),mount->nDosDriveNo, DeviceNamespaceDefault); + + point->SymbolicLinkNameOffset = sizeof (MOUNTMGR_CREATE_POINT_INPUT); + point->SymbolicLinkNameLength = (USHORT) wcslen ((PWSTR) &point[1]) * 2; + + point->DeviceNameOffset = point->SymbolicLinkNameOffset + point->SymbolicLinkNameLength; + TCGetNTNameFromNumber ((PWSTR) (buf + point->DeviceNameOffset), sizeof(buf) - point->DeviceNameOffset,mount->nDosDriveNo); + point->DeviceNameLength = (USHORT) wcslen ((PWSTR) (buf + point->DeviceNameOffset)) * 2; + + ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_CREATE_POINT, point, + point->DeviceNameOffset + point->DeviceNameLength, 0, 0); + + return ntStatus; +} + + +NTSTATUS MountManagerUnmount (int nDosDriveNo) +{ + NTSTATUS ntStatus; + char buf[256], out[300]; + PMOUNTMGR_MOUNT_POINT in = (PMOUNTMGR_MOUNT_POINT) buf; + + memset (buf, 0, sizeof buf); + + TCGetDosNameFromNumber ((PWSTR) &in[1], sizeof(buf) - sizeof(MOUNTMGR_MOUNT_POINT),nDosDriveNo, DeviceNamespaceDefault); + + // Only symbolic link can be deleted with IOCTL_MOUNTMGR_DELETE_POINTS. If any other entry is specified, the mount manager will ignore subsequent IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION for the same volume ID. + in->SymbolicLinkNameOffset = sizeof (MOUNTMGR_MOUNT_POINT); + in->SymbolicLinkNameLength = (USHORT) wcslen ((PWCHAR) &in[1]) * 2; + + ntStatus = TCDeviceIoControl (MOUNTMGR_DEVICE_NAME, IOCTL_MOUNTMGR_DELETE_POINTS, + in, sizeof(MOUNTMGR_MOUNT_POINT) + in->SymbolicLinkNameLength, out, sizeof out); + + Dump ("IOCTL_MOUNTMGR_DELETE_POINTS returned 0x%08x\n", ntStatus); + + return ntStatus; +} + + +NTSTATUS MountDevice (PDEVICE_OBJECT DeviceObject, MOUNT_STRUCT *mount) +{ + PDEVICE_OBJECT NewDeviceObject; + NTSTATUS ntStatus; + + // Make sure the user is asking for a reasonable nDosDriveNo + if (mount->nDosDriveNo >= 0 && mount->nDosDriveNo <= 25 + && IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceDefault) // drive letter must not exist both locally and globally + && IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceGlobal) + ) + { + Dump ("Mount request looks valid\n"); + } + else + { + Dump ("WARNING: MOUNT DRIVE LETTER INVALID\n"); + mount->nReturnCode = ERR_DRIVE_NOT_FOUND; + return ERR_DRIVE_NOT_FOUND; + } + + if (!SelfTestsPassed) + { + mount->nReturnCode = ERR_SELF_TESTS_FAILED; + return ERR_SELF_TESTS_FAILED; + } + + ntStatus = TCCreateDeviceObject (DeviceObject->DriverObject, &NewDeviceObject, mount); + + if (!NT_SUCCESS (ntStatus)) + { + Dump ("Mount CREATE DEVICE ERROR, ntStatus = 0x%08x\n", ntStatus); + return ntStatus; + } + else + { + PEXTENSION NewExtension = (PEXTENSION) NewDeviceObject->DeviceExtension; + SECURITY_SUBJECT_CONTEXT subContext; + PACCESS_TOKEN accessToken; + + SeCaptureSubjectContext (&subContext); + SeLockSubjectContext(&subContext); + if (subContext.ClientToken && subContext.ImpersonationLevel >= SecurityImpersonation) + accessToken = subContext.ClientToken; + else + accessToken = subContext.PrimaryToken; + + if (!accessToken) + { + ntStatus = STATUS_INVALID_PARAMETER; + } + else + { + PTOKEN_USER tokenUser; + + ntStatus = SeQueryInformationToken (accessToken, TokenUser, &tokenUser); + if (NT_SUCCESS (ntStatus)) + { + ULONG sidLength = RtlLengthSid (tokenUser->User.Sid); + + NewExtension->UserSid = TCalloc (sidLength); + if (!NewExtension->UserSid) + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + else + ntStatus = RtlCopySid (sidLength, NewExtension->UserSid, tokenUser->User.Sid); + + ExFreePool (tokenUser); // Documented in newer versions of WDK + } + } + + SeUnlockSubjectContext(&subContext); + SeReleaseSubjectContext (&subContext); + + if (NT_SUCCESS (ntStatus)) + ntStatus = TCStartVolumeThread (NewDeviceObject, NewExtension, mount); + + if (!NT_SUCCESS (ntStatus)) + { + Dump ("Mount FAILURE NT ERROR, ntStatus = 0x%08x\n", ntStatus); + TCDeleteDeviceObject (NewDeviceObject, NewExtension); + return ntStatus; + } + else + { + if (mount->nReturnCode == 0) + { + HANDLE volumeHandle; + PFILE_OBJECT volumeFileObject; + ULONG labelLen = (ULONG) wcslen (mount->wszLabel); + BOOL bIsNTFS = FALSE; + ULONG labelMaxLen, labelEffectiveLen; + + Dump ("Mount SUCCESS TC code = 0x%08x READ-ONLY = %d\n", mount->nReturnCode, NewExtension->bReadOnly); + + if (NewExtension->bReadOnly) + NewDeviceObject->Characteristics |= FILE_READ_ONLY_DEVICE; + + NewDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; + + NewExtension->UniqueVolumeId = LastUniqueVolumeId++; + + // check again that the drive letter is available globally and locally + if ( !IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceDefault) + || !IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceGlobal) + ) + { + TCDeleteDeviceObject (NewDeviceObject, NewExtension); + mount->nReturnCode = ERR_DRIVE_NOT_FOUND; + return ERR_DRIVE_NOT_FOUND; + } + + if (mount->bMountManager) + MountManagerMount (mount); + + NewExtension->bMountManager = mount->bMountManager; + + // We create symbolic link even if mount manager is notified of + // arriving volume as it apparently sometimes fails to create the link + CreateDriveLink (mount->nDosDriveNo); + + mount->FilesystemDirty = FALSE; + + if (NT_SUCCESS (TCOpenFsVolume (NewExtension, &volumeHandle, &volumeFileObject))) + { + __try + { + ULONG fsStatus; + + if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_IS_VOLUME_DIRTY, NULL, 0, &fsStatus, sizeof (fsStatus))) + && (fsStatus & VOLUME_IS_DIRTY)) + { + mount->FilesystemDirty = TRUE; + } + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + mount->FilesystemDirty = TRUE; + } + + // detect if the filesystem is NTFS or FAT + __try + { + NTFS_VOLUME_DATA_BUFFER ntfsData; + if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsData, sizeof (ntfsData)))) + { + bIsNTFS = TRUE; + } + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + bIsNTFS = FALSE; + } + + NewExtension->bIsNTFS = bIsNTFS; + mount->bIsNTFS = bIsNTFS; + + if (labelLen > 0) + { + if (bIsNTFS) + labelMaxLen = 32; // NTFS maximum label length + else + labelMaxLen = 11; // FAT maximum label length + + // calculate label effective length + labelEffectiveLen = labelLen > labelMaxLen? labelMaxLen : labelLen; + + // correct the label in the device + memset (&NewExtension->wszLabel[labelEffectiveLen], 0, 33 - labelEffectiveLen); + memcpy (mount->wszLabel, NewExtension->wszLabel, 33); + + // set the volume label + __try + { + IO_STATUS_BLOCK ioblock; + ULONG labelInfoSize = sizeof(FILE_FS_LABEL_INFORMATION) + (labelEffectiveLen * sizeof(WCHAR)); + FILE_FS_LABEL_INFORMATION* labelInfo = (FILE_FS_LABEL_INFORMATION*) TCalloc (labelInfoSize); + labelInfo->VolumeLabelLength = labelEffectiveLen * sizeof(WCHAR); + memcpy (labelInfo->VolumeLabel, mount->wszLabel, labelInfo->VolumeLabelLength); + + if (STATUS_SUCCESS == ZwSetVolumeInformationFile (volumeHandle, &ioblock, labelInfo, labelInfoSize, FileFsLabelInformation)) + { + mount->bDriverSetLabel = TRUE; + NewExtension->bDriverSetLabel = TRUE; + } + + TCfree(labelInfo); + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + + } + } + + TCCloseFsVolume (volumeHandle, volumeFileObject); + } + } + else + { + Dump ("Mount FAILURE TC code = 0x%08x\n", mount->nReturnCode); + TCDeleteDeviceObject (NewDeviceObject, NewExtension); + } + + return STATUS_SUCCESS; + } + } +} + +NTSTATUS UnmountDevice (UNMOUNT_STRUCT *unmountRequest, PDEVICE_OBJECT deviceObject, BOOL ignoreOpenFiles) +{ + PEXTENSION extension = deviceObject->DeviceExtension; + NTSTATUS ntStatus; + HANDLE volumeHandle; + PFILE_OBJECT volumeFileObject; + + Dump ("UnmountDevice %d\n", extension->nDosDriveNo); + + ntStatus = TCOpenFsVolume (extension, &volumeHandle, &volumeFileObject); + + if (NT_SUCCESS (ntStatus)) + { + int dismountRetry; + + // Dismounting a writable NTFS filesystem prevents the driver from being unloaded on Windows 7 + if (IsOSAtLeast (WIN_7) && !extension->bReadOnly) + { + NTFS_VOLUME_DATA_BUFFER ntfsData; + + if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsData, sizeof (ntfsData)))) + DriverUnloadDisabled = TRUE; + } + + // Lock volume + ntStatus = TCFsctlCall (volumeFileObject, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0); + Dump ("FSCTL_LOCK_VOLUME returned %X\n", ntStatus); + + if (!NT_SUCCESS (ntStatus) && !ignoreOpenFiles) + { + TCCloseFsVolume (volumeHandle, volumeFileObject); + return ERR_FILES_OPEN; + } + + // Dismount volume + for (dismountRetry = 0; dismountRetry < 200; ++dismountRetry) + { + ntStatus = TCFsctlCall (volumeFileObject, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0); + Dump ("FSCTL_DISMOUNT_VOLUME returned %X\n", ntStatus); + + if (NT_SUCCESS (ntStatus) || ntStatus == STATUS_VOLUME_DISMOUNTED) + break; + + if (!ignoreOpenFiles) + { + TCCloseFsVolume (volumeHandle, volumeFileObject); + return ERR_FILES_OPEN; + } + + TCSleep (100); + } + } + else + { + // Volume cannot be opened => force dismount if allowed + if (!ignoreOpenFiles) + return ERR_FILES_OPEN; + else + volumeHandle = NULL; + } + + if (extension->bMountManager) + MountManagerUnmount (extension->nDosDriveNo); + + // We always remove symbolic link as mount manager might fail to do so + RemoveDriveLink (extension->nDosDriveNo); + + extension->bShuttingDown = TRUE; + + ntStatus = IoAcquireRemoveLock (&extension->Queue.RemoveLock, NULL); + ASSERT (NT_SUCCESS (ntStatus)); + IoReleaseRemoveLockAndWait (&extension->Queue.RemoveLock, NULL); + + if (volumeHandle != NULL) + TCCloseFsVolume (volumeHandle, volumeFileObject); + + if (unmountRequest) + { + PCRYPTO_INFO cryptoInfo = ((PEXTENSION) deviceObject->DeviceExtension)->cryptoInfo; + unmountRequest->HiddenVolumeProtectionTriggered = (cryptoInfo->bProtectHiddenVolume && cryptoInfo->bHiddenVolProtectionAction); + } + + TCDeleteDeviceObject (deviceObject, (PEXTENSION) deviceObject->DeviceExtension); + return 0; +} + + +static PDEVICE_OBJECT FindVolumeWithHighestUniqueId (int maxUniqueId) +{ + PDEVICE_OBJECT highestIdDevice = NULL; + int highestId = -1; + int drive; + + for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) + { + PDEVICE_OBJECT device = GetVirtualVolumeDeviceObject (drive); + if (device) + { + PEXTENSION extension = (PEXTENSION) device->DeviceExtension; + if (extension->UniqueVolumeId > highestId && extension->UniqueVolumeId <= maxUniqueId) + { + highestId = extension->UniqueVolumeId; + highestIdDevice = device; + } + } + } + + return highestIdDevice; +} + + +NTSTATUS UnmountAllDevices (UNMOUNT_STRUCT *unmountRequest, BOOL ignoreOpenFiles) +{ + NTSTATUS status = 0; + PDEVICE_OBJECT ListDevice; + int maxUniqueId = LastUniqueVolumeId; + + Dump ("Unmounting all volumes\n"); + + if (unmountRequest) + unmountRequest->HiddenVolumeProtectionTriggered = FALSE; + + // Dismount volumes in the reverse order they were mounted to properly dismount nested volumes + while ((ListDevice = FindVolumeWithHighestUniqueId (maxUniqueId)) != NULL) + { + PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; + maxUniqueId = ListExtension->UniqueVolumeId - 1; + + if (IsVolumeAccessibleByCurrentUser (ListExtension)) + { + NTSTATUS ntStatus; + + if (unmountRequest) + unmountRequest->nDosDriveNo = ListExtension->nDosDriveNo; + + ntStatus = UnmountDevice (unmountRequest, ListDevice, ignoreOpenFiles); + status = ntStatus == 0 ? status : ntStatus; + + if (unmountRequest && unmountRequest->HiddenVolumeProtectionTriggered) + break; + } + } + + return status; +} + +// Resolves symbolic link name to its target name +NTSTATUS SymbolicLinkToTarget (PWSTR symlinkName, PWSTR targetName, USHORT maxTargetNameLength) +{ + NTSTATUS ntStatus; + OBJECT_ATTRIBUTES objectAttributes; + UNICODE_STRING fullFileName; + HANDLE handle; + + RtlInitUnicodeString (&fullFileName, symlinkName); + InitializeObjectAttributes (&objectAttributes, &fullFileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); + + ntStatus = ZwOpenSymbolicLinkObject (&handle, GENERIC_READ, &objectAttributes); + + if (NT_SUCCESS (ntStatus)) + { + UNICODE_STRING target; + target.Buffer = targetName; + target.Length = 0; + target.MaximumLength = maxTargetNameLength; + memset (targetName, 0, maxTargetNameLength); + + ntStatus = ZwQuerySymbolicLinkObject (handle, &target, NULL); + + ZwClose (handle); + } + + return ntStatus; +} + + +// Checks if two regions overlap (borders are parts of regions) +BOOL RegionsOverlap (unsigned __int64 start1, unsigned __int64 end1, unsigned __int64 start2, unsigned __int64 end2) +{ + return (start1 < start2) ? (end1 >= start2) : (start1 <= end2); +} + + +void GetIntersection (uint64 start1, uint32 length1, uint64 start2, uint64 end2, uint64 *intersectStart, uint32 *intersectLength) +{ + uint64 end1 = start1 + length1 - 1; + uint64 intersectEnd = (end1 <= end2) ? end1 : end2; + + *intersectStart = (start1 >= start2) ? start1 : start2; + *intersectLength = (uint32) ((*intersectStart > intersectEnd) ? 0 : intersectEnd + 1 - *intersectStart); + + if (*intersectLength == 0) + *intersectStart = start1; +} + + +BOOL IsAccessibleByUser (PUNICODE_STRING objectFileName, BOOL readOnly) +{ + OBJECT_ATTRIBUTES fileObjAttributes; + IO_STATUS_BLOCK ioStatusBlock; + HANDLE fileHandle; + NTSTATUS status; + + ASSERT (!IoIsSystemThread (PsGetCurrentThread())); + + InitializeObjectAttributes (&fileObjAttributes, objectFileName, OBJ_CASE_INSENSITIVE | OBJ_FORCE_ACCESS_CHECK | OBJ_KERNEL_HANDLE, NULL, NULL); + + status = ZwCreateFile (&fileHandle, + readOnly ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE, + &fileObjAttributes, + &ioStatusBlock, + NULL, + FILE_ATTRIBUTE_NORMAL, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + FILE_OPEN, + FILE_SYNCHRONOUS_IO_NONALERT, + NULL, + 0); + + if (NT_SUCCESS (status)) + { + ZwClose (fileHandle); + return TRUE; + } + + return FALSE; +} + + +BOOL UserCanAccessDriveDevice () +{ + UNICODE_STRING name; + RtlInitUnicodeString (&name, L"\\Device\\MountPointManager"); + + return IsAccessibleByUser (&name, FALSE); +} + +BOOL IsDriveLetterAvailable (int nDosDriveNo, DeviceNamespaceType namespaceType) +{ + OBJECT_ATTRIBUTES objectAttributes; + UNICODE_STRING objectName; + WCHAR link[128]; + HANDLE handle; + NTSTATUS ntStatus; + + TCGetDosNameFromNumber (link, sizeof(link),nDosDriveNo, namespaceType); + RtlInitUnicodeString (&objectName, link); + InitializeObjectAttributes (&objectAttributes, &objectName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); + + if (NT_SUCCESS (ntStatus = ZwOpenSymbolicLinkObject (&handle, GENERIC_READ, &objectAttributes))) + { + ZwClose (handle); + return FALSE; + } + + return (ntStatus == STATUS_OBJECT_NAME_NOT_FOUND)? TRUE : FALSE; +} + + +NTSTATUS TCCompleteIrp (PIRP irp, NTSTATUS status, ULONG_PTR information) +{ + irp->IoStatus.Status = status; + irp->IoStatus.Information = information; + IoCompleteRequest (irp, IO_NO_INCREMENT); + return status; +} + + +NTSTATUS TCCompleteDiskIrp (PIRP irp, NTSTATUS status, ULONG_PTR information) +{ + irp->IoStatus.Status = status; + irp->IoStatus.Information = information; + IoCompleteRequest (irp, NT_SUCCESS (status) ? IO_DISK_INCREMENT : IO_NO_INCREMENT); + return status; +} + + +size_t GetCpuCount () +{ + KAFFINITY activeCpuMap = KeQueryActiveProcessors(); + size_t mapSize = sizeof (activeCpuMap) * 8; + size_t cpuCount = 0; + + while (mapSize--) + { + if (activeCpuMap & 1) + ++cpuCount; + + activeCpuMap >>= 1; + } + + if (cpuCount == 0) + return 1; + + return cpuCount; +} + + +void EnsureNullTerminatedString (wchar_t *str, size_t maxSizeInBytes) +{ + ASSERT ((maxSizeInBytes & 1) == 0); + str[maxSizeInBytes / sizeof (wchar_t) - 1] = 0; +} + + +void *AllocateMemoryWithTimeout (size_t size, int retryDelay, int timeout) +{ + LARGE_INTEGER waitInterval; + waitInterval.QuadPart = retryDelay * -10000; + + ASSERT (KeGetCurrentIrql() <= APC_LEVEL); + ASSERT (retryDelay > 0 && retryDelay <= timeout); + + while (TRUE) + { + void *memory = TCalloc (size); + if (memory) + return memory; + + timeout -= retryDelay; + if (timeout <= 0) + break; + + KeDelayExecutionThread (KernelMode, FALSE, &waitInterval); + } + + return NULL; +} + + +NTSTATUS TCReadRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, PKEY_VALUE_PARTIAL_INFORMATION *keyData) +{ + OBJECT_ATTRIBUTES regObjAttribs; + HANDLE regKeyHandle; + NTSTATUS status; + UNICODE_STRING valName; + ULONG size = 0; + ULONG resultSize; + + InitializeObjectAttributes (®ObjAttribs, keyPath, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); + status = ZwOpenKey (®KeyHandle, KEY_READ, ®ObjAttribs); + if (!NT_SUCCESS (status)) + return status; + + RtlInitUnicodeString (&valName, keyValueName); + status = ZwQueryValueKey (regKeyHandle, &valName, KeyValuePartialInformation, NULL, 0, &size); + + if (!NT_SUCCESS (status) && status != STATUS_BUFFER_OVERFLOW && status != STATUS_BUFFER_TOO_SMALL) + { + ZwClose (regKeyHandle); + return status; + } + + if (size == 0) + { + ZwClose (regKeyHandle); + return STATUS_NO_DATA_DETECTED; + } + + *keyData = (PKEY_VALUE_PARTIAL_INFORMATION) TCalloc (size); + if (!*keyData) + { + ZwClose (regKeyHandle); + return STATUS_INSUFFICIENT_RESOURCES; + } + + status = ZwQueryValueKey (regKeyHandle, &valName, KeyValuePartialInformation, *keyData, size, &resultSize); + + ZwClose (regKeyHandle); + return status; +} + + +NTSTATUS TCWriteRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, ULONG keyValueType, void *valueData, ULONG valueSize) +{ + OBJECT_ATTRIBUTES regObjAttribs; + HANDLE regKeyHandle; + NTSTATUS status; + UNICODE_STRING valName; + + InitializeObjectAttributes (®ObjAttribs, keyPath, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); + status = ZwOpenKey (®KeyHandle, KEY_READ | KEY_WRITE, ®ObjAttribs); + if (!NT_SUCCESS (status)) + return status; + + RtlInitUnicodeString (&valName, keyValueName); + + status = ZwSetValueKey (regKeyHandle, &valName, 0, keyValueType, valueData, valueSize); + + ZwClose (regKeyHandle); + return status; +} + + +BOOL IsVolumeClassFilterRegistered () +{ + UNICODE_STRING name; + NTSTATUS status; + BOOL registered = FALSE; + + PKEY_VALUE_PARTIAL_INFORMATION data; + + RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{71A27CDD-812A-11D0-BEC7-08002BE2092F}"); + status = TCReadRegistryKey (&name, L"UpperFilters", &data); + + if (NT_SUCCESS (status)) + { + if (data->Type == REG_MULTI_SZ && data->DataLength >= 9 * sizeof (wchar_t)) + { + // Search for the string "veracrypt" + ULONG i; + for (i = 0; i <= data->DataLength - 9 * sizeof (wchar_t); ++i) + { + if (memcmp (data->Data + i, L"veracrypt", 9 * sizeof (wchar_t)) == 0) + { + Dump ("Volume class filter active\n"); + registered = TRUE; + break; + } + } + } + + TCfree (data); + } + + return registered; +} + + +NTSTATUS ReadRegistryConfigFlags (BOOL driverEntry) +{ + PKEY_VALUE_PARTIAL_INFORMATION data; + UNICODE_STRING name; + NTSTATUS status; + uint32 flags = 0; + + RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\veracrypt"); + status = TCReadRegistryKey (&name, TC_DRIVER_CONFIG_REG_VALUE_NAME, &data); + + if (NT_SUCCESS (status)) + { + if (data->Type == REG_DWORD) + { + flags = *(uint32 *) data->Data; + Dump ("Configuration flags = 0x%x\n", flags); + + if (driverEntry) + { + if (flags & (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD | TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES)) + CacheBootPassword = TRUE; + + if (flags & TC_DRIVER_CONFIG_DISABLE_NONADMIN_SYS_FAVORITES_ACCESS) + NonAdminSystemFavoritesAccessDisabled = TRUE; + + if (flags & TC_DRIVER_CONFIG_CACHE_BOOT_PIM) + CacheBootPim = TRUE; + } + + EnableHwEncryption ((flags & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? FALSE : TRUE); + + EnableExtendedIoctlSupport = (flags & TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL)? TRUE : FALSE; + } + else + status = STATUS_INVALID_PARAMETER; + + TCfree (data); + } + + if (driverEntry && NT_SUCCESS (TCReadRegistryKey (&name, TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME, &data))) + { + if (data->Type == REG_DWORD) + EncryptionThreadPoolFreeCpuCountLimit = *(uint32 *) data->Data; + + TCfree (data); + } + + return status; +} + + +NTSTATUS WriteRegistryConfigFlags (uint32 flags) +{ + UNICODE_STRING name; + RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Services\\veracrypt"); + + return TCWriteRegistryKey (&name, TC_DRIVER_CONFIG_REG_VALUE_NAME, REG_DWORD, &flags, sizeof (flags)); +} + + +NTSTATUS GetDeviceSectorSize (PDEVICE_OBJECT deviceObject, ULONG *bytesPerSector) +{ + NTSTATUS status; + DISK_GEOMETRY geometry; + + status = SendDeviceIoControlRequest (deviceObject, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &geometry, sizeof (geometry)); + + if (!NT_SUCCESS (status)) + return status; + + *bytesPerSector = geometry.BytesPerSector; + return STATUS_SUCCESS; +} + + +NTSTATUS ZeroUnreadableSectors (PDEVICE_OBJECT deviceObject, LARGE_INTEGER startOffset, ULONG size, uint64 *zeroedSectorCount) +{ + NTSTATUS status; + ULONG sectorSize; + ULONG sectorCount; + byte *sectorBuffer = NULL; + + *zeroedSectorCount = 0; + + status = GetDeviceSectorSize (deviceObject, §orSize); + if (!NT_SUCCESS (status)) + return status; + + sectorBuffer = TCalloc (sectorSize); + if (!sectorBuffer) + return STATUS_INSUFFICIENT_RESOURCES; + + for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount, startOffset.QuadPart += sectorSize) + { + status = TCReadDevice (deviceObject, sectorBuffer, startOffset, sectorSize); + if (!NT_SUCCESS (status)) + { + Dump ("Zeroing sector at %I64d\n", startOffset.QuadPart); + memset (sectorBuffer, 0, sectorSize); + + status = TCWriteDevice (deviceObject, sectorBuffer, startOffset, sectorSize); + if (!NT_SUCCESS (status)) + goto err; + + ++(*zeroedSectorCount); + } + } + + status = STATUS_SUCCESS; + +err: + if (sectorBuffer) + TCfree (sectorBuffer); + + return status; +} + + +NTSTATUS ReadDeviceSkipUnreadableSectors (PDEVICE_OBJECT deviceObject, byte *buffer, LARGE_INTEGER startOffset, ULONG size, uint64 *badSectorCount) +{ + NTSTATUS status; + ULONG sectorSize; + ULONG sectorCount; + + *badSectorCount = 0; + + status = GetDeviceSectorSize (deviceObject, §orSize); + if (!NT_SUCCESS (status)) + return status; + + for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount, startOffset.QuadPart += sectorSize, buffer += sectorSize) + { + status = TCReadDevice (deviceObject, buffer, startOffset, sectorSize); + if (!NT_SUCCESS (status)) + { + Dump ("Skipping bad sector at %I64d\n", startOffset.QuadPart); + memset (buffer, 0, sectorSize); + ++(*badSectorCount); + } + } + + return STATUS_SUCCESS; +} + + +BOOL IsVolumeAccessibleByCurrentUser (PEXTENSION volumeDeviceExtension) +{ + SECURITY_SUBJECT_CONTEXT subContext; + PACCESS_TOKEN accessToken; + PTOKEN_USER tokenUser; + BOOL result = FALSE; + + if (IoIsSystemThread (PsGetCurrentThread()) + || UserCanAccessDriveDevice() + || !volumeDeviceExtension->UserSid + || (volumeDeviceExtension->SystemFavorite && !NonAdminSystemFavoritesAccessDisabled)) + { + return TRUE; + } + + SeCaptureSubjectContext (&subContext); + SeLockSubjectContext(&subContext); + if (subContext.ClientToken && subContext.ImpersonationLevel >= SecurityImpersonation) + accessToken = subContext.ClientToken; + else + accessToken = subContext.PrimaryToken; + + if (!accessToken) + goto ret; + + if (SeTokenIsAdmin (accessToken)) + { + result = TRUE; + goto ret; + } + + if (!NT_SUCCESS (SeQueryInformationToken (accessToken, TokenUser, &tokenUser))) + goto ret; + + result = RtlEqualSid (volumeDeviceExtension->UserSid, tokenUser->User.Sid); + ExFreePool (tokenUser); // Documented in newer versions of WDK + +ret: + SeUnlockSubjectContext(&subContext); + SeReleaseSubjectContext (&subContext); + return result; +} + + +void GetElapsedTimeInit (LARGE_INTEGER *lastPerfCounter) +{ + *lastPerfCounter = KeQueryPerformanceCounter (NULL); +} + + +// Returns elapsed time in microseconds since last call +int64 GetElapsedTime (LARGE_INTEGER *lastPerfCounter) +{ + LARGE_INTEGER freq; + LARGE_INTEGER counter = KeQueryPerformanceCounter (&freq); + + int64 elapsed = (counter.QuadPart - lastPerfCounter->QuadPart) * 1000000LL / freq.QuadPart; + *lastPerfCounter = counter; + + return elapsed; +} + + +BOOL IsOSAtLeast (OSVersionEnum reqMinOS) +{ + /* When updating this function, update IsOSVersionAtLeast() in Dlgcode.c too. */ + + ULONG major = 0, minor = 0; + + ASSERT (OsMajorVersion != 0); + + switch (reqMinOS) + { + case WIN_2000: major = 5; minor = 0; break; + case WIN_XP: major = 5; minor = 1; break; + case WIN_SERVER_2003: major = 5; minor = 2; break; + case WIN_VISTA: major = 6; minor = 0; break; + case WIN_7: major = 6; minor = 1; break; + case WIN_8: major = 6; minor = 2; break; + case WIN_8_1: major = 6; minor = 3; break; + case WIN_10: major = 10; minor = 0; break; + + default: + TC_THROW_FATAL_EXCEPTION; + break; + } + + return ((OsMajorVersion << 16 | OsMinorVersion << 8) + >= (major << 16 | minor << 8)); +} diff --git a/src/Driver/Ntdriver.h b/src/Driver/Ntdriver.h index 59634760..d5d548e8 100644 --- a/src/Driver/Ntdriver.h +++ b/src/Driver/Ntdriver.h @@ -1,189 +1,189 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifndef TC_HEADER_NTDRIVER -#define TC_HEADER_NTDRIVER - -#include "Common.h" -#include "EncryptedIoQueue.h" - -/* This structure is used to start new threads */ -typedef struct _THREAD_BLOCK_ -{ - PDEVICE_OBJECT DeviceObject; - NTSTATUS ntCreateStatus; - WCHAR wszMountVolume[TC_MAX_PATH + 8]; - MOUNT_STRUCT *mount; -} THREAD_BLOCK, *PTHREAD_BLOCK; - - -/* This structure is allocated for non-root devices! WARNING: bRootDevice - must be the first member of the structure! */ -typedef struct EXTENSION -{ - BOOL bRootDevice; /* Is this the root device ? which the user-mode apps talk to */ - BOOL IsVolumeDevice; - BOOL IsDriveFilterDevice; - BOOL IsVolumeFilterDevice; - - int UniqueVolumeId; - int nDosDriveNo; /* Drive number this extension is mounted against */ - - BOOL bShuttingDown; /* Is the driver shutting down ? */ - BOOL bThreadShouldQuit; /* Instruct per device worker thread to quit */ - PETHREAD peThread; /* Thread handle */ - KEVENT keCreateEvent; /* Device creation event */ - KSPIN_LOCK ListSpinLock; /* IRP spinlock */ - LIST_ENTRY ListEntry; /* IRP listentry */ - KSEMAPHORE RequestSemaphore; /* IRP list request Semaphore */ - - HANDLE hDeviceFile; /* Device handle for this device */ - PFILE_OBJECT pfoDeviceFile; /* Device fileobject for this device */ - PDEVICE_OBJECT pFsdDevice; /* lower level device handle */ - - CRYPTO_INFO *cryptoInfo; /* Cryptographic and other information for this device */ - - __int64 HostLength; - __int64 DiskLength; /* The length of the disk referred to by this device */ - __int64 NumberOfCylinders; /* Partition info */ - ULONG TracksPerCylinder; /* Partition info */ - ULONG SectorsPerTrack; /* Partition info */ - ULONG BytesPerSector; /* Partition info */ - UCHAR PartitionType; /* Partition info */ - - uint32 HostBytesPerSector; - uint32 HostBytesPerPhysicalSector; - ULONG BytesOffsetForSectorAlignment; - - KEVENT keVolumeEvent; /* Event structure used when setting up a device */ - - EncryptedIoQueue Queue; - - BOOL bReadOnly; /* Is this device read-only ? */ - BOOL bRemovable; /* Is this device removable media ? */ - BOOL PartitionInInactiveSysEncScope; - BOOL bRawDevice; /* Is this a raw-partition or raw-floppy device ? */ - BOOL bMountManager; /* Mount manager knows about volume */ - BOOL SystemFavorite; - - WCHAR wszVolume[TC_MAX_PATH]; /* DONT change this size without also changing MOUNT_LIST_STRUCT! */ - WCHAR wszLabel[33]; - BOOL bIsNTFS; - BOOL bDriverSetLabel; - - unsigned char volumeID[VOLUME_ID_SIZE]; - - LARGE_INTEGER fileCreationTime; - LARGE_INTEGER fileLastAccessTime; - LARGE_INTEGER fileLastWriteTime; - LARGE_INTEGER fileLastChangeTime; - BOOL bTimeStampValid; - - PSID UserSid; - BOOL SecurityClientContextValid; - SECURITY_CLIENT_CONTEXT SecurityClientContext; - -} EXTENSION, *PEXTENSION; - - -typedef enum -{ - ValidateInput, - ValidateOutput, - ValidateInputOutput -} ValidateIOBufferSizeType; - -typedef enum -{ - DeviceNamespaceDefault, - DeviceNamespaceGlobal, -} DeviceNamespaceType; - -extern PDRIVER_OBJECT TCDriverObject; -extern PDEVICE_OBJECT RootDeviceObject; -extern BOOL DriverShuttingDown; -extern ULONG OsMajorVersion; -extern ULONG OsMinorVersion; -extern BOOL VolumeClassFilterRegistered; -extern BOOL CacheBootPassword; -extern BOOL CacheBootPim; - -/* Helper macro returning x seconds in units of 100 nanoseconds */ -#define WAIT_SECONDS(x) ((x)*10000000) - -NTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath); -NTSTATUS DriverAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo); -void DumpMemory (void *memory, int size); -BOOL IsAccessibleByUser (PUNICODE_STRING objectFileName, BOOL readOnly); -NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp); -NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp); -NTSTATUS SendDeviceIoControlRequest (PDEVICE_OBJECT deviceObject, ULONG ioControlCode, void *inputBuffer, int inputBufferSize, void *outputBuffer, int outputBufferSize); -NTSTATUS TCDispatchQueueIRP (PDEVICE_OBJECT DeviceObject, PIRP Irp); -NTSTATUS TCCreateRootDeviceObject (PDRIVER_OBJECT DriverObject); -NTSTATUS TCCreateDeviceObject (PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT * ppDeviceObject, MOUNT_STRUCT * mount); -NTSTATUS TCReadDevice (PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length); -NTSTATUS TCWriteDevice (PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length); -NTSTATUS TCStartThread (PKSTART_ROUTINE threadProc, PVOID threadArg, PKTHREAD *kThread); -NTSTATUS TCStartThreadInProcess (PKSTART_ROUTINE threadProc, PVOID threadArg, PKTHREAD *kThread, PEPROCESS process); -NTSTATUS TCStartVolumeThread (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, MOUNT_STRUCT * mount); -void TCStopThread (PKTHREAD kThread, PKEVENT wakeUpEvent); -void TCStopVolumeThread (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension); -VOID VolumeThreadProc (PVOID Context); -void TCSleep (int milliSeconds); -void TCGetNTNameFromNumber (LPWSTR ntname, int cbNtName, int nDriveNo); -void TCGetDosNameFromNumber (LPWSTR dosname, int cbDosName, int nDriveNo, DeviceNamespaceType namespaceType); -LPWSTR TCTranslateCode (ULONG ulCode); -void TCDeleteDeviceObject (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension); -VOID TCUnloadDriver (PDRIVER_OBJECT DriverObject); -void OnShutdownPending (); -NTSTATUS TCDeviceIoControl (PWSTR deviceName, ULONG IoControlCode, void *InputBuffer, ULONG InputBufferSize, void *OutputBuffer, ULONG OutputBufferSize); -NTSTATUS TCOpenFsVolume (PEXTENSION Extension, PHANDLE volumeHandle, PFILE_OBJECT * fileObject); -void TCCloseFsVolume (HANDLE volumeHandle, PFILE_OBJECT fileObject); -NTSTATUS TCFsctlCall (PFILE_OBJECT fileObject, LONG IoControlCode, void *InputBuffer, int InputBufferSize, void *OutputBuffer, int OutputBufferSize); -NTSTATUS CreateDriveLink (int nDosDriveNo); -NTSTATUS RemoveDriveLink (int nDosDriveNo); -NTSTATUS MountManagerMount (MOUNT_STRUCT *mount); -NTSTATUS MountManagerUnmount (int nDosDriveNo); -NTSTATUS MountDevice (PDEVICE_OBJECT deviceObject, MOUNT_STRUCT *mount); -NTSTATUS UnmountDevice (UNMOUNT_STRUCT *unmountRequest, PDEVICE_OBJECT deviceObject, BOOL ignoreOpenFiles); -NTSTATUS UnmountAllDevices (UNMOUNT_STRUCT *unmountRequest, BOOL ignoreOpenFiles); -NTSTATUS SymbolicLinkToTarget (PWSTR symlinkName, PWSTR targetName, USHORT maxTargetNameLength); -BOOL RootDeviceControlMutexAcquireNoWait (); -void RootDeviceControlMutexRelease (); -BOOL RegionsOverlap (unsigned __int64 start1, unsigned __int64 end1, unsigned __int64 start2, unsigned __int64 end2); -void GetIntersection (uint64 start1, uint32 length1, uint64 start2, uint64 end2, uint64 *intersectStart, uint32 *intersectLength); -NTSTATUS TCCompleteIrp (PIRP irp, NTSTATUS status, ULONG_PTR information); -NTSTATUS TCCompleteDiskIrp (PIRP irp, NTSTATUS status, ULONG_PTR information); -NTSTATUS ProbeRealDriveSize (PDEVICE_OBJECT driveDeviceObject, LARGE_INTEGER *driveSize); -BOOL UserCanAccessDriveDevice (); -size_t GetCpuCount (); -void EnsureNullTerminatedString (wchar_t *str, size_t maxSizeInBytes); -void *AllocateMemoryWithTimeout (size_t size, int retryDelay, int timeout); -BOOL IsDriveLetterAvailable (int nDosDriveNo, DeviceNamespaceType namespaceType); -NTSTATUS TCReadRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, PKEY_VALUE_PARTIAL_INFORMATION *keyData); -NTSTATUS TCWriteRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, ULONG keyValueType, void *valueData, ULONG valueSize); -BOOL IsVolumeClassFilterRegistered (); -NTSTATUS ReadRegistryConfigFlags (BOOL driverEntry); -NTSTATUS WriteRegistryConfigFlags (uint32 flags); -BOOL ValidateIOBufferSize (PIRP irp, size_t requiredBufferSize, ValidateIOBufferSizeType type); -NTSTATUS GetDeviceSectorSize (PDEVICE_OBJECT deviceObject, ULONG *bytesPerSector); -NTSTATUS ZeroUnreadableSectors (PDEVICE_OBJECT deviceObject, LARGE_INTEGER startOffset, ULONG size, uint64 *zeroedSectorCount); -NTSTATUS ReadDeviceSkipUnreadableSectors (PDEVICE_OBJECT deviceObject, byte *buffer, LARGE_INTEGER startOffset, ULONG size, uint64 *badSectorCount); -BOOL IsVolumeAccessibleByCurrentUser (PEXTENSION volumeDeviceExtension); -void GetElapsedTimeInit (LARGE_INTEGER *lastPerfCounter); -int64 GetElapsedTime (LARGE_INTEGER *lastPerfCounter); -BOOL IsOSAtLeast (OSVersionEnum reqMinOS); - -#define TC_BUG_CHECK(status) KeBugCheckEx (SECURITY_SYSTEM, __LINE__, (ULONG_PTR) status, 0, 'VC') - -#endif // TC_HEADER_NTDRIVER +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifndef TC_HEADER_NTDRIVER +#define TC_HEADER_NTDRIVER + +#include "Common.h" +#include "EncryptedIoQueue.h" + +/* This structure is used to start new threads */ +typedef struct _THREAD_BLOCK_ +{ + PDEVICE_OBJECT DeviceObject; + NTSTATUS ntCreateStatus; + WCHAR wszMountVolume[TC_MAX_PATH + 8]; + MOUNT_STRUCT *mount; +} THREAD_BLOCK, *PTHREAD_BLOCK; + + +/* This structure is allocated for non-root devices! WARNING: bRootDevice + must be the first member of the structure! */ +typedef struct EXTENSION +{ + BOOL bRootDevice; /* Is this the root device ? which the user-mode apps talk to */ + BOOL IsVolumeDevice; + BOOL IsDriveFilterDevice; + BOOL IsVolumeFilterDevice; + + int UniqueVolumeId; + int nDosDriveNo; /* Drive number this extension is mounted against */ + + BOOL bShuttingDown; /* Is the driver shutting down ? */ + BOOL bThreadShouldQuit; /* Instruct per device worker thread to quit */ + PETHREAD peThread; /* Thread handle */ + KEVENT keCreateEvent; /* Device creation event */ + KSPIN_LOCK ListSpinLock; /* IRP spinlock */ + LIST_ENTRY ListEntry; /* IRP listentry */ + KSEMAPHORE RequestSemaphore; /* IRP list request Semaphore */ + + HANDLE hDeviceFile; /* Device handle for this device */ + PFILE_OBJECT pfoDeviceFile; /* Device fileobject for this device */ + PDEVICE_OBJECT pFsdDevice; /* lower level device handle */ + + CRYPTO_INFO *cryptoInfo; /* Cryptographic and other information for this device */ + + __int64 HostLength; + __int64 DiskLength; /* The length of the disk referred to by this device */ + __int64 NumberOfCylinders; /* Partition info */ + ULONG TracksPerCylinder; /* Partition info */ + ULONG SectorsPerTrack; /* Partition info */ + ULONG BytesPerSector; /* Partition info */ + UCHAR PartitionType; /* Partition info */ + + uint32 HostBytesPerSector; + uint32 HostBytesPerPhysicalSector; + ULONG BytesOffsetForSectorAlignment; + + KEVENT keVolumeEvent; /* Event structure used when setting up a device */ + + EncryptedIoQueue Queue; + + BOOL bReadOnly; /* Is this device read-only ? */ + BOOL bRemovable; /* Is this device removable media ? */ + BOOL PartitionInInactiveSysEncScope; + BOOL bRawDevice; /* Is this a raw-partition or raw-floppy device ? */ + BOOL bMountManager; /* Mount manager knows about volume */ + BOOL SystemFavorite; + + WCHAR wszVolume[TC_MAX_PATH]; /* DONT change this size without also changing MOUNT_LIST_STRUCT! */ + WCHAR wszLabel[33]; + BOOL bIsNTFS; + BOOL bDriverSetLabel; + + unsigned char volumeID[VOLUME_ID_SIZE]; + + LARGE_INTEGER fileCreationTime; + LARGE_INTEGER fileLastAccessTime; + LARGE_INTEGER fileLastWriteTime; + LARGE_INTEGER fileLastChangeTime; + BOOL bTimeStampValid; + + PSID UserSid; + BOOL SecurityClientContextValid; + SECURITY_CLIENT_CONTEXT SecurityClientContext; + +} EXTENSION, *PEXTENSION; + + +typedef enum +{ + ValidateInput, + ValidateOutput, + ValidateInputOutput +} ValidateIOBufferSizeType; + +typedef enum +{ + DeviceNamespaceDefault, + DeviceNamespaceGlobal, +} DeviceNamespaceType; + +extern PDRIVER_OBJECT TCDriverObject; +extern PDEVICE_OBJECT RootDeviceObject; +extern BOOL DriverShuttingDown; +extern ULONG OsMajorVersion; +extern ULONG OsMinorVersion; +extern BOOL VolumeClassFilterRegistered; +extern BOOL CacheBootPassword; +extern BOOL CacheBootPim; + +/* Helper macro returning x seconds in units of 100 nanoseconds */ +#define WAIT_SECONDS(x) ((x)*10000000) + +NTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath); +NTSTATUS DriverAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo); +void DumpMemory (void *memory, int size); +BOOL IsAccessibleByUser (PUNICODE_STRING objectFileName, BOOL readOnly); +NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp); +NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp); +NTSTATUS SendDeviceIoControlRequest (PDEVICE_OBJECT deviceObject, ULONG ioControlCode, void *inputBuffer, int inputBufferSize, void *outputBuffer, int outputBufferSize); +NTSTATUS TCDispatchQueueIRP (PDEVICE_OBJECT DeviceObject, PIRP Irp); +NTSTATUS TCCreateRootDeviceObject (PDRIVER_OBJECT DriverObject); +NTSTATUS TCCreateDeviceObject (PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT * ppDeviceObject, MOUNT_STRUCT * mount); +NTSTATUS TCReadDevice (PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length); +NTSTATUS TCWriteDevice (PDEVICE_OBJECT deviceObject, PVOID buffer, LARGE_INTEGER offset, ULONG length); +NTSTATUS TCStartThread (PKSTART_ROUTINE threadProc, PVOID threadArg, PKTHREAD *kThread); +NTSTATUS TCStartThreadInProcess (PKSTART_ROUTINE threadProc, PVOID threadArg, PKTHREAD *kThread, PEPROCESS process); +NTSTATUS TCStartVolumeThread (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, MOUNT_STRUCT * mount); +void TCStopThread (PKTHREAD kThread, PKEVENT wakeUpEvent); +void TCStopVolumeThread (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension); +VOID VolumeThreadProc (PVOID Context); +void TCSleep (int milliSeconds); +void TCGetNTNameFromNumber (LPWSTR ntname, int cbNtName, int nDriveNo); +void TCGetDosNameFromNumber (LPWSTR dosname, int cbDosName, int nDriveNo, DeviceNamespaceType namespaceType); +LPWSTR TCTranslateCode (ULONG ulCode); +void TCDeleteDeviceObject (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension); +VOID TCUnloadDriver (PDRIVER_OBJECT DriverObject); +void OnShutdownPending (); +NTSTATUS TCDeviceIoControl (PWSTR deviceName, ULONG IoControlCode, void *InputBuffer, ULONG InputBufferSize, void *OutputBuffer, ULONG OutputBufferSize); +NTSTATUS TCOpenFsVolume (PEXTENSION Extension, PHANDLE volumeHandle, PFILE_OBJECT * fileObject); +void TCCloseFsVolume (HANDLE volumeHandle, PFILE_OBJECT fileObject); +NTSTATUS TCFsctlCall (PFILE_OBJECT fileObject, LONG IoControlCode, void *InputBuffer, int InputBufferSize, void *OutputBuffer, int OutputBufferSize); +NTSTATUS CreateDriveLink (int nDosDriveNo); +NTSTATUS RemoveDriveLink (int nDosDriveNo); +NTSTATUS MountManagerMount (MOUNT_STRUCT *mount); +NTSTATUS MountManagerUnmount (int nDosDriveNo); +NTSTATUS MountDevice (PDEVICE_OBJECT deviceObject, MOUNT_STRUCT *mount); +NTSTATUS UnmountDevice (UNMOUNT_STRUCT *unmountRequest, PDEVICE_OBJECT deviceObject, BOOL ignoreOpenFiles); +NTSTATUS UnmountAllDevices (UNMOUNT_STRUCT *unmountRequest, BOOL ignoreOpenFiles); +NTSTATUS SymbolicLinkToTarget (PWSTR symlinkName, PWSTR targetName, USHORT maxTargetNameLength); +BOOL RootDeviceControlMutexAcquireNoWait (); +void RootDeviceControlMutexRelease (); +BOOL RegionsOverlap (unsigned __int64 start1, unsigned __int64 end1, unsigned __int64 start2, unsigned __int64 end2); +void GetIntersection (uint64 start1, uint32 length1, uint64 start2, uint64 end2, uint64 *intersectStart, uint32 *intersectLength); +NTSTATUS TCCompleteIrp (PIRP irp, NTSTATUS status, ULONG_PTR information); +NTSTATUS TCCompleteDiskIrp (PIRP irp, NTSTATUS status, ULONG_PTR information); +NTSTATUS ProbeRealDriveSize (PDEVICE_OBJECT driveDeviceObject, LARGE_INTEGER *driveSize); +BOOL UserCanAccessDriveDevice (); +size_t GetCpuCount (); +void EnsureNullTerminatedString (wchar_t *str, size_t maxSizeInBytes); +void *AllocateMemoryWithTimeout (size_t size, int retryDelay, int timeout); +BOOL IsDriveLetterAvailable (int nDosDriveNo, DeviceNamespaceType namespaceType); +NTSTATUS TCReadRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, PKEY_VALUE_PARTIAL_INFORMATION *keyData); +NTSTATUS TCWriteRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, ULONG keyValueType, void *valueData, ULONG valueSize); +BOOL IsVolumeClassFilterRegistered (); +NTSTATUS ReadRegistryConfigFlags (BOOL driverEntry); +NTSTATUS WriteRegistryConfigFlags (uint32 flags); +BOOL ValidateIOBufferSize (PIRP irp, size_t requiredBufferSize, ValidateIOBufferSizeType type); +NTSTATUS GetDeviceSectorSize (PDEVICE_OBJECT deviceObject, ULONG *bytesPerSector); +NTSTATUS ZeroUnreadableSectors (PDEVICE_OBJECT deviceObject, LARGE_INTEGER startOffset, ULONG size, uint64 *zeroedSectorCount); +NTSTATUS ReadDeviceSkipUnreadableSectors (PDEVICE_OBJECT deviceObject, byte *buffer, LARGE_INTEGER startOffset, ULONG size, uint64 *badSectorCount); +BOOL IsVolumeAccessibleByCurrentUser (PEXTENSION volumeDeviceExtension); +void GetElapsedTimeInit (LARGE_INTEGER *lastPerfCounter); +int64 GetElapsedTime (LARGE_INTEGER *lastPerfCounter); +BOOL IsOSAtLeast (OSVersionEnum reqMinOS); + +#define TC_BUG_CHECK(status) KeBugCheckEx (SECURITY_SYSTEM, __LINE__, (ULONG_PTR) status, 0, 'VC') + +#endif // TC_HEADER_NTDRIVER diff --git a/src/Driver/Ntvol.c b/src/Driver/Ntvol.c index 4f35323b..34ee2dbb 100644 --- a/src/Driver/Ntvol.c +++ b/src/Driver/Ntvol.c @@ -1,900 +1,900 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "TCdefs.h" -#include -#include "Crypto.h" -#include "Volumes.h" - -#include "Apidrvr.h" -#include "DriveFilter.h" -#include "Ntdriver.h" -#include "Ntvol.h" -#include "VolumeFilter.h" - -#include "Boot/Windows/BootCommon.h" - -#include "Cache.h" - -#if 0 && _DEBUG -#define EXTRA_INFO 1 -#endif - -#pragma warning( disable : 4127 ) - -#include - -volatile BOOL ProbingHostDeviceForWrite = FALSE; - - -NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, - PEXTENSION Extension, - MOUNT_STRUCT *mount, - PWSTR pwszMountVolume, - BOOL bRawDevice) -{ - FILE_STANDARD_INFORMATION FileStandardInfo; - FILE_BASIC_INFORMATION FileBasicInfo; - OBJECT_ATTRIBUTES oaFileAttributes; - UNICODE_STRING FullFileName; - IO_STATUS_BLOCK IoStatusBlock; - PCRYPTO_INFO cryptoInfoPtr = NULL; - PCRYPTO_INFO tmpCryptoInfo = NULL; - LARGE_INTEGER lDiskLength; - __int64 partitionStartingOffset = 0; - int volumeType; - char *readBuffer = 0; - NTSTATUS ntStatus = 0; - BOOL forceAccessCheck = (!bRawDevice && !(OsMajorVersion == 5 &&OsMinorVersion == 0)); // Windows 2000 does not support OBJ_FORCE_ACCESS_CHECK attribute - BOOL disableBuffering = TRUE; - BOOL exclusiveAccess = mount->bExclusiveAccess; - - Extension->pfoDeviceFile = NULL; - Extension->hDeviceFile = NULL; - Extension->bTimeStampValid = FALSE; - - RtlInitUnicodeString (&FullFileName, pwszMountVolume); - InitializeObjectAttributes (&oaFileAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | (forceAccessCheck ? OBJ_FORCE_ACCESS_CHECK : 0) | OBJ_KERNEL_HANDLE, NULL, NULL); - KeInitializeEvent (&Extension->keVolumeEvent, NotificationEvent, FALSE); - - if (Extension->SecurityClientContextValid) - { - ntStatus = SeImpersonateClientEx (&Extension->SecurityClientContext, NULL); - if (!NT_SUCCESS (ntStatus)) - goto error; - } - - mount->VolumeMountedReadOnlyAfterDeviceWriteProtected = FALSE; - - // If we are opening a device, query its size first - if (bRawDevice) - { - PARTITION_INFORMATION pi; - PARTITION_INFORMATION_EX pix; - LARGE_INTEGER diskLengthInfo; - DISK_GEOMETRY dg; - STORAGE_PROPERTY_QUERY storagePropertyQuery = {0}; - STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR storageDescriptor = {0}; - - ntStatus = IoGetDeviceObjectPointer (&FullFileName, - FILE_READ_DATA | FILE_READ_ATTRIBUTES, - &Extension->pfoDeviceFile, - &Extension->pFsdDevice); - - if (!NT_SUCCESS (ntStatus)) - goto error; - - ntStatus = TCSendHostDeviceIoControlRequest (DeviceObject, Extension, IOCTL_DISK_GET_DRIVE_GEOMETRY, (char *) &dg, sizeof (dg)); - if (!NT_SUCCESS (ntStatus)) - goto error; - - lDiskLength.QuadPart = dg.Cylinders.QuadPart * dg.SectorsPerTrack * dg.TracksPerCylinder * dg.BytesPerSector; - Extension->HostBytesPerSector = dg.BytesPerSector; - - storagePropertyQuery.PropertyId = StorageAccessAlignmentProperty; - storagePropertyQuery.QueryType = PropertyStandardQuery; - - /* IOCTL_STORAGE_QUERY_PROPERTY supported only on Vista and above */ - if (NT_SUCCESS (TCSendHostDeviceIoControlRequestEx (DeviceObject, Extension, IOCTL_STORAGE_QUERY_PROPERTY, - (char*) &storagePropertyQuery, sizeof(storagePropertyQuery), - (char *) &storageDescriptor, sizeof (storageDescriptor)))) - { - Extension->HostBytesPerPhysicalSector = storageDescriptor.BytesPerPhysicalSector; - } - else - { - Extension->HostBytesPerPhysicalSector = dg.BytesPerSector; - } - - // Drive geometry is used only when IOCTL_DISK_GET_PARTITION_INFO fails - if (NT_SUCCESS (TCSendHostDeviceIoControlRequest (DeviceObject, Extension, IOCTL_DISK_GET_PARTITION_INFO_EX, (char *) &pix, sizeof (pix)))) - { - lDiskLength.QuadPart = pix.PartitionLength.QuadPart; - partitionStartingOffset = pix.StartingOffset.QuadPart; - } - // Windows 2000 does not support IOCTL_DISK_GET_PARTITION_INFO_EX - else if (NT_SUCCESS (TCSendHostDeviceIoControlRequest (DeviceObject, Extension, IOCTL_DISK_GET_PARTITION_INFO, (char *) &pi, sizeof (pi)))) - { - lDiskLength.QuadPart = pi.PartitionLength.QuadPart; - partitionStartingOffset = pi.StartingOffset.QuadPart; - } - else if (NT_SUCCESS (TCSendHostDeviceIoControlRequest (DeviceObject, Extension, IOCTL_DISK_GET_LENGTH_INFO, &diskLengthInfo, sizeof (diskLengthInfo)))) - { - lDiskLength = diskLengthInfo; - } - - ProbingHostDeviceForWrite = TRUE; - - if (!mount->bMountReadOnly - && TCSendHostDeviceIoControlRequest (DeviceObject, Extension, - IsHiddenSystemRunning() ? TC_IOCTL_DISK_IS_WRITABLE : IOCTL_DISK_IS_WRITABLE, NULL, 0) == STATUS_MEDIA_WRITE_PROTECTED) - { - mount->bMountReadOnly = TRUE; - DeviceObject->Characteristics |= FILE_READ_ONLY_DEVICE; - mount->VolumeMountedReadOnlyAfterDeviceWriteProtected = TRUE; - } - - ProbingHostDeviceForWrite = FALSE; - - // Some Windows tools (e.g. diskmgmt, diskpart, vssadmin) fail or experience timeouts when there is a raw device - // open for exclusive access. Therefore, exclusive access is used only for file-hosted volumes. - // Applications requiring a consistent device image need to acquire exclusive write access first. This is prevented - // when a device-hosted volume is mounted. - - exclusiveAccess = FALSE; - } - else - { - // Limit the maximum required buffer size - if (mount->BytesPerSector > 128 * BYTES_PER_KB) - { - ntStatus = STATUS_INVALID_PARAMETER; - goto error; - } - - Extension->HostBytesPerSector = mount->BytesPerSector; - Extension->HostBytesPerPhysicalSector = mount->BytesPerPhysicalSector; - - if (Extension->HostBytesPerSector != TC_SECTOR_SIZE_FILE_HOSTED_VOLUME) - disableBuffering = FALSE; - } - - // Open the volume hosting file/device - if (!mount->bMountReadOnly) - { - ntStatus = ZwCreateFile (&Extension->hDeviceFile, - GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, - &oaFileAttributes, - &IoStatusBlock, - NULL, - FILE_ATTRIBUTE_NORMAL | - FILE_ATTRIBUTE_SYSTEM, - exclusiveAccess ? 0 : FILE_SHARE_READ | FILE_SHARE_WRITE, - FILE_OPEN, - FILE_RANDOM_ACCESS | - FILE_WRITE_THROUGH | - (disableBuffering ? FILE_NO_INTERMEDIATE_BUFFERING : 0) | - FILE_SYNCHRONOUS_IO_NONALERT, - NULL, - 0); - } - - /* 26-4-99 NT for some partitions returns this code, it is really a access denied */ - if (ntStatus == 0xc000001b) - ntStatus = STATUS_ACCESS_DENIED; - - mount->VolumeMountedReadOnlyAfterAccessDenied = FALSE; - - if (mount->bMountReadOnly || ntStatus == STATUS_ACCESS_DENIED) - { - ntStatus = ZwCreateFile (&Extension->hDeviceFile, - GENERIC_READ | SYNCHRONIZE, - &oaFileAttributes, - &IoStatusBlock, - NULL, - FILE_ATTRIBUTE_NORMAL | - FILE_ATTRIBUTE_SYSTEM, - exclusiveAccess ? FILE_SHARE_READ : FILE_SHARE_READ | FILE_SHARE_WRITE, - FILE_OPEN, - FILE_RANDOM_ACCESS | - FILE_WRITE_THROUGH | - (disableBuffering ? FILE_NO_INTERMEDIATE_BUFFERING : 0) | - FILE_SYNCHRONOUS_IO_NONALERT, - NULL, - 0); - - if (NT_SUCCESS (ntStatus) && !mount->bMountReadOnly) - mount->VolumeMountedReadOnlyAfterAccessDenied = TRUE; - - Extension->bReadOnly = TRUE; - DeviceObject->Characteristics |= FILE_READ_ONLY_DEVICE; - } - else - Extension->bReadOnly = FALSE; - - /* 26-4-99 NT for some partitions returns this code, it is really a - access denied */ - if (ntStatus == 0xc000001b) - { - /* Partitions which return this code can still be opened with - FILE_SHARE_READ but this causes NT problems elsewhere in - particular if you do FILE_SHARE_READ NT will die later if - anyone even tries to open the partition (or file for that - matter...) */ - ntStatus = STATUS_SHARING_VIOLATION; - } - - if (!NT_SUCCESS (ntStatus)) - { - goto error; - } - - // If we have opened a file, query its size now - if (bRawDevice == FALSE) - { - ntStatus = ZwQueryInformationFile (Extension->hDeviceFile, - &IoStatusBlock, - &FileBasicInfo, - sizeof (FileBasicInfo), - FileBasicInformation); - - if (NT_SUCCESS (ntStatus)) - { - if (mount->bPreserveTimestamp) - { - Extension->fileCreationTime = FileBasicInfo.CreationTime; - Extension->fileLastAccessTime = FileBasicInfo.LastAccessTime; - Extension->fileLastWriteTime = FileBasicInfo.LastWriteTime; - Extension->fileLastChangeTime = FileBasicInfo.ChangeTime; - Extension->bTimeStampValid = TRUE; - } - - ntStatus = ZwQueryInformationFile (Extension->hDeviceFile, - &IoStatusBlock, - &FileStandardInfo, - sizeof (FileStandardInfo), - FileStandardInformation); - } - - if (!NT_SUCCESS (ntStatus)) - { - Dump ("ZwQueryInformationFile failed while opening file: NTSTATUS 0x%08x\n", - ntStatus); - goto error; - } - - lDiskLength.QuadPart = FileStandardInfo.EndOfFile.QuadPart; - - if (FileBasicInfo.FileAttributes & FILE_ATTRIBUTE_COMPRESSED) - { - Dump ("File \"%ls\" is marked as compressed - not supported!\n", pwszMountVolume); - mount->nReturnCode = ERR_COMPRESSION_NOT_SUPPORTED; - ntStatus = STATUS_SUCCESS; - goto error; - } - - ntStatus = ObReferenceObjectByHandle (Extension->hDeviceFile, - FILE_ALL_ACCESS, - *IoFileObjectType, - KernelMode, - &Extension->pfoDeviceFile, - 0); - - if (!NT_SUCCESS (ntStatus)) - { - goto error; - } - - /* Get the FSD device for the file (probably either NTFS or FAT) */ - Extension->pFsdDevice = IoGetRelatedDeviceObject (Extension->pfoDeviceFile); - } - else - { - // Try to gain "raw" access to the partition in case there is a live filesystem on it (otherwise, - // the NTFS driver guards hidden sectors and prevents mounting using a backup header e.g. after the user - // accidentally quick-formats a dismounted partition-hosted TrueCrypt volume as NTFS). - - PFILE_OBJECT pfoTmpDeviceFile = NULL; - - if (NT_SUCCESS (ObReferenceObjectByHandle (Extension->hDeviceFile, FILE_ALL_ACCESS, *IoFileObjectType, KernelMode, &pfoTmpDeviceFile, NULL)) - && pfoTmpDeviceFile != NULL) - { - TCFsctlCall (pfoTmpDeviceFile, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, 0, NULL, 0); - ObDereferenceObject (pfoTmpDeviceFile); - } - } - - // Check volume size - if (lDiskLength.QuadPart < TC_MIN_VOLUME_SIZE_LEGACY || lDiskLength.QuadPart > TC_MAX_VOLUME_SIZE) - { - mount->nReturnCode = ERR_VOL_SIZE_WRONG; - ntStatus = STATUS_SUCCESS; - goto error; - } - - Extension->DiskLength = lDiskLength.QuadPart; - Extension->HostLength = lDiskLength.QuadPart; - - readBuffer = TCalloc (max (max (TC_VOLUME_HEADER_EFFECTIVE_SIZE, PAGE_SIZE), Extension->HostBytesPerSector)); - if (readBuffer == NULL) - { - ntStatus = STATUS_INSUFFICIENT_RESOURCES; - goto error; - } - - // Go through all volume types (e.g., normal, hidden) - for (volumeType = TC_VOLUME_TYPE_NORMAL; - volumeType < TC_VOLUME_TYPE_COUNT; - volumeType++) - { - Dump ("Trying to open volume type %d\n", volumeType); - - /* Read the volume header */ - - if (!mount->bPartitionInInactiveSysEncScope - || (mount->bPartitionInInactiveSysEncScope && volumeType == TC_VOLUME_TYPE_HIDDEN)) - { - // Header of a volume that is not within the scope of system encryption, or - // header of a system hidden volume (containing a hidden OS) - - LARGE_INTEGER headerOffset; - - if (mount->UseBackupHeader && lDiskLength.QuadPart <= TC_TOTAL_VOLUME_HEADERS_SIZE) - continue; - - switch (volumeType) - { - case TC_VOLUME_TYPE_NORMAL: - headerOffset.QuadPart = mount->UseBackupHeader ? lDiskLength.QuadPart - TC_VOLUME_HEADER_GROUP_SIZE : TC_VOLUME_HEADER_OFFSET; - break; - - case TC_VOLUME_TYPE_HIDDEN: - if (lDiskLength.QuadPart <= TC_VOLUME_HEADER_GROUP_SIZE) - continue; - - headerOffset.QuadPart = mount->UseBackupHeader ? lDiskLength.QuadPart - TC_HIDDEN_VOLUME_HEADER_OFFSET : TC_HIDDEN_VOLUME_HEADER_OFFSET; - break; - } - - Dump ("Reading volume header at %I64d\n", headerOffset.QuadPart); - - ntStatus = ZwReadFile (Extension->hDeviceFile, - NULL, - NULL, - NULL, - &IoStatusBlock, - readBuffer, - bRawDevice ? max (TC_VOLUME_HEADER_EFFECTIVE_SIZE, Extension->HostBytesPerSector) : TC_VOLUME_HEADER_EFFECTIVE_SIZE, - &headerOffset, - NULL); - } - else - { - // Header of a partition that is within the scope of system encryption - - WCHAR parentDrivePath [47+1] = {0}; - HANDLE hParentDeviceFile = NULL; - UNICODE_STRING FullParentPath; - OBJECT_ATTRIBUTES oaParentFileAttributes; - LARGE_INTEGER parentKeyDataOffset; - - RtlStringCbPrintfW (parentDrivePath, - sizeof (parentDrivePath), - WIDE ("\\Device\\Harddisk%d\\Partition0"), - mount->nPartitionInInactiveSysEncScopeDriveNo); - - Dump ("Mounting partition within scope of system encryption (reading key data from: %ls)\n", parentDrivePath); - - RtlInitUnicodeString (&FullParentPath, parentDrivePath); - InitializeObjectAttributes (&oaParentFileAttributes, &FullParentPath, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); - - ntStatus = ZwCreateFile (&hParentDeviceFile, - GENERIC_READ | SYNCHRONIZE, - &oaParentFileAttributes, - &IoStatusBlock, - NULL, - FILE_ATTRIBUTE_NORMAL | - FILE_ATTRIBUTE_SYSTEM, - FILE_SHARE_READ | FILE_SHARE_WRITE, - FILE_OPEN, - FILE_RANDOM_ACCESS | - FILE_WRITE_THROUGH | - FILE_NO_INTERMEDIATE_BUFFERING | - FILE_SYNCHRONOUS_IO_NONALERT, - NULL, - 0); - - if (!NT_SUCCESS (ntStatus)) - { - if (hParentDeviceFile != NULL) - ZwClose (hParentDeviceFile); - - Dump ("Cannot open %ls\n", parentDrivePath); - - goto error; - } - - parentKeyDataOffset.QuadPart = TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET; - - ntStatus = ZwReadFile (hParentDeviceFile, - NULL, - NULL, - NULL, - &IoStatusBlock, - readBuffer, - max (TC_VOLUME_HEADER_EFFECTIVE_SIZE, Extension->HostBytesPerSector), - &parentKeyDataOffset, - NULL); - - if (hParentDeviceFile != NULL) - ZwClose (hParentDeviceFile); - } - - if (!NT_SUCCESS (ntStatus) && ntStatus != STATUS_END_OF_FILE) - { - Dump ("Read failed: NTSTATUS 0x%08x\n", ntStatus); - goto error; - } - - if (ntStatus == STATUS_END_OF_FILE || IoStatusBlock.Information < TC_VOLUME_HEADER_EFFECTIVE_SIZE) - { - Dump ("Read didn't read enough data\n"); - - // If FSCTL_ALLOW_EXTENDED_DASD_IO failed and there is a live filesystem on the partition, then the - // filesystem driver may report EOF when we are reading hidden sectors (when the filesystem is - // shorter than the partition). This can happen for example after the user quick-formats a dismounted - // partition-hosted TrueCrypt volume and then tries to mount the volume using the embedded backup header. - memset (readBuffer, 0, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - } - - /* Attempt to recognize the volume (decrypt the header) */ - - ReadVolumeHeaderRecoveryMode = mount->RecoveryMode; - - if ((volumeType == TC_VOLUME_TYPE_HIDDEN) && mount->bProtectHiddenVolume) - { - mount->nReturnCode = ReadVolumeHeaderWCache ( - FALSE, - mount->bCache, - mount->bCachePim, - readBuffer, - &mount->ProtectedHidVolPassword, - mount->ProtectedHidVolPkcs5Prf, - mount->ProtectedHidVolPim, - mount->bTrueCryptMode, - &tmpCryptoInfo); - } - else - { - mount->nReturnCode = ReadVolumeHeaderWCache ( - mount->bPartitionInInactiveSysEncScope && volumeType == TC_VOLUME_TYPE_NORMAL, - mount->bCache, - mount->bCachePim, - readBuffer, - &mount->VolumePassword, - mount->pkcs5_prf, - mount->VolumePim, - mount->bTrueCryptMode, - &Extension->cryptoInfo); - } - - ReadVolumeHeaderRecoveryMode = FALSE; - - if (mount->nReturnCode == 0 || mount->nReturnCode == ERR_CIPHER_INIT_WEAK_KEY) - { - /* Volume header successfully decrypted */ - - if (!Extension->cryptoInfo) - { - /* should never happen */ - mount->nReturnCode = ERR_OUTOFMEMORY; - ntStatus = STATUS_SUCCESS; - goto error; - } - - Dump ("Volume header decrypted\n"); - Dump ("Required program version = %x\n", (int) Extension->cryptoInfo->RequiredProgramVersion); - Dump ("Legacy volume = %d\n", (int) Extension->cryptoInfo->LegacyVolume); - - if (IsHiddenSystemRunning() && !Extension->cryptoInfo->hiddenVolume) - { - Extension->bReadOnly = mount->bMountReadOnly = TRUE; - HiddenSysLeakProtectionCount++; - } - - Extension->cryptoInfo->bProtectHiddenVolume = FALSE; - Extension->cryptoInfo->bHiddenVolProtectionAction = FALSE; - - Extension->cryptoInfo->bPartitionInInactiveSysEncScope = mount->bPartitionInInactiveSysEncScope; - - /* compute the ID of this volume: SHA-512 of the effective header */ - sha256 (Extension->volumeID, readBuffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - - if (volumeType == TC_VOLUME_TYPE_NORMAL) - { - if (mount->bPartitionInInactiveSysEncScope) - { - if (Extension->cryptoInfo->EncryptedAreaStart.Value > (unsigned __int64) partitionStartingOffset - || Extension->cryptoInfo->EncryptedAreaStart.Value + Extension->cryptoInfo->VolumeSize.Value <= (unsigned __int64) partitionStartingOffset) - { - // The partition is not within the key scope of system encryption - mount->nReturnCode = ERR_PASSWORD_WRONG; - ntStatus = STATUS_SUCCESS; - goto error; - } - - if (Extension->cryptoInfo->EncryptedAreaLength.Value != Extension->cryptoInfo->VolumeSize.Value) - { - // Partial encryption is not supported for volumes mounted as regular - mount->nReturnCode = ERR_ENCRYPTION_NOT_COMPLETED; - ntStatus = STATUS_SUCCESS; - goto error; - } - } - else if (Extension->cryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) - { - if (Extension->cryptoInfo->EncryptedAreaLength.Value != Extension->cryptoInfo->VolumeSize.Value) - { - // Non-system in-place encryption process has not been completed on this volume - mount->nReturnCode = ERR_NONSYS_INPLACE_ENC_INCOMPLETE; - ntStatus = STATUS_SUCCESS; - goto error; - } - } - } - - Extension->cryptoInfo->FirstDataUnitNo.Value = 0; - - if (Extension->cryptoInfo->hiddenVolume && IsHiddenSystemRunning()) - { - // Prevent mount of a hidden system partition if the system hosted on it is currently running - if (memcmp (Extension->cryptoInfo->master_keydata, GetSystemDriveCryptoInfo()->master_keydata, EAGetKeySize (Extension->cryptoInfo->ea)) == 0) - { - mount->nReturnCode = ERR_VOL_ALREADY_MOUNTED; - ntStatus = STATUS_SUCCESS; - goto error; - } - } - - switch (volumeType) - { - case TC_VOLUME_TYPE_NORMAL: - - Extension->cryptoInfo->hiddenVolume = FALSE; - - if (mount->bPartitionInInactiveSysEncScope) - { - Extension->cryptoInfo->volDataAreaOffset = 0; - Extension->DiskLength = lDiskLength.QuadPart; - Extension->cryptoInfo->FirstDataUnitNo.Value = partitionStartingOffset / ENCRYPTION_DATA_UNIT_SIZE; - } - else if (Extension->cryptoInfo->LegacyVolume) - { - Extension->cryptoInfo->volDataAreaOffset = TC_VOLUME_HEADER_SIZE_LEGACY; - Extension->DiskLength = lDiskLength.QuadPart - TC_VOLUME_HEADER_SIZE_LEGACY; - } - else - { - Extension->cryptoInfo->volDataAreaOffset = Extension->cryptoInfo->EncryptedAreaStart.Value; - Extension->DiskLength = Extension->cryptoInfo->VolumeSize.Value; - } - - break; - - case TC_VOLUME_TYPE_HIDDEN: - - cryptoInfoPtr = mount->bProtectHiddenVolume ? tmpCryptoInfo : Extension->cryptoInfo; - - Extension->cryptoInfo->hiddenVolumeOffset = cryptoInfoPtr->EncryptedAreaStart.Value; - - Dump ("Hidden volume offset = %I64d\n", Extension->cryptoInfo->hiddenVolumeOffset); - Dump ("Hidden volume size = %I64d\n", cryptoInfoPtr->hiddenVolumeSize); - Dump ("Hidden volume end = %I64d\n", Extension->cryptoInfo->hiddenVolumeOffset + cryptoInfoPtr->hiddenVolumeSize - 1); - - // Validate the offset - if (Extension->cryptoInfo->hiddenVolumeOffset % ENCRYPTION_DATA_UNIT_SIZE != 0) - { - mount->nReturnCode = ERR_VOL_SIZE_WRONG; - ntStatus = STATUS_SUCCESS; - goto error; - } - - // If we are supposed to actually mount the hidden volume (not just to protect it) - if (!mount->bProtectHiddenVolume) - { - Extension->DiskLength = cryptoInfoPtr->hiddenVolumeSize; - Extension->cryptoInfo->hiddenVolume = TRUE; - Extension->cryptoInfo->volDataAreaOffset = Extension->cryptoInfo->hiddenVolumeOffset; - } - else - { - // Hidden volume protection - Extension->cryptoInfo->hiddenVolume = FALSE; - Extension->cryptoInfo->bProtectHiddenVolume = TRUE; - - Extension->cryptoInfo->hiddenVolumeProtectedSize = tmpCryptoInfo->hiddenVolumeSize; - - Dump ("Hidden volume protection active: %I64d-%I64d (%I64d)\n", Extension->cryptoInfo->hiddenVolumeOffset, Extension->cryptoInfo->hiddenVolumeProtectedSize + Extension->cryptoInfo->hiddenVolumeOffset - 1, Extension->cryptoInfo->hiddenVolumeProtectedSize); - } - - break; - } - - Dump ("Volume data offset = %I64d\n", Extension->cryptoInfo->volDataAreaOffset); - Dump ("Volume data size = %I64d\n", Extension->DiskLength); - Dump ("Volume data end = %I64d\n", Extension->cryptoInfo->volDataAreaOffset + Extension->DiskLength - 1); - - if (Extension->DiskLength == 0) - { - Dump ("Incorrect volume size\n"); - continue; - } - - // If this is a hidden volume, make sure we are supposed to actually - // mount it (i.e. not just to protect it) - if (volumeType == TC_VOLUME_TYPE_NORMAL || !mount->bProtectHiddenVolume) - { - // Validate sector size - if (bRawDevice && Extension->cryptoInfo->SectorSize != Extension->HostBytesPerSector) - { - mount->nReturnCode = ERR_PARAMETER_INCORRECT; - ntStatus = STATUS_SUCCESS; - goto error; - } - - // Calculate virtual volume geometry - Extension->TracksPerCylinder = 1; - Extension->SectorsPerTrack = 1; - Extension->BytesPerSector = Extension->cryptoInfo->SectorSize; - Extension->NumberOfCylinders = Extension->DiskLength / Extension->BytesPerSector; - Extension->PartitionType = 0; - - Extension->bRawDevice = bRawDevice; - - memset (Extension->wszVolume, 0, sizeof (Extension->wszVolume)); - if (wcsstr (pwszMountVolume, WIDE ("\\??\\UNC\\")) == pwszMountVolume) - { - /* UNC path */ - RtlStringCbPrintfW (Extension->wszVolume, - sizeof (Extension->wszVolume), - WIDE ("\\??\\\\%s"), - pwszMountVolume + 7); - } - else - { - RtlStringCbCopyW (Extension->wszVolume, sizeof(Extension->wszVolume),pwszMountVolume); - } - - memset (Extension->wszLabel, 0, sizeof (Extension->wszLabel)); - RtlStringCbCopyW (Extension->wszLabel, sizeof(Extension->wszLabel), mount->wszLabel); - } - - // If we are to protect a hidden volume we cannot exit yet, for we must also - // decrypt the hidden volume header. - if (!(volumeType == TC_VOLUME_TYPE_NORMAL && mount->bProtectHiddenVolume)) - { - TCfree (readBuffer); - - if (tmpCryptoInfo != NULL) - { - crypto_close (tmpCryptoInfo); - tmpCryptoInfo = NULL; - } - - return STATUS_SUCCESS; - } - } - else if ((mount->bProtectHiddenVolume && volumeType == TC_VOLUME_TYPE_NORMAL) - || mount->nReturnCode != ERR_PASSWORD_WRONG) - { - /* If we are not supposed to protect a hidden volume, the only error that is - tolerated is ERR_PASSWORD_WRONG (to allow mounting a possible hidden volume). - - If we _are_ supposed to protect a hidden volume, we do not tolerate any error - (both volume headers must be successfully decrypted). */ - - break; - } - } - - /* Failed due to some non-OS reason so we drop through and return NT - SUCCESS then nReturnCode is checked later in user-mode */ - - if (mount->nReturnCode == ERR_OUTOFMEMORY) - ntStatus = STATUS_INSUFFICIENT_RESOURCES; - else - ntStatus = STATUS_SUCCESS; - -error: - if (mount->nReturnCode == ERR_SUCCESS) - mount->nReturnCode = ERR_PASSWORD_WRONG; - - if (tmpCryptoInfo != NULL) - { - crypto_close (tmpCryptoInfo); - tmpCryptoInfo = NULL; - } - - if (Extension->cryptoInfo) - { - crypto_close (Extension->cryptoInfo); - Extension->cryptoInfo = NULL; - } - - if (Extension->bTimeStampValid) - { - RestoreTimeStamp (Extension); - } - - /* Close the hDeviceFile */ - if (Extension->hDeviceFile != NULL) - ZwClose (Extension->hDeviceFile); - - /* The cryptoInfo pointer is deallocated if the readheader routines - fail so there is no need to deallocate here */ - - /* Dereference the user-mode file object */ - if (Extension->pfoDeviceFile != NULL) - ObDereferenceObject (Extension->pfoDeviceFile); - - /* Free the tmp IO buffers */ - if (readBuffer != NULL) - TCfree (readBuffer); - - return ntStatus; -} - -void TCCloseVolume (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension) -{ - UNREFERENCED_PARAMETER (DeviceObject); /* Remove compiler warning */ - - if (Extension->hDeviceFile != NULL) - { - if (Extension->bRawDevice == FALSE - && Extension->bTimeStampValid) - { - RestoreTimeStamp (Extension); - } - ZwClose (Extension->hDeviceFile); - } - ObDereferenceObject (Extension->pfoDeviceFile); - if (Extension->cryptoInfo) - { - crypto_close (Extension->cryptoInfo); - Extension->cryptoInfo = NULL; - } -} - - -NTSTATUS TCSendHostDeviceIoControlRequestEx (PDEVICE_OBJECT DeviceObject, - PEXTENSION Extension, - ULONG IoControlCode, - void *InputBuffer, - ULONG InputBufferSize, - void *OutputBuffer, - ULONG OutputBufferSize) -{ - IO_STATUS_BLOCK IoStatusBlock; - NTSTATUS ntStatus; - PIRP Irp; - - UNREFERENCED_PARAMETER(DeviceObject); /* Remove compiler warning */ - - KeClearEvent (&Extension->keVolumeEvent); - - Irp = IoBuildDeviceIoControlRequest (IoControlCode, - Extension->pFsdDevice, - InputBuffer, InputBufferSize, - OutputBuffer, OutputBufferSize, - FALSE, - &Extension->keVolumeEvent, - &IoStatusBlock); - - if (Irp == NULL) - { - Dump ("IRP allocation failed\n"); - return STATUS_INSUFFICIENT_RESOURCES; - } - - // Disk device may be used by filesystem driver which needs file object - IoGetNextIrpStackLocation (Irp) -> FileObject = Extension->pfoDeviceFile; - - ntStatus = IoCallDriver (Extension->pFsdDevice, Irp); - if (ntStatus == STATUS_PENDING) - { - KeWaitForSingleObject (&Extension->keVolumeEvent, Executive, KernelMode, FALSE, NULL); - ntStatus = IoStatusBlock.Status; - } - - return ntStatus; -} - -NTSTATUS TCSendHostDeviceIoControlRequest (PDEVICE_OBJECT DeviceObject, - PEXTENSION Extension, - ULONG IoControlCode, - void *OutputBuffer, - ULONG OutputBufferSize) -{ - return TCSendHostDeviceIoControlRequestEx (DeviceObject, Extension, IoControlCode, NULL, 0, OutputBuffer, OutputBufferSize); -} - -NTSTATUS COMPLETE_IRP (PDEVICE_OBJECT DeviceObject, - PIRP Irp, - NTSTATUS IrpStatus, - ULONG_PTR IrpInformation) -{ - Irp->IoStatus.Status = IrpStatus; - Irp->IoStatus.Information = IrpInformation; - - UNREFERENCED_PARAMETER (DeviceObject); /* Remove compiler warning */ - -#if EXTRA_INFO - if (!NT_SUCCESS (IrpStatus)) - { - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); - Dump ("COMPLETE_IRP FAILING IRP %ls Flags 0x%08x vpb 0x%08x NTSTATUS 0x%08x\n", TCTranslateCode (irpSp->MajorFunction), - (ULONG) DeviceObject->Flags, (ULONG) DeviceObject->Vpb->Flags, IrpStatus); - } - else - { - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); - Dump ("COMPLETE_IRP SUCCESS IRP %ls Flags 0x%08x vpb 0x%08x NTSTATUS 0x%08x\n", TCTranslateCode (irpSp->MajorFunction), - (ULONG) DeviceObject->Flags, (ULONG) DeviceObject->Vpb->Flags, IrpStatus); - } -#endif - IoCompleteRequest (Irp, IO_NO_INCREMENT); - return IrpStatus; -} - - -static void RestoreTimeStamp (PEXTENSION Extension) -{ - NTSTATUS ntStatus; - FILE_BASIC_INFORMATION FileBasicInfo; - IO_STATUS_BLOCK IoStatusBlock; - - if (Extension->hDeviceFile != NULL - && Extension->bRawDevice == FALSE - && Extension->bReadOnly == FALSE - && Extension->bTimeStampValid) - { - ntStatus = ZwQueryInformationFile (Extension->hDeviceFile, - &IoStatusBlock, - &FileBasicInfo, - sizeof (FileBasicInfo), - FileBasicInformation); - - if (!NT_SUCCESS (ntStatus)) - { - Dump ("ZwQueryInformationFile failed in RestoreTimeStamp: NTSTATUS 0x%08x\n", - ntStatus); - } - else - { - FileBasicInfo.CreationTime = Extension->fileCreationTime; - FileBasicInfo.LastAccessTime = Extension->fileLastAccessTime; - FileBasicInfo.LastWriteTime = Extension->fileLastWriteTime; - FileBasicInfo.ChangeTime = Extension->fileLastChangeTime; - - ntStatus = ZwSetInformationFile( - Extension->hDeviceFile, - &IoStatusBlock, - &FileBasicInfo, - sizeof (FileBasicInfo), - FileBasicInformation); - - if (!NT_SUCCESS (ntStatus)) - Dump ("ZwSetInformationFile failed in RestoreTimeStamp: NTSTATUS 0x%08x\n",ntStatus); - } - } -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "TCdefs.h" +#include +#include "Crypto.h" +#include "Volumes.h" + +#include "Apidrvr.h" +#include "DriveFilter.h" +#include "Ntdriver.h" +#include "Ntvol.h" +#include "VolumeFilter.h" + +#include "Boot/Windows/BootCommon.h" + +#include "Cache.h" + +#if 0 && _DEBUG +#define EXTRA_INFO 1 +#endif + +#pragma warning( disable : 4127 ) + +#include + +volatile BOOL ProbingHostDeviceForWrite = FALSE; + + +NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, + PEXTENSION Extension, + MOUNT_STRUCT *mount, + PWSTR pwszMountVolume, + BOOL bRawDevice) +{ + FILE_STANDARD_INFORMATION FileStandardInfo; + FILE_BASIC_INFORMATION FileBasicInfo; + OBJECT_ATTRIBUTES oaFileAttributes; + UNICODE_STRING FullFileName; + IO_STATUS_BLOCK IoStatusBlock; + PCRYPTO_INFO cryptoInfoPtr = NULL; + PCRYPTO_INFO tmpCryptoInfo = NULL; + LARGE_INTEGER lDiskLength; + __int64 partitionStartingOffset = 0; + int volumeType; + char *readBuffer = 0; + NTSTATUS ntStatus = 0; + BOOL forceAccessCheck = (!bRawDevice && !(OsMajorVersion == 5 &&OsMinorVersion == 0)); // Windows 2000 does not support OBJ_FORCE_ACCESS_CHECK attribute + BOOL disableBuffering = TRUE; + BOOL exclusiveAccess = mount->bExclusiveAccess; + + Extension->pfoDeviceFile = NULL; + Extension->hDeviceFile = NULL; + Extension->bTimeStampValid = FALSE; + + RtlInitUnicodeString (&FullFileName, pwszMountVolume); + InitializeObjectAttributes (&oaFileAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | (forceAccessCheck ? OBJ_FORCE_ACCESS_CHECK : 0) | OBJ_KERNEL_HANDLE, NULL, NULL); + KeInitializeEvent (&Extension->keVolumeEvent, NotificationEvent, FALSE); + + if (Extension->SecurityClientContextValid) + { + ntStatus = SeImpersonateClientEx (&Extension->SecurityClientContext, NULL); + if (!NT_SUCCESS (ntStatus)) + goto error; + } + + mount->VolumeMountedReadOnlyAfterDeviceWriteProtected = FALSE; + + // If we are opening a device, query its size first + if (bRawDevice) + { + PARTITION_INFORMATION pi; + PARTITION_INFORMATION_EX pix; + LARGE_INTEGER diskLengthInfo; + DISK_GEOMETRY dg; + STORAGE_PROPERTY_QUERY storagePropertyQuery = {0}; + STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR storageDescriptor = {0}; + + ntStatus = IoGetDeviceObjectPointer (&FullFileName, + FILE_READ_DATA | FILE_READ_ATTRIBUTES, + &Extension->pfoDeviceFile, + &Extension->pFsdDevice); + + if (!NT_SUCCESS (ntStatus)) + goto error; + + ntStatus = TCSendHostDeviceIoControlRequest (DeviceObject, Extension, IOCTL_DISK_GET_DRIVE_GEOMETRY, (char *) &dg, sizeof (dg)); + if (!NT_SUCCESS (ntStatus)) + goto error; + + lDiskLength.QuadPart = dg.Cylinders.QuadPart * dg.SectorsPerTrack * dg.TracksPerCylinder * dg.BytesPerSector; + Extension->HostBytesPerSector = dg.BytesPerSector; + + storagePropertyQuery.PropertyId = StorageAccessAlignmentProperty; + storagePropertyQuery.QueryType = PropertyStandardQuery; + + /* IOCTL_STORAGE_QUERY_PROPERTY supported only on Vista and above */ + if (NT_SUCCESS (TCSendHostDeviceIoControlRequestEx (DeviceObject, Extension, IOCTL_STORAGE_QUERY_PROPERTY, + (char*) &storagePropertyQuery, sizeof(storagePropertyQuery), + (char *) &storageDescriptor, sizeof (storageDescriptor)))) + { + Extension->HostBytesPerPhysicalSector = storageDescriptor.BytesPerPhysicalSector; + } + else + { + Extension->HostBytesPerPhysicalSector = dg.BytesPerSector; + } + + // Drive geometry is used only when IOCTL_DISK_GET_PARTITION_INFO fails + if (NT_SUCCESS (TCSendHostDeviceIoControlRequest (DeviceObject, Extension, IOCTL_DISK_GET_PARTITION_INFO_EX, (char *) &pix, sizeof (pix)))) + { + lDiskLength.QuadPart = pix.PartitionLength.QuadPart; + partitionStartingOffset = pix.StartingOffset.QuadPart; + } + // Windows 2000 does not support IOCTL_DISK_GET_PARTITION_INFO_EX + else if (NT_SUCCESS (TCSendHostDeviceIoControlRequest (DeviceObject, Extension, IOCTL_DISK_GET_PARTITION_INFO, (char *) &pi, sizeof (pi)))) + { + lDiskLength.QuadPart = pi.PartitionLength.QuadPart; + partitionStartingOffset = pi.StartingOffset.QuadPart; + } + else if (NT_SUCCESS (TCSendHostDeviceIoControlRequest (DeviceObject, Extension, IOCTL_DISK_GET_LENGTH_INFO, &diskLengthInfo, sizeof (diskLengthInfo)))) + { + lDiskLength = diskLengthInfo; + } + + ProbingHostDeviceForWrite = TRUE; + + if (!mount->bMountReadOnly + && TCSendHostDeviceIoControlRequest (DeviceObject, Extension, + IsHiddenSystemRunning() ? TC_IOCTL_DISK_IS_WRITABLE : IOCTL_DISK_IS_WRITABLE, NULL, 0) == STATUS_MEDIA_WRITE_PROTECTED) + { + mount->bMountReadOnly = TRUE; + DeviceObject->Characteristics |= FILE_READ_ONLY_DEVICE; + mount->VolumeMountedReadOnlyAfterDeviceWriteProtected = TRUE; + } + + ProbingHostDeviceForWrite = FALSE; + + // Some Windows tools (e.g. diskmgmt, diskpart, vssadmin) fail or experience timeouts when there is a raw device + // open for exclusive access. Therefore, exclusive access is used only for file-hosted volumes. + // Applications requiring a consistent device image need to acquire exclusive write access first. This is prevented + // when a device-hosted volume is mounted. + + exclusiveAccess = FALSE; + } + else + { + // Limit the maximum required buffer size + if (mount->BytesPerSector > 128 * BYTES_PER_KB) + { + ntStatus = STATUS_INVALID_PARAMETER; + goto error; + } + + Extension->HostBytesPerSector = mount->BytesPerSector; + Extension->HostBytesPerPhysicalSector = mount->BytesPerPhysicalSector; + + if (Extension->HostBytesPerSector != TC_SECTOR_SIZE_FILE_HOSTED_VOLUME) + disableBuffering = FALSE; + } + + // Open the volume hosting file/device + if (!mount->bMountReadOnly) + { + ntStatus = ZwCreateFile (&Extension->hDeviceFile, + GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, + &oaFileAttributes, + &IoStatusBlock, + NULL, + FILE_ATTRIBUTE_NORMAL | + FILE_ATTRIBUTE_SYSTEM, + exclusiveAccess ? 0 : FILE_SHARE_READ | FILE_SHARE_WRITE, + FILE_OPEN, + FILE_RANDOM_ACCESS | + FILE_WRITE_THROUGH | + (disableBuffering ? FILE_NO_INTERMEDIATE_BUFFERING : 0) | + FILE_SYNCHRONOUS_IO_NONALERT, + NULL, + 0); + } + + /* 26-4-99 NT for some partitions returns this code, it is really a access denied */ + if (ntStatus == 0xc000001b) + ntStatus = STATUS_ACCESS_DENIED; + + mount->VolumeMountedReadOnlyAfterAccessDenied = FALSE; + + if (mount->bMountReadOnly || ntStatus == STATUS_ACCESS_DENIED) + { + ntStatus = ZwCreateFile (&Extension->hDeviceFile, + GENERIC_READ | SYNCHRONIZE, + &oaFileAttributes, + &IoStatusBlock, + NULL, + FILE_ATTRIBUTE_NORMAL | + FILE_ATTRIBUTE_SYSTEM, + exclusiveAccess ? FILE_SHARE_READ : FILE_SHARE_READ | FILE_SHARE_WRITE, + FILE_OPEN, + FILE_RANDOM_ACCESS | + FILE_WRITE_THROUGH | + (disableBuffering ? FILE_NO_INTERMEDIATE_BUFFERING : 0) | + FILE_SYNCHRONOUS_IO_NONALERT, + NULL, + 0); + + if (NT_SUCCESS (ntStatus) && !mount->bMountReadOnly) + mount->VolumeMountedReadOnlyAfterAccessDenied = TRUE; + + Extension->bReadOnly = TRUE; + DeviceObject->Characteristics |= FILE_READ_ONLY_DEVICE; + } + else + Extension->bReadOnly = FALSE; + + /* 26-4-99 NT for some partitions returns this code, it is really a + access denied */ + if (ntStatus == 0xc000001b) + { + /* Partitions which return this code can still be opened with + FILE_SHARE_READ but this causes NT problems elsewhere in + particular if you do FILE_SHARE_READ NT will die later if + anyone even tries to open the partition (or file for that + matter...) */ + ntStatus = STATUS_SHARING_VIOLATION; + } + + if (!NT_SUCCESS (ntStatus)) + { + goto error; + } + + // If we have opened a file, query its size now + if (bRawDevice == FALSE) + { + ntStatus = ZwQueryInformationFile (Extension->hDeviceFile, + &IoStatusBlock, + &FileBasicInfo, + sizeof (FileBasicInfo), + FileBasicInformation); + + if (NT_SUCCESS (ntStatus)) + { + if (mount->bPreserveTimestamp) + { + Extension->fileCreationTime = FileBasicInfo.CreationTime; + Extension->fileLastAccessTime = FileBasicInfo.LastAccessTime; + Extension->fileLastWriteTime = FileBasicInfo.LastWriteTime; + Extension->fileLastChangeTime = FileBasicInfo.ChangeTime; + Extension->bTimeStampValid = TRUE; + } + + ntStatus = ZwQueryInformationFile (Extension->hDeviceFile, + &IoStatusBlock, + &FileStandardInfo, + sizeof (FileStandardInfo), + FileStandardInformation); + } + + if (!NT_SUCCESS (ntStatus)) + { + Dump ("ZwQueryInformationFile failed while opening file: NTSTATUS 0x%08x\n", + ntStatus); + goto error; + } + + lDiskLength.QuadPart = FileStandardInfo.EndOfFile.QuadPart; + + if (FileBasicInfo.FileAttributes & FILE_ATTRIBUTE_COMPRESSED) + { + Dump ("File \"%ls\" is marked as compressed - not supported!\n", pwszMountVolume); + mount->nReturnCode = ERR_COMPRESSION_NOT_SUPPORTED; + ntStatus = STATUS_SUCCESS; + goto error; + } + + ntStatus = ObReferenceObjectByHandle (Extension->hDeviceFile, + FILE_ALL_ACCESS, + *IoFileObjectType, + KernelMode, + &Extension->pfoDeviceFile, + 0); + + if (!NT_SUCCESS (ntStatus)) + { + goto error; + } + + /* Get the FSD device for the file (probably either NTFS or FAT) */ + Extension->pFsdDevice = IoGetRelatedDeviceObject (Extension->pfoDeviceFile); + } + else + { + // Try to gain "raw" access to the partition in case there is a live filesystem on it (otherwise, + // the NTFS driver guards hidden sectors and prevents mounting using a backup header e.g. after the user + // accidentally quick-formats a dismounted partition-hosted TrueCrypt volume as NTFS). + + PFILE_OBJECT pfoTmpDeviceFile = NULL; + + if (NT_SUCCESS (ObReferenceObjectByHandle (Extension->hDeviceFile, FILE_ALL_ACCESS, *IoFileObjectType, KernelMode, &pfoTmpDeviceFile, NULL)) + && pfoTmpDeviceFile != NULL) + { + TCFsctlCall (pfoTmpDeviceFile, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, 0, NULL, 0); + ObDereferenceObject (pfoTmpDeviceFile); + } + } + + // Check volume size + if (lDiskLength.QuadPart < TC_MIN_VOLUME_SIZE_LEGACY || lDiskLength.QuadPart > TC_MAX_VOLUME_SIZE) + { + mount->nReturnCode = ERR_VOL_SIZE_WRONG; + ntStatus = STATUS_SUCCESS; + goto error; + } + + Extension->DiskLength = lDiskLength.QuadPart; + Extension->HostLength = lDiskLength.QuadPart; + + readBuffer = TCalloc (max (max (TC_VOLUME_HEADER_EFFECTIVE_SIZE, PAGE_SIZE), Extension->HostBytesPerSector)); + if (readBuffer == NULL) + { + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + goto error; + } + + // Go through all volume types (e.g., normal, hidden) + for (volumeType = TC_VOLUME_TYPE_NORMAL; + volumeType < TC_VOLUME_TYPE_COUNT; + volumeType++) + { + Dump ("Trying to open volume type %d\n", volumeType); + + /* Read the volume header */ + + if (!mount->bPartitionInInactiveSysEncScope + || (mount->bPartitionInInactiveSysEncScope && volumeType == TC_VOLUME_TYPE_HIDDEN)) + { + // Header of a volume that is not within the scope of system encryption, or + // header of a system hidden volume (containing a hidden OS) + + LARGE_INTEGER headerOffset; + + if (mount->UseBackupHeader && lDiskLength.QuadPart <= TC_TOTAL_VOLUME_HEADERS_SIZE) + continue; + + switch (volumeType) + { + case TC_VOLUME_TYPE_NORMAL: + headerOffset.QuadPart = mount->UseBackupHeader ? lDiskLength.QuadPart - TC_VOLUME_HEADER_GROUP_SIZE : TC_VOLUME_HEADER_OFFSET; + break; + + case TC_VOLUME_TYPE_HIDDEN: + if (lDiskLength.QuadPart <= TC_VOLUME_HEADER_GROUP_SIZE) + continue; + + headerOffset.QuadPart = mount->UseBackupHeader ? lDiskLength.QuadPart - TC_HIDDEN_VOLUME_HEADER_OFFSET : TC_HIDDEN_VOLUME_HEADER_OFFSET; + break; + } + + Dump ("Reading volume header at %I64d\n", headerOffset.QuadPart); + + ntStatus = ZwReadFile (Extension->hDeviceFile, + NULL, + NULL, + NULL, + &IoStatusBlock, + readBuffer, + bRawDevice ? max (TC_VOLUME_HEADER_EFFECTIVE_SIZE, Extension->HostBytesPerSector) : TC_VOLUME_HEADER_EFFECTIVE_SIZE, + &headerOffset, + NULL); + } + else + { + // Header of a partition that is within the scope of system encryption + + WCHAR parentDrivePath [47+1] = {0}; + HANDLE hParentDeviceFile = NULL; + UNICODE_STRING FullParentPath; + OBJECT_ATTRIBUTES oaParentFileAttributes; + LARGE_INTEGER parentKeyDataOffset; + + RtlStringCbPrintfW (parentDrivePath, + sizeof (parentDrivePath), + WIDE ("\\Device\\Harddisk%d\\Partition0"), + mount->nPartitionInInactiveSysEncScopeDriveNo); + + Dump ("Mounting partition within scope of system encryption (reading key data from: %ls)\n", parentDrivePath); + + RtlInitUnicodeString (&FullParentPath, parentDrivePath); + InitializeObjectAttributes (&oaParentFileAttributes, &FullParentPath, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); + + ntStatus = ZwCreateFile (&hParentDeviceFile, + GENERIC_READ | SYNCHRONIZE, + &oaParentFileAttributes, + &IoStatusBlock, + NULL, + FILE_ATTRIBUTE_NORMAL | + FILE_ATTRIBUTE_SYSTEM, + FILE_SHARE_READ | FILE_SHARE_WRITE, + FILE_OPEN, + FILE_RANDOM_ACCESS | + FILE_WRITE_THROUGH | + FILE_NO_INTERMEDIATE_BUFFERING | + FILE_SYNCHRONOUS_IO_NONALERT, + NULL, + 0); + + if (!NT_SUCCESS (ntStatus)) + { + if (hParentDeviceFile != NULL) + ZwClose (hParentDeviceFile); + + Dump ("Cannot open %ls\n", parentDrivePath); + + goto error; + } + + parentKeyDataOffset.QuadPart = TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET; + + ntStatus = ZwReadFile (hParentDeviceFile, + NULL, + NULL, + NULL, + &IoStatusBlock, + readBuffer, + max (TC_VOLUME_HEADER_EFFECTIVE_SIZE, Extension->HostBytesPerSector), + &parentKeyDataOffset, + NULL); + + if (hParentDeviceFile != NULL) + ZwClose (hParentDeviceFile); + } + + if (!NT_SUCCESS (ntStatus) && ntStatus != STATUS_END_OF_FILE) + { + Dump ("Read failed: NTSTATUS 0x%08x\n", ntStatus); + goto error; + } + + if (ntStatus == STATUS_END_OF_FILE || IoStatusBlock.Information < TC_VOLUME_HEADER_EFFECTIVE_SIZE) + { + Dump ("Read didn't read enough data\n"); + + // If FSCTL_ALLOW_EXTENDED_DASD_IO failed and there is a live filesystem on the partition, then the + // filesystem driver may report EOF when we are reading hidden sectors (when the filesystem is + // shorter than the partition). This can happen for example after the user quick-formats a dismounted + // partition-hosted TrueCrypt volume and then tries to mount the volume using the embedded backup header. + memset (readBuffer, 0, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + } + + /* Attempt to recognize the volume (decrypt the header) */ + + ReadVolumeHeaderRecoveryMode = mount->RecoveryMode; + + if ((volumeType == TC_VOLUME_TYPE_HIDDEN) && mount->bProtectHiddenVolume) + { + mount->nReturnCode = ReadVolumeHeaderWCache ( + FALSE, + mount->bCache, + mount->bCachePim, + readBuffer, + &mount->ProtectedHidVolPassword, + mount->ProtectedHidVolPkcs5Prf, + mount->ProtectedHidVolPim, + mount->bTrueCryptMode, + &tmpCryptoInfo); + } + else + { + mount->nReturnCode = ReadVolumeHeaderWCache ( + mount->bPartitionInInactiveSysEncScope && volumeType == TC_VOLUME_TYPE_NORMAL, + mount->bCache, + mount->bCachePim, + readBuffer, + &mount->VolumePassword, + mount->pkcs5_prf, + mount->VolumePim, + mount->bTrueCryptMode, + &Extension->cryptoInfo); + } + + ReadVolumeHeaderRecoveryMode = FALSE; + + if (mount->nReturnCode == 0 || mount->nReturnCode == ERR_CIPHER_INIT_WEAK_KEY) + { + /* Volume header successfully decrypted */ + + if (!Extension->cryptoInfo) + { + /* should never happen */ + mount->nReturnCode = ERR_OUTOFMEMORY; + ntStatus = STATUS_SUCCESS; + goto error; + } + + Dump ("Volume header decrypted\n"); + Dump ("Required program version = %x\n", (int) Extension->cryptoInfo->RequiredProgramVersion); + Dump ("Legacy volume = %d\n", (int) Extension->cryptoInfo->LegacyVolume); + + if (IsHiddenSystemRunning() && !Extension->cryptoInfo->hiddenVolume) + { + Extension->bReadOnly = mount->bMountReadOnly = TRUE; + HiddenSysLeakProtectionCount++; + } + + Extension->cryptoInfo->bProtectHiddenVolume = FALSE; + Extension->cryptoInfo->bHiddenVolProtectionAction = FALSE; + + Extension->cryptoInfo->bPartitionInInactiveSysEncScope = mount->bPartitionInInactiveSysEncScope; + + /* compute the ID of this volume: SHA-512 of the effective header */ + sha256 (Extension->volumeID, readBuffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + + if (volumeType == TC_VOLUME_TYPE_NORMAL) + { + if (mount->bPartitionInInactiveSysEncScope) + { + if (Extension->cryptoInfo->EncryptedAreaStart.Value > (unsigned __int64) partitionStartingOffset + || Extension->cryptoInfo->EncryptedAreaStart.Value + Extension->cryptoInfo->VolumeSize.Value <= (unsigned __int64) partitionStartingOffset) + { + // The partition is not within the key scope of system encryption + mount->nReturnCode = ERR_PASSWORD_WRONG; + ntStatus = STATUS_SUCCESS; + goto error; + } + + if (Extension->cryptoInfo->EncryptedAreaLength.Value != Extension->cryptoInfo->VolumeSize.Value) + { + // Partial encryption is not supported for volumes mounted as regular + mount->nReturnCode = ERR_ENCRYPTION_NOT_COMPLETED; + ntStatus = STATUS_SUCCESS; + goto error; + } + } + else if (Extension->cryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) + { + if (Extension->cryptoInfo->EncryptedAreaLength.Value != Extension->cryptoInfo->VolumeSize.Value) + { + // Non-system in-place encryption process has not been completed on this volume + mount->nReturnCode = ERR_NONSYS_INPLACE_ENC_INCOMPLETE; + ntStatus = STATUS_SUCCESS; + goto error; + } + } + } + + Extension->cryptoInfo->FirstDataUnitNo.Value = 0; + + if (Extension->cryptoInfo->hiddenVolume && IsHiddenSystemRunning()) + { + // Prevent mount of a hidden system partition if the system hosted on it is currently running + if (memcmp (Extension->cryptoInfo->master_keydata, GetSystemDriveCryptoInfo()->master_keydata, EAGetKeySize (Extension->cryptoInfo->ea)) == 0) + { + mount->nReturnCode = ERR_VOL_ALREADY_MOUNTED; + ntStatus = STATUS_SUCCESS; + goto error; + } + } + + switch (volumeType) + { + case TC_VOLUME_TYPE_NORMAL: + + Extension->cryptoInfo->hiddenVolume = FALSE; + + if (mount->bPartitionInInactiveSysEncScope) + { + Extension->cryptoInfo->volDataAreaOffset = 0; + Extension->DiskLength = lDiskLength.QuadPart; + Extension->cryptoInfo->FirstDataUnitNo.Value = partitionStartingOffset / ENCRYPTION_DATA_UNIT_SIZE; + } + else if (Extension->cryptoInfo->LegacyVolume) + { + Extension->cryptoInfo->volDataAreaOffset = TC_VOLUME_HEADER_SIZE_LEGACY; + Extension->DiskLength = lDiskLength.QuadPart - TC_VOLUME_HEADER_SIZE_LEGACY; + } + else + { + Extension->cryptoInfo->volDataAreaOffset = Extension->cryptoInfo->EncryptedAreaStart.Value; + Extension->DiskLength = Extension->cryptoInfo->VolumeSize.Value; + } + + break; + + case TC_VOLUME_TYPE_HIDDEN: + + cryptoInfoPtr = mount->bProtectHiddenVolume ? tmpCryptoInfo : Extension->cryptoInfo; + + Extension->cryptoInfo->hiddenVolumeOffset = cryptoInfoPtr->EncryptedAreaStart.Value; + + Dump ("Hidden volume offset = %I64d\n", Extension->cryptoInfo->hiddenVolumeOffset); + Dump ("Hidden volume size = %I64d\n", cryptoInfoPtr->hiddenVolumeSize); + Dump ("Hidden volume end = %I64d\n", Extension->cryptoInfo->hiddenVolumeOffset + cryptoInfoPtr->hiddenVolumeSize - 1); + + // Validate the offset + if (Extension->cryptoInfo->hiddenVolumeOffset % ENCRYPTION_DATA_UNIT_SIZE != 0) + { + mount->nReturnCode = ERR_VOL_SIZE_WRONG; + ntStatus = STATUS_SUCCESS; + goto error; + } + + // If we are supposed to actually mount the hidden volume (not just to protect it) + if (!mount->bProtectHiddenVolume) + { + Extension->DiskLength = cryptoInfoPtr->hiddenVolumeSize; + Extension->cryptoInfo->hiddenVolume = TRUE; + Extension->cryptoInfo->volDataAreaOffset = Extension->cryptoInfo->hiddenVolumeOffset; + } + else + { + // Hidden volume protection + Extension->cryptoInfo->hiddenVolume = FALSE; + Extension->cryptoInfo->bProtectHiddenVolume = TRUE; + + Extension->cryptoInfo->hiddenVolumeProtectedSize = tmpCryptoInfo->hiddenVolumeSize; + + Dump ("Hidden volume protection active: %I64d-%I64d (%I64d)\n", Extension->cryptoInfo->hiddenVolumeOffset, Extension->cryptoInfo->hiddenVolumeProtectedSize + Extension->cryptoInfo->hiddenVolumeOffset - 1, Extension->cryptoInfo->hiddenVolumeProtectedSize); + } + + break; + } + + Dump ("Volume data offset = %I64d\n", Extension->cryptoInfo->volDataAreaOffset); + Dump ("Volume data size = %I64d\n", Extension->DiskLength); + Dump ("Volume data end = %I64d\n", Extension->cryptoInfo->volDataAreaOffset + Extension->DiskLength - 1); + + if (Extension->DiskLength == 0) + { + Dump ("Incorrect volume size\n"); + continue; + } + + // If this is a hidden volume, make sure we are supposed to actually + // mount it (i.e. not just to protect it) + if (volumeType == TC_VOLUME_TYPE_NORMAL || !mount->bProtectHiddenVolume) + { + // Validate sector size + if (bRawDevice && Extension->cryptoInfo->SectorSize != Extension->HostBytesPerSector) + { + mount->nReturnCode = ERR_PARAMETER_INCORRECT; + ntStatus = STATUS_SUCCESS; + goto error; + } + + // Calculate virtual volume geometry + Extension->TracksPerCylinder = 1; + Extension->SectorsPerTrack = 1; + Extension->BytesPerSector = Extension->cryptoInfo->SectorSize; + Extension->NumberOfCylinders = Extension->DiskLength / Extension->BytesPerSector; + Extension->PartitionType = 0; + + Extension->bRawDevice = bRawDevice; + + memset (Extension->wszVolume, 0, sizeof (Extension->wszVolume)); + if (wcsstr (pwszMountVolume, WIDE ("\\??\\UNC\\")) == pwszMountVolume) + { + /* UNC path */ + RtlStringCbPrintfW (Extension->wszVolume, + sizeof (Extension->wszVolume), + WIDE ("\\??\\\\%s"), + pwszMountVolume + 7); + } + else + { + RtlStringCbCopyW (Extension->wszVolume, sizeof(Extension->wszVolume),pwszMountVolume); + } + + memset (Extension->wszLabel, 0, sizeof (Extension->wszLabel)); + RtlStringCbCopyW (Extension->wszLabel, sizeof(Extension->wszLabel), mount->wszLabel); + } + + // If we are to protect a hidden volume we cannot exit yet, for we must also + // decrypt the hidden volume header. + if (!(volumeType == TC_VOLUME_TYPE_NORMAL && mount->bProtectHiddenVolume)) + { + TCfree (readBuffer); + + if (tmpCryptoInfo != NULL) + { + crypto_close (tmpCryptoInfo); + tmpCryptoInfo = NULL; + } + + return STATUS_SUCCESS; + } + } + else if ((mount->bProtectHiddenVolume && volumeType == TC_VOLUME_TYPE_NORMAL) + || mount->nReturnCode != ERR_PASSWORD_WRONG) + { + /* If we are not supposed to protect a hidden volume, the only error that is + tolerated is ERR_PASSWORD_WRONG (to allow mounting a possible hidden volume). + + If we _are_ supposed to protect a hidden volume, we do not tolerate any error + (both volume headers must be successfully decrypted). */ + + break; + } + } + + /* Failed due to some non-OS reason so we drop through and return NT + SUCCESS then nReturnCode is checked later in user-mode */ + + if (mount->nReturnCode == ERR_OUTOFMEMORY) + ntStatus = STATUS_INSUFFICIENT_RESOURCES; + else + ntStatus = STATUS_SUCCESS; + +error: + if (mount->nReturnCode == ERR_SUCCESS) + mount->nReturnCode = ERR_PASSWORD_WRONG; + + if (tmpCryptoInfo != NULL) + { + crypto_close (tmpCryptoInfo); + tmpCryptoInfo = NULL; + } + + if (Extension->cryptoInfo) + { + crypto_close (Extension->cryptoInfo); + Extension->cryptoInfo = NULL; + } + + if (Extension->bTimeStampValid) + { + RestoreTimeStamp (Extension); + } + + /* Close the hDeviceFile */ + if (Extension->hDeviceFile != NULL) + ZwClose (Extension->hDeviceFile); + + /* The cryptoInfo pointer is deallocated if the readheader routines + fail so there is no need to deallocate here */ + + /* Dereference the user-mode file object */ + if (Extension->pfoDeviceFile != NULL) + ObDereferenceObject (Extension->pfoDeviceFile); + + /* Free the tmp IO buffers */ + if (readBuffer != NULL) + TCfree (readBuffer); + + return ntStatus; +} + +void TCCloseVolume (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension) +{ + UNREFERENCED_PARAMETER (DeviceObject); /* Remove compiler warning */ + + if (Extension->hDeviceFile != NULL) + { + if (Extension->bRawDevice == FALSE + && Extension->bTimeStampValid) + { + RestoreTimeStamp (Extension); + } + ZwClose (Extension->hDeviceFile); + } + ObDereferenceObject (Extension->pfoDeviceFile); + if (Extension->cryptoInfo) + { + crypto_close (Extension->cryptoInfo); + Extension->cryptoInfo = NULL; + } +} + + +NTSTATUS TCSendHostDeviceIoControlRequestEx (PDEVICE_OBJECT DeviceObject, + PEXTENSION Extension, + ULONG IoControlCode, + void *InputBuffer, + ULONG InputBufferSize, + void *OutputBuffer, + ULONG OutputBufferSize) +{ + IO_STATUS_BLOCK IoStatusBlock; + NTSTATUS ntStatus; + PIRP Irp; + + UNREFERENCED_PARAMETER(DeviceObject); /* Remove compiler warning */ + + KeClearEvent (&Extension->keVolumeEvent); + + Irp = IoBuildDeviceIoControlRequest (IoControlCode, + Extension->pFsdDevice, + InputBuffer, InputBufferSize, + OutputBuffer, OutputBufferSize, + FALSE, + &Extension->keVolumeEvent, + &IoStatusBlock); + + if (Irp == NULL) + { + Dump ("IRP allocation failed\n"); + return STATUS_INSUFFICIENT_RESOURCES; + } + + // Disk device may be used by filesystem driver which needs file object + IoGetNextIrpStackLocation (Irp) -> FileObject = Extension->pfoDeviceFile; + + ntStatus = IoCallDriver (Extension->pFsdDevice, Irp); + if (ntStatus == STATUS_PENDING) + { + KeWaitForSingleObject (&Extension->keVolumeEvent, Executive, KernelMode, FALSE, NULL); + ntStatus = IoStatusBlock.Status; + } + + return ntStatus; +} + +NTSTATUS TCSendHostDeviceIoControlRequest (PDEVICE_OBJECT DeviceObject, + PEXTENSION Extension, + ULONG IoControlCode, + void *OutputBuffer, + ULONG OutputBufferSize) +{ + return TCSendHostDeviceIoControlRequestEx (DeviceObject, Extension, IoControlCode, NULL, 0, OutputBuffer, OutputBufferSize); +} + +NTSTATUS COMPLETE_IRP (PDEVICE_OBJECT DeviceObject, + PIRP Irp, + NTSTATUS IrpStatus, + ULONG_PTR IrpInformation) +{ + Irp->IoStatus.Status = IrpStatus; + Irp->IoStatus.Information = IrpInformation; + + UNREFERENCED_PARAMETER (DeviceObject); /* Remove compiler warning */ + +#if EXTRA_INFO + if (!NT_SUCCESS (IrpStatus)) + { + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); + Dump ("COMPLETE_IRP FAILING IRP %ls Flags 0x%08x vpb 0x%08x NTSTATUS 0x%08x\n", TCTranslateCode (irpSp->MajorFunction), + (ULONG) DeviceObject->Flags, (ULONG) DeviceObject->Vpb->Flags, IrpStatus); + } + else + { + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); + Dump ("COMPLETE_IRP SUCCESS IRP %ls Flags 0x%08x vpb 0x%08x NTSTATUS 0x%08x\n", TCTranslateCode (irpSp->MajorFunction), + (ULONG) DeviceObject->Flags, (ULONG) DeviceObject->Vpb->Flags, IrpStatus); + } +#endif + IoCompleteRequest (Irp, IO_NO_INCREMENT); + return IrpStatus; +} + + +static void RestoreTimeStamp (PEXTENSION Extension) +{ + NTSTATUS ntStatus; + FILE_BASIC_INFORMATION FileBasicInfo; + IO_STATUS_BLOCK IoStatusBlock; + + if (Extension->hDeviceFile != NULL + && Extension->bRawDevice == FALSE + && Extension->bReadOnly == FALSE + && Extension->bTimeStampValid) + { + ntStatus = ZwQueryInformationFile (Extension->hDeviceFile, + &IoStatusBlock, + &FileBasicInfo, + sizeof (FileBasicInfo), + FileBasicInformation); + + if (!NT_SUCCESS (ntStatus)) + { + Dump ("ZwQueryInformationFile failed in RestoreTimeStamp: NTSTATUS 0x%08x\n", + ntStatus); + } + else + { + FileBasicInfo.CreationTime = Extension->fileCreationTime; + FileBasicInfo.LastAccessTime = Extension->fileLastAccessTime; + FileBasicInfo.LastWriteTime = Extension->fileLastWriteTime; + FileBasicInfo.ChangeTime = Extension->fileLastChangeTime; + + ntStatus = ZwSetInformationFile( + Extension->hDeviceFile, + &IoStatusBlock, + &FileBasicInfo, + sizeof (FileBasicInfo), + FileBasicInformation); + + if (!NT_SUCCESS (ntStatus)) + Dump ("ZwSetInformationFile failed in RestoreTimeStamp: NTSTATUS 0x%08x\n",ntStatus); + } + } +} diff --git a/src/Driver/Ntvol.h b/src/Driver/Ntvol.h index 4a496a73..912c02b0 100644 --- a/src/Driver/Ntvol.h +++ b/src/Driver/Ntvol.h @@ -1,22 +1,22 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -extern volatile BOOL ProbingHostDeviceForWrite; - -NTSTATUS TCOpenVolume ( PDEVICE_OBJECT DeviceObject , PEXTENSION Extension , MOUNT_STRUCT *mount , PWSTR pwszMountVolume , BOOL bRawDevice ); -void TCCloseVolume ( PDEVICE_OBJECT DeviceObject , PEXTENSION Extension ); -NTSTATUS TCCompletion ( PDEVICE_OBJECT DeviceObject , PIRP Irp , PVOID pUserBuffer ); -static NTSTATUS TCSendHostDeviceIoControlRequest ( PDEVICE_OBJECT DeviceObject , PEXTENSION Extension , ULONG IoControlCode , void *OutputBuffer , ULONG OutputBufferSize ); -static NTSTATUS TCSendHostDeviceIoControlRequestEx ( PDEVICE_OBJECT DeviceObject , PEXTENSION Extension , ULONG IoControlCode , void *InputBuffer , ULONG InputBufferSize , void *OutputBuffer , ULONG OutputBufferSize ); -NTSTATUS COMPLETE_IRP ( PDEVICE_OBJECT DeviceObject , PIRP Irp , NTSTATUS IrpStatus , ULONG_PTR IrpInformation ); -static void RestoreTimeStamp ( PEXTENSION Extension ); +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +extern volatile BOOL ProbingHostDeviceForWrite; + +NTSTATUS TCOpenVolume ( PDEVICE_OBJECT DeviceObject , PEXTENSION Extension , MOUNT_STRUCT *mount , PWSTR pwszMountVolume , BOOL bRawDevice ); +void TCCloseVolume ( PDEVICE_OBJECT DeviceObject , PEXTENSION Extension ); +NTSTATUS TCCompletion ( PDEVICE_OBJECT DeviceObject , PIRP Irp , PVOID pUserBuffer ); +static NTSTATUS TCSendHostDeviceIoControlRequest ( PDEVICE_OBJECT DeviceObject , PEXTENSION Extension , ULONG IoControlCode , void *OutputBuffer , ULONG OutputBufferSize ); +static NTSTATUS TCSendHostDeviceIoControlRequestEx ( PDEVICE_OBJECT DeviceObject , PEXTENSION Extension , ULONG IoControlCode , void *InputBuffer , ULONG InputBufferSize , void *OutputBuffer , ULONG OutputBufferSize ); +NTSTATUS COMPLETE_IRP ( PDEVICE_OBJECT DeviceObject , PIRP Irp , NTSTATUS IrpStatus , ULONG_PTR IrpInformation ); +static void RestoreTimeStamp ( PEXTENSION Extension ); diff --git a/src/Driver/Resource.h b/src/Driver/Resource.h index effd8044..a3e73646 100644 --- a/src/Driver/Resource.h +++ b/src/Driver/Resource.h @@ -1,16 +1,16 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by Driver.rc -// - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NO_MFC 1 -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Driver.rc +// + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NO_MFC 1 +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/src/Driver/Sources b/src/Driver/Sources index 592c2dc6..8e8aef2d 100644 --- a/src/Driver/Sources +++ b/src/Driver/Sources @@ -1,21 +1,21 @@ -TARGETNAME=veracrypt -TARGETTYPE=DRIVER - -USER_C_FLAGS=$(USER_C_FLAGS) -D_UNICODE -LINKER_FLAGS=$(LINKER_FLAGS) -map - -INCLUDES = ../Common;../Crypto - -SOURCES = \ - DriveFilter.c \ - DumpFilter.c \ - EncryptedIoQueue.c \ - Ntdriver.c \ - Ntvol.c \ - VolumeFilter.c \ - Driver.rc - -TARGETLIBS = \ - $(SDK_LIB_PATH)/uuid.lib \ - ../Common/obj$(BUILD_ALT_DIR)/*/Common.lib \ - ../Crypto/obj$(BUILD_ALT_DIR)/*/Crypto.lib +TARGETNAME=veracrypt +TARGETTYPE=DRIVER + +USER_C_FLAGS=$(USER_C_FLAGS) -D_UNICODE +LINKER_FLAGS=$(LINKER_FLAGS) -map + +INCLUDES = ../Common;../Crypto + +SOURCES = \ + DriveFilter.c \ + DumpFilter.c \ + EncryptedIoQueue.c \ + Ntdriver.c \ + Ntvol.c \ + VolumeFilter.c \ + Driver.rc + +TARGETLIBS = \ + $(SDK_LIB_PATH)/uuid.lib \ + ../Common/obj$(BUILD_ALT_DIR)/*/Common.lib \ + ../Crypto/obj$(BUILD_ALT_DIR)/*/Crypto.lib diff --git a/src/Driver/VolumeFilter.c b/src/Driver/VolumeFilter.c index 78b2d7b9..8cb675f6 100644 --- a/src/Driver/VolumeFilter.c +++ b/src/Driver/VolumeFilter.c @@ -1,299 +1,299 @@ -/* - 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 "TCdefs.h" -#include "Ntdriver.h" -#include "Ntvol.h" -#include "DriveFilter.h" -#include "VolumeFilter.h" - -typedef DriveFilterExtension VolumeFilterExtension; - -// Number of times the filter driver answered that an unencrypted volume -// is read-only (or mounted an outer/normal TrueCrypt volume as read only) -uint32 HiddenSysLeakProtectionCount = 0; - - -NTSTATUS VolumeFilterAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo) -{ - VolumeFilterExtension *Extension; - NTSTATUS status; - PDEVICE_OBJECT filterDeviceObject = NULL; - PDEVICE_OBJECT attachedDeviceObject; - - Dump ("VolumeFilterAddDevice pdo=%p\n", pdo); - - attachedDeviceObject = IoGetAttachedDeviceReference (pdo); - status = IoCreateDevice (driverObject, sizeof (VolumeFilterExtension), NULL, attachedDeviceObject->DeviceType, 0, FALSE, &filterDeviceObject); - - ObDereferenceObject (attachedDeviceObject); - - if (!NT_SUCCESS (status)) - { - filterDeviceObject = NULL; - goto err; - } - - Extension = (VolumeFilterExtension *) filterDeviceObject->DeviceExtension; - memset (Extension, 0, sizeof (VolumeFilterExtension)); - - status = IoAttachDeviceToDeviceStackSafe (filterDeviceObject, pdo, &(Extension->LowerDeviceObject)); - if (status != STATUS_SUCCESS) - { - goto err; - } - - if (!Extension->LowerDeviceObject) - { - status = STATUS_DEVICE_REMOVED; - goto err; - } - - Extension->IsVolumeFilterDevice = TRUE; - Extension->DeviceObject = filterDeviceObject; - Extension->Pdo = pdo; - - IoInitializeRemoveLock (&Extension->Queue.RemoveLock, 'LRCV', 0, 0); - - filterDeviceObject->Flags |= Extension->LowerDeviceObject->Flags & (DO_DIRECT_IO | DO_BUFFERED_IO | DO_POWER_PAGABLE); - filterDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; - - return status; - -err: - if (filterDeviceObject) - { - if (Extension->LowerDeviceObject) - IoDetachDevice (Extension->LowerDeviceObject); - - IoDeleteDevice (filterDeviceObject); - } - - return status; -} - - -static NTSTATUS PassIrp (PDEVICE_OBJECT deviceObject, PIRP irp) -{ - IoSkipCurrentIrpStackLocation (irp); - return IoCallDriver (deviceObject, irp); -} - - -static NTSTATUS PassFilteredIrp (PDEVICE_OBJECT deviceObject, PIRP irp, PIO_COMPLETION_ROUTINE completionRoutine, PVOID completionRoutineArg) -{ - IoCopyCurrentIrpStackLocationToNext (irp); - - if (completionRoutine) - IoSetCompletionRoutine (irp, completionRoutine, completionRoutineArg, TRUE, TRUE, TRUE); - - return IoCallDriver (deviceObject, irp); -} - - -static NTSTATUS OnDeviceUsageNotificationCompleted (PDEVICE_OBJECT filterDeviceObject, PIRP Irp, VolumeFilterExtension *Extension) -{ - if (Irp->PendingReturned) - IoMarkIrpPending (Irp); - - if (!(Extension->LowerDeviceObject->Flags & DO_POWER_PAGABLE)) - filterDeviceObject->Flags &= ~DO_POWER_PAGABLE; - - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return STATUS_CONTINUE_COMPLETION; -} - - -static NTSTATUS OnStartDeviceCompleted (PDEVICE_OBJECT filterDeviceObject, PIRP Irp, VolumeFilterExtension *Extension) -{ - if (Irp->PendingReturned) - IoMarkIrpPending (Irp); - - if (Extension->LowerDeviceObject->Characteristics & FILE_REMOVABLE_MEDIA) - filterDeviceObject->Characteristics |= FILE_REMOVABLE_MEDIA; - - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return STATUS_CONTINUE_COMPLETION; -} - - -static NTSTATUS DispatchControl (PDEVICE_OBJECT DeviceObject, PIRP Irp, VolumeFilterExtension *Extension, PIO_STACK_LOCATION irpSp) -{ - NTSTATUS status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); - if (!NT_SUCCESS (status)) - return TCCompleteIrp (Irp, status, 0); - - if (IsHiddenSystemRunning()) - { - switch (irpSp->Parameters.DeviceIoControl.IoControlCode) - { - case IOCTL_DISK_IS_WRITABLE: - { - // All volumes except the system volume must be read-only - - DriveFilterExtension *bootDriveExtension = GetBootDriveFilterExtension(); - STORAGE_DEVICE_NUMBER storageDeviceNumber; - - if (!bootDriveExtension->SystemStorageDeviceNumberValid) - TC_BUG_CHECK (STATUS_INVALID_PARAMETER); - - status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &storageDeviceNumber, sizeof (storageDeviceNumber)); - - if (NT_SUCCESS (status) && bootDriveExtension->SystemStorageDeviceNumber == storageDeviceNumber.DeviceNumber) - { - PARTITION_INFORMATION_EX partition; - status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &partition, sizeof (partition)); - - if (NT_SUCCESS (status) && partition.StartingOffset.QuadPart == bootDriveExtension->ConfiguredEncryptedAreaStart) - { - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return TCCompleteDiskIrp (Irp, STATUS_SUCCESS, 0); - } - } - - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - - ++HiddenSysLeakProtectionCount; - return TCCompleteDiskIrp (Irp, STATUS_MEDIA_WRITE_PROTECTED, 0); - } - - case TC_IOCTL_DISK_IS_WRITABLE: - Dump ("TC_IOCTL_DISK_IS_WRITABLE pdo=%p\n", Extension->Pdo); - - if (!ProbingHostDeviceForWrite) - break; - - // Probe the real state of the device as the user is mounting a TrueCrypt volume. - - // Volume filter may be attached to a merged drive+volume PDO. First test if TC_IOCTL_DISK_IS_WRITABLE works for the underlying device. - status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, TC_IOCTL_DISK_IS_WRITABLE, NULL, 0, NULL, 0); - - if (NT_SUCCESS (status) || status == STATUS_MEDIA_WRITE_PROTECTED) - { - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return TCCompleteDiskIrp (Irp, status, 0); - } - - status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, IOCTL_DISK_IS_WRITABLE, NULL, 0, NULL, 0); - - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return TCCompleteDiskIrp (Irp, status, 0); - - case IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES: - - // Filter IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES to enable potential future use of hidden systems on drives that use the trim operation but not wear-leveling (if any appear in future). The documentation forbids users to create hidden volumes/systems on drives that use wear-leveling and consequently also on drives that use trim (as trim is used only by drives that use wear-leveling, as of 2010). - - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return TCCompleteDiskIrp (Irp, STATUS_SUCCESS, 0); - } - } - - status = PassIrp (Extension->LowerDeviceObject, Irp); - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return status; -} - - -static NTSTATUS DispatchPnp (PDEVICE_OBJECT DeviceObject, PIRP Irp, VolumeFilterExtension *Extension, PIO_STACK_LOCATION irpSp) -{ - NTSTATUS status; - - status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); - if (!NT_SUCCESS (status)) - return TCCompleteIrp (Irp, status, 0); - - switch (irpSp->MinorFunction) - { - case IRP_MN_START_DEVICE: - Dump ("IRP_MN_START_DEVICE volume pdo=%p\n", Extension->Pdo); - return PassFilteredIrp (Extension->LowerDeviceObject, Irp, OnStartDeviceCompleted, Extension); - - case IRP_MN_DEVICE_USAGE_NOTIFICATION: - { - PDEVICE_OBJECT attachedDevice = IoGetAttachedDeviceReference (DeviceObject); - - if (attachedDevice == DeviceObject || (attachedDevice->Flags & DO_POWER_PAGABLE)) - DeviceObject->Flags |= DO_POWER_PAGABLE; - - ObDereferenceObject (attachedDevice); - } - - return PassFilteredIrp (Extension->LowerDeviceObject, Irp, OnDeviceUsageNotificationCompleted, Extension); - - - case IRP_MN_REMOVE_DEVICE: - Dump ("IRP_MN_REMOVE_DEVICE volume pdo=%p\n", Extension->Pdo); - - IoReleaseRemoveLockAndWait (&Extension->Queue.RemoveLock, Irp); - status = PassIrp (Extension->LowerDeviceObject, Irp); - - IoDetachDevice (Extension->LowerDeviceObject); - - IoDeleteDevice (DeviceObject); - return status; - - default: - status = PassIrp (Extension->LowerDeviceObject, Irp); - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - } - - return status; -} - - -static NTSTATUS DispatchPower (PDEVICE_OBJECT DeviceObject, PIRP Irp, VolumeFilterExtension *Extension, PIO_STACK_LOCATION irpSp) -{ - NTSTATUS status; - PoStartNextPowerIrp (Irp); - - status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); - if (!NT_SUCCESS (status)) - return TCCompleteIrp (Irp, status, 0); - - IoSkipCurrentIrpStackLocation (Irp); - status = PoCallDriver (Extension->LowerDeviceObject, Irp); - - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return status; -} - - -NTSTATUS VolumeFilterDispatchIrp (PDEVICE_OBJECT DeviceObject, PIRP Irp) -{ - VolumeFilterExtension *Extension = (VolumeFilterExtension *) DeviceObject->DeviceExtension; - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); - NTSTATUS status; - - ASSERT (!Extension->bRootDevice && Extension->IsVolumeFilterDevice); - - switch (irpSp->MajorFunction) - { - case IRP_MJ_DEVICE_CONTROL: - return DispatchControl (DeviceObject, Irp, Extension, irpSp); - - case IRP_MJ_PNP: - return DispatchPnp (DeviceObject, Irp, Extension, irpSp); - - case IRP_MJ_POWER: - return DispatchPower (DeviceObject, Irp, Extension, irpSp); - - default: - status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); - if (!NT_SUCCESS (status)) - return TCCompleteIrp (Irp, status, 0); - - status = PassIrp (Extension->LowerDeviceObject, Irp); - - IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); - return status; - } -} +/* + 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 "TCdefs.h" +#include "Ntdriver.h" +#include "Ntvol.h" +#include "DriveFilter.h" +#include "VolumeFilter.h" + +typedef DriveFilterExtension VolumeFilterExtension; + +// Number of times the filter driver answered that an unencrypted volume +// is read-only (or mounted an outer/normal TrueCrypt volume as read only) +uint32 HiddenSysLeakProtectionCount = 0; + + +NTSTATUS VolumeFilterAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo) +{ + VolumeFilterExtension *Extension; + NTSTATUS status; + PDEVICE_OBJECT filterDeviceObject = NULL; + PDEVICE_OBJECT attachedDeviceObject; + + Dump ("VolumeFilterAddDevice pdo=%p\n", pdo); + + attachedDeviceObject = IoGetAttachedDeviceReference (pdo); + status = IoCreateDevice (driverObject, sizeof (VolumeFilterExtension), NULL, attachedDeviceObject->DeviceType, 0, FALSE, &filterDeviceObject); + + ObDereferenceObject (attachedDeviceObject); + + if (!NT_SUCCESS (status)) + { + filterDeviceObject = NULL; + goto err; + } + + Extension = (VolumeFilterExtension *) filterDeviceObject->DeviceExtension; + memset (Extension, 0, sizeof (VolumeFilterExtension)); + + status = IoAttachDeviceToDeviceStackSafe (filterDeviceObject, pdo, &(Extension->LowerDeviceObject)); + if (status != STATUS_SUCCESS) + { + goto err; + } + + if (!Extension->LowerDeviceObject) + { + status = STATUS_DEVICE_REMOVED; + goto err; + } + + Extension->IsVolumeFilterDevice = TRUE; + Extension->DeviceObject = filterDeviceObject; + Extension->Pdo = pdo; + + IoInitializeRemoveLock (&Extension->Queue.RemoveLock, 'LRCV', 0, 0); + + filterDeviceObject->Flags |= Extension->LowerDeviceObject->Flags & (DO_DIRECT_IO | DO_BUFFERED_IO | DO_POWER_PAGABLE); + filterDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; + + return status; + +err: + if (filterDeviceObject) + { + if (Extension->LowerDeviceObject) + IoDetachDevice (Extension->LowerDeviceObject); + + IoDeleteDevice (filterDeviceObject); + } + + return status; +} + + +static NTSTATUS PassIrp (PDEVICE_OBJECT deviceObject, PIRP irp) +{ + IoSkipCurrentIrpStackLocation (irp); + return IoCallDriver (deviceObject, irp); +} + + +static NTSTATUS PassFilteredIrp (PDEVICE_OBJECT deviceObject, PIRP irp, PIO_COMPLETION_ROUTINE completionRoutine, PVOID completionRoutineArg) +{ + IoCopyCurrentIrpStackLocationToNext (irp); + + if (completionRoutine) + IoSetCompletionRoutine (irp, completionRoutine, completionRoutineArg, TRUE, TRUE, TRUE); + + return IoCallDriver (deviceObject, irp); +} + + +static NTSTATUS OnDeviceUsageNotificationCompleted (PDEVICE_OBJECT filterDeviceObject, PIRP Irp, VolumeFilterExtension *Extension) +{ + if (Irp->PendingReturned) + IoMarkIrpPending (Irp); + + if (!(Extension->LowerDeviceObject->Flags & DO_POWER_PAGABLE)) + filterDeviceObject->Flags &= ~DO_POWER_PAGABLE; + + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return STATUS_CONTINUE_COMPLETION; +} + + +static NTSTATUS OnStartDeviceCompleted (PDEVICE_OBJECT filterDeviceObject, PIRP Irp, VolumeFilterExtension *Extension) +{ + if (Irp->PendingReturned) + IoMarkIrpPending (Irp); + + if (Extension->LowerDeviceObject->Characteristics & FILE_REMOVABLE_MEDIA) + filterDeviceObject->Characteristics |= FILE_REMOVABLE_MEDIA; + + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return STATUS_CONTINUE_COMPLETION; +} + + +static NTSTATUS DispatchControl (PDEVICE_OBJECT DeviceObject, PIRP Irp, VolumeFilterExtension *Extension, PIO_STACK_LOCATION irpSp) +{ + NTSTATUS status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); + if (!NT_SUCCESS (status)) + return TCCompleteIrp (Irp, status, 0); + + if (IsHiddenSystemRunning()) + { + switch (irpSp->Parameters.DeviceIoControl.IoControlCode) + { + case IOCTL_DISK_IS_WRITABLE: + { + // All volumes except the system volume must be read-only + + DriveFilterExtension *bootDriveExtension = GetBootDriveFilterExtension(); + STORAGE_DEVICE_NUMBER storageDeviceNumber; + + if (!bootDriveExtension->SystemStorageDeviceNumberValid) + TC_BUG_CHECK (STATUS_INVALID_PARAMETER); + + status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &storageDeviceNumber, sizeof (storageDeviceNumber)); + + if (NT_SUCCESS (status) && bootDriveExtension->SystemStorageDeviceNumber == storageDeviceNumber.DeviceNumber) + { + PARTITION_INFORMATION_EX partition; + status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &partition, sizeof (partition)); + + if (NT_SUCCESS (status) && partition.StartingOffset.QuadPart == bootDriveExtension->ConfiguredEncryptedAreaStart) + { + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return TCCompleteDiskIrp (Irp, STATUS_SUCCESS, 0); + } + } + + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + + ++HiddenSysLeakProtectionCount; + return TCCompleteDiskIrp (Irp, STATUS_MEDIA_WRITE_PROTECTED, 0); + } + + case TC_IOCTL_DISK_IS_WRITABLE: + Dump ("TC_IOCTL_DISK_IS_WRITABLE pdo=%p\n", Extension->Pdo); + + if (!ProbingHostDeviceForWrite) + break; + + // Probe the real state of the device as the user is mounting a TrueCrypt volume. + + // Volume filter may be attached to a merged drive+volume PDO. First test if TC_IOCTL_DISK_IS_WRITABLE works for the underlying device. + status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, TC_IOCTL_DISK_IS_WRITABLE, NULL, 0, NULL, 0); + + if (NT_SUCCESS (status) || status == STATUS_MEDIA_WRITE_PROTECTED) + { + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return TCCompleteDiskIrp (Irp, status, 0); + } + + status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, IOCTL_DISK_IS_WRITABLE, NULL, 0, NULL, 0); + + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return TCCompleteDiskIrp (Irp, status, 0); + + case IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES: + + // Filter IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES to enable potential future use of hidden systems on drives that use the trim operation but not wear-leveling (if any appear in future). The documentation forbids users to create hidden volumes/systems on drives that use wear-leveling and consequently also on drives that use trim (as trim is used only by drives that use wear-leveling, as of 2010). + + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return TCCompleteDiskIrp (Irp, STATUS_SUCCESS, 0); + } + } + + status = PassIrp (Extension->LowerDeviceObject, Irp); + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return status; +} + + +static NTSTATUS DispatchPnp (PDEVICE_OBJECT DeviceObject, PIRP Irp, VolumeFilterExtension *Extension, PIO_STACK_LOCATION irpSp) +{ + NTSTATUS status; + + status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); + if (!NT_SUCCESS (status)) + return TCCompleteIrp (Irp, status, 0); + + switch (irpSp->MinorFunction) + { + case IRP_MN_START_DEVICE: + Dump ("IRP_MN_START_DEVICE volume pdo=%p\n", Extension->Pdo); + return PassFilteredIrp (Extension->LowerDeviceObject, Irp, OnStartDeviceCompleted, Extension); + + case IRP_MN_DEVICE_USAGE_NOTIFICATION: + { + PDEVICE_OBJECT attachedDevice = IoGetAttachedDeviceReference (DeviceObject); + + if (attachedDevice == DeviceObject || (attachedDevice->Flags & DO_POWER_PAGABLE)) + DeviceObject->Flags |= DO_POWER_PAGABLE; + + ObDereferenceObject (attachedDevice); + } + + return PassFilteredIrp (Extension->LowerDeviceObject, Irp, OnDeviceUsageNotificationCompleted, Extension); + + + case IRP_MN_REMOVE_DEVICE: + Dump ("IRP_MN_REMOVE_DEVICE volume pdo=%p\n", Extension->Pdo); + + IoReleaseRemoveLockAndWait (&Extension->Queue.RemoveLock, Irp); + status = PassIrp (Extension->LowerDeviceObject, Irp); + + IoDetachDevice (Extension->LowerDeviceObject); + + IoDeleteDevice (DeviceObject); + return status; + + default: + status = PassIrp (Extension->LowerDeviceObject, Irp); + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + } + + return status; +} + + +static NTSTATUS DispatchPower (PDEVICE_OBJECT DeviceObject, PIRP Irp, VolumeFilterExtension *Extension, PIO_STACK_LOCATION irpSp) +{ + NTSTATUS status; + PoStartNextPowerIrp (Irp); + + status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); + if (!NT_SUCCESS (status)) + return TCCompleteIrp (Irp, status, 0); + + IoSkipCurrentIrpStackLocation (Irp); + status = PoCallDriver (Extension->LowerDeviceObject, Irp); + + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return status; +} + + +NTSTATUS VolumeFilterDispatchIrp (PDEVICE_OBJECT DeviceObject, PIRP Irp) +{ + VolumeFilterExtension *Extension = (VolumeFilterExtension *) DeviceObject->DeviceExtension; + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); + NTSTATUS status; + + ASSERT (!Extension->bRootDevice && Extension->IsVolumeFilterDevice); + + switch (irpSp->MajorFunction) + { + case IRP_MJ_DEVICE_CONTROL: + return DispatchControl (DeviceObject, Irp, Extension, irpSp); + + case IRP_MJ_PNP: + return DispatchPnp (DeviceObject, Irp, Extension, irpSp); + + case IRP_MJ_POWER: + return DispatchPower (DeviceObject, Irp, Extension, irpSp); + + default: + status = IoAcquireRemoveLock (&Extension->Queue.RemoveLock, Irp); + if (!NT_SUCCESS (status)) + return TCCompleteIrp (Irp, status, 0); + + status = PassIrp (Extension->LowerDeviceObject, Irp); + + IoReleaseRemoveLock (&Extension->Queue.RemoveLock, Irp); + return status; + } +} diff --git a/src/Driver/VolumeFilter.h b/src/Driver/VolumeFilter.h index ace7627a..be0cbd0b 100644 --- a/src/Driver/VolumeFilter.h +++ b/src/Driver/VolumeFilter.h @@ -1,23 +1,23 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_DRIVER_VOLUME_FILTER -#define TC_HEADER_DRIVER_VOLUME_FILTER - -#include "TCdefs.h" - -extern uint32 HiddenSysLeakProtectionCount; - -NTSTATUS VolumeFilterAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo); -NTSTATUS VolumeFilterDispatchIrp (PDEVICE_OBJECT DeviceObject, PIRP Irp); - -#endif // TC_HEADER_DRIVER_VOLUME_FILTER +/* + 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. +*/ + +#ifndef TC_HEADER_DRIVER_VOLUME_FILTER +#define TC_HEADER_DRIVER_VOLUME_FILTER + +#include "TCdefs.h" + +extern uint32 HiddenSysLeakProtectionCount; + +NTSTATUS VolumeFilterAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo); +NTSTATUS VolumeFilterDispatchIrp (PDEVICE_OBJECT DeviceObject, PIRP Irp); + +#endif // TC_HEADER_DRIVER_VOLUME_FILTER diff --git a/src/ExpandVolume/DlgExpandVolume.cpp b/src/ExpandVolume/DlgExpandVolume.cpp index 0a24c2c2..e08721b3 100644 --- a/src/ExpandVolume/DlgExpandVolume.cpp +++ b/src/ExpandVolume/DlgExpandVolume.cpp @@ -1,777 +1,777 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' and also from the source code of extcv, which is Copyright (c) 2009-2010 Kih-Oskh - or Copyright (c) 2012-2013 Josef Schneider - - 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 "Tcdefs.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Apidrvr.h" -#include "Volumes.h" -#include "Crypto.h" -#include "Dlgcode.h" -#include "Language.h" -#include "Pkcs5.h" -#include "Random.h" -// #include "../Mount/Mount.h" - -#include "../Common/Dictionary.h" -#include "../Common/Common.h" -#include "../Common/Resource.h" -#include "../Common/SecurityToken.h" -#include "../Common/Progress.h" - -#include "ExpandVolume.h" -#include "Resource.h" - -// TO DO: display sector sizes different than 512 bytes -#define SECTOR_SIZE_MSG 512 - -#define TIMER_ID_RANDVIEW 0xff -#define TIMER_INTERVAL_RANDVIEW 50 - -// see definition of enum EV_FileSystem -const wchar_t * szFileSystemStr[4] = {L"RAW",L"FAT",L"NTFS",L"EXFAT"}; - -// prototypes for internal functions -BOOL CALLBACK ExpandVolSizeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -BOOL CALLBACK ExpandVolProgressDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); - -namespace VeraCryptExpander -{ -/* defined in WinMain.c, referenced by ExpandVolumeWizard() */ -int ExtcvAskVolumePassword (HWND hwndDlg, const wchar_t* fileName, Password *password, int *pkcs5, int *pim, BOOL* truecryptMode, char *titleStringId, BOOL enableMountOptions); -} - - -int GetSpaceString(wchar_t *dest, size_t cbDest, uint64 size, BOOL bDevice) -{ - const wchar_t * szFmtBytes = L"%.0lf %s"; - const wchar_t * szFmtOther = L"%.2lf %s"; - const wchar_t * SuffixStr[] = {L"Byte", L"KB", L"MB", L"GB", L"TB"}; - const uint64 Muliplier[] = {1, BYTES_PER_KB, BYTES_PER_MB, BYTES_PER_GB, BYTES_PER_TB}; - const int nMaxSuffix = sizeof(Muliplier)/sizeof(uint64) - 1; - int i; - - for (i=1; i<=nMaxSuffix && size>Muliplier[i]; i++) ; - - --i; - - if (bDevice) { - wchar_t szTemp[512]; - - if (StringCbPrintfW(szTemp, sizeof(szTemp),i?szFmtOther:szFmtBytes, size/(double)Muliplier[i], SuffixStr[i]) < 0 ) - return -1; - - return StringCbPrintfW(dest, cbDest, L"%I64u sectors (%s)", size/SECTOR_SIZE_MSG , szTemp); - } - - return StringCbPrintfW(dest, cbDest,i?szFmtOther:szFmtBytes, size/(double)Muliplier[i], SuffixStr[i]); -} - -void SetCurrentVolSize(HWND hwndDlg, uint64 size) -{ - const uint64 Muliplier[] = {BYTES_PER_KB, BYTES_PER_MB, BYTES_PER_GB, BYTES_PER_TB}; - const int IdRadioBtn[] = {IDC_KB, IDC_MB, IDC_GB, IDC_TB}; - const int nMaxSuffix = sizeof(Muliplier)/sizeof(uint64) - 1; - int i; - wchar_t szTemp[256]; - - for (i=1; i<=nMaxSuffix && size>Muliplier[i]; i++) ; - - --i; - - SendDlgItemMessage (hwndDlg, IdRadioBtn[i], BM_SETCHECK, BST_CHECKED, 0); - StringCbPrintfW(szTemp,sizeof(szTemp),L"%I64u",size/Muliplier[i]); - SetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTemp); -} - -uint64 GetSizeBoxMultiplier(HWND hwndDlg) -{ - const uint64 Muliplier[] = {BYTES_PER_KB, BYTES_PER_MB, BYTES_PER_GB, BYTES_PER_TB}; - const int IdRadioBtn[] = {IDC_KB, IDC_MB, IDC_GB, IDC_TB}; - const int nMaxSuffix = sizeof(Muliplier)/sizeof(uint64) - 1; - int i; - - for (i=nMaxSuffix; i>0 && !IsButtonChecked (GetDlgItem (hwndDlg, IdRadioBtn[i])); --i) ; - - return Muliplier[i]; -} - -BOOL CALLBACK ExpandVolSizeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - static EXPAND_VOL_THREAD_PARAMS *pVolExpandParam; - - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - wchar_t szTemp[4096]; - - pVolExpandParam = (EXPAND_VOL_THREAD_PARAMS*)lParam; - - EnableWindow (GetDlgItem (hwndDlg, IDC_SIZEBOX), !pVolExpandParam->bIsDevice); - EnableWindow (GetDlgItem (hwndDlg, IDC_KB), !pVolExpandParam->bIsDevice); - EnableWindow (GetDlgItem (hwndDlg, IDC_MB), !pVolExpandParam->bIsDevice); - EnableWindow (GetDlgItem (hwndDlg, IDC_GB), !pVolExpandParam->bIsDevice); - EnableWindow (GetDlgItem (hwndDlg, IDC_TB), !pVolExpandParam->bIsDevice); - - EnableWindow (GetDlgItem (hwndDlg, IDC_INIT_NEWSPACE), - !(pVolExpandParam->bIsLegacy && pVolExpandParam->bIsDevice)); - SendDlgItemMessage (hwndDlg, IDC_INIT_NEWSPACE, BM_SETCHECK, - pVolExpandParam->bInitFreeSpace ? BST_CHECKED : BST_UNCHECKED, 0); - - if (!pVolExpandParam->bIsDevice) - SetCurrentVolSize(hwndDlg,pVolExpandParam->oldSize); - - SendMessage (GetDlgItem (hwndDlg, IDC_BOX_HELP), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE); - - GetSpaceString(szTemp,sizeof(szTemp),pVolExpandParam->oldSize,pVolExpandParam->bIsDevice); - - SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_OLDSIZE), szTemp); - SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NAME), pVolExpandParam->szVolumeName); - SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_FILE_SYSTEM), szFileSystemStr[pVolExpandParam->FileSystem]); - - if (pVolExpandParam->bIsDevice) - { - GetSpaceString(szTemp,sizeof(szTemp),pVolExpandParam->newSize,TRUE); - } - else - { - wchar_t szHostFreeStr[256]; - - SetWindowText (GetDlgItem (hwndDlg, IDT_NEW_SIZE), L""); - GetSpaceString(szHostFreeStr,sizeof(szHostFreeStr),pVolExpandParam->hostSizeFree,FALSE); - StringCbPrintfW (szTemp,sizeof(szTemp),L"%s available on host drive", szHostFreeStr); - } - - SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NEWSIZE), szTemp); - - // set help text - if (pVolExpandParam->bIsDevice) - { - StringCbPrintfW (szTemp,sizeof(szTemp),L"This is a device-based VeraCrypt volume.\n\nThe new volume size will be choosen automatically as the size of the host device."); - if (pVolExpandParam->bIsLegacy) - StringCbCatW(szTemp,sizeof(szTemp),L" Note: filling the new space with random data is not supported for legacy volumes."); - } - else - { - StringCbPrintfW (szTemp, sizeof(szTemp),L"Please specify the new size of the VeraCrypt volume (must be at least %I64u KB larger than the current size).",TC_MINVAL_FS_EXPAND/1024); - } - SetWindowText (GetDlgItem (hwndDlg, IDC_BOX_HELP), szTemp); - - } - return 0; - - - case WM_COMMAND: - if (lw == IDCANCEL) - { - EndDialog (hwndDlg, lw); - return 1; - } - - if (lw == IDOK) - { - wchar_t szTemp[4096]; - - pVolExpandParam->bInitFreeSpace = IsButtonChecked (GetDlgItem (hwndDlg, IDC_INIT_NEWSPACE)); - if (!pVolExpandParam->bIsDevice) // for devices new size is set by calling function - { - GetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTemp, ARRAYSIZE (szTemp)); - pVolExpandParam->newSize = _wtoi64(szTemp) * GetSizeBoxMultiplier(hwndDlg); - } - - EndDialog (hwndDlg, lw); - return 1; - } - - return 0; - } - - return 0; -} - - -extern "C" void AddProgressDlgStatus(HWND hwndDlg, const wchar_t* szText) -{ - HWND hwndCtrl; - - hwndCtrl = GetDlgItem (hwndDlg,IDC_BOX_STATUS); - SendMessage(hwndCtrl,EM_REPLACESEL,FALSE,(LPARAM)szText); - SendMessage(hwndCtrl,EM_SCROLLCARET,0,0); -} - - -extern "C" void SetProgressDlgStatus(HWND hwndDlg, const wchar_t* szText) -{ - HWND hwndCtrl; - - hwndCtrl = GetDlgItem (hwndDlg,IDC_BOX_STATUS); - SendMessage(hwndCtrl,EM_SETSEL,0,-1); - SendMessage(hwndCtrl,EM_REPLACESEL,FALSE,(LPARAM)szText); - SendMessage(hwndCtrl,EM_SCROLLCARET,0,0); -} - - -BOOL CALLBACK ExpandVolProgressDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - static EXPAND_VOL_THREAD_PARAMS *pProgressDlgParam; - static BOOL bVolTransformStarted = FALSE; - static BOOL showRandPool = TRUE; - static unsigned char randPool[16]; - static unsigned char maskRandPool [16]; - static BOOL bUseMask = FALSE; - static DWORD mouseEntropyGathered = 0xFFFFFFFF; - static DWORD mouseEventsInitialCount = 0; - /* max value of entropy needed to fill all random pool = 8 * RNG_POOL_SIZE = 2560 bits */ - static const DWORD maxEntropyLevel = RNG_POOL_SIZE * 8; - static HWND hEntropyBar = NULL; - - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - wchar_t szOldHostSize[512], szNewHostSize[512]; - HCRYPTPROV hRngProv; - - pProgressDlgParam = (EXPAND_VOL_THREAD_PARAMS*)lParam; - bVolTransformStarted = FALSE; - showRandPool = FALSE; - - hCurPage = hwndDlg; - nPbar = IDC_PROGRESS_BAR; - - VirtualLock (randPool, sizeof(randPool)); - VirtualLock (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); - VirtualLock (maskRandPool, sizeof(maskRandPool)); - - mouseEntropyGathered = 0xFFFFFFFF; - mouseEventsInitialCount = 0; - bUseMask = FALSE; - if (CryptAcquireContext (&hRngProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) - { - if (CryptGenRandom (hRngProv, sizeof (maskRandPool), maskRandPool)) - bUseMask = TRUE; - CryptReleaseContext (hRngProv, 0); - } - - GetSpaceString(szOldHostSize,sizeof(szOldHostSize),pProgressDlgParam->oldSize,pProgressDlgParam->bIsDevice); - GetSpaceString(szNewHostSize,sizeof(szNewHostSize),pProgressDlgParam->newSize,pProgressDlgParam->bIsDevice); - - SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_OLDSIZE), szOldHostSize); - SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NEWSIZE), szNewHostSize); - SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NAME), pProgressDlgParam->szVolumeName); - SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_FILE_SYSTEM), szFileSystemStr[pProgressDlgParam->FileSystem]); - SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_INITSPACE), pProgressDlgParam->bInitFreeSpace?L"Yes":L"No"); - - SendMessage (GetDlgItem (hwndDlg, IDC_BOX_STATUS), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE); - - SendMessage (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); - - // set status text - if ( !pProgressDlgParam->bInitFreeSpace && pProgressDlgParam->bIsLegacy ) - { - showRandPool = FALSE; - EnableWindow (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), FALSE); - SetDlgItemText(hwndDlg, IDC_BOX_STATUS, L"Click 'Continue' to expand the volume."); - } - else - { - SetDlgItemText(hwndDlg, IDC_BOX_STATUS, L"IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the encryption keys. Then click 'Continue' to expand the volume."); - } - - SendMessage (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), BM_SETCHECK, BST_UNCHECKED, 0); - hEntropyBar = GetDlgItem (hwndDlg, IDC_ENTROPY_BAR); - SendMessage (hEntropyBar, PBM_SETRANGE32, 0, maxEntropyLevel); - SendMessage (hEntropyBar, PBM_SETSTEP, 1, 0); - SetTimer (hwndDlg, TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL); - } - return 0; - case TC_APPMSG_VOL_TRANSFORM_THREAD_ENDED: - { - int nStatus = (int)lParam; - - NormalCursor (); - if (nStatus != 0) - { - if ( nStatus != ERR_USER_ABORT ) - AddProgressDlgStatus (hwndDlg, L"Error: volume expansion failed."); - else - AddProgressDlgStatus (hwndDlg, L"Error: operation aborted by user."); - } - else - { - AddProgressDlgStatus (hwndDlg, L"Finished. Volume successfully expanded."); - } - - SetWindowText (GetDlgItem (hwndDlg, IDOK), L"Exit"); - EnableWindow (GetDlgItem (hwndDlg, IDOK), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE); - } - return 1; - - case WM_TIMER: - - switch (wParam) - { - case TIMER_ID_RANDVIEW: - { - wchar_t szRndPool[64] = {0}; - DWORD mouseEventsCounter; - - RandpeekBytes (hwndDlg, randPool, sizeof (randPool),&mouseEventsCounter); - - ProcessEntropyEstimate (hEntropyBar, &mouseEventsInitialCount, mouseEventsCounter, maxEntropyLevel, &mouseEntropyGathered); - - if (showRandPool) - StringCbPrintfW (szRndPool, sizeof(szRndPool), L"%08X%08X%08X%08X", - *((DWORD*) (randPool + 12)), *((DWORD*) (randPool + 8)), *((DWORD*) (randPool + 4)), *((DWORD*) (randPool))); - else if (bUseMask) - { - for (int i = 0; i < 16; i++) - { - wchar_t tmp2[3]; - unsigned char tmpByte = randPool[i] ^ maskRandPool[i]; - tmp2[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); - tmp2[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); - tmp2[2] = 0; - StringCbCatW (szRndPool, sizeof(szRndPool), tmp2); - } - } - else - { - wmemset (szRndPool, L'*', 32); - } - - SetWindowText (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), szRndPool); - - burn (randPool, sizeof(randPool)); - burn (szRndPool, sizeof(szRndPool)); - } - return 1; - } - return 0; - - case WM_COMMAND: - if (lw == IDC_DISPLAY_POOL_CONTENTS) - { - showRandPool = IsButtonChecked (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS)); - return 1; - } - if (lw == IDCANCEL) - { - if (bVolTransformStarted) - { - if (MessageBoxW (hwndDlg, L"Warning: Volume expansion is in progress!\n\nStopping now may result in a damaged volume.\n\nDo you really want to cancel?", lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO) - return 1; - - // tell the volume transform thread to terminate - bVolTransformThreadCancel = TRUE; - } - EndDialog (hwndDlg, lw); - return 1; - } - - if (lw == IDOK) - { - if (bVolTransformStarted) - { - // TransformThreadFunction finished -> OK button is now exit - EndDialog (hwndDlg, lw); - } - else - { - showRandPool = FALSE; - KillTimer (hwndDlg, TIMER_ID_RANDVIEW); - EnableWindow (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDOK), FALSE); - SetProgressDlgStatus (hwndDlg, L"Starting volume expansion ...\r\n"); - bVolTransformStarted = TRUE; - pProgressDlgParam->hwndDlg = hwndDlg; - if ( _beginthread (volTransformThreadFunction, 0, pProgressDlgParam) == -1L ) - { - handleError (hwndDlg, ERR_OS_ERROR, SRC_POS); - EndDialog (hwndDlg, lw); - } - WaitCursor(); - } - return 1; - } - - return 0; - - case WM_NCDESTROY: - burn (randPool, sizeof (randPool)); - burn (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); - burn (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); - burn (maskRandPool, sizeof(maskRandPool)); - return 0; - } - - return 0; -} - - -typedef struct -{ - OpenVolumeContext *context; - const wchar_t *volumePath; - Password *password; - int pkcs5_prf; - int pim; - BOOL truecryptMode; - BOOL write; - BOOL preserveTimestamps; - BOOL useBackupHeader; - int* nStatus; -} OpenVolumeThreadParam; - -void CALLBACK OpenVolumeWaitThreadProc(void* pArg, HWND hwndDlg) -{ - OpenVolumeThreadParam* pThreadParam = (OpenVolumeThreadParam*) pArg; - - *(pThreadParam)->nStatus = OpenVolume(pThreadParam->context, pThreadParam->volumePath, pThreadParam->password, pThreadParam->pkcs5_prf, - pThreadParam->pim, pThreadParam->truecryptMode, pThreadParam->write, pThreadParam->preserveTimestamps, pThreadParam->useBackupHeader); -} - -/* - ExpandVolumeWizard - - Expands a trucrypt volume (wizard for user interface) - - Parameters: - - hwndDlg : HWND - [in] handle to parent window (if any) - - szVolume : char * - [in] Pointer to a string with the volume name (e.g. '\Device\Harddisk0\Partition1' or 'C:\topsecret.tc') - - Return value: - - none - -*/ -void ExpandVolumeWizard (HWND hwndDlg, wchar_t *lpszVolume) -{ - int nStatus = ERR_OS_ERROR; - wchar_t szTmp[4096]; - Password VolumePassword; - int VolumePkcs5 = 0, VolumePim = -1; - uint64 hostSize, volSize, hostSizeFree, maxSizeFS; - BOOL bIsDevice, bIsLegacy; - DWORD dwError; - int driveNo; - enum EV_FileSystem volFSType; - wchar_t rootPath[] = L"A:\\"; - - switch (IsSystemDevicePath (lpszVolume, hwndDlg, TRUE)) - { - case 1: - case 2: - MessageBoxW (hwndDlg, L"A VeraCrypt system volume can't be expanded.", lpszTitle, MB_OK|MB_ICONEXCLAMATION); - goto ret; - } - - EnableElevatedCursorChange (hwndDlg); - WaitCursor(); - - if (IsMountedVolume (lpszVolume)) - { - Warning ("DISMOUNT_FIRST", hwndDlg); - goto ret; - } - - if (Randinit() != ERR_SUCCESS) { - if (CryptoAPILastError == ERROR_SUCCESS) - nStatus = ERR_RAND_INIT_FAILED; - else - nStatus = ERR_CAPI_INIT_FAILED; - goto error; - } - - NormalCursor(); - - // Ask the user if there is a hidden volume - char *volTypeChoices[] = {0, "DOES_VOLUME_CONTAIN_HIDDEN", "VOLUME_CONTAINS_HIDDEN", "VOLUME_DOES_NOT_CONTAIN_HIDDEN", "IDCANCEL", 0}; - switch (AskMultiChoice ((void **) volTypeChoices, FALSE, hwndDlg)) - { - case 1: - MessageBoxW (hwndDlg, L"An outer volume containing a hidden volume can't be expanded, because this destroys the hidden volume.", lpszTitle, MB_OK|MB_ICONEXCLAMATION); - goto ret; - - case 2: - break; - - default: - nStatus = ERR_SUCCESS; - goto ret; - } - - WaitCursor(); - - nStatus = QueryVolumeInfo(hwndDlg,lpszVolume,&hostSizeFree,&maxSizeFS); - - if (nStatus!=ERR_SUCCESS) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - NormalCursor(); - - while (TRUE) - { - OpenVolumeContext expandVol; - BOOL truecryptMode = FALSE; - - if (!VeraCryptExpander::ExtcvAskVolumePassword (hwndDlg, lpszVolume, &VolumePassword, &VolumePkcs5, &VolumePim, &truecryptMode, "ENTER_NORMAL_VOL_PASSWORD", FALSE)) - { - goto ret; - } - - EnableElevatedCursorChange (hwndDlg); - WaitCursor(); - - if (KeyFilesEnable && FirstKeyFile) - KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, lpszVolume); - - WaitCursor (); - - OpenVolumeThreadParam threadParam; - threadParam.context = &expandVol; - threadParam.volumePath = lpszVolume; - threadParam.password = &VolumePassword; - threadParam.pkcs5_prf = VolumePkcs5; - threadParam.pim = VolumePim; - threadParam.truecryptMode = FALSE; - threadParam.write = FALSE; - threadParam.preserveTimestamps = bPreserveTimestamp; - threadParam.useBackupHeader = FALSE; - threadParam.nStatus = &nStatus; - - ShowWaitDialog (hwndDlg, TRUE, OpenVolumeWaitThreadProc, &threadParam); - - NormalCursor (); - - dwError = GetLastError(); - - if (nStatus == ERR_SUCCESS) - { - bIsDevice = expandVol.IsDevice; - bIsLegacy = expandVol.CryptoInfo->LegacyVolume; - hostSize = expandVol.HostSize; - VolumePkcs5 = expandVol.CryptoInfo->pkcs5; - if ( bIsLegacy ) - { - if ( bIsDevice ) - volSize = 0; // updated later - else - volSize = hostSize; - } - else - { - volSize = GetVolumeSizeByDataAreaSize (expandVol.CryptoInfo->VolumeSize.Value, bIsLegacy); - } - CloseVolume (&expandVol); - break; - } - else if (nStatus != ERR_PASSWORD_WRONG) - { - SetLastError (dwError); - goto error; - } - - NormalCursor(); - - handleError (hwndDlg, nStatus, SRC_POS); - } - - WaitCursor(); - - // auto mount the volume to check the file system type - nStatus=MountVolTemp(hwndDlg, lpszVolume, &driveNo, &VolumePassword, VolumePkcs5, VolumePim); - - if (nStatus != ERR_SUCCESS) - goto error; - - rootPath[0] += driveNo; - - if ( !GetFileSystemType(rootPath,&volFSType) ) - volFSType = EV_FS_TYPE_RAW; - - if ( bIsLegacy && bIsDevice && volFSType == EV_FS_TYPE_NTFS ) - { - uint64 NumberOfSectors; - DWORD BytesPerSector; - - if ( !GetNtfsNumberOfSectors(rootPath, &NumberOfSectors, &BytesPerSector) ) - nStatus = ERR_OS_ERROR; - - // NTFS reported size does not include boot sector copy at volume end - volSize = ( NumberOfSectors + 1 ) * BytesPerSector; - } - - UnmountVolume (hwndDlg, driveNo, TRUE); - - NormalCursor(); - - if (nStatus != ERR_SUCCESS) - goto error; - - if ( bIsDevice && bIsLegacy && volFSType != EV_FS_TYPE_NTFS ) - { - MessageBoxW (hwndDlg, - L"Expanding a device hosted legacy volume with no NTFS file system\n" - L"is unsupported.\n" - L"Note that expanding the VeraCrypt volume itself is not neccessary\n" - L"for legacy volumes.\n", - lpszTitle, MB_OK|MB_ICONEXCLAMATION); - goto ret; - } - - // check if there is enough free space on host device/drive to expand the volume - if ( (bIsDevice && hostSize < volSize + TC_MINVAL_FS_EXPAND) || (!bIsDevice && hostSizeFree < TC_MINVAL_FS_EXPAND) ) - { - MessageBoxW (hwndDlg, L"Not enough free space to expand the volume", lpszTitle, MB_OK|MB_ICONEXCLAMATION); - goto ret; - } - - if (!bIsDevice && hostSize != volSize ) { - // there is some junk data at the end of the volume - if (MessageBoxW (hwndDlg, L"Warning: The container file is larger than the VeraCrypt volume area. The data after the VeraCrypt volume area will be overwritten.\n\nDo you want to continue?", lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO) - goto ret; - } - - switch (volFSType) - { - case EV_FS_TYPE_NTFS: - break; - case EV_FS_TYPE_FAT: - if (MessageBoxW (hwndDlg,L"Warning: The VeraCrypt volume contains a FAT file system!\n\nOnly the VeraCrypt volume itself will be expanded, but not the file system.\n\nDo you want to continue?", - lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO) - goto ret; - break; - case EV_FS_TYPE_EXFAT: - if (MessageBoxW (hwndDlg,L"Warning: The VeraCrypt volume contains an exFAT file system!\n\nOnly the VeraCrypt volume itself will be expanded, but not the file system.\n\nDo you want to continue?", - lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO) - goto ret; - break; - default: - if (MessageBoxW (hwndDlg,L"Warning: The VeraCrypt volume contains an unknown or no file system!\n\nOnly the VeraCrypt volume itself will be expanded, the file system remains unchanged.\n\nDo you want to continue?", - lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO) - goto ret; - } - - EXPAND_VOL_THREAD_PARAMS VolExpandParam; - - VolExpandParam.bInitFreeSpace = (bIsLegacy && bIsDevice) ? FALSE:TRUE; - VolExpandParam.szVolumeName = lpszVolume; - VolExpandParam.FileSystem = volFSType; - VolExpandParam.pVolumePassword = &VolumePassword; - VolExpandParam.VolumePkcs5 = VolumePkcs5; - VolExpandParam.VolumePim = VolumePim; - VolExpandParam.bIsDevice = bIsDevice; - VolExpandParam.bIsLegacy = bIsLegacy; - VolExpandParam.oldSize = bIsDevice ? volSize : hostSize; - VolExpandParam.newSize = hostSize; - VolExpandParam.hostSizeFree = hostSizeFree; - - while (1) - { - uint64 newVolumeSize; - - if (IDCANCEL == DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_SIZE_DIALOG), hwndDlg, - (DLGPROC) ExpandVolSizeDlgProc, (LPARAM) &VolExpandParam)) - { - goto ret; - } - - newVolumeSize = VolExpandParam.newSize; - - if ( !bIsDevice ) - { - if ( newVolumeSize < hostSize + TC_MINVAL_FS_EXPAND) - { - StringCbPrintfW(szTmp,sizeof(szTmp),L"New volume size too small, must be at least %I64u kB larger than the current size.",TC_MINVAL_FS_EXPAND/BYTES_PER_KB); - MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_OK | MB_ICONEXCLAMATION ); - continue; - } - - if ( newVolumeSize - hostSize > hostSizeFree ) - { - StringCbPrintfW(szTmp,sizeof(szTmp),L"New volume size too large, not enough space on host drive."); - MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_OK | MB_ICONEXCLAMATION ); - continue; - } - - if ( newVolumeSize>maxSizeFS ) - { - StringCbPrintfW(szTmp,sizeof(szTmp),L"Maximum file size of %I64u MB on host drive exceeded.",maxSizeFS/BYTES_PER_MB); - MessageBoxW (hwndDlg, L"!\n",lpszTitle, MB_OK | MB_ICONEXCLAMATION ); - continue; - } - } - - if ( newVolumeSize > TC_MAX_VOLUME_SIZE ) - { - // note: current limit TC_MAX_VOLUME_SIZE is 1 PetaByte - StringCbPrintfW(szTmp,sizeof(szTmp),L"Maximum VeraCrypt volume size of %I64u TB exceeded!\n",TC_MAX_VOLUME_SIZE/BYTES_PER_TB); - MessageBoxW (hwndDlg, szTmp,lpszTitle, MB_OK | MB_ICONEXCLAMATION ); - if (bIsDevice) - break; // TODO: ask to limit volume size to TC_MAX_VOLUME_SIZE - continue; - } - - break; - } - - VolExpandParam.oldSize = volSize; - - // start progress dialog - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_EXPAND_PROGRESS_DLG), hwndDlg, - (DLGPROC) ExpandVolProgressDlgProc, (LPARAM) &VolExpandParam ); - -ret: - nStatus = ERR_SUCCESS; - -error: - - if (nStatus != 0) - handleError (hwndDlg, nStatus, SRC_POS); - - burn (&VolumePassword, sizeof (VolumePassword)); - - RestoreDefaultKeyFilesParam(); - RandStop (FALSE); - NormalCursor(); - - return; -} - + or Copyright (c) 2012-2013 Josef Schneider + + 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 "Tcdefs.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Apidrvr.h" +#include "Volumes.h" +#include "Crypto.h" +#include "Dlgcode.h" +#include "Language.h" +#include "Pkcs5.h" +#include "Random.h" +// #include "../Mount/Mount.h" + +#include "../Common/Dictionary.h" +#include "../Common/Common.h" +#include "../Common/Resource.h" +#include "../Common/SecurityToken.h" +#include "../Common/Progress.h" + +#include "ExpandVolume.h" +#include "Resource.h" + +// TO DO: display sector sizes different than 512 bytes +#define SECTOR_SIZE_MSG 512 + +#define TIMER_ID_RANDVIEW 0xff +#define TIMER_INTERVAL_RANDVIEW 50 + +// see definition of enum EV_FileSystem +const wchar_t * szFileSystemStr[4] = {L"RAW",L"FAT",L"NTFS",L"EXFAT"}; + +// prototypes for internal functions +BOOL CALLBACK ExpandVolSizeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +BOOL CALLBACK ExpandVolProgressDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); + +namespace VeraCryptExpander +{ +/* defined in WinMain.c, referenced by ExpandVolumeWizard() */ +int ExtcvAskVolumePassword (HWND hwndDlg, const wchar_t* fileName, Password *password, int *pkcs5, int *pim, BOOL* truecryptMode, char *titleStringId, BOOL enableMountOptions); +} + + +int GetSpaceString(wchar_t *dest, size_t cbDest, uint64 size, BOOL bDevice) +{ + const wchar_t * szFmtBytes = L"%.0lf %s"; + const wchar_t * szFmtOther = L"%.2lf %s"; + const wchar_t * SuffixStr[] = {L"Byte", L"KB", L"MB", L"GB", L"TB"}; + const uint64 Muliplier[] = {1, BYTES_PER_KB, BYTES_PER_MB, BYTES_PER_GB, BYTES_PER_TB}; + const int nMaxSuffix = sizeof(Muliplier)/sizeof(uint64) - 1; + int i; + + for (i=1; i<=nMaxSuffix && size>Muliplier[i]; i++) ; + + --i; + + if (bDevice) { + wchar_t szTemp[512]; + + if (StringCbPrintfW(szTemp, sizeof(szTemp),i?szFmtOther:szFmtBytes, size/(double)Muliplier[i], SuffixStr[i]) < 0 ) + return -1; + + return StringCbPrintfW(dest, cbDest, L"%I64u sectors (%s)", size/SECTOR_SIZE_MSG , szTemp); + } + + return StringCbPrintfW(dest, cbDest,i?szFmtOther:szFmtBytes, size/(double)Muliplier[i], SuffixStr[i]); +} + +void SetCurrentVolSize(HWND hwndDlg, uint64 size) +{ + const uint64 Muliplier[] = {BYTES_PER_KB, BYTES_PER_MB, BYTES_PER_GB, BYTES_PER_TB}; + const int IdRadioBtn[] = {IDC_KB, IDC_MB, IDC_GB, IDC_TB}; + const int nMaxSuffix = sizeof(Muliplier)/sizeof(uint64) - 1; + int i; + wchar_t szTemp[256]; + + for (i=1; i<=nMaxSuffix && size>Muliplier[i]; i++) ; + + --i; + + SendDlgItemMessage (hwndDlg, IdRadioBtn[i], BM_SETCHECK, BST_CHECKED, 0); + StringCbPrintfW(szTemp,sizeof(szTemp),L"%I64u",size/Muliplier[i]); + SetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTemp); +} + +uint64 GetSizeBoxMultiplier(HWND hwndDlg) +{ + const uint64 Muliplier[] = {BYTES_PER_KB, BYTES_PER_MB, BYTES_PER_GB, BYTES_PER_TB}; + const int IdRadioBtn[] = {IDC_KB, IDC_MB, IDC_GB, IDC_TB}; + const int nMaxSuffix = sizeof(Muliplier)/sizeof(uint64) - 1; + int i; + + for (i=nMaxSuffix; i>0 && !IsButtonChecked (GetDlgItem (hwndDlg, IdRadioBtn[i])); --i) ; + + return Muliplier[i]; +} + +BOOL CALLBACK ExpandVolSizeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + static EXPAND_VOL_THREAD_PARAMS *pVolExpandParam; + + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + wchar_t szTemp[4096]; + + pVolExpandParam = (EXPAND_VOL_THREAD_PARAMS*)lParam; + + EnableWindow (GetDlgItem (hwndDlg, IDC_SIZEBOX), !pVolExpandParam->bIsDevice); + EnableWindow (GetDlgItem (hwndDlg, IDC_KB), !pVolExpandParam->bIsDevice); + EnableWindow (GetDlgItem (hwndDlg, IDC_MB), !pVolExpandParam->bIsDevice); + EnableWindow (GetDlgItem (hwndDlg, IDC_GB), !pVolExpandParam->bIsDevice); + EnableWindow (GetDlgItem (hwndDlg, IDC_TB), !pVolExpandParam->bIsDevice); + + EnableWindow (GetDlgItem (hwndDlg, IDC_INIT_NEWSPACE), + !(pVolExpandParam->bIsLegacy && pVolExpandParam->bIsDevice)); + SendDlgItemMessage (hwndDlg, IDC_INIT_NEWSPACE, BM_SETCHECK, + pVolExpandParam->bInitFreeSpace ? BST_CHECKED : BST_UNCHECKED, 0); + + if (!pVolExpandParam->bIsDevice) + SetCurrentVolSize(hwndDlg,pVolExpandParam->oldSize); + + SendMessage (GetDlgItem (hwndDlg, IDC_BOX_HELP), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE); + + GetSpaceString(szTemp,sizeof(szTemp),pVolExpandParam->oldSize,pVolExpandParam->bIsDevice); + + SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_OLDSIZE), szTemp); + SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NAME), pVolExpandParam->szVolumeName); + SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_FILE_SYSTEM), szFileSystemStr[pVolExpandParam->FileSystem]); + + if (pVolExpandParam->bIsDevice) + { + GetSpaceString(szTemp,sizeof(szTemp),pVolExpandParam->newSize,TRUE); + } + else + { + wchar_t szHostFreeStr[256]; + + SetWindowText (GetDlgItem (hwndDlg, IDT_NEW_SIZE), L""); + GetSpaceString(szHostFreeStr,sizeof(szHostFreeStr),pVolExpandParam->hostSizeFree,FALSE); + StringCbPrintfW (szTemp,sizeof(szTemp),L"%s available on host drive", szHostFreeStr); + } + + SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NEWSIZE), szTemp); + + // set help text + if (pVolExpandParam->bIsDevice) + { + StringCbPrintfW (szTemp,sizeof(szTemp),L"This is a device-based VeraCrypt volume.\n\nThe new volume size will be choosen automatically as the size of the host device."); + if (pVolExpandParam->bIsLegacy) + StringCbCatW(szTemp,sizeof(szTemp),L" Note: filling the new space with random data is not supported for legacy volumes."); + } + else + { + StringCbPrintfW (szTemp, sizeof(szTemp),L"Please specify the new size of the VeraCrypt volume (must be at least %I64u KB larger than the current size).",TC_MINVAL_FS_EXPAND/1024); + } + SetWindowText (GetDlgItem (hwndDlg, IDC_BOX_HELP), szTemp); + + } + return 0; + + + case WM_COMMAND: + if (lw == IDCANCEL) + { + EndDialog (hwndDlg, lw); + return 1; + } + + if (lw == IDOK) + { + wchar_t szTemp[4096]; + + pVolExpandParam->bInitFreeSpace = IsButtonChecked (GetDlgItem (hwndDlg, IDC_INIT_NEWSPACE)); + if (!pVolExpandParam->bIsDevice) // for devices new size is set by calling function + { + GetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTemp, ARRAYSIZE (szTemp)); + pVolExpandParam->newSize = _wtoi64(szTemp) * GetSizeBoxMultiplier(hwndDlg); + } + + EndDialog (hwndDlg, lw); + return 1; + } + + return 0; + } + + return 0; +} + + +extern "C" void AddProgressDlgStatus(HWND hwndDlg, const wchar_t* szText) +{ + HWND hwndCtrl; + + hwndCtrl = GetDlgItem (hwndDlg,IDC_BOX_STATUS); + SendMessage(hwndCtrl,EM_REPLACESEL,FALSE,(LPARAM)szText); + SendMessage(hwndCtrl,EM_SCROLLCARET,0,0); +} + + +extern "C" void SetProgressDlgStatus(HWND hwndDlg, const wchar_t* szText) +{ + HWND hwndCtrl; + + hwndCtrl = GetDlgItem (hwndDlg,IDC_BOX_STATUS); + SendMessage(hwndCtrl,EM_SETSEL,0,-1); + SendMessage(hwndCtrl,EM_REPLACESEL,FALSE,(LPARAM)szText); + SendMessage(hwndCtrl,EM_SCROLLCARET,0,0); +} + + +BOOL CALLBACK ExpandVolProgressDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + static EXPAND_VOL_THREAD_PARAMS *pProgressDlgParam; + static BOOL bVolTransformStarted = FALSE; + static BOOL showRandPool = TRUE; + static unsigned char randPool[16]; + static unsigned char maskRandPool [16]; + static BOOL bUseMask = FALSE; + static DWORD mouseEntropyGathered = 0xFFFFFFFF; + static DWORD mouseEventsInitialCount = 0; + /* max value of entropy needed to fill all random pool = 8 * RNG_POOL_SIZE = 2560 bits */ + static const DWORD maxEntropyLevel = RNG_POOL_SIZE * 8; + static HWND hEntropyBar = NULL; + + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + wchar_t szOldHostSize[512], szNewHostSize[512]; + HCRYPTPROV hRngProv; + + pProgressDlgParam = (EXPAND_VOL_THREAD_PARAMS*)lParam; + bVolTransformStarted = FALSE; + showRandPool = FALSE; + + hCurPage = hwndDlg; + nPbar = IDC_PROGRESS_BAR; + + VirtualLock (randPool, sizeof(randPool)); + VirtualLock (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); + VirtualLock (maskRandPool, sizeof(maskRandPool)); + + mouseEntropyGathered = 0xFFFFFFFF; + mouseEventsInitialCount = 0; + bUseMask = FALSE; + if (CryptAcquireContext (&hRngProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + { + if (CryptGenRandom (hRngProv, sizeof (maskRandPool), maskRandPool)) + bUseMask = TRUE; + CryptReleaseContext (hRngProv, 0); + } + + GetSpaceString(szOldHostSize,sizeof(szOldHostSize),pProgressDlgParam->oldSize,pProgressDlgParam->bIsDevice); + GetSpaceString(szNewHostSize,sizeof(szNewHostSize),pProgressDlgParam->newSize,pProgressDlgParam->bIsDevice); + + SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_OLDSIZE), szOldHostSize); + SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NEWSIZE), szNewHostSize); + SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NAME), pProgressDlgParam->szVolumeName); + SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_FILE_SYSTEM), szFileSystemStr[pProgressDlgParam->FileSystem]); + SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_INITSPACE), pProgressDlgParam->bInitFreeSpace?L"Yes":L"No"); + + SendMessage (GetDlgItem (hwndDlg, IDC_BOX_STATUS), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE); + + SendMessage (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); + + // set status text + if ( !pProgressDlgParam->bInitFreeSpace && pProgressDlgParam->bIsLegacy ) + { + showRandPool = FALSE; + EnableWindow (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), FALSE); + SetDlgItemText(hwndDlg, IDC_BOX_STATUS, L"Click 'Continue' to expand the volume."); + } + else + { + SetDlgItemText(hwndDlg, IDC_BOX_STATUS, L"IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the encryption keys. Then click 'Continue' to expand the volume."); + } + + SendMessage (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), BM_SETCHECK, BST_UNCHECKED, 0); + hEntropyBar = GetDlgItem (hwndDlg, IDC_ENTROPY_BAR); + SendMessage (hEntropyBar, PBM_SETRANGE32, 0, maxEntropyLevel); + SendMessage (hEntropyBar, PBM_SETSTEP, 1, 0); + SetTimer (hwndDlg, TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL); + } + return 0; + case TC_APPMSG_VOL_TRANSFORM_THREAD_ENDED: + { + int nStatus = (int)lParam; + + NormalCursor (); + if (nStatus != 0) + { + if ( nStatus != ERR_USER_ABORT ) + AddProgressDlgStatus (hwndDlg, L"Error: volume expansion failed."); + else + AddProgressDlgStatus (hwndDlg, L"Error: operation aborted by user."); + } + else + { + AddProgressDlgStatus (hwndDlg, L"Finished. Volume successfully expanded."); + } + + SetWindowText (GetDlgItem (hwndDlg, IDOK), L"Exit"); + EnableWindow (GetDlgItem (hwndDlg, IDOK), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE); + } + return 1; + + case WM_TIMER: + + switch (wParam) + { + case TIMER_ID_RANDVIEW: + { + wchar_t szRndPool[64] = {0}; + DWORD mouseEventsCounter; + + RandpeekBytes (hwndDlg, randPool, sizeof (randPool),&mouseEventsCounter); + + ProcessEntropyEstimate (hEntropyBar, &mouseEventsInitialCount, mouseEventsCounter, maxEntropyLevel, &mouseEntropyGathered); + + if (showRandPool) + StringCbPrintfW (szRndPool, sizeof(szRndPool), L"%08X%08X%08X%08X", + *((DWORD*) (randPool + 12)), *((DWORD*) (randPool + 8)), *((DWORD*) (randPool + 4)), *((DWORD*) (randPool))); + else if (bUseMask) + { + for (int i = 0; i < 16; i++) + { + wchar_t tmp2[3]; + unsigned char tmpByte = randPool[i] ^ maskRandPool[i]; + tmp2[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); + tmp2[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); + tmp2[2] = 0; + StringCbCatW (szRndPool, sizeof(szRndPool), tmp2); + } + } + else + { + wmemset (szRndPool, L'*', 32); + } + + SetWindowText (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), szRndPool); + + burn (randPool, sizeof(randPool)); + burn (szRndPool, sizeof(szRndPool)); + } + return 1; + } + return 0; + + case WM_COMMAND: + if (lw == IDC_DISPLAY_POOL_CONTENTS) + { + showRandPool = IsButtonChecked (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS)); + return 1; + } + if (lw == IDCANCEL) + { + if (bVolTransformStarted) + { + if (MessageBoxW (hwndDlg, L"Warning: Volume expansion is in progress!\n\nStopping now may result in a damaged volume.\n\nDo you really want to cancel?", lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO) + return 1; + + // tell the volume transform thread to terminate + bVolTransformThreadCancel = TRUE; + } + EndDialog (hwndDlg, lw); + return 1; + } + + if (lw == IDOK) + { + if (bVolTransformStarted) + { + // TransformThreadFunction finished -> OK button is now exit + EndDialog (hwndDlg, lw); + } + else + { + showRandPool = FALSE; + KillTimer (hwndDlg, TIMER_ID_RANDVIEW); + EnableWindow (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDOK), FALSE); + SetProgressDlgStatus (hwndDlg, L"Starting volume expansion ...\r\n"); + bVolTransformStarted = TRUE; + pProgressDlgParam->hwndDlg = hwndDlg; + if ( _beginthread (volTransformThreadFunction, 0, pProgressDlgParam) == -1L ) + { + handleError (hwndDlg, ERR_OS_ERROR, SRC_POS); + EndDialog (hwndDlg, lw); + } + WaitCursor(); + } + return 1; + } + + return 0; + + case WM_NCDESTROY: + burn (randPool, sizeof (randPool)); + burn (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); + burn (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); + burn (maskRandPool, sizeof(maskRandPool)); + return 0; + } + + return 0; +} + + +typedef struct +{ + OpenVolumeContext *context; + const wchar_t *volumePath; + Password *password; + int pkcs5_prf; + int pim; + BOOL truecryptMode; + BOOL write; + BOOL preserveTimestamps; + BOOL useBackupHeader; + int* nStatus; +} OpenVolumeThreadParam; + +void CALLBACK OpenVolumeWaitThreadProc(void* pArg, HWND hwndDlg) +{ + OpenVolumeThreadParam* pThreadParam = (OpenVolumeThreadParam*) pArg; + + *(pThreadParam)->nStatus = OpenVolume(pThreadParam->context, pThreadParam->volumePath, pThreadParam->password, pThreadParam->pkcs5_prf, + pThreadParam->pim, pThreadParam->truecryptMode, pThreadParam->write, pThreadParam->preserveTimestamps, pThreadParam->useBackupHeader); +} + +/* + ExpandVolumeWizard + + Expands a trucrypt volume (wizard for user interface) + + Parameters: + + hwndDlg : HWND + [in] handle to parent window (if any) + + szVolume : char * + [in] Pointer to a string with the volume name (e.g. '\Device\Harddisk0\Partition1' or 'C:\topsecret.tc') + + Return value: + + none + +*/ +void ExpandVolumeWizard (HWND hwndDlg, wchar_t *lpszVolume) +{ + int nStatus = ERR_OS_ERROR; + wchar_t szTmp[4096]; + Password VolumePassword; + int VolumePkcs5 = 0, VolumePim = -1; + uint64 hostSize, volSize, hostSizeFree, maxSizeFS; + BOOL bIsDevice, bIsLegacy; + DWORD dwError; + int driveNo; + enum EV_FileSystem volFSType; + wchar_t rootPath[] = L"A:\\"; + + switch (IsSystemDevicePath (lpszVolume, hwndDlg, TRUE)) + { + case 1: + case 2: + MessageBoxW (hwndDlg, L"A VeraCrypt system volume can't be expanded.", lpszTitle, MB_OK|MB_ICONEXCLAMATION); + goto ret; + } + + EnableElevatedCursorChange (hwndDlg); + WaitCursor(); + + if (IsMountedVolume (lpszVolume)) + { + Warning ("DISMOUNT_FIRST", hwndDlg); + goto ret; + } + + if (Randinit() != ERR_SUCCESS) { + if (CryptoAPILastError == ERROR_SUCCESS) + nStatus = ERR_RAND_INIT_FAILED; + else + nStatus = ERR_CAPI_INIT_FAILED; + goto error; + } + + NormalCursor(); + + // Ask the user if there is a hidden volume + char *volTypeChoices[] = {0, "DOES_VOLUME_CONTAIN_HIDDEN", "VOLUME_CONTAINS_HIDDEN", "VOLUME_DOES_NOT_CONTAIN_HIDDEN", "IDCANCEL", 0}; + switch (AskMultiChoice ((void **) volTypeChoices, FALSE, hwndDlg)) + { + case 1: + MessageBoxW (hwndDlg, L"An outer volume containing a hidden volume can't be expanded, because this destroys the hidden volume.", lpszTitle, MB_OK|MB_ICONEXCLAMATION); + goto ret; + + case 2: + break; + + default: + nStatus = ERR_SUCCESS; + goto ret; + } + + WaitCursor(); + + nStatus = QueryVolumeInfo(hwndDlg,lpszVolume,&hostSizeFree,&maxSizeFS); + + if (nStatus!=ERR_SUCCESS) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + NormalCursor(); + + while (TRUE) + { + OpenVolumeContext expandVol; + BOOL truecryptMode = FALSE; + + if (!VeraCryptExpander::ExtcvAskVolumePassword (hwndDlg, lpszVolume, &VolumePassword, &VolumePkcs5, &VolumePim, &truecryptMode, "ENTER_NORMAL_VOL_PASSWORD", FALSE)) + { + goto ret; + } + + EnableElevatedCursorChange (hwndDlg); + WaitCursor(); + + if (KeyFilesEnable && FirstKeyFile) + KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, lpszVolume); + + WaitCursor (); + + OpenVolumeThreadParam threadParam; + threadParam.context = &expandVol; + threadParam.volumePath = lpszVolume; + threadParam.password = &VolumePassword; + threadParam.pkcs5_prf = VolumePkcs5; + threadParam.pim = VolumePim; + threadParam.truecryptMode = FALSE; + threadParam.write = FALSE; + threadParam.preserveTimestamps = bPreserveTimestamp; + threadParam.useBackupHeader = FALSE; + threadParam.nStatus = &nStatus; + + ShowWaitDialog (hwndDlg, TRUE, OpenVolumeWaitThreadProc, &threadParam); + + NormalCursor (); + + dwError = GetLastError(); + + if (nStatus == ERR_SUCCESS) + { + bIsDevice = expandVol.IsDevice; + bIsLegacy = expandVol.CryptoInfo->LegacyVolume; + hostSize = expandVol.HostSize; + VolumePkcs5 = expandVol.CryptoInfo->pkcs5; + if ( bIsLegacy ) + { + if ( bIsDevice ) + volSize = 0; // updated later + else + volSize = hostSize; + } + else + { + volSize = GetVolumeSizeByDataAreaSize (expandVol.CryptoInfo->VolumeSize.Value, bIsLegacy); + } + CloseVolume (&expandVol); + break; + } + else if (nStatus != ERR_PASSWORD_WRONG) + { + SetLastError (dwError); + goto error; + } + + NormalCursor(); + + handleError (hwndDlg, nStatus, SRC_POS); + } + + WaitCursor(); + + // auto mount the volume to check the file system type + nStatus=MountVolTemp(hwndDlg, lpszVolume, &driveNo, &VolumePassword, VolumePkcs5, VolumePim); + + if (nStatus != ERR_SUCCESS) + goto error; + + rootPath[0] += driveNo; + + if ( !GetFileSystemType(rootPath,&volFSType) ) + volFSType = EV_FS_TYPE_RAW; + + if ( bIsLegacy && bIsDevice && volFSType == EV_FS_TYPE_NTFS ) + { + uint64 NumberOfSectors; + DWORD BytesPerSector; + + if ( !GetNtfsNumberOfSectors(rootPath, &NumberOfSectors, &BytesPerSector) ) + nStatus = ERR_OS_ERROR; + + // NTFS reported size does not include boot sector copy at volume end + volSize = ( NumberOfSectors + 1 ) * BytesPerSector; + } + + UnmountVolume (hwndDlg, driveNo, TRUE); + + NormalCursor(); + + if (nStatus != ERR_SUCCESS) + goto error; + + if ( bIsDevice && bIsLegacy && volFSType != EV_FS_TYPE_NTFS ) + { + MessageBoxW (hwndDlg, + L"Expanding a device hosted legacy volume with no NTFS file system\n" + L"is unsupported.\n" + L"Note that expanding the VeraCrypt volume itself is not neccessary\n" + L"for legacy volumes.\n", + lpszTitle, MB_OK|MB_ICONEXCLAMATION); + goto ret; + } + + // check if there is enough free space on host device/drive to expand the volume + if ( (bIsDevice && hostSize < volSize + TC_MINVAL_FS_EXPAND) || (!bIsDevice && hostSizeFree < TC_MINVAL_FS_EXPAND) ) + { + MessageBoxW (hwndDlg, L"Not enough free space to expand the volume", lpszTitle, MB_OK|MB_ICONEXCLAMATION); + goto ret; + } + + if (!bIsDevice && hostSize != volSize ) { + // there is some junk data at the end of the volume + if (MessageBoxW (hwndDlg, L"Warning: The container file is larger than the VeraCrypt volume area. The data after the VeraCrypt volume area will be overwritten.\n\nDo you want to continue?", lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO) + goto ret; + } + + switch (volFSType) + { + case EV_FS_TYPE_NTFS: + break; + case EV_FS_TYPE_FAT: + if (MessageBoxW (hwndDlg,L"Warning: The VeraCrypt volume contains a FAT file system!\n\nOnly the VeraCrypt volume itself will be expanded, but not the file system.\n\nDo you want to continue?", + lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO) + goto ret; + break; + case EV_FS_TYPE_EXFAT: + if (MessageBoxW (hwndDlg,L"Warning: The VeraCrypt volume contains an exFAT file system!\n\nOnly the VeraCrypt volume itself will be expanded, but not the file system.\n\nDo you want to continue?", + lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO) + goto ret; + break; + default: + if (MessageBoxW (hwndDlg,L"Warning: The VeraCrypt volume contains an unknown or no file system!\n\nOnly the VeraCrypt volume itself will be expanded, the file system remains unchanged.\n\nDo you want to continue?", + lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO) + goto ret; + } + + EXPAND_VOL_THREAD_PARAMS VolExpandParam; + + VolExpandParam.bInitFreeSpace = (bIsLegacy && bIsDevice) ? FALSE:TRUE; + VolExpandParam.szVolumeName = lpszVolume; + VolExpandParam.FileSystem = volFSType; + VolExpandParam.pVolumePassword = &VolumePassword; + VolExpandParam.VolumePkcs5 = VolumePkcs5; + VolExpandParam.VolumePim = VolumePim; + VolExpandParam.bIsDevice = bIsDevice; + VolExpandParam.bIsLegacy = bIsLegacy; + VolExpandParam.oldSize = bIsDevice ? volSize : hostSize; + VolExpandParam.newSize = hostSize; + VolExpandParam.hostSizeFree = hostSizeFree; + + while (1) + { + uint64 newVolumeSize; + + if (IDCANCEL == DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_SIZE_DIALOG), hwndDlg, + (DLGPROC) ExpandVolSizeDlgProc, (LPARAM) &VolExpandParam)) + { + goto ret; + } + + newVolumeSize = VolExpandParam.newSize; + + if ( !bIsDevice ) + { + if ( newVolumeSize < hostSize + TC_MINVAL_FS_EXPAND) + { + StringCbPrintfW(szTmp,sizeof(szTmp),L"New volume size too small, must be at least %I64u kB larger than the current size.",TC_MINVAL_FS_EXPAND/BYTES_PER_KB); + MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_OK | MB_ICONEXCLAMATION ); + continue; + } + + if ( newVolumeSize - hostSize > hostSizeFree ) + { + StringCbPrintfW(szTmp,sizeof(szTmp),L"New volume size too large, not enough space on host drive."); + MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_OK | MB_ICONEXCLAMATION ); + continue; + } + + if ( newVolumeSize>maxSizeFS ) + { + StringCbPrintfW(szTmp,sizeof(szTmp),L"Maximum file size of %I64u MB on host drive exceeded.",maxSizeFS/BYTES_PER_MB); + MessageBoxW (hwndDlg, L"!\n",lpszTitle, MB_OK | MB_ICONEXCLAMATION ); + continue; + } + } + + if ( newVolumeSize > TC_MAX_VOLUME_SIZE ) + { + // note: current limit TC_MAX_VOLUME_SIZE is 1 PetaByte + StringCbPrintfW(szTmp,sizeof(szTmp),L"Maximum VeraCrypt volume size of %I64u TB exceeded!\n",TC_MAX_VOLUME_SIZE/BYTES_PER_TB); + MessageBoxW (hwndDlg, szTmp,lpszTitle, MB_OK | MB_ICONEXCLAMATION ); + if (bIsDevice) + break; // TODO: ask to limit volume size to TC_MAX_VOLUME_SIZE + continue; + } + + break; + } + + VolExpandParam.oldSize = volSize; + + // start progress dialog + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_EXPAND_PROGRESS_DLG), hwndDlg, + (DLGPROC) ExpandVolProgressDlgProc, (LPARAM) &VolExpandParam ); + +ret: + nStatus = ERR_SUCCESS; + +error: + + if (nStatus != 0) + handleError (hwndDlg, nStatus, SRC_POS); + + burn (&VolumePassword, sizeof (VolumePassword)); + + RestoreDefaultKeyFilesParam(); + RandStop (FALSE); + NormalCursor(); + + return; +} + diff --git a/src/ExpandVolume/ExpandVolume.c b/src/ExpandVolume/ExpandVolume.c index 0206efbc..9deb3af4 100644 --- a/src/ExpandVolume/ExpandVolume.c +++ b/src/ExpandVolume/ExpandVolume.c @@ -1,17 +1,17 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' and also from the source code of extcv, which is Copyright (c) 2009-2010 Kih-Oskh - or Copyright (c) 2012-2013 Josef Schneider - - 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 + or Copyright (c) 2012-2013 Josef Schneider + + 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 "Tcdefs.h" @@ -38,8 +38,8 @@ #include "ExpandVolume.h" #include "Resource.h" -#ifndef SRC_POS -#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) +#ifndef SRC_POS +#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) #endif #define DEBUG_EXPAND_VOLUME @@ -595,9 +595,9 @@ static int ExpandVolume (HWND hwndDlg, wchar_t *lpszVolume, Password *pVolumePas if (Randinit ()) { - if (CryptoAPILastError == ERROR_SUCCESS) - nStatus = ERR_RAND_INIT_FAILED; - else + if (CryptoAPILastError == ERROR_SUCCESS) + nStatus = ERR_RAND_INIT_FAILED; + else nStatus = ERR_CAPI_INIT_FAILED; goto error; } @@ -868,9 +868,9 @@ static int ExpandVolume (HWND hwndDlg, wchar_t *lpszVolume, Password *pVolumePas LARGE_INTEGER offset; WipeAlgorithmId wipeAlgorithm = TC_WIPE_35_GUTMANN; - if ( !RandgetBytes (hwndDlg, wipeRandChars, TC_WIPE_RAND_CHAR_COUNT, TRUE) - || !RandgetBytes (hwndDlg, wipeRandCharsUpdate, TC_WIPE_RAND_CHAR_COUNT, TRUE) - ) + if ( !RandgetBytes (hwndDlg, wipeRandChars, TC_WIPE_RAND_CHAR_COUNT, TRUE) + || !RandgetBytes (hwndDlg, wipeRandCharsUpdate, TC_WIPE_RAND_CHAR_COUNT, TRUE) + ) { nStatus = ERR_OS_ERROR; goto error; diff --git a/src/ExpandVolume/ExpandVolume.rc b/src/ExpandVolume/ExpandVolume.rc index 897b75b1..31f71d95 100644 --- a/src/ExpandVolume/ExpandVolume.rc +++ b/src/ExpandVolume/ExpandVolume.rc @@ -1,298 +1,298 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" -#include "..\\common\\resource.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_SIZE_DIALOG DIALOGEX 0, 0, 376, 271 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt Expander" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - EDITTEXT IDC_SIZEBOX,30,102,109,14,ES_RIGHT | ES_AUTOHSCROLL | ES_NUMBER - CONTROL "&KB",IDC_KB,"Button",BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,169,105,38,10 - CONTROL "&MB",IDC_MB,"Button",BS_AUTORADIOBUTTON,209,105,38,10 - CONTROL "&GB",IDC_GB,"Button",BS_AUTORADIOBUTTON,248,105,38,10 - CONTROL "&TB",IDC_TB,"Button",BS_AUTORADIOBUTTON,288,105,38,10 - CONTROL "Fill new space with random data",IDC_INIT_NEWSPACE, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,30,127,118,10 - DEFPUSHBUTTON "Continue",IDOK,15,238,84,18 - PUSHBUTTON "Cancel",IDCANCEL,277,238,84,18 - LTEXT "Help Text",IDC_BOX_HELP,15,165,346,58,0,WS_EX_CLIENTEDGE - GROUPBOX "Enter new volume size",IDC_STATIC,15,83,346,63 - RTEXT "Current size: ",IDT_CURRENT_SIZE,27,42,46,8 - CONTROL "",IDC_EXPAND_VOLUME_OLDSIZE,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,80,42,275,8,WS_EX_TRANSPARENT - RTEXT "New size: ",IDT_NEW_SIZE,28,54,45,8 - LTEXT "",IDC_EXPAND_VOLUME_NEWSIZE,80,54,275,8,0,WS_EX_TRANSPARENT - RTEXT "Volume: ",IDT_VOL_NAME,31,18,42,8 - GROUPBOX "",IDC_STATIC,15,9,346,59 - CONTROL "",IDC_EXPAND_VOLUME_NAME,"Static",SS_SIMPLE | WS_GROUP,80,18,275,8,WS_EX_TRANSPARENT - RTEXT "File system: ",IDT_FILE_SYS,31,30,42,8 - CONTROL "",IDC_EXPAND_FILE_SYSTEM,"Static",SS_SIMPLE | WS_GROUP,80,30,275,8,WS_EX_TRANSPARENT -END - -IDD_MOUNT_DLG DIALOGEX 0, 0, 376, 271 -STYLE DS_SETFONT | DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt Expander" -MENU IDR_MENU -CLASS "VeraCryptCustomDlg" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - COMBOBOX IDC_VOLUME,56,192,212,74,CBS_DROPDOWN | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP - PUSHBUTTON "Select &File...",IDC_SELECT_FILE,276,192,84,14 - PUSHBUTTON "Select D&evice...",IDC_SELECT_DEVICE,276,211,84,14 - DEFPUSHBUTTON "Mount",IDOK,8,243,84,18,WS_GROUP - PUSHBUTTON "E&xit",IDC_EXIT,284,243,84,18,WS_GROUP - CONTROL 112,IDC_LOGO,"Static",SS_BITMAP | SS_NOTIFY | WS_BORDER,16,192,27,31 - GROUPBOX "Volume",IDT_VOLUME,8,179,360,53 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,1,0,373,147 - GROUPBOX "",IDC_STATIC,282,238,88,24 - GROUPBOX "",IDC_STATIC,6,238,88,24 - GROUPBOX "",IDC_STATIC,1,147,373,123,BS_CENTER - LTEXT "1. Select the VeraCrypt volume to be expanded\n2. Click the 'Mount' button",IDC_STATIC,15,156,293,21 - LTEXT "Static",IDC_INFOEXPAND,8,6,361,134,SS_NOPREFIX | SS_SUNKEN,WS_EX_STATICEDGE -END - -IDD_PASSWORD_DLG DIALOGEX 0, 0, 322, 107 -STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_VISIBLE | WS_CAPTION -CAPTION "Enter VeraCrypt Volume Password" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - EDITTEXT IDC_PASSWORD,69,8,166,14,ES_PASSWORD | ES_AUTOHSCROLL - COMBOBOX IDC_PKCS5_PRF_ID,69,26,86,90,CBS_DROPDOWNLIST | WS_TABSTOP - CONTROL "TrueCrypt Mode",IDC_TRUECRYPT_MODE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,159,28,76,10 - EDITTEXT IDC_PIM,69,43,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER | NOT WS_VISIBLE - CONTROL "Use P&IM",IDC_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,49,97,10 - CONTROL "Cache passwords and keyfil&es in memory",IDC_CACHE, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,62,153,10 - CONTROL "&Display password",IDC_SHOW_PASSWORD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,75,83,10 - CONTROL "U&se keyfiles",IDC_KEYFILES_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,88,83,11 - PUSHBUTTON "&Keyfiles...",IDC_KEY_FILES,171,86,64,14 - PUSHBUTTON "Mount Opti&ons...",IDC_MOUNT_OPTIONS,243,86,64,14 - DEFPUSHBUTTON "OK",IDOK,243,8,64,14 - PUSHBUTTON "Cancel",IDCANCEL,243,25,64,14 - RTEXT "Password:",IDT_PASSWORD,0,10,65,13 - RTEXT "PKCS-5 PRF:",IDT_PKCS5_PRF,0,27,65,13 - RTEXT "Volume PIM:",IDT_PIM,0,46,65,13,NOT WS_VISIBLE - LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,115,46,189,8,NOT WS_VISIBLE -END - -IDD_EXPAND_PROGRESS_DLG DIALOGEX 0, 0, 376, 283 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt Expander" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - RTEXT "Current size: ",IDT_CURRENT_SIZE,27,40,46,8 - CONTROL "",IDC_EXPAND_VOLUME_OLDSIZE,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,80,40,275,8,WS_EX_TRANSPARENT - RTEXT "New size: ",IDT_NEW_SIZE,28,52,45,8 - LTEXT "",IDC_EXPAND_VOLUME_NEWSIZE,80,52,275,8,0,WS_EX_TRANSPARENT - CONTROL "",IDC_PROGRESS_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,22,96,332,12 - RTEXT "",IDC_TIMEREMAIN,275,114,42,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE - RTEXT "",IDC_WRITESPEED,178,114,42,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE - LTEXT "",IDC_BYTESWRITTEN,77,114,39,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE - RTEXT "Done",IDT_DONE,53,115,22,8 - RTEXT "Speed",IDT_SPEED,142,115,34,8 - RTEXT "Left",IDT_LEFT,248,115,25,8 - GROUPBOX "",IDC_STATIC,15,84,346,49 - RTEXT "Volume: ",IDT_VOL_NAME,31,16,42,8 - GROUPBOX "",IDC_STATIC,15,7,346,72 - CONTROL "",IDC_EXPAND_VOLUME_NAME,"Static",SS_SIMPLE | WS_GROUP,80,16,275,8,WS_EX_TRANSPARENT - DEFPUSHBUTTON "Continue",IDOK,15,247,84,18 - PUSHBUTTON "Cancel",IDCANCEL,277,247,84,18 - EDITTEXT IDC_BOX_STATUS,15,176,346,66,ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY | ES_WANTRETURN | WS_VSCROLL - CONTROL "",IDC_EXPAND_VOLUME_INITSPACE,"Static",SS_SIMPLE | WS_GROUP,80,64,275,8,WS_EX_TRANSPARENT - RTEXT "Fill new space: ",IDT_INIT_SPACE,20,64,53,8 - RTEXT "File system: ",IDT_FILE_SYS,31,28,42,8 - CONTROL "",IDC_EXPAND_FILE_SYSTEM,"Static",SS_SIMPLE | WS_GROUP,80,28,275,8,WS_EX_TRANSPARENT - RTEXT "Random Pool: ",IDT_RANDOM_POOL2,20,144,53,8 - CONTROL "",IDC_RANDOM_BYTES,"Static",SS_SIMPLE | WS_GROUP,80,144,149,8,WS_EX_TRANSPARENT - CONTROL "Display pool content",IDC_DISPLAY_POOL_CONTENTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,236,142,125,12 - GROUPBOX "Randomness Collected From Mouse Movements",IDT_ENTROPY_BAR,20,156,214,18 - CONTROL "",IDC_ENTROPY_BAR,"msctls_progress32",WS_BORDER,31,165,193,6 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_SIZE_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 15 - RIGHTMARGIN, 361 - VERTGUIDE, 30 - TOPMARGIN, 14 - BOTTOMMARGIN, 256 - END - - IDD_MOUNT_DLG, DIALOG - BEGIN - RIGHTMARGIN, 369 - VERTGUIDE, 8 - BOTTOMMARGIN, 269 - END - - IDD_PASSWORD_DLG, DIALOG - BEGIN - BOTTOMMARGIN, 102 - END - - IDD_EXPAND_PROGRESS_DLG, DIALOG - BEGIN - RIGHTMARGIN, 361 - VERTGUIDE, 15 - VERTGUIDE, 73 - VERTGUIDE, 80 - VERTGUIDE, 355 - TOPMARGIN, 9 - BOTTOMMARGIN, 268 - HORZGUIDE, 176 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// HEADER -// - -IDR_MOUNT_RSRC_HEADER HEADER "resource.h" - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,17,22,0 - PRODUCTVERSION 1,17,22,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "IDRIX" - VALUE "FileDescription", "VeraCrypt Expander" - VALUE "FileVersion", "1.17" - VALUE "LegalTrademarks", "VeraCrypt" - VALUE "OriginalFilename", "VeraCryptExpander.exe" - VALUE "ProductName", "VeraCrypt" - VALUE "ProductVersion", "1.17" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "#include ""..\\\\common\\\\resource.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "#include ""..\\\\common\\\\common.rc""\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_LOGO_96DPI BITMAP "Logo_96dpi.bmp" -IDB_LOGO_288DPI BITMAP "Logo_288dpi.bmp" - -///////////////////////////////////////////////////////////////////////////// -// -// Menu -// - -IDR_MENU MENUEX -BEGIN - MENUITEM "About", IDM_ABOUT,MFT_STRING,MFS_ENABLED - MENUITEM "Homepage", IDM_HOMEPAGE,MFT_STRING | MFT_RIGHTJUSTIFY,MFS_ENABLED -END - - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE -BEGIN - IDS_UACSTRING "VeraCrypt Expander" -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// -#include "..\\common\\common.rc" - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" +#include "..\\common\\resource.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_SIZE_DIALOG DIALOGEX 0, 0, 376, 271 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt Expander" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + EDITTEXT IDC_SIZEBOX,30,102,109,14,ES_RIGHT | ES_AUTOHSCROLL | ES_NUMBER + CONTROL "&KB",IDC_KB,"Button",BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,169,105,38,10 + CONTROL "&MB",IDC_MB,"Button",BS_AUTORADIOBUTTON,209,105,38,10 + CONTROL "&GB",IDC_GB,"Button",BS_AUTORADIOBUTTON,248,105,38,10 + CONTROL "&TB",IDC_TB,"Button",BS_AUTORADIOBUTTON,288,105,38,10 + CONTROL "Fill new space with random data",IDC_INIT_NEWSPACE, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,30,127,118,10 + DEFPUSHBUTTON "Continue",IDOK,15,238,84,18 + PUSHBUTTON "Cancel",IDCANCEL,277,238,84,18 + LTEXT "Help Text",IDC_BOX_HELP,15,165,346,58,0,WS_EX_CLIENTEDGE + GROUPBOX "Enter new volume size",IDC_STATIC,15,83,346,63 + RTEXT "Current size: ",IDT_CURRENT_SIZE,27,42,46,8 + CONTROL "",IDC_EXPAND_VOLUME_OLDSIZE,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,80,42,275,8,WS_EX_TRANSPARENT + RTEXT "New size: ",IDT_NEW_SIZE,28,54,45,8 + LTEXT "",IDC_EXPAND_VOLUME_NEWSIZE,80,54,275,8,0,WS_EX_TRANSPARENT + RTEXT "Volume: ",IDT_VOL_NAME,31,18,42,8 + GROUPBOX "",IDC_STATIC,15,9,346,59 + CONTROL "",IDC_EXPAND_VOLUME_NAME,"Static",SS_SIMPLE | WS_GROUP,80,18,275,8,WS_EX_TRANSPARENT + RTEXT "File system: ",IDT_FILE_SYS,31,30,42,8 + CONTROL "",IDC_EXPAND_FILE_SYSTEM,"Static",SS_SIMPLE | WS_GROUP,80,30,275,8,WS_EX_TRANSPARENT +END + +IDD_MOUNT_DLG DIALOGEX 0, 0, 376, 271 +STYLE DS_SETFONT | DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt Expander" +MENU IDR_MENU +CLASS "VeraCryptCustomDlg" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + COMBOBOX IDC_VOLUME,56,192,212,74,CBS_DROPDOWN | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP + PUSHBUTTON "Select &File...",IDC_SELECT_FILE,276,192,84,14 + PUSHBUTTON "Select D&evice...",IDC_SELECT_DEVICE,276,211,84,14 + DEFPUSHBUTTON "Mount",IDOK,8,243,84,18,WS_GROUP + PUSHBUTTON "E&xit",IDC_EXIT,284,243,84,18,WS_GROUP + CONTROL 112,IDC_LOGO,"Static",SS_BITMAP | SS_NOTIFY | WS_BORDER,16,192,27,31 + GROUPBOX "Volume",IDT_VOLUME,8,179,360,53 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,1,0,373,147 + GROUPBOX "",IDC_STATIC,282,238,88,24 + GROUPBOX "",IDC_STATIC,6,238,88,24 + GROUPBOX "",IDC_STATIC,1,147,373,123,BS_CENTER + LTEXT "1. Select the VeraCrypt volume to be expanded\n2. Click the 'Mount' button",IDC_STATIC,15,156,293,21 + LTEXT "Static",IDC_INFOEXPAND,8,6,361,134,SS_NOPREFIX | SS_SUNKEN,WS_EX_STATICEDGE +END + +IDD_PASSWORD_DLG DIALOGEX 0, 0, 322, 107 +STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_VISIBLE | WS_CAPTION +CAPTION "Enter VeraCrypt Volume Password" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + EDITTEXT IDC_PASSWORD,69,8,166,14,ES_PASSWORD | ES_AUTOHSCROLL + COMBOBOX IDC_PKCS5_PRF_ID,69,26,86,90,CBS_DROPDOWNLIST | WS_TABSTOP + CONTROL "TrueCrypt Mode",IDC_TRUECRYPT_MODE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,159,28,76,10 + EDITTEXT IDC_PIM,69,43,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER | NOT WS_VISIBLE + CONTROL "Use P&IM",IDC_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,49,97,10 + CONTROL "Cache passwords and keyfil&es in memory",IDC_CACHE, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,62,153,10 + CONTROL "&Display password",IDC_SHOW_PASSWORD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,75,83,10 + CONTROL "U&se keyfiles",IDC_KEYFILES_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,88,83,11 + PUSHBUTTON "&Keyfiles...",IDC_KEY_FILES,171,86,64,14 + PUSHBUTTON "Mount Opti&ons...",IDC_MOUNT_OPTIONS,243,86,64,14 + DEFPUSHBUTTON "OK",IDOK,243,8,64,14 + PUSHBUTTON "Cancel",IDCANCEL,243,25,64,14 + RTEXT "Password:",IDT_PASSWORD,0,10,65,13 + RTEXT "PKCS-5 PRF:",IDT_PKCS5_PRF,0,27,65,13 + RTEXT "Volume PIM:",IDT_PIM,0,46,65,13,NOT WS_VISIBLE + LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,115,46,189,8,NOT WS_VISIBLE +END + +IDD_EXPAND_PROGRESS_DLG DIALOGEX 0, 0, 376, 283 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt Expander" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + RTEXT "Current size: ",IDT_CURRENT_SIZE,27,40,46,8 + CONTROL "",IDC_EXPAND_VOLUME_OLDSIZE,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,80,40,275,8,WS_EX_TRANSPARENT + RTEXT "New size: ",IDT_NEW_SIZE,28,52,45,8 + LTEXT "",IDC_EXPAND_VOLUME_NEWSIZE,80,52,275,8,0,WS_EX_TRANSPARENT + CONTROL "",IDC_PROGRESS_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,22,96,332,12 + RTEXT "",IDC_TIMEREMAIN,275,114,42,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE + RTEXT "",IDC_WRITESPEED,178,114,42,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE + LTEXT "",IDC_BYTESWRITTEN,77,114,39,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE + RTEXT "Done",IDT_DONE,53,115,22,8 + RTEXT "Speed",IDT_SPEED,142,115,34,8 + RTEXT "Left",IDT_LEFT,248,115,25,8 + GROUPBOX "",IDC_STATIC,15,84,346,49 + RTEXT "Volume: ",IDT_VOL_NAME,31,16,42,8 + GROUPBOX "",IDC_STATIC,15,7,346,72 + CONTROL "",IDC_EXPAND_VOLUME_NAME,"Static",SS_SIMPLE | WS_GROUP,80,16,275,8,WS_EX_TRANSPARENT + DEFPUSHBUTTON "Continue",IDOK,15,247,84,18 + PUSHBUTTON "Cancel",IDCANCEL,277,247,84,18 + EDITTEXT IDC_BOX_STATUS,15,176,346,66,ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY | ES_WANTRETURN | WS_VSCROLL + CONTROL "",IDC_EXPAND_VOLUME_INITSPACE,"Static",SS_SIMPLE | WS_GROUP,80,64,275,8,WS_EX_TRANSPARENT + RTEXT "Fill new space: ",IDT_INIT_SPACE,20,64,53,8 + RTEXT "File system: ",IDT_FILE_SYS,31,28,42,8 + CONTROL "",IDC_EXPAND_FILE_SYSTEM,"Static",SS_SIMPLE | WS_GROUP,80,28,275,8,WS_EX_TRANSPARENT + RTEXT "Random Pool: ",IDT_RANDOM_POOL2,20,144,53,8 + CONTROL "",IDC_RANDOM_BYTES,"Static",SS_SIMPLE | WS_GROUP,80,144,149,8,WS_EX_TRANSPARENT + CONTROL "Display pool content",IDC_DISPLAY_POOL_CONTENTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,236,142,125,12 + GROUPBOX "Randomness Collected From Mouse Movements",IDT_ENTROPY_BAR,20,156,214,18 + CONTROL "",IDC_ENTROPY_BAR,"msctls_progress32",WS_BORDER,31,165,193,6 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_SIZE_DIALOG, DIALOG + BEGIN + LEFTMARGIN, 15 + RIGHTMARGIN, 361 + VERTGUIDE, 30 + TOPMARGIN, 14 + BOTTOMMARGIN, 256 + END + + IDD_MOUNT_DLG, DIALOG + BEGIN + RIGHTMARGIN, 369 + VERTGUIDE, 8 + BOTTOMMARGIN, 269 + END + + IDD_PASSWORD_DLG, DIALOG + BEGIN + BOTTOMMARGIN, 102 + END + + IDD_EXPAND_PROGRESS_DLG, DIALOG + BEGIN + RIGHTMARGIN, 361 + VERTGUIDE, 15 + VERTGUIDE, 73 + VERTGUIDE, 80 + VERTGUIDE, 355 + TOPMARGIN, 9 + BOTTOMMARGIN, 268 + HORZGUIDE, 176 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// HEADER +// + +IDR_MOUNT_RSRC_HEADER HEADER "resource.h" + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,17,22,0 + PRODUCTVERSION 1,17,22,0 + FILEFLAGSMASK 0x17L +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "IDRIX" + VALUE "FileDescription", "VeraCrypt Expander" + VALUE "FileVersion", "1.17" + VALUE "LegalTrademarks", "VeraCrypt" + VALUE "OriginalFilename", "VeraCryptExpander.exe" + VALUE "ProductName", "VeraCrypt" + VALUE "ProductVersion", "1.17" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "#include ""..\\\\common\\\\resource.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "#include ""..\\\\common\\\\common.rc""\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Bitmap +// + +IDB_LOGO_96DPI BITMAP "Logo_96dpi.bmp" +IDB_LOGO_288DPI BITMAP "Logo_288dpi.bmp" + +///////////////////////////////////////////////////////////////////////////// +// +// Menu +// + +IDR_MENU MENUEX +BEGIN + MENUITEM "About", IDM_ABOUT,MFT_STRING,MFS_ENABLED + MENUITEM "Homepage", IDM_HOMEPAGE,MFT_STRING | MFT_RIGHTJUSTIFY,MFS_ENABLED +END + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE +BEGIN + IDS_UACSTRING "VeraCrypt Expander" +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#include "..\\common\\common.rc" + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/src/ExpandVolume/ExpandVolume.vcproj b/src/ExpandVolume/ExpandVolume.vcproj index 4ca6c9d9..37b6f461 100644 --- a/src/ExpandVolume/ExpandVolume.vcproj +++ b/src/ExpandVolume/ExpandVolume.vcproj @@ -1,977 +1,977 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ExpandVolume/InitDataArea.c b/src/ExpandVolume/InitDataArea.c index 43c7a312..4e6417be 100644 --- a/src/ExpandVolume/InitDataArea.c +++ b/src/ExpandVolume/InitDataArea.c @@ -1,17 +1,17 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' and also from the source code of extcv, which is Copyright (c) 2009-2010 Kih-Oskh - or Copyright (c) 2012-2013 Josef Schneider - - 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 + or Copyright (c) 2012-2013 Josef Schneider + + 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 @@ -32,8 +32,8 @@ #include "InitDataArea.h" -#ifndef SRC_POS -#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) +#ifndef SRC_POS +#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) #endif int FormatWriteBufferSize = 1024 * 1024; diff --git a/src/ExpandVolume/InitDataArea.h b/src/ExpandVolume/InitDataArea.h index 7650d00c..35c6bbd5 100644 --- a/src/ExpandVolume/InitDataArea.h +++ b/src/ExpandVolume/InitDataArea.h @@ -1,15 +1,15 @@ -/* - 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, and also derived from source code of extcv which - is Copyright (c) 2009-2010 by Kih-Oskh or Copyright (c) 2012-2013 Josef Schneider - - - 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. +/* + 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, and also derived from source code of extcv which + is Copyright (c) 2009-2010 by Kih-Oskh or Copyright (c) 2012-2013 Josef Schneider + + + 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. */ #ifndef TC_HEADER_InitDataArea diff --git a/src/ExpandVolume/WinMain.cpp b/src/ExpandVolume/WinMain.cpp index fb9d52af..630fc79d 100644 --- a/src/ExpandVolume/WinMain.cpp +++ b/src/ExpandVolume/WinMain.cpp @@ -1,17 +1,17 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' and also from the source code of extcv, which is Copyright (c) 2009-2010 Kih-Oskh - or Copyright (c) 2012-2013 Josef Schneider - - 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 + or Copyright (c) 2012-2013 Josef Schneider + + 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 "Tcdefs.h" @@ -383,32 +383,32 @@ static char *PasswordDialogTitleStringId; /* Except in response to the WM_INITDIALOG message, the dialog box procedure should return nonzero if it processes the message, and zero if it does not. - see DialogProc */ -BOOL CALLBACK ExtcvPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - static Password *szXPwd; - static int *pkcs5; - static int *pim; - static BOOL* truecryptMode; - - switch (msg) - { - case WM_INITDIALOG: - { - int i, nIndex; - szXPwd = ((PasswordDlgParam *) lParam) -> password; - pkcs5 = ((PasswordDlgParam *) lParam) -> pkcs5; - pim = ((PasswordDlgParam *) lParam) -> pim; - truecryptMode = ((PasswordDlgParam *) lParam) -> truecryptMode; - LocalizeDialog (hwndDlg, "IDD_PASSWORD_DLG"); - DragAcceptFiles (hwndDlg, TRUE); - - if (PasswordDialogTitleStringId) - { - SetWindowTextW (hwndDlg, GetString (PasswordDialogTitleStringId)); - } - else if (wcslen (PasswordDlgVolume) > 0) - { +BOOL CALLBACK ExtcvPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + static Password *szXPwd; + static int *pkcs5; + static int *pim; + static BOOL* truecryptMode; + + switch (msg) + { + case WM_INITDIALOG: + { + int i, nIndex; + szXPwd = ((PasswordDlgParam *) lParam) -> password; + pkcs5 = ((PasswordDlgParam *) lParam) -> pkcs5; + pim = ((PasswordDlgParam *) lParam) -> pim; + truecryptMode = ((PasswordDlgParam *) lParam) -> truecryptMode; + LocalizeDialog (hwndDlg, "IDD_PASSWORD_DLG"); + DragAcceptFiles (hwndDlg, TRUE); + + if (PasswordDialogTitleStringId) + { + SetWindowTextW (hwndDlg, GetString (PasswordDialogTitleStringId)); + } + else if (wcslen (PasswordDlgVolume) > 0) + { wchar_t s[1024]; const int maxVisibleLen = 40; @@ -420,359 +420,359 @@ BOOL CALLBACK ExtcvPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARA else StringCbPrintfW (s, sizeof(s), GetString ("ENTER_PASSWORD_FOR"), PasswordDlgVolume); - SetWindowTextW (hwndDlg, s); - } - - /* Populate the PRF algorithms list */ - HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - - nIndex = SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); - - for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) - { - nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); - } - - /* make autodetection the default */ - SendMessage (hComboBox, CB_SETCURSEL, 0, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_CACHE), BM_SETCHECK, bCacheInDriver ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, MAX_PIM, 0); - - SetPim (hwndDlg, IDC_PIM, *pim); - - /* make PIM field visible if a PIM value has been explicitely specified */ - if (*pim > 0) - { - ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); - } - - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); - - mountOptions.PartitionInInactiveSysEncScope = bPrebootPasswordDlgMode; - - if (bPrebootPasswordDlgMode) - { - SendMessage (hwndDlg, TC_APPMSG_PREBOOT_PASSWORD_MODE, 0, 0); - } - - if (PasswordDialogDisableMountOptions) - { - EnableWindow (GetDlgItem (hwndDlg, IDC_CACHE), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_MOUNT_OPTIONS), FALSE); - } - - /* No support for mounting TrueCrypt volumes */ - SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE); - - if (!SetForegroundWindow (hwndDlg) && (FavoriteMountOnArrivalInProgress)) - { - SetWindowPos (hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - - FLASHWINFO flash; - flash.cbSize = sizeof (flash); - flash.dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG; - flash.dwTimeout = 0; - flash.hwnd = hwndDlg; - flash.uCount = 0; - - FlashWindowEx (&flash); - - SetWindowPos (hwndDlg, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - } - } - return 0; - - case TC_APPMSG_PREBOOT_PASSWORD_MODE: - { - /* No support for mounting TrueCrypt system partition */ - SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE); - - /* Repopulate the PRF algorithms list with algorithms that support system encryption */ - HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - - int i, nIndex = SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); - - for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) - { - if (HashForSystemEncryption(i)) - { - nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); - } - } - - /* make autodetection the default */ - SendMessage (hComboBox, CB_SETCURSEL, 0, 0); - - ToBootPwdField (hwndDlg, IDC_PASSWORD); - - // Attempt to wipe the password stored in the input field buffer - wchar_t tmp[MAX_PASSWORD+1]; - wmemset (tmp, L'X', MAX_PASSWORD); - tmp [MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), L""); - - StringCbPrintfW (OrigKeyboardLayout, sizeof(OrigKeyboardLayout),L"%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF); - - DWORD keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); - - if (keybLayout != 0x00000409 && keybLayout != 0x04090409) - { - Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - if (SetTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0) - { - Error ("CANNOT_SET_TIMER", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - if (GetCheckBox (hwndDlg, IDC_SHOW_PASSWORD)) - { - // simulate hiding password - SetCheckBox (hwndDlg, IDC_SHOW_PASSWORD, FALSE); - - HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD, IDC_PASSWORD, IDC_PIM); - } - - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_ENABLE), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_KEY_FILES), FALSE); - - SetPim (hwndDlg, IDC_PIM, *pim); - - bPrebootPasswordDlgMode = TRUE; - } - return 1; - - case WM_TIMER: - switch (wParam) - { - case TIMER_ID_KEYB_LAYOUT_GUARD: - if (bPrebootPasswordDlgMode) - { - DWORD keybLayout = (DWORD) GetKeyboardLayout (NULL); - - if (keybLayout != 0x00000409 && keybLayout != 0x04090409) - { - // Keyboard layout is not standard US - - // Attempt to wipe the password stored in the input field buffer - wchar_t tmp[MAX_PASSWORD+1]; - wmemset (tmp, L'X', MAX_PASSWORD); - tmp [MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), L""); - - keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); - - if (keybLayout != 0x00000409 && keybLayout != 0x04090409) - { - KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); - Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - wchar_t szTmp [4096]; - StringCbCopyW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_CHANGE_PREVENTED")); - StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); - StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION")); - MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); - } - } - return 1; - } - return 0; - - case WM_COMMAND: - - if (lw == IDC_MOUNT_OPTIONS) - { - DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, - (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions); - - if (!bPrebootPasswordDlgMode && mountOptions.PartitionInInactiveSysEncScope) - SendMessage (hwndDlg, TC_APPMSG_PREBOOT_PASSWORD_MODE, 0, 0); - - return 1; - } - - if (lw == IDC_PIM_ENABLE) - { - ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); - - SetFocus (GetDlgItem (hwndDlg, IDC_PIM)); - return 1; - } - - if (lw == IDC_SHOW_PASSWORD) - { - HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD, IDC_PASSWORD, IDC_PIM); - return 1; - } - - if (lw == IDC_KEY_FILES) - { - KeyFilesDlgParam param; - param.EnableKeyFiles = KeyFilesEnable; - param.FirstKeyFile = FirstKeyFile; - - if (IDOK == DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, - (DLGPROC) KeyFilesDlgProc, (LPARAM) ¶m)) - { - KeyFilesEnable = param.EnableKeyFiles; - FirstKeyFile = param.FirstKeyFile; - - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); - } - - return 1; - } - - if (lw == IDC_KEYFILES_ENABLE) - { - KeyFilesEnable = GetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE); - - return 1; - } - - if (lw == IDCANCEL || lw == IDOK) - { - wchar_t tmp[MAX_PASSWORD+1]; - - if (lw == IDOK) - { - if (mountOptions.ProtectHiddenVolume && hidVolProtKeyFilesParam.EnableKeyFiles) - KeyFilesApply (hwndDlg, &mountOptions.ProtectedHidVolPassword, hidVolProtKeyFilesParam.FirstKeyFile, PasswordDlgVolume); - - if (GetPassword (hwndDlg, IDC_PASSWORD, (LPSTR) szXPwd->Text, MAX_PASSWORD + 1, TRUE)) - szXPwd->Length = strlen ((char *) szXPwd->Text); - else - return 1; - - bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_CACHE)); - *pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); - *truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); - - *pim = GetPim (hwndDlg, IDC_PIM); - - /* SHA-256 is not supported by TrueCrypt */ - if ( (*truecryptMode) - && ((*pkcs5 == SHA256) || (mountOptions.ProtectHiddenVolume && mountOptions.ProtectedHidVolPkcs5Prf == SHA256)) - ) - { - Error ("ALGO_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); - return 1; - } - - if ( (*truecryptMode) - && (*pim != 0) - ) - { - Error ("PIM_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); - return 1; - } - } - - // Attempt to wipe password stored in the input field buffer - wmemset (tmp, L'X', MAX_PASSWORD); - tmp[MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); - - if (hidVolProtKeyFilesParam.FirstKeyFile != NULL) - { - KeyFileRemoveAll (&hidVolProtKeyFilesParam.FirstKeyFile); - hidVolProtKeyFilesParam.EnableKeyFiles = FALSE; - } - - if (bPrebootPasswordDlgMode) - { - KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); - - // Restore the original keyboard layout - if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) - Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); - } - - EndDialog (hwndDlg, lw); - return 1; - } - return 0; - - case WM_CONTEXTMENU: - { - RECT buttonRect; - GetWindowRect (GetDlgItem (hwndDlg, IDC_KEY_FILES), &buttonRect); - - if (LOWORD (lParam) >= buttonRect.left && LOWORD (lParam) <= buttonRect.right - && HIWORD (lParam) >= buttonRect.top && HIWORD (lParam) <= buttonRect.bottom) - { - // The "Keyfiles" button has been right-clicked - - KeyFilesDlgParam param; - param.EnableKeyFiles = KeyFilesEnable; - param.FirstKeyFile = FirstKeyFile; - - POINT popupPos; - popupPos.x = buttonRect.left + 2; - popupPos.y = buttonRect.top + 2; - - if (KeyfilesPopupMenu (hwndDlg, popupPos, ¶m)) - { - KeyFilesEnable = param.EnableKeyFiles; - FirstKeyFile = param.FirstKeyFile; - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); - } - } - } - 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)); - FirstKeyFile = KeyFileAdd (FirstKeyFile, kf); - KeyFilesEnable = TRUE; - } - } - - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); - DragFinish (hdrop); - } - return 1; - } - - return 0; + SetWindowTextW (hwndDlg, s); + } + + /* Populate the PRF algorithms list */ + HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + + nIndex = SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); + + for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) + { + nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); + } + + /* make autodetection the default */ + SendMessage (hComboBox, CB_SETCURSEL, 0, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_CACHE), BM_SETCHECK, bCacheInDriver ? BST_CHECKED:BST_UNCHECKED, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, MAX_PIM, 0); + + SetPim (hwndDlg, IDC_PIM, *pim); + + /* make PIM field visible if a PIM value has been explicitely specified */ + if (*pim > 0) + { + ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); + } + + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); + + mountOptions.PartitionInInactiveSysEncScope = bPrebootPasswordDlgMode; + + if (bPrebootPasswordDlgMode) + { + SendMessage (hwndDlg, TC_APPMSG_PREBOOT_PASSWORD_MODE, 0, 0); + } + + if (PasswordDialogDisableMountOptions) + { + EnableWindow (GetDlgItem (hwndDlg, IDC_CACHE), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_MOUNT_OPTIONS), FALSE); + } + + /* No support for mounting TrueCrypt volumes */ + SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE); + + if (!SetForegroundWindow (hwndDlg) && (FavoriteMountOnArrivalInProgress)) + { + SetWindowPos (hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + + FLASHWINFO flash; + flash.cbSize = sizeof (flash); + flash.dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG; + flash.dwTimeout = 0; + flash.hwnd = hwndDlg; + flash.uCount = 0; + + FlashWindowEx (&flash); + + SetWindowPos (hwndDlg, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + } + return 0; + + case TC_APPMSG_PREBOOT_PASSWORD_MODE: + { + /* No support for mounting TrueCrypt system partition */ + SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE); + + /* Repopulate the PRF algorithms list with algorithms that support system encryption */ + HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + + int i, nIndex = SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); + + for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) + { + if (HashForSystemEncryption(i)) + { + nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); + } + } + + /* make autodetection the default */ + SendMessage (hComboBox, CB_SETCURSEL, 0, 0); + + ToBootPwdField (hwndDlg, IDC_PASSWORD); + + // Attempt to wipe the password stored in the input field buffer + wchar_t tmp[MAX_PASSWORD+1]; + wmemset (tmp, L'X', MAX_PASSWORD); + tmp [MAX_PASSWORD] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), L""); + + StringCbPrintfW (OrigKeyboardLayout, sizeof(OrigKeyboardLayout),L"%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF); + + DWORD keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); + + if (keybLayout != 0x00000409 && keybLayout != 0x04090409) + { + Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + if (SetTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0) + { + Error ("CANNOT_SET_TIMER", hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + if (GetCheckBox (hwndDlg, IDC_SHOW_PASSWORD)) + { + // simulate hiding password + SetCheckBox (hwndDlg, IDC_SHOW_PASSWORD, FALSE); + + HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD, IDC_PASSWORD, IDC_PIM); + } + + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_ENABLE), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_KEY_FILES), FALSE); + + SetPim (hwndDlg, IDC_PIM, *pim); + + bPrebootPasswordDlgMode = TRUE; + } + return 1; + + case WM_TIMER: + switch (wParam) + { + case TIMER_ID_KEYB_LAYOUT_GUARD: + if (bPrebootPasswordDlgMode) + { + DWORD keybLayout = (DWORD) GetKeyboardLayout (NULL); + + if (keybLayout != 0x00000409 && keybLayout != 0x04090409) + { + // Keyboard layout is not standard US + + // Attempt to wipe the password stored in the input field buffer + wchar_t tmp[MAX_PASSWORD+1]; + wmemset (tmp, L'X', MAX_PASSWORD); + tmp [MAX_PASSWORD] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), L""); + + keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); + + if (keybLayout != 0x00000409 && keybLayout != 0x04090409) + { + KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); + Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + wchar_t szTmp [4096]; + StringCbCopyW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_CHANGE_PREVENTED")); + StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); + StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION")); + MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); + } + } + return 1; + } + return 0; + + case WM_COMMAND: + + if (lw == IDC_MOUNT_OPTIONS) + { + DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, + (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions); + + if (!bPrebootPasswordDlgMode && mountOptions.PartitionInInactiveSysEncScope) + SendMessage (hwndDlg, TC_APPMSG_PREBOOT_PASSWORD_MODE, 0, 0); + + return 1; + } + + if (lw == IDC_PIM_ENABLE) + { + ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); + + SetFocus (GetDlgItem (hwndDlg, IDC_PIM)); + return 1; + } + + if (lw == IDC_SHOW_PASSWORD) + { + HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD, IDC_PASSWORD, IDC_PIM); + return 1; + } + + if (lw == IDC_KEY_FILES) + { + KeyFilesDlgParam param; + param.EnableKeyFiles = KeyFilesEnable; + param.FirstKeyFile = FirstKeyFile; + + if (IDOK == DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, + (DLGPROC) KeyFilesDlgProc, (LPARAM) ¶m)) + { + KeyFilesEnable = param.EnableKeyFiles; + FirstKeyFile = param.FirstKeyFile; + + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); + } + + return 1; + } + + if (lw == IDC_KEYFILES_ENABLE) + { + KeyFilesEnable = GetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE); + + return 1; + } + + if (lw == IDCANCEL || lw == IDOK) + { + wchar_t tmp[MAX_PASSWORD+1]; + + if (lw == IDOK) + { + if (mountOptions.ProtectHiddenVolume && hidVolProtKeyFilesParam.EnableKeyFiles) + KeyFilesApply (hwndDlg, &mountOptions.ProtectedHidVolPassword, hidVolProtKeyFilesParam.FirstKeyFile, PasswordDlgVolume); + + if (GetPassword (hwndDlg, IDC_PASSWORD, (LPSTR) szXPwd->Text, MAX_PASSWORD + 1, TRUE)) + szXPwd->Length = strlen ((char *) szXPwd->Text); + else + return 1; + + bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_CACHE)); + *pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); + *truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); + + *pim = GetPim (hwndDlg, IDC_PIM); + + /* SHA-256 is not supported by TrueCrypt */ + if ( (*truecryptMode) + && ((*pkcs5 == SHA256) || (mountOptions.ProtectHiddenVolume && mountOptions.ProtectedHidVolPkcs5Prf == SHA256)) + ) + { + Error ("ALGO_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); + return 1; + } + + if ( (*truecryptMode) + && (*pim != 0) + ) + { + Error ("PIM_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); + return 1; + } + } + + // Attempt to wipe password stored in the input field buffer + wmemset (tmp, L'X', MAX_PASSWORD); + tmp[MAX_PASSWORD] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); + + if (hidVolProtKeyFilesParam.FirstKeyFile != NULL) + { + KeyFileRemoveAll (&hidVolProtKeyFilesParam.FirstKeyFile); + hidVolProtKeyFilesParam.EnableKeyFiles = FALSE; + } + + if (bPrebootPasswordDlgMode) + { + KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); + + // Restore the original keyboard layout + if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) + Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); + } + + EndDialog (hwndDlg, lw); + return 1; + } + return 0; + + case WM_CONTEXTMENU: + { + RECT buttonRect; + GetWindowRect (GetDlgItem (hwndDlg, IDC_KEY_FILES), &buttonRect); + + if (LOWORD (lParam) >= buttonRect.left && LOWORD (lParam) <= buttonRect.right + && HIWORD (lParam) >= buttonRect.top && HIWORD (lParam) <= buttonRect.bottom) + { + // The "Keyfiles" button has been right-clicked + + KeyFilesDlgParam param; + param.EnableKeyFiles = KeyFilesEnable; + param.FirstKeyFile = FirstKeyFile; + + POINT popupPos; + popupPos.x = buttonRect.left + 2; + popupPos.y = buttonRect.top + 2; + + if (KeyfilesPopupMenu (hwndDlg, popupPos, ¶m)) + { + KeyFilesEnable = param.EnableKeyFiles; + FirstKeyFile = param.FirstKeyFile; + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); + } + } + } + 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)); + FirstKeyFile = KeyFileAdd (FirstKeyFile, kf); + KeyFilesEnable = TRUE; + } + } + + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); + DragFinish (hdrop); + } + return 1; + } + + return 0; } void SaveSettings (HWND hwndDlg) @@ -792,36 +792,36 @@ int RestoreVolumeHeader (HWND hwndDlg, char *lpszVolume) return 0; } -int ExtcvAskVolumePassword (HWND hwndDlg, const wchar_t* fileName, Password *password, int *pkcs5, int *pim, BOOL* truecryptMode, char *titleStringId, BOOL enableMountOptions) -{ - int result; - PasswordDlgParam dlgParam; - - PasswordDialogTitleStringId = titleStringId; - PasswordDialogDisableMountOptions = !enableMountOptions; - - dlgParam.password = password; - dlgParam.pkcs5 = pkcs5; - dlgParam.pim = pim; - dlgParam.truecryptMode = truecryptMode; - - StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume), fileName); - - result = DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_PASSWORD_DLG), hwndDlg, - (DLGPROC) ExtcvPasswordDlgProc, (LPARAM) &dlgParam); - - if (result != IDOK) - { - password->Length = 0; - *pkcs5 = 0; - *pim = 0; - *truecryptMode = FALSE; - burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); - burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); - } - - return result == IDOK; +int ExtcvAskVolumePassword (HWND hwndDlg, const wchar_t* fileName, Password *password, int *pkcs5, int *pim, BOOL* truecryptMode, char *titleStringId, BOOL enableMountOptions) +{ + int result; + PasswordDlgParam dlgParam; + + PasswordDialogTitleStringId = titleStringId; + PasswordDialogDisableMountOptions = !enableMountOptions; + + dlgParam.password = password; + dlgParam.pkcs5 = pkcs5; + dlgParam.pim = pim; + dlgParam.truecryptMode = truecryptMode; + + StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume), fileName); + + result = DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_PASSWORD_DLG), hwndDlg, + (DLGPROC) ExtcvPasswordDlgProc, (LPARAM) &dlgParam); + + if (result != IDOK) + { + password->Length = 0; + *pkcs5 = 0; + *pim = 0; + *truecryptMode = FALSE; + burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); + burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); + } + + return result == IDOK; } // GUI actions @@ -839,7 +839,7 @@ static BOOL SelectContainer (HWND hwndDlg) static BOOL SelectPartition (HWND hwndDlg) { - RawDevicesDlgParam param; + RawDevicesDlgParam param; param.pszFileName = szFileName; int nResult = DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_RAWDEVICES_DLG), hwndDlg, (DLGPROC) RawDevicesDlgProc, (LPARAM) & param); diff --git a/src/ExpandVolume/resource.h b/src/ExpandVolume/resource.h index 741e78ac..42b9f2b4 100644 --- a/src/ExpandVolume/resource.h +++ b/src/ExpandVolume/resource.h @@ -1,147 +1,147 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by ExpandVolume.rc -// -#define IDD_MOUNT_DLG 101 -#define IDD_PASSWORD_DLG 104 -#define IDR_MENU 106 -#define IDD_EXPAND_PROGRESS_DLG 106 -#define IDR_MOUNT_RSRC_HEADER 109 -#define IDS_UACSTRING 110 -#define IDB_LOGO_288DPI 111 -#define IDB_LOGO_96DPI 112 -#define IDD_SIZE_DIALOG 117 -#define IDC_BOX_HELP 1003 -#define IDC_CACHE 1005 -#define IDC_NO_HISTORY 1006 -#define IDC_DRIVELIST 1007 -#define IDC_SPACE_LEFT 1009 -#define IDC_KB 1011 -#define IDC_MB 1013 -#define IDC_PROGRESS_BAR 1014 -#define IDC_GB 1015 -#define IDC_TB 1016 -#define IDC_EXPAND_VOLUME_OLDSIZE 1017 -#define IDC_EXPAND_VOLUME_NEWSIZE 1019 -#define IDC_EXPAND_VOLUME_NAME 1020 -#define IDC_EXPAND_VOLUME_INITSPACE 1021 -#define IDC_EXPAND_FILE_SYSTEM 1022 -#define IDC_RANDOM_BYTES 1023 -#define IDC_BYTESWRITTEN 1024 -#define IDC_WRITESPEED 1025 -#define IDC_MOUNT_OPTIONS 1026 -#define IDC_TIMEREMAIN 1027 -#define IDC_KEY_FILES 1030 -#define IDC_VOLUME 1033 -#define IDC_PASSWORD 1034 -#define IDC_SELECT_DEVICE 1036 -#define IDC_CREATE_VOLUME 1037 -#define IDC_VOLUME_TOOLS 1038 -#define IDC_SIZEBOX 1038 -#define IDC_WIPE_CACHE 1039 -#define IDC_MOUNTALL 1040 -#define IDC_SELECT_FILE 1042 -#define IDC_VOLUME_PROPERTIES 1044 -#define IDT_RANDOM_POOL 1047 -#define IDT_VOL_NAME 1047 -#define IDT_HEADER_KEY 1048 -#define IDT_CURRENT_SIZE 1048 -#define IDT_VOLUME 1049 -#define IDT_MASTER_KEY 1049 -#define IDT_NEW_SIZE 1049 -#define IDT_PASSWORD 1050 -#define IDT_DONE 1050 -#define IDT_SPEED 1051 -#define IDT_LEFT 1052 -#define IDT_INIT_SPACE 1053 -#define IDT_FILE_SYS 1054 -#define IDT_INIT_SPACE2 1055 -#define IDT_RANDOM_POOL2 1055 -#define IDC_EXIT 1060 -#define IDC_UNMOUNTALL 1063 -#define IDC_SHOW_PASSWORD 1094 -#define IDC_LOGO 1095 -#define IDC_SIZEDLG_TITLE 1111 -#define IDC_INIT_NEWSPACE 1112 -#define IDC_INFOEXPAND 1113 -#define IDC_BOX_STATUS 1114 -#define IDC_TRUECRYPT_MODE 1140 -#define IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT 1141 -#define IDT_OLD_PIM 1142 -#define IDC_OLD_PIM 1143 -#define IDC_OLD_PIM_HELP 1144 -#define ID_HOMEPAGE 1145 -#define IDM_HELP 40001 -#define IDM_ABOUT 40002 -#define IDM_UNMOUNT_VOLUME 40003 -#define IDM_CLEAR_HISTORY 40004 -#define IDM_FORUMS 40005 -#define IDM_BENCHMARK 40006 -#define IDM_TRAVELER 40007 -#define IDM_MOUNT_VOLUME_OPTIONS 40008 -#define IDM_FAQ 40009 -#define IDM_REFRESH_DRIVE_LETTERS 40010 -#define IDM_DEFAULT_KEYFILES 40011 -#define IDM_WEBSITE 40012 -#define IDM_MOUNTALL 40013 -#define IDM_UNMOUNTALL 40014 -#define IDM_MOUNT_VOLUME 40015 -#define IDM_CHANGE_PASSWORD 40016 -#define IDM_VOLUME_WIZARD 40017 -#define IDM_CREATE_VOLUME 40018 -#define IDM_WIPE_CACHE 40019 -#define IDM_PREFERENCES 40020 -#define IDM_LICENSE 40021 -#define IDM_SELECT_FILE 40022 -#define IDM_SELECT_DEVICE 40023 -#define IDM_VOLUME_PROPERTIES 40024 -#define IDM_LANGUAGE 40025 -#define IDM_MOUNT_FAVORITE_VOLUMES 40026 -#define IDM_SAVE_FAVORITE_VOLUMES 40027 -#define IDM_BACKUP_VOL_HEADER 40028 -#define IDM_RESTORE_VOL_HEADER 40029 -#define IDM_HOTKEY_SETTINGS 40030 -#define IDM_TC_DOWNLOADS 40031 -#define IDM_NEWS 40032 -#define IDM_BUGREPORT 40033 -#define IDM_CONTACT 40034 -#define IDM_VERSION_HISTORY 40035 -#define IDM_HOMEPAGE 40036 -#define IDM_TEST_VECTORS 40037 -#define IDM_ADD_REMOVE_VOL_KEYFILES 40038 -#define IDM_REMOVE_ALL_KEYFILES_FROM_VOL 40039 -#define IDM_GENERATE_KEYFILE 40040 -#define IDM_CHANGE_HEADER_KEY_DERIV_ALGO 40041 -#define IDM_KEYFILE_GENERATOR 40042 -#define IDM_SET_DEFAULT_KEYFILES 40043 -#define IDM_ONLINE_TUTORIAL 40044 -#define IDM_ONLINE_HELP 40045 -#define IDM_DONATIONS 40046 -#define IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO 40047 -#define IDM_CHANGE_SYS_PASSWORD 40048 -#define IDM_CREATE_RESCUE_DISK 40049 -#define IDM_PERMANENTLY_DECRYPT_SYS 40050 -#define IDM_VERIFY_RESCUE_DISK 40051 -#define IDM_SYSTEM_ENCRYPTION_STATUS 40052 -#define IDM_ENCRYPT_SYSTEM_DEVICE 40053 -#define IDM_SYSENC_RESUME 40054 -#define IDM_MOUNT_SYSENC_PART_WITHOUT_PBA 40055 -#define IDM_CREATE_HIDDEN_OS 40056 -#define IDM_TOKEN_PREFERENCES 40057 -#define IDM_CLOSE_ALL_TOKEN_SESSIONS 40058 -#define IDM_SYS_ENC_SETTINGS 40059 -#define IDM_SYSENC_SETTINGS 40060 -#define IDM_RESUME_INTERRUPTED_PROC 40061 -#define IDM_MANAGE_TOKEN_KEYFILES 40062 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NO_MFC 1 -#define _APS_NEXT_RESOURCE_VALUE 120 -#define _APS_NEXT_COMMAND_VALUE 40064 -#define _APS_NEXT_CONTROL_VALUE 1146 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by ExpandVolume.rc +// +#define IDD_MOUNT_DLG 101 +#define IDD_PASSWORD_DLG 104 +#define IDR_MENU 106 +#define IDD_EXPAND_PROGRESS_DLG 106 +#define IDR_MOUNT_RSRC_HEADER 109 +#define IDS_UACSTRING 110 +#define IDB_LOGO_288DPI 111 +#define IDB_LOGO_96DPI 112 +#define IDD_SIZE_DIALOG 117 +#define IDC_BOX_HELP 1003 +#define IDC_CACHE 1005 +#define IDC_NO_HISTORY 1006 +#define IDC_DRIVELIST 1007 +#define IDC_SPACE_LEFT 1009 +#define IDC_KB 1011 +#define IDC_MB 1013 +#define IDC_PROGRESS_BAR 1014 +#define IDC_GB 1015 +#define IDC_TB 1016 +#define IDC_EXPAND_VOLUME_OLDSIZE 1017 +#define IDC_EXPAND_VOLUME_NEWSIZE 1019 +#define IDC_EXPAND_VOLUME_NAME 1020 +#define IDC_EXPAND_VOLUME_INITSPACE 1021 +#define IDC_EXPAND_FILE_SYSTEM 1022 +#define IDC_RANDOM_BYTES 1023 +#define IDC_BYTESWRITTEN 1024 +#define IDC_WRITESPEED 1025 +#define IDC_MOUNT_OPTIONS 1026 +#define IDC_TIMEREMAIN 1027 +#define IDC_KEY_FILES 1030 +#define IDC_VOLUME 1033 +#define IDC_PASSWORD 1034 +#define IDC_SELECT_DEVICE 1036 +#define IDC_CREATE_VOLUME 1037 +#define IDC_VOLUME_TOOLS 1038 +#define IDC_SIZEBOX 1038 +#define IDC_WIPE_CACHE 1039 +#define IDC_MOUNTALL 1040 +#define IDC_SELECT_FILE 1042 +#define IDC_VOLUME_PROPERTIES 1044 +#define IDT_RANDOM_POOL 1047 +#define IDT_VOL_NAME 1047 +#define IDT_HEADER_KEY 1048 +#define IDT_CURRENT_SIZE 1048 +#define IDT_VOLUME 1049 +#define IDT_MASTER_KEY 1049 +#define IDT_NEW_SIZE 1049 +#define IDT_PASSWORD 1050 +#define IDT_DONE 1050 +#define IDT_SPEED 1051 +#define IDT_LEFT 1052 +#define IDT_INIT_SPACE 1053 +#define IDT_FILE_SYS 1054 +#define IDT_INIT_SPACE2 1055 +#define IDT_RANDOM_POOL2 1055 +#define IDC_EXIT 1060 +#define IDC_UNMOUNTALL 1063 +#define IDC_SHOW_PASSWORD 1094 +#define IDC_LOGO 1095 +#define IDC_SIZEDLG_TITLE 1111 +#define IDC_INIT_NEWSPACE 1112 +#define IDC_INFOEXPAND 1113 +#define IDC_BOX_STATUS 1114 +#define IDC_TRUECRYPT_MODE 1140 +#define IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT 1141 +#define IDT_OLD_PIM 1142 +#define IDC_OLD_PIM 1143 +#define IDC_OLD_PIM_HELP 1144 +#define ID_HOMEPAGE 1145 +#define IDM_HELP 40001 +#define IDM_ABOUT 40002 +#define IDM_UNMOUNT_VOLUME 40003 +#define IDM_CLEAR_HISTORY 40004 +#define IDM_FORUMS 40005 +#define IDM_BENCHMARK 40006 +#define IDM_TRAVELER 40007 +#define IDM_MOUNT_VOLUME_OPTIONS 40008 +#define IDM_FAQ 40009 +#define IDM_REFRESH_DRIVE_LETTERS 40010 +#define IDM_DEFAULT_KEYFILES 40011 +#define IDM_WEBSITE 40012 +#define IDM_MOUNTALL 40013 +#define IDM_UNMOUNTALL 40014 +#define IDM_MOUNT_VOLUME 40015 +#define IDM_CHANGE_PASSWORD 40016 +#define IDM_VOLUME_WIZARD 40017 +#define IDM_CREATE_VOLUME 40018 +#define IDM_WIPE_CACHE 40019 +#define IDM_PREFERENCES 40020 +#define IDM_LICENSE 40021 +#define IDM_SELECT_FILE 40022 +#define IDM_SELECT_DEVICE 40023 +#define IDM_VOLUME_PROPERTIES 40024 +#define IDM_LANGUAGE 40025 +#define IDM_MOUNT_FAVORITE_VOLUMES 40026 +#define IDM_SAVE_FAVORITE_VOLUMES 40027 +#define IDM_BACKUP_VOL_HEADER 40028 +#define IDM_RESTORE_VOL_HEADER 40029 +#define IDM_HOTKEY_SETTINGS 40030 +#define IDM_TC_DOWNLOADS 40031 +#define IDM_NEWS 40032 +#define IDM_BUGREPORT 40033 +#define IDM_CONTACT 40034 +#define IDM_VERSION_HISTORY 40035 +#define IDM_HOMEPAGE 40036 +#define IDM_TEST_VECTORS 40037 +#define IDM_ADD_REMOVE_VOL_KEYFILES 40038 +#define IDM_REMOVE_ALL_KEYFILES_FROM_VOL 40039 +#define IDM_GENERATE_KEYFILE 40040 +#define IDM_CHANGE_HEADER_KEY_DERIV_ALGO 40041 +#define IDM_KEYFILE_GENERATOR 40042 +#define IDM_SET_DEFAULT_KEYFILES 40043 +#define IDM_ONLINE_TUTORIAL 40044 +#define IDM_ONLINE_HELP 40045 +#define IDM_DONATIONS 40046 +#define IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO 40047 +#define IDM_CHANGE_SYS_PASSWORD 40048 +#define IDM_CREATE_RESCUE_DISK 40049 +#define IDM_PERMANENTLY_DECRYPT_SYS 40050 +#define IDM_VERIFY_RESCUE_DISK 40051 +#define IDM_SYSTEM_ENCRYPTION_STATUS 40052 +#define IDM_ENCRYPT_SYSTEM_DEVICE 40053 +#define IDM_SYSENC_RESUME 40054 +#define IDM_MOUNT_SYSENC_PART_WITHOUT_PBA 40055 +#define IDM_CREATE_HIDDEN_OS 40056 +#define IDM_TOKEN_PREFERENCES 40057 +#define IDM_CLOSE_ALL_TOKEN_SESSIONS 40058 +#define IDM_SYS_ENC_SETTINGS 40059 +#define IDM_SYSENC_SETTINGS 40060 +#define IDM_RESUME_INTERRUPTED_PROC 40061 +#define IDM_MANAGE_TOKEN_KEYFILES 40062 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NO_MFC 1 +#define _APS_NEXT_RESOURCE_VALUE 120 +#define _APS_NEXT_COMMAND_VALUE 40064 +#define _APS_NEXT_CONTROL_VALUE 1146 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/src/Format/Format.manifest b/src/Format/Format.manifest index 255a867e..5d4cb896 100644 --- a/src/Format/Format.manifest +++ b/src/Format/Format.manifest @@ -1,33 +1,33 @@ - - - - - - - - - - - - true - - - - - - - - - - - - - + + + + + + + + + + + + true + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Format/Format.rc b/src/Format/Format.rc index 9e13a29b..1f2cc41d 100644 --- a/src/Format/Format.rc +++ b/src/Format/Format.rc @@ -1,747 +1,747 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" -#include "..\\common\\resource.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,17,22,0 - PRODUCTVERSION 1,17,22,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "IDRIX" - VALUE "FileDescription", "VeraCrypt Format" - VALUE "FileVersion", "1.17" - VALUE "LegalTrademarks", "VeraCrypt" - VALUE "OriginalFilename", "VeraCrypt Format.exe" - VALUE "ProductName", "VeraCrypt" - VALUE "ProductVersion", "1.17" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - - -///////////////////////////////////////////////////////////////////////////// -// -// HEADER -// - -IDR_FORMAT_RSRC_HEADER HEADER "resource.h" - -///////////////////////////////////////////////////////////////////////////// -// -// TYPELIB -// - -IDR_FORMAT_TLB TYPELIB "Format.tlb" - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_VOL_CREATION_WIZARD_DLG DIALOGEX 0, 0, 400, 229 -STYLE DS_SETFONT | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt Volume Creation Wizard" -CLASS "VeraCryptCustomDlg" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - PUSHBUTTON "&Help",IDHELP,176,209,50,14 - PUSHBUTTON "",IDC_PREV,235,209,50,14 - DEFPUSHBUTTON "",IDC_NEXT,285,209,50,14 - PUSHBUTTON "Cancel",IDCANCEL,343,209,50,14 - LTEXT "",IDC_BOX_TITLE,160,8,233,17 - GROUPBOX "",IDC_STATIC,4,0,392,203 - CONTROL 116,IDC_BITMAP_WIZARD,"Static",SS_BITMAP | SS_SUNKEN,10,9,137,169 - LTEXT "",IDC_POS_BOX,160,24,231,172 -END - -IDD_CIPHER_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - COMBOBOX IDC_COMBO_BOX,7,23,137,126,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP - PUSHBUTTON "&Test",IDC_CIPHER_TEST,149,22,59,14 - PUSHBUTTON "&Benchmark",IDC_BENCHMARK,149,100,59,14 - COMBOBOX IDC_COMBO_BOX_HASH_ALGO,7,137,83,126,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP - LTEXT "",IDC_BOX_HELP,7,40,205,58 - GROUPBOX "Encryption Algorithm",IDT_ENCRYPTION_ALGO,0,10,217,111 - GROUPBOX "Hash Algorithm",IDT_HASH_ALGO,0,124,217,35 - LTEXT "More information",IDC_LINK_MORE_INFO_ABOUT_CIPHER,7,102,135,10,SS_NOTIFY - LTEXT "Information on hash algorithms",IDC_LINK_HASH_INFO,97,139,115,8,SS_NOTIFY -END - -IDD_PASSWORD_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - EDITTEXT IDC_PASSWORD,53,3,170,14,ES_PASSWORD | ES_AUTOHSCROLL - EDITTEXT IDC_VERIFY,53,19,170,14,ES_PASSWORD | ES_AUTOHSCROLL - CONTROL "U&se keyfiles",IDC_KEYFILES_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,53,35,95,10 - PUSHBUTTON "&Keyfiles...",IDC_KEY_FILES,152,36,71,14,WS_DISABLED - CONTROL "&Display password",IDC_SHOW_PASSWORD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,53,45,95,11,WS_EX_TRANSPARENT - CONTROL "Use P&IM",IDC_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,53,56,97,10 - RTEXT "Password:",IDT_PASSWORD,1,6,50,8 - RTEXT "&Confirm:",IDT_CONFIRM,1,23,50,8 - LTEXT "",IDC_BOX_HELP,0,71,225,97 -END - -IDD_SIZE_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - EDITTEXT IDC_SIZEBOX,0,22,71,14,ES_AUTOHSCROLL | ES_NUMBER - CONTROL "&KB",IDC_KB,"Button",BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,80,25,27,10 - CONTROL "&MB",IDC_MB,"Button",BS_AUTORADIOBUTTON,115,25,27,10 - CONTROL "&GB",IDC_GB,"Button",BS_AUTORADIOBUTTON,150,25,27,10 - LTEXT "",IDC_BOX_HELP,0,84,214,75 - LTEXT "",IDC_SPACE_LEFT,0,44,214,33 - CONTROL "&TB",IDC_TB,"Button",BS_AUTORADIOBUTTON,185,25,27,10 -END - -IDD_VOLUME_LOCATION_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - COMBOBOX IDC_COMBO_BOX,0,9,148,80,CBS_DROPDOWN | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP - CONTROL "&Never save history",IDC_NO_HISTORY,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,3,28,213,10 - PUSHBUTTON "",IDC_SELECT_VOLUME_LOCATION,155,9,62,14 - LTEXT "",IDC_BOX_HELP,0,42,219,125 -END - -IDD_FORMAT_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - COMBOBOX IDC_FILESYS,43,13,36,90,CBS_DROPDOWNLIST | WS_TABSTOP - COMBOBOX IDC_CLUSTERSIZE,112,13,42,90,CBS_DROPDOWNLIST | WS_TABSTOP - CONTROL "Quick Format",IDC_QUICKFORMAT,"Button",BS_AUTOCHECKBOX | BS_MULTILINE | WS_TABSTOP,163,11,60,18 - CONTROL "",IDC_SHOW_KEYS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,214,38,9,8 - PUSHBUTTON "Abort",IDC_ABORT_BUTTON,169,75,50,14 - RTEXT "Header Key: ",IDT_HEADER_KEY,2,47,54,8 - CONTROL "",IDC_HEADER_KEY,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,57,46,163,8,WS_EX_TRANSPARENT - RTEXT "Master Key: ",IDT_MASTER_KEY,2,55,54,8 - LTEXT "",IDC_DISK_KEY,57,54,163,8,0,WS_EX_TRANSPARENT - RTEXT "Cluster ",IDT_CLUSTER,80,15,32,8 - LTEXT "",IDC_BOX_HELP,1,112,224,40 - GROUPBOX "Options",IDT_FORMAT_OPTIONS,0,3,225,29 - CONTROL "",IDC_PROGRESS_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,6,76,158,12 - RTEXT "",IDC_TIMEREMAIN,177,93,42,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE - RTEXT "",IDC_WRITESPEED,106,93,42,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE - LTEXT "",IDC_BYTESWRITTEN,29,93,39,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE - RTEXT "Done",IDT_DONE,5,94,22,8 - RTEXT "Speed",IDT_SPEED,70,94,34,8 - RTEXT "Left",IDT_LEFT,150,94,25,8 - GROUPBOX "",IDC_STATIC,0,67,225,41 - RTEXT "Filesystem ",IDT_FILESYSTEM,1,15,41,8,0,WS_EX_RIGHT - RTEXT "Random Pool: ",IDT_RANDOM_POOL,2,39,54,8 - GROUPBOX "",IDC_STATIC,0,32,225,35 - CONTROL "",IDC_RANDOM_BYTES,"Static",SS_SIMPLE | WS_GROUP,57,38,155,8,WS_EX_TRANSPARENT - GROUPBOX "Randomness Collected From Mouse Movements",IDT_ENTROPY_BAR,0,153,224,18 - CONTROL "",IDC_ENTROPY_BAR,"msctls_progress32",WS_BORDER,11,162,202,6 -END - -IDD_INTRO_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "Create an encrypted file container",IDC_FILE_CONTAINER, - "Button",BS_AUTORADIOBUTTON,0,7,217,10 - LTEXT "More information",IDC_MORE_INFO_ON_CONTAINERS,16,40,165,10,SS_NOTIFY - CONTROL "Encrypt a non-system partition/drive",IDC_NONSYS_DEVICE, - "Button",BS_AUTORADIOBUTTON,0,53,217,10 - CONTROL "Encrypt the system partition or entire system drive",IDC_SYS_DEVICE, - "Button",BS_AUTORADIOBUTTON,0,89,217,10 - LTEXT "More information about system encryption",IDC_MORE_INFO_ON_SYS_ENCRYPTION,16,153,190,10,SS_NOTIFY - LTEXT "Creates a virtual encrypted disk within a file. Recommended for inexperienced users.",IDT_FILE_CONTAINER,16,20,205,16 - LTEXT "Encrypts a non-system partition on any internal or external drive (e.g. a flash drive). Optionally, creates a hidden volume.",IDT_NON_SYS_DEVICE,16,66,205,20 - LTEXT "Encrypts the partition/drive where Windows is installed. Anyone who wants to gain access and use the system, read and write files, etc., will need to enter the correct password each time before Windows boots. Optionally, creates a hidden system.",IDT_SYS_DEVICE,16,102,205,47 -END - -IDD_INFO_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - LTEXT "",IDC_BOX_HELP,0,10,225,155 -END - -IDD_HIDVOL_HOST_FILL_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - LTEXT "",IDC_BOX_HELP,0,6,226,138 - PUSHBUTTON "Open Outer Volume",IDC_OPEN_OUTER_VOLUME,0,146,85,14 -END - -IDD_HIDDEN_VOL_WIZARD_MODE_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "Normal mode",IDC_HIDVOL_WIZ_MODE_FULL,"Button",BS_AUTORADIOBUTTON,0,7,217,10 - CONTROL "Direct mode",IDC_HIDVOL_WIZ_MODE_DIRECT,"Button",BS_AUTORADIOBUTTON,0,87,217,10 - LTEXT "",IDC_BOX_HELP,16,20,205,63 - LTEXT "",IDC_BOX_HELP2,16,101,205,59 -END - -IDD_PASSWORD_ENTRY_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - EDITTEXT IDC_PASSWORD_DIRECT,50,2,173,14,ES_PASSWORD | ES_AUTOHSCROLL - COMBOBOX IDC_PKCS5_PRF_ID,50,17,104,90,CBS_DROPDOWNLIST | WS_TABSTOP - EDITTEXT IDC_PIM,50,32,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER | NOT WS_VISIBLE - LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,96,34,127,8,NOT WS_VISIBLE - CONTROL "&Display password",IDC_SHOW_PASSWORD_SINGLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,50,46,84,11,WS_EX_TRANSPARENT - CONTROL "U&se keyfiles",IDC_KEYFILES_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,50,57,94,11 - PUSHBUTTON "&Keyfiles...",IDC_KEY_FILES,149,54,74,14 - LTEXT "",IDC_BOX_HELP,0,74,225,94 - RTEXT "Password:",IDT_PASSWORD,0,6,48,8 - RTEXT "PKCS-5 PRF:",IDT_PKCS5_PRF,0,19,48,8 - RTEXT "Volume PIM:",IDT_PIM,0,35,48,8,NOT WS_VISIBLE - CONTROL "Use P&IM",IDC_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,50,35,97,10 -END - -IDD_VOLUME_TYPE_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "Standard VeraCrypt volume",IDC_STD_VOL,"Button",BS_AUTORADIOBUTTON,0,7,212,10 - CONTROL "Hi&dden VeraCrypt volume ",IDC_HIDDEN_VOL,"Button",BS_AUTORADIOBUTTON,0,68,212,10 - LTEXT "More information about hidden volumes",IDC_HIDDEN_VOL_HELP,16,151,205,10,SS_NOTIFY - LTEXT "",IDC_BOX_HELP_NORMAL_VOL,16,20,205,41 - LTEXT "",IDC_BOX_HELP,16,83,205,62 -END - -IDD_SYSENC_SPAN_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "Encrypt the Windows system partition",IDC_SYS_PARTITION, - "Button",BS_AUTORADIOBUTTON,0,7,212,10 - CONTROL "Encrypt the whole drive",IDC_WHOLE_SYS_DRIVE,"Button",BS_AUTORADIOBUTTON,0,53,212,10 - LTEXT "Select this option to encrypt the partition where the currently running Windows operating system is installed.",IDT_SYS_PARTITION,16,20,205,32 - LTEXT "",IDT_WHOLE_SYS_DRIVE,16,70,205,95 -END - -IDD_SYSENC_RESCUE_DISK_CREATION_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - EDITTEXT IDC_RESCUE_DISK_ISO_PATH,0,159,163,13,ES_AUTOHSCROLL - PUSHBUTTON "Bro&wse...",IDC_BROWSE,166,158,59,14 - LTEXT "",IDT_RESCUE_DISK_INFO,0,1,225,137 - CONTROL "Skip Rescue Disk verification",IDC_SKIP_RESCUE_VERIFICATION, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,0,145,106,10 -END - -IDD_SYSENC_COLLECTING_RANDOM_DATA_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - CONTROL "Display pool content",IDC_DISPLAY_POOL_CONTENTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,1,98,122,10 - CONTROL "",IDC_SYS_POOL_CONTENTS,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,8,14,205,72,WS_EX_TRANSPARENT - LTEXT "IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the encryption keys. Then click Next to continue.",IDT_COLLECTING_RANDOM_DATA_NOTE,1,112,224,40 - GROUPBOX "Current pool content (partial)",IDT_PARTIAL_POOL_CONTENTS,0,5,222,88 - GROUPBOX "Randomness Collected From Mouse Movements",IDT_ENTROPY_BAR,0,154,224,18 - CONTROL "",IDC_ENTROPY_BAR,"msctls_progress32",WS_BORDER,11,163,202,6 -END - -IDD_SYSENC_MULTI_BOOT_MODE_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "Single-boot",IDC_SINGLE_BOOT,"Button",BS_AUTORADIOBUTTON,0,7,212,10 - CONTROL "Multi-boot",IDC_MULTI_BOOT,"Button",BS_AUTORADIOBUTTON,0,53,217,10 - LTEXT "Select this option if there is only one operating system installed on this computer (even if it has multiple users).",IDT_SINGLE_BOOT,16,20,205,32 - LTEXT "Select this option if there are two or more operating systems installed on this computer.\n\nFor example:\n- Windows XP and Windows XP\n- Windows XP and Windows Vista\n- Windows and Mac OS X\n- Windows and Linux\n- Windows, Linux and Mac OS X",IDT_MULTI_BOOT,16,66,205,72 -END - -IDD_SYSENC_RESCUE_DISK_BURN_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - LTEXT "Download CD/DVD recording software",IDC_DOWNLOAD_CD_BURN_SOFTWARE,0,136,217,10,SS_NOTIFY - LTEXT "",IDT_RESCUE_DISK_BURN_INFO,0,4,225,128 -END - -IDD_SYSENC_WIPE_MODE_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - COMBOBOX IDC_WIPE_MODE,61,0,127,90,CBS_DROPDOWNLIST | WS_TABSTOP - RTEXT "Wipe mode:",IDT_WIPE_MODE,0,2,59,8,0,WS_EX_RIGHT - LTEXT "",IDT_WIPE_MODE_INFO,0,19,225,128 -END - -IDD_INPLACE_ENCRYPTION_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - COMBOBOX IDC_WIPE_MODE,67,13,125,90,CBS_DROPDOWNLIST | WS_TABSTOP - PUSHBUTTON "&Pause",IDC_PAUSE,169,40,50,14 - LTEXT "More information",IDC_MORE_INFO_SYS_ENCRYPTION,1,150,202,10,SS_NOTIFY - LTEXT "",IDC_BYTESWRITTEN,29,58,39,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE - RTEXT "",IDC_WRITESPEED,103,58,46,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE - RTEXT "",IDC_TIMEREMAIN,177,58,42,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE - RTEXT "Wipe mode:",IDT_WIPE_MODE,6,15,59,8,0,WS_EX_RIGHT - CONTROL "",IDC_PROGRESS_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,6,41,158,12 - RTEXT "Done",IDT_DONE,5,59,22,8 - RTEXT "Status",IDT_STATUS,72,59,29,8 - RTEXT "Left",IDT_LEFT,151,59,24,8 - LTEXT "",IDC_BOX_HELP,1,77,224,70 - GROUPBOX "Options",IDT_FORMAT_OPTIONS,0,3,225,29 - GROUPBOX "",IDC_STATIC,0,32,225,41 -END - -IDD_SYSENC_KEYS_GEN_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - CONTROL "Display generated keys (their portions)",IDC_DISPLAY_KEYS, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,1,94,216,10 - CONTROL "",IDC_HEADER_KEY,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,57,71,163,8,WS_EX_TRANSPARENT - LTEXT "",IDC_DISK_KEY,57,79,163,8,0,WS_EX_TRANSPARENT - LTEXT "The keys, salt, and other data have been successfully generated. If you want to generate new keys, click Back and then Next. Otherwise, click Next to continue.",IDT_SYSENC_KEYS_GEN_INFO,1,23,224,41 - RTEXT "Header Key: ",IDT_HEADER_KEY,2,72,54,8 - RTEXT "Master Key: ",IDT_MASTER_KEY,2,80,54,8 - GROUPBOX "",-1,0,65,225,26 -END - -IDD_UNIVERSAL_DUAL_CHOICE_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "",IDC_CHOICE1,"Button",BS_AUTORADIOBUTTON,0,7,212,10 - CONTROL "",IDC_CHOICE2,"Button",BS_AUTORADIOBUTTON,0,17,217,10 - LTEXT "",IDC_BOX_HELP,1,34,220,112 -END - -IDD_SYSENC_DRIVE_ANALYSIS_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - LTEXT "",IDT_SYSENC_DRIVE_ANALYSIS_INFO,2,10,215,88 - CONTROL "",IDC_PROGRESS_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,1,115,216,12 - LTEXT "Progress:",IDT_PROGRESS,2,104,57,8 -END - -IDD_SYSENC_TYPE_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "Normal",IDC_SYSENC_NORMAL,"Button",BS_AUTORADIOBUTTON,0,7,212,10 - CONTROL "Hi&dden",IDC_SYSENC_HIDDEN,"Button",BS_AUTORADIOBUTTON,0,53,212,10 - LTEXT "More information",IDC_HIDDEN_SYSENC_INFO_LINK,16,148,205,10,SS_NOTIFY - LTEXT "",IDC_BOX_HELP_SYSENC_NORMAL,16,20,205,25 - LTEXT "",IDC_BOX_HELP,16,67,205,72 -END - -IDD_SYSENC_HIDDEN_OS_REQ_CHECK_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - LTEXT "More information",IDC_HIDDEN_SYSENC_INFO_LINK,0,150,217,10,SS_NOTIFY - LTEXT "",IDC_BOX_HELP,0,2,225,142 -END - -IDD_DEVICE_WIPE_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - PUSHBUTTON "Abort",IDC_ABORT_BUTTON,169,48,50,14 - LTEXT "",IDC_BYTESWRITTEN,29,66,39,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE - RTEXT "",IDC_WRITESPEED,103,66,46,11,SS_CENTERIMAGE | NOT WS_VISIBLE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE - RTEXT "",IDC_TIMEREMAIN,177,66,42,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE - RTEXT "Wipe mode:",IDT_WIPE_MODE,6,22,59,8,0,WS_EX_RIGHT - CONTROL "",IDC_PROGRESS_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,6,49,158,12 - RTEXT "Done",IDT_DONE,5,67,22,8 - RTEXT "Pass",IDT_PASS,72,67,29,8,NOT WS_VISIBLE - RTEXT "Left",IDT_LEFT,151,67,24,8 - LTEXT "",IDC_BOX_HELP,1,86,224,80 - GROUPBOX "",IDT_FORMAT_OPTIONS,0,10,225,29 - GROUPBOX "",IDC_STATIC,0,40,225,42 - LTEXT "",IDC_WIPE_MODE,67,21,125,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_STATICEDGE -END - -IDD_DEVICE_WIPE_MODE_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - COMBOBOX IDC_WIPE_MODE,61,9,127,90,CBS_DROPDOWNLIST | WS_TABSTOP - RTEXT "Wipe mode:",IDT_WIPE_MODE,0,11,59,8,0,WS_EX_RIGHT - LTEXT "",IDT_WIPE_MODE_INFO,0,29,225,122 -END - -IDD_DEVICE_TRANSFORM_MODE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "Create encrypted volume and format it",IDC_DEVICE_TRANSFORM_MODE_FORMAT, - "Button",BS_AUTORADIOBUTTON,0,8,217,10 - CONTROL "Encrypt partition in place",IDC_DEVICE_TRANSFORM_MODE_INPLACE, - "Button",BS_AUTORADIOBUTTON,0,98,217,10 - LTEXT "",IDC_BOX_HELP,16,21,205,74 - LTEXT "",IDC_BOX_HELP2,16,112,205,53 -END - -IDD_EXPANDED_LIST_SELECT_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - LTEXT "",IDC_BOX_HELP,0,107,225,58 - LISTBOX IDC_LIST_BOX,0,3,222,100,LBS_NOINTEGRALHEIGHT | LBS_DISABLENOSCROLL | WS_VSCROLL -END - -IDD_DRIVE_LETTER_SELECTION_PAGE DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - LTEXT "",IDC_BOX_HELP,0,40,225,118 - COMBOBOX IDC_DRIVE_LETTER_LIST,94,15,38,69,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP - RTEXT "Drive letter:",IDT_DRIVE_LETTER,5,17,86,8 -END - -IDD_PIM_PAGE_DLG DIALOGEX 0, 0, 226, 172 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - EDITTEXT IDC_PIM,53,0,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER - LTEXT "",IDC_BOX_HELP,0,32,225,126 - RTEXT "Volume PIM:",IDT_PIM,1,3,50,8 - LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,97,3,126,8 - LTEXT "Information on PIM",IDC_LINK_PIM_INFO,0,161,213,8,SS_NOTIFY - CONTROL "Display PIM",IDC_SHOW_PIM,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,53,17,150,10 -END - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "#include ""..\\\\common\\\\resource.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "#include ""..\\\\common\\\\common.rc""\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_VOL_CREATION_WIZARD_DLG, DIALOG - BEGIN - RIGHTMARGIN, 393 - TOPMARGIN, 1 - BOTTOMMARGIN, 227 - HORZGUIDE, 216 - END - - IDD_CIPHER_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 223 - BOTTOMMARGIN, 161 - END - - IDD_PASSWORD_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 223 - BOTTOMMARGIN, 143 - END - - IDD_SIZE_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 223 - BOTTOMMARGIN, 165 - END - - IDD_VOLUME_LOCATION_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 223 - BOTTOMMARGIN, 167 - END - - IDD_FORMAT_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 217 - BOTTOMMARGIN, 153 - HORZGUIDE, 80 - HORZGUIDE, 96 - END - - IDD_INTRO_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_INFO_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_HIDVOL_HOST_FILL_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_HIDDEN_VOL_WIZARD_MODE_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_PASSWORD_ENTRY_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 223 - BOTTOMMARGIN, 143 - END - - IDD_VOLUME_TYPE_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_SYSENC_SPAN_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_SYSENC_RESCUE_DISK_CREATION_DLG, DIALOG - BEGIN - RIGHTMARGIN, 223 - BOTTOMMARGIN, 167 - END - - IDD_SYSENC_COLLECTING_RANDOM_DATA_DLG, DIALOG - BEGIN - RIGHTMARGIN, 217 - BOTTOMMARGIN, 153 - HORZGUIDE, 80 - HORZGUIDE, 96 - END - - IDD_SYSENC_MULTI_BOOT_MODE_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_SYSENC_RESCUE_DISK_BURN_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 223 - BOTTOMMARGIN, 167 - END - - IDD_SYSENC_WIPE_MODE_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_INPLACE_ENCRYPTION_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 217 - BOTTOMMARGIN, 166 - HORZGUIDE, 80 - HORZGUIDE, 96 - END - - IDD_SYSENC_KEYS_GEN_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 217 - BOTTOMMARGIN, 153 - HORZGUIDE, 80 - HORZGUIDE, 96 - END - - IDD_UNIVERSAL_DUAL_CHOICE_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_SYSENC_DRIVE_ANALYSIS_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 217 - BOTTOMMARGIN, 153 - HORZGUIDE, 80 - HORZGUIDE, 96 - END - - IDD_SYSENC_TYPE_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_SYSENC_HIDDEN_OS_REQ_CHECK_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 223 - BOTTOMMARGIN, 167 - END - - IDD_DEVICE_WIPE_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 217 - BOTTOMMARGIN, 166 - HORZGUIDE, 80 - HORZGUIDE, 96 - END - - IDD_DEVICE_WIPE_MODE_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_DEVICE_TRANSFORM_MODE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_EXPANDED_LIST_SELECT_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_DRIVE_LETTER_SELECTION_PAGE, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 219 - TOPMARGIN, 7 - BOTTOMMARGIN, 165 - END - - IDD_PIM_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 223 - BOTTOMMARGIN, 171 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_WIZARD BITMAP "VeraCrypt_wizard.bmp" - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE -BEGIN - IDS_UACSTRING_FMT "VeraCrypt" -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// -#include "..\\common\\common.rc" - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" +#include "..\\common\\resource.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,17,22,0 + PRODUCTVERSION 1,17,22,0 + FILEFLAGSMASK 0x17L +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "IDRIX" + VALUE "FileDescription", "VeraCrypt Format" + VALUE "FileVersion", "1.17" + VALUE "LegalTrademarks", "VeraCrypt" + VALUE "OriginalFilename", "VeraCrypt Format.exe" + VALUE "ProductName", "VeraCrypt" + VALUE "ProductVersion", "1.17" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// HEADER +// + +IDR_FORMAT_RSRC_HEADER HEADER "resource.h" + +///////////////////////////////////////////////////////////////////////////// +// +// TYPELIB +// + +IDR_FORMAT_TLB TYPELIB "Format.tlb" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_VOL_CREATION_WIZARD_DLG DIALOGEX 0, 0, 400, 229 +STYLE DS_SETFONT | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt Volume Creation Wizard" +CLASS "VeraCryptCustomDlg" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + PUSHBUTTON "&Help",IDHELP,176,209,50,14 + PUSHBUTTON "",IDC_PREV,235,209,50,14 + DEFPUSHBUTTON "",IDC_NEXT,285,209,50,14 + PUSHBUTTON "Cancel",IDCANCEL,343,209,50,14 + LTEXT "",IDC_BOX_TITLE,160,8,233,17 + GROUPBOX "",IDC_STATIC,4,0,392,203 + CONTROL 116,IDC_BITMAP_WIZARD,"Static",SS_BITMAP | SS_SUNKEN,10,9,137,169 + LTEXT "",IDC_POS_BOX,160,24,231,172 +END + +IDD_CIPHER_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + COMBOBOX IDC_COMBO_BOX,7,23,137,126,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP + PUSHBUTTON "&Test",IDC_CIPHER_TEST,149,22,59,14 + PUSHBUTTON "&Benchmark",IDC_BENCHMARK,149,100,59,14 + COMBOBOX IDC_COMBO_BOX_HASH_ALGO,7,137,83,126,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP + LTEXT "",IDC_BOX_HELP,7,40,205,58 + GROUPBOX "Encryption Algorithm",IDT_ENCRYPTION_ALGO,0,10,217,111 + GROUPBOX "Hash Algorithm",IDT_HASH_ALGO,0,124,217,35 + LTEXT "More information",IDC_LINK_MORE_INFO_ABOUT_CIPHER,7,102,135,10,SS_NOTIFY + LTEXT "Information on hash algorithms",IDC_LINK_HASH_INFO,97,139,115,8,SS_NOTIFY +END + +IDD_PASSWORD_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + EDITTEXT IDC_PASSWORD,53,3,170,14,ES_PASSWORD | ES_AUTOHSCROLL + EDITTEXT IDC_VERIFY,53,19,170,14,ES_PASSWORD | ES_AUTOHSCROLL + CONTROL "U&se keyfiles",IDC_KEYFILES_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,53,35,95,10 + PUSHBUTTON "&Keyfiles...",IDC_KEY_FILES,152,36,71,14,WS_DISABLED + CONTROL "&Display password",IDC_SHOW_PASSWORD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,53,45,95,11,WS_EX_TRANSPARENT + CONTROL "Use P&IM",IDC_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,53,56,97,10 + RTEXT "Password:",IDT_PASSWORD,1,6,50,8 + RTEXT "&Confirm:",IDT_CONFIRM,1,23,50,8 + LTEXT "",IDC_BOX_HELP,0,71,225,97 +END + +IDD_SIZE_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + EDITTEXT IDC_SIZEBOX,0,22,71,14,ES_AUTOHSCROLL | ES_NUMBER + CONTROL "&KB",IDC_KB,"Button",BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,80,25,27,10 + CONTROL "&MB",IDC_MB,"Button",BS_AUTORADIOBUTTON,115,25,27,10 + CONTROL "&GB",IDC_GB,"Button",BS_AUTORADIOBUTTON,150,25,27,10 + LTEXT "",IDC_BOX_HELP,0,84,214,75 + LTEXT "",IDC_SPACE_LEFT,0,44,214,33 + CONTROL "&TB",IDC_TB,"Button",BS_AUTORADIOBUTTON,185,25,27,10 +END + +IDD_VOLUME_LOCATION_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + COMBOBOX IDC_COMBO_BOX,0,9,148,80,CBS_DROPDOWN | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP + CONTROL "&Never save history",IDC_NO_HISTORY,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,3,28,213,10 + PUSHBUTTON "",IDC_SELECT_VOLUME_LOCATION,155,9,62,14 + LTEXT "",IDC_BOX_HELP,0,42,219,125 +END + +IDD_FORMAT_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + COMBOBOX IDC_FILESYS,43,13,36,90,CBS_DROPDOWNLIST | WS_TABSTOP + COMBOBOX IDC_CLUSTERSIZE,112,13,42,90,CBS_DROPDOWNLIST | WS_TABSTOP + CONTROL "Quick Format",IDC_QUICKFORMAT,"Button",BS_AUTOCHECKBOX | BS_MULTILINE | WS_TABSTOP,163,11,60,18 + CONTROL "",IDC_SHOW_KEYS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,214,38,9,8 + PUSHBUTTON "Abort",IDC_ABORT_BUTTON,169,75,50,14 + RTEXT "Header Key: ",IDT_HEADER_KEY,2,47,54,8 + CONTROL "",IDC_HEADER_KEY,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,57,46,163,8,WS_EX_TRANSPARENT + RTEXT "Master Key: ",IDT_MASTER_KEY,2,55,54,8 + LTEXT "",IDC_DISK_KEY,57,54,163,8,0,WS_EX_TRANSPARENT + RTEXT "Cluster ",IDT_CLUSTER,80,15,32,8 + LTEXT "",IDC_BOX_HELP,1,112,224,40 + GROUPBOX "Options",IDT_FORMAT_OPTIONS,0,3,225,29 + CONTROL "",IDC_PROGRESS_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,6,76,158,12 + RTEXT "",IDC_TIMEREMAIN,177,93,42,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE + RTEXT "",IDC_WRITESPEED,106,93,42,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE + LTEXT "",IDC_BYTESWRITTEN,29,93,39,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE + RTEXT "Done",IDT_DONE,5,94,22,8 + RTEXT "Speed",IDT_SPEED,70,94,34,8 + RTEXT "Left",IDT_LEFT,150,94,25,8 + GROUPBOX "",IDC_STATIC,0,67,225,41 + RTEXT "Filesystem ",IDT_FILESYSTEM,1,15,41,8,0,WS_EX_RIGHT + RTEXT "Random Pool: ",IDT_RANDOM_POOL,2,39,54,8 + GROUPBOX "",IDC_STATIC,0,32,225,35 + CONTROL "",IDC_RANDOM_BYTES,"Static",SS_SIMPLE | WS_GROUP,57,38,155,8,WS_EX_TRANSPARENT + GROUPBOX "Randomness Collected From Mouse Movements",IDT_ENTROPY_BAR,0,153,224,18 + CONTROL "",IDC_ENTROPY_BAR,"msctls_progress32",WS_BORDER,11,162,202,6 +END + +IDD_INTRO_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "Create an encrypted file container",IDC_FILE_CONTAINER, + "Button",BS_AUTORADIOBUTTON,0,7,217,10 + LTEXT "More information",IDC_MORE_INFO_ON_CONTAINERS,16,40,165,10,SS_NOTIFY + CONTROL "Encrypt a non-system partition/drive",IDC_NONSYS_DEVICE, + "Button",BS_AUTORADIOBUTTON,0,53,217,10 + CONTROL "Encrypt the system partition or entire system drive",IDC_SYS_DEVICE, + "Button",BS_AUTORADIOBUTTON,0,89,217,10 + LTEXT "More information about system encryption",IDC_MORE_INFO_ON_SYS_ENCRYPTION,16,153,190,10,SS_NOTIFY + LTEXT "Creates a virtual encrypted disk within a file. Recommended for inexperienced users.",IDT_FILE_CONTAINER,16,20,205,16 + LTEXT "Encrypts a non-system partition on any internal or external drive (e.g. a flash drive). Optionally, creates a hidden volume.",IDT_NON_SYS_DEVICE,16,66,205,20 + LTEXT "Encrypts the partition/drive where Windows is installed. Anyone who wants to gain access and use the system, read and write files, etc., will need to enter the correct password each time before Windows boots. Optionally, creates a hidden system.",IDT_SYS_DEVICE,16,102,205,47 +END + +IDD_INFO_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + LTEXT "",IDC_BOX_HELP,0,10,225,155 +END + +IDD_HIDVOL_HOST_FILL_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + LTEXT "",IDC_BOX_HELP,0,6,226,138 + PUSHBUTTON "Open Outer Volume",IDC_OPEN_OUTER_VOLUME,0,146,85,14 +END + +IDD_HIDDEN_VOL_WIZARD_MODE_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "Normal mode",IDC_HIDVOL_WIZ_MODE_FULL,"Button",BS_AUTORADIOBUTTON,0,7,217,10 + CONTROL "Direct mode",IDC_HIDVOL_WIZ_MODE_DIRECT,"Button",BS_AUTORADIOBUTTON,0,87,217,10 + LTEXT "",IDC_BOX_HELP,16,20,205,63 + LTEXT "",IDC_BOX_HELP2,16,101,205,59 +END + +IDD_PASSWORD_ENTRY_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + EDITTEXT IDC_PASSWORD_DIRECT,50,2,173,14,ES_PASSWORD | ES_AUTOHSCROLL + COMBOBOX IDC_PKCS5_PRF_ID,50,17,104,90,CBS_DROPDOWNLIST | WS_TABSTOP + EDITTEXT IDC_PIM,50,32,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER | NOT WS_VISIBLE + LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,96,34,127,8,NOT WS_VISIBLE + CONTROL "&Display password",IDC_SHOW_PASSWORD_SINGLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,50,46,84,11,WS_EX_TRANSPARENT + CONTROL "U&se keyfiles",IDC_KEYFILES_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,50,57,94,11 + PUSHBUTTON "&Keyfiles...",IDC_KEY_FILES,149,54,74,14 + LTEXT "",IDC_BOX_HELP,0,74,225,94 + RTEXT "Password:",IDT_PASSWORD,0,6,48,8 + RTEXT "PKCS-5 PRF:",IDT_PKCS5_PRF,0,19,48,8 + RTEXT "Volume PIM:",IDT_PIM,0,35,48,8,NOT WS_VISIBLE + CONTROL "Use P&IM",IDC_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,50,35,97,10 +END + +IDD_VOLUME_TYPE_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "Standard VeraCrypt volume",IDC_STD_VOL,"Button",BS_AUTORADIOBUTTON,0,7,212,10 + CONTROL "Hi&dden VeraCrypt volume ",IDC_HIDDEN_VOL,"Button",BS_AUTORADIOBUTTON,0,68,212,10 + LTEXT "More information about hidden volumes",IDC_HIDDEN_VOL_HELP,16,151,205,10,SS_NOTIFY + LTEXT "",IDC_BOX_HELP_NORMAL_VOL,16,20,205,41 + LTEXT "",IDC_BOX_HELP,16,83,205,62 +END + +IDD_SYSENC_SPAN_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "Encrypt the Windows system partition",IDC_SYS_PARTITION, + "Button",BS_AUTORADIOBUTTON,0,7,212,10 + CONTROL "Encrypt the whole drive",IDC_WHOLE_SYS_DRIVE,"Button",BS_AUTORADIOBUTTON,0,53,212,10 + LTEXT "Select this option to encrypt the partition where the currently running Windows operating system is installed.",IDT_SYS_PARTITION,16,20,205,32 + LTEXT "",IDT_WHOLE_SYS_DRIVE,16,70,205,95 +END + +IDD_SYSENC_RESCUE_DISK_CREATION_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + EDITTEXT IDC_RESCUE_DISK_ISO_PATH,0,159,163,13,ES_AUTOHSCROLL + PUSHBUTTON "Bro&wse...",IDC_BROWSE,166,158,59,14 + LTEXT "",IDT_RESCUE_DISK_INFO,0,1,225,137 + CONTROL "Skip Rescue Disk verification",IDC_SKIP_RESCUE_VERIFICATION, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,0,145,106,10 +END + +IDD_SYSENC_COLLECTING_RANDOM_DATA_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + CONTROL "Display pool content",IDC_DISPLAY_POOL_CONTENTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,1,98,122,10 + CONTROL "",IDC_SYS_POOL_CONTENTS,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,8,14,205,72,WS_EX_TRANSPARENT + LTEXT "IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the encryption keys. Then click Next to continue.",IDT_COLLECTING_RANDOM_DATA_NOTE,1,112,224,40 + GROUPBOX "Current pool content (partial)",IDT_PARTIAL_POOL_CONTENTS,0,5,222,88 + GROUPBOX "Randomness Collected From Mouse Movements",IDT_ENTROPY_BAR,0,154,224,18 + CONTROL "",IDC_ENTROPY_BAR,"msctls_progress32",WS_BORDER,11,163,202,6 +END + +IDD_SYSENC_MULTI_BOOT_MODE_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "Single-boot",IDC_SINGLE_BOOT,"Button",BS_AUTORADIOBUTTON,0,7,212,10 + CONTROL "Multi-boot",IDC_MULTI_BOOT,"Button",BS_AUTORADIOBUTTON,0,53,217,10 + LTEXT "Select this option if there is only one operating system installed on this computer (even if it has multiple users).",IDT_SINGLE_BOOT,16,20,205,32 + LTEXT "Select this option if there are two or more operating systems installed on this computer.\n\nFor example:\n- Windows XP and Windows XP\n- Windows XP and Windows Vista\n- Windows and Mac OS X\n- Windows and Linux\n- Windows, Linux and Mac OS X",IDT_MULTI_BOOT,16,66,205,72 +END + +IDD_SYSENC_RESCUE_DISK_BURN_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + LTEXT "Download CD/DVD recording software",IDC_DOWNLOAD_CD_BURN_SOFTWARE,0,136,217,10,SS_NOTIFY + LTEXT "",IDT_RESCUE_DISK_BURN_INFO,0,4,225,128 +END + +IDD_SYSENC_WIPE_MODE_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + COMBOBOX IDC_WIPE_MODE,61,0,127,90,CBS_DROPDOWNLIST | WS_TABSTOP + RTEXT "Wipe mode:",IDT_WIPE_MODE,0,2,59,8,0,WS_EX_RIGHT + LTEXT "",IDT_WIPE_MODE_INFO,0,19,225,128 +END + +IDD_INPLACE_ENCRYPTION_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + COMBOBOX IDC_WIPE_MODE,67,13,125,90,CBS_DROPDOWNLIST | WS_TABSTOP + PUSHBUTTON "&Pause",IDC_PAUSE,169,40,50,14 + LTEXT "More information",IDC_MORE_INFO_SYS_ENCRYPTION,1,150,202,10,SS_NOTIFY + LTEXT "",IDC_BYTESWRITTEN,29,58,39,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE + RTEXT "",IDC_WRITESPEED,103,58,46,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE + RTEXT "",IDC_TIMEREMAIN,177,58,42,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE + RTEXT "Wipe mode:",IDT_WIPE_MODE,6,15,59,8,0,WS_EX_RIGHT + CONTROL "",IDC_PROGRESS_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,6,41,158,12 + RTEXT "Done",IDT_DONE,5,59,22,8 + RTEXT "Status",IDT_STATUS,72,59,29,8 + RTEXT "Left",IDT_LEFT,151,59,24,8 + LTEXT "",IDC_BOX_HELP,1,77,224,70 + GROUPBOX "Options",IDT_FORMAT_OPTIONS,0,3,225,29 + GROUPBOX "",IDC_STATIC,0,32,225,41 +END + +IDD_SYSENC_KEYS_GEN_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + CONTROL "Display generated keys (their portions)",IDC_DISPLAY_KEYS, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,1,94,216,10 + CONTROL "",IDC_HEADER_KEY,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,57,71,163,8,WS_EX_TRANSPARENT + LTEXT "",IDC_DISK_KEY,57,79,163,8,0,WS_EX_TRANSPARENT + LTEXT "The keys, salt, and other data have been successfully generated. If you want to generate new keys, click Back and then Next. Otherwise, click Next to continue.",IDT_SYSENC_KEYS_GEN_INFO,1,23,224,41 + RTEXT "Header Key: ",IDT_HEADER_KEY,2,72,54,8 + RTEXT "Master Key: ",IDT_MASTER_KEY,2,80,54,8 + GROUPBOX "",-1,0,65,225,26 +END + +IDD_UNIVERSAL_DUAL_CHOICE_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "",IDC_CHOICE1,"Button",BS_AUTORADIOBUTTON,0,7,212,10 + CONTROL "",IDC_CHOICE2,"Button",BS_AUTORADIOBUTTON,0,17,217,10 + LTEXT "",IDC_BOX_HELP,1,34,220,112 +END + +IDD_SYSENC_DRIVE_ANALYSIS_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + LTEXT "",IDT_SYSENC_DRIVE_ANALYSIS_INFO,2,10,215,88 + CONTROL "",IDC_PROGRESS_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,1,115,216,12 + LTEXT "Progress:",IDT_PROGRESS,2,104,57,8 +END + +IDD_SYSENC_TYPE_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "Normal",IDC_SYSENC_NORMAL,"Button",BS_AUTORADIOBUTTON,0,7,212,10 + CONTROL "Hi&dden",IDC_SYSENC_HIDDEN,"Button",BS_AUTORADIOBUTTON,0,53,212,10 + LTEXT "More information",IDC_HIDDEN_SYSENC_INFO_LINK,16,148,205,10,SS_NOTIFY + LTEXT "",IDC_BOX_HELP_SYSENC_NORMAL,16,20,205,25 + LTEXT "",IDC_BOX_HELP,16,67,205,72 +END + +IDD_SYSENC_HIDDEN_OS_REQ_CHECK_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + LTEXT "More information",IDC_HIDDEN_SYSENC_INFO_LINK,0,150,217,10,SS_NOTIFY + LTEXT "",IDC_BOX_HELP,0,2,225,142 +END + +IDD_DEVICE_WIPE_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + PUSHBUTTON "Abort",IDC_ABORT_BUTTON,169,48,50,14 + LTEXT "",IDC_BYTESWRITTEN,29,66,39,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE + RTEXT "",IDC_WRITESPEED,103,66,46,11,SS_CENTERIMAGE | NOT WS_VISIBLE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE + RTEXT "",IDC_TIMEREMAIN,177,66,42,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_RIGHT | WS_EX_STATICEDGE + RTEXT "Wipe mode:",IDT_WIPE_MODE,6,22,59,8,0,WS_EX_RIGHT + CONTROL "",IDC_PROGRESS_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,6,49,158,12 + RTEXT "Done",IDT_DONE,5,67,22,8 + RTEXT "Pass",IDT_PASS,72,67,29,8,NOT WS_VISIBLE + RTEXT "Left",IDT_LEFT,151,67,24,8 + LTEXT "",IDC_BOX_HELP,1,86,224,80 + GROUPBOX "",IDT_FORMAT_OPTIONS,0,10,225,29 + GROUPBOX "",IDC_STATIC,0,40,225,42 + LTEXT "",IDC_WIPE_MODE,67,21,125,11,SS_CENTERIMAGE,WS_EX_TRANSPARENT | WS_EX_STATICEDGE +END + +IDD_DEVICE_WIPE_MODE_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + COMBOBOX IDC_WIPE_MODE,61,9,127,90,CBS_DROPDOWNLIST | WS_TABSTOP + RTEXT "Wipe mode:",IDT_WIPE_MODE,0,11,59,8,0,WS_EX_RIGHT + LTEXT "",IDT_WIPE_MODE_INFO,0,29,225,122 +END + +IDD_DEVICE_TRANSFORM_MODE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "Create encrypted volume and format it",IDC_DEVICE_TRANSFORM_MODE_FORMAT, + "Button",BS_AUTORADIOBUTTON,0,8,217,10 + CONTROL "Encrypt partition in place",IDC_DEVICE_TRANSFORM_MODE_INPLACE, + "Button",BS_AUTORADIOBUTTON,0,98,217,10 + LTEXT "",IDC_BOX_HELP,16,21,205,74 + LTEXT "",IDC_BOX_HELP2,16,112,205,53 +END + +IDD_EXPANDED_LIST_SELECT_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + LTEXT "",IDC_BOX_HELP,0,107,225,58 + LISTBOX IDC_LIST_BOX,0,3,222,100,LBS_NOINTEGRALHEIGHT | LBS_DISABLENOSCROLL | WS_VSCROLL +END + +IDD_DRIVE_LETTER_SELECTION_PAGE DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + LTEXT "",IDC_BOX_HELP,0,40,225,118 + COMBOBOX IDC_DRIVE_LETTER_LIST,94,15,38,69,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP + RTEXT "Drive letter:",IDT_DRIVE_LETTER,5,17,86,8 +END + +IDD_PIM_PAGE_DLG DIALOGEX 0, 0, 226, 172 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + EDITTEXT IDC_PIM,53,0,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER + LTEXT "",IDC_BOX_HELP,0,32,225,126 + RTEXT "Volume PIM:",IDT_PIM,1,3,50,8 + LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,97,3,126,8 + LTEXT "Information on PIM",IDC_LINK_PIM_INFO,0,161,213,8,SS_NOTIFY + CONTROL "Display PIM",IDC_SHOW_PIM,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,53,17,150,10 +END + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "#include ""..\\\\common\\\\resource.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "#include ""..\\\\common\\\\common.rc""\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_VOL_CREATION_WIZARD_DLG, DIALOG + BEGIN + RIGHTMARGIN, 393 + TOPMARGIN, 1 + BOTTOMMARGIN, 227 + HORZGUIDE, 216 + END + + IDD_CIPHER_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 223 + BOTTOMMARGIN, 161 + END + + IDD_PASSWORD_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 223 + BOTTOMMARGIN, 143 + END + + IDD_SIZE_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 223 + BOTTOMMARGIN, 165 + END + + IDD_VOLUME_LOCATION_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 223 + BOTTOMMARGIN, 167 + END + + IDD_FORMAT_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 217 + BOTTOMMARGIN, 153 + HORZGUIDE, 80 + HORZGUIDE, 96 + END + + IDD_INTRO_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_INFO_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_HIDVOL_HOST_FILL_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_HIDDEN_VOL_WIZARD_MODE_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_PASSWORD_ENTRY_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 223 + BOTTOMMARGIN, 143 + END + + IDD_VOLUME_TYPE_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_SYSENC_SPAN_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_SYSENC_RESCUE_DISK_CREATION_DLG, DIALOG + BEGIN + RIGHTMARGIN, 223 + BOTTOMMARGIN, 167 + END + + IDD_SYSENC_COLLECTING_RANDOM_DATA_DLG, DIALOG + BEGIN + RIGHTMARGIN, 217 + BOTTOMMARGIN, 153 + HORZGUIDE, 80 + HORZGUIDE, 96 + END + + IDD_SYSENC_MULTI_BOOT_MODE_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_SYSENC_RESCUE_DISK_BURN_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 223 + BOTTOMMARGIN, 167 + END + + IDD_SYSENC_WIPE_MODE_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_INPLACE_ENCRYPTION_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 217 + BOTTOMMARGIN, 166 + HORZGUIDE, 80 + HORZGUIDE, 96 + END + + IDD_SYSENC_KEYS_GEN_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 217 + BOTTOMMARGIN, 153 + HORZGUIDE, 80 + HORZGUIDE, 96 + END + + IDD_UNIVERSAL_DUAL_CHOICE_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_SYSENC_DRIVE_ANALYSIS_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 217 + BOTTOMMARGIN, 153 + HORZGUIDE, 80 + HORZGUIDE, 96 + END + + IDD_SYSENC_TYPE_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_SYSENC_HIDDEN_OS_REQ_CHECK_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 223 + BOTTOMMARGIN, 167 + END + + IDD_DEVICE_WIPE_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 217 + BOTTOMMARGIN, 166 + HORZGUIDE, 80 + HORZGUIDE, 96 + END + + IDD_DEVICE_WIPE_MODE_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_DEVICE_TRANSFORM_MODE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_EXPANDED_LIST_SELECT_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_DRIVE_LETTER_SELECTION_PAGE, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 219 + TOPMARGIN, 7 + BOTTOMMARGIN, 165 + END + + IDD_PIM_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 223 + BOTTOMMARGIN, 171 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Bitmap +// + +IDB_WIZARD BITMAP "VeraCrypt_wizard.bmp" + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE +BEGIN + IDS_UACSTRING_FMT "VeraCrypt" +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#include "..\\common\\common.rc" + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/src/Format/Format.vcproj b/src/Format/Format.vcproj index b8747baf..9fa108bc 100644 --- a/src/Format/Format.vcproj +++ b/src/Format/Format.vcproj @@ -1,1028 +1,1028 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Format/FormatCom.cpp b/src/Format/FormatCom.cpp index 2dd5fa79..8ba2372f 100644 --- a/src/Format/FormatCom.cpp +++ b/src/Format/FormatCom.cpp @@ -1,248 +1,248 @@ -/* - 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 -#include -#include -#include -#include "BaseCom.h" -#include "BootEncryption.h" -#include "Dlgcode.h" -#include "Format.h" -#include "Progress.h" -#include "TcFormat.h" -#include "FormatCom.h" -#include "FormatCom_h.h" -#include "FormatCom_i.c" - -using namespace VeraCrypt; - -static volatile LONG ObjectCount = 0; - -class TrueCryptFormatCom : public ITrueCryptFormatCom -{ - -public: - TrueCryptFormatCom (DWORD messageThreadId) : RefCount (0), - MessageThreadId (messageThreadId), - CallBack (NULL) - { - InterlockedIncrement (&ObjectCount); - } - - virtual ~TrueCryptFormatCom () - { - if (InterlockedDecrement (&ObjectCount) == 0) - PostThreadMessage (MessageThreadId, WM_APP, 0, 0); - } - - virtual ULONG STDMETHODCALLTYPE AddRef () - { - return InterlockedIncrement (&RefCount); - } - - virtual ULONG STDMETHODCALLTYPE Release () - { - if (!InterlockedDecrement (&RefCount)) - { - delete this; - return 0; - } - - return RefCount; - } - - virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID riid, void **ppvObject) - { - if (riid == IID_IUnknown || riid == IID_ITrueCryptFormatCom) - *ppvObject = this; - else - { - *ppvObject = NULL; - return E_NOINTERFACE; - } - - AddRef (); - return S_OK; - } - - virtual DWORD STDMETHODCALLTYPE CallDriver (DWORD ioctl, BSTR input, BSTR *output) - { - return BaseCom::CallDriver (ioctl, input, output); - } - - virtual DWORD STDMETHODCALLTYPE CopyFile (BSTR sourceFile, BSTR destinationFile) - { - return BaseCom::CopyFile (sourceFile, destinationFile); - } - - virtual DWORD STDMETHODCALLTYPE DeleteFile (BSTR file) - { - return BaseCom::DeleteFile (file); - } - - virtual BOOL STDMETHODCALLTYPE FormatNtfs (int driveNo, int clusterSize) - { - return ::FormatNtfs (driveNo, clusterSize); - } - - virtual int STDMETHODCALLTYPE AnalyzeHiddenVolumeHost ( - LONG_PTR hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *nbrFreeClusters) - { - return ::AnalyzeHiddenVolumeHost ( - (HWND) hwndDlg, driveNo, hiddenVolHostSize, realClusterSize, nbrFreeClusters); - } - - virtual DWORD STDMETHODCALLTYPE ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone) - { - return BaseCom::ReadWriteFile (write, device, filePath, bufferBstr, offset, size, sizeDone); - } - - virtual DWORD STDMETHODCALLTYPE RegisterFilterDriver (BOOL registerDriver, int filterType) - { - return BaseCom::RegisterFilterDriver (registerDriver, filterType); - } - - virtual DWORD STDMETHODCALLTYPE RegisterSystemFavoritesService (BOOL registerService) - { - return BaseCom::RegisterSystemFavoritesService (registerService); - } - - virtual DWORD STDMETHODCALLTYPE SetDriverServiceStartType (DWORD startType) - { - return BaseCom::SetDriverServiceStartType (startType); - } - - virtual BOOL STDMETHODCALLTYPE IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) - { - return BaseCom::IsPagingFileActive (checkNonWindowsPartitionsOnly); - } - - virtual DWORD STDMETHODCALLTYPE WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value) - { - return BaseCom::WriteLocalMachineRegistryDwordValue (keyPath, valueName, value); - } - - virtual BOOL STDMETHODCALLTYPE FormatFs (int driveNo, int clusterSize, int fsType) - { - return ::FormatFs (driveNo, clusterSize, fsType); - } - -protected: - DWORD MessageThreadId; - LONG RefCount; - ITrueCryptFormatCom *CallBack; -}; - - -extern "C" BOOL ComServerFormat () -{ - SetProcessShutdownParameters (0x100, 0); - - TrueCryptFactory factory (GetCurrentThreadId ()); - DWORD cookie; - - if (IsUacSupported ()) - UacElevated = TRUE; - - if (CoRegisterClassObject (CLSID_TrueCryptFormatCom, (LPUNKNOWN) &factory, - CLSCTX_LOCAL_SERVER, REGCLS_SINGLEUSE, &cookie) != S_OK) - return FALSE; - - MSG msg; - while (int r = GetMessageW (&msg, NULL, 0, 0)) - { - if (r == -1) - return FALSE; - - TranslateMessage (&msg); - DispatchMessageW (&msg); - - if (msg.message == WM_APP - && ObjectCount < 1 - && !factory.IsServerLocked ()) - break; - } - CoRevokeClassObject (cookie); - - return TRUE; -} - - -static BOOL ComGetInstance (HWND hWnd, ITrueCryptFormatCom **tcServer) -{ - return ComGetInstanceBase (hWnd, CLSID_TrueCryptFormatCom, IID_ITrueCryptFormatCom, (void **) tcServer); -} - - -ITrueCryptFormatCom *GetElevatedInstance (HWND parent) -{ - ITrueCryptFormatCom *instance; - - if (!ComGetInstance (parent, &instance)) - throw UserAbort (SRC_POS); - - return instance; -} - - -extern "C" int UacFormatNtfs (HWND hWnd, int driveNo, int clusterSize) -{ - CComPtr tc; - int r; - - CoInitialize (NULL); - - if (ComGetInstance (hWnd, &tc)) - r = tc->FormatNtfs (driveNo, clusterSize); - else - r = 0; - - CoUninitialize (); - - return r; -} - -extern "C" int UacFormatFs (HWND hWnd, int driveNo, int clusterSize, int fsType) -{ - CComPtr tc; - int r; - - CoInitialize (NULL); - - if (ComGetInstance (hWnd, &tc)) - r = tc->FormatFs (driveNo, clusterSize, fsType); - else - r = 0; - - CoUninitialize (); - - return r; -} - - -extern "C" int UacAnalyzeHiddenVolumeHost (HWND hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *nbrFreeClusters) -{ - CComPtr tc; - int r; - - CoInitialize (NULL); - - if (ComGetInstance (hwndDlg, &tc)) - r = tc->AnalyzeHiddenVolumeHost ((LONG_PTR) hwndDlg, driveNo, hiddenVolHostSize, realClusterSize, nbrFreeClusters); - else - r = 0; - - CoUninitialize (); - - return r; -} +/* + 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 +#include +#include +#include +#include "BaseCom.h" +#include "BootEncryption.h" +#include "Dlgcode.h" +#include "Format.h" +#include "Progress.h" +#include "TcFormat.h" +#include "FormatCom.h" +#include "FormatCom_h.h" +#include "FormatCom_i.c" + +using namespace VeraCrypt; + +static volatile LONG ObjectCount = 0; + +class TrueCryptFormatCom : public ITrueCryptFormatCom +{ + +public: + TrueCryptFormatCom (DWORD messageThreadId) : RefCount (0), + MessageThreadId (messageThreadId), + CallBack (NULL) + { + InterlockedIncrement (&ObjectCount); + } + + virtual ~TrueCryptFormatCom () + { + if (InterlockedDecrement (&ObjectCount) == 0) + PostThreadMessage (MessageThreadId, WM_APP, 0, 0); + } + + virtual ULONG STDMETHODCALLTYPE AddRef () + { + return InterlockedIncrement (&RefCount); + } + + virtual ULONG STDMETHODCALLTYPE Release () + { + if (!InterlockedDecrement (&RefCount)) + { + delete this; + return 0; + } + + return RefCount; + } + + virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID riid, void **ppvObject) + { + if (riid == IID_IUnknown || riid == IID_ITrueCryptFormatCom) + *ppvObject = this; + else + { + *ppvObject = NULL; + return E_NOINTERFACE; + } + + AddRef (); + return S_OK; + } + + virtual DWORD STDMETHODCALLTYPE CallDriver (DWORD ioctl, BSTR input, BSTR *output) + { + return BaseCom::CallDriver (ioctl, input, output); + } + + virtual DWORD STDMETHODCALLTYPE CopyFile (BSTR sourceFile, BSTR destinationFile) + { + return BaseCom::CopyFile (sourceFile, destinationFile); + } + + virtual DWORD STDMETHODCALLTYPE DeleteFile (BSTR file) + { + return BaseCom::DeleteFile (file); + } + + virtual BOOL STDMETHODCALLTYPE FormatNtfs (int driveNo, int clusterSize) + { + return ::FormatNtfs (driveNo, clusterSize); + } + + virtual int STDMETHODCALLTYPE AnalyzeHiddenVolumeHost ( + LONG_PTR hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *nbrFreeClusters) + { + return ::AnalyzeHiddenVolumeHost ( + (HWND) hwndDlg, driveNo, hiddenVolHostSize, realClusterSize, nbrFreeClusters); + } + + virtual DWORD STDMETHODCALLTYPE ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone) + { + return BaseCom::ReadWriteFile (write, device, filePath, bufferBstr, offset, size, sizeDone); + } + + virtual DWORD STDMETHODCALLTYPE RegisterFilterDriver (BOOL registerDriver, int filterType) + { + return BaseCom::RegisterFilterDriver (registerDriver, filterType); + } + + virtual DWORD STDMETHODCALLTYPE RegisterSystemFavoritesService (BOOL registerService) + { + return BaseCom::RegisterSystemFavoritesService (registerService); + } + + virtual DWORD STDMETHODCALLTYPE SetDriverServiceStartType (DWORD startType) + { + return BaseCom::SetDriverServiceStartType (startType); + } + + virtual BOOL STDMETHODCALLTYPE IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) + { + return BaseCom::IsPagingFileActive (checkNonWindowsPartitionsOnly); + } + + virtual DWORD STDMETHODCALLTYPE WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value) + { + return BaseCom::WriteLocalMachineRegistryDwordValue (keyPath, valueName, value); + } + + virtual BOOL STDMETHODCALLTYPE FormatFs (int driveNo, int clusterSize, int fsType) + { + return ::FormatFs (driveNo, clusterSize, fsType); + } + +protected: + DWORD MessageThreadId; + LONG RefCount; + ITrueCryptFormatCom *CallBack; +}; + + +extern "C" BOOL ComServerFormat () +{ + SetProcessShutdownParameters (0x100, 0); + + TrueCryptFactory factory (GetCurrentThreadId ()); + DWORD cookie; + + if (IsUacSupported ()) + UacElevated = TRUE; + + if (CoRegisterClassObject (CLSID_TrueCryptFormatCom, (LPUNKNOWN) &factory, + CLSCTX_LOCAL_SERVER, REGCLS_SINGLEUSE, &cookie) != S_OK) + return FALSE; + + MSG msg; + while (int r = GetMessageW (&msg, NULL, 0, 0)) + { + if (r == -1) + return FALSE; + + TranslateMessage (&msg); + DispatchMessageW (&msg); + + if (msg.message == WM_APP + && ObjectCount < 1 + && !factory.IsServerLocked ()) + break; + } + CoRevokeClassObject (cookie); + + return TRUE; +} + + +static BOOL ComGetInstance (HWND hWnd, ITrueCryptFormatCom **tcServer) +{ + return ComGetInstanceBase (hWnd, CLSID_TrueCryptFormatCom, IID_ITrueCryptFormatCom, (void **) tcServer); +} + + +ITrueCryptFormatCom *GetElevatedInstance (HWND parent) +{ + ITrueCryptFormatCom *instance; + + if (!ComGetInstance (parent, &instance)) + throw UserAbort (SRC_POS); + + return instance; +} + + +extern "C" int UacFormatNtfs (HWND hWnd, int driveNo, int clusterSize) +{ + CComPtr tc; + int r; + + CoInitialize (NULL); + + if (ComGetInstance (hWnd, &tc)) + r = tc->FormatNtfs (driveNo, clusterSize); + else + r = 0; + + CoUninitialize (); + + return r; +} + +extern "C" int UacFormatFs (HWND hWnd, int driveNo, int clusterSize, int fsType) +{ + CComPtr tc; + int r; + + CoInitialize (NULL); + + if (ComGetInstance (hWnd, &tc)) + r = tc->FormatFs (driveNo, clusterSize, fsType); + else + r = 0; + + CoUninitialize (); + + return r; +} + + +extern "C" int UacAnalyzeHiddenVolumeHost (HWND hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *nbrFreeClusters) +{ + CComPtr tc; + int r; + + CoInitialize (NULL); + + if (ComGetInstance (hwndDlg, &tc)) + r = tc->AnalyzeHiddenVolumeHost ((LONG_PTR) hwndDlg, driveNo, hiddenVolHostSize, realClusterSize, nbrFreeClusters); + else + r = 0; + + CoUninitialize (); + + return r; +} diff --git a/src/Format/FormatCom.h b/src/Format/FormatCom.h index e79cd9cc..3d545b20 100644 --- a/src/Format/FormatCom.h +++ b/src/Format/FormatCom.h @@ -1,37 +1,37 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_FORMAT_COM -#define TC_HEADER_FORMAT_COM - -#include - -#ifdef __cplusplus - -#include "FormatCom_h.h" -ITrueCryptFormatCom *GetElevatedInstance (HWND parent); - -extern "C" { -#endif - -BOOL ComServerFormat (); -int UacFormatNtfs (HWND hWnd, int driveNo, int clusterSize); -int UacFormatFs (HWND hWnd, int driveNo, int clusterSize, int fsType); -int UacAnalyzeHiddenVolumeHost (HWND hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *nbrFreeClusters); -int UacFormatVolume (char *cvolumePath , BOOL bDevice , unsigned __int64 size , unsigned __int64 hiddenVolHostSize , Password *password , int cipher , int pkcs5 , BOOL quickFormat, BOOL sparseFileSwitch, int fileSystem , int clusterSize, HWND hwndDlg , BOOL hiddenVol , int *realClusterSize); -BOOL UacUpdateProgressBar (__int64 nSecNo, BOOL *bVolTransformThreadCancel); - -#ifdef __cplusplus -} -#endif - +/* + 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. +*/ + +#ifndef TC_HEADER_FORMAT_COM +#define TC_HEADER_FORMAT_COM + +#include + +#ifdef __cplusplus + +#include "FormatCom_h.h" +ITrueCryptFormatCom *GetElevatedInstance (HWND parent); + +extern "C" { +#endif + +BOOL ComServerFormat (); +int UacFormatNtfs (HWND hWnd, int driveNo, int clusterSize); +int UacFormatFs (HWND hWnd, int driveNo, int clusterSize, int fsType); +int UacAnalyzeHiddenVolumeHost (HWND hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *nbrFreeClusters); +int UacFormatVolume (char *cvolumePath , BOOL bDevice , unsigned __int64 size , unsigned __int64 hiddenVolHostSize , Password *password , int cipher , int pkcs5 , BOOL quickFormat, BOOL sparseFileSwitch, int fileSystem , int clusterSize, HWND hwndDlg , BOOL hiddenVol , int *realClusterSize); +BOOL UacUpdateProgressBar (__int64 nSecNo, BOOL *bVolTransformThreadCancel); + +#ifdef __cplusplus +} +#endif + #endif // TC_HEADER_FORMAT_COM \ No newline at end of file diff --git a/src/Format/FormatCom.idl b/src/Format/FormatCom.idl index 5579d28d..764663b1 100644 --- a/src/Format/FormatCom.idl +++ b/src/Format/FormatCom.idl @@ -1,53 +1,53 @@ -/* - 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. -*/ - -import "wtypes.idl"; -import "..\Common\Password.h"; - -[ - uuid(56327DDA-F1A7-4e13-B128-520D129BDEF6), - helpstring("VeraCrypt Format UAC Support Library"), - version(2.5) // Update ComSetup.cpp when changing version number -] -library TrueCryptFormatCom -{ - [ - uuid(7AB357D9-A17F-466e-BCD6-F49E97C218D8), - object, - oleautomation, - helpstring("VeraCrypt Format UAC Support Interface") - ] - interface ITrueCryptFormatCom : IUnknown - { - int AnalyzeHiddenVolumeHost (LONG_PTR hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *nbrFreeClusters); - DWORD CallDriver (DWORD ioctl, BSTR input, BSTR *output); - DWORD CopyFile (BSTR sourceFile, BSTR destinationFile); - DWORD DeleteFile (BSTR file); - BOOL FormatNtfs (int driveNo, int clusterSize); - BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly); - DWORD ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone); - DWORD RegisterFilterDriver (BOOL registerDriver, int filterType); - DWORD RegisterSystemFavoritesService (BOOL registerService); - DWORD SetDriverServiceStartType (DWORD startType); - DWORD WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value); - BOOL FormatFs (int driveNo, int clusterSize, int fsType); - }; - - [ - uuid(A96D3797-9F31-49f4-A0CE-9657392CF789), - helpstring("VeraCrypt Format UAC Support Coclass") - ] - coclass TrueCryptFormatCom - { - [default] interface ITrueCryptFormatCom; - } -} +/* + 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. +*/ + +import "wtypes.idl"; +import "..\Common\Password.h"; + +[ + uuid(56327DDA-F1A7-4e13-B128-520D129BDEF6), + helpstring("VeraCrypt Format UAC Support Library"), + version(2.5) // Update ComSetup.cpp when changing version number +] +library TrueCryptFormatCom +{ + [ + uuid(7AB357D9-A17F-466e-BCD6-F49E97C218D8), + object, + oleautomation, + helpstring("VeraCrypt Format UAC Support Interface") + ] + interface ITrueCryptFormatCom : IUnknown + { + int AnalyzeHiddenVolumeHost (LONG_PTR hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *nbrFreeClusters); + DWORD CallDriver (DWORD ioctl, BSTR input, BSTR *output); + DWORD CopyFile (BSTR sourceFile, BSTR destinationFile); + DWORD DeleteFile (BSTR file); + BOOL FormatNtfs (int driveNo, int clusterSize); + BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly); + DWORD ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone); + DWORD RegisterFilterDriver (BOOL registerDriver, int filterType); + DWORD RegisterSystemFavoritesService (BOOL registerService); + DWORD SetDriverServiceStartType (DWORD startType); + DWORD WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value); + BOOL FormatFs (int driveNo, int clusterSize, int fsType); + }; + + [ + uuid(A96D3797-9F31-49f4-A0CE-9657392CF789), + helpstring("VeraCrypt Format UAC Support Coclass") + ] + coclass TrueCryptFormatCom + { + [default] interface ITrueCryptFormatCom; + } +} diff --git a/src/Format/InPlace.c b/src/Format/InPlace.c index 720b9466..ff7fed1b 100644 --- a/src/Format/InPlace.c +++ b/src/Format/InPlace.c @@ -1,2293 +1,2293 @@ -/* - 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. -*/ - - -/* In this file, _WIN32_WINNT is defined as 0x0600 to make filesystem shrink available (Vista -or later). _WIN32_WINNT cannot be defined as 0x0600 for the entire user-space projects -because it breaks the main font app when the app is running on XP (likely an MS bug). -IMPORTANT: Due to this issue, functions in this file must not directly interact with GUI. */ -#define TC_LOCAL_WIN32_WINNT_OVERRIDE 1 -#if (_WIN32_WINNT < 0x0600) -# undef _WIN32_WINNT -# define _WIN32_WINNT 0x0600 -#endif - - -#include -#include -#include -#include - -#include "Tcdefs.h" -#include "Platform/Finally.h" - -#include "Common.h" -#include "Crc.h" -#include "Dlgcode.h" -#include "Language.h" -#include "Tcformat.h" -#include "Volumes.h" - -#include "InPlace.h" - -#include - -using namespace std; -using namespace VeraCrypt; - -#if TC_VOLUME_DATA_OFFSET != 131072 -# error TC_VOLUME_DATA_OFFSET != 131072 -#endif - -#if TC_VOLUME_HEADER_EFFECTIVE_SIZE != 512 -# error TC_VOLUME_HEADER_EFFECTIVE_SIZE != 512 -#endif - -#if TC_TOTAL_VOLUME_HEADERS_SIZE != 262144 -# error TC_TOTAL_VOLUME_HEADERS_SIZE != 262144 -#endif - -#define TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE (2048 * BYTES_PER_KB) -#define TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE (2 * TC_MAX_VOLUME_SECTOR_SIZE) -#define TC_NTFS_CONCEAL_CONSTANT 0xFF -#define TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL (64 * BYTES_PER_MB) -#define TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE (TC_TOTAL_VOLUME_HEADERS_SIZE + TC_MIN_NTFS_FS_SIZE * 2) - - -// If the returned value is greater than 0, it is the desired volume size in NTFS sectors (not in bytes) -// after shrinking has been performed. If there's any error, returns -1. -static __int64 NewFileSysSizeAfterShrink (HANDLE dev, const wchar_t *devicePath, int64 *totalClusterCount, DWORD *bytesPerCluster, BOOL silent) -{ - NTFS_VOLUME_DATA_BUFFER ntfsVolData; - DWORD nBytesReturned; - __int64 fileSysSize, desiredNbrSectors; - - // Filesystem size and sector size - - if (!DeviceIoControl (dev, - FSCTL_GET_NTFS_VOLUME_DATA, - NULL, - 0, - (LPVOID) &ntfsVolData, - sizeof (ntfsVolData), - &nBytesReturned, - NULL)) - { - if (!silent) - handleWin32Error (MainDlg, SRC_POS); - - return -1; - } - - if ( (ntfsVolData.NumberSectors.QuadPart <= 0) - || (ntfsVolData.NumberSectors.QuadPart > (INT64_MAX / (__int64) ntfsVolData.BytesPerSector)) // overflow test - ) - { - SetLastError (ERROR_INTERNAL_ERROR); - if (!silent) - handleWin32Error (MainDlg, SRC_POS); - - return -1; - } - - fileSysSize = ntfsVolData.NumberSectors.QuadPart * ntfsVolData.BytesPerSector; - - desiredNbrSectors = (fileSysSize - TC_TOTAL_VOLUME_HEADERS_SIZE) / ntfsVolData.BytesPerSector; - - if (desiredNbrSectors <= 0) - return -1; - - if (totalClusterCount) - *totalClusterCount = ntfsVolData.TotalClusters.QuadPart; - if (bytesPerCluster) - *bytesPerCluster = ntfsVolData.BytesPerCluster; - - return desiredNbrSectors; -} - - -BOOL CheckRequirementsForNonSysInPlaceEnc (HWND hwndDlg, const wchar_t *devicePath, BOOL silent) -{ - NTFS_VOLUME_DATA_BUFFER ntfsVolData; - DWORD nBytesReturned; - HANDLE dev; - WCHAR szFileSysName [256]; - WCHAR devPath [MAX_PATH]; - WCHAR dosDev [TC_MAX_PATH] = {0}; - WCHAR devName [MAX_PATH] = {0}; - int driveLetterNo = -1; - WCHAR szRootPath[4] = {0, L':', L'\\', 0}; - __int64 deviceSize; - int partitionNumber = -1, driveNumber = -1; - - - /* ---------- Checks that do not require admin rights ----------- */ - - - /* Operating system */ - - if (CurrentOSMajor < 6) - { - if (!silent) - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "OS_NOT_SUPPORTED_FOR_NONSYS_INPLACE_ENC", FALSE); - - return FALSE; - } - - - /* Volume type (must be a partition or a dynamic volume) */ - - if (swscanf (devicePath, L"\\Device\\HarddiskVolume%d", &partitionNumber) != 1 - && swscanf (devicePath, L"\\Device\\Harddisk%d\\Partition%d", &driveNumber, &partitionNumber) != 2) - { - if (!silent) - Error ("INPLACE_ENC_INVALID_PATH", hwndDlg); - - return FALSE; - } - - if (partitionNumber == 0) - { - if (!silent) - Warning ("RAW_DEV_NOT_SUPPORTED_FOR_INPLACE_ENC", hwndDlg); - - return FALSE; - } - - - /* Admin rights */ - - if (!IsAdmin()) - { - // We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC - // status can be ignored). In case the IsAdmin() detection somehow fails, we allow the user to continue. - - if (!silent) - Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", hwndDlg); - } - - - /* ---------- Checks that may require admin rights ----------- */ - - - /* Access to the partition */ - - StringCbCopyW (devPath, sizeof(devPath), devicePath); - - driveLetterNo = GetDiskDeviceDriveLetter (devPath); - - if (driveLetterNo >= 0) - szRootPath[0] = (wchar_t) driveLetterNo + L'A'; - - if (FakeDosNameForDevice (devicePath, dosDev, sizeof(dosDev), devName, sizeof(devName),FALSE) != 0) - { - if (!silent) - { - handleWin32Error (hwndDlg, SRC_POS); - Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg); - } - return FALSE; - } - - dev = OpenPartitionVolume (hwndDlg, devName, - FALSE, // Do not require exclusive access - TRUE, // Require shared access (must be TRUE; otherwise, volume properties will not be possible to obtain) - FALSE, // Do not ask the user to confirm shared access (if exclusive fails) - FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages) - silent); // Silent mode - - if (dev == INVALID_HANDLE_VALUE) - return FALSE; - - - /* File system type */ - - GetVolumeInformation (szRootPath, NULL, 0, NULL, NULL, NULL, szFileSysName, ARRAYSIZE (szFileSysName)); - - if (wcsncmp (szFileSysName, L"NTFS", 4)) - { - // The previous filesystem type detection method failed (or it's not NTFS) -- try an alternative method - - if (!DeviceIoControl (dev, - FSCTL_GET_NTFS_VOLUME_DATA, - NULL, - 0, - (LPVOID) &ntfsVolData, - sizeof (ntfsVolData), - &nBytesReturned, - NULL)) - { - if (!silent) - { - // The filesystem is not NTFS or the filesystem type could not be determined (or the NTFS filesystem - // is dismounted). - - if (IsDeviceMounted (devName)) - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "ONLY_NTFS_SUPPORTED_FOR_NONSYS_INPLACE_ENC", FALSE); - else - Warning ("ONLY_MOUNTED_VOL_SUPPORTED_FOR_NONSYS_INPLACE_ENC", hwndDlg); - } - - CloseHandle (dev); - return FALSE; - } - } - - - /* Attempt to determine whether the filesystem can be safely shrunk */ - - if (NewFileSysSizeAfterShrink (dev, devicePath, NULL, NULL, silent) == -1) - { - // Cannot determine whether shrinking is required - if (!silent) - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE); - - CloseHandle (dev); - return FALSE; - } - - - /* Partition size */ - - deviceSize = GetDeviceSize (devicePath); - if (deviceSize < 0) - { - // Cannot determine the size of the partition - if (!silent) - Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg); - - CloseHandle (dev); - return FALSE; - } - - if (deviceSize < TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE) - { - // The partition is too small - if (!silent) - { - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "PARTITION_TOO_SMALL_FOR_NONSYS_INPLACE_ENC", FALSE); - } - - CloseHandle (dev); - return FALSE; - } - - - /* Free space on the filesystem */ - - if (!DeviceIoControl (dev, - FSCTL_GET_NTFS_VOLUME_DATA, - NULL, - 0, - (LPVOID) &ntfsVolData, - sizeof (ntfsVolData), - &nBytesReturned, - NULL)) - { - if (!silent) - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", TRUE); - - CloseHandle (dev); - return FALSE; - } - - if (ntfsVolData.FreeClusters.QuadPart * ntfsVolData.BytesPerCluster < TC_TOTAL_VOLUME_HEADERS_SIZE) - { - if (!silent) - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "NOT_ENOUGH_FREE_FILESYS_SPACE_FOR_SHRINK", TRUE); - - CloseHandle (dev); - return FALSE; - } - - - /* Filesystem sector size */ - - if (ntfsVolData.BytesPerSector > TC_MAX_VOLUME_SECTOR_SIZE - || ntfsVolData.BytesPerSector % ENCRYPTION_DATA_UNIT_SIZE != 0) - { - if (!silent) - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "SECTOR_SIZE_UNSUPPORTED", TRUE); - - CloseHandle (dev); - return FALSE; - } - - - CloseHandle (dev); - return TRUE; -} - -BOOL CheckRequirementsForNonSysInPlaceDec (HWND hwndDlg, const wchar_t *devicePath, BOOL silent) -{ - int partitionNumber = -1, driveNumber = -1; - - /* ---------- Checks that do not require admin rights ----------- */ - - /* Volume type (must be a partition or a dynamic volume) */ - if ((swscanf (devicePath, L"\\Device\\HarddiskVolume%d", &partitionNumber) != 1 - && swscanf (devicePath, L"\\Device\\Harddisk%d\\Partition%d", &driveNumber, &partitionNumber) != 2) - || partitionNumber == 0) - { - if (!silent) - Error ("INPLACE_ENC_INVALID_PATH", hwndDlg); - - return FALSE; - } - - - /* Admin rights */ - if (!IsAdmin()) - { - // We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC - // status can be ignored). In case the IsAdmin() detection somehow fails, we allow the user to continue. - - if (!silent) - Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", hwndDlg); - } - - - /* ---------- Checks that may require admin rights ----------- */ - - // [Currently none] - - return TRUE; -} - - -int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, volatile HANDLE *outHandle, WipeAlgorithmId wipeAlgorithm) -{ - SHRINK_VOLUME_INFORMATION shrinkVolInfo; - signed __int64 sizeToShrinkTo; - int nStatus = ERR_SUCCESS; - PCRYPTO_INFO cryptoInfo = NULL; - PCRYPTO_INFO cryptoInfo2 = NULL; - HANDLE dev = INVALID_HANDLE_VALUE; - DWORD dwError; - char *header; - WCHAR dosDev[TC_MAX_PATH] = {0}; - WCHAR devName[MAX_PATH] = {0}; - int driveLetter = -1; - WCHAR deviceName[MAX_PATH]; - uint64 dataAreaSize; - __int64 deviceSize; - LARGE_INTEGER offset; - DWORD dwResult; - HWND hwndDlg = volParams->hwndDlg; - - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PREPARING); - - - if (!CheckRequirementsForNonSysInPlaceEnc (hwndDlg, volParams->volumePath, FALSE)) - return ERR_DONT_REPORT; - - - header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE); - if (!header) - return ERR_OUTOFMEMORY; - - VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - - deviceSize = GetDeviceSize (volParams->volumePath); - if (deviceSize < 0) - { - // Cannot determine the size of the partition - nStatus = ERR_PARAMETER_INCORRECT; - goto closing_seq; - } - - if (deviceSize < TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE) - { - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "PARTITION_TOO_SMALL_FOR_NONSYS_INPLACE_ENC", TRUE); - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - - dataAreaSize = GetVolumeDataAreaSize (volParams->hiddenVol, deviceSize); - - StringCchCopyW (deviceName, ARRAYSIZE(deviceName), volParams->volumePath); - - driveLetter = GetDiskDeviceDriveLetter (deviceName); - - - if (FakeDosNameForDevice (volParams->volumePath, dosDev, sizeof(dosDev),devName, sizeof(devName),FALSE) != 0) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - if (IsDeviceMounted (devName)) - { - dev = OpenPartitionVolume (hwndDlg, devName, - FALSE, // Do not require exclusive access (must be FALSE; otherwise, it will not be possible to dismount the volume or obtain its properties and FSCTL_ALLOW_EXTENDED_DASD_IO will fail too) - TRUE, // Require shared access (must be TRUE; otherwise, it will not be possible to dismount the volume or obtain its properties and FSCTL_ALLOW_EXTENDED_DASD_IO will fail too) - FALSE, // Do not ask the user to confirm shared access (if exclusive fails) - FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages) - FALSE); // Non-silent mode - - if (dev == INVALID_HANDLE_VALUE) - { - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - } - else - { - // The volume is not mounted so we can't work with the filesystem. - Error ("ONLY_MOUNTED_VOL_SUPPORTED_FOR_NONSYS_INPLACE_ENC", hwndDlg); - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - - - /* Gain "raw" access to the partition (the NTFS driver guards hidden sectors). */ - - if (!DeviceIoControl (dev, - FSCTL_ALLOW_EXTENDED_DASD_IO, - NULL, - 0, - NULL, - 0, - &dwResult, - NULL)) - { - handleWin32Error (MainDlg, SRC_POS); - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE); - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - - - - /* Shrink the filesystem */ - - int64 totalClusterCount; - DWORD bytesPerCluster; - - sizeToShrinkTo = NewFileSysSizeAfterShrink (dev, volParams->volumePath, &totalClusterCount, &bytesPerCluster, FALSE); - - if (sizeToShrinkTo == -1) - { - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE); - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_RESIZING); - - memset (&shrinkVolInfo, 0, sizeof (shrinkVolInfo)); - - shrinkVolInfo.ShrinkRequestType = ShrinkPrepare; - shrinkVolInfo.NewNumberOfSectors = sizeToShrinkTo; - - if (!DeviceIoControl (dev, - FSCTL_SHRINK_VOLUME, - (LPVOID) &shrinkVolInfo, - sizeof (shrinkVolInfo), - NULL, - 0, - &dwResult, - NULL)) - { - handleWin32Error (hwndDlg, SRC_POS); - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "CANNOT_RESIZE_FILESYS", TRUE); - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - - BOOL clustersMovedBeforeVolumeEnd = FALSE; - - while (true) - { - shrinkVolInfo.ShrinkRequestType = ShrinkCommit; - shrinkVolInfo.NewNumberOfSectors = 0; - - if (!DeviceIoControl (dev, FSCTL_SHRINK_VOLUME, &shrinkVolInfo, sizeof (shrinkVolInfo), NULL, 0, &dwResult, NULL)) - { - // If there are any occupied clusters beyond the new desired end of the volume, the call fails with - // ERROR_ACCESS_DENIED (STATUS_ALREADY_COMMITTED). - if (GetLastError () == ERROR_ACCESS_DENIED) - { - if (!clustersMovedBeforeVolumeEnd) - { - if (MoveClustersBeforeThreshold (dev, deviceName, totalClusterCount - (bytesPerCluster > TC_TOTAL_VOLUME_HEADERS_SIZE ? 1 : TC_TOTAL_VOLUME_HEADERS_SIZE / bytesPerCluster))) - { - clustersMovedBeforeVolumeEnd = TRUE; - continue; - } - - handleWin32Error (hwndDlg, SRC_POS); - } - } - else - handleWin32Error (hwndDlg, SRC_POS); - - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "CANNOT_RESIZE_FILESYS", TRUE); - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - - break; - } - - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PREPARING); - - - /* Gain exclusive access to the volume */ - - nStatus = DismountFileSystem (hwndDlg, dev, - driveLetter, - TRUE, - TRUE, - FALSE); - - if (nStatus != ERR_SUCCESS) - { - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - - - - /* Create header backup on the partition. Until the volume is fully encrypted, the backup header will provide - us with the master key, encrypted range, and other data for pause/resume operations. We cannot create the - primary header until the entire partition is encrypted (because we encrypt backwards and the primary header - area is occuppied by data until the very end of the process). */ - - // Prepare the backup header - for (int wipePass = 0; wipePass < (wipeAlgorithm == TC_WIPE_NONE ? 1 : PRAND_HEADER_WIPE_PASSES); wipePass++) - { - nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE, - header, - volParams->ea, - FIRST_MODE_OF_OPERATION_ID, - volParams->password, - volParams->pkcs5, - volParams->pim, - wipePass == 0 ? NULL : (char *) cryptoInfo->master_keydata, - &cryptoInfo, - dataAreaSize, - 0, - TC_VOLUME_DATA_OFFSET + dataAreaSize, // Start of the encrypted area = the first byte of the backup heeader (encrypting from the end) - 0, // No data is encrypted yet - 0, - volParams->headerFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC, - volParams->sectorSize, - wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_HEADER_WIPE_PASSES - 1)); - - if (nStatus != 0) - goto closing_seq; - - offset.QuadPart = TC_VOLUME_DATA_OFFSET + dataAreaSize; - - if (!SetFilePointerEx (dev, offset, NULL, FILE_BEGIN)) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - // Write the backup header to the partition - if (!WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header)) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - // Fill the reserved sectors of the backup header area with random data - nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, dataAreaSize, FALSE, TRUE); - - if (nStatus != ERR_SUCCESS) - goto closing_seq; - } - - - /* Now we will try to decrypt the backup header to verify it has been correctly written. */ - - nStatus = OpenBackupHeader (dev, volParams->volumePath, volParams->password, volParams->pkcs5, volParams->pim, &cryptoInfo2, NULL, deviceSize); - - if (nStatus != ERR_SUCCESS - || cryptoInfo->EncryptedAreaStart.Value != cryptoInfo2->EncryptedAreaStart.Value - || cryptoInfo2->EncryptedAreaStart.Value == 0) - { - if (nStatus == ERR_SUCCESS) - nStatus = ERR_PARAMETER_INCORRECT; - - goto closing_seq; - } - - // The backup header is valid so we know we should be able to safely resume in-place encryption - // of this partition even if the system/app crashes. - - - - /* Conceal the NTFS filesystem (by performing an easy-to-undo modification). This will prevent Windows - and apps from interfering with the volume until it has been fully encrypted. */ - - nStatus = ConcealNTFS (dev); - - if (nStatus != ERR_SUCCESS) - goto closing_seq; - - - - // /* If a drive letter is assigned to the device, remove it (so that users do not try to open it, which - //would cause Windows to ask them if they want to format the volume and other dangerous things). */ - - //if (driveLetter >= 0) - //{ - // char rootPath[] = { driveLetter + 'A', ':', '\\', 0 }; - - // // Try to remove the assigned drive letter - // if (DeleteVolumeMountPoint (rootPath)) - // driveLetter = -1; - //} - - - - /* Update config files and app data */ - - // In the config file, increase the number of partitions where in-place encryption is in progress - - SaveNonSysInPlaceEncSettings (1, wipeAlgorithm, FALSE); - - - // Add the wizard to the system startup sequence if appropriate - - if (!IsNonInstallMode ()) - ManageStartupSeqWiz (FALSE, L"/prinplace"); - - - nStatus = ERR_SUCCESS; - - -closing_seq: - - dwError = GetLastError(); - - if (cryptoInfo != NULL) - { - crypto_close (cryptoInfo); - cryptoInfo = NULL; - } - - if (cryptoInfo2 != NULL) - { - crypto_close (cryptoInfo2); - cryptoInfo2 = NULL; - } - - burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - TCfree (header); - - if (dosDev[0]) - RemoveFakeDosName (volParams->volumePath, dosDev); - - *outHandle = dev; - - if (nStatus != ERR_SUCCESS) - SetLastError (dwError); - - return nStatus; -} - - -int EncryptPartitionInPlaceResume (HANDLE dev, - volatile FORMAT_VOL_PARAMETERS *volParams, - WipeAlgorithmId wipeAlgorithm, - volatile BOOL *bTryToCorrectReadErrors) -{ - PCRYPTO_INFO masterCryptoInfo = NULL, headerCryptoInfo = NULL, tmpCryptoInfo = NULL; - UINT64_STRUCT unitNo; - char *buf = NULL, *header = NULL; - byte *wipeBuffer = NULL; - byte wipeRandChars [TC_WIPE_RAND_CHAR_COUNT]; - byte wipeRandCharsUpdate [TC_WIPE_RAND_CHAR_COUNT]; - WCHAR dosDev[TC_MAX_PATH] = {0}; - WCHAR devName[MAX_PATH] = {0}; - WCHAR deviceName[MAX_PATH]; - int nStatus = ERR_SUCCESS; - __int64 deviceSize; - uint64 remainingBytes, lastHeaderUpdateDistance = 0, zeroedSectorCount = 0; - uint32 workChunkSize; - DWORD dwError, dwResult; - BOOL bPause = FALSE, bEncryptedAreaSizeChanged = FALSE; - LARGE_INTEGER offset; - int sectorSize; - int i; - DWORD n; - WCHAR *devicePath = volParams->volumePath; - Password *password = volParams->password; - int pkcs5_prf = volParams->pkcs5; - int pim = volParams->pim; - DISK_GEOMETRY driveGeometry; - HWND hwndDlg = volParams->hwndDlg; - - - bInPlaceEncNonSysResumed = TRUE; - - buf = (char *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE); - if (!buf) - { - nStatus = ERR_OUTOFMEMORY; - goto closing_seq; - } - - header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE); - if (!header) - { - nStatus = ERR_OUTOFMEMORY; - goto closing_seq; - } - - VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - - if (wipeAlgorithm != TC_WIPE_NONE) - { - wipeBuffer = (byte *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE); - if (!wipeBuffer) - { - nStatus = ERR_OUTOFMEMORY; - goto closing_seq; - } - } - - headerCryptoInfo = crypto_open(); - - if (headerCryptoInfo == NULL) - { - nStatus = ERR_OUTOFMEMORY; - goto closing_seq; - } - - deviceSize = GetDeviceSize (devicePath); - if (deviceSize < 0) - { - // Cannot determine the size of the partition - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - if (dev == INVALID_HANDLE_VALUE) - { - StringCchCopyW (deviceName, ARRAYSIZE(deviceName), devicePath); - - if (FakeDosNameForDevice (deviceName, dosDev, sizeof(dosDev),devName, sizeof(devName),FALSE) != 0) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - dev = OpenPartitionVolume (hwndDlg, devName, - FALSE, // Do not require exclusive access - FALSE, // Do not require shared access - TRUE, // Ask the user to confirm shared access (if exclusive fails) - FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages) - FALSE); // Non-silent mode - - if (dev == INVALID_HANDLE_VALUE) - { - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - } - - // This should never be needed, but is still performed for extra safety (without checking the result) - DeviceIoControl (dev, - FSCTL_ALLOW_EXTENDED_DASD_IO, - NULL, - 0, - NULL, - 0, - &dwResult, - NULL); - - - if (!DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveGeometry, sizeof (driveGeometry), &dwResult, NULL)) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - sectorSize = driveGeometry.BytesPerSector; - - - nStatus = OpenBackupHeader (dev, devicePath, password, pkcs5_prf, pim, &masterCryptoInfo, headerCryptoInfo, deviceSize); - - if (nStatus != ERR_SUCCESS) - goto closing_seq; - - - - remainingBytes = masterCryptoInfo->VolumeSize.Value - masterCryptoInfo->EncryptedAreaLength.Value; - - lastHeaderUpdateDistance = 0; - - - ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value); - - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_ENCRYPTING); - - bFirstNonSysInPlaceEncResumeDone = TRUE; - - - /* The in-place encryption core */ - - while (remainingBytes > 0) - { - workChunkSize = (uint32) min (remainingBytes, TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE); - - if (workChunkSize % ENCRYPTION_DATA_UNIT_SIZE != 0) - { - nStatus = ERR_PARAMETER_INCORRECT; - goto closing_seq; - } - - unitNo.Value = (remainingBytes - workChunkSize + TC_VOLUME_DATA_OFFSET) / ENCRYPTION_DATA_UNIT_SIZE; - - - // Read the plaintext into RAM - -inplace_enc_read: - - offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize - TC_VOLUME_DATA_OFFSET; - - if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - if (ReadFile (dev, buf, workChunkSize, &n, NULL) == 0) - { - // Read error - - DWORD dwTmpErr = GetLastError (); - - if (IsDiskReadError (dwTmpErr) && !bVolTransformThreadCancel) - { - // Physical defect or data corruption - - if (!*bTryToCorrectReadErrors) - { - *bTryToCorrectReadErrors = (AskWarnYesNo ("ENABLE_BAD_SECTOR_ZEROING", hwndDlg) == IDYES); - } - - if (*bTryToCorrectReadErrors) - { - // Try to correct the read errors physically - - offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize - TC_VOLUME_DATA_OFFSET; - - nStatus = ZeroUnreadableSectors (dev, offset, workChunkSize, sectorSize, &zeroedSectorCount); - - if (nStatus != ERR_SUCCESS) - { - // Due to write errors, we can't correct the read errors - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - goto inplace_enc_read; - } - } - - SetLastError (dwTmpErr); // Preserve the original error code - - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - if (remainingBytes - workChunkSize < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE) - { - // We reached the inital portion of the filesystem, which we had concealed (in order to prevent - // Windows from interfering with the volume). Now we need to undo that modification. - - for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE - (remainingBytes - workChunkSize); i++) - buf[i] ^= TC_NTFS_CONCEAL_CONSTANT; - } - - - // Encrypt the plaintext in RAM - - EncryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo); - - - // If enabled, wipe the area to which we will write the ciphertext - - if (wipeAlgorithm != TC_WIPE_NONE) - { - byte wipePass; - int wipePassCount = GetWipePassCount (wipeAlgorithm); - - if (wipePassCount <= 0) - { - SetLastError (ERROR_INVALID_PARAMETER); - nStatus = ERR_PARAMETER_INCORRECT; - goto closing_seq; - } - - offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize; - - for (wipePass = 1; wipePass <= wipePassCount; ++wipePass) - { - if (!WipeBuffer (wipeAlgorithm, wipeRandChars, wipePass, wipeBuffer, workChunkSize)) - { - ULONG i; - for (i = 0; i < workChunkSize; ++i) - { - wipeBuffer[i] = buf[i] + wipePass; - } - - EncryptDataUnits (wipeBuffer, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo); - memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate)); - } - - if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 - || WriteFile (dev, wipeBuffer, workChunkSize, &n, NULL) == 0) - { - // Write error - dwError = GetLastError(); - - // Undo failed write operation - if (workChunkSize > TC_VOLUME_DATA_OFFSET && SetFilePointerEx (dev, offset, NULL, FILE_BEGIN)) - { - DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo); - WriteFile (dev, buf + TC_VOLUME_DATA_OFFSET, workChunkSize - TC_VOLUME_DATA_OFFSET, &n, NULL); - } - - SetLastError (dwError); - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - } - - memcpy (wipeRandChars, wipeRandCharsUpdate, sizeof (wipeRandCharsUpdate)); - } - - - // Write the ciphertext - - offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize; - - if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - if (WriteFile (dev, buf, workChunkSize, &n, NULL) == 0) - { - // Write error - dwError = GetLastError(); - - // Undo failed write operation - if (workChunkSize > TC_VOLUME_DATA_OFFSET && SetFilePointerEx (dev, offset, NULL, FILE_BEGIN)) - { - DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo); - WriteFile (dev, buf + TC_VOLUME_DATA_OFFSET, workChunkSize - TC_VOLUME_DATA_OFFSET, &n, NULL); - } - - SetLastError (dwError); - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - - masterCryptoInfo->EncryptedAreaStart.Value -= workChunkSize; - masterCryptoInfo->EncryptedAreaLength.Value += workChunkSize; - - remainingBytes -= workChunkSize; - lastHeaderUpdateDistance += workChunkSize; - - bEncryptedAreaSizeChanged = TRUE; - - if (lastHeaderUpdateDistance >= TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL) - { - nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize); - - if (nStatus != ERR_SUCCESS) - goto closing_seq; - - lastHeaderUpdateDistance = 0; - } - - ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value); - - if (bVolTransformThreadCancel) - { - bPause = TRUE; - break; - } - } - - nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize); - - - if (nStatus != ERR_SUCCESS) - goto closing_seq; - - - if (!bPause) - { - /* The data area has been fully encrypted; create and write the primary volume header */ - - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINALIZING); - - for (int wipePass = 0; wipePass < (wipeAlgorithm == TC_WIPE_NONE ? 1 : PRAND_HEADER_WIPE_PASSES); wipePass++) - { - nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE, - header, - headerCryptoInfo->ea, - headerCryptoInfo->mode, - password, - masterCryptoInfo->pkcs5, - pim, - (char *) masterCryptoInfo->master_keydata, - &tmpCryptoInfo, - masterCryptoInfo->VolumeSize.Value, - 0, - masterCryptoInfo->EncryptedAreaStart.Value, - masterCryptoInfo->EncryptedAreaLength.Value, - masterCryptoInfo->RequiredProgramVersion, - masterCryptoInfo->HeaderFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC, - masterCryptoInfo->SectorSize, - wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_HEADER_WIPE_PASSES - 1)); - - if (nStatus != ERR_SUCCESS) - goto closing_seq; - - - offset.QuadPart = TC_VOLUME_HEADER_OFFSET; - - if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 - || !WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header)) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - // Fill the reserved sectors of the header area with random data - nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, headerCryptoInfo, masterCryptoInfo->VolumeSize.Value, TRUE, FALSE); - - if (nStatus != ERR_SUCCESS) - goto closing_seq; - } - - // Update the configuration files - - SaveNonSysInPlaceEncSettings (-1, wipeAlgorithm, FALSE); - - - - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINISHED); - - nStatus = ERR_SUCCESS; - } - else - { - // The process has been paused by the user or aborted by the wizard (e.g. on app exit) - - nStatus = ERR_USER_ABORT; - - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED); - } - - -closing_seq: - - dwError = GetLastError(); - - if (bEncryptedAreaSizeChanged - && dev != INVALID_HANDLE_VALUE - && masterCryptoInfo != NULL - && headerCryptoInfo != NULL - && deviceSize > 0) - { - // Execution of the core loop may have been interrupted due to an error or user action without updating the header - FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize); - } - - if (masterCryptoInfo != NULL) - { - crypto_close (masterCryptoInfo); - masterCryptoInfo = NULL; - } - - if (headerCryptoInfo != NULL) - { - crypto_close (headerCryptoInfo); - headerCryptoInfo = NULL; - } - - if (tmpCryptoInfo != NULL) - { - crypto_close (tmpCryptoInfo); - tmpCryptoInfo = NULL; - } - - if (dosDev[0]) - RemoveFakeDosName (devicePath, dosDev); - - if (dev != INVALID_HANDLE_VALUE) - { - CloseHandle (dev); - dev = INVALID_HANDLE_VALUE; - } - - if (buf != NULL) - TCfree (buf); - - if (header != NULL) - { - burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - TCfree (header); - } - - if (wipeBuffer != NULL) - TCfree (wipeBuffer); - - if (zeroedSectorCount > 0) - { - wchar_t msg[30000] = {0}; - wchar_t sizeStr[500] = {0}; - - GetSizeString (zeroedSectorCount * sectorSize, sizeStr, sizeof(sizeStr)); - - StringCbPrintfW (msg, sizeof(msg), - GetString ("ZEROED_BAD_SECTOR_COUNT"), - zeroedSectorCount, - sizeStr); - - WarningDirect (msg, hwndDlg); - } - - if (nStatus != ERR_SUCCESS && nStatus != ERR_USER_ABORT) - SetLastError (dwError); - - return nStatus; -} - -int DecryptPartitionInPlace (volatile FORMAT_VOL_PARAMETERS *volParams, volatile BOOL *DiscardUnreadableEncryptedSectors) -{ - HANDLE dev = INVALID_HANDLE_VALUE; - PCRYPTO_INFO masterCryptoInfo = NULL, headerCryptoInfo = NULL; - UINT64_STRUCT unitNo; - char *buf = NULL; - byte *tmpSectorBuf = NULL; - WCHAR dosDev[TC_MAX_PATH] = {0}; - WCHAR devName[MAX_PATH] = {0}; - WCHAR deviceName[MAX_PATH]; - int nStatus = ERR_SUCCESS; - __int64 deviceSize; - uint64 remainingBytes, workChunkStartByteOffset, lastHeaderUpdateDistance = 0, skippedBadSectorCount = 0; - uint32 workChunkSize; - DWORD dwError, dwResult; - BOOL bPause = FALSE, bEncryptedAreaSizeChanged = FALSE; - LARGE_INTEGER offset; - int sectorSize; - int i; - DWORD n; - WCHAR *devicePath = volParams->volumePath; - Password *password = volParams->password; - HWND hwndDlg = volParams->hwndDlg; - int pkcs5_prf = volParams->pkcs5; - int pim = volParams->pim; - DISK_GEOMETRY driveGeometry; - - - buf = (char *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE); - if (!buf) - { - nStatus = ERR_OUTOFMEMORY; - goto closing_seq; - } - - headerCryptoInfo = crypto_open(); - - if (headerCryptoInfo == NULL) - { - nStatus = ERR_OUTOFMEMORY; - goto closing_seq; - } - - deviceSize = GetDeviceSize (devicePath); - if (deviceSize < 0) - { - // Cannot determine the size of the partition - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - - // The wizard should have dismounted the TC volume if it was mounted, but for extra safety we will check this again. - if (IsMountedVolume (devicePath)) - { - int driveLetter = GetMountedVolumeDriveNo (devicePath); - - if (driveLetter == -1 - || !UnmountVolume (hwndDlg, driveLetter, TRUE)) - { - handleWin32Error (hwndDlg, SRC_POS); - AbortProcess ("CANT_DISMOUNT_VOLUME"); - } - } - - - StringCchCopyW (deviceName, ARRAYSIZE(deviceName), devicePath); - - if (FakeDosNameForDevice (deviceName, dosDev, sizeof(dosDev), devName, sizeof(devName), FALSE) != 0) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - dev = OpenPartitionVolume (hwndDlg, devName, - TRUE, // Require exclusive access - FALSE, // Do not require shared access - TRUE, // Ask the user to confirm shared access (if exclusive fails) - FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages) - FALSE); // Non-silent mode - - if (dev == INVALID_HANDLE_VALUE) - { - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - - - - // This should never be needed, but is still performed for extra safety (without checking the result) - DeviceIoControl (dev, - FSCTL_ALLOW_EXTENDED_DASD_IO, - NULL, - 0, - NULL, - 0, - &dwResult, - NULL); - - - if (!DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveGeometry, sizeof (driveGeometry), &dwResult, NULL)) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - if ( (driveGeometry.BytesPerSector == 0) - || (driveGeometry.BytesPerSector > TC_MAX_VOLUME_SECTOR_SIZE) - || (driveGeometry.BytesPerSector % ENCRYPTION_DATA_UNIT_SIZE != 0) - ) - { - Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg); - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - - sectorSize = driveGeometry.BytesPerSector; - - - tmpSectorBuf = (byte *) TCalloc (sectorSize); - if (!tmpSectorBuf) - { - nStatus = ERR_OUTOFMEMORY; - goto closing_seq; - } - - - nStatus = OpenBackupHeader (dev, devicePath, password, pkcs5_prf, pim, &masterCryptoInfo, headerCryptoInfo, deviceSize); - - if (nStatus != ERR_SUCCESS) - goto closing_seq; - - - if (masterCryptoInfo->LegacyVolume) - { - Error ("NONSYS_INPLACE_DECRYPTION_BAD_VOL_FORMAT", hwndDlg); - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - - if (masterCryptoInfo->hiddenVolume) - { - Error ("NONSYS_INPLACE_DECRYPTION_CANT_DECRYPT_HID_VOL", hwndDlg); - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - - if (!bInPlaceEncNonSysResumed - && masterCryptoInfo->VolumeSize.Value == masterCryptoInfo->EncryptedAreaLength.Value) - { - /* Decryption started (not resumed) */ - - if ((masterCryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) == 0) - { - // The volume has not been encrypted in-place so it may contain a hidden volume. - // Ask the user to confirm it does not. - - char *tmpStr[] = {0, - "CONFIRM_VOL_CONTAINS_NO_HIDDEN_VOL", - "VOL_CONTAINS_NO_HIDDEN_VOL", - "VOL_CONTAINS_A_HIDDEN_VOL", - 0}; - - switch (AskMultiChoice ((void **) tmpStr, FALSE, hwndDlg)) - { - case 1: - // NOP - break; - case 2: - default: - // Cancel - nStatus = ERR_DONT_REPORT; - goto closing_seq; - } - } - - // Update config files and app data - - // In the config file, increase the number of partitions where in-place decryption is in progress - SaveNonSysInPlaceEncSettings (1, TC_WIPE_NONE, TRUE); - - // Add the wizard to the system startup sequence if appropriate - if (!IsNonInstallMode ()) - ManageStartupSeqWiz (FALSE, L"/prinplace"); - } - - - - bInPlaceEncNonSysResumed = TRUE; - bFirstNonSysInPlaceEncResumeDone = TRUE; - - - remainingBytes = masterCryptoInfo->EncryptedAreaLength.Value; - - lastHeaderUpdateDistance = 0; - - - ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value); - - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_DECRYPTING); - - - - /* The in-place decryption core */ - - while (remainingBytes > 0) - { - workChunkSize = (uint32) min (remainingBytes, TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE); - - if (workChunkSize % ENCRYPTION_DATA_UNIT_SIZE != 0) - { - nStatus = ERR_PARAMETER_INCORRECT; - goto closing_seq; - } - - workChunkStartByteOffset = masterCryptoInfo->EncryptedAreaStart.Value; - - unitNo.Value = workChunkStartByteOffset / ENCRYPTION_DATA_UNIT_SIZE; - - - // Read the ciphertext into RAM - - offset.QuadPart = workChunkStartByteOffset; - - if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - if (ReadFile (dev, buf, workChunkSize, &n, NULL) == 0) - { - // Read error - - DWORD dwTmpErr = GetLastError (); - - if (IsDiskReadError (dwTmpErr) && !bVolTransformThreadCancel) - { - // Physical defect or data corruption - - if (!*DiscardUnreadableEncryptedSectors) - { - *DiscardUnreadableEncryptedSectors = (AskWarnYesNo ("DISCARD_UNREADABLE_ENCRYPTED_SECTORS", hwndDlg) == IDYES); - } - - if (*DiscardUnreadableEncryptedSectors) - { - // Read the work chunk again, but this time each sector individually and skiping each bad sector - - LARGE_INTEGER tmpSectorOffset; - uint64 tmpSectorCount; - uint64 tmpBufOffset = 0; - DWORD tmpNbrReadBytes = 0; - - tmpSectorOffset.QuadPart = offset.QuadPart; - - for (tmpSectorCount = workChunkSize / sectorSize; tmpSectorCount > 0; --tmpSectorCount) - { - if (SetFilePointerEx (dev, tmpSectorOffset, NULL, FILE_BEGIN) == 0) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - if (ReadFile (dev, tmpSectorBuf, sectorSize, &tmpNbrReadBytes, NULL) == 0 - || tmpNbrReadBytes != (DWORD) sectorSize) - { - // Read error - - // Clear the buffer so the content of each unreadable sector is replaced with decrypted all-zero blocks (producing pseudorandom data) - memset (tmpSectorBuf, 0, sectorSize); - - skippedBadSectorCount++; - } - - memcpy (buf + tmpBufOffset, tmpSectorBuf, sectorSize); - - tmpSectorOffset.QuadPart += sectorSize; - tmpBufOffset += sectorSize; - } - } - else - { - SetLastError (dwTmpErr); // Preserve the original error code - - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - } - else - { - SetLastError (dwTmpErr); // Preserve the original error code - - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - } - - // Decrypt the ciphertext in RAM - - DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo); - - - - // Conceal initial portion of the filesystem - - if (workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE) - { - // We are decrypting the initial TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE bytes of the filesystem. We will - // conceal this portion to prevent Windows and applications from interfering with the volume. - - for (i = 0; i < min (TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET + workChunkSize); i++) - buf[i] ^= TC_NTFS_CONCEAL_CONSTANT; - } - - - // Write the plaintext - - offset.QuadPart = workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET; - - if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - if (WriteFile (dev, buf, workChunkSize, &n, NULL) == 0) - { - // Write error - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - - masterCryptoInfo->EncryptedAreaStart.Value += workChunkSize; - masterCryptoInfo->EncryptedAreaLength.Value -= workChunkSize; - - remainingBytes -= workChunkSize; - lastHeaderUpdateDistance += workChunkSize; - - bEncryptedAreaSizeChanged = TRUE; - - if (lastHeaderUpdateDistance >= TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL) - { - nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize); - - if (nStatus != ERR_SUCCESS) - { - // Possible write error - goto closing_seq; - } - - lastHeaderUpdateDistance = 0; - } - - ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value); - - if (bVolTransformThreadCancel) - { - bPause = TRUE; - break; - } - } - - nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize); - - - if (nStatus != ERR_SUCCESS) - { - // Possible write error - goto closing_seq; - } - - - if (!bPause) - { - /* Volume has been fully decrypted. */ - - - // Prevent attempts to update volume header during the closing sequence - bEncryptedAreaSizeChanged = FALSE; - - - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINALIZING); - - - - /* Undo concealing of the filesystem */ - - nStatus = ConcealNTFS (dev); - - if (nStatus != ERR_SUCCESS) - goto closing_seq; - - - - /* Ovewrite the backup header and the remaining ciphertext with all-zero blocks (the primary header was overwritten with the decrypted data). */ - - memset (tmpSectorBuf, 0, sectorSize); - - for (offset.QuadPart = masterCryptoInfo->VolumeSize.Value; - offset.QuadPart <= deviceSize - sectorSize; - offset.QuadPart += sectorSize) - { - if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - if (WriteFile (dev, tmpSectorBuf, sectorSize, &n, NULL) == 0) - { - // Write error - dwError = GetLastError(); - - SetLastError (dwError); - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - } - - - - /* Update the configuration files */ - - SaveNonSysInPlaceEncSettings (-1, TC_WIPE_NONE, TRUE); - - - - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINISHED); - - nStatus = ERR_SUCCESS; - - } - else - { - // The process has been paused by the user or aborted by the wizard (e.g. on app exit) - - nStatus = ERR_USER_ABORT; - - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED); - } - - if (dev != INVALID_HANDLE_VALUE) - { - CloseHandle (dev); - dev = INVALID_HANDLE_VALUE; - } - - -closing_seq: - - dwError = GetLastError(); - - if (bEncryptedAreaSizeChanged - && dev != INVALID_HANDLE_VALUE - && masterCryptoInfo != NULL - && headerCryptoInfo != NULL - && deviceSize > 0) - { - // Execution of the core loop may have been interrupted due to an error or user action without updating the header - FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize); - } - - if (dev != INVALID_HANDLE_VALUE) - { - CloseHandle (dev); - dev = INVALID_HANDLE_VALUE; - } - - if (masterCryptoInfo != NULL) - { - crypto_close (masterCryptoInfo); - masterCryptoInfo = NULL; - } - - if (headerCryptoInfo != NULL) - { - crypto_close (headerCryptoInfo); - headerCryptoInfo = NULL; - } - - if (dosDev[0]) - RemoveFakeDosName (devicePath, dosDev); - - if (buf != NULL) - { - TCfree (buf); - buf = NULL; - } - - if (tmpSectorBuf != NULL) - { - TCfree (tmpSectorBuf); - tmpSectorBuf = NULL; - } - - if (skippedBadSectorCount > 0) - { - wchar_t msg[30000] = {0}; - wchar_t sizeStr[500] = {0}; - - GetSizeString (skippedBadSectorCount * sectorSize, sizeStr, sizeof(sizeStr)); - - StringCbPrintfW (msg, sizeof(msg), - GetString ("SKIPPED_BAD_SECTOR_COUNT"), - skippedBadSectorCount, - sizeStr); - - WarningDirect (msg, hwndDlg); - } - - if (nStatus != ERR_SUCCESS && nStatus != ERR_USER_ABORT) - SetLastError (dwError); - - return nStatus; -} - -int FastVolumeHeaderUpdate (HANDLE dev, CRYPTO_INFO *headerCryptoInfo, CRYPTO_INFO *masterCryptoInfo, __int64 deviceSize) -{ - LARGE_INTEGER offset; - DWORD n; - int nStatus = ERR_SUCCESS; - byte *header; - DWORD dwError; - uint32 headerCrc32; - byte *fieldPos; - - header = (byte *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE); - - if (!header) - return ERR_OUTOFMEMORY; - - VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - - - fieldPos = (byte *) header + TC_HEADER_OFFSET_ENCRYPTED_AREA_START; - - offset.QuadPart = deviceSize - TC_VOLUME_HEADER_GROUP_SIZE; - - if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 - || !ReadEffectiveVolumeHeader (TRUE, dev, header, &n) || n < TC_VOLUME_HEADER_EFFECTIVE_SIZE) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - - DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, headerCryptoInfo); - - if (GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x56455241) - { - nStatus = ERR_PARAMETER_INCORRECT; - goto closing_seq; - } - - mputInt64 (fieldPos, (masterCryptoInfo->EncryptedAreaStart.Value)); - mputInt64 (fieldPos, (masterCryptoInfo->EncryptedAreaLength.Value)); - - // We need to ensure the TC_HEADER_FLAG_NONSYS_INPLACE_ENC flag bit is set, because if volumes created by TC-format - // were decrypted in place, it would be possible to mount them partially encrypted and it wouldn't be possible - // to resume interrupted decryption after the wizard exits. - masterCryptoInfo->HeaderFlags |= TC_HEADER_FLAG_NONSYS_INPLACE_ENC; - fieldPos = (byte *) header + TC_HEADER_OFFSET_FLAGS; - mputLong (fieldPos, (masterCryptoInfo->HeaderFlags)); - - - headerCrc32 = GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC); - fieldPos = (byte *) header + TC_HEADER_OFFSET_HEADER_CRC; - mputLong (fieldPos, headerCrc32); - - EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, headerCryptoInfo); - - - if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 - || !WriteEffectiveVolumeHeader (TRUE, dev, header)) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - -closing_seq: - - dwError = GetLastError(); - - burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - TCfree (header); - - if (nStatus != ERR_SUCCESS) - SetLastError (dwError); - - return nStatus; -} - - -static HANDLE OpenPartitionVolume (HWND hwndDlg, const wchar_t *devName, - BOOL bExclusiveRequired, - BOOL bSharedRequired, - BOOL bSharedRequiresConfirmation, - BOOL bShowAlternativeSteps, - BOOL bSilent) -{ - HANDLE dev = INVALID_HANDLE_VALUE; - int retryCount = 0; - - if (bExclusiveRequired) - bSharedRequired = FALSE; - - if (bExclusiveRequired || !bSharedRequired) - { - // Exclusive access - // Note that when exclusive access is denied, it is worth retrying (usually succeeds after a few tries). - while (dev == INVALID_HANDLE_VALUE && retryCount++ < EXCL_ACCESS_MAX_AUTO_RETRIES) - { - dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL); - - if (retryCount > 1) - Sleep (EXCL_ACCESS_AUTO_RETRY_DELAY); - } - } - - if (dev == INVALID_HANDLE_VALUE) - { - if (bExclusiveRequired) - { - if (!bSilent) - { - handleWin32Error (hwndDlg, SRC_POS); - - if (bShowAlternativeSteps) - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE); - else - Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg); - } - return INVALID_HANDLE_VALUE; - } - - // Shared mode - dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL); - if (dev != INVALID_HANDLE_VALUE) - { - if (bSharedRequiresConfirmation - && !bSilent - && AskWarnNoYes ("DEVICE_IN_USE_INPLACE_ENC", hwndDlg) == IDNO) - { - CloseHandle (dev); - return INVALID_HANDLE_VALUE; - } - } - else - { - if (!bSilent) - { - handleWin32Error (MainDlg, SRC_POS); - - if (bShowAlternativeSteps) - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE); - else - Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg); - } - return INVALID_HANDLE_VALUE; - } - } - - return dev; -} - - -static int DismountFileSystem (HWND hwndDlg, HANDLE dev, - int driveLetter, - BOOL bForcedAllowed, - BOOL bForcedRequiresConfirmation, - BOOL bSilent) -{ - int attempt; - BOOL bResult; - DWORD dwResult; - - CloseVolumeExplorerWindows (MainDlg, driveLetter); - - attempt = UNMOUNT_MAX_AUTO_RETRIES * 10; - - while (!(bResult = DeviceIoControl (dev, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) - && attempt > 0) - { - Sleep (UNMOUNT_AUTO_RETRY_DELAY); - attempt--; - } - - if (!bResult) - { - if (!bForcedAllowed) - { - if (!bSilent) - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_LOCK_OR_DISMOUNT_FILESYS", TRUE); - - return ERR_DONT_REPORT; - } - - if (bForcedRequiresConfirmation - && !bSilent - && AskWarnYesNo ("VOL_LOCK_FAILED_OFFER_FORCED_DISMOUNT", hwndDlg) == IDNO) - { - return ERR_DONT_REPORT; - } - } - - // Dismount the volume - - attempt = UNMOUNT_MAX_AUTO_RETRIES * 10; - - while (!(bResult = DeviceIoControl (dev, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) - && attempt > 0) - { - Sleep (UNMOUNT_AUTO_RETRY_DELAY); - attempt--; - } - - if (!bResult) - { - if (!bSilent) - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_LOCK_OR_DISMOUNT_FILESYS", TRUE); - - return ERR_DONT_REPORT; - } - - return ERR_SUCCESS; -} - - -// Easy-to-undo modification applied to conceal the NTFS filesystem (to prevent Windows and apps from -// interfering with it until the volume has been fully encrypted). Note that this function will precisely -// undo any modifications it made to the filesystem automatically if an error occurs when writing (including -// physical drive defects). -static int ConcealNTFS (HANDLE dev) -{ - char buf [TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE]; - DWORD nbrBytesProcessed, nbrBytesProcessed2; - int i; - LARGE_INTEGER offset; - DWORD dwError; - - offset.QuadPart = 0; - - if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) - return ERR_OS_ERROR; - - if (ReadFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed, NULL) == 0) - return ERR_OS_ERROR; - - for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE; i++) - buf[i] ^= TC_NTFS_CONCEAL_CONSTANT; - - offset.QuadPart = 0; - - if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) - return ERR_OS_ERROR; - - if (WriteFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed, NULL) == 0) - { - // One or more of the sectors is/are probably damaged and cause write errors. - // We must undo the modifications we made. - - dwError = GetLastError(); - - for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE; i++) - buf[i] ^= TC_NTFS_CONCEAL_CONSTANT; - - offset.QuadPart = 0; - - do - { - Sleep (1); - } - while (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 - || WriteFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed2, NULL) == 0); - - SetLastError (dwError); - - return ERR_OS_ERROR; - } - - return ERR_SUCCESS; -} - - -void ShowInPlaceEncErrMsgWAltSteps (HWND hwndDlg, char *iniStrId, BOOL bErr) -{ - wchar_t msg[30000]; - - StringCbCopyW (msg, sizeof(msg), GetString (iniStrId)); - - StringCbCatW (msg, sizeof(msg), L"\n\n\n"); - StringCbCatW (msg, sizeof(msg), GetString ("INPLACE_ENC_ALTERNATIVE_STEPS")); - - if (bErr) - ErrorDirect (msg, hwndDlg); - else - WarningDirect (msg, hwndDlg); -} - - -static void ExportProgressStats (__int64 bytesDone, __int64 totalSize) -{ - NonSysInplaceEncBytesDone = bytesDone; - NonSysInplaceEncTotalSize = totalSize; -} - - -void SetNonSysInplaceEncUIStatus (int nonSysInplaceEncStatus) -{ - NonSysInplaceEncStatus = nonSysInplaceEncStatus; -} - - -BOOL SaveNonSysInPlaceEncSettings (int delta, WipeAlgorithmId newWipeAlgorithm, BOOL bDecrypt) -{ - int count; - char str[32]; - WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE; - - if (delta == 0) - return TRUE; - - count = LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) + delta; - - if (count < 1) - { - RemoveNonSysInPlaceEncNotifications(); - return TRUE; - } - else if (!bDecrypt) - { - if (newWipeAlgorithm != TC_WIPE_NONE) - { - StringCbPrintfA (str, sizeof(str), "%d", (int) newWipeAlgorithm); - - SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE), (DWORD) strlen(str), FALSE, FALSE); - } - else if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE))) - { - _wremove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE)); - } - } - - StringCbPrintfA (str, sizeof(str), "%d", count); - - return SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC), (DWORD) strlen(str), FALSE, FALSE); -} - - -// Repairs damaged sectors (i.e. those with read errors) by zeroing them. -// Note that this operating fails if there are any write errors. -int ZeroUnreadableSectors (HANDLE dev, LARGE_INTEGER startOffset, int64 size, int sectorSize, uint64 *zeroedSectorCount) -{ - int nStatus; - DWORD n; - int64 sectorCount; - LARGE_INTEGER workOffset; - byte *sectorBuffer = NULL; - DWORD dwError; - - workOffset.QuadPart = startOffset.QuadPart; - - sectorBuffer = (byte *) TCalloc (sectorSize); - - if (!sectorBuffer) - return ERR_OUTOFMEMORY; - - if (SetFilePointerEx (dev, startOffset, NULL, FILE_BEGIN) == 0) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - - for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount) - { - if (ReadFile (dev, sectorBuffer, sectorSize, &n, NULL) == 0) - { - memset (sectorBuffer, 0, sectorSize); - - if (SetFilePointerEx (dev, workOffset, NULL, FILE_BEGIN) == 0) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - if (WriteFile (dev, sectorBuffer, sectorSize, &n, NULL) == 0) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - ++(*zeroedSectorCount); - } - - workOffset.QuadPart += n; - } - - nStatus = ERR_SUCCESS; - -closing_seq: - - dwError = GetLastError(); - - if (sectorBuffer != NULL) - TCfree (sectorBuffer); - - if (nStatus != ERR_SUCCESS) - SetLastError (dwError); - - return nStatus; -} - - -static int OpenBackupHeader (HANDLE dev, const wchar_t *devicePath, Password *password, int pkcs5, int pim, PCRYPTO_INFO *retMasterCryptoInfo, CRYPTO_INFO *headerCryptoInfo, __int64 deviceSize) -{ - LARGE_INTEGER offset; - DWORD n; - int nStatus = ERR_SUCCESS; - char *header; - DWORD dwError; - - header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE); - if (!header) - return ERR_OUTOFMEMORY; - - VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - - - - offset.QuadPart = deviceSize - TC_VOLUME_HEADER_GROUP_SIZE; - - if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 - || !ReadEffectiveVolumeHeader (TRUE, dev, (byte *) header, &n) || n < TC_VOLUME_HEADER_EFFECTIVE_SIZE) - { - nStatus = ERR_OS_ERROR; - goto closing_seq; - } - - - nStatus = ReadVolumeHeader (FALSE, header, password, pkcs5, pim, FALSE, retMasterCryptoInfo, headerCryptoInfo); - if (nStatus != ERR_SUCCESS) - goto closing_seq; - - -closing_seq: - - dwError = GetLastError(); - - burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); - TCfree (header); - - dwError = GetLastError(); - - if (nStatus != ERR_SUCCESS) - SetLastError (dwError); - - return nStatus; -} - - -static BOOL GetFreeClusterBeforeThreshold (HANDLE volumeHandle, int64 *freeCluster, int64 clusterThreshold) -{ - const int bitmapSize = 65536; - byte bitmapBuffer[bitmapSize + sizeof (VOLUME_BITMAP_BUFFER)]; - VOLUME_BITMAP_BUFFER *bitmap = (VOLUME_BITMAP_BUFFER *) bitmapBuffer; - STARTING_LCN_INPUT_BUFFER startLcn; - startLcn.StartingLcn.QuadPart = 0; - - DWORD bytesReturned; - while (DeviceIoControl (volumeHandle, FSCTL_GET_VOLUME_BITMAP, &startLcn, sizeof (startLcn), &bitmapBuffer, sizeof (bitmapBuffer), &bytesReturned, NULL) - || GetLastError() == ERROR_MORE_DATA) - { - for (int64 bitmapIndex = 0; bitmapIndex < min (bitmapSize, (bitmap->BitmapSize.QuadPart / 8)); ++bitmapIndex) - { - if (bitmap->StartingLcn.QuadPart + bitmapIndex * 8 >= clusterThreshold) - goto err; - - if (bitmap->Buffer[bitmapIndex] != 0xff) - { - for (int bit = 0; bit < 8; ++bit) - { - if ((bitmap->Buffer[bitmapIndex] & (1 << bit)) == 0) - { - *freeCluster = bitmap->StartingLcn.QuadPart + bitmapIndex * 8 + bit; - - if (*freeCluster >= clusterThreshold) - goto err; - - return TRUE; - } - } - } - } - - startLcn.StartingLcn.QuadPart += min (bitmapSize * 8, bitmap->BitmapSize.QuadPart); - } - -err: - SetLastError (ERROR_DISK_FULL); - return FALSE; -} - - -static BOOL MoveClustersBeforeThresholdInDir (HANDLE volumeHandle, const wstring &directory, int64 clusterThreshold) -{ - WIN32_FIND_DATAW findData; - - HANDLE findHandle = FindFirstFileW (((directory.size() <= 3 ? L"" : L"\\\\?\\") + directory + L"\\*").c_str(), &findData); - if (findHandle == INVALID_HANDLE_VALUE) - return TRUE; // Error ignored - - finally_do_arg (HANDLE, findHandle, { FindClose (finally_arg); }); - - // Find all files and directories - do - { - if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - { - wstring subDir = findData.cFileName; - - if (subDir == L"." || subDir == L"..") - continue; - - if (!MoveClustersBeforeThresholdInDir (volumeHandle, directory + L"\\" + subDir, clusterThreshold)) - return FALSE; - } - - DWORD access = FILE_READ_ATTRIBUTES; - - if (findData.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) - access = FILE_READ_DATA; - - HANDLE fsObject = CreateFileW ((directory + L"\\" + findData.cFileName).c_str(), access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - if (fsObject == INVALID_HANDLE_VALUE) - continue; - - finally_do_arg (HANDLE, fsObject, { CloseHandle (finally_arg); }); - - STARTING_VCN_INPUT_BUFFER startVcn; - startVcn.StartingVcn.QuadPart = 0; - RETRIEVAL_POINTERS_BUFFER retPointers; - DWORD bytesReturned; - - // Find clusters allocated beyond the threshold - while (DeviceIoControl (fsObject, FSCTL_GET_RETRIEVAL_POINTERS, &startVcn, sizeof (startVcn), &retPointers, sizeof (retPointers), &bytesReturned, NULL) - || GetLastError() == ERROR_MORE_DATA) - { - if (retPointers.ExtentCount == 0) - break; - - if (retPointers.Extents[0].Lcn.QuadPart != -1) - { - int64 extentStartCluster = retPointers.Extents[0].Lcn.QuadPart; - int64 extentLen = retPointers.Extents[0].NextVcn.QuadPart - retPointers.StartingVcn.QuadPart; - int64 extentEndCluster = extentStartCluster + extentLen - 1; - - if (extentEndCluster >= clusterThreshold) - { - // Move clusters before the threshold - for (int64 movedCluster = max (extentStartCluster, clusterThreshold); movedCluster <= extentEndCluster; ++movedCluster) - { - for (int retry = 0; ; ++retry) - { - MOVE_FILE_DATA moveData; - - if (GetFreeClusterBeforeThreshold (volumeHandle, &moveData.StartingLcn.QuadPart, clusterThreshold)) - { - moveData.FileHandle = fsObject; - moveData.StartingVcn.QuadPart = movedCluster - extentStartCluster + retPointers.StartingVcn.QuadPart; - moveData.ClusterCount = 1; - - if (DeviceIoControl (volumeHandle, FSCTL_MOVE_FILE, &moveData, sizeof (moveData), NULL, 0, &bytesReturned, NULL)) - break; - } - - if (retry > 600) - return FALSE; - - // There are possible race conditions as we work on a live filesystem - Sleep (100); - } - } - } - } - - startVcn.StartingVcn = retPointers.Extents[0].NextVcn; - } - - } while (FindNextFileW (findHandle, &findData)); - - return TRUE; -} - - -BOOL MoveClustersBeforeThreshold (HANDLE volumeHandle, PWSTR volumeDevicePath, int64 clusterThreshold) -{ - int drive = GetDiskDeviceDriveLetter (volumeDevicePath); - if (drive == -1) - { - SetLastError (ERROR_INVALID_PARAMETER); - return FALSE; - } - - wstring volumeRoot = L"X:"; - volumeRoot[0] = L'A' + (wchar_t) drive; - - return MoveClustersBeforeThresholdInDir (volumeHandle, volumeRoot, clusterThreshold); -} +/* + 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. +*/ + + +/* In this file, _WIN32_WINNT is defined as 0x0600 to make filesystem shrink available (Vista +or later). _WIN32_WINNT cannot be defined as 0x0600 for the entire user-space projects +because it breaks the main font app when the app is running on XP (likely an MS bug). +IMPORTANT: Due to this issue, functions in this file must not directly interact with GUI. */ +#define TC_LOCAL_WIN32_WINNT_OVERRIDE 1 +#if (_WIN32_WINNT < 0x0600) +# undef _WIN32_WINNT +# define _WIN32_WINNT 0x0600 +#endif + + +#include +#include +#include +#include + +#include "Tcdefs.h" +#include "Platform/Finally.h" + +#include "Common.h" +#include "Crc.h" +#include "Dlgcode.h" +#include "Language.h" +#include "Tcformat.h" +#include "Volumes.h" + +#include "InPlace.h" + +#include + +using namespace std; +using namespace VeraCrypt; + +#if TC_VOLUME_DATA_OFFSET != 131072 +# error TC_VOLUME_DATA_OFFSET != 131072 +#endif + +#if TC_VOLUME_HEADER_EFFECTIVE_SIZE != 512 +# error TC_VOLUME_HEADER_EFFECTIVE_SIZE != 512 +#endif + +#if TC_TOTAL_VOLUME_HEADERS_SIZE != 262144 +# error TC_TOTAL_VOLUME_HEADERS_SIZE != 262144 +#endif + +#define TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE (2048 * BYTES_PER_KB) +#define TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE (2 * TC_MAX_VOLUME_SECTOR_SIZE) +#define TC_NTFS_CONCEAL_CONSTANT 0xFF +#define TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL (64 * BYTES_PER_MB) +#define TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE (TC_TOTAL_VOLUME_HEADERS_SIZE + TC_MIN_NTFS_FS_SIZE * 2) + + +// If the returned value is greater than 0, it is the desired volume size in NTFS sectors (not in bytes) +// after shrinking has been performed. If there's any error, returns -1. +static __int64 NewFileSysSizeAfterShrink (HANDLE dev, const wchar_t *devicePath, int64 *totalClusterCount, DWORD *bytesPerCluster, BOOL silent) +{ + NTFS_VOLUME_DATA_BUFFER ntfsVolData; + DWORD nBytesReturned; + __int64 fileSysSize, desiredNbrSectors; + + // Filesystem size and sector size + + if (!DeviceIoControl (dev, + FSCTL_GET_NTFS_VOLUME_DATA, + NULL, + 0, + (LPVOID) &ntfsVolData, + sizeof (ntfsVolData), + &nBytesReturned, + NULL)) + { + if (!silent) + handleWin32Error (MainDlg, SRC_POS); + + return -1; + } + + if ( (ntfsVolData.NumberSectors.QuadPart <= 0) + || (ntfsVolData.NumberSectors.QuadPart > (INT64_MAX / (__int64) ntfsVolData.BytesPerSector)) // overflow test + ) + { + SetLastError (ERROR_INTERNAL_ERROR); + if (!silent) + handleWin32Error (MainDlg, SRC_POS); + + return -1; + } + + fileSysSize = ntfsVolData.NumberSectors.QuadPart * ntfsVolData.BytesPerSector; + + desiredNbrSectors = (fileSysSize - TC_TOTAL_VOLUME_HEADERS_SIZE) / ntfsVolData.BytesPerSector; + + if (desiredNbrSectors <= 0) + return -1; + + if (totalClusterCount) + *totalClusterCount = ntfsVolData.TotalClusters.QuadPart; + if (bytesPerCluster) + *bytesPerCluster = ntfsVolData.BytesPerCluster; + + return desiredNbrSectors; +} + + +BOOL CheckRequirementsForNonSysInPlaceEnc (HWND hwndDlg, const wchar_t *devicePath, BOOL silent) +{ + NTFS_VOLUME_DATA_BUFFER ntfsVolData; + DWORD nBytesReturned; + HANDLE dev; + WCHAR szFileSysName [256]; + WCHAR devPath [MAX_PATH]; + WCHAR dosDev [TC_MAX_PATH] = {0}; + WCHAR devName [MAX_PATH] = {0}; + int driveLetterNo = -1; + WCHAR szRootPath[4] = {0, L':', L'\\', 0}; + __int64 deviceSize; + int partitionNumber = -1, driveNumber = -1; + + + /* ---------- Checks that do not require admin rights ----------- */ + + + /* Operating system */ + + if (CurrentOSMajor < 6) + { + if (!silent) + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "OS_NOT_SUPPORTED_FOR_NONSYS_INPLACE_ENC", FALSE); + + return FALSE; + } + + + /* Volume type (must be a partition or a dynamic volume) */ + + if (swscanf (devicePath, L"\\Device\\HarddiskVolume%d", &partitionNumber) != 1 + && swscanf (devicePath, L"\\Device\\Harddisk%d\\Partition%d", &driveNumber, &partitionNumber) != 2) + { + if (!silent) + Error ("INPLACE_ENC_INVALID_PATH", hwndDlg); + + return FALSE; + } + + if (partitionNumber == 0) + { + if (!silent) + Warning ("RAW_DEV_NOT_SUPPORTED_FOR_INPLACE_ENC", hwndDlg); + + return FALSE; + } + + + /* Admin rights */ + + if (!IsAdmin()) + { + // We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC + // status can be ignored). In case the IsAdmin() detection somehow fails, we allow the user to continue. + + if (!silent) + Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", hwndDlg); + } + + + /* ---------- Checks that may require admin rights ----------- */ + + + /* Access to the partition */ + + StringCbCopyW (devPath, sizeof(devPath), devicePath); + + driveLetterNo = GetDiskDeviceDriveLetter (devPath); + + if (driveLetterNo >= 0) + szRootPath[0] = (wchar_t) driveLetterNo + L'A'; + + if (FakeDosNameForDevice (devicePath, dosDev, sizeof(dosDev), devName, sizeof(devName),FALSE) != 0) + { + if (!silent) + { + handleWin32Error (hwndDlg, SRC_POS); + Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg); + } + return FALSE; + } + + dev = OpenPartitionVolume (hwndDlg, devName, + FALSE, // Do not require exclusive access + TRUE, // Require shared access (must be TRUE; otherwise, volume properties will not be possible to obtain) + FALSE, // Do not ask the user to confirm shared access (if exclusive fails) + FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages) + silent); // Silent mode + + if (dev == INVALID_HANDLE_VALUE) + return FALSE; + + + /* File system type */ + + GetVolumeInformation (szRootPath, NULL, 0, NULL, NULL, NULL, szFileSysName, ARRAYSIZE (szFileSysName)); + + if (wcsncmp (szFileSysName, L"NTFS", 4)) + { + // The previous filesystem type detection method failed (or it's not NTFS) -- try an alternative method + + if (!DeviceIoControl (dev, + FSCTL_GET_NTFS_VOLUME_DATA, + NULL, + 0, + (LPVOID) &ntfsVolData, + sizeof (ntfsVolData), + &nBytesReturned, + NULL)) + { + if (!silent) + { + // The filesystem is not NTFS or the filesystem type could not be determined (or the NTFS filesystem + // is dismounted). + + if (IsDeviceMounted (devName)) + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "ONLY_NTFS_SUPPORTED_FOR_NONSYS_INPLACE_ENC", FALSE); + else + Warning ("ONLY_MOUNTED_VOL_SUPPORTED_FOR_NONSYS_INPLACE_ENC", hwndDlg); + } + + CloseHandle (dev); + return FALSE; + } + } + + + /* Attempt to determine whether the filesystem can be safely shrunk */ + + if (NewFileSysSizeAfterShrink (dev, devicePath, NULL, NULL, silent) == -1) + { + // Cannot determine whether shrinking is required + if (!silent) + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE); + + CloseHandle (dev); + return FALSE; + } + + + /* Partition size */ + + deviceSize = GetDeviceSize (devicePath); + if (deviceSize < 0) + { + // Cannot determine the size of the partition + if (!silent) + Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg); + + CloseHandle (dev); + return FALSE; + } + + if (deviceSize < TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE) + { + // The partition is too small + if (!silent) + { + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "PARTITION_TOO_SMALL_FOR_NONSYS_INPLACE_ENC", FALSE); + } + + CloseHandle (dev); + return FALSE; + } + + + /* Free space on the filesystem */ + + if (!DeviceIoControl (dev, + FSCTL_GET_NTFS_VOLUME_DATA, + NULL, + 0, + (LPVOID) &ntfsVolData, + sizeof (ntfsVolData), + &nBytesReturned, + NULL)) + { + if (!silent) + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", TRUE); + + CloseHandle (dev); + return FALSE; + } + + if (ntfsVolData.FreeClusters.QuadPart * ntfsVolData.BytesPerCluster < TC_TOTAL_VOLUME_HEADERS_SIZE) + { + if (!silent) + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "NOT_ENOUGH_FREE_FILESYS_SPACE_FOR_SHRINK", TRUE); + + CloseHandle (dev); + return FALSE; + } + + + /* Filesystem sector size */ + + if (ntfsVolData.BytesPerSector > TC_MAX_VOLUME_SECTOR_SIZE + || ntfsVolData.BytesPerSector % ENCRYPTION_DATA_UNIT_SIZE != 0) + { + if (!silent) + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "SECTOR_SIZE_UNSUPPORTED", TRUE); + + CloseHandle (dev); + return FALSE; + } + + + CloseHandle (dev); + return TRUE; +} + +BOOL CheckRequirementsForNonSysInPlaceDec (HWND hwndDlg, const wchar_t *devicePath, BOOL silent) +{ + int partitionNumber = -1, driveNumber = -1; + + /* ---------- Checks that do not require admin rights ----------- */ + + /* Volume type (must be a partition or a dynamic volume) */ + if ((swscanf (devicePath, L"\\Device\\HarddiskVolume%d", &partitionNumber) != 1 + && swscanf (devicePath, L"\\Device\\Harddisk%d\\Partition%d", &driveNumber, &partitionNumber) != 2) + || partitionNumber == 0) + { + if (!silent) + Error ("INPLACE_ENC_INVALID_PATH", hwndDlg); + + return FALSE; + } + + + /* Admin rights */ + if (!IsAdmin()) + { + // We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC + // status can be ignored). In case the IsAdmin() detection somehow fails, we allow the user to continue. + + if (!silent) + Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", hwndDlg); + } + + + /* ---------- Checks that may require admin rights ----------- */ + + // [Currently none] + + return TRUE; +} + + +int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, volatile HANDLE *outHandle, WipeAlgorithmId wipeAlgorithm) +{ + SHRINK_VOLUME_INFORMATION shrinkVolInfo; + signed __int64 sizeToShrinkTo; + int nStatus = ERR_SUCCESS; + PCRYPTO_INFO cryptoInfo = NULL; + PCRYPTO_INFO cryptoInfo2 = NULL; + HANDLE dev = INVALID_HANDLE_VALUE; + DWORD dwError; + char *header; + WCHAR dosDev[TC_MAX_PATH] = {0}; + WCHAR devName[MAX_PATH] = {0}; + int driveLetter = -1; + WCHAR deviceName[MAX_PATH]; + uint64 dataAreaSize; + __int64 deviceSize; + LARGE_INTEGER offset; + DWORD dwResult; + HWND hwndDlg = volParams->hwndDlg; + + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PREPARING); + + + if (!CheckRequirementsForNonSysInPlaceEnc (hwndDlg, volParams->volumePath, FALSE)) + return ERR_DONT_REPORT; + + + header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE); + if (!header) + return ERR_OUTOFMEMORY; + + VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + + deviceSize = GetDeviceSize (volParams->volumePath); + if (deviceSize < 0) + { + // Cannot determine the size of the partition + nStatus = ERR_PARAMETER_INCORRECT; + goto closing_seq; + } + + if (deviceSize < TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE) + { + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "PARTITION_TOO_SMALL_FOR_NONSYS_INPLACE_ENC", TRUE); + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + + dataAreaSize = GetVolumeDataAreaSize (volParams->hiddenVol, deviceSize); + + StringCchCopyW (deviceName, ARRAYSIZE(deviceName), volParams->volumePath); + + driveLetter = GetDiskDeviceDriveLetter (deviceName); + + + if (FakeDosNameForDevice (volParams->volumePath, dosDev, sizeof(dosDev),devName, sizeof(devName),FALSE) != 0) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + if (IsDeviceMounted (devName)) + { + dev = OpenPartitionVolume (hwndDlg, devName, + FALSE, // Do not require exclusive access (must be FALSE; otherwise, it will not be possible to dismount the volume or obtain its properties and FSCTL_ALLOW_EXTENDED_DASD_IO will fail too) + TRUE, // Require shared access (must be TRUE; otherwise, it will not be possible to dismount the volume or obtain its properties and FSCTL_ALLOW_EXTENDED_DASD_IO will fail too) + FALSE, // Do not ask the user to confirm shared access (if exclusive fails) + FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages) + FALSE); // Non-silent mode + + if (dev == INVALID_HANDLE_VALUE) + { + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + } + else + { + // The volume is not mounted so we can't work with the filesystem. + Error ("ONLY_MOUNTED_VOL_SUPPORTED_FOR_NONSYS_INPLACE_ENC", hwndDlg); + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + + + /* Gain "raw" access to the partition (the NTFS driver guards hidden sectors). */ + + if (!DeviceIoControl (dev, + FSCTL_ALLOW_EXTENDED_DASD_IO, + NULL, + 0, + NULL, + 0, + &dwResult, + NULL)) + { + handleWin32Error (MainDlg, SRC_POS); + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE); + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + + + + /* Shrink the filesystem */ + + int64 totalClusterCount; + DWORD bytesPerCluster; + + sizeToShrinkTo = NewFileSysSizeAfterShrink (dev, volParams->volumePath, &totalClusterCount, &bytesPerCluster, FALSE); + + if (sizeToShrinkTo == -1) + { + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE); + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_RESIZING); + + memset (&shrinkVolInfo, 0, sizeof (shrinkVolInfo)); + + shrinkVolInfo.ShrinkRequestType = ShrinkPrepare; + shrinkVolInfo.NewNumberOfSectors = sizeToShrinkTo; + + if (!DeviceIoControl (dev, + FSCTL_SHRINK_VOLUME, + (LPVOID) &shrinkVolInfo, + sizeof (shrinkVolInfo), + NULL, + 0, + &dwResult, + NULL)) + { + handleWin32Error (hwndDlg, SRC_POS); + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "CANNOT_RESIZE_FILESYS", TRUE); + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + + BOOL clustersMovedBeforeVolumeEnd = FALSE; + + while (true) + { + shrinkVolInfo.ShrinkRequestType = ShrinkCommit; + shrinkVolInfo.NewNumberOfSectors = 0; + + if (!DeviceIoControl (dev, FSCTL_SHRINK_VOLUME, &shrinkVolInfo, sizeof (shrinkVolInfo), NULL, 0, &dwResult, NULL)) + { + // If there are any occupied clusters beyond the new desired end of the volume, the call fails with + // ERROR_ACCESS_DENIED (STATUS_ALREADY_COMMITTED). + if (GetLastError () == ERROR_ACCESS_DENIED) + { + if (!clustersMovedBeforeVolumeEnd) + { + if (MoveClustersBeforeThreshold (dev, deviceName, totalClusterCount - (bytesPerCluster > TC_TOTAL_VOLUME_HEADERS_SIZE ? 1 : TC_TOTAL_VOLUME_HEADERS_SIZE / bytesPerCluster))) + { + clustersMovedBeforeVolumeEnd = TRUE; + continue; + } + + handleWin32Error (hwndDlg, SRC_POS); + } + } + else + handleWin32Error (hwndDlg, SRC_POS); + + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "CANNOT_RESIZE_FILESYS", TRUE); + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + + break; + } + + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PREPARING); + + + /* Gain exclusive access to the volume */ + + nStatus = DismountFileSystem (hwndDlg, dev, + driveLetter, + TRUE, + TRUE, + FALSE); + + if (nStatus != ERR_SUCCESS) + { + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + + + + /* Create header backup on the partition. Until the volume is fully encrypted, the backup header will provide + us with the master key, encrypted range, and other data for pause/resume operations. We cannot create the + primary header until the entire partition is encrypted (because we encrypt backwards and the primary header + area is occuppied by data until the very end of the process). */ + + // Prepare the backup header + for (int wipePass = 0; wipePass < (wipeAlgorithm == TC_WIPE_NONE ? 1 : PRAND_HEADER_WIPE_PASSES); wipePass++) + { + nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE, + header, + volParams->ea, + FIRST_MODE_OF_OPERATION_ID, + volParams->password, + volParams->pkcs5, + volParams->pim, + wipePass == 0 ? NULL : (char *) cryptoInfo->master_keydata, + &cryptoInfo, + dataAreaSize, + 0, + TC_VOLUME_DATA_OFFSET + dataAreaSize, // Start of the encrypted area = the first byte of the backup heeader (encrypting from the end) + 0, // No data is encrypted yet + 0, + volParams->headerFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC, + volParams->sectorSize, + wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_HEADER_WIPE_PASSES - 1)); + + if (nStatus != 0) + goto closing_seq; + + offset.QuadPart = TC_VOLUME_DATA_OFFSET + dataAreaSize; + + if (!SetFilePointerEx (dev, offset, NULL, FILE_BEGIN)) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + // Write the backup header to the partition + if (!WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header)) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + // Fill the reserved sectors of the backup header area with random data + nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, dataAreaSize, FALSE, TRUE); + + if (nStatus != ERR_SUCCESS) + goto closing_seq; + } + + + /* Now we will try to decrypt the backup header to verify it has been correctly written. */ + + nStatus = OpenBackupHeader (dev, volParams->volumePath, volParams->password, volParams->pkcs5, volParams->pim, &cryptoInfo2, NULL, deviceSize); + + if (nStatus != ERR_SUCCESS + || cryptoInfo->EncryptedAreaStart.Value != cryptoInfo2->EncryptedAreaStart.Value + || cryptoInfo2->EncryptedAreaStart.Value == 0) + { + if (nStatus == ERR_SUCCESS) + nStatus = ERR_PARAMETER_INCORRECT; + + goto closing_seq; + } + + // The backup header is valid so we know we should be able to safely resume in-place encryption + // of this partition even if the system/app crashes. + + + + /* Conceal the NTFS filesystem (by performing an easy-to-undo modification). This will prevent Windows + and apps from interfering with the volume until it has been fully encrypted. */ + + nStatus = ConcealNTFS (dev); + + if (nStatus != ERR_SUCCESS) + goto closing_seq; + + + + // /* If a drive letter is assigned to the device, remove it (so that users do not try to open it, which + //would cause Windows to ask them if they want to format the volume and other dangerous things). */ + + //if (driveLetter >= 0) + //{ + // char rootPath[] = { driveLetter + 'A', ':', '\\', 0 }; + + // // Try to remove the assigned drive letter + // if (DeleteVolumeMountPoint (rootPath)) + // driveLetter = -1; + //} + + + + /* Update config files and app data */ + + // In the config file, increase the number of partitions where in-place encryption is in progress + + SaveNonSysInPlaceEncSettings (1, wipeAlgorithm, FALSE); + + + // Add the wizard to the system startup sequence if appropriate + + if (!IsNonInstallMode ()) + ManageStartupSeqWiz (FALSE, L"/prinplace"); + + + nStatus = ERR_SUCCESS; + + +closing_seq: + + dwError = GetLastError(); + + if (cryptoInfo != NULL) + { + crypto_close (cryptoInfo); + cryptoInfo = NULL; + } + + if (cryptoInfo2 != NULL) + { + crypto_close (cryptoInfo2); + cryptoInfo2 = NULL; + } + + burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + TCfree (header); + + if (dosDev[0]) + RemoveFakeDosName (volParams->volumePath, dosDev); + + *outHandle = dev; + + if (nStatus != ERR_SUCCESS) + SetLastError (dwError); + + return nStatus; +} + + +int EncryptPartitionInPlaceResume (HANDLE dev, + volatile FORMAT_VOL_PARAMETERS *volParams, + WipeAlgorithmId wipeAlgorithm, + volatile BOOL *bTryToCorrectReadErrors) +{ + PCRYPTO_INFO masterCryptoInfo = NULL, headerCryptoInfo = NULL, tmpCryptoInfo = NULL; + UINT64_STRUCT unitNo; + char *buf = NULL, *header = NULL; + byte *wipeBuffer = NULL; + byte wipeRandChars [TC_WIPE_RAND_CHAR_COUNT]; + byte wipeRandCharsUpdate [TC_WIPE_RAND_CHAR_COUNT]; + WCHAR dosDev[TC_MAX_PATH] = {0}; + WCHAR devName[MAX_PATH] = {0}; + WCHAR deviceName[MAX_PATH]; + int nStatus = ERR_SUCCESS; + __int64 deviceSize; + uint64 remainingBytes, lastHeaderUpdateDistance = 0, zeroedSectorCount = 0; + uint32 workChunkSize; + DWORD dwError, dwResult; + BOOL bPause = FALSE, bEncryptedAreaSizeChanged = FALSE; + LARGE_INTEGER offset; + int sectorSize; + int i; + DWORD n; + WCHAR *devicePath = volParams->volumePath; + Password *password = volParams->password; + int pkcs5_prf = volParams->pkcs5; + int pim = volParams->pim; + DISK_GEOMETRY driveGeometry; + HWND hwndDlg = volParams->hwndDlg; + + + bInPlaceEncNonSysResumed = TRUE; + + buf = (char *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE); + if (!buf) + { + nStatus = ERR_OUTOFMEMORY; + goto closing_seq; + } + + header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE); + if (!header) + { + nStatus = ERR_OUTOFMEMORY; + goto closing_seq; + } + + VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + + if (wipeAlgorithm != TC_WIPE_NONE) + { + wipeBuffer = (byte *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE); + if (!wipeBuffer) + { + nStatus = ERR_OUTOFMEMORY; + goto closing_seq; + } + } + + headerCryptoInfo = crypto_open(); + + if (headerCryptoInfo == NULL) + { + nStatus = ERR_OUTOFMEMORY; + goto closing_seq; + } + + deviceSize = GetDeviceSize (devicePath); + if (deviceSize < 0) + { + // Cannot determine the size of the partition + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + if (dev == INVALID_HANDLE_VALUE) + { + StringCchCopyW (deviceName, ARRAYSIZE(deviceName), devicePath); + + if (FakeDosNameForDevice (deviceName, dosDev, sizeof(dosDev),devName, sizeof(devName),FALSE) != 0) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + dev = OpenPartitionVolume (hwndDlg, devName, + FALSE, // Do not require exclusive access + FALSE, // Do not require shared access + TRUE, // Ask the user to confirm shared access (if exclusive fails) + FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages) + FALSE); // Non-silent mode + + if (dev == INVALID_HANDLE_VALUE) + { + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + } + + // This should never be needed, but is still performed for extra safety (without checking the result) + DeviceIoControl (dev, + FSCTL_ALLOW_EXTENDED_DASD_IO, + NULL, + 0, + NULL, + 0, + &dwResult, + NULL); + + + if (!DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveGeometry, sizeof (driveGeometry), &dwResult, NULL)) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + sectorSize = driveGeometry.BytesPerSector; + + + nStatus = OpenBackupHeader (dev, devicePath, password, pkcs5_prf, pim, &masterCryptoInfo, headerCryptoInfo, deviceSize); + + if (nStatus != ERR_SUCCESS) + goto closing_seq; + + + + remainingBytes = masterCryptoInfo->VolumeSize.Value - masterCryptoInfo->EncryptedAreaLength.Value; + + lastHeaderUpdateDistance = 0; + + + ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value); + + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_ENCRYPTING); + + bFirstNonSysInPlaceEncResumeDone = TRUE; + + + /* The in-place encryption core */ + + while (remainingBytes > 0) + { + workChunkSize = (uint32) min (remainingBytes, TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE); + + if (workChunkSize % ENCRYPTION_DATA_UNIT_SIZE != 0) + { + nStatus = ERR_PARAMETER_INCORRECT; + goto closing_seq; + } + + unitNo.Value = (remainingBytes - workChunkSize + TC_VOLUME_DATA_OFFSET) / ENCRYPTION_DATA_UNIT_SIZE; + + + // Read the plaintext into RAM + +inplace_enc_read: + + offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize - TC_VOLUME_DATA_OFFSET; + + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + if (ReadFile (dev, buf, workChunkSize, &n, NULL) == 0) + { + // Read error + + DWORD dwTmpErr = GetLastError (); + + if (IsDiskReadError (dwTmpErr) && !bVolTransformThreadCancel) + { + // Physical defect or data corruption + + if (!*bTryToCorrectReadErrors) + { + *bTryToCorrectReadErrors = (AskWarnYesNo ("ENABLE_BAD_SECTOR_ZEROING", hwndDlg) == IDYES); + } + + if (*bTryToCorrectReadErrors) + { + // Try to correct the read errors physically + + offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize - TC_VOLUME_DATA_OFFSET; + + nStatus = ZeroUnreadableSectors (dev, offset, workChunkSize, sectorSize, &zeroedSectorCount); + + if (nStatus != ERR_SUCCESS) + { + // Due to write errors, we can't correct the read errors + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + goto inplace_enc_read; + } + } + + SetLastError (dwTmpErr); // Preserve the original error code + + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + if (remainingBytes - workChunkSize < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE) + { + // We reached the inital portion of the filesystem, which we had concealed (in order to prevent + // Windows from interfering with the volume). Now we need to undo that modification. + + for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE - (remainingBytes - workChunkSize); i++) + buf[i] ^= TC_NTFS_CONCEAL_CONSTANT; + } + + + // Encrypt the plaintext in RAM + + EncryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo); + + + // If enabled, wipe the area to which we will write the ciphertext + + if (wipeAlgorithm != TC_WIPE_NONE) + { + byte wipePass; + int wipePassCount = GetWipePassCount (wipeAlgorithm); + + if (wipePassCount <= 0) + { + SetLastError (ERROR_INVALID_PARAMETER); + nStatus = ERR_PARAMETER_INCORRECT; + goto closing_seq; + } + + offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize; + + for (wipePass = 1; wipePass <= wipePassCount; ++wipePass) + { + if (!WipeBuffer (wipeAlgorithm, wipeRandChars, wipePass, wipeBuffer, workChunkSize)) + { + ULONG i; + for (i = 0; i < workChunkSize; ++i) + { + wipeBuffer[i] = buf[i] + wipePass; + } + + EncryptDataUnits (wipeBuffer, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo); + memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate)); + } + + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 + || WriteFile (dev, wipeBuffer, workChunkSize, &n, NULL) == 0) + { + // Write error + dwError = GetLastError(); + + // Undo failed write operation + if (workChunkSize > TC_VOLUME_DATA_OFFSET && SetFilePointerEx (dev, offset, NULL, FILE_BEGIN)) + { + DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo); + WriteFile (dev, buf + TC_VOLUME_DATA_OFFSET, workChunkSize - TC_VOLUME_DATA_OFFSET, &n, NULL); + } + + SetLastError (dwError); + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + } + + memcpy (wipeRandChars, wipeRandCharsUpdate, sizeof (wipeRandCharsUpdate)); + } + + + // Write the ciphertext + + offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize; + + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + if (WriteFile (dev, buf, workChunkSize, &n, NULL) == 0) + { + // Write error + dwError = GetLastError(); + + // Undo failed write operation + if (workChunkSize > TC_VOLUME_DATA_OFFSET && SetFilePointerEx (dev, offset, NULL, FILE_BEGIN)) + { + DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo); + WriteFile (dev, buf + TC_VOLUME_DATA_OFFSET, workChunkSize - TC_VOLUME_DATA_OFFSET, &n, NULL); + } + + SetLastError (dwError); + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + + masterCryptoInfo->EncryptedAreaStart.Value -= workChunkSize; + masterCryptoInfo->EncryptedAreaLength.Value += workChunkSize; + + remainingBytes -= workChunkSize; + lastHeaderUpdateDistance += workChunkSize; + + bEncryptedAreaSizeChanged = TRUE; + + if (lastHeaderUpdateDistance >= TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL) + { + nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize); + + if (nStatus != ERR_SUCCESS) + goto closing_seq; + + lastHeaderUpdateDistance = 0; + } + + ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value); + + if (bVolTransformThreadCancel) + { + bPause = TRUE; + break; + } + } + + nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize); + + + if (nStatus != ERR_SUCCESS) + goto closing_seq; + + + if (!bPause) + { + /* The data area has been fully encrypted; create and write the primary volume header */ + + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINALIZING); + + for (int wipePass = 0; wipePass < (wipeAlgorithm == TC_WIPE_NONE ? 1 : PRAND_HEADER_WIPE_PASSES); wipePass++) + { + nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE, + header, + headerCryptoInfo->ea, + headerCryptoInfo->mode, + password, + masterCryptoInfo->pkcs5, + pim, + (char *) masterCryptoInfo->master_keydata, + &tmpCryptoInfo, + masterCryptoInfo->VolumeSize.Value, + 0, + masterCryptoInfo->EncryptedAreaStart.Value, + masterCryptoInfo->EncryptedAreaLength.Value, + masterCryptoInfo->RequiredProgramVersion, + masterCryptoInfo->HeaderFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC, + masterCryptoInfo->SectorSize, + wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_HEADER_WIPE_PASSES - 1)); + + if (nStatus != ERR_SUCCESS) + goto closing_seq; + + + offset.QuadPart = TC_VOLUME_HEADER_OFFSET; + + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 + || !WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header)) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + // Fill the reserved sectors of the header area with random data + nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, headerCryptoInfo, masterCryptoInfo->VolumeSize.Value, TRUE, FALSE); + + if (nStatus != ERR_SUCCESS) + goto closing_seq; + } + + // Update the configuration files + + SaveNonSysInPlaceEncSettings (-1, wipeAlgorithm, FALSE); + + + + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINISHED); + + nStatus = ERR_SUCCESS; + } + else + { + // The process has been paused by the user or aborted by the wizard (e.g. on app exit) + + nStatus = ERR_USER_ABORT; + + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED); + } + + +closing_seq: + + dwError = GetLastError(); + + if (bEncryptedAreaSizeChanged + && dev != INVALID_HANDLE_VALUE + && masterCryptoInfo != NULL + && headerCryptoInfo != NULL + && deviceSize > 0) + { + // Execution of the core loop may have been interrupted due to an error or user action without updating the header + FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize); + } + + if (masterCryptoInfo != NULL) + { + crypto_close (masterCryptoInfo); + masterCryptoInfo = NULL; + } + + if (headerCryptoInfo != NULL) + { + crypto_close (headerCryptoInfo); + headerCryptoInfo = NULL; + } + + if (tmpCryptoInfo != NULL) + { + crypto_close (tmpCryptoInfo); + tmpCryptoInfo = NULL; + } + + if (dosDev[0]) + RemoveFakeDosName (devicePath, dosDev); + + if (dev != INVALID_HANDLE_VALUE) + { + CloseHandle (dev); + dev = INVALID_HANDLE_VALUE; + } + + if (buf != NULL) + TCfree (buf); + + if (header != NULL) + { + burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + TCfree (header); + } + + if (wipeBuffer != NULL) + TCfree (wipeBuffer); + + if (zeroedSectorCount > 0) + { + wchar_t msg[30000] = {0}; + wchar_t sizeStr[500] = {0}; + + GetSizeString (zeroedSectorCount * sectorSize, sizeStr, sizeof(sizeStr)); + + StringCbPrintfW (msg, sizeof(msg), + GetString ("ZEROED_BAD_SECTOR_COUNT"), + zeroedSectorCount, + sizeStr); + + WarningDirect (msg, hwndDlg); + } + + if (nStatus != ERR_SUCCESS && nStatus != ERR_USER_ABORT) + SetLastError (dwError); + + return nStatus; +} + +int DecryptPartitionInPlace (volatile FORMAT_VOL_PARAMETERS *volParams, volatile BOOL *DiscardUnreadableEncryptedSectors) +{ + HANDLE dev = INVALID_HANDLE_VALUE; + PCRYPTO_INFO masterCryptoInfo = NULL, headerCryptoInfo = NULL; + UINT64_STRUCT unitNo; + char *buf = NULL; + byte *tmpSectorBuf = NULL; + WCHAR dosDev[TC_MAX_PATH] = {0}; + WCHAR devName[MAX_PATH] = {0}; + WCHAR deviceName[MAX_PATH]; + int nStatus = ERR_SUCCESS; + __int64 deviceSize; + uint64 remainingBytes, workChunkStartByteOffset, lastHeaderUpdateDistance = 0, skippedBadSectorCount = 0; + uint32 workChunkSize; + DWORD dwError, dwResult; + BOOL bPause = FALSE, bEncryptedAreaSizeChanged = FALSE; + LARGE_INTEGER offset; + int sectorSize; + int i; + DWORD n; + WCHAR *devicePath = volParams->volumePath; + Password *password = volParams->password; + HWND hwndDlg = volParams->hwndDlg; + int pkcs5_prf = volParams->pkcs5; + int pim = volParams->pim; + DISK_GEOMETRY driveGeometry; + + + buf = (char *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE); + if (!buf) + { + nStatus = ERR_OUTOFMEMORY; + goto closing_seq; + } + + headerCryptoInfo = crypto_open(); + + if (headerCryptoInfo == NULL) + { + nStatus = ERR_OUTOFMEMORY; + goto closing_seq; + } + + deviceSize = GetDeviceSize (devicePath); + if (deviceSize < 0) + { + // Cannot determine the size of the partition + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + + // The wizard should have dismounted the TC volume if it was mounted, but for extra safety we will check this again. + if (IsMountedVolume (devicePath)) + { + int driveLetter = GetMountedVolumeDriveNo (devicePath); + + if (driveLetter == -1 + || !UnmountVolume (hwndDlg, driveLetter, TRUE)) + { + handleWin32Error (hwndDlg, SRC_POS); + AbortProcess ("CANT_DISMOUNT_VOLUME"); + } + } + + + StringCchCopyW (deviceName, ARRAYSIZE(deviceName), devicePath); + + if (FakeDosNameForDevice (deviceName, dosDev, sizeof(dosDev), devName, sizeof(devName), FALSE) != 0) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + dev = OpenPartitionVolume (hwndDlg, devName, + TRUE, // Require exclusive access + FALSE, // Do not require shared access + TRUE, // Ask the user to confirm shared access (if exclusive fails) + FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages) + FALSE); // Non-silent mode + + if (dev == INVALID_HANDLE_VALUE) + { + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + + + + // This should never be needed, but is still performed for extra safety (without checking the result) + DeviceIoControl (dev, + FSCTL_ALLOW_EXTENDED_DASD_IO, + NULL, + 0, + NULL, + 0, + &dwResult, + NULL); + + + if (!DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveGeometry, sizeof (driveGeometry), &dwResult, NULL)) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + if ( (driveGeometry.BytesPerSector == 0) + || (driveGeometry.BytesPerSector > TC_MAX_VOLUME_SECTOR_SIZE) + || (driveGeometry.BytesPerSector % ENCRYPTION_DATA_UNIT_SIZE != 0) + ) + { + Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg); + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + + sectorSize = driveGeometry.BytesPerSector; + + + tmpSectorBuf = (byte *) TCalloc (sectorSize); + if (!tmpSectorBuf) + { + nStatus = ERR_OUTOFMEMORY; + goto closing_seq; + } + + + nStatus = OpenBackupHeader (dev, devicePath, password, pkcs5_prf, pim, &masterCryptoInfo, headerCryptoInfo, deviceSize); + + if (nStatus != ERR_SUCCESS) + goto closing_seq; + + + if (masterCryptoInfo->LegacyVolume) + { + Error ("NONSYS_INPLACE_DECRYPTION_BAD_VOL_FORMAT", hwndDlg); + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + + if (masterCryptoInfo->hiddenVolume) + { + Error ("NONSYS_INPLACE_DECRYPTION_CANT_DECRYPT_HID_VOL", hwndDlg); + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + + if (!bInPlaceEncNonSysResumed + && masterCryptoInfo->VolumeSize.Value == masterCryptoInfo->EncryptedAreaLength.Value) + { + /* Decryption started (not resumed) */ + + if ((masterCryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) == 0) + { + // The volume has not been encrypted in-place so it may contain a hidden volume. + // Ask the user to confirm it does not. + + char *tmpStr[] = {0, + "CONFIRM_VOL_CONTAINS_NO_HIDDEN_VOL", + "VOL_CONTAINS_NO_HIDDEN_VOL", + "VOL_CONTAINS_A_HIDDEN_VOL", + 0}; + + switch (AskMultiChoice ((void **) tmpStr, FALSE, hwndDlg)) + { + case 1: + // NOP + break; + case 2: + default: + // Cancel + nStatus = ERR_DONT_REPORT; + goto closing_seq; + } + } + + // Update config files and app data + + // In the config file, increase the number of partitions where in-place decryption is in progress + SaveNonSysInPlaceEncSettings (1, TC_WIPE_NONE, TRUE); + + // Add the wizard to the system startup sequence if appropriate + if (!IsNonInstallMode ()) + ManageStartupSeqWiz (FALSE, L"/prinplace"); + } + + + + bInPlaceEncNonSysResumed = TRUE; + bFirstNonSysInPlaceEncResumeDone = TRUE; + + + remainingBytes = masterCryptoInfo->EncryptedAreaLength.Value; + + lastHeaderUpdateDistance = 0; + + + ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value); + + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_DECRYPTING); + + + + /* The in-place decryption core */ + + while (remainingBytes > 0) + { + workChunkSize = (uint32) min (remainingBytes, TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE); + + if (workChunkSize % ENCRYPTION_DATA_UNIT_SIZE != 0) + { + nStatus = ERR_PARAMETER_INCORRECT; + goto closing_seq; + } + + workChunkStartByteOffset = masterCryptoInfo->EncryptedAreaStart.Value; + + unitNo.Value = workChunkStartByteOffset / ENCRYPTION_DATA_UNIT_SIZE; + + + // Read the ciphertext into RAM + + offset.QuadPart = workChunkStartByteOffset; + + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + if (ReadFile (dev, buf, workChunkSize, &n, NULL) == 0) + { + // Read error + + DWORD dwTmpErr = GetLastError (); + + if (IsDiskReadError (dwTmpErr) && !bVolTransformThreadCancel) + { + // Physical defect or data corruption + + if (!*DiscardUnreadableEncryptedSectors) + { + *DiscardUnreadableEncryptedSectors = (AskWarnYesNo ("DISCARD_UNREADABLE_ENCRYPTED_SECTORS", hwndDlg) == IDYES); + } + + if (*DiscardUnreadableEncryptedSectors) + { + // Read the work chunk again, but this time each sector individually and skiping each bad sector + + LARGE_INTEGER tmpSectorOffset; + uint64 tmpSectorCount; + uint64 tmpBufOffset = 0; + DWORD tmpNbrReadBytes = 0; + + tmpSectorOffset.QuadPart = offset.QuadPart; + + for (tmpSectorCount = workChunkSize / sectorSize; tmpSectorCount > 0; --tmpSectorCount) + { + if (SetFilePointerEx (dev, tmpSectorOffset, NULL, FILE_BEGIN) == 0) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + if (ReadFile (dev, tmpSectorBuf, sectorSize, &tmpNbrReadBytes, NULL) == 0 + || tmpNbrReadBytes != (DWORD) sectorSize) + { + // Read error + + // Clear the buffer so the content of each unreadable sector is replaced with decrypted all-zero blocks (producing pseudorandom data) + memset (tmpSectorBuf, 0, sectorSize); + + skippedBadSectorCount++; + } + + memcpy (buf + tmpBufOffset, tmpSectorBuf, sectorSize); + + tmpSectorOffset.QuadPart += sectorSize; + tmpBufOffset += sectorSize; + } + } + else + { + SetLastError (dwTmpErr); // Preserve the original error code + + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + } + else + { + SetLastError (dwTmpErr); // Preserve the original error code + + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + } + + // Decrypt the ciphertext in RAM + + DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo); + + + + // Conceal initial portion of the filesystem + + if (workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE) + { + // We are decrypting the initial TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE bytes of the filesystem. We will + // conceal this portion to prevent Windows and applications from interfering with the volume. + + for (i = 0; i < min (TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET + workChunkSize); i++) + buf[i] ^= TC_NTFS_CONCEAL_CONSTANT; + } + + + // Write the plaintext + + offset.QuadPart = workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET; + + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + if (WriteFile (dev, buf, workChunkSize, &n, NULL) == 0) + { + // Write error + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + + masterCryptoInfo->EncryptedAreaStart.Value += workChunkSize; + masterCryptoInfo->EncryptedAreaLength.Value -= workChunkSize; + + remainingBytes -= workChunkSize; + lastHeaderUpdateDistance += workChunkSize; + + bEncryptedAreaSizeChanged = TRUE; + + if (lastHeaderUpdateDistance >= TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL) + { + nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize); + + if (nStatus != ERR_SUCCESS) + { + // Possible write error + goto closing_seq; + } + + lastHeaderUpdateDistance = 0; + } + + ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value); + + if (bVolTransformThreadCancel) + { + bPause = TRUE; + break; + } + } + + nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize); + + + if (nStatus != ERR_SUCCESS) + { + // Possible write error + goto closing_seq; + } + + + if (!bPause) + { + /* Volume has been fully decrypted. */ + + + // Prevent attempts to update volume header during the closing sequence + bEncryptedAreaSizeChanged = FALSE; + + + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINALIZING); + + + + /* Undo concealing of the filesystem */ + + nStatus = ConcealNTFS (dev); + + if (nStatus != ERR_SUCCESS) + goto closing_seq; + + + + /* Ovewrite the backup header and the remaining ciphertext with all-zero blocks (the primary header was overwritten with the decrypted data). */ + + memset (tmpSectorBuf, 0, sectorSize); + + for (offset.QuadPart = masterCryptoInfo->VolumeSize.Value; + offset.QuadPart <= deviceSize - sectorSize; + offset.QuadPart += sectorSize) + { + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + if (WriteFile (dev, tmpSectorBuf, sectorSize, &n, NULL) == 0) + { + // Write error + dwError = GetLastError(); + + SetLastError (dwError); + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + } + + + + /* Update the configuration files */ + + SaveNonSysInPlaceEncSettings (-1, TC_WIPE_NONE, TRUE); + + + + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINISHED); + + nStatus = ERR_SUCCESS; + + } + else + { + // The process has been paused by the user or aborted by the wizard (e.g. on app exit) + + nStatus = ERR_USER_ABORT; + + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED); + } + + if (dev != INVALID_HANDLE_VALUE) + { + CloseHandle (dev); + dev = INVALID_HANDLE_VALUE; + } + + +closing_seq: + + dwError = GetLastError(); + + if (bEncryptedAreaSizeChanged + && dev != INVALID_HANDLE_VALUE + && masterCryptoInfo != NULL + && headerCryptoInfo != NULL + && deviceSize > 0) + { + // Execution of the core loop may have been interrupted due to an error or user action without updating the header + FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize); + } + + if (dev != INVALID_HANDLE_VALUE) + { + CloseHandle (dev); + dev = INVALID_HANDLE_VALUE; + } + + if (masterCryptoInfo != NULL) + { + crypto_close (masterCryptoInfo); + masterCryptoInfo = NULL; + } + + if (headerCryptoInfo != NULL) + { + crypto_close (headerCryptoInfo); + headerCryptoInfo = NULL; + } + + if (dosDev[0]) + RemoveFakeDosName (devicePath, dosDev); + + if (buf != NULL) + { + TCfree (buf); + buf = NULL; + } + + if (tmpSectorBuf != NULL) + { + TCfree (tmpSectorBuf); + tmpSectorBuf = NULL; + } + + if (skippedBadSectorCount > 0) + { + wchar_t msg[30000] = {0}; + wchar_t sizeStr[500] = {0}; + + GetSizeString (skippedBadSectorCount * sectorSize, sizeStr, sizeof(sizeStr)); + + StringCbPrintfW (msg, sizeof(msg), + GetString ("SKIPPED_BAD_SECTOR_COUNT"), + skippedBadSectorCount, + sizeStr); + + WarningDirect (msg, hwndDlg); + } + + if (nStatus != ERR_SUCCESS && nStatus != ERR_USER_ABORT) + SetLastError (dwError); + + return nStatus; +} + +int FastVolumeHeaderUpdate (HANDLE dev, CRYPTO_INFO *headerCryptoInfo, CRYPTO_INFO *masterCryptoInfo, __int64 deviceSize) +{ + LARGE_INTEGER offset; + DWORD n; + int nStatus = ERR_SUCCESS; + byte *header; + DWORD dwError; + uint32 headerCrc32; + byte *fieldPos; + + header = (byte *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE); + + if (!header) + return ERR_OUTOFMEMORY; + + VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + + + fieldPos = (byte *) header + TC_HEADER_OFFSET_ENCRYPTED_AREA_START; + + offset.QuadPart = deviceSize - TC_VOLUME_HEADER_GROUP_SIZE; + + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 + || !ReadEffectiveVolumeHeader (TRUE, dev, header, &n) || n < TC_VOLUME_HEADER_EFFECTIVE_SIZE) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + + DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, headerCryptoInfo); + + if (GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x56455241) + { + nStatus = ERR_PARAMETER_INCORRECT; + goto closing_seq; + } + + mputInt64 (fieldPos, (masterCryptoInfo->EncryptedAreaStart.Value)); + mputInt64 (fieldPos, (masterCryptoInfo->EncryptedAreaLength.Value)); + + // We need to ensure the TC_HEADER_FLAG_NONSYS_INPLACE_ENC flag bit is set, because if volumes created by TC-format + // were decrypted in place, it would be possible to mount them partially encrypted and it wouldn't be possible + // to resume interrupted decryption after the wizard exits. + masterCryptoInfo->HeaderFlags |= TC_HEADER_FLAG_NONSYS_INPLACE_ENC; + fieldPos = (byte *) header + TC_HEADER_OFFSET_FLAGS; + mputLong (fieldPos, (masterCryptoInfo->HeaderFlags)); + + + headerCrc32 = GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC); + fieldPos = (byte *) header + TC_HEADER_OFFSET_HEADER_CRC; + mputLong (fieldPos, headerCrc32); + + EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, headerCryptoInfo); + + + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 + || !WriteEffectiveVolumeHeader (TRUE, dev, header)) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + +closing_seq: + + dwError = GetLastError(); + + burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + TCfree (header); + + if (nStatus != ERR_SUCCESS) + SetLastError (dwError); + + return nStatus; +} + + +static HANDLE OpenPartitionVolume (HWND hwndDlg, const wchar_t *devName, + BOOL bExclusiveRequired, + BOOL bSharedRequired, + BOOL bSharedRequiresConfirmation, + BOOL bShowAlternativeSteps, + BOOL bSilent) +{ + HANDLE dev = INVALID_HANDLE_VALUE; + int retryCount = 0; + + if (bExclusiveRequired) + bSharedRequired = FALSE; + + if (bExclusiveRequired || !bSharedRequired) + { + // Exclusive access + // Note that when exclusive access is denied, it is worth retrying (usually succeeds after a few tries). + while (dev == INVALID_HANDLE_VALUE && retryCount++ < EXCL_ACCESS_MAX_AUTO_RETRIES) + { + dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL); + + if (retryCount > 1) + Sleep (EXCL_ACCESS_AUTO_RETRY_DELAY); + } + } + + if (dev == INVALID_HANDLE_VALUE) + { + if (bExclusiveRequired) + { + if (!bSilent) + { + handleWin32Error (hwndDlg, SRC_POS); + + if (bShowAlternativeSteps) + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE); + else + Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg); + } + return INVALID_HANDLE_VALUE; + } + + // Shared mode + dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL); + if (dev != INVALID_HANDLE_VALUE) + { + if (bSharedRequiresConfirmation + && !bSilent + && AskWarnNoYes ("DEVICE_IN_USE_INPLACE_ENC", hwndDlg) == IDNO) + { + CloseHandle (dev); + return INVALID_HANDLE_VALUE; + } + } + else + { + if (!bSilent) + { + handleWin32Error (MainDlg, SRC_POS); + + if (bShowAlternativeSteps) + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE); + else + Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg); + } + return INVALID_HANDLE_VALUE; + } + } + + return dev; +} + + +static int DismountFileSystem (HWND hwndDlg, HANDLE dev, + int driveLetter, + BOOL bForcedAllowed, + BOOL bForcedRequiresConfirmation, + BOOL bSilent) +{ + int attempt; + BOOL bResult; + DWORD dwResult; + + CloseVolumeExplorerWindows (MainDlg, driveLetter); + + attempt = UNMOUNT_MAX_AUTO_RETRIES * 10; + + while (!(bResult = DeviceIoControl (dev, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) + && attempt > 0) + { + Sleep (UNMOUNT_AUTO_RETRY_DELAY); + attempt--; + } + + if (!bResult) + { + if (!bForcedAllowed) + { + if (!bSilent) + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_LOCK_OR_DISMOUNT_FILESYS", TRUE); + + return ERR_DONT_REPORT; + } + + if (bForcedRequiresConfirmation + && !bSilent + && AskWarnYesNo ("VOL_LOCK_FAILED_OFFER_FORCED_DISMOUNT", hwndDlg) == IDNO) + { + return ERR_DONT_REPORT; + } + } + + // Dismount the volume + + attempt = UNMOUNT_MAX_AUTO_RETRIES * 10; + + while (!(bResult = DeviceIoControl (dev, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) + && attempt > 0) + { + Sleep (UNMOUNT_AUTO_RETRY_DELAY); + attempt--; + } + + if (!bResult) + { + if (!bSilent) + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_LOCK_OR_DISMOUNT_FILESYS", TRUE); + + return ERR_DONT_REPORT; + } + + return ERR_SUCCESS; +} + + +// Easy-to-undo modification applied to conceal the NTFS filesystem (to prevent Windows and apps from +// interfering with it until the volume has been fully encrypted). Note that this function will precisely +// undo any modifications it made to the filesystem automatically if an error occurs when writing (including +// physical drive defects). +static int ConcealNTFS (HANDLE dev) +{ + char buf [TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE]; + DWORD nbrBytesProcessed, nbrBytesProcessed2; + int i; + LARGE_INTEGER offset; + DWORD dwError; + + offset.QuadPart = 0; + + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) + return ERR_OS_ERROR; + + if (ReadFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed, NULL) == 0) + return ERR_OS_ERROR; + + for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE; i++) + buf[i] ^= TC_NTFS_CONCEAL_CONSTANT; + + offset.QuadPart = 0; + + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) + return ERR_OS_ERROR; + + if (WriteFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed, NULL) == 0) + { + // One or more of the sectors is/are probably damaged and cause write errors. + // We must undo the modifications we made. + + dwError = GetLastError(); + + for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE; i++) + buf[i] ^= TC_NTFS_CONCEAL_CONSTANT; + + offset.QuadPart = 0; + + do + { + Sleep (1); + } + while (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 + || WriteFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed2, NULL) == 0); + + SetLastError (dwError); + + return ERR_OS_ERROR; + } + + return ERR_SUCCESS; +} + + +void ShowInPlaceEncErrMsgWAltSteps (HWND hwndDlg, char *iniStrId, BOOL bErr) +{ + wchar_t msg[30000]; + + StringCbCopyW (msg, sizeof(msg), GetString (iniStrId)); + + StringCbCatW (msg, sizeof(msg), L"\n\n\n"); + StringCbCatW (msg, sizeof(msg), GetString ("INPLACE_ENC_ALTERNATIVE_STEPS")); + + if (bErr) + ErrorDirect (msg, hwndDlg); + else + WarningDirect (msg, hwndDlg); +} + + +static void ExportProgressStats (__int64 bytesDone, __int64 totalSize) +{ + NonSysInplaceEncBytesDone = bytesDone; + NonSysInplaceEncTotalSize = totalSize; +} + + +void SetNonSysInplaceEncUIStatus (int nonSysInplaceEncStatus) +{ + NonSysInplaceEncStatus = nonSysInplaceEncStatus; +} + + +BOOL SaveNonSysInPlaceEncSettings (int delta, WipeAlgorithmId newWipeAlgorithm, BOOL bDecrypt) +{ + int count; + char str[32]; + WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE; + + if (delta == 0) + return TRUE; + + count = LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) + delta; + + if (count < 1) + { + RemoveNonSysInPlaceEncNotifications(); + return TRUE; + } + else if (!bDecrypt) + { + if (newWipeAlgorithm != TC_WIPE_NONE) + { + StringCbPrintfA (str, sizeof(str), "%d", (int) newWipeAlgorithm); + + SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE), (DWORD) strlen(str), FALSE, FALSE); + } + else if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE))) + { + _wremove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE)); + } + } + + StringCbPrintfA (str, sizeof(str), "%d", count); + + return SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC), (DWORD) strlen(str), FALSE, FALSE); +} + + +// Repairs damaged sectors (i.e. those with read errors) by zeroing them. +// Note that this operating fails if there are any write errors. +int ZeroUnreadableSectors (HANDLE dev, LARGE_INTEGER startOffset, int64 size, int sectorSize, uint64 *zeroedSectorCount) +{ + int nStatus; + DWORD n; + int64 sectorCount; + LARGE_INTEGER workOffset; + byte *sectorBuffer = NULL; + DWORD dwError; + + workOffset.QuadPart = startOffset.QuadPart; + + sectorBuffer = (byte *) TCalloc (sectorSize); + + if (!sectorBuffer) + return ERR_OUTOFMEMORY; + + if (SetFilePointerEx (dev, startOffset, NULL, FILE_BEGIN) == 0) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + + for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount) + { + if (ReadFile (dev, sectorBuffer, sectorSize, &n, NULL) == 0) + { + memset (sectorBuffer, 0, sectorSize); + + if (SetFilePointerEx (dev, workOffset, NULL, FILE_BEGIN) == 0) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + if (WriteFile (dev, sectorBuffer, sectorSize, &n, NULL) == 0) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + ++(*zeroedSectorCount); + } + + workOffset.QuadPart += n; + } + + nStatus = ERR_SUCCESS; + +closing_seq: + + dwError = GetLastError(); + + if (sectorBuffer != NULL) + TCfree (sectorBuffer); + + if (nStatus != ERR_SUCCESS) + SetLastError (dwError); + + return nStatus; +} + + +static int OpenBackupHeader (HANDLE dev, const wchar_t *devicePath, Password *password, int pkcs5, int pim, PCRYPTO_INFO *retMasterCryptoInfo, CRYPTO_INFO *headerCryptoInfo, __int64 deviceSize) +{ + LARGE_INTEGER offset; + DWORD n; + int nStatus = ERR_SUCCESS; + char *header; + DWORD dwError; + + header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE); + if (!header) + return ERR_OUTOFMEMORY; + + VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + + + + offset.QuadPart = deviceSize - TC_VOLUME_HEADER_GROUP_SIZE; + + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 + || !ReadEffectiveVolumeHeader (TRUE, dev, (byte *) header, &n) || n < TC_VOLUME_HEADER_EFFECTIVE_SIZE) + { + nStatus = ERR_OS_ERROR; + goto closing_seq; + } + + + nStatus = ReadVolumeHeader (FALSE, header, password, pkcs5, pim, FALSE, retMasterCryptoInfo, headerCryptoInfo); + if (nStatus != ERR_SUCCESS) + goto closing_seq; + + +closing_seq: + + dwError = GetLastError(); + + burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE); + TCfree (header); + + dwError = GetLastError(); + + if (nStatus != ERR_SUCCESS) + SetLastError (dwError); + + return nStatus; +} + + +static BOOL GetFreeClusterBeforeThreshold (HANDLE volumeHandle, int64 *freeCluster, int64 clusterThreshold) +{ + const int bitmapSize = 65536; + byte bitmapBuffer[bitmapSize + sizeof (VOLUME_BITMAP_BUFFER)]; + VOLUME_BITMAP_BUFFER *bitmap = (VOLUME_BITMAP_BUFFER *) bitmapBuffer; + STARTING_LCN_INPUT_BUFFER startLcn; + startLcn.StartingLcn.QuadPart = 0; + + DWORD bytesReturned; + while (DeviceIoControl (volumeHandle, FSCTL_GET_VOLUME_BITMAP, &startLcn, sizeof (startLcn), &bitmapBuffer, sizeof (bitmapBuffer), &bytesReturned, NULL) + || GetLastError() == ERROR_MORE_DATA) + { + for (int64 bitmapIndex = 0; bitmapIndex < min (bitmapSize, (bitmap->BitmapSize.QuadPart / 8)); ++bitmapIndex) + { + if (bitmap->StartingLcn.QuadPart + bitmapIndex * 8 >= clusterThreshold) + goto err; + + if (bitmap->Buffer[bitmapIndex] != 0xff) + { + for (int bit = 0; bit < 8; ++bit) + { + if ((bitmap->Buffer[bitmapIndex] & (1 << bit)) == 0) + { + *freeCluster = bitmap->StartingLcn.QuadPart + bitmapIndex * 8 + bit; + + if (*freeCluster >= clusterThreshold) + goto err; + + return TRUE; + } + } + } + } + + startLcn.StartingLcn.QuadPart += min (bitmapSize * 8, bitmap->BitmapSize.QuadPart); + } + +err: + SetLastError (ERROR_DISK_FULL); + return FALSE; +} + + +static BOOL MoveClustersBeforeThresholdInDir (HANDLE volumeHandle, const wstring &directory, int64 clusterThreshold) +{ + WIN32_FIND_DATAW findData; + + HANDLE findHandle = FindFirstFileW (((directory.size() <= 3 ? L"" : L"\\\\?\\") + directory + L"\\*").c_str(), &findData); + if (findHandle == INVALID_HANDLE_VALUE) + return TRUE; // Error ignored + + finally_do_arg (HANDLE, findHandle, { FindClose (finally_arg); }); + + // Find all files and directories + do + { + if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + wstring subDir = findData.cFileName; + + if (subDir == L"." || subDir == L"..") + continue; + + if (!MoveClustersBeforeThresholdInDir (volumeHandle, directory + L"\\" + subDir, clusterThreshold)) + return FALSE; + } + + DWORD access = FILE_READ_ATTRIBUTES; + + if (findData.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) + access = FILE_READ_DATA; + + HANDLE fsObject = CreateFileW ((directory + L"\\" + findData.cFileName).c_str(), access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); + if (fsObject == INVALID_HANDLE_VALUE) + continue; + + finally_do_arg (HANDLE, fsObject, { CloseHandle (finally_arg); }); + + STARTING_VCN_INPUT_BUFFER startVcn; + startVcn.StartingVcn.QuadPart = 0; + RETRIEVAL_POINTERS_BUFFER retPointers; + DWORD bytesReturned; + + // Find clusters allocated beyond the threshold + while (DeviceIoControl (fsObject, FSCTL_GET_RETRIEVAL_POINTERS, &startVcn, sizeof (startVcn), &retPointers, sizeof (retPointers), &bytesReturned, NULL) + || GetLastError() == ERROR_MORE_DATA) + { + if (retPointers.ExtentCount == 0) + break; + + if (retPointers.Extents[0].Lcn.QuadPart != -1) + { + int64 extentStartCluster = retPointers.Extents[0].Lcn.QuadPart; + int64 extentLen = retPointers.Extents[0].NextVcn.QuadPart - retPointers.StartingVcn.QuadPart; + int64 extentEndCluster = extentStartCluster + extentLen - 1; + + if (extentEndCluster >= clusterThreshold) + { + // Move clusters before the threshold + for (int64 movedCluster = max (extentStartCluster, clusterThreshold); movedCluster <= extentEndCluster; ++movedCluster) + { + for (int retry = 0; ; ++retry) + { + MOVE_FILE_DATA moveData; + + if (GetFreeClusterBeforeThreshold (volumeHandle, &moveData.StartingLcn.QuadPart, clusterThreshold)) + { + moveData.FileHandle = fsObject; + moveData.StartingVcn.QuadPart = movedCluster - extentStartCluster + retPointers.StartingVcn.QuadPart; + moveData.ClusterCount = 1; + + if (DeviceIoControl (volumeHandle, FSCTL_MOVE_FILE, &moveData, sizeof (moveData), NULL, 0, &bytesReturned, NULL)) + break; + } + + if (retry > 600) + return FALSE; + + // There are possible race conditions as we work on a live filesystem + Sleep (100); + } + } + } + } + + startVcn.StartingVcn = retPointers.Extents[0].NextVcn; + } + + } while (FindNextFileW (findHandle, &findData)); + + return TRUE; +} + + +BOOL MoveClustersBeforeThreshold (HANDLE volumeHandle, PWSTR volumeDevicePath, int64 clusterThreshold) +{ + int drive = GetDiskDeviceDriveLetter (volumeDevicePath); + if (drive == -1) + { + SetLastError (ERROR_INVALID_PARAMETER); + return FALSE; + } + + wstring volumeRoot = L"X:"; + volumeRoot[0] = L'A' + (wchar_t) drive; + + return MoveClustersBeforeThresholdInDir (volumeHandle, volumeRoot, clusterThreshold); +} diff --git a/src/Format/InPlace.h b/src/Format/InPlace.h index 63673d9d..75cb9e94 100644 --- a/src/Format/InPlace.h +++ b/src/Format/InPlace.h @@ -1,52 +1,52 @@ -/* - 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. -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "Format.h" - -enum nonsys_inplace_enc_status -{ - NONSYS_INPLACE_ENC_STATUS_NONE = 0, - NONSYS_INPLACE_ENC_STATUS_PREPARING, - NONSYS_INPLACE_ENC_STATUS_RESIZING, - NONSYS_INPLACE_ENC_STATUS_ENCRYPTING, - NONSYS_INPLACE_ENC_STATUS_DECRYPTING, - NONSYS_INPLACE_ENC_STATUS_FINALIZING, - NONSYS_INPLACE_ENC_STATUS_PAUSED, - NONSYS_INPLACE_ENC_STATUS_FINISHED, - NONSYS_INPLACE_ENC_STATUS_ERROR -}; - -BOOL CheckRequirementsForNonSysInPlaceEnc (HWND hwndDlg, const wchar_t *devicePath, BOOL silent); -BOOL CheckRequirementsForNonSysInPlaceDec (HWND hwndDlg, const wchar_t *devicePath, BOOL silent); -int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, volatile HANDLE *outHandle, WipeAlgorithmId wipeAlgorithm); -int EncryptPartitionInPlaceResume (HANDLE dev, volatile FORMAT_VOL_PARAMETERS *volParams, WipeAlgorithmId wipeAlgorithm, volatile BOOL *bTryToCorrectReadErrors); -int DecryptPartitionInPlace (volatile FORMAT_VOL_PARAMETERS *volParams, volatile BOOL *DiscardUnreadableEncryptedSectors); -void ShowInPlaceEncErrMsgWAltSteps (HWND hwndDlg, char *iniStrId, BOOL bErr); -void SetNonSysInplaceEncUIStatus (int nonSysInplaceEncStatus); -int FastVolumeHeaderUpdate (HANDLE dev, CRYPTO_INFO *headerCryptoInfo, CRYPTO_INFO *masterCryptoInfo, __int64 deviceSize); - -static HANDLE OpenPartitionVolume (HWND hwndDlg, const wchar_t *devName, BOOL bExclusiveRequired, BOOL bSharedRequired, BOOL bSharedRequiresConfirmation, BOOL bShowAlternativeSteps, BOOL bSilent); -static int DismountFileSystem (HWND hwndDlg, HANDLE dev, int driveLetter, BOOL bForcedAllowed, BOOL bForcedRequiresConfirmation, BOOL bSilent); -static int ConcealNTFS (HANDLE dev); -BOOL SaveNonSysInPlaceEncSettings (int delta, WipeAlgorithmId wipeAlgorithm, BOOL bDecrypting); -static void ExportProgressStats (__int64 bytesDone, __int64 totalSize); -int ZeroUnreadableSectors (HANDLE dev, LARGE_INTEGER startOffset, int64 size, int sectorSize, uint64 *zeroedSectorCount); -static int OpenBackupHeader (HANDLE dev, const wchar_t *devicePath, Password *password, int pkcs5, int pim, PCRYPTO_INFO *retCryptoInfo, CRYPTO_INFO *headerCryptoInfo, __int64 deviceSize); -BOOL MoveClustersBeforeThreshold (HANDLE volumeHandle, PWSTR volumeDevicePath, int64 clusterThreshold); - -#ifdef __cplusplus -} -#endif +/* + 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. +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "Format.h" + +enum nonsys_inplace_enc_status +{ + NONSYS_INPLACE_ENC_STATUS_NONE = 0, + NONSYS_INPLACE_ENC_STATUS_PREPARING, + NONSYS_INPLACE_ENC_STATUS_RESIZING, + NONSYS_INPLACE_ENC_STATUS_ENCRYPTING, + NONSYS_INPLACE_ENC_STATUS_DECRYPTING, + NONSYS_INPLACE_ENC_STATUS_FINALIZING, + NONSYS_INPLACE_ENC_STATUS_PAUSED, + NONSYS_INPLACE_ENC_STATUS_FINISHED, + NONSYS_INPLACE_ENC_STATUS_ERROR +}; + +BOOL CheckRequirementsForNonSysInPlaceEnc (HWND hwndDlg, const wchar_t *devicePath, BOOL silent); +BOOL CheckRequirementsForNonSysInPlaceDec (HWND hwndDlg, const wchar_t *devicePath, BOOL silent); +int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, volatile HANDLE *outHandle, WipeAlgorithmId wipeAlgorithm); +int EncryptPartitionInPlaceResume (HANDLE dev, volatile FORMAT_VOL_PARAMETERS *volParams, WipeAlgorithmId wipeAlgorithm, volatile BOOL *bTryToCorrectReadErrors); +int DecryptPartitionInPlace (volatile FORMAT_VOL_PARAMETERS *volParams, volatile BOOL *DiscardUnreadableEncryptedSectors); +void ShowInPlaceEncErrMsgWAltSteps (HWND hwndDlg, char *iniStrId, BOOL bErr); +void SetNonSysInplaceEncUIStatus (int nonSysInplaceEncStatus); +int FastVolumeHeaderUpdate (HANDLE dev, CRYPTO_INFO *headerCryptoInfo, CRYPTO_INFO *masterCryptoInfo, __int64 deviceSize); + +static HANDLE OpenPartitionVolume (HWND hwndDlg, const wchar_t *devName, BOOL bExclusiveRequired, BOOL bSharedRequired, BOOL bSharedRequiresConfirmation, BOOL bShowAlternativeSteps, BOOL bSilent); +static int DismountFileSystem (HWND hwndDlg, HANDLE dev, int driveLetter, BOOL bForcedAllowed, BOOL bForcedRequiresConfirmation, BOOL bSilent); +static int ConcealNTFS (HANDLE dev); +BOOL SaveNonSysInPlaceEncSettings (int delta, WipeAlgorithmId wipeAlgorithm, BOOL bDecrypting); +static void ExportProgressStats (__int64 bytesDone, __int64 totalSize); +int ZeroUnreadableSectors (HANDLE dev, LARGE_INTEGER startOffset, int64 size, int sectorSize, uint64 *zeroedSectorCount); +static int OpenBackupHeader (HANDLE dev, const wchar_t *devicePath, Password *password, int pkcs5, int pim, PCRYPTO_INFO *retCryptoInfo, CRYPTO_INFO *headerCryptoInfo, __int64 deviceSize); +BOOL MoveClustersBeforeThreshold (HANDLE volumeHandle, PWSTR volumeDevicePath, int64 clusterThreshold); + +#ifdef __cplusplus +} +#endif diff --git a/src/Format/Resource.h b/src/Format/Resource.h index 6f0fdb1b..c407a7f6 100644 --- a/src/Format/Resource.h +++ b/src/Format/Resource.h @@ -1,159 +1,159 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by Format.rc -// -#define IDR_FORMAT_TLB 1 -#define IDD_VOL_CREATION_WIZARD_DLG 101 -#define IDD_CIPHER_PAGE_DLG 102 -#define IDD_SIZE_PAGE_DLG 103 -#define IDD_PASSWORD_PAGE_DLG 104 -#define IDD_VOLUME_LOCATION_PAGE_DLG 105 -#define IDD_FORMAT_PAGE_DLG 106 -#define IDD_INTRO_PAGE_DLG 107 -#define IDD_INFO_PAGE_DLG 108 -#define IDD_HIDVOL_HOST_FILL_PAGE_DLG 109 -#define IDD_HIDDEN_VOL_WIZARD_MODE_PAGE_DLG 110 -#define IDD_PASSWORD_ENTRY_PAGE_DLG 111 -#define IDS_UACSTRING_FMT 112 -#define IDD_VOLUME_TYPE_PAGE_DLG 113 -#define IDR_FORMAT_RSRC_HEADER 114 -#define IDD_SYSENC_SPAN_PAGE_DLG 115 -#define IDB_WIZARD 116 -#define IDD_SYSENC_RESCUE_DISK_CREATION_DLG 117 -#define IDD_SYSENC_COLLECTING_RANDOM_DATA_DLG 118 -#define IDD_SYSENC_MULTI_BOOT_MODE_PAGE_DLG 119 -#define IDD_SYSENC_RESCUE_DISK_BURN_PAGE_DLG 120 -#define IDD_SYSENC_WIPE_MODE_PAGE_DLG 121 -#define IDD_INPLACE_ENCRYPTION_PAGE_DLG 122 -#define IDD_SYSENC_KEYS_GEN_PAGE_DLG 123 -#define IDD_UNIVERSAL_DUAL_CHOICE_PAGE_DLG 124 -#define IDD_SYSENC_DRIVE_ANALYSIS_PAGE_DLG 125 -#define IDD_SYSENC_TYPE_PAGE_DLG 126 -#define IDD_SYSENC_HIDDEN_OS_REQ_CHECK_PAGE_DLG 127 -#define IDD_DEVICE_WIPE_PAGE_DLG 128 -#define IDD_DEVICE_WIPE_MODE_PAGE_DLG 129 -#define IDD_DEVICE_TRANSFORM_MODE_DLG 130 -#define IDD_EXPANDED_LIST_SELECT_PAGE_DLG 131 -#define IDD_DRIVE_LETTER_SELECTION_PAGE 132 -#define IDD_PIM_PAGE_DLG 133 -#define IDC_BOX_TITLE 1000 -#define IDC_RESCUE_DISK_ISO_PATH 1001 -#define IDC_COMBO_BOX 1002 -#define IDC_BOX_HELP 1003 -#define IDC_PASSWORD 1004 -#define IDC_BROWSE 1005 -#define IDC_BOX_HELP2 1006 -#define IDC_COMBO_BOX_HASH 1007 -#define IDC_COMBO_BOX_HASH_ALGO 1008 -#define IDC_SPACE_LEFT 1009 -#define IDC_VERIFY 1010 -#define IDC_KB 1011 -#define IDC_NO_HISTORY 1012 -#define IDC_MB 1013 -#define IDC_PROGRESS_BAR 1014 -#define IDC_GB 1015 -#define IDC_ABORT_BUTTON 1016 -#define IDC_HEADER_KEY 1017 -#define IDC_LIST_BOX 1018 -#define IDC_DISK_KEY 1019 -#define IDC_RANDOM_BYTES 1020 -#define IDC_CIPHER_TEST 1021 -#define IDC_BENCHMARK 1022 -#define IDC_QUICKFORMAT 1023 -#define IDC_BYTESWRITTEN 1024 -#define IDC_WRITESPEED 1025 -#define IDC_KEY_FILES 1026 -#define IDC_TIMEREMAIN 1027 -#define IDC_CLUSTERSIZE 1028 -#define IDC_FILESYS 1029 -#define IDC_SHOW_KEYS 1030 -#define IDC_STD_VOL 1031 -#define IDC_HIDDEN_VOL 1032 -#define IDC_HIDDEN_VOL_HELP 1033 -#define IDC_OPEN_OUTER_VOLUME 1034 -#define IDC_HIDVOL_WIZ_MODE_FULL 1035 -#define IDC_HIDVOL_WIZ_MODE_DIRECT 1036 -#define IDC_PASSWORD_DIRECT 1037 -#define IDC_SIZEBOX 1038 -#define IDC_SELECT_VOLUME_LOCATION 1039 -#define IDC_NEXT 1040 -#define IDC_PREV 1041 -#define IDT_ENCRYPTION_ALGO 1042 -#define IDT_HASH_ALGO 1043 -#define IDT_FORMAT_OPTIONS 1044 -#define IDT_FILESYSTEM 1045 -#define IDT_CLUSTER 1046 -#define IDT_RANDOM_POOL 1047 -#define IDT_HEADER_KEY 1048 -#define IDT_MASTER_KEY 1049 -#define IDT_DONE 1050 -#define IDT_SPEED 1051 -#define IDT_LEFT 1052 -#define IDT_CONFIRM 1053 -#define IDT_PASSWORD 1054 -#define IDC_SHOW_PASSWORD_SINGLE 1055 -#define IDC_SHOW_PASSWORD 1056 -#define IDC_LINK_MORE_INFO_ABOUT_CIPHER 1057 -#define IDC_LINK_HASH_INFO 1058 -#define IDC_POS_BOX 1059 -#define IDC_BITMAP_WIZARD 1060 -#define IDC_FILE_CONTAINER 1061 -#define IDC_NONSYS_DEVICE 1062 -#define IDC_SYS_DEVICE 1063 -#define IDT_FILE_CONTAINER 1064 -#define IDT_NON_SYS_DEVICE 1065 -#define IDT_SYS_DEVICE 1066 -#define IDC_WHOLE_SYS_DRIVE 1067 -#define IDC_SYS_PARTITION 1068 -#define IDT_WHOLE_SYS_DRIVE 1069 -#define IDT_SYS_PARTITION 1070 -#define IDT_RESCUE_DISK_INFO 1071 -#define IDC_MORE_INFO 1072 -#define IDC_MORE_INFO_ON_SYS_ENCRYPTION 1073 -#define IDT_COLLECTING_RANDOM_DATA_NOTE 1074 -#define IDC_MORE_INFO_ON_CONTAINERS 1075 -#define IDC_SINGLE_BOOT 1076 -#define IDC_MULTI_BOOT 1077 -#define IDT_MULTI_BOOT 1078 -#define IDT_SINGLE_BOOT 1079 -#define IDC_SYS_POOL_CONTENTS 1080 -#define IDT_PARTIAL_POOL_CONTENTS 1081 -#define IDC_DOWNLOAD_CD_BURN_SOFTWARE 1082 -#define IDT_RESCUE_DISK_BURN_INFO 1083 -#define IDT_WIPE_MODE_INFO 1084 -#define IDC_WIPE_MODE 1085 -#define IDC_SELECT 1086 -#define IDT_SYSENC_KEYS_GEN_INFO 1087 -#define IDC_DISPLAY_KEYS 1088 -#define IDC_PAUSE 1089 -#define IDT_WIPE_MODE 1090 -#define IDC_MORE_INFO_SYS_ENCRYPTION 1091 -#define IDC_BOX_HELP_NORMAL_VOL 1092 -#define IDT_STATUS 1093 -#define IDT_PROGRESS 1094 -#define IDT_SYSENC_DRIVE_ANALYSIS_INFO 1095 -#define IDC_SYSENC_NORMAL 1096 -#define IDC_SYSENC_HIDDEN 1097 -#define IDC_BOX_HELP_SYSENC_NORMAL 1098 -#define IDC_HIDDEN_SYSENC_INFO_LINK 1099 -#define IDT_PASS 1100 -#define IDC_DEVICE_TRANSFORM_MODE_FORMAT 1101 -#define IDC_DEVICE_TRANSFORM_MODE_INPLACE 1102 -#define IDC_DRIVE_LETTER_LIST 1103 -#define IDT_DRIVE_LETTER 1104 -#define IDC_LINK_PIM_INFO 1105 -#define IDC_SHOW_PIM 1106 -#define IDC_TB 1107 -#define IDC_SKIP_RESCUE_VERIFICATION 1108 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NO_MFC 1 -#define _APS_NEXT_RESOURCE_VALUE 134 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1109 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Format.rc +// +#define IDR_FORMAT_TLB 1 +#define IDD_VOL_CREATION_WIZARD_DLG 101 +#define IDD_CIPHER_PAGE_DLG 102 +#define IDD_SIZE_PAGE_DLG 103 +#define IDD_PASSWORD_PAGE_DLG 104 +#define IDD_VOLUME_LOCATION_PAGE_DLG 105 +#define IDD_FORMAT_PAGE_DLG 106 +#define IDD_INTRO_PAGE_DLG 107 +#define IDD_INFO_PAGE_DLG 108 +#define IDD_HIDVOL_HOST_FILL_PAGE_DLG 109 +#define IDD_HIDDEN_VOL_WIZARD_MODE_PAGE_DLG 110 +#define IDD_PASSWORD_ENTRY_PAGE_DLG 111 +#define IDS_UACSTRING_FMT 112 +#define IDD_VOLUME_TYPE_PAGE_DLG 113 +#define IDR_FORMAT_RSRC_HEADER 114 +#define IDD_SYSENC_SPAN_PAGE_DLG 115 +#define IDB_WIZARD 116 +#define IDD_SYSENC_RESCUE_DISK_CREATION_DLG 117 +#define IDD_SYSENC_COLLECTING_RANDOM_DATA_DLG 118 +#define IDD_SYSENC_MULTI_BOOT_MODE_PAGE_DLG 119 +#define IDD_SYSENC_RESCUE_DISK_BURN_PAGE_DLG 120 +#define IDD_SYSENC_WIPE_MODE_PAGE_DLG 121 +#define IDD_INPLACE_ENCRYPTION_PAGE_DLG 122 +#define IDD_SYSENC_KEYS_GEN_PAGE_DLG 123 +#define IDD_UNIVERSAL_DUAL_CHOICE_PAGE_DLG 124 +#define IDD_SYSENC_DRIVE_ANALYSIS_PAGE_DLG 125 +#define IDD_SYSENC_TYPE_PAGE_DLG 126 +#define IDD_SYSENC_HIDDEN_OS_REQ_CHECK_PAGE_DLG 127 +#define IDD_DEVICE_WIPE_PAGE_DLG 128 +#define IDD_DEVICE_WIPE_MODE_PAGE_DLG 129 +#define IDD_DEVICE_TRANSFORM_MODE_DLG 130 +#define IDD_EXPANDED_LIST_SELECT_PAGE_DLG 131 +#define IDD_DRIVE_LETTER_SELECTION_PAGE 132 +#define IDD_PIM_PAGE_DLG 133 +#define IDC_BOX_TITLE 1000 +#define IDC_RESCUE_DISK_ISO_PATH 1001 +#define IDC_COMBO_BOX 1002 +#define IDC_BOX_HELP 1003 +#define IDC_PASSWORD 1004 +#define IDC_BROWSE 1005 +#define IDC_BOX_HELP2 1006 +#define IDC_COMBO_BOX_HASH 1007 +#define IDC_COMBO_BOX_HASH_ALGO 1008 +#define IDC_SPACE_LEFT 1009 +#define IDC_VERIFY 1010 +#define IDC_KB 1011 +#define IDC_NO_HISTORY 1012 +#define IDC_MB 1013 +#define IDC_PROGRESS_BAR 1014 +#define IDC_GB 1015 +#define IDC_ABORT_BUTTON 1016 +#define IDC_HEADER_KEY 1017 +#define IDC_LIST_BOX 1018 +#define IDC_DISK_KEY 1019 +#define IDC_RANDOM_BYTES 1020 +#define IDC_CIPHER_TEST 1021 +#define IDC_BENCHMARK 1022 +#define IDC_QUICKFORMAT 1023 +#define IDC_BYTESWRITTEN 1024 +#define IDC_WRITESPEED 1025 +#define IDC_KEY_FILES 1026 +#define IDC_TIMEREMAIN 1027 +#define IDC_CLUSTERSIZE 1028 +#define IDC_FILESYS 1029 +#define IDC_SHOW_KEYS 1030 +#define IDC_STD_VOL 1031 +#define IDC_HIDDEN_VOL 1032 +#define IDC_HIDDEN_VOL_HELP 1033 +#define IDC_OPEN_OUTER_VOLUME 1034 +#define IDC_HIDVOL_WIZ_MODE_FULL 1035 +#define IDC_HIDVOL_WIZ_MODE_DIRECT 1036 +#define IDC_PASSWORD_DIRECT 1037 +#define IDC_SIZEBOX 1038 +#define IDC_SELECT_VOLUME_LOCATION 1039 +#define IDC_NEXT 1040 +#define IDC_PREV 1041 +#define IDT_ENCRYPTION_ALGO 1042 +#define IDT_HASH_ALGO 1043 +#define IDT_FORMAT_OPTIONS 1044 +#define IDT_FILESYSTEM 1045 +#define IDT_CLUSTER 1046 +#define IDT_RANDOM_POOL 1047 +#define IDT_HEADER_KEY 1048 +#define IDT_MASTER_KEY 1049 +#define IDT_DONE 1050 +#define IDT_SPEED 1051 +#define IDT_LEFT 1052 +#define IDT_CONFIRM 1053 +#define IDT_PASSWORD 1054 +#define IDC_SHOW_PASSWORD_SINGLE 1055 +#define IDC_SHOW_PASSWORD 1056 +#define IDC_LINK_MORE_INFO_ABOUT_CIPHER 1057 +#define IDC_LINK_HASH_INFO 1058 +#define IDC_POS_BOX 1059 +#define IDC_BITMAP_WIZARD 1060 +#define IDC_FILE_CONTAINER 1061 +#define IDC_NONSYS_DEVICE 1062 +#define IDC_SYS_DEVICE 1063 +#define IDT_FILE_CONTAINER 1064 +#define IDT_NON_SYS_DEVICE 1065 +#define IDT_SYS_DEVICE 1066 +#define IDC_WHOLE_SYS_DRIVE 1067 +#define IDC_SYS_PARTITION 1068 +#define IDT_WHOLE_SYS_DRIVE 1069 +#define IDT_SYS_PARTITION 1070 +#define IDT_RESCUE_DISK_INFO 1071 +#define IDC_MORE_INFO 1072 +#define IDC_MORE_INFO_ON_SYS_ENCRYPTION 1073 +#define IDT_COLLECTING_RANDOM_DATA_NOTE 1074 +#define IDC_MORE_INFO_ON_CONTAINERS 1075 +#define IDC_SINGLE_BOOT 1076 +#define IDC_MULTI_BOOT 1077 +#define IDT_MULTI_BOOT 1078 +#define IDT_SINGLE_BOOT 1079 +#define IDC_SYS_POOL_CONTENTS 1080 +#define IDT_PARTIAL_POOL_CONTENTS 1081 +#define IDC_DOWNLOAD_CD_BURN_SOFTWARE 1082 +#define IDT_RESCUE_DISK_BURN_INFO 1083 +#define IDT_WIPE_MODE_INFO 1084 +#define IDC_WIPE_MODE 1085 +#define IDC_SELECT 1086 +#define IDT_SYSENC_KEYS_GEN_INFO 1087 +#define IDC_DISPLAY_KEYS 1088 +#define IDC_PAUSE 1089 +#define IDT_WIPE_MODE 1090 +#define IDC_MORE_INFO_SYS_ENCRYPTION 1091 +#define IDC_BOX_HELP_NORMAL_VOL 1092 +#define IDT_STATUS 1093 +#define IDT_PROGRESS 1094 +#define IDT_SYSENC_DRIVE_ANALYSIS_INFO 1095 +#define IDC_SYSENC_NORMAL 1096 +#define IDC_SYSENC_HIDDEN 1097 +#define IDC_BOX_HELP_SYSENC_NORMAL 1098 +#define IDC_HIDDEN_SYSENC_INFO_LINK 1099 +#define IDT_PASS 1100 +#define IDC_DEVICE_TRANSFORM_MODE_FORMAT 1101 +#define IDC_DEVICE_TRANSFORM_MODE_INPLACE 1102 +#define IDC_DRIVE_LETTER_LIST 1103 +#define IDT_DRIVE_LETTER 1104 +#define IDC_LINK_PIM_INFO 1105 +#define IDC_SHOW_PIM 1106 +#define IDC_TB 1107 +#define IDC_SKIP_RESCUE_VERIFICATION 1108 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NO_MFC 1 +#define _APS_NEXT_RESOURCE_VALUE 134 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1109 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/src/Format/Tcformat.c b/src/Format/Tcformat.c index a4372533..2065cb5f 100644 --- a/src/Format/Tcformat.c +++ b/src/Format/Tcformat.c @@ -1,10233 +1,10233 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "Crypto.h" -#include "cpu.h" -#include "Apidrvr.h" -#include "Dlgcode.h" -#include "Language.h" -#include "Combo.h" -#include "Registry.h" -#include "Boot/Windows/BootDefs.h" -#include "Common/Common.h" -#include "Common/BootEncryption.h" -#include "Common/Dictionary.h" -#include "Common/Endian.h" -#include "Common/resource.h" -#include "Common/Pkcs5.h" -#include "Platform/Finally.h" -#include "Platform/ForEach.h" -#include "Random.h" -#include "Fat.h" -#include "InPlace.h" -#include "Resource.h" -#include "TcFormat.h" -#include "Format.h" -#include "FormatCom.h" -#include "Password.h" -#include "Progress.h" -#include "Tests.h" -#include "Cmdline.h" -#include "Volumes.h" -#include "Wipe.h" -#include "Xml.h" - -#include - -using namespace VeraCrypt; - -enum wizard_pages -{ - /* IMPORTANT: IF YOU ADD/REMOVE/MOVE ANY PAGES THAT ARE RELATED TO SYSTEM ENCRYPTION, - REVISE THE 'DECOY_OS_INSTRUCTIONS_PORTION_??' STRINGS! */ - - INTRO_PAGE, - SYSENC_TYPE_PAGE, - SYSENC_HIDDEN_OS_REQ_CHECK_PAGE, - SYSENC_SPAN_PAGE, - SYSENC_PRE_DRIVE_ANALYSIS_PAGE, - SYSENC_DRIVE_ANALYSIS_PAGE, - SYSENC_MULTI_BOOT_MODE_PAGE, - SYSENC_MULTI_BOOT_SYS_EQ_BOOT_PAGE, - SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE, - SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE, - SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE, - SYSENC_MULTI_BOOT_OUTCOME_PAGE, - VOLUME_TYPE_PAGE, - HIDDEN_VOL_WIZARD_MODE_PAGE, - VOLUME_LOCATION_PAGE, - DEVICE_TRANSFORM_MODE_PAGE, - HIDDEN_VOL_HOST_PRE_CIPHER_PAGE, - HIDDEN_VOL_PRE_CIPHER_PAGE, - CIPHER_PAGE, - SIZE_PAGE, - HIDDEN_VOL_HOST_PASSWORD_PAGE, - PASSWORD_PAGE, - PIM_PAGE, - FILESYS_PAGE, - SYSENC_COLLECTING_RANDOM_DATA_PAGE, - SYSENC_KEYS_GEN_PAGE, - SYSENC_RESCUE_DISK_CREATION_PAGE, - SYSENC_RESCUE_DISK_BURN_PAGE, - SYSENC_RESCUE_DISK_VERIFIED_PAGE, - SYSENC_WIPE_MODE_PAGE, - SYSENC_PRETEST_INFO_PAGE, - SYSENC_PRETEST_RESULT_PAGE, - SYSENC_ENCRYPTION_PAGE, - NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE, - NONSYS_INPLACE_ENC_RESUME_PARTITION_SEL_PAGE, - NONSYS_INPLACE_ENC_RAND_DATA_PAGE, - NONSYS_INPLACE_ENC_WIPE_MODE_PAGE, - NONSYS_INPLACE_ENC_TRANSFORM_PAGE, - NONSYS_INPLACE_ENC_TRANSFORM_FINISHED_PAGE, - NONSYS_INPLACE_DEC_TRANSFORM_FINISHED_DRIVE_LETTER_PAGE, - FORMAT_PAGE, - FORMAT_FINISHED_PAGE, - SYSENC_HIDDEN_OS_INITIAL_INFO_PAGE, - SYSENC_HIDDEN_OS_WIPE_INFO_PAGE, - DEVICE_WIPE_MODE_PAGE, - DEVICE_WIPE_PAGE -}; - -#define TIMER_INTERVAL_RANDVIEW 30 -#define TIMER_INTERVAL_SYSENC_PROGRESS 30 -#define TIMER_INTERVAL_NONSYS_INPLACE_ENC_PROGRESS 30 -#define TIMER_INTERVAL_SYSENC_DRIVE_ANALYSIS_PROGRESS 100 -#define TIMER_INTERVAL_WIPE_PROGRESS 30 -#define TIMER_INTERVAL_KEYB_LAYOUT_GUARD 10 - -enum sys_encryption_cmd_line_switches -{ - SYSENC_COMMAND_NONE = 0, - SYSENC_COMMAND_RESUME, - SYSENC_COMMAND_STARTUP_SEQ_RESUME, - SYSENC_COMMAND_ENCRYPT, - SYSENC_COMMAND_DECRYPT, - SYSENC_COMMAND_CREATE_HIDDEN_OS, - SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV -}; - -typedef struct -{ - int NumberOfSysDrives; // Number of drives that contain an operating system. -1: unknown, 1: one, 2: two or more - int MultipleSystemsOnDrive; // Multiple systems are installed on the drive where the currently running system resides. -1: unknown, 0: no, 1: yes - int BootLoaderLocation; // Boot loader (boot manager) installed in: 1: MBR/1st cylinder, 0: partition/bootsector: -1: unknown - int BootLoaderBrand; // -1: unknown, 0: Microsoft Windows, 1: any non-Windows boot manager/loader - int SystemOnBootDrive; // If the currently running operating system is installed on the boot drive. -1: unknown, 0: no, 1: yes -} SYSENC_MULTIBOOT_CFG; - -#define SYSENC_PAUSE_RETRY_INTERVAL 100 -#define SYSENC_PAUSE_RETRIES 200 - -// Expected duration of system drive analysis, in ms -#define SYSENC_DRIVE_ANALYSIS_ETA (4*60000) - -BootEncryption *BootEncObj = NULL; -BootEncryptionStatus BootEncStatus; - -HWND hCurPage = NULL; /* Handle to current wizard page */ -int nCurPageNo = -1; /* The current wizard page */ -int nLastPageNo = -1; -volatile int WizardMode = DEFAULT_VOL_CREATION_WIZARD_MODE; /* IMPORTANT: Never change this value directly -- always use ChangeWizardMode() instead. */ -volatile BOOL bHiddenOS = FALSE; /* If TRUE, we are performing or (or supposed to perform) actions relating to an operating system installed in a hidden volume (i.e., encrypting a decoy OS partition or creating the outer/hidden volume for the hidden OS). To determine or set the phase of the process, call ChangeHiddenOSCreationPhase() and DetermineHiddenOSCreationPhase()) */ -BOOL bDirectSysEncMode = FALSE; -BOOL bDirectSysEncModeCommand = SYSENC_COMMAND_NONE; -BOOL DirectDeviceEncMode = FALSE; -BOOL DirectNonSysInplaceDecStartMode = FALSE; -BOOL DirectNonSysInplaceEncResumeMode = FALSE; -BOOL DirectNonSysInplaceDecResumeMode = FALSE; -BOOL DirectPromptNonSysInplaceEncResumeMode = FALSE; -BOOL DirectCreationMode = FALSE; - -volatile BOOL bInPlaceEncNonSys = FALSE; /* If TRUE, existing data on a non-system partition/volume are to be encrypted (or decrypted if bInPlaceDecNonSys is TRUE) in place (for system encryption, this flag is ignored) */ -volatile BOOL bInPlaceDecNonSys = FALSE; /* If TRUE, existing data on a non-system partition/volume are to be decrypted in place (for system encryption, this flag is ignored) */ -volatile BOOL bInPlaceEncNonSysResumed = FALSE; /* If TRUE, the wizard is supposed to resume (or has resumed) process of non-system in-place encryption/decryption. */ -volatile BOOL bFirstNonSysInPlaceEncResumeDone = FALSE; -__int64 NonSysInplaceEncBytesDone = 0; -__int64 NonSysInplaceEncTotalSize = 0; -BOOL bDeviceTransformModeChoiceMade = FALSE; /* TRUE if the user has at least once manually selected the 'in-place' or 'format' option (on the 'device transform mode' page). */ -int nNeedToStoreFilesOver4GB = 0; /* Whether the user wants to be able to store files larger than 4GB on the volume: -1 = Undecided or error, 0 = No, 1 = Yes */ -int nVolumeEA = 1; /* Default encryption algorithm */ -BOOL bSystemEncryptionInProgress = FALSE; /* TRUE when encrypting/decrypting the system partition/drive (FALSE when paused). */ -BOOL bWholeSysDrive = FALSE; /* Whether to encrypt the entire system drive or just the system partition. */ -static BOOL bSystemEncryptionStatusChanged = FALSE; /* TRUE if this instance changed the value of SystemEncryptionStatus (it's set to FALSE each time the system encryption settings are saved to the config file). This value is to be treated as protected -- only the wizard can change this value (others may only read it). */ -volatile BOOL bSysEncDriveAnalysisInProgress = FALSE; -volatile BOOL bSysEncDriveAnalysisTimeOutOccurred = FALSE; -int SysEncDetectHiddenSectors = -1; /* Whether the user wants us to detect and encrypt the Host Protect Area (if any): -1 = Undecided or error, 0 = No, 1 = Yes */ -int SysEncDriveAnalysisStart; -BOOL bDontVerifyRescueDisk = FALSE; -BOOL bFirstSysEncResumeDone = FALSE; -int nMultiBoot = 0; /* The number of operating systems installed on the computer, according to the user. 0: undetermined, 1: one, 2: two or more */ -volatile BOOL bHiddenVol = FALSE; /* If true, we are (or will be) creating a hidden volume. */ -volatile BOOL bHiddenVolHost = FALSE; /* If true, we are (or will be) creating the host volume (called "outer") for a hidden volume. */ -volatile BOOL bHiddenVolDirect = FALSE; /* If true, the wizard omits creating a host volume in the course of the process of hidden volume creation. */ -volatile BOOL bHiddenVolFinished = FALSE; -int hiddenVolHostDriveNo = -1; /* Drive letter for the volume intended to host a hidden volume. */ -BOOL bRemovableHostDevice = FALSE; /* TRUE when creating a device/partition-hosted volume on a removable device. State undefined when creating file-hosted volumes. */ -int realClusterSize; /* Parameter used when determining the maximum possible size of a hidden volume. */ -int hash_algo = DEFAULT_HASH_ALGORITHM; /* Which PRF to use in header key derivation (PKCS #5) and in the RNG. */ -unsigned __int64 nUIVolumeSize = 0; /* The volume size. Important: This value is not in bytes. It has to be multiplied by nMultiplier. Do not use this value when actually creating the volume (it may chop off sector size, if it is not a multiple of 1024 bytes). */ -unsigned __int64 nVolumeSize = 0; /* The volume size, in bytes. */ -unsigned __int64 nHiddenVolHostSize = 0; /* Size of the hidden volume host, in bytes */ -__int64 nMaximumHiddenVolSize = 0; /* Maximum possible size of the hidden volume, in bytes */ -__int64 nbrFreeClusters = 0; -__int64 nMultiplier = BYTES_PER_MB; /* Size selection multiplier. */ -wchar_t szFileName[TC_MAX_PATH+1]; /* The file selected by the user */ -wchar_t szDiskFile[TC_MAX_PATH+1]; /* Fully qualified name derived from szFileName */ -wchar_t szRescueDiskISO[TC_MAX_PATH+1]; /* The filename and path to the Rescue Disk ISO file to be burned (for boot encryption) */ -BOOL bDeviceWipeInProgress = FALSE; -volatile BOOL bTryToCorrectReadErrors = FALSE; -volatile BOOL DiscardUnreadableEncryptedSectors = FALSE; - -volatile BOOL bVolTransformThreadCancel = FALSE; /* TRUE if the user cancels/pauses volume encryption/format */ -volatile BOOL bVolTransformThreadRunning = FALSE; /* Is the volume encryption/format thread running */ -volatile BOOL bVolTransformThreadToRun = FALSE; /* TRUE if the Format/Encrypt button has been clicked and we are proceeding towards launching the thread. */ - -volatile BOOL bConfirmQuit = FALSE; /* If TRUE, the user is asked to confirm exit when he clicks the X icon, Exit, etc. */ -volatile BOOL bConfirmQuitSysEncPretest = FALSE; - -BOOL bDevice = FALSE; /* Is this a partition volume ? */ - -BOOL showKeys = FALSE; -volatile HWND hMasterKey = NULL; /* Text box showing hex dump of the master key */ -volatile HWND hHeaderKey = NULL; /* Text box showing hex dump of the header key */ -volatile HWND hRandPool = NULL; /* Text box showing hex dump of the random pool */ -volatile HWND hRandPoolSys = NULL; /* Text box showing hex dump of the random pool for system encryption */ -volatile HWND hPasswordInputField = NULL; /* Password input field */ -volatile HWND hVerifyPasswordInputField = NULL; /* Verify-password input field */ - -HBITMAP hbmWizardBitmapRescaled = NULL; - -wchar_t OrigKeyboardLayout [8+1] = L"00000409"; -BOOL bKeyboardLayoutChanged = FALSE; /* TRUE if the keyboard layout was changed to the standard US keyboard layout (from any other layout). */ -BOOL bKeybLayoutAltKeyWarningShown = FALSE; /* TRUE if the user has been informed that it is not possible to type characters by pressing keys while the right Alt key is held down. */ - -#ifndef _DEBUG - BOOL bWarnDeviceFormatAdvanced = TRUE; -#else - BOOL bWarnDeviceFormatAdvanced = FALSE; -#endif - -BOOL bWarnOuterVolSuitableFileSys = TRUE; - -Password volumePassword; /* User password */ -char szVerify[MAX_PASSWORD + 1]; /* Tmp password buffer */ -char szRawPassword[MAX_PASSWORD + 1]; /* Password before keyfile was applied to it */ - -int volumePim = 0; - -BOOL bHistoryCmdLine = FALSE; /* History control is always disabled */ -BOOL ComServerMode = FALSE; - - -Password CmdVolumePassword = {0}; /* Password passed from command line */ -int CmdVolumeEA = 0; -int CmdVolumePkcs5 = 0; -int CmdVolumePim = 0; -int CmdVolumeFilesystem = FILESYS_NONE; -unsigned __int64 CmdVolumeFileSize = 0; -BOOL CmdSparseFileSwitch = FALSE; - -BOOL bForceOperation = FALSE; - -BOOL bOperationSuccess = FALSE; - -BOOL bGuiMode = TRUE; - -int nPbar = 0; /* Control ID of progress bar:- for format code */ - -wchar_t HeaderKeyGUIView [KEY_GUI_VIEW_SIZE]; -wchar_t MasterKeyGUIView [KEY_GUI_VIEW_SIZE]; - -#define RANDPOOL_DISPLAY_COLUMNS 15 -#define RANDPOOL_DISPLAY_ROWS 8 -#define RANDPOOL_DISPLAY_BYTE_PORTION (RANDPOOL_DISPLAY_COLUMNS * RANDPOOL_DISPLAY_ROWS) -#define RANDPOOL_DISPLAY_SIZE (RANDPOOL_DISPLAY_BYTE_PORTION * 3 + RANDPOOL_DISPLAY_ROWS + 2) -unsigned char randPool [RANDPOOL_DISPLAY_BYTE_PORTION]; -unsigned char lastRandPool [RANDPOOL_DISPLAY_BYTE_PORTION]; -static unsigned char maskRandPool [RANDPOOL_DISPLAY_BYTE_PORTION]; -static BOOL bUseMask = FALSE; -static DWORD mouseEntropyGathered = 0xFFFFFFFF; -static DWORD mouseEventsInitialCount = 0; -/* max value of entropy needed to fill all random pool = 8 * RNG_POOL_SIZE = 2560 bits */ -static const DWORD maxEntropyLevel = RNG_POOL_SIZE * 8; -static HWND hEntropyBar = NULL; -wchar_t outRandPoolDispBuffer [RANDPOOL_DISPLAY_SIZE]; -BOOL bDisplayPoolContents = TRUE; - -volatile BOOL bSparseFileSwitch = FALSE; -volatile BOOL quickFormat = FALSE; /* WARNING: Meaning of this variable depends on bSparseFileSwitch. If bSparseFileSwitch is TRUE, this variable represents the sparse file flag. */ -volatile int fileSystem = FILESYS_NONE; -volatile int clusterSize = 0; - -SYSENC_MULTIBOOT_CFG SysEncMultiBootCfg; -wchar_t SysEncMultiBootCfgOutcome [4096] = {L'N',L'/',L'A',0}; -volatile int NonSysInplaceEncStatus = NONSYS_INPLACE_ENC_STATUS_NONE; - -vector DeferredNonSysInPlaceEncDevices; - -// specific definitions and implementation for support of resume operation -// in wait dialog mechanism - -void CALLBACK ResumeInPlaceEncWaitThreadProc(void* pArg, HWND hwndDlg) -{ - wchar_t szDevicePath[MAX_PATH] = {0}; - RawDevicesDlgParam param; - param.devices = GetAvailableHostDevices (false, true, false); - param.pszFileName = szDevicePath; - - DeferredNonSysInPlaceEncDevices.clear(); - - if ((IDOK == DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_RAWDEVICES_DLG), hwndDlg, - (DLGPROC) RawDevicesDlgProc, (LPARAM) ¶m)) && wcslen(szDevicePath)) - { - foreach (const HostDevice &device, param.devices) - { - if (device.Path == szDevicePath) - { - OpenVolumeContext volume; - int status = OpenVolume (&volume, device.Path.c_str(), &volumePassword, hash_algo, volumePim, FALSE, FALSE, FALSE, TRUE); - - if ( status == ERR_SUCCESS) - { - if ((volume.CryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) != 0 - && volume.CryptoInfo->EncryptedAreaLength.Value != volume.CryptoInfo->VolumeSize.Value) - { - DeferredNonSysInPlaceEncDevices.push_back (device); - } - else if (volume.CryptoInfo->EncryptedAreaLength.Value == volume.CryptoInfo->VolumeSize.Value) - { - WCHAR szMsg[1024]; - StringCbPrintfW(szMsg, sizeof(szMsg), GetString ("SELECTED_PARTITION_ALREADY_INPLACE_ENC"), - volume.CryptoInfo->HeaderFlags); - ErrorDirect(szMsg, hwndDlg); - } - else - { - WCHAR szMsg[1024]; - StringCbPrintfW(szMsg, sizeof(szMsg), GetString ("SELECTED_PARTITION_NOT_INPLACE_ENC"), - volume.CryptoInfo->HeaderFlags); - ErrorDirect(szMsg, hwndDlg); - } - - CloseVolume (&volume); - } - else - { - handleError(hwndDlg, status, SRC_POS); - } - - break; - } - } - } - else - { - foreach (const HostDevice &device, param.devices) - { - if ( !device.ContainsSystem - && (device.IsPartition || device.DynamicVolume || device.IsVirtualPartition || device.Partitions.empty()) - ) - { - - OpenVolumeContext volume; - - if (OpenVolume (&volume, device.Path.c_str(), &volumePassword, hash_algo, volumePim, FALSE, FALSE, FALSE, TRUE) == ERR_SUCCESS) - { - if ((volume.CryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) != 0 - && volume.CryptoInfo->EncryptedAreaLength.Value != volume.CryptoInfo->VolumeSize.Value) - { - DeferredNonSysInPlaceEncDevices.push_back (device); - } - - CloseVolume (&volume); - } - } - } - } -} - - -static BOOL ElevateWholeWizardProcess (wstring arguments) -{ - wchar_t modPath[MAX_PATH]; - - if (IsAdmin()) - return TRUE; - - if (!IsUacSupported()) - return IsAdmin(); - - GetModuleFileName (NULL, modPath, ARRAYSIZE (modPath)); - - while (true) - { - if ((int)ShellExecute (MainDlg, L"runas", modPath, (wstring(L"/q UAC ") + arguments).c_str(), NULL, SW_SHOWNORMAL) > 32) - { - exit (0); - } - else - { - if (IDRETRY == ErrorRetryCancel ("UAC_INIT_ERROR", MainDlg)) - continue; - return FALSE; - } - } -} - -static void WipePasswordsAndKeyfiles (void) -{ - wchar_t tmp[MAX_PASSWORD+1]; - - // Attempt to wipe passwords stored in the input field buffers - wmemset (tmp, L'X', MAX_PASSWORD); - tmp [MAX_PASSWORD] = 0; - SetWindowText (hPasswordInputField, tmp); - SetWindowText (hVerifyPasswordInputField, tmp); - - burn (&szVerify[0], sizeof (szVerify)); - burn (&volumePassword, sizeof (volumePassword)); - burn (&szRawPassword[0], sizeof (szRawPassword)); - burn (&volumePim, sizeof (volumePim)); - burn (&CmdVolumePassword, sizeof (CmdVolumePassword)); - burn (&CmdVolumePim, sizeof (CmdVolumePim)); - - SetWindowText (hPasswordInputField, L""); - SetWindowText (hVerifyPasswordInputField, L""); - - KeyFileRemoveAll (&FirstKeyFile); - KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile); -} - -static void localcleanup (void) -{ - wchar_t tmp[RANDPOOL_DISPLAY_SIZE+1]; - - // System encryption - - if (WizardMode == WIZARD_MODE_SYS_DEVICE - && InstanceHasSysEncMutex ()) - { - try - { - BootEncStatus = BootEncObj->GetStatus(); - - if (BootEncStatus.SetupInProgress) - { - BootEncObj->AbortSetup (); - } - } - catch (...) - { - // NOP - } - } - - // Mon-system in-place encryption - - if (bInPlaceEncNonSys && (bVolTransformThreadRunning || bVolTransformThreadToRun)) - { - NonSysInplaceEncPause (); - } - - CloseNonSysInplaceEncMutex (); - - - // Device wipe - - if (bDeviceWipeInProgress) - WipeAbort(); - - - WipePasswordsAndKeyfiles (); - - RandStop (TRUE); - - burn (HeaderKeyGUIView, sizeof(HeaderKeyGUIView)); - burn (MasterKeyGUIView, sizeof(MasterKeyGUIView)); - burn (randPool, sizeof(randPool)); - burn (lastRandPool, sizeof(lastRandPool)); - burn (outRandPoolDispBuffer, sizeof(outRandPoolDispBuffer)); - burn (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); - burn (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); - burn (maskRandPool, sizeof(maskRandPool)); - burn (szFileName, sizeof(szFileName)); - burn (szDiskFile, sizeof(szDiskFile)); - - // Attempt to wipe the GUI fields showing portions of randpool, of the master and header keys - wmemset (tmp, L'X', ARRAYSIZE(tmp)); - tmp [ARRAYSIZE(tmp)-1] = 0; - SetWindowText (hRandPool, tmp); - SetWindowText (hRandPoolSys, tmp); - SetWindowText (hMasterKey, tmp); - SetWindowText (hHeaderKey, tmp); - - UnregisterRedTick (hInst); - - // Delete buffered bitmaps (if any) - if (hbmWizardBitmapRescaled != NULL) - { - DeleteObject ((HGDIOBJ) hbmWizardBitmapRescaled); - hbmWizardBitmapRescaled = NULL; - } - - // Cleanup common code resources - cleanup (); - - if (BootEncObj != NULL) - { - delete BootEncObj; - BootEncObj = NULL; - } -} - -static BOOL CALLBACK BroadcastSysEncCfgUpdateCallb (HWND hwnd, LPARAM lParam) -{ - LONG_PTR userDataVal = GetWindowLongPtrW (hwnd, GWLP_USERDATA); - if ((userDataVal == (LONG_PTR) 'VERA') || (userDataVal == (LONG_PTR) 'TRUE')) // Prior to 1.0e, 'TRUE' was used for VeraCrypt dialogs - { - wchar_t name[1024] = { 0 }; - GetWindowText (hwnd, name, ARRAYSIZE (name) - 1); - if (hwnd != MainDlg && wcsstr (name, L"VeraCrypt")) - { - PostMessage (hwnd, TC_APPMSG_SYSENC_CONFIG_UPDATE, 0, 0); - } - } - return TRUE; -} - -static BOOL BroadcastSysEncCfgUpdate (void) -{ - BOOL bSuccess = FALSE; - EnumWindows (BroadcastSysEncCfgUpdateCallb, (LPARAM) &bSuccess); - return bSuccess; -} - -// IMPORTANT: This function may be called only by Format (other modules can only _read_ the system encryption config). -// Returns TRUE if successful (otherwise FALSE) -static BOOL SaveSysEncSettings (HWND hwndDlg) -{ - FILE *f; - - if (!bSystemEncryptionStatusChanged) - return TRUE; - - if (hwndDlg == NULL && MainDlg != NULL) - hwndDlg = MainDlg; - - if (!CreateSysEncMutex ()) - return FALSE; // Only one instance that has the mutex can modify the system encryption settings - - if (SystemEncryptionStatus == SYSENC_STATUS_NONE) - { - if (_wremove (GetConfigPath (TC_APPD_FILENAME_SYSTEM_ENCRYPTION)) != 0) - { - Error ("CANNOT_SAVE_SYS_ENCRYPTION_SETTINGS", hwndDlg); - return FALSE; - } - - bSystemEncryptionStatusChanged = FALSE; - BroadcastSysEncCfgUpdate (); - return TRUE; - } - - f = _wfopen (GetConfigPath (TC_APPD_FILENAME_SYSTEM_ENCRYPTION), L"w,ccs=UTF-8"); - if (f == NULL) - { - Error ("CANNOT_SAVE_SYS_ENCRYPTION_SETTINGS", hwndDlg); - handleWin32Error (hwndDlg, SRC_POS); - return FALSE; - } - - if (XmlWriteHeader (f) < 0 - - || fputws (L"\n\t", f) < 0 - - || fwprintf (f, L"\n\t\t%d", SystemEncryptionStatus) < 0 - - || fwprintf (f, L"\n\t\t%d", (int) nWipeMode) < 0 - - || fputws (L"\n\t", f) < 0 - - || XmlWriteFooter (f) < 0) - { - handleWin32Error (hwndDlg, SRC_POS); - fclose (f); - Error ("CANNOT_SAVE_SYS_ENCRYPTION_SETTINGS", hwndDlg); - return FALSE; - } - - TCFlushFile (f); - - fclose (f); - - bSystemEncryptionStatusChanged = FALSE; - BroadcastSysEncCfgUpdate (); - - return TRUE; -} - -// WARNING: This function may take a long time to finish -static unsigned int DetermineHiddenOSCreationPhase (void) -{ - unsigned int phase = TC_HIDDEN_OS_CREATION_PHASE_NONE; - - try - { - phase = BootEncObj->GetHiddenOSCreationPhase(); - } - catch (Exception &e) - { - e.Show (MainDlg); - AbortProcess("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS"); - } - - return phase; -} - -// IMPORTANT: This function may be called only by Format (other modules can only _read_ the status). -// Returns TRUE if successful (otherwise FALSE) -static BOOL ChangeHiddenOSCreationPhase (int newPhase) -{ - if (!CreateSysEncMutex ()) - { - Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); - return FALSE; - } - - try - { - BootEncObj->SetHiddenOSCreationPhase (newPhase); - } - catch (Exception &e) - { - e.Show (MainDlg); - return FALSE; - } - - //// The contents of the following items might be inappropriate after a change of the phase - //szFileName[0] = 0; - //szDiskFile[0] = 0; - //nUIVolumeSize = 0; - //nVolumeSize = 0; - - return TRUE; -} - -// IMPORTANT: This function may be called only by Format (other modules can only _read_ the system encryption status). -// Returns TRUE if successful (otherwise FALSE) -static BOOL ChangeSystemEncryptionStatus (int newStatus) -{ - if (!CreateSysEncMutex ()) - { - Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); - return FALSE; // Only one instance that has the mutex can modify the system encryption settings - } - - SystemEncryptionStatus = newStatus; - bSystemEncryptionStatusChanged = TRUE; - - if (newStatus == SYSENC_STATUS_ENCRYPTING) - { - // If the user has created a hidden OS and now is creating a decoy OS, we must wipe the hidden OS - // config area in the MBR. - WipeHiddenOSCreationConfig(); - } - - if (newStatus == SYSENC_STATUS_NONE && !IsHiddenOSRunning()) - { - if (DetermineHiddenOSCreationPhase() != TC_HIDDEN_OS_CREATION_PHASE_NONE - && !ChangeHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE)) - return FALSE; - - WipeHiddenOSCreationConfig(); - } - - if (!SaveSysEncSettings (MainDlg)) - { - return FALSE; - } - - return TRUE; -} - -// If the return code of this function is ignored and newWizardMode == WIZARD_MODE_SYS_DEVICE, then this function -// may be called only after CreateSysEncMutex() returns TRUE. It returns TRUE if successful (otherwise FALSE). -static BOOL ChangeWizardMode (int newWizardMode) -{ - if (WizardMode != newWizardMode) - { - if (WizardMode == WIZARD_MODE_SYS_DEVICE || newWizardMode == WIZARD_MODE_SYS_DEVICE) - { - if (newWizardMode == WIZARD_MODE_SYS_DEVICE) - { - if (!CreateSysEncMutex ()) - { - Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); - return FALSE; - } - } - - // If the previous mode was different, the password may have been typed using a different - // keyboard layout (which might confuse the user and cause other problems if system encryption - // was or will be involved). - WipePasswordsAndKeyfiles(); - } - - if (newWizardMode != WIZARD_MODE_NONSYS_DEVICE) - { - bInPlaceEncNonSys = FALSE; - bInPlaceDecNonSys = FALSE; - } - - if (newWizardMode == WIZARD_MODE_NONSYS_DEVICE && !IsAdmin() && IsUacSupported()) - { - if (!ElevateWholeWizardProcess (L"/e")) - return FALSE; - } - - // The contents of the following items may be inappropriate after a change of mode - if (! (bInPlaceDecNonSys && !bInPlaceEncNonSysResumed)) // If we are starting (but not resuming) decryption of non-system volume, we actually need szFileName as it contains the command line param. - szFileName[0] = 0; - szDiskFile[0] = 0; - nUIVolumeSize = 0; - nVolumeSize = 0; - - WizardMode = newWizardMode; - } - - bDevice = (WizardMode != WIZARD_MODE_FILE_CONTAINER); - - if (newWizardMode != WIZARD_MODE_SYS_DEVICE - && !bHiddenOS) - { - CloseSysEncMutex (); - } - - return TRUE; -} - -// Determines whether the wizard directly affects system encryption in any way. -// Note, for example, that when the user enters a password for a hidden volume that is to host a hidden OS, -// WizardMode is NOT set to WIZARD_MODE_SYS_DEVICE. The keyboard layout, however, has to be US. That's why -// this function has to be called instead of checking the value of WizardMode. -static BOOL SysEncInEffect (void) -{ - return (WizardMode == WIZARD_MODE_SYS_DEVICE - || CreatingHiddenSysVol()); -} - -static BOOL CreatingHiddenSysVol (void) -{ - return (bHiddenOS - && bHiddenVol && !bHiddenVolHost); -} - -static void LoadSettingsAndCheckModified (HWND hwndDlg, BOOL bOnlyCheckModified, BOOL* pbSettingsModified, BOOL* pbHistoryModified) -{ - if (!bOnlyCheckModified) - EnableHwEncryption ((ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? FALSE : TRUE); - - WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE; - - if (!bOnlyCheckModified) - LoadSysEncSettings (); - - if (!bOnlyCheckModified && LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) != 0) - bInPlaceEncNonSysPending = TRUE; - - if (!bOnlyCheckModified) - defaultKeyFilesParam.EnableKeyFiles = FALSE; - - ConfigReadCompareInt ("StartOnLogon", FALSE, &bStartOnLogon, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("HiddenSectorDetectionStatus", 0, &HiddenSectorDetectionStatus, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("ShowDisconnectedNetworkDrives", FALSE, &bShowDisconnectedNetworkDrives, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("HideWaitingDialog", FALSE, &bHideWaitingDialog, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("SaveVolumeHistory", FALSE, &bHistory, bOnlyCheckModified, pbSettingsModified); - - { - char szTmp[MAX_PATH] = {0}; - WideCharToMultiByte (CP_UTF8, 0, SecurityTokenLibraryPath, -1, szTmp, MAX_PATH, NULL, NULL); - ConfigReadCompareString ("SecurityTokenLibrary", "", szTmp, sizeof (szTmp) - 1, bOnlyCheckModified, pbSettingsModified); - MultiByteToWideChar (CP_UTF8, 0, szTmp, -1, SecurityTokenLibraryPath, ARRAYSIZE (SecurityTokenLibraryPath)); - - if (!bOnlyCheckModified && SecurityTokenLibraryPath[0]) - InitSecurityTokenLibrary(hwndDlg); - } - - if (bOnlyCheckModified) - { - char langid[6] = {0}; - if (!IsNonInstallMode ()) - { - ConfigReadString ("Language", "", langid, sizeof (langid)); - // when installed, if no preferred language set by user, English is selected default - if (langid [0] == 0) - StringCbCopyA (langid, sizeof(langid), "en"); - - if (pbSettingsModified && strcmp (langid, GetPreferredLangId ())) - *pbSettingsModified = TRUE; - } - else - { - StringCbCopyA (langid, sizeof(langid), GetPreferredLangId ()); - ConfigReadCompareString ("Language", "", langid, sizeof (langid), TRUE, pbSettingsModified); - } - } - - if (hwndDlg != NULL) - { - LoadCombo (GetDlgItem (hwndDlg, IDC_COMBO_BOX), bHistory, bOnlyCheckModified, pbHistoryModified); - return; - } - - if (bHistoryCmdLine) - return; -} - -static void LoadSettings (HWND hwndDlg) -{ - LoadSettingsAndCheckModified (hwndDlg, FALSE, NULL, NULL); -} - -static void SaveSettings (HWND hwndDlg) -{ - WaitCursor (); - - // Check first if modifications ocurred before writing to the settings and history files - // This avoids leaking information about VeraCrypt usage when user only mount volumes without changing setttings or history - BOOL bSettingsChanged = FALSE; - BOOL bHistoryChanged = FALSE; - - LoadSettingsAndCheckModified (hwndDlg, TRUE, &bSettingsChanged, &bHistoryChanged); - - if (bHistoryChanged && hwndDlg != NULL) - DumpCombo (GetDlgItem (hwndDlg, IDC_COMBO_BOX), !bHistory); - - if (bSettingsChanged) - { - ConfigWriteBegin (); - - ConfigWriteInt ("StartOnLogon", bStartOnLogon); - ConfigWriteInt ("HiddenSectorDetectionStatus", HiddenSectorDetectionStatus); - ConfigWriteInt ("SaveVolumeHistory", bHistory); - ConfigWriteStringW ("SecurityTokenLibrary", SecurityTokenLibraryPath[0] ? SecurityTokenLibraryPath : L""); - - ConfigWriteString ("Language", GetPreferredLangId ()); - - ConfigWriteEnd (hwndDlg); - } - - NormalCursor (); -} - -// WARNING: This function does NOT cause immediate application exit (use e.g. return 1 after calling it -// from a DialogProc function). -static void EndMainDlg (HWND hwndDlg) -{ - if (nCurPageNo == VOLUME_LOCATION_PAGE) - { - if (IsWindow(GetDlgItem(hCurPage, IDC_NO_HISTORY))) - bHistory = !IsButtonChecked (GetDlgItem (hCurPage, IDC_NO_HISTORY)); - - MoveEditToCombo (GetDlgItem (hCurPage, IDC_COMBO_BOX), bHistory); - SaveSettings (hCurPage); - } - else - { - SaveSettings (NULL); - } - - SaveSysEncSettings (hwndDlg); - - if (!bHistory) - CleanLastVisitedMRU (); - - EndDialog (hwndDlg, 0); -} - -// Returns TRUE if system encryption or decryption had been or is in progress and has not been completed -static BOOL SysEncryptionOrDecryptionRequired (void) -{ - /* If you update this function, revise SysEncryptionOrDecryptionRequired() in Mount.c as well. */ - - static BootEncryptionStatus locBootEncStatus; - - try - { - locBootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - return (SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING - || SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING - || - ( - locBootEncStatus.DriveMounted - && - ( - locBootEncStatus.ConfiguredEncryptedAreaStart != locBootEncStatus.EncryptedAreaStart - || locBootEncStatus.ConfiguredEncryptedAreaEnd != locBootEncStatus.EncryptedAreaEnd - ) - ) - ); -} - -// Returns TRUE if the system partition/drive is completely encrypted -static BOOL SysDriveOrPartitionFullyEncrypted (BOOL bSilent) -{ - /* If you update this function, revise SysDriveOrPartitionFullyEncrypted() in Mount.c as well. */ - - static BootEncryptionStatus locBootEncStatus; - - try - { - locBootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - if (!bSilent) - e.Show (MainDlg); - } - - return (!locBootEncStatus.SetupInProgress - && locBootEncStatus.ConfiguredEncryptedAreaEnd != 0 - && locBootEncStatus.ConfiguredEncryptedAreaEnd != -1 - && locBootEncStatus.ConfiguredEncryptedAreaStart == locBootEncStatus.EncryptedAreaStart - && locBootEncStatus.ConfiguredEncryptedAreaEnd == locBootEncStatus.EncryptedAreaEnd); -} - -// This functions is to be used when the wizard mode needs to be changed to WIZARD_MODE_SYS_DEVICE. -// If the function fails to switch the mode, it returns FALSE (otherwise TRUE). -BOOL SwitchWizardToSysEncMode (void) -{ - WaitCursor (); - - try - { - BootEncStatus = BootEncObj->GetStatus(); - bWholeSysDrive = BootEncObj->SystemPartitionCoversWholeDrive(); - } - catch (Exception &e) - { - e.Show (MainDlg); - Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); - NormalCursor (); - return FALSE; - } - - // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption - if (!CreateSysEncMutex ()) - { - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); - NormalCursor (); - return FALSE; - } - - // User-mode app may have crashed and its mutex may have gotten lost, so we need to check the driver status too - if (BootEncStatus.SetupInProgress) - { - if (AskWarnYesNo ("SYSTEM_ENCRYPTION_RESUME_PROMPT", MainDlg) == IDYES) - { - if (SystemEncryptionStatus != SYSENC_STATUS_ENCRYPTING - && SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING) - { - // The config file with status was lost or not written correctly - if (!ResolveUnknownSysEncDirection ()) - { - CloseSysEncMutex (); - NormalCursor (); - return FALSE; - } - } - - bDirectSysEncMode = TRUE; - ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); - LoadPage (MainDlg, SYSENC_ENCRYPTION_PAGE); - NormalCursor (); - return TRUE; - } - else - { - CloseSysEncMutex (); - Error ("SYS_ENCRYPTION_OR_DECRYPTION_IN_PROGRESS", MainDlg); - NormalCursor (); - return FALSE; - } - } - - if (BootEncStatus.DriveMounted - || BootEncStatus.DriveEncrypted - || SysEncryptionOrDecryptionRequired ()) - { - - if (!SysDriveOrPartitionFullyEncrypted (FALSE) - && AskWarnYesNo ("SYSTEM_ENCRYPTION_RESUME_PROMPT", MainDlg) == IDYES) - { - if (SystemEncryptionStatus == SYSENC_STATUS_NONE) - { - // If the config file with status was lost or not written correctly, we - // don't know whether to encrypt or decrypt (but we know that encryption or - // decryption is required). Ask the user to select encryption, decryption, - // or cancel - if (!ResolveUnknownSysEncDirection ()) - { - CloseSysEncMutex (); - NormalCursor (); - return FALSE; - } - } - - bDirectSysEncMode = TRUE; - ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); - LoadPage (MainDlg, SYSENC_ENCRYPTION_PAGE); - NormalCursor (); - return TRUE; - } - else - { - CloseSysEncMutex (); - Error ("SETUP_FAILED_BOOT_DRIVE_ENCRYPTED", MainDlg); - NormalCursor (); - return FALSE; - } - } - else - { - // Check compliance with requirements for boot encryption - - if (!IsAdmin()) - { - if (!IsUacSupported()) - { - Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", MainDlg); - } - } - - try - { - BootEncObj->CheckRequirements (); - } - catch (Exception &e) - { - CloseSysEncMutex (); - e.Show (MainDlg); - NormalCursor (); - return FALSE; - } - - if (!ChangeWizardMode (WIZARD_MODE_SYS_DEVICE)) - { - NormalCursor (); - return FALSE; - } - - if (bSysDriveSelected || bSysPartitionSelected) - { - // The user selected the non-sys-device wizard mode but then selected a system device - - bWholeSysDrive = (bSysDriveSelected && !bSysPartitionSelected); - - bSysDriveSelected = FALSE; - bSysPartitionSelected = FALSE; - - try - { - if (!bHiddenVol) - { - if (bWholeSysDrive && !BootEncObj->SystemPartitionCoversWholeDrive()) - { - if (BootEncObj->SystemDriveContainsNonStandardPartitions()) - { - if (AskWarnYesNoString ((wstring (GetString ("SYSDRIVE_NON_STANDARD_PARTITIONS")) + L"\n\n" + GetString ("ASK_ENCRYPT_PARTITION_INSTEAD_OF_DRIVE")).c_str(), MainDlg) == IDYES) - bWholeSysDrive = FALSE; - } - - if (!IsOSAtLeast (WIN_VISTA) && bWholeSysDrive) - { - if (BootEncObj->SystemDriveContainsExtendedPartition()) - { - bWholeSysDrive = FALSE; - - Error ("WDE_UNSUPPORTED_FOR_EXTENDED_PARTITIONS", MainDlg); - - if (AskYesNo ("ASK_ENCRYPT_PARTITION_INSTEAD_OF_DRIVE", MainDlg) == IDNO) - { - ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE); - return FALSE; - } - } - else - Warning ("WDE_EXTENDED_PARTITIONS_WARNING", MainDlg); - } - } - else if (BootEncObj->SystemPartitionCoversWholeDrive() - && !bWholeSysDrive) - bWholeSysDrive = (AskYesNo ("WHOLE_SYC_DEVICE_RECOM", MainDlg) == IDYES); - } - - } - catch (Exception &e) - { - e.Show (MainDlg); - return FALSE; - } - - if (!bHiddenVol) - { - // Skip SYSENC_SPAN_PAGE and SYSENC_TYPE_PAGE as the user already made the choice - LoadPage (MainDlg, bWholeSysDrive ? SYSENC_PRE_DRIVE_ANALYSIS_PAGE : SYSENC_MULTI_BOOT_MODE_PAGE); - } - else - { - // The user selected the non-sys-device wizard mode but then selected a system device. - // In addition, he selected the hidden volume mode. - - if (bWholeSysDrive) - Warning ("HIDDEN_OS_PRECLUDES_SINGLE_KEY_WDE", MainDlg); - - bWholeSysDrive = FALSE; - - LoadPage (MainDlg, SYSENC_TYPE_PAGE); - } - } - else - LoadPage (MainDlg, SYSENC_TYPE_PAGE); - - NormalCursor (); - return TRUE; - } -} - -void SwitchWizardToFileContainerMode (void) -{ - ChangeWizardMode (WIZARD_MODE_FILE_CONTAINER); - - LoadPage (MainDlg, VOLUME_LOCATION_PAGE); - - NormalCursor (); -} - -void SwitchWizardToNonSysDeviceMode (void) -{ - ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE); - - LoadPage (MainDlg, VOLUME_TYPE_PAGE); - - NormalCursor (); -} - -BOOL SwitchWizardToHiddenOSMode (void) -{ - if (SwitchWizardToSysEncMode()) - { - if (nCurPageNo != SYSENC_ENCRYPTION_PAGE) // If the user did not manually choose to resume encryption or decryption of the system partition/drive - { - bHiddenOS = TRUE; - bHiddenVol = TRUE; - bHiddenVolHost = TRUE; - bHiddenVolDirect = FALSE; - bWholeSysDrive = FALSE; - bInPlaceEncNonSys = FALSE; - bInPlaceDecNonSys = FALSE; - - if (bDirectSysEncModeCommand == SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV) - { - // Some of the requirements for hidden OS should have already been checked by the wizard process - // that launched us (in order to elevate), but we must recheck them. Otherwise, an advanced user - // could bypass the checks by using the undocumented CLI switch. Moreover, some requirements - // can be checked only at this point (when we are elevated). - try - { - BootEncObj->CheckRequirementsHiddenOS (); - - BootEncObj->InitialSecurityChecksForHiddenOS (); - } - catch (Exception &e) - { - e.Show (MainDlg); - return FALSE; - } - - LoadPage (MainDlg, SYSENC_MULTI_BOOT_MODE_PAGE); - } - else - LoadPage (MainDlg, SYSENC_HIDDEN_OS_REQ_CHECK_PAGE); - - NormalCursor (); - } - else - return TRUE; - } - else - return FALSE; - - return TRUE; -} - -void SwitchWizardToNonSysInplaceEncResumeMode (BOOL bDecrypt) -{ - if (!IsAdmin() && IsUacSupported()) - { - if (!ElevateWholeWizardProcess (bDecrypt ? L"/resumeinplacedec" : L"/zinplace")) - AbortProcessSilent (); - } - - if (!IsAdmin()) - AbortProcess("ADMIN_PRIVILEGES_WARN_DEVICES"); - - CreateNonSysInplaceEncMutex (); - - bInPlaceEncNonSys = TRUE; - bInPlaceDecNonSys = bDecrypt; - bInPlaceEncNonSysResumed = TRUE; - - ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE); - - LoadPage (MainDlg, NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE); -} - -void SwitchWizardToNonSysInplaceDecStartMode (wchar_t *volPath) -{ - if (!IsAdmin() && IsUacSupported()) - { - if (!ElevateWholeWizardProcess ((wstring (L"/inplacedec \"") + volPath + L"\"").c_str())) - AbortProcessSilent (); - } - - if (!IsAdmin()) - AbortProcess("ADMIN_PRIVILEGES_WARN_DEVICES"); - - if (!CheckRequirementsForNonSysInPlaceDec (MainDlg, volPath, FALSE)) - AbortProcessSilent (); - - CreateNonSysInplaceEncMutex (); - - bInPlaceEncNonSys = TRUE; - bInPlaceDecNonSys = TRUE; - bInPlaceEncNonSysResumed = FALSE; - - ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE); - - LoadPage (MainDlg, NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE); -} - -// Use this function e.g. if the config file with the system encryption settings was lost or not written -// correctly, and we don't know whether to encrypt or decrypt (but we know that encryption or decryption -// is required). Returns FALSE if failed or cancelled. -static BOOL ResolveUnknownSysEncDirection (void) -{ - if (CreateSysEncMutex ()) - { - if (SystemEncryptionStatus != SYSENC_STATUS_ENCRYPTING - && SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING) - { - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); - return FALSE; - } - - if (BootEncStatus.SetupInProgress) - { - return ChangeSystemEncryptionStatus ( - (BootEncStatus.SetupMode != SetupDecryption) ? SYSENC_STATUS_ENCRYPTING : SYSENC_STATUS_DECRYPTING); - } - else - { - // Ask the user to select encryption, decryption, or cancel - - char *tmpStr[] = {0, - !BootEncStatus.DriveEncrypted ? "CHOOSE_ENCRYPT_OR_DECRYPT_FINALIZE_DECRYPT_NOTE" : "CHOOSE_ENCRYPT_OR_DECRYPT", - "ENCRYPT", - "DECRYPT", - "IDCANCEL", - 0}; - - switch (AskMultiChoice ((void **) tmpStr, FALSE, MainDlg)) - { - case 1: - return ChangeSystemEncryptionStatus (SYSENC_STATUS_ENCRYPTING); - case 2: - return ChangeSystemEncryptionStatus (SYSENC_STATUS_DECRYPTING); - default: - return FALSE; - } - } - } - else - return TRUE; - } - else - { - Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); - return FALSE; - } -} - -// This function should be used to resolve inconsistencies that might lead to a deadlock (inability to encrypt or -// decrypt the system partition/drive and to uninstall TrueCrypt). The function removes the system encryption key -// data ("volume header"), the TrueCrypt boot loader, restores the original system loader (if available), -// unregisters the boot driver, etc. Note that if the system partition/drive is encrypted, it will start decrypting -// it in the background (therefore, it should be used when the system partition/drive is not encrypted, ideally). -// Exceptions are handled and errors are reported within the function. Returns TRUE if successful. -static BOOL ForceRemoveSysEnc (void) -{ - if (CreateSysEncMutex ()) // If no other instance is currently taking care of system encryption - { - BootEncryptionStatus locBootEncStatus; - - try - { - locBootEncStatus = BootEncObj->GetStatus(); - - if (locBootEncStatus.SetupInProgress) - BootEncObj->AbortSetupWait (); - - locBootEncStatus = BootEncObj->GetStatus(); - - if (locBootEncStatus.DriveMounted) - { - // Remove the header - BootEncObj->StartDecryption (DiscardUnreadableEncryptedSectors); - locBootEncStatus = BootEncObj->GetStatus(); - - while (locBootEncStatus.SetupInProgress) - { - Sleep (100); - locBootEncStatus = BootEncObj->GetStatus(); - } - - BootEncObj->CheckEncryptionSetupResult (); - } - - Sleep (50); - } - catch (Exception &e) - { - e.Show (MainDlg); - return FALSE; - } - - try - { - locBootEncStatus = BootEncObj->GetStatus(); - - if (!locBootEncStatus.DriveMounted) - BootEncObj->Deinstall (true); - } - catch (Exception &e) - { - e.Show (MainDlg); - return FALSE; - } - - return TRUE; - } - else - return FALSE; -} - -// Returns 0 if there's an error. -__int64 GetSystemPartitionSize (void) -{ - try - { - return BootEncObj->GetSystemDriveConfiguration().SystemPartition.Info.PartitionLength.QuadPart; - } - catch (Exception &e) - { - e.Show (MainDlg); - return 0; - } -} - -void ComboSelChangeEA (HWND hwndDlg) -{ - int nIndex = (int) SendMessage (GetDlgItem (hwndDlg, IDC_COMBO_BOX), CB_GETCURSEL, 0, 0); - - if (nIndex == CB_ERR) - { - SetWindowText (GetDlgItem (hwndDlg, IDC_BOX_HELP), L""); - } - else - { - wchar_t name[100]; - wchar_t auxLine[4096]; - wchar_t hyperLink[256] = { 0 }; - int cipherIDs[5]; - int i, cnt = 0; - - nIndex = (int) SendMessage (GetDlgItem (hwndDlg, IDC_COMBO_BOX), CB_GETITEMDATA, nIndex, 0); - EAGetName (name, nIndex, 0); - - if (wcscmp (name, L"AES") == 0) - { - StringCbPrintfW (hyperLink, sizeof(hyperLink) / 2, GetString ("MORE_INFO_ABOUT"), name); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("AES_HELP")); - } - else if (wcscmp (name, L"Serpent") == 0) - { - StringCbPrintfW (hyperLink, sizeof(hyperLink) / 2, GetString ("MORE_INFO_ABOUT"), name); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SERPENT_HELP")); - } - else if (wcscmp (name, L"Twofish") == 0) - { - StringCbPrintfW (hyperLink, sizeof(hyperLink) / 2, GetString ("MORE_INFO_ABOUT"), name); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("TWOFISH_HELP")); - } - else if (EAGetCipherCount (nIndex) > 1) - { - // Cascade - cipherIDs[cnt++] = i = EAGetLastCipher(nIndex); - while (i = EAGetPreviousCipher(nIndex, i)) - { - cipherIDs[cnt] = i; - cnt++; - } - - switch (cnt) // Number of ciphers in the cascade - { - case 2: - StringCbPrintfW (auxLine, sizeof(auxLine), GetString ("TWO_LAYER_CASCADE_HELP"), - CipherGetName (cipherIDs[1]), - CipherGetKeySize (cipherIDs[1])*8, - CipherGetName (cipherIDs[0]), - CipherGetKeySize (cipherIDs[0])*8); - break; - - case 3: - StringCbPrintfW (auxLine, sizeof(auxLine), GetString ("THREE_LAYER_CASCADE_HELP"), - CipherGetName (cipherIDs[2]), - CipherGetKeySize (cipherIDs[2])*8, - CipherGetName (cipherIDs[1]), - CipherGetKeySize (cipherIDs[1])*8, - CipherGetName (cipherIDs[0]), - CipherGetKeySize (cipherIDs[0])*8); - break; - } - - StringCbCopyW (hyperLink, sizeof(hyperLink), GetString ("IDC_LINK_MORE_INFO_ABOUT_CIPHER")); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), auxLine); - } - else - { - // No info available for this encryption algorithm - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), L""); - } - - - // Update hyperlink - SetWindowTextW (GetDlgItem (hwndDlg, IDC_LINK_MORE_INFO_ABOUT_CIPHER), hyperLink); - AccommodateTextField (hwndDlg, IDC_LINK_MORE_INFO_ABOUT_CIPHER, FALSE, hUserUnderlineFont); - } -} - -static void VerifySizeAndUpdate (HWND hwndDlg, BOOL bUpdate) -{ - BOOL bEnable = TRUE; - wchar_t szTmp[50]; - __int64 lTmp; - __int64 i; - static unsigned __int64 nLastVolumeSize = 0; - - GetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTmp, ARRAYSIZE (szTmp)); - - for (i = 0; i < (__int64) wcslen (szTmp); i++) - { - if (szTmp[i] >= L'0' && szTmp[i] <= L'9') - continue; - else - { - bEnable = FALSE; - break; - } - } - - if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_KB))) - nMultiplier = BYTES_PER_KB; - else if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_MB))) - nMultiplier = BYTES_PER_MB; - else if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_GB))) - nMultiplier = BYTES_PER_GB; - else - nMultiplier = BYTES_PER_TB; - - if (bDevice && !(bHiddenVol && !bHiddenVolHost)) // If raw device but not a hidden volume - { - lTmp = nVolumeSize; - i = 1; - } - else - { - i = nMultiplier; - lTmp = _wtoi64 (szTmp); - - DWORD sectorSize = GetFormatSectorSize(); - uint32 sectorSizeRem = (lTmp * nMultiplier) % sectorSize; - - if (sectorSizeRem != 0) - lTmp = (lTmp * nMultiplier + (sectorSize - sectorSizeRem)) / nMultiplier; - } - - if (bEnable) - { - if (lTmp * i < (bHiddenVolHost ? TC_MIN_HIDDEN_VOLUME_HOST_SIZE : (bHiddenVol ? TC_MIN_HIDDEN_VOLUME_SIZE : TC_MIN_VOLUME_SIZE))) - bEnable = FALSE; - - if (!bHiddenVolHost && bHiddenVol) - { - if (lTmp * i > nMaximumHiddenVolSize) - bEnable = FALSE; - } - else - { - if (lTmp * i > (bHiddenVolHost ? TC_MAX_HIDDEN_VOLUME_HOST_SIZE : TC_MAX_VOLUME_SIZE)) - bEnable = FALSE; - } - } - - if (bUpdate) - { - nUIVolumeSize = lTmp; - - if (!bDevice || (bHiddenVol && !bHiddenVolHost)) // Update only if it's not a raw device or if it's a hidden volume - nVolumeSize = i * lTmp; - } - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), bEnable); - - if (nVolumeSize != nLastVolumeSize) - { - // Change of volume size may make some file systems allowed or disallowed, so the default filesystem must - // be reselected. - fileSystem = FILESYS_NONE; - nLastVolumeSize = nVolumeSize; - } -} - -static void UpdateWizardModeControls (HWND hwndDlg, int setWizardMode) -{ - SendMessage (GetDlgItem (hwndDlg, IDC_FILE_CONTAINER), - BM_SETCHECK, - setWizardMode == WIZARD_MODE_FILE_CONTAINER ? BST_CHECKED : BST_UNCHECKED, - 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_NONSYS_DEVICE), - BM_SETCHECK, - setWizardMode == WIZARD_MODE_NONSYS_DEVICE ? BST_CHECKED : BST_UNCHECKED, - 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_SYS_DEVICE), - BM_SETCHECK, - setWizardMode == WIZARD_MODE_SYS_DEVICE ? BST_CHECKED : BST_UNCHECKED, - 0); -} - -static int GetSelectedWizardMode (HWND hwndDlg) -{ - if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_FILE_CONTAINER))) - return WIZARD_MODE_FILE_CONTAINER; - - if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_NONSYS_DEVICE))) - return WIZARD_MODE_NONSYS_DEVICE; - - if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_SYS_DEVICE))) - return WIZARD_MODE_SYS_DEVICE; - - return DEFAULT_VOL_CREATION_WIZARD_MODE; -} - -static void RefreshMultiBootControls (HWND hwndDlg) -{ -#ifdef DEBUG - if (nMultiBoot == 0) - nMultiBoot = 1; -#endif - - SendMessage (GetDlgItem (hwndDlg, IDC_SINGLE_BOOT), - BM_SETCHECK, - nMultiBoot == 1 ? BST_CHECKED : BST_UNCHECKED, - 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_MULTI_BOOT), - BM_SETCHECK, - nMultiBoot > 1 ? BST_CHECKED : BST_UNCHECKED, - 0); -} - -// -1 = Undecided or error, 0 = No, 1 = Yes -static int Get2RadButtonPageAnswer (void) -{ - if (IsButtonChecked (GetDlgItem (hCurPage, IDC_CHOICE1))) - return 1; - - if (IsButtonChecked (GetDlgItem (hCurPage, IDC_CHOICE2))) - return 0; - - return -1; -} - -// 0 = No, 1 = Yes -static void Update2RadButtonPage (int answer) -{ - SendMessage (GetDlgItem (hCurPage, IDC_CHOICE1), - BM_SETCHECK, - answer == 1 ? BST_CHECKED : BST_UNCHECKED, - 0); - - SendMessage (GetDlgItem (hCurPage, IDC_CHOICE2), - BM_SETCHECK, - answer == 0 ? BST_CHECKED : BST_UNCHECKED, - 0); -} - -// -1 = Undecided, 0 = No, 1 = Yes -static void Init2RadButtonPageYesNo (int answer) -{ - SetWindowTextW (GetDlgItem (hCurPage, IDC_CHOICE1), GetString ("UISTR_YES")); - SetWindowTextW (GetDlgItem (hCurPage, IDC_CHOICE2), GetString ("UISTR_NO")); - - SetWindowTextW (GetDlgItem (MainDlg, IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (MainDlg, IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); - - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), answer >= 0); - EnableWindow (GetDlgItem (MainDlg, IDC_PREV), TRUE); - - Update2RadButtonPage (answer); -} - -static void UpdateSysEncProgressBar (void) -{ - BootEncryptionStatus locBootEncStatus; - - try - { - locBootEncStatus = BootEncObj->GetStatus(); - } - catch (...) - { - return; - } - - if (locBootEncStatus.EncryptedAreaEnd == -1 - || locBootEncStatus.EncryptedAreaStart == -1) - { - UpdateProgressBarProc (0); - } - else - { - UpdateProgressBarProc (locBootEncStatus.EncryptedAreaEnd - locBootEncStatus.EncryptedAreaStart + 1); - - if (locBootEncStatus.SetupInProgress) - { - wchar_t tmpStr[100]; - - // Status - - if (locBootEncStatus.TransformWaitingForIdle) - StringCbCopyW (tmpStr, sizeof(tmpStr), GetString ("PROGRESS_STATUS_WAITING")); - else - StringCbCopyW (tmpStr, sizeof(tmpStr), GetString (SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING ? "PROGRESS_STATUS_DECRYPTING" : "PROGRESS_STATUS_ENCRYPTING")); - - StringCbCatW (tmpStr, sizeof(tmpStr), L" "); - - SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), tmpStr); - } - } -} - -static void InitSysEncProgressBar (void) -{ - BootEncryptionStatus locBootEncStatus; - - try - { - locBootEncStatus = BootEncObj->GetStatus(); - } - catch (...) - { - return; - } - - if (locBootEncStatus.ConfiguredEncryptedAreaEnd == -1 - || locBootEncStatus.ConfiguredEncryptedAreaStart == -1) - return; - - InitProgressBar (locBootEncStatus.ConfiguredEncryptedAreaEnd - - locBootEncStatus.ConfiguredEncryptedAreaStart + 1, - (locBootEncStatus.EncryptedAreaEnd == locBootEncStatus.EncryptedAreaStart || locBootEncStatus.EncryptedAreaEnd == -1) ? - 0 : locBootEncStatus.EncryptedAreaEnd - locBootEncStatus.EncryptedAreaStart + 1, - SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING, - TRUE, - TRUE, - TRUE); -} - -static void UpdateSysEncControls (void) -{ - BootEncryptionStatus locBootEncStatus; - - try - { - locBootEncStatus = BootEncObj->GetStatus(); - } - catch (...) - { - return; - } - - EnableWindow (GetDlgItem (hCurPage, IDC_WIPE_MODE), - !locBootEncStatus.SetupInProgress - && SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING); - - SetWindowTextW (GetDlgItem (hCurPage, IDC_PAUSE), - GetString (locBootEncStatus.SetupInProgress ? "IDC_PAUSE" : "RESUME")); - - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), !locBootEncStatus.SetupInProgress && !bFirstSysEncResumeDone); - - if (!locBootEncStatus.SetupInProgress) - { - wchar_t tmpStr[100]; - - StringCbCopyW (tmpStr, sizeof(tmpStr), GetString ((SysDriveOrPartitionFullyEncrypted (TRUE) || !locBootEncStatus.DriveMounted) ? - "PROGRESS_STATUS_FINISHED" : "PROGRESS_STATUS_PAUSED")); - StringCbCatW (tmpStr, sizeof(tmpStr), L" "); - - // Status - SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), tmpStr); - - if (SysDriveOrPartitionFullyEncrypted (TRUE) || SystemEncryptionStatus == SYSENC_STATUS_NONE) - { - StringCbCopyW (tmpStr, sizeof(tmpStr), GetString ("PROCESSED_PORTION_100_PERCENT")); - StringCbCatW (tmpStr, sizeof(tmpStr), L" "); - - SetWindowTextW (GetDlgItem (hCurPage, IDC_BYTESWRITTEN), tmpStr); - } - - SetWindowText (GetDlgItem (hCurPage, IDC_TIMEREMAIN), L" "); - } -} - -static void SysEncPause (void) -{ - BootEncryptionStatus locBootEncStatus; - - if (CreateSysEncMutex ()) - { - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), FALSE); - - try - { - locBootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); - return; - } - - if (!locBootEncStatus.SetupInProgress) - { - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); - return; - } - - WaitCursor (); - - try - { - int attempts = SYSENC_PAUSE_RETRIES; - - BootEncObj->AbortSetup (); - - locBootEncStatus = BootEncObj->GetStatus(); - - while (locBootEncStatus.SetupInProgress && attempts > 0) - { - Sleep (SYSENC_PAUSE_RETRY_INTERVAL); - attempts--; - locBootEncStatus = BootEncObj->GetStatus(); - } - - if (!locBootEncStatus.SetupInProgress) - BootEncObj->CheckEncryptionSetupResult (); - - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - NormalCursor (); - - if (locBootEncStatus.SetupInProgress) - { - SetTimer (MainDlg, TIMER_ID_SYSENC_PROGRESS, TIMER_INTERVAL_SYSENC_PROGRESS, NULL); - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); - Error ("FAILED_TO_INTERRUPT_SYSTEM_ENCRYPTION", MainDlg); - return; - } - - UpdateSysEncControls (); - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); - } - else - Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); -} - - -static void SysEncResume (void) -{ - BootEncryptionStatus locBootEncStatus; - - if (CreateSysEncMutex ()) - { - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), FALSE); - - try - { - locBootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); - return; - } - - if (locBootEncStatus.SetupInProgress) - { - // Prevent the OS from entering Sleep mode when idle - SetThreadExecutionState (ES_CONTINUOUS | ES_SYSTEM_REQUIRED); - - bSystemEncryptionInProgress = TRUE; - UpdateSysEncControls (); - SetTimer (MainDlg, TIMER_ID_SYSENC_PROGRESS, TIMER_INTERVAL_SYSENC_PROGRESS, NULL); - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); - return; - } - - bVolTransformThreadCancel = FALSE; - bSystemEncryptionInProgress = FALSE; - WaitCursor (); - - try - { - switch (SystemEncryptionStatus) - { - case SYSENC_STATUS_ENCRYPTING: - - BootEncObj->StartEncryption (nWipeMode, bTryToCorrectReadErrors ? true : false); - break; - - case SYSENC_STATUS_DECRYPTING: - - if (locBootEncStatus.DriveMounted) // If the drive is not encrypted we will just deinstall - BootEncObj->StartDecryption (DiscardUnreadableEncryptedSectors); - - break; - } - - bSystemEncryptionInProgress = TRUE; - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - NormalCursor (); - - if (!bSystemEncryptionInProgress) - { - // Allow the OS to enter Sleep mode when idle - SetThreadExecutionState (ES_CONTINUOUS); - - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); - Error ("FAILED_TO_RESUME_SYSTEM_ENCRYPTION", MainDlg); - return; - } - - // Prevent the OS from entering Sleep mode when idle - SetThreadExecutionState (ES_CONTINUOUS | ES_SYSTEM_REQUIRED); - - bFirstSysEncResumeDone = TRUE; - InitSysEncProgressBar (); - UpdateSysEncProgressBar (); - UpdateSysEncControls (); - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); - SetTimer (MainDlg, TIMER_ID_SYSENC_PROGRESS, TIMER_INTERVAL_SYSENC_PROGRESS, NULL); - } - else - Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); -} - - -static BOOL GetDevicePathForHiddenOS (void) -{ - BOOL tmpbDevice = FALSE; - - try - { - StringCbCopyW (szFileName, sizeof(szFileName), BootEncObj->GetPartitionForHiddenOS().DevicePath.c_str()); - - CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice); - } - catch (Exception &e) - { - e.Show (MainDlg); - return FALSE; - } - - return (szFileName[0] != 0 - && szDiskFile[0] != 0 - && tmpbDevice); -} - - -// Returns TRUE if there is unallocated space greater than 64 MB (max possible slack space size) between the -// boot partition and the first partition behind it. If there's none or if an error occurs, returns FALSE. -static BOOL CheckGapBetweenSysAndHiddenOS (void) -{ - try - { - SystemDriveConfiguration sysDriveCfg = BootEncObj->GetSystemDriveConfiguration(); - - return (sysDriveCfg.SystemPartition.Info.StartingOffset.QuadPart - + sysDriveCfg.SystemPartition.Info.PartitionLength.QuadPart - + 64 * BYTES_PER_MB - + 128 * BYTES_PER_KB - <= BootEncObj->GetPartitionForHiddenOS().Info.StartingOffset.QuadPart); - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - return FALSE; -} - - -static void NonSysInplaceEncPause (void) -{ - bVolTransformThreadCancel = TRUE; - - WaitCursor (); - - int waitThreshold = 100; // Do not block GUI events for more than 10 seconds. IMPORTANT: This prevents deadlocks when the thread calls us back e.g. to update GUI! - - while (bVolTransformThreadRunning || bVolTransformThreadToRun) - { - MSG guiMsg; - - bVolTransformThreadCancel = TRUE; - - if (waitThreshold <= 0) - { - while (PeekMessageW (&guiMsg, NULL, 0, 0, PM_REMOVE) != 0) - { - DispatchMessageW (&guiMsg); - } - } - else - waitThreshold--; - - Sleep (100); - } -} - - -static void NonSysInplaceEncResume (void) -{ - if (bVolTransformThreadRunning || bVolTransformThreadToRun || bVolTransformThreadCancel) - return; - - if (!bInPlaceEncNonSysResumed - && !FinalPreTransformPrompts ()) - { - return; - } - - CreateNonSysInplaceEncMutex (); - - bFirstNonSysInPlaceEncResumeDone = TRUE; - - SetTimer (MainDlg, TIMER_ID_NONSYS_INPLACE_ENC_PROGRESS, TIMER_INTERVAL_NONSYS_INPLACE_ENC_PROGRESS, NULL); - - bVolTransformThreadCancel = FALSE; - bVolTransformThreadToRun = TRUE; - - UpdateNonSysInPlaceEncControls (); - - LastDialogId = "NONSYS_INPLACE_ENC_IN_PROGRESS"; - - _beginthread (volTransformThreadFunction, 0, MainDlg); - - return; -} - - -void ShowNonSysInPlaceEncUIStatus (void) -{ - wchar_t nonSysInplaceEncUIStatus [300] = {0}; - - switch (NonSysInplaceEncStatus) - { - case NONSYS_INPLACE_ENC_STATUS_PAUSED: - StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_PAUSED")); - break; - case NONSYS_INPLACE_ENC_STATUS_PREPARING: - StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_PREPARING")); - break; - case NONSYS_INPLACE_ENC_STATUS_RESIZING: - StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_RESIZING")); - break; - case NONSYS_INPLACE_ENC_STATUS_ENCRYPTING: - StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_ENCRYPTING")); - break; - case NONSYS_INPLACE_ENC_STATUS_DECRYPTING: - StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_DECRYPTING")); - break; - case NONSYS_INPLACE_ENC_STATUS_FINALIZING: - StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_FINALIZING")); - break; - case NONSYS_INPLACE_ENC_STATUS_FINISHED: - StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_FINISHED")); - break; - case NONSYS_INPLACE_ENC_STATUS_ERROR: - StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_ERROR")); - break; - } - - StringCbCatW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), L" "); - - SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), nonSysInplaceEncUIStatus); -} - - -void UpdateNonSysInPlaceEncControls (void) -{ - // Reduce flickering by updating a GUI element only when a relevant change affects it - static BOOL lastbVolTransformThreadRunning = !bVolTransformThreadRunning; - static BOOL lastbVolTransformThreadToRun = !bVolTransformThreadToRun; - static BOOL lastbInPlaceEncNonSysResumed = !bInPlaceEncNonSysResumed; - - EnableWindow (GetDlgItem (hCurPage, IDC_WIPE_MODE), !(bVolTransformThreadRunning || bVolTransformThreadToRun) && !bInPlaceDecNonSys); - - if (lastbVolTransformThreadRunning != bVolTransformThreadRunning - || lastbVolTransformThreadToRun != bVolTransformThreadToRun) - { - SetWindowTextW (GetDlgItem (hCurPage, IDC_PAUSE), - GetString ((bVolTransformThreadRunning || bVolTransformThreadToRun) ? "IDC_PAUSE" : "RESUME")); - - lastbVolTransformThreadRunning = bVolTransformThreadRunning; - lastbVolTransformThreadToRun = bVolTransformThreadToRun; - } - - if (lastbInPlaceEncNonSysResumed != bInPlaceEncNonSysResumed) - { - SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString (bInPlaceEncNonSysResumed ? "DEFER" : "CANCEL")); - lastbInPlaceEncNonSysResumed = bInPlaceEncNonSysResumed; - } - - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), bFirstNonSysInPlaceEncResumeDone - && NonSysInplaceEncStatus != NONSYS_INPLACE_ENC_STATUS_FINALIZING - && NonSysInplaceEncStatus != NONSYS_INPLACE_ENC_STATUS_FINISHED); - - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), !(bVolTransformThreadRunning || bVolTransformThreadToRun) && !bFirstNonSysInPlaceEncResumeDone); - EnableWindow (GetDlgItem (MainDlg, IDC_PREV), !(bVolTransformThreadRunning || bVolTransformThreadToRun) && !bInPlaceEncNonSysResumed); - EnableWindow (GetDlgItem (MainDlg, IDCANCEL), - !(bVolTransformThreadToRun - || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_PREPARING - || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_RESIZING - || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINALIZING - || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINISHED)); - - if (bVolTransformThreadRunning || bVolTransformThreadToRun) - { - switch (NonSysInplaceEncStatus) - { - case NONSYS_INPLACE_ENC_STATUS_PREPARING: - case NONSYS_INPLACE_ENC_STATUS_RESIZING: - case NONSYS_INPLACE_ENC_STATUS_FINALIZING: - ArrowWaitCursor (); - break; - - case NONSYS_INPLACE_ENC_STATUS_ENCRYPTING: - NormalCursor (); - break; - - default: - NormalCursor (); - break; - } - - if (bVolTransformThreadCancel) - WaitCursor (); - } - else - { - NormalCursor (); - - if (bInPlaceEncNonSysResumed) - { - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED); - } - else - SetWindowText (GetDlgItem (hCurPage, IDC_WRITESPEED), L" "); - - SetWindowText (GetDlgItem (hCurPage, IDC_TIMEREMAIN), L" "); - } - - ShowNonSysInPlaceEncUIStatus (); - - UpdateNonSysInplaceEncProgressBar (); -} - - -static void UpdateNonSysInplaceEncProgressBar (void) -{ - static int lastNonSysInplaceEncStatus = NONSYS_INPLACE_ENC_STATUS_NONE; - int nonSysInplaceEncStatus = NonSysInplaceEncStatus; - __int64 totalSize = NonSysInplaceEncTotalSize; - - if (bVolTransformThreadRunning - && (nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_ENCRYPTING - || nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_DECRYPTING - || nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINALIZING - || nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINISHED)) - { - if (lastNonSysInplaceEncStatus != nonSysInplaceEncStatus - && (nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_ENCRYPTING || nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_DECRYPTING)) - { - InitNonSysInplaceEncProgressBar (); - } - else - { - if (totalSize <= 0 && nVolumeSize > 0) - totalSize = nVolumeSize; - - if (totalSize > 0) - UpdateProgressBarProc (NonSysInplaceEncBytesDone); - } - } - - ShowNonSysInPlaceEncUIStatus (); - - lastNonSysInplaceEncStatus = nonSysInplaceEncStatus; -} - - -static void InitNonSysInplaceEncProgressBar (void) -{ - __int64 totalSize = NonSysInplaceEncTotalSize; - - if (totalSize <= 0) - { - if (nVolumeSize <= 0) - return; - - totalSize = nVolumeSize; - } - - InitProgressBar (totalSize, - NonSysInplaceEncBytesDone, - bInPlaceDecNonSys, - TRUE, - TRUE, - TRUE); -} - - -void DisplayRandPool (HWND hwndDlg, HWND hPoolDisplay, BOOL bShow) -{ - wchar_t tmp[4]; - unsigned char tmpByte; - int col, row; - static BOOL bRandPoolDispAscii = FALSE; - DWORD mouseEventsCounter; - - RandpeekBytes (hwndDlg, randPool, sizeof (randPool), &mouseEventsCounter); - - ProcessEntropyEstimate (hEntropyBar, &mouseEventsInitialCount, mouseEventsCounter, maxEntropyLevel, &mouseEntropyGathered); - - if (memcmp (lastRandPool, randPool, sizeof(lastRandPool)) != 0) - { - outRandPoolDispBuffer[0] = 0; - - for (row = 0; row < RANDPOOL_DISPLAY_ROWS; row++) - { - for (col = 0; col < RANDPOOL_DISPLAY_COLUMNS; col++) - { - if (bShow) - { - tmpByte = randPool[row * RANDPOOL_DISPLAY_COLUMNS + col]; - - StringCbPrintfW (tmp, sizeof(tmp), bRandPoolDispAscii ? ((tmpByte >= 32 && tmpByte < 255 && tmpByte != L'&') ? L" %c " : L" . ") : L"%02X ", tmpByte); - } - else if (bUseMask) - { - /* use mask to compute a randomized ASCII representation */ - tmpByte = (randPool[row * RANDPOOL_DISPLAY_COLUMNS + col] - - lastRandPool[row * RANDPOOL_DISPLAY_COLUMNS + col]) ^ maskRandPool [row * RANDPOOL_DISPLAY_COLUMNS + col]; - tmp[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); - tmp[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); - tmp[2] = L' '; - tmp[3] = 0; - } - else - { - StringCbCopyW (tmp, sizeof(tmp), L"** "); - } - - - StringCbCatW (outRandPoolDispBuffer, sizeof(outRandPoolDispBuffer), tmp); - } - StringCbCatW (outRandPoolDispBuffer, sizeof(outRandPoolDispBuffer), L"\n"); - } - SetWindowText (hPoolDisplay, outRandPoolDispBuffer); - - memcpy (lastRandPool, randPool, sizeof(lastRandPool)); - } -} - - -void DisplayPortionsOfKeys (HWND headerKeyHandle, HWND masterKeyHandle, wchar_t *headerKeyStr, wchar_t *masterKeyStr, BOOL hideKeys) -{ - const wchar_t *hiddenKey = L"******************************** "; - - SetWindowTextW (headerKeyHandle, hideKeys ? hiddenKey : (std::wstring (headerKeyStr) + GetString ("TRIPLE_DOT_GLYPH_ELLIPSIS")).c_str()); - SetWindowTextW (masterKeyHandle, hideKeys ? hiddenKey : (std::wstring (masterKeyStr) + GetString ("TRIPLE_DOT_GLYPH_ELLIPSIS")).c_str()); -} - - -static void WipeAbort (void) -{ - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), FALSE); - - if (bHiddenOS && IsHiddenOSRunning()) - { - /* Decoy system partition wipe */ - - DecoySystemWipeStatus decoySysPartitionWipeStatus; - - try - { - decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); - return; - } - - if (!decoySysPartitionWipeStatus.WipeInProgress) - { - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); - return; - } - - WaitCursor (); - - try - { - int attempts = SYSENC_PAUSE_RETRIES; - - BootEncObj->AbortDecoyOSWipe (); - - decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); - - while (decoySysPartitionWipeStatus.WipeInProgress && attempts > 0) - { - Sleep (SYSENC_PAUSE_RETRY_INTERVAL); - attempts--; - decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); - } - - if (!decoySysPartitionWipeStatus.WipeInProgress) - BootEncObj->CheckDecoyOSWipeResult (); - - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - NormalCursor (); - - if (decoySysPartitionWipeStatus.WipeInProgress) - { - SetTimer (MainDlg, TIMER_ID_WIPE_PROGRESS, TIMER_INTERVAL_WIPE_PROGRESS, NULL); - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); - Error ("FAILED_TO_INTERRUPT_WIPING", MainDlg); - return; - } - } - else - { - /* Regular device wipe (not decoy system partition wipe) */ - } - - UpdateWipeControls (); - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); -} - - -static void WipeStart (void) -{ - if (bHiddenOS && IsHiddenOSRunning()) - { - /* Decoy system partition wipe */ - - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), FALSE); - - bDeviceWipeInProgress = FALSE; - WaitCursor (); - - try - { - BootEncObj->StartDecoyOSWipe (nWipeMode); - - bDeviceWipeInProgress = TRUE; - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - NormalCursor (); - - if (!bDeviceWipeInProgress) - { - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); - Error ("FAILED_TO_START_WIPING", MainDlg); - return; - } - } - else - { - /* Regular device wipe (not decoy system partition wipe) */ - } - - InitWipeProgressBar (); - UpdateWipeProgressBar (); - UpdateWipeControls (); - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); - SetTimer (MainDlg, TIMER_ID_WIPE_PROGRESS, TIMER_INTERVAL_WIPE_PROGRESS, NULL); -} - - -static void UpdateWipeProgressBar (void) -{ - if (bHiddenOS && IsHiddenOSRunning()) - { - /* Decoy system partition wipe */ - - DecoySystemWipeStatus decoySysPartitionWipeStatus; - - try - { - decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); - BootEncStatus = BootEncObj->GetStatus(); - } - catch (...) - { - return; - } - - if (decoySysPartitionWipeStatus.WipedAreaEnd == -1) - UpdateProgressBarProc (0); - else - UpdateProgressBarProc (decoySysPartitionWipeStatus.WipedAreaEnd - BootEncStatus.ConfiguredEncryptedAreaStart + 1); - } - else - { - /* Regular device wipe (not decoy system partition wipe) */ - } -} - - -static void InitWipeProgressBar (void) -{ - if (bHiddenOS && IsHiddenOSRunning()) - { - /* Decoy system partition wipe */ - - DecoySystemWipeStatus decoySysPartitionWipeStatus; - - try - { - decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); - BootEncStatus = BootEncObj->GetStatus(); - } - catch (...) - { - return; - } - - if (BootEncStatus.ConfiguredEncryptedAreaEnd == -1 - || BootEncStatus.ConfiguredEncryptedAreaStart == -1) - return; - - InitProgressBar (BootEncStatus.ConfiguredEncryptedAreaEnd - BootEncStatus.ConfiguredEncryptedAreaStart + 1, - (decoySysPartitionWipeStatus.WipedAreaEnd == BootEncStatus.ConfiguredEncryptedAreaStart || decoySysPartitionWipeStatus.WipedAreaEnd == -1) ? - 0 : decoySysPartitionWipeStatus.WipedAreaEnd - BootEncStatus.ConfiguredEncryptedAreaStart + 1, - FALSE, - TRUE, - FALSE, - TRUE); - } - else - { - /* Regular device wipe (not decoy system partition wipe) */ - } -} - - -static void UpdateWipeControls (void) -{ - if (bHiddenOS && IsHiddenOSRunning()) - { - /* Decoy system partition wipe */ - - DecoySystemWipeStatus decoySysPartitionWipeStatus; - - try - { - decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); - BootEncStatus = BootEncObj->GetStatus(); - } - catch (...) - { - return; - } - - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), !decoySysPartitionWipeStatus.WipeInProgress); - } - else - { - /* Regular device wipe (not decoy system partition wipe) */ - - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), bDeviceWipeInProgress); - - if (!bDeviceWipeInProgress) - { - SetWindowText (GetDlgItem (hCurPage, IDC_TIMEREMAIN), L" "); - } - } - - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), bDeviceWipeInProgress); - EnableWindow (GetDlgItem (MainDlg, IDC_PREV), !bDeviceWipeInProgress); - - bConfirmQuit = bDeviceWipeInProgress; -} - - - -static void __cdecl sysEncDriveAnalysisThread (void *hwndDlgArg) -{ - // Mark the detection process as 'in progress' - HiddenSectorDetectionStatus = 1; - SaveSettings (NULL); - BroadcastSysEncCfgUpdate (); - - try - { - BootEncObj->ProbeRealSystemDriveSize (); - bSysEncDriveAnalysisTimeOutOccurred = FALSE; - } - catch (TimeOut &) - { - bSysEncDriveAnalysisTimeOutOccurred = TRUE; - } - catch (Exception &e) - { - // There was a problem but the system did not freeze. Mark the detection process as completed. - HiddenSectorDetectionStatus = 0; - SaveSettings (NULL); - BroadcastSysEncCfgUpdate (); - - e.Show (NULL); - EndMainDlg (MainDlg); - exit(0); - } - - // Mark the detection process as completed - HiddenSectorDetectionStatus = 0; - SaveSettings (NULL); - BroadcastSysEncCfgUpdate (); - - // This artificial delay prevents user confusion on systems where the analysis ends almost instantly - Sleep (3000); - - bSysEncDriveAnalysisInProgress = FALSE; -} - -static void __cdecl volTransformThreadFunction (void *hwndDlgArg) -{ - int nStatus; - DWORD dwWin32FormatError; - BOOL bHidden; - HWND hwndDlg = (HWND) hwndDlgArg; - volatile FORMAT_VOL_PARAMETERS *volParams = (FORMAT_VOL_PARAMETERS *) malloc (sizeof(FORMAT_VOL_PARAMETERS)); - - if (volParams == NULL) - AbortProcess ("ERR_MEM_ALLOC"); - - VirtualLock ((LPVOID) volParams, sizeof(FORMAT_VOL_PARAMETERS)); - - bOperationSuccess = FALSE; - - if (bGuiMode) - { - bVolTransformThreadRunning = TRUE; - bVolTransformThreadToRun = FALSE; - } - - // Check administrator privileges - if (!IsAdmin () && !IsUacSupported ()) - { - if (fileSystem == FILESYS_NTFS || fileSystem == FILESYS_EXFAT) - { - if (Silent || (MessageBoxW (hwndDlg, GetString ("ADMIN_PRIVILEGES_WARN_NTFS"), lpszTitle, MB_OKCANCEL|MB_ICONWARNING|MB_DEFBUTTON2) == IDCANCEL)) - goto cancel; - } - if (bDevice) - { - if (Silent || (MessageBoxW (hwndDlg, GetString ("ADMIN_PRIVILEGES_WARN_DEVICES"), lpszTitle, MB_OKCANCEL|MB_ICONWARNING|MB_DEFBUTTON2) == IDCANCEL)) - goto cancel; - } - } - - if (!bInPlaceEncNonSys) - { - if (!bDevice) - { - int x = _waccess (szDiskFile, 06); - if (x == 0 || errno != ENOENT) - { - wchar_t szTmp[512]; - - if (!bForceOperation && !((bHiddenVol && !bHiddenVolHost) && errno != EACCES)) // Only ask ask for permission to overwrite an existing volume if we're not creating a hidden volume - { - StringCbPrintfW (szTmp, sizeof szTmp, - GetString (errno == EACCES ? "READONLYPROMPT" : "OVERWRITEPROMPT"), - szDiskFile); - - x = Silent? IDNO : MessageBoxW (hwndDlg, szTmp, lpszTitle, YES_NO|MB_ICONWARNING|MB_DEFBUTTON2); - - if (x != IDYES) - goto cancel; - } - } - - if (_waccess (szDiskFile, 06) != 0) - { - if (errno == EACCES) - { - if (_wchmod (szDiskFile, _S_IREAD | _S_IWRITE) != 0) - { - if (!Silent) MessageBoxW (hwndDlg, GetString ("ACCESSMODEFAIL"), lpszTitle, ICON_HAND); - goto cancel; - } - } - } - - } - else - { - // Partition / device / dynamic volume - - if (!FinalPreTransformPrompts ()) - goto cancel; - } - } - - // Prevent the OS from entering Sleep mode when idle - SetThreadExecutionState (ES_CONTINUOUS | ES_SYSTEM_REQUIRED); - - bHidden = bHiddenVol && !bHiddenVolHost; - - volParams->bDevice = bDevice; - volParams->hiddenVol = bHidden; - volParams->volumePath = szDiskFile; - volParams->size = nVolumeSize; - volParams->hiddenVolHostSize = nHiddenVolHostSize; - volParams->ea = nVolumeEA; - volParams->pkcs5 = hash_algo; - volParams->headerFlags = (CreatingHiddenSysVol() ? TC_HEADER_FLAG_ENCRYPTED_SYSTEM : 0); - volParams->fileSystem = fileSystem; - volParams->clusterSize = clusterSize; - volParams->sparseFileSwitch = bSparseFileSwitch; - volParams->quickFormat = quickFormat; - volParams->sectorSize = GetFormatSectorSize(); - volParams->realClusterSize = &realClusterSize; - volParams->password = &volumePassword; - volParams->pim = volumePim; - volParams->hwndDlg = hwndDlg; - volParams->bForceOperation = bForceOperation; - volParams->bGuiMode = bGuiMode; - - if (bInPlaceDecNonSys) - { - // In-place decryption of non-system volume - - if (!bInPlaceEncNonSysResumed) - DiscardUnreadableEncryptedSectors = FALSE; - - nStatus = DecryptPartitionInPlace (volParams, &DiscardUnreadableEncryptedSectors); - } - else if (bInPlaceEncNonSys) - { - // In-place encryption of non-system volume - - HANDLE hPartition = INVALID_HANDLE_VALUE; - - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PREPARING); - - if (!bInPlaceEncNonSysResumed) - { - bTryToCorrectReadErrors = FALSE; - - nStatus = EncryptPartitionInPlaceBegin (volParams, &hPartition, nWipeMode); - - if (nStatus == ERR_SUCCESS) - { - nStatus = EncryptPartitionInPlaceResume (hPartition, volParams, nWipeMode, &bTryToCorrectReadErrors); - } - else if (hPartition != INVALID_HANDLE_VALUE) - { - CloseHandle (hPartition); - hPartition = INVALID_HANDLE_VALUE; - } - } - else - { - nStatus = EncryptPartitionInPlaceResume (INVALID_HANDLE_VALUE, volParams, nWipeMode, &bTryToCorrectReadErrors); - } - } - else - { - // Format-encryption - - if (hwndDlg && bGuiMode) InitProgressBar (GetVolumeDataAreaSize (bHidden, nVolumeSize), 0, FALSE, FALSE, FALSE, TRUE); - - nStatus = TCFormatVolume (volParams); - } - - // Allow the OS to enter Sleep mode when idle - SetThreadExecutionState (ES_CONTINUOUS); - - if (nStatus == ERR_OUTOFMEMORY) - { - AbortProcess ("OUTOFMEMORY"); - } - - if (bInPlaceEncNonSys - && nStatus == ERR_USER_ABORT - && NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINISHED) - { - // Ignore user abort if non-system in-place encryption/decryption successfully finished - nStatus = ERR_SUCCESS; - } - - - dwWin32FormatError = GetLastError (); - - if (bHiddenVolHost && (!bGuiMode || !bVolTransformThreadCancel) && nStatus == 0) - { - /* Auto mount the newly created hidden volume host */ - switch (MountHiddenVolHost (hwndDlg, szDiskFile, &hiddenVolHostDriveNo, &volumePassword, hash_algo, volumePim, FALSE)) - { - case ERR_NO_FREE_DRIVES: - if (!Silent) MessageBoxW (hwndDlg, GetString ("NO_FREE_DRIVE_FOR_OUTER_VOL"), lpszTitle, ICON_HAND); - if (bGuiMode) bVolTransformThreadCancel = TRUE; - break; - case ERR_VOL_MOUNT_FAILED: - case ERR_PASSWORD_WRONG: - if (!Silent) MessageBoxW (hwndDlg, GetString ("CANT_MOUNT_OUTER_VOL"), lpszTitle, ICON_HAND); - if (bGuiMode) bVolTransformThreadCancel = TRUE; - break; - } - } - - SetLastError (dwWin32FormatError); - - if ((bVolTransformThreadCancel || nStatus == ERR_USER_ABORT) - && !(bInPlaceEncNonSys && NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINISHED)) // Ignore user abort if non-system in-place encryption/decryption successfully finished. - { - if (!bDevice && !(bHiddenVol && !bHiddenVolHost)) // If we're not creating a hidden volume and if it's a file container - { - _wremove (szDiskFile); // Delete the container - } - - goto cancel; - } - - if (nStatus != ERR_USER_ABORT) - { - if (nStatus != 0) - { - /* An error occurred */ - - wchar_t szMsg[8192]; - - handleError (hwndDlg, nStatus, SRC_POS); - - if (bInPlaceEncNonSys) - { - if (bInPlaceEncNonSysResumed) - { - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED); - Error ("INPLACE_ENC_GENERIC_ERR_RESUME", hwndDlg); - } - else - { - SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_ERROR); - - if (bInPlaceDecNonSys) - Error ("INPLACE_DEC_GENERIC_ERR", hwndDlg); - else - ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_GENERIC_ERR_ALT_STEPS", TRUE); - } - } - else if (!Silent && !(bHiddenVolHost && hiddenVolHostDriveNo < 0)) // If the error was not that the hidden volume host could not be mounted (this error has already been reported to the user) - { - StringCbPrintfW (szMsg, sizeof(szMsg), GetString ("CREATE_FAILED"), szDiskFile); - MessageBoxW (hwndDlg, szMsg, lpszTitle, ICON_HAND); - } - - if (!bDevice && !(bHiddenVol && !bHiddenVolHost)) // If we're not creating a hidden volume and if it's a file container - { - _wremove (szDiskFile); // Delete the container - } - - goto cancel; - } - else - { - /* Volume successfully created */ - - RestoreDefaultKeyFilesParam (); - - PimEnable = FALSE; - - bOperationSuccess = TRUE; - - if (bDevice && !bInPlaceEncNonSys) - { - // Handle assigned drive letter (if any) - - HandleOldAssignedDriveLetter (); - } - - if (!bHiddenVolHost) - { - if (bHiddenVol) - { - bHiddenVolFinished = TRUE; - - if (!bHiddenOS) - Warning ("HIDVOL_FORMAT_FINISHED_HELP", hwndDlg); - } - else if (bInPlaceEncNonSys) - { - if (!bInPlaceDecNonSys) - { - Warning ("NONSYS_INPLACE_ENC_FINISHED_INFO", hwndDlg); - - HandleOldAssignedDriveLetter (); - } - else - { - // NOP - Final steps for in-place decryption are handled with the TC_APPMSG_NONSYS_INPLACE_ENC_FINISHED message. - } - } - else - { - Info("FORMAT_FINISHED_INFO", hwndDlg); - - if (bSparseFileSwitch && quickFormat) - Warning("SPARSE_FILE_SIZE_NOTE", hwndDlg); - } - } - else - { - /* We've just created an outer volume (to host a hidden volume within) */ - - bHiddenVolHost = FALSE; - bHiddenVolFinished = FALSE; - nHiddenVolHostSize = nVolumeSize; - - // Clear the outer volume password - burn(&szVerify[0], sizeof (szVerify)); - burn(&szRawPassword[0], sizeof (szRawPassword)); - - if (!Silent) MessageBeep (MB_OK); - } - - if (!bInPlaceEncNonSys && hwndDlg && bGuiMode) - SetTimer (hwndDlg, TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL); - - - // volParams is ensured to be non NULL at this stage - burn ((LPVOID) volParams, sizeof(FORMAT_VOL_PARAMETERS)); - VirtualUnlock ((LPVOID) volParams, sizeof(FORMAT_VOL_PARAMETERS)); - free ((LPVOID) volParams); - volParams = NULL; - - if (bGuiMode) - { - bVolTransformThreadRunning = FALSE; - bVolTransformThreadCancel = FALSE; - } - - if (hwndDlg && bGuiMode) PostMessage (hwndDlg, bInPlaceEncNonSys ? TC_APPMSG_NONSYS_INPLACE_ENC_FINISHED : TC_APPMSG_FORMAT_FINISHED, 0, 0); - - LastDialogId = "FORMAT_FINISHED"; - if (bGuiMode) _endthread (); - } - } - -cancel: - - LastDialogId = (bInPlaceEncNonSys ? "NONSYS_INPLACE_ENC_CANCELED" : "FORMAT_CANCELED"); - - if (!bInPlaceEncNonSys && hwndDlg && bGuiMode) - SetTimer (hwndDlg, TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL); - - if (volParams != NULL) - { - burn ((LPVOID) volParams, sizeof(FORMAT_VOL_PARAMETERS)); - VirtualUnlock ((LPVOID) volParams, sizeof(FORMAT_VOL_PARAMETERS)); - free ((LPVOID) volParams); - volParams = NULL; - } - - if (bGuiMode) - { - bVolTransformThreadRunning = FALSE; - bVolTransformThreadCancel = FALSE; - } - - // Allow the OS to enter Sleep mode when idle - SetThreadExecutionState (ES_CONTINUOUS); - - if (hwndDlg) PostMessage (hwndDlg, TC_APPMSG_VOL_TRANSFORM_THREAD_ENDED, 0, 0); - - if (bHiddenVolHost && hiddenVolHostDriveNo < -1 && !bVolTransformThreadCancel) // If hidden volume host could not be mounted - AbortProcessSilent (); - - if (bGuiMode) _endthread (); -} - -static void LoadPage (HWND hwndDlg, int nPageNo) -{ - RECT rD, rW; - - nLastPageNo = nCurPageNo; - - if (hCurPage != NULL) - { - // WARNING: nCurPageNo must be set to a non-existent ID here before wiping the password fields below in - // this function, etc. Otherwise, such actions (SetWindowText) would invoke the EN_CHANGE handlers, which - // would, if keyfiles were applied, e.g. use strlen() on a buffer full of random data, in most cases - // not null-terminated. - nCurPageNo = -1; - - - // Place here any actions that need to be performed at the latest possible time when leaving a wizard page - // (i.e. right before "destroying" the page). Also, code that needs to be executed both on IDC_NEXT and - // on IDC_PREV can be placed here so as to avoid code doubling. - - switch (nLastPageNo) - { - case PASSWORD_PAGE: - { - wchar_t tmp[MAX_PASSWORD+1]; - - // Attempt to wipe passwords stored in the input field buffers. This is performed here (and - // not in the IDC_PREV or IDC_NEXT sections) in order to prevent certain race conditions - // when keyfiles are used. - wmemset (tmp, 'X', MAX_PASSWORD); - tmp [MAX_PASSWORD] = 0; - SetWindowText (hPasswordInputField, tmp); - SetWindowText (hVerifyPasswordInputField, tmp); - } - break; - } - - DestroyWindow (hCurPage); - hCurPage = NULL; - } - - // This prevents the mouse pointer from remaining as the "hand" cursor when the user presses Enter - // while hovering over a hyperlink. - bHyperLinkBeingTracked = FALSE; - NormalCursor(); - - GetWindowRect (GetDlgItem (hwndDlg, IDC_POS_BOX), &rW); - - - nCurPageNo = nPageNo; - - - switch (nPageNo) - { - case INTRO_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INTRO_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case SYSENC_TYPE_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_TYPE_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case SYSENC_HIDDEN_OS_REQ_CHECK_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_HIDDEN_OS_REQ_CHECK_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case SYSENC_SPAN_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_SPAN_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case SYSENC_PRE_DRIVE_ANALYSIS_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_UNIVERSAL_DUAL_CHOICE_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case SYSENC_DRIVE_ANALYSIS_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_DRIVE_ANALYSIS_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case SYSENC_MULTI_BOOT_MODE_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_MULTI_BOOT_MODE_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case SYSENC_MULTI_BOOT_SYS_EQ_BOOT_PAGE: - case SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE: - case SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE: - case SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_UNIVERSAL_DUAL_CHOICE_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case SYSENC_MULTI_BOOT_OUTCOME_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case VOLUME_TYPE_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_VOLUME_TYPE_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case HIDDEN_VOL_WIZARD_MODE_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_HIDDEN_VOL_WIZARD_MODE_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case VOLUME_LOCATION_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_VOLUME_LOCATION_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - - EnableWindow (GetDlgItem(hCurPage, IDC_NO_HISTORY), !bHistoryCmdLine); - - EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), - GetWindowTextLength (GetDlgItem (hCurPage, IDC_COMBO_BOX)) > 0); - - break; - - case DEVICE_TRANSFORM_MODE_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_DEVICE_TRANSFORM_MODE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case HIDDEN_VOL_HOST_PRE_CIPHER_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case HIDDEN_VOL_PRE_CIPHER_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case CIPHER_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_CIPHER_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case SIZE_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SIZE_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case HIDDEN_VOL_HOST_PASSWORD_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_PASSWORD_ENTRY_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case PASSWORD_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_PASSWORD_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case PIM_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_PIM_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case FILESYS_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_UNIVERSAL_DUAL_CHOICE_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case SYSENC_COLLECTING_RANDOM_DATA_PAGE: - case NONSYS_INPLACE_ENC_RAND_DATA_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_COLLECTING_RANDOM_DATA_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case SYSENC_KEYS_GEN_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_KEYS_GEN_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case SYSENC_RESCUE_DISK_CREATION_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_RESCUE_DISK_CREATION_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case SYSENC_RESCUE_DISK_BURN_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_RESCUE_DISK_BURN_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case SYSENC_RESCUE_DISK_VERIFIED_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case SYSENC_WIPE_MODE_PAGE: - case NONSYS_INPLACE_ENC_WIPE_MODE_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_WIPE_MODE_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case SYSENC_PRETEST_INFO_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case SYSENC_PRETEST_RESULT_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case SYSENC_ENCRYPTION_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INPLACE_ENCRYPTION_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_PASSWORD_ENTRY_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case NONSYS_INPLACE_ENC_RESUME_PARTITION_SEL_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_EXPANDED_LIST_SELECT_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case NONSYS_INPLACE_ENC_TRANSFORM_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INPLACE_ENCRYPTION_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case NONSYS_INPLACE_ENC_TRANSFORM_FINISHED_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case NONSYS_INPLACE_DEC_TRANSFORM_FINISHED_DRIVE_LETTER_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_DRIVE_LETTER_SELECTION_PAGE), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case FORMAT_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_FORMAT_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - case FORMAT_FINISHED_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW ((bHiddenVol && !bHiddenVolHost && !bHiddenVolFinished) ? IDD_HIDVOL_HOST_FILL_PAGE_DLG : IDD_INFO_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case SYSENC_HIDDEN_OS_INITIAL_INFO_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, (DLGPROC) PageDialogProc); - break; - - case SYSENC_HIDDEN_OS_WIPE_INFO_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, (DLGPROC) PageDialogProc); - break; - - case DEVICE_WIPE_MODE_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_DEVICE_WIPE_MODE_PAGE_DLG), hwndDlg, (DLGPROC) PageDialogProc); - break; - - case DEVICE_WIPE_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_DEVICE_WIPE_PAGE_DLG), hwndDlg, (DLGPROC) PageDialogProc); - break; - } - - rD.left = 162; - rD.top = 25; - rD.right = 0; - rD.bottom = 0; - MapDialogRect (hwndDlg, &rD); - - if (hCurPage != NULL) - { - MoveWindow (hCurPage, rD.left, rD.top, rW.right - rW.left, rW.bottom - rW.top, TRUE); - ShowWindow (hCurPage, SW_SHOWNORMAL); - - // Place here any message boxes that need to be displayed as soon as a new page is displayed. This - // ensures that the page is fully rendered (otherwise it would remain blank, until the message box - // is closed). - switch (nPageNo) - { - case PASSWORD_PAGE: - - CheckCapsLock (hwndDlg, FALSE); - - if (CreatingHiddenSysVol()) - Warning ("PASSWORD_HIDDEN_OS_NOTE", MainDlg); - - break; - - case CIPHER_PAGE: - - if (CreatingHiddenSysVol()) - Warning ("HIDDEN_OS_PRE_CIPHER_WARNING", MainDlg); - - break; - } - } -} - - -__int64 PrintFreeSpace (HWND hwndTextBox, wchar_t *lpszDrive, PLARGE_INTEGER lDiskFree) -{ - char *nResourceString; - __int64 nMultiplier; - wchar_t szTmp2[256]; - - if (lDiskFree->QuadPart < BYTES_PER_KB) - nMultiplier = 1; - else if (lDiskFree->QuadPart < BYTES_PER_MB) - nMultiplier = BYTES_PER_KB; - else if (lDiskFree->QuadPart < BYTES_PER_GB) - nMultiplier = BYTES_PER_MB; - else if (lDiskFree->QuadPart < BYTES_PER_TB) - nMultiplier = BYTES_PER_GB; - else - nMultiplier = BYTES_PER_TB; - - if (nMultiplier == 1) - { - if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume - nResourceString = "MAX_HIDVOL_SIZE_BYTES"; - else if (bDevice) - nResourceString = "DEVICE_FREE_BYTES"; - else - nResourceString = "DISK_FREE_BYTES"; - } - else if (nMultiplier == BYTES_PER_KB) - { - if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume - nResourceString = "MAX_HIDVOL_SIZE_KB"; - else if (bDevice) - nResourceString = "DEVICE_FREE_KB"; - else - nResourceString = "DISK_FREE_KB"; - } - else if (nMultiplier == BYTES_PER_MB) - { - if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume - nResourceString = "MAX_HIDVOL_SIZE_MB"; - else if (bDevice) - nResourceString = "DEVICE_FREE_MB"; - else - nResourceString = "DISK_FREE_MB"; - } - else if (nMultiplier == BYTES_PER_GB) - { - if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume - nResourceString = "MAX_HIDVOL_SIZE_GB"; - else if (bDevice) - nResourceString = "DEVICE_FREE_GB"; - else - nResourceString = "DISK_FREE_GB"; - } - else - { - if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume - nResourceString = "MAX_HIDVOL_SIZE_TB"; - else if (bDevice) - nResourceString = "DEVICE_FREE_TB"; - else - nResourceString = "DISK_FREE_TB"; - } - - if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume - { - StringCbPrintfW (szTmp2, sizeof szTmp2, GetString (nResourceString), ((double) lDiskFree->QuadPart) / nMultiplier); - SetWindowTextW (GetDlgItem (hwndTextBox, IDC_SIZEBOX), szTmp2); - } - else if (lpszDrive) - StringCbPrintfW (szTmp2, sizeof szTmp2, GetString (nResourceString), lpszDrive, ((double) lDiskFree->QuadPart) / nMultiplier); - else - szTmp2 [0] = 0; - - SetWindowTextW (hwndTextBox, szTmp2); - - if (lDiskFree->QuadPart % (__int64) BYTES_PER_MB != 0) - nMultiplier = BYTES_PER_KB; - - return nMultiplier; -} - -void DisplaySizingErrorText (HWND hwndTextBox) -{ - wchar_t szTmp[1024]; - - if (translateWin32Error (szTmp, sizeof (szTmp) / sizeof(szTmp[0]))) - { - wchar_t szTmp2[1024]; - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s\n%s", GetString ("CANNOT_CALC_SPACE"), szTmp); - SetWindowTextW (hwndTextBox, szTmp2); - } - else - { - SetWindowText (hwndTextBox, L""); - } -} - -void EnableDisableFileNext (HWND hComboBox, HWND hMainButton) -{ - int nIndex = (int) SendMessage (hComboBox, CB_GETCURSEL, 0, 0); - if (bHistory && nIndex == CB_ERR) - { - EnableWindow (hMainButton, FALSE); - SetFocus (hComboBox); - } - else - { - EnableWindow (hMainButton, TRUE); - SetFocus (hMainButton); - } -} - -// Returns TRUE if the file is a sparse file. If it's not a sparse file or in case of any error, returns FALSE. -BOOL IsSparseFile (HWND hwndDlg) -{ - HANDLE hFile; - BY_HANDLE_FILE_INFORMATION bhFileInfo; - - FILETIME ftLastAccessTime; - BOOL bTimeStampValid = FALSE; - - BOOL retCode = FALSE; - - hFile = CreateFile (szFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (hFile == INVALID_HANDLE_VALUE) - { - MessageBoxW (hwndDlg, GetString ("CANT_ACCESS_VOL"), lpszTitle, ICON_HAND); - return FALSE; - } - - if (bPreserveTimestamp) - { - if (GetFileTime (hFile, NULL, &ftLastAccessTime, NULL) == 0) - bTimeStampValid = FALSE; - else - bTimeStampValid = TRUE; - } - - bhFileInfo.dwFileAttributes = 0; - - GetFileInformationByHandle(hFile, &bhFileInfo); - - retCode = bhFileInfo.dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE; - - if (bTimeStampValid) - SetFileTime (hFile, NULL, &ftLastAccessTime, NULL); - - CloseHandle (hFile); - return retCode; -} - - -// Note: GetFileVolSize is not to be used for devices (only for file-hosted volumes) -BOOL GetFileVolSize (HWND hwndDlg, unsigned __int64 *size) -{ - LARGE_INTEGER fileSize; - HANDLE hFile; - - FILETIME ftLastAccessTime; - BOOL bTimeStampValid = FALSE; - - hFile = CreateFile (szFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (hFile == INVALID_HANDLE_VALUE) - { - MessageBoxW (hwndDlg, GetString ("CANT_ACCESS_VOL"), lpszTitle, ICON_HAND); - return FALSE; - } - - if (bPreserveTimestamp) - { - if (GetFileTime (hFile, NULL, &ftLastAccessTime, NULL) == 0) - bTimeStampValid = FALSE; - else - bTimeStampValid = TRUE; - } - - if (GetFileSizeEx(hFile, &fileSize) == 0) - { - MessageBoxW (hwndDlg, GetString ("CANT_GET_VOLSIZE"), lpszTitle, ICON_HAND); - - if (bTimeStampValid) - SetFileTime (hFile, NULL, &ftLastAccessTime, NULL); - - CloseHandle (hFile); - return FALSE; - } - - if (bTimeStampValid) - SetFileTime (hFile, NULL, &ftLastAccessTime, NULL); - - CloseHandle (hFile); - *size = fileSize.QuadPart; - return TRUE; -} - - -BOOL QueryFreeSpace (HWND hwndDlg, HWND hwndTextBox, BOOL display) -{ - if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume - { - LARGE_INTEGER lDiskFree; - - lDiskFree.QuadPart = nMaximumHiddenVolSize; - - if (display) - PrintFreeSpace (hwndTextBox, NULL, &lDiskFree); - - return TRUE; - } - else if (bDevice == FALSE) - { - wchar_t root[TC_MAX_PATH]; - ULARGE_INTEGER free; - - if (!GetVolumePathName (szFileName, root, ARRAYSIZE (root))) - { - handleWin32Error (hwndDlg, SRC_POS); - return FALSE; - } - - if (!GetDiskFreeSpaceEx (root, &free, 0, 0)) - { - if (display) - DisplaySizingErrorText (hwndTextBox); - - return FALSE; - } - else - { - LARGE_INTEGER lDiskFree; - lDiskFree.QuadPart = free.QuadPart; - - if (display) - PrintFreeSpace (hwndTextBox, root, &lDiskFree); - - return TRUE; - } - } - else - { - DISK_GEOMETRY driveInfo; - PARTITION_INFORMATION diskInfo; - BOOL piValid = FALSE; - BOOL gValid = FALSE; - - // Query partition size - piValid = GetPartitionInfo (szDiskFile, &diskInfo); - gValid = GetDriveGeometry (szDiskFile, &driveInfo); - - if (!piValid && !gValid) - { - if (display) - DisplaySizingErrorText (hwndTextBox); - - return FALSE; - } - - DWORD sectorSize = GetFormatSectorSize(); - - if (sectorSize < TC_MIN_VOLUME_SECTOR_SIZE - || sectorSize > TC_MAX_VOLUME_SECTOR_SIZE - || sectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0) - { - Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg); - return FALSE; - } - - if (piValid) - { - nVolumeSize = diskInfo.PartitionLength.QuadPart; - - if(display) - nMultiplier = PrintFreeSpace (hwndTextBox, szDiskFile, &diskInfo.PartitionLength); - - nUIVolumeSize = diskInfo.PartitionLength.QuadPart / nMultiplier; - - if (nVolumeSize == 0) - { - if (display) - SetWindowTextW (hwndTextBox, GetString ("EXT_PARTITION")); - - return FALSE; - } - } - else - { - LARGE_INTEGER lDiskFree; - - // Drive geometry info is used only when GetPartitionInfo() fails - lDiskFree.QuadPart = driveInfo.Cylinders.QuadPart * driveInfo.BytesPerSector * - driveInfo.SectorsPerTrack * driveInfo.TracksPerCylinder; - - nVolumeSize = lDiskFree.QuadPart; - - if (display) - nMultiplier = PrintFreeSpace (hwndTextBox, szDiskFile, &lDiskFree); - - nUIVolumeSize = lDiskFree.QuadPart / nMultiplier; - } - - return TRUE; - } -} - - -static BOOL FinalPreTransformPrompts (void) -{ - int x; - wchar_t szTmp[4096]; - int driveNo; - WCHAR deviceName[MAX_PATH]; - - StringCbCopyW (deviceName, sizeof(deviceName), szFileName); - - driveNo = GetDiskDeviceDriveLetter (deviceName); - - if (!bForceOperation && !(bHiddenVol && !bHiddenVolHost)) // Do not ask for permission to overwrite an existing volume if we're creating a hidden volume within it - { - wchar_t drive[128]; - wchar_t volumeLabel[128]; - wchar_t *type; - BOOL bTmpIsPartition = FALSE; - - type = GetPathType (szFileName, !bInPlaceEncNonSys, &bTmpIsPartition); - - if (driveNo != -1) - { - if (!GetDriveLabel (driveNo, volumeLabel, sizeof (volumeLabel))) - volumeLabel[0] = 0; - - StringCbPrintfW (drive, sizeof (drive), volumeLabel[0] ? L" (%hc: '%s')" : L" (%hc:%s)", 'A' + driveNo, volumeLabel[0] ? volumeLabel : L""); - } - else - { - drive[0] = 0; - volumeLabel[0] = 0; - } - - if (bHiddenOS && bHiddenVolHost) - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("OVERWRITEPROMPT_DEVICE_HIDDEN_OS_PARTITION"), szFileName, drive); - else - StringCbPrintfW (szTmp, sizeof(szTmp), GetString (bInPlaceEncNonSys ? (bInPlaceDecNonSys ? "NONSYS_INPLACE_DEC_CONFIRM" : "NONSYS_INPLACE_ENC_CONFIRM") : "OVERWRITEPROMPT_DEVICE"), type, szFileName, drive); - - if (bInPlaceEncNonSys) - x = AskWarnYesNoString (szTmp, MainDlg); - else - x = AskWarnNoYesString (szTmp, MainDlg); - - if (x != IDYES) - return FALSE; - - - if (driveNo != -1 && bTmpIsPartition && !bInPlaceEncNonSys) - { - float percentFreeSpace = 100.0; - __int64 occupiedBytes = 0; - - // Do a second check. If we find that the partition contains more than 1GB of data or more than 12% - // of its space is occupied, we will display an extra warning, however, this time it won't be a Yes/No - // dialog box (because users often ignore such dialog boxes). - - if (GetStatsFreeSpaceOnPartition (szFileName, &percentFreeSpace, &occupiedBytes, TRUE) != -1) - { - if (occupiedBytes > BYTES_PER_GB && percentFreeSpace < 99.99 // "percentFreeSpace < 99.99" is needed because an NTFS filesystem larger than several terabytes can have more than 1GB of data in use, even if there are no files stored on it. - || percentFreeSpace < 88) // A 24-MB NTFS filesystem has 11.5% of space in use even if there are no files stored on it. - { - wchar_t tmpMcMsg [8000]; - wchar_t tmpMcOption1 [500]; - wchar_t tmpMcOptionCancel [50]; - - StringCbCopyW (tmpMcMsg, sizeof(tmpMcMsg), GetString("OVERWRITEPROMPT_DEVICE_SECOND_WARNING_LOTS_OF_DATA")); - StringCbCopyW (tmpMcOption1, sizeof(tmpMcOption1), GetString("ERASE_FILES_BY_CREATING_VOLUME")); - StringCbCopyW (tmpMcOptionCancel, sizeof(tmpMcOptionCancel), GetString("CANCEL")); - - StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), L"\n\n"); - StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), GetString("DRIVE_LETTER_ITEM")); - StringCbPrintfW (szTmp, sizeof (szTmp), L"%hc:", 'A' + driveNo); - StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), szTmp); - - StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), L"\n"); - StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), GetString("LABEL_ITEM")); - StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), volumeLabel[0] != 0 ? volumeLabel : GetString("NOT_APPLICABLE_OR_NOT_AVAILABLE")); - - StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), L"\n"); - StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), GetString("SIZE_ITEM")); - GetSizeString (nVolumeSize, szTmp, sizeof(szTmp)); - StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), szTmp); - - StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), L"\n"); - StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), GetString("PATH_ITEM")); - StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), deviceName); - - wchar_t *tmpStr[] = {L"", tmpMcMsg, tmpMcOption1, tmpMcOptionCancel, 0}; - switch (AskMultiChoice ((void **) tmpStr, TRUE, MainDlg)) - { - case 1: - // Proceed - - // NOP - break; - - default: - return FALSE; - } - } - } - } - } - return TRUE; -} - -void UpdateLastDialogId (void) -{ - static char PageDebugId[128]; - - StringCbPrintfA (PageDebugId, sizeof(PageDebugId), "FORMAT_PAGE_%d", nCurPageNo); - LastDialogId = PageDebugId; -} - - -void HandleOldAssignedDriveLetter (void) -{ - if (bDevice) - { - // Handle assigned drive letter (if any) - - WCHAR deviceName[MAX_PATH]; - int driveLetter = -1; - - StringCbCopyW (deviceName, sizeof(deviceName), szDiskFile); - driveLetter = GetDiskDeviceDriveLetter (deviceName); - - if (!Silent && !bHiddenVolHost - && !bHiddenOS - && driveLetter >= 0) - { - wchar_t rootPath[] = { (wchar_t) driveLetter + L'A', L':', L'\\', 0 }; - wchar_t szTmp[8192]; - - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("AFTER_FORMAT_DRIVE_LETTER_WARN"), rootPath[0], rootPath[0], rootPath[0], rootPath[0]); - MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING); - } - } -} - - -// Returns TRUE if it makes sense to ask the user whether he wants to store files larger than 4GB in the volume. -static BOOL FileSize4GBLimitQuestionNeeded (void) -{ - uint64 dataAreaSize = GetVolumeDataAreaSize (bHiddenVol && !bHiddenVolHost, nVolumeSize); - - return (dataAreaSize > 4 * BYTES_PER_GB + TC_MIN_FAT_FS_SIZE - && dataAreaSize <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()); -} - - -/* Except in response to the WM_INITDIALOG message, the dialog box procedure - should return nonzero if it processes the message, and zero if it does - not. - see DialogProc */ -BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - WORD hw = HIWORD (wParam); - static BOOL PimValueChangedWarning = FALSE; - - hCurPage = hwndDlg; - - switch (uMsg) - { - case WM_INITDIALOG: - PimValueChangedWarning = FALSE; - LocalizeDialog (hwndDlg, "IDD_VOL_CREATION_WIZARD_DLG"); - - burn (randPool, sizeof(randPool)); - burn (lastRandPool, sizeof(lastRandPool)); - burn (maskRandPool, sizeof (maskRandPool)); - - UpdateLastDialogId (); - - switch (nCurPageNo) - { - case INTRO_PAGE: - - SendMessage (GetDlgItem (hwndDlg, IDC_FILE_CONTAINER), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_NONSYS_DEVICE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_SYS_DEVICE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("INTRO_TITLE")); - - ToHyperlink (hwndDlg, IDC_MORE_INFO_ON_CONTAINERS); - ToHyperlink (hwndDlg, IDC_MORE_INFO_ON_SYS_ENCRYPTION); - - EnableWindow (GetDlgItem (hwndDlg, IDC_STD_VOL), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_HIDDEN_VOL), TRUE); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - - UpdateWizardModeControls (hwndDlg, WizardMode); - break; - - case SYSENC_TYPE_PAGE: - - bHiddenVolHost = bHiddenVol = bHiddenOS; - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_TYPE_PAGE_TITLE")); - - SendMessage (GetDlgItem (hwndDlg, IDC_SYSENC_HIDDEN), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_SYSENC_NORMAL), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - - CheckButton (GetDlgItem (hwndDlg, bHiddenOS ? IDC_SYSENC_HIDDEN : IDC_SYSENC_NORMAL)); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_HIDDEN_TYPE_HELP")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP_SYSENC_NORMAL), GetString ("SYSENC_NORMAL_TYPE_HELP")); - - ToHyperlink (hwndDlg, IDC_HIDDEN_SYSENC_INFO_LINK); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), !bDirectSysEncMode); - - SetWindowTextW (GetDlgItem (MainDlg, IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (MainDlg, IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); - break; - - case SYSENC_HIDDEN_OS_REQ_CHECK_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_HIDDEN_OS_REQ_CHECK_PAGE_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_HIDDEN_OS_REQ_CHECK_PAGE_HELP")); - SetWindowTextW (GetDlgItem (MainDlg, IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (MainDlg, IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); - - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (MainDlg, IDC_PREV), bDirectSysEncModeCommand != SYSENC_COMMAND_CREATE_HIDDEN_OS && bDirectSysEncModeCommand != SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV); - - ToHyperlink (hwndDlg, IDC_HIDDEN_SYSENC_INFO_LINK); - break; - - case SYSENC_SPAN_PAGE: - - SendMessage (GetDlgItem (hwndDlg, IDC_WHOLE_SYS_DRIVE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_SYS_PARTITION), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYS_ENCRYPTION_SPAN_TITLE")); - - SetWindowTextW (GetDlgItem (hwndDlg, IDT_WHOLE_SYS_DRIVE), GetString ("SYS_ENCRYPTION_SPAN_WHOLE_SYS_DRIVE_HELP")); - - CheckButton (GetDlgItem (hwndDlg, bWholeSysDrive ? IDC_WHOLE_SYS_DRIVE : IDC_SYS_PARTITION)); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - break; - - - case SYSENC_PRE_DRIVE_ANALYSIS_PAGE: - - Init2RadButtonPageYesNo (SysEncDetectHiddenSectors); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_PRE_DRIVE_ANALYSIS_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_PRE_DRIVE_ANALYSIS_HELP")); - break; - - - case SYSENC_DRIVE_ANALYSIS_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_DRIVE_ANALYSIS_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDT_SYSENC_DRIVE_ANALYSIS_INFO), GetString ("SYSENC_DRIVE_ANALYSIS_INFO")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), FALSE); - EnableWindow (GetDlgItem (MainDlg, IDC_PREV), FALSE); - EnableWindow (GetDlgItem (MainDlg, IDCANCEL), FALSE); - - LoadSettings (hwndDlg); - - if (HiddenSectorDetectionStatus == 1) - { - // Detection of hidden sectors was already in progress but it did not finish successfully. - // Ask the user if he wants to try again (to prevent repeated system freezing, etc.) - - char *tmpStr[] = {0, "HIDDEN_SECTOR_DETECTION_FAILED_PREVIOUSLY", "SKIP_HIDDEN_SECTOR_DETECTION", "RETRY_HIDDEN_SECTOR_DETECTION", "IDC_EXIT", 0}; - switch (AskMultiChoice ((void **) tmpStr, FALSE, MainDlg)) - { - case 1: - // Do not try again - LoadPage (MainDlg, SYSENC_DRIVE_ANALYSIS_PAGE + 1); - return 0; - - case 2: - // Try again - break; - - default: - EndMainDlg (MainDlg); - return 0; - } - } - - SetTimer (MainDlg, TIMER_ID_SYSENC_DRIVE_ANALYSIS_PROGRESS, TIMER_INTERVAL_SYSENC_DRIVE_ANALYSIS_PROGRESS, NULL); - bSysEncDriveAnalysisInProgress = TRUE; - ArrowWaitCursor (); - SysEncDriveAnalysisStart = GetTickCount (); - InitProgressBar (SYSENC_DRIVE_ANALYSIS_ETA, 0, FALSE, FALSE, FALSE, TRUE); - - _beginthread (sysEncDriveAnalysisThread, 0, hwndDlg); - - break; - - - case SYSENC_MULTI_BOOT_MODE_PAGE: - - SendMessage (GetDlgItem (hwndDlg, IDC_SINGLE_BOOT), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_MULTI_BOOT), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYS_MULTI_BOOT_MODE_TITLE")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); - - RefreshMultiBootControls (hwndDlg); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), nMultiBoot > 0); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); - break; - - - case SYSENC_MULTI_BOOT_SYS_EQ_BOOT_PAGE: - - Init2RadButtonPageYesNo (SysEncMultiBootCfg.SystemOnBootDrive); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_MULTI_BOOT_SYS_EQ_BOOT_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_MULTI_BOOT_SYS_EQ_BOOT_HELP")); - break; - - - case SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE: - - SetWindowTextW (GetDlgItem (hCurPage, IDC_CHOICE1), GetString ("DIGIT_ONE")); - SetWindowTextW (GetDlgItem (hCurPage, IDC_CHOICE2), GetString ("TWO_OR_MORE")); - - SetWindowTextW (GetDlgItem (MainDlg, IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (MainDlg, IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); - - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), SysEncMultiBootCfg.NumberOfSysDrives > 0); - EnableWindow (GetDlgItem (MainDlg, IDC_PREV), TRUE); - - if (SysEncMultiBootCfg.NumberOfSysDrives == 2) - Update2RadButtonPage (0); // 2 or more drives contain an OS - else if (SysEncMultiBootCfg.NumberOfSysDrives == 1) - Update2RadButtonPage (1); // Only 1 drive contains an OS - else - Update2RadButtonPage (-1); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_HELP")); - break; - - - case SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE: - - Init2RadButtonPageYesNo (SysEncMultiBootCfg.MultipleSystemsOnDrive); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_MULTI_BOOT_ADJACENT_SYS_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_MULTI_BOOT_ADJACENT_SYS_HELP")); - break; - - - case SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE: - - Init2RadButtonPageYesNo (SysEncMultiBootCfg.BootLoaderBrand); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_HELP")); - break; - - - case SYSENC_MULTI_BOOT_OUTCOME_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_MULTI_BOOT_OUTCOME_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), SysEncMultiBootCfgOutcome); - SetWindowTextW (GetDlgItem (MainDlg, IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (MainDlg, IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (MainDlg, IDC_PREV), TRUE); - break; - - - case VOLUME_TYPE_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("VOLUME_TYPE_TITLE")); - - SendMessage (GetDlgItem (hwndDlg, IDC_HIDDEN_VOL), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_STD_VOL), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - - CheckButton (GetDlgItem (hwndDlg, bHiddenVol ? IDC_HIDDEN_VOL : IDC_STD_VOL)); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDDEN_VOLUME_TYPE_HELP")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP_NORMAL_VOL), GetString ("NORMAL_VOLUME_TYPE_HELP")); - - ToHyperlink (hwndDlg, IDC_HIDDEN_VOL_HELP); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - - SetWindowTextW (GetDlgItem (MainDlg, IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (MainDlg, IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); - break; - - case HIDDEN_VOL_WIZARD_MODE_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDDEN_VOL_WIZARD_MODE_TITLE")); - - SendMessage (GetDlgItem (hwndDlg, IDC_HIDVOL_WIZ_MODE_DIRECT), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_HIDVOL_WIZ_MODE_FULL), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - - CheckButton (GetDlgItem (hwndDlg, bHiddenVolDirect ? IDC_HIDVOL_WIZ_MODE_DIRECT : IDC_HIDVOL_WIZ_MODE_FULL)); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDDEN_VOL_WIZARD_MODE_NORMAL_HELP")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP2), GetString ("HIDDEN_VOL_WIZARD_MODE_DIRECT_HELP")); - - EnableWindow (GetDlgItem (hwndDlg, IDC_HIDVOL_WIZ_MODE_DIRECT), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_HIDVOL_WIZ_MODE_FULL), TRUE); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - - break; - - case VOLUME_LOCATION_PAGE: - { - char *nID; - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_SELECT_VOLUME_LOCATION), - GetString (bDevice ? "IDC_SELECT_DEVICE" : "IDC_SELECT_FILE")); - - if (bHiddenVolDirect && bHiddenVolHost) - { - nID = "FILE_HELP_HIDDEN_HOST_VOL_DIRECT"; - } - else - { - if (bDevice) - nID = bHiddenVolHost ? "DEVICE_HELP_HIDDEN_HOST_VOL" : "DEVICE_HELP"; - else - nID = bHiddenVolHost ? "FILE_HELP_HIDDEN_HOST_VOL" : "FILE_HELP"; - } - - SendMessage (GetDlgItem (hwndDlg, IDC_COMBO_BOX), CB_RESETCONTENT, 0, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_COMBO_BOX), CB_LIMITTEXT, TC_MAX_PATH, 0); - - LoadCombo (GetDlgItem (hwndDlg, IDC_COMBO_BOX), bHistory, FALSE, NULL); - - SendMessage (GetDlgItem (hwndDlg, IDC_NO_HISTORY), BM_SETCHECK, bHistory ? BST_UNCHECKED : BST_CHECKED, 0); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("FILE_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (nID)); - - SetFocus (GetDlgItem (hwndDlg, IDC_COMBO_BOX)); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - - AddComboItem (GetDlgItem (hwndDlg, IDC_COMBO_BOX), szFileName, bHistory); - - EnableDisableFileNext (GetDlgItem (hwndDlg, IDC_COMBO_BOX), - GetDlgItem (GetParent (hwndDlg), IDC_NEXT)); - - } - break; - - case DEVICE_TRANSFORM_MODE_PAGE: - - if (!bDeviceTransformModeChoiceMade && !bInPlaceEncNonSys) - { - // The user has not chosen whether to perform in-place encryption or format yet. - // We will preselect in-place encryption if the requirements are met and if the - // filesystem does not appear empty. - - WaitCursor(); - - if (CheckRequirementsForNonSysInPlaceEnc (hwndDlg, szDiskFile, TRUE)) - { - bInPlaceEncNonSys = (FileSystemAppearsEmpty (szDiskFile) == 0); - } - } - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("DEVICE_TRANSFORM_MODE_PAGE_TITLE")); - - SendMessage (GetDlgItem (hwndDlg, IDC_DEVICE_TRANSFORM_MODE_INPLACE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_DEVICE_TRANSFORM_MODE_FORMAT), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("DEVICE_TRANSFORM_MODE_PAGE_FORMAT_HELP")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP2), GetString ("DEVICE_TRANSFORM_MODE_PAGE_INPLACE_HELP")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - - CheckButton (GetDlgItem (hwndDlg, bInPlaceEncNonSys ? IDC_DEVICE_TRANSFORM_MODE_INPLACE : IDC_DEVICE_TRANSFORM_MODE_FORMAT)); - - NormalCursor(); - - break; - - case HIDDEN_VOL_HOST_PRE_CIPHER_PAGE: - { - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDVOL_HOST_PRE_CIPHER_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (bHiddenOS ? "HIDVOL_HOST_PRE_CIPHER_HELP_SYSENC" : "HIDVOL_HOST_PRE_CIPHER_HELP")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - - if (bHiddenOS) - { - if (!GetDevicePathForHiddenOS()) - AbortProcess ("INVALID_PATH"); - } - } - break; - - case HIDDEN_VOL_PRE_CIPHER_PAGE: - { - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDVOL_PRE_CIPHER_TITLE")); - - if (bHiddenOS) - { - // Verify whether the clone of the OS fits in the hidden volume (the hidden - // volume is to host a hidden OS). - if (nMaximumHiddenVolSize - TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH < GetSystemPartitionSize()) - { - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDDEN_VOLUME_TOO_SMALL_FOR_OS_CLONE")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("EXIT")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - - bConfirmQuit = FALSE; - bConfirmQuitSysEncPretest = FALSE; - } - else - { - // The hidden volume must be as large as the system partition - nVolumeSize = GetSystemPartitionSize() + TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH; - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDDEN_OS_PRE_CIPHER_HELP")); - } - } - else - { - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDVOL_PRE_CIPHER_HELP")); - } - } - break; - - case CIPHER_PAGE: - { - int ea, hid; - wchar_t buf[100]; - - // Encryption algorithms - - SendMessage (GetDlgItem (hwndDlg, IDC_COMBO_BOX), CB_RESETCONTENT, 0, 0); - - if (bHiddenVol) - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVolHost ? "CIPHER_HIDVOL_HOST_TITLE" : "CIPHER_HIDVOL_TITLE")); - else - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("CIPHER_TITLE")); - - for (ea = EAGetFirst (); ea != 0; ea = EAGetNext (ea)) - { - if (EAIsFormatEnabled (ea)) - AddComboPair (GetDlgItem (hwndDlg, IDC_COMBO_BOX), EAGetName (buf, ea, 1), ea); - } - - SelectAlgo (GetDlgItem (hwndDlg, IDC_COMBO_BOX), &nVolumeEA); - ComboSelChangeEA (hwndDlg); - SetFocus (GetDlgItem (hwndDlg, IDC_COMBO_BOX)); - - ToHyperlink (hwndDlg, IDC_LINK_MORE_INFO_ABOUT_CIPHER); - - // Hash algorithms - - if (SysEncInEffect ()) - { - hash_algo = DEFAULT_HASH_ALGORITHM_BOOT; - RandSetHashFunction (hash_algo); - - for (hid = FIRST_PRF_ID; hid <= LAST_PRF_ID; hid++) - { - // For now, we keep RIPEMD160 for system encryption - if (((hid == RIPEMD160) || !HashIsDeprecated (hid)) && HashForSystemEncryption (hid)) - AddComboPair (GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO), HashGetName(hid), hid); - } - } - else - { - hash_algo = RandGetHashFunction(); - for (hid = FIRST_PRF_ID; hid <= LAST_PRF_ID; hid++) - { - if (!HashIsDeprecated (hid)) - AddComboPair (GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO), HashGetName(hid), hid); - } - } - - SelectAlgo (GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO), &hash_algo); - - ToHyperlink (hwndDlg, IDC_LINK_HASH_INFO); - - // Wizard buttons - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - } - break; - - case SIZE_PAGE: - { - wchar_t str[1000]; - - if (bHiddenVolHost) - { - StringCbCopyW (str, sizeof(str), GetString ("SIZE_HELP_HIDDEN_HOST_VOL")); - } - else - { - StringCbCopyW (str, sizeof(str), GetString (bHiddenVol ? "SIZE_HELP_HIDDEN_VOL" : "SIZE_HELP")); - } - - if (bDevice && !(bHiddenVol && !bHiddenVolHost)) // If raw device but not a hidden volume - { - StringCbPrintfW (str, sizeof str, L"%s%s", - GetString ((bHiddenOS && bHiddenVol) ? "SIZE_PARTITION_HIDDEN_SYSENC_HELP" : "SIZE_PARTITION_HELP"), - (bHiddenVolHost && !bHiddenOS) ? GetString ("SIZE_PARTITION_HIDDEN_VOL_HELP") : L""); - } - - SendMessage (GetDlgItem (hwndDlg, IDC_SPACE_LEFT), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_SIZEBOX), EM_LIMITTEXT, 12, 0); - - if(!QueryFreeSpace (hwndDlg, GetDlgItem (hwndDlg, IDC_SPACE_LEFT), TRUE)) - { - nUIVolumeSize=0; - nVolumeSize=0; - SetWindowTextW (GetDlgItem (hwndDlg, IDC_SIZEBOX), GetString ("UNKNOWN")); - EnableWindow (GetDlgItem (hwndDlg, IDC_SIZEBOX), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_KB), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_MB), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_GB), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_TB), FALSE); - } - else if (bDevice && !(bHiddenVol && !bHiddenVolHost)) // If raw device but not a hidden volume - { - EnableWindow (GetDlgItem (hwndDlg, IDC_SIZEBOX), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_KB), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_MB), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_GB), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_TB), FALSE); - } - else - { - EnableWindow (GetDlgItem (hwndDlg, IDC_SIZEBOX), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_KB), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_MB), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_GB), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_TB), TRUE); - } - - SendMessage (GetDlgItem (hwndDlg, IDC_KB), BM_SETCHECK, BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_MB), BM_SETCHECK, BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_GB), BM_SETCHECK, BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_TB), BM_SETCHECK, BST_UNCHECKED, 0); - - switch (nMultiplier) - { - case BYTES_PER_KB: - SendMessage (GetDlgItem (hwndDlg, IDC_KB), BM_SETCHECK, BST_CHECKED, 0); - break; - case BYTES_PER_MB: - SendMessage (GetDlgItem (hwndDlg, IDC_MB), BM_SETCHECK, BST_CHECKED, 0); - break; - case BYTES_PER_GB: - SendMessage (GetDlgItem (hwndDlg, IDC_GB), BM_SETCHECK, BST_CHECKED, 0); - break; - case BYTES_PER_TB: - SendMessage (GetDlgItem (hwndDlg, IDC_TB), BM_SETCHECK, BST_CHECKED, 0); - break; - } - - if (nUIVolumeSize != 0) - { - wchar_t szTmp[32]; - StringCbPrintfW (szTmp, sizeof(szTmp), L"%I64u", nUIVolumeSize); - SetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTmp); - } - - SetFocus (GetDlgItem (hwndDlg, IDC_SIZEBOX)); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), str); - - if (bHiddenVol) - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVolHost ? "SIZE_HIDVOL_HOST_TITLE" : "SIZE_HIDVOL_TITLE")); - else - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SIZE_TITLE")); - - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - - VerifySizeAndUpdate (hwndDlg, FALSE); - } - break; - - case HIDDEN_VOL_HOST_PASSWORD_PAGE: - case NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE: - { - /* Populate the PRF algorithms list */ - int nIndex, i; - HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - - nIndex = (int) SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); - - for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) - { - nIndex = (int) SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); - } - - /* make autodetection the default */ - SendMessage (hComboBox, CB_SETCURSEL, 0, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD_DIRECT), EM_LIMITTEXT, MAX_PASSWORD, 0); - - SetPassword (hwndDlg, IDC_PASSWORD_DIRECT, szRawPassword); - - SetFocus (GetDlgItem (hwndDlg, IDC_PASSWORD_DIRECT)); - - SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, MAX_PIM, 0); - SetPim (hwndDlg, IDC_PIM, volumePim); - - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_ENABLE), PimEnable? SW_HIDE : SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), PimEnable? SW_SHOW : SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), PimEnable? SW_SHOW : SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), PimEnable? SW_SHOW : SW_HIDE); - - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (bInPlaceEncNonSys ? (bInPlaceEncNonSysResumed ? "NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE_HELP" : "NONSYS_INPLACE_DEC_PASSWORD_PAGE_HELP") : "PASSWORD_HIDDENVOL_HOST_DIRECT_HELP")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bInPlaceEncNonSys ? "PASSWORD" : "PASSWORD_HIDVOL_HOST_TITLE")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), !bInPlaceEncNonSys); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - } - - break; - - case PASSWORD_PAGE: - { - wchar_t str[1000]; - - hPasswordInputField = GetDlgItem (hwndDlg, IDC_PASSWORD); - hVerifyPasswordInputField = GetDlgItem (hwndDlg, IDC_VERIFY); - - if (SysEncInEffect ()) - { - ToBootPwdField (hwndDlg, IDC_PASSWORD); - ToBootPwdField (hwndDlg, IDC_VERIFY); - - StringCbPrintfW (OrigKeyboardLayout, sizeof(OrigKeyboardLayout), L"%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF); - - if ((DWORD) GetKeyboardLayout (NULL) != 0x00000409 && (DWORD) GetKeyboardLayout (NULL) != 0x04090409) - { - DWORD keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); - - if (keybLayout != 0x00000409 && keybLayout != 0x04090409) - { - Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", MainDlg); - EndMainDlg (MainDlg); - return 1; - } - bKeyboardLayoutChanged = TRUE; - } - - - if (SetTimer (MainDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0) - { - Error ("CANNOT_SET_TIMER", MainDlg); - EndMainDlg (MainDlg); - return 1; - } - } - - if (bHiddenVolHost) - { - StringCbCopyW (str, sizeof(str), GetString (bHiddenOS ? "PASSWORD_SYSENC_OUTERVOL_HELP" : "PASSWORD_HIDDENVOL_HOST_HELP")); - } - else if (bHiddenVol) - { - StringCbPrintfW (str, sizeof str, L"%s%s", - GetString (bHiddenOS ? "PASSWORD_HIDDEN_OS_HELP" : "PASSWORD_HIDDENVOL_HELP"), - GetString ("PASSWORD_HELP")); - } - else - { - StringCbCopyW (str, sizeof(str), GetString ("PASSWORD_HELP")); - } - - SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_VERIFY), EM_LIMITTEXT, MAX_PASSWORD, 0); - - SetPassword (hwndDlg, IDC_PASSWORD, szRawPassword); - SetPassword (hwndDlg, IDC_VERIFY, szVerify); - - SetFocus (GetDlgItem (hwndDlg, IDC_PASSWORD)); - - SetCheckBox (hwndDlg, IDC_PIM_ENABLE, PimEnable); - - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable && !SysEncInEffect()); - EnableWindow (GetDlgItem (hwndDlg, IDC_KEY_FILES), KeyFilesEnable); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), str); - - if (CreatingHiddenSysVol()) - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PASSWORD_HIDDEN_OS_TITLE")); - else if (bHiddenVol) - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVolHost ? "PASSWORD_HIDVOL_HOST_TITLE" : "PASSWORD_HIDVOL_TITLE")); - else if (WizardMode == WIZARD_MODE_SYS_DEVICE) - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PASSWORD")); - else - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PASSWORD_TITLE")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - - VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (GetParent (hwndDlg), IDC_NEXT), - GetDlgItem (hwndDlg, IDC_PASSWORD), - GetDlgItem (hwndDlg, IDC_VERIFY), - NULL, - NULL, - KeyFilesEnable && FirstKeyFile!=NULL && !SysEncInEffect()); - volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); - - } - break; - - case PIM_PAGE: - { - SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, SysEncInEffect()? MAX_BOOT_PIM: MAX_PIM, 0); - if (volumePim > 0) - { - SetPim (hwndDlg, IDC_PIM, volumePim); - - PimValueChangedWarning = TRUE; - SetDlgItemTextW (hwndDlg, IDC_PIM_HELP, GetString (SysEncInEffect ()? "PIM_SYSENC_CHANGE_WARNING" : "PIM_CHANGE_WARNING")); - } - - SetFocus (GetDlgItem (hwndDlg, IDC_PIM)); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (SysEncInEffect ()? "PIM_SYSENC_HELP" : "PIM_HELP")); - - ToHyperlink (hwndDlg, IDC_LINK_PIM_INFO); - - if (CreatingHiddenSysVol()) - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PIM_HIDDEN_OS_TITLE")); - else if (bHiddenVol) - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVolHost ? "PIM_HIDVOL_HOST_TITLE" : "PIM_HIDVOL_TITLE")); - else if (WizardMode == WIZARD_MODE_SYS_DEVICE) - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PIM")); - else - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PIM_TITLE")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - } - break; - - case FILESYS_PAGE: - { - wchar_t szTmp[8192]; - - Init2RadButtonPageYesNo (nNeedToStoreFilesOver4GB); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("FILESYS_PAGE_TITLE")); - - StringCbCopyW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_QUESTION")); - - if (bHiddenVolHost) - StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); - else - { - StringCbCatW (szTmp, sizeof(szTmp), L"\n\n\n"); - StringCbCatW (szTmp, sizeof(szTmp), GetString ("NOTE_BEGINNING")); - } - - StringCbCatW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_EXPLANATION")); - - if (bHiddenVolHost) - { - StringCbCatW (szTmp, sizeof(szTmp), L" "); - StringCbCatW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_EXPLANATION_HIDVOL")); - } - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), szTmp); - } - break; - - case SYSENC_COLLECTING_RANDOM_DATA_PAGE: - case NONSYS_INPLACE_ENC_RAND_DATA_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("COLLECTING_RANDOM_DATA_TITLE")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - - mouseEntropyGathered = 0xFFFFFFFF; - mouseEventsInitialCount = 0; - bUseMask = FALSE; - { - HCRYPTPROV hRngProv; - if (CryptAcquireContext (&hRngProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) - { - if (CryptGenRandom (hRngProv, sizeof (maskRandPool), maskRandPool)) - bUseMask = TRUE; - CryptReleaseContext (hRngProv, 0); - } - } - - SetTimer (GetParent (hwndDlg), TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL); - - hRandPoolSys = GetDlgItem (hwndDlg, IDC_SYS_POOL_CONTENTS); - hEntropyBar = GetDlgItem (hwndDlg, IDC_ENTROPY_BAR); - SendMessage (hEntropyBar, PBM_SETRANGE32, 0, maxEntropyLevel); - SendMessage (hEntropyBar, PBM_SETSTEP, 1, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_SYS_POOL_CONTENTS), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); - - SendMessage (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), BM_SETCHECK, showKeys ? BST_CHECKED : BST_UNCHECKED, 0); - - DisplayRandPool (hwndDlg, hRandPoolSys, showKeys); - - break; - - case SYSENC_KEYS_GEN_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("KEYS_GEN_TITLE")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - - hMasterKey = GetDlgItem (hwndDlg, IDC_DISK_KEY); - hHeaderKey = GetDlgItem (hwndDlg, IDC_HEADER_KEY); - - SendMessage (GetDlgItem (hwndDlg, IDC_DISK_KEY), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_HEADER_KEY), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); - - SendMessage (GetDlgItem (hwndDlg, IDC_DISPLAY_KEYS), BM_SETCHECK, showKeys ? BST_CHECKED : BST_UNCHECKED, 0); - - DisplayPortionsOfKeys (hHeaderKey, hMasterKey, HeaderKeyGUIView, MasterKeyGUIView, !showKeys); - - break; - - case SYSENC_RESCUE_DISK_CREATION_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("RESCUE_DISK")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (hwndDlg, IDT_RESCUE_DISK_INFO), GetString ("RESCUE_DISK_INFO")); - SetDlgItemText (hwndDlg, IDC_RESCUE_DISK_ISO_PATH, szRescueDiskISO); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), (GetWindowTextLength (GetDlgItem (hwndDlg, IDC_RESCUE_DISK_ISO_PATH)) > 1)); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - SetCheckBox (hCurPage, IDC_SKIP_RESCUE_VERIFICATION, bDontVerifyRescueDisk); - - break; - - case SYSENC_RESCUE_DISK_BURN_PAGE: - { - wchar_t szTmp[8192]; - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bDontVerifyRescueDisk ? "RESCUE_DISK_CREATED_TITLE" : "RESCUE_DISK_RECORDING_TITLE")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - StringCbPrintfW (szTmp, sizeof szTmp, - GetString (bDontVerifyRescueDisk ? "RESCUE_DISK_BURN_INFO_NO_CHECK" : "RESCUE_DISK_BURN_INFO"), - szRescueDiskISO, IsWindowsIsoBurnerAvailable() ? L"" : GetString ("RESCUE_DISK_BURN_INFO_NONWIN_ISO_BURNER")); - - SetWindowTextW (GetDlgItem (hwndDlg, IDT_RESCUE_DISK_BURN_INFO), szTmp); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - - /* The 'Back' button must be disabled now because the user could burn a Rescue Disk, then go back, and - generate a different master key, which would cause the Rescue Disk verification to fail (the result - would be confusion and bug reports). */ - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - - if (IsWindowsIsoBurnerAvailable()) - SetWindowTextW (GetDlgItem (hwndDlg, IDC_DOWNLOAD_CD_BURN_SOFTWARE), GetString ("LAUNCH_WIN_ISOBURN")); - - ToHyperlink (hwndDlg, IDC_DOWNLOAD_CD_BURN_SOFTWARE); - - if (IsWindowsIsoBurnerAvailable() && !bDontVerifyRescueDisk) - LaunchWindowsIsoBurner (hwndDlg, szRescueDiskISO); - } - break; - - case SYSENC_RESCUE_DISK_VERIFIED_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("RESCUE_DISK_DISK_VERIFIED_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("RESCUE_DISK_VERIFIED_INFO")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - - // Rescue Disk has been verified, no need to go back - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - - // Prevent losing the burned rescue disk by inadvertent exit - bConfirmQuit = TRUE; - - break; - - case SYSENC_WIPE_MODE_PAGE: - case NONSYS_INPLACE_ENC_WIPE_MODE_PAGE: - { - if (nWipeMode == TC_WIPE_1_RAND) - nWipeMode = TC_WIPE_NONE; - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("WIPE_MODE_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDT_WIPE_MODE_INFO), GetString ("INPLACE_ENC_WIPE_MODE_INFO")); - - PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), - SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING && !bInPlaceEncNonSys, - TRUE, - FALSE); - - SelectAlgo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), (int *) &nWipeMode); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - } - break; - - case SYSENC_PRETEST_INFO_PAGE: - - if (bHiddenOS) - { - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDDEN_OS_CREATION_PREINFO_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDDEN_OS_CREATION_PREINFO_HELP")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("START")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - } - else - { - wchar_t finalMsg[8024] = {0}; - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYS_ENCRYPTION_PRETEST_TITLE")); - - try - { - StringCbPrintfW (finalMsg, sizeof(finalMsg), - GetString ("SYS_ENCRYPTION_PRETEST_INFO"), - BootEncObj->GetSystemDriveConfiguration().DriveNumber); - } - catch (Exception &e) - { - e.Show (hwndDlg); - EndMainDlg (MainDlg); - return 0; - } - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), finalMsg); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("TEST")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - } - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - - break; - - case SYSENC_PRETEST_RESULT_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYS_ENCRYPTION_PRETEST_RESULT_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYS_ENCRYPTION_PRETEST_RESULT_INFO")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("ENCRYPT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("DEFER")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); - - break; - - case SYSENC_ENCRYPTION_PAGE: - - if (CreateSysEncMutex ()) - { - try - { - BootEncStatus = BootEncObj->GetStatus(); - bSystemEncryptionInProgress = BootEncStatus.SetupInProgress; - } - catch (Exception &e) - { - e.Show (hwndDlg); - Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); - EndMainDlg (MainDlg); - return 0; - } - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), - GetString (SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING ? "ENCRYPTION" : "DECRYPTION")); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_ENCRYPTION_PAGE_INFO")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("DEFER")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), - GetString (SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING ? "ENCRYPT" : "DECRYPT")); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_PAUSE), - GetString (bSystemEncryptionInProgress ? "IDC_PAUSE" : "RESUME")); - - EnableWindow (GetDlgItem (hwndDlg, IDC_PAUSE), BootEncStatus.DriveEncrypted); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), !BootEncStatus.SetupInProgress); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), TRUE); - - ToHyperlink (hwndDlg, IDC_MORE_INFO_SYS_ENCRYPTION); - - if (SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING) - { - nWipeMode = TC_WIPE_NONE; - EnableWindow (GetDlgItem (hwndDlg, IDC_WIPE_MODE), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_WIPE_MODE), FALSE); - PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), TRUE, TRUE, FALSE); - SelectAlgo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), (int *) &nWipeMode); - } - else - { - EnableWindow (GetDlgItem (hwndDlg, IDC_WIPE_MODE), !bSystemEncryptionInProgress); - PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), FALSE, TRUE, FALSE); - SelectAlgo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), (int *) &nWipeMode); - } - - PostMessage (hwndDlg, TC_APPMSG_PERFORM_POST_SYSENC_WMINIT_TASKS, 0, 0); - } - else - { - Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); - EndMainDlg (MainDlg); - return 0; - } - return 0; - - case NONSYS_INPLACE_ENC_RESUME_PARTITION_SEL_PAGE: - - { - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("FILE_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("NONSYS_INPLACE_ENC_RESUME_VOL_SELECT_HELP")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); - - foreach (const HostDevice &device, DeferredNonSysInPlaceEncDevices) - { - SendMessage (GetDlgItem (hwndDlg, IDC_LIST_BOX), LB_ADDSTRING, 0, (LPARAM) device.Path.c_str()); - } - - // Deselect all - SendMessage (GetDlgItem (hwndDlg, IDC_LIST_BOX), LB_SETCURSEL, (WPARAM) -1, 0); - } - - break; - - case NONSYS_INPLACE_ENC_TRANSFORM_PAGE: - - if (bInPlaceEncNonSysResumed) - { - WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE; - - if (LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) != 0) - nWipeMode = savedWipeAlgorithm; - } - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bInPlaceDecNonSys ? "DECRYPTION" : "ENCRYPTION")); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (bInPlaceDecNonSys ? "NONSYS_INPLACE_DEC_DECRYPTION_PAGE_INFO" : "NONSYS_INPLACE_ENC_ENCRYPTION_PAGE_INFO")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString (bInPlaceEncNonSysResumed ? "DEFER" : "CANCEL")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString (bInPlaceEncNonSysResumed ? "RESUME" : (bInPlaceDecNonSys ? "DECRYPT" : "ENCRYPT"))); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_PAUSE), GetString ("IDC_PAUSE")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), !bInPlaceEncNonSysResumed && !bInPlaceDecNonSys); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PAUSE), FALSE); - - ShowWindow (GetDlgItem (hwndDlg, IDC_MORE_INFO_SYS_ENCRYPTION), SW_HIDE); - - if (bInPlaceDecNonSys) - { - ShowWindow(GetDlgItem(hwndDlg, IDT_FORMAT_OPTIONS), SW_HIDE); - ShowWindow(GetDlgItem(hwndDlg, IDT_WIPE_MODE), SW_HIDE); - ShowWindow(GetDlgItem(hwndDlg, IDC_WIPE_MODE), SW_HIDE); - } - else - { - EnableWindow (GetDlgItem (hwndDlg, IDC_WIPE_MODE), TRUE); - PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), FALSE, TRUE, FALSE); - SelectAlgo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), (int *) &nWipeMode); - } - - break; - - case NONSYS_INPLACE_ENC_TRANSFORM_FINISHED_PAGE: - - bConfirmQuit = FALSE; - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bInPlaceDecNonSys ? "NONSYS_INPLACE_DEC_FINISHED_TITLE" : "NONSYS_INPLACE_ENC_FINISHED_TITLE")); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (bInPlaceDecNonSys ? "NONSYS_INPLACE_DEC_FINISHED_INFO" : "NONSYS_INPLACE_ENC_FINISHED_INFO")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("FINALIZE")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("EXIT")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), FALSE); - - break; - - case NONSYS_INPLACE_DEC_TRANSFORM_FINISHED_DRIVE_LETTER_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("NONSYS_INPLACE_DEC_FINISHED_TITLE")); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("NONSYS_INPLACE_DEC_FINISHED_DRIVE_LETTER_SEL_INFO")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("FINALIZE")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); - - // The Cancel button and the X button must be disabled to prevent the user from forgetting to assign a drive letter to the partition by closing - // the window accidentally or clicking Cancel. The user is forced to click Finish to assign at least the pre-selected free drive letter. - // This is critical because inexperienced users would not know how to access data on the decrypted volume without a drive letter. - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), FALSE); - DisableCloseButton (MainDlg); - bConfirmQuit = TRUE; // Alt-F4 will still work but the user will be prompted to confirm the action. - - // Decryption of non-system volume finished, no drive letter is assigned to the decrypted volume, and free drive letters are available. - // This is critical because inexperienced users would not know how to access data on the decrypted volume. We cannot allow exit - // until a drive letter is freed up and assigned to the decrypted volume. - - while (GetFirstAvailableDrive () == -1) - { - Error ("NONSYS_INPLACE_DEC_FINISHED_NO_DRIVE_LETTER_AVAILABLE", hwndDlg); - } - - // Populate the combobox with free drive letters - { - DWORD dwUsedDrives = GetUsedLogicalDrives(); - wchar_t szDriveLetter[] = {L' ', L':', 0 }; - int i; - - for (i = 0; i < 26; i++) - { - if (!(dwUsedDrives & 1 << i)) - { - // Add - szDriveLetter [0] = (wchar_t) (i + L'A'); - AddComboPair (GetDlgItem (hCurPage, IDC_DRIVE_LETTER_LIST), szDriveLetter, i); - } - } - } - SendMessage (GetDlgItem (hwndDlg, IDC_DRIVE_LETTER_LIST), CB_SETCURSEL, 0, 0); - break; - - case FORMAT_PAGE: - { - BOOL bNTFSallowed = FALSE; - BOOL bFATallowed = FALSE; - BOOL bEXFATallowed = FALSE; - BOOL bNoFSallowed = FALSE; - HCRYPTPROV hRngProv; - - mouseEntropyGathered = 0xFFFFFFFF; - mouseEventsInitialCount = 0; - bUseMask = FALSE; - if (CryptAcquireContext (&hRngProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) - { - if (CryptGenRandom (hRngProv, sizeof (maskRandPool), maskRandPool)) - bUseMask = TRUE; - CryptReleaseContext (hRngProv, 0); - } - - SetTimer (GetParent (hwndDlg), TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL); - - hMasterKey = GetDlgItem (hwndDlg, IDC_DISK_KEY); - hHeaderKey = GetDlgItem (hwndDlg, IDC_HEADER_KEY); - hRandPool = GetDlgItem (hwndDlg, IDC_RANDOM_BYTES); - hEntropyBar = GetDlgItem (hwndDlg, IDC_ENTROPY_BAR); - SendMessage (hEntropyBar, PBM_SETRANGE32, 0, maxEntropyLevel); - SendMessage (hEntropyBar, PBM_SETSTEP, 1, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_DISK_KEY), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_HEADER_KEY), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), - GetString (bHiddenVolHost ? "FORMAT_HIDVOL_HOST_HELP" : "FORMAT_HELP")); - - if (bHiddenVol) - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVolHost ? "FORMAT_HIDVOL_HOST_TITLE" : "FORMAT_HIDVOL_TITLE")); - else - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("FORMAT_TITLE")); - - /* Quick/Dynamic */ - - if (bHiddenVol) - { - quickFormat = !bHiddenVolHost; - bSparseFileSwitch = FALSE; - - SetCheckBox (hwndDlg, IDC_QUICKFORMAT, quickFormat); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_QUICKFORMAT), GetString ((bDevice || !bHiddenVolHost) ? "IDC_QUICKFORMAT" : "SPARSE_FILE")); - EnableWindow (GetDlgItem (hwndDlg, IDC_QUICKFORMAT), bDevice && bHiddenVolHost); - } - else - { - if (bDevice) - { - bSparseFileSwitch = FALSE; - SetWindowTextW (GetDlgItem (hwndDlg, IDC_QUICKFORMAT), GetString("IDC_QUICKFORMAT")); - EnableWindow (GetDlgItem (hwndDlg, IDC_QUICKFORMAT), TRUE); - } - else - { - wchar_t root[TC_MAX_PATH]; - DWORD fileSystemFlags = 0; - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_QUICKFORMAT), GetString("SPARSE_FILE")); - - /* Check if the host file system supports sparse files */ - - if (GetVolumePathName (szFileName, root, array_capacity (root))) - { - GetVolumeInformation (root, NULL, 0, NULL, NULL, &fileSystemFlags, NULL, 0); - bSparseFileSwitch = fileSystemFlags & FILE_SUPPORTS_SPARSE_FILES; - } - else - bSparseFileSwitch = FALSE; - - EnableWindow (GetDlgItem (hwndDlg, IDC_QUICKFORMAT), bSparseFileSwitch); - } - } - - SendMessage (GetDlgItem (hwndDlg, IDC_SHOW_KEYS), BM_SETCHECK, showKeys ? BST_CHECKED : BST_UNCHECKED, 0); - SetWindowText (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), showKeys ? L"" : L"******************************** "); - SetWindowText (GetDlgItem (hwndDlg, IDC_HEADER_KEY), showKeys ? L"" : L"******************************** "); - SetWindowText (GetDlgItem (hwndDlg, IDC_DISK_KEY), showKeys ? L"" : L"******************************** "); - - SendMessage (GetDlgItem (hwndDlg, IDC_CLUSTERSIZE), CB_RESETCONTENT, 0, 0); - AddComboPair (GetDlgItem (hwndDlg, IDC_CLUSTERSIZE), GetString ("DEFAULT"), 0); - - for (int i = 1; i <= 128; i *= 2) - { - wstringstream s; - DWORD size = GetFormatSectorSize() * i; - - if (size > TC_MAX_FAT_CLUSTER_SIZE) - break; - - if (size == 512) - s << L"0.5"; - else - s << size / BYTES_PER_KB; - - s << L" " << GetString ("KB"); - - AddComboPair (GetDlgItem (hwndDlg, IDC_CLUSTERSIZE), s.str().c_str(), i); - } - - SendMessage (GetDlgItem (hwndDlg, IDC_CLUSTERSIZE), CB_SETCURSEL, 0, 0); - - EnableWindow (GetDlgItem (hwndDlg, IDC_CLUSTERSIZE), TRUE); - - /* Filesystems */ - - bNTFSallowed = FALSE; - bFATallowed = FALSE; - bNoFSallowed = FALSE; - - SendMessage (GetDlgItem (hwndDlg, IDC_FILESYS), CB_RESETCONTENT, 0, 0); - - EnableWindow (GetDlgItem (hwndDlg, IDC_FILESYS), TRUE); - - uint64 dataAreaSize = GetVolumeDataAreaSize (bHiddenVol && !bHiddenVolHost, nVolumeSize); - - if (!CreatingHiddenSysVol()) - { - if (dataAreaSize >= TC_MIN_NTFS_FS_SIZE && dataAreaSize <= TC_MAX_NTFS_FS_SIZE) - { - AddComboPair (GetDlgItem (hwndDlg, IDC_FILESYS), L"NTFS", FILESYS_NTFS); - bNTFSallowed = TRUE; - } - - if (dataAreaSize >= TC_MIN_FAT_FS_SIZE && dataAreaSize <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()) - { - AddComboPair (GetDlgItem (hwndDlg, IDC_FILESYS), L"FAT", FILESYS_FAT); - bFATallowed = TRUE; - } - - //exFAT support added starting from Vista SP1 - if (IsOSVersionAtLeast (WIN_VISTA, 1) && dataAreaSize >= TC_MIN_EXFAT_FS_SIZE && dataAreaSize <= TC_MAX_EXFAT_FS_SIZE) - { - AddComboPair (GetDlgItem (hwndDlg, IDC_FILESYS), L"exFAT", FILESYS_EXFAT); - bEXFATallowed = TRUE; - } - } - else - { - // We're creating a hidden volume for a hidden OS, so we don't need to format it with - // any filesystem (the entire OS will be copied to the hidden volume sector by sector). - EnableWindow (GetDlgItem (hwndDlg, IDC_FILESYS), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_CLUSTERSIZE), FALSE); - } - - if (!bHiddenVolHost) - { - AddComboPair (GetDlgItem (hwndDlg, IDC_FILESYS), GetString ("NONE"), FILESYS_NONE); - bNoFSallowed = TRUE; - } - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - - if (fileSystem == FILESYS_NONE) // If no file system has been previously selected - { - // Set default file system - - if (bFATallowed && !(nNeedToStoreFilesOver4GB == 1 && (bNTFSallowed || bEXFATallowed))) - fileSystem = FILESYS_FAT; - else if (bEXFATallowed) - fileSystem = FILESYS_EXFAT; - else if (bNTFSallowed) - fileSystem = FILESYS_NTFS; - else if (bNoFSallowed) - fileSystem = FILESYS_NONE; - else - { - AddComboPair (GetDlgItem (hwndDlg, IDC_FILESYS), L"---", 0); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); - } - } - - SendMessage (GetDlgItem (hwndDlg, IDC_FILESYS), CB_SETCURSEL, 0, 0); - SelectAlgo (GetDlgItem (hwndDlg, IDC_FILESYS), (int *) &fileSystem); - - EnableWindow (GetDlgItem (hwndDlg, IDC_ABORT_BUTTON), FALSE); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("FORMAT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - - SetFocus (GetDlgItem (GetParent (hwndDlg), IDC_NEXT)); - } - break; - - case FORMAT_FINISHED_PAGE: - { - if (!bHiddenVolHost && bHiddenVol && !bHiddenVolFinished) - { - wchar_t msg[4096]; - - nNeedToStoreFilesOver4GB = -1; - - if (bHiddenOS) - { - wchar_t szMaxRecomOuterVolFillSize[100]; - - __int64 maxRecomOuterVolFillSize = 0; - - // Determine the maximum recommended total size of files that can be copied to the outer volume - // while leaving enough space for the hidden volume, which must contain a clone of the OS - - maxRecomOuterVolFillSize = nVolumeSize - GetSystemPartitionSize(); - - // -50% reserve for filesystem "peculiarities" - maxRecomOuterVolFillSize /= 2; - - StringCbPrintfW (szMaxRecomOuterVolFillSize, sizeof(szMaxRecomOuterVolFillSize), L"%I64d %s", maxRecomOuterVolFillSize / BYTES_PER_MB, GetString ("MB")); - - StringCbPrintfW (msg, sizeof(msg), GetString ("HIDVOL_HOST_FILLING_HELP_SYSENC"), hiddenVolHostDriveNo + 'A', szMaxRecomOuterVolFillSize); - } - else - StringCbPrintfW (msg, sizeof(msg), GetString ("HIDVOL_HOST_FILLING_HELP"), hiddenVolHostDriveNo + 'A'); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), msg); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDVOL_HOST_FILLING_TITLE")); - } - else - { - if (bHiddenOS) - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_HIDDEN_VOL_FORMAT_FINISHED_HELP")); - else - { - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (bInPlaceEncNonSys ? "NONSYS_INPLACE_ENC_FINISHED_INFO" : "FORMAT_FINISHED_HELP")); - bConfirmQuit = FALSE; - } - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVol ? "HIDVOL_FORMAT_FINISHED_TITLE" : "FORMAT_FINISHED_TITLE")); - } - - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), (!bHiddenVol || bHiddenVolFinished) && !bHiddenOS && !bInPlaceEncNonSys); - - if ((!bHiddenVol || bHiddenVolFinished) && !bHiddenOS) - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("EXIT")); - } - break; - - case SYSENC_HIDDEN_OS_INITIAL_INFO_PAGE: - - if (!IsHiddenOSRunning() || !bHiddenOS) - { - ReportUnexpectedState (SRC_POS); - EndMainDlg (MainDlg); - return 0; - } - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_HIDDEN_OS_INITIAL_INFO_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("FIRST_HIDDEN_OS_BOOT_INFO")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("DEFER")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); - break; - - case SYSENC_HIDDEN_OS_WIPE_INFO_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_HIDDEN_OS_WIPE_INFO_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_HIDDEN_OS_WIPE_INFO")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - - break; - - case DEVICE_WIPE_MODE_PAGE: - - if (nWipeMode == TC_WIPE_NONE) - nWipeMode = TC_WIPE_1_RAND; - - if (bHiddenOS && IsHiddenOSRunning()) - { - // Decoy system partition wipe - - WipeAbort(); // In case the GUI previously crashed and the driver is still wiping - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); - } - else - { - // Regular device wipe (not decoy system partition wipe) - - // Title bar - SetWindowText (MainDlg, _T(TC_APP_NAME)); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - } - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("WIPE_MODE_TITLE")); - SetWindowTextW (GetDlgItem (hwndDlg, IDT_WIPE_MODE_INFO), GetString ("WIPE_MODE_INFO")); - - PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), FALSE, FALSE, TRUE); - - SelectAlgo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), (int *) &nWipeMode); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); - - break; - - case DEVICE_WIPE_PAGE: - - if (bHiddenOS && IsHiddenOSRunning()) - { - // Decoy system partition wipe - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("DEVICE_WIPE_PAGE_INFO_HIDDEN_OS")); - } - else - { - // Regular device wipe (not decoy system partition wipe) - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("DEVICE_WIPE_PAGE_INFO")); - } - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("DEVICE_WIPE_PAGE_TITLE")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("WIPE")); - SetWindowTextW (GetDlgItem (hCurPage, IDC_WIPE_MODE), (wstring (L" ") + GetWipeModeName (nWipeMode)).c_str()); - - EnableWindow (GetDlgItem (hwndDlg, IDC_ABORT_BUTTON), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - - break; - } - return 0; - - case WM_HELP: - OpenPageHelp (GetParent (hwndDlg), nCurPageNo); - return 1; - - case TC_APPMSG_PERFORM_POST_SYSENC_WMINIT_TASKS: - AfterSysEncProgressWMInitTasks (hwndDlg); - return 1; - - case WM_CTLCOLORSTATIC: - { - if (PimValueChangedWarning && ((HWND)lParam == GetDlgItem(hwndDlg, IDC_PIM_HELP)) ) - { - // we're about to draw the static - // set the text colour in (HDC)lParam - SetBkMode((HDC)wParam,TRANSPARENT); - SetTextColor((HDC)wParam, RGB(255,0,0)); - // NOTE: per documentation as pointed out by selbie, GetSolidBrush would leak a GDI handle. - return (BOOL)GetSysColorBrush(COLOR_MENU); - } - } - return 0; - - case WM_COMMAND: - - if (nCurPageNo == INTRO_PAGE) - { - switch (lw) - { - case IDC_FILE_CONTAINER: - UpdateWizardModeControls (hwndDlg, WIZARD_MODE_FILE_CONTAINER); - return 1; - - case IDC_NONSYS_DEVICE: - UpdateWizardModeControls (hwndDlg, WIZARD_MODE_NONSYS_DEVICE); - return 1; - - case IDC_SYS_DEVICE: - UpdateWizardModeControls (hwndDlg, WIZARD_MODE_SYS_DEVICE); - return 1; - - case IDC_MORE_INFO_ON_CONTAINERS: - Applink ("introcontainer", TRUE, ""); - return 1; - - case IDC_MORE_INFO_ON_SYS_ENCRYPTION: - Applink ("introsysenc", TRUE, ""); - return 1; - } - } - - if (nCurPageNo == SYSENC_TYPE_PAGE) - { - switch (lw) - { - case IDC_SYSENC_HIDDEN: - bHiddenOS = TRUE; - bHiddenVol = TRUE; - bHiddenVolHost = TRUE; - return 1; - - case IDC_SYSENC_NORMAL: - bHiddenOS = FALSE; - bHiddenVol = FALSE; - bHiddenVolHost = FALSE; - return 1; - - case IDC_HIDDEN_SYSENC_INFO_LINK: - Applink ("hiddensysenc", TRUE, ""); - return 1; - } - } - - if (nCurPageNo == SYSENC_HIDDEN_OS_REQ_CHECK_PAGE && lw == IDC_HIDDEN_SYSENC_INFO_LINK) - { - Applink ("hiddensysenc", TRUE, ""); - return 1; - } - - if (nCurPageNo == SYSENC_SPAN_PAGE) - { - switch (lw) - { - case IDC_WHOLE_SYS_DRIVE: - bWholeSysDrive = TRUE; - return 1; - case IDC_SYS_PARTITION: - bWholeSysDrive = FALSE; - return 1; - } - - } - - if (nCurPageNo == SYSENC_MULTI_BOOT_MODE_PAGE) - { - switch (lw) - { - case IDC_SINGLE_BOOT: - nMultiBoot = 1; - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - return 1; - case IDC_MULTI_BOOT: - nMultiBoot = 2; - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - return 1; - } - } - - // Dual choice pages - switch (nCurPageNo) - { - case SYSENC_MULTI_BOOT_SYS_EQ_BOOT_PAGE: - case SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE: - case SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE: - case SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE: - case SYSENC_PRE_DRIVE_ANALYSIS_PAGE: - - if (lw == IDC_CHOICE1 || lw == IDC_CHOICE2) - { - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - return 1; - } - break; - } - - if (nCurPageNo == FILESYS_PAGE && (lw == IDC_CHOICE1 || lw == IDC_CHOICE2)) - { - if (bWarnOuterVolSuitableFileSys && lw == IDC_CHOICE1 && bHiddenVolHost) - { - wchar_t szTmp [4096]; - - bWarnOuterVolSuitableFileSys = FALSE; // Do not show this warning anymore (this also prevents potential endless repetition due to some race conditions) - - StringCbCopyW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_EXPLANATION_HIDVOL")); - StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); - StringCbCatW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_EXPLANATION_HIDVOL_CONFIRM")); - - if (MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2) == IDNO) - { - nNeedToStoreFilesOver4GB = 0; - Init2RadButtonPageYesNo (nNeedToStoreFilesOver4GB); - } - } - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - return 1; - } - - if (lw == IDC_HIDDEN_VOL && nCurPageNo == VOLUME_TYPE_PAGE) - { - bHiddenVol = TRUE; - bHiddenVolHost = TRUE; - bInPlaceEncNonSys = FALSE; - return 1; - } - - if (lw == IDC_STD_VOL && nCurPageNo == VOLUME_TYPE_PAGE) - { - bHiddenVol = FALSE; - bHiddenVolHost = FALSE; - return 1; - } - - if (nCurPageNo == SYSENC_ENCRYPTION_PAGE) - { - BootEncryptionStatus locBootEncStatus; - - switch (lw) - { - case IDC_PAUSE: - try - { - locBootEncStatus = BootEncObj->GetStatus(); - - if (locBootEncStatus.SetupInProgress) - SysEncPause (); - else - SysEncResume (); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - return 1; - - case IDC_WIPE_MODE: - if (hw == CBN_SELCHANGE) - { - nWipeMode = (WipeAlgorithmId) SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), - CB_GETITEMDATA, - SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), - 0); - - return 1; - } - break; - - case IDC_MORE_INFO_SYS_ENCRYPTION: - Applink ("sysencprogressinfo", TRUE, ""); - return 1; - } - } - - if (bInPlaceEncNonSys) - { - switch (nCurPageNo) - { - case NONSYS_INPLACE_ENC_RESUME_PARTITION_SEL_PAGE: - - if (lw == IDC_LIST_BOX - && (hw == LBN_SELCHANGE || hw == LBN_DBLCLK)) - { - BOOL tmpbDevice = FALSE; - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); - - int selPartitionItemId = (int) SendMessage (GetDlgItem (hwndDlg, IDC_LIST_BOX), LB_GETCURSEL, 0, 0); - - if (selPartitionItemId == LB_ERR) - { - // Deselect all - SendMessage (GetDlgItem (hwndDlg, IDC_LIST_BOX), LB_SETCURSEL, (WPARAM) -1, 0); - - SetFocus (GetDlgItem (MainDlg, IDC_NEXT)); - return 1; - } - - SetFocus (GetDlgItem (MainDlg, IDC_NEXT)); - - StringCbCopyW (szFileName, sizeof(szFileName), DeferredNonSysInPlaceEncDevices [selPartitionItemId].Path.c_str()); - CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice); - - nVolumeSize = GetDeviceSize (szDiskFile); - if (nVolumeSize == -1) - { - handleWin32Error (MainDlg, SRC_POS); - return 1; - } - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - - return 1; - } - break; - - case NONSYS_INPLACE_ENC_TRANSFORM_PAGE: - { - switch (lw) - { - case IDC_PAUSE: - - // Pause/resume non-system in-place encryption - - if (bVolTransformThreadRunning || bVolTransformThreadToRun) - { - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), FALSE); - NonSysInplaceEncPause (); - } - else - NonSysInplaceEncResume (); - - return 1; - - case IDC_WIPE_MODE: - if (hw == CBN_SELCHANGE) - { - nWipeMode = (WipeAlgorithmId) SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), - CB_GETITEMDATA, - SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), - 0); - - return 1; - } - break; - } - } - break; - } - } - - - if (lw == IDC_OPEN_OUTER_VOLUME && nCurPageNo == FORMAT_FINISHED_PAGE) - { - OpenVolumeExplorerWindow (hiddenVolHostDriveNo); - return 1; - } - - if (lw == IDC_HIDDEN_VOL_HELP && nCurPageNo == VOLUME_TYPE_PAGE) - { - Applink ("hiddenvolume", TRUE, ""); - return 1; - } - - if (lw == IDC_ABORT_BUTTON && nCurPageNo == FORMAT_PAGE) - { - if (MessageBoxW (hwndDlg, GetString ("FORMAT_ABORT"), lpszTitle, MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2 ) == IDYES) - bVolTransformThreadCancel = TRUE; - return 1; - } - - if (lw == IDC_CIPHER_TEST && nCurPageNo == CIPHER_PAGE) - { - LPARAM nIndex; - int c; - - nIndex = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETCURSEL, 0, 0); - nVolumeEA = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETITEMDATA, nIndex, 0); - - for (c = EAGetLastCipher (nVolumeEA); c != 0; c = EAGetPreviousCipher (nVolumeEA, c)) - { - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_CIPHER_TEST_DLG), - GetParent (hwndDlg), (DLGPROC) CipherTestDialogProc, (LPARAM) c); - } - return 1; - } - - if (lw == IDC_BENCHMARK && nCurPageNo == CIPHER_PAGE) - { - // Reduce CPU load - bFastPollEnabled = FALSE; - bRandmixEnabled = FALSE; - - DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_BENCHMARK_DLG), hwndDlg, - (DLGPROC) BenchmarkDlgProc, (LPARAM) NULL); - - bFastPollEnabled = TRUE; - bRandmixEnabled = TRUE; - - return 1; - } - - if (lw == IDC_LINK_MORE_INFO_ABOUT_CIPHER && nCurPageNo == CIPHER_PAGE) - { - wchar_t name[100]; - - int nIndex = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETCURSEL, 0, 0); - nIndex = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETITEMDATA, nIndex, 0); - EAGetName (name, nIndex, 0); - - if (wcscmp (name, L"AES") == 0) - Applink ("aes", FALSE, ""); - else if (wcscmp (name, L"Serpent") == 0) - Applink ("serpent", FALSE, ""); - else if (wcscmp (name, L"Twofish") == 0) - Applink ("twofish", FALSE, ""); - else if (EAGetCipherCount (nIndex) > 1) - Applink ("cascades", TRUE, ""); - - return 1; - } - - if (lw == IDC_LINK_HASH_INFO && nCurPageNo == CIPHER_PAGE) - { - Applink ("hashalgorithms", TRUE, ""); - return 1; - } - - if (lw == IDC_LINK_PIM_INFO && nCurPageNo == PIM_PAGE) - { - Applink ("pim", TRUE, ""); - return 1; - } - - if (hw == CBN_EDITCHANGE && nCurPageNo == VOLUME_LOCATION_PAGE) - { - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), - GetWindowTextLength (GetDlgItem (hCurPage, IDC_COMBO_BOX)) > 0); - - bDeviceTransformModeChoiceMade = FALSE; - bInPlaceEncNonSys = FALSE; - - return 1; - } - - if (hw == CBN_SELCHANGE && nCurPageNo == VOLUME_LOCATION_PAGE) - { - LPARAM nIndex; - - nIndex = MoveEditToCombo ((HWND) lParam, bHistory); - nIndex = UpdateComboOrder (GetDlgItem (hwndDlg, IDC_COMBO_BOX)); - - if (nIndex != CB_ERR) - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - else - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); - - bDeviceTransformModeChoiceMade = FALSE; - bInPlaceEncNonSys = FALSE; - - return 1; - } - - if (hw == EN_CHANGE && nCurPageNo == SIZE_PAGE) - { - VerifySizeAndUpdate (hwndDlg, FALSE); - return 1; - } - - if (hw == EN_CHANGE && nCurPageNo == PASSWORD_PAGE) - { - VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (GetParent (hwndDlg), IDC_NEXT), - GetDlgItem (hwndDlg, IDC_PASSWORD), - GetDlgItem (hwndDlg, IDC_VERIFY), - NULL, - NULL, - KeyFilesEnable && FirstKeyFile!=NULL && !SysEncInEffect()); - volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); - - return 1; - } - - if (hw == EN_CHANGE && nCurPageNo == PIM_PAGE) - { - if (lw == IDC_PIM) - { - if(GetPim (hwndDlg, IDC_PIM) != 0) - { - PimValueChangedWarning = TRUE; - SetDlgItemTextW (hwndDlg, IDC_PIM_HELP, GetString (SysEncInEffect ()? "PIM_SYSENC_CHANGE_WARNING" : "PIM_CHANGE_WARNING")); - } - else - { - PimValueChangedWarning = FALSE; - SetDlgItemTextW (hwndDlg, IDC_PIM_HELP, (wchar_t *) GetDictionaryValueByInt (IDC_PIM_HELP)); - } - } - - return 1; - } - - if (lw == IDC_SHOW_PASSWORD && nCurPageNo == PASSWORD_PAGE) - { - HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD, IDC_PASSWORD, IDC_VERIFY); - return 1; - } - - if (lw == IDC_SHOW_PIM && nCurPageNo == PIM_PAGE) - { - HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PIM, IDC_PIM, 0); - return 1; - } - - if (lw == IDC_PIM_ENABLE) - { - PimEnable = GetCheckBox (hwndDlg, IDC_PIM_ENABLE); - if (!PimEnable) - volumePim = 0; - if (nCurPageNo == HIDDEN_VOL_HOST_PASSWORD_PAGE - || nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE - ) - { - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_ENABLE), PimEnable? SW_HIDE : SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), PimEnable? SW_SHOW : SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), PimEnable? SW_SHOW : SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), PimEnable? SW_SHOW : SW_HIDE); - if (PimEnable) - { - SetFocus (GetDlgItem (hwndDlg, IDC_PIM)); - } - } - return 1; - } - - if (nCurPageNo == PASSWORD_PAGE - || nCurPageNo == HIDDEN_VOL_HOST_PASSWORD_PAGE - || nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) - { - if (lw == IDC_KEY_FILES) - { - if (SysEncInEffect()) - { - Warning ("KEYFILES_NOT_SUPPORTED_FOR_SYS_ENCRYPTION", MainDlg); - return 1; - } - - KeyFilesDlgParam param; - param.EnableKeyFiles = KeyFilesEnable; - param.FirstKeyFile = FirstKeyFile; - - if (IDOK == DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, - (DLGPROC) KeyFilesDlgProc, (LPARAM) ¶m)) - { - KeyFilesEnable = param.EnableKeyFiles; - FirstKeyFile = param.FirstKeyFile; - - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); - - if (nCurPageNo != HIDDEN_VOL_HOST_PASSWORD_PAGE && nCurPageNo != NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) - EnableWindow (GetDlgItem (hwndDlg, IDC_KEY_FILES), KeyFilesEnable); - - if (nCurPageNo != HIDDEN_VOL_HOST_PASSWORD_PAGE && nCurPageNo != NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) - { - VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (GetParent (hwndDlg), IDC_NEXT), - GetDlgItem (hCurPage, IDC_PASSWORD), - GetDlgItem (hCurPage, IDC_VERIFY), - volumePassword.Text, szVerify, KeyFilesEnable && FirstKeyFile!=NULL); - } - } - - return 1; - } - - if (lw == IDC_KEYFILES_ENABLE) - { - KeyFilesEnable = GetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE); - - if (nCurPageNo != HIDDEN_VOL_HOST_PASSWORD_PAGE && nCurPageNo != NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) - { - EnableWindow (GetDlgItem (hwndDlg, IDC_KEY_FILES), KeyFilesEnable); - - VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (GetParent (hwndDlg), IDC_NEXT), - GetDlgItem (hCurPage, IDC_PASSWORD), - GetDlgItem (hCurPage, IDC_VERIFY), - volumePassword.Text, szVerify, KeyFilesEnable && FirstKeyFile!=NULL); - } - - return 1; - } - } - - if (nCurPageNo == HIDDEN_VOL_HOST_PASSWORD_PAGE - || nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) - { - if (hw == EN_CHANGE) - { - GetPassword (hCurPage, IDC_PASSWORD_DIRECT, (char*) volumePassword.Text, MAX_PASSWORD + 1, FALSE); - volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); - return 1; - } - - if (lw == IDC_SHOW_PASSWORD_SINGLE) - { - HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD_SINGLE, IDC_PASSWORD_DIRECT, IDC_PIM); - return 1; - } - } - - if ((lw == IDC_KB || lw == IDC_MB || lw == IDC_GB || lw == IDC_TB) && nCurPageNo == SIZE_PAGE) - { - SendMessage (GetDlgItem (hwndDlg, IDC_KB), BM_SETCHECK, BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_MB), BM_SETCHECK, BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_GB), BM_SETCHECK, BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_TB), BM_SETCHECK, BST_UNCHECKED, 0); - - switch (lw) - { - case IDC_KB: - SendMessage (GetDlgItem (hwndDlg, IDC_KB), BM_SETCHECK, BST_CHECKED, 0); - break; - case IDC_MB: - SendMessage (GetDlgItem (hwndDlg, IDC_MB), BM_SETCHECK, BST_CHECKED, 0); - break; - case IDC_GB: - SendMessage (GetDlgItem (hwndDlg, IDC_GB), BM_SETCHECK, BST_CHECKED, 0); - break; - case IDC_TB: - SendMessage (GetDlgItem (hwndDlg, IDC_TB), BM_SETCHECK, BST_CHECKED, 0); - break; - } - - VerifySizeAndUpdate (hwndDlg, FALSE); - return 1; - } - - if (lw == IDC_HIDVOL_WIZ_MODE_DIRECT && nCurPageNo == HIDDEN_VOL_WIZARD_MODE_PAGE) - { - bHiddenVolDirect = TRUE; - return 1; - } - - if (lw == IDC_HIDVOL_WIZ_MODE_FULL && nCurPageNo == HIDDEN_VOL_WIZARD_MODE_PAGE) - { - bHiddenVolDirect = FALSE; - return 1; - } - - if (lw == IDC_SELECT_VOLUME_LOCATION && nCurPageNo == VOLUME_LOCATION_PAGE) - { - if (!bDevice) - { - // Select file - - if (BrowseFiles (hwndDlg, "OPEN_TITLE", szFileName, bHistory, !bHiddenVolDirect, NULL) == FALSE) - return 1; - - AddComboItem (GetDlgItem (hwndDlg, IDC_COMBO_BOX), szFileName, bHistory); - - EnableDisableFileNext (GetDlgItem (hwndDlg, IDC_COMBO_BOX), - GetDlgItem (GetParent (hwndDlg), IDC_NEXT)); - - return 1; - } - else - { - // Select device - RawDevicesDlgParam param; - param.pszFileName = szFileName; - INT_PTR nResult = DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_RAWDEVICES_DLG), GetParent (hwndDlg), - (DLGPROC) RawDevicesDlgProc, (LPARAM) & param); - - // Check administrator privileges - if (!wcsstr (szFileName, L"Floppy") && !IsAdmin() && !IsUacSupported ()) - MessageBoxW (hwndDlg, GetString ("ADMIN_PRIVILEGES_WARN_DEVICES"), lpszTitle, MB_OK|MB_ICONWARNING); - - if (nResult == IDOK && wcslen (szFileName) > 0) - { - AddComboItem (GetDlgItem (hwndDlg, IDC_COMBO_BOX), szFileName, bHistory); - - EnableDisableFileNext (GetDlgItem (hwndDlg, IDC_COMBO_BOX), - GetDlgItem (GetParent (hwndDlg), IDC_NEXT)); - - bDeviceTransformModeChoiceMade = FALSE; - bInPlaceEncNonSys = FALSE; - } - return 1; - } - } - - if (nCurPageNo == DEVICE_TRANSFORM_MODE_PAGE) - { - switch (lw) - { - case IDC_DEVICE_TRANSFORM_MODE_FORMAT: - - bInPlaceEncNonSys = FALSE; - bDeviceTransformModeChoiceMade = TRUE; - - return 1; - - case IDC_DEVICE_TRANSFORM_MODE_INPLACE: - - bInPlaceEncNonSys = TRUE; - bDeviceTransformModeChoiceMade = TRUE; - - bHiddenVol = FALSE; - bHiddenVolDirect = FALSE; - bHiddenVolHost = FALSE; - bSparseFileSwitch = FALSE; - quickFormat = FALSE; - - return 1; - } - } - - if (lw == IDC_HIDVOL_WIZ_MODE_FULL && nCurPageNo == HIDDEN_VOL_WIZARD_MODE_PAGE) - { - bHiddenVolDirect = FALSE; - return 1; - } - - if (hw == CBN_SELCHANGE && nCurPageNo == CIPHER_PAGE) - { - switch (lw) - { - case IDC_COMBO_BOX: - ComboSelChangeEA (hwndDlg); - break; - - case IDC_COMBO_BOX_HASH_ALGO: - if (SysEncInEffect ()) - { - HWND hHashAlgoItem = GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO); - int selectedAlgo = (int) SendMessage (hHashAlgoItem, CB_GETITEMDATA, SendMessage (hHashAlgoItem, CB_GETCURSEL, 0, 0), 0); - if (!HashForSystemEncryption(selectedAlgo)) - { - hash_algo = DEFAULT_HASH_ALGORITHM_BOOT; - RandSetHashFunction (DEFAULT_HASH_ALGORITHM_BOOT); - Info ("ALGO_NOT_SUPPORTED_FOR_SYS_ENCRYPTION", MainDlg); - SelectAlgo (GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO), &hash_algo); - } - } - break; - } - return 1; - - } - - if (lw == IDC_QUICKFORMAT && IsButtonChecked (GetDlgItem (hCurPage, IDC_QUICKFORMAT))) - { - if (bSparseFileSwitch) - { - if (AskWarnYesNo("CONFIRM_SPARSE_FILE", MainDlg) == IDNO) - SetCheckBox (hwndDlg, IDC_QUICKFORMAT, FALSE); - } - else - { - if (AskWarnYesNo("WARN_QUICK_FORMAT", MainDlg) == IDNO) - SetCheckBox (hwndDlg, IDC_QUICKFORMAT, FALSE); - } - return 1; - } - - if (lw == IDC_FILESYS && hw == CBN_SELCHANGE) - { - fileSystem = (int) SendMessage (GetDlgItem (hCurPage, IDC_FILESYS), CB_GETITEMDATA, - SendMessage (GetDlgItem (hCurPage, IDC_FILESYS), CB_GETCURSEL, 0, 0) , 0); - - return 1; - } - - if (lw == IDC_SHOW_KEYS && nCurPageNo == FORMAT_PAGE) - { - showKeys = IsButtonChecked (GetDlgItem (hCurPage, IDC_SHOW_KEYS)); - - SetWindowText (GetDlgItem (hCurPage, IDC_RANDOM_BYTES), showKeys ? L" " : L"******************************** "); - SetWindowText (GetDlgItem (hCurPage, IDC_HEADER_KEY), showKeys ? L"" : L"******************************** "); - SetWindowText (GetDlgItem (hCurPage, IDC_DISK_KEY), showKeys ? L"" : L"******************************** "); - return 1; - } - - if (lw == IDC_DISPLAY_POOL_CONTENTS - && (nCurPageNo == SYSENC_COLLECTING_RANDOM_DATA_PAGE || nCurPageNo == NONSYS_INPLACE_ENC_RAND_DATA_PAGE)) - { - showKeys = IsButtonChecked (GetDlgItem (hCurPage, IDC_DISPLAY_POOL_CONTENTS)); - DisplayRandPool (hwndDlg, hRandPoolSys, showKeys); - - return 1; - } - - if (lw == IDC_DISPLAY_KEYS && nCurPageNo == SYSENC_KEYS_GEN_PAGE) - { - showKeys = IsButtonChecked (GetDlgItem (hCurPage, IDC_DISPLAY_KEYS)); - - DisplayPortionsOfKeys (GetDlgItem (hwndDlg, IDC_HEADER_KEY), GetDlgItem (hwndDlg, IDC_DISK_KEY), HeaderKeyGUIView, MasterKeyGUIView, !showKeys); - return 1; - } - - if (nCurPageNo == SYSENC_RESCUE_DISK_CREATION_PAGE) - { - if (lw == IDC_BROWSE) - { - wchar_t tmpszRescueDiskISO [TC_MAX_PATH+1]; - - if (!BrowseFiles (hwndDlg, "OPEN_TITLE", tmpszRescueDiskISO, FALSE, TRUE, NULL)) - return 1; - - StringCbCopyW (szRescueDiskISO, sizeof(szRescueDiskISO), tmpszRescueDiskISO); - - SetDlgItemText (hwndDlg, IDC_RESCUE_DISK_ISO_PATH, szRescueDiskISO); - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), (GetWindowTextLength (GetDlgItem (hwndDlg, IDC_RESCUE_DISK_ISO_PATH)) > 1)); - return 1; - } - - if ( hw == EN_CHANGE ) - { - GetDlgItemText (hwndDlg, IDC_RESCUE_DISK_ISO_PATH, szRescueDiskISO, sizeof(szRescueDiskISO)); - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), (GetWindowTextLength (GetDlgItem (hwndDlg, IDC_RESCUE_DISK_ISO_PATH)) > 1)); - return 1; - } - } - - if (nCurPageNo == SYSENC_RESCUE_DISK_BURN_PAGE && lw == IDC_DOWNLOAD_CD_BURN_SOFTWARE) - { - if (IsWindowsIsoBurnerAvailable()) - LaunchWindowsIsoBurner (hwndDlg, szRescueDiskISO); - else - Applink ("isoburning", TRUE, ""); - - return 1; - } - - if ((nCurPageNo == SYSENC_WIPE_MODE_PAGE - || nCurPageNo == NONSYS_INPLACE_ENC_WIPE_MODE_PAGE - || nCurPageNo == DEVICE_WIPE_MODE_PAGE) - && hw == CBN_SELCHANGE) - { - nWipeMode = (WipeAlgorithmId) SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), - CB_GETITEMDATA, - SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), - 0); - - return 1; - } - - if (nCurPageNo == DEVICE_WIPE_PAGE) - { - switch (lw) - { - case IDC_ABORT_BUTTON: - - if (AskWarnNoYes ("CONFIRM_WIPE_ABORT", MainDlg) == IDYES) - WipeAbort(); - - return 1; - } - } - - if (lw == IDC_NO_HISTORY) - { - if (!(bHistory = !IsButtonChecked (GetDlgItem (hCurPage, IDC_NO_HISTORY)))) - ClearHistory (GetDlgItem (hCurPage, IDC_COMBO_BOX)); - - return 1; - } - - return 0; - } - - return 0; -} - -/* Except in response to the WM_INITDIALOG and WM_ENDSESSION messages, the dialog box procedure - should return nonzero if it processes the message, and zero if it does not. - see DialogProc */ -BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - - int nNewPageNo = nCurPageNo; - - switch (uMsg) - { - case WM_INITDIALOG: - { - MainDlg = hwndDlg; - InitDialog (hwndDlg); - LocalizeDialog (hwndDlg, "IDD_VOL_CREATION_WIZARD_DLG"); - - if (IsTrueCryptInstallerRunning()) - AbortProcess ("TC_INSTALLER_IS_RUNNING"); - - // Resize the bitmap if the user has a non-default DPI - if (ScreenDPI != USER_DEFAULT_SCREEN_DPI) - { - hbmWizardBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_WIZARD), - GetDlgItem (hwndDlg, IDC_BITMAP_WIZARD), - 0, 0, 0, 0, FALSE, FALSE); - } - - LoadSettings (hwndDlg); - - LoadDefaultKeyFilesParam (); - RestoreDefaultKeyFilesParam (); - - SysEncMultiBootCfg.NumberOfSysDrives = -1; - SysEncMultiBootCfg.MultipleSystemsOnDrive = -1; - SysEncMultiBootCfg.BootLoaderLocation = -1; - SysEncMultiBootCfg.BootLoaderBrand = -1; - SysEncMultiBootCfg.SystemOnBootDrive = -1; - - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (hwndDlg); - Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); - EndMainDlg (MainDlg); - return 0; - } - - SendMessageW (GetDlgItem (hwndDlg, IDC_BOX_TITLE), WM_SETFONT, (WPARAM) hTitleFont, (LPARAM) TRUE); - SetWindowTextW (hwndDlg, lpszTitle); - - ExtractCommandLine (hwndDlg, (wchar_t *) lParam); - - if (ComServerMode) - { - InitDialog (hwndDlg); - - if (!ComServerFormat ()) - { - handleWin32Error (hwndDlg, SRC_POS); - exit (1); - } - exit (0); - } - - if (DirectCreationMode) - { - wchar_t root[TC_MAX_PATH]; - DWORD fileSystemFlags = 0; - uint64 dataAreaSize; - wchar_t szFileSystemNameBuffer[256]; - ULARGE_INTEGER free; - - showKeys = FALSE; - bGuiMode = FALSE; - - if (CmdVolumePassword.Length == 0) - AbortProcess ("ERR_PASSWORD_MISSING"); - - if (CmdVolumeFileSize == 0) - AbortProcess ("ERR_SIZE_MISSING"); - - CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &bDevice); - - if (bDevice) - AbortProcess ("ERR_DEVICE_CLI_CREATE_NOT_SUPPORTED"); - - volumePassword = CmdVolumePassword; - volumePim = CmdVolumePim; - - if (CmdVolumeEA > 0) - nVolumeEA = CmdVolumeEA; - - if (CmdVolumePkcs5 > 0) - hash_algo = CmdVolumePkcs5; - - if (CmdVolumeFilesystem > 0) - fileSystem = CmdVolumeFilesystem; - else - fileSystem = FILESYS_NTFS; - - nVolumeSize = CmdVolumeFileSize; - - // correct volume size to be multiple of sector size - if (bDevice && !(bHiddenVol && !bHiddenVolHost)) // If raw device but not a hidden volume - { - // do nothing. no correction is needed - } - else - { - unsigned __int64 sectorSize = (unsigned __int64) GetFormatSectorSize(); - unsigned __int64 sectorSizeRem = nVolumeSize % sectorSize; - - if (sectorSizeRem != 0) - nVolumeSize = nVolumeSize + (sectorSize - sectorSizeRem); - } - - if (nVolumeSize < (bHiddenVolHost ? TC_MIN_HIDDEN_VOLUME_HOST_SIZE : (bHiddenVol ? TC_MIN_HIDDEN_VOLUME_SIZE : TC_MIN_VOLUME_SIZE))) - AbortProcess ("ERR_VOLUME_SIZE_TOO_SMALL"); - - if ( ((!bHiddenVolHost && bHiddenVol) && (nVolumeSize > nMaximumHiddenVolSize)) - || (nVolumeSize > (bHiddenVolHost ? TC_MAX_HIDDEN_VOLUME_HOST_SIZE : TC_MAX_VOLUME_SIZE)) - ) - { - AbortProcess ("ERR_VOLUME_SIZE_TOO_BIG"); - } - - if (!GetVolumePathName (szFileName, root, array_capacity (root))) - { - handleWin32Error (hwndDlg, SRC_POS); - exit (1); - } - - if (CmdSparseFileSwitch) - { - /* Check if the host file system supports sparse files */ - GetVolumeInformation (root, NULL, 0, NULL, NULL, &fileSystemFlags, NULL, 0); - bSparseFileSwitch = fileSystemFlags & FILE_SUPPORTS_SPARSE_FILES; - - if (!bSparseFileSwitch) - { - AbortProcess ("ERR_DYNAMIC_NOT_SUPPORTED"); - } - } - - quickFormat = TRUE; - - if (!GetDiskFreeSpaceEx (root, &free, 0, 0)) - { - wchar_t szTmp[1024]; - - if (translateWin32Error (szTmp, sizeof (szTmp) / sizeof(szTmp[0]))) - { - wchar_t szTmp2[1024]; - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s\n%s", GetString ("CANNOT_CALC_SPACE"), szTmp); - AbortProcessDirect (szTmp2); - } - else - { - handleWin32Error (hwndDlg, SRC_POS); - } - - exit (1); - } - else - { - if (!bSparseFileSwitch && (nVolumeSize > free.QuadPart)) - { - AbortProcess ("ERR_CONTAINER_SIZE_TOO_BIG"); - } - } - - dataAreaSize = GetVolumeDataAreaSize (bHiddenVol && !bHiddenVolHost, nVolumeSize); - - if ( (fileSystem == FILESYS_NTFS) && - (dataAreaSize < TC_MIN_NTFS_FS_SIZE || dataAreaSize > TC_MAX_NTFS_FS_SIZE) - ) - { - AbortProcess ("ERR_NTFS_INVALID_VOLUME_SIZE"); - } - - if ( (fileSystem == FILESYS_EXFAT) && - (dataAreaSize < TC_MIN_EXFAT_FS_SIZE || dataAreaSize > TC_MAX_EXFAT_FS_SIZE) - ) - { - AbortProcess ("ERR_EXFAT_INVALID_VOLUME_SIZE"); - } - - if ( (fileSystem == FILESYS_FAT) && - (dataAreaSize < TC_MIN_FAT_FS_SIZE || dataAreaSize > (TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize())) - ) - { - AbortProcess ("ERR_FAT_INVALID_VOLUME_SIZE"); - } - - /* Verify that the volume would not be too large for the host file system */ - if (GetVolumePathName (szDiskFile, root, ARRAYSIZE (root)) - && GetVolumeInformation (root, NULL, 0, NULL, NULL, NULL, szFileSystemNameBuffer, ARRAYSIZE(szFileSystemNameBuffer)) - && !wcsncmp (szFileSystemNameBuffer, L"FAT32", 5)) - { - // The host file system is FAT32 - if (nVolumeSize >= 4 * BYTES_PER_GB) - { - AbortProcess ("VOLUME_TOO_LARGE_FOR_FAT32"); - } - } - - /* Verify that the volume would not be too large for the operating system */ - if (!IsOSAtLeast (WIN_VISTA) - && nVolumeSize > 2 * BYTES_PER_TB) - { - AbortProcess ("VOLUME_TOO_LARGE_FOR_WINXP"); - } - - if (volumePassword.Length > 0) - { - // Check password length (check also done for outer volume which is not the case in TrueCrypt). - if (!CheckPasswordLength (NULL, volumePassword.Length, volumePim, FALSE, Silent, Silent)) - { - exit (1); - } - } - - volTransformThreadFunction (hwndDlg); - - exit (bOperationSuccess? 0 : 1); - } - - SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, 0, szRescueDiskISO); - StringCbCatW (szRescueDiskISO, sizeof(szRescueDiskISO), L"\\VeraCrypt Rescue Disk.iso"); - - if (IsOSAtLeast (WIN_VISTA)) - { - // Availability of in-place encryption (which is pre-selected by default whenever - // possible) makes partition-hosted volume creation safer. - bWarnDeviceFormatAdvanced = FALSE; - } - -#ifdef _DEBUG - // For faster testing - strcpy (szVerify, "q"); - strcpy (szRawPassword, "q"); -#endif - - PostMessage (hwndDlg, TC_APPMSG_PERFORM_POST_WMINIT_TASKS, 0, 0); - } - return 0; - - case WM_SYSCOMMAND: - if (lw == IDC_ABOUT) - { - DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_ABOUT_DLG), hwndDlg, (DLGPROC) AboutDlgProc); - return 1; - } - return 0; - - case WM_TIMER: - - switch (wParam) - { - case TIMER_ID_RANDVIEW: - - if (WizardMode == WIZARD_MODE_SYS_DEVICE - || bInPlaceEncNonSys) - { - DisplayRandPool (hwndDlg, hRandPoolSys, showKeys); - } - else - { - int partialLen = 16; - wchar_t tmp2[43]; - int i; - DWORD mouseEventsCounter; - - RandpeekBytes (hwndDlg, randPool, partialLen, &mouseEventsCounter); - - ProcessEntropyEstimate (hEntropyBar, &mouseEventsInitialCount, mouseEventsCounter, maxEntropyLevel, &mouseEntropyGathered); - - tmp2[0] = 0; - - for (i = 0; i < partialLen; i++) - { - wchar_t tmp3[3]; - if (showKeys) - { - StringCbPrintfW (tmp3, sizeof(tmp3), L"%02X", (int) randPool[i]); - } - else if (bUseMask) - { - unsigned char tmpByte = randPool[i] ^ maskRandPool[i]; - tmp3[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); - tmp3[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); - tmp3[2] = 0; - } - else - StringCbCopyW (tmp3, sizeof (tmp3), L"**"); - StringCbCatW (tmp2, sizeof(tmp2), tmp3); - } - - tmp2[32] = 0; - - SetWindowTextW (GetDlgItem (hCurPage, IDC_RANDOM_BYTES), (wstring (tmp2) + GetString ("TRIPLE_DOT_GLYPH_ELLIPSIS")).c_str()); - - burn (randPool, partialLen); - burn (tmp2, sizeof(tmp2)); - } - return 1; - - case TIMER_ID_SYSENC_PROGRESS: - { - // Manage system encryption/decryption and update related GUI - - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - KillTimer (MainDlg, TIMER_ID_SYSENC_PROGRESS); - - try - { - BootEncObj->AbortSetup (); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - - e.Show (hwndDlg); - Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); - EndMainDlg (MainDlg); - return 1; - } - - if (BootEncStatus.SetupInProgress) - UpdateSysEncProgressBar (); - - if (bSystemEncryptionInProgress != BootEncStatus.SetupInProgress) - { - bSystemEncryptionInProgress = BootEncStatus.SetupInProgress; - - UpdateSysEncProgressBar (); - UpdateSysEncControls (); - - if (!bSystemEncryptionInProgress) - { - // The driver stopped encrypting/decrypting - - // Allow the OS to enter Sleep mode when idle - SetThreadExecutionState (ES_CONTINUOUS); - - KillTimer (hwndDlg, TIMER_ID_SYSENC_PROGRESS); - - UpdateLastDialogId (); - - try - { - if (BootEncStatus.DriveMounted) // If we had been really encrypting/decrypting (not just proceeding to deinstall) - BootEncObj->CheckEncryptionSetupResult(); - } - catch (SystemException &e) - { - if (!bTryToCorrectReadErrors - && SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING - && (IsDiskReadError (e.ErrorCode))) - { - bTryToCorrectReadErrors = (AskWarnYesNo ("ENABLE_BAD_SECTOR_ZEROING", MainDlg) == IDYES); - - if (bTryToCorrectReadErrors) - { - SysEncResume(); - return 1; - } - } - else if (!DiscardUnreadableEncryptedSectors - && SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING - && (IsDiskReadError (e.ErrorCode))) - { - DiscardUnreadableEncryptedSectors = (AskWarnYesNo ("DISCARD_UNREADABLE_ENCRYPTED_SECTORS", MainDlg) == IDYES); - - if (DiscardUnreadableEncryptedSectors) - { - SysEncResume(); - return 1; - } - } - - e.Show (hwndDlg); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - - switch (SystemEncryptionStatus) - { - case SYSENC_STATUS_ENCRYPTING: - - if (BootEncStatus.ConfiguredEncryptedAreaStart == BootEncStatus.EncryptedAreaStart - && BootEncStatus.ConfiguredEncryptedAreaEnd == BootEncStatus.EncryptedAreaEnd) - { - // The partition/drive has been fully encrypted - - ManageStartupSeqWiz (TRUE, L""); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_NEXT), GetString ("FINALIZE")); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE); - EnableWindow (GetDlgItem (hCurPage, IDC_WIPE_MODE), FALSE); - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), FALSE); - - WipeHiddenOSCreationConfig(); // For extra conservative security - - ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); - - Info ("SYSTEM_ENCRYPTION_FINISHED", MainDlg); - return 1; - } - break; - - case SYSENC_STATUS_DECRYPTING: - - if (!BootEncStatus.DriveEncrypted) - { - // The partition/drive has been fully decrypted - - try - { - // Finalize the process - BootEncObj->Deinstall (); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - - ManageStartupSeqWiz (TRUE, L""); - ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_NEXT), GetString ("FINALIZE")); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE); - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), FALSE); - - Info ("SYSTEM_DECRYPTION_FINISHED", MainDlg); - - // Reboot is required to enable uninstallation and hibernation - if (AskWarnYesNo ("CONFIRM_RESTART", MainDlg) == IDYES) - { - EndMainDlg (MainDlg); - - try - { - BootEncObj->RestartComputer(); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - } - - return 1; - } - break; - } - } - } - } - return 1; - - case TIMER_ID_NONSYS_INPLACE_ENC_PROGRESS: - - if (bInPlaceEncNonSys) - { - // Non-system in-place encryption - - if (!bVolTransformThreadRunning && !bVolTransformThreadToRun) - { - KillTimer (hwndDlg, TIMER_ID_NONSYS_INPLACE_ENC_PROGRESS); - - UpdateLastDialogId (); - } - - UpdateNonSysInPlaceEncControls (); - } - return 1; - - case TIMER_ID_KEYB_LAYOUT_GUARD: - if (SysEncInEffect ()) - { - DWORD keybLayout = (DWORD) GetKeyboardLayout (NULL); - - /* Watch the keyboard layout */ - - if (keybLayout != 0x00000409 && keybLayout != 0x04090409) - { - // Keyboard layout is not standard US - - WipePasswordsAndKeyfiles (); - - SetPassword (hCurPage, IDC_PASSWORD, szRawPassword); - SetPassword (hCurPage, IDC_VERIFY, szVerify); - - keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); - - if (keybLayout != 0x00000409 && keybLayout != 0x04090409) - { - KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); - Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", MainDlg); - EndMainDlg (MainDlg); - return 1; - } - - bKeyboardLayoutChanged = TRUE; - - wchar_t szTmp [4096]; - StringCbCopyW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_CHANGE_PREVENTED")); - StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); - StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION")); - MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); - } - - /* Watch the right Alt key (which is used to enter various characters on non-US keyboards) */ - - if (bKeyboardLayoutChanged && !bKeybLayoutAltKeyWarningShown) - { - if (GetAsyncKeyState (VK_RMENU) < 0) - { - bKeybLayoutAltKeyWarningShown = TRUE; - - wchar_t szTmp [4096]; - StringCbCopyW (szTmp, sizeof(szTmp), GetString ("ALT_KEY_CHARS_NOT_FOR_SYS_ENCRYPTION")); - StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); - StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION")); - MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TOPMOST); - } - } - } - return 1; - - case TIMER_ID_SYSENC_DRIVE_ANALYSIS_PROGRESS: - - if (bSysEncDriveAnalysisInProgress) - { - UpdateProgressBarProc (GetTickCount() - SysEncDriveAnalysisStart); - - if (GetTickCount() - SysEncDriveAnalysisStart > SYSENC_DRIVE_ANALYSIS_ETA) - { - // It's taking longer than expected -- reinit the progress bar - SysEncDriveAnalysisStart = GetTickCount (); - InitProgressBar (SYSENC_DRIVE_ANALYSIS_ETA, 0, FALSE, FALSE, FALSE, TRUE); - } - - ArrowWaitCursor (); - } - else - { - KillTimer (hwndDlg, TIMER_ID_SYSENC_DRIVE_ANALYSIS_PROGRESS); - UpdateProgressBarProc (SYSENC_DRIVE_ANALYSIS_ETA); - Sleep (1500); // User-friendly GUI - - if (bSysEncDriveAnalysisTimeOutOccurred) - Warning ("SYS_DRIVE_SIZE_PROBE_TIMEOUT", MainDlg); - - LoadPage (hwndDlg, SYSENC_DRIVE_ANALYSIS_PAGE + 1); - } - return 1; - - case TIMER_ID_WIPE_PROGRESS: - - // Manage device wipe and update related GUI - - if (bHiddenOS && IsHiddenOSRunning()) - { - // Decoy system partition wipe - - DecoySystemWipeStatus decoySysPartitionWipeStatus; - - try - { - decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - KillTimer (MainDlg, TIMER_ID_WIPE_PROGRESS); - - try - { - BootEncObj->AbortDecoyOSWipe (); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - - e.Show (hwndDlg); - EndMainDlg (MainDlg); - return 1; - } - - if (decoySysPartitionWipeStatus.WipeInProgress) - { - ArrowWaitCursor (); - - UpdateWipeProgressBar (); - } - - if (bDeviceWipeInProgress != decoySysPartitionWipeStatus.WipeInProgress) - { - bDeviceWipeInProgress = decoySysPartitionWipeStatus.WipeInProgress; - - UpdateWipeProgressBar (); - UpdateWipeControls (); - - if (!bDeviceWipeInProgress) - { - // The driver stopped wiping - - KillTimer (hwndDlg, TIMER_ID_WIPE_PROGRESS); - UpdateLastDialogId (); - - try - { - BootEncObj->CheckDecoyOSWipeResult(); - } - catch (Exception &e) - { - e.Show (hwndDlg); - AbortProcessSilent(); - } - - if (BootEncStatus.ConfiguredEncryptedAreaEnd == decoySysPartitionWipeStatus.WipedAreaEnd) - { - // Decoy system partition has been fully wiped - - ChangeHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_WIPED); - - SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("EXIT")); - EnableWindow (GetDlgItem (MainDlg, IDCANCEL), TRUE); - EnableWindow (GetDlgItem (MainDlg, IDC_PREV), FALSE); - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), FALSE); - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), FALSE); - - Info ("WIPE_FINISHED_DECOY_SYSTEM_PARTITION", MainDlg); - - TextInfoDialogBox (TC_TBXID_DECOY_OS_INSTRUCTIONS); - - if (BootEncObj->GetSystemDriveConfiguration().ExtraBootPartitionPresent) - Warning ("DECOY_OS_VERSION_WARNING", MainDlg); - - return 1; - } - } - } - } - else - { - // Regular device wipe (not decoy system partition wipe) - - //Info ("WIPE_FINISHED"); - } - return 1; - } - - return 0; - - - case TC_APPMSG_PERFORM_POST_WMINIT_TASKS: - - AfterWMInitTasks (hwndDlg); - return 1; - - case TC_APPMSG_FORMAT_FINISHED: - { - wchar_t tmp[RNG_POOL_SIZE*2+1]; - - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDHELP), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), TRUE); - SetFocus (GetDlgItem (hwndDlg, IDC_NEXT)); - - if (nCurPageNo == FORMAT_PAGE) - KillTimer (hwndDlg, TIMER_ID_RANDVIEW); - - // Attempt to wipe the GUI fields showing portions of randpool, of the master and header keys - wmemset (tmp, 'X', ARRAYSIZE(tmp)); - tmp [ARRAYSIZE(tmp)-1] = 0; - SetWindowText (hRandPool, tmp); - SetWindowText (hMasterKey, tmp); - SetWindowText (hHeaderKey, tmp); - - LoadPage (hwndDlg, FORMAT_FINISHED_PAGE); - } - return 1; - - case TC_APPMSG_NONSYS_INPLACE_ENC_FINISHED: - - // A partition has just been fully encrypted in place - - KillTimer (hwndDlg, TIMER_ID_NONSYS_INPLACE_ENC_PROGRESS); - - if (bInPlaceDecNonSys) - { - // Decryption of non-system volume finished and free drive letters are available. Check if a drive letter is assigned to the decrypted volume. - - WCHAR deviceName[MAX_PATH + 1]; - - StringCbCopyW (deviceName, sizeof(deviceName), szDiskFile); - - if (GetDiskDeviceDriveLetter (deviceName) < 0) - { - // No drive letter is assigned to the device - MessageBeep (MB_OK); - LoadPage (hwndDlg, NONSYS_INPLACE_DEC_TRANSFORM_FINISHED_DRIVE_LETTER_PAGE); - return 1; - } - else - { - Info ("NONSYS_INPLACE_DEC_FINISHED_INFO", hwndDlg); - } - } - - LoadPage (hwndDlg, NONSYS_INPLACE_ENC_TRANSFORM_FINISHED_PAGE); - return 1; - - case TC_APPMSG_VOL_TRANSFORM_THREAD_ENDED: - - if (bInPlaceEncNonSys) - { - // In-place encryption was interrupted/paused (did not finish) - - KillTimer (hwndDlg, TIMER_ID_NONSYS_INPLACE_ENC_PROGRESS); - - UpdateNonSysInPlaceEncControls (); - } - else - { - // Format has been aborted (did not finish) - - EnableWindow (GetDlgItem (hCurPage, IDC_QUICKFORMAT), (bDevice || bSparseFileSwitch) && !(bHiddenVol && !bHiddenVolHost)); - EnableWindow (GetDlgItem (hCurPage, IDC_FILESYS), TRUE); - EnableWindow (GetDlgItem (hCurPage, IDC_CLUSTERSIZE), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDHELP), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), TRUE); - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), TRUE); - SendMessage (GetDlgItem (hCurPage, IDC_PROGRESS_BAR), PBM_SETPOS, 0, 0L); - SetFocus (GetDlgItem (hwndDlg, IDC_NEXT)); - } - - NormalCursor (); - return 1; - - case WM_HELP: - - OpenPageHelp (hwndDlg, nCurPageNo); - return 1; - - case TC_APPMSG_FORMAT_USER_QUIT: - - if (nCurPageNo == NONSYS_INPLACE_ENC_TRANSFORM_PAGE - && (bVolTransformThreadRunning || bVolTransformThreadToRun || bInPlaceEncNonSysResumed)) - { - // Non-system encryption in progress - if (AskNoYes ("NONSYS_INPLACE_ENC_DEFER_CONFIRM", hwndDlg) == IDYES) - { - NonSysInplaceEncPause (); - - EndMainDlg (hwndDlg); - return 1; - } - else - return 1; // Disallow close - } - else if (bVolTransformThreadRunning || bVolTransformThreadToRun) - { - // Format (non-in-place encryption) in progress - if (AskNoYes ("FORMAT_ABORT", hwndDlg) == IDYES) - { - bVolTransformThreadCancel = TRUE; - - EndMainDlg (hwndDlg); - return 1; - } - else - return 1; // Disallow close - } - else if ((nCurPageNo == SYSENC_ENCRYPTION_PAGE || nCurPageNo == SYSENC_PRETEST_RESULT_PAGE) - && SystemEncryptionStatus != SYSENC_STATUS_NONE - && InstanceHasSysEncMutex ()) - { - // System encryption/decryption in progress - - if (AskYesNo (SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING ? - "SYSTEM_DECRYPTION_DEFER_CONFIRM" : "SYSTEM_ENCRYPTION_DEFER_CONFIRM", MainDlg) == IDYES) - { - if (nCurPageNo == SYSENC_PRETEST_RESULT_PAGE) - TextInfoDialogBox (TC_TBXID_SYS_ENC_RESCUE_DISK); - - try - { - BootEncStatus = BootEncObj->GetStatus(); - - if (BootEncStatus.SetupInProgress) - { - BootEncObj->AbortSetupWait (); - Sleep (200); - BootEncStatus = BootEncObj->GetStatus(); - } - - if (!BootEncStatus.SetupInProgress) - { - EndMainDlg (MainDlg); - return 1; - } - else - { - Error ("FAILED_TO_INTERRUPT_SYSTEM_ENCRYPTION", MainDlg); - return 1; // Disallow close - } - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - return 1; // Disallow close - } - else - return 1; // Disallow close - } - else if (bConfirmQuitSysEncPretest) - { - if (AskWarnNoYes (bHiddenOS ? "CONFIRM_CANCEL_HIDDEN_OS_CREATION" : "CONFIRM_CANCEL_SYS_ENC_PRETEST", MainDlg) == IDNO) - return 1; // Disallow close - } - else if (bConfirmQuit) - { - if (AskWarnNoYes ("CONFIRM_EXIT_UNIVERSAL", MainDlg) == IDNO) - return 1; // Disallow close - } - - if (hiddenVolHostDriveNo > -1) - { - CloseVolumeExplorerWindows (hwndDlg, hiddenVolHostDriveNo); - UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE); - } - - EndMainDlg (hwndDlg); - return 1; - - - case WM_COMMAND: - - if (lw == IDHELP) - { - OpenPageHelp (hwndDlg, nCurPageNo); - return 1; - } - else if (lw == IDCANCEL) - { - PostMessage (hwndDlg, TC_APPMSG_FORMAT_USER_QUIT, 0, 0); - return 1; - } - else if (lw == IDC_NEXT) - { - if (nCurPageNo == INTRO_PAGE) - { - switch (GetSelectedWizardMode (hCurPage)) - { - case WIZARD_MODE_FILE_CONTAINER: - - if (CurrentOSMajor >= 6 && IsUacSupported() && IsAdmin() && !IsBuiltInAdmin() && !IsNonInstallMode()) - { - static bool warningConfirmed = false; - if (!warningConfirmed) - { - if (AskWarnYesNo ("CONTAINER_ADMIN_WARNING", MainDlg) == IDYES) - exit (0); - - warningConfirmed = true; - } - } - - WaitCursor (); - CloseSysEncMutex (); - ChangeWizardMode (WIZARD_MODE_FILE_CONTAINER); - bHiddenOS = FALSE; - bInPlaceEncNonSys = FALSE; - nNewPageNo = VOLUME_TYPE_PAGE - 1; // Skip irrelevant pages - break; - - case WIZARD_MODE_NONSYS_DEVICE: - - WaitCursor (); - CloseSysEncMutex (); - - if (!ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE)) - { - NormalCursor (); - return 1; - } - - bHiddenOS = FALSE; - nNewPageNo = VOLUME_TYPE_PAGE - 1; // Skip irrelevant pages - break; - - case WIZARD_MODE_SYS_DEVICE: - - WaitCursor (); - bHiddenVol = FALSE; - bInPlaceEncNonSys = FALSE; - SwitchWizardToSysEncMode (); - return 1; - } - } - else if (nCurPageNo == SYSENC_TYPE_PAGE) - { - if (bHiddenOS) - { - bWholeSysDrive = FALSE; - bHiddenVolDirect = FALSE; - } - - if (!bHiddenOS) - nNewPageNo = SYSENC_SPAN_PAGE - 1; // Skip irrelevant pages - } - else if (nCurPageNo == SYSENC_HIDDEN_OS_REQ_CHECK_PAGE) - { - WaitCursor (); - try - { - BootEncObj->CheckRequirementsHiddenOS (); - - if (CheckGapBetweenSysAndHiddenOS ()) - Warning ("GAP_BETWEEN_SYS_AND_HIDDEN_OS_PARTITION", MainDlg); - } - catch (Exception &e) - { - e.Show (hwndDlg); - NormalCursor (); - return 1; - } - - if (AskWarnYesNo ("DECOY_OS_REINSTALL_WARNING", MainDlg) == IDNO) - { - NormalCursor (); - return 1; - } - - WarningDirect ((wstring (GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO")) - + L"\n\n" - + GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION")).c_str(), MainDlg); - - if (!IsAdmin() && IsUacSupported()) - { - // If UAC elevation is needed, we need to elevate the complete wizard process here, because - // we will need to switch to the non-sys-device mode, which requires the whole wizard process - // to have admin rights. - - CloseSysEncMutex (); - - if (!ElevateWholeWizardProcess (L"/r")) - { - // Failed to obtain admin rights - - NormalCursor (); - - if (!CreateSysEncMutex ()) - AbortProcess ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE"); - - return 1; - } - } - - // This check requires admin rights - try - { - BootEncObj->InitialSecurityChecksForHiddenOS (); - } - catch (Exception &e) - { - e.Show (hwndDlg); - EndMainDlg (MainDlg); // Some of the checks need the wizard to be restarted (results are cached until exit and the checks would fail even if the issues were rectified). - return 1; - } - - nNewPageNo = SYSENC_MULTI_BOOT_MODE_PAGE - 1; // Skip irrelevant pages - } - else if (nCurPageNo == SYSENC_SPAN_PAGE) - { - try - { - if (bWholeSysDrive && !BootEncObj->SystemPartitionCoversWholeDrive()) - { - if (BootEncObj->SystemDriveContainsNonStandardPartitions()) - { - if (AskWarnYesNoString ((wstring (GetString ("SYSDRIVE_NON_STANDARD_PARTITIONS")) + L"\n\n" + GetString ("ASK_ENCRYPT_PARTITION_INSTEAD_OF_DRIVE")).c_str(), MainDlg) == IDYES) - bWholeSysDrive = FALSE; - } - - if (!IsOSAtLeast (WIN_VISTA) && bWholeSysDrive) - { - if (BootEncObj->SystemDriveContainsExtendedPartition()) - { - Error ("WDE_UNSUPPORTED_FOR_EXTENDED_PARTITIONS", MainDlg); - - if (AskYesNo ("ASK_ENCRYPT_PARTITION_INSTEAD_OF_DRIVE", MainDlg) == IDNO) - return 1; - - bWholeSysDrive = FALSE; - } - else - Warning ("WDE_EXTENDED_PARTITIONS_WARNING", hwndDlg); - } - } - - if (!bWholeSysDrive && BootEncObj->SystemPartitionCoversWholeDrive()) - bWholeSysDrive = (AskYesNo ("WHOLE_SYC_DEVICE_RECOM", hwndDlg) == IDYES); - } - catch (Exception &e) - { - e.Show (hwndDlg); - NormalCursor (); - return 1; - } - - if (!bWholeSysDrive) - nNewPageNo = SYSENC_MULTI_BOOT_MODE_PAGE - 1; // Skip irrelevant pages - } - else if (nCurPageNo == SYSENC_PRE_DRIVE_ANALYSIS_PAGE) - { - if ((SysEncDetectHiddenSectors = Get2RadButtonPageAnswer()) != 1) - { - // Skip drive analysis - nNewPageNo = SYSENC_DRIVE_ANALYSIS_PAGE; - - // If the user had already searched for hidden sectors, we must clear (invalidate) the - // result because now he changed his mind and no longer wishes to encrypt the hidden sectors. - try - { - BootEncObj->InvalidateCachedSysDriveProperties (); - } - catch (Exception &e) - { - e.Show (MainDlg); - EndMainDlg (MainDlg); - exit(0); - } - } - } - else if (nCurPageNo == SYSENC_MULTI_BOOT_MODE_PAGE) - { - if (nMultiBoot > 1) - { - // Multi-boot - - if (AskWarnNoYes ("MULTI_BOOT_FOR_ADVANCED_ONLY", hwndDlg) == IDNO) - return 1; - - if (bHiddenOS) - { - if (AskWarnNoYes ("HIDDEN_OS_MULTI_BOOT", hwndDlg) == IDNO) - { - Error ("UNSUPPORTED_HIDDEN_OS_MULTI_BOOT_CFG", hwndDlg); - return 1; - } - } - } - - if (bHiddenOS) - { - if (IsOSAtLeast (WIN_7) - && BootEncObj->GetSystemDriveConfiguration().ExtraBootPartitionPresent - && AskWarnYesNo ("CONFIRM_HIDDEN_OS_EXTRA_BOOT_PARTITION", hwndDlg) == IDNO) - { - TextInfoDialogBox (TC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS); - NormalCursor (); - return 1; - } - - if (AskWarnYesNo ("DECOY_OS_REQUIREMENTS", hwndDlg) == IDNO) - { - NormalCursor (); - return 1; - } - - if (!ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE)) - { - NormalCursor (); - return 1; - } - - // Skip irrelevant pages - nNewPageNo = HIDDEN_VOL_HOST_PRE_CIPHER_PAGE - 1; - } - else if (nMultiBoot <= 1) - { - // Single-boot (not creating a hidden OS) - - // Skip irrelevant pages - nNewPageNo = CIPHER_PAGE - 1; - } - } - else if (nCurPageNo == SYSENC_MULTI_BOOT_SYS_EQ_BOOT_PAGE) - { - SysEncMultiBootCfg.SystemOnBootDrive = Get2RadButtonPageAnswer (); - - if (!SysEncMultiBootCfg.SystemOnBootDrive) - { - Error ("SYS_PARTITION_MUST_BE_ON_BOOT_DRIVE", hwndDlg); - EndMainDlg (MainDlg); - return 1; - } - } - else if (nCurPageNo == SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE) - { - if (Get2RadButtonPageAnswer () == 0) - { - // 2 or more drives contain an OS - - SysEncMultiBootCfg.NumberOfSysDrives = 2; - } - else if (Get2RadButtonPageAnswer () == 1) - { - // Only 1 drive contains an OS - - SysEncMultiBootCfg.NumberOfSysDrives = 1; - - if (bWholeSysDrive) - { - // Whole-system-drive encryption is currently not supported if the drive contains - // more than one system - Error ("WDE_UNSUPPORTED_FOR_MULTIPLE_SYSTEMS_ON_ONE_DRIVE", hwndDlg); - return 1; - } - - // Ask whether there is a non-Windows boot loader in the MBR - nNewPageNo = SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE - 1; - } - } - else if (nCurPageNo == SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE) - { - SysEncMultiBootCfg.MultipleSystemsOnDrive = Get2RadButtonPageAnswer (); - - if (SysEncMultiBootCfg.MultipleSystemsOnDrive && bWholeSysDrive) - { - // Whole-system-drive encryption is currently not supported if the drive contains - // more than one system - Error ("WDE_UNSUPPORTED_FOR_MULTIPLE_SYSTEMS_ON_ONE_DRIVE", hwndDlg); - return 1; - } - } - - else if (nCurPageNo == SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE) - { - SysEncMultiBootCfg.BootLoaderBrand = Get2RadButtonPageAnswer (); - - if (SysEncMultiBootCfg.BootLoaderBrand) - { - // A non-Windows boot manager in the MBR - Error ("CUSTOM_BOOT_MANAGERS_IN_MBR_UNSUPPORTED", hwndDlg); - EndMainDlg (MainDlg); - return 1; - } - else - { - // Either a standard Windows boot manager or no boot manager - wcscpy_s (SysEncMultiBootCfgOutcome, sizeof(SysEncMultiBootCfgOutcome) / 2, GetString ("WINDOWS_BOOT_LOADER_HINTS")); - } - } - - else if (nCurPageNo == SYSENC_MULTI_BOOT_OUTCOME_PAGE) - { - if (bHiddenOS) - { - if (!ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE)) - { - NormalCursor (); - return 1; - } - - nNewPageNo = HIDDEN_VOL_HOST_PRE_CIPHER_PAGE - 1; // Skip irrelevant pages - } - else - nNewPageNo = CIPHER_PAGE - 1; // Skip irrelevant pages - } - - else if (nCurPageNo == VOLUME_TYPE_PAGE) - { - if (IsButtonChecked (GetDlgItem (hCurPage, IDC_HIDDEN_VOL))) - { - if (!IsAdmin() && !IsUacSupported () - && IDNO == MessageBoxW (hwndDlg, GetString ("ADMIN_PRIVILEGES_WARN_HIDVOL"), - lpszTitle, MB_ICONWARNING|MB_YESNO|MB_DEFBUTTON2)) - { - return 1; - } - else - { - bHiddenVol = TRUE; - bHiddenVolHost = TRUE; - bInPlaceEncNonSys = FALSE; - } - } - else - { - bHiddenVol = FALSE; - bHiddenVolHost = FALSE; - bHiddenVolDirect = FALSE; - nNewPageNo = VOLUME_LOCATION_PAGE - 1; // Skip the hidden volume creation wizard mode selection - } - } - - else if (nCurPageNo == HIDDEN_VOL_WIZARD_MODE_PAGE) - { - if (IsButtonChecked (GetDlgItem (hCurPage, IDC_HIDVOL_WIZ_MODE_DIRECT))) - bHiddenVolDirect = TRUE; - else - { - if (IsHiddenOSRunning()) - { - WarningDirect ((wstring (GetString ("HIDDEN_VOL_CREATION_UNDER_HIDDEN_OS_HOWTO")) - + L"\n\n" - + GetString ("NOTE_BEGINNING") - + GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO") - + L" " - + GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION")).c_str(), hwndDlg); - NormalCursor (); - return 1; - } - - bHiddenVolDirect = FALSE; - } - } - - else if (nCurPageNo == VOLUME_LOCATION_PAGE) - { - BOOL tmpbDevice; - - WaitCursor(); - - GetWindowTextW (GetDlgItem (hCurPage, IDC_COMBO_BOX), szFileName, ARRAYSIZE (szFileName)); - RelativePath2Absolute (szFileName); - CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice); - - if (tmpbDevice != bDevice) - { - if (bDevice) - { - // Not a valid device path - Error ("CANNOT_CALC_SPACE", hwndDlg); - NormalCursor (); - return 1; - } - else - { - if (AskWarnYesNo ("DEVICE_SELECTED_IN_NON_DEVICE_MODE", hwndDlg) == IDNO) - { - NormalCursor (); - return 1; - } - - SwitchWizardToNonSysDeviceMode (); - NormalCursor (); - return 1; - } - } - - MoveEditToCombo (GetDlgItem (hCurPage, IDC_COMBO_BOX), bHistory); - - if (IsMountedVolume (szDiskFile)) - { - Error ("ALREADY_MOUNTED", hwndDlg); - NormalCursor (); - return 1; - } - - if (bDevice) - { - switch (IsSystemDevicePath (szDiskFile, hCurPage, TRUE)) - { - case 1: - case 2: - case 3: - if (AskYesNo ("CONFIRM_SYSTEM_ENCRYPTION_MODE", hwndDlg) == IDNO) - { - NormalCursor (); - return 1; - } - szFileName[0] = 0; - szDiskFile[0] = 0; - SwitchWizardToSysEncMode (); - NormalCursor (); - return 1; - - case -1: - // In some environments (such as PE), the system volume is not located on a hard drive. - // Therefore, we must interpret this return code as "Not a system device path" (otherwise, - // non-system devices could not be TC-formatted in such environments). Note that this is - // rather safe, because bReliableRequired is set to TRUE. - - // NOP - break; - } - } - else - { - if (CheckFileExtension(szFileName) - && AskWarnNoYes ("EXE_FILE_EXTENSION_CONFIRM", hwndDlg) == IDNO) - { - NormalCursor (); - return 1; - } - } - - bHistory = !IsButtonChecked (GetDlgItem (hCurPage, IDC_NO_HISTORY)); - - SaveSettings (hCurPage); - - if (bHiddenVolDirect && bHiddenVolHost) - { - nNewPageNo = HIDDEN_VOL_HOST_PASSWORD_PAGE - 1; - - if (bDevice) - { - if(!QueryFreeSpace (hwndDlg, GetDlgItem (hwndDlg, IDC_SPACE_LEFT), FALSE)) - { - MessageBoxW (hwndDlg, GetString ("CANT_GET_VOLSIZE"), lpszTitle, ICON_HAND); - NormalCursor (); - return 1; - } - else - nHiddenVolHostSize = nVolumeSize; - } - else - { - if (!GetFileVolSize (hwndDlg, &nHiddenVolHostSize)) - { - NormalCursor (); - return 1; - } - else if (IsSparseFile (hwndDlg)) - { - // Hidden volumes must not be created within sparse file containers - Warning ("HIDDEN_VOL_HOST_SPARSE", hwndDlg); - NormalCursor (); - return 1; - } - } - } - else - { - if (!bHiddenVol && !bDevice) - nNewPageNo = CIPHER_PAGE - 1; - else if (bHiddenVol) - nNewPageNo = (bHiddenVolHost ? HIDDEN_VOL_HOST_PRE_CIPHER_PAGE : HIDDEN_VOL_PRE_CIPHER_PAGE) - 1; - } - } - - else if (nCurPageNo == DEVICE_TRANSFORM_MODE_PAGE) - { - if (bInPlaceEncNonSys) - { - // Check requirements for non-system in-place encryption - - if (!CheckRequirementsForNonSysInPlaceEnc (hwndDlg, szDiskFile, FALSE)) - { - return 1; - } - - // We are going to skip the Size page so we must get the size here - nVolumeSize = GetDeviceSize (szDiskFile); - - if (nVolumeSize == -1) - { - handleWin32Error (MainDlg, SRC_POS); - return 1; - } - - if (AskWarnYesNo ("NONSYS_INPLACE_ENC_CONFIRM_BACKUP", hwndDlg) == IDNO) - return 1; - } - nNewPageNo = CIPHER_PAGE - 1; - } - - else if (nCurPageNo == HIDDEN_VOL_HOST_PRE_CIPHER_PAGE) - { - if (bHiddenVolHost) - nNewPageNo = CIPHER_PAGE - 1; // Skip the info on the hiddem volume - } - - else if (nCurPageNo == CIPHER_PAGE) - { - LPARAM nIndex; - nIndex = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETCURSEL, 0, 0); - nVolumeEA = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETITEMDATA, nIndex, 0); - - if (SysEncInEffect () - && EAGetCipherCount (nVolumeEA) > 1) // Cascade? - { - if (AskWarnNoYes ("CONFIRM_CASCADE_FOR_SYS_ENCRYPTION", hwndDlg) == IDNO) - return 1; - - if (!bHiddenOS) - Info ("NOTE_CASCADE_FOR_SYS_ENCRYPTION", hwndDlg); - } - - nIndex = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX_HASH_ALGO), CB_GETCURSEL, 0, 0); - hash_algo = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX_HASH_ALGO), CB_GETITEMDATA, nIndex, 0); - - RandSetHashFunction (hash_algo); - - if (SysEncInEffect () || bInPlaceEncNonSys) - nNewPageNo = PASSWORD_PAGE - 1; // Skip irrelevant pages - } - - else if (nCurPageNo == SIZE_PAGE) - { - wchar_t szFileSystemNameBuffer[256]; - - VerifySizeAndUpdate (hCurPage, TRUE); - - if (!bDevice) - { - /* Verify that the volume would not be too large for the host file system */ - - wchar_t root[TC_MAX_PATH]; - - if (GetVolumePathName (szDiskFile, root, ARRAYSIZE (root)) - && GetVolumeInformation (root, NULL, 0, NULL, NULL, NULL, szFileSystemNameBuffer, ARRAYSIZE(szFileSystemNameBuffer)) - && !wcsncmp (szFileSystemNameBuffer, L"FAT32", 5)) - { - // The host file system is FAT32 - if (nUIVolumeSize * nMultiplier >= 4 * BYTES_PER_GB) - { - Error ("VOLUME_TOO_LARGE_FOR_FAT32", hwndDlg); - return 1; - } - } - - /* Verify that the volume would not be too large for the operating system */ - - if (!IsOSAtLeast (WIN_VISTA) - && nUIVolumeSize * nMultiplier > 2 * BYTES_PER_TB) - { - Warning ("VOLUME_TOO_LARGE_FOR_WINXP", hwndDlg); - } - } - - if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume - { - /* Ask for confirmation if the hidden volume is too large for the user to be - able to write much more data to the outer volume. */ - - if (((double) nUIVolumeSize / (nMaximumHiddenVolSize / nMultiplier)) > 0.85) // 85% - { - if (AskWarnNoYes ("FREE_SPACE_FOR_WRITING_TO_OUTER_VOLUME", hwndDlg) == IDNO) - return 1; - } - } - - if (!(bHiddenVolDirect && bHiddenVolHost)) - nNewPageNo = PASSWORD_PAGE - 1; - } - - else if (nCurPageNo == PASSWORD_PAGE) - { - VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (MainDlg, IDC_NEXT), - GetDlgItem (hCurPage, IDC_PASSWORD), - GetDlgItem (hCurPage, IDC_VERIFY), - volumePassword.Text, - szVerify, - KeyFilesEnable && FirstKeyFile!=NULL && !SysEncInEffect()); - - volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); - - if (volumePassword.Length > 0) - { - // Password character encoding - if (SysEncInEffect () && !CheckPasswordCharEncoding (GetDlgItem (hCurPage, IDC_PASSWORD), NULL)) - { - Error ("UNSUPPORTED_CHARS_IN_PWD", hwndDlg); - return 1; - } - // Check password length (check also done for outer volume which is not the case in TrueCrypt). - else if (!CheckPasswordLength (hwndDlg, volumePassword.Length, 0, SysEncInEffect(), FALSE, FALSE)) - { - return 1; - } - } - - // Store the password in case we need to restore it after keyfile is applied to it - if (!GetPassword (hCurPage, IDC_PASSWORD, szRawPassword, sizeof (szRawPassword), TRUE)) - return 1; - - if (!SysEncInEffect ()) - { - if (KeyFilesEnable) - { - WaitCursor (); - - if (!KeyFilesApply (hwndDlg, &volumePassword, FirstKeyFile, NULL)) - { - NormalCursor (); - return 1; - } - - NormalCursor (); - } - - } - else - { - KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); - - if (bKeyboardLayoutChanged) - { - // Restore the original keyboard layout - if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) - Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); - else - bKeyboardLayoutChanged = FALSE; - } - - } - - if (!PimEnable) - { - // PIM not activated. Skip PIM page - nNewPageNo = PIM_PAGE; - volumePim = 0; - - if (SysEncInEffect ()) - { - nNewPageNo = SYSENC_COLLECTING_RANDOM_DATA_PAGE - 1; // Skip irrelevant pages - } - - if (bInPlaceEncNonSys) - { - nNewPageNo = NONSYS_INPLACE_ENC_RAND_DATA_PAGE - 1; // Skip irrelevant pages - } - else if (WizardMode != WIZARD_MODE_SYS_DEVICE - && !FileSize4GBLimitQuestionNeeded () - || CreatingHiddenSysVol()) // If we're creating a hidden volume for a hidden OS, we don't need to format it with any filesystem (the entire OS will be copied to the hidden volume sector by sector). - { - nNewPageNo = FORMAT_PAGE - 1; // Skip irrelevant pages - } - - } - } - - else if (nCurPageNo == PIM_PAGE) - { - volumePim = GetPim (hCurPage, IDC_PIM); - - if (!SysEncInEffect() && (volumePim > MAX_PIM_VALUE)) - { - SetFocus (GetDlgItem(hCurPage, IDC_PIM)); - Error ("PIM_TOO_BIG", hwndDlg); - return 1; - } - - if (volumePassword.Length > 0) - { - // Password character encoding - if (SysEncInEffect() && (volumePim > MAX_BOOT_PIM_VALUE)) - { - SetFocus (GetDlgItem(hCurPage, IDC_PIM)); - Error ("PIM_SYSENC_TOO_BIG", hwndDlg); - return 1; - } - // Check password length (check also done for outer volume which is not the case in TrueCrypt). - else if (!CheckPasswordLength (hwndDlg, volumePassword.Length, volumePim, SysEncInEffect(), TRUE, FALSE)) - { - return 1; - } - } - - if (SysEncInEffect ()) - { - - nNewPageNo = SYSENC_COLLECTING_RANDOM_DATA_PAGE - 1; // Skip irrelevant pages - } - - if (bInPlaceEncNonSys) - { - nNewPageNo = NONSYS_INPLACE_ENC_RAND_DATA_PAGE - 1; // Skip irrelevant pages - } - else if (WizardMode != WIZARD_MODE_SYS_DEVICE - && !FileSize4GBLimitQuestionNeeded () - || CreatingHiddenSysVol()) // If we're creating a hidden volume for a hidden OS, we don't need to format it with any filesystem (the entire OS will be copied to the hidden volume sector by sector). - { - nNewPageNo = FORMAT_PAGE - 1; // Skip irrelevant pages - } - } - - else if (nCurPageNo == HIDDEN_VOL_HOST_PASSWORD_PAGE - || nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) - { - WaitCursor (); - - if (!GetPassword (hCurPage, IDC_PASSWORD_DIRECT, (char*) volumePassword.Text, MAX_PASSWORD + 1, TRUE)) - { - NormalCursor (); - return 1; - } - volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); - - hash_algo = (int) SendMessage (GetDlgItem (hCurPage, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hCurPage, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); - - volumePim = GetPim (hCurPage, IDC_PIM); - - // Store the password in case we need to restore it after keyfile is applied to it - if (!GetPassword (hCurPage, IDC_PASSWORD_DIRECT, szRawPassword, sizeof (szRawPassword), TRUE)) - { - NormalCursor (); - return 1; - } - - if (KeyFilesEnable) - { - KeyFilesApply (hwndDlg, &volumePassword, FirstKeyFile, NULL); - } - - if (!bInPlaceEncNonSys) - { - - /* Mount the volume which is to host the new hidden volume as read only */ - - if (hiddenVolHostDriveNo >= 0) // If the hidden volume host is currently mounted (e.g. after previous unsuccessful dismount attempt) - { - BOOL tmp_result; - - // Dismount the hidden volume host (in order to remount it as read-only subsequently) - while (!(tmp_result = UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE))) - { - if (MessageBoxW (hwndDlg, GetString ("CANT_DISMOUNT_OUTER_VOL"), lpszTitle, MB_RETRYCANCEL) != IDRETRY) - { - // Cancel - NormalCursor(); - return 1; - } - } - if (tmp_result) // If dismounted - hiddenVolHostDriveNo = -1; - } - - if (hiddenVolHostDriveNo < 0) // If the hidden volume host is not mounted - { - int retCode; - - // Mount the hidden volume host as read-only (to ensure consistent and secure - // results of the volume bitmap scanning) - switch (MountHiddenVolHost (hwndDlg, szDiskFile, &hiddenVolHostDriveNo, &volumePassword, hash_algo, volumePim, TRUE)) - { - case ERR_NO_FREE_DRIVES: - NormalCursor (); - MessageBoxW (hwndDlg, GetString ("NO_FREE_DRIVE_FOR_OUTER_VOL"), lpszTitle, ICON_HAND); - return 1; - case ERR_VOL_MOUNT_FAILED: - case ERR_PASSWORD_WRONG: - NormalCursor (); - return 1; - case 0: - - /* Hidden volume host successfully mounted as read-only */ - - WaitCursor (); - - // Verify that the outer volume contains a suitable file system, retrieve cluster size, and - // scan the volume bitmap - if (!IsAdmin () && IsUacSupported ()) - retCode = UacAnalyzeHiddenVolumeHost (hwndDlg, &hiddenVolHostDriveNo, GetVolumeDataAreaSize (FALSE, nHiddenVolHostSize), &realClusterSize, &nbrFreeClusters); - else - retCode = AnalyzeHiddenVolumeHost (hwndDlg, &hiddenVolHostDriveNo, GetVolumeDataAreaSize (FALSE, nHiddenVolHostSize), &realClusterSize, &nbrFreeClusters); - - switch (retCode) - { - case -1: // Fatal error - CloseVolumeExplorerWindows (hwndDlg, hiddenVolHostDriveNo); - - if (UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE)) - hiddenVolHostDriveNo = -1; - - AbortProcessSilent (); - break; - - case 0: // Unsupported file system (or other non-fatal error which has already been reported) - if (bHiddenVolDirect) - { - CloseVolumeExplorerWindows (hwndDlg, hiddenVolHostDriveNo); - - if (UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE)) - hiddenVolHostDriveNo = -1; - } - NormalCursor (); - return 1; - - case 1: - - // Determine the maximum possible size of the hidden volume - if (DetermineMaxHiddenVolSize (hwndDlg) < 1) - { - // Non-fatal error while determining maximum possible size of the hidden volume - NormalCursor(); - return 1; - } - else - { - BOOL tmp_result; - - /* Maximum possible size of the hidden volume successfully determined */ - - // Dismount the hidden volume host - while (!(tmp_result = UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE))) - { - if (MessageBoxW (hwndDlg, GetString ("CANT_DISMOUNT_OUTER_VOL"), lpszTitle, MB_RETRYCANCEL) != IDRETRY) - { - // Cancel - NormalCursor(); - return 1; - } - } - - if (tmp_result) // If dismounted - { - hiddenVolHostDriveNo = -1; - - bHiddenVolHost = FALSE; - bHiddenVolFinished = FALSE; - - // Clear the outer volume password - WipePasswordsAndKeyfiles (); - - RestoreDefaultKeyFilesParam (); - - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), TRUE); - NormalCursor (); - - nNewPageNo = HIDDEN_VOL_HOST_PRE_CIPHER_PAGE; - } - } - break; - } - break; - } - } - } - else if (bInPlaceEncNonSysResumed) - { - /* Scan all available partitions to discover all partitions where non-system in-place - encryption/decryption has been interrupted. */ - - BOOL tmpbDevice; - - NormalCursor (); - - ShowWaitDialog (hwndDlg, TRUE, ResumeInPlaceEncWaitThreadProc, NULL); - - WaitCursor(); - - if (DeferredNonSysInPlaceEncDevices.empty()) - { - Warning ("FOUND_NO_PARTITION_W_DEFERRED_INPLACE_ENC", hwndDlg); - - NormalCursor(); - return 1; - } - else if (DeferredNonSysInPlaceEncDevices.size() == 1) - { - CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), DeferredNonSysInPlaceEncDevices.front().Path.c_str(), &tmpbDevice); - - nVolumeSize = GetDeviceSize (szDiskFile); - if (nVolumeSize == -1) - { - handleWin32Error (MainDlg, SRC_POS); - NormalCursor(); - return 1; - } - - nNewPageNo = NONSYS_INPLACE_ENC_TRANSFORM_PAGE - 1; // Skip irrelevant pages - } - - NormalCursor(); - } - else - { - /* Try to mount the non-system volume to decrypt in place (the process has not started yet, we are NOT trying to resume it). - We will try to mount it using the backup header, which we require to work (i.e. be non-damaged) before we start writing - to the volume (the primary header will be overwritten by decrypted data soon after the decryption process begins, so the - backup header will contain the only copy of the master key). */ - - int driveNo = -1; - - // The volume may already be mounted. We need to dismount it first in order to verify the supplied password/keyfile(s) is/are correct. - if (IsMountedVolume (szFileName)) - { - driveNo = GetMountedVolumeDriveNo (szFileName); - - if (driveNo == -1 - || !UnmountVolume (hwndDlg, driveNo, TRUE)) - { - handleWin32Error (MainDlg, SRC_POS); - AbortProcess ("CANT_DISMOUNT_VOLUME"); - } - } - - driveNo = GetLastAvailableDrive (); - - if (driveNo < 0) - AbortProcess ("NO_FREE_DRIVES"); - - MountOptions mountOptions; - ZeroMemory (&mountOptions, sizeof (mountOptions)); - - mountOptions.UseBackupHeader = FALSE; // This must be FALSE at this point because otherwise we wouldn't be able to detect a legacy volume - mountOptions.ReadOnly = TRUE; - mountOptions.Removable = ConfigReadInt ("MountVolumesRemovable", FALSE); - - // Check that it is not a hidden or legacy volume - - if (MountVolume (hwndDlg, driveNo, szFileName, &volumePassword, hash_algo, volumePim, FALSE, FALSE, FALSE, TRUE, &mountOptions, FALSE, TRUE) < 1) - { - NormalCursor(); - return 1; - } - - { - DWORD dwResult; - VOLUME_PROPERTIES_STRUCT volProp; - - memset (&volProp, 0, sizeof(volProp)); - volProp.driveNo = driveNo; - if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &volProp, sizeof (volProp), &volProp, sizeof (volProp), &dwResult, NULL) || dwResult == 0) - { - handleWin32Error (hwndDlg, SRC_POS); - UnmountVolume (hwndDlg, driveNo, TRUE); - AbortProcess ("CANT_GET_VOL_INFO"); - } - - if (volProp.volFormatVersion == TC_VOLUME_FORMAT_VERSION_PRE_6_0) - { - UnmountVolume (hwndDlg, driveNo, TRUE); - AbortProcess ("NONSYS_INPLACE_DECRYPTION_BAD_VOL_FORMAT"); - } - - if (volProp.hiddenVolume) - { - UnmountVolume (hwndDlg, driveNo, TRUE); - AbortProcess ("NONSYS_INPLACE_DECRYPTION_CANT_DECRYPT_HID_VOL"); - } - } - - // Remount the volume using the backup header to verify it is working - - if (!UnmountVolume (hwndDlg, driveNo, TRUE)) - { - handleWin32Error (MainDlg, SRC_POS); - AbortProcess ("CANT_DISMOUNT_VOLUME"); - } - - mountOptions.UseBackupHeader = TRUE; // This must be TRUE at this point (we won't be using the regular header, which will be lost soon after the decryption process starts) - - if (MountVolume (hwndDlg, driveNo, szFileName, &volumePassword, hash_algo, volumePim, FALSE, FALSE, FALSE, TRUE, &mountOptions, FALSE, TRUE) < 1) - { - NormalCursor(); - return 1; - } - - if (!UnmountVolume (hwndDlg, driveNo, TRUE)) - { - handleWin32Error (MainDlg, SRC_POS); - AbortProcess ("CANT_DISMOUNT_VOLUME"); - } - - BOOL tmpbDevice; - - CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice); - - nVolumeSize = GetDeviceSize (szDiskFile); - if (nVolumeSize == -1) - { - handleWin32Error (MainDlg, SRC_POS); - AbortProcessSilent (); - } - - nNewPageNo = NONSYS_INPLACE_ENC_TRANSFORM_PAGE - 1; // Skip irrelevant pages - NormalCursor(); - } - } - - else if (nCurPageNo == FILESYS_PAGE) - { - if (!bHiddenVol && IsHiddenOSRunning() && Get2RadButtonPageAnswer() == 1) - { - // The user wants to store files larger than 4GB on the non-hidden volume about to be created and a hidden OS is running - - WarningDirect ((wstring (GetString ("CANNOT_SATISFY_OVER_4G_FILE_SIZE_REQ")) - + L" " - + GetString ("CANNOT_CREATE_NON_HIDDEN_NTFS_VOLUMES_UNDER_HIDDEN_OS") - + L"\n\n" - + GetString ("NOTE_BEGINNING") - + GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO") - + L" " - + GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION")).c_str(), hwndDlg); - - return 1; - } - - if (nNeedToStoreFilesOver4GB != Get2RadButtonPageAnswer()) - fileSystem = FILESYS_NONE; // The user may have gone back and changed the answer, so default file system must be reselected - - nNeedToStoreFilesOver4GB = Get2RadButtonPageAnswer(); - - nNewPageNo = FORMAT_PAGE - 1; // Skip irrelevant pages - } - - else if (nCurPageNo == SYSENC_COLLECTING_RANDOM_DATA_PAGE - || nCurPageNo == NONSYS_INPLACE_ENC_RAND_DATA_PAGE) - { - wchar_t tmp[RANDPOOL_DISPLAY_SIZE+1]; - - if (!bInPlaceEncNonSys) - { - /* Generate master key and other related data (except the rescue disk) for system encryption. */ - - try - { - WaitCursor(); - BootEncObj->PrepareInstallation (!bWholeSysDrive, volumePassword, nVolumeEA, FIRST_MODE_OF_OPERATION_ID, hash_algo, volumePim, L""); - } - catch (Exception &e) - { - e.Show (hwndDlg); - NormalCursor (); - return 1; - } - } - - KillTimer (hwndDlg, TIMER_ID_RANDVIEW); - - // Attempt to wipe the GUI field showing portions of randpool - wmemset (tmp, L'X', ARRAYSIZE(tmp)); - tmp [ARRAYSIZE(tmp)-1] = 0; - SetWindowText (hRandPoolSys, tmp); - - NormalCursor (); - } - - else if (nCurPageNo == SYSENC_KEYS_GEN_PAGE) - { - wchar_t tmp[KEY_GUI_VIEW_SIZE+1]; - - // Attempt to wipe the GUI fields showing portions of the master and header keys - wmemset (tmp, L'X', ARRAYSIZE(tmp)); - tmp [ARRAYSIZE(tmp)-1] = 0; - SetWindowText (hMasterKey, tmp); - SetWindowText (hHeaderKey, tmp); - } - - else if (nCurPageNo == SYSENC_RESCUE_DISK_CREATION_PAGE) - { - /* Generate rescue disk for boot encryption */ - - GetWindowText (GetDlgItem (hCurPage, IDC_RESCUE_DISK_ISO_PATH), szRescueDiskISO, ARRAYSIZE (szRescueDiskISO)); - - bDontVerifyRescueDisk = GetCheckBox (hCurPage, IDC_SKIP_RESCUE_VERIFICATION); - - try - { - WaitCursor(); - BootEncObj->CreateRescueIsoImage (true, szRescueDiskISO); - - } - catch (Exception &e) - { - e.Show (hwndDlg); - NormalCursor (); - return 1; - } - -retryCDDriveCheck: - if (!bDontVerifyRescueDisk && !BootEncObj->IsCDRecorderPresent()) - { - char *multiChoiceStr[] = { 0, "CD_BURNER_NOT_PRESENT", - "CD_BURNER_NOT_PRESENT_WILL_STORE_ISO", - "CD_BURNER_NOT_PRESENT_WILL_CONNECT_LATER", - "CD_BURNER_NOT_PRESENT_CONNECTED_NOW", - 0 }; - - switch (AskMultiChoice ((void **) multiChoiceStr, FALSE, hwndDlg)) - { - case 1: - wchar_t msg[8192]; - StringCchPrintfW (msg, array_capacity (msg), GetString ("CD_BURNER_NOT_PRESENT_WILL_STORE_ISO_INFO"), szRescueDiskISO); - WarningDirect (msg, hwndDlg); - - Warning ("RESCUE_DISK_BURN_NO_CHECK_WARN", hwndDlg); - bDontVerifyRescueDisk = TRUE; - nNewPageNo = SYSENC_RESCUE_DISK_VERIFIED_PAGE; - break; - - case 2: - AbortProcessSilent(); - - case 3: - break; - - default: - goto retryCDDriveCheck; - } - } - - if (IsWindowsIsoBurnerAvailable() && !bDontVerifyRescueDisk) - Info ("RESCUE_DISK_WIN_ISOBURN_PRELAUNCH_NOTE", hwndDlg); - - NormalCursor (); - } - - else if (nCurPageNo == SYSENC_RESCUE_DISK_BURN_PAGE) - { - if (!bDontVerifyRescueDisk) - { - /* Verify that the rescue disk has been written correctly */ - - try - { - WaitCursor(); - if (!BootEncObj->VerifyRescueDisk ()) - { - wchar_t szTmp[8000]; - - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("RESCUE_DISK_CHECK_FAILED"), - IsWindowsIsoBurnerAvailable () ? L"" : GetString ("RESCUE_DISK_CHECK_FAILED_SENTENCE_APPENDIX")); - - ErrorDirect (szTmp, hwndDlg); - - NormalCursor (); -#ifndef _DEBUG - return 1; -#endif - } - } - catch (Exception &e) - { - e.Show (hwndDlg); - NormalCursor (); - return 1; - } - NormalCursor (); - } - else - { - Warning ("RESCUE_DISK_BURN_NO_CHECK_WARN", hwndDlg); - nNewPageNo = SYSENC_RESCUE_DISK_VERIFIED_PAGE; // Skip irrelevant pages - } - } - - else if (nCurPageNo == SYSENC_WIPE_MODE_PAGE - || nCurPageNo == NONSYS_INPLACE_ENC_WIPE_MODE_PAGE) - { - if (nWipeMode > 0 - && AskWarnYesNo ("WIPE_MODE_WARN", hwndDlg) == IDNO) - return 1; - } - - else if (nCurPageNo == SYSENC_PRETEST_INFO_PAGE) - { - if (LocalizationActive - && AskWarnYesNo ("PREBOOT_NOT_LOCALIZED", hwndDlg) == IDNO) - return 1; - - bConfirmQuitSysEncPretest = TRUE; - - if (!bHiddenOS) // This text is not tailored to hidden OS - TextInfoDialogBox (TC_TBXID_SYS_ENCRYPTION_PRETEST); - - if (AskWarnYesNo ("CONFIRM_RESTART", hwndDlg) == IDNO) - return 1; - - /* Install the pre-boot authentication component and initiate the system encryption pretest. - If we are creating a hidden OS, pretest is omitted and OS cloning will follow. */ - - try - { - WaitCursor(); - -#if 0 - // Make sure the Rescue Disk is not in the drive - while (BootEncObj->VerifyRescueDisk ()) - { - Error ("REMOVE_RESCUE_DISK_FROM_DRIVE"); - } -#endif - - BootEncObj->Install (bHiddenOS ? true : false); - } - catch (Exception &e) - { - e.Show (hwndDlg); - Error (bHiddenOS ? "CANNOT_INITIATE_HIDDEN_OS_CREATION" : "CANNOT_INITIATE_SYS_ENCRYPTION_PRETEST", hwndDlg); - NormalCursor (); - return 1; - } - - - /* Add the main TrueCrypt app to the system startup sequence (the TrueCrypt Background Task), which - we need e.g. for notifications about prevented hibernation, about hidden OS leak protection, about - inconsistent hidden OS installs (TrueCrypt upgraded in the decoy system but not in the hidden one), etc. - Note that this must be done before calling ChangeSystemEncryptionStatus(), which broadcasts the change, - so that the main app (if it's running with different cached settings) will not overwrite our new - settings when it exits. */ - bStartOnLogon = TRUE; - SaveSettings (NULL); - ManageStartupSeq (); - - - if (bHiddenOS) - { - /* When we are going to create a hidden OS, the system encryption status is set - to SYSENC_STATUS_PRETEST (not to any special hidden-OS status), in case the XML - configuration file and its properties somehow leaks somewhere outside the system - partition (which will be wiped later on) indicating that a hidden OS has been created - on the computer. Instead, we update our raw config flags in the master boot record - (which is also altered when our boot loader is installed). */ - - if (!ChangeSystemEncryptionStatus (SYSENC_STATUS_PRETEST) - || !ChangeHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_CLONING)) - { - ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); - Error ("CANNOT_INITIATE_HIDDEN_OS_CREATION", hwndDlg); - NormalCursor (); - return 1; - } - } - else if (!ChangeSystemEncryptionStatus (SYSENC_STATUS_PRETEST)) - { - Error ("CANNOT_INITIATE_SYS_ENCRYPTION_PRETEST", hwndDlg); - NormalCursor (); - return 1; - } - - // Add the wizard to the system startup sequence - ManageStartupSeqWiz (FALSE, L"/acsysenc"); - - EndMainDlg (MainDlg); - - try - { - BootEncObj->RestartComputer (); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - - return 1; - } - - else if (nCurPageNo == SYSENC_PRETEST_RESULT_PAGE) - { - TextInfoDialogBox (TC_TBXID_SYS_ENC_RESCUE_DISK); - - // Begin the actual encryption process - - ChangeSystemEncryptionStatus (SYSENC_STATUS_ENCRYPTING); - } - - else if (nCurPageNo == SYSENC_ENCRYPTION_PAGE - && CreateSysEncMutex ()) - { - // The 'Next' button functions as Finish or Resume - - if (SystemEncryptionStatus != SYSENC_STATUS_NONE) - { - try - { - // Resume - SysEncResume (); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - } - else - { - // Finish - PostMessage (hwndDlg, TC_APPMSG_FORMAT_USER_QUIT, 0, 0); - } - - return 1; - } - else if (nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PARTITION_SEL_PAGE) - { - nNewPageNo = NONSYS_INPLACE_ENC_TRANSFORM_PAGE - 1; // Skip irrelevant pages - } - else if (nCurPageNo == NONSYS_INPLACE_ENC_TRANSFORM_PAGE) - { - /* In-place encryption start (the 'Next' button has been clicked) */ - if (bInPlaceDecNonSys - && !bInPlaceEncNonSysResumed - && AskWarnYesNo ("NONSYS_INPLACE_ENC_CONFIRM_BACKUP", hwndDlg) == IDNO) - { - // Cancel - return 1; - } - - NonSysInplaceEncResume (); - return 1; - } - else if (nCurPageNo == NONSYS_INPLACE_ENC_TRANSFORM_FINISHED_PAGE) - { - PostMessage (hwndDlg, TC_APPMSG_FORMAT_USER_QUIT, 0, 0); - return 1; - } - else if (nCurPageNo == NONSYS_INPLACE_DEC_TRANSFORM_FINISHED_DRIVE_LETTER_PAGE) - { - BOOL bDrvLetterAssignResult = FALSE; - - int tmpDriveLetter = (int) SendMessage (GetDlgItem (hCurPage, IDC_DRIVE_LETTER_LIST), - CB_GETITEMDATA, - SendMessage (GetDlgItem (hCurPage, IDC_DRIVE_LETTER_LIST), CB_GETCURSEL, 0, 0), - 0); - - if (tmpDriveLetter < 0) - tmpDriveLetter = GetFirstAvailableDrive (); - - do - { - wchar_t szDriveLetter[] = {L'A', L':', 0 }; - wchar_t rootPath[] = {L'A', L':', L'\\', 0 }; - wchar_t uniqVolName[MAX_PATH+1] = { 0 }; - - rootPath[0] += (wchar_t) tmpDriveLetter; - szDriveLetter[0] += (wchar_t) tmpDriveLetter; - - if (DefineDosDevice (DDD_RAW_TARGET_PATH, szDriveLetter, szDiskFile)) - { - bDrvLetterAssignResult = GetVolumeNameForVolumeMountPoint (rootPath, uniqVolName, MAX_PATH); - - DefineDosDevice (DDD_RAW_TARGET_PATH|DDD_REMOVE_DEFINITION|DDD_EXACT_MATCH_ON_REMOVE, - szDriveLetter, - szDiskFile); - - if (bDrvLetterAssignResult) - { - if (SetVolumeMountPoint (rootPath, uniqVolName) == 0) - bDrvLetterAssignResult = FALSE; - } - } - - if (!bDrvLetterAssignResult) - { - if (AskErrYesNo ("ERR_CANNOT_ASSIGN_DRIVE_LETTER_NONSYS_DEC", hwndDlg) == IDNO) - break; - } - - } while (bDrvLetterAssignResult == FALSE); - - bConfirmQuit = FALSE; - - PostMessage (hwndDlg, TC_APPMSG_FORMAT_USER_QUIT, 0, 0); - return 1; - } - else if (nCurPageNo == FORMAT_PAGE) - { - /* Format start (the 'Next' button has been clicked on the Format page) */ - - if (bVolTransformThreadRunning || bVolTransformThreadToRun) - return 1; - - bVolTransformThreadCancel = FALSE; - - bVolTransformThreadToRun = TRUE; - - fileSystem = (int) SendMessage (GetDlgItem (hCurPage, IDC_FILESYS), CB_GETITEMDATA, - SendMessage (GetDlgItem (hCurPage, IDC_FILESYS), CB_GETCURSEL, 0, 0) , 0); - - clusterSize = (int) SendMessage (GetDlgItem (hCurPage, IDC_CLUSTERSIZE), CB_GETITEMDATA, - SendMessage (GetDlgItem (hCurPage, IDC_CLUSTERSIZE), CB_GETCURSEL, 0, 0) , 0); - - quickFormat = IsButtonChecked (GetDlgItem (hCurPage, IDC_QUICKFORMAT)); - - - if (!bHiddenVol && IsHiddenOSRunning()) - { - // Creating a non-hidden volume under a hidden OS - - if (fileSystem == FILESYS_NTFS || fileSystem == FILESYS_EXFAT) - { - WarningDirect ((wstring (GetString ("CANNOT_CREATE_NON_HIDDEN_NTFS_VOLUMES_UNDER_HIDDEN_OS")) - + L"\n\n" - + GetString ("NOTE_BEGINNING") - + GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO") - + L" " - + GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION")).c_str(), hwndDlg); - - if (GetVolumeDataAreaSize (FALSE, nVolumeSize) <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize() - && AskYesNo("OFFER_FAT_FORMAT_ALTERNATIVE", hwndDlg) == IDYES) - { - fileSystem = FILESYS_FAT; - SelectAlgo (GetDlgItem (hCurPage, IDC_FILESYS), (int *) &fileSystem); - } - else - { - if (GetVolumeDataAreaSize (FALSE, nVolumeSize) > TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()) - Info ("FAT_NOT_AVAILABLE_FOR_SO_LARGE_VOLUME", hwndDlg); - - bVolTransformThreadToRun = FALSE; - return 1; - } - } - } - - if (bHiddenVolHost) - { - hiddenVolHostDriveNo = -1; - nMaximumHiddenVolSize = 0; - - if (fileSystem == FILESYS_NTFS || fileSystem == FILESYS_EXFAT) - { - if (bHiddenOS && (fileSystem == FILESYS_NTFS) - && (double) nVolumeSize / GetSystemPartitionSize() < MIN_HIDDENOS_DECOY_PARTITION_SIZE_RATIO_NTFS) - { - Error("OUTER_VOLUME_TOO_SMALL_FOR_HIDDEN_OS_NTFS", hwndDlg); - - if (GetVolumeDataAreaSize (FALSE, nVolumeSize) <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize() - && AskYesNo("OFFER_FAT_FORMAT_ALTERNATIVE", hwndDlg) == IDYES) - { - fileSystem = FILESYS_FAT; - SelectAlgo (GetDlgItem (hCurPage, IDC_FILESYS), (int *) &fileSystem); - } - else - { - if (GetVolumeDataAreaSize (FALSE, nVolumeSize) > TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()) - Info ("FAT_NOT_AVAILABLE_FOR_SO_LARGE_VOLUME", hwndDlg); - - bVolTransformThreadToRun = FALSE; - return 1; - } - } - - if (fileSystem == FILESYS_NTFS || fileSystem == FILESYS_EXFAT) // The file system may have been changed in the previous block - { - if (nCurrentOS == WIN_2000) - { - Error("HIDDEN_VOL_HOST_UNSUPPORTED_FILESYS_WIN2000", hwndDlg); - bVolTransformThreadToRun = FALSE; - return 1; - } - else if ((fileSystem == FILESYS_NTFS) && (GetVolumeDataAreaSize (FALSE, nVolumeSize) <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()) - && AskYesNo("HIDDEN_VOL_HOST_NTFS_ASK", hwndDlg) == IDNO) - { - bVolTransformThreadToRun = FALSE; - return 1; - } - } - } - } - else if (bHiddenVol) - { - // Hidden volume is always quick-formatted (if, however, the meaning of quickFormat is - // whether to create a sparse file, it must be set to FALSE). - quickFormat = !bSparseFileSwitch; - } - - - if (fileSystem == FILESYS_FAT - && nNeedToStoreFilesOver4GB == 1 - && AskWarnNoYes("CONFIRM_FAT_FOR_FILES_OVER_4GB", hwndDlg) == IDNO) - { - bVolTransformThreadToRun = FALSE; - return 1; - } - - EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDHELP), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE); - EnableWindow (GetDlgItem (hCurPage, IDC_QUICKFORMAT), FALSE); - EnableWindow (GetDlgItem (hCurPage, IDC_CLUSTERSIZE), FALSE); - EnableWindow (GetDlgItem (hCurPage, IDC_FILESYS), FALSE); - EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); - SetFocus (GetDlgItem (hCurPage, IDC_ABORT_BUTTON)); - - // Increase cluster size if it's too small for this volume size (causes size of - // free space to be 0). Note that the below constant 0x2000000 is based on - // results of tests performed under Windows XP. - if (fileSystem == FILESYS_FAT && clusterSize > 0) - { - BOOL fixed = FALSE; - while (clusterSize < 128 - && nVolumeSize / (clusterSize * GetFormatSectorSize()) > 0x2000000) - { - clusterSize *= 2; - fixed = TRUE; - } - if (fixed) - MessageBoxW (hwndDlg, GetString ("CLUSTER_TOO_SMALL"), lpszTitle, MB_ICONWARNING); - } - - LastDialogId = "FORMAT_IN_PROGRESS"; - ArrowWaitCursor (); - _beginthread (volTransformThreadFunction, 0, MainDlg); - - return 1; - } - - else if (nCurPageNo == FORMAT_FINISHED_PAGE) - { - if (!bHiddenVol || bHiddenVolFinished) - { - /* Wizard loop restart */ - - if (bHiddenOS) - { - if (!ChangeWizardMode (WIZARD_MODE_SYS_DEVICE)) - return 1; - - // Hidden volume for hidden OS has been created. Now we will prepare our boot loader - // that will handle the OS cloning. - try - { - WaitCursor(); - - BootEncObj->PrepareHiddenOSCreation (nVolumeEA, FIRST_MODE_OF_OPERATION_ID, hash_algo); - } - catch (Exception &e) - { - e.Show (MainDlg); - NormalCursor(); - return 1; - } - - bHiddenVol = FALSE; - - LoadPage (hwndDlg, SYSENC_PRETEST_INFO_PAGE); - } - else - LoadPage (hwndDlg, INTRO_PAGE); - - SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); - bHiddenVolFinished = FALSE; - WipePasswordsAndKeyfiles (); - - return 1; - } - else - { - /* We're going to scan the bitmap of the hidden volume host (in the non-Direct hidden volume wizard mode) */ - int retCode; - WaitCursor (); - - if (hiddenVolHostDriveNo != -1) // If the hidden volume host is mounted - { - BOOL tmp_result; - - // Dismount the hidden volume host (in order to remount it as read-only subsequently) - CloseVolumeExplorerWindows (hwndDlg, hiddenVolHostDriveNo); - while (!(tmp_result = UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE))) - { - if (MessageBoxW (hwndDlg, GetString ("CANT_DISMOUNT_OUTER_VOL"), lpszTitle, MB_RETRYCANCEL | MB_ICONERROR | MB_SETFOREGROUND) != IDRETRY) - { - // Cancel - NormalCursor(); - return 1; - } - } - if (tmp_result) // If dismounted - hiddenVolHostDriveNo = -1; - } - - if (hiddenVolHostDriveNo < 0) // If the hidden volume host is not mounted - { - // Remount the hidden volume host as read-only (to ensure consistent and secure - // results of the volume bitmap scanning) - switch (MountHiddenVolHost (hwndDlg, szDiskFile, &hiddenVolHostDriveNo, &volumePassword, hash_algo, volumePim, TRUE)) - { - case ERR_NO_FREE_DRIVES: - MessageBoxW (hwndDlg, GetString ("NO_FREE_DRIVE_FOR_OUTER_VOL"), lpszTitle, ICON_HAND); - NormalCursor (); - return 1; - - case ERR_VOL_MOUNT_FAILED: - case ERR_PASSWORD_WRONG: - NormalCursor (); - return 1; - - case 0: - - /* Hidden volume host successfully mounted as read-only */ - - // Verify that the outer volume contains a suitable file system, retrieve cluster size, and - // scan the volume bitmap - if (!IsAdmin () && IsUacSupported ()) - retCode = UacAnalyzeHiddenVolumeHost (hwndDlg, &hiddenVolHostDriveNo, GetVolumeDataAreaSize (FALSE, nHiddenVolHostSize), &realClusterSize, &nbrFreeClusters); - else - retCode = AnalyzeHiddenVolumeHost (hwndDlg, &hiddenVolHostDriveNo, GetVolumeDataAreaSize (FALSE, nHiddenVolHostSize), &realClusterSize, &nbrFreeClusters); - - switch (retCode) - { - case -1: // Fatal error - CloseVolumeExplorerWindows (hwndDlg, hiddenVolHostDriveNo); - - if (UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE)) - hiddenVolHostDriveNo = -1; - - AbortProcessSilent (); - break; - - case 0: // Unsupported file system (or other non-fatal error which has already been reported) - NormalCursor (); - return 1; - - case 1: // Success - { - BOOL tmp_result; - - // Determine the maximum possible size of the hidden volume - if (DetermineMaxHiddenVolSize (hwndDlg) < 1) - { - NormalCursor (); - goto ovf_end; - } - - /* Maximum possible size of the hidden volume successfully determined */ - - // Dismount the hidden volume host - while (!(tmp_result = UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE))) - { - if (MessageBoxW (hwndDlg, GetString ("CANT_DISMOUNT_OUTER_VOL"), lpszTitle, MB_RETRYCANCEL) != IDRETRY) - { - // Cancel - NormalCursor (); - goto ovf_end; - } - } - - // Prevent having to recreate the outer volume due to inadvertent exit - bConfirmQuit = TRUE; - - hiddenVolHostDriveNo = -1; - - nNewPageNo = HIDDEN_VOL_HOST_PRE_CIPHER_PAGE; - - // Clear the outer volume password - WipePasswordsAndKeyfiles (); - - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), TRUE); - NormalCursor (); - - } - break; - } - break; - } - } - } - } - - else if (nCurPageNo == DEVICE_WIPE_PAGE) - { - if (AskWarnOkCancel (bHiddenOS && IsHiddenOSRunning() ? "CONFIRM_WIPE_START_DECOY_SYS_PARTITION" : "CONFIRM_WIPE_START", hwndDlg) == IDOK) - { - WipeStart (); - ArrowWaitCursor(); - } - return 1; - } - - LoadPage (hwndDlg, nNewPageNo + 1); -ovf_end: - return 1; - } - else if (lw == IDC_PREV) - { - if (nCurPageNo == SYSENC_SPAN_PAGE) - { - // Skip irrelevant pages when going back - if (!bHiddenOS) - nNewPageNo = SYSENC_TYPE_PAGE + 1; - } - if (nCurPageNo == SYSENC_MULTI_BOOT_MODE_PAGE) - { - // Skip the drive analysis page(s) or other irrelevant pages when going back - if (bHiddenOS) - nNewPageNo = SYSENC_HIDDEN_OS_REQ_CHECK_PAGE + 1; - else if (bWholeSysDrive) - nNewPageNo = SYSENC_PRE_DRIVE_ANALYSIS_PAGE + 1; - else - nNewPageNo = SYSENC_SPAN_PAGE + 1; - } - else if (nCurPageNo == SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE) - { - if (SysEncMultiBootCfg.NumberOfSysDrives == 1) - { - // We can skip SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE (it is implied that there are multiple systems on the drive) - nNewPageNo = SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE + 1; - } - } - else if (nCurPageNo == HIDDEN_VOL_HOST_PRE_CIPHER_PAGE) - { - if (bHiddenOS) - { - if (!ChangeWizardMode (WIZARD_MODE_SYS_DEVICE)) - { - NormalCursor (); - return 1; - } - - // Skip irrelevant pages. - // Note that we're ignoring nMultiBoot here, as the multi-boot question pages are skipped - // when creating a hidden OS (only a single message box is displayed with requirements). - nNewPageNo = SYSENC_MULTI_BOOT_MODE_PAGE + 1; - } - else - { - nNewPageNo = VOLUME_LOCATION_PAGE + 1; - } - } - else if (nCurPageNo == HIDDEN_VOL_WIZARD_MODE_PAGE) - { - if (IsButtonChecked (GetDlgItem (hCurPage, IDC_HIDVOL_WIZ_MODE_DIRECT))) - bHiddenVolDirect = TRUE; - else - bHiddenVolDirect = FALSE; - } - else if (nCurPageNo == VOLUME_TYPE_PAGE) - { - if (WizardMode != WIZARD_MODE_SYS_DEVICE) - nNewPageNo = INTRO_PAGE + 1; // Skip irrelevant pages - } - else if (nCurPageNo == VOLUME_LOCATION_PAGE) - { - BOOL tmpbDevice; - - GetWindowText (GetDlgItem (hCurPage, IDC_COMBO_BOX), szFileName, ARRAYSIZE (szFileName)); - CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice); - - if (tmpbDevice == bDevice) - { - MoveEditToCombo (GetDlgItem (hCurPage, IDC_COMBO_BOX), bHistory); - SaveSettings (hCurPage); - } - - if (!bHiddenVol) - nNewPageNo = VOLUME_TYPE_PAGE + 1; // Skip the hidden volume creation wizard mode selection - } - - else if (nCurPageNo == CIPHER_PAGE) - { - LPARAM nIndex; - nIndex = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETCURSEL, 0, 0); - nVolumeEA = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETITEMDATA, nIndex, 0); - - nIndex = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX_HASH_ALGO), CB_GETCURSEL, 0, 0); - hash_algo = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX_HASH_ALGO), CB_GETITEMDATA, nIndex, 0); - - RandSetHashFunction (hash_algo); - - if (WizardMode == WIZARD_MODE_SYS_DEVICE) - { - if (nMultiBoot > 1) - nNewPageNo = SYSENC_MULTI_BOOT_OUTCOME_PAGE + 1; // Skip irrelevant pages - else - nNewPageNo = SYSENC_MULTI_BOOT_MODE_PAGE + 1; // Skip irrelevant pages - } - else if (!bHiddenVol) - nNewPageNo = (bDevice ? DEVICE_TRANSFORM_MODE_PAGE : VOLUME_LOCATION_PAGE) + 1; - else if (bHiddenVolHost) - nNewPageNo = HIDDEN_VOL_HOST_PRE_CIPHER_PAGE + 1; // Skip the info on the hidden volume - } - - else if (nCurPageNo == SIZE_PAGE) - { - VerifySizeAndUpdate (hCurPage, TRUE); - } - - else if (nCurPageNo == FILESYS_PAGE) - { - if (nNeedToStoreFilesOver4GB != Get2RadButtonPageAnswer()) - fileSystem = FILESYS_NONE; // The user may have gone back and changed the answer, so default file system must be reselected - - nNeedToStoreFilesOver4GB = Get2RadButtonPageAnswer(); - - nNewPageNo = (PimEnable? PIM_PAGE : PASSWORD_PAGE) + 1; // Skip PIM page if it is not enabled - } - - else if (nCurPageNo == PASSWORD_PAGE) - { - // Store the password in case we need to restore it after keyfile is applied to it - GetPassword (hCurPage, IDC_PASSWORD, szRawPassword, sizeof (szRawPassword), FALSE); - - VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (MainDlg, IDC_NEXT), - GetDlgItem (hCurPage, IDC_PASSWORD), - GetDlgItem (hCurPage, IDC_VERIFY), - volumePassword.Text, - szVerify, - KeyFilesEnable && FirstKeyFile!=NULL && !SysEncInEffect ()); - - volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); - - - nNewPageNo = SIZE_PAGE + 1; // Skip the hidden volume host password page - - if (SysEncInEffect ()) - { - nNewPageNo = CIPHER_PAGE + 1; // Skip irrelevant pages - - KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); - - if (bKeyboardLayoutChanged) - { - // Restore the original keyboard layout - if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) - Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); - else - bKeyboardLayoutChanged = FALSE; - } - } - else if (bInPlaceEncNonSys) - nNewPageNo = CIPHER_PAGE + 1; - } - - else if (nCurPageNo == PIM_PAGE) - { - volumePim = GetPim (hCurPage, IDC_PIM); - } - - else if (nCurPageNo == HIDDEN_VOL_HOST_PASSWORD_PAGE - || nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) - { - // Store the password in case we need to restore it after keyfile is applied to it - GetPassword (hCurPage, IDC_PASSWORD_DIRECT, szRawPassword, MAX_PASSWORD + 1, FALSE); - - memcpy (volumePassword.Text, szRawPassword, MAX_PASSWORD + 1); - volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); - - if (!bInPlaceEncNonSys) - nNewPageNo = VOLUME_LOCATION_PAGE + 1; - } - - else if (nCurPageNo == SYSENC_COLLECTING_RANDOM_DATA_PAGE - || nCurPageNo == NONSYS_INPLACE_ENC_RAND_DATA_PAGE) - { - wchar_t tmp[RANDPOOL_DISPLAY_SIZE+1]; - - KillTimer (hwndDlg, TIMER_ID_RANDVIEW); - - // Attempt to wipe the GUI field showing portions of randpool - wmemset (tmp, L'X', ARRAYSIZE(tmp)); - tmp [ARRAYSIZE(tmp)-1] = 0; - SetWindowText (hRandPoolSys, tmp); - - nNewPageNo = (PimEnable? PIM_PAGE : PASSWORD_PAGE) + 1; // Skip irrelevant pages - } - - else if (nCurPageNo == SYSENC_KEYS_GEN_PAGE) - { - wchar_t tmp[KEY_GUI_VIEW_SIZE+1]; - - // Attempt to wipe the GUI fields showing portions of the master and header keys - wmemset (tmp, L'X', ARRAYSIZE(tmp)); - tmp [ARRAYSIZE(tmp)-1] = 0; - SetWindowText (hMasterKey, tmp); - SetWindowText (hHeaderKey, tmp); - } - - else if (nCurPageNo == SYSENC_WIPE_MODE_PAGE) - { - if (bDontVerifyRescueDisk) - nNewPageNo = SYSENC_RESCUE_DISK_VERIFIED_PAGE; // Skip irrelevant pages - } - - else if (nCurPageNo == FORMAT_PAGE) - { - wchar_t tmp[RNG_POOL_SIZE*2+1]; - - KillTimer (hwndDlg, TIMER_ID_RANDVIEW); - - // Attempt to wipe the GUI fields showing portions of randpool, of the master and header keys - wmemset (tmp, L'X', ARRAYSIZE(tmp)); - tmp [ARRAYSIZE(tmp)-1] = 0; - SetWindowText (hRandPool, tmp); - SetWindowText (hMasterKey, tmp); - SetWindowText (hHeaderKey, tmp); - - if (WizardMode != WIZARD_MODE_SYS_DEVICE) - { - // Skip irrelevant pages - - if (FileSize4GBLimitQuestionNeeded () - && !CreatingHiddenSysVol() // If we're creating a hidden volume for a hidden OS, we don't need to format it with any filesystem (the entire OS will be copied to the hidden volume sector by sector). - && !bInPlaceEncNonSys) - { - nNewPageNo = FILESYS_PAGE + 1; - } - else - nNewPageNo = (PimEnable? PIM_PAGE : PASSWORD_PAGE) + 1; - } - } - - LoadPage (hwndDlg, nNewPageNo - 1); - - return 1; - } - - return 0; - - case WM_ENDSESSION: - EndMainDlg (MainDlg); - localcleanup (); - return 0; - - case WM_CLOSE: - PostMessage (hwndDlg, TC_APPMSG_FORMAT_USER_QUIT, 0, 0); - return 1; - } - - return 0; -} - -void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) -{ - wchar_t **lpszCommandLineArgs = NULL; /* Array of command line arguments */ - int nNoCommandLineArgs; /* The number of arguments in the array */ - - if (_wcsicmp (lpszCommandLine, L"-Embedding") == 0) - { - ComServerMode = TRUE; - return; - } - - /* Extract command line arguments */ - nNoCommandLineArgs = Win32CommandLine (&lpszCommandLineArgs); - if (nNoCommandLineArgs > 0) - { - int i; - - for (i = 0; i < nNoCommandLineArgs; i++) - { - enum - { - OptionHistory, - OptionNoIsoCheck, - OptionQuit, - OptionTokenLib, - CommandResumeSysEncLogOn, - CommandResumeSysEnc, - CommandDecryptSysEnc, - CommandEncDev, - CommandHiddenSys, - CommandResumeNonSysInplaceLogOn, - CommandResumeHiddenSys, - CommandSysEnc, - CommandInplaceDec, - CommandResumeInplaceDec, - CommandResumeInplace, - OptionEncryption, - OptionFilesystem, - OptionPkcs5, - OptionPassword, - OptionPim, - OptionSize, - OptionCreate, - OptionSilent, - OptionDynamic, - OptionForce, - }; - - argument args[]= - { - // Public - { OptionHistory, L"/history", L"/h", FALSE }, - { OptionNoIsoCheck, L"/noisocheck", L"/n", FALSE }, - { OptionTokenLib, L"/tokenlib", NULL, FALSE }, - { OptionQuit, L"/quit", L"/q", FALSE }, - { OptionEncryption, L"/encryption", NULL , FALSE }, - { OptionFilesystem, L"/filesystem", NULL , FALSE }, - { OptionPkcs5, L"/hash", NULL , FALSE }, - { OptionPassword, L"/password", NULL, FALSE }, - { OptionPim, L"/pim", NULL, FALSE }, - { OptionSize, L"/size", NULL, FALSE }, - { OptionCreate, L"/create", NULL, FALSE }, - { OptionSilent, L"/silent", NULL, FALSE }, - { OptionDynamic, L"/dynamic", NULL, FALSE }, - { OptionForce, L"/force", NULL, FALSE }, - - // Internal - { CommandResumeSysEncLogOn, L"/acsysenc", L"/a", TRUE }, - { CommandResumeSysEnc, L"/csysenc", L"/c", TRUE }, - { CommandDecryptSysEnc, L"/dsysenc", L"/d", TRUE }, - { CommandEncDev, L"/encdev", L"/e", TRUE }, - { CommandHiddenSys, L"/isysenc", L"/i", TRUE }, - { CommandResumeNonSysInplaceLogOn, L"/prinplace", L"/p", TRUE }, - { CommandResumeHiddenSys, L"/risysenc", L"/r", TRUE }, - { CommandSysEnc, L"/sysenc", L"/s", TRUE }, - { CommandInplaceDec, L"/inplacedec", NULL, TRUE }, - { CommandResumeInplaceDec, L"/resumeinplacedec",NULL, TRUE }, - { CommandResumeInplace, L"/zinplace", L"/z", TRUE } - }; - - argumentspec as; - - int x; - - if (lpszCommandLineArgs[i] == NULL) - continue; - - as.args = args; - as.arg_cnt = sizeof(args)/ sizeof(args[0]); - - x = GetArgumentID (&as, lpszCommandLineArgs[i]); - - switch (x) - { - case OptionCreate: - { - DirectCreationMode = TRUE; - - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, - szFileName, ARRAYSIZE (szFileName))) - { - RelativePath2Absolute (szFileName); - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - break; - case OptionEncryption: - { - wchar_t szTmp[64] = {0}; - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, - &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) - { - CmdVolumeEA = EAGetByName (szTmp); - if (CmdVolumeEA == 0) - AbortProcess ("COMMAND_LINE_ERROR"); - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - break; - case OptionFilesystem: - { - wchar_t szTmp[8] = {0}; - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, - &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) - { - if (_wcsicmp(szTmp, L"NONE") == 0) - CmdVolumeFilesystem = FILESYS_NONE; - else if (_wcsicmp(szTmp, L"FAT32") == 0 || _wcsicmp(szTmp, L"FAT") == 0) - CmdVolumeFilesystem = FILESYS_FAT; - else if (_wcsicmp(szTmp, L"NTFS") == 0) - CmdVolumeFilesystem = FILESYS_NTFS; - else if (IsOSVersionAtLeast (WIN_VISTA, 1) && _wcsicmp(szTmp, L"EXFAT") == 0) - CmdVolumeFilesystem = FILESYS_EXFAT; - else - { - AbortProcess ("COMMAND_LINE_ERROR"); - } - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - break; - case OptionPassword: - { - wchar_t szTmp[MAX_PASSWORD + 1]; - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, - szTmp, ARRAYSIZE (szTmp))) - { - int iLen = WideCharToMultiByte (CP_UTF8, 0, szTmp, -1, (LPSTR) CmdVolumePassword.Text, MAX_PASSWORD + 1, NULL, NULL); - burn (szTmp, sizeof (szTmp)); - if (iLen > 0) - CmdVolumePassword.Length = (unsigned __int32) (iLen - 1); - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - break; - case OptionPkcs5: - { - wchar_t szTmp[32] = {0}; - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, - &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) - { - if (_wcsicmp(szTmp, L"sha512") == 0 || _wcsicmp(szTmp, L"sha-512") == 0) - CmdVolumePkcs5 = SHA512; - else if (_wcsicmp(szTmp, L"whirlpool") == 0) - CmdVolumePkcs5 = WHIRLPOOL; - else if (_wcsicmp(szTmp, L"sha256") == 0 || _wcsicmp(szTmp, L"sha-256") == 0) - CmdVolumePkcs5 = SHA256; - else if (_wcsicmp(szTmp, L"ripemd160") == 0 || _wcsicmp(szTmp, L"ripemd-160") == 0) - CmdVolumePkcs5 = RIPEMD160; - else - { - CmdVolumePkcs5 = 0; - AbortProcess ("COMMAND_LINE_ERROR"); - } - - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - break; - - case OptionPim: - { - wchar_t szTmp[32] = {0}; - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, - &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) - { - wchar_t* endPtr = NULL; - CmdVolumePim = (int) wcstol(szTmp, &endPtr, 0); - if (CmdVolumePim < 0 || CmdVolumePim > MAX_PIM_VALUE || endPtr == szTmp || *endPtr != L'\0') - { - CmdVolumePim = 0; - AbortProcess ("COMMAND_LINE_ERROR"); - } - - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - break; - case OptionSilent: - Silent = TRUE; - break; - case OptionDynamic: - CmdSparseFileSwitch = TRUE; - break; - case OptionForce: - bForceOperation = TRUE; - break; - case OptionSize: - { - wchar_t szTmp[32] = {0}; - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, - &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp)) - && (wcslen (szTmp) >= 2) - ) - { - /* size can be expressed in bytes or with suffixes K, M,G or T - * to indicate the unit to use - */ - unsigned __int64 multiplier; - wchar_t* endPtr = NULL; - wchar_t lastChar = szTmp [wcslen (szTmp) - 1]; - if (lastChar >= L'0' && lastChar <= L'9') - multiplier = 1; - else if (lastChar == L'K' || lastChar == L'k') - multiplier = BYTES_PER_KB; - else if (lastChar == L'M' || lastChar == L'm') - multiplier = BYTES_PER_MB; - else if (lastChar == L'G' || lastChar == L'g') - multiplier = BYTES_PER_GB; - else if (lastChar == L'T' || lastChar == L't') - multiplier = BYTES_PER_TB; - else - AbortProcess ("COMMAND_LINE_ERROR"); - - if (multiplier != 1) - szTmp [wcslen (szTmp) - 1] = 0; - - CmdVolumeFileSize = _wcstoui64(szTmp, &endPtr, 0); - if (CmdVolumeFileSize == 0 || CmdVolumeFileSize == _UI64_MAX - || endPtr == szTmp || *endPtr != L'\0') - { - AbortProcess ("COMMAND_LINE_ERROR"); - } - - CmdVolumeFileSize *= multiplier; - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - break; - case CommandSysEnc: - // Encrypt system partition/drive (passed by Mount if system encryption hasn't started or to reverse decryption) - - // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption - if (CreateSysEncMutex ()) - { - bDirectSysEncMode = TRUE; - bDirectSysEncModeCommand = SYSENC_COMMAND_ENCRYPT; - ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); - } - else - { - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); - exit(0); - } - - break; - - case CommandDecryptSysEnc: - // Decrypt system partition/drive (passed by Mount, also to reverse encryption in progress, when paused) - - // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption - if (CreateSysEncMutex ()) - { - bDirectSysEncMode = TRUE; - bDirectSysEncModeCommand = SYSENC_COMMAND_DECRYPT; - ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); - } - else - { - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); - exit(0); - } - break; - - case CommandHiddenSys: - // Create a hidden operating system (passed by Mount when the user selects System -> Create Hidden Operating System) - - // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption - if (CreateSysEncMutex ()) - { - bDirectSysEncMode = TRUE; - bDirectSysEncModeCommand = SYSENC_COMMAND_CREATE_HIDDEN_OS; - ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); - } - else - { - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); - exit(0); - } - - break; - - case CommandResumeHiddenSys: - // Resume process of creation of a hidden operating system (passed by Wizard when the user needs to UAC-elevate the whole wizard process) - - // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption - if (CreateSysEncMutex ()) - { - bDirectSysEncMode = TRUE; - bDirectSysEncModeCommand = SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV; - ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); - } - else - { - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); - exit(0); - } - - break; - - case CommandResumeSysEnc: - // Resume previous system-encryption operation (passed by Mount) e.g. encryption, decryption, or pretest - - // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption - if (CreateSysEncMutex ()) - { - bDirectSysEncMode = TRUE; - bDirectSysEncModeCommand = SYSENC_COMMAND_RESUME; - ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); - } - else - { - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); - exit(0); - } - break; - - case CommandResumeSysEncLogOn: - // Same as csysenc but passed only by the system (from the startup sequence) - - // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption - if (CreateSysEncMutex ()) - { - bDirectSysEncMode = TRUE; - bDirectSysEncModeCommand = SYSENC_COMMAND_STARTUP_SEQ_RESUME; - ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); - } - else - { - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); - exit(0); - } - break; - - case CommandEncDev: - // Resume process of creation of a non-sys-device-hosted volume (passed by Wizard when the user needs to UAC-elevate) - DirectDeviceEncMode = TRUE; - break; - - case CommandInplaceDec: - // Start (not resume) decrypting the specified non-system volume in place - { - wchar_t szTmp [TC_MAX_PATH + 8000] = {0}; - - GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp)); - - if (wcslen (szTmp) < 1) - { - // No valid volume path specified as command-line parameter - AbortProcess ("ERR_PARAMETER_INCORRECT"); - } - - memset (szFileName, 0, sizeof (szFileName)); - StringCbCopyW (szFileName, sizeof (szFileName), szTmp); - DirectNonSysInplaceDecStartMode = TRUE; - } - break; - - case CommandResumeInplace: - // Resume interrupted process of non-system in-place encryption of a partition - DirectNonSysInplaceEncResumeMode = TRUE; - break; - - case CommandResumeInplaceDec: - // Resume interrupted process of non-system in-place decryption of a partition - DirectNonSysInplaceDecResumeMode = TRUE; - break; - - case CommandResumeNonSysInplaceLogOn: - // Ask the user whether to resume interrupted process of non-system in-place encryption of a partition - // This switch is passed only by the system (from the startup sequence). - DirectPromptNonSysInplaceEncResumeMode = TRUE; - break; - - case OptionNoIsoCheck: - bDontVerifyRescueDisk = TRUE; - break; - - case OptionHistory: - { - wchar_t szTmp[8] = {0}; - bHistory = bHistoryCmdLine = TRUE; - - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, - szTmp, ARRAYSIZE (szTmp))) - { - if (!_wcsicmp(szTmp,L"y") || !_wcsicmp(szTmp,L"yes")) - { - bHistory = TRUE; - } - - else if (!_wcsicmp(szTmp,L"n") || !_wcsicmp(szTmp,L"no")) - { - bHistory = FALSE; - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - } - break; - - case OptionTokenLib: - if (GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, SecurityTokenLibraryPath, ARRAYSIZE (SecurityTokenLibraryPath)) == HAS_ARGUMENT) - InitSecurityTokenLibrary(hwndDlg); - else - AbortProcess ("COMMAND_LINE_ERROR"); - - break; - - case OptionQuit: - { - // Used to indicate non-install elevation - wchar_t szTmp[32]; - if (GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp)) != HAS_ARGUMENT) - AbortProcess ("COMMAND_LINE_ERROR"); - } - break; - - default: - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_COMMANDHELP_DLG), hwndDlg, (DLGPROC) - CommandHelpDlgProc, (LPARAM) &as); - - exit(0); - } - } - } - - /* Free up the command line arguments */ - while (--nNoCommandLineArgs >= 0) - { - free (lpszCommandLineArgs[nNoCommandLineArgs]); - } - - if (lpszCommandLineArgs) - free (lpszCommandLineArgs); -} - - -int DetermineMaxHiddenVolSize (HWND hwndDlg) -{ - __int64 nbrReserveBytes; - - if (nbrFreeClusters * realClusterSize < TC_MIN_HIDDEN_VOLUME_SIZE) - { - MessageBoxW (hwndDlg, GetString ("NO_SPACE_FOR_HIDDEN_VOL"), lpszTitle, ICON_HAND); - UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE); - AbortProcessSilent (); - } - - // Add a reserve (in case the user mounts the outer volume and creates new files - // on it by accident or OS writes some new data behind his or her back, such as - // System Restore etc.) - nbrReserveBytes = GetVolumeDataAreaSize (FALSE, nHiddenVolHostSize) / 200; - if (nbrReserveBytes > BYTES_PER_MB * 10) - nbrReserveBytes = BYTES_PER_MB * 10; - - // Compute the final value - - nMaximumHiddenVolSize = nbrFreeClusters * realClusterSize - TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE - nbrReserveBytes; - nMaximumHiddenVolSize -= nMaximumHiddenVolSize % realClusterSize; // Must be a multiple of the sector size - - if (nMaximumHiddenVolSize < TC_MIN_HIDDEN_VOLUME_SIZE) - { - MessageBoxW (hwndDlg, GetString ("NO_SPACE_FOR_HIDDEN_VOL"), lpszTitle, ICON_HAND); - UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE); - AbortProcessSilent (); - } - - // Prepare the hidden volume size parameters - if (nMaximumHiddenVolSize < BYTES_PER_MB) - nMultiplier = BYTES_PER_KB; - else if (nMaximumHiddenVolSize < BYTES_PER_GB) - nMultiplier = BYTES_PER_MB; - else if (nMaximumHiddenVolSize < BYTES_PER_TB) - nMultiplier = BYTES_PER_GB; - else - nMultiplier = BYTES_PER_TB; - - nUIVolumeSize = 0; // Set the initial value for the hidden volume size input field to the max - nVolumeSize = nUIVolumeSize * nMultiplier; // Chop off possible remainder - - return 1; -} - - -// Tests whether the file system of the given volume is suitable to host a hidden volume, -// retrieves the cluster size, and scans the volume cluster bitmap. In addition, checks -// the TrueCrypt volume format version and the type of volume. -int AnalyzeHiddenVolumeHost (HWND hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *pnbrFreeClusters) -{ - HANDLE hDevice; - DWORD bytesReturned; - DWORD dwSectorsPerCluster, dwBytesPerSector, dwNumberOfFreeClusters, dwTotalNumberOfClusters; - DWORD dwResult; - int result; - wchar_t szFileSystemNameBuffer[256]; - wchar_t tmpPath[7] = {L'\\',L'\\',L'.',L'\\',(wchar_t) *driveNo + L'A',L':',0}; - wchar_t szRootPathName[4] = {(wchar_t) *driveNo + L'A', L':', L'\\', 0}; - BYTE readBuffer[TC_MAX_VOLUME_SECTOR_SIZE * 2]; - LARGE_INTEGER offset, offsetNew; - VOLUME_PROPERTIES_STRUCT volProp; - - memset (&volProp, 0, sizeof(volProp)); - volProp.driveNo = *driveNo; - if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &volProp, sizeof (volProp), &volProp, sizeof (volProp), &dwResult, NULL) || dwResult == 0) - { - handleWin32Error (hwndDlg, SRC_POS); - Error ("CANT_ACCESS_OUTER_VOL", hwndDlg); - goto efsf_error; - } - - if (volProp.volFormatVersion < TC_VOLUME_FORMAT_VERSION) - { - // We do not support creating hidden volumes within volumes created by TrueCrypt 5.1a or earlier. - Error ("ERR_VOL_FORMAT_BAD", hwndDlg); - return 0; - } - - if (volProp.hiddenVolume) - { - // The user entered a password for a hidden volume - Error ("ERR_HIDDEN_NOT_NORMAL_VOLUME", hwndDlg); - return 0; - } - - if (volProp.volumeHeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC - || volProp.volumeHeaderFlags & TC_HEADER_FLAG_ENCRYPTED_SYSTEM) - { - Warning ("ERR_HIDDEN_VOL_HOST_ENCRYPTED_INPLACE", hwndDlg); - return 0; - } - - hDevice = CreateFile (tmpPath, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (hDevice == INVALID_HANDLE_VALUE) - { - MessageBoxW (hwndDlg, GetString ("CANT_ACCESS_OUTER_VOL"), lpszTitle, ICON_HAND); - goto efsf_error; - } - - offset.QuadPart = 0; - - if (SetFilePointerEx (hDevice, offset, &offsetNew, FILE_BEGIN) == 0) - { - handleWin32Error (hwndDlg, SRC_POS); - goto efs_error; - } - - result = ReadFile (hDevice, &readBuffer, TC_MAX_VOLUME_SECTOR_SIZE, &bytesReturned, NULL); - - if (result == 0) - { - handleWin32Error (hwndDlg, SRC_POS); - MessageBoxW (hwndDlg, GetString ("CANT_ACCESS_OUTER_VOL"), lpszTitle, ICON_HAND); - goto efs_error; - } - - CloseHandle (hDevice); - hDevice = INVALID_HANDLE_VALUE; - - // Determine file system type - - GetVolumeInformation(szRootPathName, NULL, 0, NULL, NULL, NULL, szFileSystemNameBuffer, ARRAYSIZE(szFileSystemNameBuffer)); - - // The Windows API sometimes fails to indentify the file system correctly so we're using "raw" analysis too. - if (!wcsncmp (szFileSystemNameBuffer, L"FAT", 3) - || (readBuffer[0x36] == 'F' && readBuffer[0x37] == 'A' && readBuffer[0x38] == 'T') - || (readBuffer[0x52] == 'F' && readBuffer[0x53] == 'A' && readBuffer[0x54] == 'T')) - { - // FAT12/FAT16/FAT32 - - // Retrieve the cluster size - *realClusterSize = ((int) readBuffer[0xb] + ((int) readBuffer[0xc] << 8)) * (int) readBuffer[0xd]; - - // Get the map of the clusters that are free and in use on the outer volume. - // The map will be scanned to determine the size of the uninterrupted block of free - // space (provided there is any) whose end is aligned with the end of the volume. - // The value will then be used to determine the maximum possible size of the hidden volume. - - return ScanVolClusterBitmap (hwndDlg, - driveNo, - hiddenVolHostSize / *realClusterSize, - pnbrFreeClusters); - } - else if (!wcsncmp (szFileSystemNameBuffer, L"NTFS", 4) || !_wcsnicmp (szFileSystemNameBuffer, L"exFAT", 5)) - { - // NTFS - bool bIsNtfs = (0 == wcsncmp (szFileSystemNameBuffer, L"NTFS", 4)); - - if (nCurrentOS == WIN_2000) - { - Error("HIDDEN_VOL_HOST_UNSUPPORTED_FILESYS_WIN2000", hwndDlg); - return 0; - } - - if (bIsNtfs && bHiddenVolDirect && GetVolumeDataAreaSize (FALSE, hiddenVolHostSize) <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()) - Info ("HIDDEN_VOL_HOST_NTFS", hwndDlg); - - if (!GetDiskFreeSpace(szRootPathName, - &dwSectorsPerCluster, - &dwBytesPerSector, - &dwNumberOfFreeClusters, - &dwTotalNumberOfClusters)) - { - handleWin32Error (hwndDlg, SRC_POS); - Error ("CANT_GET_OUTER_VOL_INFO", hwndDlg); - return -1; - }; - - *realClusterSize = dwBytesPerSector * dwSectorsPerCluster; - - // Get the map of the clusters that are free and in use on the outer volume. - // The map will be scanned to determine the size of the uninterrupted block of free - // space (provided there is any) whose end is aligned with the end of the volume. - // The value will then be used to determine the maximum possible size of the hidden volume. - - return ScanVolClusterBitmap (hwndDlg, - driveNo, - hiddenVolHostSize / *realClusterSize, - pnbrFreeClusters); - } - else - { - // Unsupported file system - - Error ((nCurrentOS == WIN_2000) ? "HIDDEN_VOL_HOST_UNSUPPORTED_FILESYS_WIN2000" : "HIDDEN_VOL_HOST_UNSUPPORTED_FILESYS", hwndDlg); - return 0; - } - -efs_error: - CloseHandle (hDevice); - -efsf_error: - CloseVolumeExplorerWindows (hwndDlg, *driveNo); - - return -1; -} - - -// Mounts a volume within which the user intends to create a hidden volume -int MountHiddenVolHost (HWND hwndDlg, wchar_t *volumePath, int *driveNo, Password *password, int pkcs5_prf, int pim, BOOL bReadOnly) -{ - MountOptions mountOptions; - ZeroMemory (&mountOptions, sizeof (mountOptions)); - - *driveNo = GetLastAvailableDrive (); - - if (*driveNo == -1) - { - *driveNo = -2; - return ERR_NO_FREE_DRIVES; - } - - mountOptions.ReadOnly = bReadOnly; - mountOptions.Removable = ConfigReadInt ("MountVolumesRemovable", FALSE); - mountOptions.ProtectHiddenVolume = FALSE; - mountOptions.PreserveTimestamp = bPreserveTimestamp; - mountOptions.PartitionInInactiveSysEncScope = FALSE; - mountOptions.UseBackupHeader = FALSE; - - if (MountVolume (hwndDlg, *driveNo, volumePath, password, pkcs5_prf, pim, FALSE, FALSE, FALSE, TRUE, &mountOptions, FALSE, TRUE) < 1) - { - *driveNo = -3; - return ERR_VOL_MOUNT_FAILED; - } - return 0; -} - - -/* Gets the map of the clusters that are free and in use on a volume that is to host - a hidden volume. The map is scanned to determine the size of the uninterrupted - area of free space (provided there is any) whose end is aligned with the end - of the volume. The value will then be used to determine the maximum possible size - of the hidden volume. */ -int ScanVolClusterBitmap (HWND hwndDlg, int *driveNo, __int64 nbrClusters, __int64 *nbrFreeClusters) -{ - PVOLUME_BITMAP_BUFFER lpOutBuffer; - STARTING_LCN_INPUT_BUFFER lpInBuffer; - - HANDLE hDevice; - DWORD lBytesReturned; - BYTE rmnd; - wchar_t tmpPath[7] = {L'\\',L'\\',L'.',L'\\', (wchar_t) *driveNo + L'A', L':', 0}; - - DWORD bufLen; - __int64 bitmapCnt; - - hDevice = CreateFile (tmpPath, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - - if (hDevice == INVALID_HANDLE_VALUE) - { - MessageBoxW (hwndDlg, GetString ("CANT_ACCESS_OUTER_VOL"), lpszTitle, ICON_HAND); - goto vcmf_error; - } - - bufLen = (DWORD) (nbrClusters / 8 + 2 * sizeof(LARGE_INTEGER)); - bufLen += 100000 + bufLen/10; // Add reserve - - lpOutBuffer = (PVOLUME_BITMAP_BUFFER) malloc (bufLen); - - if (lpOutBuffer == NULL) - { - MessageBoxW (hwndDlg, GetString ("ERR_MEM_ALLOC"), lpszTitle, ICON_HAND); - goto vcm_error; - } - - lpInBuffer.StartingLcn.QuadPart = 0; - - if ( !DeviceIoControl (hDevice, - FSCTL_GET_VOLUME_BITMAP, - &lpInBuffer, - sizeof(lpInBuffer), - lpOutBuffer, - bufLen, - &lBytesReturned, - NULL)) - { - handleWin32Error (hwndDlg, SRC_POS); - MessageBoxW (hwndDlg, GetString ("CANT_GET_CLUSTER_BITMAP"), lpszTitle, ICON_HAND); - - goto vcm_error; - } - - rmnd = (BYTE) (lpOutBuffer->BitmapSize.QuadPart % 8); - - if ((rmnd != 0) - && ((lpOutBuffer->Buffer[lpOutBuffer->BitmapSize.QuadPart / 8] & ((1 << rmnd)-1) ) != 0)) - { - *nbrFreeClusters = 0; - } - else - { - *nbrFreeClusters = lpOutBuffer->BitmapSize.QuadPart; - bitmapCnt = lpOutBuffer->BitmapSize.QuadPart / 8; - - // Scan the bitmap from the end - while (--bitmapCnt >= 0) - { - if (lpOutBuffer->Buffer[bitmapCnt] != 0) - { - // There might be up to 7 extra free clusters in this byte of the bitmap. - // These are ignored because there is always a cluster reserve added anyway. - *nbrFreeClusters = lpOutBuffer->BitmapSize.QuadPart - ((bitmapCnt + 1) * 8); - break; - } - } - } - - CloseHandle (hDevice); - free(lpOutBuffer); - return 1; - -vcm_error: - CloseHandle (hDevice); - if (lpOutBuffer) free(lpOutBuffer); - -vcmf_error: - return -1; -} - - -// Wipe the hidden OS config flag bits in the MBR -static BOOL WipeHiddenOSCreationConfig (void) -{ - if (!IsHiddenOSRunning()) - { - try - { - WaitCursor(); - finally_do ({ NormalCursor(); }); - - BootEncObj->WipeHiddenOSCreationConfig(); - } - catch (Exception &e) - { - e.Show (MainDlg); - return FALSE; - } - } - - return TRUE; -} - - -// Tasks that need to be performed after the WM_INITDIALOG message for the SYSENC_ENCRYPTION_PAGE dialog is -// handled should be done here (otherwise the UAC prompt causes the GUI to be only half-rendered). -static void AfterSysEncProgressWMInitTasks (HWND hwndDlg) -{ - try - { - switch (SystemEncryptionStatus) - { - case SYSENC_STATUS_ENCRYPTING: - - if (BootEncStatus.ConfiguredEncryptedAreaStart == BootEncStatus.EncryptedAreaStart - && BootEncStatus.ConfiguredEncryptedAreaEnd == BootEncStatus.EncryptedAreaEnd) - { - // The partition/drive had been fully encrypted - - ManageStartupSeqWiz (TRUE, L""); - WipeHiddenOSCreationConfig(); // For extra conservative security - ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); - - Info ("SYSTEM_ENCRYPTION_FINISHED", hwndDlg); - EndMainDlg (MainDlg); - return; - } - else - { - SysEncResume (); - } - - break; - - case SYSENC_STATUS_DECRYPTING: - SysEncResume (); - break; - - default: - - // Unexpected mode here -- fix the inconsistency - - ManageStartupSeqWiz (TRUE, L""); - ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); - EndMainDlg (MainDlg); - InconsistencyResolved (SRC_POS); - return; - } - } - catch (Exception &e) - { - e.Show (hwndDlg); - EndMainDlg (MainDlg); - return; - } - - InitSysEncProgressBar (); - - UpdateSysEncProgressBar (); - - UpdateSysEncControls (); -} - - -// Tasks that need to be performed after the WM_INITDIALOG message is handled must be done here. -// For example, any tasks that may invoke the UAC prompt (otherwise the UAC dialog box would not be on top). -static void AfterWMInitTasks (HWND hwndDlg) -{ - // Note that if bDirectSysEncModeCommand is not SYSENC_COMMAND_NONE, we already have the mutex. - - // SYSENC_COMMAND_DECRYPT has the highest priority because it also performs uninstallation (restores the - // original contents of the first drive cylinder, etc.) so it must be attempted regardless of the phase - // or content of configuration files. - if (bDirectSysEncModeCommand == SYSENC_COMMAND_DECRYPT) - { - if (IsHiddenOSRunning()) - { - Warning ("CANNOT_DECRYPT_HIDDEN_OS", hwndDlg); - AbortProcessSilent(); - } - - // Add the wizard to the system startup sequence - ManageStartupSeqWiz (FALSE, L"/acsysenc"); - - ChangeSystemEncryptionStatus (SYSENC_STATUS_DECRYPTING); - LoadPage (hwndDlg, SYSENC_ENCRYPTION_PAGE); - return; - } - - - if (SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING - || SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING) - { - try - { - BootEncStatus = BootEncObj->GetStatus(); - - if (!BootEncStatus.DriveMounted) - { - if (!BootEncStatus.DeviceFilterActive) - { - // This is an inconsistent state. SystemEncryptionStatus should never be SYSENC_STATUS_ENCRYPTING - // or SYSENC_STATUS_DECRYPTING when the drive filter is not active. Possible causes: 1) corrupted - // or stale config file, 2) corrupted system - - // Fix the inconsistency - ManageStartupSeqWiz (TRUE, L""); - ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); - EndMainDlg (MainDlg); - InconsistencyResolved (SRC_POS); - return; - } - else if (bDirectSysEncMode) - { - // This is an inconsistent state. We have a direct system encryption command, - // SystemEncryptionStatus is SYSENC_STATUS_ENCRYPTING or SYSENC_STATUS_DECRYPTING, the - // system drive is not 'mounted' and drive filter is active. Possible causes: 1) The drive had - // been decrypted in the pre-boot environment. 2) The OS is not located on the lowest partition, - // the drive is to be fully encrypted, but the user rebooted before encryption reached the - // system partition and then pressed Esc in the boot loader screen. 3) Corrupted or stale config - // file. 4) Damaged system. - - Warning ("SYSTEM_ENCRYPTION_SCHEDULED_BUT_PBA_FAILED", hwndDlg); - EndMainDlg (MainDlg); - return; - } - } - } - catch (Exception &e) - { - e.Show (MainDlg); - } - } - - - if (SystemEncryptionStatus != SYSENC_STATUS_PRETEST) - { - // Handle system encryption command line arguments (if we're not in the Pretest phase). - // Note that if bDirectSysEncModeCommand is not SYSENC_COMMAND_NONE, we already have the mutex. - // Also note that SYSENC_COMMAND_DECRYPT is handled above. - - switch (bDirectSysEncModeCommand) - { - case SYSENC_COMMAND_RESUME: - case SYSENC_COMMAND_STARTUP_SEQ_RESUME: - - if (bDirectSysEncModeCommand == SYSENC_COMMAND_STARTUP_SEQ_RESUME - && AskWarnYesNo ("SYSTEM_ENCRYPTION_RESUME_PROMPT", hwndDlg) == IDNO) - { - EndMainDlg (MainDlg); - return; - } - - if (SysEncryptionOrDecryptionRequired ()) - { - if (SystemEncryptionStatus != SYSENC_STATUS_ENCRYPTING - && SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING) - { - // If the config file with status was lost or not written correctly, we - // don't know whether to encrypt or decrypt (but we know that encryption or - // decryption is required). Ask the user to select encryption, decryption, - // or cancel - if (!ResolveUnknownSysEncDirection ()) - { - EndMainDlg (MainDlg); - return; - } - } - - LoadPage (hwndDlg, SYSENC_ENCRYPTION_PAGE); - return; - } - else - { - // Nothing to resume - Warning ("NO_SYS_ENC_PROCESS_TO_RESUME", hwndDlg); - EndMainDlg (MainDlg); - - return; - } - break; - - case SYSENC_COMMAND_ENCRYPT: - - if (SysDriveOrPartitionFullyEncrypted (FALSE)) - { - Info ("SYS_PARTITION_OR_DRIVE_APPEARS_FULLY_ENCRYPTED", hwndDlg); - EndMainDlg (MainDlg); - return; - } - - if (SysEncryptionOrDecryptionRequired ()) - { - // System partition/drive encryption process already initiated but is incomplete. - // If we were encrypting, resume the process directly. If we were decrypting, reverse - // the process and start encrypting. - - ChangeSystemEncryptionStatus (SYSENC_STATUS_ENCRYPTING); - LoadPage (hwndDlg, SYSENC_ENCRYPTION_PAGE); - return; - } - else - { - // Initiate the Pretest preparation phase - if (!SwitchWizardToSysEncMode ()) - { - bDirectSysEncMode = FALSE; - EndMainDlg (MainDlg); - } - return; - } - - break; - - case SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV: - case SYSENC_COMMAND_CREATE_HIDDEN_OS: - - if (!SwitchWizardToHiddenOSMode ()) - { - bDirectSysEncMode = FALSE; - EndMainDlg (MainDlg); - } - return; - } - } - - - if (!bDirectSysEncMode - || bDirectSysEncMode && SystemEncryptionStatus == SYSENC_STATUS_NONE) - { - // Handle system encryption cases where the wizard did not start even though it - // was added to the startup sequence, as well as other weird cases and "leftovers" - - if (SystemEncryptionStatus != SYSENC_STATUS_NONE - && SystemEncryptionStatus != SYSENC_STATUS_PRETEST - && SysEncryptionOrDecryptionRequired ()) - { - // System encryption/decryption had been in progress and did not finish - - if (CreateSysEncMutex ()) // If no other instance is currently taking care of system encryption - { - if (AskWarnYesNo ("SYSTEM_ENCRYPTION_RESUME_PROMPT", hwndDlg) == IDYES) - { - bDirectSysEncMode = TRUE; - ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); - LoadPage (hwndDlg, SYSENC_ENCRYPTION_PAGE); - return; - } - else - CloseSysEncMutex (); - } - } - - else if (SystemEncryptionStatus == SYSENC_STATUS_PRETEST) - { - // System pretest had been in progress but we were not launched during the startup seq - - if (CreateSysEncMutex ()) // If no other instance is currently taking care of system encryption - { - // The pretest has "priority handling" - bDirectSysEncMode = TRUE; - ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); - - /* Do not return yet -- the principal pretest handler is below. */ - } - } - - else if ((SystemEncryptionStatus == SYSENC_STATUS_NONE || SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING) - && !BootEncStatus.DriveEncrypted - && (BootEncStatus.DriveMounted || BootEncStatus.VolumeHeaderPresent)) - { - // The pretest may have been in progress but we can't be sure (it is not in the config file). - // Another possibility is that the user had finished decrypting the drive, but the config file - // was not correctly updated. In both cases the best thing we can do is remove the header and - // deinstall. Otherwise, the result might be some kind of deadlock. - - if (CreateSysEncMutex ()) // If no other instance is currently taking care of system encryption - { - WaitCursor (); - - ForceRemoveSysEnc(); - - InconsistencyResolved (SRC_POS); - - NormalCursor(); - CloseSysEncMutex (); - } - } - } - - if (bDirectSysEncMode && CreateSysEncMutex ()) - { - // We were launched either by Mount or by the system (startup sequence). Most of such cases should have - // been handled above already. Here we handle only the pretest phase (which can also be a hidden OS - // creation phase actually) and possible inconsistencies. - - switch (SystemEncryptionStatus) - { - case SYSENC_STATUS_PRETEST: - { - unsigned int hiddenOSCreationPhase = DetermineHiddenOSCreationPhase(); - - bHiddenOS = (hiddenOSCreationPhase != TC_HIDDEN_OS_CREATION_PHASE_NONE); - - // Evaluate the results of the system encryption pretest (or of the hidden OS creation process) - - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (hwndDlg); - Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", hwndDlg); - EndMainDlg (MainDlg); - return; - } - - if (BootEncStatus.DriveMounted) - { - /* Pretest successful or hidden OS has been booted during the process of hidden OS creation. */ - - switch (hiddenOSCreationPhase) - { - case TC_HIDDEN_OS_CREATION_PHASE_NONE: - - // Pretest successful (or the hidden OS has been booted for the first time since the user started installing a new decoy OS) - - if (IsHiddenOSRunning()) - { - // The hidden OS has been booted for the first time since the user started installing a - // new decoy OS (presumably, our MBR config flags have been erased). - - // As for things we are responsible for, the process of hidden OS creation is completed - // (the rest is up to the user). - - ManageStartupSeqWiz (TRUE, L""); - ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); - - EndMainDlg (MainDlg); - - return; - } - - // Pretest successful (no hidden operating system involved) - - LoadPage (hwndDlg, SYSENC_PRETEST_RESULT_PAGE); - return; - - case TC_HIDDEN_OS_CREATION_PHASE_WIPING: - - // Hidden OS has been booted when we are supposed to wipe the original OS - - LoadPage (hwndDlg, SYSENC_HIDDEN_OS_INITIAL_INFO_PAGE); - return; - - case TC_HIDDEN_OS_CREATION_PHASE_WIPED: - - // Hidden OS has been booted and the original OS wiped. Now the user is required to install a new, decoy, OS. - - TextInfoDialogBox (TC_TBXID_DECOY_OS_INSTRUCTIONS); - - EndMainDlg (MainDlg); - return; - - default: - - // Unexpected/unknown status - ReportUnexpectedState (SRC_POS); - EndMainDlg (MainDlg); - return; - } - } - else - { - BOOL bAnswerTerminate = FALSE, bAnswerRetry = FALSE; - - /* Pretest failed - or hidden OS cloning has been interrupted (and non-hidden OS is running) - or wiping of the original OS has not been started (and non-hidden OS is running) */ - - if (hiddenOSCreationPhase == TC_HIDDEN_OS_CREATION_PHASE_NONE) - { - // Pretest failed (no hidden operating system involved) - - if (AskWarnYesNo ("BOOT_PRETEST_FAILED_RETRY", hwndDlg) == IDYES) - { - // User wants to retry the pretest - bAnswerTerminate = FALSE; - bAnswerRetry = TRUE; - } - else - { - // User doesn't want to retry the pretest - bAnswerTerminate = TRUE; - bAnswerRetry = FALSE; - } - } - else - { - // Hidden OS cloning was interrupted or wiping of the original OS has not been started - - char *tmpStr[] = {0, - hiddenOSCreationPhase == TC_HIDDEN_OS_CREATION_PHASE_WIPING ? "OS_WIPING_NOT_FINISHED_ASK" : "HIDDEN_OS_CREATION_NOT_FINISHED_ASK", - "HIDDEN_OS_CREATION_NOT_FINISHED_CHOICE_RETRY", - "HIDDEN_OS_CREATION_NOT_FINISHED_CHOICE_TERMINATE", - "HIDDEN_OS_CREATION_NOT_FINISHED_CHOICE_ASK_LATER", - 0}; - - switch (AskMultiChoice ((void **) tmpStr, FALSE, hwndDlg)) - { - case 1: - // User wants to restart and continue/retry - bAnswerTerminate = FALSE; - bAnswerRetry = TRUE; - break; - - case 2: - // User doesn't want to retry but wants to terminate the entire process of hidden OS creation - bAnswerTerminate = TRUE; - bAnswerRetry = FALSE; - break; - - default: - // User doesn't want to do anything now - bAnswerTerminate = FALSE; - bAnswerRetry = FALSE; - } - } - - - if (bAnswerRetry) - { - // User wants to restart and retry the pretest (or hidden OS creation) - - // We re-register the driver for boot because the user may have selected - // "Last Known Good Configuration" from the Windows boot menu. - // Note that we need to do this even when creating a hidden OS (because - // the hidden OS needs our boot driver and it will be a clone of this OS). - try - { - BootEncObj->RegisterBootDriver (bHiddenOS ? true : false); - } - catch (Exception &e) - { - e.Show (NULL); - } - - if (AskWarnYesNo ("CONFIRM_RESTART", hwndDlg) == IDYES) - { - EndMainDlg (MainDlg); - - try - { - BootEncObj->RestartComputer (); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - - return; - } - - EndMainDlg (MainDlg); - return; - } - else if (bAnswerTerminate) - { - // User doesn't want to retry pretest (or OS cloning), but to terminate the entire process - - try - { - BootEncObj->Deinstall (true); - } - catch (Exception &e) - { - e.Show (hwndDlg); - AbortProcessSilent(); - } - - ManageStartupSeqWiz (TRUE, L""); - ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); - EndMainDlg (MainDlg); - return; - } - else - { - // User doesn't want to take any action now - - AbortProcessSilent(); - } - } - } - break; - - default: - - // Unexpected progress status -- fix the inconsistency - - ManageStartupSeqWiz (TRUE, L""); - ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); - EndMainDlg (MainDlg); - InconsistencyResolved (SRC_POS); - return; - } - } - else - { - if (DirectDeviceEncMode) - { - SwitchWizardToNonSysDeviceMode(); - return; - } - - if (DirectPromptNonSysInplaceEncResumeMode - && !bInPlaceEncNonSysPending) - { - // This instance of the wizard has been launched via the system startup sequence to prompt for resume of - // a non-system in-place encryption/decryption process. However, no config file indicates that any such process - // has been interrupted. This inconsistency may occur, for example, when the process is finished - // but the wizard is not removed from the startup sequence because system encryption is in progress. - // Therefore, we remove it from the startup sequence now if possible. - - if (!IsNonInstallMode () && SystemEncryptionStatus == SYSENC_STATUS_NONE) - ManageStartupSeqWiz (TRUE, L""); - - AbortProcessSilent (); - } - - BOOL bDecrypt = FALSE; - - if (DirectNonSysInplaceDecStartMode) - { - SwitchWizardToNonSysInplaceDecStartMode (szFileName); - return; - } - else if (DirectNonSysInplaceEncResumeMode || DirectNonSysInplaceDecResumeMode) - { - SwitchWizardToNonSysInplaceEncResumeMode (DirectNonSysInplaceDecResumeMode); - return; - } - else if (DirectPromptNonSysInplaceEncResumeMode) - { - if (NonSysInplaceEncInProgressElsewhere ()) - AbortProcessSilent (); - - if (AskNonSysInPlaceEncryptionResume(hwndDlg, &bDecrypt) == IDYES) - SwitchWizardToNonSysInplaceEncResumeMode(bDecrypt); - else - AbortProcessSilent (); - - return; - } - else if (bInPlaceEncNonSysPending - && !NonSysInplaceEncInProgressElsewhere () - && AskNonSysInPlaceEncryptionResume(hwndDlg, &bDecrypt) == IDYES) - { - SwitchWizardToNonSysInplaceEncResumeMode(bDecrypt); - return; - } - - LoadPage (hwndDlg, INTRO_PAGE); - } -} - -int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpszCommandLine, int nCmdShow) -{ - int status; - atexit (localcleanup); - - VirtualLock (&volumePassword, sizeof(volumePassword)); - VirtualLock (szVerify, sizeof(szVerify)); - VirtualLock (szRawPassword, sizeof(szRawPassword)); - VirtualLock (&volumePim, sizeof(volumePim)); - VirtualLock (&CmdVolumePassword, sizeof (CmdVolumePassword)); - - VirtualLock (MasterKeyGUIView, sizeof(MasterKeyGUIView)); - VirtualLock (HeaderKeyGUIView, sizeof(HeaderKeyGUIView)); - - VirtualLock (randPool, sizeof(randPool)); - VirtualLock (lastRandPool, sizeof(lastRandPool)); - VirtualLock (outRandPoolDispBuffer, sizeof(outRandPoolDispBuffer)); - VirtualLock (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); - VirtualLock (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); - VirtualLock (maskRandPool, sizeof(maskRandPool)); - - VirtualLock (&szFileName, sizeof(szFileName)); - VirtualLock (&szDiskFile, sizeof(szDiskFile)); - - DetectX86Features (); - - try - { - BootEncObj = new BootEncryption (NULL); - } - catch (Exception &e) - { - e.Show (NULL); - } - - if (BootEncObj == NULL) - AbortProcess ("INIT_SYS_ENC"); - - InitApp (hInstance, lpszCommandLine); - - // Write block size greater than 64 KB causes a performance drop when writing to files on XP/Vista - if (!IsOSAtLeast (WIN_7)) - FormatWriteBufferSize = 64 * 1024; - -#if TC_MAX_VOLUME_SECTOR_SIZE > 64 * 1024 -#error TC_MAX_VOLUME_SECTOR_SIZE > 64 * 1024 -#endif - - nPbar = IDC_PROGRESS_BAR; - - if (Randinit ()) - { - DWORD dwLastError = GetLastError (); - wchar_t szTmp[4096]; - if (CryptoAPILastError == ERROR_SUCCESS) - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("INIT_RAND"), SRC_POS, dwLastError); - else - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CAPI_RAND"), SRC_POS, CryptoAPILastError); - AbortProcessDirect (szTmp); - } - - RegisterRedTick(hInstance); - - /* Allocate, dup, then store away the application title */ - lpszTitle = GetString ("IDD_VOL_CREATION_WIZARD_DLG"); - - status = DriverAttach (); - if (status != 0) - { - if (status == ERR_OS_ERROR) - handleWin32Error (NULL, SRC_POS); - else - handleError (NULL, status, SRC_POS); - - AbortProcess ("NODRIVER"); - } - - if (!AutoTestAlgorithms()) - AbortProcess ("ERR_SELF_TESTS_FAILED"); - - /* Create the main dialog box */ - DialogBoxParamW (hInstance, MAKEINTRESOURCEW (IDD_VOL_CREATION_WIZARD_DLG), NULL, (DLGPROC) MainDialogProc, - (LPARAM)lpszCommandLine); - - FinalizeApp (); - return 0; -} - - -static DWORD GetFormatSectorSize () -{ - if (!bDevice) - return TC_SECTOR_SIZE_FILE_HOSTED_VOLUME; - - DISK_GEOMETRY geometry; - - if (!GetDriveGeometry (szDiskFile, &geometry)) - { - handleWin32Error (MainDlg, SRC_POS); - AbortProcessSilent(); - } - - return geometry.BytesPerSector; -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "Crypto.h" +#include "cpu.h" +#include "Apidrvr.h" +#include "Dlgcode.h" +#include "Language.h" +#include "Combo.h" +#include "Registry.h" +#include "Boot/Windows/BootDefs.h" +#include "Common/Common.h" +#include "Common/BootEncryption.h" +#include "Common/Dictionary.h" +#include "Common/Endian.h" +#include "Common/resource.h" +#include "Common/Pkcs5.h" +#include "Platform/Finally.h" +#include "Platform/ForEach.h" +#include "Random.h" +#include "Fat.h" +#include "InPlace.h" +#include "Resource.h" +#include "TcFormat.h" +#include "Format.h" +#include "FormatCom.h" +#include "Password.h" +#include "Progress.h" +#include "Tests.h" +#include "Cmdline.h" +#include "Volumes.h" +#include "Wipe.h" +#include "Xml.h" + +#include + +using namespace VeraCrypt; + +enum wizard_pages +{ + /* IMPORTANT: IF YOU ADD/REMOVE/MOVE ANY PAGES THAT ARE RELATED TO SYSTEM ENCRYPTION, + REVISE THE 'DECOY_OS_INSTRUCTIONS_PORTION_??' STRINGS! */ + + INTRO_PAGE, + SYSENC_TYPE_PAGE, + SYSENC_HIDDEN_OS_REQ_CHECK_PAGE, + SYSENC_SPAN_PAGE, + SYSENC_PRE_DRIVE_ANALYSIS_PAGE, + SYSENC_DRIVE_ANALYSIS_PAGE, + SYSENC_MULTI_BOOT_MODE_PAGE, + SYSENC_MULTI_BOOT_SYS_EQ_BOOT_PAGE, + SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE, + SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE, + SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE, + SYSENC_MULTI_BOOT_OUTCOME_PAGE, + VOLUME_TYPE_PAGE, + HIDDEN_VOL_WIZARD_MODE_PAGE, + VOLUME_LOCATION_PAGE, + DEVICE_TRANSFORM_MODE_PAGE, + HIDDEN_VOL_HOST_PRE_CIPHER_PAGE, + HIDDEN_VOL_PRE_CIPHER_PAGE, + CIPHER_PAGE, + SIZE_PAGE, + HIDDEN_VOL_HOST_PASSWORD_PAGE, + PASSWORD_PAGE, + PIM_PAGE, + FILESYS_PAGE, + SYSENC_COLLECTING_RANDOM_DATA_PAGE, + SYSENC_KEYS_GEN_PAGE, + SYSENC_RESCUE_DISK_CREATION_PAGE, + SYSENC_RESCUE_DISK_BURN_PAGE, + SYSENC_RESCUE_DISK_VERIFIED_PAGE, + SYSENC_WIPE_MODE_PAGE, + SYSENC_PRETEST_INFO_PAGE, + SYSENC_PRETEST_RESULT_PAGE, + SYSENC_ENCRYPTION_PAGE, + NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE, + NONSYS_INPLACE_ENC_RESUME_PARTITION_SEL_PAGE, + NONSYS_INPLACE_ENC_RAND_DATA_PAGE, + NONSYS_INPLACE_ENC_WIPE_MODE_PAGE, + NONSYS_INPLACE_ENC_TRANSFORM_PAGE, + NONSYS_INPLACE_ENC_TRANSFORM_FINISHED_PAGE, + NONSYS_INPLACE_DEC_TRANSFORM_FINISHED_DRIVE_LETTER_PAGE, + FORMAT_PAGE, + FORMAT_FINISHED_PAGE, + SYSENC_HIDDEN_OS_INITIAL_INFO_PAGE, + SYSENC_HIDDEN_OS_WIPE_INFO_PAGE, + DEVICE_WIPE_MODE_PAGE, + DEVICE_WIPE_PAGE +}; + +#define TIMER_INTERVAL_RANDVIEW 30 +#define TIMER_INTERVAL_SYSENC_PROGRESS 30 +#define TIMER_INTERVAL_NONSYS_INPLACE_ENC_PROGRESS 30 +#define TIMER_INTERVAL_SYSENC_DRIVE_ANALYSIS_PROGRESS 100 +#define TIMER_INTERVAL_WIPE_PROGRESS 30 +#define TIMER_INTERVAL_KEYB_LAYOUT_GUARD 10 + +enum sys_encryption_cmd_line_switches +{ + SYSENC_COMMAND_NONE = 0, + SYSENC_COMMAND_RESUME, + SYSENC_COMMAND_STARTUP_SEQ_RESUME, + SYSENC_COMMAND_ENCRYPT, + SYSENC_COMMAND_DECRYPT, + SYSENC_COMMAND_CREATE_HIDDEN_OS, + SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV +}; + +typedef struct +{ + int NumberOfSysDrives; // Number of drives that contain an operating system. -1: unknown, 1: one, 2: two or more + int MultipleSystemsOnDrive; // Multiple systems are installed on the drive where the currently running system resides. -1: unknown, 0: no, 1: yes + int BootLoaderLocation; // Boot loader (boot manager) installed in: 1: MBR/1st cylinder, 0: partition/bootsector: -1: unknown + int BootLoaderBrand; // -1: unknown, 0: Microsoft Windows, 1: any non-Windows boot manager/loader + int SystemOnBootDrive; // If the currently running operating system is installed on the boot drive. -1: unknown, 0: no, 1: yes +} SYSENC_MULTIBOOT_CFG; + +#define SYSENC_PAUSE_RETRY_INTERVAL 100 +#define SYSENC_PAUSE_RETRIES 200 + +// Expected duration of system drive analysis, in ms +#define SYSENC_DRIVE_ANALYSIS_ETA (4*60000) + +BootEncryption *BootEncObj = NULL; +BootEncryptionStatus BootEncStatus; + +HWND hCurPage = NULL; /* Handle to current wizard page */ +int nCurPageNo = -1; /* The current wizard page */ +int nLastPageNo = -1; +volatile int WizardMode = DEFAULT_VOL_CREATION_WIZARD_MODE; /* IMPORTANT: Never change this value directly -- always use ChangeWizardMode() instead. */ +volatile BOOL bHiddenOS = FALSE; /* If TRUE, we are performing or (or supposed to perform) actions relating to an operating system installed in a hidden volume (i.e., encrypting a decoy OS partition or creating the outer/hidden volume for the hidden OS). To determine or set the phase of the process, call ChangeHiddenOSCreationPhase() and DetermineHiddenOSCreationPhase()) */ +BOOL bDirectSysEncMode = FALSE; +BOOL bDirectSysEncModeCommand = SYSENC_COMMAND_NONE; +BOOL DirectDeviceEncMode = FALSE; +BOOL DirectNonSysInplaceDecStartMode = FALSE; +BOOL DirectNonSysInplaceEncResumeMode = FALSE; +BOOL DirectNonSysInplaceDecResumeMode = FALSE; +BOOL DirectPromptNonSysInplaceEncResumeMode = FALSE; +BOOL DirectCreationMode = FALSE; + +volatile BOOL bInPlaceEncNonSys = FALSE; /* If TRUE, existing data on a non-system partition/volume are to be encrypted (or decrypted if bInPlaceDecNonSys is TRUE) in place (for system encryption, this flag is ignored) */ +volatile BOOL bInPlaceDecNonSys = FALSE; /* If TRUE, existing data on a non-system partition/volume are to be decrypted in place (for system encryption, this flag is ignored) */ +volatile BOOL bInPlaceEncNonSysResumed = FALSE; /* If TRUE, the wizard is supposed to resume (or has resumed) process of non-system in-place encryption/decryption. */ +volatile BOOL bFirstNonSysInPlaceEncResumeDone = FALSE; +__int64 NonSysInplaceEncBytesDone = 0; +__int64 NonSysInplaceEncTotalSize = 0; +BOOL bDeviceTransformModeChoiceMade = FALSE; /* TRUE if the user has at least once manually selected the 'in-place' or 'format' option (on the 'device transform mode' page). */ +int nNeedToStoreFilesOver4GB = 0; /* Whether the user wants to be able to store files larger than 4GB on the volume: -1 = Undecided or error, 0 = No, 1 = Yes */ +int nVolumeEA = 1; /* Default encryption algorithm */ +BOOL bSystemEncryptionInProgress = FALSE; /* TRUE when encrypting/decrypting the system partition/drive (FALSE when paused). */ +BOOL bWholeSysDrive = FALSE; /* Whether to encrypt the entire system drive or just the system partition. */ +static BOOL bSystemEncryptionStatusChanged = FALSE; /* TRUE if this instance changed the value of SystemEncryptionStatus (it's set to FALSE each time the system encryption settings are saved to the config file). This value is to be treated as protected -- only the wizard can change this value (others may only read it). */ +volatile BOOL bSysEncDriveAnalysisInProgress = FALSE; +volatile BOOL bSysEncDriveAnalysisTimeOutOccurred = FALSE; +int SysEncDetectHiddenSectors = -1; /* Whether the user wants us to detect and encrypt the Host Protect Area (if any): -1 = Undecided or error, 0 = No, 1 = Yes */ +int SysEncDriveAnalysisStart; +BOOL bDontVerifyRescueDisk = FALSE; +BOOL bFirstSysEncResumeDone = FALSE; +int nMultiBoot = 0; /* The number of operating systems installed on the computer, according to the user. 0: undetermined, 1: one, 2: two or more */ +volatile BOOL bHiddenVol = FALSE; /* If true, we are (or will be) creating a hidden volume. */ +volatile BOOL bHiddenVolHost = FALSE; /* If true, we are (or will be) creating the host volume (called "outer") for a hidden volume. */ +volatile BOOL bHiddenVolDirect = FALSE; /* If true, the wizard omits creating a host volume in the course of the process of hidden volume creation. */ +volatile BOOL bHiddenVolFinished = FALSE; +int hiddenVolHostDriveNo = -1; /* Drive letter for the volume intended to host a hidden volume. */ +BOOL bRemovableHostDevice = FALSE; /* TRUE when creating a device/partition-hosted volume on a removable device. State undefined when creating file-hosted volumes. */ +int realClusterSize; /* Parameter used when determining the maximum possible size of a hidden volume. */ +int hash_algo = DEFAULT_HASH_ALGORITHM; /* Which PRF to use in header key derivation (PKCS #5) and in the RNG. */ +unsigned __int64 nUIVolumeSize = 0; /* The volume size. Important: This value is not in bytes. It has to be multiplied by nMultiplier. Do not use this value when actually creating the volume (it may chop off sector size, if it is not a multiple of 1024 bytes). */ +unsigned __int64 nVolumeSize = 0; /* The volume size, in bytes. */ +unsigned __int64 nHiddenVolHostSize = 0; /* Size of the hidden volume host, in bytes */ +__int64 nMaximumHiddenVolSize = 0; /* Maximum possible size of the hidden volume, in bytes */ +__int64 nbrFreeClusters = 0; +__int64 nMultiplier = BYTES_PER_MB; /* Size selection multiplier. */ +wchar_t szFileName[TC_MAX_PATH+1]; /* The file selected by the user */ +wchar_t szDiskFile[TC_MAX_PATH+1]; /* Fully qualified name derived from szFileName */ +wchar_t szRescueDiskISO[TC_MAX_PATH+1]; /* The filename and path to the Rescue Disk ISO file to be burned (for boot encryption) */ +BOOL bDeviceWipeInProgress = FALSE; +volatile BOOL bTryToCorrectReadErrors = FALSE; +volatile BOOL DiscardUnreadableEncryptedSectors = FALSE; + +volatile BOOL bVolTransformThreadCancel = FALSE; /* TRUE if the user cancels/pauses volume encryption/format */ +volatile BOOL bVolTransformThreadRunning = FALSE; /* Is the volume encryption/format thread running */ +volatile BOOL bVolTransformThreadToRun = FALSE; /* TRUE if the Format/Encrypt button has been clicked and we are proceeding towards launching the thread. */ + +volatile BOOL bConfirmQuit = FALSE; /* If TRUE, the user is asked to confirm exit when he clicks the X icon, Exit, etc. */ +volatile BOOL bConfirmQuitSysEncPretest = FALSE; + +BOOL bDevice = FALSE; /* Is this a partition volume ? */ + +BOOL showKeys = FALSE; +volatile HWND hMasterKey = NULL; /* Text box showing hex dump of the master key */ +volatile HWND hHeaderKey = NULL; /* Text box showing hex dump of the header key */ +volatile HWND hRandPool = NULL; /* Text box showing hex dump of the random pool */ +volatile HWND hRandPoolSys = NULL; /* Text box showing hex dump of the random pool for system encryption */ +volatile HWND hPasswordInputField = NULL; /* Password input field */ +volatile HWND hVerifyPasswordInputField = NULL; /* Verify-password input field */ + +HBITMAP hbmWizardBitmapRescaled = NULL; + +wchar_t OrigKeyboardLayout [8+1] = L"00000409"; +BOOL bKeyboardLayoutChanged = FALSE; /* TRUE if the keyboard layout was changed to the standard US keyboard layout (from any other layout). */ +BOOL bKeybLayoutAltKeyWarningShown = FALSE; /* TRUE if the user has been informed that it is not possible to type characters by pressing keys while the right Alt key is held down. */ + +#ifndef _DEBUG + BOOL bWarnDeviceFormatAdvanced = TRUE; +#else + BOOL bWarnDeviceFormatAdvanced = FALSE; +#endif + +BOOL bWarnOuterVolSuitableFileSys = TRUE; + +Password volumePassword; /* User password */ +char szVerify[MAX_PASSWORD + 1]; /* Tmp password buffer */ +char szRawPassword[MAX_PASSWORD + 1]; /* Password before keyfile was applied to it */ + +int volumePim = 0; + +BOOL bHistoryCmdLine = FALSE; /* History control is always disabled */ +BOOL ComServerMode = FALSE; + + +Password CmdVolumePassword = {0}; /* Password passed from command line */ +int CmdVolumeEA = 0; +int CmdVolumePkcs5 = 0; +int CmdVolumePim = 0; +int CmdVolumeFilesystem = FILESYS_NONE; +unsigned __int64 CmdVolumeFileSize = 0; +BOOL CmdSparseFileSwitch = FALSE; + +BOOL bForceOperation = FALSE; + +BOOL bOperationSuccess = FALSE; + +BOOL bGuiMode = TRUE; + +int nPbar = 0; /* Control ID of progress bar:- for format code */ + +wchar_t HeaderKeyGUIView [KEY_GUI_VIEW_SIZE]; +wchar_t MasterKeyGUIView [KEY_GUI_VIEW_SIZE]; + +#define RANDPOOL_DISPLAY_COLUMNS 15 +#define RANDPOOL_DISPLAY_ROWS 8 +#define RANDPOOL_DISPLAY_BYTE_PORTION (RANDPOOL_DISPLAY_COLUMNS * RANDPOOL_DISPLAY_ROWS) +#define RANDPOOL_DISPLAY_SIZE (RANDPOOL_DISPLAY_BYTE_PORTION * 3 + RANDPOOL_DISPLAY_ROWS + 2) +unsigned char randPool [RANDPOOL_DISPLAY_BYTE_PORTION]; +unsigned char lastRandPool [RANDPOOL_DISPLAY_BYTE_PORTION]; +static unsigned char maskRandPool [RANDPOOL_DISPLAY_BYTE_PORTION]; +static BOOL bUseMask = FALSE; +static DWORD mouseEntropyGathered = 0xFFFFFFFF; +static DWORD mouseEventsInitialCount = 0; +/* max value of entropy needed to fill all random pool = 8 * RNG_POOL_SIZE = 2560 bits */ +static const DWORD maxEntropyLevel = RNG_POOL_SIZE * 8; +static HWND hEntropyBar = NULL; +wchar_t outRandPoolDispBuffer [RANDPOOL_DISPLAY_SIZE]; +BOOL bDisplayPoolContents = TRUE; + +volatile BOOL bSparseFileSwitch = FALSE; +volatile BOOL quickFormat = FALSE; /* WARNING: Meaning of this variable depends on bSparseFileSwitch. If bSparseFileSwitch is TRUE, this variable represents the sparse file flag. */ +volatile int fileSystem = FILESYS_NONE; +volatile int clusterSize = 0; + +SYSENC_MULTIBOOT_CFG SysEncMultiBootCfg; +wchar_t SysEncMultiBootCfgOutcome [4096] = {L'N',L'/',L'A',0}; +volatile int NonSysInplaceEncStatus = NONSYS_INPLACE_ENC_STATUS_NONE; + +vector DeferredNonSysInPlaceEncDevices; + +// specific definitions and implementation for support of resume operation +// in wait dialog mechanism + +void CALLBACK ResumeInPlaceEncWaitThreadProc(void* pArg, HWND hwndDlg) +{ + wchar_t szDevicePath[MAX_PATH] = {0}; + RawDevicesDlgParam param; + param.devices = GetAvailableHostDevices (false, true, false); + param.pszFileName = szDevicePath; + + DeferredNonSysInPlaceEncDevices.clear(); + + if ((IDOK == DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_RAWDEVICES_DLG), hwndDlg, + (DLGPROC) RawDevicesDlgProc, (LPARAM) ¶m)) && wcslen(szDevicePath)) + { + foreach (const HostDevice &device, param.devices) + { + if (device.Path == szDevicePath) + { + OpenVolumeContext volume; + int status = OpenVolume (&volume, device.Path.c_str(), &volumePassword, hash_algo, volumePim, FALSE, FALSE, FALSE, TRUE); + + if ( status == ERR_SUCCESS) + { + if ((volume.CryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) != 0 + && volume.CryptoInfo->EncryptedAreaLength.Value != volume.CryptoInfo->VolumeSize.Value) + { + DeferredNonSysInPlaceEncDevices.push_back (device); + } + else if (volume.CryptoInfo->EncryptedAreaLength.Value == volume.CryptoInfo->VolumeSize.Value) + { + WCHAR szMsg[1024]; + StringCbPrintfW(szMsg, sizeof(szMsg), GetString ("SELECTED_PARTITION_ALREADY_INPLACE_ENC"), + volume.CryptoInfo->HeaderFlags); + ErrorDirect(szMsg, hwndDlg); + } + else + { + WCHAR szMsg[1024]; + StringCbPrintfW(szMsg, sizeof(szMsg), GetString ("SELECTED_PARTITION_NOT_INPLACE_ENC"), + volume.CryptoInfo->HeaderFlags); + ErrorDirect(szMsg, hwndDlg); + } + + CloseVolume (&volume); + } + else + { + handleError(hwndDlg, status, SRC_POS); + } + + break; + } + } + } + else + { + foreach (const HostDevice &device, param.devices) + { + if ( !device.ContainsSystem + && (device.IsPartition || device.DynamicVolume || device.IsVirtualPartition || device.Partitions.empty()) + ) + { + + OpenVolumeContext volume; + + if (OpenVolume (&volume, device.Path.c_str(), &volumePassword, hash_algo, volumePim, FALSE, FALSE, FALSE, TRUE) == ERR_SUCCESS) + { + if ((volume.CryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) != 0 + && volume.CryptoInfo->EncryptedAreaLength.Value != volume.CryptoInfo->VolumeSize.Value) + { + DeferredNonSysInPlaceEncDevices.push_back (device); + } + + CloseVolume (&volume); + } + } + } + } +} + + +static BOOL ElevateWholeWizardProcess (wstring arguments) +{ + wchar_t modPath[MAX_PATH]; + + if (IsAdmin()) + return TRUE; + + if (!IsUacSupported()) + return IsAdmin(); + + GetModuleFileName (NULL, modPath, ARRAYSIZE (modPath)); + + while (true) + { + if ((int)ShellExecute (MainDlg, L"runas", modPath, (wstring(L"/q UAC ") + arguments).c_str(), NULL, SW_SHOWNORMAL) > 32) + { + exit (0); + } + else + { + if (IDRETRY == ErrorRetryCancel ("UAC_INIT_ERROR", MainDlg)) + continue; + return FALSE; + } + } +} + +static void WipePasswordsAndKeyfiles (void) +{ + wchar_t tmp[MAX_PASSWORD+1]; + + // Attempt to wipe passwords stored in the input field buffers + wmemset (tmp, L'X', MAX_PASSWORD); + tmp [MAX_PASSWORD] = 0; + SetWindowText (hPasswordInputField, tmp); + SetWindowText (hVerifyPasswordInputField, tmp); + + burn (&szVerify[0], sizeof (szVerify)); + burn (&volumePassword, sizeof (volumePassword)); + burn (&szRawPassword[0], sizeof (szRawPassword)); + burn (&volumePim, sizeof (volumePim)); + burn (&CmdVolumePassword, sizeof (CmdVolumePassword)); + burn (&CmdVolumePim, sizeof (CmdVolumePim)); + + SetWindowText (hPasswordInputField, L""); + SetWindowText (hVerifyPasswordInputField, L""); + + KeyFileRemoveAll (&FirstKeyFile); + KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile); +} + +static void localcleanup (void) +{ + wchar_t tmp[RANDPOOL_DISPLAY_SIZE+1]; + + // System encryption + + if (WizardMode == WIZARD_MODE_SYS_DEVICE + && InstanceHasSysEncMutex ()) + { + try + { + BootEncStatus = BootEncObj->GetStatus(); + + if (BootEncStatus.SetupInProgress) + { + BootEncObj->AbortSetup (); + } + } + catch (...) + { + // NOP + } + } + + // Mon-system in-place encryption + + if (bInPlaceEncNonSys && (bVolTransformThreadRunning || bVolTransformThreadToRun)) + { + NonSysInplaceEncPause (); + } + + CloseNonSysInplaceEncMutex (); + + + // Device wipe + + if (bDeviceWipeInProgress) + WipeAbort(); + + + WipePasswordsAndKeyfiles (); + + RandStop (TRUE); + + burn (HeaderKeyGUIView, sizeof(HeaderKeyGUIView)); + burn (MasterKeyGUIView, sizeof(MasterKeyGUIView)); + burn (randPool, sizeof(randPool)); + burn (lastRandPool, sizeof(lastRandPool)); + burn (outRandPoolDispBuffer, sizeof(outRandPoolDispBuffer)); + burn (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); + burn (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); + burn (maskRandPool, sizeof(maskRandPool)); + burn (szFileName, sizeof(szFileName)); + burn (szDiskFile, sizeof(szDiskFile)); + + // Attempt to wipe the GUI fields showing portions of randpool, of the master and header keys + wmemset (tmp, L'X', ARRAYSIZE(tmp)); + tmp [ARRAYSIZE(tmp)-1] = 0; + SetWindowText (hRandPool, tmp); + SetWindowText (hRandPoolSys, tmp); + SetWindowText (hMasterKey, tmp); + SetWindowText (hHeaderKey, tmp); + + UnregisterRedTick (hInst); + + // Delete buffered bitmaps (if any) + if (hbmWizardBitmapRescaled != NULL) + { + DeleteObject ((HGDIOBJ) hbmWizardBitmapRescaled); + hbmWizardBitmapRescaled = NULL; + } + + // Cleanup common code resources + cleanup (); + + if (BootEncObj != NULL) + { + delete BootEncObj; + BootEncObj = NULL; + } +} + +static BOOL CALLBACK BroadcastSysEncCfgUpdateCallb (HWND hwnd, LPARAM lParam) +{ + LONG_PTR userDataVal = GetWindowLongPtrW (hwnd, GWLP_USERDATA); + if ((userDataVal == (LONG_PTR) 'VERA') || (userDataVal == (LONG_PTR) 'TRUE')) // Prior to 1.0e, 'TRUE' was used for VeraCrypt dialogs + { + wchar_t name[1024] = { 0 }; + GetWindowText (hwnd, name, ARRAYSIZE (name) - 1); + if (hwnd != MainDlg && wcsstr (name, L"VeraCrypt")) + { + PostMessage (hwnd, TC_APPMSG_SYSENC_CONFIG_UPDATE, 0, 0); + } + } + return TRUE; +} + +static BOOL BroadcastSysEncCfgUpdate (void) +{ + BOOL bSuccess = FALSE; + EnumWindows (BroadcastSysEncCfgUpdateCallb, (LPARAM) &bSuccess); + return bSuccess; +} + +// IMPORTANT: This function may be called only by Format (other modules can only _read_ the system encryption config). +// Returns TRUE if successful (otherwise FALSE) +static BOOL SaveSysEncSettings (HWND hwndDlg) +{ + FILE *f; + + if (!bSystemEncryptionStatusChanged) + return TRUE; + + if (hwndDlg == NULL && MainDlg != NULL) + hwndDlg = MainDlg; + + if (!CreateSysEncMutex ()) + return FALSE; // Only one instance that has the mutex can modify the system encryption settings + + if (SystemEncryptionStatus == SYSENC_STATUS_NONE) + { + if (_wremove (GetConfigPath (TC_APPD_FILENAME_SYSTEM_ENCRYPTION)) != 0) + { + Error ("CANNOT_SAVE_SYS_ENCRYPTION_SETTINGS", hwndDlg); + return FALSE; + } + + bSystemEncryptionStatusChanged = FALSE; + BroadcastSysEncCfgUpdate (); + return TRUE; + } + + f = _wfopen (GetConfigPath (TC_APPD_FILENAME_SYSTEM_ENCRYPTION), L"w,ccs=UTF-8"); + if (f == NULL) + { + Error ("CANNOT_SAVE_SYS_ENCRYPTION_SETTINGS", hwndDlg); + handleWin32Error (hwndDlg, SRC_POS); + return FALSE; + } + + if (XmlWriteHeader (f) < 0 + + || fputws (L"\n\t", f) < 0 + + || fwprintf (f, L"\n\t\t%d", SystemEncryptionStatus) < 0 + + || fwprintf (f, L"\n\t\t%d", (int) nWipeMode) < 0 + + || fputws (L"\n\t", f) < 0 + + || XmlWriteFooter (f) < 0) + { + handleWin32Error (hwndDlg, SRC_POS); + fclose (f); + Error ("CANNOT_SAVE_SYS_ENCRYPTION_SETTINGS", hwndDlg); + return FALSE; + } + + TCFlushFile (f); + + fclose (f); + + bSystemEncryptionStatusChanged = FALSE; + BroadcastSysEncCfgUpdate (); + + return TRUE; +} + +// WARNING: This function may take a long time to finish +static unsigned int DetermineHiddenOSCreationPhase (void) +{ + unsigned int phase = TC_HIDDEN_OS_CREATION_PHASE_NONE; + + try + { + phase = BootEncObj->GetHiddenOSCreationPhase(); + } + catch (Exception &e) + { + e.Show (MainDlg); + AbortProcess("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS"); + } + + return phase; +} + +// IMPORTANT: This function may be called only by Format (other modules can only _read_ the status). +// Returns TRUE if successful (otherwise FALSE) +static BOOL ChangeHiddenOSCreationPhase (int newPhase) +{ + if (!CreateSysEncMutex ()) + { + Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); + return FALSE; + } + + try + { + BootEncObj->SetHiddenOSCreationPhase (newPhase); + } + catch (Exception &e) + { + e.Show (MainDlg); + return FALSE; + } + + //// The contents of the following items might be inappropriate after a change of the phase + //szFileName[0] = 0; + //szDiskFile[0] = 0; + //nUIVolumeSize = 0; + //nVolumeSize = 0; + + return TRUE; +} + +// IMPORTANT: This function may be called only by Format (other modules can only _read_ the system encryption status). +// Returns TRUE if successful (otherwise FALSE) +static BOOL ChangeSystemEncryptionStatus (int newStatus) +{ + if (!CreateSysEncMutex ()) + { + Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); + return FALSE; // Only one instance that has the mutex can modify the system encryption settings + } + + SystemEncryptionStatus = newStatus; + bSystemEncryptionStatusChanged = TRUE; + + if (newStatus == SYSENC_STATUS_ENCRYPTING) + { + // If the user has created a hidden OS and now is creating a decoy OS, we must wipe the hidden OS + // config area in the MBR. + WipeHiddenOSCreationConfig(); + } + + if (newStatus == SYSENC_STATUS_NONE && !IsHiddenOSRunning()) + { + if (DetermineHiddenOSCreationPhase() != TC_HIDDEN_OS_CREATION_PHASE_NONE + && !ChangeHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE)) + return FALSE; + + WipeHiddenOSCreationConfig(); + } + + if (!SaveSysEncSettings (MainDlg)) + { + return FALSE; + } + + return TRUE; +} + +// If the return code of this function is ignored and newWizardMode == WIZARD_MODE_SYS_DEVICE, then this function +// may be called only after CreateSysEncMutex() returns TRUE. It returns TRUE if successful (otherwise FALSE). +static BOOL ChangeWizardMode (int newWizardMode) +{ + if (WizardMode != newWizardMode) + { + if (WizardMode == WIZARD_MODE_SYS_DEVICE || newWizardMode == WIZARD_MODE_SYS_DEVICE) + { + if (newWizardMode == WIZARD_MODE_SYS_DEVICE) + { + if (!CreateSysEncMutex ()) + { + Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); + return FALSE; + } + } + + // If the previous mode was different, the password may have been typed using a different + // keyboard layout (which might confuse the user and cause other problems if system encryption + // was or will be involved). + WipePasswordsAndKeyfiles(); + } + + if (newWizardMode != WIZARD_MODE_NONSYS_DEVICE) + { + bInPlaceEncNonSys = FALSE; + bInPlaceDecNonSys = FALSE; + } + + if (newWizardMode == WIZARD_MODE_NONSYS_DEVICE && !IsAdmin() && IsUacSupported()) + { + if (!ElevateWholeWizardProcess (L"/e")) + return FALSE; + } + + // The contents of the following items may be inappropriate after a change of mode + if (! (bInPlaceDecNonSys && !bInPlaceEncNonSysResumed)) // If we are starting (but not resuming) decryption of non-system volume, we actually need szFileName as it contains the command line param. + szFileName[0] = 0; + szDiskFile[0] = 0; + nUIVolumeSize = 0; + nVolumeSize = 0; + + WizardMode = newWizardMode; + } + + bDevice = (WizardMode != WIZARD_MODE_FILE_CONTAINER); + + if (newWizardMode != WIZARD_MODE_SYS_DEVICE + && !bHiddenOS) + { + CloseSysEncMutex (); + } + + return TRUE; +} + +// Determines whether the wizard directly affects system encryption in any way. +// Note, for example, that when the user enters a password for a hidden volume that is to host a hidden OS, +// WizardMode is NOT set to WIZARD_MODE_SYS_DEVICE. The keyboard layout, however, has to be US. That's why +// this function has to be called instead of checking the value of WizardMode. +static BOOL SysEncInEffect (void) +{ + return (WizardMode == WIZARD_MODE_SYS_DEVICE + || CreatingHiddenSysVol()); +} + +static BOOL CreatingHiddenSysVol (void) +{ + return (bHiddenOS + && bHiddenVol && !bHiddenVolHost); +} + +static void LoadSettingsAndCheckModified (HWND hwndDlg, BOOL bOnlyCheckModified, BOOL* pbSettingsModified, BOOL* pbHistoryModified) +{ + if (!bOnlyCheckModified) + EnableHwEncryption ((ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? FALSE : TRUE); + + WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE; + + if (!bOnlyCheckModified) + LoadSysEncSettings (); + + if (!bOnlyCheckModified && LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) != 0) + bInPlaceEncNonSysPending = TRUE; + + if (!bOnlyCheckModified) + defaultKeyFilesParam.EnableKeyFiles = FALSE; + + ConfigReadCompareInt ("StartOnLogon", FALSE, &bStartOnLogon, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("HiddenSectorDetectionStatus", 0, &HiddenSectorDetectionStatus, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("ShowDisconnectedNetworkDrives", FALSE, &bShowDisconnectedNetworkDrives, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("HideWaitingDialog", FALSE, &bHideWaitingDialog, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("SaveVolumeHistory", FALSE, &bHistory, bOnlyCheckModified, pbSettingsModified); + + { + char szTmp[MAX_PATH] = {0}; + WideCharToMultiByte (CP_UTF8, 0, SecurityTokenLibraryPath, -1, szTmp, MAX_PATH, NULL, NULL); + ConfigReadCompareString ("SecurityTokenLibrary", "", szTmp, sizeof (szTmp) - 1, bOnlyCheckModified, pbSettingsModified); + MultiByteToWideChar (CP_UTF8, 0, szTmp, -1, SecurityTokenLibraryPath, ARRAYSIZE (SecurityTokenLibraryPath)); + + if (!bOnlyCheckModified && SecurityTokenLibraryPath[0]) + InitSecurityTokenLibrary(hwndDlg); + } + + if (bOnlyCheckModified) + { + char langid[6] = {0}; + if (!IsNonInstallMode ()) + { + ConfigReadString ("Language", "", langid, sizeof (langid)); + // when installed, if no preferred language set by user, English is selected default + if (langid [0] == 0) + StringCbCopyA (langid, sizeof(langid), "en"); + + if (pbSettingsModified && strcmp (langid, GetPreferredLangId ())) + *pbSettingsModified = TRUE; + } + else + { + StringCbCopyA (langid, sizeof(langid), GetPreferredLangId ()); + ConfigReadCompareString ("Language", "", langid, sizeof (langid), TRUE, pbSettingsModified); + } + } + + if (hwndDlg != NULL) + { + LoadCombo (GetDlgItem (hwndDlg, IDC_COMBO_BOX), bHistory, bOnlyCheckModified, pbHistoryModified); + return; + } + + if (bHistoryCmdLine) + return; +} + +static void LoadSettings (HWND hwndDlg) +{ + LoadSettingsAndCheckModified (hwndDlg, FALSE, NULL, NULL); +} + +static void SaveSettings (HWND hwndDlg) +{ + WaitCursor (); + + // Check first if modifications ocurred before writing to the settings and history files + // This avoids leaking information about VeraCrypt usage when user only mount volumes without changing setttings or history + BOOL bSettingsChanged = FALSE; + BOOL bHistoryChanged = FALSE; + + LoadSettingsAndCheckModified (hwndDlg, TRUE, &bSettingsChanged, &bHistoryChanged); + + if (bHistoryChanged && hwndDlg != NULL) + DumpCombo (GetDlgItem (hwndDlg, IDC_COMBO_BOX), !bHistory); + + if (bSettingsChanged) + { + ConfigWriteBegin (); + + ConfigWriteInt ("StartOnLogon", bStartOnLogon); + ConfigWriteInt ("HiddenSectorDetectionStatus", HiddenSectorDetectionStatus); + ConfigWriteInt ("SaveVolumeHistory", bHistory); + ConfigWriteStringW ("SecurityTokenLibrary", SecurityTokenLibraryPath[0] ? SecurityTokenLibraryPath : L""); + + ConfigWriteString ("Language", GetPreferredLangId ()); + + ConfigWriteEnd (hwndDlg); + } + + NormalCursor (); +} + +// WARNING: This function does NOT cause immediate application exit (use e.g. return 1 after calling it +// from a DialogProc function). +static void EndMainDlg (HWND hwndDlg) +{ + if (nCurPageNo == VOLUME_LOCATION_PAGE) + { + if (IsWindow(GetDlgItem(hCurPage, IDC_NO_HISTORY))) + bHistory = !IsButtonChecked (GetDlgItem (hCurPage, IDC_NO_HISTORY)); + + MoveEditToCombo (GetDlgItem (hCurPage, IDC_COMBO_BOX), bHistory); + SaveSettings (hCurPage); + } + else + { + SaveSettings (NULL); + } + + SaveSysEncSettings (hwndDlg); + + if (!bHistory) + CleanLastVisitedMRU (); + + EndDialog (hwndDlg, 0); +} + +// Returns TRUE if system encryption or decryption had been or is in progress and has not been completed +static BOOL SysEncryptionOrDecryptionRequired (void) +{ + /* If you update this function, revise SysEncryptionOrDecryptionRequired() in Mount.c as well. */ + + static BootEncryptionStatus locBootEncStatus; + + try + { + locBootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + return (SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING + || SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING + || + ( + locBootEncStatus.DriveMounted + && + ( + locBootEncStatus.ConfiguredEncryptedAreaStart != locBootEncStatus.EncryptedAreaStart + || locBootEncStatus.ConfiguredEncryptedAreaEnd != locBootEncStatus.EncryptedAreaEnd + ) + ) + ); +} + +// Returns TRUE if the system partition/drive is completely encrypted +static BOOL SysDriveOrPartitionFullyEncrypted (BOOL bSilent) +{ + /* If you update this function, revise SysDriveOrPartitionFullyEncrypted() in Mount.c as well. */ + + static BootEncryptionStatus locBootEncStatus; + + try + { + locBootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + if (!bSilent) + e.Show (MainDlg); + } + + return (!locBootEncStatus.SetupInProgress + && locBootEncStatus.ConfiguredEncryptedAreaEnd != 0 + && locBootEncStatus.ConfiguredEncryptedAreaEnd != -1 + && locBootEncStatus.ConfiguredEncryptedAreaStart == locBootEncStatus.EncryptedAreaStart + && locBootEncStatus.ConfiguredEncryptedAreaEnd == locBootEncStatus.EncryptedAreaEnd); +} + +// This functions is to be used when the wizard mode needs to be changed to WIZARD_MODE_SYS_DEVICE. +// If the function fails to switch the mode, it returns FALSE (otherwise TRUE). +BOOL SwitchWizardToSysEncMode (void) +{ + WaitCursor (); + + try + { + BootEncStatus = BootEncObj->GetStatus(); + bWholeSysDrive = BootEncObj->SystemPartitionCoversWholeDrive(); + } + catch (Exception &e) + { + e.Show (MainDlg); + Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); + NormalCursor (); + return FALSE; + } + + // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption + if (!CreateSysEncMutex ()) + { + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); + NormalCursor (); + return FALSE; + } + + // User-mode app may have crashed and its mutex may have gotten lost, so we need to check the driver status too + if (BootEncStatus.SetupInProgress) + { + if (AskWarnYesNo ("SYSTEM_ENCRYPTION_RESUME_PROMPT", MainDlg) == IDYES) + { + if (SystemEncryptionStatus != SYSENC_STATUS_ENCRYPTING + && SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING) + { + // The config file with status was lost or not written correctly + if (!ResolveUnknownSysEncDirection ()) + { + CloseSysEncMutex (); + NormalCursor (); + return FALSE; + } + } + + bDirectSysEncMode = TRUE; + ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); + LoadPage (MainDlg, SYSENC_ENCRYPTION_PAGE); + NormalCursor (); + return TRUE; + } + else + { + CloseSysEncMutex (); + Error ("SYS_ENCRYPTION_OR_DECRYPTION_IN_PROGRESS", MainDlg); + NormalCursor (); + return FALSE; + } + } + + if (BootEncStatus.DriveMounted + || BootEncStatus.DriveEncrypted + || SysEncryptionOrDecryptionRequired ()) + { + + if (!SysDriveOrPartitionFullyEncrypted (FALSE) + && AskWarnYesNo ("SYSTEM_ENCRYPTION_RESUME_PROMPT", MainDlg) == IDYES) + { + if (SystemEncryptionStatus == SYSENC_STATUS_NONE) + { + // If the config file with status was lost or not written correctly, we + // don't know whether to encrypt or decrypt (but we know that encryption or + // decryption is required). Ask the user to select encryption, decryption, + // or cancel + if (!ResolveUnknownSysEncDirection ()) + { + CloseSysEncMutex (); + NormalCursor (); + return FALSE; + } + } + + bDirectSysEncMode = TRUE; + ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); + LoadPage (MainDlg, SYSENC_ENCRYPTION_PAGE); + NormalCursor (); + return TRUE; + } + else + { + CloseSysEncMutex (); + Error ("SETUP_FAILED_BOOT_DRIVE_ENCRYPTED", MainDlg); + NormalCursor (); + return FALSE; + } + } + else + { + // Check compliance with requirements for boot encryption + + if (!IsAdmin()) + { + if (!IsUacSupported()) + { + Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", MainDlg); + } + } + + try + { + BootEncObj->CheckRequirements (); + } + catch (Exception &e) + { + CloseSysEncMutex (); + e.Show (MainDlg); + NormalCursor (); + return FALSE; + } + + if (!ChangeWizardMode (WIZARD_MODE_SYS_DEVICE)) + { + NormalCursor (); + return FALSE; + } + + if (bSysDriveSelected || bSysPartitionSelected) + { + // The user selected the non-sys-device wizard mode but then selected a system device + + bWholeSysDrive = (bSysDriveSelected && !bSysPartitionSelected); + + bSysDriveSelected = FALSE; + bSysPartitionSelected = FALSE; + + try + { + if (!bHiddenVol) + { + if (bWholeSysDrive && !BootEncObj->SystemPartitionCoversWholeDrive()) + { + if (BootEncObj->SystemDriveContainsNonStandardPartitions()) + { + if (AskWarnYesNoString ((wstring (GetString ("SYSDRIVE_NON_STANDARD_PARTITIONS")) + L"\n\n" + GetString ("ASK_ENCRYPT_PARTITION_INSTEAD_OF_DRIVE")).c_str(), MainDlg) == IDYES) + bWholeSysDrive = FALSE; + } + + if (!IsOSAtLeast (WIN_VISTA) && bWholeSysDrive) + { + if (BootEncObj->SystemDriveContainsExtendedPartition()) + { + bWholeSysDrive = FALSE; + + Error ("WDE_UNSUPPORTED_FOR_EXTENDED_PARTITIONS", MainDlg); + + if (AskYesNo ("ASK_ENCRYPT_PARTITION_INSTEAD_OF_DRIVE", MainDlg) == IDNO) + { + ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE); + return FALSE; + } + } + else + Warning ("WDE_EXTENDED_PARTITIONS_WARNING", MainDlg); + } + } + else if (BootEncObj->SystemPartitionCoversWholeDrive() + && !bWholeSysDrive) + bWholeSysDrive = (AskYesNo ("WHOLE_SYC_DEVICE_RECOM", MainDlg) == IDYES); + } + + } + catch (Exception &e) + { + e.Show (MainDlg); + return FALSE; + } + + if (!bHiddenVol) + { + // Skip SYSENC_SPAN_PAGE and SYSENC_TYPE_PAGE as the user already made the choice + LoadPage (MainDlg, bWholeSysDrive ? SYSENC_PRE_DRIVE_ANALYSIS_PAGE : SYSENC_MULTI_BOOT_MODE_PAGE); + } + else + { + // The user selected the non-sys-device wizard mode but then selected a system device. + // In addition, he selected the hidden volume mode. + + if (bWholeSysDrive) + Warning ("HIDDEN_OS_PRECLUDES_SINGLE_KEY_WDE", MainDlg); + + bWholeSysDrive = FALSE; + + LoadPage (MainDlg, SYSENC_TYPE_PAGE); + } + } + else + LoadPage (MainDlg, SYSENC_TYPE_PAGE); + + NormalCursor (); + return TRUE; + } +} + +void SwitchWizardToFileContainerMode (void) +{ + ChangeWizardMode (WIZARD_MODE_FILE_CONTAINER); + + LoadPage (MainDlg, VOLUME_LOCATION_PAGE); + + NormalCursor (); +} + +void SwitchWizardToNonSysDeviceMode (void) +{ + ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE); + + LoadPage (MainDlg, VOLUME_TYPE_PAGE); + + NormalCursor (); +} + +BOOL SwitchWizardToHiddenOSMode (void) +{ + if (SwitchWizardToSysEncMode()) + { + if (nCurPageNo != SYSENC_ENCRYPTION_PAGE) // If the user did not manually choose to resume encryption or decryption of the system partition/drive + { + bHiddenOS = TRUE; + bHiddenVol = TRUE; + bHiddenVolHost = TRUE; + bHiddenVolDirect = FALSE; + bWholeSysDrive = FALSE; + bInPlaceEncNonSys = FALSE; + bInPlaceDecNonSys = FALSE; + + if (bDirectSysEncModeCommand == SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV) + { + // Some of the requirements for hidden OS should have already been checked by the wizard process + // that launched us (in order to elevate), but we must recheck them. Otherwise, an advanced user + // could bypass the checks by using the undocumented CLI switch. Moreover, some requirements + // can be checked only at this point (when we are elevated). + try + { + BootEncObj->CheckRequirementsHiddenOS (); + + BootEncObj->InitialSecurityChecksForHiddenOS (); + } + catch (Exception &e) + { + e.Show (MainDlg); + return FALSE; + } + + LoadPage (MainDlg, SYSENC_MULTI_BOOT_MODE_PAGE); + } + else + LoadPage (MainDlg, SYSENC_HIDDEN_OS_REQ_CHECK_PAGE); + + NormalCursor (); + } + else + return TRUE; + } + else + return FALSE; + + return TRUE; +} + +void SwitchWizardToNonSysInplaceEncResumeMode (BOOL bDecrypt) +{ + if (!IsAdmin() && IsUacSupported()) + { + if (!ElevateWholeWizardProcess (bDecrypt ? L"/resumeinplacedec" : L"/zinplace")) + AbortProcessSilent (); + } + + if (!IsAdmin()) + AbortProcess("ADMIN_PRIVILEGES_WARN_DEVICES"); + + CreateNonSysInplaceEncMutex (); + + bInPlaceEncNonSys = TRUE; + bInPlaceDecNonSys = bDecrypt; + bInPlaceEncNonSysResumed = TRUE; + + ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE); + + LoadPage (MainDlg, NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE); +} + +void SwitchWizardToNonSysInplaceDecStartMode (wchar_t *volPath) +{ + if (!IsAdmin() && IsUacSupported()) + { + if (!ElevateWholeWizardProcess ((wstring (L"/inplacedec \"") + volPath + L"\"").c_str())) + AbortProcessSilent (); + } + + if (!IsAdmin()) + AbortProcess("ADMIN_PRIVILEGES_WARN_DEVICES"); + + if (!CheckRequirementsForNonSysInPlaceDec (MainDlg, volPath, FALSE)) + AbortProcessSilent (); + + CreateNonSysInplaceEncMutex (); + + bInPlaceEncNonSys = TRUE; + bInPlaceDecNonSys = TRUE; + bInPlaceEncNonSysResumed = FALSE; + + ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE); + + LoadPage (MainDlg, NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE); +} + +// Use this function e.g. if the config file with the system encryption settings was lost or not written +// correctly, and we don't know whether to encrypt or decrypt (but we know that encryption or decryption +// is required). Returns FALSE if failed or cancelled. +static BOOL ResolveUnknownSysEncDirection (void) +{ + if (CreateSysEncMutex ()) + { + if (SystemEncryptionStatus != SYSENC_STATUS_ENCRYPTING + && SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING) + { + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); + return FALSE; + } + + if (BootEncStatus.SetupInProgress) + { + return ChangeSystemEncryptionStatus ( + (BootEncStatus.SetupMode != SetupDecryption) ? SYSENC_STATUS_ENCRYPTING : SYSENC_STATUS_DECRYPTING); + } + else + { + // Ask the user to select encryption, decryption, or cancel + + char *tmpStr[] = {0, + !BootEncStatus.DriveEncrypted ? "CHOOSE_ENCRYPT_OR_DECRYPT_FINALIZE_DECRYPT_NOTE" : "CHOOSE_ENCRYPT_OR_DECRYPT", + "ENCRYPT", + "DECRYPT", + "IDCANCEL", + 0}; + + switch (AskMultiChoice ((void **) tmpStr, FALSE, MainDlg)) + { + case 1: + return ChangeSystemEncryptionStatus (SYSENC_STATUS_ENCRYPTING); + case 2: + return ChangeSystemEncryptionStatus (SYSENC_STATUS_DECRYPTING); + default: + return FALSE; + } + } + } + else + return TRUE; + } + else + { + Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); + return FALSE; + } +} + +// This function should be used to resolve inconsistencies that might lead to a deadlock (inability to encrypt or +// decrypt the system partition/drive and to uninstall TrueCrypt). The function removes the system encryption key +// data ("volume header"), the TrueCrypt boot loader, restores the original system loader (if available), +// unregisters the boot driver, etc. Note that if the system partition/drive is encrypted, it will start decrypting +// it in the background (therefore, it should be used when the system partition/drive is not encrypted, ideally). +// Exceptions are handled and errors are reported within the function. Returns TRUE if successful. +static BOOL ForceRemoveSysEnc (void) +{ + if (CreateSysEncMutex ()) // If no other instance is currently taking care of system encryption + { + BootEncryptionStatus locBootEncStatus; + + try + { + locBootEncStatus = BootEncObj->GetStatus(); + + if (locBootEncStatus.SetupInProgress) + BootEncObj->AbortSetupWait (); + + locBootEncStatus = BootEncObj->GetStatus(); + + if (locBootEncStatus.DriveMounted) + { + // Remove the header + BootEncObj->StartDecryption (DiscardUnreadableEncryptedSectors); + locBootEncStatus = BootEncObj->GetStatus(); + + while (locBootEncStatus.SetupInProgress) + { + Sleep (100); + locBootEncStatus = BootEncObj->GetStatus(); + } + + BootEncObj->CheckEncryptionSetupResult (); + } + + Sleep (50); + } + catch (Exception &e) + { + e.Show (MainDlg); + return FALSE; + } + + try + { + locBootEncStatus = BootEncObj->GetStatus(); + + if (!locBootEncStatus.DriveMounted) + BootEncObj->Deinstall (true); + } + catch (Exception &e) + { + e.Show (MainDlg); + return FALSE; + } + + return TRUE; + } + else + return FALSE; +} + +// Returns 0 if there's an error. +__int64 GetSystemPartitionSize (void) +{ + try + { + return BootEncObj->GetSystemDriveConfiguration().SystemPartition.Info.PartitionLength.QuadPart; + } + catch (Exception &e) + { + e.Show (MainDlg); + return 0; + } +} + +void ComboSelChangeEA (HWND hwndDlg) +{ + int nIndex = (int) SendMessage (GetDlgItem (hwndDlg, IDC_COMBO_BOX), CB_GETCURSEL, 0, 0); + + if (nIndex == CB_ERR) + { + SetWindowText (GetDlgItem (hwndDlg, IDC_BOX_HELP), L""); + } + else + { + wchar_t name[100]; + wchar_t auxLine[4096]; + wchar_t hyperLink[256] = { 0 }; + int cipherIDs[5]; + int i, cnt = 0; + + nIndex = (int) SendMessage (GetDlgItem (hwndDlg, IDC_COMBO_BOX), CB_GETITEMDATA, nIndex, 0); + EAGetName (name, nIndex, 0); + + if (wcscmp (name, L"AES") == 0) + { + StringCbPrintfW (hyperLink, sizeof(hyperLink) / 2, GetString ("MORE_INFO_ABOUT"), name); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("AES_HELP")); + } + else if (wcscmp (name, L"Serpent") == 0) + { + StringCbPrintfW (hyperLink, sizeof(hyperLink) / 2, GetString ("MORE_INFO_ABOUT"), name); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SERPENT_HELP")); + } + else if (wcscmp (name, L"Twofish") == 0) + { + StringCbPrintfW (hyperLink, sizeof(hyperLink) / 2, GetString ("MORE_INFO_ABOUT"), name); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("TWOFISH_HELP")); + } + else if (EAGetCipherCount (nIndex) > 1) + { + // Cascade + cipherIDs[cnt++] = i = EAGetLastCipher(nIndex); + while (i = EAGetPreviousCipher(nIndex, i)) + { + cipherIDs[cnt] = i; + cnt++; + } + + switch (cnt) // Number of ciphers in the cascade + { + case 2: + StringCbPrintfW (auxLine, sizeof(auxLine), GetString ("TWO_LAYER_CASCADE_HELP"), + CipherGetName (cipherIDs[1]), + CipherGetKeySize (cipherIDs[1])*8, + CipherGetName (cipherIDs[0]), + CipherGetKeySize (cipherIDs[0])*8); + break; + + case 3: + StringCbPrintfW (auxLine, sizeof(auxLine), GetString ("THREE_LAYER_CASCADE_HELP"), + CipherGetName (cipherIDs[2]), + CipherGetKeySize (cipherIDs[2])*8, + CipherGetName (cipherIDs[1]), + CipherGetKeySize (cipherIDs[1])*8, + CipherGetName (cipherIDs[0]), + CipherGetKeySize (cipherIDs[0])*8); + break; + } + + StringCbCopyW (hyperLink, sizeof(hyperLink), GetString ("IDC_LINK_MORE_INFO_ABOUT_CIPHER")); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), auxLine); + } + else + { + // No info available for this encryption algorithm + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), L""); + } + + + // Update hyperlink + SetWindowTextW (GetDlgItem (hwndDlg, IDC_LINK_MORE_INFO_ABOUT_CIPHER), hyperLink); + AccommodateTextField (hwndDlg, IDC_LINK_MORE_INFO_ABOUT_CIPHER, FALSE, hUserUnderlineFont); + } +} + +static void VerifySizeAndUpdate (HWND hwndDlg, BOOL bUpdate) +{ + BOOL bEnable = TRUE; + wchar_t szTmp[50]; + __int64 lTmp; + __int64 i; + static unsigned __int64 nLastVolumeSize = 0; + + GetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTmp, ARRAYSIZE (szTmp)); + + for (i = 0; i < (__int64) wcslen (szTmp); i++) + { + if (szTmp[i] >= L'0' && szTmp[i] <= L'9') + continue; + else + { + bEnable = FALSE; + break; + } + } + + if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_KB))) + nMultiplier = BYTES_PER_KB; + else if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_MB))) + nMultiplier = BYTES_PER_MB; + else if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_GB))) + nMultiplier = BYTES_PER_GB; + else + nMultiplier = BYTES_PER_TB; + + if (bDevice && !(bHiddenVol && !bHiddenVolHost)) // If raw device but not a hidden volume + { + lTmp = nVolumeSize; + i = 1; + } + else + { + i = nMultiplier; + lTmp = _wtoi64 (szTmp); + + DWORD sectorSize = GetFormatSectorSize(); + uint32 sectorSizeRem = (lTmp * nMultiplier) % sectorSize; + + if (sectorSizeRem != 0) + lTmp = (lTmp * nMultiplier + (sectorSize - sectorSizeRem)) / nMultiplier; + } + + if (bEnable) + { + if (lTmp * i < (bHiddenVolHost ? TC_MIN_HIDDEN_VOLUME_HOST_SIZE : (bHiddenVol ? TC_MIN_HIDDEN_VOLUME_SIZE : TC_MIN_VOLUME_SIZE))) + bEnable = FALSE; + + if (!bHiddenVolHost && bHiddenVol) + { + if (lTmp * i > nMaximumHiddenVolSize) + bEnable = FALSE; + } + else + { + if (lTmp * i > (bHiddenVolHost ? TC_MAX_HIDDEN_VOLUME_HOST_SIZE : TC_MAX_VOLUME_SIZE)) + bEnable = FALSE; + } + } + + if (bUpdate) + { + nUIVolumeSize = lTmp; + + if (!bDevice || (bHiddenVol && !bHiddenVolHost)) // Update only if it's not a raw device or if it's a hidden volume + nVolumeSize = i * lTmp; + } + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), bEnable); + + if (nVolumeSize != nLastVolumeSize) + { + // Change of volume size may make some file systems allowed or disallowed, so the default filesystem must + // be reselected. + fileSystem = FILESYS_NONE; + nLastVolumeSize = nVolumeSize; + } +} + +static void UpdateWizardModeControls (HWND hwndDlg, int setWizardMode) +{ + SendMessage (GetDlgItem (hwndDlg, IDC_FILE_CONTAINER), + BM_SETCHECK, + setWizardMode == WIZARD_MODE_FILE_CONTAINER ? BST_CHECKED : BST_UNCHECKED, + 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_NONSYS_DEVICE), + BM_SETCHECK, + setWizardMode == WIZARD_MODE_NONSYS_DEVICE ? BST_CHECKED : BST_UNCHECKED, + 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_SYS_DEVICE), + BM_SETCHECK, + setWizardMode == WIZARD_MODE_SYS_DEVICE ? BST_CHECKED : BST_UNCHECKED, + 0); +} + +static int GetSelectedWizardMode (HWND hwndDlg) +{ + if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_FILE_CONTAINER))) + return WIZARD_MODE_FILE_CONTAINER; + + if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_NONSYS_DEVICE))) + return WIZARD_MODE_NONSYS_DEVICE; + + if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_SYS_DEVICE))) + return WIZARD_MODE_SYS_DEVICE; + + return DEFAULT_VOL_CREATION_WIZARD_MODE; +} + +static void RefreshMultiBootControls (HWND hwndDlg) +{ +#ifdef DEBUG + if (nMultiBoot == 0) + nMultiBoot = 1; +#endif + + SendMessage (GetDlgItem (hwndDlg, IDC_SINGLE_BOOT), + BM_SETCHECK, + nMultiBoot == 1 ? BST_CHECKED : BST_UNCHECKED, + 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_MULTI_BOOT), + BM_SETCHECK, + nMultiBoot > 1 ? BST_CHECKED : BST_UNCHECKED, + 0); +} + +// -1 = Undecided or error, 0 = No, 1 = Yes +static int Get2RadButtonPageAnswer (void) +{ + if (IsButtonChecked (GetDlgItem (hCurPage, IDC_CHOICE1))) + return 1; + + if (IsButtonChecked (GetDlgItem (hCurPage, IDC_CHOICE2))) + return 0; + + return -1; +} + +// 0 = No, 1 = Yes +static void Update2RadButtonPage (int answer) +{ + SendMessage (GetDlgItem (hCurPage, IDC_CHOICE1), + BM_SETCHECK, + answer == 1 ? BST_CHECKED : BST_UNCHECKED, + 0); + + SendMessage (GetDlgItem (hCurPage, IDC_CHOICE2), + BM_SETCHECK, + answer == 0 ? BST_CHECKED : BST_UNCHECKED, + 0); +} + +// -1 = Undecided, 0 = No, 1 = Yes +static void Init2RadButtonPageYesNo (int answer) +{ + SetWindowTextW (GetDlgItem (hCurPage, IDC_CHOICE1), GetString ("UISTR_YES")); + SetWindowTextW (GetDlgItem (hCurPage, IDC_CHOICE2), GetString ("UISTR_NO")); + + SetWindowTextW (GetDlgItem (MainDlg, IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (MainDlg, IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); + + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), answer >= 0); + EnableWindow (GetDlgItem (MainDlg, IDC_PREV), TRUE); + + Update2RadButtonPage (answer); +} + +static void UpdateSysEncProgressBar (void) +{ + BootEncryptionStatus locBootEncStatus; + + try + { + locBootEncStatus = BootEncObj->GetStatus(); + } + catch (...) + { + return; + } + + if (locBootEncStatus.EncryptedAreaEnd == -1 + || locBootEncStatus.EncryptedAreaStart == -1) + { + UpdateProgressBarProc (0); + } + else + { + UpdateProgressBarProc (locBootEncStatus.EncryptedAreaEnd - locBootEncStatus.EncryptedAreaStart + 1); + + if (locBootEncStatus.SetupInProgress) + { + wchar_t tmpStr[100]; + + // Status + + if (locBootEncStatus.TransformWaitingForIdle) + StringCbCopyW (tmpStr, sizeof(tmpStr), GetString ("PROGRESS_STATUS_WAITING")); + else + StringCbCopyW (tmpStr, sizeof(tmpStr), GetString (SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING ? "PROGRESS_STATUS_DECRYPTING" : "PROGRESS_STATUS_ENCRYPTING")); + + StringCbCatW (tmpStr, sizeof(tmpStr), L" "); + + SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), tmpStr); + } + } +} + +static void InitSysEncProgressBar (void) +{ + BootEncryptionStatus locBootEncStatus; + + try + { + locBootEncStatus = BootEncObj->GetStatus(); + } + catch (...) + { + return; + } + + if (locBootEncStatus.ConfiguredEncryptedAreaEnd == -1 + || locBootEncStatus.ConfiguredEncryptedAreaStart == -1) + return; + + InitProgressBar (locBootEncStatus.ConfiguredEncryptedAreaEnd + - locBootEncStatus.ConfiguredEncryptedAreaStart + 1, + (locBootEncStatus.EncryptedAreaEnd == locBootEncStatus.EncryptedAreaStart || locBootEncStatus.EncryptedAreaEnd == -1) ? + 0 : locBootEncStatus.EncryptedAreaEnd - locBootEncStatus.EncryptedAreaStart + 1, + SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING, + TRUE, + TRUE, + TRUE); +} + +static void UpdateSysEncControls (void) +{ + BootEncryptionStatus locBootEncStatus; + + try + { + locBootEncStatus = BootEncObj->GetStatus(); + } + catch (...) + { + return; + } + + EnableWindow (GetDlgItem (hCurPage, IDC_WIPE_MODE), + !locBootEncStatus.SetupInProgress + && SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING); + + SetWindowTextW (GetDlgItem (hCurPage, IDC_PAUSE), + GetString (locBootEncStatus.SetupInProgress ? "IDC_PAUSE" : "RESUME")); + + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), !locBootEncStatus.SetupInProgress && !bFirstSysEncResumeDone); + + if (!locBootEncStatus.SetupInProgress) + { + wchar_t tmpStr[100]; + + StringCbCopyW (tmpStr, sizeof(tmpStr), GetString ((SysDriveOrPartitionFullyEncrypted (TRUE) || !locBootEncStatus.DriveMounted) ? + "PROGRESS_STATUS_FINISHED" : "PROGRESS_STATUS_PAUSED")); + StringCbCatW (tmpStr, sizeof(tmpStr), L" "); + + // Status + SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), tmpStr); + + if (SysDriveOrPartitionFullyEncrypted (TRUE) || SystemEncryptionStatus == SYSENC_STATUS_NONE) + { + StringCbCopyW (tmpStr, sizeof(tmpStr), GetString ("PROCESSED_PORTION_100_PERCENT")); + StringCbCatW (tmpStr, sizeof(tmpStr), L" "); + + SetWindowTextW (GetDlgItem (hCurPage, IDC_BYTESWRITTEN), tmpStr); + } + + SetWindowText (GetDlgItem (hCurPage, IDC_TIMEREMAIN), L" "); + } +} + +static void SysEncPause (void) +{ + BootEncryptionStatus locBootEncStatus; + + if (CreateSysEncMutex ()) + { + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), FALSE); + + try + { + locBootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); + return; + } + + if (!locBootEncStatus.SetupInProgress) + { + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); + return; + } + + WaitCursor (); + + try + { + int attempts = SYSENC_PAUSE_RETRIES; + + BootEncObj->AbortSetup (); + + locBootEncStatus = BootEncObj->GetStatus(); + + while (locBootEncStatus.SetupInProgress && attempts > 0) + { + Sleep (SYSENC_PAUSE_RETRY_INTERVAL); + attempts--; + locBootEncStatus = BootEncObj->GetStatus(); + } + + if (!locBootEncStatus.SetupInProgress) + BootEncObj->CheckEncryptionSetupResult (); + + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + NormalCursor (); + + if (locBootEncStatus.SetupInProgress) + { + SetTimer (MainDlg, TIMER_ID_SYSENC_PROGRESS, TIMER_INTERVAL_SYSENC_PROGRESS, NULL); + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); + Error ("FAILED_TO_INTERRUPT_SYSTEM_ENCRYPTION", MainDlg); + return; + } + + UpdateSysEncControls (); + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); + } + else + Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); +} + + +static void SysEncResume (void) +{ + BootEncryptionStatus locBootEncStatus; + + if (CreateSysEncMutex ()) + { + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), FALSE); + + try + { + locBootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); + return; + } + + if (locBootEncStatus.SetupInProgress) + { + // Prevent the OS from entering Sleep mode when idle + SetThreadExecutionState (ES_CONTINUOUS | ES_SYSTEM_REQUIRED); + + bSystemEncryptionInProgress = TRUE; + UpdateSysEncControls (); + SetTimer (MainDlg, TIMER_ID_SYSENC_PROGRESS, TIMER_INTERVAL_SYSENC_PROGRESS, NULL); + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); + return; + } + + bVolTransformThreadCancel = FALSE; + bSystemEncryptionInProgress = FALSE; + WaitCursor (); + + try + { + switch (SystemEncryptionStatus) + { + case SYSENC_STATUS_ENCRYPTING: + + BootEncObj->StartEncryption (nWipeMode, bTryToCorrectReadErrors ? true : false); + break; + + case SYSENC_STATUS_DECRYPTING: + + if (locBootEncStatus.DriveMounted) // If the drive is not encrypted we will just deinstall + BootEncObj->StartDecryption (DiscardUnreadableEncryptedSectors); + + break; + } + + bSystemEncryptionInProgress = TRUE; + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + NormalCursor (); + + if (!bSystemEncryptionInProgress) + { + // Allow the OS to enter Sleep mode when idle + SetThreadExecutionState (ES_CONTINUOUS); + + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); + Error ("FAILED_TO_RESUME_SYSTEM_ENCRYPTION", MainDlg); + return; + } + + // Prevent the OS from entering Sleep mode when idle + SetThreadExecutionState (ES_CONTINUOUS | ES_SYSTEM_REQUIRED); + + bFirstSysEncResumeDone = TRUE; + InitSysEncProgressBar (); + UpdateSysEncProgressBar (); + UpdateSysEncControls (); + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); + SetTimer (MainDlg, TIMER_ID_SYSENC_PROGRESS, TIMER_INTERVAL_SYSENC_PROGRESS, NULL); + } + else + Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); +} + + +static BOOL GetDevicePathForHiddenOS (void) +{ + BOOL tmpbDevice = FALSE; + + try + { + StringCbCopyW (szFileName, sizeof(szFileName), BootEncObj->GetPartitionForHiddenOS().DevicePath.c_str()); + + CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice); + } + catch (Exception &e) + { + e.Show (MainDlg); + return FALSE; + } + + return (szFileName[0] != 0 + && szDiskFile[0] != 0 + && tmpbDevice); +} + + +// Returns TRUE if there is unallocated space greater than 64 MB (max possible slack space size) between the +// boot partition and the first partition behind it. If there's none or if an error occurs, returns FALSE. +static BOOL CheckGapBetweenSysAndHiddenOS (void) +{ + try + { + SystemDriveConfiguration sysDriveCfg = BootEncObj->GetSystemDriveConfiguration(); + + return (sysDriveCfg.SystemPartition.Info.StartingOffset.QuadPart + + sysDriveCfg.SystemPartition.Info.PartitionLength.QuadPart + + 64 * BYTES_PER_MB + + 128 * BYTES_PER_KB + <= BootEncObj->GetPartitionForHiddenOS().Info.StartingOffset.QuadPart); + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + return FALSE; +} + + +static void NonSysInplaceEncPause (void) +{ + bVolTransformThreadCancel = TRUE; + + WaitCursor (); + + int waitThreshold = 100; // Do not block GUI events for more than 10 seconds. IMPORTANT: This prevents deadlocks when the thread calls us back e.g. to update GUI! + + while (bVolTransformThreadRunning || bVolTransformThreadToRun) + { + MSG guiMsg; + + bVolTransformThreadCancel = TRUE; + + if (waitThreshold <= 0) + { + while (PeekMessageW (&guiMsg, NULL, 0, 0, PM_REMOVE) != 0) + { + DispatchMessageW (&guiMsg); + } + } + else + waitThreshold--; + + Sleep (100); + } +} + + +static void NonSysInplaceEncResume (void) +{ + if (bVolTransformThreadRunning || bVolTransformThreadToRun || bVolTransformThreadCancel) + return; + + if (!bInPlaceEncNonSysResumed + && !FinalPreTransformPrompts ()) + { + return; + } + + CreateNonSysInplaceEncMutex (); + + bFirstNonSysInPlaceEncResumeDone = TRUE; + + SetTimer (MainDlg, TIMER_ID_NONSYS_INPLACE_ENC_PROGRESS, TIMER_INTERVAL_NONSYS_INPLACE_ENC_PROGRESS, NULL); + + bVolTransformThreadCancel = FALSE; + bVolTransformThreadToRun = TRUE; + + UpdateNonSysInPlaceEncControls (); + + LastDialogId = "NONSYS_INPLACE_ENC_IN_PROGRESS"; + + _beginthread (volTransformThreadFunction, 0, MainDlg); + + return; +} + + +void ShowNonSysInPlaceEncUIStatus (void) +{ + wchar_t nonSysInplaceEncUIStatus [300] = {0}; + + switch (NonSysInplaceEncStatus) + { + case NONSYS_INPLACE_ENC_STATUS_PAUSED: + StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_PAUSED")); + break; + case NONSYS_INPLACE_ENC_STATUS_PREPARING: + StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_PREPARING")); + break; + case NONSYS_INPLACE_ENC_STATUS_RESIZING: + StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_RESIZING")); + break; + case NONSYS_INPLACE_ENC_STATUS_ENCRYPTING: + StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_ENCRYPTING")); + break; + case NONSYS_INPLACE_ENC_STATUS_DECRYPTING: + StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_DECRYPTING")); + break; + case NONSYS_INPLACE_ENC_STATUS_FINALIZING: + StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_FINALIZING")); + break; + case NONSYS_INPLACE_ENC_STATUS_FINISHED: + StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_FINISHED")); + break; + case NONSYS_INPLACE_ENC_STATUS_ERROR: + StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_ERROR")); + break; + } + + StringCbCatW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), L" "); + + SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), nonSysInplaceEncUIStatus); +} + + +void UpdateNonSysInPlaceEncControls (void) +{ + // Reduce flickering by updating a GUI element only when a relevant change affects it + static BOOL lastbVolTransformThreadRunning = !bVolTransformThreadRunning; + static BOOL lastbVolTransformThreadToRun = !bVolTransformThreadToRun; + static BOOL lastbInPlaceEncNonSysResumed = !bInPlaceEncNonSysResumed; + + EnableWindow (GetDlgItem (hCurPage, IDC_WIPE_MODE), !(bVolTransformThreadRunning || bVolTransformThreadToRun) && !bInPlaceDecNonSys); + + if (lastbVolTransformThreadRunning != bVolTransformThreadRunning + || lastbVolTransformThreadToRun != bVolTransformThreadToRun) + { + SetWindowTextW (GetDlgItem (hCurPage, IDC_PAUSE), + GetString ((bVolTransformThreadRunning || bVolTransformThreadToRun) ? "IDC_PAUSE" : "RESUME")); + + lastbVolTransformThreadRunning = bVolTransformThreadRunning; + lastbVolTransformThreadToRun = bVolTransformThreadToRun; + } + + if (lastbInPlaceEncNonSysResumed != bInPlaceEncNonSysResumed) + { + SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString (bInPlaceEncNonSysResumed ? "DEFER" : "CANCEL")); + lastbInPlaceEncNonSysResumed = bInPlaceEncNonSysResumed; + } + + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), bFirstNonSysInPlaceEncResumeDone + && NonSysInplaceEncStatus != NONSYS_INPLACE_ENC_STATUS_FINALIZING + && NonSysInplaceEncStatus != NONSYS_INPLACE_ENC_STATUS_FINISHED); + + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), !(bVolTransformThreadRunning || bVolTransformThreadToRun) && !bFirstNonSysInPlaceEncResumeDone); + EnableWindow (GetDlgItem (MainDlg, IDC_PREV), !(bVolTransformThreadRunning || bVolTransformThreadToRun) && !bInPlaceEncNonSysResumed); + EnableWindow (GetDlgItem (MainDlg, IDCANCEL), + !(bVolTransformThreadToRun + || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_PREPARING + || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_RESIZING + || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINALIZING + || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINISHED)); + + if (bVolTransformThreadRunning || bVolTransformThreadToRun) + { + switch (NonSysInplaceEncStatus) + { + case NONSYS_INPLACE_ENC_STATUS_PREPARING: + case NONSYS_INPLACE_ENC_STATUS_RESIZING: + case NONSYS_INPLACE_ENC_STATUS_FINALIZING: + ArrowWaitCursor (); + break; + + case NONSYS_INPLACE_ENC_STATUS_ENCRYPTING: + NormalCursor (); + break; + + default: + NormalCursor (); + break; + } + + if (bVolTransformThreadCancel) + WaitCursor (); + } + else + { + NormalCursor (); + + if (bInPlaceEncNonSysResumed) + { + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED); + } + else + SetWindowText (GetDlgItem (hCurPage, IDC_WRITESPEED), L" "); + + SetWindowText (GetDlgItem (hCurPage, IDC_TIMEREMAIN), L" "); + } + + ShowNonSysInPlaceEncUIStatus (); + + UpdateNonSysInplaceEncProgressBar (); +} + + +static void UpdateNonSysInplaceEncProgressBar (void) +{ + static int lastNonSysInplaceEncStatus = NONSYS_INPLACE_ENC_STATUS_NONE; + int nonSysInplaceEncStatus = NonSysInplaceEncStatus; + __int64 totalSize = NonSysInplaceEncTotalSize; + + if (bVolTransformThreadRunning + && (nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_ENCRYPTING + || nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_DECRYPTING + || nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINALIZING + || nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINISHED)) + { + if (lastNonSysInplaceEncStatus != nonSysInplaceEncStatus + && (nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_ENCRYPTING || nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_DECRYPTING)) + { + InitNonSysInplaceEncProgressBar (); + } + else + { + if (totalSize <= 0 && nVolumeSize > 0) + totalSize = nVolumeSize; + + if (totalSize > 0) + UpdateProgressBarProc (NonSysInplaceEncBytesDone); + } + } + + ShowNonSysInPlaceEncUIStatus (); + + lastNonSysInplaceEncStatus = nonSysInplaceEncStatus; +} + + +static void InitNonSysInplaceEncProgressBar (void) +{ + __int64 totalSize = NonSysInplaceEncTotalSize; + + if (totalSize <= 0) + { + if (nVolumeSize <= 0) + return; + + totalSize = nVolumeSize; + } + + InitProgressBar (totalSize, + NonSysInplaceEncBytesDone, + bInPlaceDecNonSys, + TRUE, + TRUE, + TRUE); +} + + +void DisplayRandPool (HWND hwndDlg, HWND hPoolDisplay, BOOL bShow) +{ + wchar_t tmp[4]; + unsigned char tmpByte; + int col, row; + static BOOL bRandPoolDispAscii = FALSE; + DWORD mouseEventsCounter; + + RandpeekBytes (hwndDlg, randPool, sizeof (randPool), &mouseEventsCounter); + + ProcessEntropyEstimate (hEntropyBar, &mouseEventsInitialCount, mouseEventsCounter, maxEntropyLevel, &mouseEntropyGathered); + + if (memcmp (lastRandPool, randPool, sizeof(lastRandPool)) != 0) + { + outRandPoolDispBuffer[0] = 0; + + for (row = 0; row < RANDPOOL_DISPLAY_ROWS; row++) + { + for (col = 0; col < RANDPOOL_DISPLAY_COLUMNS; col++) + { + if (bShow) + { + tmpByte = randPool[row * RANDPOOL_DISPLAY_COLUMNS + col]; + + StringCbPrintfW (tmp, sizeof(tmp), bRandPoolDispAscii ? ((tmpByte >= 32 && tmpByte < 255 && tmpByte != L'&') ? L" %c " : L" . ") : L"%02X ", tmpByte); + } + else if (bUseMask) + { + /* use mask to compute a randomized ASCII representation */ + tmpByte = (randPool[row * RANDPOOL_DISPLAY_COLUMNS + col] - + lastRandPool[row * RANDPOOL_DISPLAY_COLUMNS + col]) ^ maskRandPool [row * RANDPOOL_DISPLAY_COLUMNS + col]; + tmp[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); + tmp[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); + tmp[2] = L' '; + tmp[3] = 0; + } + else + { + StringCbCopyW (tmp, sizeof(tmp), L"** "); + } + + + StringCbCatW (outRandPoolDispBuffer, sizeof(outRandPoolDispBuffer), tmp); + } + StringCbCatW (outRandPoolDispBuffer, sizeof(outRandPoolDispBuffer), L"\n"); + } + SetWindowText (hPoolDisplay, outRandPoolDispBuffer); + + memcpy (lastRandPool, randPool, sizeof(lastRandPool)); + } +} + + +void DisplayPortionsOfKeys (HWND headerKeyHandle, HWND masterKeyHandle, wchar_t *headerKeyStr, wchar_t *masterKeyStr, BOOL hideKeys) +{ + const wchar_t *hiddenKey = L"******************************** "; + + SetWindowTextW (headerKeyHandle, hideKeys ? hiddenKey : (std::wstring (headerKeyStr) + GetString ("TRIPLE_DOT_GLYPH_ELLIPSIS")).c_str()); + SetWindowTextW (masterKeyHandle, hideKeys ? hiddenKey : (std::wstring (masterKeyStr) + GetString ("TRIPLE_DOT_GLYPH_ELLIPSIS")).c_str()); +} + + +static void WipeAbort (void) +{ + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), FALSE); + + if (bHiddenOS && IsHiddenOSRunning()) + { + /* Decoy system partition wipe */ + + DecoySystemWipeStatus decoySysPartitionWipeStatus; + + try + { + decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); + return; + } + + if (!decoySysPartitionWipeStatus.WipeInProgress) + { + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); + return; + } + + WaitCursor (); + + try + { + int attempts = SYSENC_PAUSE_RETRIES; + + BootEncObj->AbortDecoyOSWipe (); + + decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); + + while (decoySysPartitionWipeStatus.WipeInProgress && attempts > 0) + { + Sleep (SYSENC_PAUSE_RETRY_INTERVAL); + attempts--; + decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); + } + + if (!decoySysPartitionWipeStatus.WipeInProgress) + BootEncObj->CheckDecoyOSWipeResult (); + + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + NormalCursor (); + + if (decoySysPartitionWipeStatus.WipeInProgress) + { + SetTimer (MainDlg, TIMER_ID_WIPE_PROGRESS, TIMER_INTERVAL_WIPE_PROGRESS, NULL); + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); + Error ("FAILED_TO_INTERRUPT_WIPING", MainDlg); + return; + } + } + else + { + /* Regular device wipe (not decoy system partition wipe) */ + } + + UpdateWipeControls (); + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); +} + + +static void WipeStart (void) +{ + if (bHiddenOS && IsHiddenOSRunning()) + { + /* Decoy system partition wipe */ + + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), FALSE); + + bDeviceWipeInProgress = FALSE; + WaitCursor (); + + try + { + BootEncObj->StartDecoyOSWipe (nWipeMode); + + bDeviceWipeInProgress = TRUE; + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + NormalCursor (); + + if (!bDeviceWipeInProgress) + { + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); + Error ("FAILED_TO_START_WIPING", MainDlg); + return; + } + } + else + { + /* Regular device wipe (not decoy system partition wipe) */ + } + + InitWipeProgressBar (); + UpdateWipeProgressBar (); + UpdateWipeControls (); + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); + SetTimer (MainDlg, TIMER_ID_WIPE_PROGRESS, TIMER_INTERVAL_WIPE_PROGRESS, NULL); +} + + +static void UpdateWipeProgressBar (void) +{ + if (bHiddenOS && IsHiddenOSRunning()) + { + /* Decoy system partition wipe */ + + DecoySystemWipeStatus decoySysPartitionWipeStatus; + + try + { + decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); + BootEncStatus = BootEncObj->GetStatus(); + } + catch (...) + { + return; + } + + if (decoySysPartitionWipeStatus.WipedAreaEnd == -1) + UpdateProgressBarProc (0); + else + UpdateProgressBarProc (decoySysPartitionWipeStatus.WipedAreaEnd - BootEncStatus.ConfiguredEncryptedAreaStart + 1); + } + else + { + /* Regular device wipe (not decoy system partition wipe) */ + } +} + + +static void InitWipeProgressBar (void) +{ + if (bHiddenOS && IsHiddenOSRunning()) + { + /* Decoy system partition wipe */ + + DecoySystemWipeStatus decoySysPartitionWipeStatus; + + try + { + decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); + BootEncStatus = BootEncObj->GetStatus(); + } + catch (...) + { + return; + } + + if (BootEncStatus.ConfiguredEncryptedAreaEnd == -1 + || BootEncStatus.ConfiguredEncryptedAreaStart == -1) + return; + + InitProgressBar (BootEncStatus.ConfiguredEncryptedAreaEnd - BootEncStatus.ConfiguredEncryptedAreaStart + 1, + (decoySysPartitionWipeStatus.WipedAreaEnd == BootEncStatus.ConfiguredEncryptedAreaStart || decoySysPartitionWipeStatus.WipedAreaEnd == -1) ? + 0 : decoySysPartitionWipeStatus.WipedAreaEnd - BootEncStatus.ConfiguredEncryptedAreaStart + 1, + FALSE, + TRUE, + FALSE, + TRUE); + } + else + { + /* Regular device wipe (not decoy system partition wipe) */ + } +} + + +static void UpdateWipeControls (void) +{ + if (bHiddenOS && IsHiddenOSRunning()) + { + /* Decoy system partition wipe */ + + DecoySystemWipeStatus decoySysPartitionWipeStatus; + + try + { + decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); + BootEncStatus = BootEncObj->GetStatus(); + } + catch (...) + { + return; + } + + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), !decoySysPartitionWipeStatus.WipeInProgress); + } + else + { + /* Regular device wipe (not decoy system partition wipe) */ + + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), bDeviceWipeInProgress); + + if (!bDeviceWipeInProgress) + { + SetWindowText (GetDlgItem (hCurPage, IDC_TIMEREMAIN), L" "); + } + } + + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), bDeviceWipeInProgress); + EnableWindow (GetDlgItem (MainDlg, IDC_PREV), !bDeviceWipeInProgress); + + bConfirmQuit = bDeviceWipeInProgress; +} + + + +static void __cdecl sysEncDriveAnalysisThread (void *hwndDlgArg) +{ + // Mark the detection process as 'in progress' + HiddenSectorDetectionStatus = 1; + SaveSettings (NULL); + BroadcastSysEncCfgUpdate (); + + try + { + BootEncObj->ProbeRealSystemDriveSize (); + bSysEncDriveAnalysisTimeOutOccurred = FALSE; + } + catch (TimeOut &) + { + bSysEncDriveAnalysisTimeOutOccurred = TRUE; + } + catch (Exception &e) + { + // There was a problem but the system did not freeze. Mark the detection process as completed. + HiddenSectorDetectionStatus = 0; + SaveSettings (NULL); + BroadcastSysEncCfgUpdate (); + + e.Show (NULL); + EndMainDlg (MainDlg); + exit(0); + } + + // Mark the detection process as completed + HiddenSectorDetectionStatus = 0; + SaveSettings (NULL); + BroadcastSysEncCfgUpdate (); + + // This artificial delay prevents user confusion on systems where the analysis ends almost instantly + Sleep (3000); + + bSysEncDriveAnalysisInProgress = FALSE; +} + +static void __cdecl volTransformThreadFunction (void *hwndDlgArg) +{ + int nStatus; + DWORD dwWin32FormatError; + BOOL bHidden; + HWND hwndDlg = (HWND) hwndDlgArg; + volatile FORMAT_VOL_PARAMETERS *volParams = (FORMAT_VOL_PARAMETERS *) malloc (sizeof(FORMAT_VOL_PARAMETERS)); + + if (volParams == NULL) + AbortProcess ("ERR_MEM_ALLOC"); + + VirtualLock ((LPVOID) volParams, sizeof(FORMAT_VOL_PARAMETERS)); + + bOperationSuccess = FALSE; + + if (bGuiMode) + { + bVolTransformThreadRunning = TRUE; + bVolTransformThreadToRun = FALSE; + } + + // Check administrator privileges + if (!IsAdmin () && !IsUacSupported ()) + { + if (fileSystem == FILESYS_NTFS || fileSystem == FILESYS_EXFAT) + { + if (Silent || (MessageBoxW (hwndDlg, GetString ("ADMIN_PRIVILEGES_WARN_NTFS"), lpszTitle, MB_OKCANCEL|MB_ICONWARNING|MB_DEFBUTTON2) == IDCANCEL)) + goto cancel; + } + if (bDevice) + { + if (Silent || (MessageBoxW (hwndDlg, GetString ("ADMIN_PRIVILEGES_WARN_DEVICES"), lpszTitle, MB_OKCANCEL|MB_ICONWARNING|MB_DEFBUTTON2) == IDCANCEL)) + goto cancel; + } + } + + if (!bInPlaceEncNonSys) + { + if (!bDevice) + { + int x = _waccess (szDiskFile, 06); + if (x == 0 || errno != ENOENT) + { + wchar_t szTmp[512]; + + if (!bForceOperation && !((bHiddenVol && !bHiddenVolHost) && errno != EACCES)) // Only ask ask for permission to overwrite an existing volume if we're not creating a hidden volume + { + StringCbPrintfW (szTmp, sizeof szTmp, + GetString (errno == EACCES ? "READONLYPROMPT" : "OVERWRITEPROMPT"), + szDiskFile); + + x = Silent? IDNO : MessageBoxW (hwndDlg, szTmp, lpszTitle, YES_NO|MB_ICONWARNING|MB_DEFBUTTON2); + + if (x != IDYES) + goto cancel; + } + } + + if (_waccess (szDiskFile, 06) != 0) + { + if (errno == EACCES) + { + if (_wchmod (szDiskFile, _S_IREAD | _S_IWRITE) != 0) + { + if (!Silent) MessageBoxW (hwndDlg, GetString ("ACCESSMODEFAIL"), lpszTitle, ICON_HAND); + goto cancel; + } + } + } + + } + else + { + // Partition / device / dynamic volume + + if (!FinalPreTransformPrompts ()) + goto cancel; + } + } + + // Prevent the OS from entering Sleep mode when idle + SetThreadExecutionState (ES_CONTINUOUS | ES_SYSTEM_REQUIRED); + + bHidden = bHiddenVol && !bHiddenVolHost; + + volParams->bDevice = bDevice; + volParams->hiddenVol = bHidden; + volParams->volumePath = szDiskFile; + volParams->size = nVolumeSize; + volParams->hiddenVolHostSize = nHiddenVolHostSize; + volParams->ea = nVolumeEA; + volParams->pkcs5 = hash_algo; + volParams->headerFlags = (CreatingHiddenSysVol() ? TC_HEADER_FLAG_ENCRYPTED_SYSTEM : 0); + volParams->fileSystem = fileSystem; + volParams->clusterSize = clusterSize; + volParams->sparseFileSwitch = bSparseFileSwitch; + volParams->quickFormat = quickFormat; + volParams->sectorSize = GetFormatSectorSize(); + volParams->realClusterSize = &realClusterSize; + volParams->password = &volumePassword; + volParams->pim = volumePim; + volParams->hwndDlg = hwndDlg; + volParams->bForceOperation = bForceOperation; + volParams->bGuiMode = bGuiMode; + + if (bInPlaceDecNonSys) + { + // In-place decryption of non-system volume + + if (!bInPlaceEncNonSysResumed) + DiscardUnreadableEncryptedSectors = FALSE; + + nStatus = DecryptPartitionInPlace (volParams, &DiscardUnreadableEncryptedSectors); + } + else if (bInPlaceEncNonSys) + { + // In-place encryption of non-system volume + + HANDLE hPartition = INVALID_HANDLE_VALUE; + + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PREPARING); + + if (!bInPlaceEncNonSysResumed) + { + bTryToCorrectReadErrors = FALSE; + + nStatus = EncryptPartitionInPlaceBegin (volParams, &hPartition, nWipeMode); + + if (nStatus == ERR_SUCCESS) + { + nStatus = EncryptPartitionInPlaceResume (hPartition, volParams, nWipeMode, &bTryToCorrectReadErrors); + } + else if (hPartition != INVALID_HANDLE_VALUE) + { + CloseHandle (hPartition); + hPartition = INVALID_HANDLE_VALUE; + } + } + else + { + nStatus = EncryptPartitionInPlaceResume (INVALID_HANDLE_VALUE, volParams, nWipeMode, &bTryToCorrectReadErrors); + } + } + else + { + // Format-encryption + + if (hwndDlg && bGuiMode) InitProgressBar (GetVolumeDataAreaSize (bHidden, nVolumeSize), 0, FALSE, FALSE, FALSE, TRUE); + + nStatus = TCFormatVolume (volParams); + } + + // Allow the OS to enter Sleep mode when idle + SetThreadExecutionState (ES_CONTINUOUS); + + if (nStatus == ERR_OUTOFMEMORY) + { + AbortProcess ("OUTOFMEMORY"); + } + + if (bInPlaceEncNonSys + && nStatus == ERR_USER_ABORT + && NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINISHED) + { + // Ignore user abort if non-system in-place encryption/decryption successfully finished + nStatus = ERR_SUCCESS; + } + + + dwWin32FormatError = GetLastError (); + + if (bHiddenVolHost && (!bGuiMode || !bVolTransformThreadCancel) && nStatus == 0) + { + /* Auto mount the newly created hidden volume host */ + switch (MountHiddenVolHost (hwndDlg, szDiskFile, &hiddenVolHostDriveNo, &volumePassword, hash_algo, volumePim, FALSE)) + { + case ERR_NO_FREE_DRIVES: + if (!Silent) MessageBoxW (hwndDlg, GetString ("NO_FREE_DRIVE_FOR_OUTER_VOL"), lpszTitle, ICON_HAND); + if (bGuiMode) bVolTransformThreadCancel = TRUE; + break; + case ERR_VOL_MOUNT_FAILED: + case ERR_PASSWORD_WRONG: + if (!Silent) MessageBoxW (hwndDlg, GetString ("CANT_MOUNT_OUTER_VOL"), lpszTitle, ICON_HAND); + if (bGuiMode) bVolTransformThreadCancel = TRUE; + break; + } + } + + SetLastError (dwWin32FormatError); + + if ((bVolTransformThreadCancel || nStatus == ERR_USER_ABORT) + && !(bInPlaceEncNonSys && NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINISHED)) // Ignore user abort if non-system in-place encryption/decryption successfully finished. + { + if (!bDevice && !(bHiddenVol && !bHiddenVolHost)) // If we're not creating a hidden volume and if it's a file container + { + _wremove (szDiskFile); // Delete the container + } + + goto cancel; + } + + if (nStatus != ERR_USER_ABORT) + { + if (nStatus != 0) + { + /* An error occurred */ + + wchar_t szMsg[8192]; + + handleError (hwndDlg, nStatus, SRC_POS); + + if (bInPlaceEncNonSys) + { + if (bInPlaceEncNonSysResumed) + { + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED); + Error ("INPLACE_ENC_GENERIC_ERR_RESUME", hwndDlg); + } + else + { + SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_ERROR); + + if (bInPlaceDecNonSys) + Error ("INPLACE_DEC_GENERIC_ERR", hwndDlg); + else + ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_GENERIC_ERR_ALT_STEPS", TRUE); + } + } + else if (!Silent && !(bHiddenVolHost && hiddenVolHostDriveNo < 0)) // If the error was not that the hidden volume host could not be mounted (this error has already been reported to the user) + { + StringCbPrintfW (szMsg, sizeof(szMsg), GetString ("CREATE_FAILED"), szDiskFile); + MessageBoxW (hwndDlg, szMsg, lpszTitle, ICON_HAND); + } + + if (!bDevice && !(bHiddenVol && !bHiddenVolHost)) // If we're not creating a hidden volume and if it's a file container + { + _wremove (szDiskFile); // Delete the container + } + + goto cancel; + } + else + { + /* Volume successfully created */ + + RestoreDefaultKeyFilesParam (); + + PimEnable = FALSE; + + bOperationSuccess = TRUE; + + if (bDevice && !bInPlaceEncNonSys) + { + // Handle assigned drive letter (if any) + + HandleOldAssignedDriveLetter (); + } + + if (!bHiddenVolHost) + { + if (bHiddenVol) + { + bHiddenVolFinished = TRUE; + + if (!bHiddenOS) + Warning ("HIDVOL_FORMAT_FINISHED_HELP", hwndDlg); + } + else if (bInPlaceEncNonSys) + { + if (!bInPlaceDecNonSys) + { + Warning ("NONSYS_INPLACE_ENC_FINISHED_INFO", hwndDlg); + + HandleOldAssignedDriveLetter (); + } + else + { + // NOP - Final steps for in-place decryption are handled with the TC_APPMSG_NONSYS_INPLACE_ENC_FINISHED message. + } + } + else + { + Info("FORMAT_FINISHED_INFO", hwndDlg); + + if (bSparseFileSwitch && quickFormat) + Warning("SPARSE_FILE_SIZE_NOTE", hwndDlg); + } + } + else + { + /* We've just created an outer volume (to host a hidden volume within) */ + + bHiddenVolHost = FALSE; + bHiddenVolFinished = FALSE; + nHiddenVolHostSize = nVolumeSize; + + // Clear the outer volume password + burn(&szVerify[0], sizeof (szVerify)); + burn(&szRawPassword[0], sizeof (szRawPassword)); + + if (!Silent) MessageBeep (MB_OK); + } + + if (!bInPlaceEncNonSys && hwndDlg && bGuiMode) + SetTimer (hwndDlg, TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL); + + + // volParams is ensured to be non NULL at this stage + burn ((LPVOID) volParams, sizeof(FORMAT_VOL_PARAMETERS)); + VirtualUnlock ((LPVOID) volParams, sizeof(FORMAT_VOL_PARAMETERS)); + free ((LPVOID) volParams); + volParams = NULL; + + if (bGuiMode) + { + bVolTransformThreadRunning = FALSE; + bVolTransformThreadCancel = FALSE; + } + + if (hwndDlg && bGuiMode) PostMessage (hwndDlg, bInPlaceEncNonSys ? TC_APPMSG_NONSYS_INPLACE_ENC_FINISHED : TC_APPMSG_FORMAT_FINISHED, 0, 0); + + LastDialogId = "FORMAT_FINISHED"; + if (bGuiMode) _endthread (); + } + } + +cancel: + + LastDialogId = (bInPlaceEncNonSys ? "NONSYS_INPLACE_ENC_CANCELED" : "FORMAT_CANCELED"); + + if (!bInPlaceEncNonSys && hwndDlg && bGuiMode) + SetTimer (hwndDlg, TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL); + + if (volParams != NULL) + { + burn ((LPVOID) volParams, sizeof(FORMAT_VOL_PARAMETERS)); + VirtualUnlock ((LPVOID) volParams, sizeof(FORMAT_VOL_PARAMETERS)); + free ((LPVOID) volParams); + volParams = NULL; + } + + if (bGuiMode) + { + bVolTransformThreadRunning = FALSE; + bVolTransformThreadCancel = FALSE; + } + + // Allow the OS to enter Sleep mode when idle + SetThreadExecutionState (ES_CONTINUOUS); + + if (hwndDlg) PostMessage (hwndDlg, TC_APPMSG_VOL_TRANSFORM_THREAD_ENDED, 0, 0); + + if (bHiddenVolHost && hiddenVolHostDriveNo < -1 && !bVolTransformThreadCancel) // If hidden volume host could not be mounted + AbortProcessSilent (); + + if (bGuiMode) _endthread (); +} + +static void LoadPage (HWND hwndDlg, int nPageNo) +{ + RECT rD, rW; + + nLastPageNo = nCurPageNo; + + if (hCurPage != NULL) + { + // WARNING: nCurPageNo must be set to a non-existent ID here before wiping the password fields below in + // this function, etc. Otherwise, such actions (SetWindowText) would invoke the EN_CHANGE handlers, which + // would, if keyfiles were applied, e.g. use strlen() on a buffer full of random data, in most cases + // not null-terminated. + nCurPageNo = -1; + + + // Place here any actions that need to be performed at the latest possible time when leaving a wizard page + // (i.e. right before "destroying" the page). Also, code that needs to be executed both on IDC_NEXT and + // on IDC_PREV can be placed here so as to avoid code doubling. + + switch (nLastPageNo) + { + case PASSWORD_PAGE: + { + wchar_t tmp[MAX_PASSWORD+1]; + + // Attempt to wipe passwords stored in the input field buffers. This is performed here (and + // not in the IDC_PREV or IDC_NEXT sections) in order to prevent certain race conditions + // when keyfiles are used. + wmemset (tmp, 'X', MAX_PASSWORD); + tmp [MAX_PASSWORD] = 0; + SetWindowText (hPasswordInputField, tmp); + SetWindowText (hVerifyPasswordInputField, tmp); + } + break; + } + + DestroyWindow (hCurPage); + hCurPage = NULL; + } + + // This prevents the mouse pointer from remaining as the "hand" cursor when the user presses Enter + // while hovering over a hyperlink. + bHyperLinkBeingTracked = FALSE; + NormalCursor(); + + GetWindowRect (GetDlgItem (hwndDlg, IDC_POS_BOX), &rW); + + + nCurPageNo = nPageNo; + + + switch (nPageNo) + { + case INTRO_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INTRO_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case SYSENC_TYPE_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_TYPE_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case SYSENC_HIDDEN_OS_REQ_CHECK_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_HIDDEN_OS_REQ_CHECK_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case SYSENC_SPAN_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_SPAN_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case SYSENC_PRE_DRIVE_ANALYSIS_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_UNIVERSAL_DUAL_CHOICE_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case SYSENC_DRIVE_ANALYSIS_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_DRIVE_ANALYSIS_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case SYSENC_MULTI_BOOT_MODE_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_MULTI_BOOT_MODE_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case SYSENC_MULTI_BOOT_SYS_EQ_BOOT_PAGE: + case SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE: + case SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE: + case SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_UNIVERSAL_DUAL_CHOICE_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case SYSENC_MULTI_BOOT_OUTCOME_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case VOLUME_TYPE_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_VOLUME_TYPE_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case HIDDEN_VOL_WIZARD_MODE_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_HIDDEN_VOL_WIZARD_MODE_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case VOLUME_LOCATION_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_VOLUME_LOCATION_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + + EnableWindow (GetDlgItem(hCurPage, IDC_NO_HISTORY), !bHistoryCmdLine); + + EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), + GetWindowTextLength (GetDlgItem (hCurPage, IDC_COMBO_BOX)) > 0); + + break; + + case DEVICE_TRANSFORM_MODE_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_DEVICE_TRANSFORM_MODE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case HIDDEN_VOL_HOST_PRE_CIPHER_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case HIDDEN_VOL_PRE_CIPHER_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case CIPHER_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_CIPHER_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case SIZE_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SIZE_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case HIDDEN_VOL_HOST_PASSWORD_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_PASSWORD_ENTRY_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case PASSWORD_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_PASSWORD_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case PIM_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_PIM_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case FILESYS_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_UNIVERSAL_DUAL_CHOICE_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case SYSENC_COLLECTING_RANDOM_DATA_PAGE: + case NONSYS_INPLACE_ENC_RAND_DATA_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_COLLECTING_RANDOM_DATA_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case SYSENC_KEYS_GEN_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_KEYS_GEN_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case SYSENC_RESCUE_DISK_CREATION_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_RESCUE_DISK_CREATION_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case SYSENC_RESCUE_DISK_BURN_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_RESCUE_DISK_BURN_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case SYSENC_RESCUE_DISK_VERIFIED_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case SYSENC_WIPE_MODE_PAGE: + case NONSYS_INPLACE_ENC_WIPE_MODE_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_WIPE_MODE_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case SYSENC_PRETEST_INFO_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case SYSENC_PRETEST_RESULT_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case SYSENC_ENCRYPTION_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INPLACE_ENCRYPTION_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_PASSWORD_ENTRY_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case NONSYS_INPLACE_ENC_RESUME_PARTITION_SEL_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_EXPANDED_LIST_SELECT_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case NONSYS_INPLACE_ENC_TRANSFORM_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INPLACE_ENCRYPTION_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case NONSYS_INPLACE_ENC_TRANSFORM_FINISHED_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case NONSYS_INPLACE_DEC_TRANSFORM_FINISHED_DRIVE_LETTER_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_DRIVE_LETTER_SELECTION_PAGE), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case FORMAT_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_FORMAT_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + case FORMAT_FINISHED_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW ((bHiddenVol && !bHiddenVolHost && !bHiddenVolFinished) ? IDD_HIDVOL_HOST_FILL_PAGE_DLG : IDD_INFO_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case SYSENC_HIDDEN_OS_INITIAL_INFO_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, (DLGPROC) PageDialogProc); + break; + + case SYSENC_HIDDEN_OS_WIPE_INFO_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INFO_PAGE_DLG), hwndDlg, (DLGPROC) PageDialogProc); + break; + + case DEVICE_WIPE_MODE_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_DEVICE_WIPE_MODE_PAGE_DLG), hwndDlg, (DLGPROC) PageDialogProc); + break; + + case DEVICE_WIPE_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_DEVICE_WIPE_PAGE_DLG), hwndDlg, (DLGPROC) PageDialogProc); + break; + } + + rD.left = 162; + rD.top = 25; + rD.right = 0; + rD.bottom = 0; + MapDialogRect (hwndDlg, &rD); + + if (hCurPage != NULL) + { + MoveWindow (hCurPage, rD.left, rD.top, rW.right - rW.left, rW.bottom - rW.top, TRUE); + ShowWindow (hCurPage, SW_SHOWNORMAL); + + // Place here any message boxes that need to be displayed as soon as a new page is displayed. This + // ensures that the page is fully rendered (otherwise it would remain blank, until the message box + // is closed). + switch (nPageNo) + { + case PASSWORD_PAGE: + + CheckCapsLock (hwndDlg, FALSE); + + if (CreatingHiddenSysVol()) + Warning ("PASSWORD_HIDDEN_OS_NOTE", MainDlg); + + break; + + case CIPHER_PAGE: + + if (CreatingHiddenSysVol()) + Warning ("HIDDEN_OS_PRE_CIPHER_WARNING", MainDlg); + + break; + } + } +} + + +__int64 PrintFreeSpace (HWND hwndTextBox, wchar_t *lpszDrive, PLARGE_INTEGER lDiskFree) +{ + char *nResourceString; + __int64 nMultiplier; + wchar_t szTmp2[256]; + + if (lDiskFree->QuadPart < BYTES_PER_KB) + nMultiplier = 1; + else if (lDiskFree->QuadPart < BYTES_PER_MB) + nMultiplier = BYTES_PER_KB; + else if (lDiskFree->QuadPart < BYTES_PER_GB) + nMultiplier = BYTES_PER_MB; + else if (lDiskFree->QuadPart < BYTES_PER_TB) + nMultiplier = BYTES_PER_GB; + else + nMultiplier = BYTES_PER_TB; + + if (nMultiplier == 1) + { + if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume + nResourceString = "MAX_HIDVOL_SIZE_BYTES"; + else if (bDevice) + nResourceString = "DEVICE_FREE_BYTES"; + else + nResourceString = "DISK_FREE_BYTES"; + } + else if (nMultiplier == BYTES_PER_KB) + { + if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume + nResourceString = "MAX_HIDVOL_SIZE_KB"; + else if (bDevice) + nResourceString = "DEVICE_FREE_KB"; + else + nResourceString = "DISK_FREE_KB"; + } + else if (nMultiplier == BYTES_PER_MB) + { + if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume + nResourceString = "MAX_HIDVOL_SIZE_MB"; + else if (bDevice) + nResourceString = "DEVICE_FREE_MB"; + else + nResourceString = "DISK_FREE_MB"; + } + else if (nMultiplier == BYTES_PER_GB) + { + if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume + nResourceString = "MAX_HIDVOL_SIZE_GB"; + else if (bDevice) + nResourceString = "DEVICE_FREE_GB"; + else + nResourceString = "DISK_FREE_GB"; + } + else + { + if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume + nResourceString = "MAX_HIDVOL_SIZE_TB"; + else if (bDevice) + nResourceString = "DEVICE_FREE_TB"; + else + nResourceString = "DISK_FREE_TB"; + } + + if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume + { + StringCbPrintfW (szTmp2, sizeof szTmp2, GetString (nResourceString), ((double) lDiskFree->QuadPart) / nMultiplier); + SetWindowTextW (GetDlgItem (hwndTextBox, IDC_SIZEBOX), szTmp2); + } + else if (lpszDrive) + StringCbPrintfW (szTmp2, sizeof szTmp2, GetString (nResourceString), lpszDrive, ((double) lDiskFree->QuadPart) / nMultiplier); + else + szTmp2 [0] = 0; + + SetWindowTextW (hwndTextBox, szTmp2); + + if (lDiskFree->QuadPart % (__int64) BYTES_PER_MB != 0) + nMultiplier = BYTES_PER_KB; + + return nMultiplier; +} + +void DisplaySizingErrorText (HWND hwndTextBox) +{ + wchar_t szTmp[1024]; + + if (translateWin32Error (szTmp, sizeof (szTmp) / sizeof(szTmp[0]))) + { + wchar_t szTmp2[1024]; + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s\n%s", GetString ("CANNOT_CALC_SPACE"), szTmp); + SetWindowTextW (hwndTextBox, szTmp2); + } + else + { + SetWindowText (hwndTextBox, L""); + } +} + +void EnableDisableFileNext (HWND hComboBox, HWND hMainButton) +{ + int nIndex = (int) SendMessage (hComboBox, CB_GETCURSEL, 0, 0); + if (bHistory && nIndex == CB_ERR) + { + EnableWindow (hMainButton, FALSE); + SetFocus (hComboBox); + } + else + { + EnableWindow (hMainButton, TRUE); + SetFocus (hMainButton); + } +} + +// Returns TRUE if the file is a sparse file. If it's not a sparse file or in case of any error, returns FALSE. +BOOL IsSparseFile (HWND hwndDlg) +{ + HANDLE hFile; + BY_HANDLE_FILE_INFORMATION bhFileInfo; + + FILETIME ftLastAccessTime; + BOOL bTimeStampValid = FALSE; + + BOOL retCode = FALSE; + + hFile = CreateFile (szFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (hFile == INVALID_HANDLE_VALUE) + { + MessageBoxW (hwndDlg, GetString ("CANT_ACCESS_VOL"), lpszTitle, ICON_HAND); + return FALSE; + } + + if (bPreserveTimestamp) + { + if (GetFileTime (hFile, NULL, &ftLastAccessTime, NULL) == 0) + bTimeStampValid = FALSE; + else + bTimeStampValid = TRUE; + } + + bhFileInfo.dwFileAttributes = 0; + + GetFileInformationByHandle(hFile, &bhFileInfo); + + retCode = bhFileInfo.dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE; + + if (bTimeStampValid) + SetFileTime (hFile, NULL, &ftLastAccessTime, NULL); + + CloseHandle (hFile); + return retCode; +} + + +// Note: GetFileVolSize is not to be used for devices (only for file-hosted volumes) +BOOL GetFileVolSize (HWND hwndDlg, unsigned __int64 *size) +{ + LARGE_INTEGER fileSize; + HANDLE hFile; + + FILETIME ftLastAccessTime; + BOOL bTimeStampValid = FALSE; + + hFile = CreateFile (szFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (hFile == INVALID_HANDLE_VALUE) + { + MessageBoxW (hwndDlg, GetString ("CANT_ACCESS_VOL"), lpszTitle, ICON_HAND); + return FALSE; + } + + if (bPreserveTimestamp) + { + if (GetFileTime (hFile, NULL, &ftLastAccessTime, NULL) == 0) + bTimeStampValid = FALSE; + else + bTimeStampValid = TRUE; + } + + if (GetFileSizeEx(hFile, &fileSize) == 0) + { + MessageBoxW (hwndDlg, GetString ("CANT_GET_VOLSIZE"), lpszTitle, ICON_HAND); + + if (bTimeStampValid) + SetFileTime (hFile, NULL, &ftLastAccessTime, NULL); + + CloseHandle (hFile); + return FALSE; + } + + if (bTimeStampValid) + SetFileTime (hFile, NULL, &ftLastAccessTime, NULL); + + CloseHandle (hFile); + *size = fileSize.QuadPart; + return TRUE; +} + + +BOOL QueryFreeSpace (HWND hwndDlg, HWND hwndTextBox, BOOL display) +{ + if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume + { + LARGE_INTEGER lDiskFree; + + lDiskFree.QuadPart = nMaximumHiddenVolSize; + + if (display) + PrintFreeSpace (hwndTextBox, NULL, &lDiskFree); + + return TRUE; + } + else if (bDevice == FALSE) + { + wchar_t root[TC_MAX_PATH]; + ULARGE_INTEGER free; + + if (!GetVolumePathName (szFileName, root, ARRAYSIZE (root))) + { + handleWin32Error (hwndDlg, SRC_POS); + return FALSE; + } + + if (!GetDiskFreeSpaceEx (root, &free, 0, 0)) + { + if (display) + DisplaySizingErrorText (hwndTextBox); + + return FALSE; + } + else + { + LARGE_INTEGER lDiskFree; + lDiskFree.QuadPart = free.QuadPart; + + if (display) + PrintFreeSpace (hwndTextBox, root, &lDiskFree); + + return TRUE; + } + } + else + { + DISK_GEOMETRY driveInfo; + PARTITION_INFORMATION diskInfo; + BOOL piValid = FALSE; + BOOL gValid = FALSE; + + // Query partition size + piValid = GetPartitionInfo (szDiskFile, &diskInfo); + gValid = GetDriveGeometry (szDiskFile, &driveInfo); + + if (!piValid && !gValid) + { + if (display) + DisplaySizingErrorText (hwndTextBox); + + return FALSE; + } + + DWORD sectorSize = GetFormatSectorSize(); + + if (sectorSize < TC_MIN_VOLUME_SECTOR_SIZE + || sectorSize > TC_MAX_VOLUME_SECTOR_SIZE + || sectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0) + { + Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg); + return FALSE; + } + + if (piValid) + { + nVolumeSize = diskInfo.PartitionLength.QuadPart; + + if(display) + nMultiplier = PrintFreeSpace (hwndTextBox, szDiskFile, &diskInfo.PartitionLength); + + nUIVolumeSize = diskInfo.PartitionLength.QuadPart / nMultiplier; + + if (nVolumeSize == 0) + { + if (display) + SetWindowTextW (hwndTextBox, GetString ("EXT_PARTITION")); + + return FALSE; + } + } + else + { + LARGE_INTEGER lDiskFree; + + // Drive geometry info is used only when GetPartitionInfo() fails + lDiskFree.QuadPart = driveInfo.Cylinders.QuadPart * driveInfo.BytesPerSector * + driveInfo.SectorsPerTrack * driveInfo.TracksPerCylinder; + + nVolumeSize = lDiskFree.QuadPart; + + if (display) + nMultiplier = PrintFreeSpace (hwndTextBox, szDiskFile, &lDiskFree); + + nUIVolumeSize = lDiskFree.QuadPart / nMultiplier; + } + + return TRUE; + } +} + + +static BOOL FinalPreTransformPrompts (void) +{ + int x; + wchar_t szTmp[4096]; + int driveNo; + WCHAR deviceName[MAX_PATH]; + + StringCbCopyW (deviceName, sizeof(deviceName), szFileName); + + driveNo = GetDiskDeviceDriveLetter (deviceName); + + if (!bForceOperation && !(bHiddenVol && !bHiddenVolHost)) // Do not ask for permission to overwrite an existing volume if we're creating a hidden volume within it + { + wchar_t drive[128]; + wchar_t volumeLabel[128]; + wchar_t *type; + BOOL bTmpIsPartition = FALSE; + + type = GetPathType (szFileName, !bInPlaceEncNonSys, &bTmpIsPartition); + + if (driveNo != -1) + { + if (!GetDriveLabel (driveNo, volumeLabel, sizeof (volumeLabel))) + volumeLabel[0] = 0; + + StringCbPrintfW (drive, sizeof (drive), volumeLabel[0] ? L" (%hc: '%s')" : L" (%hc:%s)", 'A' + driveNo, volumeLabel[0] ? volumeLabel : L""); + } + else + { + drive[0] = 0; + volumeLabel[0] = 0; + } + + if (bHiddenOS && bHiddenVolHost) + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("OVERWRITEPROMPT_DEVICE_HIDDEN_OS_PARTITION"), szFileName, drive); + else + StringCbPrintfW (szTmp, sizeof(szTmp), GetString (bInPlaceEncNonSys ? (bInPlaceDecNonSys ? "NONSYS_INPLACE_DEC_CONFIRM" : "NONSYS_INPLACE_ENC_CONFIRM") : "OVERWRITEPROMPT_DEVICE"), type, szFileName, drive); + + if (bInPlaceEncNonSys) + x = AskWarnYesNoString (szTmp, MainDlg); + else + x = AskWarnNoYesString (szTmp, MainDlg); + + if (x != IDYES) + return FALSE; + + + if (driveNo != -1 && bTmpIsPartition && !bInPlaceEncNonSys) + { + float percentFreeSpace = 100.0; + __int64 occupiedBytes = 0; + + // Do a second check. If we find that the partition contains more than 1GB of data or more than 12% + // of its space is occupied, we will display an extra warning, however, this time it won't be a Yes/No + // dialog box (because users often ignore such dialog boxes). + + if (GetStatsFreeSpaceOnPartition (szFileName, &percentFreeSpace, &occupiedBytes, TRUE) != -1) + { + if (occupiedBytes > BYTES_PER_GB && percentFreeSpace < 99.99 // "percentFreeSpace < 99.99" is needed because an NTFS filesystem larger than several terabytes can have more than 1GB of data in use, even if there are no files stored on it. + || percentFreeSpace < 88) // A 24-MB NTFS filesystem has 11.5% of space in use even if there are no files stored on it. + { + wchar_t tmpMcMsg [8000]; + wchar_t tmpMcOption1 [500]; + wchar_t tmpMcOptionCancel [50]; + + StringCbCopyW (tmpMcMsg, sizeof(tmpMcMsg), GetString("OVERWRITEPROMPT_DEVICE_SECOND_WARNING_LOTS_OF_DATA")); + StringCbCopyW (tmpMcOption1, sizeof(tmpMcOption1), GetString("ERASE_FILES_BY_CREATING_VOLUME")); + StringCbCopyW (tmpMcOptionCancel, sizeof(tmpMcOptionCancel), GetString("CANCEL")); + + StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), L"\n\n"); + StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), GetString("DRIVE_LETTER_ITEM")); + StringCbPrintfW (szTmp, sizeof (szTmp), L"%hc:", 'A' + driveNo); + StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), szTmp); + + StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), L"\n"); + StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), GetString("LABEL_ITEM")); + StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), volumeLabel[0] != 0 ? volumeLabel : GetString("NOT_APPLICABLE_OR_NOT_AVAILABLE")); + + StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), L"\n"); + StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), GetString("SIZE_ITEM")); + GetSizeString (nVolumeSize, szTmp, sizeof(szTmp)); + StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), szTmp); + + StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), L"\n"); + StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), GetString("PATH_ITEM")); + StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), deviceName); + + wchar_t *tmpStr[] = {L"", tmpMcMsg, tmpMcOption1, tmpMcOptionCancel, 0}; + switch (AskMultiChoice ((void **) tmpStr, TRUE, MainDlg)) + { + case 1: + // Proceed + + // NOP + break; + + default: + return FALSE; + } + } + } + } + } + return TRUE; +} + +void UpdateLastDialogId (void) +{ + static char PageDebugId[128]; + + StringCbPrintfA (PageDebugId, sizeof(PageDebugId), "FORMAT_PAGE_%d", nCurPageNo); + LastDialogId = PageDebugId; +} + + +void HandleOldAssignedDriveLetter (void) +{ + if (bDevice) + { + // Handle assigned drive letter (if any) + + WCHAR deviceName[MAX_PATH]; + int driveLetter = -1; + + StringCbCopyW (deviceName, sizeof(deviceName), szDiskFile); + driveLetter = GetDiskDeviceDriveLetter (deviceName); + + if (!Silent && !bHiddenVolHost + && !bHiddenOS + && driveLetter >= 0) + { + wchar_t rootPath[] = { (wchar_t) driveLetter + L'A', L':', L'\\', 0 }; + wchar_t szTmp[8192]; + + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("AFTER_FORMAT_DRIVE_LETTER_WARN"), rootPath[0], rootPath[0], rootPath[0], rootPath[0]); + MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING); + } + } +} + + +// Returns TRUE if it makes sense to ask the user whether he wants to store files larger than 4GB in the volume. +static BOOL FileSize4GBLimitQuestionNeeded (void) +{ + uint64 dataAreaSize = GetVolumeDataAreaSize (bHiddenVol && !bHiddenVolHost, nVolumeSize); + + return (dataAreaSize > 4 * BYTES_PER_GB + TC_MIN_FAT_FS_SIZE + && dataAreaSize <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()); +} + + +/* Except in response to the WM_INITDIALOG message, the dialog box procedure + should return nonzero if it processes the message, and zero if it does + not. - see DialogProc */ +BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + WORD hw = HIWORD (wParam); + static BOOL PimValueChangedWarning = FALSE; + + hCurPage = hwndDlg; + + switch (uMsg) + { + case WM_INITDIALOG: + PimValueChangedWarning = FALSE; + LocalizeDialog (hwndDlg, "IDD_VOL_CREATION_WIZARD_DLG"); + + burn (randPool, sizeof(randPool)); + burn (lastRandPool, sizeof(lastRandPool)); + burn (maskRandPool, sizeof (maskRandPool)); + + UpdateLastDialogId (); + + switch (nCurPageNo) + { + case INTRO_PAGE: + + SendMessage (GetDlgItem (hwndDlg, IDC_FILE_CONTAINER), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_NONSYS_DEVICE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_SYS_DEVICE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("INTRO_TITLE")); + + ToHyperlink (hwndDlg, IDC_MORE_INFO_ON_CONTAINERS); + ToHyperlink (hwndDlg, IDC_MORE_INFO_ON_SYS_ENCRYPTION); + + EnableWindow (GetDlgItem (hwndDlg, IDC_STD_VOL), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_HIDDEN_VOL), TRUE); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + + UpdateWizardModeControls (hwndDlg, WizardMode); + break; + + case SYSENC_TYPE_PAGE: + + bHiddenVolHost = bHiddenVol = bHiddenOS; + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_TYPE_PAGE_TITLE")); + + SendMessage (GetDlgItem (hwndDlg, IDC_SYSENC_HIDDEN), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_SYSENC_NORMAL), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + + CheckButton (GetDlgItem (hwndDlg, bHiddenOS ? IDC_SYSENC_HIDDEN : IDC_SYSENC_NORMAL)); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_HIDDEN_TYPE_HELP")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP_SYSENC_NORMAL), GetString ("SYSENC_NORMAL_TYPE_HELP")); + + ToHyperlink (hwndDlg, IDC_HIDDEN_SYSENC_INFO_LINK); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), !bDirectSysEncMode); + + SetWindowTextW (GetDlgItem (MainDlg, IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (MainDlg, IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); + break; + + case SYSENC_HIDDEN_OS_REQ_CHECK_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_HIDDEN_OS_REQ_CHECK_PAGE_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_HIDDEN_OS_REQ_CHECK_PAGE_HELP")); + SetWindowTextW (GetDlgItem (MainDlg, IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (MainDlg, IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); + + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (MainDlg, IDC_PREV), bDirectSysEncModeCommand != SYSENC_COMMAND_CREATE_HIDDEN_OS && bDirectSysEncModeCommand != SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV); + + ToHyperlink (hwndDlg, IDC_HIDDEN_SYSENC_INFO_LINK); + break; + + case SYSENC_SPAN_PAGE: + + SendMessage (GetDlgItem (hwndDlg, IDC_WHOLE_SYS_DRIVE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_SYS_PARTITION), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYS_ENCRYPTION_SPAN_TITLE")); + + SetWindowTextW (GetDlgItem (hwndDlg, IDT_WHOLE_SYS_DRIVE), GetString ("SYS_ENCRYPTION_SPAN_WHOLE_SYS_DRIVE_HELP")); + + CheckButton (GetDlgItem (hwndDlg, bWholeSysDrive ? IDC_WHOLE_SYS_DRIVE : IDC_SYS_PARTITION)); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + break; + + + case SYSENC_PRE_DRIVE_ANALYSIS_PAGE: + + Init2RadButtonPageYesNo (SysEncDetectHiddenSectors); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_PRE_DRIVE_ANALYSIS_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_PRE_DRIVE_ANALYSIS_HELP")); + break; + + + case SYSENC_DRIVE_ANALYSIS_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_DRIVE_ANALYSIS_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDT_SYSENC_DRIVE_ANALYSIS_INFO), GetString ("SYSENC_DRIVE_ANALYSIS_INFO")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), FALSE); + EnableWindow (GetDlgItem (MainDlg, IDC_PREV), FALSE); + EnableWindow (GetDlgItem (MainDlg, IDCANCEL), FALSE); + + LoadSettings (hwndDlg); + + if (HiddenSectorDetectionStatus == 1) + { + // Detection of hidden sectors was already in progress but it did not finish successfully. + // Ask the user if he wants to try again (to prevent repeated system freezing, etc.) + + char *tmpStr[] = {0, "HIDDEN_SECTOR_DETECTION_FAILED_PREVIOUSLY", "SKIP_HIDDEN_SECTOR_DETECTION", "RETRY_HIDDEN_SECTOR_DETECTION", "IDC_EXIT", 0}; + switch (AskMultiChoice ((void **) tmpStr, FALSE, MainDlg)) + { + case 1: + // Do not try again + LoadPage (MainDlg, SYSENC_DRIVE_ANALYSIS_PAGE + 1); + return 0; + + case 2: + // Try again + break; + + default: + EndMainDlg (MainDlg); + return 0; + } + } + + SetTimer (MainDlg, TIMER_ID_SYSENC_DRIVE_ANALYSIS_PROGRESS, TIMER_INTERVAL_SYSENC_DRIVE_ANALYSIS_PROGRESS, NULL); + bSysEncDriveAnalysisInProgress = TRUE; + ArrowWaitCursor (); + SysEncDriveAnalysisStart = GetTickCount (); + InitProgressBar (SYSENC_DRIVE_ANALYSIS_ETA, 0, FALSE, FALSE, FALSE, TRUE); + + _beginthread (sysEncDriveAnalysisThread, 0, hwndDlg); + + break; + + + case SYSENC_MULTI_BOOT_MODE_PAGE: + + SendMessage (GetDlgItem (hwndDlg, IDC_SINGLE_BOOT), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_MULTI_BOOT), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYS_MULTI_BOOT_MODE_TITLE")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); + + RefreshMultiBootControls (hwndDlg); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), nMultiBoot > 0); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); + break; + + + case SYSENC_MULTI_BOOT_SYS_EQ_BOOT_PAGE: + + Init2RadButtonPageYesNo (SysEncMultiBootCfg.SystemOnBootDrive); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_MULTI_BOOT_SYS_EQ_BOOT_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_MULTI_BOOT_SYS_EQ_BOOT_HELP")); + break; + + + case SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE: + + SetWindowTextW (GetDlgItem (hCurPage, IDC_CHOICE1), GetString ("DIGIT_ONE")); + SetWindowTextW (GetDlgItem (hCurPage, IDC_CHOICE2), GetString ("TWO_OR_MORE")); + + SetWindowTextW (GetDlgItem (MainDlg, IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (MainDlg, IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); + + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), SysEncMultiBootCfg.NumberOfSysDrives > 0); + EnableWindow (GetDlgItem (MainDlg, IDC_PREV), TRUE); + + if (SysEncMultiBootCfg.NumberOfSysDrives == 2) + Update2RadButtonPage (0); // 2 or more drives contain an OS + else if (SysEncMultiBootCfg.NumberOfSysDrives == 1) + Update2RadButtonPage (1); // Only 1 drive contains an OS + else + Update2RadButtonPage (-1); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_HELP")); + break; + + + case SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE: + + Init2RadButtonPageYesNo (SysEncMultiBootCfg.MultipleSystemsOnDrive); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_MULTI_BOOT_ADJACENT_SYS_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_MULTI_BOOT_ADJACENT_SYS_HELP")); + break; + + + case SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE: + + Init2RadButtonPageYesNo (SysEncMultiBootCfg.BootLoaderBrand); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_HELP")); + break; + + + case SYSENC_MULTI_BOOT_OUTCOME_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_MULTI_BOOT_OUTCOME_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), SysEncMultiBootCfgOutcome); + SetWindowTextW (GetDlgItem (MainDlg, IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (MainDlg, IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (MainDlg, IDC_PREV), TRUE); + break; + + + case VOLUME_TYPE_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("VOLUME_TYPE_TITLE")); + + SendMessage (GetDlgItem (hwndDlg, IDC_HIDDEN_VOL), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_STD_VOL), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + + CheckButton (GetDlgItem (hwndDlg, bHiddenVol ? IDC_HIDDEN_VOL : IDC_STD_VOL)); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDDEN_VOLUME_TYPE_HELP")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP_NORMAL_VOL), GetString ("NORMAL_VOLUME_TYPE_HELP")); + + ToHyperlink (hwndDlg, IDC_HIDDEN_VOL_HELP); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + + SetWindowTextW (GetDlgItem (MainDlg, IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (MainDlg, IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); + break; + + case HIDDEN_VOL_WIZARD_MODE_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDDEN_VOL_WIZARD_MODE_TITLE")); + + SendMessage (GetDlgItem (hwndDlg, IDC_HIDVOL_WIZ_MODE_DIRECT), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_HIDVOL_WIZ_MODE_FULL), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + + CheckButton (GetDlgItem (hwndDlg, bHiddenVolDirect ? IDC_HIDVOL_WIZ_MODE_DIRECT : IDC_HIDVOL_WIZ_MODE_FULL)); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDDEN_VOL_WIZARD_MODE_NORMAL_HELP")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP2), GetString ("HIDDEN_VOL_WIZARD_MODE_DIRECT_HELP")); + + EnableWindow (GetDlgItem (hwndDlg, IDC_HIDVOL_WIZ_MODE_DIRECT), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_HIDVOL_WIZ_MODE_FULL), TRUE); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + + break; + + case VOLUME_LOCATION_PAGE: + { + char *nID; + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_SELECT_VOLUME_LOCATION), + GetString (bDevice ? "IDC_SELECT_DEVICE" : "IDC_SELECT_FILE")); + + if (bHiddenVolDirect && bHiddenVolHost) + { + nID = "FILE_HELP_HIDDEN_HOST_VOL_DIRECT"; + } + else + { + if (bDevice) + nID = bHiddenVolHost ? "DEVICE_HELP_HIDDEN_HOST_VOL" : "DEVICE_HELP"; + else + nID = bHiddenVolHost ? "FILE_HELP_HIDDEN_HOST_VOL" : "FILE_HELP"; + } + + SendMessage (GetDlgItem (hwndDlg, IDC_COMBO_BOX), CB_RESETCONTENT, 0, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_COMBO_BOX), CB_LIMITTEXT, TC_MAX_PATH, 0); + + LoadCombo (GetDlgItem (hwndDlg, IDC_COMBO_BOX), bHistory, FALSE, NULL); + + SendMessage (GetDlgItem (hwndDlg, IDC_NO_HISTORY), BM_SETCHECK, bHistory ? BST_UNCHECKED : BST_CHECKED, 0); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("FILE_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (nID)); + + SetFocus (GetDlgItem (hwndDlg, IDC_COMBO_BOX)); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + + AddComboItem (GetDlgItem (hwndDlg, IDC_COMBO_BOX), szFileName, bHistory); + + EnableDisableFileNext (GetDlgItem (hwndDlg, IDC_COMBO_BOX), + GetDlgItem (GetParent (hwndDlg), IDC_NEXT)); + + } + break; + + case DEVICE_TRANSFORM_MODE_PAGE: + + if (!bDeviceTransformModeChoiceMade && !bInPlaceEncNonSys) + { + // The user has not chosen whether to perform in-place encryption or format yet. + // We will preselect in-place encryption if the requirements are met and if the + // filesystem does not appear empty. + + WaitCursor(); + + if (CheckRequirementsForNonSysInPlaceEnc (hwndDlg, szDiskFile, TRUE)) + { + bInPlaceEncNonSys = (FileSystemAppearsEmpty (szDiskFile) == 0); + } + } + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("DEVICE_TRANSFORM_MODE_PAGE_TITLE")); + + SendMessage (GetDlgItem (hwndDlg, IDC_DEVICE_TRANSFORM_MODE_INPLACE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_DEVICE_TRANSFORM_MODE_FORMAT), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("DEVICE_TRANSFORM_MODE_PAGE_FORMAT_HELP")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP2), GetString ("DEVICE_TRANSFORM_MODE_PAGE_INPLACE_HELP")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + + CheckButton (GetDlgItem (hwndDlg, bInPlaceEncNonSys ? IDC_DEVICE_TRANSFORM_MODE_INPLACE : IDC_DEVICE_TRANSFORM_MODE_FORMAT)); + + NormalCursor(); + + break; + + case HIDDEN_VOL_HOST_PRE_CIPHER_PAGE: + { + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDVOL_HOST_PRE_CIPHER_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (bHiddenOS ? "HIDVOL_HOST_PRE_CIPHER_HELP_SYSENC" : "HIDVOL_HOST_PRE_CIPHER_HELP")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + + if (bHiddenOS) + { + if (!GetDevicePathForHiddenOS()) + AbortProcess ("INVALID_PATH"); + } + } + break; + + case HIDDEN_VOL_PRE_CIPHER_PAGE: + { + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDVOL_PRE_CIPHER_TITLE")); + + if (bHiddenOS) + { + // Verify whether the clone of the OS fits in the hidden volume (the hidden + // volume is to host a hidden OS). + if (nMaximumHiddenVolSize - TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH < GetSystemPartitionSize()) + { + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDDEN_VOLUME_TOO_SMALL_FOR_OS_CLONE")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("EXIT")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + + bConfirmQuit = FALSE; + bConfirmQuitSysEncPretest = FALSE; + } + else + { + // The hidden volume must be as large as the system partition + nVolumeSize = GetSystemPartitionSize() + TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH; + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDDEN_OS_PRE_CIPHER_HELP")); + } + } + else + { + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDVOL_PRE_CIPHER_HELP")); + } + } + break; + + case CIPHER_PAGE: + { + int ea, hid; + wchar_t buf[100]; + + // Encryption algorithms + + SendMessage (GetDlgItem (hwndDlg, IDC_COMBO_BOX), CB_RESETCONTENT, 0, 0); + + if (bHiddenVol) + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVolHost ? "CIPHER_HIDVOL_HOST_TITLE" : "CIPHER_HIDVOL_TITLE")); + else + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("CIPHER_TITLE")); + + for (ea = EAGetFirst (); ea != 0; ea = EAGetNext (ea)) + { + if (EAIsFormatEnabled (ea)) + AddComboPair (GetDlgItem (hwndDlg, IDC_COMBO_BOX), EAGetName (buf, ea, 1), ea); + } + + SelectAlgo (GetDlgItem (hwndDlg, IDC_COMBO_BOX), &nVolumeEA); + ComboSelChangeEA (hwndDlg); + SetFocus (GetDlgItem (hwndDlg, IDC_COMBO_BOX)); + + ToHyperlink (hwndDlg, IDC_LINK_MORE_INFO_ABOUT_CIPHER); + + // Hash algorithms + + if (SysEncInEffect ()) + { + hash_algo = DEFAULT_HASH_ALGORITHM_BOOT; + RandSetHashFunction (hash_algo); + + for (hid = FIRST_PRF_ID; hid <= LAST_PRF_ID; hid++) + { + // For now, we keep RIPEMD160 for system encryption + if (((hid == RIPEMD160) || !HashIsDeprecated (hid)) && HashForSystemEncryption (hid)) + AddComboPair (GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO), HashGetName(hid), hid); + } + } + else + { + hash_algo = RandGetHashFunction(); + for (hid = FIRST_PRF_ID; hid <= LAST_PRF_ID; hid++) + { + if (!HashIsDeprecated (hid)) + AddComboPair (GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO), HashGetName(hid), hid); + } + } + + SelectAlgo (GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO), &hash_algo); + + ToHyperlink (hwndDlg, IDC_LINK_HASH_INFO); + + // Wizard buttons + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + } + break; + + case SIZE_PAGE: + { + wchar_t str[1000]; + + if (bHiddenVolHost) + { + StringCbCopyW (str, sizeof(str), GetString ("SIZE_HELP_HIDDEN_HOST_VOL")); + } + else + { + StringCbCopyW (str, sizeof(str), GetString (bHiddenVol ? "SIZE_HELP_HIDDEN_VOL" : "SIZE_HELP")); + } + + if (bDevice && !(bHiddenVol && !bHiddenVolHost)) // If raw device but not a hidden volume + { + StringCbPrintfW (str, sizeof str, L"%s%s", + GetString ((bHiddenOS && bHiddenVol) ? "SIZE_PARTITION_HIDDEN_SYSENC_HELP" : "SIZE_PARTITION_HELP"), + (bHiddenVolHost && !bHiddenOS) ? GetString ("SIZE_PARTITION_HIDDEN_VOL_HELP") : L""); + } + + SendMessage (GetDlgItem (hwndDlg, IDC_SPACE_LEFT), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_SIZEBOX), EM_LIMITTEXT, 12, 0); + + if(!QueryFreeSpace (hwndDlg, GetDlgItem (hwndDlg, IDC_SPACE_LEFT), TRUE)) + { + nUIVolumeSize=0; + nVolumeSize=0; + SetWindowTextW (GetDlgItem (hwndDlg, IDC_SIZEBOX), GetString ("UNKNOWN")); + EnableWindow (GetDlgItem (hwndDlg, IDC_SIZEBOX), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_KB), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_MB), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_GB), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_TB), FALSE); + } + else if (bDevice && !(bHiddenVol && !bHiddenVolHost)) // If raw device but not a hidden volume + { + EnableWindow (GetDlgItem (hwndDlg, IDC_SIZEBOX), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_KB), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_MB), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_GB), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_TB), FALSE); + } + else + { + EnableWindow (GetDlgItem (hwndDlg, IDC_SIZEBOX), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_KB), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_MB), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_GB), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_TB), TRUE); + } + + SendMessage (GetDlgItem (hwndDlg, IDC_KB), BM_SETCHECK, BST_UNCHECKED, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_MB), BM_SETCHECK, BST_UNCHECKED, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_GB), BM_SETCHECK, BST_UNCHECKED, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_TB), BM_SETCHECK, BST_UNCHECKED, 0); + + switch (nMultiplier) + { + case BYTES_PER_KB: + SendMessage (GetDlgItem (hwndDlg, IDC_KB), BM_SETCHECK, BST_CHECKED, 0); + break; + case BYTES_PER_MB: + SendMessage (GetDlgItem (hwndDlg, IDC_MB), BM_SETCHECK, BST_CHECKED, 0); + break; + case BYTES_PER_GB: + SendMessage (GetDlgItem (hwndDlg, IDC_GB), BM_SETCHECK, BST_CHECKED, 0); + break; + case BYTES_PER_TB: + SendMessage (GetDlgItem (hwndDlg, IDC_TB), BM_SETCHECK, BST_CHECKED, 0); + break; + } + + if (nUIVolumeSize != 0) + { + wchar_t szTmp[32]; + StringCbPrintfW (szTmp, sizeof(szTmp), L"%I64u", nUIVolumeSize); + SetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTmp); + } + + SetFocus (GetDlgItem (hwndDlg, IDC_SIZEBOX)); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), str); + + if (bHiddenVol) + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVolHost ? "SIZE_HIDVOL_HOST_TITLE" : "SIZE_HIDVOL_TITLE")); + else + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SIZE_TITLE")); + + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + + VerifySizeAndUpdate (hwndDlg, FALSE); + } + break; + + case HIDDEN_VOL_HOST_PASSWORD_PAGE: + case NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE: + { + /* Populate the PRF algorithms list */ + int nIndex, i; + HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + + nIndex = (int) SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); + + for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) + { + nIndex = (int) SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); + } + + /* make autodetection the default */ + SendMessage (hComboBox, CB_SETCURSEL, 0, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD_DIRECT), EM_LIMITTEXT, MAX_PASSWORD, 0); + + SetPassword (hwndDlg, IDC_PASSWORD_DIRECT, szRawPassword); + + SetFocus (GetDlgItem (hwndDlg, IDC_PASSWORD_DIRECT)); + + SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, MAX_PIM, 0); + SetPim (hwndDlg, IDC_PIM, volumePim); + + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_ENABLE), PimEnable? SW_HIDE : SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), PimEnable? SW_SHOW : SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), PimEnable? SW_SHOW : SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), PimEnable? SW_SHOW : SW_HIDE); + + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (bInPlaceEncNonSys ? (bInPlaceEncNonSysResumed ? "NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE_HELP" : "NONSYS_INPLACE_DEC_PASSWORD_PAGE_HELP") : "PASSWORD_HIDDENVOL_HOST_DIRECT_HELP")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bInPlaceEncNonSys ? "PASSWORD" : "PASSWORD_HIDVOL_HOST_TITLE")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), !bInPlaceEncNonSys); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + } + + break; + + case PASSWORD_PAGE: + { + wchar_t str[1000]; + + hPasswordInputField = GetDlgItem (hwndDlg, IDC_PASSWORD); + hVerifyPasswordInputField = GetDlgItem (hwndDlg, IDC_VERIFY); + + if (SysEncInEffect ()) + { + ToBootPwdField (hwndDlg, IDC_PASSWORD); + ToBootPwdField (hwndDlg, IDC_VERIFY); + + StringCbPrintfW (OrigKeyboardLayout, sizeof(OrigKeyboardLayout), L"%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF); + + if ((DWORD) GetKeyboardLayout (NULL) != 0x00000409 && (DWORD) GetKeyboardLayout (NULL) != 0x04090409) + { + DWORD keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); + + if (keybLayout != 0x00000409 && keybLayout != 0x04090409) + { + Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", MainDlg); + EndMainDlg (MainDlg); + return 1; + } + bKeyboardLayoutChanged = TRUE; + } + + + if (SetTimer (MainDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0) + { + Error ("CANNOT_SET_TIMER", MainDlg); + EndMainDlg (MainDlg); + return 1; + } + } + + if (bHiddenVolHost) + { + StringCbCopyW (str, sizeof(str), GetString (bHiddenOS ? "PASSWORD_SYSENC_OUTERVOL_HELP" : "PASSWORD_HIDDENVOL_HOST_HELP")); + } + else if (bHiddenVol) + { + StringCbPrintfW (str, sizeof str, L"%s%s", + GetString (bHiddenOS ? "PASSWORD_HIDDEN_OS_HELP" : "PASSWORD_HIDDENVOL_HELP"), + GetString ("PASSWORD_HELP")); + } + else + { + StringCbCopyW (str, sizeof(str), GetString ("PASSWORD_HELP")); + } + + SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_VERIFY), EM_LIMITTEXT, MAX_PASSWORD, 0); + + SetPassword (hwndDlg, IDC_PASSWORD, szRawPassword); + SetPassword (hwndDlg, IDC_VERIFY, szVerify); + + SetFocus (GetDlgItem (hwndDlg, IDC_PASSWORD)); + + SetCheckBox (hwndDlg, IDC_PIM_ENABLE, PimEnable); + + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable && !SysEncInEffect()); + EnableWindow (GetDlgItem (hwndDlg, IDC_KEY_FILES), KeyFilesEnable); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), str); + + if (CreatingHiddenSysVol()) + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PASSWORD_HIDDEN_OS_TITLE")); + else if (bHiddenVol) + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVolHost ? "PASSWORD_HIDVOL_HOST_TITLE" : "PASSWORD_HIDVOL_TITLE")); + else if (WizardMode == WIZARD_MODE_SYS_DEVICE) + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PASSWORD")); + else + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PASSWORD_TITLE")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + + VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (GetParent (hwndDlg), IDC_NEXT), + GetDlgItem (hwndDlg, IDC_PASSWORD), + GetDlgItem (hwndDlg, IDC_VERIFY), + NULL, + NULL, + KeyFilesEnable && FirstKeyFile!=NULL && !SysEncInEffect()); + volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); + + } + break; + + case PIM_PAGE: + { + SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, SysEncInEffect()? MAX_BOOT_PIM: MAX_PIM, 0); + if (volumePim > 0) + { + SetPim (hwndDlg, IDC_PIM, volumePim); + + PimValueChangedWarning = TRUE; + SetDlgItemTextW (hwndDlg, IDC_PIM_HELP, GetString (SysEncInEffect ()? "PIM_SYSENC_CHANGE_WARNING" : "PIM_CHANGE_WARNING")); + } + + SetFocus (GetDlgItem (hwndDlg, IDC_PIM)); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (SysEncInEffect ()? "PIM_SYSENC_HELP" : "PIM_HELP")); + + ToHyperlink (hwndDlg, IDC_LINK_PIM_INFO); + + if (CreatingHiddenSysVol()) + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PIM_HIDDEN_OS_TITLE")); + else if (bHiddenVol) + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVolHost ? "PIM_HIDVOL_HOST_TITLE" : "PIM_HIDVOL_TITLE")); + else if (WizardMode == WIZARD_MODE_SYS_DEVICE) + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PIM")); + else + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PIM_TITLE")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + } + break; + + case FILESYS_PAGE: + { + wchar_t szTmp[8192]; + + Init2RadButtonPageYesNo (nNeedToStoreFilesOver4GB); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("FILESYS_PAGE_TITLE")); + + StringCbCopyW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_QUESTION")); + + if (bHiddenVolHost) + StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); + else + { + StringCbCatW (szTmp, sizeof(szTmp), L"\n\n\n"); + StringCbCatW (szTmp, sizeof(szTmp), GetString ("NOTE_BEGINNING")); + } + + StringCbCatW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_EXPLANATION")); + + if (bHiddenVolHost) + { + StringCbCatW (szTmp, sizeof(szTmp), L" "); + StringCbCatW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_EXPLANATION_HIDVOL")); + } + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), szTmp); + } + break; + + case SYSENC_COLLECTING_RANDOM_DATA_PAGE: + case NONSYS_INPLACE_ENC_RAND_DATA_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("COLLECTING_RANDOM_DATA_TITLE")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + + mouseEntropyGathered = 0xFFFFFFFF; + mouseEventsInitialCount = 0; + bUseMask = FALSE; + { + HCRYPTPROV hRngProv; + if (CryptAcquireContext (&hRngProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + { + if (CryptGenRandom (hRngProv, sizeof (maskRandPool), maskRandPool)) + bUseMask = TRUE; + CryptReleaseContext (hRngProv, 0); + } + } + + SetTimer (GetParent (hwndDlg), TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL); + + hRandPoolSys = GetDlgItem (hwndDlg, IDC_SYS_POOL_CONTENTS); + hEntropyBar = GetDlgItem (hwndDlg, IDC_ENTROPY_BAR); + SendMessage (hEntropyBar, PBM_SETRANGE32, 0, maxEntropyLevel); + SendMessage (hEntropyBar, PBM_SETSTEP, 1, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_SYS_POOL_CONTENTS), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); + + SendMessage (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), BM_SETCHECK, showKeys ? BST_CHECKED : BST_UNCHECKED, 0); + + DisplayRandPool (hwndDlg, hRandPoolSys, showKeys); + + break; + + case SYSENC_KEYS_GEN_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("KEYS_GEN_TITLE")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + + hMasterKey = GetDlgItem (hwndDlg, IDC_DISK_KEY); + hHeaderKey = GetDlgItem (hwndDlg, IDC_HEADER_KEY); + + SendMessage (GetDlgItem (hwndDlg, IDC_DISK_KEY), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_HEADER_KEY), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); + + SendMessage (GetDlgItem (hwndDlg, IDC_DISPLAY_KEYS), BM_SETCHECK, showKeys ? BST_CHECKED : BST_UNCHECKED, 0); + + DisplayPortionsOfKeys (hHeaderKey, hMasterKey, HeaderKeyGUIView, MasterKeyGUIView, !showKeys); + + break; + + case SYSENC_RESCUE_DISK_CREATION_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("RESCUE_DISK")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (hwndDlg, IDT_RESCUE_DISK_INFO), GetString ("RESCUE_DISK_INFO")); + SetDlgItemText (hwndDlg, IDC_RESCUE_DISK_ISO_PATH, szRescueDiskISO); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), (GetWindowTextLength (GetDlgItem (hwndDlg, IDC_RESCUE_DISK_ISO_PATH)) > 1)); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + SetCheckBox (hCurPage, IDC_SKIP_RESCUE_VERIFICATION, bDontVerifyRescueDisk); + + break; + + case SYSENC_RESCUE_DISK_BURN_PAGE: + { + wchar_t szTmp[8192]; + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bDontVerifyRescueDisk ? "RESCUE_DISK_CREATED_TITLE" : "RESCUE_DISK_RECORDING_TITLE")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + StringCbPrintfW (szTmp, sizeof szTmp, + GetString (bDontVerifyRescueDisk ? "RESCUE_DISK_BURN_INFO_NO_CHECK" : "RESCUE_DISK_BURN_INFO"), + szRescueDiskISO, IsWindowsIsoBurnerAvailable() ? L"" : GetString ("RESCUE_DISK_BURN_INFO_NONWIN_ISO_BURNER")); + + SetWindowTextW (GetDlgItem (hwndDlg, IDT_RESCUE_DISK_BURN_INFO), szTmp); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + + /* The 'Back' button must be disabled now because the user could burn a Rescue Disk, then go back, and + generate a different master key, which would cause the Rescue Disk verification to fail (the result + would be confusion and bug reports). */ + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + + if (IsWindowsIsoBurnerAvailable()) + SetWindowTextW (GetDlgItem (hwndDlg, IDC_DOWNLOAD_CD_BURN_SOFTWARE), GetString ("LAUNCH_WIN_ISOBURN")); + + ToHyperlink (hwndDlg, IDC_DOWNLOAD_CD_BURN_SOFTWARE); + + if (IsWindowsIsoBurnerAvailable() && !bDontVerifyRescueDisk) + LaunchWindowsIsoBurner (hwndDlg, szRescueDiskISO); + } + break; + + case SYSENC_RESCUE_DISK_VERIFIED_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("RESCUE_DISK_DISK_VERIFIED_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("RESCUE_DISK_VERIFIED_INFO")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + + // Rescue Disk has been verified, no need to go back + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + + // Prevent losing the burned rescue disk by inadvertent exit + bConfirmQuit = TRUE; + + break; + + case SYSENC_WIPE_MODE_PAGE: + case NONSYS_INPLACE_ENC_WIPE_MODE_PAGE: + { + if (nWipeMode == TC_WIPE_1_RAND) + nWipeMode = TC_WIPE_NONE; + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("WIPE_MODE_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDT_WIPE_MODE_INFO), GetString ("INPLACE_ENC_WIPE_MODE_INFO")); + + PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), + SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING && !bInPlaceEncNonSys, + TRUE, + FALSE); + + SelectAlgo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), (int *) &nWipeMode); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + } + break; + + case SYSENC_PRETEST_INFO_PAGE: + + if (bHiddenOS) + { + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDDEN_OS_CREATION_PREINFO_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDDEN_OS_CREATION_PREINFO_HELP")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("START")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + } + else + { + wchar_t finalMsg[8024] = {0}; + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYS_ENCRYPTION_PRETEST_TITLE")); + + try + { + StringCbPrintfW (finalMsg, sizeof(finalMsg), + GetString ("SYS_ENCRYPTION_PRETEST_INFO"), + BootEncObj->GetSystemDriveConfiguration().DriveNumber); + } + catch (Exception &e) + { + e.Show (hwndDlg); + EndMainDlg (MainDlg); + return 0; + } + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), finalMsg); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("TEST")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + } + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + + break; + + case SYSENC_PRETEST_RESULT_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYS_ENCRYPTION_PRETEST_RESULT_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYS_ENCRYPTION_PRETEST_RESULT_INFO")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("ENCRYPT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("DEFER")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); + + break; + + case SYSENC_ENCRYPTION_PAGE: + + if (CreateSysEncMutex ()) + { + try + { + BootEncStatus = BootEncObj->GetStatus(); + bSystemEncryptionInProgress = BootEncStatus.SetupInProgress; + } + catch (Exception &e) + { + e.Show (hwndDlg); + Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); + EndMainDlg (MainDlg); + return 0; + } + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), + GetString (SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING ? "ENCRYPTION" : "DECRYPTION")); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_ENCRYPTION_PAGE_INFO")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("DEFER")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), + GetString (SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING ? "ENCRYPT" : "DECRYPT")); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_PAUSE), + GetString (bSystemEncryptionInProgress ? "IDC_PAUSE" : "RESUME")); + + EnableWindow (GetDlgItem (hwndDlg, IDC_PAUSE), BootEncStatus.DriveEncrypted); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), !BootEncStatus.SetupInProgress); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), TRUE); + + ToHyperlink (hwndDlg, IDC_MORE_INFO_SYS_ENCRYPTION); + + if (SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING) + { + nWipeMode = TC_WIPE_NONE; + EnableWindow (GetDlgItem (hwndDlg, IDC_WIPE_MODE), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_WIPE_MODE), FALSE); + PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), TRUE, TRUE, FALSE); + SelectAlgo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), (int *) &nWipeMode); + } + else + { + EnableWindow (GetDlgItem (hwndDlg, IDC_WIPE_MODE), !bSystemEncryptionInProgress); + PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), FALSE, TRUE, FALSE); + SelectAlgo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), (int *) &nWipeMode); + } + + PostMessage (hwndDlg, TC_APPMSG_PERFORM_POST_SYSENC_WMINIT_TASKS, 0, 0); + } + else + { + Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", MainDlg); + EndMainDlg (MainDlg); + return 0; + } + return 0; + + case NONSYS_INPLACE_ENC_RESUME_PARTITION_SEL_PAGE: + + { + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("FILE_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("NONSYS_INPLACE_ENC_RESUME_VOL_SELECT_HELP")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); + + foreach (const HostDevice &device, DeferredNonSysInPlaceEncDevices) + { + SendMessage (GetDlgItem (hwndDlg, IDC_LIST_BOX), LB_ADDSTRING, 0, (LPARAM) device.Path.c_str()); + } + + // Deselect all + SendMessage (GetDlgItem (hwndDlg, IDC_LIST_BOX), LB_SETCURSEL, (WPARAM) -1, 0); + } + + break; + + case NONSYS_INPLACE_ENC_TRANSFORM_PAGE: + + if (bInPlaceEncNonSysResumed) + { + WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE; + + if (LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) != 0) + nWipeMode = savedWipeAlgorithm; + } + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bInPlaceDecNonSys ? "DECRYPTION" : "ENCRYPTION")); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (bInPlaceDecNonSys ? "NONSYS_INPLACE_DEC_DECRYPTION_PAGE_INFO" : "NONSYS_INPLACE_ENC_ENCRYPTION_PAGE_INFO")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString (bInPlaceEncNonSysResumed ? "DEFER" : "CANCEL")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString (bInPlaceEncNonSysResumed ? "RESUME" : (bInPlaceDecNonSys ? "DECRYPT" : "ENCRYPT"))); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_PAUSE), GetString ("IDC_PAUSE")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), !bInPlaceEncNonSysResumed && !bInPlaceDecNonSys); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PAUSE), FALSE); + + ShowWindow (GetDlgItem (hwndDlg, IDC_MORE_INFO_SYS_ENCRYPTION), SW_HIDE); + + if (bInPlaceDecNonSys) + { + ShowWindow(GetDlgItem(hwndDlg, IDT_FORMAT_OPTIONS), SW_HIDE); + ShowWindow(GetDlgItem(hwndDlg, IDT_WIPE_MODE), SW_HIDE); + ShowWindow(GetDlgItem(hwndDlg, IDC_WIPE_MODE), SW_HIDE); + } + else + { + EnableWindow (GetDlgItem (hwndDlg, IDC_WIPE_MODE), TRUE); + PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), FALSE, TRUE, FALSE); + SelectAlgo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), (int *) &nWipeMode); + } + + break; + + case NONSYS_INPLACE_ENC_TRANSFORM_FINISHED_PAGE: + + bConfirmQuit = FALSE; + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bInPlaceDecNonSys ? "NONSYS_INPLACE_DEC_FINISHED_TITLE" : "NONSYS_INPLACE_ENC_FINISHED_TITLE")); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (bInPlaceDecNonSys ? "NONSYS_INPLACE_DEC_FINISHED_INFO" : "NONSYS_INPLACE_ENC_FINISHED_INFO")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("FINALIZE")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("EXIT")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), FALSE); + + break; + + case NONSYS_INPLACE_DEC_TRANSFORM_FINISHED_DRIVE_LETTER_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("NONSYS_INPLACE_DEC_FINISHED_TITLE")); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("NONSYS_INPLACE_DEC_FINISHED_DRIVE_LETTER_SEL_INFO")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("FINALIZE")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); + + // The Cancel button and the X button must be disabled to prevent the user from forgetting to assign a drive letter to the partition by closing + // the window accidentally or clicking Cancel. The user is forced to click Finish to assign at least the pre-selected free drive letter. + // This is critical because inexperienced users would not know how to access data on the decrypted volume without a drive letter. + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), FALSE); + DisableCloseButton (MainDlg); + bConfirmQuit = TRUE; // Alt-F4 will still work but the user will be prompted to confirm the action. + + // Decryption of non-system volume finished, no drive letter is assigned to the decrypted volume, and free drive letters are available. + // This is critical because inexperienced users would not know how to access data on the decrypted volume. We cannot allow exit + // until a drive letter is freed up and assigned to the decrypted volume. + + while (GetFirstAvailableDrive () == -1) + { + Error ("NONSYS_INPLACE_DEC_FINISHED_NO_DRIVE_LETTER_AVAILABLE", hwndDlg); + } + + // Populate the combobox with free drive letters + { + DWORD dwUsedDrives = GetUsedLogicalDrives(); + wchar_t szDriveLetter[] = {L' ', L':', 0 }; + int i; + + for (i = 0; i < 26; i++) + { + if (!(dwUsedDrives & 1 << i)) + { + // Add + szDriveLetter [0] = (wchar_t) (i + L'A'); + AddComboPair (GetDlgItem (hCurPage, IDC_DRIVE_LETTER_LIST), szDriveLetter, i); + } + } + } + SendMessage (GetDlgItem (hwndDlg, IDC_DRIVE_LETTER_LIST), CB_SETCURSEL, 0, 0); + break; + + case FORMAT_PAGE: + { + BOOL bNTFSallowed = FALSE; + BOOL bFATallowed = FALSE; + BOOL bEXFATallowed = FALSE; + BOOL bNoFSallowed = FALSE; + HCRYPTPROV hRngProv; + + mouseEntropyGathered = 0xFFFFFFFF; + mouseEventsInitialCount = 0; + bUseMask = FALSE; + if (CryptAcquireContext (&hRngProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + { + if (CryptGenRandom (hRngProv, sizeof (maskRandPool), maskRandPool)) + bUseMask = TRUE; + CryptReleaseContext (hRngProv, 0); + } + + SetTimer (GetParent (hwndDlg), TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL); + + hMasterKey = GetDlgItem (hwndDlg, IDC_DISK_KEY); + hHeaderKey = GetDlgItem (hwndDlg, IDC_HEADER_KEY); + hRandPool = GetDlgItem (hwndDlg, IDC_RANDOM_BYTES); + hEntropyBar = GetDlgItem (hwndDlg, IDC_ENTROPY_BAR); + SendMessage (hEntropyBar, PBM_SETRANGE32, 0, maxEntropyLevel); + SendMessage (hEntropyBar, PBM_SETSTEP, 1, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_DISK_KEY), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_HEADER_KEY), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), + GetString (bHiddenVolHost ? "FORMAT_HIDVOL_HOST_HELP" : "FORMAT_HELP")); + + if (bHiddenVol) + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVolHost ? "FORMAT_HIDVOL_HOST_TITLE" : "FORMAT_HIDVOL_TITLE")); + else + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("FORMAT_TITLE")); + + /* Quick/Dynamic */ + + if (bHiddenVol) + { + quickFormat = !bHiddenVolHost; + bSparseFileSwitch = FALSE; + + SetCheckBox (hwndDlg, IDC_QUICKFORMAT, quickFormat); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_QUICKFORMAT), GetString ((bDevice || !bHiddenVolHost) ? "IDC_QUICKFORMAT" : "SPARSE_FILE")); + EnableWindow (GetDlgItem (hwndDlg, IDC_QUICKFORMAT), bDevice && bHiddenVolHost); + } + else + { + if (bDevice) + { + bSparseFileSwitch = FALSE; + SetWindowTextW (GetDlgItem (hwndDlg, IDC_QUICKFORMAT), GetString("IDC_QUICKFORMAT")); + EnableWindow (GetDlgItem (hwndDlg, IDC_QUICKFORMAT), TRUE); + } + else + { + wchar_t root[TC_MAX_PATH]; + DWORD fileSystemFlags = 0; + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_QUICKFORMAT), GetString("SPARSE_FILE")); + + /* Check if the host file system supports sparse files */ + + if (GetVolumePathName (szFileName, root, array_capacity (root))) + { + GetVolumeInformation (root, NULL, 0, NULL, NULL, &fileSystemFlags, NULL, 0); + bSparseFileSwitch = fileSystemFlags & FILE_SUPPORTS_SPARSE_FILES; + } + else + bSparseFileSwitch = FALSE; + + EnableWindow (GetDlgItem (hwndDlg, IDC_QUICKFORMAT), bSparseFileSwitch); + } + } + + SendMessage (GetDlgItem (hwndDlg, IDC_SHOW_KEYS), BM_SETCHECK, showKeys ? BST_CHECKED : BST_UNCHECKED, 0); + SetWindowText (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), showKeys ? L"" : L"******************************** "); + SetWindowText (GetDlgItem (hwndDlg, IDC_HEADER_KEY), showKeys ? L"" : L"******************************** "); + SetWindowText (GetDlgItem (hwndDlg, IDC_DISK_KEY), showKeys ? L"" : L"******************************** "); + + SendMessage (GetDlgItem (hwndDlg, IDC_CLUSTERSIZE), CB_RESETCONTENT, 0, 0); + AddComboPair (GetDlgItem (hwndDlg, IDC_CLUSTERSIZE), GetString ("DEFAULT"), 0); + + for (int i = 1; i <= 128; i *= 2) + { + wstringstream s; + DWORD size = GetFormatSectorSize() * i; + + if (size > TC_MAX_FAT_CLUSTER_SIZE) + break; + + if (size == 512) + s << L"0.5"; + else + s << size / BYTES_PER_KB; + + s << L" " << GetString ("KB"); + + AddComboPair (GetDlgItem (hwndDlg, IDC_CLUSTERSIZE), s.str().c_str(), i); + } + + SendMessage (GetDlgItem (hwndDlg, IDC_CLUSTERSIZE), CB_SETCURSEL, 0, 0); + + EnableWindow (GetDlgItem (hwndDlg, IDC_CLUSTERSIZE), TRUE); + + /* Filesystems */ + + bNTFSallowed = FALSE; + bFATallowed = FALSE; + bNoFSallowed = FALSE; + + SendMessage (GetDlgItem (hwndDlg, IDC_FILESYS), CB_RESETCONTENT, 0, 0); + + EnableWindow (GetDlgItem (hwndDlg, IDC_FILESYS), TRUE); + + uint64 dataAreaSize = GetVolumeDataAreaSize (bHiddenVol && !bHiddenVolHost, nVolumeSize); + + if (!CreatingHiddenSysVol()) + { + if (dataAreaSize >= TC_MIN_NTFS_FS_SIZE && dataAreaSize <= TC_MAX_NTFS_FS_SIZE) + { + AddComboPair (GetDlgItem (hwndDlg, IDC_FILESYS), L"NTFS", FILESYS_NTFS); + bNTFSallowed = TRUE; + } + + if (dataAreaSize >= TC_MIN_FAT_FS_SIZE && dataAreaSize <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()) + { + AddComboPair (GetDlgItem (hwndDlg, IDC_FILESYS), L"FAT", FILESYS_FAT); + bFATallowed = TRUE; + } + + //exFAT support added starting from Vista SP1 + if (IsOSVersionAtLeast (WIN_VISTA, 1) && dataAreaSize >= TC_MIN_EXFAT_FS_SIZE && dataAreaSize <= TC_MAX_EXFAT_FS_SIZE) + { + AddComboPair (GetDlgItem (hwndDlg, IDC_FILESYS), L"exFAT", FILESYS_EXFAT); + bEXFATallowed = TRUE; + } + } + else + { + // We're creating a hidden volume for a hidden OS, so we don't need to format it with + // any filesystem (the entire OS will be copied to the hidden volume sector by sector). + EnableWindow (GetDlgItem (hwndDlg, IDC_FILESYS), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_CLUSTERSIZE), FALSE); + } + + if (!bHiddenVolHost) + { + AddComboPair (GetDlgItem (hwndDlg, IDC_FILESYS), GetString ("NONE"), FILESYS_NONE); + bNoFSallowed = TRUE; + } + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + + if (fileSystem == FILESYS_NONE) // If no file system has been previously selected + { + // Set default file system + + if (bFATallowed && !(nNeedToStoreFilesOver4GB == 1 && (bNTFSallowed || bEXFATallowed))) + fileSystem = FILESYS_FAT; + else if (bEXFATallowed) + fileSystem = FILESYS_EXFAT; + else if (bNTFSallowed) + fileSystem = FILESYS_NTFS; + else if (bNoFSallowed) + fileSystem = FILESYS_NONE; + else + { + AddComboPair (GetDlgItem (hwndDlg, IDC_FILESYS), L"---", 0); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); + } + } + + SendMessage (GetDlgItem (hwndDlg, IDC_FILESYS), CB_SETCURSEL, 0, 0); + SelectAlgo (GetDlgItem (hwndDlg, IDC_FILESYS), (int *) &fileSystem); + + EnableWindow (GetDlgItem (hwndDlg, IDC_ABORT_BUTTON), FALSE); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("FORMAT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + + SetFocus (GetDlgItem (GetParent (hwndDlg), IDC_NEXT)); + } + break; + + case FORMAT_FINISHED_PAGE: + { + if (!bHiddenVolHost && bHiddenVol && !bHiddenVolFinished) + { + wchar_t msg[4096]; + + nNeedToStoreFilesOver4GB = -1; + + if (bHiddenOS) + { + wchar_t szMaxRecomOuterVolFillSize[100]; + + __int64 maxRecomOuterVolFillSize = 0; + + // Determine the maximum recommended total size of files that can be copied to the outer volume + // while leaving enough space for the hidden volume, which must contain a clone of the OS + + maxRecomOuterVolFillSize = nVolumeSize - GetSystemPartitionSize(); + + // -50% reserve for filesystem "peculiarities" + maxRecomOuterVolFillSize /= 2; + + StringCbPrintfW (szMaxRecomOuterVolFillSize, sizeof(szMaxRecomOuterVolFillSize), L"%I64d %s", maxRecomOuterVolFillSize / BYTES_PER_MB, GetString ("MB")); + + StringCbPrintfW (msg, sizeof(msg), GetString ("HIDVOL_HOST_FILLING_HELP_SYSENC"), hiddenVolHostDriveNo + 'A', szMaxRecomOuterVolFillSize); + } + else + StringCbPrintfW (msg, sizeof(msg), GetString ("HIDVOL_HOST_FILLING_HELP"), hiddenVolHostDriveNo + 'A'); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), msg); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDVOL_HOST_FILLING_TITLE")); + } + else + { + if (bHiddenOS) + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_HIDDEN_VOL_FORMAT_FINISHED_HELP")); + else + { + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (bInPlaceEncNonSys ? "NONSYS_INPLACE_ENC_FINISHED_INFO" : "FORMAT_FINISHED_HELP")); + bConfirmQuit = FALSE; + } + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVol ? "HIDVOL_FORMAT_FINISHED_TITLE" : "FORMAT_FINISHED_TITLE")); + } + + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), (!bHiddenVol || bHiddenVolFinished) && !bHiddenOS && !bInPlaceEncNonSys); + + if ((!bHiddenVol || bHiddenVolFinished) && !bHiddenOS) + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("EXIT")); + } + break; + + case SYSENC_HIDDEN_OS_INITIAL_INFO_PAGE: + + if (!IsHiddenOSRunning() || !bHiddenOS) + { + ReportUnexpectedState (SRC_POS); + EndMainDlg (MainDlg); + return 0; + } + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_HIDDEN_OS_INITIAL_INFO_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("FIRST_HIDDEN_OS_BOOT_INFO")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("DEFER")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); + break; + + case SYSENC_HIDDEN_OS_WIPE_INFO_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYSENC_HIDDEN_OS_WIPE_INFO_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_HIDDEN_OS_WIPE_INFO")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + + break; + + case DEVICE_WIPE_MODE_PAGE: + + if (nWipeMode == TC_WIPE_NONE) + nWipeMode = TC_WIPE_1_RAND; + + if (bHiddenOS && IsHiddenOSRunning()) + { + // Decoy system partition wipe + + WipeAbort(); // In case the GUI previously crashed and the driver is still wiping + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); + } + else + { + // Regular device wipe (not decoy system partition wipe) + + // Title bar + SetWindowText (MainDlg, _T(TC_APP_NAME)); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + } + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("WIPE_MODE_TITLE")); + SetWindowTextW (GetDlgItem (hwndDlg, IDT_WIPE_MODE_INFO), GetString ("WIPE_MODE_INFO")); + + PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), FALSE, FALSE, TRUE); + + SelectAlgo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), (int *) &nWipeMode); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); + + break; + + case DEVICE_WIPE_PAGE: + + if (bHiddenOS && IsHiddenOSRunning()) + { + // Decoy system partition wipe + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("DEVICE_WIPE_PAGE_INFO_HIDDEN_OS")); + } + else + { + // Regular device wipe (not decoy system partition wipe) + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("DEVICE_WIPE_PAGE_INFO")); + } + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("DEVICE_WIPE_PAGE_TITLE")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("WIPE")); + SetWindowTextW (GetDlgItem (hCurPage, IDC_WIPE_MODE), (wstring (L" ") + GetWipeModeName (nWipeMode)).c_str()); + + EnableWindow (GetDlgItem (hwndDlg, IDC_ABORT_BUTTON), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + + break; + } + return 0; + + case WM_HELP: + OpenPageHelp (GetParent (hwndDlg), nCurPageNo); + return 1; + + case TC_APPMSG_PERFORM_POST_SYSENC_WMINIT_TASKS: + AfterSysEncProgressWMInitTasks (hwndDlg); + return 1; + + case WM_CTLCOLORSTATIC: + { + if (PimValueChangedWarning && ((HWND)lParam == GetDlgItem(hwndDlg, IDC_PIM_HELP)) ) + { + // we're about to draw the static + // set the text colour in (HDC)lParam + SetBkMode((HDC)wParam,TRANSPARENT); + SetTextColor((HDC)wParam, RGB(255,0,0)); + // NOTE: per documentation as pointed out by selbie, GetSolidBrush would leak a GDI handle. + return (BOOL)GetSysColorBrush(COLOR_MENU); + } + } + return 0; + + case WM_COMMAND: + + if (nCurPageNo == INTRO_PAGE) + { + switch (lw) + { + case IDC_FILE_CONTAINER: + UpdateWizardModeControls (hwndDlg, WIZARD_MODE_FILE_CONTAINER); + return 1; + + case IDC_NONSYS_DEVICE: + UpdateWizardModeControls (hwndDlg, WIZARD_MODE_NONSYS_DEVICE); + return 1; + + case IDC_SYS_DEVICE: + UpdateWizardModeControls (hwndDlg, WIZARD_MODE_SYS_DEVICE); + return 1; + + case IDC_MORE_INFO_ON_CONTAINERS: + Applink ("introcontainer", TRUE, ""); + return 1; + + case IDC_MORE_INFO_ON_SYS_ENCRYPTION: + Applink ("introsysenc", TRUE, ""); + return 1; + } + } + + if (nCurPageNo == SYSENC_TYPE_PAGE) + { + switch (lw) + { + case IDC_SYSENC_HIDDEN: + bHiddenOS = TRUE; + bHiddenVol = TRUE; + bHiddenVolHost = TRUE; + return 1; + + case IDC_SYSENC_NORMAL: + bHiddenOS = FALSE; + bHiddenVol = FALSE; + bHiddenVolHost = FALSE; + return 1; + + case IDC_HIDDEN_SYSENC_INFO_LINK: + Applink ("hiddensysenc", TRUE, ""); + return 1; + } + } + + if (nCurPageNo == SYSENC_HIDDEN_OS_REQ_CHECK_PAGE && lw == IDC_HIDDEN_SYSENC_INFO_LINK) + { + Applink ("hiddensysenc", TRUE, ""); + return 1; + } + + if (nCurPageNo == SYSENC_SPAN_PAGE) + { + switch (lw) + { + case IDC_WHOLE_SYS_DRIVE: + bWholeSysDrive = TRUE; + return 1; + case IDC_SYS_PARTITION: + bWholeSysDrive = FALSE; + return 1; + } + + } + + if (nCurPageNo == SYSENC_MULTI_BOOT_MODE_PAGE) + { + switch (lw) + { + case IDC_SINGLE_BOOT: + nMultiBoot = 1; + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + return 1; + case IDC_MULTI_BOOT: + nMultiBoot = 2; + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + return 1; + } + } + + // Dual choice pages + switch (nCurPageNo) + { + case SYSENC_MULTI_BOOT_SYS_EQ_BOOT_PAGE: + case SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE: + case SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE: + case SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE: + case SYSENC_PRE_DRIVE_ANALYSIS_PAGE: + + if (lw == IDC_CHOICE1 || lw == IDC_CHOICE2) + { + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + return 1; + } + break; + } + + if (nCurPageNo == FILESYS_PAGE && (lw == IDC_CHOICE1 || lw == IDC_CHOICE2)) + { + if (bWarnOuterVolSuitableFileSys && lw == IDC_CHOICE1 && bHiddenVolHost) + { + wchar_t szTmp [4096]; + + bWarnOuterVolSuitableFileSys = FALSE; // Do not show this warning anymore (this also prevents potential endless repetition due to some race conditions) + + StringCbCopyW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_EXPLANATION_HIDVOL")); + StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); + StringCbCatW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_EXPLANATION_HIDVOL_CONFIRM")); + + if (MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2) == IDNO) + { + nNeedToStoreFilesOver4GB = 0; + Init2RadButtonPageYesNo (nNeedToStoreFilesOver4GB); + } + } + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + return 1; + } + + if (lw == IDC_HIDDEN_VOL && nCurPageNo == VOLUME_TYPE_PAGE) + { + bHiddenVol = TRUE; + bHiddenVolHost = TRUE; + bInPlaceEncNonSys = FALSE; + return 1; + } + + if (lw == IDC_STD_VOL && nCurPageNo == VOLUME_TYPE_PAGE) + { + bHiddenVol = FALSE; + bHiddenVolHost = FALSE; + return 1; + } + + if (nCurPageNo == SYSENC_ENCRYPTION_PAGE) + { + BootEncryptionStatus locBootEncStatus; + + switch (lw) + { + case IDC_PAUSE: + try + { + locBootEncStatus = BootEncObj->GetStatus(); + + if (locBootEncStatus.SetupInProgress) + SysEncPause (); + else + SysEncResume (); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + return 1; + + case IDC_WIPE_MODE: + if (hw == CBN_SELCHANGE) + { + nWipeMode = (WipeAlgorithmId) SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), + CB_GETITEMDATA, + SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), + 0); + + return 1; + } + break; + + case IDC_MORE_INFO_SYS_ENCRYPTION: + Applink ("sysencprogressinfo", TRUE, ""); + return 1; + } + } + + if (bInPlaceEncNonSys) + { + switch (nCurPageNo) + { + case NONSYS_INPLACE_ENC_RESUME_PARTITION_SEL_PAGE: + + if (lw == IDC_LIST_BOX + && (hw == LBN_SELCHANGE || hw == LBN_DBLCLK)) + { + BOOL tmpbDevice = FALSE; + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); + + int selPartitionItemId = (int) SendMessage (GetDlgItem (hwndDlg, IDC_LIST_BOX), LB_GETCURSEL, 0, 0); + + if (selPartitionItemId == LB_ERR) + { + // Deselect all + SendMessage (GetDlgItem (hwndDlg, IDC_LIST_BOX), LB_SETCURSEL, (WPARAM) -1, 0); + + SetFocus (GetDlgItem (MainDlg, IDC_NEXT)); + return 1; + } + + SetFocus (GetDlgItem (MainDlg, IDC_NEXT)); + + StringCbCopyW (szFileName, sizeof(szFileName), DeferredNonSysInPlaceEncDevices [selPartitionItemId].Path.c_str()); + CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice); + + nVolumeSize = GetDeviceSize (szDiskFile); + if (nVolumeSize == -1) + { + handleWin32Error (MainDlg, SRC_POS); + return 1; + } + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + + return 1; + } + break; + + case NONSYS_INPLACE_ENC_TRANSFORM_PAGE: + { + switch (lw) + { + case IDC_PAUSE: + + // Pause/resume non-system in-place encryption + + if (bVolTransformThreadRunning || bVolTransformThreadToRun) + { + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), FALSE); + NonSysInplaceEncPause (); + } + else + NonSysInplaceEncResume (); + + return 1; + + case IDC_WIPE_MODE: + if (hw == CBN_SELCHANGE) + { + nWipeMode = (WipeAlgorithmId) SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), + CB_GETITEMDATA, + SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), + 0); + + return 1; + } + break; + } + } + break; + } + } + + + if (lw == IDC_OPEN_OUTER_VOLUME && nCurPageNo == FORMAT_FINISHED_PAGE) + { + OpenVolumeExplorerWindow (hiddenVolHostDriveNo); + return 1; + } + + if (lw == IDC_HIDDEN_VOL_HELP && nCurPageNo == VOLUME_TYPE_PAGE) + { + Applink ("hiddenvolume", TRUE, ""); + return 1; + } + + if (lw == IDC_ABORT_BUTTON && nCurPageNo == FORMAT_PAGE) + { + if (MessageBoxW (hwndDlg, GetString ("FORMAT_ABORT"), lpszTitle, MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2 ) == IDYES) + bVolTransformThreadCancel = TRUE; + return 1; + } + + if (lw == IDC_CIPHER_TEST && nCurPageNo == CIPHER_PAGE) + { + LPARAM nIndex; + int c; + + nIndex = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETCURSEL, 0, 0); + nVolumeEA = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETITEMDATA, nIndex, 0); + + for (c = EAGetLastCipher (nVolumeEA); c != 0; c = EAGetPreviousCipher (nVolumeEA, c)) + { + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_CIPHER_TEST_DLG), + GetParent (hwndDlg), (DLGPROC) CipherTestDialogProc, (LPARAM) c); + } + return 1; + } + + if (lw == IDC_BENCHMARK && nCurPageNo == CIPHER_PAGE) + { + // Reduce CPU load + bFastPollEnabled = FALSE; + bRandmixEnabled = FALSE; + + DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_BENCHMARK_DLG), hwndDlg, + (DLGPROC) BenchmarkDlgProc, (LPARAM) NULL); + + bFastPollEnabled = TRUE; + bRandmixEnabled = TRUE; + + return 1; + } + + if (lw == IDC_LINK_MORE_INFO_ABOUT_CIPHER && nCurPageNo == CIPHER_PAGE) + { + wchar_t name[100]; + + int nIndex = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETCURSEL, 0, 0); + nIndex = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETITEMDATA, nIndex, 0); + EAGetName (name, nIndex, 0); + + if (wcscmp (name, L"AES") == 0) + Applink ("aes", FALSE, ""); + else if (wcscmp (name, L"Serpent") == 0) + Applink ("serpent", FALSE, ""); + else if (wcscmp (name, L"Twofish") == 0) + Applink ("twofish", FALSE, ""); + else if (EAGetCipherCount (nIndex) > 1) + Applink ("cascades", TRUE, ""); + + return 1; + } + + if (lw == IDC_LINK_HASH_INFO && nCurPageNo == CIPHER_PAGE) + { + Applink ("hashalgorithms", TRUE, ""); + return 1; + } + + if (lw == IDC_LINK_PIM_INFO && nCurPageNo == PIM_PAGE) + { + Applink ("pim", TRUE, ""); + return 1; + } + + if (hw == CBN_EDITCHANGE && nCurPageNo == VOLUME_LOCATION_PAGE) + { + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), + GetWindowTextLength (GetDlgItem (hCurPage, IDC_COMBO_BOX)) > 0); + + bDeviceTransformModeChoiceMade = FALSE; + bInPlaceEncNonSys = FALSE; + + return 1; + } + + if (hw == CBN_SELCHANGE && nCurPageNo == VOLUME_LOCATION_PAGE) + { + LPARAM nIndex; + + nIndex = MoveEditToCombo ((HWND) lParam, bHistory); + nIndex = UpdateComboOrder (GetDlgItem (hwndDlg, IDC_COMBO_BOX)); + + if (nIndex != CB_ERR) + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + else + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); + + bDeviceTransformModeChoiceMade = FALSE; + bInPlaceEncNonSys = FALSE; + + return 1; + } + + if (hw == EN_CHANGE && nCurPageNo == SIZE_PAGE) + { + VerifySizeAndUpdate (hwndDlg, FALSE); + return 1; + } + + if (hw == EN_CHANGE && nCurPageNo == PASSWORD_PAGE) + { + VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (GetParent (hwndDlg), IDC_NEXT), + GetDlgItem (hwndDlg, IDC_PASSWORD), + GetDlgItem (hwndDlg, IDC_VERIFY), + NULL, + NULL, + KeyFilesEnable && FirstKeyFile!=NULL && !SysEncInEffect()); + volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); + + return 1; + } + + if (hw == EN_CHANGE && nCurPageNo == PIM_PAGE) + { + if (lw == IDC_PIM) + { + if(GetPim (hwndDlg, IDC_PIM) != 0) + { + PimValueChangedWarning = TRUE; + SetDlgItemTextW (hwndDlg, IDC_PIM_HELP, GetString (SysEncInEffect ()? "PIM_SYSENC_CHANGE_WARNING" : "PIM_CHANGE_WARNING")); + } + else + { + PimValueChangedWarning = FALSE; + SetDlgItemTextW (hwndDlg, IDC_PIM_HELP, (wchar_t *) GetDictionaryValueByInt (IDC_PIM_HELP)); + } + } + + return 1; + } + + if (lw == IDC_SHOW_PASSWORD && nCurPageNo == PASSWORD_PAGE) + { + HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD, IDC_PASSWORD, IDC_VERIFY); + return 1; + } + + if (lw == IDC_SHOW_PIM && nCurPageNo == PIM_PAGE) + { + HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PIM, IDC_PIM, 0); + return 1; + } + + if (lw == IDC_PIM_ENABLE) + { + PimEnable = GetCheckBox (hwndDlg, IDC_PIM_ENABLE); + if (!PimEnable) + volumePim = 0; + if (nCurPageNo == HIDDEN_VOL_HOST_PASSWORD_PAGE + || nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE + ) + { + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_ENABLE), PimEnable? SW_HIDE : SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), PimEnable? SW_SHOW : SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), PimEnable? SW_SHOW : SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), PimEnable? SW_SHOW : SW_HIDE); + if (PimEnable) + { + SetFocus (GetDlgItem (hwndDlg, IDC_PIM)); + } + } + return 1; + } + + if (nCurPageNo == PASSWORD_PAGE + || nCurPageNo == HIDDEN_VOL_HOST_PASSWORD_PAGE + || nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) + { + if (lw == IDC_KEY_FILES) + { + if (SysEncInEffect()) + { + Warning ("KEYFILES_NOT_SUPPORTED_FOR_SYS_ENCRYPTION", MainDlg); + return 1; + } + + KeyFilesDlgParam param; + param.EnableKeyFiles = KeyFilesEnable; + param.FirstKeyFile = FirstKeyFile; + + if (IDOK == DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, + (DLGPROC) KeyFilesDlgProc, (LPARAM) ¶m)) + { + KeyFilesEnable = param.EnableKeyFiles; + FirstKeyFile = param.FirstKeyFile; + + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); + + if (nCurPageNo != HIDDEN_VOL_HOST_PASSWORD_PAGE && nCurPageNo != NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) + EnableWindow (GetDlgItem (hwndDlg, IDC_KEY_FILES), KeyFilesEnable); + + if (nCurPageNo != HIDDEN_VOL_HOST_PASSWORD_PAGE && nCurPageNo != NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) + { + VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (GetParent (hwndDlg), IDC_NEXT), + GetDlgItem (hCurPage, IDC_PASSWORD), + GetDlgItem (hCurPage, IDC_VERIFY), + volumePassword.Text, szVerify, KeyFilesEnable && FirstKeyFile!=NULL); + } + } + + return 1; + } + + if (lw == IDC_KEYFILES_ENABLE) + { + KeyFilesEnable = GetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE); + + if (nCurPageNo != HIDDEN_VOL_HOST_PASSWORD_PAGE && nCurPageNo != NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) + { + EnableWindow (GetDlgItem (hwndDlg, IDC_KEY_FILES), KeyFilesEnable); + + VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (GetParent (hwndDlg), IDC_NEXT), + GetDlgItem (hCurPage, IDC_PASSWORD), + GetDlgItem (hCurPage, IDC_VERIFY), + volumePassword.Text, szVerify, KeyFilesEnable && FirstKeyFile!=NULL); + } + + return 1; + } + } + + if (nCurPageNo == HIDDEN_VOL_HOST_PASSWORD_PAGE + || nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) + { + if (hw == EN_CHANGE) + { + GetPassword (hCurPage, IDC_PASSWORD_DIRECT, (char*) volumePassword.Text, MAX_PASSWORD + 1, FALSE); + volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); + return 1; + } + + if (lw == IDC_SHOW_PASSWORD_SINGLE) + { + HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD_SINGLE, IDC_PASSWORD_DIRECT, IDC_PIM); + return 1; + } + } + + if ((lw == IDC_KB || lw == IDC_MB || lw == IDC_GB || lw == IDC_TB) && nCurPageNo == SIZE_PAGE) + { + SendMessage (GetDlgItem (hwndDlg, IDC_KB), BM_SETCHECK, BST_UNCHECKED, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_MB), BM_SETCHECK, BST_UNCHECKED, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_GB), BM_SETCHECK, BST_UNCHECKED, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_TB), BM_SETCHECK, BST_UNCHECKED, 0); + + switch (lw) + { + case IDC_KB: + SendMessage (GetDlgItem (hwndDlg, IDC_KB), BM_SETCHECK, BST_CHECKED, 0); + break; + case IDC_MB: + SendMessage (GetDlgItem (hwndDlg, IDC_MB), BM_SETCHECK, BST_CHECKED, 0); + break; + case IDC_GB: + SendMessage (GetDlgItem (hwndDlg, IDC_GB), BM_SETCHECK, BST_CHECKED, 0); + break; + case IDC_TB: + SendMessage (GetDlgItem (hwndDlg, IDC_TB), BM_SETCHECK, BST_CHECKED, 0); + break; + } + + VerifySizeAndUpdate (hwndDlg, FALSE); + return 1; + } + + if (lw == IDC_HIDVOL_WIZ_MODE_DIRECT && nCurPageNo == HIDDEN_VOL_WIZARD_MODE_PAGE) + { + bHiddenVolDirect = TRUE; + return 1; + } + + if (lw == IDC_HIDVOL_WIZ_MODE_FULL && nCurPageNo == HIDDEN_VOL_WIZARD_MODE_PAGE) + { + bHiddenVolDirect = FALSE; + return 1; + } + + if (lw == IDC_SELECT_VOLUME_LOCATION && nCurPageNo == VOLUME_LOCATION_PAGE) + { + if (!bDevice) + { + // Select file + + if (BrowseFiles (hwndDlg, "OPEN_TITLE", szFileName, bHistory, !bHiddenVolDirect, NULL) == FALSE) + return 1; + + AddComboItem (GetDlgItem (hwndDlg, IDC_COMBO_BOX), szFileName, bHistory); + + EnableDisableFileNext (GetDlgItem (hwndDlg, IDC_COMBO_BOX), + GetDlgItem (GetParent (hwndDlg), IDC_NEXT)); + + return 1; + } + else + { + // Select device + RawDevicesDlgParam param; + param.pszFileName = szFileName; + INT_PTR nResult = DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_RAWDEVICES_DLG), GetParent (hwndDlg), + (DLGPROC) RawDevicesDlgProc, (LPARAM) & param); + + // Check administrator privileges + if (!wcsstr (szFileName, L"Floppy") && !IsAdmin() && !IsUacSupported ()) + MessageBoxW (hwndDlg, GetString ("ADMIN_PRIVILEGES_WARN_DEVICES"), lpszTitle, MB_OK|MB_ICONWARNING); + + if (nResult == IDOK && wcslen (szFileName) > 0) + { + AddComboItem (GetDlgItem (hwndDlg, IDC_COMBO_BOX), szFileName, bHistory); + + EnableDisableFileNext (GetDlgItem (hwndDlg, IDC_COMBO_BOX), + GetDlgItem (GetParent (hwndDlg), IDC_NEXT)); + + bDeviceTransformModeChoiceMade = FALSE; + bInPlaceEncNonSys = FALSE; + } + return 1; + } + } + + if (nCurPageNo == DEVICE_TRANSFORM_MODE_PAGE) + { + switch (lw) + { + case IDC_DEVICE_TRANSFORM_MODE_FORMAT: + + bInPlaceEncNonSys = FALSE; + bDeviceTransformModeChoiceMade = TRUE; + + return 1; + + case IDC_DEVICE_TRANSFORM_MODE_INPLACE: + + bInPlaceEncNonSys = TRUE; + bDeviceTransformModeChoiceMade = TRUE; + + bHiddenVol = FALSE; + bHiddenVolDirect = FALSE; + bHiddenVolHost = FALSE; + bSparseFileSwitch = FALSE; + quickFormat = FALSE; + + return 1; + } + } + + if (lw == IDC_HIDVOL_WIZ_MODE_FULL && nCurPageNo == HIDDEN_VOL_WIZARD_MODE_PAGE) + { + bHiddenVolDirect = FALSE; + return 1; + } + + if (hw == CBN_SELCHANGE && nCurPageNo == CIPHER_PAGE) + { + switch (lw) + { + case IDC_COMBO_BOX: + ComboSelChangeEA (hwndDlg); + break; + + case IDC_COMBO_BOX_HASH_ALGO: + if (SysEncInEffect ()) + { + HWND hHashAlgoItem = GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO); + int selectedAlgo = (int) SendMessage (hHashAlgoItem, CB_GETITEMDATA, SendMessage (hHashAlgoItem, CB_GETCURSEL, 0, 0), 0); + if (!HashForSystemEncryption(selectedAlgo)) + { + hash_algo = DEFAULT_HASH_ALGORITHM_BOOT; + RandSetHashFunction (DEFAULT_HASH_ALGORITHM_BOOT); + Info ("ALGO_NOT_SUPPORTED_FOR_SYS_ENCRYPTION", MainDlg); + SelectAlgo (GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO), &hash_algo); + } + } + break; + } + return 1; + + } + + if (lw == IDC_QUICKFORMAT && IsButtonChecked (GetDlgItem (hCurPage, IDC_QUICKFORMAT))) + { + if (bSparseFileSwitch) + { + if (AskWarnYesNo("CONFIRM_SPARSE_FILE", MainDlg) == IDNO) + SetCheckBox (hwndDlg, IDC_QUICKFORMAT, FALSE); + } + else + { + if (AskWarnYesNo("WARN_QUICK_FORMAT", MainDlg) == IDNO) + SetCheckBox (hwndDlg, IDC_QUICKFORMAT, FALSE); + } + return 1; + } + + if (lw == IDC_FILESYS && hw == CBN_SELCHANGE) + { + fileSystem = (int) SendMessage (GetDlgItem (hCurPage, IDC_FILESYS), CB_GETITEMDATA, + SendMessage (GetDlgItem (hCurPage, IDC_FILESYS), CB_GETCURSEL, 0, 0) , 0); + + return 1; + } + + if (lw == IDC_SHOW_KEYS && nCurPageNo == FORMAT_PAGE) + { + showKeys = IsButtonChecked (GetDlgItem (hCurPage, IDC_SHOW_KEYS)); + + SetWindowText (GetDlgItem (hCurPage, IDC_RANDOM_BYTES), showKeys ? L" " : L"******************************** "); + SetWindowText (GetDlgItem (hCurPage, IDC_HEADER_KEY), showKeys ? L"" : L"******************************** "); + SetWindowText (GetDlgItem (hCurPage, IDC_DISK_KEY), showKeys ? L"" : L"******************************** "); + return 1; + } + + if (lw == IDC_DISPLAY_POOL_CONTENTS + && (nCurPageNo == SYSENC_COLLECTING_RANDOM_DATA_PAGE || nCurPageNo == NONSYS_INPLACE_ENC_RAND_DATA_PAGE)) + { + showKeys = IsButtonChecked (GetDlgItem (hCurPage, IDC_DISPLAY_POOL_CONTENTS)); + DisplayRandPool (hwndDlg, hRandPoolSys, showKeys); + + return 1; + } + + if (lw == IDC_DISPLAY_KEYS && nCurPageNo == SYSENC_KEYS_GEN_PAGE) + { + showKeys = IsButtonChecked (GetDlgItem (hCurPage, IDC_DISPLAY_KEYS)); + + DisplayPortionsOfKeys (GetDlgItem (hwndDlg, IDC_HEADER_KEY), GetDlgItem (hwndDlg, IDC_DISK_KEY), HeaderKeyGUIView, MasterKeyGUIView, !showKeys); + return 1; + } + + if (nCurPageNo == SYSENC_RESCUE_DISK_CREATION_PAGE) + { + if (lw == IDC_BROWSE) + { + wchar_t tmpszRescueDiskISO [TC_MAX_PATH+1]; + + if (!BrowseFiles (hwndDlg, "OPEN_TITLE", tmpszRescueDiskISO, FALSE, TRUE, NULL)) + return 1; + + StringCbCopyW (szRescueDiskISO, sizeof(szRescueDiskISO), tmpszRescueDiskISO); + + SetDlgItemText (hwndDlg, IDC_RESCUE_DISK_ISO_PATH, szRescueDiskISO); + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), (GetWindowTextLength (GetDlgItem (hwndDlg, IDC_RESCUE_DISK_ISO_PATH)) > 1)); + return 1; + } + + if ( hw == EN_CHANGE ) + { + GetDlgItemText (hwndDlg, IDC_RESCUE_DISK_ISO_PATH, szRescueDiskISO, sizeof(szRescueDiskISO)); + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), (GetWindowTextLength (GetDlgItem (hwndDlg, IDC_RESCUE_DISK_ISO_PATH)) > 1)); + return 1; + } + } + + if (nCurPageNo == SYSENC_RESCUE_DISK_BURN_PAGE && lw == IDC_DOWNLOAD_CD_BURN_SOFTWARE) + { + if (IsWindowsIsoBurnerAvailable()) + LaunchWindowsIsoBurner (hwndDlg, szRescueDiskISO); + else + Applink ("isoburning", TRUE, ""); + + return 1; + } + + if ((nCurPageNo == SYSENC_WIPE_MODE_PAGE + || nCurPageNo == NONSYS_INPLACE_ENC_WIPE_MODE_PAGE + || nCurPageNo == DEVICE_WIPE_MODE_PAGE) + && hw == CBN_SELCHANGE) + { + nWipeMode = (WipeAlgorithmId) SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), + CB_GETITEMDATA, + SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), + 0); + + return 1; + } + + if (nCurPageNo == DEVICE_WIPE_PAGE) + { + switch (lw) + { + case IDC_ABORT_BUTTON: + + if (AskWarnNoYes ("CONFIRM_WIPE_ABORT", MainDlg) == IDYES) + WipeAbort(); + + return 1; + } + } + + if (lw == IDC_NO_HISTORY) + { + if (!(bHistory = !IsButtonChecked (GetDlgItem (hCurPage, IDC_NO_HISTORY)))) + ClearHistory (GetDlgItem (hCurPage, IDC_COMBO_BOX)); + + return 1; + } + + return 0; + } + + return 0; +} + +/* Except in response to the WM_INITDIALOG and WM_ENDSESSION messages, the dialog box procedure + should return nonzero if it processes the message, and zero if it does not. - see DialogProc */ +BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + + int nNewPageNo = nCurPageNo; + + switch (uMsg) + { + case WM_INITDIALOG: + { + MainDlg = hwndDlg; + InitDialog (hwndDlg); + LocalizeDialog (hwndDlg, "IDD_VOL_CREATION_WIZARD_DLG"); + + if (IsTrueCryptInstallerRunning()) + AbortProcess ("TC_INSTALLER_IS_RUNNING"); + + // Resize the bitmap if the user has a non-default DPI + if (ScreenDPI != USER_DEFAULT_SCREEN_DPI) + { + hbmWizardBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_WIZARD), + GetDlgItem (hwndDlg, IDC_BITMAP_WIZARD), + 0, 0, 0, 0, FALSE, FALSE); + } + + LoadSettings (hwndDlg); + + LoadDefaultKeyFilesParam (); + RestoreDefaultKeyFilesParam (); + + SysEncMultiBootCfg.NumberOfSysDrives = -1; + SysEncMultiBootCfg.MultipleSystemsOnDrive = -1; + SysEncMultiBootCfg.BootLoaderLocation = -1; + SysEncMultiBootCfg.BootLoaderBrand = -1; + SysEncMultiBootCfg.SystemOnBootDrive = -1; + + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (hwndDlg); + Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); + EndMainDlg (MainDlg); + return 0; + } + + SendMessageW (GetDlgItem (hwndDlg, IDC_BOX_TITLE), WM_SETFONT, (WPARAM) hTitleFont, (LPARAM) TRUE); + SetWindowTextW (hwndDlg, lpszTitle); + + ExtractCommandLine (hwndDlg, (wchar_t *) lParam); + + if (ComServerMode) + { + InitDialog (hwndDlg); + + if (!ComServerFormat ()) + { + handleWin32Error (hwndDlg, SRC_POS); + exit (1); + } + exit (0); + } + + if (DirectCreationMode) + { + wchar_t root[TC_MAX_PATH]; + DWORD fileSystemFlags = 0; + uint64 dataAreaSize; + wchar_t szFileSystemNameBuffer[256]; + ULARGE_INTEGER free; + + showKeys = FALSE; + bGuiMode = FALSE; + + if (CmdVolumePassword.Length == 0) + AbortProcess ("ERR_PASSWORD_MISSING"); + + if (CmdVolumeFileSize == 0) + AbortProcess ("ERR_SIZE_MISSING"); + + CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &bDevice); + + if (bDevice) + AbortProcess ("ERR_DEVICE_CLI_CREATE_NOT_SUPPORTED"); + + volumePassword = CmdVolumePassword; + volumePim = CmdVolumePim; + + if (CmdVolumeEA > 0) + nVolumeEA = CmdVolumeEA; + + if (CmdVolumePkcs5 > 0) + hash_algo = CmdVolumePkcs5; + + if (CmdVolumeFilesystem > 0) + fileSystem = CmdVolumeFilesystem; + else + fileSystem = FILESYS_NTFS; + + nVolumeSize = CmdVolumeFileSize; + + // correct volume size to be multiple of sector size + if (bDevice && !(bHiddenVol && !bHiddenVolHost)) // If raw device but not a hidden volume + { + // do nothing. no correction is needed + } + else + { + unsigned __int64 sectorSize = (unsigned __int64) GetFormatSectorSize(); + unsigned __int64 sectorSizeRem = nVolumeSize % sectorSize; + + if (sectorSizeRem != 0) + nVolumeSize = nVolumeSize + (sectorSize - sectorSizeRem); + } + + if (nVolumeSize < (bHiddenVolHost ? TC_MIN_HIDDEN_VOLUME_HOST_SIZE : (bHiddenVol ? TC_MIN_HIDDEN_VOLUME_SIZE : TC_MIN_VOLUME_SIZE))) + AbortProcess ("ERR_VOLUME_SIZE_TOO_SMALL"); + + if ( ((!bHiddenVolHost && bHiddenVol) && (nVolumeSize > nMaximumHiddenVolSize)) + || (nVolumeSize > (bHiddenVolHost ? TC_MAX_HIDDEN_VOLUME_HOST_SIZE : TC_MAX_VOLUME_SIZE)) + ) + { + AbortProcess ("ERR_VOLUME_SIZE_TOO_BIG"); + } + + if (!GetVolumePathName (szFileName, root, array_capacity (root))) + { + handleWin32Error (hwndDlg, SRC_POS); + exit (1); + } + + if (CmdSparseFileSwitch) + { + /* Check if the host file system supports sparse files */ + GetVolumeInformation (root, NULL, 0, NULL, NULL, &fileSystemFlags, NULL, 0); + bSparseFileSwitch = fileSystemFlags & FILE_SUPPORTS_SPARSE_FILES; + + if (!bSparseFileSwitch) + { + AbortProcess ("ERR_DYNAMIC_NOT_SUPPORTED"); + } + } + + quickFormat = TRUE; + + if (!GetDiskFreeSpaceEx (root, &free, 0, 0)) + { + wchar_t szTmp[1024]; + + if (translateWin32Error (szTmp, sizeof (szTmp) / sizeof(szTmp[0]))) + { + wchar_t szTmp2[1024]; + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s\n%s", GetString ("CANNOT_CALC_SPACE"), szTmp); + AbortProcessDirect (szTmp2); + } + else + { + handleWin32Error (hwndDlg, SRC_POS); + } + + exit (1); + } + else + { + if (!bSparseFileSwitch && (nVolumeSize > free.QuadPart)) + { + AbortProcess ("ERR_CONTAINER_SIZE_TOO_BIG"); + } + } + + dataAreaSize = GetVolumeDataAreaSize (bHiddenVol && !bHiddenVolHost, nVolumeSize); + + if ( (fileSystem == FILESYS_NTFS) && + (dataAreaSize < TC_MIN_NTFS_FS_SIZE || dataAreaSize > TC_MAX_NTFS_FS_SIZE) + ) + { + AbortProcess ("ERR_NTFS_INVALID_VOLUME_SIZE"); + } + + if ( (fileSystem == FILESYS_EXFAT) && + (dataAreaSize < TC_MIN_EXFAT_FS_SIZE || dataAreaSize > TC_MAX_EXFAT_FS_SIZE) + ) + { + AbortProcess ("ERR_EXFAT_INVALID_VOLUME_SIZE"); + } + + if ( (fileSystem == FILESYS_FAT) && + (dataAreaSize < TC_MIN_FAT_FS_SIZE || dataAreaSize > (TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize())) + ) + { + AbortProcess ("ERR_FAT_INVALID_VOLUME_SIZE"); + } + + /* Verify that the volume would not be too large for the host file system */ + if (GetVolumePathName (szDiskFile, root, ARRAYSIZE (root)) + && GetVolumeInformation (root, NULL, 0, NULL, NULL, NULL, szFileSystemNameBuffer, ARRAYSIZE(szFileSystemNameBuffer)) + && !wcsncmp (szFileSystemNameBuffer, L"FAT32", 5)) + { + // The host file system is FAT32 + if (nVolumeSize >= 4 * BYTES_PER_GB) + { + AbortProcess ("VOLUME_TOO_LARGE_FOR_FAT32"); + } + } + + /* Verify that the volume would not be too large for the operating system */ + if (!IsOSAtLeast (WIN_VISTA) + && nVolumeSize > 2 * BYTES_PER_TB) + { + AbortProcess ("VOLUME_TOO_LARGE_FOR_WINXP"); + } + + if (volumePassword.Length > 0) + { + // Check password length (check also done for outer volume which is not the case in TrueCrypt). + if (!CheckPasswordLength (NULL, volumePassword.Length, volumePim, FALSE, Silent, Silent)) + { + exit (1); + } + } + + volTransformThreadFunction (hwndDlg); + + exit (bOperationSuccess? 0 : 1); + } + + SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, 0, szRescueDiskISO); + StringCbCatW (szRescueDiskISO, sizeof(szRescueDiskISO), L"\\VeraCrypt Rescue Disk.iso"); + + if (IsOSAtLeast (WIN_VISTA)) + { + // Availability of in-place encryption (which is pre-selected by default whenever + // possible) makes partition-hosted volume creation safer. + bWarnDeviceFormatAdvanced = FALSE; + } + +#ifdef _DEBUG + // For faster testing + strcpy (szVerify, "q"); + strcpy (szRawPassword, "q"); +#endif + + PostMessage (hwndDlg, TC_APPMSG_PERFORM_POST_WMINIT_TASKS, 0, 0); + } + return 0; + + case WM_SYSCOMMAND: + if (lw == IDC_ABOUT) + { + DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_ABOUT_DLG), hwndDlg, (DLGPROC) AboutDlgProc); + return 1; + } + return 0; + + case WM_TIMER: + + switch (wParam) + { + case TIMER_ID_RANDVIEW: + + if (WizardMode == WIZARD_MODE_SYS_DEVICE + || bInPlaceEncNonSys) + { + DisplayRandPool (hwndDlg, hRandPoolSys, showKeys); + } + else + { + int partialLen = 16; + wchar_t tmp2[43]; + int i; + DWORD mouseEventsCounter; + + RandpeekBytes (hwndDlg, randPool, partialLen, &mouseEventsCounter); + + ProcessEntropyEstimate (hEntropyBar, &mouseEventsInitialCount, mouseEventsCounter, maxEntropyLevel, &mouseEntropyGathered); + + tmp2[0] = 0; + + for (i = 0; i < partialLen; i++) + { + wchar_t tmp3[3]; + if (showKeys) + { + StringCbPrintfW (tmp3, sizeof(tmp3), L"%02X", (int) randPool[i]); + } + else if (bUseMask) + { + unsigned char tmpByte = randPool[i] ^ maskRandPool[i]; + tmp3[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); + tmp3[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); + tmp3[2] = 0; + } + else + StringCbCopyW (tmp3, sizeof (tmp3), L"**"); + StringCbCatW (tmp2, sizeof(tmp2), tmp3); + } + + tmp2[32] = 0; + + SetWindowTextW (GetDlgItem (hCurPage, IDC_RANDOM_BYTES), (wstring (tmp2) + GetString ("TRIPLE_DOT_GLYPH_ELLIPSIS")).c_str()); + + burn (randPool, partialLen); + burn (tmp2, sizeof(tmp2)); + } + return 1; + + case TIMER_ID_SYSENC_PROGRESS: + { + // Manage system encryption/decryption and update related GUI + + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + KillTimer (MainDlg, TIMER_ID_SYSENC_PROGRESS); + + try + { + BootEncObj->AbortSetup (); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + + e.Show (hwndDlg); + Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", MainDlg); + EndMainDlg (MainDlg); + return 1; + } + + if (BootEncStatus.SetupInProgress) + UpdateSysEncProgressBar (); + + if (bSystemEncryptionInProgress != BootEncStatus.SetupInProgress) + { + bSystemEncryptionInProgress = BootEncStatus.SetupInProgress; + + UpdateSysEncProgressBar (); + UpdateSysEncControls (); + + if (!bSystemEncryptionInProgress) + { + // The driver stopped encrypting/decrypting + + // Allow the OS to enter Sleep mode when idle + SetThreadExecutionState (ES_CONTINUOUS); + + KillTimer (hwndDlg, TIMER_ID_SYSENC_PROGRESS); + + UpdateLastDialogId (); + + try + { + if (BootEncStatus.DriveMounted) // If we had been really encrypting/decrypting (not just proceeding to deinstall) + BootEncObj->CheckEncryptionSetupResult(); + } + catch (SystemException &e) + { + if (!bTryToCorrectReadErrors + && SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING + && (IsDiskReadError (e.ErrorCode))) + { + bTryToCorrectReadErrors = (AskWarnYesNo ("ENABLE_BAD_SECTOR_ZEROING", MainDlg) == IDYES); + + if (bTryToCorrectReadErrors) + { + SysEncResume(); + return 1; + } + } + else if (!DiscardUnreadableEncryptedSectors + && SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING + && (IsDiskReadError (e.ErrorCode))) + { + DiscardUnreadableEncryptedSectors = (AskWarnYesNo ("DISCARD_UNREADABLE_ENCRYPTED_SECTORS", MainDlg) == IDYES); + + if (DiscardUnreadableEncryptedSectors) + { + SysEncResume(); + return 1; + } + } + + e.Show (hwndDlg); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + + switch (SystemEncryptionStatus) + { + case SYSENC_STATUS_ENCRYPTING: + + if (BootEncStatus.ConfiguredEncryptedAreaStart == BootEncStatus.EncryptedAreaStart + && BootEncStatus.ConfiguredEncryptedAreaEnd == BootEncStatus.EncryptedAreaEnd) + { + // The partition/drive has been fully encrypted + + ManageStartupSeqWiz (TRUE, L""); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_NEXT), GetString ("FINALIZE")); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE); + EnableWindow (GetDlgItem (hCurPage, IDC_WIPE_MODE), FALSE); + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), FALSE); + + WipeHiddenOSCreationConfig(); // For extra conservative security + + ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); + + Info ("SYSTEM_ENCRYPTION_FINISHED", MainDlg); + return 1; + } + break; + + case SYSENC_STATUS_DECRYPTING: + + if (!BootEncStatus.DriveEncrypted) + { + // The partition/drive has been fully decrypted + + try + { + // Finalize the process + BootEncObj->Deinstall (); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + + ManageStartupSeqWiz (TRUE, L""); + ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_NEXT), GetString ("FINALIZE")); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE); + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), FALSE); + + Info ("SYSTEM_DECRYPTION_FINISHED", MainDlg); + + // Reboot is required to enable uninstallation and hibernation + if (AskWarnYesNo ("CONFIRM_RESTART", MainDlg) == IDYES) + { + EndMainDlg (MainDlg); + + try + { + BootEncObj->RestartComputer(); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + } + + return 1; + } + break; + } + } + } + } + return 1; + + case TIMER_ID_NONSYS_INPLACE_ENC_PROGRESS: + + if (bInPlaceEncNonSys) + { + // Non-system in-place encryption + + if (!bVolTransformThreadRunning && !bVolTransformThreadToRun) + { + KillTimer (hwndDlg, TIMER_ID_NONSYS_INPLACE_ENC_PROGRESS); + + UpdateLastDialogId (); + } + + UpdateNonSysInPlaceEncControls (); + } + return 1; + + case TIMER_ID_KEYB_LAYOUT_GUARD: + if (SysEncInEffect ()) + { + DWORD keybLayout = (DWORD) GetKeyboardLayout (NULL); + + /* Watch the keyboard layout */ + + if (keybLayout != 0x00000409 && keybLayout != 0x04090409) + { + // Keyboard layout is not standard US + + WipePasswordsAndKeyfiles (); + + SetPassword (hCurPage, IDC_PASSWORD, szRawPassword); + SetPassword (hCurPage, IDC_VERIFY, szVerify); + + keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); + + if (keybLayout != 0x00000409 && keybLayout != 0x04090409) + { + KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); + Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", MainDlg); + EndMainDlg (MainDlg); + return 1; + } + + bKeyboardLayoutChanged = TRUE; + + wchar_t szTmp [4096]; + StringCbCopyW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_CHANGE_PREVENTED")); + StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); + StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION")); + MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); + } + + /* Watch the right Alt key (which is used to enter various characters on non-US keyboards) */ + + if (bKeyboardLayoutChanged && !bKeybLayoutAltKeyWarningShown) + { + if (GetAsyncKeyState (VK_RMENU) < 0) + { + bKeybLayoutAltKeyWarningShown = TRUE; + + wchar_t szTmp [4096]; + StringCbCopyW (szTmp, sizeof(szTmp), GetString ("ALT_KEY_CHARS_NOT_FOR_SYS_ENCRYPTION")); + StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); + StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION")); + MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TOPMOST); + } + } + } + return 1; + + case TIMER_ID_SYSENC_DRIVE_ANALYSIS_PROGRESS: + + if (bSysEncDriveAnalysisInProgress) + { + UpdateProgressBarProc (GetTickCount() - SysEncDriveAnalysisStart); + + if (GetTickCount() - SysEncDriveAnalysisStart > SYSENC_DRIVE_ANALYSIS_ETA) + { + // It's taking longer than expected -- reinit the progress bar + SysEncDriveAnalysisStart = GetTickCount (); + InitProgressBar (SYSENC_DRIVE_ANALYSIS_ETA, 0, FALSE, FALSE, FALSE, TRUE); + } + + ArrowWaitCursor (); + } + else + { + KillTimer (hwndDlg, TIMER_ID_SYSENC_DRIVE_ANALYSIS_PROGRESS); + UpdateProgressBarProc (SYSENC_DRIVE_ANALYSIS_ETA); + Sleep (1500); // User-friendly GUI + + if (bSysEncDriveAnalysisTimeOutOccurred) + Warning ("SYS_DRIVE_SIZE_PROBE_TIMEOUT", MainDlg); + + LoadPage (hwndDlg, SYSENC_DRIVE_ANALYSIS_PAGE + 1); + } + return 1; + + case TIMER_ID_WIPE_PROGRESS: + + // Manage device wipe and update related GUI + + if (bHiddenOS && IsHiddenOSRunning()) + { + // Decoy system partition wipe + + DecoySystemWipeStatus decoySysPartitionWipeStatus; + + try + { + decoySysPartitionWipeStatus = BootEncObj->GetDecoyOSWipeStatus(); + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + KillTimer (MainDlg, TIMER_ID_WIPE_PROGRESS); + + try + { + BootEncObj->AbortDecoyOSWipe (); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + + e.Show (hwndDlg); + EndMainDlg (MainDlg); + return 1; + } + + if (decoySysPartitionWipeStatus.WipeInProgress) + { + ArrowWaitCursor (); + + UpdateWipeProgressBar (); + } + + if (bDeviceWipeInProgress != decoySysPartitionWipeStatus.WipeInProgress) + { + bDeviceWipeInProgress = decoySysPartitionWipeStatus.WipeInProgress; + + UpdateWipeProgressBar (); + UpdateWipeControls (); + + if (!bDeviceWipeInProgress) + { + // The driver stopped wiping + + KillTimer (hwndDlg, TIMER_ID_WIPE_PROGRESS); + UpdateLastDialogId (); + + try + { + BootEncObj->CheckDecoyOSWipeResult(); + } + catch (Exception &e) + { + e.Show (hwndDlg); + AbortProcessSilent(); + } + + if (BootEncStatus.ConfiguredEncryptedAreaEnd == decoySysPartitionWipeStatus.WipedAreaEnd) + { + // Decoy system partition has been fully wiped + + ChangeHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_WIPED); + + SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("EXIT")); + EnableWindow (GetDlgItem (MainDlg, IDCANCEL), TRUE); + EnableWindow (GetDlgItem (MainDlg, IDC_PREV), FALSE); + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), FALSE); + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), FALSE); + + Info ("WIPE_FINISHED_DECOY_SYSTEM_PARTITION", MainDlg); + + TextInfoDialogBox (TC_TBXID_DECOY_OS_INSTRUCTIONS); + + if (BootEncObj->GetSystemDriveConfiguration().ExtraBootPartitionPresent) + Warning ("DECOY_OS_VERSION_WARNING", MainDlg); + + return 1; + } + } + } + } + else + { + // Regular device wipe (not decoy system partition wipe) + + //Info ("WIPE_FINISHED"); + } + return 1; + } + + return 0; + + + case TC_APPMSG_PERFORM_POST_WMINIT_TASKS: + + AfterWMInitTasks (hwndDlg); + return 1; + + case TC_APPMSG_FORMAT_FINISHED: + { + wchar_t tmp[RNG_POOL_SIZE*2+1]; + + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDHELP), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), TRUE); + SetFocus (GetDlgItem (hwndDlg, IDC_NEXT)); + + if (nCurPageNo == FORMAT_PAGE) + KillTimer (hwndDlg, TIMER_ID_RANDVIEW); + + // Attempt to wipe the GUI fields showing portions of randpool, of the master and header keys + wmemset (tmp, 'X', ARRAYSIZE(tmp)); + tmp [ARRAYSIZE(tmp)-1] = 0; + SetWindowText (hRandPool, tmp); + SetWindowText (hMasterKey, tmp); + SetWindowText (hHeaderKey, tmp); + + LoadPage (hwndDlg, FORMAT_FINISHED_PAGE); + } + return 1; + + case TC_APPMSG_NONSYS_INPLACE_ENC_FINISHED: + + // A partition has just been fully encrypted in place + + KillTimer (hwndDlg, TIMER_ID_NONSYS_INPLACE_ENC_PROGRESS); + + if (bInPlaceDecNonSys) + { + // Decryption of non-system volume finished and free drive letters are available. Check if a drive letter is assigned to the decrypted volume. + + WCHAR deviceName[MAX_PATH + 1]; + + StringCbCopyW (deviceName, sizeof(deviceName), szDiskFile); + + if (GetDiskDeviceDriveLetter (deviceName) < 0) + { + // No drive letter is assigned to the device + MessageBeep (MB_OK); + LoadPage (hwndDlg, NONSYS_INPLACE_DEC_TRANSFORM_FINISHED_DRIVE_LETTER_PAGE); + return 1; + } + else + { + Info ("NONSYS_INPLACE_DEC_FINISHED_INFO", hwndDlg); + } + } + + LoadPage (hwndDlg, NONSYS_INPLACE_ENC_TRANSFORM_FINISHED_PAGE); + return 1; + + case TC_APPMSG_VOL_TRANSFORM_THREAD_ENDED: + + if (bInPlaceEncNonSys) + { + // In-place encryption was interrupted/paused (did not finish) + + KillTimer (hwndDlg, TIMER_ID_NONSYS_INPLACE_ENC_PROGRESS); + + UpdateNonSysInPlaceEncControls (); + } + else + { + // Format has been aborted (did not finish) + + EnableWindow (GetDlgItem (hCurPage, IDC_QUICKFORMAT), (bDevice || bSparseFileSwitch) && !(bHiddenVol && !bHiddenVolHost)); + EnableWindow (GetDlgItem (hCurPage, IDC_FILESYS), TRUE); + EnableWindow (GetDlgItem (hCurPage, IDC_CLUSTERSIZE), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDHELP), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), TRUE); + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), TRUE); + SendMessage (GetDlgItem (hCurPage, IDC_PROGRESS_BAR), PBM_SETPOS, 0, 0L); + SetFocus (GetDlgItem (hwndDlg, IDC_NEXT)); + } + + NormalCursor (); + return 1; + + case WM_HELP: + + OpenPageHelp (hwndDlg, nCurPageNo); + return 1; + + case TC_APPMSG_FORMAT_USER_QUIT: + + if (nCurPageNo == NONSYS_INPLACE_ENC_TRANSFORM_PAGE + && (bVolTransformThreadRunning || bVolTransformThreadToRun || bInPlaceEncNonSysResumed)) + { + // Non-system encryption in progress + if (AskNoYes ("NONSYS_INPLACE_ENC_DEFER_CONFIRM", hwndDlg) == IDYES) + { + NonSysInplaceEncPause (); + + EndMainDlg (hwndDlg); + return 1; + } + else + return 1; // Disallow close + } + else if (bVolTransformThreadRunning || bVolTransformThreadToRun) + { + // Format (non-in-place encryption) in progress + if (AskNoYes ("FORMAT_ABORT", hwndDlg) == IDYES) + { + bVolTransformThreadCancel = TRUE; + + EndMainDlg (hwndDlg); + return 1; + } + else + return 1; // Disallow close + } + else if ((nCurPageNo == SYSENC_ENCRYPTION_PAGE || nCurPageNo == SYSENC_PRETEST_RESULT_PAGE) + && SystemEncryptionStatus != SYSENC_STATUS_NONE + && InstanceHasSysEncMutex ()) + { + // System encryption/decryption in progress + + if (AskYesNo (SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING ? + "SYSTEM_DECRYPTION_DEFER_CONFIRM" : "SYSTEM_ENCRYPTION_DEFER_CONFIRM", MainDlg) == IDYES) + { + if (nCurPageNo == SYSENC_PRETEST_RESULT_PAGE) + TextInfoDialogBox (TC_TBXID_SYS_ENC_RESCUE_DISK); + + try + { + BootEncStatus = BootEncObj->GetStatus(); + + if (BootEncStatus.SetupInProgress) + { + BootEncObj->AbortSetupWait (); + Sleep (200); + BootEncStatus = BootEncObj->GetStatus(); + } + + if (!BootEncStatus.SetupInProgress) + { + EndMainDlg (MainDlg); + return 1; + } + else + { + Error ("FAILED_TO_INTERRUPT_SYSTEM_ENCRYPTION", MainDlg); + return 1; // Disallow close + } + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + return 1; // Disallow close + } + else + return 1; // Disallow close + } + else if (bConfirmQuitSysEncPretest) + { + if (AskWarnNoYes (bHiddenOS ? "CONFIRM_CANCEL_HIDDEN_OS_CREATION" : "CONFIRM_CANCEL_SYS_ENC_PRETEST", MainDlg) == IDNO) + return 1; // Disallow close + } + else if (bConfirmQuit) + { + if (AskWarnNoYes ("CONFIRM_EXIT_UNIVERSAL", MainDlg) == IDNO) + return 1; // Disallow close + } + + if (hiddenVolHostDriveNo > -1) + { + CloseVolumeExplorerWindows (hwndDlg, hiddenVolHostDriveNo); + UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE); + } + + EndMainDlg (hwndDlg); + return 1; + + + case WM_COMMAND: + + if (lw == IDHELP) + { + OpenPageHelp (hwndDlg, nCurPageNo); + return 1; + } + else if (lw == IDCANCEL) + { + PostMessage (hwndDlg, TC_APPMSG_FORMAT_USER_QUIT, 0, 0); + return 1; + } + else if (lw == IDC_NEXT) + { + if (nCurPageNo == INTRO_PAGE) + { + switch (GetSelectedWizardMode (hCurPage)) + { + case WIZARD_MODE_FILE_CONTAINER: + + if (CurrentOSMajor >= 6 && IsUacSupported() && IsAdmin() && !IsBuiltInAdmin() && !IsNonInstallMode()) + { + static bool warningConfirmed = false; + if (!warningConfirmed) + { + if (AskWarnYesNo ("CONTAINER_ADMIN_WARNING", MainDlg) == IDYES) + exit (0); + + warningConfirmed = true; + } + } + + WaitCursor (); + CloseSysEncMutex (); + ChangeWizardMode (WIZARD_MODE_FILE_CONTAINER); + bHiddenOS = FALSE; + bInPlaceEncNonSys = FALSE; + nNewPageNo = VOLUME_TYPE_PAGE - 1; // Skip irrelevant pages + break; + + case WIZARD_MODE_NONSYS_DEVICE: + + WaitCursor (); + CloseSysEncMutex (); + + if (!ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE)) + { + NormalCursor (); + return 1; + } + + bHiddenOS = FALSE; + nNewPageNo = VOLUME_TYPE_PAGE - 1; // Skip irrelevant pages + break; + + case WIZARD_MODE_SYS_DEVICE: + + WaitCursor (); + bHiddenVol = FALSE; + bInPlaceEncNonSys = FALSE; + SwitchWizardToSysEncMode (); + return 1; + } + } + else if (nCurPageNo == SYSENC_TYPE_PAGE) + { + if (bHiddenOS) + { + bWholeSysDrive = FALSE; + bHiddenVolDirect = FALSE; + } + + if (!bHiddenOS) + nNewPageNo = SYSENC_SPAN_PAGE - 1; // Skip irrelevant pages + } + else if (nCurPageNo == SYSENC_HIDDEN_OS_REQ_CHECK_PAGE) + { + WaitCursor (); + try + { + BootEncObj->CheckRequirementsHiddenOS (); + + if (CheckGapBetweenSysAndHiddenOS ()) + Warning ("GAP_BETWEEN_SYS_AND_HIDDEN_OS_PARTITION", MainDlg); + } + catch (Exception &e) + { + e.Show (hwndDlg); + NormalCursor (); + return 1; + } + + if (AskWarnYesNo ("DECOY_OS_REINSTALL_WARNING", MainDlg) == IDNO) + { + NormalCursor (); + return 1; + } + + WarningDirect ((wstring (GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO")) + + L"\n\n" + + GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION")).c_str(), MainDlg); + + if (!IsAdmin() && IsUacSupported()) + { + // If UAC elevation is needed, we need to elevate the complete wizard process here, because + // we will need to switch to the non-sys-device mode, which requires the whole wizard process + // to have admin rights. + + CloseSysEncMutex (); + + if (!ElevateWholeWizardProcess (L"/r")) + { + // Failed to obtain admin rights + + NormalCursor (); + + if (!CreateSysEncMutex ()) + AbortProcess ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE"); + + return 1; + } + } + + // This check requires admin rights + try + { + BootEncObj->InitialSecurityChecksForHiddenOS (); + } + catch (Exception &e) + { + e.Show (hwndDlg); + EndMainDlg (MainDlg); // Some of the checks need the wizard to be restarted (results are cached until exit and the checks would fail even if the issues were rectified). + return 1; + } + + nNewPageNo = SYSENC_MULTI_BOOT_MODE_PAGE - 1; // Skip irrelevant pages + } + else if (nCurPageNo == SYSENC_SPAN_PAGE) + { + try + { + if (bWholeSysDrive && !BootEncObj->SystemPartitionCoversWholeDrive()) + { + if (BootEncObj->SystemDriveContainsNonStandardPartitions()) + { + if (AskWarnYesNoString ((wstring (GetString ("SYSDRIVE_NON_STANDARD_PARTITIONS")) + L"\n\n" + GetString ("ASK_ENCRYPT_PARTITION_INSTEAD_OF_DRIVE")).c_str(), MainDlg) == IDYES) + bWholeSysDrive = FALSE; + } + + if (!IsOSAtLeast (WIN_VISTA) && bWholeSysDrive) + { + if (BootEncObj->SystemDriveContainsExtendedPartition()) + { + Error ("WDE_UNSUPPORTED_FOR_EXTENDED_PARTITIONS", MainDlg); + + if (AskYesNo ("ASK_ENCRYPT_PARTITION_INSTEAD_OF_DRIVE", MainDlg) == IDNO) + return 1; + + bWholeSysDrive = FALSE; + } + else + Warning ("WDE_EXTENDED_PARTITIONS_WARNING", hwndDlg); + } + } + + if (!bWholeSysDrive && BootEncObj->SystemPartitionCoversWholeDrive()) + bWholeSysDrive = (AskYesNo ("WHOLE_SYC_DEVICE_RECOM", hwndDlg) == IDYES); + } + catch (Exception &e) + { + e.Show (hwndDlg); + NormalCursor (); + return 1; + } + + if (!bWholeSysDrive) + nNewPageNo = SYSENC_MULTI_BOOT_MODE_PAGE - 1; // Skip irrelevant pages + } + else if (nCurPageNo == SYSENC_PRE_DRIVE_ANALYSIS_PAGE) + { + if ((SysEncDetectHiddenSectors = Get2RadButtonPageAnswer()) != 1) + { + // Skip drive analysis + nNewPageNo = SYSENC_DRIVE_ANALYSIS_PAGE; + + // If the user had already searched for hidden sectors, we must clear (invalidate) the + // result because now he changed his mind and no longer wishes to encrypt the hidden sectors. + try + { + BootEncObj->InvalidateCachedSysDriveProperties (); + } + catch (Exception &e) + { + e.Show (MainDlg); + EndMainDlg (MainDlg); + exit(0); + } + } + } + else if (nCurPageNo == SYSENC_MULTI_BOOT_MODE_PAGE) + { + if (nMultiBoot > 1) + { + // Multi-boot + + if (AskWarnNoYes ("MULTI_BOOT_FOR_ADVANCED_ONLY", hwndDlg) == IDNO) + return 1; + + if (bHiddenOS) + { + if (AskWarnNoYes ("HIDDEN_OS_MULTI_BOOT", hwndDlg) == IDNO) + { + Error ("UNSUPPORTED_HIDDEN_OS_MULTI_BOOT_CFG", hwndDlg); + return 1; + } + } + } + + if (bHiddenOS) + { + if (IsOSAtLeast (WIN_7) + && BootEncObj->GetSystemDriveConfiguration().ExtraBootPartitionPresent + && AskWarnYesNo ("CONFIRM_HIDDEN_OS_EXTRA_BOOT_PARTITION", hwndDlg) == IDNO) + { + TextInfoDialogBox (TC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS); + NormalCursor (); + return 1; + } + + if (AskWarnYesNo ("DECOY_OS_REQUIREMENTS", hwndDlg) == IDNO) + { + NormalCursor (); + return 1; + } + + if (!ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE)) + { + NormalCursor (); + return 1; + } + + // Skip irrelevant pages + nNewPageNo = HIDDEN_VOL_HOST_PRE_CIPHER_PAGE - 1; + } + else if (nMultiBoot <= 1) + { + // Single-boot (not creating a hidden OS) + + // Skip irrelevant pages + nNewPageNo = CIPHER_PAGE - 1; + } + } + else if (nCurPageNo == SYSENC_MULTI_BOOT_SYS_EQ_BOOT_PAGE) + { + SysEncMultiBootCfg.SystemOnBootDrive = Get2RadButtonPageAnswer (); + + if (!SysEncMultiBootCfg.SystemOnBootDrive) + { + Error ("SYS_PARTITION_MUST_BE_ON_BOOT_DRIVE", hwndDlg); + EndMainDlg (MainDlg); + return 1; + } + } + else if (nCurPageNo == SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE) + { + if (Get2RadButtonPageAnswer () == 0) + { + // 2 or more drives contain an OS + + SysEncMultiBootCfg.NumberOfSysDrives = 2; + } + else if (Get2RadButtonPageAnswer () == 1) + { + // Only 1 drive contains an OS + + SysEncMultiBootCfg.NumberOfSysDrives = 1; + + if (bWholeSysDrive) + { + // Whole-system-drive encryption is currently not supported if the drive contains + // more than one system + Error ("WDE_UNSUPPORTED_FOR_MULTIPLE_SYSTEMS_ON_ONE_DRIVE", hwndDlg); + return 1; + } + + // Ask whether there is a non-Windows boot loader in the MBR + nNewPageNo = SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE - 1; + } + } + else if (nCurPageNo == SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE) + { + SysEncMultiBootCfg.MultipleSystemsOnDrive = Get2RadButtonPageAnswer (); + + if (SysEncMultiBootCfg.MultipleSystemsOnDrive && bWholeSysDrive) + { + // Whole-system-drive encryption is currently not supported if the drive contains + // more than one system + Error ("WDE_UNSUPPORTED_FOR_MULTIPLE_SYSTEMS_ON_ONE_DRIVE", hwndDlg); + return 1; + } + } + + else if (nCurPageNo == SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE) + { + SysEncMultiBootCfg.BootLoaderBrand = Get2RadButtonPageAnswer (); + + if (SysEncMultiBootCfg.BootLoaderBrand) + { + // A non-Windows boot manager in the MBR + Error ("CUSTOM_BOOT_MANAGERS_IN_MBR_UNSUPPORTED", hwndDlg); + EndMainDlg (MainDlg); + return 1; + } + else + { + // Either a standard Windows boot manager or no boot manager + wcscpy_s (SysEncMultiBootCfgOutcome, sizeof(SysEncMultiBootCfgOutcome) / 2, GetString ("WINDOWS_BOOT_LOADER_HINTS")); + } + } + + else if (nCurPageNo == SYSENC_MULTI_BOOT_OUTCOME_PAGE) + { + if (bHiddenOS) + { + if (!ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE)) + { + NormalCursor (); + return 1; + } + + nNewPageNo = HIDDEN_VOL_HOST_PRE_CIPHER_PAGE - 1; // Skip irrelevant pages + } + else + nNewPageNo = CIPHER_PAGE - 1; // Skip irrelevant pages + } + + else if (nCurPageNo == VOLUME_TYPE_PAGE) + { + if (IsButtonChecked (GetDlgItem (hCurPage, IDC_HIDDEN_VOL))) + { + if (!IsAdmin() && !IsUacSupported () + && IDNO == MessageBoxW (hwndDlg, GetString ("ADMIN_PRIVILEGES_WARN_HIDVOL"), + lpszTitle, MB_ICONWARNING|MB_YESNO|MB_DEFBUTTON2)) + { + return 1; + } + else + { + bHiddenVol = TRUE; + bHiddenVolHost = TRUE; + bInPlaceEncNonSys = FALSE; + } + } + else + { + bHiddenVol = FALSE; + bHiddenVolHost = FALSE; + bHiddenVolDirect = FALSE; + nNewPageNo = VOLUME_LOCATION_PAGE - 1; // Skip the hidden volume creation wizard mode selection + } + } + + else if (nCurPageNo == HIDDEN_VOL_WIZARD_MODE_PAGE) + { + if (IsButtonChecked (GetDlgItem (hCurPage, IDC_HIDVOL_WIZ_MODE_DIRECT))) + bHiddenVolDirect = TRUE; + else + { + if (IsHiddenOSRunning()) + { + WarningDirect ((wstring (GetString ("HIDDEN_VOL_CREATION_UNDER_HIDDEN_OS_HOWTO")) + + L"\n\n" + + GetString ("NOTE_BEGINNING") + + GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO") + + L" " + + GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION")).c_str(), hwndDlg); + NormalCursor (); + return 1; + } + + bHiddenVolDirect = FALSE; + } + } + + else if (nCurPageNo == VOLUME_LOCATION_PAGE) + { + BOOL tmpbDevice; + + WaitCursor(); + + GetWindowTextW (GetDlgItem (hCurPage, IDC_COMBO_BOX), szFileName, ARRAYSIZE (szFileName)); + RelativePath2Absolute (szFileName); + CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice); + + if (tmpbDevice != bDevice) + { + if (bDevice) + { + // Not a valid device path + Error ("CANNOT_CALC_SPACE", hwndDlg); + NormalCursor (); + return 1; + } + else + { + if (AskWarnYesNo ("DEVICE_SELECTED_IN_NON_DEVICE_MODE", hwndDlg) == IDNO) + { + NormalCursor (); + return 1; + } + + SwitchWizardToNonSysDeviceMode (); + NormalCursor (); + return 1; + } + } + + MoveEditToCombo (GetDlgItem (hCurPage, IDC_COMBO_BOX), bHistory); + + if (IsMountedVolume (szDiskFile)) + { + Error ("ALREADY_MOUNTED", hwndDlg); + NormalCursor (); + return 1; + } + + if (bDevice) + { + switch (IsSystemDevicePath (szDiskFile, hCurPage, TRUE)) + { + case 1: + case 2: + case 3: + if (AskYesNo ("CONFIRM_SYSTEM_ENCRYPTION_MODE", hwndDlg) == IDNO) + { + NormalCursor (); + return 1; + } + szFileName[0] = 0; + szDiskFile[0] = 0; + SwitchWizardToSysEncMode (); + NormalCursor (); + return 1; + + case -1: + // In some environments (such as PE), the system volume is not located on a hard drive. + // Therefore, we must interpret this return code as "Not a system device path" (otherwise, + // non-system devices could not be TC-formatted in such environments). Note that this is + // rather safe, because bReliableRequired is set to TRUE. + + // NOP + break; + } + } + else + { + if (CheckFileExtension(szFileName) + && AskWarnNoYes ("EXE_FILE_EXTENSION_CONFIRM", hwndDlg) == IDNO) + { + NormalCursor (); + return 1; + } + } + + bHistory = !IsButtonChecked (GetDlgItem (hCurPage, IDC_NO_HISTORY)); + + SaveSettings (hCurPage); + + if (bHiddenVolDirect && bHiddenVolHost) + { + nNewPageNo = HIDDEN_VOL_HOST_PASSWORD_PAGE - 1; + + if (bDevice) + { + if(!QueryFreeSpace (hwndDlg, GetDlgItem (hwndDlg, IDC_SPACE_LEFT), FALSE)) + { + MessageBoxW (hwndDlg, GetString ("CANT_GET_VOLSIZE"), lpszTitle, ICON_HAND); + NormalCursor (); + return 1; + } + else + nHiddenVolHostSize = nVolumeSize; + } + else + { + if (!GetFileVolSize (hwndDlg, &nHiddenVolHostSize)) + { + NormalCursor (); + return 1; + } + else if (IsSparseFile (hwndDlg)) + { + // Hidden volumes must not be created within sparse file containers + Warning ("HIDDEN_VOL_HOST_SPARSE", hwndDlg); + NormalCursor (); + return 1; + } + } + } + else + { + if (!bHiddenVol && !bDevice) + nNewPageNo = CIPHER_PAGE - 1; + else if (bHiddenVol) + nNewPageNo = (bHiddenVolHost ? HIDDEN_VOL_HOST_PRE_CIPHER_PAGE : HIDDEN_VOL_PRE_CIPHER_PAGE) - 1; + } + } + + else if (nCurPageNo == DEVICE_TRANSFORM_MODE_PAGE) + { + if (bInPlaceEncNonSys) + { + // Check requirements for non-system in-place encryption + + if (!CheckRequirementsForNonSysInPlaceEnc (hwndDlg, szDiskFile, FALSE)) + { + return 1; + } + + // We are going to skip the Size page so we must get the size here + nVolumeSize = GetDeviceSize (szDiskFile); + + if (nVolumeSize == -1) + { + handleWin32Error (MainDlg, SRC_POS); + return 1; + } + + if (AskWarnYesNo ("NONSYS_INPLACE_ENC_CONFIRM_BACKUP", hwndDlg) == IDNO) + return 1; + } + nNewPageNo = CIPHER_PAGE - 1; + } + + else if (nCurPageNo == HIDDEN_VOL_HOST_PRE_CIPHER_PAGE) + { + if (bHiddenVolHost) + nNewPageNo = CIPHER_PAGE - 1; // Skip the info on the hiddem volume + } + + else if (nCurPageNo == CIPHER_PAGE) + { + LPARAM nIndex; + nIndex = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETCURSEL, 0, 0); + nVolumeEA = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETITEMDATA, nIndex, 0); + + if (SysEncInEffect () + && EAGetCipherCount (nVolumeEA) > 1) // Cascade? + { + if (AskWarnNoYes ("CONFIRM_CASCADE_FOR_SYS_ENCRYPTION", hwndDlg) == IDNO) + return 1; + + if (!bHiddenOS) + Info ("NOTE_CASCADE_FOR_SYS_ENCRYPTION", hwndDlg); + } + + nIndex = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX_HASH_ALGO), CB_GETCURSEL, 0, 0); + hash_algo = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX_HASH_ALGO), CB_GETITEMDATA, nIndex, 0); + + RandSetHashFunction (hash_algo); + + if (SysEncInEffect () || bInPlaceEncNonSys) + nNewPageNo = PASSWORD_PAGE - 1; // Skip irrelevant pages + } + + else if (nCurPageNo == SIZE_PAGE) + { + wchar_t szFileSystemNameBuffer[256]; + + VerifySizeAndUpdate (hCurPage, TRUE); + + if (!bDevice) + { + /* Verify that the volume would not be too large for the host file system */ + + wchar_t root[TC_MAX_PATH]; + + if (GetVolumePathName (szDiskFile, root, ARRAYSIZE (root)) + && GetVolumeInformation (root, NULL, 0, NULL, NULL, NULL, szFileSystemNameBuffer, ARRAYSIZE(szFileSystemNameBuffer)) + && !wcsncmp (szFileSystemNameBuffer, L"FAT32", 5)) + { + // The host file system is FAT32 + if (nUIVolumeSize * nMultiplier >= 4 * BYTES_PER_GB) + { + Error ("VOLUME_TOO_LARGE_FOR_FAT32", hwndDlg); + return 1; + } + } + + /* Verify that the volume would not be too large for the operating system */ + + if (!IsOSAtLeast (WIN_VISTA) + && nUIVolumeSize * nMultiplier > 2 * BYTES_PER_TB) + { + Warning ("VOLUME_TOO_LARGE_FOR_WINXP", hwndDlg); + } + } + + if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume + { + /* Ask for confirmation if the hidden volume is too large for the user to be + able to write much more data to the outer volume. */ + + if (((double) nUIVolumeSize / (nMaximumHiddenVolSize / nMultiplier)) > 0.85) // 85% + { + if (AskWarnNoYes ("FREE_SPACE_FOR_WRITING_TO_OUTER_VOLUME", hwndDlg) == IDNO) + return 1; + } + } + + if (!(bHiddenVolDirect && bHiddenVolHost)) + nNewPageNo = PASSWORD_PAGE - 1; + } + + else if (nCurPageNo == PASSWORD_PAGE) + { + VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (MainDlg, IDC_NEXT), + GetDlgItem (hCurPage, IDC_PASSWORD), + GetDlgItem (hCurPage, IDC_VERIFY), + volumePassword.Text, + szVerify, + KeyFilesEnable && FirstKeyFile!=NULL && !SysEncInEffect()); + + volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); + + if (volumePassword.Length > 0) + { + // Password character encoding + if (SysEncInEffect () && !CheckPasswordCharEncoding (GetDlgItem (hCurPage, IDC_PASSWORD), NULL)) + { + Error ("UNSUPPORTED_CHARS_IN_PWD", hwndDlg); + return 1; + } + // Check password length (check also done for outer volume which is not the case in TrueCrypt). + else if (!CheckPasswordLength (hwndDlg, volumePassword.Length, 0, SysEncInEffect(), FALSE, FALSE)) + { + return 1; + } + } + + // Store the password in case we need to restore it after keyfile is applied to it + if (!GetPassword (hCurPage, IDC_PASSWORD, szRawPassword, sizeof (szRawPassword), TRUE)) + return 1; + + if (!SysEncInEffect ()) + { + if (KeyFilesEnable) + { + WaitCursor (); + + if (!KeyFilesApply (hwndDlg, &volumePassword, FirstKeyFile, NULL)) + { + NormalCursor (); + return 1; + } + + NormalCursor (); + } + + } + else + { + KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); + + if (bKeyboardLayoutChanged) + { + // Restore the original keyboard layout + if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) + Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); + else + bKeyboardLayoutChanged = FALSE; + } + + } + + if (!PimEnable) + { + // PIM not activated. Skip PIM page + nNewPageNo = PIM_PAGE; + volumePim = 0; + + if (SysEncInEffect ()) + { + nNewPageNo = SYSENC_COLLECTING_RANDOM_DATA_PAGE - 1; // Skip irrelevant pages + } + + if (bInPlaceEncNonSys) + { + nNewPageNo = NONSYS_INPLACE_ENC_RAND_DATA_PAGE - 1; // Skip irrelevant pages + } + else if (WizardMode != WIZARD_MODE_SYS_DEVICE + && !FileSize4GBLimitQuestionNeeded () + || CreatingHiddenSysVol()) // If we're creating a hidden volume for a hidden OS, we don't need to format it with any filesystem (the entire OS will be copied to the hidden volume sector by sector). + { + nNewPageNo = FORMAT_PAGE - 1; // Skip irrelevant pages + } + + } + } + + else if (nCurPageNo == PIM_PAGE) + { + volumePim = GetPim (hCurPage, IDC_PIM); + + if (!SysEncInEffect() && (volumePim > MAX_PIM_VALUE)) + { + SetFocus (GetDlgItem(hCurPage, IDC_PIM)); + Error ("PIM_TOO_BIG", hwndDlg); + return 1; + } + + if (volumePassword.Length > 0) + { + // Password character encoding + if (SysEncInEffect() && (volumePim > MAX_BOOT_PIM_VALUE)) + { + SetFocus (GetDlgItem(hCurPage, IDC_PIM)); + Error ("PIM_SYSENC_TOO_BIG", hwndDlg); + return 1; + } + // Check password length (check also done for outer volume which is not the case in TrueCrypt). + else if (!CheckPasswordLength (hwndDlg, volumePassword.Length, volumePim, SysEncInEffect(), TRUE, FALSE)) + { + return 1; + } + } + + if (SysEncInEffect ()) + { + + nNewPageNo = SYSENC_COLLECTING_RANDOM_DATA_PAGE - 1; // Skip irrelevant pages + } + + if (bInPlaceEncNonSys) + { + nNewPageNo = NONSYS_INPLACE_ENC_RAND_DATA_PAGE - 1; // Skip irrelevant pages + } + else if (WizardMode != WIZARD_MODE_SYS_DEVICE + && !FileSize4GBLimitQuestionNeeded () + || CreatingHiddenSysVol()) // If we're creating a hidden volume for a hidden OS, we don't need to format it with any filesystem (the entire OS will be copied to the hidden volume sector by sector). + { + nNewPageNo = FORMAT_PAGE - 1; // Skip irrelevant pages + } + } + + else if (nCurPageNo == HIDDEN_VOL_HOST_PASSWORD_PAGE + || nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) + { + WaitCursor (); + + if (!GetPassword (hCurPage, IDC_PASSWORD_DIRECT, (char*) volumePassword.Text, MAX_PASSWORD + 1, TRUE)) + { + NormalCursor (); + return 1; + } + volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); + + hash_algo = (int) SendMessage (GetDlgItem (hCurPage, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hCurPage, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); + + volumePim = GetPim (hCurPage, IDC_PIM); + + // Store the password in case we need to restore it after keyfile is applied to it + if (!GetPassword (hCurPage, IDC_PASSWORD_DIRECT, szRawPassword, sizeof (szRawPassword), TRUE)) + { + NormalCursor (); + return 1; + } + + if (KeyFilesEnable) + { + KeyFilesApply (hwndDlg, &volumePassword, FirstKeyFile, NULL); + } + + if (!bInPlaceEncNonSys) + { + + /* Mount the volume which is to host the new hidden volume as read only */ + + if (hiddenVolHostDriveNo >= 0) // If the hidden volume host is currently mounted (e.g. after previous unsuccessful dismount attempt) + { + BOOL tmp_result; + + // Dismount the hidden volume host (in order to remount it as read-only subsequently) + while (!(tmp_result = UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE))) + { + if (MessageBoxW (hwndDlg, GetString ("CANT_DISMOUNT_OUTER_VOL"), lpszTitle, MB_RETRYCANCEL) != IDRETRY) + { + // Cancel + NormalCursor(); + return 1; + } + } + if (tmp_result) // If dismounted + hiddenVolHostDriveNo = -1; + } + + if (hiddenVolHostDriveNo < 0) // If the hidden volume host is not mounted + { + int retCode; + + // Mount the hidden volume host as read-only (to ensure consistent and secure + // results of the volume bitmap scanning) + switch (MountHiddenVolHost (hwndDlg, szDiskFile, &hiddenVolHostDriveNo, &volumePassword, hash_algo, volumePim, TRUE)) + { + case ERR_NO_FREE_DRIVES: + NormalCursor (); + MessageBoxW (hwndDlg, GetString ("NO_FREE_DRIVE_FOR_OUTER_VOL"), lpszTitle, ICON_HAND); + return 1; + case ERR_VOL_MOUNT_FAILED: + case ERR_PASSWORD_WRONG: + NormalCursor (); + return 1; + case 0: + + /* Hidden volume host successfully mounted as read-only */ + + WaitCursor (); + + // Verify that the outer volume contains a suitable file system, retrieve cluster size, and + // scan the volume bitmap + if (!IsAdmin () && IsUacSupported ()) + retCode = UacAnalyzeHiddenVolumeHost (hwndDlg, &hiddenVolHostDriveNo, GetVolumeDataAreaSize (FALSE, nHiddenVolHostSize), &realClusterSize, &nbrFreeClusters); + else + retCode = AnalyzeHiddenVolumeHost (hwndDlg, &hiddenVolHostDriveNo, GetVolumeDataAreaSize (FALSE, nHiddenVolHostSize), &realClusterSize, &nbrFreeClusters); + + switch (retCode) + { + case -1: // Fatal error + CloseVolumeExplorerWindows (hwndDlg, hiddenVolHostDriveNo); + + if (UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE)) + hiddenVolHostDriveNo = -1; + + AbortProcessSilent (); + break; + + case 0: // Unsupported file system (or other non-fatal error which has already been reported) + if (bHiddenVolDirect) + { + CloseVolumeExplorerWindows (hwndDlg, hiddenVolHostDriveNo); + + if (UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE)) + hiddenVolHostDriveNo = -1; + } + NormalCursor (); + return 1; + + case 1: + + // Determine the maximum possible size of the hidden volume + if (DetermineMaxHiddenVolSize (hwndDlg) < 1) + { + // Non-fatal error while determining maximum possible size of the hidden volume + NormalCursor(); + return 1; + } + else + { + BOOL tmp_result; + + /* Maximum possible size of the hidden volume successfully determined */ + + // Dismount the hidden volume host + while (!(tmp_result = UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE))) + { + if (MessageBoxW (hwndDlg, GetString ("CANT_DISMOUNT_OUTER_VOL"), lpszTitle, MB_RETRYCANCEL) != IDRETRY) + { + // Cancel + NormalCursor(); + return 1; + } + } + + if (tmp_result) // If dismounted + { + hiddenVolHostDriveNo = -1; + + bHiddenVolHost = FALSE; + bHiddenVolFinished = FALSE; + + // Clear the outer volume password + WipePasswordsAndKeyfiles (); + + RestoreDefaultKeyFilesParam (); + + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), TRUE); + NormalCursor (); + + nNewPageNo = HIDDEN_VOL_HOST_PRE_CIPHER_PAGE; + } + } + break; + } + break; + } + } + } + else if (bInPlaceEncNonSysResumed) + { + /* Scan all available partitions to discover all partitions where non-system in-place + encryption/decryption has been interrupted. */ + + BOOL tmpbDevice; + + NormalCursor (); + + ShowWaitDialog (hwndDlg, TRUE, ResumeInPlaceEncWaitThreadProc, NULL); + + WaitCursor(); + + if (DeferredNonSysInPlaceEncDevices.empty()) + { + Warning ("FOUND_NO_PARTITION_W_DEFERRED_INPLACE_ENC", hwndDlg); + + NormalCursor(); + return 1; + } + else if (DeferredNonSysInPlaceEncDevices.size() == 1) + { + CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), DeferredNonSysInPlaceEncDevices.front().Path.c_str(), &tmpbDevice); + + nVolumeSize = GetDeviceSize (szDiskFile); + if (nVolumeSize == -1) + { + handleWin32Error (MainDlg, SRC_POS); + NormalCursor(); + return 1; + } + + nNewPageNo = NONSYS_INPLACE_ENC_TRANSFORM_PAGE - 1; // Skip irrelevant pages + } + + NormalCursor(); + } + else + { + /* Try to mount the non-system volume to decrypt in place (the process has not started yet, we are NOT trying to resume it). + We will try to mount it using the backup header, which we require to work (i.e. be non-damaged) before we start writing + to the volume (the primary header will be overwritten by decrypted data soon after the decryption process begins, so the + backup header will contain the only copy of the master key). */ + + int driveNo = -1; + + // The volume may already be mounted. We need to dismount it first in order to verify the supplied password/keyfile(s) is/are correct. + if (IsMountedVolume (szFileName)) + { + driveNo = GetMountedVolumeDriveNo (szFileName); + + if (driveNo == -1 + || !UnmountVolume (hwndDlg, driveNo, TRUE)) + { + handleWin32Error (MainDlg, SRC_POS); + AbortProcess ("CANT_DISMOUNT_VOLUME"); + } + } + + driveNo = GetLastAvailableDrive (); + + if (driveNo < 0) + AbortProcess ("NO_FREE_DRIVES"); + + MountOptions mountOptions; + ZeroMemory (&mountOptions, sizeof (mountOptions)); + + mountOptions.UseBackupHeader = FALSE; // This must be FALSE at this point because otherwise we wouldn't be able to detect a legacy volume + mountOptions.ReadOnly = TRUE; + mountOptions.Removable = ConfigReadInt ("MountVolumesRemovable", FALSE); + + // Check that it is not a hidden or legacy volume + + if (MountVolume (hwndDlg, driveNo, szFileName, &volumePassword, hash_algo, volumePim, FALSE, FALSE, FALSE, TRUE, &mountOptions, FALSE, TRUE) < 1) + { + NormalCursor(); + return 1; + } + + { + DWORD dwResult; + VOLUME_PROPERTIES_STRUCT volProp; + + memset (&volProp, 0, sizeof(volProp)); + volProp.driveNo = driveNo; + if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &volProp, sizeof (volProp), &volProp, sizeof (volProp), &dwResult, NULL) || dwResult == 0) + { + handleWin32Error (hwndDlg, SRC_POS); + UnmountVolume (hwndDlg, driveNo, TRUE); + AbortProcess ("CANT_GET_VOL_INFO"); + } + + if (volProp.volFormatVersion == TC_VOLUME_FORMAT_VERSION_PRE_6_0) + { + UnmountVolume (hwndDlg, driveNo, TRUE); + AbortProcess ("NONSYS_INPLACE_DECRYPTION_BAD_VOL_FORMAT"); + } + + if (volProp.hiddenVolume) + { + UnmountVolume (hwndDlg, driveNo, TRUE); + AbortProcess ("NONSYS_INPLACE_DECRYPTION_CANT_DECRYPT_HID_VOL"); + } + } + + // Remount the volume using the backup header to verify it is working + + if (!UnmountVolume (hwndDlg, driveNo, TRUE)) + { + handleWin32Error (MainDlg, SRC_POS); + AbortProcess ("CANT_DISMOUNT_VOLUME"); + } + + mountOptions.UseBackupHeader = TRUE; // This must be TRUE at this point (we won't be using the regular header, which will be lost soon after the decryption process starts) + + if (MountVolume (hwndDlg, driveNo, szFileName, &volumePassword, hash_algo, volumePim, FALSE, FALSE, FALSE, TRUE, &mountOptions, FALSE, TRUE) < 1) + { + NormalCursor(); + return 1; + } + + if (!UnmountVolume (hwndDlg, driveNo, TRUE)) + { + handleWin32Error (MainDlg, SRC_POS); + AbortProcess ("CANT_DISMOUNT_VOLUME"); + } + + BOOL tmpbDevice; + + CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice); + + nVolumeSize = GetDeviceSize (szDiskFile); + if (nVolumeSize == -1) + { + handleWin32Error (MainDlg, SRC_POS); + AbortProcessSilent (); + } + + nNewPageNo = NONSYS_INPLACE_ENC_TRANSFORM_PAGE - 1; // Skip irrelevant pages + NormalCursor(); + } + } + + else if (nCurPageNo == FILESYS_PAGE) + { + if (!bHiddenVol && IsHiddenOSRunning() && Get2RadButtonPageAnswer() == 1) + { + // The user wants to store files larger than 4GB on the non-hidden volume about to be created and a hidden OS is running + + WarningDirect ((wstring (GetString ("CANNOT_SATISFY_OVER_4G_FILE_SIZE_REQ")) + + L" " + + GetString ("CANNOT_CREATE_NON_HIDDEN_NTFS_VOLUMES_UNDER_HIDDEN_OS") + + L"\n\n" + + GetString ("NOTE_BEGINNING") + + GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO") + + L" " + + GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION")).c_str(), hwndDlg); + + return 1; + } + + if (nNeedToStoreFilesOver4GB != Get2RadButtonPageAnswer()) + fileSystem = FILESYS_NONE; // The user may have gone back and changed the answer, so default file system must be reselected + + nNeedToStoreFilesOver4GB = Get2RadButtonPageAnswer(); + + nNewPageNo = FORMAT_PAGE - 1; // Skip irrelevant pages + } + + else if (nCurPageNo == SYSENC_COLLECTING_RANDOM_DATA_PAGE + || nCurPageNo == NONSYS_INPLACE_ENC_RAND_DATA_PAGE) + { + wchar_t tmp[RANDPOOL_DISPLAY_SIZE+1]; + + if (!bInPlaceEncNonSys) + { + /* Generate master key and other related data (except the rescue disk) for system encryption. */ + + try + { + WaitCursor(); + BootEncObj->PrepareInstallation (!bWholeSysDrive, volumePassword, nVolumeEA, FIRST_MODE_OF_OPERATION_ID, hash_algo, volumePim, L""); + } + catch (Exception &e) + { + e.Show (hwndDlg); + NormalCursor (); + return 1; + } + } + + KillTimer (hwndDlg, TIMER_ID_RANDVIEW); + + // Attempt to wipe the GUI field showing portions of randpool + wmemset (tmp, L'X', ARRAYSIZE(tmp)); + tmp [ARRAYSIZE(tmp)-1] = 0; + SetWindowText (hRandPoolSys, tmp); + + NormalCursor (); + } + + else if (nCurPageNo == SYSENC_KEYS_GEN_PAGE) + { + wchar_t tmp[KEY_GUI_VIEW_SIZE+1]; + + // Attempt to wipe the GUI fields showing portions of the master and header keys + wmemset (tmp, L'X', ARRAYSIZE(tmp)); + tmp [ARRAYSIZE(tmp)-1] = 0; + SetWindowText (hMasterKey, tmp); + SetWindowText (hHeaderKey, tmp); + } + + else if (nCurPageNo == SYSENC_RESCUE_DISK_CREATION_PAGE) + { + /* Generate rescue disk for boot encryption */ + + GetWindowText (GetDlgItem (hCurPage, IDC_RESCUE_DISK_ISO_PATH), szRescueDiskISO, ARRAYSIZE (szRescueDiskISO)); + + bDontVerifyRescueDisk = GetCheckBox (hCurPage, IDC_SKIP_RESCUE_VERIFICATION); + + try + { + WaitCursor(); + BootEncObj->CreateRescueIsoImage (true, szRescueDiskISO); + + } + catch (Exception &e) + { + e.Show (hwndDlg); + NormalCursor (); + return 1; + } + +retryCDDriveCheck: + if (!bDontVerifyRescueDisk && !BootEncObj->IsCDRecorderPresent()) + { + char *multiChoiceStr[] = { 0, "CD_BURNER_NOT_PRESENT", + "CD_BURNER_NOT_PRESENT_WILL_STORE_ISO", + "CD_BURNER_NOT_PRESENT_WILL_CONNECT_LATER", + "CD_BURNER_NOT_PRESENT_CONNECTED_NOW", + 0 }; + + switch (AskMultiChoice ((void **) multiChoiceStr, FALSE, hwndDlg)) + { + case 1: + wchar_t msg[8192]; + StringCchPrintfW (msg, array_capacity (msg), GetString ("CD_BURNER_NOT_PRESENT_WILL_STORE_ISO_INFO"), szRescueDiskISO); + WarningDirect (msg, hwndDlg); + + Warning ("RESCUE_DISK_BURN_NO_CHECK_WARN", hwndDlg); + bDontVerifyRescueDisk = TRUE; + nNewPageNo = SYSENC_RESCUE_DISK_VERIFIED_PAGE; + break; + + case 2: + AbortProcessSilent(); + + case 3: + break; + + default: + goto retryCDDriveCheck; + } + } + + if (IsWindowsIsoBurnerAvailable() && !bDontVerifyRescueDisk) + Info ("RESCUE_DISK_WIN_ISOBURN_PRELAUNCH_NOTE", hwndDlg); + + NormalCursor (); + } + + else if (nCurPageNo == SYSENC_RESCUE_DISK_BURN_PAGE) + { + if (!bDontVerifyRescueDisk) + { + /* Verify that the rescue disk has been written correctly */ + + try + { + WaitCursor(); + if (!BootEncObj->VerifyRescueDisk ()) + { + wchar_t szTmp[8000]; + + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("RESCUE_DISK_CHECK_FAILED"), + IsWindowsIsoBurnerAvailable () ? L"" : GetString ("RESCUE_DISK_CHECK_FAILED_SENTENCE_APPENDIX")); + + ErrorDirect (szTmp, hwndDlg); + + NormalCursor (); +#ifndef _DEBUG + return 1; +#endif + } + } + catch (Exception &e) + { + e.Show (hwndDlg); + NormalCursor (); + return 1; + } + NormalCursor (); + } + else + { + Warning ("RESCUE_DISK_BURN_NO_CHECK_WARN", hwndDlg); + nNewPageNo = SYSENC_RESCUE_DISK_VERIFIED_PAGE; // Skip irrelevant pages + } + } + + else if (nCurPageNo == SYSENC_WIPE_MODE_PAGE + || nCurPageNo == NONSYS_INPLACE_ENC_WIPE_MODE_PAGE) + { + if (nWipeMode > 0 + && AskWarnYesNo ("WIPE_MODE_WARN", hwndDlg) == IDNO) + return 1; + } + + else if (nCurPageNo == SYSENC_PRETEST_INFO_PAGE) + { + if (LocalizationActive + && AskWarnYesNo ("PREBOOT_NOT_LOCALIZED", hwndDlg) == IDNO) + return 1; + + bConfirmQuitSysEncPretest = TRUE; + + if (!bHiddenOS) // This text is not tailored to hidden OS + TextInfoDialogBox (TC_TBXID_SYS_ENCRYPTION_PRETEST); + + if (AskWarnYesNo ("CONFIRM_RESTART", hwndDlg) == IDNO) + return 1; + + /* Install the pre-boot authentication component and initiate the system encryption pretest. + If we are creating a hidden OS, pretest is omitted and OS cloning will follow. */ + + try + { + WaitCursor(); + +#if 0 + // Make sure the Rescue Disk is not in the drive + while (BootEncObj->VerifyRescueDisk ()) + { + Error ("REMOVE_RESCUE_DISK_FROM_DRIVE"); + } +#endif + + BootEncObj->Install (bHiddenOS ? true : false); + } + catch (Exception &e) + { + e.Show (hwndDlg); + Error (bHiddenOS ? "CANNOT_INITIATE_HIDDEN_OS_CREATION" : "CANNOT_INITIATE_SYS_ENCRYPTION_PRETEST", hwndDlg); + NormalCursor (); + return 1; + } + + + /* Add the main TrueCrypt app to the system startup sequence (the TrueCrypt Background Task), which + we need e.g. for notifications about prevented hibernation, about hidden OS leak protection, about + inconsistent hidden OS installs (TrueCrypt upgraded in the decoy system but not in the hidden one), etc. + Note that this must be done before calling ChangeSystemEncryptionStatus(), which broadcasts the change, + so that the main app (if it's running with different cached settings) will not overwrite our new + settings when it exits. */ + bStartOnLogon = TRUE; + SaveSettings (NULL); + ManageStartupSeq (); + + + if (bHiddenOS) + { + /* When we are going to create a hidden OS, the system encryption status is set + to SYSENC_STATUS_PRETEST (not to any special hidden-OS status), in case the XML + configuration file and its properties somehow leaks somewhere outside the system + partition (which will be wiped later on) indicating that a hidden OS has been created + on the computer. Instead, we update our raw config flags in the master boot record + (which is also altered when our boot loader is installed). */ + + if (!ChangeSystemEncryptionStatus (SYSENC_STATUS_PRETEST) + || !ChangeHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_CLONING)) + { + ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); + Error ("CANNOT_INITIATE_HIDDEN_OS_CREATION", hwndDlg); + NormalCursor (); + return 1; + } + } + else if (!ChangeSystemEncryptionStatus (SYSENC_STATUS_PRETEST)) + { + Error ("CANNOT_INITIATE_SYS_ENCRYPTION_PRETEST", hwndDlg); + NormalCursor (); + return 1; + } + + // Add the wizard to the system startup sequence + ManageStartupSeqWiz (FALSE, L"/acsysenc"); + + EndMainDlg (MainDlg); + + try + { + BootEncObj->RestartComputer (); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + + return 1; + } + + else if (nCurPageNo == SYSENC_PRETEST_RESULT_PAGE) + { + TextInfoDialogBox (TC_TBXID_SYS_ENC_RESCUE_DISK); + + // Begin the actual encryption process + + ChangeSystemEncryptionStatus (SYSENC_STATUS_ENCRYPTING); + } + + else if (nCurPageNo == SYSENC_ENCRYPTION_PAGE + && CreateSysEncMutex ()) + { + // The 'Next' button functions as Finish or Resume + + if (SystemEncryptionStatus != SYSENC_STATUS_NONE) + { + try + { + // Resume + SysEncResume (); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + } + else + { + // Finish + PostMessage (hwndDlg, TC_APPMSG_FORMAT_USER_QUIT, 0, 0); + } + + return 1; + } + else if (nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PARTITION_SEL_PAGE) + { + nNewPageNo = NONSYS_INPLACE_ENC_TRANSFORM_PAGE - 1; // Skip irrelevant pages + } + else if (nCurPageNo == NONSYS_INPLACE_ENC_TRANSFORM_PAGE) + { + /* In-place encryption start (the 'Next' button has been clicked) */ + if (bInPlaceDecNonSys + && !bInPlaceEncNonSysResumed + && AskWarnYesNo ("NONSYS_INPLACE_ENC_CONFIRM_BACKUP", hwndDlg) == IDNO) + { + // Cancel + return 1; + } + + NonSysInplaceEncResume (); + return 1; + } + else if (nCurPageNo == NONSYS_INPLACE_ENC_TRANSFORM_FINISHED_PAGE) + { + PostMessage (hwndDlg, TC_APPMSG_FORMAT_USER_QUIT, 0, 0); + return 1; + } + else if (nCurPageNo == NONSYS_INPLACE_DEC_TRANSFORM_FINISHED_DRIVE_LETTER_PAGE) + { + BOOL bDrvLetterAssignResult = FALSE; + + int tmpDriveLetter = (int) SendMessage (GetDlgItem (hCurPage, IDC_DRIVE_LETTER_LIST), + CB_GETITEMDATA, + SendMessage (GetDlgItem (hCurPage, IDC_DRIVE_LETTER_LIST), CB_GETCURSEL, 0, 0), + 0); + + if (tmpDriveLetter < 0) + tmpDriveLetter = GetFirstAvailableDrive (); + + do + { + wchar_t szDriveLetter[] = {L'A', L':', 0 }; + wchar_t rootPath[] = {L'A', L':', L'\\', 0 }; + wchar_t uniqVolName[MAX_PATH+1] = { 0 }; + + rootPath[0] += (wchar_t) tmpDriveLetter; + szDriveLetter[0] += (wchar_t) tmpDriveLetter; + + if (DefineDosDevice (DDD_RAW_TARGET_PATH, szDriveLetter, szDiskFile)) + { + bDrvLetterAssignResult = GetVolumeNameForVolumeMountPoint (rootPath, uniqVolName, MAX_PATH); + + DefineDosDevice (DDD_RAW_TARGET_PATH|DDD_REMOVE_DEFINITION|DDD_EXACT_MATCH_ON_REMOVE, + szDriveLetter, + szDiskFile); + + if (bDrvLetterAssignResult) + { + if (SetVolumeMountPoint (rootPath, uniqVolName) == 0) + bDrvLetterAssignResult = FALSE; + } + } + + if (!bDrvLetterAssignResult) + { + if (AskErrYesNo ("ERR_CANNOT_ASSIGN_DRIVE_LETTER_NONSYS_DEC", hwndDlg) == IDNO) + break; + } + + } while (bDrvLetterAssignResult == FALSE); + + bConfirmQuit = FALSE; + + PostMessage (hwndDlg, TC_APPMSG_FORMAT_USER_QUIT, 0, 0); + return 1; + } + else if (nCurPageNo == FORMAT_PAGE) + { + /* Format start (the 'Next' button has been clicked on the Format page) */ + + if (bVolTransformThreadRunning || bVolTransformThreadToRun) + return 1; + + bVolTransformThreadCancel = FALSE; + + bVolTransformThreadToRun = TRUE; + + fileSystem = (int) SendMessage (GetDlgItem (hCurPage, IDC_FILESYS), CB_GETITEMDATA, + SendMessage (GetDlgItem (hCurPage, IDC_FILESYS), CB_GETCURSEL, 0, 0) , 0); + + clusterSize = (int) SendMessage (GetDlgItem (hCurPage, IDC_CLUSTERSIZE), CB_GETITEMDATA, + SendMessage (GetDlgItem (hCurPage, IDC_CLUSTERSIZE), CB_GETCURSEL, 0, 0) , 0); + + quickFormat = IsButtonChecked (GetDlgItem (hCurPage, IDC_QUICKFORMAT)); + + + if (!bHiddenVol && IsHiddenOSRunning()) + { + // Creating a non-hidden volume under a hidden OS + + if (fileSystem == FILESYS_NTFS || fileSystem == FILESYS_EXFAT) + { + WarningDirect ((wstring (GetString ("CANNOT_CREATE_NON_HIDDEN_NTFS_VOLUMES_UNDER_HIDDEN_OS")) + + L"\n\n" + + GetString ("NOTE_BEGINNING") + + GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO") + + L" " + + GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION")).c_str(), hwndDlg); + + if (GetVolumeDataAreaSize (FALSE, nVolumeSize) <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize() + && AskYesNo("OFFER_FAT_FORMAT_ALTERNATIVE", hwndDlg) == IDYES) + { + fileSystem = FILESYS_FAT; + SelectAlgo (GetDlgItem (hCurPage, IDC_FILESYS), (int *) &fileSystem); + } + else + { + if (GetVolumeDataAreaSize (FALSE, nVolumeSize) > TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()) + Info ("FAT_NOT_AVAILABLE_FOR_SO_LARGE_VOLUME", hwndDlg); + + bVolTransformThreadToRun = FALSE; + return 1; + } + } + } + + if (bHiddenVolHost) + { + hiddenVolHostDriveNo = -1; + nMaximumHiddenVolSize = 0; + + if (fileSystem == FILESYS_NTFS || fileSystem == FILESYS_EXFAT) + { + if (bHiddenOS && (fileSystem == FILESYS_NTFS) + && (double) nVolumeSize / GetSystemPartitionSize() < MIN_HIDDENOS_DECOY_PARTITION_SIZE_RATIO_NTFS) + { + Error("OUTER_VOLUME_TOO_SMALL_FOR_HIDDEN_OS_NTFS", hwndDlg); + + if (GetVolumeDataAreaSize (FALSE, nVolumeSize) <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize() + && AskYesNo("OFFER_FAT_FORMAT_ALTERNATIVE", hwndDlg) == IDYES) + { + fileSystem = FILESYS_FAT; + SelectAlgo (GetDlgItem (hCurPage, IDC_FILESYS), (int *) &fileSystem); + } + else + { + if (GetVolumeDataAreaSize (FALSE, nVolumeSize) > TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()) + Info ("FAT_NOT_AVAILABLE_FOR_SO_LARGE_VOLUME", hwndDlg); + + bVolTransformThreadToRun = FALSE; + return 1; + } + } + + if (fileSystem == FILESYS_NTFS || fileSystem == FILESYS_EXFAT) // The file system may have been changed in the previous block + { + if (nCurrentOS == WIN_2000) + { + Error("HIDDEN_VOL_HOST_UNSUPPORTED_FILESYS_WIN2000", hwndDlg); + bVolTransformThreadToRun = FALSE; + return 1; + } + else if ((fileSystem == FILESYS_NTFS) && (GetVolumeDataAreaSize (FALSE, nVolumeSize) <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()) + && AskYesNo("HIDDEN_VOL_HOST_NTFS_ASK", hwndDlg) == IDNO) + { + bVolTransformThreadToRun = FALSE; + return 1; + } + } + } + } + else if (bHiddenVol) + { + // Hidden volume is always quick-formatted (if, however, the meaning of quickFormat is + // whether to create a sparse file, it must be set to FALSE). + quickFormat = !bSparseFileSwitch; + } + + + if (fileSystem == FILESYS_FAT + && nNeedToStoreFilesOver4GB == 1 + && AskWarnNoYes("CONFIRM_FAT_FOR_FILES_OVER_4GB", hwndDlg) == IDNO) + { + bVolTransformThreadToRun = FALSE; + return 1; + } + + EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDHELP), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE); + EnableWindow (GetDlgItem (hCurPage, IDC_QUICKFORMAT), FALSE); + EnableWindow (GetDlgItem (hCurPage, IDC_CLUSTERSIZE), FALSE); + EnableWindow (GetDlgItem (hCurPage, IDC_FILESYS), FALSE); + EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), TRUE); + SetFocus (GetDlgItem (hCurPage, IDC_ABORT_BUTTON)); + + // Increase cluster size if it's too small for this volume size (causes size of + // free space to be 0). Note that the below constant 0x2000000 is based on + // results of tests performed under Windows XP. + if (fileSystem == FILESYS_FAT && clusterSize > 0) + { + BOOL fixed = FALSE; + while (clusterSize < 128 + && nVolumeSize / (clusterSize * GetFormatSectorSize()) > 0x2000000) + { + clusterSize *= 2; + fixed = TRUE; + } + if (fixed) + MessageBoxW (hwndDlg, GetString ("CLUSTER_TOO_SMALL"), lpszTitle, MB_ICONWARNING); + } + + LastDialogId = "FORMAT_IN_PROGRESS"; + ArrowWaitCursor (); + _beginthread (volTransformThreadFunction, 0, MainDlg); + + return 1; + } + + else if (nCurPageNo == FORMAT_FINISHED_PAGE) + { + if (!bHiddenVol || bHiddenVolFinished) + { + /* Wizard loop restart */ + + if (bHiddenOS) + { + if (!ChangeWizardMode (WIZARD_MODE_SYS_DEVICE)) + return 1; + + // Hidden volume for hidden OS has been created. Now we will prepare our boot loader + // that will handle the OS cloning. + try + { + WaitCursor(); + + BootEncObj->PrepareHiddenOSCreation (nVolumeEA, FIRST_MODE_OF_OPERATION_ID, hash_algo); + } + catch (Exception &e) + { + e.Show (MainDlg); + NormalCursor(); + return 1; + } + + bHiddenVol = FALSE; + + LoadPage (hwndDlg, SYSENC_PRETEST_INFO_PAGE); + } + else + LoadPage (hwndDlg, INTRO_PAGE); + + SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString ("CANCEL")); + bHiddenVolFinished = FALSE; + WipePasswordsAndKeyfiles (); + + return 1; + } + else + { + /* We're going to scan the bitmap of the hidden volume host (in the non-Direct hidden volume wizard mode) */ + int retCode; + WaitCursor (); + + if (hiddenVolHostDriveNo != -1) // If the hidden volume host is mounted + { + BOOL tmp_result; + + // Dismount the hidden volume host (in order to remount it as read-only subsequently) + CloseVolumeExplorerWindows (hwndDlg, hiddenVolHostDriveNo); + while (!(tmp_result = UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE))) + { + if (MessageBoxW (hwndDlg, GetString ("CANT_DISMOUNT_OUTER_VOL"), lpszTitle, MB_RETRYCANCEL | MB_ICONERROR | MB_SETFOREGROUND) != IDRETRY) + { + // Cancel + NormalCursor(); + return 1; + } + } + if (tmp_result) // If dismounted + hiddenVolHostDriveNo = -1; + } + + if (hiddenVolHostDriveNo < 0) // If the hidden volume host is not mounted + { + // Remount the hidden volume host as read-only (to ensure consistent and secure + // results of the volume bitmap scanning) + switch (MountHiddenVolHost (hwndDlg, szDiskFile, &hiddenVolHostDriveNo, &volumePassword, hash_algo, volumePim, TRUE)) + { + case ERR_NO_FREE_DRIVES: + MessageBoxW (hwndDlg, GetString ("NO_FREE_DRIVE_FOR_OUTER_VOL"), lpszTitle, ICON_HAND); + NormalCursor (); + return 1; + + case ERR_VOL_MOUNT_FAILED: + case ERR_PASSWORD_WRONG: + NormalCursor (); + return 1; + + case 0: + + /* Hidden volume host successfully mounted as read-only */ + + // Verify that the outer volume contains a suitable file system, retrieve cluster size, and + // scan the volume bitmap + if (!IsAdmin () && IsUacSupported ()) + retCode = UacAnalyzeHiddenVolumeHost (hwndDlg, &hiddenVolHostDriveNo, GetVolumeDataAreaSize (FALSE, nHiddenVolHostSize), &realClusterSize, &nbrFreeClusters); + else + retCode = AnalyzeHiddenVolumeHost (hwndDlg, &hiddenVolHostDriveNo, GetVolumeDataAreaSize (FALSE, nHiddenVolHostSize), &realClusterSize, &nbrFreeClusters); + + switch (retCode) + { + case -1: // Fatal error + CloseVolumeExplorerWindows (hwndDlg, hiddenVolHostDriveNo); + + if (UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE)) + hiddenVolHostDriveNo = -1; + + AbortProcessSilent (); + break; + + case 0: // Unsupported file system (or other non-fatal error which has already been reported) + NormalCursor (); + return 1; + + case 1: // Success + { + BOOL tmp_result; + + // Determine the maximum possible size of the hidden volume + if (DetermineMaxHiddenVolSize (hwndDlg) < 1) + { + NormalCursor (); + goto ovf_end; + } + + /* Maximum possible size of the hidden volume successfully determined */ + + // Dismount the hidden volume host + while (!(tmp_result = UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE))) + { + if (MessageBoxW (hwndDlg, GetString ("CANT_DISMOUNT_OUTER_VOL"), lpszTitle, MB_RETRYCANCEL) != IDRETRY) + { + // Cancel + NormalCursor (); + goto ovf_end; + } + } + + // Prevent having to recreate the outer volume due to inadvertent exit + bConfirmQuit = TRUE; + + hiddenVolHostDriveNo = -1; + + nNewPageNo = HIDDEN_VOL_HOST_PRE_CIPHER_PAGE; + + // Clear the outer volume password + WipePasswordsAndKeyfiles (); + + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), TRUE); + NormalCursor (); + + } + break; + } + break; + } + } + } + } + + else if (nCurPageNo == DEVICE_WIPE_PAGE) + { + if (AskWarnOkCancel (bHiddenOS && IsHiddenOSRunning() ? "CONFIRM_WIPE_START_DECOY_SYS_PARTITION" : "CONFIRM_WIPE_START", hwndDlg) == IDOK) + { + WipeStart (); + ArrowWaitCursor(); + } + return 1; + } + + LoadPage (hwndDlg, nNewPageNo + 1); +ovf_end: + return 1; + } + else if (lw == IDC_PREV) + { + if (nCurPageNo == SYSENC_SPAN_PAGE) + { + // Skip irrelevant pages when going back + if (!bHiddenOS) + nNewPageNo = SYSENC_TYPE_PAGE + 1; + } + if (nCurPageNo == SYSENC_MULTI_BOOT_MODE_PAGE) + { + // Skip the drive analysis page(s) or other irrelevant pages when going back + if (bHiddenOS) + nNewPageNo = SYSENC_HIDDEN_OS_REQ_CHECK_PAGE + 1; + else if (bWholeSysDrive) + nNewPageNo = SYSENC_PRE_DRIVE_ANALYSIS_PAGE + 1; + else + nNewPageNo = SYSENC_SPAN_PAGE + 1; + } + else if (nCurPageNo == SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE) + { + if (SysEncMultiBootCfg.NumberOfSysDrives == 1) + { + // We can skip SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE (it is implied that there are multiple systems on the drive) + nNewPageNo = SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE + 1; + } + } + else if (nCurPageNo == HIDDEN_VOL_HOST_PRE_CIPHER_PAGE) + { + if (bHiddenOS) + { + if (!ChangeWizardMode (WIZARD_MODE_SYS_DEVICE)) + { + NormalCursor (); + return 1; + } + + // Skip irrelevant pages. + // Note that we're ignoring nMultiBoot here, as the multi-boot question pages are skipped + // when creating a hidden OS (only a single message box is displayed with requirements). + nNewPageNo = SYSENC_MULTI_BOOT_MODE_PAGE + 1; + } + else + { + nNewPageNo = VOLUME_LOCATION_PAGE + 1; + } + } + else if (nCurPageNo == HIDDEN_VOL_WIZARD_MODE_PAGE) + { + if (IsButtonChecked (GetDlgItem (hCurPage, IDC_HIDVOL_WIZ_MODE_DIRECT))) + bHiddenVolDirect = TRUE; + else + bHiddenVolDirect = FALSE; + } + else if (nCurPageNo == VOLUME_TYPE_PAGE) + { + if (WizardMode != WIZARD_MODE_SYS_DEVICE) + nNewPageNo = INTRO_PAGE + 1; // Skip irrelevant pages + } + else if (nCurPageNo == VOLUME_LOCATION_PAGE) + { + BOOL tmpbDevice; + + GetWindowText (GetDlgItem (hCurPage, IDC_COMBO_BOX), szFileName, ARRAYSIZE (szFileName)); + CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice); + + if (tmpbDevice == bDevice) + { + MoveEditToCombo (GetDlgItem (hCurPage, IDC_COMBO_BOX), bHistory); + SaveSettings (hCurPage); + } + + if (!bHiddenVol) + nNewPageNo = VOLUME_TYPE_PAGE + 1; // Skip the hidden volume creation wizard mode selection + } + + else if (nCurPageNo == CIPHER_PAGE) + { + LPARAM nIndex; + nIndex = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETCURSEL, 0, 0); + nVolumeEA = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETITEMDATA, nIndex, 0); + + nIndex = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX_HASH_ALGO), CB_GETCURSEL, 0, 0); + hash_algo = (int) SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX_HASH_ALGO), CB_GETITEMDATA, nIndex, 0); + + RandSetHashFunction (hash_algo); + + if (WizardMode == WIZARD_MODE_SYS_DEVICE) + { + if (nMultiBoot > 1) + nNewPageNo = SYSENC_MULTI_BOOT_OUTCOME_PAGE + 1; // Skip irrelevant pages + else + nNewPageNo = SYSENC_MULTI_BOOT_MODE_PAGE + 1; // Skip irrelevant pages + } + else if (!bHiddenVol) + nNewPageNo = (bDevice ? DEVICE_TRANSFORM_MODE_PAGE : VOLUME_LOCATION_PAGE) + 1; + else if (bHiddenVolHost) + nNewPageNo = HIDDEN_VOL_HOST_PRE_CIPHER_PAGE + 1; // Skip the info on the hidden volume + } + + else if (nCurPageNo == SIZE_PAGE) + { + VerifySizeAndUpdate (hCurPage, TRUE); + } + + else if (nCurPageNo == FILESYS_PAGE) + { + if (nNeedToStoreFilesOver4GB != Get2RadButtonPageAnswer()) + fileSystem = FILESYS_NONE; // The user may have gone back and changed the answer, so default file system must be reselected + + nNeedToStoreFilesOver4GB = Get2RadButtonPageAnswer(); + + nNewPageNo = (PimEnable? PIM_PAGE : PASSWORD_PAGE) + 1; // Skip PIM page if it is not enabled + } + + else if (nCurPageNo == PASSWORD_PAGE) + { + // Store the password in case we need to restore it after keyfile is applied to it + GetPassword (hCurPage, IDC_PASSWORD, szRawPassword, sizeof (szRawPassword), FALSE); + + VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (MainDlg, IDC_NEXT), + GetDlgItem (hCurPage, IDC_PASSWORD), + GetDlgItem (hCurPage, IDC_VERIFY), + volumePassword.Text, + szVerify, + KeyFilesEnable && FirstKeyFile!=NULL && !SysEncInEffect ()); + + volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); + + + nNewPageNo = SIZE_PAGE + 1; // Skip the hidden volume host password page + + if (SysEncInEffect ()) + { + nNewPageNo = CIPHER_PAGE + 1; // Skip irrelevant pages + + KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); + + if (bKeyboardLayoutChanged) + { + // Restore the original keyboard layout + if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) + Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); + else + bKeyboardLayoutChanged = FALSE; + } + } + else if (bInPlaceEncNonSys) + nNewPageNo = CIPHER_PAGE + 1; + } + + else if (nCurPageNo == PIM_PAGE) + { + volumePim = GetPim (hCurPage, IDC_PIM); + } + + else if (nCurPageNo == HIDDEN_VOL_HOST_PASSWORD_PAGE + || nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) + { + // Store the password in case we need to restore it after keyfile is applied to it + GetPassword (hCurPage, IDC_PASSWORD_DIRECT, szRawPassword, MAX_PASSWORD + 1, FALSE); + + memcpy (volumePassword.Text, szRawPassword, MAX_PASSWORD + 1); + volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); + + if (!bInPlaceEncNonSys) + nNewPageNo = VOLUME_LOCATION_PAGE + 1; + } + + else if (nCurPageNo == SYSENC_COLLECTING_RANDOM_DATA_PAGE + || nCurPageNo == NONSYS_INPLACE_ENC_RAND_DATA_PAGE) + { + wchar_t tmp[RANDPOOL_DISPLAY_SIZE+1]; + + KillTimer (hwndDlg, TIMER_ID_RANDVIEW); + + // Attempt to wipe the GUI field showing portions of randpool + wmemset (tmp, L'X', ARRAYSIZE(tmp)); + tmp [ARRAYSIZE(tmp)-1] = 0; + SetWindowText (hRandPoolSys, tmp); + + nNewPageNo = (PimEnable? PIM_PAGE : PASSWORD_PAGE) + 1; // Skip irrelevant pages + } + + else if (nCurPageNo == SYSENC_KEYS_GEN_PAGE) + { + wchar_t tmp[KEY_GUI_VIEW_SIZE+1]; + + // Attempt to wipe the GUI fields showing portions of the master and header keys + wmemset (tmp, L'X', ARRAYSIZE(tmp)); + tmp [ARRAYSIZE(tmp)-1] = 0; + SetWindowText (hMasterKey, tmp); + SetWindowText (hHeaderKey, tmp); + } + + else if (nCurPageNo == SYSENC_WIPE_MODE_PAGE) + { + if (bDontVerifyRescueDisk) + nNewPageNo = SYSENC_RESCUE_DISK_VERIFIED_PAGE; // Skip irrelevant pages + } + + else if (nCurPageNo == FORMAT_PAGE) + { + wchar_t tmp[RNG_POOL_SIZE*2+1]; + + KillTimer (hwndDlg, TIMER_ID_RANDVIEW); + + // Attempt to wipe the GUI fields showing portions of randpool, of the master and header keys + wmemset (tmp, L'X', ARRAYSIZE(tmp)); + tmp [ARRAYSIZE(tmp)-1] = 0; + SetWindowText (hRandPool, tmp); + SetWindowText (hMasterKey, tmp); + SetWindowText (hHeaderKey, tmp); + + if (WizardMode != WIZARD_MODE_SYS_DEVICE) + { + // Skip irrelevant pages + + if (FileSize4GBLimitQuestionNeeded () + && !CreatingHiddenSysVol() // If we're creating a hidden volume for a hidden OS, we don't need to format it with any filesystem (the entire OS will be copied to the hidden volume sector by sector). + && !bInPlaceEncNonSys) + { + nNewPageNo = FILESYS_PAGE + 1; + } + else + nNewPageNo = (PimEnable? PIM_PAGE : PASSWORD_PAGE) + 1; + } + } + + LoadPage (hwndDlg, nNewPageNo - 1); + + return 1; + } + + return 0; + + case WM_ENDSESSION: + EndMainDlg (MainDlg); + localcleanup (); + return 0; + + case WM_CLOSE: + PostMessage (hwndDlg, TC_APPMSG_FORMAT_USER_QUIT, 0, 0); + return 1; + } + + return 0; +} + +void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) +{ + wchar_t **lpszCommandLineArgs = NULL; /* Array of command line arguments */ + int nNoCommandLineArgs; /* The number of arguments in the array */ + + if (_wcsicmp (lpszCommandLine, L"-Embedding") == 0) + { + ComServerMode = TRUE; + return; + } + + /* Extract command line arguments */ + nNoCommandLineArgs = Win32CommandLine (&lpszCommandLineArgs); + if (nNoCommandLineArgs > 0) + { + int i; + + for (i = 0; i < nNoCommandLineArgs; i++) + { + enum + { + OptionHistory, + OptionNoIsoCheck, + OptionQuit, + OptionTokenLib, + CommandResumeSysEncLogOn, + CommandResumeSysEnc, + CommandDecryptSysEnc, + CommandEncDev, + CommandHiddenSys, + CommandResumeNonSysInplaceLogOn, + CommandResumeHiddenSys, + CommandSysEnc, + CommandInplaceDec, + CommandResumeInplaceDec, + CommandResumeInplace, + OptionEncryption, + OptionFilesystem, + OptionPkcs5, + OptionPassword, + OptionPim, + OptionSize, + OptionCreate, + OptionSilent, + OptionDynamic, + OptionForce, + }; + + argument args[]= + { + // Public + { OptionHistory, L"/history", L"/h", FALSE }, + { OptionNoIsoCheck, L"/noisocheck", L"/n", FALSE }, + { OptionTokenLib, L"/tokenlib", NULL, FALSE }, + { OptionQuit, L"/quit", L"/q", FALSE }, + { OptionEncryption, L"/encryption", NULL , FALSE }, + { OptionFilesystem, L"/filesystem", NULL , FALSE }, + { OptionPkcs5, L"/hash", NULL , FALSE }, + { OptionPassword, L"/password", NULL, FALSE }, + { OptionPim, L"/pim", NULL, FALSE }, + { OptionSize, L"/size", NULL, FALSE }, + { OptionCreate, L"/create", NULL, FALSE }, + { OptionSilent, L"/silent", NULL, FALSE }, + { OptionDynamic, L"/dynamic", NULL, FALSE }, + { OptionForce, L"/force", NULL, FALSE }, + + // Internal + { CommandResumeSysEncLogOn, L"/acsysenc", L"/a", TRUE }, + { CommandResumeSysEnc, L"/csysenc", L"/c", TRUE }, + { CommandDecryptSysEnc, L"/dsysenc", L"/d", TRUE }, + { CommandEncDev, L"/encdev", L"/e", TRUE }, + { CommandHiddenSys, L"/isysenc", L"/i", TRUE }, + { CommandResumeNonSysInplaceLogOn, L"/prinplace", L"/p", TRUE }, + { CommandResumeHiddenSys, L"/risysenc", L"/r", TRUE }, + { CommandSysEnc, L"/sysenc", L"/s", TRUE }, + { CommandInplaceDec, L"/inplacedec", NULL, TRUE }, + { CommandResumeInplaceDec, L"/resumeinplacedec",NULL, TRUE }, + { CommandResumeInplace, L"/zinplace", L"/z", TRUE } + }; + + argumentspec as; + + int x; + + if (lpszCommandLineArgs[i] == NULL) + continue; + + as.args = args; + as.arg_cnt = sizeof(args)/ sizeof(args[0]); + + x = GetArgumentID (&as, lpszCommandLineArgs[i]); + + switch (x) + { + case OptionCreate: + { + DirectCreationMode = TRUE; + + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, + szFileName, ARRAYSIZE (szFileName))) + { + RelativePath2Absolute (szFileName); + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + break; + case OptionEncryption: + { + wchar_t szTmp[64] = {0}; + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, + &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) + { + CmdVolumeEA = EAGetByName (szTmp); + if (CmdVolumeEA == 0) + AbortProcess ("COMMAND_LINE_ERROR"); + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + break; + case OptionFilesystem: + { + wchar_t szTmp[8] = {0}; + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, + &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) + { + if (_wcsicmp(szTmp, L"NONE") == 0) + CmdVolumeFilesystem = FILESYS_NONE; + else if (_wcsicmp(szTmp, L"FAT32") == 0 || _wcsicmp(szTmp, L"FAT") == 0) + CmdVolumeFilesystem = FILESYS_FAT; + else if (_wcsicmp(szTmp, L"NTFS") == 0) + CmdVolumeFilesystem = FILESYS_NTFS; + else if (IsOSVersionAtLeast (WIN_VISTA, 1) && _wcsicmp(szTmp, L"EXFAT") == 0) + CmdVolumeFilesystem = FILESYS_EXFAT; + else + { + AbortProcess ("COMMAND_LINE_ERROR"); + } + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + break; + case OptionPassword: + { + wchar_t szTmp[MAX_PASSWORD + 1]; + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, + szTmp, ARRAYSIZE (szTmp))) + { + int iLen = WideCharToMultiByte (CP_UTF8, 0, szTmp, -1, (LPSTR) CmdVolumePassword.Text, MAX_PASSWORD + 1, NULL, NULL); + burn (szTmp, sizeof (szTmp)); + if (iLen > 0) + CmdVolumePassword.Length = (unsigned __int32) (iLen - 1); + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + break; + case OptionPkcs5: + { + wchar_t szTmp[32] = {0}; + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, + &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) + { + if (_wcsicmp(szTmp, L"sha512") == 0 || _wcsicmp(szTmp, L"sha-512") == 0) + CmdVolumePkcs5 = SHA512; + else if (_wcsicmp(szTmp, L"whirlpool") == 0) + CmdVolumePkcs5 = WHIRLPOOL; + else if (_wcsicmp(szTmp, L"sha256") == 0 || _wcsicmp(szTmp, L"sha-256") == 0) + CmdVolumePkcs5 = SHA256; + else if (_wcsicmp(szTmp, L"ripemd160") == 0 || _wcsicmp(szTmp, L"ripemd-160") == 0) + CmdVolumePkcs5 = RIPEMD160; + else + { + CmdVolumePkcs5 = 0; + AbortProcess ("COMMAND_LINE_ERROR"); + } + + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + break; + + case OptionPim: + { + wchar_t szTmp[32] = {0}; + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, + &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) + { + wchar_t* endPtr = NULL; + CmdVolumePim = (int) wcstol(szTmp, &endPtr, 0); + if (CmdVolumePim < 0 || CmdVolumePim > MAX_PIM_VALUE || endPtr == szTmp || *endPtr != L'\0') + { + CmdVolumePim = 0; + AbortProcess ("COMMAND_LINE_ERROR"); + } + + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + break; + case OptionSilent: + Silent = TRUE; + break; + case OptionDynamic: + CmdSparseFileSwitch = TRUE; + break; + case OptionForce: + bForceOperation = TRUE; + break; + case OptionSize: + { + wchar_t szTmp[32] = {0}; + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, + &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp)) + && (wcslen (szTmp) >= 2) + ) + { + /* size can be expressed in bytes or with suffixes K, M,G or T + * to indicate the unit to use + */ + unsigned __int64 multiplier; + wchar_t* endPtr = NULL; + wchar_t lastChar = szTmp [wcslen (szTmp) - 1]; + if (lastChar >= L'0' && lastChar <= L'9') + multiplier = 1; + else if (lastChar == L'K' || lastChar == L'k') + multiplier = BYTES_PER_KB; + else if (lastChar == L'M' || lastChar == L'm') + multiplier = BYTES_PER_MB; + else if (lastChar == L'G' || lastChar == L'g') + multiplier = BYTES_PER_GB; + else if (lastChar == L'T' || lastChar == L't') + multiplier = BYTES_PER_TB; + else + AbortProcess ("COMMAND_LINE_ERROR"); + + if (multiplier != 1) + szTmp [wcslen (szTmp) - 1] = 0; + + CmdVolumeFileSize = _wcstoui64(szTmp, &endPtr, 0); + if (CmdVolumeFileSize == 0 || CmdVolumeFileSize == _UI64_MAX + || endPtr == szTmp || *endPtr != L'\0') + { + AbortProcess ("COMMAND_LINE_ERROR"); + } + + CmdVolumeFileSize *= multiplier; + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + break; + case CommandSysEnc: + // Encrypt system partition/drive (passed by Mount if system encryption hasn't started or to reverse decryption) + + // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption + if (CreateSysEncMutex ()) + { + bDirectSysEncMode = TRUE; + bDirectSysEncModeCommand = SYSENC_COMMAND_ENCRYPT; + ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); + } + else + { + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); + exit(0); + } + + break; + + case CommandDecryptSysEnc: + // Decrypt system partition/drive (passed by Mount, also to reverse encryption in progress, when paused) + + // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption + if (CreateSysEncMutex ()) + { + bDirectSysEncMode = TRUE; + bDirectSysEncModeCommand = SYSENC_COMMAND_DECRYPT; + ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); + } + else + { + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); + exit(0); + } + break; + + case CommandHiddenSys: + // Create a hidden operating system (passed by Mount when the user selects System -> Create Hidden Operating System) + + // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption + if (CreateSysEncMutex ()) + { + bDirectSysEncMode = TRUE; + bDirectSysEncModeCommand = SYSENC_COMMAND_CREATE_HIDDEN_OS; + ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); + } + else + { + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); + exit(0); + } + + break; + + case CommandResumeHiddenSys: + // Resume process of creation of a hidden operating system (passed by Wizard when the user needs to UAC-elevate the whole wizard process) + + // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption + if (CreateSysEncMutex ()) + { + bDirectSysEncMode = TRUE; + bDirectSysEncModeCommand = SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV; + ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); + } + else + { + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); + exit(0); + } + + break; + + case CommandResumeSysEnc: + // Resume previous system-encryption operation (passed by Mount) e.g. encryption, decryption, or pretest + + // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption + if (CreateSysEncMutex ()) + { + bDirectSysEncMode = TRUE; + bDirectSysEncModeCommand = SYSENC_COMMAND_RESUME; + ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); + } + else + { + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); + exit(0); + } + break; + + case CommandResumeSysEncLogOn: + // Same as csysenc but passed only by the system (from the startup sequence) + + // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption + if (CreateSysEncMutex ()) + { + bDirectSysEncMode = TRUE; + bDirectSysEncModeCommand = SYSENC_COMMAND_STARTUP_SEQ_RESUME; + ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); + } + else + { + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); + exit(0); + } + break; + + case CommandEncDev: + // Resume process of creation of a non-sys-device-hosted volume (passed by Wizard when the user needs to UAC-elevate) + DirectDeviceEncMode = TRUE; + break; + + case CommandInplaceDec: + // Start (not resume) decrypting the specified non-system volume in place + { + wchar_t szTmp [TC_MAX_PATH + 8000] = {0}; + + GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp)); + + if (wcslen (szTmp) < 1) + { + // No valid volume path specified as command-line parameter + AbortProcess ("ERR_PARAMETER_INCORRECT"); + } + + memset (szFileName, 0, sizeof (szFileName)); + StringCbCopyW (szFileName, sizeof (szFileName), szTmp); + DirectNonSysInplaceDecStartMode = TRUE; + } + break; + + case CommandResumeInplace: + // Resume interrupted process of non-system in-place encryption of a partition + DirectNonSysInplaceEncResumeMode = TRUE; + break; + + case CommandResumeInplaceDec: + // Resume interrupted process of non-system in-place decryption of a partition + DirectNonSysInplaceDecResumeMode = TRUE; + break; + + case CommandResumeNonSysInplaceLogOn: + // Ask the user whether to resume interrupted process of non-system in-place encryption of a partition + // This switch is passed only by the system (from the startup sequence). + DirectPromptNonSysInplaceEncResumeMode = TRUE; + break; + + case OptionNoIsoCheck: + bDontVerifyRescueDisk = TRUE; + break; + + case OptionHistory: + { + wchar_t szTmp[8] = {0}; + bHistory = bHistoryCmdLine = TRUE; + + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, + szTmp, ARRAYSIZE (szTmp))) + { + if (!_wcsicmp(szTmp,L"y") || !_wcsicmp(szTmp,L"yes")) + { + bHistory = TRUE; + } + + else if (!_wcsicmp(szTmp,L"n") || !_wcsicmp(szTmp,L"no")) + { + bHistory = FALSE; + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + } + break; + + case OptionTokenLib: + if (GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, SecurityTokenLibraryPath, ARRAYSIZE (SecurityTokenLibraryPath)) == HAS_ARGUMENT) + InitSecurityTokenLibrary(hwndDlg); + else + AbortProcess ("COMMAND_LINE_ERROR"); + + break; + + case OptionQuit: + { + // Used to indicate non-install elevation + wchar_t szTmp[32]; + if (GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp)) != HAS_ARGUMENT) + AbortProcess ("COMMAND_LINE_ERROR"); + } + break; + + default: + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_COMMANDHELP_DLG), hwndDlg, (DLGPROC) + CommandHelpDlgProc, (LPARAM) &as); + + exit(0); + } + } + } + + /* Free up the command line arguments */ + while (--nNoCommandLineArgs >= 0) + { + free (lpszCommandLineArgs[nNoCommandLineArgs]); + } + + if (lpszCommandLineArgs) + free (lpszCommandLineArgs); +} + + +int DetermineMaxHiddenVolSize (HWND hwndDlg) +{ + __int64 nbrReserveBytes; + + if (nbrFreeClusters * realClusterSize < TC_MIN_HIDDEN_VOLUME_SIZE) + { + MessageBoxW (hwndDlg, GetString ("NO_SPACE_FOR_HIDDEN_VOL"), lpszTitle, ICON_HAND); + UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE); + AbortProcessSilent (); + } + + // Add a reserve (in case the user mounts the outer volume and creates new files + // on it by accident or OS writes some new data behind his or her back, such as + // System Restore etc.) + nbrReserveBytes = GetVolumeDataAreaSize (FALSE, nHiddenVolHostSize) / 200; + if (nbrReserveBytes > BYTES_PER_MB * 10) + nbrReserveBytes = BYTES_PER_MB * 10; + + // Compute the final value + + nMaximumHiddenVolSize = nbrFreeClusters * realClusterSize - TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE - nbrReserveBytes; + nMaximumHiddenVolSize -= nMaximumHiddenVolSize % realClusterSize; // Must be a multiple of the sector size + + if (nMaximumHiddenVolSize < TC_MIN_HIDDEN_VOLUME_SIZE) + { + MessageBoxW (hwndDlg, GetString ("NO_SPACE_FOR_HIDDEN_VOL"), lpszTitle, ICON_HAND); + UnmountVolume (hwndDlg, hiddenVolHostDriveNo, TRUE); + AbortProcessSilent (); + } + + // Prepare the hidden volume size parameters + if (nMaximumHiddenVolSize < BYTES_PER_MB) + nMultiplier = BYTES_PER_KB; + else if (nMaximumHiddenVolSize < BYTES_PER_GB) + nMultiplier = BYTES_PER_MB; + else if (nMaximumHiddenVolSize < BYTES_PER_TB) + nMultiplier = BYTES_PER_GB; + else + nMultiplier = BYTES_PER_TB; + + nUIVolumeSize = 0; // Set the initial value for the hidden volume size input field to the max + nVolumeSize = nUIVolumeSize * nMultiplier; // Chop off possible remainder + + return 1; +} + + +// Tests whether the file system of the given volume is suitable to host a hidden volume, +// retrieves the cluster size, and scans the volume cluster bitmap. In addition, checks +// the TrueCrypt volume format version and the type of volume. +int AnalyzeHiddenVolumeHost (HWND hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *pnbrFreeClusters) +{ + HANDLE hDevice; + DWORD bytesReturned; + DWORD dwSectorsPerCluster, dwBytesPerSector, dwNumberOfFreeClusters, dwTotalNumberOfClusters; + DWORD dwResult; + int result; + wchar_t szFileSystemNameBuffer[256]; + wchar_t tmpPath[7] = {L'\\',L'\\',L'.',L'\\',(wchar_t) *driveNo + L'A',L':',0}; + wchar_t szRootPathName[4] = {(wchar_t) *driveNo + L'A', L':', L'\\', 0}; + BYTE readBuffer[TC_MAX_VOLUME_SECTOR_SIZE * 2]; + LARGE_INTEGER offset, offsetNew; + VOLUME_PROPERTIES_STRUCT volProp; + + memset (&volProp, 0, sizeof(volProp)); + volProp.driveNo = *driveNo; + if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &volProp, sizeof (volProp), &volProp, sizeof (volProp), &dwResult, NULL) || dwResult == 0) + { + handleWin32Error (hwndDlg, SRC_POS); + Error ("CANT_ACCESS_OUTER_VOL", hwndDlg); + goto efsf_error; + } + + if (volProp.volFormatVersion < TC_VOLUME_FORMAT_VERSION) + { + // We do not support creating hidden volumes within volumes created by TrueCrypt 5.1a or earlier. + Error ("ERR_VOL_FORMAT_BAD", hwndDlg); + return 0; + } + + if (volProp.hiddenVolume) + { + // The user entered a password for a hidden volume + Error ("ERR_HIDDEN_NOT_NORMAL_VOLUME", hwndDlg); + return 0; + } + + if (volProp.volumeHeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC + || volProp.volumeHeaderFlags & TC_HEADER_FLAG_ENCRYPTED_SYSTEM) + { + Warning ("ERR_HIDDEN_VOL_HOST_ENCRYPTED_INPLACE", hwndDlg); + return 0; + } + + hDevice = CreateFile (tmpPath, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (hDevice == INVALID_HANDLE_VALUE) + { + MessageBoxW (hwndDlg, GetString ("CANT_ACCESS_OUTER_VOL"), lpszTitle, ICON_HAND); + goto efsf_error; + } + + offset.QuadPart = 0; + + if (SetFilePointerEx (hDevice, offset, &offsetNew, FILE_BEGIN) == 0) + { + handleWin32Error (hwndDlg, SRC_POS); + goto efs_error; + } + + result = ReadFile (hDevice, &readBuffer, TC_MAX_VOLUME_SECTOR_SIZE, &bytesReturned, NULL); + + if (result == 0) + { + handleWin32Error (hwndDlg, SRC_POS); + MessageBoxW (hwndDlg, GetString ("CANT_ACCESS_OUTER_VOL"), lpszTitle, ICON_HAND); + goto efs_error; + } + + CloseHandle (hDevice); + hDevice = INVALID_HANDLE_VALUE; + + // Determine file system type + + GetVolumeInformation(szRootPathName, NULL, 0, NULL, NULL, NULL, szFileSystemNameBuffer, ARRAYSIZE(szFileSystemNameBuffer)); + + // The Windows API sometimes fails to indentify the file system correctly so we're using "raw" analysis too. + if (!wcsncmp (szFileSystemNameBuffer, L"FAT", 3) + || (readBuffer[0x36] == 'F' && readBuffer[0x37] == 'A' && readBuffer[0x38] == 'T') + || (readBuffer[0x52] == 'F' && readBuffer[0x53] == 'A' && readBuffer[0x54] == 'T')) + { + // FAT12/FAT16/FAT32 + + // Retrieve the cluster size + *realClusterSize = ((int) readBuffer[0xb] + ((int) readBuffer[0xc] << 8)) * (int) readBuffer[0xd]; + + // Get the map of the clusters that are free and in use on the outer volume. + // The map will be scanned to determine the size of the uninterrupted block of free + // space (provided there is any) whose end is aligned with the end of the volume. + // The value will then be used to determine the maximum possible size of the hidden volume. + + return ScanVolClusterBitmap (hwndDlg, + driveNo, + hiddenVolHostSize / *realClusterSize, + pnbrFreeClusters); + } + else if (!wcsncmp (szFileSystemNameBuffer, L"NTFS", 4) || !_wcsnicmp (szFileSystemNameBuffer, L"exFAT", 5)) + { + // NTFS + bool bIsNtfs = (0 == wcsncmp (szFileSystemNameBuffer, L"NTFS", 4)); + + if (nCurrentOS == WIN_2000) + { + Error("HIDDEN_VOL_HOST_UNSUPPORTED_FILESYS_WIN2000", hwndDlg); + return 0; + } + + if (bIsNtfs && bHiddenVolDirect && GetVolumeDataAreaSize (FALSE, hiddenVolHostSize) <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()) + Info ("HIDDEN_VOL_HOST_NTFS", hwndDlg); + + if (!GetDiskFreeSpace(szRootPathName, + &dwSectorsPerCluster, + &dwBytesPerSector, + &dwNumberOfFreeClusters, + &dwTotalNumberOfClusters)) + { + handleWin32Error (hwndDlg, SRC_POS); + Error ("CANT_GET_OUTER_VOL_INFO", hwndDlg); + return -1; + }; + + *realClusterSize = dwBytesPerSector * dwSectorsPerCluster; + + // Get the map of the clusters that are free and in use on the outer volume. + // The map will be scanned to determine the size of the uninterrupted block of free + // space (provided there is any) whose end is aligned with the end of the volume. + // The value will then be used to determine the maximum possible size of the hidden volume. + + return ScanVolClusterBitmap (hwndDlg, + driveNo, + hiddenVolHostSize / *realClusterSize, + pnbrFreeClusters); + } + else + { + // Unsupported file system + + Error ((nCurrentOS == WIN_2000) ? "HIDDEN_VOL_HOST_UNSUPPORTED_FILESYS_WIN2000" : "HIDDEN_VOL_HOST_UNSUPPORTED_FILESYS", hwndDlg); + return 0; + } + +efs_error: + CloseHandle (hDevice); + +efsf_error: + CloseVolumeExplorerWindows (hwndDlg, *driveNo); + + return -1; +} + + +// Mounts a volume within which the user intends to create a hidden volume +int MountHiddenVolHost (HWND hwndDlg, wchar_t *volumePath, int *driveNo, Password *password, int pkcs5_prf, int pim, BOOL bReadOnly) +{ + MountOptions mountOptions; + ZeroMemory (&mountOptions, sizeof (mountOptions)); + + *driveNo = GetLastAvailableDrive (); + + if (*driveNo == -1) + { + *driveNo = -2; + return ERR_NO_FREE_DRIVES; + } + + mountOptions.ReadOnly = bReadOnly; + mountOptions.Removable = ConfigReadInt ("MountVolumesRemovable", FALSE); + mountOptions.ProtectHiddenVolume = FALSE; + mountOptions.PreserveTimestamp = bPreserveTimestamp; + mountOptions.PartitionInInactiveSysEncScope = FALSE; + mountOptions.UseBackupHeader = FALSE; + + if (MountVolume (hwndDlg, *driveNo, volumePath, password, pkcs5_prf, pim, FALSE, FALSE, FALSE, TRUE, &mountOptions, FALSE, TRUE) < 1) + { + *driveNo = -3; + return ERR_VOL_MOUNT_FAILED; + } + return 0; +} + + +/* Gets the map of the clusters that are free and in use on a volume that is to host + a hidden volume. The map is scanned to determine the size of the uninterrupted + area of free space (provided there is any) whose end is aligned with the end + of the volume. The value will then be used to determine the maximum possible size + of the hidden volume. */ +int ScanVolClusterBitmap (HWND hwndDlg, int *driveNo, __int64 nbrClusters, __int64 *nbrFreeClusters) +{ + PVOLUME_BITMAP_BUFFER lpOutBuffer; + STARTING_LCN_INPUT_BUFFER lpInBuffer; + + HANDLE hDevice; + DWORD lBytesReturned; + BYTE rmnd; + wchar_t tmpPath[7] = {L'\\',L'\\',L'.',L'\\', (wchar_t) *driveNo + L'A', L':', 0}; + + DWORD bufLen; + __int64 bitmapCnt; + + hDevice = CreateFile (tmpPath, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + + if (hDevice == INVALID_HANDLE_VALUE) + { + MessageBoxW (hwndDlg, GetString ("CANT_ACCESS_OUTER_VOL"), lpszTitle, ICON_HAND); + goto vcmf_error; + } + + bufLen = (DWORD) (nbrClusters / 8 + 2 * sizeof(LARGE_INTEGER)); + bufLen += 100000 + bufLen/10; // Add reserve + + lpOutBuffer = (PVOLUME_BITMAP_BUFFER) malloc (bufLen); + + if (lpOutBuffer == NULL) + { + MessageBoxW (hwndDlg, GetString ("ERR_MEM_ALLOC"), lpszTitle, ICON_HAND); + goto vcm_error; + } + + lpInBuffer.StartingLcn.QuadPart = 0; + + if ( !DeviceIoControl (hDevice, + FSCTL_GET_VOLUME_BITMAP, + &lpInBuffer, + sizeof(lpInBuffer), + lpOutBuffer, + bufLen, + &lBytesReturned, + NULL)) + { + handleWin32Error (hwndDlg, SRC_POS); + MessageBoxW (hwndDlg, GetString ("CANT_GET_CLUSTER_BITMAP"), lpszTitle, ICON_HAND); + + goto vcm_error; + } + + rmnd = (BYTE) (lpOutBuffer->BitmapSize.QuadPart % 8); + + if ((rmnd != 0) + && ((lpOutBuffer->Buffer[lpOutBuffer->BitmapSize.QuadPart / 8] & ((1 << rmnd)-1) ) != 0)) + { + *nbrFreeClusters = 0; + } + else + { + *nbrFreeClusters = lpOutBuffer->BitmapSize.QuadPart; + bitmapCnt = lpOutBuffer->BitmapSize.QuadPart / 8; + + // Scan the bitmap from the end + while (--bitmapCnt >= 0) + { + if (lpOutBuffer->Buffer[bitmapCnt] != 0) + { + // There might be up to 7 extra free clusters in this byte of the bitmap. + // These are ignored because there is always a cluster reserve added anyway. + *nbrFreeClusters = lpOutBuffer->BitmapSize.QuadPart - ((bitmapCnt + 1) * 8); + break; + } + } + } + + CloseHandle (hDevice); + free(lpOutBuffer); + return 1; + +vcm_error: + CloseHandle (hDevice); + if (lpOutBuffer) free(lpOutBuffer); + +vcmf_error: + return -1; +} + + +// Wipe the hidden OS config flag bits in the MBR +static BOOL WipeHiddenOSCreationConfig (void) +{ + if (!IsHiddenOSRunning()) + { + try + { + WaitCursor(); + finally_do ({ NormalCursor(); }); + + BootEncObj->WipeHiddenOSCreationConfig(); + } + catch (Exception &e) + { + e.Show (MainDlg); + return FALSE; + } + } + + return TRUE; +} + + +// Tasks that need to be performed after the WM_INITDIALOG message for the SYSENC_ENCRYPTION_PAGE dialog is +// handled should be done here (otherwise the UAC prompt causes the GUI to be only half-rendered). +static void AfterSysEncProgressWMInitTasks (HWND hwndDlg) +{ + try + { + switch (SystemEncryptionStatus) + { + case SYSENC_STATUS_ENCRYPTING: + + if (BootEncStatus.ConfiguredEncryptedAreaStart == BootEncStatus.EncryptedAreaStart + && BootEncStatus.ConfiguredEncryptedAreaEnd == BootEncStatus.EncryptedAreaEnd) + { + // The partition/drive had been fully encrypted + + ManageStartupSeqWiz (TRUE, L""); + WipeHiddenOSCreationConfig(); // For extra conservative security + ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); + + Info ("SYSTEM_ENCRYPTION_FINISHED", hwndDlg); + EndMainDlg (MainDlg); + return; + } + else + { + SysEncResume (); + } + + break; + + case SYSENC_STATUS_DECRYPTING: + SysEncResume (); + break; + + default: + + // Unexpected mode here -- fix the inconsistency + + ManageStartupSeqWiz (TRUE, L""); + ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); + EndMainDlg (MainDlg); + InconsistencyResolved (SRC_POS); + return; + } + } + catch (Exception &e) + { + e.Show (hwndDlg); + EndMainDlg (MainDlg); + return; + } + + InitSysEncProgressBar (); + + UpdateSysEncProgressBar (); + + UpdateSysEncControls (); +} + + +// Tasks that need to be performed after the WM_INITDIALOG message is handled must be done here. +// For example, any tasks that may invoke the UAC prompt (otherwise the UAC dialog box would not be on top). +static void AfterWMInitTasks (HWND hwndDlg) +{ + // Note that if bDirectSysEncModeCommand is not SYSENC_COMMAND_NONE, we already have the mutex. + + // SYSENC_COMMAND_DECRYPT has the highest priority because it also performs uninstallation (restores the + // original contents of the first drive cylinder, etc.) so it must be attempted regardless of the phase + // or content of configuration files. + if (bDirectSysEncModeCommand == SYSENC_COMMAND_DECRYPT) + { + if (IsHiddenOSRunning()) + { + Warning ("CANNOT_DECRYPT_HIDDEN_OS", hwndDlg); + AbortProcessSilent(); + } + + // Add the wizard to the system startup sequence + ManageStartupSeqWiz (FALSE, L"/acsysenc"); + + ChangeSystemEncryptionStatus (SYSENC_STATUS_DECRYPTING); + LoadPage (hwndDlg, SYSENC_ENCRYPTION_PAGE); + return; + } + + + if (SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING + || SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING) + { + try + { + BootEncStatus = BootEncObj->GetStatus(); + + if (!BootEncStatus.DriveMounted) + { + if (!BootEncStatus.DeviceFilterActive) + { + // This is an inconsistent state. SystemEncryptionStatus should never be SYSENC_STATUS_ENCRYPTING + // or SYSENC_STATUS_DECRYPTING when the drive filter is not active. Possible causes: 1) corrupted + // or stale config file, 2) corrupted system + + // Fix the inconsistency + ManageStartupSeqWiz (TRUE, L""); + ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); + EndMainDlg (MainDlg); + InconsistencyResolved (SRC_POS); + return; + } + else if (bDirectSysEncMode) + { + // This is an inconsistent state. We have a direct system encryption command, + // SystemEncryptionStatus is SYSENC_STATUS_ENCRYPTING or SYSENC_STATUS_DECRYPTING, the + // system drive is not 'mounted' and drive filter is active. Possible causes: 1) The drive had + // been decrypted in the pre-boot environment. 2) The OS is not located on the lowest partition, + // the drive is to be fully encrypted, but the user rebooted before encryption reached the + // system partition and then pressed Esc in the boot loader screen. 3) Corrupted or stale config + // file. 4) Damaged system. + + Warning ("SYSTEM_ENCRYPTION_SCHEDULED_BUT_PBA_FAILED", hwndDlg); + EndMainDlg (MainDlg); + return; + } + } + } + catch (Exception &e) + { + e.Show (MainDlg); + } + } + + + if (SystemEncryptionStatus != SYSENC_STATUS_PRETEST) + { + // Handle system encryption command line arguments (if we're not in the Pretest phase). + // Note that if bDirectSysEncModeCommand is not SYSENC_COMMAND_NONE, we already have the mutex. + // Also note that SYSENC_COMMAND_DECRYPT is handled above. + + switch (bDirectSysEncModeCommand) + { + case SYSENC_COMMAND_RESUME: + case SYSENC_COMMAND_STARTUP_SEQ_RESUME: + + if (bDirectSysEncModeCommand == SYSENC_COMMAND_STARTUP_SEQ_RESUME + && AskWarnYesNo ("SYSTEM_ENCRYPTION_RESUME_PROMPT", hwndDlg) == IDNO) + { + EndMainDlg (MainDlg); + return; + } + + if (SysEncryptionOrDecryptionRequired ()) + { + if (SystemEncryptionStatus != SYSENC_STATUS_ENCRYPTING + && SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING) + { + // If the config file with status was lost or not written correctly, we + // don't know whether to encrypt or decrypt (but we know that encryption or + // decryption is required). Ask the user to select encryption, decryption, + // or cancel + if (!ResolveUnknownSysEncDirection ()) + { + EndMainDlg (MainDlg); + return; + } + } + + LoadPage (hwndDlg, SYSENC_ENCRYPTION_PAGE); + return; + } + else + { + // Nothing to resume + Warning ("NO_SYS_ENC_PROCESS_TO_RESUME", hwndDlg); + EndMainDlg (MainDlg); + + return; + } + break; + + case SYSENC_COMMAND_ENCRYPT: + + if (SysDriveOrPartitionFullyEncrypted (FALSE)) + { + Info ("SYS_PARTITION_OR_DRIVE_APPEARS_FULLY_ENCRYPTED", hwndDlg); + EndMainDlg (MainDlg); + return; + } + + if (SysEncryptionOrDecryptionRequired ()) + { + // System partition/drive encryption process already initiated but is incomplete. + // If we were encrypting, resume the process directly. If we were decrypting, reverse + // the process and start encrypting. + + ChangeSystemEncryptionStatus (SYSENC_STATUS_ENCRYPTING); + LoadPage (hwndDlg, SYSENC_ENCRYPTION_PAGE); + return; + } + else + { + // Initiate the Pretest preparation phase + if (!SwitchWizardToSysEncMode ()) + { + bDirectSysEncMode = FALSE; + EndMainDlg (MainDlg); + } + return; + } + + break; + + case SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV: + case SYSENC_COMMAND_CREATE_HIDDEN_OS: + + if (!SwitchWizardToHiddenOSMode ()) + { + bDirectSysEncMode = FALSE; + EndMainDlg (MainDlg); + } + return; + } + } + + + if (!bDirectSysEncMode + || bDirectSysEncMode && SystemEncryptionStatus == SYSENC_STATUS_NONE) + { + // Handle system encryption cases where the wizard did not start even though it + // was added to the startup sequence, as well as other weird cases and "leftovers" + + if (SystemEncryptionStatus != SYSENC_STATUS_NONE + && SystemEncryptionStatus != SYSENC_STATUS_PRETEST + && SysEncryptionOrDecryptionRequired ()) + { + // System encryption/decryption had been in progress and did not finish + + if (CreateSysEncMutex ()) // If no other instance is currently taking care of system encryption + { + if (AskWarnYesNo ("SYSTEM_ENCRYPTION_RESUME_PROMPT", hwndDlg) == IDYES) + { + bDirectSysEncMode = TRUE; + ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); + LoadPage (hwndDlg, SYSENC_ENCRYPTION_PAGE); + return; + } + else + CloseSysEncMutex (); + } + } + + else if (SystemEncryptionStatus == SYSENC_STATUS_PRETEST) + { + // System pretest had been in progress but we were not launched during the startup seq + + if (CreateSysEncMutex ()) // If no other instance is currently taking care of system encryption + { + // The pretest has "priority handling" + bDirectSysEncMode = TRUE; + ChangeWizardMode (WIZARD_MODE_SYS_DEVICE); + + /* Do not return yet -- the principal pretest handler is below. */ + } + } + + else if ((SystemEncryptionStatus == SYSENC_STATUS_NONE || SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING) + && !BootEncStatus.DriveEncrypted + && (BootEncStatus.DriveMounted || BootEncStatus.VolumeHeaderPresent)) + { + // The pretest may have been in progress but we can't be sure (it is not in the config file). + // Another possibility is that the user had finished decrypting the drive, but the config file + // was not correctly updated. In both cases the best thing we can do is remove the header and + // deinstall. Otherwise, the result might be some kind of deadlock. + + if (CreateSysEncMutex ()) // If no other instance is currently taking care of system encryption + { + WaitCursor (); + + ForceRemoveSysEnc(); + + InconsistencyResolved (SRC_POS); + + NormalCursor(); + CloseSysEncMutex (); + } + } + } + + if (bDirectSysEncMode && CreateSysEncMutex ()) + { + // We were launched either by Mount or by the system (startup sequence). Most of such cases should have + // been handled above already. Here we handle only the pretest phase (which can also be a hidden OS + // creation phase actually) and possible inconsistencies. + + switch (SystemEncryptionStatus) + { + case SYSENC_STATUS_PRETEST: + { + unsigned int hiddenOSCreationPhase = DetermineHiddenOSCreationPhase(); + + bHiddenOS = (hiddenOSCreationPhase != TC_HIDDEN_OS_CREATION_PHASE_NONE); + + // Evaluate the results of the system encryption pretest (or of the hidden OS creation process) + + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (hwndDlg); + Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS", hwndDlg); + EndMainDlg (MainDlg); + return; + } + + if (BootEncStatus.DriveMounted) + { + /* Pretest successful or hidden OS has been booted during the process of hidden OS creation. */ + + switch (hiddenOSCreationPhase) + { + case TC_HIDDEN_OS_CREATION_PHASE_NONE: + + // Pretest successful (or the hidden OS has been booted for the first time since the user started installing a new decoy OS) + + if (IsHiddenOSRunning()) + { + // The hidden OS has been booted for the first time since the user started installing a + // new decoy OS (presumably, our MBR config flags have been erased). + + // As for things we are responsible for, the process of hidden OS creation is completed + // (the rest is up to the user). + + ManageStartupSeqWiz (TRUE, L""); + ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); + + EndMainDlg (MainDlg); + + return; + } + + // Pretest successful (no hidden operating system involved) + + LoadPage (hwndDlg, SYSENC_PRETEST_RESULT_PAGE); + return; + + case TC_HIDDEN_OS_CREATION_PHASE_WIPING: + + // Hidden OS has been booted when we are supposed to wipe the original OS + + LoadPage (hwndDlg, SYSENC_HIDDEN_OS_INITIAL_INFO_PAGE); + return; + + case TC_HIDDEN_OS_CREATION_PHASE_WIPED: + + // Hidden OS has been booted and the original OS wiped. Now the user is required to install a new, decoy, OS. + + TextInfoDialogBox (TC_TBXID_DECOY_OS_INSTRUCTIONS); + + EndMainDlg (MainDlg); + return; + + default: + + // Unexpected/unknown status + ReportUnexpectedState (SRC_POS); + EndMainDlg (MainDlg); + return; + } + } + else + { + BOOL bAnswerTerminate = FALSE, bAnswerRetry = FALSE; + + /* Pretest failed + or hidden OS cloning has been interrupted (and non-hidden OS is running) + or wiping of the original OS has not been started (and non-hidden OS is running) */ + + if (hiddenOSCreationPhase == TC_HIDDEN_OS_CREATION_PHASE_NONE) + { + // Pretest failed (no hidden operating system involved) + + if (AskWarnYesNo ("BOOT_PRETEST_FAILED_RETRY", hwndDlg) == IDYES) + { + // User wants to retry the pretest + bAnswerTerminate = FALSE; + bAnswerRetry = TRUE; + } + else + { + // User doesn't want to retry the pretest + bAnswerTerminate = TRUE; + bAnswerRetry = FALSE; + } + } + else + { + // Hidden OS cloning was interrupted or wiping of the original OS has not been started + + char *tmpStr[] = {0, + hiddenOSCreationPhase == TC_HIDDEN_OS_CREATION_PHASE_WIPING ? "OS_WIPING_NOT_FINISHED_ASK" : "HIDDEN_OS_CREATION_NOT_FINISHED_ASK", + "HIDDEN_OS_CREATION_NOT_FINISHED_CHOICE_RETRY", + "HIDDEN_OS_CREATION_NOT_FINISHED_CHOICE_TERMINATE", + "HIDDEN_OS_CREATION_NOT_FINISHED_CHOICE_ASK_LATER", + 0}; + + switch (AskMultiChoice ((void **) tmpStr, FALSE, hwndDlg)) + { + case 1: + // User wants to restart and continue/retry + bAnswerTerminate = FALSE; + bAnswerRetry = TRUE; + break; + + case 2: + // User doesn't want to retry but wants to terminate the entire process of hidden OS creation + bAnswerTerminate = TRUE; + bAnswerRetry = FALSE; + break; + + default: + // User doesn't want to do anything now + bAnswerTerminate = FALSE; + bAnswerRetry = FALSE; + } + } + + + if (bAnswerRetry) + { + // User wants to restart and retry the pretest (or hidden OS creation) + + // We re-register the driver for boot because the user may have selected + // "Last Known Good Configuration" from the Windows boot menu. + // Note that we need to do this even when creating a hidden OS (because + // the hidden OS needs our boot driver and it will be a clone of this OS). + try + { + BootEncObj->RegisterBootDriver (bHiddenOS ? true : false); + } + catch (Exception &e) + { + e.Show (NULL); + } + + if (AskWarnYesNo ("CONFIRM_RESTART", hwndDlg) == IDYES) + { + EndMainDlg (MainDlg); + + try + { + BootEncObj->RestartComputer (); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + + return; + } + + EndMainDlg (MainDlg); + return; + } + else if (bAnswerTerminate) + { + // User doesn't want to retry pretest (or OS cloning), but to terminate the entire process + + try + { + BootEncObj->Deinstall (true); + } + catch (Exception &e) + { + e.Show (hwndDlg); + AbortProcessSilent(); + } + + ManageStartupSeqWiz (TRUE, L""); + ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); + EndMainDlg (MainDlg); + return; + } + else + { + // User doesn't want to take any action now + + AbortProcessSilent(); + } + } + } + break; + + default: + + // Unexpected progress status -- fix the inconsistency + + ManageStartupSeqWiz (TRUE, L""); + ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); + EndMainDlg (MainDlg); + InconsistencyResolved (SRC_POS); + return; + } + } + else + { + if (DirectDeviceEncMode) + { + SwitchWizardToNonSysDeviceMode(); + return; + } + + if (DirectPromptNonSysInplaceEncResumeMode + && !bInPlaceEncNonSysPending) + { + // This instance of the wizard has been launched via the system startup sequence to prompt for resume of + // a non-system in-place encryption/decryption process. However, no config file indicates that any such process + // has been interrupted. This inconsistency may occur, for example, when the process is finished + // but the wizard is not removed from the startup sequence because system encryption is in progress. + // Therefore, we remove it from the startup sequence now if possible. + + if (!IsNonInstallMode () && SystemEncryptionStatus == SYSENC_STATUS_NONE) + ManageStartupSeqWiz (TRUE, L""); + + AbortProcessSilent (); + } + + BOOL bDecrypt = FALSE; + + if (DirectNonSysInplaceDecStartMode) + { + SwitchWizardToNonSysInplaceDecStartMode (szFileName); + return; + } + else if (DirectNonSysInplaceEncResumeMode || DirectNonSysInplaceDecResumeMode) + { + SwitchWizardToNonSysInplaceEncResumeMode (DirectNonSysInplaceDecResumeMode); + return; + } + else if (DirectPromptNonSysInplaceEncResumeMode) + { + if (NonSysInplaceEncInProgressElsewhere ()) + AbortProcessSilent (); + + if (AskNonSysInPlaceEncryptionResume(hwndDlg, &bDecrypt) == IDYES) + SwitchWizardToNonSysInplaceEncResumeMode(bDecrypt); + else + AbortProcessSilent (); + + return; + } + else if (bInPlaceEncNonSysPending + && !NonSysInplaceEncInProgressElsewhere () + && AskNonSysInPlaceEncryptionResume(hwndDlg, &bDecrypt) == IDYES) + { + SwitchWizardToNonSysInplaceEncResumeMode(bDecrypt); + return; + } + + LoadPage (hwndDlg, INTRO_PAGE); + } +} + +int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpszCommandLine, int nCmdShow) +{ + int status; + atexit (localcleanup); + + VirtualLock (&volumePassword, sizeof(volumePassword)); + VirtualLock (szVerify, sizeof(szVerify)); + VirtualLock (szRawPassword, sizeof(szRawPassword)); + VirtualLock (&volumePim, sizeof(volumePim)); + VirtualLock (&CmdVolumePassword, sizeof (CmdVolumePassword)); + + VirtualLock (MasterKeyGUIView, sizeof(MasterKeyGUIView)); + VirtualLock (HeaderKeyGUIView, sizeof(HeaderKeyGUIView)); + + VirtualLock (randPool, sizeof(randPool)); + VirtualLock (lastRandPool, sizeof(lastRandPool)); + VirtualLock (outRandPoolDispBuffer, sizeof(outRandPoolDispBuffer)); + VirtualLock (&mouseEntropyGathered, sizeof(mouseEntropyGathered)); + VirtualLock (&mouseEventsInitialCount, sizeof(mouseEventsInitialCount)); + VirtualLock (maskRandPool, sizeof(maskRandPool)); + + VirtualLock (&szFileName, sizeof(szFileName)); + VirtualLock (&szDiskFile, sizeof(szDiskFile)); + + DetectX86Features (); + + try + { + BootEncObj = new BootEncryption (NULL); + } + catch (Exception &e) + { + e.Show (NULL); + } + + if (BootEncObj == NULL) + AbortProcess ("INIT_SYS_ENC"); + + InitApp (hInstance, lpszCommandLine); + + // Write block size greater than 64 KB causes a performance drop when writing to files on XP/Vista + if (!IsOSAtLeast (WIN_7)) + FormatWriteBufferSize = 64 * 1024; + +#if TC_MAX_VOLUME_SECTOR_SIZE > 64 * 1024 +#error TC_MAX_VOLUME_SECTOR_SIZE > 64 * 1024 +#endif + + nPbar = IDC_PROGRESS_BAR; + + if (Randinit ()) + { + DWORD dwLastError = GetLastError (); + wchar_t szTmp[4096]; + if (CryptoAPILastError == ERROR_SUCCESS) + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("INIT_RAND"), SRC_POS, dwLastError); + else + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CAPI_RAND"), SRC_POS, CryptoAPILastError); + AbortProcessDirect (szTmp); + } + + RegisterRedTick(hInstance); + + /* Allocate, dup, then store away the application title */ + lpszTitle = GetString ("IDD_VOL_CREATION_WIZARD_DLG"); + + status = DriverAttach (); + if (status != 0) + { + if (status == ERR_OS_ERROR) + handleWin32Error (NULL, SRC_POS); + else + handleError (NULL, status, SRC_POS); + + AbortProcess ("NODRIVER"); + } + + if (!AutoTestAlgorithms()) + AbortProcess ("ERR_SELF_TESTS_FAILED"); + + /* Create the main dialog box */ + DialogBoxParamW (hInstance, MAKEINTRESOURCEW (IDD_VOL_CREATION_WIZARD_DLG), NULL, (DLGPROC) MainDialogProc, + (LPARAM)lpszCommandLine); + + FinalizeApp (); + return 0; +} + + +static DWORD GetFormatSectorSize () +{ + if (!bDevice) + return TC_SECTOR_SIZE_FILE_HOSTED_VOLUME; + + DISK_GEOMETRY geometry; + + if (!GetDriveGeometry (szDiskFile, &geometry)) + { + handleWin32Error (MainDlg, SRC_POS); + AbortProcessSilent(); + } + + return geometry.BytesPerSector; +} diff --git a/src/Format/Tcformat.h b/src/Format/Tcformat.h index e6d64a08..c45e6916 100644 --- a/src/Format/Tcformat.h +++ b/src/Format/Tcformat.h @@ -1,109 +1,109 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Common/Common.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define NBR_KEY_BYTES_TO_DISPLAY 16 -#define KEY_GUI_VIEW_SIZE 64 // Max characters of the key hex dump to display - -enum timer_ids -{ - TIMER_ID_RANDVIEW = 0xff, - TIMER_ID_SYSENC_PROGRESS, - TIMER_ID_NONSYS_INPLACE_ENC_PROGRESS, - TIMER_ID_WIPE_PROGRESS, - TIMER_ID_SYSENC_DRIVE_ANALYSIS_PROGRESS, - TIMER_ID_KEYB_LAYOUT_GUARD -}; - -static void localcleanup ( void ); -static void LoadSettings ( HWND hwndDlg ); -static void SaveSettings ( HWND hwndDlg ); -static void EndMainDlg ( HWND hwndDlg ); -void ComboSelChangeEA ( HWND hwndDlg ); -static void VerifySizeAndUpdate ( HWND hwndDlg , BOOL bUpdate ); -static void __cdecl sysEncDriveAnalysisThread (void *hwndDlgArg); -static void __cdecl volTransformThreadFunction ( void *hwndDlg ); -static void LoadPage ( HWND hwndDlg , int nPageNo ); -__int64 PrintFreeSpace ( HWND hwndTextBox , wchar_t *lpszDrive , PLARGE_INTEGER lDiskFree ); -void DisplaySizingErrorText ( HWND hwndTextBox ); -void EnableDisableFileNext ( HWND hComboBox , HWND hMainButton ); -BOOL QueryFreeSpace ( HWND hwndDlg , HWND hwndTextBox , BOOL display ); -static BOOL FinalPreTransformPrompts (void); -void UpdateLastDialogId (void); -void HandleOldAssignedDriveLetter (void); -void AddCipher ( HWND hComboBox , char *lpszCipher , int nCipher ); -BOOL CALLBACK PageDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); -BOOL CALLBACK MainDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); -void ExtractCommandLine ( HWND hwndDlg , wchar_t *lpszCommandLine ); -void DisplayRandPool (HWND hwndDlg, HWND hPoolDisplay, BOOL bShow); -void DisplayPortionsOfKeys (HWND headerKeyHandle, HWND masterKeyHandle, wchar_t *headerKeyStr, wchar_t *masterKeyStr, BOOL hideKeys); -int DetermineMaxHiddenVolSize (HWND hwndDlg); -BOOL IsSparseFile (HWND hwndDlg); -BOOL GetFileVolSize (HWND hwndDlg, unsigned __int64 *size); -BOOL SwitchWizardToSysEncMode (void); -void SwitchWizardToFileContainerMode (void); -static BOOL ResolveUnknownSysEncDirection (void); -static BOOL WipeHiddenOSCreationConfig (void); -static void AfterWMInitTasks (HWND hwndDlg); -static void AfterSysEncProgressWMInitTasks (HWND hwndDlg); -static void InitSysEncProgressBar (void); -static void InitNonSysInplaceEncProgressBar (void); -static void UpdateNonSysInplaceEncProgressBar (void); -static BOOL SysEncInEffect (void); -static BOOL CreatingHiddenSysVol(void); -static void NonSysInplaceEncPause (void); -static void NonSysInplaceEncResume (void); -void ShowNonSysInPlaceEncUIStatus (void); -void UpdateNonSysInPlaceEncControls (void); -int MountHiddenVolHost ( HWND hwndDlg, wchar_t *volumePath, int *driveNo, Password *password, int pkcs5_prf, int pim, BOOL bReadOnly ); -int AnalyzeHiddenVolumeHost (HWND hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *pnbrFreeClusters); -int ScanVolClusterBitmap ( HWND hwndDlg, int *driveNo, __int64 nbrClusters, __int64 *nbrFreeClusters); -static void WipeStart (void); -static void WipeAbort (void); -static void UpdateWipeProgressBar (void); -static void InitWipeProgressBar (void); -static void UpdateWipeControls (void); -static DWORD GetFormatSectorSize (); - -extern BOOL showKeys; -extern volatile HWND hMasterKey; -extern volatile HWND hHeaderKey; -extern volatile BOOL bHiddenVolHost; -extern volatile BOOL bHiddenVolDirect; -extern BOOL bRemovableHostDevice; -extern BOOL bWarnDeviceFormatAdvanced; -extern HWND hCurPage; -extern HWND hProgressBar; -extern volatile BOOL bVolTransformThreadCancel; -extern volatile BOOL bInPlaceEncNonSysResumed; -extern volatile BOOL bFirstNonSysInPlaceEncResumeDone; -extern volatile BOOL bInPlaceEncNonSys; -extern volatile BOOL bInPlaceDecNonSys; -extern __int64 NonSysInplaceEncBytesDone; -extern __int64 NonSysInplaceEncTotalSize; -extern int nPbar; -extern volatile int WizardMode; -extern volatile BOOL bInPlaceEncNonSysResumed; - -extern wchar_t HeaderKeyGUIView [KEY_GUI_VIEW_SIZE]; -extern wchar_t MasterKeyGUIView [KEY_GUI_VIEW_SIZE]; -extern volatile int NonSysInplaceEncStatus; - -#ifdef __cplusplus -} -#endif +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Common/Common.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define NBR_KEY_BYTES_TO_DISPLAY 16 +#define KEY_GUI_VIEW_SIZE 64 // Max characters of the key hex dump to display + +enum timer_ids +{ + TIMER_ID_RANDVIEW = 0xff, + TIMER_ID_SYSENC_PROGRESS, + TIMER_ID_NONSYS_INPLACE_ENC_PROGRESS, + TIMER_ID_WIPE_PROGRESS, + TIMER_ID_SYSENC_DRIVE_ANALYSIS_PROGRESS, + TIMER_ID_KEYB_LAYOUT_GUARD +}; + +static void localcleanup ( void ); +static void LoadSettings ( HWND hwndDlg ); +static void SaveSettings ( HWND hwndDlg ); +static void EndMainDlg ( HWND hwndDlg ); +void ComboSelChangeEA ( HWND hwndDlg ); +static void VerifySizeAndUpdate ( HWND hwndDlg , BOOL bUpdate ); +static void __cdecl sysEncDriveAnalysisThread (void *hwndDlgArg); +static void __cdecl volTransformThreadFunction ( void *hwndDlg ); +static void LoadPage ( HWND hwndDlg , int nPageNo ); +__int64 PrintFreeSpace ( HWND hwndTextBox , wchar_t *lpszDrive , PLARGE_INTEGER lDiskFree ); +void DisplaySizingErrorText ( HWND hwndTextBox ); +void EnableDisableFileNext ( HWND hComboBox , HWND hMainButton ); +BOOL QueryFreeSpace ( HWND hwndDlg , HWND hwndTextBox , BOOL display ); +static BOOL FinalPreTransformPrompts (void); +void UpdateLastDialogId (void); +void HandleOldAssignedDriveLetter (void); +void AddCipher ( HWND hComboBox , char *lpszCipher , int nCipher ); +BOOL CALLBACK PageDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); +BOOL CALLBACK MainDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); +void ExtractCommandLine ( HWND hwndDlg , wchar_t *lpszCommandLine ); +void DisplayRandPool (HWND hwndDlg, HWND hPoolDisplay, BOOL bShow); +void DisplayPortionsOfKeys (HWND headerKeyHandle, HWND masterKeyHandle, wchar_t *headerKeyStr, wchar_t *masterKeyStr, BOOL hideKeys); +int DetermineMaxHiddenVolSize (HWND hwndDlg); +BOOL IsSparseFile (HWND hwndDlg); +BOOL GetFileVolSize (HWND hwndDlg, unsigned __int64 *size); +BOOL SwitchWizardToSysEncMode (void); +void SwitchWizardToFileContainerMode (void); +static BOOL ResolveUnknownSysEncDirection (void); +static BOOL WipeHiddenOSCreationConfig (void); +static void AfterWMInitTasks (HWND hwndDlg); +static void AfterSysEncProgressWMInitTasks (HWND hwndDlg); +static void InitSysEncProgressBar (void); +static void InitNonSysInplaceEncProgressBar (void); +static void UpdateNonSysInplaceEncProgressBar (void); +static BOOL SysEncInEffect (void); +static BOOL CreatingHiddenSysVol(void); +static void NonSysInplaceEncPause (void); +static void NonSysInplaceEncResume (void); +void ShowNonSysInPlaceEncUIStatus (void); +void UpdateNonSysInPlaceEncControls (void); +int MountHiddenVolHost ( HWND hwndDlg, wchar_t *volumePath, int *driveNo, Password *password, int pkcs5_prf, int pim, BOOL bReadOnly ); +int AnalyzeHiddenVolumeHost (HWND hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *pnbrFreeClusters); +int ScanVolClusterBitmap ( HWND hwndDlg, int *driveNo, __int64 nbrClusters, __int64 *nbrFreeClusters); +static void WipeStart (void); +static void WipeAbort (void); +static void UpdateWipeProgressBar (void); +static void InitWipeProgressBar (void); +static void UpdateWipeControls (void); +static DWORD GetFormatSectorSize (); + +extern BOOL showKeys; +extern volatile HWND hMasterKey; +extern volatile HWND hHeaderKey; +extern volatile BOOL bHiddenVolHost; +extern volatile BOOL bHiddenVolDirect; +extern BOOL bRemovableHostDevice; +extern BOOL bWarnDeviceFormatAdvanced; +extern HWND hCurPage; +extern HWND hProgressBar; +extern volatile BOOL bVolTransformThreadCancel; +extern volatile BOOL bInPlaceEncNonSysResumed; +extern volatile BOOL bFirstNonSysInPlaceEncResumeDone; +extern volatile BOOL bInPlaceEncNonSys; +extern volatile BOOL bInPlaceDecNonSys; +extern __int64 NonSysInplaceEncBytesDone; +extern __int64 NonSysInplaceEncTotalSize; +extern int nPbar; +extern volatile int WizardMode; +extern volatile BOOL bInPlaceEncNonSysResumed; + +extern wchar_t HeaderKeyGUIView [KEY_GUI_VIEW_SIZE]; +extern wchar_t MasterKeyGUIView [KEY_GUI_VIEW_SIZE]; +extern volatile int NonSysInplaceEncStatus; + +#ifdef __cplusplus +} +#endif diff --git a/src/License.html b/src/License.html index e2c48145..c839cd05 100644 --- a/src/License.html +++ b/src/License.html @@ -1,179 +1,179 @@ - - - - -VeraCrypt License - - - -VeraCrypt License
-
-Software distributed under this license is distributed on an "AS IS" BASIS WITHOUT WARRANTIES OF ANY KIND. THE AUTHORS AND DISTRIBUTORS OF THE SOFTWARE DISCLAIM ANY LIABILITY. ANYONE WHO USES, COPIES, MODIFIES, OR (RE)DISTRIBUTES ANY PART OF THE SOFTWARE IS, BY SUCH ACTION(S), ACCEPTING AND AGREEING TO BE BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE SOFTWARE, NOR ANY PART(S) THEREOF.
-
-VeraCrypt is governed by the TrueCrypt License version 3.0, a verbatim copy of this version of the TrueCrypt License can be found below. -
-This license does not grant you rights to use any contributors' name, logo, or trademarks, including IDRIX, VeraCrypt and all derivative names. For example, the following names are not allowed: VeraCrypt, VeraCrypt+, VeraCrypt Professional, iVeraCrypt, etc. Nor any other names confusingly similar to the name VeraCrypt (e.g., Vera-Crypt, Vera Crypt, VerKrypt, etc). -
- ____________________________________________________________
-
-TrueCrypt License Version 3.0
-
-Software distributed under this license is distributed on an "AS IS" BASIS WITHOUT WARRANTIES OF ANY KIND. THE AUTHORS AND DISTRIBUTORS OF THE SOFTWARE DISCLAIM ANY LIABILITY. ANYONE WHO USES, COPIES, MODIFIES, OR (RE)DISTRIBUTES ANY PART OF THE SOFTWARE IS, BY SUCH ACTION(S), ACCEPTING AND AGREEING TO BE BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE SOFTWARE, NOR ANY PART(S) THEREOF.
-
-
I. Definitions
-
1. "This Product" means the work (including, but not limited to, source code, graphics, texts, and accompanying files) made available under and governed by this version of this license ("License"), as may be indicated by, but is not limited to, copyright notice(s) attached to or included in the work.
-
2. "You" means (and "Your" refers to) an individual or a legal entity (e.g., a non-profit organization, commercial organization, government agency, etc.) exercising permissions granted by this License.
-
3. "Modification" means (and "modify" refers to) any alteration of This Product, including, but not limited to, addition to or deletion from the substance or structure of This Product, translation into another language, repackaging, alteration or removal of any file included with This Product, and addition of any new files to This Product.
-
-4. "Your Product" means This Product modified by You, or any work You derive from (or base on) any part of This Product. In addition, "Your Product" means any work in which You include any (modified or unmodified) portion of This Product. However, if the work in which you include it is an aggregate software distribution (such as an operating system distribution or a cover CD-ROM of a magazine) containing multiple separate products, then the term "Your Product" includes only those products (in the aggregate software distribution) that use, include, or depend on a modified or unmodified version of This Product (and the term "Your Product" does not include the whole aggregate software distribution). For the purposes of this License, a product suite consisting of two or more products is considered a single product (operating system distributions and cover media of magazines are not considered product suites).
-
5. "Distribution" means (and "distribute" refers to), regardless of means or methods, conveyance, transfer, providing, or making available of This/Your Product or portions thereof to third parties (including, but not limited to, making This/Your Product, or portions thereof, available for download to third parties, whether or not any third party has downloaded the product, or any portion thereof, made available for download).
-

-
II. Use, Copying, and Distribution of This Product
-
-1. Provided that You comply with all applicable terms and conditions of this License, You may make copies of This Product (unmodified) and distribute copies of This Product (unmodified) that are not included in another product forming Your Product (except as permitted under Chapter III). Note: For terms and conditions for copying and distribution of modified versions of This Product, see Chapter III.
-
2. Provided that You comply with all applicable terms and conditions of this License, You may use This Product freely (see also Chapter III) on any number of computers/systems for non-commercial and/or commercial purposes.
-

-
III. Modification, Derivation, and Inclusion in Other Products
-
-1. If all conditions specified in the following paragraphs in this Chapter (III) are met (for exceptions, see Section III.2) and if You comply with all other applicable terms and conditions of this License, You may modify This Product (thus forming Your Product), derive new works from This Product or portions thereof (thus forming Your Product), include This Product or portions thereof in another product (thus forming Your Product, unless defined otherwise in Chapter I), and You may use (for non-commercial and/or commercial purposes), copy, and/or distribute Your Product.
-
-
    -
  1. The name of Your Product (or of Your modified version of This Product) must not contain the name TrueCrypt (for example, the following names are not allowed: TrueCrypt, TrueCrypt+, TrueCrypt Professional, iTrueCrypt, etc.) nor any other names confusingly similar to the name TrueCrypt (e.g., True-Crypt, True Crypt, TruKrypt, etc.)
    -
    - All occurrences of the name TrueCrypt that could reasonably be considered to identify Your Product must be removed from Your Product and from any associated materials. Logo(s) included in (or attached to) Your Product (and in/to associated materials) must not incorporate and must not be confusingly similar to any of the TrueCrypt logos (including, but not limited to, the non-textual logo consisting primarily of a key in stylized form) or portion(s) thereof. All graphics contained in This Product (logos, icons, etc.) must be removed from Your Product (or from Your modified version of This Product) and from any associated materials.
    -
    -
  2. -
  3. The following phrases must be removed from Your Product and from any associated materials, except the text of this License: "A TrueCrypt Foundation Release", "Released by TrueCrypt Foundation", "This is a TrueCrypt Foundation release."
    -
    -
  4. -
  5. Phrase "Based on TrueCrypt, freely available at http://www.truecrypt.org/" must be displayed by Your Product (if technically feasible) and contained in its documentation. Alternatively, if This Product or its portion You included in Your Product constitutes only a minor portion of Your Product, phrase "Portions of this product are based in part on TrueCrypt, freely available at http://www.truecrypt.org/" may be displayed instead. In each of the cases mentioned above in this paragraph, "http://www.truecrypt.org/" must be a hyperlink (if technically feasible) pointing to http://www.truecrypt.org/ and You may freely choose the location within the user interface (if there is any) of Your Product (e.g., an "About" window, etc.) and the way in which Your Product will display the respective phrase.
    -
    - Your Product (and any associated materials, e.g., the documentation, the content of the official web site of Your Product, etc.) must not present any Internet address containing the domain name truecrypt.org (or any domain name that forwards to the domain name truecrypt.org) in a manner that might suggest that it is where information about Your Product may be obtained or where bugs found in Your Product may be reported or where support for Your Product may be available or otherwise attempt to indicate that the domain name truecrypt.org is associated with Your Product.
    -
    -
  6. -
  7. The complete source code of Your Product must be freely and publicly available (for exceptions, see Section III.2) at least until You cease to distribute Your Product. This condition can be met in one or both of the following ways: (i) You include the complete source code of Your Product with every copy of Your Product that You make and distribute and You make all such copies of Your Product available to the general public free of charge, and/or (ii) You include information (valid and correct at least until You cease to distribute Your Product) about where the complete source code of Your Product can be obtained free of charge (e.g., an Internet address) or for a reasonable reproduction fee with every copy of Your Product that You make and distribute and, if there is a web site officially associated with Your Product, You include the aforementioned information about the source code on a freely and publicly accessible web page to which such web site links via an easily viewable hyperlink (at least until You cease to distribute Your Product).
    -
    -The source code of Your Product must not be deliberately obfuscated and it must not be in an intermediate form (e.g., the output of a preprocessor). Source code means the preferred form in which a programmer would usually modify the program.
    -
    - Portions of the source code of Your Product not contained in This Product (e.g., portions added by You in creating Your Product, whether created by You or by third parties) must be available under license(s) that (however, see also Subsection III.1.e) allow(s) anyone to modify and derive new works from the portions of the source code that are not contained in This Product and to use, copy, and redistribute such modifications and/or derivative works. The license(s) must be perpetual, non-exclusive, royalty-free, no-charge, and worldwide, and must not invalidate, weaken, restrict, interpret, amend, modify, interfere with or otherwise affect any part, term, provision, or clause of this License. The text(s) of the license(s) must be included with every copy of Your Product that You make and distribute.

    -
  8. -
  9. You must not change the license terms of This Product in any way (adding any new terms is considered changing the license terms even if the original terms are retained), which means, e.g., that no part of This Product may be put under another license. You must keep intact all the legal notices contained in the source code files. You must include the following items with every copy of Your Product that You make and distribute: a clear and conspicuous notice stating that Your Product or portion(s) thereof is/are governed by this version of the TrueCrypt License, a verbatim copy of this version of the TrueCrypt License (as contained herein), a clear and conspicuous notice containing information about where the included copy of the License can be found, and an appropriate copyright notice.
    -
  10. -
-2. You are not obligated to comply with Subsection III.1.d if Your Product is not distributed (i.e., Your Product is available only to You).
-
-
-
- IV. Disclaimer of Liability, Disclaimer of Warranty, Indemnification
-
- You expressly acknowledge and agree to the following:
-
- 1. IN NO EVENT WILL ANY (CO)AUTHOR OF THIS PRODUCT, OR ANY APPLICABLE INTELLECTUAL-PROPERTY OWNER, OR ANY OTHER PARTY WHO MAY COPY AND/OR (RE)DISTRIBUTE THIS PRODUCT OR PORTIONS THEREOF, AS MAY BE PERMITTED HEREIN, BE LIABLE TO YOU OR TO ANY OTHER PARTY FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, ANY DIRECT, INDIRECT, GENERAL, SPECIAL, INCIDENTAL, PUNITIVE, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, CORRUPTION OR LOSS OF DATA, ANY LOSSES SUSTAINED BY YOU OR THIRD PARTIES, A FAILURE OF THIS PRODUCT TO OPERATE WITH ANY OTHER PRODUCT, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR BUSINESS INTERRUPTION), WHETHER IN CONTRACT, STRICT LIABILITY, TORT (INCLUDING, BUT NOT LIMITED TO, NEGLIGENCE) OR OTHERWISE, ARISING OUT OF THE USE, COPYING, MODIFICATION, OR (RE)DISTRIBUTION OF THIS PRODUCT (OR A PORTION THEREOF) OR OF YOUR PRODUCT (OR A PORTION THEREOF), OR INABILITY TO USE THIS PRODUCT (OR A PORTION THEREOF), EVEN IF SUCH DAMAGES (OR THE POSSIBILITY OF SUCH DAMAGES) ARE/WERE PREDICTABLE OR KNOWN TO ANY (CO)AUTHOR, INTELLECTUAL-PROPERTY OWNER, OR ANY OTHER PARTY.
-
- 2. THIS PRODUCT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THIS PRODUCT IS WITH YOU. SHOULD THIS PRODUCT PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
-
- 3. THIS PRODUCT MAY INCORPORATE IMPLEMENTATIONS OF CRYPTOGRAPHIC ALGORITHMS THAT ARE REGULATED (E.G., SUBJECT TO EXPORT/IMPORT CONTROL REGULATIONS) OR ILLEGAL IN SOME COUNTRIES. IT IS SOLELY YOUR RESPONSIBILITY TO VERIFY THAT IT IS LEGAL TO IMPORT AND/OR (RE)EXPORT AND/OR USE THIS PRODUCT (OR PORTIONS THEREOF) IN COUNTRIES WHERE YOU INTEND TO USE IT AND/OR TO WHICH YOU INTEND TO IMPORT IT AND/OR FROM WHICH YOU INTEND TO EXPORT IT, AND IT IS SOLELY YOUR RESPONSIBILITY TO COMPLY WITH ANY APPLICABLE REGULATIONS, RESTRICTIONS, AND LAWS.
-
-4. YOU SHALL INDEMNIFY, DEFEND AND HOLD ALL (CO)AUTHORS OF THIS PRODUCT, AND APPLICABLE INTELLECTUAL-PROPERTY OWNERS, HARMLESS FROM AND AGAINST ANY AND ALL LIABILITY, DAMAGES, LOSSES, SETTLEMENTS, PENALTIES, FINES, COSTS, EXPENSES (INCLUDING REASONABLE ATTORNEYS' FEES), DEMANDS, CAUSES OF ACTION, CLAIMS, ACTIONS, PROCEEDINGS, AND SUITS, DIRECTLY RELATED TO OR ARISING OUT OF YOUR USE, INABILITY TO USE, COPYING, (RE)DISTRIBUTION, IMPORT AND/OR (RE)EXPORT OF THIS PRODUCT (OR PORTIONS THEREOF) AND/OR YOUR BREACH OF ANY TERM OF THIS LICENSE.
-
-
-
- V. Trademarks
-
- This License does not grant permission to use trademarks associated with (or applying to) This Product, except for fair use as defined by applicable law and except for use expressly permitted or required by this License. Any attempt otherwise to use trademarks associated with (or applying to) This Product automatically and immediately terminates Your rights under This License and may constitute trademark infringement (which may be prosecuted).
-
-
-
- VI. General Terms and Conditions, Miscellaneous Provisions
-
- 1. ANYONE WHO USES AND/OR COPIES AND/OR MODIFIES AND/OR CREATES DERIVATIVE WORKS OF AND/OR (RE)DISTRIBUTES THIS PRODUCT, OR ANY PORTION(S) THEREOF, IS, BY SUCH ACTION(S), AGREEING TO BE BOUND BY AND ACCEPTING ALL TERMS AND CONDITIONS OF THIS LICENSE (AND THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS LICENSE). IF YOU DO NOT ACCEPT (AND AGREE TO BE BOUND BY) ALL TERMS AND CONDITIONS OF THIS LICENSE, DO NOT USE, COPY, MODIFY, CREATE DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY PORTION(S) THEREOF.
-
-2. YOU MAY NOT USE, MODIFY, COPY, CREATE DERIVATIVE WORKS OF, (RE)DISTRIBUTE, OR SUBLICENSE THIS PRODUCT, OR PORTION(S) THEREOF, EXCEPT AS EXPRESSLY PROVIDED IN THIS LICENSE (EVEN IF APPLICABLE LAW GIVES YOU MORE RIGHTS). ANY ATTEMPT (EVEN IF PERMITTED BY APPLICABLE LAW) OTHERWISE TO USE, MODIFY, COPY, CREATE DERIVATIVE WORKS OF, (RE)DISTRIBUTE, OR SUBLICENSE THIS PRODUCT, OR PORTION(S) THEREOF, AUTOMATICALLY AND IMMEDIATELY TERMINATES YOUR RIGHTS UNDER THIS LICENSE AND CAN CONSTITUTE COPYRIGHT INFRINGEMENT (WHICH MAY BE PROSECUTED). ANY CONDITIONS AND RESTRICTIONS CONTAINED IN THIS LICENSE ARE ALSO LIMITATIONS ON THE SCOPE OF THIS LICENSE AND ALSO DEFINE THE SCOPE OF YOUR RIGHTS UNDER THIS LICENSE. YOUR FAILURE TO COMPLY WITH THE TERMS AND CONDITIONS OF THIS LICENSE OR FAILURE TO PERFORM ANY APPLICABLE OBLIGATION IMPOSED BY THIS LICENSE AUTOMATICALLY AND IMMEDIATELY TERMINATES YOUR RIGHTS UNDER THIS LICENSE AND CAN CAUSE OR BE CONSIDERED COPYRIGHT INFRINGEMENT (WHICH MAY BE PROSECUTED). NOTHING IN THIS LICENSE SHALL IMPLY OR BE CONSTRUED AS A PROMISE, OBLIGATION, OR COVENANT NOT TO SUE FOR COPYRIGHT OR TRADEMARK INFRINGEMENT IF YOU DO NOT COMPLY WITH THE TERMS AND CONDITIONS OF THIS LICENSE.
-
- 3. This License does not constitute or imply a waiver of any intellectual property rights except as may be otherwise expressly provided in this License. This License does not transfer, assign, or convey any intellectual property rights (e.g., it does not transfer ownership of copyrights or trademarks).
-
-4. Subject to the terms and conditions of this License, You may allow a third party to use Your copy of This Product (or a copy that You make and distribute, or Your Product) provided that the third party explicitly accepts and agrees to be bound by all terms and conditions of this License and the third party is not prohibited from using This Product (or portions thereof) by this License (see, e.g., Section VI.7) or by applicable law. However, You are not obligated to ensure that the third party accepts (and agrees to be bound by all terms of) this License if You distribute only the self-extracting package (containing This Product) that does not allow the user to install (nor extract) the files contained in the package until he or she accepts and agrees to be bound by all terms and conditions of this License.
-
- 5. Without specific prior written permission from the authors of This Product (or from their common representative), You must not use the name of This Product, the names of the authors of This Product, or the names of the legal entities (or informal groups) of which the authors were/are members/employees, to endorse or promote Your Product or any work in which You include a modified or unmodified version of This Product, or to endorse or promote You or Your affiliates, or in a way that might suggest that Your Product (or any work in which You include a modified or unmodified version of This Product), You, or Your affiliates is/are endorsed by one or more authors of This Product, or in a way that might suggest that one or more authors of This Product is/are affiliated with You (or Your affiliates) or directly participated in the creation of Your Product or of any work in which You include a modified or unmodified version of This Product.
-
-6. IF YOU ARE NOT SURE WHETHER YOU UNDERSTAND ALL PARTS OF THIS LICENSE OR IF YOU ARE NOT SURE WHETHER YOU CAN COMPLY WITH ALL TERMS AND CONDITIONS OF THIS LICENSE, YOU MUST NOT USE, COPY, MODIFY, CREATE DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY PORTION(S) OF IT. YOU SHOULD CONSULT WITH A LAWYER.
-
- 7. IF (IN RELEVANT CONTEXT) ANY PROVISION OF CHAPTER IV OF THIS LICENSE IS UNENFORCEABLE, INVALID, OR PROHIBITED UNDER APPLICABLE LAW IN YOUR JURISDICTION, YOU HAVE NO RIGHTS UNDER THIS LICENSE AND YOU MUST NOT USE, COPY, MODIFY, CREATE DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY PORTION(S) THEREOF.
-
- 8. Except as otherwise provided in this License, if any provision of this License, or a portion thereof, is found to be invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of this License, and such invalid or unenforceable provision shall be construed to reflect the original intent of the provision and shall be enforced to the maximum extent permitted by applicable law so as to effect the original intent of the provision as closely as possible.
-
- ____________________________________________________________
-

-Third-Party Licenses
-
-This Product contains components that were created by third parties and that are governed by third-party licenses, which are contained hereinafter (separated by lines consisting of underscores). Each of the third-party licenses applies only to (portions of) the source code file(s) in which the third-party license is contained or in which it is explicitly referenced, and to compiled or otherwise processed forms of such source code. None of the third-party licenses applies to This Product as a whole, even when it uses terms such as "product", "program", or any other equivalent terms/phrases. This Product as a whole is governed by the TrueCrypt License (see above). Some of the third-party components have been modified by the authors of This Product. Unless otherwise stated, such modifications and additions are governed by the TrueCrypt License (see above). Note: Unless otherwise stated, graphics and files that are not part of the source code are governed by the TrueCrypt License.
-
- ____________________________________________________________
-
-
- License agreement for Encryption for the Masses.
-
- Copyright (C) 1998-2000 Paul Le Roux. All Rights Reserved.
-
- This product can be copied and distributed free of charge, including source code.
-
- You may modify this product and source code, and distribute such modifications, and you may derive new works based on this product, provided that:
-
- 1. Any product which is simply derived from this product cannot be called E4M, or Encryption for the Masses.
-
- 2. If you use any of the source code in your product, and your product is distributed with source code, you must include this notice with those portions of this source code that you use.
-
- Or,
-
- If your product is distributed in binary form only, you must display on any packaging, and marketing materials which reference your product, a notice which states:
-
- "This product uses components written by Paul Le Roux <pleroux@swprofessionals.com>"
-
- 3. If you use any of the source code originally by Eric Young, you must in addition follow his terms and conditions.
-
- 4. Nothing requires that you accept this License, as you have not signed it. However, nothing else grants you permission to modify or distribute the product or its derivative works.
-
- These actions are prohibited by law if you do not accept this License.
-
- 5. If any of these license terms is found to be to broad in scope, and declared invalid by any court or legal process, you agree that all other terms shall not be so affected, and shall remain valid and enforceable.
-
- 6. THIS PROGRAM IS DISTRIBUTED FREE OF CHARGE, THEREFORE THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. UNLESS OTHERWISE STATED THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 7. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM, INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS, EVEN IF SUCH HOLDER OR OTHER PARTY HAD PREVIOUSLY BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
- ____________________________________________________________
-
- Copyright (c) 1998-2008, Brian Gladman, Worcester, UK. All rights reserved.
-
- LICENSE TERMS
-
-The free distribution and use of this software is allowed (with or without changes) provided that:
-
    -
  1. source code distributions include the above copyright notice, this list of conditions and the following disclaimer;
    -
  2. -
  3. binary distributions include the above copyright notice, this list of conditions and the following disclaimer in their documentation;
    -
  4. -
  5. the name of the copyright holder is not used to endorse products built using this software without specific written permission.
  6. -
- DISCLAIMER
-
- This software is provided 'as is' with no explicit or implied warranties in respect of its properties, including, but not limited to, correctness and/or fitness for purpose.
- ____________________________________________________________
-
- Copyright (C) 2002-2004 Mark Adler, all rights reserved
- version 1.8, 9 Jan 2004
-
- This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software.
-
-Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
-
    -
  1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  2. -
  3. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  4. -
  5. This notice may not be removed or altered from any source distribution.
  6. -
-____________________________________________________________
- - + + + + +VeraCrypt License + + + +VeraCrypt License
+
+Software distributed under this license is distributed on an "AS IS" BASIS WITHOUT WARRANTIES OF ANY KIND. THE AUTHORS AND DISTRIBUTORS OF THE SOFTWARE DISCLAIM ANY LIABILITY. ANYONE WHO USES, COPIES, MODIFIES, OR (RE)DISTRIBUTES ANY PART OF THE SOFTWARE IS, BY SUCH ACTION(S), ACCEPTING AND AGREEING TO BE BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE SOFTWARE, NOR ANY PART(S) THEREOF.
+
+VeraCrypt is governed by the TrueCrypt License version 3.0, a verbatim copy of this version of the TrueCrypt License can be found below. +
+This license does not grant you rights to use any contributors' name, logo, or trademarks, including IDRIX, VeraCrypt and all derivative names. For example, the following names are not allowed: VeraCrypt, VeraCrypt+, VeraCrypt Professional, iVeraCrypt, etc. Nor any other names confusingly similar to the name VeraCrypt (e.g., Vera-Crypt, Vera Crypt, VerKrypt, etc). +
+ ____________________________________________________________
+
+TrueCrypt License Version 3.0
+
+Software distributed under this license is distributed on an "AS IS" BASIS WITHOUT WARRANTIES OF ANY KIND. THE AUTHORS AND DISTRIBUTORS OF THE SOFTWARE DISCLAIM ANY LIABILITY. ANYONE WHO USES, COPIES, MODIFIES, OR (RE)DISTRIBUTES ANY PART OF THE SOFTWARE IS, BY SUCH ACTION(S), ACCEPTING AND AGREEING TO BE BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE SOFTWARE, NOR ANY PART(S) THEREOF.
+
+
I. Definitions
+
1. "This Product" means the work (including, but not limited to, source code, graphics, texts, and accompanying files) made available under and governed by this version of this license ("License"), as may be indicated by, but is not limited to, copyright notice(s) attached to or included in the work.
+
2. "You" means (and "Your" refers to) an individual or a legal entity (e.g., a non-profit organization, commercial organization, government agency, etc.) exercising permissions granted by this License.
+
3. "Modification" means (and "modify" refers to) any alteration of This Product, including, but not limited to, addition to or deletion from the substance or structure of This Product, translation into another language, repackaging, alteration or removal of any file included with This Product, and addition of any new files to This Product.
+
+4. "Your Product" means This Product modified by You, or any work You derive from (or base on) any part of This Product. In addition, "Your Product" means any work in which You include any (modified or unmodified) portion of This Product. However, if the work in which you include it is an aggregate software distribution (such as an operating system distribution or a cover CD-ROM of a magazine) containing multiple separate products, then the term "Your Product" includes only those products (in the aggregate software distribution) that use, include, or depend on a modified or unmodified version of This Product (and the term "Your Product" does not include the whole aggregate software distribution). For the purposes of this License, a product suite consisting of two or more products is considered a single product (operating system distributions and cover media of magazines are not considered product suites).
+
5. "Distribution" means (and "distribute" refers to), regardless of means or methods, conveyance, transfer, providing, or making available of This/Your Product or portions thereof to third parties (including, but not limited to, making This/Your Product, or portions thereof, available for download to third parties, whether or not any third party has downloaded the product, or any portion thereof, made available for download).
+

+
II. Use, Copying, and Distribution of This Product
+
+1. Provided that You comply with all applicable terms and conditions of this License, You may make copies of This Product (unmodified) and distribute copies of This Product (unmodified) that are not included in another product forming Your Product (except as permitted under Chapter III). Note: For terms and conditions for copying and distribution of modified versions of This Product, see Chapter III.
+
2. Provided that You comply with all applicable terms and conditions of this License, You may use This Product freely (see also Chapter III) on any number of computers/systems for non-commercial and/or commercial purposes.
+

+
III. Modification, Derivation, and Inclusion in Other Products
+
+1. If all conditions specified in the following paragraphs in this Chapter (III) are met (for exceptions, see Section III.2) and if You comply with all other applicable terms and conditions of this License, You may modify This Product (thus forming Your Product), derive new works from This Product or portions thereof (thus forming Your Product), include This Product or portions thereof in another product (thus forming Your Product, unless defined otherwise in Chapter I), and You may use (for non-commercial and/or commercial purposes), copy, and/or distribute Your Product.
+
+
    +
  1. The name of Your Product (or of Your modified version of This Product) must not contain the name TrueCrypt (for example, the following names are not allowed: TrueCrypt, TrueCrypt+, TrueCrypt Professional, iTrueCrypt, etc.) nor any other names confusingly similar to the name TrueCrypt (e.g., True-Crypt, True Crypt, TruKrypt, etc.)
    +
    + All occurrences of the name TrueCrypt that could reasonably be considered to identify Your Product must be removed from Your Product and from any associated materials. Logo(s) included in (or attached to) Your Product (and in/to associated materials) must not incorporate and must not be confusingly similar to any of the TrueCrypt logos (including, but not limited to, the non-textual logo consisting primarily of a key in stylized form) or portion(s) thereof. All graphics contained in This Product (logos, icons, etc.) must be removed from Your Product (or from Your modified version of This Product) and from any associated materials.
    +
    +
  2. +
  3. The following phrases must be removed from Your Product and from any associated materials, except the text of this License: "A TrueCrypt Foundation Release", "Released by TrueCrypt Foundation", "This is a TrueCrypt Foundation release."
    +
    +
  4. +
  5. Phrase "Based on TrueCrypt, freely available at http://www.truecrypt.org/" must be displayed by Your Product (if technically feasible) and contained in its documentation. Alternatively, if This Product or its portion You included in Your Product constitutes only a minor portion of Your Product, phrase "Portions of this product are based in part on TrueCrypt, freely available at http://www.truecrypt.org/" may be displayed instead. In each of the cases mentioned above in this paragraph, "http://www.truecrypt.org/" must be a hyperlink (if technically feasible) pointing to http://www.truecrypt.org/ and You may freely choose the location within the user interface (if there is any) of Your Product (e.g., an "About" window, etc.) and the way in which Your Product will display the respective phrase.
    +
    + Your Product (and any associated materials, e.g., the documentation, the content of the official web site of Your Product, etc.) must not present any Internet address containing the domain name truecrypt.org (or any domain name that forwards to the domain name truecrypt.org) in a manner that might suggest that it is where information about Your Product may be obtained or where bugs found in Your Product may be reported or where support for Your Product may be available or otherwise attempt to indicate that the domain name truecrypt.org is associated with Your Product.
    +
    +
  6. +
  7. The complete source code of Your Product must be freely and publicly available (for exceptions, see Section III.2) at least until You cease to distribute Your Product. This condition can be met in one or both of the following ways: (i) You include the complete source code of Your Product with every copy of Your Product that You make and distribute and You make all such copies of Your Product available to the general public free of charge, and/or (ii) You include information (valid and correct at least until You cease to distribute Your Product) about where the complete source code of Your Product can be obtained free of charge (e.g., an Internet address) or for a reasonable reproduction fee with every copy of Your Product that You make and distribute and, if there is a web site officially associated with Your Product, You include the aforementioned information about the source code on a freely and publicly accessible web page to which such web site links via an easily viewable hyperlink (at least until You cease to distribute Your Product).
    +
    +The source code of Your Product must not be deliberately obfuscated and it must not be in an intermediate form (e.g., the output of a preprocessor). Source code means the preferred form in which a programmer would usually modify the program.
    +
    + Portions of the source code of Your Product not contained in This Product (e.g., portions added by You in creating Your Product, whether created by You or by third parties) must be available under license(s) that (however, see also Subsection III.1.e) allow(s) anyone to modify and derive new works from the portions of the source code that are not contained in This Product and to use, copy, and redistribute such modifications and/or derivative works. The license(s) must be perpetual, non-exclusive, royalty-free, no-charge, and worldwide, and must not invalidate, weaken, restrict, interpret, amend, modify, interfere with or otherwise affect any part, term, provision, or clause of this License. The text(s) of the license(s) must be included with every copy of Your Product that You make and distribute.

    +
  8. +
  9. You must not change the license terms of This Product in any way (adding any new terms is considered changing the license terms even if the original terms are retained), which means, e.g., that no part of This Product may be put under another license. You must keep intact all the legal notices contained in the source code files. You must include the following items with every copy of Your Product that You make and distribute: a clear and conspicuous notice stating that Your Product or portion(s) thereof is/are governed by this version of the TrueCrypt License, a verbatim copy of this version of the TrueCrypt License (as contained herein), a clear and conspicuous notice containing information about where the included copy of the License can be found, and an appropriate copyright notice.
    +
  10. +
+2. You are not obligated to comply with Subsection III.1.d if Your Product is not distributed (i.e., Your Product is available only to You).
+
+
+
+ IV. Disclaimer of Liability, Disclaimer of Warranty, Indemnification
+
+ You expressly acknowledge and agree to the following:
+
+ 1. IN NO EVENT WILL ANY (CO)AUTHOR OF THIS PRODUCT, OR ANY APPLICABLE INTELLECTUAL-PROPERTY OWNER, OR ANY OTHER PARTY WHO MAY COPY AND/OR (RE)DISTRIBUTE THIS PRODUCT OR PORTIONS THEREOF, AS MAY BE PERMITTED HEREIN, BE LIABLE TO YOU OR TO ANY OTHER PARTY FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, ANY DIRECT, INDIRECT, GENERAL, SPECIAL, INCIDENTAL, PUNITIVE, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, CORRUPTION OR LOSS OF DATA, ANY LOSSES SUSTAINED BY YOU OR THIRD PARTIES, A FAILURE OF THIS PRODUCT TO OPERATE WITH ANY OTHER PRODUCT, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR BUSINESS INTERRUPTION), WHETHER IN CONTRACT, STRICT LIABILITY, TORT (INCLUDING, BUT NOT LIMITED TO, NEGLIGENCE) OR OTHERWISE, ARISING OUT OF THE USE, COPYING, MODIFICATION, OR (RE)DISTRIBUTION OF THIS PRODUCT (OR A PORTION THEREOF) OR OF YOUR PRODUCT (OR A PORTION THEREOF), OR INABILITY TO USE THIS PRODUCT (OR A PORTION THEREOF), EVEN IF SUCH DAMAGES (OR THE POSSIBILITY OF SUCH DAMAGES) ARE/WERE PREDICTABLE OR KNOWN TO ANY (CO)AUTHOR, INTELLECTUAL-PROPERTY OWNER, OR ANY OTHER PARTY.
+
+ 2. THIS PRODUCT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THIS PRODUCT IS WITH YOU. SHOULD THIS PRODUCT PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
+
+ 3. THIS PRODUCT MAY INCORPORATE IMPLEMENTATIONS OF CRYPTOGRAPHIC ALGORITHMS THAT ARE REGULATED (E.G., SUBJECT TO EXPORT/IMPORT CONTROL REGULATIONS) OR ILLEGAL IN SOME COUNTRIES. IT IS SOLELY YOUR RESPONSIBILITY TO VERIFY THAT IT IS LEGAL TO IMPORT AND/OR (RE)EXPORT AND/OR USE THIS PRODUCT (OR PORTIONS THEREOF) IN COUNTRIES WHERE YOU INTEND TO USE IT AND/OR TO WHICH YOU INTEND TO IMPORT IT AND/OR FROM WHICH YOU INTEND TO EXPORT IT, AND IT IS SOLELY YOUR RESPONSIBILITY TO COMPLY WITH ANY APPLICABLE REGULATIONS, RESTRICTIONS, AND LAWS.
+
+4. YOU SHALL INDEMNIFY, DEFEND AND HOLD ALL (CO)AUTHORS OF THIS PRODUCT, AND APPLICABLE INTELLECTUAL-PROPERTY OWNERS, HARMLESS FROM AND AGAINST ANY AND ALL LIABILITY, DAMAGES, LOSSES, SETTLEMENTS, PENALTIES, FINES, COSTS, EXPENSES (INCLUDING REASONABLE ATTORNEYS' FEES), DEMANDS, CAUSES OF ACTION, CLAIMS, ACTIONS, PROCEEDINGS, AND SUITS, DIRECTLY RELATED TO OR ARISING OUT OF YOUR USE, INABILITY TO USE, COPYING, (RE)DISTRIBUTION, IMPORT AND/OR (RE)EXPORT OF THIS PRODUCT (OR PORTIONS THEREOF) AND/OR YOUR BREACH OF ANY TERM OF THIS LICENSE.
+
+
+
+ V. Trademarks
+
+ This License does not grant permission to use trademarks associated with (or applying to) This Product, except for fair use as defined by applicable law and except for use expressly permitted or required by this License. Any attempt otherwise to use trademarks associated with (or applying to) This Product automatically and immediately terminates Your rights under This License and may constitute trademark infringement (which may be prosecuted).
+
+
+
+ VI. General Terms and Conditions, Miscellaneous Provisions
+
+ 1. ANYONE WHO USES AND/OR COPIES AND/OR MODIFIES AND/OR CREATES DERIVATIVE WORKS OF AND/OR (RE)DISTRIBUTES THIS PRODUCT, OR ANY PORTION(S) THEREOF, IS, BY SUCH ACTION(S), AGREEING TO BE BOUND BY AND ACCEPTING ALL TERMS AND CONDITIONS OF THIS LICENSE (AND THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS LICENSE). IF YOU DO NOT ACCEPT (AND AGREE TO BE BOUND BY) ALL TERMS AND CONDITIONS OF THIS LICENSE, DO NOT USE, COPY, MODIFY, CREATE DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY PORTION(S) THEREOF.
+
+2. YOU MAY NOT USE, MODIFY, COPY, CREATE DERIVATIVE WORKS OF, (RE)DISTRIBUTE, OR SUBLICENSE THIS PRODUCT, OR PORTION(S) THEREOF, EXCEPT AS EXPRESSLY PROVIDED IN THIS LICENSE (EVEN IF APPLICABLE LAW GIVES YOU MORE RIGHTS). ANY ATTEMPT (EVEN IF PERMITTED BY APPLICABLE LAW) OTHERWISE TO USE, MODIFY, COPY, CREATE DERIVATIVE WORKS OF, (RE)DISTRIBUTE, OR SUBLICENSE THIS PRODUCT, OR PORTION(S) THEREOF, AUTOMATICALLY AND IMMEDIATELY TERMINATES YOUR RIGHTS UNDER THIS LICENSE AND CAN CONSTITUTE COPYRIGHT INFRINGEMENT (WHICH MAY BE PROSECUTED). ANY CONDITIONS AND RESTRICTIONS CONTAINED IN THIS LICENSE ARE ALSO LIMITATIONS ON THE SCOPE OF THIS LICENSE AND ALSO DEFINE THE SCOPE OF YOUR RIGHTS UNDER THIS LICENSE. YOUR FAILURE TO COMPLY WITH THE TERMS AND CONDITIONS OF THIS LICENSE OR FAILURE TO PERFORM ANY APPLICABLE OBLIGATION IMPOSED BY THIS LICENSE AUTOMATICALLY AND IMMEDIATELY TERMINATES YOUR RIGHTS UNDER THIS LICENSE AND CAN CAUSE OR BE CONSIDERED COPYRIGHT INFRINGEMENT (WHICH MAY BE PROSECUTED). NOTHING IN THIS LICENSE SHALL IMPLY OR BE CONSTRUED AS A PROMISE, OBLIGATION, OR COVENANT NOT TO SUE FOR COPYRIGHT OR TRADEMARK INFRINGEMENT IF YOU DO NOT COMPLY WITH THE TERMS AND CONDITIONS OF THIS LICENSE.
+
+ 3. This License does not constitute or imply a waiver of any intellectual property rights except as may be otherwise expressly provided in this License. This License does not transfer, assign, or convey any intellectual property rights (e.g., it does not transfer ownership of copyrights or trademarks).
+
+4. Subject to the terms and conditions of this License, You may allow a third party to use Your copy of This Product (or a copy that You make and distribute, or Your Product) provided that the third party explicitly accepts and agrees to be bound by all terms and conditions of this License and the third party is not prohibited from using This Product (or portions thereof) by this License (see, e.g., Section VI.7) or by applicable law. However, You are not obligated to ensure that the third party accepts (and agrees to be bound by all terms of) this License if You distribute only the self-extracting package (containing This Product) that does not allow the user to install (nor extract) the files contained in the package until he or she accepts and agrees to be bound by all terms and conditions of this License.
+
+ 5. Without specific prior written permission from the authors of This Product (or from their common representative), You must not use the name of This Product, the names of the authors of This Product, or the names of the legal entities (or informal groups) of which the authors were/are members/employees, to endorse or promote Your Product or any work in which You include a modified or unmodified version of This Product, or to endorse or promote You or Your affiliates, or in a way that might suggest that Your Product (or any work in which You include a modified or unmodified version of This Product), You, or Your affiliates is/are endorsed by one or more authors of This Product, or in a way that might suggest that one or more authors of This Product is/are affiliated with You (or Your affiliates) or directly participated in the creation of Your Product or of any work in which You include a modified or unmodified version of This Product.
+
+6. IF YOU ARE NOT SURE WHETHER YOU UNDERSTAND ALL PARTS OF THIS LICENSE OR IF YOU ARE NOT SURE WHETHER YOU CAN COMPLY WITH ALL TERMS AND CONDITIONS OF THIS LICENSE, YOU MUST NOT USE, COPY, MODIFY, CREATE DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY PORTION(S) OF IT. YOU SHOULD CONSULT WITH A LAWYER.
+
+ 7. IF (IN RELEVANT CONTEXT) ANY PROVISION OF CHAPTER IV OF THIS LICENSE IS UNENFORCEABLE, INVALID, OR PROHIBITED UNDER APPLICABLE LAW IN YOUR JURISDICTION, YOU HAVE NO RIGHTS UNDER THIS LICENSE AND YOU MUST NOT USE, COPY, MODIFY, CREATE DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY PORTION(S) THEREOF.
+
+ 8. Except as otherwise provided in this License, if any provision of this License, or a portion thereof, is found to be invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of this License, and such invalid or unenforceable provision shall be construed to reflect the original intent of the provision and shall be enforced to the maximum extent permitted by applicable law so as to effect the original intent of the provision as closely as possible.
+
+ ____________________________________________________________
+

+Third-Party Licenses
+
+This Product contains components that were created by third parties and that are governed by third-party licenses, which are contained hereinafter (separated by lines consisting of underscores). Each of the third-party licenses applies only to (portions of) the source code file(s) in which the third-party license is contained or in which it is explicitly referenced, and to compiled or otherwise processed forms of such source code. None of the third-party licenses applies to This Product as a whole, even when it uses terms such as "product", "program", or any other equivalent terms/phrases. This Product as a whole is governed by the TrueCrypt License (see above). Some of the third-party components have been modified by the authors of This Product. Unless otherwise stated, such modifications and additions are governed by the TrueCrypt License (see above). Note: Unless otherwise stated, graphics and files that are not part of the source code are governed by the TrueCrypt License.
+
+ ____________________________________________________________
+
+
+ License agreement for Encryption for the Masses.
+
+ Copyright (C) 1998-2000 Paul Le Roux. All Rights Reserved.
+
+ This product can be copied and distributed free of charge, including source code.
+
+ You may modify this product and source code, and distribute such modifications, and you may derive new works based on this product, provided that:
+
+ 1. Any product which is simply derived from this product cannot be called E4M, or Encryption for the Masses.
+
+ 2. If you use any of the source code in your product, and your product is distributed with source code, you must include this notice with those portions of this source code that you use.
+
+ Or,
+
+ If your product is distributed in binary form only, you must display on any packaging, and marketing materials which reference your product, a notice which states:
+
+ "This product uses components written by Paul Le Roux <pleroux@swprofessionals.com>"
+
+ 3. If you use any of the source code originally by Eric Young, you must in addition follow his terms and conditions.
+
+ 4. Nothing requires that you accept this License, as you have not signed it. However, nothing else grants you permission to modify or distribute the product or its derivative works.
+
+ These actions are prohibited by law if you do not accept this License.
+
+ 5. If any of these license terms is found to be to broad in scope, and declared invalid by any court or legal process, you agree that all other terms shall not be so affected, and shall remain valid and enforceable.
+
+ 6. THIS PROGRAM IS DISTRIBUTED FREE OF CHARGE, THEREFORE THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. UNLESS OTHERWISE STATED THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 7. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM, INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS, EVEN IF SUCH HOLDER OR OTHER PARTY HAD PREVIOUSLY BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ ____________________________________________________________
+
+ Copyright (c) 1998-2008, Brian Gladman, Worcester, UK. All rights reserved.
+
+ LICENSE TERMS
+
+The free distribution and use of this software is allowed (with or without changes) provided that:
+
    +
  1. source code distributions include the above copyright notice, this list of conditions and the following disclaimer;
    +
  2. +
  3. binary distributions include the above copyright notice, this list of conditions and the following disclaimer in their documentation;
    +
  4. +
  5. the name of the copyright holder is not used to endorse products built using this software without specific written permission.
  6. +
+ DISCLAIMER
+
+ This software is provided 'as is' with no explicit or implied warranties in respect of its properties, including, but not limited to, correctness and/or fitness for purpose.
+ ____________________________________________________________
+
+ Copyright (C) 2002-2004 Mark Adler, all rights reserved
+ version 1.8, 9 Jan 2004
+
+ This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software.
+
+Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
+
    +
  1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  2. +
  3. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  4. +
  5. This notice may not be removed or altered from any source distribution.
  6. +
+____________________________________________________________
+ + diff --git a/src/License.txt b/src/License.txt index c174ef1b..44c0c657 100644 --- a/src/License.txt +++ b/src/License.txt @@ -1,702 +1,702 @@ -VeraCrypt License -Software distributed under this license is distributed on an "AS -IS" BASIS WITHOUT WARRANTIES OF ANY KIND. THE AUTHORS AND -DISTRIBUTORS OF THE SOFTWARE DISCLAIM ANY LIABILITY. ANYONE WHO -USES, COPIES, MODIFIES, OR (RE)DISTRIBUTES ANY PART OF THE -SOFTWARE IS, BY SUCH ACTION(S), ACCEPTING AND AGREEING TO BE -BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT -ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE -SOFTWARE, NOR ANY PART(S) THEREOF. - -VeraCrypt is multi-licensed under Apache License 2.0 and -the TrueCrypt License version 3.0, a verbatim copy of both -licenses can be found below. - -This license does not grant you rights to use any -contributors' name, logo, or trademarks, including IDRIX, -VeraCrypt and all derivative names. -For example, the following names are not allowed: VeraCrypt, -VeraCrypt+, VeraCrypt Professional, iVeraCrypt, etc. Nor any -other names confusingly similar to the name VeraCrypt (e.g., -Vera-Crypt, Vera Crypt, VerKrypt, etc.) -____________________________________________________________ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. -____________________________________________________________ - -TrueCrypt License Version 3.0 - -Software distributed under this license is distributed on an "AS -IS" BASIS WITHOUT WARRANTIES OF ANY KIND. THE AUTHORS AND -DISTRIBUTORS OF THE SOFTWARE DISCLAIM ANY LIABILITY. ANYONE WHO -USES, COPIES, MODIFIES, OR (RE)DISTRIBUTES ANY PART OF THE -SOFTWARE IS, BY SUCH ACTION(S), ACCEPTING AND AGREEING TO BE -BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT -ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE -SOFTWARE, NOR ANY PART(S) THEREOF. - - -I. Definitions - -1. "This Product" means the work (including, but not limited to, -source code, graphics, texts, and accompanying files) made -available under and governed by this version of this license -("License"), as may be indicated by, but is not limited to, -copyright notice(s) attached to or included in the work. - -2. "You" means (and "Your" refers to) an individual or a legal -entity (e.g., a non-profit organization, commercial -organization, government agency, etc.) exercising permissions -granted by this License. - -3. "Modification" means (and "modify" refers to) any alteration -of This Product, including, but not limited to, addition to or -deletion from the substance or structure of This Product, -translation into another language, repackaging, alteration or -removal of any file included with This Product, and addition of -any new files to This Product. - -4. "Your Product" means This Product modified by You, or any -work You derive from (or base on) any part of This Product. In -addition, "Your Product" means any work in which You include any -(modified or unmodified) portion of This Product. However, if -the work in which you include it is an aggregate software -distribution (such as an operating system distribution or a -cover CD-ROM of a magazine) containing multiple separate -products, then the term "Your Product" includes only those -products (in the aggregate software distribution) that use, -include, or depend on a modified or unmodified version of This -Product (and the term "Your Product" does not include the whole -aggregate software distribution). For the purposes of this -License, a product suite consisting of two or more products is -considered a single product (operating system distributions and -cover media of magazines are not considered product suites). - -5. "Distribution" means (and "distribute" refers to), regardless -of means or methods, conveyance, transfer, providing, or making -available of This/Your Product or portions thereof to third -parties (including, but not limited to, making This/Your -Product, or portions thereof, available for download to third -parties, whether or not any third party has downloaded the -product, or any portion thereof, made available for download). - - - -II. Use, Copying, and Distribution of This Product - -1. Provided that You comply with all applicable terms and -conditions of this License, You may make copies of This Product -(unmodified) and distribute copies of This Product (unmodified) -that are not included in another product forming Your Product -(except as permitted under Chapter III). Note: For terms and -conditions for copying and distribution of modified versions of -This Product, see Chapter III. - -2. Provided that You comply with all applicable terms and -conditions of this License, You may use This Product freely (see -also Chapter III) on any number of computers/systems for non- -commercial and/or commercial purposes. - - - -III. Modification, Derivation, and Inclusion in Other Products - -1. If all conditions specified in the following paragraphs in -this Chapter (III) are met (for exceptions, see Section III.2) -and if You comply with all other applicable terms and conditions -of this License, You may modify This Product (thus forming Your -Product), derive new works from This Product or portions thereof -(thus forming Your Product), include This Product or portions -thereof in another product (thus forming Your Product, unless -defined otherwise in Chapter I), and You may use (for non- -commercial and/or commercial purposes), copy, and/or distribute -Your Product. - - a. The name of Your Product (or of Your modified version of - This Product) must not contain the name TrueCrypt (for - example, the following names are not allowed: TrueCrypt, - TrueCrypt+, TrueCrypt Professional, iTrueCrypt, etc.) nor - any other names confusingly similar to the name TrueCrypt - (e.g., True-Crypt, True Crypt, TruKrypt, etc.) - - All occurrences of the name TrueCrypt that could reasonably - be considered to identify Your Product must be removed from - Your Product and from any associated materials. Logo(s) - included in (or attached to) Your Product (and in/to - associated materials) must not incorporate and must not be - confusingly similar to any of the TrueCrypt logos - (including, but not limited to, the non-textual logo - consisting primarily of a key in stylized form) or - portion(s) thereof. All graphics contained in This Product - (logos, icons, etc.) must be removed from Your Product (or - from Your modified version of This Product) and from any - associated materials. - - b. The following phrases must be removed from Your Product - and from any associated materials, except the text of this - License: "A TrueCrypt Foundation Release", "Released by - TrueCrypt Foundation", "This is a TrueCrypt Foundation - release." - - c. Phrase "Based on TrueCrypt, freely available at - http://www.truecrypt.org/" must be displayed by Your Product - (if technically feasible) and contained in its - documentation. Alternatively, if This Product or its portion - You included in Your Product constitutes only a minor - portion of Your Product, phrase "Portions of this product - are based in part on TrueCrypt, freely available at - http://www.truecrypt.org/" may be displayed instead. In each - of the cases mentioned above in this paragraph, - "http://www.truecrypt.org/" must be a hyperlink (if - technically feasible) pointing to http://www.truecrypt.org/ - and You may freely choose the location within the user - interface (if there is any) of Your Product (e.g., an - "About" window, etc.) and the way in which Your Product will - display the respective phrase. - - Your Product (and any associated materials, e.g., the - documentation, the content of the official web site of Your - Product, etc.) must not present any Internet address - containing the domain name truecrypt.org (or any domain name - that forwards to the domain name truecrypt.org) in a manner - that might suggest that it is where information about Your - Product may be obtained or where bugs found in Your Product - may be reported or where support for Your Product may be - available or otherwise attempt to indicate that the domain - name truecrypt.org is associated with Your Product. - - d. The complete source code of Your Product must be freely - and publicly available (for exceptions, see Section III.2) - at least until You cease to distribute Your Product. This - condition can be met in one or both of the following ways: - (i) You include the complete source code of Your Product - with every copy of Your Product that You make and distribute - and You make all such copies of Your Product available to - the general public free of charge, and/or (ii) You include - information (valid and correct at least until You cease to - distribute Your Product) about where the complete source - code of Your Product can be obtained free of charge (e.g., - an Internet address) or for a reasonable reproduction fee - with every copy of Your Product that You make and distribute - and, if there is a web site officially associated with Your - Product, You include the aforementioned information about - the source code on a freely and publicly accessible web - page to which such web site links via an easily viewable - hyperlink (at least until You cease to distribute Your - Product). - - The source code of Your Product must not be deliberately - obfuscated and it must not be in an intermediate form (e.g., - the output of a preprocessor). Source code means the - preferred form in which a programmer would usually modify - the program. - - Portions of the source code of Your Product not contained in - This Product (e.g., portions added by You in creating Your - Product, whether created by You or by third parties) must be - available under license(s) that (however, see also - Subsection III.1.e) allow(s) anyone to modify and derive new - works from the portions of the source code that are not - contained in This Product and to use, copy, and redistribute - such modifications and/or derivative works. The license(s) - must be perpetual, non-exclusive, royalty-free, no-charge, - and worldwide, and must not invalidate, weaken, restrict, - interpret, amend, modify, interfere with or otherwise affect - any part, term, provision, or clause of this License. The - text(s) of the license(s) must be included with every copy - of Your Product that You make and distribute. - - e. You must not change the license terms of This Product in - any way (adding any new terms is considered changing the - license terms even if the original terms are retained), - which means, e.g., that no part of This Product may be put - under another license. You must keep intact all the legal - notices contained in the source code files. You must include - the following items with every copy of Your Product that You - make and distribute: a clear and conspicuous notice stating - that Your Product or portion(s) thereof is/are governed by - this version of the TrueCrypt License, a verbatim copy of - this version of the TrueCrypt License (as contained herein), - a clear and conspicuous notice containing information about - where the included copy of the License can be found, and an - appropriate copyright notice. - - -2. You are not obligated to comply with Subsection III.1.d if -Your Product is not distributed (i.e., Your Product is available -only to You). - - - -IV. Disclaimer of Liability, Disclaimer of Warranty, -Indemnification - -You expressly acknowledge and agree to the following: - -1. IN NO EVENT WILL ANY (CO)AUTHOR OF THIS PRODUCT, OR ANY -APPLICABLE INTELLECTUAL-PROPERTY OWNER, OR ANY OTHER PARTY WHO -MAY COPY AND/OR (RE)DISTRIBUTE THIS PRODUCT OR PORTIONS THEREOF, -AS MAY BE PERMITTED HEREIN, BE LIABLE TO YOU OR TO ANY OTHER -PARTY FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, ANY -DIRECT, INDIRECT, GENERAL, SPECIAL, INCIDENTAL, PUNITIVE, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, CORRUPTION OR LOSS OF DATA, ANY LOSSES SUSTAINED BY YOU OR -THIRD PARTIES, A FAILURE OF THIS PRODUCT TO OPERATE WITH ANY -OTHER PRODUCT, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR -BUSINESS INTERRUPTION), WHETHER IN CONTRACT, STRICT LIABILITY, -TORT (INCLUDING, BUT NOT LIMITED TO, NEGLIGENCE) OR OTHERWISE, -ARISING OUT OF THE USE, COPYING, MODIFICATION, OR -(RE)DISTRIBUTION OF THIS PRODUCT (OR A PORTION THEREOF) OR OF -YOUR PRODUCT (OR A PORTION THEREOF), OR INABILITY TO USE THIS -PRODUCT (OR A PORTION THEREOF), EVEN IF SUCH DAMAGES (OR THE -POSSIBILITY OF SUCH DAMAGES) ARE/WERE PREDICTABLE OR KNOWN TO -ANY (CO)AUTHOR, INTELLECTUAL-PROPERTY OWNER, OR ANY OTHER PARTY. - -2. THIS PRODUCT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY -KIND, WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT -LIMITED TO, THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE ENTIRE RISK AS TO -THE QUALITY AND PERFORMANCE OF THIS PRODUCT IS WITH YOU. SHOULD -THIS PRODUCT PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL -NECESSARY SERVICING, REPAIR, OR CORRECTION. - -3. THIS PRODUCT MAY INCORPORATE IMPLEMENTATIONS OF CRYPTOGRAPHIC -ALGORITHMS THAT ARE REGULATED (E.G., SUBJECT TO EXPORT/IMPORT -CONTROL REGULATIONS) OR ILLEGAL IN SOME COUNTRIES. IT IS SOLELY -YOUR RESPONSIBILITY TO VERIFY THAT IT IS LEGAL TO IMPORT AND/OR -(RE)EXPORT AND/OR USE THIS PRODUCT (OR PORTIONS THEREOF) IN -COUNTRIES WHERE YOU INTEND TO USE IT AND/OR TO WHICH YOU INTEND -TO IMPORT IT AND/OR FROM WHICH YOU INTEND TO EXPORT IT, AND IT -IS SOLELY YOUR RESPONSIBILITY TO COMPLY WITH ANY APPLICABLE -REGULATIONS, RESTRICTIONS, AND LAWS. - -4. YOU SHALL INDEMNIFY, DEFEND AND HOLD ALL (CO)AUTHORS OF THIS -PRODUCT, AND APPLICABLE INTELLECTUAL-PROPERTY OWNERS, HARMLESS -FROM AND AGAINST ANY AND ALL LIABILITY, DAMAGES, LOSSES, -SETTLEMENTS, PENALTIES, FINES, COSTS, EXPENSES (INCLUDING -REASONABLE ATTORNEYS' FEES), DEMANDS, CAUSES OF ACTION, CLAIMS, -ACTIONS, PROCEEDINGS, AND SUITS, DIRECTLY RELATED TO OR ARISING -OUT OF YOUR USE, INABILITY TO USE, COPYING, (RE)DISTRIBUTION, -IMPORT AND/OR (RE)EXPORT OF THIS PRODUCT (OR PORTIONS THEREOF) -AND/OR YOUR BREACH OF ANY TERM OF THIS LICENSE. - - - -V. Trademarks - -This License does not grant permission to use trademarks -associated with (or applying to) This Product, except for fair -use as defined by applicable law and except for use expressly -permitted or required by this License. Any attempt otherwise to -use trademarks associated with (or applying to) This Product -automatically and immediately terminates Your rights under This -License and may constitute trademark infringement (which may be -prosecuted). - - - -VI. General Terms and Conditions, Miscellaneous Provisions - -1. ANYONE WHO USES AND/OR COPIES AND/OR MODIFIES AND/OR CREATES -DERIVATIVE WORKS OF AND/OR (RE)DISTRIBUTES THIS PRODUCT, OR ANY -PORTION(S) THEREOF, IS, BY SUCH ACTION(S), AGREEING TO BE BOUND -BY AND ACCEPTING ALL TERMS AND CONDITIONS OF THIS LICENSE (AND -THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS LICENSE). -IF YOU DO NOT ACCEPT (AND AGREE TO BE BOUND BY) ALL TERMS AND -CONDITIONS OF THIS LICENSE, DO NOT USE, COPY, MODIFY, CREATE -DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY -PORTION(S) THEREOF. - -2. YOU MAY NOT USE, MODIFY, COPY, CREATE DERIVATIVE WORKS OF, -(RE)DISTRIBUTE, OR SUBLICENSE THIS PRODUCT, OR PORTION(S) -THEREOF, EXCEPT AS EXPRESSLY PROVIDED IN THIS LICENSE (EVEN IF -APPLICABLE LAW GIVES YOU MORE RIGHTS). ANY ATTEMPT (EVEN IF -PERMITTED BY APPLICABLE LAW) OTHERWISE TO USE, MODIFY, COPY, -CREATE DERIVATIVE WORKS OF, (RE)DISTRIBUTE, OR SUBLICENSE THIS -PRODUCT, OR PORTION(S) THEREOF, AUTOMATICALLY AND IMMEDIATELY -TERMINATES YOUR RIGHTS UNDER THIS LICENSE AND CAN CONSTITUTE -COPYRIGHT INFRINGEMENT (WHICH MAY BE PROSECUTED). ANY CONDITIONS -AND RESTRICTIONS CONTAINED IN THIS LICENSE ARE ALSO LIMITATIONS -ON THE SCOPE OF THIS LICENSE AND ALSO DEFINE THE SCOPE OF YOUR -RIGHTS UNDER THIS LICENSE. YOUR FAILURE TO COMPLY WITH THE TERMS -AND CONDITIONS OF THIS LICENSE OR FAILURE TO PERFORM ANY -APPLICABLE OBLIGATION IMPOSED BY THIS LICENSE AUTOMATICALLY AND -IMMEDIATELY TERMINATES YOUR RIGHTS UNDER THIS LICENSE AND CAN -CAUSE OR BE CONSIDERED COPYRIGHT INFRINGEMENT (WHICH MAY BE -PROSECUTED). NOTHING IN THIS LICENSE SHALL IMPLY OR BE CONSTRUED -AS A PROMISE, OBLIGATION, OR COVENANT NOT TO SUE FOR COPYRIGHT -OR TRADEMARK INFRINGEMENT IF YOU DO NOT COMPLY WITH THE TERMS -AND CONDITIONS OF THIS LICENSE. - -3. This License does not constitute or imply a waiver of any -intellectual property rights except as may be otherwise -expressly provided in this License. This License does not -transfer, assign, or convey any intellectual property rights -(e.g., it does not transfer ownership of copyrights or -trademarks). - -4. Subject to the terms and conditions of this License, You may -allow a third party to use Your copy of This Product (or a copy -that You make and distribute, or Your Product) provided that the -third party explicitly accepts and agrees to be bound by all -terms and conditions of this License and the third party is not -prohibited from using This Product (or portions thereof) by this -License (see, e.g., Section VI.7) or by applicable law. However, -You are not obligated to ensure that the third party accepts -(and agrees to be bound by all terms of) this License if You -distribute only the self-extracting package (containing This -Product) that does not allow the user to install (nor extract) -the files contained in the package until he or she accepts and -agrees to be bound by all terms and conditions of this License. - -5. Without specific prior written permission from the authors of -This Product (or from their common representative), You must not -use the name of This Product, the names of the authors of This -Product, or the names of the legal entities (or informal groups) -of which the authors were/are members/employees, to endorse or -promote Your Product or any work in which You include a modified -or unmodified version of This Product, or to endorse or promote -You or Your affiliates, or in a way that might suggest that Your -Product (or any work in which You include a modified or -unmodified version of This Product), You, or Your affiliates -is/are endorsed by one or more authors of This Product, or in a -way that might suggest that one or more authors of This Product -is/are affiliated with You (or Your affiliates) or directly -participated in the creation of Your Product or of any work in -which You include a modified or unmodified version of This -Product. - -6. IF YOU ARE NOT SURE WHETHER YOU UNDERSTAND ALL PARTS OF THIS -LICENSE OR IF YOU ARE NOT SURE WHETHER YOU CAN COMPLY WITH ALL -TERMS AND CONDITIONS OF THIS LICENSE, YOU MUST NOT USE, COPY, -MODIFY, CREATE DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS -PRODUCT, NOR ANY PORTION(S) OF IT. YOU SHOULD CONSULT WITH A -LAWYER. - -7. IF (IN RELEVANT CONTEXT) ANY PROVISION OF CHAPTER IV OF THIS -LICENSE IS UNENFORCEABLE, INVALID, OR PROHIBITED UNDER -APPLICABLE LAW IN YOUR JURISDICTION, YOU HAVE NO RIGHTS UNDER -THIS LICENSE AND YOU MUST NOT USE, COPY, MODIFY, CREATE -DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY -PORTION(S) THEREOF. - -8. Except as otherwise provided in this License, if any -provision of this License, or a portion thereof, is found to be -invalid or unenforceable under applicable law, it shall not -affect the validity or enforceability of the remainder of this -License, and such invalid or unenforceable provision shall be -construed to reflect the original intent of the provision and -shall be enforced to the maximum extent permitted by applicable -law so as to effect the original intent of the provision as -closely as possible. - -____________________________________________________________ - - -Third-Party Licenses - -This Product contains components that were created by third -parties and that are governed by third-party licenses, which are -contained hereinafter (separated by lines consisting of -underscores). Each of the third-party licenses applies only to -(portions of) the source code file(s) in which the third-party -license is contained or in which it is explicitly referenced, -and to compiled or otherwise processed forms of such source -code. None of the third-party licenses applies to This Product -as a whole, even when it uses terms such as "product", -"program", or any other equivalent terms/phrases. This Product -as a whole is governed by the TrueCrypt License (see above). -Some of the third-party components have been modified by the -authors of This Product. Unless otherwise stated, such -modifications and additions are governed by the TrueCrypt -License (see above). Note: Unless otherwise stated, graphics and -files that are not part of the source code are governed by the -TrueCrypt License. - -____________________________________________________________ - -License agreement for Encryption for the Masses. - -Copyright (C) 1998-2000 Paul Le Roux. All Rights Reserved. - -This product can be copied and distributed free of charge, -including source code. - -You may modify this product and source code, and distribute such -modifications, and you may derive new works based on this -product, provided that: - -1. Any product which is simply derived from this product cannot -be called E4M, or Encryption for the Masses. - -2. If you use any of the source code in your product, and your -product is distributed with source code, you must include this -notice with those portions of this source code that you use. - -Or, - -If your product is distributed in binary form only, you must -display on any packaging, and marketing materials which -reference your product, a notice which states: - -"This product uses components written by Paul Le Roux -" - -3. If you use any of the source code originally by Eric Young, -you must in addition follow his terms and conditions. - -4. Nothing requires that you accept this License, as you have -not signed it. However, nothing else grants you permission to -modify or distribute the product or its derivative works. - -These actions are prohibited by law if you do not accept this -License. - -5. If any of these license terms is found to be to broad in -scope, and declared invalid by any court or legal process, you -agree that all other terms shall not be so affected, and shall -remain valid and enforceable. - -6. THIS PROGRAM IS DISTRIBUTED FREE OF CHARGE, THEREFORE THERE -IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. UNLESS OTHERWISE STATED THE PROGRAM IS PROVIDED -"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR -IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE -ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS -WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE -COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -7. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY -MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE -LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, -INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR -INABILITY TO USE THE PROGRAM, INCLUDING BUT NOT LIMITED TO LOSS -OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH -ANY OTHER PROGRAMS, EVEN IF SUCH HOLDER OR OTHER PARTY HAD -PREVIOUSLY BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. -____________________________________________________________ - -Copyright (c) 1998-2008, Brian Gladman, Worcester, UK. -All rights reserved. - -LICENSE TERMS - -The free distribution and use of this software is allowed (with -or without changes) provided that: - - 1. source code distributions include the above copyright - notice, this list of conditions and the following - disclaimer; - - 2. binary distributions include the above copyright notice, - this list of conditions and the following disclaimer in - their documentation; - - 3. the name of the copyright holder is not used to endorse - products built using this software without specific written - permission. - -DISCLAIMER - -This software is provided 'as is' with no explicit or implied -warranties in respect of its properties, including, but not -limited to, correctness and/or fitness for purpose. -____________________________________________________________ - -Copyright (C) 2002-2004 Mark Adler, all rights reserved -version 1.8, 9 Jan 2004 - -This software is provided 'as-is', without any express or -implied warranty. In no event will the author be held liable -for any damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you - must not claim that you wrote the original software. If you - use this software in a product, an acknowledgment in the - product documentation would be appreciated but is not - required. -2. Altered source versions must be plainly marked as such, and - must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source - distribution. -____________________________________________________________ +VeraCrypt License +Software distributed under this license is distributed on an "AS +IS" BASIS WITHOUT WARRANTIES OF ANY KIND. THE AUTHORS AND +DISTRIBUTORS OF THE SOFTWARE DISCLAIM ANY LIABILITY. ANYONE WHO +USES, COPIES, MODIFIES, OR (RE)DISTRIBUTES ANY PART OF THE +SOFTWARE IS, BY SUCH ACTION(S), ACCEPTING AND AGREEING TO BE +BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT +ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE +SOFTWARE, NOR ANY PART(S) THEREOF. + +VeraCrypt is multi-licensed under Apache License 2.0 and +the TrueCrypt License version 3.0, a verbatim copy of both +licenses can be found below. + +This license does not grant you rights to use any +contributors' name, logo, or trademarks, including IDRIX, +VeraCrypt and all derivative names. +For example, the following names are not allowed: VeraCrypt, +VeraCrypt+, VeraCrypt Professional, iVeraCrypt, etc. Nor any +other names confusingly similar to the name VeraCrypt (e.g., +Vera-Crypt, Vera Crypt, VerKrypt, etc.) +____________________________________________________________ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. +____________________________________________________________ + +TrueCrypt License Version 3.0 + +Software distributed under this license is distributed on an "AS +IS" BASIS WITHOUT WARRANTIES OF ANY KIND. THE AUTHORS AND +DISTRIBUTORS OF THE SOFTWARE DISCLAIM ANY LIABILITY. ANYONE WHO +USES, COPIES, MODIFIES, OR (RE)DISTRIBUTES ANY PART OF THE +SOFTWARE IS, BY SUCH ACTION(S), ACCEPTING AND AGREEING TO BE +BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT +ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE +SOFTWARE, NOR ANY PART(S) THEREOF. + + +I. Definitions + +1. "This Product" means the work (including, but not limited to, +source code, graphics, texts, and accompanying files) made +available under and governed by this version of this license +("License"), as may be indicated by, but is not limited to, +copyright notice(s) attached to or included in the work. + +2. "You" means (and "Your" refers to) an individual or a legal +entity (e.g., a non-profit organization, commercial +organization, government agency, etc.) exercising permissions +granted by this License. + +3. "Modification" means (and "modify" refers to) any alteration +of This Product, including, but not limited to, addition to or +deletion from the substance or structure of This Product, +translation into another language, repackaging, alteration or +removal of any file included with This Product, and addition of +any new files to This Product. + +4. "Your Product" means This Product modified by You, or any +work You derive from (or base on) any part of This Product. In +addition, "Your Product" means any work in which You include any +(modified or unmodified) portion of This Product. However, if +the work in which you include it is an aggregate software +distribution (such as an operating system distribution or a +cover CD-ROM of a magazine) containing multiple separate +products, then the term "Your Product" includes only those +products (in the aggregate software distribution) that use, +include, or depend on a modified or unmodified version of This +Product (and the term "Your Product" does not include the whole +aggregate software distribution). For the purposes of this +License, a product suite consisting of two or more products is +considered a single product (operating system distributions and +cover media of magazines are not considered product suites). + +5. "Distribution" means (and "distribute" refers to), regardless +of means or methods, conveyance, transfer, providing, or making +available of This/Your Product or portions thereof to third +parties (including, but not limited to, making This/Your +Product, or portions thereof, available for download to third +parties, whether or not any third party has downloaded the +product, or any portion thereof, made available for download). + + + +II. Use, Copying, and Distribution of This Product + +1. Provided that You comply with all applicable terms and +conditions of this License, You may make copies of This Product +(unmodified) and distribute copies of This Product (unmodified) +that are not included in another product forming Your Product +(except as permitted under Chapter III). Note: For terms and +conditions for copying and distribution of modified versions of +This Product, see Chapter III. + +2. Provided that You comply with all applicable terms and +conditions of this License, You may use This Product freely (see +also Chapter III) on any number of computers/systems for non- +commercial and/or commercial purposes. + + + +III. Modification, Derivation, and Inclusion in Other Products + +1. If all conditions specified in the following paragraphs in +this Chapter (III) are met (for exceptions, see Section III.2) +and if You comply with all other applicable terms and conditions +of this License, You may modify This Product (thus forming Your +Product), derive new works from This Product or portions thereof +(thus forming Your Product), include This Product or portions +thereof in another product (thus forming Your Product, unless +defined otherwise in Chapter I), and You may use (for non- +commercial and/or commercial purposes), copy, and/or distribute +Your Product. + + a. The name of Your Product (or of Your modified version of + This Product) must not contain the name TrueCrypt (for + example, the following names are not allowed: TrueCrypt, + TrueCrypt+, TrueCrypt Professional, iTrueCrypt, etc.) nor + any other names confusingly similar to the name TrueCrypt + (e.g., True-Crypt, True Crypt, TruKrypt, etc.) + + All occurrences of the name TrueCrypt that could reasonably + be considered to identify Your Product must be removed from + Your Product and from any associated materials. Logo(s) + included in (or attached to) Your Product (and in/to + associated materials) must not incorporate and must not be + confusingly similar to any of the TrueCrypt logos + (including, but not limited to, the non-textual logo + consisting primarily of a key in stylized form) or + portion(s) thereof. All graphics contained in This Product + (logos, icons, etc.) must be removed from Your Product (or + from Your modified version of This Product) and from any + associated materials. + + b. The following phrases must be removed from Your Product + and from any associated materials, except the text of this + License: "A TrueCrypt Foundation Release", "Released by + TrueCrypt Foundation", "This is a TrueCrypt Foundation + release." + + c. Phrase "Based on TrueCrypt, freely available at + http://www.truecrypt.org/" must be displayed by Your Product + (if technically feasible) and contained in its + documentation. Alternatively, if This Product or its portion + You included in Your Product constitutes only a minor + portion of Your Product, phrase "Portions of this product + are based in part on TrueCrypt, freely available at + http://www.truecrypt.org/" may be displayed instead. In each + of the cases mentioned above in this paragraph, + "http://www.truecrypt.org/" must be a hyperlink (if + technically feasible) pointing to http://www.truecrypt.org/ + and You may freely choose the location within the user + interface (if there is any) of Your Product (e.g., an + "About" window, etc.) and the way in which Your Product will + display the respective phrase. + + Your Product (and any associated materials, e.g., the + documentation, the content of the official web site of Your + Product, etc.) must not present any Internet address + containing the domain name truecrypt.org (or any domain name + that forwards to the domain name truecrypt.org) in a manner + that might suggest that it is where information about Your + Product may be obtained or where bugs found in Your Product + may be reported or where support for Your Product may be + available or otherwise attempt to indicate that the domain + name truecrypt.org is associated with Your Product. + + d. The complete source code of Your Product must be freely + and publicly available (for exceptions, see Section III.2) + at least until You cease to distribute Your Product. This + condition can be met in one or both of the following ways: + (i) You include the complete source code of Your Product + with every copy of Your Product that You make and distribute + and You make all such copies of Your Product available to + the general public free of charge, and/or (ii) You include + information (valid and correct at least until You cease to + distribute Your Product) about where the complete source + code of Your Product can be obtained free of charge (e.g., + an Internet address) or for a reasonable reproduction fee + with every copy of Your Product that You make and distribute + and, if there is a web site officially associated with Your + Product, You include the aforementioned information about + the source code on a freely and publicly accessible web + page to which such web site links via an easily viewable + hyperlink (at least until You cease to distribute Your + Product). + + The source code of Your Product must not be deliberately + obfuscated and it must not be in an intermediate form (e.g., + the output of a preprocessor). Source code means the + preferred form in which a programmer would usually modify + the program. + + Portions of the source code of Your Product not contained in + This Product (e.g., portions added by You in creating Your + Product, whether created by You or by third parties) must be + available under license(s) that (however, see also + Subsection III.1.e) allow(s) anyone to modify and derive new + works from the portions of the source code that are not + contained in This Product and to use, copy, and redistribute + such modifications and/or derivative works. The license(s) + must be perpetual, non-exclusive, royalty-free, no-charge, + and worldwide, and must not invalidate, weaken, restrict, + interpret, amend, modify, interfere with or otherwise affect + any part, term, provision, or clause of this License. The + text(s) of the license(s) must be included with every copy + of Your Product that You make and distribute. + + e. You must not change the license terms of This Product in + any way (adding any new terms is considered changing the + license terms even if the original terms are retained), + which means, e.g., that no part of This Product may be put + under another license. You must keep intact all the legal + notices contained in the source code files. You must include + the following items with every copy of Your Product that You + make and distribute: a clear and conspicuous notice stating + that Your Product or portion(s) thereof is/are governed by + this version of the TrueCrypt License, a verbatim copy of + this version of the TrueCrypt License (as contained herein), + a clear and conspicuous notice containing information about + where the included copy of the License can be found, and an + appropriate copyright notice. + + +2. You are not obligated to comply with Subsection III.1.d if +Your Product is not distributed (i.e., Your Product is available +only to You). + + + +IV. Disclaimer of Liability, Disclaimer of Warranty, +Indemnification + +You expressly acknowledge and agree to the following: + +1. IN NO EVENT WILL ANY (CO)AUTHOR OF THIS PRODUCT, OR ANY +APPLICABLE INTELLECTUAL-PROPERTY OWNER, OR ANY OTHER PARTY WHO +MAY COPY AND/OR (RE)DISTRIBUTE THIS PRODUCT OR PORTIONS THEREOF, +AS MAY BE PERMITTED HEREIN, BE LIABLE TO YOU OR TO ANY OTHER +PARTY FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, ANY +DIRECT, INDIRECT, GENERAL, SPECIAL, INCIDENTAL, PUNITIVE, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, CORRUPTION OR LOSS OF DATA, ANY LOSSES SUSTAINED BY YOU OR +THIRD PARTIES, A FAILURE OF THIS PRODUCT TO OPERATE WITH ANY +OTHER PRODUCT, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR +BUSINESS INTERRUPTION), WHETHER IN CONTRACT, STRICT LIABILITY, +TORT (INCLUDING, BUT NOT LIMITED TO, NEGLIGENCE) OR OTHERWISE, +ARISING OUT OF THE USE, COPYING, MODIFICATION, OR +(RE)DISTRIBUTION OF THIS PRODUCT (OR A PORTION THEREOF) OR OF +YOUR PRODUCT (OR A PORTION THEREOF), OR INABILITY TO USE THIS +PRODUCT (OR A PORTION THEREOF), EVEN IF SUCH DAMAGES (OR THE +POSSIBILITY OF SUCH DAMAGES) ARE/WERE PREDICTABLE OR KNOWN TO +ANY (CO)AUTHOR, INTELLECTUAL-PROPERTY OWNER, OR ANY OTHER PARTY. + +2. THIS PRODUCT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY +KIND, WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT +LIMITED TO, THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE ENTIRE RISK AS TO +THE QUALITY AND PERFORMANCE OF THIS PRODUCT IS WITH YOU. SHOULD +THIS PRODUCT PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL +NECESSARY SERVICING, REPAIR, OR CORRECTION. + +3. THIS PRODUCT MAY INCORPORATE IMPLEMENTATIONS OF CRYPTOGRAPHIC +ALGORITHMS THAT ARE REGULATED (E.G., SUBJECT TO EXPORT/IMPORT +CONTROL REGULATIONS) OR ILLEGAL IN SOME COUNTRIES. IT IS SOLELY +YOUR RESPONSIBILITY TO VERIFY THAT IT IS LEGAL TO IMPORT AND/OR +(RE)EXPORT AND/OR USE THIS PRODUCT (OR PORTIONS THEREOF) IN +COUNTRIES WHERE YOU INTEND TO USE IT AND/OR TO WHICH YOU INTEND +TO IMPORT IT AND/OR FROM WHICH YOU INTEND TO EXPORT IT, AND IT +IS SOLELY YOUR RESPONSIBILITY TO COMPLY WITH ANY APPLICABLE +REGULATIONS, RESTRICTIONS, AND LAWS. + +4. YOU SHALL INDEMNIFY, DEFEND AND HOLD ALL (CO)AUTHORS OF THIS +PRODUCT, AND APPLICABLE INTELLECTUAL-PROPERTY OWNERS, HARMLESS +FROM AND AGAINST ANY AND ALL LIABILITY, DAMAGES, LOSSES, +SETTLEMENTS, PENALTIES, FINES, COSTS, EXPENSES (INCLUDING +REASONABLE ATTORNEYS' FEES), DEMANDS, CAUSES OF ACTION, CLAIMS, +ACTIONS, PROCEEDINGS, AND SUITS, DIRECTLY RELATED TO OR ARISING +OUT OF YOUR USE, INABILITY TO USE, COPYING, (RE)DISTRIBUTION, +IMPORT AND/OR (RE)EXPORT OF THIS PRODUCT (OR PORTIONS THEREOF) +AND/OR YOUR BREACH OF ANY TERM OF THIS LICENSE. + + + +V. Trademarks + +This License does not grant permission to use trademarks +associated with (or applying to) This Product, except for fair +use as defined by applicable law and except for use expressly +permitted or required by this License. Any attempt otherwise to +use trademarks associated with (or applying to) This Product +automatically and immediately terminates Your rights under This +License and may constitute trademark infringement (which may be +prosecuted). + + + +VI. General Terms and Conditions, Miscellaneous Provisions + +1. ANYONE WHO USES AND/OR COPIES AND/OR MODIFIES AND/OR CREATES +DERIVATIVE WORKS OF AND/OR (RE)DISTRIBUTES THIS PRODUCT, OR ANY +PORTION(S) THEREOF, IS, BY SUCH ACTION(S), AGREEING TO BE BOUND +BY AND ACCEPTING ALL TERMS AND CONDITIONS OF THIS LICENSE (AND +THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS LICENSE). +IF YOU DO NOT ACCEPT (AND AGREE TO BE BOUND BY) ALL TERMS AND +CONDITIONS OF THIS LICENSE, DO NOT USE, COPY, MODIFY, CREATE +DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY +PORTION(S) THEREOF. + +2. YOU MAY NOT USE, MODIFY, COPY, CREATE DERIVATIVE WORKS OF, +(RE)DISTRIBUTE, OR SUBLICENSE THIS PRODUCT, OR PORTION(S) +THEREOF, EXCEPT AS EXPRESSLY PROVIDED IN THIS LICENSE (EVEN IF +APPLICABLE LAW GIVES YOU MORE RIGHTS). ANY ATTEMPT (EVEN IF +PERMITTED BY APPLICABLE LAW) OTHERWISE TO USE, MODIFY, COPY, +CREATE DERIVATIVE WORKS OF, (RE)DISTRIBUTE, OR SUBLICENSE THIS +PRODUCT, OR PORTION(S) THEREOF, AUTOMATICALLY AND IMMEDIATELY +TERMINATES YOUR RIGHTS UNDER THIS LICENSE AND CAN CONSTITUTE +COPYRIGHT INFRINGEMENT (WHICH MAY BE PROSECUTED). ANY CONDITIONS +AND RESTRICTIONS CONTAINED IN THIS LICENSE ARE ALSO LIMITATIONS +ON THE SCOPE OF THIS LICENSE AND ALSO DEFINE THE SCOPE OF YOUR +RIGHTS UNDER THIS LICENSE. YOUR FAILURE TO COMPLY WITH THE TERMS +AND CONDITIONS OF THIS LICENSE OR FAILURE TO PERFORM ANY +APPLICABLE OBLIGATION IMPOSED BY THIS LICENSE AUTOMATICALLY AND +IMMEDIATELY TERMINATES YOUR RIGHTS UNDER THIS LICENSE AND CAN +CAUSE OR BE CONSIDERED COPYRIGHT INFRINGEMENT (WHICH MAY BE +PROSECUTED). NOTHING IN THIS LICENSE SHALL IMPLY OR BE CONSTRUED +AS A PROMISE, OBLIGATION, OR COVENANT NOT TO SUE FOR COPYRIGHT +OR TRADEMARK INFRINGEMENT IF YOU DO NOT COMPLY WITH THE TERMS +AND CONDITIONS OF THIS LICENSE. + +3. This License does not constitute or imply a waiver of any +intellectual property rights except as may be otherwise +expressly provided in this License. This License does not +transfer, assign, or convey any intellectual property rights +(e.g., it does not transfer ownership of copyrights or +trademarks). + +4. Subject to the terms and conditions of this License, You may +allow a third party to use Your copy of This Product (or a copy +that You make and distribute, or Your Product) provided that the +third party explicitly accepts and agrees to be bound by all +terms and conditions of this License and the third party is not +prohibited from using This Product (or portions thereof) by this +License (see, e.g., Section VI.7) or by applicable law. However, +You are not obligated to ensure that the third party accepts +(and agrees to be bound by all terms of) this License if You +distribute only the self-extracting package (containing This +Product) that does not allow the user to install (nor extract) +the files contained in the package until he or she accepts and +agrees to be bound by all terms and conditions of this License. + +5. Without specific prior written permission from the authors of +This Product (or from their common representative), You must not +use the name of This Product, the names of the authors of This +Product, or the names of the legal entities (or informal groups) +of which the authors were/are members/employees, to endorse or +promote Your Product or any work in which You include a modified +or unmodified version of This Product, or to endorse or promote +You or Your affiliates, or in a way that might suggest that Your +Product (or any work in which You include a modified or +unmodified version of This Product), You, or Your affiliates +is/are endorsed by one or more authors of This Product, or in a +way that might suggest that one or more authors of This Product +is/are affiliated with You (or Your affiliates) or directly +participated in the creation of Your Product or of any work in +which You include a modified or unmodified version of This +Product. + +6. IF YOU ARE NOT SURE WHETHER YOU UNDERSTAND ALL PARTS OF THIS +LICENSE OR IF YOU ARE NOT SURE WHETHER YOU CAN COMPLY WITH ALL +TERMS AND CONDITIONS OF THIS LICENSE, YOU MUST NOT USE, COPY, +MODIFY, CREATE DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS +PRODUCT, NOR ANY PORTION(S) OF IT. YOU SHOULD CONSULT WITH A +LAWYER. + +7. IF (IN RELEVANT CONTEXT) ANY PROVISION OF CHAPTER IV OF THIS +LICENSE IS UNENFORCEABLE, INVALID, OR PROHIBITED UNDER +APPLICABLE LAW IN YOUR JURISDICTION, YOU HAVE NO RIGHTS UNDER +THIS LICENSE AND YOU MUST NOT USE, COPY, MODIFY, CREATE +DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY +PORTION(S) THEREOF. + +8. Except as otherwise provided in this License, if any +provision of this License, or a portion thereof, is found to be +invalid or unenforceable under applicable law, it shall not +affect the validity or enforceability of the remainder of this +License, and such invalid or unenforceable provision shall be +construed to reflect the original intent of the provision and +shall be enforced to the maximum extent permitted by applicable +law so as to effect the original intent of the provision as +closely as possible. + +____________________________________________________________ + + +Third-Party Licenses + +This Product contains components that were created by third +parties and that are governed by third-party licenses, which are +contained hereinafter (separated by lines consisting of +underscores). Each of the third-party licenses applies only to +(portions of) the source code file(s) in which the third-party +license is contained or in which it is explicitly referenced, +and to compiled or otherwise processed forms of such source +code. None of the third-party licenses applies to This Product +as a whole, even when it uses terms such as "product", +"program", or any other equivalent terms/phrases. This Product +as a whole is governed by the TrueCrypt License (see above). +Some of the third-party components have been modified by the +authors of This Product. Unless otherwise stated, such +modifications and additions are governed by the TrueCrypt +License (see above). Note: Unless otherwise stated, graphics and +files that are not part of the source code are governed by the +TrueCrypt License. + +____________________________________________________________ + +License agreement for Encryption for the Masses. + +Copyright (C) 1998-2000 Paul Le Roux. All Rights Reserved. + +This product can be copied and distributed free of charge, +including source code. + +You may modify this product and source code, and distribute such +modifications, and you may derive new works based on this +product, provided that: + +1. Any product which is simply derived from this product cannot +be called E4M, or Encryption for the Masses. + +2. If you use any of the source code in your product, and your +product is distributed with source code, you must include this +notice with those portions of this source code that you use. + +Or, + +If your product is distributed in binary form only, you must +display on any packaging, and marketing materials which +reference your product, a notice which states: + +"This product uses components written by Paul Le Roux +" + +3. If you use any of the source code originally by Eric Young, +you must in addition follow his terms and conditions. + +4. Nothing requires that you accept this License, as you have +not signed it. However, nothing else grants you permission to +modify or distribute the product or its derivative works. + +These actions are prohibited by law if you do not accept this +License. + +5. If any of these license terms is found to be to broad in +scope, and declared invalid by any court or legal process, you +agree that all other terms shall not be so affected, and shall +remain valid and enforceable. + +6. THIS PROGRAM IS DISTRIBUTED FREE OF CHARGE, THEREFORE THERE +IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. UNLESS OTHERWISE STATED THE PROGRAM IS PROVIDED +"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR +IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE +ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS +WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE +COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +7. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY +MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE +LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, +INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR +INABILITY TO USE THE PROGRAM, INCLUDING BUT NOT LIMITED TO LOSS +OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH +ANY OTHER PROGRAMS, EVEN IF SUCH HOLDER OR OTHER PARTY HAD +PREVIOUSLY BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +____________________________________________________________ + +Copyright (c) 1998-2008, Brian Gladman, Worcester, UK. +All rights reserved. + +LICENSE TERMS + +The free distribution and use of this software is allowed (with +or without changes) provided that: + + 1. source code distributions include the above copyright + notice, this list of conditions and the following + disclaimer; + + 2. binary distributions include the above copyright notice, + this list of conditions and the following disclaimer in + their documentation; + + 3. the name of the copyright holder is not used to endorse + products built using this software without specific written + permission. + +DISCLAIMER + +This software is provided 'as is' with no explicit or implied +warranties in respect of its properties, including, but not +limited to, correctness and/or fitness for purpose. +____________________________________________________________ + +Copyright (C) 2002-2004 Mark Adler, all rights reserved +version 1.8, 9 Jan 2004 + +This software is provided 'as-is', without any express or +implied warranty. In no event will the author be held liable +for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you + use this software in a product, an acknowledgment in the + product documentation would be appreciated but is not + required. +2. Altered source versions must be plainly marked as such, and + must not be misrepresented as being the original software. +3. This notice may not be removed or altered from any source + distribution. +____________________________________________________________ diff --git a/src/Main/Forms/Forms.cpp b/src/Main/Forms/Forms.cpp index ee8455bf..3f0fcc9e 100644 --- a/src/Main/Forms/Forms.cpp +++ b/src/Main/Forms/Forms.cpp @@ -1,3525 +1,3525 @@ -/////////////////////////////////////////////////////////////////////////// -// C++ code generated with wxFormBuilder (version Jun 5 2014) -// http://www.wxformbuilder.org/ -// -// PLEASE DO "NOT" EDIT THIS FILE! -/////////////////////////////////////////////////////////////////////////// - -#include "System.h" - -#include "Forms.h" - -/////////////////////////////////////////////////////////////////////////// -using namespace VeraCrypt; - -MainFrameBase::MainFrameBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxSize( -1,496 ), wxDefaultSize ); - - MainMenuBar = new wxMenuBar( 0 ); - VolumesMenu = new wxMenu(); - wxMenuItem* CreateNewVolumeMenuItem; - CreateNewVolumeMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Create New Volume...") ) , wxEmptyString, wxITEM_NORMAL ); - VolumesMenu->Append( CreateNewVolumeMenuItem ); - - VolumesMenu->AppendSeparator(); - - MountVolumeMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Mount Volume") ) , wxEmptyString, wxITEM_NORMAL ); - VolumesMenu->Append( MountVolumeMenuItem ); - - wxMenuItem* AutoMountDevicesMenuItem; - AutoMountDevicesMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Auto-Mount All Device-Hosted Volumes") ) , wxEmptyString, wxITEM_NORMAL ); - VolumesMenu->Append( AutoMountDevicesMenuItem ); - - VolumesMenu->AppendSeparator(); - - DismountVolumeMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Dismount Volume") ) , wxEmptyString, wxITEM_NORMAL ); - VolumesMenu->Append( DismountVolumeMenuItem ); - - DismountAllMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Dismount All Mounted Volumes") ) , wxEmptyString, wxITEM_NORMAL ); - VolumesMenu->Append( DismountAllMenuItem ); - - VolumesMenu->AppendSeparator(); - - wxMenuItem* ChangePasswordMenuItem; - ChangePasswordMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Change Volume Password...") ) , wxEmptyString, wxITEM_NORMAL ); - VolumesMenu->Append( ChangePasswordMenuItem ); - - wxMenuItem* ChangePkcs5PrfMenuItem; - ChangePkcs5PrfMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Change Header Key Derivation Algorithm...") ) , wxEmptyString, wxITEM_NORMAL ); - VolumesMenu->Append( ChangePkcs5PrfMenuItem ); - - wxMenuItem* ChangeKeyfilesMenuItem; - ChangeKeyfilesMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Add/Remove Keyfiles to/from Volume...") ) , wxEmptyString, wxITEM_NORMAL ); - VolumesMenu->Append( ChangeKeyfilesMenuItem ); - - wxMenuItem* RemoveKeyfilesMenuItem; - RemoveKeyfilesMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Remove All Keyfiles from Volume...") ) , wxEmptyString, wxITEM_NORMAL ); - VolumesMenu->Append( RemoveKeyfilesMenuItem ); - - VolumesMenu->AppendSeparator(); - - VolumePropertiesMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Volume Properties...") ) , wxEmptyString, wxITEM_NORMAL ); - VolumesMenu->Append( VolumePropertiesMenuItem ); - - MainMenuBar->Append( VolumesMenu, _("&Volumes") ); - - FavoritesMenu = new wxMenu(); - AddToFavoritesMenuItem = new wxMenuItem( FavoritesMenu, wxID_ANY, wxString( _("Add Selected Volume to Favorites...") ) , wxEmptyString, wxITEM_NORMAL ); - FavoritesMenu->Append( AddToFavoritesMenuItem ); - - AddAllMountedToFavoritesMenuItem = new wxMenuItem( FavoritesMenu, wxID_ANY, wxString( _("Add All Mounted Volumes to Favorites...") ) , wxEmptyString, wxITEM_NORMAL ); - FavoritesMenu->Append( AddAllMountedToFavoritesMenuItem ); - - wxMenuItem* OrganizeFavoritesMenuItem; - OrganizeFavoritesMenuItem = new wxMenuItem( FavoritesMenu, wxID_ANY, wxString( _("Organize Favorite Volumes...") ) , wxEmptyString, wxITEM_NORMAL ); - FavoritesMenu->Append( OrganizeFavoritesMenuItem ); - - FavoritesMenu->AppendSeparator(); - - wxMenuItem* MountAllFavoritesMenuItem; - MountAllFavoritesMenuItem = new wxMenuItem( FavoritesMenu, wxID_ANY, wxString( _("Mount Favorite Volumes") ) , wxEmptyString, wxITEM_NORMAL ); - FavoritesMenu->Append( MountAllFavoritesMenuItem ); - - FavoritesMenu->AppendSeparator(); - - MainMenuBar->Append( FavoritesMenu, _("&Favorites") ); - - ToolsMenu = new wxMenu(); - wxMenuItem* BenchmarkMenuItem; - BenchmarkMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Benchmark...") ) , wxEmptyString, wxITEM_NORMAL ); - ToolsMenu->Append( BenchmarkMenuItem ); - - wxMenuItem* EncryptionTestMenuItem; - EncryptionTestMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Test Vectors...") ) , wxEmptyString, wxITEM_NORMAL ); - ToolsMenu->Append( EncryptionTestMenuItem ); - - ToolsMenu->AppendSeparator(); - - wxMenuItem* VolumeCreationWizardMenuItem; - VolumeCreationWizardMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Volume Creation Wizard") ) , wxEmptyString, wxITEM_NORMAL ); - ToolsMenu->Append( VolumeCreationWizardMenuItem ); - - ToolsMenu->AppendSeparator(); - - BackupVolumeHeadersMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Backup Volume Header...") ) , wxEmptyString, wxITEM_NORMAL ); - ToolsMenu->Append( BackupVolumeHeadersMenuItem ); - - RestoreVolumeHeaderMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Restore Volume Header...") ) , wxEmptyString, wxITEM_NORMAL ); - ToolsMenu->Append( RestoreVolumeHeaderMenuItem ); - - ToolsMenu->AppendSeparator(); - - wxMenuItem* CreateKeyfileMenuItem; - CreateKeyfileMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Keyfile Generator") ) , wxEmptyString, wxITEM_NORMAL ); - ToolsMenu->Append( CreateKeyfileMenuItem ); - - wxMenuItem* ManageSecurityTokenKeyfilesMenuItem; - ManageSecurityTokenKeyfilesMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Manage Security Token Keyfiles...") ) , wxEmptyString, wxITEM_NORMAL ); - ToolsMenu->Append( ManageSecurityTokenKeyfilesMenuItem ); - - wxMenuItem* CloseAllSecurityTokenSessionsMenuItem; - CloseAllSecurityTokenSessionsMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Close All Security Token Sessions") ) , wxEmptyString, wxITEM_NORMAL ); - ToolsMenu->Append( CloseAllSecurityTokenSessionsMenuItem ); - - ToolsMenu->AppendSeparator(); - - WipeCachedPasswordsMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Wipe Cached Passwords") ) , wxEmptyString, wxITEM_NORMAL ); - ToolsMenu->Append( WipeCachedPasswordsMenuItem ); - - MainMenuBar->Append( ToolsMenu, _("T&ools") ); - - SettingsMenu = new wxMenu(); - HotkeysMenuItem = new wxMenuItem( SettingsMenu, wxID_ANY, wxString( _("Hotkeys...") ) , wxEmptyString, wxITEM_NORMAL ); - SettingsMenu->Append( HotkeysMenuItem ); - - wxMenuItem* DefaultKeyfilesMenuItem; - DefaultKeyfilesMenuItem = new wxMenuItem( SettingsMenu, wxID_ANY, wxString( _("Default Keyfiles...") ) , wxEmptyString, wxITEM_NORMAL ); - SettingsMenu->Append( DefaultKeyfilesMenuItem ); - - wxMenuItem* DefaultMountParametersMenuItem; - DefaultMountParametersMenuItem = new wxMenuItem( SettingsMenu, wxID_ANY, wxString( _("Default Mount Parameters...") ) , wxEmptyString, wxITEM_NORMAL ); - SettingsMenu->Append( DefaultMountParametersMenuItem ); - - wxMenuItem* SecurityTokenPreferencesMenuItem; - SecurityTokenPreferencesMenuItem = new wxMenuItem( SettingsMenu, wxID_ANY, wxString( _("Security Tokens...") ) , wxEmptyString, wxITEM_NORMAL ); - SettingsMenu->Append( SecurityTokenPreferencesMenuItem ); - - SettingsMenu->AppendSeparator(); - - PreferencesMenuItem = new wxMenuItem( SettingsMenu, wxID_PREFERENCES, wxString( _("&Preferences...") ) , wxEmptyString, wxITEM_NORMAL ); - SettingsMenu->Append( PreferencesMenuItem ); - - MainMenuBar->Append( SettingsMenu, _("Settin&gs") ); - - HelpMenu = new wxMenu(); - wxMenuItem* UserGuideMenuItem; - UserGuideMenuItem = new wxMenuItem( HelpMenu, wxID_HELP, wxString( _("User's Guide") ) , wxEmptyString, wxITEM_NORMAL ); - HelpMenu->Append( UserGuideMenuItem ); - - wxMenuItem* OnlineHelpMenuItem; - OnlineHelpMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Online Help") ) , wxEmptyString, wxITEM_NORMAL ); - HelpMenu->Append( OnlineHelpMenuItem ); - - wxMenuItem* BeginnersTutorialMenuItem; - BeginnersTutorialMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Beginner's Tutorial") ) , wxEmptyString, wxITEM_NORMAL ); - HelpMenu->Append( BeginnersTutorialMenuItem ); - - wxMenuItem* FaqMenuItem; - FaqMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Frequently Asked Questions") ) , wxEmptyString, wxITEM_NORMAL ); - HelpMenu->Append( FaqMenuItem ); - - HelpMenu->AppendSeparator(); - - wxMenuItem* WebsiteMenuItem; - WebsiteMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("VeraCrypt Website") ) , wxEmptyString, wxITEM_NORMAL ); - HelpMenu->Append( WebsiteMenuItem ); - - wxMenuItem* DownloadsMenuItem; - DownloadsMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Downloads") ) , wxEmptyString, wxITEM_NORMAL ); - HelpMenu->Append( DownloadsMenuItem ); - - wxMenuItem* NewsMenuItem; - NewsMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("News") ) , wxEmptyString, wxITEM_NORMAL ); - HelpMenu->Append( NewsMenuItem ); - - wxMenuItem* VersionHistoryMenuItem; - VersionHistoryMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Version History") ) , wxEmptyString, wxITEM_NORMAL ); - HelpMenu->Append( VersionHistoryMenuItem ); - - HelpMenu->AppendSeparator(); - - wxMenuItem* DonateMenuItem; - DonateMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Donate") ) , wxEmptyString, wxITEM_NORMAL ); - HelpMenu->Append( DonateMenuItem ); - - wxMenuItem* ContactMenuItem; - ContactMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Contact") ) , wxEmptyString, wxITEM_NORMAL ); - HelpMenu->Append( ContactMenuItem ); - - wxMenuItem* LegalNoticesMenuItem; - LegalNoticesMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Legal Notices") ) , wxEmptyString, wxITEM_NORMAL ); - HelpMenu->Append( LegalNoticesMenuItem ); - - wxMenuItem* AboutMenuItem; - AboutMenuItem = new wxMenuItem( HelpMenu, wxID_ABOUT, wxString( _("About") ) , wxEmptyString, wxITEM_NORMAL ); - HelpMenu->Append( AboutMenuItem ); - - MainMenuBar->Append( HelpMenu, _("&Help") ); - - this->SetMenuBar( MainMenuBar ); - - wxBoxSizer* bSizer1; - bSizer1 = new wxBoxSizer( wxVERTICAL ); - - MainPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - wxBoxSizer* bSizer2; - bSizer2 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer48; - bSizer48 = new wxBoxSizer( wxVERTICAL ); - - wxStaticBoxSizer* sbSizer1; - sbSizer1 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - SlotListCtrl = new wxListCtrl( MainPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES|wxSUNKEN_BORDER ); - sbSizer1->Add( SlotListCtrl, 1, wxALL|wxEXPAND, 5 ); - - - bSizer48->Add( sbSizer1, 1, wxEXPAND, 5 ); - - LowStaticBoxSizer = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - HigherButtonSizer = new wxBoxSizer( wxVERTICAL ); - - - LowStaticBoxSizer->Add( HigherButtonSizer, 0, wxEXPAND|wxTOP, 2 ); - - wxGridSizer* gSizer1; - gSizer1 = new wxGridSizer( 1, 3, 0, 0 ); - - wxBoxSizer* bSizer17; - bSizer17 = new wxBoxSizer( wxVERTICAL ); - - bSizer17->SetMinSize( wxSize( 138,34 ) ); - CreateVolumeButton = new wxButton( MainPanel, wxID_ANY, _("&Create Volume"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer17->Add( CreateVolumeButton, 1, wxALL|wxEXPAND, 5 ); - - - gSizer1->Add( bSizer17, 0, 0, 5 ); - - wxBoxSizer* bSizer18; - bSizer18 = new wxBoxSizer( wxVERTICAL ); - - bSizer18->SetMinSize( wxSize( 138,34 ) ); - VolumePropertiesButton = new wxButton( MainPanel, wxID_ANY, _("&Volume Properties..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer18->Add( VolumePropertiesButton, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxEXPAND, 5 ); - - - gSizer1->Add( bSizer18, 0, wxALIGN_CENTER_HORIZONTAL, 5 ); - - wxBoxSizer* bSizer19; - bSizer19 = new wxBoxSizer( wxVERTICAL ); - - bSizer19->SetMinSize( wxSize( 138,34 ) ); - WipeCacheButton = new wxButton( MainPanel, wxID_ANY, _("&Wipe Cache"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer19->Add( WipeCacheButton, 1, wxALL|wxALIGN_RIGHT|wxEXPAND, 5 ); - - - gSizer1->Add( bSizer19, 0, wxALIGN_RIGHT, 5 ); - - - LowStaticBoxSizer->Add( gSizer1, 0, wxEXPAND|wxRIGHT|wxLEFT, 5 ); - - - LowStaticBoxSizer->Add( 0, 0, 0, 0, 5 ); - - VolumeStaticBoxSizer = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, _("Volume") ), wxVERTICAL ); - - VolumeGridBagSizer = new wxGridBagSizer( 0, 0 ); - VolumeGridBagSizer->SetFlexibleDirection( wxBOTH ); - VolumeGridBagSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - - LogoBitmap = new wxStaticBitmap( MainPanel, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER ); - LogoBitmap->SetMinSize( wxSize( 42,52 ) ); - - VolumeGridBagSizer->Add( LogoBitmap, wxGBPosition( 0, 0 ), wxGBSpan( 2, 1 ), wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - VolumePathComboBox = new wxComboBox( MainPanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_DROPDOWN ); - VolumeGridBagSizer->Add( VolumePathComboBox, wxGBPosition( 0, 1 ), wxGBSpan( 1, 2 ), wxEXPAND|wxALL, 5 ); - - wxBoxSizer* bSizer191; - bSizer191 = new wxBoxSizer( wxVERTICAL ); - - bSizer191->SetMinSize( wxSize( 138,34 ) ); - SelectFileButton = new wxButton( MainPanel, wxID_ANY, _("Select &File..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer191->Add( SelectFileButton, 1, wxALL|wxEXPAND, 5 ); - - - VolumeGridBagSizer->Add( bSizer191, wxGBPosition( 0, 3 ), wxGBSpan( 1, 1 ), wxEXPAND, 5 ); - - NoHistoryCheckBox = new wxCheckBox( MainPanel, wxID_ANY, _("&Never save history"), wxDefaultPosition, wxDefaultSize, 0 ); - VolumeGridBagSizer->Add( NoHistoryCheckBox, wxGBPosition( 1, 1 ), wxGBSpan( 1, 1 ), wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - - wxBoxSizer* bSizer20; - bSizer20 = new wxBoxSizer( wxVERTICAL ); - - bSizer20->SetMinSize( wxSize( 138,34 ) ); - VolumeToolsButton = new wxButton( MainPanel, wxID_ANY, _("Volume &Tools..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer20->Add( VolumeToolsButton, 1, wxALL|wxEXPAND, 5 ); - - - VolumeGridBagSizer->Add( bSizer20, wxGBPosition( 1, 2 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT, 5 ); - - wxBoxSizer* bSizer21; - bSizer21 = new wxBoxSizer( wxVERTICAL ); - - bSizer21->SetMinSize( wxSize( 138,34 ) ); - SelectDeviceButton = new wxButton( MainPanel, wxID_ANY, _("Select D&evice..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer21->Add( SelectDeviceButton, 1, wxEXPAND|wxALL, 5 ); - - - VolumeGridBagSizer->Add( bSizer21, wxGBPosition( 1, 3 ), wxGBSpan( 1, 1 ), wxEXPAND, 5 ); - - - VolumeGridBagSizer->AddGrowableCol( 1 ); - VolumeGridBagSizer->AddGrowableRow( 0 ); - - VolumeStaticBoxSizer->Add( VolumeGridBagSizer, 1, wxEXPAND|wxALL, 4 ); - - - LowStaticBoxSizer->Add( VolumeStaticBoxSizer, 1, wxEXPAND, 5 ); - - - LowStaticBoxSizer->Add( 0, 0, 0, 0, 5 ); - - wxGridSizer* gSizer2; - gSizer2 = new wxGridSizer( 1, 4, 0, 0 ); - - wxStaticBoxSizer* sbSizer4; - sbSizer4 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - sbSizer4->SetMinSize( wxSize( 139,-1 ) ); - VolumeButton = new wxButton( MainPanel, wxID_ANY, _("&Mount"), wxDefaultPosition, wxDefaultSize, 0 ); - VolumeButton->SetDefault(); - VolumeButton->SetMinSize( wxSize( -1,32 ) ); - - sbSizer4->Add( VolumeButton, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP, 2 ); - - - gSizer2->Add( sbSizer4, 1, wxEXPAND, 0 ); - - wxStaticBoxSizer* sbSizer41; - sbSizer41 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - MountAllDevicesButton = new wxButton( MainPanel, wxID_ANY, _("&Auto-Mount Devices"), wxDefaultPosition, wxDefaultSize, 0 ); - MountAllDevicesButton->SetMinSize( wxSize( -1,32 ) ); - - sbSizer41->Add( MountAllDevicesButton, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP, 2 ); - - - gSizer2->Add( sbSizer41, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND, 5 ); - - wxStaticBoxSizer* sbSizer42; - sbSizer42 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - DismountAllButton = new wxButton( MainPanel, wxID_ANY, _("Di&smount All"), wxDefaultPosition, wxDefaultSize, 0 ); - DismountAllButton->SetMinSize( wxSize( -1,32 ) ); - - sbSizer42->Add( DismountAllButton, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP, 2 ); - - - gSizer2->Add( sbSizer42, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND, 5 ); - - wxStaticBoxSizer* sbSizer43; - sbSizer43 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - ExitButton = new wxButton( MainPanel, wxID_ANY, _("E&xit"), wxDefaultPosition, wxDefaultSize, 0 ); - ExitButton->SetMinSize( wxSize( -1,32 ) ); - - sbSizer43->Add( ExitButton, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP, 2 ); - - - gSizer2->Add( sbSizer43, 1, wxALIGN_RIGHT|wxEXPAND, 5 ); - - - LowStaticBoxSizer->Add( gSizer2, 0, wxEXPAND, 5 ); - - - bSizer48->Add( LowStaticBoxSizer, 0, wxEXPAND, 5 ); - - - bSizer2->Add( bSizer48, 1, wxEXPAND, 5 ); - - - MainPanel->SetSizer( bSizer2 ); - MainPanel->Layout(); - bSizer2->Fit( MainPanel ); - bSizer1->Add( MainPanel, 1, wxEXPAND, 0 ); - - - this->SetSizer( bSizer1 ); - this->Layout(); - bSizer1->Fit( this ); - - this->Centre( wxBOTH ); - - // Connect Events - this->Connect( wxEVT_ACTIVATE, wxActivateEventHandler( MainFrameBase::OnActivate ) ); - this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( MainFrameBase::OnClose ) ); - this->Connect( CreateNewVolumeMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCreateVolumeButtonClick ) ); - this->Connect( MountVolumeMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnMountVolumeMenuItemSelected ) ); - this->Connect( AutoMountDevicesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnMountAllDevicesButtonClick ) ); - this->Connect( DismountVolumeMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDismountVolumeMenuItemSelected ) ); - this->Connect( DismountAllMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDismountAllButtonClick ) ); - this->Connect( ChangePasswordMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnChangePasswordMenuItemSelected ) ); - this->Connect( ChangePkcs5PrfMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnChangePkcs5PrfMenuItemSelected ) ); - this->Connect( ChangeKeyfilesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnChangeKeyfilesMenuItemSelected ) ); - this->Connect( RemoveKeyfilesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnRemoveKeyfilesMenuItemSelected ) ); - this->Connect( VolumePropertiesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnVolumePropertiesButtonClick ) ); - this->Connect( AddToFavoritesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnAddToFavoritesMenuItemSelected ) ); - this->Connect( AddAllMountedToFavoritesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnAddAllMountedToFavoritesMenuItemSelected ) ); - this->Connect( OrganizeFavoritesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnOrganizeFavoritesMenuItemSelected ) ); - this->Connect( MountAllFavoritesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnMountAllFavoritesMenuItemSelected ) ); - this->Connect( BenchmarkMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnBenchmarkMenuItemSelected ) ); - this->Connect( EncryptionTestMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnEncryptionTestMenuItemSelected ) ); - this->Connect( VolumeCreationWizardMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCreateVolumeButtonClick ) ); - this->Connect( BackupVolumeHeadersMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnBackupVolumeHeadersMenuItemSelected ) ); - this->Connect( RestoreVolumeHeaderMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnRestoreVolumeHeaderMenuItemSelected ) ); - this->Connect( CreateKeyfileMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCreateKeyfileMenuItemSelected ) ); - this->Connect( ManageSecurityTokenKeyfilesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnManageSecurityTokenKeyfilesMenuItemSelected ) ); - this->Connect( CloseAllSecurityTokenSessionsMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCloseAllSecurityTokenSessionsMenuItemSelected ) ); - this->Connect( WipeCachedPasswordsMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnWipeCacheButtonClick ) ); - this->Connect( HotkeysMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnHotkeysMenuItemSelected ) ); - this->Connect( DefaultKeyfilesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDefaultKeyfilesMenuItemSelected ) ); - this->Connect( DefaultMountParametersMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDefaultMountParametersMenuItemSelected ) ); - this->Connect( SecurityTokenPreferencesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnSecurityTokenPreferencesMenuItemSelected ) ); - this->Connect( PreferencesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnPreferencesMenuItemSelected ) ); - this->Connect( UserGuideMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnUserGuideMenuItemSelected ) ); - this->Connect( OnlineHelpMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnOnlineHelpMenuItemSelected ) ); - this->Connect( BeginnersTutorialMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnBeginnersTutorialMenuItemSelected ) ); - this->Connect( FaqMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnFaqMenuItemSelected ) ); - this->Connect( WebsiteMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnWebsiteMenuItemSelected ) ); - this->Connect( DownloadsMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDownloadsMenuItemSelected ) ); - this->Connect( NewsMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnNewsMenuItemSelected ) ); - this->Connect( VersionHistoryMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnVersionHistoryMenuItemSelected ) ); - this->Connect( DonateMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDonateMenuItemSelected ) ); - this->Connect( ContactMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnContactMenuItemSelected ) ); - this->Connect( LegalNoticesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnLegalNoticesMenuItemSelected ) ); - this->Connect( AboutMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnAboutMenuItemSelected ) ); - SlotListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( MainFrameBase::OnListItemActivated ), NULL, this ); - SlotListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( MainFrameBase::OnListItemDeselected ), NULL, this ); - SlotListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, wxListEventHandler( MainFrameBase::OnListItemRightClick ), NULL, this ); - SlotListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( MainFrameBase::OnListItemSelected ), NULL, this ); - CreateVolumeButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnCreateVolumeButtonClick ), NULL, this ); - VolumePropertiesButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnVolumePropertiesButtonClick ), NULL, this ); - WipeCacheButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnWipeCacheButtonClick ), NULL, this ); - LogoBitmap->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( MainFrameBase::OnLogoBitmapClick ), NULL, this ); - SelectFileButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnSelectFileButtonClick ), NULL, this ); - NoHistoryCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MainFrameBase::OnNoHistoryCheckBoxClick ), NULL, this ); - VolumeToolsButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnVolumeToolsButtonClick ), NULL, this ); - SelectDeviceButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnSelectDeviceButtonClick ), NULL, this ); - VolumeButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnVolumeButtonClick ), NULL, this ); - MountAllDevicesButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnMountAllDevicesButtonClick ), NULL, this ); - DismountAllButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnDismountAllButtonClick ), NULL, this ); - ExitButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnExitButtonClick ), NULL, this ); -} - -MainFrameBase::~MainFrameBase() -{ - // Disconnect Events - this->Disconnect( wxEVT_ACTIVATE, wxActivateEventHandler( MainFrameBase::OnActivate ) ); - this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( MainFrameBase::OnClose ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCreateVolumeButtonClick ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnMountVolumeMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnMountAllDevicesButtonClick ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDismountVolumeMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDismountAllButtonClick ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnChangePasswordMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnChangePkcs5PrfMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnChangeKeyfilesMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnRemoveKeyfilesMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnVolumePropertiesButtonClick ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnAddToFavoritesMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnAddAllMountedToFavoritesMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnOrganizeFavoritesMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnMountAllFavoritesMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnBenchmarkMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnEncryptionTestMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCreateVolumeButtonClick ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnBackupVolumeHeadersMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnRestoreVolumeHeaderMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCreateKeyfileMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnManageSecurityTokenKeyfilesMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCloseAllSecurityTokenSessionsMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnWipeCacheButtonClick ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnHotkeysMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDefaultKeyfilesMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDefaultMountParametersMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnSecurityTokenPreferencesMenuItemSelected ) ); - this->Disconnect( wxID_PREFERENCES, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnPreferencesMenuItemSelected ) ); - this->Disconnect( wxID_HELP, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnUserGuideMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnOnlineHelpMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnBeginnersTutorialMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnFaqMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnWebsiteMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDownloadsMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnNewsMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnVersionHistoryMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDonateMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnContactMenuItemSelected ) ); - this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnLegalNoticesMenuItemSelected ) ); - this->Disconnect( wxID_ABOUT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnAboutMenuItemSelected ) ); - SlotListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( MainFrameBase::OnListItemActivated ), NULL, this ); - SlotListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( MainFrameBase::OnListItemDeselected ), NULL, this ); - SlotListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, wxListEventHandler( MainFrameBase::OnListItemRightClick ), NULL, this ); - SlotListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( MainFrameBase::OnListItemSelected ), NULL, this ); - CreateVolumeButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnCreateVolumeButtonClick ), NULL, this ); - VolumePropertiesButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnVolumePropertiesButtonClick ), NULL, this ); - WipeCacheButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnWipeCacheButtonClick ), NULL, this ); - LogoBitmap->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( MainFrameBase::OnLogoBitmapClick ), NULL, this ); - SelectFileButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnSelectFileButtonClick ), NULL, this ); - NoHistoryCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MainFrameBase::OnNoHistoryCheckBoxClick ), NULL, this ); - VolumeToolsButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnVolumeToolsButtonClick ), NULL, this ); - SelectDeviceButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnSelectDeviceButtonClick ), NULL, this ); - VolumeButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnVolumeButtonClick ), NULL, this ); - MountAllDevicesButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnMountAllDevicesButtonClick ), NULL, this ); - DismountAllButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnDismountAllButtonClick ), NULL, this ); - ExitButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnExitButtonClick ), NULL, this ); - -} - -WizardFrameBase::WizardFrameBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxSize( 800,500 ), wxDefaultSize ); - - MainSizer = new wxBoxSizer( wxVERTICAL ); - - MainPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - wxBoxSizer* bSizer63; - bSizer63 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer64; - bSizer64 = new wxBoxSizer( wxVERTICAL ); - - wxStaticBoxSizer* sbSizer27; - sbSizer27 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxHORIZONTAL ); - - WizardBitmap = new wxStaticBitmap( MainPanel, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer27->Add( WizardBitmap, 0, wxALL|wxEXPAND, 5 ); - - wxBoxSizer* bSizer66; - bSizer66 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer126; - bSizer126 = new wxBoxSizer( wxHORIZONTAL ); - - PageTitleStaticText = new wxStaticText( MainPanel, wxID_ANY, _("Page Title"), wxDefaultPosition, wxDefaultSize, 0 ); - PageTitleStaticText->Wrap( -1 ); - PageTitleStaticText->SetFont( wxFont( 16, 70, 90, 90, false, wxT("Times New Roman") ) ); - - bSizer126->Add( PageTitleStaticText, 0, wxALL, 5 ); - - - bSizer66->Add( bSizer126, 0, wxLEFT, 5 ); - - PageSizer = new wxBoxSizer( wxVERTICAL ); - - - bSizer66->Add( PageSizer, 1, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - - sbSizer27->Add( bSizer66, 1, wxEXPAND|wxLEFT, 5 ); - - - bSizer64->Add( sbSizer27, 1, wxEXPAND|wxRIGHT|wxLEFT, 5 ); - - wxBoxSizer* bSizer70; - bSizer70 = new wxBoxSizer( wxHORIZONTAL ); - - - bSizer70->Add( 0, 0, 1, wxEXPAND, 5 ); - - HelpButton = new wxButton( MainPanel, wxID_HELP, _("&Help"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer70->Add( HelpButton, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); - - - bSizer70->Add( 0, 0, 0, wxLEFT|wxALIGN_RIGHT, 5 ); - - PreviousButton = new wxButton( MainPanel, wxID_ANY, _("< &Prev"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer70->Add( PreviousButton, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); - - NextButton = new wxButton( MainPanel, wxID_ANY, _("&Next >"), wxDefaultPosition, wxDefaultSize, 0|wxWANTS_CHARS ); - NextButton->SetDefault(); - bSizer70->Add( NextButton, 0, wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); - - - bSizer70->Add( 0, 0, 0, wxLEFT|wxALIGN_RIGHT, 5 ); - - CancelButton = new wxButton( MainPanel, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer70->Add( CancelButton, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); - - - bSizer64->Add( bSizer70, 0, wxEXPAND|wxALIGN_RIGHT|wxALL, 5 ); - - - bSizer63->Add( bSizer64, 1, wxEXPAND, 5 ); - - - MainPanel->SetSizer( bSizer63 ); - MainPanel->Layout(); - bSizer63->Fit( MainPanel ); - MainSizer->Add( MainPanel, 1, wxEXPAND, 5 ); - - - this->SetSizer( MainSizer ); - this->Layout(); - MainSizer->Fit( this ); - - // Connect Events - this->Connect( wxEVT_ACTIVATE, wxActivateEventHandler( WizardFrameBase::OnActivate ) ); - this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( WizardFrameBase::OnClose ) ); - MainPanel->Connect( wxEVT_MOTION, wxMouseEventHandler( WizardFrameBase::OnMouseMotion ), NULL, this ); - HelpButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnHelpButtonClick ), NULL, this ); - PreviousButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnPreviousButtonClick ), NULL, this ); - NextButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnNextButtonClick ), NULL, this ); - CancelButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnCancelButtonClick ), NULL, this ); -} - -WizardFrameBase::~WizardFrameBase() -{ - // Disconnect Events - this->Disconnect( wxEVT_ACTIVATE, wxActivateEventHandler( WizardFrameBase::OnActivate ) ); - this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( WizardFrameBase::OnClose ) ); - MainPanel->Disconnect( wxEVT_MOTION, wxMouseEventHandler( WizardFrameBase::OnMouseMotion ), NULL, this ); - HelpButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnHelpButtonClick ), NULL, this ); - PreviousButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnPreviousButtonClick ), NULL, this ); - NextButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnNextButtonClick ), NULL, this ); - CancelButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnCancelButtonClick ), NULL, this ); - -} - -AboutDialogBase::AboutDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - - wxBoxSizer* bSizer116; - bSizer116 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer117; - bSizer117 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer120; - bSizer120 = new wxBoxSizer( wxVERTICAL ); - - bSizer120->SetMinSize( wxSize( -1,78 ) ); - m_panel14 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - m_panel14->SetBackgroundColour( wxColour( 10, 108, 206 ) ); - - wxBoxSizer* bSizer121; - bSizer121 = new wxBoxSizer( wxVERTICAL ); - - - bSizer121->Add( 0, 0, 1, wxEXPAND|wxALL, 5 ); - - wxBoxSizer* bSizer122; - bSizer122 = new wxBoxSizer( wxVERTICAL ); - - LogoBitmap = new wxStaticBitmap( m_panel14, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxDefaultSize, 0 ); - bSizer122->Add( LogoBitmap, 0, wxALL, 10 ); - - - bSizer121->Add( bSizer122, 0, wxEXPAND|wxLEFT, 8 ); - - - m_panel14->SetSizer( bSizer121 ); - m_panel14->Layout(); - bSizer121->Fit( m_panel14 ); - bSizer120->Add( m_panel14, 1, wxEXPAND, 5 ); - - - bSizer117->Add( bSizer120, 0, wxEXPAND, 5 ); - - wxBoxSizer* bSizer118; - bSizer118 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer123; - bSizer123 = new wxBoxSizer( wxVERTICAL ); - - VersionStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - VersionStaticText->Wrap( -1 ); - bSizer123->Add( VersionStaticText, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); - - - bSizer123->Add( 0, 0, 0, wxTOP, 3 ); - - CopyrightStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - CopyrightStaticText->Wrap( -1 ); - bSizer123->Add( CopyrightStaticText, 0, wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - - - bSizer123->Add( 0, 0, 0, wxTOP, 3 ); - - WebsiteHyperlink = new wxHyperlinkCtrl( this, wxID_ANY, wxEmptyString, wxT("."), wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); - - WebsiteHyperlink->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - WebsiteHyperlink->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - WebsiteHyperlink->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - bSizer123->Add( WebsiteHyperlink, 0, wxALL, 5 ); - - - bSizer118->Add( bSizer123, 1, wxEXPAND|wxLEFT, 5 ); - - - bSizer117->Add( bSizer118, 1, wxALL|wxEXPAND, 15 ); - - m_staticline3 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); - bSizer117->Add( m_staticline3, 0, wxEXPAND|wxBOTTOM, 5 ); - - CreditsTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY|wxSUNKEN_BORDER ); - bSizer117->Add( CreditsTextCtrl, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 10 ); - - - bSizer117->Add( 0, 0, 0, wxTOP, 5 ); - - m_staticline4 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); - bSizer117->Add( m_staticline4, 0, wxEXPAND|wxTOP|wxBOTTOM, 3 ); - - m_staticline5 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); - bSizer117->Add( m_staticline5, 0, wxEXPAND|wxBOTTOM, 5 ); - - wxBoxSizer* bSizer119; - bSizer119 = new wxBoxSizer( wxHORIZONTAL ); - - - bSizer119->Add( 0, 0, 1, wxEXPAND|wxALL, 5 ); - - wxButton* OKButton; - OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); - bSizer119->Add( OKButton, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - - bSizer119->Add( 0, 0, 0, wxLEFT, 5 ); - - - bSizer117->Add( bSizer119, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 6 ); - - - bSizer116->Add( bSizer117, 1, wxEXPAND, 5 ); - - - this->SetSizer( bSizer116 ); - this->Layout(); - bSizer116->Fit( this ); - - // Connect Events - WebsiteHyperlink->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( AboutDialogBase::OnWebsiteHyperlinkClick ), NULL, this ); -} - -AboutDialogBase::~AboutDialogBase() -{ - // Disconnect Events - WebsiteHyperlink->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( AboutDialogBase::OnWebsiteHyperlinkClick ), NULL, this ); - -} - -BenchmarkDialogBase::BenchmarkDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - - wxBoxSizer* bSizer153; - bSizer153 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer154; - bSizer154 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer155; - bSizer155 = new wxBoxSizer( wxHORIZONTAL ); - - wxStaticText* m_staticText54; - m_staticText54 = new wxStaticText( this, wxID_ANY, _("Buffer Size:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText54->Wrap( -1 ); - bSizer155->Add( m_staticText54, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - wxArrayString BufferSizeChoiceChoices; - BufferSizeChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, BufferSizeChoiceChoices, 0 ); - BufferSizeChoice->SetSelection( 0 ); - bSizer155->Add( BufferSizeChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - - bSizer154->Add( bSizer155, 0, wxEXPAND, 5 ); - - wxStaticLine* m_staticline6; - m_staticline6 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); - bSizer154->Add( m_staticline6, 0, wxEXPAND | wxALL, 5 ); - - wxBoxSizer* bSizer156; - bSizer156 = new wxBoxSizer( wxHORIZONTAL ); - - BenchmarkListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxSUNKEN_BORDER ); - bSizer156->Add( BenchmarkListCtrl, 1, wxALL|wxEXPAND, 5 ); - - RightSizer = new wxBoxSizer( wxVERTICAL ); - - BenchmarkButton = new wxButton( this, wxID_OK, _("Benchmark"), wxDefaultPosition, wxDefaultSize, 0 ); - BenchmarkButton->SetDefault(); - RightSizer->Add( BenchmarkButton, 0, wxALL|wxEXPAND, 5 ); - - wxButton* CancelButton; - CancelButton = new wxButton( this, wxID_CANCEL, _("Close"), wxDefaultPosition, wxDefaultSize, 0 ); - RightSizer->Add( CancelButton, 0, wxALL|wxEXPAND, 5 ); - - - RightSizer->Add( 0, 0, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 ); - - BenchmarkNoteStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - BenchmarkNoteStaticText->Wrap( -1 ); - RightSizer->Add( BenchmarkNoteStaticText, 1, wxALL|wxEXPAND, 5 ); - - - bSizer156->Add( RightSizer, 0, wxEXPAND, 5 ); - - - bSizer154->Add( bSizer156, 1, wxEXPAND, 5 ); - - - bSizer153->Add( bSizer154, 1, wxEXPAND|wxALL, 5 ); - - - this->SetSizer( bSizer153 ); - this->Layout(); - bSizer153->Fit( this ); - - // Connect Events - BenchmarkButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( BenchmarkDialogBase::OnBenchmarkButtonClick ), NULL, this ); -} - -BenchmarkDialogBase::~BenchmarkDialogBase() -{ - // Disconnect Events - BenchmarkButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( BenchmarkDialogBase::OnBenchmarkButtonClick ), NULL, this ); - -} - -ChangePasswordDialogBase::ChangePasswordDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); - - wxBoxSizer* bSizer30; - bSizer30 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer31; - bSizer31 = new wxBoxSizer( wxHORIZONTAL ); - - wxBoxSizer* bSizer32; - bSizer32 = new wxBoxSizer( wxVERTICAL ); - - CurrentSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Current") ), wxVERTICAL ); - - CurrentPasswordPanelSizer = new wxBoxSizer( wxVERTICAL ); - - - CurrentSizer->Add( CurrentPasswordPanelSizer, 0, wxALIGN_LEFT, 5 ); - - - bSizer32->Add( CurrentSizer, 0, wxEXPAND, 5 ); - - NewSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("New") ), wxVERTICAL ); - - NewPasswordPanelSizer = new wxBoxSizer( wxVERTICAL ); - - - NewSizer->Add( NewPasswordPanelSizer, 0, wxALIGN_LEFT, 5 ); - - - bSizer32->Add( NewSizer, 0, wxTOP|wxEXPAND, 5 ); - - - bSizer31->Add( bSizer32, 1, wxEXPAND|wxALL, 5 ); - - wxBoxSizer* bSizer33; - bSizer33 = new wxBoxSizer( wxVERTICAL ); - - OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); - bSizer33->Add( OKButton, 0, wxALL|wxEXPAND, 5 ); - - CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer33->Add( CancelButton, 0, wxALL|wxEXPAND, 5 ); - - - bSizer31->Add( bSizer33, 0, 0, 5 ); - - - bSizer30->Add( bSizer31, 1, wxEXPAND|wxALL, 5 ); - - - this->SetSizer( bSizer30 ); - this->Layout(); - bSizer30->Fit( this ); - - // Connect Events - OKButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ChangePasswordDialogBase::OnOKButtonClick ), NULL, this ); -} - -ChangePasswordDialogBase::~ChangePasswordDialogBase() -{ - // Disconnect Events - OKButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ChangePasswordDialogBase::OnOKButtonClick ), NULL, this ); - -} - -DeviceSelectionDialogBase::DeviceSelectionDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxSize( -1,-1 ), wxDefaultSize ); - this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); - - wxBoxSizer* bSizer3; - bSizer3 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer4; - bSizer4 = new wxBoxSizer( wxVERTICAL ); - - DeviceListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES|wxSUNKEN_BORDER ); - bSizer4->Add( DeviceListCtrl, 1, wxALL|wxEXPAND, 5 ); - - StdButtons = new wxStdDialogButtonSizer(); - StdButtonsOK = new wxButton( this, wxID_OK ); - StdButtons->AddButton( StdButtonsOK ); - StdButtonsCancel = new wxButton( this, wxID_CANCEL ); - StdButtons->AddButton( StdButtonsCancel ); - StdButtons->Realize(); - - bSizer4->Add( StdButtons, 0, wxEXPAND|wxALL, 5 ); - - - bSizer3->Add( bSizer4, 1, wxEXPAND|wxALL, 5 ); - - - this->SetSizer( bSizer3 ); - this->Layout(); - bSizer3->Fit( this ); - - this->Centre( wxBOTH ); - - // Connect Events - DeviceListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemActivated ), NULL, this ); - DeviceListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemDeselected ), NULL, this ); - DeviceListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemSelected ), NULL, this ); -} - -DeviceSelectionDialogBase::~DeviceSelectionDialogBase() -{ - // Disconnect Events - DeviceListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemActivated ), NULL, this ); - DeviceListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemDeselected ), NULL, this ); - DeviceListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemSelected ), NULL, this ); - -} - -EncryptionTestDialogBase::EncryptionTestDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - - wxBoxSizer* bSizer132; - bSizer132 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer133; - bSizer133 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer134; - bSizer134 = new wxBoxSizer( wxHORIZONTAL ); - - wxStaticText* m_staticText41; - m_staticText41 = new wxStaticText( this, wxID_ANY, _("Encryption algorithm:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText41->Wrap( -1 ); - bSizer134->Add( m_staticText41, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - wxArrayString EncryptionAlgorithmChoiceChoices; - EncryptionAlgorithmChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, EncryptionAlgorithmChoiceChoices, 0 ); - EncryptionAlgorithmChoice->SetSelection( 0 ); - bSizer134->Add( EncryptionAlgorithmChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - XtsModeCheckBox = new wxCheckBox( this, wxID_ANY, _("XTS mode"), wxDefaultPosition, wxDefaultSize, 0 ); - XtsModeCheckBox->SetValue(true); - bSizer134->Add( XtsModeCheckBox, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - - bSizer133->Add( bSizer134, 0, wxALIGN_CENTER_HORIZONTAL, 5 ); - - wxStaticBoxSizer* sbSizer38; - sbSizer38 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Key (hexadecimal)") ), wxVERTICAL ); - - KeyTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - KeyTextCtrl->SetMaxLength( 0 ); - KeyTextCtrl->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier") ) ); - - sbSizer38->Add( KeyTextCtrl, 1, wxALL|wxEXPAND, 5 ); - - wxBoxSizer* bSizer135; - bSizer135 = new wxBoxSizer( wxHORIZONTAL ); - - wxStaticText* m_staticText43; - m_staticText43 = new wxStaticText( this, wxID_ANY, _("Key size:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText43->Wrap( -1 ); - bSizer135->Add( m_staticText43, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - - KeySizeStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - KeySizeStaticText->Wrap( -1 ); - bSizer135->Add( KeySizeStaticText, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT, 5 ); - - - sbSizer38->Add( bSizer135, 0, wxEXPAND, 5 ); - - - bSizer133->Add( sbSizer38, 0, wxEXPAND|wxALL, 5 ); - - wxStaticBoxSizer* sbSizer39; - sbSizer39 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("XTS mode") ), wxVERTICAL ); - - wxStaticText* m_staticText45; - m_staticText45 = new wxStaticText( this, wxID_ANY, _("Secondary key (hexadecimal)"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText45->Wrap( -1 ); - sbSizer39->Add( m_staticText45, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); - - SecondaryKeyTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - SecondaryKeyTextCtrl->SetMaxLength( 0 ); - SecondaryKeyTextCtrl->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier") ) ); - - sbSizer39->Add( SecondaryKeyTextCtrl, 0, wxEXPAND|wxALL, 5 ); - - wxStaticText* m_staticText46; - m_staticText46 = new wxStaticText( this, wxID_ANY, _("Data unit number (64-bit, data unit size is 512 bytes)"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText46->Wrap( -1 ); - sbSizer39->Add( m_staticText46, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); - - DataUnitNumberTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - DataUnitNumberTextCtrl->SetMaxLength( 0 ); - sbSizer39->Add( DataUnitNumberTextCtrl, 0, wxALL, 5 ); - - wxStaticText* m_staticText47; - m_staticText47 = new wxStaticText( this, wxID_ANY, _("Block number:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText47->Wrap( -1 ); - sbSizer39->Add( m_staticText47, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); - - BlockNumberTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - BlockNumberTextCtrl->SetMaxLength( 0 ); - sbSizer39->Add( BlockNumberTextCtrl, 0, wxALL, 5 ); - - - bSizer133->Add( sbSizer39, 1, wxEXPAND|wxALL, 5 ); - - wxStaticBoxSizer* sbSizer40; - sbSizer40 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Plaintext (hexadecimal)") ), wxVERTICAL ); - - PlainTextTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - PlainTextTextCtrl->SetMaxLength( 0 ); - PlainTextTextCtrl->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier") ) ); - - sbSizer40->Add( PlainTextTextCtrl, 0, wxALL|wxEXPAND, 5 ); - - - bSizer133->Add( sbSizer40, 0, wxEXPAND|wxALL, 5 ); - - wxStaticBoxSizer* sbSizer41; - sbSizer41 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Ciphertext (hexadecimal)") ), wxVERTICAL ); - - CipherTextTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - CipherTextTextCtrl->SetMaxLength( 0 ); - CipherTextTextCtrl->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier") ) ); - - sbSizer41->Add( CipherTextTextCtrl, 0, wxALL|wxEXPAND, 5 ); - - - bSizer133->Add( sbSizer41, 0, wxEXPAND|wxALL, 5 ); - - wxBoxSizer* bSizer136; - bSizer136 = new wxBoxSizer( wxHORIZONTAL ); - - EncryptButton = new wxButton( this, wxID_ANY, _("&Encrypt"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer136->Add( EncryptButton, 0, wxALL, 5 ); - - DecryptButton = new wxButton( this, wxID_ANY, _("&Decrypt"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer136->Add( DecryptButton, 0, wxALL, 5 ); - - AutoTestAllButton = new wxButton( this, wxID_ANY, _("&Auto-Test All"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer136->Add( AutoTestAllButton, 0, wxALL, 5 ); - - ResetButton = new wxButton( this, wxID_ANY, _("&Reset"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer136->Add( ResetButton, 0, wxALL, 5 ); - - CloseButton = new wxButton( this, wxID_CANCEL, _("Close"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer136->Add( CloseButton, 0, wxALL, 5 ); - - - bSizer133->Add( bSizer136, 0, wxEXPAND, 5 ); - - - bSizer132->Add( bSizer133, 1, wxEXPAND|wxALL, 5 ); - - - this->SetSizer( bSizer132 ); - this->Layout(); - bSizer132->Fit( this ); - - // Connect Events - EncryptionAlgorithmChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( EncryptionTestDialogBase::OnEncryptionAlgorithmSelected ), NULL, this ); - XtsModeCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnXtsModeCheckBoxClick ), NULL, this ); - EncryptButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnEncryptButtonClick ), NULL, this ); - DecryptButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnDecryptButtonClick ), NULL, this ); - AutoTestAllButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnAutoTestAllButtonClick ), NULL, this ); - ResetButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnResetButtonClick ), NULL, this ); -} - -EncryptionTestDialogBase::~EncryptionTestDialogBase() -{ - // Disconnect Events - EncryptionAlgorithmChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( EncryptionTestDialogBase::OnEncryptionAlgorithmSelected ), NULL, this ); - XtsModeCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnXtsModeCheckBoxClick ), NULL, this ); - EncryptButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnEncryptButtonClick ), NULL, this ); - DecryptButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnDecryptButtonClick ), NULL, this ); - AutoTestAllButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnAutoTestAllButtonClick ), NULL, this ); - ResetButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnResetButtonClick ), NULL, this ); - -} - -FavoriteVolumesDialogBase::FavoriteVolumesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - - wxBoxSizer* bSizer57; - bSizer57 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer60; - bSizer60 = new wxBoxSizer( wxHORIZONTAL ); - - wxBoxSizer* bSizer58; - bSizer58 = new wxBoxSizer( wxVERTICAL ); - - FavoritesListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES|wxSUNKEN_BORDER ); - bSizer58->Add( FavoritesListCtrl, 1, wxALL|wxEXPAND, 5 ); - - wxGridSizer* gSizer5; - gSizer5 = new wxGridSizer( 1, 4, 0, 0 ); - - MoveUpButton = new wxButton( this, wxID_ANY, _("Move &Up"), wxDefaultPosition, wxDefaultSize, 0 ); - gSizer5->Add( MoveUpButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 ); - - MoveDownButton = new wxButton( this, wxID_ANY, _("Move &Down"), wxDefaultPosition, wxDefaultSize, 0 ); - gSizer5->Add( MoveDownButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 ); - - RemoveButton = new wxButton( this, wxID_ANY, _("&Remove"), wxDefaultPosition, wxDefaultSize, 0 ); - gSizer5->Add( RemoveButton, 0, wxALIGN_RIGHT|wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - RemoveAllButton = new wxButton( this, wxID_ANY, _("Remove &All"), wxDefaultPosition, wxDefaultSize, 0 ); - gSizer5->Add( RemoveAllButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - - bSizer58->Add( gSizer5, 0, wxEXPAND|wxRIGHT|wxLEFT, 5 ); - - wxFlexGridSizer* fgSizer4; - fgSizer4 = new wxFlexGridSizer( 1, 5, 0, 0 ); - fgSizer4->AddGrowableCol( 2 ); - fgSizer4->SetFlexibleDirection( wxBOTH ); - fgSizer4->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - - - fgSizer4->Add( 0, 0, 1, wxEXPAND, 5 ); - - - bSizer58->Add( fgSizer4, 0, wxEXPAND, 5 ); - - - bSizer60->Add( bSizer58, 1, wxEXPAND, 5 ); - - wxBoxSizer* bSizer59; - bSizer59 = new wxBoxSizer( wxVERTICAL ); - - OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); - bSizer59->Add( OKButton, 0, wxALL, 5 ); - - CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer59->Add( CancelButton, 0, wxALL, 5 ); - - - bSizer60->Add( bSizer59, 0, wxEXPAND, 5 ); - - - bSizer57->Add( bSizer60, 1, wxEXPAND|wxALL, 5 ); - - - this->SetSizer( bSizer57 ); - this->Layout(); - bSizer57->Fit( this ); - - // Connect Events - FavoritesListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( FavoriteVolumesDialogBase::OnListItemDeselected ), NULL, this ); - FavoritesListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( FavoriteVolumesDialogBase::OnListItemSelected ), NULL, this ); - MoveUpButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnMoveUpButtonClick ), NULL, this ); - MoveDownButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnMoveDownButtonClick ), NULL, this ); - RemoveButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnRemoveButtonClick ), NULL, this ); - RemoveAllButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnRemoveAllButtonClick ), NULL, this ); - OKButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnOKButtonClick ), NULL, this ); -} - -FavoriteVolumesDialogBase::~FavoriteVolumesDialogBase() -{ - // Disconnect Events - FavoritesListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( FavoriteVolumesDialogBase::OnListItemDeselected ), NULL, this ); - FavoritesListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( FavoriteVolumesDialogBase::OnListItemSelected ), NULL, this ); - MoveUpButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnMoveUpButtonClick ), NULL, this ); - MoveDownButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnMoveDownButtonClick ), NULL, this ); - RemoveButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnRemoveButtonClick ), NULL, this ); - RemoveAllButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnRemoveAllButtonClick ), NULL, this ); - OKButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnOKButtonClick ), NULL, this ); - -} - -KeyfilesDialogBase::KeyfilesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); - - wxBoxSizer* bSizer26; - bSizer26 = new wxBoxSizer( wxVERTICAL ); - - UpperSizer = new wxBoxSizer( wxHORIZONTAL ); - - PanelSizer = new wxBoxSizer( wxVERTICAL ); - - - UpperSizer->Add( PanelSizer, 1, wxEXPAND, 5 ); - - wxBoxSizer* bSizer22; - bSizer22 = new wxBoxSizer( wxVERTICAL ); - - OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); - bSizer22->Add( OKButton, 0, wxALL|wxEXPAND, 5 ); - - CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer22->Add( CancelButton, 0, wxALL|wxEXPAND, 5 ); - - WarningStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - WarningStaticText->Wrap( -1 ); - bSizer22->Add( WarningStaticText, 1, wxALL|wxEXPAND, 5 ); - - - UpperSizer->Add( bSizer22, 0, wxEXPAND, 5 ); - - - bSizer26->Add( UpperSizer, 1, wxTOP|wxRIGHT|wxLEFT, 5 ); - - wxBoxSizer* bSizer23; - bSizer23 = new wxBoxSizer( wxVERTICAL ); - - KeyfilesNoteSizer = new wxBoxSizer( wxVERTICAL ); - - wxStaticLine* m_staticline1; - m_staticline1 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); - KeyfilesNoteSizer->Add( m_staticline1, 0, wxEXPAND | wxALL, 5 ); - - KeyfilesNoteStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - KeyfilesNoteStaticText->Wrap( -1 ); - KeyfilesNoteSizer->Add( KeyfilesNoteStaticText, 0, wxALL|wxEXPAND, 5 ); - - wxStaticLine* m_staticline2; - m_staticline2 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); - KeyfilesNoteSizer->Add( m_staticline2, 0, wxEXPAND | wxALL, 5 ); - - - bSizer23->Add( KeyfilesNoteSizer, 1, wxEXPAND, 5 ); - - wxFlexGridSizer* fgSizer2; - fgSizer2 = new wxFlexGridSizer( 1, 2, 0, 0 ); - fgSizer2->AddGrowableCol( 0 ); - fgSizer2->SetFlexibleDirection( wxBOTH ); - fgSizer2->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - - KeyfilesHyperlink = new wxHyperlinkCtrl( this, wxID_ANY, _("More information on keyfiles"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); - - KeyfilesHyperlink->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - KeyfilesHyperlink->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - KeyfilesHyperlink->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - fgSizer2->Add( KeyfilesHyperlink, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - CreateKeyfileButtton = new wxButton( this, wxID_ANY, _("&Generate Random Keyfile..."), wxDefaultPosition, wxDefaultSize, 0 ); - fgSizer2->Add( CreateKeyfileButtton, 0, wxALL, 5 ); - - - bSizer23->Add( fgSizer2, 0, wxEXPAND, 5 ); - - - bSizer26->Add( bSizer23, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - - - this->SetSizer( bSizer26 ); - this->Layout(); - bSizer26->Fit( this ); - - // Connect Events - KeyfilesHyperlink->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( KeyfilesDialogBase::OnKeyfilesHyperlinkClick ), NULL, this ); - CreateKeyfileButtton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesDialogBase::OnCreateKeyfileButttonClick ), NULL, this ); -} - -KeyfilesDialogBase::~KeyfilesDialogBase() -{ - // Disconnect Events - KeyfilesHyperlink->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( KeyfilesDialogBase::OnKeyfilesHyperlinkClick ), NULL, this ); - CreateKeyfileButtton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesDialogBase::OnCreateKeyfileButttonClick ), NULL, this ); - -} - -KeyfileGeneratorDialogBase::KeyfileGeneratorDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - - MainSizer = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer144; - bSizer144 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer145; - bSizer145 = new wxBoxSizer( wxHORIZONTAL ); - - - bSizer145->Add( 0, 0, 1, wxEXPAND, 5 ); - - wxStaticText* m_staticText49; - m_staticText49 = new wxStaticText( this, wxID_ANY, _("Mixing PRF:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText49->Wrap( -1 ); - bSizer145->Add( m_staticText49, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - wxArrayString HashChoiceChoices; - HashChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, HashChoiceChoices, 0 ); - HashChoice->SetSelection( 0 ); - bSizer145->Add( HashChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - - bSizer145->Add( 0, 0, 1, wxEXPAND, 5 ); - - - bSizer144->Add( bSizer145, 0, wxEXPAND, 5 ); - - wxStaticBoxSizer* sbSizer43; - sbSizer43 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - wxBoxSizer* bSizer147; - bSizer147 = new wxBoxSizer( wxHORIZONTAL ); - - wxStaticText* m_staticText52; - m_staticText52 = new wxStaticText( this, wxID_ANY, _("Random Pool:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText52->Wrap( -1 ); - bSizer147->Add( m_staticText52, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); - - RandomPoolStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - RandomPoolStaticText->Wrap( -1 ); - RandomPoolStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); - - bSizer147->Add( RandomPoolStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - ShowRandomPoolCheckBox = new wxCheckBox( this, wxID_ANY, _("Show"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer147->Add( ShowRandomPoolCheckBox, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - - sbSizer43->Add( bSizer147, 0, wxEXPAND|wxTOP, 5 ); - - - sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); - - wxStaticBoxSizer* sbSizer45; - sbSizer45 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Randomness Collected From Mouse Movements") ), wxVERTICAL ); - - CollectedEntropy = new wxGauge( this, wxID_ANY, 2560, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); - CollectedEntropy->SetValue( 0 ); - sbSizer45->Add( CollectedEntropy, 1, wxALL|wxEXPAND, 5 ); - - - sbSizer43->Add( sbSizer45, 0, wxBOTTOM|wxEXPAND|wxTOP, 5 ); - - - sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); - - MouseStaticText = new wxStaticText( this, wxID_ANY, _("IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the keyfile."), wxDefaultPosition, wxDefaultSize, 0 ); - MouseStaticText->Wrap( -1 ); - sbSizer43->Add( MouseStaticText, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 ); - - - sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); - - - bSizer144->Add( sbSizer43, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - - wxBoxSizer* bSizer162; - bSizer162 = new wxBoxSizer( wxVERTICAL ); - - wxFlexGridSizer* fgSizer8; - fgSizer8 = new wxFlexGridSizer( 3, 3, 0, 0 ); - fgSizer8->AddGrowableCol( 2 ); - fgSizer8->SetFlexibleDirection( wxBOTH ); - fgSizer8->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - - m_staticText60 = new wxStaticText( this, wxID_ANY, _("Number of keyfiles:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText60->Wrap( -1 ); - fgSizer8->Add( m_staticText60, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - NumberOfKeyfiles = new wxSpinCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 1, 9999999, 1 ); - fgSizer8->Add( NumberOfKeyfiles, 0, wxALL, 5 ); - - m_panel18 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - fgSizer8->Add( m_panel18, 1, wxEXPAND | wxALL, 5 ); - - m_staticText63 = new wxStaticText( this, wxID_ANY, _("Keyfiles size (in Bytes):"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText63->Wrap( -1 ); - fgSizer8->Add( m_staticText63, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - KeyfilesSize = new wxSpinCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 64, 1048576, 64 ); - fgSizer8->Add( KeyfilesSize, 0, wxALL, 5 ); - - RandomSizeCheckBox = new wxCheckBox( this, wxID_ANY, _("Random size (64 <-> 1048576)"), wxDefaultPosition, wxDefaultSize, 0 ); - fgSizer8->Add( RandomSizeCheckBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - m_staticText65 = new wxStaticText( this, wxID_ANY, _("Keyfiles base name:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText65->Wrap( -1 ); - fgSizer8->Add( m_staticText65, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - KeyfilesBaseName = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - fgSizer8->Add( KeyfilesBaseName, 0, wxALL, 5 ); - - m_panel19 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - fgSizer8->Add( m_panel19, 1, wxEXPAND | wxALL, 5 ); - - - bSizer162->Add( fgSizer8, 1, wxEXPAND, 5 ); - - - bSizer144->Add( bSizer162, 0, wxALL|wxEXPAND, 5 ); - - wxBoxSizer* bSizer146; - bSizer146 = new wxBoxSizer( wxHORIZONTAL ); - - GenerateButton = new wxButton( this, wxID_ANY, _("Generate and Save Keyfile..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer146->Add( GenerateButton, 0, wxALL, 5 ); - - - bSizer146->Add( 0, 0, 1, wxEXPAND, 5 ); - - wxButton* m_button61; - m_button61 = new wxButton( this, wxID_CANCEL, _("Close"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer146->Add( m_button61, 0, wxALL, 5 ); - - - bSizer144->Add( bSizer146, 0, wxEXPAND, 5 ); - - - MainSizer->Add( bSizer144, 1, wxEXPAND|wxALL, 5 ); - - - this->SetSizer( MainSizer ); - this->Layout(); - MainSizer->Fit( this ); - - // Connect Events - this->Connect( wxEVT_MOTION, wxMouseEventHandler( KeyfileGeneratorDialogBase::OnMouseMotion ) ); - HashChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnHashSelected ), NULL, this ); - ShowRandomPoolCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnShowRandomPoolCheckBoxClicked ), NULL, this ); - RandomSizeCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnRandomSizeCheckBoxClicked ), NULL, this ); - GenerateButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnGenerateButtonClick ), NULL, this ); -} - -KeyfileGeneratorDialogBase::~KeyfileGeneratorDialogBase() -{ - // Disconnect Events - this->Disconnect( wxEVT_MOTION, wxMouseEventHandler( KeyfileGeneratorDialogBase::OnMouseMotion ) ); - HashChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnHashSelected ), NULL, this ); - ShowRandomPoolCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnShowRandomPoolCheckBoxClicked ), NULL, this ); - RandomSizeCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnRandomSizeCheckBoxClicked ), NULL, this ); - GenerateButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnGenerateButtonClick ), NULL, this ); - -} - -LegalNoticesDialogBase::LegalNoticesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - - wxBoxSizer* bSizer114; - bSizer114 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer115; - bSizer115 = new wxBoxSizer( wxVERTICAL ); - - LegalNoticesTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY ); - bSizer115->Add( LegalNoticesTextCtrl, 1, wxALL|wxEXPAND, 5 ); - - wxButton* OKButton; - OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); - bSizer115->Add( OKButton, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 ); - - - bSizer114->Add( bSizer115, 1, wxEXPAND|wxALL, 5 ); - - - this->SetSizer( bSizer114 ); - this->Layout(); - bSizer114->Fit( this ); -} - -LegalNoticesDialogBase::~LegalNoticesDialogBase() -{ -} - -MountOptionsDialogBase::MountOptionsDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); - - MainSizer = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer19; - bSizer19 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer14; - bSizer14 = new wxBoxSizer( wxHORIZONTAL ); - - PasswordSizer = new wxBoxSizer( wxVERTICAL ); - - - bSizer14->Add( PasswordSizer, 1, wxEXPAND, 5 ); - - wxBoxSizer* bSizer9; - bSizer9 = new wxBoxSizer( wxVERTICAL ); - - OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); - bSizer9->Add( OKButton, 0, wxALL|wxEXPAND, 5 ); - - CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer9->Add( CancelButton, 0, wxALL|wxEXPAND, 5 ); - - - bSizer9->Add( 0, 0, 1, wxTOP|wxEXPAND, 5 ); - - OptionsButton = new wxButton( this, wxID_ANY, _("Op&tions"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer9->Add( OptionsButton, 0, wxALL|wxEXPAND, 5 ); - - - bSizer14->Add( bSizer9, 0, wxEXPAND, 5 ); - - - bSizer19->Add( bSizer14, 0, wxEXPAND|wxALL, 5 ); - - wxBoxSizer* bSizer6; - bSizer6 = new wxBoxSizer( wxVERTICAL ); - - OptionsPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - OptionsSizer = new wxStaticBoxSizer( new wxStaticBox( OptionsPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - - OptionsSizer->Add( 0, 0, 0, wxTOP, 5 ); - - ReadOnlyCheckBox = new wxCheckBox( OptionsPanel, wxID_ANY, _("Mount volume as &read-only"), wxDefaultPosition, wxDefaultSize, 0 ); - OptionsSizer->Add( ReadOnlyCheckBox, 0, wxALL, 5 ); - - RemovableCheckBox = new wxCheckBox( OptionsPanel, wxID_ANY, _("Mount volume as removable &medium"), wxDefaultPosition, wxDefaultSize, 0 ); - OptionsSizer->Add( RemovableCheckBox, 0, wxALL, 5 ); - - PartitionInSystemEncryptionScopeCheckBox = new wxCheckBox( OptionsPanel, wxID_ANY, _("Mount partition &using system encryption (preboot authentication)"), wxDefaultPosition, wxDefaultSize, 0 ); - OptionsSizer->Add( PartitionInSystemEncryptionScopeCheckBox, 0, wxALL, 5 ); - - ProtectionSizer = new wxStaticBoxSizer( new wxStaticBox( OptionsPanel, wxID_ANY, _("Hidden Volume Protection") ), wxVERTICAL ); - - ProtectionCheckBox = new wxCheckBox( OptionsPanel, wxID_ANY, _("&Protect hidden volume when mounting outer volume"), wxDefaultPosition, wxDefaultSize, 0 ); - ProtectionSizer->Add( ProtectionCheckBox, 0, wxALL, 5 ); - - ProtectionPasswordSizer = new wxBoxSizer( wxVERTICAL ); - - - ProtectionSizer->Add( ProtectionPasswordSizer, 1, wxEXPAND|wxLEFT, 5 ); - - ProtectionHyperlinkCtrl = new wxHyperlinkCtrl( OptionsPanel, wxID_ANY, _("What is hidden volume protection?"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); - - ProtectionHyperlinkCtrl->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - ProtectionHyperlinkCtrl->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - ProtectionHyperlinkCtrl->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - ProtectionSizer->Add( ProtectionHyperlinkCtrl, 0, wxALL, 5 ); - - - OptionsSizer->Add( ProtectionSizer, 1, wxEXPAND|wxALL, 5 ); - - FilesystemSizer = new wxBoxSizer( wxVERTICAL ); - - m_panel8 = new wxPanel( OptionsPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - wxStaticBoxSizer* sbSizer28; - sbSizer28 = new wxStaticBoxSizer( new wxStaticBox( m_panel8, wxID_ANY, _("Filesystem") ), wxVERTICAL ); - - wxBoxSizer* bSizer54; - bSizer54 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer55; - bSizer55 = new wxBoxSizer( wxVERTICAL ); - - NoFilesystemCheckBox = new wxCheckBox( m_panel8, wxID_ANY, _("Do ¬ mount"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer55->Add( NoFilesystemCheckBox, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); - - - bSizer54->Add( bSizer55, 1, wxEXPAND, 5 ); - - FilesystemOptionsSizer = new wxGridBagSizer( 0, 0 ); - FilesystemOptionsSizer->SetFlexibleDirection( wxBOTH ); - FilesystemOptionsSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - FilesystemOptionsSizer->SetEmptyCellSize( wxSize( 0,0 ) ); - - FilesystemSpacer = new wxBoxSizer( wxVERTICAL ); - - - FilesystemOptionsSizer->Add( FilesystemSpacer, wxGBPosition( 0, 0 ), wxGBSpan( 1, 1 ), wxEXPAND|wxTOP, 5 ); - - MountPointTextCtrlStaticText = new wxStaticText( m_panel8, wxID_ANY, _("Mount at directory:"), wxDefaultPosition, wxDefaultSize, 0 ); - MountPointTextCtrlStaticText->Wrap( -1 ); - FilesystemOptionsSizer->Add( MountPointTextCtrlStaticText, wxGBPosition( 1, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - MountPointTextCtrl = new wxTextCtrl( m_panel8, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - MountPointTextCtrl->SetMaxLength( 0 ); - FilesystemOptionsSizer->Add( MountPointTextCtrl, wxGBPosition( 1, 1 ), wxGBSpan( 1, 1 ), wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); - - MountPointButton = new wxButton( m_panel8, wxID_ANY, _("Se&lect..."), wxDefaultPosition, wxDefaultSize, 0 ); - FilesystemOptionsSizer->Add( MountPointButton, wxGBPosition( 1, 2 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxRIGHT|wxLEFT, 5 ); - - FilesystemOptionsStaticText = new wxStaticText( m_panel8, wxID_ANY, _("Mount options:"), wxDefaultPosition, wxDefaultSize, 0 ); - FilesystemOptionsStaticText->Wrap( -1 ); - FilesystemOptionsSizer->Add( FilesystemOptionsStaticText, wxGBPosition( 2, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxLEFT, 5 ); - - FilesystemOptionsTextCtrl = new wxTextCtrl( m_panel8, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - FilesystemOptionsTextCtrl->SetMaxLength( 0 ); - FilesystemOptionsSizer->Add( FilesystemOptionsTextCtrl, wxGBPosition( 2, 1 ), wxGBSpan( 1, 2 ), wxALIGN_CENTER_VERTICAL|wxEXPAND|wxTOP|wxRIGHT|wxLEFT, 5 ); - - - FilesystemOptionsSizer->AddGrowableCol( 1 ); - - bSizer54->Add( FilesystemOptionsSizer, 0, wxEXPAND, 5 ); - - - sbSizer28->Add( bSizer54, 0, wxEXPAND|wxBOTTOM, 5 ); - - - m_panel8->SetSizer( sbSizer28 ); - m_panel8->Layout(); - sbSizer28->Fit( m_panel8 ); - FilesystemSizer->Add( m_panel8, 0, wxEXPAND | wxALL, 5 ); - - - OptionsSizer->Add( FilesystemSizer, 0, wxEXPAND, 5 ); - - - OptionsPanel->SetSizer( OptionsSizer ); - OptionsPanel->Layout(); - OptionsSizer->Fit( OptionsPanel ); - bSizer6->Add( OptionsPanel, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - - - bSizer19->Add( bSizer6, 0, wxEXPAND, 5 ); - - - MainSizer->Add( bSizer19, 1, wxEXPAND, 5 ); - - - this->SetSizer( MainSizer ); - this->Layout(); - MainSizer->Fit( this ); - - this->Centre( wxBOTH ); - - // Connect Events - this->Connect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( MountOptionsDialogBase::OnInitDialog ) ); - OKButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnOKButtonClick ), NULL, this ); - OptionsButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnOptionsButtonClick ), NULL, this ); - ReadOnlyCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnReadOnlyCheckBoxClick ), NULL, this ); - ProtectionCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnProtectionCheckBoxClick ), NULL, this ); - ProtectionHyperlinkCtrl->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( MountOptionsDialogBase::OnProtectionHyperlinkClick ), NULL, this ); - NoFilesystemCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnNoFilesystemCheckBoxClick ), NULL, this ); - MountPointButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnMountPointButtonClick ), NULL, this ); -} - -MountOptionsDialogBase::~MountOptionsDialogBase() -{ - // Disconnect Events - this->Disconnect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( MountOptionsDialogBase::OnInitDialog ) ); - OKButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnOKButtonClick ), NULL, this ); - OptionsButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnOptionsButtonClick ), NULL, this ); - ReadOnlyCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnReadOnlyCheckBoxClick ), NULL, this ); - ProtectionCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnProtectionCheckBoxClick ), NULL, this ); - ProtectionHyperlinkCtrl->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( MountOptionsDialogBase::OnProtectionHyperlinkClick ), NULL, this ); - NoFilesystemCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnNoFilesystemCheckBoxClick ), NULL, this ); - MountPointButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnMountPointButtonClick ), NULL, this ); - -} - -NewSecurityTokenKeyfileDialogBase::NewSecurityTokenKeyfileDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - - wxBoxSizer* bSizer143; - bSizer143 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer144; - bSizer144 = new wxBoxSizer( wxVERTICAL ); - - wxStaticBoxSizer* sbSizer42; - sbSizer42 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - wxFlexGridSizer* fgSizer7; - fgSizer7 = new wxFlexGridSizer( 2, 2, 0, 0 ); - fgSizer7->SetFlexibleDirection( wxBOTH ); - fgSizer7->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - - wxStaticText* m_staticText47; - m_staticText47 = new wxStaticText( this, wxID_ANY, _("Security token:"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT ); - m_staticText47->Wrap( -1 ); - fgSizer7->Add( m_staticText47, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - wxArrayString SecurityTokenChoiceChoices; - SecurityTokenChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, SecurityTokenChoiceChoices, 0 ); - SecurityTokenChoice->SetSelection( 0 ); - fgSizer7->Add( SecurityTokenChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); - - wxStaticText* m_staticText48; - m_staticText48 = new wxStaticText( this, wxID_ANY, _("Keyfile name:"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT ); - m_staticText48->Wrap( -1 ); - fgSizer7->Add( m_staticText48, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - KeyfileNameTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - KeyfileNameTextCtrl->SetMaxLength( 0 ); - fgSizer7->Add( KeyfileNameTextCtrl, 0, wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL, 5 ); - - - sbSizer42->Add( fgSizer7, 1, wxEXPAND|wxTOP, 5 ); - - - bSizer144->Add( sbSizer42, 1, wxEXPAND|wxALL, 5 ); - - StdButtons = new wxStdDialogButtonSizer(); - StdButtonsOK = new wxButton( this, wxID_OK ); - StdButtons->AddButton( StdButtonsOK ); - StdButtonsCancel = new wxButton( this, wxID_CANCEL ); - StdButtons->AddButton( StdButtonsCancel ); - StdButtons->Realize(); - - bSizer144->Add( StdButtons, 0, wxALIGN_RIGHT|wxALL, 5 ); - - - bSizer143->Add( bSizer144, 1, wxEXPAND|wxALL, 5 ); - - - this->SetSizer( bSizer143 ); - this->Layout(); - bSizer143->Fit( this ); - - // Connect Events - KeyfileNameTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( NewSecurityTokenKeyfileDialogBase::OnKeyfileNameChanged ), NULL, this ); -} - -NewSecurityTokenKeyfileDialogBase::~NewSecurityTokenKeyfileDialogBase() -{ - // Disconnect Events - KeyfileNameTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( NewSecurityTokenKeyfileDialogBase::OnKeyfileNameChanged ), NULL, this ); - -} - -PreferencesDialogBase::PreferencesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); - - wxBoxSizer* bSizer32; - bSizer32 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer41; - bSizer41 = new wxBoxSizer( wxVERTICAL ); - - PreferencesNotebook = new wxNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 ); - SecurityPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - wxBoxSizer* bSizer44; - bSizer44 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer33; - bSizer33 = new wxBoxSizer( wxVERTICAL ); - - AutoDismountSizer = new wxStaticBoxSizer( new wxStaticBox( SecurityPage, wxID_ANY, _("Auto-Dismount") ), wxVERTICAL ); - - wxStaticBoxSizer* sbSizer13; - sbSizer13 = new wxStaticBoxSizer( new wxStaticBox( SecurityPage, wxID_ANY, _("Dismount All Volumes When") ), wxVERTICAL ); - - DismountOnLogOffCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("User logs off"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer13->Add( DismountOnLogOffCheckBox, 0, wxALL, 5 ); - - DismountOnScreenSaverCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Screen saver is launched"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer13->Add( DismountOnScreenSaverCheckBox, 0, wxALL, 5 ); - - DismountOnPowerSavingCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("System is entering power saving mode"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer13->Add( DismountOnPowerSavingCheckBox, 0, wxALL, 5 ); - - - AutoDismountSizer->Add( sbSizer13, 0, wxEXPAND|wxALL, 5 ); - - wxBoxSizer* bSizer34; - bSizer34 = new wxBoxSizer( wxHORIZONTAL ); - - DismountOnInactivityCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Auto-dismount volume after no data has been read/written to it for"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer34->Add( DismountOnInactivityCheckBox, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); - - DismountOnInactivitySpinCtrl = new wxSpinCtrl( SecurityPage, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize( -1,-1 ), wxSP_ARROW_KEYS, 1, 9999, 1 ); - DismountOnInactivitySpinCtrl->SetMinSize( wxSize( 60,-1 ) ); - - bSizer34->Add( DismountOnInactivitySpinCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - wxStaticText* m_staticText5; - m_staticText5 = new wxStaticText( SecurityPage, wxID_ANY, _("minutes"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText5->Wrap( -1 ); - bSizer34->Add( m_staticText5, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT, 5 ); - - - AutoDismountSizer->Add( bSizer34, 0, wxEXPAND, 5 ); - - ForceAutoDismountCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Force auto-dismount even if volume contains open files or directories"), wxDefaultPosition, wxDefaultSize, 0 ); - AutoDismountSizer->Add( ForceAutoDismountCheckBox, 0, wxALL, 5 ); - - - bSizer33->Add( AutoDismountSizer, 0, wxEXPAND|wxALL, 5 ); - - FilesystemSecuritySizer = new wxStaticBoxSizer( new wxStaticBox( SecurityPage, wxID_ANY, _("Filesystem") ), wxVERTICAL ); - - PreserveTimestampsCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Preserve modification timestamp of file containers"), wxDefaultPosition, wxDefaultSize, 0 ); - FilesystemSecuritySizer->Add( PreserveTimestampsCheckBox, 0, wxALL, 5 ); - - - bSizer33->Add( FilesystemSecuritySizer, 0, wxEXPAND|wxALL, 5 ); - - wxStaticBoxSizer* sbSizer14; - sbSizer14 = new wxStaticBoxSizer( new wxStaticBox( SecurityPage, wxID_ANY, _("Password Cache") ), wxVERTICAL ); - - WipeCacheOnCloseCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Wipe after VeraCrypt window has been closed"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer14->Add( WipeCacheOnCloseCheckBox, 0, wxALL, 5 ); - - WipeCacheOnAutoDismountCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Wipe after volume has been auto-dismounted"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer14->Add( WipeCacheOnAutoDismountCheckBox, 0, wxALL, 5 ); - - - bSizer33->Add( sbSizer14, 0, wxEXPAND|wxALL, 5 ); - - - bSizer44->Add( bSizer33, 1, wxEXPAND|wxALL, 5 ); - - - SecurityPage->SetSizer( bSizer44 ); - SecurityPage->Layout(); - bSizer44->Fit( SecurityPage ); - PreferencesNotebook->AddPage( SecurityPage, _("Security"), true ); - DefaultMountOptionsPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - wxBoxSizer* bSizer46; - bSizer46 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer35; - bSizer35 = new wxBoxSizer( wxVERTICAL ); - - wxStaticBoxSizer* sbSizer15; - sbSizer15 = new wxStaticBoxSizer( new wxStaticBox( DefaultMountOptionsPage, wxID_ANY, _("Default Mount Options") ), wxVERTICAL ); - - MountReadOnlyCheckBox = new wxCheckBox( DefaultMountOptionsPage, wxID_ANY, _("Mount volumes as read-only"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer15->Add( MountReadOnlyCheckBox, 0, wxALL, 5 ); - - MountRemovableCheckBox = new wxCheckBox( DefaultMountOptionsPage, wxID_ANY, _("Mount volumes as removable media"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer15->Add( MountRemovableCheckBox, 0, wxALL, 5 ); - - CachePasswordsCheckBox = new wxCheckBox( DefaultMountOptionsPage, wxID_ANY, _("Cache passwords in memory"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer15->Add( CachePasswordsCheckBox, 0, wxALL, 5 ); - - TrueCryptModeCheckBox = new wxCheckBox( DefaultMountOptionsPage, wxID_ANY, _("TrueCrypt Mode"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer15->Add( TrueCryptModeCheckBox, 0, wxALL, 5 ); - - wxBoxSizer* bSizer163; - bSizer163 = new wxBoxSizer( wxHORIZONTAL ); - - Pkcs5PrfStaticText = new wxStaticText( DefaultMountOptionsPage, wxID_ANY, _("PKCS5-PRF:"), wxDefaultPosition, wxDefaultSize, 0 ); - Pkcs5PrfStaticText->Wrap( -1 ); - bSizer163->Add( Pkcs5PrfStaticText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - wxArrayString Pkcs5PrfChoiceChoices; - Pkcs5PrfChoice = new wxChoice( DefaultMountOptionsPage, wxID_ANY, wxDefaultPosition, wxDefaultSize, Pkcs5PrfChoiceChoices, 0 ); - Pkcs5PrfChoice->SetSelection( 0 ); - bSizer163->Add( Pkcs5PrfChoice, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - - sbSizer15->Add( bSizer163, 0, wxEXPAND, 5 ); - - - bSizer35->Add( sbSizer15, 0, wxEXPAND|wxALL, 5 ); - - FilesystemSizer = new wxStaticBoxSizer( new wxStaticBox( DefaultMountOptionsPage, wxID_ANY, _("Filesystem") ), wxVERTICAL ); - - wxFlexGridSizer* fgSizer3; - fgSizer3 = new wxFlexGridSizer( 1, 2, 0, 0 ); - fgSizer3->AddGrowableCol( 1 ); - fgSizer3->SetFlexibleDirection( wxBOTH ); - fgSizer3->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - - wxStaticText* m_staticText6; - m_staticText6 = new wxStaticText( DefaultMountOptionsPage, wxID_ANY, _("Mount options:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText6->Wrap( -1 ); - fgSizer3->Add( m_staticText6, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); - - FilesystemOptionsTextCtrl = new wxTextCtrl( DefaultMountOptionsPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - FilesystemOptionsTextCtrl->SetMaxLength( 0 ); - fgSizer3->Add( FilesystemOptionsTextCtrl, 0, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); - - - FilesystemSizer->Add( fgSizer3, 1, wxEXPAND, 5 ); - - - bSizer35->Add( FilesystemSizer, 0, wxEXPAND|wxALL, 5 ); - - - bSizer46->Add( bSizer35, 1, wxEXPAND|wxALL, 5 ); - - - DefaultMountOptionsPage->SetSizer( bSizer46 ); - DefaultMountOptionsPage->Layout(); - bSizer46->Fit( DefaultMountOptionsPage ); - PreferencesNotebook->AddPage( DefaultMountOptionsPage, _("Mount Options"), false ); - BackgroundTaskPanel = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - wxBoxSizer* bSizer61; - bSizer61 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer62; - bSizer62 = new wxBoxSizer( wxVERTICAL ); - - wxStaticBoxSizer* sbSizer18; - sbSizer18 = new wxStaticBoxSizer( new wxStaticBox( BackgroundTaskPanel, wxID_ANY, _("VeraCrypt Background Task") ), wxVERTICAL ); - - BackgroundTaskEnabledCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Enabled"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer18->Add( BackgroundTaskEnabledCheckBox, 0, wxALL, 5 ); - - CloseBackgroundTaskOnNoVolumesCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Exit when there are no mounted volumes"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer18->Add( CloseBackgroundTaskOnNoVolumesCheckBox, 0, wxALL, 5 ); - - wxStaticBoxSizer* sbSizer26; - sbSizer26 = new wxStaticBoxSizer( new wxStaticBox( BackgroundTaskPanel, wxID_ANY, _("Task Icon Menu Items") ), wxVERTICAL ); - - BackgroundTaskMenuMountItemsEnabledCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Mount Favorite Volumes"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer26->Add( BackgroundTaskMenuMountItemsEnabledCheckBox, 0, wxALL, 5 ); - - BackgroundTaskMenuOpenItemsEnabledCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Open Mounted Volumes"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer26->Add( BackgroundTaskMenuOpenItemsEnabledCheckBox, 0, wxALL, 5 ); - - BackgroundTaskMenuDismountItemsEnabledCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Dismount Mounted Volumes"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer26->Add( BackgroundTaskMenuDismountItemsEnabledCheckBox, 0, wxALL, 5 ); - - - sbSizer18->Add( sbSizer26, 1, wxEXPAND|wxALL, 5 ); - - - bSizer62->Add( sbSizer18, 0, wxEXPAND|wxALL, 5 ); - - - bSizer61->Add( bSizer62, 1, wxEXPAND|wxALL, 5 ); - - - BackgroundTaskPanel->SetSizer( bSizer61 ); - BackgroundTaskPanel->Layout(); - bSizer61->Fit( BackgroundTaskPanel ); - PreferencesNotebook->AddPage( BackgroundTaskPanel, _("Background Task"), false ); - SystemIntegrationPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - wxBoxSizer* bSizer49; - bSizer49 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer37; - bSizer37 = new wxBoxSizer( wxVERTICAL ); - - LogOnSizer = new wxStaticBoxSizer( new wxStaticBox( SystemIntegrationPage, wxID_ANY, _("Actions to Perform when User Logs On") ), wxVERTICAL ); - - StartOnLogonCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Start VeraCrypt Background Task"), wxDefaultPosition, wxDefaultSize, 0 ); - LogOnSizer->Add( StartOnLogonCheckBox, 0, wxALL, 5 ); - - MountFavoritesOnLogonCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Mount favorite volumes"), wxDefaultPosition, wxDefaultSize, 0 ); - LogOnSizer->Add( MountFavoritesOnLogonCheckBox, 0, wxALL, 5 ); - - MountDevicesOnLogonCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Mount all device-hosted VeraCrypt volumes"), wxDefaultPosition, wxDefaultSize, 0 ); - LogOnSizer->Add( MountDevicesOnLogonCheckBox, 0, wxALL, 5 ); - - - bSizer37->Add( LogOnSizer, 0, wxALL|wxEXPAND, 5 ); - - ExplorerSizer = new wxStaticBoxSizer( new wxStaticBox( SystemIntegrationPage, wxID_ANY, _("Filesystem Explorer") ), wxVERTICAL ); - - OpenExplorerWindowAfterMountCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Open Explorer window for successfully mounted volume"), wxDefaultPosition, wxDefaultSize, 0 ); - ExplorerSizer->Add( OpenExplorerWindowAfterMountCheckBox, 0, wxALL, 5 ); - - CloseExplorerWindowsOnDismountCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Close all Explorer windows of volume being dismounted"), wxDefaultPosition, wxDefaultSize, 0 ); - ExplorerSizer->Add( CloseExplorerWindowsOnDismountCheckBox, 0, wxALL, 5 ); - - - bSizer37->Add( ExplorerSizer, 0, wxEXPAND|wxALL, 5 ); - - KernelServicesSizer = new wxStaticBoxSizer( new wxStaticBox( SystemIntegrationPage, wxID_ANY, _("Kernel Services") ), wxVERTICAL ); - - NoKernelCryptoCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Do not use kernel cryptographic services"), wxDefaultPosition, wxDefaultSize, 0 ); - KernelServicesSizer->Add( NoKernelCryptoCheckBox, 0, wxALL, 5 ); - - - bSizer37->Add( KernelServicesSizer, 0, wxEXPAND|wxALL, 5 ); - - - bSizer49->Add( bSizer37, 1, wxEXPAND|wxALL, 5 ); - - - SystemIntegrationPage->SetSizer( bSizer49 ); - SystemIntegrationPage->Layout(); - bSizer49->Fit( SystemIntegrationPage ); - PreferencesNotebook->AddPage( SystemIntegrationPage, _("System Integration"), false ); - PerformanceOptionsPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - wxBoxSizer* bSizer151; - bSizer151 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer152; - bSizer152 = new wxBoxSizer( wxVERTICAL ); - - wxStaticBoxSizer* sbSizer44; - sbSizer44 = new wxStaticBoxSizer( new wxStaticBox( PerformanceOptionsPage, wxID_ANY, _("Hardware Acceleration") ), wxVERTICAL ); - - wxBoxSizer* bSizer158; - bSizer158 = new wxBoxSizer( wxHORIZONTAL ); - - wxStaticText* m_staticText57; - m_staticText57 = new wxStaticText( PerformanceOptionsPage, wxID_ANY, _("Processor (CPU) in this computer supports hardware acceleration for AES:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText57->Wrap( -1 ); - bSizer158->Add( m_staticText57, 0, wxALL, 5 ); - - AesHwCpuSupportedStaticText = new wxStaticText( PerformanceOptionsPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0|wxSUNKEN_BORDER ); - AesHwCpuSupportedStaticText->Wrap( -1 ); - bSizer158->Add( AesHwCpuSupportedStaticText, 0, wxALL, 5 ); - - - sbSizer44->Add( bSizer158, 1, wxEXPAND, 5 ); - - - sbSizer44->Add( 0, 0, 0, wxBOTTOM, 5 ); - - NoHardwareCryptoCheckBox = new wxCheckBox( PerformanceOptionsPage, wxID_ANY, _("Do not accelerate AES encryption/decryption by using the AES instructions of the processor"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer44->Add( NoHardwareCryptoCheckBox, 0, wxALL, 5 ); - - - bSizer152->Add( sbSizer44, 0, wxEXPAND|wxALL, 5 ); - - - bSizer151->Add( bSizer152, 1, wxALL|wxEXPAND, 5 ); - - - PerformanceOptionsPage->SetSizer( bSizer151 ); - PerformanceOptionsPage->Layout(); - bSizer151->Fit( PerformanceOptionsPage ); - PreferencesNotebook->AddPage( PerformanceOptionsPage, _("Performance"), false ); - DefaultKeyfilesPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - wxBoxSizer* bSizer40; - bSizer40 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer43; - bSizer43 = new wxBoxSizer( wxVERTICAL ); - - wxStaticBoxSizer* bSizer42; - bSizer42 = new wxStaticBoxSizer( new wxStaticBox( DefaultKeyfilesPage, wxID_ANY, _("Default Keyfiles") ), wxVERTICAL ); - - DefaultKeyfilesSizer = new wxBoxSizer( wxVERTICAL ); - - - bSizer42->Add( DefaultKeyfilesSizer, 1, wxEXPAND, 5 ); - - - bSizer43->Add( bSizer42, 1, wxEXPAND|wxALL, 5 ); - - UseKeyfilesCheckBox = new wxCheckBox( DefaultKeyfilesPage, wxID_ANY, _("Use keyfiles by default"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer43->Add( UseKeyfilesCheckBox, 0, wxALL, 5 ); - - - bSizer40->Add( bSizer43, 1, wxEXPAND|wxALL, 5 ); - - - DefaultKeyfilesPage->SetSizer( bSizer40 ); - DefaultKeyfilesPage->Layout(); - bSizer40->Fit( DefaultKeyfilesPage ); - PreferencesNotebook->AddPage( DefaultKeyfilesPage, _("Keyfiles"), false ); - SecurityTokensPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - wxBoxSizer* bSizer127; - bSizer127 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer128; - bSizer128 = new wxBoxSizer( wxVERTICAL ); - - wxStaticBoxSizer* sbSizer36; - sbSizer36 = new wxStaticBoxSizer( new wxStaticBox( SecurityTokensPage, wxID_ANY, _("PKCS #11 Library Path") ), wxVERTICAL ); - - wxBoxSizer* bSizer129; - bSizer129 = new wxBoxSizer( wxHORIZONTAL ); - - Pkcs11ModulePathTextCtrl = new wxTextCtrl( SecurityTokensPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - Pkcs11ModulePathTextCtrl->SetMaxLength( 0 ); - bSizer129->Add( Pkcs11ModulePathTextCtrl, 1, wxALL, 5 ); - - SelectPkcs11ModuleButton = new wxButton( SecurityTokensPage, wxID_ANY, _("Select &Library..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer129->Add( SelectPkcs11ModuleButton, 0, wxALL, 5 ); - - - sbSizer36->Add( bSizer129, 1, wxEXPAND, 5 ); - - - bSizer128->Add( sbSizer36, 0, wxEXPAND|wxALL, 5 ); - - wxStaticBoxSizer* sbSizer37; - sbSizer37 = new wxStaticBoxSizer( new wxStaticBox( SecurityTokensPage, wxID_ANY, _("Security Options") ), wxVERTICAL ); - - CloseSecurityTokenSessionsAfterMountCheckBox = new wxCheckBox( SecurityTokensPage, wxID_ANY, _("&Close token session (log out) after a volume is successfully mounted"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer37->Add( CloseSecurityTokenSessionsAfterMountCheckBox, 0, wxALL, 5 ); - - - bSizer128->Add( sbSizer37, 0, wxEXPAND|wxALL, 5 ); - - - bSizer127->Add( bSizer128, 1, wxEXPAND|wxALL, 5 ); - - - SecurityTokensPage->SetSizer( bSizer127 ); - SecurityTokensPage->Layout(); - bSizer127->Fit( SecurityTokensPage ); - PreferencesNotebook->AddPage( SecurityTokensPage, _("Security Tokens"), false ); - HotkeysPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); - wxBoxSizer* bSizer51; - bSizer51 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer38; - bSizer38 = new wxBoxSizer( wxVERTICAL ); - - wxStaticBoxSizer* sbSizer21; - sbSizer21 = new wxStaticBoxSizer( new wxStaticBox( HotkeysPage, wxID_ANY, _("System-Wide Hotkeys") ), wxVERTICAL ); - - HotkeyListCtrl = new wxListCtrl( HotkeysPage, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES|wxSUNKEN_BORDER ); - sbSizer21->Add( HotkeyListCtrl, 1, wxALL|wxEXPAND, 5 ); - - wxStaticBoxSizer* sbSizer23; - sbSizer23 = new wxStaticBoxSizer( new wxStaticBox( HotkeysPage, wxID_ANY, _("Shortcut") ), wxVERTICAL ); - - wxFlexGridSizer* fgSizer4; - fgSizer4 = new wxFlexGridSizer( 2, 3, 0, 0 ); - fgSizer4->SetFlexibleDirection( wxBOTH ); - fgSizer4->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - - wxStaticText* m_staticText10; - m_staticText10 = new wxStaticText( HotkeysPage, wxID_ANY, _("Key to assign:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText10->Wrap( -1 ); - fgSizer4->Add( m_staticText10, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - HotkeyTextCtrl = new wxTextCtrl( HotkeysPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - HotkeyTextCtrl->SetMaxLength( 0 ); - fgSizer4->Add( HotkeyTextCtrl, 0, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); - - AssignHotkeyButton = new wxButton( HotkeysPage, wxID_ANY, _("Assign"), wxDefaultPosition, wxDefaultSize, 0 ); - fgSizer4->Add( AssignHotkeyButton, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - - fgSizer4->Add( 0, 0, 1, wxEXPAND, 5 ); - - wxGridSizer* gSizer4; - gSizer4 = new wxGridSizer( 1, 4, 0, 0 ); - - HotkeyControlCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Control"), wxDefaultPosition, wxDefaultSize, 0 ); - gSizer4->Add( HotkeyControlCheckBox, 0, wxALL, 5 ); - - HotkeyShiftCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Shift"), wxDefaultPosition, wxDefaultSize, 0 ); - gSizer4->Add( HotkeyShiftCheckBox, 0, wxALL, 5 ); - - HotkeyAltCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Alt"), wxDefaultPosition, wxDefaultSize, 0 ); - gSizer4->Add( HotkeyAltCheckBox, 0, wxALL, 5 ); - - HotkeyWinCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Win"), wxDefaultPosition, wxDefaultSize, 0 ); - gSizer4->Add( HotkeyWinCheckBox, 0, wxALL, 5 ); - - - fgSizer4->Add( gSizer4, 1, wxEXPAND, 5 ); - - RemoveHotkeyButton = new wxButton( HotkeysPage, wxID_ANY, _("Remove"), wxDefaultPosition, wxDefaultSize, 0 ); - fgSizer4->Add( RemoveHotkeyButton, 1, wxALL, 5 ); - - - sbSizer23->Add( fgSizer4, 1, wxALIGN_RIGHT, 5 ); - - - sbSizer21->Add( sbSizer23, 0, wxEXPAND|wxALL, 5 ); - - wxStaticBoxSizer* sbSizer24; - sbSizer24 = new wxStaticBoxSizer( new wxStaticBox( HotkeysPage, wxID_ANY, _("Options") ), wxVERTICAL ); - - BeepAfterHotkeyMountDismountCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Play system notification sound after mount/dismount"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer24->Add( BeepAfterHotkeyMountDismountCheckBox, 0, wxALL, 5 ); - - DisplayMessageAfterHotkeyDismountCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Display confirmation message box after dismount"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer24->Add( DisplayMessageAfterHotkeyDismountCheckBox, 0, wxALL, 5 ); - - - sbSizer21->Add( sbSizer24, 0, wxEXPAND|wxALL, 5 ); - - - bSizer38->Add( sbSizer21, 1, wxEXPAND|wxALL, 5 ); - - - bSizer51->Add( bSizer38, 1, wxEXPAND|wxALL, 5 ); - - - HotkeysPage->SetSizer( bSizer51 ); - HotkeysPage->Layout(); - bSizer51->Fit( HotkeysPage ); - PreferencesNotebook->AddPage( HotkeysPage, _("Hotkeys"), false ); - - bSizer41->Add( PreferencesNotebook, 1, wxEXPAND | wxALL, 5 ); - - StdButtons = new wxStdDialogButtonSizer(); - StdButtonsOK = new wxButton( this, wxID_OK ); - StdButtons->AddButton( StdButtonsOK ); - StdButtonsCancel = new wxButton( this, wxID_CANCEL ); - StdButtons->AddButton( StdButtonsCancel ); - StdButtons->Realize(); - - bSizer41->Add( StdButtons, 0, wxEXPAND|wxALL, 5 ); - - - bSizer32->Add( bSizer41, 1, wxEXPAND|wxALL, 5 ); - - - this->SetSizer( bSizer32 ); - this->Layout(); - bSizer32->Fit( this ); - - // Connect Events - this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( PreferencesDialogBase::OnClose ) ); - DismountOnScreenSaverCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnDismountOnScreenSaverCheckBoxClick ), NULL, this ); - DismountOnPowerSavingCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnDismountOnPowerSavingCheckBoxClick ), NULL, this ); - ForceAutoDismountCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnForceAutoDismountCheckBoxClick ), NULL, this ); - PreserveTimestampsCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnPreserveTimestampsCheckBoxClick ), NULL, this ); - BackgroundTaskEnabledCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnBackgroundTaskEnabledCheckBoxClick ), NULL, this ); - NoKernelCryptoCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnNoKernelCryptoCheckBoxClick ), NULL, this ); - NoHardwareCryptoCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnNoHardwareCryptoCheckBoxClick ), NULL, this ); - SelectPkcs11ModuleButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnSelectPkcs11ModuleButtonClick ), NULL, this ); - HotkeyListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( PreferencesDialogBase::OnHotkeyListItemDeselected ), NULL, this ); - HotkeyListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( PreferencesDialogBase::OnHotkeyListItemSelected ), NULL, this ); - AssignHotkeyButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnAssignHotkeyButtonClick ), NULL, this ); - RemoveHotkeyButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnRemoveHotkeyButtonClick ), NULL, this ); - StdButtonsCancel->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnCancelButtonClick ), NULL, this ); - StdButtonsOK->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnOKButtonClick ), NULL, this ); -} - -PreferencesDialogBase::~PreferencesDialogBase() -{ - // Disconnect Events - this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( PreferencesDialogBase::OnClose ) ); - DismountOnScreenSaverCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnDismountOnScreenSaverCheckBoxClick ), NULL, this ); - DismountOnPowerSavingCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnDismountOnPowerSavingCheckBoxClick ), NULL, this ); - ForceAutoDismountCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnForceAutoDismountCheckBoxClick ), NULL, this ); - PreserveTimestampsCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnPreserveTimestampsCheckBoxClick ), NULL, this ); - BackgroundTaskEnabledCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnBackgroundTaskEnabledCheckBoxClick ), NULL, this ); - NoKernelCryptoCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnNoKernelCryptoCheckBoxClick ), NULL, this ); - NoHardwareCryptoCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnNoHardwareCryptoCheckBoxClick ), NULL, this ); - SelectPkcs11ModuleButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnSelectPkcs11ModuleButtonClick ), NULL, this ); - HotkeyListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( PreferencesDialogBase::OnHotkeyListItemDeselected ), NULL, this ); - HotkeyListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( PreferencesDialogBase::OnHotkeyListItemSelected ), NULL, this ); - AssignHotkeyButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnAssignHotkeyButtonClick ), NULL, this ); - RemoveHotkeyButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnRemoveHotkeyButtonClick ), NULL, this ); - StdButtonsCancel->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnCancelButtonClick ), NULL, this ); - StdButtonsOK->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnOKButtonClick ), NULL, this ); - -} - -RandomPoolEnrichmentDialogBase::RandomPoolEnrichmentDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - - MainSizer = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer144; - bSizer144 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer145; - bSizer145 = new wxBoxSizer( wxHORIZONTAL ); - - - bSizer145->Add( 0, 0, 1, wxEXPAND, 5 ); - - wxStaticText* m_staticText49; - m_staticText49 = new wxStaticText( this, wxID_ANY, _("Mixing PRF:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText49->Wrap( -1 ); - bSizer145->Add( m_staticText49, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - wxArrayString HashChoiceChoices; - HashChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, HashChoiceChoices, 0 ); - HashChoice->SetSelection( 0 ); - bSizer145->Add( HashChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - - bSizer145->Add( 0, 0, 1, wxEXPAND, 5 ); - - - bSizer144->Add( bSizer145, 0, wxEXPAND, 5 ); - - wxStaticBoxSizer* sbSizer43; - sbSizer43 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - wxBoxSizer* bSizer147; - bSizer147 = new wxBoxSizer( wxHORIZONTAL ); - - wxStaticText* m_staticText52; - m_staticText52 = new wxStaticText( this, wxID_ANY, _("Random Pool:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText52->Wrap( -1 ); - bSizer147->Add( m_staticText52, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); - - RandomPoolStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - RandomPoolStaticText->Wrap( -1 ); - RandomPoolStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); - - bSizer147->Add( RandomPoolStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - ShowRandomPoolCheckBox = new wxCheckBox( this, wxID_ANY, _("Show"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer147->Add( ShowRandomPoolCheckBox, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - - sbSizer43->Add( bSizer147, 0, wxEXPAND|wxTOP, 5 ); - - - sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); - - wxStaticBoxSizer* sbSizer45; - sbSizer45 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Randomness Collected From Mouse Movements") ), wxVERTICAL ); - - CollectedEntropy = new wxGauge( this, wxID_ANY, 2560, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); - CollectedEntropy->SetValue( 0 ); - sbSizer45->Add( CollectedEntropy, 0, wxALL|wxEXPAND, 5 ); - - - sbSizer43->Add( sbSizer45, 0, wxBOTTOM|wxEXPAND|wxTOP, 5 ); - - - sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); - - MouseStaticText = new wxStaticText( this, wxID_ANY, _("IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases security. When done, click 'Continue'."), wxDefaultPosition, wxDefaultSize, 0 ); - MouseStaticText->Wrap( -1 ); - sbSizer43->Add( MouseStaticText, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 ); - - - sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); - - - bSizer144->Add( sbSizer43, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - - wxBoxSizer* bSizer146; - bSizer146 = new wxBoxSizer( wxHORIZONTAL ); - - - bSizer146->Add( 0, 0, 1, wxEXPAND, 5 ); - - ContinueButton = new wxButton( this, wxID_OK, _("&Continue"), wxDefaultPosition, wxDefaultSize, 0 ); - ContinueButton->SetDefault(); - bSizer146->Add( ContinueButton, 0, wxALL, 5 ); - - - bSizer146->Add( 0, 0, 1, wxEXPAND, 5 ); - - - bSizer144->Add( bSizer146, 0, wxEXPAND, 5 ); - - - MainSizer->Add( bSizer144, 1, wxEXPAND|wxALL, 5 ); - - - this->SetSizer( MainSizer ); - this->Layout(); - MainSizer->Fit( this ); - - this->Centre( wxBOTH ); - - // Connect Events - this->Connect( wxEVT_MOTION, wxMouseEventHandler( RandomPoolEnrichmentDialogBase::OnMouseMotion ) ); - HashChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( RandomPoolEnrichmentDialogBase::OnHashSelected ), NULL, this ); - ShowRandomPoolCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( RandomPoolEnrichmentDialogBase::OnShowRandomPoolCheckBoxClicked ), NULL, this ); -} - -RandomPoolEnrichmentDialogBase::~RandomPoolEnrichmentDialogBase() -{ - // Disconnect Events - this->Disconnect( wxEVT_MOTION, wxMouseEventHandler( RandomPoolEnrichmentDialogBase::OnMouseMotion ) ); - HashChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( RandomPoolEnrichmentDialogBase::OnHashSelected ), NULL, this ); - ShowRandomPoolCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( RandomPoolEnrichmentDialogBase::OnShowRandomPoolCheckBoxClicked ), NULL, this ); - -} - -SecurityTokenKeyfilesDialogBase::SecurityTokenKeyfilesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxSize( -1,-1 ), wxDefaultSize ); - this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); - - wxBoxSizer* bSizer3; - bSizer3 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer138; - bSizer138 = new wxBoxSizer( wxHORIZONTAL ); - - wxBoxSizer* bSizer142; - bSizer142 = new wxBoxSizer( wxVERTICAL ); - - SecurityTokenKeyfileListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES|wxSUNKEN_BORDER ); - bSizer142->Add( SecurityTokenKeyfileListCtrl, 1, wxALL|wxEXPAND, 5 ); - - wxBoxSizer* bSizer141; - bSizer141 = new wxBoxSizer( wxHORIZONTAL ); - - ExportButton = new wxButton( this, wxID_ANY, _("&Export..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer141->Add( ExportButton, 0, wxALL, 5 ); - - DeleteButton = new wxButton( this, wxID_ANY, _("&Delete"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer141->Add( DeleteButton, 0, wxALL, 5 ); - - - bSizer141->Add( 0, 0, 1, wxEXPAND|wxLEFT, 5 ); - - ImportButton = new wxButton( this, wxID_ANY, _("&Import Keyfile to Token..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer141->Add( ImportButton, 0, wxALL, 5 ); - - - bSizer142->Add( bSizer141, 0, wxEXPAND, 5 ); - - - bSizer138->Add( bSizer142, 1, wxEXPAND, 5 ); - - wxBoxSizer* bSizer139; - bSizer139 = new wxBoxSizer( wxVERTICAL ); - - OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); - bSizer139->Add( OKButton, 0, wxALL, 5 ); - - CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer139->Add( CancelButton, 0, wxALL, 5 ); - - - bSizer138->Add( bSizer139, 0, wxEXPAND, 5 ); - - - bSizer3->Add( bSizer138, 1, wxEXPAND|wxALL, 5 ); - - - this->SetSizer( bSizer3 ); - this->Layout(); - bSizer3->Fit( this ); - - // Connect Events - SecurityTokenKeyfileListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemActivated ), NULL, this ); - SecurityTokenKeyfileListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemDeselected ), NULL, this ); - SecurityTokenKeyfileListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemSelected ), NULL, this ); - ExportButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnExportButtonClick ), NULL, this ); - DeleteButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnDeleteButtonClick ), NULL, this ); - ImportButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnImportButtonClick ), NULL, this ); - OKButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnOKButtonClick ), NULL, this ); -} - -SecurityTokenKeyfilesDialogBase::~SecurityTokenKeyfilesDialogBase() -{ - // Disconnect Events - SecurityTokenKeyfileListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemActivated ), NULL, this ); - SecurityTokenKeyfileListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemDeselected ), NULL, this ); - SecurityTokenKeyfileListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemSelected ), NULL, this ); - ExportButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnExportButtonClick ), NULL, this ); - DeleteButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnDeleteButtonClick ), NULL, this ); - ImportButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnImportButtonClick ), NULL, this ); - OKButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnOKButtonClick ), NULL, this ); - -} - -VolumePropertiesDialogBase::VolumePropertiesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - - wxBoxSizer* bSizer49; - bSizer49 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer50; - bSizer50 = new wxBoxSizer( wxVERTICAL ); - - PropertiesListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES|wxSUNKEN_BORDER ); - bSizer50->Add( PropertiesListCtrl, 1, wxALL|wxEXPAND, 5 ); - - StdButtons = new wxStdDialogButtonSizer(); - StdButtonsOK = new wxButton( this, wxID_OK ); - StdButtons->AddButton( StdButtonsOK ); - StdButtons->Realize(); - - bSizer50->Add( StdButtons, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 ); - - - bSizer49->Add( bSizer50, 1, wxEXPAND|wxALL, 5 ); - - - this->SetSizer( bSizer49 ); - this->Layout(); - bSizer49->Fit( this ); -} - -VolumePropertiesDialogBase::~VolumePropertiesDialogBase() -{ -} - -EncryptionOptionsWizardPageBase::EncryptionOptionsWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) -{ - wxBoxSizer* bSizer93; - bSizer93 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer94; - bSizer94 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer95; - bSizer95 = new wxBoxSizer( wxVERTICAL ); - - wxStaticBoxSizer* sbSizer29; - sbSizer29 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Encryption Algorithm") ), wxVERTICAL ); - - wxBoxSizer* bSizer96; - bSizer96 = new wxBoxSizer( wxHORIZONTAL ); - - wxArrayString EncryptionAlgorithmChoiceChoices; - EncryptionAlgorithmChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, EncryptionAlgorithmChoiceChoices, 0 ); - EncryptionAlgorithmChoice->SetSelection( 0 ); - bSizer96->Add( EncryptionAlgorithmChoice, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - TestButton = new wxButton( this, wxID_ANY, _("&Test"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer96->Add( TestButton, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); - - - sbSizer29->Add( bSizer96, 0, wxEXPAND, 5 ); - - EncryptionAlgorithmStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - EncryptionAlgorithmStaticText->Wrap( -1 ); - sbSizer29->Add( EncryptionAlgorithmStaticText, 1, wxALL|wxEXPAND, 5 ); - - wxBoxSizer* bSizer97; - bSizer97 = new wxBoxSizer( wxHORIZONTAL ); - - EncryptionAlgorithmHyperlink = new wxHyperlinkCtrl( this, wxID_ANY, _("More information"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); - - EncryptionAlgorithmHyperlink->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - EncryptionAlgorithmHyperlink->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - EncryptionAlgorithmHyperlink->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - bSizer97->Add( EncryptionAlgorithmHyperlink, 0, wxALL, 5 ); - - - bSizer97->Add( 0, 0, 1, wxEXPAND, 5 ); - - BenchmarkButton = new wxButton( this, wxID_ANY, _("&Benchmark"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer97->Add( BenchmarkButton, 0, wxALL, 5 ); - - - sbSizer29->Add( bSizer97, 0, wxEXPAND, 5 ); - - - bSizer95->Add( sbSizer29, 1, wxEXPAND|wxALL, 5 ); - - wxStaticBoxSizer* sbSizer30; - sbSizer30 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Hash Algorithm") ), wxHORIZONTAL ); - - wxArrayString HashChoiceChoices; - HashChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, HashChoiceChoices, 0 ); - HashChoice->SetSelection( 0 ); - sbSizer30->Add( HashChoice, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - HashHyperlink = new wxHyperlinkCtrl( this, wxID_ANY, _("Information on hash algorithms"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); - - HashHyperlink->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - HashHyperlink->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - HashHyperlink->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); - sbSizer30->Add( HashHyperlink, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - - bSizer95->Add( sbSizer30, 0, wxEXPAND|wxALL, 5 ); - - - bSizer94->Add( bSizer95, 1, wxEXPAND, 5 ); - - - bSizer93->Add( bSizer94, 1, wxEXPAND, 5 ); - - - this->SetSizer( bSizer93 ); - this->Layout(); - bSizer93->Fit( this ); - - // Connect Events - EncryptionAlgorithmChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnEncryptionAlgorithmSelected ), NULL, this ); - TestButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnTestButtonClick ), NULL, this ); - EncryptionAlgorithmHyperlink->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( EncryptionOptionsWizardPageBase::OnEncryptionAlgorithmHyperlinkClick ), NULL, this ); - BenchmarkButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnBenchmarkButtonClick ), NULL, this ); - HashHyperlink->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( EncryptionOptionsWizardPageBase::OnHashHyperlinkClick ), NULL, this ); -} - -EncryptionOptionsWizardPageBase::~EncryptionOptionsWizardPageBase() -{ - // Disconnect Events - EncryptionAlgorithmChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnEncryptionAlgorithmSelected ), NULL, this ); - TestButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnTestButtonClick ), NULL, this ); - EncryptionAlgorithmHyperlink->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( EncryptionOptionsWizardPageBase::OnEncryptionAlgorithmHyperlinkClick ), NULL, this ); - BenchmarkButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnBenchmarkButtonClick ), NULL, this ); - HashHyperlink->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( EncryptionOptionsWizardPageBase::OnHashHyperlinkClick ), NULL, this ); - -} - -InfoWizardPageBase::InfoWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) -{ - wxBoxSizer* bSizer71; - bSizer71 = new wxBoxSizer( wxVERTICAL ); - - InfoPageSizer = new wxBoxSizer( wxVERTICAL ); - - InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - InfoStaticText->Wrap( -1 ); - InfoPageSizer->Add( InfoStaticText, 1, wxALL|wxEXPAND, 5 ); - - - bSizer71->Add( InfoPageSizer, 1, wxEXPAND, 5 ); - - - this->SetSizer( bSizer71 ); - this->Layout(); - bSizer71->Fit( this ); -} - -InfoWizardPageBase::~InfoWizardPageBase() -{ -} - -KeyfilesPanelBase::KeyfilesPanelBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) -{ - this->SetMinSize( wxSize( 500,300 ) ); - - wxBoxSizer* bSizer19; - bSizer19 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer20; - bSizer20 = new wxBoxSizer( wxHORIZONTAL ); - - wxBoxSizer* bSizer21; - bSizer21 = new wxBoxSizer( wxVERTICAL ); - - KeyfilesListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxSUNKEN_BORDER ); - bSizer21->Add( KeyfilesListCtrl, 1, wxEXPAND|wxALL, 5 ); - - wxBoxSizer* bSizer137; - bSizer137 = new wxBoxSizer( wxHORIZONTAL ); - - AddFilesButton = new wxButton( this, wxID_ANY, _("Add &Files..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer137->Add( AddFilesButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - AddDirectoryButton = new wxButton( this, wxID_ANY, _("Add &Path..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer137->Add( AddDirectoryButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - AddSecurityTokenSignatureButton = new wxButton( this, wxID_ANY, _("Add &Token Files..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer137->Add( AddSecurityTokenSignatureButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - RemoveButton = new wxButton( this, wxID_ANY, _("&Remove"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer137->Add( RemoveButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - RemoveAllButton = new wxButton( this, wxID_ANY, _("Remove &All"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer137->Add( RemoveAllButton, 0, wxEXPAND|wxALL, 5 ); - - - bSizer21->Add( bSizer137, 0, wxEXPAND, 5 ); - - - bSizer20->Add( bSizer21, 1, wxEXPAND, 5 ); - - - bSizer19->Add( bSizer20, 1, wxEXPAND, 5 ); - - - this->SetSizer( bSizer19 ); - this->Layout(); - bSizer19->Fit( this ); - - // Connect Events - KeyfilesListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( KeyfilesPanelBase::OnListItemDeselected ), NULL, this ); - KeyfilesListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( KeyfilesPanelBase::OnListItemSelected ), NULL, this ); - KeyfilesListCtrl->Connect( wxEVT_SIZE, wxSizeEventHandler( KeyfilesPanelBase::OnListSizeChanged ), NULL, this ); - AddFilesButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddFilesButtonClick ), NULL, this ); - AddDirectoryButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddDirectoryButtonClick ), NULL, this ); - AddSecurityTokenSignatureButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddSecurityTokenSignatureButtonClick ), NULL, this ); - RemoveButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnRemoveButtonClick ), NULL, this ); - RemoveAllButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnRemoveAllButtonClick ), NULL, this ); -} - -KeyfilesPanelBase::~KeyfilesPanelBase() -{ - // Disconnect Events - KeyfilesListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( KeyfilesPanelBase::OnListItemDeselected ), NULL, this ); - KeyfilesListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( KeyfilesPanelBase::OnListItemSelected ), NULL, this ); - KeyfilesListCtrl->Disconnect( wxEVT_SIZE, wxSizeEventHandler( KeyfilesPanelBase::OnListSizeChanged ), NULL, this ); - AddFilesButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddFilesButtonClick ), NULL, this ); - AddDirectoryButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddDirectoryButtonClick ), NULL, this ); - AddSecurityTokenSignatureButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddSecurityTokenSignatureButtonClick ), NULL, this ); - RemoveButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnRemoveButtonClick ), NULL, this ); - RemoveAllButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnRemoveAllButtonClick ), NULL, this ); - -} - -ProgressWizardPageBase::ProgressWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) -{ - wxBoxSizer* bSizer81; - bSizer81 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer82; - bSizer82 = new wxBoxSizer( wxVERTICAL ); - - ProgressSizer = new wxBoxSizer( wxHORIZONTAL ); - - ProgressGauge = new wxGauge( this, wxID_ANY, 100, wxDefaultPosition, wxSize( -1,-1 ), wxGA_HORIZONTAL|wxGA_SMOOTH ); - ProgressGauge->SetValue( 0 ); - ProgressSizer->Add( ProgressGauge, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - AbortButton = new wxButton( this, wxID_ANY, _("&Abort"), wxDefaultPosition, wxDefaultSize, 0 ); - AbortButton->Enable( false ); - - ProgressSizer->Add( AbortButton, 0, wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 ); - - - bSizer82->Add( ProgressSizer, 0, wxEXPAND, 5 ); - - InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - InfoStaticText->Wrap( -1 ); - bSizer82->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); - - - bSizer81->Add( bSizer82, 0, wxEXPAND, 5 ); - - - this->SetSizer( bSizer81 ); - this->Layout(); - bSizer81->Fit( this ); - - // Connect Events - AbortButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ProgressWizardPageBase::OnAbortButtonClick ), NULL, this ); -} - -ProgressWizardPageBase::~ProgressWizardPageBase() -{ - // Disconnect Events - AbortButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ProgressWizardPageBase::OnAbortButtonClick ), NULL, this ); - -} - -SelectDirectoryWizardPageBase::SelectDirectoryWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) -{ - this->SetMinSize( wxSize( 200,65 ) ); - - wxBoxSizer* bSizer68; - bSizer68 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer69; - bSizer69 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer70; - bSizer70 = new wxBoxSizer( wxHORIZONTAL ); - - DirectoryTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - DirectoryTextCtrl->SetMaxLength( 0 ); - bSizer70->Add( DirectoryTextCtrl, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - BrowseButton = new wxButton( this, wxID_ANY, _("&Browse..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer70->Add( BrowseButton, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - - bSizer69->Add( bSizer70, 0, wxEXPAND, 5 ); - - InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - InfoStaticText->Wrap( 300 ); - bSizer69->Add( InfoStaticText, 1, wxALL|wxEXPAND, 5 ); - - - bSizer68->Add( bSizer69, 1, wxEXPAND, 5 ); - - - this->SetSizer( bSizer68 ); - this->Layout(); - bSizer68->Fit( this ); - - // Connect Events - DirectoryTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( SelectDirectoryWizardPageBase::OnDirectoryTextChanged ), NULL, this ); - BrowseButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SelectDirectoryWizardPageBase::OnBrowseButtonClick ), NULL, this ); -} - -SelectDirectoryWizardPageBase::~SelectDirectoryWizardPageBase() -{ - // Disconnect Events - DirectoryTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( SelectDirectoryWizardPageBase::OnDirectoryTextChanged ), NULL, this ); - BrowseButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SelectDirectoryWizardPageBase::OnBrowseButtonClick ), NULL, this ); - -} - -SingleChoiceWizardPageBase::SingleChoiceWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) -{ - wxBoxSizer* bSizer71; - bSizer71 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer77; - bSizer77 = new wxBoxSizer( wxVERTICAL ); - - - bSizer77->Add( 0, 0, 0, wxEXPAND|wxTOP, 5 ); - - OuterChoicesSizer = new wxBoxSizer( wxVERTICAL ); - - ChoicesSizer = new wxBoxSizer( wxVERTICAL ); - - - OuterChoicesSizer->Add( ChoicesSizer, 0, wxEXPAND, 5 ); - - - bSizer77->Add( OuterChoicesSizer, 0, wxEXPAND, 5 ); - - InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - InfoStaticText->Wrap( -1 ); - bSizer77->Add( InfoStaticText, 1, wxALL|wxEXPAND, 5 ); - - - bSizer71->Add( bSizer77, 1, wxEXPAND, 5 ); - - - this->SetSizer( bSizer71 ); - this->Layout(); - bSizer71->Fit( this ); -} - -SingleChoiceWizardPageBase::~SingleChoiceWizardPageBase() -{ -} - -VolumeCreationProgressWizardPageBase::VolumeCreationProgressWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) -{ - wxBoxSizer* bSizer104; - bSizer104 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer105; - bSizer105 = new wxBoxSizer( wxVERTICAL ); - - wxStaticBoxSizer* sbSizer31; - sbSizer31 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - KeySamplesUpperSizer = new wxBoxSizer( wxVERTICAL ); - - KeySamplesUpperInnerSizer = new wxBoxSizer( wxVERTICAL ); - - - KeySamplesUpperSizer->Add( KeySamplesUpperInnerSizer, 1, wxEXPAND|wxTOP, 3 ); - - - sbSizer31->Add( KeySamplesUpperSizer, 1, wxEXPAND, 30 ); - - wxFlexGridSizer* fgSizer5; - fgSizer5 = new wxFlexGridSizer( 3, 2, 0, 0 ); - fgSizer5->SetFlexibleDirection( wxBOTH ); - fgSizer5->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - - wxStaticText* m_staticText25; - m_staticText25 = new wxStaticText( this, wxID_ANY, _("Random Pool:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText25->Wrap( -1 ); - fgSizer5->Add( m_staticText25, 0, wxALL|wxALIGN_RIGHT|wxALIGN_BOTTOM, 5 ); - - wxBoxSizer* bSizer126; - bSizer126 = new wxBoxSizer( wxHORIZONTAL ); - - RandomPoolSampleStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - RandomPoolSampleStaticText->Wrap( -1 ); - RandomPoolSampleStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); - - bSizer126->Add( RandomPoolSampleStaticText, 0, wxEXPAND|wxTOP|wxRIGHT|wxALIGN_BOTTOM, 7 ); - - DisplayKeysCheckBox = new wxCheckBox( this, wxID_ANY, _("Show"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer126->Add( DisplayKeysCheckBox, 0, wxEXPAND|wxRIGHT, 5 ); - - - fgSizer5->Add( bSizer126, 1, wxEXPAND|wxALIGN_BOTTOM, 5 ); - - wxStaticText* m_staticText28; - m_staticText28 = new wxStaticText( this, wxID_ANY, _("Header Key:"), wxDefaultPosition, wxSize( -1,-1 ), 0 ); - m_staticText28->Wrap( -1 ); - fgSizer5->Add( m_staticText28, 0, wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_BOTTOM, 5 ); - - HeaderKeySampleStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - HeaderKeySampleStaticText->Wrap( -1 ); - HeaderKeySampleStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); - - fgSizer5->Add( HeaderKeySampleStaticText, 0, wxALIGN_BOTTOM|wxEXPAND|wxTOP|wxRIGHT, 2 ); - - wxStaticText* m_staticText29; - m_staticText29 = new wxStaticText( this, wxID_ANY, _("Master Key:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText29->Wrap( -1 ); - fgSizer5->Add( m_staticText29, 0, wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_BOTTOM, 5 ); - - MasterKeySampleStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - MasterKeySampleStaticText->Wrap( -1 ); - MasterKeySampleStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); - - fgSizer5->Add( MasterKeySampleStaticText, 0, wxEXPAND|wxALIGN_BOTTOM|wxTOP|wxRIGHT, 2 ); - - - sbSizer31->Add( fgSizer5, 0, wxEXPAND, 5 ); - - - bSizer105->Add( sbSizer31, 0, wxALL|wxEXPAND, 5 ); - - wxStaticBoxSizer* sbSizer45; - sbSizer45 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Randomness Collected From Mouse Movements") ), wxVERTICAL ); - - CollectedEntropy = new wxGauge( this, wxID_ANY, 2560, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); - CollectedEntropy->SetValue( 0 ); - sbSizer45->Add( CollectedEntropy, 0, wxALL|wxEXPAND, 5 ); - - - bSizer105->Add( sbSizer45, 0, wxEXPAND|wxLEFT|wxRIGHT, 5 ); - - wxStaticBoxSizer* sbSizer32; - sbSizer32 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - wxBoxSizer* bSizer106; - bSizer106 = new wxBoxSizer( wxHORIZONTAL ); - - ProgressGauge = new wxGauge( this, wxID_ANY, 100, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); - bSizer106->Add( ProgressGauge, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - AbortButton = new wxButton( this, wxID_ANY, _("Abort"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer106->Add( AbortButton, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - - sbSizer32->Add( bSizer106, 0, wxEXPAND, 5 ); - - wxGridSizer* gSizer6; - gSizer6 = new wxGridSizer( 1, 3, 0, 0 ); - - wxBoxSizer* bSizer108; - bSizer108 = new wxBoxSizer( wxHORIZONTAL ); - - m_staticText31 = new wxStaticText( this, wxID_ANY, _("Done"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText31->Wrap( -1 ); - bSizer108->Add( m_staticText31, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - m_panel12 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxSize( -1,-1 ), wxSUNKEN_BORDER ); - wxBoxSizer* bSizer115; - bSizer115 = new wxBoxSizer( wxHORIZONTAL ); - - SizeDoneStaticText = new wxStaticText( m_panel12, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT|wxST_NO_AUTORESIZE ); - SizeDoneStaticText->Wrap( -1 ); - bSizer115->Add( SizeDoneStaticText, 1, wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL, 3 ); - - - m_panel12->SetSizer( bSizer115 ); - m_panel12->Layout(); - bSizer115->Fit( m_panel12 ); - bSizer108->Add( m_panel12, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - - gSizer6->Add( bSizer108, 1, wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); - - wxBoxSizer* bSizer1081; - bSizer1081 = new wxBoxSizer( wxHORIZONTAL ); - - m_staticText311 = new wxStaticText( this, wxID_ANY, _("Speed"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText311->Wrap( -1 ); - bSizer1081->Add( m_staticText311, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - m_panel121 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER ); - wxBoxSizer* bSizer1151; - bSizer1151 = new wxBoxSizer( wxHORIZONTAL ); - - SpeedStaticText = new wxStaticText( m_panel121, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT|wxST_NO_AUTORESIZE ); - SpeedStaticText->Wrap( -1 ); - bSizer1151->Add( SpeedStaticText, 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 3 ); - - - m_panel121->SetSizer( bSizer1151 ); - m_panel121->Layout(); - bSizer1151->Fit( m_panel121 ); - bSizer1081->Add( m_panel121, 1, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); - - - gSizer6->Add( bSizer1081, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 ); - - wxBoxSizer* bSizer1082; - bSizer1082 = new wxBoxSizer( wxHORIZONTAL ); - - m_staticText312 = new wxStaticText( this, wxID_ANY, _("Left"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText312->Wrap( -1 ); - bSizer1082->Add( m_staticText312, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - m_panel122 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); - wxBoxSizer* bSizer1152; - bSizer1152 = new wxBoxSizer( wxHORIZONTAL ); - - TimeLeftStaticText = new wxStaticText( m_panel122, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT|wxST_NO_AUTORESIZE ); - TimeLeftStaticText->Wrap( -1 ); - bSizer1152->Add( TimeLeftStaticText, 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 3 ); - - - m_panel122->SetSizer( bSizer1152 ); - m_panel122->Layout(); - bSizer1152->Fit( m_panel122 ); - bSizer1082->Add( m_panel122, 1, wxALL|wxEXPAND, 5 ); - - - gSizer6->Add( bSizer1082, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); - - - sbSizer32->Add( gSizer6, 0, wxEXPAND|wxTOP, 2 ); - - - bSizer105->Add( sbSizer32, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - - InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - InfoStaticText->Wrap( -1 ); - bSizer105->Add( InfoStaticText, 0, wxBOTTOM|wxLEFT|wxRIGHT, 5 ); - - - bSizer104->Add( bSizer105, 1, wxEXPAND, 5 ); - - - this->SetSizer( bSizer104 ); - this->Layout(); - bSizer104->Fit( this ); - - // Connect Events - DisplayKeysCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeCreationProgressWizardPageBase::OnDisplayKeysCheckBoxClick ), NULL, this ); - AbortButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeCreationProgressWizardPageBase::OnAbortButtonClick ), NULL, this ); -} - -VolumeCreationProgressWizardPageBase::~VolumeCreationProgressWizardPageBase() -{ - // Disconnect Events - DisplayKeysCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeCreationProgressWizardPageBase::OnDisplayKeysCheckBoxClick ), NULL, this ); - AbortButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeCreationProgressWizardPageBase::OnAbortButtonClick ), NULL, this ); - -} - -VolumeLocationWizardPageBase::VolumeLocationWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) -{ - wxBoxSizer* bSizer86; - bSizer86 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer87; - bSizer87 = new wxBoxSizer( wxVERTICAL ); - - - bSizer87->Add( 0, 0, 0, wxEXPAND|wxTOP, 5 ); - - wxBoxSizer* bSizer88; - bSizer88 = new wxBoxSizer( wxHORIZONTAL ); - - wxBoxSizer* bSizer89; - bSizer89 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer126; - bSizer126 = new wxBoxSizer( wxHORIZONTAL ); - - VolumePathComboBox = new wxComboBox( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_DROPDOWN ); - bSizer126->Add( VolumePathComboBox, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - wxBoxSizer* bSizer90; - bSizer90 = new wxBoxSizer( wxVERTICAL ); - - SelectFileButton = new wxButton( this, wxID_ANY, _("Select &File..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer90->Add( SelectFileButton, 0, wxALL|wxEXPAND, 5 ); - - SelectDeviceButton = new wxButton( this, wxID_ANY, _("Select D&evice..."), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer90->Add( SelectDeviceButton, 0, wxALL|wxEXPAND, 5 ); - - - bSizer126->Add( bSizer90, 0, wxALIGN_CENTER_VERTICAL, 5 ); - - - bSizer89->Add( bSizer126, 0, wxEXPAND, 5 ); - - wxBoxSizer* bSizer91; - bSizer91 = new wxBoxSizer( wxHORIZONTAL ); - - - bSizer91->Add( 0, 0, 0, wxLEFT, 5 ); - - NoHistoryCheckBox = new wxCheckBox( this, wxID_ANY, _("&Never save history"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer91->Add( NoHistoryCheckBox, 0, wxALL|wxEXPAND, 5 ); - - - bSizer89->Add( bSizer91, 0, wxEXPAND, 5 ); - - - bSizer88->Add( bSizer89, 1, wxEXPAND, 5 ); - - - bSizer87->Add( bSizer88, 0, wxEXPAND, 5 ); - - - bSizer87->Add( 0, 0, 0, wxEXPAND|wxBOTTOM, 5 ); - - InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - InfoStaticText->Wrap( -1 ); - bSizer87->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); - - - bSizer86->Add( bSizer87, 1, wxEXPAND, 5 ); - - - this->SetSizer( bSizer86 ); - this->Layout(); - bSizer86->Fit( this ); - - // Connect Events - VolumePathComboBox->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnVolumePathTextChanged ), NULL, this ); - SelectFileButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnSelectFileButtonClick ), NULL, this ); - SelectDeviceButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnSelectDeviceButtonClick ), NULL, this ); - NoHistoryCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnNoHistoryCheckBoxClick ), NULL, this ); -} - -VolumeLocationWizardPageBase::~VolumeLocationWizardPageBase() -{ - // Disconnect Events - VolumePathComboBox->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnVolumePathTextChanged ), NULL, this ); - SelectFileButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnSelectFileButtonClick ), NULL, this ); - SelectDeviceButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnSelectDeviceButtonClick ), NULL, this ); - NoHistoryCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnNoHistoryCheckBoxClick ), NULL, this ); - -} - -VolumeFormatOptionsWizardPageBase::VolumeFormatOptionsWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) -{ - wxBoxSizer* bSizer124; - bSizer124 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer125; - bSizer125 = new wxBoxSizer( wxVERTICAL ); - - wxStaticBoxSizer* sbSizer33; - sbSizer33 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Filesystem Options") ), wxVERTICAL ); - - wxFlexGridSizer* fgSizer6; - fgSizer6 = new wxFlexGridSizer( 2, 2, 0, 0 ); - fgSizer6->SetFlexibleDirection( wxBOTH ); - fgSizer6->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - - m_staticText43 = new wxStaticText( this, wxID_ANY, _("Filesystem type:"), wxDefaultPosition, wxDefaultSize, 0 ); - m_staticText43->Wrap( -1 ); - fgSizer6->Add( m_staticText43, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - wxArrayString FilesystemTypeChoiceChoices; - FilesystemTypeChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, FilesystemTypeChoiceChoices, 0 ); - FilesystemTypeChoice->SetSelection( 0 ); - fgSizer6->Add( FilesystemTypeChoice, 0, wxALL, 5 ); - - - sbSizer33->Add( fgSizer6, 1, wxEXPAND, 5 ); - - - bSizer125->Add( sbSizer33, 0, wxEXPAND|wxALL, 5 ); - - wxStaticBoxSizer* sbSizer34; - sbSizer34 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Volume Format Options") ), wxVERTICAL ); - - QuickFormatCheckBox = new wxCheckBox( this, wxID_ANY, _("Quick format"), wxDefaultPosition, wxDefaultSize, 0 ); - sbSizer34->Add( QuickFormatCheckBox, 0, wxALL, 5 ); - - - bSizer125->Add( sbSizer34, 0, wxEXPAND|wxALL, 5 ); - - - bSizer125->Add( 0, 0, 1, wxEXPAND|wxTOP|wxBOTTOM, 5 ); - - InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - InfoStaticText->Wrap( -1 ); - bSizer125->Add( InfoStaticText, 0, wxALL, 5 ); - - - bSizer124->Add( bSizer125, 0, wxEXPAND, 5 ); - - - this->SetSizer( bSizer124 ); - this->Layout(); - bSizer124->Fit( this ); - - // Connect Events - FilesystemTypeChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( VolumeFormatOptionsWizardPageBase::OnFilesystemTypeSelected ), NULL, this ); - QuickFormatCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeFormatOptionsWizardPageBase::OnQuickFormatCheckBoxClick ), NULL, this ); -} - -VolumeFormatOptionsWizardPageBase::~VolumeFormatOptionsWizardPageBase() -{ - // Disconnect Events - FilesystemTypeChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( VolumeFormatOptionsWizardPageBase::OnFilesystemTypeSelected ), NULL, this ); - QuickFormatCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeFormatOptionsWizardPageBase::OnQuickFormatCheckBoxClick ), NULL, this ); - -} - -VolumePasswordPanelBase::VolumePasswordPanelBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) -{ - wxBoxSizer* bSizer7; - bSizer7 = new wxBoxSizer( wxVERTICAL ); - - GridBagSizer = new wxGridBagSizer( 0, 0 ); - GridBagSizer->SetFlexibleDirection( wxBOTH ); - GridBagSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - GridBagSizer->SetEmptyCellSize( wxSize( 0,0 ) ); - - PasswordStaticText = new wxStaticText( this, wxID_ANY, _("Password:"), wxDefaultPosition, wxDefaultSize, 0 ); - PasswordStaticText->Wrap( -1 ); - GridBagSizer->Add( PasswordStaticText, wxGBPosition( 1, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxRIGHT, 5 ); - - PasswordTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD ); - PasswordTextCtrl->SetMaxLength( 1 ); - PasswordTextCtrl->SetMinSize( wxSize( 232,-1 ) ); - - GridBagSizer->Add( PasswordTextCtrl, wxGBPosition( 1, 1 ), wxGBSpan( 1, 2 ), wxBOTTOM|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); - - ConfirmPasswordStaticText = new wxStaticText( this, wxID_ANY, _("Confirm password:"), wxDefaultPosition, wxDefaultSize, 0 ); - ConfirmPasswordStaticText->Wrap( -1 ); - GridBagSizer->Add( ConfirmPasswordStaticText, wxGBPosition( 2, 0 ), wxGBSpan( 1, 1 ), wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); - - ConfirmPasswordTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD ); - ConfirmPasswordTextCtrl->SetMaxLength( 1 ); - ConfirmPasswordTextCtrl->SetMinSize( wxSize( 232,-1 ) ); - - GridBagSizer->Add( ConfirmPasswordTextCtrl, wxGBPosition( 2, 1 ), wxGBSpan( 1, 2 ), wxBOTTOM|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); - - VolumePimStaticText = new wxStaticText( this, wxID_ANY, _("Volume PIM:"), wxDefaultPosition, wxDefaultSize, 0 ); - VolumePimStaticText->Wrap( -1 ); - GridBagSizer->Add( VolumePimStaticText, wxGBPosition( 3, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxRIGHT, 5 ); - - VolumePimTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD ); - VolumePimTextCtrl->SetMaxLength( 7 ); - GridBagSizer->Add( VolumePimTextCtrl, wxGBPosition( 3, 1 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxEXPAND, 5 ); - - VolumePimHelpStaticText = new wxStaticText( this, wxID_ANY, _("(Empty or 0 for default iterations)"), wxDefaultPosition, wxDefaultSize, 0 ); - VolumePimHelpStaticText->Wrap( -1 ); - GridBagSizer->Add( VolumePimHelpStaticText, wxGBPosition( 3, 2 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxLEFT|wxRIGHT, 5 ); - - PimCheckBox = new wxCheckBox( this, wxID_ANY, _("Use PIM"), wxDefaultPosition, wxDefaultSize, 0 ); - GridBagSizer->Add( PimCheckBox, wxGBPosition( 4, 1 ), wxGBSpan( 1, 2 ), wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); - - CacheCheckBox = new wxCheckBox( this, wxID_ANY, _("Cach&e passwords and keyfiles in memory "), wxDefaultPosition, wxDefaultSize, 0 ); - GridBagSizer->Add( CacheCheckBox, wxGBPosition( 5, 1 ), wxGBSpan( 1, 2 ), wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); - - DisplayPasswordCheckBox = new wxCheckBox( this, wxID_ANY, _("&Display password"), wxDefaultPosition, wxDefaultSize, 0 ); - GridBagSizer->Add( DisplayPasswordCheckBox, wxGBPosition( 6, 1 ), wxGBSpan( 1, 2 ), wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); - - UseKeyfilesCheckBox = new wxCheckBox( this, wxID_ANY, _("U&se keyfiles"), wxDefaultPosition, wxDefaultSize, 0 ); - GridBagSizer->Add( UseKeyfilesCheckBox, wxGBPosition( 7, 1 ), wxGBSpan( 1, 1 ), wxTOP|wxRIGHT|wxLEFT, 5 ); - - KeyfilesButton = new wxButton( this, wxID_ANY, _("&Keyfiles..."), wxDefaultPosition, wxDefaultSize, 0 ); - GridBagSizer->Add( KeyfilesButton, wxGBPosition( 7, 2 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT|wxALIGN_BOTTOM|wxLEFT, 5 ); - - Pkcs5PrfSizer = new wxBoxSizer( wxVERTICAL ); - - - GridBagSizer->Add( Pkcs5PrfSizer, wxGBPosition( 8, 1 ), wxGBSpan( 1, 1 ), wxEXPAND|wxTOP|wxBOTTOM, 5 ); - - Pkcs5PrfStaticText = new wxStaticText( this, wxID_ANY, _("PKCS-5 PRF:"), wxDefaultPosition, wxDefaultSize, 0 ); - Pkcs5PrfStaticText->Wrap( -1 ); - GridBagSizer->Add( Pkcs5PrfStaticText, wxGBPosition( 9, 0 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxRIGHT, 5 ); - - wxString Pkcs5PrfChoiceChoices[] = { _("Unchanged") }; - int Pkcs5PrfChoiceNChoices = sizeof( Pkcs5PrfChoiceChoices ) / sizeof( wxString ); - Pkcs5PrfChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, Pkcs5PrfChoiceNChoices, Pkcs5PrfChoiceChoices, 0 ); - Pkcs5PrfChoice->SetSelection( 0 ); - GridBagSizer->Add( Pkcs5PrfChoice, wxGBPosition( 9, 1 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxLEFT, 5 ); - - TrueCryptModeCheckBox = new wxCheckBox( this, wxID_ANY, _("TrueCrypt Mode"), wxDefaultPosition, wxDefaultSize, 0 ); - GridBagSizer->Add( TrueCryptModeCheckBox, wxGBPosition( 9, 2 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxLEFT, 5 ); - - HeaderWipeCountText = new wxStaticText( this, wxID_ANY, _("Header Wipe:"), wxDefaultPosition, wxDefaultSize, 0 ); - HeaderWipeCountText->Wrap( -1 ); - GridBagSizer->Add( HeaderWipeCountText, wxGBPosition( 10, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxRIGHT, 5 ); - - wxString HeaderWipeCountChoices[] = { _("1-pass"), _("3-pass"), _("7-pass"), _("35-pass"), _("256-pass") }; - int HeaderWipeCountNChoices = sizeof( HeaderWipeCountChoices ) / sizeof( wxString ); - HeaderWipeCount = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, HeaderWipeCountNChoices, HeaderWipeCountChoices, 0 ); - HeaderWipeCount->SetSelection( 1 ); - GridBagSizer->Add( HeaderWipeCount, wxGBPosition( 10, 1 ), wxGBSpan( 1, 1 ), wxALL, 5 ); - - PasswordPlaceholderSizer = new wxBoxSizer( wxVERTICAL ); - - - GridBagSizer->Add( PasswordPlaceholderSizer, wxGBPosition( 11, 1 ), wxGBSpan( 1, 2 ), wxTOP|wxEXPAND, 5 ); - - - GridBagSizer->AddGrowableCol( 1 ); - - bSizer7->Add( GridBagSizer, 1, wxALL|wxEXPAND, 5 ); - - - this->SetSizer( bSizer7 ); - this->Layout(); - bSizer7->Fit( this ); - - // Connect Events - PasswordTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnTextChanged ), NULL, this ); - ConfirmPasswordTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnTextChanged ), NULL, this ); - VolumePimTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnPimChanged ), NULL, this ); - PimCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnUsePimCheckBoxClick ), NULL, this ); - DisplayPasswordCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnDisplayPasswordCheckBoxClick ), NULL, this ); - UseKeyfilesCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnUseKeyfilesCheckBoxClick ), NULL, this ); - KeyfilesButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonClick ), NULL, this ); - KeyfilesButton->Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonRightDown ), NULL, this ); - KeyfilesButton->Connect( wxEVT_RIGHT_UP, wxMouseEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonRightClick ), NULL, this ); - TrueCryptModeCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnTrueCryptModeChecked ), NULL, this ); -} - -VolumePasswordPanelBase::~VolumePasswordPanelBase() -{ - // Disconnect Events - PasswordTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnTextChanged ), NULL, this ); - ConfirmPasswordTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnTextChanged ), NULL, this ); - VolumePimTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnPimChanged ), NULL, this ); - PimCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnUsePimCheckBoxClick ), NULL, this ); - DisplayPasswordCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnDisplayPasswordCheckBoxClick ), NULL, this ); - UseKeyfilesCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnUseKeyfilesCheckBoxClick ), NULL, this ); - KeyfilesButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonClick ), NULL, this ); - KeyfilesButton->Disconnect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonRightDown ), NULL, this ); - KeyfilesButton->Disconnect( wxEVT_RIGHT_UP, wxMouseEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonRightClick ), NULL, this ); - TrueCryptModeCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnTrueCryptModeChecked ), NULL, this ); - -} - -VolumePasswordWizardPageBase::VolumePasswordWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) -{ - wxBoxSizer* bSizer101; - bSizer101 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer102; - bSizer102 = new wxBoxSizer( wxVERTICAL ); - - PasswordPanelSizer = new wxBoxSizer( wxVERTICAL ); - - - bSizer102->Add( PasswordPanelSizer, 0, wxEXPAND, 5 ); - - InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - InfoStaticText->Wrap( -1 ); - bSizer102->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); - - - bSizer101->Add( bSizer102, 1, wxEXPAND, 5 ); - - - this->SetSizer( bSizer101 ); - this->Layout(); - bSizer101->Fit( this ); -} - -VolumePasswordWizardPageBase::~VolumePasswordWizardPageBase() -{ -} - -VolumePimWizardPageBase::VolumePimWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) -{ - wxBoxSizer* bSizer101; - bSizer101 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer102; - bSizer102 = new wxBoxSizer( wxVERTICAL ); - - PimPanelSizer = new wxBoxSizer( wxVERTICAL ); - - PimSizer = new wxBoxSizer( wxHORIZONTAL ); - - VolumePimStaticText = new wxStaticText( this, wxID_ANY, _("Volume PIM:"), wxDefaultPosition, wxDefaultSize, 0 ); - VolumePimStaticText->Wrap( -1 ); - PimSizer->Add( VolumePimStaticText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - VolumePimTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD ); - VolumePimTextCtrl->SetMaxLength( 7 ); - PimSizer->Add( VolumePimTextCtrl, 0, wxALL, 5 ); - - VolumePimHelpStaticText = new wxStaticText( this, wxID_ANY, _("(Empty or 0 for default iterations)"), wxDefaultPosition, wxDefaultSize, 0 ); - VolumePimHelpStaticText->Wrap( -1 ); - PimSizer->Add( VolumePimHelpStaticText, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - - PimPanelSizer->Add( PimSizer, 1, wxEXPAND, 5 ); - - wxBoxSizer* bSizer166; - bSizer166 = new wxBoxSizer( wxHORIZONTAL ); - - DisplayPimCheckBox = new wxCheckBox( this, wxID_ANY, _("&Display PIM"), wxDefaultPosition, wxDefaultSize, 0 ); - bSizer166->Add( DisplayPimCheckBox, 1, wxALL|wxEXPAND, 5 ); - - - PimPanelSizer->Add( bSizer166, 1, wxEXPAND, 5 ); - - - bSizer102->Add( PimPanelSizer, 0, wxEXPAND, 5 ); - - InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - InfoStaticText->Wrap( -1 ); - bSizer102->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); - - - bSizer101->Add( bSizer102, 1, wxEXPAND, 5 ); - - - this->SetSizer( bSizer101 ); - this->Layout(); - bSizer101->Fit( this ); - - // Connect Events - VolumePimTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePimWizardPageBase::OnPimChanged ), NULL, this ); - DisplayPimCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePimWizardPageBase::OnDisplayPimCheckBoxClick ), NULL, this ); -} - -VolumePimWizardPageBase::~VolumePimWizardPageBase() -{ - // Disconnect Events - VolumePimTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePimWizardPageBase::OnPimChanged ), NULL, this ); - DisplayPimCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePimWizardPageBase::OnDisplayPimCheckBoxClick ), NULL, this ); - -} - -VolumeSizeWizardPageBase::VolumeSizeWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) -{ - wxBoxSizer* bSizer98; - bSizer98 = new wxBoxSizer( wxVERTICAL ); - - wxBoxSizer* bSizer99; - bSizer99 = new wxBoxSizer( wxVERTICAL ); - - - bSizer99->Add( 0, 0, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 ); - - wxBoxSizer* bSizer100; - bSizer100 = new wxBoxSizer( wxHORIZONTAL ); - - VolumeSizeTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - VolumeSizeTextCtrl->SetMaxLength( 0 ); - bSizer100->Add( VolumeSizeTextCtrl, 0, wxALL, 5 ); - - wxArrayString VolumeSizePrefixChoiceChoices; - VolumeSizePrefixChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, VolumeSizePrefixChoiceChoices, 0 ); - VolumeSizePrefixChoice->SetSelection( 0 ); - bSizer100->Add( VolumeSizePrefixChoice, 0, wxALL, 5 ); - - - bSizer99->Add( bSizer100, 0, wxEXPAND, 5 ); - - - bSizer99->Add( 0, 0, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 ); - - FreeSpaceStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - FreeSpaceStaticText->Wrap( -1 ); - bSizer99->Add( FreeSpaceStaticText, 0, wxALL|wxEXPAND, 5 ); - - - bSizer99->Add( 0, 0, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 ); - - InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - InfoStaticText->Wrap( -1 ); - bSizer99->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); - - - bSizer98->Add( bSizer99, 0, wxEXPAND, 5 ); - - - this->SetSizer( bSizer98 ); - this->Layout(); - bSizer98->Fit( this ); - - // Connect Events - VolumeSizeTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumeSizeWizardPageBase::OnVolumeSizeTextChanged ), NULL, this ); - VolumeSizePrefixChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( VolumeSizeWizardPageBase::OnVolumeSizePrefixSelected ), NULL, this ); -} - -VolumeSizeWizardPageBase::~VolumeSizeWizardPageBase() -{ - // Disconnect Events - VolumeSizeTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumeSizeWizardPageBase::OnVolumeSizeTextChanged ), NULL, this ); - VolumeSizePrefixChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( VolumeSizeWizardPageBase::OnVolumeSizePrefixSelected ), NULL, this ); - -} - -WaitDialogBase::WaitDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) -{ - this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - - wxBoxSizer* bSizer160; - bSizer160 = new wxBoxSizer( wxVERTICAL ); - - WaitStaticText = new wxStaticText( this, wxID_ANY, _("MyLabel"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE ); - WaitStaticText->Wrap( -1 ); - bSizer160->Add( WaitStaticText, 0, wxALIGN_CENTER_HORIZONTAL|wxALL|wxEXPAND, 5 ); - - WaitProgessBar = new wxGauge( this, wxID_ANY, 100, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); - WaitProgessBar->SetValue( 0 ); - bSizer160->Add( WaitProgessBar, 0, wxALL|wxEXPAND, 5 ); - - - this->SetSizer( bSizer160 ); - this->Layout(); - bSizer160->Fit( this ); - - this->Centre( wxBOTH ); - - // Connect Events - this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( WaitDialogBase::OnWaitDialogClose ) ); - this->Connect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( WaitDialogBase::OnWaitDialogInit ) ); -} - -WaitDialogBase::~WaitDialogBase() -{ - // Disconnect Events - this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( WaitDialogBase::OnWaitDialogClose ) ); - this->Disconnect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( WaitDialogBase::OnWaitDialogInit ) ); - -} +/////////////////////////////////////////////////////////////////////////// +// C++ code generated with wxFormBuilder (version Jun 5 2014) +// http://www.wxformbuilder.org/ +// +// PLEASE DO "NOT" EDIT THIS FILE! +/////////////////////////////////////////////////////////////////////////// + +#include "System.h" + +#include "Forms.h" + +/////////////////////////////////////////////////////////////////////////// +using namespace VeraCrypt; + +MainFrameBase::MainFrameBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxSize( -1,496 ), wxDefaultSize ); + + MainMenuBar = new wxMenuBar( 0 ); + VolumesMenu = new wxMenu(); + wxMenuItem* CreateNewVolumeMenuItem; + CreateNewVolumeMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Create New Volume...") ) , wxEmptyString, wxITEM_NORMAL ); + VolumesMenu->Append( CreateNewVolumeMenuItem ); + + VolumesMenu->AppendSeparator(); + + MountVolumeMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Mount Volume") ) , wxEmptyString, wxITEM_NORMAL ); + VolumesMenu->Append( MountVolumeMenuItem ); + + wxMenuItem* AutoMountDevicesMenuItem; + AutoMountDevicesMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Auto-Mount All Device-Hosted Volumes") ) , wxEmptyString, wxITEM_NORMAL ); + VolumesMenu->Append( AutoMountDevicesMenuItem ); + + VolumesMenu->AppendSeparator(); + + DismountVolumeMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Dismount Volume") ) , wxEmptyString, wxITEM_NORMAL ); + VolumesMenu->Append( DismountVolumeMenuItem ); + + DismountAllMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Dismount All Mounted Volumes") ) , wxEmptyString, wxITEM_NORMAL ); + VolumesMenu->Append( DismountAllMenuItem ); + + VolumesMenu->AppendSeparator(); + + wxMenuItem* ChangePasswordMenuItem; + ChangePasswordMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Change Volume Password...") ) , wxEmptyString, wxITEM_NORMAL ); + VolumesMenu->Append( ChangePasswordMenuItem ); + + wxMenuItem* ChangePkcs5PrfMenuItem; + ChangePkcs5PrfMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Change Header Key Derivation Algorithm...") ) , wxEmptyString, wxITEM_NORMAL ); + VolumesMenu->Append( ChangePkcs5PrfMenuItem ); + + wxMenuItem* ChangeKeyfilesMenuItem; + ChangeKeyfilesMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Add/Remove Keyfiles to/from Volume...") ) , wxEmptyString, wxITEM_NORMAL ); + VolumesMenu->Append( ChangeKeyfilesMenuItem ); + + wxMenuItem* RemoveKeyfilesMenuItem; + RemoveKeyfilesMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Remove All Keyfiles from Volume...") ) , wxEmptyString, wxITEM_NORMAL ); + VolumesMenu->Append( RemoveKeyfilesMenuItem ); + + VolumesMenu->AppendSeparator(); + + VolumePropertiesMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Volume Properties...") ) , wxEmptyString, wxITEM_NORMAL ); + VolumesMenu->Append( VolumePropertiesMenuItem ); + + MainMenuBar->Append( VolumesMenu, _("&Volumes") ); + + FavoritesMenu = new wxMenu(); + AddToFavoritesMenuItem = new wxMenuItem( FavoritesMenu, wxID_ANY, wxString( _("Add Selected Volume to Favorites...") ) , wxEmptyString, wxITEM_NORMAL ); + FavoritesMenu->Append( AddToFavoritesMenuItem ); + + AddAllMountedToFavoritesMenuItem = new wxMenuItem( FavoritesMenu, wxID_ANY, wxString( _("Add All Mounted Volumes to Favorites...") ) , wxEmptyString, wxITEM_NORMAL ); + FavoritesMenu->Append( AddAllMountedToFavoritesMenuItem ); + + wxMenuItem* OrganizeFavoritesMenuItem; + OrganizeFavoritesMenuItem = new wxMenuItem( FavoritesMenu, wxID_ANY, wxString( _("Organize Favorite Volumes...") ) , wxEmptyString, wxITEM_NORMAL ); + FavoritesMenu->Append( OrganizeFavoritesMenuItem ); + + FavoritesMenu->AppendSeparator(); + + wxMenuItem* MountAllFavoritesMenuItem; + MountAllFavoritesMenuItem = new wxMenuItem( FavoritesMenu, wxID_ANY, wxString( _("Mount Favorite Volumes") ) , wxEmptyString, wxITEM_NORMAL ); + FavoritesMenu->Append( MountAllFavoritesMenuItem ); + + FavoritesMenu->AppendSeparator(); + + MainMenuBar->Append( FavoritesMenu, _("&Favorites") ); + + ToolsMenu = new wxMenu(); + wxMenuItem* BenchmarkMenuItem; + BenchmarkMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Benchmark...") ) , wxEmptyString, wxITEM_NORMAL ); + ToolsMenu->Append( BenchmarkMenuItem ); + + wxMenuItem* EncryptionTestMenuItem; + EncryptionTestMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Test Vectors...") ) , wxEmptyString, wxITEM_NORMAL ); + ToolsMenu->Append( EncryptionTestMenuItem ); + + ToolsMenu->AppendSeparator(); + + wxMenuItem* VolumeCreationWizardMenuItem; + VolumeCreationWizardMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Volume Creation Wizard") ) , wxEmptyString, wxITEM_NORMAL ); + ToolsMenu->Append( VolumeCreationWizardMenuItem ); + + ToolsMenu->AppendSeparator(); + + BackupVolumeHeadersMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Backup Volume Header...") ) , wxEmptyString, wxITEM_NORMAL ); + ToolsMenu->Append( BackupVolumeHeadersMenuItem ); + + RestoreVolumeHeaderMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Restore Volume Header...") ) , wxEmptyString, wxITEM_NORMAL ); + ToolsMenu->Append( RestoreVolumeHeaderMenuItem ); + + ToolsMenu->AppendSeparator(); + + wxMenuItem* CreateKeyfileMenuItem; + CreateKeyfileMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Keyfile Generator") ) , wxEmptyString, wxITEM_NORMAL ); + ToolsMenu->Append( CreateKeyfileMenuItem ); + + wxMenuItem* ManageSecurityTokenKeyfilesMenuItem; + ManageSecurityTokenKeyfilesMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Manage Security Token Keyfiles...") ) , wxEmptyString, wxITEM_NORMAL ); + ToolsMenu->Append( ManageSecurityTokenKeyfilesMenuItem ); + + wxMenuItem* CloseAllSecurityTokenSessionsMenuItem; + CloseAllSecurityTokenSessionsMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Close All Security Token Sessions") ) , wxEmptyString, wxITEM_NORMAL ); + ToolsMenu->Append( CloseAllSecurityTokenSessionsMenuItem ); + + ToolsMenu->AppendSeparator(); + + WipeCachedPasswordsMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Wipe Cached Passwords") ) , wxEmptyString, wxITEM_NORMAL ); + ToolsMenu->Append( WipeCachedPasswordsMenuItem ); + + MainMenuBar->Append( ToolsMenu, _("T&ools") ); + + SettingsMenu = new wxMenu(); + HotkeysMenuItem = new wxMenuItem( SettingsMenu, wxID_ANY, wxString( _("Hotkeys...") ) , wxEmptyString, wxITEM_NORMAL ); + SettingsMenu->Append( HotkeysMenuItem ); + + wxMenuItem* DefaultKeyfilesMenuItem; + DefaultKeyfilesMenuItem = new wxMenuItem( SettingsMenu, wxID_ANY, wxString( _("Default Keyfiles...") ) , wxEmptyString, wxITEM_NORMAL ); + SettingsMenu->Append( DefaultKeyfilesMenuItem ); + + wxMenuItem* DefaultMountParametersMenuItem; + DefaultMountParametersMenuItem = new wxMenuItem( SettingsMenu, wxID_ANY, wxString( _("Default Mount Parameters...") ) , wxEmptyString, wxITEM_NORMAL ); + SettingsMenu->Append( DefaultMountParametersMenuItem ); + + wxMenuItem* SecurityTokenPreferencesMenuItem; + SecurityTokenPreferencesMenuItem = new wxMenuItem( SettingsMenu, wxID_ANY, wxString( _("Security Tokens...") ) , wxEmptyString, wxITEM_NORMAL ); + SettingsMenu->Append( SecurityTokenPreferencesMenuItem ); + + SettingsMenu->AppendSeparator(); + + PreferencesMenuItem = new wxMenuItem( SettingsMenu, wxID_PREFERENCES, wxString( _("&Preferences...") ) , wxEmptyString, wxITEM_NORMAL ); + SettingsMenu->Append( PreferencesMenuItem ); + + MainMenuBar->Append( SettingsMenu, _("Settin&gs") ); + + HelpMenu = new wxMenu(); + wxMenuItem* UserGuideMenuItem; + UserGuideMenuItem = new wxMenuItem( HelpMenu, wxID_HELP, wxString( _("User's Guide") ) , wxEmptyString, wxITEM_NORMAL ); + HelpMenu->Append( UserGuideMenuItem ); + + wxMenuItem* OnlineHelpMenuItem; + OnlineHelpMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Online Help") ) , wxEmptyString, wxITEM_NORMAL ); + HelpMenu->Append( OnlineHelpMenuItem ); + + wxMenuItem* BeginnersTutorialMenuItem; + BeginnersTutorialMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Beginner's Tutorial") ) , wxEmptyString, wxITEM_NORMAL ); + HelpMenu->Append( BeginnersTutorialMenuItem ); + + wxMenuItem* FaqMenuItem; + FaqMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Frequently Asked Questions") ) , wxEmptyString, wxITEM_NORMAL ); + HelpMenu->Append( FaqMenuItem ); + + HelpMenu->AppendSeparator(); + + wxMenuItem* WebsiteMenuItem; + WebsiteMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("VeraCrypt Website") ) , wxEmptyString, wxITEM_NORMAL ); + HelpMenu->Append( WebsiteMenuItem ); + + wxMenuItem* DownloadsMenuItem; + DownloadsMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Downloads") ) , wxEmptyString, wxITEM_NORMAL ); + HelpMenu->Append( DownloadsMenuItem ); + + wxMenuItem* NewsMenuItem; + NewsMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("News") ) , wxEmptyString, wxITEM_NORMAL ); + HelpMenu->Append( NewsMenuItem ); + + wxMenuItem* VersionHistoryMenuItem; + VersionHistoryMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Version History") ) , wxEmptyString, wxITEM_NORMAL ); + HelpMenu->Append( VersionHistoryMenuItem ); + + HelpMenu->AppendSeparator(); + + wxMenuItem* DonateMenuItem; + DonateMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Donate") ) , wxEmptyString, wxITEM_NORMAL ); + HelpMenu->Append( DonateMenuItem ); + + wxMenuItem* ContactMenuItem; + ContactMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Contact") ) , wxEmptyString, wxITEM_NORMAL ); + HelpMenu->Append( ContactMenuItem ); + + wxMenuItem* LegalNoticesMenuItem; + LegalNoticesMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Legal Notices") ) , wxEmptyString, wxITEM_NORMAL ); + HelpMenu->Append( LegalNoticesMenuItem ); + + wxMenuItem* AboutMenuItem; + AboutMenuItem = new wxMenuItem( HelpMenu, wxID_ABOUT, wxString( _("About") ) , wxEmptyString, wxITEM_NORMAL ); + HelpMenu->Append( AboutMenuItem ); + + MainMenuBar->Append( HelpMenu, _("&Help") ); + + this->SetMenuBar( MainMenuBar ); + + wxBoxSizer* bSizer1; + bSizer1 = new wxBoxSizer( wxVERTICAL ); + + MainPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + wxBoxSizer* bSizer2; + bSizer2 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer48; + bSizer48 = new wxBoxSizer( wxVERTICAL ); + + wxStaticBoxSizer* sbSizer1; + sbSizer1 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); + + SlotListCtrl = new wxListCtrl( MainPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES|wxSUNKEN_BORDER ); + sbSizer1->Add( SlotListCtrl, 1, wxALL|wxEXPAND, 5 ); + + + bSizer48->Add( sbSizer1, 1, wxEXPAND, 5 ); + + LowStaticBoxSizer = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); + + HigherButtonSizer = new wxBoxSizer( wxVERTICAL ); + + + LowStaticBoxSizer->Add( HigherButtonSizer, 0, wxEXPAND|wxTOP, 2 ); + + wxGridSizer* gSizer1; + gSizer1 = new wxGridSizer( 1, 3, 0, 0 ); + + wxBoxSizer* bSizer17; + bSizer17 = new wxBoxSizer( wxVERTICAL ); + + bSizer17->SetMinSize( wxSize( 138,34 ) ); + CreateVolumeButton = new wxButton( MainPanel, wxID_ANY, _("&Create Volume"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer17->Add( CreateVolumeButton, 1, wxALL|wxEXPAND, 5 ); + + + gSizer1->Add( bSizer17, 0, 0, 5 ); + + wxBoxSizer* bSizer18; + bSizer18 = new wxBoxSizer( wxVERTICAL ); + + bSizer18->SetMinSize( wxSize( 138,34 ) ); + VolumePropertiesButton = new wxButton( MainPanel, wxID_ANY, _("&Volume Properties..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer18->Add( VolumePropertiesButton, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxEXPAND, 5 ); + + + gSizer1->Add( bSizer18, 0, wxALIGN_CENTER_HORIZONTAL, 5 ); + + wxBoxSizer* bSizer19; + bSizer19 = new wxBoxSizer( wxVERTICAL ); + + bSizer19->SetMinSize( wxSize( 138,34 ) ); + WipeCacheButton = new wxButton( MainPanel, wxID_ANY, _("&Wipe Cache"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer19->Add( WipeCacheButton, 1, wxALL|wxALIGN_RIGHT|wxEXPAND, 5 ); + + + gSizer1->Add( bSizer19, 0, wxALIGN_RIGHT, 5 ); + + + LowStaticBoxSizer->Add( gSizer1, 0, wxEXPAND|wxRIGHT|wxLEFT, 5 ); + + + LowStaticBoxSizer->Add( 0, 0, 0, 0, 5 ); + + VolumeStaticBoxSizer = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, _("Volume") ), wxVERTICAL ); + + VolumeGridBagSizer = new wxGridBagSizer( 0, 0 ); + VolumeGridBagSizer->SetFlexibleDirection( wxBOTH ); + VolumeGridBagSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); + + LogoBitmap = new wxStaticBitmap( MainPanel, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER ); + LogoBitmap->SetMinSize( wxSize( 42,52 ) ); + + VolumeGridBagSizer->Add( LogoBitmap, wxGBPosition( 0, 0 ), wxGBSpan( 2, 1 ), wxALIGN_CENTER_VERTICAL|wxALL, 5 ); + + VolumePathComboBox = new wxComboBox( MainPanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_DROPDOWN ); + VolumeGridBagSizer->Add( VolumePathComboBox, wxGBPosition( 0, 1 ), wxGBSpan( 1, 2 ), wxEXPAND|wxALL, 5 ); + + wxBoxSizer* bSizer191; + bSizer191 = new wxBoxSizer( wxVERTICAL ); + + bSizer191->SetMinSize( wxSize( 138,34 ) ); + SelectFileButton = new wxButton( MainPanel, wxID_ANY, _("Select &File..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer191->Add( SelectFileButton, 1, wxALL|wxEXPAND, 5 ); + + + VolumeGridBagSizer->Add( bSizer191, wxGBPosition( 0, 3 ), wxGBSpan( 1, 1 ), wxEXPAND, 5 ); + + NoHistoryCheckBox = new wxCheckBox( MainPanel, wxID_ANY, _("&Never save history"), wxDefaultPosition, wxDefaultSize, 0 ); + VolumeGridBagSizer->Add( NoHistoryCheckBox, wxGBPosition( 1, 1 ), wxGBSpan( 1, 1 ), wxBOTTOM|wxRIGHT|wxLEFT, 5 ); + + wxBoxSizer* bSizer20; + bSizer20 = new wxBoxSizer( wxVERTICAL ); + + bSizer20->SetMinSize( wxSize( 138,34 ) ); + VolumeToolsButton = new wxButton( MainPanel, wxID_ANY, _("Volume &Tools..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer20->Add( VolumeToolsButton, 1, wxALL|wxEXPAND, 5 ); + + + VolumeGridBagSizer->Add( bSizer20, wxGBPosition( 1, 2 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT, 5 ); + + wxBoxSizer* bSizer21; + bSizer21 = new wxBoxSizer( wxVERTICAL ); + + bSizer21->SetMinSize( wxSize( 138,34 ) ); + SelectDeviceButton = new wxButton( MainPanel, wxID_ANY, _("Select D&evice..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer21->Add( SelectDeviceButton, 1, wxEXPAND|wxALL, 5 ); + + + VolumeGridBagSizer->Add( bSizer21, wxGBPosition( 1, 3 ), wxGBSpan( 1, 1 ), wxEXPAND, 5 ); + + + VolumeGridBagSizer->AddGrowableCol( 1 ); + VolumeGridBagSizer->AddGrowableRow( 0 ); + + VolumeStaticBoxSizer->Add( VolumeGridBagSizer, 1, wxEXPAND|wxALL, 4 ); + + + LowStaticBoxSizer->Add( VolumeStaticBoxSizer, 1, wxEXPAND, 5 ); + + + LowStaticBoxSizer->Add( 0, 0, 0, 0, 5 ); + + wxGridSizer* gSizer2; + gSizer2 = new wxGridSizer( 1, 4, 0, 0 ); + + wxStaticBoxSizer* sbSizer4; + sbSizer4 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); + + sbSizer4->SetMinSize( wxSize( 139,-1 ) ); + VolumeButton = new wxButton( MainPanel, wxID_ANY, _("&Mount"), wxDefaultPosition, wxDefaultSize, 0 ); + VolumeButton->SetDefault(); + VolumeButton->SetMinSize( wxSize( -1,32 ) ); + + sbSizer4->Add( VolumeButton, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP, 2 ); + + + gSizer2->Add( sbSizer4, 1, wxEXPAND, 0 ); + + wxStaticBoxSizer* sbSizer41; + sbSizer41 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); + + MountAllDevicesButton = new wxButton( MainPanel, wxID_ANY, _("&Auto-Mount Devices"), wxDefaultPosition, wxDefaultSize, 0 ); + MountAllDevicesButton->SetMinSize( wxSize( -1,32 ) ); + + sbSizer41->Add( MountAllDevicesButton, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP, 2 ); + + + gSizer2->Add( sbSizer41, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND, 5 ); + + wxStaticBoxSizer* sbSizer42; + sbSizer42 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); + + DismountAllButton = new wxButton( MainPanel, wxID_ANY, _("Di&smount All"), wxDefaultPosition, wxDefaultSize, 0 ); + DismountAllButton->SetMinSize( wxSize( -1,32 ) ); + + sbSizer42->Add( DismountAllButton, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP, 2 ); + + + gSizer2->Add( sbSizer42, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND, 5 ); + + wxStaticBoxSizer* sbSizer43; + sbSizer43 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); + + ExitButton = new wxButton( MainPanel, wxID_ANY, _("E&xit"), wxDefaultPosition, wxDefaultSize, 0 ); + ExitButton->SetMinSize( wxSize( -1,32 ) ); + + sbSizer43->Add( ExitButton, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP, 2 ); + + + gSizer2->Add( sbSizer43, 1, wxALIGN_RIGHT|wxEXPAND, 5 ); + + + LowStaticBoxSizer->Add( gSizer2, 0, wxEXPAND, 5 ); + + + bSizer48->Add( LowStaticBoxSizer, 0, wxEXPAND, 5 ); + + + bSizer2->Add( bSizer48, 1, wxEXPAND, 5 ); + + + MainPanel->SetSizer( bSizer2 ); + MainPanel->Layout(); + bSizer2->Fit( MainPanel ); + bSizer1->Add( MainPanel, 1, wxEXPAND, 0 ); + + + this->SetSizer( bSizer1 ); + this->Layout(); + bSizer1->Fit( this ); + + this->Centre( wxBOTH ); + + // Connect Events + this->Connect( wxEVT_ACTIVATE, wxActivateEventHandler( MainFrameBase::OnActivate ) ); + this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( MainFrameBase::OnClose ) ); + this->Connect( CreateNewVolumeMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCreateVolumeButtonClick ) ); + this->Connect( MountVolumeMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnMountVolumeMenuItemSelected ) ); + this->Connect( AutoMountDevicesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnMountAllDevicesButtonClick ) ); + this->Connect( DismountVolumeMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDismountVolumeMenuItemSelected ) ); + this->Connect( DismountAllMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDismountAllButtonClick ) ); + this->Connect( ChangePasswordMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnChangePasswordMenuItemSelected ) ); + this->Connect( ChangePkcs5PrfMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnChangePkcs5PrfMenuItemSelected ) ); + this->Connect( ChangeKeyfilesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnChangeKeyfilesMenuItemSelected ) ); + this->Connect( RemoveKeyfilesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnRemoveKeyfilesMenuItemSelected ) ); + this->Connect( VolumePropertiesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnVolumePropertiesButtonClick ) ); + this->Connect( AddToFavoritesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnAddToFavoritesMenuItemSelected ) ); + this->Connect( AddAllMountedToFavoritesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnAddAllMountedToFavoritesMenuItemSelected ) ); + this->Connect( OrganizeFavoritesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnOrganizeFavoritesMenuItemSelected ) ); + this->Connect( MountAllFavoritesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnMountAllFavoritesMenuItemSelected ) ); + this->Connect( BenchmarkMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnBenchmarkMenuItemSelected ) ); + this->Connect( EncryptionTestMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnEncryptionTestMenuItemSelected ) ); + this->Connect( VolumeCreationWizardMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCreateVolumeButtonClick ) ); + this->Connect( BackupVolumeHeadersMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnBackupVolumeHeadersMenuItemSelected ) ); + this->Connect( RestoreVolumeHeaderMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnRestoreVolumeHeaderMenuItemSelected ) ); + this->Connect( CreateKeyfileMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCreateKeyfileMenuItemSelected ) ); + this->Connect( ManageSecurityTokenKeyfilesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnManageSecurityTokenKeyfilesMenuItemSelected ) ); + this->Connect( CloseAllSecurityTokenSessionsMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCloseAllSecurityTokenSessionsMenuItemSelected ) ); + this->Connect( WipeCachedPasswordsMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnWipeCacheButtonClick ) ); + this->Connect( HotkeysMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnHotkeysMenuItemSelected ) ); + this->Connect( DefaultKeyfilesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDefaultKeyfilesMenuItemSelected ) ); + this->Connect( DefaultMountParametersMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDefaultMountParametersMenuItemSelected ) ); + this->Connect( SecurityTokenPreferencesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnSecurityTokenPreferencesMenuItemSelected ) ); + this->Connect( PreferencesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnPreferencesMenuItemSelected ) ); + this->Connect( UserGuideMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnUserGuideMenuItemSelected ) ); + this->Connect( OnlineHelpMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnOnlineHelpMenuItemSelected ) ); + this->Connect( BeginnersTutorialMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnBeginnersTutorialMenuItemSelected ) ); + this->Connect( FaqMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnFaqMenuItemSelected ) ); + this->Connect( WebsiteMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnWebsiteMenuItemSelected ) ); + this->Connect( DownloadsMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDownloadsMenuItemSelected ) ); + this->Connect( NewsMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnNewsMenuItemSelected ) ); + this->Connect( VersionHistoryMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnVersionHistoryMenuItemSelected ) ); + this->Connect( DonateMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDonateMenuItemSelected ) ); + this->Connect( ContactMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnContactMenuItemSelected ) ); + this->Connect( LegalNoticesMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnLegalNoticesMenuItemSelected ) ); + this->Connect( AboutMenuItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnAboutMenuItemSelected ) ); + SlotListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( MainFrameBase::OnListItemActivated ), NULL, this ); + SlotListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( MainFrameBase::OnListItemDeselected ), NULL, this ); + SlotListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, wxListEventHandler( MainFrameBase::OnListItemRightClick ), NULL, this ); + SlotListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( MainFrameBase::OnListItemSelected ), NULL, this ); + CreateVolumeButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnCreateVolumeButtonClick ), NULL, this ); + VolumePropertiesButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnVolumePropertiesButtonClick ), NULL, this ); + WipeCacheButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnWipeCacheButtonClick ), NULL, this ); + LogoBitmap->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( MainFrameBase::OnLogoBitmapClick ), NULL, this ); + SelectFileButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnSelectFileButtonClick ), NULL, this ); + NoHistoryCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MainFrameBase::OnNoHistoryCheckBoxClick ), NULL, this ); + VolumeToolsButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnVolumeToolsButtonClick ), NULL, this ); + SelectDeviceButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnSelectDeviceButtonClick ), NULL, this ); + VolumeButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnVolumeButtonClick ), NULL, this ); + MountAllDevicesButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnMountAllDevicesButtonClick ), NULL, this ); + DismountAllButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnDismountAllButtonClick ), NULL, this ); + ExitButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnExitButtonClick ), NULL, this ); +} + +MainFrameBase::~MainFrameBase() +{ + // Disconnect Events + this->Disconnect( wxEVT_ACTIVATE, wxActivateEventHandler( MainFrameBase::OnActivate ) ); + this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( MainFrameBase::OnClose ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCreateVolumeButtonClick ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnMountVolumeMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnMountAllDevicesButtonClick ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDismountVolumeMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDismountAllButtonClick ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnChangePasswordMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnChangePkcs5PrfMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnChangeKeyfilesMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnRemoveKeyfilesMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnVolumePropertiesButtonClick ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnAddToFavoritesMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnAddAllMountedToFavoritesMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnOrganizeFavoritesMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnMountAllFavoritesMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnBenchmarkMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnEncryptionTestMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCreateVolumeButtonClick ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnBackupVolumeHeadersMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnRestoreVolumeHeaderMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCreateKeyfileMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnManageSecurityTokenKeyfilesMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnCloseAllSecurityTokenSessionsMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnWipeCacheButtonClick ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnHotkeysMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDefaultKeyfilesMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDefaultMountParametersMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnSecurityTokenPreferencesMenuItemSelected ) ); + this->Disconnect( wxID_PREFERENCES, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnPreferencesMenuItemSelected ) ); + this->Disconnect( wxID_HELP, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnUserGuideMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnOnlineHelpMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnBeginnersTutorialMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnFaqMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnWebsiteMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDownloadsMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnNewsMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnVersionHistoryMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnDonateMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnContactMenuItemSelected ) ); + this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnLegalNoticesMenuItemSelected ) ); + this->Disconnect( wxID_ABOUT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrameBase::OnAboutMenuItemSelected ) ); + SlotListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( MainFrameBase::OnListItemActivated ), NULL, this ); + SlotListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( MainFrameBase::OnListItemDeselected ), NULL, this ); + SlotListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, wxListEventHandler( MainFrameBase::OnListItemRightClick ), NULL, this ); + SlotListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( MainFrameBase::OnListItemSelected ), NULL, this ); + CreateVolumeButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnCreateVolumeButtonClick ), NULL, this ); + VolumePropertiesButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnVolumePropertiesButtonClick ), NULL, this ); + WipeCacheButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnWipeCacheButtonClick ), NULL, this ); + LogoBitmap->Disconnect( wxEVT_LEFT_DOWN, wxMouseEventHandler( MainFrameBase::OnLogoBitmapClick ), NULL, this ); + SelectFileButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnSelectFileButtonClick ), NULL, this ); + NoHistoryCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MainFrameBase::OnNoHistoryCheckBoxClick ), NULL, this ); + VolumeToolsButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnVolumeToolsButtonClick ), NULL, this ); + SelectDeviceButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnSelectDeviceButtonClick ), NULL, this ); + VolumeButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnVolumeButtonClick ), NULL, this ); + MountAllDevicesButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnMountAllDevicesButtonClick ), NULL, this ); + DismountAllButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnDismountAllButtonClick ), NULL, this ); + ExitButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnExitButtonClick ), NULL, this ); + +} + +WizardFrameBase::WizardFrameBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxSize( 800,500 ), wxDefaultSize ); + + MainSizer = new wxBoxSizer( wxVERTICAL ); + + MainPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + wxBoxSizer* bSizer63; + bSizer63 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer64; + bSizer64 = new wxBoxSizer( wxVERTICAL ); + + wxStaticBoxSizer* sbSizer27; + sbSizer27 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxHORIZONTAL ); + + WizardBitmap = new wxStaticBitmap( MainPanel, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer27->Add( WizardBitmap, 0, wxALL|wxEXPAND, 5 ); + + wxBoxSizer* bSizer66; + bSizer66 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer126; + bSizer126 = new wxBoxSizer( wxHORIZONTAL ); + + PageTitleStaticText = new wxStaticText( MainPanel, wxID_ANY, _("Page Title"), wxDefaultPosition, wxDefaultSize, 0 ); + PageTitleStaticText->Wrap( -1 ); + PageTitleStaticText->SetFont( wxFont( 16, 70, 90, 90, false, wxT("Times New Roman") ) ); + + bSizer126->Add( PageTitleStaticText, 0, wxALL, 5 ); + + + bSizer66->Add( bSizer126, 0, wxLEFT, 5 ); + + PageSizer = new wxBoxSizer( wxVERTICAL ); + + + bSizer66->Add( PageSizer, 1, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + + sbSizer27->Add( bSizer66, 1, wxEXPAND|wxLEFT, 5 ); + + + bSizer64->Add( sbSizer27, 1, wxEXPAND|wxRIGHT|wxLEFT, 5 ); + + wxBoxSizer* bSizer70; + bSizer70 = new wxBoxSizer( wxHORIZONTAL ); + + + bSizer70->Add( 0, 0, 1, wxEXPAND, 5 ); + + HelpButton = new wxButton( MainPanel, wxID_HELP, _("&Help"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer70->Add( HelpButton, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); + + + bSizer70->Add( 0, 0, 0, wxLEFT|wxALIGN_RIGHT, 5 ); + + PreviousButton = new wxButton( MainPanel, wxID_ANY, _("< &Prev"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer70->Add( PreviousButton, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); + + NextButton = new wxButton( MainPanel, wxID_ANY, _("&Next >"), wxDefaultPosition, wxDefaultSize, 0|wxWANTS_CHARS ); + NextButton->SetDefault(); + bSizer70->Add( NextButton, 0, wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); + + + bSizer70->Add( 0, 0, 0, wxLEFT|wxALIGN_RIGHT, 5 ); + + CancelButton = new wxButton( MainPanel, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer70->Add( CancelButton, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); + + + bSizer64->Add( bSizer70, 0, wxEXPAND|wxALIGN_RIGHT|wxALL, 5 ); + + + bSizer63->Add( bSizer64, 1, wxEXPAND, 5 ); + + + MainPanel->SetSizer( bSizer63 ); + MainPanel->Layout(); + bSizer63->Fit( MainPanel ); + MainSizer->Add( MainPanel, 1, wxEXPAND, 5 ); + + + this->SetSizer( MainSizer ); + this->Layout(); + MainSizer->Fit( this ); + + // Connect Events + this->Connect( wxEVT_ACTIVATE, wxActivateEventHandler( WizardFrameBase::OnActivate ) ); + this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( WizardFrameBase::OnClose ) ); + MainPanel->Connect( wxEVT_MOTION, wxMouseEventHandler( WizardFrameBase::OnMouseMotion ), NULL, this ); + HelpButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnHelpButtonClick ), NULL, this ); + PreviousButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnPreviousButtonClick ), NULL, this ); + NextButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnNextButtonClick ), NULL, this ); + CancelButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnCancelButtonClick ), NULL, this ); +} + +WizardFrameBase::~WizardFrameBase() +{ + // Disconnect Events + this->Disconnect( wxEVT_ACTIVATE, wxActivateEventHandler( WizardFrameBase::OnActivate ) ); + this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( WizardFrameBase::OnClose ) ); + MainPanel->Disconnect( wxEVT_MOTION, wxMouseEventHandler( WizardFrameBase::OnMouseMotion ), NULL, this ); + HelpButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnHelpButtonClick ), NULL, this ); + PreviousButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnPreviousButtonClick ), NULL, this ); + NextButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnNextButtonClick ), NULL, this ); + CancelButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnCancelButtonClick ), NULL, this ); + +} + +AboutDialogBase::AboutDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + + wxBoxSizer* bSizer116; + bSizer116 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer117; + bSizer117 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer120; + bSizer120 = new wxBoxSizer( wxVERTICAL ); + + bSizer120->SetMinSize( wxSize( -1,78 ) ); + m_panel14 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + m_panel14->SetBackgroundColour( wxColour( 10, 108, 206 ) ); + + wxBoxSizer* bSizer121; + bSizer121 = new wxBoxSizer( wxVERTICAL ); + + + bSizer121->Add( 0, 0, 1, wxEXPAND|wxALL, 5 ); + + wxBoxSizer* bSizer122; + bSizer122 = new wxBoxSizer( wxVERTICAL ); + + LogoBitmap = new wxStaticBitmap( m_panel14, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxDefaultSize, 0 ); + bSizer122->Add( LogoBitmap, 0, wxALL, 10 ); + + + bSizer121->Add( bSizer122, 0, wxEXPAND|wxLEFT, 8 ); + + + m_panel14->SetSizer( bSizer121 ); + m_panel14->Layout(); + bSizer121->Fit( m_panel14 ); + bSizer120->Add( m_panel14, 1, wxEXPAND, 5 ); + + + bSizer117->Add( bSizer120, 0, wxEXPAND, 5 ); + + wxBoxSizer* bSizer118; + bSizer118 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer123; + bSizer123 = new wxBoxSizer( wxVERTICAL ); + + VersionStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + VersionStaticText->Wrap( -1 ); + bSizer123->Add( VersionStaticText, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); + + + bSizer123->Add( 0, 0, 0, wxTOP, 3 ); + + CopyrightStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + CopyrightStaticText->Wrap( -1 ); + bSizer123->Add( CopyrightStaticText, 0, wxBOTTOM|wxRIGHT|wxLEFT, 5 ); + + + bSizer123->Add( 0, 0, 0, wxTOP, 3 ); + + WebsiteHyperlink = new wxHyperlinkCtrl( this, wxID_ANY, wxEmptyString, wxT("."), wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); + + WebsiteHyperlink->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + WebsiteHyperlink->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + WebsiteHyperlink->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + bSizer123->Add( WebsiteHyperlink, 0, wxALL, 5 ); + + + bSizer118->Add( bSizer123, 1, wxEXPAND|wxLEFT, 5 ); + + + bSizer117->Add( bSizer118, 1, wxALL|wxEXPAND, 15 ); + + m_staticline3 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); + bSizer117->Add( m_staticline3, 0, wxEXPAND|wxBOTTOM, 5 ); + + CreditsTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY|wxSUNKEN_BORDER ); + bSizer117->Add( CreditsTextCtrl, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 10 ); + + + bSizer117->Add( 0, 0, 0, wxTOP, 5 ); + + m_staticline4 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); + bSizer117->Add( m_staticline4, 0, wxEXPAND|wxTOP|wxBOTTOM, 3 ); + + m_staticline5 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); + bSizer117->Add( m_staticline5, 0, wxEXPAND|wxBOTTOM, 5 ); + + wxBoxSizer* bSizer119; + bSizer119 = new wxBoxSizer( wxHORIZONTAL ); + + + bSizer119->Add( 0, 0, 1, wxEXPAND|wxALL, 5 ); + + wxButton* OKButton; + OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); + OKButton->SetDefault(); + bSizer119->Add( OKButton, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + + bSizer119->Add( 0, 0, 0, wxLEFT, 5 ); + + + bSizer117->Add( bSizer119, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 6 ); + + + bSizer116->Add( bSizer117, 1, wxEXPAND, 5 ); + + + this->SetSizer( bSizer116 ); + this->Layout(); + bSizer116->Fit( this ); + + // Connect Events + WebsiteHyperlink->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( AboutDialogBase::OnWebsiteHyperlinkClick ), NULL, this ); +} + +AboutDialogBase::~AboutDialogBase() +{ + // Disconnect Events + WebsiteHyperlink->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( AboutDialogBase::OnWebsiteHyperlinkClick ), NULL, this ); + +} + +BenchmarkDialogBase::BenchmarkDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + + wxBoxSizer* bSizer153; + bSizer153 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer154; + bSizer154 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer155; + bSizer155 = new wxBoxSizer( wxHORIZONTAL ); + + wxStaticText* m_staticText54; + m_staticText54 = new wxStaticText( this, wxID_ANY, _("Buffer Size:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText54->Wrap( -1 ); + bSizer155->Add( m_staticText54, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + wxArrayString BufferSizeChoiceChoices; + BufferSizeChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, BufferSizeChoiceChoices, 0 ); + BufferSizeChoice->SetSelection( 0 ); + bSizer155->Add( BufferSizeChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + + bSizer154->Add( bSizer155, 0, wxEXPAND, 5 ); + + wxStaticLine* m_staticline6; + m_staticline6 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); + bSizer154->Add( m_staticline6, 0, wxEXPAND | wxALL, 5 ); + + wxBoxSizer* bSizer156; + bSizer156 = new wxBoxSizer( wxHORIZONTAL ); + + BenchmarkListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxSUNKEN_BORDER ); + bSizer156->Add( BenchmarkListCtrl, 1, wxALL|wxEXPAND, 5 ); + + RightSizer = new wxBoxSizer( wxVERTICAL ); + + BenchmarkButton = new wxButton( this, wxID_OK, _("Benchmark"), wxDefaultPosition, wxDefaultSize, 0 ); + BenchmarkButton->SetDefault(); + RightSizer->Add( BenchmarkButton, 0, wxALL|wxEXPAND, 5 ); + + wxButton* CancelButton; + CancelButton = new wxButton( this, wxID_CANCEL, _("Close"), wxDefaultPosition, wxDefaultSize, 0 ); + RightSizer->Add( CancelButton, 0, wxALL|wxEXPAND, 5 ); + + + RightSizer->Add( 0, 0, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 ); + + BenchmarkNoteStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + BenchmarkNoteStaticText->Wrap( -1 ); + RightSizer->Add( BenchmarkNoteStaticText, 1, wxALL|wxEXPAND, 5 ); + + + bSizer156->Add( RightSizer, 0, wxEXPAND, 5 ); + + + bSizer154->Add( bSizer156, 1, wxEXPAND, 5 ); + + + bSizer153->Add( bSizer154, 1, wxEXPAND|wxALL, 5 ); + + + this->SetSizer( bSizer153 ); + this->Layout(); + bSizer153->Fit( this ); + + // Connect Events + BenchmarkButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( BenchmarkDialogBase::OnBenchmarkButtonClick ), NULL, this ); +} + +BenchmarkDialogBase::~BenchmarkDialogBase() +{ + // Disconnect Events + BenchmarkButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( BenchmarkDialogBase::OnBenchmarkButtonClick ), NULL, this ); + +} + +ChangePasswordDialogBase::ChangePasswordDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); + + wxBoxSizer* bSizer30; + bSizer30 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer31; + bSizer31 = new wxBoxSizer( wxHORIZONTAL ); + + wxBoxSizer* bSizer32; + bSizer32 = new wxBoxSizer( wxVERTICAL ); + + CurrentSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Current") ), wxVERTICAL ); + + CurrentPasswordPanelSizer = new wxBoxSizer( wxVERTICAL ); + + + CurrentSizer->Add( CurrentPasswordPanelSizer, 0, wxALIGN_LEFT, 5 ); + + + bSizer32->Add( CurrentSizer, 0, wxEXPAND, 5 ); + + NewSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("New") ), wxVERTICAL ); + + NewPasswordPanelSizer = new wxBoxSizer( wxVERTICAL ); + + + NewSizer->Add( NewPasswordPanelSizer, 0, wxALIGN_LEFT, 5 ); + + + bSizer32->Add( NewSizer, 0, wxTOP|wxEXPAND, 5 ); + + + bSizer31->Add( bSizer32, 1, wxEXPAND|wxALL, 5 ); + + wxBoxSizer* bSizer33; + bSizer33 = new wxBoxSizer( wxVERTICAL ); + + OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); + OKButton->SetDefault(); + bSizer33->Add( OKButton, 0, wxALL|wxEXPAND, 5 ); + + CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer33->Add( CancelButton, 0, wxALL|wxEXPAND, 5 ); + + + bSizer31->Add( bSizer33, 0, 0, 5 ); + + + bSizer30->Add( bSizer31, 1, wxEXPAND|wxALL, 5 ); + + + this->SetSizer( bSizer30 ); + this->Layout(); + bSizer30->Fit( this ); + + // Connect Events + OKButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ChangePasswordDialogBase::OnOKButtonClick ), NULL, this ); +} + +ChangePasswordDialogBase::~ChangePasswordDialogBase() +{ + // Disconnect Events + OKButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ChangePasswordDialogBase::OnOKButtonClick ), NULL, this ); + +} + +DeviceSelectionDialogBase::DeviceSelectionDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxSize( -1,-1 ), wxDefaultSize ); + this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); + + wxBoxSizer* bSizer3; + bSizer3 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer4; + bSizer4 = new wxBoxSizer( wxVERTICAL ); + + DeviceListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES|wxSUNKEN_BORDER ); + bSizer4->Add( DeviceListCtrl, 1, wxALL|wxEXPAND, 5 ); + + StdButtons = new wxStdDialogButtonSizer(); + StdButtonsOK = new wxButton( this, wxID_OK ); + StdButtons->AddButton( StdButtonsOK ); + StdButtonsCancel = new wxButton( this, wxID_CANCEL ); + StdButtons->AddButton( StdButtonsCancel ); + StdButtons->Realize(); + + bSizer4->Add( StdButtons, 0, wxEXPAND|wxALL, 5 ); + + + bSizer3->Add( bSizer4, 1, wxEXPAND|wxALL, 5 ); + + + this->SetSizer( bSizer3 ); + this->Layout(); + bSizer3->Fit( this ); + + this->Centre( wxBOTH ); + + // Connect Events + DeviceListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemActivated ), NULL, this ); + DeviceListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemDeselected ), NULL, this ); + DeviceListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemSelected ), NULL, this ); +} + +DeviceSelectionDialogBase::~DeviceSelectionDialogBase() +{ + // Disconnect Events + DeviceListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemActivated ), NULL, this ); + DeviceListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemDeselected ), NULL, this ); + DeviceListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemSelected ), NULL, this ); + +} + +EncryptionTestDialogBase::EncryptionTestDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + + wxBoxSizer* bSizer132; + bSizer132 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer133; + bSizer133 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer134; + bSizer134 = new wxBoxSizer( wxHORIZONTAL ); + + wxStaticText* m_staticText41; + m_staticText41 = new wxStaticText( this, wxID_ANY, _("Encryption algorithm:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText41->Wrap( -1 ); + bSizer134->Add( m_staticText41, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + wxArrayString EncryptionAlgorithmChoiceChoices; + EncryptionAlgorithmChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, EncryptionAlgorithmChoiceChoices, 0 ); + EncryptionAlgorithmChoice->SetSelection( 0 ); + bSizer134->Add( EncryptionAlgorithmChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + XtsModeCheckBox = new wxCheckBox( this, wxID_ANY, _("XTS mode"), wxDefaultPosition, wxDefaultSize, 0 ); + XtsModeCheckBox->SetValue(true); + bSizer134->Add( XtsModeCheckBox, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + + bSizer133->Add( bSizer134, 0, wxALIGN_CENTER_HORIZONTAL, 5 ); + + wxStaticBoxSizer* sbSizer38; + sbSizer38 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Key (hexadecimal)") ), wxVERTICAL ); + + KeyTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + KeyTextCtrl->SetMaxLength( 0 ); + KeyTextCtrl->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier") ) ); + + sbSizer38->Add( KeyTextCtrl, 1, wxALL|wxEXPAND, 5 ); + + wxBoxSizer* bSizer135; + bSizer135 = new wxBoxSizer( wxHORIZONTAL ); + + wxStaticText* m_staticText43; + m_staticText43 = new wxStaticText( this, wxID_ANY, _("Key size:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText43->Wrap( -1 ); + bSizer135->Add( m_staticText43, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); + + KeySizeStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + KeySizeStaticText->Wrap( -1 ); + bSizer135->Add( KeySizeStaticText, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT, 5 ); + + + sbSizer38->Add( bSizer135, 0, wxEXPAND, 5 ); + + + bSizer133->Add( sbSizer38, 0, wxEXPAND|wxALL, 5 ); + + wxStaticBoxSizer* sbSizer39; + sbSizer39 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("XTS mode") ), wxVERTICAL ); + + wxStaticText* m_staticText45; + m_staticText45 = new wxStaticText( this, wxID_ANY, _("Secondary key (hexadecimal)"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText45->Wrap( -1 ); + sbSizer39->Add( m_staticText45, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); + + SecondaryKeyTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + SecondaryKeyTextCtrl->SetMaxLength( 0 ); + SecondaryKeyTextCtrl->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier") ) ); + + sbSizer39->Add( SecondaryKeyTextCtrl, 0, wxEXPAND|wxALL, 5 ); + + wxStaticText* m_staticText46; + m_staticText46 = new wxStaticText( this, wxID_ANY, _("Data unit number (64-bit, data unit size is 512 bytes)"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText46->Wrap( -1 ); + sbSizer39->Add( m_staticText46, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); + + DataUnitNumberTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + DataUnitNumberTextCtrl->SetMaxLength( 0 ); + sbSizer39->Add( DataUnitNumberTextCtrl, 0, wxALL, 5 ); + + wxStaticText* m_staticText47; + m_staticText47 = new wxStaticText( this, wxID_ANY, _("Block number:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText47->Wrap( -1 ); + sbSizer39->Add( m_staticText47, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); + + BlockNumberTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + BlockNumberTextCtrl->SetMaxLength( 0 ); + sbSizer39->Add( BlockNumberTextCtrl, 0, wxALL, 5 ); + + + bSizer133->Add( sbSizer39, 1, wxEXPAND|wxALL, 5 ); + + wxStaticBoxSizer* sbSizer40; + sbSizer40 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Plaintext (hexadecimal)") ), wxVERTICAL ); + + PlainTextTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + PlainTextTextCtrl->SetMaxLength( 0 ); + PlainTextTextCtrl->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier") ) ); + + sbSizer40->Add( PlainTextTextCtrl, 0, wxALL|wxEXPAND, 5 ); + + + bSizer133->Add( sbSizer40, 0, wxEXPAND|wxALL, 5 ); + + wxStaticBoxSizer* sbSizer41; + sbSizer41 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Ciphertext (hexadecimal)") ), wxVERTICAL ); + + CipherTextTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + CipherTextTextCtrl->SetMaxLength( 0 ); + CipherTextTextCtrl->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier") ) ); + + sbSizer41->Add( CipherTextTextCtrl, 0, wxALL|wxEXPAND, 5 ); + + + bSizer133->Add( sbSizer41, 0, wxEXPAND|wxALL, 5 ); + + wxBoxSizer* bSizer136; + bSizer136 = new wxBoxSizer( wxHORIZONTAL ); + + EncryptButton = new wxButton( this, wxID_ANY, _("&Encrypt"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer136->Add( EncryptButton, 0, wxALL, 5 ); + + DecryptButton = new wxButton( this, wxID_ANY, _("&Decrypt"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer136->Add( DecryptButton, 0, wxALL, 5 ); + + AutoTestAllButton = new wxButton( this, wxID_ANY, _("&Auto-Test All"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer136->Add( AutoTestAllButton, 0, wxALL, 5 ); + + ResetButton = new wxButton( this, wxID_ANY, _("&Reset"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer136->Add( ResetButton, 0, wxALL, 5 ); + + CloseButton = new wxButton( this, wxID_CANCEL, _("Close"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer136->Add( CloseButton, 0, wxALL, 5 ); + + + bSizer133->Add( bSizer136, 0, wxEXPAND, 5 ); + + + bSizer132->Add( bSizer133, 1, wxEXPAND|wxALL, 5 ); + + + this->SetSizer( bSizer132 ); + this->Layout(); + bSizer132->Fit( this ); + + // Connect Events + EncryptionAlgorithmChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( EncryptionTestDialogBase::OnEncryptionAlgorithmSelected ), NULL, this ); + XtsModeCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnXtsModeCheckBoxClick ), NULL, this ); + EncryptButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnEncryptButtonClick ), NULL, this ); + DecryptButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnDecryptButtonClick ), NULL, this ); + AutoTestAllButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnAutoTestAllButtonClick ), NULL, this ); + ResetButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnResetButtonClick ), NULL, this ); +} + +EncryptionTestDialogBase::~EncryptionTestDialogBase() +{ + // Disconnect Events + EncryptionAlgorithmChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( EncryptionTestDialogBase::OnEncryptionAlgorithmSelected ), NULL, this ); + XtsModeCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnXtsModeCheckBoxClick ), NULL, this ); + EncryptButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnEncryptButtonClick ), NULL, this ); + DecryptButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnDecryptButtonClick ), NULL, this ); + AutoTestAllButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnAutoTestAllButtonClick ), NULL, this ); + ResetButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnResetButtonClick ), NULL, this ); + +} + +FavoriteVolumesDialogBase::FavoriteVolumesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + + wxBoxSizer* bSizer57; + bSizer57 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer60; + bSizer60 = new wxBoxSizer( wxHORIZONTAL ); + + wxBoxSizer* bSizer58; + bSizer58 = new wxBoxSizer( wxVERTICAL ); + + FavoritesListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES|wxSUNKEN_BORDER ); + bSizer58->Add( FavoritesListCtrl, 1, wxALL|wxEXPAND, 5 ); + + wxGridSizer* gSizer5; + gSizer5 = new wxGridSizer( 1, 4, 0, 0 ); + + MoveUpButton = new wxButton( this, wxID_ANY, _("Move &Up"), wxDefaultPosition, wxDefaultSize, 0 ); + gSizer5->Add( MoveUpButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 ); + + MoveDownButton = new wxButton( this, wxID_ANY, _("Move &Down"), wxDefaultPosition, wxDefaultSize, 0 ); + gSizer5->Add( MoveDownButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 ); + + RemoveButton = new wxButton( this, wxID_ANY, _("&Remove"), wxDefaultPosition, wxDefaultSize, 0 ); + gSizer5->Add( RemoveButton, 0, wxALIGN_RIGHT|wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + RemoveAllButton = new wxButton( this, wxID_ANY, _("Remove &All"), wxDefaultPosition, wxDefaultSize, 0 ); + gSizer5->Add( RemoveAllButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + + bSizer58->Add( gSizer5, 0, wxEXPAND|wxRIGHT|wxLEFT, 5 ); + + wxFlexGridSizer* fgSizer4; + fgSizer4 = new wxFlexGridSizer( 1, 5, 0, 0 ); + fgSizer4->AddGrowableCol( 2 ); + fgSizer4->SetFlexibleDirection( wxBOTH ); + fgSizer4->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); + + + fgSizer4->Add( 0, 0, 1, wxEXPAND, 5 ); + + + bSizer58->Add( fgSizer4, 0, wxEXPAND, 5 ); + + + bSizer60->Add( bSizer58, 1, wxEXPAND, 5 ); + + wxBoxSizer* bSizer59; + bSizer59 = new wxBoxSizer( wxVERTICAL ); + + OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); + OKButton->SetDefault(); + bSizer59->Add( OKButton, 0, wxALL, 5 ); + + CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer59->Add( CancelButton, 0, wxALL, 5 ); + + + bSizer60->Add( bSizer59, 0, wxEXPAND, 5 ); + + + bSizer57->Add( bSizer60, 1, wxEXPAND|wxALL, 5 ); + + + this->SetSizer( bSizer57 ); + this->Layout(); + bSizer57->Fit( this ); + + // Connect Events + FavoritesListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( FavoriteVolumesDialogBase::OnListItemDeselected ), NULL, this ); + FavoritesListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( FavoriteVolumesDialogBase::OnListItemSelected ), NULL, this ); + MoveUpButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnMoveUpButtonClick ), NULL, this ); + MoveDownButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnMoveDownButtonClick ), NULL, this ); + RemoveButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnRemoveButtonClick ), NULL, this ); + RemoveAllButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnRemoveAllButtonClick ), NULL, this ); + OKButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnOKButtonClick ), NULL, this ); +} + +FavoriteVolumesDialogBase::~FavoriteVolumesDialogBase() +{ + // Disconnect Events + FavoritesListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( FavoriteVolumesDialogBase::OnListItemDeselected ), NULL, this ); + FavoritesListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( FavoriteVolumesDialogBase::OnListItemSelected ), NULL, this ); + MoveUpButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnMoveUpButtonClick ), NULL, this ); + MoveDownButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnMoveDownButtonClick ), NULL, this ); + RemoveButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnRemoveButtonClick ), NULL, this ); + RemoveAllButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnRemoveAllButtonClick ), NULL, this ); + OKButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnOKButtonClick ), NULL, this ); + +} + +KeyfilesDialogBase::KeyfilesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); + + wxBoxSizer* bSizer26; + bSizer26 = new wxBoxSizer( wxVERTICAL ); + + UpperSizer = new wxBoxSizer( wxHORIZONTAL ); + + PanelSizer = new wxBoxSizer( wxVERTICAL ); + + + UpperSizer->Add( PanelSizer, 1, wxEXPAND, 5 ); + + wxBoxSizer* bSizer22; + bSizer22 = new wxBoxSizer( wxVERTICAL ); + + OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); + OKButton->SetDefault(); + bSizer22->Add( OKButton, 0, wxALL|wxEXPAND, 5 ); + + CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer22->Add( CancelButton, 0, wxALL|wxEXPAND, 5 ); + + WarningStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + WarningStaticText->Wrap( -1 ); + bSizer22->Add( WarningStaticText, 1, wxALL|wxEXPAND, 5 ); + + + UpperSizer->Add( bSizer22, 0, wxEXPAND, 5 ); + + + bSizer26->Add( UpperSizer, 1, wxTOP|wxRIGHT|wxLEFT, 5 ); + + wxBoxSizer* bSizer23; + bSizer23 = new wxBoxSizer( wxVERTICAL ); + + KeyfilesNoteSizer = new wxBoxSizer( wxVERTICAL ); + + wxStaticLine* m_staticline1; + m_staticline1 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); + KeyfilesNoteSizer->Add( m_staticline1, 0, wxEXPAND | wxALL, 5 ); + + KeyfilesNoteStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + KeyfilesNoteStaticText->Wrap( -1 ); + KeyfilesNoteSizer->Add( KeyfilesNoteStaticText, 0, wxALL|wxEXPAND, 5 ); + + wxStaticLine* m_staticline2; + m_staticline2 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); + KeyfilesNoteSizer->Add( m_staticline2, 0, wxEXPAND | wxALL, 5 ); + + + bSizer23->Add( KeyfilesNoteSizer, 1, wxEXPAND, 5 ); + + wxFlexGridSizer* fgSizer2; + fgSizer2 = new wxFlexGridSizer( 1, 2, 0, 0 ); + fgSizer2->AddGrowableCol( 0 ); + fgSizer2->SetFlexibleDirection( wxBOTH ); + fgSizer2->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); + + KeyfilesHyperlink = new wxHyperlinkCtrl( this, wxID_ANY, _("More information on keyfiles"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); + + KeyfilesHyperlink->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + KeyfilesHyperlink->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + KeyfilesHyperlink->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + fgSizer2->Add( KeyfilesHyperlink, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + CreateKeyfileButtton = new wxButton( this, wxID_ANY, _("&Generate Random Keyfile..."), wxDefaultPosition, wxDefaultSize, 0 ); + fgSizer2->Add( CreateKeyfileButtton, 0, wxALL, 5 ); + + + bSizer23->Add( fgSizer2, 0, wxEXPAND, 5 ); + + + bSizer26->Add( bSizer23, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); + + + this->SetSizer( bSizer26 ); + this->Layout(); + bSizer26->Fit( this ); + + // Connect Events + KeyfilesHyperlink->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( KeyfilesDialogBase::OnKeyfilesHyperlinkClick ), NULL, this ); + CreateKeyfileButtton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesDialogBase::OnCreateKeyfileButttonClick ), NULL, this ); +} + +KeyfilesDialogBase::~KeyfilesDialogBase() +{ + // Disconnect Events + KeyfilesHyperlink->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( KeyfilesDialogBase::OnKeyfilesHyperlinkClick ), NULL, this ); + CreateKeyfileButtton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesDialogBase::OnCreateKeyfileButttonClick ), NULL, this ); + +} + +KeyfileGeneratorDialogBase::KeyfileGeneratorDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + + MainSizer = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer144; + bSizer144 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer145; + bSizer145 = new wxBoxSizer( wxHORIZONTAL ); + + + bSizer145->Add( 0, 0, 1, wxEXPAND, 5 ); + + wxStaticText* m_staticText49; + m_staticText49 = new wxStaticText( this, wxID_ANY, _("Mixing PRF:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText49->Wrap( -1 ); + bSizer145->Add( m_staticText49, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + wxArrayString HashChoiceChoices; + HashChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, HashChoiceChoices, 0 ); + HashChoice->SetSelection( 0 ); + bSizer145->Add( HashChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + + bSizer145->Add( 0, 0, 1, wxEXPAND, 5 ); + + + bSizer144->Add( bSizer145, 0, wxEXPAND, 5 ); + + wxStaticBoxSizer* sbSizer43; + sbSizer43 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); + + wxBoxSizer* bSizer147; + bSizer147 = new wxBoxSizer( wxHORIZONTAL ); + + wxStaticText* m_staticText52; + m_staticText52 = new wxStaticText( this, wxID_ANY, _("Random Pool:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText52->Wrap( -1 ); + bSizer147->Add( m_staticText52, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); + + RandomPoolStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + RandomPoolStaticText->Wrap( -1 ); + RandomPoolStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); + + bSizer147->Add( RandomPoolStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + ShowRandomPoolCheckBox = new wxCheckBox( this, wxID_ANY, _("Show"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer147->Add( ShowRandomPoolCheckBox, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + + sbSizer43->Add( bSizer147, 0, wxEXPAND|wxTOP, 5 ); + + + sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); + + wxStaticBoxSizer* sbSizer45; + sbSizer45 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Randomness Collected From Mouse Movements") ), wxVERTICAL ); + + CollectedEntropy = new wxGauge( this, wxID_ANY, 2560, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); + CollectedEntropy->SetValue( 0 ); + sbSizer45->Add( CollectedEntropy, 1, wxALL|wxEXPAND, 5 ); + + + sbSizer43->Add( sbSizer45, 0, wxBOTTOM|wxEXPAND|wxTOP, 5 ); + + + sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); + + MouseStaticText = new wxStaticText( this, wxID_ANY, _("IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the keyfile."), wxDefaultPosition, wxDefaultSize, 0 ); + MouseStaticText->Wrap( -1 ); + sbSizer43->Add( MouseStaticText, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 ); + + + sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); + + + bSizer144->Add( sbSizer43, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); + + wxBoxSizer* bSizer162; + bSizer162 = new wxBoxSizer( wxVERTICAL ); + + wxFlexGridSizer* fgSizer8; + fgSizer8 = new wxFlexGridSizer( 3, 3, 0, 0 ); + fgSizer8->AddGrowableCol( 2 ); + fgSizer8->SetFlexibleDirection( wxBOTH ); + fgSizer8->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); + + m_staticText60 = new wxStaticText( this, wxID_ANY, _("Number of keyfiles:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText60->Wrap( -1 ); + fgSizer8->Add( m_staticText60, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); + + NumberOfKeyfiles = new wxSpinCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 1, 9999999, 1 ); + fgSizer8->Add( NumberOfKeyfiles, 0, wxALL, 5 ); + + m_panel18 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + fgSizer8->Add( m_panel18, 1, wxEXPAND | wxALL, 5 ); + + m_staticText63 = new wxStaticText( this, wxID_ANY, _("Keyfiles size (in Bytes):"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText63->Wrap( -1 ); + fgSizer8->Add( m_staticText63, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); + + KeyfilesSize = new wxSpinCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 64, 1048576, 64 ); + fgSizer8->Add( KeyfilesSize, 0, wxALL, 5 ); + + RandomSizeCheckBox = new wxCheckBox( this, wxID_ANY, _("Random size (64 <-> 1048576)"), wxDefaultPosition, wxDefaultSize, 0 ); + fgSizer8->Add( RandomSizeCheckBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); + + m_staticText65 = new wxStaticText( this, wxID_ANY, _("Keyfiles base name:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText65->Wrap( -1 ); + fgSizer8->Add( m_staticText65, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); + + KeyfilesBaseName = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + fgSizer8->Add( KeyfilesBaseName, 0, wxALL, 5 ); + + m_panel19 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + fgSizer8->Add( m_panel19, 1, wxEXPAND | wxALL, 5 ); + + + bSizer162->Add( fgSizer8, 1, wxEXPAND, 5 ); + + + bSizer144->Add( bSizer162, 0, wxALL|wxEXPAND, 5 ); + + wxBoxSizer* bSizer146; + bSizer146 = new wxBoxSizer( wxHORIZONTAL ); + + GenerateButton = new wxButton( this, wxID_ANY, _("Generate and Save Keyfile..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer146->Add( GenerateButton, 0, wxALL, 5 ); + + + bSizer146->Add( 0, 0, 1, wxEXPAND, 5 ); + + wxButton* m_button61; + m_button61 = new wxButton( this, wxID_CANCEL, _("Close"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer146->Add( m_button61, 0, wxALL, 5 ); + + + bSizer144->Add( bSizer146, 0, wxEXPAND, 5 ); + + + MainSizer->Add( bSizer144, 1, wxEXPAND|wxALL, 5 ); + + + this->SetSizer( MainSizer ); + this->Layout(); + MainSizer->Fit( this ); + + // Connect Events + this->Connect( wxEVT_MOTION, wxMouseEventHandler( KeyfileGeneratorDialogBase::OnMouseMotion ) ); + HashChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnHashSelected ), NULL, this ); + ShowRandomPoolCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnShowRandomPoolCheckBoxClicked ), NULL, this ); + RandomSizeCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnRandomSizeCheckBoxClicked ), NULL, this ); + GenerateButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnGenerateButtonClick ), NULL, this ); +} + +KeyfileGeneratorDialogBase::~KeyfileGeneratorDialogBase() +{ + // Disconnect Events + this->Disconnect( wxEVT_MOTION, wxMouseEventHandler( KeyfileGeneratorDialogBase::OnMouseMotion ) ); + HashChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnHashSelected ), NULL, this ); + ShowRandomPoolCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnShowRandomPoolCheckBoxClicked ), NULL, this ); + RandomSizeCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnRandomSizeCheckBoxClicked ), NULL, this ); + GenerateButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnGenerateButtonClick ), NULL, this ); + +} + +LegalNoticesDialogBase::LegalNoticesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + + wxBoxSizer* bSizer114; + bSizer114 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer115; + bSizer115 = new wxBoxSizer( wxVERTICAL ); + + LegalNoticesTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY ); + bSizer115->Add( LegalNoticesTextCtrl, 1, wxALL|wxEXPAND, 5 ); + + wxButton* OKButton; + OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); + OKButton->SetDefault(); + bSizer115->Add( OKButton, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 ); + + + bSizer114->Add( bSizer115, 1, wxEXPAND|wxALL, 5 ); + + + this->SetSizer( bSizer114 ); + this->Layout(); + bSizer114->Fit( this ); +} + +LegalNoticesDialogBase::~LegalNoticesDialogBase() +{ +} + +MountOptionsDialogBase::MountOptionsDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); + + MainSizer = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer19; + bSizer19 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer14; + bSizer14 = new wxBoxSizer( wxHORIZONTAL ); + + PasswordSizer = new wxBoxSizer( wxVERTICAL ); + + + bSizer14->Add( PasswordSizer, 1, wxEXPAND, 5 ); + + wxBoxSizer* bSizer9; + bSizer9 = new wxBoxSizer( wxVERTICAL ); + + OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); + OKButton->SetDefault(); + bSizer9->Add( OKButton, 0, wxALL|wxEXPAND, 5 ); + + CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer9->Add( CancelButton, 0, wxALL|wxEXPAND, 5 ); + + + bSizer9->Add( 0, 0, 1, wxTOP|wxEXPAND, 5 ); + + OptionsButton = new wxButton( this, wxID_ANY, _("Op&tions"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer9->Add( OptionsButton, 0, wxALL|wxEXPAND, 5 ); + + + bSizer14->Add( bSizer9, 0, wxEXPAND, 5 ); + + + bSizer19->Add( bSizer14, 0, wxEXPAND|wxALL, 5 ); + + wxBoxSizer* bSizer6; + bSizer6 = new wxBoxSizer( wxVERTICAL ); + + OptionsPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + OptionsSizer = new wxStaticBoxSizer( new wxStaticBox( OptionsPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); + + + OptionsSizer->Add( 0, 0, 0, wxTOP, 5 ); + + ReadOnlyCheckBox = new wxCheckBox( OptionsPanel, wxID_ANY, _("Mount volume as &read-only"), wxDefaultPosition, wxDefaultSize, 0 ); + OptionsSizer->Add( ReadOnlyCheckBox, 0, wxALL, 5 ); + + RemovableCheckBox = new wxCheckBox( OptionsPanel, wxID_ANY, _("Mount volume as removable &medium"), wxDefaultPosition, wxDefaultSize, 0 ); + OptionsSizer->Add( RemovableCheckBox, 0, wxALL, 5 ); + + PartitionInSystemEncryptionScopeCheckBox = new wxCheckBox( OptionsPanel, wxID_ANY, _("Mount partition &using system encryption (preboot authentication)"), wxDefaultPosition, wxDefaultSize, 0 ); + OptionsSizer->Add( PartitionInSystemEncryptionScopeCheckBox, 0, wxALL, 5 ); + + ProtectionSizer = new wxStaticBoxSizer( new wxStaticBox( OptionsPanel, wxID_ANY, _("Hidden Volume Protection") ), wxVERTICAL ); + + ProtectionCheckBox = new wxCheckBox( OptionsPanel, wxID_ANY, _("&Protect hidden volume when mounting outer volume"), wxDefaultPosition, wxDefaultSize, 0 ); + ProtectionSizer->Add( ProtectionCheckBox, 0, wxALL, 5 ); + + ProtectionPasswordSizer = new wxBoxSizer( wxVERTICAL ); + + + ProtectionSizer->Add( ProtectionPasswordSizer, 1, wxEXPAND|wxLEFT, 5 ); + + ProtectionHyperlinkCtrl = new wxHyperlinkCtrl( OptionsPanel, wxID_ANY, _("What is hidden volume protection?"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); + + ProtectionHyperlinkCtrl->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + ProtectionHyperlinkCtrl->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + ProtectionHyperlinkCtrl->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + ProtectionSizer->Add( ProtectionHyperlinkCtrl, 0, wxALL, 5 ); + + + OptionsSizer->Add( ProtectionSizer, 1, wxEXPAND|wxALL, 5 ); + + FilesystemSizer = new wxBoxSizer( wxVERTICAL ); + + m_panel8 = new wxPanel( OptionsPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + wxStaticBoxSizer* sbSizer28; + sbSizer28 = new wxStaticBoxSizer( new wxStaticBox( m_panel8, wxID_ANY, _("Filesystem") ), wxVERTICAL ); + + wxBoxSizer* bSizer54; + bSizer54 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer55; + bSizer55 = new wxBoxSizer( wxVERTICAL ); + + NoFilesystemCheckBox = new wxCheckBox( m_panel8, wxID_ANY, _("Do ¬ mount"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer55->Add( NoFilesystemCheckBox, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); + + + bSizer54->Add( bSizer55, 1, wxEXPAND, 5 ); + + FilesystemOptionsSizer = new wxGridBagSizer( 0, 0 ); + FilesystemOptionsSizer->SetFlexibleDirection( wxBOTH ); + FilesystemOptionsSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); + FilesystemOptionsSizer->SetEmptyCellSize( wxSize( 0,0 ) ); + + FilesystemSpacer = new wxBoxSizer( wxVERTICAL ); + + + FilesystemOptionsSizer->Add( FilesystemSpacer, wxGBPosition( 0, 0 ), wxGBSpan( 1, 1 ), wxEXPAND|wxTOP, 5 ); + + MountPointTextCtrlStaticText = new wxStaticText( m_panel8, wxID_ANY, _("Mount at directory:"), wxDefaultPosition, wxDefaultSize, 0 ); + MountPointTextCtrlStaticText->Wrap( -1 ); + FilesystemOptionsSizer->Add( MountPointTextCtrlStaticText, wxGBPosition( 1, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + MountPointTextCtrl = new wxTextCtrl( m_panel8, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + MountPointTextCtrl->SetMaxLength( 0 ); + FilesystemOptionsSizer->Add( MountPointTextCtrl, wxGBPosition( 1, 1 ), wxGBSpan( 1, 1 ), wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); + + MountPointButton = new wxButton( m_panel8, wxID_ANY, _("Se&lect..."), wxDefaultPosition, wxDefaultSize, 0 ); + FilesystemOptionsSizer->Add( MountPointButton, wxGBPosition( 1, 2 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxRIGHT|wxLEFT, 5 ); + + FilesystemOptionsStaticText = new wxStaticText( m_panel8, wxID_ANY, _("Mount options:"), wxDefaultPosition, wxDefaultSize, 0 ); + FilesystemOptionsStaticText->Wrap( -1 ); + FilesystemOptionsSizer->Add( FilesystemOptionsStaticText, wxGBPosition( 2, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxLEFT, 5 ); + + FilesystemOptionsTextCtrl = new wxTextCtrl( m_panel8, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + FilesystemOptionsTextCtrl->SetMaxLength( 0 ); + FilesystemOptionsSizer->Add( FilesystemOptionsTextCtrl, wxGBPosition( 2, 1 ), wxGBSpan( 1, 2 ), wxALIGN_CENTER_VERTICAL|wxEXPAND|wxTOP|wxRIGHT|wxLEFT, 5 ); + + + FilesystemOptionsSizer->AddGrowableCol( 1 ); + + bSizer54->Add( FilesystemOptionsSizer, 0, wxEXPAND, 5 ); + + + sbSizer28->Add( bSizer54, 0, wxEXPAND|wxBOTTOM, 5 ); + + + m_panel8->SetSizer( sbSizer28 ); + m_panel8->Layout(); + sbSizer28->Fit( m_panel8 ); + FilesystemSizer->Add( m_panel8, 0, wxEXPAND | wxALL, 5 ); + + + OptionsSizer->Add( FilesystemSizer, 0, wxEXPAND, 5 ); + + + OptionsPanel->SetSizer( OptionsSizer ); + OptionsPanel->Layout(); + OptionsSizer->Fit( OptionsPanel ); + bSizer6->Add( OptionsPanel, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); + + + bSizer19->Add( bSizer6, 0, wxEXPAND, 5 ); + + + MainSizer->Add( bSizer19, 1, wxEXPAND, 5 ); + + + this->SetSizer( MainSizer ); + this->Layout(); + MainSizer->Fit( this ); + + this->Centre( wxBOTH ); + + // Connect Events + this->Connect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( MountOptionsDialogBase::OnInitDialog ) ); + OKButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnOKButtonClick ), NULL, this ); + OptionsButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnOptionsButtonClick ), NULL, this ); + ReadOnlyCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnReadOnlyCheckBoxClick ), NULL, this ); + ProtectionCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnProtectionCheckBoxClick ), NULL, this ); + ProtectionHyperlinkCtrl->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( MountOptionsDialogBase::OnProtectionHyperlinkClick ), NULL, this ); + NoFilesystemCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnNoFilesystemCheckBoxClick ), NULL, this ); + MountPointButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnMountPointButtonClick ), NULL, this ); +} + +MountOptionsDialogBase::~MountOptionsDialogBase() +{ + // Disconnect Events + this->Disconnect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( MountOptionsDialogBase::OnInitDialog ) ); + OKButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnOKButtonClick ), NULL, this ); + OptionsButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnOptionsButtonClick ), NULL, this ); + ReadOnlyCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnReadOnlyCheckBoxClick ), NULL, this ); + ProtectionCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnProtectionCheckBoxClick ), NULL, this ); + ProtectionHyperlinkCtrl->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( MountOptionsDialogBase::OnProtectionHyperlinkClick ), NULL, this ); + NoFilesystemCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnNoFilesystemCheckBoxClick ), NULL, this ); + MountPointButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnMountPointButtonClick ), NULL, this ); + +} + +NewSecurityTokenKeyfileDialogBase::NewSecurityTokenKeyfileDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + + wxBoxSizer* bSizer143; + bSizer143 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer144; + bSizer144 = new wxBoxSizer( wxVERTICAL ); + + wxStaticBoxSizer* sbSizer42; + sbSizer42 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); + + wxFlexGridSizer* fgSizer7; + fgSizer7 = new wxFlexGridSizer( 2, 2, 0, 0 ); + fgSizer7->SetFlexibleDirection( wxBOTH ); + fgSizer7->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); + + wxStaticText* m_staticText47; + m_staticText47 = new wxStaticText( this, wxID_ANY, _("Security token:"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT ); + m_staticText47->Wrap( -1 ); + fgSizer7->Add( m_staticText47, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + wxArrayString SecurityTokenChoiceChoices; + SecurityTokenChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, SecurityTokenChoiceChoices, 0 ); + SecurityTokenChoice->SetSelection( 0 ); + fgSizer7->Add( SecurityTokenChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); + + wxStaticText* m_staticText48; + m_staticText48 = new wxStaticText( this, wxID_ANY, _("Keyfile name:"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT ); + m_staticText48->Wrap( -1 ); + fgSizer7->Add( m_staticText48, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + KeyfileNameTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + KeyfileNameTextCtrl->SetMaxLength( 0 ); + fgSizer7->Add( KeyfileNameTextCtrl, 0, wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL, 5 ); + + + sbSizer42->Add( fgSizer7, 1, wxEXPAND|wxTOP, 5 ); + + + bSizer144->Add( sbSizer42, 1, wxEXPAND|wxALL, 5 ); + + StdButtons = new wxStdDialogButtonSizer(); + StdButtonsOK = new wxButton( this, wxID_OK ); + StdButtons->AddButton( StdButtonsOK ); + StdButtonsCancel = new wxButton( this, wxID_CANCEL ); + StdButtons->AddButton( StdButtonsCancel ); + StdButtons->Realize(); + + bSizer144->Add( StdButtons, 0, wxALIGN_RIGHT|wxALL, 5 ); + + + bSizer143->Add( bSizer144, 1, wxEXPAND|wxALL, 5 ); + + + this->SetSizer( bSizer143 ); + this->Layout(); + bSizer143->Fit( this ); + + // Connect Events + KeyfileNameTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( NewSecurityTokenKeyfileDialogBase::OnKeyfileNameChanged ), NULL, this ); +} + +NewSecurityTokenKeyfileDialogBase::~NewSecurityTokenKeyfileDialogBase() +{ + // Disconnect Events + KeyfileNameTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( NewSecurityTokenKeyfileDialogBase::OnKeyfileNameChanged ), NULL, this ); + +} + +PreferencesDialogBase::PreferencesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); + + wxBoxSizer* bSizer32; + bSizer32 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer41; + bSizer41 = new wxBoxSizer( wxVERTICAL ); + + PreferencesNotebook = new wxNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 ); + SecurityPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + wxBoxSizer* bSizer44; + bSizer44 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer33; + bSizer33 = new wxBoxSizer( wxVERTICAL ); + + AutoDismountSizer = new wxStaticBoxSizer( new wxStaticBox( SecurityPage, wxID_ANY, _("Auto-Dismount") ), wxVERTICAL ); + + wxStaticBoxSizer* sbSizer13; + sbSizer13 = new wxStaticBoxSizer( new wxStaticBox( SecurityPage, wxID_ANY, _("Dismount All Volumes When") ), wxVERTICAL ); + + DismountOnLogOffCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("User logs off"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer13->Add( DismountOnLogOffCheckBox, 0, wxALL, 5 ); + + DismountOnScreenSaverCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Screen saver is launched"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer13->Add( DismountOnScreenSaverCheckBox, 0, wxALL, 5 ); + + DismountOnPowerSavingCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("System is entering power saving mode"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer13->Add( DismountOnPowerSavingCheckBox, 0, wxALL, 5 ); + + + AutoDismountSizer->Add( sbSizer13, 0, wxEXPAND|wxALL, 5 ); + + wxBoxSizer* bSizer34; + bSizer34 = new wxBoxSizer( wxHORIZONTAL ); + + DismountOnInactivityCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Auto-dismount volume after no data has been read/written to it for"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer34->Add( DismountOnInactivityCheckBox, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); + + DismountOnInactivitySpinCtrl = new wxSpinCtrl( SecurityPage, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize( -1,-1 ), wxSP_ARROW_KEYS, 1, 9999, 1 ); + DismountOnInactivitySpinCtrl->SetMinSize( wxSize( 60,-1 ) ); + + bSizer34->Add( DismountOnInactivitySpinCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); + + wxStaticText* m_staticText5; + m_staticText5 = new wxStaticText( SecurityPage, wxID_ANY, _("minutes"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText5->Wrap( -1 ); + bSizer34->Add( m_staticText5, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT, 5 ); + + + AutoDismountSizer->Add( bSizer34, 0, wxEXPAND, 5 ); + + ForceAutoDismountCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Force auto-dismount even if volume contains open files or directories"), wxDefaultPosition, wxDefaultSize, 0 ); + AutoDismountSizer->Add( ForceAutoDismountCheckBox, 0, wxALL, 5 ); + + + bSizer33->Add( AutoDismountSizer, 0, wxEXPAND|wxALL, 5 ); + + FilesystemSecuritySizer = new wxStaticBoxSizer( new wxStaticBox( SecurityPage, wxID_ANY, _("Filesystem") ), wxVERTICAL ); + + PreserveTimestampsCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Preserve modification timestamp of file containers"), wxDefaultPosition, wxDefaultSize, 0 ); + FilesystemSecuritySizer->Add( PreserveTimestampsCheckBox, 0, wxALL, 5 ); + + + bSizer33->Add( FilesystemSecuritySizer, 0, wxEXPAND|wxALL, 5 ); + + wxStaticBoxSizer* sbSizer14; + sbSizer14 = new wxStaticBoxSizer( new wxStaticBox( SecurityPage, wxID_ANY, _("Password Cache") ), wxVERTICAL ); + + WipeCacheOnCloseCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Wipe after VeraCrypt window has been closed"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer14->Add( WipeCacheOnCloseCheckBox, 0, wxALL, 5 ); + + WipeCacheOnAutoDismountCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Wipe after volume has been auto-dismounted"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer14->Add( WipeCacheOnAutoDismountCheckBox, 0, wxALL, 5 ); + + + bSizer33->Add( sbSizer14, 0, wxEXPAND|wxALL, 5 ); + + + bSizer44->Add( bSizer33, 1, wxEXPAND|wxALL, 5 ); + + + SecurityPage->SetSizer( bSizer44 ); + SecurityPage->Layout(); + bSizer44->Fit( SecurityPage ); + PreferencesNotebook->AddPage( SecurityPage, _("Security"), true ); + DefaultMountOptionsPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + wxBoxSizer* bSizer46; + bSizer46 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer35; + bSizer35 = new wxBoxSizer( wxVERTICAL ); + + wxStaticBoxSizer* sbSizer15; + sbSizer15 = new wxStaticBoxSizer( new wxStaticBox( DefaultMountOptionsPage, wxID_ANY, _("Default Mount Options") ), wxVERTICAL ); + + MountReadOnlyCheckBox = new wxCheckBox( DefaultMountOptionsPage, wxID_ANY, _("Mount volumes as read-only"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer15->Add( MountReadOnlyCheckBox, 0, wxALL, 5 ); + + MountRemovableCheckBox = new wxCheckBox( DefaultMountOptionsPage, wxID_ANY, _("Mount volumes as removable media"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer15->Add( MountRemovableCheckBox, 0, wxALL, 5 ); + + CachePasswordsCheckBox = new wxCheckBox( DefaultMountOptionsPage, wxID_ANY, _("Cache passwords in memory"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer15->Add( CachePasswordsCheckBox, 0, wxALL, 5 ); + + TrueCryptModeCheckBox = new wxCheckBox( DefaultMountOptionsPage, wxID_ANY, _("TrueCrypt Mode"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer15->Add( TrueCryptModeCheckBox, 0, wxALL, 5 ); + + wxBoxSizer* bSizer163; + bSizer163 = new wxBoxSizer( wxHORIZONTAL ); + + Pkcs5PrfStaticText = new wxStaticText( DefaultMountOptionsPage, wxID_ANY, _("PKCS5-PRF:"), wxDefaultPosition, wxDefaultSize, 0 ); + Pkcs5PrfStaticText->Wrap( -1 ); + bSizer163->Add( Pkcs5PrfStaticText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); + + wxArrayString Pkcs5PrfChoiceChoices; + Pkcs5PrfChoice = new wxChoice( DefaultMountOptionsPage, wxID_ANY, wxDefaultPosition, wxDefaultSize, Pkcs5PrfChoiceChoices, 0 ); + Pkcs5PrfChoice->SetSelection( 0 ); + bSizer163->Add( Pkcs5PrfChoice, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); + + + sbSizer15->Add( bSizer163, 0, wxEXPAND, 5 ); + + + bSizer35->Add( sbSizer15, 0, wxEXPAND|wxALL, 5 ); + + FilesystemSizer = new wxStaticBoxSizer( new wxStaticBox( DefaultMountOptionsPage, wxID_ANY, _("Filesystem") ), wxVERTICAL ); + + wxFlexGridSizer* fgSizer3; + fgSizer3 = new wxFlexGridSizer( 1, 2, 0, 0 ); + fgSizer3->AddGrowableCol( 1 ); + fgSizer3->SetFlexibleDirection( wxBOTH ); + fgSizer3->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); + + wxStaticText* m_staticText6; + m_staticText6 = new wxStaticText( DefaultMountOptionsPage, wxID_ANY, _("Mount options:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText6->Wrap( -1 ); + fgSizer3->Add( m_staticText6, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); + + FilesystemOptionsTextCtrl = new wxTextCtrl( DefaultMountOptionsPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + FilesystemOptionsTextCtrl->SetMaxLength( 0 ); + fgSizer3->Add( FilesystemOptionsTextCtrl, 0, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); + + + FilesystemSizer->Add( fgSizer3, 1, wxEXPAND, 5 ); + + + bSizer35->Add( FilesystemSizer, 0, wxEXPAND|wxALL, 5 ); + + + bSizer46->Add( bSizer35, 1, wxEXPAND|wxALL, 5 ); + + + DefaultMountOptionsPage->SetSizer( bSizer46 ); + DefaultMountOptionsPage->Layout(); + bSizer46->Fit( DefaultMountOptionsPage ); + PreferencesNotebook->AddPage( DefaultMountOptionsPage, _("Mount Options"), false ); + BackgroundTaskPanel = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + wxBoxSizer* bSizer61; + bSizer61 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer62; + bSizer62 = new wxBoxSizer( wxVERTICAL ); + + wxStaticBoxSizer* sbSizer18; + sbSizer18 = new wxStaticBoxSizer( new wxStaticBox( BackgroundTaskPanel, wxID_ANY, _("VeraCrypt Background Task") ), wxVERTICAL ); + + BackgroundTaskEnabledCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Enabled"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer18->Add( BackgroundTaskEnabledCheckBox, 0, wxALL, 5 ); + + CloseBackgroundTaskOnNoVolumesCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Exit when there are no mounted volumes"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer18->Add( CloseBackgroundTaskOnNoVolumesCheckBox, 0, wxALL, 5 ); + + wxStaticBoxSizer* sbSizer26; + sbSizer26 = new wxStaticBoxSizer( new wxStaticBox( BackgroundTaskPanel, wxID_ANY, _("Task Icon Menu Items") ), wxVERTICAL ); + + BackgroundTaskMenuMountItemsEnabledCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Mount Favorite Volumes"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer26->Add( BackgroundTaskMenuMountItemsEnabledCheckBox, 0, wxALL, 5 ); + + BackgroundTaskMenuOpenItemsEnabledCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Open Mounted Volumes"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer26->Add( BackgroundTaskMenuOpenItemsEnabledCheckBox, 0, wxALL, 5 ); + + BackgroundTaskMenuDismountItemsEnabledCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Dismount Mounted Volumes"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer26->Add( BackgroundTaskMenuDismountItemsEnabledCheckBox, 0, wxALL, 5 ); + + + sbSizer18->Add( sbSizer26, 1, wxEXPAND|wxALL, 5 ); + + + bSizer62->Add( sbSizer18, 0, wxEXPAND|wxALL, 5 ); + + + bSizer61->Add( bSizer62, 1, wxEXPAND|wxALL, 5 ); + + + BackgroundTaskPanel->SetSizer( bSizer61 ); + BackgroundTaskPanel->Layout(); + bSizer61->Fit( BackgroundTaskPanel ); + PreferencesNotebook->AddPage( BackgroundTaskPanel, _("Background Task"), false ); + SystemIntegrationPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + wxBoxSizer* bSizer49; + bSizer49 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer37; + bSizer37 = new wxBoxSizer( wxVERTICAL ); + + LogOnSizer = new wxStaticBoxSizer( new wxStaticBox( SystemIntegrationPage, wxID_ANY, _("Actions to Perform when User Logs On") ), wxVERTICAL ); + + StartOnLogonCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Start VeraCrypt Background Task"), wxDefaultPosition, wxDefaultSize, 0 ); + LogOnSizer->Add( StartOnLogonCheckBox, 0, wxALL, 5 ); + + MountFavoritesOnLogonCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Mount favorite volumes"), wxDefaultPosition, wxDefaultSize, 0 ); + LogOnSizer->Add( MountFavoritesOnLogonCheckBox, 0, wxALL, 5 ); + + MountDevicesOnLogonCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Mount all device-hosted VeraCrypt volumes"), wxDefaultPosition, wxDefaultSize, 0 ); + LogOnSizer->Add( MountDevicesOnLogonCheckBox, 0, wxALL, 5 ); + + + bSizer37->Add( LogOnSizer, 0, wxALL|wxEXPAND, 5 ); + + ExplorerSizer = new wxStaticBoxSizer( new wxStaticBox( SystemIntegrationPage, wxID_ANY, _("Filesystem Explorer") ), wxVERTICAL ); + + OpenExplorerWindowAfterMountCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Open Explorer window for successfully mounted volume"), wxDefaultPosition, wxDefaultSize, 0 ); + ExplorerSizer->Add( OpenExplorerWindowAfterMountCheckBox, 0, wxALL, 5 ); + + CloseExplorerWindowsOnDismountCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Close all Explorer windows of volume being dismounted"), wxDefaultPosition, wxDefaultSize, 0 ); + ExplorerSizer->Add( CloseExplorerWindowsOnDismountCheckBox, 0, wxALL, 5 ); + + + bSizer37->Add( ExplorerSizer, 0, wxEXPAND|wxALL, 5 ); + + KernelServicesSizer = new wxStaticBoxSizer( new wxStaticBox( SystemIntegrationPage, wxID_ANY, _("Kernel Services") ), wxVERTICAL ); + + NoKernelCryptoCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Do not use kernel cryptographic services"), wxDefaultPosition, wxDefaultSize, 0 ); + KernelServicesSizer->Add( NoKernelCryptoCheckBox, 0, wxALL, 5 ); + + + bSizer37->Add( KernelServicesSizer, 0, wxEXPAND|wxALL, 5 ); + + + bSizer49->Add( bSizer37, 1, wxEXPAND|wxALL, 5 ); + + + SystemIntegrationPage->SetSizer( bSizer49 ); + SystemIntegrationPage->Layout(); + bSizer49->Fit( SystemIntegrationPage ); + PreferencesNotebook->AddPage( SystemIntegrationPage, _("System Integration"), false ); + PerformanceOptionsPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + wxBoxSizer* bSizer151; + bSizer151 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer152; + bSizer152 = new wxBoxSizer( wxVERTICAL ); + + wxStaticBoxSizer* sbSizer44; + sbSizer44 = new wxStaticBoxSizer( new wxStaticBox( PerformanceOptionsPage, wxID_ANY, _("Hardware Acceleration") ), wxVERTICAL ); + + wxBoxSizer* bSizer158; + bSizer158 = new wxBoxSizer( wxHORIZONTAL ); + + wxStaticText* m_staticText57; + m_staticText57 = new wxStaticText( PerformanceOptionsPage, wxID_ANY, _("Processor (CPU) in this computer supports hardware acceleration for AES:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText57->Wrap( -1 ); + bSizer158->Add( m_staticText57, 0, wxALL, 5 ); + + AesHwCpuSupportedStaticText = new wxStaticText( PerformanceOptionsPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0|wxSUNKEN_BORDER ); + AesHwCpuSupportedStaticText->Wrap( -1 ); + bSizer158->Add( AesHwCpuSupportedStaticText, 0, wxALL, 5 ); + + + sbSizer44->Add( bSizer158, 1, wxEXPAND, 5 ); + + + sbSizer44->Add( 0, 0, 0, wxBOTTOM, 5 ); + + NoHardwareCryptoCheckBox = new wxCheckBox( PerformanceOptionsPage, wxID_ANY, _("Do not accelerate AES encryption/decryption by using the AES instructions of the processor"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer44->Add( NoHardwareCryptoCheckBox, 0, wxALL, 5 ); + + + bSizer152->Add( sbSizer44, 0, wxEXPAND|wxALL, 5 ); + + + bSizer151->Add( bSizer152, 1, wxALL|wxEXPAND, 5 ); + + + PerformanceOptionsPage->SetSizer( bSizer151 ); + PerformanceOptionsPage->Layout(); + bSizer151->Fit( PerformanceOptionsPage ); + PreferencesNotebook->AddPage( PerformanceOptionsPage, _("Performance"), false ); + DefaultKeyfilesPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + wxBoxSizer* bSizer40; + bSizer40 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer43; + bSizer43 = new wxBoxSizer( wxVERTICAL ); + + wxStaticBoxSizer* bSizer42; + bSizer42 = new wxStaticBoxSizer( new wxStaticBox( DefaultKeyfilesPage, wxID_ANY, _("Default Keyfiles") ), wxVERTICAL ); + + DefaultKeyfilesSizer = new wxBoxSizer( wxVERTICAL ); + + + bSizer42->Add( DefaultKeyfilesSizer, 1, wxEXPAND, 5 ); + + + bSizer43->Add( bSizer42, 1, wxEXPAND|wxALL, 5 ); + + UseKeyfilesCheckBox = new wxCheckBox( DefaultKeyfilesPage, wxID_ANY, _("Use keyfiles by default"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer43->Add( UseKeyfilesCheckBox, 0, wxALL, 5 ); + + + bSizer40->Add( bSizer43, 1, wxEXPAND|wxALL, 5 ); + + + DefaultKeyfilesPage->SetSizer( bSizer40 ); + DefaultKeyfilesPage->Layout(); + bSizer40->Fit( DefaultKeyfilesPage ); + PreferencesNotebook->AddPage( DefaultKeyfilesPage, _("Keyfiles"), false ); + SecurityTokensPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + wxBoxSizer* bSizer127; + bSizer127 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer128; + bSizer128 = new wxBoxSizer( wxVERTICAL ); + + wxStaticBoxSizer* sbSizer36; + sbSizer36 = new wxStaticBoxSizer( new wxStaticBox( SecurityTokensPage, wxID_ANY, _("PKCS #11 Library Path") ), wxVERTICAL ); + + wxBoxSizer* bSizer129; + bSizer129 = new wxBoxSizer( wxHORIZONTAL ); + + Pkcs11ModulePathTextCtrl = new wxTextCtrl( SecurityTokensPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + Pkcs11ModulePathTextCtrl->SetMaxLength( 0 ); + bSizer129->Add( Pkcs11ModulePathTextCtrl, 1, wxALL, 5 ); + + SelectPkcs11ModuleButton = new wxButton( SecurityTokensPage, wxID_ANY, _("Select &Library..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer129->Add( SelectPkcs11ModuleButton, 0, wxALL, 5 ); + + + sbSizer36->Add( bSizer129, 1, wxEXPAND, 5 ); + + + bSizer128->Add( sbSizer36, 0, wxEXPAND|wxALL, 5 ); + + wxStaticBoxSizer* sbSizer37; + sbSizer37 = new wxStaticBoxSizer( new wxStaticBox( SecurityTokensPage, wxID_ANY, _("Security Options") ), wxVERTICAL ); + + CloseSecurityTokenSessionsAfterMountCheckBox = new wxCheckBox( SecurityTokensPage, wxID_ANY, _("&Close token session (log out) after a volume is successfully mounted"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer37->Add( CloseSecurityTokenSessionsAfterMountCheckBox, 0, wxALL, 5 ); + + + bSizer128->Add( sbSizer37, 0, wxEXPAND|wxALL, 5 ); + + + bSizer127->Add( bSizer128, 1, wxEXPAND|wxALL, 5 ); + + + SecurityTokensPage->SetSizer( bSizer127 ); + SecurityTokensPage->Layout(); + bSizer127->Fit( SecurityTokensPage ); + PreferencesNotebook->AddPage( SecurityTokensPage, _("Security Tokens"), false ); + HotkeysPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); + wxBoxSizer* bSizer51; + bSizer51 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer38; + bSizer38 = new wxBoxSizer( wxVERTICAL ); + + wxStaticBoxSizer* sbSizer21; + sbSizer21 = new wxStaticBoxSizer( new wxStaticBox( HotkeysPage, wxID_ANY, _("System-Wide Hotkeys") ), wxVERTICAL ); + + HotkeyListCtrl = new wxListCtrl( HotkeysPage, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES|wxSUNKEN_BORDER ); + sbSizer21->Add( HotkeyListCtrl, 1, wxALL|wxEXPAND, 5 ); + + wxStaticBoxSizer* sbSizer23; + sbSizer23 = new wxStaticBoxSizer( new wxStaticBox( HotkeysPage, wxID_ANY, _("Shortcut") ), wxVERTICAL ); + + wxFlexGridSizer* fgSizer4; + fgSizer4 = new wxFlexGridSizer( 2, 3, 0, 0 ); + fgSizer4->SetFlexibleDirection( wxBOTH ); + fgSizer4->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); + + wxStaticText* m_staticText10; + m_staticText10 = new wxStaticText( HotkeysPage, wxID_ANY, _("Key to assign:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText10->Wrap( -1 ); + fgSizer4->Add( m_staticText10, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + HotkeyTextCtrl = new wxTextCtrl( HotkeysPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + HotkeyTextCtrl->SetMaxLength( 0 ); + fgSizer4->Add( HotkeyTextCtrl, 0, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); + + AssignHotkeyButton = new wxButton( HotkeysPage, wxID_ANY, _("Assign"), wxDefaultPosition, wxDefaultSize, 0 ); + fgSizer4->Add( AssignHotkeyButton, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + + fgSizer4->Add( 0, 0, 1, wxEXPAND, 5 ); + + wxGridSizer* gSizer4; + gSizer4 = new wxGridSizer( 1, 4, 0, 0 ); + + HotkeyControlCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Control"), wxDefaultPosition, wxDefaultSize, 0 ); + gSizer4->Add( HotkeyControlCheckBox, 0, wxALL, 5 ); + + HotkeyShiftCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Shift"), wxDefaultPosition, wxDefaultSize, 0 ); + gSizer4->Add( HotkeyShiftCheckBox, 0, wxALL, 5 ); + + HotkeyAltCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Alt"), wxDefaultPosition, wxDefaultSize, 0 ); + gSizer4->Add( HotkeyAltCheckBox, 0, wxALL, 5 ); + + HotkeyWinCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Win"), wxDefaultPosition, wxDefaultSize, 0 ); + gSizer4->Add( HotkeyWinCheckBox, 0, wxALL, 5 ); + + + fgSizer4->Add( gSizer4, 1, wxEXPAND, 5 ); + + RemoveHotkeyButton = new wxButton( HotkeysPage, wxID_ANY, _("Remove"), wxDefaultPosition, wxDefaultSize, 0 ); + fgSizer4->Add( RemoveHotkeyButton, 1, wxALL, 5 ); + + + sbSizer23->Add( fgSizer4, 1, wxALIGN_RIGHT, 5 ); + + + sbSizer21->Add( sbSizer23, 0, wxEXPAND|wxALL, 5 ); + + wxStaticBoxSizer* sbSizer24; + sbSizer24 = new wxStaticBoxSizer( new wxStaticBox( HotkeysPage, wxID_ANY, _("Options") ), wxVERTICAL ); + + BeepAfterHotkeyMountDismountCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Play system notification sound after mount/dismount"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer24->Add( BeepAfterHotkeyMountDismountCheckBox, 0, wxALL, 5 ); + + DisplayMessageAfterHotkeyDismountCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Display confirmation message box after dismount"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer24->Add( DisplayMessageAfterHotkeyDismountCheckBox, 0, wxALL, 5 ); + + + sbSizer21->Add( sbSizer24, 0, wxEXPAND|wxALL, 5 ); + + + bSizer38->Add( sbSizer21, 1, wxEXPAND|wxALL, 5 ); + + + bSizer51->Add( bSizer38, 1, wxEXPAND|wxALL, 5 ); + + + HotkeysPage->SetSizer( bSizer51 ); + HotkeysPage->Layout(); + bSizer51->Fit( HotkeysPage ); + PreferencesNotebook->AddPage( HotkeysPage, _("Hotkeys"), false ); + + bSizer41->Add( PreferencesNotebook, 1, wxEXPAND | wxALL, 5 ); + + StdButtons = new wxStdDialogButtonSizer(); + StdButtonsOK = new wxButton( this, wxID_OK ); + StdButtons->AddButton( StdButtonsOK ); + StdButtonsCancel = new wxButton( this, wxID_CANCEL ); + StdButtons->AddButton( StdButtonsCancel ); + StdButtons->Realize(); + + bSizer41->Add( StdButtons, 0, wxEXPAND|wxALL, 5 ); + + + bSizer32->Add( bSizer41, 1, wxEXPAND|wxALL, 5 ); + + + this->SetSizer( bSizer32 ); + this->Layout(); + bSizer32->Fit( this ); + + // Connect Events + this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( PreferencesDialogBase::OnClose ) ); + DismountOnScreenSaverCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnDismountOnScreenSaverCheckBoxClick ), NULL, this ); + DismountOnPowerSavingCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnDismountOnPowerSavingCheckBoxClick ), NULL, this ); + ForceAutoDismountCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnForceAutoDismountCheckBoxClick ), NULL, this ); + PreserveTimestampsCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnPreserveTimestampsCheckBoxClick ), NULL, this ); + BackgroundTaskEnabledCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnBackgroundTaskEnabledCheckBoxClick ), NULL, this ); + NoKernelCryptoCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnNoKernelCryptoCheckBoxClick ), NULL, this ); + NoHardwareCryptoCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnNoHardwareCryptoCheckBoxClick ), NULL, this ); + SelectPkcs11ModuleButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnSelectPkcs11ModuleButtonClick ), NULL, this ); + HotkeyListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( PreferencesDialogBase::OnHotkeyListItemDeselected ), NULL, this ); + HotkeyListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( PreferencesDialogBase::OnHotkeyListItemSelected ), NULL, this ); + AssignHotkeyButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnAssignHotkeyButtonClick ), NULL, this ); + RemoveHotkeyButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnRemoveHotkeyButtonClick ), NULL, this ); + StdButtonsCancel->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnCancelButtonClick ), NULL, this ); + StdButtonsOK->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnOKButtonClick ), NULL, this ); +} + +PreferencesDialogBase::~PreferencesDialogBase() +{ + // Disconnect Events + this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( PreferencesDialogBase::OnClose ) ); + DismountOnScreenSaverCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnDismountOnScreenSaverCheckBoxClick ), NULL, this ); + DismountOnPowerSavingCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnDismountOnPowerSavingCheckBoxClick ), NULL, this ); + ForceAutoDismountCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnForceAutoDismountCheckBoxClick ), NULL, this ); + PreserveTimestampsCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnPreserveTimestampsCheckBoxClick ), NULL, this ); + BackgroundTaskEnabledCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnBackgroundTaskEnabledCheckBoxClick ), NULL, this ); + NoKernelCryptoCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnNoKernelCryptoCheckBoxClick ), NULL, this ); + NoHardwareCryptoCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnNoHardwareCryptoCheckBoxClick ), NULL, this ); + SelectPkcs11ModuleButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnSelectPkcs11ModuleButtonClick ), NULL, this ); + HotkeyListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( PreferencesDialogBase::OnHotkeyListItemDeselected ), NULL, this ); + HotkeyListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( PreferencesDialogBase::OnHotkeyListItemSelected ), NULL, this ); + AssignHotkeyButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnAssignHotkeyButtonClick ), NULL, this ); + RemoveHotkeyButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnRemoveHotkeyButtonClick ), NULL, this ); + StdButtonsCancel->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnCancelButtonClick ), NULL, this ); + StdButtonsOK->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnOKButtonClick ), NULL, this ); + +} + +RandomPoolEnrichmentDialogBase::RandomPoolEnrichmentDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + + MainSizer = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer144; + bSizer144 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer145; + bSizer145 = new wxBoxSizer( wxHORIZONTAL ); + + + bSizer145->Add( 0, 0, 1, wxEXPAND, 5 ); + + wxStaticText* m_staticText49; + m_staticText49 = new wxStaticText( this, wxID_ANY, _("Mixing PRF:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText49->Wrap( -1 ); + bSizer145->Add( m_staticText49, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + wxArrayString HashChoiceChoices; + HashChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, HashChoiceChoices, 0 ); + HashChoice->SetSelection( 0 ); + bSizer145->Add( HashChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + + bSizer145->Add( 0, 0, 1, wxEXPAND, 5 ); + + + bSizer144->Add( bSizer145, 0, wxEXPAND, 5 ); + + wxStaticBoxSizer* sbSizer43; + sbSizer43 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); + + wxBoxSizer* bSizer147; + bSizer147 = new wxBoxSizer( wxHORIZONTAL ); + + wxStaticText* m_staticText52; + m_staticText52 = new wxStaticText( this, wxID_ANY, _("Random Pool:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText52->Wrap( -1 ); + bSizer147->Add( m_staticText52, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); + + RandomPoolStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + RandomPoolStaticText->Wrap( -1 ); + RandomPoolStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); + + bSizer147->Add( RandomPoolStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + ShowRandomPoolCheckBox = new wxCheckBox( this, wxID_ANY, _("Show"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer147->Add( ShowRandomPoolCheckBox, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + + sbSizer43->Add( bSizer147, 0, wxEXPAND|wxTOP, 5 ); + + + sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); + + wxStaticBoxSizer* sbSizer45; + sbSizer45 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Randomness Collected From Mouse Movements") ), wxVERTICAL ); + + CollectedEntropy = new wxGauge( this, wxID_ANY, 2560, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); + CollectedEntropy->SetValue( 0 ); + sbSizer45->Add( CollectedEntropy, 0, wxALL|wxEXPAND, 5 ); + + + sbSizer43->Add( sbSizer45, 0, wxBOTTOM|wxEXPAND|wxTOP, 5 ); + + + sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); + + MouseStaticText = new wxStaticText( this, wxID_ANY, _("IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases security. When done, click 'Continue'."), wxDefaultPosition, wxDefaultSize, 0 ); + MouseStaticText->Wrap( -1 ); + sbSizer43->Add( MouseStaticText, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 ); + + + sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); + + + bSizer144->Add( sbSizer43, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); + + wxBoxSizer* bSizer146; + bSizer146 = new wxBoxSizer( wxHORIZONTAL ); + + + bSizer146->Add( 0, 0, 1, wxEXPAND, 5 ); + + ContinueButton = new wxButton( this, wxID_OK, _("&Continue"), wxDefaultPosition, wxDefaultSize, 0 ); + ContinueButton->SetDefault(); + bSizer146->Add( ContinueButton, 0, wxALL, 5 ); + + + bSizer146->Add( 0, 0, 1, wxEXPAND, 5 ); + + + bSizer144->Add( bSizer146, 0, wxEXPAND, 5 ); + + + MainSizer->Add( bSizer144, 1, wxEXPAND|wxALL, 5 ); + + + this->SetSizer( MainSizer ); + this->Layout(); + MainSizer->Fit( this ); + + this->Centre( wxBOTH ); + + // Connect Events + this->Connect( wxEVT_MOTION, wxMouseEventHandler( RandomPoolEnrichmentDialogBase::OnMouseMotion ) ); + HashChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( RandomPoolEnrichmentDialogBase::OnHashSelected ), NULL, this ); + ShowRandomPoolCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( RandomPoolEnrichmentDialogBase::OnShowRandomPoolCheckBoxClicked ), NULL, this ); +} + +RandomPoolEnrichmentDialogBase::~RandomPoolEnrichmentDialogBase() +{ + // Disconnect Events + this->Disconnect( wxEVT_MOTION, wxMouseEventHandler( RandomPoolEnrichmentDialogBase::OnMouseMotion ) ); + HashChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( RandomPoolEnrichmentDialogBase::OnHashSelected ), NULL, this ); + ShowRandomPoolCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( RandomPoolEnrichmentDialogBase::OnShowRandomPoolCheckBoxClicked ), NULL, this ); + +} + +SecurityTokenKeyfilesDialogBase::SecurityTokenKeyfilesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxSize( -1,-1 ), wxDefaultSize ); + this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); + + wxBoxSizer* bSizer3; + bSizer3 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer138; + bSizer138 = new wxBoxSizer( wxHORIZONTAL ); + + wxBoxSizer* bSizer142; + bSizer142 = new wxBoxSizer( wxVERTICAL ); + + SecurityTokenKeyfileListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES|wxSUNKEN_BORDER ); + bSizer142->Add( SecurityTokenKeyfileListCtrl, 1, wxALL|wxEXPAND, 5 ); + + wxBoxSizer* bSizer141; + bSizer141 = new wxBoxSizer( wxHORIZONTAL ); + + ExportButton = new wxButton( this, wxID_ANY, _("&Export..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer141->Add( ExportButton, 0, wxALL, 5 ); + + DeleteButton = new wxButton( this, wxID_ANY, _("&Delete"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer141->Add( DeleteButton, 0, wxALL, 5 ); + + + bSizer141->Add( 0, 0, 1, wxEXPAND|wxLEFT, 5 ); + + ImportButton = new wxButton( this, wxID_ANY, _("&Import Keyfile to Token..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer141->Add( ImportButton, 0, wxALL, 5 ); + + + bSizer142->Add( bSizer141, 0, wxEXPAND, 5 ); + + + bSizer138->Add( bSizer142, 1, wxEXPAND, 5 ); + + wxBoxSizer* bSizer139; + bSizer139 = new wxBoxSizer( wxVERTICAL ); + + OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); + OKButton->SetDefault(); + bSizer139->Add( OKButton, 0, wxALL, 5 ); + + CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer139->Add( CancelButton, 0, wxALL, 5 ); + + + bSizer138->Add( bSizer139, 0, wxEXPAND, 5 ); + + + bSizer3->Add( bSizer138, 1, wxEXPAND|wxALL, 5 ); + + + this->SetSizer( bSizer3 ); + this->Layout(); + bSizer3->Fit( this ); + + // Connect Events + SecurityTokenKeyfileListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemActivated ), NULL, this ); + SecurityTokenKeyfileListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemDeselected ), NULL, this ); + SecurityTokenKeyfileListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemSelected ), NULL, this ); + ExportButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnExportButtonClick ), NULL, this ); + DeleteButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnDeleteButtonClick ), NULL, this ); + ImportButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnImportButtonClick ), NULL, this ); + OKButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnOKButtonClick ), NULL, this ); +} + +SecurityTokenKeyfilesDialogBase::~SecurityTokenKeyfilesDialogBase() +{ + // Disconnect Events + SecurityTokenKeyfileListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemActivated ), NULL, this ); + SecurityTokenKeyfileListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemDeselected ), NULL, this ); + SecurityTokenKeyfileListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemSelected ), NULL, this ); + ExportButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnExportButtonClick ), NULL, this ); + DeleteButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnDeleteButtonClick ), NULL, this ); + ImportButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnImportButtonClick ), NULL, this ); + OKButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnOKButtonClick ), NULL, this ); + +} + +VolumePropertiesDialogBase::VolumePropertiesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + + wxBoxSizer* bSizer49; + bSizer49 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer50; + bSizer50 = new wxBoxSizer( wxVERTICAL ); + + PropertiesListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES|wxSUNKEN_BORDER ); + bSizer50->Add( PropertiesListCtrl, 1, wxALL|wxEXPAND, 5 ); + + StdButtons = new wxStdDialogButtonSizer(); + StdButtonsOK = new wxButton( this, wxID_OK ); + StdButtons->AddButton( StdButtonsOK ); + StdButtons->Realize(); + + bSizer50->Add( StdButtons, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 ); + + + bSizer49->Add( bSizer50, 1, wxEXPAND|wxALL, 5 ); + + + this->SetSizer( bSizer49 ); + this->Layout(); + bSizer49->Fit( this ); +} + +VolumePropertiesDialogBase::~VolumePropertiesDialogBase() +{ +} + +EncryptionOptionsWizardPageBase::EncryptionOptionsWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) +{ + wxBoxSizer* bSizer93; + bSizer93 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer94; + bSizer94 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer95; + bSizer95 = new wxBoxSizer( wxVERTICAL ); + + wxStaticBoxSizer* sbSizer29; + sbSizer29 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Encryption Algorithm") ), wxVERTICAL ); + + wxBoxSizer* bSizer96; + bSizer96 = new wxBoxSizer( wxHORIZONTAL ); + + wxArrayString EncryptionAlgorithmChoiceChoices; + EncryptionAlgorithmChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, EncryptionAlgorithmChoiceChoices, 0 ); + EncryptionAlgorithmChoice->SetSelection( 0 ); + bSizer96->Add( EncryptionAlgorithmChoice, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + TestButton = new wxButton( this, wxID_ANY, _("&Test"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer96->Add( TestButton, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); + + + sbSizer29->Add( bSizer96, 0, wxEXPAND, 5 ); + + EncryptionAlgorithmStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + EncryptionAlgorithmStaticText->Wrap( -1 ); + sbSizer29->Add( EncryptionAlgorithmStaticText, 1, wxALL|wxEXPAND, 5 ); + + wxBoxSizer* bSizer97; + bSizer97 = new wxBoxSizer( wxHORIZONTAL ); + + EncryptionAlgorithmHyperlink = new wxHyperlinkCtrl( this, wxID_ANY, _("More information"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); + + EncryptionAlgorithmHyperlink->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + EncryptionAlgorithmHyperlink->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + EncryptionAlgorithmHyperlink->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + bSizer97->Add( EncryptionAlgorithmHyperlink, 0, wxALL, 5 ); + + + bSizer97->Add( 0, 0, 1, wxEXPAND, 5 ); + + BenchmarkButton = new wxButton( this, wxID_ANY, _("&Benchmark"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer97->Add( BenchmarkButton, 0, wxALL, 5 ); + + + sbSizer29->Add( bSizer97, 0, wxEXPAND, 5 ); + + + bSizer95->Add( sbSizer29, 1, wxEXPAND|wxALL, 5 ); + + wxStaticBoxSizer* sbSizer30; + sbSizer30 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Hash Algorithm") ), wxHORIZONTAL ); + + wxArrayString HashChoiceChoices; + HashChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, HashChoiceChoices, 0 ); + HashChoice->SetSelection( 0 ); + sbSizer30->Add( HashChoice, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + HashHyperlink = new wxHyperlinkCtrl( this, wxID_ANY, _("Information on hash algorithms"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); + + HashHyperlink->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + HashHyperlink->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + HashHyperlink->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); + sbSizer30->Add( HashHyperlink, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + + bSizer95->Add( sbSizer30, 0, wxEXPAND|wxALL, 5 ); + + + bSizer94->Add( bSizer95, 1, wxEXPAND, 5 ); + + + bSizer93->Add( bSizer94, 1, wxEXPAND, 5 ); + + + this->SetSizer( bSizer93 ); + this->Layout(); + bSizer93->Fit( this ); + + // Connect Events + EncryptionAlgorithmChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnEncryptionAlgorithmSelected ), NULL, this ); + TestButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnTestButtonClick ), NULL, this ); + EncryptionAlgorithmHyperlink->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( EncryptionOptionsWizardPageBase::OnEncryptionAlgorithmHyperlinkClick ), NULL, this ); + BenchmarkButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnBenchmarkButtonClick ), NULL, this ); + HashHyperlink->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( EncryptionOptionsWizardPageBase::OnHashHyperlinkClick ), NULL, this ); +} + +EncryptionOptionsWizardPageBase::~EncryptionOptionsWizardPageBase() +{ + // Disconnect Events + EncryptionAlgorithmChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnEncryptionAlgorithmSelected ), NULL, this ); + TestButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnTestButtonClick ), NULL, this ); + EncryptionAlgorithmHyperlink->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( EncryptionOptionsWizardPageBase::OnEncryptionAlgorithmHyperlinkClick ), NULL, this ); + BenchmarkButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnBenchmarkButtonClick ), NULL, this ); + HashHyperlink->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( EncryptionOptionsWizardPageBase::OnHashHyperlinkClick ), NULL, this ); + +} + +InfoWizardPageBase::InfoWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) +{ + wxBoxSizer* bSizer71; + bSizer71 = new wxBoxSizer( wxVERTICAL ); + + InfoPageSizer = new wxBoxSizer( wxVERTICAL ); + + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + InfoStaticText->Wrap( -1 ); + InfoPageSizer->Add( InfoStaticText, 1, wxALL|wxEXPAND, 5 ); + + + bSizer71->Add( InfoPageSizer, 1, wxEXPAND, 5 ); + + + this->SetSizer( bSizer71 ); + this->Layout(); + bSizer71->Fit( this ); +} + +InfoWizardPageBase::~InfoWizardPageBase() +{ +} + +KeyfilesPanelBase::KeyfilesPanelBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) +{ + this->SetMinSize( wxSize( 500,300 ) ); + + wxBoxSizer* bSizer19; + bSizer19 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer20; + bSizer20 = new wxBoxSizer( wxHORIZONTAL ); + + wxBoxSizer* bSizer21; + bSizer21 = new wxBoxSizer( wxVERTICAL ); + + KeyfilesListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxSUNKEN_BORDER ); + bSizer21->Add( KeyfilesListCtrl, 1, wxEXPAND|wxALL, 5 ); + + wxBoxSizer* bSizer137; + bSizer137 = new wxBoxSizer( wxHORIZONTAL ); + + AddFilesButton = new wxButton( this, wxID_ANY, _("Add &Files..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer137->Add( AddFilesButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + AddDirectoryButton = new wxButton( this, wxID_ANY, _("Add &Path..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer137->Add( AddDirectoryButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + AddSecurityTokenSignatureButton = new wxButton( this, wxID_ANY, _("Add &Token Files..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer137->Add( AddSecurityTokenSignatureButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + RemoveButton = new wxButton( this, wxID_ANY, _("&Remove"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer137->Add( RemoveButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + RemoveAllButton = new wxButton( this, wxID_ANY, _("Remove &All"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer137->Add( RemoveAllButton, 0, wxEXPAND|wxALL, 5 ); + + + bSizer21->Add( bSizer137, 0, wxEXPAND, 5 ); + + + bSizer20->Add( bSizer21, 1, wxEXPAND, 5 ); + + + bSizer19->Add( bSizer20, 1, wxEXPAND, 5 ); + + + this->SetSizer( bSizer19 ); + this->Layout(); + bSizer19->Fit( this ); + + // Connect Events + KeyfilesListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( KeyfilesPanelBase::OnListItemDeselected ), NULL, this ); + KeyfilesListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( KeyfilesPanelBase::OnListItemSelected ), NULL, this ); + KeyfilesListCtrl->Connect( wxEVT_SIZE, wxSizeEventHandler( KeyfilesPanelBase::OnListSizeChanged ), NULL, this ); + AddFilesButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddFilesButtonClick ), NULL, this ); + AddDirectoryButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddDirectoryButtonClick ), NULL, this ); + AddSecurityTokenSignatureButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddSecurityTokenSignatureButtonClick ), NULL, this ); + RemoveButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnRemoveButtonClick ), NULL, this ); + RemoveAllButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnRemoveAllButtonClick ), NULL, this ); +} + +KeyfilesPanelBase::~KeyfilesPanelBase() +{ + // Disconnect Events + KeyfilesListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( KeyfilesPanelBase::OnListItemDeselected ), NULL, this ); + KeyfilesListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( KeyfilesPanelBase::OnListItemSelected ), NULL, this ); + KeyfilesListCtrl->Disconnect( wxEVT_SIZE, wxSizeEventHandler( KeyfilesPanelBase::OnListSizeChanged ), NULL, this ); + AddFilesButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddFilesButtonClick ), NULL, this ); + AddDirectoryButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddDirectoryButtonClick ), NULL, this ); + AddSecurityTokenSignatureButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddSecurityTokenSignatureButtonClick ), NULL, this ); + RemoveButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnRemoveButtonClick ), NULL, this ); + RemoveAllButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnRemoveAllButtonClick ), NULL, this ); + +} + +ProgressWizardPageBase::ProgressWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) +{ + wxBoxSizer* bSizer81; + bSizer81 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer82; + bSizer82 = new wxBoxSizer( wxVERTICAL ); + + ProgressSizer = new wxBoxSizer( wxHORIZONTAL ); + + ProgressGauge = new wxGauge( this, wxID_ANY, 100, wxDefaultPosition, wxSize( -1,-1 ), wxGA_HORIZONTAL|wxGA_SMOOTH ); + ProgressGauge->SetValue( 0 ); + ProgressSizer->Add( ProgressGauge, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + AbortButton = new wxButton( this, wxID_ANY, _("&Abort"), wxDefaultPosition, wxDefaultSize, 0 ); + AbortButton->Enable( false ); + + ProgressSizer->Add( AbortButton, 0, wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 ); + + + bSizer82->Add( ProgressSizer, 0, wxEXPAND, 5 ); + + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + InfoStaticText->Wrap( -1 ); + bSizer82->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); + + + bSizer81->Add( bSizer82, 0, wxEXPAND, 5 ); + + + this->SetSizer( bSizer81 ); + this->Layout(); + bSizer81->Fit( this ); + + // Connect Events + AbortButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ProgressWizardPageBase::OnAbortButtonClick ), NULL, this ); +} + +ProgressWizardPageBase::~ProgressWizardPageBase() +{ + // Disconnect Events + AbortButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ProgressWizardPageBase::OnAbortButtonClick ), NULL, this ); + +} + +SelectDirectoryWizardPageBase::SelectDirectoryWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) +{ + this->SetMinSize( wxSize( 200,65 ) ); + + wxBoxSizer* bSizer68; + bSizer68 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer69; + bSizer69 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer70; + bSizer70 = new wxBoxSizer( wxHORIZONTAL ); + + DirectoryTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + DirectoryTextCtrl->SetMaxLength( 0 ); + bSizer70->Add( DirectoryTextCtrl, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + BrowseButton = new wxButton( this, wxID_ANY, _("&Browse..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer70->Add( BrowseButton, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + + bSizer69->Add( bSizer70, 0, wxEXPAND, 5 ); + + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + InfoStaticText->Wrap( 300 ); + bSizer69->Add( InfoStaticText, 1, wxALL|wxEXPAND, 5 ); + + + bSizer68->Add( bSizer69, 1, wxEXPAND, 5 ); + + + this->SetSizer( bSizer68 ); + this->Layout(); + bSizer68->Fit( this ); + + // Connect Events + DirectoryTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( SelectDirectoryWizardPageBase::OnDirectoryTextChanged ), NULL, this ); + BrowseButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SelectDirectoryWizardPageBase::OnBrowseButtonClick ), NULL, this ); +} + +SelectDirectoryWizardPageBase::~SelectDirectoryWizardPageBase() +{ + // Disconnect Events + DirectoryTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( SelectDirectoryWizardPageBase::OnDirectoryTextChanged ), NULL, this ); + BrowseButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SelectDirectoryWizardPageBase::OnBrowseButtonClick ), NULL, this ); + +} + +SingleChoiceWizardPageBase::SingleChoiceWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) +{ + wxBoxSizer* bSizer71; + bSizer71 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer77; + bSizer77 = new wxBoxSizer( wxVERTICAL ); + + + bSizer77->Add( 0, 0, 0, wxEXPAND|wxTOP, 5 ); + + OuterChoicesSizer = new wxBoxSizer( wxVERTICAL ); + + ChoicesSizer = new wxBoxSizer( wxVERTICAL ); + + + OuterChoicesSizer->Add( ChoicesSizer, 0, wxEXPAND, 5 ); + + + bSizer77->Add( OuterChoicesSizer, 0, wxEXPAND, 5 ); + + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + InfoStaticText->Wrap( -1 ); + bSizer77->Add( InfoStaticText, 1, wxALL|wxEXPAND, 5 ); + + + bSizer71->Add( bSizer77, 1, wxEXPAND, 5 ); + + + this->SetSizer( bSizer71 ); + this->Layout(); + bSizer71->Fit( this ); +} + +SingleChoiceWizardPageBase::~SingleChoiceWizardPageBase() +{ +} + +VolumeCreationProgressWizardPageBase::VolumeCreationProgressWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) +{ + wxBoxSizer* bSizer104; + bSizer104 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer105; + bSizer105 = new wxBoxSizer( wxVERTICAL ); + + wxStaticBoxSizer* sbSizer31; + sbSizer31 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); + + KeySamplesUpperSizer = new wxBoxSizer( wxVERTICAL ); + + KeySamplesUpperInnerSizer = new wxBoxSizer( wxVERTICAL ); + + + KeySamplesUpperSizer->Add( KeySamplesUpperInnerSizer, 1, wxEXPAND|wxTOP, 3 ); + + + sbSizer31->Add( KeySamplesUpperSizer, 1, wxEXPAND, 30 ); + + wxFlexGridSizer* fgSizer5; + fgSizer5 = new wxFlexGridSizer( 3, 2, 0, 0 ); + fgSizer5->SetFlexibleDirection( wxBOTH ); + fgSizer5->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); + + wxStaticText* m_staticText25; + m_staticText25 = new wxStaticText( this, wxID_ANY, _("Random Pool:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText25->Wrap( -1 ); + fgSizer5->Add( m_staticText25, 0, wxALL|wxALIGN_RIGHT|wxALIGN_BOTTOM, 5 ); + + wxBoxSizer* bSizer126; + bSizer126 = new wxBoxSizer( wxHORIZONTAL ); + + RandomPoolSampleStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + RandomPoolSampleStaticText->Wrap( -1 ); + RandomPoolSampleStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); + + bSizer126->Add( RandomPoolSampleStaticText, 0, wxEXPAND|wxTOP|wxRIGHT|wxALIGN_BOTTOM, 7 ); + + DisplayKeysCheckBox = new wxCheckBox( this, wxID_ANY, _("Show"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer126->Add( DisplayKeysCheckBox, 0, wxEXPAND|wxRIGHT, 5 ); + + + fgSizer5->Add( bSizer126, 1, wxEXPAND|wxALIGN_BOTTOM, 5 ); + + wxStaticText* m_staticText28; + m_staticText28 = new wxStaticText( this, wxID_ANY, _("Header Key:"), wxDefaultPosition, wxSize( -1,-1 ), 0 ); + m_staticText28->Wrap( -1 ); + fgSizer5->Add( m_staticText28, 0, wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_BOTTOM, 5 ); + + HeaderKeySampleStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + HeaderKeySampleStaticText->Wrap( -1 ); + HeaderKeySampleStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); + + fgSizer5->Add( HeaderKeySampleStaticText, 0, wxALIGN_BOTTOM|wxEXPAND|wxTOP|wxRIGHT, 2 ); + + wxStaticText* m_staticText29; + m_staticText29 = new wxStaticText( this, wxID_ANY, _("Master Key:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText29->Wrap( -1 ); + fgSizer5->Add( m_staticText29, 0, wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_BOTTOM, 5 ); + + MasterKeySampleStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + MasterKeySampleStaticText->Wrap( -1 ); + MasterKeySampleStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); + + fgSizer5->Add( MasterKeySampleStaticText, 0, wxEXPAND|wxALIGN_BOTTOM|wxTOP|wxRIGHT, 2 ); + + + sbSizer31->Add( fgSizer5, 0, wxEXPAND, 5 ); + + + bSizer105->Add( sbSizer31, 0, wxALL|wxEXPAND, 5 ); + + wxStaticBoxSizer* sbSizer45; + sbSizer45 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Randomness Collected From Mouse Movements") ), wxVERTICAL ); + + CollectedEntropy = new wxGauge( this, wxID_ANY, 2560, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); + CollectedEntropy->SetValue( 0 ); + sbSizer45->Add( CollectedEntropy, 0, wxALL|wxEXPAND, 5 ); + + + bSizer105->Add( sbSizer45, 0, wxEXPAND|wxLEFT|wxRIGHT, 5 ); + + wxStaticBoxSizer* sbSizer32; + sbSizer32 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); + + wxBoxSizer* bSizer106; + bSizer106 = new wxBoxSizer( wxHORIZONTAL ); + + ProgressGauge = new wxGauge( this, wxID_ANY, 100, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); + bSizer106->Add( ProgressGauge, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + AbortButton = new wxButton( this, wxID_ANY, _("Abort"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer106->Add( AbortButton, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); + + + sbSizer32->Add( bSizer106, 0, wxEXPAND, 5 ); + + wxGridSizer* gSizer6; + gSizer6 = new wxGridSizer( 1, 3, 0, 0 ); + + wxBoxSizer* bSizer108; + bSizer108 = new wxBoxSizer( wxHORIZONTAL ); + + m_staticText31 = new wxStaticText( this, wxID_ANY, _("Done"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText31->Wrap( -1 ); + bSizer108->Add( m_staticText31, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + m_panel12 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxSize( -1,-1 ), wxSUNKEN_BORDER ); + wxBoxSizer* bSizer115; + bSizer115 = new wxBoxSizer( wxHORIZONTAL ); + + SizeDoneStaticText = new wxStaticText( m_panel12, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT|wxST_NO_AUTORESIZE ); + SizeDoneStaticText->Wrap( -1 ); + bSizer115->Add( SizeDoneStaticText, 1, wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL, 3 ); + + + m_panel12->SetSizer( bSizer115 ); + m_panel12->Layout(); + bSizer115->Fit( m_panel12 ); + bSizer108->Add( m_panel12, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALL, 5 ); + + + gSizer6->Add( bSizer108, 1, wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); + + wxBoxSizer* bSizer1081; + bSizer1081 = new wxBoxSizer( wxHORIZONTAL ); + + m_staticText311 = new wxStaticText( this, wxID_ANY, _("Speed"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText311->Wrap( -1 ); + bSizer1081->Add( m_staticText311, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + m_panel121 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER ); + wxBoxSizer* bSizer1151; + bSizer1151 = new wxBoxSizer( wxHORIZONTAL ); + + SpeedStaticText = new wxStaticText( m_panel121, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT|wxST_NO_AUTORESIZE ); + SpeedStaticText->Wrap( -1 ); + bSizer1151->Add( SpeedStaticText, 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 3 ); + + + m_panel121->SetSizer( bSizer1151 ); + m_panel121->Layout(); + bSizer1151->Fit( m_panel121 ); + bSizer1081->Add( m_panel121, 1, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); + + + gSizer6->Add( bSizer1081, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 ); + + wxBoxSizer* bSizer1082; + bSizer1082 = new wxBoxSizer( wxHORIZONTAL ); + + m_staticText312 = new wxStaticText( this, wxID_ANY, _("Left"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText312->Wrap( -1 ); + bSizer1082->Add( m_staticText312, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + m_panel122 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); + wxBoxSizer* bSizer1152; + bSizer1152 = new wxBoxSizer( wxHORIZONTAL ); + + TimeLeftStaticText = new wxStaticText( m_panel122, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT|wxST_NO_AUTORESIZE ); + TimeLeftStaticText->Wrap( -1 ); + bSizer1152->Add( TimeLeftStaticText, 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 3 ); + + + m_panel122->SetSizer( bSizer1152 ); + m_panel122->Layout(); + bSizer1152->Fit( m_panel122 ); + bSizer1082->Add( m_panel122, 1, wxALL|wxEXPAND, 5 ); + + + gSizer6->Add( bSizer1082, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); + + + sbSizer32->Add( gSizer6, 0, wxEXPAND|wxTOP, 2 ); + + + bSizer105->Add( sbSizer32, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); + + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + InfoStaticText->Wrap( -1 ); + bSizer105->Add( InfoStaticText, 0, wxBOTTOM|wxLEFT|wxRIGHT, 5 ); + + + bSizer104->Add( bSizer105, 1, wxEXPAND, 5 ); + + + this->SetSizer( bSizer104 ); + this->Layout(); + bSizer104->Fit( this ); + + // Connect Events + DisplayKeysCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeCreationProgressWizardPageBase::OnDisplayKeysCheckBoxClick ), NULL, this ); + AbortButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeCreationProgressWizardPageBase::OnAbortButtonClick ), NULL, this ); +} + +VolumeCreationProgressWizardPageBase::~VolumeCreationProgressWizardPageBase() +{ + // Disconnect Events + DisplayKeysCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeCreationProgressWizardPageBase::OnDisplayKeysCheckBoxClick ), NULL, this ); + AbortButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeCreationProgressWizardPageBase::OnAbortButtonClick ), NULL, this ); + +} + +VolumeLocationWizardPageBase::VolumeLocationWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) +{ + wxBoxSizer* bSizer86; + bSizer86 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer87; + bSizer87 = new wxBoxSizer( wxVERTICAL ); + + + bSizer87->Add( 0, 0, 0, wxEXPAND|wxTOP, 5 ); + + wxBoxSizer* bSizer88; + bSizer88 = new wxBoxSizer( wxHORIZONTAL ); + + wxBoxSizer* bSizer89; + bSizer89 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer126; + bSizer126 = new wxBoxSizer( wxHORIZONTAL ); + + VolumePathComboBox = new wxComboBox( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_DROPDOWN ); + bSizer126->Add( VolumePathComboBox, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); + + wxBoxSizer* bSizer90; + bSizer90 = new wxBoxSizer( wxVERTICAL ); + + SelectFileButton = new wxButton( this, wxID_ANY, _("Select &File..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer90->Add( SelectFileButton, 0, wxALL|wxEXPAND, 5 ); + + SelectDeviceButton = new wxButton( this, wxID_ANY, _("Select D&evice..."), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer90->Add( SelectDeviceButton, 0, wxALL|wxEXPAND, 5 ); + + + bSizer126->Add( bSizer90, 0, wxALIGN_CENTER_VERTICAL, 5 ); + + + bSizer89->Add( bSizer126, 0, wxEXPAND, 5 ); + + wxBoxSizer* bSizer91; + bSizer91 = new wxBoxSizer( wxHORIZONTAL ); + + + bSizer91->Add( 0, 0, 0, wxLEFT, 5 ); + + NoHistoryCheckBox = new wxCheckBox( this, wxID_ANY, _("&Never save history"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer91->Add( NoHistoryCheckBox, 0, wxALL|wxEXPAND, 5 ); + + + bSizer89->Add( bSizer91, 0, wxEXPAND, 5 ); + + + bSizer88->Add( bSizer89, 1, wxEXPAND, 5 ); + + + bSizer87->Add( bSizer88, 0, wxEXPAND, 5 ); + + + bSizer87->Add( 0, 0, 0, wxEXPAND|wxBOTTOM, 5 ); + + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + InfoStaticText->Wrap( -1 ); + bSizer87->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); + + + bSizer86->Add( bSizer87, 1, wxEXPAND, 5 ); + + + this->SetSizer( bSizer86 ); + this->Layout(); + bSizer86->Fit( this ); + + // Connect Events + VolumePathComboBox->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnVolumePathTextChanged ), NULL, this ); + SelectFileButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnSelectFileButtonClick ), NULL, this ); + SelectDeviceButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnSelectDeviceButtonClick ), NULL, this ); + NoHistoryCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnNoHistoryCheckBoxClick ), NULL, this ); +} + +VolumeLocationWizardPageBase::~VolumeLocationWizardPageBase() +{ + // Disconnect Events + VolumePathComboBox->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnVolumePathTextChanged ), NULL, this ); + SelectFileButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnSelectFileButtonClick ), NULL, this ); + SelectDeviceButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnSelectDeviceButtonClick ), NULL, this ); + NoHistoryCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnNoHistoryCheckBoxClick ), NULL, this ); + +} + +VolumeFormatOptionsWizardPageBase::VolumeFormatOptionsWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) +{ + wxBoxSizer* bSizer124; + bSizer124 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer125; + bSizer125 = new wxBoxSizer( wxVERTICAL ); + + wxStaticBoxSizer* sbSizer33; + sbSizer33 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Filesystem Options") ), wxVERTICAL ); + + wxFlexGridSizer* fgSizer6; + fgSizer6 = new wxFlexGridSizer( 2, 2, 0, 0 ); + fgSizer6->SetFlexibleDirection( wxBOTH ); + fgSizer6->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); + + m_staticText43 = new wxStaticText( this, wxID_ANY, _("Filesystem type:"), wxDefaultPosition, wxDefaultSize, 0 ); + m_staticText43->Wrap( -1 ); + fgSizer6->Add( m_staticText43, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); + + wxArrayString FilesystemTypeChoiceChoices; + FilesystemTypeChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, FilesystemTypeChoiceChoices, 0 ); + FilesystemTypeChoice->SetSelection( 0 ); + fgSizer6->Add( FilesystemTypeChoice, 0, wxALL, 5 ); + + + sbSizer33->Add( fgSizer6, 1, wxEXPAND, 5 ); + + + bSizer125->Add( sbSizer33, 0, wxEXPAND|wxALL, 5 ); + + wxStaticBoxSizer* sbSizer34; + sbSizer34 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Volume Format Options") ), wxVERTICAL ); + + QuickFormatCheckBox = new wxCheckBox( this, wxID_ANY, _("Quick format"), wxDefaultPosition, wxDefaultSize, 0 ); + sbSizer34->Add( QuickFormatCheckBox, 0, wxALL, 5 ); + + + bSizer125->Add( sbSizer34, 0, wxEXPAND|wxALL, 5 ); + + + bSizer125->Add( 0, 0, 1, wxEXPAND|wxTOP|wxBOTTOM, 5 ); + + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + InfoStaticText->Wrap( -1 ); + bSizer125->Add( InfoStaticText, 0, wxALL, 5 ); + + + bSizer124->Add( bSizer125, 0, wxEXPAND, 5 ); + + + this->SetSizer( bSizer124 ); + this->Layout(); + bSizer124->Fit( this ); + + // Connect Events + FilesystemTypeChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( VolumeFormatOptionsWizardPageBase::OnFilesystemTypeSelected ), NULL, this ); + QuickFormatCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeFormatOptionsWizardPageBase::OnQuickFormatCheckBoxClick ), NULL, this ); +} + +VolumeFormatOptionsWizardPageBase::~VolumeFormatOptionsWizardPageBase() +{ + // Disconnect Events + FilesystemTypeChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( VolumeFormatOptionsWizardPageBase::OnFilesystemTypeSelected ), NULL, this ); + QuickFormatCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeFormatOptionsWizardPageBase::OnQuickFormatCheckBoxClick ), NULL, this ); + +} + +VolumePasswordPanelBase::VolumePasswordPanelBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) +{ + wxBoxSizer* bSizer7; + bSizer7 = new wxBoxSizer( wxVERTICAL ); + + GridBagSizer = new wxGridBagSizer( 0, 0 ); + GridBagSizer->SetFlexibleDirection( wxBOTH ); + GridBagSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); + GridBagSizer->SetEmptyCellSize( wxSize( 0,0 ) ); + + PasswordStaticText = new wxStaticText( this, wxID_ANY, _("Password:"), wxDefaultPosition, wxDefaultSize, 0 ); + PasswordStaticText->Wrap( -1 ); + GridBagSizer->Add( PasswordStaticText, wxGBPosition( 1, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxRIGHT, 5 ); + + PasswordTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD ); + PasswordTextCtrl->SetMaxLength( 1 ); + PasswordTextCtrl->SetMinSize( wxSize( 232,-1 ) ); + + GridBagSizer->Add( PasswordTextCtrl, wxGBPosition( 1, 1 ), wxGBSpan( 1, 2 ), wxBOTTOM|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); + + ConfirmPasswordStaticText = new wxStaticText( this, wxID_ANY, _("Confirm password:"), wxDefaultPosition, wxDefaultSize, 0 ); + ConfirmPasswordStaticText->Wrap( -1 ); + GridBagSizer->Add( ConfirmPasswordStaticText, wxGBPosition( 2, 0 ), wxGBSpan( 1, 1 ), wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); + + ConfirmPasswordTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD ); + ConfirmPasswordTextCtrl->SetMaxLength( 1 ); + ConfirmPasswordTextCtrl->SetMinSize( wxSize( 232,-1 ) ); + + GridBagSizer->Add( ConfirmPasswordTextCtrl, wxGBPosition( 2, 1 ), wxGBSpan( 1, 2 ), wxBOTTOM|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); + + VolumePimStaticText = new wxStaticText( this, wxID_ANY, _("Volume PIM:"), wxDefaultPosition, wxDefaultSize, 0 ); + VolumePimStaticText->Wrap( -1 ); + GridBagSizer->Add( VolumePimStaticText, wxGBPosition( 3, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxRIGHT, 5 ); + + VolumePimTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD ); + VolumePimTextCtrl->SetMaxLength( 7 ); + GridBagSizer->Add( VolumePimTextCtrl, wxGBPosition( 3, 1 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxEXPAND, 5 ); + + VolumePimHelpStaticText = new wxStaticText( this, wxID_ANY, _("(Empty or 0 for default iterations)"), wxDefaultPosition, wxDefaultSize, 0 ); + VolumePimHelpStaticText->Wrap( -1 ); + GridBagSizer->Add( VolumePimHelpStaticText, wxGBPosition( 3, 2 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxLEFT|wxRIGHT, 5 ); + + PimCheckBox = new wxCheckBox( this, wxID_ANY, _("Use PIM"), wxDefaultPosition, wxDefaultSize, 0 ); + GridBagSizer->Add( PimCheckBox, wxGBPosition( 4, 1 ), wxGBSpan( 1, 2 ), wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); + + CacheCheckBox = new wxCheckBox( this, wxID_ANY, _("Cach&e passwords and keyfiles in memory "), wxDefaultPosition, wxDefaultSize, 0 ); + GridBagSizer->Add( CacheCheckBox, wxGBPosition( 5, 1 ), wxGBSpan( 1, 2 ), wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); + + DisplayPasswordCheckBox = new wxCheckBox( this, wxID_ANY, _("&Display password"), wxDefaultPosition, wxDefaultSize, 0 ); + GridBagSizer->Add( DisplayPasswordCheckBox, wxGBPosition( 6, 1 ), wxGBSpan( 1, 2 ), wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); + + UseKeyfilesCheckBox = new wxCheckBox( this, wxID_ANY, _("U&se keyfiles"), wxDefaultPosition, wxDefaultSize, 0 ); + GridBagSizer->Add( UseKeyfilesCheckBox, wxGBPosition( 7, 1 ), wxGBSpan( 1, 1 ), wxTOP|wxRIGHT|wxLEFT, 5 ); + + KeyfilesButton = new wxButton( this, wxID_ANY, _("&Keyfiles..."), wxDefaultPosition, wxDefaultSize, 0 ); + GridBagSizer->Add( KeyfilesButton, wxGBPosition( 7, 2 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT|wxALIGN_BOTTOM|wxLEFT, 5 ); + + Pkcs5PrfSizer = new wxBoxSizer( wxVERTICAL ); + + + GridBagSizer->Add( Pkcs5PrfSizer, wxGBPosition( 8, 1 ), wxGBSpan( 1, 1 ), wxEXPAND|wxTOP|wxBOTTOM, 5 ); + + Pkcs5PrfStaticText = new wxStaticText( this, wxID_ANY, _("PKCS-5 PRF:"), wxDefaultPosition, wxDefaultSize, 0 ); + Pkcs5PrfStaticText->Wrap( -1 ); + GridBagSizer->Add( Pkcs5PrfStaticText, wxGBPosition( 9, 0 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxRIGHT, 5 ); + + wxString Pkcs5PrfChoiceChoices[] = { _("Unchanged") }; + int Pkcs5PrfChoiceNChoices = sizeof( Pkcs5PrfChoiceChoices ) / sizeof( wxString ); + Pkcs5PrfChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, Pkcs5PrfChoiceNChoices, Pkcs5PrfChoiceChoices, 0 ); + Pkcs5PrfChoice->SetSelection( 0 ); + GridBagSizer->Add( Pkcs5PrfChoice, wxGBPosition( 9, 1 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxLEFT, 5 ); + + TrueCryptModeCheckBox = new wxCheckBox( this, wxID_ANY, _("TrueCrypt Mode"), wxDefaultPosition, wxDefaultSize, 0 ); + GridBagSizer->Add( TrueCryptModeCheckBox, wxGBPosition( 9, 2 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxLEFT, 5 ); + + HeaderWipeCountText = new wxStaticText( this, wxID_ANY, _("Header Wipe:"), wxDefaultPosition, wxDefaultSize, 0 ); + HeaderWipeCountText->Wrap( -1 ); + GridBagSizer->Add( HeaderWipeCountText, wxGBPosition( 10, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxRIGHT, 5 ); + + wxString HeaderWipeCountChoices[] = { _("1-pass"), _("3-pass"), _("7-pass"), _("35-pass"), _("256-pass") }; + int HeaderWipeCountNChoices = sizeof( HeaderWipeCountChoices ) / sizeof( wxString ); + HeaderWipeCount = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, HeaderWipeCountNChoices, HeaderWipeCountChoices, 0 ); + HeaderWipeCount->SetSelection( 1 ); + GridBagSizer->Add( HeaderWipeCount, wxGBPosition( 10, 1 ), wxGBSpan( 1, 1 ), wxALL, 5 ); + + PasswordPlaceholderSizer = new wxBoxSizer( wxVERTICAL ); + + + GridBagSizer->Add( PasswordPlaceholderSizer, wxGBPosition( 11, 1 ), wxGBSpan( 1, 2 ), wxTOP|wxEXPAND, 5 ); + + + GridBagSizer->AddGrowableCol( 1 ); + + bSizer7->Add( GridBagSizer, 1, wxALL|wxEXPAND, 5 ); + + + this->SetSizer( bSizer7 ); + this->Layout(); + bSizer7->Fit( this ); + + // Connect Events + PasswordTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnTextChanged ), NULL, this ); + ConfirmPasswordTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnTextChanged ), NULL, this ); + VolumePimTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnPimChanged ), NULL, this ); + PimCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnUsePimCheckBoxClick ), NULL, this ); + DisplayPasswordCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnDisplayPasswordCheckBoxClick ), NULL, this ); + UseKeyfilesCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnUseKeyfilesCheckBoxClick ), NULL, this ); + KeyfilesButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonClick ), NULL, this ); + KeyfilesButton->Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonRightDown ), NULL, this ); + KeyfilesButton->Connect( wxEVT_RIGHT_UP, wxMouseEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonRightClick ), NULL, this ); + TrueCryptModeCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnTrueCryptModeChecked ), NULL, this ); +} + +VolumePasswordPanelBase::~VolumePasswordPanelBase() +{ + // Disconnect Events + PasswordTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnTextChanged ), NULL, this ); + ConfirmPasswordTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnTextChanged ), NULL, this ); + VolumePimTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnPimChanged ), NULL, this ); + PimCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnUsePimCheckBoxClick ), NULL, this ); + DisplayPasswordCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnDisplayPasswordCheckBoxClick ), NULL, this ); + UseKeyfilesCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnUseKeyfilesCheckBoxClick ), NULL, this ); + KeyfilesButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonClick ), NULL, this ); + KeyfilesButton->Disconnect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonRightDown ), NULL, this ); + KeyfilesButton->Disconnect( wxEVT_RIGHT_UP, wxMouseEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonRightClick ), NULL, this ); + TrueCryptModeCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnTrueCryptModeChecked ), NULL, this ); + +} + +VolumePasswordWizardPageBase::VolumePasswordWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) +{ + wxBoxSizer* bSizer101; + bSizer101 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer102; + bSizer102 = new wxBoxSizer( wxVERTICAL ); + + PasswordPanelSizer = new wxBoxSizer( wxVERTICAL ); + + + bSizer102->Add( PasswordPanelSizer, 0, wxEXPAND, 5 ); + + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + InfoStaticText->Wrap( -1 ); + bSizer102->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); + + + bSizer101->Add( bSizer102, 1, wxEXPAND, 5 ); + + + this->SetSizer( bSizer101 ); + this->Layout(); + bSizer101->Fit( this ); +} + +VolumePasswordWizardPageBase::~VolumePasswordWizardPageBase() +{ +} + +VolumePimWizardPageBase::VolumePimWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) +{ + wxBoxSizer* bSizer101; + bSizer101 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer102; + bSizer102 = new wxBoxSizer( wxVERTICAL ); + + PimPanelSizer = new wxBoxSizer( wxVERTICAL ); + + PimSizer = new wxBoxSizer( wxHORIZONTAL ); + + VolumePimStaticText = new wxStaticText( this, wxID_ANY, _("Volume PIM:"), wxDefaultPosition, wxDefaultSize, 0 ); + VolumePimStaticText->Wrap( -1 ); + PimSizer->Add( VolumePimStaticText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); + + VolumePimTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD ); + VolumePimTextCtrl->SetMaxLength( 7 ); + PimSizer->Add( VolumePimTextCtrl, 0, wxALL, 5 ); + + VolumePimHelpStaticText = new wxStaticText( this, wxID_ANY, _("(Empty or 0 for default iterations)"), wxDefaultPosition, wxDefaultSize, 0 ); + VolumePimHelpStaticText->Wrap( -1 ); + PimSizer->Add( VolumePimHelpStaticText, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); + + + PimPanelSizer->Add( PimSizer, 1, wxEXPAND, 5 ); + + wxBoxSizer* bSizer166; + bSizer166 = new wxBoxSizer( wxHORIZONTAL ); + + DisplayPimCheckBox = new wxCheckBox( this, wxID_ANY, _("&Display PIM"), wxDefaultPosition, wxDefaultSize, 0 ); + bSizer166->Add( DisplayPimCheckBox, 1, wxALL|wxEXPAND, 5 ); + + + PimPanelSizer->Add( bSizer166, 1, wxEXPAND, 5 ); + + + bSizer102->Add( PimPanelSizer, 0, wxEXPAND, 5 ); + + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + InfoStaticText->Wrap( -1 ); + bSizer102->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); + + + bSizer101->Add( bSizer102, 1, wxEXPAND, 5 ); + + + this->SetSizer( bSizer101 ); + this->Layout(); + bSizer101->Fit( this ); + + // Connect Events + VolumePimTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePimWizardPageBase::OnPimChanged ), NULL, this ); + DisplayPimCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePimWizardPageBase::OnDisplayPimCheckBoxClick ), NULL, this ); +} + +VolumePimWizardPageBase::~VolumePimWizardPageBase() +{ + // Disconnect Events + VolumePimTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePimWizardPageBase::OnPimChanged ), NULL, this ); + DisplayPimCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePimWizardPageBase::OnDisplayPimCheckBoxClick ), NULL, this ); + +} + +VolumeSizeWizardPageBase::VolumeSizeWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) +{ + wxBoxSizer* bSizer98; + bSizer98 = new wxBoxSizer( wxVERTICAL ); + + wxBoxSizer* bSizer99; + bSizer99 = new wxBoxSizer( wxVERTICAL ); + + + bSizer99->Add( 0, 0, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 ); + + wxBoxSizer* bSizer100; + bSizer100 = new wxBoxSizer( wxHORIZONTAL ); + + VolumeSizeTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + VolumeSizeTextCtrl->SetMaxLength( 0 ); + bSizer100->Add( VolumeSizeTextCtrl, 0, wxALL, 5 ); + + wxArrayString VolumeSizePrefixChoiceChoices; + VolumeSizePrefixChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, VolumeSizePrefixChoiceChoices, 0 ); + VolumeSizePrefixChoice->SetSelection( 0 ); + bSizer100->Add( VolumeSizePrefixChoice, 0, wxALL, 5 ); + + + bSizer99->Add( bSizer100, 0, wxEXPAND, 5 ); + + + bSizer99->Add( 0, 0, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 ); + + FreeSpaceStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + FreeSpaceStaticText->Wrap( -1 ); + bSizer99->Add( FreeSpaceStaticText, 0, wxALL|wxEXPAND, 5 ); + + + bSizer99->Add( 0, 0, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 ); + + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + InfoStaticText->Wrap( -1 ); + bSizer99->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); + + + bSizer98->Add( bSizer99, 0, wxEXPAND, 5 ); + + + this->SetSizer( bSizer98 ); + this->Layout(); + bSizer98->Fit( this ); + + // Connect Events + VolumeSizeTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumeSizeWizardPageBase::OnVolumeSizeTextChanged ), NULL, this ); + VolumeSizePrefixChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( VolumeSizeWizardPageBase::OnVolumeSizePrefixSelected ), NULL, this ); +} + +VolumeSizeWizardPageBase::~VolumeSizeWizardPageBase() +{ + // Disconnect Events + VolumeSizeTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumeSizeWizardPageBase::OnVolumeSizeTextChanged ), NULL, this ); + VolumeSizePrefixChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( VolumeSizeWizardPageBase::OnVolumeSizePrefixSelected ), NULL, this ); + +} + +WaitDialogBase::WaitDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) +{ + this->SetSizeHints( wxDefaultSize, wxDefaultSize ); + + wxBoxSizer* bSizer160; + bSizer160 = new wxBoxSizer( wxVERTICAL ); + + WaitStaticText = new wxStaticText( this, wxID_ANY, _("MyLabel"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE ); + WaitStaticText->Wrap( -1 ); + bSizer160->Add( WaitStaticText, 0, wxALIGN_CENTER_HORIZONTAL|wxALL|wxEXPAND, 5 ); + + WaitProgessBar = new wxGauge( this, wxID_ANY, 100, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); + WaitProgessBar->SetValue( 0 ); + bSizer160->Add( WaitProgessBar, 0, wxALL|wxEXPAND, 5 ); + + + this->SetSizer( bSizer160 ); + this->Layout(); + bSizer160->Fit( this ); + + this->Centre( wxBOTH ); + + // Connect Events + this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( WaitDialogBase::OnWaitDialogClose ) ); + this->Connect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( WaitDialogBase::OnWaitDialogInit ) ); +} + +WaitDialogBase::~WaitDialogBase() +{ + // Disconnect Events + this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( WaitDialogBase::OnWaitDialogClose ) ); + this->Disconnect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( WaitDialogBase::OnWaitDialogInit ) ); + +} diff --git a/src/Main/Forms/Forms.h b/src/Main/Forms/Forms.h index 5a3e8646..fd558e94 100644 --- a/src/Main/Forms/Forms.h +++ b/src/Main/Forms/Forms.h @@ -1,1097 +1,1097 @@ -/////////////////////////////////////////////////////////////////////////// -// C++ code generated with wxFormBuilder (version Jun 5 2014) -// http://www.wxformbuilder.org/ -// -// PLEASE DO "NOT" EDIT THIS FILE! -/////////////////////////////////////////////////////////////////////////// - -#ifndef __FORMS_H__ -#define __FORMS_H__ - -#include -#include -#include -class WizardPage; - -#include "WizardPage.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/////////////////////////////////////////////////////////////////////////// - -namespace VeraCrypt -{ - /////////////////////////////////////////////////////////////////////////////// - /// Class MainFrameBase - /////////////////////////////////////////////////////////////////////////////// - class MainFrameBase : public wxFrame - { - private: - - protected: - wxMenuBar* MainMenuBar; - wxMenu* VolumesMenu; - wxMenuItem* MountVolumeMenuItem; - wxMenuItem* DismountVolumeMenuItem; - wxMenuItem* DismountAllMenuItem; - wxMenuItem* VolumePropertiesMenuItem; - wxMenu* FavoritesMenu; - wxMenuItem* AddToFavoritesMenuItem; - wxMenuItem* AddAllMountedToFavoritesMenuItem; - wxMenu* ToolsMenu; - wxMenuItem* BackupVolumeHeadersMenuItem; - wxMenuItem* RestoreVolumeHeaderMenuItem; - wxMenuItem* WipeCachedPasswordsMenuItem; - wxMenu* SettingsMenu; - wxMenuItem* HotkeysMenuItem; - wxMenuItem* PreferencesMenuItem; - wxMenu* HelpMenu; - wxPanel* MainPanel; - wxListCtrl* SlotListCtrl; - wxStaticBoxSizer* LowStaticBoxSizer; - wxBoxSizer* HigherButtonSizer; - wxButton* CreateVolumeButton; - wxButton* VolumePropertiesButton; - wxButton* WipeCacheButton; - wxStaticBoxSizer* VolumeStaticBoxSizer; - wxGridBagSizer* VolumeGridBagSizer; - wxStaticBitmap* LogoBitmap; - wxComboBox* VolumePathComboBox; - wxButton* SelectFileButton; - wxCheckBox* NoHistoryCheckBox; - wxButton* VolumeToolsButton; - wxButton* SelectDeviceButton; - wxButton* VolumeButton; - wxButton* MountAllDevicesButton; - wxButton* DismountAllButton; - wxButton* ExitButton; - - // Virtual event handlers, overide them in your derived class - virtual void OnActivate( wxActivateEvent& event ) { event.Skip(); } - virtual void OnClose( wxCloseEvent& event ) { event.Skip(); } - virtual void OnCreateVolumeButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnMountVolumeMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnMountAllDevicesButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnDismountVolumeMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnDismountAllButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnChangePasswordMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnChangePkcs5PrfMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnChangeKeyfilesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnRemoveKeyfilesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnVolumePropertiesButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnAddToFavoritesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnAddAllMountedToFavoritesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnOrganizeFavoritesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnMountAllFavoritesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnBenchmarkMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnEncryptionTestMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnBackupVolumeHeadersMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnRestoreVolumeHeaderMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnCreateKeyfileMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnManageSecurityTokenKeyfilesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnCloseAllSecurityTokenSessionsMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnWipeCacheButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnHotkeysMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnDefaultKeyfilesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnDefaultMountParametersMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnSecurityTokenPreferencesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnPreferencesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnUserGuideMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnOnlineHelpMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnBeginnersTutorialMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnFaqMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnWebsiteMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnDownloadsMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnNewsMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnVersionHistoryMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnDonateMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnContactMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnLegalNoticesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnAboutMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnListItemActivated( wxListEvent& event ) { event.Skip(); } - virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } - virtual void OnListItemRightClick( wxListEvent& event ) { event.Skip(); } - virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } - virtual void OnLogoBitmapClick( wxMouseEvent& event ) { event.Skip(); } - virtual void OnSelectFileButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnNoHistoryCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnVolumeToolsButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnSelectDeviceButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnVolumeButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnExitButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - MainFrameBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxCAPTION|wxCLOSE_BOX|wxMINIMIZE_BOX|wxSYSTEM_MENU|wxTAB_TRAVERSAL ); - - ~MainFrameBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class WizardFrameBase - /////////////////////////////////////////////////////////////////////////////// - class WizardFrameBase : public wxFrame - { - private: - - protected: - wxBoxSizer* MainSizer; - wxPanel* MainPanel; - wxStaticBitmap* WizardBitmap; - wxStaticText* PageTitleStaticText; - wxBoxSizer* PageSizer; - wxButton* HelpButton; - wxButton* PreviousButton; - wxButton* NextButton; - wxButton* CancelButton; - - // Virtual event handlers, overide them in your derived class - virtual void OnActivate( wxActivateEvent& event ) { event.Skip(); } - virtual void OnClose( wxCloseEvent& event ) { event.Skip(); } - virtual void OnMouseMotion( wxMouseEvent& event ) { event.Skip(); } - virtual void OnHelpButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnPreviousButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnNextButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnCancelButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - WizardFrameBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxCAPTION|wxCLOSE_BOX|wxMINIMIZE_BOX|wxSYSTEM_MENU|wxTAB_TRAVERSAL ); - - ~WizardFrameBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class AboutDialogBase - /////////////////////////////////////////////////////////////////////////////// - class AboutDialogBase : public wxDialog - { - private: - - protected: - wxPanel* m_panel14; - wxStaticBitmap* LogoBitmap; - wxStaticText* VersionStaticText; - wxStaticText* CopyrightStaticText; - wxHyperlinkCtrl* WebsiteHyperlink; - wxStaticLine* m_staticline3; - wxTextCtrl* CreditsTextCtrl; - wxStaticLine* m_staticline4; - wxStaticLine* m_staticline5; - - // Virtual event handlers, overide them in your derived class - virtual void OnWebsiteHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } - - - public: - - AboutDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); - ~AboutDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class BenchmarkDialogBase - /////////////////////////////////////////////////////////////////////////////// - class BenchmarkDialogBase : public wxDialog - { - private: - - protected: - wxChoice* BufferSizeChoice; - wxListCtrl* BenchmarkListCtrl; - wxBoxSizer* RightSizer; - wxButton* BenchmarkButton; - wxStaticText* BenchmarkNoteStaticText; - - // Virtual event handlers, overide them in your derived class - virtual void OnBenchmarkButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - BenchmarkDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Encryption Algorithm Benchmark"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); - ~BenchmarkDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class ChangePasswordDialogBase - /////////////////////////////////////////////////////////////////////////////// - class ChangePasswordDialogBase : public wxDialog - { - private: - - protected: - wxStaticBoxSizer* CurrentSizer; - wxBoxSizer* CurrentPasswordPanelSizer; - wxStaticBoxSizer* NewSizer; - wxBoxSizer* NewPasswordPanelSizer; - wxButton* OKButton; - wxButton* CancelButton; - - // Virtual event handlers, overide them in your derived class - virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - ChangePasswordDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); - ~ChangePasswordDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class DeviceSelectionDialogBase - /////////////////////////////////////////////////////////////////////////////// - class DeviceSelectionDialogBase : public wxDialog - { - private: - - protected: - wxListCtrl* DeviceListCtrl; - wxStdDialogButtonSizer* StdButtons; - wxButton* StdButtonsOK; - wxButton* StdButtonsCancel; - - // Virtual event handlers, overide them in your derived class - virtual void OnListItemActivated( wxListEvent& event ) { event.Skip(); } - virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } - virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } - - - public: - - DeviceSelectionDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Select a Partition or Device"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxDEFAULT_DIALOG_STYLE ); - ~DeviceSelectionDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class EncryptionTestDialogBase - /////////////////////////////////////////////////////////////////////////////// - class EncryptionTestDialogBase : public wxDialog - { - private: - - protected: - wxChoice* EncryptionAlgorithmChoice; - wxCheckBox* XtsModeCheckBox; - wxTextCtrl* KeyTextCtrl; - wxStaticText* KeySizeStaticText; - wxTextCtrl* SecondaryKeyTextCtrl; - wxTextCtrl* DataUnitNumberTextCtrl; - wxTextCtrl* BlockNumberTextCtrl; - wxTextCtrl* PlainTextTextCtrl; - wxTextCtrl* CipherTextTextCtrl; - wxButton* EncryptButton; - wxButton* DecryptButton; - wxButton* AutoTestAllButton; - wxButton* ResetButton; - wxButton* CloseButton; - - // Virtual event handlers, overide them in your derived class - virtual void OnEncryptionAlgorithmSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnXtsModeCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnEncryptButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnDecryptButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnAutoTestAllButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnResetButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - EncryptionTestDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Test Vectors"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); - ~EncryptionTestDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class FavoriteVolumesDialogBase - /////////////////////////////////////////////////////////////////////////////// - class FavoriteVolumesDialogBase : public wxDialog - { - private: - - protected: - wxListCtrl* FavoritesListCtrl; - wxButton* MoveUpButton; - wxButton* MoveDownButton; - wxButton* RemoveButton; - wxButton* RemoveAllButton; - wxButton* OKButton; - wxButton* CancelButton; - - // Virtual event handlers, overide them in your derived class - virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } - virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } - virtual void OnMoveUpButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnMoveDownButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnRemoveButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnRemoveAllButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - FavoriteVolumesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Favorite Volumes"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); - ~FavoriteVolumesDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class KeyfilesDialogBase - /////////////////////////////////////////////////////////////////////////////// - class KeyfilesDialogBase : public wxDialog - { - private: - - protected: - wxBoxSizer* UpperSizer; - wxBoxSizer* PanelSizer; - wxButton* OKButton; - wxButton* CancelButton; - wxStaticText* WarningStaticText; - wxBoxSizer* KeyfilesNoteSizer; - wxStaticText* KeyfilesNoteStaticText; - wxHyperlinkCtrl* KeyfilesHyperlink; - wxButton* CreateKeyfileButtton; - - // Virtual event handlers, overide them in your derived class - virtual void OnKeyfilesHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } - virtual void OnCreateKeyfileButttonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - KeyfilesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Select Keyfiles"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); - ~KeyfilesDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class KeyfileGeneratorDialogBase - /////////////////////////////////////////////////////////////////////////////// - class KeyfileGeneratorDialogBase : public wxDialog - { - private: - - protected: - wxBoxSizer* MainSizer; - wxChoice* HashChoice; - wxStaticText* RandomPoolStaticText; - wxCheckBox* ShowRandomPoolCheckBox; - wxGauge* CollectedEntropy; - wxStaticText* MouseStaticText; - wxStaticText* m_staticText60; - wxSpinCtrl* NumberOfKeyfiles; - wxPanel* m_panel18; - wxStaticText* m_staticText63; - wxSpinCtrl* KeyfilesSize; - wxCheckBox* RandomSizeCheckBox; - wxStaticText* m_staticText65; - wxTextCtrl* KeyfilesBaseName; - wxPanel* m_panel19; - wxButton* GenerateButton; - - // Virtual event handlers, overide them in your derived class - virtual void OnMouseMotion( wxMouseEvent& event ) { event.Skip(); } - virtual void OnHashSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnShowRandomPoolCheckBoxClicked( wxCommandEvent& event ) { event.Skip(); } - virtual void OnRandomSizeCheckBoxClicked( wxCommandEvent& event ) { event.Skip(); } - virtual void OnGenerateButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - KeyfileGeneratorDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); - ~KeyfileGeneratorDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class LegalNoticesDialogBase - /////////////////////////////////////////////////////////////////////////////// - class LegalNoticesDialogBase : public wxDialog - { - private: - - protected: - wxTextCtrl* LegalNoticesTextCtrl; - - public: - - LegalNoticesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Legal Notices"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); - ~LegalNoticesDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class MountOptionsDialogBase - /////////////////////////////////////////////////////////////////////////////// - class MountOptionsDialogBase : public wxDialog - { - private: - - protected: - wxBoxSizer* MainSizer; - wxBoxSizer* PasswordSizer; - wxButton* OKButton; - wxButton* CancelButton; - wxButton* OptionsButton; - wxPanel* OptionsPanel; - wxStaticBoxSizer* OptionsSizer; - wxCheckBox* ReadOnlyCheckBox; - wxCheckBox* RemovableCheckBox; - wxCheckBox* PartitionInSystemEncryptionScopeCheckBox; - wxStaticBoxSizer* ProtectionSizer; - wxCheckBox* ProtectionCheckBox; - wxBoxSizer* ProtectionPasswordSizer; - wxHyperlinkCtrl* ProtectionHyperlinkCtrl; - wxBoxSizer* FilesystemSizer; - wxPanel* m_panel8; - wxCheckBox* NoFilesystemCheckBox; - wxGridBagSizer* FilesystemOptionsSizer; - wxBoxSizer* FilesystemSpacer; - wxStaticText* MountPointTextCtrlStaticText; - wxTextCtrl* MountPointTextCtrl; - wxButton* MountPointButton; - wxStaticText* FilesystemOptionsStaticText; - wxTextCtrl* FilesystemOptionsTextCtrl; - - // Virtual event handlers, overide them in your derived class - virtual void OnInitDialog( wxInitDialogEvent& event ) { event.Skip(); } - virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnOptionsButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnReadOnlyCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnProtectionCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnProtectionHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } - virtual void OnNoFilesystemCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnMountPointButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - MountOptionsDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Enter VeraCrypt Volume Password"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxDEFAULT_DIALOG_STYLE ); - ~MountOptionsDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class NewSecurityTokenKeyfileDialogBase - /////////////////////////////////////////////////////////////////////////////// - class NewSecurityTokenKeyfileDialogBase : public wxDialog - { - private: - - protected: - wxChoice* SecurityTokenChoice; - wxTextCtrl* KeyfileNameTextCtrl; - wxStdDialogButtonSizer* StdButtons; - wxButton* StdButtonsOK; - wxButton* StdButtonsCancel; - - // Virtual event handlers, overide them in your derived class - virtual void OnKeyfileNameChanged( wxCommandEvent& event ) { event.Skip(); } - - - public: - - NewSecurityTokenKeyfileDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("New Security Token Keyfile Properties"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); - ~NewSecurityTokenKeyfileDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class PreferencesDialogBase - /////////////////////////////////////////////////////////////////////////////// - class PreferencesDialogBase : public wxDialog - { - private: - - protected: - wxNotebook* PreferencesNotebook; - wxPanel* SecurityPage; - wxStaticBoxSizer* AutoDismountSizer; - wxCheckBox* DismountOnLogOffCheckBox; - wxCheckBox* DismountOnScreenSaverCheckBox; - wxCheckBox* DismountOnPowerSavingCheckBox; - wxCheckBox* DismountOnInactivityCheckBox; - wxSpinCtrl* DismountOnInactivitySpinCtrl; - wxCheckBox* ForceAutoDismountCheckBox; - wxStaticBoxSizer* FilesystemSecuritySizer; - wxCheckBox* PreserveTimestampsCheckBox; - wxCheckBox* WipeCacheOnCloseCheckBox; - wxCheckBox* WipeCacheOnAutoDismountCheckBox; - wxCheckBox* MountReadOnlyCheckBox; - wxCheckBox* MountRemovableCheckBox; - wxCheckBox* CachePasswordsCheckBox; - wxCheckBox* TrueCryptModeCheckBox; - wxStaticText* Pkcs5PrfStaticText; - wxChoice* Pkcs5PrfChoice; - wxStaticBoxSizer* FilesystemSizer; - wxTextCtrl* FilesystemOptionsTextCtrl; - wxPanel* BackgroundTaskPanel; - wxCheckBox* BackgroundTaskEnabledCheckBox; - wxCheckBox* CloseBackgroundTaskOnNoVolumesCheckBox; - wxCheckBox* BackgroundTaskMenuMountItemsEnabledCheckBox; - wxCheckBox* BackgroundTaskMenuOpenItemsEnabledCheckBox; - wxCheckBox* BackgroundTaskMenuDismountItemsEnabledCheckBox; - wxPanel* SystemIntegrationPage; - wxStaticBoxSizer* LogOnSizer; - wxCheckBox* StartOnLogonCheckBox; - wxCheckBox* MountFavoritesOnLogonCheckBox; - wxCheckBox* MountDevicesOnLogonCheckBox; - wxStaticBoxSizer* ExplorerSizer; - wxCheckBox* OpenExplorerWindowAfterMountCheckBox; - wxCheckBox* CloseExplorerWindowsOnDismountCheckBox; - wxStaticBoxSizer* KernelServicesSizer; - wxCheckBox* NoKernelCryptoCheckBox; - wxPanel* PerformanceOptionsPage; - wxStaticText* AesHwCpuSupportedStaticText; - wxCheckBox* NoHardwareCryptoCheckBox; - wxBoxSizer* DefaultKeyfilesSizer; - wxCheckBox* UseKeyfilesCheckBox; - wxTextCtrl* Pkcs11ModulePathTextCtrl; - wxButton* SelectPkcs11ModuleButton; - wxCheckBox* CloseSecurityTokenSessionsAfterMountCheckBox; - wxListCtrl* HotkeyListCtrl; - wxTextCtrl* HotkeyTextCtrl; - wxButton* AssignHotkeyButton; - wxCheckBox* HotkeyControlCheckBox; - wxCheckBox* HotkeyShiftCheckBox; - wxCheckBox* HotkeyAltCheckBox; - wxCheckBox* HotkeyWinCheckBox; - wxButton* RemoveHotkeyButton; - wxCheckBox* BeepAfterHotkeyMountDismountCheckBox; - wxCheckBox* DisplayMessageAfterHotkeyDismountCheckBox; - wxStdDialogButtonSizer* StdButtons; - wxButton* StdButtonsOK; - wxButton* StdButtonsCancel; - - // Virtual event handlers, overide them in your derived class - virtual void OnClose( wxCloseEvent& event ) { event.Skip(); } - virtual void OnDismountOnScreenSaverCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnDismountOnPowerSavingCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnForceAutoDismountCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnPreserveTimestampsCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnBackgroundTaskEnabledCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnNoKernelCryptoCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnNoHardwareCryptoCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnSelectPkcs11ModuleButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnHotkeyListItemDeselected( wxListEvent& event ) { event.Skip(); } - virtual void OnHotkeyListItemSelected( wxListEvent& event ) { event.Skip(); } - virtual void OnAssignHotkeyButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnRemoveHotkeyButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnCancelButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - wxPanel* DefaultMountOptionsPage; - wxPanel* DefaultKeyfilesPage; - wxPanel* SecurityTokensPage; - wxPanel* HotkeysPage; - - PreferencesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Preferences"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); - ~PreferencesDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class RandomPoolEnrichmentDialogBase - /////////////////////////////////////////////////////////////////////////////// - class RandomPoolEnrichmentDialogBase : public wxDialog - { - private: - - protected: - wxBoxSizer* MainSizer; - wxChoice* HashChoice; - wxStaticText* RandomPoolStaticText; - wxCheckBox* ShowRandomPoolCheckBox; - wxGauge* CollectedEntropy; - wxStaticText* MouseStaticText; - wxButton* ContinueButton; - - // Virtual event handlers, overide them in your derived class - virtual void OnMouseMotion( wxMouseEvent& event ) { event.Skip(); } - virtual void OnHashSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnShowRandomPoolCheckBoxClicked( wxCommandEvent& event ) { event.Skip(); } - - - public: - - RandomPoolEnrichmentDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Random Pool Enrichment"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); - ~RandomPoolEnrichmentDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class SecurityTokenKeyfilesDialogBase - /////////////////////////////////////////////////////////////////////////////// - class SecurityTokenKeyfilesDialogBase : public wxDialog - { - private: - - protected: - wxListCtrl* SecurityTokenKeyfileListCtrl; - wxButton* ExportButton; - wxButton* DeleteButton; - wxButton* ImportButton; - wxButton* OKButton; - wxButton* CancelButton; - - // Virtual event handlers, overide them in your derived class - virtual void OnListItemActivated( wxListEvent& event ) { event.Skip(); } - virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } - virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } - virtual void OnExportButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnDeleteButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnImportButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - SecurityTokenKeyfilesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Security Token Keyfiles"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxDEFAULT_DIALOG_STYLE ); - ~SecurityTokenKeyfilesDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class VolumePropertiesDialogBase - /////////////////////////////////////////////////////////////////////////////// - class VolumePropertiesDialogBase : public wxDialog - { - private: - - protected: - wxListCtrl* PropertiesListCtrl; - wxStdDialogButtonSizer* StdButtons; - wxButton* StdButtonsOK; - - public: - - VolumePropertiesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Volume Properties"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); - ~VolumePropertiesDialogBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class EncryptionOptionsWizardPageBase - /////////////////////////////////////////////////////////////////////////////// - class EncryptionOptionsWizardPageBase : public WizardPage - { - private: - - protected: - wxChoice* EncryptionAlgorithmChoice; - wxButton* TestButton; - wxStaticText* EncryptionAlgorithmStaticText; - wxHyperlinkCtrl* EncryptionAlgorithmHyperlink; - wxButton* BenchmarkButton; - wxChoice* HashChoice; - wxHyperlinkCtrl* HashHyperlink; - - // Virtual event handlers, overide them in your derived class - virtual void OnEncryptionAlgorithmSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnTestButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnEncryptionAlgorithmHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } - virtual void OnBenchmarkButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnHashHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } - - - public: - - EncryptionOptionsWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~EncryptionOptionsWizardPageBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class InfoWizardPageBase - /////////////////////////////////////////////////////////////////////////////// - class InfoWizardPageBase : public WizardPage - { - private: - - protected: - wxBoxSizer* InfoPageSizer; - wxStaticText* InfoStaticText; - - public: - - InfoWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~InfoWizardPageBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class KeyfilesPanelBase - /////////////////////////////////////////////////////////////////////////////// - class KeyfilesPanelBase : public wxPanel - { - private: - - protected: - wxListCtrl* KeyfilesListCtrl; - wxButton* AddFilesButton; - wxButton* AddDirectoryButton; - wxButton* AddSecurityTokenSignatureButton; - wxButton* RemoveButton; - wxButton* RemoveAllButton; - - // Virtual event handlers, overide them in your derived class - virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } - virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } - virtual void OnListSizeChanged( wxSizeEvent& event ) { event.Skip(); } - virtual void OnAddFilesButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnAddDirectoryButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnAddSecurityTokenSignatureButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnRemoveButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnRemoveAllButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - KeyfilesPanelBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~KeyfilesPanelBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class ProgressWizardPageBase - /////////////////////////////////////////////////////////////////////////////// - class ProgressWizardPageBase : public WizardPage - { - private: - - protected: - wxBoxSizer* ProgressSizer; - wxGauge* ProgressGauge; - wxButton* AbortButton; - wxStaticText* InfoStaticText; - - // Virtual event handlers, overide them in your derived class - virtual void OnAbortButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - ProgressWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~ProgressWizardPageBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class SelectDirectoryWizardPageBase - /////////////////////////////////////////////////////////////////////////////// - class SelectDirectoryWizardPageBase : public WizardPage - { - private: - - protected: - wxTextCtrl* DirectoryTextCtrl; - wxButton* BrowseButton; - wxStaticText* InfoStaticText; - - // Virtual event handlers, overide them in your derived class - virtual void OnDirectoryTextChanged( wxCommandEvent& event ) { event.Skip(); } - virtual void OnBrowseButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - SelectDirectoryWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~SelectDirectoryWizardPageBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class SingleChoiceWizardPageBase - /////////////////////////////////////////////////////////////////////////////// - class SingleChoiceWizardPageBase : public WizardPage - { - private: - - protected: - wxBoxSizer* OuterChoicesSizer; - wxBoxSizer* ChoicesSizer; - wxStaticText* InfoStaticText; - - public: - - SingleChoiceWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~SingleChoiceWizardPageBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class VolumeCreationProgressWizardPageBase - /////////////////////////////////////////////////////////////////////////////// - class VolumeCreationProgressWizardPageBase : public WizardPage - { - private: - - protected: - wxBoxSizer* KeySamplesUpperSizer; - wxBoxSizer* KeySamplesUpperInnerSizer; - wxStaticText* RandomPoolSampleStaticText; - wxCheckBox* DisplayKeysCheckBox; - wxStaticText* HeaderKeySampleStaticText; - wxStaticText* MasterKeySampleStaticText; - wxGauge* CollectedEntropy; - wxGauge* ProgressGauge; - wxButton* AbortButton; - wxStaticText* m_staticText31; - wxPanel* m_panel12; - wxStaticText* SizeDoneStaticText; - wxStaticText* m_staticText311; - wxPanel* m_panel121; - wxStaticText* SpeedStaticText; - wxStaticText* m_staticText312; - wxPanel* m_panel122; - wxStaticText* TimeLeftStaticText; - wxStaticText* InfoStaticText; - - // Virtual event handlers, overide them in your derived class - virtual void OnDisplayKeysCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnAbortButtonClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - VolumeCreationProgressWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~VolumeCreationProgressWizardPageBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class VolumeLocationWizardPageBase - /////////////////////////////////////////////////////////////////////////////// - class VolumeLocationWizardPageBase : public WizardPage - { - private: - - protected: - wxComboBox* VolumePathComboBox; - wxButton* SelectFileButton; - wxButton* SelectDeviceButton; - wxCheckBox* NoHistoryCheckBox; - wxStaticText* InfoStaticText; - - // Virtual event handlers, overide them in your derived class - virtual void OnVolumePathTextChanged( wxCommandEvent& event ) { event.Skip(); } - virtual void OnSelectFileButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnSelectDeviceButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnNoHistoryCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - VolumeLocationWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~VolumeLocationWizardPageBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class VolumeFormatOptionsWizardPageBase - /////////////////////////////////////////////////////////////////////////////// - class VolumeFormatOptionsWizardPageBase : public WizardPage - { - private: - - protected: - wxStaticText* m_staticText43; - wxChoice* FilesystemTypeChoice; - wxCheckBox* QuickFormatCheckBox; - wxStaticText* InfoStaticText; - - // Virtual event handlers, overide them in your derived class - virtual void OnFilesystemTypeSelected( wxCommandEvent& event ) { event.Skip(); } - virtual void OnQuickFormatCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - VolumeFormatOptionsWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~VolumeFormatOptionsWizardPageBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class VolumePasswordPanelBase - /////////////////////////////////////////////////////////////////////////////// - class VolumePasswordPanelBase : public wxPanel - { - private: - - protected: - wxGridBagSizer* GridBagSizer; - wxStaticText* PasswordStaticText; - wxTextCtrl* PasswordTextCtrl; - wxStaticText* ConfirmPasswordStaticText; - wxTextCtrl* ConfirmPasswordTextCtrl; - wxStaticText* VolumePimStaticText; - wxTextCtrl* VolumePimTextCtrl; - wxStaticText* VolumePimHelpStaticText; - wxCheckBox* PimCheckBox; - wxCheckBox* CacheCheckBox; - wxCheckBox* DisplayPasswordCheckBox; - wxCheckBox* UseKeyfilesCheckBox; - wxButton* KeyfilesButton; - wxBoxSizer* Pkcs5PrfSizer; - wxStaticText* Pkcs5PrfStaticText; - wxChoice* Pkcs5PrfChoice; - wxCheckBox* TrueCryptModeCheckBox; - wxStaticText* HeaderWipeCountText; - wxChoice* HeaderWipeCount; - wxBoxSizer* PasswordPlaceholderSizer; - - // Virtual event handlers, overide them in your derived class - virtual void OnTextChanged( wxCommandEvent& event ) { event.Skip(); } - virtual void OnPimChanged( wxCommandEvent& event ) { event.Skip(); } - virtual void OnUsePimCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnDisplayPasswordCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnUseKeyfilesCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnKeyfilesButtonClick( wxCommandEvent& event ) { event.Skip(); } - virtual void OnKeyfilesButtonRightDown( wxMouseEvent& event ) { event.Skip(); } - virtual void OnKeyfilesButtonRightClick( wxMouseEvent& event ) { event.Skip(); } - virtual void OnTrueCryptModeChecked( wxCommandEvent& event ) { event.Skip(); } - - - public: - - VolumePasswordPanelBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~VolumePasswordPanelBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class VolumePasswordWizardPageBase - /////////////////////////////////////////////////////////////////////////////// - class VolumePasswordWizardPageBase : public WizardPage - { - private: - - protected: - wxBoxSizer* PasswordPanelSizer; - wxStaticText* InfoStaticText; - - public: - - VolumePasswordWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~VolumePasswordWizardPageBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class VolumePimWizardPageBase - /////////////////////////////////////////////////////////////////////////////// - class VolumePimWizardPageBase : public WizardPage - { - private: - - protected: - wxBoxSizer* PimPanelSizer; - wxBoxSizer* PimSizer; - wxStaticText* VolumePimStaticText; - wxTextCtrl* VolumePimTextCtrl; - wxStaticText* VolumePimHelpStaticText; - wxCheckBox* DisplayPimCheckBox; - wxStaticText* InfoStaticText; - - // Virtual event handlers, overide them in your derived class - virtual void OnPimChanged( wxCommandEvent& event ) { event.Skip(); } - virtual void OnDisplayPimCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - - - public: - - VolumePimWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~VolumePimWizardPageBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class VolumeSizeWizardPageBase - /////////////////////////////////////////////////////////////////////////////// - class VolumeSizeWizardPageBase : public WizardPage - { - private: - - protected: - wxTextCtrl* VolumeSizeTextCtrl; - wxChoice* VolumeSizePrefixChoice; - wxStaticText* FreeSpaceStaticText; - wxStaticText* InfoStaticText; - - // Virtual event handlers, overide them in your derived class - virtual void OnVolumeSizeTextChanged( wxCommandEvent& event ) { event.Skip(); } - virtual void OnVolumeSizePrefixSelected( wxCommandEvent& event ) { event.Skip(); } - - - public: - - VolumeSizeWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); - ~VolumeSizeWizardPageBase(); - - }; - - /////////////////////////////////////////////////////////////////////////////// - /// Class WaitDialogBase - /////////////////////////////////////////////////////////////////////////////// - class WaitDialogBase : public wxDialog - { - private: - - protected: - wxStaticText* WaitStaticText; - wxGauge* WaitProgessBar; - - // Virtual event handlers, overide them in your derived class - virtual void OnWaitDialogClose( wxCloseEvent& event ) { event.Skip(); } - virtual void OnWaitDialogInit( wxInitDialogEvent& event ) { event.Skip(); } - - - public: - - WaitDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxCAPTION ); - ~WaitDialogBase(); - - }; - -} // namespace VeraCrypt - -#endif //__FORMS_H__ +/////////////////////////////////////////////////////////////////////////// +// C++ code generated with wxFormBuilder (version Jun 5 2014) +// http://www.wxformbuilder.org/ +// +// PLEASE DO "NOT" EDIT THIS FILE! +/////////////////////////////////////////////////////////////////////////// + +#ifndef __FORMS_H__ +#define __FORMS_H__ + +#include +#include +#include +class WizardPage; + +#include "WizardPage.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/////////////////////////////////////////////////////////////////////////// + +namespace VeraCrypt +{ + /////////////////////////////////////////////////////////////////////////////// + /// Class MainFrameBase + /////////////////////////////////////////////////////////////////////////////// + class MainFrameBase : public wxFrame + { + private: + + protected: + wxMenuBar* MainMenuBar; + wxMenu* VolumesMenu; + wxMenuItem* MountVolumeMenuItem; + wxMenuItem* DismountVolumeMenuItem; + wxMenuItem* DismountAllMenuItem; + wxMenuItem* VolumePropertiesMenuItem; + wxMenu* FavoritesMenu; + wxMenuItem* AddToFavoritesMenuItem; + wxMenuItem* AddAllMountedToFavoritesMenuItem; + wxMenu* ToolsMenu; + wxMenuItem* BackupVolumeHeadersMenuItem; + wxMenuItem* RestoreVolumeHeaderMenuItem; + wxMenuItem* WipeCachedPasswordsMenuItem; + wxMenu* SettingsMenu; + wxMenuItem* HotkeysMenuItem; + wxMenuItem* PreferencesMenuItem; + wxMenu* HelpMenu; + wxPanel* MainPanel; + wxListCtrl* SlotListCtrl; + wxStaticBoxSizer* LowStaticBoxSizer; + wxBoxSizer* HigherButtonSizer; + wxButton* CreateVolumeButton; + wxButton* VolumePropertiesButton; + wxButton* WipeCacheButton; + wxStaticBoxSizer* VolumeStaticBoxSizer; + wxGridBagSizer* VolumeGridBagSizer; + wxStaticBitmap* LogoBitmap; + wxComboBox* VolumePathComboBox; + wxButton* SelectFileButton; + wxCheckBox* NoHistoryCheckBox; + wxButton* VolumeToolsButton; + wxButton* SelectDeviceButton; + wxButton* VolumeButton; + wxButton* MountAllDevicesButton; + wxButton* DismountAllButton; + wxButton* ExitButton; + + // Virtual event handlers, overide them in your derived class + virtual void OnActivate( wxActivateEvent& event ) { event.Skip(); } + virtual void OnClose( wxCloseEvent& event ) { event.Skip(); } + virtual void OnCreateVolumeButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnMountVolumeMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnMountAllDevicesButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnDismountVolumeMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnDismountAllButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnChangePasswordMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnChangePkcs5PrfMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnChangeKeyfilesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnRemoveKeyfilesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnVolumePropertiesButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnAddToFavoritesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnAddAllMountedToFavoritesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnOrganizeFavoritesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnMountAllFavoritesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnBenchmarkMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnEncryptionTestMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnBackupVolumeHeadersMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnRestoreVolumeHeaderMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnCreateKeyfileMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnManageSecurityTokenKeyfilesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnCloseAllSecurityTokenSessionsMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnWipeCacheButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnHotkeysMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnDefaultKeyfilesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnDefaultMountParametersMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnSecurityTokenPreferencesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnPreferencesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnUserGuideMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnOnlineHelpMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnBeginnersTutorialMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnFaqMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnWebsiteMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnDownloadsMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnNewsMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnVersionHistoryMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnDonateMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnContactMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnLegalNoticesMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnAboutMenuItemSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnListItemActivated( wxListEvent& event ) { event.Skip(); } + virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } + virtual void OnListItemRightClick( wxListEvent& event ) { event.Skip(); } + virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } + virtual void OnLogoBitmapClick( wxMouseEvent& event ) { event.Skip(); } + virtual void OnSelectFileButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnNoHistoryCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnVolumeToolsButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnSelectDeviceButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnVolumeButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnExitButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + MainFrameBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxCAPTION|wxCLOSE_BOX|wxMINIMIZE_BOX|wxSYSTEM_MENU|wxTAB_TRAVERSAL ); + + ~MainFrameBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class WizardFrameBase + /////////////////////////////////////////////////////////////////////////////// + class WizardFrameBase : public wxFrame + { + private: + + protected: + wxBoxSizer* MainSizer; + wxPanel* MainPanel; + wxStaticBitmap* WizardBitmap; + wxStaticText* PageTitleStaticText; + wxBoxSizer* PageSizer; + wxButton* HelpButton; + wxButton* PreviousButton; + wxButton* NextButton; + wxButton* CancelButton; + + // Virtual event handlers, overide them in your derived class + virtual void OnActivate( wxActivateEvent& event ) { event.Skip(); } + virtual void OnClose( wxCloseEvent& event ) { event.Skip(); } + virtual void OnMouseMotion( wxMouseEvent& event ) { event.Skip(); } + virtual void OnHelpButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnPreviousButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnNextButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnCancelButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + WizardFrameBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxCAPTION|wxCLOSE_BOX|wxMINIMIZE_BOX|wxSYSTEM_MENU|wxTAB_TRAVERSAL ); + + ~WizardFrameBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class AboutDialogBase + /////////////////////////////////////////////////////////////////////////////// + class AboutDialogBase : public wxDialog + { + private: + + protected: + wxPanel* m_panel14; + wxStaticBitmap* LogoBitmap; + wxStaticText* VersionStaticText; + wxStaticText* CopyrightStaticText; + wxHyperlinkCtrl* WebsiteHyperlink; + wxStaticLine* m_staticline3; + wxTextCtrl* CreditsTextCtrl; + wxStaticLine* m_staticline4; + wxStaticLine* m_staticline5; + + // Virtual event handlers, overide them in your derived class + virtual void OnWebsiteHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } + + + public: + + AboutDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + ~AboutDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class BenchmarkDialogBase + /////////////////////////////////////////////////////////////////////////////// + class BenchmarkDialogBase : public wxDialog + { + private: + + protected: + wxChoice* BufferSizeChoice; + wxListCtrl* BenchmarkListCtrl; + wxBoxSizer* RightSizer; + wxButton* BenchmarkButton; + wxStaticText* BenchmarkNoteStaticText; + + // Virtual event handlers, overide them in your derived class + virtual void OnBenchmarkButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + BenchmarkDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Encryption Algorithm Benchmark"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + ~BenchmarkDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class ChangePasswordDialogBase + /////////////////////////////////////////////////////////////////////////////// + class ChangePasswordDialogBase : public wxDialog + { + private: + + protected: + wxStaticBoxSizer* CurrentSizer; + wxBoxSizer* CurrentPasswordPanelSizer; + wxStaticBoxSizer* NewSizer; + wxBoxSizer* NewPasswordPanelSizer; + wxButton* OKButton; + wxButton* CancelButton; + + // Virtual event handlers, overide them in your derived class + virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + ChangePasswordDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + ~ChangePasswordDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class DeviceSelectionDialogBase + /////////////////////////////////////////////////////////////////////////////// + class DeviceSelectionDialogBase : public wxDialog + { + private: + + protected: + wxListCtrl* DeviceListCtrl; + wxStdDialogButtonSizer* StdButtons; + wxButton* StdButtonsOK; + wxButton* StdButtonsCancel; + + // Virtual event handlers, overide them in your derived class + virtual void OnListItemActivated( wxListEvent& event ) { event.Skip(); } + virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } + virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } + + + public: + + DeviceSelectionDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Select a Partition or Device"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxDEFAULT_DIALOG_STYLE ); + ~DeviceSelectionDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class EncryptionTestDialogBase + /////////////////////////////////////////////////////////////////////////////// + class EncryptionTestDialogBase : public wxDialog + { + private: + + protected: + wxChoice* EncryptionAlgorithmChoice; + wxCheckBox* XtsModeCheckBox; + wxTextCtrl* KeyTextCtrl; + wxStaticText* KeySizeStaticText; + wxTextCtrl* SecondaryKeyTextCtrl; + wxTextCtrl* DataUnitNumberTextCtrl; + wxTextCtrl* BlockNumberTextCtrl; + wxTextCtrl* PlainTextTextCtrl; + wxTextCtrl* CipherTextTextCtrl; + wxButton* EncryptButton; + wxButton* DecryptButton; + wxButton* AutoTestAllButton; + wxButton* ResetButton; + wxButton* CloseButton; + + // Virtual event handlers, overide them in your derived class + virtual void OnEncryptionAlgorithmSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnXtsModeCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnEncryptButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnDecryptButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnAutoTestAllButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnResetButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + EncryptionTestDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Test Vectors"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + ~EncryptionTestDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class FavoriteVolumesDialogBase + /////////////////////////////////////////////////////////////////////////////// + class FavoriteVolumesDialogBase : public wxDialog + { + private: + + protected: + wxListCtrl* FavoritesListCtrl; + wxButton* MoveUpButton; + wxButton* MoveDownButton; + wxButton* RemoveButton; + wxButton* RemoveAllButton; + wxButton* OKButton; + wxButton* CancelButton; + + // Virtual event handlers, overide them in your derived class + virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } + virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } + virtual void OnMoveUpButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnMoveDownButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnRemoveButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnRemoveAllButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + FavoriteVolumesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Favorite Volumes"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + ~FavoriteVolumesDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class KeyfilesDialogBase + /////////////////////////////////////////////////////////////////////////////// + class KeyfilesDialogBase : public wxDialog + { + private: + + protected: + wxBoxSizer* UpperSizer; + wxBoxSizer* PanelSizer; + wxButton* OKButton; + wxButton* CancelButton; + wxStaticText* WarningStaticText; + wxBoxSizer* KeyfilesNoteSizer; + wxStaticText* KeyfilesNoteStaticText; + wxHyperlinkCtrl* KeyfilesHyperlink; + wxButton* CreateKeyfileButtton; + + // Virtual event handlers, overide them in your derived class + virtual void OnKeyfilesHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } + virtual void OnCreateKeyfileButttonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + KeyfilesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Select Keyfiles"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + ~KeyfilesDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class KeyfileGeneratorDialogBase + /////////////////////////////////////////////////////////////////////////////// + class KeyfileGeneratorDialogBase : public wxDialog + { + private: + + protected: + wxBoxSizer* MainSizer; + wxChoice* HashChoice; + wxStaticText* RandomPoolStaticText; + wxCheckBox* ShowRandomPoolCheckBox; + wxGauge* CollectedEntropy; + wxStaticText* MouseStaticText; + wxStaticText* m_staticText60; + wxSpinCtrl* NumberOfKeyfiles; + wxPanel* m_panel18; + wxStaticText* m_staticText63; + wxSpinCtrl* KeyfilesSize; + wxCheckBox* RandomSizeCheckBox; + wxStaticText* m_staticText65; + wxTextCtrl* KeyfilesBaseName; + wxPanel* m_panel19; + wxButton* GenerateButton; + + // Virtual event handlers, overide them in your derived class + virtual void OnMouseMotion( wxMouseEvent& event ) { event.Skip(); } + virtual void OnHashSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnShowRandomPoolCheckBoxClicked( wxCommandEvent& event ) { event.Skip(); } + virtual void OnRandomSizeCheckBoxClicked( wxCommandEvent& event ) { event.Skip(); } + virtual void OnGenerateButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + KeyfileGeneratorDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + ~KeyfileGeneratorDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class LegalNoticesDialogBase + /////////////////////////////////////////////////////////////////////////////// + class LegalNoticesDialogBase : public wxDialog + { + private: + + protected: + wxTextCtrl* LegalNoticesTextCtrl; + + public: + + LegalNoticesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Legal Notices"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + ~LegalNoticesDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class MountOptionsDialogBase + /////////////////////////////////////////////////////////////////////////////// + class MountOptionsDialogBase : public wxDialog + { + private: + + protected: + wxBoxSizer* MainSizer; + wxBoxSizer* PasswordSizer; + wxButton* OKButton; + wxButton* CancelButton; + wxButton* OptionsButton; + wxPanel* OptionsPanel; + wxStaticBoxSizer* OptionsSizer; + wxCheckBox* ReadOnlyCheckBox; + wxCheckBox* RemovableCheckBox; + wxCheckBox* PartitionInSystemEncryptionScopeCheckBox; + wxStaticBoxSizer* ProtectionSizer; + wxCheckBox* ProtectionCheckBox; + wxBoxSizer* ProtectionPasswordSizer; + wxHyperlinkCtrl* ProtectionHyperlinkCtrl; + wxBoxSizer* FilesystemSizer; + wxPanel* m_panel8; + wxCheckBox* NoFilesystemCheckBox; + wxGridBagSizer* FilesystemOptionsSizer; + wxBoxSizer* FilesystemSpacer; + wxStaticText* MountPointTextCtrlStaticText; + wxTextCtrl* MountPointTextCtrl; + wxButton* MountPointButton; + wxStaticText* FilesystemOptionsStaticText; + wxTextCtrl* FilesystemOptionsTextCtrl; + + // Virtual event handlers, overide them in your derived class + virtual void OnInitDialog( wxInitDialogEvent& event ) { event.Skip(); } + virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnOptionsButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnReadOnlyCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnProtectionCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnProtectionHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } + virtual void OnNoFilesystemCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnMountPointButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + MountOptionsDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Enter VeraCrypt Volume Password"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxDEFAULT_DIALOG_STYLE ); + ~MountOptionsDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class NewSecurityTokenKeyfileDialogBase + /////////////////////////////////////////////////////////////////////////////// + class NewSecurityTokenKeyfileDialogBase : public wxDialog + { + private: + + protected: + wxChoice* SecurityTokenChoice; + wxTextCtrl* KeyfileNameTextCtrl; + wxStdDialogButtonSizer* StdButtons; + wxButton* StdButtonsOK; + wxButton* StdButtonsCancel; + + // Virtual event handlers, overide them in your derived class + virtual void OnKeyfileNameChanged( wxCommandEvent& event ) { event.Skip(); } + + + public: + + NewSecurityTokenKeyfileDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("New Security Token Keyfile Properties"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + ~NewSecurityTokenKeyfileDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class PreferencesDialogBase + /////////////////////////////////////////////////////////////////////////////// + class PreferencesDialogBase : public wxDialog + { + private: + + protected: + wxNotebook* PreferencesNotebook; + wxPanel* SecurityPage; + wxStaticBoxSizer* AutoDismountSizer; + wxCheckBox* DismountOnLogOffCheckBox; + wxCheckBox* DismountOnScreenSaverCheckBox; + wxCheckBox* DismountOnPowerSavingCheckBox; + wxCheckBox* DismountOnInactivityCheckBox; + wxSpinCtrl* DismountOnInactivitySpinCtrl; + wxCheckBox* ForceAutoDismountCheckBox; + wxStaticBoxSizer* FilesystemSecuritySizer; + wxCheckBox* PreserveTimestampsCheckBox; + wxCheckBox* WipeCacheOnCloseCheckBox; + wxCheckBox* WipeCacheOnAutoDismountCheckBox; + wxCheckBox* MountReadOnlyCheckBox; + wxCheckBox* MountRemovableCheckBox; + wxCheckBox* CachePasswordsCheckBox; + wxCheckBox* TrueCryptModeCheckBox; + wxStaticText* Pkcs5PrfStaticText; + wxChoice* Pkcs5PrfChoice; + wxStaticBoxSizer* FilesystemSizer; + wxTextCtrl* FilesystemOptionsTextCtrl; + wxPanel* BackgroundTaskPanel; + wxCheckBox* BackgroundTaskEnabledCheckBox; + wxCheckBox* CloseBackgroundTaskOnNoVolumesCheckBox; + wxCheckBox* BackgroundTaskMenuMountItemsEnabledCheckBox; + wxCheckBox* BackgroundTaskMenuOpenItemsEnabledCheckBox; + wxCheckBox* BackgroundTaskMenuDismountItemsEnabledCheckBox; + wxPanel* SystemIntegrationPage; + wxStaticBoxSizer* LogOnSizer; + wxCheckBox* StartOnLogonCheckBox; + wxCheckBox* MountFavoritesOnLogonCheckBox; + wxCheckBox* MountDevicesOnLogonCheckBox; + wxStaticBoxSizer* ExplorerSizer; + wxCheckBox* OpenExplorerWindowAfterMountCheckBox; + wxCheckBox* CloseExplorerWindowsOnDismountCheckBox; + wxStaticBoxSizer* KernelServicesSizer; + wxCheckBox* NoKernelCryptoCheckBox; + wxPanel* PerformanceOptionsPage; + wxStaticText* AesHwCpuSupportedStaticText; + wxCheckBox* NoHardwareCryptoCheckBox; + wxBoxSizer* DefaultKeyfilesSizer; + wxCheckBox* UseKeyfilesCheckBox; + wxTextCtrl* Pkcs11ModulePathTextCtrl; + wxButton* SelectPkcs11ModuleButton; + wxCheckBox* CloseSecurityTokenSessionsAfterMountCheckBox; + wxListCtrl* HotkeyListCtrl; + wxTextCtrl* HotkeyTextCtrl; + wxButton* AssignHotkeyButton; + wxCheckBox* HotkeyControlCheckBox; + wxCheckBox* HotkeyShiftCheckBox; + wxCheckBox* HotkeyAltCheckBox; + wxCheckBox* HotkeyWinCheckBox; + wxButton* RemoveHotkeyButton; + wxCheckBox* BeepAfterHotkeyMountDismountCheckBox; + wxCheckBox* DisplayMessageAfterHotkeyDismountCheckBox; + wxStdDialogButtonSizer* StdButtons; + wxButton* StdButtonsOK; + wxButton* StdButtonsCancel; + + // Virtual event handlers, overide them in your derived class + virtual void OnClose( wxCloseEvent& event ) { event.Skip(); } + virtual void OnDismountOnScreenSaverCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnDismountOnPowerSavingCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnForceAutoDismountCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnPreserveTimestampsCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnBackgroundTaskEnabledCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnNoKernelCryptoCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnNoHardwareCryptoCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnSelectPkcs11ModuleButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnHotkeyListItemDeselected( wxListEvent& event ) { event.Skip(); } + virtual void OnHotkeyListItemSelected( wxListEvent& event ) { event.Skip(); } + virtual void OnAssignHotkeyButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnRemoveHotkeyButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnCancelButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + wxPanel* DefaultMountOptionsPage; + wxPanel* DefaultKeyfilesPage; + wxPanel* SecurityTokensPage; + wxPanel* HotkeysPage; + + PreferencesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Preferences"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + ~PreferencesDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class RandomPoolEnrichmentDialogBase + /////////////////////////////////////////////////////////////////////////////// + class RandomPoolEnrichmentDialogBase : public wxDialog + { + private: + + protected: + wxBoxSizer* MainSizer; + wxChoice* HashChoice; + wxStaticText* RandomPoolStaticText; + wxCheckBox* ShowRandomPoolCheckBox; + wxGauge* CollectedEntropy; + wxStaticText* MouseStaticText; + wxButton* ContinueButton; + + // Virtual event handlers, overide them in your derived class + virtual void OnMouseMotion( wxMouseEvent& event ) { event.Skip(); } + virtual void OnHashSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnShowRandomPoolCheckBoxClicked( wxCommandEvent& event ) { event.Skip(); } + + + public: + + RandomPoolEnrichmentDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Random Pool Enrichment"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + ~RandomPoolEnrichmentDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class SecurityTokenKeyfilesDialogBase + /////////////////////////////////////////////////////////////////////////////// + class SecurityTokenKeyfilesDialogBase : public wxDialog + { + private: + + protected: + wxListCtrl* SecurityTokenKeyfileListCtrl; + wxButton* ExportButton; + wxButton* DeleteButton; + wxButton* ImportButton; + wxButton* OKButton; + wxButton* CancelButton; + + // Virtual event handlers, overide them in your derived class + virtual void OnListItemActivated( wxListEvent& event ) { event.Skip(); } + virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } + virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } + virtual void OnExportButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnDeleteButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnImportButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + SecurityTokenKeyfilesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Security Token Keyfiles"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxDEFAULT_DIALOG_STYLE ); + ~SecurityTokenKeyfilesDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class VolumePropertiesDialogBase + /////////////////////////////////////////////////////////////////////////////// + class VolumePropertiesDialogBase : public wxDialog + { + private: + + protected: + wxListCtrl* PropertiesListCtrl; + wxStdDialogButtonSizer* StdButtons; + wxButton* StdButtonsOK; + + public: + + VolumePropertiesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Volume Properties"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + ~VolumePropertiesDialogBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class EncryptionOptionsWizardPageBase + /////////////////////////////////////////////////////////////////////////////// + class EncryptionOptionsWizardPageBase : public WizardPage + { + private: + + protected: + wxChoice* EncryptionAlgorithmChoice; + wxButton* TestButton; + wxStaticText* EncryptionAlgorithmStaticText; + wxHyperlinkCtrl* EncryptionAlgorithmHyperlink; + wxButton* BenchmarkButton; + wxChoice* HashChoice; + wxHyperlinkCtrl* HashHyperlink; + + // Virtual event handlers, overide them in your derived class + virtual void OnEncryptionAlgorithmSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnTestButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnEncryptionAlgorithmHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } + virtual void OnBenchmarkButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnHashHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } + + + public: + + EncryptionOptionsWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~EncryptionOptionsWizardPageBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class InfoWizardPageBase + /////////////////////////////////////////////////////////////////////////////// + class InfoWizardPageBase : public WizardPage + { + private: + + protected: + wxBoxSizer* InfoPageSizer; + wxStaticText* InfoStaticText; + + public: + + InfoWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~InfoWizardPageBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class KeyfilesPanelBase + /////////////////////////////////////////////////////////////////////////////// + class KeyfilesPanelBase : public wxPanel + { + private: + + protected: + wxListCtrl* KeyfilesListCtrl; + wxButton* AddFilesButton; + wxButton* AddDirectoryButton; + wxButton* AddSecurityTokenSignatureButton; + wxButton* RemoveButton; + wxButton* RemoveAllButton; + + // Virtual event handlers, overide them in your derived class + virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } + virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } + virtual void OnListSizeChanged( wxSizeEvent& event ) { event.Skip(); } + virtual void OnAddFilesButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnAddDirectoryButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnAddSecurityTokenSignatureButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnRemoveButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnRemoveAllButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + KeyfilesPanelBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~KeyfilesPanelBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class ProgressWizardPageBase + /////////////////////////////////////////////////////////////////////////////// + class ProgressWizardPageBase : public WizardPage + { + private: + + protected: + wxBoxSizer* ProgressSizer; + wxGauge* ProgressGauge; + wxButton* AbortButton; + wxStaticText* InfoStaticText; + + // Virtual event handlers, overide them in your derived class + virtual void OnAbortButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + ProgressWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~ProgressWizardPageBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class SelectDirectoryWizardPageBase + /////////////////////////////////////////////////////////////////////////////// + class SelectDirectoryWizardPageBase : public WizardPage + { + private: + + protected: + wxTextCtrl* DirectoryTextCtrl; + wxButton* BrowseButton; + wxStaticText* InfoStaticText; + + // Virtual event handlers, overide them in your derived class + virtual void OnDirectoryTextChanged( wxCommandEvent& event ) { event.Skip(); } + virtual void OnBrowseButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + SelectDirectoryWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~SelectDirectoryWizardPageBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class SingleChoiceWizardPageBase + /////////////////////////////////////////////////////////////////////////////// + class SingleChoiceWizardPageBase : public WizardPage + { + private: + + protected: + wxBoxSizer* OuterChoicesSizer; + wxBoxSizer* ChoicesSizer; + wxStaticText* InfoStaticText; + + public: + + SingleChoiceWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~SingleChoiceWizardPageBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class VolumeCreationProgressWizardPageBase + /////////////////////////////////////////////////////////////////////////////// + class VolumeCreationProgressWizardPageBase : public WizardPage + { + private: + + protected: + wxBoxSizer* KeySamplesUpperSizer; + wxBoxSizer* KeySamplesUpperInnerSizer; + wxStaticText* RandomPoolSampleStaticText; + wxCheckBox* DisplayKeysCheckBox; + wxStaticText* HeaderKeySampleStaticText; + wxStaticText* MasterKeySampleStaticText; + wxGauge* CollectedEntropy; + wxGauge* ProgressGauge; + wxButton* AbortButton; + wxStaticText* m_staticText31; + wxPanel* m_panel12; + wxStaticText* SizeDoneStaticText; + wxStaticText* m_staticText311; + wxPanel* m_panel121; + wxStaticText* SpeedStaticText; + wxStaticText* m_staticText312; + wxPanel* m_panel122; + wxStaticText* TimeLeftStaticText; + wxStaticText* InfoStaticText; + + // Virtual event handlers, overide them in your derived class + virtual void OnDisplayKeysCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnAbortButtonClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + VolumeCreationProgressWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~VolumeCreationProgressWizardPageBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class VolumeLocationWizardPageBase + /////////////////////////////////////////////////////////////////////////////// + class VolumeLocationWizardPageBase : public WizardPage + { + private: + + protected: + wxComboBox* VolumePathComboBox; + wxButton* SelectFileButton; + wxButton* SelectDeviceButton; + wxCheckBox* NoHistoryCheckBox; + wxStaticText* InfoStaticText; + + // Virtual event handlers, overide them in your derived class + virtual void OnVolumePathTextChanged( wxCommandEvent& event ) { event.Skip(); } + virtual void OnSelectFileButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnSelectDeviceButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnNoHistoryCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + VolumeLocationWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~VolumeLocationWizardPageBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class VolumeFormatOptionsWizardPageBase + /////////////////////////////////////////////////////////////////////////////// + class VolumeFormatOptionsWizardPageBase : public WizardPage + { + private: + + protected: + wxStaticText* m_staticText43; + wxChoice* FilesystemTypeChoice; + wxCheckBox* QuickFormatCheckBox; + wxStaticText* InfoStaticText; + + // Virtual event handlers, overide them in your derived class + virtual void OnFilesystemTypeSelected( wxCommandEvent& event ) { event.Skip(); } + virtual void OnQuickFormatCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + VolumeFormatOptionsWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~VolumeFormatOptionsWizardPageBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class VolumePasswordPanelBase + /////////////////////////////////////////////////////////////////////////////// + class VolumePasswordPanelBase : public wxPanel + { + private: + + protected: + wxGridBagSizer* GridBagSizer; + wxStaticText* PasswordStaticText; + wxTextCtrl* PasswordTextCtrl; + wxStaticText* ConfirmPasswordStaticText; + wxTextCtrl* ConfirmPasswordTextCtrl; + wxStaticText* VolumePimStaticText; + wxTextCtrl* VolumePimTextCtrl; + wxStaticText* VolumePimHelpStaticText; + wxCheckBox* PimCheckBox; + wxCheckBox* CacheCheckBox; + wxCheckBox* DisplayPasswordCheckBox; + wxCheckBox* UseKeyfilesCheckBox; + wxButton* KeyfilesButton; + wxBoxSizer* Pkcs5PrfSizer; + wxStaticText* Pkcs5PrfStaticText; + wxChoice* Pkcs5PrfChoice; + wxCheckBox* TrueCryptModeCheckBox; + wxStaticText* HeaderWipeCountText; + wxChoice* HeaderWipeCount; + wxBoxSizer* PasswordPlaceholderSizer; + + // Virtual event handlers, overide them in your derived class + virtual void OnTextChanged( wxCommandEvent& event ) { event.Skip(); } + virtual void OnPimChanged( wxCommandEvent& event ) { event.Skip(); } + virtual void OnUsePimCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnDisplayPasswordCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnUseKeyfilesCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnKeyfilesButtonClick( wxCommandEvent& event ) { event.Skip(); } + virtual void OnKeyfilesButtonRightDown( wxMouseEvent& event ) { event.Skip(); } + virtual void OnKeyfilesButtonRightClick( wxMouseEvent& event ) { event.Skip(); } + virtual void OnTrueCryptModeChecked( wxCommandEvent& event ) { event.Skip(); } + + + public: + + VolumePasswordPanelBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~VolumePasswordPanelBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class VolumePasswordWizardPageBase + /////////////////////////////////////////////////////////////////////////////// + class VolumePasswordWizardPageBase : public WizardPage + { + private: + + protected: + wxBoxSizer* PasswordPanelSizer; + wxStaticText* InfoStaticText; + + public: + + VolumePasswordWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~VolumePasswordWizardPageBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class VolumePimWizardPageBase + /////////////////////////////////////////////////////////////////////////////// + class VolumePimWizardPageBase : public WizardPage + { + private: + + protected: + wxBoxSizer* PimPanelSizer; + wxBoxSizer* PimSizer; + wxStaticText* VolumePimStaticText; + wxTextCtrl* VolumePimTextCtrl; + wxStaticText* VolumePimHelpStaticText; + wxCheckBox* DisplayPimCheckBox; + wxStaticText* InfoStaticText; + + // Virtual event handlers, overide them in your derived class + virtual void OnPimChanged( wxCommandEvent& event ) { event.Skip(); } + virtual void OnDisplayPimCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } + + + public: + + VolumePimWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~VolumePimWizardPageBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class VolumeSizeWizardPageBase + /////////////////////////////////////////////////////////////////////////////// + class VolumeSizeWizardPageBase : public WizardPage + { + private: + + protected: + wxTextCtrl* VolumeSizeTextCtrl; + wxChoice* VolumeSizePrefixChoice; + wxStaticText* FreeSpaceStaticText; + wxStaticText* InfoStaticText; + + // Virtual event handlers, overide them in your derived class + virtual void OnVolumeSizeTextChanged( wxCommandEvent& event ) { event.Skip(); } + virtual void OnVolumeSizePrefixSelected( wxCommandEvent& event ) { event.Skip(); } + + + public: + + VolumeSizeWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + ~VolumeSizeWizardPageBase(); + + }; + + /////////////////////////////////////////////////////////////////////////////// + /// Class WaitDialogBase + /////////////////////////////////////////////////////////////////////////////// + class WaitDialogBase : public wxDialog + { + private: + + protected: + wxStaticText* WaitStaticText; + wxGauge* WaitProgessBar; + + // Virtual event handlers, overide them in your derived class + virtual void OnWaitDialogClose( wxCloseEvent& event ) { event.Skip(); } + virtual void OnWaitDialogInit( wxInitDialogEvent& event ) { event.Skip(); } + + + public: + + WaitDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxCAPTION ); + ~WaitDialogBase(); + + }; + +} // namespace VeraCrypt + +#endif //__FORMS_H__ diff --git a/src/Main/Forms/TrueCrypt.fbp b/src/Main/Forms/TrueCrypt.fbp index b71d80d1..a74a2a5b 100644 --- a/src/Main/Forms/TrueCrypt.fbp +++ b/src/Main/Forms/TrueCrypt.fbp @@ -1,28738 +1,28738 @@ - - - - - - C++ - 1 - source_name - 0 - 0 - res - UTF-8 - connect - Forms - 1000 - none - 1 - VeraCrypt - "VeraCrypt" - . - #include "System.h" - 1 - 1 - 1 - 1 - UI - 1 - 0 - - 0 - wxAUI_MGR_DEFAULT - - wxBOTH - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - -1,496 - MainFrameBase - - -1,-1 - wxCAPTION|wxCLOSE_BOX|wxMINIMIZE_BOX|wxSYSTEM_MENU - - VeraCrypt - - - - wxTAB_TRAVERSAL - 1 - OnActivate - - - - - - - - - OnClose - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1 - 1 - - - 0 - wxID_ANY - MainMenuBar - - - MainMenuBar - protected - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - &Volumes - VolumesMenu - protected - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Create New Volume... - CreateNewVolumeMenuItem - none - - - OnCreateVolumeButtonClick - - - - m_separator1 - none - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Mount Volume - MountVolumeMenuItem - protected - - - OnMountVolumeMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Auto-Mount All Device-Hosted Volumes - AutoMountDevicesMenuItem - none - - - OnMountAllDevicesButtonClick - - - - m_separator2 - none - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Dismount Volume - DismountVolumeMenuItem - protected - - - OnDismountVolumeMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Dismount All Mounted Volumes - DismountAllMenuItem - protected - - - OnDismountAllButtonClick - - - - m_separator3 - none - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Change Volume Password... - ChangePasswordMenuItem - none - - - OnChangePasswordMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Change Header Key Derivation Algorithm... - ChangePkcs5PrfMenuItem - none - - - OnChangePkcs5PrfMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Add/Remove Keyfiles to/from Volume... - ChangeKeyfilesMenuItem - none - - - OnChangeKeyfilesMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Remove All Keyfiles from Volume... - RemoveKeyfilesMenuItem - none - - - OnRemoveKeyfilesMenuItemSelected - - - - m_separator4 - none - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Volume Properties... - VolumePropertiesMenuItem - protected - - - OnVolumePropertiesButtonClick - - - - - &Favorites - FavoritesMenu - protected - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Add Selected Volume to Favorites... - AddToFavoritesMenuItem - protected - - - OnAddToFavoritesMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Add All Mounted Volumes to Favorites... - AddAllMountedToFavoritesMenuItem - protected - - - OnAddAllMountedToFavoritesMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Organize Favorite Volumes... - OrganizeFavoritesMenuItem - none - - - OnOrganizeFavoritesMenuItemSelected - - - - m_separator5 - none - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Mount Favorite Volumes - MountAllFavoritesMenuItem - none - - - OnMountAllFavoritesMenuItemSelected - - - - m_separator6 - none - - - - T&ools - ToolsMenu - protected - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Benchmark... - BenchmarkMenuItem - none - - - OnBenchmarkMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Test Vectors... - EncryptionTestMenuItem - none - - - OnEncryptionTestMenuItemSelected - - - - m_separator7 - none - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Volume Creation Wizard - VolumeCreationWizardMenuItem - none - - - OnCreateVolumeButtonClick - - - - m_separator8 - none - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Backup Volume Header... - BackupVolumeHeadersMenuItem - protected - - - OnBackupVolumeHeadersMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Restore Volume Header... - RestoreVolumeHeaderMenuItem - protected - - - OnRestoreVolumeHeaderMenuItemSelected - - - - m_separator9 - none - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Keyfile Generator - CreateKeyfileMenuItem - none - - - OnCreateKeyfileMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Manage Security Token Keyfiles... - ManageSecurityTokenKeyfilesMenuItem - none - - - OnManageSecurityTokenKeyfilesMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Close All Security Token Sessions - CloseAllSecurityTokenSessionsMenuItem - none - - - OnCloseAllSecurityTokenSessionsMenuItemSelected - - - - m_separator10 - none - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Wipe Cached Passwords - WipeCachedPasswordsMenuItem - protected - - - OnWipeCacheButtonClick - - - - - Settin&gs - SettingsMenu - protected - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Hotkeys... - HotkeysMenuItem - protected - - - OnHotkeysMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Default Keyfiles... - DefaultKeyfilesMenuItem - none - - - OnDefaultKeyfilesMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Default Mount Parameters... - DefaultMountParametersMenuItem - none - - - OnDefaultMountParametersMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Security Tokens... - SecurityTokenPreferencesMenuItem - none - - - OnSecurityTokenPreferencesMenuItemSelected - - - - m_separator11 - none - - - - 0 - 1 - - wxID_PREFERENCES - wxITEM_NORMAL - &Preferences... - PreferencesMenuItem - protected - - - OnPreferencesMenuItemSelected - - - - - &Help - HelpMenu - protected - - - 0 - 1 - - wxID_HELP - wxITEM_NORMAL - User's Guide - UserGuideMenuItem - none - - - OnUserGuideMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Online Help - OnlineHelpMenuItem - none - - - OnOnlineHelpMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Beginner's Tutorial - BeginnersTutorialMenuItem - none - - - OnBeginnersTutorialMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Frequently Asked Questions - FaqMenuItem - none - - - OnFaqMenuItemSelected - - - - m_separator12 - none - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - VeraCrypt Website - WebsiteMenuItem - none - - - OnWebsiteMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Downloads - DownloadsMenuItem - none - - - OnDownloadsMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - News - NewsMenuItem - none - - - OnNewsMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Version History - VersionHistoryMenuItem - none - - - OnVersionHistoryMenuItemSelected - - - - m_separator13 - none - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Donate - DonateMenuItem - none - - - OnDonateMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Contact - ContactMenuItem - none - - - OnContactMenuItemSelected - - - - - 0 - 1 - - wxID_ANY - wxITEM_NORMAL - Legal Notices - LegalNoticesMenuItem - none - - - OnLegalNoticesMenuItemSelected - - - - - 0 - 1 - - wxID_ABOUT - wxITEM_NORMAL - About - AboutMenuItem - none - - - OnAboutMenuItemSelected - - - - - - - bSizer1 - wxVERTICAL - none - - 0 - wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - MainPanel - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer2 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer48 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - wxID_ANY - - - sbSizer1 - wxVERTICAL - none - - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - SlotListCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - wxSUNKEN_BORDER - - - - - - - - - - - - - - - - - - - - - - - - OnListItemActivated - OnListItemDeselected - - - OnListItemRightClick - OnListItemSelected - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - wxID_ANY - - - LowStaticBoxSizer - wxVERTICAL - protected - - - 2 - wxEXPAND|wxTOP - 0 - - - HigherButtonSizer - wxVERTICAL - protected - - - - 5 - wxEXPAND|wxRIGHT|wxLEFT - 0 - - 3 - 0 - - gSizer1 - none - 1 - 0 - - 5 - - 0 - - 138,34 - bSizer17 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Create Volume - - 0 - - - 0 - -1,-1 - 1 - CreateVolumeButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnCreateVolumeButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_HORIZONTAL - 0 - - 138,34 - bSizer18 - wxVERTICAL - none - - 5 - wxALL|wxALIGN_CENTER_HORIZONTAL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Volume Properties... - - 0 - - - 0 - -1,-1 - 1 - VolumePropertiesButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnVolumePropertiesButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_RIGHT - 0 - - 138,34 - bSizer19 - wxVERTICAL - none - - 5 - wxALL|wxALIGN_RIGHT|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Wipe Cache - - 0 - - - 0 - -1,-1 - 1 - WipeCacheButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnWipeCacheButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - - 0 - - 0 - protected - 0 - - - - 5 - wxEXPAND - 1 - - wxID_ANY - Volume - - VolumeStaticBoxSizer - wxVERTICAL - protected - - - 4 - wxEXPAND|wxALL - 1 - - - wxBOTH - 1 - 0 - 0 - - VolumeGridBagSizer - wxFLEX_GROWMODE_SPECIFIED - protected - 0 - - 5 - 1 - 0 - wxALIGN_CENTER_VERTICAL|wxALL - 0 - 2 - - 1 - 1 - 1 - 1 - - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - 42,52 - 1 - LogoBitmap - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxSUNKEN_BORDER - - - - - - - - - OnLogoBitmapClick - - - - - - - - - - - - - - - - - - 5 - 2 - 1 - wxEXPAND|wxALL - 0 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - VolumePathComboBox - 1 - - - protected - 1 - - Resizable - -1 - 1 - - wxCB_DROPDOWN - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 3 - wxEXPAND - 0 - 1 - - 138,34 - bSizer191 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Select &File... - - 0 - - - 0 - -1,-1 - 1 - SelectFileButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnSelectFileButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 1 - wxBOTTOM|wxRIGHT|wxLEFT - 1 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Never save history - - 0 - - - 0 - - 1 - NoHistoryCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnNoHistoryCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 2 - wxALIGN_RIGHT - 1 - 1 - - 138,34 - bSizer20 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Volume &Tools... - - 0 - - - 0 - -1,-1 - 1 - VolumeToolsButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnVolumeToolsButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 3 - wxEXPAND - 1 - 1 - - 138,34 - bSizer21 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Select D&evice... - - 0 - - - 0 - -1,-1 - 1 - SelectDeviceButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnSelectDeviceButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - - 0 - - 0 - protected - 0 - - - - 5 - wxEXPAND - 0 - - 4 - 0 - - gSizer2 - none - 1 - 0 - - 0 - wxEXPAND - 1 - - wxID_ANY - - 139,-1 - sbSizer4 - wxVERTICAL - none - - - 2 - wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Mount - - 0 - - - 0 - -1,32 - 1 - VolumeButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnVolumeButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_HORIZONTAL|wxEXPAND - 1 - - wxID_ANY - - -1,-1 - sbSizer41 - wxVERTICAL - none - - - 2 - wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Auto-Mount Devices - - 0 - - - 0 - -1,32 - 1 - MountAllDevicesButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnMountAllDevicesButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_HORIZONTAL|wxEXPAND - 1 - - wxID_ANY - - -1,-1 - sbSizer42 - wxVERTICAL - none - - - 2 - wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Di&smount All - - 0 - - - 0 - -1,32 - 1 - DismountAllButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnDismountAllButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_RIGHT|wxEXPAND - 1 - - wxID_ANY - - -1,-1 - sbSizer43 - wxVERTICAL - none - - - 2 - wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - E&xit - - 0 - - - 0 - -1,32 - 1 - ExitButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnExitButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - 800,500 - WizardFrameBase - - -1,-1 - wxCAPTION|wxCLOSE_BOX|wxMINIMIZE_BOX|wxSYSTEM_MENU - - - - - - wxTAB_TRAVERSAL - 1 - OnActivate - - - - - - - - - OnClose - - - - - - - - - - - - - - - - - - - - - - - - - - - - MainSizer - wxVERTICAL - protected - - 5 - wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - MainPanel - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - OnMouseMotion - - - - - - - - - - - - bSizer63 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer64 - wxVERTICAL - none - - 5 - wxEXPAND|wxRIGHT|wxLEFT - 1 - - wxID_ANY - - - sbSizer27 - wxHORIZONTAL - none - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - WizardBitmap - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxLEFT - 1 - - - bSizer66 - wxVERTICAL - none - - 5 - wxLEFT - 0 - - - bSizer126 - wxHORIZONTAL - none - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - Times New Roman,90,90,16,70,0 - 0 - 0 - wxID_ANY - Page Title - - 0 - - - 0 - - 1 - PageTitleStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxTOP|wxBOTTOM|wxLEFT - 1 - - - PageSizer - wxVERTICAL - protected - - - - - - - - 5 - wxEXPAND|wxALIGN_RIGHT|wxALL - 0 - - - bSizer70 - wxHORIZONTAL - none - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - 5 - wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_HELP - &Help - - 0 - - - 0 - - 1 - HelpButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnHelpButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxLEFT|wxALIGN_RIGHT - 0 - - 0 - protected - 0 - - - - 5 - wxTOP|wxBOTTOM|wxLEFT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - < &Prev - - 0 - - - 0 - - 1 - PreviousButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnPreviousButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Next > - - 0 - - - 0 - - 1 - NextButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - wxWANTS_CHARS - OnNextButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxLEFT|wxALIGN_RIGHT - 0 - - 0 - protected - 0 - - - - 5 - wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_CANCEL - Cancel - - 0 - - - 0 - - 1 - CancelButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnCancelButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - AboutDialogBase - - - wxDEFAULT_DIALOG_STYLE - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer116 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer117 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - -1,78 - bSizer120 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - 10,108,206 - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - m_panel14 - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer121 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - 0 - protected - 0 - - - - 8 - wxEXPAND|wxLEFT - 0 - - - bSizer122 - wxVERTICAL - none - - 10 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - LogoBitmap - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 15 - wxALL|wxEXPAND - 1 - - - bSizer118 - wxVERTICAL - none - - 5 - wxEXPAND|wxLEFT - 1 - - - bSizer123 - wxVERTICAL - none - - 5 - wxTOP|wxRIGHT|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - VersionStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 3 - wxTOP - 0 - - 0 - protected - 0 - - - - 5 - wxBOTTOM|wxRIGHT|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - CopyrightStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 3 - wxTOP - 0 - - 0 - protected - 0 - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxSYS_COLOUR_WINDOWTEXT - wxID_ANY - - - 0 - - - 0 - - 1 - WebsiteHyperlink - wxSYS_COLOUR_WINDOWTEXT - 1 - - - protected - 1 - - Resizable - 1 - - wxHL_DEFAULT_STYLE - - 0 - - . - wxSYS_COLOUR_WINDOWTEXT - - - - - - - OnWebsiteHyperlinkClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxBOTTOM - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - m_staticline3 - 1 - - - protected - 1 - - Resizable - 1 - - wxLI_HORIZONTAL - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - - 0 - - 1 - CreditsTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxTE_MULTILINE|wxTE_READONLY - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - wxSUNKEN_BORDER - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxTOP - 0 - - 0 - protected - 0 - - - - 3 - wxEXPAND|wxTOP|wxBOTTOM - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - m_staticline4 - 1 - - - protected - 1 - - Resizable - 1 - - wxLI_HORIZONTAL - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxBOTTOM - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - m_staticline5 - 1 - - - protected - 1 - - Resizable - 1 - - wxLI_HORIZONTAL - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 6 - wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT - 0 - - - bSizer119 - wxHORIZONTAL - none - - 5 - wxEXPAND|wxALL - 1 - - 0 - protected - 0 - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_OK - OK - - 0 - - - 0 - - 1 - OKButton - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxLEFT - 0 - - 0 - protected - 0 - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - BenchmarkDialogBase - - - wxDEFAULT_DIALOG_STYLE - - VeraCrypt - Encryption Algorithm Benchmark - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer153 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer154 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - - bSizer155 - wxHORIZONTAL - none - - 5 - wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Buffer Size: - - 0 - - - 0 - - 1 - m_staticText54 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - BufferSizeChoice - 1 - - - protected - 1 - - Resizable - 0 - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND | wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - m_staticline6 - 1 - - - none - 1 - - Resizable - 1 - - wxLI_HORIZONTAL - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - - bSizer156 - wxHORIZONTAL - none - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - BenchmarkListCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxLC_NO_SORT_HEADER|wxLC_REPORT - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - wxSUNKEN_BORDER - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - - RightSizer - wxVERTICAL - protected - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_OK - Benchmark - - 0 - - - 0 - - 1 - BenchmarkButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnBenchmarkButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_CANCEL - Close - - 0 - - - 0 - - 1 - CancelButton - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxTOP|wxBOTTOM - 0 - - 0 - protected - 0 - - - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - -1,-1 - - 0 - - 1 - BenchmarkNoteStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - ChangePasswordDialogBase - - - wxDEFAULT_DIALOG_STYLE - - - - wxWS_EX_VALIDATE_RECURSIVELY - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer30 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer31 - wxHORIZONTAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer32 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - wxID_ANY - Current - - CurrentSizer - wxVERTICAL - protected - - - 5 - wxALIGN_LEFT - 0 - - - CurrentPasswordPanelSizer - wxVERTICAL - protected - - - - - - 5 - wxTOP|wxEXPAND - 0 - - wxID_ANY - New - - NewSizer - wxVERTICAL - protected - - - 5 - wxALIGN_LEFT - 0 - - - NewPasswordPanelSizer - wxVERTICAL - protected - - - - - - - - 5 - - 0 - - - bSizer33 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_OK - OK - - 0 - - - 0 - - 1 - OKButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnOKButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_CANCEL - Cancel - - 0 - - - 0 - - 1 - CancelButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - wxBOTH - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - -1,-1 - DeviceSelectionDialogBase - - -1,-1 - wxDEFAULT_DIALOG_STYLE - - Select a Partition or Device - - wxWS_EX_VALIDATE_RECURSIVELY - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer3 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer4 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - DeviceListCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - wxSUNKEN_BORDER - - - - - - - - - - - - - - - - - - - - - - - - OnListItemActivated - OnListItemDeselected - - - - OnListItemSelected - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - 0 - 1 - 0 - 0 - 0 - 1 - 0 - 0 - - StdButtons - protected - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - EncryptionTestDialogBase - - - wxDEFAULT_DIALOG_STYLE - - VeraCrypt - Test Vectors - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer132 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer133 - wxVERTICAL - none - - 5 - wxALIGN_CENTER_HORIZONTAL - 0 - - - bSizer134 - wxHORIZONTAL - none - - 5 - wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Encryption algorithm: - - 0 - - - 0 - - 1 - m_staticText41 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - EncryptionAlgorithmChoice - 1 - - - protected - 1 - - Resizable - 0 - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnEncryptionAlgorithmSelected - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - XTS mode - - 0 - - - 0 - - 1 - XtsModeCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnXtsModeCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Key (hexadecimal) - - sbSizer38 - wxVERTICAL - none - - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - Courier,90,90,-1,70,0 - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - KeyTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - - bSizer135 - wxHORIZONTAL - none - - 5 - wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Key size: - - 0 - - - 0 - - 1 - m_staticText43 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - KeySizeStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 1 - - wxID_ANY - XTS mode - - sbSizer39 - wxVERTICAL - none - - - 5 - wxTOP|wxRIGHT|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Secondary key (hexadecimal) - - 0 - - - 0 - - 1 - m_staticText45 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - Courier,90,90,-1,70,0 - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - SecondaryKeyTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxTOP|wxRIGHT|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Data unit number (64-bit, data unit size is 512 bytes) - - 0 - - - 0 - - 1 - m_staticText46 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - DataUnitNumberTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxTOP|wxRIGHT|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Block number: - - 0 - - - 0 - - 1 - m_staticText47 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - BlockNumberTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Plaintext (hexadecimal) - - sbSizer40 - wxVERTICAL - none - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - Courier,90,90,-1,70,0 - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - PlainTextTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Ciphertext (hexadecimal) - - sbSizer41 - wxVERTICAL - none - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - Courier,90,90,-1,70,0 - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - CipherTextTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - - bSizer136 - wxHORIZONTAL - none - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Encrypt - - 0 - - - 0 - - 1 - EncryptButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnEncryptButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Decrypt - - 0 - - - 0 - - 1 - DecryptButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnDecryptButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Auto-Test All - - 0 - - - 0 - - 1 - AutoTestAllButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnAutoTestAllButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Reset - - 0 - - - 0 - - 1 - ResetButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnResetButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_CANCEL - Close - - 0 - - - 0 - - 1 - CloseButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - FavoriteVolumesDialogBase - - - wxDEFAULT_DIALOG_STYLE - - Favorite Volumes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer57 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer60 - wxHORIZONTAL - none - - 5 - wxEXPAND - 1 - - - bSizer58 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - FavoritesListCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - wxSUNKEN_BORDER - - - - - - - - - - - - - - - - - - - - - - - - - OnListItemDeselected - - - - OnListItemSelected - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxRIGHT|wxLEFT - 0 - - 4 - 0 - - gSizer5 - none - 1 - 0 - - 5 - wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Move &Up - - 0 - - - 0 - - 1 - MoveUpButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnMoveUpButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Move &Down - - 0 - - - 0 - - 1 - MoveDownButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnMoveDownButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_RIGHT|wxEXPAND|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Remove - - 0 - - - 0 - - 1 - RemoveButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnRemoveButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Remove &All - - 0 - - - 0 - - 1 - RemoveAllButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnRemoveAllButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - 5 - wxBOTH - 2 - - 0 - - fgSizer4 - wxFLEX_GROWMODE_SPECIFIED - none - 1 - 0 - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - - - - - 5 - wxEXPAND - 0 - - - bSizer59 - wxVERTICAL - none - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_OK - OK - - 0 - - - 0 - - 1 - OKButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnOKButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_CANCEL - Cancel - - 0 - - - 0 - - 1 - CancelButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - KeyfilesDialogBase - - - wxDEFAULT_DIALOG_STYLE - - Select Keyfiles - - wxWS_EX_VALIDATE_RECURSIVELY - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer26 - wxVERTICAL - none - - 5 - wxTOP|wxRIGHT|wxLEFT - 1 - - - UpperSizer - wxHORIZONTAL - protected - - 5 - wxEXPAND - 1 - - - PanelSizer - wxVERTICAL - protected - - - - 5 - wxEXPAND - 0 - - - bSizer22 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_OK - OK - - 0 - - - 0 - - 1 - OKButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_CANCEL - Cancel - - 0 - - - 0 - - 1 - CancelButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - WarningStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT - 0 - - - bSizer23 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - KeyfilesNoteSizer - wxVERTICAL - protected - - 5 - wxEXPAND | wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - m_staticline1 - 1 - - - none - 1 - - Resizable - 1 - - wxLI_HORIZONTAL - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - -1,-1 - - 0 - - 1 - KeyfilesNoteStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND | wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - m_staticline2 - 1 - - - none - 1 - - Resizable - 1 - - wxLI_HORIZONTAL - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - 2 - wxBOTH - 0 - - 0 - - fgSizer2 - wxFLEX_GROWMODE_SPECIFIED - none - 1 - 0 - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxSYS_COLOUR_WINDOWTEXT - wxID_ANY - More information on keyfiles - - 0 - - - 0 - - 1 - KeyfilesHyperlink - wxSYS_COLOUR_WINDOWTEXT - 1 - - - protected - 1 - - Resizable - 1 - - wxHL_DEFAULT_STYLE - - 0 - - - wxSYS_COLOUR_WINDOWTEXT - - - - - - - OnKeyfilesHyperlinkClick - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Generate Random Keyfile... - - 0 - - - 0 - - 1 - CreateKeyfileButtton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnCreateKeyfileButttonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - KeyfileGeneratorDialogBase - - - wxDEFAULT_DIALOG_STYLE - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - OnMouseMotion - - - - - - - - - - - - MainSizer - wxVERTICAL - protected - - 5 - wxEXPAND|wxALL - 1 - - - bSizer144 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - - bSizer145 - wxHORIZONTAL - none - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mixing PRF: - - 0 - - - 0 - - 1 - m_staticText49 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - HashChoice - 1 - - - protected - 1 - - Resizable - 0 - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnHashSelected - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - - - 5 - wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT - 1 - - wxID_ANY - - - sbSizer43 - wxVERTICAL - none - - - 5 - wxEXPAND|wxTOP - 0 - - - bSizer147 - wxHORIZONTAL - none - - 5 - wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Random Pool: - - 0 - - - 0 - - 1 - m_staticText52 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - Courier New,90,90,-1,70,0 - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - RandomPoolStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Show - - 0 - - - 0 - - 1 - ShowRandomPoolCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnShowRandomPoolCheckBoxClicked - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - 5 - wxBOTTOM|wxEXPAND|wxTOP - 0 - - wxID_ANY - Randomness Collected From Mouse Movements - - sbSizer45 - wxVERTICAL - none - - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - CollectedEntropy - 1 - - - protected - 1 - - 2560 - Resizable - 1 - - wxGA_HORIZONTAL|wxGA_SMOOTH - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - 5 - wxALL|wxALIGN_CENTER_HORIZONTAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the keyfile. - - 0 - - - 0 - - 1 - MouseStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - - - 5 - wxALL|wxEXPAND - 1 - - - bSizer162 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - 3 - wxBOTH - 2 - - 0 - - fgSizer8 - wxFLEX_GROWMODE_SPECIFIED - none - 3 - 0 - - 5 - wxALIGN_CENTER_VERTICAL|wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Number of keyfiles: - - 0 - - - 0 - - 1 - m_staticText60 - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - 1 - 9999999 - - 0 - - 1 - - 0 - - 1 - NumberOfKeyfiles - 1 - - - protected - 1 - - Resizable - 1 - - wxSP_ARROW_KEYS - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND | wxALL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - m_panel18 - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_VERTICAL|wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Keyfiles size (in Bytes): - - 0 - - - 0 - - 1 - m_staticText63 - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - 64 - 1048576 - - 0 - - 64 - - 0 - - 1 - KeyfilesSize - 1 - - - protected - 1 - - Resizable - 1 - - wxSP_ARROW_KEYS - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_VERTICAL|wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Random size (64 <-> 1048576) - - 0 - - - 0 - - 1 - RandomSizeCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnRandomSizeCheckBoxClicked - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_VERTICAL|wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Keyfiles base name: - - 0 - - - 0 - - 1 - m_staticText65 - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - - 0 - - 1 - KeyfilesBaseName - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND | wxALL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - m_panel19 - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - - bSizer146 - wxHORIZONTAL - none - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Generate and Save Keyfile... - - 0 - - - 0 - - 1 - GenerateButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnGenerateButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_CANCEL - Close - - 0 - - - 0 - - 1 - m_button61 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - LegalNoticesDialogBase - - - wxDEFAULT_DIALOG_STYLE - - VeraCrypt - Legal Notices - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer114 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer115 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - - 0 - - 1 - LegalNoticesTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxTE_MULTILINE|wxTE_READONLY - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_HORIZONTAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_OK - OK - - 0 - - - 0 - - 1 - OKButton - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - wxBOTH - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - MountOptionsDialogBase - - -1,-1 - wxDEFAULT_DIALOG_STYLE - - Enter VeraCrypt Volume Password - - wxWS_EX_VALIDATE_RECURSIVELY - - - - - - - - - - - - - - - - - - OnInitDialog - - - - - - - - - - - - - - - - - - - - - - - MainSizer - wxVERTICAL - protected - - 5 - wxEXPAND - 1 - - - bSizer19 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 0 - - - bSizer14 - wxHORIZONTAL - none - - 5 - wxEXPAND - 1 - - - PasswordSizer - wxVERTICAL - protected - - - - 5 - wxEXPAND - 0 - - - bSizer9 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_OK - OK - - 0 - - - 0 - - 1 - OKButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnOKButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_CANCEL - Cancel - - 0 - - - 0 - - 1 - CancelButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxTOP|wxEXPAND - 1 - - 0 - protected - 0 - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Op&tions - - 0 - - - 0 - - 1 - OptionsButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnOptionsButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - - bSizer6 - wxVERTICAL - none - - 5 - wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - OptionsPanel - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - wxID_ANY - - - OptionsSizer - wxVERTICAL - protected - - - 5 - wxTOP - 0 - - 0 - protected - 0 - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mount volume as &read-only - - 0 - - - 0 - - 1 - ReadOnlyCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnReadOnlyCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mount volume as removable &medium - - 0 - - - 0 - - 1 - RemovableCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mount partition &using system encryption (preboot authentication) - - 0 - - - 0 - - 1 - PartitionInSystemEncryptionScopeCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 1 - - wxID_ANY - Hidden Volume Protection - - ProtectionSizer - wxVERTICAL - protected - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Protect hidden volume when mounting outer volume - - 0 - - - 0 - - 1 - ProtectionCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnProtectionCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxLEFT - 1 - - - ProtectionPasswordSizer - wxVERTICAL - protected - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxSYS_COLOUR_WINDOWTEXT - wxID_ANY - What is hidden volume protection? - - 0 - - - 0 - - 1 - ProtectionHyperlinkCtrl - wxSYS_COLOUR_WINDOWTEXT - 1 - - - protected - 1 - - Resizable - 1 - - wxHL_DEFAULT_STYLE - - 0 - - - wxSYS_COLOUR_WINDOWTEXT - - - - - - - OnProtectionHyperlinkClick - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - - FilesystemSizer - wxVERTICAL - protected - - 5 - wxEXPAND | wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - m_panel8 - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - wxID_ANY - Filesystem - - sbSizer28 - wxVERTICAL - none - - - 5 - wxEXPAND|wxBOTTOM - 0 - - - bSizer54 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer55 - wxVERTICAL - none - - 5 - wxTOP|wxRIGHT|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Do &not mount - - 0 - - - 0 - - 1 - NoFilesystemCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnNoFilesystemCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - 0,0 - wxBOTH - 1 - - 0 - - FilesystemOptionsSizer - wxFLEX_GROWMODE_SPECIFIED - protected - 0 - - 5 - 1 - 0 - wxEXPAND|wxTOP - 0 - 1 - - - FilesystemSpacer - wxVERTICAL - protected - - - - 5 - 1 - 0 - wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT - 1 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mount at directory: - - 0 - - - 0 - - 1 - MountPointTextCtrlStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 1 - wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND - 1 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - MountPointTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 2 - wxALIGN_CENTER_VERTICAL|wxRIGHT|wxLEFT - 1 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Se&lect... - - 0 - - - 0 - - 1 - MountPointButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnMountPointButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 0 - wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxLEFT - 2 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mount options: - - 0 - - - 0 - - 1 - FilesystemOptionsStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 2 - 1 - wxALIGN_CENTER_VERTICAL|wxEXPAND|wxTOP|wxRIGHT|wxLEFT - 2 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - FilesystemOptionsTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - NewSecurityTokenKeyfileDialogBase - - - wxDEFAULT_DIALOG_STYLE - - New Security Token Keyfile Properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer143 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer144 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - wxID_ANY - - - sbSizer42 - wxVERTICAL - none - - - 5 - wxEXPAND|wxTOP - 1 - - 2 - wxBOTH - - - 0 - - fgSizer7 - wxFLEX_GROWMODE_SPECIFIED - none - 2 - 0 - - 5 - wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Security token: - - 0 - - - 0 - - 1 - m_staticText47 - 1 - - - none - 1 - - Resizable - 1 - - wxALIGN_RIGHT - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - SecurityTokenChoice - 1 - - - protected - 1 - - Resizable - 0 - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Keyfile name: - - 0 - - - 0 - - 1 - m_staticText48 - 1 - - - none - 1 - - Resizable - 1 - - wxALIGN_RIGHT - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - KeyfileNameTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - OnKeyfileNameChanged - - - - - - - - - - - - 5 - wxALIGN_RIGHT|wxALL - 0 - - 0 - 1 - 0 - 0 - 0 - 1 - 0 - 0 - - StdButtons - protected - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - PreferencesDialogBase - - - wxDEFAULT_DIALOG_STYLE - - Preferences - - wxWS_EX_VALIDATE_RECURSIVELY - - - - - - - - - - - - OnClose - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer32 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer41 - wxVERTICAL - none - - 5 - wxEXPAND | wxALL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - PreferencesNotebook - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Security - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - SecurityPage - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer44 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer33 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Auto-Dismount - - AutoDismountSizer - wxVERTICAL - protected - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Dismount All Volumes When - - sbSizer13 - wxVERTICAL - none - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - User logs off - - 0 - - - 0 - - 1 - DismountOnLogOffCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Screen saver is launched - - 0 - - - 0 - - 1 - DismountOnScreenSaverCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnDismountOnScreenSaverCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - System is entering power saving mode - - 0 - - - 0 - - 1 - DismountOnPowerSavingCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnDismountOnPowerSavingCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - - bSizer34 - wxHORIZONTAL - none - - 5 - wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Auto-dismount volume after no data has been read/written to it for - - 0 - - - 0 - - 1 - DismountOnInactivityCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_VERTICAL|wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - 1 - 9999 - - 0 - - 1 - - 0 - 60,-1 - 1 - DismountOnInactivitySpinCtrl - 1 - - - protected - 1 - - Resizable - 1 - -1,-1 - wxSP_ARROW_KEYS - - 0 - - 1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - minutes - - 0 - - - 0 - - 1 - m_staticText5 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Force auto-dismount even if volume contains open files or directories - - 0 - - - 0 - - 1 - ForceAutoDismountCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnForceAutoDismountCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Filesystem - - FilesystemSecuritySizer - wxVERTICAL - protected - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Preserve modification timestamp of file containers - - 0 - - - 0 - - 1 - PreserveTimestampsCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnPreserveTimestampsCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Password Cache - - sbSizer14 - wxVERTICAL - none - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Wipe after VeraCrypt window has been closed - - 0 - - - 0 - - 1 - WipeCacheOnCloseCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Wipe after volume has been auto-dismounted - - 0 - - - 0 - - 1 - WipeCacheOnAutoDismountCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Mount Options - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - DefaultMountOptionsPage - 1 - - - public - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer46 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer35 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Default Mount Options - - sbSizer15 - wxVERTICAL - none - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mount volumes as read-only - - 0 - - - 0 - - 1 - MountReadOnlyCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mount volumes as removable media - - 0 - - - 0 - - 1 - MountRemovableCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Cache passwords in memory - - 0 - - - 0 - - 1 - CachePasswordsCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - TrueCrypt Mode - - 0 - - - 0 - - 1 - TrueCryptModeCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - - bSizer163 - wxHORIZONTAL - none - - 5 - wxALIGN_CENTER_VERTICAL|wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - PKCS5-PRF: - - 0 - - - 0 - - 1 - Pkcs5PrfStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_VERTICAL|wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - Pkcs5PrfChoice - 1 - - - protected - 1 - - Resizable - 0 - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Filesystem - - FilesystemSizer - wxVERTICAL - protected - - - 5 - wxEXPAND - 1 - - 2 - wxBOTH - 1 - - 0 - - fgSizer3 - wxFLEX_GROWMODE_SPECIFIED - none - 1 - 0 - - 5 - wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mount options: - - 0 - - - 0 - - 1 - m_staticText6 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - FilesystemOptionsTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Background Task - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - BackgroundTaskPanel - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer61 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer62 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - VeraCrypt Background Task - - sbSizer18 - wxVERTICAL - none - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Enabled - - 0 - - - 0 - - 1 - BackgroundTaskEnabledCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnBackgroundTaskEnabledCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Exit when there are no mounted volumes - - 0 - - - 0 - - 1 - CloseBackgroundTaskOnNoVolumesCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 1 - - wxID_ANY - Task Icon Menu Items - - sbSizer26 - wxVERTICAL - none - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mount Favorite Volumes - - 0 - - - 0 - - 1 - BackgroundTaskMenuMountItemsEnabledCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Open Mounted Volumes - - 0 - - - 0 - - 1 - BackgroundTaskMenuOpenItemsEnabledCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Dismount Mounted Volumes - - 0 - - - 0 - - 1 - BackgroundTaskMenuDismountItemsEnabledCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - System Integration - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - SystemIntegrationPage - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer49 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer37 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 0 - - wxID_ANY - Actions to Perform when User Logs On - - LogOnSizer - wxVERTICAL - protected - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Start VeraCrypt Background Task - - 0 - - - 0 - - 1 - StartOnLogonCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mount favorite volumes - - 0 - - - 0 - - 1 - MountFavoritesOnLogonCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mount all device-hosted VeraCrypt volumes - - 0 - - - 0 - - 1 - MountDevicesOnLogonCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Filesystem Explorer - - ExplorerSizer - wxVERTICAL - protected - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Open Explorer window for successfully mounted volume - - 0 - - - 0 - - 1 - OpenExplorerWindowAfterMountCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Close all Explorer windows of volume being dismounted - - 0 - - - 0 - - 1 - CloseExplorerWindowsOnDismountCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Kernel Services - - KernelServicesSizer - wxVERTICAL - protected - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Do not use kernel cryptographic services - - 0 - - - 0 - - 1 - NoKernelCryptoCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnNoKernelCryptoCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Performance - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - PerformanceOptionsPage - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer151 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 1 - - - bSizer152 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Hardware Acceleration - - sbSizer44 - wxVERTICAL - none - - - 5 - wxEXPAND - 1 - - - bSizer158 - wxHORIZONTAL - none - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Processor (CPU) in this computer supports hardware acceleration for AES: - - 0 - - - 0 - - 1 - m_staticText57 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - AesHwCpuSupportedStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - wxSUNKEN_BORDER - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxBOTTOM - 0 - - 0 - protected - 0 - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Do not accelerate AES encryption/decryption by using the AES instructions of the processor - - 0 - - - 0 - - 1 - NoHardwareCryptoCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnNoHardwareCryptoCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Keyfiles - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - DefaultKeyfilesPage - 1 - - - public - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer40 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer43 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - wxID_ANY - Default Keyfiles - - bSizer42 - wxVERTICAL - none - - - 5 - wxEXPAND - 1 - - - DefaultKeyfilesSizer - wxVERTICAL - protected - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Use keyfiles by default - - 0 - - - 0 - - 1 - UseKeyfilesCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Security Tokens - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - SecurityTokensPage - 1 - - - public - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer127 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer128 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - PKCS #11 Library Path - - sbSizer36 - wxVERTICAL - none - - - 5 - wxEXPAND - 1 - - - bSizer129 - wxHORIZONTAL - none - - 5 - wxALL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - Pkcs11ModulePathTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Select &Library... - - 0 - - - 0 - - 1 - SelectPkcs11ModuleButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnSelectPkcs11ModuleButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Security Options - - sbSizer37 - wxVERTICAL - none - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Close token session (log out) after a volume is successfully mounted - - 0 - - - 0 - - 1 - CloseSecurityTokenSessionsAfterMountCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Hotkeys - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - HotkeysPage - 1 - - - public - 1 - - Resizable - 1 - - - 0 - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer51 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer38 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - wxID_ANY - System-Wide Hotkeys - - sbSizer21 - wxVERTICAL - none - - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - HotkeyListCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - wxSUNKEN_BORDER - - - - - - - - - - - - - - - - - - - - - - - - - OnHotkeyListItemDeselected - - - - OnHotkeyListItemSelected - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Shortcut - - sbSizer23 - wxVERTICAL - none - - - 5 - wxALIGN_RIGHT - 1 - - 3 - wxBOTH - - - 0 - - fgSizer4 - wxFLEX_GROWMODE_SPECIFIED - none - 2 - 0 - - 5 - wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Key to assign: - - 0 - - - 0 - - 1 - m_staticText10 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - HotkeyTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Assign - - 0 - - - 0 - - 1 - AssignHotkeyButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnAssignHotkeyButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - 5 - wxEXPAND - 1 - - 4 - 0 - - gSizer4 - none - 1 - 0 - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Control - - 0 - - - 0 - - 1 - HotkeyControlCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Shift - - 0 - - - 0 - - 1 - HotkeyShiftCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Alt - - 0 - - - 0 - - 1 - HotkeyAltCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Win - - 0 - - - 0 - - 1 - HotkeyWinCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Remove - - 0 - - - 0 - - 1 - RemoveHotkeyButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnRemoveHotkeyButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Options - - sbSizer24 - wxVERTICAL - none - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Play system notification sound after mount/dismount - - 0 - - - 0 - - 1 - BeepAfterHotkeyMountDismountCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Display confirmation message box after dismount - - 0 - - - 0 - - 1 - DisplayMessageAfterHotkeyDismountCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - 0 - 1 - 0 - 0 - 0 - 1 - 0 - 0 - - StdButtons - protected - - OnCancelButtonClick - - - - OnOKButtonClick - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - wxBOTH - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - RandomPoolEnrichmentDialogBase - - - wxDEFAULT_DIALOG_STYLE - - VeraCrypt - Random Pool Enrichment - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - OnMouseMotion - - - - - - - - - - - - MainSizer - wxVERTICAL - protected - - 5 - wxEXPAND|wxALL - 1 - - - bSizer144 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - - bSizer145 - wxHORIZONTAL - none - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Mixing PRF: - - 0 - - - 0 - - 1 - m_staticText49 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - HashChoice - 1 - - - protected - 1 - - Resizable - 0 - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnHashSelected - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - - - 5 - wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT - 1 - - wxID_ANY - - - sbSizer43 - wxVERTICAL - none - - - 5 - wxEXPAND|wxTOP - 0 - - - bSizer147 - wxHORIZONTAL - none - - 5 - wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Random Pool: - - 0 - - - 0 - - 1 - m_staticText52 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - Courier New,90,90,-1,70,0 - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - RandomPoolStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Show - - 0 - - - 0 - - 1 - ShowRandomPoolCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnShowRandomPoolCheckBoxClicked - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - 5 - wxBOTTOM|wxEXPAND|wxTOP - 0 - - wxID_ANY - Randomness Collected From Mouse Movements - - sbSizer45 - wxVERTICAL - none - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - CollectedEntropy - 1 - - - protected - 1 - - 2560 - Resizable - 1 - - wxGA_HORIZONTAL|wxGA_SMOOTH - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - 5 - wxALL|wxALIGN_CENTER_HORIZONTAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases security. When done, click 'Continue'. - - 0 - - - 0 - - 1 - MouseStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - - - 5 - wxEXPAND - 0 - - - bSizer146 - wxHORIZONTAL - none - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_OK - &Continue - - 0 - - - 0 - - 1 - ContinueButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - -1,-1 - SecurityTokenKeyfilesDialogBase - - -1,-1 - wxDEFAULT_DIALOG_STYLE - - Security Token Keyfiles - - wxWS_EX_VALIDATE_RECURSIVELY - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer3 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer138 - wxHORIZONTAL - none - - 5 - wxEXPAND - 1 - - - bSizer142 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - SecurityTokenKeyfileListCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - wxSUNKEN_BORDER - - - - - - - - - - - - - - - - - - - - - - - - OnListItemActivated - OnListItemDeselected - - - - OnListItemSelected - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - - bSizer141 - wxHORIZONTAL - none - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Export... - - 0 - - - 0 - - 1 - ExportButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnExportButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Delete - - 0 - - - 0 - - 1 - DeleteButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnDeleteButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxLEFT - 1 - - 0 - protected - 0 - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Import Keyfile to Token... - - 0 - - - 0 - - 1 - ImportButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnImportButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - - bSizer139 - wxVERTICAL - none - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_OK - OK - - 0 - - - 0 - - 1 - OKButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnOKButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_CANCEL - Cancel - - 0 - - - 0 - - 1 - CancelButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - VolumePropertiesDialogBase - - - wxDEFAULT_DIALOG_STYLE - - Volume Properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer49 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - - bSizer50 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - PropertiesListCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - wxSUNKEN_BORDER - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_HORIZONTAL - 0 - - 0 - 0 - 0 - 0 - 0 - 1 - 0 - 0 - - StdButtons - protected - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - - EncryptionOptionsWizardPageBase - - -1,-1 - WizardPage; WizardPage.h - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer93 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer94 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer95 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - wxID_ANY - Encryption Algorithm - - sbSizer29 - wxVERTICAL - none - - - 5 - wxEXPAND - 0 - - - bSizer96 - wxHORIZONTAL - none - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - EncryptionAlgorithmChoice - 1 - - - protected - 1 - - Resizable - 0 - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnEncryptionAlgorithmSelected - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Test - - 0 - - - 0 - - 1 - TestButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnTestButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - EncryptionAlgorithmStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - - bSizer97 - wxHORIZONTAL - none - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxSYS_COLOUR_WINDOWTEXT - wxID_ANY - More information - - 0 - - - 0 - - 1 - EncryptionAlgorithmHyperlink - wxSYS_COLOUR_WINDOWTEXT - 1 - - - protected - 1 - - Resizable - 1 - - wxHL_DEFAULT_STYLE - - 0 - - - wxSYS_COLOUR_WINDOWTEXT - - - - - - - OnEncryptionAlgorithmHyperlinkClick - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - 0 - protected - 0 - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Benchmark - - 0 - - - 0 - - 1 - BenchmarkButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnBenchmarkButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Hash Algorithm - - sbSizer30 - wxHORIZONTAL - none - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - HashChoice - 1 - - - protected - 1 - - Resizable - 0 - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxSYS_COLOUR_WINDOWTEXT - wxID_ANY - Information on hash algorithms - - 0 - - - 0 - - 1 - HashHyperlink - wxSYS_COLOUR_WINDOWTEXT - 1 - - - protected - 1 - - Resizable - 1 - - wxHL_DEFAULT_STYLE - - 0 - - - wxSYS_COLOUR_WINDOWTEXT - - - - - - - OnHashHyperlinkClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - - InfoWizardPageBase - - -1,-1 - WizardPage; WizardPage.h - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer71 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - InfoPageSizer - wxVERTICAL - protected - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - InfoStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - 500,300 - KeyfilesPanelBase - - -1,-1 - - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer19 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer20 - wxHORIZONTAL - none - - 5 - wxEXPAND - 1 - - - bSizer21 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - KeyfilesListCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxLC_NO_SORT_HEADER|wxLC_REPORT - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - wxSUNKEN_BORDER - - - - - - - - - - - - - - - - - - - - - - - - - OnListItemDeselected - - - - OnListItemSelected - - - - - - - - - - - - - OnListSizeChanged - - - - - 5 - wxEXPAND - 0 - - - bSizer137 - wxHORIZONTAL - none - - 5 - wxEXPAND|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Add &Files... - - 0 - - - 0 - - 1 - AddFilesButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnAddFilesButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Add &Path... - - 0 - - - 0 - - 1 - AddDirectoryButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnAddDirectoryButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Add &Token Files... - - 0 - - - 0 - - 1 - AddSecurityTokenSignatureButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnAddSecurityTokenSignatureButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Remove - - 0 - - - 0 - - 1 - RemoveButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnRemoveButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Remove &All - - 0 - - - 0 - - 1 - RemoveAllButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnRemoveAllButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - - ProgressWizardPageBase - - -1,-1 - WizardPage; WizardPage.h - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer81 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - - bSizer82 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - - ProgressSizer - wxHORIZONTAL - protected - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - -1,-1 - 1 - ProgressGauge - 1 - - - protected - 1 - - 100 - Resizable - 1 - -1,-1 - wxGA_HORIZONTAL|wxGA_SMOOTH - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 0 - - 1 - - 0 - 0 - wxID_ANY - &Abort - - 0 - - - 0 - - 1 - AbortButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnAbortButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - InfoStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - 200,65 - SelectDirectoryWizardPageBase - - -1,-1 - WizardPage; WizardPage.h - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer68 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer69 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - - bSizer70 - wxHORIZONTAL - none - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - DirectoryTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - OnDirectoryTextChanged - - - - - - - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Browse... - - 0 - - - 0 - - 1 - BrowseButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnBrowseButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - InfoStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - 300 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - - SingleChoiceWizardPageBase - - -1,-1 - WizardPage; WizardPage.h - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer71 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer77 - wxVERTICAL - none - - 5 - wxEXPAND|wxTOP - 0 - - 0 - protected - 0 - - - - 5 - wxEXPAND - 0 - - - OuterChoicesSizer - wxVERTICAL - protected - - 5 - wxEXPAND - 0 - - - ChoicesSizer - wxVERTICAL - protected - - - - - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - InfoStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - - VolumeCreationProgressWizardPageBase - - -1,-1 - WizardPage; WizardPage.h - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer104 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer105 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 0 - - wxID_ANY - - - sbSizer31 - wxVERTICAL - none - - - 30 - wxEXPAND - 1 - - - KeySamplesUpperSizer - wxVERTICAL - protected - - 3 - wxEXPAND|wxTOP - 1 - - - KeySamplesUpperInnerSizer - wxVERTICAL - protected - - - - - - 5 - wxEXPAND - 0 - - 2 - wxBOTH - - - 0 - - fgSizer5 - wxFLEX_GROWMODE_SPECIFIED - none - 3 - 0 - - 5 - wxALL|wxALIGN_RIGHT|wxALIGN_BOTTOM - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Random Pool: - - 0 - - - 0 - - 1 - m_staticText25 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALIGN_BOTTOM - 1 - - - bSizer126 - wxHORIZONTAL - none - - 7 - wxEXPAND|wxTOP|wxRIGHT|wxALIGN_BOTTOM - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - Courier New,90,90,-1,70,0 - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - RandomPoolSampleStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxRIGHT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Show - - 0 - - - 0 - - 1 - DisplayKeysCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnDisplayKeysCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_BOTTOM - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Header Key: - - 0 - - - 0 - - 1 - m_staticText28 - 1 - - - none - 1 - - Resizable - 1 - -1,-1 - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 2 - wxALIGN_BOTTOM|wxEXPAND|wxTOP|wxRIGHT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - Courier New,90,90,-1,70,0 - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - HeaderKeySampleStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_BOTTOM - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Master Key: - - 0 - - - 0 - - 1 - m_staticText29 - 1 - - - none - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 2 - wxEXPAND|wxALIGN_BOTTOM|wxTOP|wxRIGHT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - Courier New,90,90,-1,70,0 - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - MasterKeySampleStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxLEFT|wxRIGHT - 0 - - wxID_ANY - Randomness Collected From Mouse Movements - - sbSizer45 - wxVERTICAL - none - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - CollectedEntropy - 1 - - - protected - 1 - - 2560 - Resizable - 1 - - wxGA_HORIZONTAL|wxGA_SMOOTH - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT - 0 - - wxID_ANY - - - sbSizer32 - wxVERTICAL - none - - - 5 - wxEXPAND - 0 - - - bSizer106 - wxHORIZONTAL - none - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - -1,-1 - 1 - ProgressGauge - 1 - - - protected - 1 - - 100 - Resizable - 1 - - wxGA_HORIZONTAL|wxGA_SMOOTH - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALIGN_CENTER_VERTICAL|wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Abort - - 0 - - - 0 - - 1 - AbortButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnAbortButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2 - wxEXPAND|wxTOP - 0 - - 3 - 0 - - gSizer6 - none - 1 - 0 - - 5 - wxALIGN_CENTER_VERTICAL|wxEXPAND - 1 - - - bSizer108 - wxHORIZONTAL - none - - 5 - wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Done - - 0 - - - 0 - - 1 - m_staticText31 - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - -1,-1 - 1 - m_panel12 - 1 - - - protected - 1 - - Resizable - 1 - -1,-1 - - 0 - - - - wxSUNKEN_BORDER - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer115 - wxHORIZONTAL - none - - 3 - wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - SizeDoneStaticText - 1 - - - protected - 1 - - Resizable - 1 - - wxALIGN_RIGHT|wxST_NO_AUTORESIZE - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL - 1 - - - bSizer1081 - wxHORIZONTAL - none - - 5 - wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Speed - - 0 - - - 0 - - 1 - m_staticText311 - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - m_panel121 - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxSUNKEN_BORDER - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer1151 - wxHORIZONTAL - none - - 3 - wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - SpeedStaticText - 1 - - - protected - 1 - - Resizable - 1 - - wxALIGN_RIGHT|wxST_NO_AUTORESIZE - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT - 1 - - - bSizer1082 - wxHORIZONTAL - none - - 5 - wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Left - - 0 - - - 0 - - 1 - m_staticText312 - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - m_panel122 - 1 - - - protected - 1 - - Resizable - 1 - - - 0 - - - - wxSUNKEN_BORDER|wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer1152 - wxHORIZONTAL - none - - 3 - wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - TimeLeftStaticText - 1 - - - protected - 1 - - Resizable - 1 - - wxALIGN_RIGHT|wxST_NO_AUTORESIZE - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxBOTTOM|wxLEFT|wxRIGHT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - InfoStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - - VolumeLocationWizardPageBase - - -1,-1 - WizardPage; WizardPage.h - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer86 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer87 - wxVERTICAL - none - - 5 - wxEXPAND|wxTOP - 0 - - 0 - protected - 0 - - - - 5 - wxEXPAND - 0 - - - bSizer88 - wxHORIZONTAL - none - - 5 - wxEXPAND - 1 - - - bSizer89 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - - bSizer126 - wxHORIZONTAL - none - - 5 - wxALL|wxALIGN_CENTER_VERTICAL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - -1,-1 - 1 - VolumePathComboBox - 1 - - - protected - 1 - - Resizable - -1 - 1 - - wxCB_DROPDOWN - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - OnVolumePathTextChanged - - - - - - 5 - wxALIGN_CENTER_VERTICAL - 0 - - - bSizer90 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Select &File... - - 0 - - - 0 - -1,-1 - 1 - SelectFileButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnSelectFileButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Select D&evice... - - 0 - - - 0 - -1,-1 - 1 - SelectDeviceButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnSelectDeviceButtonClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 0 - - - bSizer91 - wxHORIZONTAL - none - - 5 - wxLEFT - 0 - - 0 - protected - 0 - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Never save history - - 0 - - - 0 - - 1 - NoHistoryCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnNoHistoryCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxBOTTOM - 0 - - 0 - protected - 0 - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - InfoStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - - VolumeFormatOptionsWizardPageBase - - -1,-1 - WizardPage; WizardPage.h - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer124 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - - bSizer125 - wxVERTICAL - none - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Filesystem Options - - sbSizer33 - wxVERTICAL - none - - - 5 - wxEXPAND - 1 - - 2 - wxBOTH - - - 0 - - fgSizer6 - wxFLEX_GROWMODE_SPECIFIED - none - 2 - 0 - - 5 - wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Filesystem type: - - 0 - - - 0 - - 1 - m_staticText43 - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - FilesystemTypeChoice - 1 - - - protected - 1 - - Resizable - 0 - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnFilesystemTypeSelected - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxALL - 0 - - wxID_ANY - Volume Format Options - - sbSizer34 - wxVERTICAL - none - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Quick format - - 0 - - - 0 - - 1 - QuickFormatCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnQuickFormatCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxTOP|wxBOTTOM - 1 - - 0 - protected - 0 - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - InfoStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - - VolumePasswordPanelBase - - -1,-1 - - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer7 - wxVERTICAL - none - - 5 - wxALL|wxEXPAND - 1 - - 0,0 - wxBOTH - 1 - - 0 - - GridBagSizer - wxFLEX_GROWMODE_SPECIFIED - protected - 0 - - 5 - 1 - 0 - wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxRIGHT - 1 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Password: - - 0 - - - 0 - - 1 - PasswordStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 2 - 1 - wxBOTTOM|wxALIGN_CENTER_VERTICAL|wxEXPAND - 1 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 1 - - 0 - 232,-1 - 1 - PasswordTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxTE_PASSWORD - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - OnTextChanged - - - - - - - - 5 - 1 - 0 - wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT - 2 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Confirm password: - - 0 - - - 0 - - 1 - ConfirmPasswordStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 2 - 1 - wxBOTTOM|wxALIGN_CENTER_VERTICAL|wxEXPAND - 2 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 1 - - 0 - 232,-1 - 1 - ConfirmPasswordTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxTE_PASSWORD - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - OnTextChanged - - - - - - - - 5 - 1 - 0 - wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxRIGHT - 3 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Volume PIM: - - 0 - - - 0 - - 1 - VolumePimStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 1 - wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxEXPAND - 3 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 7 - - 0 - - 1 - VolumePimTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxTE_PASSWORD - - 0 - - - wxFILTER_NUMERIC - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - OnPimChanged - - - - - - - - 5 - 1 - 2 - wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxLEFT|wxRIGHT - 3 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - (Empty or 0 for default iterations) - - 0 - - - 0 - - 1 - VolumePimHelpStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 2 - 1 - wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL - 4 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Use PIM - - 0 - - - 0 - - 1 - PimCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnUsePimCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 2 - 1 - wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL - 5 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Cach&e passwords and keyfiles in memory - - 0 - - - 0 - - 1 - CacheCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 2 - 1 - wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL - 6 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Display password - - 0 - - - 0 - - 1 - DisplayPasswordCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnDisplayPasswordCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 1 - wxTOP|wxRIGHT|wxLEFT - 7 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - U&se keyfiles - - 0 - - - 0 - - 1 - UseKeyfilesCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnUseKeyfilesCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 2 - wxALIGN_RIGHT|wxALIGN_BOTTOM|wxLEFT - 7 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Keyfiles... - - 0 - - - 0 - - 1 - KeyfilesButton - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - OnKeyfilesButtonClick - - - - - - - - - - - - - - - - - - - OnKeyfilesButtonRightDown - OnKeyfilesButtonRightClick - - - - - - - 5 - 1 - 1 - wxEXPAND|wxTOP|wxBOTTOM - 8 - 1 - - - Pkcs5PrfSizer - wxVERTICAL - protected - - - - 5 - 1 - 0 - wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxRIGHT - 9 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - PKCS-5 PRF: - - 0 - - - 0 - - 1 - Pkcs5PrfStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 1 - wxALIGN_CENTER_VERTICAL|wxLEFT - 9 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - "Unchanged" - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - -1,-1 - - 0 - -1,-1 - 1 - Pkcs5PrfChoice - 1 - - - protected - 1 - - Resizable - 0 - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 2 - wxALIGN_CENTER_VERTICAL|wxLEFT - 9 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - TrueCrypt Mode - - 0 - - - 0 - - 1 - TrueCryptModeCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnTrueCryptModeChecked - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 0 - wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxRIGHT - 10 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Header Wipe: - - 0 - - - 0 - - 1 - HeaderWipeCountText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 1 - 1 - wxALL - 10 - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - "1-pass" "3-pass" "7-pass" "35-pass" "256-pass" - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - HeaderWipeCount - 1 - - - protected - 1 - - Resizable - 1 - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - 2 - 1 - wxTOP|wxEXPAND - 11 - 1 - - - PasswordPlaceholderSizer - wxVERTICAL - protected - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - - VolumePasswordWizardPageBase - - -1,-1 - WizardPage; WizardPage.h - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer101 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer102 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - - PasswordPanelSizer - wxVERTICAL - protected - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - InfoStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - - VolumePimWizardPageBase - - -1,-1 - WizardPage; WizardPage.h - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer101 - wxVERTICAL - none - - 5 - wxEXPAND - 1 - - - bSizer102 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - - PimPanelSizer - wxVERTICAL - protected - - 5 - wxEXPAND - 1 - - - PimSizer - wxHORIZONTAL - protected - - 5 - wxALIGN_CENTER_VERTICAL|wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - Volume PIM: - - 0 - - - 0 - - 1 - VolumePimStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 7 - - 0 - - 1 - VolumePimTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - wxTE_PASSWORD - - 0 - - - wxFILTER_NUMERIC - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - OnPimChanged - - - - - - - - 5 - wxALIGN_CENTER_VERTICAL|wxALL - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - (Empty or 0 for default iterations) - - 0 - - - 0 - - 1 - VolumePimHelpStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND - 1 - - - bSizer166 - wxHORIZONTAL - none - - 5 - wxALL|wxEXPAND - 1 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - &Display PIM - - 0 - - - 0 - - 1 - DisplayPimCheckBox - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnDisplayPimCheckBoxClick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - InfoStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - - 1 - 1 - impl_virtual - - - 0 - wxID_ANY - - - VolumeSizeWizardPageBase - - -1,-1 - WizardPage; WizardPage.h - - - - wxTAB_TRAVERSAL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bSizer98 - wxVERTICAL - none - - 5 - wxEXPAND - 0 - - - bSizer99 - wxVERTICAL - none - - 5 - wxEXPAND|wxTOP|wxBOTTOM - 0 - - 0 - protected - 0 - - - - 5 - wxEXPAND - 0 - - - bSizer100 - wxHORIZONTAL - none - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - 0 - - 0 - - 1 - VolumeSizeTextCtrl - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - - - - - - - - - - - - - - - - - - - - - - - OnVolumeSizeTextChanged - - - - - - - - 5 - wxALL - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - VolumeSizePrefixChoice - 1 - - - protected - 1 - - Resizable - 0 - 1 - - - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - - - - - OnVolumeSizePrefixSelected - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxTOP|wxBOTTOM - 0 - - 0 - protected - 0 - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - FreeSpaceStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxEXPAND|wxTOP|wxBOTTOM - 0 - - 0 - protected - 0 - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - - 0 - - - 0 - - 1 - InfoStaticText - 1 - - - protected - 1 - - Resizable - 1 - - - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - wxAUI_MGR_DEFAULT - - wxBOTH - - 1 - 1 - impl_virtual - - - - 0 - wxID_ANY - - - WaitDialogBase - - -1,-1 - wxCAPTION - - VeraCrypt - - - - - - - - - - - - - - OnWaitDialogClose - - - - - - OnWaitDialogInit - - - - - - - - - - - - - - - - - - - - - - - bSizer160 - wxVERTICAL - none - - 5 - wxALIGN_CENTER_HORIZONTAL|wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - MyLabel - - 0 - - - 0 - - 1 - WaitStaticText - 1 - - - protected - 1 - - Resizable - 1 - - wxALIGN_CENTRE - - 0 - - - - - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - 5 - wxALL|wxEXPAND - 0 - - 1 - 1 - 1 - 1 - - - - - - - - 1 - 0 - 1 - - 1 - 0 - Dock - 0 - Left - 1 - - 1 - - 0 - 0 - wxID_ANY - - 0 - - - 0 - - 1 - WaitProgessBar - 1 - - - protected - 1 - - 100 - Resizable - 1 - - wxGA_HORIZONTAL|wxGA_SMOOTH - - 0 - - - wxFILTER_NONE - wxDefaultValidator - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + C++ + 1 + source_name + 0 + 0 + res + UTF-8 + connect + Forms + 1000 + none + 1 + VeraCrypt + "VeraCrypt" + . + #include "System.h" + 1 + 1 + 1 + 1 + UI + 1 + 0 + + 0 + wxAUI_MGR_DEFAULT + + wxBOTH + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + -1,496 + MainFrameBase + + -1,-1 + wxCAPTION|wxCLOSE_BOX|wxMINIMIZE_BOX|wxSYSTEM_MENU + + VeraCrypt + + + + wxTAB_TRAVERSAL + 1 + OnActivate + + + + + + + + + OnClose + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 1 + + + 0 + wxID_ANY + MainMenuBar + + + MainMenuBar + protected + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &Volumes + VolumesMenu + protected + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Create New Volume... + CreateNewVolumeMenuItem + none + + + OnCreateVolumeButtonClick + + + + m_separator1 + none + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Mount Volume + MountVolumeMenuItem + protected + + + OnMountVolumeMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Auto-Mount All Device-Hosted Volumes + AutoMountDevicesMenuItem + none + + + OnMountAllDevicesButtonClick + + + + m_separator2 + none + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Dismount Volume + DismountVolumeMenuItem + protected + + + OnDismountVolumeMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Dismount All Mounted Volumes + DismountAllMenuItem + protected + + + OnDismountAllButtonClick + + + + m_separator3 + none + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Change Volume Password... + ChangePasswordMenuItem + none + + + OnChangePasswordMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Change Header Key Derivation Algorithm... + ChangePkcs5PrfMenuItem + none + + + OnChangePkcs5PrfMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Add/Remove Keyfiles to/from Volume... + ChangeKeyfilesMenuItem + none + + + OnChangeKeyfilesMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Remove All Keyfiles from Volume... + RemoveKeyfilesMenuItem + none + + + OnRemoveKeyfilesMenuItemSelected + + + + m_separator4 + none + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Volume Properties... + VolumePropertiesMenuItem + protected + + + OnVolumePropertiesButtonClick + + + + + &Favorites + FavoritesMenu + protected + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Add Selected Volume to Favorites... + AddToFavoritesMenuItem + protected + + + OnAddToFavoritesMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Add All Mounted Volumes to Favorites... + AddAllMountedToFavoritesMenuItem + protected + + + OnAddAllMountedToFavoritesMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Organize Favorite Volumes... + OrganizeFavoritesMenuItem + none + + + OnOrganizeFavoritesMenuItemSelected + + + + m_separator5 + none + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Mount Favorite Volumes + MountAllFavoritesMenuItem + none + + + OnMountAllFavoritesMenuItemSelected + + + + m_separator6 + none + + + + T&ools + ToolsMenu + protected + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Benchmark... + BenchmarkMenuItem + none + + + OnBenchmarkMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Test Vectors... + EncryptionTestMenuItem + none + + + OnEncryptionTestMenuItemSelected + + + + m_separator7 + none + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Volume Creation Wizard + VolumeCreationWizardMenuItem + none + + + OnCreateVolumeButtonClick + + + + m_separator8 + none + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Backup Volume Header... + BackupVolumeHeadersMenuItem + protected + + + OnBackupVolumeHeadersMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Restore Volume Header... + RestoreVolumeHeaderMenuItem + protected + + + OnRestoreVolumeHeaderMenuItemSelected + + + + m_separator9 + none + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Keyfile Generator + CreateKeyfileMenuItem + none + + + OnCreateKeyfileMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Manage Security Token Keyfiles... + ManageSecurityTokenKeyfilesMenuItem + none + + + OnManageSecurityTokenKeyfilesMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Close All Security Token Sessions + CloseAllSecurityTokenSessionsMenuItem + none + + + OnCloseAllSecurityTokenSessionsMenuItemSelected + + + + m_separator10 + none + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Wipe Cached Passwords + WipeCachedPasswordsMenuItem + protected + + + OnWipeCacheButtonClick + + + + + Settin&gs + SettingsMenu + protected + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Hotkeys... + HotkeysMenuItem + protected + + + OnHotkeysMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Default Keyfiles... + DefaultKeyfilesMenuItem + none + + + OnDefaultKeyfilesMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Default Mount Parameters... + DefaultMountParametersMenuItem + none + + + OnDefaultMountParametersMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Security Tokens... + SecurityTokenPreferencesMenuItem + none + + + OnSecurityTokenPreferencesMenuItemSelected + + + + m_separator11 + none + + + + 0 + 1 + + wxID_PREFERENCES + wxITEM_NORMAL + &Preferences... + PreferencesMenuItem + protected + + + OnPreferencesMenuItemSelected + + + + + &Help + HelpMenu + protected + + + 0 + 1 + + wxID_HELP + wxITEM_NORMAL + User's Guide + UserGuideMenuItem + none + + + OnUserGuideMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Online Help + OnlineHelpMenuItem + none + + + OnOnlineHelpMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Beginner's Tutorial + BeginnersTutorialMenuItem + none + + + OnBeginnersTutorialMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Frequently Asked Questions + FaqMenuItem + none + + + OnFaqMenuItemSelected + + + + m_separator12 + none + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + VeraCrypt Website + WebsiteMenuItem + none + + + OnWebsiteMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Downloads + DownloadsMenuItem + none + + + OnDownloadsMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + News + NewsMenuItem + none + + + OnNewsMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Version History + VersionHistoryMenuItem + none + + + OnVersionHistoryMenuItemSelected + + + + m_separator13 + none + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Donate + DonateMenuItem + none + + + OnDonateMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Contact + ContactMenuItem + none + + + OnContactMenuItemSelected + + + + + 0 + 1 + + wxID_ANY + wxITEM_NORMAL + Legal Notices + LegalNoticesMenuItem + none + + + OnLegalNoticesMenuItemSelected + + + + + 0 + 1 + + wxID_ABOUT + wxITEM_NORMAL + About + AboutMenuItem + none + + + OnAboutMenuItemSelected + + + + + + + bSizer1 + wxVERTICAL + none + + 0 + wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + MainPanel + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer2 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer48 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + wxID_ANY + + + sbSizer1 + wxVERTICAL + none + + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + SlotListCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + wxSUNKEN_BORDER + + + + + + + + + + + + + + + + + + + + + + + + OnListItemActivated + OnListItemDeselected + + + OnListItemRightClick + OnListItemSelected + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + wxID_ANY + + + LowStaticBoxSizer + wxVERTICAL + protected + + + 2 + wxEXPAND|wxTOP + 0 + + + HigherButtonSizer + wxVERTICAL + protected + + + + 5 + wxEXPAND|wxRIGHT|wxLEFT + 0 + + 3 + 0 + + gSizer1 + none + 1 + 0 + + 5 + + 0 + + 138,34 + bSizer17 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Create Volume + + 0 + + + 0 + -1,-1 + 1 + CreateVolumeButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnCreateVolumeButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_HORIZONTAL + 0 + + 138,34 + bSizer18 + wxVERTICAL + none + + 5 + wxALL|wxALIGN_CENTER_HORIZONTAL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Volume Properties... + + 0 + + + 0 + -1,-1 + 1 + VolumePropertiesButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnVolumePropertiesButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_RIGHT + 0 + + 138,34 + bSizer19 + wxVERTICAL + none + + 5 + wxALL|wxALIGN_RIGHT|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Wipe Cache + + 0 + + + 0 + -1,-1 + 1 + WipeCacheButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnWipeCacheButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + + 0 + + 0 + protected + 0 + + + + 5 + wxEXPAND + 1 + + wxID_ANY + Volume + + VolumeStaticBoxSizer + wxVERTICAL + protected + + + 4 + wxEXPAND|wxALL + 1 + + + wxBOTH + 1 + 0 + 0 + + VolumeGridBagSizer + wxFLEX_GROWMODE_SPECIFIED + protected + 0 + + 5 + 1 + 0 + wxALIGN_CENTER_VERTICAL|wxALL + 0 + 2 + + 1 + 1 + 1 + 1 + + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + 42,52 + 1 + LogoBitmap + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxSUNKEN_BORDER + + + + + + + + + OnLogoBitmapClick + + + + + + + + + + + + + + + + + + 5 + 2 + 1 + wxEXPAND|wxALL + 0 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + VolumePathComboBox + 1 + + + protected + 1 + + Resizable + -1 + 1 + + wxCB_DROPDOWN + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 3 + wxEXPAND + 0 + 1 + + 138,34 + bSizer191 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Select &File... + + 0 + + + 0 + -1,-1 + 1 + SelectFileButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnSelectFileButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 1 + wxBOTTOM|wxRIGHT|wxLEFT + 1 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Never save history + + 0 + + + 0 + + 1 + NoHistoryCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnNoHistoryCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 2 + wxALIGN_RIGHT + 1 + 1 + + 138,34 + bSizer20 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Volume &Tools... + + 0 + + + 0 + -1,-1 + 1 + VolumeToolsButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnVolumeToolsButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 3 + wxEXPAND + 1 + 1 + + 138,34 + bSizer21 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Select D&evice... + + 0 + + + 0 + -1,-1 + 1 + SelectDeviceButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnSelectDeviceButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + + 0 + + 0 + protected + 0 + + + + 5 + wxEXPAND + 0 + + 4 + 0 + + gSizer2 + none + 1 + 0 + + 0 + wxEXPAND + 1 + + wxID_ANY + + 139,-1 + sbSizer4 + wxVERTICAL + none + + + 2 + wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Mount + + 0 + + + 0 + -1,32 + 1 + VolumeButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnVolumeButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_HORIZONTAL|wxEXPAND + 1 + + wxID_ANY + + -1,-1 + sbSizer41 + wxVERTICAL + none + + + 2 + wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Auto-Mount Devices + + 0 + + + 0 + -1,32 + 1 + MountAllDevicesButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnMountAllDevicesButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_HORIZONTAL|wxEXPAND + 1 + + wxID_ANY + + -1,-1 + sbSizer42 + wxVERTICAL + none + + + 2 + wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Di&smount All + + 0 + + + 0 + -1,32 + 1 + DismountAllButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnDismountAllButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_RIGHT|wxEXPAND + 1 + + wxID_ANY + + -1,-1 + sbSizer43 + wxVERTICAL + none + + + 2 + wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + E&xit + + 0 + + + 0 + -1,32 + 1 + ExitButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnExitButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + 800,500 + WizardFrameBase + + -1,-1 + wxCAPTION|wxCLOSE_BOX|wxMINIMIZE_BOX|wxSYSTEM_MENU + + + + + + wxTAB_TRAVERSAL + 1 + OnActivate + + + + + + + + + OnClose + + + + + + + + + + + + + + + + + + + + + + + + + + + + MainSizer + wxVERTICAL + protected + + 5 + wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + MainPanel + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + OnMouseMotion + + + + + + + + + + + + bSizer63 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer64 + wxVERTICAL + none + + 5 + wxEXPAND|wxRIGHT|wxLEFT + 1 + + wxID_ANY + + + sbSizer27 + wxHORIZONTAL + none + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + WizardBitmap + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxLEFT + 1 + + + bSizer66 + wxVERTICAL + none + + 5 + wxLEFT + 0 + + + bSizer126 + wxHORIZONTAL + none + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + Times New Roman,90,90,16,70,0 + 0 + 0 + wxID_ANY + Page Title + + 0 + + + 0 + + 1 + PageTitleStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxTOP|wxBOTTOM|wxLEFT + 1 + + + PageSizer + wxVERTICAL + protected + + + + + + + + 5 + wxEXPAND|wxALIGN_RIGHT|wxALL + 0 + + + bSizer70 + wxHORIZONTAL + none + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_HELP + &Help + + 0 + + + 0 + + 1 + HelpButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnHelpButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxLEFT|wxALIGN_RIGHT + 0 + + 0 + protected + 0 + + + + 5 + wxTOP|wxBOTTOM|wxLEFT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + < &Prev + + 0 + + + 0 + + 1 + PreviousButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnPreviousButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Next > + + 0 + + + 0 + + 1 + NextButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + wxWANTS_CHARS + OnNextButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxLEFT|wxALIGN_RIGHT + 0 + + 0 + protected + 0 + + + + 5 + wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_CANCEL + Cancel + + 0 + + + 0 + + 1 + CancelButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnCancelButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + AboutDialogBase + + + wxDEFAULT_DIALOG_STYLE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer116 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer117 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + -1,78 + bSizer120 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + 10,108,206 + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_panel14 + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer121 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + 0 + protected + 0 + + + + 8 + wxEXPAND|wxLEFT + 0 + + + bSizer122 + wxVERTICAL + none + + 10 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + LogoBitmap + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 15 + wxALL|wxEXPAND + 1 + + + bSizer118 + wxVERTICAL + none + + 5 + wxEXPAND|wxLEFT + 1 + + + bSizer123 + wxVERTICAL + none + + 5 + wxTOP|wxRIGHT|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + VersionStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 3 + wxTOP + 0 + + 0 + protected + 0 + + + + 5 + wxBOTTOM|wxRIGHT|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + CopyrightStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 3 + wxTOP + 0 + + 0 + protected + 0 + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxSYS_COLOUR_WINDOWTEXT + wxID_ANY + + + 0 + + + 0 + + 1 + WebsiteHyperlink + wxSYS_COLOUR_WINDOWTEXT + 1 + + + protected + 1 + + Resizable + 1 + + wxHL_DEFAULT_STYLE + + 0 + + . + wxSYS_COLOUR_WINDOWTEXT + + + + + + + OnWebsiteHyperlinkClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxBOTTOM + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_staticline3 + 1 + + + protected + 1 + + Resizable + 1 + + wxLI_HORIZONTAL + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 10 + wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + + 0 + + 1 + CreditsTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxTE_MULTILINE|wxTE_READONLY + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + wxSUNKEN_BORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxTOP + 0 + + 0 + protected + 0 + + + + 3 + wxEXPAND|wxTOP|wxBOTTOM + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_staticline4 + 1 + + + protected + 1 + + Resizable + 1 + + wxLI_HORIZONTAL + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxBOTTOM + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_staticline5 + 1 + + + protected + 1 + + Resizable + 1 + + wxLI_HORIZONTAL + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 6 + wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT + 0 + + + bSizer119 + wxHORIZONTAL + none + + 5 + wxEXPAND|wxALL + 1 + + 0 + protected + 0 + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_OK + OK + + 0 + + + 0 + + 1 + OKButton + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxLEFT + 0 + + 0 + protected + 0 + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + BenchmarkDialogBase + + + wxDEFAULT_DIALOG_STYLE + + VeraCrypt - Encryption Algorithm Benchmark + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer153 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer154 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + + bSizer155 + wxHORIZONTAL + none + + 5 + wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Buffer Size: + + 0 + + + 0 + + 1 + m_staticText54 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + BufferSizeChoice + 1 + + + protected + 1 + + Resizable + 0 + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND | wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_staticline6 + 1 + + + none + 1 + + Resizable + 1 + + wxLI_HORIZONTAL + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + + bSizer156 + wxHORIZONTAL + none + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + BenchmarkListCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxLC_NO_SORT_HEADER|wxLC_REPORT + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + wxSUNKEN_BORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + + RightSizer + wxVERTICAL + protected + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_OK + Benchmark + + 0 + + + 0 + + 1 + BenchmarkButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnBenchmarkButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_CANCEL + Close + + 0 + + + 0 + + 1 + CancelButton + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxTOP|wxBOTTOM + 0 + + 0 + protected + 0 + + + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + -1,-1 + + 0 + + 1 + BenchmarkNoteStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + ChangePasswordDialogBase + + + wxDEFAULT_DIALOG_STYLE + + + + wxWS_EX_VALIDATE_RECURSIVELY + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer30 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer31 + wxHORIZONTAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer32 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + wxID_ANY + Current + + CurrentSizer + wxVERTICAL + protected + + + 5 + wxALIGN_LEFT + 0 + + + CurrentPasswordPanelSizer + wxVERTICAL + protected + + + + + + 5 + wxTOP|wxEXPAND + 0 + + wxID_ANY + New + + NewSizer + wxVERTICAL + protected + + + 5 + wxALIGN_LEFT + 0 + + + NewPasswordPanelSizer + wxVERTICAL + protected + + + + + + + + 5 + + 0 + + + bSizer33 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_OK + OK + + 0 + + + 0 + + 1 + OKButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnOKButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_CANCEL + Cancel + + 0 + + + 0 + + 1 + CancelButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + wxBOTH + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + -1,-1 + DeviceSelectionDialogBase + + -1,-1 + wxDEFAULT_DIALOG_STYLE + + Select a Partition or Device + + wxWS_EX_VALIDATE_RECURSIVELY + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer3 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer4 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + DeviceListCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + wxSUNKEN_BORDER + + + + + + + + + + + + + + + + + + + + + + + + OnListItemActivated + OnListItemDeselected + + + + OnListItemSelected + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + 0 + 1 + 0 + 0 + 0 + 1 + 0 + 0 + + StdButtons + protected + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + EncryptionTestDialogBase + + + wxDEFAULT_DIALOG_STYLE + + VeraCrypt - Test Vectors + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer132 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer133 + wxVERTICAL + none + + 5 + wxALIGN_CENTER_HORIZONTAL + 0 + + + bSizer134 + wxHORIZONTAL + none + + 5 + wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Encryption algorithm: + + 0 + + + 0 + + 1 + m_staticText41 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + EncryptionAlgorithmChoice + 1 + + + protected + 1 + + Resizable + 0 + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnEncryptionAlgorithmSelected + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + XTS mode + + 0 + + + 0 + + 1 + XtsModeCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnXtsModeCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Key (hexadecimal) + + sbSizer38 + wxVERTICAL + none + + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + Courier,90,90,-1,70,0 + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + KeyTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + + bSizer135 + wxHORIZONTAL + none + + 5 + wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Key size: + + 0 + + + 0 + + 1 + m_staticText43 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + KeySizeStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 1 + + wxID_ANY + XTS mode + + sbSizer39 + wxVERTICAL + none + + + 5 + wxTOP|wxRIGHT|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Secondary key (hexadecimal) + + 0 + + + 0 + + 1 + m_staticText45 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + Courier,90,90,-1,70,0 + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + SecondaryKeyTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxTOP|wxRIGHT|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Data unit number (64-bit, data unit size is 512 bytes) + + 0 + + + 0 + + 1 + m_staticText46 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + DataUnitNumberTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxTOP|wxRIGHT|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Block number: + + 0 + + + 0 + + 1 + m_staticText47 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + BlockNumberTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Plaintext (hexadecimal) + + sbSizer40 + wxVERTICAL + none + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + Courier,90,90,-1,70,0 + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + PlainTextTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Ciphertext (hexadecimal) + + sbSizer41 + wxVERTICAL + none + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + Courier,90,90,-1,70,0 + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + CipherTextTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + + bSizer136 + wxHORIZONTAL + none + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Encrypt + + 0 + + + 0 + + 1 + EncryptButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnEncryptButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Decrypt + + 0 + + + 0 + + 1 + DecryptButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnDecryptButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Auto-Test All + + 0 + + + 0 + + 1 + AutoTestAllButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnAutoTestAllButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Reset + + 0 + + + 0 + + 1 + ResetButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnResetButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_CANCEL + Close + + 0 + + + 0 + + 1 + CloseButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + FavoriteVolumesDialogBase + + + wxDEFAULT_DIALOG_STYLE + + Favorite Volumes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer57 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer60 + wxHORIZONTAL + none + + 5 + wxEXPAND + 1 + + + bSizer58 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + FavoritesListCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + wxSUNKEN_BORDER + + + + + + + + + + + + + + + + + + + + + + + + + OnListItemDeselected + + + + OnListItemSelected + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxRIGHT|wxLEFT + 0 + + 4 + 0 + + gSizer5 + none + 1 + 0 + + 5 + wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Move &Up + + 0 + + + 0 + + 1 + MoveUpButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnMoveUpButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Move &Down + + 0 + + + 0 + + 1 + MoveDownButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnMoveDownButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_RIGHT|wxEXPAND|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Remove + + 0 + + + 0 + + 1 + RemoveButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnRemoveButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Remove &All + + 0 + + + 0 + + 1 + RemoveAllButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnRemoveAllButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + 5 + wxBOTH + 2 + + 0 + + fgSizer4 + wxFLEX_GROWMODE_SPECIFIED + none + 1 + 0 + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + + + + + 5 + wxEXPAND + 0 + + + bSizer59 + wxVERTICAL + none + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_OK + OK + + 0 + + + 0 + + 1 + OKButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnOKButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_CANCEL + Cancel + + 0 + + + 0 + + 1 + CancelButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + KeyfilesDialogBase + + + wxDEFAULT_DIALOG_STYLE + + Select Keyfiles + + wxWS_EX_VALIDATE_RECURSIVELY + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer26 + wxVERTICAL + none + + 5 + wxTOP|wxRIGHT|wxLEFT + 1 + + + UpperSizer + wxHORIZONTAL + protected + + 5 + wxEXPAND + 1 + + + PanelSizer + wxVERTICAL + protected + + + + 5 + wxEXPAND + 0 + + + bSizer22 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_OK + OK + + 0 + + + 0 + + 1 + OKButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_CANCEL + Cancel + + 0 + + + 0 + + 1 + CancelButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + WarningStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT + 0 + + + bSizer23 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + KeyfilesNoteSizer + wxVERTICAL + protected + + 5 + wxEXPAND | wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_staticline1 + 1 + + + none + 1 + + Resizable + 1 + + wxLI_HORIZONTAL + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + -1,-1 + + 0 + + 1 + KeyfilesNoteStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND | wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_staticline2 + 1 + + + none + 1 + + Resizable + 1 + + wxLI_HORIZONTAL + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + 2 + wxBOTH + 0 + + 0 + + fgSizer2 + wxFLEX_GROWMODE_SPECIFIED + none + 1 + 0 + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxSYS_COLOUR_WINDOWTEXT + wxID_ANY + More information on keyfiles + + 0 + + + 0 + + 1 + KeyfilesHyperlink + wxSYS_COLOUR_WINDOWTEXT + 1 + + + protected + 1 + + Resizable + 1 + + wxHL_DEFAULT_STYLE + + 0 + + + wxSYS_COLOUR_WINDOWTEXT + + + + + + + OnKeyfilesHyperlinkClick + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Generate Random Keyfile... + + 0 + + + 0 + + 1 + CreateKeyfileButtton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnCreateKeyfileButttonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + KeyfileGeneratorDialogBase + + + wxDEFAULT_DIALOG_STYLE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + OnMouseMotion + + + + + + + + + + + + MainSizer + wxVERTICAL + protected + + 5 + wxEXPAND|wxALL + 1 + + + bSizer144 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + + bSizer145 + wxHORIZONTAL + none + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mixing PRF: + + 0 + + + 0 + + 1 + m_staticText49 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + HashChoice + 1 + + + protected + 1 + + Resizable + 0 + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnHashSelected + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + + + 5 + wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT + 1 + + wxID_ANY + + + sbSizer43 + wxVERTICAL + none + + + 5 + wxEXPAND|wxTOP + 0 + + + bSizer147 + wxHORIZONTAL + none + + 5 + wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Random Pool: + + 0 + + + 0 + + 1 + m_staticText52 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + Courier New,90,90,-1,70,0 + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + RandomPoolStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Show + + 0 + + + 0 + + 1 + ShowRandomPoolCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnShowRandomPoolCheckBoxClicked + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxBOTTOM|wxEXPAND|wxTOP + 0 + + wxID_ANY + Randomness Collected From Mouse Movements + + sbSizer45 + wxVERTICAL + none + + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + CollectedEntropy + 1 + + + protected + 1 + + 2560 + Resizable + 1 + + wxGA_HORIZONTAL|wxGA_SMOOTH + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxALL|wxALIGN_CENTER_HORIZONTAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the keyfile. + + 0 + + + 0 + + 1 + MouseStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + + + 5 + wxALL|wxEXPAND + 1 + + + bSizer162 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + 3 + wxBOTH + 2 + + 0 + + fgSizer8 + wxFLEX_GROWMODE_SPECIFIED + none + 3 + 0 + + 5 + wxALIGN_CENTER_VERTICAL|wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Number of keyfiles: + + 0 + + + 0 + + 1 + m_staticText60 + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + 1 + 9999999 + + 0 + + 1 + + 0 + + 1 + NumberOfKeyfiles + 1 + + + protected + 1 + + Resizable + 1 + + wxSP_ARROW_KEYS + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND | wxALL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_panel18 + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Keyfiles size (in Bytes): + + 0 + + + 0 + + 1 + m_staticText63 + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + 64 + 1048576 + + 0 + + 64 + + 0 + + 1 + KeyfilesSize + 1 + + + protected + 1 + + Resizable + 1 + + wxSP_ARROW_KEYS + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Random size (64 <-> 1048576) + + 0 + + + 0 + + 1 + RandomSizeCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnRandomSizeCheckBoxClicked + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Keyfiles base name: + + 0 + + + 0 + + 1 + m_staticText65 + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + + 0 + + 1 + KeyfilesBaseName + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND | wxALL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_panel19 + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + + bSizer146 + wxHORIZONTAL + none + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Generate and Save Keyfile... + + 0 + + + 0 + + 1 + GenerateButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnGenerateButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_CANCEL + Close + + 0 + + + 0 + + 1 + m_button61 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + LegalNoticesDialogBase + + + wxDEFAULT_DIALOG_STYLE + + VeraCrypt - Legal Notices + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer114 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer115 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + + 0 + + 1 + LegalNoticesTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxTE_MULTILINE|wxTE_READONLY + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_HORIZONTAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_OK + OK + + 0 + + + 0 + + 1 + OKButton + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + wxBOTH + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + MountOptionsDialogBase + + -1,-1 + wxDEFAULT_DIALOG_STYLE + + Enter VeraCrypt Volume Password + + wxWS_EX_VALIDATE_RECURSIVELY + + + + + + + + + + + + + + + + + + OnInitDialog + + + + + + + + + + + + + + + + + + + + + + + MainSizer + wxVERTICAL + protected + + 5 + wxEXPAND + 1 + + + bSizer19 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 0 + + + bSizer14 + wxHORIZONTAL + none + + 5 + wxEXPAND + 1 + + + PasswordSizer + wxVERTICAL + protected + + + + 5 + wxEXPAND + 0 + + + bSizer9 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_OK + OK + + 0 + + + 0 + + 1 + OKButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnOKButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_CANCEL + Cancel + + 0 + + + 0 + + 1 + CancelButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxTOP|wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Op&tions + + 0 + + + 0 + + 1 + OptionsButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnOptionsButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + + bSizer6 + wxVERTICAL + none + + 5 + wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + OptionsPanel + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + wxID_ANY + + + OptionsSizer + wxVERTICAL + protected + + + 5 + wxTOP + 0 + + 0 + protected + 0 + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mount volume as &read-only + + 0 + + + 0 + + 1 + ReadOnlyCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnReadOnlyCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mount volume as removable &medium + + 0 + + + 0 + + 1 + RemovableCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mount partition &using system encryption (preboot authentication) + + 0 + + + 0 + + 1 + PartitionInSystemEncryptionScopeCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 1 + + wxID_ANY + Hidden Volume Protection + + ProtectionSizer + wxVERTICAL + protected + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Protect hidden volume when mounting outer volume + + 0 + + + 0 + + 1 + ProtectionCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnProtectionCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxLEFT + 1 + + + ProtectionPasswordSizer + wxVERTICAL + protected + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxSYS_COLOUR_WINDOWTEXT + wxID_ANY + What is hidden volume protection? + + 0 + + + 0 + + 1 + ProtectionHyperlinkCtrl + wxSYS_COLOUR_WINDOWTEXT + 1 + + + protected + 1 + + Resizable + 1 + + wxHL_DEFAULT_STYLE + + 0 + + + wxSYS_COLOUR_WINDOWTEXT + + + + + + + OnProtectionHyperlinkClick + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + + FilesystemSizer + wxVERTICAL + protected + + 5 + wxEXPAND | wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_panel8 + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + wxID_ANY + Filesystem + + sbSizer28 + wxVERTICAL + none + + + 5 + wxEXPAND|wxBOTTOM + 0 + + + bSizer54 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer55 + wxVERTICAL + none + + 5 + wxTOP|wxRIGHT|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Do &not mount + + 0 + + + 0 + + 1 + NoFilesystemCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnNoFilesystemCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + 0,0 + wxBOTH + 1 + + 0 + + FilesystemOptionsSizer + wxFLEX_GROWMODE_SPECIFIED + protected + 0 + + 5 + 1 + 0 + wxEXPAND|wxTOP + 0 + 1 + + + FilesystemSpacer + wxVERTICAL + protected + + + + 5 + 1 + 0 + wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT + 1 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mount at directory: + + 0 + + + 0 + + 1 + MountPointTextCtrlStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 1 + wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND + 1 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + MountPointTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 2 + wxALIGN_CENTER_VERTICAL|wxRIGHT|wxLEFT + 1 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Se&lect... + + 0 + + + 0 + + 1 + MountPointButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnMountPointButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 0 + wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxLEFT + 2 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mount options: + + 0 + + + 0 + + 1 + FilesystemOptionsStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 2 + 1 + wxALIGN_CENTER_VERTICAL|wxEXPAND|wxTOP|wxRIGHT|wxLEFT + 2 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + FilesystemOptionsTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + NewSecurityTokenKeyfileDialogBase + + + wxDEFAULT_DIALOG_STYLE + + New Security Token Keyfile Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer143 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer144 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + wxID_ANY + + + sbSizer42 + wxVERTICAL + none + + + 5 + wxEXPAND|wxTOP + 1 + + 2 + wxBOTH + + + 0 + + fgSizer7 + wxFLEX_GROWMODE_SPECIFIED + none + 2 + 0 + + 5 + wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Security token: + + 0 + + + 0 + + 1 + m_staticText47 + 1 + + + none + 1 + + Resizable + 1 + + wxALIGN_RIGHT + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + SecurityTokenChoice + 1 + + + protected + 1 + + Resizable + 0 + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Keyfile name: + + 0 + + + 0 + + 1 + m_staticText48 + 1 + + + none + 1 + + Resizable + 1 + + wxALIGN_RIGHT + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + KeyfileNameTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + OnKeyfileNameChanged + + + + + + + + + + + + 5 + wxALIGN_RIGHT|wxALL + 0 + + 0 + 1 + 0 + 0 + 0 + 1 + 0 + 0 + + StdButtons + protected + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + PreferencesDialogBase + + + wxDEFAULT_DIALOG_STYLE + + Preferences + + wxWS_EX_VALIDATE_RECURSIVELY + + + + + + + + + + + + OnClose + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer32 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer41 + wxVERTICAL + none + + 5 + wxEXPAND | wxALL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + PreferencesNotebook + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Security + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + SecurityPage + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer44 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer33 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Auto-Dismount + + AutoDismountSizer + wxVERTICAL + protected + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Dismount All Volumes When + + sbSizer13 + wxVERTICAL + none + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + User logs off + + 0 + + + 0 + + 1 + DismountOnLogOffCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Screen saver is launched + + 0 + + + 0 + + 1 + DismountOnScreenSaverCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnDismountOnScreenSaverCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + System is entering power saving mode + + 0 + + + 0 + + 1 + DismountOnPowerSavingCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnDismountOnPowerSavingCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + + bSizer34 + wxHORIZONTAL + none + + 5 + wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Auto-dismount volume after no data has been read/written to it for + + 0 + + + 0 + + 1 + DismountOnInactivityCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + 1 + 9999 + + 0 + + 1 + + 0 + 60,-1 + 1 + DismountOnInactivitySpinCtrl + 1 + + + protected + 1 + + Resizable + 1 + -1,-1 + wxSP_ARROW_KEYS + + 0 + + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + minutes + + 0 + + + 0 + + 1 + m_staticText5 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Force auto-dismount even if volume contains open files or directories + + 0 + + + 0 + + 1 + ForceAutoDismountCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnForceAutoDismountCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Filesystem + + FilesystemSecuritySizer + wxVERTICAL + protected + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Preserve modification timestamp of file containers + + 0 + + + 0 + + 1 + PreserveTimestampsCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnPreserveTimestampsCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Password Cache + + sbSizer14 + wxVERTICAL + none + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Wipe after VeraCrypt window has been closed + + 0 + + + 0 + + 1 + WipeCacheOnCloseCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Wipe after volume has been auto-dismounted + + 0 + + + 0 + + 1 + WipeCacheOnAutoDismountCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Mount Options + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + DefaultMountOptionsPage + 1 + + + public + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer46 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer35 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Default Mount Options + + sbSizer15 + wxVERTICAL + none + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mount volumes as read-only + + 0 + + + 0 + + 1 + MountReadOnlyCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mount volumes as removable media + + 0 + + + 0 + + 1 + MountRemovableCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Cache passwords in memory + + 0 + + + 0 + + 1 + CachePasswordsCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + TrueCrypt Mode + + 0 + + + 0 + + 1 + TrueCryptModeCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + + bSizer163 + wxHORIZONTAL + none + + 5 + wxALIGN_CENTER_VERTICAL|wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + PKCS5-PRF: + + 0 + + + 0 + + 1 + Pkcs5PrfStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + Pkcs5PrfChoice + 1 + + + protected + 1 + + Resizable + 0 + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Filesystem + + FilesystemSizer + wxVERTICAL + protected + + + 5 + wxEXPAND + 1 + + 2 + wxBOTH + 1 + + 0 + + fgSizer3 + wxFLEX_GROWMODE_SPECIFIED + none + 1 + 0 + + 5 + wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mount options: + + 0 + + + 0 + + 1 + m_staticText6 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + FilesystemOptionsTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Background Task + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + BackgroundTaskPanel + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer61 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer62 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + VeraCrypt Background Task + + sbSizer18 + wxVERTICAL + none + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Enabled + + 0 + + + 0 + + 1 + BackgroundTaskEnabledCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnBackgroundTaskEnabledCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Exit when there are no mounted volumes + + 0 + + + 0 + + 1 + CloseBackgroundTaskOnNoVolumesCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 1 + + wxID_ANY + Task Icon Menu Items + + sbSizer26 + wxVERTICAL + none + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mount Favorite Volumes + + 0 + + + 0 + + 1 + BackgroundTaskMenuMountItemsEnabledCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Open Mounted Volumes + + 0 + + + 0 + + 1 + BackgroundTaskMenuOpenItemsEnabledCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Dismount Mounted Volumes + + 0 + + + 0 + + 1 + BackgroundTaskMenuDismountItemsEnabledCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + System Integration + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + SystemIntegrationPage + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer49 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer37 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 0 + + wxID_ANY + Actions to Perform when User Logs On + + LogOnSizer + wxVERTICAL + protected + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Start VeraCrypt Background Task + + 0 + + + 0 + + 1 + StartOnLogonCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mount favorite volumes + + 0 + + + 0 + + 1 + MountFavoritesOnLogonCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mount all device-hosted VeraCrypt volumes + + 0 + + + 0 + + 1 + MountDevicesOnLogonCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Filesystem Explorer + + ExplorerSizer + wxVERTICAL + protected + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Open Explorer window for successfully mounted volume + + 0 + + + 0 + + 1 + OpenExplorerWindowAfterMountCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Close all Explorer windows of volume being dismounted + + 0 + + + 0 + + 1 + CloseExplorerWindowsOnDismountCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Kernel Services + + KernelServicesSizer + wxVERTICAL + protected + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Do not use kernel cryptographic services + + 0 + + + 0 + + 1 + NoKernelCryptoCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnNoKernelCryptoCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Performance + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + PerformanceOptionsPage + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer151 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 1 + + + bSizer152 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Hardware Acceleration + + sbSizer44 + wxVERTICAL + none + + + 5 + wxEXPAND + 1 + + + bSizer158 + wxHORIZONTAL + none + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Processor (CPU) in this computer supports hardware acceleration for AES: + + 0 + + + 0 + + 1 + m_staticText57 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + AesHwCpuSupportedStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + wxSUNKEN_BORDER + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxBOTTOM + 0 + + 0 + protected + 0 + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Do not accelerate AES encryption/decryption by using the AES instructions of the processor + + 0 + + + 0 + + 1 + NoHardwareCryptoCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnNoHardwareCryptoCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Keyfiles + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + DefaultKeyfilesPage + 1 + + + public + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer40 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer43 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + wxID_ANY + Default Keyfiles + + bSizer42 + wxVERTICAL + none + + + 5 + wxEXPAND + 1 + + + DefaultKeyfilesSizer + wxVERTICAL + protected + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Use keyfiles by default + + 0 + + + 0 + + 1 + UseKeyfilesCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Security Tokens + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + SecurityTokensPage + 1 + + + public + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer127 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer128 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + PKCS #11 Library Path + + sbSizer36 + wxVERTICAL + none + + + 5 + wxEXPAND + 1 + + + bSizer129 + wxHORIZONTAL + none + + 5 + wxALL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + Pkcs11ModulePathTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Select &Library... + + 0 + + + 0 + + 1 + SelectPkcs11ModuleButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnSelectPkcs11ModuleButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Security Options + + sbSizer37 + wxVERTICAL + none + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Close token session (log out) after a volume is successfully mounted + + 0 + + + 0 + + 1 + CloseSecurityTokenSessionsAfterMountCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Hotkeys + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + HotkeysPage + 1 + + + public + 1 + + Resizable + 1 + + + 0 + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer51 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer38 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + wxID_ANY + System-Wide Hotkeys + + sbSizer21 + wxVERTICAL + none + + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + HotkeyListCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + wxSUNKEN_BORDER + + + + + + + + + + + + + + + + + + + + + + + + + OnHotkeyListItemDeselected + + + + OnHotkeyListItemSelected + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Shortcut + + sbSizer23 + wxVERTICAL + none + + + 5 + wxALIGN_RIGHT + 1 + + 3 + wxBOTH + + + 0 + + fgSizer4 + wxFLEX_GROWMODE_SPECIFIED + none + 2 + 0 + + 5 + wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Key to assign: + + 0 + + + 0 + + 1 + m_staticText10 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + HotkeyTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Assign + + 0 + + + 0 + + 1 + AssignHotkeyButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnAssignHotkeyButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxEXPAND + 1 + + 4 + 0 + + gSizer4 + none + 1 + 0 + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Control + + 0 + + + 0 + + 1 + HotkeyControlCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Shift + + 0 + + + 0 + + 1 + HotkeyShiftCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Alt + + 0 + + + 0 + + 1 + HotkeyAltCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Win + + 0 + + + 0 + + 1 + HotkeyWinCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Remove + + 0 + + + 0 + + 1 + RemoveHotkeyButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnRemoveHotkeyButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Options + + sbSizer24 + wxVERTICAL + none + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Play system notification sound after mount/dismount + + 0 + + + 0 + + 1 + BeepAfterHotkeyMountDismountCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Display confirmation message box after dismount + + 0 + + + 0 + + 1 + DisplayMessageAfterHotkeyDismountCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + 0 + 1 + 0 + 0 + 0 + 1 + 0 + 0 + + StdButtons + protected + + OnCancelButtonClick + + + + OnOKButtonClick + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + wxBOTH + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + RandomPoolEnrichmentDialogBase + + + wxDEFAULT_DIALOG_STYLE + + VeraCrypt - Random Pool Enrichment + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + OnMouseMotion + + + + + + + + + + + + MainSizer + wxVERTICAL + protected + + 5 + wxEXPAND|wxALL + 1 + + + bSizer144 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + + bSizer145 + wxHORIZONTAL + none + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Mixing PRF: + + 0 + + + 0 + + 1 + m_staticText49 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + HashChoice + 1 + + + protected + 1 + + Resizable + 0 + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnHashSelected + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + + + 5 + wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT + 1 + + wxID_ANY + + + sbSizer43 + wxVERTICAL + none + + + 5 + wxEXPAND|wxTOP + 0 + + + bSizer147 + wxHORIZONTAL + none + + 5 + wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Random Pool: + + 0 + + + 0 + + 1 + m_staticText52 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + Courier New,90,90,-1,70,0 + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + RandomPoolStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Show + + 0 + + + 0 + + 1 + ShowRandomPoolCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnShowRandomPoolCheckBoxClicked + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxBOTTOM|wxEXPAND|wxTOP + 0 + + wxID_ANY + Randomness Collected From Mouse Movements + + sbSizer45 + wxVERTICAL + none + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + CollectedEntropy + 1 + + + protected + 1 + + 2560 + Resizable + 1 + + wxGA_HORIZONTAL|wxGA_SMOOTH + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxALL|wxALIGN_CENTER_HORIZONTAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases security. When done, click 'Continue'. + + 0 + + + 0 + + 1 + MouseStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + + + 5 + wxEXPAND + 0 + + + bSizer146 + wxHORIZONTAL + none + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_OK + &Continue + + 0 + + + 0 + + 1 + ContinueButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + -1,-1 + SecurityTokenKeyfilesDialogBase + + -1,-1 + wxDEFAULT_DIALOG_STYLE + + Security Token Keyfiles + + wxWS_EX_VALIDATE_RECURSIVELY + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer3 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer138 + wxHORIZONTAL + none + + 5 + wxEXPAND + 1 + + + bSizer142 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + SecurityTokenKeyfileListCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + wxSUNKEN_BORDER + + + + + + + + + + + + + + + + + + + + + + + + OnListItemActivated + OnListItemDeselected + + + + OnListItemSelected + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + + bSizer141 + wxHORIZONTAL + none + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Export... + + 0 + + + 0 + + 1 + ExportButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnExportButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Delete + + 0 + + + 0 + + 1 + DeleteButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnDeleteButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxLEFT + 1 + + 0 + protected + 0 + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Import Keyfile to Token... + + 0 + + + 0 + + 1 + ImportButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnImportButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + + bSizer139 + wxVERTICAL + none + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_OK + OK + + 0 + + + 0 + + 1 + OKButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnOKButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_CANCEL + Cancel + + 0 + + + 0 + + 1 + CancelButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + VolumePropertiesDialogBase + + + wxDEFAULT_DIALOG_STYLE + + Volume Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer49 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + + bSizer50 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + PropertiesListCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + wxSUNKEN_BORDER + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_HORIZONTAL + 0 + + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + + StdButtons + protected + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + + EncryptionOptionsWizardPageBase + + -1,-1 + WizardPage; WizardPage.h + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer93 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer94 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer95 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + wxID_ANY + Encryption Algorithm + + sbSizer29 + wxVERTICAL + none + + + 5 + wxEXPAND + 0 + + + bSizer96 + wxHORIZONTAL + none + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + EncryptionAlgorithmChoice + 1 + + + protected + 1 + + Resizable + 0 + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnEncryptionAlgorithmSelected + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Test + + 0 + + + 0 + + 1 + TestButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnTestButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + EncryptionAlgorithmStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + + bSizer97 + wxHORIZONTAL + none + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxSYS_COLOUR_WINDOWTEXT + wxID_ANY + More information + + 0 + + + 0 + + 1 + EncryptionAlgorithmHyperlink + wxSYS_COLOUR_WINDOWTEXT + 1 + + + protected + 1 + + Resizable + 1 + + wxHL_DEFAULT_STYLE + + 0 + + + wxSYS_COLOUR_WINDOWTEXT + + + + + + + OnEncryptionAlgorithmHyperlinkClick + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + 0 + protected + 0 + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Benchmark + + 0 + + + 0 + + 1 + BenchmarkButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnBenchmarkButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Hash Algorithm + + sbSizer30 + wxHORIZONTAL + none + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + HashChoice + 1 + + + protected + 1 + + Resizable + 0 + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxSYS_COLOUR_WINDOWTEXT + wxID_ANY + Information on hash algorithms + + 0 + + + 0 + + 1 + HashHyperlink + wxSYS_COLOUR_WINDOWTEXT + 1 + + + protected + 1 + + Resizable + 1 + + wxHL_DEFAULT_STYLE + + 0 + + + wxSYS_COLOUR_WINDOWTEXT + + + + + + + OnHashHyperlinkClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + + InfoWizardPageBase + + -1,-1 + WizardPage; WizardPage.h + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer71 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + InfoPageSizer + wxVERTICAL + protected + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + InfoStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + 500,300 + KeyfilesPanelBase + + -1,-1 + + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer19 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer20 + wxHORIZONTAL + none + + 5 + wxEXPAND + 1 + + + bSizer21 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + KeyfilesListCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxLC_NO_SORT_HEADER|wxLC_REPORT + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + wxSUNKEN_BORDER + + + + + + + + + + + + + + + + + + + + + + + + + OnListItemDeselected + + + + OnListItemSelected + + + + + + + + + + + + + OnListSizeChanged + + + + + 5 + wxEXPAND + 0 + + + bSizer137 + wxHORIZONTAL + none + + 5 + wxEXPAND|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Add &Files... + + 0 + + + 0 + + 1 + AddFilesButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnAddFilesButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Add &Path... + + 0 + + + 0 + + 1 + AddDirectoryButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnAddDirectoryButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Add &Token Files... + + 0 + + + 0 + + 1 + AddSecurityTokenSignatureButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnAddSecurityTokenSignatureButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Remove + + 0 + + + 0 + + 1 + RemoveButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnRemoveButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Remove &All + + 0 + + + 0 + + 1 + RemoveAllButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnRemoveAllButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + + ProgressWizardPageBase + + -1,-1 + WizardPage; WizardPage.h + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer81 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + + bSizer82 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + + ProgressSizer + wxHORIZONTAL + protected + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + -1,-1 + 1 + ProgressGauge + 1 + + + protected + 1 + + 100 + Resizable + 1 + -1,-1 + wxGA_HORIZONTAL|wxGA_SMOOTH + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 0 + + 1 + + 0 + 0 + wxID_ANY + &Abort + + 0 + + + 0 + + 1 + AbortButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnAbortButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + InfoStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + 200,65 + SelectDirectoryWizardPageBase + + -1,-1 + WizardPage; WizardPage.h + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer68 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer69 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + + bSizer70 + wxHORIZONTAL + none + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + DirectoryTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + OnDirectoryTextChanged + + + + + + + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Browse... + + 0 + + + 0 + + 1 + BrowseButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnBrowseButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + InfoStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + 300 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + + SingleChoiceWizardPageBase + + -1,-1 + WizardPage; WizardPage.h + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer71 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer77 + wxVERTICAL + none + + 5 + wxEXPAND|wxTOP + 0 + + 0 + protected + 0 + + + + 5 + wxEXPAND + 0 + + + OuterChoicesSizer + wxVERTICAL + protected + + 5 + wxEXPAND + 0 + + + ChoicesSizer + wxVERTICAL + protected + + + + + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + InfoStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + + VolumeCreationProgressWizardPageBase + + -1,-1 + WizardPage; WizardPage.h + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer104 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer105 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 0 + + wxID_ANY + + + sbSizer31 + wxVERTICAL + none + + + 30 + wxEXPAND + 1 + + + KeySamplesUpperSizer + wxVERTICAL + protected + + 3 + wxEXPAND|wxTOP + 1 + + + KeySamplesUpperInnerSizer + wxVERTICAL + protected + + + + + + 5 + wxEXPAND + 0 + + 2 + wxBOTH + + + 0 + + fgSizer5 + wxFLEX_GROWMODE_SPECIFIED + none + 3 + 0 + + 5 + wxALL|wxALIGN_RIGHT|wxALIGN_BOTTOM + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Random Pool: + + 0 + + + 0 + + 1 + m_staticText25 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALIGN_BOTTOM + 1 + + + bSizer126 + wxHORIZONTAL + none + + 7 + wxEXPAND|wxTOP|wxRIGHT|wxALIGN_BOTTOM + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + Courier New,90,90,-1,70,0 + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + RandomPoolSampleStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Show + + 0 + + + 0 + + 1 + DisplayKeysCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnDisplayKeysCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_BOTTOM + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Header Key: + + 0 + + + 0 + + 1 + m_staticText28 + 1 + + + none + 1 + + Resizable + 1 + -1,-1 + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 2 + wxALIGN_BOTTOM|wxEXPAND|wxTOP|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + Courier New,90,90,-1,70,0 + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + HeaderKeySampleStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_BOTTOM + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Master Key: + + 0 + + + 0 + + 1 + m_staticText29 + 1 + + + none + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 2 + wxEXPAND|wxALIGN_BOTTOM|wxTOP|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + Courier New,90,90,-1,70,0 + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + MasterKeySampleStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxLEFT|wxRIGHT + 0 + + wxID_ANY + Randomness Collected From Mouse Movements + + sbSizer45 + wxVERTICAL + none + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + CollectedEntropy + 1 + + + protected + 1 + + 2560 + Resizable + 1 + + wxGA_HORIZONTAL|wxGA_SMOOTH + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT + 0 + + wxID_ANY + + + sbSizer32 + wxVERTICAL + none + + + 5 + wxEXPAND + 0 + + + bSizer106 + wxHORIZONTAL + none + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + -1,-1 + 1 + ProgressGauge + 1 + + + protected + 1 + + 100 + Resizable + 1 + + wxGA_HORIZONTAL|wxGA_SMOOTH + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Abort + + 0 + + + 0 + + 1 + AbortButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnAbortButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 2 + wxEXPAND|wxTOP + 0 + + 3 + 0 + + gSizer6 + none + 1 + 0 + + 5 + wxALIGN_CENTER_VERTICAL|wxEXPAND + 1 + + + bSizer108 + wxHORIZONTAL + none + + 5 + wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Done + + 0 + + + 0 + + 1 + m_staticText31 + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + -1,-1 + 1 + m_panel12 + 1 + + + protected + 1 + + Resizable + 1 + -1,-1 + + 0 + + + + wxSUNKEN_BORDER + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer115 + wxHORIZONTAL + none + + 3 + wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + SizeDoneStaticText + 1 + + + protected + 1 + + Resizable + 1 + + wxALIGN_RIGHT|wxST_NO_AUTORESIZE + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL + 1 + + + bSizer1081 + wxHORIZONTAL + none + + 5 + wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Speed + + 0 + + + 0 + + 1 + m_staticText311 + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_panel121 + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxSUNKEN_BORDER + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer1151 + wxHORIZONTAL + none + + 3 + wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + SpeedStaticText + 1 + + + protected + 1 + + Resizable + 1 + + wxALIGN_RIGHT|wxST_NO_AUTORESIZE + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT + 1 + + + bSizer1082 + wxHORIZONTAL + none + + 5 + wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Left + + 0 + + + 0 + + 1 + m_staticText312 + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_panel122 + 1 + + + protected + 1 + + Resizable + 1 + + + 0 + + + + wxSUNKEN_BORDER|wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer1152 + wxHORIZONTAL + none + + 3 + wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + TimeLeftStaticText + 1 + + + protected + 1 + + Resizable + 1 + + wxALIGN_RIGHT|wxST_NO_AUTORESIZE + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxBOTTOM|wxLEFT|wxRIGHT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + InfoStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + + VolumeLocationWizardPageBase + + -1,-1 + WizardPage; WizardPage.h + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer86 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer87 + wxVERTICAL + none + + 5 + wxEXPAND|wxTOP + 0 + + 0 + protected + 0 + + + + 5 + wxEXPAND + 0 + + + bSizer88 + wxHORIZONTAL + none + + 5 + wxEXPAND + 1 + + + bSizer89 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + + bSizer126 + wxHORIZONTAL + none + + 5 + wxALL|wxALIGN_CENTER_VERTICAL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + -1,-1 + 1 + VolumePathComboBox + 1 + + + protected + 1 + + Resizable + -1 + 1 + + wxCB_DROPDOWN + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + OnVolumePathTextChanged + + + + + + 5 + wxALIGN_CENTER_VERTICAL + 0 + + + bSizer90 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Select &File... + + 0 + + + 0 + -1,-1 + 1 + SelectFileButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnSelectFileButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Select D&evice... + + 0 + + + 0 + -1,-1 + 1 + SelectDeviceButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnSelectDeviceButtonClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 0 + + + bSizer91 + wxHORIZONTAL + none + + 5 + wxLEFT + 0 + + 0 + protected + 0 + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Never save history + + 0 + + + 0 + + 1 + NoHistoryCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnNoHistoryCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxBOTTOM + 0 + + 0 + protected + 0 + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + InfoStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + + VolumeFormatOptionsWizardPageBase + + -1,-1 + WizardPage; WizardPage.h + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer124 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + + bSizer125 + wxVERTICAL + none + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Filesystem Options + + sbSizer33 + wxVERTICAL + none + + + 5 + wxEXPAND + 1 + + 2 + wxBOTH + + + 0 + + fgSizer6 + wxFLEX_GROWMODE_SPECIFIED + none + 2 + 0 + + 5 + wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Filesystem type: + + 0 + + + 0 + + 1 + m_staticText43 + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + FilesystemTypeChoice + 1 + + + protected + 1 + + Resizable + 0 + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnFilesystemTypeSelected + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxALL + 0 + + wxID_ANY + Volume Format Options + + sbSizer34 + wxVERTICAL + none + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Quick format + + 0 + + + 0 + + 1 + QuickFormatCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnQuickFormatCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxTOP|wxBOTTOM + 1 + + 0 + protected + 0 + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + InfoStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + + VolumePasswordPanelBase + + -1,-1 + + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer7 + wxVERTICAL + none + + 5 + wxALL|wxEXPAND + 1 + + 0,0 + wxBOTH + 1 + + 0 + + GridBagSizer + wxFLEX_GROWMODE_SPECIFIED + protected + 0 + + 5 + 1 + 0 + wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxRIGHT + 1 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Password: + + 0 + + + 0 + + 1 + PasswordStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 2 + 1 + wxBOTTOM|wxALIGN_CENTER_VERTICAL|wxEXPAND + 1 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 1 + + 0 + 232,-1 + 1 + PasswordTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxTE_PASSWORD + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + OnTextChanged + + + + + + + + 5 + 1 + 0 + wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT + 2 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Confirm password: + + 0 + + + 0 + + 1 + ConfirmPasswordStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 2 + 1 + wxBOTTOM|wxALIGN_CENTER_VERTICAL|wxEXPAND + 2 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 1 + + 0 + 232,-1 + 1 + ConfirmPasswordTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxTE_PASSWORD + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + OnTextChanged + + + + + + + + 5 + 1 + 0 + wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxRIGHT + 3 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Volume PIM: + + 0 + + + 0 + + 1 + VolumePimStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 1 + wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxEXPAND + 3 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 7 + + 0 + + 1 + VolumePimTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxTE_PASSWORD + + 0 + + + wxFILTER_NUMERIC + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + OnPimChanged + + + + + + + + 5 + 1 + 2 + wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxLEFT|wxRIGHT + 3 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + (Empty or 0 for default iterations) + + 0 + + + 0 + + 1 + VolumePimHelpStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 2 + 1 + wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL + 4 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Use PIM + + 0 + + + 0 + + 1 + PimCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnUsePimCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 2 + 1 + wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL + 5 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Cach&e passwords and keyfiles in memory + + 0 + + + 0 + + 1 + CacheCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 2 + 1 + wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL + 6 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Display password + + 0 + + + 0 + + 1 + DisplayPasswordCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnDisplayPasswordCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 1 + wxTOP|wxRIGHT|wxLEFT + 7 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + U&se keyfiles + + 0 + + + 0 + + 1 + UseKeyfilesCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnUseKeyfilesCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 2 + wxALIGN_RIGHT|wxALIGN_BOTTOM|wxLEFT + 7 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Keyfiles... + + 0 + + + 0 + + 1 + KeyfilesButton + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + OnKeyfilesButtonClick + + + + + + + + + + + + + + + + + + + OnKeyfilesButtonRightDown + OnKeyfilesButtonRightClick + + + + + + + 5 + 1 + 1 + wxEXPAND|wxTOP|wxBOTTOM + 8 + 1 + + + Pkcs5PrfSizer + wxVERTICAL + protected + + + + 5 + 1 + 0 + wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxRIGHT + 9 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + PKCS-5 PRF: + + 0 + + + 0 + + 1 + Pkcs5PrfStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 1 + wxALIGN_CENTER_VERTICAL|wxLEFT + 9 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + "Unchanged" + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + -1,-1 + + 0 + -1,-1 + 1 + Pkcs5PrfChoice + 1 + + + protected + 1 + + Resizable + 0 + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 2 + wxALIGN_CENTER_VERTICAL|wxLEFT + 9 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + TrueCrypt Mode + + 0 + + + 0 + + 1 + TrueCryptModeCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnTrueCryptModeChecked + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 0 + wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxRIGHT + 10 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Header Wipe: + + 0 + + + 0 + + 1 + HeaderWipeCountText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 1 + 1 + wxALL + 10 + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + "1-pass" "3-pass" "7-pass" "35-pass" "256-pass" + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + HeaderWipeCount + 1 + + + protected + 1 + + Resizable + 1 + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + 2 + 1 + wxTOP|wxEXPAND + 11 + 1 + + + PasswordPlaceholderSizer + wxVERTICAL + protected + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + + VolumePasswordWizardPageBase + + -1,-1 + WizardPage; WizardPage.h + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer101 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer102 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + + PasswordPanelSizer + wxVERTICAL + protected + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + InfoStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + + VolumePimWizardPageBase + + -1,-1 + WizardPage; WizardPage.h + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer101 + wxVERTICAL + none + + 5 + wxEXPAND + 1 + + + bSizer102 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + + PimPanelSizer + wxVERTICAL + protected + + 5 + wxEXPAND + 1 + + + PimSizer + wxHORIZONTAL + protected + + 5 + wxALIGN_CENTER_VERTICAL|wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + Volume PIM: + + 0 + + + 0 + + 1 + VolumePimStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 7 + + 0 + + 1 + VolumePimTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + wxTE_PASSWORD + + 0 + + + wxFILTER_NUMERIC + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + OnPimChanged + + + + + + + + 5 + wxALIGN_CENTER_VERTICAL|wxALL + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + (Empty or 0 for default iterations) + + 0 + + + 0 + + 1 + VolumePimHelpStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND + 1 + + + bSizer166 + wxHORIZONTAL + none + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + &Display PIM + + 0 + + + 0 + + 1 + DisplayPimCheckBox + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnDisplayPimCheckBoxClick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + InfoStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + + 1 + 1 + impl_virtual + + + 0 + wxID_ANY + + + VolumeSizeWizardPageBase + + -1,-1 + WizardPage; WizardPage.h + + + + wxTAB_TRAVERSAL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bSizer98 + wxVERTICAL + none + + 5 + wxEXPAND + 0 + + + bSizer99 + wxVERTICAL + none + + 5 + wxEXPAND|wxTOP|wxBOTTOM + 0 + + 0 + protected + 0 + + + + 5 + wxEXPAND + 0 + + + bSizer100 + wxHORIZONTAL + none + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + VolumeSizeTextCtrl + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + + + + + + + + + + + + + + + + + + + + + OnVolumeSizeTextChanged + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + VolumeSizePrefixChoice + 1 + + + protected + 1 + + Resizable + 0 + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + OnVolumeSizePrefixSelected + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxTOP|wxBOTTOM + 0 + + 0 + protected + 0 + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + FreeSpaceStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxEXPAND|wxTOP|wxBOTTOM + 0 + + 0 + protected + 0 + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + InfoStaticText + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + wxAUI_MGR_DEFAULT + + wxBOTH + + 1 + 1 + impl_virtual + + + + 0 + wxID_ANY + + + WaitDialogBase + + -1,-1 + wxCAPTION + + VeraCrypt + + + + + + + + + + + + + + OnWaitDialogClose + + + + + + OnWaitDialogInit + + + + + + + + + + + + + + + + + + + + + + + bSizer160 + wxVERTICAL + none + + 5 + wxALIGN_CENTER_HORIZONTAL|wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + MyLabel + + 0 + + + 0 + + 1 + WaitStaticText + 1 + + + protected + 1 + + Resizable + 1 + + wxALIGN_CENTRE + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + wxALL|wxEXPAND + 0 + + 1 + 1 + 1 + 1 + + + + + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + WaitProgessBar + 1 + + + protected + 1 + + 100 + Resizable + 1 + + wxGA_HORIZONTAL|wxGA_SMOOTH + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Mount/Favorites.cpp b/src/Mount/Favorites.cpp index 10eb6486..77127c27 100644 --- a/src/Mount/Favorites.cpp +++ b/src/Mount/Favorites.cpp @@ -1,1024 +1,1024 @@ -/* - 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 "Tcdefs.h" -#include "Platform/Finally.h" -#include "Platform/ForEach.h" -#include "BootEncryption.h" -#include "Dlgcode.h" -#include "Language.h" -#include "Mount.h" -#include "Common/Resource.h" -#include "Resource.h" -#include "Xml.h" -#include "Favorites.h" - -using namespace std; - -namespace VeraCrypt -{ - vector FavoriteVolumes; - vector SystemFavoriteVolumes; - list FavoritesOnArrivalMountRequired; - list FavoritesMountedOnArrivalStillConnected; - HMENU FavoriteVolumesMenu; - - - BOOL AddMountedVolumeToFavorites (HWND hwndDlg, int driveNo, bool systemFavorites) - { - VOLUME_PROPERTIES_STRUCT prop; - DWORD bytesReturned; - - memset (&prop, 0, sizeof (prop)); - prop.driveNo = driveNo; - - if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &bytesReturned, NULL)) - { - handleWin32Error (hwndDlg, SRC_POS); - return FALSE; - } - - FavoriteVolume favorite; - favorite.MountPoint = L"X:\\"; - favorite.MountPoint[0] = (wchar_t) (prop.driveNo + L'A'); - - favorite.Path = prop.wszVolume; - if (favorite.Path.find (L"\\??\\") == 0) - favorite.Path = favorite.Path.substr (4); - - if (wcslen (prop.wszLabel)) - { - favorite.Label = prop.wszLabel; - favorite.UseLabelInExplorer = true; - } - - if (IsVolumeDeviceHosted (favorite.Path.c_str())) - { - // Get GUID path - wstring volumeDevPath = favorite.Path; - - wchar_t resolvedVolumeDevPath[TC_MAX_PATH]; - if (ResolveSymbolicLink (volumeDevPath.c_str(), resolvedVolumeDevPath, sizeof(resolvedVolumeDevPath))) - volumeDevPath = resolvedVolumeDevPath; - - wchar_t volumeName[TC_MAX_PATH]; - HANDLE find = FindFirstVolume (volumeName, ARRAYSIZE (volumeName)); - - if (find != INVALID_HANDLE_VALUE) - { - do - { - wchar_t findVolumeDevPath[TC_MAX_PATH]; - wstring vn = volumeName; - - if (QueryDosDevice (vn.substr (4, vn.size() - 5).c_str(), findVolumeDevPath, ARRAYSIZE (findVolumeDevPath)) != 0 - && volumeDevPath == findVolumeDevPath) - { - favorite.VolumePathId = volumeName; - break; - } - - } while (FindNextVolume (find, volumeName, ARRAYSIZE (volumeName))); - - FindVolumeClose (find); - } - } - - favorite.ReadOnly = prop.readOnly ? true : false; - favorite.Removable = prop.removable ? true : false; - favorite.SystemEncryption = prop.partitionInInactiveSysEncScope ? true : false; - favorite.OpenExplorerWindow = (bExplore == TRUE); - favorite.Pim = prop.volumePim; - memcpy (favorite.VolumeID, prop.volumeID, VOLUME_ID_SIZE); - - if (favorite.VolumePathId.empty() - && IsVolumeDeviceHosted (favorite.Path.c_str()) - && favorite.Path.find (L"\\\\?\\Volume{") != 0) - { - Warning (favorite.Path.find (L"\\Partition0") == wstring::npos ? "FAVORITE_ADD_PARTITION_TYPE_WARNING" : "FAVORITE_ADD_DRIVE_DEV_WARNING", hwndDlg); - } - - return OrganizeFavoriteVolumes (hwndDlg, systemFavorites, favorite); - } - - - static BOOL CALLBACK FavoriteVolumesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) - { - /* This dialog is used both for System Favorites and non-system Favorites. - - The following options have different meaning in System Favorites mode: - - IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT => MOUNT_SYSTEM_FAVORITES_ON_BOOT - IDC_FAVORITE_DISABLE_HOTKEY => DISABLE_NONADMIN_SYS_FAVORITES_ACCESS - - */ - - WORD lw = LOWORD (wParam); - WORD hw = HIWORD (wParam); - static bool SystemFavoritesMode; - static vector Favorites; - static int SelectedItem; - static HWND FavoriteListControl; - - switch (msg) - { - case WM_INITDIALOG: - { - try - { - FavoriteListControl = GetDlgItem (hwndDlg, IDC_FAVORITE_VOLUMES_LIST); - - FavoriteVolumesDlgProcArguments *args = (FavoriteVolumesDlgProcArguments *) lParam; - SystemFavoritesMode = args->SystemFavorites; - - LocalizeDialog (hwndDlg, SystemFavoritesMode ? "SYSTEM_FAVORITES_DLG_TITLE" : "IDD_FAVORITE_VOLUMES"); - - if (SystemFavoritesMode) - { - RECT rec; - - BootEncryptionStatus bootEncStatus = BootEncryption (hwndDlg).GetStatus(); - - if (!bootEncStatus.DriveMounted) - throw ErrorException ("SYS_FAVORITES_REQUIRE_PBA", SRC_POS); - - ShowWindow (GetDlgItem(hwndDlg, IDC_FAVORITE_MOUNT_ON_LOGON), SW_HIDE); - ShowWindow (GetDlgItem(hwndDlg, IDC_FAVORITE_MOUNT_ON_ARRIVAL), SW_HIDE); - - // MOUNT_SYSTEM_FAVORITES_ON_BOOT - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT), GetString ("MOUNT_SYSTEM_FAVORITES_ON_BOOT")); - - // DISABLE_NONADMIN_SYS_FAVORITES_ACCESS - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY), GetString ("DISABLE_NONADMIN_SYS_FAVORITES_ACCESS")); - - // Group box - - GetClientRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), &rec); - - SetWindowPos (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), 0, 0, 0, - rec.right, - rec.bottom - CompensateYDPI (95), - SWP_NOMOVE | SWP_NOZORDER); - - InvalidateRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), NULL, TRUE); - } - else - { - ShowWindow (GetDlgItem(hwndDlg, IDC_FAV_VOL_OPTIONS_GLOBAL_SETTINGS_BOX), SW_HIDE); - } - - Favorites.clear(); - - LVCOLUMNW column; - SendMessageW (FavoriteListControl, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT); - - memset (&column, 0, sizeof (column)); - column.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; - column.pszText = GetString ("DRIVE"); - column.cx = CompensateXDPI (38); - column.fmt = LVCFMT_CENTER; - SendMessageW (FavoriteListControl, LVM_INSERTCOLUMNW, 1, (LPARAM) &column); - - ++column.iSubItem; - column.fmt = LVCFMT_LEFT; - column.pszText = GetString ("LABEL"); - column.cx = CompensateXDPI (160); - SendMessageW (FavoriteListControl, LVM_INSERTCOLUMNW, 2, (LPARAM) &column); - - ++column.iSubItem; - column.fmt = LVCFMT_LEFT; - column.pszText = GetString ("VOLUME"); - column.cx = CompensateXDPI (330); - SendMessageW (FavoriteListControl, LVM_INSERTCOLUMNW, 3, (LPARAM) &column); - - SetControls (hwndDlg, FavoriteVolume(), SystemFavoritesMode, false); - - if (SystemFavoritesMode) - LoadFavoriteVolumes (Favorites, true); - else - Favorites = FavoriteVolumes; - - if (args->AddFavoriteVolume) - Favorites.push_back (args->NewFavoriteVolume); - - FillListControl (FavoriteListControl, Favorites); - - SelectedItem = -1; - - if (args->AddFavoriteVolume) - { - ListView_SetItemState (FavoriteListControl, Favorites.size() - 1, LVIS_SELECTED, LVIS_SELECTED); - ListView_EnsureVisible (FavoriteListControl, Favorites.size() - 1, FALSE); - } - - if (SystemFavoritesMode) - SetDlgItemTextW (hwndDlg, IDC_FAVORITES_HELP_LINK, GetString ("SYS_FAVORITES_HELP_LINK")); - - ToHyperlink (hwndDlg, IDC_FAVORITES_HELP_LINK); - } - catch (Exception &e) - { - e.Show (hwndDlg); - EndDialog (hwndDlg, IDCLOSE); - } - } - return 1; - - case WM_COMMAND: - - switch (lw) - { - case IDOK: - - /* Global System Favorites settings */ - - if (SystemFavoritesMode) - { - BootEncryption BootEncObj (NULL); - - if (BootEncObj.GetStatus().DriveMounted) - { - try - { - uint32 reqConfig = IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT) ? TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES : 0; - if (reqConfig != (ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES)) - BootEncObj.RegisterSystemFavoritesService (reqConfig ? TRUE : FALSE); - - SetDriverConfigurationFlag (TC_DRIVER_CONFIG_DISABLE_NONADMIN_SYS_FAVORITES_ACCESS, IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY)); - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - } - } - - /* (System) Favorites list */ - - if (SelectedItem != -1 && !Favorites.empty()) - SetFavoriteVolume (hwndDlg, Favorites[SelectedItem], SystemFavoritesMode); - - if (SaveFavoriteVolumes (hwndDlg, Favorites, SystemFavoritesMode)) - { - if (!SystemFavoritesMode) - { - bMountFavoritesOnLogon = FALSE; - - foreach (const FavoriteVolume &favorite, Favorites) - { - if (favorite.MountOnLogOn) - { - bMountFavoritesOnLogon = TRUE; - break; - } - } - - if (!bEnableBkgTask || bCloseBkgTaskWhenNoVolumes || IsNonInstallMode()) - { - foreach (const FavoriteVolume favorite, Favorites) - { - if (favorite.MountOnArrival) - { - Warning ("FAVORITE_ARRIVAL_MOUNT_BACKGROUND_TASK_ERR", hwndDlg); - break; - } - } - } - - FavoriteVolumes = Favorites; - - ManageStartupSeq(); - SaveSettings (hwndDlg); - } - else - SystemFavoriteVolumes = Favorites; - - OnFavoriteVolumesUpdated(); - LoadDriveLetters (hwndDlg, GetDlgItem (MainDlg, IDC_DRIVELIST), 0); - - EndDialog (hwndDlg, IDOK); - } - - return 1; - - case IDCANCEL: - EndDialog (hwndDlg, IDCLOSE); - return 1; - - case IDC_FAVORITE_MOVE_DOWN: - if (SelectedItem != -1 && Favorites.size() > (size_t) SelectedItem + 1) - { - swap (Favorites[SelectedItem], Favorites[SelectedItem + 1]); - - FillListControl (FavoriteListControl, Favorites); - ++SelectedItem; - ListView_SetItemState (FavoriteListControl, SelectedItem, LVIS_SELECTED, LVIS_SELECTED); - ListView_EnsureVisible (FavoriteListControl, SelectedItem, FALSE); - } - return 1; - - case IDC_FAVORITE_MOVE_UP: - if (SelectedItem > 0) - { - swap (Favorites[SelectedItem], Favorites[SelectedItem - 1]); - - FillListControl (FavoriteListControl, Favorites); - --SelectedItem; - ListView_SetItemState (FavoriteListControl, SelectedItem, LVIS_SELECTED, LVIS_SELECTED); - ListView_EnsureVisible (FavoriteListControl, SelectedItem, FALSE); - } - return 1; - - case IDC_FAVORITE_REMOVE: - if (SelectedItem != -1) - { - Favorites.erase (Favorites.begin() + SelectedItem); - FillListControl (GetDlgItem (hwndDlg, IDC_FAVORITE_VOLUMES_LIST), Favorites); - SetControls (hwndDlg, FavoriteVolume(), SystemFavoritesMode, false); - SelectedItem = -1; - } - return 1; - - - case IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT: // Note that this option means "MOUNT_SYSTEM_FAVORITES_ON_BOOT" when SystemFavoritesMode is true - if (SystemFavoritesMode) - { - // MOUNT_SYSTEM_FAVORITES_ON_BOOT - - if (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT)) - { - WarningDirect ((wstring (GetString ("SYS_FAVORITES_KEYBOARD_WARNING")) + L"\n\n" + GetString ("BOOT_PASSWORD_CACHE_KEYBOARD_WARNING")).c_str(), hwndDlg); - - if (!IsServerOS() && !IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY)) - Info ("SYS_FAVORITES_ADMIN_ONLY_INFO", hwndDlg); - } - } - return 1; - - case IDC_FAVORITE_DISABLE_HOTKEY: // Note that this option means "DISABLE_NONADMIN_SYS_FAVORITES_ACCESS" when SystemFavoritesMode is true - if (SystemFavoritesMode) - { - // DISABLE_NONADMIN_SYS_FAVORITES_ACCESS - - if (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY)) - WarningDirect ((wstring (GetString ("SYS_FAVORITES_ADMIN_ONLY_WARNING")) + L"\n\n" + GetString ("SETTING_REQUIRES_REBOOT")).c_str(), hwndDlg); - else - Warning ("SETTING_REQUIRES_REBOOT", hwndDlg); - } - return 1; - - case IDC_FAVORITES_HELP_LINK: - Applink (SystemFavoritesMode ? "sysfavorites" : "favorites", TRUE, ""); - return 1; - case IDC_SHOW_PIM: - HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PIM, IDC_PIM, 0); - return 1; - - case IDC_PIM: - if (hw == EN_CHANGE) - { - int pim = GetPim (hwndDlg, IDC_PIM); - if (pim > (SystemFavoritesMode? MAX_BOOT_PIM_VALUE: MAX_PIM_VALUE)) - { - SetDlgItemText (hwndDlg, IDC_PIM, L""); - SetFocus (GetDlgItem(hwndDlg, IDC_PIM)); - Warning (SystemFavoritesMode? "PIM_SYSENC_TOO_BIG": "PIM_TOO_BIG", hwndDlg); - return 1; - } - } - break; - } - - return 0; - - case WM_NOTIFY: - if (((LPNMHDR) lParam)->code == LVN_ITEMCHANGED) - { - static bool reentry = false; - if (reentry) - break; - - reentry = true; - - if (SelectedItem != -1) - { - SetFavoriteVolume (hwndDlg, Favorites[SelectedItem], SystemFavoritesMode); - FillListControlSubItems (FavoriteListControl, SelectedItem, Favorites[SelectedItem]); - } - - SelectedItem = ListView_GetNextItem (GetDlgItem (hwndDlg, IDC_FAVORITE_VOLUMES_LIST), -1, LVIS_SELECTED); - - if (SelectedItem != -1) - SetControls (hwndDlg, Favorites[SelectedItem], SystemFavoritesMode); - else - SetControls (hwndDlg, FavoriteVolume(), SystemFavoritesMode, false); - - reentry = false; - return 1; - } - break; - - case WM_CLOSE: - EndDialog (hwndDlg, IDCLOSE); - return 1; - case WM_CTLCOLORSTATIC: - { - HDC hdc = (HDC) wParam; - HWND hw = (HWND) lParam; - if (hw == GetDlgItem(hwndDlg, IDC_FAVORITE_VOLUME_ID)) - { - // This the favorite ID field. Make its background like normal edit - HBRUSH hbr = GetSysColorBrush (COLOR_WINDOW); - ::SelectObject(hdc, hbr); - return (BOOL) hbr; - } - } - break; - } - - return 0; - } - - - static void FillFavoriteVolumesMenu () - { - while (DeleteMenu (FavoriteVolumesMenu, 7, MF_BYPOSITION)) { } - - if (FavoriteVolumes.empty()) - return; - - AppendMenu (FavoriteVolumesMenu, MF_SEPARATOR, 0, L""); - - int i = 0; - foreach (const FavoriteVolume &favorite, FavoriteVolumes) - { - UINT flags = MF_STRING; - - if (favorite.DisconnectedDevice) - flags |= MF_GRAYED; - - wstring menuText = favorite.Path; - if (favorite.DisconnectedDevice) - menuText = favorite.Label.empty() ? wstring (L"(") + GetString ("FAVORITE_DISCONNECTED_DEV") + L")" : L""; - - if (!favorite.Label.empty()) - { - if (favorite.DisconnectedDevice) - menuText = favorite.Label + L" " + menuText; - else - menuText = favorite.Label; - } - - AppendMenuW (FavoriteVolumesMenu, flags, TC_FAVORITE_MENU_CMD_ID_OFFSET + i++, - (menuText + L"\t" + favorite.MountPoint.substr (0, 2)).c_str()); - } - } - - - static void FillListControl (HWND favoriteListControl, vector &favorites) - { - SendMessage (favoriteListControl, LVM_DELETEALLITEMS, 0, 0); - - int line = 0; - foreach (const FavoriteVolume favorite, favorites) - { - ListItemAdd (favoriteListControl, line, (wchar_t *) favorite.MountPoint.substr (0, 2).c_str()); - FillListControlSubItems (favoriteListControl, line++, favorite); - } - } - - - static void FillListControlSubItems (HWND FavoriteListControl, int line, const FavoriteVolume &favorite) - { - ListSubItemSet (FavoriteListControl, line, 1, (wchar_t *) favorite.Label.c_str()); - - if (favorite.DisconnectedDevice) - ListSubItemSet (FavoriteListControl, line, 2, (wchar_t *) (wstring (L"(") + GetString ("FAVORITE_DISCONNECTED_DEV") + L")").c_str()); - else - ListSubItemSet (FavoriteListControl, line, 2, (wchar_t *) favorite.Path.c_str()); - } - - - wstring GetFavoriteVolumeLabel (const wstring &volumePath, bool& useInExplorer) - { - foreach (const FavoriteVolume &favorite, FavoriteVolumes) - { - if (favorite.Path == volumePath) - { - useInExplorer = favorite.UseLabelInExplorer; - return favorite.Label; - } - } - - foreach (const FavoriteVolume &favorite, SystemFavoriteVolumes) - { - if (favorite.Path == volumePath) - { - useInExplorer = favorite.UseLabelInExplorer; - return favorite.Label; - } - } - - useInExplorer = false; - return wstring(); - } - - - void LoadFavoriteVolumes () - { - LoadFavoriteVolumes (FavoriteVolumes, false); - - try - { - LoadFavoriteVolumes (SystemFavoriteVolumes, true, true); - } - catch (...) { } // Ignore errors as SystemFavoriteVolumes list is used only for resolving volume paths to labels - - OnFavoriteVolumesUpdated(); - } - - - void LoadFavoriteVolumes (vector &favorites, bool systemFavorites, bool noUacElevation) - { - favorites.clear(); - wstring favoritesFilePath = systemFavorites ? GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false) : GetConfigPath (TC_APPD_FILENAME_FAVORITE_VOLUMES); - - if (systemFavorites && !IsAdmin() && !noUacElevation) - { - favoritesFilePath = GetConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES); - - try - { - BootEncryption bootEnc (MainDlg); - bootEnc.CopyFileAdmin (GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false).c_str(), favoritesFilePath.c_str()); - } - catch (SystemException &e) - { - if (e.ErrorCode == ERROR_FILE_NOT_FOUND) - return; - - throw; - } - } - - DWORD size; - char *favoritesXml = LoadFile (favoritesFilePath.c_str(), &size); - - if (systemFavorites && !IsAdmin() && !noUacElevation) - DeleteFile (GetConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES)); - - char *xml = favoritesXml; - char mountPoint[MAX_PATH], volume[MAX_PATH]; - - if (xml == NULL) - return; - - while (xml = XmlFindElement (xml, "volume")) - { - FavoriteVolume favorite; - - XmlGetAttributeText (xml, "mountpoint", mountPoint, sizeof (mountPoint)); - favorite.MountPoint = Utf8StringToWide (mountPoint); - - XmlGetNodeText (xml, volume, sizeof (volume)); - favorite.Path = Utf8StringToWide (volume); - - char label[1024]; - - XmlGetAttributeText (xml, "ID", label, sizeof (label)); - if (strlen (label) == (2*VOLUME_ID_SIZE)) - { - std::vector arr; - if (HexWideStringToArray (Utf8StringToWide (label).c_str(), arr) && arr.size() == VOLUME_ID_SIZE) - { - memcpy (favorite.VolumeID, &arr[0], VOLUME_ID_SIZE); - } - } - - XmlGetAttributeText (xml, "label", label, sizeof (label)); - favorite.Label = Utf8StringToWide (label); - - XmlGetAttributeText (xml, "pim", label, sizeof (label)); - if (strlen(label) == 0) - { - /* support old attribute name before it was changed to PIM*/ - XmlGetAttributeText (xml, "pin", label, sizeof (label)); - } - favorite.Pim = strtol (label, NULL, 10); - if (favorite.Pim < 0 || favorite.Pim > (systemFavorites? MAX_BOOT_PIM_VALUE : MAX_PIM_VALUE)) - favorite.Pim = 0; - - char boolVal[2]; - XmlGetAttributeText (xml, "readonly", boolVal, sizeof (boolVal)); - if (boolVal[0]) - favorite.ReadOnly = (boolVal[0] == '1'); - - XmlGetAttributeText (xml, "removable", boolVal, sizeof (boolVal)); - if (boolVal[0]) - favorite.Removable = (boolVal[0] == '1'); - - XmlGetAttributeText (xml, "system", boolVal, sizeof (boolVal)); - if (boolVal[0]) - favorite.SystemEncryption = (boolVal[0] == '1'); - - XmlGetAttributeText (xml, "noHotKeyMount", boolVal, sizeof (boolVal)); - if (boolVal[0]) - favorite.DisableHotkeyMount = (boolVal[0] == '1'); - - XmlGetAttributeText (xml, "openExplorerWindow", boolVal, sizeof (boolVal)); - if (boolVal[0]) - favorite.OpenExplorerWindow = (boolVal[0] == '1'); - - XmlGetAttributeText (xml, "mountOnArrival", boolVal, sizeof (boolVal)); - if (boolVal[0]) - favorite.MountOnArrival = (boolVal[0] == '1'); - - XmlGetAttributeText (xml, "mountOnLogOn", boolVal, sizeof (boolVal)); - if (boolVal[0]) - favorite.MountOnLogOn = (boolVal[0] == '1'); - - XmlGetAttributeText (xml, "useLabelInExplorer", boolVal, sizeof (boolVal)); - if (boolVal[0]) - favorite.UseLabelInExplorer = (boolVal[0] == '1') && !favorite.ReadOnly; - - XmlGetAttributeText (xml, "useVolumeID", boolVal, sizeof (boolVal)); - if (boolVal[0]) - favorite.UseVolumeID = (boolVal[0] == '1') && !IsRepeatedByteArray (0, favorite.VolumeID, sizeof (favorite.VolumeID)); - - if (favorite.Path.find (L"\\\\?\\Volume{") == 0 && favorite.Path.rfind (L"}\\") == favorite.Path.size() - 2) - { - wstring resolvedPath = VolumeGuidPathToDevicePath (favorite.Path); - if (!resolvedPath.empty()) - { - favorite.DisconnectedDevice = false; - favorite.VolumePathId = favorite.Path; - favorite.Path = resolvedPath; - } - else - favorite.DisconnectedDevice = true; - } - - favorites.push_back (favorite); - xml++; - } - - free (favoritesXml); - } - - - static void OnFavoriteVolumesUpdated () - { - FillFavoriteVolumesMenu(); - - FavoritesOnArrivalMountRequired.clear(); - - foreach (const FavoriteVolume favorite, FavoriteVolumes) - { - if (favorite.MountOnArrival) - { - FavoritesOnArrivalMountRequired.push_back (favorite); - - if (IsMountedVolume (favorite.Path.c_str())) - { - bool present = false; - - foreach (const FavoriteVolume favoriteConnected, FavoritesMountedOnArrivalStillConnected) - { - if (favorite.Path == favoriteConnected.Path) - { - present = true; - break; - } - } - - if (!present) - FavoritesMountedOnArrivalStillConnected.push_back (favorite); - } - } - } - } - - - BOOL OrganizeFavoriteVolumes (HWND hwndDlg, bool systemFavorites, const FavoriteVolume &newFavorite) - { - FavoriteVolumesDlgProcArguments args; - args.SystemFavorites = systemFavorites; - - if (!newFavorite.Path.empty()) - { - args.AddFavoriteVolume = true; - args.NewFavoriteVolume = newFavorite; - } - else - args.AddFavoriteVolume = false; - - return DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_FAVORITE_VOLUMES), hwndDlg, (DLGPROC) FavoriteVolumesDlgProc, (LPARAM) &args) == IDOK; - } - - - bool SaveFavoriteVolumes (HWND hwndDlg, const vector &favorites, bool systemFavorites) - { - FILE *f; - int cnt = 0; - - f = _wfopen (GetConfigPath (systemFavorites ? TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES : TC_APPD_FILENAME_FAVORITE_VOLUMES), L"w,ccs=UTF-8"); - if (f == NULL) - { - handleWin32Error (MainDlg, SRC_POS); - return false; - } - - XmlWriteHeader (f); - fputws (L"\n\t", f); - - foreach (const FavoriteVolume &favorite, favorites) - { - wchar_t tq[2048]; - - if (systemFavorites && favorite.Path.find (L"\\\\") == 0 && favorite.Path.find (L"Volume{") == wstring::npos) - Warning ("SYSTEM_FAVORITE_NETWORK_PATH_ERR", hwndDlg); - - XmlQuoteTextW (!favorite.VolumePathId.empty() ? favorite.VolumePathId.c_str() : favorite.Path.c_str(), tq, ARRAYSIZE (tq)); - - wstring s = L"\n\t\t 0) - s += L" pim=\"" + IntToWideString(favorite.Pim) + L"\""; - - if (favorite.ReadOnly) - s += L" readonly=\"1\""; - - if (favorite.Removable) - s += L" removable=\"1\""; - - if (favorite.SystemEncryption) - s += L" system=\"1\""; - - if (favorite.MountOnArrival) - s += L" mountOnArrival=\"1\""; - - if (favorite.MountOnLogOn) - s += L" mountOnLogOn=\"1\""; - - if (favorite.DisableHotkeyMount) - s += L" noHotKeyMount=\"1\""; - - if (favorite.OpenExplorerWindow) - s += L" openExplorerWindow=\"1\""; - - if (favorite.UseLabelInExplorer && !favorite.ReadOnly) - s += L" useLabelInExplorer=\"1\""; - - if (favorite.UseVolumeID && !IsRepeatedByteArray (0, favorite.VolumeID, sizeof (favorite.VolumeID))) - s += L" useVolumeID=\"1\""; - - s += L">" + wstring (tq) + L""; - - fwprintf (f, L"%ws", s.c_str()); - cnt++; - } - - fputws (L"\n\t", f); - XmlWriteFooter (f); - - if (!CheckFileStreamWriteErrors (hwndDlg, f, systemFavorites ? TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES : TC_APPD_FILENAME_FAVORITE_VOLUMES)) - { - fclose (f); - return false; - } - - fclose (f); - - BootEncryption bootEnc (MainDlg); - - if (systemFavorites) - { - finally_do ({ _wremove (GetConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES)); }); - - try - { - bootEnc.DeleteFileAdmin (GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false).c_str()); - } - catch (UserAbort&) { return false; } - catch (...) { } - - try - { - if (cnt != 0) - { - bootEnc.CopyFileAdmin (GetConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES), GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false).c_str()); - - if (!(ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES)) - Info ("SYS_FAVORITE_VOLUMES_SAVED", hwndDlg); - } - } - catch (Exception &e) - { - e.Show (NULL); - } - } - - if (cnt == 0) - { - if (systemFavorites) - { - try - { - bootEnc.DeleteFileAdmin (GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false).c_str()); - } - catch (...) { } - } - else - _wremove (GetConfigPath (TC_APPD_FILENAME_FAVORITE_VOLUMES)); - } - - return true; - } - - - static void SetControls (HWND hwndDlg, const FavoriteVolume &favorite, bool systemFavoritesMode, bool enable) - { - BOOL bIsDevice = favorite.DisconnectedDevice || IsVolumeDeviceHosted (favorite.Path.c_str()) || !enable; - if (favorite.Pim > 0) - { - wchar_t szTmp[MAX_PIM + 1]; - StringCbPrintfW (szTmp, sizeof(szTmp), L"%d", favorite.Pim); - SetDlgItemText (hwndDlg, IDC_PIM, szTmp); - } - else - SetDlgItemText (hwndDlg, IDC_PIM, L""); - SetDlgItemTextW (hwndDlg, IDC_FAVORITE_LABEL, favorite.Label.c_str()); - SetCheckBox (hwndDlg, IDC_FAVORITE_USE_LABEL_IN_EXPLORER, favorite.UseLabelInExplorer); - SetCheckBox (hwndDlg, IDC_FAVORITE_MOUNT_ON_LOGON, favorite.MountOnLogOn); - SetCheckBox (hwndDlg, IDC_FAVORITE_MOUNT_ON_ARRIVAL, favorite.MountOnArrival); - SetCheckBox (hwndDlg, IDC_FAVORITE_MOUNT_READONLY, favorite.ReadOnly); - SetCheckBox (hwndDlg, IDC_FAVORITE_MOUNT_REMOVABLE, favorite.Removable); - SetCheckBox (hwndDlg, IDC_FAVORITE_USE_VOLUME_ID, favorite.UseVolumeID && bIsDevice); - - if (IsRepeatedByteArray (0, favorite.VolumeID, sizeof (favorite.VolumeID)) || !bIsDevice) - { - SetDlgItemText (hwndDlg, IDC_FAVORITE_VOLUME_ID, L""); - } - else - SetDlgItemText (hwndDlg, IDC_FAVORITE_VOLUME_ID, ArrayToHexWideString (favorite.VolumeID, sizeof (favorite.VolumeID)).c_str()); - - if (systemFavoritesMode) - { - uint32 driverConfig = ReadDriverConfigurationFlags(); - - // MOUNT_SYSTEM_FAVORITES_ON_BOOT - CheckDlgButton (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT, (driverConfig & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES) ? BST_CHECKED : BST_UNCHECKED); - - // DISABLE_NONADMIN_SYS_FAVORITES_ACCESS - CheckDlgButton (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY, (driverConfig & TC_DRIVER_CONFIG_DISABLE_NONADMIN_SYS_FAVORITES_ACCESS) ? BST_CHECKED : BST_UNCHECKED); - } - else - { - SetCheckBox (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT, favorite.OpenExplorerWindow); - SetCheckBox (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY, favorite.DisableHotkeyMount); - } - - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_MOVE_UP), enable); - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_MOVE_DOWN), enable); - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_REMOVE), enable); - EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), enable); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), enable); - EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PIM), enable); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), enable); - EnableWindow (GetDlgItem (hwndDlg, IDT_FAVORITE_LABEL), enable); - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_LABEL), enable); - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_USE_LABEL_IN_EXPLORER), enable); - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_MOUNT_ON_LOGON), enable && !systemFavoritesMode); - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_MOUNT_ON_ARRIVAL), enable && !systemFavoritesMode); - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_MOUNT_READONLY), enable); - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_MOUNT_REMOVABLE), enable); - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT), enable || systemFavoritesMode); - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY), enable || systemFavoritesMode); - EnableWindow (GetDlgItem (hwndDlg, IDT_VOLUME_ID), enable && bIsDevice); - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_VOLUME_ID), enable && bIsDevice); - EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_USE_VOLUME_ID), enable && bIsDevice && !IsRepeatedByteArray (0, favorite.VolumeID, sizeof (favorite.VolumeID))); - - ShowWindow (GetDlgItem (hwndDlg, IDT_VOLUME_ID), bIsDevice? SW_SHOW : SW_HIDE); - ShowWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_VOLUME_ID), bIsDevice? SW_SHOW : SW_HIDE); - ShowWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_USE_VOLUME_ID), bIsDevice? SW_SHOW : SW_HIDE); - - // Group box - RECT boxRect, checkRect, labelRect; - - GetWindowRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), &boxRect); - GetWindowRect (GetDlgItem (hwndDlg, IDC_FAVORITE_USE_VOLUME_ID), &checkRect); - GetWindowRect (GetDlgItem (hwndDlg, IDT_VOLUME_ID), &labelRect); - - if (!bIsDevice && (boxRect.top < checkRect.top)) - { - POINT pt = {boxRect.left, checkRect.bottom}; - ScreenToClient (hwndDlg, &pt); - SetWindowPos (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), 0, pt.x, pt.y, - boxRect.right - boxRect.left, - boxRect.bottom - checkRect.bottom, - SWP_NOZORDER); - - InvalidateRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), NULL, TRUE); - } - - if (bIsDevice && (boxRect.top >= checkRect.top)) - { - POINT pt = {boxRect.left, labelRect.top - CompensateYDPI (10)}; - ScreenToClient (hwndDlg, &pt); - SetWindowPos (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), 0, pt.x, pt.y, - boxRect.right - boxRect.left, - boxRect.bottom - labelRect.top + CompensateYDPI (10), - SWP_NOZORDER); - - InvalidateRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), NULL, TRUE); - } - } - - - static void SetFavoriteVolume (HWND hwndDlg, FavoriteVolume &favorite, bool systemFavoritesMode) - { - wchar_t label[1024]; - if (GetDlgItemTextW (hwndDlg, IDC_FAVORITE_LABEL, label, ARRAYSIZE (label)) != 0) - { - favorite.Label = label; - - for (size_t i = 0; i < favorite.Label.size(); ++i) - { - if (favorite.Label[i] == L'"') - favorite.Label.at (i) = L'\''; - } - } - else - favorite.Label.clear(); - - favorite.Pim = GetPim (hwndDlg, IDC_PIM); - favorite.UseLabelInExplorer = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_USE_LABEL_IN_EXPLORER) != 0); - favorite.UseVolumeID = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_USE_VOLUME_ID) != 0); - - favorite.ReadOnly = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_MOUNT_READONLY) != 0); - favorite.Removable = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_MOUNT_REMOVABLE) != 0); - - if (!systemFavoritesMode) - { - favorite.MountOnLogOn = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_MOUNT_ON_LOGON) != 0); - favorite.MountOnArrival = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_MOUNT_ON_ARRIVAL) != 0); - favorite.DisableHotkeyMount = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY) != 0); - favorite.OpenExplorerWindow = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT) != 0); - } - - if (favorite.VolumePathId.empty() - && IsVolumeDeviceHosted (favorite.Path.c_str()) - && favorite.Path.find (L"\\\\?\\Volume{") != 0) - { - bool partition = (favorite.Path.find (L"\\Partition0") == wstring::npos); - - if (!favorite.Label.empty()) - { - ErrorDirect ((GetString (partition ? "FAVORITE_LABEL_PARTITION_TYPE_ERR" : "FAVORITE_LABEL_DEVICE_PATH_ERR") + wstring (L"\n\n") + favorite.Path).c_str(), hwndDlg); - favorite.Label.clear(); - } - - if (favorite.MountOnArrival) - { - ErrorDirect ((GetString (partition ? "FAVORITE_ARRIVAL_MOUNT_PARTITION_TYPE_ERR" : "FAVORITE_ARRIVAL_MOUNT_DEVICE_PATH_ERR") + wstring (L"\n\n") + favorite.Path).c_str(), hwndDlg); - favorite.MountOnArrival = false; - } - } - - if (favorite.MountOnArrival && favorite.Path.find (L"\\\\") == 0 && favorite.Path.find (L"Volume{") == wstring::npos) - { - Error ("FAVORITE_ARRIVAL_MOUNT_NETWORK_PATH_ERR", hwndDlg); - favorite.MountOnArrival = false; - } - } - - - void UpdateDeviceHostedFavoriteVolumes () - { - try - { - LoadFavoriteVolumes(); - } - catch (Exception &e) - { - e.Show (MainDlg); - } - } -} +/* + 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 "Tcdefs.h" +#include "Platform/Finally.h" +#include "Platform/ForEach.h" +#include "BootEncryption.h" +#include "Dlgcode.h" +#include "Language.h" +#include "Mount.h" +#include "Common/Resource.h" +#include "Resource.h" +#include "Xml.h" +#include "Favorites.h" + +using namespace std; + +namespace VeraCrypt +{ + vector FavoriteVolumes; + vector SystemFavoriteVolumes; + list FavoritesOnArrivalMountRequired; + list FavoritesMountedOnArrivalStillConnected; + HMENU FavoriteVolumesMenu; + + + BOOL AddMountedVolumeToFavorites (HWND hwndDlg, int driveNo, bool systemFavorites) + { + VOLUME_PROPERTIES_STRUCT prop; + DWORD bytesReturned; + + memset (&prop, 0, sizeof (prop)); + prop.driveNo = driveNo; + + if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &bytesReturned, NULL)) + { + handleWin32Error (hwndDlg, SRC_POS); + return FALSE; + } + + FavoriteVolume favorite; + favorite.MountPoint = L"X:\\"; + favorite.MountPoint[0] = (wchar_t) (prop.driveNo + L'A'); + + favorite.Path = prop.wszVolume; + if (favorite.Path.find (L"\\??\\") == 0) + favorite.Path = favorite.Path.substr (4); + + if (wcslen (prop.wszLabel)) + { + favorite.Label = prop.wszLabel; + favorite.UseLabelInExplorer = true; + } + + if (IsVolumeDeviceHosted (favorite.Path.c_str())) + { + // Get GUID path + wstring volumeDevPath = favorite.Path; + + wchar_t resolvedVolumeDevPath[TC_MAX_PATH]; + if (ResolveSymbolicLink (volumeDevPath.c_str(), resolvedVolumeDevPath, sizeof(resolvedVolumeDevPath))) + volumeDevPath = resolvedVolumeDevPath; + + wchar_t volumeName[TC_MAX_PATH]; + HANDLE find = FindFirstVolume (volumeName, ARRAYSIZE (volumeName)); + + if (find != INVALID_HANDLE_VALUE) + { + do + { + wchar_t findVolumeDevPath[TC_MAX_PATH]; + wstring vn = volumeName; + + if (QueryDosDevice (vn.substr (4, vn.size() - 5).c_str(), findVolumeDevPath, ARRAYSIZE (findVolumeDevPath)) != 0 + && volumeDevPath == findVolumeDevPath) + { + favorite.VolumePathId = volumeName; + break; + } + + } while (FindNextVolume (find, volumeName, ARRAYSIZE (volumeName))); + + FindVolumeClose (find); + } + } + + favorite.ReadOnly = prop.readOnly ? true : false; + favorite.Removable = prop.removable ? true : false; + favorite.SystemEncryption = prop.partitionInInactiveSysEncScope ? true : false; + favorite.OpenExplorerWindow = (bExplore == TRUE); + favorite.Pim = prop.volumePim; + memcpy (favorite.VolumeID, prop.volumeID, VOLUME_ID_SIZE); + + if (favorite.VolumePathId.empty() + && IsVolumeDeviceHosted (favorite.Path.c_str()) + && favorite.Path.find (L"\\\\?\\Volume{") != 0) + { + Warning (favorite.Path.find (L"\\Partition0") == wstring::npos ? "FAVORITE_ADD_PARTITION_TYPE_WARNING" : "FAVORITE_ADD_DRIVE_DEV_WARNING", hwndDlg); + } + + return OrganizeFavoriteVolumes (hwndDlg, systemFavorites, favorite); + } + + + static BOOL CALLBACK FavoriteVolumesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) + { + /* This dialog is used both for System Favorites and non-system Favorites. + + The following options have different meaning in System Favorites mode: + + IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT => MOUNT_SYSTEM_FAVORITES_ON_BOOT + IDC_FAVORITE_DISABLE_HOTKEY => DISABLE_NONADMIN_SYS_FAVORITES_ACCESS + + */ + + WORD lw = LOWORD (wParam); + WORD hw = HIWORD (wParam); + static bool SystemFavoritesMode; + static vector Favorites; + static int SelectedItem; + static HWND FavoriteListControl; + + switch (msg) + { + case WM_INITDIALOG: + { + try + { + FavoriteListControl = GetDlgItem (hwndDlg, IDC_FAVORITE_VOLUMES_LIST); + + FavoriteVolumesDlgProcArguments *args = (FavoriteVolumesDlgProcArguments *) lParam; + SystemFavoritesMode = args->SystemFavorites; + + LocalizeDialog (hwndDlg, SystemFavoritesMode ? "SYSTEM_FAVORITES_DLG_TITLE" : "IDD_FAVORITE_VOLUMES"); + + if (SystemFavoritesMode) + { + RECT rec; + + BootEncryptionStatus bootEncStatus = BootEncryption (hwndDlg).GetStatus(); + + if (!bootEncStatus.DriveMounted) + throw ErrorException ("SYS_FAVORITES_REQUIRE_PBA", SRC_POS); + + ShowWindow (GetDlgItem(hwndDlg, IDC_FAVORITE_MOUNT_ON_LOGON), SW_HIDE); + ShowWindow (GetDlgItem(hwndDlg, IDC_FAVORITE_MOUNT_ON_ARRIVAL), SW_HIDE); + + // MOUNT_SYSTEM_FAVORITES_ON_BOOT + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT), GetString ("MOUNT_SYSTEM_FAVORITES_ON_BOOT")); + + // DISABLE_NONADMIN_SYS_FAVORITES_ACCESS + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY), GetString ("DISABLE_NONADMIN_SYS_FAVORITES_ACCESS")); + + // Group box + + GetClientRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), &rec); + + SetWindowPos (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), 0, 0, 0, + rec.right, + rec.bottom - CompensateYDPI (95), + SWP_NOMOVE | SWP_NOZORDER); + + InvalidateRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), NULL, TRUE); + } + else + { + ShowWindow (GetDlgItem(hwndDlg, IDC_FAV_VOL_OPTIONS_GLOBAL_SETTINGS_BOX), SW_HIDE); + } + + Favorites.clear(); + + LVCOLUMNW column; + SendMessageW (FavoriteListControl, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT); + + memset (&column, 0, sizeof (column)); + column.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; + column.pszText = GetString ("DRIVE"); + column.cx = CompensateXDPI (38); + column.fmt = LVCFMT_CENTER; + SendMessageW (FavoriteListControl, LVM_INSERTCOLUMNW, 1, (LPARAM) &column); + + ++column.iSubItem; + column.fmt = LVCFMT_LEFT; + column.pszText = GetString ("LABEL"); + column.cx = CompensateXDPI (160); + SendMessageW (FavoriteListControl, LVM_INSERTCOLUMNW, 2, (LPARAM) &column); + + ++column.iSubItem; + column.fmt = LVCFMT_LEFT; + column.pszText = GetString ("VOLUME"); + column.cx = CompensateXDPI (330); + SendMessageW (FavoriteListControl, LVM_INSERTCOLUMNW, 3, (LPARAM) &column); + + SetControls (hwndDlg, FavoriteVolume(), SystemFavoritesMode, false); + + if (SystemFavoritesMode) + LoadFavoriteVolumes (Favorites, true); + else + Favorites = FavoriteVolumes; + + if (args->AddFavoriteVolume) + Favorites.push_back (args->NewFavoriteVolume); + + FillListControl (FavoriteListControl, Favorites); + + SelectedItem = -1; + + if (args->AddFavoriteVolume) + { + ListView_SetItemState (FavoriteListControl, Favorites.size() - 1, LVIS_SELECTED, LVIS_SELECTED); + ListView_EnsureVisible (FavoriteListControl, Favorites.size() - 1, FALSE); + } + + if (SystemFavoritesMode) + SetDlgItemTextW (hwndDlg, IDC_FAVORITES_HELP_LINK, GetString ("SYS_FAVORITES_HELP_LINK")); + + ToHyperlink (hwndDlg, IDC_FAVORITES_HELP_LINK); + } + catch (Exception &e) + { + e.Show (hwndDlg); + EndDialog (hwndDlg, IDCLOSE); + } + } + return 1; + + case WM_COMMAND: + + switch (lw) + { + case IDOK: + + /* Global System Favorites settings */ + + if (SystemFavoritesMode) + { + BootEncryption BootEncObj (NULL); + + if (BootEncObj.GetStatus().DriveMounted) + { + try + { + uint32 reqConfig = IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT) ? TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES : 0; + if (reqConfig != (ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES)) + BootEncObj.RegisterSystemFavoritesService (reqConfig ? TRUE : FALSE); + + SetDriverConfigurationFlag (TC_DRIVER_CONFIG_DISABLE_NONADMIN_SYS_FAVORITES_ACCESS, IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY)); + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + } + } + + /* (System) Favorites list */ + + if (SelectedItem != -1 && !Favorites.empty()) + SetFavoriteVolume (hwndDlg, Favorites[SelectedItem], SystemFavoritesMode); + + if (SaveFavoriteVolumes (hwndDlg, Favorites, SystemFavoritesMode)) + { + if (!SystemFavoritesMode) + { + bMountFavoritesOnLogon = FALSE; + + foreach (const FavoriteVolume &favorite, Favorites) + { + if (favorite.MountOnLogOn) + { + bMountFavoritesOnLogon = TRUE; + break; + } + } + + if (!bEnableBkgTask || bCloseBkgTaskWhenNoVolumes || IsNonInstallMode()) + { + foreach (const FavoriteVolume favorite, Favorites) + { + if (favorite.MountOnArrival) + { + Warning ("FAVORITE_ARRIVAL_MOUNT_BACKGROUND_TASK_ERR", hwndDlg); + break; + } + } + } + + FavoriteVolumes = Favorites; + + ManageStartupSeq(); + SaveSettings (hwndDlg); + } + else + SystemFavoriteVolumes = Favorites; + + OnFavoriteVolumesUpdated(); + LoadDriveLetters (hwndDlg, GetDlgItem (MainDlg, IDC_DRIVELIST), 0); + + EndDialog (hwndDlg, IDOK); + } + + return 1; + + case IDCANCEL: + EndDialog (hwndDlg, IDCLOSE); + return 1; + + case IDC_FAVORITE_MOVE_DOWN: + if (SelectedItem != -1 && Favorites.size() > (size_t) SelectedItem + 1) + { + swap (Favorites[SelectedItem], Favorites[SelectedItem + 1]); + + FillListControl (FavoriteListControl, Favorites); + ++SelectedItem; + ListView_SetItemState (FavoriteListControl, SelectedItem, LVIS_SELECTED, LVIS_SELECTED); + ListView_EnsureVisible (FavoriteListControl, SelectedItem, FALSE); + } + return 1; + + case IDC_FAVORITE_MOVE_UP: + if (SelectedItem > 0) + { + swap (Favorites[SelectedItem], Favorites[SelectedItem - 1]); + + FillListControl (FavoriteListControl, Favorites); + --SelectedItem; + ListView_SetItemState (FavoriteListControl, SelectedItem, LVIS_SELECTED, LVIS_SELECTED); + ListView_EnsureVisible (FavoriteListControl, SelectedItem, FALSE); + } + return 1; + + case IDC_FAVORITE_REMOVE: + if (SelectedItem != -1) + { + Favorites.erase (Favorites.begin() + SelectedItem); + FillListControl (GetDlgItem (hwndDlg, IDC_FAVORITE_VOLUMES_LIST), Favorites); + SetControls (hwndDlg, FavoriteVolume(), SystemFavoritesMode, false); + SelectedItem = -1; + } + return 1; + + + case IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT: // Note that this option means "MOUNT_SYSTEM_FAVORITES_ON_BOOT" when SystemFavoritesMode is true + if (SystemFavoritesMode) + { + // MOUNT_SYSTEM_FAVORITES_ON_BOOT + + if (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT)) + { + WarningDirect ((wstring (GetString ("SYS_FAVORITES_KEYBOARD_WARNING")) + L"\n\n" + GetString ("BOOT_PASSWORD_CACHE_KEYBOARD_WARNING")).c_str(), hwndDlg); + + if (!IsServerOS() && !IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY)) + Info ("SYS_FAVORITES_ADMIN_ONLY_INFO", hwndDlg); + } + } + return 1; + + case IDC_FAVORITE_DISABLE_HOTKEY: // Note that this option means "DISABLE_NONADMIN_SYS_FAVORITES_ACCESS" when SystemFavoritesMode is true + if (SystemFavoritesMode) + { + // DISABLE_NONADMIN_SYS_FAVORITES_ACCESS + + if (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY)) + WarningDirect ((wstring (GetString ("SYS_FAVORITES_ADMIN_ONLY_WARNING")) + L"\n\n" + GetString ("SETTING_REQUIRES_REBOOT")).c_str(), hwndDlg); + else + Warning ("SETTING_REQUIRES_REBOOT", hwndDlg); + } + return 1; + + case IDC_FAVORITES_HELP_LINK: + Applink (SystemFavoritesMode ? "sysfavorites" : "favorites", TRUE, ""); + return 1; + case IDC_SHOW_PIM: + HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PIM, IDC_PIM, 0); + return 1; + + case IDC_PIM: + if (hw == EN_CHANGE) + { + int pim = GetPim (hwndDlg, IDC_PIM); + if (pim > (SystemFavoritesMode? MAX_BOOT_PIM_VALUE: MAX_PIM_VALUE)) + { + SetDlgItemText (hwndDlg, IDC_PIM, L""); + SetFocus (GetDlgItem(hwndDlg, IDC_PIM)); + Warning (SystemFavoritesMode? "PIM_SYSENC_TOO_BIG": "PIM_TOO_BIG", hwndDlg); + return 1; + } + } + break; + } + + return 0; + + case WM_NOTIFY: + if (((LPNMHDR) lParam)->code == LVN_ITEMCHANGED) + { + static bool reentry = false; + if (reentry) + break; + + reentry = true; + + if (SelectedItem != -1) + { + SetFavoriteVolume (hwndDlg, Favorites[SelectedItem], SystemFavoritesMode); + FillListControlSubItems (FavoriteListControl, SelectedItem, Favorites[SelectedItem]); + } + + SelectedItem = ListView_GetNextItem (GetDlgItem (hwndDlg, IDC_FAVORITE_VOLUMES_LIST), -1, LVIS_SELECTED); + + if (SelectedItem != -1) + SetControls (hwndDlg, Favorites[SelectedItem], SystemFavoritesMode); + else + SetControls (hwndDlg, FavoriteVolume(), SystemFavoritesMode, false); + + reentry = false; + return 1; + } + break; + + case WM_CLOSE: + EndDialog (hwndDlg, IDCLOSE); + return 1; + case WM_CTLCOLORSTATIC: + { + HDC hdc = (HDC) wParam; + HWND hw = (HWND) lParam; + if (hw == GetDlgItem(hwndDlg, IDC_FAVORITE_VOLUME_ID)) + { + // This the favorite ID field. Make its background like normal edit + HBRUSH hbr = GetSysColorBrush (COLOR_WINDOW); + ::SelectObject(hdc, hbr); + return (BOOL) hbr; + } + } + break; + } + + return 0; + } + + + static void FillFavoriteVolumesMenu () + { + while (DeleteMenu (FavoriteVolumesMenu, 7, MF_BYPOSITION)) { } + + if (FavoriteVolumes.empty()) + return; + + AppendMenu (FavoriteVolumesMenu, MF_SEPARATOR, 0, L""); + + int i = 0; + foreach (const FavoriteVolume &favorite, FavoriteVolumes) + { + UINT flags = MF_STRING; + + if (favorite.DisconnectedDevice) + flags |= MF_GRAYED; + + wstring menuText = favorite.Path; + if (favorite.DisconnectedDevice) + menuText = favorite.Label.empty() ? wstring (L"(") + GetString ("FAVORITE_DISCONNECTED_DEV") + L")" : L""; + + if (!favorite.Label.empty()) + { + if (favorite.DisconnectedDevice) + menuText = favorite.Label + L" " + menuText; + else + menuText = favorite.Label; + } + + AppendMenuW (FavoriteVolumesMenu, flags, TC_FAVORITE_MENU_CMD_ID_OFFSET + i++, + (menuText + L"\t" + favorite.MountPoint.substr (0, 2)).c_str()); + } + } + + + static void FillListControl (HWND favoriteListControl, vector &favorites) + { + SendMessage (favoriteListControl, LVM_DELETEALLITEMS, 0, 0); + + int line = 0; + foreach (const FavoriteVolume favorite, favorites) + { + ListItemAdd (favoriteListControl, line, (wchar_t *) favorite.MountPoint.substr (0, 2).c_str()); + FillListControlSubItems (favoriteListControl, line++, favorite); + } + } + + + static void FillListControlSubItems (HWND FavoriteListControl, int line, const FavoriteVolume &favorite) + { + ListSubItemSet (FavoriteListControl, line, 1, (wchar_t *) favorite.Label.c_str()); + + if (favorite.DisconnectedDevice) + ListSubItemSet (FavoriteListControl, line, 2, (wchar_t *) (wstring (L"(") + GetString ("FAVORITE_DISCONNECTED_DEV") + L")").c_str()); + else + ListSubItemSet (FavoriteListControl, line, 2, (wchar_t *) favorite.Path.c_str()); + } + + + wstring GetFavoriteVolumeLabel (const wstring &volumePath, bool& useInExplorer) + { + foreach (const FavoriteVolume &favorite, FavoriteVolumes) + { + if (favorite.Path == volumePath) + { + useInExplorer = favorite.UseLabelInExplorer; + return favorite.Label; + } + } + + foreach (const FavoriteVolume &favorite, SystemFavoriteVolumes) + { + if (favorite.Path == volumePath) + { + useInExplorer = favorite.UseLabelInExplorer; + return favorite.Label; + } + } + + useInExplorer = false; + return wstring(); + } + + + void LoadFavoriteVolumes () + { + LoadFavoriteVolumes (FavoriteVolumes, false); + + try + { + LoadFavoriteVolumes (SystemFavoriteVolumes, true, true); + } + catch (...) { } // Ignore errors as SystemFavoriteVolumes list is used only for resolving volume paths to labels + + OnFavoriteVolumesUpdated(); + } + + + void LoadFavoriteVolumes (vector &favorites, bool systemFavorites, bool noUacElevation) + { + favorites.clear(); + wstring favoritesFilePath = systemFavorites ? GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false) : GetConfigPath (TC_APPD_FILENAME_FAVORITE_VOLUMES); + + if (systemFavorites && !IsAdmin() && !noUacElevation) + { + favoritesFilePath = GetConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES); + + try + { + BootEncryption bootEnc (MainDlg); + bootEnc.CopyFileAdmin (GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false).c_str(), favoritesFilePath.c_str()); + } + catch (SystemException &e) + { + if (e.ErrorCode == ERROR_FILE_NOT_FOUND) + return; + + throw; + } + } + + DWORD size; + char *favoritesXml = LoadFile (favoritesFilePath.c_str(), &size); + + if (systemFavorites && !IsAdmin() && !noUacElevation) + DeleteFile (GetConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES)); + + char *xml = favoritesXml; + char mountPoint[MAX_PATH], volume[MAX_PATH]; + + if (xml == NULL) + return; + + while (xml = XmlFindElement (xml, "volume")) + { + FavoriteVolume favorite; + + XmlGetAttributeText (xml, "mountpoint", mountPoint, sizeof (mountPoint)); + favorite.MountPoint = Utf8StringToWide (mountPoint); + + XmlGetNodeText (xml, volume, sizeof (volume)); + favorite.Path = Utf8StringToWide (volume); + + char label[1024]; + + XmlGetAttributeText (xml, "ID", label, sizeof (label)); + if (strlen (label) == (2*VOLUME_ID_SIZE)) + { + std::vector arr; + if (HexWideStringToArray (Utf8StringToWide (label).c_str(), arr) && arr.size() == VOLUME_ID_SIZE) + { + memcpy (favorite.VolumeID, &arr[0], VOLUME_ID_SIZE); + } + } + + XmlGetAttributeText (xml, "label", label, sizeof (label)); + favorite.Label = Utf8StringToWide (label); + + XmlGetAttributeText (xml, "pim", label, sizeof (label)); + if (strlen(label) == 0) + { + /* support old attribute name before it was changed to PIM*/ + XmlGetAttributeText (xml, "pin", label, sizeof (label)); + } + favorite.Pim = strtol (label, NULL, 10); + if (favorite.Pim < 0 || favorite.Pim > (systemFavorites? MAX_BOOT_PIM_VALUE : MAX_PIM_VALUE)) + favorite.Pim = 0; + + char boolVal[2]; + XmlGetAttributeText (xml, "readonly", boolVal, sizeof (boolVal)); + if (boolVal[0]) + favorite.ReadOnly = (boolVal[0] == '1'); + + XmlGetAttributeText (xml, "removable", boolVal, sizeof (boolVal)); + if (boolVal[0]) + favorite.Removable = (boolVal[0] == '1'); + + XmlGetAttributeText (xml, "system", boolVal, sizeof (boolVal)); + if (boolVal[0]) + favorite.SystemEncryption = (boolVal[0] == '1'); + + XmlGetAttributeText (xml, "noHotKeyMount", boolVal, sizeof (boolVal)); + if (boolVal[0]) + favorite.DisableHotkeyMount = (boolVal[0] == '1'); + + XmlGetAttributeText (xml, "openExplorerWindow", boolVal, sizeof (boolVal)); + if (boolVal[0]) + favorite.OpenExplorerWindow = (boolVal[0] == '1'); + + XmlGetAttributeText (xml, "mountOnArrival", boolVal, sizeof (boolVal)); + if (boolVal[0]) + favorite.MountOnArrival = (boolVal[0] == '1'); + + XmlGetAttributeText (xml, "mountOnLogOn", boolVal, sizeof (boolVal)); + if (boolVal[0]) + favorite.MountOnLogOn = (boolVal[0] == '1'); + + XmlGetAttributeText (xml, "useLabelInExplorer", boolVal, sizeof (boolVal)); + if (boolVal[0]) + favorite.UseLabelInExplorer = (boolVal[0] == '1') && !favorite.ReadOnly; + + XmlGetAttributeText (xml, "useVolumeID", boolVal, sizeof (boolVal)); + if (boolVal[0]) + favorite.UseVolumeID = (boolVal[0] == '1') && !IsRepeatedByteArray (0, favorite.VolumeID, sizeof (favorite.VolumeID)); + + if (favorite.Path.find (L"\\\\?\\Volume{") == 0 && favorite.Path.rfind (L"}\\") == favorite.Path.size() - 2) + { + wstring resolvedPath = VolumeGuidPathToDevicePath (favorite.Path); + if (!resolvedPath.empty()) + { + favorite.DisconnectedDevice = false; + favorite.VolumePathId = favorite.Path; + favorite.Path = resolvedPath; + } + else + favorite.DisconnectedDevice = true; + } + + favorites.push_back (favorite); + xml++; + } + + free (favoritesXml); + } + + + static void OnFavoriteVolumesUpdated () + { + FillFavoriteVolumesMenu(); + + FavoritesOnArrivalMountRequired.clear(); + + foreach (const FavoriteVolume favorite, FavoriteVolumes) + { + if (favorite.MountOnArrival) + { + FavoritesOnArrivalMountRequired.push_back (favorite); + + if (IsMountedVolume (favorite.Path.c_str())) + { + bool present = false; + + foreach (const FavoriteVolume favoriteConnected, FavoritesMountedOnArrivalStillConnected) + { + if (favorite.Path == favoriteConnected.Path) + { + present = true; + break; + } + } + + if (!present) + FavoritesMountedOnArrivalStillConnected.push_back (favorite); + } + } + } + } + + + BOOL OrganizeFavoriteVolumes (HWND hwndDlg, bool systemFavorites, const FavoriteVolume &newFavorite) + { + FavoriteVolumesDlgProcArguments args; + args.SystemFavorites = systemFavorites; + + if (!newFavorite.Path.empty()) + { + args.AddFavoriteVolume = true; + args.NewFavoriteVolume = newFavorite; + } + else + args.AddFavoriteVolume = false; + + return DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_FAVORITE_VOLUMES), hwndDlg, (DLGPROC) FavoriteVolumesDlgProc, (LPARAM) &args) == IDOK; + } + + + bool SaveFavoriteVolumes (HWND hwndDlg, const vector &favorites, bool systemFavorites) + { + FILE *f; + int cnt = 0; + + f = _wfopen (GetConfigPath (systemFavorites ? TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES : TC_APPD_FILENAME_FAVORITE_VOLUMES), L"w,ccs=UTF-8"); + if (f == NULL) + { + handleWin32Error (MainDlg, SRC_POS); + return false; + } + + XmlWriteHeader (f); + fputws (L"\n\t", f); + + foreach (const FavoriteVolume &favorite, favorites) + { + wchar_t tq[2048]; + + if (systemFavorites && favorite.Path.find (L"\\\\") == 0 && favorite.Path.find (L"Volume{") == wstring::npos) + Warning ("SYSTEM_FAVORITE_NETWORK_PATH_ERR", hwndDlg); + + XmlQuoteTextW (!favorite.VolumePathId.empty() ? favorite.VolumePathId.c_str() : favorite.Path.c_str(), tq, ARRAYSIZE (tq)); + + wstring s = L"\n\t\t 0) + s += L" pim=\"" + IntToWideString(favorite.Pim) + L"\""; + + if (favorite.ReadOnly) + s += L" readonly=\"1\""; + + if (favorite.Removable) + s += L" removable=\"1\""; + + if (favorite.SystemEncryption) + s += L" system=\"1\""; + + if (favorite.MountOnArrival) + s += L" mountOnArrival=\"1\""; + + if (favorite.MountOnLogOn) + s += L" mountOnLogOn=\"1\""; + + if (favorite.DisableHotkeyMount) + s += L" noHotKeyMount=\"1\""; + + if (favorite.OpenExplorerWindow) + s += L" openExplorerWindow=\"1\""; + + if (favorite.UseLabelInExplorer && !favorite.ReadOnly) + s += L" useLabelInExplorer=\"1\""; + + if (favorite.UseVolumeID && !IsRepeatedByteArray (0, favorite.VolumeID, sizeof (favorite.VolumeID))) + s += L" useVolumeID=\"1\""; + + s += L">" + wstring (tq) + L""; + + fwprintf (f, L"%ws", s.c_str()); + cnt++; + } + + fputws (L"\n\t", f); + XmlWriteFooter (f); + + if (!CheckFileStreamWriteErrors (hwndDlg, f, systemFavorites ? TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES : TC_APPD_FILENAME_FAVORITE_VOLUMES)) + { + fclose (f); + return false; + } + + fclose (f); + + BootEncryption bootEnc (MainDlg); + + if (systemFavorites) + { + finally_do ({ _wremove (GetConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES)); }); + + try + { + bootEnc.DeleteFileAdmin (GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false).c_str()); + } + catch (UserAbort&) { return false; } + catch (...) { } + + try + { + if (cnt != 0) + { + bootEnc.CopyFileAdmin (GetConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES), GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false).c_str()); + + if (!(ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES)) + Info ("SYS_FAVORITE_VOLUMES_SAVED", hwndDlg); + } + } + catch (Exception &e) + { + e.Show (NULL); + } + } + + if (cnt == 0) + { + if (systemFavorites) + { + try + { + bootEnc.DeleteFileAdmin (GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false).c_str()); + } + catch (...) { } + } + else + _wremove (GetConfigPath (TC_APPD_FILENAME_FAVORITE_VOLUMES)); + } + + return true; + } + + + static void SetControls (HWND hwndDlg, const FavoriteVolume &favorite, bool systemFavoritesMode, bool enable) + { + BOOL bIsDevice = favorite.DisconnectedDevice || IsVolumeDeviceHosted (favorite.Path.c_str()) || !enable; + if (favorite.Pim > 0) + { + wchar_t szTmp[MAX_PIM + 1]; + StringCbPrintfW (szTmp, sizeof(szTmp), L"%d", favorite.Pim); + SetDlgItemText (hwndDlg, IDC_PIM, szTmp); + } + else + SetDlgItemText (hwndDlg, IDC_PIM, L""); + SetDlgItemTextW (hwndDlg, IDC_FAVORITE_LABEL, favorite.Label.c_str()); + SetCheckBox (hwndDlg, IDC_FAVORITE_USE_LABEL_IN_EXPLORER, favorite.UseLabelInExplorer); + SetCheckBox (hwndDlg, IDC_FAVORITE_MOUNT_ON_LOGON, favorite.MountOnLogOn); + SetCheckBox (hwndDlg, IDC_FAVORITE_MOUNT_ON_ARRIVAL, favorite.MountOnArrival); + SetCheckBox (hwndDlg, IDC_FAVORITE_MOUNT_READONLY, favorite.ReadOnly); + SetCheckBox (hwndDlg, IDC_FAVORITE_MOUNT_REMOVABLE, favorite.Removable); + SetCheckBox (hwndDlg, IDC_FAVORITE_USE_VOLUME_ID, favorite.UseVolumeID && bIsDevice); + + if (IsRepeatedByteArray (0, favorite.VolumeID, sizeof (favorite.VolumeID)) || !bIsDevice) + { + SetDlgItemText (hwndDlg, IDC_FAVORITE_VOLUME_ID, L""); + } + else + SetDlgItemText (hwndDlg, IDC_FAVORITE_VOLUME_ID, ArrayToHexWideString (favorite.VolumeID, sizeof (favorite.VolumeID)).c_str()); + + if (systemFavoritesMode) + { + uint32 driverConfig = ReadDriverConfigurationFlags(); + + // MOUNT_SYSTEM_FAVORITES_ON_BOOT + CheckDlgButton (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT, (driverConfig & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD_FOR_SYS_FAVORITES) ? BST_CHECKED : BST_UNCHECKED); + + // DISABLE_NONADMIN_SYS_FAVORITES_ACCESS + CheckDlgButton (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY, (driverConfig & TC_DRIVER_CONFIG_DISABLE_NONADMIN_SYS_FAVORITES_ACCESS) ? BST_CHECKED : BST_UNCHECKED); + } + else + { + SetCheckBox (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT, favorite.OpenExplorerWindow); + SetCheckBox (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY, favorite.DisableHotkeyMount); + } + + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_MOVE_UP), enable); + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_MOVE_DOWN), enable); + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_REMOVE), enable); + EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), enable); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), enable); + EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PIM), enable); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), enable); + EnableWindow (GetDlgItem (hwndDlg, IDT_FAVORITE_LABEL), enable); + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_LABEL), enable); + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_USE_LABEL_IN_EXPLORER), enable); + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_MOUNT_ON_LOGON), enable && !systemFavoritesMode); + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_MOUNT_ON_ARRIVAL), enable && !systemFavoritesMode); + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_MOUNT_READONLY), enable); + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_MOUNT_REMOVABLE), enable); + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT), enable || systemFavoritesMode); + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY), enable || systemFavoritesMode); + EnableWindow (GetDlgItem (hwndDlg, IDT_VOLUME_ID), enable && bIsDevice); + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_VOLUME_ID), enable && bIsDevice); + EnableWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_USE_VOLUME_ID), enable && bIsDevice && !IsRepeatedByteArray (0, favorite.VolumeID, sizeof (favorite.VolumeID))); + + ShowWindow (GetDlgItem (hwndDlg, IDT_VOLUME_ID), bIsDevice? SW_SHOW : SW_HIDE); + ShowWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_VOLUME_ID), bIsDevice? SW_SHOW : SW_HIDE); + ShowWindow (GetDlgItem (hwndDlg, IDC_FAVORITE_USE_VOLUME_ID), bIsDevice? SW_SHOW : SW_HIDE); + + // Group box + RECT boxRect, checkRect, labelRect; + + GetWindowRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), &boxRect); + GetWindowRect (GetDlgItem (hwndDlg, IDC_FAVORITE_USE_VOLUME_ID), &checkRect); + GetWindowRect (GetDlgItem (hwndDlg, IDT_VOLUME_ID), &labelRect); + + if (!bIsDevice && (boxRect.top < checkRect.top)) + { + POINT pt = {boxRect.left, checkRect.bottom}; + ScreenToClient (hwndDlg, &pt); + SetWindowPos (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), 0, pt.x, pt.y, + boxRect.right - boxRect.left, + boxRect.bottom - checkRect.bottom, + SWP_NOZORDER); + + InvalidateRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), NULL, TRUE); + } + + if (bIsDevice && (boxRect.top >= checkRect.top)) + { + POINT pt = {boxRect.left, labelRect.top - CompensateYDPI (10)}; + ScreenToClient (hwndDlg, &pt); + SetWindowPos (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), 0, pt.x, pt.y, + boxRect.right - boxRect.left, + boxRect.bottom - labelRect.top + CompensateYDPI (10), + SWP_NOZORDER); + + InvalidateRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), NULL, TRUE); + } + } + + + static void SetFavoriteVolume (HWND hwndDlg, FavoriteVolume &favorite, bool systemFavoritesMode) + { + wchar_t label[1024]; + if (GetDlgItemTextW (hwndDlg, IDC_FAVORITE_LABEL, label, ARRAYSIZE (label)) != 0) + { + favorite.Label = label; + + for (size_t i = 0; i < favorite.Label.size(); ++i) + { + if (favorite.Label[i] == L'"') + favorite.Label.at (i) = L'\''; + } + } + else + favorite.Label.clear(); + + favorite.Pim = GetPim (hwndDlg, IDC_PIM); + favorite.UseLabelInExplorer = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_USE_LABEL_IN_EXPLORER) != 0); + favorite.UseVolumeID = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_USE_VOLUME_ID) != 0); + + favorite.ReadOnly = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_MOUNT_READONLY) != 0); + favorite.Removable = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_MOUNT_REMOVABLE) != 0); + + if (!systemFavoritesMode) + { + favorite.MountOnLogOn = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_MOUNT_ON_LOGON) != 0); + favorite.MountOnArrival = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_MOUNT_ON_ARRIVAL) != 0); + favorite.DisableHotkeyMount = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY) != 0); + favorite.OpenExplorerWindow = (IsDlgButtonChecked (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT) != 0); + } + + if (favorite.VolumePathId.empty() + && IsVolumeDeviceHosted (favorite.Path.c_str()) + && favorite.Path.find (L"\\\\?\\Volume{") != 0) + { + bool partition = (favorite.Path.find (L"\\Partition0") == wstring::npos); + + if (!favorite.Label.empty()) + { + ErrorDirect ((GetString (partition ? "FAVORITE_LABEL_PARTITION_TYPE_ERR" : "FAVORITE_LABEL_DEVICE_PATH_ERR") + wstring (L"\n\n") + favorite.Path).c_str(), hwndDlg); + favorite.Label.clear(); + } + + if (favorite.MountOnArrival) + { + ErrorDirect ((GetString (partition ? "FAVORITE_ARRIVAL_MOUNT_PARTITION_TYPE_ERR" : "FAVORITE_ARRIVAL_MOUNT_DEVICE_PATH_ERR") + wstring (L"\n\n") + favorite.Path).c_str(), hwndDlg); + favorite.MountOnArrival = false; + } + } + + if (favorite.MountOnArrival && favorite.Path.find (L"\\\\") == 0 && favorite.Path.find (L"Volume{") == wstring::npos) + { + Error ("FAVORITE_ARRIVAL_MOUNT_NETWORK_PATH_ERR", hwndDlg); + favorite.MountOnArrival = false; + } + } + + + void UpdateDeviceHostedFavoriteVolumes () + { + try + { + LoadFavoriteVolumes(); + } + catch (Exception &e) + { + e.Show (MainDlg); + } + } +} diff --git a/src/Mount/Favorites.h b/src/Mount/Favorites.h index 84ab2a25..3c8b1c9b 100644 --- a/src/Mount/Favorites.h +++ b/src/Mount/Favorites.h @@ -1,87 +1,87 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_Mount_FavoriteVolumes -#define TC_HEADER_Mount_FavoriteVolumes - -#include - -namespace VeraCrypt -{ - struct FavoriteVolume - { - FavoriteVolume() - : - Pim (0), - DisableHotkeyMount (false), - DisconnectedDevice (false), - MountOnLogOn (false), - MountOnArrival (false), - OpenExplorerWindow (false), - ReadOnly (false), - Removable (false), - SystemEncryption (false), - UseLabelInExplorer (false), - UseVolumeID (false) - { - memset (VolumeID, 0, VOLUME_ID_SIZE); - } - - wstring Path; - wstring MountPoint; - wstring VolumePathId; - wstring Label; - int Pim; - BYTE VolumeID[VOLUME_ID_SIZE]; - - bool DisableHotkeyMount; - bool DisconnectedDevice; - bool MountOnLogOn; - bool MountOnArrival; - bool OpenExplorerWindow; - bool ReadOnly; - bool Removable; - bool SystemEncryption; - bool UseLabelInExplorer; - bool UseVolumeID; - }; - - struct FavoriteVolumesDlgProcArguments - { - bool SystemFavorites; - bool AddFavoriteVolume; - FavoriteVolume NewFavoriteVolume; - }; - - extern vector FavoriteVolumes; - extern vector SystemFavoriteVolumes; - extern list FavoritesOnArrivalMountRequired; - extern list FavoritesMountedOnArrivalStillConnected; - extern HMENU FavoriteVolumesMenu; - - BOOL AddMountedVolumeToFavorites (HWND hwndDlg, int driveNo, bool systemFavorites); - static BOOL CALLBACK FavoriteVolumesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); - static void FillFavoriteVolumesMenu (); - static void FillListControl (HWND favoriteListControl, vector &favorites); - static void FillListControlSubItems (HWND favoriteListControl, int line, const FavoriteVolume &favorite); - wstring GetFavoriteVolumeLabel (const wstring &volumePath, bool& useInExplorer); - void LoadFavoriteVolumes (); - void LoadFavoriteVolumes (vector &favorites, bool systemFavorites, bool noUacElevation = false); - static void OnFavoriteVolumesUpdated (); - BOOL OrganizeFavoriteVolumes (HWND hwndDlg, bool systemFavorites, const FavoriteVolume &newFavorite = FavoriteVolume()); - bool SaveFavoriteVolumes (HWND hwndDlg, const vector &favorites, bool systemFavorites); - static void SetControls (HWND hwndDlg, const FavoriteVolume &favorite, bool systemFavoritesMode, bool enable = true); - static void SetFavoriteVolume (HWND hwndDlg, FavoriteVolume &favorite, bool systemFavoritesMode); - void UpdateDeviceHostedFavoriteVolumes (); -} - -#endif // TC_HEADER_Mount_FavoriteVolumes +/* + 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. +*/ + +#ifndef TC_HEADER_Mount_FavoriteVolumes +#define TC_HEADER_Mount_FavoriteVolumes + +#include + +namespace VeraCrypt +{ + struct FavoriteVolume + { + FavoriteVolume() + : + Pim (0), + DisableHotkeyMount (false), + DisconnectedDevice (false), + MountOnLogOn (false), + MountOnArrival (false), + OpenExplorerWindow (false), + ReadOnly (false), + Removable (false), + SystemEncryption (false), + UseLabelInExplorer (false), + UseVolumeID (false) + { + memset (VolumeID, 0, VOLUME_ID_SIZE); + } + + wstring Path; + wstring MountPoint; + wstring VolumePathId; + wstring Label; + int Pim; + BYTE VolumeID[VOLUME_ID_SIZE]; + + bool DisableHotkeyMount; + bool DisconnectedDevice; + bool MountOnLogOn; + bool MountOnArrival; + bool OpenExplorerWindow; + bool ReadOnly; + bool Removable; + bool SystemEncryption; + bool UseLabelInExplorer; + bool UseVolumeID; + }; + + struct FavoriteVolumesDlgProcArguments + { + bool SystemFavorites; + bool AddFavoriteVolume; + FavoriteVolume NewFavoriteVolume; + }; + + extern vector FavoriteVolumes; + extern vector SystemFavoriteVolumes; + extern list FavoritesOnArrivalMountRequired; + extern list FavoritesMountedOnArrivalStillConnected; + extern HMENU FavoriteVolumesMenu; + + BOOL AddMountedVolumeToFavorites (HWND hwndDlg, int driveNo, bool systemFavorites); + static BOOL CALLBACK FavoriteVolumesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); + static void FillFavoriteVolumesMenu (); + static void FillListControl (HWND favoriteListControl, vector &favorites); + static void FillListControlSubItems (HWND favoriteListControl, int line, const FavoriteVolume &favorite); + wstring GetFavoriteVolumeLabel (const wstring &volumePath, bool& useInExplorer); + void LoadFavoriteVolumes (); + void LoadFavoriteVolumes (vector &favorites, bool systemFavorites, bool noUacElevation = false); + static void OnFavoriteVolumesUpdated (); + BOOL OrganizeFavoriteVolumes (HWND hwndDlg, bool systemFavorites, const FavoriteVolume &newFavorite = FavoriteVolume()); + bool SaveFavoriteVolumes (HWND hwndDlg, const vector &favorites, bool systemFavorites); + static void SetControls (HWND hwndDlg, const FavoriteVolume &favorite, bool systemFavoritesMode, bool enable = true); + static void SetFavoriteVolume (HWND hwndDlg, FavoriteVolume &favorite, bool systemFavoritesMode); + void UpdateDeviceHostedFavoriteVolumes (); +} + +#endif // TC_HEADER_Mount_FavoriteVolumes diff --git a/src/Mount/Hotkeys.c b/src/Mount/Hotkeys.c index 59fa1093..0403c634 100644 --- a/src/Mount/Hotkeys.c +++ b/src/Mount/Hotkeys.c @@ -1,611 +1,611 @@ -/* - 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 -#include "Dlgcode.h" -#include "Hotkeys.h" -#include "Language.h" -#include "Mount.h" -#include "Resource.h" - -#include - -#ifndef SRC_POS -#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) -#endif - -#define MAX_KEY_COMB_NAME_LEN 260 - -TCHOTKEY Hotkeys [NBR_HOTKEYS]; -static TCHOTKEY tmpHotkeys [NBR_HOTKEYS]; - -static int nSelectedHotkeyId; -static UINT currentVKeyCode; -static BYTE vkeysDown[256]; - - -static void ScanAndProcessKey (UINT *vKeyCode, wchar_t *keyName) -{ - UINT vKey; - *vKeyCode = 0; - - for (vKey = 0; vKey <= 0xFF; vKey++) - { - if (GetAsyncKeyState (vKey) < 0) - { - if (!vkeysDown [vKey]) - { - vkeysDown [vKey] = 1; - if (GetKeyName (vKey, keyName)) // If the key is allowed and its name has been resolved - *vKeyCode = vKey; - } - } - else - vkeysDown [vKey] = 0; - } -} - - -/* Returns TRUE if the key is allowed and its name is resolved. */ -BOOL GetKeyName (UINT vKey, wchar_t *keyName) -{ - BOOL result = TRUE; - - if (vKey >= 0x30 && vKey <= 0x5a) - { - // ASCII characters - StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%hc", (char) vKey); - } - else if (vKey >= 0xE9 && vKey <= 0xF5) - { - // OEM-specific - StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM-%d", vKey); - - // mapping taken from: - // http://www.hotkeynet.com/ref/keynames.html - // https://mojoware.googlecode.com/svn-history/r3/trunk/mojo_engine/cKeyboard.cpp - // http://www.screenio.com/gui_screenio/gs_htmlhelp_subweb/download/SIMKEYS.cob - // - // These values seem to come from Nokia/Ericsson mobile device keys - - switch (vKey) - { - case 0xE9: // OEMReset = 0xE9 - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMReset)"); - break; - case 0xEA: // OEMJump = 0xEA - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMJump)"); - break; - case 0xEB: // OEMPA1 = 0xEB - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMPA1)"); - break; - case 0xEC: // OEMPA2 = 0xEC - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMPA2)"); - break; - case 0xED: // OEMPA3 = 0xED - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMPA3)"); - break; - case 0xEE: // OEMWSCtrl = 0xEE - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMWSCtrl)"); - break; - case 0xEF: // OEMCUSel = 0xEF - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMCUSel)"); - break; - case 0xF0: // OEMATTN = 0xF0 - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMATTN)"); - break; - case 0xF1: // OEMFinish = 0xF1 - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMFinish)"); - break; - case 0xF2: // OEMCopy = 0xF2 - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMCopy)"); - break; - case 0xF3: // OEMAuto = 0xF3 - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMAuto)"); - break; - case 0xF4: // OEMENLW = 0xF4 - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMENLW)"); - break; - case 0xF5: // OEMBackTab = 0xF5 - StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMBackTab)"); - break; - } - } - else if (vKey >= VK_F1 && vKey <= VK_F24) - { - // F1-F24 - StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"F%d", vKey - VK_F1 + 1); - } - else if (vKey >= VK_NUMPAD0 && vKey <= VK_NUMPAD9) - { - // Numpad numbers - StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s %d", GetString ("VK_NUMPAD"), vKey - VK_NUMPAD0); - } - else - { - switch (vKey) - { - case VK_MULTIPLY: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s *", GetString ("VK_NUMPAD")); break; - case VK_ADD: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s +", GetString ("VK_NUMPAD")); break; - case VK_SEPARATOR: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s Separator", GetString ("VK_NUMPAD")); break; - case VK_SUBTRACT: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s -", GetString ("VK_NUMPAD")); break; - case VK_DECIMAL: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s .", GetString ("VK_NUMPAD")); break; - case VK_DIVIDE: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s /", GetString ("VK_NUMPAD")); break; - case VK_OEM_1: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 1 (';')"); break; - case VK_OEM_PLUS: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"+"); break; - case VK_OEM_COMMA: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L","); break; - case VK_OEM_MINUS: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"-"); break; - case VK_OEM_PERIOD: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"."); break; - case VK_OEM_2: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 2 ('/')"); break; - case VK_OEM_3: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 3 (`)"); break; - case VK_OEM_4: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 4 ('[')"); break; - case VK_OEM_5: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 5 ('\\')"); break; - case VK_OEM_6: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 6 (']')"); break; - case VK_OEM_7: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 7 (')"); break; - case VK_OEM_8: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 8"); break; - case VK_OEM_AX: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM AX"); break; - case VK_OEM_102: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 102"); break; - case VK_ICO_HELP: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ICO_HELP"); break; - case VK_ICO_00: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ICO_00"); break; - case VK_ICO_CLEAR: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ICO_CLEAR"); break; - case VK_ATTN: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"Attn"); break; - case VK_CRSEL: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"CrSel"); break; - case VK_EXSEL: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ExSel"); break; - case VK_EREOF: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"Erase EOF"); break; - case VK_PA1: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"PA1"); break; - case VK_OEM_CLEAR: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM Clear"); break; - - case 0: - case 1: - case 0xFF: - result = FALSE; - break; - - default: - { - char key[16]; - wchar_t *desc; - StringCbPrintfA (key, sizeof(key),"VKEY_%02X", vKey); - desc = GetString (key); - if (desc == UnknownString) - result = FALSE; - else - StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, desc); - } - } - } - return result; -} - - -static BOOL ShortcutInUse (UINT vKeyCode, UINT modifiers, TCHOTKEY hotkeys[]) -{ - int i; - - for (i = 0; i < NBR_HOTKEYS; i++) - { - if (hotkeys[i].vKeyCode == vKeyCode && hotkeys[i].vKeyModifiers == modifiers) - return TRUE; - } - return FALSE; -} - - -void UnregisterAllHotkeys (HWND hwndDlg, TCHOTKEY hotkeys[]) -{ - int i; - - for (i = 0; i < NBR_HOTKEYS; i++) - { - if (hotkeys[i].vKeyCode != 0) - UnregisterHotKey (hwndDlg, i); - - } -} - - -BOOL RegisterAllHotkeys (HWND hwndDlg, TCHOTKEY hotkeys[]) -{ - BOOL result = TRUE; - int i; - - for (i = 0; i < NBR_HOTKEYS; i++) - { - if (hotkeys[i].vKeyCode != 0 - && !RegisterHotKey (hwndDlg, i, hotkeys[i].vKeyModifiers, hotkeys[i].vKeyCode)) - result = FALSE; - } - - return result; -} - - -static void DisplayHotkeyList (HWND hwndDlg) -{ - LVITEMW item; - HWND hList = GetDlgItem (hwndDlg, IDC_HOTKEY_LIST); - int i; - wchar_t ShortcutMod [MAX_KEY_COMB_NAME_LEN]; - wchar_t ShortcutFinal [MAX_KEY_COMB_NAME_LEN*2]; - wchar_t Shortcut [MAX_KEY_COMB_NAME_LEN]; - - SendMessage (hList, LVM_DELETEALLITEMS,0, (LPARAM)&item); - - for (i = 0; i < NBR_HOTKEYS; i++) - { - memset (&item,0,sizeof(item)); - item.mask = LVIF_TEXT; - item.iItem = i; - item.iSubItem = 0; - - switch (i) - { - - case HK_AUTOMOUNT_DEVICES: - item.pszText = GetString ("HK_AUTOMOUNT_DEVICES"); - break; - - case HK_DISMOUNT_ALL: - item.pszText = GetString ("HK_DISMOUNT_ALL"); - break; - - case HK_WIPE_CACHE: - item.pszText = GetString ("HK_WIPE_CACHE"); - break; - - case HK_DISMOUNT_ALL_AND_WIPE: - item.pszText = GetString ("HK_DISMOUNT_ALL_AND_WIPE"); - break; - - case HK_FORCE_DISMOUNT_ALL_AND_WIPE: - item.pszText = GetString ("HK_FORCE_DISMOUNT_ALL_AND_WIPE"); - break; - - case HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT: - item.pszText = GetString ("HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT"); - break; - - case HK_MOUNT_FAVORITE_VOLUMES: - item.pszText = GetString ("HK_MOUNT_FAVORITE_VOLUMES"); - break; - - case HK_SHOW_HIDE_MAIN_WINDOW: - item.pszText = GetString ("HK_SHOW_HIDE_MAIN_WINDOW"); - break; - - case HK_CLOSE_SECURITY_TOKEN_SESSIONS: - item.pszText = GetString ("IDM_CLOSE_ALL_TOKEN_SESSIONS"); - break; - - default: - item.pszText = L"[?]"; - } - - SendMessageW (hList,LVM_INSERTITEMW,0,(LPARAM)&item); - - item.iSubItem = 1; - Shortcut[0] = 0; - ShortcutMod[0] = 0; - - if (GetKeyName (tmpHotkeys[i].vKeyCode, Shortcut)) - { - if (tmpHotkeys[i].vKeyModifiers & MOD_CONTROL) - { - StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_CONTROL")); - StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+"); - } - - if (tmpHotkeys[i].vKeyModifiers & MOD_SHIFT) - { - StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_SHIFT")); - StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+"); - } - - if (tmpHotkeys[i].vKeyModifiers & MOD_ALT) - { - StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_ALT")); - StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+"); - } - - if (tmpHotkeys[i].vKeyModifiers & MOD_WIN) - { - StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_WIN")); - StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+"); - } - - StringCbPrintfW (ShortcutFinal, sizeof(ShortcutFinal), L"%s%s", ShortcutMod, Shortcut); - item.pszText = ShortcutFinal; - } - else - item.pszText = L""; - - SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&item); - } -} - - - -BOOL CALLBACK HotkeysDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - WORD hw = HIWORD (wParam); - static BOOL bKeyScanOn; - static BOOL bTPlaySoundOnSuccessfulHkDismount; - static BOOL bTDisplayBalloonOnSuccessfulHkDismount; - - switch (msg) - { - case WM_INITDIALOG: - { - LVCOLUMNW col; - HWND hList = GetDlgItem (hwndDlg, IDC_HOTKEY_LIST); - - bKeyScanOn = FALSE; - nSelectedHotkeyId = -1; - currentVKeyCode = 0; - memcpy (tmpHotkeys, Hotkeys, sizeof(tmpHotkeys)); - memset (vkeysDown, 0, sizeof(vkeysDown)); - - SendMessageW (hList,LVM_SETEXTENDEDLISTVIEWSTYLE,0, - LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_LABELTIP - ); - - memset (&col,0,sizeof(col)); - col.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; - col.pszText = GetString ("ACTION"); - col.cx = CompensateXDPI (341); - col.fmt = LVCFMT_LEFT; - SendMessageW (hList,LVM_INSERTCOLUMNW,0,(LPARAM)&col); - - col.pszText = GetString ("SHORTCUT"); - col.cx = CompensateXDPI (190); - col.fmt = LVCFMT_LEFT; - SendMessageW (hList,LVM_INSERTCOLUMNW,1,(LPARAM)&col); - - LocalizeDialog (hwndDlg, "IDD_HOTKEYS_DLG"); - - SetCheckBox (hwndDlg, IDC_HK_MOD_CTRL, TRUE); - SetCheckBox (hwndDlg, IDC_HK_MOD_SHIFT, FALSE); - SetCheckBox (hwndDlg, IDC_HK_MOD_ALT, TRUE); - SetCheckBox (hwndDlg, IDC_HK_MOD_WIN, FALSE); - - SetCheckBox (hwndDlg, IDC_HK_DISMOUNT_PLAY_SOUND, bPlaySoundOnSuccessfulHkDismount); - SetCheckBox (hwndDlg, IDC_HK_DISMOUNT_BALLOON_TOOLTIP, bDisplayBalloonOnSuccessfulHkDismount); - - bTPlaySoundOnSuccessfulHkDismount = bPlaySoundOnSuccessfulHkDismount; - bTDisplayBalloonOnSuccessfulHkDismount = bDisplayBalloonOnSuccessfulHkDismount; - - EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_ASSIGN), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_REMOVE), FALSE); - - DisplayHotkeyList(hwndDlg); - - if (SetTimer (hwndDlg, 0xfe, 10, NULL) == 0) - { - Error ("CANNOT_SET_TIMER", MainDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - return 1; - } - - case WM_TIMER: - { - if ((nSelectedHotkeyId > -1) && (GetFocus () == GetDlgItem (hwndDlg, IDC_HOTKEY_KEY))) - { - wchar_t keyName [MAX_KEY_COMB_NAME_LEN]; - UINT tmpVKeyCode; - - keyName[0] = 0; - - ScanAndProcessKey (&tmpVKeyCode, &keyName[0]); - - if (keyName[0] != 0) - { - currentVKeyCode = tmpVKeyCode; - SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), keyName); - EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_ASSIGN), TRUE); - } - else if ((currentVKeyCode != 0) && GetKeyName (currentVKeyCode, keyName)) - { - SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), keyName); - } - } - return 1; - } - - case WM_NOTIFY: - if (wParam == IDC_HOTKEY_LIST) - { - if (((LPNMHDR) lParam)->code == LVN_ITEMACTIVATE - || ((LPNMHDR) lParam)->code == LVN_ITEMCHANGED && (((LPNMLISTVIEW) lParam)->uNewState & LVIS_FOCUSED)) - { - LVITEM item; - memset(&item,0,sizeof(item)); - nSelectedHotkeyId = ((LPNMLISTVIEW) lParam)->iItem; - currentVKeyCode = 0; - memset (vkeysDown, 0, sizeof(vkeysDown)); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), GetString ("PRESS_A_KEY_TO_ASSIGN")); - - EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_REMOVE), (tmpHotkeys[nSelectedHotkeyId].vKeyCode > 0)); - - EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_ASSIGN), FALSE); - bKeyScanOn = TRUE; - return 1; - } - } - - return 0; - - case WM_COMMAND: - if (lw == IDC_HOTKEY_KEY && hw == EN_CHANGE) - { - if (!bKeyScanOn && nSelectedHotkeyId < 0 && GetWindowTextLengthW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY))) - SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), L""); - } - - if (lw == IDC_HOTKEY_ASSIGN) - { - BOOL bOwnActiveShortcut = FALSE; - - if (nSelectedHotkeyId >= 0 && currentVKeyCode != 0) - { - UINT modifiers = 0; - if (GetCheckBox (hwndDlg, IDC_HK_MOD_CTRL)) - modifiers = MOD_CONTROL; - - if (GetCheckBox (hwndDlg, IDC_HK_MOD_ALT)) - modifiers |= MOD_ALT; - - if (GetCheckBox (hwndDlg, IDC_HK_MOD_SHIFT)) - modifiers |= MOD_SHIFT; - - if (GetCheckBox (hwndDlg, IDC_HK_MOD_WIN)) - modifiers |= MOD_WIN; - - // Check if it's not already assigned - if (ShortcutInUse (currentVKeyCode, modifiers, tmpHotkeys)) - { - Error ("SHORTCUT_ALREADY_IN_USE", hwndDlg); - return 1; - } - - // Check for reserved system keys - switch (currentVKeyCode) - { - case VK_F1: - case VK_F12: - /* F1 is help and F12 is reserved for use by the debugger at all times */ - if (modifiers == 0) - { - Error ("CANNOT_USE_RESERVED_KEY", hwndDlg); - return 1; - } - break; - } - - bOwnActiveShortcut = ShortcutInUse (currentVKeyCode, modifiers, Hotkeys); - - // Test if the shortcut can be assigned without errors - if (!bOwnActiveShortcut - && !RegisterHotKey (hwndDlg, nSelectedHotkeyId, modifiers, currentVKeyCode)) - { - handleWin32Error(hwndDlg, SRC_POS); - return 1; - } - else - { - if (!bOwnActiveShortcut && !UnregisterHotKey (hwndDlg, nSelectedHotkeyId)) - handleWin32Error(hwndDlg, SRC_POS); - - tmpHotkeys[nSelectedHotkeyId].vKeyCode = currentVKeyCode; - tmpHotkeys[nSelectedHotkeyId].vKeyModifiers = modifiers; - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), L""); - EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_ASSIGN), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_REMOVE), FALSE); - nSelectedHotkeyId = -1; - bKeyScanOn = FALSE; - currentVKeyCode = 0; - memset (vkeysDown, 0, sizeof(vkeysDown)); - } - } - DisplayHotkeyList(hwndDlg); - return 1; - } - - if (lw == IDC_HOTKEY_REMOVE) - { - if (nSelectedHotkeyId >= 0) - { - tmpHotkeys[nSelectedHotkeyId].vKeyCode = 0; - tmpHotkeys[nSelectedHotkeyId].vKeyModifiers = 0; - SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), L""); - EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_ASSIGN), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_REMOVE), FALSE); - nSelectedHotkeyId = -1; - bKeyScanOn = FALSE; - currentVKeyCode = 0; - memset (vkeysDown, 0, sizeof(vkeysDown)); - DisplayHotkeyList(hwndDlg); - } - return 1; - } - - if (lw == IDC_RESET_HOTKEYS) - { - int i; - - for (i = 0; i < NBR_HOTKEYS; i++) - { - tmpHotkeys[i].vKeyCode = 0; - tmpHotkeys[i].vKeyModifiers = 0; - } - SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), L""); - EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_ASSIGN), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_REMOVE), FALSE); - nSelectedHotkeyId = -1; - bKeyScanOn = FALSE; - currentVKeyCode = 0; - memset (vkeysDown, 0, sizeof(vkeysDown)); - DisplayHotkeyList(hwndDlg); - return 1; - } - - if (lw == IDC_HK_DISMOUNT_PLAY_SOUND) - { - bTPlaySoundOnSuccessfulHkDismount = GetCheckBox (hwndDlg, IDC_HK_DISMOUNT_PLAY_SOUND); - } - - if (lw == IDC_HK_DISMOUNT_BALLOON_TOOLTIP) - { - bTDisplayBalloonOnSuccessfulHkDismount = GetCheckBox (hwndDlg, IDC_HK_DISMOUNT_BALLOON_TOOLTIP); - } - - if (lw == IDCANCEL || lw == IDCLOSE) - { - KillTimer (hwndDlg, 0xfe); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - if (lw == IDOK) - { - HWND hwndMainDlg = hwndDlg; - - while (GetParent (hwndMainDlg) != NULL) - { - hwndMainDlg = GetParent (hwndMainDlg); - } - UnregisterAllHotkeys (hwndMainDlg, Hotkeys); - memcpy (Hotkeys, tmpHotkeys, sizeof(Hotkeys)); - RegisterAllHotkeys (hwndMainDlg, Hotkeys); - KillTimer (hwndDlg, 0xfe); - bPlaySoundOnSuccessfulHkDismount = bTPlaySoundOnSuccessfulHkDismount; - bDisplayBalloonOnSuccessfulHkDismount = bTDisplayBalloonOnSuccessfulHkDismount; - - SaveSettings (hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - return 0; - - case WM_CLOSE: - - KillTimer (hwndDlg, 0xfe); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - return 0; -} - - +/* + 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 +#include "Dlgcode.h" +#include "Hotkeys.h" +#include "Language.h" +#include "Mount.h" +#include "Resource.h" + +#include + +#ifndef SRC_POS +#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) +#endif + +#define MAX_KEY_COMB_NAME_LEN 260 + +TCHOTKEY Hotkeys [NBR_HOTKEYS]; +static TCHOTKEY tmpHotkeys [NBR_HOTKEYS]; + +static int nSelectedHotkeyId; +static UINT currentVKeyCode; +static BYTE vkeysDown[256]; + + +static void ScanAndProcessKey (UINT *vKeyCode, wchar_t *keyName) +{ + UINT vKey; + *vKeyCode = 0; + + for (vKey = 0; vKey <= 0xFF; vKey++) + { + if (GetAsyncKeyState (vKey) < 0) + { + if (!vkeysDown [vKey]) + { + vkeysDown [vKey] = 1; + if (GetKeyName (vKey, keyName)) // If the key is allowed and its name has been resolved + *vKeyCode = vKey; + } + } + else + vkeysDown [vKey] = 0; + } +} + + +/* Returns TRUE if the key is allowed and its name is resolved. */ +BOOL GetKeyName (UINT vKey, wchar_t *keyName) +{ + BOOL result = TRUE; + + if (vKey >= 0x30 && vKey <= 0x5a) + { + // ASCII characters + StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%hc", (char) vKey); + } + else if (vKey >= 0xE9 && vKey <= 0xF5) + { + // OEM-specific + StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM-%d", vKey); + + // mapping taken from: + // http://www.hotkeynet.com/ref/keynames.html + // https://mojoware.googlecode.com/svn-history/r3/trunk/mojo_engine/cKeyboard.cpp + // http://www.screenio.com/gui_screenio/gs_htmlhelp_subweb/download/SIMKEYS.cob + // + // These values seem to come from Nokia/Ericsson mobile device keys + + switch (vKey) + { + case 0xE9: // OEMReset = 0xE9 + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMReset)"); + break; + case 0xEA: // OEMJump = 0xEA + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMJump)"); + break; + case 0xEB: // OEMPA1 = 0xEB + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMPA1)"); + break; + case 0xEC: // OEMPA2 = 0xEC + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMPA2)"); + break; + case 0xED: // OEMPA3 = 0xED + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMPA3)"); + break; + case 0xEE: // OEMWSCtrl = 0xEE + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMWSCtrl)"); + break; + case 0xEF: // OEMCUSel = 0xEF + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMCUSel)"); + break; + case 0xF0: // OEMATTN = 0xF0 + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMATTN)"); + break; + case 0xF1: // OEMFinish = 0xF1 + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMFinish)"); + break; + case 0xF2: // OEMCopy = 0xF2 + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMCopy)"); + break; + case 0xF3: // OEMAuto = 0xF3 + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMAuto)"); + break; + case 0xF4: // OEMENLW = 0xF4 + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMENLW)"); + break; + case 0xF5: // OEMBackTab = 0xF5 + StringCbCatW (keyName, MAX_KEY_COMB_NAME_LEN, L" (OEMBackTab)"); + break; + } + } + else if (vKey >= VK_F1 && vKey <= VK_F24) + { + // F1-F24 + StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"F%d", vKey - VK_F1 + 1); + } + else if (vKey >= VK_NUMPAD0 && vKey <= VK_NUMPAD9) + { + // Numpad numbers + StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s %d", GetString ("VK_NUMPAD"), vKey - VK_NUMPAD0); + } + else + { + switch (vKey) + { + case VK_MULTIPLY: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s *", GetString ("VK_NUMPAD")); break; + case VK_ADD: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s +", GetString ("VK_NUMPAD")); break; + case VK_SEPARATOR: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s Separator", GetString ("VK_NUMPAD")); break; + case VK_SUBTRACT: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s -", GetString ("VK_NUMPAD")); break; + case VK_DECIMAL: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s .", GetString ("VK_NUMPAD")); break; + case VK_DIVIDE: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s /", GetString ("VK_NUMPAD")); break; + case VK_OEM_1: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 1 (';')"); break; + case VK_OEM_PLUS: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"+"); break; + case VK_OEM_COMMA: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L","); break; + case VK_OEM_MINUS: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"-"); break; + case VK_OEM_PERIOD: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"."); break; + case VK_OEM_2: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 2 ('/')"); break; + case VK_OEM_3: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 3 (`)"); break; + case VK_OEM_4: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 4 ('[')"); break; + case VK_OEM_5: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 5 ('\\')"); break; + case VK_OEM_6: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 6 (']')"); break; + case VK_OEM_7: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 7 (')"); break; + case VK_OEM_8: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 8"); break; + case VK_OEM_AX: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM AX"); break; + case VK_OEM_102: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 102"); break; + case VK_ICO_HELP: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ICO_HELP"); break; + case VK_ICO_00: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ICO_00"); break; + case VK_ICO_CLEAR: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ICO_CLEAR"); break; + case VK_ATTN: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"Attn"); break; + case VK_CRSEL: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"CrSel"); break; + case VK_EXSEL: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ExSel"); break; + case VK_EREOF: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"Erase EOF"); break; + case VK_PA1: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"PA1"); break; + case VK_OEM_CLEAR: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM Clear"); break; + + case 0: + case 1: + case 0xFF: + result = FALSE; + break; + + default: + { + char key[16]; + wchar_t *desc; + StringCbPrintfA (key, sizeof(key),"VKEY_%02X", vKey); + desc = GetString (key); + if (desc == UnknownString) + result = FALSE; + else + StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, desc); + } + } + } + return result; +} + + +static BOOL ShortcutInUse (UINT vKeyCode, UINT modifiers, TCHOTKEY hotkeys[]) +{ + int i; + + for (i = 0; i < NBR_HOTKEYS; i++) + { + if (hotkeys[i].vKeyCode == vKeyCode && hotkeys[i].vKeyModifiers == modifiers) + return TRUE; + } + return FALSE; +} + + +void UnregisterAllHotkeys (HWND hwndDlg, TCHOTKEY hotkeys[]) +{ + int i; + + for (i = 0; i < NBR_HOTKEYS; i++) + { + if (hotkeys[i].vKeyCode != 0) + UnregisterHotKey (hwndDlg, i); + + } +} + + +BOOL RegisterAllHotkeys (HWND hwndDlg, TCHOTKEY hotkeys[]) +{ + BOOL result = TRUE; + int i; + + for (i = 0; i < NBR_HOTKEYS; i++) + { + if (hotkeys[i].vKeyCode != 0 + && !RegisterHotKey (hwndDlg, i, hotkeys[i].vKeyModifiers, hotkeys[i].vKeyCode)) + result = FALSE; + } + + return result; +} + + +static void DisplayHotkeyList (HWND hwndDlg) +{ + LVITEMW item; + HWND hList = GetDlgItem (hwndDlg, IDC_HOTKEY_LIST); + int i; + wchar_t ShortcutMod [MAX_KEY_COMB_NAME_LEN]; + wchar_t ShortcutFinal [MAX_KEY_COMB_NAME_LEN*2]; + wchar_t Shortcut [MAX_KEY_COMB_NAME_LEN]; + + SendMessage (hList, LVM_DELETEALLITEMS,0, (LPARAM)&item); + + for (i = 0; i < NBR_HOTKEYS; i++) + { + memset (&item,0,sizeof(item)); + item.mask = LVIF_TEXT; + item.iItem = i; + item.iSubItem = 0; + + switch (i) + { + + case HK_AUTOMOUNT_DEVICES: + item.pszText = GetString ("HK_AUTOMOUNT_DEVICES"); + break; + + case HK_DISMOUNT_ALL: + item.pszText = GetString ("HK_DISMOUNT_ALL"); + break; + + case HK_WIPE_CACHE: + item.pszText = GetString ("HK_WIPE_CACHE"); + break; + + case HK_DISMOUNT_ALL_AND_WIPE: + item.pszText = GetString ("HK_DISMOUNT_ALL_AND_WIPE"); + break; + + case HK_FORCE_DISMOUNT_ALL_AND_WIPE: + item.pszText = GetString ("HK_FORCE_DISMOUNT_ALL_AND_WIPE"); + break; + + case HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT: + item.pszText = GetString ("HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT"); + break; + + case HK_MOUNT_FAVORITE_VOLUMES: + item.pszText = GetString ("HK_MOUNT_FAVORITE_VOLUMES"); + break; + + case HK_SHOW_HIDE_MAIN_WINDOW: + item.pszText = GetString ("HK_SHOW_HIDE_MAIN_WINDOW"); + break; + + case HK_CLOSE_SECURITY_TOKEN_SESSIONS: + item.pszText = GetString ("IDM_CLOSE_ALL_TOKEN_SESSIONS"); + break; + + default: + item.pszText = L"[?]"; + } + + SendMessageW (hList,LVM_INSERTITEMW,0,(LPARAM)&item); + + item.iSubItem = 1; + Shortcut[0] = 0; + ShortcutMod[0] = 0; + + if (GetKeyName (tmpHotkeys[i].vKeyCode, Shortcut)) + { + if (tmpHotkeys[i].vKeyModifiers & MOD_CONTROL) + { + StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_CONTROL")); + StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+"); + } + + if (tmpHotkeys[i].vKeyModifiers & MOD_SHIFT) + { + StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_SHIFT")); + StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+"); + } + + if (tmpHotkeys[i].vKeyModifiers & MOD_ALT) + { + StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_ALT")); + StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+"); + } + + if (tmpHotkeys[i].vKeyModifiers & MOD_WIN) + { + StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_WIN")); + StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+"); + } + + StringCbPrintfW (ShortcutFinal, sizeof(ShortcutFinal), L"%s%s", ShortcutMod, Shortcut); + item.pszText = ShortcutFinal; + } + else + item.pszText = L""; + + SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&item); + } +} + + + +BOOL CALLBACK HotkeysDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + WORD hw = HIWORD (wParam); + static BOOL bKeyScanOn; + static BOOL bTPlaySoundOnSuccessfulHkDismount; + static BOOL bTDisplayBalloonOnSuccessfulHkDismount; + + switch (msg) + { + case WM_INITDIALOG: + { + LVCOLUMNW col; + HWND hList = GetDlgItem (hwndDlg, IDC_HOTKEY_LIST); + + bKeyScanOn = FALSE; + nSelectedHotkeyId = -1; + currentVKeyCode = 0; + memcpy (tmpHotkeys, Hotkeys, sizeof(tmpHotkeys)); + memset (vkeysDown, 0, sizeof(vkeysDown)); + + SendMessageW (hList,LVM_SETEXTENDEDLISTVIEWSTYLE,0, + LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_LABELTIP + ); + + memset (&col,0,sizeof(col)); + col.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; + col.pszText = GetString ("ACTION"); + col.cx = CompensateXDPI (341); + col.fmt = LVCFMT_LEFT; + SendMessageW (hList,LVM_INSERTCOLUMNW,0,(LPARAM)&col); + + col.pszText = GetString ("SHORTCUT"); + col.cx = CompensateXDPI (190); + col.fmt = LVCFMT_LEFT; + SendMessageW (hList,LVM_INSERTCOLUMNW,1,(LPARAM)&col); + + LocalizeDialog (hwndDlg, "IDD_HOTKEYS_DLG"); + + SetCheckBox (hwndDlg, IDC_HK_MOD_CTRL, TRUE); + SetCheckBox (hwndDlg, IDC_HK_MOD_SHIFT, FALSE); + SetCheckBox (hwndDlg, IDC_HK_MOD_ALT, TRUE); + SetCheckBox (hwndDlg, IDC_HK_MOD_WIN, FALSE); + + SetCheckBox (hwndDlg, IDC_HK_DISMOUNT_PLAY_SOUND, bPlaySoundOnSuccessfulHkDismount); + SetCheckBox (hwndDlg, IDC_HK_DISMOUNT_BALLOON_TOOLTIP, bDisplayBalloonOnSuccessfulHkDismount); + + bTPlaySoundOnSuccessfulHkDismount = bPlaySoundOnSuccessfulHkDismount; + bTDisplayBalloonOnSuccessfulHkDismount = bDisplayBalloonOnSuccessfulHkDismount; + + EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_ASSIGN), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_REMOVE), FALSE); + + DisplayHotkeyList(hwndDlg); + + if (SetTimer (hwndDlg, 0xfe, 10, NULL) == 0) + { + Error ("CANNOT_SET_TIMER", MainDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + return 1; + } + + case WM_TIMER: + { + if ((nSelectedHotkeyId > -1) && (GetFocus () == GetDlgItem (hwndDlg, IDC_HOTKEY_KEY))) + { + wchar_t keyName [MAX_KEY_COMB_NAME_LEN]; + UINT tmpVKeyCode; + + keyName[0] = 0; + + ScanAndProcessKey (&tmpVKeyCode, &keyName[0]); + + if (keyName[0] != 0) + { + currentVKeyCode = tmpVKeyCode; + SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), keyName); + EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_ASSIGN), TRUE); + } + else if ((currentVKeyCode != 0) && GetKeyName (currentVKeyCode, keyName)) + { + SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), keyName); + } + } + return 1; + } + + case WM_NOTIFY: + if (wParam == IDC_HOTKEY_LIST) + { + if (((LPNMHDR) lParam)->code == LVN_ITEMACTIVATE + || ((LPNMHDR) lParam)->code == LVN_ITEMCHANGED && (((LPNMLISTVIEW) lParam)->uNewState & LVIS_FOCUSED)) + { + LVITEM item; + memset(&item,0,sizeof(item)); + nSelectedHotkeyId = ((LPNMLISTVIEW) lParam)->iItem; + currentVKeyCode = 0; + memset (vkeysDown, 0, sizeof(vkeysDown)); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), GetString ("PRESS_A_KEY_TO_ASSIGN")); + + EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_REMOVE), (tmpHotkeys[nSelectedHotkeyId].vKeyCode > 0)); + + EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_ASSIGN), FALSE); + bKeyScanOn = TRUE; + return 1; + } + } + + return 0; + + case WM_COMMAND: + if (lw == IDC_HOTKEY_KEY && hw == EN_CHANGE) + { + if (!bKeyScanOn && nSelectedHotkeyId < 0 && GetWindowTextLengthW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY))) + SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), L""); + } + + if (lw == IDC_HOTKEY_ASSIGN) + { + BOOL bOwnActiveShortcut = FALSE; + + if (nSelectedHotkeyId >= 0 && currentVKeyCode != 0) + { + UINT modifiers = 0; + if (GetCheckBox (hwndDlg, IDC_HK_MOD_CTRL)) + modifiers = MOD_CONTROL; + + if (GetCheckBox (hwndDlg, IDC_HK_MOD_ALT)) + modifiers |= MOD_ALT; + + if (GetCheckBox (hwndDlg, IDC_HK_MOD_SHIFT)) + modifiers |= MOD_SHIFT; + + if (GetCheckBox (hwndDlg, IDC_HK_MOD_WIN)) + modifiers |= MOD_WIN; + + // Check if it's not already assigned + if (ShortcutInUse (currentVKeyCode, modifiers, tmpHotkeys)) + { + Error ("SHORTCUT_ALREADY_IN_USE", hwndDlg); + return 1; + } + + // Check for reserved system keys + switch (currentVKeyCode) + { + case VK_F1: + case VK_F12: + /* F1 is help and F12 is reserved for use by the debugger at all times */ + if (modifiers == 0) + { + Error ("CANNOT_USE_RESERVED_KEY", hwndDlg); + return 1; + } + break; + } + + bOwnActiveShortcut = ShortcutInUse (currentVKeyCode, modifiers, Hotkeys); + + // Test if the shortcut can be assigned without errors + if (!bOwnActiveShortcut + && !RegisterHotKey (hwndDlg, nSelectedHotkeyId, modifiers, currentVKeyCode)) + { + handleWin32Error(hwndDlg, SRC_POS); + return 1; + } + else + { + if (!bOwnActiveShortcut && !UnregisterHotKey (hwndDlg, nSelectedHotkeyId)) + handleWin32Error(hwndDlg, SRC_POS); + + tmpHotkeys[nSelectedHotkeyId].vKeyCode = currentVKeyCode; + tmpHotkeys[nSelectedHotkeyId].vKeyModifiers = modifiers; + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), L""); + EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_ASSIGN), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_REMOVE), FALSE); + nSelectedHotkeyId = -1; + bKeyScanOn = FALSE; + currentVKeyCode = 0; + memset (vkeysDown, 0, sizeof(vkeysDown)); + } + } + DisplayHotkeyList(hwndDlg); + return 1; + } + + if (lw == IDC_HOTKEY_REMOVE) + { + if (nSelectedHotkeyId >= 0) + { + tmpHotkeys[nSelectedHotkeyId].vKeyCode = 0; + tmpHotkeys[nSelectedHotkeyId].vKeyModifiers = 0; + SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), L""); + EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_ASSIGN), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_REMOVE), FALSE); + nSelectedHotkeyId = -1; + bKeyScanOn = FALSE; + currentVKeyCode = 0; + memset (vkeysDown, 0, sizeof(vkeysDown)); + DisplayHotkeyList(hwndDlg); + } + return 1; + } + + if (lw == IDC_RESET_HOTKEYS) + { + int i; + + for (i = 0; i < NBR_HOTKEYS; i++) + { + tmpHotkeys[i].vKeyCode = 0; + tmpHotkeys[i].vKeyModifiers = 0; + } + SetWindowTextW (GetDlgItem (hwndDlg, IDC_HOTKEY_KEY), L""); + EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_ASSIGN), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_REMOVE), FALSE); + nSelectedHotkeyId = -1; + bKeyScanOn = FALSE; + currentVKeyCode = 0; + memset (vkeysDown, 0, sizeof(vkeysDown)); + DisplayHotkeyList(hwndDlg); + return 1; + } + + if (lw == IDC_HK_DISMOUNT_PLAY_SOUND) + { + bTPlaySoundOnSuccessfulHkDismount = GetCheckBox (hwndDlg, IDC_HK_DISMOUNT_PLAY_SOUND); + } + + if (lw == IDC_HK_DISMOUNT_BALLOON_TOOLTIP) + { + bTDisplayBalloonOnSuccessfulHkDismount = GetCheckBox (hwndDlg, IDC_HK_DISMOUNT_BALLOON_TOOLTIP); + } + + if (lw == IDCANCEL || lw == IDCLOSE) + { + KillTimer (hwndDlg, 0xfe); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + if (lw == IDOK) + { + HWND hwndMainDlg = hwndDlg; + + while (GetParent (hwndMainDlg) != NULL) + { + hwndMainDlg = GetParent (hwndMainDlg); + } + UnregisterAllHotkeys (hwndMainDlg, Hotkeys); + memcpy (Hotkeys, tmpHotkeys, sizeof(Hotkeys)); + RegisterAllHotkeys (hwndMainDlg, Hotkeys); + KillTimer (hwndDlg, 0xfe); + bPlaySoundOnSuccessfulHkDismount = bTPlaySoundOnSuccessfulHkDismount; + bDisplayBalloonOnSuccessfulHkDismount = bTDisplayBalloonOnSuccessfulHkDismount; + + SaveSettings (hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + return 0; + + case WM_CLOSE: + + KillTimer (hwndDlg, 0xfe); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + return 0; +} + + diff --git a/src/Mount/Hotkeys.h b/src/Mount/Hotkeys.h index 8a6d44b6..167ddc54 100644 --- a/src/Mount/Hotkeys.h +++ b/src/Mount/Hotkeys.h @@ -1,52 +1,52 @@ -/* - 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. -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -enum -{ - /* When adding/removing hot keys, update the following functions in Mount.c: - DisplayHotkeyList() - SaveSettings() - LoadSettings() - HandleHotKey() */ - - HK_AUTOMOUNT_DEVICES = 0, - HK_CLOSE_SECURITY_TOKEN_SESSIONS, - HK_DISMOUNT_ALL, - HK_DISMOUNT_ALL_AND_WIPE, - HK_FORCE_DISMOUNT_ALL_AND_WIPE, - HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT, - HK_MOUNT_FAVORITE_VOLUMES, - HK_SHOW_HIDE_MAIN_WINDOW, - HK_WIPE_CACHE, - NBR_HOTKEYS -}; - -typedef struct -{ - UINT vKeyCode; - UINT vKeyModifiers; -} TCHOTKEY; - -extern TCHOTKEY Hotkeys [NBR_HOTKEYS]; - -BOOL CALLBACK HotkeysDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -BOOL GetKeyName (UINT vKey, wchar_t *keyName); -void UnregisterAllHotkeys (HWND hwndDlg, TCHOTKEY hotkeys[]); -BOOL RegisterAllHotkeys (HWND hwndDlg, TCHOTKEY hotkeys[]); - -#ifdef __cplusplus -} -#endif +/* + 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. +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +enum +{ + /* When adding/removing hot keys, update the following functions in Mount.c: + DisplayHotkeyList() + SaveSettings() + LoadSettings() + HandleHotKey() */ + + HK_AUTOMOUNT_DEVICES = 0, + HK_CLOSE_SECURITY_TOKEN_SESSIONS, + HK_DISMOUNT_ALL, + HK_DISMOUNT_ALL_AND_WIPE, + HK_FORCE_DISMOUNT_ALL_AND_WIPE, + HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT, + HK_MOUNT_FAVORITE_VOLUMES, + HK_SHOW_HIDE_MAIN_WINDOW, + HK_WIPE_CACHE, + NBR_HOTKEYS +}; + +typedef struct +{ + UINT vKeyCode; + UINT vKeyModifiers; +} TCHOTKEY; + +extern TCHOTKEY Hotkeys [NBR_HOTKEYS]; + +BOOL CALLBACK HotkeysDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +BOOL GetKeyName (UINT vKey, wchar_t *keyName); +void UnregisterAllHotkeys (HWND hwndDlg, TCHOTKEY hotkeys[]); +BOOL RegisterAllHotkeys (HWND hwndDlg, TCHOTKEY hotkeys[]); + +#ifdef __cplusplus +} +#endif diff --git a/src/Mount/MainCom.cpp b/src/Mount/MainCom.cpp index 738b243d..6955897d 100644 --- a/src/Mount/MainCom.cpp +++ b/src/Mount/MainCom.cpp @@ -1,294 +1,294 @@ -/* - 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 -#include -#include -#include "BaseCom.h" -#include "BootEncryption.h" -#include "Dlgcode.h" -#include "MainCom.h" -#include "MainCom_h.h" -#include "MainCom_i.c" -#include "Mount.h" -#include "Password.h" - -using namespace VeraCrypt; - -static volatile LONG ObjectCount = 0; - -class TrueCryptMainCom : public ITrueCryptMainCom -{ - -public: - TrueCryptMainCom (DWORD messageThreadId) : RefCount (0), MessageThreadId (messageThreadId) - { - InterlockedIncrement (&ObjectCount); - } - - virtual ~TrueCryptMainCom () - { - if (InterlockedDecrement (&ObjectCount) == 0) - PostThreadMessage (MessageThreadId, WM_APP, 0, 0); - } - - virtual ULONG STDMETHODCALLTYPE AddRef () - { - return InterlockedIncrement (&RefCount); - } - - virtual ULONG STDMETHODCALLTYPE Release () - { - if (!InterlockedDecrement (&RefCount)) - { - delete this; - return 0; - } - - return RefCount; - } - - virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID riid, void **ppvObject) - { - if (riid == IID_IUnknown || riid == IID_ITrueCryptMainCom) - *ppvObject = this; - else - { - *ppvObject = NULL; - return E_NOINTERFACE; - } - - AddRef (); - return S_OK; - } - - virtual void STDMETHODCALLTYPE AnalyzeKernelMiniDump (LONG_PTR hwndDlg) - { - // Do nothing - MainDlg = (HWND) hwndDlg; - } - - virtual int STDMETHODCALLTYPE BackupVolumeHeader (LONG_PTR hwndDlg, BOOL bRequireConfirmation, BSTR lpszVolume) - { - MainDlg = (HWND) hwndDlg; - return ::BackupVolumeHeader ((HWND) hwndDlg, bRequireConfirmation, lpszVolume); - } - - virtual int STDMETHODCALLTYPE RestoreVolumeHeader (LONG_PTR hwndDlg, BSTR lpszVolume) - { - MainDlg = (HWND) hwndDlg; - return ::RestoreVolumeHeader ((HWND) hwndDlg, lpszVolume); - } - - virtual DWORD STDMETHODCALLTYPE CallDriver (DWORD ioctl, BSTR input, BSTR *output) - { - return BaseCom::CallDriver (ioctl, input, output); - } - - virtual int STDMETHODCALLTYPE ChangePassword (BSTR volumePath, Password *oldPassword, Password *newPassword, int pkcs5, int wipePassCount, LONG_PTR hWnd) - { - MainDlg = (HWND) hWnd; - return ::ChangePwd (volumePath, oldPassword, 0, 0, FALSE, newPassword, pkcs5, 0, wipePassCount, (HWND) hWnd); - } - - virtual DWORD STDMETHODCALLTYPE CopyFile (BSTR sourceFile, BSTR destinationFile) - { - return BaseCom::CopyFile (sourceFile, destinationFile); - } - - virtual DWORD STDMETHODCALLTYPE DeleteFile (BSTR file) - { - return BaseCom::DeleteFile (file); - } - - virtual BOOL STDMETHODCALLTYPE IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) - { - return BaseCom::IsPagingFileActive (checkNonWindowsPartitionsOnly); - } - - virtual DWORD STDMETHODCALLTYPE ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone) - { - return BaseCom::ReadWriteFile (write, device, filePath, bufferBstr, offset, size, sizeDone); - } - - virtual DWORD STDMETHODCALLTYPE RegisterFilterDriver (BOOL registerDriver, int filterType) - { - return BaseCom::RegisterFilterDriver (registerDriver, filterType); - } - - virtual DWORD STDMETHODCALLTYPE RegisterSystemFavoritesService (BOOL registerService) - { - return BaseCom::RegisterSystemFavoritesService (registerService); - } - - virtual DWORD STDMETHODCALLTYPE SetDriverServiceStartType (DWORD startType) - { - return BaseCom::SetDriverServiceStartType (startType); - } - - virtual DWORD STDMETHODCALLTYPE WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value) - { - return BaseCom::WriteLocalMachineRegistryDwordValue (keyPath, valueName, value); - } - - virtual int STDMETHODCALLTYPE ChangePasswordEx (BSTR volumePath, Password *oldPassword, int old_pkcs5, Password *newPassword, int pkcs5, int wipePassCount, LONG_PTR hWnd) - { - MainDlg = (HWND) hWnd; - return ::ChangePwd (volumePath, oldPassword, old_pkcs5, 0, FALSE, newPassword, pkcs5, 0, wipePassCount, (HWND) hWnd); - } - - virtual int STDMETHODCALLTYPE ChangePasswordEx2 (BSTR volumePath, Password *oldPassword, int old_pkcs5, BOOL truecryptMode, Password *newPassword, int pkcs5, int wipePassCount, LONG_PTR hWnd) - { - MainDlg = (HWND) hWnd; - return ::ChangePwd (volumePath, oldPassword, old_pkcs5, 0, truecryptMode, newPassword, pkcs5, 0, wipePassCount, (HWND) hWnd); - } - - virtual int STDMETHODCALLTYPE ChangePasswordEx3 (BSTR volumePath, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, LONG_PTR hWnd) - { - MainDlg = (HWND) hWnd; - return ::ChangePwd (volumePath, oldPassword, old_pkcs5, old_pim, truecryptMode, newPassword, pkcs5, pim, wipePassCount, (HWND) hWnd); - } - -protected: - DWORD MessageThreadId; - LONG RefCount; -}; - - -extern "C" BOOL ComServerMain () -{ - SetProcessShutdownParameters (0x100, 0); - - TrueCryptFactory factory (GetCurrentThreadId ()); - DWORD cookie; - - if (IsUacSupported ()) - UacElevated = TRUE; - - if (CoRegisterClassObject (CLSID_TrueCryptMainCom, (LPUNKNOWN) &factory, - CLSCTX_LOCAL_SERVER, REGCLS_SINGLEUSE, &cookie) != S_OK) - return FALSE; - - MSG msg; - while (int r = GetMessageW (&msg, NULL, 0, 0)) - { - if (r == -1) - return FALSE; - - TranslateMessage (&msg); - DispatchMessageW (&msg); - - if (msg.message == WM_APP - && ObjectCount < 1 - && !factory.IsServerLocked ()) - break; - } - CoRevokeClassObject (cookie); - - return TRUE; -} - - -static BOOL ComGetInstance (HWND hWnd, ITrueCryptMainCom **tcServer) -{ - return ComGetInstanceBase (hWnd, CLSID_TrueCryptMainCom, IID_ITrueCryptMainCom, (void **) tcServer); -} - - -ITrueCryptMainCom *GetElevatedInstance (HWND parent) -{ - ITrueCryptMainCom *instance; - - if (!ComGetInstance (parent, &instance)) - throw UserAbort (SRC_POS); - - return instance; -} - - -extern "C" int UacBackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, wchar_t *lpszVolume) -{ - CComPtr tc; - int r; - - CoInitialize (NULL); - - if (ComGetInstance (hwndDlg, &tc)) - { - CComBSTR volumeBstr; - BSTR bstr = W2BSTR(lpszVolume); - if (bstr) - { - volumeBstr.Attach (bstr); - r = tc->BackupVolumeHeader ((LONG_PTR) hwndDlg, bRequireConfirmation, volumeBstr); - } - else - r = ERR_OUTOFMEMORY; - } - else - r = -1; - - CoUninitialize (); - - return r; -} - - -extern "C" int UacRestoreVolumeHeader (HWND hwndDlg, wchar_t *lpszVolume) -{ - CComPtr tc; - int r; - - CoInitialize (NULL); - - if (ComGetInstance (hwndDlg, &tc)) - { - CComBSTR volumeBstr; - BSTR bstr = W2BSTR(lpszVolume); - if (bstr) - { - volumeBstr.Attach (bstr); - r = tc->RestoreVolumeHeader ((LONG_PTR) hwndDlg, volumeBstr); - } - else - r = ERR_OUTOFMEMORY; - } - else - r = -1; - - CoUninitialize (); - - return r; -} - - -extern "C" int UacChangePwd (wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg) -{ - CComPtr tc; - int r; - - CoInitialize (NULL); - - if (ComGetInstance (hwndDlg, &tc)) - { - CComBSTR bstrVolume (lpszVolume); - WaitCursor (); - r = tc->ChangePasswordEx3 (bstrVolume, oldPassword, old_pkcs5, old_pim, truecryptMode, newPassword, pkcs5, pim, wipePassCount, (LONG_PTR) hwndDlg); - NormalCursor (); - } - else - r = -1; - - CoUninitialize (); - - return r; -} +/* + 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 +#include +#include +#include "BaseCom.h" +#include "BootEncryption.h" +#include "Dlgcode.h" +#include "MainCom.h" +#include "MainCom_h.h" +#include "MainCom_i.c" +#include "Mount.h" +#include "Password.h" + +using namespace VeraCrypt; + +static volatile LONG ObjectCount = 0; + +class TrueCryptMainCom : public ITrueCryptMainCom +{ + +public: + TrueCryptMainCom (DWORD messageThreadId) : RefCount (0), MessageThreadId (messageThreadId) + { + InterlockedIncrement (&ObjectCount); + } + + virtual ~TrueCryptMainCom () + { + if (InterlockedDecrement (&ObjectCount) == 0) + PostThreadMessage (MessageThreadId, WM_APP, 0, 0); + } + + virtual ULONG STDMETHODCALLTYPE AddRef () + { + return InterlockedIncrement (&RefCount); + } + + virtual ULONG STDMETHODCALLTYPE Release () + { + if (!InterlockedDecrement (&RefCount)) + { + delete this; + return 0; + } + + return RefCount; + } + + virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID riid, void **ppvObject) + { + if (riid == IID_IUnknown || riid == IID_ITrueCryptMainCom) + *ppvObject = this; + else + { + *ppvObject = NULL; + return E_NOINTERFACE; + } + + AddRef (); + return S_OK; + } + + virtual void STDMETHODCALLTYPE AnalyzeKernelMiniDump (LONG_PTR hwndDlg) + { + // Do nothing + MainDlg = (HWND) hwndDlg; + } + + virtual int STDMETHODCALLTYPE BackupVolumeHeader (LONG_PTR hwndDlg, BOOL bRequireConfirmation, BSTR lpszVolume) + { + MainDlg = (HWND) hwndDlg; + return ::BackupVolumeHeader ((HWND) hwndDlg, bRequireConfirmation, lpszVolume); + } + + virtual int STDMETHODCALLTYPE RestoreVolumeHeader (LONG_PTR hwndDlg, BSTR lpszVolume) + { + MainDlg = (HWND) hwndDlg; + return ::RestoreVolumeHeader ((HWND) hwndDlg, lpszVolume); + } + + virtual DWORD STDMETHODCALLTYPE CallDriver (DWORD ioctl, BSTR input, BSTR *output) + { + return BaseCom::CallDriver (ioctl, input, output); + } + + virtual int STDMETHODCALLTYPE ChangePassword (BSTR volumePath, Password *oldPassword, Password *newPassword, int pkcs5, int wipePassCount, LONG_PTR hWnd) + { + MainDlg = (HWND) hWnd; + return ::ChangePwd (volumePath, oldPassword, 0, 0, FALSE, newPassword, pkcs5, 0, wipePassCount, (HWND) hWnd); + } + + virtual DWORD STDMETHODCALLTYPE CopyFile (BSTR sourceFile, BSTR destinationFile) + { + return BaseCom::CopyFile (sourceFile, destinationFile); + } + + virtual DWORD STDMETHODCALLTYPE DeleteFile (BSTR file) + { + return BaseCom::DeleteFile (file); + } + + virtual BOOL STDMETHODCALLTYPE IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) + { + return BaseCom::IsPagingFileActive (checkNonWindowsPartitionsOnly); + } + + virtual DWORD STDMETHODCALLTYPE ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone) + { + return BaseCom::ReadWriteFile (write, device, filePath, bufferBstr, offset, size, sizeDone); + } + + virtual DWORD STDMETHODCALLTYPE RegisterFilterDriver (BOOL registerDriver, int filterType) + { + return BaseCom::RegisterFilterDriver (registerDriver, filterType); + } + + virtual DWORD STDMETHODCALLTYPE RegisterSystemFavoritesService (BOOL registerService) + { + return BaseCom::RegisterSystemFavoritesService (registerService); + } + + virtual DWORD STDMETHODCALLTYPE SetDriverServiceStartType (DWORD startType) + { + return BaseCom::SetDriverServiceStartType (startType); + } + + virtual DWORD STDMETHODCALLTYPE WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value) + { + return BaseCom::WriteLocalMachineRegistryDwordValue (keyPath, valueName, value); + } + + virtual int STDMETHODCALLTYPE ChangePasswordEx (BSTR volumePath, Password *oldPassword, int old_pkcs5, Password *newPassword, int pkcs5, int wipePassCount, LONG_PTR hWnd) + { + MainDlg = (HWND) hWnd; + return ::ChangePwd (volumePath, oldPassword, old_pkcs5, 0, FALSE, newPassword, pkcs5, 0, wipePassCount, (HWND) hWnd); + } + + virtual int STDMETHODCALLTYPE ChangePasswordEx2 (BSTR volumePath, Password *oldPassword, int old_pkcs5, BOOL truecryptMode, Password *newPassword, int pkcs5, int wipePassCount, LONG_PTR hWnd) + { + MainDlg = (HWND) hWnd; + return ::ChangePwd (volumePath, oldPassword, old_pkcs5, 0, truecryptMode, newPassword, pkcs5, 0, wipePassCount, (HWND) hWnd); + } + + virtual int STDMETHODCALLTYPE ChangePasswordEx3 (BSTR volumePath, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, LONG_PTR hWnd) + { + MainDlg = (HWND) hWnd; + return ::ChangePwd (volumePath, oldPassword, old_pkcs5, old_pim, truecryptMode, newPassword, pkcs5, pim, wipePassCount, (HWND) hWnd); + } + +protected: + DWORD MessageThreadId; + LONG RefCount; +}; + + +extern "C" BOOL ComServerMain () +{ + SetProcessShutdownParameters (0x100, 0); + + TrueCryptFactory factory (GetCurrentThreadId ()); + DWORD cookie; + + if (IsUacSupported ()) + UacElevated = TRUE; + + if (CoRegisterClassObject (CLSID_TrueCryptMainCom, (LPUNKNOWN) &factory, + CLSCTX_LOCAL_SERVER, REGCLS_SINGLEUSE, &cookie) != S_OK) + return FALSE; + + MSG msg; + while (int r = GetMessageW (&msg, NULL, 0, 0)) + { + if (r == -1) + return FALSE; + + TranslateMessage (&msg); + DispatchMessageW (&msg); + + if (msg.message == WM_APP + && ObjectCount < 1 + && !factory.IsServerLocked ()) + break; + } + CoRevokeClassObject (cookie); + + return TRUE; +} + + +static BOOL ComGetInstance (HWND hWnd, ITrueCryptMainCom **tcServer) +{ + return ComGetInstanceBase (hWnd, CLSID_TrueCryptMainCom, IID_ITrueCryptMainCom, (void **) tcServer); +} + + +ITrueCryptMainCom *GetElevatedInstance (HWND parent) +{ + ITrueCryptMainCom *instance; + + if (!ComGetInstance (parent, &instance)) + throw UserAbort (SRC_POS); + + return instance; +} + + +extern "C" int UacBackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, wchar_t *lpszVolume) +{ + CComPtr tc; + int r; + + CoInitialize (NULL); + + if (ComGetInstance (hwndDlg, &tc)) + { + CComBSTR volumeBstr; + BSTR bstr = W2BSTR(lpszVolume); + if (bstr) + { + volumeBstr.Attach (bstr); + r = tc->BackupVolumeHeader ((LONG_PTR) hwndDlg, bRequireConfirmation, volumeBstr); + } + else + r = ERR_OUTOFMEMORY; + } + else + r = -1; + + CoUninitialize (); + + return r; +} + + +extern "C" int UacRestoreVolumeHeader (HWND hwndDlg, wchar_t *lpszVolume) +{ + CComPtr tc; + int r; + + CoInitialize (NULL); + + if (ComGetInstance (hwndDlg, &tc)) + { + CComBSTR volumeBstr; + BSTR bstr = W2BSTR(lpszVolume); + if (bstr) + { + volumeBstr.Attach (bstr); + r = tc->RestoreVolumeHeader ((LONG_PTR) hwndDlg, volumeBstr); + } + else + r = ERR_OUTOFMEMORY; + } + else + r = -1; + + CoUninitialize (); + + return r; +} + + +extern "C" int UacChangePwd (wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg) +{ + CComPtr tc; + int r; + + CoInitialize (NULL); + + if (ComGetInstance (hwndDlg, &tc)) + { + CComBSTR bstrVolume (lpszVolume); + WaitCursor (); + r = tc->ChangePasswordEx3 (bstrVolume, oldPassword, old_pkcs5, old_pim, truecryptMode, newPassword, pkcs5, pim, wipePassCount, (LONG_PTR) hwndDlg); + NormalCursor (); + } + else + r = -1; + + CoUninitialize (); + + return r; +} diff --git a/src/Mount/MainCom.h b/src/Mount/MainCom.h index 9fad2870..5bd8e222 100644 --- a/src/Mount/MainCom.h +++ b/src/Mount/MainCom.h @@ -1,35 +1,35 @@ -/* - 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. -*/ - -#ifndef TC_HEADER_MAIN_COM -#define TC_HEADER_MAIN_COM - -#include - -#ifdef __cplusplus - -#include "MainCom_h.h" -ITrueCryptMainCom *GetElevatedInstance (HWND parent); - -extern "C" { -#endif - -BOOL ComServerMain (); -int UacBackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, wchar_t *lpszVolume); -int UacRestoreVolumeHeader (HWND hwndDlg, wchar_t *lpszVolume); -int UacChangePwd (wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg); - -#ifdef __cplusplus -} -#endif - -#endif // TC_HEADER_MAIN_COM +/* + 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. +*/ + +#ifndef TC_HEADER_MAIN_COM +#define TC_HEADER_MAIN_COM + +#include + +#ifdef __cplusplus + +#include "MainCom_h.h" +ITrueCryptMainCom *GetElevatedInstance (HWND parent); + +extern "C" { +#endif + +BOOL ComServerMain (); +int UacBackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, wchar_t *lpszVolume); +int UacRestoreVolumeHeader (HWND hwndDlg, wchar_t *lpszVolume); +int UacChangePwd (wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg); + +#ifdef __cplusplus +} +#endif + +#endif // TC_HEADER_MAIN_COM diff --git a/src/Mount/MainCom.idl b/src/Mount/MainCom.idl index 4e268a53..4999dba5 100644 --- a/src/Mount/MainCom.idl +++ b/src/Mount/MainCom.idl @@ -1,57 +1,57 @@ -/* - 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. -*/ - -import "wtypes.idl"; -import "..\Common\Password.h"; - -[ - uuid(9ACF6176-5FC4-4690-A025-B3306A50EB6A), - helpstring("VeraCrypt Main UAC Support Library"), - version(2.7) // Update ComSetup.cpp when changing version number -] -library TrueCryptMainCom -{ - [ - uuid(C786E27C-2801-482c-B45D-D4357B270A29), - object, - oleautomation, - helpstring("VeraCrypt Main UAC Support Interface") - ] - interface ITrueCryptMainCom : IUnknown - { - void AnalyzeKernelMiniDump (LONG_PTR hwndDlg); - int BackupVolumeHeader (LONG_PTR hwndDlg, BOOL bRequireConfirmation, BSTR lpszVolume); - DWORD CallDriver (DWORD ioctl, BSTR input, BSTR *output); - int ChangePassword (BSTR volumePath, Password *oldPassword, Password *newPassword, int pkcs5, int wipePassCount, LONG_PTR hWnd); - DWORD CopyFile (BSTR sourceFile, BSTR destinationFile); - DWORD DeleteFile (BSTR file); - BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly); - DWORD ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone); - DWORD RegisterFilterDriver (BOOL registerDriver, int filterType); - DWORD RegisterSystemFavoritesService (BOOL registerService); - int RestoreVolumeHeader (LONG_PTR hwndDlg, BSTR lpszVolume); - DWORD SetDriverServiceStartType (DWORD startType); - DWORD WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value); - int ChangePasswordEx (BSTR volumePath, Password *oldPassword, int old_pkcs5, Password *newPassword, int pkcs5, int wipePassCount, LONG_PTR hWnd); - int ChangePasswordEx2 (BSTR volumePath, Password *oldPassword, int old_pkcs5, BOOL truecryptMode, Password *newPassword, int pkcs5, int wipePassCount, LONG_PTR hWnd); - int ChangePasswordEx3 (BSTR volumePath, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, LONG_PTR hWnd); - }; - - [ - uuid(FE8B3B95-C80C-41f7-830F-FBA271C26F7E), - helpstring("VeraCrypt Main UAC Support Coclass") - ] - coclass TrueCryptMainCom - { - [default] interface ITrueCryptMainCom; - } -} +/* + 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. +*/ + +import "wtypes.idl"; +import "..\Common\Password.h"; + +[ + uuid(9ACF6176-5FC4-4690-A025-B3306A50EB6A), + helpstring("VeraCrypt Main UAC Support Library"), + version(2.7) // Update ComSetup.cpp when changing version number +] +library TrueCryptMainCom +{ + [ + uuid(C786E27C-2801-482c-B45D-D4357B270A29), + object, + oleautomation, + helpstring("VeraCrypt Main UAC Support Interface") + ] + interface ITrueCryptMainCom : IUnknown + { + void AnalyzeKernelMiniDump (LONG_PTR hwndDlg); + int BackupVolumeHeader (LONG_PTR hwndDlg, BOOL bRequireConfirmation, BSTR lpszVolume); + DWORD CallDriver (DWORD ioctl, BSTR input, BSTR *output); + int ChangePassword (BSTR volumePath, Password *oldPassword, Password *newPassword, int pkcs5, int wipePassCount, LONG_PTR hWnd); + DWORD CopyFile (BSTR sourceFile, BSTR destinationFile); + DWORD DeleteFile (BSTR file); + BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly); + DWORD ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone); + DWORD RegisterFilterDriver (BOOL registerDriver, int filterType); + DWORD RegisterSystemFavoritesService (BOOL registerService); + int RestoreVolumeHeader (LONG_PTR hwndDlg, BSTR lpszVolume); + DWORD SetDriverServiceStartType (DWORD startType); + DWORD WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value); + int ChangePasswordEx (BSTR volumePath, Password *oldPassword, int old_pkcs5, Password *newPassword, int pkcs5, int wipePassCount, LONG_PTR hWnd); + int ChangePasswordEx2 (BSTR volumePath, Password *oldPassword, int old_pkcs5, BOOL truecryptMode, Password *newPassword, int pkcs5, int wipePassCount, LONG_PTR hWnd); + int ChangePasswordEx3 (BSTR volumePath, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, LONG_PTR hWnd); + }; + + [ + uuid(FE8B3B95-C80C-41f7-830F-FBA271C26F7E), + helpstring("VeraCrypt Main UAC Support Coclass") + ] + coclass TrueCryptMainCom + { + [default] interface ITrueCryptMainCom; + } +} diff --git a/src/Mount/Mount.c b/src/Mount/Mount.c index 5bcaddad..ef665a5a 100644 --- a/src/Mount/Mount.c +++ b/src/Mount/Mount.c @@ -1,11024 +1,11024 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" -#include "cpu.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Apidrvr.h" -#include "BootEncryption.h" -#include "Cmdline.h" -#include "Crypto.h" -#include "Dlgcode.h" -#include "Combo.h" -#include "Favorites.h" -#include "Hotkeys.h" -#include "Keyfiles.h" -#include "Language.h" -#include "MainCom.h" -#include "Mount.h" -#include "Pkcs5.h" -#include "Random.h" -#include "Registry.h" -#include "Resource.h" -#include "Password.h" -#include "Xml.h" -#include "../Boot/Windows/BootCommon.h" -#include "../Common/Dictionary.h" -#include "../Common/Common.h" -#include "../Common/Resource.h" -#include "../Common/SecurityToken.h" -#include "../Platform/Finally.h" -#include "../Platform/ForEach.h" - -#include - -#include - -typedef BOOL (WINAPI *WTSREGISTERSESSIONNOTIFICATION)(HWND, DWORD); -typedef BOOL (WINAPI *WTSUNREGISTERSESSIONNOTIFICATION)(HWND); - -using namespace VeraCrypt; - -enum timer_ids -{ - TIMER_ID_MAIN = 0xff, - TIMER_ID_KEYB_LAYOUT_GUARD -}; - -enum hidden_os_read_only_notif_mode -{ - TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_NONE = 0, - TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_COMPACT, - TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_DISABLED -}; - -#define TIMER_INTERVAL_MAIN 500 -#define TIMER_INTERVAL_KEYB_LAYOUT_GUARD 10 - -BootEncryption *BootEncObj = NULL; -BootEncryptionStatus BootEncStatus; -BootEncryptionStatus RecentBootEncStatus; - -BOOL bExplore = FALSE; /* Display explorer window after mount */ -BOOL bBeep = FALSE; /* Donot beep after mount */ -wchar_t szFileName[TC_MAX_PATH+1]; /* Volume to mount */ -wchar_t szDriveLetter[3]; /* Drive Letter to mount */ -wchar_t commandLineDrive = 0; -BOOL bCacheInDriver = FALSE; /* Cache any passwords we see */ -BOOL bCacheInDriverDefault = FALSE; -BOOL bCacheDuringMultipleMount = FALSE; -BOOL bCmdCacheDuringMultipleMount = FALSE; -BOOL bIncludePimInCache = FALSE; -BOOL bTryEmptyPasswordWhenKeyfileUsed = FALSE; -BOOL bCmdTryEmptyPasswordWhenKeyfileUsed = FALSE; -BOOL bCmdTryEmptyPasswordWhenKeyfileUsedValid = FALSE; -BOOL bHistoryCmdLine = FALSE; /* History control is always disabled */ -BOOL bUseDifferentTrayIconIfVolMounted = TRUE; -BOOL bCloseDismountedWindows=TRUE; /* Close all open explorer windows of dismounted volume */ -BOOL bWipeCacheOnExit = FALSE; /* Wipe password from chace on exit */ -BOOL bWipeCacheOnAutoDismount = TRUE; -BOOL bEnableBkgTask = FALSE; -BOOL bCloseBkgTaskWhenNoVolumes = FALSE; -BOOL bDismountOnLogOff = TRUE; -BOOL bDismountOnSessionLocked = TRUE; -BOOL bDismountOnScreenSaver = TRUE; -BOOL bDismountOnPowerSaving = FALSE; -BOOL bForceAutoDismount = TRUE; -BOOL bForceMount = FALSE; /* Mount volume even if host file/device already in use */ -BOOL bForceUnmount = FALSE; /* Unmount volume even if it cannot be locked */ -BOOL bWipe = FALSE; /* Wipe driver passwords */ -BOOL bAuto = FALSE; /* Do everything without user input */ -BOOL LogOn = FALSE; -BOOL bAutoMountDevices = FALSE; /* Auto-mount devices */ -BOOL bAutoMountFavorites = FALSE; -BOOL bPlaySoundOnSuccessfulHkDismount = TRUE; -BOOL bDisplayBalloonOnSuccessfulHkDismount = TRUE; -BOOL bHibernationPreventionNotified = FALSE; /* TRUE if the user has been notified that hibernation was prevented (system encryption) during the session. */ -BOOL bHiddenSysLeakProtNotifiedDuringSession = FALSE; /* TRUE if the user has been notified during the session that unencrypted filesystems and non-hidden TrueCrypt volumes are mounted as read-only under hidden OS. */ -BOOL CloseSecurityTokenSessionsAfterMount = FALSE; - -BOOL Quit = FALSE; /* Exit after processing command line */ -BOOL ComServerMode = FALSE; -BOOL ServiceMode = FALSE; -BOOL UsePreferences = TRUE; - -int HiddenSysLeakProtectionNotificationStatus = TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_NONE; -int MaxVolumeIdleTime = -120; -int nCurrentShowType = 0; /* current display mode, mount, unmount etc */ -int nSelectedDriveIndex = -1; /* Item number of selected drive */ - -int cmdUnmountDrive = -2; /* Volume drive letter to unmount (-1 = all) */ -Password VolumePassword; /* Password used for mounting volumes */ -Password CmdVolumePassword; /* Password passed from command line */ -char CmdTokenPin [SecurityToken::MaxPasswordLength + 1] = {0}; -int VolumePkcs5 = 0; -int CmdVolumePkcs5 = 0; -int VolumePim = -1; -int CmdVolumePim = -1; -int DefaultVolumePkcs5 = 0; -BOOL VolumeTrueCryptMode = FALSE; -BOOL CmdVolumeTrueCryptMode = FALSE; -BOOL DefaultVolumeTrueCryptMode = FALSE; -BOOL CmdVolumePasswordValid = FALSE; -MountOptions CmdMountOptions; -BOOL CmdMountOptionsValid = FALSE; -MountOptions mountOptions; -MountOptions defaultMountOptions; -KeyFile *FirstCmdKeyFile; - -HBITMAP hbmLogoBitmapRescaled = NULL; -wchar_t OrigKeyboardLayout [8+1] = L"00000409"; -BOOL bKeyboardLayoutChanged = FALSE; /* TRUE if the keyboard layout was changed to the standard US keyboard layout (from any other layout). */ -BOOL bKeybLayoutAltKeyWarningShown = FALSE; /* TRUE if the user has been informed that it is not possible to type characters by pressing keys while the right Alt key is held down. */ - -static KeyFilesDlgParam hidVolProtKeyFilesParam; - -static MOUNT_LIST_STRUCT LastKnownMountList; -VOLUME_NOTIFICATIONS_LIST VolumeNotificationsList; -static DWORD LastKnownLogicalDrives; - -static HANDLE TaskBarIconMutex = NULL; -static BOOL MainWindowHidden = FALSE; -static int pwdChangeDlgMode = PCDM_CHANGE_PASSWORD; -static int bSysEncPwdChangeDlgMode = FALSE; -static int bPrebootPasswordDlgMode = FALSE; -static int NoCmdLineArgs; -static BOOL CmdLineVolumeSpecified; -static int LastDriveListVolumeColumnWidth; -// WTS handling -static HMODULE hWtsLib = NULL; -static WTSREGISTERSESSIONNOTIFICATION fnWtsRegisterSessionNotification = NULL; -static WTSUNREGISTERSESSIONNOTIFICATION fnWtsUnRegisterSessionNotification = NULL; - -static void RegisterWtsNotification(HWND hWnd) -{ - if (!hWtsLib) - { - wchar_t dllPath[MAX_PATH]; - if (GetSystemDirectory(dllPath, MAX_PATH)) - StringCbCatW(dllPath, sizeof(dllPath), L"\\wtsapi32.dll"); - else - StringCbCopyW(dllPath, sizeof(dllPath), L"c:\\Windows\\System32\\wtsapi32.dll"); - - hWtsLib = LoadLibrary(dllPath); - if (hWtsLib) - { - fnWtsRegisterSessionNotification = (WTSREGISTERSESSIONNOTIFICATION) GetProcAddress(hWtsLib, "WTSRegisterSessionNotification" ); - fnWtsUnRegisterSessionNotification = (WTSUNREGISTERSESSIONNOTIFICATION) GetProcAddress(hWtsLib, "WTSUnRegisterSessionNotification" ); - if ( !fnWtsRegisterSessionNotification - || !fnWtsUnRegisterSessionNotification - || !fnWtsRegisterSessionNotification( hWnd, NOTIFY_FOR_THIS_SESSION ) - ) - { - fnWtsRegisterSessionNotification = NULL; - fnWtsUnRegisterSessionNotification = NULL; - FreeLibrary(hWtsLib); - hWtsLib = NULL; - } - } - } -} - -static void UnregisterWtsNotification(HWND hWnd) -{ - if (hWtsLib && fnWtsUnRegisterSessionNotification) - { - fnWtsUnRegisterSessionNotification(hWnd); - FreeLibrary(hWtsLib); - hWtsLib = NULL; - fnWtsRegisterSessionNotification = NULL; - fnWtsUnRegisterSessionNotification = NULL; - } -} - -static void localcleanup (void) -{ - // Wipe command line - char *c = GetCommandLineA (); - wchar_t *wc = GetCommandLineW (); - burn(c, strlen (c)); - burn(wc, wcslen (wc) * sizeof (wchar_t)); - - /* Delete buffered bitmaps (if any) */ - if (hbmLogoBitmapRescaled != NULL) - { - DeleteObject ((HGDIOBJ) hbmLogoBitmapRescaled); - hbmLogoBitmapRescaled = NULL; - } - - /* These items should have already been cleared by the functions that used them, but we're going to - clear them for extra security. */ - burn (&VolumePassword, sizeof (VolumePassword)); - burn (&CmdVolumePassword, sizeof (CmdVolumePassword)); - burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&CmdVolumePkcs5, sizeof (CmdVolumePkcs5)); - burn (&VolumePim, sizeof (VolumePim)); - burn (&CmdVolumePim, sizeof (CmdVolumePim)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); - burn (&CmdVolumeTrueCryptMode, sizeof (CmdVolumeTrueCryptMode)); - burn (&mountOptions, sizeof (mountOptions)); - burn (&defaultMountOptions, sizeof (defaultMountOptions)); - burn (szFileName, sizeof(szFileName)); - burn (&CmdTokenPin, sizeof (CmdTokenPin)); - - /* Cleanup common code resources */ - cleanup (); - - if (BootEncObj != NULL) - { - delete BootEncObj; - BootEncObj = NULL; - } - - RandStop (TRUE); -} - -void RefreshMainDlg (HWND hwndDlg) -{ - int drive = (wchar_t) (HIWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST)))); - - MoveEditToCombo (GetDlgItem (hwndDlg, IDC_VOLUME), bHistory); - LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), drive); - EnableDisableButtons (hwndDlg); -} - -void EndMainDlg (HWND hwndDlg) -{ - MoveEditToCombo (GetDlgItem (hwndDlg, IDC_VOLUME), bHistory); - - if (UsePreferences) - SaveSettings (hwndDlg); - - if (bWipeCacheOnExit) - { - DWORD dwResult; - DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - } - - if (!bHistory) - { - SetWindowText (GetDlgItem (hwndDlg, IDC_VOLUME), L""); - ClearHistory (GetDlgItem (hwndDlg, IDC_VOLUME)); - } - - if (TaskBarIconMutex != NULL) - { - MainWindowHidden = TRUE; - ShowWindow (hwndDlg, SW_HIDE); - } - else - { - KillTimer (hwndDlg, TIMER_ID_MAIN); - TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); - EndDialog (hwndDlg, 0); - } -} - -static void InitMainDialog (HWND hwndDlg) -{ - MENUITEMINFOW info; - char *popupTexts[] = {"MENU_VOLUMES", "MENU_SYSTEM_ENCRYPTION", "MENU_FAVORITES", "MENU_TOOLS", "MENU_SETTINGS", "MENU_HELP", "MENU_WEBSITE", 0}; - wchar_t *str; - int i; - - /* Call the common dialog init code */ - InitDialog (hwndDlg); - LocalizeDialog (hwndDlg, NULL); - - SetWindowLongPtrW (hwndDlg, DWLP_USER, (LONG_PTR) (IsAdmin() ? TC_MAIN_WINDOW_FLAG_ADMIN_PRIVILEGES : 0)); - - DragAcceptFiles (hwndDlg, TRUE); - - SendMessageW (GetDlgItem (hwndDlg, IDC_VOLUME), CB_LIMITTEXT, TC_MAX_PATH, 0); - SetWindowTextW (hwndDlg, (IsAdmin() && !IsBuiltInAdmin() && IsUacSupported() && !IsNonInstallMode()) ? (wstring (lpszTitle) + L" [" + GetString ("ADMINISTRATOR") + L"]").c_str() : lpszTitle); - - // Help file name - InitHelpFileName(); - - // Localize menu strings - for (i = 40001; str = (wchar_t *)GetDictionaryValueByInt (i); i++) - { - info.cbSize = sizeof (info); - info.fMask = MIIM_TYPE; - info.fType = MFT_STRING; - info.dwTypeData = str; - info.cch = (UINT) wcslen (str); - - SetMenuItemInfoW (GetMenu (hwndDlg), i, FALSE, &info); - } - - for (i = 0; popupTexts[i] != 0; i++) - { - str = GetString (popupTexts[i]); - - info.cbSize = sizeof (info); - info.fMask = MIIM_TYPE; - - if (strcmp (popupTexts[i], "MENU_WEBSITE") == 0) - info.fType = MFT_STRING | MFT_RIGHTJUSTIFY; - else - info.fType = MFT_STRING; - - if (strcmp (popupTexts[i], "MENU_FAVORITES") == 0) - FavoriteVolumesMenu = GetSubMenu (GetMenu (hwndDlg), i); - - info.dwTypeData = str; - info.cch = (UINT) wcslen (str); - - SetMenuItemInfoW (GetMenu (hwndDlg), i, TRUE, &info); - } - - // Disable menu item for changing system header key derivation algorithm until it's implemented - EnableMenuItem (GetMenu (hwndDlg), IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO, MF_GRAYED); - - try - { - LoadFavoriteVolumes(); - } - catch (Exception &e) - { - e.Show (NULL); - } - - // Resize the logo bitmap if the user has a non-default DPI - if (ScreenDPI != USER_DEFAULT_SCREEN_DPI - && hbmLogoBitmapRescaled == NULL) // If not re-called (e.g. after language pack change) - { - hbmLogoBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_LOGO_288DPI), - GetDlgItem (hwndDlg, IDC_LOGO), - 0, 0, 0, 0, FALSE, TRUE); - } - - BuildTree (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST)); - - if (*szDriveLetter != 0) - { - SelectItem (GetDlgItem (hwndDlg, IDC_DRIVELIST), *szDriveLetter); - - if(nSelectedDriveIndex > SendMessage (GetDlgItem (hwndDlg, IDC_DRIVELIST), LVM_GETITEMCOUNT, 0, 0)/2) - SendMessage(GetDlgItem (hwndDlg, IDC_DRIVELIST), LVM_SCROLL, 0, 10000); - } - else - { - SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hwndDlg, IDC_DRIVELIST), 1L); - } - - SendMessage (GetDlgItem (hwndDlg, IDC_NO_HISTORY), BM_SETCHECK, bHistory ? BST_UNCHECKED : BST_CHECKED, 0); - EnableDisableButtons (hwndDlg); -} - -void EnableDisableButtons (HWND hwndDlg) -{ - HWND hOKButton = GetDlgItem (hwndDlg, IDOK); - WORD x; - - x = LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))); - - EnableMenuItem (GetMenu (hwndDlg), IDM_MOUNT_VOLUME, MF_ENABLED); - EnableMenuItem (GetMenu (hwndDlg), IDM_MOUNT_VOLUME_OPTIONS, MF_ENABLED); - EnableMenuItem (GetMenu (hwndDlg), IDM_BACKUP_VOL_HEADER, MF_ENABLED); - EnableMenuItem (GetMenu (hwndDlg), IDM_RESTORE_VOL_HEADER, MF_ENABLED); - EnableMenuItem (GetMenu (hwndDlg), IDM_CHANGE_PASSWORD, MF_ENABLED); - EnableWindow (hOKButton, TRUE); - - switch (x) - { - case TC_MLIST_ITEM_NONSYS_VOL: - { - SetWindowTextW (hOKButton, GetString ("UNMOUNT_BUTTON")); - EnableWindow (hOKButton, TRUE); - EnableMenuItem (GetMenu (hwndDlg), IDM_UNMOUNT_VOLUME, MF_ENABLED); - - EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES), TRUE); - EnableMenuItem (GetMenu (hwndDlg), IDM_VOLUME_PROPERTIES, MF_ENABLED); - } - break; - - case TC_MLIST_ITEM_SYS_PARTITION: - case TC_MLIST_ITEM_SYS_DRIVE: - EnableWindow (hOKButton, FALSE); - SetWindowTextW (hOKButton, GetString ("MOUNT_BUTTON")); - EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES), TRUE); - EnableMenuItem (GetMenu (hwndDlg), IDM_UNMOUNT_VOLUME, MF_GRAYED); - break; - - case TC_MLIST_ITEM_FREE: - default: - SetWindowTextW (hOKButton, GetString ("MOUNT_BUTTON")); - EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES), FALSE); - EnableMenuItem (GetMenu (hwndDlg), IDM_VOLUME_PROPERTIES, MF_GRAYED); - EnableMenuItem (GetMenu (hwndDlg), IDM_UNMOUNT_VOLUME, MF_GRAYED); - } - - EnableWindow (GetDlgItem (hwndDlg, IDC_WIPE_CACHE), !IsPasswordCacheEmpty()); - EnableMenuItem (GetMenu (hwndDlg), IDM_WIPE_CACHE, IsPasswordCacheEmpty() ? MF_GRAYED:MF_ENABLED); - EnableMenuItem (GetMenu (hwndDlg), IDM_CLEAR_HISTORY, IsComboEmpty (GetDlgItem (hwndDlg, IDC_VOLUME)) ? MF_GRAYED:MF_ENABLED); -} - -BOOL VolumeSelected (HWND hwndDlg) -{ - return (GetWindowTextLength (GetDlgItem (hwndDlg, IDC_VOLUME)) > 0); -} - -void GetVolumePath (HWND hwndDlg, LPWSTR szPath, int nMaxCount) -{ - GetWindowText (GetDlgItem (hwndDlg, IDC_VOLUME), szPath, nMaxCount); - CorrectFileName (szPath); -} - -/* Returns TRUE if the last partition/drive selected via the Select Device dialog box was the system -partition/drive and if it is encrypted. - WARNING: This function is very fast but not always reliable (for example, if the user manually types - a device path before Select Device is invoked during the session; after the Select Device dialog - has been invoked at least once, the correct system device paths are cached). Therefore, it must NOT - be used before performing any dangerous operations (such as header backup restore or formatting a - supposedly non-system device) -- instead use IsSystemDevicePath(path, hwndDlg, TRUE) for such - purposes. This function can be used only for preliminary GUI checks requiring very fast responses. */ -BOOL ActiveSysEncDeviceSelected (void) -{ - try - { - BootEncStatus = BootEncObj->GetStatus(); - - if (BootEncStatus.DriveEncrypted) - { - int retCode = 0; - - GetVolumePath (MainDlg, szFileName, ARRAYSIZE (szFileName)); - - retCode = IsSystemDevicePath (szFileName, MainDlg, FALSE); - - return (WholeSysDriveEncryption(FALSE) ? (retCode == 2 || retCode == 1) : (retCode == 1)); - } - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - return FALSE; -} - -// When a function does not require the affected volume to be dismounted, there may be cases where we have two valid -// paths selected in the main window and we cannot be sure which of them the user really intends to apply the function to. -// This function asks the user to explicitly select either the volume path specified in the input field below the main -// drive list (whether mounted or not), or the path to the volume selected in the main drive list. If, however, both -// of the GUI elements contain the same volume (or one of them does not contain any path), this function does not -// ask the user and returns the volume path directly (no selection ambiguity). -// If driveNoPtr is not NULL, and the volume is mounted, its drive letter is returned in *driveNoPtr (if no valid drive -// letter is resolved, -1 is stored instead). -static wstring ResolveAmbiguousSelection (HWND hwndDlg, int *driveNoPtr) -{ - LPARAM selectedDrive = GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST)); - - wchar_t volPathInputField [TC_MAX_PATH]; - - wchar_t volPathDriveListW [TC_MAX_PATH]; - wstring volPathDriveListStr; - - wstring retPath; - - VOLUME_PROPERTIES_STRUCT prop; - DWORD dwResult; - - BOOL useInputField = TRUE; - - memset (&prop, 0, sizeof(prop)); - - BOOL ambig = (LOWORD (selectedDrive) != TC_MLIST_ITEM_FREE && LOWORD (selectedDrive) != 0xffff && HIWORD (selectedDrive) != 0xffff - && VolumeSelected (MainDlg)); - - if (VolumeSelected (MainDlg)) - { - // volPathInputField will contain the volume path (if any) from the input field below the drive list - GetVolumePath (MainDlg, volPathInputField, ARRAYSIZE (volPathInputField)); - - if (!ambig) - retPath = (wstring) volPathInputField; - } - - if (LOWORD (selectedDrive) != TC_MLIST_ITEM_FREE && LOWORD (selectedDrive) != 0xffff && HIWORD (selectedDrive) != 0xffff) - { - // A volume is selected in the main drive list. - - switch (LOWORD (selectedDrive)) - { - case TC_MLIST_ITEM_NONSYS_VOL: - prop.driveNo = HIWORD (selectedDrive) - L'A'; - - if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL) || dwResult == 0) - { - // The driver did not return any path for this drive letter (the volume may have been dismounted). - - // Return whatever is in the input field below the drive list (even if empty) - return ((wstring) volPathInputField); - } - - // volPathDriveListWStr will contain the volume path selected in the main drive list - volPathDriveListStr = (wstring) prop.wszVolume; - break; - - case TC_MLIST_ITEM_SYS_PARTITION: - - GetSysDevicePaths (MainDlg); - - if (bCachedSysDevicePathsValid) - { - volPathDriveListStr = (wstring) SysPartitionDevicePath; - } - - break; - - case TC_MLIST_ITEM_SYS_DRIVE: - - GetSysDevicePaths (MainDlg); - - if (bCachedSysDevicePathsValid) - { - volPathDriveListStr = (wstring) SysDriveDevicePath; - } - - break; - } - - if (!ambig) - { - useInputField = FALSE; - retPath = volPathDriveListStr; - } - } - - if (ambig) - { - /* We have two paths. Compare them and if they don't match, ask the user to select one of them. Otherwise, return the path without asking. */ - - if (wmemcmp (volPathDriveListStr.c_str (), L"\\??\\", 4) == 0) - { - // The volume path starts with "\\??\\" which is used for file-hosted containers. We're going to strip this prefix. - - volPathDriveListStr = (wstring) (volPathDriveListStr.c_str () + 4); - } - - StringCbCopyW (volPathDriveListW, sizeof(volPathDriveListW), volPathDriveListStr.c_str ()); - - if (wcscmp (((wmemcmp (volPathDriveListW, L"\\??\\", 4) == 0) ? volPathDriveListW + 4 : volPathDriveListW), volPathInputField) != 0) - { - // The path selected in the input field is different from the path to the volume selected - // in the drive lettter list. We have to resolve possible ambiguity. - - wchar_t *tmp[] = {L"", L"", L"", L"", L"", 0}; - const int maxVolPathLen = 80; - - if (volPathDriveListStr.length () > maxVolPathLen) - { - // Ellipsis (path too long) - volPathDriveListStr = wstring (L"...") + volPathDriveListStr.substr (volPathDriveListStr.length () - maxVolPathLen, maxVolPathLen); - } - - wstring volPathInputFieldWStr (volPathInputField); - - if (volPathInputFieldWStr.length () > maxVolPathLen) - { - // Ellipsis (path too long) - volPathInputFieldWStr = wstring (L"...") + volPathInputFieldWStr.substr (volPathInputFieldWStr.length () - maxVolPathLen, maxVolPathLen); - } - - tmp[1] = GetString ("AMBIGUOUS_VOL_SELECTION"); - tmp[2] = (wchar_t *) volPathDriveListStr.c_str(); - tmp[3] = (wchar_t *) volPathInputFieldWStr.c_str(); - tmp[4] = GetString ("IDCANCEL"); - - switch (AskMultiChoice ((void **) tmp, FALSE, hwndDlg)) - { - case 1: - retPath = volPathDriveListStr; - break; - - case 2: - retPath = (wstring) volPathInputField; - break; - - default: - if (driveNoPtr != NULL) - *driveNoPtr = -1; - - return wstring (L""); - } - } - else - { - // Both selected paths are the same - retPath = (wstring) volPathInputField; - } - } - - if (driveNoPtr != NULL) - *driveNoPtr = GetMountedVolumeDriveNo ((wchar_t *) retPath.c_str ()); - - - if (wmemcmp (retPath.c_str (), L"\\??\\", 4) == 0) - { - // The selected volume path starts with "\\??\\" which is used for file-hosted containers. We're going to strip this prefix. - - retPath = (wstring) (retPath.c_str () + 4); - } - - return retPath; -} - -void LoadSettingsAndCheckModified (HWND hwndDlg, BOOL bOnlyCheckModified, BOOL* pbSettingsModified, BOOL* pbHistoryModified) -{ - char langid[6] = {0}; - if (!bOnlyCheckModified) - EnableHwEncryption ((ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? FALSE : TRUE); - - WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE; - - if (!bOnlyCheckModified) - LoadSysEncSettings (); - - if (!bOnlyCheckModified && LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) != 0) - bInPlaceEncNonSysPending = TRUE; - - // If the config file has already been loaded during this session - if (ConfigBuffer != NULL) - { - free (ConfigBuffer); - ConfigBuffer = NULL; - } - - // Options - ConfigReadCompareInt ("OpenExplorerWindowAfterMount", FALSE, &bExplore, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("UseDifferentTrayIconIfVolumesMounted", TRUE, &bUseDifferentTrayIconIfVolMounted, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("SaveVolumeHistory", FALSE, &bHistory, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("CachePasswords", FALSE, &bCacheInDriverDefault, bOnlyCheckModified, pbSettingsModified); - if (!bOnlyCheckModified) - bCacheInDriver = bCacheInDriverDefault; - - ConfigReadCompareInt ("CachePasswordDuringMultipleMount", FALSE, &bCacheDuringMultipleMount, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("WipePasswordCacheOnExit", FALSE, &bWipeCacheOnExit, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("WipeCacheOnAutoDismount", TRUE, &bWipeCacheOnAutoDismount, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("IncludePimInCache", FALSE, &bIncludePimInCache, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("TryEmptyPasswordWhenKeyfileUsed",FALSE, &bTryEmptyPasswordWhenKeyfileUsed, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("StartOnLogon", FALSE, &bStartOnLogon, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("MountDevicesOnLogon", FALSE, &bMountDevicesOnLogon, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("MountFavoritesOnLogon", FALSE, &bMountFavoritesOnLogon, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("EnableBackgroundTask", TRUE, &bEnableBkgTask, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("CloseBackgroundTaskOnNoVolumes", FALSE, &bCloseBkgTaskWhenNoVolumes, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("DismountOnLogOff", !(IsServerOS() && IsAdmin()), &bDismountOnLogOff, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("DismountOnSessionLocked", FALSE, &bDismountOnSessionLocked, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("DismountOnPowerSaving", FALSE, &bDismountOnPowerSaving, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("DismountOnScreenSaver", FALSE, &bDismountOnScreenSaver, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("ForceAutoDismount", TRUE, &bForceAutoDismount, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("MaxVolumeIdleTime", -60, &MaxVolumeIdleTime, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("HiddenSectorDetectionStatus", 0, &HiddenSectorDetectionStatus, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("UseKeyfiles", FALSE, &defaultKeyFilesParam.EnableKeyFiles, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("PreserveTimestamps", TRUE, &defaultMountOptions.PreserveTimestamp, bOnlyCheckModified, pbSettingsModified); - if (!bOnlyCheckModified) - bPreserveTimestamp = defaultMountOptions.PreserveTimestamp; - - ConfigReadCompareInt ("ShowDisconnectedNetworkDrives", FALSE, &bShowDisconnectedNetworkDrives, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("HideWaitingDialog", FALSE, &bHideWaitingDialog, bOnlyCheckModified, pbSettingsModified); - - ConfigReadCompareInt ("MountVolumesRemovable", FALSE, &defaultMountOptions.Removable, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("MountVolumesReadOnly", FALSE, &defaultMountOptions.ReadOnly, bOnlyCheckModified, pbSettingsModified); - - if (!bOnlyCheckModified) - { - defaultMountOptions.ProtectHiddenVolume = FALSE; - defaultMountOptions.ProtectedHidVolPkcs5Prf = 0; - defaultMountOptions.ProtectedHidVolPim = 0; - defaultMountOptions.PartitionInInactiveSysEncScope = FALSE; - defaultMountOptions.RecoveryMode = FALSE; - defaultMountOptions.UseBackupHeader = FALSE; - - mountOptions = defaultMountOptions; - } - - ConfigReadCompareInt ("CloseSecurityTokenSessionsAfterMount", 0, &CloseSecurityTokenSessionsAfterMount, bOnlyCheckModified, pbSettingsModified); - - if (IsHiddenOSRunning()) - ConfigReadCompareInt ("HiddenSystemLeakProtNotifStatus", TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_NONE, &HiddenSysLeakProtectionNotificationStatus, bOnlyCheckModified, pbSettingsModified); - - // Drive letter - command line arg overrides registry - if (!bOnlyCheckModified && bHistory && szDriveLetter[0] == 0) - { - char szTmp[3] = {0}; - ConfigReadString ("LastSelectedDrive", "", szTmp, sizeof (szTmp)); - MultiByteToWideChar (CP_UTF8, 0, szTmp, -1, szDriveLetter, ARRAYSIZE (szDriveLetter)); - } - if (bHistory && pbSettingsModified) - { - // only check for last drive modification if history enabled - char szTmp[32] = {0}; - LPARAM lLetter; - lLetter = GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST)); - if (LOWORD (lLetter) != 0xffff) - StringCbPrintfA (szTmp, sizeof(szTmp), "%lc:", (wchar_t) HIWORD (lLetter)); - - ConfigReadCompareString ("LastSelectedDrive", "", szTmp, sizeof (szTmp), bOnlyCheckModified, pbSettingsModified); - } - - { - char szTmp[MAX_PATH]; - WideCharToMultiByte (CP_UTF8, 0, SecurityTokenLibraryPath, -1, szTmp, MAX_PATH, NULL, NULL); - ConfigReadCompareString ("SecurityTokenLibrary", "", szTmp, sizeof (szTmp) - 1, bOnlyCheckModified, pbSettingsModified); - MultiByteToWideChar (CP_UTF8, 0, szTmp, -1, SecurityTokenLibraryPath, ARRAYSIZE (SecurityTokenLibraryPath)); - if (!bOnlyCheckModified && SecurityTokenLibraryPath[0]) - { - InitSecurityTokenLibrary(hwndDlg); - } - } - - // Hotkeys - ConfigReadCompareInt ("PlaySoundOnHotkeyMountDismount", TRUE, &bPlaySoundOnSuccessfulHkDismount, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("DisplayMsgBoxOnHotkeyDismount", TRUE, &bDisplayBalloonOnSuccessfulHkDismount, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyModAutoMountDevices", 0, (int*) &Hotkeys [HK_AUTOMOUNT_DEVICES].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyCodeAutoMountDevices", 0, (int*) &Hotkeys [HK_AUTOMOUNT_DEVICES].vKeyCode, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyModDismountAll", 0, (int*) &Hotkeys [HK_DISMOUNT_ALL].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyCodeDismountAll", 0, (int*) &Hotkeys [HK_DISMOUNT_ALL].vKeyCode, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyModWipeCache", 0, (int*) &Hotkeys [HK_WIPE_CACHE].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyCodeWipeCache", 0, (int*) &Hotkeys [HK_WIPE_CACHE].vKeyCode, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyModDismountAllWipe", 0, (int*) &Hotkeys [HK_DISMOUNT_ALL_AND_WIPE].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyCodeDismountAllWipe", 0, (int*) &Hotkeys [HK_DISMOUNT_ALL_AND_WIPE].vKeyCode, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyModForceDismountAllWipe", 0, (int*) &Hotkeys [HK_FORCE_DISMOUNT_ALL_AND_WIPE].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyCodeForceDismountAllWipe", 0, (int*) &Hotkeys [HK_FORCE_DISMOUNT_ALL_AND_WIPE].vKeyCode, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyModForceDismountAllWipeExit", 0, (int*) &Hotkeys [HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyCodeForceDismountAllWipeExit", 0, (int*) &Hotkeys [HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT].vKeyCode, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyModMountFavoriteVolumes", 0, (int*) &Hotkeys [HK_MOUNT_FAVORITE_VOLUMES].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyCodeMountFavoriteVolumes", 0, (int*) &Hotkeys [HK_MOUNT_FAVORITE_VOLUMES].vKeyCode, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyModShowHideMainWindow", 0, (int*) &Hotkeys [HK_SHOW_HIDE_MAIN_WINDOW].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyCodeShowHideMainWindow", 0, (int*) &Hotkeys [HK_SHOW_HIDE_MAIN_WINDOW].vKeyCode, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyModCloseSecurityTokenSessions", 0, (int*) &Hotkeys [HK_CLOSE_SECURITY_TOKEN_SESSIONS].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("HotkeyCodeCloseSecurityTokenSessions", 0, (int*) &Hotkeys [HK_CLOSE_SECURITY_TOKEN_SESSIONS].vKeyCode, bOnlyCheckModified, pbSettingsModified); - - // History - if (bHistoryCmdLine != TRUE) - { - LoadCombo (GetDlgItem (MainDlg, IDC_VOLUME), bHistory, bOnlyCheckModified, pbHistoryModified); - if (!bOnlyCheckModified && CmdLineVolumeSpecified) - SetWindowText (GetDlgItem (MainDlg, IDC_VOLUME), szFileName); - } - - // Mount Options - ConfigReadCompareInt ("DefaultPRF", 0, &DefaultVolumePkcs5, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("DefaultTrueCryptMode", FALSE, &DefaultVolumeTrueCryptMode, bOnlyCheckModified, pbSettingsModified); - - if (bOnlyCheckModified) - { - if (!IsNonInstallMode ()) - { - ConfigReadString ("Language", "", langid, sizeof (langid)); - // when installed, if no preferred language set by user, English is set default - // - if (langid [0] == 0) - StringCbCopyA (langid, sizeof(langid), "en"); - - if (pbSettingsModified && strcmp (langid, GetPreferredLangId ())) - *pbSettingsModified = TRUE; - } - else - { - StringCbCopyA (langid, sizeof(langid), GetPreferredLangId ()); - ConfigReadCompareString ("Language", "", langid, sizeof (langid), TRUE, pbSettingsModified); - } - } - - if (DefaultVolumePkcs5 < 0 || DefaultVolumePkcs5 > LAST_PRF_ID) - DefaultVolumePkcs5 = 0; - if (DefaultVolumeTrueCryptMode != TRUE && DefaultVolumeTrueCryptMode != FALSE) - DefaultVolumeTrueCryptMode = FALSE; - -} - -void LoadSettings ( HWND hwndDlg ) -{ - LoadSettingsAndCheckModified (hwndDlg, FALSE, NULL, NULL); -} - -void SaveSettings (HWND hwndDlg) -{ - WaitCursor (); - - // Check first if modifications ocurred before writing to the settings and history files - // This avoids leaking information about VeraCrypt usage when user only mount volumes without changing setttings or history - BOOL bSettingsChanged = FALSE; - BOOL bHistoryChanged = FALSE; - - LoadSettingsAndCheckModified (hwndDlg, TRUE, &bSettingsChanged, &bHistoryChanged); - - if (bSettingsChanged) - { - char szTmp[32] = {0}; - LPARAM lLetter; - - // Options - ConfigWriteBegin (); - - ConfigWriteInt ("OpenExplorerWindowAfterMount", bExplore); - ConfigWriteInt ("UseDifferentTrayIconIfVolumesMounted", bUseDifferentTrayIconIfVolMounted); - ConfigWriteInt ("SaveVolumeHistory", bHistory); - - ConfigWriteInt ("CachePasswords", bCacheInDriverDefault); - ConfigWriteInt ("CachePasswordDuringMultipleMount", bCacheDuringMultipleMount); - ConfigWriteInt ("WipePasswordCacheOnExit", bWipeCacheOnExit); - ConfigWriteInt ("WipeCacheOnAutoDismount", bWipeCacheOnAutoDismount); - - ConfigWriteInt ("IncludePimInCache", bIncludePimInCache); - - ConfigWriteInt ("TryEmptyPasswordWhenKeyfileUsed", bTryEmptyPasswordWhenKeyfileUsed); - - ConfigWriteInt ("StartOnLogon", bStartOnLogon); - ConfigWriteInt ("MountDevicesOnLogon", bMountDevicesOnLogon); - ConfigWriteInt ("MountFavoritesOnLogon", bMountFavoritesOnLogon); - - ConfigWriteInt ("MountVolumesReadOnly", defaultMountOptions.ReadOnly); - ConfigWriteInt ("MountVolumesRemovable", defaultMountOptions.Removable); - ConfigWriteInt ("PreserveTimestamps", defaultMountOptions.PreserveTimestamp); - ConfigWriteInt ("ShowDisconnectedNetworkDrives",bShowDisconnectedNetworkDrives); - ConfigWriteInt ("HideWaitingDialog", bHideWaitingDialog); - - ConfigWriteInt ("EnableBackgroundTask", bEnableBkgTask); - ConfigWriteInt ("CloseBackgroundTaskOnNoVolumes", bCloseBkgTaskWhenNoVolumes); - - ConfigWriteInt ("DismountOnLogOff", bDismountOnLogOff); - ConfigWriteInt ("DismountOnSessionLocked", bDismountOnSessionLocked); - ConfigWriteInt ("DismountOnPowerSaving", bDismountOnPowerSaving); - ConfigWriteInt ("DismountOnScreenSaver", bDismountOnScreenSaver); - ConfigWriteInt ("ForceAutoDismount", bForceAutoDismount); - ConfigWriteInt ("MaxVolumeIdleTime", MaxVolumeIdleTime); - - ConfigWriteInt ("HiddenSectorDetectionStatus", HiddenSectorDetectionStatus); - - ConfigWriteInt ("UseKeyfiles", defaultKeyFilesParam.EnableKeyFiles); - - if (IsHiddenOSRunning()) - ConfigWriteInt ("HiddenSystemLeakProtNotifStatus", HiddenSysLeakProtectionNotificationStatus); - - // save last selected drive only when history enabled - if (bHistory) - { - // Drive Letter - lLetter = GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST)); - if (LOWORD (lLetter) != 0xffff) - StringCbPrintfA (szTmp, sizeof(szTmp), "%lc:", (wchar_t) HIWORD (lLetter)); - ConfigWriteString ("LastSelectedDrive", szTmp); - } - - ConfigWriteInt ("CloseSecurityTokenSessionsAfterMount", CloseSecurityTokenSessionsAfterMount); - - // Hotkeys - ConfigWriteInt ("HotkeyModAutoMountDevices", Hotkeys[HK_AUTOMOUNT_DEVICES].vKeyModifiers); - ConfigWriteInt ("HotkeyCodeAutoMountDevices", Hotkeys[HK_AUTOMOUNT_DEVICES].vKeyCode); - ConfigWriteInt ("HotkeyModDismountAll", Hotkeys[HK_DISMOUNT_ALL].vKeyModifiers); - ConfigWriteInt ("HotkeyCodeDismountAll", Hotkeys[HK_DISMOUNT_ALL].vKeyCode); - ConfigWriteInt ("HotkeyModWipeCache", Hotkeys[HK_WIPE_CACHE].vKeyModifiers); - ConfigWriteInt ("HotkeyCodeWipeCache", Hotkeys[HK_WIPE_CACHE].vKeyCode); - ConfigWriteInt ("HotkeyModDismountAllWipe", Hotkeys[HK_DISMOUNT_ALL_AND_WIPE].vKeyModifiers); - ConfigWriteInt ("HotkeyCodeDismountAllWipe", Hotkeys[HK_DISMOUNT_ALL_AND_WIPE].vKeyCode); - ConfigWriteInt ("HotkeyModForceDismountAllWipe", Hotkeys[HK_FORCE_DISMOUNT_ALL_AND_WIPE].vKeyModifiers); - ConfigWriteInt ("HotkeyCodeForceDismountAllWipe", Hotkeys[HK_FORCE_DISMOUNT_ALL_AND_WIPE].vKeyCode); - ConfigWriteInt ("HotkeyModForceDismountAllWipeExit", Hotkeys[HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT].vKeyModifiers); - ConfigWriteInt ("HotkeyCodeForceDismountAllWipeExit", Hotkeys[HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT].vKeyCode); - ConfigWriteInt ("HotkeyModMountFavoriteVolumes", Hotkeys[HK_MOUNT_FAVORITE_VOLUMES].vKeyModifiers); - ConfigWriteInt ("HotkeyCodeMountFavoriteVolumes", Hotkeys[HK_MOUNT_FAVORITE_VOLUMES].vKeyCode); - ConfigWriteInt ("HotkeyModShowHideMainWindow", Hotkeys[HK_SHOW_HIDE_MAIN_WINDOW].vKeyModifiers); - ConfigWriteInt ("HotkeyCodeShowHideMainWindow", Hotkeys[HK_SHOW_HIDE_MAIN_WINDOW].vKeyCode); - ConfigWriteInt ("HotkeyModCloseSecurityTokenSessions", Hotkeys[HK_CLOSE_SECURITY_TOKEN_SESSIONS].vKeyModifiers); - ConfigWriteInt ("HotkeyCodeCloseSecurityTokenSessions", Hotkeys[HK_CLOSE_SECURITY_TOKEN_SESSIONS].vKeyCode); - ConfigWriteInt ("PlaySoundOnHotkeyMountDismount", bPlaySoundOnSuccessfulHkDismount); - ConfigWriteInt ("DisplayMsgBoxOnHotkeyDismount", bDisplayBalloonOnSuccessfulHkDismount); - - // Language - ConfigWriteString ("Language", GetPreferredLangId ()); - - // PKCS#11 Library Path - ConfigWriteStringW ("SecurityTokenLibrary", SecurityTokenLibraryPath[0] ? SecurityTokenLibraryPath : L""); - - // Mount Options - ConfigWriteInt ("DefaultPRF", DefaultVolumePkcs5); - ConfigWriteInt ("DefaultTrueCryptMode", DefaultVolumeTrueCryptMode); - - ConfigWriteEnd (hwndDlg); - } - - if (bHistoryChanged) - { - // History - DumpCombo (GetDlgItem (MainDlg, IDC_VOLUME), IsButtonChecked (GetDlgItem (MainDlg, IDC_NO_HISTORY))); - } - - NormalCursor (); -} - -// Returns TRUE if system encryption or decryption had been or is in progress and has not been completed -static BOOL SysEncryptionOrDecryptionRequired (void) -{ - /* If you update this function, revise SysEncryptionOrDecryptionRequired() in Tcformat.c as well. */ - - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - return (SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING - || SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING - || - ( - BootEncStatus.DriveMounted - && - ( - BootEncStatus.ConfiguredEncryptedAreaStart != BootEncStatus.EncryptedAreaStart - || BootEncStatus.ConfiguredEncryptedAreaEnd != BootEncStatus.EncryptedAreaEnd - ) - ) - ); -} - -// Returns TRUE if the system partition/drive is completely encrypted -static BOOL SysDriveOrPartitionFullyEncrypted (BOOL bSilent) -{ - /* If you update this function, revise SysDriveOrPartitionFullyEncrypted() in Tcformat.c as well. */ - - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - if (!bSilent) - e.Show (MainDlg); - } - - return (!BootEncStatus.SetupInProgress - && BootEncStatus.ConfiguredEncryptedAreaEnd != 0 - && BootEncStatus.ConfiguredEncryptedAreaEnd != -1 - && BootEncStatus.ConfiguredEncryptedAreaStart == BootEncStatus.EncryptedAreaStart - && BootEncStatus.ConfiguredEncryptedAreaEnd == BootEncStatus.EncryptedAreaEnd); -} - -// Returns TRUE if the system partition/drive is being filtered by the TrueCrypt driver and the key data -// was successfully decrypted (the device is fully ready to be encrypted or decrypted). Note that this -// function does not examine whether the system device is encrypted or not (or to what extent). -static BOOL SysEncDeviceActive (BOOL bSilent) -{ - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - if (!bSilent) - e.Show (MainDlg); - - return FALSE; - } - - return (BootEncStatus.DriveMounted); -} - -// Returns TRUE if the entire system drive (as opposed to the system partition only) of the currently running OS is (or is to be) encrypted -BOOL WholeSysDriveEncryption (BOOL bSilent) -{ - try - { - BootEncStatus = BootEncObj->GetStatus(); - - if (BootEncStatus.BootDriveLength.QuadPart < 1) // paranoid check - return FALSE; - else - return (BootEncStatus.ConfiguredEncryptedAreaStart == TC_BOOT_LOADER_AREA_SIZE - && BootEncStatus.ConfiguredEncryptedAreaEnd >= BootEncStatus.BootDriveLength.QuadPart - 1); - } - catch (Exception &e) - { - if (!bSilent) - e.Show (MainDlg); - - return FALSE; - } -} - -// Returns the size of the system drive/partition (if encrypted) in bytes -unsigned __int64 GetSysEncDeviceSize (BOOL bSilent) -{ - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - if (!bSilent) - e.Show (MainDlg); - return 1; - } - - if ( BootEncStatus.ConfiguredEncryptedAreaEnd < 0 - || BootEncStatus.ConfiguredEncryptedAreaStart < 0 - || BootEncStatus.ConfiguredEncryptedAreaEnd < BootEncStatus.ConfiguredEncryptedAreaStart - ) - return 1; // we return 1 to avoid devision by zero - else - return ((unsigned __int64)(BootEncStatus.ConfiguredEncryptedAreaEnd - BootEncStatus.ConfiguredEncryptedAreaStart)) + 1; -} - -// Returns the current size of the encrypted area of the system drive/partition in bytes -unsigned __int64 GetSysEncDeviceEncryptedPartSize (BOOL bSilent) -{ - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - if (!bSilent) - e.Show (MainDlg); - return 0; - } - - if ( BootEncStatus.EncryptedAreaEnd < 0 - || BootEncStatus.EncryptedAreaStart < 0 - || BootEncStatus.EncryptedAreaEnd < BootEncStatus.EncryptedAreaStart - ) - return 0; - else - return ((unsigned __int64)(BootEncStatus.EncryptedAreaEnd - BootEncStatus.EncryptedAreaStart)) + 1; -} - - -static void PopulateSysEncContextMenu (HMENU popup, BOOL bToolsOnly) -{ - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - if (!bToolsOnly && !IsHiddenOSRunning()) - { - if (SysEncryptionOrDecryptionRequired ()) - { - if (!BootEncStatus.SetupInProgress) - AppendMenuW (popup, MF_STRING, IDM_SYSENC_RESUME, GetString ("IDM_SYSENC_RESUME")); - - if (SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING) - AppendMenuW (popup, MF_STRING, IDM_PERMANENTLY_DECRYPT_SYS, GetString ("PERMANENTLY_DECRYPT")); - - AppendMenuW (popup, MF_STRING, IDM_ENCRYPT_SYSTEM_DEVICE, GetString ("ENCRYPT")); - AppendMenu (popup, MF_SEPARATOR, 0, L""); - } - } - - AppendMenuW (popup, MF_STRING, IDM_CHANGE_SYS_PASSWORD, GetString ("IDM_CHANGE_SYS_PASSWORD")); - // AppendMenuW (popup, MF_STRING, IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO, GetString ("IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO")); - - AppendMenu (popup, MF_SEPARATOR, 0, L""); - AppendMenuW (popup, MF_STRING, IDM_SYS_ENC_SETTINGS, GetString ("IDM_SYS_ENC_SETTINGS")); - - if (!IsHiddenOSRunning()) - { - AppendMenu (popup, MF_SEPARATOR, 0, L""); - AppendMenuW (popup, MF_STRING, IDM_CREATE_RESCUE_DISK, GetString ("IDM_CREATE_RESCUE_DISK")); - AppendMenuW (popup, MF_STRING, IDM_VERIFY_RESCUE_DISK, GetString ("IDM_VERIFY_RESCUE_DISK")); - AppendMenuW (popup, MF_STRING, IDM_VERIFY_RESCUE_DISK_ISO, GetString ("IDM_VERIFY_RESCUE_DISK_ISO")); - } - - if (!bToolsOnly) - { - if (SysDriveOrPartitionFullyEncrypted (FALSE) && !IsHiddenOSRunning()) - { - AppendMenu (popup, MF_SEPARATOR, 0, L""); - AppendMenuW (popup, MF_STRING, IDM_PERMANENTLY_DECRYPT_SYS, GetString ("PERMANENTLY_DECRYPT")); - } - AppendMenu (popup, MF_SEPARATOR, 0, L""); - AppendMenuW (popup, MF_STRING, IDM_VOLUME_PROPERTIES, GetString ("IDPM_PROPERTIES")); - } -} - - -// WARNING: This function may take a long time to complete. To prevent data corruption, it MUST be called before -// mounting a partition (as a regular volume) that is within key scope of system encryption. -// Returns TRUE if the partition can be mounted as a partition within key scope of inactive system encryption. -// If devicePath is empty, the currently selected partition in the GUI is checked. -BOOL CheckSysEncMountWithoutPBA (HWND hwndDlg, const wchar_t *devicePath, BOOL quiet) -{ - BOOL tmpbDevice; - wchar_t szDevicePath [TC_MAX_PATH+1]; - wchar_t szDiskFile [TC_MAX_PATH+1]; - - if (wcslen (devicePath) < 2) - { - GetVolumePath (MainDlg, szDevicePath, ARRAYSIZE (szDevicePath)); - CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szDevicePath, &tmpbDevice); - - if (!tmpbDevice) - { - if (!quiet) - Warning ("NO_SYSENC_PARTITION_SELECTED", hwndDlg); - - return FALSE; - } - - if (LOWORD (GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST))) != TC_MLIST_ITEM_FREE) - { - if (!quiet) - Warning ("SELECT_FREE_DRIVE", hwndDlg); - - return FALSE; - } - } - else - StringCbCopyW (szDevicePath, sizeof(szDevicePath), devicePath); - - wchar_t *partionPortion = wcsrchr (szDevicePath, L'\\'); - - if (!partionPortion - || !_wcsicmp (partionPortion, L"\\Partition0")) - { - // Only partitions are supported (not whole drives) - if (!quiet) - Warning ("NO_SYSENC_PARTITION_SELECTED", hwndDlg); - - return FALSE; - } - - try - { - BootEncStatus = BootEncObj->GetStatus(); - - if (BootEncStatus.DriveMounted) - { - int retCode = 0; - int driveNo; - wchar_t parentDrivePath [TC_MAX_PATH+1]; - - if (swscanf (szDevicePath, L"\\Device\\Harddisk%d\\Partition", &driveNo) != 1) - { - if (!quiet) - Error ("INVALID_PATH", hwndDlg); - - return FALSE; - } - - StringCbPrintfW (parentDrivePath, - sizeof (parentDrivePath), - L"\\Device\\Harddisk%d\\Partition0", - driveNo); - - WaitCursor (); - - // This is critical (re-mounting a mounted system volume as a normal volume could cause data corruption) - // so we force the slower but reliable method - retCode = IsSystemDevicePath (parentDrivePath, MainDlg, TRUE); - - NormalCursor(); - - if (retCode != 2) - return TRUE; - else - { - // The partition is located on active system drive - - if (!quiet) - Warning ("MOUNT_WITHOUT_PBA_VOL_ON_ACTIVE_SYSENC_DRIVE", hwndDlg); - - return FALSE; - } - } - else - return TRUE; - } - catch (Exception &e) - { - NormalCursor(); - e.Show (hwndDlg); - } - - return FALSE; -} - - -// Returns TRUE if the host drive of the specified partition contains a portion of the TrueCrypt Boot Loader -// and if the drive is not within key scope of active system encryption (e.g. the system drive of the running OS). -// If bPrebootPasswordDlgMode is TRUE, this function returns FALSE (because the check would be redundant). -BOOL TCBootLoaderOnInactiveSysEncDrive (wchar_t *szDevicePath) -{ - try - { - int driveNo; - wchar_t parentDrivePath [TC_MAX_PATH+1]; - - if (bPrebootPasswordDlgMode) - return FALSE; - - - if (swscanf (szDevicePath, L"\\Device\\Harddisk%d\\Partition", &driveNo) != 1) - return FALSE; - - StringCbPrintfW (parentDrivePath, - sizeof (parentDrivePath), - L"\\Device\\Harddisk%d\\Partition0", - driveNo); - - BootEncStatus = BootEncObj->GetStatus(); - - if (BootEncStatus.DriveMounted - && IsSystemDevicePath (parentDrivePath, MainDlg, FALSE) == 2) - { - // The partition is within key scope of active system encryption - return FALSE; - } - - return ((BOOL) BootEncObj->IsBootLoaderOnDrive (parentDrivePath)); - } - catch (...) - { - return FALSE; - } - -} - - -BOOL SelectItem (HWND hTree, wchar_t nLetter) -{ - if (nLetter == 0) - { - // The caller specified an invalid drive letter (typically because it is unknown). - // Find out which drive letter is currently selected in the list and use it. - nLetter = (wchar_t) (HIWORD (GetSelectedLong (hTree))); - } - - int i; - LVITEM item; - - for (i = 0; i < ListView_GetItemCount(hTree); i++) - { - memset(&item, 0, sizeof(LVITEM)); - item.mask = LVIF_PARAM; - item.iItem = i; - - if (ListView_GetItem (hTree, &item) == FALSE) - return FALSE; - else - { - if (HIWORD (item.lParam) == nLetter) - { - memset(&item, 0, sizeof(LVITEM)); - item.state = LVIS_FOCUSED|LVIS_SELECTED; - item.stateMask = LVIS_FOCUSED|LVIS_SELECTED; - item.mask = LVIF_STATE; - item.iItem = i; - SendMessage(hTree, LVM_SETITEMSTATE, i, (LPARAM) &item); - return TRUE; - } - } - } - - return TRUE; -} - - -static void LaunchVolCreationWizard (HWND hwndDlg, const wchar_t *arg) -{ - wchar_t t[TC_MAX_PATH + 1024] = {L'"',0}; - wchar_t *tmp; - - GetModuleFileName (NULL, t+1, ARRAYSIZE(t)-1); - - tmp = wcsrchr (t, L'\\'); - if (tmp) - { - STARTUPINFO si; - PROCESS_INFORMATION pi; - wchar_t formatExeName[64]; - wchar_t* suffix = NULL; - ZeroMemory (&si, sizeof (si)); - - StringCbCopyW (formatExeName, sizeof (formatExeName), L"\\VeraCrypt Format"); - - // check if there is a suffix in VeraCrypt file name - // in order to use the same for "VeraCrypt Format" - suffix = wcsrchr (tmp + 1, L'-'); - if (suffix) - { - StringCbCatW (formatExeName, sizeof (formatExeName), suffix); - StringCbCatW (formatExeName, sizeof (formatExeName), L"\""); - } - else - StringCbCatW (formatExeName, sizeof (formatExeName), L".exe\""); - - *tmp = 0; - StringCbCatW (t, sizeof(t), formatExeName); - - if (!FileExists(t)) - Error ("VOL_CREATION_WIZARD_NOT_FOUND", hwndDlg); // Display a user-friendly error message and advise what to do - - if (wcslen (arg) > 0) - { - StringCbCatW (t, sizeof(t), L" "); - StringCbCatW (t, sizeof(t), arg); - } - - if (!CreateProcess (NULL, (LPWSTR) t, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi)) - { - handleWin32Error (hwndDlg, SRC_POS); - } - else - { - CloseHandle (pi.hProcess); - CloseHandle (pi.hThread); - } - } -} - -static void LaunchVolExpander (HWND hwndDlg) -{ - wchar_t t[TC_MAX_PATH + TC_MAX_PATH] = {L'"',0}; - wchar_t *tmp; - - GetModuleFileName (NULL, t+1, ARRAYSIZE(t)-1); - - tmp = wcsrchr (t, L'\\'); - if (tmp) - { - wchar_t expanderExeName[64]; - wchar_t* suffix = NULL; - - StringCbCopyW (expanderExeName, sizeof (expanderExeName), L"\\VeraCryptExpander"); - - // check if there is a suffix in VeraCrypt file name - // in order to use the same for "VeraCrypt Format" - suffix = wcsrchr (tmp + 1, L'-'); - if (suffix) - { - StringCbCatW (expanderExeName, sizeof (expanderExeName), suffix); - StringCbCatW (expanderExeName, sizeof (expanderExeName), L"\""); - } - else - StringCbCatW (expanderExeName, sizeof (expanderExeName), L".exe\""); - - *tmp = 0; - StringCbCatW (t, sizeof(t), expanderExeName); - - if (!FileExists(t)) - Error ("VOL_EXPANDER_NOT_FOUND", hwndDlg); // Display a user-friendly error message and advise what to do - else if (((int)ShellExecuteW (NULL, (!IsAdmin() && IsUacSupported()) ? L"runas" : L"open", t, NULL, NULL, SW_SHOW)) <= 32) - { - handleWin32Error (hwndDlg, SRC_POS); - } - } -} - - -// Fills drive list -// drive>0 = update only the corresponding drive subitems -void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) -{ - // Remember the top-most visible item - int lastTopMostVisibleItem = ListView_GetTopIndex (hTree); - - wchar_t *szDriveLetters[]= - {L"A:", L"B:", L"C:", L"D:", - L"E:", L"F:", L"G:", L"H:", L"I:", L"J:", L"K:", - L"L:", L"M:", L"N:", L"O:", L"P:", L"Q:", L"R:", - L"S:", L"T:", L"U:", L"V:", L"W:", L"X:", L"Y:", - L"Z:"}; - - DWORD dwResult; - BOOL bResult; - DWORD dwUsedDrives; - MOUNT_LIST_STRUCT driver; - VOLUME_PROPERTIES_STRUCT propSysEnc; - wchar_t sysDriveLetter = 0; - - BOOL bSysEnc = FALSE; - BOOL bWholeSysDriveEncryption = FALSE; - - LVITEM listItem; - int item = 0; - char i; - - try - { - BootEncStatus = BootEncObj->GetStatus(); - if (bSysEnc = BootEncStatus.DriveMounted) - { - BootEncObj->GetVolumeProperties (&propSysEnc); - } - } - catch (...) - { - bSysEnc = FALSE; - } - - ZeroMemory (&driver, sizeof (driver)); - bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &driver, - sizeof (driver), &driver, sizeof (driver), &dwResult, - NULL); - memcpy (&LastKnownMountList, &driver, sizeof (driver)); - - if (bResult == FALSE) - { - KillTimer (MainDlg, TIMER_ID_MAIN); - handleWin32Error (hTree, SRC_POS); - AbortProcessSilent(); - } - - LastKnownLogicalDrives = dwUsedDrives = GetUsedLogicalDrives (); - if (dwUsedDrives == 0) - Warning ("DRIVELETTERS", hwndDlg); - - if(drive == 0) - ListView_DeleteAllItems(hTree); - - if (bSysEnc) - { - bWholeSysDriveEncryption = WholeSysDriveEncryption (TRUE); - - sysDriveLetter = GetSystemDriveLetter (); - } - - /* System drive */ - - if (bWholeSysDriveEncryption) - { - int curDrive = 0; - - if (drive > 0) - { - LVITEM tmp; - memset(&tmp, 0, sizeof(LVITEM)); - tmp.mask = LVIF_PARAM; - tmp.iItem = item; - if (ListView_GetItem (hTree, &tmp)) - curDrive = HIWORD(tmp.lParam); - } - - { - wchar_t szTmp[1024]; - wchar_t szTmpW[1024]; - - memset(&listItem, 0, sizeof(listItem)); - - listItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; - listItem.iImage = 2; - listItem.iItem = item++; - - listItem.pszText = szTmp; - szTmp[0] = L' '; - szTmp[1] = 0; - - listItem.lParam = MAKELONG (TC_MLIST_ITEM_SYS_DRIVE, ENC_SYSDRIVE_PSEUDO_DRIVE_LETTER); - - if(drive == 0) - ListView_InsertItem (hTree, &listItem); - else - ListView_SetItem (hTree, &listItem); - - listItem.mask=LVIF_TEXT; - - // Fully encrypted - if (SysDriveOrPartitionFullyEncrypted (TRUE)) - { - StringCbCopyW (szTmpW, sizeof(szTmpW), GetString ("SYSTEM_DRIVE")); - } - else - { - // Partially encrypted - - if (BootEncStatus.SetupInProgress) - { - // Currently encrypting/decrypting - - if (BootEncStatus.SetupMode != SetupDecryption) - { - StringCbPrintfW (szTmpW, - sizeof szTmpW, - GetString ("SYSTEM_DRIVE_ENCRYPTING"), - (double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0); - } - else - { - StringCbPrintfW (szTmpW, - sizeof szTmpW, - GetString ("SYSTEM_DRIVE_DECRYPTING"), - 100.0 - ((double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0)); - } - } - else - { - StringCbPrintfW (szTmpW, - sizeof szTmpW, - GetString ("SYSTEM_DRIVE_PARTIALLY_ENCRYPTED"), - (double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0); - } - } - - ListSubItemSet (hTree, listItem.iItem, 1, szTmpW); - - GetSizeString (GetSysEncDeviceSize(TRUE), szTmpW, sizeof(szTmpW)); - ListSubItemSet (hTree, listItem.iItem, 2, szTmpW); - - if (propSysEnc.ea >= EAGetFirst() && propSysEnc.ea <= EAGetCount()) - { - EAGetName (szTmp, propSysEnc.ea, 1); - } - else - { - szTmp[0] = L'?'; - szTmp[1] = 0; - } - listItem.iSubItem = 3; - ListView_SetItem (hTree, &listItem); - - ListSubItemSet (hTree, listItem.iItem, 4, GetString (IsHiddenOSRunning() ? "HIDDEN" : "SYSTEM_VOLUME_TYPE_ADJECTIVE")); - } - } - - /* Drive letters */ - - for (i = 0; i < 26; i++) - { - int curDrive = 0; - - BOOL bSysEncPartition = (bSysEnc && !bWholeSysDriveEncryption && sysDriveLetter == *((wchar_t *) szDriveLetters[i])); - - if (drive > 0) - { - LVITEM tmp; - memset(&tmp, 0, sizeof(LVITEM)); - tmp.mask = LVIF_PARAM; - tmp.iItem = item; - if (ListView_GetItem (hTree, &tmp)) - curDrive = HIWORD(tmp.lParam); - } - - if (driver.ulMountedDrives & (1 << i) - || bSysEncPartition) - { - wchar_t szTmp[1024]; - wchar_t szTmpW[1024]; - wchar_t *ws; - - memset(&listItem, 0, sizeof(listItem)); - - listItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; - listItem.iImage = bSysEncPartition ? 2 : 1; - listItem.iItem = item++; - - if (drive > 0 && drive != curDrive) - continue; - - listItem.lParam = MAKELONG ( - bSysEncPartition ? TC_MLIST_ITEM_SYS_PARTITION : TC_MLIST_ITEM_NONSYS_VOL, - i + L'A'); - - listItem.pszText = szDriveLetters[i]; - - if (drive == 0) - ListView_InsertItem (hTree, &listItem); - else - ListView_SetItem (hTree, &listItem); - - listItem.mask=LVIF_TEXT; - listItem.pszText = szTmp; - - if (bSysEncPartition) - { - // Fully encrypted - if (SysDriveOrPartitionFullyEncrypted (TRUE)) - { - StringCbCopyW (szTmpW, sizeof(szTmpW), GetString (IsHiddenOSRunning() ? "HIDDEN_SYSTEM_PARTITION" : "SYSTEM_PARTITION")); - } - else - { - // Partially encrypted - - if (BootEncStatus.SetupInProgress) - { - // Currently encrypting/decrypting - - if (BootEncStatus.SetupMode != SetupDecryption) - { - StringCbPrintfW (szTmpW, - sizeof szTmpW, - GetString ("SYSTEM_PARTITION_ENCRYPTING"), - (double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0); - } - else - { - StringCbPrintfW (szTmpW, - sizeof szTmpW, - GetString ("SYSTEM_PARTITION_DECRYPTING"), - 100.0 - ((double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0)); - } - } - else - { - StringCbPrintfW (szTmpW, - sizeof szTmpW, - GetString ("SYSTEM_PARTITION_PARTIALLY_ENCRYPTED"), - (double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0); - } - } - - ListSubItemSet (hTree, listItem.iItem, 1, szTmpW); - } - else - { - wchar_t *path = driver.wszVolume[i]; - - if (wmemcmp (path, L"\\??\\", 4) == 0) - path += 4; - - listItem.iSubItem = 1; - - // first check label used for mounting. If empty, look for it in favorites. - bool useInExplorer = false; - wstring label = (wchar_t *) driver.wszLabel[i]; - if (label.empty()) - label = GetFavoriteVolumeLabel (path, useInExplorer); - if (!label.empty()) - ListSubItemSet (hTree, listItem.iItem, 1, (wchar_t *) label.c_str()); - else - ListSubItemSet (hTree, listItem.iItem, 1, (wchar_t *) FitPathInGfxWidth (hTree, hUserFont, ListView_GetColumnWidth (hTree, 1) - GetTextGfxWidth (hTree, L"___", hUserFont), path).c_str()); - } - - GetSizeString (bSysEncPartition ? GetSysEncDeviceSize(TRUE) : driver.diskLength[i], szTmpW, sizeof(szTmpW)); - ListSubItemSet (hTree, listItem.iItem, 2, szTmpW); - - EAGetName (szTmp, bSysEncPartition ? propSysEnc.ea : driver.ea[i], 1); - listItem.iSubItem = 3; - ListView_SetItem (hTree, &listItem); - - if (bSysEncPartition) - { - ws = GetString (IsHiddenOSRunning() ? "HIDDEN" : "SYSTEM_VOLUME_TYPE_ADJECTIVE"); - VolumeNotificationsList.bHidVolDamagePrevReported[i] = FALSE; - ListSubItemSet (hTree, listItem.iItem, 4, ws); - } - else - { - switch (driver.volumeType[i]) - { - case PROP_VOL_TYPE_NORMAL: - ws = GetString ("NORMAL"); - break; - case PROP_VOL_TYPE_HIDDEN: - ws = GetString ("HIDDEN"); - break; - case PROP_VOL_TYPE_OUTER: - ws = GetString ("OUTER"); // Normal/outer volume (hidden volume protected) - break; - case PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED: - ws = GetString ("OUTER_VOL_WRITE_PREVENTED"); // Normal/outer volume (hidden volume protected AND write denied) - break; - default: - ws = L"?"; - } - - if (driver.truecryptMode[i]) - { - StringCbPrintfW (szTmpW, sizeof(szTmpW), L"TrueCrypt-%s", ws); - ListSubItemSet (hTree, listItem.iItem, 4, szTmpW); - } - else - ListSubItemSet (hTree, listItem.iItem, 4, ws); - - if (driver.volumeType[i] == PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED) // Normal/outer volume (hidden volume protected AND write denied) - { - if (!VolumeNotificationsList.bHidVolDamagePrevReported[i]) - { - wchar_t szTmp[4096]; - - VolumeNotificationsList.bHidVolDamagePrevReported[i] = TRUE; - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), i+L'A'); - SetForegroundWindow (GetParent(hTree)); - MessageBoxW (GetParent(hTree), szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); - } - } - else - { - VolumeNotificationsList.bHidVolDamagePrevReported[i] = FALSE; - } - } - } - else - { - VolumeNotificationsList.bHidVolDamagePrevReported[i] = FALSE; - - if (!(dwUsedDrives & 1 << i)) - { - if(drive > 0 && drive != HIWORD (GetSelectedLong (hTree))) - { - item++; - continue; - } - - memset(&listItem,0,sizeof(listItem)); - - listItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; - listItem.iImage = 0; - listItem.iItem = item++; - listItem.pszText = szDriveLetters[i]; - listItem.lParam = MAKELONG (TC_MLIST_ITEM_FREE, i + 'A'); - - if(drive == 0) - ListView_InsertItem (hTree, &listItem); - else - ListView_SetItem (hTree, &listItem); - - listItem.mask=LVIF_TEXT; - listItem.pszText = L""; - listItem.iSubItem = 1; - ListView_SetItem (hTree, &listItem); - listItem.iSubItem = 2; - ListView_SetItem (hTree, &listItem); - listItem.iSubItem = 3; - ListView_SetItem (hTree, &listItem); - listItem.iSubItem = 4; - ListView_SetItem (hTree, &listItem); - - } - } - } - - // Restore the original scroll position (the topmost item that was visible when we were called) and the - // last selected item. - SetListScrollHPos (hTree, lastTopMostVisibleItem); - SelectItem (hTree, 0); -} - -static void PasswordChangeEnable (HWND hwndDlg, int button, int passwordId, BOOL keyFilesEnabled, - int newPasswordId, int newVerifyId, BOOL newKeyFilesEnabled) -{ - char password[MAX_PASSWORD + 1]; - char newPassword[MAX_PASSWORD + 1]; - char newVerify[MAX_PASSWORD + 1]; - wchar_t tmp[MAX_PASSWORD + 1]; - BOOL bEnable = TRUE; - int passwordUtf8Len, newPasswordUtf8Len, newVerifyUtf8Len; - - GetWindowText (GetDlgItem (hwndDlg, passwordId), tmp, ARRAYSIZE (tmp)); - passwordUtf8Len = WideCharToMultiByte (CP_UTF8, 0, tmp, -1, password, sizeof (password), NULL, NULL); - - if (pwdChangeDlgMode == PCDM_CHANGE_PKCS5_PRF) - newKeyFilesEnabled = keyFilesEnabled; - - switch (pwdChangeDlgMode) - { - case PCDM_REMOVE_ALL_KEYFILES_FROM_VOL: - case PCDM_ADD_REMOVE_VOL_KEYFILES: - case PCDM_CHANGE_PKCS5_PRF: - memcpy (newPassword, password, sizeof (newPassword)); - memcpy (newVerify, password, sizeof (newVerify)); - newPasswordUtf8Len = passwordUtf8Len; - newVerifyUtf8Len = passwordUtf8Len; - break; - - default: - GetWindowText (GetDlgItem (hwndDlg, newPasswordId), tmp, ARRAYSIZE (tmp)); - newPasswordUtf8Len = WideCharToMultiByte (CP_UTF8, 0, tmp, -1, newPassword, sizeof (newPassword), NULL, NULL); - GetWindowText (GetDlgItem (hwndDlg, newVerifyId), tmp, ARRAYSIZE (tmp)); - newVerifyUtf8Len = WideCharToMultiByte (CP_UTF8, 0, tmp, -1, newVerify, sizeof (newVerify), NULL, NULL); - - } - - if (passwordUtf8Len <= 0 || (!keyFilesEnabled && ((passwordUtf8Len - 1) < MIN_PASSWORD))) - bEnable = FALSE; - else if (strcmp (newPassword, newVerify) != 0) - bEnable = FALSE; - else if ((newPasswordUtf8Len <= 0) || (!newKeyFilesEnabled && ((newPasswordUtf8Len - 1) < MIN_PASSWORD))) - bEnable = FALSE; - - burn (password, sizeof (password)); - burn (newPassword, sizeof (newPassword)); - burn (newVerify, sizeof (newVerify)); - burn (tmp, sizeof (tmp)); - - EnableWindow (GetDlgItem (hwndDlg, button), bEnable); -} - -// implementation for support of change password operation in wait dialog mechanism - -typedef struct -{ - Password *oldPassword; - int old_pkcs5; - int old_pim; - Password *newPassword; - int pkcs5; - int pim; - int wipePassCount; - BOOL truecryptMode; - int* pnStatus; -} ChangePwdThreadParam; - -void CALLBACK ChangePwdWaitThreadProc(void* pArg, HWND hwndDlg) -{ - ChangePwdThreadParam* pThreadParam = (ChangePwdThreadParam*) pArg; - - if (bSysEncPwdChangeDlgMode) - { - // System - - try - { - VOLUME_PROPERTIES_STRUCT properties; - BootEncObj->GetVolumeProperties(&properties); - pThreadParam->old_pkcs5 = properties.pkcs5; - } - catch(...) - {} - - pThreadParam->pkcs5 = 0; // PKCS-5 PRF unchanged (currently we can't change PRF of system encryption) - - try - { - *pThreadParam->pnStatus = BootEncObj->ChangePassword (pThreadParam->oldPassword, pThreadParam->old_pkcs5, pThreadParam->old_pim, pThreadParam->newPassword, pThreadParam->pkcs5, pThreadParam->pim, pThreadParam->wipePassCount, hwndDlg); - } - catch (Exception &e) - { - e.Show (hwndDlg); - *(pThreadParam->pnStatus) = ERR_OS_ERROR; - } - } - else - { - // Non-system - - *pThreadParam->pnStatus = ChangePwd (szFileName, pThreadParam->oldPassword, pThreadParam->old_pkcs5, pThreadParam->old_pim, pThreadParam->truecryptMode, pThreadParam->newPassword, pThreadParam->pkcs5, pThreadParam->pim, pThreadParam->wipePassCount, hwndDlg); - - if (*pThreadParam->pnStatus == ERR_OS_ERROR - && GetLastError () == ERROR_ACCESS_DENIED - && IsUacSupported () - && IsVolumeDeviceHosted (szFileName)) - { - *pThreadParam->pnStatus = UacChangePwd (szFileName, pThreadParam->oldPassword, pThreadParam->old_pkcs5, pThreadParam->old_pim, pThreadParam->truecryptMode, pThreadParam->newPassword, pThreadParam->pkcs5, pThreadParam->pim, pThreadParam->wipePassCount, hwndDlg); - } - } -} - -// implementation for support of backup header operation in wait dialog mechanism - -typedef struct -{ - BOOL bRequireConfirmation; - wchar_t *lpszVolume; - size_t cchVolume; - int* iResult; -} BackupHeaderThreadParam; - -void CALLBACK BackupHeaderWaitThreadProc(void* pArg, HWND hwndDlg) -{ - BackupHeaderThreadParam* pThreadParam = (BackupHeaderThreadParam*) pArg; - - if (TranslateVolumeID (hwndDlg, pThreadParam->lpszVolume, pThreadParam->cchVolume)) - { - if (!IsAdmin () && IsUacSupported () && IsVolumeDeviceHosted (pThreadParam->lpszVolume)) - *(pThreadParam->iResult) = UacBackupVolumeHeader (hwndDlg, pThreadParam->bRequireConfirmation, pThreadParam->lpszVolume); - else - *(pThreadParam->iResult) = BackupVolumeHeader (hwndDlg, pThreadParam->bRequireConfirmation, pThreadParam->lpszVolume); - } - else - *(pThreadParam->iResult) = ERR_OS_ERROR; -} - -// implementation for support of restoring header operation in wait dialog mechanism - -typedef struct -{ - wchar_t *lpszVolume; - size_t cchVolume; - int* iResult; -} RestoreHeaderThreadParam; - -void CALLBACK RestoreHeaderWaitThreadProc(void* pArg, HWND hwndDlg) -{ - RestoreHeaderThreadParam* pThreadParam = (RestoreHeaderThreadParam*) pArg; - - if (TranslateVolumeID (hwndDlg, pThreadParam->lpszVolume, pThreadParam->cchVolume)) - { - if (!IsAdmin () && IsUacSupported () && IsVolumeDeviceHosted (pThreadParam->lpszVolume)) - *(pThreadParam->iResult) = UacRestoreVolumeHeader (hwndDlg, pThreadParam->lpszVolume); - else - *(pThreadParam->iResult) = RestoreVolumeHeader (hwndDlg, pThreadParam->lpszVolume); - } - else - *(pThreadParam->iResult) = ERR_OS_ERROR; -} - -/* Except in response to the WM_INITDIALOG message, the dialog box procedure - should return nonzero if it processes the message, and zero if it does - not. - see DialogProc */ -BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - static KeyFilesDlgParam newKeyFilesParam; - static BOOL PimValueChangedWarning = FALSE; - static int* NewPimValuePtr = NULL; - - WORD lw = LOWORD (wParam); - WORD hw = HIWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - LPARAM nIndex, nSelectedIndex = 0; - HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_OLD_PRF_ID); - int i; - WipeAlgorithmId headerWipeMode = TC_WIPE_3_DOD_5220; - int EffectiveVolumePkcs5 = CmdVolumePkcs5; - BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; - int EffectiveVolumePim = CmdVolumePim; - - /* Priority is given to command line parameters - * Default values used only when nothing specified in command line - */ - if (EffectiveVolumePkcs5 == 0) - EffectiveVolumePkcs5 = DefaultVolumePkcs5; - if (!EffectiveVolumeTrueCryptMode) - EffectiveVolumeTrueCryptMode = DefaultVolumeTrueCryptMode; - - NewPimValuePtr = (int*) lParam; - - PimValueChangedWarning = FALSE; - - ZeroMemory (&newKeyFilesParam, sizeof (newKeyFilesParam)); - if (NewPimValuePtr) - { - /* we are in the case of a volume. Store its name to use it in the key file dialog - * this will help avoid using the current container file as a key file - */ - StringCbCopyW (newKeyFilesParam.VolumeFileName, sizeof (newKeyFilesParam.VolumeFileName), szFileName); - } - - SetWindowTextW (hwndDlg, GetString ("IDD_PASSWORDCHANGE_DLG")); - LocalizeDialog (hwndDlg, "IDD_PASSWORDCHANGE_DLG"); - - SendMessage (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_VERIFY), EM_LIMITTEXT, MAX_PASSWORD, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_OLD_PIM), EM_LIMITTEXT, MAX_PIM, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, MAX_PIM, 0); - EnableWindow (GetDlgItem (hwndDlg, IDOK), FALSE); - - SetCheckBox (hwndDlg, IDC_ENABLE_KEYFILES, KeyFilesEnable); - EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEW_KEYFILES), TRUE); - - /* Add PRF algorithm list for current password */ - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - - nIndex = SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); - - for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) - { - nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); - if (i == EffectiveVolumePkcs5) - { - nSelectedIndex = nIndex; - } - } - - SendMessage (hComboBox, CB_SETCURSEL, nSelectedIndex, 0); - - /* check TrueCrypt Mode if it was set as default*/ - SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, EffectiveVolumeTrueCryptMode); - - /* set default PIM if set in the command line*/ - if (EffectiveVolumePim > 0) - { - SetCheckBox (hwndDlg, IDC_PIM_ENABLE, TRUE); - ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDT_OLD_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_OLD_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_OLD_PIM_HELP), SW_SHOW); - SetPim (hwndDlg, IDC_OLD_PIM, EffectiveVolumePim); - } - - /* Add PRF algorithm list for new password */ - hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - - nIndex = SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("UNCHANGED")); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); - - for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) - { - if (!HashIsDeprecated (i)) - { - nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); - } - } - - SendMessage (hComboBox, CB_SETCURSEL, 0, 0); - - PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), FALSE, FALSE, TRUE); - SelectAlgo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), (int *) &headerWipeMode); - - switch (pwdChangeDlgMode) - { - case PCDM_CHANGE_PKCS5_PRF: - SetWindowTextW (hwndDlg, GetString ("IDD_PCDM_CHANGE_PKCS5_PRF")); - LocalizeDialog (hwndDlg, "IDD_PCDM_CHANGE_PKCS5_PRF"); - EnableWindow (GetDlgItem (hwndDlg, IDC_PASSWORD), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_VERIFY), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEW_PIM_ENABLE), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_ENABLE_NEW_KEYFILES), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_NEW), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEW_KEYFILES), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_NEW_PASSWORD), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_CONFIRM_PASSWORD), FALSE); - break; - - case PCDM_ADD_REMOVE_VOL_KEYFILES: - SetWindowTextW (hwndDlg, GetString ("IDD_PCDM_ADD_REMOVE_VOL_KEYFILES")); - LocalizeDialog (hwndDlg, "IDD_PCDM_ADD_REMOVE_VOL_KEYFILES"); - newKeyFilesParam.EnableKeyFiles = TRUE; - EnableWindow (GetDlgItem (hwndDlg, IDC_PASSWORD), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_VERIFY), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEW_PIM_ENABLE), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_NEW), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_NEW_PASSWORD), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_CONFIRM_PASSWORD), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_NEW_PKCS5_PRF), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), FALSE); - break; - - case PCDM_REMOVE_ALL_KEYFILES_FROM_VOL: - newKeyFilesParam.EnableKeyFiles = FALSE; - SetWindowTextW (hwndDlg, GetString ("IDD_PCDM_REMOVE_ALL_KEYFILES_FROM_VOL")); - LocalizeDialog (hwndDlg, "IDD_PCDM_REMOVE_ALL_KEYFILES_FROM_VOL"); - KeyFilesEnable = TRUE; - SetCheckBox (hwndDlg, IDC_ENABLE_KEYFILES, TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_ENABLE_KEYFILES), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PASSWORD), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_VERIFY), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEW_PIM_ENABLE), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_ENABLE_NEW_KEYFILES), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_NEW), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEW_KEYFILES), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_NEW_PASSWORD), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_CONFIRM_PASSWORD), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_NEW_PKCS5_PRF), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), FALSE); - break; - - case PCDM_CHANGE_PASSWORD: - default: - // NOP - break; - }; - - if (bSysEncPwdChangeDlgMode) - { - /* No support for changing the password of TrueCrypt system partition */ - SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE); - - ToBootPwdField (hwndDlg, IDC_PASSWORD); - ToBootPwdField (hwndDlg, IDC_VERIFY); - ToBootPwdField (hwndDlg, IDC_OLD_PASSWORD); - - if ((DWORD) GetKeyboardLayout (NULL) != 0x00000409 && (DWORD) GetKeyboardLayout (NULL) != 0x04090409) - { - DWORD keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); - - if (keybLayout != 0x00000409 && keybLayout != 0x04090409) - { - Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 0; - } - - bKeyboardLayoutChanged = TRUE; - } - - - /* for system encryption, we can't change the PRF */ - EnableWindow (GetDlgItem (hwndDlg, IDT_PKCS5_PRF), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDT_NEW_PKCS5_PRF), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PKCS5_OLD_PRF_ID), FALSE); - - if (SetTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0) - { - Error ("CANNOT_SET_TIMER", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 0; - } - - newKeyFilesParam.EnableKeyFiles = FALSE; - KeyFilesEnable = FALSE; - SetCheckBox (hwndDlg, IDC_ENABLE_KEYFILES, FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_ENABLE_KEYFILES), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_ENABLE_NEW_KEYFILES), FALSE); - } - - CheckCapsLock (hwndDlg, FALSE); - - return 0; - } - - case WM_TIMER: - switch (wParam) - { - case TIMER_ID_KEYB_LAYOUT_GUARD: - if (bSysEncPwdChangeDlgMode) - { - DWORD keybLayout = (DWORD) GetKeyboardLayout (NULL); - - /* Watch the keyboard layout */ - - if (keybLayout != 0x00000409 && keybLayout != 0x04090409) - { - // Keyboard layout is not standard US - - // Attempt to wipe passwords stored in the input field buffers - wchar_t tmp[MAX_PASSWORD+1]; - wmemset (tmp, L'X', MAX_PASSWORD); - tmp [MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), tmp); - - SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), L""); - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), L""); - SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), L""); - - keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); - - if (keybLayout != 0x00000409 && keybLayout != 0x04090409) - { - KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); - Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - bKeyboardLayoutChanged = TRUE; - - wchar_t szTmp [4096]; - StringCbCopyW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_CHANGE_PREVENTED")); - StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); - StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION")); - MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); - } - - - /* Watch the right Alt key (which is used to enter various characters on non-US keyboards) */ - - if (bKeyboardLayoutChanged && !bKeybLayoutAltKeyWarningShown) - { - if (GetAsyncKeyState (VK_RMENU) < 0) - { - bKeybLayoutAltKeyWarningShown = TRUE; - - wchar_t szTmp [4096]; - StringCbCopyW (szTmp, sizeof(szTmp), GetString ("ALT_KEY_CHARS_NOT_FOR_SYS_ENCRYPTION")); - StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); - StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION")); - MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TOPMOST); - } - } - } - return 1; - } - return 0; - - case WM_CTLCOLORSTATIC: - { - if (PimValueChangedWarning && ((HWND)lParam == GetDlgItem(hwndDlg, IDC_PIM_HELP)) ) - { - // we're about to draw the static - // set the text colour in (HDC)lParam - SetBkMode((HDC)wParam,TRANSPARENT); - SetTextColor((HDC)wParam, RGB(255,0,0)); - // NOTE: per documentation as pointed out by selbie, GetSolidBrush would leak a GDI handle. - return (BOOL)GetSysColorBrush(COLOR_MENU); - } - } - return 0; - - case WM_COMMAND: - if (lw == IDCANCEL) - { - // Attempt to wipe passwords stored in the input field buffers - wchar_t tmp[MAX_PASSWORD+1]; - wmemset (tmp, L'X', MAX_PASSWORD); - tmp[MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), tmp); - RestoreDefaultKeyFilesParam (); - - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - if (hw == EN_CHANGE) - { - PasswordChangeEnable (hwndDlg, IDOK, - IDC_OLD_PASSWORD, - KeyFilesEnable && FirstKeyFile != NULL, - IDC_PASSWORD, IDC_VERIFY, - newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); - - if ((lw == IDC_OLD_PIM) && IsWindowEnabled (GetDlgItem (hwndDlg, IDC_PIM))) - { - wchar_t tmp[MAX_PIM+1] = {0}; - GetDlgItemText (hwndDlg, IDC_OLD_PIM, tmp, MAX_PIM + 1); - SetDlgItemText (hwndDlg, IDC_PIM, tmp); - } - - if (lw == IDC_PIM) - { - if(GetPim (hwndDlg, IDC_OLD_PIM) != GetPim (hwndDlg, IDC_PIM)) - { - PimValueChangedWarning = TRUE; - SetDlgItemTextW (hwndDlg, IDC_PIM_HELP, GetString (bSysEncPwdChangeDlgMode? "PIM_SYSENC_CHANGE_WARNING" : "PIM_CHANGE_WARNING")); - } - else - { - PimValueChangedWarning = FALSE; - SetDlgItemTextW (hwndDlg, IDC_PIM_HELP, (wchar_t *) GetDictionaryValueByInt (IDC_PIM_HELP)); - } - } - - return 1; - } - - if (lw == IDC_PIM_ENABLE) - { - ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDT_OLD_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_OLD_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_OLD_PIM_HELP), SW_SHOW); - - // check also the "Use PIM" for the new password if it is enabled - if (IsWindowEnabled (GetDlgItem (hwndDlg, IDC_NEW_PIM_ENABLE))) - { - SetCheckBox (hwndDlg, IDC_NEW_PIM_ENABLE, TRUE); - - ShowWindow (GetDlgItem (hwndDlg, IDC_NEW_PIM_ENABLE), SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); - } - - SetFocus (GetDlgItem (hwndDlg, IDC_OLD_PIM)); - - return 1; - } - - if (lw == IDC_NEW_PIM_ENABLE) - { - ShowWindow (GetDlgItem (hwndDlg, IDC_NEW_PIM_ENABLE), SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); - - SetFocus (GetDlgItem (hwndDlg, IDC_PIM)); - - return 1; - } - - if (lw == IDC_KEYFILES) - { - if (bSysEncPwdChangeDlgMode) - { - Warning ("KEYFILES_NOT_SUPPORTED_FOR_SYS_ENCRYPTION", hwndDlg); - return 1; - } - - KeyFilesDlgParam param; - param.EnableKeyFiles = KeyFilesEnable; - param.FirstKeyFile = FirstKeyFile; - - if (IDOK == DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, - (DLGPROC) KeyFilesDlgProc, (LPARAM) ¶m)) - { - KeyFilesEnable = param.EnableKeyFiles; - FirstKeyFile = param.FirstKeyFile; - - SetCheckBox (hwndDlg, IDC_ENABLE_KEYFILES, KeyFilesEnable); - } - - PasswordChangeEnable (hwndDlg, IDOK, - IDC_OLD_PASSWORD, - KeyFilesEnable && FirstKeyFile != NULL, - IDC_PASSWORD, IDC_VERIFY, - newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); - - return 1; - } - - - if (lw == IDC_NEW_KEYFILES) - { - if (bSysEncPwdChangeDlgMode) - { - Warning ("KEYFILES_NOT_SUPPORTED_FOR_SYS_ENCRYPTION", hwndDlg); - return 1; - } - - if (IDOK == DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, - (DLGPROC) KeyFilesDlgProc, (LPARAM) &newKeyFilesParam)) - { - SetCheckBox (hwndDlg, IDC_ENABLE_NEW_KEYFILES, newKeyFilesParam.EnableKeyFiles); - - VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (hwndDlg, IDOK), GetDlgItem (hwndDlg, IDC_PASSWORD), - GetDlgItem (hwndDlg, IDC_VERIFY), NULL, NULL, - newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); - } - - PasswordChangeEnable (hwndDlg, IDOK, - IDC_OLD_PASSWORD, - KeyFilesEnable && FirstKeyFile != NULL, - IDC_PASSWORD, IDC_VERIFY, - newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); - - return 1; - } - - if (lw == IDC_ENABLE_KEYFILES) - { - KeyFilesEnable = GetCheckBox (hwndDlg, IDC_ENABLE_KEYFILES); - - PasswordChangeEnable (hwndDlg, IDOK, - IDC_OLD_PASSWORD, - KeyFilesEnable && FirstKeyFile != NULL, - IDC_PASSWORD, IDC_VERIFY, - newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); - - return 1; - } - - if (lw == IDC_ENABLE_NEW_KEYFILES) - { - newKeyFilesParam.EnableKeyFiles = GetCheckBox (hwndDlg, IDC_ENABLE_NEW_KEYFILES); - - PasswordChangeEnable (hwndDlg, IDOK, - IDC_OLD_PASSWORD, - KeyFilesEnable && FirstKeyFile != NULL, - IDC_PASSWORD, IDC_VERIFY, - newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); - - return 1; - } - - if (hw == CBN_SELCHANGE) - { - switch (lw) - { - case IDC_PKCS5_PRF_ID: - if (bSysEncPwdChangeDlgMode) - { - int new_hash_algo_id = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, - SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); - - if (new_hash_algo_id != 0 && !HashForSystemEncryption(new_hash_algo_id)) - { - int new_hash_algo_id = DEFAULT_HASH_ALGORITHM_BOOT; - Info ("ALGO_NOT_SUPPORTED_FOR_SYS_ENCRYPTION", hwndDlg); - SelectAlgo (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), &new_hash_algo_id); - } - } - break; - } - return 1; - - } - - if (lw == IDC_TRUECRYPT_MODE) - { - BOOL bEnablePim = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE) ? FALSE: TRUE; - EnableWindow (GetDlgItem (hwndDlg, IDT_OLD_PIM), bEnablePim); - EnableWindow (GetDlgItem (hwndDlg, IDC_OLD_PIM), bEnablePim); - EnableWindow (GetDlgItem (hwndDlg, IDC_OLD_PIM_HELP), bEnablePim); - } - - if (lw == IDC_SHOW_PASSWORD_CHPWD_ORI) - { - HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_ORI, IDC_OLD_PASSWORD, IDC_OLD_PIM); - return 1; - } - - if (lw == IDC_SHOW_PASSWORD_CHPWD_NEW) - { - HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_NEW, IDC_PASSWORD, IDC_VERIFY); - HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_NEW, IDC_PIM, 0); - return 1; - } - - if (lw == IDOK) - { - HWND hParent = GetParent (hwndDlg); - Password oldPassword; - Password newPassword; - WipeAlgorithmId headerWiperMode = (WipeAlgorithmId) SendMessage ( - GetDlgItem (hwndDlg, IDC_WIPE_MODE), - CB_GETITEMDATA, - SendMessage (GetDlgItem (hwndDlg, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), - 0); - int nStatus; - int old_pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_OLD_PRF_ID), CB_GETITEMDATA, - SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_OLD_PRF_ID), CB_GETCURSEL, 0, 0), 0); - int pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, - SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); - BOOL truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); - - int old_pim = GetPim (hwndDlg, IDC_OLD_PIM); - int pim = GetPim (hwndDlg, IDC_PIM); - - if (truecryptMode && (old_pkcs5 == SHA256)) - { - Error ("ALGO_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); - return 1; - } - else if (truecryptMode && (old_pim != 0)) - { - Error ("PIM_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); - return 1; - } - - if (bSysEncPwdChangeDlgMode && !CheckPasswordCharEncoding (GetDlgItem (hwndDlg, IDC_PASSWORD), NULL)) - { - Error ("UNSUPPORTED_CHARS_IN_PWD", hwndDlg); - return 1; - } - - if (bSysEncPwdChangeDlgMode && (pim > MAX_BOOT_PIM_VALUE)) - { - SetFocus (GetDlgItem(hwndDlg, IDC_PIM)); - Error ("PIM_SYSENC_TOO_BIG", hwndDlg); - return 1; - } - - if (!bSysEncPwdChangeDlgMode && (pim > MAX_PIM_VALUE)) - { - SetFocus (GetDlgItem(hwndDlg, IDC_PIM)); - Error ("PIM_TOO_BIG", hwndDlg); - return 1; - } - - if (pwdChangeDlgMode == PCDM_CHANGE_PKCS5_PRF) - { - newKeyFilesParam.EnableKeyFiles = KeyFilesEnable; - } - else if (!(newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL) - && pwdChangeDlgMode == PCDM_CHANGE_PASSWORD) - { - if (!CheckPasswordLength (hwndDlg, GetWindowTextLength(GetDlgItem (hwndDlg, IDC_PASSWORD)), pim, bSysEncPwdChangeDlgMode, FALSE, FALSE)) - return 1; - } - - GetVolumePath (hParent, szFileName, ARRAYSIZE (szFileName)); - - if (GetPassword (hwndDlg, IDC_OLD_PASSWORD, (LPSTR) oldPassword.Text, sizeof (oldPassword.Text), TRUE)) - oldPassword.Length = (unsigned __int32) strlen ((char *) oldPassword.Text); - else - { - return 1; - } - - switch (pwdChangeDlgMode) - { - case PCDM_REMOVE_ALL_KEYFILES_FROM_VOL: - case PCDM_ADD_REMOVE_VOL_KEYFILES: - case PCDM_CHANGE_PKCS5_PRF: - memcpy (newPassword.Text, oldPassword.Text, sizeof (newPassword.Text)); - newPassword.Length = (unsigned __int32) strlen ((char *) oldPassword.Text); - pim = old_pim; - break; - - default: - if (GetPassword (hwndDlg, IDC_PASSWORD, (LPSTR) newPassword.Text, sizeof (newPassword.Text), TRUE)) - newPassword.Length = (unsigned __int32) strlen ((char *) newPassword.Text); - else - return 1; - } - - WaitCursor (); - - if (KeyFilesEnable) - KeyFilesApply (hwndDlg, &oldPassword, FirstKeyFile, szFileName); - - if (newKeyFilesParam.EnableKeyFiles) - { - if (!KeyFilesApply (hwndDlg, &newPassword, pwdChangeDlgMode == PCDM_CHANGE_PKCS5_PRF ? FirstKeyFile : newKeyFilesParam.FirstKeyFile, szFileName)) - { - nStatus = ERR_DONT_REPORT; - goto err; - } - } - - ChangePwdThreadParam changePwdParam; - changePwdParam.oldPassword = &oldPassword; - changePwdParam.old_pkcs5 = old_pkcs5; - changePwdParam.old_pim = old_pim; - changePwdParam.newPassword = &newPassword; - changePwdParam.pkcs5 = pkcs5; - changePwdParam.pim = pim; - changePwdParam.wipePassCount = GetWipePassCount(headerWiperMode); - changePwdParam.pnStatus = &nStatus; - changePwdParam.truecryptMode = truecryptMode; - - ShowWaitDialog(hwndDlg, TRUE, ChangePwdWaitThreadProc, &changePwdParam); - -err: - // notify the caller in case the PIM has changed - if (NewPimValuePtr) - { - if (pim != old_pim) - *NewPimValuePtr = pim; - else - *NewPimValuePtr = -1; - } - - burn (&oldPassword, sizeof (oldPassword)); - burn (&newPassword, sizeof (newPassword)); - burn (&old_pim, sizeof(old_pim)); - burn (&pim, sizeof(pim)); - - NormalCursor (); - - if (nStatus == 0) - { - // Attempt to wipe passwords stored in the input field buffers - wchar_t tmp[MAX_PASSWORD+1]; - wmemset (tmp, L'X', MAX_PASSWORD); - tmp[MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), tmp); - - KeyFileRemoveAll (&newKeyFilesParam.FirstKeyFile); - RestoreDefaultKeyFilesParam (); - - if (bSysEncPwdChangeDlgMode) - { - KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); - } - - EndDialog (hwndDlg, IDOK); - } - return 1; - } - return 0; - } - - return 0; -} - -static wchar_t PasswordDlgVolume[MAX_PATH + 1]; -static BOOL PasswordDialogDisableMountOptions; -static char *PasswordDialogTitleStringId; - -/* Except in response to the WM_INITDIALOG message, the dialog box procedure - should return nonzero if it processes the message, and zero if it does - not. - see DialogProc */ -BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - static Password *szXPwd; - static int *pkcs5; - static int *pim; - static BOOL* truecryptMode; - - switch (msg) - { - case WM_INITDIALOG: - { - int i, nIndex, defaultPrfIndex = 0; - szXPwd = ((PasswordDlgParam *) lParam) -> password; - pkcs5 = ((PasswordDlgParam *) lParam) -> pkcs5; - pim = ((PasswordDlgParam *) lParam) -> pim; - truecryptMode = ((PasswordDlgParam *) lParam) -> truecryptMode; - LocalizeDialog (hwndDlg, "IDD_PASSWORD_DLG"); - DragAcceptFiles (hwndDlg, TRUE); - - if (PasswordDialogTitleStringId) - { - SetWindowTextW (hwndDlg, GetString (PasswordDialogTitleStringId)); - } - else if (wcslen (PasswordDlgVolume) > 0) - { - wchar_t s[1024]; - RECT rect; - GetWindowRect (hwndDlg, &rect); - - bool useInExplorer = false; - wstring label = GetFavoriteVolumeLabel (PasswordDlgVolume, useInExplorer); - if (!label.empty()) - { - StringCbPrintfW (s, sizeof(s), GetString ("ENTER_PASSWORD_FOR_LABEL"), label.c_str()); - if (useInExplorer) - StringCbCopyW (mountOptions.Label, sizeof (mountOptions.Label), label.c_str()); - } - else - { - StringCbPrintfW (s, sizeof(s), GetString ("ENTER_PASSWORD_FOR"), L"___"); - StringCbPrintfW (s, sizeof(s), GetString ("ENTER_PASSWORD_FOR"), FitPathInGfxWidth (hwndDlg, WindowTitleBarFont, rect.right - rect.left - GetTextGfxWidth (hwndDlg, s, WindowTitleBarFont), PasswordDlgVolume).c_str()); - } - - SetWindowTextW (hwndDlg, s); - } - - /* Populate the PRF algorithms list */ - HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - - nIndex = (int) SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); - - for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) - { - nIndex = (int) SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); - if (*pkcs5 && (*pkcs5 == i)) - defaultPrfIndex = nIndex; - } - - /* make autodetection the default unless a specific PRF was specified in the command line */ - SendMessage (hComboBox, CB_SETCURSEL, defaultPrfIndex, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_CACHE), BM_SETCHECK, bCacheInDriver ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, MAX_PIM, 0); - - SetPim (hwndDlg, IDC_PIM, *pim); - - /* make PIM field visible if a PIM value has been explicitely specified */ - if (*pim > 0) - { - SetCheckBox (hwndDlg, IDC_PIM_ENABLE, TRUE); - ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); - } - - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); - - mountOptions.PartitionInInactiveSysEncScope = bPrebootPasswordDlgMode; - - if (bPrebootPasswordDlgMode) - { - SendMessage (hwndDlg, TC_APPMSG_PREBOOT_PASSWORD_MODE, 0, 0); - } - - if (PasswordDialogDisableMountOptions) - { - EnableWindow (GetDlgItem (hwndDlg, IDC_CACHE), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_MOUNT_OPTIONS), FALSE); - /* Disable TrueCrypt mode option in case of backup/restore header operation */ - SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE); - } - else if (*truecryptMode) - { - /* Check TrueCryptMode if it is enabled on the command line */ - SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, TRUE); - } - - if (!SetForegroundWindow (hwndDlg) && (FavoriteMountOnArrivalInProgress || LogOn)) - { - SetWindowPos (hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - - FLASHWINFO flash; - flash.cbSize = sizeof (flash); - flash.dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG; - flash.dwTimeout = 0; - flash.hwnd = hwndDlg; - flash.uCount = 0; - - FlashWindowEx (&flash); - - SetWindowPos (hwndDlg, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - } - } - return 0; - - case TC_APPMSG_PREBOOT_PASSWORD_MODE: - { - /* Repopulate the PRF algorithms list with algorithms that support system encryption */ - HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - - int i, defaultPrfIndex = 0, nIndex = (int) SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); - - for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) - { - if (HashForSystemEncryption(i)) - { - nIndex = (int) SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); - if (*pkcs5 && (*pkcs5 == i)) - defaultPrfIndex = nIndex; - } - } - - /* make autodetection the default unless a specific PRF was specified in the command line */ - SendMessage (hComboBox, CB_SETCURSEL, defaultPrfIndex, 0); - - ToBootPwdField (hwndDlg, IDC_PASSWORD); - - // Attempt to wipe the password stored in the input field buffer - wchar_t tmp[MAX_PASSWORD+1]; - wmemset (tmp, L'X', MAX_PASSWORD); - tmp [MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), L""); - - StringCbPrintfW (OrigKeyboardLayout, sizeof(OrigKeyboardLayout),L"%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF); - - DWORD keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); - - if (keybLayout != 0x00000409 && keybLayout != 0x04090409) - { - Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - if (SetTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0) - { - Error ("CANNOT_SET_TIMER", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - if (GetCheckBox (hwndDlg, IDC_SHOW_PASSWORD)) - { - // simulate hiding password - SetCheckBox (hwndDlg, IDC_SHOW_PASSWORD, FALSE); - - HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD, IDC_PASSWORD, IDC_PIM); - } - - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_ENABLE), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_KEY_FILES), FALSE); - - SetPim (hwndDlg, IDC_PIM, *pim); - - bPrebootPasswordDlgMode = TRUE; - } - return 1; - - case WM_TIMER: - switch (wParam) - { - case TIMER_ID_KEYB_LAYOUT_GUARD: - if (bPrebootPasswordDlgMode) - { - DWORD keybLayout = (DWORD) GetKeyboardLayout (NULL); - - if (keybLayout != 0x00000409 && keybLayout != 0x04090409) - { - // Keyboard layout is not standard US - - // Attempt to wipe the password stored in the input field buffer - wchar_t tmp[MAX_PASSWORD+1]; - wmemset (tmp, L'X', MAX_PASSWORD); - tmp [MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), L""); - - keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); - - if (keybLayout != 0x00000409 && keybLayout != 0x04090409) - { - KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); - Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - wchar_t szTmp [4096]; - StringCbCopyW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_CHANGE_PREVENTED")); - StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); - StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION")); - MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); - } - } - return 1; - } - return 0; - - case WM_COMMAND: - - if (lw == IDC_MOUNT_OPTIONS) - { - /* Use default PRF specified by the user if any */ - if (mountOptions.ProtectedHidVolPkcs5Prf == 0) - mountOptions.ProtectedHidVolPkcs5Prf = *pkcs5; - if (mountOptions.ProtectedHidVolPim == 0) - mountOptions.ProtectedHidVolPim = *pim; - DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, - (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions); - - if (!bPrebootPasswordDlgMode && mountOptions.PartitionInInactiveSysEncScope) - SendMessage (hwndDlg, TC_APPMSG_PREBOOT_PASSWORD_MODE, 0, 0); - - return 1; - } - - if (lw == IDC_PIM_ENABLE) - { - ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); - - SetFocus (GetDlgItem (hwndDlg, IDC_PIM)); - return 1; - } - - if (lw == IDC_SHOW_PASSWORD) - { - HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD, IDC_PASSWORD, IDC_PIM); - return 1; - } - - if (lw == IDC_TRUECRYPT_MODE) - { - BOOL bEnablePim = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE) ? FALSE: TRUE; - EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), bEnablePim); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), bEnablePim); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), bEnablePim); - } - - if (lw == IDC_KEY_FILES) - { - KeyFilesDlgParam param; - param.EnableKeyFiles = KeyFilesEnable; - param.FirstKeyFile = FirstKeyFile; - - if (IDOK == DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, - (DLGPROC) KeyFilesDlgProc, (LPARAM) ¶m)) - { - KeyFilesEnable = param.EnableKeyFiles; - FirstKeyFile = param.FirstKeyFile; - - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); - } - - return 1; - } - - if (lw == IDC_KEYFILES_ENABLE) - { - KeyFilesEnable = GetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE); - - return 1; - } - - if (lw == IDCANCEL || lw == IDOK) - { - wchar_t tmp[MAX_PASSWORD+1]; - - if (lw == IDOK) - { - if (mountOptions.ProtectHiddenVolume && hidVolProtKeyFilesParam.EnableKeyFiles) - KeyFilesApply (hwndDlg, &mountOptions.ProtectedHidVolPassword, hidVolProtKeyFilesParam.FirstKeyFile, wcslen (PasswordDlgVolume) > 0 ? PasswordDlgVolume : NULL); - - if (GetPassword (hwndDlg, IDC_PASSWORD, (LPSTR) szXPwd->Text, MAX_PASSWORD + 1, TRUE)) - szXPwd->Length = (unsigned __int32) strlen ((char *) szXPwd->Text); - else - return 1; - - bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_CACHE)); - *pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); - *truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); - - *pim = GetPim (hwndDlg, IDC_PIM); - - /* SHA-256 is not supported by TrueCrypt */ - if ( (*truecryptMode) - && ((*pkcs5 == SHA256) || (mountOptions.ProtectHiddenVolume && mountOptions.ProtectedHidVolPkcs5Prf == SHA256)) - ) - { - Error ("ALGO_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); - return 1; - } - - if ( (*truecryptMode) - && (*pim != 0) - ) - { - Error ("PIM_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); - return 1; - } - } - - // Attempt to wipe password stored in the input field buffer - wmemset (tmp, L'X', MAX_PASSWORD); - tmp[MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); - - if (hidVolProtKeyFilesParam.FirstKeyFile != NULL) - { - KeyFileRemoveAll (&hidVolProtKeyFilesParam.FirstKeyFile); - hidVolProtKeyFilesParam.EnableKeyFiles = FALSE; - } - - if (bPrebootPasswordDlgMode) - { - KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); - - // Restore the original keyboard layout - if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) - Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); - } - - EndDialog (hwndDlg, lw); - return 1; - } - return 0; - - case WM_CONTEXTMENU: - { - RECT buttonRect; - GetWindowRect (GetDlgItem (hwndDlg, IDC_KEY_FILES), &buttonRect); - - if (LOWORD (lParam) >= buttonRect.left && LOWORD (lParam) <= buttonRect.right - && HIWORD (lParam) >= buttonRect.top && HIWORD (lParam) <= buttonRect.bottom) - { - // The "Keyfiles" button has been right-clicked - - KeyFilesDlgParam param; - param.EnableKeyFiles = KeyFilesEnable; - param.FirstKeyFile = FirstKeyFile; - - POINT popupPos; - popupPos.x = buttonRect.left + 2; - popupPos.y = buttonRect.top + 2; - - if (KeyfilesPopupMenu (hwndDlg, popupPos, ¶m)) - { - KeyFilesEnable = param.EnableKeyFiles; - FirstKeyFile = param.FirstKeyFile; - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); - } - } - } - 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)); - FirstKeyFile = KeyFileAdd (FirstKeyFile, kf); - KeyFilesEnable = TRUE; - } - } - - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); - DragFinish (hdrop); - } - return 1; - } - - return 0; -} - -static void PreferencesDlgEnableButtons (HWND hwndDlg) -{ - BOOL back = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_BKG_TASK_ENABLE)); - BOOL idle = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE)); - BOOL installed = !IsNonInstallMode(); - BOOL wtsEnabled = (hWtsLib != NULL) ? TRUE : FALSE; - - EnableWindow (GetDlgItem (hwndDlg, IDC_CLOSE_BKG_TASK_WHEN_NOVOL), back && installed); - EnableWindow (GetDlgItem (hwndDlg, IDT_LOGON), installed); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_LOGON_START), back && installed); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_LOGON_MOUNT_DEVICES), installed); - EnableWindow (GetDlgItem (hwndDlg, IDT_AUTO_DISMOUNT), back); - EnableWindow (GetDlgItem (hwndDlg, IDT_AUTO_DISMOUNT_ON), back); - EnableWindow (GetDlgItem (hwndDlg, IDT_MINUTES), back); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_LOGOFF), back); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SESSION_LOCKED), back && wtsEnabled); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_POWERSAVING), back); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SCREENSAVER), back); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE), back); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE_TIME), back && idle); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT), back); -} - -BOOL CALLBACK PreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - static BOOL PreferencesDialogActive = FALSE; - static HWND ActivePreferencesDialogWindow; - - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - if (PreferencesDialogActive) - { - ShowWindow (ActivePreferencesDialogWindow, SW_SHOW); - SetForegroundWindow (ActivePreferencesDialogWindow); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - ActivePreferencesDialogWindow = hwndDlg; - PreferencesDialogActive = TRUE; - - LocalizeDialog (hwndDlg, "IDD_PREFERENCES_DLG"); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_OPEN_EXPLORER), BM_SETCHECK, - bExplore ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_USE_DIFF_TRAY_ICON_IF_VOL_MOUNTED), BM_SETCHECK, - bUseDifferentTrayIconIfVolMounted ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PRESERVE_TIMESTAMPS), BM_SETCHECK, - defaultMountOptions.PreserveTimestamp ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_SHOW_DISCONNECTED_NETWORK_DRIVES), BM_SETCHECK, - bShowDisconnectedNetworkDrives ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_HIDE_WAITING_DIALOG), BM_SETCHECK, - bHideWaitingDialog ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT), BM_SETCHECK, - bCacheDuringMultipleMount ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_EXIT), BM_SETCHECK, - bWipeCacheOnExit ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_AUTODISMOUNT), BM_SETCHECK, - bWipeCacheOnAutoDismount ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PASSWORDS), BM_SETCHECK, - bCacheInDriver ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PIM), BM_SETCHECK, - bIncludePimInCache? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_READONLY), BM_SETCHECK, - defaultMountOptions.ReadOnly ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_REMOVABLE), BM_SETCHECK, - defaultMountOptions.Removable ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_LOGON_START), BM_SETCHECK, - bStartOnLogon ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_LOGON_MOUNT_DEVICES), BM_SETCHECK, - bMountDevicesOnLogon ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_BKG_TASK_ENABLE), BM_SETCHECK, - bEnableBkgTask ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_CLOSE_BKG_TASK_WHEN_NOVOL), BM_SETCHECK, - bCloseBkgTaskWhenNoVolumes || IsNonInstallMode() ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_LOGOFF), BM_SETCHECK, - bDismountOnLogOff ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SESSION_LOCKED), BM_SETCHECK, - bDismountOnSessionLocked ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_POWERSAVING), BM_SETCHECK, - bDismountOnPowerSaving ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SCREENSAVER), BM_SETCHECK, - bDismountOnScreenSaver ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT), BM_SETCHECK, - bForceAutoDismount ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE), BM_SETCHECK, - MaxVolumeIdleTime > 0 ? BST_CHECKED:BST_UNCHECKED, 0); - - SetDlgItemInt (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE_TIME, abs (MaxVolumeIdleTime), FALSE); - - PreferencesDlgEnableButtons (hwndDlg); - } - return 0; - - case WM_COMMAND: - - if (lw == IDC_PREF_BKG_TASK_ENABLE && !IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_BKG_TASK_ENABLE))) - { - if (AskWarnNoYes ("CONFIRM_BACKGROUND_TASK_DISABLED", hwndDlg) == IDNO) - SetCheckBox (hwndDlg, IDC_PREF_BKG_TASK_ENABLE, TRUE); - } - - // Forced dismount disabled warning - if (lw == IDC_PREF_DISMOUNT_INACTIVE - || lw == IDC_PREF_DISMOUNT_LOGOFF - || lw == IDC_PREF_DISMOUNT_SESSION_LOCKED - || lw == IDC_PREF_DISMOUNT_POWERSAVING - || lw == IDC_PREF_DISMOUNT_SCREENSAVER - || lw == IDC_PREF_FORCE_AUTO_DISMOUNT) - { - BOOL i = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE)); - BOOL l = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_LOGOFF)); - BOOL sl = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SESSION_LOCKED)); - BOOL p = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_POWERSAVING)); - BOOL s = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SCREENSAVER)); - BOOL q = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT)); - - if (!q) - { - if (lw == IDC_PREF_FORCE_AUTO_DISMOUNT && (i || l || sl || p || s)) - { - if (AskWarnNoYes ("CONFIRM_NO_FORCED_AUTODISMOUNT", hwndDlg) == IDNO) - SetCheckBox (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT, TRUE); - } - else if ((lw == IDC_PREF_DISMOUNT_INACTIVE && i - || lw == IDC_PREF_DISMOUNT_LOGOFF && l - || lw == IDC_PREF_DISMOUNT_SESSION_LOCKED && sl - || lw == IDC_PREF_DISMOUNT_POWERSAVING && p - || lw == IDC_PREF_DISMOUNT_SCREENSAVER && s)) - Warning ("WARN_PREF_AUTO_DISMOUNT", hwndDlg); - } - - if (p && lw == IDC_PREF_DISMOUNT_POWERSAVING) - Warning ("WARN_PREF_AUTO_DISMOUNT_ON_POWER", hwndDlg); - } - - if (lw == IDCANCEL) - { - PreferencesDialogActive = FALSE; - EndDialog (hwndDlg, lw); - return 1; - } - - if (lw == IDOK) - { - WaitCursor (); - - bExplore = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_OPEN_EXPLORER)); - bUseDifferentTrayIconIfVolMounted = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_USE_DIFF_TRAY_ICON_IF_VOL_MOUNTED)); - bPreserveTimestamp = defaultMountOptions.PreserveTimestamp = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PRESERVE_TIMESTAMPS)); - bShowDisconnectedNetworkDrives = IsButtonChecked (GetDlgItem (hwndDlg, IDC_SHOW_DISCONNECTED_NETWORK_DRIVES)); - bHideWaitingDialog = IsButtonChecked (GetDlgItem (hwndDlg, IDC_HIDE_WAITING_DIALOG)); - bCacheDuringMultipleMount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT)); - bWipeCacheOnExit = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_EXIT)); - bWipeCacheOnAutoDismount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_AUTODISMOUNT)); - bCacheInDriverDefault = bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PASSWORDS)); - bIncludePimInCache = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PIM)); - defaultMountOptions.ReadOnly = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_READONLY)); - defaultMountOptions.Removable = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_REMOVABLE)); - bEnableBkgTask = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_BKG_TASK_ENABLE)); - bCloseBkgTaskWhenNoVolumes = IsNonInstallMode() ? bCloseBkgTaskWhenNoVolumes : IsButtonChecked (GetDlgItem (hwndDlg, IDC_CLOSE_BKG_TASK_WHEN_NOVOL)); - bDismountOnLogOff = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_LOGOFF)); - bDismountOnSessionLocked = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SESSION_LOCKED)); - bDismountOnPowerSaving = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_POWERSAVING)); - bDismountOnScreenSaver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SCREENSAVER)); - bForceAutoDismount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT)); - MaxVolumeIdleTime = GetDlgItemInt (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE_TIME, NULL, FALSE) - * (IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE)) ? 1 : -1); - bStartOnLogon = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_LOGON_START)); - bMountDevicesOnLogon = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_LOGON_MOUNT_DEVICES)); - - ManageStartupSeq (); - - SaveSettings (hwndDlg); - - NormalCursor (); - - PreferencesDialogActive = FALSE; - EndDialog (hwndDlg, lw); - return 1; - } - - if (lw == IDC_MORE_SETTINGS) - { - HMENU popup = CreatePopupMenu (); - if (popup) - { - AppendMenuW (popup, MF_STRING, IDM_LANGUAGE, GetString ("IDM_LANGUAGE")); - AppendMenuW (popup, MF_STRING, IDM_HOTKEY_SETTINGS, GetString ("IDM_HOTKEY_SETTINGS")); - AppendMenuW (popup, MF_STRING, IDM_PERFORMANCE_SETTINGS, GetString ("IDM_PERFORMANCE_SETTINGS")); - AppendMenuW (popup, MF_STRING, IDM_SYSENC_SETTINGS, GetString ("IDM_SYSENC_SETTINGS")); - AppendMenuW (popup, MF_STRING, IDM_SYS_FAVORITES_SETTINGS, GetString ("IDM_SYS_FAVORITES_SETTINGS")); - AppendMenuW (popup, MF_STRING, IDM_DEFAULT_KEYFILES, GetString ("IDM_DEFAULT_KEYFILES")); - AppendMenuW (popup, MF_STRING, IDM_DEFAULT_MOUNT_PARAMETERS, GetString ("IDM_DEFAULT_MOUNT_PARAMETERS")); - AppendMenuW (popup, MF_STRING, IDM_TOKEN_PREFERENCES, GetString ("IDM_TOKEN_PREFERENCES")); - - RECT rect; - GetWindowRect (GetDlgItem (hwndDlg, IDC_MORE_SETTINGS), &rect); - - int menuItem = TrackPopupMenu (popup, TPM_RETURNCMD | TPM_LEFTBUTTON, rect.left + 2, rect.top + 2, 0, hwndDlg, NULL); - DestroyMenu (popup); - - SendMessage (MainDlg, WM_COMMAND, menuItem, NULL); - return 1; - } - else - return 0; - } - - if (HIWORD (wParam) == BN_CLICKED) - { - PreferencesDlgEnableButtons (hwndDlg); - return 1; - } - - return 0; - } - - return 0; -} - - -BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - static MountOptions *mountOptions; - - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - BOOL protect; - - mountOptions = (MountOptions *) lParam; - - LocalizeDialog (hwndDlg, "IDD_MOUNT_OPTIONS"); - - SendDlgItemMessage (hwndDlg, IDC_MOUNT_READONLY, BM_SETCHECK, - mountOptions->ReadOnly ? BST_CHECKED : BST_UNCHECKED, 0); - SendDlgItemMessage (hwndDlg, IDC_MOUNT_REMOVABLE, BM_SETCHECK, - mountOptions->Removable ? BST_CHECKED : BST_UNCHECKED, 0); - SendDlgItemMessage (hwndDlg, IDC_PROTECT_HIDDEN_VOL, BM_SETCHECK, - mountOptions->ProtectHiddenVolume ? BST_CHECKED : BST_UNCHECKED, 0); - - SendDlgItemMessage (hwndDlg, IDC_PROTECT_HIDDEN_VOL, BM_SETCHECK, - mountOptions->ProtectHiddenVolume ? BST_CHECKED : BST_UNCHECKED, 0); - - mountOptions->PartitionInInactiveSysEncScope = bPrebootPasswordDlgMode; - - SendDlgItemMessage (hwndDlg, IDC_MOUNT_SYSENC_PART_WITHOUT_PBA, BM_SETCHECK, - bPrebootPasswordDlgMode ? BST_CHECKED : BST_UNCHECKED, 0); - - SendDlgItemMessage (hwndDlg, IDC_USE_EMBEDDED_HEADER_BAK, BM_SETCHECK, - mountOptions->UseBackupHeader ? BST_CHECKED : BST_UNCHECKED, 0); - - EnableWindow (GetDlgItem (hwndDlg, IDC_MOUNT_SYSENC_PART_WITHOUT_PBA), !bPrebootPasswordDlgMode); - - SetDlgItemTextW (hwndDlg, IDC_VOLUME_LABEL, mountOptions->Label); - SendDlgItemMessage (hwndDlg, IDC_VOLUME_LABEL, EM_LIMITTEXT, 32, 0); // 32 is the maximum possible length for a drive label in Windows - - /* Add PRF algorithm list for hidden volume password */ - HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - - int i, nSelectedIndex = 0, nIndex = (int) SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); - - for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) - { - nIndex = (int) SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); - /* if a PRF was selected previously, select it */ - if (i == mountOptions->ProtectedHidVolPkcs5Prf) - nSelectedIndex = nIndex; - } - - SendMessage (hComboBox, CB_SETCURSEL, nSelectedIndex, 0); - - protect = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL)); - - EnableWindow (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL), !IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY))); - EnableWindow (GetDlgItem (hwndDlg, IDT_HIDDEN_VOL_PROTECTION), !IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY))); - EnableWindow (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PASSWORD_MO), protect); - EnableWindow (GetDlgItem (hwndDlg, IDT_HIDDEN_PROT_PASSWD), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_HIDVOL_PROT), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT), protect); - EnableWindow (GetDlgItem (hwndDlg, IDT_PKCS5_PRF), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), protect); - EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), protect); - - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT, hidVolProtKeyFilesParam.EnableKeyFiles); - - SendDlgItemMessage (hwndDlg, IDC_PASSWORD_PROT_HIDVOL, EM_LIMITTEXT, MAX_PASSWORD, 0); - SendDlgItemMessage (hwndDlg, IDC_PIM, EM_LIMITTEXT, MAX_PIM, 0); - - if (mountOptions->ProtectedHidVolPassword.Length > 0) - { - wchar_t szTmp[MAX_PASSWORD + 1]; - if (0 == MultiByteToWideChar (CP_UTF8, 0, (LPSTR) mountOptions->ProtectedHidVolPassword.Text, -1, szTmp, MAX_PASSWORD + 1)) - szTmp [0] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), szTmp); - burn (szTmp, sizeof (szTmp)); - } - - SetPim (hwndDlg, IDC_PIM, mountOptions->ProtectedHidVolPim); - - /* make PIM field visible if a PIM value has been explicitely specified */ - if (mountOptions->ProtectedHidVolPim > 0) - { - SetCheckBox (hwndDlg, IDC_PIM_ENABLE, TRUE); - ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); - } - - ToHyperlink (hwndDlg, IDC_LINK_HIDVOL_PROTECTION_INFO); - - } - return 0; - - case WM_CONTEXTMENU: - { - RECT buttonRect; - GetWindowRect (GetDlgItem (hwndDlg, IDC_KEYFILES_HIDVOL_PROT), &buttonRect); - - if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL)) - && LOWORD (lParam) >= buttonRect.left && LOWORD (lParam) <= buttonRect.right - && HIWORD (lParam) >= buttonRect.top && HIWORD (lParam) <= buttonRect.bottom) - { - // The "Keyfiles" button has been right-clicked - - POINT popupPos; - popupPos.x = buttonRect.left + 2; - popupPos.y = buttonRect.top + 2; - - if (KeyfilesPopupMenu (hwndDlg, popupPos, &hidVolProtKeyFilesParam)) - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT, hidVolProtKeyFilesParam.EnableKeyFiles); - } - } - break; - - case WM_COMMAND: - - if (lw == IDC_KEYFILES_HIDVOL_PROT) - { - if (IDOK == DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, - (DLGPROC) KeyFilesDlgProc, (LPARAM) &hidVolProtKeyFilesParam)) - { - SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT, hidVolProtKeyFilesParam.EnableKeyFiles); - } - } - - if (lw == IDC_KEYFILES_ENABLE_HIDVOL_PROT) - { - hidVolProtKeyFilesParam.EnableKeyFiles = GetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT); - - return 0; - } - - if (lw == IDC_SHOW_PASSWORD_MO) - { - HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD_MO, IDC_PASSWORD_PROT_HIDVOL, IDC_PIM); - return 1; - } - - if (lw == IDC_PIM_ENABLE) - { - ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); - ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); - ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); - - SetFocus (GetDlgItem (hwndDlg, IDC_PIM)); - return 1; - } - - if (lw == IDC_LINK_HIDVOL_PROTECTION_INFO) - { - Applink ("hiddenvolprotection", TRUE, ""); - } - - if (lw == IDCANCEL) - { - wchar_t tmp[MAX_PASSWORD+1]; - - // Cleanup - wmemset (tmp, L'X', MAX_PASSWORD); - tmp[MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); - - EndDialog (hwndDlg, lw); - return 1; - } - - if (lw == IDOK) - { - wchar_t tmp[MAX_PASSWORD+1]; - - mountOptions->ReadOnly = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY)); - mountOptions->Removable = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_REMOVABLE)); - mountOptions->ProtectHiddenVolume = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL)); - mountOptions->PartitionInInactiveSysEncScope = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_SYSENC_PART_WITHOUT_PBA)); - mountOptions->UseBackupHeader = IsButtonChecked (GetDlgItem (hwndDlg, IDC_USE_EMBEDDED_HEADER_BAK)); - - GetDlgItemTextW (hwndDlg, IDC_VOLUME_LABEL, mountOptions->Label, sizeof (mountOptions->Label) /sizeof (wchar_t)); - - if (mountOptions->ProtectHiddenVolume) - { - GetPassword (hwndDlg, IDC_PASSWORD_PROT_HIDVOL, - (LPSTR) mountOptions->ProtectedHidVolPassword.Text, MAX_PASSWORD + 1, - FALSE); - - mountOptions->ProtectedHidVolPassword.Length = (unsigned __int32) strlen ((char *) mountOptions->ProtectedHidVolPassword.Text); - - mountOptions->ProtectedHidVolPkcs5Prf = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, - SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); - - mountOptions->ProtectedHidVolPim = GetPim (hwndDlg, IDC_PIM); - } - - // Cleanup - wmemset (tmp, L'X', MAX_PASSWORD); - tmp[MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); - - if ((mountOptions->ProtectHiddenVolume && !bEnableBkgTask) - && (AskWarnYesNo ("HIDVOL_PROT_BKG_TASK_WARNING", hwndDlg) == IDYES)) - { - bEnableBkgTask = TRUE; - TaskBarIconAdd (MainDlg); - } - - EndDialog (hwndDlg, lw); - return 1; - } - - if (lw == IDC_MOUNT_READONLY || lw == IDC_PROTECT_HIDDEN_VOL) - { - BOOL protect; - - if (lw == IDC_MOUNT_READONLY) - { - SendDlgItemMessage (hwndDlg, IDC_PROTECT_HIDDEN_VOL, BM_SETCHECK, BST_UNCHECKED, 0); - EnableWindow (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL), !IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY))); - EnableWindow (GetDlgItem (hwndDlg, IDT_HIDDEN_VOL_PROTECTION), !IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY))); - } - - protect = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL)); - - EnableWindow (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), protect); - EnableWindow (GetDlgItem (hwndDlg, IDT_HIDDEN_PROT_PASSWD), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PASSWORD_MO), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_HIDVOL_PROT), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT), protect); - EnableWindow (GetDlgItem (hwndDlg, IDT_PKCS5_PRF), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), protect); - EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), protect); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), protect); - - return 1; - } - - return 0; - } - - return 0; -} - - -// Returns the block size (in bits) of the cipher with which the volume mounted as the -// specified drive letter is encrypted. In case of a cascade of ciphers with different -// block sizes the function returns the smallest block size. -int GetCipherBlockSizeByDriveNo (int nDosDriveNo) -{ - VOLUME_PROPERTIES_STRUCT prop; - DWORD dwResult; - - int blockSize = 0, cipherID; - - memset (&prop, 0, sizeof(prop)); - prop.driveNo = nDosDriveNo; - - if (DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL)) - { - if ( (prop.driveNo == nDosDriveNo) - && (prop.ea >= EAGetFirst() && prop.ea <= EAGetCount()) - ) - { - for (cipherID = EAGetLastCipher (prop.ea); - cipherID != 0; - cipherID = EAGetPreviousCipher (prop.ea, cipherID)) - { - if (blockSize > 0) - blockSize = min (blockSize, CipherGetBlockSize (cipherID) * 8); - else - blockSize = CipherGetBlockSize (cipherID) * 8; - } - } - } - - return blockSize; -} - - -// Returns the mode of operation in which the volume mounted as the specified drive letter is encrypted. -int GetModeOfOperationByDriveNo (int nDosDriveNo) -{ - VOLUME_PROPERTIES_STRUCT prop; - DWORD dwResult; - - memset (&prop, 0, sizeof(prop)); - prop.driveNo = nDosDriveNo; - - if (DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL)) - { - if ( (prop.driveNo == nDosDriveNo) - && (prop.ea >= EAGetFirst() && prop.ea <= EAGetCount()) - && (prop.mode >= FIRST_MODE_OF_OPERATION_ID && prop.mode < MODE_ENUM_END_ID) - ) - { - return prop.mode; - } - } - - return 0; -} - -void DisplayVolumePropertiesListContextMenu (HWND hwndDlg, LPARAM lParam) -{ - /* Volume Properties list context menu */ - DWORD mPos; - int menuItem; - HWND hList = GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES_LIST); - int hItem = ListView_GetSelectionMark (hList); - - SetFocus (hList); - - if (hItem >= 0) - { - HMENU popup = CreatePopupMenu (); - AppendMenuW (popup, MF_STRING, IDPM_COPY_VALUE_TO_CLIPBOARD, GetString ("IDPM_COPY_VALUE_TO_CLIPBOARD")); - - if (lParam) - { - mPos=GetMessagePos(); - } - else - { - POINT pt = {0}; - if (ListView_GetItemPosition (hList, hItem, &pt)) - { - pt.x += 2 + ::GetSystemMetrics(SM_CXICON); - pt.y += 2; - } - ClientToScreen (hList, &pt); - mPos = MAKELONG (pt.x, pt.y); - } - - menuItem = TrackPopupMenu (popup, - TPM_RETURNCMD | TPM_LEFTBUTTON, - GET_X_LPARAM(mPos), - GET_Y_LPARAM(mPos), - 0, - hwndDlg, - NULL); - - DestroyMenu (popup); - - switch (menuItem) - { - case IDPM_COPY_VALUE_TO_CLIPBOARD: - { - wchar_t valueText[256] = {0}; - ListView_GetItemText (hList, hItem, 1, valueText, ARRAYSIZE (valueText)); - CopyTextToClipboard (valueText); - } - break; - } - } -} - - -BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - BOOL bSysEnc = (BOOL) lParam; - BOOL bSysEncWholeDrive = FALSE; - WORD lw = LOWORD (wParam); - int i = 0; - - switch (msg) - { - case WM_INITDIALOG: - { - VOLUME_PROPERTIES_STRUCT prop; - DWORD dwResult; - - LVCOLUMNW lvCol; - HWND list = GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES_LIST); - wchar_t szTmp[1024]; - wchar_t sw[1024]; - wchar_t *s; - - if (bSysEnc) - { - try - { - BootEncStatus = BootEncObj->GetStatus(); - bSysEncWholeDrive = WholeSysDriveEncryption(FALSE); - } - catch (Exception &e) - { - e.Show (MainDlg); - return 0; - } - - if (!BootEncStatus.DriveEncrypted && !BootEncStatus.DriveMounted) - return 0; - } - else - { - switch (LOWORD (GetSelectedLong (GetDlgItem (GetParent(hwndDlg), IDC_DRIVELIST)))) - { - case TC_MLIST_ITEM_FREE: - - // No mounted volume - EndDialog (hwndDlg, IDOK); - return 0; - - case TC_MLIST_ITEM_NONSYS_VOL: - // NOP - break; - - case TC_MLIST_ITEM_SYS_DRIVE: - // Encrypted system drive - bSysEnc = TRUE; - bSysEncWholeDrive = TRUE; - break; - - case TC_MLIST_ITEM_SYS_PARTITION: - // Encrypted system partition - bSysEnc = TRUE; - bSysEncWholeDrive = FALSE; - break; - } - } - - LocalizeDialog (hwndDlg, "IDD_VOLUME_PROPERTIES"); - - SendMessage (list,LVM_SETEXTENDEDLISTVIEWSTYLE, 0, - LVS_EX_FULLROWSELECT - |LVS_EX_HEADERDRAGDROP - |LVS_EX_LABELTIP - ); - - memset (&lvCol,0,sizeof(lvCol)); - lvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; - lvCol.pszText = GetString ("VALUE"); - lvCol.cx = CompensateXDPI (208); - lvCol.fmt = LVCFMT_LEFT; - SendMessage (list,LVM_INSERTCOLUMNW,0,(LPARAM)&lvCol); - - lvCol.pszText = GetString ("PROPERTY"); - lvCol.cx = CompensateXDPI (192); - lvCol.fmt = LVCFMT_LEFT; - SendMessage (list,LVM_INSERTCOLUMNW,0,(LPARAM)&lvCol); - - memset (&prop, 0, sizeof(prop)); - prop.driveNo = HIWORD (GetSelectedLong (GetDlgItem (GetParent(hwndDlg), IDC_DRIVELIST))) - L'A'; - - if (bSysEnc) - { - try - { - BootEncStatus = BootEncObj->GetStatus(); - if (!BootEncStatus.DriveEncrypted && !BootEncStatus.DriveMounted) - return 0; - - BootEncObj->GetVolumeProperties (&prop); - } - catch (Exception &e) - { - e.Show (MainDlg); - return 0; - } - } - else - { - if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL) || dwResult == 0) - return 0; - } - - // Location - ListItemAdd (list, i, GetString ("LOCATION")); - if (bSysEnc) - ListSubItemSet (list, i++, 1, GetString (bSysEncWholeDrive ? "SYSTEM_DRIVE" : IsHiddenOSRunning() ? "HIDDEN_SYSTEM_PARTITION" : "SYSTEM_PARTITION")); - else - ListSubItemSet (list, i++, 1, (wchar_t *) (prop.wszVolume[1] != L'?' ? prop.wszVolume : prop.wszVolume + 4)); - - if (!bSysEnc && IsVolumeDeviceHosted ((wchar_t *) (prop.wszVolume[1] != L'?' ? prop.wszVolume : prop.wszVolume + 4))) - { - // Volume ID - std::wstring hexID = ArrayToHexWideString (prop.volumeID, sizeof (prop.volumeID)); - ListItemAdd (list, i, GetString ("VOLUME_ID")); - - ListSubItemSet (list, i++, 1, hexID.c_str()); - } - - - // Size - ListItemAdd (list, i, GetString ("SIZE")); - StringCbPrintfW (sw, sizeof(sw), L"%I64u %s", prop.diskLength, GetString ("BYTES")); - ListSubItemSet (list, i++, 1, sw); - - // Type - ListItemAdd (list, i, GetString ("TYPE")); - if (bSysEnc) - ListSubItemSet (list, i++, 1, GetString (IsHiddenOSRunning() ? "TYPE_HIDDEN_SYSTEM_ADJECTIVE" : "SYSTEM_VOLUME_TYPE_ADJECTIVE")); - else - { - bool truecryptMode = prop.pkcs5Iterations == get_pkcs5_iteration_count(prop.pkcs5, 0, TRUE, prop.partitionInInactiveSysEncScope); - s = prop.hiddenVolume ? GetString ("HIDDEN") : - (prop.hiddenVolProtection != HIDVOL_PROT_STATUS_NONE ? GetString ("OUTER") : GetString ("NORMAL")); - - if (truecryptMode) - { - StringCbPrintfW (sw, sizeof(sw), L"TrueCrypt - %s", s); - ListSubItemSet (list, i++, 1, sw); - } - else - ListSubItemSet (list, i++, 1, s); - } - - if (!bSysEnc) - { - // Write protection - ListItemAdd (list, i, GetString ("READ_ONLY")); - - if (prop.readOnly || prop.hiddenVolProtection == HIDVOL_PROT_STATUS_ACTION_TAKEN) - s = GetString ("UISTR_YES"); - else - s = GetString ("UISTR_NO"); - - ListSubItemSet (list, i++, 1, s); - - // Hidden Volume Protection - ListItemAdd (list, i, GetString ("HIDDEN_VOL_PROTECTION")); - if (prop.hiddenVolume) - s = GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE"); - else if (prop.hiddenVolProtection == HIDVOL_PROT_STATUS_NONE) - s = GetString ("UISTR_NO"); - else if (prop.hiddenVolProtection == HIDVOL_PROT_STATUS_ACTIVE) - s = GetString ("UISTR_YES"); - else if (prop.hiddenVolProtection == HIDVOL_PROT_STATUS_ACTION_TAKEN) - s = GetString ("HID_VOL_DAMAGE_PREVENTED"); - - ListSubItemSet (list, i++, 1, s); - } - - // Encryption algorithm - ListItemAdd (list, i, GetString ("ENCRYPTION_ALGORITHM")); - - if (prop.ea < EAGetFirst() || prop.ea > EAGetCount ()) - { - ListSubItemSet (list, i, 1, L"?"); - return 1; - } - - EAGetName (szTmp, prop.ea, 1); - ListSubItemSet (list, i++, 1, szTmp); - - // Key size(s) - { - wchar_t name[128]; - int size = EAGetKeySize (prop.ea); - EAGetName (name, prop.ea, 1); - - // Primary key - ListItemAdd (list, i, GetString ("KEY_SIZE")); - StringCbPrintfW (sw, sizeof(sw), L"%d %s", size * 8, GetString ("BITS")); - ListSubItemSet (list, i++, 1, sw); - - if (wcscmp (EAGetModeName (prop.ea, prop.mode, TRUE), L"XTS") == 0) - { - // Secondary key (XTS) - - ListItemAdd (list, i, GetString ("SECONDARY_KEY_SIZE_XTS")); - ListSubItemSet (list, i++, 1, sw); - } - } - - // Block size - ListItemAdd (list, i, GetString ("BLOCK_SIZE")); - - StringCbPrintfW (sw, sizeof(sw), L"%d ", CipherGetBlockSize (EAGetFirstCipher(prop.ea))*8); - StringCbCatW (sw, sizeof(sw), GetString ("BITS")); - ListSubItemSet (list, i++, 1, sw); - - // Mode - ListItemAdd (list, i, GetString ("MODE_OF_OPERATION")); - ListSubItemSet (list, i++, 1, EAGetModeName (prop.ea, prop.mode, TRUE)); - - // PKCS 5 PRF - ListItemAdd (list, i, GetString ("PKCS5_PRF")); - if (prop.volumePim == 0) - ListSubItemSet (list, i++, 1, get_pkcs5_prf_name (prop.pkcs5)); - else - { - StringCbPrintfW (szTmp, sizeof(szTmp), L"%s (Dynamic)", get_pkcs5_prf_name (prop.pkcs5)); - ListSubItemSet (list, i++, 1, szTmp); - } - -#if 0 - // PCKS 5 iterations - ListItemAdd (list, i, GetString ("PKCS5_ITERATIONS")); - sprintf (szTmp, "%d", prop.pkcs5Iterations); - ListSubItemSet (list, i++, 1, szTmp); -#endif - -#if 0 - { - // Legacy - - FILETIME ft, curFt; - LARGE_INTEGER ft64, curFt64; - SYSTEMTIME st; - wchar_t date[128]; - memset (date, 0, sizeof (date)); - - // Volume date - ListItemAdd (list, i, GetString ("VOLUME_CREATE_DATE")); - *(unsigned __int64 *)(&ft) = prop.volumeCreationTime; - FileTimeToSystemTime (&ft, &st); - GetDateFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2); - swprintf (date, L"%s ", sw); - GetTimeFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2); - wcscat (date, sw); - ListSubItemSet (list, i++, 1, date); - - // Header date - ListItemAdd (list, i, GetString ("VOLUME_HEADER_DATE")); - *(unsigned __int64 *)(&ft) = prop.headerCreationTime; - FileTimeToSystemTime (&ft, &st); - GetDateFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2); - swprintf (date, L"%s ", sw); - GetTimeFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2); - wcscat (date, sw); - - GetLocalTime (&st); - SystemTimeToFileTime (&st, &curFt); - curFt64.HighPart = curFt.dwHighDateTime; - curFt64.LowPart = curFt.dwLowDateTime; - ft64.HighPart = ft.dwHighDateTime; - ft64.LowPart = ft.dwLowDateTime; - swprintf (date + wcslen (date), GetString ("VOLUME_HEADER_DAYS") - , (curFt64.QuadPart - ft64.QuadPart)/(24LL*3600*10000000)); - ListSubItemSet (list, i++, 1, date); - } -#endif // 0 - - if (!bSysEnc || IsHiddenOSRunning()) - { - // Volume format version - ListItemAdd (list, i, GetString ("VOLUME_FORMAT_VERSION")); - StringCbPrintfW (szTmp, sizeof(szTmp), L"%d", prop.volFormatVersion); - ListSubItemSet (list, i++, 1, szTmp); - - // Backup header - ListItemAdd (list, i, GetString ("BACKUP_HEADER")); - ListSubItemSet (list, i++, 1, GetString (prop.volFormatVersion > 1 ? "UISTR_YES" : "UISTR_NO")); - } - - // Total data read - ListItemAdd (list, i, GetString ("TOTAL_DATA_READ")); - GetSizeString (prop.totalBytesRead, sw, sizeof(sw)); - ListSubItemSet (list, i++, 1, sw); - - // Total data written - ListItemAdd (list, i, GetString ("TOTAL_DATA_WRITTEN")); - GetSizeString (prop.totalBytesWritten, sw, sizeof(sw)); - ListSubItemSet (list, i++, 1, sw); - - if (bSysEnc) - { - // TrueCrypt Boot Loader version - ListItemAdd (list, i, GetString ("VC_BOOT_LOADER_VERSION")); - ListSubItemSet (list, i++, 1, GetUserFriendlyVersionString (BootEncStatus.BootLoaderVersion).c_str()); - - // Encrypted portion - ListItemAdd (list, i, GetString ("ENCRYPTED_PORTION")); - if (GetSysEncDeviceEncryptedPartSize (FALSE) == GetSysEncDeviceSize (FALSE)) - ListSubItemSet (list, i++, 1, GetString ("ENCRYPTED_PORTION_FULLY_ENCRYPTED")); - else if (GetSysEncDeviceEncryptedPartSize (FALSE) <= 1) - ListSubItemSet (list, i++, 1, GetString ("ENCRYPTED_PORTION_NOT_ENCRYPTED")); - else - { - - StringCbPrintfW (sw, - sizeof sw, - GetString ("PROCESSED_PORTION_X_PERCENT"), - (double) GetSysEncDeviceEncryptedPartSize (FALSE) / (double) GetSysEncDeviceSize (FALSE) * 100.0); - - ListSubItemSet (list, i++, 1, sw); - } - } - - return 0; - } - - case WM_NOTIFY: - - if(wParam == IDC_VOLUME_PROPERTIES_LIST) - { - /* Right click */ - - switch (((NM_LISTVIEW *) lParam)->hdr.code) - { - case NM_RCLICK: - case LVN_BEGINRDRAG: - /* If the mouse was moving while the right mouse button is pressed, popup menu would - not open, because drag&drop operation would be initiated. Therefore, we're handling - RMB drag-and-drop operations as well. */ - { - - DisplayVolumePropertiesListContextMenu (hwndDlg, lParam); - - return 1; - } - } - } - return 0; - - case WM_CONTEXTMENU: - { - HWND hList = GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES_LIST); - // only handle if it is coming from keyboard and if the drive - // list has focus. The other cases are handled elsewhere - if ( (-1 == GET_X_LPARAM(lParam)) - && (-1 == GET_Y_LPARAM(lParam)) - && (GetFocus () == hList) - ) - { - DisplayVolumePropertiesListContextMenu (hwndDlg, NULL); - } - } - return 0; - - case WM_COMMAND: - if (lw == IDOK) - { - EndDialog (hwndDlg, lw); - return 1; - } - return 0; - - case WM_CLOSE: - EndDialog (hwndDlg, lw); - return 1; - } - - return 0; -} - - -BOOL CALLBACK TravelerDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - static BOOL bAutoRunWarningDisplayed = FALSE; - - switch (msg) - { - case WM_INITDIALOG: - { - WCHAR i; - int index; - WCHAR drive[] = { 0, L':', 0 }; - - LocalizeDialog (hwndDlg, "IDD_TRAVELER_DLG"); - - SendDlgItemMessage (hwndDlg, IDC_COPY_WIZARD, BM_SETCHECK, - BST_CHECKED, 0); - - SendDlgItemMessage (hwndDlg, IDC_COPY_EXPANDER, BM_SETCHECK, - BST_CHECKED, 0); - - SendDlgItemMessage (hwndDlg, IDC_TRAVEL_OPEN_EXPLORER, BM_SETCHECK, - BST_CHECKED, 0); - - SendDlgItemMessage (hwndDlg, IDC_AUTORUN_DISABLE, BM_SETCHECK, - BST_CHECKED, 0); - - SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_RESETCONTENT, 0, 0); - - index = (int) SendDlgItemMessageW (hwndDlg, IDC_DRIVELIST, CB_ADDSTRING, 0, (LPARAM) GetString ("FIRST_AVAILABLE")); - SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_SETITEMDATA, index, (LPARAM) 0); - - for (i = L'A'; i <= L'Z'; i++) - { - if (i == L'C') - continue; - drive[0] = i; - index = (int) SendDlgItemMessageW (hwndDlg, IDC_DRIVELIST, CB_ADDSTRING, 0, (LPARAM) drive); - SendDlgItemMessageW (hwndDlg, IDC_DRIVELIST, CB_SETITEMDATA, index, (LPARAM) i); - } - - SendDlgItemMessageW (hwndDlg, IDC_DRIVELIST, CB_SETCURSEL, 0, 0); - - return 0; - } - - case WM_CTLCOLORSTATIC: - { - HDC hdc = (HDC) wParam; - HWND hw = (HWND) lParam; - if (hw == GetDlgItem(hwndDlg, IDC_DIRECTORY)) - { - // This the directory field. Make its background like normal edit - HBRUSH hbr = GetSysColorBrush (COLOR_WINDOW); - ::SelectObject(hdc, hbr); - return (BOOL) hbr; - } - } - return 0; - - case WM_COMMAND: - - if (HIWORD (wParam) == BN_CLICKED - && (lw == IDC_AUTORUN_DISABLE || lw == IDC_AUTORUN_MOUNT || lw == IDC_AUTORUN_START )) - { - BOOL enabled = IsButtonChecked (GetDlgItem (hwndDlg, IDC_AUTORUN_MOUNT)); - - EnableWindow (GetDlgItem (hwndDlg, IDC_BROWSE_FILES), enabled); - EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_NAME), enabled); - EnableWindow (GetDlgItem (hwndDlg, IDC_TRAVEL_OPEN_EXPLORER), enabled); - EnableWindow (GetDlgItem (hwndDlg, IDC_TRAV_CACHE_PASSWORDS), enabled); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PIM), enabled); - EnableWindow (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY), enabled); - EnableWindow (GetDlgItem (hwndDlg, IDC_DRIVELIST), enabled); - EnableWindow (GetDlgItem (hwndDlg, IDT_TRAVELER_MOUNT), enabled); - EnableWindow (GetDlgItem (hwndDlg, IDT_MOUNT_LETTER), enabled); - EnableWindow (GetDlgItem (hwndDlg, IDT_MOUNT_SETTINGS), enabled); - - if (!bAutoRunWarningDisplayed - && (lw == IDC_AUTORUN_MOUNT || lw == IDC_AUTORUN_START)) - { - bAutoRunWarningDisplayed = TRUE; - Warning ("AUTORUN_MAY_NOT_ALWAYS_WORK", hwndDlg); - } - - return 1; - } - - if (lw == IDC_BROWSE_FILES) - { - wchar_t dstDir[MAX_PATH]; - wchar_t volName[MAX_PATH] = { 0 }; - - GetDlgItemText (hwndDlg, IDC_DIRECTORY, dstDir, ARRAYSIZE (dstDir)); - - if (BrowseFilesInDir (hwndDlg, "OPEN_TITLE", dstDir, volName, bHistory, FALSE, NULL)) - SetDlgItemText (hwndDlg, IDC_VOLUME_NAME, wcschr (volName, L'\\') + 1); - - return 1; - } - - if (lw == IDC_BROWSE_DIRS) - { - wchar_t dstPath[MAX_PATH * 2]; - GetDlgItemText (hwndDlg, IDC_DIRECTORY, dstPath, ARRAYSIZE (dstPath)); - - if (BrowseDirectories (hwndDlg, "SELECT_DEST_DIR", dstPath)) - SetDlgItemText (hwndDlg, IDC_DIRECTORY, dstPath); - - return 1; - } - - if (lw == IDCANCEL || lw == IDCLOSE) - { - EndDialog (hwndDlg, lw); - return 1; - } - - if (lw == IDC_CREATE) - { - - BOOL copyWizard, copyExpander, bExplore, bCacheInDriver, bIncludePimInCache, bAutoRun, bAutoMount, bMountReadOnly; - WCHAR dstDir[MAX_PATH + 1]; - WCHAR srcPath[1024 + MAX_PATH + 1]; - WCHAR dstPath[2*MAX_PATH + 1]; - WCHAR appDir[1024]; - WCHAR volName[MAX_PATH + 2]; - int drive; - WCHAR* ptr; - - GetDlgItemTextW (hwndDlg, IDC_DIRECTORY, dstDir, array_capacity (dstDir)); - volName[0] = 0; - GetDlgItemTextW (hwndDlg, IDC_VOLUME_NAME, volName + 1, (array_capacity (volName)) - 1); - - drive = (int) SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_GETCURSEL, 0, 0); - drive = (int) SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_GETITEMDATA, drive, 0); - - copyWizard = IsButtonChecked (GetDlgItem (hwndDlg, IDC_COPY_WIZARD)); - copyExpander = IsButtonChecked (GetDlgItem (hwndDlg, IDC_COPY_EXPANDER)); - bExplore = IsButtonChecked (GetDlgItem (hwndDlg, IDC_TRAVEL_OPEN_EXPLORER)); - bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_TRAV_CACHE_PASSWORDS)); - bIncludePimInCache = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PIM)); - bMountReadOnly = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY)); - bAutoRun = !IsButtonChecked (GetDlgItem (hwndDlg, IDC_AUTORUN_DISABLE)); - bAutoMount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_AUTORUN_MOUNT)); - - if (dstDir[0] == 0) - { - SetFocus (GetDlgItem (hwndDlg, IDC_DIRECTORY)); - MessageBoxW (hwndDlg, GetString ("NO_PATH_SELECTED"), lpszTitle, MB_ICONEXCLAMATION); - return 1; - } - - - if (bAutoMount && volName[1] == 0) - { - SetFocus (GetDlgItem (hwndDlg, IDC_VOLUME_NAME)); - MessageBoxW (hwndDlg, GetString ("NO_FILE_SELECTED"), lpszTitle, MB_ICONEXCLAMATION); - return 1; - } - - if (volName[1] != 0) - { - volName[0] = L'"'; - StringCbCatW (volName, sizeof(volName), L"\""); - } - - GetModuleFileNameW (NULL, appDir, array_capacity (appDir)); - if (ptr = wcsrchr (appDir, L'\\')) - ptr[0] = 0; - - WaitCursor (); - - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt", dstDir); - if (!CreateDirectoryW (dstPath, NULL)) - { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; - } - - // Main app 32-bit - if (Is64BitOs () && !IsNonInstallMode ()) - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt-x86.exe", appDir); - else - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt.exe", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt.exe", dstDir); - if (!TCCopyFile (srcPath, dstPath)) - { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; - } - - // Main app 64-bit - if (Is64BitOs () && !IsNonInstallMode ()) - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt.exe", appDir); - else - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt-x64.exe", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt-x64.exe", dstDir); - if (!TCCopyFile (srcPath, dstPath)) - { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; - } - - // Wizard - if (copyWizard) - { - // Wizard 32-bit - if (Is64BitOs () && !IsNonInstallMode ()) - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format-x86.exe", appDir); - else - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format.exe", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format.exe", dstDir); - if (!TCCopyFile (srcPath, dstPath)) - { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; - } - - // Wizard 64-bit - if (Is64BitOs () && !IsNonInstallMode ()) - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format.exe", appDir); - else - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format-x64.exe", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format-x64.exe", dstDir); - if (!TCCopyFile (srcPath, dstPath)) - { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; - } - } - - // Expander - if (copyExpander) - { - // Expander 32-bit - if (Is64BitOs () && !IsNonInstallMode ()) - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander-x86.exe", appDir); - else - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander.exe", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander.exe", dstDir); - if (!TCCopyFile (srcPath, dstPath)) - { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; - } - - // Expander 64-bit - if (Is64BitOs () && !IsNonInstallMode ()) - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander.exe", appDir); - else - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander-x64.exe", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander-x64.exe", dstDir); - if (!TCCopyFile (srcPath, dstPath)) - { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; - } - } - - // Driver - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\veracrypt.sys", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt.sys", dstDir); - if (!TCCopyFile (srcPath, dstPath)) - { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; - } - - // Driver x64 - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\veracrypt-x64.sys", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt-x64.sys", dstDir); - if (!TCCopyFile (srcPath, dstPath)) - { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; - } - - if (strcmp (GetPreferredLangId (), "en") != 0) - { - // Language pack - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\Language.%hs.xml", appDir, GetPreferredLangId ()); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\Language.%hs.xml", dstDir, GetPreferredLangId ()); - TCCopyFile (srcPath, dstPath); - } - - // AutoRun - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\autorun.inf", dstDir); - DeleteFileW (dstPath); - if (bAutoRun) - { - FILE *af; - wchar_t autoMount[2*MAX_PATH + 2]; - wchar_t driveLetter[] = { L' ', L'/', L'l', L' ', (wchar_t) drive, 0 }; - - af = _wfopen (dstPath, L"w,ccs=UNICODE"); - - if (af == NULL) - { - MessageBoxW (hwndDlg, GetString ("CANT_CREATE_AUTORUN"), lpszTitle, MB_ICONERROR); - goto stop; - } - - StringCbPrintfW (autoMount, sizeof(autoMount), L"VeraCrypt\\VeraCrypt.exe /q background%s%s%s%s /m rm /v %s", - drive > 0 ? driveLetter : L"", - bExplore ? L" /e" : L"", - bCacheInDriver ? (bIncludePimInCache? L" /c p" : L" /c y") : L"", - bMountReadOnly ? L" /m ro" : L"", - volName); - - fwprintf (af, L"[autorun]\nlabel=%s\nicon=VeraCrypt\\VeraCrypt.exe\n", GetString ("TC_TRAVELER_DISK")); - fwprintf (af, L"action=%s\n", bAutoMount ? GetString ("MOUNT_TC_VOLUME") : GetString ("IDC_PREF_LOGON_START")); - fwprintf (af, L"open=%s\n", bAutoMount ? autoMount : L"VeraCrypt\\VeraCrypt.exe"); - fwprintf (af, L"shell\\start=%s\nshell\\start\\command=VeraCrypt\\VeraCrypt.exe\n", GetString ("IDC_PREF_LOGON_START")); - fwprintf (af, L"shell\\dismount=%s\nshell\\dismount\\command=VeraCrypt\\VeraCrypt.exe /q /d\n", GetString ("DISMOUNT_ALL_TC_VOLUMES")); - - CheckFileStreamWriteErrors (hwndDlg, af, dstPath); - fclose (af); - } - MessageBoxW (hwndDlg, GetString ("TRAVELER_DISK_CREATED"), lpszTitle, MB_ICONINFORMATION); - -stop: - NormalCursor (); - return 1; - } - return 0; - } - - return 0; -} - -void BuildTree (HWND hwndDlg, HWND hTree) -{ - HIMAGELIST hList; - HBITMAP hBitmap, hBitmapMask; - LVCOLUMNW lvCol; - - ListView_DeleteColumn (hTree,0); - ListView_DeleteColumn (hTree,0); - ListView_DeleteColumn (hTree,0); - ListView_DeleteColumn (hTree,0); - ListView_DeleteColumn (hTree,0); - ListView_DeleteColumn (hTree,0); - - SendMessage(hTree,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 ("DRIVE"); - lvCol.cx = CompensateXDPI (38); - lvCol.fmt = LVCFMT_COL_HAS_IMAGES|LVCFMT_LEFT ; - SendMessage (hTree,LVM_INSERTCOLUMNW,0,(LPARAM)&lvCol); - - lvCol.pszText = GetString ("VOLUME"); - lvCol.cx = CompensateXDPI (200); - lvCol.fmt = LVCFMT_LEFT; - SendMessage (hTree,LVM_INSERTCOLUMNW,1,(LPARAM)&lvCol); - LastDriveListVolumeColumnWidth = ListView_GetColumnWidth (hTree, 1); - - lvCol.pszText = GetString ("SIZE"); - lvCol.cx = CompensateXDPI (55); - lvCol.fmt = LVCFMT_RIGHT; - SendMessage (hTree,LVM_INSERTCOLUMNW,2,(LPARAM)&lvCol); - - lvCol.pszText = GetString ("ENCRYPTION_ALGORITHM_LV"); - lvCol.cx = CompensateXDPI (123); - lvCol.fmt = LVCFMT_LEFT; - SendMessage (hTree,LVM_INSERTCOLUMNW,3,(LPARAM)&lvCol); - - lvCol.pszText = GetString ("TYPE"); - lvCol.cx = CompensateXDPI (100); - lvCol.fmt = LVCFMT_LEFT; - SendMessage (hTree,LVM_INSERTCOLUMNW,4,(LPARAM)&lvCol); - - // Regular drive icon - - hBitmap = LoadBitmap (hInst, MAKEINTRESOURCE (IDB_DRIVEICON)); - if (hBitmap == NULL) - return; - hBitmapMask = LoadBitmap (hInst, MAKEINTRESOURCE (IDB_DRIVEICON_MASK)); - - hList = CreateImageList (16, 12, ILC_COLOR8|ILC_MASK, 2, 2); - if (AddBitmapToImageList (hList, hBitmap, hBitmapMask) == -1) - { - DeleteObject (hBitmap); - DeleteObject (hBitmapMask); - return; - } - else - { - DeleteObject (hBitmap); - DeleteObject (hBitmapMask); - } - - // System drive icon - - hBitmap = LoadBitmap (hInst, MAKEINTRESOURCE (IDB_SYS_DRIVEICON)); - if (hBitmap == NULL) - return; - hBitmapMask = LoadBitmap (hInst, MAKEINTRESOURCE (IDB_SYS_DRIVEICON_MASK)); - - if (AddBitmapToImageList (hList, hBitmap, hBitmapMask) == -1) - { - DeleteObject (hBitmap); - DeleteObject (hBitmapMask); - return; - } - else - { - DeleteObject (hBitmap); - DeleteObject (hBitmapMask); - } - - ListView_SetImageList (hTree, hList, LVSIL_NORMAL); - ListView_SetImageList (hTree, hList, LVSIL_SMALL); - - LoadDriveLetters (hwndDlg, hTree, 0); -} - -LPARAM GetSelectedLong (HWND hTree) -{ - int hItem = ListView_GetSelectionMark (hTree); - LVITEM item; - - if (nSelectedDriveIndex >= 0) - hItem = nSelectedDriveIndex; - - memset(&item, 0, sizeof(LVITEM)); - item.mask = LVIF_PARAM; - item.iItem = hItem; - - if ( (ListView_GetItemCount (hTree) < 1) - || (ListView_GetItem (hTree, &item) == FALSE) - ) - return MAKELONG (0xffff, 0xffff); - else - return item.lParam; -} - -LPARAM GetItemLong (HWND hTree, int itemNo) -{ - LVITEM item; - - memset(&item, 0, sizeof(LVITEM)); - item.mask = LVIF_PARAM; - item.iItem = itemNo; - - if (ListView_GetItem (hTree, &item) == FALSE) - return MAKELONG (0xffff, 0xffff); - else - return item.lParam; -} - -static int AskVolumePassword (HWND hwndDlg, Password *password, int *pkcs5, int *pim, BOOL* truecryptMode, char *titleStringId, BOOL enableMountOptions) -{ - INT_PTR result; - PasswordDlgParam dlgParam; - - PasswordDialogTitleStringId = titleStringId; - PasswordDialogDisableMountOptions = !enableMountOptions; - - dlgParam.password = password; - dlgParam.pkcs5 = pkcs5; - dlgParam.pim = pim; - dlgParam.truecryptMode = truecryptMode; - - result = DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_PASSWORD_DLG), hwndDlg, - (DLGPROC) PasswordDlgProc, (LPARAM) &dlgParam); - - if (result != IDOK) - { - password->Length = 0; - *pkcs5 = 0; - *pim = -1; - *truecryptMode = FALSE; - burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); - burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); - } - - return result == IDOK; -} - -// GUI actions - -static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim) -{ - BOOL status = FALSE; - wchar_t fileName[MAX_PATH]; - int mounted = 0, EffectiveVolumePkcs5 = CmdVolumePkcs5; - BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; - int EffectiveVolumePim = (pim < 0)? CmdVolumePim : pim; - BOOL bEffectiveCacheDuringMultipleMount = bCmdCacheDuringMultipleMount? TRUE: bCacheDuringMultipleMount; - BOOL bEffectiveTryEmptyPasswordWhenKeyfileUsed = bCmdTryEmptyPasswordWhenKeyfileUsedValid? bCmdTryEmptyPasswordWhenKeyfileUsed : bTryEmptyPasswordWhenKeyfileUsed; - BOOL bUseCmdVolumePassword = CmdVolumePasswordValid && ((CmdVolumePassword.Length > 0) || (KeyFilesEnable && FirstKeyFile)); - - /* Priority is given to command line parameters - * Default values used only when nothing specified in command line - */ - if (EffectiveVolumePkcs5 == 0) - EffectiveVolumePkcs5 = DefaultVolumePkcs5; - if (!EffectiveVolumeTrueCryptMode) - EffectiveVolumeTrueCryptMode = DefaultVolumeTrueCryptMode; - - bPrebootPasswordDlgMode = mountOptions.PartitionInInactiveSysEncScope; - - if (nDosDriveNo == -1) - nDosDriveNo = HIWORD (GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST))) - L'A'; - - if (!MultipleMountOperationInProgress) - { - VolumePassword.Length = 0; - VolumePkcs5 = 0; - VolumeTrueCryptMode = FALSE; - VolumePim = -1; - } - - if (szFileName == NULL) - { - GetVolumePath (hwndDlg, fileName, ARRAYSIZE (fileName)); - } - else - StringCchCopyW (fileName, ARRAYSIZE (fileName), szFileName); - - if (wcslen(fileName) == 0) - { - status = FALSE; - goto ret; - } - - if (!TranslateVolumeID (hwndDlg, fileName, ARRAYSIZE (fileName))) - { - status = FALSE; - goto ret; - } - - szFileName = fileName; - - if (IsMountedVolume (szFileName)) - { - Warning ("VOL_ALREADY_MOUNTED", hwndDlg); - status = FALSE; - goto ret; - } - - if (!VolumePathExists (szFileName)) - { - if (!MultipleMountOperationInProgress) - handleWin32Error (hwndDlg, SRC_POS); - - status = FALSE; - goto ret; - } - - ResetWrongPwdRetryCount (); - - WaitCursor (); - - if (!bUseCmdVolumePassword) - { - // First try cached passwords and if they fail ask user for a new one - // try TrueCrypt mode first since it is quick, only if no custom pim specified - if (EffectiveVolumePim <= 0) - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, 0, 0, TRUE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); - if (!mounted) - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, 0, EffectiveVolumePim, FALSE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); - - // If keyfiles are enabled, test empty password first - if (!mounted && KeyFilesEnable && FirstKeyFile && bEffectiveTryEmptyPasswordWhenKeyfileUsed) - { - Password emptyPassword; - emptyPassword.Length = 0; - - KeyFilesApply (hwndDlg, &emptyPassword, FirstKeyFile, szFileName); - // try TrueCrypt mode first since it is quick, only if no custom pim specified - if (EffectiveVolumePim <= 0) - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &emptyPassword, 0, 0, TRUE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); - if (!mounted) - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &emptyPassword, 0, EffectiveVolumePim, FALSE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); - - burn (&emptyPassword, sizeof (emptyPassword)); - } - } - - // Test password and/or keyfiles used for the previous volume - if (!mounted && bEffectiveCacheDuringMultipleMount && MultipleMountOperationInProgress && VolumePassword.Length != 0) - { - // try TrueCrypt mode first as it is quick, only if no custom pim specified - if (EffectiveVolumePim <= 0) - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, 0, 0, TRUE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); - if (!mounted) - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, 0, EffectiveVolumePim, FALSE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); - } - - NormalCursor (); - - if (mounted) - { - - // Check for problematic file extensions (exe, dll, sys) - if (CheckFileExtension(szFileName)) - Warning ("EXE_FILE_EXTENSION_MOUNT_WARNING", hwndDlg); - } - - while (mounted == 0) - { - if (bUseCmdVolumePassword) - { - VolumePassword = CmdVolumePassword; - VolumePkcs5 = EffectiveVolumePkcs5; - VolumeTrueCryptMode = EffectiveVolumeTrueCryptMode; - VolumePim = EffectiveVolumePim; - } - else if (!Silent) - { - int GuiPkcs5 = EffectiveVolumePkcs5; - BOOL GuiTrueCryptMode = EffectiveVolumeTrueCryptMode; - int GuiPim = EffectiveVolumePim; - StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume), szFileName); - - if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &GuiTrueCryptMode, NULL, TRUE)) - goto ret; - else - { - VolumePkcs5 = GuiPkcs5; - VolumeTrueCryptMode = GuiTrueCryptMode; - VolumePim = GuiPim; - burn (&GuiPkcs5, sizeof(GuiPkcs5)); - burn (&GuiTrueCryptMode, sizeof(GuiTrueCryptMode)); - burn (&GuiPim, sizeof(GuiPim)); - } - } - - WaitCursor (); - - if (KeyFilesEnable) - KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, szFileName); - - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, !Silent); - NormalCursor (); - - // Check for problematic file extensions (exe, dll, sys) - if (mounted > 0 && CheckFileExtension (szFileName)) - Warning ("EXE_FILE_EXTENSION_MOUNT_WARNING", hwndDlg); - - if (!MultipleMountOperationInProgress) - { - burn (&VolumePassword, sizeof (VolumePassword)); - burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); - burn (&VolumePim, sizeof (VolumePim)); - } - - burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); - burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); - - if (CmdVolumePassword.Length > 0 || Silent) - break; - } - - if (mounted > 0) - { - status = TRUE; - - if (bBeep) - MessageBeep (0xFFFFFFFF); - - RefreshMainDlg(MainDlg); - - if (bExplore) - { - WaitCursor(); - OpenVolumeExplorerWindow (nDosDriveNo); - NormalCursor(); - } - - if (mountOptions.ProtectHiddenVolume) - Info ("HIDVOL_PROT_WARN_AFTER_MOUNT", hwndDlg); - } - -ret: - if (!MultipleMountOperationInProgress) - { - burn (&VolumePassword, sizeof (VolumePassword)); - burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); - burn (&VolumePim, sizeof (VolumePim)); - } - - burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); - burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); - - RestoreDefaultKeyFilesParam (); - - if (UsePreferences) - bCacheInDriver = bCacheInDriverDefault; - - if (status && CloseSecurityTokenSessionsAfterMount && !MultipleMountOperationInProgress) - SecurityToken::CloseAllSessions(); - - return status; -} - - -static BOOL Dismount (HWND hwndDlg, int nDosDriveNo) -{ - BOOL status = FALSE; - WaitCursor (); - - if (nDosDriveNo == -2) - nDosDriveNo = (char) (HIWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) - L'A'); - - if (bCloseDismountedWindows) - { - CloseVolumeExplorerWindows (hwndDlg, nDosDriveNo); - } - - if (UnmountVolume (hwndDlg, nDosDriveNo, bForceUnmount)) - { - status = TRUE; - - if (bBeep) - MessageBeep (0xFFFFFFFF); - RefreshMainDlg (hwndDlg); - - if (nCurrentOS == WIN_2000 && RemoteSession && !IsAdmin ()) - LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), 0); - } - - NormalCursor (); - return status; -} - -void __cdecl mountThreadFunction (void *hwndDlgArg) -{ - HWND hwndDlg =(HWND) hwndDlgArg; - BOOL bIsForeground = (GetForegroundWindow () == hwndDlg)? TRUE : FALSE; - // Disable parent dialog during processing to avoid user interaction - EnableWindow(hwndDlg, FALSE); - finally_do_arg2 (HWND, hwndDlg, BOOL, bIsForeground, { EnableWindow(finally_arg, TRUE); if (finally_arg2) BringToForeground (finally_arg); bPrebootPasswordDlgMode = FALSE;}); - - Mount (hwndDlg, -1, 0, -1); -} - -typedef struct -{ - UNMOUNT_STRUCT* punmount; - BOOL interact; - int dismountMaxRetries; - int dismountAutoRetryDelay; - BOOL* pbResult; - DWORD* pdwResult; - DWORD dwLastError; - BOOL bReturn; -} DismountAllThreadParam; - -void CALLBACK DismountAllThreadProc(void* pArg, HWND hwndDlg) -{ - DismountAllThreadParam* pThreadParam = (DismountAllThreadParam*) pArg; - UNMOUNT_STRUCT* punmount = pThreadParam->punmount; - BOOL* pbResult = pThreadParam->pbResult; - DWORD* pdwResult = pThreadParam->pdwResult; - int dismountMaxRetries = pThreadParam->dismountMaxRetries; - int dismountAutoRetryDelay = pThreadParam->dismountAutoRetryDelay; - - do - { - *pbResult = DeviceIoControl (hDriver, TC_IOCTL_DISMOUNT_ALL_VOLUMES, punmount, - sizeof (UNMOUNT_STRUCT), punmount, sizeof (UNMOUNT_STRUCT), pdwResult, NULL); - - if ( punmount->nDosDriveNo < 0 || punmount->nDosDriveNo > 25 - || (punmount->ignoreOpenFiles != TRUE && punmount->ignoreOpenFiles != FALSE) - || (punmount->HiddenVolumeProtectionTriggered != TRUE && punmount->HiddenVolumeProtectionTriggered != FALSE) - || (punmount->nReturnCode < 0) - ) - { - if (*pbResult) - SetLastError (ERROR_INTERNAL_ERROR); - *pbResult = FALSE; - } - - if (*pbResult == FALSE) - { - NormalCursor(); - handleWin32Error (hwndDlg, SRC_POS); - pThreadParam->dwLastError = GetLastError (); - pThreadParam->bReturn = FALSE; - return; - } - - if (punmount->nReturnCode == ERR_SUCCESS - && punmount->HiddenVolumeProtectionTriggered - && !VolumeNotificationsList.bHidVolDamagePrevReported [punmount->nDosDriveNo] - && pThreadParam->interact - && !Silent) - { - wchar_t msg[4096]; - - VolumeNotificationsList.bHidVolDamagePrevReported [punmount->nDosDriveNo] = TRUE; - - StringCbPrintfW (msg, sizeof(msg), GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), punmount->nDosDriveNo + L'A'); - SetForegroundWindow (hwndDlg); - MessageBoxW (hwndDlg, msg, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); - - punmount->HiddenVolumeProtectionTriggered = FALSE; - continue; - } - - if (punmount->nReturnCode == ERR_FILES_OPEN) - Sleep (dismountAutoRetryDelay); - else - break; - - } while (--dismountMaxRetries > 0); - - pThreadParam->dwLastError = GetLastError (); - pThreadParam->bReturn = TRUE; -} - -static BOOL DismountAll (HWND hwndDlg, BOOL forceUnmount, BOOL interact, int dismountMaxRetries, int dismountAutoRetryDelay) -{ - BOOL status = TRUE; - MOUNT_LIST_STRUCT mountList = {0}; - DWORD dwResult; - UNMOUNT_STRUCT unmount = {0}; - BOOL bResult; - MOUNT_LIST_STRUCT prevMountList = {0}; - int i; - DismountAllThreadParam dismountAllThreadParam; - -retry: - WaitCursor(); - - DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mountList, sizeof (mountList), &mountList, sizeof (mountList), &dwResult, NULL); - - if (mountList.ulMountedDrives == 0) - { - NormalCursor(); - return TRUE; - } - - BroadcastDeviceChange (DBT_DEVICEREMOVEPENDING, 0, mountList.ulMountedDrives); - - memcpy (&prevMountList, &mountList, sizeof (mountList)); - - for (i = 0; i < 26; i++) - { - if (mountList.ulMountedDrives & (1 << i)) - { - if (bCloseDismountedWindows) - CloseVolumeExplorerWindows (hwndDlg, i); - } - } - - unmount.nDosDriveNo = 0; - unmount.ignoreOpenFiles = forceUnmount; - - dismountAllThreadParam.punmount = &unmount; - dismountAllThreadParam.interact = interact; - dismountAllThreadParam.dismountMaxRetries = dismountMaxRetries; - dismountAllThreadParam.dismountAutoRetryDelay = dismountAutoRetryDelay; - dismountAllThreadParam.pbResult = &bResult; - dismountAllThreadParam.pdwResult = &dwResult; - dismountAllThreadParam.dwLastError = ERROR_SUCCESS; - dismountAllThreadParam.bReturn = TRUE; - - if (interact && !Silent) - { - - ShowWaitDialog (hwndDlg, FALSE, DismountAllThreadProc, &dismountAllThreadParam); - } - else - DismountAllThreadProc (&dismountAllThreadParam, hwndDlg); - - SetLastError (dismountAllThreadParam.dwLastError); - - if (!dismountAllThreadParam.bReturn) - return FALSE; - - memset (&mountList, 0, sizeof (mountList)); - DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mountList, sizeof (mountList), &mountList, sizeof (mountList), &dwResult, NULL); - - // remove any custom label from registry - for (i = 0; i < 26; i++) - { - if ((prevMountList.ulMountedDrives & (1 << i)) && (!(mountList.ulMountedDrives & (1 << i))) && wcslen (prevMountList.wszLabel[i])) - { - UpdateDriveCustomLabel (i, prevMountList.wszLabel[i], FALSE); - } - } - - BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, 0, prevMountList.ulMountedDrives & ~mountList.ulMountedDrives); - - RefreshMainDlg (hwndDlg); - - if (nCurrentOS == WIN_2000 && RemoteSession && !IsAdmin ()) - LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), 0); - - NormalCursor(); - - if (unmount.nReturnCode != 0) - { - if (forceUnmount) - status = FALSE; - - if (unmount.nReturnCode == ERR_FILES_OPEN) - { - if (interact && IDYES == AskWarnYesNoTopmost ("UNMOUNTALL_LOCK_FAILED", hwndDlg)) - { - forceUnmount = TRUE; - goto retry; - } - - if (IsOSAtLeast (WIN_7)) - { - // Undo SHCNE_DRIVEREMOVED - DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, NULL, 0, &mountList, sizeof (mountList), &dwResult, NULL); - - for (i = 0; i < 26; i++) - { - if (mountList.ulMountedDrives & (1 << i)) - { - wchar_t root[] = { (wchar_t) i + L'A', L':', L'\\', 0 }; - SHChangeNotify (SHCNE_DRIVEADD, SHCNF_PATH, root, NULL); - } - } - } - - return FALSE; - } - - if (interact) - MessageBoxW (hwndDlg, GetString ("UNMOUNT_FAILED"), lpszTitle, MB_ICONERROR); - } - else - { - if (bBeep) - MessageBeep (0xFFFFFFFF); - } - - return status; -} - -static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) -{ - HWND driveList = GetDlgItem (MainDlg, IDC_DRIVELIST); - int selDrive = ListView_GetSelectionMark (driveList); - BOOL shared = FALSE, status = FALSE, bHeaderBakRetry = FALSE; - int mountedVolCount = 0; - vector devices; - int EffectiveVolumePkcs5 = CmdVolumePkcs5; - BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; - - /* Priority is given to command line parameters - * Default values used only when nothing specified in command line - */ - if (EffectiveVolumePkcs5 == 0) - EffectiveVolumePkcs5 = DefaultVolumePkcs5; - if (!EffectiveVolumeTrueCryptMode) - EffectiveVolumeTrueCryptMode = DefaultVolumeTrueCryptMode; - - VolumePassword.Length = 0; - mountOptions = defaultMountOptions; - bPrebootPasswordDlgMode = FALSE; - VolumePim = -1; - - if (selDrive == -1) - selDrive = 0; - - ResetWrongPwdRetryCount (); - - MultipleMountOperationInProgress = TRUE; - - do - { - if (!bHeaderBakRetry) - { - if (!CmdVolumePasswordValid && bPasswordPrompt) - { - int GuiPkcs5 = EffectiveVolumePkcs5; - BOOL GuiTrueCryptMode = EffectiveVolumeTrueCryptMode; - int GuiPim = CmdVolumePim; - PasswordDlgVolume[0] = '\0'; - if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &GuiTrueCryptMode, NULL, TRUE)) - goto ret; - else - { - VolumePkcs5 = GuiPkcs5; - VolumeTrueCryptMode = GuiTrueCryptMode; - VolumePim = GuiPim; - burn (&GuiPkcs5, sizeof(GuiPkcs5)); - burn (&GuiTrueCryptMode, sizeof(GuiTrueCryptMode)); - burn (&GuiPim, sizeof(GuiPim)); - } - } - else if (CmdVolumePasswordValid) - { - bPasswordPrompt = FALSE; - VolumePassword = CmdVolumePassword; - VolumePkcs5 = EffectiveVolumePkcs5; - VolumeTrueCryptMode = EffectiveVolumeTrueCryptMode; - VolumePim = CmdVolumePim; - } - - WaitCursor(); - - if (FirstCmdKeyFile) - KeyFilesApply (hwndDlg, &VolumePassword, FirstCmdKeyFile, NULL); - else if (KeyFilesEnable) - KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, NULL); - - } - - if (devices.empty()) - devices = GetAvailableHostDevices (true, false, true, true); - foreach (const HostDevice &drive, devices) - { - vector partitions = drive.Partitions; - partitions.insert (partitions.begin(), drive); - - foreach (const HostDevice &device, partitions) - { - wchar_t szFileName[TC_MAX_PATH]; - StringCbCopyW (szFileName, sizeof (szFileName), device.Path.c_str()); - BOOL mounted = IsMountedVolume (szFileName); - - // Skip other partitions of the disk if partition0 (whole disk) is mounted - if (!device.IsPartition && mounted) - break; - - if (device.Floppy) - break; - - if (device.HasUnencryptedFilesystem && !mountOptions.UseBackupHeader && !bHeaderBakRetry) - continue; - - if (!mounted) - { - int nDosDriveNo; - int driveAItem = -1, driveBItem = -1; - - while (LOWORD (GetItemLong (driveList, selDrive)) != 0xffff) - { - if(LOWORD (GetItemLong (driveList, selDrive)) != TC_MLIST_ITEM_FREE) - { - selDrive++; - continue; - } - nDosDriveNo = HIWORD(GetItemLong (driveList, selDrive)) - L'A'; - - /* don't use drives A: and B: for now until no other free drive found */ - if (nDosDriveNo == 0) - { - driveAItem = selDrive; - selDrive++; - continue; - } - if (nDosDriveNo == 1) - { - driveBItem = selDrive; - selDrive++; - continue; - } - break; - } - - if (LOWORD (GetItemLong (driveList, selDrive)) == 0xffff) - { - /* use A: or B: if available as a last resort */ - if (driveAItem >= 0) - { - nDosDriveNo = 0; - selDrive = driveAItem; - } - else if (driveBItem >= 0) - { - nDosDriveNo = 1; - selDrive = driveBItem; - } - else - goto ret; - } - - // First try user password then cached passwords - if ((mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, TRUE, FALSE)) > 0 - || ((VolumePassword.Length > 0) && ((mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, VolumePkcs5, VolumePim, VolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, TRUE, FALSE)) > 0))) - { - // A volume has been successfully mounted - - ResetWrongPwdRetryCount (); - - if (mounted == 2) - shared = TRUE; - - LoadDriveLetters (hwndDlg, driveList, (HIWORD (GetItemLong (GetDlgItem (MainDlg, IDC_DRIVELIST), selDrive)))); - selDrive++; - - if (bExplore) - { - WaitCursor(); - OpenVolumeExplorerWindow (nDosDriveNo); - NormalCursor(); - } - - if (bBeep) - MessageBeep (0xFFFFFFFF); - - status = TRUE; - - mountedVolCount++; - - // Skip other partitions of the disk if partition0 (whole disk) has been mounted - if (!device.IsPartition) - break; - } - } - } - } - - if (mountedVolCount < 1) - { - // Failed to mount any volume - - IncreaseWrongPwdRetryCount (1); - - if (WrongPwdRetryCountOverLimit () - && !mountOptions.UseBackupHeader - && !bHeaderBakRetry) - { - // Retry using embedded header backup (if any) - mountOptions.UseBackupHeader = TRUE; - bHeaderBakRetry = TRUE; - } - else if (bHeaderBakRetry) - { - mountOptions.UseBackupHeader = defaultMountOptions.UseBackupHeader; - bHeaderBakRetry = FALSE; - } - - if (!Silent && !bHeaderBakRetry) - { - WCHAR szTmp[4096]; - - StringCbPrintfW (szTmp, sizeof(szTmp), GetString (KeyFilesEnable || FirstCmdKeyFile ? "PASSWORD_OR_KEYFILE_WRONG_AUTOMOUNT" : "PASSWORD_WRONG_AUTOMOUNT")); - if (CheckCapsLock (hwndDlg, TRUE)) - StringCbCatW (szTmp, sizeof(szTmp), GetString ("PASSWORD_WRONG_CAPSLOCK_ON")); - - MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_ICONWARNING); - } - } - else if (bHeaderBakRetry) - { - // We have successfully mounted a volume using the header backup embedded in the volume (the header is damaged) - mountOptions.UseBackupHeader = defaultMountOptions.UseBackupHeader; - bHeaderBakRetry = FALSE; - - if (!Silent) - Warning ("HEADER_DAMAGED_AUTO_USED_HEADER_BAK", hwndDlg); - } - - if (!bHeaderBakRetry) - { - burn (&VolumePassword, sizeof (VolumePassword)); - burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); - burn (&VolumePim, sizeof (VolumePim)); - burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); - burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); - } - - } while (bPasswordPrompt && mountedVolCount < 1); - - /* One or more volumes successfully mounted */ - - ResetWrongPwdRetryCount (); - - if (shared) - Warning ("DEVICE_IN_USE_INFO", hwndDlg); - - if (mountOptions.ProtectHiddenVolume) - { - if (mountedVolCount > 1) - Info ("HIDVOL_PROT_WARN_AFTER_MOUNT_PLURAL", hwndDlg); - else if (mountedVolCount == 1) - Info ("HIDVOL_PROT_WARN_AFTER_MOUNT", hwndDlg); - } - - if (status && CloseSecurityTokenSessionsAfterMount) - SecurityToken::CloseAllSessions(); - -ret: - MultipleMountOperationInProgress = FALSE; - - burn (&VolumePassword, sizeof (VolumePassword)); - burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); - burn (&VolumePim, sizeof (VolumePim)); - burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); - burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); - - mountOptions.UseBackupHeader = defaultMountOptions.UseBackupHeader; - - RestoreDefaultKeyFilesParam (); - - if (UsePreferences) - bCacheInDriver = bCacheInDriverDefault; - - EnableDisableButtons (MainDlg); - - NormalCursor(); - - return status; -} - -typedef struct -{ - BOOL bPasswordPrompt; - BOOL bRet; -} MountAllDevicesThreadParam; - -void CALLBACK mountAllDevicesThreadProc(void* pArg, HWND hwndDlg) -{ - MountAllDevicesThreadParam* threadParam =(MountAllDevicesThreadParam*) pArg; - BOOL bPasswordPrompt = threadParam->bPasswordPrompt; - - threadParam->bRet = MountAllDevicesThreadCode (hwndDlg, bPasswordPrompt); -} - -static BOOL MountAllDevices (HWND hwndDlg, BOOL bPasswordPrompt) -{ - MountAllDevicesThreadParam param; - param.bPasswordPrompt = bPasswordPrompt; - param.bRet = FALSE; - - ShowWaitDialog (hwndDlg, FALSE, mountAllDevicesThreadProc, ¶m); - - return param.bRet; -} - -static void ChangePassword (HWND hwndDlg) -{ - INT_PTR result; - int newPimValue = -1; - - GetVolumePath (hwndDlg, szFileName, ARRAYSIZE (szFileName)); - - if (!TranslateVolumeID (hwndDlg, szFileName, ARRAYSIZE (szFileName))) - { - return; - } - - if (IsMountedVolume (szFileName)) - { - Warning (pwdChangeDlgMode == PCDM_CHANGE_PKCS5_PRF ? "MOUNTED_NO_PKCS5_PRF_CHANGE" : "MOUNTED_NOPWCHANGE", hwndDlg); - return; - } - - if (!VolumePathExists (szFileName)) - { - handleWin32Error (hwndDlg, SRC_POS); - return; - } - - bSysEncPwdChangeDlgMode = FALSE; - - result = DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_PASSWORDCHANGE_DLG), hwndDlg, - (DLGPROC) PasswordChangeDlgProc, (LPARAM) &newPimValue); - - if (result == IDOK) - { - switch (pwdChangeDlgMode) - { - case PCDM_CHANGE_PKCS5_PRF: - Info ("PKCS5_PRF_CHANGED", hwndDlg); - break; - - case PCDM_ADD_REMOVE_VOL_KEYFILES: - case PCDM_REMOVE_ALL_KEYFILES_FROM_VOL: - Info ("KEYFILE_CHANGED", hwndDlg); - break; - - case PCDM_CHANGE_PASSWORD: - default: - { - Info ("PASSWORD_CHANGED", hwndDlg); - if (newPimValue != -1) - { - // update the encoded volue in favorite XML if found - bool bFavoriteFound = false; - for (vector ::iterator favorite = FavoriteVolumes.begin(); - favorite != FavoriteVolumes.end(); favorite++) - { - if (favorite->Path == szFileName) - { - bFavoriteFound = true; - favorite->Pim = newPimValue; - SaveFavoriteVolumes (hwndDlg, FavoriteVolumes, false); - break; - } - } - - if (!bFavoriteFound) - { - for (vector ::iterator favorite = SystemFavoriteVolumes.begin(); - favorite != SystemFavoriteVolumes.end(); favorite++) - { - if (favorite->Path == szFileName) - { - bFavoriteFound = true; - favorite->Pim = newPimValue; - - if (AskYesNo("FAVORITE_PIM_CHANGED", hwndDlg) == IDYES) - { - SaveFavoriteVolumes (hwndDlg, SystemFavoriteVolumes, true); - } - break; - } - } - } - } - } - } - } -} - -// Change password of the system partition/drive -static void ChangeSysEncPassword (HWND hwndDlg, BOOL bOnlyChangeKDF) -{ - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - if (!BootEncStatus.DriveEncrypted - && !BootEncStatus.DriveMounted - && !BootEncStatus.VolumeHeaderPresent - && !SysEncryptionOrDecryptionRequired ()) - { - Warning ("SYS_DRIVE_NOT_ENCRYPTED", hwndDlg); - return; - } - - if (SysEncryptionOrDecryptionRequired () - || BootEncStatus.SetupInProgress) - { - Warning ("SYSTEM_ENCRYPTION_NOT_COMPLETED", hwndDlg); - return; - } - - if (CreateSysEncMutex ()) // If no instance of the wizard is currently taking care of system encryption - { - StringCbPrintfW (OrigKeyboardLayout, sizeof(OrigKeyboardLayout), L"%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF); - - bSysEncPwdChangeDlgMode = TRUE; - - if (bOnlyChangeKDF) - pwdChangeDlgMode = PCDM_CHANGE_PKCS5_PRF; - else - pwdChangeDlgMode = PCDM_CHANGE_PASSWORD; - - - INT_PTR result = DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_PASSWORDCHANGE_DLG), hwndDlg, (DLGPROC) PasswordChangeDlgProc); - - bSysEncPwdChangeDlgMode = FALSE; - - if (bKeyboardLayoutChanged) - { - // Restore the original keyboard layout - if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) - Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); - else - bKeyboardLayoutChanged = FALSE; - } - - bKeybLayoutAltKeyWarningShown = FALSE; - - if (result == IDOK) - { - switch (pwdChangeDlgMode) - { - case PCDM_CHANGE_PKCS5_PRF: - Info ("PKCS5_PRF_CHANGED", hwndDlg); - - if (!IsHiddenOSRunning()) - { - if (AskWarnYesNo ("SYS_HKD_ALGO_CHANGED_ASK_RESCUE_DISK", hwndDlg) == IDYES) - CreateRescueDisk (hwndDlg); - } - - break; - - case PCDM_ADD_REMOVE_VOL_KEYFILES: - case PCDM_REMOVE_ALL_KEYFILES_FROM_VOL: - // NOP - Keyfiles are not supported for system encryption - break; - - case PCDM_CHANGE_PASSWORD: - default: - Info ("PASSWORD_CHANGED", hwndDlg); - - if (!IsHiddenOSRunning()) - { - if (AskWarnYesNo ("SYS_PASSWORD_CHANGED_ASK_RESCUE_DISK", hwndDlg) == IDYES) - CreateRescueDisk (hwndDlg); - } - } - } - - CloseSysEncMutex (); - } - else - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); -} - -// Initiates or resumes encryption of the system partition/drive -static void EncryptSystemDevice (HWND hwndDlg) -{ - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - if (!BootEncStatus.DriveEncrypted - && !BootEncStatus.DriveMounted - && !SysEncryptionOrDecryptionRequired ()) - { - // System partition/drive is not encrypted (nothing to resume). Initiate the process. - - if (!MutexExistsOnSystem (TC_MUTEX_NAME_SYSENC)) // If no instance of the wizard is currently taking care of system encryption - { - LaunchVolCreationWizard (hwndDlg, L"/sysenc"); - } - else - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); - - return; - } - else if (SysEncryptionOrDecryptionRequired ()) - { - // System partition/drive encryption already initiated but is incomplete -- attempt to resume the process. - // Note that this also covers the pretest phase and paused decryption (reverses decrypting and starts encrypting) - - if (!MutexExistsOnSystem (TC_MUTEX_NAME_SYSENC)) // If no instance of the wizard is currently taking care of system encryption - { - LaunchVolCreationWizard (hwndDlg, L"/sysenc"); - } - else - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); - } - else if (SysDriveOrPartitionFullyEncrypted (FALSE)) - { - // System partition/drive appears to be fully encrypted - Info ("SYS_PARTITION_OR_DRIVE_APPEARS_FULLY_ENCRYPTED", hwndDlg); - return; - } -} - -// Initiates decryption of the system partition/drive -static void DecryptSystemDevice (HWND hwndDlg) -{ - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - if (!BootEncStatus.DriveEncrypted - && !BootEncStatus.DriveMounted - && !BootEncStatus.DeviceFilterActive - && !BootEncStatus.VolumeHeaderPresent - && !SysEncryptionOrDecryptionRequired ()) - { - Warning ("SYS_DRIVE_NOT_ENCRYPTED", hwndDlg); - return; - } - - if (IsHiddenOSRunning()) - { - Warning ("CANNOT_DECRYPT_HIDDEN_OS", hwndDlg); - return; - } - - if (AskNoYes ("CONFIRM_DECRYPT_SYS_DEVICE", hwndDlg) == IDNO) - return; - - if (AskWarnNoYes ("CONFIRM_DECRYPT_SYS_DEVICE_CAUTION", hwndDlg) == IDNO) - return; - - if (CreateSysEncMutex ()) // If no instance of the wizard is currently taking care of system encryption - { - try - { - // User-mode app may have crashed and its mutex may have gotten lost, so we need to check the driver status too - if (BootEncStatus.SetupInProgress) - { - int attempts = 20; - - BootEncObj->AbortSetup (); - while (BootEncStatus.SetupInProgress && attempts > 0) - { - Sleep (100); - BootEncStatus = BootEncObj->GetStatus(); - attempts--; - WaitCursor(); - } - } - } - catch (Exception &e) - { - e.Show (MainDlg); - } - NormalCursor (); - - if (BootEncStatus.SetupInProgress) - { - CloseSysEncMutex (); - Error ("SYS_ENCRYPTION_OR_DECRYPTION_IN_PROGRESS", hwndDlg); - return; - } - - CloseSysEncMutex (); - LaunchVolCreationWizard (hwndDlg, L"/dsysenc"); - } - else - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); -} - -// Initiates the process of creation of a hidden operating system -static void CreateHiddenOS (HWND hwndDlg) -{ - - // Display brief information as to what a hidden operating system is and what it's good for. This needs to be - // done, because if the system partition/drive is currently encrypted, the wizard will not display any - // such information, but will exit (displaying only an error meessage). - Info("HIDDEN_OS_PREINFO", hwndDlg); - - LaunchVolCreationWizard (hwndDlg, L"/isysenc"); -} - -static void DecryptNonSysDevice (HWND hwndDlg, BOOL bResolveAmbiguousSelection, BOOL bUseDriveListSel) -{ - wstring scPath; - - if (bResolveAmbiguousSelection) - { - scPath = ResolveAmbiguousSelection (hwndDlg, NULL); - - if (scPath.empty ()) - { - // The user selected Cancel - return; - } - } - else if (bUseDriveListSel) - { - // Decrypt mounted volume selected in the main drive list - - LPARAM lLetter = GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST)); - - if (LOWORD (lLetter) != 0xffff) - { - VOLUME_PROPERTIES_STRUCT prop; - DWORD bytesReturned; - - memset (&prop, 0, sizeof (prop)); - prop.driveNo = (wchar_t) HIWORD (lLetter) - L'A'; - - if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &bytesReturned, NULL)) - { - handleWin32Error (MainDlg, SRC_POS); - return; - } - - scPath = prop.wszVolume; - } - else - return; - } - else - { - // Decrypt volume specified in the input field below the main drive list - - wchar_t volPath [TC_MAX_PATH]; - - GetVolumePath (MainDlg, volPath, ARRAYSIZE (volPath)); - - scPath = volPath; - } - - if (scPath.empty ()) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - return; - } - - WaitCursor(); - - switch (IsSystemDevicePath (scPath.c_str (), MainDlg, TRUE)) - { - case 1: - case 2: - // The user wants to decrypt the system partition/drive. Divert to the appropriate function. - - NormalCursor (); - - DecryptSystemDevice (hwndDlg); - return; - } - - WaitCursor(); - - // Make sure the user is not attempting to decrypt a partition on an entirely encrypted system drive. - if (IsNonSysPartitionOnSysDrive (scPath.c_str ()) == 1) - { - if (WholeSysDriveEncryption (TRUE)) - { - // The system drive is entirely encrypted and the encrypted OS is running - - NormalCursor (); - - Warning ("CANT_DECRYPT_PARTITION_ON_ENTIRELY_ENCRYPTED_SYS_DRIVE", hwndDlg); - return; - } - } - else if (TCBootLoaderOnInactiveSysEncDrive ((wchar_t *) scPath.c_str ())) - { - // The system drive MAY be entirely encrypted (external access without PBA) and the potentially encrypted OS is not running - - NormalCursor (); - - Warning ("CANT_DECRYPT_PARTITION_ON_ENTIRELY_ENCRYPTED_SYS_DRIVE_UNSURE", hwndDlg); - - // We allow the user to continue as we don't know if the drive is really an encrypted system drive. - // If it is, the user has been warned and he will not be able to start decrypting, because the - // format wizard will not enable (nor will it allow the user to enable) the mount option for - // external without-PBA access (the user will receive the 'Incorrect password' error message). - } - - NormalCursor (); - - - if (AskNoYesString ((wstring (GetString ("CONFIRM_DECRYPT_NON_SYS_DEVICE")) + L"\n\n" + scPath).c_str(), hwndDlg) == IDNO) - return; - - if (AskWarnNoYes ("CONFIRM_DECRYPT_NON_SYS_DEVICE_CAUTION", hwndDlg) == IDNO) - return; - - LaunchVolCreationWizard (hwndDlg, (wstring (L"/inplacedec \"") + scPath + L"\"").c_str ()); -} - -// Blindly attempts (without any checks) to instruct the wizard to resume whatever system encryption process -// had been interrupted or not started but scheduled or exptected to start. -static void ResumeInterruptedSysEncProcess (HWND hwndDlg) -{ - if (!MutexExistsOnSystem (TC_MUTEX_NAME_SYSENC)) // If no instance of the wizard is currently taking care of system encryption - { - LaunchVolCreationWizard (MainDlg, L"/csysenc"); - } - else - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); -} - -void CreateRescueDisk (HWND hwndDlg) -{ - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - if (IsHiddenOSRunning()) - { - Warning ("CANNOT_CREATE_RESCUE_DISK_ON_HIDDEN_OS", hwndDlg); - return; - } - - if (!BootEncStatus.DriveEncrypted - && !BootEncStatus.DriveMounted - && !BootEncStatus.VolumeHeaderPresent - && !SysEncryptionOrDecryptionRequired ()) - { - Warning ("SYS_DRIVE_NOT_ENCRYPTED", hwndDlg); - return; - } - - if (SysEncryptionOrDecryptionRequired () - || BootEncStatus.SetupInProgress) - { - Warning ("SYSTEM_ENCRYPTION_NOT_COMPLETED", hwndDlg); - return; - } - - if (CreateSysEncMutex ()) // If no instance of the wizard is currently taking care of system encryption - { - try - { - wchar_t szTmp [8096]; - wchar_t szRescueDiskISO [TC_MAX_PATH+1]; - - if (AskOkCancel ("RESCUE_DISK_NON_WIZARD_CREATION_SELECT_PATH", hwndDlg) != IDOK) - { - CloseSysEncMutex (); - return; - } - - wchar_t initialDir[MAX_PATH]; - SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, 0, initialDir); - - if (!BrowseFilesInDir (hwndDlg, "OPEN_TITLE", initialDir, szRescueDiskISO, FALSE, TRUE, NULL, L"VeraCrypt Rescue Disk.iso", L"iso")) - { - CloseSysEncMutex (); - return; - } - - WaitCursor(); - BootEncObj->CreateRescueIsoImage (false, szRescueDiskISO); - - StringCbPrintfW (szTmp, sizeof szTmp, - GetString (IsWindowsIsoBurnerAvailable() ? "RESCUE_DISK_NON_WIZARD_CREATION_WIN_ISOBURN" : "RESCUE_DISK_NON_WIZARD_CREATION_BURN"), - szRescueDiskISO); - - if (IsWindowsIsoBurnerAvailable()) - { - if (AskYesNoString (szTmp, hwndDlg) == IDYES) - LaunchWindowsIsoBurner (MainDlg, szRescueDiskISO); - } - else - InfoDirect (szTmp, hwndDlg); - } - catch (Exception &e) - { - e.Show (hwndDlg); - Error ("ERROR_CREATING_RESCUE_DISK", hwndDlg); - } - CloseSysEncMutex (); - - NormalCursor (); - } - else - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); -} - -static void VerifyRescueDisk (HWND hwndDlg, bool checkIsoFile) -{ - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - if (!BootEncStatus.DriveEncrypted - && !BootEncStatus.DriveMounted - && !BootEncStatus.VolumeHeaderPresent - && !SysEncryptionOrDecryptionRequired ()) - { - Warning ("SYS_DRIVE_NOT_ENCRYPTED", hwndDlg); - return; - } - - if (SysEncryptionOrDecryptionRequired () - || BootEncStatus.SetupInProgress) - { - Warning ("SYSTEM_ENCRYPTION_NOT_COMPLETED", hwndDlg); - return; - } - - if (CreateSysEncMutex ()) // If no instance of the wizard is currently taking care of system encryption - { - try - { - if (!checkIsoFile && (AskOkCancel ("RESCUE_DISK_NON_WIZARD_CHECK_INSERT", hwndDlg) != IDOK)) - { - CloseSysEncMutex (); - return; - } - - // Create a temporary up-to-date rescue disk image in RAM (with it the CD/DVD content will be compared) - BootEncObj->CreateRescueIsoImage (false, L""); - - - if (checkIsoFile) - { - wchar_t szRescueDiskISO [TC_MAX_PATH+1]; - wchar_t initialDir[MAX_PATH]; - SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, 0, initialDir); - - if (!BrowseFilesInDir (hwndDlg, "OPEN_TITLE", initialDir, szRescueDiskISO, FALSE, FALSE, NULL, L"VeraCrypt Rescue Disk.iso", L"iso")) - { - CloseSysEncMutex (); - return; - } - - WaitCursor(); - if (!BootEncObj->VerifyRescueDiskIsoImage (szRescueDiskISO)) - Error ("RESCUE_DISK_ISO_IMAGE_CHECK_FAILED", hwndDlg); - else - Info ("RESCUE_DISK_ISO_IMAGE_CHECK_PASSED", hwndDlg); - } - else - { - WaitCursor(); - if (!BootEncObj->VerifyRescueDisk ()) - Error ("RESCUE_DISK_NON_WIZARD_CHECK_FAILED", hwndDlg); - else - Info ("RESCUE_DISK_NON_WIZARD_CHECK_PASSED", hwndDlg); - } - } - catch (Exception &e) - { - e.Show (MainDlg); - Error ("RESCUE_DISK_NON_WIZARD_CHECK_FAILED", hwndDlg); - } - CloseSysEncMutex (); - - NormalCursor (); - } - else - Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); -} - -static void ShowSystemEncryptionStatus (HWND hwndDlg) -{ - try - { - BootEncStatus = BootEncObj->GetStatus(); - } - catch (Exception &e) - { - e.Show (MainDlg); - } - - if (GetAsyncKeyState (VK_SHIFT) < 0 && GetAsyncKeyState (VK_CONTROL) < 0) - { - // Ctrl+Shift held (for debugging purposes) - - DebugMsgBox ("Debugging information for system encryption:\n\nDeviceFilterActive: %d\nBootLoaderVersion: %x\nSetupInProgress: %d\nSetupMode: %d\nVolumeHeaderPresent: %d\nDriveMounted: %d\nDriveEncrypted: %d\n" - "HiddenSystem: %d\nHiddenSystemPartitionStart: %I64d\n" - "ConfiguredEncryptedAreaStart: %I64d\nConfiguredEncryptedAreaEnd: %I64d\nEncryptedAreaStart: %I64d\nEncryptedAreaEnd: %I64d\nEncrypted: %I64d%%", - BootEncStatus.DeviceFilterActive, - BootEncStatus.BootLoaderVersion, - BootEncStatus.SetupInProgress, - BootEncStatus.SetupMode, - BootEncStatus.VolumeHeaderPresent, - BootEncStatus.DriveMounted, - BootEncStatus.DriveEncrypted, - BootEncStatus.HiddenSystem ? 1 : 0, - BootEncStatus.HiddenSystemPartitionStart, - BootEncStatus.ConfiguredEncryptedAreaStart, - BootEncStatus.ConfiguredEncryptedAreaEnd, - BootEncStatus.EncryptedAreaStart, - BootEncStatus.EncryptedAreaEnd, - !BootEncStatus.DriveEncrypted ? 0 : (BootEncStatus.EncryptedAreaEnd + 1 - BootEncStatus.EncryptedAreaStart) * 100I64 / (BootEncStatus.ConfiguredEncryptedAreaEnd + 1 - BootEncStatus.ConfiguredEncryptedAreaStart)); - } - - if (!BootEncStatus.DriveEncrypted && !BootEncStatus.DriveMounted) - { - Info ("SYS_DRIVE_NOT_ENCRYPTED", hwndDlg); - return; - } - - DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_VOLUME_PROPERTIES), hwndDlg, - (DLGPROC) VolumePropertiesDlgProc, (LPARAM) TRUE); - -} - -static void ResumeInterruptedNonSysInplaceEncProcess (BOOL bDecrypt) -{ - // IMPORTANT: This function must not check any config files! Otherwise, if a config file was lost or corrupt, - // the user would not be able resume encryption and the data on the volume would be inaccessible. - - LaunchVolCreationWizard (MainDlg, bDecrypt? L"/resumeinplacedec" : L"/zinplace"); -} - -BOOL SelectContainer (HWND hwndDlg) -{ - if (BrowseFiles (hwndDlg, "OPEN_VOL_TITLE", szFileName, bHistory, FALSE, NULL) == FALSE) - return FALSE; - - AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory); - EnableDisableButtons (hwndDlg); - SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST)); - return TRUE; -} - -BOOL SelectPartition (HWND hwndDlg) -{ - RawDevicesDlgParam param; - param.pszFileName = szFileName; - INT_PTR nResult = DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_RAWDEVICES_DLG), hwndDlg, - (DLGPROC) RawDevicesDlgProc, (LPARAM) & param); - if (nResult == IDOK) - { - AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory); - EnableDisableButtons (hwndDlg); - SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST)); - return TRUE; - } - - return FALSE; -} - -static void WipeCache (HWND hwndDlg, BOOL silent) -{ - DWORD dwResult; - BOOL bResult; - - bResult = DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - if (hwndDlg == NULL) - return; - - if (bResult == FALSE) - handleWin32Error (hwndDlg, SRC_POS); - else - { - EnableDisableButtons (hwndDlg); - - if (!silent) - InfoBalloon ("PASSWORD_CACHE_WIPED_SHORT", "PASSWORD_CACHE_WIPED", hwndDlg); - } -} - -static void Benchmark (HWND hwndDlg) -{ - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_BENCHMARK_DLG), hwndDlg, - (DLGPROC) BenchmarkDlgProc, (LPARAM) NULL); -} - - -static BOOL CheckMountList (HWND hwndDlg, BOOL bForceTaskBarUpdate) -{ - MOUNT_LIST_STRUCT current; - static BootEncryptionStatus newBootEncStatus; - static BOOL lastbUseDifferentTrayIconIfVolMounted = bUseDifferentTrayIconIfVolMounted; - static uint32 lastUlMountedDrives = 0; - - GetMountList (¤t); - - if ((bForceTaskBarUpdate || current.ulMountedDrives != lastUlMountedDrives || bUseDifferentTrayIconIfVolMounted != lastbUseDifferentTrayIconIfVolMounted) - && TaskBarIconMutex != NULL) - { - lastUlMountedDrives = current.ulMountedDrives; - lastbUseDifferentTrayIconIfVolMounted = bUseDifferentTrayIconIfVolMounted; - - TaskBarIconChange (MainDlg, current.ulMountedDrives != 0 && bUseDifferentTrayIconIfVolMounted ? IDI_TRUECRYPT_MOUNTED_ICON : IDI_TRUECRYPT_ICON); - } - - if (bForceTaskBarUpdate) - { - return TRUE; - } - - if (LastKnownLogicalDrives != GetUsedLogicalDrives() - || memcmp (&LastKnownMountList, ¤t, sizeof (current)) != 0) - { - wchar_t selDrive; - - WaitCursor (); - LastKnownMountList = current; - - selDrive = (wchar_t) HIWORD (GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST))); - LoadDriveLetters (hwndDlg, GetDlgItem (MainDlg, IDC_DRIVELIST), 0); - NormalCursor (); - - if (selDrive != ((wchar_t) 0xFFFF) && (current.ulMountedDrives & (1 << (selDrive - L'A'))) == 0 && !IsDriveAvailable (selDrive - L'A')) - { - nSelectedDriveIndex = -1; - return FALSE; - } - - if (selDrive != ((wchar_t) 0xFFFF)) - SelectItem (GetDlgItem (MainDlg, IDC_DRIVELIST),selDrive); - } - - try - { - newBootEncStatus = BootEncObj->GetStatus(); - - if (newBootEncStatus.SetupInProgress != RecentBootEncStatus.SetupInProgress - || newBootEncStatus.EncryptedAreaEnd != RecentBootEncStatus.EncryptedAreaEnd - || newBootEncStatus.DriveEncrypted != RecentBootEncStatus.DriveEncrypted - || newBootEncStatus.DriveMounted != RecentBootEncStatus.DriveMounted - || newBootEncStatus.SetupMode != RecentBootEncStatus.SetupMode - || newBootEncStatus.EncryptedAreaStart != RecentBootEncStatus.EncryptedAreaStart) - { - /* System encryption status change */ - - wchar_t selDrive; - int driveLetterToRefresh; - - if (RecentBootEncStatus.DriveMounted == newBootEncStatus.DriveMounted) // If an icon (and whole new line) for a system device isn't to be added/removed - { - // Partial refresh - if (WholeSysDriveEncryption (TRUE)) - { - // System drive (not just partition) - driveLetterToRefresh = ENC_SYSDRIVE_PSEUDO_DRIVE_LETTER; - } - else - { - // System partition - driveLetterToRefresh = GetSystemDriveLetter (); - } - } - else - { - // Full rebuild of the mount list - driveLetterToRefresh = 0; - } - - selDrive = (wchar_t) HIWORD (GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST))); - LoadDriveLetters (hwndDlg, GetDlgItem (MainDlg, IDC_DRIVELIST), driveLetterToRefresh); - - RecentBootEncStatus = newBootEncStatus; - - if (selDrive != ((wchar_t) 0xFFFF) && (current.ulMountedDrives & (1 << (selDrive - L'A'))) == 0 && !IsDriveAvailable (selDrive - L'A')) - { - nSelectedDriveIndex = -1; - } - - if (selDrive != ((wchar_t) 0xFFFF)) - { - SelectItem (GetDlgItem (MainDlg, IDC_DRIVELIST),selDrive); - } - } - - /* Miscellaneous notifications */ - - // Hibernation prevention notifications - if (newBootEncStatus.HibernationPreventionCount != RecentBootEncStatus.HibernationPreventionCount - && !bHibernationPreventionNotified) - { - bHibernationPreventionNotified = TRUE; - RecentBootEncStatus.HibernationPreventionCount = newBootEncStatus.HibernationPreventionCount; - - if (IsHiddenOSRunning() && BootEncObj->GetSystemDriveConfiguration().ExtraBootPartitionPresent) - WarningTopMost ("HIDDEN_OS_HIBERNATION_PREVENTED", hwndDlg); - else - WarningTopMost ("SYS_ENC_HIBERNATION_PREVENTED", hwndDlg); - } - - // Write mode prevention (hidden OS leak protection) - if (IsHiddenOSRunning()) - { - if (newBootEncStatus.HiddenSysLeakProtectionCount != RecentBootEncStatus.HiddenSysLeakProtectionCount - && !bHiddenSysLeakProtNotifiedDuringSession) - { - bHiddenSysLeakProtNotifiedDuringSession = TRUE; - - switch (HiddenSysLeakProtectionNotificationStatus) - { - case TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_COMPACT: - { - char *tmp[] = {0, "HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO", "SHOW_MORE_INFORMATION", "DO_NOT_SHOW_THIS_AGAIN", "CONTINUE", 0}; - switch (AskMultiChoice ((void **) tmp, FALSE, hwndDlg)) - { - case 1: - InfoDirect ((wstring (GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO")) - + L"\n\n" - + GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION") - + L"\n\n\n" - + GetString ("DECOY_TO_HIDDEN_OS_DATA_TRANSFER_HOWTO")).c_str(), hwndDlg); - break; - - case 2: - // No more warnings will be shown - if (ConfigBuffer == NULL) - { - // We need to load the config file because it is not done automatically when - // launched from the sys startup sequence (and SaveSettings would start by _loading_ - // the settings to cache). - LoadSettings (MainDlg); - } - HiddenSysLeakProtectionNotificationStatus = TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_DISABLED; - SaveSettings (MainDlg); - break; - - default: - // NOP - break; - } - } - break; - - case TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_DISABLED: - // NOP - break; - - case TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_NONE: - default: - { - // First time warning -- include technical explanation - InfoDirect ((wstring (GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO")) - + L"\n\n" - + GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION") - + L"\n\n\n" - + GetString ("DECOY_TO_HIDDEN_OS_DATA_TRANSFER_HOWTO")).c_str(), hwndDlg); - - // Further warnings will not include the explanation (and will allow disabling) - - if (ConfigBuffer == NULL) - { - // We need to load the config file because it is not done automatically when - // launched from the sys startup sequence (and SaveSettings would start by _loading_ - // the settings to cache). - LoadSettings (MainDlg); - } - HiddenSysLeakProtectionNotificationStatus = TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_COMPACT; - SaveSettings (MainDlg); - } - break; - } - } - } - } - catch (...) - { - // NOP - } - - return TRUE; -} - - -void DisplayDriveListContextMenu (HWND hwndDlg, LPARAM lParam) -{ - /* Drive list context menu */ - DWORD mPos; - int menuItem; - HMENU popup = CreatePopupMenu (); - HWND hList = GetDlgItem (hwndDlg, IDC_DRIVELIST); - - SetFocus (hList); - - switch (LOWORD (GetSelectedLong (hList))) - { - case TC_MLIST_ITEM_FREE: - - // No mounted volume at this drive letter - - AppendMenuW (popup, MF_STRING, IDM_MOUNT_VOLUME, GetString ("IDM_MOUNT_VOLUME")); - AppendMenu (popup, MF_SEPARATOR, 0, L""); - AppendMenuW (popup, MF_STRING, IDPM_SELECT_FILE_AND_MOUNT, GetString ("SELECT_FILE_AND_MOUNT")); - AppendMenuW (popup, MF_STRING, IDPM_SELECT_DEVICE_AND_MOUNT, GetString ("SELECT_DEVICE_AND_MOUNT")); - break; - - case TC_MLIST_ITEM_NONSYS_VOL: - - // There's a mounted non-system volume at this drive letter - - AppendMenuW (popup, MF_STRING, IDM_UNMOUNT_VOLUME, GetString ("DISMOUNT")); - AppendMenuW (popup, MF_STRING, IDPM_OPEN_VOLUME, GetString ("OPEN")); - AppendMenu (popup, MF_SEPARATOR, 0, L""); - AppendMenuW (popup, MF_STRING, IDPM_CHECK_FILESYS, GetString ("IDPM_CHECK_FILESYS")); - AppendMenuW (popup, MF_STRING, IDPM_REPAIR_FILESYS, GetString ("IDPM_REPAIR_FILESYS")); - AppendMenu (popup, MF_SEPARATOR, 0, L""); - AppendMenuW (popup, MF_STRING, IDPM_ADD_TO_FAVORITES, GetString ("IDPM_ADD_TO_FAVORITES")); - AppendMenuW (popup, MF_STRING, IDPM_ADD_TO_SYSTEM_FAVORITES, GetString ("IDPM_ADD_TO_SYSTEM_FAVORITES")); - AppendMenu (popup, MF_SEPARATOR, 0, L""); - AppendMenuW (popup, MF_STRING, IDM_DECRYPT_NONSYS_VOL, GetString ("IDM_DECRYPT_NONSYS_VOL")); - AppendMenu (popup, MF_SEPARATOR, 0, L""); - AppendMenuW (popup, MF_STRING, IDM_VOLUME_PROPERTIES, GetString ("IDPM_PROPERTIES")); - break; - - case TC_MLIST_ITEM_SYS_PARTITION: - case TC_MLIST_ITEM_SYS_DRIVE: - - // System partition/drive - - PopulateSysEncContextMenu (popup, FALSE); - break; - } - - if (lParam) - { - mPos=GetMessagePos(); - } - else - { - POINT pt = {0}; - if (ListView_GetItemPosition (hList, nSelectedDriveIndex, &pt)) - { - pt.x += 2 + ::GetSystemMetrics(SM_CXICON); - pt.y += 2; - } - ClientToScreen (hList, &pt); - mPos = MAKELONG (pt.x, pt.y); - } - - menuItem = TrackPopupMenu (popup, - TPM_RETURNCMD | TPM_LEFTBUTTON, - GET_X_LPARAM(mPos), - GET_Y_LPARAM(mPos), - 0, - hwndDlg, - NULL); - - DestroyMenu (popup); - - switch (menuItem) - { - case IDPM_SELECT_FILE_AND_MOUNT: - if (SelectContainer (hwndDlg)) - MountSelectedVolume (hwndDlg, FALSE); - break; - - case IDPM_SELECT_DEVICE_AND_MOUNT: - if (SelectPartition (hwndDlg)) - MountSelectedVolume (hwndDlg, FALSE); - break; - - case IDPM_CHECK_FILESYS: - case IDPM_REPAIR_FILESYS: - { - LPARAM lLetter = GetSelectedLong (hList); - - if (LOWORD (lLetter) != 0xffff) - CheckFilesystem (hwndDlg, (wchar_t) HIWORD (lLetter) - L'A', menuItem == IDPM_REPAIR_FILESYS); - } - break; - - case IDM_UNMOUNT_VOLUME: - if (CheckMountList (hwndDlg, FALSE)) - Dismount (hwndDlg, -2); - break; - - case IDM_DECRYPT_NONSYS_VOL: - if (CheckMountList (hwndDlg, FALSE)) - DecryptNonSysDevice (hwndDlg, FALSE, TRUE); - break; - - case IDPM_OPEN_VOLUME: - { - LPARAM state; - if (lParam) - nSelectedDriveIndex = ((LPNMITEMACTIVATE)lParam)->iItem; - else - nSelectedDriveIndex = ListView_GetSelectionMark (hList); - state = GetItemLong (hList, nSelectedDriveIndex ); - - WaitCursor (); - OpenVolumeExplorerWindow (HIWORD(state) - L'A'); - NormalCursor (); - } - break; - - case IDM_VOLUME_PROPERTIES: - DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_VOLUME_PROPERTIES), hwndDlg, - (DLGPROC) VolumePropertiesDlgProc, (LPARAM) FALSE); - break; - - case IDM_MOUNT_VOLUME: - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - mountOptions = defaultMountOptions; - bPrebootPasswordDlgMode = FALSE; - - if (CheckMountList (hwndDlg, FALSE)) - _beginthread(mountThreadFunction, 0, hwndDlg); - } - break; - - case IDPM_ADD_TO_FAVORITES: - case IDPM_ADD_TO_SYSTEM_FAVORITES: - { - LPARAM selectedDrive = GetSelectedLong (hList); - - if (LOWORD (selectedDrive) == TC_MLIST_ITEM_NONSYS_VOL) - AddMountedVolumeToFavorites (hwndDlg, HIWORD (selectedDrive) - L'A', menuItem == IDPM_ADD_TO_SYSTEM_FAVORITES); - } - break; - - default: - SendMessage (MainDlg, WM_COMMAND, menuItem, NULL); - break; - } -} - - -/* Except in response to the WM_INITDIALOG and WM_ENDSESSION messages, the dialog box procedure - should return nonzero if it processes a message, and zero if it does not. */ -BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - static UINT taskBarCreatedMsg; - WORD lw = LOWORD (wParam); - WORD hw = HIWORD (wParam); - - switch (uMsg) - { - case WM_HOTKEY: - - HandleHotKey (hwndDlg, wParam); - return 1; - - case WM_INITDIALOG: - { - int exitCode = 0; - - MainDlg = hwndDlg; - - if (IsTrueCryptInstallerRunning()) - AbortProcess ("TC_INSTALLER_IS_RUNNING"); - - // Set critical default options in case UsePreferences is false - bPreserveTimestamp = defaultMountOptions.PreserveTimestamp = TRUE; - bShowDisconnectedNetworkDrives = FALSE; - bHideWaitingDialog = FALSE; - - ResetWrongPwdRetryCount (); - - ExtractCommandLine (hwndDlg, (wchar_t *) lParam); - - try - { - BootEncObj->SetParentWindow (hwndDlg); - BootEncStatus = BootEncObj->GetStatus(); - RecentBootEncStatus = BootEncStatus; - } - catch (...) - { - // NOP - } - - if (UsePreferences) - { - // General preferences - LoadSettings (hwndDlg); - - // Keyfiles - LoadDefaultKeyFilesParam (); - RestoreDefaultKeyFilesParam (); - } - - if (ComServerMode) - { - InitDialog (hwndDlg); - - if (!ComServerMain ()) - { - handleWin32Error (hwndDlg, SRC_POS); - exit (1); - } - exit (0); - } - - if (CmdMountOptionsValid) - mountOptions = CmdMountOptions; - - InitMainDialog (hwndDlg); - - try - { - if (IsHiddenOSRunning()) - { - uint32 driverConfig = ReadDriverConfigurationFlags(); - if (BootEncObj->GetInstalledBootLoaderVersion() != VERSION_NUM) - Warning ("UPDATE_TC_IN_HIDDEN_OS_TOO", hwndDlg); - if ( !(driverConfig & TC_DRIVER_CONFIG_DISABLE_EVIL_MAID_ATTACK_DETECTION) - && !BootEncObj->CheckBootloaderFingerprint ()) - Warning ("BOOT_LOADER_FINGERPRINT_CHECK_FAILED", hwndDlg); - } - else if (SysDriveOrPartitionFullyEncrypted (TRUE)) - { - uint32 driverConfig = ReadDriverConfigurationFlags(); - if (BootEncObj->GetInstalledBootLoaderVersion() != VERSION_NUM) - { - Warning ("BOOT_LOADER_VERSION_DIFFERENT_FROM_DRIVER_VERSION", hwndDlg); - } - if ( !(driverConfig & TC_DRIVER_CONFIG_DISABLE_EVIL_MAID_ATTACK_DETECTION) - && !BootEncObj->CheckBootloaderFingerprint ()) - Warning ("BOOT_LOADER_FINGERPRINT_CHECK_FAILED", hwndDlg); - } - } - catch (...) { } - - // Automount - if (bAuto || (Quit && szFileName[0] != 0)) - { - // No drive letter specified on command line - if (commandLineDrive == 0) - szDriveLetter[0] = (wchar_t) GetFirstAvailableDrive () + L'A'; - - if (bAutoMountDevices) - { - defaultMountOptions = mountOptions; - if (FirstCmdKeyFile) - { - KeyFilesEnable = defaultKeyFilesParam.EnableKeyFiles = TRUE; - KeyFileCloneAll (FirstCmdKeyFile, &FirstKeyFile); - KeyFileCloneAll (FirstCmdKeyFile, &defaultKeyFilesParam.FirstKeyFile); - } - - if (!MountAllDevices (hwndDlg, !Silent && !CmdVolumePasswordValid && IsPasswordCacheEmpty())) - exitCode = 1; - } - - if (bAutoMountFavorites) - { - defaultMountOptions = mountOptions; - if (FirstCmdKeyFile) - { - KeyFilesEnable = defaultKeyFilesParam.EnableKeyFiles = TRUE; - KeyFileCloneAll (FirstCmdKeyFile, &FirstKeyFile); - KeyFileCloneAll (FirstCmdKeyFile, &defaultKeyFilesParam.FirstKeyFile); - } - - if (!MountFavoriteVolumes (hwndDlg, FALSE, LogOn)) - exitCode = 1; - } - - if (szFileName[0] != 0 && !TranslateVolumeID (hwndDlg, szFileName, ARRAYSIZE (szFileName))) - { - exitCode = 1; - } - else if (szFileName[0] != 0 && !IsMountedVolume (szFileName)) - { - BOOL mounted = FALSE; - int EffectiveVolumePkcs5 = CmdVolumePkcs5; - BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; - BOOL bEffectiveTryEmptyPasswordWhenKeyfileUsed = bCmdTryEmptyPasswordWhenKeyfileUsedValid? bCmdTryEmptyPasswordWhenKeyfileUsed : bTryEmptyPasswordWhenKeyfileUsed; - - if (!VolumePathExists (szFileName)) - { - handleWin32Error (hwndDlg, SRC_POS); - } - else - { - /* Priority is given to command line parameters - * Default values used only when nothing specified in command line - */ - if (EffectiveVolumePkcs5 == 0) - EffectiveVolumePkcs5 = DefaultVolumePkcs5; - if (!EffectiveVolumeTrueCryptMode) - EffectiveVolumeTrueCryptMode = DefaultVolumeTrueCryptMode; - - // Command line password or keyfiles - if (CmdVolumePassword.Length != 0 || (FirstCmdKeyFile && (CmdVolumePasswordValid || bEffectiveTryEmptyPasswordWhenKeyfileUsed))) - { - BOOL reportBadPasswd = CmdVolumePassword.Length > 0; - - if (FirstCmdKeyFile) - KeyFilesApplyWithPin (hwndDlg, &CmdVolumePassword, CmdTokenPin, FirstCmdKeyFile, szFileName); - - mounted = MountVolume (hwndDlg, szDriveLetter[0] - L'A', - szFileName, &CmdVolumePassword, EffectiveVolumePkcs5, CmdVolumePim, EffectiveVolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, - &mountOptions, Silent, reportBadPasswd); - - burn (&CmdVolumePassword, sizeof (CmdVolumePassword)); - } - else - { - // Cached password - mounted = MountVolume (hwndDlg, szDriveLetter[0] - L'A', szFileName, NULL, EffectiveVolumePkcs5, CmdVolumePim, EffectiveVolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); - } - - if (FirstCmdKeyFile) - { - KeyFileRemoveAll (&FirstKeyFile); - FirstKeyFile = FirstCmdKeyFile; - KeyFilesEnable = TRUE; - } - - // Ask user for password - while (!mounted && !Silent) - { - int GuiPkcs5 = EffectiveVolumePkcs5; - int GuiPim = CmdVolumePim; - BOOL GuiTrueCryptMode = EffectiveVolumeTrueCryptMode; - VolumePassword.Length = 0; - - StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume),szFileName); - if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &GuiTrueCryptMode, NULL, TRUE)) - break; - else - { - VolumePkcs5 = GuiPkcs5; - VolumePim = GuiPim; - VolumeTrueCryptMode = GuiTrueCryptMode; - burn (&GuiPkcs5, sizeof(GuiPkcs5)); - burn (&GuiPim, sizeof(GuiPim)); - burn (&GuiTrueCryptMode, sizeof(GuiTrueCryptMode)); - } - - WaitCursor (); - - if (KeyFilesEnable && FirstKeyFile) - KeyFilesApplyWithPin (hwndDlg, &VolumePassword, CmdTokenPin, FirstKeyFile, szFileName); - - mounted = MountVolume (hwndDlg, szDriveLetter[0] - L'A', szFileName, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, FALSE, TRUE); - - burn (&VolumePassword, sizeof (VolumePassword)); - burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&VolumePim, sizeof (VolumePim)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); - burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); - burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); - - NormalCursor (); - } - } - - if (UsePreferences) - { - RestoreDefaultKeyFilesParam (); - bCacheInDriver = bCacheInDriverDefault; - } - - if (mounted > 0) - { - if (bBeep) - MessageBeep (0xFFFFFFFF); - - if (bExplore) - OpenVolumeExplorerWindow (szDriveLetter[0] - L'A'); - - RefreshMainDlg(hwndDlg); - - if(!Silent) - { - // Check for problematic file extensions (exe, dll, sys) - if (CheckFileExtension (szFileName)) - Warning ("EXE_FILE_EXTENSION_MOUNT_WARNING", hwndDlg); - } - } - else - exitCode = 1; - } - else if (bExplore && GetMountedVolumeDriveNo (szFileName) != -1) - OpenVolumeExplorerWindow (GetMountedVolumeDriveNo (szFileName)); - else if (szFileName[0] != 0 && IsMountedVolume (szFileName)) - Warning ("VOL_ALREADY_MOUNTED", hwndDlg); - - if (!Quit) - RefreshMainDlg(hwndDlg); - } - - // Wipe cache - if (bWipe) - WipeCache (hwndDlg, Silent); - - // Wipe command line password - if (CmdVolumePassword.Length != 0) - { - burn (&CmdVolumePassword, sizeof (CmdVolumePassword)); - CmdVolumePassword.Length = 0; - } - - // Wipe command line keyfiles - if (FirstCmdKeyFile) - { - if (defaultKeyFilesParam.FirstKeyFile) - KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile); - - defaultKeyFilesParam.EnableKeyFiles = FALSE; - - if (!Quit) - { - LoadSettings (hwndDlg); - LoadDefaultKeyFilesParam (); - RestoreDefaultKeyFilesParam (); - } - } - - // Dismount - if (cmdUnmountDrive >= 0) - { - MOUNT_LIST_STRUCT mountList; - DWORD bytesReturned; - - if (DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, NULL, 0, &mountList, sizeof (mountList), &bytesReturned, NULL) - && (mountList.ulMountedDrives & (1 << cmdUnmountDrive)) == 0) - { - Error ("NO_VOLUME_MOUNTED_TO_DRIVE", hwndDlg); - exitCode = 1; - } - else if (!Dismount (hwndDlg, cmdUnmountDrive)) - exitCode = 1; - } - else if (cmdUnmountDrive == -1) - { - if (!DismountAll (hwndDlg, bForceUnmount, !Silent, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY)) - exitCode = 1; - } - - // TaskBar icon - if (bEnableBkgTask) - TaskBarIconAdd (hwndDlg); - - // Quit - if (Quit) - { - if (TaskBarIconMutex == NULL) - exit (exitCode); - - MainWindowHidden = TRUE; - - LoadSettings (hwndDlg); - LoadDefaultKeyFilesParam (); - RestoreDefaultKeyFilesParam (); - - if (!bEnableBkgTask) - { - if (TaskBarIconMutex) - TaskBarIconRemove (hwndDlg); - exit (exitCode); - } - } - - // No command line arguments or only /volume => bring active instance - // to foreground if available - if (NoCmdLineArgs == 0 || (CmdLineVolumeSpecified && NoCmdLineArgs <= 2)) - { - HWND h = hwndDlg; - EnumWindows (FindTCWindowEnum, (LPARAM) &h); - - if (h != hwndDlg - && (!IsAdmin() || (GetWindowLongPtrW (h, DWLP_USER) & TC_MAIN_WINDOW_FLAG_ADMIN_PRIVILEGES) != 0)) - { - if (CmdLineVolumeSpecified) - { - COPYDATASTRUCT cd; - memcpy (&cd.dwData, WM_COPY_SET_VOLUME_NAME, 4); - cd.lpData = szFileName; - cd.cbData = (DWORD) ((wcslen (szFileName) + 1) * sizeof (wchar_t)); - - SendMessage (h, WM_COPYDATA, (WPARAM)hwndDlg, (LPARAM)&cd); - } - - SendMessage (h, TC_APPMSG_MOUNT_SHOW_WINDOW, 0, 0); - - ShowWindow (h, SW_SHOW); - SetForegroundWindow (h); - - if (TaskBarIconMutex == NULL) - exit (0); - } - } - - HookMouseWheel (hwndDlg, IDC_VOLUME); - - // Register hot keys - if (!RegisterAllHotkeys (hwndDlg, Hotkeys) - && TaskBarIconMutex != NULL) // Warn only if we are the first instance of TrueCrypt - Warning("HOTKEY_REGISTRATION_ERROR", hwndDlg); - - Silent = FALSE; - - GetMountList (&LastKnownMountList); - SetTimer (hwndDlg, TIMER_ID_MAIN, TIMER_INTERVAL_MAIN, NULL); - - taskBarCreatedMsg = RegisterWindowMessage (L"TaskbarCreated"); - - AllowMessageInUIPI (taskBarCreatedMsg); - - SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST)); - - /* Check system encryption status */ - - if (!Quit) // Do not care about system encryption or in-place encryption if we were launched from the system startup sequence (the wizard was added to it too). - { - if (SysEncryptionOrDecryptionRequired ()) - { - if (!MutexExistsOnSystem (TC_MUTEX_NAME_SYSENC)) // If no instance of the wizard is currently taking care of system encryption - { - // We shouldn't block the mutex at this point - - if (SystemEncryptionStatus == SYSENC_STATUS_PRETEST - || AskWarnYesNo ("SYSTEM_ENCRYPTION_RESUME_PROMPT", hwndDlg) == IDYES) - { - // The wizard was not launched during the system startup seq, or the user may have forgotten - // to resume the encryption/decryption process. - - - LaunchVolCreationWizard (hwndDlg, L"/csysenc"); - } - } - } - - if (bInPlaceEncNonSysPending && !NonSysInplaceEncInProgressElsewhere()) - { - BOOL bDecrypt = FALSE; - if (AskNonSysInPlaceEncryptionResume(hwndDlg, &bDecrypt) == IDYES) - ResumeInterruptedNonSysInplaceEncProcess (bDecrypt); - } - } - - if (TaskBarIconMutex != NULL) - RegisterWtsNotification(hwndDlg); - DoPostInstallTasks (hwndDlg); - ResetCurrentDirectory (); - } - return 0; - - case WM_MOUSEWHEEL: - return HandleDriveListMouseWheelEvent (uMsg, wParam, lParam, FALSE); - - case WM_CONTEXTMENU: - { - HWND hList = GetDlgItem (hwndDlg, IDC_DRIVELIST); - // only handle if it is coming from keyboard and if the drive - // list has focus. The other cases are handled elsewhere - if ( (-1 == GET_X_LPARAM(lParam)) - && (-1 == GET_Y_LPARAM(lParam)) - && (GetFocus () == hList) - ) - { - INT item = ListView_GetSelectionMark (hList); - if (item >= 0) - { - nSelectedDriveIndex = item; - DisplayDriveListContextMenu (hwndDlg, NULL); - } - } - } - break; - - case WM_WINDOWPOSCHANGING: - if (MainWindowHidden) - { - // Prevent window from being shown - PWINDOWPOS wp = (PWINDOWPOS)lParam; - wp->flags &= ~SWP_SHOWWINDOW; - return 0; - } - return 1; - - case WM_SYSCOMMAND: - if (lw == IDC_ABOUT) - { - DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_ABOUT_DLG), hwndDlg, (DLGPROC) AboutDlgProc); - return 1; - } - return 0; - - case WM_HELP: - OpenPageHelp (hwndDlg, 0); - return 1; - - case WM_WTSSESSION_CHANGE: - if (TaskBarIconMutex != NULL) - { - if (bDismountOnSessionLocked && ((WTS_SESSION_LOCK == wParam) || (WTS_CONSOLE_DISCONNECT == wParam) || (WTS_REMOTE_DISCONNECT == wParam))) - { - // Auto-dismount when session is locked - DWORD dwResult; - - if (bWipeCacheOnAutoDismount) - { - DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - SecurityToken::CloseAllSessions(); - } - - DismountAll (hwndDlg, bForceAutoDismount, TRUE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); - } - } - return 0; - - case WM_ENDSESSION: - if (TaskBarIconMutex != NULL) - { - if (bDismountOnLogOff) - { - // Auto-dismount when user logs off - DWORD dwResult; - - if (bWipeCacheOnAutoDismount) - DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - - DismountAll (hwndDlg, bForceAutoDismount, FALSE, 1, 0); - } - - TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); - } - EndMainDlg (hwndDlg); - localcleanup (); - return 0; - - case WM_POWERBROADCAST: - if (wParam == PBT_APMSUSPEND - && TaskBarIconMutex != NULL && bDismountOnPowerSaving) - { - // Auto-dismount when entering power-saving mode - DWORD dwResult; - - if (bWipeCacheOnAutoDismount) - { - DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - SecurityToken::CloseAllSessions(); - } - - DismountAll (hwndDlg, bForceAutoDismount, TRUE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); - } - return 0; - - case WM_TIMER: - { - // Check mount list and update GUI if needed - CheckMountList (hwndDlg, FALSE); - - // Cache status - if (IsPasswordCacheEmpty() == IsWindowEnabled (GetDlgItem (hwndDlg, IDC_WIPE_CACHE))) - EnableWindow (GetDlgItem (hwndDlg, IDC_WIPE_CACHE), !IsPasswordCacheEmpty()); - - // Check driver warning flags - DWORD bytesOut; - GetWarningFlagsRequest warnings; - if (DeviceIoControl (hDriver, TC_IOCTL_GET_WARNING_FLAGS, NULL, 0, &warnings, sizeof (warnings), &bytesOut, NULL)) - { - if (warnings.SystemFavoriteVolumeDirty) - WarningTopMost ("SYS_FAVORITE_VOLUME_DIRTY", hwndDlg); - - if (warnings.PagingFileCreationPrevented) - WarningTopMost ("PAGING_FILE_CREATION_PREVENTED", hwndDlg); - } - - if (TaskBarIconMutex != NULL) - { - - // Idle auto-dismount - if (MaxVolumeIdleTime > 0) - DismountIdleVolumes (); - - // Screen saver auto-dismount - if (bDismountOnScreenSaver) - { - static BOOL previousState = FALSE; - BOOL running = FALSE; - SystemParametersInfo (SPI_GETSCREENSAVERRUNNING, 0, &running, 0); - - if (running && !previousState) - { - DWORD dwResult; - previousState = TRUE; - - if (bWipeCacheOnAutoDismount) - { - DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - SecurityToken::CloseAllSessions(); - } - - DismountAll (hwndDlg, bForceAutoDismount, FALSE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); - } - else - { - previousState = running; - } - } - - // Auto-mount favorite volumes on arrival -#if TIMER_INTERVAL_MAIN != 500 -#error TIMER_INTERVAL_MAIN != 500 -#endif - static int favoritesAutoMountTimerDivisor = 0; - if ((++favoritesAutoMountTimerDivisor & 1) && !FavoritesOnArrivalMountRequired.empty()) - { - static bool reentry = false; - if (reentry) - break; - - reentry = true; - - foreach (FavoriteVolume favorite, FavoritesOnArrivalMountRequired) - { - if (favorite.UseVolumeID) - { - if (IsMountedVolumeID (favorite.VolumeID)) - continue; - - std::wstring volDevPath = FindDeviceByVolumeID (favorite.VolumeID); - if (volDevPath.length() > 0) - { - favorite.Path = volDevPath; - favorite.DisconnectedDevice = false; - } - else - continue; - } - else if (!favorite.VolumePathId.empty()) - { - if (IsMountedVolume (favorite.Path.c_str())) - continue; - - wchar_t volDevPath[TC_MAX_PATH]; - if (QueryDosDevice (favorite.VolumePathId.substr (4, favorite.VolumePathId.size() - 5).c_str(), volDevPath, TC_MAX_PATH) == 0) - continue; - - favorite.DisconnectedDevice = false; - } - else if (favorite.Path.find (L"\\\\?\\Volume{") == 0) - { - wstring resolvedPath = VolumeGuidPathToDevicePath (favorite.Path); - if (resolvedPath.empty()) - continue; - - favorite.DisconnectedDevice = false; - favorite.VolumePathId = favorite.Path; - favorite.Path = resolvedPath; - } - - if (IsMountedVolume (favorite.Path.c_str())) - continue; - - if (!IsVolumeDeviceHosted (favorite.Path.c_str())) - { - if (!FileExists (favorite.Path.c_str())) - continue; - } - else if (favorite.VolumePathId.empty()) - continue; - - bool mountedAndNotDisconnected = false; - foreach (FavoriteVolume mountedFavorite, FavoritesMountedOnArrivalStillConnected) - { - if (favorite.Path == mountedFavorite.Path) - { - mountedAndNotDisconnected = true; - break; - } - } - - if (!mountedAndNotDisconnected) - { - FavoriteMountOnArrivalInProgress = TRUE; - MountFavoriteVolumes (hwndDlg, FALSE, FALSE, FALSE, favorite); - FavoriteMountOnArrivalInProgress = FALSE; - - FavoritesMountedOnArrivalStillConnected.push_back (favorite); - } - } - - bool deleted; - for (list ::iterator favorite = FavoritesMountedOnArrivalStillConnected.begin(); - favorite != FavoritesMountedOnArrivalStillConnected.end(); - deleted ? favorite : ++favorite) - { - deleted = false; - - if (IsMountedVolume (favorite->Path.c_str())) - continue; - - if (!IsVolumeDeviceHosted (favorite->Path.c_str())) - { - if (FileExists (favorite->Path.c_str())) - continue; - } - - wchar_t volDevPath[TC_MAX_PATH]; - if (favorite->VolumePathId.size() > 5 - && QueryDosDevice (favorite->VolumePathId.substr (4, favorite->VolumePathId.size() - 5).c_str(), volDevPath, TC_MAX_PATH) != 0) - { - continue; - } - - // set DisconnectedDevice field on FavoritesOnArrivalMountRequired element - foreach (FavoriteVolume onArrivalFavorite, FavoritesOnArrivalMountRequired) - { - if (onArrivalFavorite.Path == favorite->Path) - { - onArrivalFavorite.DisconnectedDevice = true; - break; - } - } - - favorite = FavoritesMountedOnArrivalStillConnected.erase (favorite); - deleted = true; - } - - reentry = false; - } - } - - // Exit background process in non-install mode or if no volume mounted - // and no other instance active - if (LastKnownMountList.ulMountedDrives == 0 - && MainWindowHidden -#ifndef _DEBUG - && (bCloseBkgTaskWhenNoVolumes || IsNonInstallMode ()) - && !SysEncDeviceActive (TRUE) -#endif - && GetDriverRefCount () < 2) - { - TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); - EndMainDlg (hwndDlg); - } - } - return 1; - - case TC_APPMSG_TASKBAR_ICON: - { - switch (lParam) - { - case WM_LBUTTONDOWN: - SetForegroundWindow (hwndDlg); - MainWindowHidden = FALSE; - ShowWindow (hwndDlg, SW_SHOW); - ShowWindow (hwndDlg, SW_RESTORE); - return 1; - - case WM_RBUTTONUP: - { - POINT pos; - HMENU popup = CreatePopupMenu (); - int sel, i, n; - - if (MainWindowHidden) - { - AppendMenuW (popup, MF_STRING, IDM_SHOW_HIDE, GetString ("SHOW_TC")); - AppendMenu (popup, MF_SEPARATOR, 0, L""); - } - else if (bEnableBkgTask - && (!(LastKnownMountList.ulMountedDrives == 0 - && (bCloseBkgTaskWhenNoVolumes || IsNonInstallMode ()) - && !SysEncDeviceActive (TRUE) - && GetDriverRefCount () < 2))) - { - AppendMenuW (popup, MF_STRING, IDM_SHOW_HIDE, GetString ("HIDE_TC")); - AppendMenu (popup, MF_SEPARATOR, 0, L""); - } - AppendMenuW (popup, MF_STRING, IDM_MOUNTALL, GetString ("IDC_MOUNTALL")); - AppendMenuW (popup, MF_STRING, IDM_MOUNT_FAVORITE_VOLUMES, GetString ("IDM_MOUNT_FAVORITE_VOLUMES")); - AppendMenuW (popup, MF_STRING, IDM_UNMOUNTALL, GetString ("IDC_UNMOUNTALL")); - AppendMenu (popup, MF_SEPARATOR, 0, L""); - - for (n = 0; n < 2; n++) - { - for (i = 0; i < 26; i++) - { - if (LastKnownMountList.ulMountedDrives & (1 << i)) - { - wchar_t s[1024]; - wchar_t *vol = (wchar_t *) LastKnownMountList.wszVolume[i]; - - if (wcsstr (vol, L"\\??\\")) vol += 4; - - // first check label used for mounting. If empty, look for it in favorites. - bool useInExplorer = false; - wstring label = (wchar_t *) LastKnownMountList.wszLabel[i]; - if (label.empty()) - label = GetFavoriteVolumeLabel (vol, useInExplorer); - - StringCbPrintfW (s, sizeof(s), L"%s %c: (%s)", - GetString (n==0 ? "OPEN" : "DISMOUNT"), - i + L'A', - label.empty() ? vol : label.c_str()); - AppendMenuW (popup, MF_STRING, n*26 + TRAYICON_MENU_DRIVE_OFFSET + i, s); - } - } - if (LastKnownMountList.ulMountedDrives != 0) - AppendMenu (popup, MF_SEPARATOR, 0, L""); - } - - AppendMenuW (popup, MF_STRING, IDM_HELP, GetString ("MENU_HELP")); - AppendMenuW (popup, MF_STRING, IDM_HOMEPAGE_SYSTRAY, GetString ("HOMEPAGE")); - AppendMenuW (popup, MF_STRING, IDM_PREFERENCES, GetString ("IDM_PREFERENCES")); - AppendMenuW (popup, MF_STRING, IDM_ABOUT, GetString ("IDM_ABOUT")); - AppendMenu (popup, MF_SEPARATOR, 0, L""); - AppendMenuW (popup, MF_STRING, IDCANCEL, GetString ("EXIT")); - - GetCursorPos (&pos); - - SetForegroundWindow(hwndDlg); - - sel = TrackPopupMenu (popup, - TPM_RETURNCMD | TPM_LEFTALIGN | TPM_BOTTOMALIGN | TPM_RIGHTBUTTON, - pos.x, - pos.y, - 0, - hwndDlg, - NULL); - - if (sel >= TRAYICON_MENU_DRIVE_OFFSET && sel < TRAYICON_MENU_DRIVE_OFFSET + 26) - { - OpenVolumeExplorerWindow (sel - TRAYICON_MENU_DRIVE_OFFSET); - } - else if (sel >= TRAYICON_MENU_DRIVE_OFFSET + 26 && sel < TRAYICON_MENU_DRIVE_OFFSET + 26*2) - { - if (CheckMountList (hwndDlg, FALSE)) - { - if (Dismount (hwndDlg, sel - TRAYICON_MENU_DRIVE_OFFSET - 26)) - { - wchar_t txt [2048]; - StringCbPrintfW (txt, sizeof(txt), GetString ("VOLUME_MOUNTED_AS_DRIVE_LETTER_X_DISMOUNTED"), sel - TRAYICON_MENU_DRIVE_OFFSET - 26 + L'A'); - - InfoBalloonDirect (GetString ("SUCCESSFULLY_DISMOUNTED"), txt, hwndDlg); - } - } - } - else if (sel == IDM_SHOW_HIDE) - { - ChangeMainWindowVisibility (); - } - else if (sel == IDM_HOMEPAGE_SYSTRAY) - { - Applink ("home", TRUE, ""); - } - else if (sel == IDCANCEL) - { - if ((LastKnownMountList.ulMountedDrives == 0 - && !SysEncDeviceActive (TRUE)) - || AskWarnNoYes ("CONFIRM_EXIT", hwndDlg) == IDYES) - { - // Close all other TC windows - EnumWindows (CloseTCWindowsEnum, 0); - - TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); - SendMessage (hwndDlg, WM_COMMAND, sel, 0); - } - } - else - { - SendMessage (hwndDlg, WM_COMMAND, sel, 0); - } - - PostMessage(hwndDlg, WM_NULL, 0, 0); - DestroyMenu (popup); - } - return 1; - } - } - - return 0; - - case TC_APPMSG_CLOSE_BKG_TASK: - if (TaskBarIconMutex != NULL) - TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); - - return 1; - - case TC_APPMSG_SYSENC_CONFIG_UPDATE: - LoadSysEncSettings (); - - // The wizard added VeraCrypt.exe to the system startup sequence or performed other operations that - // require us to update our cached settings. - LoadSettings (hwndDlg); - - return 1; - - case WM_DEVICECHANGE: - if (!IgnoreWmDeviceChange && wParam != DBT_DEVICEARRIVAL) - { - // Check if any host device has been removed and force dismount of volumes accordingly - PDEV_BROADCAST_HDR hdr = (PDEV_BROADCAST_HDR) lParam; - int m; - - GetMountList (&LastKnownMountList); - - if (wParam == DBT_DEVICEREMOVECOMPLETE && hdr->dbch_devicetype == DBT_DEVTYP_VOLUME) - { - // File-hosted volumes - PDEV_BROADCAST_VOLUME vol = (PDEV_BROADCAST_VOLUME) lParam; - int i; - - for (i = 0; i < 26; i++) - { - if ((vol->dbcv_unitmask & (1 << i)) && !(GetUsedLogicalDrives() & (1 << i))) - { - for (m = 0; m < 26; m++) - { - if (LastKnownMountList.ulMountedDrives & (1 << m)) - { - wchar_t *vol = (wchar_t *) LastKnownMountList.wszVolume[m]; - - if (wcsstr (vol, L"\\??\\") == vol) - vol += 4; - - if (vol[1] == L':' && i == (vol[0] - (vol[0] <= L'Z' ? L'A' : L'a'))) - { - UnmountVolume (hwndDlg, m, TRUE); - WarningBalloon ("HOST_DEVICE_REMOVAL_DISMOUNT_WARN_TITLE", "HOST_DEVICE_REMOVAL_DISMOUNT_WARN", hwndDlg); - } - } - } - } - } - } - - // Device-hosted volumes - for (m = 0; m < 26; m++) - { - if (LastKnownMountList.ulMountedDrives & (1 << m)) - { - wchar_t *vol = (wchar_t *) LastKnownMountList.wszVolume[m]; - - if (wcsstr (vol, L"\\??\\") == vol) - vol += 4; - - if (IsVolumeDeviceHosted (vol)) - { - OPEN_TEST_STRUCT ots = {0}; - - if (!OpenDevice (vol, &ots, FALSE, FALSE, NULL)) - { - UnmountVolume (hwndDlg, m, TRUE); - WarningBalloon ("HOST_DEVICE_REMOVAL_DISMOUNT_WARN_TITLE", "HOST_DEVICE_REMOVAL_DISMOUNT_WARN", hwndDlg); - } - } - } - } - - // Favorite volumes - UpdateDeviceHostedFavoriteVolumes(); - - return 1; - } - return 0; - - case WM_NOTIFY: - - if(wParam == IDC_DRIVELIST) - { - if (((LPNMHDR) lParam)->code == NM_CUSTOMDRAW) - { - int width = ListView_GetColumnWidth (GetDlgItem (hwndDlg, IDC_DRIVELIST), 1); - if (width != LastDriveListVolumeColumnWidth) - { - LastDriveListVolumeColumnWidth = width; - LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), 0); - } - return 0; - } - - /* Single click within drive list */ - if (((LPNMHDR) lParam)->code == LVN_ITEMCHANGED && (((LPNMLISTVIEW) lParam)->uNewState & LVIS_FOCUSED )) - { - nSelectedDriveIndex = ((LPNMLISTVIEW) lParam)->iItem; - EnableDisableButtons (hwndDlg); - return 1; - } - - /* Double click within drive list */ - if (((LPNMHDR) lParam)->code == LVN_ITEMACTIVATE) - { - LPARAM state = GetItemLong (GetDlgItem (hwndDlg, IDC_DRIVELIST), ((LPNMITEMACTIVATE)lParam)->iItem ); - nSelectedDriveIndex = ((LPNMITEMACTIVATE)lParam)->iItem; - if (LOWORD(state) == TC_MLIST_ITEM_NONSYS_VOL || LOWORD(state) == TC_MLIST_ITEM_SYS_PARTITION) - { - // Open explorer window for mounted volume - WaitCursor (); - OpenVolumeExplorerWindow (HIWORD(state) - L'A'); - NormalCursor (); - } - else if (LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) == TC_MLIST_ITEM_FREE) - { - mountOptions = defaultMountOptions; - bPrebootPasswordDlgMode = FALSE; - - if (GetAsyncKeyState (VK_CONTROL) < 0) - { - /* Priority is given to command line parameters - * Default values used only when nothing specified in command line - */ - if (CmdVolumePkcs5 == 0) - mountOptions.ProtectedHidVolPkcs5Prf = DefaultVolumePkcs5; - else - mountOptions.ProtectedHidVolPkcs5Prf = CmdVolumePkcs5; - mountOptions.ProtectedHidVolPim = CmdVolumePim; - - if (IDCANCEL == DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, - (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions)) - return 1; - - if (mountOptions.ProtectHiddenVolume && hidVolProtKeyFilesParam.EnableKeyFiles) - { - wchar_t selectedVolume [TC_MAX_PATH + 1]; - GetVolumePath (hwndDlg, selectedVolume, ARRAYSIZE (selectedVolume)); - KeyFilesApply (hwndDlg, &mountOptions.ProtectedHidVolPassword, hidVolProtKeyFilesParam.FirstKeyFile, selectedVolume); - } - } - - if (CheckMountList (hwndDlg, FALSE)) - _beginthread(mountThreadFunction, 0, hwndDlg); - } - return 1; - } - - /* Right click and drag&drop operations */ - - switch (((NM_LISTVIEW *) lParam)->hdr.code) - { - case NM_RCLICK: - case LVN_BEGINRDRAG: - /* If the mouse was moving while the right mouse button is pressed, popup menu would - not open, because drag&drop operation would be initiated. Therefore, we're handling - RMB drag-and-drop operations as well. */ - { - - DisplayDriveListContextMenu (hwndDlg, lParam); - - return 1; - } - } - } - return 0; - - case WM_ERASEBKGND: - return 0; - - case WM_COMMAND: - - if (lw == IDCANCEL || lw == IDC_EXIT) - { - EndMainDlg (hwndDlg); - return 1; - } - - if (lw == IDHELP || lw == IDM_HELP) - { - OpenPageHelp (hwndDlg, 0); - return 1; - } - - if (lw == IDM_ABOUT || lw == IDC_LOGO) - { - DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_ABOUT_DLG), hwndDlg, (DLGPROC) AboutDlgProc); - return 1; - } - - if (lw == IDOK && LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) == TC_MLIST_ITEM_NONSYS_VOL - || lw == IDM_UNMOUNT_VOLUME) - { - if (lw == IDM_UNMOUNT_VOLUME && LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) != TC_MLIST_ITEM_NONSYS_VOL) - { - Warning ("SELECT_A_MOUNTED_VOLUME", hwndDlg); - return 1; - } - - if (CheckMountList (hwndDlg, FALSE)) - Dismount (hwndDlg, -2); - return 1; - } - - if ((lw == IDOK || lw == IDM_MOUNT_VOLUME || lw == IDM_MOUNT_VOLUME_OPTIONS || lw == IDC_MOUNTALL || lw == IDM_MOUNTALL) - && LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) == 0xffff) - { - MessageBoxW (hwndDlg, GetString ("SELECT_FREE_DRIVE"), L"VeraCrypt", MB_ICONEXCLAMATION); - return 1; - } - - if ((lw == IDOK || lw == IDM_MOUNT_VOLUME || lw == IDM_MOUNT_VOLUME_OPTIONS)) - { - MountSelectedVolume (hwndDlg, lw == IDM_MOUNT_VOLUME_OPTIONS); - return 1; - } - - if (lw == IDC_UNMOUNTALL || lw == IDM_UNMOUNTALL) - { - if (DismountAll (hwndDlg, bForceUnmount, TRUE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY) - && lw == IDM_UNMOUNTALL) // If initiated via the systray menu - { - InfoBalloon ("SUCCESSFULLY_DISMOUNTED", "MOUNTED_VOLUMES_DISMOUNTED", hwndDlg); - } - - return 1; - } - - if (lw == IDC_MOUNTALL || lw == IDM_MOUNTALL) - { - // If Shift key is down and the password cache isn't empty, bypass password prompt - MountAllDevices (hwndDlg, !(GetAsyncKeyState (VK_SHIFT) < 0 && !IsPasswordCacheEmpty())); - return 1; - } - - if (lw == IDC_SELECT_FILE || lw == IDM_SELECT_FILE) - { - SelectContainer (hwndDlg); - return 1; - } - - if (lw == IDC_SELECT_DEVICE || lw == IDM_SELECT_DEVICE) - { - SelectPartition (hwndDlg); - return 1; - } - - // System Encryption menu - switch (lw) - { - case IDM_ENCRYPT_SYSTEM_DEVICE: - EncryptSystemDevice (hwndDlg); - break; - case IDM_PERMANENTLY_DECRYPT_SYS: - DecryptSystemDevice (hwndDlg); - break; - case IDM_CREATE_HIDDEN_OS: - CreateHiddenOS (hwndDlg); - break; - case IDM_SYSENC_RESUME: - ResumeInterruptedSysEncProcess (hwndDlg); - break; - case IDM_SYSTEM_ENCRYPTION_STATUS: - ShowSystemEncryptionStatus (hwndDlg); - break; - case IDM_CHANGE_SYS_PASSWORD: - ChangeSysEncPassword (hwndDlg, FALSE); - break; - case IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO: - ChangeSysEncPassword (hwndDlg, TRUE); - break; - case IDM_CREATE_RESCUE_DISK: - CreateRescueDisk (hwndDlg); - break; - case IDM_VERIFY_RESCUE_DISK: - VerifyRescueDisk (hwndDlg, false); - break; - case IDM_VERIFY_RESCUE_DISK_ISO: - VerifyRescueDisk (hwndDlg, true); - break; - case IDM_MOUNT_SYSENC_PART_WITHOUT_PBA: - - if (CheckSysEncMountWithoutPBA (hwndDlg, L"", FALSE)) - { - mountOptions = defaultMountOptions; - mountOptions.PartitionInInactiveSysEncScope = TRUE; - bPrebootPasswordDlgMode = TRUE; - - if (CheckMountList (hwndDlg, FALSE)) - _beginthread(mountThreadFunction, 0, hwndDlg); - } - break; - } - - if (lw == IDC_VOLUME_TOOLS) - { - /* Volume Tools popup menu */ - - int menuItem; - wchar_t volPath[TC_MAX_PATH]; /* Volume to mount */ - HMENU popup = CreatePopupMenu (); - RECT rect; - - if (ActiveSysEncDeviceSelected ()) - { - PopulateSysEncContextMenu (popup, TRUE); - } - else - { - AppendMenuW (popup, MF_STRING, IDM_CHANGE_PASSWORD, GetString ("IDM_CHANGE_PASSWORD")); - AppendMenuW (popup, MF_STRING, IDM_CHANGE_HEADER_KEY_DERIV_ALGO, GetString ("IDM_CHANGE_HEADER_KEY_DERIV_ALGO")); - AppendMenu (popup, MF_SEPARATOR, 0, L""); - AppendMenuW (popup, MF_STRING, IDM_ADD_REMOVE_VOL_KEYFILES, GetString ("IDM_ADD_REMOVE_VOL_KEYFILES")); - AppendMenuW (popup, MF_STRING, IDM_REMOVE_ALL_KEYFILES_FROM_VOL, GetString ("IDM_REMOVE_ALL_KEYFILES_FROM_VOL")); - AppendMenu (popup, MF_SEPARATOR, 0, L""); - AppendMenuW (popup, MF_STRING, IDM_DECRYPT_NONSYS_VOL, GetString ("IDM_DECRYPT_NONSYS_VOL")); - AppendMenu (popup, MF_SEPARATOR, 0, NULL); - AppendMenuW (popup, MF_STRING, IDM_BACKUP_VOL_HEADER, GetString ("IDM_BACKUP_VOL_HEADER")); - AppendMenuW (popup, MF_STRING, IDM_RESTORE_VOL_HEADER, GetString ("IDM_RESTORE_VOL_HEADER")); - } - - GetWindowRect (GetDlgItem (hwndDlg, IDC_VOLUME_TOOLS), &rect); - - menuItem = TrackPopupMenu (popup, - TPM_RETURNCMD | TPM_LEFTBUTTON, - rect.left + 2, - rect.top + 2, - 0, - hwndDlg, - NULL); - - DestroyMenu (popup); - - switch (menuItem) - { - case IDM_DECRYPT_NONSYS_VOL: - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - DecryptNonSysDevice (hwndDlg, TRUE, FALSE); - } - break; - - case IDM_CHANGE_PASSWORD: - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - pwdChangeDlgMode = PCDM_CHANGE_PASSWORD; - ChangePassword (hwndDlg); - } - break; - - case IDM_CHANGE_HEADER_KEY_DERIV_ALGO: - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - pwdChangeDlgMode = PCDM_CHANGE_PKCS5_PRF; - ChangePassword (hwndDlg); - } - break; - - case IDM_ADD_REMOVE_VOL_KEYFILES: - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - pwdChangeDlgMode = PCDM_ADD_REMOVE_VOL_KEYFILES; - ChangePassword (hwndDlg); - } - break; - - case IDM_REMOVE_ALL_KEYFILES_FROM_VOL: - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - pwdChangeDlgMode = PCDM_REMOVE_ALL_KEYFILES_FROM_VOL; - ChangePassword (hwndDlg); - } - break; - - case IDM_BACKUP_VOL_HEADER: - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - GetVolumePath (hwndDlg, volPath, ARRAYSIZE (volPath)); - - WaitCursor (); - - int iStatus = 0; - BackupHeaderThreadParam threadParam; - threadParam.bRequireConfirmation = TRUE; - threadParam.lpszVolume = volPath; - threadParam.cchVolume = ARRAYSIZE (volPath); - threadParam.iResult = &iStatus; - - ShowWaitDialog (hwndDlg, TRUE, BackupHeaderWaitThreadProc, &threadParam); - - NormalCursor (); - } - break; - - case IDM_RESTORE_VOL_HEADER: - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - GetVolumePath (hwndDlg, volPath, ARRAYSIZE (volPath)); - - WaitCursor (); - - int iStatus = 0; - RestoreHeaderThreadParam threadParam; - threadParam.lpszVolume = volPath; - threadParam.cchVolume = ARRAYSIZE (volPath); - threadParam.iResult = &iStatus; - - ShowWaitDialog(hwndDlg, TRUE, RestoreHeaderWaitThreadProc, &threadParam); - - NormalCursor (); - } - break; - - default: - SendMessage (MainDlg, WM_COMMAND, menuItem, NULL); - break; - } - return 1; - } - - if (lw == IDM_DECRYPT_NONSYS_VOL) - { - LPARAM selectedDrive = GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST)); - - if (LOWORD (selectedDrive) == TC_MLIST_ITEM_FREE && !VolumeSelected (MainDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - DecryptNonSysDevice (hwndDlg, TRUE, FALSE); - } - - return 1; - } - - if (lw == IDM_CHANGE_PASSWORD) - { - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - if (ActiveSysEncDeviceSelected ()) - { - ChangeSysEncPassword (hwndDlg, FALSE); - } - else - { - pwdChangeDlgMode = PCDM_CHANGE_PASSWORD; - ChangePassword (hwndDlg); - } - } - return 1; - } - - if (lw == IDM_CHANGE_HEADER_KEY_DERIV_ALGO) - { - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - if (ActiveSysEncDeviceSelected ()) - { - ChangeSysEncPassword (hwndDlg, TRUE); - } - else - { - pwdChangeDlgMode = PCDM_CHANGE_PKCS5_PRF; - ChangePassword (hwndDlg); - } - } - return 1; - } - - if (lw == IDC_WIPE_CACHE || lw == IDM_WIPE_CACHE) - { - WipeCache (hwndDlg, FALSE); - return 1; - } - - if (lw == IDM_CLEAR_HISTORY) - { - ClearHistory (GetDlgItem (hwndDlg, IDC_VOLUME)); - EnableDisableButtons (hwndDlg); - return 1; - } - - if (lw == IDC_CREATE_VOLUME || lw == IDM_CREATE_VOLUME || lw == IDM_VOLUME_WIZARD) - { - LaunchVolCreationWizard (hwndDlg, L""); - return 1; - } - - if (lw == IDM_VOLUME_EXPANDER) - { - LaunchVolExpander (hwndDlg); - return 1; - } - - if (lw == IDM_ADD_REMOVE_VOL_KEYFILES) - { - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - pwdChangeDlgMode = PCDM_ADD_REMOVE_VOL_KEYFILES; - ChangePassword (hwndDlg); - } - return 1; - } - - if (lw == IDM_REMOVE_ALL_KEYFILES_FROM_VOL) - { - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - pwdChangeDlgMode = PCDM_REMOVE_ALL_KEYFILES_FROM_VOL; - ChangePassword (hwndDlg); - } - return 1; - } - - if (lw == IDM_MANAGE_TOKEN_KEYFILES) - { - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TOKEN_KEYFILES), hwndDlg, (DLGPROC) SecurityTokenKeyfileDlgProc, NULL); - return 1; - } - - if (lw == IDM_CLOSE_ALL_TOKEN_SESSIONS) - { - { - WaitCursor(); - finally_do ({ NormalCursor(); }); - - SecurityToken::CloseAllSessions(); - } - - InfoBalloon (NULL, "ALL_TOKEN_SESSIONS_CLOSED", hwndDlg); - - return 1; - } - - if (lw == IDM_KEYFILE_GENERATOR) - { - DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_KEYFILE_GENERATOR), hwndDlg, - (DLGPROC) KeyfileGeneratorDlgProc, (LPARAM) 0); - - return 1; - } - - if (lw == IDM_DONATE) - { - Applink ("donate", TRUE, ""); - return 1; - } - - if (lw == IDM_LICENSE) - { - TextInfoDialogBox (TC_TBXID_LEGAL_NOTICES); - return 1; - } - - if (lw == IDM_WEBSITE) - { - Applink ("website", TRUE, ""); - return 1; - } - else if (lw == IDM_HOMEPAGE) - { - Applink ("homepage", TRUE, ""); - return 1; - } - else if (lw == IDM_ONLINE_TUTORIAL) - { - Applink ("tutorial", TRUE, ""); - return 1; - } - else if (lw == IDM_ONLINE_HELP) - { - OpenOnlineHelp (); - return 1; - } - else if (lw == IDM_FAQ) - { - Applink ("faq", TRUE, ""); - return 1; - } - else if (lw == IDM_TC_DOWNLOADS) - { - Applink ("downloads", TRUE, ""); - return 1; - } - else if (lw == IDM_NEWS) - { - Applink ("news", TRUE, ""); - return 1; - } - else if (lw == IDM_VERSION_HISTORY) - { - Applink ("history", TRUE, ""); - return 1; - } - else if (lw == IDM_CONTACT) - { - Applink ("contact", FALSE, ""); - return 1; - } - - if (lw == IDM_PREFERENCES) - { - if (IDOK == DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_PREFERENCES_DLG), hwndDlg, - (DLGPROC) PreferencesDlgProc, (LPARAM) 0)) - { - if (bEnableBkgTask) - { - TaskBarIconAdd (hwndDlg); - RegisterWtsNotification(hwndDlg); - } - else - { - TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); - if (MainWindowHidden) - EndMainDlg (hwndDlg); - } - } - return 1; - } - - if (lw == IDM_HOTKEY_SETTINGS) - { - DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_HOTKEYS_DLG), hwndDlg, - (DLGPROC) HotkeysDlgProc, (LPARAM) 0); - return 1; - } - - if (lw == IDM_PERFORMANCE_SETTINGS) - { - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_PERFORMANCE_SETTINGS), hwndDlg, (DLGPROC) PerformanceSettingsDlgProc, 0); - return 1; - } - - if (lw == IDM_DEFAULT_KEYFILES) - { - KeyfileDefaultsDlg (hwndDlg); - return 1; - } - - if (lw == IDM_DEFAULT_MOUNT_PARAMETERS) - { - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_DEFAULT_MOUNT_PARAMETERS), hwndDlg, (DLGPROC) DefaultMountParametersDlgProc, 0); - return 1; - } - - if (lw == IDM_ADD_VOLUME_TO_FAVORITES || lw == IDM_ADD_VOLUME_TO_SYSTEM_FAVORITES) - { - LPARAM selectedDrive = GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST)); - - wchar_t volPathLower[TC_MAX_PATH]; - - // volPathLower will contain the volume path (if any) from the input field below the drive list - GetVolumePath (hwndDlg, volPathLower, ARRAYSIZE (volPathLower)); - - if (LOWORD (selectedDrive) != TC_MLIST_ITEM_NONSYS_VOL - && !(VolumeSelected (hwndDlg) && IsMountedVolume (volPathLower))) - { - Warning ("SELECT_A_MOUNTED_VOLUME", hwndDlg); - - return 1; - } - - int driveNo; - - if (VolumeSelected (hwndDlg) - && IsMountedVolume (volPathLower)) - { - TranslateVolumeID (hwndDlg, volPathLower, ARRAYSIZE (volPathLower)); - - if (LOWORD (selectedDrive) != TC_MLIST_ITEM_NONSYS_VOL) - { - driveNo = GetMountedVolumeDriveNo (volPathLower); - } - else - { - /* We need to resolve selection ambiguity. Two different mounted volumes are currently - selected (one in the drive letter list and the other in the input field below the list). */ - - VOLUME_PROPERTIES_STRUCT prop; - DWORD dwResult; - - memset (&prop, 0, sizeof(prop)); - prop.driveNo = HIWORD (selectedDrive) - L'A'; - - if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL) || dwResult == 0) - { - Warning ("SELECT_A_MOUNTED_VOLUME", hwndDlg); - return 1; - } - - // volPathHigher will contain the volume path selected in the main drive list - wstring volPathHigher (prop.wszVolume); - - if (wcscmp (((wmemcmp (prop.wszVolume, L"\\??\\", 4) == 0) ? (wchar_t *) prop.wszVolume + 4 : prop.wszVolume), volPathLower) != 0) - { - // The path selected in the input field is different from the path to the volume selected - // in the drive lettter list. We have to resolve possible ambiguity. - - wchar_t *tmp[] = {L"", L"", L"", L"", L"", 0}; - const int maxVolPathLen = 80; - - if (volPathHigher.length () > maxVolPathLen) - { - volPathHigher = wstring (L"...") + volPathHigher.substr (volPathHigher.length () - maxVolPathLen, maxVolPathLen); - } - - wstring volPathLowerWStr (volPathLower); - - if (volPathLowerWStr.length () > maxVolPathLen) - { - volPathLowerWStr = wstring (L"...") + volPathLowerWStr.substr (volPathLowerWStr.length () - maxVolPathLen, maxVolPathLen); - } - - tmp[1] = GetString ("AMBIGUOUS_VOL_SELECTION"); - tmp[2] = (wchar_t *) volPathHigher.c_str(); - tmp[3] = (wchar_t *) volPathLowerWStr.c_str(); - tmp[4] = GetString ("IDCANCEL"); - - switch (AskMultiChoice ((void **) tmp, FALSE, hwndDlg)) - { - case 1: - driveNo = HIWORD (selectedDrive) - L'A'; - break; - - case 2: - driveNo = GetMountedVolumeDriveNo (volPathLower); - break; - - default: - return 1; - } - } - else - { - driveNo = HIWORD (selectedDrive) - L'A'; - } - } - } - else - { - driveNo = HIWORD (selectedDrive) - L'A'; - } - - AddMountedVolumeToFavorites (hwndDlg, driveNo, lw == IDM_ADD_VOLUME_TO_SYSTEM_FAVORITES); - - return 1; - } - - if (lw == IDM_ORGANIZE_FAVORITES || lw == IDM_ORGANIZE_SYSTEM_FAVORITES) - { - OrganizeFavoriteVolumes (hwndDlg, lw == IDM_ORGANIZE_SYSTEM_FAVORITES); - return 1; - } - - if (lw == IDM_TOKEN_PREFERENCES) - { - SecurityTokenPreferencesDialog (hwndDlg); - return 1; - } - - if (lw == IDM_SYSENC_SETTINGS || lw == IDM_SYS_ENC_SETTINGS) - { - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_SETTINGS), hwndDlg, (DLGPROC) BootLoaderPreferencesDlgProc, 0); - return 1; - } - - if (lw == IDM_SYS_FAVORITES_SETTINGS) - { - OrganizeFavoriteVolumes (hwndDlg, true); - return 1; - } - - if (lw == IDM_BENCHMARK) - { - Benchmark (hwndDlg); - return 1; - } - - if (lw == IDM_TRAVELER) - { - DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_TRAVELER_DLG), hwndDlg, - (DLGPROC) TravelerDlgProc, (LPARAM) 0); - return 1; - } - - if (lw == IDM_BACKUP_VOL_HEADER) - { - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - wchar_t volPath[TC_MAX_PATH]; /* Volume to mount */ - - GetVolumePath (hwndDlg, volPath, ARRAYSIZE (volPath)); - - WaitCursor (); - - int iStatus = 0; - BackupHeaderThreadParam threadParam; - threadParam.bRequireConfirmation = TRUE; - threadParam.lpszVolume = volPath; - threadParam.cchVolume = ARRAYSIZE (volPath); - threadParam.iResult = &iStatus; - - ShowWaitDialog (hwndDlg, TRUE, BackupHeaderWaitThreadProc, &threadParam); - - NormalCursor (); - } - return 1; - } - - if (lw == IDM_RESTORE_VOL_HEADER) - { - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else - { - wchar_t volPath[TC_MAX_PATH]; /* Volume to mount */ - - GetVolumePath (hwndDlg, volPath, ARRAYSIZE (volPath)); - - WaitCursor (); - - int iStatus = 0; - RestoreHeaderThreadParam threadParam; - threadParam.lpszVolume = volPath; - threadParam.cchVolume = ARRAYSIZE (volPath); - threadParam.iResult = &iStatus; - - ShowWaitDialog(hwndDlg, TRUE, RestoreHeaderWaitThreadProc, &threadParam); - - NormalCursor (); - } - return 1; - } - - if (lw == IDM_LANGUAGE) - { - BOOL p; - if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_LANGUAGE), hwndDlg, - (DLGPROC) LanguageDlgProc, (LPARAM) 0) == IDOK) - { - LoadLanguageFile (); - SaveSettings (hwndDlg); - - p = LocalizationActive; - LocalizationActive = TRUE; - InitMainDialog (hwndDlg); - InvalidateRect (hwndDlg, NULL, FALSE); - LocalizationActive = p; - DrawMenuBar (hwndDlg); - } - return 1; - } - - if (lw == IDM_TEST_VECTORS) - { - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_CIPHER_TEST_DLG), hwndDlg, (DLGPROC) CipherTestDialogProc, (LPARAM) 1); - return 1; - } - - if (lw == IDM_REFRESH_DRIVE_LETTERS) - { - DWORD driveMap = GetUsedLogicalDrives (); - - WaitCursor (); - - if (!(nCurrentOS == WIN_2000 && RemoteSession)) - { - BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, 0, ~driveMap); - Sleep (100); - BroadcastDeviceChange (DBT_DEVICEARRIVAL, 0, driveMap); - } - - LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), 0); - - if (nSelectedDriveIndex >= 0) - { - SelectItem (GetDlgItem (hwndDlg, IDC_DRIVELIST), - (wchar_t) HIWORD (GetItemLong (GetDlgItem (hwndDlg, IDC_DRIVELIST), nSelectedDriveIndex))); - } - - NormalCursor (); - return 1; - } - - if (lw == IDM_MOUNT_FAVORITE_VOLUMES) - { - _beginthread(mountFavoriteVolumeThreadFunction, 0, NULL); - return 1; - } - - if (lw == IDM_RESUME_INTERRUPTED_PROC) - { - // Ask the user to select encryption, decryption, or cancel - BOOL bDecrypt = FALSE; - char *tmpStr[] = {0, - "CHOOSE_ENCRYPT_OR_DECRYPT", - "ENCRYPT", - "DECRYPT", - "IDCANCEL", - 0}; - - switch (AskMultiChoice ((void **) tmpStr, FALSE, hwndDlg)) - { - case 1: - bDecrypt = FALSE; - break; - case 2: - bDecrypt = TRUE; - break; - default: - return 1; - } - ResumeInterruptedNonSysInplaceEncProcess (bDecrypt); - return 1; - } - - if (lw == IDC_VOLUME_PROPERTIES || lw == IDM_VOLUME_PROPERTIES) - { - DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_VOLUME_PROPERTIES), hwndDlg, - (DLGPROC) VolumePropertiesDlgProc, (LPARAM) 0); - return 1; - } - - if (lw == IDC_VOLUME && hw == CBN_EDITCHANGE) - { - EnableDisableButtons (hwndDlg); - return 1; - } - - if (lw == IDC_VOLUME && hw == CBN_SELCHANGE) - { - UpdateComboOrder (GetDlgItem (hwndDlg, IDC_VOLUME)); - MoveEditToCombo ((HWND) lParam, bHistory); - PostMessage (hwndDlg, TC_APPMSG_MOUNT_ENABLE_DISABLE_CONTROLS, 0, 0); - return 1; - } - - if (lw == IDC_NO_HISTORY) - { - if (!(bHistory = !IsButtonChecked (GetDlgItem (hwndDlg, IDC_NO_HISTORY)))) - ClearHistory (GetDlgItem (hwndDlg, IDC_VOLUME)); - - return 1; - } - - if (lw >= TC_FAVORITE_MENU_CMD_ID_OFFSET && lw < TC_FAVORITE_MENU_CMD_ID_OFFSET_END) - { - size_t favoriteIndex = lw - TC_FAVORITE_MENU_CMD_ID_OFFSET; - - if (favoriteIndex < FavoriteVolumes.size()) - { - if ((FavoriteVolumes[favoriteIndex].UseVolumeID && IsMountedVolumeID (FavoriteVolumes[favoriteIndex].VolumeID)) - || (!FavoriteVolumes[favoriteIndex].UseVolumeID && IsMountedVolume (FavoriteVolumes[favoriteIndex].Path.c_str())) - ) - { - std::wstring volName; - WaitCursor(); - if (FavoriteVolumes[favoriteIndex].UseVolumeID) - volName = FindDeviceByVolumeID (FavoriteVolumes[favoriteIndex].VolumeID); - else - volName = FavoriteVolumes[favoriteIndex].Path; - OpenVolumeExplorerWindow (GetMountedVolumeDriveNo ((wchar_t*) FavoriteVolumes[favoriteIndex].Path.c_str())); - NormalCursor(); - } - else - { - mountFavoriteVolumeThreadParam* pParam = (mountFavoriteVolumeThreadParam*) calloc(1, sizeof(mountFavoriteVolumeThreadParam)); - pParam->systemFavorites = FALSE; - pParam->logOnMount = FALSE; - pParam->hotKeyMount = FALSE; - pParam->favoriteVolumeToMount = &FavoriteVolumes[favoriteIndex]; - - _beginthread(mountFavoriteVolumeThreadFunction, 0, pParam); - } - } - - return 1; - } - - return 0; - - case WM_DROPFILES: - { - HDROP hdrop = (HDROP) wParam; - DragQueryFile (hdrop, 0, szFileName, ARRAYSIZE (szFileName)); - DragFinish (hdrop); - - AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory); - EnableDisableButtons (hwndDlg); - SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST)); - } - return 1; - - case TC_APPMSG_MOUNT_ENABLE_DISABLE_CONTROLS: - EnableDisableButtons (hwndDlg); - return 1; - - case TC_APPMSG_MOUNT_SHOW_WINDOW: - MainWindowHidden = FALSE; - ShowWindow (hwndDlg, SW_SHOW); - ShowWindow (hwndDlg, SW_RESTORE); - return 1; - - case WM_COPYDATA: - { - PCOPYDATASTRUCT cd = (PCOPYDATASTRUCT)lParam; - if (memcmp (&cd->dwData, WM_COPY_SET_VOLUME_NAME, 4) == 0) - { - if (cd->cbData > 0) - { - ((wchar_t *) cd->lpData)[(cd->cbData / sizeof (wchar_t)) - 1] = 0; - AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), (wchar_t *)cd->lpData, bHistory); - } - - EnableDisableButtons (hwndDlg); - SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST)); - } - } - return 1; - - case WM_CLOSE: - EndMainDlg (hwndDlg); - return 1; - - case WM_INITMENUPOPUP: - { - // disable "Set Header Key Derivation Algorithm" entry in "Volumes" menu - // "Volumes" menu is the first (index 0) submenu of the main menu - if ((HMENU) wParam == GetSubMenu (GetMenu (hwndDlg), 0)) - { - if (ActiveSysEncDeviceSelected ()) - EnableMenuItem (GetMenu (hwndDlg), IDM_CHANGE_HEADER_KEY_DERIV_ALGO, MF_GRAYED); - else - EnableMenuItem (GetMenu (hwndDlg), IDM_CHANGE_HEADER_KEY_DERIV_ALGO, MF_ENABLED); - } - } - return 1; - - default: - // Recreate tray icon if Explorer restarted - if (taskBarCreatedMsg != 0 && uMsg == taskBarCreatedMsg && TaskBarIconMutex != NULL) - { - TaskBarIconRemove (hwndDlg); - TaskBarIconAdd (hwndDlg); - CheckMountList(hwndDlg, TRUE); - return 1; - } - } - - return 0; -} - -void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) -{ - wchar_t **lpszCommandLineArgs = NULL; /* Array of command line arguments */ - int nNoCommandLineArgs; /* The number of arguments in the array */ - wchar_t tmpPath[MAX_PATH * 2]; - - /* Defaults */ - mountOptions.PreserveTimestamp = TRUE; - - if (_wcsicmp (lpszCommandLine, L"-Embedding") == 0) - { - ComServerMode = TRUE; - return; - } - - /* Extract command line arguments */ - NoCmdLineArgs = nNoCommandLineArgs = Win32CommandLine (&lpszCommandLineArgs); - - if (nNoCommandLineArgs > 0) - { - int i; - - for (i = 0; i < nNoCommandLineArgs; i++) - { - enum - { - OptionAuto, - OptionBeep, - OptionCache, - CommandDismount, - OptionExplore, - OptionForce, - CommandHelp, - OptionHistory, - OptionKeyfile, - OptionLetter, - OptionMountOption, - OptionPassword, - OptionQuit, - OptionSilent, - OptionTokenLib, - OptionTokenPin, - OptionVolume, - CommandWipeCache, - OptionPkcs5, - OptionTrueCryptMode, - OptionPim, - OptionTryEmptyPassword, - OptionNoWaitDlg, - }; - - argument args[]= - { - { OptionAuto, L"/auto", L"/a", FALSE }, - { OptionBeep, L"/beep", L"/b", FALSE }, - { OptionCache, L"/cache", L"/c", FALSE }, - { CommandDismount, L"/dismount", L"/d", FALSE }, - { OptionExplore, L"/explore", L"/e", FALSE }, - { OptionForce, L"/force", L"/f", FALSE }, - { OptionPkcs5, L"/hash", NULL , FALSE }, - { CommandHelp, L"/help", L"/?", FALSE }, - { OptionHistory, L"/history", L"/h", FALSE }, - { OptionKeyfile, L"/keyfile", L"/k", FALSE }, - { OptionLetter, L"/letter", L"/l", FALSE }, - { OptionMountOption, L"/mountoption", L"/m", FALSE }, - { OptionPassword, L"/password", L"/p", FALSE }, - { OptionPim, L"/pim", NULL, FALSE }, - { OptionQuit, L"/quit", L"/q", FALSE }, - { OptionSilent, L"/silent", L"/s", FALSE }, - { OptionTokenLib, L"/tokenlib", NULL, FALSE }, - { OptionTokenPin, L"/tokenpin", NULL, FALSE }, - { OptionTrueCryptMode, L"/truecrypt", L"/tc", FALSE }, - { OptionVolume, L"/volume", L"/v", FALSE }, - { CommandWipeCache, L"/wipecache", L"/w", FALSE }, - { OptionTryEmptyPassword, L"/tryemptypass", NULL, FALSE }, - { OptionNoWaitDlg, L"/nowaitdlg", NULL, FALSE }, - }; - - argumentspec as; - - as.args = args; - as.arg_cnt = sizeof(args)/ sizeof(args[0]); - - switch (GetArgumentID (&as, lpszCommandLineArgs[i])) - { - case OptionAuto: - { - wchar_t szTmp[32] = {0}; - bAuto = TRUE; - - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, - &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) - { - if (!_wcsicmp (szTmp, L"devices")) - bAutoMountDevices = TRUE; - else if (!_wcsicmp (szTmp, L"favorites")) - bAutoMountFavorites = TRUE; - else if (!_wcsicmp (szTmp, L"logon")) - LogOn = TRUE; - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - } - break; - - case OptionBeep: - bBeep = TRUE; - break; - - case OptionTryEmptyPassword: - { - wchar_t szTmp[16] = {0}; - bCmdTryEmptyPasswordWhenKeyfileUsed = TRUE; - bCmdTryEmptyPasswordWhenKeyfileUsedValid = TRUE; - - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, - szTmp, ARRAYSIZE (szTmp))) - { - if (!_wcsicmp(szTmp,L"n") || !_wcsicmp(szTmp,L"no")) - bCmdTryEmptyPasswordWhenKeyfileUsed = FALSE; - else if (!_wcsicmp(szTmp,L"y") || !_wcsicmp(szTmp,L"yes")) - bCmdTryEmptyPasswordWhenKeyfileUsed = TRUE; - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - } - break; - - case OptionNoWaitDlg: - { - wchar_t szTmp[16] = {0}; - bCmdHideWaitingDialog = TRUE; - bCmdHideWaitingDialogValid = TRUE; - - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, - szTmp, ARRAYSIZE (szTmp))) - { - if (!_wcsicmp(szTmp,L"n") || !_wcsicmp(szTmp,L"no")) - bCmdHideWaitingDialog = FALSE; - else if (!_wcsicmp(szTmp,L"y") || !_wcsicmp(szTmp,L"yes")) - bCmdHideWaitingDialog = TRUE; - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - } - break; - - case OptionCache: - { - wchar_t szTmp[16] = {0}; - bCacheInDriver = TRUE; - bIncludePimInCache = FALSE; - - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, - szTmp, ARRAYSIZE (szTmp))) - { - if (!_wcsicmp(szTmp,L"n") || !_wcsicmp(szTmp,L"no")) - bCacheInDriver = FALSE; - else if (!_wcsicmp(szTmp,L"y") || !_wcsicmp(szTmp,L"yes")) - bCacheInDriver = TRUE; - else if (!_wcsicmp(szTmp,L"p") || !_wcsicmp(szTmp,L"pim")) - { - bCacheInDriver = TRUE; - bIncludePimInCache = TRUE; - } - else if (!_wcsicmp(szTmp,L"f") || !_wcsicmp(szTmp,L"favorites")) - { - bCacheInDriver = FALSE; - bCmdCacheDuringMultipleMount = TRUE; - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - } - break; - - case CommandDismount: - - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, - szDriveLetter, ARRAYSIZE (szDriveLetter))) - { - if ( (wcslen(szDriveLetter) == 1) - || (wcslen(szDriveLetter) == 2 && szDriveLetter[1] == L':') - ) - { - cmdUnmountDrive = towupper(szDriveLetter[0]) - L'A'; - if ((cmdUnmountDrive < 0) || (cmdUnmountDrive > (L'Z' - L'A'))) - AbortProcess ("BAD_DRIVE_LETTER"); - } - else - AbortProcess ("BAD_DRIVE_LETTER"); - - } - else - cmdUnmountDrive = -1; - - break; - - case OptionExplore: - bExplore = TRUE; - break; - - case OptionForce: - bForceMount = TRUE; - bForceUnmount = TRUE; - break; - - case OptionKeyfile: - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, - nNoCommandLineArgs, tmpPath, ARRAYSIZE (tmpPath))) - { - KeyFile *kf; - RelativePath2Absolute (tmpPath); - kf = (KeyFile *) malloc (sizeof (KeyFile)); - if (kf) - { - StringCchCopyW (kf->FileName, ARRAYSIZE(kf->FileName), tmpPath); - FirstCmdKeyFile = KeyFileAdd (FirstCmdKeyFile, kf); - } - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - - break; - - case OptionLetter: - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, - szDriveLetter, ARRAYSIZE (szDriveLetter))) - { - if ( (wcslen(szDriveLetter) == 1) - || (wcslen(szDriveLetter) == 2 && szDriveLetter[1] == L':') - ) - { - commandLineDrive = *szDriveLetter = (wchar_t) towupper (*szDriveLetter); - - if (commandLineDrive < L'A' || commandLineDrive > L'Z') - AbortProcess ("BAD_DRIVE_LETTER"); - } - else - AbortProcess ("BAD_DRIVE_LETTER"); - } - else - AbortProcess ("BAD_DRIVE_LETTER"); - - break; - - case OptionHistory: - { - wchar_t szTmp[8] = {0}; - bHistory = bHistoryCmdLine = TRUE; - - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, - szTmp, ARRAYSIZE (szTmp))) - { - if (!_wcsicmp(szTmp,L"n") || !_wcsicmp(szTmp,L"no")) - bHistory = FALSE; - else if (!_wcsicmp(szTmp,L"y") || !_wcsicmp(szTmp,L"yes")) - bHistory = TRUE; - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - } - break; - - case OptionMountOption: - { - wchar_t szTmp[64] = {0}; - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, - &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) - { - if (!_wcsicmp (szTmp, L"ro") || !_wcsicmp (szTmp, L"readonly")) - mountOptions.ReadOnly = TRUE; - - else if (!_wcsicmp (szTmp, L"rm") || !_wcsicmp (szTmp, L"removable")) - mountOptions.Removable = TRUE; - - else if (!_wcsicmp (szTmp, L"ts") || !_wcsicmp (szTmp, L"timestamp")) - mountOptions.PreserveTimestamp = FALSE; - - else if (!_wcsicmp (szTmp, L"sm") || !_wcsicmp (szTmp, L"system")) - mountOptions.PartitionInInactiveSysEncScope = bPrebootPasswordDlgMode = TRUE; - - else if (!_wcsicmp (szTmp, L"bk") || !_wcsicmp (szTmp, L"headerbak")) - mountOptions.UseBackupHeader = TRUE; - - else if (!_wcsicmp (szTmp, L"recovery")) - mountOptions.RecoveryMode = TRUE; - else if ((wcslen(szTmp) > 6) && (wcslen(szTmp) <= 38) && !_wcsnicmp (szTmp, L"label=", 6)) - { - // get the label - StringCbCopyW (mountOptions.Label, sizeof (mountOptions.Label), &szTmp[6]); - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - - CmdMountOptions = mountOptions; - CmdMountOptionsValid = TRUE; - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - break; - - case OptionPassword: - { - wchar_t szTmp[MAX_PASSWORD + 1]; - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, - szTmp, ARRAYSIZE (szTmp))) - { - int iLen = WideCharToMultiByte (CP_UTF8, 0, szTmp, -1, (char*) CmdVolumePassword.Text, MAX_PASSWORD + 1, NULL, NULL); - burn (szTmp, sizeof (szTmp)); - if (iLen > 0) - { - CmdVolumePassword.Length = (unsigned __int32) (iLen - 1); - CmdVolumePasswordValid = TRUE; - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - break; - - case OptionVolume: - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, - nNoCommandLineArgs, szFileName, ARRAYSIZE (szFileName))) - { - RelativePath2Absolute (szFileName); - AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory); - CmdLineVolumeSpecified = TRUE; - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - break; - - case OptionQuit: - { - wchar_t szTmp[32] = {0}; - - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, - &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) - { - if (!_wcsicmp (szTmp, L"UAC")) // Used to indicate non-install elevation - break; - - else if (!_wcsicmp (szTmp, L"preferences")) - { - Quit = TRUE; - UsePreferences = TRUE; - break; - } - - else if (!_wcsicmp (szTmp, L"background")) - bEnableBkgTask = TRUE; - - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - - Quit = TRUE; - UsePreferences = FALSE; - } - break; - - case OptionSilent: - Silent = TRUE; - break; - - case OptionTokenLib: - if (GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, SecurityTokenLibraryPath, ARRAYSIZE (SecurityTokenLibraryPath)) == HAS_ARGUMENT) - InitSecurityTokenLibrary(hwndDlg); - else - AbortProcess ("COMMAND_LINE_ERROR"); - - break; - - case OptionTokenPin: - { - wchar_t szTmp[SecurityToken::MaxPasswordLength + 1] = {0}; - if (GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp)) == HAS_ARGUMENT) - { - if (0 == WideCharToMultiByte (CP_UTF8, 0, szTmp, -1, CmdTokenPin, array_capacity (CmdTokenPin), nullptr, nullptr)) - AbortProcess ("COMMAND_LINE_ERROR"); - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - - break; - - case CommandWipeCache: - bWipe = TRUE; - break; - - case CommandHelp: - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_COMMANDHELP_DLG), hwndDlg, (DLGPROC) - CommandHelpDlgProc, (LPARAM) &as); - exit(0); - break; - - case OptionPkcs5: - { - wchar_t szTmp[32] = {0}; - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, - &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) - { - if (_wcsicmp(szTmp, L"sha512") == 0 || _wcsicmp(szTmp, L"sha-512") == 0) - CmdVolumePkcs5 = SHA512; - else if (_wcsicmp(szTmp, L"whirlpool") == 0) - CmdVolumePkcs5 = WHIRLPOOL; - else if (_wcsicmp(szTmp, L"sha256") == 0 || _wcsicmp(szTmp, L"sha-256") == 0) - CmdVolumePkcs5 = SHA256; - else if (_wcsicmp(szTmp, L"ripemd160") == 0 || _wcsicmp(szTmp, L"ripemd-160") == 0) - CmdVolumePkcs5 = RIPEMD160; - else - { - CmdVolumePkcs5 = 0; - AbortProcess ("COMMAND_LINE_ERROR"); - } - - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - break; - - case OptionPim: - { - wchar_t szTmp[32] = {0}; - if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, - &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) - { - wchar_t* endPtr = NULL; - CmdVolumePim = (int) wcstol(szTmp, &endPtr, 0); - if (CmdVolumePim < 0 || CmdVolumePim > MAX_PIM_VALUE || endPtr == szTmp || *endPtr != L'\0') - { - CmdVolumePim = 0; - AbortProcess ("COMMAND_LINE_ERROR"); - } - - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - break; - - case OptionTrueCryptMode: - CmdVolumeTrueCryptMode = TRUE; - break; - - // no option = file name if there is only one argument - default: - { - if (nNoCommandLineArgs == 1) - { - StringCbCopyW (szFileName, array_capacity (szFileName), lpszCommandLineArgs[i]); - RelativePath2Absolute (szFileName); - - CmdLineVolumeSpecified = TRUE; - AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory); - } - else - AbortProcess ("COMMAND_LINE_ERROR"); - } - } - } - } - - /* Free up the command line arguments */ - while (--nNoCommandLineArgs >= 0) - { - free (lpszCommandLineArgs[nNoCommandLineArgs]); - } - - if (lpszCommandLineArgs) - free (lpszCommandLineArgs); -} - - -static SERVICE_STATUS SystemFavoritesServiceStatus; -static SERVICE_STATUS_HANDLE SystemFavoritesServiceStatusHandle; - -static void SystemFavoritesServiceLogMessage (const wstring &errorMessage, WORD wType) -{ - HANDLE eventSource = RegisterEventSource (NULL, TC_SYSTEM_FAVORITES_SERVICE_NAME); - - if (eventSource) - { - LPCTSTR strings[] = { TC_SYSTEM_FAVORITES_SERVICE_NAME, errorMessage.c_str() }; - ReportEvent (eventSource, wType, 0, 0xC0000000 + wType, NULL, array_capacity (strings), 0, strings, NULL); - - DeregisterEventSource (eventSource); - } -} - -static void SystemFavoritesServiceLogError (const wstring &errorMessage) -{ - SystemFavoritesServiceLogMessage (errorMessage, EVENTLOG_ERROR_TYPE); -} - -static void SystemFavoritesServiceLogWarning (const wstring &warningMessage) -{ - SystemFavoritesServiceLogMessage (warningMessage, EVENTLOG_WARNING_TYPE); -} - -static void SystemFavoritesServiceLogInfo (const wstring &infoMessage) -{ - SystemFavoritesServiceLogMessage (infoMessage, EVENTLOG_INFORMATION_TYPE); -} - - -static void SystemFavoritesServiceSetStatus (DWORD status, DWORD waitHint = 0) -{ - SystemFavoritesServiceStatus.dwCurrentState = status; - SystemFavoritesServiceStatus.dwWaitHint = waitHint; - SystemFavoritesServiceStatus.dwWin32ExitCode = NO_ERROR; - - SetServiceStatus (SystemFavoritesServiceStatusHandle, &SystemFavoritesServiceStatus); -} - - -static VOID WINAPI SystemFavoritesServiceCtrlHandler (DWORD control) -{ - if (control == SERVICE_CONTROL_STOP) - SystemFavoritesServiceSetStatus (SERVICE_STOP_PENDING); - else - SystemFavoritesServiceSetStatus (SystemFavoritesServiceStatus.dwCurrentState); -} - - -static VOID WINAPI SystemFavoritesServiceMain (DWORD argc, LPTSTR *argv) -{ - BOOL status = FALSE; - memset (&SystemFavoritesServiceStatus, 0, sizeof (SystemFavoritesServiceStatus)); - SystemFavoritesServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; - - SystemFavoritesServiceStatusHandle = RegisterServiceCtrlHandler (TC_SYSTEM_FAVORITES_SERVICE_NAME, SystemFavoritesServiceCtrlHandler); - if (!SystemFavoritesServiceStatusHandle) - return; - - SystemFavoritesServiceSetStatus (SERVICE_START_PENDING, 120000); - - SystemFavoritesServiceLogInfo (wstring (L"Starting System Favorites mounting process")); - - try - { - status = MountFavoriteVolumes (NULL, TRUE); - } - catch (...) { } - - if (status) - { - SystemFavoritesServiceLogInfo (wstring (L"System Favorites mounting process finished")); - } - else - { - SystemFavoritesServiceLogError (wstring (L"System Favorites mounting process failed.")); - } - - SystemFavoritesServiceSetStatus (SERVICE_RUNNING); - SystemFavoritesServiceSetStatus (SERVICE_STOPPED); -} - - -static BOOL StartSystemFavoritesService () -{ - ServiceMode = TRUE; - Silent = TRUE; - DeviceChangeBroadcastDisabled = TRUE; - bShowDisconnectedNetworkDrives = TRUE; - bHideWaitingDialog = TRUE; - - InitOSVersionInfo(); - - if (DriverAttach() != ERR_SUCCESS) - return FALSE; - - SERVICE_TABLE_ENTRY serviceTable[2]; - serviceTable[0].lpServiceName = TC_SYSTEM_FAVORITES_SERVICE_NAME; - serviceTable[0].lpServiceProc = SystemFavoritesServiceMain; - - serviceTable[1].lpServiceName = NULL; - serviceTable[1].lpServiceProc = NULL; - - BOOL result = StartServiceCtrlDispatcher (serviceTable); - - if (!(ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD)) - WipeCache (NULL, TRUE); - - return result; -} - -#ifndef VCEXPANDER -int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpszCommandLine, int nCmdShow) -{ - int argc; - LPWSTR *argv = CommandLineToArgvW (GetCommandLineW(), &argc); - - if (argv && argc == 2 && wstring (TC_SYSTEM_FAVORITES_SERVICE_CMDLINE_OPTION) == argv[1]) - return StartSystemFavoritesService() ? 0 : 1; - - int status; - atexit (localcleanup); - SetProcessShutdownParameters (0x100, 0); - - VirtualLock (&VolumePassword, sizeof (VolumePassword)); - VirtualLock (&CmdVolumePassword, sizeof (CmdVolumePassword)); - VirtualLock (&mountOptions, sizeof (mountOptions)); - VirtualLock (&defaultMountOptions, sizeof (defaultMountOptions)); - VirtualLock (&szFileName, sizeof(szFileName)); - VirtualLock (&CmdTokenPin, sizeof (CmdTokenPin)); - - DetectX86Features (); - - try - { - BootEncObj = new BootEncryption (NULL); - } - catch (Exception &e) - { - e.Show (NULL); - } - - if (BootEncObj == NULL) - AbortProcess ("INIT_SYS_ENC"); - - InitApp (hInstance, lpszCommandLine); - - RegisterRedTick(hInstance); - - /* Allocate, dup, then store away the application title */ - lpszTitle = L"VeraCrypt"; - - status = DriverAttach (); - if (status != 0) - { - if (status == ERR_OS_ERROR) - handleWin32Error (NULL, SRC_POS); - else - handleError (NULL, status, SRC_POS); - - AbortProcess ("NODRIVER"); - } - - /* Create the main dialog box */ - DialogBoxParamW (hInstance, MAKEINTRESOURCEW (IDD_MOUNT_DLG), NULL, (DLGPROC) MainDialogProc, - (LPARAM) lpszCommandLine); - - FinalizeApp (); - /* Terminate */ - return 0; -} -#endif - - -BOOL TaskBarIconAdd (HWND hwnd) -{ - NOTIFYICONDATAW tnid; - - ZeroMemory (&tnid, sizeof (tnid)); - - // Only one icon may be created - if (TaskBarIconMutex != NULL) return TRUE; - - TaskBarIconMutex = CreateMutex (NULL, TRUE, L"VeraCryptTaskBarIcon"); - if (TaskBarIconMutex == NULL || GetLastError () == ERROR_ALREADY_EXISTS) - { - if (TaskBarIconMutex != NULL) - { - CloseHandle(TaskBarIconMutex); - TaskBarIconMutex = NULL; - } - return FALSE; - } - - tnid.cbSize = sizeof (NOTIFYICONDATAW); - tnid.hWnd = hwnd; - tnid.uID = IDI_TRUECRYPT_ICON; - tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; - tnid.uCallbackMessage = TC_APPMSG_TASKBAR_ICON; - tnid.hIcon = (HICON) LoadImage (hInst, MAKEINTRESOURCE (IDI_TRUECRYPT_ICON), - IMAGE_ICON, - ScreenDPI >= 120 ? 0 : 16, - ScreenDPI >= 120 ? 0 : 16, - (ScreenDPI >= 120 ? LR_DEFAULTSIZE : 0) - | LR_SHARED - | (nCurrentOS != WIN_2000 ? LR_DEFAULTCOLOR : LR_VGACOLOR)); // Windows 2000 cannot display more than 16 fixed colors in notification tray - - StringCbCopyW (tnid.szTip, sizeof(tnid.szTip), L"VeraCrypt"); - - return Shell_NotifyIconW (NIM_ADD, &tnid); -} - - -BOOL TaskBarIconRemove (HWND hwnd) -{ - if (TaskBarIconMutex != NULL) - { - NOTIFYICONDATA tnid; - BOOL res; - - ZeroMemory (&tnid, sizeof (tnid)); - tnid.cbSize = sizeof(NOTIFYICONDATA); - tnid.hWnd = hwnd; - tnid.uID = IDI_TRUECRYPT_ICON; - - res = Shell_NotifyIcon (NIM_DELETE, &tnid); - if (TaskBarIconMutex) - { - CloseHandle (TaskBarIconMutex); - TaskBarIconMutex = NULL; - } - return res; - } - else - return FALSE; -} - - -BOOL TaskBarIconChange (HWND hwnd, int iconId) -{ - if (TaskBarIconMutex == NULL) - return FALSE; - - NOTIFYICONDATA tnid; - - ZeroMemory (&tnid, sizeof (tnid)); - - tnid.cbSize = sizeof (tnid); - tnid.hWnd = hwnd; - tnid.uID = IDI_TRUECRYPT_ICON; - tnid.uFlags = NIF_ICON; - tnid.hIcon = (HICON) LoadImage (hInst, MAKEINTRESOURCE (iconId), - IMAGE_ICON, - ScreenDPI >= 120 ? 0 : 16, - ScreenDPI >= 120 ? 0 : 16, - (ScreenDPI >= 120 ? LR_DEFAULTSIZE : 0) - | LR_SHARED - | (nCurrentOS != WIN_2000 ? LR_DEFAULTCOLOR : LR_VGACOLOR)); // Windows 2000 cannot display more than 16 fixed colors in notification tray - - return Shell_NotifyIcon (NIM_MODIFY, &tnid); -} - - -void DismountIdleVolumes () -{ - static DWORD lastMinTickCount; - static int InactivityTime[26]; - static unsigned __int64 LastRead[26], LastWritten[26]; - static int LastId[26]; - - VOLUME_PROPERTIES_STRUCT prop; - DWORD dwResult; - BOOL bResult; - int i; - - if (GetTickCount() > lastMinTickCount && GetTickCount() - lastMinTickCount < 60 * 1000) - return; - - lastMinTickCount = GetTickCount(); - - for (i = 0; i < 26; i++) - { - if (LastKnownMountList.ulMountedDrives & (1 << i)) - { - memset (&prop, 0, sizeof(prop)); - prop.driveNo = i; - - bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, - sizeof (prop), &prop, sizeof (prop), &dwResult, NULL); - - if ( bResult - && ( (prop.driveNo == i) && prop.uniqueId >= 0 - && prop.ea >= EAGetFirst() && prop.ea <= EAGetCount() - && prop.mode >= FIRST_MODE_OF_OPERATION_ID && prop.mode <= LAST_MODE_OF_OPERATION - && prop.pkcs5 >= FIRST_PRF_ID && prop.pkcs5 <= LAST_PRF_ID - && prop.pkcs5Iterations > 0 - && prop.hiddenVolProtection >= 0 && prop.volFormatVersion >= 0 - && prop.volumePim >= 0 - ) - ) - { - if (LastRead[i] == prop.totalBytesRead - && LastWritten[i] == prop.totalBytesWritten - && LastId[i] == prop.uniqueId) - { - if (++InactivityTime[i] >= MaxVolumeIdleTime) - { - BroadcastDeviceChange (DBT_DEVICEREMOVEPENDING, i, 0); - - if (bCloseDismountedWindows && CloseVolumeExplorerWindows (MainDlg, i)) - Sleep (250); - - if (DriverUnmountVolume (MainDlg, i, bForceAutoDismount) == 0) - { - InactivityTime[i] = 0; - BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, i, 0); - - if (bWipeCacheOnAutoDismount) - { - DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - SecurityToken::CloseAllSessions(); - } - } - } - } - else - { - InactivityTime[i] = 0; - LastRead[i] = prop.totalBytesRead; - LastWritten[i] = prop.totalBytesWritten; - LastId[i] = prop.uniqueId; - } - } - } - } -} - -static BOOL MountFavoriteVolumeBase (HWND hwnd, const FavoriteVolume &favorite, BOOL& lastbExplore, BOOL& userForcedReadOnly, BOOL systemFavorites, BOOL logOnMount, BOOL hotKeyMount, const FavoriteVolume &favoriteVolumeToMount) -{ - BOOL status = TRUE; - int drive; - std::wstring effectiveVolumePath; - drive = towupper (favorite.MountPoint[0]) - L'A'; - - if ((drive < MIN_MOUNTED_VOLUME_DRIVE_NUMBER) || (drive > MAX_MOUNTED_VOLUME_DRIVE_NUMBER)) - { - if (!systemFavorites) - Error ("DRIVE_LETTER_UNAVAILABLE", MainDlg); - else if (ServiceMode && systemFavorites) - { - SystemFavoritesServiceLogError (wstring (L"The drive letter ") + (wchar_t) (drive + L'A') + wstring (L" used by favorite \"") + favorite.Path + L"\" is invalid.\nThis system favorite will not be mounted"); - } - return FALSE; - } - - mountOptions.ReadOnly = favorite.ReadOnly || userForcedReadOnly; - mountOptions.Removable = favorite.Removable; - if (favorite.UseLabelInExplorer && !favorite.Label.empty()) - StringCbCopyW (mountOptions.Label, sizeof (mountOptions.Label), favorite.Label.c_str()); - else - ZeroMemory (mountOptions.Label, sizeof (mountOptions.Label)); - - if (favorite.UseVolumeID && !IsRepeatedByteArray (0, favorite.VolumeID, sizeof (favorite.VolumeID))) - { - effectiveVolumePath = FindDeviceByVolumeID (favorite.VolumeID); - } - else - effectiveVolumePath = favorite.Path; - - if (favorite.SystemEncryption) - { - mountOptions.PartitionInInactiveSysEncScope = TRUE; - bPrebootPasswordDlgMode = TRUE; - } - else - { - mountOptions.PartitionInInactiveSysEncScope = FALSE; - bPrebootPasswordDlgMode = FALSE; - } - - if ((LastKnownMountList.ulMountedDrives & (1 << drive)) == 0) - { - MountVolumesAsSystemFavorite = systemFavorites; - - wstring mountPoint = (wchar_t) (drive + L'A') + wstring (L":\\"); - wchar_t prevVolumeAtMountPoint[MAX_PATH] = { 0 }; - - if (systemFavorites) - { - // Partitions of new drives are assigned free drive letters by Windows on boot. Make sure this does not prevent system favorite volumes - // from being mounted. Each partition (using the same drive letter as a system favorite volume) is assigned another free drive letter. - - if (GetVolumeNameForVolumeMountPoint (mountPoint.c_str(), prevVolumeAtMountPoint, ARRAYSIZE (prevVolumeAtMountPoint))) - DeleteVolumeMountPoint (mountPoint.c_str()); - else - prevVolumeAtMountPoint[0] = 0; - } - - lastbExplore = bExplore; - - bExplore = (BOOL) favorite.OpenExplorerWindow; - - if (!systemFavorites - && !logOnMount - && !hotKeyMount - && !favoriteVolumeToMount.Path.empty() - && GetAsyncKeyState (VK_CONTROL) < 0) - { - /* Priority is given to command line parameters - * Default values used only when nothing specified in command line - */ - if (CmdVolumePkcs5 == 0) - mountOptions.ProtectedHidVolPkcs5Prf = DefaultVolumePkcs5; - else - mountOptions.ProtectedHidVolPkcs5Prf = CmdVolumePkcs5; - mountOptions.ProtectedHidVolPim = CmdVolumePim; - if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwnd, (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions) == IDCANCEL) - { - status = FALSE; - goto skipMount; - } - } - - BOOL prevReadOnly = mountOptions.ReadOnly; - - if (ServiceMode) - SystemFavoritesServiceLogInfo (wstring (L"Mounting system favorite \"") + effectiveVolumePath + L"\""); - - status = Mount (hwnd, drive, (wchar_t *) effectiveVolumePath.c_str(), favorite.Pim); - - if (ServiceMode) - { - // Update the service status to avoid being killed - SystemFavoritesServiceStatus.dwCheckPoint++; - SystemFavoritesServiceSetStatus (SERVICE_START_PENDING, 120000); - - if (status) - { - SystemFavoritesServiceLogInfo (wstring (L"Favorite \"") + effectiveVolumePath + wstring (L"\" mounted successfully as ") + (wchar_t) (drive + L'A') + L":"); - } - else - { - SystemFavoritesServiceLogError (wstring (L"Favorite \"") + effectiveVolumePath + L"\" failed to mount"); - } - } - - if (status && mountOptions.ReadOnly != prevReadOnly) - userForcedReadOnly = mountOptions.ReadOnly; - -skipMount: - bExplore = lastbExplore; - - if (systemFavorites && prevVolumeAtMountPoint[0]) - { - if (status) - { - int freeDrive = GetFirstAvailableDrive(); - if (freeDrive != -1) - { - mountPoint[0] = (wchar_t) (freeDrive + L'A'); - SetVolumeMountPoint (mountPoint.c_str(), prevVolumeAtMountPoint); - } - } - else - SetVolumeMountPoint (mountPoint.c_str(), prevVolumeAtMountPoint); - } - - LoadDriveLetters (MainDlg, GetDlgItem (MainDlg, IDC_DRIVELIST), 0); - - MountVolumesAsSystemFavorite = FALSE; - - if (ServiceMode && LastMountedVolumeDirty) - { - DWORD bytesOut; - DeviceIoControl (hDriver, TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY, NULL, 0, NULL, 0, &bytesOut, NULL); - - SystemFavoritesServiceLogError (wstring (L"The filesystem of the volume mounted as ") + (wchar_t) (drive + L'A') + L": was not cleanly dismounted and needs to be checked for errors."); - } - } - else if (!systemFavorites && !favoriteVolumeToMount.Path.empty()) - Error ("DRIVE_LETTER_UNAVAILABLE", MainDlg); - else if (ServiceMode && systemFavorites) - { - SystemFavoritesServiceLogError (wstring (L"The drive letter ") + (wchar_t) (drive + L'A') + wstring (L" used by favorite \"") + effectiveVolumePath + L"\" is already taken.\nThis system favorite will not be mounted"); - } - - return status; -} - - -BOOL MountFavoriteVolumes (HWND hwnd, BOOL systemFavorites, BOOL logOnMount, BOOL hotKeyMount, const FavoriteVolume &favoriteVolumeToMount) -{ - BOOL bRet = TRUE, status = TRUE; - BOOL lastbExplore; - BOOL userForcedReadOnly = FALSE; - - if (ServiceMode) - { - // in service case, intialize some global variable here. - LastKnownMountList.ulMountedDrives = 0; - LoadDriveLetters (MainDlg, GetDlgItem (MainDlg, IDC_DRIVELIST), 0); - } - - mountOptions = defaultMountOptions; - - VolumePassword.Length = 0; - MultipleMountOperationInProgress = (favoriteVolumeToMount.Path.empty() || FavoriteMountOnArrivalInProgress); - - vector favorites, skippedSystemFavorites; - - if (systemFavorites) - { - try - { - if (ServiceMode) - SystemFavoritesServiceLogInfo (wstring (L"Reading System Favorites XML file")); - LoadFavoriteVolumes (favorites, true); - - if (ServiceMode) - { - wchar_t szTmp[32]; - StringCbPrintf (szTmp, sizeof(szTmp), L"%d", (int) favorites.size()); - SystemFavoritesServiceLogInfo (wstring (L"Loaded ") + szTmp + wstring (L" favorites from the file")); - - /* correct set the connected state of the system favorites */ - for (vector ::iterator favorite = favorites.begin(); - favorite != favorites.end(); favorite++) - { - if (favorite->UseVolumeID) - { - std::wstring path = FindDeviceByVolumeID (favorite->VolumeID); - if (path.empty ()) - { - favorite->DisconnectedDevice = true; - } - else - { - favorite->DisconnectedDevice = false; - favorite->Path = path; - favorite->UseVolumeID = false; /* force the use of real path to avoid calling FindDeviceByVolumeID again */ - } - } - } - } - } - catch (...) - { - if (ServiceMode) - SystemFavoritesServiceLogError (wstring (L"An error occured while reading System Favorites XML file")); - return false; - } - } - else if (!favoriteVolumeToMount.Path.empty()) - favorites.push_back (favoriteVolumeToMount); - else - favorites = FavoriteVolumes; - - foreach (const FavoriteVolume &favorite, favorites) - { - if (ServiceMode && systemFavorites && favorite.DisconnectedDevice) - { - skippedSystemFavorites.push_back (favorite); - if (favorite.UseVolumeID) - SystemFavoritesServiceLogWarning (wstring (L"Favorite \"ID:") + ArrayToHexWideString (favorite.VolumeID, sizeof (favorite.VolumeID)) + L"\" is disconnected. It will be ignored."); - else - SystemFavoritesServiceLogWarning (wstring (L"Favorite \"") + favorite.Path + L"\" is disconnected. It will be ignored."); - } - - if (favorite.DisconnectedDevice - || (logOnMount && !favorite.MountOnLogOn) - || (hotKeyMount && favorite.DisableHotkeyMount)) - { - continue; - } - - status = MountFavoriteVolumeBase (hwnd, favorite, lastbExplore, userForcedReadOnly, systemFavorites, logOnMount, hotKeyMount, favoriteVolumeToMount); - if (!status) - bRet = FALSE; - } - - if (systemFavorites && ServiceMode && !skippedSystemFavorites.empty()) - { - // Some drives need more time to initialize correctly. - // We retry 4 times after sleeping 5 seconds - int retryCounter = 0; - size_t remainingFavorites = skippedSystemFavorites.size(); - while ((remainingFavorites > 0) && (retryCounter++ < 4)) - { - Sleep (5000); - - SystemFavoritesServiceLogInfo (wstring (L"Trying to mount skipped system favorites")); - - // Update the service status to avoid being killed - SystemFavoritesServiceStatus.dwCheckPoint++; - SystemFavoritesServiceSetStatus (SERVICE_START_PENDING, 120000); - - for (vector ::iterator favorite = skippedSystemFavorites.begin(); - favorite != skippedSystemFavorites.end(); favorite++) - { - if (favorite->DisconnectedDevice) - { - // check if the favorite is here and get its path - wstring resolvedPath; - if (favorite->UseVolumeID) - { - resolvedPath = FindDeviceByVolumeID (favorite->VolumeID); - } - else - resolvedPath = VolumeGuidPathToDevicePath (favorite->Path); - if (!resolvedPath.empty()) - { - favorite->DisconnectedDevice = false; - favorite->VolumePathId = favorite->Path; - favorite->Path = resolvedPath; - - remainingFavorites--; - - // favorite OK. - if (favorite->UseVolumeID) - SystemFavoritesServiceLogInfo (wstring (L"Favorite \"ID:") + ArrayToHexWideString (favorite->VolumeID, sizeof (favorite->VolumeID)) + L"\" is connected. Performing mount."); - else - SystemFavoritesServiceLogInfo (wstring (L"Favorite \"") + favorite->VolumePathId + L"\" is connected. Performing mount."); - - status = MountFavoriteVolumeBase (hwnd, *favorite, lastbExplore, userForcedReadOnly, systemFavorites, logOnMount, hotKeyMount, favoriteVolumeToMount); - if (!status) - bRet = FALSE; - } - } - } - - if (remainingFavorites == 0) - SystemFavoritesServiceLogInfo (wstring (L"All skipped system favorites have been processed")); - else - { - wchar_t szTmp[32]; - StringCbPrintfW (szTmp, sizeof(szTmp), L"%d", (int) remainingFavorites); - SystemFavoritesServiceLogWarning (wstring (L"Number of unprocessed system favorites is ") + szTmp); - } - } - } - - MultipleMountOperationInProgress = FALSE; - burn (&VolumePassword, sizeof (VolumePassword)); - burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&VolumePim, sizeof (VolumePim)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); - - if (bRet && CloseSecurityTokenSessionsAfterMount) - SecurityToken::CloseAllSessions(); - - return bRet; -} - -void CALLBACK mountFavoriteVolumeCallbackFunction (void *pArg, HWND hwnd) -{ - mountFavoriteVolumeThreadParam* pParam = (mountFavoriteVolumeThreadParam*) pArg; - - if (pParam) - { - if (pParam->favoriteVolumeToMount) - MountFavoriteVolumes (hwnd, pParam->systemFavorites, pParam->logOnMount, pParam->hotKeyMount, *(pParam->favoriteVolumeToMount)); - else - MountFavoriteVolumes (hwnd, pParam->systemFavorites, pParam->logOnMount, pParam->hotKeyMount); - - free (pParam); - } - else - MountFavoriteVolumes (hwnd); -} - -void __cdecl mountFavoriteVolumeThreadFunction (void *pArg) -{ - ShowWaitDialog (MainDlg, FALSE, mountFavoriteVolumeCallbackFunction, pArg); -} - -static void SaveDefaultKeyFilesParam (HWND hwnd) -{ - if (defaultKeyFilesParam.FirstKeyFile == NULL) - { - /* No keyfiles selected */ - _wremove (GetConfigPath (TC_APPD_FILENAME_DEFAULT_KEYFILES)); - } - else - { - FILE *f; - KeyFile *kf = FirstKeyFile; - - f = _wfopen (GetConfigPath (TC_APPD_FILENAME_DEFAULT_KEYFILES), L"w,ccs=UTF-8"); - if (f == NULL) - { - handleWin32Error (MainDlg, SRC_POS); - return; - } - - XmlWriteHeader (f); - - fputws (L"\n\t", f); - - while (kf != NULL) - { - wchar_t q[TC_MAX_PATH * 2]; - - XmlQuoteTextW (kf->FileName, q, ARRAYSIZE (q)); - fwprintf (f, L"\n\t\t%s", q); - - kf = kf->Next; - } - - fputws (L"\n\t", f); - - XmlWriteFooter (f); - - CheckFileStreamWriteErrors (hwnd, f, TC_APPD_FILENAME_DEFAULT_KEYFILES); - fclose (f); - return; - } -} - - -static void KeyfileDefaultsDlg (HWND hwndDlg) -{ - KeyFilesDlgParam param; - - param.EnableKeyFiles = defaultKeyFilesParam.EnableKeyFiles; - param.FirstKeyFile = defaultKeyFilesParam.FirstKeyFile; - - if (DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, - (DLGPROC) KeyFilesDlgProc, (LPARAM) ¶m) == IDOK) - { - if (!param.EnableKeyFiles || AskWarnYesNo ("CONFIRM_SAVE_DEFAULT_KEYFILES", hwndDlg) == IDYES) - { - KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile); - defaultKeyFilesParam.EnableKeyFiles = param.EnableKeyFiles; - defaultKeyFilesParam.FirstKeyFile = param.FirstKeyFile; - - RestoreDefaultKeyFilesParam (); - SaveDefaultKeyFilesParam (hwndDlg); - } - } -} - - -static void HandleHotKey (HWND hwndDlg, WPARAM wParam) -{ - DWORD dwResult; - BOOL success = TRUE; - - switch (wParam) - { - case HK_AUTOMOUNT_DEVICES: - MountAllDevices (hwndDlg, TRUE); - break; - - case HK_DISMOUNT_ALL: - case HK_DISMOUNT_ALL_AND_WIPE: - - if (wParam == HK_DISMOUNT_ALL_AND_WIPE) - WipeCache (hwndDlg, TRUE); - - if (DismountAll (hwndDlg, FALSE, TRUE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY)) - { - if (bDisplayBalloonOnSuccessfulHkDismount) - InfoBalloon ("SUCCESSFULLY_DISMOUNTED", (wParam == HK_DISMOUNT_ALL_AND_WIPE ? "VOLUMES_DISMOUNTED_CACHE_WIPED" : "MOUNTED_VOLUMES_DISMOUNTED"), hwndDlg); - - if (bPlaySoundOnSuccessfulHkDismount) - MessageBeep (0xFFFFFFFF); - } - - break; - - case HK_WIPE_CACHE: - WipeCache (hwndDlg, FALSE); - - break; - - case HK_FORCE_DISMOUNT_ALL_AND_WIPE: - success = DismountAll (hwndDlg, TRUE, FALSE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); - success &= DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - if (success) - { - if (bDisplayBalloonOnSuccessfulHkDismount) - InfoBalloon ("SUCCESSFULLY_DISMOUNTED", "VOLUMES_DISMOUNTED_CACHE_WIPED", hwndDlg); - - if (bPlaySoundOnSuccessfulHkDismount) - MessageBeep (0xFFFFFFFF); - } - break; - - case HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT: - success = DismountAll (hwndDlg, TRUE, FALSE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); - success &= DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - if (success) - { - if (bDisplayBalloonOnSuccessfulHkDismount) - InfoBalloon ("SUCCESSFULLY_DISMOUNTED", "VOLUMES_DISMOUNTED_CACHE_WIPED", hwndDlg); - - if (bPlaySoundOnSuccessfulHkDismount) - MessageBeep (0xFFFFFFFF); - } - TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); - EndMainDlg (hwndDlg); - break; - - case HK_MOUNT_FAVORITE_VOLUMES: - { - mountFavoriteVolumeThreadParam* pParam = (mountFavoriteVolumeThreadParam*) calloc(1, sizeof(mountFavoriteVolumeThreadParam)); - pParam->systemFavorites = FALSE; - pParam->logOnMount = FALSE; - pParam->hotKeyMount = TRUE; - pParam->favoriteVolumeToMount = NULL; - - _beginthread(mountFavoriteVolumeThreadFunction, 0, pParam); - } - break; - - case HK_SHOW_HIDE_MAIN_WINDOW: - ChangeMainWindowVisibility (); - break; - - case HK_CLOSE_SECURITY_TOKEN_SESSIONS: - SecurityToken::CloseAllSessions(); - - InfoBalloon (NULL, "ALL_TOKEN_SESSIONS_CLOSED", hwndDlg); - - break; - } -} - - -void ChangeMainWindowVisibility () -{ - MainWindowHidden = !MainWindowHidden; - - if (!MainWindowHidden) - SetForegroundWindow (MainDlg); - - ShowWindow (MainDlg, !MainWindowHidden ? SW_SHOW : SW_HIDE); - - if (!MainWindowHidden) - ShowWindow (MainDlg, SW_RESTORE); -} - - -int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, const wchar_t *lpszVolume) -{ - int nStatus = ERR_OS_ERROR; - wchar_t szTmp[4096]; - int fBackup = -1; - OpenVolumeContext volume; - OpenVolumeContext hiddenVolume; - Password hiddenVolPassword; - int hiddenVolPkcs5 = 0, hiddenVolPim = 0; - byte temporaryKey[MASTER_KEYDATA_SIZE]; - byte originalK2[MASTER_KEYDATA_SIZE]; - int EffectiveVolumePkcs5 = CmdVolumePkcs5; - int EffectiveVolumePim = CmdVolumePim; - - /* Priority is given to command line parameters - * Default values used only when nothing specified in command line - */ - if (EffectiveVolumePkcs5 == 0) - EffectiveVolumePkcs5 = DefaultVolumePkcs5; - - if (!lpszVolume) - { - nStatus = ERR_OUTOFMEMORY; - handleError (hwndDlg, nStatus, SRC_POS); - return nStatus; - } - - volume.VolumeIsOpen = FALSE; - hiddenVolume.VolumeIsOpen = FALSE; - - switch (IsSystemDevicePath (lpszVolume, hwndDlg, TRUE)) - { - case 1: - case 2: - if (AskErrNoYes ("BACKUP_HEADER_NOT_FOR_SYS_DEVICE", hwndDlg) == IDYES) - CreateRescueDisk (hwndDlg); - - return 0; - } - - if (IsMountedVolume (lpszVolume)) - { - Warning ("DISMOUNT_FIRST", hwndDlg); - goto ret; - } - - if (!VolumePathExists (lpszVolume)) - { - handleWin32Error (hwndDlg, SRC_POS); - goto ret; - } - - Info ("EXTERNAL_VOL_HEADER_BAK_FIRST_INFO", hwndDlg); - - - WaitCursor(); - - // Open both types of volumes - for (int type = TC_VOLUME_TYPE_NORMAL; type <= TC_VOLUME_TYPE_HIDDEN; ++type) - { - OpenVolumeContext *askVol = (type == TC_VOLUME_TYPE_HIDDEN ? &hiddenVolume : &volume); - Password *askPassword = (type == TC_VOLUME_TYPE_HIDDEN ? &hiddenVolPassword : &VolumePassword); - int* askPkcs5 = (type == TC_VOLUME_TYPE_HIDDEN ? &hiddenVolPkcs5 : &VolumePkcs5); - int* askPim = (type == TC_VOLUME_TYPE_HIDDEN ? &hiddenVolPim : &VolumePim); - - while (TRUE) - { - int GuiPkcs5 = ((EffectiveVolumePkcs5 > 0) && (*askPkcs5 == 0))? EffectiveVolumePkcs5 : *askPkcs5; - int GuiPim = ((EffectiveVolumePim > 0) && (*askPim <= 0))? EffectiveVolumePim : *askPim; - if (!AskVolumePassword (hwndDlg, askPassword, &GuiPkcs5, &GuiPim, &VolumeTrueCryptMode, type == TC_VOLUME_TYPE_HIDDEN ? "ENTER_HIDDEN_VOL_PASSWORD" : "ENTER_NORMAL_VOL_PASSWORD", FALSE)) - { - nStatus = ERR_SUCCESS; - goto ret; - } - else - { - *askPkcs5 = GuiPkcs5; - *askPim = GuiPim; - burn (&GuiPkcs5, sizeof (GuiPkcs5)); - burn (&GuiPim, sizeof (GuiPim)); - } - - WaitCursor(); - - if (KeyFilesEnable && FirstKeyFile) - KeyFilesApply (hwndDlg, askPassword, FirstKeyFile, lpszVolume); - - nStatus = OpenVolume (askVol, lpszVolume, askPassword, *askPkcs5, *askPim, VolumeTrueCryptMode, FALSE, bPreserveTimestamp, FALSE); - - NormalCursor(); - - if (nStatus == ERR_SUCCESS) - { - if ((type == TC_VOLUME_TYPE_NORMAL && askVol->CryptoInfo->hiddenVolume) - || (type == TC_VOLUME_TYPE_HIDDEN && !askVol->CryptoInfo->hiddenVolume)) - { - CloseVolume (askVol); - handleError (hwndDlg, ERR_PASSWORD_WRONG, SRC_POS); - continue; - } - - RandSetHashFunction (askVol->CryptoInfo->pkcs5); - - if (type == TC_VOLUME_TYPE_NORMAL) - { - // Ask the user if there is a hidden volume - char *volTypeChoices[] = {0, "DOES_VOLUME_CONTAIN_HIDDEN", "VOLUME_CONTAINS_HIDDEN", "VOLUME_DOES_NOT_CONTAIN_HIDDEN", "IDCANCEL", 0}; - switch (AskMultiChoice ((void **) volTypeChoices, FALSE, hwndDlg)) - { - case 1: - break; - case 2: - goto noHidden; - - default: - nStatus = ERR_SUCCESS; - goto ret; - } - } - - break; - } - - if (nStatus != ERR_PASSWORD_WRONG) - goto error; - - handleError (hwndDlg, nStatus, SRC_POS); - } - } -noHidden: - - if (hiddenVolume.VolumeIsOpen && volume.CryptoInfo->LegacyVolume != hiddenVolume.CryptoInfo->LegacyVolume) - { - nStatus = ERR_PARAMETER_INCORRECT; - goto error; - } - - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CONFIRM_VOL_HEADER_BAK"), lpszVolume); - - if (bRequireConfirmation - && (MessageBoxW (hwndDlg, szTmp, lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON1) == IDNO)) - goto ret; - - /* Select backup file */ - if (!BrowseFiles (hwndDlg, "OPEN_TITLE", szFileName, bHistory, TRUE, NULL)) - goto ret; - - /* Conceive the backup file */ - if ((fBackup = _wopen(szFileName, _O_CREAT|_O_TRUNC|_O_WRONLY|_O_BINARY, _S_IREAD|_S_IWRITE)) == -1) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - // Backup headers - - byte backup[TC_VOLUME_HEADER_GROUP_SIZE]; - - bool legacyVolume = volume.CryptoInfo->LegacyVolume ? true : false; - int backupFileSize = legacyVolume ? TC_VOLUME_HEADER_SIZE_LEGACY * 2 : TC_VOLUME_HEADER_GROUP_SIZE; - - // Fill backup buffer with random data - memcpy (originalK2, volume.CryptoInfo->k2, sizeof (volume.CryptoInfo->k2)); - - if (Randinit() != ERR_SUCCESS) - { - if (CryptoAPILastError == ERROR_SUCCESS) - nStatus = ERR_RAND_INIT_FAILED; - else - nStatus = ERR_CAPI_INIT_FAILED; - goto error; - } - - /* force the display of the random enriching dialog */ - SetRandomPoolEnrichedByUserStatus (FALSE); - - NormalCursor(); - UserEnrichRandomPool (hwndDlg); - WaitCursor(); - - // Temporary keys - if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (volume.CryptoInfo->ea), TRUE) - || !RandgetBytes (hwndDlg, volume.CryptoInfo->k2, sizeof (volume.CryptoInfo->k2), FALSE)) - { - nStatus = ERR_PARAMETER_INCORRECT; - goto error; - } - - if (EAInit (volume.CryptoInfo->ea, temporaryKey, volume.CryptoInfo->ks) != ERR_SUCCESS || !EAInitMode (volume.CryptoInfo)) - { - nStatus = ERR_PARAMETER_INCORRECT; - goto error; - } - - EncryptBuffer (backup, backupFileSize, volume.CryptoInfo); - - memcpy (volume.CryptoInfo->k2, originalK2, sizeof (volume.CryptoInfo->k2)); - if (EAInit (volume.CryptoInfo->ea, volume.CryptoInfo->master_keydata, volume.CryptoInfo->ks) != ERR_SUCCESS || !EAInitMode (volume.CryptoInfo)) - { - nStatus = ERR_PARAMETER_INCORRECT; - goto error; - } - - // Store header encrypted with a new key - nStatus = ReEncryptVolumeHeader (hwndDlg, (char *) backup, FALSE, volume.CryptoInfo, &VolumePassword, VolumePim, FALSE); - if (nStatus != ERR_SUCCESS) - goto error; - - if (hiddenVolume.VolumeIsOpen) - { - nStatus = ReEncryptVolumeHeader (hwndDlg, (char *) backup + (legacyVolume ? TC_VOLUME_HEADER_SIZE_LEGACY : TC_VOLUME_HEADER_SIZE), - FALSE, hiddenVolume.CryptoInfo, &hiddenVolPassword, hiddenVolPim, FALSE); - - if (nStatus != ERR_SUCCESS) - goto error; - } - - if (_write (fBackup, backup, backupFileSize) == -1) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - /* Backup has been successfully created */ - Warning("VOL_HEADER_BACKED_UP", hwndDlg); - -ret: - nStatus = ERR_SUCCESS; - -error: - DWORD dwError = GetLastError (); - - CloseVolume (&volume); - CloseVolume (&hiddenVolume); - - if (fBackup != -1) - _close (fBackup); - - SetLastError (dwError); - if (nStatus != 0) - handleError (hwndDlg, nStatus, SRC_POS); - - burn (&VolumePassword, sizeof (VolumePassword)); - burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&VolumePim, sizeof (VolumePim)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); - burn (&hiddenVolPassword, sizeof (hiddenVolPassword)); - burn (temporaryKey, sizeof (temporaryKey)); - burn (originalK2, sizeof (originalK2)); - - RestoreDefaultKeyFilesParam(); - RandStop (FALSE); - NormalCursor(); - - return nStatus; -} - - -int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume) -{ - int nDosLinkCreated = -1, nStatus = ERR_OS_ERROR; - wchar_t szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH]; - wchar_t szFileName[TC_MAX_PATH]; - wchar_t szDosDevice[TC_MAX_PATH]; - void *dev = INVALID_HANDLE_VALUE; - DWORD dwError; - BOOL bDevice; - unsigned __int64 hostSize = 0; - FILETIME ftCreationTime; - FILETIME ftLastWriteTime; - FILETIME ftLastAccessTime; - wchar_t szTmp[4096]; - BOOL bTimeStampValid = FALSE; - HANDLE fBackup = INVALID_HANDLE_VALUE; - LARGE_INTEGER headerOffset; - CRYPTO_INFO *restoredCryptoInfo = NULL; - int EffectiveVolumePkcs5 = CmdVolumePkcs5; - int EffectiveVolumePim = CmdVolumePim; - - /* Priority is given to command line parameters - * Default values used only when nothing specified in command line - */ - if (EffectiveVolumePkcs5 == 0) - EffectiveVolumePkcs5 = DefaultVolumePkcs5; - - if (!lpszVolume) - { - nStatus = ERR_OUTOFMEMORY; - handleError (hwndDlg, nStatus, SRC_POS); - return nStatus; - } - - switch (IsSystemDevicePath (lpszVolume, hwndDlg, TRUE)) - { - case 1: - case 2: - if (AskErrNoYes ("RESTORE_HEADER_NOT_FOR_SYS_DEVICE", hwndDlg) == IDYES) - CreateRescueDisk (hwndDlg); - - return 0; - - case -1: - // In some environments (such as PE), the system volume is not located on a hard drive. - // Therefore, we must interpret this return code as "Not a system device path" (otherwise, - // it would not be possible to restore headers on non-system devices in such environments). - // Note that this is rather safe, because bReliableRequired is set to TRUE. - - // NOP - break; - } - - if (IsMountedVolume (lpszVolume)) - { - Warning ("DISMOUNT_FIRST", hwndDlg); - return 0; - } - - if (!VolumePathExists (lpszVolume)) - { - handleWin32Error (hwndDlg, SRC_POS); - return 0; - } - - BOOL restoreInternalBackup; - - // Ask the user to select the type of backup (internal/external) - char *volTypeChoices[] = {0, "HEADER_RESTORE_EXTERNAL_INTERNAL", "HEADER_RESTORE_INTERNAL", "HEADER_RESTORE_EXTERNAL", "IDCANCEL", 0}; - switch (AskMultiChoice ((void **) volTypeChoices, FALSE, hwndDlg)) - { - case 1: - restoreInternalBackup = TRUE; - break; - case 2: - restoreInternalBackup = FALSE; - break; - default: - return 0; - } - - OpenVolumeContext volume; - volume.VolumeIsOpen = FALSE; - - /* force the display of the random enriching dialog */ - SetRandomPoolEnrichedByUserStatus (FALSE); - - WaitCursor(); - - if (restoreInternalBackup) - { - // Restore header from the internal backup - - // Open the volume using backup header - while (TRUE) - { - int GuiPkcs5 = ((EffectiveVolumePkcs5 > 0) && (VolumePkcs5 == 0))? EffectiveVolumePkcs5 : VolumePkcs5; - int GuiPim = ((EffectiveVolumePim > 0) && (VolumePim <= 0))? EffectiveVolumePim : VolumePim; - StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume), lpszVolume); - if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &VolumeTrueCryptMode, NULL, FALSE)) - { - nStatus = ERR_SUCCESS; - goto ret; - } - else - { - VolumePkcs5 = GuiPkcs5; - VolumePim = GuiPim; - burn (&GuiPkcs5, sizeof (GuiPkcs5)); - burn (&GuiPim, sizeof (GuiPim)); - } - - WaitCursor(); - - if (KeyFilesEnable && FirstKeyFile) - KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, lpszVolume); - - nStatus = OpenVolume (&volume, lpszVolume, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode,TRUE, bPreserveTimestamp, TRUE); - - NormalCursor(); - - if (nStatus == ERR_SUCCESS) - break; - - if (nStatus != ERR_PASSWORD_WRONG) - goto error; - - handleError (hwndDlg, nStatus, SRC_POS); - } - - if (volume.CryptoInfo->LegacyVolume) - { - Error ("VOLUME_HAS_NO_BACKUP_HEADER", hwndDlg); - nStatus = ERROR_SUCCESS; - goto error; - } - - // Create a new header with a new salt - char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; - - nStatus = ReEncryptVolumeHeader (hwndDlg, buffer, FALSE, volume.CryptoInfo, &VolumePassword, VolumePim, FALSE); - if (nStatus != 0) - goto error; - - headerOffset.QuadPart = volume.CryptoInfo->hiddenVolume ? TC_HIDDEN_VOLUME_HEADER_OFFSET : TC_VOLUME_HEADER_OFFSET; - if (!SetFilePointerEx (volume.HostFileHandle, headerOffset, NULL, FILE_BEGIN)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - if (!WriteEffectiveVolumeHeader (volume.IsDevice, volume.HostFileHandle, (byte *) buffer)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - } - else - { - // Restore header from an external backup - - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CONFIRM_VOL_HEADER_RESTORE"), lpszVolume); - - if (MessageBoxW (hwndDlg, szTmp, lpszTitle, YES_NO|MB_ICONWARNING|MB_DEFBUTTON2) == IDNO) - { - nStatus = ERR_SUCCESS; - goto ret; - } - - /* Select backup file */ - if (!BrowseFiles (hwndDlg, "OPEN_TITLE", szFileName, bHistory, FALSE, NULL)) - { - nStatus = ERR_SUCCESS; - goto ret; - } - - /* Open the backup file */ - fBackup = CreateFile (szFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); - if (fBackup == INVALID_HANDLE_VALUE) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - // Determine size of the backup file - LARGE_INTEGER backupSize; - if (!GetFileSizeEx (fBackup, &backupSize)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), lpszVolume, &bDevice); - - if (bDevice == FALSE) - StringCbCopyW (szCFDevice, sizeof(szCFDevice), szDiskFile); - else - { - nDosLinkCreated = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice),szCFDevice, sizeof(szCFDevice),FALSE); - if (nDosLinkCreated != 0) - goto error; - } - - // Open the volume - dev = CreateFile (szCFDevice, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); - - if (dev == INVALID_HANDLE_VALUE) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - // Determine volume host size - if (bDevice) - { - PARTITION_INFORMATION diskInfo; - DWORD dwResult; - BOOL bResult; - - bResult = GetPartitionInfo (lpszVolume, &diskInfo); - - if (bResult) - { - hostSize = diskInfo.PartitionLength.QuadPart; - } - else - { - DISK_GEOMETRY driveInfo; - - bResult = DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, - &driveInfo, sizeof (driveInfo), &dwResult, NULL); - - if (!bResult) - goto error; - - hostSize = driveInfo.Cylinders.QuadPart * driveInfo.BytesPerSector * - driveInfo.SectorsPerTrack * driveInfo.TracksPerCylinder; - } - - if (hostSize == 0) - { - nStatus = ERR_VOL_SIZE_WRONG; - goto error; - } - } - else - { - LARGE_INTEGER fileSize; - if (!GetFileSizeEx (dev, &fileSize)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - hostSize = fileSize.QuadPart; - } - - if (!bDevice && bPreserveTimestamp) - { - /* Remember the container modification/creation date and time. */ - - if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0) - bTimeStampValid = FALSE; - else - bTimeStampValid = TRUE; - } - - /* Read the volume header from the backup file */ - char buffer[TC_VOLUME_HEADER_GROUP_SIZE]; - - DWORD bytesRead; - if (!ReadFile (fBackup, buffer, sizeof (buffer), &bytesRead, NULL)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - if (bytesRead != backupSize.QuadPart) - { - nStatus = ERR_VOL_SIZE_WRONG; - goto error; - } - - LARGE_INTEGER headerOffset; - LARGE_INTEGER headerBackupOffset; - bool legacyBackup; - int headerOffsetBackupFile; - - // Determine the format of the backup file - switch (backupSize.QuadPart) - { - case TC_VOLUME_HEADER_GROUP_SIZE: - legacyBackup = false; - break; - - case TC_VOLUME_HEADER_SIZE_LEGACY * 2: - legacyBackup = true; - break; - - default: - Error ("HEADER_BACKUP_SIZE_INCORRECT", hwndDlg); - nStatus = ERR_SUCCESS; - goto error; - } - - // Open the header - while (TRUE) - { - int GuiPkcs5 = ((EffectiveVolumePkcs5 > 0) && (VolumePkcs5 == 0))? EffectiveVolumePkcs5 : VolumePkcs5; - int GuiPim = ((EffectiveVolumePim > 0) && (VolumePim <= 0))? EffectiveVolumePim : VolumePim; - if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &VolumeTrueCryptMode, "ENTER_HEADER_BACKUP_PASSWORD", FALSE)) - { - nStatus = ERR_SUCCESS; - goto ret; - } - else - { - VolumePkcs5 = GuiPkcs5; - VolumePim = GuiPim; - burn (&GuiPkcs5, sizeof (GuiPkcs5)); - burn (&GuiPim, sizeof (GuiPim)); - } - - if (KeyFilesEnable && FirstKeyFile) - KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, bDevice? NULL : lpszVolume); - - // Decrypt volume header - headerOffsetBackupFile = 0; - for (int type = TC_VOLUME_TYPE_NORMAL; type <= TC_VOLUME_TYPE_HIDDEN; ++type) - { - if (type == TC_VOLUME_TYPE_HIDDEN) - headerOffsetBackupFile += (legacyBackup ? TC_VOLUME_HEADER_SIZE_LEGACY : TC_VOLUME_HEADER_SIZE); - - nStatus = ReadVolumeHeader (FALSE, buffer + headerOffsetBackupFile, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode, &restoredCryptoInfo, NULL); - if (nStatus == ERR_SUCCESS) - break; - } - - if (nStatus == ERR_SUCCESS) - break; - - if (nStatus != ERR_PASSWORD_WRONG) - goto error; - - handleError (hwndDlg, nStatus, SRC_POS); - } - - BOOL hiddenVol = restoredCryptoInfo->hiddenVolume; - - if (legacyBackup) - { - headerOffset.QuadPart = hiddenVol ? hostSize - TC_HIDDEN_VOLUME_HEADER_OFFSET_LEGACY : TC_VOLUME_HEADER_OFFSET; - } - else - { - headerOffset.QuadPart = hiddenVol ? TC_HIDDEN_VOLUME_HEADER_OFFSET : TC_VOLUME_HEADER_OFFSET; - headerBackupOffset.QuadPart = hiddenVol ? hostSize - TC_VOLUME_HEADER_SIZE : hostSize - TC_VOLUME_HEADER_GROUP_SIZE; - } - - WaitCursor(); - - // Restore header encrypted with a new key - nStatus = ReEncryptVolumeHeader (hwndDlg, buffer, FALSE, restoredCryptoInfo, &VolumePassword, VolumePim, FALSE); - if (nStatus != ERR_SUCCESS) - goto error; - - if (!SetFilePointerEx (dev, headerOffset, NULL, FILE_BEGIN)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - if (!WriteEffectiveVolumeHeader (bDevice, dev, (byte *) buffer)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - if (!restoredCryptoInfo->LegacyVolume) - { - // Restore backup header encrypted with a new key - nStatus = ReEncryptVolumeHeader (hwndDlg, buffer, FALSE, restoredCryptoInfo, &VolumePassword, VolumePim, FALSE); - if (nStatus != ERR_SUCCESS) - goto error; - - if (!SetFilePointerEx (dev, headerBackupOffset, NULL, FILE_BEGIN)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - - if (!WriteEffectiveVolumeHeader (bDevice, dev, (byte *) buffer)) - { - nStatus = ERR_OS_ERROR; - goto error; - } - } - } - - - /* Volume header has been successfully restored */ - - Info("VOL_HEADER_RESTORED", hwndDlg); -ret: - nStatus = ERR_SUCCESS; - -error: - dwError = GetLastError (); - NormalCursor(); - - if (restoreInternalBackup) - { - CloseVolume (&volume); - } - else - { - if (restoredCryptoInfo) - crypto_close (restoredCryptoInfo); - - if (bTimeStampValid) - SetFileTime (dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime); - - if (dev != INVALID_HANDLE_VALUE) - CloseHandle (dev); - - if (fBackup != INVALID_HANDLE_VALUE) - CloseHandle (fBackup); - - if (nDosLinkCreated == 0) - RemoveFakeDosName (szDiskFile, szDosDevice); - } - - SetLastError (dwError); - if (nStatus != 0) - handleError (hwndDlg, nStatus, SRC_POS); - - burn (&VolumePassword, sizeof (VolumePassword)); - burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&VolumePim, sizeof (VolumePim)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); - RestoreDefaultKeyFilesParam(); - RandStop (FALSE); - NormalCursor(); - - return nStatus; -} - - -void SetDriverConfigurationFlag (uint32 flag, BOOL state) -{ - BootEncObj->SetDriverConfigurationFlag (flag, state ? true : false); -} - - -static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - LocalizeDialog (hwndDlg, "IDD_PERFORMANCE_SETTINGS"); - - uint32 driverConfig = ReadDriverConfigurationFlags(); - CheckDlgButton (hwndDlg, IDC_ENABLE_HARDWARE_ENCRYPTION, (driverConfig & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? BST_UNCHECKED : BST_CHECKED); - CheckDlgButton (hwndDlg, IDC_ENABLE_EXTENDED_IOCTL_SUPPORT, (driverConfig & TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL) ? BST_CHECKED : BST_UNCHECKED); - - SYSTEM_INFO sysInfo; - GetSystemInfo (&sysInfo); - - HWND freeCpuCombo = GetDlgItem (hwndDlg, IDC_ENCRYPTION_FREE_CPU_COUNT); - uint32 encryptionFreeCpuCount = ReadEncryptionThreadPoolFreeCpuCountLimit(); - - if (encryptionFreeCpuCount > sysInfo.dwNumberOfProcessors - 1) - encryptionFreeCpuCount = sysInfo.dwNumberOfProcessors - 1; - - for (uint32 i = 1; i < sysInfo.dwNumberOfProcessors; ++i) - { - wstringstream s; - s << i; - AddComboPair (freeCpuCombo, s.str().c_str(), i); - } - - if (sysInfo.dwNumberOfProcessors < 2 || encryptionFreeCpuCount == 0) - EnableWindow (freeCpuCombo, FALSE); - - if (sysInfo.dwNumberOfProcessors < 2) - EnableWindow (GetDlgItem (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL), FALSE); - - if (encryptionFreeCpuCount != 0) - { - CheckDlgButton (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL, BST_CHECKED); - SendMessage (freeCpuCombo, CB_SETCURSEL, encryptionFreeCpuCount - 1, 0); - } - - SetWindowTextW (GetDlgItem (hwndDlg, IDT_LIMIT_ENC_THREAD_POOL_NOTE), GetString("LIMIT_ENC_THREAD_POOL_NOTE")); - - SetDlgItemTextW (hwndDlg, IDC_HW_AES_SUPPORTED_BY_CPU, (wstring (L" ") + (GetString (is_aes_hw_cpu_supported() ? "UISTR_YES" : "UISTR_NO"))).c_str()); - - ToHyperlink (hwndDlg, IDC_MORE_INFO_ON_HW_ACCELERATION); - ToHyperlink (hwndDlg, IDC_MORE_INFO_ON_THREAD_BASED_PARALLELIZATION); - } - return 0; - - case WM_COMMAND: - - switch (lw) - { - case IDCANCEL: - EndDialog (hwndDlg, lw); - return 1; - - case IDOK: - { - if (IsNonInstallMode()) - { - Error ("FEATURE_REQUIRES_INSTALLATION", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - BOOL disableHW = !IsDlgButtonChecked (hwndDlg, IDC_ENABLE_HARDWARE_ENCRYPTION); - BOOL enableExtendedIOCTL = IsDlgButtonChecked (hwndDlg, IDC_ENABLE_EXTENDED_IOCTL_SUPPORT); - - try - { - VOLUME_PROPERTIES_STRUCT prop; - try - { - BootEncStatus = BootEncObj->GetStatus(); - BootEncObj->GetVolumeProperties (&prop); - } - catch (...) - { - BootEncStatus.DriveMounted = false; - } - - if (BootEncStatus.DriveMounted) - { - byte userConfig; - string customUserMessage; - uint16 bootLoaderVersion; - - BootEncObj->ReadBootSectorConfig (nullptr, 0, &userConfig, &customUserMessage, &bootLoaderVersion); - - if (bootLoaderVersion != VERSION_NUM) - Warning ("BOOT_LOADER_VERSION_INCORRECT_PREFERENCES", hwndDlg); - - if (disableHW) - userConfig |= TC_BOOT_USER_CFG_FLAG_DISABLE_HW_ENCRYPTION; - else - userConfig &= ~TC_BOOT_USER_CFG_FLAG_DISABLE_HW_ENCRYPTION; - - BootEncObj->WriteBootSectorUserConfig (userConfig, customUserMessage, prop.volumePim); - } - - SetDriverConfigurationFlag (TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION, disableHW); - SetDriverConfigurationFlag (TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL, enableExtendedIOCTL); - - DWORD bytesReturned; - if (!DeviceIoControl (hDriver, TC_IOCTL_REREAD_DRIVER_CONFIG, NULL, 0, NULL, 0, &bytesReturned, NULL)) - handleWin32Error (hwndDlg, SRC_POS); - - EnableHwEncryption (!disableHW); - - uint32 cpuFreeCount = 0; - if (IsDlgButtonChecked (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL)) - { - LRESULT cpuFreeItem = SendMessage (GetDlgItem (hwndDlg, IDC_ENCRYPTION_FREE_CPU_COUNT), CB_GETCURSEL, 0, 0); - if (cpuFreeItem != CB_ERR) - cpuFreeCount = (uint32) (cpuFreeItem + 1); - } - - if (ReadEncryptionThreadPoolFreeCpuCountLimit() != cpuFreeCount) - { - BootEncObj->WriteLocalMachineRegistryDwordValue (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME, cpuFreeCount); - Warning ("SETTING_REQUIRES_REBOOT", hwndDlg); - } - - EndDialog (hwndDlg, lw); - return 1; - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - } - return 1; - - case IDC_ENABLE_HARDWARE_ENCRYPTION: - if (!IsDlgButtonChecked (hwndDlg, IDC_ENABLE_HARDWARE_ENCRYPTION) - && AskWarnYesNo ("CONFIRM_SETTING_DEGRADES_PERFORMANCE", hwndDlg) == IDNO) - { - CheckDlgButton (hwndDlg, IDC_ENABLE_HARDWARE_ENCRYPTION, BST_CHECKED); - } - return 1; - - case IDC_LIMIT_ENC_THREAD_POOL: - if (IsDlgButtonChecked (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL) - && AskWarnYesNo ("CONFIRM_SETTING_DEGRADES_PERFORMANCE", hwndDlg) == IDNO) - { - CheckDlgButton (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL, BST_UNCHECKED); - } - else - { - SendMessage (GetDlgItem (hwndDlg, IDC_ENCRYPTION_FREE_CPU_COUNT), CB_SETCURSEL, 0, 0); - Warning ("SETTING_REQUIRES_REBOOT", hwndDlg); // Warn the user before he thinks about benchmarking - } - - EnableWindow (GetDlgItem (hwndDlg, IDC_ENCRYPTION_FREE_CPU_COUNT), IsDlgButtonChecked (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL)); - return 1; - - case IDC_BENCHMARK: - Benchmark (hwndDlg); - return 1; - - case IDC_MORE_INFO_ON_HW_ACCELERATION: - Applink ("hwacceleration", TRUE, ""); - return 1; - - case IDC_MORE_INFO_ON_THREAD_BASED_PARALLELIZATION: - Applink ("parallelization", TRUE, ""); - return 1; - } - - return 0; - } - - return 0; -} - - -static BOOL CALLBACK SecurityTokenPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - LocalizeDialog (hwndDlg, "IDD_TOKEN_PREFERENCES"); - SetDlgItemText (hwndDlg, IDC_PKCS11_MODULE, SecurityTokenLibraryPath); - CheckDlgButton (hwndDlg, IDC_CLOSE_TOKEN_SESSION_AFTER_MOUNT, CloseSecurityTokenSessionsAfterMount ? BST_CHECKED : BST_UNCHECKED); - - SetWindowTextW (GetDlgItem (hwndDlg, IDT_PKCS11_LIB_HELP), GetString("PKCS11_LIB_LOCATION_HELP")); - - return 0; - - case WM_COMMAND: - - switch (lw) - { - case IDCANCEL: - EndDialog (hwndDlg, lw); - return 1; - - case IDOK: - { - wchar_t securityTokenLibraryPath[MAX_PATH]; - GetDlgItemText (hwndDlg, IDC_PKCS11_MODULE, securityTokenLibraryPath, ARRAYSIZE (securityTokenLibraryPath)); - - if (securityTokenLibraryPath[0] == 0) - { - try - { - SecurityToken::CloseLibrary(); - } - catch (...) { } - - SecurityTokenLibraryPath[0] = 0; - } - else - { - wchar_t prevSecurityTokenLibraryPath[MAX_PATH]; - StringCbCopyW (prevSecurityTokenLibraryPath, sizeof(prevSecurityTokenLibraryPath), SecurityTokenLibraryPath); - StringCbCopyW (SecurityTokenLibraryPath, sizeof(SecurityTokenLibraryPath), securityTokenLibraryPath); - - if (!InitSecurityTokenLibrary(hwndDlg)) - { - StringCbCopyW (SecurityTokenLibraryPath, sizeof(SecurityTokenLibraryPath), prevSecurityTokenLibraryPath); - return 1; - } - } - - CloseSecurityTokenSessionsAfterMount = (IsDlgButtonChecked (hwndDlg, IDC_CLOSE_TOKEN_SESSION_AFTER_MOUNT) == BST_CHECKED); - - WaitCursor (); - SaveSettings (hwndDlg); - NormalCursor (); - - EndDialog (hwndDlg, lw); - return 1; - } - - case IDC_AUTO_DETECT_PKCS11_MODULE: - { - wchar_t systemDir[MAX_PATH]; - GetSystemDirectory (systemDir, ARRAYSIZE (systemDir)); - WIN32_FIND_DATA findData; - bool found = false; - - WaitCursor(); - - HANDLE find = FindFirstFile ((wstring (systemDir) + L"\\*.dll").c_str(), &findData); - while (!found && find != INVALID_HANDLE_VALUE) - { - wstring dllPathname = wstring (systemDir) + L"\\" + findData.cFileName; - DWORD fileSize; - - char *file = LoadFile (dllPathname.c_str(), &fileSize); - if (file) - { - const char *functionName = "C_GetFunctionList"; - size_t strLen = strlen (functionName); - - if (fileSize > strLen) - { - for (size_t i = 0; i < fileSize - strLen; ++i) - { - if (memcmp (file + i, functionName, strLen) == 0) - { - HMODULE module = LoadLibrary (dllPathname.c_str()); - if (module) - { - if (GetProcAddress (module, functionName)) - { - SetDlgItemText (hwndDlg, IDC_PKCS11_MODULE, dllPathname.c_str()); - found = true; - - FreeLibrary (module); - break; - } - - FreeLibrary (module); - } - } - } - } - - free (file); - } - - if (!FindNextFile (find, &findData)) - break; - } - - if (find != INVALID_HANDLE_VALUE) - FindClose (find); - - NormalCursor(); - - if (!found) - Warning ("PKCS11_MODULE_AUTO_DETECTION_FAILED", hwndDlg); - - return 1; - } - - case IDC_SELECT_PKCS11_MODULE: - { - wchar_t securityTokenLibraryPath[MAX_PATH]; - wchar_t systemDir[MAX_PATH]; - wchar_t browseFilter[1024]; - - Info ("SELECT_PKCS11_MODULE_HELP", hwndDlg); - - StringCbPrintfW (browseFilter, sizeof(browseFilter), L"%ls (*.dll)%c*.dll%c%c", GetString ("DLL_FILES"), 0, 0, 0); - GetSystemDirectory (systemDir, ARRAYSIZE (systemDir)); - - if (BrowseFilesInDir (hwndDlg, "SELECT_PKCS11_MODULE", systemDir, securityTokenLibraryPath, TRUE, FALSE, browseFilter)) - SetDlgItemText (hwndDlg, IDC_PKCS11_MODULE, securityTokenLibraryPath); - return 1; - } - } - return 0; - } - - return 0; -} - -static BOOL CALLBACK DefaultMountParametersDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - LocalizeDialog (hwndDlg, "IDD_DEFAULT_MOUNT_PARAMETERS"); - - SendMessage (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), BM_SETCHECK, - DefaultVolumeTrueCryptMode ? BST_CHECKED:BST_UNCHECKED, 0); - - /* Populate the PRF algorithms list */ - int i, nIndex, defaultPrfIndex = 0; - HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); - SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); - - nIndex = (int) SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); - - for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) - { - nIndex = (int) SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); - SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); - if (DefaultVolumePkcs5 && (DefaultVolumePkcs5 == i)) - defaultPrfIndex = nIndex; - } - - /* make autodetection the default unless a specific PRF was specified in the command line */ - SendMessage (hComboBox, CB_SETCURSEL, defaultPrfIndex, 0); - - return 0; - } - - case WM_COMMAND: - - switch (lw) - { - case IDCANCEL: - EndDialog (hwndDlg, lw); - return 1; - - case IDOK: - { - int pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); - BOOL truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); - /* SHA-256 is not supported by TrueCrypt */ - if ( (truecryptMode) - && (pkcs5 == SHA256) - ) - { - Error ("ALGO_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); - } - else - { - WaitCursor (); - DefaultVolumeTrueCryptMode = truecryptMode; - DefaultVolumePkcs5 = pkcs5; - - SaveSettings (hwndDlg); - - NormalCursor (); - EndDialog (hwndDlg, lw); - } - return 1; - } - - } - return 0; - } - - return 0; -} - -void SecurityTokenPreferencesDialog (HWND hwndDlg) -{ - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TOKEN_PREFERENCES), hwndDlg, (DLGPROC) SecurityTokenPreferencesDlgProc, 0); -} - - -static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - { - if (!BootEncObj->GetStatus().DriveMounted) - { - Warning ("SYS_DRIVE_NOT_ENCRYPTED", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - try - { - LocalizeDialog (hwndDlg, "IDD_SYSENC_SETTINGS"); - - uint32 driverConfig = ReadDriverConfigurationFlags(); - byte userConfig; - string customUserMessage; - uint16 bootLoaderVersion; - BOOL bPasswordCacheEnabled = (driverConfig & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD)? TRUE : FALSE; - BOOL bPimCacheEnabled = (driverConfig & TC_DRIVER_CONFIG_CACHE_BOOT_PIM)? TRUE : FALSE; - - BootEncObj->ReadBootSectorConfig (nullptr, 0, &userConfig, &customUserMessage, &bootLoaderVersion); - - if (bootLoaderVersion != VERSION_NUM) - Warning ("BOOT_LOADER_VERSION_INCORRECT_PREFERENCES", hwndDlg); - - SendMessage (GetDlgItem (hwndDlg, IDC_CUSTOM_BOOT_LOADER_MESSAGE), EM_LIMITTEXT, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH, 0); - SetDlgItemTextA (hwndDlg, IDC_CUSTOM_BOOT_LOADER_MESSAGE, customUserMessage.c_str()); - - CheckDlgButton (hwndDlg, IDC_DISABLE_BOOT_LOADER_PIM_PROMPT, (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM) ? BST_CHECKED : BST_UNCHECKED); - CheckDlgButton (hwndDlg, IDC_DISABLE_BOOT_LOADER_OUTPUT, (userConfig & TC_BOOT_USER_CFG_FLAG_SILENT_MODE) ? BST_CHECKED : BST_UNCHECKED); - CheckDlgButton (hwndDlg, IDC_ALLOW_ESC_PBA_BYPASS, (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_ESC) ? BST_UNCHECKED : BST_CHECKED); - CheckDlgButton (hwndDlg, IDC_BOOT_LOADER_CACHE_PASSWORD, bPasswordCacheEnabled ? BST_CHECKED : BST_UNCHECKED); - CheckDlgButton (hwndDlg, IDC_DISABLE_EVIL_MAID_ATTACK_DETECTION, (driverConfig & TC_DRIVER_CONFIG_DISABLE_EVIL_MAID_ATTACK_DETECTION) ? BST_CHECKED : BST_UNCHECKED); - EnableWindow (GetDlgItem (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM), bPasswordCacheEnabled); - CheckDlgButton (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM, (bPasswordCacheEnabled && bPimCacheEnabled)? BST_CHECKED : BST_UNCHECKED); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_CUSTOM_BOOT_LOADER_MESSAGE_HELP), GetString("CUSTOM_BOOT_LOADER_MESSAGE_HELP")); - } - catch (Exception &e) - { - e.Show (hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - } - return 0; - - case WM_COMMAND: - - switch (lw) - { - case IDCANCEL: - EndDialog (hwndDlg, lw); - return 1; - - case IDOK: - { - VOLUME_PROPERTIES_STRUCT prop; - - if (!BootEncObj->GetStatus().DriveMounted) - { - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - try - { - BootEncObj->GetVolumeProperties (&prop); - } - catch (Exception &e) - { - e.Show (hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - char customUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH + 1]; - GetDlgItemTextA (hwndDlg, IDC_CUSTOM_BOOT_LOADER_MESSAGE, customUserMessage, sizeof (customUserMessage)); - - byte userConfig; - try - { - BootEncObj->ReadBootSectorConfig (nullptr, 0, &userConfig); - } - catch (Exception &e) - { - e.Show (hwndDlg); - return 1; - } - - if (IsDlgButtonChecked (hwndDlg, IDC_DISABLE_BOOT_LOADER_PIM_PROMPT)) - userConfig |= TC_BOOT_USER_CFG_FLAG_DISABLE_PIM; - else - userConfig &= ~TC_BOOT_USER_CFG_FLAG_DISABLE_PIM; - - if (IsDlgButtonChecked (hwndDlg, IDC_DISABLE_BOOT_LOADER_OUTPUT)) - userConfig |= TC_BOOT_USER_CFG_FLAG_SILENT_MODE; - else - userConfig &= ~TC_BOOT_USER_CFG_FLAG_SILENT_MODE; - - if (!IsDlgButtonChecked (hwndDlg, IDC_ALLOW_ESC_PBA_BYPASS)) - userConfig |= TC_BOOT_USER_CFG_FLAG_DISABLE_ESC; - else - userConfig &= ~TC_BOOT_USER_CFG_FLAG_DISABLE_ESC; - - try - { - BOOL bPasswordCacheEnabled = IsDlgButtonChecked (hwndDlg, IDC_BOOT_LOADER_CACHE_PASSWORD); - BOOL bPimCacheEnabled = IsDlgButtonChecked (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM); - BootEncObj->WriteBootSectorUserConfig (userConfig, customUserMessage, prop.volumePim); - SetDriverConfigurationFlag (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD, bPasswordCacheEnabled); - SetDriverConfigurationFlag (TC_DRIVER_CONFIG_CACHE_BOOT_PIM, (bPasswordCacheEnabled && bPimCacheEnabled)? TRUE : FALSE); - SetDriverConfigurationFlag (TC_DRIVER_CONFIG_DISABLE_EVIL_MAID_ATTACK_DETECTION, IsDlgButtonChecked (hwndDlg, IDC_DISABLE_EVIL_MAID_ATTACK_DETECTION)); - } - catch (Exception &e) - { - e.Show (hwndDlg); - return 1; - } - - EndDialog (hwndDlg, lw); - return 1; - } - - case IDC_DISABLE_BOOT_LOADER_PIM_PROMPT: - if ((IsDlgButtonChecked (hwndDlg, IDC_DISABLE_BOOT_LOADER_PIM_PROMPT)) - && AskWarnYesNo ("DISABLE_BOOT_LOADER_PIM_PROMPT", hwndDlg) == IDNO) - { - CheckDlgButton (hwndDlg, IDC_DISABLE_BOOT_LOADER_PIM_PROMPT, BST_UNCHECKED); - } - - case IDC_DISABLE_BOOT_LOADER_OUTPUT: - if ((IsDlgButtonChecked (hwndDlg, IDC_DISABLE_BOOT_LOADER_OUTPUT)) - && AskWarnYesNo ("CUSTOM_BOOT_LOADER_MESSAGE_PROMPT", hwndDlg) == IDNO) - { - CheckDlgButton (hwndDlg, IDC_DISABLE_BOOT_LOADER_OUTPUT, BST_UNCHECKED); - } - - break; - - case IDC_BOOT_LOADER_CACHE_PASSWORD: - if (IsDlgButtonChecked (hwndDlg, IDC_BOOT_LOADER_CACHE_PASSWORD)) - { - Warning ("BOOT_PASSWORD_CACHE_KEYBOARD_WARNING", hwndDlg); - EnableWindow (GetDlgItem (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM), TRUE); - } - else - { - EnableWindow (GetDlgItem (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM), FALSE); - } - - break; - } - return 0; - } - - return 0; -} - - -void MountSelectedVolume (HWND hwndDlg, BOOL mountWithOptions) -{ - if (!VolumeSelected(hwndDlg)) - { - Warning ("NO_VOLUME_SELECTED", hwndDlg); - } - else if (LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) == TC_MLIST_ITEM_FREE) - { - mountOptions = defaultMountOptions; - bPrebootPasswordDlgMode = FALSE; - - if (mountWithOptions || GetAsyncKeyState (VK_CONTROL) < 0) - { - /* Priority is given to command line parameters - * Default values used only when nothing specified in command line - */ - if (CmdVolumePkcs5 == 0) - mountOptions.ProtectedHidVolPkcs5Prf = DefaultVolumePkcs5; - else - mountOptions.ProtectedHidVolPkcs5Prf = CmdVolumePkcs5; - mountOptions.ProtectedHidVolPim = CmdVolumePim; - if (IDCANCEL == DialogBoxParamW (hInst, - MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, - (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions)) - return; - - if (mountOptions.ProtectHiddenVolume && hidVolProtKeyFilesParam.EnableKeyFiles) - { - wchar_t selectedVolume [TC_MAX_PATH + 1]; - GetVolumePath (hwndDlg, selectedVolume, ARRAYSIZE (selectedVolume)); - KeyFilesApply (hwndDlg, &mountOptions.ProtectedHidVolPassword, hidVolProtKeyFilesParam.FirstKeyFile, selectedVolume); - } - } - - if (CheckMountList (hwndDlg, FALSE)) - _beginthread (mountThreadFunction, 0, hwndDlg); - } - else - Warning ("SELECT_FREE_DRIVE", hwndDlg); -} - -static BOOL HandleDriveListMouseWheelEvent (UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL bListMustBePointed) -{ - static BOOL eventHandlerActive = FALSE; - if (eventHandlerActive) - return 0; - - RECT listRect; - int mouseX = GET_X_LPARAM (lParam); - int mouseY = GET_Y_LPARAM (lParam); - - GetWindowRect (GetDlgItem (MainDlg, IDC_DRIVELIST), &listRect); - - // Determine if the mouse pointer is within the main drive list - bool bListPointed = (mouseX >= listRect.left && mouseX <= listRect.right - && mouseY >= listRect.top && mouseY <= listRect.bottom); - - if (bListMustBePointed && bListPointed - || !bListMustBePointed) - { - eventHandlerActive = TRUE; - - if (!bListMustBePointed && bListPointed) - SetFocus (GetDlgItem (MainDlg, IDC_DRIVELIST)); - - SendMessage (GetDlgItem (MainDlg, IDC_DRIVELIST), uMsg, wParam, lParam); - - eventHandlerActive = FALSE; - return 0; // Do not process this event any further e.g. to prevent two lists from being scrolled at once - } - - return 1; -} - - -static LRESULT CALLBACK MouseWheelProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - WNDPROC wp = (WNDPROC) GetWindowLongPtrW (hwnd, GWLP_USERDATA); - - switch (message) - { - case WM_MOUSEWHEEL: - - if (HandleDriveListMouseWheelEvent (message, wParam, lParam, TRUE) == 0) - return 0; // Do not process this event any further e.g. to prevent two lists from being scrolled at once - } - - return CallWindowProcW (wp, hwnd, message, wParam, lParam); -} - - -void HookMouseWheel (HWND hwndDlg, UINT ctrlId) -{ - HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId); - - SetWindowLongPtrW (hwndCtrl, GWLP_USERDATA, (LONG_PTR) GetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC)); - SetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC, (LONG_PTR) MouseWheelProc); -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" +#include "cpu.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Apidrvr.h" +#include "BootEncryption.h" +#include "Cmdline.h" +#include "Crypto.h" +#include "Dlgcode.h" +#include "Combo.h" +#include "Favorites.h" +#include "Hotkeys.h" +#include "Keyfiles.h" +#include "Language.h" +#include "MainCom.h" +#include "Mount.h" +#include "Pkcs5.h" +#include "Random.h" +#include "Registry.h" +#include "Resource.h" +#include "Password.h" +#include "Xml.h" +#include "../Boot/Windows/BootCommon.h" +#include "../Common/Dictionary.h" +#include "../Common/Common.h" +#include "../Common/Resource.h" +#include "../Common/SecurityToken.h" +#include "../Platform/Finally.h" +#include "../Platform/ForEach.h" + +#include + +#include + +typedef BOOL (WINAPI *WTSREGISTERSESSIONNOTIFICATION)(HWND, DWORD); +typedef BOOL (WINAPI *WTSUNREGISTERSESSIONNOTIFICATION)(HWND); + +using namespace VeraCrypt; + +enum timer_ids +{ + TIMER_ID_MAIN = 0xff, + TIMER_ID_KEYB_LAYOUT_GUARD +}; + +enum hidden_os_read_only_notif_mode +{ + TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_NONE = 0, + TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_COMPACT, + TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_DISABLED +}; + +#define TIMER_INTERVAL_MAIN 500 +#define TIMER_INTERVAL_KEYB_LAYOUT_GUARD 10 + +BootEncryption *BootEncObj = NULL; +BootEncryptionStatus BootEncStatus; +BootEncryptionStatus RecentBootEncStatus; + +BOOL bExplore = FALSE; /* Display explorer window after mount */ +BOOL bBeep = FALSE; /* Donot beep after mount */ +wchar_t szFileName[TC_MAX_PATH+1]; /* Volume to mount */ +wchar_t szDriveLetter[3]; /* Drive Letter to mount */ +wchar_t commandLineDrive = 0; +BOOL bCacheInDriver = FALSE; /* Cache any passwords we see */ +BOOL bCacheInDriverDefault = FALSE; +BOOL bCacheDuringMultipleMount = FALSE; +BOOL bCmdCacheDuringMultipleMount = FALSE; +BOOL bIncludePimInCache = FALSE; +BOOL bTryEmptyPasswordWhenKeyfileUsed = FALSE; +BOOL bCmdTryEmptyPasswordWhenKeyfileUsed = FALSE; +BOOL bCmdTryEmptyPasswordWhenKeyfileUsedValid = FALSE; +BOOL bHistoryCmdLine = FALSE; /* History control is always disabled */ +BOOL bUseDifferentTrayIconIfVolMounted = TRUE; +BOOL bCloseDismountedWindows=TRUE; /* Close all open explorer windows of dismounted volume */ +BOOL bWipeCacheOnExit = FALSE; /* Wipe password from chace on exit */ +BOOL bWipeCacheOnAutoDismount = TRUE; +BOOL bEnableBkgTask = FALSE; +BOOL bCloseBkgTaskWhenNoVolumes = FALSE; +BOOL bDismountOnLogOff = TRUE; +BOOL bDismountOnSessionLocked = TRUE; +BOOL bDismountOnScreenSaver = TRUE; +BOOL bDismountOnPowerSaving = FALSE; +BOOL bForceAutoDismount = TRUE; +BOOL bForceMount = FALSE; /* Mount volume even if host file/device already in use */ +BOOL bForceUnmount = FALSE; /* Unmount volume even if it cannot be locked */ +BOOL bWipe = FALSE; /* Wipe driver passwords */ +BOOL bAuto = FALSE; /* Do everything without user input */ +BOOL LogOn = FALSE; +BOOL bAutoMountDevices = FALSE; /* Auto-mount devices */ +BOOL bAutoMountFavorites = FALSE; +BOOL bPlaySoundOnSuccessfulHkDismount = TRUE; +BOOL bDisplayBalloonOnSuccessfulHkDismount = TRUE; +BOOL bHibernationPreventionNotified = FALSE; /* TRUE if the user has been notified that hibernation was prevented (system encryption) during the session. */ +BOOL bHiddenSysLeakProtNotifiedDuringSession = FALSE; /* TRUE if the user has been notified during the session that unencrypted filesystems and non-hidden TrueCrypt volumes are mounted as read-only under hidden OS. */ +BOOL CloseSecurityTokenSessionsAfterMount = FALSE; + +BOOL Quit = FALSE; /* Exit after processing command line */ +BOOL ComServerMode = FALSE; +BOOL ServiceMode = FALSE; +BOOL UsePreferences = TRUE; + +int HiddenSysLeakProtectionNotificationStatus = TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_NONE; +int MaxVolumeIdleTime = -120; +int nCurrentShowType = 0; /* current display mode, mount, unmount etc */ +int nSelectedDriveIndex = -1; /* Item number of selected drive */ + +int cmdUnmountDrive = -2; /* Volume drive letter to unmount (-1 = all) */ +Password VolumePassword; /* Password used for mounting volumes */ +Password CmdVolumePassword; /* Password passed from command line */ +char CmdTokenPin [SecurityToken::MaxPasswordLength + 1] = {0}; +int VolumePkcs5 = 0; +int CmdVolumePkcs5 = 0; +int VolumePim = -1; +int CmdVolumePim = -1; +int DefaultVolumePkcs5 = 0; +BOOL VolumeTrueCryptMode = FALSE; +BOOL CmdVolumeTrueCryptMode = FALSE; +BOOL DefaultVolumeTrueCryptMode = FALSE; +BOOL CmdVolumePasswordValid = FALSE; +MountOptions CmdMountOptions; +BOOL CmdMountOptionsValid = FALSE; +MountOptions mountOptions; +MountOptions defaultMountOptions; +KeyFile *FirstCmdKeyFile; + +HBITMAP hbmLogoBitmapRescaled = NULL; +wchar_t OrigKeyboardLayout [8+1] = L"00000409"; +BOOL bKeyboardLayoutChanged = FALSE; /* TRUE if the keyboard layout was changed to the standard US keyboard layout (from any other layout). */ +BOOL bKeybLayoutAltKeyWarningShown = FALSE; /* TRUE if the user has been informed that it is not possible to type characters by pressing keys while the right Alt key is held down. */ + +static KeyFilesDlgParam hidVolProtKeyFilesParam; + +static MOUNT_LIST_STRUCT LastKnownMountList; +VOLUME_NOTIFICATIONS_LIST VolumeNotificationsList; +static DWORD LastKnownLogicalDrives; + +static HANDLE TaskBarIconMutex = NULL; +static BOOL MainWindowHidden = FALSE; +static int pwdChangeDlgMode = PCDM_CHANGE_PASSWORD; +static int bSysEncPwdChangeDlgMode = FALSE; +static int bPrebootPasswordDlgMode = FALSE; +static int NoCmdLineArgs; +static BOOL CmdLineVolumeSpecified; +static int LastDriveListVolumeColumnWidth; +// WTS handling +static HMODULE hWtsLib = NULL; +static WTSREGISTERSESSIONNOTIFICATION fnWtsRegisterSessionNotification = NULL; +static WTSUNREGISTERSESSIONNOTIFICATION fnWtsUnRegisterSessionNotification = NULL; + +static void RegisterWtsNotification(HWND hWnd) +{ + if (!hWtsLib) + { + wchar_t dllPath[MAX_PATH]; + if (GetSystemDirectory(dllPath, MAX_PATH)) + StringCbCatW(dllPath, sizeof(dllPath), L"\\wtsapi32.dll"); + else + StringCbCopyW(dllPath, sizeof(dllPath), L"c:\\Windows\\System32\\wtsapi32.dll"); + + hWtsLib = LoadLibrary(dllPath); + if (hWtsLib) + { + fnWtsRegisterSessionNotification = (WTSREGISTERSESSIONNOTIFICATION) GetProcAddress(hWtsLib, "WTSRegisterSessionNotification" ); + fnWtsUnRegisterSessionNotification = (WTSUNREGISTERSESSIONNOTIFICATION) GetProcAddress(hWtsLib, "WTSUnRegisterSessionNotification" ); + if ( !fnWtsRegisterSessionNotification + || !fnWtsUnRegisterSessionNotification + || !fnWtsRegisterSessionNotification( hWnd, NOTIFY_FOR_THIS_SESSION ) + ) + { + fnWtsRegisterSessionNotification = NULL; + fnWtsUnRegisterSessionNotification = NULL; + FreeLibrary(hWtsLib); + hWtsLib = NULL; + } + } + } +} + +static void UnregisterWtsNotification(HWND hWnd) +{ + if (hWtsLib && fnWtsUnRegisterSessionNotification) + { + fnWtsUnRegisterSessionNotification(hWnd); + FreeLibrary(hWtsLib); + hWtsLib = NULL; + fnWtsRegisterSessionNotification = NULL; + fnWtsUnRegisterSessionNotification = NULL; + } +} + +static void localcleanup (void) +{ + // Wipe command line + char *c = GetCommandLineA (); + wchar_t *wc = GetCommandLineW (); + burn(c, strlen (c)); + burn(wc, wcslen (wc) * sizeof (wchar_t)); + + /* Delete buffered bitmaps (if any) */ + if (hbmLogoBitmapRescaled != NULL) + { + DeleteObject ((HGDIOBJ) hbmLogoBitmapRescaled); + hbmLogoBitmapRescaled = NULL; + } + + /* These items should have already been cleared by the functions that used them, but we're going to + clear them for extra security. */ + burn (&VolumePassword, sizeof (VolumePassword)); + burn (&CmdVolumePassword, sizeof (CmdVolumePassword)); + burn (&VolumePkcs5, sizeof (VolumePkcs5)); + burn (&CmdVolumePkcs5, sizeof (CmdVolumePkcs5)); + burn (&VolumePim, sizeof (VolumePim)); + burn (&CmdVolumePim, sizeof (CmdVolumePim)); + burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); + burn (&CmdVolumeTrueCryptMode, sizeof (CmdVolumeTrueCryptMode)); + burn (&mountOptions, sizeof (mountOptions)); + burn (&defaultMountOptions, sizeof (defaultMountOptions)); + burn (szFileName, sizeof(szFileName)); + burn (&CmdTokenPin, sizeof (CmdTokenPin)); + + /* Cleanup common code resources */ + cleanup (); + + if (BootEncObj != NULL) + { + delete BootEncObj; + BootEncObj = NULL; + } + + RandStop (TRUE); +} + +void RefreshMainDlg (HWND hwndDlg) +{ + int drive = (wchar_t) (HIWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST)))); + + MoveEditToCombo (GetDlgItem (hwndDlg, IDC_VOLUME), bHistory); + LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), drive); + EnableDisableButtons (hwndDlg); +} + +void EndMainDlg (HWND hwndDlg) +{ + MoveEditToCombo (GetDlgItem (hwndDlg, IDC_VOLUME), bHistory); + + if (UsePreferences) + SaveSettings (hwndDlg); + + if (bWipeCacheOnExit) + { + DWORD dwResult; + DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); + } + + if (!bHistory) + { + SetWindowText (GetDlgItem (hwndDlg, IDC_VOLUME), L""); + ClearHistory (GetDlgItem (hwndDlg, IDC_VOLUME)); + } + + if (TaskBarIconMutex != NULL) + { + MainWindowHidden = TRUE; + ShowWindow (hwndDlg, SW_HIDE); + } + else + { + KillTimer (hwndDlg, TIMER_ID_MAIN); + TaskBarIconRemove (hwndDlg); + UnregisterWtsNotification(hwndDlg); + EndDialog (hwndDlg, 0); + } +} + +static void InitMainDialog (HWND hwndDlg) +{ + MENUITEMINFOW info; + char *popupTexts[] = {"MENU_VOLUMES", "MENU_SYSTEM_ENCRYPTION", "MENU_FAVORITES", "MENU_TOOLS", "MENU_SETTINGS", "MENU_HELP", "MENU_WEBSITE", 0}; + wchar_t *str; + int i; + + /* Call the common dialog init code */ + InitDialog (hwndDlg); + LocalizeDialog (hwndDlg, NULL); + + SetWindowLongPtrW (hwndDlg, DWLP_USER, (LONG_PTR) (IsAdmin() ? TC_MAIN_WINDOW_FLAG_ADMIN_PRIVILEGES : 0)); + + DragAcceptFiles (hwndDlg, TRUE); + + SendMessageW (GetDlgItem (hwndDlg, IDC_VOLUME), CB_LIMITTEXT, TC_MAX_PATH, 0); + SetWindowTextW (hwndDlg, (IsAdmin() && !IsBuiltInAdmin() && IsUacSupported() && !IsNonInstallMode()) ? (wstring (lpszTitle) + L" [" + GetString ("ADMINISTRATOR") + L"]").c_str() : lpszTitle); + + // Help file name + InitHelpFileName(); + + // Localize menu strings + for (i = 40001; str = (wchar_t *)GetDictionaryValueByInt (i); i++) + { + info.cbSize = sizeof (info); + info.fMask = MIIM_TYPE; + info.fType = MFT_STRING; + info.dwTypeData = str; + info.cch = (UINT) wcslen (str); + + SetMenuItemInfoW (GetMenu (hwndDlg), i, FALSE, &info); + } + + for (i = 0; popupTexts[i] != 0; i++) + { + str = GetString (popupTexts[i]); + + info.cbSize = sizeof (info); + info.fMask = MIIM_TYPE; + + if (strcmp (popupTexts[i], "MENU_WEBSITE") == 0) + info.fType = MFT_STRING | MFT_RIGHTJUSTIFY; + else + info.fType = MFT_STRING; + + if (strcmp (popupTexts[i], "MENU_FAVORITES") == 0) + FavoriteVolumesMenu = GetSubMenu (GetMenu (hwndDlg), i); + + info.dwTypeData = str; + info.cch = (UINT) wcslen (str); + + SetMenuItemInfoW (GetMenu (hwndDlg), i, TRUE, &info); + } + + // Disable menu item for changing system header key derivation algorithm until it's implemented + EnableMenuItem (GetMenu (hwndDlg), IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO, MF_GRAYED); + + try + { + LoadFavoriteVolumes(); + } + catch (Exception &e) + { + e.Show (NULL); + } + + // Resize the logo bitmap if the user has a non-default DPI + if (ScreenDPI != USER_DEFAULT_SCREEN_DPI + && hbmLogoBitmapRescaled == NULL) // If not re-called (e.g. after language pack change) + { + hbmLogoBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_LOGO_288DPI), + GetDlgItem (hwndDlg, IDC_LOGO), + 0, 0, 0, 0, FALSE, TRUE); + } + + BuildTree (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST)); + + if (*szDriveLetter != 0) + { + SelectItem (GetDlgItem (hwndDlg, IDC_DRIVELIST), *szDriveLetter); + + if(nSelectedDriveIndex > SendMessage (GetDlgItem (hwndDlg, IDC_DRIVELIST), LVM_GETITEMCOUNT, 0, 0)/2) + SendMessage(GetDlgItem (hwndDlg, IDC_DRIVELIST), LVM_SCROLL, 0, 10000); + } + else + { + SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hwndDlg, IDC_DRIVELIST), 1L); + } + + SendMessage (GetDlgItem (hwndDlg, IDC_NO_HISTORY), BM_SETCHECK, bHistory ? BST_UNCHECKED : BST_CHECKED, 0); + EnableDisableButtons (hwndDlg); +} + +void EnableDisableButtons (HWND hwndDlg) +{ + HWND hOKButton = GetDlgItem (hwndDlg, IDOK); + WORD x; + + x = LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))); + + EnableMenuItem (GetMenu (hwndDlg), IDM_MOUNT_VOLUME, MF_ENABLED); + EnableMenuItem (GetMenu (hwndDlg), IDM_MOUNT_VOLUME_OPTIONS, MF_ENABLED); + EnableMenuItem (GetMenu (hwndDlg), IDM_BACKUP_VOL_HEADER, MF_ENABLED); + EnableMenuItem (GetMenu (hwndDlg), IDM_RESTORE_VOL_HEADER, MF_ENABLED); + EnableMenuItem (GetMenu (hwndDlg), IDM_CHANGE_PASSWORD, MF_ENABLED); + EnableWindow (hOKButton, TRUE); + + switch (x) + { + case TC_MLIST_ITEM_NONSYS_VOL: + { + SetWindowTextW (hOKButton, GetString ("UNMOUNT_BUTTON")); + EnableWindow (hOKButton, TRUE); + EnableMenuItem (GetMenu (hwndDlg), IDM_UNMOUNT_VOLUME, MF_ENABLED); + + EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES), TRUE); + EnableMenuItem (GetMenu (hwndDlg), IDM_VOLUME_PROPERTIES, MF_ENABLED); + } + break; + + case TC_MLIST_ITEM_SYS_PARTITION: + case TC_MLIST_ITEM_SYS_DRIVE: + EnableWindow (hOKButton, FALSE); + SetWindowTextW (hOKButton, GetString ("MOUNT_BUTTON")); + EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES), TRUE); + EnableMenuItem (GetMenu (hwndDlg), IDM_UNMOUNT_VOLUME, MF_GRAYED); + break; + + case TC_MLIST_ITEM_FREE: + default: + SetWindowTextW (hOKButton, GetString ("MOUNT_BUTTON")); + EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES), FALSE); + EnableMenuItem (GetMenu (hwndDlg), IDM_VOLUME_PROPERTIES, MF_GRAYED); + EnableMenuItem (GetMenu (hwndDlg), IDM_UNMOUNT_VOLUME, MF_GRAYED); + } + + EnableWindow (GetDlgItem (hwndDlg, IDC_WIPE_CACHE), !IsPasswordCacheEmpty()); + EnableMenuItem (GetMenu (hwndDlg), IDM_WIPE_CACHE, IsPasswordCacheEmpty() ? MF_GRAYED:MF_ENABLED); + EnableMenuItem (GetMenu (hwndDlg), IDM_CLEAR_HISTORY, IsComboEmpty (GetDlgItem (hwndDlg, IDC_VOLUME)) ? MF_GRAYED:MF_ENABLED); +} + +BOOL VolumeSelected (HWND hwndDlg) +{ + return (GetWindowTextLength (GetDlgItem (hwndDlg, IDC_VOLUME)) > 0); +} + +void GetVolumePath (HWND hwndDlg, LPWSTR szPath, int nMaxCount) +{ + GetWindowText (GetDlgItem (hwndDlg, IDC_VOLUME), szPath, nMaxCount); + CorrectFileName (szPath); +} + +/* Returns TRUE if the last partition/drive selected via the Select Device dialog box was the system +partition/drive and if it is encrypted. + WARNING: This function is very fast but not always reliable (for example, if the user manually types + a device path before Select Device is invoked during the session; after the Select Device dialog + has been invoked at least once, the correct system device paths are cached). Therefore, it must NOT + be used before performing any dangerous operations (such as header backup restore or formatting a + supposedly non-system device) -- instead use IsSystemDevicePath(path, hwndDlg, TRUE) for such + purposes. This function can be used only for preliminary GUI checks requiring very fast responses. */ +BOOL ActiveSysEncDeviceSelected (void) +{ + try + { + BootEncStatus = BootEncObj->GetStatus(); + + if (BootEncStatus.DriveEncrypted) + { + int retCode = 0; + + GetVolumePath (MainDlg, szFileName, ARRAYSIZE (szFileName)); + + retCode = IsSystemDevicePath (szFileName, MainDlg, FALSE); + + return (WholeSysDriveEncryption(FALSE) ? (retCode == 2 || retCode == 1) : (retCode == 1)); + } + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + return FALSE; +} + +// When a function does not require the affected volume to be dismounted, there may be cases where we have two valid +// paths selected in the main window and we cannot be sure which of them the user really intends to apply the function to. +// This function asks the user to explicitly select either the volume path specified in the input field below the main +// drive list (whether mounted or not), or the path to the volume selected in the main drive list. If, however, both +// of the GUI elements contain the same volume (or one of them does not contain any path), this function does not +// ask the user and returns the volume path directly (no selection ambiguity). +// If driveNoPtr is not NULL, and the volume is mounted, its drive letter is returned in *driveNoPtr (if no valid drive +// letter is resolved, -1 is stored instead). +static wstring ResolveAmbiguousSelection (HWND hwndDlg, int *driveNoPtr) +{ + LPARAM selectedDrive = GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST)); + + wchar_t volPathInputField [TC_MAX_PATH]; + + wchar_t volPathDriveListW [TC_MAX_PATH]; + wstring volPathDriveListStr; + + wstring retPath; + + VOLUME_PROPERTIES_STRUCT prop; + DWORD dwResult; + + BOOL useInputField = TRUE; + + memset (&prop, 0, sizeof(prop)); + + BOOL ambig = (LOWORD (selectedDrive) != TC_MLIST_ITEM_FREE && LOWORD (selectedDrive) != 0xffff && HIWORD (selectedDrive) != 0xffff + && VolumeSelected (MainDlg)); + + if (VolumeSelected (MainDlg)) + { + // volPathInputField will contain the volume path (if any) from the input field below the drive list + GetVolumePath (MainDlg, volPathInputField, ARRAYSIZE (volPathInputField)); + + if (!ambig) + retPath = (wstring) volPathInputField; + } + + if (LOWORD (selectedDrive) != TC_MLIST_ITEM_FREE && LOWORD (selectedDrive) != 0xffff && HIWORD (selectedDrive) != 0xffff) + { + // A volume is selected in the main drive list. + + switch (LOWORD (selectedDrive)) + { + case TC_MLIST_ITEM_NONSYS_VOL: + prop.driveNo = HIWORD (selectedDrive) - L'A'; + + if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL) || dwResult == 0) + { + // The driver did not return any path for this drive letter (the volume may have been dismounted). + + // Return whatever is in the input field below the drive list (even if empty) + return ((wstring) volPathInputField); + } + + // volPathDriveListWStr will contain the volume path selected in the main drive list + volPathDriveListStr = (wstring) prop.wszVolume; + break; + + case TC_MLIST_ITEM_SYS_PARTITION: + + GetSysDevicePaths (MainDlg); + + if (bCachedSysDevicePathsValid) + { + volPathDriveListStr = (wstring) SysPartitionDevicePath; + } + + break; + + case TC_MLIST_ITEM_SYS_DRIVE: + + GetSysDevicePaths (MainDlg); + + if (bCachedSysDevicePathsValid) + { + volPathDriveListStr = (wstring) SysDriveDevicePath; + } + + break; + } + + if (!ambig) + { + useInputField = FALSE; + retPath = volPathDriveListStr; + } + } + + if (ambig) + { + /* We have two paths. Compare them and if they don't match, ask the user to select one of them. Otherwise, return the path without asking. */ + + if (wmemcmp (volPathDriveListStr.c_str (), L"\\??\\", 4) == 0) + { + // The volume path starts with "\\??\\" which is used for file-hosted containers. We're going to strip this prefix. + + volPathDriveListStr = (wstring) (volPathDriveListStr.c_str () + 4); + } + + StringCbCopyW (volPathDriveListW, sizeof(volPathDriveListW), volPathDriveListStr.c_str ()); + + if (wcscmp (((wmemcmp (volPathDriveListW, L"\\??\\", 4) == 0) ? volPathDriveListW + 4 : volPathDriveListW), volPathInputField) != 0) + { + // The path selected in the input field is different from the path to the volume selected + // in the drive lettter list. We have to resolve possible ambiguity. + + wchar_t *tmp[] = {L"", L"", L"", L"", L"", 0}; + const int maxVolPathLen = 80; + + if (volPathDriveListStr.length () > maxVolPathLen) + { + // Ellipsis (path too long) + volPathDriveListStr = wstring (L"...") + volPathDriveListStr.substr (volPathDriveListStr.length () - maxVolPathLen, maxVolPathLen); + } + + wstring volPathInputFieldWStr (volPathInputField); + + if (volPathInputFieldWStr.length () > maxVolPathLen) + { + // Ellipsis (path too long) + volPathInputFieldWStr = wstring (L"...") + volPathInputFieldWStr.substr (volPathInputFieldWStr.length () - maxVolPathLen, maxVolPathLen); + } + + tmp[1] = GetString ("AMBIGUOUS_VOL_SELECTION"); + tmp[2] = (wchar_t *) volPathDriveListStr.c_str(); + tmp[3] = (wchar_t *) volPathInputFieldWStr.c_str(); + tmp[4] = GetString ("IDCANCEL"); + + switch (AskMultiChoice ((void **) tmp, FALSE, hwndDlg)) + { + case 1: + retPath = volPathDriveListStr; + break; + + case 2: + retPath = (wstring) volPathInputField; + break; + + default: + if (driveNoPtr != NULL) + *driveNoPtr = -1; + + return wstring (L""); + } + } + else + { + // Both selected paths are the same + retPath = (wstring) volPathInputField; + } + } + + if (driveNoPtr != NULL) + *driveNoPtr = GetMountedVolumeDriveNo ((wchar_t *) retPath.c_str ()); + + + if (wmemcmp (retPath.c_str (), L"\\??\\", 4) == 0) + { + // The selected volume path starts with "\\??\\" which is used for file-hosted containers. We're going to strip this prefix. + + retPath = (wstring) (retPath.c_str () + 4); + } + + return retPath; +} + +void LoadSettingsAndCheckModified (HWND hwndDlg, BOOL bOnlyCheckModified, BOOL* pbSettingsModified, BOOL* pbHistoryModified) +{ + char langid[6] = {0}; + if (!bOnlyCheckModified) + EnableHwEncryption ((ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? FALSE : TRUE); + + WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE; + + if (!bOnlyCheckModified) + LoadSysEncSettings (); + + if (!bOnlyCheckModified && LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) != 0) + bInPlaceEncNonSysPending = TRUE; + + // If the config file has already been loaded during this session + if (ConfigBuffer != NULL) + { + free (ConfigBuffer); + ConfigBuffer = NULL; + } + + // Options + ConfigReadCompareInt ("OpenExplorerWindowAfterMount", FALSE, &bExplore, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("UseDifferentTrayIconIfVolumesMounted", TRUE, &bUseDifferentTrayIconIfVolMounted, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("SaveVolumeHistory", FALSE, &bHistory, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("CachePasswords", FALSE, &bCacheInDriverDefault, bOnlyCheckModified, pbSettingsModified); + if (!bOnlyCheckModified) + bCacheInDriver = bCacheInDriverDefault; + + ConfigReadCompareInt ("CachePasswordDuringMultipleMount", FALSE, &bCacheDuringMultipleMount, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("WipePasswordCacheOnExit", FALSE, &bWipeCacheOnExit, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("WipeCacheOnAutoDismount", TRUE, &bWipeCacheOnAutoDismount, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("IncludePimInCache", FALSE, &bIncludePimInCache, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("TryEmptyPasswordWhenKeyfileUsed",FALSE, &bTryEmptyPasswordWhenKeyfileUsed, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("StartOnLogon", FALSE, &bStartOnLogon, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("MountDevicesOnLogon", FALSE, &bMountDevicesOnLogon, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("MountFavoritesOnLogon", FALSE, &bMountFavoritesOnLogon, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("EnableBackgroundTask", TRUE, &bEnableBkgTask, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("CloseBackgroundTaskOnNoVolumes", FALSE, &bCloseBkgTaskWhenNoVolumes, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("DismountOnLogOff", !(IsServerOS() && IsAdmin()), &bDismountOnLogOff, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("DismountOnSessionLocked", FALSE, &bDismountOnSessionLocked, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("DismountOnPowerSaving", FALSE, &bDismountOnPowerSaving, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("DismountOnScreenSaver", FALSE, &bDismountOnScreenSaver, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("ForceAutoDismount", TRUE, &bForceAutoDismount, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("MaxVolumeIdleTime", -60, &MaxVolumeIdleTime, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("HiddenSectorDetectionStatus", 0, &HiddenSectorDetectionStatus, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("UseKeyfiles", FALSE, &defaultKeyFilesParam.EnableKeyFiles, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("PreserveTimestamps", TRUE, &defaultMountOptions.PreserveTimestamp, bOnlyCheckModified, pbSettingsModified); + if (!bOnlyCheckModified) + bPreserveTimestamp = defaultMountOptions.PreserveTimestamp; + + ConfigReadCompareInt ("ShowDisconnectedNetworkDrives", FALSE, &bShowDisconnectedNetworkDrives, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("HideWaitingDialog", FALSE, &bHideWaitingDialog, bOnlyCheckModified, pbSettingsModified); + + ConfigReadCompareInt ("MountVolumesRemovable", FALSE, &defaultMountOptions.Removable, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("MountVolumesReadOnly", FALSE, &defaultMountOptions.ReadOnly, bOnlyCheckModified, pbSettingsModified); + + if (!bOnlyCheckModified) + { + defaultMountOptions.ProtectHiddenVolume = FALSE; + defaultMountOptions.ProtectedHidVolPkcs5Prf = 0; + defaultMountOptions.ProtectedHidVolPim = 0; + defaultMountOptions.PartitionInInactiveSysEncScope = FALSE; + defaultMountOptions.RecoveryMode = FALSE; + defaultMountOptions.UseBackupHeader = FALSE; + + mountOptions = defaultMountOptions; + } + + ConfigReadCompareInt ("CloseSecurityTokenSessionsAfterMount", 0, &CloseSecurityTokenSessionsAfterMount, bOnlyCheckModified, pbSettingsModified); + + if (IsHiddenOSRunning()) + ConfigReadCompareInt ("HiddenSystemLeakProtNotifStatus", TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_NONE, &HiddenSysLeakProtectionNotificationStatus, bOnlyCheckModified, pbSettingsModified); + + // Drive letter - command line arg overrides registry + if (!bOnlyCheckModified && bHistory && szDriveLetter[0] == 0) + { + char szTmp[3] = {0}; + ConfigReadString ("LastSelectedDrive", "", szTmp, sizeof (szTmp)); + MultiByteToWideChar (CP_UTF8, 0, szTmp, -1, szDriveLetter, ARRAYSIZE (szDriveLetter)); + } + if (bHistory && pbSettingsModified) + { + // only check for last drive modification if history enabled + char szTmp[32] = {0}; + LPARAM lLetter; + lLetter = GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST)); + if (LOWORD (lLetter) != 0xffff) + StringCbPrintfA (szTmp, sizeof(szTmp), "%lc:", (wchar_t) HIWORD (lLetter)); + + ConfigReadCompareString ("LastSelectedDrive", "", szTmp, sizeof (szTmp), bOnlyCheckModified, pbSettingsModified); + } + + { + char szTmp[MAX_PATH]; + WideCharToMultiByte (CP_UTF8, 0, SecurityTokenLibraryPath, -1, szTmp, MAX_PATH, NULL, NULL); + ConfigReadCompareString ("SecurityTokenLibrary", "", szTmp, sizeof (szTmp) - 1, bOnlyCheckModified, pbSettingsModified); + MultiByteToWideChar (CP_UTF8, 0, szTmp, -1, SecurityTokenLibraryPath, ARRAYSIZE (SecurityTokenLibraryPath)); + if (!bOnlyCheckModified && SecurityTokenLibraryPath[0]) + { + InitSecurityTokenLibrary(hwndDlg); + } + } + + // Hotkeys + ConfigReadCompareInt ("PlaySoundOnHotkeyMountDismount", TRUE, &bPlaySoundOnSuccessfulHkDismount, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("DisplayMsgBoxOnHotkeyDismount", TRUE, &bDisplayBalloonOnSuccessfulHkDismount, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyModAutoMountDevices", 0, (int*) &Hotkeys [HK_AUTOMOUNT_DEVICES].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyCodeAutoMountDevices", 0, (int*) &Hotkeys [HK_AUTOMOUNT_DEVICES].vKeyCode, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyModDismountAll", 0, (int*) &Hotkeys [HK_DISMOUNT_ALL].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyCodeDismountAll", 0, (int*) &Hotkeys [HK_DISMOUNT_ALL].vKeyCode, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyModWipeCache", 0, (int*) &Hotkeys [HK_WIPE_CACHE].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyCodeWipeCache", 0, (int*) &Hotkeys [HK_WIPE_CACHE].vKeyCode, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyModDismountAllWipe", 0, (int*) &Hotkeys [HK_DISMOUNT_ALL_AND_WIPE].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyCodeDismountAllWipe", 0, (int*) &Hotkeys [HK_DISMOUNT_ALL_AND_WIPE].vKeyCode, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyModForceDismountAllWipe", 0, (int*) &Hotkeys [HK_FORCE_DISMOUNT_ALL_AND_WIPE].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyCodeForceDismountAllWipe", 0, (int*) &Hotkeys [HK_FORCE_DISMOUNT_ALL_AND_WIPE].vKeyCode, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyModForceDismountAllWipeExit", 0, (int*) &Hotkeys [HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyCodeForceDismountAllWipeExit", 0, (int*) &Hotkeys [HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT].vKeyCode, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyModMountFavoriteVolumes", 0, (int*) &Hotkeys [HK_MOUNT_FAVORITE_VOLUMES].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyCodeMountFavoriteVolumes", 0, (int*) &Hotkeys [HK_MOUNT_FAVORITE_VOLUMES].vKeyCode, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyModShowHideMainWindow", 0, (int*) &Hotkeys [HK_SHOW_HIDE_MAIN_WINDOW].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyCodeShowHideMainWindow", 0, (int*) &Hotkeys [HK_SHOW_HIDE_MAIN_WINDOW].vKeyCode, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyModCloseSecurityTokenSessions", 0, (int*) &Hotkeys [HK_CLOSE_SECURITY_TOKEN_SESSIONS].vKeyModifiers, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("HotkeyCodeCloseSecurityTokenSessions", 0, (int*) &Hotkeys [HK_CLOSE_SECURITY_TOKEN_SESSIONS].vKeyCode, bOnlyCheckModified, pbSettingsModified); + + // History + if (bHistoryCmdLine != TRUE) + { + LoadCombo (GetDlgItem (MainDlg, IDC_VOLUME), bHistory, bOnlyCheckModified, pbHistoryModified); + if (!bOnlyCheckModified && CmdLineVolumeSpecified) + SetWindowText (GetDlgItem (MainDlg, IDC_VOLUME), szFileName); + } + + // Mount Options + ConfigReadCompareInt ("DefaultPRF", 0, &DefaultVolumePkcs5, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("DefaultTrueCryptMode", FALSE, &DefaultVolumeTrueCryptMode, bOnlyCheckModified, pbSettingsModified); + + if (bOnlyCheckModified) + { + if (!IsNonInstallMode ()) + { + ConfigReadString ("Language", "", langid, sizeof (langid)); + // when installed, if no preferred language set by user, English is set default + // + if (langid [0] == 0) + StringCbCopyA (langid, sizeof(langid), "en"); + + if (pbSettingsModified && strcmp (langid, GetPreferredLangId ())) + *pbSettingsModified = TRUE; + } + else + { + StringCbCopyA (langid, sizeof(langid), GetPreferredLangId ()); + ConfigReadCompareString ("Language", "", langid, sizeof (langid), TRUE, pbSettingsModified); + } + } + + if (DefaultVolumePkcs5 < 0 || DefaultVolumePkcs5 > LAST_PRF_ID) + DefaultVolumePkcs5 = 0; + if (DefaultVolumeTrueCryptMode != TRUE && DefaultVolumeTrueCryptMode != FALSE) + DefaultVolumeTrueCryptMode = FALSE; + +} + +void LoadSettings ( HWND hwndDlg ) +{ + LoadSettingsAndCheckModified (hwndDlg, FALSE, NULL, NULL); +} + +void SaveSettings (HWND hwndDlg) +{ + WaitCursor (); + + // Check first if modifications ocurred before writing to the settings and history files + // This avoids leaking information about VeraCrypt usage when user only mount volumes without changing setttings or history + BOOL bSettingsChanged = FALSE; + BOOL bHistoryChanged = FALSE; + + LoadSettingsAndCheckModified (hwndDlg, TRUE, &bSettingsChanged, &bHistoryChanged); + + if (bSettingsChanged) + { + char szTmp[32] = {0}; + LPARAM lLetter; + + // Options + ConfigWriteBegin (); + + ConfigWriteInt ("OpenExplorerWindowAfterMount", bExplore); + ConfigWriteInt ("UseDifferentTrayIconIfVolumesMounted", bUseDifferentTrayIconIfVolMounted); + ConfigWriteInt ("SaveVolumeHistory", bHistory); + + ConfigWriteInt ("CachePasswords", bCacheInDriverDefault); + ConfigWriteInt ("CachePasswordDuringMultipleMount", bCacheDuringMultipleMount); + ConfigWriteInt ("WipePasswordCacheOnExit", bWipeCacheOnExit); + ConfigWriteInt ("WipeCacheOnAutoDismount", bWipeCacheOnAutoDismount); + + ConfigWriteInt ("IncludePimInCache", bIncludePimInCache); + + ConfigWriteInt ("TryEmptyPasswordWhenKeyfileUsed", bTryEmptyPasswordWhenKeyfileUsed); + + ConfigWriteInt ("StartOnLogon", bStartOnLogon); + ConfigWriteInt ("MountDevicesOnLogon", bMountDevicesOnLogon); + ConfigWriteInt ("MountFavoritesOnLogon", bMountFavoritesOnLogon); + + ConfigWriteInt ("MountVolumesReadOnly", defaultMountOptions.ReadOnly); + ConfigWriteInt ("MountVolumesRemovable", defaultMountOptions.Removable); + ConfigWriteInt ("PreserveTimestamps", defaultMountOptions.PreserveTimestamp); + ConfigWriteInt ("ShowDisconnectedNetworkDrives",bShowDisconnectedNetworkDrives); + ConfigWriteInt ("HideWaitingDialog", bHideWaitingDialog); + + ConfigWriteInt ("EnableBackgroundTask", bEnableBkgTask); + ConfigWriteInt ("CloseBackgroundTaskOnNoVolumes", bCloseBkgTaskWhenNoVolumes); + + ConfigWriteInt ("DismountOnLogOff", bDismountOnLogOff); + ConfigWriteInt ("DismountOnSessionLocked", bDismountOnSessionLocked); + ConfigWriteInt ("DismountOnPowerSaving", bDismountOnPowerSaving); + ConfigWriteInt ("DismountOnScreenSaver", bDismountOnScreenSaver); + ConfigWriteInt ("ForceAutoDismount", bForceAutoDismount); + ConfigWriteInt ("MaxVolumeIdleTime", MaxVolumeIdleTime); + + ConfigWriteInt ("HiddenSectorDetectionStatus", HiddenSectorDetectionStatus); + + ConfigWriteInt ("UseKeyfiles", defaultKeyFilesParam.EnableKeyFiles); + + if (IsHiddenOSRunning()) + ConfigWriteInt ("HiddenSystemLeakProtNotifStatus", HiddenSysLeakProtectionNotificationStatus); + + // save last selected drive only when history enabled + if (bHistory) + { + // Drive Letter + lLetter = GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST)); + if (LOWORD (lLetter) != 0xffff) + StringCbPrintfA (szTmp, sizeof(szTmp), "%lc:", (wchar_t) HIWORD (lLetter)); + ConfigWriteString ("LastSelectedDrive", szTmp); + } + + ConfigWriteInt ("CloseSecurityTokenSessionsAfterMount", CloseSecurityTokenSessionsAfterMount); + + // Hotkeys + ConfigWriteInt ("HotkeyModAutoMountDevices", Hotkeys[HK_AUTOMOUNT_DEVICES].vKeyModifiers); + ConfigWriteInt ("HotkeyCodeAutoMountDevices", Hotkeys[HK_AUTOMOUNT_DEVICES].vKeyCode); + ConfigWriteInt ("HotkeyModDismountAll", Hotkeys[HK_DISMOUNT_ALL].vKeyModifiers); + ConfigWriteInt ("HotkeyCodeDismountAll", Hotkeys[HK_DISMOUNT_ALL].vKeyCode); + ConfigWriteInt ("HotkeyModWipeCache", Hotkeys[HK_WIPE_CACHE].vKeyModifiers); + ConfigWriteInt ("HotkeyCodeWipeCache", Hotkeys[HK_WIPE_CACHE].vKeyCode); + ConfigWriteInt ("HotkeyModDismountAllWipe", Hotkeys[HK_DISMOUNT_ALL_AND_WIPE].vKeyModifiers); + ConfigWriteInt ("HotkeyCodeDismountAllWipe", Hotkeys[HK_DISMOUNT_ALL_AND_WIPE].vKeyCode); + ConfigWriteInt ("HotkeyModForceDismountAllWipe", Hotkeys[HK_FORCE_DISMOUNT_ALL_AND_WIPE].vKeyModifiers); + ConfigWriteInt ("HotkeyCodeForceDismountAllWipe", Hotkeys[HK_FORCE_DISMOUNT_ALL_AND_WIPE].vKeyCode); + ConfigWriteInt ("HotkeyModForceDismountAllWipeExit", Hotkeys[HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT].vKeyModifiers); + ConfigWriteInt ("HotkeyCodeForceDismountAllWipeExit", Hotkeys[HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT].vKeyCode); + ConfigWriteInt ("HotkeyModMountFavoriteVolumes", Hotkeys[HK_MOUNT_FAVORITE_VOLUMES].vKeyModifiers); + ConfigWriteInt ("HotkeyCodeMountFavoriteVolumes", Hotkeys[HK_MOUNT_FAVORITE_VOLUMES].vKeyCode); + ConfigWriteInt ("HotkeyModShowHideMainWindow", Hotkeys[HK_SHOW_HIDE_MAIN_WINDOW].vKeyModifiers); + ConfigWriteInt ("HotkeyCodeShowHideMainWindow", Hotkeys[HK_SHOW_HIDE_MAIN_WINDOW].vKeyCode); + ConfigWriteInt ("HotkeyModCloseSecurityTokenSessions", Hotkeys[HK_CLOSE_SECURITY_TOKEN_SESSIONS].vKeyModifiers); + ConfigWriteInt ("HotkeyCodeCloseSecurityTokenSessions", Hotkeys[HK_CLOSE_SECURITY_TOKEN_SESSIONS].vKeyCode); + ConfigWriteInt ("PlaySoundOnHotkeyMountDismount", bPlaySoundOnSuccessfulHkDismount); + ConfigWriteInt ("DisplayMsgBoxOnHotkeyDismount", bDisplayBalloonOnSuccessfulHkDismount); + + // Language + ConfigWriteString ("Language", GetPreferredLangId ()); + + // PKCS#11 Library Path + ConfigWriteStringW ("SecurityTokenLibrary", SecurityTokenLibraryPath[0] ? SecurityTokenLibraryPath : L""); + + // Mount Options + ConfigWriteInt ("DefaultPRF", DefaultVolumePkcs5); + ConfigWriteInt ("DefaultTrueCryptMode", DefaultVolumeTrueCryptMode); + + ConfigWriteEnd (hwndDlg); + } + + if (bHistoryChanged) + { + // History + DumpCombo (GetDlgItem (MainDlg, IDC_VOLUME), IsButtonChecked (GetDlgItem (MainDlg, IDC_NO_HISTORY))); + } + + NormalCursor (); +} + +// Returns TRUE if system encryption or decryption had been or is in progress and has not been completed +static BOOL SysEncryptionOrDecryptionRequired (void) +{ + /* If you update this function, revise SysEncryptionOrDecryptionRequired() in Tcformat.c as well. */ + + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + return (SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING + || SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING + || + ( + BootEncStatus.DriveMounted + && + ( + BootEncStatus.ConfiguredEncryptedAreaStart != BootEncStatus.EncryptedAreaStart + || BootEncStatus.ConfiguredEncryptedAreaEnd != BootEncStatus.EncryptedAreaEnd + ) + ) + ); +} + +// Returns TRUE if the system partition/drive is completely encrypted +static BOOL SysDriveOrPartitionFullyEncrypted (BOOL bSilent) +{ + /* If you update this function, revise SysDriveOrPartitionFullyEncrypted() in Tcformat.c as well. */ + + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + if (!bSilent) + e.Show (MainDlg); + } + + return (!BootEncStatus.SetupInProgress + && BootEncStatus.ConfiguredEncryptedAreaEnd != 0 + && BootEncStatus.ConfiguredEncryptedAreaEnd != -1 + && BootEncStatus.ConfiguredEncryptedAreaStart == BootEncStatus.EncryptedAreaStart + && BootEncStatus.ConfiguredEncryptedAreaEnd == BootEncStatus.EncryptedAreaEnd); +} + +// Returns TRUE if the system partition/drive is being filtered by the TrueCrypt driver and the key data +// was successfully decrypted (the device is fully ready to be encrypted or decrypted). Note that this +// function does not examine whether the system device is encrypted or not (or to what extent). +static BOOL SysEncDeviceActive (BOOL bSilent) +{ + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + if (!bSilent) + e.Show (MainDlg); + + return FALSE; + } + + return (BootEncStatus.DriveMounted); +} + +// Returns TRUE if the entire system drive (as opposed to the system partition only) of the currently running OS is (or is to be) encrypted +BOOL WholeSysDriveEncryption (BOOL bSilent) +{ + try + { + BootEncStatus = BootEncObj->GetStatus(); + + if (BootEncStatus.BootDriveLength.QuadPart < 1) // paranoid check + return FALSE; + else + return (BootEncStatus.ConfiguredEncryptedAreaStart == TC_BOOT_LOADER_AREA_SIZE + && BootEncStatus.ConfiguredEncryptedAreaEnd >= BootEncStatus.BootDriveLength.QuadPart - 1); + } + catch (Exception &e) + { + if (!bSilent) + e.Show (MainDlg); + + return FALSE; + } +} + +// Returns the size of the system drive/partition (if encrypted) in bytes +unsigned __int64 GetSysEncDeviceSize (BOOL bSilent) +{ + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + if (!bSilent) + e.Show (MainDlg); + return 1; + } + + if ( BootEncStatus.ConfiguredEncryptedAreaEnd < 0 + || BootEncStatus.ConfiguredEncryptedAreaStart < 0 + || BootEncStatus.ConfiguredEncryptedAreaEnd < BootEncStatus.ConfiguredEncryptedAreaStart + ) + return 1; // we return 1 to avoid devision by zero + else + return ((unsigned __int64)(BootEncStatus.ConfiguredEncryptedAreaEnd - BootEncStatus.ConfiguredEncryptedAreaStart)) + 1; +} + +// Returns the current size of the encrypted area of the system drive/partition in bytes +unsigned __int64 GetSysEncDeviceEncryptedPartSize (BOOL bSilent) +{ + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + if (!bSilent) + e.Show (MainDlg); + return 0; + } + + if ( BootEncStatus.EncryptedAreaEnd < 0 + || BootEncStatus.EncryptedAreaStart < 0 + || BootEncStatus.EncryptedAreaEnd < BootEncStatus.EncryptedAreaStart + ) + return 0; + else + return ((unsigned __int64)(BootEncStatus.EncryptedAreaEnd - BootEncStatus.EncryptedAreaStart)) + 1; +} + + +static void PopulateSysEncContextMenu (HMENU popup, BOOL bToolsOnly) +{ + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + if (!bToolsOnly && !IsHiddenOSRunning()) + { + if (SysEncryptionOrDecryptionRequired ()) + { + if (!BootEncStatus.SetupInProgress) + AppendMenuW (popup, MF_STRING, IDM_SYSENC_RESUME, GetString ("IDM_SYSENC_RESUME")); + + if (SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING) + AppendMenuW (popup, MF_STRING, IDM_PERMANENTLY_DECRYPT_SYS, GetString ("PERMANENTLY_DECRYPT")); + + AppendMenuW (popup, MF_STRING, IDM_ENCRYPT_SYSTEM_DEVICE, GetString ("ENCRYPT")); + AppendMenu (popup, MF_SEPARATOR, 0, L""); + } + } + + AppendMenuW (popup, MF_STRING, IDM_CHANGE_SYS_PASSWORD, GetString ("IDM_CHANGE_SYS_PASSWORD")); + // AppendMenuW (popup, MF_STRING, IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO, GetString ("IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO")); + + AppendMenu (popup, MF_SEPARATOR, 0, L""); + AppendMenuW (popup, MF_STRING, IDM_SYS_ENC_SETTINGS, GetString ("IDM_SYS_ENC_SETTINGS")); + + if (!IsHiddenOSRunning()) + { + AppendMenu (popup, MF_SEPARATOR, 0, L""); + AppendMenuW (popup, MF_STRING, IDM_CREATE_RESCUE_DISK, GetString ("IDM_CREATE_RESCUE_DISK")); + AppendMenuW (popup, MF_STRING, IDM_VERIFY_RESCUE_DISK, GetString ("IDM_VERIFY_RESCUE_DISK")); + AppendMenuW (popup, MF_STRING, IDM_VERIFY_RESCUE_DISK_ISO, GetString ("IDM_VERIFY_RESCUE_DISK_ISO")); + } + + if (!bToolsOnly) + { + if (SysDriveOrPartitionFullyEncrypted (FALSE) && !IsHiddenOSRunning()) + { + AppendMenu (popup, MF_SEPARATOR, 0, L""); + AppendMenuW (popup, MF_STRING, IDM_PERMANENTLY_DECRYPT_SYS, GetString ("PERMANENTLY_DECRYPT")); + } + AppendMenu (popup, MF_SEPARATOR, 0, L""); + AppendMenuW (popup, MF_STRING, IDM_VOLUME_PROPERTIES, GetString ("IDPM_PROPERTIES")); + } +} + + +// WARNING: This function may take a long time to complete. To prevent data corruption, it MUST be called before +// mounting a partition (as a regular volume) that is within key scope of system encryption. +// Returns TRUE if the partition can be mounted as a partition within key scope of inactive system encryption. +// If devicePath is empty, the currently selected partition in the GUI is checked. +BOOL CheckSysEncMountWithoutPBA (HWND hwndDlg, const wchar_t *devicePath, BOOL quiet) +{ + BOOL tmpbDevice; + wchar_t szDevicePath [TC_MAX_PATH+1]; + wchar_t szDiskFile [TC_MAX_PATH+1]; + + if (wcslen (devicePath) < 2) + { + GetVolumePath (MainDlg, szDevicePath, ARRAYSIZE (szDevicePath)); + CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szDevicePath, &tmpbDevice); + + if (!tmpbDevice) + { + if (!quiet) + Warning ("NO_SYSENC_PARTITION_SELECTED", hwndDlg); + + return FALSE; + } + + if (LOWORD (GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST))) != TC_MLIST_ITEM_FREE) + { + if (!quiet) + Warning ("SELECT_FREE_DRIVE", hwndDlg); + + return FALSE; + } + } + else + StringCbCopyW (szDevicePath, sizeof(szDevicePath), devicePath); + + wchar_t *partionPortion = wcsrchr (szDevicePath, L'\\'); + + if (!partionPortion + || !_wcsicmp (partionPortion, L"\\Partition0")) + { + // Only partitions are supported (not whole drives) + if (!quiet) + Warning ("NO_SYSENC_PARTITION_SELECTED", hwndDlg); + + return FALSE; + } + + try + { + BootEncStatus = BootEncObj->GetStatus(); + + if (BootEncStatus.DriveMounted) + { + int retCode = 0; + int driveNo; + wchar_t parentDrivePath [TC_MAX_PATH+1]; + + if (swscanf (szDevicePath, L"\\Device\\Harddisk%d\\Partition", &driveNo) != 1) + { + if (!quiet) + Error ("INVALID_PATH", hwndDlg); + + return FALSE; + } + + StringCbPrintfW (parentDrivePath, + sizeof (parentDrivePath), + L"\\Device\\Harddisk%d\\Partition0", + driveNo); + + WaitCursor (); + + // This is critical (re-mounting a mounted system volume as a normal volume could cause data corruption) + // so we force the slower but reliable method + retCode = IsSystemDevicePath (parentDrivePath, MainDlg, TRUE); + + NormalCursor(); + + if (retCode != 2) + return TRUE; + else + { + // The partition is located on active system drive + + if (!quiet) + Warning ("MOUNT_WITHOUT_PBA_VOL_ON_ACTIVE_SYSENC_DRIVE", hwndDlg); + + return FALSE; + } + } + else + return TRUE; + } + catch (Exception &e) + { + NormalCursor(); + e.Show (hwndDlg); + } + + return FALSE; +} + + +// Returns TRUE if the host drive of the specified partition contains a portion of the TrueCrypt Boot Loader +// and if the drive is not within key scope of active system encryption (e.g. the system drive of the running OS). +// If bPrebootPasswordDlgMode is TRUE, this function returns FALSE (because the check would be redundant). +BOOL TCBootLoaderOnInactiveSysEncDrive (wchar_t *szDevicePath) +{ + try + { + int driveNo; + wchar_t parentDrivePath [TC_MAX_PATH+1]; + + if (bPrebootPasswordDlgMode) + return FALSE; + + + if (swscanf (szDevicePath, L"\\Device\\Harddisk%d\\Partition", &driveNo) != 1) + return FALSE; + + StringCbPrintfW (parentDrivePath, + sizeof (parentDrivePath), + L"\\Device\\Harddisk%d\\Partition0", + driveNo); + + BootEncStatus = BootEncObj->GetStatus(); + + if (BootEncStatus.DriveMounted + && IsSystemDevicePath (parentDrivePath, MainDlg, FALSE) == 2) + { + // The partition is within key scope of active system encryption + return FALSE; + } + + return ((BOOL) BootEncObj->IsBootLoaderOnDrive (parentDrivePath)); + } + catch (...) + { + return FALSE; + } + +} + + +BOOL SelectItem (HWND hTree, wchar_t nLetter) +{ + if (nLetter == 0) + { + // The caller specified an invalid drive letter (typically because it is unknown). + // Find out which drive letter is currently selected in the list and use it. + nLetter = (wchar_t) (HIWORD (GetSelectedLong (hTree))); + } + + int i; + LVITEM item; + + for (i = 0; i < ListView_GetItemCount(hTree); i++) + { + memset(&item, 0, sizeof(LVITEM)); + item.mask = LVIF_PARAM; + item.iItem = i; + + if (ListView_GetItem (hTree, &item) == FALSE) + return FALSE; + else + { + if (HIWORD (item.lParam) == nLetter) + { + memset(&item, 0, sizeof(LVITEM)); + item.state = LVIS_FOCUSED|LVIS_SELECTED; + item.stateMask = LVIS_FOCUSED|LVIS_SELECTED; + item.mask = LVIF_STATE; + item.iItem = i; + SendMessage(hTree, LVM_SETITEMSTATE, i, (LPARAM) &item); + return TRUE; + } + } + } + + return TRUE; +} + + +static void LaunchVolCreationWizard (HWND hwndDlg, const wchar_t *arg) +{ + wchar_t t[TC_MAX_PATH + 1024] = {L'"',0}; + wchar_t *tmp; + + GetModuleFileName (NULL, t+1, ARRAYSIZE(t)-1); + + tmp = wcsrchr (t, L'\\'); + if (tmp) + { + STARTUPINFO si; + PROCESS_INFORMATION pi; + wchar_t formatExeName[64]; + wchar_t* suffix = NULL; + ZeroMemory (&si, sizeof (si)); + + StringCbCopyW (formatExeName, sizeof (formatExeName), L"\\VeraCrypt Format"); + + // check if there is a suffix in VeraCrypt file name + // in order to use the same for "VeraCrypt Format" + suffix = wcsrchr (tmp + 1, L'-'); + if (suffix) + { + StringCbCatW (formatExeName, sizeof (formatExeName), suffix); + StringCbCatW (formatExeName, sizeof (formatExeName), L"\""); + } + else + StringCbCatW (formatExeName, sizeof (formatExeName), L".exe\""); + + *tmp = 0; + StringCbCatW (t, sizeof(t), formatExeName); + + if (!FileExists(t)) + Error ("VOL_CREATION_WIZARD_NOT_FOUND", hwndDlg); // Display a user-friendly error message and advise what to do + + if (wcslen (arg) > 0) + { + StringCbCatW (t, sizeof(t), L" "); + StringCbCatW (t, sizeof(t), arg); + } + + if (!CreateProcess (NULL, (LPWSTR) t, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi)) + { + handleWin32Error (hwndDlg, SRC_POS); + } + else + { + CloseHandle (pi.hProcess); + CloseHandle (pi.hThread); + } + } +} + +static void LaunchVolExpander (HWND hwndDlg) +{ + wchar_t t[TC_MAX_PATH + TC_MAX_PATH] = {L'"',0}; + wchar_t *tmp; + + GetModuleFileName (NULL, t+1, ARRAYSIZE(t)-1); + + tmp = wcsrchr (t, L'\\'); + if (tmp) + { + wchar_t expanderExeName[64]; + wchar_t* suffix = NULL; + + StringCbCopyW (expanderExeName, sizeof (expanderExeName), L"\\VeraCryptExpander"); + + // check if there is a suffix in VeraCrypt file name + // in order to use the same for "VeraCrypt Format" + suffix = wcsrchr (tmp + 1, L'-'); + if (suffix) + { + StringCbCatW (expanderExeName, sizeof (expanderExeName), suffix); + StringCbCatW (expanderExeName, sizeof (expanderExeName), L"\""); + } + else + StringCbCatW (expanderExeName, sizeof (expanderExeName), L".exe\""); + + *tmp = 0; + StringCbCatW (t, sizeof(t), expanderExeName); + + if (!FileExists(t)) + Error ("VOL_EXPANDER_NOT_FOUND", hwndDlg); // Display a user-friendly error message and advise what to do + else if (((int)ShellExecuteW (NULL, (!IsAdmin() && IsUacSupported()) ? L"runas" : L"open", t, NULL, NULL, SW_SHOW)) <= 32) + { + handleWin32Error (hwndDlg, SRC_POS); + } + } +} + + +// Fills drive list +// drive>0 = update only the corresponding drive subitems +void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) +{ + // Remember the top-most visible item + int lastTopMostVisibleItem = ListView_GetTopIndex (hTree); + + wchar_t *szDriveLetters[]= + {L"A:", L"B:", L"C:", L"D:", + L"E:", L"F:", L"G:", L"H:", L"I:", L"J:", L"K:", + L"L:", L"M:", L"N:", L"O:", L"P:", L"Q:", L"R:", + L"S:", L"T:", L"U:", L"V:", L"W:", L"X:", L"Y:", + L"Z:"}; + + DWORD dwResult; + BOOL bResult; + DWORD dwUsedDrives; + MOUNT_LIST_STRUCT driver; + VOLUME_PROPERTIES_STRUCT propSysEnc; + wchar_t sysDriveLetter = 0; + + BOOL bSysEnc = FALSE; + BOOL bWholeSysDriveEncryption = FALSE; + + LVITEM listItem; + int item = 0; + char i; + + try + { + BootEncStatus = BootEncObj->GetStatus(); + if (bSysEnc = BootEncStatus.DriveMounted) + { + BootEncObj->GetVolumeProperties (&propSysEnc); + } + } + catch (...) + { + bSysEnc = FALSE; + } + + ZeroMemory (&driver, sizeof (driver)); + bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &driver, + sizeof (driver), &driver, sizeof (driver), &dwResult, + NULL); + memcpy (&LastKnownMountList, &driver, sizeof (driver)); + + if (bResult == FALSE) + { + KillTimer (MainDlg, TIMER_ID_MAIN); + handleWin32Error (hTree, SRC_POS); + AbortProcessSilent(); + } + + LastKnownLogicalDrives = dwUsedDrives = GetUsedLogicalDrives (); + if (dwUsedDrives == 0) + Warning ("DRIVELETTERS", hwndDlg); + + if(drive == 0) + ListView_DeleteAllItems(hTree); + + if (bSysEnc) + { + bWholeSysDriveEncryption = WholeSysDriveEncryption (TRUE); + + sysDriveLetter = GetSystemDriveLetter (); + } + + /* System drive */ + + if (bWholeSysDriveEncryption) + { + int curDrive = 0; + + if (drive > 0) + { + LVITEM tmp; + memset(&tmp, 0, sizeof(LVITEM)); + tmp.mask = LVIF_PARAM; + tmp.iItem = item; + if (ListView_GetItem (hTree, &tmp)) + curDrive = HIWORD(tmp.lParam); + } + + { + wchar_t szTmp[1024]; + wchar_t szTmpW[1024]; + + memset(&listItem, 0, sizeof(listItem)); + + listItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; + listItem.iImage = 2; + listItem.iItem = item++; + + listItem.pszText = szTmp; + szTmp[0] = L' '; + szTmp[1] = 0; + + listItem.lParam = MAKELONG (TC_MLIST_ITEM_SYS_DRIVE, ENC_SYSDRIVE_PSEUDO_DRIVE_LETTER); + + if(drive == 0) + ListView_InsertItem (hTree, &listItem); + else + ListView_SetItem (hTree, &listItem); + + listItem.mask=LVIF_TEXT; + + // Fully encrypted + if (SysDriveOrPartitionFullyEncrypted (TRUE)) + { + StringCbCopyW (szTmpW, sizeof(szTmpW), GetString ("SYSTEM_DRIVE")); + } + else + { + // Partially encrypted + + if (BootEncStatus.SetupInProgress) + { + // Currently encrypting/decrypting + + if (BootEncStatus.SetupMode != SetupDecryption) + { + StringCbPrintfW (szTmpW, + sizeof szTmpW, + GetString ("SYSTEM_DRIVE_ENCRYPTING"), + (double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0); + } + else + { + StringCbPrintfW (szTmpW, + sizeof szTmpW, + GetString ("SYSTEM_DRIVE_DECRYPTING"), + 100.0 - ((double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0)); + } + } + else + { + StringCbPrintfW (szTmpW, + sizeof szTmpW, + GetString ("SYSTEM_DRIVE_PARTIALLY_ENCRYPTED"), + (double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0); + } + } + + ListSubItemSet (hTree, listItem.iItem, 1, szTmpW); + + GetSizeString (GetSysEncDeviceSize(TRUE), szTmpW, sizeof(szTmpW)); + ListSubItemSet (hTree, listItem.iItem, 2, szTmpW); + + if (propSysEnc.ea >= EAGetFirst() && propSysEnc.ea <= EAGetCount()) + { + EAGetName (szTmp, propSysEnc.ea, 1); + } + else + { + szTmp[0] = L'?'; + szTmp[1] = 0; + } + listItem.iSubItem = 3; + ListView_SetItem (hTree, &listItem); + + ListSubItemSet (hTree, listItem.iItem, 4, GetString (IsHiddenOSRunning() ? "HIDDEN" : "SYSTEM_VOLUME_TYPE_ADJECTIVE")); + } + } + + /* Drive letters */ + + for (i = 0; i < 26; i++) + { + int curDrive = 0; + + BOOL bSysEncPartition = (bSysEnc && !bWholeSysDriveEncryption && sysDriveLetter == *((wchar_t *) szDriveLetters[i])); + + if (drive > 0) + { + LVITEM tmp; + memset(&tmp, 0, sizeof(LVITEM)); + tmp.mask = LVIF_PARAM; + tmp.iItem = item; + if (ListView_GetItem (hTree, &tmp)) + curDrive = HIWORD(tmp.lParam); + } + + if (driver.ulMountedDrives & (1 << i) + || bSysEncPartition) + { + wchar_t szTmp[1024]; + wchar_t szTmpW[1024]; + wchar_t *ws; + + memset(&listItem, 0, sizeof(listItem)); + + listItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; + listItem.iImage = bSysEncPartition ? 2 : 1; + listItem.iItem = item++; + + if (drive > 0 && drive != curDrive) + continue; + + listItem.lParam = MAKELONG ( + bSysEncPartition ? TC_MLIST_ITEM_SYS_PARTITION : TC_MLIST_ITEM_NONSYS_VOL, + i + L'A'); + + listItem.pszText = szDriveLetters[i]; + + if (drive == 0) + ListView_InsertItem (hTree, &listItem); + else + ListView_SetItem (hTree, &listItem); + + listItem.mask=LVIF_TEXT; + listItem.pszText = szTmp; + + if (bSysEncPartition) + { + // Fully encrypted + if (SysDriveOrPartitionFullyEncrypted (TRUE)) + { + StringCbCopyW (szTmpW, sizeof(szTmpW), GetString (IsHiddenOSRunning() ? "HIDDEN_SYSTEM_PARTITION" : "SYSTEM_PARTITION")); + } + else + { + // Partially encrypted + + if (BootEncStatus.SetupInProgress) + { + // Currently encrypting/decrypting + + if (BootEncStatus.SetupMode != SetupDecryption) + { + StringCbPrintfW (szTmpW, + sizeof szTmpW, + GetString ("SYSTEM_PARTITION_ENCRYPTING"), + (double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0); + } + else + { + StringCbPrintfW (szTmpW, + sizeof szTmpW, + GetString ("SYSTEM_PARTITION_DECRYPTING"), + 100.0 - ((double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0)); + } + } + else + { + StringCbPrintfW (szTmpW, + sizeof szTmpW, + GetString ("SYSTEM_PARTITION_PARTIALLY_ENCRYPTED"), + (double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0); + } + } + + ListSubItemSet (hTree, listItem.iItem, 1, szTmpW); + } + else + { + wchar_t *path = driver.wszVolume[i]; + + if (wmemcmp (path, L"\\??\\", 4) == 0) + path += 4; + + listItem.iSubItem = 1; + + // first check label used for mounting. If empty, look for it in favorites. + bool useInExplorer = false; + wstring label = (wchar_t *) driver.wszLabel[i]; + if (label.empty()) + label = GetFavoriteVolumeLabel (path, useInExplorer); + if (!label.empty()) + ListSubItemSet (hTree, listItem.iItem, 1, (wchar_t *) label.c_str()); + else + ListSubItemSet (hTree, listItem.iItem, 1, (wchar_t *) FitPathInGfxWidth (hTree, hUserFont, ListView_GetColumnWidth (hTree, 1) - GetTextGfxWidth (hTree, L"___", hUserFont), path).c_str()); + } + + GetSizeString (bSysEncPartition ? GetSysEncDeviceSize(TRUE) : driver.diskLength[i], szTmpW, sizeof(szTmpW)); + ListSubItemSet (hTree, listItem.iItem, 2, szTmpW); + + EAGetName (szTmp, bSysEncPartition ? propSysEnc.ea : driver.ea[i], 1); + listItem.iSubItem = 3; + ListView_SetItem (hTree, &listItem); + + if (bSysEncPartition) + { + ws = GetString (IsHiddenOSRunning() ? "HIDDEN" : "SYSTEM_VOLUME_TYPE_ADJECTIVE"); + VolumeNotificationsList.bHidVolDamagePrevReported[i] = FALSE; + ListSubItemSet (hTree, listItem.iItem, 4, ws); + } + else + { + switch (driver.volumeType[i]) + { + case PROP_VOL_TYPE_NORMAL: + ws = GetString ("NORMAL"); + break; + case PROP_VOL_TYPE_HIDDEN: + ws = GetString ("HIDDEN"); + break; + case PROP_VOL_TYPE_OUTER: + ws = GetString ("OUTER"); // Normal/outer volume (hidden volume protected) + break; + case PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED: + ws = GetString ("OUTER_VOL_WRITE_PREVENTED"); // Normal/outer volume (hidden volume protected AND write denied) + break; + default: + ws = L"?"; + } + + if (driver.truecryptMode[i]) + { + StringCbPrintfW (szTmpW, sizeof(szTmpW), L"TrueCrypt-%s", ws); + ListSubItemSet (hTree, listItem.iItem, 4, szTmpW); + } + else + ListSubItemSet (hTree, listItem.iItem, 4, ws); + + if (driver.volumeType[i] == PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED) // Normal/outer volume (hidden volume protected AND write denied) + { + if (!VolumeNotificationsList.bHidVolDamagePrevReported[i]) + { + wchar_t szTmp[4096]; + + VolumeNotificationsList.bHidVolDamagePrevReported[i] = TRUE; + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), i+L'A'); + SetForegroundWindow (GetParent(hTree)); + MessageBoxW (GetParent(hTree), szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); + } + } + else + { + VolumeNotificationsList.bHidVolDamagePrevReported[i] = FALSE; + } + } + } + else + { + VolumeNotificationsList.bHidVolDamagePrevReported[i] = FALSE; + + if (!(dwUsedDrives & 1 << i)) + { + if(drive > 0 && drive != HIWORD (GetSelectedLong (hTree))) + { + item++; + continue; + } + + memset(&listItem,0,sizeof(listItem)); + + listItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; + listItem.iImage = 0; + listItem.iItem = item++; + listItem.pszText = szDriveLetters[i]; + listItem.lParam = MAKELONG (TC_MLIST_ITEM_FREE, i + 'A'); + + if(drive == 0) + ListView_InsertItem (hTree, &listItem); + else + ListView_SetItem (hTree, &listItem); + + listItem.mask=LVIF_TEXT; + listItem.pszText = L""; + listItem.iSubItem = 1; + ListView_SetItem (hTree, &listItem); + listItem.iSubItem = 2; + ListView_SetItem (hTree, &listItem); + listItem.iSubItem = 3; + ListView_SetItem (hTree, &listItem); + listItem.iSubItem = 4; + ListView_SetItem (hTree, &listItem); + + } + } + } + + // Restore the original scroll position (the topmost item that was visible when we were called) and the + // last selected item. + SetListScrollHPos (hTree, lastTopMostVisibleItem); + SelectItem (hTree, 0); +} + +static void PasswordChangeEnable (HWND hwndDlg, int button, int passwordId, BOOL keyFilesEnabled, + int newPasswordId, int newVerifyId, BOOL newKeyFilesEnabled) +{ + char password[MAX_PASSWORD + 1]; + char newPassword[MAX_PASSWORD + 1]; + char newVerify[MAX_PASSWORD + 1]; + wchar_t tmp[MAX_PASSWORD + 1]; + BOOL bEnable = TRUE; + int passwordUtf8Len, newPasswordUtf8Len, newVerifyUtf8Len; + + GetWindowText (GetDlgItem (hwndDlg, passwordId), tmp, ARRAYSIZE (tmp)); + passwordUtf8Len = WideCharToMultiByte (CP_UTF8, 0, tmp, -1, password, sizeof (password), NULL, NULL); + + if (pwdChangeDlgMode == PCDM_CHANGE_PKCS5_PRF) + newKeyFilesEnabled = keyFilesEnabled; + + switch (pwdChangeDlgMode) + { + case PCDM_REMOVE_ALL_KEYFILES_FROM_VOL: + case PCDM_ADD_REMOVE_VOL_KEYFILES: + case PCDM_CHANGE_PKCS5_PRF: + memcpy (newPassword, password, sizeof (newPassword)); + memcpy (newVerify, password, sizeof (newVerify)); + newPasswordUtf8Len = passwordUtf8Len; + newVerifyUtf8Len = passwordUtf8Len; + break; + + default: + GetWindowText (GetDlgItem (hwndDlg, newPasswordId), tmp, ARRAYSIZE (tmp)); + newPasswordUtf8Len = WideCharToMultiByte (CP_UTF8, 0, tmp, -1, newPassword, sizeof (newPassword), NULL, NULL); + GetWindowText (GetDlgItem (hwndDlg, newVerifyId), tmp, ARRAYSIZE (tmp)); + newVerifyUtf8Len = WideCharToMultiByte (CP_UTF8, 0, tmp, -1, newVerify, sizeof (newVerify), NULL, NULL); + + } + + if (passwordUtf8Len <= 0 || (!keyFilesEnabled && ((passwordUtf8Len - 1) < MIN_PASSWORD))) + bEnable = FALSE; + else if (strcmp (newPassword, newVerify) != 0) + bEnable = FALSE; + else if ((newPasswordUtf8Len <= 0) || (!newKeyFilesEnabled && ((newPasswordUtf8Len - 1) < MIN_PASSWORD))) + bEnable = FALSE; + + burn (password, sizeof (password)); + burn (newPassword, sizeof (newPassword)); + burn (newVerify, sizeof (newVerify)); + burn (tmp, sizeof (tmp)); + + EnableWindow (GetDlgItem (hwndDlg, button), bEnable); +} + +// implementation for support of change password operation in wait dialog mechanism + +typedef struct +{ + Password *oldPassword; + int old_pkcs5; + int old_pim; + Password *newPassword; + int pkcs5; + int pim; + int wipePassCount; + BOOL truecryptMode; + int* pnStatus; +} ChangePwdThreadParam; + +void CALLBACK ChangePwdWaitThreadProc(void* pArg, HWND hwndDlg) +{ + ChangePwdThreadParam* pThreadParam = (ChangePwdThreadParam*) pArg; + + if (bSysEncPwdChangeDlgMode) + { + // System + + try + { + VOLUME_PROPERTIES_STRUCT properties; + BootEncObj->GetVolumeProperties(&properties); + pThreadParam->old_pkcs5 = properties.pkcs5; + } + catch(...) + {} + + pThreadParam->pkcs5 = 0; // PKCS-5 PRF unchanged (currently we can't change PRF of system encryption) + + try + { + *pThreadParam->pnStatus = BootEncObj->ChangePassword (pThreadParam->oldPassword, pThreadParam->old_pkcs5, pThreadParam->old_pim, pThreadParam->newPassword, pThreadParam->pkcs5, pThreadParam->pim, pThreadParam->wipePassCount, hwndDlg); + } + catch (Exception &e) + { + e.Show (hwndDlg); + *(pThreadParam->pnStatus) = ERR_OS_ERROR; + } + } + else + { + // Non-system + + *pThreadParam->pnStatus = ChangePwd (szFileName, pThreadParam->oldPassword, pThreadParam->old_pkcs5, pThreadParam->old_pim, pThreadParam->truecryptMode, pThreadParam->newPassword, pThreadParam->pkcs5, pThreadParam->pim, pThreadParam->wipePassCount, hwndDlg); + + if (*pThreadParam->pnStatus == ERR_OS_ERROR + && GetLastError () == ERROR_ACCESS_DENIED + && IsUacSupported () + && IsVolumeDeviceHosted (szFileName)) + { + *pThreadParam->pnStatus = UacChangePwd (szFileName, pThreadParam->oldPassword, pThreadParam->old_pkcs5, pThreadParam->old_pim, pThreadParam->truecryptMode, pThreadParam->newPassword, pThreadParam->pkcs5, pThreadParam->pim, pThreadParam->wipePassCount, hwndDlg); + } + } +} + +// implementation for support of backup header operation in wait dialog mechanism + +typedef struct +{ + BOOL bRequireConfirmation; + wchar_t *lpszVolume; + size_t cchVolume; + int* iResult; +} BackupHeaderThreadParam; + +void CALLBACK BackupHeaderWaitThreadProc(void* pArg, HWND hwndDlg) +{ + BackupHeaderThreadParam* pThreadParam = (BackupHeaderThreadParam*) pArg; + + if (TranslateVolumeID (hwndDlg, pThreadParam->lpszVolume, pThreadParam->cchVolume)) + { + if (!IsAdmin () && IsUacSupported () && IsVolumeDeviceHosted (pThreadParam->lpszVolume)) + *(pThreadParam->iResult) = UacBackupVolumeHeader (hwndDlg, pThreadParam->bRequireConfirmation, pThreadParam->lpszVolume); + else + *(pThreadParam->iResult) = BackupVolumeHeader (hwndDlg, pThreadParam->bRequireConfirmation, pThreadParam->lpszVolume); + } + else + *(pThreadParam->iResult) = ERR_OS_ERROR; +} + +// implementation for support of restoring header operation in wait dialog mechanism + +typedef struct +{ + wchar_t *lpszVolume; + size_t cchVolume; + int* iResult; +} RestoreHeaderThreadParam; + +void CALLBACK RestoreHeaderWaitThreadProc(void* pArg, HWND hwndDlg) +{ + RestoreHeaderThreadParam* pThreadParam = (RestoreHeaderThreadParam*) pArg; + + if (TranslateVolumeID (hwndDlg, pThreadParam->lpszVolume, pThreadParam->cchVolume)) + { + if (!IsAdmin () && IsUacSupported () && IsVolumeDeviceHosted (pThreadParam->lpszVolume)) + *(pThreadParam->iResult) = UacRestoreVolumeHeader (hwndDlg, pThreadParam->lpszVolume); + else + *(pThreadParam->iResult) = RestoreVolumeHeader (hwndDlg, pThreadParam->lpszVolume); + } + else + *(pThreadParam->iResult) = ERR_OS_ERROR; +} + +/* Except in response to the WM_INITDIALOG message, the dialog box procedure + should return nonzero if it processes the message, and zero if it does + not. - see DialogProc */ +BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + static KeyFilesDlgParam newKeyFilesParam; + static BOOL PimValueChangedWarning = FALSE; + static int* NewPimValuePtr = NULL; + + WORD lw = LOWORD (wParam); + WORD hw = HIWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + LPARAM nIndex, nSelectedIndex = 0; + HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_OLD_PRF_ID); + int i; + WipeAlgorithmId headerWipeMode = TC_WIPE_3_DOD_5220; + int EffectiveVolumePkcs5 = CmdVolumePkcs5; + BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; + int EffectiveVolumePim = CmdVolumePim; + + /* Priority is given to command line parameters + * Default values used only when nothing specified in command line + */ + if (EffectiveVolumePkcs5 == 0) + EffectiveVolumePkcs5 = DefaultVolumePkcs5; + if (!EffectiveVolumeTrueCryptMode) + EffectiveVolumeTrueCryptMode = DefaultVolumeTrueCryptMode; + + NewPimValuePtr = (int*) lParam; + + PimValueChangedWarning = FALSE; + + ZeroMemory (&newKeyFilesParam, sizeof (newKeyFilesParam)); + if (NewPimValuePtr) + { + /* we are in the case of a volume. Store its name to use it in the key file dialog + * this will help avoid using the current container file as a key file + */ + StringCbCopyW (newKeyFilesParam.VolumeFileName, sizeof (newKeyFilesParam.VolumeFileName), szFileName); + } + + SetWindowTextW (hwndDlg, GetString ("IDD_PASSWORDCHANGE_DLG")); + LocalizeDialog (hwndDlg, "IDD_PASSWORDCHANGE_DLG"); + + SendMessage (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_VERIFY), EM_LIMITTEXT, MAX_PASSWORD, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_OLD_PIM), EM_LIMITTEXT, MAX_PIM, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, MAX_PIM, 0); + EnableWindow (GetDlgItem (hwndDlg, IDOK), FALSE); + + SetCheckBox (hwndDlg, IDC_ENABLE_KEYFILES, KeyFilesEnable); + EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEW_KEYFILES), TRUE); + + /* Add PRF algorithm list for current password */ + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + + nIndex = SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); + + for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) + { + nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); + if (i == EffectiveVolumePkcs5) + { + nSelectedIndex = nIndex; + } + } + + SendMessage (hComboBox, CB_SETCURSEL, nSelectedIndex, 0); + + /* check TrueCrypt Mode if it was set as default*/ + SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, EffectiveVolumeTrueCryptMode); + + /* set default PIM if set in the command line*/ + if (EffectiveVolumePim > 0) + { + SetCheckBox (hwndDlg, IDC_PIM_ENABLE, TRUE); + ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDT_OLD_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_OLD_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_OLD_PIM_HELP), SW_SHOW); + SetPim (hwndDlg, IDC_OLD_PIM, EffectiveVolumePim); + } + + /* Add PRF algorithm list for new password */ + hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + + nIndex = SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("UNCHANGED")); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); + + for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) + { + if (!HashIsDeprecated (i)) + { + nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); + } + } + + SendMessage (hComboBox, CB_SETCURSEL, 0, 0); + + PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), FALSE, FALSE, TRUE); + SelectAlgo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), (int *) &headerWipeMode); + + switch (pwdChangeDlgMode) + { + case PCDM_CHANGE_PKCS5_PRF: + SetWindowTextW (hwndDlg, GetString ("IDD_PCDM_CHANGE_PKCS5_PRF")); + LocalizeDialog (hwndDlg, "IDD_PCDM_CHANGE_PKCS5_PRF"); + EnableWindow (GetDlgItem (hwndDlg, IDC_PASSWORD), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_VERIFY), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEW_PIM_ENABLE), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_ENABLE_NEW_KEYFILES), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_NEW), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEW_KEYFILES), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_NEW_PASSWORD), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_CONFIRM_PASSWORD), FALSE); + break; + + case PCDM_ADD_REMOVE_VOL_KEYFILES: + SetWindowTextW (hwndDlg, GetString ("IDD_PCDM_ADD_REMOVE_VOL_KEYFILES")); + LocalizeDialog (hwndDlg, "IDD_PCDM_ADD_REMOVE_VOL_KEYFILES"); + newKeyFilesParam.EnableKeyFiles = TRUE; + EnableWindow (GetDlgItem (hwndDlg, IDC_PASSWORD), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_VERIFY), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEW_PIM_ENABLE), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_NEW), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_NEW_PASSWORD), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_CONFIRM_PASSWORD), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_NEW_PKCS5_PRF), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), FALSE); + break; + + case PCDM_REMOVE_ALL_KEYFILES_FROM_VOL: + newKeyFilesParam.EnableKeyFiles = FALSE; + SetWindowTextW (hwndDlg, GetString ("IDD_PCDM_REMOVE_ALL_KEYFILES_FROM_VOL")); + LocalizeDialog (hwndDlg, "IDD_PCDM_REMOVE_ALL_KEYFILES_FROM_VOL"); + KeyFilesEnable = TRUE; + SetCheckBox (hwndDlg, IDC_ENABLE_KEYFILES, TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_ENABLE_KEYFILES), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PASSWORD), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_VERIFY), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEW_PIM_ENABLE), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_ENABLE_NEW_KEYFILES), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_NEW), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEW_KEYFILES), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_NEW_PASSWORD), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_CONFIRM_PASSWORD), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_NEW_PKCS5_PRF), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), FALSE); + break; + + case PCDM_CHANGE_PASSWORD: + default: + // NOP + break; + }; + + if (bSysEncPwdChangeDlgMode) + { + /* No support for changing the password of TrueCrypt system partition */ + SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE); + + ToBootPwdField (hwndDlg, IDC_PASSWORD); + ToBootPwdField (hwndDlg, IDC_VERIFY); + ToBootPwdField (hwndDlg, IDC_OLD_PASSWORD); + + if ((DWORD) GetKeyboardLayout (NULL) != 0x00000409 && (DWORD) GetKeyboardLayout (NULL) != 0x04090409) + { + DWORD keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); + + if (keybLayout != 0x00000409 && keybLayout != 0x04090409) + { + Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 0; + } + + bKeyboardLayoutChanged = TRUE; + } + + + /* for system encryption, we can't change the PRF */ + EnableWindow (GetDlgItem (hwndDlg, IDT_PKCS5_PRF), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDT_NEW_PKCS5_PRF), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PKCS5_OLD_PRF_ID), FALSE); + + if (SetTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0) + { + Error ("CANNOT_SET_TIMER", hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 0; + } + + newKeyFilesParam.EnableKeyFiles = FALSE; + KeyFilesEnable = FALSE; + SetCheckBox (hwndDlg, IDC_ENABLE_KEYFILES, FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_ENABLE_KEYFILES), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_ENABLE_NEW_KEYFILES), FALSE); + } + + CheckCapsLock (hwndDlg, FALSE); + + return 0; + } + + case WM_TIMER: + switch (wParam) + { + case TIMER_ID_KEYB_LAYOUT_GUARD: + if (bSysEncPwdChangeDlgMode) + { + DWORD keybLayout = (DWORD) GetKeyboardLayout (NULL); + + /* Watch the keyboard layout */ + + if (keybLayout != 0x00000409 && keybLayout != 0x04090409) + { + // Keyboard layout is not standard US + + // Attempt to wipe passwords stored in the input field buffers + wchar_t tmp[MAX_PASSWORD+1]; + wmemset (tmp, L'X', MAX_PASSWORD); + tmp [MAX_PASSWORD] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), tmp); + + SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), L""); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), L""); + SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), L""); + + keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); + + if (keybLayout != 0x00000409 && keybLayout != 0x04090409) + { + KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); + Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + bKeyboardLayoutChanged = TRUE; + + wchar_t szTmp [4096]; + StringCbCopyW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_CHANGE_PREVENTED")); + StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); + StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION")); + MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); + } + + + /* Watch the right Alt key (which is used to enter various characters on non-US keyboards) */ + + if (bKeyboardLayoutChanged && !bKeybLayoutAltKeyWarningShown) + { + if (GetAsyncKeyState (VK_RMENU) < 0) + { + bKeybLayoutAltKeyWarningShown = TRUE; + + wchar_t szTmp [4096]; + StringCbCopyW (szTmp, sizeof(szTmp), GetString ("ALT_KEY_CHARS_NOT_FOR_SYS_ENCRYPTION")); + StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); + StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION")); + MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TOPMOST); + } + } + } + return 1; + } + return 0; + + case WM_CTLCOLORSTATIC: + { + if (PimValueChangedWarning && ((HWND)lParam == GetDlgItem(hwndDlg, IDC_PIM_HELP)) ) + { + // we're about to draw the static + // set the text colour in (HDC)lParam + SetBkMode((HDC)wParam,TRANSPARENT); + SetTextColor((HDC)wParam, RGB(255,0,0)); + // NOTE: per documentation as pointed out by selbie, GetSolidBrush would leak a GDI handle. + return (BOOL)GetSysColorBrush(COLOR_MENU); + } + } + return 0; + + case WM_COMMAND: + if (lw == IDCANCEL) + { + // Attempt to wipe passwords stored in the input field buffers + wchar_t tmp[MAX_PASSWORD+1]; + wmemset (tmp, L'X', MAX_PASSWORD); + tmp[MAX_PASSWORD] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), tmp); + RestoreDefaultKeyFilesParam (); + + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + if (hw == EN_CHANGE) + { + PasswordChangeEnable (hwndDlg, IDOK, + IDC_OLD_PASSWORD, + KeyFilesEnable && FirstKeyFile != NULL, + IDC_PASSWORD, IDC_VERIFY, + newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); + + if ((lw == IDC_OLD_PIM) && IsWindowEnabled (GetDlgItem (hwndDlg, IDC_PIM))) + { + wchar_t tmp[MAX_PIM+1] = {0}; + GetDlgItemText (hwndDlg, IDC_OLD_PIM, tmp, MAX_PIM + 1); + SetDlgItemText (hwndDlg, IDC_PIM, tmp); + } + + if (lw == IDC_PIM) + { + if(GetPim (hwndDlg, IDC_OLD_PIM) != GetPim (hwndDlg, IDC_PIM)) + { + PimValueChangedWarning = TRUE; + SetDlgItemTextW (hwndDlg, IDC_PIM_HELP, GetString (bSysEncPwdChangeDlgMode? "PIM_SYSENC_CHANGE_WARNING" : "PIM_CHANGE_WARNING")); + } + else + { + PimValueChangedWarning = FALSE; + SetDlgItemTextW (hwndDlg, IDC_PIM_HELP, (wchar_t *) GetDictionaryValueByInt (IDC_PIM_HELP)); + } + } + + return 1; + } + + if (lw == IDC_PIM_ENABLE) + { + ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDT_OLD_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_OLD_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_OLD_PIM_HELP), SW_SHOW); + + // check also the "Use PIM" for the new password if it is enabled + if (IsWindowEnabled (GetDlgItem (hwndDlg, IDC_NEW_PIM_ENABLE))) + { + SetCheckBox (hwndDlg, IDC_NEW_PIM_ENABLE, TRUE); + + ShowWindow (GetDlgItem (hwndDlg, IDC_NEW_PIM_ENABLE), SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); + } + + SetFocus (GetDlgItem (hwndDlg, IDC_OLD_PIM)); + + return 1; + } + + if (lw == IDC_NEW_PIM_ENABLE) + { + ShowWindow (GetDlgItem (hwndDlg, IDC_NEW_PIM_ENABLE), SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); + + SetFocus (GetDlgItem (hwndDlg, IDC_PIM)); + + return 1; + } + + if (lw == IDC_KEYFILES) + { + if (bSysEncPwdChangeDlgMode) + { + Warning ("KEYFILES_NOT_SUPPORTED_FOR_SYS_ENCRYPTION", hwndDlg); + return 1; + } + + KeyFilesDlgParam param; + param.EnableKeyFiles = KeyFilesEnable; + param.FirstKeyFile = FirstKeyFile; + + if (IDOK == DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, + (DLGPROC) KeyFilesDlgProc, (LPARAM) ¶m)) + { + KeyFilesEnable = param.EnableKeyFiles; + FirstKeyFile = param.FirstKeyFile; + + SetCheckBox (hwndDlg, IDC_ENABLE_KEYFILES, KeyFilesEnable); + } + + PasswordChangeEnable (hwndDlg, IDOK, + IDC_OLD_PASSWORD, + KeyFilesEnable && FirstKeyFile != NULL, + IDC_PASSWORD, IDC_VERIFY, + newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); + + return 1; + } + + + if (lw == IDC_NEW_KEYFILES) + { + if (bSysEncPwdChangeDlgMode) + { + Warning ("KEYFILES_NOT_SUPPORTED_FOR_SYS_ENCRYPTION", hwndDlg); + return 1; + } + + if (IDOK == DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, + (DLGPROC) KeyFilesDlgProc, (LPARAM) &newKeyFilesParam)) + { + SetCheckBox (hwndDlg, IDC_ENABLE_NEW_KEYFILES, newKeyFilesParam.EnableKeyFiles); + + VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (hwndDlg, IDOK), GetDlgItem (hwndDlg, IDC_PASSWORD), + GetDlgItem (hwndDlg, IDC_VERIFY), NULL, NULL, + newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); + } + + PasswordChangeEnable (hwndDlg, IDOK, + IDC_OLD_PASSWORD, + KeyFilesEnable && FirstKeyFile != NULL, + IDC_PASSWORD, IDC_VERIFY, + newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); + + return 1; + } + + if (lw == IDC_ENABLE_KEYFILES) + { + KeyFilesEnable = GetCheckBox (hwndDlg, IDC_ENABLE_KEYFILES); + + PasswordChangeEnable (hwndDlg, IDOK, + IDC_OLD_PASSWORD, + KeyFilesEnable && FirstKeyFile != NULL, + IDC_PASSWORD, IDC_VERIFY, + newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); + + return 1; + } + + if (lw == IDC_ENABLE_NEW_KEYFILES) + { + newKeyFilesParam.EnableKeyFiles = GetCheckBox (hwndDlg, IDC_ENABLE_NEW_KEYFILES); + + PasswordChangeEnable (hwndDlg, IDOK, + IDC_OLD_PASSWORD, + KeyFilesEnable && FirstKeyFile != NULL, + IDC_PASSWORD, IDC_VERIFY, + newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); + + return 1; + } + + if (hw == CBN_SELCHANGE) + { + switch (lw) + { + case IDC_PKCS5_PRF_ID: + if (bSysEncPwdChangeDlgMode) + { + int new_hash_algo_id = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, + SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); + + if (new_hash_algo_id != 0 && !HashForSystemEncryption(new_hash_algo_id)) + { + int new_hash_algo_id = DEFAULT_HASH_ALGORITHM_BOOT; + Info ("ALGO_NOT_SUPPORTED_FOR_SYS_ENCRYPTION", hwndDlg); + SelectAlgo (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), &new_hash_algo_id); + } + } + break; + } + return 1; + + } + + if (lw == IDC_TRUECRYPT_MODE) + { + BOOL bEnablePim = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE) ? FALSE: TRUE; + EnableWindow (GetDlgItem (hwndDlg, IDT_OLD_PIM), bEnablePim); + EnableWindow (GetDlgItem (hwndDlg, IDC_OLD_PIM), bEnablePim); + EnableWindow (GetDlgItem (hwndDlg, IDC_OLD_PIM_HELP), bEnablePim); + } + + if (lw == IDC_SHOW_PASSWORD_CHPWD_ORI) + { + HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_ORI, IDC_OLD_PASSWORD, IDC_OLD_PIM); + return 1; + } + + if (lw == IDC_SHOW_PASSWORD_CHPWD_NEW) + { + HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_NEW, IDC_PASSWORD, IDC_VERIFY); + HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_NEW, IDC_PIM, 0); + return 1; + } + + if (lw == IDOK) + { + HWND hParent = GetParent (hwndDlg); + Password oldPassword; + Password newPassword; + WipeAlgorithmId headerWiperMode = (WipeAlgorithmId) SendMessage ( + GetDlgItem (hwndDlg, IDC_WIPE_MODE), + CB_GETITEMDATA, + SendMessage (GetDlgItem (hwndDlg, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), + 0); + int nStatus; + int old_pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_OLD_PRF_ID), CB_GETITEMDATA, + SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_OLD_PRF_ID), CB_GETCURSEL, 0, 0), 0); + int pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, + SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); + BOOL truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); + + int old_pim = GetPim (hwndDlg, IDC_OLD_PIM); + int pim = GetPim (hwndDlg, IDC_PIM); + + if (truecryptMode && (old_pkcs5 == SHA256)) + { + Error ("ALGO_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); + return 1; + } + else if (truecryptMode && (old_pim != 0)) + { + Error ("PIM_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); + return 1; + } + + if (bSysEncPwdChangeDlgMode && !CheckPasswordCharEncoding (GetDlgItem (hwndDlg, IDC_PASSWORD), NULL)) + { + Error ("UNSUPPORTED_CHARS_IN_PWD", hwndDlg); + return 1; + } + + if (bSysEncPwdChangeDlgMode && (pim > MAX_BOOT_PIM_VALUE)) + { + SetFocus (GetDlgItem(hwndDlg, IDC_PIM)); + Error ("PIM_SYSENC_TOO_BIG", hwndDlg); + return 1; + } + + if (!bSysEncPwdChangeDlgMode && (pim > MAX_PIM_VALUE)) + { + SetFocus (GetDlgItem(hwndDlg, IDC_PIM)); + Error ("PIM_TOO_BIG", hwndDlg); + return 1; + } + + if (pwdChangeDlgMode == PCDM_CHANGE_PKCS5_PRF) + { + newKeyFilesParam.EnableKeyFiles = KeyFilesEnable; + } + else if (!(newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL) + && pwdChangeDlgMode == PCDM_CHANGE_PASSWORD) + { + if (!CheckPasswordLength (hwndDlg, GetWindowTextLength(GetDlgItem (hwndDlg, IDC_PASSWORD)), pim, bSysEncPwdChangeDlgMode, FALSE, FALSE)) + return 1; + } + + GetVolumePath (hParent, szFileName, ARRAYSIZE (szFileName)); + + if (GetPassword (hwndDlg, IDC_OLD_PASSWORD, (LPSTR) oldPassword.Text, sizeof (oldPassword.Text), TRUE)) + oldPassword.Length = (unsigned __int32) strlen ((char *) oldPassword.Text); + else + { + return 1; + } + + switch (pwdChangeDlgMode) + { + case PCDM_REMOVE_ALL_KEYFILES_FROM_VOL: + case PCDM_ADD_REMOVE_VOL_KEYFILES: + case PCDM_CHANGE_PKCS5_PRF: + memcpy (newPassword.Text, oldPassword.Text, sizeof (newPassword.Text)); + newPassword.Length = (unsigned __int32) strlen ((char *) oldPassword.Text); + pim = old_pim; + break; + + default: + if (GetPassword (hwndDlg, IDC_PASSWORD, (LPSTR) newPassword.Text, sizeof (newPassword.Text), TRUE)) + newPassword.Length = (unsigned __int32) strlen ((char *) newPassword.Text); + else + return 1; + } + + WaitCursor (); + + if (KeyFilesEnable) + KeyFilesApply (hwndDlg, &oldPassword, FirstKeyFile, szFileName); + + if (newKeyFilesParam.EnableKeyFiles) + { + if (!KeyFilesApply (hwndDlg, &newPassword, pwdChangeDlgMode == PCDM_CHANGE_PKCS5_PRF ? FirstKeyFile : newKeyFilesParam.FirstKeyFile, szFileName)) + { + nStatus = ERR_DONT_REPORT; + goto err; + } + } + + ChangePwdThreadParam changePwdParam; + changePwdParam.oldPassword = &oldPassword; + changePwdParam.old_pkcs5 = old_pkcs5; + changePwdParam.old_pim = old_pim; + changePwdParam.newPassword = &newPassword; + changePwdParam.pkcs5 = pkcs5; + changePwdParam.pim = pim; + changePwdParam.wipePassCount = GetWipePassCount(headerWiperMode); + changePwdParam.pnStatus = &nStatus; + changePwdParam.truecryptMode = truecryptMode; + + ShowWaitDialog(hwndDlg, TRUE, ChangePwdWaitThreadProc, &changePwdParam); + +err: + // notify the caller in case the PIM has changed + if (NewPimValuePtr) + { + if (pim != old_pim) + *NewPimValuePtr = pim; + else + *NewPimValuePtr = -1; + } + + burn (&oldPassword, sizeof (oldPassword)); + burn (&newPassword, sizeof (newPassword)); + burn (&old_pim, sizeof(old_pim)); + burn (&pim, sizeof(pim)); + + NormalCursor (); + + if (nStatus == 0) + { + // Attempt to wipe passwords stored in the input field buffers + wchar_t tmp[MAX_PASSWORD+1]; + wmemset (tmp, L'X', MAX_PASSWORD); + tmp[MAX_PASSWORD] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), tmp); + + KeyFileRemoveAll (&newKeyFilesParam.FirstKeyFile); + RestoreDefaultKeyFilesParam (); + + if (bSysEncPwdChangeDlgMode) + { + KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); + } + + EndDialog (hwndDlg, IDOK); + } + return 1; + } + return 0; + } + + return 0; +} + +static wchar_t PasswordDlgVolume[MAX_PATH + 1]; +static BOOL PasswordDialogDisableMountOptions; +static char *PasswordDialogTitleStringId; + +/* Except in response to the WM_INITDIALOG message, the dialog box procedure + should return nonzero if it processes the message, and zero if it does + not. - see DialogProc */ +BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + static Password *szXPwd; + static int *pkcs5; + static int *pim; + static BOOL* truecryptMode; + + switch (msg) + { + case WM_INITDIALOG: + { + int i, nIndex, defaultPrfIndex = 0; + szXPwd = ((PasswordDlgParam *) lParam) -> password; + pkcs5 = ((PasswordDlgParam *) lParam) -> pkcs5; + pim = ((PasswordDlgParam *) lParam) -> pim; + truecryptMode = ((PasswordDlgParam *) lParam) -> truecryptMode; + LocalizeDialog (hwndDlg, "IDD_PASSWORD_DLG"); + DragAcceptFiles (hwndDlg, TRUE); + + if (PasswordDialogTitleStringId) + { + SetWindowTextW (hwndDlg, GetString (PasswordDialogTitleStringId)); + } + else if (wcslen (PasswordDlgVolume) > 0) + { + wchar_t s[1024]; + RECT rect; + GetWindowRect (hwndDlg, &rect); + + bool useInExplorer = false; + wstring label = GetFavoriteVolumeLabel (PasswordDlgVolume, useInExplorer); + if (!label.empty()) + { + StringCbPrintfW (s, sizeof(s), GetString ("ENTER_PASSWORD_FOR_LABEL"), label.c_str()); + if (useInExplorer) + StringCbCopyW (mountOptions.Label, sizeof (mountOptions.Label), label.c_str()); + } + else + { + StringCbPrintfW (s, sizeof(s), GetString ("ENTER_PASSWORD_FOR"), L"___"); + StringCbPrintfW (s, sizeof(s), GetString ("ENTER_PASSWORD_FOR"), FitPathInGfxWidth (hwndDlg, WindowTitleBarFont, rect.right - rect.left - GetTextGfxWidth (hwndDlg, s, WindowTitleBarFont), PasswordDlgVolume).c_str()); + } + + SetWindowTextW (hwndDlg, s); + } + + /* Populate the PRF algorithms list */ + HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + + nIndex = (int) SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); + + for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) + { + nIndex = (int) SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); + if (*pkcs5 && (*pkcs5 == i)) + defaultPrfIndex = nIndex; + } + + /* make autodetection the default unless a specific PRF was specified in the command line */ + SendMessage (hComboBox, CB_SETCURSEL, defaultPrfIndex, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_CACHE), BM_SETCHECK, bCacheInDriver ? BST_CHECKED:BST_UNCHECKED, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, MAX_PIM, 0); + + SetPim (hwndDlg, IDC_PIM, *pim); + + /* make PIM field visible if a PIM value has been explicitely specified */ + if (*pim > 0) + { + SetCheckBox (hwndDlg, IDC_PIM_ENABLE, TRUE); + ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); + } + + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); + + mountOptions.PartitionInInactiveSysEncScope = bPrebootPasswordDlgMode; + + if (bPrebootPasswordDlgMode) + { + SendMessage (hwndDlg, TC_APPMSG_PREBOOT_PASSWORD_MODE, 0, 0); + } + + if (PasswordDialogDisableMountOptions) + { + EnableWindow (GetDlgItem (hwndDlg, IDC_CACHE), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_MOUNT_OPTIONS), FALSE); + /* Disable TrueCrypt mode option in case of backup/restore header operation */ + SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE); + } + else if (*truecryptMode) + { + /* Check TrueCryptMode if it is enabled on the command line */ + SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, TRUE); + } + + if (!SetForegroundWindow (hwndDlg) && (FavoriteMountOnArrivalInProgress || LogOn)) + { + SetWindowPos (hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + + FLASHWINFO flash; + flash.cbSize = sizeof (flash); + flash.dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG; + flash.dwTimeout = 0; + flash.hwnd = hwndDlg; + flash.uCount = 0; + + FlashWindowEx (&flash); + + SetWindowPos (hwndDlg, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + } + } + return 0; + + case TC_APPMSG_PREBOOT_PASSWORD_MODE: + { + /* Repopulate the PRF algorithms list with algorithms that support system encryption */ + HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + + int i, defaultPrfIndex = 0, nIndex = (int) SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); + + for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) + { + if (HashForSystemEncryption(i)) + { + nIndex = (int) SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); + if (*pkcs5 && (*pkcs5 == i)) + defaultPrfIndex = nIndex; + } + } + + /* make autodetection the default unless a specific PRF was specified in the command line */ + SendMessage (hComboBox, CB_SETCURSEL, defaultPrfIndex, 0); + + ToBootPwdField (hwndDlg, IDC_PASSWORD); + + // Attempt to wipe the password stored in the input field buffer + wchar_t tmp[MAX_PASSWORD+1]; + wmemset (tmp, L'X', MAX_PASSWORD); + tmp [MAX_PASSWORD] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), L""); + + StringCbPrintfW (OrigKeyboardLayout, sizeof(OrigKeyboardLayout),L"%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF); + + DWORD keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); + + if (keybLayout != 0x00000409 && keybLayout != 0x04090409) + { + Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + if (SetTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0) + { + Error ("CANNOT_SET_TIMER", hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + if (GetCheckBox (hwndDlg, IDC_SHOW_PASSWORD)) + { + // simulate hiding password + SetCheckBox (hwndDlg, IDC_SHOW_PASSWORD, FALSE); + + HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD, IDC_PASSWORD, IDC_PIM); + } + + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_ENABLE), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_KEY_FILES), FALSE); + + SetPim (hwndDlg, IDC_PIM, *pim); + + bPrebootPasswordDlgMode = TRUE; + } + return 1; + + case WM_TIMER: + switch (wParam) + { + case TIMER_ID_KEYB_LAYOUT_GUARD: + if (bPrebootPasswordDlgMode) + { + DWORD keybLayout = (DWORD) GetKeyboardLayout (NULL); + + if (keybLayout != 0x00000409 && keybLayout != 0x04090409) + { + // Keyboard layout is not standard US + + // Attempt to wipe the password stored in the input field buffer + wchar_t tmp[MAX_PASSWORD+1]; + wmemset (tmp, L'X', MAX_PASSWORD); + tmp [MAX_PASSWORD] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), L""); + + keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE); + + if (keybLayout != 0x00000409 && keybLayout != 0x04090409) + { + KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); + Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + wchar_t szTmp [4096]; + StringCbCopyW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_CHANGE_PREVENTED")); + StringCbCatW (szTmp, sizeof(szTmp), L"\n\n"); + StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION")); + MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); + } + } + return 1; + } + return 0; + + case WM_COMMAND: + + if (lw == IDC_MOUNT_OPTIONS) + { + /* Use default PRF specified by the user if any */ + if (mountOptions.ProtectedHidVolPkcs5Prf == 0) + mountOptions.ProtectedHidVolPkcs5Prf = *pkcs5; + if (mountOptions.ProtectedHidVolPim == 0) + mountOptions.ProtectedHidVolPim = *pim; + DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, + (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions); + + if (!bPrebootPasswordDlgMode && mountOptions.PartitionInInactiveSysEncScope) + SendMessage (hwndDlg, TC_APPMSG_PREBOOT_PASSWORD_MODE, 0, 0); + + return 1; + } + + if (lw == IDC_PIM_ENABLE) + { + ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); + + SetFocus (GetDlgItem (hwndDlg, IDC_PIM)); + return 1; + } + + if (lw == IDC_SHOW_PASSWORD) + { + HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD, IDC_PASSWORD, IDC_PIM); + return 1; + } + + if (lw == IDC_TRUECRYPT_MODE) + { + BOOL bEnablePim = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE) ? FALSE: TRUE; + EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), bEnablePim); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), bEnablePim); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), bEnablePim); + } + + if (lw == IDC_KEY_FILES) + { + KeyFilesDlgParam param; + param.EnableKeyFiles = KeyFilesEnable; + param.FirstKeyFile = FirstKeyFile; + + if (IDOK == DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, + (DLGPROC) KeyFilesDlgProc, (LPARAM) ¶m)) + { + KeyFilesEnable = param.EnableKeyFiles; + FirstKeyFile = param.FirstKeyFile; + + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); + } + + return 1; + } + + if (lw == IDC_KEYFILES_ENABLE) + { + KeyFilesEnable = GetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE); + + return 1; + } + + if (lw == IDCANCEL || lw == IDOK) + { + wchar_t tmp[MAX_PASSWORD+1]; + + if (lw == IDOK) + { + if (mountOptions.ProtectHiddenVolume && hidVolProtKeyFilesParam.EnableKeyFiles) + KeyFilesApply (hwndDlg, &mountOptions.ProtectedHidVolPassword, hidVolProtKeyFilesParam.FirstKeyFile, wcslen (PasswordDlgVolume) > 0 ? PasswordDlgVolume : NULL); + + if (GetPassword (hwndDlg, IDC_PASSWORD, (LPSTR) szXPwd->Text, MAX_PASSWORD + 1, TRUE)) + szXPwd->Length = (unsigned __int32) strlen ((char *) szXPwd->Text); + else + return 1; + + bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_CACHE)); + *pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); + *truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); + + *pim = GetPim (hwndDlg, IDC_PIM); + + /* SHA-256 is not supported by TrueCrypt */ + if ( (*truecryptMode) + && ((*pkcs5 == SHA256) || (mountOptions.ProtectHiddenVolume && mountOptions.ProtectedHidVolPkcs5Prf == SHA256)) + ) + { + Error ("ALGO_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); + return 1; + } + + if ( (*truecryptMode) + && (*pim != 0) + ) + { + Error ("PIM_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); + return 1; + } + } + + // Attempt to wipe password stored in the input field buffer + wmemset (tmp, L'X', MAX_PASSWORD); + tmp[MAX_PASSWORD] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); + + if (hidVolProtKeyFilesParam.FirstKeyFile != NULL) + { + KeyFileRemoveAll (&hidVolProtKeyFilesParam.FirstKeyFile); + hidVolProtKeyFilesParam.EnableKeyFiles = FALSE; + } + + if (bPrebootPasswordDlgMode) + { + KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); + + // Restore the original keyboard layout + if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) + Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); + } + + EndDialog (hwndDlg, lw); + return 1; + } + return 0; + + case WM_CONTEXTMENU: + { + RECT buttonRect; + GetWindowRect (GetDlgItem (hwndDlg, IDC_KEY_FILES), &buttonRect); + + if (LOWORD (lParam) >= buttonRect.left && LOWORD (lParam) <= buttonRect.right + && HIWORD (lParam) >= buttonRect.top && HIWORD (lParam) <= buttonRect.bottom) + { + // The "Keyfiles" button has been right-clicked + + KeyFilesDlgParam param; + param.EnableKeyFiles = KeyFilesEnable; + param.FirstKeyFile = FirstKeyFile; + + POINT popupPos; + popupPos.x = buttonRect.left + 2; + popupPos.y = buttonRect.top + 2; + + if (KeyfilesPopupMenu (hwndDlg, popupPos, ¶m)) + { + KeyFilesEnable = param.EnableKeyFiles; + FirstKeyFile = param.FirstKeyFile; + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); + } + } + } + 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)); + FirstKeyFile = KeyFileAdd (FirstKeyFile, kf); + KeyFilesEnable = TRUE; + } + } + + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable); + DragFinish (hdrop); + } + return 1; + } + + return 0; +} + +static void PreferencesDlgEnableButtons (HWND hwndDlg) +{ + BOOL back = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_BKG_TASK_ENABLE)); + BOOL idle = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE)); + BOOL installed = !IsNonInstallMode(); + BOOL wtsEnabled = (hWtsLib != NULL) ? TRUE : FALSE; + + EnableWindow (GetDlgItem (hwndDlg, IDC_CLOSE_BKG_TASK_WHEN_NOVOL), back && installed); + EnableWindow (GetDlgItem (hwndDlg, IDT_LOGON), installed); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_LOGON_START), back && installed); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_LOGON_MOUNT_DEVICES), installed); + EnableWindow (GetDlgItem (hwndDlg, IDT_AUTO_DISMOUNT), back); + EnableWindow (GetDlgItem (hwndDlg, IDT_AUTO_DISMOUNT_ON), back); + EnableWindow (GetDlgItem (hwndDlg, IDT_MINUTES), back); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_LOGOFF), back); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SESSION_LOCKED), back && wtsEnabled); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_POWERSAVING), back); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SCREENSAVER), back); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE), back); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE_TIME), back && idle); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT), back); +} + +BOOL CALLBACK PreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + static BOOL PreferencesDialogActive = FALSE; + static HWND ActivePreferencesDialogWindow; + + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + if (PreferencesDialogActive) + { + ShowWindow (ActivePreferencesDialogWindow, SW_SHOW); + SetForegroundWindow (ActivePreferencesDialogWindow); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + ActivePreferencesDialogWindow = hwndDlg; + PreferencesDialogActive = TRUE; + + LocalizeDialog (hwndDlg, "IDD_PREFERENCES_DLG"); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_OPEN_EXPLORER), BM_SETCHECK, + bExplore ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_USE_DIFF_TRAY_ICON_IF_VOL_MOUNTED), BM_SETCHECK, + bUseDifferentTrayIconIfVolMounted ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PRESERVE_TIMESTAMPS), BM_SETCHECK, + defaultMountOptions.PreserveTimestamp ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_SHOW_DISCONNECTED_NETWORK_DRIVES), BM_SETCHECK, + bShowDisconnectedNetworkDrives ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_HIDE_WAITING_DIALOG), BM_SETCHECK, + bHideWaitingDialog ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT), BM_SETCHECK, + bCacheDuringMultipleMount ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_EXIT), BM_SETCHECK, + bWipeCacheOnExit ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_AUTODISMOUNT), BM_SETCHECK, + bWipeCacheOnAutoDismount ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PASSWORDS), BM_SETCHECK, + bCacheInDriver ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PIM), BM_SETCHECK, + bIncludePimInCache? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_READONLY), BM_SETCHECK, + defaultMountOptions.ReadOnly ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_REMOVABLE), BM_SETCHECK, + defaultMountOptions.Removable ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_LOGON_START), BM_SETCHECK, + bStartOnLogon ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_LOGON_MOUNT_DEVICES), BM_SETCHECK, + bMountDevicesOnLogon ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_BKG_TASK_ENABLE), BM_SETCHECK, + bEnableBkgTask ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_CLOSE_BKG_TASK_WHEN_NOVOL), BM_SETCHECK, + bCloseBkgTaskWhenNoVolumes || IsNonInstallMode() ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_LOGOFF), BM_SETCHECK, + bDismountOnLogOff ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SESSION_LOCKED), BM_SETCHECK, + bDismountOnSessionLocked ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_POWERSAVING), BM_SETCHECK, + bDismountOnPowerSaving ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SCREENSAVER), BM_SETCHECK, + bDismountOnScreenSaver ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT), BM_SETCHECK, + bForceAutoDismount ? BST_CHECKED:BST_UNCHECKED, 0); + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE), BM_SETCHECK, + MaxVolumeIdleTime > 0 ? BST_CHECKED:BST_UNCHECKED, 0); + + SetDlgItemInt (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE_TIME, abs (MaxVolumeIdleTime), FALSE); + + PreferencesDlgEnableButtons (hwndDlg); + } + return 0; + + case WM_COMMAND: + + if (lw == IDC_PREF_BKG_TASK_ENABLE && !IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_BKG_TASK_ENABLE))) + { + if (AskWarnNoYes ("CONFIRM_BACKGROUND_TASK_DISABLED", hwndDlg) == IDNO) + SetCheckBox (hwndDlg, IDC_PREF_BKG_TASK_ENABLE, TRUE); + } + + // Forced dismount disabled warning + if (lw == IDC_PREF_DISMOUNT_INACTIVE + || lw == IDC_PREF_DISMOUNT_LOGOFF + || lw == IDC_PREF_DISMOUNT_SESSION_LOCKED + || lw == IDC_PREF_DISMOUNT_POWERSAVING + || lw == IDC_PREF_DISMOUNT_SCREENSAVER + || lw == IDC_PREF_FORCE_AUTO_DISMOUNT) + { + BOOL i = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE)); + BOOL l = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_LOGOFF)); + BOOL sl = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SESSION_LOCKED)); + BOOL p = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_POWERSAVING)); + BOOL s = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SCREENSAVER)); + BOOL q = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT)); + + if (!q) + { + if (lw == IDC_PREF_FORCE_AUTO_DISMOUNT && (i || l || sl || p || s)) + { + if (AskWarnNoYes ("CONFIRM_NO_FORCED_AUTODISMOUNT", hwndDlg) == IDNO) + SetCheckBox (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT, TRUE); + } + else if ((lw == IDC_PREF_DISMOUNT_INACTIVE && i + || lw == IDC_PREF_DISMOUNT_LOGOFF && l + || lw == IDC_PREF_DISMOUNT_SESSION_LOCKED && sl + || lw == IDC_PREF_DISMOUNT_POWERSAVING && p + || lw == IDC_PREF_DISMOUNT_SCREENSAVER && s)) + Warning ("WARN_PREF_AUTO_DISMOUNT", hwndDlg); + } + + if (p && lw == IDC_PREF_DISMOUNT_POWERSAVING) + Warning ("WARN_PREF_AUTO_DISMOUNT_ON_POWER", hwndDlg); + } + + if (lw == IDCANCEL) + { + PreferencesDialogActive = FALSE; + EndDialog (hwndDlg, lw); + return 1; + } + + if (lw == IDOK) + { + WaitCursor (); + + bExplore = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_OPEN_EXPLORER)); + bUseDifferentTrayIconIfVolMounted = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_USE_DIFF_TRAY_ICON_IF_VOL_MOUNTED)); + bPreserveTimestamp = defaultMountOptions.PreserveTimestamp = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PRESERVE_TIMESTAMPS)); + bShowDisconnectedNetworkDrives = IsButtonChecked (GetDlgItem (hwndDlg, IDC_SHOW_DISCONNECTED_NETWORK_DRIVES)); + bHideWaitingDialog = IsButtonChecked (GetDlgItem (hwndDlg, IDC_HIDE_WAITING_DIALOG)); + bCacheDuringMultipleMount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT)); + bWipeCacheOnExit = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_EXIT)); + bWipeCacheOnAutoDismount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_AUTODISMOUNT)); + bCacheInDriverDefault = bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PASSWORDS)); + bIncludePimInCache = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PIM)); + defaultMountOptions.ReadOnly = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_READONLY)); + defaultMountOptions.Removable = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_REMOVABLE)); + bEnableBkgTask = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_BKG_TASK_ENABLE)); + bCloseBkgTaskWhenNoVolumes = IsNonInstallMode() ? bCloseBkgTaskWhenNoVolumes : IsButtonChecked (GetDlgItem (hwndDlg, IDC_CLOSE_BKG_TASK_WHEN_NOVOL)); + bDismountOnLogOff = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_LOGOFF)); + bDismountOnSessionLocked = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SESSION_LOCKED)); + bDismountOnPowerSaving = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_POWERSAVING)); + bDismountOnScreenSaver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SCREENSAVER)); + bForceAutoDismount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT)); + MaxVolumeIdleTime = GetDlgItemInt (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE_TIME, NULL, FALSE) + * (IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE)) ? 1 : -1); + bStartOnLogon = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_LOGON_START)); + bMountDevicesOnLogon = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_LOGON_MOUNT_DEVICES)); + + ManageStartupSeq (); + + SaveSettings (hwndDlg); + + NormalCursor (); + + PreferencesDialogActive = FALSE; + EndDialog (hwndDlg, lw); + return 1; + } + + if (lw == IDC_MORE_SETTINGS) + { + HMENU popup = CreatePopupMenu (); + if (popup) + { + AppendMenuW (popup, MF_STRING, IDM_LANGUAGE, GetString ("IDM_LANGUAGE")); + AppendMenuW (popup, MF_STRING, IDM_HOTKEY_SETTINGS, GetString ("IDM_HOTKEY_SETTINGS")); + AppendMenuW (popup, MF_STRING, IDM_PERFORMANCE_SETTINGS, GetString ("IDM_PERFORMANCE_SETTINGS")); + AppendMenuW (popup, MF_STRING, IDM_SYSENC_SETTINGS, GetString ("IDM_SYSENC_SETTINGS")); + AppendMenuW (popup, MF_STRING, IDM_SYS_FAVORITES_SETTINGS, GetString ("IDM_SYS_FAVORITES_SETTINGS")); + AppendMenuW (popup, MF_STRING, IDM_DEFAULT_KEYFILES, GetString ("IDM_DEFAULT_KEYFILES")); + AppendMenuW (popup, MF_STRING, IDM_DEFAULT_MOUNT_PARAMETERS, GetString ("IDM_DEFAULT_MOUNT_PARAMETERS")); + AppendMenuW (popup, MF_STRING, IDM_TOKEN_PREFERENCES, GetString ("IDM_TOKEN_PREFERENCES")); + + RECT rect; + GetWindowRect (GetDlgItem (hwndDlg, IDC_MORE_SETTINGS), &rect); + + int menuItem = TrackPopupMenu (popup, TPM_RETURNCMD | TPM_LEFTBUTTON, rect.left + 2, rect.top + 2, 0, hwndDlg, NULL); + DestroyMenu (popup); + + SendMessage (MainDlg, WM_COMMAND, menuItem, NULL); + return 1; + } + else + return 0; + } + + if (HIWORD (wParam) == BN_CLICKED) + { + PreferencesDlgEnableButtons (hwndDlg); + return 1; + } + + return 0; + } + + return 0; +} + + +BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + static MountOptions *mountOptions; + + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + BOOL protect; + + mountOptions = (MountOptions *) lParam; + + LocalizeDialog (hwndDlg, "IDD_MOUNT_OPTIONS"); + + SendDlgItemMessage (hwndDlg, IDC_MOUNT_READONLY, BM_SETCHECK, + mountOptions->ReadOnly ? BST_CHECKED : BST_UNCHECKED, 0); + SendDlgItemMessage (hwndDlg, IDC_MOUNT_REMOVABLE, BM_SETCHECK, + mountOptions->Removable ? BST_CHECKED : BST_UNCHECKED, 0); + SendDlgItemMessage (hwndDlg, IDC_PROTECT_HIDDEN_VOL, BM_SETCHECK, + mountOptions->ProtectHiddenVolume ? BST_CHECKED : BST_UNCHECKED, 0); + + SendDlgItemMessage (hwndDlg, IDC_PROTECT_HIDDEN_VOL, BM_SETCHECK, + mountOptions->ProtectHiddenVolume ? BST_CHECKED : BST_UNCHECKED, 0); + + mountOptions->PartitionInInactiveSysEncScope = bPrebootPasswordDlgMode; + + SendDlgItemMessage (hwndDlg, IDC_MOUNT_SYSENC_PART_WITHOUT_PBA, BM_SETCHECK, + bPrebootPasswordDlgMode ? BST_CHECKED : BST_UNCHECKED, 0); + + SendDlgItemMessage (hwndDlg, IDC_USE_EMBEDDED_HEADER_BAK, BM_SETCHECK, + mountOptions->UseBackupHeader ? BST_CHECKED : BST_UNCHECKED, 0); + + EnableWindow (GetDlgItem (hwndDlg, IDC_MOUNT_SYSENC_PART_WITHOUT_PBA), !bPrebootPasswordDlgMode); + + SetDlgItemTextW (hwndDlg, IDC_VOLUME_LABEL, mountOptions->Label); + SendDlgItemMessage (hwndDlg, IDC_VOLUME_LABEL, EM_LIMITTEXT, 32, 0); // 32 is the maximum possible length for a drive label in Windows + + /* Add PRF algorithm list for hidden volume password */ + HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + + int i, nSelectedIndex = 0, nIndex = (int) SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); + + for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) + { + nIndex = (int) SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); + /* if a PRF was selected previously, select it */ + if (i == mountOptions->ProtectedHidVolPkcs5Prf) + nSelectedIndex = nIndex; + } + + SendMessage (hComboBox, CB_SETCURSEL, nSelectedIndex, 0); + + protect = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL)); + + EnableWindow (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL), !IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY))); + EnableWindow (GetDlgItem (hwndDlg, IDT_HIDDEN_VOL_PROTECTION), !IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY))); + EnableWindow (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PASSWORD_MO), protect); + EnableWindow (GetDlgItem (hwndDlg, IDT_HIDDEN_PROT_PASSWD), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_HIDVOL_PROT), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT), protect); + EnableWindow (GetDlgItem (hwndDlg, IDT_PKCS5_PRF), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), protect); + EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), protect); + + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT, hidVolProtKeyFilesParam.EnableKeyFiles); + + SendDlgItemMessage (hwndDlg, IDC_PASSWORD_PROT_HIDVOL, EM_LIMITTEXT, MAX_PASSWORD, 0); + SendDlgItemMessage (hwndDlg, IDC_PIM, EM_LIMITTEXT, MAX_PIM, 0); + + if (mountOptions->ProtectedHidVolPassword.Length > 0) + { + wchar_t szTmp[MAX_PASSWORD + 1]; + if (0 == MultiByteToWideChar (CP_UTF8, 0, (LPSTR) mountOptions->ProtectedHidVolPassword.Text, -1, szTmp, MAX_PASSWORD + 1)) + szTmp [0] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), szTmp); + burn (szTmp, sizeof (szTmp)); + } + + SetPim (hwndDlg, IDC_PIM, mountOptions->ProtectedHidVolPim); + + /* make PIM field visible if a PIM value has been explicitely specified */ + if (mountOptions->ProtectedHidVolPim > 0) + { + SetCheckBox (hwndDlg, IDC_PIM_ENABLE, TRUE); + ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); + } + + ToHyperlink (hwndDlg, IDC_LINK_HIDVOL_PROTECTION_INFO); + + } + return 0; + + case WM_CONTEXTMENU: + { + RECT buttonRect; + GetWindowRect (GetDlgItem (hwndDlg, IDC_KEYFILES_HIDVOL_PROT), &buttonRect); + + if (IsButtonChecked (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL)) + && LOWORD (lParam) >= buttonRect.left && LOWORD (lParam) <= buttonRect.right + && HIWORD (lParam) >= buttonRect.top && HIWORD (lParam) <= buttonRect.bottom) + { + // The "Keyfiles" button has been right-clicked + + POINT popupPos; + popupPos.x = buttonRect.left + 2; + popupPos.y = buttonRect.top + 2; + + if (KeyfilesPopupMenu (hwndDlg, popupPos, &hidVolProtKeyFilesParam)) + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT, hidVolProtKeyFilesParam.EnableKeyFiles); + } + } + break; + + case WM_COMMAND: + + if (lw == IDC_KEYFILES_HIDVOL_PROT) + { + if (IDOK == DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, + (DLGPROC) KeyFilesDlgProc, (LPARAM) &hidVolProtKeyFilesParam)) + { + SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT, hidVolProtKeyFilesParam.EnableKeyFiles); + } + } + + if (lw == IDC_KEYFILES_ENABLE_HIDVOL_PROT) + { + hidVolProtKeyFilesParam.EnableKeyFiles = GetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT); + + return 0; + } + + if (lw == IDC_SHOW_PASSWORD_MO) + { + HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD_MO, IDC_PASSWORD_PROT_HIDVOL, IDC_PIM); + return 1; + } + + if (lw == IDC_PIM_ENABLE) + { + ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE); + ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); + ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); + + SetFocus (GetDlgItem (hwndDlg, IDC_PIM)); + return 1; + } + + if (lw == IDC_LINK_HIDVOL_PROTECTION_INFO) + { + Applink ("hiddenvolprotection", TRUE, ""); + } + + if (lw == IDCANCEL) + { + wchar_t tmp[MAX_PASSWORD+1]; + + // Cleanup + wmemset (tmp, L'X', MAX_PASSWORD); + tmp[MAX_PASSWORD] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); + + EndDialog (hwndDlg, lw); + return 1; + } + + if (lw == IDOK) + { + wchar_t tmp[MAX_PASSWORD+1]; + + mountOptions->ReadOnly = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY)); + mountOptions->Removable = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_REMOVABLE)); + mountOptions->ProtectHiddenVolume = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL)); + mountOptions->PartitionInInactiveSysEncScope = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_SYSENC_PART_WITHOUT_PBA)); + mountOptions->UseBackupHeader = IsButtonChecked (GetDlgItem (hwndDlg, IDC_USE_EMBEDDED_HEADER_BAK)); + + GetDlgItemTextW (hwndDlg, IDC_VOLUME_LABEL, mountOptions->Label, sizeof (mountOptions->Label) /sizeof (wchar_t)); + + if (mountOptions->ProtectHiddenVolume) + { + GetPassword (hwndDlg, IDC_PASSWORD_PROT_HIDVOL, + (LPSTR) mountOptions->ProtectedHidVolPassword.Text, MAX_PASSWORD + 1, + FALSE); + + mountOptions->ProtectedHidVolPassword.Length = (unsigned __int32) strlen ((char *) mountOptions->ProtectedHidVolPassword.Text); + + mountOptions->ProtectedHidVolPkcs5Prf = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, + SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); + + mountOptions->ProtectedHidVolPim = GetPim (hwndDlg, IDC_PIM); + } + + // Cleanup + wmemset (tmp, L'X', MAX_PASSWORD); + tmp[MAX_PASSWORD] = 0; + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); + + if ((mountOptions->ProtectHiddenVolume && !bEnableBkgTask) + && (AskWarnYesNo ("HIDVOL_PROT_BKG_TASK_WARNING", hwndDlg) == IDYES)) + { + bEnableBkgTask = TRUE; + TaskBarIconAdd (MainDlg); + } + + EndDialog (hwndDlg, lw); + return 1; + } + + if (lw == IDC_MOUNT_READONLY || lw == IDC_PROTECT_HIDDEN_VOL) + { + BOOL protect; + + if (lw == IDC_MOUNT_READONLY) + { + SendDlgItemMessage (hwndDlg, IDC_PROTECT_HIDDEN_VOL, BM_SETCHECK, BST_UNCHECKED, 0); + EnableWindow (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL), !IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY))); + EnableWindow (GetDlgItem (hwndDlg, IDT_HIDDEN_VOL_PROTECTION), !IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY))); + } + + protect = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL)); + + EnableWindow (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), protect); + EnableWindow (GetDlgItem (hwndDlg, IDT_HIDDEN_PROT_PASSWD), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PASSWORD_MO), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_HIDVOL_PROT), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT), protect); + EnableWindow (GetDlgItem (hwndDlg, IDT_PKCS5_PRF), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), protect); + EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), protect); + EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), protect); + + return 1; + } + + return 0; + } + + return 0; +} + + +// Returns the block size (in bits) of the cipher with which the volume mounted as the +// specified drive letter is encrypted. In case of a cascade of ciphers with different +// block sizes the function returns the smallest block size. +int GetCipherBlockSizeByDriveNo (int nDosDriveNo) +{ + VOLUME_PROPERTIES_STRUCT prop; + DWORD dwResult; + + int blockSize = 0, cipherID; + + memset (&prop, 0, sizeof(prop)); + prop.driveNo = nDosDriveNo; + + if (DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL)) + { + if ( (prop.driveNo == nDosDriveNo) + && (prop.ea >= EAGetFirst() && prop.ea <= EAGetCount()) + ) + { + for (cipherID = EAGetLastCipher (prop.ea); + cipherID != 0; + cipherID = EAGetPreviousCipher (prop.ea, cipherID)) + { + if (blockSize > 0) + blockSize = min (blockSize, CipherGetBlockSize (cipherID) * 8); + else + blockSize = CipherGetBlockSize (cipherID) * 8; + } + } + } + + return blockSize; +} + + +// Returns the mode of operation in which the volume mounted as the specified drive letter is encrypted. +int GetModeOfOperationByDriveNo (int nDosDriveNo) +{ + VOLUME_PROPERTIES_STRUCT prop; + DWORD dwResult; + + memset (&prop, 0, sizeof(prop)); + prop.driveNo = nDosDriveNo; + + if (DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL)) + { + if ( (prop.driveNo == nDosDriveNo) + && (prop.ea >= EAGetFirst() && prop.ea <= EAGetCount()) + && (prop.mode >= FIRST_MODE_OF_OPERATION_ID && prop.mode < MODE_ENUM_END_ID) + ) + { + return prop.mode; + } + } + + return 0; +} + +void DisplayVolumePropertiesListContextMenu (HWND hwndDlg, LPARAM lParam) +{ + /* Volume Properties list context menu */ + DWORD mPos; + int menuItem; + HWND hList = GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES_LIST); + int hItem = ListView_GetSelectionMark (hList); + + SetFocus (hList); + + if (hItem >= 0) + { + HMENU popup = CreatePopupMenu (); + AppendMenuW (popup, MF_STRING, IDPM_COPY_VALUE_TO_CLIPBOARD, GetString ("IDPM_COPY_VALUE_TO_CLIPBOARD")); + + if (lParam) + { + mPos=GetMessagePos(); + } + else + { + POINT pt = {0}; + if (ListView_GetItemPosition (hList, hItem, &pt)) + { + pt.x += 2 + ::GetSystemMetrics(SM_CXICON); + pt.y += 2; + } + ClientToScreen (hList, &pt); + mPos = MAKELONG (pt.x, pt.y); + } + + menuItem = TrackPopupMenu (popup, + TPM_RETURNCMD | TPM_LEFTBUTTON, + GET_X_LPARAM(mPos), + GET_Y_LPARAM(mPos), + 0, + hwndDlg, + NULL); + + DestroyMenu (popup); + + switch (menuItem) + { + case IDPM_COPY_VALUE_TO_CLIPBOARD: + { + wchar_t valueText[256] = {0}; + ListView_GetItemText (hList, hItem, 1, valueText, ARRAYSIZE (valueText)); + CopyTextToClipboard (valueText); + } + break; + } + } +} + + +BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + BOOL bSysEnc = (BOOL) lParam; + BOOL bSysEncWholeDrive = FALSE; + WORD lw = LOWORD (wParam); + int i = 0; + + switch (msg) + { + case WM_INITDIALOG: + { + VOLUME_PROPERTIES_STRUCT prop; + DWORD dwResult; + + LVCOLUMNW lvCol; + HWND list = GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES_LIST); + wchar_t szTmp[1024]; + wchar_t sw[1024]; + wchar_t *s; + + if (bSysEnc) + { + try + { + BootEncStatus = BootEncObj->GetStatus(); + bSysEncWholeDrive = WholeSysDriveEncryption(FALSE); + } + catch (Exception &e) + { + e.Show (MainDlg); + return 0; + } + + if (!BootEncStatus.DriveEncrypted && !BootEncStatus.DriveMounted) + return 0; + } + else + { + switch (LOWORD (GetSelectedLong (GetDlgItem (GetParent(hwndDlg), IDC_DRIVELIST)))) + { + case TC_MLIST_ITEM_FREE: + + // No mounted volume + EndDialog (hwndDlg, IDOK); + return 0; + + case TC_MLIST_ITEM_NONSYS_VOL: + // NOP + break; + + case TC_MLIST_ITEM_SYS_DRIVE: + // Encrypted system drive + bSysEnc = TRUE; + bSysEncWholeDrive = TRUE; + break; + + case TC_MLIST_ITEM_SYS_PARTITION: + // Encrypted system partition + bSysEnc = TRUE; + bSysEncWholeDrive = FALSE; + break; + } + } + + LocalizeDialog (hwndDlg, "IDD_VOLUME_PROPERTIES"); + + SendMessage (list,LVM_SETEXTENDEDLISTVIEWSTYLE, 0, + LVS_EX_FULLROWSELECT + |LVS_EX_HEADERDRAGDROP + |LVS_EX_LABELTIP + ); + + memset (&lvCol,0,sizeof(lvCol)); + lvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; + lvCol.pszText = GetString ("VALUE"); + lvCol.cx = CompensateXDPI (208); + lvCol.fmt = LVCFMT_LEFT; + SendMessage (list,LVM_INSERTCOLUMNW,0,(LPARAM)&lvCol); + + lvCol.pszText = GetString ("PROPERTY"); + lvCol.cx = CompensateXDPI (192); + lvCol.fmt = LVCFMT_LEFT; + SendMessage (list,LVM_INSERTCOLUMNW,0,(LPARAM)&lvCol); + + memset (&prop, 0, sizeof(prop)); + prop.driveNo = HIWORD (GetSelectedLong (GetDlgItem (GetParent(hwndDlg), IDC_DRIVELIST))) - L'A'; + + if (bSysEnc) + { + try + { + BootEncStatus = BootEncObj->GetStatus(); + if (!BootEncStatus.DriveEncrypted && !BootEncStatus.DriveMounted) + return 0; + + BootEncObj->GetVolumeProperties (&prop); + } + catch (Exception &e) + { + e.Show (MainDlg); + return 0; + } + } + else + { + if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL) || dwResult == 0) + return 0; + } + + // Location + ListItemAdd (list, i, GetString ("LOCATION")); + if (bSysEnc) + ListSubItemSet (list, i++, 1, GetString (bSysEncWholeDrive ? "SYSTEM_DRIVE" : IsHiddenOSRunning() ? "HIDDEN_SYSTEM_PARTITION" : "SYSTEM_PARTITION")); + else + ListSubItemSet (list, i++, 1, (wchar_t *) (prop.wszVolume[1] != L'?' ? prop.wszVolume : prop.wszVolume + 4)); + + if (!bSysEnc && IsVolumeDeviceHosted ((wchar_t *) (prop.wszVolume[1] != L'?' ? prop.wszVolume : prop.wszVolume + 4))) + { + // Volume ID + std::wstring hexID = ArrayToHexWideString (prop.volumeID, sizeof (prop.volumeID)); + ListItemAdd (list, i, GetString ("VOLUME_ID")); + + ListSubItemSet (list, i++, 1, hexID.c_str()); + } + + + // Size + ListItemAdd (list, i, GetString ("SIZE")); + StringCbPrintfW (sw, sizeof(sw), L"%I64u %s", prop.diskLength, GetString ("BYTES")); + ListSubItemSet (list, i++, 1, sw); + + // Type + ListItemAdd (list, i, GetString ("TYPE")); + if (bSysEnc) + ListSubItemSet (list, i++, 1, GetString (IsHiddenOSRunning() ? "TYPE_HIDDEN_SYSTEM_ADJECTIVE" : "SYSTEM_VOLUME_TYPE_ADJECTIVE")); + else + { + bool truecryptMode = prop.pkcs5Iterations == get_pkcs5_iteration_count(prop.pkcs5, 0, TRUE, prop.partitionInInactiveSysEncScope); + s = prop.hiddenVolume ? GetString ("HIDDEN") : + (prop.hiddenVolProtection != HIDVOL_PROT_STATUS_NONE ? GetString ("OUTER") : GetString ("NORMAL")); + + if (truecryptMode) + { + StringCbPrintfW (sw, sizeof(sw), L"TrueCrypt - %s", s); + ListSubItemSet (list, i++, 1, sw); + } + else + ListSubItemSet (list, i++, 1, s); + } + + if (!bSysEnc) + { + // Write protection + ListItemAdd (list, i, GetString ("READ_ONLY")); + + if (prop.readOnly || prop.hiddenVolProtection == HIDVOL_PROT_STATUS_ACTION_TAKEN) + s = GetString ("UISTR_YES"); + else + s = GetString ("UISTR_NO"); + + ListSubItemSet (list, i++, 1, s); + + // Hidden Volume Protection + ListItemAdd (list, i, GetString ("HIDDEN_VOL_PROTECTION")); + if (prop.hiddenVolume) + s = GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE"); + else if (prop.hiddenVolProtection == HIDVOL_PROT_STATUS_NONE) + s = GetString ("UISTR_NO"); + else if (prop.hiddenVolProtection == HIDVOL_PROT_STATUS_ACTIVE) + s = GetString ("UISTR_YES"); + else if (prop.hiddenVolProtection == HIDVOL_PROT_STATUS_ACTION_TAKEN) + s = GetString ("HID_VOL_DAMAGE_PREVENTED"); + + ListSubItemSet (list, i++, 1, s); + } + + // Encryption algorithm + ListItemAdd (list, i, GetString ("ENCRYPTION_ALGORITHM")); + + if (prop.ea < EAGetFirst() || prop.ea > EAGetCount ()) + { + ListSubItemSet (list, i, 1, L"?"); + return 1; + } + + EAGetName (szTmp, prop.ea, 1); + ListSubItemSet (list, i++, 1, szTmp); + + // Key size(s) + { + wchar_t name[128]; + int size = EAGetKeySize (prop.ea); + EAGetName (name, prop.ea, 1); + + // Primary key + ListItemAdd (list, i, GetString ("KEY_SIZE")); + StringCbPrintfW (sw, sizeof(sw), L"%d %s", size * 8, GetString ("BITS")); + ListSubItemSet (list, i++, 1, sw); + + if (wcscmp (EAGetModeName (prop.ea, prop.mode, TRUE), L"XTS") == 0) + { + // Secondary key (XTS) + + ListItemAdd (list, i, GetString ("SECONDARY_KEY_SIZE_XTS")); + ListSubItemSet (list, i++, 1, sw); + } + } + + // Block size + ListItemAdd (list, i, GetString ("BLOCK_SIZE")); + + StringCbPrintfW (sw, sizeof(sw), L"%d ", CipherGetBlockSize (EAGetFirstCipher(prop.ea))*8); + StringCbCatW (sw, sizeof(sw), GetString ("BITS")); + ListSubItemSet (list, i++, 1, sw); + + // Mode + ListItemAdd (list, i, GetString ("MODE_OF_OPERATION")); + ListSubItemSet (list, i++, 1, EAGetModeName (prop.ea, prop.mode, TRUE)); + + // PKCS 5 PRF + ListItemAdd (list, i, GetString ("PKCS5_PRF")); + if (prop.volumePim == 0) + ListSubItemSet (list, i++, 1, get_pkcs5_prf_name (prop.pkcs5)); + else + { + StringCbPrintfW (szTmp, sizeof(szTmp), L"%s (Dynamic)", get_pkcs5_prf_name (prop.pkcs5)); + ListSubItemSet (list, i++, 1, szTmp); + } + +#if 0 + // PCKS 5 iterations + ListItemAdd (list, i, GetString ("PKCS5_ITERATIONS")); + sprintf (szTmp, "%d", prop.pkcs5Iterations); + ListSubItemSet (list, i++, 1, szTmp); +#endif + +#if 0 + { + // Legacy + + FILETIME ft, curFt; + LARGE_INTEGER ft64, curFt64; + SYSTEMTIME st; + wchar_t date[128]; + memset (date, 0, sizeof (date)); + + // Volume date + ListItemAdd (list, i, GetString ("VOLUME_CREATE_DATE")); + *(unsigned __int64 *)(&ft) = prop.volumeCreationTime; + FileTimeToSystemTime (&ft, &st); + GetDateFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2); + swprintf (date, L"%s ", sw); + GetTimeFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2); + wcscat (date, sw); + ListSubItemSet (list, i++, 1, date); + + // Header date + ListItemAdd (list, i, GetString ("VOLUME_HEADER_DATE")); + *(unsigned __int64 *)(&ft) = prop.headerCreationTime; + FileTimeToSystemTime (&ft, &st); + GetDateFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2); + swprintf (date, L"%s ", sw); + GetTimeFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2); + wcscat (date, sw); + + GetLocalTime (&st); + SystemTimeToFileTime (&st, &curFt); + curFt64.HighPart = curFt.dwHighDateTime; + curFt64.LowPart = curFt.dwLowDateTime; + ft64.HighPart = ft.dwHighDateTime; + ft64.LowPart = ft.dwLowDateTime; + swprintf (date + wcslen (date), GetString ("VOLUME_HEADER_DAYS") + , (curFt64.QuadPart - ft64.QuadPart)/(24LL*3600*10000000)); + ListSubItemSet (list, i++, 1, date); + } +#endif // 0 + + if (!bSysEnc || IsHiddenOSRunning()) + { + // Volume format version + ListItemAdd (list, i, GetString ("VOLUME_FORMAT_VERSION")); + StringCbPrintfW (szTmp, sizeof(szTmp), L"%d", prop.volFormatVersion); + ListSubItemSet (list, i++, 1, szTmp); + + // Backup header + ListItemAdd (list, i, GetString ("BACKUP_HEADER")); + ListSubItemSet (list, i++, 1, GetString (prop.volFormatVersion > 1 ? "UISTR_YES" : "UISTR_NO")); + } + + // Total data read + ListItemAdd (list, i, GetString ("TOTAL_DATA_READ")); + GetSizeString (prop.totalBytesRead, sw, sizeof(sw)); + ListSubItemSet (list, i++, 1, sw); + + // Total data written + ListItemAdd (list, i, GetString ("TOTAL_DATA_WRITTEN")); + GetSizeString (prop.totalBytesWritten, sw, sizeof(sw)); + ListSubItemSet (list, i++, 1, sw); + + if (bSysEnc) + { + // TrueCrypt Boot Loader version + ListItemAdd (list, i, GetString ("VC_BOOT_LOADER_VERSION")); + ListSubItemSet (list, i++, 1, GetUserFriendlyVersionString (BootEncStatus.BootLoaderVersion).c_str()); + + // Encrypted portion + ListItemAdd (list, i, GetString ("ENCRYPTED_PORTION")); + if (GetSysEncDeviceEncryptedPartSize (FALSE) == GetSysEncDeviceSize (FALSE)) + ListSubItemSet (list, i++, 1, GetString ("ENCRYPTED_PORTION_FULLY_ENCRYPTED")); + else if (GetSysEncDeviceEncryptedPartSize (FALSE) <= 1) + ListSubItemSet (list, i++, 1, GetString ("ENCRYPTED_PORTION_NOT_ENCRYPTED")); + else + { + + StringCbPrintfW (sw, + sizeof sw, + GetString ("PROCESSED_PORTION_X_PERCENT"), + (double) GetSysEncDeviceEncryptedPartSize (FALSE) / (double) GetSysEncDeviceSize (FALSE) * 100.0); + + ListSubItemSet (list, i++, 1, sw); + } + } + + return 0; + } + + case WM_NOTIFY: + + if(wParam == IDC_VOLUME_PROPERTIES_LIST) + { + /* Right click */ + + switch (((NM_LISTVIEW *) lParam)->hdr.code) + { + case NM_RCLICK: + case LVN_BEGINRDRAG: + /* If the mouse was moving while the right mouse button is pressed, popup menu would + not open, because drag&drop operation would be initiated. Therefore, we're handling + RMB drag-and-drop operations as well. */ + { + + DisplayVolumePropertiesListContextMenu (hwndDlg, lParam); + + return 1; + } + } + } + return 0; + + case WM_CONTEXTMENU: + { + HWND hList = GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES_LIST); + // only handle if it is coming from keyboard and if the drive + // list has focus. The other cases are handled elsewhere + if ( (-1 == GET_X_LPARAM(lParam)) + && (-1 == GET_Y_LPARAM(lParam)) + && (GetFocus () == hList) + ) + { + DisplayVolumePropertiesListContextMenu (hwndDlg, NULL); + } + } + return 0; + + case WM_COMMAND: + if (lw == IDOK) + { + EndDialog (hwndDlg, lw); + return 1; + } + return 0; + + case WM_CLOSE: + EndDialog (hwndDlg, lw); + return 1; + } + + return 0; +} + + +BOOL CALLBACK TravelerDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + static BOOL bAutoRunWarningDisplayed = FALSE; + + switch (msg) + { + case WM_INITDIALOG: + { + WCHAR i; + int index; + WCHAR drive[] = { 0, L':', 0 }; + + LocalizeDialog (hwndDlg, "IDD_TRAVELER_DLG"); + + SendDlgItemMessage (hwndDlg, IDC_COPY_WIZARD, BM_SETCHECK, + BST_CHECKED, 0); + + SendDlgItemMessage (hwndDlg, IDC_COPY_EXPANDER, BM_SETCHECK, + BST_CHECKED, 0); + + SendDlgItemMessage (hwndDlg, IDC_TRAVEL_OPEN_EXPLORER, BM_SETCHECK, + BST_CHECKED, 0); + + SendDlgItemMessage (hwndDlg, IDC_AUTORUN_DISABLE, BM_SETCHECK, + BST_CHECKED, 0); + + SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_RESETCONTENT, 0, 0); + + index = (int) SendDlgItemMessageW (hwndDlg, IDC_DRIVELIST, CB_ADDSTRING, 0, (LPARAM) GetString ("FIRST_AVAILABLE")); + SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_SETITEMDATA, index, (LPARAM) 0); + + for (i = L'A'; i <= L'Z'; i++) + { + if (i == L'C') + continue; + drive[0] = i; + index = (int) SendDlgItemMessageW (hwndDlg, IDC_DRIVELIST, CB_ADDSTRING, 0, (LPARAM) drive); + SendDlgItemMessageW (hwndDlg, IDC_DRIVELIST, CB_SETITEMDATA, index, (LPARAM) i); + } + + SendDlgItemMessageW (hwndDlg, IDC_DRIVELIST, CB_SETCURSEL, 0, 0); + + return 0; + } + + case WM_CTLCOLORSTATIC: + { + HDC hdc = (HDC) wParam; + HWND hw = (HWND) lParam; + if (hw == GetDlgItem(hwndDlg, IDC_DIRECTORY)) + { + // This the directory field. Make its background like normal edit + HBRUSH hbr = GetSysColorBrush (COLOR_WINDOW); + ::SelectObject(hdc, hbr); + return (BOOL) hbr; + } + } + return 0; + + case WM_COMMAND: + + if (HIWORD (wParam) == BN_CLICKED + && (lw == IDC_AUTORUN_DISABLE || lw == IDC_AUTORUN_MOUNT || lw == IDC_AUTORUN_START )) + { + BOOL enabled = IsButtonChecked (GetDlgItem (hwndDlg, IDC_AUTORUN_MOUNT)); + + EnableWindow (GetDlgItem (hwndDlg, IDC_BROWSE_FILES), enabled); + EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_NAME), enabled); + EnableWindow (GetDlgItem (hwndDlg, IDC_TRAVEL_OPEN_EXPLORER), enabled); + EnableWindow (GetDlgItem (hwndDlg, IDC_TRAV_CACHE_PASSWORDS), enabled); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PIM), enabled); + EnableWindow (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY), enabled); + EnableWindow (GetDlgItem (hwndDlg, IDC_DRIVELIST), enabled); + EnableWindow (GetDlgItem (hwndDlg, IDT_TRAVELER_MOUNT), enabled); + EnableWindow (GetDlgItem (hwndDlg, IDT_MOUNT_LETTER), enabled); + EnableWindow (GetDlgItem (hwndDlg, IDT_MOUNT_SETTINGS), enabled); + + if (!bAutoRunWarningDisplayed + && (lw == IDC_AUTORUN_MOUNT || lw == IDC_AUTORUN_START)) + { + bAutoRunWarningDisplayed = TRUE; + Warning ("AUTORUN_MAY_NOT_ALWAYS_WORK", hwndDlg); + } + + return 1; + } + + if (lw == IDC_BROWSE_FILES) + { + wchar_t dstDir[MAX_PATH]; + wchar_t volName[MAX_PATH] = { 0 }; + + GetDlgItemText (hwndDlg, IDC_DIRECTORY, dstDir, ARRAYSIZE (dstDir)); + + if (BrowseFilesInDir (hwndDlg, "OPEN_TITLE", dstDir, volName, bHistory, FALSE, NULL)) + SetDlgItemText (hwndDlg, IDC_VOLUME_NAME, wcschr (volName, L'\\') + 1); + + return 1; + } + + if (lw == IDC_BROWSE_DIRS) + { + wchar_t dstPath[MAX_PATH * 2]; + GetDlgItemText (hwndDlg, IDC_DIRECTORY, dstPath, ARRAYSIZE (dstPath)); + + if (BrowseDirectories (hwndDlg, "SELECT_DEST_DIR", dstPath)) + SetDlgItemText (hwndDlg, IDC_DIRECTORY, dstPath); + + return 1; + } + + if (lw == IDCANCEL || lw == IDCLOSE) + { + EndDialog (hwndDlg, lw); + return 1; + } + + if (lw == IDC_CREATE) + { + + BOOL copyWizard, copyExpander, bExplore, bCacheInDriver, bIncludePimInCache, bAutoRun, bAutoMount, bMountReadOnly; + WCHAR dstDir[MAX_PATH + 1]; + WCHAR srcPath[1024 + MAX_PATH + 1]; + WCHAR dstPath[2*MAX_PATH + 1]; + WCHAR appDir[1024]; + WCHAR volName[MAX_PATH + 2]; + int drive; + WCHAR* ptr; + + GetDlgItemTextW (hwndDlg, IDC_DIRECTORY, dstDir, array_capacity (dstDir)); + volName[0] = 0; + GetDlgItemTextW (hwndDlg, IDC_VOLUME_NAME, volName + 1, (array_capacity (volName)) - 1); + + drive = (int) SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_GETCURSEL, 0, 0); + drive = (int) SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_GETITEMDATA, drive, 0); + + copyWizard = IsButtonChecked (GetDlgItem (hwndDlg, IDC_COPY_WIZARD)); + copyExpander = IsButtonChecked (GetDlgItem (hwndDlg, IDC_COPY_EXPANDER)); + bExplore = IsButtonChecked (GetDlgItem (hwndDlg, IDC_TRAVEL_OPEN_EXPLORER)); + bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_TRAV_CACHE_PASSWORDS)); + bIncludePimInCache = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PIM)); + bMountReadOnly = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY)); + bAutoRun = !IsButtonChecked (GetDlgItem (hwndDlg, IDC_AUTORUN_DISABLE)); + bAutoMount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_AUTORUN_MOUNT)); + + if (dstDir[0] == 0) + { + SetFocus (GetDlgItem (hwndDlg, IDC_DIRECTORY)); + MessageBoxW (hwndDlg, GetString ("NO_PATH_SELECTED"), lpszTitle, MB_ICONEXCLAMATION); + return 1; + } + + + if (bAutoMount && volName[1] == 0) + { + SetFocus (GetDlgItem (hwndDlg, IDC_VOLUME_NAME)); + MessageBoxW (hwndDlg, GetString ("NO_FILE_SELECTED"), lpszTitle, MB_ICONEXCLAMATION); + return 1; + } + + if (volName[1] != 0) + { + volName[0] = L'"'; + StringCbCatW (volName, sizeof(volName), L"\""); + } + + GetModuleFileNameW (NULL, appDir, array_capacity (appDir)); + if (ptr = wcsrchr (appDir, L'\\')) + ptr[0] = 0; + + WaitCursor (); + + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt", dstDir); + if (!CreateDirectoryW (dstPath, NULL)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + + // Main app 32-bit + if (Is64BitOs () && !IsNonInstallMode ()) + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt-x86.exe", appDir); + else + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt.exe", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt.exe", dstDir); + if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + + // Main app 64-bit + if (Is64BitOs () && !IsNonInstallMode ()) + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt.exe", appDir); + else + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt-x64.exe", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt-x64.exe", dstDir); + if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + + // Wizard + if (copyWizard) + { + // Wizard 32-bit + if (Is64BitOs () && !IsNonInstallMode ()) + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format-x86.exe", appDir); + else + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format.exe", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format.exe", dstDir); + if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + + // Wizard 64-bit + if (Is64BitOs () && !IsNonInstallMode ()) + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format.exe", appDir); + else + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format-x64.exe", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format-x64.exe", dstDir); + if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + } + + // Expander + if (copyExpander) + { + // Expander 32-bit + if (Is64BitOs () && !IsNonInstallMode ()) + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander-x86.exe", appDir); + else + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander.exe", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander.exe", dstDir); + if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + + // Expander 64-bit + if (Is64BitOs () && !IsNonInstallMode ()) + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander.exe", appDir); + else + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander-x64.exe", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander-x64.exe", dstDir); + if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + } + + // Driver + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\veracrypt.sys", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt.sys", dstDir); + if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + + // Driver x64 + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\veracrypt-x64.sys", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt-x64.sys", dstDir); + if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + + if (strcmp (GetPreferredLangId (), "en") != 0) + { + // Language pack + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\Language.%hs.xml", appDir, GetPreferredLangId ()); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\Language.%hs.xml", dstDir, GetPreferredLangId ()); + TCCopyFile (srcPath, dstPath); + } + + // AutoRun + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\autorun.inf", dstDir); + DeleteFileW (dstPath); + if (bAutoRun) + { + FILE *af; + wchar_t autoMount[2*MAX_PATH + 2]; + wchar_t driveLetter[] = { L' ', L'/', L'l', L' ', (wchar_t) drive, 0 }; + + af = _wfopen (dstPath, L"w,ccs=UNICODE"); + + if (af == NULL) + { + MessageBoxW (hwndDlg, GetString ("CANT_CREATE_AUTORUN"), lpszTitle, MB_ICONERROR); + goto stop; + } + + StringCbPrintfW (autoMount, sizeof(autoMount), L"VeraCrypt\\VeraCrypt.exe /q background%s%s%s%s /m rm /v %s", + drive > 0 ? driveLetter : L"", + bExplore ? L" /e" : L"", + bCacheInDriver ? (bIncludePimInCache? L" /c p" : L" /c y") : L"", + bMountReadOnly ? L" /m ro" : L"", + volName); + + fwprintf (af, L"[autorun]\nlabel=%s\nicon=VeraCrypt\\VeraCrypt.exe\n", GetString ("TC_TRAVELER_DISK")); + fwprintf (af, L"action=%s\n", bAutoMount ? GetString ("MOUNT_TC_VOLUME") : GetString ("IDC_PREF_LOGON_START")); + fwprintf (af, L"open=%s\n", bAutoMount ? autoMount : L"VeraCrypt\\VeraCrypt.exe"); + fwprintf (af, L"shell\\start=%s\nshell\\start\\command=VeraCrypt\\VeraCrypt.exe\n", GetString ("IDC_PREF_LOGON_START")); + fwprintf (af, L"shell\\dismount=%s\nshell\\dismount\\command=VeraCrypt\\VeraCrypt.exe /q /d\n", GetString ("DISMOUNT_ALL_TC_VOLUMES")); + + CheckFileStreamWriteErrors (hwndDlg, af, dstPath); + fclose (af); + } + MessageBoxW (hwndDlg, GetString ("TRAVELER_DISK_CREATED"), lpszTitle, MB_ICONINFORMATION); + +stop: + NormalCursor (); + return 1; + } + return 0; + } + + return 0; +} + +void BuildTree (HWND hwndDlg, HWND hTree) +{ + HIMAGELIST hList; + HBITMAP hBitmap, hBitmapMask; + LVCOLUMNW lvCol; + + ListView_DeleteColumn (hTree,0); + ListView_DeleteColumn (hTree,0); + ListView_DeleteColumn (hTree,0); + ListView_DeleteColumn (hTree,0); + ListView_DeleteColumn (hTree,0); + ListView_DeleteColumn (hTree,0); + + SendMessage(hTree,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 ("DRIVE"); + lvCol.cx = CompensateXDPI (38); + lvCol.fmt = LVCFMT_COL_HAS_IMAGES|LVCFMT_LEFT ; + SendMessage (hTree,LVM_INSERTCOLUMNW,0,(LPARAM)&lvCol); + + lvCol.pszText = GetString ("VOLUME"); + lvCol.cx = CompensateXDPI (200); + lvCol.fmt = LVCFMT_LEFT; + SendMessage (hTree,LVM_INSERTCOLUMNW,1,(LPARAM)&lvCol); + LastDriveListVolumeColumnWidth = ListView_GetColumnWidth (hTree, 1); + + lvCol.pszText = GetString ("SIZE"); + lvCol.cx = CompensateXDPI (55); + lvCol.fmt = LVCFMT_RIGHT; + SendMessage (hTree,LVM_INSERTCOLUMNW,2,(LPARAM)&lvCol); + + lvCol.pszText = GetString ("ENCRYPTION_ALGORITHM_LV"); + lvCol.cx = CompensateXDPI (123); + lvCol.fmt = LVCFMT_LEFT; + SendMessage (hTree,LVM_INSERTCOLUMNW,3,(LPARAM)&lvCol); + + lvCol.pszText = GetString ("TYPE"); + lvCol.cx = CompensateXDPI (100); + lvCol.fmt = LVCFMT_LEFT; + SendMessage (hTree,LVM_INSERTCOLUMNW,4,(LPARAM)&lvCol); + + // Regular drive icon + + hBitmap = LoadBitmap (hInst, MAKEINTRESOURCE (IDB_DRIVEICON)); + if (hBitmap == NULL) + return; + hBitmapMask = LoadBitmap (hInst, MAKEINTRESOURCE (IDB_DRIVEICON_MASK)); + + hList = CreateImageList (16, 12, ILC_COLOR8|ILC_MASK, 2, 2); + if (AddBitmapToImageList (hList, hBitmap, hBitmapMask) == -1) + { + DeleteObject (hBitmap); + DeleteObject (hBitmapMask); + return; + } + else + { + DeleteObject (hBitmap); + DeleteObject (hBitmapMask); + } + + // System drive icon + + hBitmap = LoadBitmap (hInst, MAKEINTRESOURCE (IDB_SYS_DRIVEICON)); + if (hBitmap == NULL) + return; + hBitmapMask = LoadBitmap (hInst, MAKEINTRESOURCE (IDB_SYS_DRIVEICON_MASK)); + + if (AddBitmapToImageList (hList, hBitmap, hBitmapMask) == -1) + { + DeleteObject (hBitmap); + DeleteObject (hBitmapMask); + return; + } + else + { + DeleteObject (hBitmap); + DeleteObject (hBitmapMask); + } + + ListView_SetImageList (hTree, hList, LVSIL_NORMAL); + ListView_SetImageList (hTree, hList, LVSIL_SMALL); + + LoadDriveLetters (hwndDlg, hTree, 0); +} + +LPARAM GetSelectedLong (HWND hTree) +{ + int hItem = ListView_GetSelectionMark (hTree); + LVITEM item; + + if (nSelectedDriveIndex >= 0) + hItem = nSelectedDriveIndex; + + memset(&item, 0, sizeof(LVITEM)); + item.mask = LVIF_PARAM; + item.iItem = hItem; + + if ( (ListView_GetItemCount (hTree) < 1) + || (ListView_GetItem (hTree, &item) == FALSE) + ) + return MAKELONG (0xffff, 0xffff); + else + return item.lParam; +} + +LPARAM GetItemLong (HWND hTree, int itemNo) +{ + LVITEM item; + + memset(&item, 0, sizeof(LVITEM)); + item.mask = LVIF_PARAM; + item.iItem = itemNo; + + if (ListView_GetItem (hTree, &item) == FALSE) + return MAKELONG (0xffff, 0xffff); + else + return item.lParam; +} + +static int AskVolumePassword (HWND hwndDlg, Password *password, int *pkcs5, int *pim, BOOL* truecryptMode, char *titleStringId, BOOL enableMountOptions) +{ + INT_PTR result; + PasswordDlgParam dlgParam; + + PasswordDialogTitleStringId = titleStringId; + PasswordDialogDisableMountOptions = !enableMountOptions; + + dlgParam.password = password; + dlgParam.pkcs5 = pkcs5; + dlgParam.pim = pim; + dlgParam.truecryptMode = truecryptMode; + + result = DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_PASSWORD_DLG), hwndDlg, + (DLGPROC) PasswordDlgProc, (LPARAM) &dlgParam); + + if (result != IDOK) + { + password->Length = 0; + *pkcs5 = 0; + *pim = -1; + *truecryptMode = FALSE; + burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); + burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); + } + + return result == IDOK; +} + +// GUI actions + +static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim) +{ + BOOL status = FALSE; + wchar_t fileName[MAX_PATH]; + int mounted = 0, EffectiveVolumePkcs5 = CmdVolumePkcs5; + BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; + int EffectiveVolumePim = (pim < 0)? CmdVolumePim : pim; + BOOL bEffectiveCacheDuringMultipleMount = bCmdCacheDuringMultipleMount? TRUE: bCacheDuringMultipleMount; + BOOL bEffectiveTryEmptyPasswordWhenKeyfileUsed = bCmdTryEmptyPasswordWhenKeyfileUsedValid? bCmdTryEmptyPasswordWhenKeyfileUsed : bTryEmptyPasswordWhenKeyfileUsed; + BOOL bUseCmdVolumePassword = CmdVolumePasswordValid && ((CmdVolumePassword.Length > 0) || (KeyFilesEnable && FirstKeyFile)); + + /* Priority is given to command line parameters + * Default values used only when nothing specified in command line + */ + if (EffectiveVolumePkcs5 == 0) + EffectiveVolumePkcs5 = DefaultVolumePkcs5; + if (!EffectiveVolumeTrueCryptMode) + EffectiveVolumeTrueCryptMode = DefaultVolumeTrueCryptMode; + + bPrebootPasswordDlgMode = mountOptions.PartitionInInactiveSysEncScope; + + if (nDosDriveNo == -1) + nDosDriveNo = HIWORD (GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST))) - L'A'; + + if (!MultipleMountOperationInProgress) + { + VolumePassword.Length = 0; + VolumePkcs5 = 0; + VolumeTrueCryptMode = FALSE; + VolumePim = -1; + } + + if (szFileName == NULL) + { + GetVolumePath (hwndDlg, fileName, ARRAYSIZE (fileName)); + } + else + StringCchCopyW (fileName, ARRAYSIZE (fileName), szFileName); + + if (wcslen(fileName) == 0) + { + status = FALSE; + goto ret; + } + + if (!TranslateVolumeID (hwndDlg, fileName, ARRAYSIZE (fileName))) + { + status = FALSE; + goto ret; + } + + szFileName = fileName; + + if (IsMountedVolume (szFileName)) + { + Warning ("VOL_ALREADY_MOUNTED", hwndDlg); + status = FALSE; + goto ret; + } + + if (!VolumePathExists (szFileName)) + { + if (!MultipleMountOperationInProgress) + handleWin32Error (hwndDlg, SRC_POS); + + status = FALSE; + goto ret; + } + + ResetWrongPwdRetryCount (); + + WaitCursor (); + + if (!bUseCmdVolumePassword) + { + // First try cached passwords and if they fail ask user for a new one + // try TrueCrypt mode first since it is quick, only if no custom pim specified + if (EffectiveVolumePim <= 0) + mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, 0, 0, TRUE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); + if (!mounted) + mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, 0, EffectiveVolumePim, FALSE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); + + // If keyfiles are enabled, test empty password first + if (!mounted && KeyFilesEnable && FirstKeyFile && bEffectiveTryEmptyPasswordWhenKeyfileUsed) + { + Password emptyPassword; + emptyPassword.Length = 0; + + KeyFilesApply (hwndDlg, &emptyPassword, FirstKeyFile, szFileName); + // try TrueCrypt mode first since it is quick, only if no custom pim specified + if (EffectiveVolumePim <= 0) + mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &emptyPassword, 0, 0, TRUE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); + if (!mounted) + mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &emptyPassword, 0, EffectiveVolumePim, FALSE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); + + burn (&emptyPassword, sizeof (emptyPassword)); + } + } + + // Test password and/or keyfiles used for the previous volume + if (!mounted && bEffectiveCacheDuringMultipleMount && MultipleMountOperationInProgress && VolumePassword.Length != 0) + { + // try TrueCrypt mode first as it is quick, only if no custom pim specified + if (EffectiveVolumePim <= 0) + mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, 0, 0, TRUE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); + if (!mounted) + mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, 0, EffectiveVolumePim, FALSE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); + } + + NormalCursor (); + + if (mounted) + { + + // Check for problematic file extensions (exe, dll, sys) + if (CheckFileExtension(szFileName)) + Warning ("EXE_FILE_EXTENSION_MOUNT_WARNING", hwndDlg); + } + + while (mounted == 0) + { + if (bUseCmdVolumePassword) + { + VolumePassword = CmdVolumePassword; + VolumePkcs5 = EffectiveVolumePkcs5; + VolumeTrueCryptMode = EffectiveVolumeTrueCryptMode; + VolumePim = EffectiveVolumePim; + } + else if (!Silent) + { + int GuiPkcs5 = EffectiveVolumePkcs5; + BOOL GuiTrueCryptMode = EffectiveVolumeTrueCryptMode; + int GuiPim = EffectiveVolumePim; + StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume), szFileName); + + if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &GuiTrueCryptMode, NULL, TRUE)) + goto ret; + else + { + VolumePkcs5 = GuiPkcs5; + VolumeTrueCryptMode = GuiTrueCryptMode; + VolumePim = GuiPim; + burn (&GuiPkcs5, sizeof(GuiPkcs5)); + burn (&GuiTrueCryptMode, sizeof(GuiTrueCryptMode)); + burn (&GuiPim, sizeof(GuiPim)); + } + } + + WaitCursor (); + + if (KeyFilesEnable) + KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, szFileName); + + mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, !Silent); + NormalCursor (); + + // Check for problematic file extensions (exe, dll, sys) + if (mounted > 0 && CheckFileExtension (szFileName)) + Warning ("EXE_FILE_EXTENSION_MOUNT_WARNING", hwndDlg); + + if (!MultipleMountOperationInProgress) + { + burn (&VolumePassword, sizeof (VolumePassword)); + burn (&VolumePkcs5, sizeof (VolumePkcs5)); + burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); + burn (&VolumePim, sizeof (VolumePim)); + } + + burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); + burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); + + if (CmdVolumePassword.Length > 0 || Silent) + break; + } + + if (mounted > 0) + { + status = TRUE; + + if (bBeep) + MessageBeep (0xFFFFFFFF); + + RefreshMainDlg(MainDlg); + + if (bExplore) + { + WaitCursor(); + OpenVolumeExplorerWindow (nDosDriveNo); + NormalCursor(); + } + + if (mountOptions.ProtectHiddenVolume) + Info ("HIDVOL_PROT_WARN_AFTER_MOUNT", hwndDlg); + } + +ret: + if (!MultipleMountOperationInProgress) + { + burn (&VolumePassword, sizeof (VolumePassword)); + burn (&VolumePkcs5, sizeof (VolumePkcs5)); + burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); + burn (&VolumePim, sizeof (VolumePim)); + } + + burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); + burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); + + RestoreDefaultKeyFilesParam (); + + if (UsePreferences) + bCacheInDriver = bCacheInDriverDefault; + + if (status && CloseSecurityTokenSessionsAfterMount && !MultipleMountOperationInProgress) + SecurityToken::CloseAllSessions(); + + return status; +} + + +static BOOL Dismount (HWND hwndDlg, int nDosDriveNo) +{ + BOOL status = FALSE; + WaitCursor (); + + if (nDosDriveNo == -2) + nDosDriveNo = (char) (HIWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) - L'A'); + + if (bCloseDismountedWindows) + { + CloseVolumeExplorerWindows (hwndDlg, nDosDriveNo); + } + + if (UnmountVolume (hwndDlg, nDosDriveNo, bForceUnmount)) + { + status = TRUE; + + if (bBeep) + MessageBeep (0xFFFFFFFF); + RefreshMainDlg (hwndDlg); + + if (nCurrentOS == WIN_2000 && RemoteSession && !IsAdmin ()) + LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), 0); + } + + NormalCursor (); + return status; +} + +void __cdecl mountThreadFunction (void *hwndDlgArg) +{ + HWND hwndDlg =(HWND) hwndDlgArg; + BOOL bIsForeground = (GetForegroundWindow () == hwndDlg)? TRUE : FALSE; + // Disable parent dialog during processing to avoid user interaction + EnableWindow(hwndDlg, FALSE); + finally_do_arg2 (HWND, hwndDlg, BOOL, bIsForeground, { EnableWindow(finally_arg, TRUE); if (finally_arg2) BringToForeground (finally_arg); bPrebootPasswordDlgMode = FALSE;}); + + Mount (hwndDlg, -1, 0, -1); +} + +typedef struct +{ + UNMOUNT_STRUCT* punmount; + BOOL interact; + int dismountMaxRetries; + int dismountAutoRetryDelay; + BOOL* pbResult; + DWORD* pdwResult; + DWORD dwLastError; + BOOL bReturn; +} DismountAllThreadParam; + +void CALLBACK DismountAllThreadProc(void* pArg, HWND hwndDlg) +{ + DismountAllThreadParam* pThreadParam = (DismountAllThreadParam*) pArg; + UNMOUNT_STRUCT* punmount = pThreadParam->punmount; + BOOL* pbResult = pThreadParam->pbResult; + DWORD* pdwResult = pThreadParam->pdwResult; + int dismountMaxRetries = pThreadParam->dismountMaxRetries; + int dismountAutoRetryDelay = pThreadParam->dismountAutoRetryDelay; + + do + { + *pbResult = DeviceIoControl (hDriver, TC_IOCTL_DISMOUNT_ALL_VOLUMES, punmount, + sizeof (UNMOUNT_STRUCT), punmount, sizeof (UNMOUNT_STRUCT), pdwResult, NULL); + + if ( punmount->nDosDriveNo < 0 || punmount->nDosDriveNo > 25 + || (punmount->ignoreOpenFiles != TRUE && punmount->ignoreOpenFiles != FALSE) + || (punmount->HiddenVolumeProtectionTriggered != TRUE && punmount->HiddenVolumeProtectionTriggered != FALSE) + || (punmount->nReturnCode < 0) + ) + { + if (*pbResult) + SetLastError (ERROR_INTERNAL_ERROR); + *pbResult = FALSE; + } + + if (*pbResult == FALSE) + { + NormalCursor(); + handleWin32Error (hwndDlg, SRC_POS); + pThreadParam->dwLastError = GetLastError (); + pThreadParam->bReturn = FALSE; + return; + } + + if (punmount->nReturnCode == ERR_SUCCESS + && punmount->HiddenVolumeProtectionTriggered + && !VolumeNotificationsList.bHidVolDamagePrevReported [punmount->nDosDriveNo] + && pThreadParam->interact + && !Silent) + { + wchar_t msg[4096]; + + VolumeNotificationsList.bHidVolDamagePrevReported [punmount->nDosDriveNo] = TRUE; + + StringCbPrintfW (msg, sizeof(msg), GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), punmount->nDosDriveNo + L'A'); + SetForegroundWindow (hwndDlg); + MessageBoxW (hwndDlg, msg, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); + + punmount->HiddenVolumeProtectionTriggered = FALSE; + continue; + } + + if (punmount->nReturnCode == ERR_FILES_OPEN) + Sleep (dismountAutoRetryDelay); + else + break; + + } while (--dismountMaxRetries > 0); + + pThreadParam->dwLastError = GetLastError (); + pThreadParam->bReturn = TRUE; +} + +static BOOL DismountAll (HWND hwndDlg, BOOL forceUnmount, BOOL interact, int dismountMaxRetries, int dismountAutoRetryDelay) +{ + BOOL status = TRUE; + MOUNT_LIST_STRUCT mountList = {0}; + DWORD dwResult; + UNMOUNT_STRUCT unmount = {0}; + BOOL bResult; + MOUNT_LIST_STRUCT prevMountList = {0}; + int i; + DismountAllThreadParam dismountAllThreadParam; + +retry: + WaitCursor(); + + DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mountList, sizeof (mountList), &mountList, sizeof (mountList), &dwResult, NULL); + + if (mountList.ulMountedDrives == 0) + { + NormalCursor(); + return TRUE; + } + + BroadcastDeviceChange (DBT_DEVICEREMOVEPENDING, 0, mountList.ulMountedDrives); + + memcpy (&prevMountList, &mountList, sizeof (mountList)); + + for (i = 0; i < 26; i++) + { + if (mountList.ulMountedDrives & (1 << i)) + { + if (bCloseDismountedWindows) + CloseVolumeExplorerWindows (hwndDlg, i); + } + } + + unmount.nDosDriveNo = 0; + unmount.ignoreOpenFiles = forceUnmount; + + dismountAllThreadParam.punmount = &unmount; + dismountAllThreadParam.interact = interact; + dismountAllThreadParam.dismountMaxRetries = dismountMaxRetries; + dismountAllThreadParam.dismountAutoRetryDelay = dismountAutoRetryDelay; + dismountAllThreadParam.pbResult = &bResult; + dismountAllThreadParam.pdwResult = &dwResult; + dismountAllThreadParam.dwLastError = ERROR_SUCCESS; + dismountAllThreadParam.bReturn = TRUE; + + if (interact && !Silent) + { + + ShowWaitDialog (hwndDlg, FALSE, DismountAllThreadProc, &dismountAllThreadParam); + } + else + DismountAllThreadProc (&dismountAllThreadParam, hwndDlg); + + SetLastError (dismountAllThreadParam.dwLastError); + + if (!dismountAllThreadParam.bReturn) + return FALSE; + + memset (&mountList, 0, sizeof (mountList)); + DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mountList, sizeof (mountList), &mountList, sizeof (mountList), &dwResult, NULL); + + // remove any custom label from registry + for (i = 0; i < 26; i++) + { + if ((prevMountList.ulMountedDrives & (1 << i)) && (!(mountList.ulMountedDrives & (1 << i))) && wcslen (prevMountList.wszLabel[i])) + { + UpdateDriveCustomLabel (i, prevMountList.wszLabel[i], FALSE); + } + } + + BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, 0, prevMountList.ulMountedDrives & ~mountList.ulMountedDrives); + + RefreshMainDlg (hwndDlg); + + if (nCurrentOS == WIN_2000 && RemoteSession && !IsAdmin ()) + LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), 0); + + NormalCursor(); + + if (unmount.nReturnCode != 0) + { + if (forceUnmount) + status = FALSE; + + if (unmount.nReturnCode == ERR_FILES_OPEN) + { + if (interact && IDYES == AskWarnYesNoTopmost ("UNMOUNTALL_LOCK_FAILED", hwndDlg)) + { + forceUnmount = TRUE; + goto retry; + } + + if (IsOSAtLeast (WIN_7)) + { + // Undo SHCNE_DRIVEREMOVED + DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, NULL, 0, &mountList, sizeof (mountList), &dwResult, NULL); + + for (i = 0; i < 26; i++) + { + if (mountList.ulMountedDrives & (1 << i)) + { + wchar_t root[] = { (wchar_t) i + L'A', L':', L'\\', 0 }; + SHChangeNotify (SHCNE_DRIVEADD, SHCNF_PATH, root, NULL); + } + } + } + + return FALSE; + } + + if (interact) + MessageBoxW (hwndDlg, GetString ("UNMOUNT_FAILED"), lpszTitle, MB_ICONERROR); + } + else + { + if (bBeep) + MessageBeep (0xFFFFFFFF); + } + + return status; +} + +static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) +{ + HWND driveList = GetDlgItem (MainDlg, IDC_DRIVELIST); + int selDrive = ListView_GetSelectionMark (driveList); + BOOL shared = FALSE, status = FALSE, bHeaderBakRetry = FALSE; + int mountedVolCount = 0; + vector devices; + int EffectiveVolumePkcs5 = CmdVolumePkcs5; + BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; + + /* Priority is given to command line parameters + * Default values used only when nothing specified in command line + */ + if (EffectiveVolumePkcs5 == 0) + EffectiveVolumePkcs5 = DefaultVolumePkcs5; + if (!EffectiveVolumeTrueCryptMode) + EffectiveVolumeTrueCryptMode = DefaultVolumeTrueCryptMode; + + VolumePassword.Length = 0; + mountOptions = defaultMountOptions; + bPrebootPasswordDlgMode = FALSE; + VolumePim = -1; + + if (selDrive == -1) + selDrive = 0; + + ResetWrongPwdRetryCount (); + + MultipleMountOperationInProgress = TRUE; + + do + { + if (!bHeaderBakRetry) + { + if (!CmdVolumePasswordValid && bPasswordPrompt) + { + int GuiPkcs5 = EffectiveVolumePkcs5; + BOOL GuiTrueCryptMode = EffectiveVolumeTrueCryptMode; + int GuiPim = CmdVolumePim; + PasswordDlgVolume[0] = '\0'; + if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &GuiTrueCryptMode, NULL, TRUE)) + goto ret; + else + { + VolumePkcs5 = GuiPkcs5; + VolumeTrueCryptMode = GuiTrueCryptMode; + VolumePim = GuiPim; + burn (&GuiPkcs5, sizeof(GuiPkcs5)); + burn (&GuiTrueCryptMode, sizeof(GuiTrueCryptMode)); + burn (&GuiPim, sizeof(GuiPim)); + } + } + else if (CmdVolumePasswordValid) + { + bPasswordPrompt = FALSE; + VolumePassword = CmdVolumePassword; + VolumePkcs5 = EffectiveVolumePkcs5; + VolumeTrueCryptMode = EffectiveVolumeTrueCryptMode; + VolumePim = CmdVolumePim; + } + + WaitCursor(); + + if (FirstCmdKeyFile) + KeyFilesApply (hwndDlg, &VolumePassword, FirstCmdKeyFile, NULL); + else if (KeyFilesEnable) + KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, NULL); + + } + + if (devices.empty()) + devices = GetAvailableHostDevices (true, false, true, true); + foreach (const HostDevice &drive, devices) + { + vector partitions = drive.Partitions; + partitions.insert (partitions.begin(), drive); + + foreach (const HostDevice &device, partitions) + { + wchar_t szFileName[TC_MAX_PATH]; + StringCbCopyW (szFileName, sizeof (szFileName), device.Path.c_str()); + BOOL mounted = IsMountedVolume (szFileName); + + // Skip other partitions of the disk if partition0 (whole disk) is mounted + if (!device.IsPartition && mounted) + break; + + if (device.Floppy) + break; + + if (device.HasUnencryptedFilesystem && !mountOptions.UseBackupHeader && !bHeaderBakRetry) + continue; + + if (!mounted) + { + int nDosDriveNo; + int driveAItem = -1, driveBItem = -1; + + while (LOWORD (GetItemLong (driveList, selDrive)) != 0xffff) + { + if(LOWORD (GetItemLong (driveList, selDrive)) != TC_MLIST_ITEM_FREE) + { + selDrive++; + continue; + } + nDosDriveNo = HIWORD(GetItemLong (driveList, selDrive)) - L'A'; + + /* don't use drives A: and B: for now until no other free drive found */ + if (nDosDriveNo == 0) + { + driveAItem = selDrive; + selDrive++; + continue; + } + if (nDosDriveNo == 1) + { + driveBItem = selDrive; + selDrive++; + continue; + } + break; + } + + if (LOWORD (GetItemLong (driveList, selDrive)) == 0xffff) + { + /* use A: or B: if available as a last resort */ + if (driveAItem >= 0) + { + nDosDriveNo = 0; + selDrive = driveAItem; + } + else if (driveBItem >= 0) + { + nDosDriveNo = 1; + selDrive = driveBItem; + } + else + goto ret; + } + + // First try user password then cached passwords + if ((mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, TRUE, FALSE)) > 0 + || ((VolumePassword.Length > 0) && ((mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, VolumePkcs5, VolumePim, VolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, TRUE, FALSE)) > 0))) + { + // A volume has been successfully mounted + + ResetWrongPwdRetryCount (); + + if (mounted == 2) + shared = TRUE; + + LoadDriveLetters (hwndDlg, driveList, (HIWORD (GetItemLong (GetDlgItem (MainDlg, IDC_DRIVELIST), selDrive)))); + selDrive++; + + if (bExplore) + { + WaitCursor(); + OpenVolumeExplorerWindow (nDosDriveNo); + NormalCursor(); + } + + if (bBeep) + MessageBeep (0xFFFFFFFF); + + status = TRUE; + + mountedVolCount++; + + // Skip other partitions of the disk if partition0 (whole disk) has been mounted + if (!device.IsPartition) + break; + } + } + } + } + + if (mountedVolCount < 1) + { + // Failed to mount any volume + + IncreaseWrongPwdRetryCount (1); + + if (WrongPwdRetryCountOverLimit () + && !mountOptions.UseBackupHeader + && !bHeaderBakRetry) + { + // Retry using embedded header backup (if any) + mountOptions.UseBackupHeader = TRUE; + bHeaderBakRetry = TRUE; + } + else if (bHeaderBakRetry) + { + mountOptions.UseBackupHeader = defaultMountOptions.UseBackupHeader; + bHeaderBakRetry = FALSE; + } + + if (!Silent && !bHeaderBakRetry) + { + WCHAR szTmp[4096]; + + StringCbPrintfW (szTmp, sizeof(szTmp), GetString (KeyFilesEnable || FirstCmdKeyFile ? "PASSWORD_OR_KEYFILE_WRONG_AUTOMOUNT" : "PASSWORD_WRONG_AUTOMOUNT")); + if (CheckCapsLock (hwndDlg, TRUE)) + StringCbCatW (szTmp, sizeof(szTmp), GetString ("PASSWORD_WRONG_CAPSLOCK_ON")); + + MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_ICONWARNING); + } + } + else if (bHeaderBakRetry) + { + // We have successfully mounted a volume using the header backup embedded in the volume (the header is damaged) + mountOptions.UseBackupHeader = defaultMountOptions.UseBackupHeader; + bHeaderBakRetry = FALSE; + + if (!Silent) + Warning ("HEADER_DAMAGED_AUTO_USED_HEADER_BAK", hwndDlg); + } + + if (!bHeaderBakRetry) + { + burn (&VolumePassword, sizeof (VolumePassword)); + burn (&VolumePkcs5, sizeof (VolumePkcs5)); + burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); + burn (&VolumePim, sizeof (VolumePim)); + burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); + burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); + } + + } while (bPasswordPrompt && mountedVolCount < 1); + + /* One or more volumes successfully mounted */ + + ResetWrongPwdRetryCount (); + + if (shared) + Warning ("DEVICE_IN_USE_INFO", hwndDlg); + + if (mountOptions.ProtectHiddenVolume) + { + if (mountedVolCount > 1) + Info ("HIDVOL_PROT_WARN_AFTER_MOUNT_PLURAL", hwndDlg); + else if (mountedVolCount == 1) + Info ("HIDVOL_PROT_WARN_AFTER_MOUNT", hwndDlg); + } + + if (status && CloseSecurityTokenSessionsAfterMount) + SecurityToken::CloseAllSessions(); + +ret: + MultipleMountOperationInProgress = FALSE; + + burn (&VolumePassword, sizeof (VolumePassword)); + burn (&VolumePkcs5, sizeof (VolumePkcs5)); + burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); + burn (&VolumePim, sizeof (VolumePim)); + burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); + burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); + + mountOptions.UseBackupHeader = defaultMountOptions.UseBackupHeader; + + RestoreDefaultKeyFilesParam (); + + if (UsePreferences) + bCacheInDriver = bCacheInDriverDefault; + + EnableDisableButtons (MainDlg); + + NormalCursor(); + + return status; +} + +typedef struct +{ + BOOL bPasswordPrompt; + BOOL bRet; +} MountAllDevicesThreadParam; + +void CALLBACK mountAllDevicesThreadProc(void* pArg, HWND hwndDlg) +{ + MountAllDevicesThreadParam* threadParam =(MountAllDevicesThreadParam*) pArg; + BOOL bPasswordPrompt = threadParam->bPasswordPrompt; + + threadParam->bRet = MountAllDevicesThreadCode (hwndDlg, bPasswordPrompt); +} + +static BOOL MountAllDevices (HWND hwndDlg, BOOL bPasswordPrompt) +{ + MountAllDevicesThreadParam param; + param.bPasswordPrompt = bPasswordPrompt; + param.bRet = FALSE; + + ShowWaitDialog (hwndDlg, FALSE, mountAllDevicesThreadProc, ¶m); + + return param.bRet; +} + +static void ChangePassword (HWND hwndDlg) +{ + INT_PTR result; + int newPimValue = -1; + + GetVolumePath (hwndDlg, szFileName, ARRAYSIZE (szFileName)); + + if (!TranslateVolumeID (hwndDlg, szFileName, ARRAYSIZE (szFileName))) + { + return; + } + + if (IsMountedVolume (szFileName)) + { + Warning (pwdChangeDlgMode == PCDM_CHANGE_PKCS5_PRF ? "MOUNTED_NO_PKCS5_PRF_CHANGE" : "MOUNTED_NOPWCHANGE", hwndDlg); + return; + } + + if (!VolumePathExists (szFileName)) + { + handleWin32Error (hwndDlg, SRC_POS); + return; + } + + bSysEncPwdChangeDlgMode = FALSE; + + result = DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_PASSWORDCHANGE_DLG), hwndDlg, + (DLGPROC) PasswordChangeDlgProc, (LPARAM) &newPimValue); + + if (result == IDOK) + { + switch (pwdChangeDlgMode) + { + case PCDM_CHANGE_PKCS5_PRF: + Info ("PKCS5_PRF_CHANGED", hwndDlg); + break; + + case PCDM_ADD_REMOVE_VOL_KEYFILES: + case PCDM_REMOVE_ALL_KEYFILES_FROM_VOL: + Info ("KEYFILE_CHANGED", hwndDlg); + break; + + case PCDM_CHANGE_PASSWORD: + default: + { + Info ("PASSWORD_CHANGED", hwndDlg); + if (newPimValue != -1) + { + // update the encoded volue in favorite XML if found + bool bFavoriteFound = false; + for (vector ::iterator favorite = FavoriteVolumes.begin(); + favorite != FavoriteVolumes.end(); favorite++) + { + if (favorite->Path == szFileName) + { + bFavoriteFound = true; + favorite->Pim = newPimValue; + SaveFavoriteVolumes (hwndDlg, FavoriteVolumes, false); + break; + } + } + + if (!bFavoriteFound) + { + for (vector ::iterator favorite = SystemFavoriteVolumes.begin(); + favorite != SystemFavoriteVolumes.end(); favorite++) + { + if (favorite->Path == szFileName) + { + bFavoriteFound = true; + favorite->Pim = newPimValue; + + if (AskYesNo("FAVORITE_PIM_CHANGED", hwndDlg) == IDYES) + { + SaveFavoriteVolumes (hwndDlg, SystemFavoriteVolumes, true); + } + break; + } + } + } + } + } + } + } +} + +// Change password of the system partition/drive +static void ChangeSysEncPassword (HWND hwndDlg, BOOL bOnlyChangeKDF) +{ + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + if (!BootEncStatus.DriveEncrypted + && !BootEncStatus.DriveMounted + && !BootEncStatus.VolumeHeaderPresent + && !SysEncryptionOrDecryptionRequired ()) + { + Warning ("SYS_DRIVE_NOT_ENCRYPTED", hwndDlg); + return; + } + + if (SysEncryptionOrDecryptionRequired () + || BootEncStatus.SetupInProgress) + { + Warning ("SYSTEM_ENCRYPTION_NOT_COMPLETED", hwndDlg); + return; + } + + if (CreateSysEncMutex ()) // If no instance of the wizard is currently taking care of system encryption + { + StringCbPrintfW (OrigKeyboardLayout, sizeof(OrigKeyboardLayout), L"%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF); + + bSysEncPwdChangeDlgMode = TRUE; + + if (bOnlyChangeKDF) + pwdChangeDlgMode = PCDM_CHANGE_PKCS5_PRF; + else + pwdChangeDlgMode = PCDM_CHANGE_PASSWORD; + + + INT_PTR result = DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_PASSWORDCHANGE_DLG), hwndDlg, (DLGPROC) PasswordChangeDlgProc); + + bSysEncPwdChangeDlgMode = FALSE; + + if (bKeyboardLayoutChanged) + { + // Restore the original keyboard layout + if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) + Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); + else + bKeyboardLayoutChanged = FALSE; + } + + bKeybLayoutAltKeyWarningShown = FALSE; + + if (result == IDOK) + { + switch (pwdChangeDlgMode) + { + case PCDM_CHANGE_PKCS5_PRF: + Info ("PKCS5_PRF_CHANGED", hwndDlg); + + if (!IsHiddenOSRunning()) + { + if (AskWarnYesNo ("SYS_HKD_ALGO_CHANGED_ASK_RESCUE_DISK", hwndDlg) == IDYES) + CreateRescueDisk (hwndDlg); + } + + break; + + case PCDM_ADD_REMOVE_VOL_KEYFILES: + case PCDM_REMOVE_ALL_KEYFILES_FROM_VOL: + // NOP - Keyfiles are not supported for system encryption + break; + + case PCDM_CHANGE_PASSWORD: + default: + Info ("PASSWORD_CHANGED", hwndDlg); + + if (!IsHiddenOSRunning()) + { + if (AskWarnYesNo ("SYS_PASSWORD_CHANGED_ASK_RESCUE_DISK", hwndDlg) == IDYES) + CreateRescueDisk (hwndDlg); + } + } + } + + CloseSysEncMutex (); + } + else + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); +} + +// Initiates or resumes encryption of the system partition/drive +static void EncryptSystemDevice (HWND hwndDlg) +{ + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + if (!BootEncStatus.DriveEncrypted + && !BootEncStatus.DriveMounted + && !SysEncryptionOrDecryptionRequired ()) + { + // System partition/drive is not encrypted (nothing to resume). Initiate the process. + + if (!MutexExistsOnSystem (TC_MUTEX_NAME_SYSENC)) // If no instance of the wizard is currently taking care of system encryption + { + LaunchVolCreationWizard (hwndDlg, L"/sysenc"); + } + else + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); + + return; + } + else if (SysEncryptionOrDecryptionRequired ()) + { + // System partition/drive encryption already initiated but is incomplete -- attempt to resume the process. + // Note that this also covers the pretest phase and paused decryption (reverses decrypting and starts encrypting) + + if (!MutexExistsOnSystem (TC_MUTEX_NAME_SYSENC)) // If no instance of the wizard is currently taking care of system encryption + { + LaunchVolCreationWizard (hwndDlg, L"/sysenc"); + } + else + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); + } + else if (SysDriveOrPartitionFullyEncrypted (FALSE)) + { + // System partition/drive appears to be fully encrypted + Info ("SYS_PARTITION_OR_DRIVE_APPEARS_FULLY_ENCRYPTED", hwndDlg); + return; + } +} + +// Initiates decryption of the system partition/drive +static void DecryptSystemDevice (HWND hwndDlg) +{ + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + if (!BootEncStatus.DriveEncrypted + && !BootEncStatus.DriveMounted + && !BootEncStatus.DeviceFilterActive + && !BootEncStatus.VolumeHeaderPresent + && !SysEncryptionOrDecryptionRequired ()) + { + Warning ("SYS_DRIVE_NOT_ENCRYPTED", hwndDlg); + return; + } + + if (IsHiddenOSRunning()) + { + Warning ("CANNOT_DECRYPT_HIDDEN_OS", hwndDlg); + return; + } + + if (AskNoYes ("CONFIRM_DECRYPT_SYS_DEVICE", hwndDlg) == IDNO) + return; + + if (AskWarnNoYes ("CONFIRM_DECRYPT_SYS_DEVICE_CAUTION", hwndDlg) == IDNO) + return; + + if (CreateSysEncMutex ()) // If no instance of the wizard is currently taking care of system encryption + { + try + { + // User-mode app may have crashed and its mutex may have gotten lost, so we need to check the driver status too + if (BootEncStatus.SetupInProgress) + { + int attempts = 20; + + BootEncObj->AbortSetup (); + while (BootEncStatus.SetupInProgress && attempts > 0) + { + Sleep (100); + BootEncStatus = BootEncObj->GetStatus(); + attempts--; + WaitCursor(); + } + } + } + catch (Exception &e) + { + e.Show (MainDlg); + } + NormalCursor (); + + if (BootEncStatus.SetupInProgress) + { + CloseSysEncMutex (); + Error ("SYS_ENCRYPTION_OR_DECRYPTION_IN_PROGRESS", hwndDlg); + return; + } + + CloseSysEncMutex (); + LaunchVolCreationWizard (hwndDlg, L"/dsysenc"); + } + else + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); +} + +// Initiates the process of creation of a hidden operating system +static void CreateHiddenOS (HWND hwndDlg) +{ + + // Display brief information as to what a hidden operating system is and what it's good for. This needs to be + // done, because if the system partition/drive is currently encrypted, the wizard will not display any + // such information, but will exit (displaying only an error meessage). + Info("HIDDEN_OS_PREINFO", hwndDlg); + + LaunchVolCreationWizard (hwndDlg, L"/isysenc"); +} + +static void DecryptNonSysDevice (HWND hwndDlg, BOOL bResolveAmbiguousSelection, BOOL bUseDriveListSel) +{ + wstring scPath; + + if (bResolveAmbiguousSelection) + { + scPath = ResolveAmbiguousSelection (hwndDlg, NULL); + + if (scPath.empty ()) + { + // The user selected Cancel + return; + } + } + else if (bUseDriveListSel) + { + // Decrypt mounted volume selected in the main drive list + + LPARAM lLetter = GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST)); + + if (LOWORD (lLetter) != 0xffff) + { + VOLUME_PROPERTIES_STRUCT prop; + DWORD bytesReturned; + + memset (&prop, 0, sizeof (prop)); + prop.driveNo = (wchar_t) HIWORD (lLetter) - L'A'; + + if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &bytesReturned, NULL)) + { + handleWin32Error (MainDlg, SRC_POS); + return; + } + + scPath = prop.wszVolume; + } + else + return; + } + else + { + // Decrypt volume specified in the input field below the main drive list + + wchar_t volPath [TC_MAX_PATH]; + + GetVolumePath (MainDlg, volPath, ARRAYSIZE (volPath)); + + scPath = volPath; + } + + if (scPath.empty ()) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + return; + } + + WaitCursor(); + + switch (IsSystemDevicePath (scPath.c_str (), MainDlg, TRUE)) + { + case 1: + case 2: + // The user wants to decrypt the system partition/drive. Divert to the appropriate function. + + NormalCursor (); + + DecryptSystemDevice (hwndDlg); + return; + } + + WaitCursor(); + + // Make sure the user is not attempting to decrypt a partition on an entirely encrypted system drive. + if (IsNonSysPartitionOnSysDrive (scPath.c_str ()) == 1) + { + if (WholeSysDriveEncryption (TRUE)) + { + // The system drive is entirely encrypted and the encrypted OS is running + + NormalCursor (); + + Warning ("CANT_DECRYPT_PARTITION_ON_ENTIRELY_ENCRYPTED_SYS_DRIVE", hwndDlg); + return; + } + } + else if (TCBootLoaderOnInactiveSysEncDrive ((wchar_t *) scPath.c_str ())) + { + // The system drive MAY be entirely encrypted (external access without PBA) and the potentially encrypted OS is not running + + NormalCursor (); + + Warning ("CANT_DECRYPT_PARTITION_ON_ENTIRELY_ENCRYPTED_SYS_DRIVE_UNSURE", hwndDlg); + + // We allow the user to continue as we don't know if the drive is really an encrypted system drive. + // If it is, the user has been warned and he will not be able to start decrypting, because the + // format wizard will not enable (nor will it allow the user to enable) the mount option for + // external without-PBA access (the user will receive the 'Incorrect password' error message). + } + + NormalCursor (); + + + if (AskNoYesString ((wstring (GetString ("CONFIRM_DECRYPT_NON_SYS_DEVICE")) + L"\n\n" + scPath).c_str(), hwndDlg) == IDNO) + return; + + if (AskWarnNoYes ("CONFIRM_DECRYPT_NON_SYS_DEVICE_CAUTION", hwndDlg) == IDNO) + return; + + LaunchVolCreationWizard (hwndDlg, (wstring (L"/inplacedec \"") + scPath + L"\"").c_str ()); +} + +// Blindly attempts (without any checks) to instruct the wizard to resume whatever system encryption process +// had been interrupted or not started but scheduled or exptected to start. +static void ResumeInterruptedSysEncProcess (HWND hwndDlg) +{ + if (!MutexExistsOnSystem (TC_MUTEX_NAME_SYSENC)) // If no instance of the wizard is currently taking care of system encryption + { + LaunchVolCreationWizard (MainDlg, L"/csysenc"); + } + else + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); +} + +void CreateRescueDisk (HWND hwndDlg) +{ + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + if (IsHiddenOSRunning()) + { + Warning ("CANNOT_CREATE_RESCUE_DISK_ON_HIDDEN_OS", hwndDlg); + return; + } + + if (!BootEncStatus.DriveEncrypted + && !BootEncStatus.DriveMounted + && !BootEncStatus.VolumeHeaderPresent + && !SysEncryptionOrDecryptionRequired ()) + { + Warning ("SYS_DRIVE_NOT_ENCRYPTED", hwndDlg); + return; + } + + if (SysEncryptionOrDecryptionRequired () + || BootEncStatus.SetupInProgress) + { + Warning ("SYSTEM_ENCRYPTION_NOT_COMPLETED", hwndDlg); + return; + } + + if (CreateSysEncMutex ()) // If no instance of the wizard is currently taking care of system encryption + { + try + { + wchar_t szTmp [8096]; + wchar_t szRescueDiskISO [TC_MAX_PATH+1]; + + if (AskOkCancel ("RESCUE_DISK_NON_WIZARD_CREATION_SELECT_PATH", hwndDlg) != IDOK) + { + CloseSysEncMutex (); + return; + } + + wchar_t initialDir[MAX_PATH]; + SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, 0, initialDir); + + if (!BrowseFilesInDir (hwndDlg, "OPEN_TITLE", initialDir, szRescueDiskISO, FALSE, TRUE, NULL, L"VeraCrypt Rescue Disk.iso", L"iso")) + { + CloseSysEncMutex (); + return; + } + + WaitCursor(); + BootEncObj->CreateRescueIsoImage (false, szRescueDiskISO); + + StringCbPrintfW (szTmp, sizeof szTmp, + GetString (IsWindowsIsoBurnerAvailable() ? "RESCUE_DISK_NON_WIZARD_CREATION_WIN_ISOBURN" : "RESCUE_DISK_NON_WIZARD_CREATION_BURN"), + szRescueDiskISO); + + if (IsWindowsIsoBurnerAvailable()) + { + if (AskYesNoString (szTmp, hwndDlg) == IDYES) + LaunchWindowsIsoBurner (MainDlg, szRescueDiskISO); + } + else + InfoDirect (szTmp, hwndDlg); + } + catch (Exception &e) + { + e.Show (hwndDlg); + Error ("ERROR_CREATING_RESCUE_DISK", hwndDlg); + } + CloseSysEncMutex (); + + NormalCursor (); + } + else + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); +} + +static void VerifyRescueDisk (HWND hwndDlg, bool checkIsoFile) +{ + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + if (!BootEncStatus.DriveEncrypted + && !BootEncStatus.DriveMounted + && !BootEncStatus.VolumeHeaderPresent + && !SysEncryptionOrDecryptionRequired ()) + { + Warning ("SYS_DRIVE_NOT_ENCRYPTED", hwndDlg); + return; + } + + if (SysEncryptionOrDecryptionRequired () + || BootEncStatus.SetupInProgress) + { + Warning ("SYSTEM_ENCRYPTION_NOT_COMPLETED", hwndDlg); + return; + } + + if (CreateSysEncMutex ()) // If no instance of the wizard is currently taking care of system encryption + { + try + { + if (!checkIsoFile && (AskOkCancel ("RESCUE_DISK_NON_WIZARD_CHECK_INSERT", hwndDlg) != IDOK)) + { + CloseSysEncMutex (); + return; + } + + // Create a temporary up-to-date rescue disk image in RAM (with it the CD/DVD content will be compared) + BootEncObj->CreateRescueIsoImage (false, L""); + + + if (checkIsoFile) + { + wchar_t szRescueDiskISO [TC_MAX_PATH+1]; + wchar_t initialDir[MAX_PATH]; + SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, 0, initialDir); + + if (!BrowseFilesInDir (hwndDlg, "OPEN_TITLE", initialDir, szRescueDiskISO, FALSE, FALSE, NULL, L"VeraCrypt Rescue Disk.iso", L"iso")) + { + CloseSysEncMutex (); + return; + } + + WaitCursor(); + if (!BootEncObj->VerifyRescueDiskIsoImage (szRescueDiskISO)) + Error ("RESCUE_DISK_ISO_IMAGE_CHECK_FAILED", hwndDlg); + else + Info ("RESCUE_DISK_ISO_IMAGE_CHECK_PASSED", hwndDlg); + } + else + { + WaitCursor(); + if (!BootEncObj->VerifyRescueDisk ()) + Error ("RESCUE_DISK_NON_WIZARD_CHECK_FAILED", hwndDlg); + else + Info ("RESCUE_DISK_NON_WIZARD_CHECK_PASSED", hwndDlg); + } + } + catch (Exception &e) + { + e.Show (MainDlg); + Error ("RESCUE_DISK_NON_WIZARD_CHECK_FAILED", hwndDlg); + } + CloseSysEncMutex (); + + NormalCursor (); + } + else + Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE", hwndDlg); +} + +static void ShowSystemEncryptionStatus (HWND hwndDlg) +{ + try + { + BootEncStatus = BootEncObj->GetStatus(); + } + catch (Exception &e) + { + e.Show (MainDlg); + } + + if (GetAsyncKeyState (VK_SHIFT) < 0 && GetAsyncKeyState (VK_CONTROL) < 0) + { + // Ctrl+Shift held (for debugging purposes) + + DebugMsgBox ("Debugging information for system encryption:\n\nDeviceFilterActive: %d\nBootLoaderVersion: %x\nSetupInProgress: %d\nSetupMode: %d\nVolumeHeaderPresent: %d\nDriveMounted: %d\nDriveEncrypted: %d\n" + "HiddenSystem: %d\nHiddenSystemPartitionStart: %I64d\n" + "ConfiguredEncryptedAreaStart: %I64d\nConfiguredEncryptedAreaEnd: %I64d\nEncryptedAreaStart: %I64d\nEncryptedAreaEnd: %I64d\nEncrypted: %I64d%%", + BootEncStatus.DeviceFilterActive, + BootEncStatus.BootLoaderVersion, + BootEncStatus.SetupInProgress, + BootEncStatus.SetupMode, + BootEncStatus.VolumeHeaderPresent, + BootEncStatus.DriveMounted, + BootEncStatus.DriveEncrypted, + BootEncStatus.HiddenSystem ? 1 : 0, + BootEncStatus.HiddenSystemPartitionStart, + BootEncStatus.ConfiguredEncryptedAreaStart, + BootEncStatus.ConfiguredEncryptedAreaEnd, + BootEncStatus.EncryptedAreaStart, + BootEncStatus.EncryptedAreaEnd, + !BootEncStatus.DriveEncrypted ? 0 : (BootEncStatus.EncryptedAreaEnd + 1 - BootEncStatus.EncryptedAreaStart) * 100I64 / (BootEncStatus.ConfiguredEncryptedAreaEnd + 1 - BootEncStatus.ConfiguredEncryptedAreaStart)); + } + + if (!BootEncStatus.DriveEncrypted && !BootEncStatus.DriveMounted) + { + Info ("SYS_DRIVE_NOT_ENCRYPTED", hwndDlg); + return; + } + + DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_VOLUME_PROPERTIES), hwndDlg, + (DLGPROC) VolumePropertiesDlgProc, (LPARAM) TRUE); + +} + +static void ResumeInterruptedNonSysInplaceEncProcess (BOOL bDecrypt) +{ + // IMPORTANT: This function must not check any config files! Otherwise, if a config file was lost or corrupt, + // the user would not be able resume encryption and the data on the volume would be inaccessible. + + LaunchVolCreationWizard (MainDlg, bDecrypt? L"/resumeinplacedec" : L"/zinplace"); +} + +BOOL SelectContainer (HWND hwndDlg) +{ + if (BrowseFiles (hwndDlg, "OPEN_VOL_TITLE", szFileName, bHistory, FALSE, NULL) == FALSE) + return FALSE; + + AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory); + EnableDisableButtons (hwndDlg); + SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST)); + return TRUE; +} + +BOOL SelectPartition (HWND hwndDlg) +{ + RawDevicesDlgParam param; + param.pszFileName = szFileName; + INT_PTR nResult = DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_RAWDEVICES_DLG), hwndDlg, + (DLGPROC) RawDevicesDlgProc, (LPARAM) & param); + if (nResult == IDOK) + { + AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory); + EnableDisableButtons (hwndDlg); + SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST)); + return TRUE; + } + + return FALSE; +} + +static void WipeCache (HWND hwndDlg, BOOL silent) +{ + DWORD dwResult; + BOOL bResult; + + bResult = DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); + if (hwndDlg == NULL) + return; + + if (bResult == FALSE) + handleWin32Error (hwndDlg, SRC_POS); + else + { + EnableDisableButtons (hwndDlg); + + if (!silent) + InfoBalloon ("PASSWORD_CACHE_WIPED_SHORT", "PASSWORD_CACHE_WIPED", hwndDlg); + } +} + +static void Benchmark (HWND hwndDlg) +{ + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_BENCHMARK_DLG), hwndDlg, + (DLGPROC) BenchmarkDlgProc, (LPARAM) NULL); +} + + +static BOOL CheckMountList (HWND hwndDlg, BOOL bForceTaskBarUpdate) +{ + MOUNT_LIST_STRUCT current; + static BootEncryptionStatus newBootEncStatus; + static BOOL lastbUseDifferentTrayIconIfVolMounted = bUseDifferentTrayIconIfVolMounted; + static uint32 lastUlMountedDrives = 0; + + GetMountList (¤t); + + if ((bForceTaskBarUpdate || current.ulMountedDrives != lastUlMountedDrives || bUseDifferentTrayIconIfVolMounted != lastbUseDifferentTrayIconIfVolMounted) + && TaskBarIconMutex != NULL) + { + lastUlMountedDrives = current.ulMountedDrives; + lastbUseDifferentTrayIconIfVolMounted = bUseDifferentTrayIconIfVolMounted; + + TaskBarIconChange (MainDlg, current.ulMountedDrives != 0 && bUseDifferentTrayIconIfVolMounted ? IDI_TRUECRYPT_MOUNTED_ICON : IDI_TRUECRYPT_ICON); + } + + if (bForceTaskBarUpdate) + { + return TRUE; + } + + if (LastKnownLogicalDrives != GetUsedLogicalDrives() + || memcmp (&LastKnownMountList, ¤t, sizeof (current)) != 0) + { + wchar_t selDrive; + + WaitCursor (); + LastKnownMountList = current; + + selDrive = (wchar_t) HIWORD (GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST))); + LoadDriveLetters (hwndDlg, GetDlgItem (MainDlg, IDC_DRIVELIST), 0); + NormalCursor (); + + if (selDrive != ((wchar_t) 0xFFFF) && (current.ulMountedDrives & (1 << (selDrive - L'A'))) == 0 && !IsDriveAvailable (selDrive - L'A')) + { + nSelectedDriveIndex = -1; + return FALSE; + } + + if (selDrive != ((wchar_t) 0xFFFF)) + SelectItem (GetDlgItem (MainDlg, IDC_DRIVELIST),selDrive); + } + + try + { + newBootEncStatus = BootEncObj->GetStatus(); + + if (newBootEncStatus.SetupInProgress != RecentBootEncStatus.SetupInProgress + || newBootEncStatus.EncryptedAreaEnd != RecentBootEncStatus.EncryptedAreaEnd + || newBootEncStatus.DriveEncrypted != RecentBootEncStatus.DriveEncrypted + || newBootEncStatus.DriveMounted != RecentBootEncStatus.DriveMounted + || newBootEncStatus.SetupMode != RecentBootEncStatus.SetupMode + || newBootEncStatus.EncryptedAreaStart != RecentBootEncStatus.EncryptedAreaStart) + { + /* System encryption status change */ + + wchar_t selDrive; + int driveLetterToRefresh; + + if (RecentBootEncStatus.DriveMounted == newBootEncStatus.DriveMounted) // If an icon (and whole new line) for a system device isn't to be added/removed + { + // Partial refresh + if (WholeSysDriveEncryption (TRUE)) + { + // System drive (not just partition) + driveLetterToRefresh = ENC_SYSDRIVE_PSEUDO_DRIVE_LETTER; + } + else + { + // System partition + driveLetterToRefresh = GetSystemDriveLetter (); + } + } + else + { + // Full rebuild of the mount list + driveLetterToRefresh = 0; + } + + selDrive = (wchar_t) HIWORD (GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST))); + LoadDriveLetters (hwndDlg, GetDlgItem (MainDlg, IDC_DRIVELIST), driveLetterToRefresh); + + RecentBootEncStatus = newBootEncStatus; + + if (selDrive != ((wchar_t) 0xFFFF) && (current.ulMountedDrives & (1 << (selDrive - L'A'))) == 0 && !IsDriveAvailable (selDrive - L'A')) + { + nSelectedDriveIndex = -1; + } + + if (selDrive != ((wchar_t) 0xFFFF)) + { + SelectItem (GetDlgItem (MainDlg, IDC_DRIVELIST),selDrive); + } + } + + /* Miscellaneous notifications */ + + // Hibernation prevention notifications + if (newBootEncStatus.HibernationPreventionCount != RecentBootEncStatus.HibernationPreventionCount + && !bHibernationPreventionNotified) + { + bHibernationPreventionNotified = TRUE; + RecentBootEncStatus.HibernationPreventionCount = newBootEncStatus.HibernationPreventionCount; + + if (IsHiddenOSRunning() && BootEncObj->GetSystemDriveConfiguration().ExtraBootPartitionPresent) + WarningTopMost ("HIDDEN_OS_HIBERNATION_PREVENTED", hwndDlg); + else + WarningTopMost ("SYS_ENC_HIBERNATION_PREVENTED", hwndDlg); + } + + // Write mode prevention (hidden OS leak protection) + if (IsHiddenOSRunning()) + { + if (newBootEncStatus.HiddenSysLeakProtectionCount != RecentBootEncStatus.HiddenSysLeakProtectionCount + && !bHiddenSysLeakProtNotifiedDuringSession) + { + bHiddenSysLeakProtNotifiedDuringSession = TRUE; + + switch (HiddenSysLeakProtectionNotificationStatus) + { + case TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_COMPACT: + { + char *tmp[] = {0, "HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO", "SHOW_MORE_INFORMATION", "DO_NOT_SHOW_THIS_AGAIN", "CONTINUE", 0}; + switch (AskMultiChoice ((void **) tmp, FALSE, hwndDlg)) + { + case 1: + InfoDirect ((wstring (GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO")) + + L"\n\n" + + GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION") + + L"\n\n\n" + + GetString ("DECOY_TO_HIDDEN_OS_DATA_TRANSFER_HOWTO")).c_str(), hwndDlg); + break; + + case 2: + // No more warnings will be shown + if (ConfigBuffer == NULL) + { + // We need to load the config file because it is not done automatically when + // launched from the sys startup sequence (and SaveSettings would start by _loading_ + // the settings to cache). + LoadSettings (MainDlg); + } + HiddenSysLeakProtectionNotificationStatus = TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_DISABLED; + SaveSettings (MainDlg); + break; + + default: + // NOP + break; + } + } + break; + + case TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_DISABLED: + // NOP + break; + + case TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_NONE: + default: + { + // First time warning -- include technical explanation + InfoDirect ((wstring (GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO")) + + L"\n\n" + + GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION") + + L"\n\n\n" + + GetString ("DECOY_TO_HIDDEN_OS_DATA_TRANSFER_HOWTO")).c_str(), hwndDlg); + + // Further warnings will not include the explanation (and will allow disabling) + + if (ConfigBuffer == NULL) + { + // We need to load the config file because it is not done automatically when + // launched from the sys startup sequence (and SaveSettings would start by _loading_ + // the settings to cache). + LoadSettings (MainDlg); + } + HiddenSysLeakProtectionNotificationStatus = TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_COMPACT; + SaveSettings (MainDlg); + } + break; + } + } + } + } + catch (...) + { + // NOP + } + + return TRUE; +} + + +void DisplayDriveListContextMenu (HWND hwndDlg, LPARAM lParam) +{ + /* Drive list context menu */ + DWORD mPos; + int menuItem; + HMENU popup = CreatePopupMenu (); + HWND hList = GetDlgItem (hwndDlg, IDC_DRIVELIST); + + SetFocus (hList); + + switch (LOWORD (GetSelectedLong (hList))) + { + case TC_MLIST_ITEM_FREE: + + // No mounted volume at this drive letter + + AppendMenuW (popup, MF_STRING, IDM_MOUNT_VOLUME, GetString ("IDM_MOUNT_VOLUME")); + AppendMenu (popup, MF_SEPARATOR, 0, L""); + AppendMenuW (popup, MF_STRING, IDPM_SELECT_FILE_AND_MOUNT, GetString ("SELECT_FILE_AND_MOUNT")); + AppendMenuW (popup, MF_STRING, IDPM_SELECT_DEVICE_AND_MOUNT, GetString ("SELECT_DEVICE_AND_MOUNT")); + break; + + case TC_MLIST_ITEM_NONSYS_VOL: + + // There's a mounted non-system volume at this drive letter + + AppendMenuW (popup, MF_STRING, IDM_UNMOUNT_VOLUME, GetString ("DISMOUNT")); + AppendMenuW (popup, MF_STRING, IDPM_OPEN_VOLUME, GetString ("OPEN")); + AppendMenu (popup, MF_SEPARATOR, 0, L""); + AppendMenuW (popup, MF_STRING, IDPM_CHECK_FILESYS, GetString ("IDPM_CHECK_FILESYS")); + AppendMenuW (popup, MF_STRING, IDPM_REPAIR_FILESYS, GetString ("IDPM_REPAIR_FILESYS")); + AppendMenu (popup, MF_SEPARATOR, 0, L""); + AppendMenuW (popup, MF_STRING, IDPM_ADD_TO_FAVORITES, GetString ("IDPM_ADD_TO_FAVORITES")); + AppendMenuW (popup, MF_STRING, IDPM_ADD_TO_SYSTEM_FAVORITES, GetString ("IDPM_ADD_TO_SYSTEM_FAVORITES")); + AppendMenu (popup, MF_SEPARATOR, 0, L""); + AppendMenuW (popup, MF_STRING, IDM_DECRYPT_NONSYS_VOL, GetString ("IDM_DECRYPT_NONSYS_VOL")); + AppendMenu (popup, MF_SEPARATOR, 0, L""); + AppendMenuW (popup, MF_STRING, IDM_VOLUME_PROPERTIES, GetString ("IDPM_PROPERTIES")); + break; + + case TC_MLIST_ITEM_SYS_PARTITION: + case TC_MLIST_ITEM_SYS_DRIVE: + + // System partition/drive + + PopulateSysEncContextMenu (popup, FALSE); + break; + } + + if (lParam) + { + mPos=GetMessagePos(); + } + else + { + POINT pt = {0}; + if (ListView_GetItemPosition (hList, nSelectedDriveIndex, &pt)) + { + pt.x += 2 + ::GetSystemMetrics(SM_CXICON); + pt.y += 2; + } + ClientToScreen (hList, &pt); + mPos = MAKELONG (pt.x, pt.y); + } + + menuItem = TrackPopupMenu (popup, + TPM_RETURNCMD | TPM_LEFTBUTTON, + GET_X_LPARAM(mPos), + GET_Y_LPARAM(mPos), + 0, + hwndDlg, + NULL); + + DestroyMenu (popup); + + switch (menuItem) + { + case IDPM_SELECT_FILE_AND_MOUNT: + if (SelectContainer (hwndDlg)) + MountSelectedVolume (hwndDlg, FALSE); + break; + + case IDPM_SELECT_DEVICE_AND_MOUNT: + if (SelectPartition (hwndDlg)) + MountSelectedVolume (hwndDlg, FALSE); + break; + + case IDPM_CHECK_FILESYS: + case IDPM_REPAIR_FILESYS: + { + LPARAM lLetter = GetSelectedLong (hList); + + if (LOWORD (lLetter) != 0xffff) + CheckFilesystem (hwndDlg, (wchar_t) HIWORD (lLetter) - L'A', menuItem == IDPM_REPAIR_FILESYS); + } + break; + + case IDM_UNMOUNT_VOLUME: + if (CheckMountList (hwndDlg, FALSE)) + Dismount (hwndDlg, -2); + break; + + case IDM_DECRYPT_NONSYS_VOL: + if (CheckMountList (hwndDlg, FALSE)) + DecryptNonSysDevice (hwndDlg, FALSE, TRUE); + break; + + case IDPM_OPEN_VOLUME: + { + LPARAM state; + if (lParam) + nSelectedDriveIndex = ((LPNMITEMACTIVATE)lParam)->iItem; + else + nSelectedDriveIndex = ListView_GetSelectionMark (hList); + state = GetItemLong (hList, nSelectedDriveIndex ); + + WaitCursor (); + OpenVolumeExplorerWindow (HIWORD(state) - L'A'); + NormalCursor (); + } + break; + + case IDM_VOLUME_PROPERTIES: + DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_VOLUME_PROPERTIES), hwndDlg, + (DLGPROC) VolumePropertiesDlgProc, (LPARAM) FALSE); + break; + + case IDM_MOUNT_VOLUME: + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + mountOptions = defaultMountOptions; + bPrebootPasswordDlgMode = FALSE; + + if (CheckMountList (hwndDlg, FALSE)) + _beginthread(mountThreadFunction, 0, hwndDlg); + } + break; + + case IDPM_ADD_TO_FAVORITES: + case IDPM_ADD_TO_SYSTEM_FAVORITES: + { + LPARAM selectedDrive = GetSelectedLong (hList); + + if (LOWORD (selectedDrive) == TC_MLIST_ITEM_NONSYS_VOL) + AddMountedVolumeToFavorites (hwndDlg, HIWORD (selectedDrive) - L'A', menuItem == IDPM_ADD_TO_SYSTEM_FAVORITES); + } + break; + + default: + SendMessage (MainDlg, WM_COMMAND, menuItem, NULL); + break; + } +} + + +/* Except in response to the WM_INITDIALOG and WM_ENDSESSION messages, the dialog box procedure + should return nonzero if it processes a message, and zero if it does not. */ +BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + static UINT taskBarCreatedMsg; + WORD lw = LOWORD (wParam); + WORD hw = HIWORD (wParam); + + switch (uMsg) + { + case WM_HOTKEY: + + HandleHotKey (hwndDlg, wParam); + return 1; + + case WM_INITDIALOG: + { + int exitCode = 0; + + MainDlg = hwndDlg; + + if (IsTrueCryptInstallerRunning()) + AbortProcess ("TC_INSTALLER_IS_RUNNING"); + + // Set critical default options in case UsePreferences is false + bPreserveTimestamp = defaultMountOptions.PreserveTimestamp = TRUE; + bShowDisconnectedNetworkDrives = FALSE; + bHideWaitingDialog = FALSE; + + ResetWrongPwdRetryCount (); + + ExtractCommandLine (hwndDlg, (wchar_t *) lParam); + + try + { + BootEncObj->SetParentWindow (hwndDlg); + BootEncStatus = BootEncObj->GetStatus(); + RecentBootEncStatus = BootEncStatus; + } + catch (...) + { + // NOP + } + + if (UsePreferences) + { + // General preferences + LoadSettings (hwndDlg); + + // Keyfiles + LoadDefaultKeyFilesParam (); + RestoreDefaultKeyFilesParam (); + } + + if (ComServerMode) + { + InitDialog (hwndDlg); + + if (!ComServerMain ()) + { + handleWin32Error (hwndDlg, SRC_POS); + exit (1); + } + exit (0); + } + + if (CmdMountOptionsValid) + mountOptions = CmdMountOptions; + + InitMainDialog (hwndDlg); + + try + { + if (IsHiddenOSRunning()) + { + uint32 driverConfig = ReadDriverConfigurationFlags(); + if (BootEncObj->GetInstalledBootLoaderVersion() != VERSION_NUM) + Warning ("UPDATE_TC_IN_HIDDEN_OS_TOO", hwndDlg); + if ( !(driverConfig & TC_DRIVER_CONFIG_DISABLE_EVIL_MAID_ATTACK_DETECTION) + && !BootEncObj->CheckBootloaderFingerprint ()) + Warning ("BOOT_LOADER_FINGERPRINT_CHECK_FAILED", hwndDlg); + } + else if (SysDriveOrPartitionFullyEncrypted (TRUE)) + { + uint32 driverConfig = ReadDriverConfigurationFlags(); + if (BootEncObj->GetInstalledBootLoaderVersion() != VERSION_NUM) + { + Warning ("BOOT_LOADER_VERSION_DIFFERENT_FROM_DRIVER_VERSION", hwndDlg); + } + if ( !(driverConfig & TC_DRIVER_CONFIG_DISABLE_EVIL_MAID_ATTACK_DETECTION) + && !BootEncObj->CheckBootloaderFingerprint ()) + Warning ("BOOT_LOADER_FINGERPRINT_CHECK_FAILED", hwndDlg); + } + } + catch (...) { } + + // Automount + if (bAuto || (Quit && szFileName[0] != 0)) + { + // No drive letter specified on command line + if (commandLineDrive == 0) + szDriveLetter[0] = (wchar_t) GetFirstAvailableDrive () + L'A'; + + if (bAutoMountDevices) + { + defaultMountOptions = mountOptions; + if (FirstCmdKeyFile) + { + KeyFilesEnable = defaultKeyFilesParam.EnableKeyFiles = TRUE; + KeyFileCloneAll (FirstCmdKeyFile, &FirstKeyFile); + KeyFileCloneAll (FirstCmdKeyFile, &defaultKeyFilesParam.FirstKeyFile); + } + + if (!MountAllDevices (hwndDlg, !Silent && !CmdVolumePasswordValid && IsPasswordCacheEmpty())) + exitCode = 1; + } + + if (bAutoMountFavorites) + { + defaultMountOptions = mountOptions; + if (FirstCmdKeyFile) + { + KeyFilesEnable = defaultKeyFilesParam.EnableKeyFiles = TRUE; + KeyFileCloneAll (FirstCmdKeyFile, &FirstKeyFile); + KeyFileCloneAll (FirstCmdKeyFile, &defaultKeyFilesParam.FirstKeyFile); + } + + if (!MountFavoriteVolumes (hwndDlg, FALSE, LogOn)) + exitCode = 1; + } + + if (szFileName[0] != 0 && !TranslateVolumeID (hwndDlg, szFileName, ARRAYSIZE (szFileName))) + { + exitCode = 1; + } + else if (szFileName[0] != 0 && !IsMountedVolume (szFileName)) + { + BOOL mounted = FALSE; + int EffectiveVolumePkcs5 = CmdVolumePkcs5; + BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; + BOOL bEffectiveTryEmptyPasswordWhenKeyfileUsed = bCmdTryEmptyPasswordWhenKeyfileUsedValid? bCmdTryEmptyPasswordWhenKeyfileUsed : bTryEmptyPasswordWhenKeyfileUsed; + + if (!VolumePathExists (szFileName)) + { + handleWin32Error (hwndDlg, SRC_POS); + } + else + { + /* Priority is given to command line parameters + * Default values used only when nothing specified in command line + */ + if (EffectiveVolumePkcs5 == 0) + EffectiveVolumePkcs5 = DefaultVolumePkcs5; + if (!EffectiveVolumeTrueCryptMode) + EffectiveVolumeTrueCryptMode = DefaultVolumeTrueCryptMode; + + // Command line password or keyfiles + if (CmdVolumePassword.Length != 0 || (FirstCmdKeyFile && (CmdVolumePasswordValid || bEffectiveTryEmptyPasswordWhenKeyfileUsed))) + { + BOOL reportBadPasswd = CmdVolumePassword.Length > 0; + + if (FirstCmdKeyFile) + KeyFilesApplyWithPin (hwndDlg, &CmdVolumePassword, CmdTokenPin, FirstCmdKeyFile, szFileName); + + mounted = MountVolume (hwndDlg, szDriveLetter[0] - L'A', + szFileName, &CmdVolumePassword, EffectiveVolumePkcs5, CmdVolumePim, EffectiveVolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, + &mountOptions, Silent, reportBadPasswd); + + burn (&CmdVolumePassword, sizeof (CmdVolumePassword)); + } + else + { + // Cached password + mounted = MountVolume (hwndDlg, szDriveLetter[0] - L'A', szFileName, NULL, EffectiveVolumePkcs5, CmdVolumePim, EffectiveVolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); + } + + if (FirstCmdKeyFile) + { + KeyFileRemoveAll (&FirstKeyFile); + FirstKeyFile = FirstCmdKeyFile; + KeyFilesEnable = TRUE; + } + + // Ask user for password + while (!mounted && !Silent) + { + int GuiPkcs5 = EffectiveVolumePkcs5; + int GuiPim = CmdVolumePim; + BOOL GuiTrueCryptMode = EffectiveVolumeTrueCryptMode; + VolumePassword.Length = 0; + + StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume),szFileName); + if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &GuiTrueCryptMode, NULL, TRUE)) + break; + else + { + VolumePkcs5 = GuiPkcs5; + VolumePim = GuiPim; + VolumeTrueCryptMode = GuiTrueCryptMode; + burn (&GuiPkcs5, sizeof(GuiPkcs5)); + burn (&GuiPim, sizeof(GuiPim)); + burn (&GuiTrueCryptMode, sizeof(GuiTrueCryptMode)); + } + + WaitCursor (); + + if (KeyFilesEnable && FirstKeyFile) + KeyFilesApplyWithPin (hwndDlg, &VolumePassword, CmdTokenPin, FirstKeyFile, szFileName); + + mounted = MountVolume (hwndDlg, szDriveLetter[0] - L'A', szFileName, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, FALSE, TRUE); + + burn (&VolumePassword, sizeof (VolumePassword)); + burn (&VolumePkcs5, sizeof (VolumePkcs5)); + burn (&VolumePim, sizeof (VolumePim)); + burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); + burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); + burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); + + NormalCursor (); + } + } + + if (UsePreferences) + { + RestoreDefaultKeyFilesParam (); + bCacheInDriver = bCacheInDriverDefault; + } + + if (mounted > 0) + { + if (bBeep) + MessageBeep (0xFFFFFFFF); + + if (bExplore) + OpenVolumeExplorerWindow (szDriveLetter[0] - L'A'); + + RefreshMainDlg(hwndDlg); + + if(!Silent) + { + // Check for problematic file extensions (exe, dll, sys) + if (CheckFileExtension (szFileName)) + Warning ("EXE_FILE_EXTENSION_MOUNT_WARNING", hwndDlg); + } + } + else + exitCode = 1; + } + else if (bExplore && GetMountedVolumeDriveNo (szFileName) != -1) + OpenVolumeExplorerWindow (GetMountedVolumeDriveNo (szFileName)); + else if (szFileName[0] != 0 && IsMountedVolume (szFileName)) + Warning ("VOL_ALREADY_MOUNTED", hwndDlg); + + if (!Quit) + RefreshMainDlg(hwndDlg); + } + + // Wipe cache + if (bWipe) + WipeCache (hwndDlg, Silent); + + // Wipe command line password + if (CmdVolumePassword.Length != 0) + { + burn (&CmdVolumePassword, sizeof (CmdVolumePassword)); + CmdVolumePassword.Length = 0; + } + + // Wipe command line keyfiles + if (FirstCmdKeyFile) + { + if (defaultKeyFilesParam.FirstKeyFile) + KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile); + + defaultKeyFilesParam.EnableKeyFiles = FALSE; + + if (!Quit) + { + LoadSettings (hwndDlg); + LoadDefaultKeyFilesParam (); + RestoreDefaultKeyFilesParam (); + } + } + + // Dismount + if (cmdUnmountDrive >= 0) + { + MOUNT_LIST_STRUCT mountList; + DWORD bytesReturned; + + if (DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, NULL, 0, &mountList, sizeof (mountList), &bytesReturned, NULL) + && (mountList.ulMountedDrives & (1 << cmdUnmountDrive)) == 0) + { + Error ("NO_VOLUME_MOUNTED_TO_DRIVE", hwndDlg); + exitCode = 1; + } + else if (!Dismount (hwndDlg, cmdUnmountDrive)) + exitCode = 1; + } + else if (cmdUnmountDrive == -1) + { + if (!DismountAll (hwndDlg, bForceUnmount, !Silent, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY)) + exitCode = 1; + } + + // TaskBar icon + if (bEnableBkgTask) + TaskBarIconAdd (hwndDlg); + + // Quit + if (Quit) + { + if (TaskBarIconMutex == NULL) + exit (exitCode); + + MainWindowHidden = TRUE; + + LoadSettings (hwndDlg); + LoadDefaultKeyFilesParam (); + RestoreDefaultKeyFilesParam (); + + if (!bEnableBkgTask) + { + if (TaskBarIconMutex) + TaskBarIconRemove (hwndDlg); + exit (exitCode); + } + } + + // No command line arguments or only /volume => bring active instance + // to foreground if available + if (NoCmdLineArgs == 0 || (CmdLineVolumeSpecified && NoCmdLineArgs <= 2)) + { + HWND h = hwndDlg; + EnumWindows (FindTCWindowEnum, (LPARAM) &h); + + if (h != hwndDlg + && (!IsAdmin() || (GetWindowLongPtrW (h, DWLP_USER) & TC_MAIN_WINDOW_FLAG_ADMIN_PRIVILEGES) != 0)) + { + if (CmdLineVolumeSpecified) + { + COPYDATASTRUCT cd; + memcpy (&cd.dwData, WM_COPY_SET_VOLUME_NAME, 4); + cd.lpData = szFileName; + cd.cbData = (DWORD) ((wcslen (szFileName) + 1) * sizeof (wchar_t)); + + SendMessage (h, WM_COPYDATA, (WPARAM)hwndDlg, (LPARAM)&cd); + } + + SendMessage (h, TC_APPMSG_MOUNT_SHOW_WINDOW, 0, 0); + + ShowWindow (h, SW_SHOW); + SetForegroundWindow (h); + + if (TaskBarIconMutex == NULL) + exit (0); + } + } + + HookMouseWheel (hwndDlg, IDC_VOLUME); + + // Register hot keys + if (!RegisterAllHotkeys (hwndDlg, Hotkeys) + && TaskBarIconMutex != NULL) // Warn only if we are the first instance of TrueCrypt + Warning("HOTKEY_REGISTRATION_ERROR", hwndDlg); + + Silent = FALSE; + + GetMountList (&LastKnownMountList); + SetTimer (hwndDlg, TIMER_ID_MAIN, TIMER_INTERVAL_MAIN, NULL); + + taskBarCreatedMsg = RegisterWindowMessage (L"TaskbarCreated"); + + AllowMessageInUIPI (taskBarCreatedMsg); + + SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST)); + + /* Check system encryption status */ + + if (!Quit) // Do not care about system encryption or in-place encryption if we were launched from the system startup sequence (the wizard was added to it too). + { + if (SysEncryptionOrDecryptionRequired ()) + { + if (!MutexExistsOnSystem (TC_MUTEX_NAME_SYSENC)) // If no instance of the wizard is currently taking care of system encryption + { + // We shouldn't block the mutex at this point + + if (SystemEncryptionStatus == SYSENC_STATUS_PRETEST + || AskWarnYesNo ("SYSTEM_ENCRYPTION_RESUME_PROMPT", hwndDlg) == IDYES) + { + // The wizard was not launched during the system startup seq, or the user may have forgotten + // to resume the encryption/decryption process. + + + LaunchVolCreationWizard (hwndDlg, L"/csysenc"); + } + } + } + + if (bInPlaceEncNonSysPending && !NonSysInplaceEncInProgressElsewhere()) + { + BOOL bDecrypt = FALSE; + if (AskNonSysInPlaceEncryptionResume(hwndDlg, &bDecrypt) == IDYES) + ResumeInterruptedNonSysInplaceEncProcess (bDecrypt); + } + } + + if (TaskBarIconMutex != NULL) + RegisterWtsNotification(hwndDlg); + DoPostInstallTasks (hwndDlg); + ResetCurrentDirectory (); + } + return 0; + + case WM_MOUSEWHEEL: + return HandleDriveListMouseWheelEvent (uMsg, wParam, lParam, FALSE); + + case WM_CONTEXTMENU: + { + HWND hList = GetDlgItem (hwndDlg, IDC_DRIVELIST); + // only handle if it is coming from keyboard and if the drive + // list has focus. The other cases are handled elsewhere + if ( (-1 == GET_X_LPARAM(lParam)) + && (-1 == GET_Y_LPARAM(lParam)) + && (GetFocus () == hList) + ) + { + INT item = ListView_GetSelectionMark (hList); + if (item >= 0) + { + nSelectedDriveIndex = item; + DisplayDriveListContextMenu (hwndDlg, NULL); + } + } + } + break; + + case WM_WINDOWPOSCHANGING: + if (MainWindowHidden) + { + // Prevent window from being shown + PWINDOWPOS wp = (PWINDOWPOS)lParam; + wp->flags &= ~SWP_SHOWWINDOW; + return 0; + } + return 1; + + case WM_SYSCOMMAND: + if (lw == IDC_ABOUT) + { + DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_ABOUT_DLG), hwndDlg, (DLGPROC) AboutDlgProc); + return 1; + } + return 0; + + case WM_HELP: + OpenPageHelp (hwndDlg, 0); + return 1; + + case WM_WTSSESSION_CHANGE: + if (TaskBarIconMutex != NULL) + { + if (bDismountOnSessionLocked && ((WTS_SESSION_LOCK == wParam) || (WTS_CONSOLE_DISCONNECT == wParam) || (WTS_REMOTE_DISCONNECT == wParam))) + { + // Auto-dismount when session is locked + DWORD dwResult; + + if (bWipeCacheOnAutoDismount) + { + DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); + SecurityToken::CloseAllSessions(); + } + + DismountAll (hwndDlg, bForceAutoDismount, TRUE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); + } + } + return 0; + + case WM_ENDSESSION: + if (TaskBarIconMutex != NULL) + { + if (bDismountOnLogOff) + { + // Auto-dismount when user logs off + DWORD dwResult; + + if (bWipeCacheOnAutoDismount) + DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); + + DismountAll (hwndDlg, bForceAutoDismount, FALSE, 1, 0); + } + + TaskBarIconRemove (hwndDlg); + UnregisterWtsNotification(hwndDlg); + } + EndMainDlg (hwndDlg); + localcleanup (); + return 0; + + case WM_POWERBROADCAST: + if (wParam == PBT_APMSUSPEND + && TaskBarIconMutex != NULL && bDismountOnPowerSaving) + { + // Auto-dismount when entering power-saving mode + DWORD dwResult; + + if (bWipeCacheOnAutoDismount) + { + DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); + SecurityToken::CloseAllSessions(); + } + + DismountAll (hwndDlg, bForceAutoDismount, TRUE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); + } + return 0; + + case WM_TIMER: + { + // Check mount list and update GUI if needed + CheckMountList (hwndDlg, FALSE); + + // Cache status + if (IsPasswordCacheEmpty() == IsWindowEnabled (GetDlgItem (hwndDlg, IDC_WIPE_CACHE))) + EnableWindow (GetDlgItem (hwndDlg, IDC_WIPE_CACHE), !IsPasswordCacheEmpty()); + + // Check driver warning flags + DWORD bytesOut; + GetWarningFlagsRequest warnings; + if (DeviceIoControl (hDriver, TC_IOCTL_GET_WARNING_FLAGS, NULL, 0, &warnings, sizeof (warnings), &bytesOut, NULL)) + { + if (warnings.SystemFavoriteVolumeDirty) + WarningTopMost ("SYS_FAVORITE_VOLUME_DIRTY", hwndDlg); + + if (warnings.PagingFileCreationPrevented) + WarningTopMost ("PAGING_FILE_CREATION_PREVENTED", hwndDlg); + } + + if (TaskBarIconMutex != NULL) + { + + // Idle auto-dismount + if (MaxVolumeIdleTime > 0) + DismountIdleVolumes (); + + // Screen saver auto-dismount + if (bDismountOnScreenSaver) + { + static BOOL previousState = FALSE; + BOOL running = FALSE; + SystemParametersInfo (SPI_GETSCREENSAVERRUNNING, 0, &running, 0); + + if (running && !previousState) + { + DWORD dwResult; + previousState = TRUE; + + if (bWipeCacheOnAutoDismount) + { + DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); + SecurityToken::CloseAllSessions(); + } + + DismountAll (hwndDlg, bForceAutoDismount, FALSE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); + } + else + { + previousState = running; + } + } + + // Auto-mount favorite volumes on arrival +#if TIMER_INTERVAL_MAIN != 500 +#error TIMER_INTERVAL_MAIN != 500 +#endif + static int favoritesAutoMountTimerDivisor = 0; + if ((++favoritesAutoMountTimerDivisor & 1) && !FavoritesOnArrivalMountRequired.empty()) + { + static bool reentry = false; + if (reentry) + break; + + reentry = true; + + foreach (FavoriteVolume favorite, FavoritesOnArrivalMountRequired) + { + if (favorite.UseVolumeID) + { + if (IsMountedVolumeID (favorite.VolumeID)) + continue; + + std::wstring volDevPath = FindDeviceByVolumeID (favorite.VolumeID); + if (volDevPath.length() > 0) + { + favorite.Path = volDevPath; + favorite.DisconnectedDevice = false; + } + else + continue; + } + else if (!favorite.VolumePathId.empty()) + { + if (IsMountedVolume (favorite.Path.c_str())) + continue; + + wchar_t volDevPath[TC_MAX_PATH]; + if (QueryDosDevice (favorite.VolumePathId.substr (4, favorite.VolumePathId.size() - 5).c_str(), volDevPath, TC_MAX_PATH) == 0) + continue; + + favorite.DisconnectedDevice = false; + } + else if (favorite.Path.find (L"\\\\?\\Volume{") == 0) + { + wstring resolvedPath = VolumeGuidPathToDevicePath (favorite.Path); + if (resolvedPath.empty()) + continue; + + favorite.DisconnectedDevice = false; + favorite.VolumePathId = favorite.Path; + favorite.Path = resolvedPath; + } + + if (IsMountedVolume (favorite.Path.c_str())) + continue; + + if (!IsVolumeDeviceHosted (favorite.Path.c_str())) + { + if (!FileExists (favorite.Path.c_str())) + continue; + } + else if (favorite.VolumePathId.empty()) + continue; + + bool mountedAndNotDisconnected = false; + foreach (FavoriteVolume mountedFavorite, FavoritesMountedOnArrivalStillConnected) + { + if (favorite.Path == mountedFavorite.Path) + { + mountedAndNotDisconnected = true; + break; + } + } + + if (!mountedAndNotDisconnected) + { + FavoriteMountOnArrivalInProgress = TRUE; + MountFavoriteVolumes (hwndDlg, FALSE, FALSE, FALSE, favorite); + FavoriteMountOnArrivalInProgress = FALSE; + + FavoritesMountedOnArrivalStillConnected.push_back (favorite); + } + } + + bool deleted; + for (list ::iterator favorite = FavoritesMountedOnArrivalStillConnected.begin(); + favorite != FavoritesMountedOnArrivalStillConnected.end(); + deleted ? favorite : ++favorite) + { + deleted = false; + + if (IsMountedVolume (favorite->Path.c_str())) + continue; + + if (!IsVolumeDeviceHosted (favorite->Path.c_str())) + { + if (FileExists (favorite->Path.c_str())) + continue; + } + + wchar_t volDevPath[TC_MAX_PATH]; + if (favorite->VolumePathId.size() > 5 + && QueryDosDevice (favorite->VolumePathId.substr (4, favorite->VolumePathId.size() - 5).c_str(), volDevPath, TC_MAX_PATH) != 0) + { + continue; + } + + // set DisconnectedDevice field on FavoritesOnArrivalMountRequired element + foreach (FavoriteVolume onArrivalFavorite, FavoritesOnArrivalMountRequired) + { + if (onArrivalFavorite.Path == favorite->Path) + { + onArrivalFavorite.DisconnectedDevice = true; + break; + } + } + + favorite = FavoritesMountedOnArrivalStillConnected.erase (favorite); + deleted = true; + } + + reentry = false; + } + } + + // Exit background process in non-install mode or if no volume mounted + // and no other instance active + if (LastKnownMountList.ulMountedDrives == 0 + && MainWindowHidden +#ifndef _DEBUG + && (bCloseBkgTaskWhenNoVolumes || IsNonInstallMode ()) + && !SysEncDeviceActive (TRUE) +#endif + && GetDriverRefCount () < 2) + { + TaskBarIconRemove (hwndDlg); + UnregisterWtsNotification(hwndDlg); + EndMainDlg (hwndDlg); + } + } + return 1; + + case TC_APPMSG_TASKBAR_ICON: + { + switch (lParam) + { + case WM_LBUTTONDOWN: + SetForegroundWindow (hwndDlg); + MainWindowHidden = FALSE; + ShowWindow (hwndDlg, SW_SHOW); + ShowWindow (hwndDlg, SW_RESTORE); + return 1; + + case WM_RBUTTONUP: + { + POINT pos; + HMENU popup = CreatePopupMenu (); + int sel, i, n; + + if (MainWindowHidden) + { + AppendMenuW (popup, MF_STRING, IDM_SHOW_HIDE, GetString ("SHOW_TC")); + AppendMenu (popup, MF_SEPARATOR, 0, L""); + } + else if (bEnableBkgTask + && (!(LastKnownMountList.ulMountedDrives == 0 + && (bCloseBkgTaskWhenNoVolumes || IsNonInstallMode ()) + && !SysEncDeviceActive (TRUE) + && GetDriverRefCount () < 2))) + { + AppendMenuW (popup, MF_STRING, IDM_SHOW_HIDE, GetString ("HIDE_TC")); + AppendMenu (popup, MF_SEPARATOR, 0, L""); + } + AppendMenuW (popup, MF_STRING, IDM_MOUNTALL, GetString ("IDC_MOUNTALL")); + AppendMenuW (popup, MF_STRING, IDM_MOUNT_FAVORITE_VOLUMES, GetString ("IDM_MOUNT_FAVORITE_VOLUMES")); + AppendMenuW (popup, MF_STRING, IDM_UNMOUNTALL, GetString ("IDC_UNMOUNTALL")); + AppendMenu (popup, MF_SEPARATOR, 0, L""); + + for (n = 0; n < 2; n++) + { + for (i = 0; i < 26; i++) + { + if (LastKnownMountList.ulMountedDrives & (1 << i)) + { + wchar_t s[1024]; + wchar_t *vol = (wchar_t *) LastKnownMountList.wszVolume[i]; + + if (wcsstr (vol, L"\\??\\")) vol += 4; + + // first check label used for mounting. If empty, look for it in favorites. + bool useInExplorer = false; + wstring label = (wchar_t *) LastKnownMountList.wszLabel[i]; + if (label.empty()) + label = GetFavoriteVolumeLabel (vol, useInExplorer); + + StringCbPrintfW (s, sizeof(s), L"%s %c: (%s)", + GetString (n==0 ? "OPEN" : "DISMOUNT"), + i + L'A', + label.empty() ? vol : label.c_str()); + AppendMenuW (popup, MF_STRING, n*26 + TRAYICON_MENU_DRIVE_OFFSET + i, s); + } + } + if (LastKnownMountList.ulMountedDrives != 0) + AppendMenu (popup, MF_SEPARATOR, 0, L""); + } + + AppendMenuW (popup, MF_STRING, IDM_HELP, GetString ("MENU_HELP")); + AppendMenuW (popup, MF_STRING, IDM_HOMEPAGE_SYSTRAY, GetString ("HOMEPAGE")); + AppendMenuW (popup, MF_STRING, IDM_PREFERENCES, GetString ("IDM_PREFERENCES")); + AppendMenuW (popup, MF_STRING, IDM_ABOUT, GetString ("IDM_ABOUT")); + AppendMenu (popup, MF_SEPARATOR, 0, L""); + AppendMenuW (popup, MF_STRING, IDCANCEL, GetString ("EXIT")); + + GetCursorPos (&pos); + + SetForegroundWindow(hwndDlg); + + sel = TrackPopupMenu (popup, + TPM_RETURNCMD | TPM_LEFTALIGN | TPM_BOTTOMALIGN | TPM_RIGHTBUTTON, + pos.x, + pos.y, + 0, + hwndDlg, + NULL); + + if (sel >= TRAYICON_MENU_DRIVE_OFFSET && sel < TRAYICON_MENU_DRIVE_OFFSET + 26) + { + OpenVolumeExplorerWindow (sel - TRAYICON_MENU_DRIVE_OFFSET); + } + else if (sel >= TRAYICON_MENU_DRIVE_OFFSET + 26 && sel < TRAYICON_MENU_DRIVE_OFFSET + 26*2) + { + if (CheckMountList (hwndDlg, FALSE)) + { + if (Dismount (hwndDlg, sel - TRAYICON_MENU_DRIVE_OFFSET - 26)) + { + wchar_t txt [2048]; + StringCbPrintfW (txt, sizeof(txt), GetString ("VOLUME_MOUNTED_AS_DRIVE_LETTER_X_DISMOUNTED"), sel - TRAYICON_MENU_DRIVE_OFFSET - 26 + L'A'); + + InfoBalloonDirect (GetString ("SUCCESSFULLY_DISMOUNTED"), txt, hwndDlg); + } + } + } + else if (sel == IDM_SHOW_HIDE) + { + ChangeMainWindowVisibility (); + } + else if (sel == IDM_HOMEPAGE_SYSTRAY) + { + Applink ("home", TRUE, ""); + } + else if (sel == IDCANCEL) + { + if ((LastKnownMountList.ulMountedDrives == 0 + && !SysEncDeviceActive (TRUE)) + || AskWarnNoYes ("CONFIRM_EXIT", hwndDlg) == IDYES) + { + // Close all other TC windows + EnumWindows (CloseTCWindowsEnum, 0); + + TaskBarIconRemove (hwndDlg); + UnregisterWtsNotification(hwndDlg); + SendMessage (hwndDlg, WM_COMMAND, sel, 0); + } + } + else + { + SendMessage (hwndDlg, WM_COMMAND, sel, 0); + } + + PostMessage(hwndDlg, WM_NULL, 0, 0); + DestroyMenu (popup); + } + return 1; + } + } + + return 0; + + case TC_APPMSG_CLOSE_BKG_TASK: + if (TaskBarIconMutex != NULL) + TaskBarIconRemove (hwndDlg); + UnregisterWtsNotification(hwndDlg); + + return 1; + + case TC_APPMSG_SYSENC_CONFIG_UPDATE: + LoadSysEncSettings (); + + // The wizard added VeraCrypt.exe to the system startup sequence or performed other operations that + // require us to update our cached settings. + LoadSettings (hwndDlg); + + return 1; + + case WM_DEVICECHANGE: + if (!IgnoreWmDeviceChange && wParam != DBT_DEVICEARRIVAL) + { + // Check if any host device has been removed and force dismount of volumes accordingly + PDEV_BROADCAST_HDR hdr = (PDEV_BROADCAST_HDR) lParam; + int m; + + GetMountList (&LastKnownMountList); + + if (wParam == DBT_DEVICEREMOVECOMPLETE && hdr->dbch_devicetype == DBT_DEVTYP_VOLUME) + { + // File-hosted volumes + PDEV_BROADCAST_VOLUME vol = (PDEV_BROADCAST_VOLUME) lParam; + int i; + + for (i = 0; i < 26; i++) + { + if ((vol->dbcv_unitmask & (1 << i)) && !(GetUsedLogicalDrives() & (1 << i))) + { + for (m = 0; m < 26; m++) + { + if (LastKnownMountList.ulMountedDrives & (1 << m)) + { + wchar_t *vol = (wchar_t *) LastKnownMountList.wszVolume[m]; + + if (wcsstr (vol, L"\\??\\") == vol) + vol += 4; + + if (vol[1] == L':' && i == (vol[0] - (vol[0] <= L'Z' ? L'A' : L'a'))) + { + UnmountVolume (hwndDlg, m, TRUE); + WarningBalloon ("HOST_DEVICE_REMOVAL_DISMOUNT_WARN_TITLE", "HOST_DEVICE_REMOVAL_DISMOUNT_WARN", hwndDlg); + } + } + } + } + } + } + + // Device-hosted volumes + for (m = 0; m < 26; m++) + { + if (LastKnownMountList.ulMountedDrives & (1 << m)) + { + wchar_t *vol = (wchar_t *) LastKnownMountList.wszVolume[m]; + + if (wcsstr (vol, L"\\??\\") == vol) + vol += 4; + + if (IsVolumeDeviceHosted (vol)) + { + OPEN_TEST_STRUCT ots = {0}; + + if (!OpenDevice (vol, &ots, FALSE, FALSE, NULL)) + { + UnmountVolume (hwndDlg, m, TRUE); + WarningBalloon ("HOST_DEVICE_REMOVAL_DISMOUNT_WARN_TITLE", "HOST_DEVICE_REMOVAL_DISMOUNT_WARN", hwndDlg); + } + } + } + } + + // Favorite volumes + UpdateDeviceHostedFavoriteVolumes(); + + return 1; + } + return 0; + + case WM_NOTIFY: + + if(wParam == IDC_DRIVELIST) + { + if (((LPNMHDR) lParam)->code == NM_CUSTOMDRAW) + { + int width = ListView_GetColumnWidth (GetDlgItem (hwndDlg, IDC_DRIVELIST), 1); + if (width != LastDriveListVolumeColumnWidth) + { + LastDriveListVolumeColumnWidth = width; + LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), 0); + } + return 0; + } + + /* Single click within drive list */ + if (((LPNMHDR) lParam)->code == LVN_ITEMCHANGED && (((LPNMLISTVIEW) lParam)->uNewState & LVIS_FOCUSED )) + { + nSelectedDriveIndex = ((LPNMLISTVIEW) lParam)->iItem; + EnableDisableButtons (hwndDlg); + return 1; + } + + /* Double click within drive list */ + if (((LPNMHDR) lParam)->code == LVN_ITEMACTIVATE) + { + LPARAM state = GetItemLong (GetDlgItem (hwndDlg, IDC_DRIVELIST), ((LPNMITEMACTIVATE)lParam)->iItem ); + nSelectedDriveIndex = ((LPNMITEMACTIVATE)lParam)->iItem; + if (LOWORD(state) == TC_MLIST_ITEM_NONSYS_VOL || LOWORD(state) == TC_MLIST_ITEM_SYS_PARTITION) + { + // Open explorer window for mounted volume + WaitCursor (); + OpenVolumeExplorerWindow (HIWORD(state) - L'A'); + NormalCursor (); + } + else if (LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) == TC_MLIST_ITEM_FREE) + { + mountOptions = defaultMountOptions; + bPrebootPasswordDlgMode = FALSE; + + if (GetAsyncKeyState (VK_CONTROL) < 0) + { + /* Priority is given to command line parameters + * Default values used only when nothing specified in command line + */ + if (CmdVolumePkcs5 == 0) + mountOptions.ProtectedHidVolPkcs5Prf = DefaultVolumePkcs5; + else + mountOptions.ProtectedHidVolPkcs5Prf = CmdVolumePkcs5; + mountOptions.ProtectedHidVolPim = CmdVolumePim; + + if (IDCANCEL == DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, + (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions)) + return 1; + + if (mountOptions.ProtectHiddenVolume && hidVolProtKeyFilesParam.EnableKeyFiles) + { + wchar_t selectedVolume [TC_MAX_PATH + 1]; + GetVolumePath (hwndDlg, selectedVolume, ARRAYSIZE (selectedVolume)); + KeyFilesApply (hwndDlg, &mountOptions.ProtectedHidVolPassword, hidVolProtKeyFilesParam.FirstKeyFile, selectedVolume); + } + } + + if (CheckMountList (hwndDlg, FALSE)) + _beginthread(mountThreadFunction, 0, hwndDlg); + } + return 1; + } + + /* Right click and drag&drop operations */ + + switch (((NM_LISTVIEW *) lParam)->hdr.code) + { + case NM_RCLICK: + case LVN_BEGINRDRAG: + /* If the mouse was moving while the right mouse button is pressed, popup menu would + not open, because drag&drop operation would be initiated. Therefore, we're handling + RMB drag-and-drop operations as well. */ + { + + DisplayDriveListContextMenu (hwndDlg, lParam); + + return 1; + } + } + } + return 0; + + case WM_ERASEBKGND: + return 0; + + case WM_COMMAND: + + if (lw == IDCANCEL || lw == IDC_EXIT) + { + EndMainDlg (hwndDlg); + return 1; + } + + if (lw == IDHELP || lw == IDM_HELP) + { + OpenPageHelp (hwndDlg, 0); + return 1; + } + + if (lw == IDM_ABOUT || lw == IDC_LOGO) + { + DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_ABOUT_DLG), hwndDlg, (DLGPROC) AboutDlgProc); + return 1; + } + + if (lw == IDOK && LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) == TC_MLIST_ITEM_NONSYS_VOL + || lw == IDM_UNMOUNT_VOLUME) + { + if (lw == IDM_UNMOUNT_VOLUME && LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) != TC_MLIST_ITEM_NONSYS_VOL) + { + Warning ("SELECT_A_MOUNTED_VOLUME", hwndDlg); + return 1; + } + + if (CheckMountList (hwndDlg, FALSE)) + Dismount (hwndDlg, -2); + return 1; + } + + if ((lw == IDOK || lw == IDM_MOUNT_VOLUME || lw == IDM_MOUNT_VOLUME_OPTIONS || lw == IDC_MOUNTALL || lw == IDM_MOUNTALL) + && LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) == 0xffff) + { + MessageBoxW (hwndDlg, GetString ("SELECT_FREE_DRIVE"), L"VeraCrypt", MB_ICONEXCLAMATION); + return 1; + } + + if ((lw == IDOK || lw == IDM_MOUNT_VOLUME || lw == IDM_MOUNT_VOLUME_OPTIONS)) + { + MountSelectedVolume (hwndDlg, lw == IDM_MOUNT_VOLUME_OPTIONS); + return 1; + } + + if (lw == IDC_UNMOUNTALL || lw == IDM_UNMOUNTALL) + { + if (DismountAll (hwndDlg, bForceUnmount, TRUE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY) + && lw == IDM_UNMOUNTALL) // If initiated via the systray menu + { + InfoBalloon ("SUCCESSFULLY_DISMOUNTED", "MOUNTED_VOLUMES_DISMOUNTED", hwndDlg); + } + + return 1; + } + + if (lw == IDC_MOUNTALL || lw == IDM_MOUNTALL) + { + // If Shift key is down and the password cache isn't empty, bypass password prompt + MountAllDevices (hwndDlg, !(GetAsyncKeyState (VK_SHIFT) < 0 && !IsPasswordCacheEmpty())); + return 1; + } + + if (lw == IDC_SELECT_FILE || lw == IDM_SELECT_FILE) + { + SelectContainer (hwndDlg); + return 1; + } + + if (lw == IDC_SELECT_DEVICE || lw == IDM_SELECT_DEVICE) + { + SelectPartition (hwndDlg); + return 1; + } + + // System Encryption menu + switch (lw) + { + case IDM_ENCRYPT_SYSTEM_DEVICE: + EncryptSystemDevice (hwndDlg); + break; + case IDM_PERMANENTLY_DECRYPT_SYS: + DecryptSystemDevice (hwndDlg); + break; + case IDM_CREATE_HIDDEN_OS: + CreateHiddenOS (hwndDlg); + break; + case IDM_SYSENC_RESUME: + ResumeInterruptedSysEncProcess (hwndDlg); + break; + case IDM_SYSTEM_ENCRYPTION_STATUS: + ShowSystemEncryptionStatus (hwndDlg); + break; + case IDM_CHANGE_SYS_PASSWORD: + ChangeSysEncPassword (hwndDlg, FALSE); + break; + case IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO: + ChangeSysEncPassword (hwndDlg, TRUE); + break; + case IDM_CREATE_RESCUE_DISK: + CreateRescueDisk (hwndDlg); + break; + case IDM_VERIFY_RESCUE_DISK: + VerifyRescueDisk (hwndDlg, false); + break; + case IDM_VERIFY_RESCUE_DISK_ISO: + VerifyRescueDisk (hwndDlg, true); + break; + case IDM_MOUNT_SYSENC_PART_WITHOUT_PBA: + + if (CheckSysEncMountWithoutPBA (hwndDlg, L"", FALSE)) + { + mountOptions = defaultMountOptions; + mountOptions.PartitionInInactiveSysEncScope = TRUE; + bPrebootPasswordDlgMode = TRUE; + + if (CheckMountList (hwndDlg, FALSE)) + _beginthread(mountThreadFunction, 0, hwndDlg); + } + break; + } + + if (lw == IDC_VOLUME_TOOLS) + { + /* Volume Tools popup menu */ + + int menuItem; + wchar_t volPath[TC_MAX_PATH]; /* Volume to mount */ + HMENU popup = CreatePopupMenu (); + RECT rect; + + if (ActiveSysEncDeviceSelected ()) + { + PopulateSysEncContextMenu (popup, TRUE); + } + else + { + AppendMenuW (popup, MF_STRING, IDM_CHANGE_PASSWORD, GetString ("IDM_CHANGE_PASSWORD")); + AppendMenuW (popup, MF_STRING, IDM_CHANGE_HEADER_KEY_DERIV_ALGO, GetString ("IDM_CHANGE_HEADER_KEY_DERIV_ALGO")); + AppendMenu (popup, MF_SEPARATOR, 0, L""); + AppendMenuW (popup, MF_STRING, IDM_ADD_REMOVE_VOL_KEYFILES, GetString ("IDM_ADD_REMOVE_VOL_KEYFILES")); + AppendMenuW (popup, MF_STRING, IDM_REMOVE_ALL_KEYFILES_FROM_VOL, GetString ("IDM_REMOVE_ALL_KEYFILES_FROM_VOL")); + AppendMenu (popup, MF_SEPARATOR, 0, L""); + AppendMenuW (popup, MF_STRING, IDM_DECRYPT_NONSYS_VOL, GetString ("IDM_DECRYPT_NONSYS_VOL")); + AppendMenu (popup, MF_SEPARATOR, 0, NULL); + AppendMenuW (popup, MF_STRING, IDM_BACKUP_VOL_HEADER, GetString ("IDM_BACKUP_VOL_HEADER")); + AppendMenuW (popup, MF_STRING, IDM_RESTORE_VOL_HEADER, GetString ("IDM_RESTORE_VOL_HEADER")); + } + + GetWindowRect (GetDlgItem (hwndDlg, IDC_VOLUME_TOOLS), &rect); + + menuItem = TrackPopupMenu (popup, + TPM_RETURNCMD | TPM_LEFTBUTTON, + rect.left + 2, + rect.top + 2, + 0, + hwndDlg, + NULL); + + DestroyMenu (popup); + + switch (menuItem) + { + case IDM_DECRYPT_NONSYS_VOL: + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + DecryptNonSysDevice (hwndDlg, TRUE, FALSE); + } + break; + + case IDM_CHANGE_PASSWORD: + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + pwdChangeDlgMode = PCDM_CHANGE_PASSWORD; + ChangePassword (hwndDlg); + } + break; + + case IDM_CHANGE_HEADER_KEY_DERIV_ALGO: + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + pwdChangeDlgMode = PCDM_CHANGE_PKCS5_PRF; + ChangePassword (hwndDlg); + } + break; + + case IDM_ADD_REMOVE_VOL_KEYFILES: + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + pwdChangeDlgMode = PCDM_ADD_REMOVE_VOL_KEYFILES; + ChangePassword (hwndDlg); + } + break; + + case IDM_REMOVE_ALL_KEYFILES_FROM_VOL: + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + pwdChangeDlgMode = PCDM_REMOVE_ALL_KEYFILES_FROM_VOL; + ChangePassword (hwndDlg); + } + break; + + case IDM_BACKUP_VOL_HEADER: + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + GetVolumePath (hwndDlg, volPath, ARRAYSIZE (volPath)); + + WaitCursor (); + + int iStatus = 0; + BackupHeaderThreadParam threadParam; + threadParam.bRequireConfirmation = TRUE; + threadParam.lpszVolume = volPath; + threadParam.cchVolume = ARRAYSIZE (volPath); + threadParam.iResult = &iStatus; + + ShowWaitDialog (hwndDlg, TRUE, BackupHeaderWaitThreadProc, &threadParam); + + NormalCursor (); + } + break; + + case IDM_RESTORE_VOL_HEADER: + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + GetVolumePath (hwndDlg, volPath, ARRAYSIZE (volPath)); + + WaitCursor (); + + int iStatus = 0; + RestoreHeaderThreadParam threadParam; + threadParam.lpszVolume = volPath; + threadParam.cchVolume = ARRAYSIZE (volPath); + threadParam.iResult = &iStatus; + + ShowWaitDialog(hwndDlg, TRUE, RestoreHeaderWaitThreadProc, &threadParam); + + NormalCursor (); + } + break; + + default: + SendMessage (MainDlg, WM_COMMAND, menuItem, NULL); + break; + } + return 1; + } + + if (lw == IDM_DECRYPT_NONSYS_VOL) + { + LPARAM selectedDrive = GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST)); + + if (LOWORD (selectedDrive) == TC_MLIST_ITEM_FREE && !VolumeSelected (MainDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + DecryptNonSysDevice (hwndDlg, TRUE, FALSE); + } + + return 1; + } + + if (lw == IDM_CHANGE_PASSWORD) + { + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + if (ActiveSysEncDeviceSelected ()) + { + ChangeSysEncPassword (hwndDlg, FALSE); + } + else + { + pwdChangeDlgMode = PCDM_CHANGE_PASSWORD; + ChangePassword (hwndDlg); + } + } + return 1; + } + + if (lw == IDM_CHANGE_HEADER_KEY_DERIV_ALGO) + { + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + if (ActiveSysEncDeviceSelected ()) + { + ChangeSysEncPassword (hwndDlg, TRUE); + } + else + { + pwdChangeDlgMode = PCDM_CHANGE_PKCS5_PRF; + ChangePassword (hwndDlg); + } + } + return 1; + } + + if (lw == IDC_WIPE_CACHE || lw == IDM_WIPE_CACHE) + { + WipeCache (hwndDlg, FALSE); + return 1; + } + + if (lw == IDM_CLEAR_HISTORY) + { + ClearHistory (GetDlgItem (hwndDlg, IDC_VOLUME)); + EnableDisableButtons (hwndDlg); + return 1; + } + + if (lw == IDC_CREATE_VOLUME || lw == IDM_CREATE_VOLUME || lw == IDM_VOLUME_WIZARD) + { + LaunchVolCreationWizard (hwndDlg, L""); + return 1; + } + + if (lw == IDM_VOLUME_EXPANDER) + { + LaunchVolExpander (hwndDlg); + return 1; + } + + if (lw == IDM_ADD_REMOVE_VOL_KEYFILES) + { + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + pwdChangeDlgMode = PCDM_ADD_REMOVE_VOL_KEYFILES; + ChangePassword (hwndDlg); + } + return 1; + } + + if (lw == IDM_REMOVE_ALL_KEYFILES_FROM_VOL) + { + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + pwdChangeDlgMode = PCDM_REMOVE_ALL_KEYFILES_FROM_VOL; + ChangePassword (hwndDlg); + } + return 1; + } + + if (lw == IDM_MANAGE_TOKEN_KEYFILES) + { + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TOKEN_KEYFILES), hwndDlg, (DLGPROC) SecurityTokenKeyfileDlgProc, NULL); + return 1; + } + + if (lw == IDM_CLOSE_ALL_TOKEN_SESSIONS) + { + { + WaitCursor(); + finally_do ({ NormalCursor(); }); + + SecurityToken::CloseAllSessions(); + } + + InfoBalloon (NULL, "ALL_TOKEN_SESSIONS_CLOSED", hwndDlg); + + return 1; + } + + if (lw == IDM_KEYFILE_GENERATOR) + { + DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_KEYFILE_GENERATOR), hwndDlg, + (DLGPROC) KeyfileGeneratorDlgProc, (LPARAM) 0); + + return 1; + } + + if (lw == IDM_DONATE) + { + Applink ("donate", TRUE, ""); + return 1; + } + + if (lw == IDM_LICENSE) + { + TextInfoDialogBox (TC_TBXID_LEGAL_NOTICES); + return 1; + } + + if (lw == IDM_WEBSITE) + { + Applink ("website", TRUE, ""); + return 1; + } + else if (lw == IDM_HOMEPAGE) + { + Applink ("homepage", TRUE, ""); + return 1; + } + else if (lw == IDM_ONLINE_TUTORIAL) + { + Applink ("tutorial", TRUE, ""); + return 1; + } + else if (lw == IDM_ONLINE_HELP) + { + OpenOnlineHelp (); + return 1; + } + else if (lw == IDM_FAQ) + { + Applink ("faq", TRUE, ""); + return 1; + } + else if (lw == IDM_TC_DOWNLOADS) + { + Applink ("downloads", TRUE, ""); + return 1; + } + else if (lw == IDM_NEWS) + { + Applink ("news", TRUE, ""); + return 1; + } + else if (lw == IDM_VERSION_HISTORY) + { + Applink ("history", TRUE, ""); + return 1; + } + else if (lw == IDM_CONTACT) + { + Applink ("contact", FALSE, ""); + return 1; + } + + if (lw == IDM_PREFERENCES) + { + if (IDOK == DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_PREFERENCES_DLG), hwndDlg, + (DLGPROC) PreferencesDlgProc, (LPARAM) 0)) + { + if (bEnableBkgTask) + { + TaskBarIconAdd (hwndDlg); + RegisterWtsNotification(hwndDlg); + } + else + { + TaskBarIconRemove (hwndDlg); + UnregisterWtsNotification(hwndDlg); + if (MainWindowHidden) + EndMainDlg (hwndDlg); + } + } + return 1; + } + + if (lw == IDM_HOTKEY_SETTINGS) + { + DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_HOTKEYS_DLG), hwndDlg, + (DLGPROC) HotkeysDlgProc, (LPARAM) 0); + return 1; + } + + if (lw == IDM_PERFORMANCE_SETTINGS) + { + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_PERFORMANCE_SETTINGS), hwndDlg, (DLGPROC) PerformanceSettingsDlgProc, 0); + return 1; + } + + if (lw == IDM_DEFAULT_KEYFILES) + { + KeyfileDefaultsDlg (hwndDlg); + return 1; + } + + if (lw == IDM_DEFAULT_MOUNT_PARAMETERS) + { + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_DEFAULT_MOUNT_PARAMETERS), hwndDlg, (DLGPROC) DefaultMountParametersDlgProc, 0); + return 1; + } + + if (lw == IDM_ADD_VOLUME_TO_FAVORITES || lw == IDM_ADD_VOLUME_TO_SYSTEM_FAVORITES) + { + LPARAM selectedDrive = GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST)); + + wchar_t volPathLower[TC_MAX_PATH]; + + // volPathLower will contain the volume path (if any) from the input field below the drive list + GetVolumePath (hwndDlg, volPathLower, ARRAYSIZE (volPathLower)); + + if (LOWORD (selectedDrive) != TC_MLIST_ITEM_NONSYS_VOL + && !(VolumeSelected (hwndDlg) && IsMountedVolume (volPathLower))) + { + Warning ("SELECT_A_MOUNTED_VOLUME", hwndDlg); + + return 1; + } + + int driveNo; + + if (VolumeSelected (hwndDlg) + && IsMountedVolume (volPathLower)) + { + TranslateVolumeID (hwndDlg, volPathLower, ARRAYSIZE (volPathLower)); + + if (LOWORD (selectedDrive) != TC_MLIST_ITEM_NONSYS_VOL) + { + driveNo = GetMountedVolumeDriveNo (volPathLower); + } + else + { + /* We need to resolve selection ambiguity. Two different mounted volumes are currently + selected (one in the drive letter list and the other in the input field below the list). */ + + VOLUME_PROPERTIES_STRUCT prop; + DWORD dwResult; + + memset (&prop, 0, sizeof(prop)); + prop.driveNo = HIWORD (selectedDrive) - L'A'; + + if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL) || dwResult == 0) + { + Warning ("SELECT_A_MOUNTED_VOLUME", hwndDlg); + return 1; + } + + // volPathHigher will contain the volume path selected in the main drive list + wstring volPathHigher (prop.wszVolume); + + if (wcscmp (((wmemcmp (prop.wszVolume, L"\\??\\", 4) == 0) ? (wchar_t *) prop.wszVolume + 4 : prop.wszVolume), volPathLower) != 0) + { + // The path selected in the input field is different from the path to the volume selected + // in the drive lettter list. We have to resolve possible ambiguity. + + wchar_t *tmp[] = {L"", L"", L"", L"", L"", 0}; + const int maxVolPathLen = 80; + + if (volPathHigher.length () > maxVolPathLen) + { + volPathHigher = wstring (L"...") + volPathHigher.substr (volPathHigher.length () - maxVolPathLen, maxVolPathLen); + } + + wstring volPathLowerWStr (volPathLower); + + if (volPathLowerWStr.length () > maxVolPathLen) + { + volPathLowerWStr = wstring (L"...") + volPathLowerWStr.substr (volPathLowerWStr.length () - maxVolPathLen, maxVolPathLen); + } + + tmp[1] = GetString ("AMBIGUOUS_VOL_SELECTION"); + tmp[2] = (wchar_t *) volPathHigher.c_str(); + tmp[3] = (wchar_t *) volPathLowerWStr.c_str(); + tmp[4] = GetString ("IDCANCEL"); + + switch (AskMultiChoice ((void **) tmp, FALSE, hwndDlg)) + { + case 1: + driveNo = HIWORD (selectedDrive) - L'A'; + break; + + case 2: + driveNo = GetMountedVolumeDriveNo (volPathLower); + break; + + default: + return 1; + } + } + else + { + driveNo = HIWORD (selectedDrive) - L'A'; + } + } + } + else + { + driveNo = HIWORD (selectedDrive) - L'A'; + } + + AddMountedVolumeToFavorites (hwndDlg, driveNo, lw == IDM_ADD_VOLUME_TO_SYSTEM_FAVORITES); + + return 1; + } + + if (lw == IDM_ORGANIZE_FAVORITES || lw == IDM_ORGANIZE_SYSTEM_FAVORITES) + { + OrganizeFavoriteVolumes (hwndDlg, lw == IDM_ORGANIZE_SYSTEM_FAVORITES); + return 1; + } + + if (lw == IDM_TOKEN_PREFERENCES) + { + SecurityTokenPreferencesDialog (hwndDlg); + return 1; + } + + if (lw == IDM_SYSENC_SETTINGS || lw == IDM_SYS_ENC_SETTINGS) + { + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_SYSENC_SETTINGS), hwndDlg, (DLGPROC) BootLoaderPreferencesDlgProc, 0); + return 1; + } + + if (lw == IDM_SYS_FAVORITES_SETTINGS) + { + OrganizeFavoriteVolumes (hwndDlg, true); + return 1; + } + + if (lw == IDM_BENCHMARK) + { + Benchmark (hwndDlg); + return 1; + } + + if (lw == IDM_TRAVELER) + { + DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_TRAVELER_DLG), hwndDlg, + (DLGPROC) TravelerDlgProc, (LPARAM) 0); + return 1; + } + + if (lw == IDM_BACKUP_VOL_HEADER) + { + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + wchar_t volPath[TC_MAX_PATH]; /* Volume to mount */ + + GetVolumePath (hwndDlg, volPath, ARRAYSIZE (volPath)); + + WaitCursor (); + + int iStatus = 0; + BackupHeaderThreadParam threadParam; + threadParam.bRequireConfirmation = TRUE; + threadParam.lpszVolume = volPath; + threadParam.cchVolume = ARRAYSIZE (volPath); + threadParam.iResult = &iStatus; + + ShowWaitDialog (hwndDlg, TRUE, BackupHeaderWaitThreadProc, &threadParam); + + NormalCursor (); + } + return 1; + } + + if (lw == IDM_RESTORE_VOL_HEADER) + { + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else + { + wchar_t volPath[TC_MAX_PATH]; /* Volume to mount */ + + GetVolumePath (hwndDlg, volPath, ARRAYSIZE (volPath)); + + WaitCursor (); + + int iStatus = 0; + RestoreHeaderThreadParam threadParam; + threadParam.lpszVolume = volPath; + threadParam.cchVolume = ARRAYSIZE (volPath); + threadParam.iResult = &iStatus; + + ShowWaitDialog(hwndDlg, TRUE, RestoreHeaderWaitThreadProc, &threadParam); + + NormalCursor (); + } + return 1; + } + + if (lw == IDM_LANGUAGE) + { + BOOL p; + if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_LANGUAGE), hwndDlg, + (DLGPROC) LanguageDlgProc, (LPARAM) 0) == IDOK) + { + LoadLanguageFile (); + SaveSettings (hwndDlg); + + p = LocalizationActive; + LocalizationActive = TRUE; + InitMainDialog (hwndDlg); + InvalidateRect (hwndDlg, NULL, FALSE); + LocalizationActive = p; + DrawMenuBar (hwndDlg); + } + return 1; + } + + if (lw == IDM_TEST_VECTORS) + { + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_CIPHER_TEST_DLG), hwndDlg, (DLGPROC) CipherTestDialogProc, (LPARAM) 1); + return 1; + } + + if (lw == IDM_REFRESH_DRIVE_LETTERS) + { + DWORD driveMap = GetUsedLogicalDrives (); + + WaitCursor (); + + if (!(nCurrentOS == WIN_2000 && RemoteSession)) + { + BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, 0, ~driveMap); + Sleep (100); + BroadcastDeviceChange (DBT_DEVICEARRIVAL, 0, driveMap); + } + + LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), 0); + + if (nSelectedDriveIndex >= 0) + { + SelectItem (GetDlgItem (hwndDlg, IDC_DRIVELIST), + (wchar_t) HIWORD (GetItemLong (GetDlgItem (hwndDlg, IDC_DRIVELIST), nSelectedDriveIndex))); + } + + NormalCursor (); + return 1; + } + + if (lw == IDM_MOUNT_FAVORITE_VOLUMES) + { + _beginthread(mountFavoriteVolumeThreadFunction, 0, NULL); + return 1; + } + + if (lw == IDM_RESUME_INTERRUPTED_PROC) + { + // Ask the user to select encryption, decryption, or cancel + BOOL bDecrypt = FALSE; + char *tmpStr[] = {0, + "CHOOSE_ENCRYPT_OR_DECRYPT", + "ENCRYPT", + "DECRYPT", + "IDCANCEL", + 0}; + + switch (AskMultiChoice ((void **) tmpStr, FALSE, hwndDlg)) + { + case 1: + bDecrypt = FALSE; + break; + case 2: + bDecrypt = TRUE; + break; + default: + return 1; + } + ResumeInterruptedNonSysInplaceEncProcess (bDecrypt); + return 1; + } + + if (lw == IDC_VOLUME_PROPERTIES || lw == IDM_VOLUME_PROPERTIES) + { + DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_VOLUME_PROPERTIES), hwndDlg, + (DLGPROC) VolumePropertiesDlgProc, (LPARAM) 0); + return 1; + } + + if (lw == IDC_VOLUME && hw == CBN_EDITCHANGE) + { + EnableDisableButtons (hwndDlg); + return 1; + } + + if (lw == IDC_VOLUME && hw == CBN_SELCHANGE) + { + UpdateComboOrder (GetDlgItem (hwndDlg, IDC_VOLUME)); + MoveEditToCombo ((HWND) lParam, bHistory); + PostMessage (hwndDlg, TC_APPMSG_MOUNT_ENABLE_DISABLE_CONTROLS, 0, 0); + return 1; + } + + if (lw == IDC_NO_HISTORY) + { + if (!(bHistory = !IsButtonChecked (GetDlgItem (hwndDlg, IDC_NO_HISTORY)))) + ClearHistory (GetDlgItem (hwndDlg, IDC_VOLUME)); + + return 1; + } + + if (lw >= TC_FAVORITE_MENU_CMD_ID_OFFSET && lw < TC_FAVORITE_MENU_CMD_ID_OFFSET_END) + { + size_t favoriteIndex = lw - TC_FAVORITE_MENU_CMD_ID_OFFSET; + + if (favoriteIndex < FavoriteVolumes.size()) + { + if ((FavoriteVolumes[favoriteIndex].UseVolumeID && IsMountedVolumeID (FavoriteVolumes[favoriteIndex].VolumeID)) + || (!FavoriteVolumes[favoriteIndex].UseVolumeID && IsMountedVolume (FavoriteVolumes[favoriteIndex].Path.c_str())) + ) + { + std::wstring volName; + WaitCursor(); + if (FavoriteVolumes[favoriteIndex].UseVolumeID) + volName = FindDeviceByVolumeID (FavoriteVolumes[favoriteIndex].VolumeID); + else + volName = FavoriteVolumes[favoriteIndex].Path; + OpenVolumeExplorerWindow (GetMountedVolumeDriveNo ((wchar_t*) FavoriteVolumes[favoriteIndex].Path.c_str())); + NormalCursor(); + } + else + { + mountFavoriteVolumeThreadParam* pParam = (mountFavoriteVolumeThreadParam*) calloc(1, sizeof(mountFavoriteVolumeThreadParam)); + pParam->systemFavorites = FALSE; + pParam->logOnMount = FALSE; + pParam->hotKeyMount = FALSE; + pParam->favoriteVolumeToMount = &FavoriteVolumes[favoriteIndex]; + + _beginthread(mountFavoriteVolumeThreadFunction, 0, pParam); + } + } + + return 1; + } + + return 0; + + case WM_DROPFILES: + { + HDROP hdrop = (HDROP) wParam; + DragQueryFile (hdrop, 0, szFileName, ARRAYSIZE (szFileName)); + DragFinish (hdrop); + + AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory); + EnableDisableButtons (hwndDlg); + SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST)); + } + return 1; + + case TC_APPMSG_MOUNT_ENABLE_DISABLE_CONTROLS: + EnableDisableButtons (hwndDlg); + return 1; + + case TC_APPMSG_MOUNT_SHOW_WINDOW: + MainWindowHidden = FALSE; + ShowWindow (hwndDlg, SW_SHOW); + ShowWindow (hwndDlg, SW_RESTORE); + return 1; + + case WM_COPYDATA: + { + PCOPYDATASTRUCT cd = (PCOPYDATASTRUCT)lParam; + if (memcmp (&cd->dwData, WM_COPY_SET_VOLUME_NAME, 4) == 0) + { + if (cd->cbData > 0) + { + ((wchar_t *) cd->lpData)[(cd->cbData / sizeof (wchar_t)) - 1] = 0; + AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), (wchar_t *)cd->lpData, bHistory); + } + + EnableDisableButtons (hwndDlg); + SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST)); + } + } + return 1; + + case WM_CLOSE: + EndMainDlg (hwndDlg); + return 1; + + case WM_INITMENUPOPUP: + { + // disable "Set Header Key Derivation Algorithm" entry in "Volumes" menu + // "Volumes" menu is the first (index 0) submenu of the main menu + if ((HMENU) wParam == GetSubMenu (GetMenu (hwndDlg), 0)) + { + if (ActiveSysEncDeviceSelected ()) + EnableMenuItem (GetMenu (hwndDlg), IDM_CHANGE_HEADER_KEY_DERIV_ALGO, MF_GRAYED); + else + EnableMenuItem (GetMenu (hwndDlg), IDM_CHANGE_HEADER_KEY_DERIV_ALGO, MF_ENABLED); + } + } + return 1; + + default: + // Recreate tray icon if Explorer restarted + if (taskBarCreatedMsg != 0 && uMsg == taskBarCreatedMsg && TaskBarIconMutex != NULL) + { + TaskBarIconRemove (hwndDlg); + TaskBarIconAdd (hwndDlg); + CheckMountList(hwndDlg, TRUE); + return 1; + } + } + + return 0; +} + +void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) +{ + wchar_t **lpszCommandLineArgs = NULL; /* Array of command line arguments */ + int nNoCommandLineArgs; /* The number of arguments in the array */ + wchar_t tmpPath[MAX_PATH * 2]; + + /* Defaults */ + mountOptions.PreserveTimestamp = TRUE; + + if (_wcsicmp (lpszCommandLine, L"-Embedding") == 0) + { + ComServerMode = TRUE; + return; + } + + /* Extract command line arguments */ + NoCmdLineArgs = nNoCommandLineArgs = Win32CommandLine (&lpszCommandLineArgs); + + if (nNoCommandLineArgs > 0) + { + int i; + + for (i = 0; i < nNoCommandLineArgs; i++) + { + enum + { + OptionAuto, + OptionBeep, + OptionCache, + CommandDismount, + OptionExplore, + OptionForce, + CommandHelp, + OptionHistory, + OptionKeyfile, + OptionLetter, + OptionMountOption, + OptionPassword, + OptionQuit, + OptionSilent, + OptionTokenLib, + OptionTokenPin, + OptionVolume, + CommandWipeCache, + OptionPkcs5, + OptionTrueCryptMode, + OptionPim, + OptionTryEmptyPassword, + OptionNoWaitDlg, + }; + + argument args[]= + { + { OptionAuto, L"/auto", L"/a", FALSE }, + { OptionBeep, L"/beep", L"/b", FALSE }, + { OptionCache, L"/cache", L"/c", FALSE }, + { CommandDismount, L"/dismount", L"/d", FALSE }, + { OptionExplore, L"/explore", L"/e", FALSE }, + { OptionForce, L"/force", L"/f", FALSE }, + { OptionPkcs5, L"/hash", NULL , FALSE }, + { CommandHelp, L"/help", L"/?", FALSE }, + { OptionHistory, L"/history", L"/h", FALSE }, + { OptionKeyfile, L"/keyfile", L"/k", FALSE }, + { OptionLetter, L"/letter", L"/l", FALSE }, + { OptionMountOption, L"/mountoption", L"/m", FALSE }, + { OptionPassword, L"/password", L"/p", FALSE }, + { OptionPim, L"/pim", NULL, FALSE }, + { OptionQuit, L"/quit", L"/q", FALSE }, + { OptionSilent, L"/silent", L"/s", FALSE }, + { OptionTokenLib, L"/tokenlib", NULL, FALSE }, + { OptionTokenPin, L"/tokenpin", NULL, FALSE }, + { OptionTrueCryptMode, L"/truecrypt", L"/tc", FALSE }, + { OptionVolume, L"/volume", L"/v", FALSE }, + { CommandWipeCache, L"/wipecache", L"/w", FALSE }, + { OptionTryEmptyPassword, L"/tryemptypass", NULL, FALSE }, + { OptionNoWaitDlg, L"/nowaitdlg", NULL, FALSE }, + }; + + argumentspec as; + + as.args = args; + as.arg_cnt = sizeof(args)/ sizeof(args[0]); + + switch (GetArgumentID (&as, lpszCommandLineArgs[i])) + { + case OptionAuto: + { + wchar_t szTmp[32] = {0}; + bAuto = TRUE; + + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, + &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) + { + if (!_wcsicmp (szTmp, L"devices")) + bAutoMountDevices = TRUE; + else if (!_wcsicmp (szTmp, L"favorites")) + bAutoMountFavorites = TRUE; + else if (!_wcsicmp (szTmp, L"logon")) + LogOn = TRUE; + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + } + break; + + case OptionBeep: + bBeep = TRUE; + break; + + case OptionTryEmptyPassword: + { + wchar_t szTmp[16] = {0}; + bCmdTryEmptyPasswordWhenKeyfileUsed = TRUE; + bCmdTryEmptyPasswordWhenKeyfileUsedValid = TRUE; + + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, + szTmp, ARRAYSIZE (szTmp))) + { + if (!_wcsicmp(szTmp,L"n") || !_wcsicmp(szTmp,L"no")) + bCmdTryEmptyPasswordWhenKeyfileUsed = FALSE; + else if (!_wcsicmp(szTmp,L"y") || !_wcsicmp(szTmp,L"yes")) + bCmdTryEmptyPasswordWhenKeyfileUsed = TRUE; + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + } + break; + + case OptionNoWaitDlg: + { + wchar_t szTmp[16] = {0}; + bCmdHideWaitingDialog = TRUE; + bCmdHideWaitingDialogValid = TRUE; + + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, + szTmp, ARRAYSIZE (szTmp))) + { + if (!_wcsicmp(szTmp,L"n") || !_wcsicmp(szTmp,L"no")) + bCmdHideWaitingDialog = FALSE; + else if (!_wcsicmp(szTmp,L"y") || !_wcsicmp(szTmp,L"yes")) + bCmdHideWaitingDialog = TRUE; + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + } + break; + + case OptionCache: + { + wchar_t szTmp[16] = {0}; + bCacheInDriver = TRUE; + bIncludePimInCache = FALSE; + + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, + szTmp, ARRAYSIZE (szTmp))) + { + if (!_wcsicmp(szTmp,L"n") || !_wcsicmp(szTmp,L"no")) + bCacheInDriver = FALSE; + else if (!_wcsicmp(szTmp,L"y") || !_wcsicmp(szTmp,L"yes")) + bCacheInDriver = TRUE; + else if (!_wcsicmp(szTmp,L"p") || !_wcsicmp(szTmp,L"pim")) + { + bCacheInDriver = TRUE; + bIncludePimInCache = TRUE; + } + else if (!_wcsicmp(szTmp,L"f") || !_wcsicmp(szTmp,L"favorites")) + { + bCacheInDriver = FALSE; + bCmdCacheDuringMultipleMount = TRUE; + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + } + break; + + case CommandDismount: + + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, + szDriveLetter, ARRAYSIZE (szDriveLetter))) + { + if ( (wcslen(szDriveLetter) == 1) + || (wcslen(szDriveLetter) == 2 && szDriveLetter[1] == L':') + ) + { + cmdUnmountDrive = towupper(szDriveLetter[0]) - L'A'; + if ((cmdUnmountDrive < 0) || (cmdUnmountDrive > (L'Z' - L'A'))) + AbortProcess ("BAD_DRIVE_LETTER"); + } + else + AbortProcess ("BAD_DRIVE_LETTER"); + + } + else + cmdUnmountDrive = -1; + + break; + + case OptionExplore: + bExplore = TRUE; + break; + + case OptionForce: + bForceMount = TRUE; + bForceUnmount = TRUE; + break; + + case OptionKeyfile: + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, + nNoCommandLineArgs, tmpPath, ARRAYSIZE (tmpPath))) + { + KeyFile *kf; + RelativePath2Absolute (tmpPath); + kf = (KeyFile *) malloc (sizeof (KeyFile)); + if (kf) + { + StringCchCopyW (kf->FileName, ARRAYSIZE(kf->FileName), tmpPath); + FirstCmdKeyFile = KeyFileAdd (FirstCmdKeyFile, kf); + } + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + + break; + + case OptionLetter: + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, + szDriveLetter, ARRAYSIZE (szDriveLetter))) + { + if ( (wcslen(szDriveLetter) == 1) + || (wcslen(szDriveLetter) == 2 && szDriveLetter[1] == L':') + ) + { + commandLineDrive = *szDriveLetter = (wchar_t) towupper (*szDriveLetter); + + if (commandLineDrive < L'A' || commandLineDrive > L'Z') + AbortProcess ("BAD_DRIVE_LETTER"); + } + else + AbortProcess ("BAD_DRIVE_LETTER"); + } + else + AbortProcess ("BAD_DRIVE_LETTER"); + + break; + + case OptionHistory: + { + wchar_t szTmp[8] = {0}; + bHistory = bHistoryCmdLine = TRUE; + + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, + szTmp, ARRAYSIZE (szTmp))) + { + if (!_wcsicmp(szTmp,L"n") || !_wcsicmp(szTmp,L"no")) + bHistory = FALSE; + else if (!_wcsicmp(szTmp,L"y") || !_wcsicmp(szTmp,L"yes")) + bHistory = TRUE; + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + } + break; + + case OptionMountOption: + { + wchar_t szTmp[64] = {0}; + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, + &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) + { + if (!_wcsicmp (szTmp, L"ro") || !_wcsicmp (szTmp, L"readonly")) + mountOptions.ReadOnly = TRUE; + + else if (!_wcsicmp (szTmp, L"rm") || !_wcsicmp (szTmp, L"removable")) + mountOptions.Removable = TRUE; + + else if (!_wcsicmp (szTmp, L"ts") || !_wcsicmp (szTmp, L"timestamp")) + mountOptions.PreserveTimestamp = FALSE; + + else if (!_wcsicmp (szTmp, L"sm") || !_wcsicmp (szTmp, L"system")) + mountOptions.PartitionInInactiveSysEncScope = bPrebootPasswordDlgMode = TRUE; + + else if (!_wcsicmp (szTmp, L"bk") || !_wcsicmp (szTmp, L"headerbak")) + mountOptions.UseBackupHeader = TRUE; + + else if (!_wcsicmp (szTmp, L"recovery")) + mountOptions.RecoveryMode = TRUE; + else if ((wcslen(szTmp) > 6) && (wcslen(szTmp) <= 38) && !_wcsnicmp (szTmp, L"label=", 6)) + { + // get the label + StringCbCopyW (mountOptions.Label, sizeof (mountOptions.Label), &szTmp[6]); + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + + CmdMountOptions = mountOptions; + CmdMountOptionsValid = TRUE; + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + break; + + case OptionPassword: + { + wchar_t szTmp[MAX_PASSWORD + 1]; + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, + szTmp, ARRAYSIZE (szTmp))) + { + int iLen = WideCharToMultiByte (CP_UTF8, 0, szTmp, -1, (char*) CmdVolumePassword.Text, MAX_PASSWORD + 1, NULL, NULL); + burn (szTmp, sizeof (szTmp)); + if (iLen > 0) + { + CmdVolumePassword.Length = (unsigned __int32) (iLen - 1); + CmdVolumePasswordValid = TRUE; + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + break; + + case OptionVolume: + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, + nNoCommandLineArgs, szFileName, ARRAYSIZE (szFileName))) + { + RelativePath2Absolute (szFileName); + AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory); + CmdLineVolumeSpecified = TRUE; + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + break; + + case OptionQuit: + { + wchar_t szTmp[32] = {0}; + + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, + &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) + { + if (!_wcsicmp (szTmp, L"UAC")) // Used to indicate non-install elevation + break; + + else if (!_wcsicmp (szTmp, L"preferences")) + { + Quit = TRUE; + UsePreferences = TRUE; + break; + } + + else if (!_wcsicmp (szTmp, L"background")) + bEnableBkgTask = TRUE; + + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + + Quit = TRUE; + UsePreferences = FALSE; + } + break; + + case OptionSilent: + Silent = TRUE; + break; + + case OptionTokenLib: + if (GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, SecurityTokenLibraryPath, ARRAYSIZE (SecurityTokenLibraryPath)) == HAS_ARGUMENT) + InitSecurityTokenLibrary(hwndDlg); + else + AbortProcess ("COMMAND_LINE_ERROR"); + + break; + + case OptionTokenPin: + { + wchar_t szTmp[SecurityToken::MaxPasswordLength + 1] = {0}; + if (GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp)) == HAS_ARGUMENT) + { + if (0 == WideCharToMultiByte (CP_UTF8, 0, szTmp, -1, CmdTokenPin, array_capacity (CmdTokenPin), nullptr, nullptr)) + AbortProcess ("COMMAND_LINE_ERROR"); + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + + break; + + case CommandWipeCache: + bWipe = TRUE; + break; + + case CommandHelp: + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_COMMANDHELP_DLG), hwndDlg, (DLGPROC) + CommandHelpDlgProc, (LPARAM) &as); + exit(0); + break; + + case OptionPkcs5: + { + wchar_t szTmp[32] = {0}; + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, + &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) + { + if (_wcsicmp(szTmp, L"sha512") == 0 || _wcsicmp(szTmp, L"sha-512") == 0) + CmdVolumePkcs5 = SHA512; + else if (_wcsicmp(szTmp, L"whirlpool") == 0) + CmdVolumePkcs5 = WHIRLPOOL; + else if (_wcsicmp(szTmp, L"sha256") == 0 || _wcsicmp(szTmp, L"sha-256") == 0) + CmdVolumePkcs5 = SHA256; + else if (_wcsicmp(szTmp, L"ripemd160") == 0 || _wcsicmp(szTmp, L"ripemd-160") == 0) + CmdVolumePkcs5 = RIPEMD160; + else + { + CmdVolumePkcs5 = 0; + AbortProcess ("COMMAND_LINE_ERROR"); + } + + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + break; + + case OptionPim: + { + wchar_t szTmp[32] = {0}; + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, + &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp))) + { + wchar_t* endPtr = NULL; + CmdVolumePim = (int) wcstol(szTmp, &endPtr, 0); + if (CmdVolumePim < 0 || CmdVolumePim > MAX_PIM_VALUE || endPtr == szTmp || *endPtr != L'\0') + { + CmdVolumePim = 0; + AbortProcess ("COMMAND_LINE_ERROR"); + } + + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + break; + + case OptionTrueCryptMode: + CmdVolumeTrueCryptMode = TRUE; + break; + + // no option = file name if there is only one argument + default: + { + if (nNoCommandLineArgs == 1) + { + StringCbCopyW (szFileName, array_capacity (szFileName), lpszCommandLineArgs[i]); + RelativePath2Absolute (szFileName); + + CmdLineVolumeSpecified = TRUE; + AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory); + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + } + } + } + } + + /* Free up the command line arguments */ + while (--nNoCommandLineArgs >= 0) + { + free (lpszCommandLineArgs[nNoCommandLineArgs]); + } + + if (lpszCommandLineArgs) + free (lpszCommandLineArgs); +} + + +static SERVICE_STATUS SystemFavoritesServiceStatus; +static SERVICE_STATUS_HANDLE SystemFavoritesServiceStatusHandle; + +static void SystemFavoritesServiceLogMessage (const wstring &errorMessage, WORD wType) +{ + HANDLE eventSource = RegisterEventSource (NULL, TC_SYSTEM_FAVORITES_SERVICE_NAME); + + if (eventSource) + { + LPCTSTR strings[] = { TC_SYSTEM_FAVORITES_SERVICE_NAME, errorMessage.c_str() }; + ReportEvent (eventSource, wType, 0, 0xC0000000 + wType, NULL, array_capacity (strings), 0, strings, NULL); + + DeregisterEventSource (eventSource); + } +} + +static void SystemFavoritesServiceLogError (const wstring &errorMessage) +{ + SystemFavoritesServiceLogMessage (errorMessage, EVENTLOG_ERROR_TYPE); +} + +static void SystemFavoritesServiceLogWarning (const wstring &warningMessage) +{ + SystemFavoritesServiceLogMessage (warningMessage, EVENTLOG_WARNING_TYPE); +} + +static void SystemFavoritesServiceLogInfo (const wstring &infoMessage) +{ + SystemFavoritesServiceLogMessage (infoMessage, EVENTLOG_INFORMATION_TYPE); +} + + +static void SystemFavoritesServiceSetStatus (DWORD status, DWORD waitHint = 0) +{ + SystemFavoritesServiceStatus.dwCurrentState = status; + SystemFavoritesServiceStatus.dwWaitHint = waitHint; + SystemFavoritesServiceStatus.dwWin32ExitCode = NO_ERROR; + + SetServiceStatus (SystemFavoritesServiceStatusHandle, &SystemFavoritesServiceStatus); +} + + +static VOID WINAPI SystemFavoritesServiceCtrlHandler (DWORD control) +{ + if (control == SERVICE_CONTROL_STOP) + SystemFavoritesServiceSetStatus (SERVICE_STOP_PENDING); + else + SystemFavoritesServiceSetStatus (SystemFavoritesServiceStatus.dwCurrentState); +} + + +static VOID WINAPI SystemFavoritesServiceMain (DWORD argc, LPTSTR *argv) +{ + BOOL status = FALSE; + memset (&SystemFavoritesServiceStatus, 0, sizeof (SystemFavoritesServiceStatus)); + SystemFavoritesServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + + SystemFavoritesServiceStatusHandle = RegisterServiceCtrlHandler (TC_SYSTEM_FAVORITES_SERVICE_NAME, SystemFavoritesServiceCtrlHandler); + if (!SystemFavoritesServiceStatusHandle) + return; + + SystemFavoritesServiceSetStatus (SERVICE_START_PENDING, 120000); + + SystemFavoritesServiceLogInfo (wstring (L"Starting System Favorites mounting process")); + + try + { + status = MountFavoriteVolumes (NULL, TRUE); + } + catch (...) { } + + if (status) + { + SystemFavoritesServiceLogInfo (wstring (L"System Favorites mounting process finished")); + } + else + { + SystemFavoritesServiceLogError (wstring (L"System Favorites mounting process failed.")); + } + + SystemFavoritesServiceSetStatus (SERVICE_RUNNING); + SystemFavoritesServiceSetStatus (SERVICE_STOPPED); +} + + +static BOOL StartSystemFavoritesService () +{ + ServiceMode = TRUE; + Silent = TRUE; + DeviceChangeBroadcastDisabled = TRUE; + bShowDisconnectedNetworkDrives = TRUE; + bHideWaitingDialog = TRUE; + + InitOSVersionInfo(); + + if (DriverAttach() != ERR_SUCCESS) + return FALSE; + + SERVICE_TABLE_ENTRY serviceTable[2]; + serviceTable[0].lpServiceName = TC_SYSTEM_FAVORITES_SERVICE_NAME; + serviceTable[0].lpServiceProc = SystemFavoritesServiceMain; + + serviceTable[1].lpServiceName = NULL; + serviceTable[1].lpServiceProc = NULL; + + BOOL result = StartServiceCtrlDispatcher (serviceTable); + + if (!(ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD)) + WipeCache (NULL, TRUE); + + return result; +} + +#ifndef VCEXPANDER +int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpszCommandLine, int nCmdShow) +{ + int argc; + LPWSTR *argv = CommandLineToArgvW (GetCommandLineW(), &argc); + + if (argv && argc == 2 && wstring (TC_SYSTEM_FAVORITES_SERVICE_CMDLINE_OPTION) == argv[1]) + return StartSystemFavoritesService() ? 0 : 1; + + int status; + atexit (localcleanup); + SetProcessShutdownParameters (0x100, 0); + + VirtualLock (&VolumePassword, sizeof (VolumePassword)); + VirtualLock (&CmdVolumePassword, sizeof (CmdVolumePassword)); + VirtualLock (&mountOptions, sizeof (mountOptions)); + VirtualLock (&defaultMountOptions, sizeof (defaultMountOptions)); + VirtualLock (&szFileName, sizeof(szFileName)); + VirtualLock (&CmdTokenPin, sizeof (CmdTokenPin)); + + DetectX86Features (); + + try + { + BootEncObj = new BootEncryption (NULL); + } + catch (Exception &e) + { + e.Show (NULL); + } + + if (BootEncObj == NULL) + AbortProcess ("INIT_SYS_ENC"); + + InitApp (hInstance, lpszCommandLine); + + RegisterRedTick(hInstance); + + /* Allocate, dup, then store away the application title */ + lpszTitle = L"VeraCrypt"; + + status = DriverAttach (); + if (status != 0) + { + if (status == ERR_OS_ERROR) + handleWin32Error (NULL, SRC_POS); + else + handleError (NULL, status, SRC_POS); + + AbortProcess ("NODRIVER"); + } + + /* Create the main dialog box */ + DialogBoxParamW (hInstance, MAKEINTRESOURCEW (IDD_MOUNT_DLG), NULL, (DLGPROC) MainDialogProc, + (LPARAM) lpszCommandLine); + + FinalizeApp (); + /* Terminate */ + return 0; +} +#endif + + +BOOL TaskBarIconAdd (HWND hwnd) +{ + NOTIFYICONDATAW tnid; + + ZeroMemory (&tnid, sizeof (tnid)); + + // Only one icon may be created + if (TaskBarIconMutex != NULL) return TRUE; + + TaskBarIconMutex = CreateMutex (NULL, TRUE, L"VeraCryptTaskBarIcon"); + if (TaskBarIconMutex == NULL || GetLastError () == ERROR_ALREADY_EXISTS) + { + if (TaskBarIconMutex != NULL) + { + CloseHandle(TaskBarIconMutex); + TaskBarIconMutex = NULL; + } + return FALSE; + } + + tnid.cbSize = sizeof (NOTIFYICONDATAW); + tnid.hWnd = hwnd; + tnid.uID = IDI_TRUECRYPT_ICON; + tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; + tnid.uCallbackMessage = TC_APPMSG_TASKBAR_ICON; + tnid.hIcon = (HICON) LoadImage (hInst, MAKEINTRESOURCE (IDI_TRUECRYPT_ICON), + IMAGE_ICON, + ScreenDPI >= 120 ? 0 : 16, + ScreenDPI >= 120 ? 0 : 16, + (ScreenDPI >= 120 ? LR_DEFAULTSIZE : 0) + | LR_SHARED + | (nCurrentOS != WIN_2000 ? LR_DEFAULTCOLOR : LR_VGACOLOR)); // Windows 2000 cannot display more than 16 fixed colors in notification tray + + StringCbCopyW (tnid.szTip, sizeof(tnid.szTip), L"VeraCrypt"); + + return Shell_NotifyIconW (NIM_ADD, &tnid); +} + + +BOOL TaskBarIconRemove (HWND hwnd) +{ + if (TaskBarIconMutex != NULL) + { + NOTIFYICONDATA tnid; + BOOL res; + + ZeroMemory (&tnid, sizeof (tnid)); + tnid.cbSize = sizeof(NOTIFYICONDATA); + tnid.hWnd = hwnd; + tnid.uID = IDI_TRUECRYPT_ICON; + + res = Shell_NotifyIcon (NIM_DELETE, &tnid); + if (TaskBarIconMutex) + { + CloseHandle (TaskBarIconMutex); + TaskBarIconMutex = NULL; + } + return res; + } + else + return FALSE; +} + + +BOOL TaskBarIconChange (HWND hwnd, int iconId) +{ + if (TaskBarIconMutex == NULL) + return FALSE; + + NOTIFYICONDATA tnid; + + ZeroMemory (&tnid, sizeof (tnid)); + + tnid.cbSize = sizeof (tnid); + tnid.hWnd = hwnd; + tnid.uID = IDI_TRUECRYPT_ICON; + tnid.uFlags = NIF_ICON; + tnid.hIcon = (HICON) LoadImage (hInst, MAKEINTRESOURCE (iconId), + IMAGE_ICON, + ScreenDPI >= 120 ? 0 : 16, + ScreenDPI >= 120 ? 0 : 16, + (ScreenDPI >= 120 ? LR_DEFAULTSIZE : 0) + | LR_SHARED + | (nCurrentOS != WIN_2000 ? LR_DEFAULTCOLOR : LR_VGACOLOR)); // Windows 2000 cannot display more than 16 fixed colors in notification tray + + return Shell_NotifyIcon (NIM_MODIFY, &tnid); +} + + +void DismountIdleVolumes () +{ + static DWORD lastMinTickCount; + static int InactivityTime[26]; + static unsigned __int64 LastRead[26], LastWritten[26]; + static int LastId[26]; + + VOLUME_PROPERTIES_STRUCT prop; + DWORD dwResult; + BOOL bResult; + int i; + + if (GetTickCount() > lastMinTickCount && GetTickCount() - lastMinTickCount < 60 * 1000) + return; + + lastMinTickCount = GetTickCount(); + + for (i = 0; i < 26; i++) + { + if (LastKnownMountList.ulMountedDrives & (1 << i)) + { + memset (&prop, 0, sizeof(prop)); + prop.driveNo = i; + + bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, + sizeof (prop), &prop, sizeof (prop), &dwResult, NULL); + + if ( bResult + && ( (prop.driveNo == i) && prop.uniqueId >= 0 + && prop.ea >= EAGetFirst() && prop.ea <= EAGetCount() + && prop.mode >= FIRST_MODE_OF_OPERATION_ID && prop.mode <= LAST_MODE_OF_OPERATION + && prop.pkcs5 >= FIRST_PRF_ID && prop.pkcs5 <= LAST_PRF_ID + && prop.pkcs5Iterations > 0 + && prop.hiddenVolProtection >= 0 && prop.volFormatVersion >= 0 + && prop.volumePim >= 0 + ) + ) + { + if (LastRead[i] == prop.totalBytesRead + && LastWritten[i] == prop.totalBytesWritten + && LastId[i] == prop.uniqueId) + { + if (++InactivityTime[i] >= MaxVolumeIdleTime) + { + BroadcastDeviceChange (DBT_DEVICEREMOVEPENDING, i, 0); + + if (bCloseDismountedWindows && CloseVolumeExplorerWindows (MainDlg, i)) + Sleep (250); + + if (DriverUnmountVolume (MainDlg, i, bForceAutoDismount) == 0) + { + InactivityTime[i] = 0; + BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, i, 0); + + if (bWipeCacheOnAutoDismount) + { + DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); + SecurityToken::CloseAllSessions(); + } + } + } + } + else + { + InactivityTime[i] = 0; + LastRead[i] = prop.totalBytesRead; + LastWritten[i] = prop.totalBytesWritten; + LastId[i] = prop.uniqueId; + } + } + } + } +} + +static BOOL MountFavoriteVolumeBase (HWND hwnd, const FavoriteVolume &favorite, BOOL& lastbExplore, BOOL& userForcedReadOnly, BOOL systemFavorites, BOOL logOnMount, BOOL hotKeyMount, const FavoriteVolume &favoriteVolumeToMount) +{ + BOOL status = TRUE; + int drive; + std::wstring effectiveVolumePath; + drive = towupper (favorite.MountPoint[0]) - L'A'; + + if ((drive < MIN_MOUNTED_VOLUME_DRIVE_NUMBER) || (drive > MAX_MOUNTED_VOLUME_DRIVE_NUMBER)) + { + if (!systemFavorites) + Error ("DRIVE_LETTER_UNAVAILABLE", MainDlg); + else if (ServiceMode && systemFavorites) + { + SystemFavoritesServiceLogError (wstring (L"The drive letter ") + (wchar_t) (drive + L'A') + wstring (L" used by favorite \"") + favorite.Path + L"\" is invalid.\nThis system favorite will not be mounted"); + } + return FALSE; + } + + mountOptions.ReadOnly = favorite.ReadOnly || userForcedReadOnly; + mountOptions.Removable = favorite.Removable; + if (favorite.UseLabelInExplorer && !favorite.Label.empty()) + StringCbCopyW (mountOptions.Label, sizeof (mountOptions.Label), favorite.Label.c_str()); + else + ZeroMemory (mountOptions.Label, sizeof (mountOptions.Label)); + + if (favorite.UseVolumeID && !IsRepeatedByteArray (0, favorite.VolumeID, sizeof (favorite.VolumeID))) + { + effectiveVolumePath = FindDeviceByVolumeID (favorite.VolumeID); + } + else + effectiveVolumePath = favorite.Path; + + if (favorite.SystemEncryption) + { + mountOptions.PartitionInInactiveSysEncScope = TRUE; + bPrebootPasswordDlgMode = TRUE; + } + else + { + mountOptions.PartitionInInactiveSysEncScope = FALSE; + bPrebootPasswordDlgMode = FALSE; + } + + if ((LastKnownMountList.ulMountedDrives & (1 << drive)) == 0) + { + MountVolumesAsSystemFavorite = systemFavorites; + + wstring mountPoint = (wchar_t) (drive + L'A') + wstring (L":\\"); + wchar_t prevVolumeAtMountPoint[MAX_PATH] = { 0 }; + + if (systemFavorites) + { + // Partitions of new drives are assigned free drive letters by Windows on boot. Make sure this does not prevent system favorite volumes + // from being mounted. Each partition (using the same drive letter as a system favorite volume) is assigned another free drive letter. + + if (GetVolumeNameForVolumeMountPoint (mountPoint.c_str(), prevVolumeAtMountPoint, ARRAYSIZE (prevVolumeAtMountPoint))) + DeleteVolumeMountPoint (mountPoint.c_str()); + else + prevVolumeAtMountPoint[0] = 0; + } + + lastbExplore = bExplore; + + bExplore = (BOOL) favorite.OpenExplorerWindow; + + if (!systemFavorites + && !logOnMount + && !hotKeyMount + && !favoriteVolumeToMount.Path.empty() + && GetAsyncKeyState (VK_CONTROL) < 0) + { + /* Priority is given to command line parameters + * Default values used only when nothing specified in command line + */ + if (CmdVolumePkcs5 == 0) + mountOptions.ProtectedHidVolPkcs5Prf = DefaultVolumePkcs5; + else + mountOptions.ProtectedHidVolPkcs5Prf = CmdVolumePkcs5; + mountOptions.ProtectedHidVolPim = CmdVolumePim; + if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwnd, (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions) == IDCANCEL) + { + status = FALSE; + goto skipMount; + } + } + + BOOL prevReadOnly = mountOptions.ReadOnly; + + if (ServiceMode) + SystemFavoritesServiceLogInfo (wstring (L"Mounting system favorite \"") + effectiveVolumePath + L"\""); + + status = Mount (hwnd, drive, (wchar_t *) effectiveVolumePath.c_str(), favorite.Pim); + + if (ServiceMode) + { + // Update the service status to avoid being killed + SystemFavoritesServiceStatus.dwCheckPoint++; + SystemFavoritesServiceSetStatus (SERVICE_START_PENDING, 120000); + + if (status) + { + SystemFavoritesServiceLogInfo (wstring (L"Favorite \"") + effectiveVolumePath + wstring (L"\" mounted successfully as ") + (wchar_t) (drive + L'A') + L":"); + } + else + { + SystemFavoritesServiceLogError (wstring (L"Favorite \"") + effectiveVolumePath + L"\" failed to mount"); + } + } + + if (status && mountOptions.ReadOnly != prevReadOnly) + userForcedReadOnly = mountOptions.ReadOnly; + +skipMount: + bExplore = lastbExplore; + + if (systemFavorites && prevVolumeAtMountPoint[0]) + { + if (status) + { + int freeDrive = GetFirstAvailableDrive(); + if (freeDrive != -1) + { + mountPoint[0] = (wchar_t) (freeDrive + L'A'); + SetVolumeMountPoint (mountPoint.c_str(), prevVolumeAtMountPoint); + } + } + else + SetVolumeMountPoint (mountPoint.c_str(), prevVolumeAtMountPoint); + } + + LoadDriveLetters (MainDlg, GetDlgItem (MainDlg, IDC_DRIVELIST), 0); + + MountVolumesAsSystemFavorite = FALSE; + + if (ServiceMode && LastMountedVolumeDirty) + { + DWORD bytesOut; + DeviceIoControl (hDriver, TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY, NULL, 0, NULL, 0, &bytesOut, NULL); + + SystemFavoritesServiceLogError (wstring (L"The filesystem of the volume mounted as ") + (wchar_t) (drive + L'A') + L": was not cleanly dismounted and needs to be checked for errors."); + } + } + else if (!systemFavorites && !favoriteVolumeToMount.Path.empty()) + Error ("DRIVE_LETTER_UNAVAILABLE", MainDlg); + else if (ServiceMode && systemFavorites) + { + SystemFavoritesServiceLogError (wstring (L"The drive letter ") + (wchar_t) (drive + L'A') + wstring (L" used by favorite \"") + effectiveVolumePath + L"\" is already taken.\nThis system favorite will not be mounted"); + } + + return status; +} + + +BOOL MountFavoriteVolumes (HWND hwnd, BOOL systemFavorites, BOOL logOnMount, BOOL hotKeyMount, const FavoriteVolume &favoriteVolumeToMount) +{ + BOOL bRet = TRUE, status = TRUE; + BOOL lastbExplore; + BOOL userForcedReadOnly = FALSE; + + if (ServiceMode) + { + // in service case, intialize some global variable here. + LastKnownMountList.ulMountedDrives = 0; + LoadDriveLetters (MainDlg, GetDlgItem (MainDlg, IDC_DRIVELIST), 0); + } + + mountOptions = defaultMountOptions; + + VolumePassword.Length = 0; + MultipleMountOperationInProgress = (favoriteVolumeToMount.Path.empty() || FavoriteMountOnArrivalInProgress); + + vector favorites, skippedSystemFavorites; + + if (systemFavorites) + { + try + { + if (ServiceMode) + SystemFavoritesServiceLogInfo (wstring (L"Reading System Favorites XML file")); + LoadFavoriteVolumes (favorites, true); + + if (ServiceMode) + { + wchar_t szTmp[32]; + StringCbPrintf (szTmp, sizeof(szTmp), L"%d", (int) favorites.size()); + SystemFavoritesServiceLogInfo (wstring (L"Loaded ") + szTmp + wstring (L" favorites from the file")); + + /* correct set the connected state of the system favorites */ + for (vector ::iterator favorite = favorites.begin(); + favorite != favorites.end(); favorite++) + { + if (favorite->UseVolumeID) + { + std::wstring path = FindDeviceByVolumeID (favorite->VolumeID); + if (path.empty ()) + { + favorite->DisconnectedDevice = true; + } + else + { + favorite->DisconnectedDevice = false; + favorite->Path = path; + favorite->UseVolumeID = false; /* force the use of real path to avoid calling FindDeviceByVolumeID again */ + } + } + } + } + } + catch (...) + { + if (ServiceMode) + SystemFavoritesServiceLogError (wstring (L"An error occured while reading System Favorites XML file")); + return false; + } + } + else if (!favoriteVolumeToMount.Path.empty()) + favorites.push_back (favoriteVolumeToMount); + else + favorites = FavoriteVolumes; + + foreach (const FavoriteVolume &favorite, favorites) + { + if (ServiceMode && systemFavorites && favorite.DisconnectedDevice) + { + skippedSystemFavorites.push_back (favorite); + if (favorite.UseVolumeID) + SystemFavoritesServiceLogWarning (wstring (L"Favorite \"ID:") + ArrayToHexWideString (favorite.VolumeID, sizeof (favorite.VolumeID)) + L"\" is disconnected. It will be ignored."); + else + SystemFavoritesServiceLogWarning (wstring (L"Favorite \"") + favorite.Path + L"\" is disconnected. It will be ignored."); + } + + if (favorite.DisconnectedDevice + || (logOnMount && !favorite.MountOnLogOn) + || (hotKeyMount && favorite.DisableHotkeyMount)) + { + continue; + } + + status = MountFavoriteVolumeBase (hwnd, favorite, lastbExplore, userForcedReadOnly, systemFavorites, logOnMount, hotKeyMount, favoriteVolumeToMount); + if (!status) + bRet = FALSE; + } + + if (systemFavorites && ServiceMode && !skippedSystemFavorites.empty()) + { + // Some drives need more time to initialize correctly. + // We retry 4 times after sleeping 5 seconds + int retryCounter = 0; + size_t remainingFavorites = skippedSystemFavorites.size(); + while ((remainingFavorites > 0) && (retryCounter++ < 4)) + { + Sleep (5000); + + SystemFavoritesServiceLogInfo (wstring (L"Trying to mount skipped system favorites")); + + // Update the service status to avoid being killed + SystemFavoritesServiceStatus.dwCheckPoint++; + SystemFavoritesServiceSetStatus (SERVICE_START_PENDING, 120000); + + for (vector ::iterator favorite = skippedSystemFavorites.begin(); + favorite != skippedSystemFavorites.end(); favorite++) + { + if (favorite->DisconnectedDevice) + { + // check if the favorite is here and get its path + wstring resolvedPath; + if (favorite->UseVolumeID) + { + resolvedPath = FindDeviceByVolumeID (favorite->VolumeID); + } + else + resolvedPath = VolumeGuidPathToDevicePath (favorite->Path); + if (!resolvedPath.empty()) + { + favorite->DisconnectedDevice = false; + favorite->VolumePathId = favorite->Path; + favorite->Path = resolvedPath; + + remainingFavorites--; + + // favorite OK. + if (favorite->UseVolumeID) + SystemFavoritesServiceLogInfo (wstring (L"Favorite \"ID:") + ArrayToHexWideString (favorite->VolumeID, sizeof (favorite->VolumeID)) + L"\" is connected. Performing mount."); + else + SystemFavoritesServiceLogInfo (wstring (L"Favorite \"") + favorite->VolumePathId + L"\" is connected. Performing mount."); + + status = MountFavoriteVolumeBase (hwnd, *favorite, lastbExplore, userForcedReadOnly, systemFavorites, logOnMount, hotKeyMount, favoriteVolumeToMount); + if (!status) + bRet = FALSE; + } + } + } + + if (remainingFavorites == 0) + SystemFavoritesServiceLogInfo (wstring (L"All skipped system favorites have been processed")); + else + { + wchar_t szTmp[32]; + StringCbPrintfW (szTmp, sizeof(szTmp), L"%d", (int) remainingFavorites); + SystemFavoritesServiceLogWarning (wstring (L"Number of unprocessed system favorites is ") + szTmp); + } + } + } + + MultipleMountOperationInProgress = FALSE; + burn (&VolumePassword, sizeof (VolumePassword)); + burn (&VolumePkcs5, sizeof (VolumePkcs5)); + burn (&VolumePim, sizeof (VolumePim)); + burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); + + if (bRet && CloseSecurityTokenSessionsAfterMount) + SecurityToken::CloseAllSessions(); + + return bRet; +} + +void CALLBACK mountFavoriteVolumeCallbackFunction (void *pArg, HWND hwnd) +{ + mountFavoriteVolumeThreadParam* pParam = (mountFavoriteVolumeThreadParam*) pArg; + + if (pParam) + { + if (pParam->favoriteVolumeToMount) + MountFavoriteVolumes (hwnd, pParam->systemFavorites, pParam->logOnMount, pParam->hotKeyMount, *(pParam->favoriteVolumeToMount)); + else + MountFavoriteVolumes (hwnd, pParam->systemFavorites, pParam->logOnMount, pParam->hotKeyMount); + + free (pParam); + } + else + MountFavoriteVolumes (hwnd); +} + +void __cdecl mountFavoriteVolumeThreadFunction (void *pArg) +{ + ShowWaitDialog (MainDlg, FALSE, mountFavoriteVolumeCallbackFunction, pArg); +} + +static void SaveDefaultKeyFilesParam (HWND hwnd) +{ + if (defaultKeyFilesParam.FirstKeyFile == NULL) + { + /* No keyfiles selected */ + _wremove (GetConfigPath (TC_APPD_FILENAME_DEFAULT_KEYFILES)); + } + else + { + FILE *f; + KeyFile *kf = FirstKeyFile; + + f = _wfopen (GetConfigPath (TC_APPD_FILENAME_DEFAULT_KEYFILES), L"w,ccs=UTF-8"); + if (f == NULL) + { + handleWin32Error (MainDlg, SRC_POS); + return; + } + + XmlWriteHeader (f); + + fputws (L"\n\t", f); + + while (kf != NULL) + { + wchar_t q[TC_MAX_PATH * 2]; + + XmlQuoteTextW (kf->FileName, q, ARRAYSIZE (q)); + fwprintf (f, L"\n\t\t%s", q); + + kf = kf->Next; + } + + fputws (L"\n\t", f); + + XmlWriteFooter (f); + + CheckFileStreamWriteErrors (hwnd, f, TC_APPD_FILENAME_DEFAULT_KEYFILES); + fclose (f); + return; + } +} + + +static void KeyfileDefaultsDlg (HWND hwndDlg) +{ + KeyFilesDlgParam param; + + param.EnableKeyFiles = defaultKeyFilesParam.EnableKeyFiles; + param.FirstKeyFile = defaultKeyFilesParam.FirstKeyFile; + + if (DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg, + (DLGPROC) KeyFilesDlgProc, (LPARAM) ¶m) == IDOK) + { + if (!param.EnableKeyFiles || AskWarnYesNo ("CONFIRM_SAVE_DEFAULT_KEYFILES", hwndDlg) == IDYES) + { + KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile); + defaultKeyFilesParam.EnableKeyFiles = param.EnableKeyFiles; + defaultKeyFilesParam.FirstKeyFile = param.FirstKeyFile; + + RestoreDefaultKeyFilesParam (); + SaveDefaultKeyFilesParam (hwndDlg); + } + } +} + + +static void HandleHotKey (HWND hwndDlg, WPARAM wParam) +{ + DWORD dwResult; + BOOL success = TRUE; + + switch (wParam) + { + case HK_AUTOMOUNT_DEVICES: + MountAllDevices (hwndDlg, TRUE); + break; + + case HK_DISMOUNT_ALL: + case HK_DISMOUNT_ALL_AND_WIPE: + + if (wParam == HK_DISMOUNT_ALL_AND_WIPE) + WipeCache (hwndDlg, TRUE); + + if (DismountAll (hwndDlg, FALSE, TRUE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY)) + { + if (bDisplayBalloonOnSuccessfulHkDismount) + InfoBalloon ("SUCCESSFULLY_DISMOUNTED", (wParam == HK_DISMOUNT_ALL_AND_WIPE ? "VOLUMES_DISMOUNTED_CACHE_WIPED" : "MOUNTED_VOLUMES_DISMOUNTED"), hwndDlg); + + if (bPlaySoundOnSuccessfulHkDismount) + MessageBeep (0xFFFFFFFF); + } + + break; + + case HK_WIPE_CACHE: + WipeCache (hwndDlg, FALSE); + + break; + + case HK_FORCE_DISMOUNT_ALL_AND_WIPE: + success = DismountAll (hwndDlg, TRUE, FALSE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); + success &= DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); + if (success) + { + if (bDisplayBalloonOnSuccessfulHkDismount) + InfoBalloon ("SUCCESSFULLY_DISMOUNTED", "VOLUMES_DISMOUNTED_CACHE_WIPED", hwndDlg); + + if (bPlaySoundOnSuccessfulHkDismount) + MessageBeep (0xFFFFFFFF); + } + break; + + case HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT: + success = DismountAll (hwndDlg, TRUE, FALSE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); + success &= DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); + if (success) + { + if (bDisplayBalloonOnSuccessfulHkDismount) + InfoBalloon ("SUCCESSFULLY_DISMOUNTED", "VOLUMES_DISMOUNTED_CACHE_WIPED", hwndDlg); + + if (bPlaySoundOnSuccessfulHkDismount) + MessageBeep (0xFFFFFFFF); + } + TaskBarIconRemove (hwndDlg); + UnregisterWtsNotification(hwndDlg); + EndMainDlg (hwndDlg); + break; + + case HK_MOUNT_FAVORITE_VOLUMES: + { + mountFavoriteVolumeThreadParam* pParam = (mountFavoriteVolumeThreadParam*) calloc(1, sizeof(mountFavoriteVolumeThreadParam)); + pParam->systemFavorites = FALSE; + pParam->logOnMount = FALSE; + pParam->hotKeyMount = TRUE; + pParam->favoriteVolumeToMount = NULL; + + _beginthread(mountFavoriteVolumeThreadFunction, 0, pParam); + } + break; + + case HK_SHOW_HIDE_MAIN_WINDOW: + ChangeMainWindowVisibility (); + break; + + case HK_CLOSE_SECURITY_TOKEN_SESSIONS: + SecurityToken::CloseAllSessions(); + + InfoBalloon (NULL, "ALL_TOKEN_SESSIONS_CLOSED", hwndDlg); + + break; + } +} + + +void ChangeMainWindowVisibility () +{ + MainWindowHidden = !MainWindowHidden; + + if (!MainWindowHidden) + SetForegroundWindow (MainDlg); + + ShowWindow (MainDlg, !MainWindowHidden ? SW_SHOW : SW_HIDE); + + if (!MainWindowHidden) + ShowWindow (MainDlg, SW_RESTORE); +} + + +int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, const wchar_t *lpszVolume) +{ + int nStatus = ERR_OS_ERROR; + wchar_t szTmp[4096]; + int fBackup = -1; + OpenVolumeContext volume; + OpenVolumeContext hiddenVolume; + Password hiddenVolPassword; + int hiddenVolPkcs5 = 0, hiddenVolPim = 0; + byte temporaryKey[MASTER_KEYDATA_SIZE]; + byte originalK2[MASTER_KEYDATA_SIZE]; + int EffectiveVolumePkcs5 = CmdVolumePkcs5; + int EffectiveVolumePim = CmdVolumePim; + + /* Priority is given to command line parameters + * Default values used only when nothing specified in command line + */ + if (EffectiveVolumePkcs5 == 0) + EffectiveVolumePkcs5 = DefaultVolumePkcs5; + + if (!lpszVolume) + { + nStatus = ERR_OUTOFMEMORY; + handleError (hwndDlg, nStatus, SRC_POS); + return nStatus; + } + + volume.VolumeIsOpen = FALSE; + hiddenVolume.VolumeIsOpen = FALSE; + + switch (IsSystemDevicePath (lpszVolume, hwndDlg, TRUE)) + { + case 1: + case 2: + if (AskErrNoYes ("BACKUP_HEADER_NOT_FOR_SYS_DEVICE", hwndDlg) == IDYES) + CreateRescueDisk (hwndDlg); + + return 0; + } + + if (IsMountedVolume (lpszVolume)) + { + Warning ("DISMOUNT_FIRST", hwndDlg); + goto ret; + } + + if (!VolumePathExists (lpszVolume)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto ret; + } + + Info ("EXTERNAL_VOL_HEADER_BAK_FIRST_INFO", hwndDlg); + + + WaitCursor(); + + // Open both types of volumes + for (int type = TC_VOLUME_TYPE_NORMAL; type <= TC_VOLUME_TYPE_HIDDEN; ++type) + { + OpenVolumeContext *askVol = (type == TC_VOLUME_TYPE_HIDDEN ? &hiddenVolume : &volume); + Password *askPassword = (type == TC_VOLUME_TYPE_HIDDEN ? &hiddenVolPassword : &VolumePassword); + int* askPkcs5 = (type == TC_VOLUME_TYPE_HIDDEN ? &hiddenVolPkcs5 : &VolumePkcs5); + int* askPim = (type == TC_VOLUME_TYPE_HIDDEN ? &hiddenVolPim : &VolumePim); + + while (TRUE) + { + int GuiPkcs5 = ((EffectiveVolumePkcs5 > 0) && (*askPkcs5 == 0))? EffectiveVolumePkcs5 : *askPkcs5; + int GuiPim = ((EffectiveVolumePim > 0) && (*askPim <= 0))? EffectiveVolumePim : *askPim; + if (!AskVolumePassword (hwndDlg, askPassword, &GuiPkcs5, &GuiPim, &VolumeTrueCryptMode, type == TC_VOLUME_TYPE_HIDDEN ? "ENTER_HIDDEN_VOL_PASSWORD" : "ENTER_NORMAL_VOL_PASSWORD", FALSE)) + { + nStatus = ERR_SUCCESS; + goto ret; + } + else + { + *askPkcs5 = GuiPkcs5; + *askPim = GuiPim; + burn (&GuiPkcs5, sizeof (GuiPkcs5)); + burn (&GuiPim, sizeof (GuiPim)); + } + + WaitCursor(); + + if (KeyFilesEnable && FirstKeyFile) + KeyFilesApply (hwndDlg, askPassword, FirstKeyFile, lpszVolume); + + nStatus = OpenVolume (askVol, lpszVolume, askPassword, *askPkcs5, *askPim, VolumeTrueCryptMode, FALSE, bPreserveTimestamp, FALSE); + + NormalCursor(); + + if (nStatus == ERR_SUCCESS) + { + if ((type == TC_VOLUME_TYPE_NORMAL && askVol->CryptoInfo->hiddenVolume) + || (type == TC_VOLUME_TYPE_HIDDEN && !askVol->CryptoInfo->hiddenVolume)) + { + CloseVolume (askVol); + handleError (hwndDlg, ERR_PASSWORD_WRONG, SRC_POS); + continue; + } + + RandSetHashFunction (askVol->CryptoInfo->pkcs5); + + if (type == TC_VOLUME_TYPE_NORMAL) + { + // Ask the user if there is a hidden volume + char *volTypeChoices[] = {0, "DOES_VOLUME_CONTAIN_HIDDEN", "VOLUME_CONTAINS_HIDDEN", "VOLUME_DOES_NOT_CONTAIN_HIDDEN", "IDCANCEL", 0}; + switch (AskMultiChoice ((void **) volTypeChoices, FALSE, hwndDlg)) + { + case 1: + break; + case 2: + goto noHidden; + + default: + nStatus = ERR_SUCCESS; + goto ret; + } + } + + break; + } + + if (nStatus != ERR_PASSWORD_WRONG) + goto error; + + handleError (hwndDlg, nStatus, SRC_POS); + } + } +noHidden: + + if (hiddenVolume.VolumeIsOpen && volume.CryptoInfo->LegacyVolume != hiddenVolume.CryptoInfo->LegacyVolume) + { + nStatus = ERR_PARAMETER_INCORRECT; + goto error; + } + + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CONFIRM_VOL_HEADER_BAK"), lpszVolume); + + if (bRequireConfirmation + && (MessageBoxW (hwndDlg, szTmp, lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON1) == IDNO)) + goto ret; + + /* Select backup file */ + if (!BrowseFiles (hwndDlg, "OPEN_TITLE", szFileName, bHistory, TRUE, NULL)) + goto ret; + + /* Conceive the backup file */ + if ((fBackup = _wopen(szFileName, _O_CREAT|_O_TRUNC|_O_WRONLY|_O_BINARY, _S_IREAD|_S_IWRITE)) == -1) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + // Backup headers + + byte backup[TC_VOLUME_HEADER_GROUP_SIZE]; + + bool legacyVolume = volume.CryptoInfo->LegacyVolume ? true : false; + int backupFileSize = legacyVolume ? TC_VOLUME_HEADER_SIZE_LEGACY * 2 : TC_VOLUME_HEADER_GROUP_SIZE; + + // Fill backup buffer with random data + memcpy (originalK2, volume.CryptoInfo->k2, sizeof (volume.CryptoInfo->k2)); + + if (Randinit() != ERR_SUCCESS) + { + if (CryptoAPILastError == ERROR_SUCCESS) + nStatus = ERR_RAND_INIT_FAILED; + else + nStatus = ERR_CAPI_INIT_FAILED; + goto error; + } + + /* force the display of the random enriching dialog */ + SetRandomPoolEnrichedByUserStatus (FALSE); + + NormalCursor(); + UserEnrichRandomPool (hwndDlg); + WaitCursor(); + + // Temporary keys + if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (volume.CryptoInfo->ea), TRUE) + || !RandgetBytes (hwndDlg, volume.CryptoInfo->k2, sizeof (volume.CryptoInfo->k2), FALSE)) + { + nStatus = ERR_PARAMETER_INCORRECT; + goto error; + } + + if (EAInit (volume.CryptoInfo->ea, temporaryKey, volume.CryptoInfo->ks) != ERR_SUCCESS || !EAInitMode (volume.CryptoInfo)) + { + nStatus = ERR_PARAMETER_INCORRECT; + goto error; + } + + EncryptBuffer (backup, backupFileSize, volume.CryptoInfo); + + memcpy (volume.CryptoInfo->k2, originalK2, sizeof (volume.CryptoInfo->k2)); + if (EAInit (volume.CryptoInfo->ea, volume.CryptoInfo->master_keydata, volume.CryptoInfo->ks) != ERR_SUCCESS || !EAInitMode (volume.CryptoInfo)) + { + nStatus = ERR_PARAMETER_INCORRECT; + goto error; + } + + // Store header encrypted with a new key + nStatus = ReEncryptVolumeHeader (hwndDlg, (char *) backup, FALSE, volume.CryptoInfo, &VolumePassword, VolumePim, FALSE); + if (nStatus != ERR_SUCCESS) + goto error; + + if (hiddenVolume.VolumeIsOpen) + { + nStatus = ReEncryptVolumeHeader (hwndDlg, (char *) backup + (legacyVolume ? TC_VOLUME_HEADER_SIZE_LEGACY : TC_VOLUME_HEADER_SIZE), + FALSE, hiddenVolume.CryptoInfo, &hiddenVolPassword, hiddenVolPim, FALSE); + + if (nStatus != ERR_SUCCESS) + goto error; + } + + if (_write (fBackup, backup, backupFileSize) == -1) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + /* Backup has been successfully created */ + Warning("VOL_HEADER_BACKED_UP", hwndDlg); + +ret: + nStatus = ERR_SUCCESS; + +error: + DWORD dwError = GetLastError (); + + CloseVolume (&volume); + CloseVolume (&hiddenVolume); + + if (fBackup != -1) + _close (fBackup); + + SetLastError (dwError); + if (nStatus != 0) + handleError (hwndDlg, nStatus, SRC_POS); + + burn (&VolumePassword, sizeof (VolumePassword)); + burn (&VolumePkcs5, sizeof (VolumePkcs5)); + burn (&VolumePim, sizeof (VolumePim)); + burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); + burn (&hiddenVolPassword, sizeof (hiddenVolPassword)); + burn (temporaryKey, sizeof (temporaryKey)); + burn (originalK2, sizeof (originalK2)); + + RestoreDefaultKeyFilesParam(); + RandStop (FALSE); + NormalCursor(); + + return nStatus; +} + + +int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume) +{ + int nDosLinkCreated = -1, nStatus = ERR_OS_ERROR; + wchar_t szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH]; + wchar_t szFileName[TC_MAX_PATH]; + wchar_t szDosDevice[TC_MAX_PATH]; + void *dev = INVALID_HANDLE_VALUE; + DWORD dwError; + BOOL bDevice; + unsigned __int64 hostSize = 0; + FILETIME ftCreationTime; + FILETIME ftLastWriteTime; + FILETIME ftLastAccessTime; + wchar_t szTmp[4096]; + BOOL bTimeStampValid = FALSE; + HANDLE fBackup = INVALID_HANDLE_VALUE; + LARGE_INTEGER headerOffset; + CRYPTO_INFO *restoredCryptoInfo = NULL; + int EffectiveVolumePkcs5 = CmdVolumePkcs5; + int EffectiveVolumePim = CmdVolumePim; + + /* Priority is given to command line parameters + * Default values used only when nothing specified in command line + */ + if (EffectiveVolumePkcs5 == 0) + EffectiveVolumePkcs5 = DefaultVolumePkcs5; + + if (!lpszVolume) + { + nStatus = ERR_OUTOFMEMORY; + handleError (hwndDlg, nStatus, SRC_POS); + return nStatus; + } + + switch (IsSystemDevicePath (lpszVolume, hwndDlg, TRUE)) + { + case 1: + case 2: + if (AskErrNoYes ("RESTORE_HEADER_NOT_FOR_SYS_DEVICE", hwndDlg) == IDYES) + CreateRescueDisk (hwndDlg); + + return 0; + + case -1: + // In some environments (such as PE), the system volume is not located on a hard drive. + // Therefore, we must interpret this return code as "Not a system device path" (otherwise, + // it would not be possible to restore headers on non-system devices in such environments). + // Note that this is rather safe, because bReliableRequired is set to TRUE. + + // NOP + break; + } + + if (IsMountedVolume (lpszVolume)) + { + Warning ("DISMOUNT_FIRST", hwndDlg); + return 0; + } + + if (!VolumePathExists (lpszVolume)) + { + handleWin32Error (hwndDlg, SRC_POS); + return 0; + } + + BOOL restoreInternalBackup; + + // Ask the user to select the type of backup (internal/external) + char *volTypeChoices[] = {0, "HEADER_RESTORE_EXTERNAL_INTERNAL", "HEADER_RESTORE_INTERNAL", "HEADER_RESTORE_EXTERNAL", "IDCANCEL", 0}; + switch (AskMultiChoice ((void **) volTypeChoices, FALSE, hwndDlg)) + { + case 1: + restoreInternalBackup = TRUE; + break; + case 2: + restoreInternalBackup = FALSE; + break; + default: + return 0; + } + + OpenVolumeContext volume; + volume.VolumeIsOpen = FALSE; + + /* force the display of the random enriching dialog */ + SetRandomPoolEnrichedByUserStatus (FALSE); + + WaitCursor(); + + if (restoreInternalBackup) + { + // Restore header from the internal backup + + // Open the volume using backup header + while (TRUE) + { + int GuiPkcs5 = ((EffectiveVolumePkcs5 > 0) && (VolumePkcs5 == 0))? EffectiveVolumePkcs5 : VolumePkcs5; + int GuiPim = ((EffectiveVolumePim > 0) && (VolumePim <= 0))? EffectiveVolumePim : VolumePim; + StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume), lpszVolume); + if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &VolumeTrueCryptMode, NULL, FALSE)) + { + nStatus = ERR_SUCCESS; + goto ret; + } + else + { + VolumePkcs5 = GuiPkcs5; + VolumePim = GuiPim; + burn (&GuiPkcs5, sizeof (GuiPkcs5)); + burn (&GuiPim, sizeof (GuiPim)); + } + + WaitCursor(); + + if (KeyFilesEnable && FirstKeyFile) + KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, lpszVolume); + + nStatus = OpenVolume (&volume, lpszVolume, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode,TRUE, bPreserveTimestamp, TRUE); + + NormalCursor(); + + if (nStatus == ERR_SUCCESS) + break; + + if (nStatus != ERR_PASSWORD_WRONG) + goto error; + + handleError (hwndDlg, nStatus, SRC_POS); + } + + if (volume.CryptoInfo->LegacyVolume) + { + Error ("VOLUME_HAS_NO_BACKUP_HEADER", hwndDlg); + nStatus = ERROR_SUCCESS; + goto error; + } + + // Create a new header with a new salt + char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; + + nStatus = ReEncryptVolumeHeader (hwndDlg, buffer, FALSE, volume.CryptoInfo, &VolumePassword, VolumePim, FALSE); + if (nStatus != 0) + goto error; + + headerOffset.QuadPart = volume.CryptoInfo->hiddenVolume ? TC_HIDDEN_VOLUME_HEADER_OFFSET : TC_VOLUME_HEADER_OFFSET; + if (!SetFilePointerEx (volume.HostFileHandle, headerOffset, NULL, FILE_BEGIN)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + if (!WriteEffectiveVolumeHeader (volume.IsDevice, volume.HostFileHandle, (byte *) buffer)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + } + else + { + // Restore header from an external backup + + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CONFIRM_VOL_HEADER_RESTORE"), lpszVolume); + + if (MessageBoxW (hwndDlg, szTmp, lpszTitle, YES_NO|MB_ICONWARNING|MB_DEFBUTTON2) == IDNO) + { + nStatus = ERR_SUCCESS; + goto ret; + } + + /* Select backup file */ + if (!BrowseFiles (hwndDlg, "OPEN_TITLE", szFileName, bHistory, FALSE, NULL)) + { + nStatus = ERR_SUCCESS; + goto ret; + } + + /* Open the backup file */ + fBackup = CreateFile (szFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); + if (fBackup == INVALID_HANDLE_VALUE) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + // Determine size of the backup file + LARGE_INTEGER backupSize; + if (!GetFileSizeEx (fBackup, &backupSize)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), lpszVolume, &bDevice); + + if (bDevice == FALSE) + StringCbCopyW (szCFDevice, sizeof(szCFDevice), szDiskFile); + else + { + nDosLinkCreated = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice),szCFDevice, sizeof(szCFDevice),FALSE); + if (nDosLinkCreated != 0) + goto error; + } + + // Open the volume + dev = CreateFile (szCFDevice, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); + + if (dev == INVALID_HANDLE_VALUE) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + // Determine volume host size + if (bDevice) + { + PARTITION_INFORMATION diskInfo; + DWORD dwResult; + BOOL bResult; + + bResult = GetPartitionInfo (lpszVolume, &diskInfo); + + if (bResult) + { + hostSize = diskInfo.PartitionLength.QuadPart; + } + else + { + DISK_GEOMETRY driveInfo; + + bResult = DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, + &driveInfo, sizeof (driveInfo), &dwResult, NULL); + + if (!bResult) + goto error; + + hostSize = driveInfo.Cylinders.QuadPart * driveInfo.BytesPerSector * + driveInfo.SectorsPerTrack * driveInfo.TracksPerCylinder; + } + + if (hostSize == 0) + { + nStatus = ERR_VOL_SIZE_WRONG; + goto error; + } + } + else + { + LARGE_INTEGER fileSize; + if (!GetFileSizeEx (dev, &fileSize)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + hostSize = fileSize.QuadPart; + } + + if (!bDevice && bPreserveTimestamp) + { + /* Remember the container modification/creation date and time. */ + + if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0) + bTimeStampValid = FALSE; + else + bTimeStampValid = TRUE; + } + + /* Read the volume header from the backup file */ + char buffer[TC_VOLUME_HEADER_GROUP_SIZE]; + + DWORD bytesRead; + if (!ReadFile (fBackup, buffer, sizeof (buffer), &bytesRead, NULL)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + if (bytesRead != backupSize.QuadPart) + { + nStatus = ERR_VOL_SIZE_WRONG; + goto error; + } + + LARGE_INTEGER headerOffset; + LARGE_INTEGER headerBackupOffset; + bool legacyBackup; + int headerOffsetBackupFile; + + // Determine the format of the backup file + switch (backupSize.QuadPart) + { + case TC_VOLUME_HEADER_GROUP_SIZE: + legacyBackup = false; + break; + + case TC_VOLUME_HEADER_SIZE_LEGACY * 2: + legacyBackup = true; + break; + + default: + Error ("HEADER_BACKUP_SIZE_INCORRECT", hwndDlg); + nStatus = ERR_SUCCESS; + goto error; + } + + // Open the header + while (TRUE) + { + int GuiPkcs5 = ((EffectiveVolumePkcs5 > 0) && (VolumePkcs5 == 0))? EffectiveVolumePkcs5 : VolumePkcs5; + int GuiPim = ((EffectiveVolumePim > 0) && (VolumePim <= 0))? EffectiveVolumePim : VolumePim; + if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &VolumeTrueCryptMode, "ENTER_HEADER_BACKUP_PASSWORD", FALSE)) + { + nStatus = ERR_SUCCESS; + goto ret; + } + else + { + VolumePkcs5 = GuiPkcs5; + VolumePim = GuiPim; + burn (&GuiPkcs5, sizeof (GuiPkcs5)); + burn (&GuiPim, sizeof (GuiPim)); + } + + if (KeyFilesEnable && FirstKeyFile) + KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, bDevice? NULL : lpszVolume); + + // Decrypt volume header + headerOffsetBackupFile = 0; + for (int type = TC_VOLUME_TYPE_NORMAL; type <= TC_VOLUME_TYPE_HIDDEN; ++type) + { + if (type == TC_VOLUME_TYPE_HIDDEN) + headerOffsetBackupFile += (legacyBackup ? TC_VOLUME_HEADER_SIZE_LEGACY : TC_VOLUME_HEADER_SIZE); + + nStatus = ReadVolumeHeader (FALSE, buffer + headerOffsetBackupFile, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode, &restoredCryptoInfo, NULL); + if (nStatus == ERR_SUCCESS) + break; + } + + if (nStatus == ERR_SUCCESS) + break; + + if (nStatus != ERR_PASSWORD_WRONG) + goto error; + + handleError (hwndDlg, nStatus, SRC_POS); + } + + BOOL hiddenVol = restoredCryptoInfo->hiddenVolume; + + if (legacyBackup) + { + headerOffset.QuadPart = hiddenVol ? hostSize - TC_HIDDEN_VOLUME_HEADER_OFFSET_LEGACY : TC_VOLUME_HEADER_OFFSET; + } + else + { + headerOffset.QuadPart = hiddenVol ? TC_HIDDEN_VOLUME_HEADER_OFFSET : TC_VOLUME_HEADER_OFFSET; + headerBackupOffset.QuadPart = hiddenVol ? hostSize - TC_VOLUME_HEADER_SIZE : hostSize - TC_VOLUME_HEADER_GROUP_SIZE; + } + + WaitCursor(); + + // Restore header encrypted with a new key + nStatus = ReEncryptVolumeHeader (hwndDlg, buffer, FALSE, restoredCryptoInfo, &VolumePassword, VolumePim, FALSE); + if (nStatus != ERR_SUCCESS) + goto error; + + if (!SetFilePointerEx (dev, headerOffset, NULL, FILE_BEGIN)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + if (!WriteEffectiveVolumeHeader (bDevice, dev, (byte *) buffer)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + if (!restoredCryptoInfo->LegacyVolume) + { + // Restore backup header encrypted with a new key + nStatus = ReEncryptVolumeHeader (hwndDlg, buffer, FALSE, restoredCryptoInfo, &VolumePassword, VolumePim, FALSE); + if (nStatus != ERR_SUCCESS) + goto error; + + if (!SetFilePointerEx (dev, headerBackupOffset, NULL, FILE_BEGIN)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + + if (!WriteEffectiveVolumeHeader (bDevice, dev, (byte *) buffer)) + { + nStatus = ERR_OS_ERROR; + goto error; + } + } + } + + + /* Volume header has been successfully restored */ + + Info("VOL_HEADER_RESTORED", hwndDlg); +ret: + nStatus = ERR_SUCCESS; + +error: + dwError = GetLastError (); + NormalCursor(); + + if (restoreInternalBackup) + { + CloseVolume (&volume); + } + else + { + if (restoredCryptoInfo) + crypto_close (restoredCryptoInfo); + + if (bTimeStampValid) + SetFileTime (dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime); + + if (dev != INVALID_HANDLE_VALUE) + CloseHandle (dev); + + if (fBackup != INVALID_HANDLE_VALUE) + CloseHandle (fBackup); + + if (nDosLinkCreated == 0) + RemoveFakeDosName (szDiskFile, szDosDevice); + } + + SetLastError (dwError); + if (nStatus != 0) + handleError (hwndDlg, nStatus, SRC_POS); + + burn (&VolumePassword, sizeof (VolumePassword)); + burn (&VolumePkcs5, sizeof (VolumePkcs5)); + burn (&VolumePim, sizeof (VolumePim)); + burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); + RestoreDefaultKeyFilesParam(); + RandStop (FALSE); + NormalCursor(); + + return nStatus; +} + + +void SetDriverConfigurationFlag (uint32 flag, BOOL state) +{ + BootEncObj->SetDriverConfigurationFlag (flag, state ? true : false); +} + + +static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + LocalizeDialog (hwndDlg, "IDD_PERFORMANCE_SETTINGS"); + + uint32 driverConfig = ReadDriverConfigurationFlags(); + CheckDlgButton (hwndDlg, IDC_ENABLE_HARDWARE_ENCRYPTION, (driverConfig & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? BST_UNCHECKED : BST_CHECKED); + CheckDlgButton (hwndDlg, IDC_ENABLE_EXTENDED_IOCTL_SUPPORT, (driverConfig & TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL) ? BST_CHECKED : BST_UNCHECKED); + + SYSTEM_INFO sysInfo; + GetSystemInfo (&sysInfo); + + HWND freeCpuCombo = GetDlgItem (hwndDlg, IDC_ENCRYPTION_FREE_CPU_COUNT); + uint32 encryptionFreeCpuCount = ReadEncryptionThreadPoolFreeCpuCountLimit(); + + if (encryptionFreeCpuCount > sysInfo.dwNumberOfProcessors - 1) + encryptionFreeCpuCount = sysInfo.dwNumberOfProcessors - 1; + + for (uint32 i = 1; i < sysInfo.dwNumberOfProcessors; ++i) + { + wstringstream s; + s << i; + AddComboPair (freeCpuCombo, s.str().c_str(), i); + } + + if (sysInfo.dwNumberOfProcessors < 2 || encryptionFreeCpuCount == 0) + EnableWindow (freeCpuCombo, FALSE); + + if (sysInfo.dwNumberOfProcessors < 2) + EnableWindow (GetDlgItem (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL), FALSE); + + if (encryptionFreeCpuCount != 0) + { + CheckDlgButton (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL, BST_CHECKED); + SendMessage (freeCpuCombo, CB_SETCURSEL, encryptionFreeCpuCount - 1, 0); + } + + SetWindowTextW (GetDlgItem (hwndDlg, IDT_LIMIT_ENC_THREAD_POOL_NOTE), GetString("LIMIT_ENC_THREAD_POOL_NOTE")); + + SetDlgItemTextW (hwndDlg, IDC_HW_AES_SUPPORTED_BY_CPU, (wstring (L" ") + (GetString (is_aes_hw_cpu_supported() ? "UISTR_YES" : "UISTR_NO"))).c_str()); + + ToHyperlink (hwndDlg, IDC_MORE_INFO_ON_HW_ACCELERATION); + ToHyperlink (hwndDlg, IDC_MORE_INFO_ON_THREAD_BASED_PARALLELIZATION); + } + return 0; + + case WM_COMMAND: + + switch (lw) + { + case IDCANCEL: + EndDialog (hwndDlg, lw); + return 1; + + case IDOK: + { + if (IsNonInstallMode()) + { + Error ("FEATURE_REQUIRES_INSTALLATION", hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + BOOL disableHW = !IsDlgButtonChecked (hwndDlg, IDC_ENABLE_HARDWARE_ENCRYPTION); + BOOL enableExtendedIOCTL = IsDlgButtonChecked (hwndDlg, IDC_ENABLE_EXTENDED_IOCTL_SUPPORT); + + try + { + VOLUME_PROPERTIES_STRUCT prop; + try + { + BootEncStatus = BootEncObj->GetStatus(); + BootEncObj->GetVolumeProperties (&prop); + } + catch (...) + { + BootEncStatus.DriveMounted = false; + } + + if (BootEncStatus.DriveMounted) + { + byte userConfig; + string customUserMessage; + uint16 bootLoaderVersion; + + BootEncObj->ReadBootSectorConfig (nullptr, 0, &userConfig, &customUserMessage, &bootLoaderVersion); + + if (bootLoaderVersion != VERSION_NUM) + Warning ("BOOT_LOADER_VERSION_INCORRECT_PREFERENCES", hwndDlg); + + if (disableHW) + userConfig |= TC_BOOT_USER_CFG_FLAG_DISABLE_HW_ENCRYPTION; + else + userConfig &= ~TC_BOOT_USER_CFG_FLAG_DISABLE_HW_ENCRYPTION; + + BootEncObj->WriteBootSectorUserConfig (userConfig, customUserMessage, prop.volumePim); + } + + SetDriverConfigurationFlag (TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION, disableHW); + SetDriverConfigurationFlag (TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL, enableExtendedIOCTL); + + DWORD bytesReturned; + if (!DeviceIoControl (hDriver, TC_IOCTL_REREAD_DRIVER_CONFIG, NULL, 0, NULL, 0, &bytesReturned, NULL)) + handleWin32Error (hwndDlg, SRC_POS); + + EnableHwEncryption (!disableHW); + + uint32 cpuFreeCount = 0; + if (IsDlgButtonChecked (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL)) + { + LRESULT cpuFreeItem = SendMessage (GetDlgItem (hwndDlg, IDC_ENCRYPTION_FREE_CPU_COUNT), CB_GETCURSEL, 0, 0); + if (cpuFreeItem != CB_ERR) + cpuFreeCount = (uint32) (cpuFreeItem + 1); + } + + if (ReadEncryptionThreadPoolFreeCpuCountLimit() != cpuFreeCount) + { + BootEncObj->WriteLocalMachineRegistryDwordValue (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME, cpuFreeCount); + Warning ("SETTING_REQUIRES_REBOOT", hwndDlg); + } + + EndDialog (hwndDlg, lw); + return 1; + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + } + return 1; + + case IDC_ENABLE_HARDWARE_ENCRYPTION: + if (!IsDlgButtonChecked (hwndDlg, IDC_ENABLE_HARDWARE_ENCRYPTION) + && AskWarnYesNo ("CONFIRM_SETTING_DEGRADES_PERFORMANCE", hwndDlg) == IDNO) + { + CheckDlgButton (hwndDlg, IDC_ENABLE_HARDWARE_ENCRYPTION, BST_CHECKED); + } + return 1; + + case IDC_LIMIT_ENC_THREAD_POOL: + if (IsDlgButtonChecked (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL) + && AskWarnYesNo ("CONFIRM_SETTING_DEGRADES_PERFORMANCE", hwndDlg) == IDNO) + { + CheckDlgButton (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL, BST_UNCHECKED); + } + else + { + SendMessage (GetDlgItem (hwndDlg, IDC_ENCRYPTION_FREE_CPU_COUNT), CB_SETCURSEL, 0, 0); + Warning ("SETTING_REQUIRES_REBOOT", hwndDlg); // Warn the user before he thinks about benchmarking + } + + EnableWindow (GetDlgItem (hwndDlg, IDC_ENCRYPTION_FREE_CPU_COUNT), IsDlgButtonChecked (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL)); + return 1; + + case IDC_BENCHMARK: + Benchmark (hwndDlg); + return 1; + + case IDC_MORE_INFO_ON_HW_ACCELERATION: + Applink ("hwacceleration", TRUE, ""); + return 1; + + case IDC_MORE_INFO_ON_THREAD_BASED_PARALLELIZATION: + Applink ("parallelization", TRUE, ""); + return 1; + } + + return 0; + } + + return 0; +} + + +static BOOL CALLBACK SecurityTokenPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + LocalizeDialog (hwndDlg, "IDD_TOKEN_PREFERENCES"); + SetDlgItemText (hwndDlg, IDC_PKCS11_MODULE, SecurityTokenLibraryPath); + CheckDlgButton (hwndDlg, IDC_CLOSE_TOKEN_SESSION_AFTER_MOUNT, CloseSecurityTokenSessionsAfterMount ? BST_CHECKED : BST_UNCHECKED); + + SetWindowTextW (GetDlgItem (hwndDlg, IDT_PKCS11_LIB_HELP), GetString("PKCS11_LIB_LOCATION_HELP")); + + return 0; + + case WM_COMMAND: + + switch (lw) + { + case IDCANCEL: + EndDialog (hwndDlg, lw); + return 1; + + case IDOK: + { + wchar_t securityTokenLibraryPath[MAX_PATH]; + GetDlgItemText (hwndDlg, IDC_PKCS11_MODULE, securityTokenLibraryPath, ARRAYSIZE (securityTokenLibraryPath)); + + if (securityTokenLibraryPath[0] == 0) + { + try + { + SecurityToken::CloseLibrary(); + } + catch (...) { } + + SecurityTokenLibraryPath[0] = 0; + } + else + { + wchar_t prevSecurityTokenLibraryPath[MAX_PATH]; + StringCbCopyW (prevSecurityTokenLibraryPath, sizeof(prevSecurityTokenLibraryPath), SecurityTokenLibraryPath); + StringCbCopyW (SecurityTokenLibraryPath, sizeof(SecurityTokenLibraryPath), securityTokenLibraryPath); + + if (!InitSecurityTokenLibrary(hwndDlg)) + { + StringCbCopyW (SecurityTokenLibraryPath, sizeof(SecurityTokenLibraryPath), prevSecurityTokenLibraryPath); + return 1; + } + } + + CloseSecurityTokenSessionsAfterMount = (IsDlgButtonChecked (hwndDlg, IDC_CLOSE_TOKEN_SESSION_AFTER_MOUNT) == BST_CHECKED); + + WaitCursor (); + SaveSettings (hwndDlg); + NormalCursor (); + + EndDialog (hwndDlg, lw); + return 1; + } + + case IDC_AUTO_DETECT_PKCS11_MODULE: + { + wchar_t systemDir[MAX_PATH]; + GetSystemDirectory (systemDir, ARRAYSIZE (systemDir)); + WIN32_FIND_DATA findData; + bool found = false; + + WaitCursor(); + + HANDLE find = FindFirstFile ((wstring (systemDir) + L"\\*.dll").c_str(), &findData); + while (!found && find != INVALID_HANDLE_VALUE) + { + wstring dllPathname = wstring (systemDir) + L"\\" + findData.cFileName; + DWORD fileSize; + + char *file = LoadFile (dllPathname.c_str(), &fileSize); + if (file) + { + const char *functionName = "C_GetFunctionList"; + size_t strLen = strlen (functionName); + + if (fileSize > strLen) + { + for (size_t i = 0; i < fileSize - strLen; ++i) + { + if (memcmp (file + i, functionName, strLen) == 0) + { + HMODULE module = LoadLibrary (dllPathname.c_str()); + if (module) + { + if (GetProcAddress (module, functionName)) + { + SetDlgItemText (hwndDlg, IDC_PKCS11_MODULE, dllPathname.c_str()); + found = true; + + FreeLibrary (module); + break; + } + + FreeLibrary (module); + } + } + } + } + + free (file); + } + + if (!FindNextFile (find, &findData)) + break; + } + + if (find != INVALID_HANDLE_VALUE) + FindClose (find); + + NormalCursor(); + + if (!found) + Warning ("PKCS11_MODULE_AUTO_DETECTION_FAILED", hwndDlg); + + return 1; + } + + case IDC_SELECT_PKCS11_MODULE: + { + wchar_t securityTokenLibraryPath[MAX_PATH]; + wchar_t systemDir[MAX_PATH]; + wchar_t browseFilter[1024]; + + Info ("SELECT_PKCS11_MODULE_HELP", hwndDlg); + + StringCbPrintfW (browseFilter, sizeof(browseFilter), L"%ls (*.dll)%c*.dll%c%c", GetString ("DLL_FILES"), 0, 0, 0); + GetSystemDirectory (systemDir, ARRAYSIZE (systemDir)); + + if (BrowseFilesInDir (hwndDlg, "SELECT_PKCS11_MODULE", systemDir, securityTokenLibraryPath, TRUE, FALSE, browseFilter)) + SetDlgItemText (hwndDlg, IDC_PKCS11_MODULE, securityTokenLibraryPath); + return 1; + } + } + return 0; + } + + return 0; +} + +static BOOL CALLBACK DefaultMountParametersDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + LocalizeDialog (hwndDlg, "IDD_DEFAULT_MOUNT_PARAMETERS"); + + SendMessage (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), BM_SETCHECK, + DefaultVolumeTrueCryptMode ? BST_CHECKED:BST_UNCHECKED, 0); + + /* Populate the PRF algorithms list */ + int i, nIndex, defaultPrfIndex = 0; + HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); + SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); + + nIndex = (int) SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION")); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0); + + for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++) + { + nIndex = (int) SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i)); + SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i); + if (DefaultVolumePkcs5 && (DefaultVolumePkcs5 == i)) + defaultPrfIndex = nIndex; + } + + /* make autodetection the default unless a specific PRF was specified in the command line */ + SendMessage (hComboBox, CB_SETCURSEL, defaultPrfIndex, 0); + + return 0; + } + + case WM_COMMAND: + + switch (lw) + { + case IDCANCEL: + EndDialog (hwndDlg, lw); + return 1; + + case IDOK: + { + int pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); + BOOL truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); + /* SHA-256 is not supported by TrueCrypt */ + if ( (truecryptMode) + && (pkcs5 == SHA256) + ) + { + Error ("ALGO_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); + } + else + { + WaitCursor (); + DefaultVolumeTrueCryptMode = truecryptMode; + DefaultVolumePkcs5 = pkcs5; + + SaveSettings (hwndDlg); + + NormalCursor (); + EndDialog (hwndDlg, lw); + } + return 1; + } + + } + return 0; + } + + return 0; +} + +void SecurityTokenPreferencesDialog (HWND hwndDlg) +{ + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TOKEN_PREFERENCES), hwndDlg, (DLGPROC) SecurityTokenPreferencesDlgProc, 0); +} + + +static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + { + if (!BootEncObj->GetStatus().DriveMounted) + { + Warning ("SYS_DRIVE_NOT_ENCRYPTED", hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + try + { + LocalizeDialog (hwndDlg, "IDD_SYSENC_SETTINGS"); + + uint32 driverConfig = ReadDriverConfigurationFlags(); + byte userConfig; + string customUserMessage; + uint16 bootLoaderVersion; + BOOL bPasswordCacheEnabled = (driverConfig & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD)? TRUE : FALSE; + BOOL bPimCacheEnabled = (driverConfig & TC_DRIVER_CONFIG_CACHE_BOOT_PIM)? TRUE : FALSE; + + BootEncObj->ReadBootSectorConfig (nullptr, 0, &userConfig, &customUserMessage, &bootLoaderVersion); + + if (bootLoaderVersion != VERSION_NUM) + Warning ("BOOT_LOADER_VERSION_INCORRECT_PREFERENCES", hwndDlg); + + SendMessage (GetDlgItem (hwndDlg, IDC_CUSTOM_BOOT_LOADER_MESSAGE), EM_LIMITTEXT, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH, 0); + SetDlgItemTextA (hwndDlg, IDC_CUSTOM_BOOT_LOADER_MESSAGE, customUserMessage.c_str()); + + CheckDlgButton (hwndDlg, IDC_DISABLE_BOOT_LOADER_PIM_PROMPT, (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM) ? BST_CHECKED : BST_UNCHECKED); + CheckDlgButton (hwndDlg, IDC_DISABLE_BOOT_LOADER_OUTPUT, (userConfig & TC_BOOT_USER_CFG_FLAG_SILENT_MODE) ? BST_CHECKED : BST_UNCHECKED); + CheckDlgButton (hwndDlg, IDC_ALLOW_ESC_PBA_BYPASS, (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_ESC) ? BST_UNCHECKED : BST_CHECKED); + CheckDlgButton (hwndDlg, IDC_BOOT_LOADER_CACHE_PASSWORD, bPasswordCacheEnabled ? BST_CHECKED : BST_UNCHECKED); + CheckDlgButton (hwndDlg, IDC_DISABLE_EVIL_MAID_ATTACK_DETECTION, (driverConfig & TC_DRIVER_CONFIG_DISABLE_EVIL_MAID_ATTACK_DETECTION) ? BST_CHECKED : BST_UNCHECKED); + EnableWindow (GetDlgItem (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM), bPasswordCacheEnabled); + CheckDlgButton (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM, (bPasswordCacheEnabled && bPimCacheEnabled)? BST_CHECKED : BST_UNCHECKED); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_CUSTOM_BOOT_LOADER_MESSAGE_HELP), GetString("CUSTOM_BOOT_LOADER_MESSAGE_HELP")); + } + catch (Exception &e) + { + e.Show (hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + } + return 0; + + case WM_COMMAND: + + switch (lw) + { + case IDCANCEL: + EndDialog (hwndDlg, lw); + return 1; + + case IDOK: + { + VOLUME_PROPERTIES_STRUCT prop; + + if (!BootEncObj->GetStatus().DriveMounted) + { + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + try + { + BootEncObj->GetVolumeProperties (&prop); + } + catch (Exception &e) + { + e.Show (hwndDlg); + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + char customUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH + 1]; + GetDlgItemTextA (hwndDlg, IDC_CUSTOM_BOOT_LOADER_MESSAGE, customUserMessage, sizeof (customUserMessage)); + + byte userConfig; + try + { + BootEncObj->ReadBootSectorConfig (nullptr, 0, &userConfig); + } + catch (Exception &e) + { + e.Show (hwndDlg); + return 1; + } + + if (IsDlgButtonChecked (hwndDlg, IDC_DISABLE_BOOT_LOADER_PIM_PROMPT)) + userConfig |= TC_BOOT_USER_CFG_FLAG_DISABLE_PIM; + else + userConfig &= ~TC_BOOT_USER_CFG_FLAG_DISABLE_PIM; + + if (IsDlgButtonChecked (hwndDlg, IDC_DISABLE_BOOT_LOADER_OUTPUT)) + userConfig |= TC_BOOT_USER_CFG_FLAG_SILENT_MODE; + else + userConfig &= ~TC_BOOT_USER_CFG_FLAG_SILENT_MODE; + + if (!IsDlgButtonChecked (hwndDlg, IDC_ALLOW_ESC_PBA_BYPASS)) + userConfig |= TC_BOOT_USER_CFG_FLAG_DISABLE_ESC; + else + userConfig &= ~TC_BOOT_USER_CFG_FLAG_DISABLE_ESC; + + try + { + BOOL bPasswordCacheEnabled = IsDlgButtonChecked (hwndDlg, IDC_BOOT_LOADER_CACHE_PASSWORD); + BOOL bPimCacheEnabled = IsDlgButtonChecked (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM); + BootEncObj->WriteBootSectorUserConfig (userConfig, customUserMessage, prop.volumePim); + SetDriverConfigurationFlag (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD, bPasswordCacheEnabled); + SetDriverConfigurationFlag (TC_DRIVER_CONFIG_CACHE_BOOT_PIM, (bPasswordCacheEnabled && bPimCacheEnabled)? TRUE : FALSE); + SetDriverConfigurationFlag (TC_DRIVER_CONFIG_DISABLE_EVIL_MAID_ATTACK_DETECTION, IsDlgButtonChecked (hwndDlg, IDC_DISABLE_EVIL_MAID_ATTACK_DETECTION)); + } + catch (Exception &e) + { + e.Show (hwndDlg); + return 1; + } + + EndDialog (hwndDlg, lw); + return 1; + } + + case IDC_DISABLE_BOOT_LOADER_PIM_PROMPT: + if ((IsDlgButtonChecked (hwndDlg, IDC_DISABLE_BOOT_LOADER_PIM_PROMPT)) + && AskWarnYesNo ("DISABLE_BOOT_LOADER_PIM_PROMPT", hwndDlg) == IDNO) + { + CheckDlgButton (hwndDlg, IDC_DISABLE_BOOT_LOADER_PIM_PROMPT, BST_UNCHECKED); + } + + case IDC_DISABLE_BOOT_LOADER_OUTPUT: + if ((IsDlgButtonChecked (hwndDlg, IDC_DISABLE_BOOT_LOADER_OUTPUT)) + && AskWarnYesNo ("CUSTOM_BOOT_LOADER_MESSAGE_PROMPT", hwndDlg) == IDNO) + { + CheckDlgButton (hwndDlg, IDC_DISABLE_BOOT_LOADER_OUTPUT, BST_UNCHECKED); + } + + break; + + case IDC_BOOT_LOADER_CACHE_PASSWORD: + if (IsDlgButtonChecked (hwndDlg, IDC_BOOT_LOADER_CACHE_PASSWORD)) + { + Warning ("BOOT_PASSWORD_CACHE_KEYBOARD_WARNING", hwndDlg); + EnableWindow (GetDlgItem (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM), TRUE); + } + else + { + EnableWindow (GetDlgItem (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM), FALSE); + } + + break; + } + return 0; + } + + return 0; +} + + +void MountSelectedVolume (HWND hwndDlg, BOOL mountWithOptions) +{ + if (!VolumeSelected(hwndDlg)) + { + Warning ("NO_VOLUME_SELECTED", hwndDlg); + } + else if (LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) == TC_MLIST_ITEM_FREE) + { + mountOptions = defaultMountOptions; + bPrebootPasswordDlgMode = FALSE; + + if (mountWithOptions || GetAsyncKeyState (VK_CONTROL) < 0) + { + /* Priority is given to command line parameters + * Default values used only when nothing specified in command line + */ + if (CmdVolumePkcs5 == 0) + mountOptions.ProtectedHidVolPkcs5Prf = DefaultVolumePkcs5; + else + mountOptions.ProtectedHidVolPkcs5Prf = CmdVolumePkcs5; + mountOptions.ProtectedHidVolPim = CmdVolumePim; + if (IDCANCEL == DialogBoxParamW (hInst, + MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, + (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions)) + return; + + if (mountOptions.ProtectHiddenVolume && hidVolProtKeyFilesParam.EnableKeyFiles) + { + wchar_t selectedVolume [TC_MAX_PATH + 1]; + GetVolumePath (hwndDlg, selectedVolume, ARRAYSIZE (selectedVolume)); + KeyFilesApply (hwndDlg, &mountOptions.ProtectedHidVolPassword, hidVolProtKeyFilesParam.FirstKeyFile, selectedVolume); + } + } + + if (CheckMountList (hwndDlg, FALSE)) + _beginthread (mountThreadFunction, 0, hwndDlg); + } + else + Warning ("SELECT_FREE_DRIVE", hwndDlg); +} + +static BOOL HandleDriveListMouseWheelEvent (UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL bListMustBePointed) +{ + static BOOL eventHandlerActive = FALSE; + if (eventHandlerActive) + return 0; + + RECT listRect; + int mouseX = GET_X_LPARAM (lParam); + int mouseY = GET_Y_LPARAM (lParam); + + GetWindowRect (GetDlgItem (MainDlg, IDC_DRIVELIST), &listRect); + + // Determine if the mouse pointer is within the main drive list + bool bListPointed = (mouseX >= listRect.left && mouseX <= listRect.right + && mouseY >= listRect.top && mouseY <= listRect.bottom); + + if (bListMustBePointed && bListPointed + || !bListMustBePointed) + { + eventHandlerActive = TRUE; + + if (!bListMustBePointed && bListPointed) + SetFocus (GetDlgItem (MainDlg, IDC_DRIVELIST)); + + SendMessage (GetDlgItem (MainDlg, IDC_DRIVELIST), uMsg, wParam, lParam); + + eventHandlerActive = FALSE; + return 0; // Do not process this event any further e.g. to prevent two lists from being scrolled at once + } + + return 1; +} + + +static LRESULT CALLBACK MouseWheelProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + WNDPROC wp = (WNDPROC) GetWindowLongPtrW (hwnd, GWLP_USERDATA); + + switch (message) + { + case WM_MOUSEWHEEL: + + if (HandleDriveListMouseWheelEvent (message, wParam, lParam, TRUE) == 0) + return 0; // Do not process this event any further e.g. to prevent two lists from being scrolled at once + } + + return CallWindowProcW (wp, hwnd, message, wParam, lParam); +} + + +void HookMouseWheel (HWND hwndDlg, UINT ctrlId) +{ + HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId); + + SetWindowLongPtrW (hwndCtrl, GWLP_USERDATA, (LONG_PTR) GetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC)); + SetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC, (LONG_PTR) MouseWheelProc); +} diff --git a/src/Mount/Mount.h b/src/Mount/Mount.h index 3bf0f78c..8e6a8e15 100644 --- a/src/Mount/Mount.h +++ b/src/Mount/Mount.h @@ -1,133 +1,133 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifdef __cplusplus - -#include "Favorites.h" - -extern "C" { -#endif - -enum mount_list_item_types -{ - TC_MLIST_ITEM_FREE = 0, - TC_MLIST_ITEM_NONSYS_VOL, - TC_MLIST_ITEM_SYS_PARTITION, - TC_MLIST_ITEM_SYS_DRIVE -}; - -#define TC_MAIN_WINDOW_FLAG_ADMIN_PRIVILEGES 0x1 - -#define TRAYICON_MENU_DRIVE_OFFSET 9000 -#define TC_FAVORITE_MENU_CMD_ID_OFFSET 10000 -#define TC_FAVORITE_MENU_CMD_ID_OFFSET_END (TC_FAVORITE_MENU_CMD_ID_OFFSET + 1000) - -#define WM_COPY_SET_VOLUME_NAME "VNAM" - -#define ENC_SYSDRIVE_PSEUDO_DRIVE_LETTER ('A' - 1) - -/* Password Change dialog modes */ -enum -{ - PCDM_CHANGE_PASSWORD = 0, - PCDM_CHANGE_PKCS5_PRF, - PCDM_ADD_REMOVE_VOL_KEYFILES, - PCDM_REMOVE_ALL_KEYFILES_FROM_VOL -}; - -typedef struct -{ - BOOL bHidVolDamagePrevReported[26]; -} VOLUME_NOTIFICATIONS_LIST; - -typedef struct -{ - Password *password; - int* pkcs5; - int* pim; - BOOL* truecryptMode; -} PasswordDlgParam; - -extern VOLUME_NOTIFICATIONS_LIST VolumeNotificationsList; - -extern BOOL bEnableBkgTask; -extern BOOL bCloseBkgTaskWhenNoVolumes; -extern BOOL bPlaySoundOnSuccessfulHkDismount; -extern BOOL bDisplayBalloonOnSuccessfulHkDismount; -extern BOOL bExplore; -extern BOOL bTryEmptyPasswordWhenKeyfileUsed; - -static void localcleanup ( void ); -void EndMainDlg ( HWND hwndDlg ); -void EnableDisableButtons ( HWND hwndDlg ); -BOOL VolumeSelected (HWND hwndDlg ); -void LoadSettings ( HWND hwndDlg ); -void SaveSettings ( HWND hwndDlg ); -BOOL SelectItem ( HWND hTree , wchar_t nLetter ); -void LoadDriveLetters ( HWND hwndDlg, HWND hTree, int drive ); -BOOL CALLBACK PasswordChangeDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); -BOOL CALLBACK PasswordDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); -BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -void BuildTree ( HWND hwndDlg, HWND hTree ); -LPARAM GetSelectedLong ( HWND hTree ); -LPARAM GetItemLong ( HWND hTree, int itemNo ); -BOOL CALLBACK CommandHelpDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); -BOOL CALLBACK MainDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); -void ExtractCommandLine ( HWND hwndDlg , wchar_t *lpszCommandLine ); -static void WipeCache (HWND hwndDlg, BOOL silent); -void OpenVolumeExplorerWindow (int driveNo); -BOOL TaskBarIconAdd (HWND hwnd); -BOOL TaskBarIconRemove (HWND hwnd); -BOOL TaskBarIconChange (HWND hwnd, int iconId); -void DismountIdleVolumes (); -static void SaveDefaultKeyFilesParam (HWND hwnd); -static BOOL Dismount (HWND hwndDlg, int nDosDriveNo); -static BOOL DismountAll (HWND hwndDlg, BOOL forceUnmount, BOOL interact, int dismountMaxRetries, int dismountAutoRetryDelay); -static void KeyfileDefaultsDlg (HWND hwndDlg); -static void HandleHotKey (HWND hwndDlg, WPARAM wParam); -static BOOL CheckMountList (HWND hwndDlg, BOOL bForceTaskBarUpdate); -int GetCipherBlockSizeByDriveNo (int nDosDriveNo); -int GetModeOfOperationByDriveNo (int nDosDriveNo); -void ChangeMainWindowVisibility (); -void LaunchVolCreationWizard (HWND hwndDlg); -BOOL WholeSysDriveEncryption (BOOL bSilent); -BOOL CheckSysEncMountWithoutPBA (HWND hwndDlg, const wchar_t *devicePath, BOOL quiet); -BOOL TCBootLoaderOnInactiveSysEncDrive (wchar_t *szDevicePath); -void CreateRescueDisk (HWND hwndDlg); -int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, const wchar_t *lpszVolume); -int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume); -void SecurityTokenPreferencesDialog (HWND hwndDlg); -static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); -void MountSelectedVolume (HWND hwndDlg, BOOL mountWithOptions); -uint32 ReadDriverConfigurationFlags (); -void HookMouseWheel (HWND hwndDlg, UINT ctrlId); -static BOOL HandleDriveListMouseWheelEvent (UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL bListMustBePointed); -static BOOL CALLBACK DefaultMountParametersDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); - -#ifdef __cplusplus -} - -typedef struct -{ - BOOL systemFavorites; - BOOL logOnMount; - BOOL hotKeyMount; - VeraCrypt::FavoriteVolume* favoriteVolumeToMount; -} mountFavoriteVolumeThreadParam; - -void SetDriverConfigurationFlag (uint32 flag, BOOL state); -BOOL MountFavoriteVolumes (HWND hwnd, BOOL systemFavorites = FALSE, BOOL logOnMount = FALSE, BOOL hotKeyMount = FALSE, const VeraCrypt::FavoriteVolume &favoriteVolumeToMount = VeraCrypt::FavoriteVolume()); -void __cdecl mountFavoriteVolumeThreadFunction (void *pArg); - -#endif +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifdef __cplusplus + +#include "Favorites.h" + +extern "C" { +#endif + +enum mount_list_item_types +{ + TC_MLIST_ITEM_FREE = 0, + TC_MLIST_ITEM_NONSYS_VOL, + TC_MLIST_ITEM_SYS_PARTITION, + TC_MLIST_ITEM_SYS_DRIVE +}; + +#define TC_MAIN_WINDOW_FLAG_ADMIN_PRIVILEGES 0x1 + +#define TRAYICON_MENU_DRIVE_OFFSET 9000 +#define TC_FAVORITE_MENU_CMD_ID_OFFSET 10000 +#define TC_FAVORITE_MENU_CMD_ID_OFFSET_END (TC_FAVORITE_MENU_CMD_ID_OFFSET + 1000) + +#define WM_COPY_SET_VOLUME_NAME "VNAM" + +#define ENC_SYSDRIVE_PSEUDO_DRIVE_LETTER ('A' - 1) + +/* Password Change dialog modes */ +enum +{ + PCDM_CHANGE_PASSWORD = 0, + PCDM_CHANGE_PKCS5_PRF, + PCDM_ADD_REMOVE_VOL_KEYFILES, + PCDM_REMOVE_ALL_KEYFILES_FROM_VOL +}; + +typedef struct +{ + BOOL bHidVolDamagePrevReported[26]; +} VOLUME_NOTIFICATIONS_LIST; + +typedef struct +{ + Password *password; + int* pkcs5; + int* pim; + BOOL* truecryptMode; +} PasswordDlgParam; + +extern VOLUME_NOTIFICATIONS_LIST VolumeNotificationsList; + +extern BOOL bEnableBkgTask; +extern BOOL bCloseBkgTaskWhenNoVolumes; +extern BOOL bPlaySoundOnSuccessfulHkDismount; +extern BOOL bDisplayBalloonOnSuccessfulHkDismount; +extern BOOL bExplore; +extern BOOL bTryEmptyPasswordWhenKeyfileUsed; + +static void localcleanup ( void ); +void EndMainDlg ( HWND hwndDlg ); +void EnableDisableButtons ( HWND hwndDlg ); +BOOL VolumeSelected (HWND hwndDlg ); +void LoadSettings ( HWND hwndDlg ); +void SaveSettings ( HWND hwndDlg ); +BOOL SelectItem ( HWND hTree , wchar_t nLetter ); +void LoadDriveLetters ( HWND hwndDlg, HWND hTree, int drive ); +BOOL CALLBACK PasswordChangeDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); +BOOL CALLBACK PasswordDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); +BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +void BuildTree ( HWND hwndDlg, HWND hTree ); +LPARAM GetSelectedLong ( HWND hTree ); +LPARAM GetItemLong ( HWND hTree, int itemNo ); +BOOL CALLBACK CommandHelpDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); +BOOL CALLBACK MainDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); +void ExtractCommandLine ( HWND hwndDlg , wchar_t *lpszCommandLine ); +static void WipeCache (HWND hwndDlg, BOOL silent); +void OpenVolumeExplorerWindow (int driveNo); +BOOL TaskBarIconAdd (HWND hwnd); +BOOL TaskBarIconRemove (HWND hwnd); +BOOL TaskBarIconChange (HWND hwnd, int iconId); +void DismountIdleVolumes (); +static void SaveDefaultKeyFilesParam (HWND hwnd); +static BOOL Dismount (HWND hwndDlg, int nDosDriveNo); +static BOOL DismountAll (HWND hwndDlg, BOOL forceUnmount, BOOL interact, int dismountMaxRetries, int dismountAutoRetryDelay); +static void KeyfileDefaultsDlg (HWND hwndDlg); +static void HandleHotKey (HWND hwndDlg, WPARAM wParam); +static BOOL CheckMountList (HWND hwndDlg, BOOL bForceTaskBarUpdate); +int GetCipherBlockSizeByDriveNo (int nDosDriveNo); +int GetModeOfOperationByDriveNo (int nDosDriveNo); +void ChangeMainWindowVisibility (); +void LaunchVolCreationWizard (HWND hwndDlg); +BOOL WholeSysDriveEncryption (BOOL bSilent); +BOOL CheckSysEncMountWithoutPBA (HWND hwndDlg, const wchar_t *devicePath, BOOL quiet); +BOOL TCBootLoaderOnInactiveSysEncDrive (wchar_t *szDevicePath); +void CreateRescueDisk (HWND hwndDlg); +int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, const wchar_t *lpszVolume); +int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume); +void SecurityTokenPreferencesDialog (HWND hwndDlg); +static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); +void MountSelectedVolume (HWND hwndDlg, BOOL mountWithOptions); +uint32 ReadDriverConfigurationFlags (); +void HookMouseWheel (HWND hwndDlg, UINT ctrlId); +static BOOL HandleDriveListMouseWheelEvent (UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL bListMustBePointed); +static BOOL CALLBACK DefaultMountParametersDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); + +#ifdef __cplusplus +} + +typedef struct +{ + BOOL systemFavorites; + BOOL logOnMount; + BOOL hotKeyMount; + VeraCrypt::FavoriteVolume* favoriteVolumeToMount; +} mountFavoriteVolumeThreadParam; + +void SetDriverConfigurationFlag (uint32 flag, BOOL state); +BOOL MountFavoriteVolumes (HWND hwnd, BOOL systemFavorites = FALSE, BOOL logOnMount = FALSE, BOOL hotKeyMount = FALSE, const VeraCrypt::FavoriteVolume &favoriteVolumeToMount = VeraCrypt::FavoriteVolume()); +void __cdecl mountFavoriteVolumeThreadFunction (void *pArg); + +#endif diff --git a/src/Mount/Mount.manifest b/src/Mount/Mount.manifest index 255a867e..5d4cb896 100644 --- a/src/Mount/Mount.manifest +++ b/src/Mount/Mount.manifest @@ -1,33 +1,33 @@ - - - - - - - - - - - - true - - - - - - - - - - - - - + + + + + + + + + + + + true + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Mount/Mount.rc b/src/Mount/Mount.rc index 4aad9360..1c45b89c 100644 --- a/src/Mount/Mount.rc +++ b/src/Mount/Mount.rc @@ -1,713 +1,713 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" -#include "..\\common\\resource.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// HEADER -// - -IDR_MOUNT_RSRC_HEADER HEADER "resource.h" - -///////////////////////////////////////////////////////////////////////////// -// -// TYPELIB -// - -IDR_MOUNT_TLB TYPELIB "Mount.tlb" - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_PREFERENCES_DLG DIALOGEX 0, 0, 336, 333 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - Preferences" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "Mount volumes as read-only",IDC_PREF_MOUNT_READONLY, - "Button",BS_AUTOCHECKBOX | BS_MULTILINE | WS_TABSTOP,11,11,150,16 - CONTROL "Mount volumes as removable media",IDC_PREF_MOUNT_REMOVABLE, - "Button",BS_AUTOCHECKBOX | BS_MULTILINE | WS_TABSTOP,162,11,165,16 - CONTROL "Enabled",IDC_PREF_BKG_TASK_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,44,111,10 - CONTROL "Exit when there are no mounted volumes",IDC_CLOSE_BKG_TASK_WHEN_NOVOL, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,140,44,188,10 - CONTROL "Start VeraCrypt Background Task",IDC_PREF_LOGON_START, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,75,126,10 - CONTROL "Mount all device-hosted VeraCrypt volumes",IDC_PREF_LOGON_MOUNT_DEVICES, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,140,75,188,10 - CONTROL "User logs off",IDC_PREF_DISMOUNT_LOGOFF,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,81,104,114,11 - CONTROL "User session locked",IDC_PREF_DISMOUNT_SESSION_LOCKED, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,197,105,130,11 - CONTROL "Screen saver is launched",IDC_PREF_DISMOUNT_SCREENSAVER, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,81,116,114,10 - CONTROL "Entering power saving mode",IDC_PREF_DISMOUNT_POWERSAVING, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,197,115,130,11 - CONTROL "Auto-dismount volume after no data has been read/written to it for",IDC_PREF_DISMOUNT_INACTIVE, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,128,246,11 - EDITTEXT IDC_PREF_DISMOUNT_INACTIVE_TIME,258,127,27,12,ES_AUTOHSCROLL | ES_NUMBER,WS_EX_RIGHT - CONTROL "Force auto-dismount even if volume contains open files or directories",IDC_PREF_FORCE_AUTO_DISMOUNT, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,141,294,10 - CONTROL "Open Explorer window for successfully mounted volume",IDC_PREF_OPEN_EXPLORER, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,171,316,11 - CONTROL "Use a different taskbar icon when there are mounted volumes",IDC_PREF_USE_DIFF_TRAY_ICON_IF_VOL_MOUNTED, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,184,314,10 - CONTROL "Preserve modification timestamp of file containers",IDC_PRESERVE_TIMESTAMPS, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,196,316,10 - CONTROL "Make disconnected network drives available for mounting",IDC_SHOW_DISCONNECTED_NETWORK_DRIVES, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,208,316,10 - CONTROL "Cache passwords in driver memory",IDC_PREF_CACHE_PASSWORDS, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,254,146,11 - CONTROL "Wipe cached passwords on exit",IDC_PREF_WIPE_CACHE_ON_EXIT, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,162,254,165,11 - CONTROL "Temporary Cache password during ""Mount Favorite Volumes"" operations",IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,268,294,11 - CONTROL "Wipe cached passwords on auto-dismount",IDC_PREF_WIPE_CACHE_ON_AUTODISMOUNT, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,282,296,11 - CONTROL "Include PIM when caching a password",IDC_PREF_CACHE_PIM, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,296,296,10 - PUSHBUTTON "More Settings...",IDC_MORE_SETTINGS,5,317,85,14 - DEFPUSHBUTTON "OK",IDOK,225,317,50,14 - PUSHBUTTON "Cancel",IDCANCEL,281,317,50,14 - GROUPBOX "Windows",IDT_WINDOWS_RELATED_SETTING,4,160,328,76 - GROUPBOX "Default Mount Options",IDT_DEFAULT_MOUNT_OPTIONS,4,3,328,26 - GROUPBOX "VeraCrypt Background Task",IDT_TASKBAR_ICON,4,33,328,26 - GROUPBOX "Auto-Dismount",IDT_AUTO_DISMOUNT,4,94,328,62 - LTEXT "minutes",IDT_MINUTES,289,129,39,10 - LTEXT "Dismount all when:",IDT_AUTO_DISMOUNT_ON,9,104,71,20 - GROUPBOX "Password Cache",IDT_PW_CACHE_OPTIONS,4,243,328,68 - GROUPBOX "Actions to perform upon logon to Windows",IDT_LOGON,4,63,328,28 - CONTROL "Don't show wait message dialog when performing operations",IDC_HIDE_WAITING_DIALOG, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,220,316,10 -END - -IDD_VOLUME_PROPERTIES DIALOGEX 60, 30, 284, 224 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt Volume Properties" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - DEFPUSHBUTTON "OK",IDOK,114,203,55,14 - CONTROL "",IDC_VOLUME_PROPERTIES_LIST,"SysListView32",LVS_REPORT | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,6,269,192 -END - -IDD_PASSWORDCHANGE_DLG DIALOGEX 0, 0, 346, 245 -STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Change Password or Keyfiles" -CLASS "VeraCryptCustomDlg" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - EDITTEXT IDC_OLD_PASSWORD,89,14,181,13,ES_PASSWORD | ES_AUTOHSCROLL - COMBOBOX IDC_PKCS5_OLD_PRF_ID,89,33,97,90,CBS_DROPDOWNLIST | WS_TABSTOP - CONTROL "TrueCrypt Mode",IDC_TRUECRYPT_MODE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,193,35,83,10 - EDITTEXT IDC_OLD_PIM,89,51,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER | NOT WS_VISIBLE - CONTROL "Use P&IM",IDC_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,89,59,115,10 - CONTROL "Use keyfiles",IDC_ENABLE_KEYFILES,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,89,72,109,10 - PUSHBUTTON "Keyfiles...",IDC_KEYFILES,203,70,67,14 - CONTROL "Display password",IDC_SHOW_PASSWORD_CHPWD_ORI,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,89,85,138,10,WS_EX_TRANSPARENT - EDITTEXT IDC_PASSWORD,89,121,181,13,ES_PASSWORD | ES_AUTOHSCROLL - EDITTEXT IDC_VERIFY,89,137,181,13,ES_PASSWORD | ES_AUTOHSCROLL - EDITTEXT IDC_PIM,89,154,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER | NOT WS_VISIBLE - CONTROL "Use PIM",IDC_NEW_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,89,161,97,10 - CONTROL "Use keyfiles",IDC_ENABLE_NEW_KEYFILES,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,89,172,110,11 - PUSHBUTTON "Keyfiles...",IDC_NEW_KEYFILES,202,170,68,14 - CONTROL "Display password",IDC_SHOW_PASSWORD_CHPWD_NEW,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,89,184,180,11,WS_EX_TRANSPARENT - COMBOBOX IDC_PKCS5_PRF_ID,89,199,181,90,CBS_DROPDOWNLIST | WS_TABSTOP - COMBOBOX IDC_WIPE_MODE,89,218,181,90,CBS_DROPDOWNLIST | WS_TABSTOP - DEFPUSHBUTTON "OK",IDOK,280,7,59,14 - PUSHBUTTON "Cancel",IDCANCEL,280,24,59,14 - RTEXT "Password:",IDT_PASSWORD,12,16,72,8 - RTEXT "Password:",IDT_NEW_PASSWORD,8,124,76,8 - RTEXT "Confirm Password:",IDT_CONFIRM_PASSWORD,9,140,75,16 - RTEXT "PKCS-5 PRF:",IDT_NEW_PKCS5_PRF,9,200,74,10,SS_CENTERIMAGE - GROUPBOX "Current",IDT_CURRENT,6,3,270,97 - GROUPBOX "New",IDT_NEW,6,108,270,130 - RTEXT "Wipe mode:",IDT_WIPE_MODE,9,220,74,8,0,WS_EX_RIGHT - RTEXT "PKCS-5 PRF:",IDT_PKCS5_PRF,12,34,74,10,SS_CENTERIMAGE - RTEXT "Volume PIM:",IDT_OLD_PIM,12,54,74,10,NOT WS_VISIBLE - LTEXT "(Empty or 0 for default iterations)",IDC_OLD_PIM_HELP,135,54,196,8,NOT WS_VISIBLE - RTEXT "Volume PIM:",IDT_PIM,9,157,75,16,NOT WS_VISIBLE - LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,135,157,197,8,NOT WS_VISIBLE -END - -IDD_MOUNT_DLG DIALOGEX 0, 0, 375, 271 -STYLE DS_SETFONT | DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt" -MENU IDR_MENU -CLASS "VeraCryptCustomDlg" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - CONTROL "",IDC_DRIVELIST,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,8,5,360,135 - PUSHBUTTON "&Create Volume",IDC_CREATE_VOLUME,16,159,84,14 - PUSHBUTTON "&Volume Properties...",IDC_VOLUME_PROPERTIES,146,159,84,14 - PUSHBUTTON "&Wipe Cache",IDC_WIPE_CACHE,276,159,84,14 - COMBOBOX IDC_VOLUME,56,192,212,74,CBS_DROPDOWN | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP - CONTROL "&Never save history",IDC_NO_HISTORY,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,56,213,122,10 - PUSHBUTTON "Volume &Tools...",IDC_VOLUME_TOOLS,184,211,84,14 - PUSHBUTTON "Select &File...",IDC_SELECT_FILE,276,192,84,14 - PUSHBUTTON "Select D&evice...",IDC_SELECT_DEVICE,276,211,84,14 - DEFPUSHBUTTON "OK",IDOK,8,243,84,18,WS_GROUP - PUSHBUTTON "&Auto-Mount Devices",IDC_MOUNTALL,100,243,84,18 - PUSHBUTTON "Di&smount All",IDC_UNMOUNTALL,192,243,84,18,WS_GROUP - PUSHBUTTON "E&xit",IDC_EXIT,284,243,84,18,WS_GROUP - CONTROL 112,IDC_LOGO,"Static",SS_BITMAP | SS_NOTIFY | WS_BORDER,13,190,33,31 - GROUPBOX "Volume",IDT_VOLUME,8,179,360,53 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,2,0,372,147 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,282,242,88,20 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,190,242,88,20 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,6,242,88,20 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,98,242,88,20 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,2,151,372,119 -END - -IDD_PASSWORD_DLG DIALOGEX 0, 0, 330, 103 -STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_VISIBLE | WS_CAPTION -CAPTION "Enter VeraCrypt Volume Password" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - EDITTEXT IDC_PASSWORD,69,8,179,14,ES_PASSWORD | ES_AUTOHSCROLL - COMBOBOX IDC_PKCS5_PRF_ID,69,26,96,90,CBS_DROPDOWNLIST | WS_TABSTOP - CONTROL "TrueCrypt Mode",IDC_TRUECRYPT_MODE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,170,28,76,10 - EDITTEXT IDC_PIM,69,43,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER | NOT WS_VISIBLE - CONTROL "Use P&IM",IDC_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,48,97,10 - CONTROL "Cache passwords and keyfil&es in memory",IDC_CACHE, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,61,153,10 - CONTROL "&Display password",IDC_SHOW_PASSWORD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,74,83,10 - CONTROL "U&se keyfiles",IDC_KEYFILES_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,87,99,11 - PUSHBUTTON "&Keyfiles...",IDC_KEY_FILES,173,84,75,14 - PUSHBUTTON "Mount Opti&ons...",IDC_MOUNT_OPTIONS,252,84,69,14 - LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,115,46,199,8,NOT WS_VISIBLE - DEFPUSHBUTTON "OK",IDOK,252,8,69,14 - PUSHBUTTON "Cancel",IDCANCEL,252,25,69,14 - RTEXT "Password:",IDT_PASSWORD,0,10,65,13 - RTEXT "PKCS-5 PRF:",IDT_PKCS5_PRF,0,27,65,11 - RTEXT "Volume PIM:",IDT_PIM,0,46,65,8,NOT WS_VISIBLE -END - -IDD_TRAVELER_DLG DIALOGEX 0, 0, 300, 299 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt Traveler Disk Setup" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - EDITTEXT IDC_DIRECTORY,17,29,205,13,ES_AUTOHSCROLL | ES_READONLY - PUSHBUTTON "Browse...",IDC_BROWSE_DIRS,228,28,57,14 - CONTROL "Include VeraCrypt Volume Creation Wizard",IDC_COPY_WIZARD, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,19,48,258,10 - CONTROL "Do nothing",IDC_AUTORUN_DISABLE,"Button",BS_AUTORADIOBUTTON,15,115,262,10 - CONTROL "&Start VeraCrypt",IDC_AUTORUN_START,"Button",BS_AUTORADIOBUTTON,15,126,262,11 - CONTROL "&Auto-mount VeraCrypt volume (specified below)",IDC_AUTORUN_MOUNT, - "Button",BS_AUTORADIOBUTTON,15,138,262,11 - EDITTEXT IDC_VOLUME_NAME,21,175,194,13,ES_AUTOHSCROLL | WS_DISABLED - PUSHBUTTON "Browse...",IDC_BROWSE_FILES,221,174,57,14,WS_DISABLED - COMBOBOX IDC_DRIVELIST,120,193,96,69,CBS_DROPDOWNLIST | WS_DISABLED | WS_VSCROLL | WS_TABSTOP - CONTROL "Open &Explorer window for mounted volume",IDC_TRAVEL_OPEN_EXPLORER, - "Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,22,211,256,10 - CONTROL "Mount volume as read-&only",IDC_MOUNT_READONLY,"Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,22,224,256,10 - CONTROL "&Cache password in driver memory",IDC_TRAV_CACHE_PASSWORDS, - "Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,22,237,256,10 - DEFPUSHBUTTON "Create",IDC_CREATE,173,278,57,14 - PUSHBUTTON "Close",IDCLOSE,236,278,57,14 - GROUPBOX "File Settings",IDT_FILE_SETTINGS,6,7,287,71 - GROUPBOX "AutoRun Configuration (autorun.inf)",IDT_AUTORUN,5,88,288,185 - LTEXT "VeraCrypt volume to mount (relative to traveler disk root):",IDT_TRAVELER_MOUNT,21,165,248,8,WS_DISABLED - RTEXT "Mount volume as drive letter:",IDT_MOUNT_LETTER,18,195,99,8,WS_DISABLED - LTEXT "Create traveler disk files at (traveler disk root directory):",IDT_TRAVEL_ROOT,18,19,259,8 - GROUPBOX "Mount Settings",IDT_MOUNT_SETTINGS,13,152,272,114,WS_DISABLED - LTEXT "Upon insertion of traveler disk: ",IDT_TRAVEL_INSERTION,13,102,263,8 - CONTROL "Include VeraCrypt Volume Expander",IDC_COPY_EXPANDER, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,19,62,258,10 - CONTROL "Include PIM when caching a password",IDC_PREF_CACHE_PIM, - "Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,22,250,256,10 -END - -IDD_HOTKEYS_DLG DIALOGEX 0, 0, 389, 257 -STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - System-Wide Hot Keys" -CLASS "VeraCryptCustomDlg" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - CONTROL "",IDC_HOTKEY_LIST,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,7,375,115 - EDITTEXT IDC_HOTKEY_KEY,108,140,190,13,ES_AUTOHSCROLL - PUSHBUTTON "Assign",IDC_HOTKEY_ASSIGN,304,140,59,14 - CONTROL "Ctrl",IDC_HK_MOD_CTRL,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,109,158,46,10,WS_EX_TRANSPARENT - CONTROL "Shift",IDC_HK_MOD_SHIFT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,162,158,49,10,WS_EX_TRANSPARENT - CONTROL "Alt",IDC_HK_MOD_ALT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,216,158,43,10,WS_EX_TRANSPARENT - CONTROL "Win",IDC_HK_MOD_WIN,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,266,158,34,10,WS_EX_TRANSPARENT - PUSHBUTTON "Remove",IDC_HOTKEY_REMOVE,304,158,59,14 - CONTROL "Play system notification sound after successful hot-key dismount",IDC_HK_DISMOUNT_PLAY_SOUND, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,201,348,10 - CONTROL "Display balloon tooltip after successful hot-key dismount",IDC_HK_DISMOUNT_BALLOON_TOOLTIP, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,213,351,10,WS_EX_TRANSPARENT - DEFPUSHBUTTON "OK",IDOK,260,236,59,14 - PUSHBUTTON "Cancel",IDCANCEL,323,236,59,14 - PUSHBUTTON "Reset",IDC_RESET_HOTKEYS,7,236,59,14 - RTEXT "Key to assign:",IDT_HOTKEY_KEY,15,142,86,8 - GROUPBOX "Hot Key Options",IDT_DISMOUNT_ACTION,7,188,375,42 - GROUPBOX "Shortcut",IDT_ASSIGN_HOTKEY,7,127,375,53 -END - -IDD_TOKEN_PREFERENCES DIALOGEX 0, 0, 316, 199 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - Security Token Preferences" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - EDITTEXT IDC_PKCS11_MODULE,16,23,204,13,ES_AUTOHSCROLL - PUSHBUTTON "Select &Library...",IDC_SELECT_PKCS11_MODULE,226,22,75,14 - PUSHBUTTON "Auto-&Detect Library",IDC_AUTO_DETECT_PKCS11_MODULE,16,41,112,14 - CONTROL "&Close token session (log out) after a volume is successfully mounted",IDC_CLOSE_TOKEN_SESSION_AFTER_MOUNT, - "Button",BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,16,154,284,9 - DEFPUSHBUTTON "OK",IDOK,205,178,50,14 - PUSHBUTTON "Cancel",IDCANCEL,259,178,50,14 - GROUPBOX "PKCS #11 Library Path",IDT_PKCS11_LIB_PATH,7,7,302,129 - GROUPBOX "Security Options",IDT_SECURITY_OPTIONS,7,140,302,30 - LTEXT "",IDT_PKCS11_LIB_HELP,16,63,286,65 -END - -IDD_SYSENC_SETTINGS DIALOGEX 0, 0, 370, 286 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - System Encryption Settings" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "Do not &show any texts in the pre-boot authentication screen (except the below custom message)",IDC_DISABLE_BOOT_LOADER_OUTPUT, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,37,339,9 - EDITTEXT IDC_CUSTOM_BOOT_LOADER_MESSAGE,18,67,216,14,ES_AUTOHSCROLL - CONTROL "&Cache pre-boot authentication password in driver memory (for mounting of non-system volumes)",IDC_BOOT_LOADER_CACHE_PASSWORD, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,192,339,10 - CONTROL "Allow pre-boot &authentication to be bypassed by pressing the Esc key (enables boot manager)",IDC_ALLOW_ESC_PBA_BYPASS, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,222,340,10 - DEFPUSHBUTTON "OK",IDOK,257,262,50,14 - PUSHBUTTON "Cancel",IDCANCEL,313,262,50,14 - LTEXT "Display this custom message in the pre-boot authentication screen (24 characters maximum):",IDT_CUSTOM_BOOT_LOADER_MESSAGE,18,56,337,8 - GROUPBOX "Boot Loader Screen Options",IDT_BOOT_LOADER_SCREEN_OPTIONS,8,7,355,165 - GROUPBOX "Security Options",IDT_SECURITY_OPTIONS,8,177,355,75 - LTEXT "",IDC_CUSTOM_BOOT_LOADER_MESSAGE_HELP,18,89,337,73 - CONTROL "Disable ""Evil Maid"" attack detection",IDC_DISABLE_EVIL_MAID_ATTACK_DETECTION, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,237,340,10 - CONTROL "Include PIM when caching pre-boot authentication password",IDC_BOOT_LOADER_CACHE_PIM, - "Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,18,207,340,10 - CONTROL "Do not request PIM in the pre-boot authentication screen (PIM value is stored unencrypted on disk)",IDC_DISABLE_BOOT_LOADER_PIM_PROMPT, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,20,339,9 -END - -IDD_PERFORMANCE_SETTINGS DIALOGEX 0, 0, 370, 248 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - Performance Options" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "",IDC_HW_AES_SUPPORTED_BY_CPU,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,294,21,57,12,WS_EX_CLIENTEDGE - CONTROL "Accelerate AES encryption/decryption by using the AES instructions of the processor (if available)",IDC_ENABLE_HARDWARE_ENCRYPTION, - "Button",BS_AUTOCHECKBOX | BS_MULTILINE | WS_TABSTOP,18,41,340,17 - LTEXT "More information",IDC_MORE_INFO_ON_HW_ACCELERATION,18,61,165,10,SS_NOTIFY - CONTROL "Do not use the following number of processors for encryption/decryption:",IDC_LIMIT_ENC_THREAD_POOL, - "Button",BS_AUTOCHECKBOX | BS_TOP | WS_TABSTOP,18,103,283,11 - COMBOBOX IDC_ENCRYPTION_FREE_CPU_COUNT,304,101,48,51,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP - LTEXT "More information",IDC_MORE_INFO_ON_THREAD_BASED_PARALLELIZATION,18,159,165,10,SS_NOTIFY - PUSHBUTTON "&Benchmark",IDC_BENCHMARK,7,227,59,14 - DEFPUSHBUTTON "OK",IDOK,257,227,50,14 - PUSHBUTTON "Cancel",IDCANCEL,313,227,50,14 - LTEXT "Processor (CPU) in this computer supports hardware acceleration for AES:",IDT_HW_AES_SUPPORTED_BY_CPU,18,23,273,9 - GROUPBOX "Hardware Acceleration",IDT_ACCELERATION_OPTIONS,7,6,355,74 - GROUPBOX "Thread-Based Parallelization",IDT_PARALLELIZATION_OPTIONS,7,84,355,93 - LTEXT "",IDT_LIMIT_ENC_THREAD_POOL_NOTE,18,126,334,33 - GROUPBOX "Driver Configuration",IDT_DRIVER_OPTIONS,7,183,356,36 - CONTROL "Enable extended disk control codes support",IDC_ENABLE_EXTENDED_IOCTL_SUPPORT, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,198,337,10 -END - -IDD_FAVORITE_VOLUMES DIALOGEX 0, 0, 380, 368 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - Favorite Volumes" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "",IDC_FAVORITE_VOLUMES_LIST,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,7,366,92 - PUSHBUTTON "Move &Up",IDC_FAVORITE_MOVE_UP,7,104,63,14 - PUSHBUTTON "Move &Down",IDC_FAVORITE_MOVE_DOWN,74,104,63,14 - PUSHBUTTON "&Remove",IDC_FAVORITE_REMOVE,310,104,63,14 - EDITTEXT IDC_FAVORITE_LABEL,18,225,344,13,ES_AUTOHSCROLL - CONTROL "Mount selected volume as read-o&nly",IDC_FAVORITE_MOUNT_READONLY, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,255,349,10 - CONTROL "Mount selected volume as remo&vable medium",IDC_FAVORITE_MOUNT_REMOVABLE, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,269,349,10 - CONTROL "Mount selected volume upon log&on",IDC_FAVORITE_MOUNT_ON_LOGON, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,283,349,10 - CONTROL "Mount selected volume when its host device gets &connected",IDC_FAVORITE_MOUNT_ON_ARRIVAL, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,297,349,10 - CONTROL "Open &Explorer window for selected volume when successfully mounted",IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,311,349,11 - CONTROL "Do not mount selected volume when 'Mount Favorite Volumes' &hot key is pressed",IDC_FAVORITE_DISABLE_HOTKEY, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,326,349,11 - LTEXT "Help on favorite volumes",IDC_FAVORITES_HELP_LINK,17,351,237,10,SS_NOTIFY - DEFPUSHBUTTON "OK",IDOK,269,347,50,14 - PUSHBUTTON "Cancel",IDCANCEL,323,347,50,14 - GROUPBOX "",IDC_FAV_VOL_OPTIONS_GROUP_BOX,7,123,366,219 - LTEXT "Label of selected favorite volume:",IDT_FAVORITE_LABEL,18,215,202,8 - GROUPBOX "Global Settings",IDC_FAV_VOL_OPTIONS_GLOBAL_SETTINGS_BOX,7,300,366,42 - EDITTEXT IDC_PIM,18,183,42,13,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER - LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,64,185,189,8 - LTEXT "Volume PIM:",IDT_PIM,18,173,65,8 - CONTROL "Display PIM",IDC_SHOW_PIM,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,199,150,10 - CONTROL "Use favorite label as Explorer drive label",IDC_FAVORITE_USE_LABEL_IN_EXPLORER, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,242,349,10 - LTEXT "Volume ID:",IDT_VOLUME_ID,18,131,57,8 - EDITTEXT IDC_FAVORITE_VOLUME_ID,18,141,344,14,ES_AUTOHSCROLL | ES_READONLY - CONTROL "Use Volume ID to mount favorite",IDC_FAVORITE_USE_VOLUME_ID, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,159,337,10 -END - -IDD_DEFAULT_MOUNT_PARAMETERS DIALOGEX 0, 0, 167, 65 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt - Mount Parameters" -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - DEFPUSHBUTTON "OK",IDOK,57,44,50,14 - PUSHBUTTON "Cancel",IDCANCEL,111,44,50,14 - COMBOBOX IDC_PKCS5_PRF_ID,57,24,103,90,CBS_DROPDOWNLIST | WS_TABSTOP - LTEXT "PKCS-5 PRF:",IDT_PKCS5_PRF,8,26,44,11 - CONTROL "TrueCrypt Mode",IDC_TRUECRYPT_MODE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,7,76,10 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_PREFERENCES_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 329 - TOPMARGIN, 7 - BOTTOMMARGIN, 331 - END - - IDD_VOLUME_PROPERTIES, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 277 - TOPMARGIN, 7 - BOTTOMMARGIN, 217 - END - - IDD_PASSWORDCHANGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 339 - TOPMARGIN, 7 - BOTTOMMARGIN, 238 - END - - IDD_MOUNT_DLG, DIALOG - BEGIN - RIGHTMARGIN, 369 - BOTTOMMARGIN, 269 - END - - IDD_PASSWORD_DLG, DIALOG - BEGIN - RIGHTMARGIN, 321 - BOTTOMMARGIN, 98 - END - - IDD_TRAVELER_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 293 - TOPMARGIN, 7 - BOTTOMMARGIN, 292 - END - - IDD_HOTKEYS_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 382 - TOPMARGIN, 7 - BOTTOMMARGIN, 250 - END - - IDD_TOKEN_PREFERENCES, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 309 - TOPMARGIN, 7 - BOTTOMMARGIN, 192 - END - - IDD_SYSENC_SETTINGS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 363 - TOPMARGIN, 7 - BOTTOMMARGIN, 276 - END - - IDD_PERFORMANCE_SETTINGS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 363 - TOPMARGIN, 7 - BOTTOMMARGIN, 241 - END - - IDD_FAVORITE_VOLUMES, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 373 - TOPMARGIN, 7 - BOTTOMMARGIN, 361 - END - - IDD_DEFAULT_MOUNT_PARAMETERS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 160 - TOPMARGIN, 7 - BOTTOMMARGIN, 58 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,17,22,0 - PRODUCTVERSION 1,17,22,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "IDRIX" - VALUE "FileDescription", "VeraCrypt" - VALUE "FileVersion", "1.17" - VALUE "LegalTrademarks", "VeraCrypt" - VALUE "OriginalFilename", "VeraCrypt.exe" - VALUE "ProductName", "VeraCrypt" - VALUE "ProductVersion", "1.17" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "#include ""..\\\\common\\\\resource.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "#include ""..\\\\common\\\\common.rc""\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_DRIVEICON BITMAP "Drive_icon_96dpi.bmp" -IDB_DRIVEICON_MASK BITMAP "Drive_icon_mask_96dpi.bmp" -IDB_LOGO_96DPI BITMAP "Logo_96dpi.bmp" -IDB_LOGO_288DPI BITMAP "Logo_288dpi.bmp" -IDB_SYS_DRIVEICON BITMAP "System_drive_icon_96dpi.bmp" -IDB_SYS_DRIVEICON_MASK BITMAP "System_drive_icon_mask_96dpi.bmp" - -///////////////////////////////////////////////////////////////////////////// -// -// Menu -// - -IDR_MENU MENU -BEGIN - POPUP "&Volumes" - BEGIN - MENUITEM "Select File...", IDM_SELECT_FILE - MENUITEM "Select Device...", IDM_SELECT_DEVICE - MENUITEM SEPARATOR - MENUITEM "Create New Volume...", IDM_CREATE_VOLUME - MENUITEM "Permanently Decrypt...", IDM_DECRYPT_NONSYS_VOL - MENUITEM "Resume Interrupted Process", IDM_RESUME_INTERRUPTED_PROC - MENUITEM SEPARATOR - MENUITEM "Mount Volume", IDM_MOUNT_VOLUME - MENUITEM "Mount Volume with Options", IDM_MOUNT_VOLUME_OPTIONS - MENUITEM "Auto-Mount All Device-Hosted Volumes", IDM_MOUNTALL - MENUITEM SEPARATOR - MENUITEM "Dismount Volume", IDM_UNMOUNT_VOLUME - MENUITEM "Dismount All Mounted Volumes", IDM_UNMOUNTALL - MENUITEM SEPARATOR - MENUITEM "Change Volume Password...", IDM_CHANGE_PASSWORD - MENUITEM "Add/Remove Keyfiles to/from Volume...", IDM_ADD_REMOVE_VOL_KEYFILES - MENUITEM "Remove All Keyfiles from Volume...", IDM_REMOVE_ALL_KEYFILES_FROM_VOL - MENUITEM "Set Header Key Derivation Algorithm...", IDM_CHANGE_HEADER_KEY_DERIV_ALGO - MENUITEM SEPARATOR - MENUITEM "Volume Properties", IDM_VOLUME_PROPERTIES - END - POPUP "S&ystem" - BEGIN - MENUITEM "Encrypt System Partition/Drive...", IDM_ENCRYPT_SYSTEM_DEVICE - MENUITEM "Permanently Decrypt System Partition/Drive", IDM_PERMANENTLY_DECRYPT_SYS - MENUITEM "Resume Interrupted Process", IDM_SYSENC_RESUME - MENUITEM SEPARATOR - MENUITEM "Create Hidden Operating System...", IDM_CREATE_HIDDEN_OS - MENUITEM SEPARATOR - MENUITEM "Create Rescue Disk...", IDM_CREATE_RESCUE_DISK - MENUITEM "Verify Rescue Disk", IDM_VERIFY_RESCUE_DISK - MENUITEM "Verify Rescue Disk ISO Image", IDM_VERIFY_RESCUE_DISK_ISO - MENUITEM SEPARATOR - MENUITEM "Mount Without Pre-Boot &Authentication...", IDM_MOUNT_SYSENC_PART_WITHOUT_PBA - MENUITEM SEPARATOR - MENUITEM "Change Password...", IDM_CHANGE_SYS_PASSWORD - MENUITEM "Set Header Key Derivation Algorithm...", IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO - MENUITEM SEPARATOR - MENUITEM "Properties...", IDM_SYSTEM_ENCRYPTION_STATUS - MENUITEM SEPARATOR - MENUITEM "Settings...", IDM_SYS_ENC_SETTINGS - END - POPUP "Favor&ites" - BEGIN - MENUITEM "Add Mounted Volume to Favorites...", IDM_ADD_VOLUME_TO_FAVORITES - MENUITEM "Add Mounted Volume to System Favorites...", IDM_ADD_VOLUME_TO_SYSTEM_FAVORITES - MENUITEM SEPARATOR - MENUITEM "Organize Favorite Volumes...", IDM_ORGANIZE_FAVORITES - MENUITEM "Organize System Favorite Volumes...", IDM_ORGANIZE_SYSTEM_FAVORITES - MENUITEM SEPARATOR - MENUITEM "Mount Favorite Volumes", IDM_MOUNT_FAVORITE_VOLUMES - END - POPUP "T&ools" - BEGIN - MENUITEM "Benchmark...", IDM_BENCHMARK - MENUITEM "Test Vectors...", IDM_TEST_VECTORS - MENUITEM SEPARATOR - MENUITEM "Traveler Disk Setup...", IDM_TRAVELER - MENUITEM "Volume Expander", IDM_VOLUME_EXPANDER - MENUITEM "Volume Creation Wizard", IDM_VOLUME_WIZARD - MENUITEM SEPARATOR - MENUITEM "Keyfile Generator", IDM_KEYFILE_GENERATOR - MENUITEM "Manage Security Token Keyfiles...", IDM_MANAGE_TOKEN_KEYFILES - MENUITEM "Close All Security Token Sessions", IDM_CLOSE_ALL_TOKEN_SESSIONS - MENUITEM SEPARATOR - MENUITEM "Backup Volume Header...", IDM_BACKUP_VOL_HEADER - MENUITEM "Restore Volume Header...", IDM_RESTORE_VOL_HEADER - MENUITEM SEPARATOR - MENUITEM "Refresh Drive Letters", IDM_REFRESH_DRIVE_LETTERS - MENUITEM SEPARATOR - MENUITEM "Clear Volume History", IDM_CLEAR_HISTORY - MENUITEM "Wipe Cached Passwords", IDM_WIPE_CACHE - END - POPUP "Settin&gs" - BEGIN - MENUITEM "Language...", IDM_LANGUAGE - MENUITEM "Hot Keys...", IDM_HOTKEY_SETTINGS - MENUITEM SEPARATOR - MENUITEM "System Encryption...", IDM_SYSENC_SETTINGS - MENUITEM "System Favorite Volumes...", IDM_SYS_FAVORITES_SETTINGS - MENUITEM SEPARATOR - MENUITEM "Performance/Driver Configuration", IDM_PERFORMANCE_SETTINGS - MENUITEM SEPARATOR - MENUITEM "Default Keyfiles...", IDM_DEFAULT_KEYFILES - MENUITEM "Default Mount Parameters...", IDM_DEFAULT_MOUNT_PARAMETERS - MENUITEM "Security Tokens...", IDM_TOKEN_PREFERENCES - MENUITEM SEPARATOR - MENUITEM "Preferences...", IDM_PREFERENCES - END - POPUP "Hel&p" - BEGIN - MENUITEM "User's Guide", IDM_HELP - MENUITEM "Online Help", IDM_ONLINE_HELP - MENUITEM "Beginner's Tutorial", IDM_ONLINE_TUTORIAL - MENUITEM "Frequently Asked Questions", IDM_FAQ - MENUITEM SEPARATOR - MENUITEM "VeraCrypt Website", IDM_WEBSITE - MENUITEM "Downloads", IDM_TC_DOWNLOADS - MENUITEM "News", IDM_NEWS - MENUITEM "Version History", IDM_VERSION_HISTORY - MENUITEM SEPARATOR - MENUITEM "Donate now...", IDM_DONATE - MENUITEM "Contact", IDM_CONTACT - MENUITEM "Legal Notices", IDM_LICENSE - MENUITEM "About", IDM_ABOUT - END - MENUITEM "&Homepage ", IDM_HOMEPAGE -END - - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE -BEGIN - IDS_UACSTRING "VeraCrypt" -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// -#include "..\\common\\common.rc" - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" +#include "..\\common\\resource.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// HEADER +// + +IDR_MOUNT_RSRC_HEADER HEADER "resource.h" + +///////////////////////////////////////////////////////////////////////////// +// +// TYPELIB +// + +IDR_MOUNT_TLB TYPELIB "Mount.tlb" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_PREFERENCES_DLG DIALOGEX 0, 0, 336, 333 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - Preferences" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "Mount volumes as read-only",IDC_PREF_MOUNT_READONLY, + "Button",BS_AUTOCHECKBOX | BS_MULTILINE | WS_TABSTOP,11,11,150,16 + CONTROL "Mount volumes as removable media",IDC_PREF_MOUNT_REMOVABLE, + "Button",BS_AUTOCHECKBOX | BS_MULTILINE | WS_TABSTOP,162,11,165,16 + CONTROL "Enabled",IDC_PREF_BKG_TASK_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,44,111,10 + CONTROL "Exit when there are no mounted volumes",IDC_CLOSE_BKG_TASK_WHEN_NOVOL, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,140,44,188,10 + CONTROL "Start VeraCrypt Background Task",IDC_PREF_LOGON_START, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,75,126,10 + CONTROL "Mount all device-hosted VeraCrypt volumes",IDC_PREF_LOGON_MOUNT_DEVICES, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,140,75,188,10 + CONTROL "User logs off",IDC_PREF_DISMOUNT_LOGOFF,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,81,104,114,11 + CONTROL "User session locked",IDC_PREF_DISMOUNT_SESSION_LOCKED, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,197,105,130,11 + CONTROL "Screen saver is launched",IDC_PREF_DISMOUNT_SCREENSAVER, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,81,116,114,10 + CONTROL "Entering power saving mode",IDC_PREF_DISMOUNT_POWERSAVING, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,197,115,130,11 + CONTROL "Auto-dismount volume after no data has been read/written to it for",IDC_PREF_DISMOUNT_INACTIVE, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,128,246,11 + EDITTEXT IDC_PREF_DISMOUNT_INACTIVE_TIME,258,127,27,12,ES_AUTOHSCROLL | ES_NUMBER,WS_EX_RIGHT + CONTROL "Force auto-dismount even if volume contains open files or directories",IDC_PREF_FORCE_AUTO_DISMOUNT, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,141,294,10 + CONTROL "Open Explorer window for successfully mounted volume",IDC_PREF_OPEN_EXPLORER, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,171,316,11 + CONTROL "Use a different taskbar icon when there are mounted volumes",IDC_PREF_USE_DIFF_TRAY_ICON_IF_VOL_MOUNTED, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,184,314,10 + CONTROL "Preserve modification timestamp of file containers",IDC_PRESERVE_TIMESTAMPS, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,196,316,10 + CONTROL "Make disconnected network drives available for mounting",IDC_SHOW_DISCONNECTED_NETWORK_DRIVES, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,208,316,10 + CONTROL "Cache passwords in driver memory",IDC_PREF_CACHE_PASSWORDS, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,254,146,11 + CONTROL "Wipe cached passwords on exit",IDC_PREF_WIPE_CACHE_ON_EXIT, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,162,254,165,11 + CONTROL "Temporary Cache password during ""Mount Favorite Volumes"" operations",IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,268,294,11 + CONTROL "Wipe cached passwords on auto-dismount",IDC_PREF_WIPE_CACHE_ON_AUTODISMOUNT, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,282,296,11 + CONTROL "Include PIM when caching a password",IDC_PREF_CACHE_PIM, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,296,296,10 + PUSHBUTTON "More Settings...",IDC_MORE_SETTINGS,5,317,85,14 + DEFPUSHBUTTON "OK",IDOK,225,317,50,14 + PUSHBUTTON "Cancel",IDCANCEL,281,317,50,14 + GROUPBOX "Windows",IDT_WINDOWS_RELATED_SETTING,4,160,328,76 + GROUPBOX "Default Mount Options",IDT_DEFAULT_MOUNT_OPTIONS,4,3,328,26 + GROUPBOX "VeraCrypt Background Task",IDT_TASKBAR_ICON,4,33,328,26 + GROUPBOX "Auto-Dismount",IDT_AUTO_DISMOUNT,4,94,328,62 + LTEXT "minutes",IDT_MINUTES,289,129,39,10 + LTEXT "Dismount all when:",IDT_AUTO_DISMOUNT_ON,9,104,71,20 + GROUPBOX "Password Cache",IDT_PW_CACHE_OPTIONS,4,243,328,68 + GROUPBOX "Actions to perform upon logon to Windows",IDT_LOGON,4,63,328,28 + CONTROL "Don't show wait message dialog when performing operations",IDC_HIDE_WAITING_DIALOG, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,220,316,10 +END + +IDD_VOLUME_PROPERTIES DIALOGEX 60, 30, 284, 224 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt Volume Properties" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + DEFPUSHBUTTON "OK",IDOK,114,203,55,14 + CONTROL "",IDC_VOLUME_PROPERTIES_LIST,"SysListView32",LVS_REPORT | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,6,269,192 +END + +IDD_PASSWORDCHANGE_DLG DIALOGEX 0, 0, 346, 245 +STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Change Password or Keyfiles" +CLASS "VeraCryptCustomDlg" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + EDITTEXT IDC_OLD_PASSWORD,89,14,181,13,ES_PASSWORD | ES_AUTOHSCROLL + COMBOBOX IDC_PKCS5_OLD_PRF_ID,89,33,97,90,CBS_DROPDOWNLIST | WS_TABSTOP + CONTROL "TrueCrypt Mode",IDC_TRUECRYPT_MODE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,193,35,83,10 + EDITTEXT IDC_OLD_PIM,89,51,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER | NOT WS_VISIBLE + CONTROL "Use P&IM",IDC_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,89,59,115,10 + CONTROL "Use keyfiles",IDC_ENABLE_KEYFILES,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,89,72,109,10 + PUSHBUTTON "Keyfiles...",IDC_KEYFILES,203,70,67,14 + CONTROL "Display password",IDC_SHOW_PASSWORD_CHPWD_ORI,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,89,85,138,10,WS_EX_TRANSPARENT + EDITTEXT IDC_PASSWORD,89,121,181,13,ES_PASSWORD | ES_AUTOHSCROLL + EDITTEXT IDC_VERIFY,89,137,181,13,ES_PASSWORD | ES_AUTOHSCROLL + EDITTEXT IDC_PIM,89,154,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER | NOT WS_VISIBLE + CONTROL "Use PIM",IDC_NEW_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,89,161,97,10 + CONTROL "Use keyfiles",IDC_ENABLE_NEW_KEYFILES,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,89,172,110,11 + PUSHBUTTON "Keyfiles...",IDC_NEW_KEYFILES,202,170,68,14 + CONTROL "Display password",IDC_SHOW_PASSWORD_CHPWD_NEW,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,89,184,180,11,WS_EX_TRANSPARENT + COMBOBOX IDC_PKCS5_PRF_ID,89,199,181,90,CBS_DROPDOWNLIST | WS_TABSTOP + COMBOBOX IDC_WIPE_MODE,89,218,181,90,CBS_DROPDOWNLIST | WS_TABSTOP + DEFPUSHBUTTON "OK",IDOK,280,7,59,14 + PUSHBUTTON "Cancel",IDCANCEL,280,24,59,14 + RTEXT "Password:",IDT_PASSWORD,12,16,72,8 + RTEXT "Password:",IDT_NEW_PASSWORD,8,124,76,8 + RTEXT "Confirm Password:",IDT_CONFIRM_PASSWORD,9,140,75,16 + RTEXT "PKCS-5 PRF:",IDT_NEW_PKCS5_PRF,9,200,74,10,SS_CENTERIMAGE + GROUPBOX "Current",IDT_CURRENT,6,3,270,97 + GROUPBOX "New",IDT_NEW,6,108,270,130 + RTEXT "Wipe mode:",IDT_WIPE_MODE,9,220,74,8,0,WS_EX_RIGHT + RTEXT "PKCS-5 PRF:",IDT_PKCS5_PRF,12,34,74,10,SS_CENTERIMAGE + RTEXT "Volume PIM:",IDT_OLD_PIM,12,54,74,10,NOT WS_VISIBLE + LTEXT "(Empty or 0 for default iterations)",IDC_OLD_PIM_HELP,135,54,196,8,NOT WS_VISIBLE + RTEXT "Volume PIM:",IDT_PIM,9,157,75,16,NOT WS_VISIBLE + LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,135,157,197,8,NOT WS_VISIBLE +END + +IDD_MOUNT_DLG DIALOGEX 0, 0, 375, 271 +STYLE DS_SETFONT | DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt" +MENU IDR_MENU +CLASS "VeraCryptCustomDlg" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + CONTROL "",IDC_DRIVELIST,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,8,5,360,135 + PUSHBUTTON "&Create Volume",IDC_CREATE_VOLUME,16,159,84,14 + PUSHBUTTON "&Volume Properties...",IDC_VOLUME_PROPERTIES,146,159,84,14 + PUSHBUTTON "&Wipe Cache",IDC_WIPE_CACHE,276,159,84,14 + COMBOBOX IDC_VOLUME,56,192,212,74,CBS_DROPDOWN | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP + CONTROL "&Never save history",IDC_NO_HISTORY,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,56,213,122,10 + PUSHBUTTON "Volume &Tools...",IDC_VOLUME_TOOLS,184,211,84,14 + PUSHBUTTON "Select &File...",IDC_SELECT_FILE,276,192,84,14 + PUSHBUTTON "Select D&evice...",IDC_SELECT_DEVICE,276,211,84,14 + DEFPUSHBUTTON "OK",IDOK,8,243,84,18,WS_GROUP + PUSHBUTTON "&Auto-Mount Devices",IDC_MOUNTALL,100,243,84,18 + PUSHBUTTON "Di&smount All",IDC_UNMOUNTALL,192,243,84,18,WS_GROUP + PUSHBUTTON "E&xit",IDC_EXIT,284,243,84,18,WS_GROUP + CONTROL 112,IDC_LOGO,"Static",SS_BITMAP | SS_NOTIFY | WS_BORDER,13,190,33,31 + GROUPBOX "Volume",IDT_VOLUME,8,179,360,53 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,2,0,372,147 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,282,242,88,20 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,190,242,88,20 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,6,242,88,20 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,98,242,88,20 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDFRAME,2,151,372,119 +END + +IDD_PASSWORD_DLG DIALOGEX 0, 0, 330, 103 +STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_VISIBLE | WS_CAPTION +CAPTION "Enter VeraCrypt Volume Password" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + EDITTEXT IDC_PASSWORD,69,8,179,14,ES_PASSWORD | ES_AUTOHSCROLL + COMBOBOX IDC_PKCS5_PRF_ID,69,26,96,90,CBS_DROPDOWNLIST | WS_TABSTOP + CONTROL "TrueCrypt Mode",IDC_TRUECRYPT_MODE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,170,28,76,10 + EDITTEXT IDC_PIM,69,43,42,14,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER | NOT WS_VISIBLE + CONTROL "Use P&IM",IDC_PIM_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,48,97,10 + CONTROL "Cache passwords and keyfil&es in memory",IDC_CACHE, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,61,153,10 + CONTROL "&Display password",IDC_SHOW_PASSWORD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,74,83,10 + CONTROL "U&se keyfiles",IDC_KEYFILES_ENABLE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,70,87,99,11 + PUSHBUTTON "&Keyfiles...",IDC_KEY_FILES,173,84,75,14 + PUSHBUTTON "Mount Opti&ons...",IDC_MOUNT_OPTIONS,252,84,69,14 + LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,115,46,199,8,NOT WS_VISIBLE + DEFPUSHBUTTON "OK",IDOK,252,8,69,14 + PUSHBUTTON "Cancel",IDCANCEL,252,25,69,14 + RTEXT "Password:",IDT_PASSWORD,0,10,65,13 + RTEXT "PKCS-5 PRF:",IDT_PKCS5_PRF,0,27,65,11 + RTEXT "Volume PIM:",IDT_PIM,0,46,65,8,NOT WS_VISIBLE +END + +IDD_TRAVELER_DLG DIALOGEX 0, 0, 300, 299 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt Traveler Disk Setup" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + EDITTEXT IDC_DIRECTORY,17,29,205,13,ES_AUTOHSCROLL | ES_READONLY + PUSHBUTTON "Browse...",IDC_BROWSE_DIRS,228,28,57,14 + CONTROL "Include VeraCrypt Volume Creation Wizard",IDC_COPY_WIZARD, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,19,48,258,10 + CONTROL "Do nothing",IDC_AUTORUN_DISABLE,"Button",BS_AUTORADIOBUTTON,15,115,262,10 + CONTROL "&Start VeraCrypt",IDC_AUTORUN_START,"Button",BS_AUTORADIOBUTTON,15,126,262,11 + CONTROL "&Auto-mount VeraCrypt volume (specified below)",IDC_AUTORUN_MOUNT, + "Button",BS_AUTORADIOBUTTON,15,138,262,11 + EDITTEXT IDC_VOLUME_NAME,21,175,194,13,ES_AUTOHSCROLL | WS_DISABLED + PUSHBUTTON "Browse...",IDC_BROWSE_FILES,221,174,57,14,WS_DISABLED + COMBOBOX IDC_DRIVELIST,120,193,96,69,CBS_DROPDOWNLIST | WS_DISABLED | WS_VSCROLL | WS_TABSTOP + CONTROL "Open &Explorer window for mounted volume",IDC_TRAVEL_OPEN_EXPLORER, + "Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,22,211,256,10 + CONTROL "Mount volume as read-&only",IDC_MOUNT_READONLY,"Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,22,224,256,10 + CONTROL "&Cache password in driver memory",IDC_TRAV_CACHE_PASSWORDS, + "Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,22,237,256,10 + DEFPUSHBUTTON "Create",IDC_CREATE,173,278,57,14 + PUSHBUTTON "Close",IDCLOSE,236,278,57,14 + GROUPBOX "File Settings",IDT_FILE_SETTINGS,6,7,287,71 + GROUPBOX "AutoRun Configuration (autorun.inf)",IDT_AUTORUN,5,88,288,185 + LTEXT "VeraCrypt volume to mount (relative to traveler disk root):",IDT_TRAVELER_MOUNT,21,165,248,8,WS_DISABLED + RTEXT "Mount volume as drive letter:",IDT_MOUNT_LETTER,18,195,99,8,WS_DISABLED + LTEXT "Create traveler disk files at (traveler disk root directory):",IDT_TRAVEL_ROOT,18,19,259,8 + GROUPBOX "Mount Settings",IDT_MOUNT_SETTINGS,13,152,272,114,WS_DISABLED + LTEXT "Upon insertion of traveler disk: ",IDT_TRAVEL_INSERTION,13,102,263,8 + CONTROL "Include VeraCrypt Volume Expander",IDC_COPY_EXPANDER, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,19,62,258,10 + CONTROL "Include PIM when caching a password",IDC_PREF_CACHE_PIM, + "Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,22,250,256,10 +END + +IDD_HOTKEYS_DLG DIALOGEX 0, 0, 389, 257 +STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - System-Wide Hot Keys" +CLASS "VeraCryptCustomDlg" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + CONTROL "",IDC_HOTKEY_LIST,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,7,375,115 + EDITTEXT IDC_HOTKEY_KEY,108,140,190,13,ES_AUTOHSCROLL + PUSHBUTTON "Assign",IDC_HOTKEY_ASSIGN,304,140,59,14 + CONTROL "Ctrl",IDC_HK_MOD_CTRL,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,109,158,46,10,WS_EX_TRANSPARENT + CONTROL "Shift",IDC_HK_MOD_SHIFT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,162,158,49,10,WS_EX_TRANSPARENT + CONTROL "Alt",IDC_HK_MOD_ALT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,216,158,43,10,WS_EX_TRANSPARENT + CONTROL "Win",IDC_HK_MOD_WIN,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,266,158,34,10,WS_EX_TRANSPARENT + PUSHBUTTON "Remove",IDC_HOTKEY_REMOVE,304,158,59,14 + CONTROL "Play system notification sound after successful hot-key dismount",IDC_HK_DISMOUNT_PLAY_SOUND, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,201,348,10 + CONTROL "Display balloon tooltip after successful hot-key dismount",IDC_HK_DISMOUNT_BALLOON_TOOLTIP, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,213,351,10,WS_EX_TRANSPARENT + DEFPUSHBUTTON "OK",IDOK,260,236,59,14 + PUSHBUTTON "Cancel",IDCANCEL,323,236,59,14 + PUSHBUTTON "Reset",IDC_RESET_HOTKEYS,7,236,59,14 + RTEXT "Key to assign:",IDT_HOTKEY_KEY,15,142,86,8 + GROUPBOX "Hot Key Options",IDT_DISMOUNT_ACTION,7,188,375,42 + GROUPBOX "Shortcut",IDT_ASSIGN_HOTKEY,7,127,375,53 +END + +IDD_TOKEN_PREFERENCES DIALOGEX 0, 0, 316, 199 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - Security Token Preferences" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + EDITTEXT IDC_PKCS11_MODULE,16,23,204,13,ES_AUTOHSCROLL + PUSHBUTTON "Select &Library...",IDC_SELECT_PKCS11_MODULE,226,22,75,14 + PUSHBUTTON "Auto-&Detect Library",IDC_AUTO_DETECT_PKCS11_MODULE,16,41,112,14 + CONTROL "&Close token session (log out) after a volume is successfully mounted",IDC_CLOSE_TOKEN_SESSION_AFTER_MOUNT, + "Button",BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,16,154,284,9 + DEFPUSHBUTTON "OK",IDOK,205,178,50,14 + PUSHBUTTON "Cancel",IDCANCEL,259,178,50,14 + GROUPBOX "PKCS #11 Library Path",IDT_PKCS11_LIB_PATH,7,7,302,129 + GROUPBOX "Security Options",IDT_SECURITY_OPTIONS,7,140,302,30 + LTEXT "",IDT_PKCS11_LIB_HELP,16,63,286,65 +END + +IDD_SYSENC_SETTINGS DIALOGEX 0, 0, 370, 286 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - System Encryption Settings" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "Do not &show any texts in the pre-boot authentication screen (except the below custom message)",IDC_DISABLE_BOOT_LOADER_OUTPUT, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,37,339,9 + EDITTEXT IDC_CUSTOM_BOOT_LOADER_MESSAGE,18,67,216,14,ES_AUTOHSCROLL + CONTROL "&Cache pre-boot authentication password in driver memory (for mounting of non-system volumes)",IDC_BOOT_LOADER_CACHE_PASSWORD, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,192,339,10 + CONTROL "Allow pre-boot &authentication to be bypassed by pressing the Esc key (enables boot manager)",IDC_ALLOW_ESC_PBA_BYPASS, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,222,340,10 + DEFPUSHBUTTON "OK",IDOK,257,262,50,14 + PUSHBUTTON "Cancel",IDCANCEL,313,262,50,14 + LTEXT "Display this custom message in the pre-boot authentication screen (24 characters maximum):",IDT_CUSTOM_BOOT_LOADER_MESSAGE,18,56,337,8 + GROUPBOX "Boot Loader Screen Options",IDT_BOOT_LOADER_SCREEN_OPTIONS,8,7,355,165 + GROUPBOX "Security Options",IDT_SECURITY_OPTIONS,8,177,355,75 + LTEXT "",IDC_CUSTOM_BOOT_LOADER_MESSAGE_HELP,18,89,337,73 + CONTROL "Disable ""Evil Maid"" attack detection",IDC_DISABLE_EVIL_MAID_ATTACK_DETECTION, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,237,340,10 + CONTROL "Include PIM when caching pre-boot authentication password",IDC_BOOT_LOADER_CACHE_PIM, + "Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,18,207,340,10 + CONTROL "Do not request PIM in the pre-boot authentication screen (PIM value is stored unencrypted on disk)",IDC_DISABLE_BOOT_LOADER_PIM_PROMPT, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,20,339,9 +END + +IDD_PERFORMANCE_SETTINGS DIALOGEX 0, 0, 370, 248 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - Performance Options" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "",IDC_HW_AES_SUPPORTED_BY_CPU,"Static",SS_LEFTNOWORDWRAP | WS_GROUP,294,21,57,12,WS_EX_CLIENTEDGE + CONTROL "Accelerate AES encryption/decryption by using the AES instructions of the processor (if available)",IDC_ENABLE_HARDWARE_ENCRYPTION, + "Button",BS_AUTOCHECKBOX | BS_MULTILINE | WS_TABSTOP,18,41,340,17 + LTEXT "More information",IDC_MORE_INFO_ON_HW_ACCELERATION,18,61,165,10,SS_NOTIFY + CONTROL "Do not use the following number of processors for encryption/decryption:",IDC_LIMIT_ENC_THREAD_POOL, + "Button",BS_AUTOCHECKBOX | BS_TOP | WS_TABSTOP,18,103,283,11 + COMBOBOX IDC_ENCRYPTION_FREE_CPU_COUNT,304,101,48,51,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP + LTEXT "More information",IDC_MORE_INFO_ON_THREAD_BASED_PARALLELIZATION,18,159,165,10,SS_NOTIFY + PUSHBUTTON "&Benchmark",IDC_BENCHMARK,7,227,59,14 + DEFPUSHBUTTON "OK",IDOK,257,227,50,14 + PUSHBUTTON "Cancel",IDCANCEL,313,227,50,14 + LTEXT "Processor (CPU) in this computer supports hardware acceleration for AES:",IDT_HW_AES_SUPPORTED_BY_CPU,18,23,273,9 + GROUPBOX "Hardware Acceleration",IDT_ACCELERATION_OPTIONS,7,6,355,74 + GROUPBOX "Thread-Based Parallelization",IDT_PARALLELIZATION_OPTIONS,7,84,355,93 + LTEXT "",IDT_LIMIT_ENC_THREAD_POOL_NOTE,18,126,334,33 + GROUPBOX "Driver Configuration",IDT_DRIVER_OPTIONS,7,183,356,36 + CONTROL "Enable extended disk control codes support",IDC_ENABLE_EXTENDED_IOCTL_SUPPORT, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,198,337,10 +END + +IDD_FAVORITE_VOLUMES DIALOGEX 0, 0, 380, 368 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - Favorite Volumes" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "",IDC_FAVORITE_VOLUMES_LIST,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,7,366,92 + PUSHBUTTON "Move &Up",IDC_FAVORITE_MOVE_UP,7,104,63,14 + PUSHBUTTON "Move &Down",IDC_FAVORITE_MOVE_DOWN,74,104,63,14 + PUSHBUTTON "&Remove",IDC_FAVORITE_REMOVE,310,104,63,14 + EDITTEXT IDC_FAVORITE_LABEL,18,225,344,13,ES_AUTOHSCROLL + CONTROL "Mount selected volume as read-o&nly",IDC_FAVORITE_MOUNT_READONLY, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,255,349,10 + CONTROL "Mount selected volume as remo&vable medium",IDC_FAVORITE_MOUNT_REMOVABLE, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,269,349,10 + CONTROL "Mount selected volume upon log&on",IDC_FAVORITE_MOUNT_ON_LOGON, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,283,349,10 + CONTROL "Mount selected volume when its host device gets &connected",IDC_FAVORITE_MOUNT_ON_ARRIVAL, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,297,349,10 + CONTROL "Open &Explorer window for selected volume when successfully mounted",IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,311,349,11 + CONTROL "Do not mount selected volume when 'Mount Favorite Volumes' &hot key is pressed",IDC_FAVORITE_DISABLE_HOTKEY, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,326,349,11 + LTEXT "Help on favorite volumes",IDC_FAVORITES_HELP_LINK,17,351,237,10,SS_NOTIFY + DEFPUSHBUTTON "OK",IDOK,269,347,50,14 + PUSHBUTTON "Cancel",IDCANCEL,323,347,50,14 + GROUPBOX "",IDC_FAV_VOL_OPTIONS_GROUP_BOX,7,123,366,219 + LTEXT "Label of selected favorite volume:",IDT_FAVORITE_LABEL,18,215,202,8 + GROUPBOX "Global Settings",IDC_FAV_VOL_OPTIONS_GLOBAL_SETTINGS_BOX,7,300,366,42 + EDITTEXT IDC_PIM,18,183,42,13,ES_RIGHT | ES_PASSWORD | ES_AUTOHSCROLL | ES_NUMBER + LTEXT "(Empty or 0 for default iterations)",IDC_PIM_HELP,64,185,189,8 + LTEXT "Volume PIM:",IDT_PIM,18,173,65,8 + CONTROL "Display PIM",IDC_SHOW_PIM,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,199,150,10 + CONTROL "Use favorite label as Explorer drive label",IDC_FAVORITE_USE_LABEL_IN_EXPLORER, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,242,349,10 + LTEXT "Volume ID:",IDT_VOLUME_ID,18,131,57,8 + EDITTEXT IDC_FAVORITE_VOLUME_ID,18,141,344,14,ES_AUTOHSCROLL | ES_READONLY + CONTROL "Use Volume ID to mount favorite",IDC_FAVORITE_USE_VOLUME_ID, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,18,159,337,10 +END + +IDD_DEFAULT_MOUNT_PARAMETERS DIALOGEX 0, 0, 167, 65 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt - Mount Parameters" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + DEFPUSHBUTTON "OK",IDOK,57,44,50,14 + PUSHBUTTON "Cancel",IDCANCEL,111,44,50,14 + COMBOBOX IDC_PKCS5_PRF_ID,57,24,103,90,CBS_DROPDOWNLIST | WS_TABSTOP + LTEXT "PKCS-5 PRF:",IDT_PKCS5_PRF,8,26,44,11 + CONTROL "TrueCrypt Mode",IDC_TRUECRYPT_MODE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,7,76,10 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_PREFERENCES_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 329 + TOPMARGIN, 7 + BOTTOMMARGIN, 331 + END + + IDD_VOLUME_PROPERTIES, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 277 + TOPMARGIN, 7 + BOTTOMMARGIN, 217 + END + + IDD_PASSWORDCHANGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 339 + TOPMARGIN, 7 + BOTTOMMARGIN, 238 + END + + IDD_MOUNT_DLG, DIALOG + BEGIN + RIGHTMARGIN, 369 + BOTTOMMARGIN, 269 + END + + IDD_PASSWORD_DLG, DIALOG + BEGIN + RIGHTMARGIN, 321 + BOTTOMMARGIN, 98 + END + + IDD_TRAVELER_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 293 + TOPMARGIN, 7 + BOTTOMMARGIN, 292 + END + + IDD_HOTKEYS_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 382 + TOPMARGIN, 7 + BOTTOMMARGIN, 250 + END + + IDD_TOKEN_PREFERENCES, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 309 + TOPMARGIN, 7 + BOTTOMMARGIN, 192 + END + + IDD_SYSENC_SETTINGS, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 363 + TOPMARGIN, 7 + BOTTOMMARGIN, 276 + END + + IDD_PERFORMANCE_SETTINGS, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 363 + TOPMARGIN, 7 + BOTTOMMARGIN, 241 + END + + IDD_FAVORITE_VOLUMES, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 373 + TOPMARGIN, 7 + BOTTOMMARGIN, 361 + END + + IDD_DEFAULT_MOUNT_PARAMETERS, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 160 + TOPMARGIN, 7 + BOTTOMMARGIN, 58 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,17,22,0 + PRODUCTVERSION 1,17,22,0 + FILEFLAGSMASK 0x17L +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "IDRIX" + VALUE "FileDescription", "VeraCrypt" + VALUE "FileVersion", "1.17" + VALUE "LegalTrademarks", "VeraCrypt" + VALUE "OriginalFilename", "VeraCrypt.exe" + VALUE "ProductName", "VeraCrypt" + VALUE "ProductVersion", "1.17" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "#include ""..\\\\common\\\\resource.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "#include ""..\\\\common\\\\common.rc""\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Bitmap +// + +IDB_DRIVEICON BITMAP "Drive_icon_96dpi.bmp" +IDB_DRIVEICON_MASK BITMAP "Drive_icon_mask_96dpi.bmp" +IDB_LOGO_96DPI BITMAP "Logo_96dpi.bmp" +IDB_LOGO_288DPI BITMAP "Logo_288dpi.bmp" +IDB_SYS_DRIVEICON BITMAP "System_drive_icon_96dpi.bmp" +IDB_SYS_DRIVEICON_MASK BITMAP "System_drive_icon_mask_96dpi.bmp" + +///////////////////////////////////////////////////////////////////////////// +// +// Menu +// + +IDR_MENU MENU +BEGIN + POPUP "&Volumes" + BEGIN + MENUITEM "Select File...", IDM_SELECT_FILE + MENUITEM "Select Device...", IDM_SELECT_DEVICE + MENUITEM SEPARATOR + MENUITEM "Create New Volume...", IDM_CREATE_VOLUME + MENUITEM "Permanently Decrypt...", IDM_DECRYPT_NONSYS_VOL + MENUITEM "Resume Interrupted Process", IDM_RESUME_INTERRUPTED_PROC + MENUITEM SEPARATOR + MENUITEM "Mount Volume", IDM_MOUNT_VOLUME + MENUITEM "Mount Volume with Options", IDM_MOUNT_VOLUME_OPTIONS + MENUITEM "Auto-Mount All Device-Hosted Volumes", IDM_MOUNTALL + MENUITEM SEPARATOR + MENUITEM "Dismount Volume", IDM_UNMOUNT_VOLUME + MENUITEM "Dismount All Mounted Volumes", IDM_UNMOUNTALL + MENUITEM SEPARATOR + MENUITEM "Change Volume Password...", IDM_CHANGE_PASSWORD + MENUITEM "Add/Remove Keyfiles to/from Volume...", IDM_ADD_REMOVE_VOL_KEYFILES + MENUITEM "Remove All Keyfiles from Volume...", IDM_REMOVE_ALL_KEYFILES_FROM_VOL + MENUITEM "Set Header Key Derivation Algorithm...", IDM_CHANGE_HEADER_KEY_DERIV_ALGO + MENUITEM SEPARATOR + MENUITEM "Volume Properties", IDM_VOLUME_PROPERTIES + END + POPUP "S&ystem" + BEGIN + MENUITEM "Encrypt System Partition/Drive...", IDM_ENCRYPT_SYSTEM_DEVICE + MENUITEM "Permanently Decrypt System Partition/Drive", IDM_PERMANENTLY_DECRYPT_SYS + MENUITEM "Resume Interrupted Process", IDM_SYSENC_RESUME + MENUITEM SEPARATOR + MENUITEM "Create Hidden Operating System...", IDM_CREATE_HIDDEN_OS + MENUITEM SEPARATOR + MENUITEM "Create Rescue Disk...", IDM_CREATE_RESCUE_DISK + MENUITEM "Verify Rescue Disk", IDM_VERIFY_RESCUE_DISK + MENUITEM "Verify Rescue Disk ISO Image", IDM_VERIFY_RESCUE_DISK_ISO + MENUITEM SEPARATOR + MENUITEM "Mount Without Pre-Boot &Authentication...", IDM_MOUNT_SYSENC_PART_WITHOUT_PBA + MENUITEM SEPARATOR + MENUITEM "Change Password...", IDM_CHANGE_SYS_PASSWORD + MENUITEM "Set Header Key Derivation Algorithm...", IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO + MENUITEM SEPARATOR + MENUITEM "Properties...", IDM_SYSTEM_ENCRYPTION_STATUS + MENUITEM SEPARATOR + MENUITEM "Settings...", IDM_SYS_ENC_SETTINGS + END + POPUP "Favor&ites" + BEGIN + MENUITEM "Add Mounted Volume to Favorites...", IDM_ADD_VOLUME_TO_FAVORITES + MENUITEM "Add Mounted Volume to System Favorites...", IDM_ADD_VOLUME_TO_SYSTEM_FAVORITES + MENUITEM SEPARATOR + MENUITEM "Organize Favorite Volumes...", IDM_ORGANIZE_FAVORITES + MENUITEM "Organize System Favorite Volumes...", IDM_ORGANIZE_SYSTEM_FAVORITES + MENUITEM SEPARATOR + MENUITEM "Mount Favorite Volumes", IDM_MOUNT_FAVORITE_VOLUMES + END + POPUP "T&ools" + BEGIN + MENUITEM "Benchmark...", IDM_BENCHMARK + MENUITEM "Test Vectors...", IDM_TEST_VECTORS + MENUITEM SEPARATOR + MENUITEM "Traveler Disk Setup...", IDM_TRAVELER + MENUITEM "Volume Expander", IDM_VOLUME_EXPANDER + MENUITEM "Volume Creation Wizard", IDM_VOLUME_WIZARD + MENUITEM SEPARATOR + MENUITEM "Keyfile Generator", IDM_KEYFILE_GENERATOR + MENUITEM "Manage Security Token Keyfiles...", IDM_MANAGE_TOKEN_KEYFILES + MENUITEM "Close All Security Token Sessions", IDM_CLOSE_ALL_TOKEN_SESSIONS + MENUITEM SEPARATOR + MENUITEM "Backup Volume Header...", IDM_BACKUP_VOL_HEADER + MENUITEM "Restore Volume Header...", IDM_RESTORE_VOL_HEADER + MENUITEM SEPARATOR + MENUITEM "Refresh Drive Letters", IDM_REFRESH_DRIVE_LETTERS + MENUITEM SEPARATOR + MENUITEM "Clear Volume History", IDM_CLEAR_HISTORY + MENUITEM "Wipe Cached Passwords", IDM_WIPE_CACHE + END + POPUP "Settin&gs" + BEGIN + MENUITEM "Language...", IDM_LANGUAGE + MENUITEM "Hot Keys...", IDM_HOTKEY_SETTINGS + MENUITEM SEPARATOR + MENUITEM "System Encryption...", IDM_SYSENC_SETTINGS + MENUITEM "System Favorite Volumes...", IDM_SYS_FAVORITES_SETTINGS + MENUITEM SEPARATOR + MENUITEM "Performance/Driver Configuration", IDM_PERFORMANCE_SETTINGS + MENUITEM SEPARATOR + MENUITEM "Default Keyfiles...", IDM_DEFAULT_KEYFILES + MENUITEM "Default Mount Parameters...", IDM_DEFAULT_MOUNT_PARAMETERS + MENUITEM "Security Tokens...", IDM_TOKEN_PREFERENCES + MENUITEM SEPARATOR + MENUITEM "Preferences...", IDM_PREFERENCES + END + POPUP "Hel&p" + BEGIN + MENUITEM "User's Guide", IDM_HELP + MENUITEM "Online Help", IDM_ONLINE_HELP + MENUITEM "Beginner's Tutorial", IDM_ONLINE_TUTORIAL + MENUITEM "Frequently Asked Questions", IDM_FAQ + MENUITEM SEPARATOR + MENUITEM "VeraCrypt Website", IDM_WEBSITE + MENUITEM "Downloads", IDM_TC_DOWNLOADS + MENUITEM "News", IDM_NEWS + MENUITEM "Version History", IDM_VERSION_HISTORY + MENUITEM SEPARATOR + MENUITEM "Donate now...", IDM_DONATE + MENUITEM "Contact", IDM_CONTACT + MENUITEM "Legal Notices", IDM_LICENSE + MENUITEM "About", IDM_ABOUT + END + MENUITEM "&Homepage ", IDM_HOMEPAGE +END + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE +BEGIN + IDS_UACSTRING "VeraCrypt" +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#include "..\\common\\common.rc" + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/src/Mount/Mount.vcproj b/src/Mount/Mount.vcproj index 64163c7c..c9a6ebc5 100644 --- a/src/Mount/Mount.vcproj +++ b/src/Mount/Mount.vcproj @@ -1,1027 +1,1027 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Mount/Resource.h b/src/Mount/Resource.h index 210cfde2..fee7905b 100644 --- a/src/Mount/Resource.h +++ b/src/Mount/Resource.h @@ -1,263 +1,263 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by Mount.rc -// -#define IDR_MOUNT_TLB 1 -#define IDD_MOUNT_DLG 101 -#define IDD_PASSWORDCHANGE_DLG 102 -#define IDB_DRIVEICON 103 -#define IDD_PASSWORD_DLG 104 -#define IDB_DRIVEICON_MASK 105 -#define IDR_MENU 106 -#define IDD_PREFERENCES_DLG 107 -#define IDD_VOLUME_PROPERTIES 108 -#define IDR_MOUNT_RSRC_HEADER 109 -#define IDS_UACSTRING 110 -#define IDB_LOGO_288DPI 111 -#define IDB_LOGO_96DPI 112 -#define IDB_SYS_DRIVEICON 113 -#define IDB_SYS_DRIVEICON_MASK 114 -#define IDD_TOKEN_PREFERENCES 115 -#define IDD_SYSENC_SETTINGS 116 -#define IDD_FAVORITE_VOLUMES 117 -#define IDD_DEFAULT_MOUNT_PARAMETERS 118 -#define IDC_PREF_MOUNT_READONLY 1000 -#define IDC_PREF_MOUNT_REMOVABLE 1001 -#define IDC_VERIFY 1002 -#define IDC_PREF_BKG_TASK_ENABLE 1003 -#define IDC_OLD_PASSWORD 1004 -#define IDC_CACHE 1005 -#define IDC_NO_HISTORY 1006 -#define IDC_DRIVELIST 1007 -#define IDC_PREF_OPEN_EXPLORER 1008 -#define IDC_ENABLE_KEYFILES 1009 -#define IDC_VOLUME_PROPERTIES_LIST 1010 -#define IDC_PREF_USE_DIFF_TRAY_ICON_IF_VOL_MOUNTED 1011 -#define IDC_ENABLE_NEW_KEYFILES 1012 -#define IDC_PRESERVE_TIMESTAMPS 1013 -#define IDC_PREF_WIPE_CACHE_ON_EXIT 1014 -#define IDC_PREF_CACHE_PASSWORDS 1016 -#define IDC_DIRECTORY 1017 -#define IDC_PREF_DISMOUNT_LOGOFF 1018 -#define IDC_BROWSE_DIRS 1019 -#define IDC_PREF_DISMOUNT_INACTIVE 1020 -#define IDC_AUTORUN_DISABLE 1021 -#define IDC_AUTORUN_START 1022 -#define IDC_BENCHMARK 1023 -#define IDC_AUTORUN_MOUNT 1024 -#define IDC_VOLUME_NAME 1025 -#define IDC_COPY_WIZARD 1026 -#define IDC_MOUNT_OPTIONS 1027 -#define IDT_TRAVELER_MOUNT 1028 -#define IDT_MOUNT_LETTER 1029 -#define IDT_MOUNT_SETTINGS 1030 -#define IDC_KEY_FILES 1031 -#define IDC_NEW_KEYFILES 1032 -#define IDC_KEYFILES 1033 -#define IDC_VOLUME 1034 -#define IDC_PASSWORD 1035 -#define IDC_BROWSE_FILES 1036 -#define IDC_SELECT_DEVICE 1037 -#define IDC_CREATE_VOLUME 1038 -#define IDC_VOLUME_TOOLS 1039 -#define IDC_WIPE_CACHE 1040 -#define IDC_MOUNTALL 1041 -#define IDD_TRAVELER_DLG 1042 -#define IDC_SELECT_FILE 1043 -#define IDD_HOTKEYS_DLG 1044 -#define IDC_VOLUME_PROPERTIES 1045 -#define IDT_FILE_SETTINGS 1046 -#define IDD_PERFORMANCE_SETTINGS 1047 -#define IDT_AUTORUN 1048 -#define IDT_TRAVEL_INSERTION 1049 -#define IDT_TRAVEL_ROOT 1050 -#define IDT_VOLUME 1051 -#define IDT_PASSWORD 1052 -#define IDT_CURRENT 1053 -#define IDT_NEW 1054 -#define IDT_NEW_PASSWORD 1055 -#define IDT_CONFIRM_PASSWORD 1056 -#define IDT_PW_CACHE_OPTIONS 1058 -#define IDT_DEFAULT_MOUNT_OPTIONS 1059 -#define IDT_WINDOWS_RELATED_SETTING 1060 -#define IDC_CREATE 1061 -#define IDC_EXIT 1062 -#define IDC_TRAVEL_OPEN_EXPLORER 1063 -#define IDC_TRAV_CACHE_PASSWORDS 1064 -#define IDC_UNMOUNTALL 1065 -#define IDT_TASKBAR_ICON 1066 -#define IDT_AUTO_DISMOUNT 1067 -#define IDC_PREF_FORCE_AUTO_DISMOUNT 1068 -#define IDC_PREF_DISMOUNT_INACTIVE_TIME 1069 -#define IDT_MINUTES 1070 -#define IDC_PREF_DISMOUNT_SCREENSAVER 1071 -#define IDC_PREF_DISMOUNT_POWERSAVING 1072 -#define IDT_AUTO_DISMOUNT_ON 1073 -#define IDC_PREF_WIPE_CACHE_ON_AUTODISMOUNT 1074 -#define IDC_CLOSE_BKG_TASK_WHEN_NOVOL 1075 -#define IDC_MORE_INFO_ON_HW_ACCELERATION 1076 -#define IDT_LOGON 1077 -#define IDC_MORE_INFO_ON_THREAD_BASED_PARALLELIZATION 1078 -#define IDC_PREF_LOGON_START 1079 -#define IDC_PREF_LOGON_MOUNT_DEVICES 1080 -#define IDC_SHOW_PASSWORD_CHPWD_NEW 1081 -#define IDC_HK_DISMOUNT_BALLOON_TOOLTIP 1082 -#define IDC_SHOW_PASSWORD_CHPWD_ORI 1083 -#define IDC_HK_DISMOUNT_PLAY_SOUND 1084 -#define IDC_HOTKEY_ASSIGN 1085 -#define IDC_HOTKEY_REMOVE 1086 -#define IDC_HOTKEY_KEY 1087 -#define IDT_HOTKEY_KEY 1088 -#define IDC_HOTKEY_LIST 1089 -#define IDC_RESET_HOTKEYS 1090 -#define IDT_DISMOUNT_ACTION 1091 -#define IDT_ASSIGN_HOTKEY 1092 -#define IDC_HK_MOD_SHIFT 1093 -#define IDC_HK_MOD_CTRL 1094 -#define IDC_HK_MOD_ALT 1095 -#define IDC_HK_MOD_WIN 1096 -#define IDC_SHOW_PASSWORD 1097 -#define IDC_LOGO 1098 -#define IDT_PKCS11_LIB_PATH 1099 -#define IDC_PKCS11_MODULE 1100 -#define IDC_SELECT_PKCS11_MODULE 1101 -#define IDC_AUTO_DETECT_PKCS11_MODULE 1102 -#define IDC_CLOSE_TOKEN_SESSION_AFTER_MOUNT 1103 -#define IDT_SECURITY_OPTIONS 1104 -#define IDC_DISABLE_BOOT_LOADER_OUTPUT 1105 -#define IDC_ALLOW_ESC_PBA_BYPASS 1106 -#define IDC_CUSTOM_BOOT_LOADER_MESSAGE 1107 -#define IDC_BOOT_LOADER_CACHE_PASSWORD 1108 -#define IDC_MORE_SETTINGS 1109 -#define IDT_CUSTOM_BOOT_LOADER_MESSAGE 1110 -#define IDC_CUSTOM_BOOT_LOADER_MESSAGE_HELP 1111 -#define IDT_BOOT_LOADER_SCREEN_OPTIONS 1112 -#define IDT_PKCS11_LIB_HELP 1113 -#define IDT_ACCELERATION_OPTIONS 1114 -#define IDC_ENABLE_HARDWARE_ENCRYPTION 1115 -#define IDC_FAVORITE_VOLUMES_LIST 1116 -#define IDC_FAVORITE_MOUNT_READONLY 1117 -#define IDC_FAVORITE_MOUNT_REMOVABLE 1118 -#define IDC_FAVORITE_MOUNT_ON_ARRIVAL 1119 -#define IDC_FAVORITE_LABEL 1120 -#define IDT_FAVORITE_LABEL 1121 -#define IDC_FAVORITE_MOUNT_ON_LOGON 1122 -#define IDC_FAVORITE_DISABLE_HOTKEY 1123 -#define IDC_FAVORITE_MOVE_UP 1124 -#define IDC_FAVORITE_MOVE_DOWN 1125 -#define IDC_FAVORITE_REMOVE 1126 -#define IDT_HW_AES_SUPPORTED_BY_CPU 1127 -#define IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT 1128 -#define IDC_HW_AES_SUPPORTED_BY_CPU 1129 -#define IDC_LIMIT_ENC_THREAD_POOL 1130 -#define IDC_ENCRYPTION_FREE_CPU_COUNT 1131 -#define IDT_PARALLELIZATION_OPTIONS 1132 -#define IDT_LIMIT_ENC_THREAD_POOL_NOTE 1133 -#define IDC_FAV_VOL_OPTIONS_GROUP_BOX 1134 -#define IDC_FAVORITES_HELP_LINK 1135 -#define IDC_FAV_VOL_OPTIONS_GLOBAL_SETTINGS_BOX 1136 -#define IDC_PREF_DISMOUNT_SESSION_LOCKED 1137 -#define IDT_NEW_PKCS5_PRF 1138 -#define IDC_PKCS5_OLD_PRF_ID 1139 -#define IDC_TRUECRYPT_MODE 1140 -#define IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT 1141 -#define IDT_OLD_PIM 1142 -#define IDC_OLD_PIM 1143 -#define IDC_OLD_PIM_HELP 1144 -#define IDC_NEW_PIM_ENABLE 1145 -#define IDC_SHOW_PIM 1146 -#define IDC_FAVORITE_USE_LABEL_IN_EXPLORER 1147 -#define IDC_COPY_EXPANDER 1148 -#define IDT_DRIVER_OPTIONS 1149 -#define IDC_ENABLE_EXTENDED_IOCTL_SUPPORT 1150 -#define IDC_DISABLE_EVIL_MAID_ATTACK_DETECTION 1151 -#define IDC_WIPE_MODE 1152 -#define IDT_WIPE_MODE 1153 -#define IDC_PREF_CACHE_PIM 1154 -#define IDC_BOOT_LOADER_CACHE_PIM 1155 -#define IDC_SHOW_DISCONNECTED_NETWORK_DRIVES 1156 -#define IDT_VOLUME_ID 1157 -#define IDC_FAVORITE_VOLUME_ID 1158 -#define IDC_FAVORITE_USE_VOLUME_ID 1159 -#define IDC_DISABLE_BOOT_LOADER_PIM_PROMPT 1160 -#define IDC_HIDE_WAITING_DIALOG 1161 -#define IDM_HELP 40001 -#define IDM_ABOUT 40002 -#define IDM_UNMOUNT_VOLUME 40003 -#define IDM_CLEAR_HISTORY 40004 -#define IDM_BENCHMARK 40005 -#define IDM_TRAVELER 40006 -#define IDM_MOUNT_VOLUME_OPTIONS 40007 -#define IDM_FAQ 40008 -#define IDM_REFRESH_DRIVE_LETTERS 40009 -#define IDM_DEFAULT_KEYFILES 40010 -#define IDM_WEBSITE 40011 -#define IDM_MOUNTALL 40012 -#define IDM_UNMOUNTALL 40013 -#define IDM_MOUNT_VOLUME 40014 -#define IDM_CHANGE_PASSWORD 40015 -#define IDM_VOLUME_WIZARD 40016 -#define IDM_CREATE_VOLUME 40017 -#define IDM_WIPE_CACHE 40018 -#define IDM_PREFERENCES 40019 -#define IDM_LICENSE 40020 -#define IDM_SELECT_FILE 40021 -#define IDM_SELECT_DEVICE 40022 -#define IDM_VOLUME_PROPERTIES 40023 -#define IDM_LANGUAGE 40024 -#define IDM_MOUNT_FAVORITE_VOLUMES 40025 -#define IDM_BACKUP_VOL_HEADER 40026 -#define IDM_RESTORE_VOL_HEADER 40027 -#define IDM_HOTKEY_SETTINGS 40028 -#define IDM_TC_DOWNLOADS 40029 -#define IDM_NEWS 40030 -#define IDM_CONTACT 40031 -#define IDM_VERSION_HISTORY 40032 -#define IDM_HOMEPAGE 40033 -#define IDM_TEST_VECTORS 40034 -#define IDM_ADD_REMOVE_VOL_KEYFILES 40035 -#define IDM_REMOVE_ALL_KEYFILES_FROM_VOL 40036 -#define IDM_CHANGE_HEADER_KEY_DERIV_ALGO 40037 -#define IDM_KEYFILE_GENERATOR 40038 -#define IDM_ONLINE_TUTORIAL 40039 -#define IDM_ONLINE_HELP 40040 -#define IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO 40041 -#define IDM_CHANGE_SYS_PASSWORD 40042 -#define IDM_CREATE_RESCUE_DISK 40043 -#define IDM_PERMANENTLY_DECRYPT_SYS 40044 -#define IDM_VERIFY_RESCUE_DISK 40045 -#define IDM_SYSTEM_ENCRYPTION_STATUS 40046 -#define IDM_ENCRYPT_SYSTEM_DEVICE 40047 -#define IDM_SYSENC_RESUME 40048 -#define IDM_MOUNT_SYSENC_PART_WITHOUT_PBA 40049 -#define IDM_CREATE_HIDDEN_OS 40050 -#define IDM_TOKEN_PREFERENCES 40051 -#define IDM_CLOSE_ALL_TOKEN_SESSIONS 40052 -#define IDM_SYS_ENC_SETTINGS 40053 -#define IDM_SYSENC_SETTINGS 40054 -#define IDM_RESUME_INTERRUPTED_PROC 40055 -#define IDM_MANAGE_TOKEN_KEYFILES 40056 -#define IDM_SYS_FAVORITES_SETTINGS 40057 -#define IDM_ORGANIZE_FAVORITES 40058 -#define IDM_ORGANIZE_SYSTEM_FAVORITES 40059 -#define IDM_ADD_VOLUME_TO_FAVORITES 40060 -#define IDM_ADD_VOLUME_TO_SYSTEM_FAVORITES 40061 -#define IDM_PERFORMANCE_SETTINGS 40062 -#define IDM_ANALYZE_SYSTEM_CRASH 40063 -#define IDM_DONATE 40064 -#define IDM_VOLUME_EXPANDER 40065 -#define IDM_DEFAULT_MOUNT_PARAMETERS 40066 -#define IDM_DECRYPT_NONSYS_VOL 40067 -#define IDM_VERIFY_RESCUE_DISK_ISO 40068 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NO_MFC 1 -#define _APS_NEXT_RESOURCE_VALUE 119 -#define _APS_NEXT_COMMAND_VALUE 40069 -#define _APS_NEXT_CONTROL_VALUE 1162 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Mount.rc +// +#define IDR_MOUNT_TLB 1 +#define IDD_MOUNT_DLG 101 +#define IDD_PASSWORDCHANGE_DLG 102 +#define IDB_DRIVEICON 103 +#define IDD_PASSWORD_DLG 104 +#define IDB_DRIVEICON_MASK 105 +#define IDR_MENU 106 +#define IDD_PREFERENCES_DLG 107 +#define IDD_VOLUME_PROPERTIES 108 +#define IDR_MOUNT_RSRC_HEADER 109 +#define IDS_UACSTRING 110 +#define IDB_LOGO_288DPI 111 +#define IDB_LOGO_96DPI 112 +#define IDB_SYS_DRIVEICON 113 +#define IDB_SYS_DRIVEICON_MASK 114 +#define IDD_TOKEN_PREFERENCES 115 +#define IDD_SYSENC_SETTINGS 116 +#define IDD_FAVORITE_VOLUMES 117 +#define IDD_DEFAULT_MOUNT_PARAMETERS 118 +#define IDC_PREF_MOUNT_READONLY 1000 +#define IDC_PREF_MOUNT_REMOVABLE 1001 +#define IDC_VERIFY 1002 +#define IDC_PREF_BKG_TASK_ENABLE 1003 +#define IDC_OLD_PASSWORD 1004 +#define IDC_CACHE 1005 +#define IDC_NO_HISTORY 1006 +#define IDC_DRIVELIST 1007 +#define IDC_PREF_OPEN_EXPLORER 1008 +#define IDC_ENABLE_KEYFILES 1009 +#define IDC_VOLUME_PROPERTIES_LIST 1010 +#define IDC_PREF_USE_DIFF_TRAY_ICON_IF_VOL_MOUNTED 1011 +#define IDC_ENABLE_NEW_KEYFILES 1012 +#define IDC_PRESERVE_TIMESTAMPS 1013 +#define IDC_PREF_WIPE_CACHE_ON_EXIT 1014 +#define IDC_PREF_CACHE_PASSWORDS 1016 +#define IDC_DIRECTORY 1017 +#define IDC_PREF_DISMOUNT_LOGOFF 1018 +#define IDC_BROWSE_DIRS 1019 +#define IDC_PREF_DISMOUNT_INACTIVE 1020 +#define IDC_AUTORUN_DISABLE 1021 +#define IDC_AUTORUN_START 1022 +#define IDC_BENCHMARK 1023 +#define IDC_AUTORUN_MOUNT 1024 +#define IDC_VOLUME_NAME 1025 +#define IDC_COPY_WIZARD 1026 +#define IDC_MOUNT_OPTIONS 1027 +#define IDT_TRAVELER_MOUNT 1028 +#define IDT_MOUNT_LETTER 1029 +#define IDT_MOUNT_SETTINGS 1030 +#define IDC_KEY_FILES 1031 +#define IDC_NEW_KEYFILES 1032 +#define IDC_KEYFILES 1033 +#define IDC_VOLUME 1034 +#define IDC_PASSWORD 1035 +#define IDC_BROWSE_FILES 1036 +#define IDC_SELECT_DEVICE 1037 +#define IDC_CREATE_VOLUME 1038 +#define IDC_VOLUME_TOOLS 1039 +#define IDC_WIPE_CACHE 1040 +#define IDC_MOUNTALL 1041 +#define IDD_TRAVELER_DLG 1042 +#define IDC_SELECT_FILE 1043 +#define IDD_HOTKEYS_DLG 1044 +#define IDC_VOLUME_PROPERTIES 1045 +#define IDT_FILE_SETTINGS 1046 +#define IDD_PERFORMANCE_SETTINGS 1047 +#define IDT_AUTORUN 1048 +#define IDT_TRAVEL_INSERTION 1049 +#define IDT_TRAVEL_ROOT 1050 +#define IDT_VOLUME 1051 +#define IDT_PASSWORD 1052 +#define IDT_CURRENT 1053 +#define IDT_NEW 1054 +#define IDT_NEW_PASSWORD 1055 +#define IDT_CONFIRM_PASSWORD 1056 +#define IDT_PW_CACHE_OPTIONS 1058 +#define IDT_DEFAULT_MOUNT_OPTIONS 1059 +#define IDT_WINDOWS_RELATED_SETTING 1060 +#define IDC_CREATE 1061 +#define IDC_EXIT 1062 +#define IDC_TRAVEL_OPEN_EXPLORER 1063 +#define IDC_TRAV_CACHE_PASSWORDS 1064 +#define IDC_UNMOUNTALL 1065 +#define IDT_TASKBAR_ICON 1066 +#define IDT_AUTO_DISMOUNT 1067 +#define IDC_PREF_FORCE_AUTO_DISMOUNT 1068 +#define IDC_PREF_DISMOUNT_INACTIVE_TIME 1069 +#define IDT_MINUTES 1070 +#define IDC_PREF_DISMOUNT_SCREENSAVER 1071 +#define IDC_PREF_DISMOUNT_POWERSAVING 1072 +#define IDT_AUTO_DISMOUNT_ON 1073 +#define IDC_PREF_WIPE_CACHE_ON_AUTODISMOUNT 1074 +#define IDC_CLOSE_BKG_TASK_WHEN_NOVOL 1075 +#define IDC_MORE_INFO_ON_HW_ACCELERATION 1076 +#define IDT_LOGON 1077 +#define IDC_MORE_INFO_ON_THREAD_BASED_PARALLELIZATION 1078 +#define IDC_PREF_LOGON_START 1079 +#define IDC_PREF_LOGON_MOUNT_DEVICES 1080 +#define IDC_SHOW_PASSWORD_CHPWD_NEW 1081 +#define IDC_HK_DISMOUNT_BALLOON_TOOLTIP 1082 +#define IDC_SHOW_PASSWORD_CHPWD_ORI 1083 +#define IDC_HK_DISMOUNT_PLAY_SOUND 1084 +#define IDC_HOTKEY_ASSIGN 1085 +#define IDC_HOTKEY_REMOVE 1086 +#define IDC_HOTKEY_KEY 1087 +#define IDT_HOTKEY_KEY 1088 +#define IDC_HOTKEY_LIST 1089 +#define IDC_RESET_HOTKEYS 1090 +#define IDT_DISMOUNT_ACTION 1091 +#define IDT_ASSIGN_HOTKEY 1092 +#define IDC_HK_MOD_SHIFT 1093 +#define IDC_HK_MOD_CTRL 1094 +#define IDC_HK_MOD_ALT 1095 +#define IDC_HK_MOD_WIN 1096 +#define IDC_SHOW_PASSWORD 1097 +#define IDC_LOGO 1098 +#define IDT_PKCS11_LIB_PATH 1099 +#define IDC_PKCS11_MODULE 1100 +#define IDC_SELECT_PKCS11_MODULE 1101 +#define IDC_AUTO_DETECT_PKCS11_MODULE 1102 +#define IDC_CLOSE_TOKEN_SESSION_AFTER_MOUNT 1103 +#define IDT_SECURITY_OPTIONS 1104 +#define IDC_DISABLE_BOOT_LOADER_OUTPUT 1105 +#define IDC_ALLOW_ESC_PBA_BYPASS 1106 +#define IDC_CUSTOM_BOOT_LOADER_MESSAGE 1107 +#define IDC_BOOT_LOADER_CACHE_PASSWORD 1108 +#define IDC_MORE_SETTINGS 1109 +#define IDT_CUSTOM_BOOT_LOADER_MESSAGE 1110 +#define IDC_CUSTOM_BOOT_LOADER_MESSAGE_HELP 1111 +#define IDT_BOOT_LOADER_SCREEN_OPTIONS 1112 +#define IDT_PKCS11_LIB_HELP 1113 +#define IDT_ACCELERATION_OPTIONS 1114 +#define IDC_ENABLE_HARDWARE_ENCRYPTION 1115 +#define IDC_FAVORITE_VOLUMES_LIST 1116 +#define IDC_FAVORITE_MOUNT_READONLY 1117 +#define IDC_FAVORITE_MOUNT_REMOVABLE 1118 +#define IDC_FAVORITE_MOUNT_ON_ARRIVAL 1119 +#define IDC_FAVORITE_LABEL 1120 +#define IDT_FAVORITE_LABEL 1121 +#define IDC_FAVORITE_MOUNT_ON_LOGON 1122 +#define IDC_FAVORITE_DISABLE_HOTKEY 1123 +#define IDC_FAVORITE_MOVE_UP 1124 +#define IDC_FAVORITE_MOVE_DOWN 1125 +#define IDC_FAVORITE_REMOVE 1126 +#define IDT_HW_AES_SUPPORTED_BY_CPU 1127 +#define IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT 1128 +#define IDC_HW_AES_SUPPORTED_BY_CPU 1129 +#define IDC_LIMIT_ENC_THREAD_POOL 1130 +#define IDC_ENCRYPTION_FREE_CPU_COUNT 1131 +#define IDT_PARALLELIZATION_OPTIONS 1132 +#define IDT_LIMIT_ENC_THREAD_POOL_NOTE 1133 +#define IDC_FAV_VOL_OPTIONS_GROUP_BOX 1134 +#define IDC_FAVORITES_HELP_LINK 1135 +#define IDC_FAV_VOL_OPTIONS_GLOBAL_SETTINGS_BOX 1136 +#define IDC_PREF_DISMOUNT_SESSION_LOCKED 1137 +#define IDT_NEW_PKCS5_PRF 1138 +#define IDC_PKCS5_OLD_PRF_ID 1139 +#define IDC_TRUECRYPT_MODE 1140 +#define IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT 1141 +#define IDT_OLD_PIM 1142 +#define IDC_OLD_PIM 1143 +#define IDC_OLD_PIM_HELP 1144 +#define IDC_NEW_PIM_ENABLE 1145 +#define IDC_SHOW_PIM 1146 +#define IDC_FAVORITE_USE_LABEL_IN_EXPLORER 1147 +#define IDC_COPY_EXPANDER 1148 +#define IDT_DRIVER_OPTIONS 1149 +#define IDC_ENABLE_EXTENDED_IOCTL_SUPPORT 1150 +#define IDC_DISABLE_EVIL_MAID_ATTACK_DETECTION 1151 +#define IDC_WIPE_MODE 1152 +#define IDT_WIPE_MODE 1153 +#define IDC_PREF_CACHE_PIM 1154 +#define IDC_BOOT_LOADER_CACHE_PIM 1155 +#define IDC_SHOW_DISCONNECTED_NETWORK_DRIVES 1156 +#define IDT_VOLUME_ID 1157 +#define IDC_FAVORITE_VOLUME_ID 1158 +#define IDC_FAVORITE_USE_VOLUME_ID 1159 +#define IDC_DISABLE_BOOT_LOADER_PIM_PROMPT 1160 +#define IDC_HIDE_WAITING_DIALOG 1161 +#define IDM_HELP 40001 +#define IDM_ABOUT 40002 +#define IDM_UNMOUNT_VOLUME 40003 +#define IDM_CLEAR_HISTORY 40004 +#define IDM_BENCHMARK 40005 +#define IDM_TRAVELER 40006 +#define IDM_MOUNT_VOLUME_OPTIONS 40007 +#define IDM_FAQ 40008 +#define IDM_REFRESH_DRIVE_LETTERS 40009 +#define IDM_DEFAULT_KEYFILES 40010 +#define IDM_WEBSITE 40011 +#define IDM_MOUNTALL 40012 +#define IDM_UNMOUNTALL 40013 +#define IDM_MOUNT_VOLUME 40014 +#define IDM_CHANGE_PASSWORD 40015 +#define IDM_VOLUME_WIZARD 40016 +#define IDM_CREATE_VOLUME 40017 +#define IDM_WIPE_CACHE 40018 +#define IDM_PREFERENCES 40019 +#define IDM_LICENSE 40020 +#define IDM_SELECT_FILE 40021 +#define IDM_SELECT_DEVICE 40022 +#define IDM_VOLUME_PROPERTIES 40023 +#define IDM_LANGUAGE 40024 +#define IDM_MOUNT_FAVORITE_VOLUMES 40025 +#define IDM_BACKUP_VOL_HEADER 40026 +#define IDM_RESTORE_VOL_HEADER 40027 +#define IDM_HOTKEY_SETTINGS 40028 +#define IDM_TC_DOWNLOADS 40029 +#define IDM_NEWS 40030 +#define IDM_CONTACT 40031 +#define IDM_VERSION_HISTORY 40032 +#define IDM_HOMEPAGE 40033 +#define IDM_TEST_VECTORS 40034 +#define IDM_ADD_REMOVE_VOL_KEYFILES 40035 +#define IDM_REMOVE_ALL_KEYFILES_FROM_VOL 40036 +#define IDM_CHANGE_HEADER_KEY_DERIV_ALGO 40037 +#define IDM_KEYFILE_GENERATOR 40038 +#define IDM_ONLINE_TUTORIAL 40039 +#define IDM_ONLINE_HELP 40040 +#define IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO 40041 +#define IDM_CHANGE_SYS_PASSWORD 40042 +#define IDM_CREATE_RESCUE_DISK 40043 +#define IDM_PERMANENTLY_DECRYPT_SYS 40044 +#define IDM_VERIFY_RESCUE_DISK 40045 +#define IDM_SYSTEM_ENCRYPTION_STATUS 40046 +#define IDM_ENCRYPT_SYSTEM_DEVICE 40047 +#define IDM_SYSENC_RESUME 40048 +#define IDM_MOUNT_SYSENC_PART_WITHOUT_PBA 40049 +#define IDM_CREATE_HIDDEN_OS 40050 +#define IDM_TOKEN_PREFERENCES 40051 +#define IDM_CLOSE_ALL_TOKEN_SESSIONS 40052 +#define IDM_SYS_ENC_SETTINGS 40053 +#define IDM_SYSENC_SETTINGS 40054 +#define IDM_RESUME_INTERRUPTED_PROC 40055 +#define IDM_MANAGE_TOKEN_KEYFILES 40056 +#define IDM_SYS_FAVORITES_SETTINGS 40057 +#define IDM_ORGANIZE_FAVORITES 40058 +#define IDM_ORGANIZE_SYSTEM_FAVORITES 40059 +#define IDM_ADD_VOLUME_TO_FAVORITES 40060 +#define IDM_ADD_VOLUME_TO_SYSTEM_FAVORITES 40061 +#define IDM_PERFORMANCE_SETTINGS 40062 +#define IDM_ANALYZE_SYSTEM_CRASH 40063 +#define IDM_DONATE 40064 +#define IDM_VOLUME_EXPANDER 40065 +#define IDM_DEFAULT_MOUNT_PARAMETERS 40066 +#define IDM_DECRYPT_NONSYS_VOL 40067 +#define IDM_VERIFY_RESCUE_DISK_ISO 40068 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NO_MFC 1 +#define _APS_NEXT_RESOURCE_VALUE 119 +#define _APS_NEXT_COMMAND_VALUE 40069 +#define _APS_NEXT_CONTROL_VALUE 1162 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/src/PKCS11/cryptoki.h b/src/PKCS11/cryptoki.h index 7d85ca80..f457b3e9 100644 --- a/src/PKCS11/cryptoki.h +++ b/src/PKCS11/cryptoki.h @@ -1,66 +1,66 @@ -/* cryptoki.h include file for PKCS #11. */ -/* $Revision: 1.4 $ */ - -/* License to copy and use this software is granted provided that it is - * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface - * (Cryptoki)" in all material mentioning or referencing this software. - - * License is also granted to make and use derivative works provided that - * such works are identified as "derived from the RSA Security Inc. PKCS #11 - * Cryptographic Token Interface (Cryptoki)" in all material mentioning or - * referencing the derived work. - - * RSA Security Inc. makes no representations concerning either the - * merchantability of this software or the suitability of this software for - * any particular purpose. It is provided "as is" without express or implied - * warranty of any kind. - */ - -/* This is a sample file containing the top level include directives - * for building Win32 Cryptoki libraries and applications. - */ - -#ifndef ___CRYPTOKI_H_INC___ -#define ___CRYPTOKI_H_INC___ - -#pragma pack(push, cryptoki, 1) - -/* Specifies that the function is a DLL entry point. */ -#define CK_IMPORT_SPEC __declspec(dllimport) - -/* Define CRYPTOKI_EXPORTS during the build of cryptoki libraries. Do - * not define it in applications. - */ -#ifdef CRYPTOKI_EXPORTS -/* Specified that the function is an exported DLL entry point. */ -#define CK_EXPORT_SPEC __declspec(dllexport) -#else -#define CK_EXPORT_SPEC CK_IMPORT_SPEC -#endif - -/* Ensures the calling convention for Win32 builds */ -#define CK_CALL_SPEC __cdecl - -#define CK_PTR * - -#define CK_DEFINE_FUNCTION(returnType, name) \ - returnType CK_EXPORT_SPEC CK_CALL_SPEC name - -#define CK_DECLARE_FUNCTION(returnType, name) \ - returnType CK_EXPORT_SPEC CK_CALL_SPEC name - -#define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ - returnType CK_IMPORT_SPEC (CK_CALL_SPEC CK_PTR name) - -#define CK_CALLBACK_FUNCTION(returnType, name) \ - returnType (CK_CALL_SPEC CK_PTR name) - -#ifndef NULL_PTR -#define NULL_PTR 0 -#endif - -#include "pkcs11.h" - -#pragma pack(pop, cryptoki) - -#endif /* ___CRYPTOKI_H_INC___ */ +/* cryptoki.h include file for PKCS #11. */ +/* $Revision: 1.4 $ */ + +/* License to copy and use this software is granted provided that it is + * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface + * (Cryptoki)" in all material mentioning or referencing this software. + + * License is also granted to make and use derivative works provided that + * such works are identified as "derived from the RSA Security Inc. PKCS #11 + * Cryptographic Token Interface (Cryptoki)" in all material mentioning or + * referencing the derived work. + + * RSA Security Inc. makes no representations concerning either the + * merchantability of this software or the suitability of this software for + * any particular purpose. It is provided "as is" without express or implied + * warranty of any kind. + */ + +/* This is a sample file containing the top level include directives + * for building Win32 Cryptoki libraries and applications. + */ + +#ifndef ___CRYPTOKI_H_INC___ +#define ___CRYPTOKI_H_INC___ + +#pragma pack(push, cryptoki, 1) + +/* Specifies that the function is a DLL entry point. */ +#define CK_IMPORT_SPEC __declspec(dllimport) + +/* Define CRYPTOKI_EXPORTS during the build of cryptoki libraries. Do + * not define it in applications. + */ +#ifdef CRYPTOKI_EXPORTS +/* Specified that the function is an exported DLL entry point. */ +#define CK_EXPORT_SPEC __declspec(dllexport) +#else +#define CK_EXPORT_SPEC CK_IMPORT_SPEC +#endif + +/* Ensures the calling convention for Win32 builds */ +#define CK_CALL_SPEC __cdecl + +#define CK_PTR * + +#define CK_DEFINE_FUNCTION(returnType, name) \ + returnType CK_EXPORT_SPEC CK_CALL_SPEC name + +#define CK_DECLARE_FUNCTION(returnType, name) \ + returnType CK_EXPORT_SPEC CK_CALL_SPEC name + +#define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ + returnType CK_IMPORT_SPEC (CK_CALL_SPEC CK_PTR name) + +#define CK_CALLBACK_FUNCTION(returnType, name) \ + returnType (CK_CALL_SPEC CK_PTR name) + +#ifndef NULL_PTR +#define NULL_PTR 0 +#endif + +#include "pkcs11.h" + +#pragma pack(pop, cryptoki) + +#endif /* ___CRYPTOKI_H_INC___ */ diff --git a/src/PKCS11/pkcs11.h b/src/PKCS11/pkcs11.h index 5afbb7ac..6c612204 100644 --- a/src/PKCS11/pkcs11.h +++ b/src/PKCS11/pkcs11.h @@ -1,299 +1,299 @@ -/* pkcs11.h include file for PKCS #11. */ -/* $Revision: 1.4 $ */ - -/* License to copy and use this software is granted provided that it is - * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface - * (Cryptoki)" in all material mentioning or referencing this software. - - * License is also granted to make and use derivative works provided that - * such works are identified as "derived from the RSA Security Inc. PKCS #11 - * Cryptographic Token Interface (Cryptoki)" in all material mentioning or - * referencing the derived work. - - * RSA Security Inc. makes no representations concerning either the - * merchantability of this software or the suitability of this software for - * any particular purpose. It is provided "as is" without express or implied - * warranty of any kind. - */ - -#ifndef _PKCS11_H_ -#define _PKCS11_H_ 1 - -#ifdef __cplusplus -extern "C" { -#endif - -/* Before including this file (pkcs11.h) (or pkcs11t.h by - * itself), 6 platform-specific macros must be defined. These - * macros are described below, and typical definitions for them - * are also given. Be advised that these definitions can depend - * on both the platform and the compiler used (and possibly also - * on whether a Cryptoki library is linked statically or - * dynamically). - * - * In addition to defining these 6 macros, the packing convention - * for Cryptoki structures should be set. The Cryptoki - * convention on packing is that structures should be 1-byte - * aligned. - * - * If you're using Microsoft Developer Studio 5.0 to produce - * Win32 stuff, this might be done by using the following - * preprocessor directive before including pkcs11.h or pkcs11t.h: - * - * #pragma pack(push, cryptoki, 1) - * - * and using the following preprocessor directive after including - * pkcs11.h or pkcs11t.h: - * - * #pragma pack(pop, cryptoki) - * - * If you're using an earlier version of Microsoft Developer - * Studio to produce Win16 stuff, this might be done by using - * the following preprocessor directive before including - * pkcs11.h or pkcs11t.h: - * - * #pragma pack(1) - * - * In a UNIX environment, you're on your own for this. You might - * not need to do (or be able to do!) anything. - * - * - * Now for the macros: - * - * - * 1. CK_PTR: The indirection string for making a pointer to an - * object. It can be used like this: - * - * typedef CK_BYTE CK_PTR CK_BYTE_PTR; - * - * If you're using Microsoft Developer Studio 5.0 to produce - * Win32 stuff, it might be defined by: - * - * #define CK_PTR * - * - * If you're using an earlier version of Microsoft Developer - * Studio to produce Win16 stuff, it might be defined by: - * - * #define CK_PTR far * - * - * In a typical UNIX environment, it might be defined by: - * - * #define CK_PTR * - * - * - * 2. CK_DEFINE_FUNCTION(returnType, name): A macro which makes - * an exportable Cryptoki library function definition out of a - * return type and a function name. It should be used in the - * following fashion to define the exposed Cryptoki functions in - * a Cryptoki library: - * - * CK_DEFINE_FUNCTION(CK_RV, C_Initialize)( - * CK_VOID_PTR pReserved - * ) - * { - * ... - * } - * - * If you're using Microsoft Developer Studio 5.0 to define a - * function in a Win32 Cryptoki .dll, it might be defined by: - * - * #define CK_DEFINE_FUNCTION(returnType, name) \ - * returnType __declspec(dllexport) name - * - * If you're using an earlier version of Microsoft Developer - * Studio to define a function in a Win16 Cryptoki .dll, it - * might be defined by: - * - * #define CK_DEFINE_FUNCTION(returnType, name) \ - * returnType __export _far _pascal name - * - * In a UNIX environment, it might be defined by: - * - * #define CK_DEFINE_FUNCTION(returnType, name) \ - * returnType name - * - * - * 3. CK_DECLARE_FUNCTION(returnType, name): A macro which makes - * an importable Cryptoki library function declaration out of a - * return type and a function name. It should be used in the - * following fashion: - * - * extern CK_DECLARE_FUNCTION(CK_RV, C_Initialize)( - * CK_VOID_PTR pReserved - * ); - * - * If you're using Microsoft Developer Studio 5.0 to declare a - * function in a Win32 Cryptoki .dll, it might be defined by: - * - * #define CK_DECLARE_FUNCTION(returnType, name) \ - * returnType __declspec(dllimport) name - * - * If you're using an earlier version of Microsoft Developer - * Studio to declare a function in a Win16 Cryptoki .dll, it - * might be defined by: - * - * #define CK_DECLARE_FUNCTION(returnType, name) \ - * returnType __export _far _pascal name - * - * In a UNIX environment, it might be defined by: - * - * #define CK_DECLARE_FUNCTION(returnType, name) \ - * returnType name - * - * - * 4. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro - * which makes a Cryptoki API function pointer declaration or - * function pointer type declaration out of a return type and a - * function name. It should be used in the following fashion: - * - * // Define funcPtr to be a pointer to a Cryptoki API function - * // taking arguments args and returning CK_RV. - * CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtr)(args); - * - * or - * - * // Define funcPtrType to be the type of a pointer to a - * // Cryptoki API function taking arguments args and returning - * // CK_RV, and then define funcPtr to be a variable of type - * // funcPtrType. - * typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtrType)(args); - * funcPtrType funcPtr; - * - * If you're using Microsoft Developer Studio 5.0 to access - * functions in a Win32 Cryptoki .dll, in might be defined by: - * - * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ - * returnType __declspec(dllimport) (* name) - * - * If you're using an earlier version of Microsoft Developer - * Studio to access functions in a Win16 Cryptoki .dll, it might - * be defined by: - * - * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ - * returnType __export _far _pascal (* name) - * - * In a UNIX environment, it might be defined by: - * - * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ - * returnType (* name) - * - * - * 5. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes - * a function pointer type for an application callback out of - * a return type for the callback and a name for the callback. - * It should be used in the following fashion: - * - * CK_CALLBACK_FUNCTION(CK_RV, myCallback)(args); - * - * to declare a function pointer, myCallback, to a callback - * which takes arguments args and returns a CK_RV. It can also - * be used like this: - * - * typedef CK_CALLBACK_FUNCTION(CK_RV, myCallbackType)(args); - * myCallbackType myCallback; - * - * If you're using Microsoft Developer Studio 5.0 to do Win32 - * Cryptoki development, it might be defined by: - * - * #define CK_CALLBACK_FUNCTION(returnType, name) \ - * returnType (* name) - * - * If you're using an earlier version of Microsoft Developer - * Studio to do Win16 development, it might be defined by: - * - * #define CK_CALLBACK_FUNCTION(returnType, name) \ - * returnType _far _pascal (* name) - * - * In a UNIX environment, it might be defined by: - * - * #define CK_CALLBACK_FUNCTION(returnType, name) \ - * returnType (* name) - * - * - * 6. NULL_PTR: This macro is the value of a NULL pointer. - * - * In any ANSI/ISO C environment (and in many others as well), - * this should best be defined by - * - * #ifndef NULL_PTR - * #define NULL_PTR 0 - * #endif - */ - - -/* All the various Cryptoki types and #define'd values are in the - * file pkcs11t.h. */ -#include "pkcs11t.h" - -#define __PASTE(x,y) x##y - - -/* ============================================================== - * Define the "extern" form of all the entry points. - * ============================================================== - */ - -#define CK_NEED_ARG_LIST 1 -#define CK_PKCS11_FUNCTION_INFO(name) \ - extern CK_DECLARE_FUNCTION(CK_RV, name) - -/* pkcs11f.h has all the information about the Cryptoki - * function prototypes. */ -#include "pkcs11f.h" - -#undef CK_NEED_ARG_LIST -#undef CK_PKCS11_FUNCTION_INFO - - -/* ============================================================== - * Define the typedef form of all the entry points. That is, for - * each Cryptoki function C_XXX, define a type CK_C_XXX which is - * a pointer to that kind of function. - * ============================================================== - */ - -#define CK_NEED_ARG_LIST 1 -#define CK_PKCS11_FUNCTION_INFO(name) \ - typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, __PASTE(CK_,name)) - -/* pkcs11f.h has all the information about the Cryptoki - * function prototypes. */ -#include "pkcs11f.h" - -#undef CK_NEED_ARG_LIST -#undef CK_PKCS11_FUNCTION_INFO - - -/* ============================================================== - * Define structed vector of entry points. A CK_FUNCTION_LIST - * contains a CK_VERSION indicating a library's Cryptoki version - * and then a whole slew of function pointers to the routines in - * the library. This type was declared, but not defined, in - * pkcs11t.h. - * ============================================================== - */ - -#define CK_PKCS11_FUNCTION_INFO(name) \ - __PASTE(CK_,name) name; - -struct CK_FUNCTION_LIST { - - CK_VERSION version; /* Cryptoki version */ - -/* Pile all the function pointers into the CK_FUNCTION_LIST. */ -/* pkcs11f.h has all the information about the Cryptoki - * function prototypes. */ -#include "pkcs11f.h" - -}; - -#undef CK_PKCS11_FUNCTION_INFO - - -#undef __PASTE - -#ifdef __cplusplus -} -#endif - -#endif +/* pkcs11.h include file for PKCS #11. */ +/* $Revision: 1.4 $ */ + +/* License to copy and use this software is granted provided that it is + * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface + * (Cryptoki)" in all material mentioning or referencing this software. + + * License is also granted to make and use derivative works provided that + * such works are identified as "derived from the RSA Security Inc. PKCS #11 + * Cryptographic Token Interface (Cryptoki)" in all material mentioning or + * referencing the derived work. + + * RSA Security Inc. makes no representations concerning either the + * merchantability of this software or the suitability of this software for + * any particular purpose. It is provided "as is" without express or implied + * warranty of any kind. + */ + +#ifndef _PKCS11_H_ +#define _PKCS11_H_ 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* Before including this file (pkcs11.h) (or pkcs11t.h by + * itself), 6 platform-specific macros must be defined. These + * macros are described below, and typical definitions for them + * are also given. Be advised that these definitions can depend + * on both the platform and the compiler used (and possibly also + * on whether a Cryptoki library is linked statically or + * dynamically). + * + * In addition to defining these 6 macros, the packing convention + * for Cryptoki structures should be set. The Cryptoki + * convention on packing is that structures should be 1-byte + * aligned. + * + * If you're using Microsoft Developer Studio 5.0 to produce + * Win32 stuff, this might be done by using the following + * preprocessor directive before including pkcs11.h or pkcs11t.h: + * + * #pragma pack(push, cryptoki, 1) + * + * and using the following preprocessor directive after including + * pkcs11.h or pkcs11t.h: + * + * #pragma pack(pop, cryptoki) + * + * If you're using an earlier version of Microsoft Developer + * Studio to produce Win16 stuff, this might be done by using + * the following preprocessor directive before including + * pkcs11.h or pkcs11t.h: + * + * #pragma pack(1) + * + * In a UNIX environment, you're on your own for this. You might + * not need to do (or be able to do!) anything. + * + * + * Now for the macros: + * + * + * 1. CK_PTR: The indirection string for making a pointer to an + * object. It can be used like this: + * + * typedef CK_BYTE CK_PTR CK_BYTE_PTR; + * + * If you're using Microsoft Developer Studio 5.0 to produce + * Win32 stuff, it might be defined by: + * + * #define CK_PTR * + * + * If you're using an earlier version of Microsoft Developer + * Studio to produce Win16 stuff, it might be defined by: + * + * #define CK_PTR far * + * + * In a typical UNIX environment, it might be defined by: + * + * #define CK_PTR * + * + * + * 2. CK_DEFINE_FUNCTION(returnType, name): A macro which makes + * an exportable Cryptoki library function definition out of a + * return type and a function name. It should be used in the + * following fashion to define the exposed Cryptoki functions in + * a Cryptoki library: + * + * CK_DEFINE_FUNCTION(CK_RV, C_Initialize)( + * CK_VOID_PTR pReserved + * ) + * { + * ... + * } + * + * If you're using Microsoft Developer Studio 5.0 to define a + * function in a Win32 Cryptoki .dll, it might be defined by: + * + * #define CK_DEFINE_FUNCTION(returnType, name) \ + * returnType __declspec(dllexport) name + * + * If you're using an earlier version of Microsoft Developer + * Studio to define a function in a Win16 Cryptoki .dll, it + * might be defined by: + * + * #define CK_DEFINE_FUNCTION(returnType, name) \ + * returnType __export _far _pascal name + * + * In a UNIX environment, it might be defined by: + * + * #define CK_DEFINE_FUNCTION(returnType, name) \ + * returnType name + * + * + * 3. CK_DECLARE_FUNCTION(returnType, name): A macro which makes + * an importable Cryptoki library function declaration out of a + * return type and a function name. It should be used in the + * following fashion: + * + * extern CK_DECLARE_FUNCTION(CK_RV, C_Initialize)( + * CK_VOID_PTR pReserved + * ); + * + * If you're using Microsoft Developer Studio 5.0 to declare a + * function in a Win32 Cryptoki .dll, it might be defined by: + * + * #define CK_DECLARE_FUNCTION(returnType, name) \ + * returnType __declspec(dllimport) name + * + * If you're using an earlier version of Microsoft Developer + * Studio to declare a function in a Win16 Cryptoki .dll, it + * might be defined by: + * + * #define CK_DECLARE_FUNCTION(returnType, name) \ + * returnType __export _far _pascal name + * + * In a UNIX environment, it might be defined by: + * + * #define CK_DECLARE_FUNCTION(returnType, name) \ + * returnType name + * + * + * 4. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro + * which makes a Cryptoki API function pointer declaration or + * function pointer type declaration out of a return type and a + * function name. It should be used in the following fashion: + * + * // Define funcPtr to be a pointer to a Cryptoki API function + * // taking arguments args and returning CK_RV. + * CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtr)(args); + * + * or + * + * // Define funcPtrType to be the type of a pointer to a + * // Cryptoki API function taking arguments args and returning + * // CK_RV, and then define funcPtr to be a variable of type + * // funcPtrType. + * typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtrType)(args); + * funcPtrType funcPtr; + * + * If you're using Microsoft Developer Studio 5.0 to access + * functions in a Win32 Cryptoki .dll, in might be defined by: + * + * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ + * returnType __declspec(dllimport) (* name) + * + * If you're using an earlier version of Microsoft Developer + * Studio to access functions in a Win16 Cryptoki .dll, it might + * be defined by: + * + * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ + * returnType __export _far _pascal (* name) + * + * In a UNIX environment, it might be defined by: + * + * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ + * returnType (* name) + * + * + * 5. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes + * a function pointer type for an application callback out of + * a return type for the callback and a name for the callback. + * It should be used in the following fashion: + * + * CK_CALLBACK_FUNCTION(CK_RV, myCallback)(args); + * + * to declare a function pointer, myCallback, to a callback + * which takes arguments args and returns a CK_RV. It can also + * be used like this: + * + * typedef CK_CALLBACK_FUNCTION(CK_RV, myCallbackType)(args); + * myCallbackType myCallback; + * + * If you're using Microsoft Developer Studio 5.0 to do Win32 + * Cryptoki development, it might be defined by: + * + * #define CK_CALLBACK_FUNCTION(returnType, name) \ + * returnType (* name) + * + * If you're using an earlier version of Microsoft Developer + * Studio to do Win16 development, it might be defined by: + * + * #define CK_CALLBACK_FUNCTION(returnType, name) \ + * returnType _far _pascal (* name) + * + * In a UNIX environment, it might be defined by: + * + * #define CK_CALLBACK_FUNCTION(returnType, name) \ + * returnType (* name) + * + * + * 6. NULL_PTR: This macro is the value of a NULL pointer. + * + * In any ANSI/ISO C environment (and in many others as well), + * this should best be defined by + * + * #ifndef NULL_PTR + * #define NULL_PTR 0 + * #endif + */ + + +/* All the various Cryptoki types and #define'd values are in the + * file pkcs11t.h. */ +#include "pkcs11t.h" + +#define __PASTE(x,y) x##y + + +/* ============================================================== + * Define the "extern" form of all the entry points. + * ============================================================== + */ + +#define CK_NEED_ARG_LIST 1 +#define CK_PKCS11_FUNCTION_INFO(name) \ + extern CK_DECLARE_FUNCTION(CK_RV, name) + +/* pkcs11f.h has all the information about the Cryptoki + * function prototypes. */ +#include "pkcs11f.h" + +#undef CK_NEED_ARG_LIST +#undef CK_PKCS11_FUNCTION_INFO + + +/* ============================================================== + * Define the typedef form of all the entry points. That is, for + * each Cryptoki function C_XXX, define a type CK_C_XXX which is + * a pointer to that kind of function. + * ============================================================== + */ + +#define CK_NEED_ARG_LIST 1 +#define CK_PKCS11_FUNCTION_INFO(name) \ + typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, __PASTE(CK_,name)) + +/* pkcs11f.h has all the information about the Cryptoki + * function prototypes. */ +#include "pkcs11f.h" + +#undef CK_NEED_ARG_LIST +#undef CK_PKCS11_FUNCTION_INFO + + +/* ============================================================== + * Define structed vector of entry points. A CK_FUNCTION_LIST + * contains a CK_VERSION indicating a library's Cryptoki version + * and then a whole slew of function pointers to the routines in + * the library. This type was declared, but not defined, in + * pkcs11t.h. + * ============================================================== + */ + +#define CK_PKCS11_FUNCTION_INFO(name) \ + __PASTE(CK_,name) name; + +struct CK_FUNCTION_LIST { + + CK_VERSION version; /* Cryptoki version */ + +/* Pile all the function pointers into the CK_FUNCTION_LIST. */ +/* pkcs11f.h has all the information about the Cryptoki + * function prototypes. */ +#include "pkcs11f.h" + +}; + +#undef CK_PKCS11_FUNCTION_INFO + + +#undef __PASTE + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/PKCS11/pkcs11f.h b/src/PKCS11/pkcs11f.h index 30097535..a479384e 100644 --- a/src/PKCS11/pkcs11f.h +++ b/src/PKCS11/pkcs11f.h @@ -1,912 +1,912 @@ -/* pkcs11f.h include file for PKCS #11. */ -/* $Revision: 1.4 $ */ - -/* License to copy and use this software is granted provided that it is - * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface - * (Cryptoki)" in all material mentioning or referencing this software. - - * License is also granted to make and use derivative works provided that - * such works are identified as "derived from the RSA Security Inc. PKCS #11 - * Cryptographic Token Interface (Cryptoki)" in all material mentioning or - * referencing the derived work. - - * RSA Security Inc. makes no representations concerning either the - * merchantability of this software or the suitability of this software for - * any particular purpose. It is provided "as is" without express or implied - * warranty of any kind. - */ - -/* This header file contains pretty much everything about all the */ -/* Cryptoki function prototypes. Because this information is */ -/* used for more than just declaring function prototypes, the */ -/* order of the functions appearing herein is important, and */ -/* should not be altered. */ - -/* General-purpose */ - -/* C_Initialize initializes the Cryptoki library. */ -CK_PKCS11_FUNCTION_INFO(C_Initialize) -#ifdef CK_NEED_ARG_LIST -( - CK_VOID_PTR pInitArgs /* if this is not NULL_PTR, it gets - * cast to CK_C_INITIALIZE_ARGS_PTR - * and dereferenced */ -); -#endif - - -/* C_Finalize indicates that an application is done with the - * Cryptoki library. */ -CK_PKCS11_FUNCTION_INFO(C_Finalize) -#ifdef CK_NEED_ARG_LIST -( - CK_VOID_PTR pReserved /* reserved. Should be NULL_PTR */ -); -#endif - - -/* C_GetInfo returns general information about Cryptoki. */ -CK_PKCS11_FUNCTION_INFO(C_GetInfo) -#ifdef CK_NEED_ARG_LIST -( - CK_INFO_PTR pInfo /* location that receives information */ -); -#endif - - -/* C_GetFunctionList returns the function list. */ -CK_PKCS11_FUNCTION_INFO(C_GetFunctionList) -#ifdef CK_NEED_ARG_LIST -( - CK_FUNCTION_LIST_PTR_PTR ppFunctionList /* receives pointer to - * function list */ -); -#endif - - - -/* Slot and token management */ - -/* C_GetSlotList obtains a list of slots in the system. */ -CK_PKCS11_FUNCTION_INFO(C_GetSlotList) -#ifdef CK_NEED_ARG_LIST -( - CK_BBOOL tokenPresent, /* only slots with tokens? */ - CK_SLOT_ID_PTR pSlotList, /* receives array of slot IDs */ - CK_ULONG_PTR pulCount /* receives number of slots */ -); -#endif - - -/* C_GetSlotInfo obtains information about a particular slot in - * the system. */ -CK_PKCS11_FUNCTION_INFO(C_GetSlotInfo) -#ifdef CK_NEED_ARG_LIST -( - CK_SLOT_ID slotID, /* the ID of the slot */ - CK_SLOT_INFO_PTR pInfo /* receives the slot information */ -); -#endif - - -/* C_GetTokenInfo obtains information about a particular token - * in the system. */ -CK_PKCS11_FUNCTION_INFO(C_GetTokenInfo) -#ifdef CK_NEED_ARG_LIST -( - CK_SLOT_ID slotID, /* ID of the token's slot */ - CK_TOKEN_INFO_PTR pInfo /* receives the token information */ -); -#endif - - -/* C_GetMechanismList obtains a list of mechanism types - * supported by a token. */ -CK_PKCS11_FUNCTION_INFO(C_GetMechanismList) -#ifdef CK_NEED_ARG_LIST -( - CK_SLOT_ID slotID, /* ID of token's slot */ - CK_MECHANISM_TYPE_PTR pMechanismList, /* gets mech. array */ - CK_ULONG_PTR pulCount /* gets # of mechs. */ -); -#endif - - -/* C_GetMechanismInfo obtains information about a particular - * mechanism possibly supported by a token. */ -CK_PKCS11_FUNCTION_INFO(C_GetMechanismInfo) -#ifdef CK_NEED_ARG_LIST -( - CK_SLOT_ID slotID, /* ID of the token's slot */ - CK_MECHANISM_TYPE type, /* type of mechanism */ - CK_MECHANISM_INFO_PTR pInfo /* receives mechanism info */ -); -#endif - - -/* C_InitToken initializes a token. */ -CK_PKCS11_FUNCTION_INFO(C_InitToken) -#ifdef CK_NEED_ARG_LIST -/* pLabel changed from CK_CHAR_PTR to CK_UTF8CHAR_PTR for v2.10 */ -( - CK_SLOT_ID slotID, /* ID of the token's slot */ - CK_UTF8CHAR_PTR pPin, /* the SO's initial PIN */ - CK_ULONG ulPinLen, /* length in bytes of the PIN */ - CK_UTF8CHAR_PTR pLabel /* 32-byte token label (blank padded) */ -); -#endif - - -/* C_InitPIN initializes the normal user's PIN. */ -CK_PKCS11_FUNCTION_INFO(C_InitPIN) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_UTF8CHAR_PTR pPin, /* the normal user's PIN */ - CK_ULONG ulPinLen /* length in bytes of the PIN */ -); -#endif - - -/* C_SetPIN modifies the PIN of the user who is logged in. */ -CK_PKCS11_FUNCTION_INFO(C_SetPIN) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_UTF8CHAR_PTR pOldPin, /* the old PIN */ - CK_ULONG ulOldLen, /* length of the old PIN */ - CK_UTF8CHAR_PTR pNewPin, /* the new PIN */ - CK_ULONG ulNewLen /* length of the new PIN */ -); -#endif - - - -/* Session management */ - -/* C_OpenSession opens a session between an application and a - * token. */ -CK_PKCS11_FUNCTION_INFO(C_OpenSession) -#ifdef CK_NEED_ARG_LIST -( - CK_SLOT_ID slotID, /* the slot's ID */ - CK_FLAGS flags, /* from CK_SESSION_INFO */ - CK_VOID_PTR pApplication, /* passed to callback */ - CK_NOTIFY Notify, /* callback function */ - CK_SESSION_HANDLE_PTR phSession /* gets session handle */ -); -#endif - - -/* C_CloseSession closes a session between an application and a - * token. */ -CK_PKCS11_FUNCTION_INFO(C_CloseSession) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession /* the session's handle */ -); -#endif - - -/* C_CloseAllSessions closes all sessions with a token. */ -CK_PKCS11_FUNCTION_INFO(C_CloseAllSessions) -#ifdef CK_NEED_ARG_LIST -( - CK_SLOT_ID slotID /* the token's slot */ -); -#endif - - -/* C_GetSessionInfo obtains information about the session. */ -CK_PKCS11_FUNCTION_INFO(C_GetSessionInfo) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_SESSION_INFO_PTR pInfo /* receives session info */ -); -#endif - - -/* C_GetOperationState obtains the state of the cryptographic operation - * in a session. */ -CK_PKCS11_FUNCTION_INFO(C_GetOperationState) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pOperationState, /* gets state */ - CK_ULONG_PTR pulOperationStateLen /* gets state length */ -); -#endif - - -/* C_SetOperationState restores the state of the cryptographic - * operation in a session. */ -CK_PKCS11_FUNCTION_INFO(C_SetOperationState) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pOperationState, /* holds state */ - CK_ULONG ulOperationStateLen, /* holds state length */ - CK_OBJECT_HANDLE hEncryptionKey, /* en/decryption key */ - CK_OBJECT_HANDLE hAuthenticationKey /* sign/verify key */ -); -#endif - - -/* C_Login logs a user into a token. */ -CK_PKCS11_FUNCTION_INFO(C_Login) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_USER_TYPE userType, /* the user type */ - CK_UTF8CHAR_PTR pPin, /* the user's PIN */ - CK_ULONG ulPinLen /* the length of the PIN */ -); -#endif - - -/* C_Logout logs a user out from a token. */ -CK_PKCS11_FUNCTION_INFO(C_Logout) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession /* the session's handle */ -); -#endif - - - -/* Object management */ - -/* C_CreateObject creates a new object. */ -CK_PKCS11_FUNCTION_INFO(C_CreateObject) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_ATTRIBUTE_PTR pTemplate, /* the object's template */ - CK_ULONG ulCount, /* attributes in template */ - CK_OBJECT_HANDLE_PTR phObject /* gets new object's handle. */ -); -#endif - - -/* C_CopyObject copies an object, creating a new object for the - * copy. */ -CK_PKCS11_FUNCTION_INFO(C_CopyObject) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_OBJECT_HANDLE hObject, /* the object's handle */ - CK_ATTRIBUTE_PTR pTemplate, /* template for new object */ - CK_ULONG ulCount, /* attributes in template */ - CK_OBJECT_HANDLE_PTR phNewObject /* receives handle of copy */ -); -#endif - - -/* C_DestroyObject destroys an object. */ -CK_PKCS11_FUNCTION_INFO(C_DestroyObject) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_OBJECT_HANDLE hObject /* the object's handle */ -); -#endif - - -/* C_GetObjectSize gets the size of an object in bytes. */ -CK_PKCS11_FUNCTION_INFO(C_GetObjectSize) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_OBJECT_HANDLE hObject, /* the object's handle */ - CK_ULONG_PTR pulSize /* receives size of object */ -); -#endif - - -/* C_GetAttributeValue obtains the value of one or more object - * attributes. */ -CK_PKCS11_FUNCTION_INFO(C_GetAttributeValue) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_OBJECT_HANDLE hObject, /* the object's handle */ - CK_ATTRIBUTE_PTR pTemplate, /* specifies attrs; gets vals */ - CK_ULONG ulCount /* attributes in template */ -); -#endif - - -/* C_SetAttributeValue modifies the value of one or more object - * attributes */ -CK_PKCS11_FUNCTION_INFO(C_SetAttributeValue) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_OBJECT_HANDLE hObject, /* the object's handle */ - CK_ATTRIBUTE_PTR pTemplate, /* specifies attrs and values */ - CK_ULONG ulCount /* attributes in template */ -); -#endif - - -/* C_FindObjectsInit initializes a search for token and session - * objects that match a template. */ -CK_PKCS11_FUNCTION_INFO(C_FindObjectsInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_ATTRIBUTE_PTR pTemplate, /* attribute values to match */ - CK_ULONG ulCount /* attrs in search template */ -); -#endif - - -/* C_FindObjects continues a search for token and session - * objects that match a template, obtaining additional object - * handles. */ -CK_PKCS11_FUNCTION_INFO(C_FindObjects) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_OBJECT_HANDLE_PTR phObject, /* gets obj. handles */ - CK_ULONG ulMaxObjectCount, /* max handles to get */ - CK_ULONG_PTR pulObjectCount /* actual # returned */ -); -#endif - - -/* C_FindObjectsFinal finishes a search for token and session - * objects. */ -CK_PKCS11_FUNCTION_INFO(C_FindObjectsFinal) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession /* the session's handle */ -); -#endif - - - -/* Encryption and decryption */ - -/* C_EncryptInit initializes an encryption operation. */ -CK_PKCS11_FUNCTION_INFO(C_EncryptInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the encryption mechanism */ - CK_OBJECT_HANDLE hKey /* handle of encryption key */ -); -#endif - - -/* C_Encrypt encrypts single-part data. */ -CK_PKCS11_FUNCTION_INFO(C_Encrypt) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pData, /* the plaintext data */ - CK_ULONG ulDataLen, /* bytes of plaintext */ - CK_BYTE_PTR pEncryptedData, /* gets ciphertext */ - CK_ULONG_PTR pulEncryptedDataLen /* gets c-text size */ -); -#endif - - -/* C_EncryptUpdate continues a multiple-part encryption - * operation. */ -CK_PKCS11_FUNCTION_INFO(C_EncryptUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pPart, /* the plaintext data */ - CK_ULONG ulPartLen, /* plaintext data len */ - CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */ - CK_ULONG_PTR pulEncryptedPartLen /* gets c-text size */ -); -#endif - - -/* C_EncryptFinal finishes a multiple-part encryption - * operation. */ -CK_PKCS11_FUNCTION_INFO(C_EncryptFinal) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session handle */ - CK_BYTE_PTR pLastEncryptedPart, /* last c-text */ - CK_ULONG_PTR pulLastEncryptedPartLen /* gets last size */ -); -#endif - - -/* C_DecryptInit initializes a decryption operation. */ -CK_PKCS11_FUNCTION_INFO(C_DecryptInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the decryption mechanism */ - CK_OBJECT_HANDLE hKey /* handle of decryption key */ -); -#endif - - -/* C_Decrypt decrypts encrypted data in a single part. */ -CK_PKCS11_FUNCTION_INFO(C_Decrypt) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pEncryptedData, /* ciphertext */ - CK_ULONG ulEncryptedDataLen, /* ciphertext length */ - CK_BYTE_PTR pData, /* gets plaintext */ - CK_ULONG_PTR pulDataLen /* gets p-text size */ -); -#endif - - -/* C_DecryptUpdate continues a multiple-part decryption - * operation. */ -CK_PKCS11_FUNCTION_INFO(C_DecryptUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pEncryptedPart, /* encrypted data */ - CK_ULONG ulEncryptedPartLen, /* input length */ - CK_BYTE_PTR pPart, /* gets plaintext */ - CK_ULONG_PTR pulPartLen /* p-text size */ -); -#endif - - -/* C_DecryptFinal finishes a multiple-part decryption - * operation. */ -CK_PKCS11_FUNCTION_INFO(C_DecryptFinal) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pLastPart, /* gets plaintext */ - CK_ULONG_PTR pulLastPartLen /* p-text size */ -); -#endif - - - -/* Message digesting */ - -/* C_DigestInit initializes a message-digesting operation. */ -CK_PKCS11_FUNCTION_INFO(C_DigestInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism /* the digesting mechanism */ -); -#endif - - -/* C_Digest digests data in a single part. */ -CK_PKCS11_FUNCTION_INFO(C_Digest) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pData, /* data to be digested */ - CK_ULONG ulDataLen, /* bytes of data to digest */ - CK_BYTE_PTR pDigest, /* gets the message digest */ - CK_ULONG_PTR pulDigestLen /* gets digest length */ -); -#endif - - -/* C_DigestUpdate continues a multiple-part message-digesting - * operation. */ -CK_PKCS11_FUNCTION_INFO(C_DigestUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pPart, /* data to be digested */ - CK_ULONG ulPartLen /* bytes of data to be digested */ -); -#endif - - -/* C_DigestKey continues a multi-part message-digesting - * operation, by digesting the value of a secret key as part of - * the data already digested. */ -CK_PKCS11_FUNCTION_INFO(C_DigestKey) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_OBJECT_HANDLE hKey /* secret key to digest */ -); -#endif - - -/* C_DigestFinal finishes a multiple-part message-digesting - * operation. */ -CK_PKCS11_FUNCTION_INFO(C_DigestFinal) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pDigest, /* gets the message digest */ - CK_ULONG_PTR pulDigestLen /* gets byte count of digest */ -); -#endif - - - -/* Signing and MACing */ - -/* C_SignInit initializes a signature (private key encryption) - * operation, where the signature is (will be) an appendix to - * the data, and plaintext cannot be recovered from the - *signature. */ -CK_PKCS11_FUNCTION_INFO(C_SignInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the signature mechanism */ - CK_OBJECT_HANDLE hKey /* handle of signature key */ -); -#endif - - -/* C_Sign signs (encrypts with private key) data in a single - * part, where the signature is (will be) an appendix to the - * data, and plaintext cannot be recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_Sign) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pData, /* the data to sign */ - CK_ULONG ulDataLen, /* count of bytes to sign */ - CK_BYTE_PTR pSignature, /* gets the signature */ - CK_ULONG_PTR pulSignatureLen /* gets signature length */ -); -#endif - - -/* C_SignUpdate continues a multiple-part signature operation, - * where the signature is (will be) an appendix to the data, - * and plaintext cannot be recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_SignUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pPart, /* the data to sign */ - CK_ULONG ulPartLen /* count of bytes to sign */ -); -#endif - - -/* C_SignFinal finishes a multiple-part signature operation, - * returning the signature. */ -CK_PKCS11_FUNCTION_INFO(C_SignFinal) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pSignature, /* gets the signature */ - CK_ULONG_PTR pulSignatureLen /* gets signature length */ -); -#endif - - -/* C_SignRecoverInit initializes a signature operation, where - * the data can be recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_SignRecoverInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the signature mechanism */ - CK_OBJECT_HANDLE hKey /* handle of the signature key */ -); -#endif - - -/* C_SignRecover signs data in a single operation, where the - * data can be recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_SignRecover) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pData, /* the data to sign */ - CK_ULONG ulDataLen, /* count of bytes to sign */ - CK_BYTE_PTR pSignature, /* gets the signature */ - CK_ULONG_PTR pulSignatureLen /* gets signature length */ -); -#endif - - - -/* Verifying signatures and MACs */ - -/* C_VerifyInit initializes a verification operation, where the - * signature is an appendix to the data, and plaintext cannot - * cannot be recovered from the signature (e.g. DSA). */ -CK_PKCS11_FUNCTION_INFO(C_VerifyInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the verification mechanism */ - CK_OBJECT_HANDLE hKey /* verification key */ -); -#endif - - -/* C_Verify verifies a signature in a single-part operation, - * where the signature is an appendix to the data, and plaintext - * cannot be recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_Verify) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pData, /* signed data */ - CK_ULONG ulDataLen, /* length of signed data */ - CK_BYTE_PTR pSignature, /* signature */ - CK_ULONG ulSignatureLen /* signature length*/ -); -#endif - - -/* C_VerifyUpdate continues a multiple-part verification - * operation, where the signature is an appendix to the data, - * and plaintext cannot be recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_VerifyUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pPart, /* signed data */ - CK_ULONG ulPartLen /* length of signed data */ -); -#endif - - -/* C_VerifyFinal finishes a multiple-part verification - * operation, checking the signature. */ -CK_PKCS11_FUNCTION_INFO(C_VerifyFinal) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pSignature, /* signature to verify */ - CK_ULONG ulSignatureLen /* signature length */ -); -#endif - - -/* C_VerifyRecoverInit initializes a signature verification - * operation, where the data is recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_VerifyRecoverInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the verification mechanism */ - CK_OBJECT_HANDLE hKey /* verification key */ -); -#endif - - -/* C_VerifyRecover verifies a signature in a single-part - * operation, where the data is recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_VerifyRecover) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pSignature, /* signature to verify */ - CK_ULONG ulSignatureLen, /* signature length */ - CK_BYTE_PTR pData, /* gets signed data */ - CK_ULONG_PTR pulDataLen /* gets signed data len */ -); -#endif - - - -/* Dual-function cryptographic operations */ - -/* C_DigestEncryptUpdate continues a multiple-part digesting - * and encryption operation. */ -CK_PKCS11_FUNCTION_INFO(C_DigestEncryptUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pPart, /* the plaintext data */ - CK_ULONG ulPartLen, /* plaintext length */ - CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */ - CK_ULONG_PTR pulEncryptedPartLen /* gets c-text length */ -); -#endif - - -/* C_DecryptDigestUpdate continues a multiple-part decryption and - * digesting operation. */ -CK_PKCS11_FUNCTION_INFO(C_DecryptDigestUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pEncryptedPart, /* ciphertext */ - CK_ULONG ulEncryptedPartLen, /* ciphertext length */ - CK_BYTE_PTR pPart, /* gets plaintext */ - CK_ULONG_PTR pulPartLen /* gets plaintext len */ -); -#endif - - -/* C_SignEncryptUpdate continues a multiple-part signing and - * encryption operation. */ -CK_PKCS11_FUNCTION_INFO(C_SignEncryptUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pPart, /* the plaintext data */ - CK_ULONG ulPartLen, /* plaintext length */ - CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */ - CK_ULONG_PTR pulEncryptedPartLen /* gets c-text length */ -); -#endif - - -/* C_DecryptVerifyUpdate continues a multiple-part decryption and - * verify operation. */ -CK_PKCS11_FUNCTION_INFO(C_DecryptVerifyUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pEncryptedPart, /* ciphertext */ - CK_ULONG ulEncryptedPartLen, /* ciphertext length */ - CK_BYTE_PTR pPart, /* gets plaintext */ - CK_ULONG_PTR pulPartLen /* gets p-text length */ -); -#endif - - - -/* Key management */ - -/* C_GenerateKey generates a secret key, creating a new key - * object. */ -CK_PKCS11_FUNCTION_INFO(C_GenerateKey) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* key generation mech. */ - CK_ATTRIBUTE_PTR pTemplate, /* template for new key */ - CK_ULONG ulCount, /* # of attrs in template */ - CK_OBJECT_HANDLE_PTR phKey /* gets handle of new key */ -); -#endif - - -/* C_GenerateKeyPair generates a public-key/private-key pair, - * creating new key objects. */ -CK_PKCS11_FUNCTION_INFO(C_GenerateKeyPair) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session - * handle */ - CK_MECHANISM_PTR pMechanism, /* key-gen - * mech. */ - CK_ATTRIBUTE_PTR pPublicKeyTemplate, /* template - * for pub. - * key */ - CK_ULONG ulPublicKeyAttributeCount, /* # pub. - * attrs. */ - CK_ATTRIBUTE_PTR pPrivateKeyTemplate, /* template - * for priv. - * key */ - CK_ULONG ulPrivateKeyAttributeCount, /* # priv. - * attrs. */ - CK_OBJECT_HANDLE_PTR phPublicKey, /* gets pub. - * key - * handle */ - CK_OBJECT_HANDLE_PTR phPrivateKey /* gets - * priv. key - * handle */ -); -#endif - - -/* C_WrapKey wraps (i.e., encrypts) a key. */ -CK_PKCS11_FUNCTION_INFO(C_WrapKey) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the wrapping mechanism */ - CK_OBJECT_HANDLE hWrappingKey, /* wrapping key */ - CK_OBJECT_HANDLE hKey, /* key to be wrapped */ - CK_BYTE_PTR pWrappedKey, /* gets wrapped key */ - CK_ULONG_PTR pulWrappedKeyLen /* gets wrapped key size */ -); -#endif - - -/* C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new - * key object. */ -CK_PKCS11_FUNCTION_INFO(C_UnwrapKey) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_MECHANISM_PTR pMechanism, /* unwrapping mech. */ - CK_OBJECT_HANDLE hUnwrappingKey, /* unwrapping key */ - CK_BYTE_PTR pWrappedKey, /* the wrapped key */ - CK_ULONG ulWrappedKeyLen, /* wrapped key len */ - CK_ATTRIBUTE_PTR pTemplate, /* new key template */ - CK_ULONG ulAttributeCount, /* template length */ - CK_OBJECT_HANDLE_PTR phKey /* gets new handle */ -); -#endif - - -/* C_DeriveKey derives a key from a base key, creating a new key - * object. */ -CK_PKCS11_FUNCTION_INFO(C_DeriveKey) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_MECHANISM_PTR pMechanism, /* key deriv. mech. */ - CK_OBJECT_HANDLE hBaseKey, /* base key */ - CK_ATTRIBUTE_PTR pTemplate, /* new key template */ - CK_ULONG ulAttributeCount, /* template length */ - CK_OBJECT_HANDLE_PTR phKey /* gets new handle */ -); -#endif - - - -/* Random number generation */ - -/* C_SeedRandom mixes additional seed material into the token's - * random number generator. */ -CK_PKCS11_FUNCTION_INFO(C_SeedRandom) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pSeed, /* the seed material */ - CK_ULONG ulSeedLen /* length of seed material */ -); -#endif - - -/* C_GenerateRandom generates random data. */ -CK_PKCS11_FUNCTION_INFO(C_GenerateRandom) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR RandomData, /* receives the random data */ - CK_ULONG ulRandomLen /* # of bytes to generate */ -); -#endif - - - -/* Parallel function management */ - -/* C_GetFunctionStatus is a legacy function; it obtains an - * updated status of a function running in parallel with an - * application. */ -CK_PKCS11_FUNCTION_INFO(C_GetFunctionStatus) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession /* the session's handle */ -); -#endif - - -/* C_CancelFunction is a legacy function; it cancels a function - * running in parallel. */ -CK_PKCS11_FUNCTION_INFO(C_CancelFunction) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession /* the session's handle */ -); -#endif - - - -/* Functions added in for Cryptoki Version 2.01 or later */ - -/* C_WaitForSlotEvent waits for a slot event (token insertion, - * removal, etc.) to occur. */ -CK_PKCS11_FUNCTION_INFO(C_WaitForSlotEvent) -#ifdef CK_NEED_ARG_LIST -( - CK_FLAGS flags, /* blocking/nonblocking flag */ - CK_SLOT_ID_PTR pSlot, /* location that receives the slot ID */ - CK_VOID_PTR pRserved /* reserved. Should be NULL_PTR */ -); -#endif +/* pkcs11f.h include file for PKCS #11. */ +/* $Revision: 1.4 $ */ + +/* License to copy and use this software is granted provided that it is + * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface + * (Cryptoki)" in all material mentioning or referencing this software. + + * License is also granted to make and use derivative works provided that + * such works are identified as "derived from the RSA Security Inc. PKCS #11 + * Cryptographic Token Interface (Cryptoki)" in all material mentioning or + * referencing the derived work. + + * RSA Security Inc. makes no representations concerning either the + * merchantability of this software or the suitability of this software for + * any particular purpose. It is provided "as is" without express or implied + * warranty of any kind. + */ + +/* This header file contains pretty much everything about all the */ +/* Cryptoki function prototypes. Because this information is */ +/* used for more than just declaring function prototypes, the */ +/* order of the functions appearing herein is important, and */ +/* should not be altered. */ + +/* General-purpose */ + +/* C_Initialize initializes the Cryptoki library. */ +CK_PKCS11_FUNCTION_INFO(C_Initialize) +#ifdef CK_NEED_ARG_LIST +( + CK_VOID_PTR pInitArgs /* if this is not NULL_PTR, it gets + * cast to CK_C_INITIALIZE_ARGS_PTR + * and dereferenced */ +); +#endif + + +/* C_Finalize indicates that an application is done with the + * Cryptoki library. */ +CK_PKCS11_FUNCTION_INFO(C_Finalize) +#ifdef CK_NEED_ARG_LIST +( + CK_VOID_PTR pReserved /* reserved. Should be NULL_PTR */ +); +#endif + + +/* C_GetInfo returns general information about Cryptoki. */ +CK_PKCS11_FUNCTION_INFO(C_GetInfo) +#ifdef CK_NEED_ARG_LIST +( + CK_INFO_PTR pInfo /* location that receives information */ +); +#endif + + +/* C_GetFunctionList returns the function list. */ +CK_PKCS11_FUNCTION_INFO(C_GetFunctionList) +#ifdef CK_NEED_ARG_LIST +( + CK_FUNCTION_LIST_PTR_PTR ppFunctionList /* receives pointer to + * function list */ +); +#endif + + + +/* Slot and token management */ + +/* C_GetSlotList obtains a list of slots in the system. */ +CK_PKCS11_FUNCTION_INFO(C_GetSlotList) +#ifdef CK_NEED_ARG_LIST +( + CK_BBOOL tokenPresent, /* only slots with tokens? */ + CK_SLOT_ID_PTR pSlotList, /* receives array of slot IDs */ + CK_ULONG_PTR pulCount /* receives number of slots */ +); +#endif + + +/* C_GetSlotInfo obtains information about a particular slot in + * the system. */ +CK_PKCS11_FUNCTION_INFO(C_GetSlotInfo) +#ifdef CK_NEED_ARG_LIST +( + CK_SLOT_ID slotID, /* the ID of the slot */ + CK_SLOT_INFO_PTR pInfo /* receives the slot information */ +); +#endif + + +/* C_GetTokenInfo obtains information about a particular token + * in the system. */ +CK_PKCS11_FUNCTION_INFO(C_GetTokenInfo) +#ifdef CK_NEED_ARG_LIST +( + CK_SLOT_ID slotID, /* ID of the token's slot */ + CK_TOKEN_INFO_PTR pInfo /* receives the token information */ +); +#endif + + +/* C_GetMechanismList obtains a list of mechanism types + * supported by a token. */ +CK_PKCS11_FUNCTION_INFO(C_GetMechanismList) +#ifdef CK_NEED_ARG_LIST +( + CK_SLOT_ID slotID, /* ID of token's slot */ + CK_MECHANISM_TYPE_PTR pMechanismList, /* gets mech. array */ + CK_ULONG_PTR pulCount /* gets # of mechs. */ +); +#endif + + +/* C_GetMechanismInfo obtains information about a particular + * mechanism possibly supported by a token. */ +CK_PKCS11_FUNCTION_INFO(C_GetMechanismInfo) +#ifdef CK_NEED_ARG_LIST +( + CK_SLOT_ID slotID, /* ID of the token's slot */ + CK_MECHANISM_TYPE type, /* type of mechanism */ + CK_MECHANISM_INFO_PTR pInfo /* receives mechanism info */ +); +#endif + + +/* C_InitToken initializes a token. */ +CK_PKCS11_FUNCTION_INFO(C_InitToken) +#ifdef CK_NEED_ARG_LIST +/* pLabel changed from CK_CHAR_PTR to CK_UTF8CHAR_PTR for v2.10 */ +( + CK_SLOT_ID slotID, /* ID of the token's slot */ + CK_UTF8CHAR_PTR pPin, /* the SO's initial PIN */ + CK_ULONG ulPinLen, /* length in bytes of the PIN */ + CK_UTF8CHAR_PTR pLabel /* 32-byte token label (blank padded) */ +); +#endif + + +/* C_InitPIN initializes the normal user's PIN. */ +CK_PKCS11_FUNCTION_INFO(C_InitPIN) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_UTF8CHAR_PTR pPin, /* the normal user's PIN */ + CK_ULONG ulPinLen /* length in bytes of the PIN */ +); +#endif + + +/* C_SetPIN modifies the PIN of the user who is logged in. */ +CK_PKCS11_FUNCTION_INFO(C_SetPIN) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_UTF8CHAR_PTR pOldPin, /* the old PIN */ + CK_ULONG ulOldLen, /* length of the old PIN */ + CK_UTF8CHAR_PTR pNewPin, /* the new PIN */ + CK_ULONG ulNewLen /* length of the new PIN */ +); +#endif + + + +/* Session management */ + +/* C_OpenSession opens a session between an application and a + * token. */ +CK_PKCS11_FUNCTION_INFO(C_OpenSession) +#ifdef CK_NEED_ARG_LIST +( + CK_SLOT_ID slotID, /* the slot's ID */ + CK_FLAGS flags, /* from CK_SESSION_INFO */ + CK_VOID_PTR pApplication, /* passed to callback */ + CK_NOTIFY Notify, /* callback function */ + CK_SESSION_HANDLE_PTR phSession /* gets session handle */ +); +#endif + + +/* C_CloseSession closes a session between an application and a + * token. */ +CK_PKCS11_FUNCTION_INFO(C_CloseSession) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession /* the session's handle */ +); +#endif + + +/* C_CloseAllSessions closes all sessions with a token. */ +CK_PKCS11_FUNCTION_INFO(C_CloseAllSessions) +#ifdef CK_NEED_ARG_LIST +( + CK_SLOT_ID slotID /* the token's slot */ +); +#endif + + +/* C_GetSessionInfo obtains information about the session. */ +CK_PKCS11_FUNCTION_INFO(C_GetSessionInfo) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_SESSION_INFO_PTR pInfo /* receives session info */ +); +#endif + + +/* C_GetOperationState obtains the state of the cryptographic operation + * in a session. */ +CK_PKCS11_FUNCTION_INFO(C_GetOperationState) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_BYTE_PTR pOperationState, /* gets state */ + CK_ULONG_PTR pulOperationStateLen /* gets state length */ +); +#endif + + +/* C_SetOperationState restores the state of the cryptographic + * operation in a session. */ +CK_PKCS11_FUNCTION_INFO(C_SetOperationState) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_BYTE_PTR pOperationState, /* holds state */ + CK_ULONG ulOperationStateLen, /* holds state length */ + CK_OBJECT_HANDLE hEncryptionKey, /* en/decryption key */ + CK_OBJECT_HANDLE hAuthenticationKey /* sign/verify key */ +); +#endif + + +/* C_Login logs a user into a token. */ +CK_PKCS11_FUNCTION_INFO(C_Login) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_USER_TYPE userType, /* the user type */ + CK_UTF8CHAR_PTR pPin, /* the user's PIN */ + CK_ULONG ulPinLen /* the length of the PIN */ +); +#endif + + +/* C_Logout logs a user out from a token. */ +CK_PKCS11_FUNCTION_INFO(C_Logout) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession /* the session's handle */ +); +#endif + + + +/* Object management */ + +/* C_CreateObject creates a new object. */ +CK_PKCS11_FUNCTION_INFO(C_CreateObject) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_ATTRIBUTE_PTR pTemplate, /* the object's template */ + CK_ULONG ulCount, /* attributes in template */ + CK_OBJECT_HANDLE_PTR phObject /* gets new object's handle. */ +); +#endif + + +/* C_CopyObject copies an object, creating a new object for the + * copy. */ +CK_PKCS11_FUNCTION_INFO(C_CopyObject) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_OBJECT_HANDLE hObject, /* the object's handle */ + CK_ATTRIBUTE_PTR pTemplate, /* template for new object */ + CK_ULONG ulCount, /* attributes in template */ + CK_OBJECT_HANDLE_PTR phNewObject /* receives handle of copy */ +); +#endif + + +/* C_DestroyObject destroys an object. */ +CK_PKCS11_FUNCTION_INFO(C_DestroyObject) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_OBJECT_HANDLE hObject /* the object's handle */ +); +#endif + + +/* C_GetObjectSize gets the size of an object in bytes. */ +CK_PKCS11_FUNCTION_INFO(C_GetObjectSize) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_OBJECT_HANDLE hObject, /* the object's handle */ + CK_ULONG_PTR pulSize /* receives size of object */ +); +#endif + + +/* C_GetAttributeValue obtains the value of one or more object + * attributes. */ +CK_PKCS11_FUNCTION_INFO(C_GetAttributeValue) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_OBJECT_HANDLE hObject, /* the object's handle */ + CK_ATTRIBUTE_PTR pTemplate, /* specifies attrs; gets vals */ + CK_ULONG ulCount /* attributes in template */ +); +#endif + + +/* C_SetAttributeValue modifies the value of one or more object + * attributes */ +CK_PKCS11_FUNCTION_INFO(C_SetAttributeValue) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_OBJECT_HANDLE hObject, /* the object's handle */ + CK_ATTRIBUTE_PTR pTemplate, /* specifies attrs and values */ + CK_ULONG ulCount /* attributes in template */ +); +#endif + + +/* C_FindObjectsInit initializes a search for token and session + * objects that match a template. */ +CK_PKCS11_FUNCTION_INFO(C_FindObjectsInit) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_ATTRIBUTE_PTR pTemplate, /* attribute values to match */ + CK_ULONG ulCount /* attrs in search template */ +); +#endif + + +/* C_FindObjects continues a search for token and session + * objects that match a template, obtaining additional object + * handles. */ +CK_PKCS11_FUNCTION_INFO(C_FindObjects) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_OBJECT_HANDLE_PTR phObject, /* gets obj. handles */ + CK_ULONG ulMaxObjectCount, /* max handles to get */ + CK_ULONG_PTR pulObjectCount /* actual # returned */ +); +#endif + + +/* C_FindObjectsFinal finishes a search for token and session + * objects. */ +CK_PKCS11_FUNCTION_INFO(C_FindObjectsFinal) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession /* the session's handle */ +); +#endif + + + +/* Encryption and decryption */ + +/* C_EncryptInit initializes an encryption operation. */ +CK_PKCS11_FUNCTION_INFO(C_EncryptInit) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_MECHANISM_PTR pMechanism, /* the encryption mechanism */ + CK_OBJECT_HANDLE hKey /* handle of encryption key */ +); +#endif + + +/* C_Encrypt encrypts single-part data. */ +CK_PKCS11_FUNCTION_INFO(C_Encrypt) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_BYTE_PTR pData, /* the plaintext data */ + CK_ULONG ulDataLen, /* bytes of plaintext */ + CK_BYTE_PTR pEncryptedData, /* gets ciphertext */ + CK_ULONG_PTR pulEncryptedDataLen /* gets c-text size */ +); +#endif + + +/* C_EncryptUpdate continues a multiple-part encryption + * operation. */ +CK_PKCS11_FUNCTION_INFO(C_EncryptUpdate) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_BYTE_PTR pPart, /* the plaintext data */ + CK_ULONG ulPartLen, /* plaintext data len */ + CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */ + CK_ULONG_PTR pulEncryptedPartLen /* gets c-text size */ +); +#endif + + +/* C_EncryptFinal finishes a multiple-part encryption + * operation. */ +CK_PKCS11_FUNCTION_INFO(C_EncryptFinal) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session handle */ + CK_BYTE_PTR pLastEncryptedPart, /* last c-text */ + CK_ULONG_PTR pulLastEncryptedPartLen /* gets last size */ +); +#endif + + +/* C_DecryptInit initializes a decryption operation. */ +CK_PKCS11_FUNCTION_INFO(C_DecryptInit) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_MECHANISM_PTR pMechanism, /* the decryption mechanism */ + CK_OBJECT_HANDLE hKey /* handle of decryption key */ +); +#endif + + +/* C_Decrypt decrypts encrypted data in a single part. */ +CK_PKCS11_FUNCTION_INFO(C_Decrypt) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_BYTE_PTR pEncryptedData, /* ciphertext */ + CK_ULONG ulEncryptedDataLen, /* ciphertext length */ + CK_BYTE_PTR pData, /* gets plaintext */ + CK_ULONG_PTR pulDataLen /* gets p-text size */ +); +#endif + + +/* C_DecryptUpdate continues a multiple-part decryption + * operation. */ +CK_PKCS11_FUNCTION_INFO(C_DecryptUpdate) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_BYTE_PTR pEncryptedPart, /* encrypted data */ + CK_ULONG ulEncryptedPartLen, /* input length */ + CK_BYTE_PTR pPart, /* gets plaintext */ + CK_ULONG_PTR pulPartLen /* p-text size */ +); +#endif + + +/* C_DecryptFinal finishes a multiple-part decryption + * operation. */ +CK_PKCS11_FUNCTION_INFO(C_DecryptFinal) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pLastPart, /* gets plaintext */ + CK_ULONG_PTR pulLastPartLen /* p-text size */ +); +#endif + + + +/* Message digesting */ + +/* C_DigestInit initializes a message-digesting operation. */ +CK_PKCS11_FUNCTION_INFO(C_DigestInit) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_MECHANISM_PTR pMechanism /* the digesting mechanism */ +); +#endif + + +/* C_Digest digests data in a single part. */ +CK_PKCS11_FUNCTION_INFO(C_Digest) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pData, /* data to be digested */ + CK_ULONG ulDataLen, /* bytes of data to digest */ + CK_BYTE_PTR pDigest, /* gets the message digest */ + CK_ULONG_PTR pulDigestLen /* gets digest length */ +); +#endif + + +/* C_DigestUpdate continues a multiple-part message-digesting + * operation. */ +CK_PKCS11_FUNCTION_INFO(C_DigestUpdate) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pPart, /* data to be digested */ + CK_ULONG ulPartLen /* bytes of data to be digested */ +); +#endif + + +/* C_DigestKey continues a multi-part message-digesting + * operation, by digesting the value of a secret key as part of + * the data already digested. */ +CK_PKCS11_FUNCTION_INFO(C_DigestKey) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_OBJECT_HANDLE hKey /* secret key to digest */ +); +#endif + + +/* C_DigestFinal finishes a multiple-part message-digesting + * operation. */ +CK_PKCS11_FUNCTION_INFO(C_DigestFinal) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pDigest, /* gets the message digest */ + CK_ULONG_PTR pulDigestLen /* gets byte count of digest */ +); +#endif + + + +/* Signing and MACing */ + +/* C_SignInit initializes a signature (private key encryption) + * operation, where the signature is (will be) an appendix to + * the data, and plaintext cannot be recovered from the + *signature. */ +CK_PKCS11_FUNCTION_INFO(C_SignInit) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_MECHANISM_PTR pMechanism, /* the signature mechanism */ + CK_OBJECT_HANDLE hKey /* handle of signature key */ +); +#endif + + +/* C_Sign signs (encrypts with private key) data in a single + * part, where the signature is (will be) an appendix to the + * data, and plaintext cannot be recovered from the signature. */ +CK_PKCS11_FUNCTION_INFO(C_Sign) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pData, /* the data to sign */ + CK_ULONG ulDataLen, /* count of bytes to sign */ + CK_BYTE_PTR pSignature, /* gets the signature */ + CK_ULONG_PTR pulSignatureLen /* gets signature length */ +); +#endif + + +/* C_SignUpdate continues a multiple-part signature operation, + * where the signature is (will be) an appendix to the data, + * and plaintext cannot be recovered from the signature. */ +CK_PKCS11_FUNCTION_INFO(C_SignUpdate) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pPart, /* the data to sign */ + CK_ULONG ulPartLen /* count of bytes to sign */ +); +#endif + + +/* C_SignFinal finishes a multiple-part signature operation, + * returning the signature. */ +CK_PKCS11_FUNCTION_INFO(C_SignFinal) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pSignature, /* gets the signature */ + CK_ULONG_PTR pulSignatureLen /* gets signature length */ +); +#endif + + +/* C_SignRecoverInit initializes a signature operation, where + * the data can be recovered from the signature. */ +CK_PKCS11_FUNCTION_INFO(C_SignRecoverInit) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_MECHANISM_PTR pMechanism, /* the signature mechanism */ + CK_OBJECT_HANDLE hKey /* handle of the signature key */ +); +#endif + + +/* C_SignRecover signs data in a single operation, where the + * data can be recovered from the signature. */ +CK_PKCS11_FUNCTION_INFO(C_SignRecover) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pData, /* the data to sign */ + CK_ULONG ulDataLen, /* count of bytes to sign */ + CK_BYTE_PTR pSignature, /* gets the signature */ + CK_ULONG_PTR pulSignatureLen /* gets signature length */ +); +#endif + + + +/* Verifying signatures and MACs */ + +/* C_VerifyInit initializes a verification operation, where the + * signature is an appendix to the data, and plaintext cannot + * cannot be recovered from the signature (e.g. DSA). */ +CK_PKCS11_FUNCTION_INFO(C_VerifyInit) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_MECHANISM_PTR pMechanism, /* the verification mechanism */ + CK_OBJECT_HANDLE hKey /* verification key */ +); +#endif + + +/* C_Verify verifies a signature in a single-part operation, + * where the signature is an appendix to the data, and plaintext + * cannot be recovered from the signature. */ +CK_PKCS11_FUNCTION_INFO(C_Verify) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pData, /* signed data */ + CK_ULONG ulDataLen, /* length of signed data */ + CK_BYTE_PTR pSignature, /* signature */ + CK_ULONG ulSignatureLen /* signature length*/ +); +#endif + + +/* C_VerifyUpdate continues a multiple-part verification + * operation, where the signature is an appendix to the data, + * and plaintext cannot be recovered from the signature. */ +CK_PKCS11_FUNCTION_INFO(C_VerifyUpdate) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pPart, /* signed data */ + CK_ULONG ulPartLen /* length of signed data */ +); +#endif + + +/* C_VerifyFinal finishes a multiple-part verification + * operation, checking the signature. */ +CK_PKCS11_FUNCTION_INFO(C_VerifyFinal) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pSignature, /* signature to verify */ + CK_ULONG ulSignatureLen /* signature length */ +); +#endif + + +/* C_VerifyRecoverInit initializes a signature verification + * operation, where the data is recovered from the signature. */ +CK_PKCS11_FUNCTION_INFO(C_VerifyRecoverInit) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_MECHANISM_PTR pMechanism, /* the verification mechanism */ + CK_OBJECT_HANDLE hKey /* verification key */ +); +#endif + + +/* C_VerifyRecover verifies a signature in a single-part + * operation, where the data is recovered from the signature. */ +CK_PKCS11_FUNCTION_INFO(C_VerifyRecover) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pSignature, /* signature to verify */ + CK_ULONG ulSignatureLen, /* signature length */ + CK_BYTE_PTR pData, /* gets signed data */ + CK_ULONG_PTR pulDataLen /* gets signed data len */ +); +#endif + + + +/* Dual-function cryptographic operations */ + +/* C_DigestEncryptUpdate continues a multiple-part digesting + * and encryption operation. */ +CK_PKCS11_FUNCTION_INFO(C_DigestEncryptUpdate) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_BYTE_PTR pPart, /* the plaintext data */ + CK_ULONG ulPartLen, /* plaintext length */ + CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */ + CK_ULONG_PTR pulEncryptedPartLen /* gets c-text length */ +); +#endif + + +/* C_DecryptDigestUpdate continues a multiple-part decryption and + * digesting operation. */ +CK_PKCS11_FUNCTION_INFO(C_DecryptDigestUpdate) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_BYTE_PTR pEncryptedPart, /* ciphertext */ + CK_ULONG ulEncryptedPartLen, /* ciphertext length */ + CK_BYTE_PTR pPart, /* gets plaintext */ + CK_ULONG_PTR pulPartLen /* gets plaintext len */ +); +#endif + + +/* C_SignEncryptUpdate continues a multiple-part signing and + * encryption operation. */ +CK_PKCS11_FUNCTION_INFO(C_SignEncryptUpdate) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_BYTE_PTR pPart, /* the plaintext data */ + CK_ULONG ulPartLen, /* plaintext length */ + CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */ + CK_ULONG_PTR pulEncryptedPartLen /* gets c-text length */ +); +#endif + + +/* C_DecryptVerifyUpdate continues a multiple-part decryption and + * verify operation. */ +CK_PKCS11_FUNCTION_INFO(C_DecryptVerifyUpdate) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_BYTE_PTR pEncryptedPart, /* ciphertext */ + CK_ULONG ulEncryptedPartLen, /* ciphertext length */ + CK_BYTE_PTR pPart, /* gets plaintext */ + CK_ULONG_PTR pulPartLen /* gets p-text length */ +); +#endif + + + +/* Key management */ + +/* C_GenerateKey generates a secret key, creating a new key + * object. */ +CK_PKCS11_FUNCTION_INFO(C_GenerateKey) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_MECHANISM_PTR pMechanism, /* key generation mech. */ + CK_ATTRIBUTE_PTR pTemplate, /* template for new key */ + CK_ULONG ulCount, /* # of attrs in template */ + CK_OBJECT_HANDLE_PTR phKey /* gets handle of new key */ +); +#endif + + +/* C_GenerateKeyPair generates a public-key/private-key pair, + * creating new key objects. */ +CK_PKCS11_FUNCTION_INFO(C_GenerateKeyPair) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session + * handle */ + CK_MECHANISM_PTR pMechanism, /* key-gen + * mech. */ + CK_ATTRIBUTE_PTR pPublicKeyTemplate, /* template + * for pub. + * key */ + CK_ULONG ulPublicKeyAttributeCount, /* # pub. + * attrs. */ + CK_ATTRIBUTE_PTR pPrivateKeyTemplate, /* template + * for priv. + * key */ + CK_ULONG ulPrivateKeyAttributeCount, /* # priv. + * attrs. */ + CK_OBJECT_HANDLE_PTR phPublicKey, /* gets pub. + * key + * handle */ + CK_OBJECT_HANDLE_PTR phPrivateKey /* gets + * priv. key + * handle */ +); +#endif + + +/* C_WrapKey wraps (i.e., encrypts) a key. */ +CK_PKCS11_FUNCTION_INFO(C_WrapKey) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_MECHANISM_PTR pMechanism, /* the wrapping mechanism */ + CK_OBJECT_HANDLE hWrappingKey, /* wrapping key */ + CK_OBJECT_HANDLE hKey, /* key to be wrapped */ + CK_BYTE_PTR pWrappedKey, /* gets wrapped key */ + CK_ULONG_PTR pulWrappedKeyLen /* gets wrapped key size */ +); +#endif + + +/* C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new + * key object. */ +CK_PKCS11_FUNCTION_INFO(C_UnwrapKey) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_MECHANISM_PTR pMechanism, /* unwrapping mech. */ + CK_OBJECT_HANDLE hUnwrappingKey, /* unwrapping key */ + CK_BYTE_PTR pWrappedKey, /* the wrapped key */ + CK_ULONG ulWrappedKeyLen, /* wrapped key len */ + CK_ATTRIBUTE_PTR pTemplate, /* new key template */ + CK_ULONG ulAttributeCount, /* template length */ + CK_OBJECT_HANDLE_PTR phKey /* gets new handle */ +); +#endif + + +/* C_DeriveKey derives a key from a base key, creating a new key + * object. */ +CK_PKCS11_FUNCTION_INFO(C_DeriveKey) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* session's handle */ + CK_MECHANISM_PTR pMechanism, /* key deriv. mech. */ + CK_OBJECT_HANDLE hBaseKey, /* base key */ + CK_ATTRIBUTE_PTR pTemplate, /* new key template */ + CK_ULONG ulAttributeCount, /* template length */ + CK_OBJECT_HANDLE_PTR phKey /* gets new handle */ +); +#endif + + + +/* Random number generation */ + +/* C_SeedRandom mixes additional seed material into the token's + * random number generator. */ +CK_PKCS11_FUNCTION_INFO(C_SeedRandom) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR pSeed, /* the seed material */ + CK_ULONG ulSeedLen /* length of seed material */ +); +#endif + + +/* C_GenerateRandom generates random data. */ +CK_PKCS11_FUNCTION_INFO(C_GenerateRandom) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_BYTE_PTR RandomData, /* receives the random data */ + CK_ULONG ulRandomLen /* # of bytes to generate */ +); +#endif + + + +/* Parallel function management */ + +/* C_GetFunctionStatus is a legacy function; it obtains an + * updated status of a function running in parallel with an + * application. */ +CK_PKCS11_FUNCTION_INFO(C_GetFunctionStatus) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession /* the session's handle */ +); +#endif + + +/* C_CancelFunction is a legacy function; it cancels a function + * running in parallel. */ +CK_PKCS11_FUNCTION_INFO(C_CancelFunction) +#ifdef CK_NEED_ARG_LIST +( + CK_SESSION_HANDLE hSession /* the session's handle */ +); +#endif + + + +/* Functions added in for Cryptoki Version 2.01 or later */ + +/* C_WaitForSlotEvent waits for a slot event (token insertion, + * removal, etc.) to occur. */ +CK_PKCS11_FUNCTION_INFO(C_WaitForSlotEvent) +#ifdef CK_NEED_ARG_LIST +( + CK_FLAGS flags, /* blocking/nonblocking flag */ + CK_SLOT_ID_PTR pSlot, /* location that receives the slot ID */ + CK_VOID_PTR pRserved /* reserved. Should be NULL_PTR */ +); +#endif diff --git a/src/PKCS11/pkcs11t.h b/src/PKCS11/pkcs11t.h index ff6b4e70..4c9d938d 100644 --- a/src/PKCS11/pkcs11t.h +++ b/src/PKCS11/pkcs11t.h @@ -1,1885 +1,1885 @@ -/* pkcs11t.h include file for PKCS #11. */ -/* $Revision: 1.10 $ */ - -/* License to copy and use this software is granted provided that it is - * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface - * (Cryptoki)" in all material mentioning or referencing this software. - - * License is also granted to make and use derivative works provided that - * such works are identified as "derived from the RSA Security Inc. PKCS #11 - * Cryptographic Token Interface (Cryptoki)" in all material mentioning or - * referencing the derived work. - - * RSA Security Inc. makes no representations concerning either the - * merchantability of this software or the suitability of this software for - * any particular purpose. It is provided "as is" without express or implied - * warranty of any kind. - */ - -/* See top of pkcs11.h for information about the macros that - * must be defined and the structure-packing conventions that - * must be set before including this file. */ - -#ifndef _PKCS11T_H_ -#define _PKCS11T_H_ 1 - -#define CRYPTOKI_VERSION_MAJOR 2 -#define CRYPTOKI_VERSION_MINOR 20 -#define CRYPTOKI_VERSION_AMENDMENT 3 - -#define CK_TRUE 1 -#define CK_FALSE 0 - -#ifndef CK_DISABLE_TRUE_FALSE -#ifndef FALSE -#define FALSE CK_FALSE -#endif - -#ifndef TRUE -#define TRUE CK_TRUE -#endif -#endif - -/* an unsigned 8-bit value */ -typedef unsigned char CK_BYTE; - -/* an unsigned 8-bit character */ -typedef CK_BYTE CK_CHAR; - -/* an 8-bit UTF-8 character */ -typedef CK_BYTE CK_UTF8CHAR; - -/* a BYTE-sized Boolean flag */ -typedef CK_BYTE CK_BBOOL; - -/* an unsigned value, at least 32 bits long */ -typedef unsigned long int CK_ULONG; - -/* a signed value, the same size as a CK_ULONG */ -/* CK_LONG is new for v2.0 */ -typedef long int CK_LONG; - -/* at least 32 bits; each bit is a Boolean flag */ -typedef CK_ULONG CK_FLAGS; - - -/* some special values for certain CK_ULONG variables */ -#define CK_UNAVAILABLE_INFORMATION (~0UL) -#define CK_EFFECTIVELY_INFINITE 0 - - -typedef CK_BYTE CK_PTR CK_BYTE_PTR; -typedef CK_CHAR CK_PTR CK_CHAR_PTR; -typedef CK_UTF8CHAR CK_PTR CK_UTF8CHAR_PTR; -typedef CK_ULONG CK_PTR CK_ULONG_PTR; -typedef void CK_PTR CK_VOID_PTR; - -/* Pointer to a CK_VOID_PTR-- i.e., pointer to pointer to void */ -typedef CK_VOID_PTR CK_PTR CK_VOID_PTR_PTR; - - -/* The following value is always invalid if used as a session */ -/* handle or object handle */ -#define CK_INVALID_HANDLE 0 - - -typedef struct CK_VERSION { - CK_BYTE major; /* integer portion of version number */ - CK_BYTE minor; /* 1/100ths portion of version number */ -} CK_VERSION; - -typedef CK_VERSION CK_PTR CK_VERSION_PTR; - - -typedef struct CK_INFO { - /* manufacturerID and libraryDecription have been changed from - * CK_CHAR to CK_UTF8CHAR for v2.10 */ - CK_VERSION cryptokiVersion; /* Cryptoki interface ver */ - CK_UTF8CHAR manufacturerID[32]; /* blank padded */ - CK_FLAGS flags; /* must be zero */ - - /* libraryDescription and libraryVersion are new for v2.0 */ - CK_UTF8CHAR libraryDescription[32]; /* blank padded */ - CK_VERSION libraryVersion; /* version of library */ -} CK_INFO; - -typedef CK_INFO CK_PTR CK_INFO_PTR; - - -/* CK_NOTIFICATION enumerates the types of notifications that - * Cryptoki provides to an application */ -/* CK_NOTIFICATION has been changed from an enum to a CK_ULONG - * for v2.0 */ -typedef CK_ULONG CK_NOTIFICATION; -#define CKN_SURRENDER 0 - -/* The following notification is new for PKCS #11 v2.20 amendment 3 */ -#define CKN_OTP_CHANGED 1 - - -typedef CK_ULONG CK_SLOT_ID; - -typedef CK_SLOT_ID CK_PTR CK_SLOT_ID_PTR; - - -/* CK_SLOT_INFO provides information about a slot */ -typedef struct CK_SLOT_INFO { - /* slotDescription and manufacturerID have been changed from - * CK_CHAR to CK_UTF8CHAR for v2.10 */ - CK_UTF8CHAR slotDescription[64]; /* blank padded */ - CK_UTF8CHAR manufacturerID[32]; /* blank padded */ - CK_FLAGS flags; - - /* hardwareVersion and firmwareVersion are new for v2.0 */ - CK_VERSION hardwareVersion; /* version of hardware */ - CK_VERSION firmwareVersion; /* version of firmware */ -} CK_SLOT_INFO; - -/* flags: bit flags that provide capabilities of the slot - * Bit Flag Mask Meaning - */ -#define CKF_TOKEN_PRESENT 0x00000001 /* a token is there */ -#define CKF_REMOVABLE_DEVICE 0x00000002 /* removable devices*/ -#define CKF_HW_SLOT 0x00000004 /* hardware slot */ - -typedef CK_SLOT_INFO CK_PTR CK_SLOT_INFO_PTR; - - -/* CK_TOKEN_INFO provides information about a token */ -typedef struct CK_TOKEN_INFO { - /* label, manufacturerID, and model have been changed from - * CK_CHAR to CK_UTF8CHAR for v2.10 */ - CK_UTF8CHAR label[32]; /* blank padded */ - CK_UTF8CHAR manufacturerID[32]; /* blank padded */ - CK_UTF8CHAR model[16]; /* blank padded */ - CK_CHAR serialNumber[16]; /* blank padded */ - CK_FLAGS flags; /* see below */ - - /* ulMaxSessionCount, ulSessionCount, ulMaxRwSessionCount, - * ulRwSessionCount, ulMaxPinLen, and ulMinPinLen have all been - * changed from CK_USHORT to CK_ULONG for v2.0 */ - CK_ULONG ulMaxSessionCount; /* max open sessions */ - CK_ULONG ulSessionCount; /* sess. now open */ - CK_ULONG ulMaxRwSessionCount; /* max R/W sessions */ - CK_ULONG ulRwSessionCount; /* R/W sess. now open */ - CK_ULONG ulMaxPinLen; /* in bytes */ - CK_ULONG ulMinPinLen; /* in bytes */ - CK_ULONG ulTotalPublicMemory; /* in bytes */ - CK_ULONG ulFreePublicMemory; /* in bytes */ - CK_ULONG ulTotalPrivateMemory; /* in bytes */ - CK_ULONG ulFreePrivateMemory; /* in bytes */ - - /* hardwareVersion, firmwareVersion, and time are new for - * v2.0 */ - CK_VERSION hardwareVersion; /* version of hardware */ - CK_VERSION firmwareVersion; /* version of firmware */ - CK_CHAR utcTime[16]; /* time */ -} CK_TOKEN_INFO; - -/* The flags parameter is defined as follows: - * Bit Flag Mask Meaning - */ -#define CKF_RNG 0x00000001 /* has random # - * generator */ -#define CKF_WRITE_PROTECTED 0x00000002 /* token is - * write- - * protected */ -#define CKF_LOGIN_REQUIRED 0x00000004 /* user must - * login */ -#define CKF_USER_PIN_INITIALIZED 0x00000008 /* normal user's - * PIN is set */ - -/* CKF_RESTORE_KEY_NOT_NEEDED is new for v2.0. If it is set, - * that means that *every* time the state of cryptographic - * operations of a session is successfully saved, all keys - * needed to continue those operations are stored in the state */ -#define CKF_RESTORE_KEY_NOT_NEEDED 0x00000020 - -/* CKF_CLOCK_ON_TOKEN is new for v2.0. If it is set, that means - * that the token has some sort of clock. The time on that - * clock is returned in the token info structure */ -#define CKF_CLOCK_ON_TOKEN 0x00000040 - -/* CKF_PROTECTED_AUTHENTICATION_PATH is new for v2.0. If it is - * set, that means that there is some way for the user to login - * without sending a PIN through the Cryptoki library itself */ -#define CKF_PROTECTED_AUTHENTICATION_PATH 0x00000100 - -/* CKF_DUAL_CRYPTO_OPERATIONS is new for v2.0. If it is true, - * that means that a single session with the token can perform - * dual simultaneous cryptographic operations (digest and - * encrypt; decrypt and digest; sign and encrypt; and decrypt - * and sign) */ -#define CKF_DUAL_CRYPTO_OPERATIONS 0x00000200 - -/* CKF_TOKEN_INITIALIZED if new for v2.10. If it is true, the - * token has been initialized using C_InitializeToken or an - * equivalent mechanism outside the scope of PKCS #11. - * Calling C_InitializeToken when this flag is set will cause - * the token to be reinitialized. */ -#define CKF_TOKEN_INITIALIZED 0x00000400 - -/* CKF_SECONDARY_AUTHENTICATION if new for v2.10. If it is - * true, the token supports secondary authentication for - * private key objects. This flag is deprecated in v2.11 and - onwards. */ -#define CKF_SECONDARY_AUTHENTICATION 0x00000800 - -/* CKF_USER_PIN_COUNT_LOW if new for v2.10. If it is true, an - * incorrect user login PIN has been entered at least once - * since the last successful authentication. */ -#define CKF_USER_PIN_COUNT_LOW 0x00010000 - -/* CKF_USER_PIN_FINAL_TRY if new for v2.10. If it is true, - * supplying an incorrect user PIN will it to become locked. */ -#define CKF_USER_PIN_FINAL_TRY 0x00020000 - -/* CKF_USER_PIN_LOCKED if new for v2.10. If it is true, the - * user PIN has been locked. User login to the token is not - * possible. */ -#define CKF_USER_PIN_LOCKED 0x00040000 - -/* CKF_USER_PIN_TO_BE_CHANGED if new for v2.10. If it is true, - * the user PIN value is the default value set by token - * initialization or manufacturing, or the PIN has been - * expired by the card. */ -#define CKF_USER_PIN_TO_BE_CHANGED 0x00080000 - -/* CKF_SO_PIN_COUNT_LOW if new for v2.10. If it is true, an - * incorrect SO login PIN has been entered at least once since - * the last successful authentication. */ -#define CKF_SO_PIN_COUNT_LOW 0x00100000 - -/* CKF_SO_PIN_FINAL_TRY if new for v2.10. If it is true, - * supplying an incorrect SO PIN will it to become locked. */ -#define CKF_SO_PIN_FINAL_TRY 0x00200000 - -/* CKF_SO_PIN_LOCKED if new for v2.10. If it is true, the SO - * PIN has been locked. SO login to the token is not possible. - */ -#define CKF_SO_PIN_LOCKED 0x00400000 - -/* CKF_SO_PIN_TO_BE_CHANGED if new for v2.10. If it is true, - * the SO PIN value is the default value set by token - * initialization or manufacturing, or the PIN has been - * expired by the card. */ -#define CKF_SO_PIN_TO_BE_CHANGED 0x00800000 - -typedef CK_TOKEN_INFO CK_PTR CK_TOKEN_INFO_PTR; - - -/* CK_SESSION_HANDLE is a Cryptoki-assigned value that - * identifies a session */ -typedef CK_ULONG CK_SESSION_HANDLE; - -typedef CK_SESSION_HANDLE CK_PTR CK_SESSION_HANDLE_PTR; - - -/* CK_USER_TYPE enumerates the types of Cryptoki users */ -/* CK_USER_TYPE has been changed from an enum to a CK_ULONG for - * v2.0 */ -typedef CK_ULONG CK_USER_TYPE; -/* Security Officer */ -#define CKU_SO 0 -/* Normal user */ -#define CKU_USER 1 -/* Context specific (added in v2.20) */ -#define CKU_CONTEXT_SPECIFIC 2 - -/* CK_STATE enumerates the session states */ -/* CK_STATE has been changed from an enum to a CK_ULONG for - * v2.0 */ -typedef CK_ULONG CK_STATE; -#define CKS_RO_PUBLIC_SESSION 0 -#define CKS_RO_USER_FUNCTIONS 1 -#define CKS_RW_PUBLIC_SESSION 2 -#define CKS_RW_USER_FUNCTIONS 3 -#define CKS_RW_SO_FUNCTIONS 4 - - -/* CK_SESSION_INFO provides information about a session */ -typedef struct CK_SESSION_INFO { - CK_SLOT_ID slotID; - CK_STATE state; - CK_FLAGS flags; /* see below */ - - /* ulDeviceError was changed from CK_USHORT to CK_ULONG for - * v2.0 */ - CK_ULONG ulDeviceError; /* device-dependent error code */ -} CK_SESSION_INFO; - -/* The flags are defined in the following table: - * Bit Flag Mask Meaning - */ -#define CKF_RW_SESSION 0x00000002 /* session is r/w */ -#define CKF_SERIAL_SESSION 0x00000004 /* no parallel */ - -typedef CK_SESSION_INFO CK_PTR CK_SESSION_INFO_PTR; - - -/* CK_OBJECT_HANDLE is a token-specific identifier for an - * object */ -typedef CK_ULONG CK_OBJECT_HANDLE; - -typedef CK_OBJECT_HANDLE CK_PTR CK_OBJECT_HANDLE_PTR; - - -/* CK_OBJECT_CLASS is a value that identifies the classes (or - * types) of objects that Cryptoki recognizes. It is defined - * as follows: */ -/* CK_OBJECT_CLASS was changed from CK_USHORT to CK_ULONG for - * v2.0 */ -typedef CK_ULONG CK_OBJECT_CLASS; - -/* The following classes of objects are defined: */ -/* CKO_HW_FEATURE is new for v2.10 */ -/* CKO_DOMAIN_PARAMETERS is new for v2.11 */ -/* CKO_MECHANISM is new for v2.20 */ -#define CKO_DATA 0x00000000 -#define CKO_CERTIFICATE 0x00000001 -#define CKO_PUBLIC_KEY 0x00000002 -#define CKO_PRIVATE_KEY 0x00000003 -#define CKO_SECRET_KEY 0x00000004 -#define CKO_HW_FEATURE 0x00000005 -#define CKO_DOMAIN_PARAMETERS 0x00000006 -#define CKO_MECHANISM 0x00000007 - -/* CKO_OTP_KEY is new for PKCS #11 v2.20 amendment 1 */ -#define CKO_OTP_KEY 0x00000008 - -#define CKO_VENDOR_DEFINED 0x80000000 - -typedef CK_OBJECT_CLASS CK_PTR CK_OBJECT_CLASS_PTR; - -/* CK_HW_FEATURE_TYPE is new for v2.10. CK_HW_FEATURE_TYPE is a - * value that identifies the hardware feature type of an object - * with CK_OBJECT_CLASS equal to CKO_HW_FEATURE. */ -typedef CK_ULONG CK_HW_FEATURE_TYPE; - -/* The following hardware feature types are defined */ -/* CKH_USER_INTERFACE is new for v2.20 */ -#define CKH_MONOTONIC_COUNTER 0x00000001 -#define CKH_CLOCK 0x00000002 -#define CKH_USER_INTERFACE 0x00000003 -#define CKH_VENDOR_DEFINED 0x80000000 - -/* CK_KEY_TYPE is a value that identifies a key type */ -/* CK_KEY_TYPE was changed from CK_USHORT to CK_ULONG for v2.0 */ -typedef CK_ULONG CK_KEY_TYPE; - -/* the following key types are defined: */ -#define CKK_RSA 0x00000000 -#define CKK_DSA 0x00000001 -#define CKK_DH 0x00000002 - -/* CKK_ECDSA and CKK_KEA are new for v2.0 */ -/* CKK_ECDSA is deprecated in v2.11, CKK_EC is preferred. */ -#define CKK_ECDSA 0x00000003 -#define CKK_EC 0x00000003 -#define CKK_X9_42_DH 0x00000004 -#define CKK_KEA 0x00000005 - -#define CKK_GENERIC_SECRET 0x00000010 -#define CKK_RC2 0x00000011 -#define CKK_RC4 0x00000012 -#define CKK_DES 0x00000013 -#define CKK_DES2 0x00000014 -#define CKK_DES3 0x00000015 - -/* all these key types are new for v2.0 */ -#define CKK_CAST 0x00000016 -#define CKK_CAST3 0x00000017 -/* CKK_CAST5 is deprecated in v2.11, CKK_CAST128 is preferred. */ -#define CKK_CAST5 0x00000018 -#define CKK_CAST128 0x00000018 -#define CKK_RC5 0x00000019 -#define CKK_IDEA 0x0000001A -#define CKK_SKIPJACK 0x0000001B -#define CKK_BATON 0x0000001C -#define CKK_JUNIPER 0x0000001D -#define CKK_CDMF 0x0000001E -#define CKK_AES 0x0000001F - -/* BlowFish and TwoFish are new for v2.20 */ -#define CKK_BLOWFISH 0x00000020 -#define CKK_TWOFISH 0x00000021 - -/* SecurID, HOTP, and ACTI are new for PKCS #11 v2.20 amendment 1 */ -#define CKK_SECURID 0x00000022 -#define CKK_HOTP 0x00000023 -#define CKK_ACTI 0x00000024 - -/* Camellia is new for PKCS #11 v2.20 amendment 3 */ -#define CKK_CAMELLIA 0x00000025 -/* ARIA is new for PKCS #11 v2.20 amendment 3 */ -#define CKK_ARIA 0x00000026 - - -#define CKK_VENDOR_DEFINED 0x80000000 - - -/* CK_CERTIFICATE_TYPE is a value that identifies a certificate - * type */ -/* CK_CERTIFICATE_TYPE was changed from CK_USHORT to CK_ULONG - * for v2.0 */ -typedef CK_ULONG CK_CERTIFICATE_TYPE; - -/* The following certificate types are defined: */ -/* CKC_X_509_ATTR_CERT is new for v2.10 */ -/* CKC_WTLS is new for v2.20 */ -#define CKC_X_509 0x00000000 -#define CKC_X_509_ATTR_CERT 0x00000001 -#define CKC_WTLS 0x00000002 -#define CKC_VENDOR_DEFINED 0x80000000 - - -/* CK_ATTRIBUTE_TYPE is a value that identifies an attribute - * type */ -/* CK_ATTRIBUTE_TYPE was changed from CK_USHORT to CK_ULONG for - * v2.0 */ -typedef CK_ULONG CK_ATTRIBUTE_TYPE; - -/* The CKF_ARRAY_ATTRIBUTE flag identifies an attribute which - consists of an array of values. */ -#define CKF_ARRAY_ATTRIBUTE 0x40000000 - -/* The following OTP-related defines are new for PKCS #11 v2.20 amendment 1 - and relates to the CKA_OTP_FORMAT attribute */ -#define CK_OTP_FORMAT_DECIMAL 0 -#define CK_OTP_FORMAT_HEXADECIMAL 1 -#define CK_OTP_FORMAT_ALPHANUMERIC 2 -#define CK_OTP_FORMAT_BINARY 3 - -/* The following OTP-related defines are new for PKCS #11 v2.20 amendment 1 - and relates to the CKA_OTP_..._REQUIREMENT attributes */ -#define CK_OTP_PARAM_IGNORED 0 -#define CK_OTP_PARAM_OPTIONAL 1 -#define CK_OTP_PARAM_MANDATORY 2 - -/* The following attribute types are defined: */ -#define CKA_CLASS 0x00000000 -#define CKA_TOKEN 0x00000001 -#define CKA_PRIVATE 0x00000002 -#define CKA_LABEL 0x00000003 -#define CKA_APPLICATION 0x00000010 -#define CKA_VALUE 0x00000011 - -/* CKA_OBJECT_ID is new for v2.10 */ -#define CKA_OBJECT_ID 0x00000012 - -#define CKA_CERTIFICATE_TYPE 0x00000080 -#define CKA_ISSUER 0x00000081 -#define CKA_SERIAL_NUMBER 0x00000082 - -/* CKA_AC_ISSUER, CKA_OWNER, and CKA_ATTR_TYPES are new - * for v2.10 */ -#define CKA_AC_ISSUER 0x00000083 -#define CKA_OWNER 0x00000084 -#define CKA_ATTR_TYPES 0x00000085 - -/* CKA_TRUSTED is new for v2.11 */ -#define CKA_TRUSTED 0x00000086 - -/* CKA_CERTIFICATE_CATEGORY ... - * CKA_CHECK_VALUE are new for v2.20 */ -#define CKA_CERTIFICATE_CATEGORY 0x00000087 -#define CKA_JAVA_MIDP_SECURITY_DOMAIN 0x00000088 -#define CKA_URL 0x00000089 -#define CKA_HASH_OF_SUBJECT_PUBLIC_KEY 0x0000008A -#define CKA_HASH_OF_ISSUER_PUBLIC_KEY 0x0000008B -#define CKA_CHECK_VALUE 0x00000090 - -#define CKA_KEY_TYPE 0x00000100 -#define CKA_SUBJECT 0x00000101 -#define CKA_ID 0x00000102 -#define CKA_SENSITIVE 0x00000103 -#define CKA_ENCRYPT 0x00000104 -#define CKA_DECRYPT 0x00000105 -#define CKA_WRAP 0x00000106 -#define CKA_UNWRAP 0x00000107 -#define CKA_SIGN 0x00000108 -#define CKA_SIGN_RECOVER 0x00000109 -#define CKA_VERIFY 0x0000010A -#define CKA_VERIFY_RECOVER 0x0000010B -#define CKA_DERIVE 0x0000010C -#define CKA_START_DATE 0x00000110 -#define CKA_END_DATE 0x00000111 -#define CKA_MODULUS 0x00000120 -#define CKA_MODULUS_BITS 0x00000121 -#define CKA_PUBLIC_EXPONENT 0x00000122 -#define CKA_PRIVATE_EXPONENT 0x00000123 -#define CKA_PRIME_1 0x00000124 -#define CKA_PRIME_2 0x00000125 -#define CKA_EXPONENT_1 0x00000126 -#define CKA_EXPONENT_2 0x00000127 -#define CKA_COEFFICIENT 0x00000128 -#define CKA_PRIME 0x00000130 -#define CKA_SUBPRIME 0x00000131 -#define CKA_BASE 0x00000132 - -/* CKA_PRIME_BITS and CKA_SUB_PRIME_BITS are new for v2.11 */ -#define CKA_PRIME_BITS 0x00000133 -#define CKA_SUBPRIME_BITS 0x00000134 -#define CKA_SUB_PRIME_BITS CKA_SUBPRIME_BITS -/* (To retain backwards-compatibility) */ - -#define CKA_VALUE_BITS 0x00000160 -#define CKA_VALUE_LEN 0x00000161 - -/* CKA_EXTRACTABLE, CKA_LOCAL, CKA_NEVER_EXTRACTABLE, - * CKA_ALWAYS_SENSITIVE, CKA_MODIFIABLE, CKA_ECDSA_PARAMS, - * and CKA_EC_POINT are new for v2.0 */ -#define CKA_EXTRACTABLE 0x00000162 -#define CKA_LOCAL 0x00000163 -#define CKA_NEVER_EXTRACTABLE 0x00000164 -#define CKA_ALWAYS_SENSITIVE 0x00000165 - -/* CKA_KEY_GEN_MECHANISM is new for v2.11 */ -#define CKA_KEY_GEN_MECHANISM 0x00000166 - -#define CKA_MODIFIABLE 0x00000170 - -/* CKA_ECDSA_PARAMS is deprecated in v2.11, - * CKA_EC_PARAMS is preferred. */ -#define CKA_ECDSA_PARAMS 0x00000180 -#define CKA_EC_PARAMS 0x00000180 - -#define CKA_EC_POINT 0x00000181 - -/* CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS, - * are new for v2.10. Deprecated in v2.11 and onwards. */ -#define CKA_SECONDARY_AUTH 0x00000200 -#define CKA_AUTH_PIN_FLAGS 0x00000201 - -/* CKA_ALWAYS_AUTHENTICATE ... - * CKA_UNWRAP_TEMPLATE are new for v2.20 */ -#define CKA_ALWAYS_AUTHENTICATE 0x00000202 - -#define CKA_WRAP_WITH_TRUSTED 0x00000210 -#define CKA_WRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE|0x00000211) -#define CKA_UNWRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE|0x00000212) - -/* CKA_OTP... atttributes are new for PKCS #11 v2.20 amendment 3. */ -#define CKA_OTP_FORMAT 0x00000220 -#define CKA_OTP_LENGTH 0x00000221 -#define CKA_OTP_TIME_INTERVAL 0x00000222 -#define CKA_OTP_USER_FRIENDLY_MODE 0x00000223 -#define CKA_OTP_CHALLENGE_REQUIREMENT 0x00000224 -#define CKA_OTP_TIME_REQUIREMENT 0x00000225 -#define CKA_OTP_COUNTER_REQUIREMENT 0x00000226 -#define CKA_OTP_PIN_REQUIREMENT 0x00000227 -#define CKA_OTP_COUNTER 0x0000022E -#define CKA_OTP_TIME 0x0000022F -#define CKA_OTP_USER_IDENTIFIER 0x0000022A -#define CKA_OTP_SERVICE_IDENTIFIER 0x0000022B -#define CKA_OTP_SERVICE_LOGO 0x0000022C -#define CKA_OTP_SERVICE_LOGO_TYPE 0x0000022D - - -/* CKA_HW_FEATURE_TYPE, CKA_RESET_ON_INIT, and CKA_HAS_RESET - * are new for v2.10 */ -#define CKA_HW_FEATURE_TYPE 0x00000300 -#define CKA_RESET_ON_INIT 0x00000301 -#define CKA_HAS_RESET 0x00000302 - -/* The following attributes are new for v2.20 */ -#define CKA_PIXEL_X 0x00000400 -#define CKA_PIXEL_Y 0x00000401 -#define CKA_RESOLUTION 0x00000402 -#define CKA_CHAR_ROWS 0x00000403 -#define CKA_CHAR_COLUMNS 0x00000404 -#define CKA_COLOR 0x00000405 -#define CKA_BITS_PER_PIXEL 0x00000406 -#define CKA_CHAR_SETS 0x00000480 -#define CKA_ENCODING_METHODS 0x00000481 -#define CKA_MIME_TYPES 0x00000482 -#define CKA_MECHANISM_TYPE 0x00000500 -#define CKA_REQUIRED_CMS_ATTRIBUTES 0x00000501 -#define CKA_DEFAULT_CMS_ATTRIBUTES 0x00000502 -#define CKA_SUPPORTED_CMS_ATTRIBUTES 0x00000503 -#define CKA_ALLOWED_MECHANISMS (CKF_ARRAY_ATTRIBUTE|0x00000600) - -#define CKA_VENDOR_DEFINED 0x80000000 - -/* CK_ATTRIBUTE is a structure that includes the type, length - * and value of an attribute */ -typedef struct CK_ATTRIBUTE { - CK_ATTRIBUTE_TYPE type; - CK_VOID_PTR pValue; - - /* ulValueLen went from CK_USHORT to CK_ULONG for v2.0 */ - CK_ULONG ulValueLen; /* in bytes */ -} CK_ATTRIBUTE; - -typedef CK_ATTRIBUTE CK_PTR CK_ATTRIBUTE_PTR; - - -/* CK_DATE is a structure that defines a date */ -typedef struct CK_DATE{ - CK_CHAR year[4]; /* the year ("1900" - "9999") */ - CK_CHAR month[2]; /* the month ("01" - "12") */ - CK_CHAR day[2]; /* the day ("01" - "31") */ -} CK_DATE; - - -/* CK_MECHANISM_TYPE is a value that identifies a mechanism - * type */ -/* CK_MECHANISM_TYPE was changed from CK_USHORT to CK_ULONG for - * v2.0 */ -typedef CK_ULONG CK_MECHANISM_TYPE; - -/* the following mechanism types are defined: */ -#define CKM_RSA_PKCS_KEY_PAIR_GEN 0x00000000 -#define CKM_RSA_PKCS 0x00000001 -#define CKM_RSA_9796 0x00000002 -#define CKM_RSA_X_509 0x00000003 - -/* CKM_MD2_RSA_PKCS, CKM_MD5_RSA_PKCS, and CKM_SHA1_RSA_PKCS - * are new for v2.0. They are mechanisms which hash and sign */ -#define CKM_MD2_RSA_PKCS 0x00000004 -#define CKM_MD5_RSA_PKCS 0x00000005 -#define CKM_SHA1_RSA_PKCS 0x00000006 - -/* CKM_RIPEMD128_RSA_PKCS, CKM_RIPEMD160_RSA_PKCS, and - * CKM_RSA_PKCS_OAEP are new for v2.10 */ -#define CKM_RIPEMD128_RSA_PKCS 0x00000007 -#define CKM_RIPEMD160_RSA_PKCS 0x00000008 -#define CKM_RSA_PKCS_OAEP 0x00000009 - -/* CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_RSA_X9_31, CKM_SHA1_RSA_X9_31, - * CKM_RSA_PKCS_PSS, and CKM_SHA1_RSA_PKCS_PSS are new for v2.11 */ -#define CKM_RSA_X9_31_KEY_PAIR_GEN 0x0000000A -#define CKM_RSA_X9_31 0x0000000B -#define CKM_SHA1_RSA_X9_31 0x0000000C -#define CKM_RSA_PKCS_PSS 0x0000000D -#define CKM_SHA1_RSA_PKCS_PSS 0x0000000E - -#define CKM_DSA_KEY_PAIR_GEN 0x00000010 -#define CKM_DSA 0x00000011 -#define CKM_DSA_SHA1 0x00000012 -#define CKM_DH_PKCS_KEY_PAIR_GEN 0x00000020 -#define CKM_DH_PKCS_DERIVE 0x00000021 - -/* CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_DERIVE, - * CKM_X9_42_DH_HYBRID_DERIVE, and CKM_X9_42_MQV_DERIVE are new for - * v2.11 */ -#define CKM_X9_42_DH_KEY_PAIR_GEN 0x00000030 -#define CKM_X9_42_DH_DERIVE 0x00000031 -#define CKM_X9_42_DH_HYBRID_DERIVE 0x00000032 -#define CKM_X9_42_MQV_DERIVE 0x00000033 - -/* CKM_SHA256/384/512 are new for v2.20 */ -#define CKM_SHA256_RSA_PKCS 0x00000040 -#define CKM_SHA384_RSA_PKCS 0x00000041 -#define CKM_SHA512_RSA_PKCS 0x00000042 -#define CKM_SHA256_RSA_PKCS_PSS 0x00000043 -#define CKM_SHA384_RSA_PKCS_PSS 0x00000044 -#define CKM_SHA512_RSA_PKCS_PSS 0x00000045 - -/* SHA-224 RSA mechanisms are new for PKCS #11 v2.20 amendment 3 */ -#define CKM_SHA224_RSA_PKCS 0x00000046 -#define CKM_SHA224_RSA_PKCS_PSS 0x00000047 - -#define CKM_RC2_KEY_GEN 0x00000100 -#define CKM_RC2_ECB 0x00000101 -#define CKM_RC2_CBC 0x00000102 -#define CKM_RC2_MAC 0x00000103 - -/* CKM_RC2_MAC_GENERAL and CKM_RC2_CBC_PAD are new for v2.0 */ -#define CKM_RC2_MAC_GENERAL 0x00000104 -#define CKM_RC2_CBC_PAD 0x00000105 - -#define CKM_RC4_KEY_GEN 0x00000110 -#define CKM_RC4 0x00000111 -#define CKM_DES_KEY_GEN 0x00000120 -#define CKM_DES_ECB 0x00000121 -#define CKM_DES_CBC 0x00000122 -#define CKM_DES_MAC 0x00000123 - -/* CKM_DES_MAC_GENERAL and CKM_DES_CBC_PAD are new for v2.0 */ -#define CKM_DES_MAC_GENERAL 0x00000124 -#define CKM_DES_CBC_PAD 0x00000125 - -#define CKM_DES2_KEY_GEN 0x00000130 -#define CKM_DES3_KEY_GEN 0x00000131 -#define CKM_DES3_ECB 0x00000132 -#define CKM_DES3_CBC 0x00000133 -#define CKM_DES3_MAC 0x00000134 - -/* CKM_DES3_MAC_GENERAL, CKM_DES3_CBC_PAD, CKM_CDMF_KEY_GEN, - * CKM_CDMF_ECB, CKM_CDMF_CBC, CKM_CDMF_MAC, - * CKM_CDMF_MAC_GENERAL, and CKM_CDMF_CBC_PAD are new for v2.0 */ -#define CKM_DES3_MAC_GENERAL 0x00000135 -#define CKM_DES3_CBC_PAD 0x00000136 -#define CKM_CDMF_KEY_GEN 0x00000140 -#define CKM_CDMF_ECB 0x00000141 -#define CKM_CDMF_CBC 0x00000142 -#define CKM_CDMF_MAC 0x00000143 -#define CKM_CDMF_MAC_GENERAL 0x00000144 -#define CKM_CDMF_CBC_PAD 0x00000145 - -/* the following four DES mechanisms are new for v2.20 */ -#define CKM_DES_OFB64 0x00000150 -#define CKM_DES_OFB8 0x00000151 -#define CKM_DES_CFB64 0x00000152 -#define CKM_DES_CFB8 0x00000153 - -#define CKM_MD2 0x00000200 - -/* CKM_MD2_HMAC and CKM_MD2_HMAC_GENERAL are new for v2.0 */ -#define CKM_MD2_HMAC 0x00000201 -#define CKM_MD2_HMAC_GENERAL 0x00000202 - -#define CKM_MD5 0x00000210 - -/* CKM_MD5_HMAC and CKM_MD5_HMAC_GENERAL are new for v2.0 */ -#define CKM_MD5_HMAC 0x00000211 -#define CKM_MD5_HMAC_GENERAL 0x00000212 - -#define CKM_SHA_1 0x00000220 - -/* CKM_SHA_1_HMAC and CKM_SHA_1_HMAC_GENERAL are new for v2.0 */ -#define CKM_SHA_1_HMAC 0x00000221 -#define CKM_SHA_1_HMAC_GENERAL 0x00000222 - -/* CKM_RIPEMD128, CKM_RIPEMD128_HMAC, - * CKM_RIPEMD128_HMAC_GENERAL, CKM_RIPEMD160, CKM_RIPEMD160_HMAC, - * and CKM_RIPEMD160_HMAC_GENERAL are new for v2.10 */ -#define CKM_RIPEMD128 0x00000230 -#define CKM_RIPEMD128_HMAC 0x00000231 -#define CKM_RIPEMD128_HMAC_GENERAL 0x00000232 -#define CKM_RIPEMD160 0x00000240 -#define CKM_RIPEMD160_HMAC 0x00000241 -#define CKM_RIPEMD160_HMAC_GENERAL 0x00000242 - -/* CKM_SHA256/384/512 are new for v2.20 */ -#define CKM_SHA256 0x00000250 -#define CKM_SHA256_HMAC 0x00000251 -#define CKM_SHA256_HMAC_GENERAL 0x00000252 - -/* SHA-224 is new for PKCS #11 v2.20 amendment 3 */ -#define CKM_SHA224 0x00000255 -#define CKM_SHA224_HMAC 0x00000256 -#define CKM_SHA224_HMAC_GENERAL 0x00000257 - -#define CKM_SHA384 0x00000260 -#define CKM_SHA384_HMAC 0x00000261 -#define CKM_SHA384_HMAC_GENERAL 0x00000262 -#define CKM_SHA512 0x00000270 -#define CKM_SHA512_HMAC 0x00000271 -#define CKM_SHA512_HMAC_GENERAL 0x00000272 - -/* SecurID is new for PKCS #11 v2.20 amendment 1 */ -#define CKM_SECURID_KEY_GEN 0x00000280 -#define CKM_SECURID 0x00000282 - -/* HOTP is new for PKCS #11 v2.20 amendment 1 */ -#define CKM_HOTP_KEY_GEN 0x00000290 -#define CKM_HOTP 0x00000291 - -/* ACTI is new for PKCS #11 v2.20 amendment 1 */ -#define CKM_ACTI 0x000002A0 -#define CKM_ACTI_KEY_GEN 0x000002A1 - -/* All of the following mechanisms are new for v2.0 */ -/* Note that CAST128 and CAST5 are the same algorithm */ -#define CKM_CAST_KEY_GEN 0x00000300 -#define CKM_CAST_ECB 0x00000301 -#define CKM_CAST_CBC 0x00000302 -#define CKM_CAST_MAC 0x00000303 -#define CKM_CAST_MAC_GENERAL 0x00000304 -#define CKM_CAST_CBC_PAD 0x00000305 -#define CKM_CAST3_KEY_GEN 0x00000310 -#define CKM_CAST3_ECB 0x00000311 -#define CKM_CAST3_CBC 0x00000312 -#define CKM_CAST3_MAC 0x00000313 -#define CKM_CAST3_MAC_GENERAL 0x00000314 -#define CKM_CAST3_CBC_PAD 0x00000315 -#define CKM_CAST5_KEY_GEN 0x00000320 -#define CKM_CAST128_KEY_GEN 0x00000320 -#define CKM_CAST5_ECB 0x00000321 -#define CKM_CAST128_ECB 0x00000321 -#define CKM_CAST5_CBC 0x00000322 -#define CKM_CAST128_CBC 0x00000322 -#define CKM_CAST5_MAC 0x00000323 -#define CKM_CAST128_MAC 0x00000323 -#define CKM_CAST5_MAC_GENERAL 0x00000324 -#define CKM_CAST128_MAC_GENERAL 0x00000324 -#define CKM_CAST5_CBC_PAD 0x00000325 -#define CKM_CAST128_CBC_PAD 0x00000325 -#define CKM_RC5_KEY_GEN 0x00000330 -#define CKM_RC5_ECB 0x00000331 -#define CKM_RC5_CBC 0x00000332 -#define CKM_RC5_MAC 0x00000333 -#define CKM_RC5_MAC_GENERAL 0x00000334 -#define CKM_RC5_CBC_PAD 0x00000335 -#define CKM_IDEA_KEY_GEN 0x00000340 -#define CKM_IDEA_ECB 0x00000341 -#define CKM_IDEA_CBC 0x00000342 -#define CKM_IDEA_MAC 0x00000343 -#define CKM_IDEA_MAC_GENERAL 0x00000344 -#define CKM_IDEA_CBC_PAD 0x00000345 -#define CKM_GENERIC_SECRET_KEY_GEN 0x00000350 -#define CKM_CONCATENATE_BASE_AND_KEY 0x00000360 -#define CKM_CONCATENATE_BASE_AND_DATA 0x00000362 -#define CKM_CONCATENATE_DATA_AND_BASE 0x00000363 -#define CKM_XOR_BASE_AND_DATA 0x00000364 -#define CKM_EXTRACT_KEY_FROM_KEY 0x00000365 -#define CKM_SSL3_PRE_MASTER_KEY_GEN 0x00000370 -#define CKM_SSL3_MASTER_KEY_DERIVE 0x00000371 -#define CKM_SSL3_KEY_AND_MAC_DERIVE 0x00000372 - -/* CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_TLS_PRE_MASTER_KEY_GEN, - * CKM_TLS_MASTER_KEY_DERIVE, CKM_TLS_KEY_AND_MAC_DERIVE, and - * CKM_TLS_MASTER_KEY_DERIVE_DH are new for v2.11 */ -#define CKM_SSL3_MASTER_KEY_DERIVE_DH 0x00000373 -#define CKM_TLS_PRE_MASTER_KEY_GEN 0x00000374 -#define CKM_TLS_MASTER_KEY_DERIVE 0x00000375 -#define CKM_TLS_KEY_AND_MAC_DERIVE 0x00000376 -#define CKM_TLS_MASTER_KEY_DERIVE_DH 0x00000377 - -/* CKM_TLS_PRF is new for v2.20 */ -#define CKM_TLS_PRF 0x00000378 - -#define CKM_SSL3_MD5_MAC 0x00000380 -#define CKM_SSL3_SHA1_MAC 0x00000381 -#define CKM_MD5_KEY_DERIVATION 0x00000390 -#define CKM_MD2_KEY_DERIVATION 0x00000391 -#define CKM_SHA1_KEY_DERIVATION 0x00000392 - -/* CKM_SHA256/384/512 are new for v2.20 */ -#define CKM_SHA256_KEY_DERIVATION 0x00000393 -#define CKM_SHA384_KEY_DERIVATION 0x00000394 -#define CKM_SHA512_KEY_DERIVATION 0x00000395 - -/* SHA-224 key derivation is new for PKCS #11 v2.20 amendment 3 */ -#define CKM_SHA224_KEY_DERIVATION 0x00000396 - -#define CKM_PBE_MD2_DES_CBC 0x000003A0 -#define CKM_PBE_MD5_DES_CBC 0x000003A1 -#define CKM_PBE_MD5_CAST_CBC 0x000003A2 -#define CKM_PBE_MD5_CAST3_CBC 0x000003A3 -#define CKM_PBE_MD5_CAST5_CBC 0x000003A4 -#define CKM_PBE_MD5_CAST128_CBC 0x000003A4 -#define CKM_PBE_SHA1_CAST5_CBC 0x000003A5 -#define CKM_PBE_SHA1_CAST128_CBC 0x000003A5 -#define CKM_PBE_SHA1_RC4_128 0x000003A6 -#define CKM_PBE_SHA1_RC4_40 0x000003A7 -#define CKM_PBE_SHA1_DES3_EDE_CBC 0x000003A8 -#define CKM_PBE_SHA1_DES2_EDE_CBC 0x000003A9 -#define CKM_PBE_SHA1_RC2_128_CBC 0x000003AA -#define CKM_PBE_SHA1_RC2_40_CBC 0x000003AB - -/* CKM_PKCS5_PBKD2 is new for v2.10 */ -#define CKM_PKCS5_PBKD2 0x000003B0 - -#define CKM_PBA_SHA1_WITH_SHA1_HMAC 0x000003C0 - -/* WTLS mechanisms are new for v2.20 */ -#define CKM_WTLS_PRE_MASTER_KEY_GEN 0x000003D0 -#define CKM_WTLS_MASTER_KEY_DERIVE 0x000003D1 -#define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC 0x000003D2 -#define CKM_WTLS_PRF 0x000003D3 -#define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE 0x000003D4 -#define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE 0x000003D5 - -#define CKM_KEY_WRAP_LYNKS 0x00000400 -#define CKM_KEY_WRAP_SET_OAEP 0x00000401 - -/* CKM_CMS_SIG is new for v2.20 */ -#define CKM_CMS_SIG 0x00000500 - -/* CKM_KIP mechanisms are new for PKCS #11 v2.20 amendment 2 */ -#define CKM_KIP_DERIVE 0x00000510 -#define CKM_KIP_WRAP 0x00000511 -#define CKM_KIP_MAC 0x00000512 - -/* Camellia is new for PKCS #11 v2.20 amendment 3 */ -#define CKM_CAMELLIA_KEY_GEN 0x00000550 -#define CKM_CAMELLIA_ECB 0x00000551 -#define CKM_CAMELLIA_CBC 0x00000552 -#define CKM_CAMELLIA_MAC 0x00000553 -#define CKM_CAMELLIA_MAC_GENERAL 0x00000554 -#define CKM_CAMELLIA_CBC_PAD 0x00000555 -#define CKM_CAMELLIA_ECB_ENCRYPT_DATA 0x00000556 -#define CKM_CAMELLIA_CBC_ENCRYPT_DATA 0x00000557 -#define CKM_CAMELLIA_CTR 0x00000558 - -/* ARIA is new for PKCS #11 v2.20 amendment 3 */ -#define CKM_ARIA_KEY_GEN 0x00000560 -#define CKM_ARIA_ECB 0x00000561 -#define CKM_ARIA_CBC 0x00000562 -#define CKM_ARIA_MAC 0x00000563 -#define CKM_ARIA_MAC_GENERAL 0x00000564 -#define CKM_ARIA_CBC_PAD 0x00000565 -#define CKM_ARIA_ECB_ENCRYPT_DATA 0x00000566 -#define CKM_ARIA_CBC_ENCRYPT_DATA 0x00000567 - -/* Fortezza mechanisms */ -#define CKM_SKIPJACK_KEY_GEN 0x00001000 -#define CKM_SKIPJACK_ECB64 0x00001001 -#define CKM_SKIPJACK_CBC64 0x00001002 -#define CKM_SKIPJACK_OFB64 0x00001003 -#define CKM_SKIPJACK_CFB64 0x00001004 -#define CKM_SKIPJACK_CFB32 0x00001005 -#define CKM_SKIPJACK_CFB16 0x00001006 -#define CKM_SKIPJACK_CFB8 0x00001007 -#define CKM_SKIPJACK_WRAP 0x00001008 -#define CKM_SKIPJACK_PRIVATE_WRAP 0x00001009 -#define CKM_SKIPJACK_RELAYX 0x0000100a -#define CKM_KEA_KEY_PAIR_GEN 0x00001010 -#define CKM_KEA_KEY_DERIVE 0x00001011 -#define CKM_FORTEZZA_TIMESTAMP 0x00001020 -#define CKM_BATON_KEY_GEN 0x00001030 -#define CKM_BATON_ECB128 0x00001031 -#define CKM_BATON_ECB96 0x00001032 -#define CKM_BATON_CBC128 0x00001033 -#define CKM_BATON_COUNTER 0x00001034 -#define CKM_BATON_SHUFFLE 0x00001035 -#define CKM_BATON_WRAP 0x00001036 - -/* CKM_ECDSA_KEY_PAIR_GEN is deprecated in v2.11, - * CKM_EC_KEY_PAIR_GEN is preferred */ -#define CKM_ECDSA_KEY_PAIR_GEN 0x00001040 -#define CKM_EC_KEY_PAIR_GEN 0x00001040 - -#define CKM_ECDSA 0x00001041 -#define CKM_ECDSA_SHA1 0x00001042 - -/* CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, and CKM_ECMQV_DERIVE - * are new for v2.11 */ -#define CKM_ECDH1_DERIVE 0x00001050 -#define CKM_ECDH1_COFACTOR_DERIVE 0x00001051 -#define CKM_ECMQV_DERIVE 0x00001052 - -#define CKM_JUNIPER_KEY_GEN 0x00001060 -#define CKM_JUNIPER_ECB128 0x00001061 -#define CKM_JUNIPER_CBC128 0x00001062 -#define CKM_JUNIPER_COUNTER 0x00001063 -#define CKM_JUNIPER_SHUFFLE 0x00001064 -#define CKM_JUNIPER_WRAP 0x00001065 -#define CKM_FASTHASH 0x00001070 - -/* CKM_AES_KEY_GEN, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_MAC, - * CKM_AES_MAC_GENERAL, CKM_AES_CBC_PAD, CKM_DSA_PARAMETER_GEN, - * CKM_DH_PKCS_PARAMETER_GEN, and CKM_X9_42_DH_PARAMETER_GEN are - * new for v2.11 */ -#define CKM_AES_KEY_GEN 0x00001080 -#define CKM_AES_ECB 0x00001081 -#define CKM_AES_CBC 0x00001082 -#define CKM_AES_MAC 0x00001083 -#define CKM_AES_MAC_GENERAL 0x00001084 -#define CKM_AES_CBC_PAD 0x00001085 - -/* AES counter mode is new for PKCS #11 v2.20 amendment 3 */ -#define CKM_AES_CTR 0x00001086 - -/* BlowFish and TwoFish are new for v2.20 */ -#define CKM_BLOWFISH_KEY_GEN 0x00001090 -#define CKM_BLOWFISH_CBC 0x00001091 -#define CKM_TWOFISH_KEY_GEN 0x00001092 -#define CKM_TWOFISH_CBC 0x00001093 - - -/* CKM_xxx_ENCRYPT_DATA mechanisms are new for v2.20 */ -#define CKM_DES_ECB_ENCRYPT_DATA 0x00001100 -#define CKM_DES_CBC_ENCRYPT_DATA 0x00001101 -#define CKM_DES3_ECB_ENCRYPT_DATA 0x00001102 -#define CKM_DES3_CBC_ENCRYPT_DATA 0x00001103 -#define CKM_AES_ECB_ENCRYPT_DATA 0x00001104 -#define CKM_AES_CBC_ENCRYPT_DATA 0x00001105 - -#define CKM_DSA_PARAMETER_GEN 0x00002000 -#define CKM_DH_PKCS_PARAMETER_GEN 0x00002001 -#define CKM_X9_42_DH_PARAMETER_GEN 0x00002002 - -#define CKM_VENDOR_DEFINED 0x80000000 - -typedef CK_MECHANISM_TYPE CK_PTR CK_MECHANISM_TYPE_PTR; - - -/* CK_MECHANISM is a structure that specifies a particular - * mechanism */ -typedef struct CK_MECHANISM { - CK_MECHANISM_TYPE mechanism; - CK_VOID_PTR pParameter; - - /* ulParameterLen was changed from CK_USHORT to CK_ULONG for - * v2.0 */ - CK_ULONG ulParameterLen; /* in bytes */ -} CK_MECHANISM; - -typedef CK_MECHANISM CK_PTR CK_MECHANISM_PTR; - - -/* CK_MECHANISM_INFO provides information about a particular - * mechanism */ -typedef struct CK_MECHANISM_INFO { - CK_ULONG ulMinKeySize; - CK_ULONG ulMaxKeySize; - CK_FLAGS flags; -} CK_MECHANISM_INFO; - -/* The flags are defined as follows: - * Bit Flag Mask Meaning */ -#define CKF_HW 0x00000001 /* performed by HW */ - -/* The flags CKF_ENCRYPT, CKF_DECRYPT, CKF_DIGEST, CKF_SIGN, - * CKG_SIGN_RECOVER, CKF_VERIFY, CKF_VERIFY_RECOVER, - * CKF_GENERATE, CKF_GENERATE_KEY_PAIR, CKF_WRAP, CKF_UNWRAP, - * and CKF_DERIVE are new for v2.0. They specify whether or not - * a mechanism can be used for a particular task */ -#define CKF_ENCRYPT 0x00000100 -#define CKF_DECRYPT 0x00000200 -#define CKF_DIGEST 0x00000400 -#define CKF_SIGN 0x00000800 -#define CKF_SIGN_RECOVER 0x00001000 -#define CKF_VERIFY 0x00002000 -#define CKF_VERIFY_RECOVER 0x00004000 -#define CKF_GENERATE 0x00008000 -#define CKF_GENERATE_KEY_PAIR 0x00010000 -#define CKF_WRAP 0x00020000 -#define CKF_UNWRAP 0x00040000 -#define CKF_DERIVE 0x00080000 - -/* CKF_EC_F_P, CKF_EC_F_2M, CKF_EC_ECPARAMETERS, CKF_EC_NAMEDCURVE, - * CKF_EC_UNCOMPRESS, and CKF_EC_COMPRESS are new for v2.11. They - * describe a token's EC capabilities not available in mechanism - * information. */ -#define CKF_EC_F_P 0x00100000 -#define CKF_EC_F_2M 0x00200000 -#define CKF_EC_ECPARAMETERS 0x00400000 -#define CKF_EC_NAMEDCURVE 0x00800000 -#define CKF_EC_UNCOMPRESS 0x01000000 -#define CKF_EC_COMPRESS 0x02000000 - -#define CKF_EXTENSION 0x80000000 /* FALSE for this version */ - -typedef CK_MECHANISM_INFO CK_PTR CK_MECHANISM_INFO_PTR; - - -/* CK_RV is a value that identifies the return value of a - * Cryptoki function */ -/* CK_RV was changed from CK_USHORT to CK_ULONG for v2.0 */ -typedef CK_ULONG CK_RV; - -#define CKR_OK 0x00000000 -#define CKR_CANCEL 0x00000001 -#define CKR_HOST_MEMORY 0x00000002 -#define CKR_SLOT_ID_INVALID 0x00000003 - -/* CKR_FLAGS_INVALID was removed for v2.0 */ - -/* CKR_GENERAL_ERROR and CKR_FUNCTION_FAILED are new for v2.0 */ -#define CKR_GENERAL_ERROR 0x00000005 -#define CKR_FUNCTION_FAILED 0x00000006 - -/* CKR_ARGUMENTS_BAD, CKR_NO_EVENT, CKR_NEED_TO_CREATE_THREADS, - * and CKR_CANT_LOCK are new for v2.01 */ -#define CKR_ARGUMENTS_BAD 0x00000007 -#define CKR_NO_EVENT 0x00000008 -#define CKR_NEED_TO_CREATE_THREADS 0x00000009 -#define CKR_CANT_LOCK 0x0000000A - -#define CKR_ATTRIBUTE_READ_ONLY 0x00000010 -#define CKR_ATTRIBUTE_SENSITIVE 0x00000011 -#define CKR_ATTRIBUTE_TYPE_INVALID 0x00000012 -#define CKR_ATTRIBUTE_VALUE_INVALID 0x00000013 -#define CKR_DATA_INVALID 0x00000020 -#define CKR_DATA_LEN_RANGE 0x00000021 -#define CKR_DEVICE_ERROR 0x00000030 -#define CKR_DEVICE_MEMORY 0x00000031 -#define CKR_DEVICE_REMOVED 0x00000032 -#define CKR_ENCRYPTED_DATA_INVALID 0x00000040 -#define CKR_ENCRYPTED_DATA_LEN_RANGE 0x00000041 -#define CKR_FUNCTION_CANCELED 0x00000050 -#define CKR_FUNCTION_NOT_PARALLEL 0x00000051 - -/* CKR_FUNCTION_NOT_SUPPORTED is new for v2.0 */ -#define CKR_FUNCTION_NOT_SUPPORTED 0x00000054 - -#define CKR_KEY_HANDLE_INVALID 0x00000060 - -/* CKR_KEY_SENSITIVE was removed for v2.0 */ - -#define CKR_KEY_SIZE_RANGE 0x00000062 -#define CKR_KEY_TYPE_INCONSISTENT 0x00000063 - -/* CKR_KEY_NOT_NEEDED, CKR_KEY_CHANGED, CKR_KEY_NEEDED, - * CKR_KEY_INDIGESTIBLE, CKR_KEY_FUNCTION_NOT_PERMITTED, - * CKR_KEY_NOT_WRAPPABLE, and CKR_KEY_UNEXTRACTABLE are new for - * v2.0 */ -#define CKR_KEY_NOT_NEEDED 0x00000064 -#define CKR_KEY_CHANGED 0x00000065 -#define CKR_KEY_NEEDED 0x00000066 -#define CKR_KEY_INDIGESTIBLE 0x00000067 -#define CKR_KEY_FUNCTION_NOT_PERMITTED 0x00000068 -#define CKR_KEY_NOT_WRAPPABLE 0x00000069 -#define CKR_KEY_UNEXTRACTABLE 0x0000006A - -#define CKR_MECHANISM_INVALID 0x00000070 -#define CKR_MECHANISM_PARAM_INVALID 0x00000071 - -/* CKR_OBJECT_CLASS_INCONSISTENT and CKR_OBJECT_CLASS_INVALID - * were removed for v2.0 */ -#define CKR_OBJECT_HANDLE_INVALID 0x00000082 -#define CKR_OPERATION_ACTIVE 0x00000090 -#define CKR_OPERATION_NOT_INITIALIZED 0x00000091 -#define CKR_PIN_INCORRECT 0x000000A0 -#define CKR_PIN_INVALID 0x000000A1 -#define CKR_PIN_LEN_RANGE 0x000000A2 - -/* CKR_PIN_EXPIRED and CKR_PIN_LOCKED are new for v2.0 */ -#define CKR_PIN_EXPIRED 0x000000A3 -#define CKR_PIN_LOCKED 0x000000A4 - -#define CKR_SESSION_CLOSED 0x000000B0 -#define CKR_SESSION_COUNT 0x000000B1 -#define CKR_SESSION_HANDLE_INVALID 0x000000B3 -#define CKR_SESSION_PARALLEL_NOT_SUPPORTED 0x000000B4 -#define CKR_SESSION_READ_ONLY 0x000000B5 -#define CKR_SESSION_EXISTS 0x000000B6 - -/* CKR_SESSION_READ_ONLY_EXISTS and - * CKR_SESSION_READ_WRITE_SO_EXISTS are new for v2.0 */ -#define CKR_SESSION_READ_ONLY_EXISTS 0x000000B7 -#define CKR_SESSION_READ_WRITE_SO_EXISTS 0x000000B8 - -#define CKR_SIGNATURE_INVALID 0x000000C0 -#define CKR_SIGNATURE_LEN_RANGE 0x000000C1 -#define CKR_TEMPLATE_INCOMPLETE 0x000000D0 -#define CKR_TEMPLATE_INCONSISTENT 0x000000D1 -#define CKR_TOKEN_NOT_PRESENT 0x000000E0 -#define CKR_TOKEN_NOT_RECOGNIZED 0x000000E1 -#define CKR_TOKEN_WRITE_PROTECTED 0x000000E2 -#define CKR_UNWRAPPING_KEY_HANDLE_INVALID 0x000000F0 -#define CKR_UNWRAPPING_KEY_SIZE_RANGE 0x000000F1 -#define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT 0x000000F2 -#define CKR_USER_ALREADY_LOGGED_IN 0x00000100 -#define CKR_USER_NOT_LOGGED_IN 0x00000101 -#define CKR_USER_PIN_NOT_INITIALIZED 0x00000102 -#define CKR_USER_TYPE_INVALID 0x00000103 - -/* CKR_USER_ANOTHER_ALREADY_LOGGED_IN and CKR_USER_TOO_MANY_TYPES - * are new to v2.01 */ -#define CKR_USER_ANOTHER_ALREADY_LOGGED_IN 0x00000104 -#define CKR_USER_TOO_MANY_TYPES 0x00000105 - -#define CKR_WRAPPED_KEY_INVALID 0x00000110 -#define CKR_WRAPPED_KEY_LEN_RANGE 0x00000112 -#define CKR_WRAPPING_KEY_HANDLE_INVALID 0x00000113 -#define CKR_WRAPPING_KEY_SIZE_RANGE 0x00000114 -#define CKR_WRAPPING_KEY_TYPE_INCONSISTENT 0x00000115 -#define CKR_RANDOM_SEED_NOT_SUPPORTED 0x00000120 - -/* These are new to v2.0 */ -#define CKR_RANDOM_NO_RNG 0x00000121 - -/* These are new to v2.11 */ -#define CKR_DOMAIN_PARAMS_INVALID 0x00000130 - -/* These are new to v2.0 */ -#define CKR_BUFFER_TOO_SMALL 0x00000150 -#define CKR_SAVED_STATE_INVALID 0x00000160 -#define CKR_INFORMATION_SENSITIVE 0x00000170 -#define CKR_STATE_UNSAVEABLE 0x00000180 - -/* These are new to v2.01 */ -#define CKR_CRYPTOKI_NOT_INITIALIZED 0x00000190 -#define CKR_CRYPTOKI_ALREADY_INITIALIZED 0x00000191 -#define CKR_MUTEX_BAD 0x000001A0 -#define CKR_MUTEX_NOT_LOCKED 0x000001A1 - -/* The following return values are new for PKCS #11 v2.20 amendment 3 */ -#define CKR_NEW_PIN_MODE 0x000001B0 -#define CKR_NEXT_OTP 0x000001B1 - -/* This is new to v2.20 */ -#define CKR_FUNCTION_REJECTED 0x00000200 - -#define CKR_VENDOR_DEFINED 0x80000000 - - -/* CK_NOTIFY is an application callback that processes events */ -typedef CK_CALLBACK_FUNCTION(CK_RV, CK_NOTIFY)( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_NOTIFICATION event, - CK_VOID_PTR pApplication /* passed to C_OpenSession */ -); - - -/* CK_FUNCTION_LIST is a structure holding a Cryptoki spec - * version and pointers of appropriate types to all the - * Cryptoki functions */ -/* CK_FUNCTION_LIST is new for v2.0 */ -typedef struct CK_FUNCTION_LIST CK_FUNCTION_LIST; - -typedef CK_FUNCTION_LIST CK_PTR CK_FUNCTION_LIST_PTR; - -typedef CK_FUNCTION_LIST_PTR CK_PTR CK_FUNCTION_LIST_PTR_PTR; - - -/* CK_CREATEMUTEX is an application callback for creating a - * mutex object */ -typedef CK_CALLBACK_FUNCTION(CK_RV, CK_CREATEMUTEX)( - CK_VOID_PTR_PTR ppMutex /* location to receive ptr to mutex */ -); - - -/* CK_DESTROYMUTEX is an application callback for destroying a - * mutex object */ -typedef CK_CALLBACK_FUNCTION(CK_RV, CK_DESTROYMUTEX)( - CK_VOID_PTR pMutex /* pointer to mutex */ -); - - -/* CK_LOCKMUTEX is an application callback for locking a mutex */ -typedef CK_CALLBACK_FUNCTION(CK_RV, CK_LOCKMUTEX)( - CK_VOID_PTR pMutex /* pointer to mutex */ -); - - -/* CK_UNLOCKMUTEX is an application callback for unlocking a - * mutex */ -typedef CK_CALLBACK_FUNCTION(CK_RV, CK_UNLOCKMUTEX)( - CK_VOID_PTR pMutex /* pointer to mutex */ -); - - -/* CK_C_INITIALIZE_ARGS provides the optional arguments to - * C_Initialize */ -typedef struct CK_C_INITIALIZE_ARGS { - CK_CREATEMUTEX CreateMutex; - CK_DESTROYMUTEX DestroyMutex; - CK_LOCKMUTEX LockMutex; - CK_UNLOCKMUTEX UnlockMutex; - CK_FLAGS flags; - CK_VOID_PTR pReserved; -} CK_C_INITIALIZE_ARGS; - -/* flags: bit flags that provide capabilities of the slot - * Bit Flag Mask Meaning - */ -#define CKF_LIBRARY_CANT_CREATE_OS_THREADS 0x00000001 -#define CKF_OS_LOCKING_OK 0x00000002 - -typedef CK_C_INITIALIZE_ARGS CK_PTR CK_C_INITIALIZE_ARGS_PTR; - - -/* additional flags for parameters to functions */ - -/* CKF_DONT_BLOCK is for the function C_WaitForSlotEvent */ -#define CKF_DONT_BLOCK 1 - -/* CK_RSA_PKCS_OAEP_MGF_TYPE is new for v2.10. - * CK_RSA_PKCS_OAEP_MGF_TYPE is used to indicate the Message - * Generation Function (MGF) applied to a message block when - * formatting a message block for the PKCS #1 OAEP encryption - * scheme. */ -typedef CK_ULONG CK_RSA_PKCS_MGF_TYPE; - -typedef CK_RSA_PKCS_MGF_TYPE CK_PTR CK_RSA_PKCS_MGF_TYPE_PTR; - -/* The following MGFs are defined */ -/* CKG_MGF1_SHA256, CKG_MGF1_SHA384, and CKG_MGF1_SHA512 - * are new for v2.20 */ -#define CKG_MGF1_SHA1 0x00000001 -#define CKG_MGF1_SHA256 0x00000002 -#define CKG_MGF1_SHA384 0x00000003 -#define CKG_MGF1_SHA512 0x00000004 -/* SHA-224 is new for PKCS #11 v2.20 amendment 3 */ -#define CKG_MGF1_SHA224 0x00000005 - -/* CK_RSA_PKCS_OAEP_SOURCE_TYPE is new for v2.10. - * CK_RSA_PKCS_OAEP_SOURCE_TYPE is used to indicate the source - * of the encoding parameter when formatting a message block - * for the PKCS #1 OAEP encryption scheme. */ -typedef CK_ULONG CK_RSA_PKCS_OAEP_SOURCE_TYPE; - -typedef CK_RSA_PKCS_OAEP_SOURCE_TYPE CK_PTR CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR; - -/* The following encoding parameter sources are defined */ -#define CKZ_DATA_SPECIFIED 0x00000001 - -/* CK_RSA_PKCS_OAEP_PARAMS is new for v2.10. - * CK_RSA_PKCS_OAEP_PARAMS provides the parameters to the - * CKM_RSA_PKCS_OAEP mechanism. */ -typedef struct CK_RSA_PKCS_OAEP_PARAMS { - CK_MECHANISM_TYPE hashAlg; - CK_RSA_PKCS_MGF_TYPE mgf; - CK_RSA_PKCS_OAEP_SOURCE_TYPE source; - CK_VOID_PTR pSourceData; - CK_ULONG ulSourceDataLen; -} CK_RSA_PKCS_OAEP_PARAMS; - -typedef CK_RSA_PKCS_OAEP_PARAMS CK_PTR CK_RSA_PKCS_OAEP_PARAMS_PTR; - -/* CK_RSA_PKCS_PSS_PARAMS is new for v2.11. - * CK_RSA_PKCS_PSS_PARAMS provides the parameters to the - * CKM_RSA_PKCS_PSS mechanism(s). */ -typedef struct CK_RSA_PKCS_PSS_PARAMS { - CK_MECHANISM_TYPE hashAlg; - CK_RSA_PKCS_MGF_TYPE mgf; - CK_ULONG sLen; -} CK_RSA_PKCS_PSS_PARAMS; - -typedef CK_RSA_PKCS_PSS_PARAMS CK_PTR CK_RSA_PKCS_PSS_PARAMS_PTR; - -/* CK_EC_KDF_TYPE is new for v2.11. */ -typedef CK_ULONG CK_EC_KDF_TYPE; - -/* The following EC Key Derivation Functions are defined */ -#define CKD_NULL 0x00000001 -#define CKD_SHA1_KDF 0x00000002 - -/* CK_ECDH1_DERIVE_PARAMS is new for v2.11. - * CK_ECDH1_DERIVE_PARAMS provides the parameters to the - * CKM_ECDH1_DERIVE and CKM_ECDH1_COFACTOR_DERIVE mechanisms, - * where each party contributes one key pair. - */ -typedef struct CK_ECDH1_DERIVE_PARAMS { - CK_EC_KDF_TYPE kdf; - CK_ULONG ulSharedDataLen; - CK_BYTE_PTR pSharedData; - CK_ULONG ulPublicDataLen; - CK_BYTE_PTR pPublicData; -} CK_ECDH1_DERIVE_PARAMS; - -typedef CK_ECDH1_DERIVE_PARAMS CK_PTR CK_ECDH1_DERIVE_PARAMS_PTR; - - -/* CK_ECDH2_DERIVE_PARAMS is new for v2.11. - * CK_ECDH2_DERIVE_PARAMS provides the parameters to the - * CKM_ECMQV_DERIVE mechanism, where each party contributes two key pairs. */ -typedef struct CK_ECDH2_DERIVE_PARAMS { - CK_EC_KDF_TYPE kdf; - CK_ULONG ulSharedDataLen; - CK_BYTE_PTR pSharedData; - CK_ULONG ulPublicDataLen; - CK_BYTE_PTR pPublicData; - CK_ULONG ulPrivateDataLen; - CK_OBJECT_HANDLE hPrivateData; - CK_ULONG ulPublicDataLen2; - CK_BYTE_PTR pPublicData2; -} CK_ECDH2_DERIVE_PARAMS; - -typedef CK_ECDH2_DERIVE_PARAMS CK_PTR CK_ECDH2_DERIVE_PARAMS_PTR; - -typedef struct CK_ECMQV_DERIVE_PARAMS { - CK_EC_KDF_TYPE kdf; - CK_ULONG ulSharedDataLen; - CK_BYTE_PTR pSharedData; - CK_ULONG ulPublicDataLen; - CK_BYTE_PTR pPublicData; - CK_ULONG ulPrivateDataLen; - CK_OBJECT_HANDLE hPrivateData; - CK_ULONG ulPublicDataLen2; - CK_BYTE_PTR pPublicData2; - CK_OBJECT_HANDLE publicKey; -} CK_ECMQV_DERIVE_PARAMS; - -typedef CK_ECMQV_DERIVE_PARAMS CK_PTR CK_ECMQV_DERIVE_PARAMS_PTR; - -/* Typedefs and defines for the CKM_X9_42_DH_KEY_PAIR_GEN and the - * CKM_X9_42_DH_PARAMETER_GEN mechanisms (new for PKCS #11 v2.11) */ -typedef CK_ULONG CK_X9_42_DH_KDF_TYPE; -typedef CK_X9_42_DH_KDF_TYPE CK_PTR CK_X9_42_DH_KDF_TYPE_PTR; - -/* The following X9.42 DH key derivation functions are defined - (besides CKD_NULL already defined : */ -#define CKD_SHA1_KDF_ASN1 0x00000003 -#define CKD_SHA1_KDF_CONCATENATE 0x00000004 - -/* CK_X9_42_DH1_DERIVE_PARAMS is new for v2.11. - * CK_X9_42_DH1_DERIVE_PARAMS provides the parameters to the - * CKM_X9_42_DH_DERIVE key derivation mechanism, where each party - * contributes one key pair */ -typedef struct CK_X9_42_DH1_DERIVE_PARAMS { - CK_X9_42_DH_KDF_TYPE kdf; - CK_ULONG ulOtherInfoLen; - CK_BYTE_PTR pOtherInfo; - CK_ULONG ulPublicDataLen; - CK_BYTE_PTR pPublicData; -} CK_X9_42_DH1_DERIVE_PARAMS; - -typedef struct CK_X9_42_DH1_DERIVE_PARAMS CK_PTR CK_X9_42_DH1_DERIVE_PARAMS_PTR; - -/* CK_X9_42_DH2_DERIVE_PARAMS is new for v2.11. - * CK_X9_42_DH2_DERIVE_PARAMS provides the parameters to the - * CKM_X9_42_DH_HYBRID_DERIVE and CKM_X9_42_MQV_DERIVE key derivation - * mechanisms, where each party contributes two key pairs */ -typedef struct CK_X9_42_DH2_DERIVE_PARAMS { - CK_X9_42_DH_KDF_TYPE kdf; - CK_ULONG ulOtherInfoLen; - CK_BYTE_PTR pOtherInfo; - CK_ULONG ulPublicDataLen; - CK_BYTE_PTR pPublicData; - CK_ULONG ulPrivateDataLen; - CK_OBJECT_HANDLE hPrivateData; - CK_ULONG ulPublicDataLen2; - CK_BYTE_PTR pPublicData2; -} CK_X9_42_DH2_DERIVE_PARAMS; - -typedef CK_X9_42_DH2_DERIVE_PARAMS CK_PTR CK_X9_42_DH2_DERIVE_PARAMS_PTR; - -typedef struct CK_X9_42_MQV_DERIVE_PARAMS { - CK_X9_42_DH_KDF_TYPE kdf; - CK_ULONG ulOtherInfoLen; - CK_BYTE_PTR pOtherInfo; - CK_ULONG ulPublicDataLen; - CK_BYTE_PTR pPublicData; - CK_ULONG ulPrivateDataLen; - CK_OBJECT_HANDLE hPrivateData; - CK_ULONG ulPublicDataLen2; - CK_BYTE_PTR pPublicData2; - CK_OBJECT_HANDLE publicKey; -} CK_X9_42_MQV_DERIVE_PARAMS; - -typedef CK_X9_42_MQV_DERIVE_PARAMS CK_PTR CK_X9_42_MQV_DERIVE_PARAMS_PTR; - -/* CK_KEA_DERIVE_PARAMS provides the parameters to the - * CKM_KEA_DERIVE mechanism */ -/* CK_KEA_DERIVE_PARAMS is new for v2.0 */ -typedef struct CK_KEA_DERIVE_PARAMS { - CK_BBOOL isSender; - CK_ULONG ulRandomLen; - CK_BYTE_PTR pRandomA; - CK_BYTE_PTR pRandomB; - CK_ULONG ulPublicDataLen; - CK_BYTE_PTR pPublicData; -} CK_KEA_DERIVE_PARAMS; - -typedef CK_KEA_DERIVE_PARAMS CK_PTR CK_KEA_DERIVE_PARAMS_PTR; - - -/* CK_RC2_PARAMS provides the parameters to the CKM_RC2_ECB and - * CKM_RC2_MAC mechanisms. An instance of CK_RC2_PARAMS just - * holds the effective keysize */ -typedef CK_ULONG CK_RC2_PARAMS; - -typedef CK_RC2_PARAMS CK_PTR CK_RC2_PARAMS_PTR; - - -/* CK_RC2_CBC_PARAMS provides the parameters to the CKM_RC2_CBC - * mechanism */ -typedef struct CK_RC2_CBC_PARAMS { - /* ulEffectiveBits was changed from CK_USHORT to CK_ULONG for - * v2.0 */ - CK_ULONG ulEffectiveBits; /* effective bits (1-1024) */ - - CK_BYTE iv[8]; /* IV for CBC mode */ -} CK_RC2_CBC_PARAMS; - -typedef CK_RC2_CBC_PARAMS CK_PTR CK_RC2_CBC_PARAMS_PTR; - - -/* CK_RC2_MAC_GENERAL_PARAMS provides the parameters for the - * CKM_RC2_MAC_GENERAL mechanism */ -/* CK_RC2_MAC_GENERAL_PARAMS is new for v2.0 */ -typedef struct CK_RC2_MAC_GENERAL_PARAMS { - CK_ULONG ulEffectiveBits; /* effective bits (1-1024) */ - CK_ULONG ulMacLength; /* Length of MAC in bytes */ -} CK_RC2_MAC_GENERAL_PARAMS; - -typedef CK_RC2_MAC_GENERAL_PARAMS CK_PTR \ - CK_RC2_MAC_GENERAL_PARAMS_PTR; - - -/* CK_RC5_PARAMS provides the parameters to the CKM_RC5_ECB and - * CKM_RC5_MAC mechanisms */ -/* CK_RC5_PARAMS is new for v2.0 */ -typedef struct CK_RC5_PARAMS { - CK_ULONG ulWordsize; /* wordsize in bits */ - CK_ULONG ulRounds; /* number of rounds */ -} CK_RC5_PARAMS; - -typedef CK_RC5_PARAMS CK_PTR CK_RC5_PARAMS_PTR; - - -/* CK_RC5_CBC_PARAMS provides the parameters to the CKM_RC5_CBC - * mechanism */ -/* CK_RC5_CBC_PARAMS is new for v2.0 */ -typedef struct CK_RC5_CBC_PARAMS { - CK_ULONG ulWordsize; /* wordsize in bits */ - CK_ULONG ulRounds; /* number of rounds */ - CK_BYTE_PTR pIv; /* pointer to IV */ - CK_ULONG ulIvLen; /* length of IV in bytes */ -} CK_RC5_CBC_PARAMS; - -typedef CK_RC5_CBC_PARAMS CK_PTR CK_RC5_CBC_PARAMS_PTR; - - -/* CK_RC5_MAC_GENERAL_PARAMS provides the parameters for the - * CKM_RC5_MAC_GENERAL mechanism */ -/* CK_RC5_MAC_GENERAL_PARAMS is new for v2.0 */ -typedef struct CK_RC5_MAC_GENERAL_PARAMS { - CK_ULONG ulWordsize; /* wordsize in bits */ - CK_ULONG ulRounds; /* number of rounds */ - CK_ULONG ulMacLength; /* Length of MAC in bytes */ -} CK_RC5_MAC_GENERAL_PARAMS; - -typedef CK_RC5_MAC_GENERAL_PARAMS CK_PTR \ - CK_RC5_MAC_GENERAL_PARAMS_PTR; - - -/* CK_MAC_GENERAL_PARAMS provides the parameters to most block - * ciphers' MAC_GENERAL mechanisms. Its value is the length of - * the MAC */ -/* CK_MAC_GENERAL_PARAMS is new for v2.0 */ -typedef CK_ULONG CK_MAC_GENERAL_PARAMS; - -typedef CK_MAC_GENERAL_PARAMS CK_PTR CK_MAC_GENERAL_PARAMS_PTR; - -/* CK_DES/AES_ECB/CBC_ENCRYPT_DATA_PARAMS are new for v2.20 */ -typedef struct CK_DES_CBC_ENCRYPT_DATA_PARAMS { - CK_BYTE iv[8]; - CK_BYTE_PTR pData; - CK_ULONG length; -} CK_DES_CBC_ENCRYPT_DATA_PARAMS; - -typedef CK_DES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR; - -typedef struct CK_AES_CBC_ENCRYPT_DATA_PARAMS { - CK_BYTE iv[16]; - CK_BYTE_PTR pData; - CK_ULONG length; -} CK_AES_CBC_ENCRYPT_DATA_PARAMS; - -typedef CK_AES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR; - -/* CK_SKIPJACK_PRIVATE_WRAP_PARAMS provides the parameters to the - * CKM_SKIPJACK_PRIVATE_WRAP mechanism */ -/* CK_SKIPJACK_PRIVATE_WRAP_PARAMS is new for v2.0 */ -typedef struct CK_SKIPJACK_PRIVATE_WRAP_PARAMS { - CK_ULONG ulPasswordLen; - CK_BYTE_PTR pPassword; - CK_ULONG ulPublicDataLen; - CK_BYTE_PTR pPublicData; - CK_ULONG ulPAndGLen; - CK_ULONG ulQLen; - CK_ULONG ulRandomLen; - CK_BYTE_PTR pRandomA; - CK_BYTE_PTR pPrimeP; - CK_BYTE_PTR pBaseG; - CK_BYTE_PTR pSubprimeQ; -} CK_SKIPJACK_PRIVATE_WRAP_PARAMS; - -typedef CK_SKIPJACK_PRIVATE_WRAP_PARAMS CK_PTR \ - CK_SKIPJACK_PRIVATE_WRAP_PTR; - - -/* CK_SKIPJACK_RELAYX_PARAMS provides the parameters to the - * CKM_SKIPJACK_RELAYX mechanism */ -/* CK_SKIPJACK_RELAYX_PARAMS is new for v2.0 */ -typedef struct CK_SKIPJACK_RELAYX_PARAMS { - CK_ULONG ulOldWrappedXLen; - CK_BYTE_PTR pOldWrappedX; - CK_ULONG ulOldPasswordLen; - CK_BYTE_PTR pOldPassword; - CK_ULONG ulOldPublicDataLen; - CK_BYTE_PTR pOldPublicData; - CK_ULONG ulOldRandomLen; - CK_BYTE_PTR pOldRandomA; - CK_ULONG ulNewPasswordLen; - CK_BYTE_PTR pNewPassword; - CK_ULONG ulNewPublicDataLen; - CK_BYTE_PTR pNewPublicData; - CK_ULONG ulNewRandomLen; - CK_BYTE_PTR pNewRandomA; -} CK_SKIPJACK_RELAYX_PARAMS; - -typedef CK_SKIPJACK_RELAYX_PARAMS CK_PTR \ - CK_SKIPJACK_RELAYX_PARAMS_PTR; - - -typedef struct CK_PBE_PARAMS { - CK_BYTE_PTR pInitVector; - CK_UTF8CHAR_PTR pPassword; - CK_ULONG ulPasswordLen; - CK_BYTE_PTR pSalt; - CK_ULONG ulSaltLen; - CK_ULONG ulIteration; -} CK_PBE_PARAMS; - -typedef CK_PBE_PARAMS CK_PTR CK_PBE_PARAMS_PTR; - - -/* CK_KEY_WRAP_SET_OAEP_PARAMS provides the parameters to the - * CKM_KEY_WRAP_SET_OAEP mechanism */ -/* CK_KEY_WRAP_SET_OAEP_PARAMS is new for v2.0 */ -typedef struct CK_KEY_WRAP_SET_OAEP_PARAMS { - CK_BYTE bBC; /* block contents byte */ - CK_BYTE_PTR pX; /* extra data */ - CK_ULONG ulXLen; /* length of extra data in bytes */ -} CK_KEY_WRAP_SET_OAEP_PARAMS; - -typedef CK_KEY_WRAP_SET_OAEP_PARAMS CK_PTR \ - CK_KEY_WRAP_SET_OAEP_PARAMS_PTR; - - -typedef struct CK_SSL3_RANDOM_DATA { - CK_BYTE_PTR pClientRandom; - CK_ULONG ulClientRandomLen; - CK_BYTE_PTR pServerRandom; - CK_ULONG ulServerRandomLen; -} CK_SSL3_RANDOM_DATA; - - -typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS { - CK_SSL3_RANDOM_DATA RandomInfo; - CK_VERSION_PTR pVersion; -} CK_SSL3_MASTER_KEY_DERIVE_PARAMS; - -typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS CK_PTR \ - CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR; - - -typedef struct CK_SSL3_KEY_MAT_OUT { - CK_OBJECT_HANDLE hClientMacSecret; - CK_OBJECT_HANDLE hServerMacSecret; - CK_OBJECT_HANDLE hClientKey; - CK_OBJECT_HANDLE hServerKey; - CK_BYTE_PTR pIVClient; - CK_BYTE_PTR pIVServer; -} CK_SSL3_KEY_MAT_OUT; - -typedef CK_SSL3_KEY_MAT_OUT CK_PTR CK_SSL3_KEY_MAT_OUT_PTR; - - -typedef struct CK_SSL3_KEY_MAT_PARAMS { - CK_ULONG ulMacSizeInBits; - CK_ULONG ulKeySizeInBits; - CK_ULONG ulIVSizeInBits; - CK_BBOOL bIsExport; - CK_SSL3_RANDOM_DATA RandomInfo; - CK_SSL3_KEY_MAT_OUT_PTR pReturnedKeyMaterial; -} CK_SSL3_KEY_MAT_PARAMS; - -typedef CK_SSL3_KEY_MAT_PARAMS CK_PTR CK_SSL3_KEY_MAT_PARAMS_PTR; - -/* CK_TLS_PRF_PARAMS is new for version 2.20 */ -typedef struct CK_TLS_PRF_PARAMS { - CK_BYTE_PTR pSeed; - CK_ULONG ulSeedLen; - CK_BYTE_PTR pLabel; - CK_ULONG ulLabelLen; - CK_BYTE_PTR pOutput; - CK_ULONG_PTR pulOutputLen; -} CK_TLS_PRF_PARAMS; - -typedef CK_TLS_PRF_PARAMS CK_PTR CK_TLS_PRF_PARAMS_PTR; - -/* WTLS is new for version 2.20 */ -typedef struct CK_WTLS_RANDOM_DATA { - CK_BYTE_PTR pClientRandom; - CK_ULONG ulClientRandomLen; - CK_BYTE_PTR pServerRandom; - CK_ULONG ulServerRandomLen; -} CK_WTLS_RANDOM_DATA; - -typedef CK_WTLS_RANDOM_DATA CK_PTR CK_WTLS_RANDOM_DATA_PTR; - -typedef struct CK_WTLS_MASTER_KEY_DERIVE_PARAMS { - CK_MECHANISM_TYPE DigestMechanism; - CK_WTLS_RANDOM_DATA RandomInfo; - CK_BYTE_PTR pVersion; -} CK_WTLS_MASTER_KEY_DERIVE_PARAMS; - -typedef CK_WTLS_MASTER_KEY_DERIVE_PARAMS CK_PTR \ - CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR; - -typedef struct CK_WTLS_PRF_PARAMS { - CK_MECHANISM_TYPE DigestMechanism; - CK_BYTE_PTR pSeed; - CK_ULONG ulSeedLen; - CK_BYTE_PTR pLabel; - CK_ULONG ulLabelLen; - CK_BYTE_PTR pOutput; - CK_ULONG_PTR pulOutputLen; -} CK_WTLS_PRF_PARAMS; - -typedef CK_WTLS_PRF_PARAMS CK_PTR CK_WTLS_PRF_PARAMS_PTR; - -typedef struct CK_WTLS_KEY_MAT_OUT { - CK_OBJECT_HANDLE hMacSecret; - CK_OBJECT_HANDLE hKey; - CK_BYTE_PTR pIV; -} CK_WTLS_KEY_MAT_OUT; - -typedef CK_WTLS_KEY_MAT_OUT CK_PTR CK_WTLS_KEY_MAT_OUT_PTR; - -typedef struct CK_WTLS_KEY_MAT_PARAMS { - CK_MECHANISM_TYPE DigestMechanism; - CK_ULONG ulMacSizeInBits; - CK_ULONG ulKeySizeInBits; - CK_ULONG ulIVSizeInBits; - CK_ULONG ulSequenceNumber; - CK_BBOOL bIsExport; - CK_WTLS_RANDOM_DATA RandomInfo; - CK_WTLS_KEY_MAT_OUT_PTR pReturnedKeyMaterial; -} CK_WTLS_KEY_MAT_PARAMS; - -typedef CK_WTLS_KEY_MAT_PARAMS CK_PTR CK_WTLS_KEY_MAT_PARAMS_PTR; - -/* CMS is new for version 2.20 */ -typedef struct CK_CMS_SIG_PARAMS { - CK_OBJECT_HANDLE certificateHandle; - CK_MECHANISM_PTR pSigningMechanism; - CK_MECHANISM_PTR pDigestMechanism; - CK_UTF8CHAR_PTR pContentType; - CK_BYTE_PTR pRequestedAttributes; - CK_ULONG ulRequestedAttributesLen; - CK_BYTE_PTR pRequiredAttributes; - CK_ULONG ulRequiredAttributesLen; -} CK_CMS_SIG_PARAMS; - -typedef CK_CMS_SIG_PARAMS CK_PTR CK_CMS_SIG_PARAMS_PTR; - -typedef struct CK_KEY_DERIVATION_STRING_DATA { - CK_BYTE_PTR pData; - CK_ULONG ulLen; -} CK_KEY_DERIVATION_STRING_DATA; - -typedef CK_KEY_DERIVATION_STRING_DATA CK_PTR \ - CK_KEY_DERIVATION_STRING_DATA_PTR; - - -/* The CK_EXTRACT_PARAMS is used for the - * CKM_EXTRACT_KEY_FROM_KEY mechanism. It specifies which bit - * of the base key should be used as the first bit of the - * derived key */ -/* CK_EXTRACT_PARAMS is new for v2.0 */ -typedef CK_ULONG CK_EXTRACT_PARAMS; - -typedef CK_EXTRACT_PARAMS CK_PTR CK_EXTRACT_PARAMS_PTR; - -/* CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is new for v2.10. - * CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is used to - * indicate the Pseudo-Random Function (PRF) used to generate - * key bits using PKCS #5 PBKDF2. */ -typedef CK_ULONG CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE; - -typedef CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE CK_PTR CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR; - -/* The following PRFs are defined in PKCS #5 v2.0. */ -#define CKP_PKCS5_PBKD2_HMAC_SHA1 0x00000001 - - -/* CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is new for v2.10. - * CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is used to indicate the - * source of the salt value when deriving a key using PKCS #5 - * PBKDF2. */ -typedef CK_ULONG CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE; - -typedef CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE CK_PTR CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR; - -/* The following salt value sources are defined in PKCS #5 v2.0. */ -#define CKZ_SALT_SPECIFIED 0x00000001 - -/* CK_PKCS5_PBKD2_PARAMS is new for v2.10. - * CK_PKCS5_PBKD2_PARAMS is a structure that provides the - * parameters to the CKM_PKCS5_PBKD2 mechanism. */ -typedef struct CK_PKCS5_PBKD2_PARAMS { - CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE saltSource; - CK_VOID_PTR pSaltSourceData; - CK_ULONG ulSaltSourceDataLen; - CK_ULONG iterations; - CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE prf; - CK_VOID_PTR pPrfData; - CK_ULONG ulPrfDataLen; - CK_UTF8CHAR_PTR pPassword; - CK_ULONG_PTR ulPasswordLen; -} CK_PKCS5_PBKD2_PARAMS; - -typedef CK_PKCS5_PBKD2_PARAMS CK_PTR CK_PKCS5_PBKD2_PARAMS_PTR; - -/* All CK_OTP structs are new for PKCS #11 v2.20 amendment 3 */ - -typedef CK_ULONG CK_OTP_PARAM_TYPE; -typedef CK_OTP_PARAM_TYPE CK_PARAM_TYPE; /* B/w compatibility */ - -typedef struct CK_OTP_PARAM { - CK_OTP_PARAM_TYPE type; - CK_VOID_PTR pValue; - CK_ULONG ulValueLen; -} CK_OTP_PARAM; - -typedef CK_OTP_PARAM CK_PTR CK_OTP_PARAM_PTR; - -typedef struct CK_OTP_PARAMS { - CK_OTP_PARAM_PTR pParams; - CK_ULONG ulCount; -} CK_OTP_PARAMS; - -typedef CK_OTP_PARAMS CK_PTR CK_OTP_PARAMS_PTR; - -typedef struct CK_OTP_SIGNATURE_INFO { - CK_OTP_PARAM_PTR pParams; - CK_ULONG ulCount; -} CK_OTP_SIGNATURE_INFO; - -typedef CK_OTP_SIGNATURE_INFO CK_PTR CK_OTP_SIGNATURE_INFO_PTR; - -/* The following OTP-related defines are new for PKCS #11 v2.20 amendment 1 */ -#define CK_OTP_VALUE 0 -#define CK_OTP_PIN 1 -#define CK_OTP_CHALLENGE 2 -#define CK_OTP_TIME 3 -#define CK_OTP_COUNTER 4 -#define CK_OTP_FLAGS 5 -#define CK_OTP_OUTPUT_LENGTH 6 -#define CK_OTP_OUTPUT_FORMAT 7 - -/* The following OTP-related defines are new for PKCS #11 v2.20 amendment 1 */ -#define CKF_NEXT_OTP 0x00000001 -#define CKF_EXCLUDE_TIME 0x00000002 -#define CKF_EXCLUDE_COUNTER 0x00000004 -#define CKF_EXCLUDE_CHALLENGE 0x00000008 -#define CKF_EXCLUDE_PIN 0x00000010 -#define CKF_USER_FRIENDLY_OTP 0x00000020 - -/* CK_KIP_PARAMS is new for PKCS #11 v2.20 amendment 2 */ -typedef struct CK_KIP_PARAMS { - CK_MECHANISM_PTR pMechanism; - CK_OBJECT_HANDLE hKey; - CK_BYTE_PTR pSeed; - CK_ULONG ulSeedLen; -} CK_KIP_PARAMS; - -typedef CK_KIP_PARAMS CK_PTR CK_KIP_PARAMS_PTR; - -/* CK_AES_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */ -typedef struct CK_AES_CTR_PARAMS { - CK_ULONG ulCounterBits; - CK_BYTE cb[16]; -} CK_AES_CTR_PARAMS; - -typedef CK_AES_CTR_PARAMS CK_PTR CK_AES_CTR_PARAMS_PTR; - -/* CK_CAMELLIA_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */ -typedef struct CK_CAMELLIA_CTR_PARAMS { - CK_ULONG ulCounterBits; - CK_BYTE cb[16]; -} CK_CAMELLIA_CTR_PARAMS; - -typedef CK_CAMELLIA_CTR_PARAMS CK_PTR CK_CAMELLIA_CTR_PARAMS_PTR; - -/* CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS is new for PKCS #11 v2.20 amendment 3 */ -typedef struct CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS { - CK_BYTE iv[16]; - CK_BYTE_PTR pData; - CK_ULONG length; -} CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS; - -typedef CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR; - -/* CK_ARIA_CBC_ENCRYPT_DATA_PARAMS is new for PKCS #11 v2.20 amendment 3 */ -typedef struct CK_ARIA_CBC_ENCRYPT_DATA_PARAMS { - CK_BYTE iv[16]; - CK_BYTE_PTR pData; - CK_ULONG length; -} CK_ARIA_CBC_ENCRYPT_DATA_PARAMS; - -typedef CK_ARIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR; - -#endif +/* pkcs11t.h include file for PKCS #11. */ +/* $Revision: 1.10 $ */ + +/* License to copy and use this software is granted provided that it is + * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface + * (Cryptoki)" in all material mentioning or referencing this software. + + * License is also granted to make and use derivative works provided that + * such works are identified as "derived from the RSA Security Inc. PKCS #11 + * Cryptographic Token Interface (Cryptoki)" in all material mentioning or + * referencing the derived work. + + * RSA Security Inc. makes no representations concerning either the + * merchantability of this software or the suitability of this software for + * any particular purpose. It is provided "as is" without express or implied + * warranty of any kind. + */ + +/* See top of pkcs11.h for information about the macros that + * must be defined and the structure-packing conventions that + * must be set before including this file. */ + +#ifndef _PKCS11T_H_ +#define _PKCS11T_H_ 1 + +#define CRYPTOKI_VERSION_MAJOR 2 +#define CRYPTOKI_VERSION_MINOR 20 +#define CRYPTOKI_VERSION_AMENDMENT 3 + +#define CK_TRUE 1 +#define CK_FALSE 0 + +#ifndef CK_DISABLE_TRUE_FALSE +#ifndef FALSE +#define FALSE CK_FALSE +#endif + +#ifndef TRUE +#define TRUE CK_TRUE +#endif +#endif + +/* an unsigned 8-bit value */ +typedef unsigned char CK_BYTE; + +/* an unsigned 8-bit character */ +typedef CK_BYTE CK_CHAR; + +/* an 8-bit UTF-8 character */ +typedef CK_BYTE CK_UTF8CHAR; + +/* a BYTE-sized Boolean flag */ +typedef CK_BYTE CK_BBOOL; + +/* an unsigned value, at least 32 bits long */ +typedef unsigned long int CK_ULONG; + +/* a signed value, the same size as a CK_ULONG */ +/* CK_LONG is new for v2.0 */ +typedef long int CK_LONG; + +/* at least 32 bits; each bit is a Boolean flag */ +typedef CK_ULONG CK_FLAGS; + + +/* some special values for certain CK_ULONG variables */ +#define CK_UNAVAILABLE_INFORMATION (~0UL) +#define CK_EFFECTIVELY_INFINITE 0 + + +typedef CK_BYTE CK_PTR CK_BYTE_PTR; +typedef CK_CHAR CK_PTR CK_CHAR_PTR; +typedef CK_UTF8CHAR CK_PTR CK_UTF8CHAR_PTR; +typedef CK_ULONG CK_PTR CK_ULONG_PTR; +typedef void CK_PTR CK_VOID_PTR; + +/* Pointer to a CK_VOID_PTR-- i.e., pointer to pointer to void */ +typedef CK_VOID_PTR CK_PTR CK_VOID_PTR_PTR; + + +/* The following value is always invalid if used as a session */ +/* handle or object handle */ +#define CK_INVALID_HANDLE 0 + + +typedef struct CK_VERSION { + CK_BYTE major; /* integer portion of version number */ + CK_BYTE minor; /* 1/100ths portion of version number */ +} CK_VERSION; + +typedef CK_VERSION CK_PTR CK_VERSION_PTR; + + +typedef struct CK_INFO { + /* manufacturerID and libraryDecription have been changed from + * CK_CHAR to CK_UTF8CHAR for v2.10 */ + CK_VERSION cryptokiVersion; /* Cryptoki interface ver */ + CK_UTF8CHAR manufacturerID[32]; /* blank padded */ + CK_FLAGS flags; /* must be zero */ + + /* libraryDescription and libraryVersion are new for v2.0 */ + CK_UTF8CHAR libraryDescription[32]; /* blank padded */ + CK_VERSION libraryVersion; /* version of library */ +} CK_INFO; + +typedef CK_INFO CK_PTR CK_INFO_PTR; + + +/* CK_NOTIFICATION enumerates the types of notifications that + * Cryptoki provides to an application */ +/* CK_NOTIFICATION has been changed from an enum to a CK_ULONG + * for v2.0 */ +typedef CK_ULONG CK_NOTIFICATION; +#define CKN_SURRENDER 0 + +/* The following notification is new for PKCS #11 v2.20 amendment 3 */ +#define CKN_OTP_CHANGED 1 + + +typedef CK_ULONG CK_SLOT_ID; + +typedef CK_SLOT_ID CK_PTR CK_SLOT_ID_PTR; + + +/* CK_SLOT_INFO provides information about a slot */ +typedef struct CK_SLOT_INFO { + /* slotDescription and manufacturerID have been changed from + * CK_CHAR to CK_UTF8CHAR for v2.10 */ + CK_UTF8CHAR slotDescription[64]; /* blank padded */ + CK_UTF8CHAR manufacturerID[32]; /* blank padded */ + CK_FLAGS flags; + + /* hardwareVersion and firmwareVersion are new for v2.0 */ + CK_VERSION hardwareVersion; /* version of hardware */ + CK_VERSION firmwareVersion; /* version of firmware */ +} CK_SLOT_INFO; + +/* flags: bit flags that provide capabilities of the slot + * Bit Flag Mask Meaning + */ +#define CKF_TOKEN_PRESENT 0x00000001 /* a token is there */ +#define CKF_REMOVABLE_DEVICE 0x00000002 /* removable devices*/ +#define CKF_HW_SLOT 0x00000004 /* hardware slot */ + +typedef CK_SLOT_INFO CK_PTR CK_SLOT_INFO_PTR; + + +/* CK_TOKEN_INFO provides information about a token */ +typedef struct CK_TOKEN_INFO { + /* label, manufacturerID, and model have been changed from + * CK_CHAR to CK_UTF8CHAR for v2.10 */ + CK_UTF8CHAR label[32]; /* blank padded */ + CK_UTF8CHAR manufacturerID[32]; /* blank padded */ + CK_UTF8CHAR model[16]; /* blank padded */ + CK_CHAR serialNumber[16]; /* blank padded */ + CK_FLAGS flags; /* see below */ + + /* ulMaxSessionCount, ulSessionCount, ulMaxRwSessionCount, + * ulRwSessionCount, ulMaxPinLen, and ulMinPinLen have all been + * changed from CK_USHORT to CK_ULONG for v2.0 */ + CK_ULONG ulMaxSessionCount; /* max open sessions */ + CK_ULONG ulSessionCount; /* sess. now open */ + CK_ULONG ulMaxRwSessionCount; /* max R/W sessions */ + CK_ULONG ulRwSessionCount; /* R/W sess. now open */ + CK_ULONG ulMaxPinLen; /* in bytes */ + CK_ULONG ulMinPinLen; /* in bytes */ + CK_ULONG ulTotalPublicMemory; /* in bytes */ + CK_ULONG ulFreePublicMemory; /* in bytes */ + CK_ULONG ulTotalPrivateMemory; /* in bytes */ + CK_ULONG ulFreePrivateMemory; /* in bytes */ + + /* hardwareVersion, firmwareVersion, and time are new for + * v2.0 */ + CK_VERSION hardwareVersion; /* version of hardware */ + CK_VERSION firmwareVersion; /* version of firmware */ + CK_CHAR utcTime[16]; /* time */ +} CK_TOKEN_INFO; + +/* The flags parameter is defined as follows: + * Bit Flag Mask Meaning + */ +#define CKF_RNG 0x00000001 /* has random # + * generator */ +#define CKF_WRITE_PROTECTED 0x00000002 /* token is + * write- + * protected */ +#define CKF_LOGIN_REQUIRED 0x00000004 /* user must + * login */ +#define CKF_USER_PIN_INITIALIZED 0x00000008 /* normal user's + * PIN is set */ + +/* CKF_RESTORE_KEY_NOT_NEEDED is new for v2.0. If it is set, + * that means that *every* time the state of cryptographic + * operations of a session is successfully saved, all keys + * needed to continue those operations are stored in the state */ +#define CKF_RESTORE_KEY_NOT_NEEDED 0x00000020 + +/* CKF_CLOCK_ON_TOKEN is new for v2.0. If it is set, that means + * that the token has some sort of clock. The time on that + * clock is returned in the token info structure */ +#define CKF_CLOCK_ON_TOKEN 0x00000040 + +/* CKF_PROTECTED_AUTHENTICATION_PATH is new for v2.0. If it is + * set, that means that there is some way for the user to login + * without sending a PIN through the Cryptoki library itself */ +#define CKF_PROTECTED_AUTHENTICATION_PATH 0x00000100 + +/* CKF_DUAL_CRYPTO_OPERATIONS is new for v2.0. If it is true, + * that means that a single session with the token can perform + * dual simultaneous cryptographic operations (digest and + * encrypt; decrypt and digest; sign and encrypt; and decrypt + * and sign) */ +#define CKF_DUAL_CRYPTO_OPERATIONS 0x00000200 + +/* CKF_TOKEN_INITIALIZED if new for v2.10. If it is true, the + * token has been initialized using C_InitializeToken or an + * equivalent mechanism outside the scope of PKCS #11. + * Calling C_InitializeToken when this flag is set will cause + * the token to be reinitialized. */ +#define CKF_TOKEN_INITIALIZED 0x00000400 + +/* CKF_SECONDARY_AUTHENTICATION if new for v2.10. If it is + * true, the token supports secondary authentication for + * private key objects. This flag is deprecated in v2.11 and + onwards. */ +#define CKF_SECONDARY_AUTHENTICATION 0x00000800 + +/* CKF_USER_PIN_COUNT_LOW if new for v2.10. If it is true, an + * incorrect user login PIN has been entered at least once + * since the last successful authentication. */ +#define CKF_USER_PIN_COUNT_LOW 0x00010000 + +/* CKF_USER_PIN_FINAL_TRY if new for v2.10. If it is true, + * supplying an incorrect user PIN will it to become locked. */ +#define CKF_USER_PIN_FINAL_TRY 0x00020000 + +/* CKF_USER_PIN_LOCKED if new for v2.10. If it is true, the + * user PIN has been locked. User login to the token is not + * possible. */ +#define CKF_USER_PIN_LOCKED 0x00040000 + +/* CKF_USER_PIN_TO_BE_CHANGED if new for v2.10. If it is true, + * the user PIN value is the default value set by token + * initialization or manufacturing, or the PIN has been + * expired by the card. */ +#define CKF_USER_PIN_TO_BE_CHANGED 0x00080000 + +/* CKF_SO_PIN_COUNT_LOW if new for v2.10. If it is true, an + * incorrect SO login PIN has been entered at least once since + * the last successful authentication. */ +#define CKF_SO_PIN_COUNT_LOW 0x00100000 + +/* CKF_SO_PIN_FINAL_TRY if new for v2.10. If it is true, + * supplying an incorrect SO PIN will it to become locked. */ +#define CKF_SO_PIN_FINAL_TRY 0x00200000 + +/* CKF_SO_PIN_LOCKED if new for v2.10. If it is true, the SO + * PIN has been locked. SO login to the token is not possible. + */ +#define CKF_SO_PIN_LOCKED 0x00400000 + +/* CKF_SO_PIN_TO_BE_CHANGED if new for v2.10. If it is true, + * the SO PIN value is the default value set by token + * initialization or manufacturing, or the PIN has been + * expired by the card. */ +#define CKF_SO_PIN_TO_BE_CHANGED 0x00800000 + +typedef CK_TOKEN_INFO CK_PTR CK_TOKEN_INFO_PTR; + + +/* CK_SESSION_HANDLE is a Cryptoki-assigned value that + * identifies a session */ +typedef CK_ULONG CK_SESSION_HANDLE; + +typedef CK_SESSION_HANDLE CK_PTR CK_SESSION_HANDLE_PTR; + + +/* CK_USER_TYPE enumerates the types of Cryptoki users */ +/* CK_USER_TYPE has been changed from an enum to a CK_ULONG for + * v2.0 */ +typedef CK_ULONG CK_USER_TYPE; +/* Security Officer */ +#define CKU_SO 0 +/* Normal user */ +#define CKU_USER 1 +/* Context specific (added in v2.20) */ +#define CKU_CONTEXT_SPECIFIC 2 + +/* CK_STATE enumerates the session states */ +/* CK_STATE has been changed from an enum to a CK_ULONG for + * v2.0 */ +typedef CK_ULONG CK_STATE; +#define CKS_RO_PUBLIC_SESSION 0 +#define CKS_RO_USER_FUNCTIONS 1 +#define CKS_RW_PUBLIC_SESSION 2 +#define CKS_RW_USER_FUNCTIONS 3 +#define CKS_RW_SO_FUNCTIONS 4 + + +/* CK_SESSION_INFO provides information about a session */ +typedef struct CK_SESSION_INFO { + CK_SLOT_ID slotID; + CK_STATE state; + CK_FLAGS flags; /* see below */ + + /* ulDeviceError was changed from CK_USHORT to CK_ULONG for + * v2.0 */ + CK_ULONG ulDeviceError; /* device-dependent error code */ +} CK_SESSION_INFO; + +/* The flags are defined in the following table: + * Bit Flag Mask Meaning + */ +#define CKF_RW_SESSION 0x00000002 /* session is r/w */ +#define CKF_SERIAL_SESSION 0x00000004 /* no parallel */ + +typedef CK_SESSION_INFO CK_PTR CK_SESSION_INFO_PTR; + + +/* CK_OBJECT_HANDLE is a token-specific identifier for an + * object */ +typedef CK_ULONG CK_OBJECT_HANDLE; + +typedef CK_OBJECT_HANDLE CK_PTR CK_OBJECT_HANDLE_PTR; + + +/* CK_OBJECT_CLASS is a value that identifies the classes (or + * types) of objects that Cryptoki recognizes. It is defined + * as follows: */ +/* CK_OBJECT_CLASS was changed from CK_USHORT to CK_ULONG for + * v2.0 */ +typedef CK_ULONG CK_OBJECT_CLASS; + +/* The following classes of objects are defined: */ +/* CKO_HW_FEATURE is new for v2.10 */ +/* CKO_DOMAIN_PARAMETERS is new for v2.11 */ +/* CKO_MECHANISM is new for v2.20 */ +#define CKO_DATA 0x00000000 +#define CKO_CERTIFICATE 0x00000001 +#define CKO_PUBLIC_KEY 0x00000002 +#define CKO_PRIVATE_KEY 0x00000003 +#define CKO_SECRET_KEY 0x00000004 +#define CKO_HW_FEATURE 0x00000005 +#define CKO_DOMAIN_PARAMETERS 0x00000006 +#define CKO_MECHANISM 0x00000007 + +/* CKO_OTP_KEY is new for PKCS #11 v2.20 amendment 1 */ +#define CKO_OTP_KEY 0x00000008 + +#define CKO_VENDOR_DEFINED 0x80000000 + +typedef CK_OBJECT_CLASS CK_PTR CK_OBJECT_CLASS_PTR; + +/* CK_HW_FEATURE_TYPE is new for v2.10. CK_HW_FEATURE_TYPE is a + * value that identifies the hardware feature type of an object + * with CK_OBJECT_CLASS equal to CKO_HW_FEATURE. */ +typedef CK_ULONG CK_HW_FEATURE_TYPE; + +/* The following hardware feature types are defined */ +/* CKH_USER_INTERFACE is new for v2.20 */ +#define CKH_MONOTONIC_COUNTER 0x00000001 +#define CKH_CLOCK 0x00000002 +#define CKH_USER_INTERFACE 0x00000003 +#define CKH_VENDOR_DEFINED 0x80000000 + +/* CK_KEY_TYPE is a value that identifies a key type */ +/* CK_KEY_TYPE was changed from CK_USHORT to CK_ULONG for v2.0 */ +typedef CK_ULONG CK_KEY_TYPE; + +/* the following key types are defined: */ +#define CKK_RSA 0x00000000 +#define CKK_DSA 0x00000001 +#define CKK_DH 0x00000002 + +/* CKK_ECDSA and CKK_KEA are new for v2.0 */ +/* CKK_ECDSA is deprecated in v2.11, CKK_EC is preferred. */ +#define CKK_ECDSA 0x00000003 +#define CKK_EC 0x00000003 +#define CKK_X9_42_DH 0x00000004 +#define CKK_KEA 0x00000005 + +#define CKK_GENERIC_SECRET 0x00000010 +#define CKK_RC2 0x00000011 +#define CKK_RC4 0x00000012 +#define CKK_DES 0x00000013 +#define CKK_DES2 0x00000014 +#define CKK_DES3 0x00000015 + +/* all these key types are new for v2.0 */ +#define CKK_CAST 0x00000016 +#define CKK_CAST3 0x00000017 +/* CKK_CAST5 is deprecated in v2.11, CKK_CAST128 is preferred. */ +#define CKK_CAST5 0x00000018 +#define CKK_CAST128 0x00000018 +#define CKK_RC5 0x00000019 +#define CKK_IDEA 0x0000001A +#define CKK_SKIPJACK 0x0000001B +#define CKK_BATON 0x0000001C +#define CKK_JUNIPER 0x0000001D +#define CKK_CDMF 0x0000001E +#define CKK_AES 0x0000001F + +/* BlowFish and TwoFish are new for v2.20 */ +#define CKK_BLOWFISH 0x00000020 +#define CKK_TWOFISH 0x00000021 + +/* SecurID, HOTP, and ACTI are new for PKCS #11 v2.20 amendment 1 */ +#define CKK_SECURID 0x00000022 +#define CKK_HOTP 0x00000023 +#define CKK_ACTI 0x00000024 + +/* Camellia is new for PKCS #11 v2.20 amendment 3 */ +#define CKK_CAMELLIA 0x00000025 +/* ARIA is new for PKCS #11 v2.20 amendment 3 */ +#define CKK_ARIA 0x00000026 + + +#define CKK_VENDOR_DEFINED 0x80000000 + + +/* CK_CERTIFICATE_TYPE is a value that identifies a certificate + * type */ +/* CK_CERTIFICATE_TYPE was changed from CK_USHORT to CK_ULONG + * for v2.0 */ +typedef CK_ULONG CK_CERTIFICATE_TYPE; + +/* The following certificate types are defined: */ +/* CKC_X_509_ATTR_CERT is new for v2.10 */ +/* CKC_WTLS is new for v2.20 */ +#define CKC_X_509 0x00000000 +#define CKC_X_509_ATTR_CERT 0x00000001 +#define CKC_WTLS 0x00000002 +#define CKC_VENDOR_DEFINED 0x80000000 + + +/* CK_ATTRIBUTE_TYPE is a value that identifies an attribute + * type */ +/* CK_ATTRIBUTE_TYPE was changed from CK_USHORT to CK_ULONG for + * v2.0 */ +typedef CK_ULONG CK_ATTRIBUTE_TYPE; + +/* The CKF_ARRAY_ATTRIBUTE flag identifies an attribute which + consists of an array of values. */ +#define CKF_ARRAY_ATTRIBUTE 0x40000000 + +/* The following OTP-related defines are new for PKCS #11 v2.20 amendment 1 + and relates to the CKA_OTP_FORMAT attribute */ +#define CK_OTP_FORMAT_DECIMAL 0 +#define CK_OTP_FORMAT_HEXADECIMAL 1 +#define CK_OTP_FORMAT_ALPHANUMERIC 2 +#define CK_OTP_FORMAT_BINARY 3 + +/* The following OTP-related defines are new for PKCS #11 v2.20 amendment 1 + and relates to the CKA_OTP_..._REQUIREMENT attributes */ +#define CK_OTP_PARAM_IGNORED 0 +#define CK_OTP_PARAM_OPTIONAL 1 +#define CK_OTP_PARAM_MANDATORY 2 + +/* The following attribute types are defined: */ +#define CKA_CLASS 0x00000000 +#define CKA_TOKEN 0x00000001 +#define CKA_PRIVATE 0x00000002 +#define CKA_LABEL 0x00000003 +#define CKA_APPLICATION 0x00000010 +#define CKA_VALUE 0x00000011 + +/* CKA_OBJECT_ID is new for v2.10 */ +#define CKA_OBJECT_ID 0x00000012 + +#define CKA_CERTIFICATE_TYPE 0x00000080 +#define CKA_ISSUER 0x00000081 +#define CKA_SERIAL_NUMBER 0x00000082 + +/* CKA_AC_ISSUER, CKA_OWNER, and CKA_ATTR_TYPES are new + * for v2.10 */ +#define CKA_AC_ISSUER 0x00000083 +#define CKA_OWNER 0x00000084 +#define CKA_ATTR_TYPES 0x00000085 + +/* CKA_TRUSTED is new for v2.11 */ +#define CKA_TRUSTED 0x00000086 + +/* CKA_CERTIFICATE_CATEGORY ... + * CKA_CHECK_VALUE are new for v2.20 */ +#define CKA_CERTIFICATE_CATEGORY 0x00000087 +#define CKA_JAVA_MIDP_SECURITY_DOMAIN 0x00000088 +#define CKA_URL 0x00000089 +#define CKA_HASH_OF_SUBJECT_PUBLIC_KEY 0x0000008A +#define CKA_HASH_OF_ISSUER_PUBLIC_KEY 0x0000008B +#define CKA_CHECK_VALUE 0x00000090 + +#define CKA_KEY_TYPE 0x00000100 +#define CKA_SUBJECT 0x00000101 +#define CKA_ID 0x00000102 +#define CKA_SENSITIVE 0x00000103 +#define CKA_ENCRYPT 0x00000104 +#define CKA_DECRYPT 0x00000105 +#define CKA_WRAP 0x00000106 +#define CKA_UNWRAP 0x00000107 +#define CKA_SIGN 0x00000108 +#define CKA_SIGN_RECOVER 0x00000109 +#define CKA_VERIFY 0x0000010A +#define CKA_VERIFY_RECOVER 0x0000010B +#define CKA_DERIVE 0x0000010C +#define CKA_START_DATE 0x00000110 +#define CKA_END_DATE 0x00000111 +#define CKA_MODULUS 0x00000120 +#define CKA_MODULUS_BITS 0x00000121 +#define CKA_PUBLIC_EXPONENT 0x00000122 +#define CKA_PRIVATE_EXPONENT 0x00000123 +#define CKA_PRIME_1 0x00000124 +#define CKA_PRIME_2 0x00000125 +#define CKA_EXPONENT_1 0x00000126 +#define CKA_EXPONENT_2 0x00000127 +#define CKA_COEFFICIENT 0x00000128 +#define CKA_PRIME 0x00000130 +#define CKA_SUBPRIME 0x00000131 +#define CKA_BASE 0x00000132 + +/* CKA_PRIME_BITS and CKA_SUB_PRIME_BITS are new for v2.11 */ +#define CKA_PRIME_BITS 0x00000133 +#define CKA_SUBPRIME_BITS 0x00000134 +#define CKA_SUB_PRIME_BITS CKA_SUBPRIME_BITS +/* (To retain backwards-compatibility) */ + +#define CKA_VALUE_BITS 0x00000160 +#define CKA_VALUE_LEN 0x00000161 + +/* CKA_EXTRACTABLE, CKA_LOCAL, CKA_NEVER_EXTRACTABLE, + * CKA_ALWAYS_SENSITIVE, CKA_MODIFIABLE, CKA_ECDSA_PARAMS, + * and CKA_EC_POINT are new for v2.0 */ +#define CKA_EXTRACTABLE 0x00000162 +#define CKA_LOCAL 0x00000163 +#define CKA_NEVER_EXTRACTABLE 0x00000164 +#define CKA_ALWAYS_SENSITIVE 0x00000165 + +/* CKA_KEY_GEN_MECHANISM is new for v2.11 */ +#define CKA_KEY_GEN_MECHANISM 0x00000166 + +#define CKA_MODIFIABLE 0x00000170 + +/* CKA_ECDSA_PARAMS is deprecated in v2.11, + * CKA_EC_PARAMS is preferred. */ +#define CKA_ECDSA_PARAMS 0x00000180 +#define CKA_EC_PARAMS 0x00000180 + +#define CKA_EC_POINT 0x00000181 + +/* CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS, + * are new for v2.10. Deprecated in v2.11 and onwards. */ +#define CKA_SECONDARY_AUTH 0x00000200 +#define CKA_AUTH_PIN_FLAGS 0x00000201 + +/* CKA_ALWAYS_AUTHENTICATE ... + * CKA_UNWRAP_TEMPLATE are new for v2.20 */ +#define CKA_ALWAYS_AUTHENTICATE 0x00000202 + +#define CKA_WRAP_WITH_TRUSTED 0x00000210 +#define CKA_WRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE|0x00000211) +#define CKA_UNWRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE|0x00000212) + +/* CKA_OTP... atttributes are new for PKCS #11 v2.20 amendment 3. */ +#define CKA_OTP_FORMAT 0x00000220 +#define CKA_OTP_LENGTH 0x00000221 +#define CKA_OTP_TIME_INTERVAL 0x00000222 +#define CKA_OTP_USER_FRIENDLY_MODE 0x00000223 +#define CKA_OTP_CHALLENGE_REQUIREMENT 0x00000224 +#define CKA_OTP_TIME_REQUIREMENT 0x00000225 +#define CKA_OTP_COUNTER_REQUIREMENT 0x00000226 +#define CKA_OTP_PIN_REQUIREMENT 0x00000227 +#define CKA_OTP_COUNTER 0x0000022E +#define CKA_OTP_TIME 0x0000022F +#define CKA_OTP_USER_IDENTIFIER 0x0000022A +#define CKA_OTP_SERVICE_IDENTIFIER 0x0000022B +#define CKA_OTP_SERVICE_LOGO 0x0000022C +#define CKA_OTP_SERVICE_LOGO_TYPE 0x0000022D + + +/* CKA_HW_FEATURE_TYPE, CKA_RESET_ON_INIT, and CKA_HAS_RESET + * are new for v2.10 */ +#define CKA_HW_FEATURE_TYPE 0x00000300 +#define CKA_RESET_ON_INIT 0x00000301 +#define CKA_HAS_RESET 0x00000302 + +/* The following attributes are new for v2.20 */ +#define CKA_PIXEL_X 0x00000400 +#define CKA_PIXEL_Y 0x00000401 +#define CKA_RESOLUTION 0x00000402 +#define CKA_CHAR_ROWS 0x00000403 +#define CKA_CHAR_COLUMNS 0x00000404 +#define CKA_COLOR 0x00000405 +#define CKA_BITS_PER_PIXEL 0x00000406 +#define CKA_CHAR_SETS 0x00000480 +#define CKA_ENCODING_METHODS 0x00000481 +#define CKA_MIME_TYPES 0x00000482 +#define CKA_MECHANISM_TYPE 0x00000500 +#define CKA_REQUIRED_CMS_ATTRIBUTES 0x00000501 +#define CKA_DEFAULT_CMS_ATTRIBUTES 0x00000502 +#define CKA_SUPPORTED_CMS_ATTRIBUTES 0x00000503 +#define CKA_ALLOWED_MECHANISMS (CKF_ARRAY_ATTRIBUTE|0x00000600) + +#define CKA_VENDOR_DEFINED 0x80000000 + +/* CK_ATTRIBUTE is a structure that includes the type, length + * and value of an attribute */ +typedef struct CK_ATTRIBUTE { + CK_ATTRIBUTE_TYPE type; + CK_VOID_PTR pValue; + + /* ulValueLen went from CK_USHORT to CK_ULONG for v2.0 */ + CK_ULONG ulValueLen; /* in bytes */ +} CK_ATTRIBUTE; + +typedef CK_ATTRIBUTE CK_PTR CK_ATTRIBUTE_PTR; + + +/* CK_DATE is a structure that defines a date */ +typedef struct CK_DATE{ + CK_CHAR year[4]; /* the year ("1900" - "9999") */ + CK_CHAR month[2]; /* the month ("01" - "12") */ + CK_CHAR day[2]; /* the day ("01" - "31") */ +} CK_DATE; + + +/* CK_MECHANISM_TYPE is a value that identifies a mechanism + * type */ +/* CK_MECHANISM_TYPE was changed from CK_USHORT to CK_ULONG for + * v2.0 */ +typedef CK_ULONG CK_MECHANISM_TYPE; + +/* the following mechanism types are defined: */ +#define CKM_RSA_PKCS_KEY_PAIR_GEN 0x00000000 +#define CKM_RSA_PKCS 0x00000001 +#define CKM_RSA_9796 0x00000002 +#define CKM_RSA_X_509 0x00000003 + +/* CKM_MD2_RSA_PKCS, CKM_MD5_RSA_PKCS, and CKM_SHA1_RSA_PKCS + * are new for v2.0. They are mechanisms which hash and sign */ +#define CKM_MD2_RSA_PKCS 0x00000004 +#define CKM_MD5_RSA_PKCS 0x00000005 +#define CKM_SHA1_RSA_PKCS 0x00000006 + +/* CKM_RIPEMD128_RSA_PKCS, CKM_RIPEMD160_RSA_PKCS, and + * CKM_RSA_PKCS_OAEP are new for v2.10 */ +#define CKM_RIPEMD128_RSA_PKCS 0x00000007 +#define CKM_RIPEMD160_RSA_PKCS 0x00000008 +#define CKM_RSA_PKCS_OAEP 0x00000009 + +/* CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_RSA_X9_31, CKM_SHA1_RSA_X9_31, + * CKM_RSA_PKCS_PSS, and CKM_SHA1_RSA_PKCS_PSS are new for v2.11 */ +#define CKM_RSA_X9_31_KEY_PAIR_GEN 0x0000000A +#define CKM_RSA_X9_31 0x0000000B +#define CKM_SHA1_RSA_X9_31 0x0000000C +#define CKM_RSA_PKCS_PSS 0x0000000D +#define CKM_SHA1_RSA_PKCS_PSS 0x0000000E + +#define CKM_DSA_KEY_PAIR_GEN 0x00000010 +#define CKM_DSA 0x00000011 +#define CKM_DSA_SHA1 0x00000012 +#define CKM_DH_PKCS_KEY_PAIR_GEN 0x00000020 +#define CKM_DH_PKCS_DERIVE 0x00000021 + +/* CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_DERIVE, + * CKM_X9_42_DH_HYBRID_DERIVE, and CKM_X9_42_MQV_DERIVE are new for + * v2.11 */ +#define CKM_X9_42_DH_KEY_PAIR_GEN 0x00000030 +#define CKM_X9_42_DH_DERIVE 0x00000031 +#define CKM_X9_42_DH_HYBRID_DERIVE 0x00000032 +#define CKM_X9_42_MQV_DERIVE 0x00000033 + +/* CKM_SHA256/384/512 are new for v2.20 */ +#define CKM_SHA256_RSA_PKCS 0x00000040 +#define CKM_SHA384_RSA_PKCS 0x00000041 +#define CKM_SHA512_RSA_PKCS 0x00000042 +#define CKM_SHA256_RSA_PKCS_PSS 0x00000043 +#define CKM_SHA384_RSA_PKCS_PSS 0x00000044 +#define CKM_SHA512_RSA_PKCS_PSS 0x00000045 + +/* SHA-224 RSA mechanisms are new for PKCS #11 v2.20 amendment 3 */ +#define CKM_SHA224_RSA_PKCS 0x00000046 +#define CKM_SHA224_RSA_PKCS_PSS 0x00000047 + +#define CKM_RC2_KEY_GEN 0x00000100 +#define CKM_RC2_ECB 0x00000101 +#define CKM_RC2_CBC 0x00000102 +#define CKM_RC2_MAC 0x00000103 + +/* CKM_RC2_MAC_GENERAL and CKM_RC2_CBC_PAD are new for v2.0 */ +#define CKM_RC2_MAC_GENERAL 0x00000104 +#define CKM_RC2_CBC_PAD 0x00000105 + +#define CKM_RC4_KEY_GEN 0x00000110 +#define CKM_RC4 0x00000111 +#define CKM_DES_KEY_GEN 0x00000120 +#define CKM_DES_ECB 0x00000121 +#define CKM_DES_CBC 0x00000122 +#define CKM_DES_MAC 0x00000123 + +/* CKM_DES_MAC_GENERAL and CKM_DES_CBC_PAD are new for v2.0 */ +#define CKM_DES_MAC_GENERAL 0x00000124 +#define CKM_DES_CBC_PAD 0x00000125 + +#define CKM_DES2_KEY_GEN 0x00000130 +#define CKM_DES3_KEY_GEN 0x00000131 +#define CKM_DES3_ECB 0x00000132 +#define CKM_DES3_CBC 0x00000133 +#define CKM_DES3_MAC 0x00000134 + +/* CKM_DES3_MAC_GENERAL, CKM_DES3_CBC_PAD, CKM_CDMF_KEY_GEN, + * CKM_CDMF_ECB, CKM_CDMF_CBC, CKM_CDMF_MAC, + * CKM_CDMF_MAC_GENERAL, and CKM_CDMF_CBC_PAD are new for v2.0 */ +#define CKM_DES3_MAC_GENERAL 0x00000135 +#define CKM_DES3_CBC_PAD 0x00000136 +#define CKM_CDMF_KEY_GEN 0x00000140 +#define CKM_CDMF_ECB 0x00000141 +#define CKM_CDMF_CBC 0x00000142 +#define CKM_CDMF_MAC 0x00000143 +#define CKM_CDMF_MAC_GENERAL 0x00000144 +#define CKM_CDMF_CBC_PAD 0x00000145 + +/* the following four DES mechanisms are new for v2.20 */ +#define CKM_DES_OFB64 0x00000150 +#define CKM_DES_OFB8 0x00000151 +#define CKM_DES_CFB64 0x00000152 +#define CKM_DES_CFB8 0x00000153 + +#define CKM_MD2 0x00000200 + +/* CKM_MD2_HMAC and CKM_MD2_HMAC_GENERAL are new for v2.0 */ +#define CKM_MD2_HMAC 0x00000201 +#define CKM_MD2_HMAC_GENERAL 0x00000202 + +#define CKM_MD5 0x00000210 + +/* CKM_MD5_HMAC and CKM_MD5_HMAC_GENERAL are new for v2.0 */ +#define CKM_MD5_HMAC 0x00000211 +#define CKM_MD5_HMAC_GENERAL 0x00000212 + +#define CKM_SHA_1 0x00000220 + +/* CKM_SHA_1_HMAC and CKM_SHA_1_HMAC_GENERAL are new for v2.0 */ +#define CKM_SHA_1_HMAC 0x00000221 +#define CKM_SHA_1_HMAC_GENERAL 0x00000222 + +/* CKM_RIPEMD128, CKM_RIPEMD128_HMAC, + * CKM_RIPEMD128_HMAC_GENERAL, CKM_RIPEMD160, CKM_RIPEMD160_HMAC, + * and CKM_RIPEMD160_HMAC_GENERAL are new for v2.10 */ +#define CKM_RIPEMD128 0x00000230 +#define CKM_RIPEMD128_HMAC 0x00000231 +#define CKM_RIPEMD128_HMAC_GENERAL 0x00000232 +#define CKM_RIPEMD160 0x00000240 +#define CKM_RIPEMD160_HMAC 0x00000241 +#define CKM_RIPEMD160_HMAC_GENERAL 0x00000242 + +/* CKM_SHA256/384/512 are new for v2.20 */ +#define CKM_SHA256 0x00000250 +#define CKM_SHA256_HMAC 0x00000251 +#define CKM_SHA256_HMAC_GENERAL 0x00000252 + +/* SHA-224 is new for PKCS #11 v2.20 amendment 3 */ +#define CKM_SHA224 0x00000255 +#define CKM_SHA224_HMAC 0x00000256 +#define CKM_SHA224_HMAC_GENERAL 0x00000257 + +#define CKM_SHA384 0x00000260 +#define CKM_SHA384_HMAC 0x00000261 +#define CKM_SHA384_HMAC_GENERAL 0x00000262 +#define CKM_SHA512 0x00000270 +#define CKM_SHA512_HMAC 0x00000271 +#define CKM_SHA512_HMAC_GENERAL 0x00000272 + +/* SecurID is new for PKCS #11 v2.20 amendment 1 */ +#define CKM_SECURID_KEY_GEN 0x00000280 +#define CKM_SECURID 0x00000282 + +/* HOTP is new for PKCS #11 v2.20 amendment 1 */ +#define CKM_HOTP_KEY_GEN 0x00000290 +#define CKM_HOTP 0x00000291 + +/* ACTI is new for PKCS #11 v2.20 amendment 1 */ +#define CKM_ACTI 0x000002A0 +#define CKM_ACTI_KEY_GEN 0x000002A1 + +/* All of the following mechanisms are new for v2.0 */ +/* Note that CAST128 and CAST5 are the same algorithm */ +#define CKM_CAST_KEY_GEN 0x00000300 +#define CKM_CAST_ECB 0x00000301 +#define CKM_CAST_CBC 0x00000302 +#define CKM_CAST_MAC 0x00000303 +#define CKM_CAST_MAC_GENERAL 0x00000304 +#define CKM_CAST_CBC_PAD 0x00000305 +#define CKM_CAST3_KEY_GEN 0x00000310 +#define CKM_CAST3_ECB 0x00000311 +#define CKM_CAST3_CBC 0x00000312 +#define CKM_CAST3_MAC 0x00000313 +#define CKM_CAST3_MAC_GENERAL 0x00000314 +#define CKM_CAST3_CBC_PAD 0x00000315 +#define CKM_CAST5_KEY_GEN 0x00000320 +#define CKM_CAST128_KEY_GEN 0x00000320 +#define CKM_CAST5_ECB 0x00000321 +#define CKM_CAST128_ECB 0x00000321 +#define CKM_CAST5_CBC 0x00000322 +#define CKM_CAST128_CBC 0x00000322 +#define CKM_CAST5_MAC 0x00000323 +#define CKM_CAST128_MAC 0x00000323 +#define CKM_CAST5_MAC_GENERAL 0x00000324 +#define CKM_CAST128_MAC_GENERAL 0x00000324 +#define CKM_CAST5_CBC_PAD 0x00000325 +#define CKM_CAST128_CBC_PAD 0x00000325 +#define CKM_RC5_KEY_GEN 0x00000330 +#define CKM_RC5_ECB 0x00000331 +#define CKM_RC5_CBC 0x00000332 +#define CKM_RC5_MAC 0x00000333 +#define CKM_RC5_MAC_GENERAL 0x00000334 +#define CKM_RC5_CBC_PAD 0x00000335 +#define CKM_IDEA_KEY_GEN 0x00000340 +#define CKM_IDEA_ECB 0x00000341 +#define CKM_IDEA_CBC 0x00000342 +#define CKM_IDEA_MAC 0x00000343 +#define CKM_IDEA_MAC_GENERAL 0x00000344 +#define CKM_IDEA_CBC_PAD 0x00000345 +#define CKM_GENERIC_SECRET_KEY_GEN 0x00000350 +#define CKM_CONCATENATE_BASE_AND_KEY 0x00000360 +#define CKM_CONCATENATE_BASE_AND_DATA 0x00000362 +#define CKM_CONCATENATE_DATA_AND_BASE 0x00000363 +#define CKM_XOR_BASE_AND_DATA 0x00000364 +#define CKM_EXTRACT_KEY_FROM_KEY 0x00000365 +#define CKM_SSL3_PRE_MASTER_KEY_GEN 0x00000370 +#define CKM_SSL3_MASTER_KEY_DERIVE 0x00000371 +#define CKM_SSL3_KEY_AND_MAC_DERIVE 0x00000372 + +/* CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_TLS_PRE_MASTER_KEY_GEN, + * CKM_TLS_MASTER_KEY_DERIVE, CKM_TLS_KEY_AND_MAC_DERIVE, and + * CKM_TLS_MASTER_KEY_DERIVE_DH are new for v2.11 */ +#define CKM_SSL3_MASTER_KEY_DERIVE_DH 0x00000373 +#define CKM_TLS_PRE_MASTER_KEY_GEN 0x00000374 +#define CKM_TLS_MASTER_KEY_DERIVE 0x00000375 +#define CKM_TLS_KEY_AND_MAC_DERIVE 0x00000376 +#define CKM_TLS_MASTER_KEY_DERIVE_DH 0x00000377 + +/* CKM_TLS_PRF is new for v2.20 */ +#define CKM_TLS_PRF 0x00000378 + +#define CKM_SSL3_MD5_MAC 0x00000380 +#define CKM_SSL3_SHA1_MAC 0x00000381 +#define CKM_MD5_KEY_DERIVATION 0x00000390 +#define CKM_MD2_KEY_DERIVATION 0x00000391 +#define CKM_SHA1_KEY_DERIVATION 0x00000392 + +/* CKM_SHA256/384/512 are new for v2.20 */ +#define CKM_SHA256_KEY_DERIVATION 0x00000393 +#define CKM_SHA384_KEY_DERIVATION 0x00000394 +#define CKM_SHA512_KEY_DERIVATION 0x00000395 + +/* SHA-224 key derivation is new for PKCS #11 v2.20 amendment 3 */ +#define CKM_SHA224_KEY_DERIVATION 0x00000396 + +#define CKM_PBE_MD2_DES_CBC 0x000003A0 +#define CKM_PBE_MD5_DES_CBC 0x000003A1 +#define CKM_PBE_MD5_CAST_CBC 0x000003A2 +#define CKM_PBE_MD5_CAST3_CBC 0x000003A3 +#define CKM_PBE_MD5_CAST5_CBC 0x000003A4 +#define CKM_PBE_MD5_CAST128_CBC 0x000003A4 +#define CKM_PBE_SHA1_CAST5_CBC 0x000003A5 +#define CKM_PBE_SHA1_CAST128_CBC 0x000003A5 +#define CKM_PBE_SHA1_RC4_128 0x000003A6 +#define CKM_PBE_SHA1_RC4_40 0x000003A7 +#define CKM_PBE_SHA1_DES3_EDE_CBC 0x000003A8 +#define CKM_PBE_SHA1_DES2_EDE_CBC 0x000003A9 +#define CKM_PBE_SHA1_RC2_128_CBC 0x000003AA +#define CKM_PBE_SHA1_RC2_40_CBC 0x000003AB + +/* CKM_PKCS5_PBKD2 is new for v2.10 */ +#define CKM_PKCS5_PBKD2 0x000003B0 + +#define CKM_PBA_SHA1_WITH_SHA1_HMAC 0x000003C0 + +/* WTLS mechanisms are new for v2.20 */ +#define CKM_WTLS_PRE_MASTER_KEY_GEN 0x000003D0 +#define CKM_WTLS_MASTER_KEY_DERIVE 0x000003D1 +#define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC 0x000003D2 +#define CKM_WTLS_PRF 0x000003D3 +#define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE 0x000003D4 +#define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE 0x000003D5 + +#define CKM_KEY_WRAP_LYNKS 0x00000400 +#define CKM_KEY_WRAP_SET_OAEP 0x00000401 + +/* CKM_CMS_SIG is new for v2.20 */ +#define CKM_CMS_SIG 0x00000500 + +/* CKM_KIP mechanisms are new for PKCS #11 v2.20 amendment 2 */ +#define CKM_KIP_DERIVE 0x00000510 +#define CKM_KIP_WRAP 0x00000511 +#define CKM_KIP_MAC 0x00000512 + +/* Camellia is new for PKCS #11 v2.20 amendment 3 */ +#define CKM_CAMELLIA_KEY_GEN 0x00000550 +#define CKM_CAMELLIA_ECB 0x00000551 +#define CKM_CAMELLIA_CBC 0x00000552 +#define CKM_CAMELLIA_MAC 0x00000553 +#define CKM_CAMELLIA_MAC_GENERAL 0x00000554 +#define CKM_CAMELLIA_CBC_PAD 0x00000555 +#define CKM_CAMELLIA_ECB_ENCRYPT_DATA 0x00000556 +#define CKM_CAMELLIA_CBC_ENCRYPT_DATA 0x00000557 +#define CKM_CAMELLIA_CTR 0x00000558 + +/* ARIA is new for PKCS #11 v2.20 amendment 3 */ +#define CKM_ARIA_KEY_GEN 0x00000560 +#define CKM_ARIA_ECB 0x00000561 +#define CKM_ARIA_CBC 0x00000562 +#define CKM_ARIA_MAC 0x00000563 +#define CKM_ARIA_MAC_GENERAL 0x00000564 +#define CKM_ARIA_CBC_PAD 0x00000565 +#define CKM_ARIA_ECB_ENCRYPT_DATA 0x00000566 +#define CKM_ARIA_CBC_ENCRYPT_DATA 0x00000567 + +/* Fortezza mechanisms */ +#define CKM_SKIPJACK_KEY_GEN 0x00001000 +#define CKM_SKIPJACK_ECB64 0x00001001 +#define CKM_SKIPJACK_CBC64 0x00001002 +#define CKM_SKIPJACK_OFB64 0x00001003 +#define CKM_SKIPJACK_CFB64 0x00001004 +#define CKM_SKIPJACK_CFB32 0x00001005 +#define CKM_SKIPJACK_CFB16 0x00001006 +#define CKM_SKIPJACK_CFB8 0x00001007 +#define CKM_SKIPJACK_WRAP 0x00001008 +#define CKM_SKIPJACK_PRIVATE_WRAP 0x00001009 +#define CKM_SKIPJACK_RELAYX 0x0000100a +#define CKM_KEA_KEY_PAIR_GEN 0x00001010 +#define CKM_KEA_KEY_DERIVE 0x00001011 +#define CKM_FORTEZZA_TIMESTAMP 0x00001020 +#define CKM_BATON_KEY_GEN 0x00001030 +#define CKM_BATON_ECB128 0x00001031 +#define CKM_BATON_ECB96 0x00001032 +#define CKM_BATON_CBC128 0x00001033 +#define CKM_BATON_COUNTER 0x00001034 +#define CKM_BATON_SHUFFLE 0x00001035 +#define CKM_BATON_WRAP 0x00001036 + +/* CKM_ECDSA_KEY_PAIR_GEN is deprecated in v2.11, + * CKM_EC_KEY_PAIR_GEN is preferred */ +#define CKM_ECDSA_KEY_PAIR_GEN 0x00001040 +#define CKM_EC_KEY_PAIR_GEN 0x00001040 + +#define CKM_ECDSA 0x00001041 +#define CKM_ECDSA_SHA1 0x00001042 + +/* CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, and CKM_ECMQV_DERIVE + * are new for v2.11 */ +#define CKM_ECDH1_DERIVE 0x00001050 +#define CKM_ECDH1_COFACTOR_DERIVE 0x00001051 +#define CKM_ECMQV_DERIVE 0x00001052 + +#define CKM_JUNIPER_KEY_GEN 0x00001060 +#define CKM_JUNIPER_ECB128 0x00001061 +#define CKM_JUNIPER_CBC128 0x00001062 +#define CKM_JUNIPER_COUNTER 0x00001063 +#define CKM_JUNIPER_SHUFFLE 0x00001064 +#define CKM_JUNIPER_WRAP 0x00001065 +#define CKM_FASTHASH 0x00001070 + +/* CKM_AES_KEY_GEN, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_MAC, + * CKM_AES_MAC_GENERAL, CKM_AES_CBC_PAD, CKM_DSA_PARAMETER_GEN, + * CKM_DH_PKCS_PARAMETER_GEN, and CKM_X9_42_DH_PARAMETER_GEN are + * new for v2.11 */ +#define CKM_AES_KEY_GEN 0x00001080 +#define CKM_AES_ECB 0x00001081 +#define CKM_AES_CBC 0x00001082 +#define CKM_AES_MAC 0x00001083 +#define CKM_AES_MAC_GENERAL 0x00001084 +#define CKM_AES_CBC_PAD 0x00001085 + +/* AES counter mode is new for PKCS #11 v2.20 amendment 3 */ +#define CKM_AES_CTR 0x00001086 + +/* BlowFish and TwoFish are new for v2.20 */ +#define CKM_BLOWFISH_KEY_GEN 0x00001090 +#define CKM_BLOWFISH_CBC 0x00001091 +#define CKM_TWOFISH_KEY_GEN 0x00001092 +#define CKM_TWOFISH_CBC 0x00001093 + + +/* CKM_xxx_ENCRYPT_DATA mechanisms are new for v2.20 */ +#define CKM_DES_ECB_ENCRYPT_DATA 0x00001100 +#define CKM_DES_CBC_ENCRYPT_DATA 0x00001101 +#define CKM_DES3_ECB_ENCRYPT_DATA 0x00001102 +#define CKM_DES3_CBC_ENCRYPT_DATA 0x00001103 +#define CKM_AES_ECB_ENCRYPT_DATA 0x00001104 +#define CKM_AES_CBC_ENCRYPT_DATA 0x00001105 + +#define CKM_DSA_PARAMETER_GEN 0x00002000 +#define CKM_DH_PKCS_PARAMETER_GEN 0x00002001 +#define CKM_X9_42_DH_PARAMETER_GEN 0x00002002 + +#define CKM_VENDOR_DEFINED 0x80000000 + +typedef CK_MECHANISM_TYPE CK_PTR CK_MECHANISM_TYPE_PTR; + + +/* CK_MECHANISM is a structure that specifies a particular + * mechanism */ +typedef struct CK_MECHANISM { + CK_MECHANISM_TYPE mechanism; + CK_VOID_PTR pParameter; + + /* ulParameterLen was changed from CK_USHORT to CK_ULONG for + * v2.0 */ + CK_ULONG ulParameterLen; /* in bytes */ +} CK_MECHANISM; + +typedef CK_MECHANISM CK_PTR CK_MECHANISM_PTR; + + +/* CK_MECHANISM_INFO provides information about a particular + * mechanism */ +typedef struct CK_MECHANISM_INFO { + CK_ULONG ulMinKeySize; + CK_ULONG ulMaxKeySize; + CK_FLAGS flags; +} CK_MECHANISM_INFO; + +/* The flags are defined as follows: + * Bit Flag Mask Meaning */ +#define CKF_HW 0x00000001 /* performed by HW */ + +/* The flags CKF_ENCRYPT, CKF_DECRYPT, CKF_DIGEST, CKF_SIGN, + * CKG_SIGN_RECOVER, CKF_VERIFY, CKF_VERIFY_RECOVER, + * CKF_GENERATE, CKF_GENERATE_KEY_PAIR, CKF_WRAP, CKF_UNWRAP, + * and CKF_DERIVE are new for v2.0. They specify whether or not + * a mechanism can be used for a particular task */ +#define CKF_ENCRYPT 0x00000100 +#define CKF_DECRYPT 0x00000200 +#define CKF_DIGEST 0x00000400 +#define CKF_SIGN 0x00000800 +#define CKF_SIGN_RECOVER 0x00001000 +#define CKF_VERIFY 0x00002000 +#define CKF_VERIFY_RECOVER 0x00004000 +#define CKF_GENERATE 0x00008000 +#define CKF_GENERATE_KEY_PAIR 0x00010000 +#define CKF_WRAP 0x00020000 +#define CKF_UNWRAP 0x00040000 +#define CKF_DERIVE 0x00080000 + +/* CKF_EC_F_P, CKF_EC_F_2M, CKF_EC_ECPARAMETERS, CKF_EC_NAMEDCURVE, + * CKF_EC_UNCOMPRESS, and CKF_EC_COMPRESS are new for v2.11. They + * describe a token's EC capabilities not available in mechanism + * information. */ +#define CKF_EC_F_P 0x00100000 +#define CKF_EC_F_2M 0x00200000 +#define CKF_EC_ECPARAMETERS 0x00400000 +#define CKF_EC_NAMEDCURVE 0x00800000 +#define CKF_EC_UNCOMPRESS 0x01000000 +#define CKF_EC_COMPRESS 0x02000000 + +#define CKF_EXTENSION 0x80000000 /* FALSE for this version */ + +typedef CK_MECHANISM_INFO CK_PTR CK_MECHANISM_INFO_PTR; + + +/* CK_RV is a value that identifies the return value of a + * Cryptoki function */ +/* CK_RV was changed from CK_USHORT to CK_ULONG for v2.0 */ +typedef CK_ULONG CK_RV; + +#define CKR_OK 0x00000000 +#define CKR_CANCEL 0x00000001 +#define CKR_HOST_MEMORY 0x00000002 +#define CKR_SLOT_ID_INVALID 0x00000003 + +/* CKR_FLAGS_INVALID was removed for v2.0 */ + +/* CKR_GENERAL_ERROR and CKR_FUNCTION_FAILED are new for v2.0 */ +#define CKR_GENERAL_ERROR 0x00000005 +#define CKR_FUNCTION_FAILED 0x00000006 + +/* CKR_ARGUMENTS_BAD, CKR_NO_EVENT, CKR_NEED_TO_CREATE_THREADS, + * and CKR_CANT_LOCK are new for v2.01 */ +#define CKR_ARGUMENTS_BAD 0x00000007 +#define CKR_NO_EVENT 0x00000008 +#define CKR_NEED_TO_CREATE_THREADS 0x00000009 +#define CKR_CANT_LOCK 0x0000000A + +#define CKR_ATTRIBUTE_READ_ONLY 0x00000010 +#define CKR_ATTRIBUTE_SENSITIVE 0x00000011 +#define CKR_ATTRIBUTE_TYPE_INVALID 0x00000012 +#define CKR_ATTRIBUTE_VALUE_INVALID 0x00000013 +#define CKR_DATA_INVALID 0x00000020 +#define CKR_DATA_LEN_RANGE 0x00000021 +#define CKR_DEVICE_ERROR 0x00000030 +#define CKR_DEVICE_MEMORY 0x00000031 +#define CKR_DEVICE_REMOVED 0x00000032 +#define CKR_ENCRYPTED_DATA_INVALID 0x00000040 +#define CKR_ENCRYPTED_DATA_LEN_RANGE 0x00000041 +#define CKR_FUNCTION_CANCELED 0x00000050 +#define CKR_FUNCTION_NOT_PARALLEL 0x00000051 + +/* CKR_FUNCTION_NOT_SUPPORTED is new for v2.0 */ +#define CKR_FUNCTION_NOT_SUPPORTED 0x00000054 + +#define CKR_KEY_HANDLE_INVALID 0x00000060 + +/* CKR_KEY_SENSITIVE was removed for v2.0 */ + +#define CKR_KEY_SIZE_RANGE 0x00000062 +#define CKR_KEY_TYPE_INCONSISTENT 0x00000063 + +/* CKR_KEY_NOT_NEEDED, CKR_KEY_CHANGED, CKR_KEY_NEEDED, + * CKR_KEY_INDIGESTIBLE, CKR_KEY_FUNCTION_NOT_PERMITTED, + * CKR_KEY_NOT_WRAPPABLE, and CKR_KEY_UNEXTRACTABLE are new for + * v2.0 */ +#define CKR_KEY_NOT_NEEDED 0x00000064 +#define CKR_KEY_CHANGED 0x00000065 +#define CKR_KEY_NEEDED 0x00000066 +#define CKR_KEY_INDIGESTIBLE 0x00000067 +#define CKR_KEY_FUNCTION_NOT_PERMITTED 0x00000068 +#define CKR_KEY_NOT_WRAPPABLE 0x00000069 +#define CKR_KEY_UNEXTRACTABLE 0x0000006A + +#define CKR_MECHANISM_INVALID 0x00000070 +#define CKR_MECHANISM_PARAM_INVALID 0x00000071 + +/* CKR_OBJECT_CLASS_INCONSISTENT and CKR_OBJECT_CLASS_INVALID + * were removed for v2.0 */ +#define CKR_OBJECT_HANDLE_INVALID 0x00000082 +#define CKR_OPERATION_ACTIVE 0x00000090 +#define CKR_OPERATION_NOT_INITIALIZED 0x00000091 +#define CKR_PIN_INCORRECT 0x000000A0 +#define CKR_PIN_INVALID 0x000000A1 +#define CKR_PIN_LEN_RANGE 0x000000A2 + +/* CKR_PIN_EXPIRED and CKR_PIN_LOCKED are new for v2.0 */ +#define CKR_PIN_EXPIRED 0x000000A3 +#define CKR_PIN_LOCKED 0x000000A4 + +#define CKR_SESSION_CLOSED 0x000000B0 +#define CKR_SESSION_COUNT 0x000000B1 +#define CKR_SESSION_HANDLE_INVALID 0x000000B3 +#define CKR_SESSION_PARALLEL_NOT_SUPPORTED 0x000000B4 +#define CKR_SESSION_READ_ONLY 0x000000B5 +#define CKR_SESSION_EXISTS 0x000000B6 + +/* CKR_SESSION_READ_ONLY_EXISTS and + * CKR_SESSION_READ_WRITE_SO_EXISTS are new for v2.0 */ +#define CKR_SESSION_READ_ONLY_EXISTS 0x000000B7 +#define CKR_SESSION_READ_WRITE_SO_EXISTS 0x000000B8 + +#define CKR_SIGNATURE_INVALID 0x000000C0 +#define CKR_SIGNATURE_LEN_RANGE 0x000000C1 +#define CKR_TEMPLATE_INCOMPLETE 0x000000D0 +#define CKR_TEMPLATE_INCONSISTENT 0x000000D1 +#define CKR_TOKEN_NOT_PRESENT 0x000000E0 +#define CKR_TOKEN_NOT_RECOGNIZED 0x000000E1 +#define CKR_TOKEN_WRITE_PROTECTED 0x000000E2 +#define CKR_UNWRAPPING_KEY_HANDLE_INVALID 0x000000F0 +#define CKR_UNWRAPPING_KEY_SIZE_RANGE 0x000000F1 +#define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT 0x000000F2 +#define CKR_USER_ALREADY_LOGGED_IN 0x00000100 +#define CKR_USER_NOT_LOGGED_IN 0x00000101 +#define CKR_USER_PIN_NOT_INITIALIZED 0x00000102 +#define CKR_USER_TYPE_INVALID 0x00000103 + +/* CKR_USER_ANOTHER_ALREADY_LOGGED_IN and CKR_USER_TOO_MANY_TYPES + * are new to v2.01 */ +#define CKR_USER_ANOTHER_ALREADY_LOGGED_IN 0x00000104 +#define CKR_USER_TOO_MANY_TYPES 0x00000105 + +#define CKR_WRAPPED_KEY_INVALID 0x00000110 +#define CKR_WRAPPED_KEY_LEN_RANGE 0x00000112 +#define CKR_WRAPPING_KEY_HANDLE_INVALID 0x00000113 +#define CKR_WRAPPING_KEY_SIZE_RANGE 0x00000114 +#define CKR_WRAPPING_KEY_TYPE_INCONSISTENT 0x00000115 +#define CKR_RANDOM_SEED_NOT_SUPPORTED 0x00000120 + +/* These are new to v2.0 */ +#define CKR_RANDOM_NO_RNG 0x00000121 + +/* These are new to v2.11 */ +#define CKR_DOMAIN_PARAMS_INVALID 0x00000130 + +/* These are new to v2.0 */ +#define CKR_BUFFER_TOO_SMALL 0x00000150 +#define CKR_SAVED_STATE_INVALID 0x00000160 +#define CKR_INFORMATION_SENSITIVE 0x00000170 +#define CKR_STATE_UNSAVEABLE 0x00000180 + +/* These are new to v2.01 */ +#define CKR_CRYPTOKI_NOT_INITIALIZED 0x00000190 +#define CKR_CRYPTOKI_ALREADY_INITIALIZED 0x00000191 +#define CKR_MUTEX_BAD 0x000001A0 +#define CKR_MUTEX_NOT_LOCKED 0x000001A1 + +/* The following return values are new for PKCS #11 v2.20 amendment 3 */ +#define CKR_NEW_PIN_MODE 0x000001B0 +#define CKR_NEXT_OTP 0x000001B1 + +/* This is new to v2.20 */ +#define CKR_FUNCTION_REJECTED 0x00000200 + +#define CKR_VENDOR_DEFINED 0x80000000 + + +/* CK_NOTIFY is an application callback that processes events */ +typedef CK_CALLBACK_FUNCTION(CK_RV, CK_NOTIFY)( + CK_SESSION_HANDLE hSession, /* the session's handle */ + CK_NOTIFICATION event, + CK_VOID_PTR pApplication /* passed to C_OpenSession */ +); + + +/* CK_FUNCTION_LIST is a structure holding a Cryptoki spec + * version and pointers of appropriate types to all the + * Cryptoki functions */ +/* CK_FUNCTION_LIST is new for v2.0 */ +typedef struct CK_FUNCTION_LIST CK_FUNCTION_LIST; + +typedef CK_FUNCTION_LIST CK_PTR CK_FUNCTION_LIST_PTR; + +typedef CK_FUNCTION_LIST_PTR CK_PTR CK_FUNCTION_LIST_PTR_PTR; + + +/* CK_CREATEMUTEX is an application callback for creating a + * mutex object */ +typedef CK_CALLBACK_FUNCTION(CK_RV, CK_CREATEMUTEX)( + CK_VOID_PTR_PTR ppMutex /* location to receive ptr to mutex */ +); + + +/* CK_DESTROYMUTEX is an application callback for destroying a + * mutex object */ +typedef CK_CALLBACK_FUNCTION(CK_RV, CK_DESTROYMUTEX)( + CK_VOID_PTR pMutex /* pointer to mutex */ +); + + +/* CK_LOCKMUTEX is an application callback for locking a mutex */ +typedef CK_CALLBACK_FUNCTION(CK_RV, CK_LOCKMUTEX)( + CK_VOID_PTR pMutex /* pointer to mutex */ +); + + +/* CK_UNLOCKMUTEX is an application callback for unlocking a + * mutex */ +typedef CK_CALLBACK_FUNCTION(CK_RV, CK_UNLOCKMUTEX)( + CK_VOID_PTR pMutex /* pointer to mutex */ +); + + +/* CK_C_INITIALIZE_ARGS provides the optional arguments to + * C_Initialize */ +typedef struct CK_C_INITIALIZE_ARGS { + CK_CREATEMUTEX CreateMutex; + CK_DESTROYMUTEX DestroyMutex; + CK_LOCKMUTEX LockMutex; + CK_UNLOCKMUTEX UnlockMutex; + CK_FLAGS flags; + CK_VOID_PTR pReserved; +} CK_C_INITIALIZE_ARGS; + +/* flags: bit flags that provide capabilities of the slot + * Bit Flag Mask Meaning + */ +#define CKF_LIBRARY_CANT_CREATE_OS_THREADS 0x00000001 +#define CKF_OS_LOCKING_OK 0x00000002 + +typedef CK_C_INITIALIZE_ARGS CK_PTR CK_C_INITIALIZE_ARGS_PTR; + + +/* additional flags for parameters to functions */ + +/* CKF_DONT_BLOCK is for the function C_WaitForSlotEvent */ +#define CKF_DONT_BLOCK 1 + +/* CK_RSA_PKCS_OAEP_MGF_TYPE is new for v2.10. + * CK_RSA_PKCS_OAEP_MGF_TYPE is used to indicate the Message + * Generation Function (MGF) applied to a message block when + * formatting a message block for the PKCS #1 OAEP encryption + * scheme. */ +typedef CK_ULONG CK_RSA_PKCS_MGF_TYPE; + +typedef CK_RSA_PKCS_MGF_TYPE CK_PTR CK_RSA_PKCS_MGF_TYPE_PTR; + +/* The following MGFs are defined */ +/* CKG_MGF1_SHA256, CKG_MGF1_SHA384, and CKG_MGF1_SHA512 + * are new for v2.20 */ +#define CKG_MGF1_SHA1 0x00000001 +#define CKG_MGF1_SHA256 0x00000002 +#define CKG_MGF1_SHA384 0x00000003 +#define CKG_MGF1_SHA512 0x00000004 +/* SHA-224 is new for PKCS #11 v2.20 amendment 3 */ +#define CKG_MGF1_SHA224 0x00000005 + +/* CK_RSA_PKCS_OAEP_SOURCE_TYPE is new for v2.10. + * CK_RSA_PKCS_OAEP_SOURCE_TYPE is used to indicate the source + * of the encoding parameter when formatting a message block + * for the PKCS #1 OAEP encryption scheme. */ +typedef CK_ULONG CK_RSA_PKCS_OAEP_SOURCE_TYPE; + +typedef CK_RSA_PKCS_OAEP_SOURCE_TYPE CK_PTR CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR; + +/* The following encoding parameter sources are defined */ +#define CKZ_DATA_SPECIFIED 0x00000001 + +/* CK_RSA_PKCS_OAEP_PARAMS is new for v2.10. + * CK_RSA_PKCS_OAEP_PARAMS provides the parameters to the + * CKM_RSA_PKCS_OAEP mechanism. */ +typedef struct CK_RSA_PKCS_OAEP_PARAMS { + CK_MECHANISM_TYPE hashAlg; + CK_RSA_PKCS_MGF_TYPE mgf; + CK_RSA_PKCS_OAEP_SOURCE_TYPE source; + CK_VOID_PTR pSourceData; + CK_ULONG ulSourceDataLen; +} CK_RSA_PKCS_OAEP_PARAMS; + +typedef CK_RSA_PKCS_OAEP_PARAMS CK_PTR CK_RSA_PKCS_OAEP_PARAMS_PTR; + +/* CK_RSA_PKCS_PSS_PARAMS is new for v2.11. + * CK_RSA_PKCS_PSS_PARAMS provides the parameters to the + * CKM_RSA_PKCS_PSS mechanism(s). */ +typedef struct CK_RSA_PKCS_PSS_PARAMS { + CK_MECHANISM_TYPE hashAlg; + CK_RSA_PKCS_MGF_TYPE mgf; + CK_ULONG sLen; +} CK_RSA_PKCS_PSS_PARAMS; + +typedef CK_RSA_PKCS_PSS_PARAMS CK_PTR CK_RSA_PKCS_PSS_PARAMS_PTR; + +/* CK_EC_KDF_TYPE is new for v2.11. */ +typedef CK_ULONG CK_EC_KDF_TYPE; + +/* The following EC Key Derivation Functions are defined */ +#define CKD_NULL 0x00000001 +#define CKD_SHA1_KDF 0x00000002 + +/* CK_ECDH1_DERIVE_PARAMS is new for v2.11. + * CK_ECDH1_DERIVE_PARAMS provides the parameters to the + * CKM_ECDH1_DERIVE and CKM_ECDH1_COFACTOR_DERIVE mechanisms, + * where each party contributes one key pair. + */ +typedef struct CK_ECDH1_DERIVE_PARAMS { + CK_EC_KDF_TYPE kdf; + CK_ULONG ulSharedDataLen; + CK_BYTE_PTR pSharedData; + CK_ULONG ulPublicDataLen; + CK_BYTE_PTR pPublicData; +} CK_ECDH1_DERIVE_PARAMS; + +typedef CK_ECDH1_DERIVE_PARAMS CK_PTR CK_ECDH1_DERIVE_PARAMS_PTR; + + +/* CK_ECDH2_DERIVE_PARAMS is new for v2.11. + * CK_ECDH2_DERIVE_PARAMS provides the parameters to the + * CKM_ECMQV_DERIVE mechanism, where each party contributes two key pairs. */ +typedef struct CK_ECDH2_DERIVE_PARAMS { + CK_EC_KDF_TYPE kdf; + CK_ULONG ulSharedDataLen; + CK_BYTE_PTR pSharedData; + CK_ULONG ulPublicDataLen; + CK_BYTE_PTR pPublicData; + CK_ULONG ulPrivateDataLen; + CK_OBJECT_HANDLE hPrivateData; + CK_ULONG ulPublicDataLen2; + CK_BYTE_PTR pPublicData2; +} CK_ECDH2_DERIVE_PARAMS; + +typedef CK_ECDH2_DERIVE_PARAMS CK_PTR CK_ECDH2_DERIVE_PARAMS_PTR; + +typedef struct CK_ECMQV_DERIVE_PARAMS { + CK_EC_KDF_TYPE kdf; + CK_ULONG ulSharedDataLen; + CK_BYTE_PTR pSharedData; + CK_ULONG ulPublicDataLen; + CK_BYTE_PTR pPublicData; + CK_ULONG ulPrivateDataLen; + CK_OBJECT_HANDLE hPrivateData; + CK_ULONG ulPublicDataLen2; + CK_BYTE_PTR pPublicData2; + CK_OBJECT_HANDLE publicKey; +} CK_ECMQV_DERIVE_PARAMS; + +typedef CK_ECMQV_DERIVE_PARAMS CK_PTR CK_ECMQV_DERIVE_PARAMS_PTR; + +/* Typedefs and defines for the CKM_X9_42_DH_KEY_PAIR_GEN and the + * CKM_X9_42_DH_PARAMETER_GEN mechanisms (new for PKCS #11 v2.11) */ +typedef CK_ULONG CK_X9_42_DH_KDF_TYPE; +typedef CK_X9_42_DH_KDF_TYPE CK_PTR CK_X9_42_DH_KDF_TYPE_PTR; + +/* The following X9.42 DH key derivation functions are defined + (besides CKD_NULL already defined : */ +#define CKD_SHA1_KDF_ASN1 0x00000003 +#define CKD_SHA1_KDF_CONCATENATE 0x00000004 + +/* CK_X9_42_DH1_DERIVE_PARAMS is new for v2.11. + * CK_X9_42_DH1_DERIVE_PARAMS provides the parameters to the + * CKM_X9_42_DH_DERIVE key derivation mechanism, where each party + * contributes one key pair */ +typedef struct CK_X9_42_DH1_DERIVE_PARAMS { + CK_X9_42_DH_KDF_TYPE kdf; + CK_ULONG ulOtherInfoLen; + CK_BYTE_PTR pOtherInfo; + CK_ULONG ulPublicDataLen; + CK_BYTE_PTR pPublicData; +} CK_X9_42_DH1_DERIVE_PARAMS; + +typedef struct CK_X9_42_DH1_DERIVE_PARAMS CK_PTR CK_X9_42_DH1_DERIVE_PARAMS_PTR; + +/* CK_X9_42_DH2_DERIVE_PARAMS is new for v2.11. + * CK_X9_42_DH2_DERIVE_PARAMS provides the parameters to the + * CKM_X9_42_DH_HYBRID_DERIVE and CKM_X9_42_MQV_DERIVE key derivation + * mechanisms, where each party contributes two key pairs */ +typedef struct CK_X9_42_DH2_DERIVE_PARAMS { + CK_X9_42_DH_KDF_TYPE kdf; + CK_ULONG ulOtherInfoLen; + CK_BYTE_PTR pOtherInfo; + CK_ULONG ulPublicDataLen; + CK_BYTE_PTR pPublicData; + CK_ULONG ulPrivateDataLen; + CK_OBJECT_HANDLE hPrivateData; + CK_ULONG ulPublicDataLen2; + CK_BYTE_PTR pPublicData2; +} CK_X9_42_DH2_DERIVE_PARAMS; + +typedef CK_X9_42_DH2_DERIVE_PARAMS CK_PTR CK_X9_42_DH2_DERIVE_PARAMS_PTR; + +typedef struct CK_X9_42_MQV_DERIVE_PARAMS { + CK_X9_42_DH_KDF_TYPE kdf; + CK_ULONG ulOtherInfoLen; + CK_BYTE_PTR pOtherInfo; + CK_ULONG ulPublicDataLen; + CK_BYTE_PTR pPublicData; + CK_ULONG ulPrivateDataLen; + CK_OBJECT_HANDLE hPrivateData; + CK_ULONG ulPublicDataLen2; + CK_BYTE_PTR pPublicData2; + CK_OBJECT_HANDLE publicKey; +} CK_X9_42_MQV_DERIVE_PARAMS; + +typedef CK_X9_42_MQV_DERIVE_PARAMS CK_PTR CK_X9_42_MQV_DERIVE_PARAMS_PTR; + +/* CK_KEA_DERIVE_PARAMS provides the parameters to the + * CKM_KEA_DERIVE mechanism */ +/* CK_KEA_DERIVE_PARAMS is new for v2.0 */ +typedef struct CK_KEA_DERIVE_PARAMS { + CK_BBOOL isSender; + CK_ULONG ulRandomLen; + CK_BYTE_PTR pRandomA; + CK_BYTE_PTR pRandomB; + CK_ULONG ulPublicDataLen; + CK_BYTE_PTR pPublicData; +} CK_KEA_DERIVE_PARAMS; + +typedef CK_KEA_DERIVE_PARAMS CK_PTR CK_KEA_DERIVE_PARAMS_PTR; + + +/* CK_RC2_PARAMS provides the parameters to the CKM_RC2_ECB and + * CKM_RC2_MAC mechanisms. An instance of CK_RC2_PARAMS just + * holds the effective keysize */ +typedef CK_ULONG CK_RC2_PARAMS; + +typedef CK_RC2_PARAMS CK_PTR CK_RC2_PARAMS_PTR; + + +/* CK_RC2_CBC_PARAMS provides the parameters to the CKM_RC2_CBC + * mechanism */ +typedef struct CK_RC2_CBC_PARAMS { + /* ulEffectiveBits was changed from CK_USHORT to CK_ULONG for + * v2.0 */ + CK_ULONG ulEffectiveBits; /* effective bits (1-1024) */ + + CK_BYTE iv[8]; /* IV for CBC mode */ +} CK_RC2_CBC_PARAMS; + +typedef CK_RC2_CBC_PARAMS CK_PTR CK_RC2_CBC_PARAMS_PTR; + + +/* CK_RC2_MAC_GENERAL_PARAMS provides the parameters for the + * CKM_RC2_MAC_GENERAL mechanism */ +/* CK_RC2_MAC_GENERAL_PARAMS is new for v2.0 */ +typedef struct CK_RC2_MAC_GENERAL_PARAMS { + CK_ULONG ulEffectiveBits; /* effective bits (1-1024) */ + CK_ULONG ulMacLength; /* Length of MAC in bytes */ +} CK_RC2_MAC_GENERAL_PARAMS; + +typedef CK_RC2_MAC_GENERAL_PARAMS CK_PTR \ + CK_RC2_MAC_GENERAL_PARAMS_PTR; + + +/* CK_RC5_PARAMS provides the parameters to the CKM_RC5_ECB and + * CKM_RC5_MAC mechanisms */ +/* CK_RC5_PARAMS is new for v2.0 */ +typedef struct CK_RC5_PARAMS { + CK_ULONG ulWordsize; /* wordsize in bits */ + CK_ULONG ulRounds; /* number of rounds */ +} CK_RC5_PARAMS; + +typedef CK_RC5_PARAMS CK_PTR CK_RC5_PARAMS_PTR; + + +/* CK_RC5_CBC_PARAMS provides the parameters to the CKM_RC5_CBC + * mechanism */ +/* CK_RC5_CBC_PARAMS is new for v2.0 */ +typedef struct CK_RC5_CBC_PARAMS { + CK_ULONG ulWordsize; /* wordsize in bits */ + CK_ULONG ulRounds; /* number of rounds */ + CK_BYTE_PTR pIv; /* pointer to IV */ + CK_ULONG ulIvLen; /* length of IV in bytes */ +} CK_RC5_CBC_PARAMS; + +typedef CK_RC5_CBC_PARAMS CK_PTR CK_RC5_CBC_PARAMS_PTR; + + +/* CK_RC5_MAC_GENERAL_PARAMS provides the parameters for the + * CKM_RC5_MAC_GENERAL mechanism */ +/* CK_RC5_MAC_GENERAL_PARAMS is new for v2.0 */ +typedef struct CK_RC5_MAC_GENERAL_PARAMS { + CK_ULONG ulWordsize; /* wordsize in bits */ + CK_ULONG ulRounds; /* number of rounds */ + CK_ULONG ulMacLength; /* Length of MAC in bytes */ +} CK_RC5_MAC_GENERAL_PARAMS; + +typedef CK_RC5_MAC_GENERAL_PARAMS CK_PTR \ + CK_RC5_MAC_GENERAL_PARAMS_PTR; + + +/* CK_MAC_GENERAL_PARAMS provides the parameters to most block + * ciphers' MAC_GENERAL mechanisms. Its value is the length of + * the MAC */ +/* CK_MAC_GENERAL_PARAMS is new for v2.0 */ +typedef CK_ULONG CK_MAC_GENERAL_PARAMS; + +typedef CK_MAC_GENERAL_PARAMS CK_PTR CK_MAC_GENERAL_PARAMS_PTR; + +/* CK_DES/AES_ECB/CBC_ENCRYPT_DATA_PARAMS are new for v2.20 */ +typedef struct CK_DES_CBC_ENCRYPT_DATA_PARAMS { + CK_BYTE iv[8]; + CK_BYTE_PTR pData; + CK_ULONG length; +} CK_DES_CBC_ENCRYPT_DATA_PARAMS; + +typedef CK_DES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR; + +typedef struct CK_AES_CBC_ENCRYPT_DATA_PARAMS { + CK_BYTE iv[16]; + CK_BYTE_PTR pData; + CK_ULONG length; +} CK_AES_CBC_ENCRYPT_DATA_PARAMS; + +typedef CK_AES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR; + +/* CK_SKIPJACK_PRIVATE_WRAP_PARAMS provides the parameters to the + * CKM_SKIPJACK_PRIVATE_WRAP mechanism */ +/* CK_SKIPJACK_PRIVATE_WRAP_PARAMS is new for v2.0 */ +typedef struct CK_SKIPJACK_PRIVATE_WRAP_PARAMS { + CK_ULONG ulPasswordLen; + CK_BYTE_PTR pPassword; + CK_ULONG ulPublicDataLen; + CK_BYTE_PTR pPublicData; + CK_ULONG ulPAndGLen; + CK_ULONG ulQLen; + CK_ULONG ulRandomLen; + CK_BYTE_PTR pRandomA; + CK_BYTE_PTR pPrimeP; + CK_BYTE_PTR pBaseG; + CK_BYTE_PTR pSubprimeQ; +} CK_SKIPJACK_PRIVATE_WRAP_PARAMS; + +typedef CK_SKIPJACK_PRIVATE_WRAP_PARAMS CK_PTR \ + CK_SKIPJACK_PRIVATE_WRAP_PTR; + + +/* CK_SKIPJACK_RELAYX_PARAMS provides the parameters to the + * CKM_SKIPJACK_RELAYX mechanism */ +/* CK_SKIPJACK_RELAYX_PARAMS is new for v2.0 */ +typedef struct CK_SKIPJACK_RELAYX_PARAMS { + CK_ULONG ulOldWrappedXLen; + CK_BYTE_PTR pOldWrappedX; + CK_ULONG ulOldPasswordLen; + CK_BYTE_PTR pOldPassword; + CK_ULONG ulOldPublicDataLen; + CK_BYTE_PTR pOldPublicData; + CK_ULONG ulOldRandomLen; + CK_BYTE_PTR pOldRandomA; + CK_ULONG ulNewPasswordLen; + CK_BYTE_PTR pNewPassword; + CK_ULONG ulNewPublicDataLen; + CK_BYTE_PTR pNewPublicData; + CK_ULONG ulNewRandomLen; + CK_BYTE_PTR pNewRandomA; +} CK_SKIPJACK_RELAYX_PARAMS; + +typedef CK_SKIPJACK_RELAYX_PARAMS CK_PTR \ + CK_SKIPJACK_RELAYX_PARAMS_PTR; + + +typedef struct CK_PBE_PARAMS { + CK_BYTE_PTR pInitVector; + CK_UTF8CHAR_PTR pPassword; + CK_ULONG ulPasswordLen; + CK_BYTE_PTR pSalt; + CK_ULONG ulSaltLen; + CK_ULONG ulIteration; +} CK_PBE_PARAMS; + +typedef CK_PBE_PARAMS CK_PTR CK_PBE_PARAMS_PTR; + + +/* CK_KEY_WRAP_SET_OAEP_PARAMS provides the parameters to the + * CKM_KEY_WRAP_SET_OAEP mechanism */ +/* CK_KEY_WRAP_SET_OAEP_PARAMS is new for v2.0 */ +typedef struct CK_KEY_WRAP_SET_OAEP_PARAMS { + CK_BYTE bBC; /* block contents byte */ + CK_BYTE_PTR pX; /* extra data */ + CK_ULONG ulXLen; /* length of extra data in bytes */ +} CK_KEY_WRAP_SET_OAEP_PARAMS; + +typedef CK_KEY_WRAP_SET_OAEP_PARAMS CK_PTR \ + CK_KEY_WRAP_SET_OAEP_PARAMS_PTR; + + +typedef struct CK_SSL3_RANDOM_DATA { + CK_BYTE_PTR pClientRandom; + CK_ULONG ulClientRandomLen; + CK_BYTE_PTR pServerRandom; + CK_ULONG ulServerRandomLen; +} CK_SSL3_RANDOM_DATA; + + +typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS { + CK_SSL3_RANDOM_DATA RandomInfo; + CK_VERSION_PTR pVersion; +} CK_SSL3_MASTER_KEY_DERIVE_PARAMS; + +typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS CK_PTR \ + CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR; + + +typedef struct CK_SSL3_KEY_MAT_OUT { + CK_OBJECT_HANDLE hClientMacSecret; + CK_OBJECT_HANDLE hServerMacSecret; + CK_OBJECT_HANDLE hClientKey; + CK_OBJECT_HANDLE hServerKey; + CK_BYTE_PTR pIVClient; + CK_BYTE_PTR pIVServer; +} CK_SSL3_KEY_MAT_OUT; + +typedef CK_SSL3_KEY_MAT_OUT CK_PTR CK_SSL3_KEY_MAT_OUT_PTR; + + +typedef struct CK_SSL3_KEY_MAT_PARAMS { + CK_ULONG ulMacSizeInBits; + CK_ULONG ulKeySizeInBits; + CK_ULONG ulIVSizeInBits; + CK_BBOOL bIsExport; + CK_SSL3_RANDOM_DATA RandomInfo; + CK_SSL3_KEY_MAT_OUT_PTR pReturnedKeyMaterial; +} CK_SSL3_KEY_MAT_PARAMS; + +typedef CK_SSL3_KEY_MAT_PARAMS CK_PTR CK_SSL3_KEY_MAT_PARAMS_PTR; + +/* CK_TLS_PRF_PARAMS is new for version 2.20 */ +typedef struct CK_TLS_PRF_PARAMS { + CK_BYTE_PTR pSeed; + CK_ULONG ulSeedLen; + CK_BYTE_PTR pLabel; + CK_ULONG ulLabelLen; + CK_BYTE_PTR pOutput; + CK_ULONG_PTR pulOutputLen; +} CK_TLS_PRF_PARAMS; + +typedef CK_TLS_PRF_PARAMS CK_PTR CK_TLS_PRF_PARAMS_PTR; + +/* WTLS is new for version 2.20 */ +typedef struct CK_WTLS_RANDOM_DATA { + CK_BYTE_PTR pClientRandom; + CK_ULONG ulClientRandomLen; + CK_BYTE_PTR pServerRandom; + CK_ULONG ulServerRandomLen; +} CK_WTLS_RANDOM_DATA; + +typedef CK_WTLS_RANDOM_DATA CK_PTR CK_WTLS_RANDOM_DATA_PTR; + +typedef struct CK_WTLS_MASTER_KEY_DERIVE_PARAMS { + CK_MECHANISM_TYPE DigestMechanism; + CK_WTLS_RANDOM_DATA RandomInfo; + CK_BYTE_PTR pVersion; +} CK_WTLS_MASTER_KEY_DERIVE_PARAMS; + +typedef CK_WTLS_MASTER_KEY_DERIVE_PARAMS CK_PTR \ + CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR; + +typedef struct CK_WTLS_PRF_PARAMS { + CK_MECHANISM_TYPE DigestMechanism; + CK_BYTE_PTR pSeed; + CK_ULONG ulSeedLen; + CK_BYTE_PTR pLabel; + CK_ULONG ulLabelLen; + CK_BYTE_PTR pOutput; + CK_ULONG_PTR pulOutputLen; +} CK_WTLS_PRF_PARAMS; + +typedef CK_WTLS_PRF_PARAMS CK_PTR CK_WTLS_PRF_PARAMS_PTR; + +typedef struct CK_WTLS_KEY_MAT_OUT { + CK_OBJECT_HANDLE hMacSecret; + CK_OBJECT_HANDLE hKey; + CK_BYTE_PTR pIV; +} CK_WTLS_KEY_MAT_OUT; + +typedef CK_WTLS_KEY_MAT_OUT CK_PTR CK_WTLS_KEY_MAT_OUT_PTR; + +typedef struct CK_WTLS_KEY_MAT_PARAMS { + CK_MECHANISM_TYPE DigestMechanism; + CK_ULONG ulMacSizeInBits; + CK_ULONG ulKeySizeInBits; + CK_ULONG ulIVSizeInBits; + CK_ULONG ulSequenceNumber; + CK_BBOOL bIsExport; + CK_WTLS_RANDOM_DATA RandomInfo; + CK_WTLS_KEY_MAT_OUT_PTR pReturnedKeyMaterial; +} CK_WTLS_KEY_MAT_PARAMS; + +typedef CK_WTLS_KEY_MAT_PARAMS CK_PTR CK_WTLS_KEY_MAT_PARAMS_PTR; + +/* CMS is new for version 2.20 */ +typedef struct CK_CMS_SIG_PARAMS { + CK_OBJECT_HANDLE certificateHandle; + CK_MECHANISM_PTR pSigningMechanism; + CK_MECHANISM_PTR pDigestMechanism; + CK_UTF8CHAR_PTR pContentType; + CK_BYTE_PTR pRequestedAttributes; + CK_ULONG ulRequestedAttributesLen; + CK_BYTE_PTR pRequiredAttributes; + CK_ULONG ulRequiredAttributesLen; +} CK_CMS_SIG_PARAMS; + +typedef CK_CMS_SIG_PARAMS CK_PTR CK_CMS_SIG_PARAMS_PTR; + +typedef struct CK_KEY_DERIVATION_STRING_DATA { + CK_BYTE_PTR pData; + CK_ULONG ulLen; +} CK_KEY_DERIVATION_STRING_DATA; + +typedef CK_KEY_DERIVATION_STRING_DATA CK_PTR \ + CK_KEY_DERIVATION_STRING_DATA_PTR; + + +/* The CK_EXTRACT_PARAMS is used for the + * CKM_EXTRACT_KEY_FROM_KEY mechanism. It specifies which bit + * of the base key should be used as the first bit of the + * derived key */ +/* CK_EXTRACT_PARAMS is new for v2.0 */ +typedef CK_ULONG CK_EXTRACT_PARAMS; + +typedef CK_EXTRACT_PARAMS CK_PTR CK_EXTRACT_PARAMS_PTR; + +/* CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is new for v2.10. + * CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is used to + * indicate the Pseudo-Random Function (PRF) used to generate + * key bits using PKCS #5 PBKDF2. */ +typedef CK_ULONG CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE; + +typedef CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE CK_PTR CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR; + +/* The following PRFs are defined in PKCS #5 v2.0. */ +#define CKP_PKCS5_PBKD2_HMAC_SHA1 0x00000001 + + +/* CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is new for v2.10. + * CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is used to indicate the + * source of the salt value when deriving a key using PKCS #5 + * PBKDF2. */ +typedef CK_ULONG CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE; + +typedef CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE CK_PTR CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR; + +/* The following salt value sources are defined in PKCS #5 v2.0. */ +#define CKZ_SALT_SPECIFIED 0x00000001 + +/* CK_PKCS5_PBKD2_PARAMS is new for v2.10. + * CK_PKCS5_PBKD2_PARAMS is a structure that provides the + * parameters to the CKM_PKCS5_PBKD2 mechanism. */ +typedef struct CK_PKCS5_PBKD2_PARAMS { + CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE saltSource; + CK_VOID_PTR pSaltSourceData; + CK_ULONG ulSaltSourceDataLen; + CK_ULONG iterations; + CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE prf; + CK_VOID_PTR pPrfData; + CK_ULONG ulPrfDataLen; + CK_UTF8CHAR_PTR pPassword; + CK_ULONG_PTR ulPasswordLen; +} CK_PKCS5_PBKD2_PARAMS; + +typedef CK_PKCS5_PBKD2_PARAMS CK_PTR CK_PKCS5_PBKD2_PARAMS_PTR; + +/* All CK_OTP structs are new for PKCS #11 v2.20 amendment 3 */ + +typedef CK_ULONG CK_OTP_PARAM_TYPE; +typedef CK_OTP_PARAM_TYPE CK_PARAM_TYPE; /* B/w compatibility */ + +typedef struct CK_OTP_PARAM { + CK_OTP_PARAM_TYPE type; + CK_VOID_PTR pValue; + CK_ULONG ulValueLen; +} CK_OTP_PARAM; + +typedef CK_OTP_PARAM CK_PTR CK_OTP_PARAM_PTR; + +typedef struct CK_OTP_PARAMS { + CK_OTP_PARAM_PTR pParams; + CK_ULONG ulCount; +} CK_OTP_PARAMS; + +typedef CK_OTP_PARAMS CK_PTR CK_OTP_PARAMS_PTR; + +typedef struct CK_OTP_SIGNATURE_INFO { + CK_OTP_PARAM_PTR pParams; + CK_ULONG ulCount; +} CK_OTP_SIGNATURE_INFO; + +typedef CK_OTP_SIGNATURE_INFO CK_PTR CK_OTP_SIGNATURE_INFO_PTR; + +/* The following OTP-related defines are new for PKCS #11 v2.20 amendment 1 */ +#define CK_OTP_VALUE 0 +#define CK_OTP_PIN 1 +#define CK_OTP_CHALLENGE 2 +#define CK_OTP_TIME 3 +#define CK_OTP_COUNTER 4 +#define CK_OTP_FLAGS 5 +#define CK_OTP_OUTPUT_LENGTH 6 +#define CK_OTP_OUTPUT_FORMAT 7 + +/* The following OTP-related defines are new for PKCS #11 v2.20 amendment 1 */ +#define CKF_NEXT_OTP 0x00000001 +#define CKF_EXCLUDE_TIME 0x00000002 +#define CKF_EXCLUDE_COUNTER 0x00000004 +#define CKF_EXCLUDE_CHALLENGE 0x00000008 +#define CKF_EXCLUDE_PIN 0x00000010 +#define CKF_USER_FRIENDLY_OTP 0x00000020 + +/* CK_KIP_PARAMS is new for PKCS #11 v2.20 amendment 2 */ +typedef struct CK_KIP_PARAMS { + CK_MECHANISM_PTR pMechanism; + CK_OBJECT_HANDLE hKey; + CK_BYTE_PTR pSeed; + CK_ULONG ulSeedLen; +} CK_KIP_PARAMS; + +typedef CK_KIP_PARAMS CK_PTR CK_KIP_PARAMS_PTR; + +/* CK_AES_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */ +typedef struct CK_AES_CTR_PARAMS { + CK_ULONG ulCounterBits; + CK_BYTE cb[16]; +} CK_AES_CTR_PARAMS; + +typedef CK_AES_CTR_PARAMS CK_PTR CK_AES_CTR_PARAMS_PTR; + +/* CK_CAMELLIA_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */ +typedef struct CK_CAMELLIA_CTR_PARAMS { + CK_ULONG ulCounterBits; + CK_BYTE cb[16]; +} CK_CAMELLIA_CTR_PARAMS; + +typedef CK_CAMELLIA_CTR_PARAMS CK_PTR CK_CAMELLIA_CTR_PARAMS_PTR; + +/* CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS is new for PKCS #11 v2.20 amendment 3 */ +typedef struct CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS { + CK_BYTE iv[16]; + CK_BYTE_PTR pData; + CK_ULONG length; +} CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS; + +typedef CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR; + +/* CK_ARIA_CBC_ENCRYPT_DATA_PARAMS is new for PKCS #11 v2.20 amendment 3 */ +typedef struct CK_ARIA_CBC_ENCRYPT_DATA_PARAMS { + CK_BYTE iv[16]; + CK_BYTE_PTR pData; + CK_ULONG length; +} CK_ARIA_CBC_ENCRYPT_DATA_PARAMS; + +typedef CK_ARIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR; + +#endif diff --git a/src/Platform/Buffer.cpp b/src/Platform/Buffer.cpp index 4b2ac528..2d2a9217 100644 --- a/src/Platform/Buffer.cpp +++ b/src/Platform/Buffer.cpp @@ -8,143 +8,143 @@ 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 "Buffer.h" -#include "Exception.h" - -namespace VeraCrypt -{ - Buffer::Buffer () : DataPtr (nullptr), DataSize (0) - { - } - - Buffer::Buffer (size_t size) : DataPtr (nullptr), DataSize (0) - { - Allocate (size); - } - - Buffer::~Buffer () - { - if (DataPtr != nullptr) - Free (); - } - - void Buffer::Allocate (size_t size) - { - if (size < 1) - throw ParameterIncorrect (SRC_POS); - - if (DataPtr != nullptr) - { - if (DataSize == size) - return; - Free(); - } - - try - { - DataPtr = static_cast (Memory::Allocate (size)); - DataSize = size; - } - catch (...) - { - DataPtr = nullptr; - DataSize = 0; - throw; - } - } - - void Buffer::CopyFrom (const ConstBufferPtr &bufferPtr) - { - if (!IsAllocated ()) - { - if (bufferPtr.Size()) - Allocate (bufferPtr.Size()); - } - else if (bufferPtr.Size() > DataSize) - throw ParameterTooLarge (SRC_POS); - - if (bufferPtr.Size()) - Memory::Copy (DataPtr, bufferPtr.Get(), bufferPtr.Size()); - } - - void Buffer::Erase () - { - if (DataSize > 0) - Memory::Erase (DataPtr, DataSize); - } - - void Buffer::Free () - { - if (DataPtr == nullptr) - throw NotInitialized (SRC_POS); - - Memory::Free (DataPtr); - DataPtr = nullptr; - DataSize = 0; - } - - BufferPtr Buffer::GetRange (size_t offset, size_t size) const - { - if (offset + size > DataSize) - throw ParameterIncorrect (SRC_POS); - - return BufferPtr (DataPtr + offset, size); - } - - void Buffer::Zero () - { - if (DataSize > 0) - Memory::Zero (DataPtr, DataSize); - } - - SecureBuffer::SecureBuffer (size_t size) - { - Allocate (size); - } - - SecureBuffer::~SecureBuffer () - { - if (DataPtr != nullptr && DataSize != 0) - Free (); - } - - void SecureBuffer::Allocate (size_t size) - { - Buffer::Allocate (size); - } - - void SecureBuffer::Free () - { - if (DataPtr == nullptr) - throw NotInitialized (SRC_POS); - - Erase (); - Buffer::Free (); - } - - void BufferPtr::CopyFrom (const ConstBufferPtr &bufferPtr) const - { - if (bufferPtr.Size() > DataSize) - throw ParameterTooLarge (SRC_POS); - - Memory::Copy (DataPtr, bufferPtr.Get(), bufferPtr.Size()); - } - - BufferPtr BufferPtr::GetRange (size_t offset, size_t size) const - { - if (offset + size > DataSize) - throw ParameterIncorrect (SRC_POS); - - return BufferPtr (DataPtr + offset, size); - } - - ConstBufferPtr ConstBufferPtr::GetRange (size_t offset, size_t size) const - { - if (offset + size > DataSize) - throw ParameterIncorrect (SRC_POS); - - return ConstBufferPtr (DataPtr + offset, size); - } -} +*/ + +#include "Buffer.h" +#include "Exception.h" + +namespace VeraCrypt +{ + Buffer::Buffer () : DataPtr (nullptr), DataSize (0) + { + } + + Buffer::Buffer (size_t size) : DataPtr (nullptr), DataSize (0) + { + Allocate (size); + } + + Buffer::~Buffer () + { + if (DataPtr != nullptr) + Free (); + } + + void Buffer::Allocate (size_t size) + { + if (size < 1) + throw ParameterIncorrect (SRC_POS); + + if (DataPtr != nullptr) + { + if (DataSize == size) + return; + Free(); + } + + try + { + DataPtr = static_cast (Memory::Allocate (size)); + DataSize = size; + } + catch (...) + { + DataPtr = nullptr; + DataSize = 0; + throw; + } + } + + void Buffer::CopyFrom (const ConstBufferPtr &bufferPtr) + { + if (!IsAllocated ()) + { + if (bufferPtr.Size()) + Allocate (bufferPtr.Size()); + } + else if (bufferPtr.Size() > DataSize) + throw ParameterTooLarge (SRC_POS); + + if (bufferPtr.Size()) + Memory::Copy (DataPtr, bufferPtr.Get(), bufferPtr.Size()); + } + + void Buffer::Erase () + { + if (DataSize > 0) + Memory::Erase (DataPtr, DataSize); + } + + void Buffer::Free () + { + if (DataPtr == nullptr) + throw NotInitialized (SRC_POS); + + Memory::Free (DataPtr); + DataPtr = nullptr; + DataSize = 0; + } + + BufferPtr Buffer::GetRange (size_t offset, size_t size) const + { + if (offset + size > DataSize) + throw ParameterIncorrect (SRC_POS); + + return BufferPtr (DataPtr + offset, size); + } + + void Buffer::Zero () + { + if (DataSize > 0) + Memory::Zero (DataPtr, DataSize); + } + + SecureBuffer::SecureBuffer (size_t size) + { + Allocate (size); + } + + SecureBuffer::~SecureBuffer () + { + if (DataPtr != nullptr && DataSize != 0) + Free (); + } + + void SecureBuffer::Allocate (size_t size) + { + Buffer::Allocate (size); + } + + void SecureBuffer::Free () + { + if (DataPtr == nullptr) + throw NotInitialized (SRC_POS); + + Erase (); + Buffer::Free (); + } + + void BufferPtr::CopyFrom (const ConstBufferPtr &bufferPtr) const + { + if (bufferPtr.Size() > DataSize) + throw ParameterTooLarge (SRC_POS); + + Memory::Copy (DataPtr, bufferPtr.Get(), bufferPtr.Size()); + } + + BufferPtr BufferPtr::GetRange (size_t offset, size_t size) const + { + if (offset + size > DataSize) + throw ParameterIncorrect (SRC_POS); + + return BufferPtr (DataPtr + offset, size); + } + + ConstBufferPtr ConstBufferPtr::GetRange (size_t offset, size_t size) const + { + if (offset + size > DataSize) + throw ParameterIncorrect (SRC_POS); + + return ConstBufferPtr (DataPtr + offset, size); + } +} diff --git a/src/Platform/Buffer.h b/src/Platform/Buffer.h index 532ad212..3d2d5f53 100644 --- a/src/Platform/Buffer.h +++ b/src/Platform/Buffer.h @@ -8,112 +8,112 @@ 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_Platform_Buffer -#define TC_HEADER_Platform_Buffer - -#include "PlatformBase.h" -#include "Memory.h" - -namespace VeraCrypt -{ - - class ConstBufferPtr - { - public: - ConstBufferPtr () - : DataPtr (nullptr), DataSize (0) { } - ConstBufferPtr (const byte *data, size_t size) - : DataPtr (data), DataSize (size) { } - virtual ~ConstBufferPtr () { } - - operator const byte * () const { return DataPtr; } - - bool IsDataEqual (const ConstBufferPtr &other) const { return Memory::Compare (DataPtr, DataSize, other.DataPtr, other.DataSize) == 0; } - const byte *Get () const { return DataPtr; } - ConstBufferPtr GetRange (size_t offset, size_t size) const; - void Set (const byte *data, size_t size) { DataPtr = data; DataSize = size; } - size_t Size () const { return DataSize; } - - protected: - const byte *DataPtr; - size_t DataSize; - }; - - - class BufferPtr - { - public: - BufferPtr () - : DataPtr (nullptr), DataSize (0) { } - BufferPtr (byte *data, size_t size) - : DataPtr (data), DataSize (size) { } - virtual ~BufferPtr () { } - - operator byte * () const { return DataPtr; } - void CopyFrom (const ConstBufferPtr &bufferPtr) const; - void Erase () const { Zero(); } - byte *Get () const { return DataPtr; } - BufferPtr GetRange (size_t offset, size_t size) const; - void Set (byte *data, size_t size) { DataPtr = data; DataSize = size; } - size_t Size () const { return DataSize; } - void Zero () const { Memory::Zero (DataPtr, DataSize); } - - operator ConstBufferPtr () const { return ConstBufferPtr (DataPtr, DataSize); } - - protected: - byte *DataPtr; - size_t DataSize; - }; - - class Buffer - { - public: - Buffer (); - Buffer (size_t size); - Buffer (const ConstBufferPtr &bufferPtr) { CopyFrom (bufferPtr); } - virtual ~Buffer (); - - virtual void Allocate (size_t size); - virtual void CopyFrom (const ConstBufferPtr &bufferPtr); - virtual byte *Ptr () const { return DataPtr; } - virtual void Erase (); - virtual void Free (); - virtual BufferPtr GetRange (size_t offset, size_t size) const; - virtual size_t Size () const { return DataSize; } - virtual bool IsAllocated () const { return DataSize != 0; } - virtual void Zero (); - - virtual operator byte * () const { return DataPtr; } - virtual operator BufferPtr () const { return BufferPtr (DataPtr, DataSize); } - virtual operator ConstBufferPtr () const { return ConstBufferPtr (DataPtr, DataSize); } - - protected: - byte *DataPtr; - size_t DataSize; - - private: - Buffer (const Buffer &); - Buffer &operator= (const Buffer &); - }; - - class SecureBuffer : public Buffer - { - public: - SecureBuffer () { } - SecureBuffer (size_t size); - SecureBuffer (const ConstBufferPtr &bufferPtr) { CopyFrom (bufferPtr); } - virtual ~SecureBuffer (); - - virtual void Allocate (size_t size); - virtual void Free (); - - private: - SecureBuffer (const SecureBuffer &); - SecureBuffer &operator= (const SecureBuffer &); - }; - -} - -#endif // TC_HEADER_Platform_Buffer +*/ + +#ifndef TC_HEADER_Platform_Buffer +#define TC_HEADER_Platform_Buffer + +#include "PlatformBase.h" +#include "Memory.h" + +namespace VeraCrypt +{ + + class ConstBufferPtr + { + public: + ConstBufferPtr () + : DataPtr (nullptr), DataSize (0) { } + ConstBufferPtr (const byte *data, size_t size) + : DataPtr (data), DataSize (size) { } + virtual ~ConstBufferPtr () { } + + operator const byte * () const { return DataPtr; } + + bool IsDataEqual (const ConstBufferPtr &other) const { return Memory::Compare (DataPtr, DataSize, other.DataPtr, other.DataSize) == 0; } + const byte *Get () const { return DataPtr; } + ConstBufferPtr GetRange (size_t offset, size_t size) const; + void Set (const byte *data, size_t size) { DataPtr = data; DataSize = size; } + size_t Size () const { return DataSize; } + + protected: + const byte *DataPtr; + size_t DataSize; + }; + + + class BufferPtr + { + public: + BufferPtr () + : DataPtr (nullptr), DataSize (0) { } + BufferPtr (byte *data, size_t size) + : DataPtr (data), DataSize (size) { } + virtual ~BufferPtr () { } + + operator byte * () const { return DataPtr; } + void CopyFrom (const ConstBufferPtr &bufferPtr) const; + void Erase () const { Zero(); } + byte *Get () const { return DataPtr; } + BufferPtr GetRange (size_t offset, size_t size) const; + void Set (byte *data, size_t size) { DataPtr = data; DataSize = size; } + size_t Size () const { return DataSize; } + void Zero () const { Memory::Zero (DataPtr, DataSize); } + + operator ConstBufferPtr () const { return ConstBufferPtr (DataPtr, DataSize); } + + protected: + byte *DataPtr; + size_t DataSize; + }; + + class Buffer + { + public: + Buffer (); + Buffer (size_t size); + Buffer (const ConstBufferPtr &bufferPtr) { CopyFrom (bufferPtr); } + virtual ~Buffer (); + + virtual void Allocate (size_t size); + virtual void CopyFrom (const ConstBufferPtr &bufferPtr); + virtual byte *Ptr () const { return DataPtr; } + virtual void Erase (); + virtual void Free (); + virtual BufferPtr GetRange (size_t offset, size_t size) const; + virtual size_t Size () const { return DataSize; } + virtual bool IsAllocated () const { return DataSize != 0; } + virtual void Zero (); + + virtual operator byte * () const { return DataPtr; } + virtual operator BufferPtr () const { return BufferPtr (DataPtr, DataSize); } + virtual operator ConstBufferPtr () const { return ConstBufferPtr (DataPtr, DataSize); } + + protected: + byte *DataPtr; + size_t DataSize; + + private: + Buffer (const Buffer &); + Buffer &operator= (const Buffer &); + }; + + class SecureBuffer : public Buffer + { + public: + SecureBuffer () { } + SecureBuffer (size_t size); + SecureBuffer (const ConstBufferPtr &bufferPtr) { CopyFrom (bufferPtr); } + virtual ~SecureBuffer (); + + virtual void Allocate (size_t size); + virtual void Free (); + + private: + SecureBuffer (const SecureBuffer &); + SecureBuffer &operator= (const SecureBuffer &); + }; + +} + +#endif // TC_HEADER_Platform_Buffer diff --git a/src/Platform/Directory.h b/src/Platform/Directory.h index 923c2248..574be3b2 100644 --- a/src/Platform/Directory.h +++ b/src/Platform/Directory.h @@ -8,26 +8,26 @@ 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_Platform_Directory -#define TC_HEADER_Platform_Directory - -#include "PlatformBase.h" -#include "FilesystemPath.h" - -namespace VeraCrypt -{ - class Directory - { - public: - static void Create (const DirectoryPath &path); - static DirectoryPath AppendSeparator (const DirectoryPath &path); - static FilePathList GetFilePaths (const DirectoryPath &path = L".", bool regularFilesOnly = true); - - private: - Directory (); - }; -} - -#endif // TC_HEADER_Platform_Directory +*/ + +#ifndef TC_HEADER_Platform_Directory +#define TC_HEADER_Platform_Directory + +#include "PlatformBase.h" +#include "FilesystemPath.h" + +namespace VeraCrypt +{ + class Directory + { + public: + static void Create (const DirectoryPath &path); + static DirectoryPath AppendSeparator (const DirectoryPath &path); + static FilePathList GetFilePaths (const DirectoryPath &path = L".", bool regularFilesOnly = true); + + private: + Directory (); + }; +} + +#endif // TC_HEADER_Platform_Directory diff --git a/src/Platform/Event.cpp b/src/Platform/Event.cpp index e3a7362c..d6e51182 100644 --- a/src/Platform/Event.cpp +++ b/src/Platform/Event.cpp @@ -8,44 +8,44 @@ 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 "Event.h" - -namespace VeraCrypt -{ - void Event::Connect (const EventConnectorBase &connector) - { - ScopeLock lock (HandlersMutex); - ConnectedHandlers.push_back (shared_ptr (connector.CloneNew())); - } - - void Event::Disconnect (void *handler) - { - ScopeLock lock (HandlersMutex); - - EventHandlerList newConnectedHandlers; - foreach (shared_ptr h, ConnectedHandlers) - { - if (h->GetHandler() != handler) - newConnectedHandlers.push_back (h); - } - - ConnectedHandlers = newConnectedHandlers; - } - - void Event::Raise () - { - EventArgs args; - Raise (args); - } - - void Event::Raise (EventArgs &args) - { - ScopeLock lock (HandlersMutex); - foreach_ref (EventConnectorBase &handler, ConnectedHandlers) - { - handler (args); - } - } -} +*/ + +#include "Event.h" + +namespace VeraCrypt +{ + void Event::Connect (const EventConnectorBase &connector) + { + ScopeLock lock (HandlersMutex); + ConnectedHandlers.push_back (shared_ptr (connector.CloneNew())); + } + + void Event::Disconnect (void *handler) + { + ScopeLock lock (HandlersMutex); + + EventHandlerList newConnectedHandlers; + foreach (shared_ptr h, ConnectedHandlers) + { + if (h->GetHandler() != handler) + newConnectedHandlers.push_back (h); + } + + ConnectedHandlers = newConnectedHandlers; + } + + void Event::Raise () + { + EventArgs args; + Raise (args); + } + + void Event::Raise (EventArgs &args) + { + ScopeLock lock (HandlersMutex); + foreach_ref (EventConnectorBase &handler, ConnectedHandlers) + { + handler (args); + } + } +} diff --git a/src/Platform/Event.h b/src/Platform/Event.h index bdfc67da..b28bc90d 100644 --- a/src/Platform/Event.h +++ b/src/Platform/Event.h @@ -8,83 +8,83 @@ 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_Platform_Event -#define TC_HEADER_Platform_Event - -#include "PlatformBase.h" -#include "ForEach.h" -#include "Mutex.h" -#include "SharedPtr.h" - -namespace VeraCrypt -{ - struct EventArgs - { - virtual ~EventArgs () { } - }; - - class EventConnectorBase - { - public: - virtual ~EventConnectorBase () { } - virtual void operator() (EventArgs &args) = 0; - - virtual EventConnectorBase *CloneNew () const = 0; - virtual void *GetHandler () const = 0; - }; - - typedef list < shared_ptr > EventHandlerList; - - template - class EventConnector : public EventConnectorBase - { - public: - typedef void (T::*EventHandlerFunction) (EventArgs &); - - EventConnector (T *handler, EventHandlerFunction function) - : Handler (handler), Function (function) { } - - virtual void operator() (EventArgs &args) { (Handler->*Function) (args); } - - virtual EventConnectorBase *CloneNew () const { return new EventConnector (*this); } - virtual void *GetHandler () const { return Handler; } - - protected: - T *Handler; - EventHandlerFunction Function; - }; - - class Event - { - public: - Event () { } - virtual ~Event () { } - - void Connect (const EventConnectorBase &connector); - void Disconnect (void *handler); - void Raise (); - void Raise (EventArgs &args); - - protected: - EventHandlerList ConnectedHandlers; - Mutex HandlersMutex; - - private: - Event (const Event &); - Event &operator= (const Event &); - }; - - struct ExceptionEventArgs : public EventArgs - { - ExceptionEventArgs (exception &ex) : mException (ex) { } - exception &mException; - - private: - ExceptionEventArgs (const ExceptionEventArgs &); - ExceptionEventArgs &operator= (const ExceptionEventArgs &); - }; -} - -#endif // TC_HEADER_Platform_Event +*/ + +#ifndef TC_HEADER_Platform_Event +#define TC_HEADER_Platform_Event + +#include "PlatformBase.h" +#include "ForEach.h" +#include "Mutex.h" +#include "SharedPtr.h" + +namespace VeraCrypt +{ + struct EventArgs + { + virtual ~EventArgs () { } + }; + + class EventConnectorBase + { + public: + virtual ~EventConnectorBase () { } + virtual void operator() (EventArgs &args) = 0; + + virtual EventConnectorBase *CloneNew () const = 0; + virtual void *GetHandler () const = 0; + }; + + typedef list < shared_ptr > EventHandlerList; + + template + class EventConnector : public EventConnectorBase + { + public: + typedef void (T::*EventHandlerFunction) (EventArgs &); + + EventConnector (T *handler, EventHandlerFunction function) + : Handler (handler), Function (function) { } + + virtual void operator() (EventArgs &args) { (Handler->*Function) (args); } + + virtual EventConnectorBase *CloneNew () const { return new EventConnector (*this); } + virtual void *GetHandler () const { return Handler; } + + protected: + T *Handler; + EventHandlerFunction Function; + }; + + class Event + { + public: + Event () { } + virtual ~Event () { } + + void Connect (const EventConnectorBase &connector); + void Disconnect (void *handler); + void Raise (); + void Raise (EventArgs &args); + + protected: + EventHandlerList ConnectedHandlers; + Mutex HandlersMutex; + + private: + Event (const Event &); + Event &operator= (const Event &); + }; + + struct ExceptionEventArgs : public EventArgs + { + ExceptionEventArgs (exception &ex) : mException (ex) { } + exception &mException; + + private: + ExceptionEventArgs (const ExceptionEventArgs &); + ExceptionEventArgs &operator= (const ExceptionEventArgs &); + }; +} + +#endif // TC_HEADER_Platform_Event diff --git a/src/Platform/Exception.cpp b/src/Platform/Exception.cpp index c2fcd586..31d25b88 100644 --- a/src/Platform/Exception.cpp +++ b/src/Platform/Exception.cpp @@ -8,49 +8,49 @@ 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 "Exception.h" -#include "SerializerFactory.h" - -namespace VeraCrypt -{ - void Exception::Deserialize (shared_ptr stream) - { - Serializer sr (stream); - sr.Deserialize ("Message", Message); - sr.Deserialize ("Subject", Subject); - } - - void Exception::Serialize (shared_ptr stream) const - { - Serializable::Serialize (stream); - Serializer sr (stream); - sr.Serialize ("Message", Message); - sr.Serialize ("Subject", Subject); - } - - void ExecutedProcessFailed::Deserialize (shared_ptr stream) - { - Exception::Deserialize (stream); - Serializer sr (stream); - sr.Deserialize ("Command", Command); - sr.Deserialize ("ExitCode", ExitCode); - sr.Deserialize ("ErrorOutput", ErrorOutput); - } - - void ExecutedProcessFailed::Serialize (shared_ptr stream) const - { - Exception::Serialize (stream); - Serializer sr (stream); - sr.Serialize ("Command", Command); - sr.Serialize ("ExitCode", ExitCode); - sr.Serialize ("ErrorOutput", ErrorOutput); - } - -#define TC_EXCEPTION(TYPE) TC_SERIALIZER_FACTORY_ADD(TYPE) -#undef TC_EXCEPTION_NODECL -#define TC_EXCEPTION_NODECL(TYPE) TC_SERIALIZER_FACTORY_ADD(TYPE) - - TC_SERIALIZER_FACTORY_ADD_EXCEPTION_SET (Exception); -} +*/ + +#include "Exception.h" +#include "SerializerFactory.h" + +namespace VeraCrypt +{ + void Exception::Deserialize (shared_ptr stream) + { + Serializer sr (stream); + sr.Deserialize ("Message", Message); + sr.Deserialize ("Subject", Subject); + } + + void Exception::Serialize (shared_ptr stream) const + { + Serializable::Serialize (stream); + Serializer sr (stream); + sr.Serialize ("Message", Message); + sr.Serialize ("Subject", Subject); + } + + void ExecutedProcessFailed::Deserialize (shared_ptr stream) + { + Exception::Deserialize (stream); + Serializer sr (stream); + sr.Deserialize ("Command", Command); + sr.Deserialize ("ExitCode", ExitCode); + sr.Deserialize ("ErrorOutput", ErrorOutput); + } + + void ExecutedProcessFailed::Serialize (shared_ptr stream) const + { + Exception::Serialize (stream); + Serializer sr (stream); + sr.Serialize ("Command", Command); + sr.Serialize ("ExitCode", ExitCode); + sr.Serialize ("ErrorOutput", ErrorOutput); + } + +#define TC_EXCEPTION(TYPE) TC_SERIALIZER_FACTORY_ADD(TYPE) +#undef TC_EXCEPTION_NODECL +#define TC_EXCEPTION_NODECL(TYPE) TC_SERIALIZER_FACTORY_ADD(TYPE) + + TC_SERIALIZER_FACTORY_ADD_EXCEPTION_SET (Exception); +} diff --git a/src/Platform/Exception.h b/src/Platform/Exception.h index f2ba64bc..1a5769ef 100644 --- a/src/Platform/Exception.h +++ b/src/Platform/Exception.h @@ -8,109 +8,109 @@ 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_Platform_Exception -#define TC_HEADER_Platform_Exception - -#include -#include "PlatformBase.h" -#include "Serializable.h" - -namespace VeraCrypt -{ -#define TC_SERIALIZABLE_EXCEPTION(TYPE) TC_SERIALIZABLE (TYPE); \ - virtual Exception *CloneNew () { return new TYPE (*this); } \ - virtual void Throw () const { throw *this; } - - struct Exception : public exception, public Serializable - { - public: - Exception () { } - Exception (const string &message) : Message (message) { } - Exception (const string &message, const wstring &subject) : Message (message), Subject (subject) { } - virtual ~Exception () throw () { } - - TC_SERIALIZABLE_EXCEPTION (Exception); - - virtual const char *what () const throw () { return Message.c_str(); } - virtual const wstring &GetSubject() const { return Subject; } - - protected: - string Message; - wstring Subject; - }; - - struct ExecutedProcessFailed : public Exception - { - ExecutedProcessFailed () { } - ExecutedProcessFailed (const string &message, const string &command, int exitCode, const string &errorOutput) - : Exception (message), Command (command), ExitCode (exitCode), ErrorOutput (errorOutput) { } - virtual ~ExecutedProcessFailed () throw () { } - - TC_SERIALIZABLE_EXCEPTION (ExecutedProcessFailed); - - string GetCommand () const { return Command; } - int64 GetExitCode () const { return ExitCode; } - string GetErrorOutput () const { return ErrorOutput; } - - protected: - string Command; - int64 ExitCode; - string ErrorOutput; - }; - -#define TC_EXCEPTION_DECL(NAME,BASE) \ - struct NAME : public BASE \ - { \ - NAME () { } \ - NAME (const string &message) : BASE (message) { } \ - NAME (const string &message, const wstring &subject) : BASE (message, subject) { } \ - virtual Exception *CloneNew () { return new NAME (*this); } \ - static Serializable *GetNewSerializable () { return new NAME (); } \ - virtual void Throw () const { throw *this; } \ - } - -#define TC_EXCEPTION_NODECL(dummy) // -#define TC_EXCEPTION(NAME) TC_EXCEPTION_DECL(NAME,Exception) - -#ifdef TC_EXCEPTION_SET -#undef TC_EXCEPTION_SET -#endif -#define TC_EXCEPTION_SET \ - TC_EXCEPTION_NODECL (Exception); \ - TC_EXCEPTION_NODECL (ExecutedProcessFailed); \ - TC_EXCEPTION (AlreadyInitialized); \ - TC_EXCEPTION (AssertionFailed); \ - TC_EXCEPTION (ExternalException); \ - TC_EXCEPTION (InsufficientData); \ - TC_EXCEPTION (NotApplicable); \ - TC_EXCEPTION (NotImplemented); \ - TC_EXCEPTION (NotInitialized); \ - TC_EXCEPTION (ParameterIncorrect); \ - TC_EXCEPTION (ParameterTooLarge); \ - TC_EXCEPTION (PartitionDeviceRequired); \ - TC_EXCEPTION (StringConversionFailed); \ - TC_EXCEPTION (TestFailed); \ - TC_EXCEPTION (TimeOut); \ +*/ + +#ifndef TC_HEADER_Platform_Exception +#define TC_HEADER_Platform_Exception + +#include +#include "PlatformBase.h" +#include "Serializable.h" + +namespace VeraCrypt +{ +#define TC_SERIALIZABLE_EXCEPTION(TYPE) TC_SERIALIZABLE (TYPE); \ + virtual Exception *CloneNew () { return new TYPE (*this); } \ + virtual void Throw () const { throw *this; } + + struct Exception : public exception, public Serializable + { + public: + Exception () { } + Exception (const string &message) : Message (message) { } + Exception (const string &message, const wstring &subject) : Message (message), Subject (subject) { } + virtual ~Exception () throw () { } + + TC_SERIALIZABLE_EXCEPTION (Exception); + + virtual const char *what () const throw () { return Message.c_str(); } + virtual const wstring &GetSubject() const { return Subject; } + + protected: + string Message; + wstring Subject; + }; + + struct ExecutedProcessFailed : public Exception + { + ExecutedProcessFailed () { } + ExecutedProcessFailed (const string &message, const string &command, int exitCode, const string &errorOutput) + : Exception (message), Command (command), ExitCode (exitCode), ErrorOutput (errorOutput) { } + virtual ~ExecutedProcessFailed () throw () { } + + TC_SERIALIZABLE_EXCEPTION (ExecutedProcessFailed); + + string GetCommand () const { return Command; } + int64 GetExitCode () const { return ExitCode; } + string GetErrorOutput () const { return ErrorOutput; } + + protected: + string Command; + int64 ExitCode; + string ErrorOutput; + }; + +#define TC_EXCEPTION_DECL(NAME,BASE) \ + struct NAME : public BASE \ + { \ + NAME () { } \ + NAME (const string &message) : BASE (message) { } \ + NAME (const string &message, const wstring &subject) : BASE (message, subject) { } \ + virtual Exception *CloneNew () { return new NAME (*this); } \ + static Serializable *GetNewSerializable () { return new NAME (); } \ + virtual void Throw () const { throw *this; } \ + } + +#define TC_EXCEPTION_NODECL(dummy) // +#define TC_EXCEPTION(NAME) TC_EXCEPTION_DECL(NAME,Exception) + +#ifdef TC_EXCEPTION_SET +#undef TC_EXCEPTION_SET +#endif +#define TC_EXCEPTION_SET \ + TC_EXCEPTION_NODECL (Exception); \ + TC_EXCEPTION_NODECL (ExecutedProcessFailed); \ + TC_EXCEPTION (AlreadyInitialized); \ + TC_EXCEPTION (AssertionFailed); \ + TC_EXCEPTION (ExternalException); \ + TC_EXCEPTION (InsufficientData); \ + TC_EXCEPTION (NotApplicable); \ + TC_EXCEPTION (NotImplemented); \ + TC_EXCEPTION (NotInitialized); \ + TC_EXCEPTION (ParameterIncorrect); \ + TC_EXCEPTION (ParameterTooLarge); \ + TC_EXCEPTION (PartitionDeviceRequired); \ + TC_EXCEPTION (StringConversionFailed); \ + TC_EXCEPTION (TestFailed); \ + TC_EXCEPTION (TimeOut); \ TC_EXCEPTION (UnknownException); \ TC_EXCEPTION (UnsupportedAlgoInTrueCryptMode); \ - TC_EXCEPTION (UnsupportedTrueCryptFormat); \ - TC_EXCEPTION (UserAbort) - - TC_EXCEPTION_SET; - -#undef TC_EXCEPTION -} - -#ifdef assert -# undef assert -#endif - -#ifdef DEBUG -# define assert(condition) do { if (!(condition)) throw AssertionFailed (SRC_POS); } while (false) -#else -# define assert(condition) ((void) 0) -#endif - -#endif // TC_HEADER_Platform_Exception + TC_EXCEPTION (UnsupportedTrueCryptFormat); \ + TC_EXCEPTION (UserAbort) + + TC_EXCEPTION_SET; + +#undef TC_EXCEPTION +} + +#ifdef assert +# undef assert +#endif + +#ifdef DEBUG +# define assert(condition) do { if (!(condition)) throw AssertionFailed (SRC_POS); } while (false) +#else +# define assert(condition) ((void) 0) +#endif + +#endif // TC_HEADER_Platform_Exception diff --git a/src/Platform/File.h b/src/Platform/File.h index ea4fef93..d23ac6b1 100644 --- a/src/Platform/File.h +++ b/src/Platform/File.h @@ -8,107 +8,107 @@ 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_Platform_File -#define TC_HEADER_Platform_File - -#include "PlatformBase.h" -#include "Buffer.h" -#include "FilesystemPath.h" -#include "SystemException.h" - -namespace VeraCrypt -{ - class File - { - public: - enum FileOpenMode - { - CreateReadWrite, - CreateWrite, - OpenRead, - OpenWrite, - OpenReadWrite - }; - - enum FileShareMode - { - ShareNone, - ShareRead, - ShareReadWrite, - ShareReadWriteIgnoreLock - }; - - enum FileOpenFlags - { - // Bitmap - FlagsNone = 0, - PreserveTimestamps = 1 << 0, - DisableWriteCaching = 1 << 1 - }; - -#ifdef TC_WINDOWS - typedef FILE* SystemFileHandleType; -#else - typedef int SystemFileHandleType; -#endif - - File () : FileIsOpen (false), SharedHandle (false) { } - virtual ~File (); - - void AssignSystemHandle (SystemFileHandleType openFileHandle, bool sharedHandle = true) - { - if (FileIsOpen) - Close(); - FileHandle = openFileHandle; - FileIsOpen = true; - SharedHandle = sharedHandle; - } - - void Close (); - static void Copy (const FilePath &sourcePath, const FilePath &destinationPath, bool preserveTimestamps = true); - void Delete (); - void Flush () const; - uint32 GetDeviceSectorSize () const; - static size_t GetOptimalReadSize () { return OptimalReadSize; } - static size_t GetOptimalWriteSize () { return OptimalWriteSize; } - uint64 GetPartitionDeviceStartOffset () const; - bool IsOpen () const { return FileIsOpen; } - FilePath GetPath () const; - uint64 Length () const; - void Open (const FilePath &path, FileOpenMode mode = OpenRead, FileShareMode shareMode = ShareReadWrite, FileOpenFlags flags = FlagsNone); - uint64 Read (const BufferPtr &buffer) const; - void ReadCompleteBuffer (const BufferPtr &buffer) const; - uint64 ReadAt (const BufferPtr &buffer, uint64 position) const; - void SeekAt (uint64 position) const; - void SeekEnd (int ofset) const; - void Write (const ConstBufferPtr &buffer) const; - void Write (const ConstBufferPtr &buffer, size_t length) const { Write (buffer.GetRange (0, length)); } - void WriteAt (const ConstBufferPtr &buffer, uint64 position) const; - - protected: - void ValidateState () const; - - static const size_t OptimalReadSize = 256 * 1024; - static const size_t OptimalWriteSize = 256 * 1024; - - bool FileIsOpen; - FileOpenFlags mFileOpenFlags; - bool SharedHandle; - FilePath Path; - SystemFileHandleType FileHandle; - -#ifdef TC_WINDOWS -#else - time_t AccTime; - time_t ModTime; -#endif - - private: - File (const File &); - File &operator= (const File &); - }; -} - -#endif // TC_HEADER_Platform_File +*/ + +#ifndef TC_HEADER_Platform_File +#define TC_HEADER_Platform_File + +#include "PlatformBase.h" +#include "Buffer.h" +#include "FilesystemPath.h" +#include "SystemException.h" + +namespace VeraCrypt +{ + class File + { + public: + enum FileOpenMode + { + CreateReadWrite, + CreateWrite, + OpenRead, + OpenWrite, + OpenReadWrite + }; + + enum FileShareMode + { + ShareNone, + ShareRead, + ShareReadWrite, + ShareReadWriteIgnoreLock + }; + + enum FileOpenFlags + { + // Bitmap + FlagsNone = 0, + PreserveTimestamps = 1 << 0, + DisableWriteCaching = 1 << 1 + }; + +#ifdef TC_WINDOWS + typedef FILE* SystemFileHandleType; +#else + typedef int SystemFileHandleType; +#endif + + File () : FileIsOpen (false), SharedHandle (false) { } + virtual ~File (); + + void AssignSystemHandle (SystemFileHandleType openFileHandle, bool sharedHandle = true) + { + if (FileIsOpen) + Close(); + FileHandle = openFileHandle; + FileIsOpen = true; + SharedHandle = sharedHandle; + } + + void Close (); + static void Copy (const FilePath &sourcePath, const FilePath &destinationPath, bool preserveTimestamps = true); + void Delete (); + void Flush () const; + uint32 GetDeviceSectorSize () const; + static size_t GetOptimalReadSize () { return OptimalReadSize; } + static size_t GetOptimalWriteSize () { return OptimalWriteSize; } + uint64 GetPartitionDeviceStartOffset () const; + bool IsOpen () const { return FileIsOpen; } + FilePath GetPath () const; + uint64 Length () const; + void Open (const FilePath &path, FileOpenMode mode = OpenRead, FileShareMode shareMode = ShareReadWrite, FileOpenFlags flags = FlagsNone); + uint64 Read (const BufferPtr &buffer) const; + void ReadCompleteBuffer (const BufferPtr &buffer) const; + uint64 ReadAt (const BufferPtr &buffer, uint64 position) const; + void SeekAt (uint64 position) const; + void SeekEnd (int ofset) const; + void Write (const ConstBufferPtr &buffer) const; + void Write (const ConstBufferPtr &buffer, size_t length) const { Write (buffer.GetRange (0, length)); } + void WriteAt (const ConstBufferPtr &buffer, uint64 position) const; + + protected: + void ValidateState () const; + + static const size_t OptimalReadSize = 256 * 1024; + static const size_t OptimalWriteSize = 256 * 1024; + + bool FileIsOpen; + FileOpenFlags mFileOpenFlags; + bool SharedHandle; + FilePath Path; + SystemFileHandleType FileHandle; + +#ifdef TC_WINDOWS +#else + time_t AccTime; + time_t ModTime; +#endif + + private: + File (const File &); + File &operator= (const File &); + }; +} + +#endif // TC_HEADER_Platform_File diff --git a/src/Platform/FileCommon.cpp b/src/Platform/FileCommon.cpp index e9b77540..934211bd 100644 --- a/src/Platform/FileCommon.cpp +++ b/src/Platform/FileCommon.cpp @@ -8,84 +8,84 @@ 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 "File.h" -#ifdef TC_UNIX -#include -#include -#include -#include -#endif - -namespace VeraCrypt -{ - File::~File () - { - try - { - if (FileIsOpen) - Close(); - } - catch (...) { } - } - - void File::Copy (const FilePath &sourcePath, const FilePath &destinationPath, bool preserveTimestamps) - { - File source; - source.Open (sourcePath); - - File destination; - destination.Open (destinationPath, CreateWrite); - - SecureBuffer buffer (OptimalReadSize); - uint64 len; - - while ((len = source.Read (buffer)) > 0) - { - destination.Write (buffer, static_cast (len)); - } - - if (preserveTimestamps) - { - destination.Flush(); -#ifndef TC_WINDOWS - struct stat statData; - throw_sys_sub_if (stat (string (sourcePath).c_str(), &statData) == -1, wstring (sourcePath)); - - struct utimbuf u; - u.actime = statData.st_atime; - u.modtime = statData.st_mtime; - throw_sys_sub_if (utime (string (destinationPath).c_str(), &u) == -1, wstring (destinationPath)); -#endif - } - } - - FilePath File::GetPath () const - { - if_debug (ValidateState()); - return Path; - } - - void File::ReadCompleteBuffer (const BufferPtr &buffer) const - { - size_t dataLeft = buffer.Size(); - size_t offset = 0; - - while (dataLeft > 0) - { - size_t dataRead = static_cast (Read (buffer.GetRange (offset, dataLeft))); - if (dataRead == 0) - throw InsufficientData (SRC_POS); - - dataLeft -= dataRead; - offset += dataRead; - } - } - - void File::ValidateState () const - { - if (!FileIsOpen) - throw NotInitialized (SRC_POS); - } -} +*/ + +#include "File.h" +#ifdef TC_UNIX +#include +#include +#include +#include +#endif + +namespace VeraCrypt +{ + File::~File () + { + try + { + if (FileIsOpen) + Close(); + } + catch (...) { } + } + + void File::Copy (const FilePath &sourcePath, const FilePath &destinationPath, bool preserveTimestamps) + { + File source; + source.Open (sourcePath); + + File destination; + destination.Open (destinationPath, CreateWrite); + + SecureBuffer buffer (OptimalReadSize); + uint64 len; + + while ((len = source.Read (buffer)) > 0) + { + destination.Write (buffer, static_cast (len)); + } + + if (preserveTimestamps) + { + destination.Flush(); +#ifndef TC_WINDOWS + struct stat statData; + throw_sys_sub_if (stat (string (sourcePath).c_str(), &statData) == -1, wstring (sourcePath)); + + struct utimbuf u; + u.actime = statData.st_atime; + u.modtime = statData.st_mtime; + throw_sys_sub_if (utime (string (destinationPath).c_str(), &u) == -1, wstring (destinationPath)); +#endif + } + } + + FilePath File::GetPath () const + { + if_debug (ValidateState()); + return Path; + } + + void File::ReadCompleteBuffer (const BufferPtr &buffer) const + { + size_t dataLeft = buffer.Size(); + size_t offset = 0; + + while (dataLeft > 0) + { + size_t dataRead = static_cast (Read (buffer.GetRange (offset, dataLeft))); + if (dataRead == 0) + throw InsufficientData (SRC_POS); + + dataLeft -= dataRead; + offset += dataRead; + } + } + + void File::ValidateState () const + { + if (!FileIsOpen) + throw NotInitialized (SRC_POS); + } +} diff --git a/src/Platform/FileStream.h b/src/Platform/FileStream.h index 40b0c159..55c431ff 100644 --- a/src/Platform/FileStream.h +++ b/src/Platform/FileStream.h @@ -8,55 +8,55 @@ 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_Platform_FileStream -#define TC_HEADER_Platform_FileStream - -#include "PlatformBase.h" -#include "File.h" -#include "SharedPtr.h" -#include "Stream.h" - -namespace VeraCrypt -{ - class FileStream : public Stream - { - public: - FileStream (shared_ptr file) : DataFile (file) { } - FileStream (File::SystemFileHandleType openFileHandle) { DataFile.reset (new File ()); DataFile->AssignSystemHandle (openFileHandle); } - virtual ~FileStream () { } - - virtual uint64 Read (const BufferPtr &buffer) - { - return DataFile->Read (buffer); - } - - virtual void ReadCompleteBuffer (const BufferPtr &buffer) - { - DataFile->ReadCompleteBuffer (buffer); - } - - virtual string ReadToEnd () - { - string str; - vector buffer (4096); - uint64 len; - - while ((len = DataFile->Read (BufferPtr (reinterpret_cast (&buffer[0]), buffer.size()))) > 0) - str.insert (str.end(), buffer.begin(), buffer.begin() + static_cast (len)); - - return str; - } - - virtual void Write (const ConstBufferPtr &data) - { - DataFile->Write (data); - } - - protected: - shared_ptr DataFile; - }; -} - -#endif // TC_HEADER_Platform_FileStream +*/ + +#ifndef TC_HEADER_Platform_FileStream +#define TC_HEADER_Platform_FileStream + +#include "PlatformBase.h" +#include "File.h" +#include "SharedPtr.h" +#include "Stream.h" + +namespace VeraCrypt +{ + class FileStream : public Stream + { + public: + FileStream (shared_ptr file) : DataFile (file) { } + FileStream (File::SystemFileHandleType openFileHandle) { DataFile.reset (new File ()); DataFile->AssignSystemHandle (openFileHandle); } + virtual ~FileStream () { } + + virtual uint64 Read (const BufferPtr &buffer) + { + return DataFile->Read (buffer); + } + + virtual void ReadCompleteBuffer (const BufferPtr &buffer) + { + DataFile->ReadCompleteBuffer (buffer); + } + + virtual string ReadToEnd () + { + string str; + vector buffer (4096); + uint64 len; + + while ((len = DataFile->Read (BufferPtr (reinterpret_cast (&buffer[0]), buffer.size()))) > 0) + str.insert (str.end(), buffer.begin(), buffer.begin() + static_cast (len)); + + return str; + } + + virtual void Write (const ConstBufferPtr &data) + { + DataFile->Write (data); + } + + protected: + shared_ptr DataFile; + }; +} + +#endif // TC_HEADER_Platform_FileStream diff --git a/src/Platform/FilesystemPath.h b/src/Platform/FilesystemPath.h index d3b07189..83fcc5b3 100644 --- a/src/Platform/FilesystemPath.h +++ b/src/Platform/FilesystemPath.h @@ -8,70 +8,70 @@ 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_Platform_FilesystemPath -#define TC_HEADER_Platform_FilesystemPath - -#include "PlatformBase.h" -#include "Platform/User.h" -#include "SharedPtr.h" -#include "StringConverter.h" - -namespace VeraCrypt -{ - struct FilesystemPathType - { - enum Enum - { - Unknown, - File, - Directory, - SymbolickLink, - BlockDevice, - CharacterDevice - }; - }; - - class FilesystemPath - { - public: - FilesystemPath () { } - FilesystemPath (const char *path) : Path (StringConverter::ToWide (path)) { } - FilesystemPath (string path) : Path (StringConverter::ToWide (path)) { } - FilesystemPath (const wchar_t *path) : Path (path) { } - FilesystemPath (wstring path) : Path (path) { } - virtual ~FilesystemPath () { } - - bool operator== (const FilesystemPath &other) const { return Path == other.Path; } - bool operator!= (const FilesystemPath &other) const { return Path != other.Path; } - operator string () const { return StringConverter::ToSingle (Path); } - operator wstring () const { return Path; } - - void Delete () const; - UserId GetOwner () const; - FilesystemPathType::Enum GetType () const; - bool IsBlockDevice () const throw () { try { return GetType() == FilesystemPathType::BlockDevice; } catch (...) { return false; }; } - bool IsCharacterDevice () const throw () { try { return GetType() == FilesystemPathType::CharacterDevice; } catch (...) { return false; }; } - bool IsDevice () const throw () { return IsBlockDevice() || IsCharacterDevice(); } - bool IsDirectory () const throw () { try { return GetType() == FilesystemPathType::Directory; } catch (...) { return false; } } - bool IsEmpty () const throw () { try { return Path.empty(); } catch (...) { return false; } } - bool IsFile () const throw () { try { return GetType() == FilesystemPathType::File; } catch (...) { return false; } } - FilesystemPath ToBaseName () const; - FilesystemPath ToHostDriveOfPartition () const; - - static const int MaxSize = 260; - - protected: - wstring Path; - }; - - typedef FilesystemPath DevicePath; - typedef FilesystemPath DirectoryPath; - typedef FilesystemPath FilePath; - - typedef list < shared_ptr > DirectoryPathList; - typedef list < shared_ptr > FilePathList; -} - -#endif // TC_HEADER_Platform_FilesystemPath +*/ + +#ifndef TC_HEADER_Platform_FilesystemPath +#define TC_HEADER_Platform_FilesystemPath + +#include "PlatformBase.h" +#include "Platform/User.h" +#include "SharedPtr.h" +#include "StringConverter.h" + +namespace VeraCrypt +{ + struct FilesystemPathType + { + enum Enum + { + Unknown, + File, + Directory, + SymbolickLink, + BlockDevice, + CharacterDevice + }; + }; + + class FilesystemPath + { + public: + FilesystemPath () { } + FilesystemPath (const char *path) : Path (StringConverter::ToWide (path)) { } + FilesystemPath (string path) : Path (StringConverter::ToWide (path)) { } + FilesystemPath (const wchar_t *path) : Path (path) { } + FilesystemPath (wstring path) : Path (path) { } + virtual ~FilesystemPath () { } + + bool operator== (const FilesystemPath &other) const { return Path == other.Path; } + bool operator!= (const FilesystemPath &other) const { return Path != other.Path; } + operator string () const { return StringConverter::ToSingle (Path); } + operator wstring () const { return Path; } + + void Delete () const; + UserId GetOwner () const; + FilesystemPathType::Enum GetType () const; + bool IsBlockDevice () const throw () { try { return GetType() == FilesystemPathType::BlockDevice; } catch (...) { return false; }; } + bool IsCharacterDevice () const throw () { try { return GetType() == FilesystemPathType::CharacterDevice; } catch (...) { return false; }; } + bool IsDevice () const throw () { return IsBlockDevice() || IsCharacterDevice(); } + bool IsDirectory () const throw () { try { return GetType() == FilesystemPathType::Directory; } catch (...) { return false; } } + bool IsEmpty () const throw () { try { return Path.empty(); } catch (...) { return false; } } + bool IsFile () const throw () { try { return GetType() == FilesystemPathType::File; } catch (...) { return false; } } + FilesystemPath ToBaseName () const; + FilesystemPath ToHostDriveOfPartition () const; + + static const int MaxSize = 260; + + protected: + wstring Path; + }; + + typedef FilesystemPath DevicePath; + typedef FilesystemPath DirectoryPath; + typedef FilesystemPath FilePath; + + typedef list < shared_ptr > DirectoryPathList; + typedef list < shared_ptr > FilePathList; +} + +#endif // TC_HEADER_Platform_FilesystemPath diff --git a/src/Platform/Finally.h b/src/Platform/Finally.h index c411fc4b..5fa2e904 100644 --- a/src/Platform/Finally.h +++ b/src/Platform/Finally.h @@ -8,43 +8,43 @@ 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_Platform_Finally -#define TC_HEADER_Platform_Finally - -#include "PlatformBase.h" - -// Execute code when leaving scope -#define finally_do(code) \ -struct TC_JOIN(Finally,__LINE__) \ -{ \ - TC_JOIN(~Finally,__LINE__) () { try { code } catch (...) { } } \ -} \ -TC_UNUSED_VAR \ -TC_JOIN(finally,__LINE__) - -// Execute code with argument 'finally_arg' when leaving scope -#define finally_do_arg(argType, arg, code) \ -struct TC_JOIN(Finally,__LINE__) \ -{ \ - TC_JOIN(Finally,__LINE__) (argType a) : finally_arg (a) { } \ - TC_JOIN(~Finally,__LINE__) () { try { code } catch (...) { } } \ - argType finally_arg; \ -} \ -TC_UNUSED_VAR \ -TC_JOIN(finally,__LINE__) (arg) - -#define finally_do_arg2(argType, arg, argType2, arg2, code) \ -struct TC_JOIN(Finally,__LINE__) \ -{ \ - TC_JOIN(Finally,__LINE__) (argType a, argType2 a2) : finally_arg (a), finally_arg2 (a2) { } \ - TC_JOIN(~Finally,__LINE__) () { try { code } catch (...) { } } \ - argType finally_arg; \ - argType2 finally_arg2; \ -} \ -TC_UNUSED_VAR \ -TC_JOIN(finally,__LINE__) (arg, arg2) - - -#endif // TC_HEADER_Platform_Finally +*/ + +#ifndef TC_HEADER_Platform_Finally +#define TC_HEADER_Platform_Finally + +#include "PlatformBase.h" + +// Execute code when leaving scope +#define finally_do(code) \ +struct TC_JOIN(Finally,__LINE__) \ +{ \ + TC_JOIN(~Finally,__LINE__) () { try { code } catch (...) { } } \ +} \ +TC_UNUSED_VAR \ +TC_JOIN(finally,__LINE__) + +// Execute code with argument 'finally_arg' when leaving scope +#define finally_do_arg(argType, arg, code) \ +struct TC_JOIN(Finally,__LINE__) \ +{ \ + TC_JOIN(Finally,__LINE__) (argType a) : finally_arg (a) { } \ + TC_JOIN(~Finally,__LINE__) () { try { code } catch (...) { } } \ + argType finally_arg; \ +} \ +TC_UNUSED_VAR \ +TC_JOIN(finally,__LINE__) (arg) + +#define finally_do_arg2(argType, arg, argType2, arg2, code) \ +struct TC_JOIN(Finally,__LINE__) \ +{ \ + TC_JOIN(Finally,__LINE__) (argType a, argType2 a2) : finally_arg (a), finally_arg2 (a2) { } \ + TC_JOIN(~Finally,__LINE__) () { try { code } catch (...) { } } \ + argType finally_arg; \ + argType2 finally_arg2; \ +} \ +TC_UNUSED_VAR \ +TC_JOIN(finally,__LINE__) (arg, arg2) + + +#endif // TC_HEADER_Platform_Finally diff --git a/src/Platform/ForEach.h b/src/Platform/ForEach.h index 3ffe67fb..e0fb121f 100644 --- a/src/Platform/ForEach.h +++ b/src/Platform/ForEach.h @@ -8,115 +8,115 @@ 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_Platform_ForEach -#define TC_HEADER_Platform_ForEach - -namespace VeraCrypt -{ - class ForEach - { - public: - struct Container - { - Container () : InnerContinue (true), InnerEndCondition (false) { } - virtual ~Container () { } - - void Continue () const { InnerContinue = true; } - bool InnerIsNotEnd () const { return InnerEndCondition = !InnerEndCondition; } - virtual bool IsNotEnd () const = 0; - virtual void Next () const = 0; - - mutable bool InnerContinue; - mutable bool InnerEndCondition; - }; - - protected: - template - struct ContainerForward : Container - { - ContainerForward (const T &container) - : ContainerCopy (container), EndIterator (ContainerCopy.end()), Iterator (ContainerCopy.begin()) { } - - virtual bool IsNotEnd () const { bool r = InnerContinue && Iterator != EndIterator; InnerContinue = false; return r; } - virtual void Next () const { ++Iterator; } - - const T ContainerCopy; // Support for temporary objects - typename T::const_iterator EndIterator; - mutable typename T::const_iterator Iterator; - - private: - ContainerForward &operator= (const ContainerForward &); - }; - - template - struct ContainerReverse : Container - { - ContainerReverse (const T &container) - : ContainerCopy (container), EndIterator (ContainerCopy.rend()), Iterator (ContainerCopy.rbegin()) { } - - virtual bool IsNotEnd () const { bool r = InnerContinue && Iterator != EndIterator; InnerContinue = false; return r; } - virtual void Next () const { ++Iterator; } - - const T ContainerCopy; - typename T::const_reverse_iterator EndIterator; - mutable typename T::const_reverse_iterator Iterator; - - private: - ContainerReverse &operator= (const ContainerReverse &); - }; - - public: - template - static ContainerForward GetContainerForward (const T &container) - { - return ContainerForward (container); - } - - template - static ContainerReverse GetContainerReverse (const T &container) - { - return ContainerReverse (container); - } - - protected: - template - struct TypeWrapper { }; - - public: - template - static TypeWrapper ToTypeWrapper (const T &x) { return TypeWrapper (); } - - struct TypeWrapperDummy - { - template - operator TypeWrapper () const { return TypeWrapper (); } - }; - - template - static const ContainerForward &GetContainerForward (const Container &forEachContainer, const TypeWrapper &) - { - return static_cast &> (forEachContainer); - } - - template - static const ContainerReverse &GetContainerReverse (const Container &forEachContainer, const TypeWrapper &) - { - return static_cast &> (forEachContainer); - } - }; -} - - -#define FOREACH_TEMPLATE(dereference,listType,variable,listInstance) \ - for (const ForEach::Container &forEachContainer = ForEach::GetContainer##listType (listInstance); forEachContainer.IsNotEnd(); forEachContainer.Next()) \ - for (variable = dereference(ForEach::GetContainer##listType (forEachContainer, (true ? ForEach::TypeWrapperDummy() : ForEach::ToTypeWrapper (listInstance))).Iterator); forEachContainer.InnerIsNotEnd(); forEachContainer.Continue()) - -#define foreach(variable,listInstance) FOREACH_TEMPLATE(*, Forward, variable, listInstance) -#define foreach_ref(variable,listInstance) FOREACH_TEMPLATE(**, Forward, variable, listInstance) -#define foreach_reverse(variable,listInstance) FOREACH_TEMPLATE(*, Reverse, variable, listInstance) -#define foreach_reverse_ref(variable,listInstance) FOREACH_TEMPLATE(**, Reverse, variable, listInstance) - - -#endif // TC_HEADER_Platform_ForEach +*/ + +#ifndef TC_HEADER_Platform_ForEach +#define TC_HEADER_Platform_ForEach + +namespace VeraCrypt +{ + class ForEach + { + public: + struct Container + { + Container () : InnerContinue (true), InnerEndCondition (false) { } + virtual ~Container () { } + + void Continue () const { InnerContinue = true; } + bool InnerIsNotEnd () const { return InnerEndCondition = !InnerEndCondition; } + virtual bool IsNotEnd () const = 0; + virtual void Next () const = 0; + + mutable bool InnerContinue; + mutable bool InnerEndCondition; + }; + + protected: + template + struct ContainerForward : Container + { + ContainerForward (const T &container) + : ContainerCopy (container), EndIterator (ContainerCopy.end()), Iterator (ContainerCopy.begin()) { } + + virtual bool IsNotEnd () const { bool r = InnerContinue && Iterator != EndIterator; InnerContinue = false; return r; } + virtual void Next () const { ++Iterator; } + + const T ContainerCopy; // Support for temporary objects + typename T::const_iterator EndIterator; + mutable typename T::const_iterator Iterator; + + private: + ContainerForward &operator= (const ContainerForward &); + }; + + template + struct ContainerReverse : Container + { + ContainerReverse (const T &container) + : ContainerCopy (container), EndIterator (ContainerCopy.rend()), Iterator (ContainerCopy.rbegin()) { } + + virtual bool IsNotEnd () const { bool r = InnerContinue && Iterator != EndIterator; InnerContinue = false; return r; } + virtual void Next () const { ++Iterator; } + + const T ContainerCopy; + typename T::const_reverse_iterator EndIterator; + mutable typename T::const_reverse_iterator Iterator; + + private: + ContainerReverse &operator= (const ContainerReverse &); + }; + + public: + template + static ContainerForward GetContainerForward (const T &container) + { + return ContainerForward (container); + } + + template + static ContainerReverse GetContainerReverse (const T &container) + { + return ContainerReverse (container); + } + + protected: + template + struct TypeWrapper { }; + + public: + template + static TypeWrapper ToTypeWrapper (const T &x) { return TypeWrapper (); } + + struct TypeWrapperDummy + { + template + operator TypeWrapper () const { return TypeWrapper (); } + }; + + template + static const ContainerForward &GetContainerForward (const Container &forEachContainer, const TypeWrapper &) + { + return static_cast &> (forEachContainer); + } + + template + static const ContainerReverse &GetContainerReverse (const Container &forEachContainer, const TypeWrapper &) + { + return static_cast &> (forEachContainer); + } + }; +} + + +#define FOREACH_TEMPLATE(dereference,listType,variable,listInstance) \ + for (const ForEach::Container &forEachContainer = ForEach::GetContainer##listType (listInstance); forEachContainer.IsNotEnd(); forEachContainer.Next()) \ + for (variable = dereference(ForEach::GetContainer##listType (forEachContainer, (true ? ForEach::TypeWrapperDummy() : ForEach::ToTypeWrapper (listInstance))).Iterator); forEachContainer.InnerIsNotEnd(); forEachContainer.Continue()) + +#define foreach(variable,listInstance) FOREACH_TEMPLATE(*, Forward, variable, listInstance) +#define foreach_ref(variable,listInstance) FOREACH_TEMPLATE(**, Forward, variable, listInstance) +#define foreach_reverse(variable,listInstance) FOREACH_TEMPLATE(*, Reverse, variable, listInstance) +#define foreach_reverse_ref(variable,listInstance) FOREACH_TEMPLATE(**, Reverse, variable, listInstance) + + +#endif // TC_HEADER_Platform_ForEach diff --git a/src/Platform/Functor.h b/src/Platform/Functor.h index 234b4f2f..9bc96949 100644 --- a/src/Platform/Functor.h +++ b/src/Platform/Functor.h @@ -8,26 +8,26 @@ 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_Platform_Functor -#define TC_HEADER_Platform_Functor - -#include "PlatformBase.h" - -namespace VeraCrypt -{ - struct Functor - { - virtual ~Functor () { } - virtual void operator() () = 0; - }; - - struct GetStringFunctor - { - virtual ~GetStringFunctor () { } - virtual void operator() (string &str) = 0; - }; -} - -#endif // TC_HEADER_Platform_Functor +*/ + +#ifndef TC_HEADER_Platform_Functor +#define TC_HEADER_Platform_Functor + +#include "PlatformBase.h" + +namespace VeraCrypt +{ + struct Functor + { + virtual ~Functor () { } + virtual void operator() () = 0; + }; + + struct GetStringFunctor + { + virtual ~GetStringFunctor () { } + virtual void operator() (string &str) = 0; + }; +} + +#endif // TC_HEADER_Platform_Functor diff --git a/src/Platform/Memory.cpp b/src/Platform/Memory.cpp index 7a543a8c..f84a8741 100644 --- a/src/Platform/Memory.cpp +++ b/src/Platform/Memory.cpp @@ -8,55 +8,55 @@ 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 "Common/Tcdefs.h" -#include "Memory.h" -#include "Exception.h" - -namespace VeraCrypt -{ - void *Memory::Allocate (std::size_t size) - { - if (size < 1) - throw ParameterIncorrect (SRC_POS); - - void *bufPtr = malloc (size); - if (!bufPtr) - throw bad_alloc(); - - return bufPtr; - } - - int Memory::Compare (const void *memory1, size_t size1, const void *memory2, size_t size2) - { - if (size1 > size2) - return 1; - else if (size1 < size2) - return -1; - - return memcmp (memory1, memory2, size1); - } - - void Memory::Copy (void *memoryDestination, const void *memorySource, size_t size) - { - assert (memoryDestination != nullptr && memorySource != nullptr); - memcpy (memoryDestination, memorySource, size); - } - - void Memory::Erase (void *memory, size_t size) - { - burn (memory, size); - } - - void Memory::Zero (void *memory, size_t size) - { - memset (memory, 0, size); - } - - void Memory::Free (void *memory) - { - assert (memory != nullptr); - free (memory); - } -} +*/ + +#include "Common/Tcdefs.h" +#include "Memory.h" +#include "Exception.h" + +namespace VeraCrypt +{ + void *Memory::Allocate (std::size_t size) + { + if (size < 1) + throw ParameterIncorrect (SRC_POS); + + void *bufPtr = malloc (size); + if (!bufPtr) + throw bad_alloc(); + + return bufPtr; + } + + int Memory::Compare (const void *memory1, size_t size1, const void *memory2, size_t size2) + { + if (size1 > size2) + return 1; + else if (size1 < size2) + return -1; + + return memcmp (memory1, memory2, size1); + } + + void Memory::Copy (void *memoryDestination, const void *memorySource, size_t size) + { + assert (memoryDestination != nullptr && memorySource != nullptr); + memcpy (memoryDestination, memorySource, size); + } + + void Memory::Erase (void *memory, size_t size) + { + burn (memory, size); + } + + void Memory::Zero (void *memory, size_t size) + { + memset (memory, 0, size); + } + + void Memory::Free (void *memory) + { + assert (memory != nullptr); + free (memory); + } +} diff --git a/src/Platform/Memory.h b/src/Platform/Memory.h index ddf1205c..dca1e5e2 100644 --- a/src/Platform/Memory.h +++ b/src/Platform/Memory.h @@ -8,171 +8,171 @@ 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_Platform_Memory -#define TC_HEADER_Platform_Memory - -#include -#include -#include "PlatformBase.h" - -#ifdef TC_WINDOWS - -# ifndef LITTLE_ENDIAN -# define LITTLE_ENDIAN 1234 -# endif -# ifndef BYTE_ORDER -# define BYTE_ORDER LITTLE_ENDIAN -# endif - -#elif !defined(BYTE_ORDER) - -# ifdef TC_MACOSX -# include -# elif defined (TC_BSD) -# include -# elif defined (TC_SOLARIS) -# include -# define LITTLE_ENDIAN 1234 -# define BIG_ENDIAN 4321 -# ifdef _BIG_ENDIAN -# define BYTE_ORDER BIG_ENDIAN -# else -# define BYTE_ORDER LITTLE_ENDIAN -# endif -# else -# include -# endif - -# ifndef BYTE_ORDER -# ifndef __BYTE_ORDER -# error Byte ordering cannot be determined (BYTE_ORDER undefined). -# endif - -# define BYTE_ORDER __BYTE_ORDER -# endif - -# ifndef LITTLE_ENDIAN -# define LITTLE_ENDIAN __LITTLE_ENDIAN -# endif - -# ifndef BIG_ENDIAN -# define BIG_ENDIAN __BIG_ENDIAN -# endif - -#endif // !BYTE_ORDER - -#if BYTE_ORDER != BIG_ENDIAN && BYTE_ORDER != LITTLE_ENDIAN -# error Unsupported byte ordering detected. -#endif - -namespace VeraCrypt -{ - class Memory - { - public: - static void *Allocate (size_t size); - static int Compare (const void *memory1, size_t size1, const void *memory2, size_t size2); - static void Copy (void *memoryDestination, const void *memorySource, size_t size); - static void Erase (void *memory, size_t size); - static void Free (void *memory); - static void Zero (void *memory, size_t size); - }; - - class Endian - { - public: - static byte Big (const byte &x) - { - return x; - } - - static uint16 Big (const uint16 &x) - { -#if BYTE_ORDER == BIG_ENDIAN - return x; -#else - return MirrorBytes (x); -#endif - } - - static uint32 Big (const uint32 &x) - { -#if BYTE_ORDER == BIG_ENDIAN - return x; -#else - return MirrorBytes (x); -#endif - } - - static uint64 Big (const uint64 &x) - { -#if BYTE_ORDER == BIG_ENDIAN - return x; -#else - return MirrorBytes (x); -#endif - } - - static byte Little (const byte &x) - { - return x; - } - - static uint16 Little (const uint16 &x) - { -#if BYTE_ORDER == LITTLE_ENDIAN - return x; -#else - return MirrorBytes (x); -#endif - } - - static uint32 Little (const uint32 &x) - { -#if BYTE_ORDER == LITTLE_ENDIAN - return x; -#else - return MirrorBytes (x); -#endif - } - - static uint64 Little (const uint64 &x) - { -#if BYTE_ORDER == LITTLE_ENDIAN - return x; -#else - return MirrorBytes (x); -#endif - } - - protected: - static uint16 MirrorBytes (const uint16 &x) - { - return (x << 8) | (x >> 8); - } - - static uint32 MirrorBytes (const uint32 &x) - { - uint32 n = (byte) x; - n <<= 8; n |= (byte) (x >> 8); - n <<= 8; n |= (byte) (x >> 16); - return (n << 8) | (byte) (x >> 24); - } - - static uint64 MirrorBytes (const uint64 &x) - { - uint64 n = (byte) x; - n <<= 8; n |= (byte) (x >> 8); - n <<= 8; n |= (byte) (x >> 16); - n <<= 8; n |= (byte) (x >> 24); - n <<= 8; n |= (byte) (x >> 32); - n <<= 8; n |= (byte) (x >> 40); - n <<= 8; n |= (byte) (x >> 48); - return (n << 8) | (byte) (x >> 56); - } - }; -} - -#endif // TC_HEADER_Platform_Memory +*/ + +#ifndef TC_HEADER_Platform_Memory +#define TC_HEADER_Platform_Memory + +#include +#include +#include "PlatformBase.h" + +#ifdef TC_WINDOWS + +# ifndef LITTLE_ENDIAN +# define LITTLE_ENDIAN 1234 +# endif +# ifndef BYTE_ORDER +# define BYTE_ORDER LITTLE_ENDIAN +# endif + +#elif !defined(BYTE_ORDER) + +# ifdef TC_MACOSX +# include +# elif defined (TC_BSD) +# include +# elif defined (TC_SOLARIS) +# include +# define LITTLE_ENDIAN 1234 +# define BIG_ENDIAN 4321 +# ifdef _BIG_ENDIAN +# define BYTE_ORDER BIG_ENDIAN +# else +# define BYTE_ORDER LITTLE_ENDIAN +# endif +# else +# include +# endif + +# ifndef BYTE_ORDER +# ifndef __BYTE_ORDER +# error Byte ordering cannot be determined (BYTE_ORDER undefined). +# endif + +# define BYTE_ORDER __BYTE_ORDER +# endif + +# ifndef LITTLE_ENDIAN +# define LITTLE_ENDIAN __LITTLE_ENDIAN +# endif + +# ifndef BIG_ENDIAN +# define BIG_ENDIAN __BIG_ENDIAN +# endif + +#endif // !BYTE_ORDER + +#if BYTE_ORDER != BIG_ENDIAN && BYTE_ORDER != LITTLE_ENDIAN +# error Unsupported byte ordering detected. +#endif + +namespace VeraCrypt +{ + class Memory + { + public: + static void *Allocate (size_t size); + static int Compare (const void *memory1, size_t size1, const void *memory2, size_t size2); + static void Copy (void *memoryDestination, const void *memorySource, size_t size); + static void Erase (void *memory, size_t size); + static void Free (void *memory); + static void Zero (void *memory, size_t size); + }; + + class Endian + { + public: + static byte Big (const byte &x) + { + return x; + } + + static uint16 Big (const uint16 &x) + { +#if BYTE_ORDER == BIG_ENDIAN + return x; +#else + return MirrorBytes (x); +#endif + } + + static uint32 Big (const uint32 &x) + { +#if BYTE_ORDER == BIG_ENDIAN + return x; +#else + return MirrorBytes (x); +#endif + } + + static uint64 Big (const uint64 &x) + { +#if BYTE_ORDER == BIG_ENDIAN + return x; +#else + return MirrorBytes (x); +#endif + } + + static byte Little (const byte &x) + { + return x; + } + + static uint16 Little (const uint16 &x) + { +#if BYTE_ORDER == LITTLE_ENDIAN + return x; +#else + return MirrorBytes (x); +#endif + } + + static uint32 Little (const uint32 &x) + { +#if BYTE_ORDER == LITTLE_ENDIAN + return x; +#else + return MirrorBytes (x); +#endif + } + + static uint64 Little (const uint64 &x) + { +#if BYTE_ORDER == LITTLE_ENDIAN + return x; +#else + return MirrorBytes (x); +#endif + } + + protected: + static uint16 MirrorBytes (const uint16 &x) + { + return (x << 8) | (x >> 8); + } + + static uint32 MirrorBytes (const uint32 &x) + { + uint32 n = (byte) x; + n <<= 8; n |= (byte) (x >> 8); + n <<= 8; n |= (byte) (x >> 16); + return (n << 8) | (byte) (x >> 24); + } + + static uint64 MirrorBytes (const uint64 &x) + { + uint64 n = (byte) x; + n <<= 8; n |= (byte) (x >> 8); + n <<= 8; n |= (byte) (x >> 16); + n <<= 8; n |= (byte) (x >> 24); + n <<= 8; n |= (byte) (x >> 32); + n <<= 8; n |= (byte) (x >> 40); + n <<= 8; n |= (byte) (x >> 48); + return (n << 8) | (byte) (x >> 56); + } + }; +} + +#endif // TC_HEADER_Platform_Memory diff --git a/src/Platform/MemoryStream.cpp b/src/Platform/MemoryStream.cpp index 24e311e6..b4b17cdc 100644 --- a/src/Platform/MemoryStream.cpp +++ b/src/Platform/MemoryStream.cpp @@ -8,44 +8,44 @@ 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 "Exception.h" -#include "MemoryStream.h" - -namespace VeraCrypt -{ - MemoryStream::MemoryStream (const ConstBufferPtr &data) : - ReadPosition (0) - { - Data = vector (data.Size()); - BufferPtr (&Data[0], Data.size()).CopyFrom (data); - } - - uint64 MemoryStream::Read (const BufferPtr &buffer) - { - if (Data.size() == 0) - throw ParameterIncorrect (SRC_POS); - - ConstBufferPtr streamBuf (*this); - size_t len = buffer.Size(); - if (streamBuf.Size() - ReadPosition < len) - len = streamBuf.Size() - ReadPosition; - - BufferPtr(buffer).CopyFrom (streamBuf.GetRange (ReadPosition, len)); - ReadPosition += len; - return len; - } - - void MemoryStream::ReadCompleteBuffer (const BufferPtr &buffer) - { - if (Read (buffer) != buffer.Size()) - throw InsufficientData (SRC_POS); - } - - void MemoryStream::Write (const ConstBufferPtr &data) - { - for (uint64 i = 0; i < data.Size(); i++) - Data.push_back (data[i]); - } -} +*/ + +#include "Exception.h" +#include "MemoryStream.h" + +namespace VeraCrypt +{ + MemoryStream::MemoryStream (const ConstBufferPtr &data) : + ReadPosition (0) + { + Data = vector (data.Size()); + BufferPtr (&Data[0], Data.size()).CopyFrom (data); + } + + uint64 MemoryStream::Read (const BufferPtr &buffer) + { + if (Data.size() == 0) + throw ParameterIncorrect (SRC_POS); + + ConstBufferPtr streamBuf (*this); + size_t len = buffer.Size(); + if (streamBuf.Size() - ReadPosition < len) + len = streamBuf.Size() - ReadPosition; + + BufferPtr(buffer).CopyFrom (streamBuf.GetRange (ReadPosition, len)); + ReadPosition += len; + return len; + } + + void MemoryStream::ReadCompleteBuffer (const BufferPtr &buffer) + { + if (Read (buffer) != buffer.Size()) + throw InsufficientData (SRC_POS); + } + + void MemoryStream::Write (const ConstBufferPtr &data) + { + for (uint64 i = 0; i < data.Size(); i++) + Data.push_back (data[i]); + } +} diff --git a/src/Platform/MemoryStream.h b/src/Platform/MemoryStream.h index 5591286a..b3d19c7a 100644 --- a/src/Platform/MemoryStream.h +++ b/src/Platform/MemoryStream.h @@ -8,33 +8,33 @@ 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_Platform_MemoryStream -#define TC_HEADER_Platform_MemoryStream - -#include "PlatformBase.h" -#include "Stream.h" - -namespace VeraCrypt -{ - class MemoryStream : public Stream - { - public: - MemoryStream () : ReadPosition (0) { } - MemoryStream (const ConstBufferPtr &data); - virtual ~MemoryStream () { } - - operator ConstBufferPtr () const { return ConstBufferPtr (&Data[0], Data.size()); } - - virtual uint64 Read (const BufferPtr &buffer); - virtual void ReadCompleteBuffer (const BufferPtr &buffer); - virtual void Write (const ConstBufferPtr &data); - - protected: - vector Data; - size_t ReadPosition; - }; -} - -#endif // TC_HEADER_Platform_MemoryStream +*/ + +#ifndef TC_HEADER_Platform_MemoryStream +#define TC_HEADER_Platform_MemoryStream + +#include "PlatformBase.h" +#include "Stream.h" + +namespace VeraCrypt +{ + class MemoryStream : public Stream + { + public: + MemoryStream () : ReadPosition (0) { } + MemoryStream (const ConstBufferPtr &data); + virtual ~MemoryStream () { } + + operator ConstBufferPtr () const { return ConstBufferPtr (&Data[0], Data.size()); } + + virtual uint64 Read (const BufferPtr &buffer); + virtual void ReadCompleteBuffer (const BufferPtr &buffer); + virtual void Write (const ConstBufferPtr &data); + + protected: + vector Data; + size_t ReadPosition; + }; +} + +#endif // TC_HEADER_Platform_MemoryStream diff --git a/src/Platform/Mutex.h b/src/Platform/Mutex.h index f97173b4..c8786952 100644 --- a/src/Platform/Mutex.h +++ b/src/Platform/Mutex.h @@ -8,58 +8,58 @@ 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_Platform_Mutex -#define TC_HEADER_Platform_Mutex - -#ifdef TC_WINDOWS -# include "System.h" -#else -# include -#endif -#include "PlatformBase.h" - -namespace VeraCrypt -{ - class Mutex - { -#ifdef TC_WINDOWS - typedef CRITICAL_SECTION SystemMutex_t; -#else - typedef pthread_mutex_t SystemMutex_t; -#endif - - public: - Mutex (); - ~Mutex (); - - SystemMutex_t *GetSystemHandle () { return &SystemMutex; } - void Lock (); - void Unlock (); - - protected: - bool Initialized; - SystemMutex_t SystemMutex; - - private: - Mutex (const Mutex &); - Mutex &operator= (const Mutex &); - }; - - class ScopeLock - { - public: - ScopeLock (Mutex &mutex) : ScopeMutex (mutex) { mutex.Lock(); } - ~ScopeLock () { ScopeMutex.Unlock(); } - - protected: - Mutex &ScopeMutex; - - private: - ScopeLock (const ScopeLock &); - ScopeLock &operator= (const ScopeLock &); - }; -} - -#endif // TC_HEADER_Platform_Mutex +*/ + +#ifndef TC_HEADER_Platform_Mutex +#define TC_HEADER_Platform_Mutex + +#ifdef TC_WINDOWS +# include "System.h" +#else +# include +#endif +#include "PlatformBase.h" + +namespace VeraCrypt +{ + class Mutex + { +#ifdef TC_WINDOWS + typedef CRITICAL_SECTION SystemMutex_t; +#else + typedef pthread_mutex_t SystemMutex_t; +#endif + + public: + Mutex (); + ~Mutex (); + + SystemMutex_t *GetSystemHandle () { return &SystemMutex; } + void Lock (); + void Unlock (); + + protected: + bool Initialized; + SystemMutex_t SystemMutex; + + private: + Mutex (const Mutex &); + Mutex &operator= (const Mutex &); + }; + + class ScopeLock + { + public: + ScopeLock (Mutex &mutex) : ScopeMutex (mutex) { mutex.Lock(); } + ~ScopeLock () { ScopeMutex.Unlock(); } + + protected: + Mutex &ScopeMutex; + + private: + ScopeLock (const ScopeLock &); + ScopeLock &operator= (const ScopeLock &); + }; +} + +#endif // TC_HEADER_Platform_Mutex diff --git a/src/Platform/Platform.h b/src/Platform/Platform.h index 3de41399..9e8a4cca 100644 --- a/src/Platform/Platform.h +++ b/src/Platform/Platform.h @@ -8,25 +8,25 @@ 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_Platform -#define TC_HEADER_Platform - -#include "PlatformBase.h" -#include "Buffer.h" -#include "Exception.h" -#include "Directory.h" -#include "Event.h" -#include "File.h" -#include "FilesystemPath.h" -#include "Finally.h" -#include "ForEach.h" -#include "Functor.h" -#include "Memory.h" -#include "Mutex.h" -#include "SharedPtr.h" -#include "SystemException.h" -#include "Thread.h" - -#endif // TC_HEADER_Platform +*/ + +#ifndef TC_HEADER_Platform +#define TC_HEADER_Platform + +#include "PlatformBase.h" +#include "Buffer.h" +#include "Exception.h" +#include "Directory.h" +#include "Event.h" +#include "File.h" +#include "FilesystemPath.h" +#include "Finally.h" +#include "ForEach.h" +#include "Functor.h" +#include "Memory.h" +#include "Mutex.h" +#include "SharedPtr.h" +#include "SystemException.h" +#include "Thread.h" + +#endif // TC_HEADER_Platform diff --git a/src/Platform/Platform.make b/src/Platform/Platform.make index 9d02d8aa..4d142317 100644 --- a/src/Platform/Platform.make +++ b/src/Platform/Platform.make @@ -1,39 +1,39 @@ -# -# 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. -# - -OBJS := Buffer.o -OBJS += Exception.o -OBJS += Event.o -OBJS += FileCommon.o -OBJS += MemoryStream.o -OBJS += Memory.o -OBJS += PlatformTest.o -OBJS += Serializable.o -OBJS += Serializer.o -OBJS += SerializerFactory.o -OBJS += StringConverter.o -OBJS += TextReader.o -OBJS += Unix/Directory.o -OBJS += Unix/File.o -OBJS += Unix/FilesystemPath.o -OBJS += Unix/Mutex.o -OBJS += Unix/Pipe.o -OBJS += Unix/Poller.o -OBJS += Unix/Process.o -OBJS += Unix/SyncEvent.o -OBJS += Unix/SystemException.o -OBJS += Unix/SystemInfo.o -OBJS += Unix/SystemLog.o -OBJS += Unix/Thread.o -OBJS += Unix/Time.o - -include $(BUILD_INC)/Makefile.inc +# +# 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. +# + +OBJS := Buffer.o +OBJS += Exception.o +OBJS += Event.o +OBJS += FileCommon.o +OBJS += MemoryStream.o +OBJS += Memory.o +OBJS += PlatformTest.o +OBJS += Serializable.o +OBJS += Serializer.o +OBJS += SerializerFactory.o +OBJS += StringConverter.o +OBJS += TextReader.o +OBJS += Unix/Directory.o +OBJS += Unix/File.o +OBJS += Unix/FilesystemPath.o +OBJS += Unix/Mutex.o +OBJS += Unix/Pipe.o +OBJS += Unix/Poller.o +OBJS += Unix/Process.o +OBJS += Unix/SyncEvent.o +OBJS += Unix/SystemException.o +OBJS += Unix/SystemInfo.o +OBJS += Unix/SystemLog.o +OBJS += Unix/Thread.o +OBJS += Unix/Time.o + +include $(BUILD_INC)/Makefile.inc diff --git a/src/Platform/PlatformBase.h b/src/Platform/PlatformBase.h index 1a6b5945..652069c4 100644 --- a/src/Platform/PlatformBase.h +++ b/src/Platform/PlatformBase.h @@ -8,131 +8,131 @@ 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_Platform_PlatformBase -#define TC_HEADER_Platform_PlatformBase - -#include -#include -#include -#include -#include -#include -#include - -#ifndef _MSC_VER -#include -#endif - -using namespace std; - -#ifdef nullptr -#undef nullptr -#endif - -#if !(defined(_MSC_VER) && _MSC_VER >= 1600) -#define nullptr 0 -#endif - -namespace VeraCrypt -{ -#ifdef _MSC_VER -# ifndef TC_INT_TYPES_DEFINED - typedef __int8 int8; - typedef __int16 int16; - typedef __int32 int32; - typedef __int64 int64; - typedef unsigned __int8 byte; - typedef unsigned __int16 uint16; - typedef unsigned __int32 uint32; - typedef unsigned __int64 uint64; -# endif -#else - typedef int8_t int8; - typedef int16_t int16; - typedef int32_t int32; - typedef int64_t int64; - typedef uint8_t byte; - typedef uint16_t uint16; - typedef uint32_t uint32; - typedef uint64_t uint64; -#endif -} - -#if (defined(_WIN32) || defined(_WIN64)) && !defined(TC_WINDOWS) -# define TC_WINDOWS -#endif - -#if defined(_DEBUG) && !defined(DEBUG) -# define DEBUG -#endif - -#ifndef TC_TO_STRING -# define TC_TO_STRING2(n) #n -# define TC_TO_STRING(n) TC_TO_STRING2(n) -#endif - -#define TC_JOIN_ARGS(a,b) a##b -#define TC_JOIN(a,b) TC_JOIN_ARGS(a,b) - -#ifdef __GNUC__ - template string GetFunctionName (T pos) - { - string s (pos); - size_t p = s.find ('('); - if (p == string::npos) - return s; - s = s.substr (0, p); - p = s.find_last_of (" "); - if (p == string::npos) - return s; - return s.substr (p + 1); - } -# define SRC_POS (GetFunctionName (__PRETTY_FUNCTION__) += ":" TC_TO_STRING(__LINE__)) -# define TC_UNUSED_VAR __attribute__ ((unused)) -#else -# define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) -# define TC_UNUSED_VAR -#endif - -#ifdef trace_point -# undef trace_point -#endif - -#ifdef trace_msg -# undef trace_msg -#endif - -#ifdef DEBUG -# define if_debug(...) __VA_ARGS__ - -# ifdef TC_WINDOWS -# define trace_point OutputDebugStringA ((string (SRC_POS) + "\n").c_str()) -# define trace_msg(stream_args) do { stringstream s; s << (SRC_POS) << ": " << stream_args << endl; OutputDebugStringA (s.str().c_str()); } while (0) -# define trace_msgw(stream_args) do { wstringstream s; s << (SRC_POS) << L": " << stream_args << endl; OutputDebugStringW (s.str().c_str()); } while (0) -# else -# include -# define trace_point cerr << (SRC_POS) << endl -# define trace_msg(stream_args) cerr << (SRC_POS) << ": " << stream_args << endl -# define trace_msgw(stream_args) cerr << (SRC_POS); wcerr << L": " << stream_args << endl -# endif - -# include "Platform/SystemLog.h" -# define trace_log_point SystemLog::WriteError (SRC_POS) -# define trace_log_msg(stream_args) do { stringstream s; s << (SRC_POS) << ": " << stream_args; SystemLog::WriteError (s.str()); } while (0) - -#else -# define if_debug(...) -# define trace_point -# define trace_msg(...) -# define trace_msgw(...) -# define trace_log_point -# define trace_log_msg(...) -#endif - -#define trace_val(VAL) trace_msg (#VAL << '=' << (VAL)); - -#define array_capacity(arr) (sizeof (arr) / sizeof ((arr)[0])) - -#endif // TC_HEADER_Platform_PlatformBase +*/ + +#ifndef TC_HEADER_Platform_PlatformBase +#define TC_HEADER_Platform_PlatformBase + +#include +#include +#include +#include +#include +#include +#include + +#ifndef _MSC_VER +#include +#endif + +using namespace std; + +#ifdef nullptr +#undef nullptr +#endif + +#if !(defined(_MSC_VER) && _MSC_VER >= 1600) +#define nullptr 0 +#endif + +namespace VeraCrypt +{ +#ifdef _MSC_VER +# ifndef TC_INT_TYPES_DEFINED + typedef __int8 int8; + typedef __int16 int16; + typedef __int32 int32; + typedef __int64 int64; + typedef unsigned __int8 byte; + typedef unsigned __int16 uint16; + typedef unsigned __int32 uint32; + typedef unsigned __int64 uint64; +# endif +#else + typedef int8_t int8; + typedef int16_t int16; + typedef int32_t int32; + typedef int64_t int64; + typedef uint8_t byte; + typedef uint16_t uint16; + typedef uint32_t uint32; + typedef uint64_t uint64; +#endif +} + +#if (defined(_WIN32) || defined(_WIN64)) && !defined(TC_WINDOWS) +# define TC_WINDOWS +#endif + +#if defined(_DEBUG) && !defined(DEBUG) +# define DEBUG +#endif + +#ifndef TC_TO_STRING +# define TC_TO_STRING2(n) #n +# define TC_TO_STRING(n) TC_TO_STRING2(n) +#endif + +#define TC_JOIN_ARGS(a,b) a##b +#define TC_JOIN(a,b) TC_JOIN_ARGS(a,b) + +#ifdef __GNUC__ + template string GetFunctionName (T pos) + { + string s (pos); + size_t p = s.find ('('); + if (p == string::npos) + return s; + s = s.substr (0, p); + p = s.find_last_of (" "); + if (p == string::npos) + return s; + return s.substr (p + 1); + } +# define SRC_POS (GetFunctionName (__PRETTY_FUNCTION__) += ":" TC_TO_STRING(__LINE__)) +# define TC_UNUSED_VAR __attribute__ ((unused)) +#else +# define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) +# define TC_UNUSED_VAR +#endif + +#ifdef trace_point +# undef trace_point +#endif + +#ifdef trace_msg +# undef trace_msg +#endif + +#ifdef DEBUG +# define if_debug(...) __VA_ARGS__ + +# ifdef TC_WINDOWS +# define trace_point OutputDebugStringA ((string (SRC_POS) + "\n").c_str()) +# define trace_msg(stream_args) do { stringstream s; s << (SRC_POS) << ": " << stream_args << endl; OutputDebugStringA (s.str().c_str()); } while (0) +# define trace_msgw(stream_args) do { wstringstream s; s << (SRC_POS) << L": " << stream_args << endl; OutputDebugStringW (s.str().c_str()); } while (0) +# else +# include +# define trace_point cerr << (SRC_POS) << endl +# define trace_msg(stream_args) cerr << (SRC_POS) << ": " << stream_args << endl +# define trace_msgw(stream_args) cerr << (SRC_POS); wcerr << L": " << stream_args << endl +# endif + +# include "Platform/SystemLog.h" +# define trace_log_point SystemLog::WriteError (SRC_POS) +# define trace_log_msg(stream_args) do { stringstream s; s << (SRC_POS) << ": " << stream_args; SystemLog::WriteError (s.str()); } while (0) + +#else +# define if_debug(...) +# define trace_point +# define trace_msg(...) +# define trace_msgw(...) +# define trace_log_point +# define trace_log_msg(...) +#endif + +#define trace_val(VAL) trace_msg (#VAL << '=' << (VAL)); + +#define array_capacity(arr) (sizeof (arr) / sizeof ((arr)[0])) + +#endif // TC_HEADER_Platform_PlatformBase diff --git a/src/Platform/PlatformTest.cpp b/src/Platform/PlatformTest.cpp index dc871e4e..d6fcef3c 100644 --- a/src/Platform/PlatformTest.cpp +++ b/src/Platform/PlatformTest.cpp @@ -8,347 +8,347 @@ 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 "PlatformTest.h" -#include "Exception.h" -#include "FileStream.h" -#include "Finally.h" -#include "ForEach.h" -#include "MemoryStream.h" -#include "Mutex.h" -#include "Serializable.h" -#include "SharedPtr.h" -#include "StringConverter.h" -#include "SyncEvent.h" -#include "Thread.h" -#include "Common/Tcdefs.h" - -namespace VeraCrypt -{ - // make_shared_auto, File, Stream, MemoryStream, Endian, Serializer, Serializable - void PlatformTest::SerializerTest () - { - shared_ptr stream (new MemoryStream); - -#if 0 - make_shared_auto (File, file); - finally_do_arg (File&, *file, { if (finally_arg.IsOpen()) finally_arg.Delete(); }); - - try - { - file->Open ("veracrypt-serializer-test.tmp", File::CreateReadWrite); - stream = shared_ptr (new FileStream (file)); - } - catch (...) { } -#endif - - Serializer ser (stream); - - uint32 i32 = 0x12345678; - uint64 i64 = 0x0123456789abcdefULL; - string str = "string test"; - wstring wstr = L"wstring test"; - - string convStr = "test"; - StringConverter::ToSingle (wstr, convStr); - if (convStr != "wstring test") - throw TestFailed (SRC_POS); - - StringConverter::Erase (convStr); - if (convStr != " ") - throw TestFailed (SRC_POS); - - wstring wEraseTest = L"erase test"; - StringConverter::Erase (wEraseTest); - if (wEraseTest != L" ") - throw TestFailed (SRC_POS); - - list stringList; - stringList.push_back (str + "1"); - stringList.push_back (str + "2"); - stringList.push_back (str + "3"); - - list wstringList; - wstringList.push_back (wstr + L"1"); - wstringList.push_back (wstr + L"2"); - wstringList.push_back (wstr + L"3"); - - Buffer buffer (10); - for (size_t i = 0; i < buffer.Size(); i++) - buffer[i] = (byte) i; - - ser.Serialize ("int32", i32); - ser.Serialize ("int64", i64); - ser.Serialize ("string", str); - ser.Serialize ("wstring", wstr); - ser.Serialize ("stringList", stringList); - ser.Serialize ("wstringList", wstringList); - ser.Serialize ("buffer", ConstBufferPtr (buffer)); - - ExecutedProcessFailed ex (SRC_POS, "cmd", -123, "error output"); - ex.Serialize (stream); - - list < shared_ptr > exList; - exList.push_back (make_shared (ExecutedProcessFailed (SRC_POS, "cmd", -123, "error output1"))); - exList.push_back (make_shared (ExecutedProcessFailed (SRC_POS, "cmd", -234, "error output2"))); - exList.push_back (make_shared (ExecutedProcessFailed (SRC_POS, "cmd", -567, "error output3"))); - Serializable::SerializeList (stream, exList); - -#if 0 - if (file->IsOpen()) - file->SeekAt (0); -#endif - - uint32 di32; - ser.Deserialize ("int32", di32); - if (i32 != di32) - throw TestFailed (SRC_POS); - - uint64 di64; - ser.Deserialize ("int64", di64); - if (i64 != di64) - throw TestFailed (SRC_POS); - - string dstr; - ser.Deserialize ("string", dstr); - if (str != dstr) - throw TestFailed (SRC_POS); - - wstring dwstr; - ser.Deserialize ("wstring", dwstr); - if (str != dstr) - throw TestFailed (SRC_POS); - - int i = 1; - foreach (string item, ser.DeserializeStringList ("stringList")) - { - stringstream s; - s << str << i++; - if (item != s.str()) - throw TestFailed (SRC_POS); - } - - i = 1; - foreach (wstring item, ser.DeserializeWStringList ("wstringList")) - { - wstringstream s; - s << wstr << i++; - if (item != s.str()) - throw TestFailed (SRC_POS); - } - - Buffer dbuffer (10); - ser.Deserialize ("buffer", buffer); - for (size_t i = 0; i < buffer.Size(); i++) - if (buffer[i] != (byte) i) - throw TestFailed (SRC_POS); - - shared_ptr dex = Serializable::DeserializeNew (stream); - if (!dex - || dex->GetCommand() != "cmd" - || dex->GetExitCode() != -123 - || dex->GetErrorOutput() != "error output") - throw TestFailed (SRC_POS); - - list < shared_ptr > dexList; - Serializable::DeserializeList (stream, dexList); - i = 1; - foreach_ref (const ExecutedProcessFailed &ex, dexList) - { - stringstream s; - s << "error output" << i++; - if (ex.GetErrorOutput() != s.str()) - throw TestFailed (SRC_POS); - } - } - - // shared_ptr, Mutex, ScopeLock, SyncEvent, Thread - static struct - { - shared_ptr SharedIntPtr; - Mutex IntMutex; - SyncEvent ExitAllowedEvent; - } ThreadTestData; - - void PlatformTest::ThreadTest () - { - Mutex mutex; - mutex.Lock(); - mutex.Unlock(); - - const int maxThreads = 3; - ThreadTestData.SharedIntPtr.reset (new int (0)); - - for (int i = 0; i < maxThreads; i++) - { - Thread t; - t.Start (&ThreadTestProc, (void *) &ThreadTestData); - } - - for (int i = 0; i < 50; i++) - { - { - ScopeLock sl (ThreadTestData.IntMutex); - if (*ThreadTestData.SharedIntPtr == maxThreads) - break; - } - - Thread::Sleep(100); - } - - if (*ThreadTestData.SharedIntPtr != maxThreads) - throw TestFailed (SRC_POS); - - for (int i = 0; i < 60000; i++) - { - ThreadTestData.ExitAllowedEvent.Signal(); - Thread::Sleep(1); - - ScopeLock sl (ThreadTestData.IntMutex); - if (*ThreadTestData.SharedIntPtr == 0) - break; - } - - if (*ThreadTestData.SharedIntPtr != 0) - throw TestFailed (SRC_POS); - } - - TC_THREAD_PROC PlatformTest::ThreadTestProc (void *arg) - { - - if (arg != (void *) &ThreadTestData) - return 0; - - { - ScopeLock sl (ThreadTestData.IntMutex); - ++(*ThreadTestData.SharedIntPtr); - } - - ThreadTestData.ExitAllowedEvent.Wait(); - - { - ScopeLock sl (ThreadTestData.IntMutex); - --(*ThreadTestData.SharedIntPtr); - } - - return 0; - } - - bool PlatformTest::TestAll () - { - // Integer types - if (sizeof (byte) != 1 || sizeof (int8) != 1 || sizeof (__int8) != 1) throw TestFailed (SRC_POS); - if (sizeof (uint16) != 2 || sizeof (int16) != 2 || sizeof (__int16) != 2) throw TestFailed (SRC_POS); - if (sizeof (uint32) != 4 || sizeof (int32) != 4 || sizeof (__int32) != 4) throw TestFailed (SRC_POS); - if (sizeof (uint64) != 8 || sizeof (int64) != 8) throw TestFailed (SRC_POS); - - // Exception handling - TestFlag = false; - try - { - try - { - throw TestFailed (SRC_POS); - } - catch (...) - { - throw; - } - return false; - } - catch (Exception &) - { - TestFlag = true; - } - if (!TestFlag) - return false; - - // RTTI - RttiTest rtti; - RttiTestBase &rttiBaseRef = rtti; - RttiTestBase *rttiBasePtr = &rtti; - - if (typeid (rttiBaseRef) != typeid (rtti)) - throw TestFailed (SRC_POS); - - if (typeid (*rttiBasePtr) != typeid (rtti)) - throw TestFailed (SRC_POS); - - if (dynamic_cast (rttiBasePtr) == nullptr) - throw TestFailed (SRC_POS); - - try - { - dynamic_cast (rttiBaseRef); - } - catch (...) - { - throw TestFailed (SRC_POS); - } - - // finally - TestFlag = false; - { - finally_do ({ TestFlag = true; }); - if (TestFlag) - throw TestFailed (SRC_POS); - } - if (!TestFlag) - throw TestFailed (SRC_POS); - - TestFlag = false; - { - finally_do_arg (bool*, &TestFlag, { *finally_arg = true; }); - if (TestFlag) - throw TestFailed (SRC_POS); - } - if (!TestFlag) - throw TestFailed (SRC_POS); - - TestFlag = false; - int tesFlag2 = 0; - { - finally_do_arg2 (bool*, &TestFlag, int*, &tesFlag2, { *finally_arg = true; *finally_arg2 = 2; }); - if (TestFlag || tesFlag2 != 0) - throw TestFailed (SRC_POS); - } - if (!TestFlag || tesFlag2 != 2) - throw TestFailed (SRC_POS); - - // uint64, vector, list, string, wstring, stringstream, wstringstream - // shared_ptr, make_shared, StringConverter, foreach - list > numList; - - numList.push_front (make_shared (StringConverter::ToUInt64 (StringConverter::FromNumber ((uint64) 0xFFFFffffFFFFfffeULL)))); - numList.push_front (make_shared (StringConverter::ToUInt32 (StringConverter::GetTrailingNumber ("str2")))); - numList.push_front (make_shared (3)); - - list testList; - wstringstream wstream (L"test"); - foreach_reverse_ref (uint64 n, numList) - { - wstream.str (L""); - wstream << L"str" << n; - testList.push_back (wstream.str()); - } - - stringstream sstream; - sstream << "dummy"; - sstream.str (""); - sstream << "str18446744073709551614,str2" << " str" << StringConverter::Trim (StringConverter::ToSingle (L"\t 3 \r\n")); - foreach (const string &s, StringConverter::Split (sstream.str(), ", ")) - { - if (testList.front() != StringConverter::ToWide (s)) - throw TestFailed (SRC_POS); - testList.pop_front(); - } - - SerializerTest(); - ThreadTest(); - - return true; - } - - bool PlatformTest::TestFlag; -} +*/ + +#include "PlatformTest.h" +#include "Exception.h" +#include "FileStream.h" +#include "Finally.h" +#include "ForEach.h" +#include "MemoryStream.h" +#include "Mutex.h" +#include "Serializable.h" +#include "SharedPtr.h" +#include "StringConverter.h" +#include "SyncEvent.h" +#include "Thread.h" +#include "Common/Tcdefs.h" + +namespace VeraCrypt +{ + // make_shared_auto, File, Stream, MemoryStream, Endian, Serializer, Serializable + void PlatformTest::SerializerTest () + { + shared_ptr stream (new MemoryStream); + +#if 0 + make_shared_auto (File, file); + finally_do_arg (File&, *file, { if (finally_arg.IsOpen()) finally_arg.Delete(); }); + + try + { + file->Open ("veracrypt-serializer-test.tmp", File::CreateReadWrite); + stream = shared_ptr (new FileStream (file)); + } + catch (...) { } +#endif + + Serializer ser (stream); + + uint32 i32 = 0x12345678; + uint64 i64 = 0x0123456789abcdefULL; + string str = "string test"; + wstring wstr = L"wstring test"; + + string convStr = "test"; + StringConverter::ToSingle (wstr, convStr); + if (convStr != "wstring test") + throw TestFailed (SRC_POS); + + StringConverter::Erase (convStr); + if (convStr != " ") + throw TestFailed (SRC_POS); + + wstring wEraseTest = L"erase test"; + StringConverter::Erase (wEraseTest); + if (wEraseTest != L" ") + throw TestFailed (SRC_POS); + + list stringList; + stringList.push_back (str + "1"); + stringList.push_back (str + "2"); + stringList.push_back (str + "3"); + + list wstringList; + wstringList.push_back (wstr + L"1"); + wstringList.push_back (wstr + L"2"); + wstringList.push_back (wstr + L"3"); + + Buffer buffer (10); + for (size_t i = 0; i < buffer.Size(); i++) + buffer[i] = (byte) i; + + ser.Serialize ("int32", i32); + ser.Serialize ("int64", i64); + ser.Serialize ("string", str); + ser.Serialize ("wstring", wstr); + ser.Serialize ("stringList", stringList); + ser.Serialize ("wstringList", wstringList); + ser.Serialize ("buffer", ConstBufferPtr (buffer)); + + ExecutedProcessFailed ex (SRC_POS, "cmd", -123, "error output"); + ex.Serialize (stream); + + list < shared_ptr > exList; + exList.push_back (make_shared (ExecutedProcessFailed (SRC_POS, "cmd", -123, "error output1"))); + exList.push_back (make_shared (ExecutedProcessFailed (SRC_POS, "cmd", -234, "error output2"))); + exList.push_back (make_shared (ExecutedProcessFailed (SRC_POS, "cmd", -567, "error output3"))); + Serializable::SerializeList (stream, exList); + +#if 0 + if (file->IsOpen()) + file->SeekAt (0); +#endif + + uint32 di32; + ser.Deserialize ("int32", di32); + if (i32 != di32) + throw TestFailed (SRC_POS); + + uint64 di64; + ser.Deserialize ("int64", di64); + if (i64 != di64) + throw TestFailed (SRC_POS); + + string dstr; + ser.Deserialize ("string", dstr); + if (str != dstr) + throw TestFailed (SRC_POS); + + wstring dwstr; + ser.Deserialize ("wstring", dwstr); + if (str != dstr) + throw TestFailed (SRC_POS); + + int i = 1; + foreach (string item, ser.DeserializeStringList ("stringList")) + { + stringstream s; + s << str << i++; + if (item != s.str()) + throw TestFailed (SRC_POS); + } + + i = 1; + foreach (wstring item, ser.DeserializeWStringList ("wstringList")) + { + wstringstream s; + s << wstr << i++; + if (item != s.str()) + throw TestFailed (SRC_POS); + } + + Buffer dbuffer (10); + ser.Deserialize ("buffer", buffer); + for (size_t i = 0; i < buffer.Size(); i++) + if (buffer[i] != (byte) i) + throw TestFailed (SRC_POS); + + shared_ptr dex = Serializable::DeserializeNew (stream); + if (!dex + || dex->GetCommand() != "cmd" + || dex->GetExitCode() != -123 + || dex->GetErrorOutput() != "error output") + throw TestFailed (SRC_POS); + + list < shared_ptr > dexList; + Serializable::DeserializeList (stream, dexList); + i = 1; + foreach_ref (const ExecutedProcessFailed &ex, dexList) + { + stringstream s; + s << "error output" << i++; + if (ex.GetErrorOutput() != s.str()) + throw TestFailed (SRC_POS); + } + } + + // shared_ptr, Mutex, ScopeLock, SyncEvent, Thread + static struct + { + shared_ptr SharedIntPtr; + Mutex IntMutex; + SyncEvent ExitAllowedEvent; + } ThreadTestData; + + void PlatformTest::ThreadTest () + { + Mutex mutex; + mutex.Lock(); + mutex.Unlock(); + + const int maxThreads = 3; + ThreadTestData.SharedIntPtr.reset (new int (0)); + + for (int i = 0; i < maxThreads; i++) + { + Thread t; + t.Start (&ThreadTestProc, (void *) &ThreadTestData); + } + + for (int i = 0; i < 50; i++) + { + { + ScopeLock sl (ThreadTestData.IntMutex); + if (*ThreadTestData.SharedIntPtr == maxThreads) + break; + } + + Thread::Sleep(100); + } + + if (*ThreadTestData.SharedIntPtr != maxThreads) + throw TestFailed (SRC_POS); + + for (int i = 0; i < 60000; i++) + { + ThreadTestData.ExitAllowedEvent.Signal(); + Thread::Sleep(1); + + ScopeLock sl (ThreadTestData.IntMutex); + if (*ThreadTestData.SharedIntPtr == 0) + break; + } + + if (*ThreadTestData.SharedIntPtr != 0) + throw TestFailed (SRC_POS); + } + + TC_THREAD_PROC PlatformTest::ThreadTestProc (void *arg) + { + + if (arg != (void *) &ThreadTestData) + return 0; + + { + ScopeLock sl (ThreadTestData.IntMutex); + ++(*ThreadTestData.SharedIntPtr); + } + + ThreadTestData.ExitAllowedEvent.Wait(); + + { + ScopeLock sl (ThreadTestData.IntMutex); + --(*ThreadTestData.SharedIntPtr); + } + + return 0; + } + + bool PlatformTest::TestAll () + { + // Integer types + if (sizeof (byte) != 1 || sizeof (int8) != 1 || sizeof (__int8) != 1) throw TestFailed (SRC_POS); + if (sizeof (uint16) != 2 || sizeof (int16) != 2 || sizeof (__int16) != 2) throw TestFailed (SRC_POS); + if (sizeof (uint32) != 4 || sizeof (int32) != 4 || sizeof (__int32) != 4) throw TestFailed (SRC_POS); + if (sizeof (uint64) != 8 || sizeof (int64) != 8) throw TestFailed (SRC_POS); + + // Exception handling + TestFlag = false; + try + { + try + { + throw TestFailed (SRC_POS); + } + catch (...) + { + throw; + } + return false; + } + catch (Exception &) + { + TestFlag = true; + } + if (!TestFlag) + return false; + + // RTTI + RttiTest rtti; + RttiTestBase &rttiBaseRef = rtti; + RttiTestBase *rttiBasePtr = &rtti; + + if (typeid (rttiBaseRef) != typeid (rtti)) + throw TestFailed (SRC_POS); + + if (typeid (*rttiBasePtr) != typeid (rtti)) + throw TestFailed (SRC_POS); + + if (dynamic_cast (rttiBasePtr) == nullptr) + throw TestFailed (SRC_POS); + + try + { + dynamic_cast (rttiBaseRef); + } + catch (...) + { + throw TestFailed (SRC_POS); + } + + // finally + TestFlag = false; + { + finally_do ({ TestFlag = true; }); + if (TestFlag) + throw TestFailed (SRC_POS); + } + if (!TestFlag) + throw TestFailed (SRC_POS); + + TestFlag = false; + { + finally_do_arg (bool*, &TestFlag, { *finally_arg = true; }); + if (TestFlag) + throw TestFailed (SRC_POS); + } + if (!TestFlag) + throw TestFailed (SRC_POS); + + TestFlag = false; + int tesFlag2 = 0; + { + finally_do_arg2 (bool*, &TestFlag, int*, &tesFlag2, { *finally_arg = true; *finally_arg2 = 2; }); + if (TestFlag || tesFlag2 != 0) + throw TestFailed (SRC_POS); + } + if (!TestFlag || tesFlag2 != 2) + throw TestFailed (SRC_POS); + + // uint64, vector, list, string, wstring, stringstream, wstringstream + // shared_ptr, make_shared, StringConverter, foreach + list > numList; + + numList.push_front (make_shared (StringConverter::ToUInt64 (StringConverter::FromNumber ((uint64) 0xFFFFffffFFFFfffeULL)))); + numList.push_front (make_shared (StringConverter::ToUInt32 (StringConverter::GetTrailingNumber ("str2")))); + numList.push_front (make_shared (3)); + + list testList; + wstringstream wstream (L"test"); + foreach_reverse_ref (uint64 n, numList) + { + wstream.str (L""); + wstream << L"str" << n; + testList.push_back (wstream.str()); + } + + stringstream sstream; + sstream << "dummy"; + sstream.str (""); + sstream << "str18446744073709551614,str2" << " str" << StringConverter::Trim (StringConverter::ToSingle (L"\t 3 \r\n")); + foreach (const string &s, StringConverter::Split (sstream.str(), ", ")) + { + if (testList.front() != StringConverter::ToWide (s)) + throw TestFailed (SRC_POS); + testList.pop_front(); + } + + SerializerTest(); + ThreadTest(); + + return true; + } + + bool PlatformTest::TestFlag; +} diff --git a/src/Platform/PlatformTest.h b/src/Platform/PlatformTest.h index ff6978dd..e4dfb7ae 100644 --- a/src/Platform/PlatformTest.h +++ b/src/Platform/PlatformTest.h @@ -8,40 +8,40 @@ 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_Platform_PlatformTest -#define TC_HEADER_Platform_PlatformTest - -#include "PlatformBase.h" -#include "Thread.h" - -namespace VeraCrypt -{ - class PlatformTest - { - public: - static bool TestAll (); - - protected: - class RttiTestBase - { - public: - virtual ~RttiTestBase () { }; - }; - - class RttiTest : public RttiTestBase { - public: - virtual ~RttiTest () { }; - }; - - PlatformTest (); - static void SerializerTest (); - static void ThreadTest (); - static TC_THREAD_PROC ThreadTestProc (void *param); - - static bool TestFlag; - }; -} - -#endif // TC_HEADER_Platform_PlatformTest +*/ + +#ifndef TC_HEADER_Platform_PlatformTest +#define TC_HEADER_Platform_PlatformTest + +#include "PlatformBase.h" +#include "Thread.h" + +namespace VeraCrypt +{ + class PlatformTest + { + public: + static bool TestAll (); + + protected: + class RttiTestBase + { + public: + virtual ~RttiTestBase () { }; + }; + + class RttiTest : public RttiTestBase { + public: + virtual ~RttiTest () { }; + }; + + PlatformTest (); + static void SerializerTest (); + static void ThreadTest (); + static TC_THREAD_PROC ThreadTestProc (void *param); + + static bool TestFlag; + }; +} + +#endif // TC_HEADER_Platform_PlatformTest diff --git a/src/Platform/Serializable.cpp b/src/Platform/Serializable.cpp index 0ffb2771..8ff2c829 100644 --- a/src/Platform/Serializable.cpp +++ b/src/Platform/Serializable.cpp @@ -8,36 +8,36 @@ 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 "Serializable.h" -#include "SerializerFactory.h" - -namespace VeraCrypt -{ - string Serializable::DeserializeHeader (shared_ptr stream) - { - Serializer sr (stream); - return sr.DeserializeString ("SerializableName"); - } - - Serializable *Serializable::DeserializeNew (shared_ptr stream) - { - string name = Serializable::DeserializeHeader (stream); - Serializable *serializable = SerializerFactory::GetNewSerializable (name); - serializable->Deserialize (stream); - - return serializable; - } - - void Serializable::Serialize (shared_ptr stream) const - { - Serializer sr (stream); - Serializable::SerializeHeader (sr, SerializerFactory::GetName (typeid (*this))); - } - - void Serializable::SerializeHeader (Serializer &serializer, const string &name) - { - serializer.Serialize ("SerializableName", name); - } -} +*/ + +#include "Serializable.h" +#include "SerializerFactory.h" + +namespace VeraCrypt +{ + string Serializable::DeserializeHeader (shared_ptr stream) + { + Serializer sr (stream); + return sr.DeserializeString ("SerializableName"); + } + + Serializable *Serializable::DeserializeNew (shared_ptr stream) + { + string name = Serializable::DeserializeHeader (stream); + Serializable *serializable = SerializerFactory::GetNewSerializable (name); + serializable->Deserialize (stream); + + return serializable; + } + + void Serializable::Serialize (shared_ptr stream) const + { + Serializer sr (stream); + Serializable::SerializeHeader (sr, SerializerFactory::GetName (typeid (*this))); + } + + void Serializable::SerializeHeader (Serializer &serializer, const string &name) + { + serializer.Serialize ("SerializableName", name); + } +} diff --git a/src/Platform/Serializable.h b/src/Platform/Serializable.h index 1248c630..64c859f6 100644 --- a/src/Platform/Serializable.h +++ b/src/Platform/Serializable.h @@ -8,79 +8,79 @@ 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_Platform_Serializable -#define TC_HEADER_Platform_Serializable - -#include -#include "PlatformBase.h" -#include "ForEach.h" -#include "Serializer.h" -#include "SerializerFactory.h" - -namespace VeraCrypt -{ - class Serializable - { - public: - virtual ~Serializable () { } - - virtual void Deserialize (shared_ptr stream) = 0; - static string DeserializeHeader (shared_ptr stream); - static Serializable *DeserializeNew (shared_ptr stream); - - template - static shared_ptr DeserializeNew (shared_ptr stream) - { - shared_ptr p (dynamic_cast (DeserializeNew (stream))); - if (!p) - throw std::runtime_error (SRC_POS); - return p; - } - - template - static void DeserializeList (shared_ptr stream, list < shared_ptr > &dataList) - { - if (DeserializeHeader (stream) != string ("list<") + SerializerFactory::GetName (typeid (T)) + ">") - throw std::runtime_error (SRC_POS); - - Serializer sr (stream); - uint64 listSize; - sr.Deserialize ("ListSize", listSize); - - for (size_t i = 0; i < listSize; i++) - { - shared_ptr p (dynamic_cast (DeserializeNew (stream))); - if (!p) - throw std::runtime_error (SRC_POS); - dataList.push_back (p); - } - } - - virtual void Serialize (shared_ptr stream) const; - - template - static void SerializeList (shared_ptr stream, const list < shared_ptr > &dataList) - { - Serializer sr (stream); - SerializeHeader (sr, string ("list<") + SerializerFactory::GetName (typeid (T)) + ">"); - - sr.Serialize ("ListSize", (uint64) dataList.size()); - foreach_ref (const T &item, dataList) - item.Serialize (stream); - } - - static void SerializeHeader (Serializer &serializer, const string &name); - - protected: - Serializable () { } - }; -} - -#define TC_SERIALIZABLE(TYPE) \ - static Serializable *GetNewSerializable () { return new TYPE(); } \ - virtual void Deserialize (shared_ptr stream); \ - virtual void Serialize (shared_ptr stream) const - -#endif // TC_HEADER_Platform_Serializable +*/ + +#ifndef TC_HEADER_Platform_Serializable +#define TC_HEADER_Platform_Serializable + +#include +#include "PlatformBase.h" +#include "ForEach.h" +#include "Serializer.h" +#include "SerializerFactory.h" + +namespace VeraCrypt +{ + class Serializable + { + public: + virtual ~Serializable () { } + + virtual void Deserialize (shared_ptr stream) = 0; + static string DeserializeHeader (shared_ptr stream); + static Serializable *DeserializeNew (shared_ptr stream); + + template + static shared_ptr DeserializeNew (shared_ptr stream) + { + shared_ptr p (dynamic_cast (DeserializeNew (stream))); + if (!p) + throw std::runtime_error (SRC_POS); + return p; + } + + template + static void DeserializeList (shared_ptr stream, list < shared_ptr > &dataList) + { + if (DeserializeHeader (stream) != string ("list<") + SerializerFactory::GetName (typeid (T)) + ">") + throw std::runtime_error (SRC_POS); + + Serializer sr (stream); + uint64 listSize; + sr.Deserialize ("ListSize", listSize); + + for (size_t i = 0; i < listSize; i++) + { + shared_ptr p (dynamic_cast (DeserializeNew (stream))); + if (!p) + throw std::runtime_error (SRC_POS); + dataList.push_back (p); + } + } + + virtual void Serialize (shared_ptr stream) const; + + template + static void SerializeList (shared_ptr stream, const list < shared_ptr > &dataList) + { + Serializer sr (stream); + SerializeHeader (sr, string ("list<") + SerializerFactory::GetName (typeid (T)) + ">"); + + sr.Serialize ("ListSize", (uint64) dataList.size()); + foreach_ref (const T &item, dataList) + item.Serialize (stream); + } + + static void SerializeHeader (Serializer &serializer, const string &name); + + protected: + Serializable () { } + }; +} + +#define TC_SERIALIZABLE(TYPE) \ + static Serializable *GetNewSerializable () { return new TYPE(); } \ + virtual void Deserialize (shared_ptr stream); \ + virtual void Serialize (shared_ptr stream) const + +#endif // TC_HEADER_Platform_Serializable diff --git a/src/Platform/Serializer.cpp b/src/Platform/Serializer.cpp index f30f2212..1ac71cd1 100644 --- a/src/Platform/Serializer.cpp +++ b/src/Platform/Serializer.cpp @@ -8,296 +8,296 @@ 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 "Exception.h" -#include "ForEach.h" -#include "Memory.h" -#include "Serializer.h" - -namespace VeraCrypt -{ - template - T Serializer::Deserialize () - { - uint64 size; - DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &size, sizeof (size))); - - if (Endian::Big (size) != sizeof (T)) - throw ParameterIncorrect (SRC_POS); - - T data; - DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &data, sizeof (data))); - - return Endian::Big (data); - } - - void Serializer::Deserialize (const string &name, bool &data) - { - ValidateName (name); - data = Deserialize () == 1; - } - - void Serializer::Deserialize (const string &name, byte &data) - { - ValidateName (name); - data = Deserialize (); - } - - void Serializer::Deserialize (const string &name, int32 &data) - { - ValidateName (name); - data = (int32) Deserialize (); - } - - void Serializer::Deserialize (const string &name, int64 &data) - { - ValidateName (name); - data = (int64) Deserialize (); - } - - void Serializer::Deserialize (const string &name, uint32 &data) - { - ValidateName (name); - data = Deserialize (); - } - - void Serializer::Deserialize (const string &name, uint64 &data) - { - ValidateName (name); - data = Deserialize (); - } - - void Serializer::Deserialize (const string &name, string &data) - { - ValidateName (name); - data = DeserializeString (); - } - - void Serializer::Deserialize (const string &name, wstring &data) - { - ValidateName (name); - data = DeserializeWString (); - } - - void Serializer::Deserialize (const string &name, const BufferPtr &data) - { - ValidateName (name); - - uint64 size = Deserialize (); - if (data.Size() != size) - throw ParameterIncorrect (SRC_POS); - - DataStream->ReadCompleteBuffer (data); - } - - bool Serializer::DeserializeBool (const string &name) - { - bool data; - Deserialize (name, data); - return data; - } - - int32 Serializer::DeserializeInt32 (const string &name) - { - ValidateName (name); - return Deserialize (); - } - - int64 Serializer::DeserializeInt64 (const string &name) - { - ValidateName (name); - return Deserialize (); - } - - uint32 Serializer::DeserializeUInt32 (const string &name) - { - ValidateName (name); - return Deserialize (); - } - - uint64 Serializer::DeserializeUInt64 (const string &name) - { - ValidateName (name); - return Deserialize (); - } - - string Serializer::DeserializeString () - { - uint64 size = Deserialize (); - - vector data ((size_t) size); - DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &data[0], (size_t) size)); - - return string (&data[0]); - } - - string Serializer::DeserializeString (const string &name) - { - ValidateName (name); - return DeserializeString (); - } - - list Serializer::DeserializeStringList (const string &name) - { - ValidateName (name); - list deserializedList; - uint64 listSize = Deserialize (); - - for (size_t i = 0; i < listSize; i++) - deserializedList.push_back (DeserializeString ()); - - return deserializedList; - } - - wstring Serializer::DeserializeWString () - { - uint64 size = Deserialize (); - - vector data ((size_t) size / sizeof (wchar_t)); - DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &data[0], (size_t) size)); - - return wstring (&data[0]); - } - - list Serializer::DeserializeWStringList (const string &name) - { - ValidateName (name); - list deserializedList; - uint64 listSize = Deserialize (); - - for (size_t i = 0; i < listSize; i++) - deserializedList.push_back (DeserializeWString ()); - - return deserializedList; - } - - wstring Serializer::DeserializeWString (const string &name) - { - ValidateName (name); - return DeserializeWString (); - } - - template - void Serializer::Serialize (T data) - { - uint64 size = Endian::Big (uint64 (sizeof (data))); - DataStream->Write (ConstBufferPtr ((byte *) &size, sizeof (size))); - - data = Endian::Big (data); - DataStream->Write (ConstBufferPtr ((byte *) &data, sizeof (data))); - } - - void Serializer::Serialize (const string &name, bool data) - { - SerializeString (name); - byte d = data ? 1 : 0; - Serialize (d); - } - - void Serializer::Serialize (const string &name, byte data) - { - SerializeString (name); - Serialize (data); - } - - void Serializer::Serialize (const string &name, const char *data) - { - Serialize (name, string (data)); - } - - void Serializer::Serialize (const string &name, int32 data) - { - SerializeString (name); - Serialize ((uint32) data); - } - - void Serializer::Serialize (const string &name, int64 data) - { - SerializeString (name); - Serialize ((uint64) data); - } - - void Serializer::Serialize (const string &name, uint32 data) - { - SerializeString (name); - Serialize (data); - } - - void Serializer::Serialize (const string &name, uint64 data) - { - SerializeString (name); - Serialize (data); - } - - void Serializer::Serialize (const string &name, const string &data) - { - SerializeString (name); - SerializeString (data); - } - - void Serializer::Serialize (const string &name, const wchar_t *data) - { - Serialize (name, wstring (data)); - } - - void Serializer::Serialize (const string &name, const wstring &data) - { - SerializeString (name); - SerializeWString (data); - } - - void Serializer::Serialize (const string &name, const list &stringList) - { - SerializeString (name); - - uint64 listSize = stringList.size(); - Serialize (listSize); - - foreach (const string &item, stringList) - SerializeString (item); - } - - void Serializer::Serialize (const string &name, const list &stringList) - { - SerializeString (name); - - uint64 listSize = stringList.size(); - Serialize (listSize); - - foreach (const wstring &item, stringList) - SerializeWString (item); - } - - void Serializer::Serialize (const string &name, const ConstBufferPtr &data) - { - SerializeString (name); - - uint64 size = data.Size(); - Serialize (size); - - DataStream->Write (data); - } - - void Serializer::SerializeString (const string &data) - { - Serialize ((uint64) data.size() + 1); - DataStream->Write (ConstBufferPtr ((byte *) (data.data() ? data.data() : data.c_str()), data.size() + 1)); - } - - void Serializer::SerializeWString (const wstring &data) - { - uint64 size = (data.size() + 1) * sizeof (wchar_t); - Serialize (size); - DataStream->Write (ConstBufferPtr ((byte *) (data.data() ? data.data() : data.c_str()), (size_t) size)); - } - - void Serializer::ValidateName (const string &name) - { - string dName = DeserializeString(); - if (dName != name) - { - throw ParameterIncorrect (SRC_POS); - } - } -} +*/ + +#include "Exception.h" +#include "ForEach.h" +#include "Memory.h" +#include "Serializer.h" + +namespace VeraCrypt +{ + template + T Serializer::Deserialize () + { + uint64 size; + DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &size, sizeof (size))); + + if (Endian::Big (size) != sizeof (T)) + throw ParameterIncorrect (SRC_POS); + + T data; + DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &data, sizeof (data))); + + return Endian::Big (data); + } + + void Serializer::Deserialize (const string &name, bool &data) + { + ValidateName (name); + data = Deserialize () == 1; + } + + void Serializer::Deserialize (const string &name, byte &data) + { + ValidateName (name); + data = Deserialize (); + } + + void Serializer::Deserialize (const string &name, int32 &data) + { + ValidateName (name); + data = (int32) Deserialize (); + } + + void Serializer::Deserialize (const string &name, int64 &data) + { + ValidateName (name); + data = (int64) Deserialize (); + } + + void Serializer::Deserialize (const string &name, uint32 &data) + { + ValidateName (name); + data = Deserialize (); + } + + void Serializer::Deserialize (const string &name, uint64 &data) + { + ValidateName (name); + data = Deserialize (); + } + + void Serializer::Deserialize (const string &name, string &data) + { + ValidateName (name); + data = DeserializeString (); + } + + void Serializer::Deserialize (const string &name, wstring &data) + { + ValidateName (name); + data = DeserializeWString (); + } + + void Serializer::Deserialize (const string &name, const BufferPtr &data) + { + ValidateName (name); + + uint64 size = Deserialize (); + if (data.Size() != size) + throw ParameterIncorrect (SRC_POS); + + DataStream->ReadCompleteBuffer (data); + } + + bool Serializer::DeserializeBool (const string &name) + { + bool data; + Deserialize (name, data); + return data; + } + + int32 Serializer::DeserializeInt32 (const string &name) + { + ValidateName (name); + return Deserialize (); + } + + int64 Serializer::DeserializeInt64 (const string &name) + { + ValidateName (name); + return Deserialize (); + } + + uint32 Serializer::DeserializeUInt32 (const string &name) + { + ValidateName (name); + return Deserialize (); + } + + uint64 Serializer::DeserializeUInt64 (const string &name) + { + ValidateName (name); + return Deserialize (); + } + + string Serializer::DeserializeString () + { + uint64 size = Deserialize (); + + vector data ((size_t) size); + DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &data[0], (size_t) size)); + + return string (&data[0]); + } + + string Serializer::DeserializeString (const string &name) + { + ValidateName (name); + return DeserializeString (); + } + + list Serializer::DeserializeStringList (const string &name) + { + ValidateName (name); + list deserializedList; + uint64 listSize = Deserialize (); + + for (size_t i = 0; i < listSize; i++) + deserializedList.push_back (DeserializeString ()); + + return deserializedList; + } + + wstring Serializer::DeserializeWString () + { + uint64 size = Deserialize (); + + vector data ((size_t) size / sizeof (wchar_t)); + DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &data[0], (size_t) size)); + + return wstring (&data[0]); + } + + list Serializer::DeserializeWStringList (const string &name) + { + ValidateName (name); + list deserializedList; + uint64 listSize = Deserialize (); + + for (size_t i = 0; i < listSize; i++) + deserializedList.push_back (DeserializeWString ()); + + return deserializedList; + } + + wstring Serializer::DeserializeWString (const string &name) + { + ValidateName (name); + return DeserializeWString (); + } + + template + void Serializer::Serialize (T data) + { + uint64 size = Endian::Big (uint64 (sizeof (data))); + DataStream->Write (ConstBufferPtr ((byte *) &size, sizeof (size))); + + data = Endian::Big (data); + DataStream->Write (ConstBufferPtr ((byte *) &data, sizeof (data))); + } + + void Serializer::Serialize (const string &name, bool data) + { + SerializeString (name); + byte d = data ? 1 : 0; + Serialize (d); + } + + void Serializer::Serialize (const string &name, byte data) + { + SerializeString (name); + Serialize (data); + } + + void Serializer::Serialize (const string &name, const char *data) + { + Serialize (name, string (data)); + } + + void Serializer::Serialize (const string &name, int32 data) + { + SerializeString (name); + Serialize ((uint32) data); + } + + void Serializer::Serialize (const string &name, int64 data) + { + SerializeString (name); + Serialize ((uint64) data); + } + + void Serializer::Serialize (const string &name, uint32 data) + { + SerializeString (name); + Serialize (data); + } + + void Serializer::Serialize (const string &name, uint64 data) + { + SerializeString (name); + Serialize (data); + } + + void Serializer::Serialize (const string &name, const string &data) + { + SerializeString (name); + SerializeString (data); + } + + void Serializer::Serialize (const string &name, const wchar_t *data) + { + Serialize (name, wstring (data)); + } + + void Serializer::Serialize (const string &name, const wstring &data) + { + SerializeString (name); + SerializeWString (data); + } + + void Serializer::Serialize (const string &name, const list &stringList) + { + SerializeString (name); + + uint64 listSize = stringList.size(); + Serialize (listSize); + + foreach (const string &item, stringList) + SerializeString (item); + } + + void Serializer::Serialize (const string &name, const list &stringList) + { + SerializeString (name); + + uint64 listSize = stringList.size(); + Serialize (listSize); + + foreach (const wstring &item, stringList) + SerializeWString (item); + } + + void Serializer::Serialize (const string &name, const ConstBufferPtr &data) + { + SerializeString (name); + + uint64 size = data.Size(); + Serialize (size); + + DataStream->Write (data); + } + + void Serializer::SerializeString (const string &data) + { + Serialize ((uint64) data.size() + 1); + DataStream->Write (ConstBufferPtr ((byte *) (data.data() ? data.data() : data.c_str()), data.size() + 1)); + } + + void Serializer::SerializeWString (const wstring &data) + { + uint64 size = (data.size() + 1) * sizeof (wchar_t); + Serialize (size); + DataStream->Write (ConstBufferPtr ((byte *) (data.data() ? data.data() : data.c_str()), (size_t) size)); + } + + void Serializer::ValidateName (const string &name) + { + string dName = DeserializeString(); + if (dName != name) + { + throw ParameterIncorrect (SRC_POS); + } + } +} diff --git a/src/Platform/Serializer.h b/src/Platform/Serializer.h index 67760c45..50065b9a 100644 --- a/src/Platform/Serializer.h +++ b/src/Platform/Serializer.h @@ -8,71 +8,71 @@ 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_Platform_Serializer -#define TC_HEADER_Platform_Serializer - -#include "PlatformBase.h" -#include "Buffer.h" -#include "SharedPtr.h" -#include "Stream.h" - -namespace VeraCrypt -{ - class Serializer - { - public: - Serializer (shared_ptr stream) : DataStream (stream) { } - virtual ~Serializer () { } - - void Deserialize (const string &name, bool &data); - void Deserialize (const string &name, byte &data); - void Deserialize (const string &name, int32 &data); - void Deserialize (const string &name, int64 &data); - void Deserialize (const string &name, uint32 &data); - void Deserialize (const string &name, uint64 &data); - void Deserialize (const string &name, string &data); - void Deserialize (const string &name, wstring &data); - void Deserialize (const string &name, const BufferPtr &data); - bool DeserializeBool (const string &name); - int32 DeserializeInt32 (const string &name); - int64 DeserializeInt64 (const string &name); - uint32 DeserializeUInt32 (const string &name); - uint64 DeserializeUInt64 (const string &name); - string DeserializeString (const string &name); - list DeserializeStringList (const string &name); - wstring DeserializeWString (const string &name); - list DeserializeWStringList (const string &name); - void Serialize (const string &name, bool data); - void Serialize (const string &name, byte data); - void Serialize (const string &name, const char *data); - void Serialize (const string &name, int32 data); - void Serialize (const string &name, int64 data); - void Serialize (const string &name, uint32 data); - void Serialize (const string &name, uint64 data); - void Serialize (const string &name, const string &data); - void Serialize (const string &name, const wstring &data); - void Serialize (const string &name, const wchar_t *data); - void Serialize (const string &name, const list &stringList); - void Serialize (const string &name, const list &stringList); - void Serialize (const string &name, const ConstBufferPtr &data); - - protected: - template T Deserialize (); - string DeserializeString (); - wstring DeserializeWString (); - template void Serialize (T data); - void SerializeString (const string &data); - void SerializeWString (const wstring &data); - void ValidateName (const string &name); - - shared_ptr DataStream; - - private: - Serializer (const Serializer &); - Serializer &operator= (const Serializer &); - }; -} - -#endif // TC_HEADER_Platform_Serializer +*/ + +#ifndef TC_HEADER_Platform_Serializer +#define TC_HEADER_Platform_Serializer + +#include "PlatformBase.h" +#include "Buffer.h" +#include "SharedPtr.h" +#include "Stream.h" + +namespace VeraCrypt +{ + class Serializer + { + public: + Serializer (shared_ptr stream) : DataStream (stream) { } + virtual ~Serializer () { } + + void Deserialize (const string &name, bool &data); + void Deserialize (const string &name, byte &data); + void Deserialize (const string &name, int32 &data); + void Deserialize (const string &name, int64 &data); + void Deserialize (const string &name, uint32 &data); + void Deserialize (const string &name, uint64 &data); + void Deserialize (const string &name, string &data); + void Deserialize (const string &name, wstring &data); + void Deserialize (const string &name, const BufferPtr &data); + bool DeserializeBool (const string &name); + int32 DeserializeInt32 (const string &name); + int64 DeserializeInt64 (const string &name); + uint32 DeserializeUInt32 (const string &name); + uint64 DeserializeUInt64 (const string &name); + string DeserializeString (const string &name); + list DeserializeStringList (const string &name); + wstring DeserializeWString (const string &name); + list DeserializeWStringList (const string &name); + void Serialize (const string &name, bool data); + void Serialize (const string &name, byte data); + void Serialize (const string &name, const char *data); + void Serialize (const string &name, int32 data); + void Serialize (const string &name, int64 data); + void Serialize (const string &name, uint32 data); + void Serialize (const string &name, uint64 data); + void Serialize (const string &name, const string &data); + void Serialize (const string &name, const wstring &data); + void Serialize (const string &name, const wchar_t *data); + void Serialize (const string &name, const list &stringList); + void Serialize (const string &name, const list &stringList); + void Serialize (const string &name, const ConstBufferPtr &data); + + protected: + template T Deserialize (); + string DeserializeString (); + wstring DeserializeWString (); + template void Serialize (T data); + void SerializeString (const string &data); + void SerializeWString (const wstring &data); + void ValidateName (const string &name); + + shared_ptr DataStream; + + private: + Serializer (const Serializer &); + Serializer &operator= (const Serializer &); + }; +} + +#endif // TC_HEADER_Platform_Serializer diff --git a/src/Platform/SerializerFactory.cpp b/src/Platform/SerializerFactory.cpp index 663bbea1..aca002ca 100644 --- a/src/Platform/SerializerFactory.cpp +++ b/src/Platform/SerializerFactory.cpp @@ -8,51 +8,51 @@ 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 -#include "SerializerFactory.h" - -namespace VeraCrypt -{ - void SerializerFactory::Deinitialize () - { - if (--UseCount == 0) - { - delete NameToTypeMap; - delete TypeToNameMap; - } - } - - string SerializerFactory::GetName (const type_info &typeInfo) - { - string typeName = StringConverter::GetTypeName (typeInfo); - if (TypeToNameMap->find (typeName) == TypeToNameMap->end()) - throw std::runtime_error (SRC_POS); - - return (*TypeToNameMap)[typeName]; - } - - Serializable *SerializerFactory::GetNewSerializable (const string &typeName) - { - if (NameToTypeMap->find (typeName) == NameToTypeMap->end()) - throw std::runtime_error (SRC_POS); - - return (*NameToTypeMap)[typeName].GetNewPtr(); - } - - void SerializerFactory::Initialize () - { - if (UseCount == 0) - { - NameToTypeMap = new map ; - TypeToNameMap = new map ; - } - - ++UseCount; - } - - map *SerializerFactory::NameToTypeMap; - map *SerializerFactory::TypeToNameMap; - int SerializerFactory::UseCount; -} +*/ + +#include +#include "SerializerFactory.h" + +namespace VeraCrypt +{ + void SerializerFactory::Deinitialize () + { + if (--UseCount == 0) + { + delete NameToTypeMap; + delete TypeToNameMap; + } + } + + string SerializerFactory::GetName (const type_info &typeInfo) + { + string typeName = StringConverter::GetTypeName (typeInfo); + if (TypeToNameMap->find (typeName) == TypeToNameMap->end()) + throw std::runtime_error (SRC_POS); + + return (*TypeToNameMap)[typeName]; + } + + Serializable *SerializerFactory::GetNewSerializable (const string &typeName) + { + if (NameToTypeMap->find (typeName) == NameToTypeMap->end()) + throw std::runtime_error (SRC_POS); + + return (*NameToTypeMap)[typeName].GetNewPtr(); + } + + void SerializerFactory::Initialize () + { + if (UseCount == 0) + { + NameToTypeMap = new map ; + TypeToNameMap = new map ; + } + + ++UseCount; + } + + map *SerializerFactory::NameToTypeMap; + map *SerializerFactory::TypeToNameMap; + int SerializerFactory::UseCount; +} diff --git a/src/Platform/SerializerFactory.h b/src/Platform/SerializerFactory.h index c63dbcf8..e3f7a892 100644 --- a/src/Platform/SerializerFactory.h +++ b/src/Platform/SerializerFactory.h @@ -8,90 +8,90 @@ 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_Platform_SerializerFactory -#define TC_HEADER_Platform_SerializerFactory - -#include -#include "PlatformBase.h" -#include "StringConverter.h" - -namespace VeraCrypt -{ - class Serializable; - - class SerializerFactory - { - public: - ~SerializerFactory (); - - static void Deinitialize (); - static string GetName (const type_info &typeInfo); - static Serializable *GetNewSerializable (const string &typeName); - static void Initialize (); - - struct MapEntry - { - MapEntry () { } - MapEntry (const string &typeName, Serializable* (*getNewPtr) ()) - : TypeName (typeName), GetNewPtr (getNewPtr) { } - - MapEntry &operator= (const MapEntry &right) - { - TypeName = right.TypeName; - GetNewPtr = right.GetNewPtr; - return *this; - } - - string TypeName; - Serializable* (*GetNewPtr) (); - }; - - static map *NameToTypeMap; - static map *TypeToNameMap; - - protected: - SerializerFactory (); - - static int UseCount; - }; - -} - -#define TC_SERIALIZER_FACTORY_ADD_EXCEPTION_SET(TYPE) \ - struct TYPE##SerializerFactoryInitializer \ - { \ - TYPE##SerializerFactoryInitializer () \ - { \ - SerializerFactory::Initialize(); \ - TC_EXCEPTION_SET; \ - } \ - ~TYPE##SerializerFactoryInitializer () \ - { \ - SerializerFactory::Deinitialize(); \ - } \ - }; \ - static TYPE##SerializerFactoryInitializer TYPE##SerializerFactoryInitializer - -#define TC_SERIALIZER_FACTORY_ADD_CLASS(TYPE) \ - struct TYPE##SerializerFactoryInitializer \ - { \ - TYPE##SerializerFactoryInitializer () \ - { \ - SerializerFactory::Initialize(); \ - TC_SERIALIZER_FACTORY_ADD (TYPE); \ - } \ - ~TYPE##SerializerFactoryInitializer () \ - { \ - SerializerFactory::Deinitialize(); \ - } \ - }; \ - static TYPE##SerializerFactoryInitializer TYPE##SerializerFactoryInitializerInst - -#define TC_SERIALIZER_FACTORY_ADD(TYPE) \ - (*SerializerFactory::NameToTypeMap)[#TYPE] = SerializerFactory::MapEntry (StringConverter::GetTypeName (typeid (TYPE)), &TYPE::GetNewSerializable); \ - (*SerializerFactory::TypeToNameMap)[StringConverter::GetTypeName (typeid (TYPE))] = #TYPE - - -#endif // TC_HEADER_Platform_SerializerFactory +*/ + +#ifndef TC_HEADER_Platform_SerializerFactory +#define TC_HEADER_Platform_SerializerFactory + +#include +#include "PlatformBase.h" +#include "StringConverter.h" + +namespace VeraCrypt +{ + class Serializable; + + class SerializerFactory + { + public: + ~SerializerFactory (); + + static void Deinitialize (); + static string GetName (const type_info &typeInfo); + static Serializable *GetNewSerializable (const string &typeName); + static void Initialize (); + + struct MapEntry + { + MapEntry () { } + MapEntry (const string &typeName, Serializable* (*getNewPtr) ()) + : TypeName (typeName), GetNewPtr (getNewPtr) { } + + MapEntry &operator= (const MapEntry &right) + { + TypeName = right.TypeName; + GetNewPtr = right.GetNewPtr; + return *this; + } + + string TypeName; + Serializable* (*GetNewPtr) (); + }; + + static map *NameToTypeMap; + static map *TypeToNameMap; + + protected: + SerializerFactory (); + + static int UseCount; + }; + +} + +#define TC_SERIALIZER_FACTORY_ADD_EXCEPTION_SET(TYPE) \ + struct TYPE##SerializerFactoryInitializer \ + { \ + TYPE##SerializerFactoryInitializer () \ + { \ + SerializerFactory::Initialize(); \ + TC_EXCEPTION_SET; \ + } \ + ~TYPE##SerializerFactoryInitializer () \ + { \ + SerializerFactory::Deinitialize(); \ + } \ + }; \ + static TYPE##SerializerFactoryInitializer TYPE##SerializerFactoryInitializer + +#define TC_SERIALIZER_FACTORY_ADD_CLASS(TYPE) \ + struct TYPE##SerializerFactoryInitializer \ + { \ + TYPE##SerializerFactoryInitializer () \ + { \ + SerializerFactory::Initialize(); \ + TC_SERIALIZER_FACTORY_ADD (TYPE); \ + } \ + ~TYPE##SerializerFactoryInitializer () \ + { \ + SerializerFactory::Deinitialize(); \ + } \ + }; \ + static TYPE##SerializerFactoryInitializer TYPE##SerializerFactoryInitializerInst + +#define TC_SERIALIZER_FACTORY_ADD(TYPE) \ + (*SerializerFactory::NameToTypeMap)[#TYPE] = SerializerFactory::MapEntry (StringConverter::GetTypeName (typeid (TYPE)), &TYPE::GetNewSerializable); \ + (*SerializerFactory::TypeToNameMap)[StringConverter::GetTypeName (typeid (TYPE))] = #TYPE + + +#endif // TC_HEADER_Platform_SerializerFactory diff --git a/src/Platform/SharedPtr.h b/src/Platform/SharedPtr.h index 0bc7bdcf..ce49469b 100644 --- a/src/Platform/SharedPtr.h +++ b/src/Platform/SharedPtr.h @@ -8,159 +8,159 @@ 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_Platform_SharedPtr -#define TC_HEADER_Platform_SharedPtr - -#include -#include "SharedVal.h" - -#ifdef nullptr - -namespace VeraCrypt -{ - template - class SharedPtr - { - public: - explicit SharedPtr () - : Pointer (nullptr), UseCount (nullptr) { } - - explicit SharedPtr (T *pointer) - : Pointer (pointer), UseCount (new SharedVal (1)) { } - - SharedPtr (const SharedPtr &source) - { - CopyFrom (source); - } - - ~SharedPtr () - { - Release(); - } - - SharedPtr &operator= (const SharedPtr &source) - { - if (&source == this) - return *this; - - Release(); - CopyFrom (source); - return *this; - } - - bool operator == (const SharedPtr &other) - { - return get() == other.get(); - } - - bool operator != (const SharedPtr &other) - { - return get() != other.get(); - } - - T &operator* () const - { -#ifdef DEBUG - if (Pointer == nullptr) - throw std::runtime_error (SRC_POS); -#endif - return *Pointer; - } - - T *operator-> () const - { -#ifdef DEBUG - if (Pointer == nullptr) - throw std::runtime_error (SRC_POS); -#endif - return Pointer; - } - - operator bool () const - { - return Pointer != nullptr; - } - - T *get () const - { - return Pointer; - } - - void reset () - { - Release(); - } - - void reset (T *pointer) - { - *this = SharedPtr (pointer); - } - - uint64 use_count () const - { - if (!UseCount) - return 0; - - return *UseCount; - } - - protected: - void CopyFrom (const SharedPtr &source) - { - Pointer = source.Pointer; - UseCount = source.UseCount; - - if (UseCount) - UseCount->Increment(); - } - - void Release () - { - if (UseCount != nullptr) - { - if (UseCount->Decrement() == 0) - { - if (Pointer != nullptr) - delete Pointer; - delete UseCount; - } - - Pointer = nullptr; - UseCount = nullptr; - } - } - - T *Pointer; - SharedVal *UseCount; - }; - -#ifdef shared_ptr -#undef shared_ptr -#endif -#define shared_ptr VeraCrypt::SharedPtr - -#ifdef make_shared -#undef make_shared -#endif - - template shared_ptr make_shared () - { - return shared_ptr (new T ()); - } - - template shared_ptr make_shared (const A &arg) - { - return shared_ptr (new T (arg)); - } - -#define make_shared VeraCrypt::make_shared - -} - -#endif // nullptr - -#define make_shared_auto(typeName,instanceName) shared_ptr instanceName (new typeName ()) - -#endif // TC_HEADER_Platform_SharedPtr +*/ + +#ifndef TC_HEADER_Platform_SharedPtr +#define TC_HEADER_Platform_SharedPtr + +#include +#include "SharedVal.h" + +#ifdef nullptr + +namespace VeraCrypt +{ + template + class SharedPtr + { + public: + explicit SharedPtr () + : Pointer (nullptr), UseCount (nullptr) { } + + explicit SharedPtr (T *pointer) + : Pointer (pointer), UseCount (new SharedVal (1)) { } + + SharedPtr (const SharedPtr &source) + { + CopyFrom (source); + } + + ~SharedPtr () + { + Release(); + } + + SharedPtr &operator= (const SharedPtr &source) + { + if (&source == this) + return *this; + + Release(); + CopyFrom (source); + return *this; + } + + bool operator == (const SharedPtr &other) + { + return get() == other.get(); + } + + bool operator != (const SharedPtr &other) + { + return get() != other.get(); + } + + T &operator* () const + { +#ifdef DEBUG + if (Pointer == nullptr) + throw std::runtime_error (SRC_POS); +#endif + return *Pointer; + } + + T *operator-> () const + { +#ifdef DEBUG + if (Pointer == nullptr) + throw std::runtime_error (SRC_POS); +#endif + return Pointer; + } + + operator bool () const + { + return Pointer != nullptr; + } + + T *get () const + { + return Pointer; + } + + void reset () + { + Release(); + } + + void reset (T *pointer) + { + *this = SharedPtr (pointer); + } + + uint64 use_count () const + { + if (!UseCount) + return 0; + + return *UseCount; + } + + protected: + void CopyFrom (const SharedPtr &source) + { + Pointer = source.Pointer; + UseCount = source.UseCount; + + if (UseCount) + UseCount->Increment(); + } + + void Release () + { + if (UseCount != nullptr) + { + if (UseCount->Decrement() == 0) + { + if (Pointer != nullptr) + delete Pointer; + delete UseCount; + } + + Pointer = nullptr; + UseCount = nullptr; + } + } + + T *Pointer; + SharedVal *UseCount; + }; + +#ifdef shared_ptr +#undef shared_ptr +#endif +#define shared_ptr VeraCrypt::SharedPtr + +#ifdef make_shared +#undef make_shared +#endif + + template shared_ptr make_shared () + { + return shared_ptr (new T ()); + } + + template shared_ptr make_shared (const A &arg) + { + return shared_ptr (new T (arg)); + } + +#define make_shared VeraCrypt::make_shared + +} + +#endif // nullptr + +#define make_shared_auto(typeName,instanceName) shared_ptr instanceName (new typeName ()) + +#endif // TC_HEADER_Platform_SharedPtr diff --git a/src/Platform/SharedVal.h b/src/Platform/SharedVal.h index 1a1e98cc..ffdc7e84 100644 --- a/src/Platform/SharedVal.h +++ b/src/Platform/SharedVal.h @@ -8,68 +8,68 @@ 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_Platform_SharedVal -#define TC_HEADER_Platform_SharedVal - -#include "PlatformBase.h" -#include "Mutex.h" - -namespace VeraCrypt -{ - template - class SharedVal - { - public: - SharedVal () { } - explicit SharedVal (T value) : Value (value) { } - virtual ~SharedVal () { } - - operator T () - { - return Get (); - } - - T Decrement () - { - ValMutex.Lock(); - T r = --Value; - ValMutex.Unlock(); - return r; - } - - T Get () - { - ValMutex.Lock(); - T r = Value; - ValMutex.Unlock(); - return r; - } - - T Increment () - { - ValMutex.Lock(); - T r = ++Value; - ValMutex.Unlock(); - return r; - } - - void Set (T value) - { - ValMutex.Lock(); - Value = value; - ValMutex.Unlock(); - } - - protected: - volatile T Value; - Mutex ValMutex; - - private: - SharedVal (const SharedVal &); - SharedVal &operator= (const SharedVal &); - }; -} - -#endif // TC_HEADER_Platform_SharedVal +*/ + +#ifndef TC_HEADER_Platform_SharedVal +#define TC_HEADER_Platform_SharedVal + +#include "PlatformBase.h" +#include "Mutex.h" + +namespace VeraCrypt +{ + template + class SharedVal + { + public: + SharedVal () { } + explicit SharedVal (T value) : Value (value) { } + virtual ~SharedVal () { } + + operator T () + { + return Get (); + } + + T Decrement () + { + ValMutex.Lock(); + T r = --Value; + ValMutex.Unlock(); + return r; + } + + T Get () + { + ValMutex.Lock(); + T r = Value; + ValMutex.Unlock(); + return r; + } + + T Increment () + { + ValMutex.Lock(); + T r = ++Value; + ValMutex.Unlock(); + return r; + } + + void Set (T value) + { + ValMutex.Lock(); + Value = value; + ValMutex.Unlock(); + } + + protected: + volatile T Value; + Mutex ValMutex; + + private: + SharedVal (const SharedVal &); + SharedVal &operator= (const SharedVal &); + }; +} + +#endif // TC_HEADER_Platform_SharedVal diff --git a/src/Platform/Stream.h b/src/Platform/Stream.h index 3f2ddc2d..293a66f1 100644 --- a/src/Platform/Stream.h +++ b/src/Platform/Stream.h @@ -8,31 +8,31 @@ 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_Platform_Stream -#define TC_HEADER_Platform_Stream - -#include "PlatformBase.h" -#include "Buffer.h" - -namespace VeraCrypt -{ - class Stream - { - public: - virtual ~Stream () { } - virtual uint64 Read (const BufferPtr &buffer) = 0; - virtual void ReadCompleteBuffer (const BufferPtr &buffer) = 0; - virtual void Write (const ConstBufferPtr &data) = 0; - - protected: - Stream () { }; - - private: - Stream (const Stream &); - Stream &operator= (const Stream &); - }; -} - -#endif // TC_HEADER_Platform_Stream +*/ + +#ifndef TC_HEADER_Platform_Stream +#define TC_HEADER_Platform_Stream + +#include "PlatformBase.h" +#include "Buffer.h" + +namespace VeraCrypt +{ + class Stream + { + public: + virtual ~Stream () { } + virtual uint64 Read (const BufferPtr &buffer) = 0; + virtual void ReadCompleteBuffer (const BufferPtr &buffer) = 0; + virtual void Write (const ConstBufferPtr &data) = 0; + + protected: + Stream () { }; + + private: + Stream (const Stream &); + Stream &operator= (const Stream &); + }; +} + +#endif // TC_HEADER_Platform_Stream diff --git a/src/Platform/StringConverter.cpp b/src/Platform/StringConverter.cpp index 3e99e0f2..d5c17e88 100644 --- a/src/Platform/StringConverter.cpp +++ b/src/Platform/StringConverter.cpp @@ -8,412 +8,412 @@ 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. -*/ - -#ifdef __GNUC__ -# include -#endif -#include -#include -#include "Buffer.h" -#include "Exception.h" -#include "ForEach.h" -#include "StringConverter.h" -#include "SystemException.h" - -namespace VeraCrypt -{ - void StringConverter::Erase (string &str) - { - for (size_t i = 0; i < str.size(); ++i) - { - str[i] = ' '; - } - } - - void StringConverter::Erase (wstring &str) - { - for (size_t i = 0; i < str.size(); ++i) - { - str[i] = ' '; - } - } - - wstring StringConverter::FromNumber (double number) - { - wstringstream s; - s << number; - return s.str(); - } - - wstring StringConverter::FromNumber (int32 number) - { - wstringstream s; - s << number; - return s.str(); - } - - wstring StringConverter::FromNumber (uint32 number) - { - wstringstream s; - s << number; - return s.str(); - } - - wstring StringConverter::FromNumber (int64 number) - { - wstringstream s; - s << number; - return s.str(); - } - - wstring StringConverter::FromNumber (uint64 number) - { - wstringstream s; - s << number; - return s.str(); - } - - string StringConverter::GetTrailingNumber (const string &str) - { - size_t start = str.find_last_not_of ("0123456789"); - if (start == string::npos) - return str; - - string s = str.substr (start + 1); - if (s.empty ()) - throw ParameterIncorrect (SRC_POS); - - return s; - } - - string StringConverter::GetTypeName (const type_info &typeInfo) - { - try - { -#ifdef _MSC_VER - // type_info::name() leaks memory as of MS VC++ 8.0 - string rawName (typeInfo.raw_name()); - - size_t cut1 = (rawName.find (".?A") != string::npos) ? 4 : string::npos; - size_t cut2 = rawName.find ("@"); - size_t cut3 = rawName.find ("@@"); - - if (cut1 == string::npos || cut2 == string::npos || cut3 == string::npos) - return typeInfo.name(); - - return rawName.substr (cut2 + 1, cut3 - cut2 - 1) + "::" + rawName.substr (cut1, cut2 - cut1); - -#elif defined (__GNUC__) - int status; - char *name = abi::__cxa_demangle (typeInfo.name(), nullptr, nullptr, &status); - - if (name) - { - string s (name); - free (name); - return s; - } -#endif - } - catch (...) { } - - return typeInfo.name(); - } - - wstring StringConverter::QuoteSpaces (const wstring &str) - { - if (str.find (L' ') == string::npos) - return str; - - wstring escaped (L"'"); - foreach (wchar_t c, str) - { - if (c == L'\'') - escaped += L'\''; - escaped += c; - } - return escaped + L'\''; - } - - vector StringConverter::Split (const string &str, const string &separators, bool returnEmptyFields) - { - vector elements; - - if (!returnEmptyFields) - { - size_t p = 0; - while ((p = str.find_first_not_of (separators, p)) != string::npos) - { - size_t end = str.find_first_of (separators, p); - if (end == string::npos) - { - elements.push_back (str.substr (p)); - break; - } - - elements.push_back (str.substr (p, end - p)); - p = end; - } - } - else - { - string element; - elements.push_back (element); - foreach (char c, str) - { - if (separators.find (c) != string::npos) - { - element.erase(); - elements.push_back (element); - } - else - { - elements.back() += c; - } - } - } - - return elements; - } - - string StringConverter::StripTrailingNumber (const string &str) - { - size_t start = str.find_last_not_of ("0123456789"); - if (start == string::npos) - return ""; - - return str.substr (0, start + 1); - } - - wstring StringConverter::ToExceptionString (const exception &ex) - { - const SystemException *sysEx = dynamic_cast (&ex); - if (sysEx) - return ToWide (sysEx->what()) + L": " + sysEx->SystemText() + L": " + sysEx->GetSubject(); - - if (ex.what() && !string (ex.what()).empty()) - return ToWide (GetTypeName (typeid (ex)) + ": " + ex.what()); - - return ToWide (GetTypeName (typeid (ex))); - } - - string StringConverter::ToLower (const string &str) - { - string s; - foreach (char c, str) - s += tolower (c, locale()); - return s; - } - - string StringConverter::ToSingle (const wstring &wstr, bool noThrow) - { - string str; - ToSingle (wstr, str, noThrow); - return str; - } - - void StringConverter::ToSingle (const wstring &wstr, string &str, bool noThrow) - { - try - { - mbstate_t mbState; - Memory::Zero (&mbState, sizeof (mbState)); - const wchar_t *src = wstr.c_str(); - - size_t size = wcsrtombs (nullptr, &src, 0, &mbState); - if (size == (size_t) -1) - throw StringConversionFailed (SRC_POS, wstr); - - vector buf (size + 1); - Memory::Zero (&mbState, sizeof (mbState)); - - if ((size = wcsrtombs (&buf[0], &src, buf.size(), &mbState)) == (size_t) -1) - throw StringConversionFailed (SRC_POS, wstr); - - str.clear(); - str.insert (0, &buf.front(), size); - Memory::Erase (&buf.front(), buf.size()); - } - catch (...) - { - if (!noThrow) - throw; - } - } - - uint32 StringConverter::ToUInt32 (const string &str) - { - uint32 n; - stringstream ss (str); - - ss >> n; - if (ss.fail() || n == 0xffffFFFFU) - throw ParameterIncorrect (SRC_POS); - - return n; - } - - uint32 StringConverter::ToUInt32 (const wstring &str) - { - uint32 n; - wstringstream ss (str); - - ss >> n; - if (ss.fail() || n == 0xffffFFFFU) - throw ParameterIncorrect (SRC_POS); - - return n; +*/ + +#ifdef __GNUC__ +# include +#endif +#include +#include +#include "Buffer.h" +#include "Exception.h" +#include "ForEach.h" +#include "StringConverter.h" +#include "SystemException.h" + +namespace VeraCrypt +{ + void StringConverter::Erase (string &str) + { + for (size_t i = 0; i < str.size(); ++i) + { + str[i] = ' '; + } + } + + void StringConverter::Erase (wstring &str) + { + for (size_t i = 0; i < str.size(); ++i) + { + str[i] = ' '; + } + } + + wstring StringConverter::FromNumber (double number) + { + wstringstream s; + s << number; + return s.str(); + } + + wstring StringConverter::FromNumber (int32 number) + { + wstringstream s; + s << number; + return s.str(); + } + + wstring StringConverter::FromNumber (uint32 number) + { + wstringstream s; + s << number; + return s.str(); + } + + wstring StringConverter::FromNumber (int64 number) + { + wstringstream s; + s << number; + return s.str(); } - int32 StringConverter::ToInt32 (const string &str) - { - int32 n; - stringstream ss (str); - - ss >> n; - if (ss.fail() || n == 0x7fffFFFF || n == -0x7fffFFFF) - throw ParameterIncorrect (SRC_POS); - - return n; - } - - int32 StringConverter::ToInt32 (const wstring &str) - { - int32 n; - wstringstream ss (str); - - ss >> n; - if (ss.fail() || n == 0x7fffFFFF || n == -0x7fffFFFF) - throw ParameterIncorrect (SRC_POS); - - return n; - } - - uint64 StringConverter::ToUInt64 (const string &str) - { - uint64 n; - stringstream ss (str); - - ss >> n; - if (ss.fail() || n == 0xffffFFFFffffFFFFULL) - throw ParameterIncorrect (SRC_POS); - - return n; - } - - uint64 StringConverter::ToUInt64 (const wstring &str) - { - uint64 n; - wstringstream ss (str); - - ss >> n; - if (ss.fail() || n == 0xffffFFFFffffFFFFULL) - throw ParameterIncorrect (SRC_POS); - - return n; + wstring StringConverter::FromNumber (uint64 number) + { + wstringstream s; + s << number; + return s.str(); + } + + string StringConverter::GetTrailingNumber (const string &str) + { + size_t start = str.find_last_not_of ("0123456789"); + if (start == string::npos) + return str; + + string s = str.substr (start + 1); + if (s.empty ()) + throw ParameterIncorrect (SRC_POS); + + return s; + } + + string StringConverter::GetTypeName (const type_info &typeInfo) + { + try + { +#ifdef _MSC_VER + // type_info::name() leaks memory as of MS VC++ 8.0 + string rawName (typeInfo.raw_name()); + + size_t cut1 = (rawName.find (".?A") != string::npos) ? 4 : string::npos; + size_t cut2 = rawName.find ("@"); + size_t cut3 = rawName.find ("@@"); + + if (cut1 == string::npos || cut2 == string::npos || cut3 == string::npos) + return typeInfo.name(); + + return rawName.substr (cut2 + 1, cut3 - cut2 - 1) + "::" + rawName.substr (cut1, cut2 - cut1); + +#elif defined (__GNUC__) + int status; + char *name = abi::__cxa_demangle (typeInfo.name(), nullptr, nullptr, &status); + + if (name) + { + string s (name); + free (name); + return s; + } +#endif + } + catch (...) { } + + return typeInfo.name(); + } + + wstring StringConverter::QuoteSpaces (const wstring &str) + { + if (str.find (L' ') == string::npos) + return str; + + wstring escaped (L"'"); + foreach (wchar_t c, str) + { + if (c == L'\'') + escaped += L'\''; + escaped += c; + } + return escaped + L'\''; + } + + vector StringConverter::Split (const string &str, const string &separators, bool returnEmptyFields) + { + vector elements; + + if (!returnEmptyFields) + { + size_t p = 0; + while ((p = str.find_first_not_of (separators, p)) != string::npos) + { + size_t end = str.find_first_of (separators, p); + if (end == string::npos) + { + elements.push_back (str.substr (p)); + break; + } + + elements.push_back (str.substr (p, end - p)); + p = end; + } + } + else + { + string element; + elements.push_back (element); + foreach (char c, str) + { + if (separators.find (c) != string::npos) + { + element.erase(); + elements.push_back (element); + } + else + { + elements.back() += c; + } + } + } + + return elements; + } + + string StringConverter::StripTrailingNumber (const string &str) + { + size_t start = str.find_last_not_of ("0123456789"); + if (start == string::npos) + return ""; + + return str.substr (0, start + 1); + } + + wstring StringConverter::ToExceptionString (const exception &ex) + { + const SystemException *sysEx = dynamic_cast (&ex); + if (sysEx) + return ToWide (sysEx->what()) + L": " + sysEx->SystemText() + L": " + sysEx->GetSubject(); + + if (ex.what() && !string (ex.what()).empty()) + return ToWide (GetTypeName (typeid (ex)) + ": " + ex.what()); + + return ToWide (GetTypeName (typeid (ex))); + } + + string StringConverter::ToLower (const string &str) + { + string s; + foreach (char c, str) + s += tolower (c, locale()); + return s; + } + + string StringConverter::ToSingle (const wstring &wstr, bool noThrow) + { + string str; + ToSingle (wstr, str, noThrow); + return str; + } + + void StringConverter::ToSingle (const wstring &wstr, string &str, bool noThrow) + { + try + { + mbstate_t mbState; + Memory::Zero (&mbState, sizeof (mbState)); + const wchar_t *src = wstr.c_str(); + + size_t size = wcsrtombs (nullptr, &src, 0, &mbState); + if (size == (size_t) -1) + throw StringConversionFailed (SRC_POS, wstr); + + vector buf (size + 1); + Memory::Zero (&mbState, sizeof (mbState)); + + if ((size = wcsrtombs (&buf[0], &src, buf.size(), &mbState)) == (size_t) -1) + throw StringConversionFailed (SRC_POS, wstr); + + str.clear(); + str.insert (0, &buf.front(), size); + Memory::Erase (&buf.front(), buf.size()); + } + catch (...) + { + if (!noThrow) + throw; + } } - int64 StringConverter::ToInt64 (const string &str) - { - int64 n; - stringstream ss (str); - - ss >> n; - if (ss.fail() || n == 0x7fffFFFFffffFFFFLL || n == -0x7fffFFFFffffFFFFLL) - throw ParameterIncorrect (SRC_POS); - - return n; - } - - int64 StringConverter::ToInt64 (const wstring &str) - { - int64 n; - wstringstream ss (str); - - ss >> n; - if (ss.fail() || n == 0x7fffFFFFffffFFFFLL || n == -0x7fffFFFFffffFFFFLL) - throw ParameterIncorrect (SRC_POS); - - return n; - } - - string StringConverter::ToUpper (const string &str) - { - string s; - foreach (char c, str) - s += toupper (c, locale()); - return s; - } - - wstring StringConverter::ToWide (const string &str, bool noThrow) - { - try - { - mbstate_t mbState; - Memory::Zero (&mbState, sizeof (mbState)); - const char *src = str.c_str(); - - size_t size = mbsrtowcs (nullptr, &src, 0, &mbState); - if (size == (size_t) -1) - throw StringConversionFailed (SRC_POS); - - vector buf (size + 1); - Memory::Zero (&mbState, sizeof (mbState)); - - if ((size = mbsrtowcs (&buf[0], &src, buf.size(), &mbState)) == (size_t) -1) - throw StringConversionFailed (SRC_POS); - - wstring s; - s.insert (s.begin(), buf.begin(), buf.begin() + size); - return s; - } - catch (...) - { - if (noThrow) - return L""; - throw; - } - } - - void StringConverter::ToWideBuffer (const wstring &str, wchar_t *buffer, size_t bufferSize) - { - if (str.length() < 1) - { - buffer[0] = 0; - return; - } - - BufferPtr ( - (byte *) buffer, - bufferSize).CopyFrom ( - ConstBufferPtr ((byte *) (wstring (str).c_str()), - (str.length() + 1) * sizeof (wchar_t) - ) - ); - } - - string StringConverter::Trim (const string &str) - { - size_t start = 0; - size_t end = str.size(); - if (end < 1) - return str; - - foreach (char c, str) - { - if (c > ' ') - break; - ++start; - } - - foreach_reverse (char c, str) - { - if (c > ' ') - break; - --end; - } - - return str.substr (start, end - start); - } -} + uint32 StringConverter::ToUInt32 (const string &str) + { + uint32 n; + stringstream ss (str); + + ss >> n; + if (ss.fail() || n == 0xffffFFFFU) + throw ParameterIncorrect (SRC_POS); + + return n; + } + + uint32 StringConverter::ToUInt32 (const wstring &str) + { + uint32 n; + wstringstream ss (str); + + ss >> n; + if (ss.fail() || n == 0xffffFFFFU) + throw ParameterIncorrect (SRC_POS); + + return n; + } + + int32 StringConverter::ToInt32 (const string &str) + { + int32 n; + stringstream ss (str); + + ss >> n; + if (ss.fail() || n == 0x7fffFFFF || n == -0x7fffFFFF) + throw ParameterIncorrect (SRC_POS); + + return n; + } + + int32 StringConverter::ToInt32 (const wstring &str) + { + int32 n; + wstringstream ss (str); + + ss >> n; + if (ss.fail() || n == 0x7fffFFFF || n == -0x7fffFFFF) + throw ParameterIncorrect (SRC_POS); + + return n; + } + + uint64 StringConverter::ToUInt64 (const string &str) + { + uint64 n; + stringstream ss (str); + + ss >> n; + if (ss.fail() || n == 0xffffFFFFffffFFFFULL) + throw ParameterIncorrect (SRC_POS); + + return n; + } + + uint64 StringConverter::ToUInt64 (const wstring &str) + { + uint64 n; + wstringstream ss (str); + + ss >> n; + if (ss.fail() || n == 0xffffFFFFffffFFFFULL) + throw ParameterIncorrect (SRC_POS); + + return n; + } + + int64 StringConverter::ToInt64 (const string &str) + { + int64 n; + stringstream ss (str); + + ss >> n; + if (ss.fail() || n == 0x7fffFFFFffffFFFFLL || n == -0x7fffFFFFffffFFFFLL) + throw ParameterIncorrect (SRC_POS); + + return n; + } + + int64 StringConverter::ToInt64 (const wstring &str) + { + int64 n; + wstringstream ss (str); + + ss >> n; + if (ss.fail() || n == 0x7fffFFFFffffFFFFLL || n == -0x7fffFFFFffffFFFFLL) + throw ParameterIncorrect (SRC_POS); + + return n; + } + + string StringConverter::ToUpper (const string &str) + { + string s; + foreach (char c, str) + s += toupper (c, locale()); + return s; + } + + wstring StringConverter::ToWide (const string &str, bool noThrow) + { + try + { + mbstate_t mbState; + Memory::Zero (&mbState, sizeof (mbState)); + const char *src = str.c_str(); + + size_t size = mbsrtowcs (nullptr, &src, 0, &mbState); + if (size == (size_t) -1) + throw StringConversionFailed (SRC_POS); + + vector buf (size + 1); + Memory::Zero (&mbState, sizeof (mbState)); + + if ((size = mbsrtowcs (&buf[0], &src, buf.size(), &mbState)) == (size_t) -1) + throw StringConversionFailed (SRC_POS); + + wstring s; + s.insert (s.begin(), buf.begin(), buf.begin() + size); + return s; + } + catch (...) + { + if (noThrow) + return L""; + throw; + } + } + + void StringConverter::ToWideBuffer (const wstring &str, wchar_t *buffer, size_t bufferSize) + { + if (str.length() < 1) + { + buffer[0] = 0; + return; + } + + BufferPtr ( + (byte *) buffer, + bufferSize).CopyFrom ( + ConstBufferPtr ((byte *) (wstring (str).c_str()), + (str.length() + 1) * sizeof (wchar_t) + ) + ); + } + + string StringConverter::Trim (const string &str) + { + size_t start = 0; + size_t end = str.size(); + if (end < 1) + return str; + + foreach (char c, str) + { + if (c > ' ') + break; + ++start; + } + + foreach_reverse (char c, str) + { + if (c > ' ') + break; + --end; + } + + return str.substr (start, end - start); + } +} diff --git a/src/Platform/StringConverter.h b/src/Platform/StringConverter.h index 13d61f53..6c412437 100644 --- a/src/Platform/StringConverter.h +++ b/src/Platform/StringConverter.h @@ -8,61 +8,61 @@ 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_Platform_StringConverter -#define TC_HEADER_Platform_StringConverter - -#include -#include "PlatformBase.h" - -namespace VeraCrypt -{ - class StringConverter - { - public: - static void Erase (string &str); - static void Erase (wstring &str); - static wstring FromNumber (double number); - static wstring FromNumber (int32 number); - static wstring FromNumber (uint32 number); - static wstring FromNumber (int64 number); - static wstring FromNumber (uint64 number); - static string GetTrailingNumber (const string &str); - static string GetTypeName (const type_info &typeInfo); - static wstring QuoteSpaces (const wstring &str); - static vector Split (const string &str, const string &separators = " \t\r\n", bool returnEmptyFields = false); - static string StripTrailingNumber (const string &str); - static wstring ToExceptionString (const exception &ex); - static string ToLower (const string &str); - static uint32 ToUInt32 (const string &str); +*/ + +#ifndef TC_HEADER_Platform_StringConverter +#define TC_HEADER_Platform_StringConverter + +#include +#include "PlatformBase.h" + +namespace VeraCrypt +{ + class StringConverter + { + public: + static void Erase (string &str); + static void Erase (wstring &str); + static wstring FromNumber (double number); + static wstring FromNumber (int32 number); + static wstring FromNumber (uint32 number); + static wstring FromNumber (int64 number); + static wstring FromNumber (uint64 number); + static string GetTrailingNumber (const string &str); + static string GetTypeName (const type_info &typeInfo); + static wstring QuoteSpaces (const wstring &str); + static vector Split (const string &str, const string &separators = " \t\r\n", bool returnEmptyFields = false); + static string StripTrailingNumber (const string &str); + static wstring ToExceptionString (const exception &ex); + static string ToLower (const string &str); + static uint32 ToUInt32 (const string &str); static uint32 ToUInt32 (const wstring &str); - static int32 ToInt32 (const string &str); - static int32 ToInt32 (const wstring &str); - static uint64 ToUInt64 (const string &str); + static int32 ToInt32 (const string &str); + static int32 ToInt32 (const wstring &str); + static uint64 ToUInt64 (const string &str); static uint64 ToUInt64 (const wstring &str); - static int64 ToInt64 (const string &str); - static int64 ToInt64 (const wstring &str); - static string ToSingle (double number) { return ToSingle (FromNumber (number)); } - static string ToSingle (int32 number) { return ToSingle (FromNumber (number)); } - static string ToSingle (uint32 number) { return ToSingle (FromNumber (number)); } - static string ToSingle (int64 number) { return ToSingle (FromNumber (number)); } - static string ToSingle (uint64 number) { return ToSingle (FromNumber (number)); } - static string ToSingle (const wstring &wstr, bool noThrow = false); - static void ToSingle (const wstring &wstr, string &str, bool noThrow = false); - static string ToUpper (const string &str); - static wstring ToWide (double number) { return FromNumber (number); } - static wstring ToWide (int32 number) { return FromNumber (number); } - static wstring ToWide (uint32 number) { return FromNumber (number); } - static wstring ToWide (int64 number) { return FromNumber (number); } - static wstring ToWide (uint64 number) { return FromNumber (number); } - static wstring ToWide (const string &str, bool noThrow = false); - static void ToWideBuffer (const wstring &str, wchar_t *buffer, size_t bufferSize); - static string Trim (const string &str); - - private: - StringConverter (); - }; -} - -#endif // TC_HEADER_Platform_StringConverter + static int64 ToInt64 (const string &str); + static int64 ToInt64 (const wstring &str); + static string ToSingle (double number) { return ToSingle (FromNumber (number)); } + static string ToSingle (int32 number) { return ToSingle (FromNumber (number)); } + static string ToSingle (uint32 number) { return ToSingle (FromNumber (number)); } + static string ToSingle (int64 number) { return ToSingle (FromNumber (number)); } + static string ToSingle (uint64 number) { return ToSingle (FromNumber (number)); } + static string ToSingle (const wstring &wstr, bool noThrow = false); + static void ToSingle (const wstring &wstr, string &str, bool noThrow = false); + static string ToUpper (const string &str); + static wstring ToWide (double number) { return FromNumber (number); } + static wstring ToWide (int32 number) { return FromNumber (number); } + static wstring ToWide (uint32 number) { return FromNumber (number); } + static wstring ToWide (int64 number) { return FromNumber (number); } + static wstring ToWide (uint64 number) { return FromNumber (number); } + static wstring ToWide (const string &str, bool noThrow = false); + static void ToWideBuffer (const wstring &str, wchar_t *buffer, size_t bufferSize); + static string Trim (const string &str); + + private: + StringConverter (); + }; +} + +#endif // TC_HEADER_Platform_StringConverter diff --git a/src/Platform/SyncEvent.h b/src/Platform/SyncEvent.h index cc46e2c8..cea6610c 100644 --- a/src/Platform/SyncEvent.h +++ b/src/Platform/SyncEvent.h @@ -8,44 +8,44 @@ 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_Platform_SyncEvent -#define TC_HEADER_Platform_SyncEvent - -#ifdef TC_WINDOWS -# include "System.h" -#else -# include -#endif -#include "PlatformBase.h" -#include "Mutex.h" - -namespace VeraCrypt -{ - class SyncEvent - { - public: - SyncEvent (); - ~SyncEvent (); - - void Signal (); - void Wait (); - - protected: - bool Initialized; -#ifdef TC_WINDOWS - HANDLE SystemSyncEvent; -#else - volatile bool Signaled; - pthread_cond_t SystemSyncEvent; - Mutex EventMutex; -#endif - - private: - SyncEvent (const SyncEvent &); - SyncEvent &operator= (const SyncEvent &); - }; -} - -#endif // TC_HEADER_Platform_SyncEvent +*/ + +#ifndef TC_HEADER_Platform_SyncEvent +#define TC_HEADER_Platform_SyncEvent + +#ifdef TC_WINDOWS +# include "System.h" +#else +# include +#endif +#include "PlatformBase.h" +#include "Mutex.h" + +namespace VeraCrypt +{ + class SyncEvent + { + public: + SyncEvent (); + ~SyncEvent (); + + void Signal (); + void Wait (); + + protected: + bool Initialized; +#ifdef TC_WINDOWS + HANDLE SystemSyncEvent; +#else + volatile bool Signaled; + pthread_cond_t SystemSyncEvent; + Mutex EventMutex; +#endif + + private: + SyncEvent (const SyncEvent &); + SyncEvent &operator= (const SyncEvent &); + }; +} + +#endif // TC_HEADER_Platform_SyncEvent diff --git a/src/Platform/System.h b/src/Platform/System.h index 7cb79715..85385d85 100644 --- a/src/Platform/System.h +++ b/src/Platform/System.h @@ -8,13 +8,13 @@ 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_Platform_System -#define TC_HEADER_Platform_System - -#ifdef TC_WINDOWS -#include "Windows/System.h" -#endif - -#endif // TC_HEADER_Platform_System +*/ + +#ifndef TC_HEADER_Platform_System +#define TC_HEADER_Platform_System + +#ifdef TC_WINDOWS +#include "Windows/System.h" +#endif + +#endif // TC_HEADER_Platform_System diff --git a/src/Platform/SystemException.h b/src/Platform/SystemException.h index aac5856e..f4e6e9ab 100644 --- a/src/Platform/SystemException.h +++ b/src/Platform/SystemException.h @@ -8,43 +8,43 @@ 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_Platform_SystemException -#define TC_HEADER_Platform_SystemException - -#include "PlatformBase.h" -#include "Exception.h" - -namespace VeraCrypt -{ - class SystemException : public Exception - { - public: - SystemException (); - SystemException (const string &message); - SystemException (const string &message, const string &subject); - SystemException (const string &message, const wstring &subject); - SystemException (const string &message, int64 errorCode) - : Exception (message), ErrorCode (errorCode) { } - virtual ~SystemException () throw () { } - - TC_SERIALIZABLE_EXCEPTION (SystemException); - - int64 GetErrorCode () const { return ErrorCode; } - bool IsError () const; - wstring SystemText () const; - - protected: - int64 ErrorCode; - }; - -#undef TC_EXCEPTION_SET -#define TC_EXCEPTION_SET \ - TC_EXCEPTION_NODECL (SystemException); -} - -#define throw_sys_if(condition) do { if (condition) throw SystemException (SRC_POS); } while (false) -#define throw_sys_sub_if(condition,subject) do { if (condition) throw SystemException (SRC_POS, (subject)); } while (false) - -#endif // TC_HEADER_Platform_SystemException +*/ + +#ifndef TC_HEADER_Platform_SystemException +#define TC_HEADER_Platform_SystemException + +#include "PlatformBase.h" +#include "Exception.h" + +namespace VeraCrypt +{ + class SystemException : public Exception + { + public: + SystemException (); + SystemException (const string &message); + SystemException (const string &message, const string &subject); + SystemException (const string &message, const wstring &subject); + SystemException (const string &message, int64 errorCode) + : Exception (message), ErrorCode (errorCode) { } + virtual ~SystemException () throw () { } + + TC_SERIALIZABLE_EXCEPTION (SystemException); + + int64 GetErrorCode () const { return ErrorCode; } + bool IsError () const; + wstring SystemText () const; + + protected: + int64 ErrorCode; + }; + +#undef TC_EXCEPTION_SET +#define TC_EXCEPTION_SET \ + TC_EXCEPTION_NODECL (SystemException); +} + +#define throw_sys_if(condition) do { if (condition) throw SystemException (SRC_POS); } while (false) +#define throw_sys_sub_if(condition,subject) do { if (condition) throw SystemException (SRC_POS, (subject)); } while (false) + +#endif // TC_HEADER_Platform_SystemException diff --git a/src/Platform/SystemInfo.h b/src/Platform/SystemInfo.h index 88412045..d8b29b77 100644 --- a/src/Platform/SystemInfo.h +++ b/src/Platform/SystemInfo.h @@ -8,25 +8,25 @@ 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_Platform_SystemInfo -#define TC_HEADER_Platform_SystemInfo - -#include "PlatformBase.h" - -namespace VeraCrypt -{ - class SystemInfo - { - public: - static wstring GetPlatformName (); - static vector GetVersion (); - static bool IsVersionAtLeast (int versionNumber1, int versionNumber2, int versionNumber3 = 0); - - protected: - SystemInfo (); - }; -} - -#endif // TC_HEADER_Platform_SystemInfo +*/ + +#ifndef TC_HEADER_Platform_SystemInfo +#define TC_HEADER_Platform_SystemInfo + +#include "PlatformBase.h" + +namespace VeraCrypt +{ + class SystemInfo + { + public: + static wstring GetPlatformName (); + static vector GetVersion (); + static bool IsVersionAtLeast (int versionNumber1, int versionNumber2, int versionNumber3 = 0); + + protected: + SystemInfo (); + }; +} + +#endif // TC_HEADER_Platform_SystemInfo diff --git a/src/Platform/SystemLog.h b/src/Platform/SystemLog.h index 41abc7be..eea7783f 100644 --- a/src/Platform/SystemLog.h +++ b/src/Platform/SystemLog.h @@ -8,39 +8,39 @@ 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_Platform_SystemLog -#define TC_HEADER_Platform_SystemLog - -#include "Platform/PlatformBase.h" -#include "Platform/StringConverter.h" - -namespace VeraCrypt -{ - class SystemLog - { - public: - static void WriteDebug (const string &debugMessage); - static void WriteError (const string &errorMessage); - - static void WriteException (const exception &ex) - { - WriteError (string ("exception: ") + StringConverter::ToSingle (StringConverter::ToExceptionString (ex))); - } - - protected: - SystemLog (); - }; - -#ifdef DEBUG -# define tracelog_point do { stringstream s; s << (SRC_POS); SystemLog::WriteError (s.str()); } while (false) -# define tracelog_msg(stream_args) do { stringstream s; s << (SRC_POS) << ": " << stream_args; SystemLog::WriteError (s.str()); } while (false) -#else -# define tracelog_point -# define tracelog_msg(stream_args) while (false) { stringstream s; s << stream_args; } -#endif - -} - -#endif // TC_HEADER_Platform_SystemLog +*/ + +#ifndef TC_HEADER_Platform_SystemLog +#define TC_HEADER_Platform_SystemLog + +#include "Platform/PlatformBase.h" +#include "Platform/StringConverter.h" + +namespace VeraCrypt +{ + class SystemLog + { + public: + static void WriteDebug (const string &debugMessage); + static void WriteError (const string &errorMessage); + + static void WriteException (const exception &ex) + { + WriteError (string ("exception: ") + StringConverter::ToSingle (StringConverter::ToExceptionString (ex))); + } + + protected: + SystemLog (); + }; + +#ifdef DEBUG +# define tracelog_point do { stringstream s; s << (SRC_POS); SystemLog::WriteError (s.str()); } while (false) +# define tracelog_msg(stream_args) do { stringstream s; s << (SRC_POS) << ": " << stream_args; SystemLog::WriteError (s.str()); } while (false) +#else +# define tracelog_point +# define tracelog_msg(stream_args) while (false) { stringstream s; s << stream_args; } +#endif + +} + +#endif // TC_HEADER_Platform_SystemLog diff --git a/src/Platform/TextReader.cpp b/src/Platform/TextReader.cpp index 91f9ed09..dcb1cd16 100644 --- a/src/Platform/TextReader.cpp +++ b/src/Platform/TextReader.cpp @@ -8,34 +8,34 @@ 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 "TextReader.h" - -namespace VeraCrypt -{ - TextReader::TextReader (const FilePath &path) - { - InputFile.reset (new File); - InputFile->Open (path); - InputStream = shared_ptr (new FileStream (InputFile)); - } - - bool TextReader::ReadLine (string &outputString) - { - outputString.erase(); - - char c; - while (InputStream->Read (BufferPtr ((byte *) &c, sizeof (c))) == sizeof (c)) - { - if (c == '\r') - continue; - - if (c == '\n') - return true; - - outputString += c; - } - return !outputString.empty(); - } -} +*/ + +#include "TextReader.h" + +namespace VeraCrypt +{ + TextReader::TextReader (const FilePath &path) + { + InputFile.reset (new File); + InputFile->Open (path); + InputStream = shared_ptr (new FileStream (InputFile)); + } + + bool TextReader::ReadLine (string &outputString) + { + outputString.erase(); + + char c; + while (InputStream->Read (BufferPtr ((byte *) &c, sizeof (c))) == sizeof (c)) + { + if (c == '\r') + continue; + + if (c == '\n') + return true; + + outputString += c; + } + return !outputString.empty(); + } +} diff --git a/src/Platform/TextReader.h b/src/Platform/TextReader.h index bd866bcd..91006df6 100644 --- a/src/Platform/TextReader.h +++ b/src/Platform/TextReader.h @@ -8,32 +8,32 @@ 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_Platform_TextReader -#define TC_HEADER_Platform_TextReader - -#include "PlatformBase.h" -#include "FileStream.h" -#include "FilesystemPath.h" -#include "SharedPtr.h" -#include "Stream.h" - -namespace VeraCrypt -{ - class TextReader - { - public: - TextReader (const FilePath &path); - TextReader (shared_ptr stream) : InputStream (stream) { } - virtual ~TextReader () { } - - virtual bool ReadLine (string &outputString); - - protected: - shared_ptr InputFile; - shared_ptr InputStream; - }; -} - -#endif // TC_HEADER_Platform_TextReader +*/ + +#ifndef TC_HEADER_Platform_TextReader +#define TC_HEADER_Platform_TextReader + +#include "PlatformBase.h" +#include "FileStream.h" +#include "FilesystemPath.h" +#include "SharedPtr.h" +#include "Stream.h" + +namespace VeraCrypt +{ + class TextReader + { + public: + TextReader (const FilePath &path); + TextReader (shared_ptr stream) : InputStream (stream) { } + virtual ~TextReader () { } + + virtual bool ReadLine (string &outputString); + + protected: + shared_ptr InputFile; + shared_ptr InputStream; + }; +} + +#endif // TC_HEADER_Platform_TextReader diff --git a/src/Platform/Thread.h b/src/Platform/Thread.h index c9f462e1..4ec73e5e 100644 --- a/src/Platform/Thread.h +++ b/src/Platform/Thread.h @@ -8,71 +8,71 @@ 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_Platform_Thread -#define TC_HEADER_Platform_Thread - -#ifdef TC_WINDOWS -# include "System.h" -# define TC_THREAD_PROC DWORD WINAPI -#else -# include -# define TC_THREAD_PROC void* -#endif -#include "PlatformBase.h" -#include "Functor.h" -#include "SharedPtr.h" -#include "SyncEvent.h" - -namespace VeraCrypt -{ - class Thread - { - public: -#ifdef TC_WINDOWS - typedef HANDLE ThreadSystemHandle; - typedef LPTHREAD_START_ROUTINE ThreadProcPtr; -#else - typedef pthread_t ThreadSystemHandle; - typedef void* (*ThreadProcPtr) (void *); -#endif - Thread () { }; - virtual ~Thread () { }; - - void Join () const; - void Start (ThreadProcPtr threadProc, void *parameter = nullptr); - - void Start (Functor *functor) - { - Start (Thread::FunctorEntry, (void *)functor); - } - - static void Sleep (uint32 milliSeconds); - - protected: - static TC_THREAD_PROC FunctorEntry (void *functorArg) - { - Functor *functor = (Functor *) functorArg; - try - { - (*functor) (); - } - catch (...) { } - - delete functor; - return 0; - } - - static const size_t MinThreadStackSize = 1024 * 1024; - - ThreadSystemHandle SystemHandle; - - private: - Thread (const Thread &); - Thread &operator= (const Thread &); - }; - -} - -#endif // TC_HEADER_Platform_Thread +*/ + +#ifndef TC_HEADER_Platform_Thread +#define TC_HEADER_Platform_Thread + +#ifdef TC_WINDOWS +# include "System.h" +# define TC_THREAD_PROC DWORD WINAPI +#else +# include +# define TC_THREAD_PROC void* +#endif +#include "PlatformBase.h" +#include "Functor.h" +#include "SharedPtr.h" +#include "SyncEvent.h" + +namespace VeraCrypt +{ + class Thread + { + public: +#ifdef TC_WINDOWS + typedef HANDLE ThreadSystemHandle; + typedef LPTHREAD_START_ROUTINE ThreadProcPtr; +#else + typedef pthread_t ThreadSystemHandle; + typedef void* (*ThreadProcPtr) (void *); +#endif + Thread () { }; + virtual ~Thread () { }; + + void Join () const; + void Start (ThreadProcPtr threadProc, void *parameter = nullptr); + + void Start (Functor *functor) + { + Start (Thread::FunctorEntry, (void *)functor); + } + + static void Sleep (uint32 milliSeconds); + + protected: + static TC_THREAD_PROC FunctorEntry (void *functorArg) + { + Functor *functor = (Functor *) functorArg; + try + { + (*functor) (); + } + catch (...) { } + + delete functor; + return 0; + } + + static const size_t MinThreadStackSize = 1024 * 1024; + + ThreadSystemHandle SystemHandle; + + private: + Thread (const Thread &); + Thread &operator= (const Thread &); + }; + +} + +#endif // TC_HEADER_Platform_Thread diff --git a/src/Platform/Time.h b/src/Platform/Time.h index 6acd79af..9fade923 100644 --- a/src/Platform/Time.h +++ b/src/Platform/Time.h @@ -8,27 +8,27 @@ 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_Platform_Time -#define TC_HEADER_Platform_Time - -#include "PlatformBase.h" - -namespace VeraCrypt -{ - class Time - { - public: - Time () { } - virtual ~Time () { } - - static uint64 GetCurrent (); // Returns time in hundreds of nanoseconds since 1601/01/01 - - private: - Time (const Time &); - Time &operator= (const Time &); - }; -} - -#endif // TC_HEADER_Platform_Time +*/ + +#ifndef TC_HEADER_Platform_Time +#define TC_HEADER_Platform_Time + +#include "PlatformBase.h" + +namespace VeraCrypt +{ + class Time + { + public: + Time () { } + virtual ~Time () { } + + static uint64 GetCurrent (); // Returns time in hundreds of nanoseconds since 1601/01/01 + + private: + Time (const Time &); + Time &operator= (const Time &); + }; +} + +#endif // TC_HEADER_Platform_Time diff --git a/src/Platform/User.h b/src/Platform/User.h index d53f1c91..34c00527 100644 --- a/src/Platform/User.h +++ b/src/Platform/User.h @@ -8,29 +8,29 @@ 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_Platform_User -#define TC_HEADER_Platform_User - -#include "PlatformBase.h" - -#ifdef TC_UNIX -#include -#include -#endif - -namespace VeraCrypt -{ - struct UserId - { - UserId () { } -#ifdef TC_UNIX - UserId (uid_t systemId) : SystemId (systemId) { } - - uid_t SystemId; -#endif - }; -} - -#endif // TC_HEADER_Platform_User +*/ + +#ifndef TC_HEADER_Platform_User +#define TC_HEADER_Platform_User + +#include "PlatformBase.h" + +#ifdef TC_UNIX +#include +#include +#endif + +namespace VeraCrypt +{ + struct UserId + { + UserId () { } +#ifdef TC_UNIX + UserId (uid_t systemId) : SystemId (systemId) { } + + uid_t SystemId; +#endif + }; +} + +#endif // TC_HEADER_Platform_User diff --git a/src/Readme.txt b/src/Readme.txt index 02864800..faf1683f 100644 --- a/src/Readme.txt +++ b/src/Readme.txt @@ -1,265 +1,265 @@ -This archive contains the source code of VeraCrypt. -It is based on original TrueCrypt 7.1a with security enhancements and modifications. - - -Important -========= - -You may use the source code contained in this archive only if you accept and -agree to the license terms contained in the file 'License.txt', which is -included in this archive. - -Note that the license specifies, for example, that a derived work must not be -called 'TrueCrypt' or 'VeraCrypt' - - - -Contents -======== - -I. Windows - Requirements for Building VeraCrypt for Windows - Instructions for Building VeraCrypt for Windows - Instructions for Signing and Packaging VeraCrypt for Windows - -II. Linux and Mac OS X - Requirements for Building VeraCrypt for Linux and Mac OS X - Instructions for Building VeraCrypt for Linux and Mac OS X - Mac OS X specifics - -III. FreeBSD and OpenSolaris - -IV. Third-Party Developers (Contributors) - -V. Legal Information - -VI. Further Information - - - -I. Windows -========== - -Requirements for Building VeraCrypt for Windows: ------------------------------------------------- - -- Microsoft Visual C++ 2008 SP1 (Professional Edition or compatible) -- Microsoft Visual C++ 1.52 (available from MSDN Subscriber Downloads) -- Microsoft Windows SDK for Windows 7 (configured for Visual C++) -- Microsoft Windows SDK for Windows 8.1 (needed for SHA-256 code signing) -- Microsoft Windows Driver Kit 7.1.0 (build 7600.16385.1) -- RSA Security Inc. PKCS #11 Cryptographic Token Interface (Cryptoki) 2.20 - header files (available at ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-11/v2-20) -- NASM assembler 2.08 or compatible -- gzip compressor -- upx packer (available at http://upx.sourceforge.net/) - -IMPORTANT: - -The 64-bit editions of Windows Vista and later versions of Windows, and in -some cases (e.g. playback of HD DVD content) also the 32-bit editions, do not -allow the VeraCrypt driver to run without an appropriate digital signature. -Therefore, all .sys files in official VeraCrypt binary packages are digitally -signed with the digital certificate of the IDRIX, which was -issued by Thawte certification authority. At the end of each official .exe and -.sys file, there are embedded digital signatures and all related certificates -(i.e. all certificates in the relevant certification chain, such as the -certification authority certificates, CA-MS cross-certificate, and the -IDRIX certificate). -Keep this in mind if you compile VeraCrypt -and compare your binaries with the official binaries. If your binaries are -unsigned, the sizes of the official binaries will usually be approximately -10 KB greater than sizes of your binaries (there may be further differences -if you use a different version of the compiler, or if you install a different -or no service pack for Visual Studio, or different hotfixes for it, or if you -use different versions of the required SDKs). - - -Instructions for Building VeraCrypt for Windows: ------------------------------------------------- - -1) Create an environment variable 'MSVC16_ROOT' pointing to the folder 'MSVC15' - extracted from the Visual C++ 1.52 self-extracting package. - - Note: The 16-bit installer MSVC15\SETUP.EXE cannot be run on 64-bit Windows, - but it is actually not necessary to run it. You only need to extract the - folder 'MSVC15', which contains the 32-bit binaries required to build the - VeraCrypt Boot Loader. - -2) If you have installed the Windows Driver Development Kit in another - directory than '%SYSTEMDRIVE%\WinDDK', create an environment variable - 'WINDDK_ROOT' pointing to the DDK installation directory. - -3) Copy the PKCS #11 header files to a standard include path or create an - environment variable 'PKCS11_INC' pointing to the directory where - the PKCS #11 header files are installed. - -4) Open the solution file 'VeraCrypt.sln' in Microsoft Visual Studio 2008. - -5) Select 'All' as the active solution configuration. - -6) Build the solution. - -7) If successful, there should be newly built VeraCrypt binaries in the - 'Release' folder. - -Instructions for Signing and Packaging VeraCrypt for Windows: -------------------------------------------------------------- - -First, create an environment variable 'WSDK81' pointing to the Windows SDK -for Windows 8.1 installation directory. -The folder "Signing" contains a batch file (sign.bat) that will sign all -VeraCrypt components using a code signing certificate present on the -certificate store and also build the final installation setup. -The batch file suppose that the code signing certificate is issued by Thawt. -This is the case for IDRIX's certificate. If yours is issued by another CA, -then you should put the Root and Intermediate certificates in the "Signing" -folder and then modify sign.bat accordingly. - - -II. Linux and Mac OS X -====================== - -Requirements for Building VeraCrypt for Linux and Mac OS X: ------------------------------------------------------------ - -- GNU Make -- GNU C++ Compiler 4.0 or compatible -- Apple Xcode (Mac OS X only) -- NASM assembler 2.08 or compatible (x86/x64 architecture only) -- pkg-config -- makeself (Linux only) -- wxWidgets 3.0 shared library and header files installed or - wxWidgets 3.0 library source code (available at http://www.wxwidgets.org) -- FUSE library and header files (available at https://github.com/libfuse/libfuse - and https://osxfuse.github.io/) -- RSA Security Inc. PKCS #11 Cryptographic Token Interface (Cryptoki) 2.20 - header files (available at ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-11/v2-20). - They are already included in the source tree under the directory PKCS11 but - it is possible to override it using the environment variable 'PKCS11_INC'. - - -Instructions for Building VeraCrypt for Linux and Mac OS X: ------------------------------------------------------------ - -1) Change the current directory to the root of the VeraCrypt source code. - -2) If you have no wxWidgets shared library installed, run the following - command to configure the wxWidgets static library for VeraCrypt and to - build it: - - $ make WXSTATIC=1 WX_ROOT=/usr/src/wxWidgets wxbuild - - The variable WX_ROOT must point to the location of the source code of the - wxWidgets library. Output files will be placed in the './wxrelease/' - directory. - -3) To build VeraCrypt, run the following command: - - $ make - - or if you have no wxWidgets shared library installed: - - $ make WXSTATIC=1 - -4) If successful, the VeraCrypt executable should be located in the directory - 'Main'. - -By default, a universal executable supporting both graphical and text user -interface (through the switch --text) is built. -On Linux, a console-only executable, which requires no GUI library, can be -built using the 'NOGUI' parameter: - - $ make NOGUI=1 WXSTATIC=1 WX_ROOT=/usr/src/wxWidgets wxbuild - $ make NOGUI=1 WXSTATIC=1 - -On MacOSX, building a console-only executable is not supported. - -Mac OS X specifics: ------------------------------------------------------------ - -Under MacOSX, the SDK for OSX 10.7 is used by default. To use another version -of the SDK (i.e. 10.6), you can export the environment variable VC_OSX_TARGET: - - $ export VC_OSX_TARGET=10.6 - - -Before building under MacOSX, pkg-config must be installed if not yet available. -Get it from http://pkgconfig.freedesktop.org/releases/pkg-config-0.28.tar.gz and -compile using the following commands : - - $ ./configure --with-internal-glib - $ make - $ sudo make install - -After making sure pkg-config is available, download and install OSXFuse from -https://osxfuse.github.io/ (MacFUSE compatibility layer must selected) - -The script build_veracrypt_macosx.sh available under "src/Build" performs the -full build of VeraCrypt including the creation of the installer pkg. It expects -to find the wxWidgets 3.0.2 sources at the same level as where you put -VeraCrypt sources (i.e. if "src" path is "/Users/joe/Projects/VeraCrypt/src" -then wxWidgets should be at "/Users/joe/Projects/wxWidgets-wxWidgets-3.0.2") - -The build process uses Code Signing certificates whose ID is specified in -src/Main/Main.make (lines 167 & 169). You'll have to modify these lines to put -the ID of your Code Signing certificates or comment them if you don't have one. - -Because of incompatibility issues with OSXFUSE, the SDK 10.9 generates a -VeraCrypt binary that has issues communicating with the OSXFUSE kernel extension. -Thus, we recommend to use the SDK 10.8 or earlier for building VeraCrypt. - - - -III. FreeBSD and OpenSolaris -============================ - -FreeBSD and OpenSolaris are not yet supported. - - - -IV. Third-Party Developers (Contributors) -========================================= - -If you intend to implement a feature, please contact us first to make sure: - -1) That the feature has not been implemented (we may have already implemented - it, but haven't released the code yet). -2) That the feature is acceptable. -3) Whether we need help of third-party developers with implementing the feature. - -Information on how to contact us can be found at: -https://veracrypt.codeplex.com/ - - - -V. Legal Information -==================== - -Copyright Information ---------------------- - -This software as a whole: -Copyright (c) 2013-2015 IDRIX. All rights reserved. - -Portions of this software: -Copyright (c) 2003-2012 TrueCrypt Developers Association. All rights reserved. -Copyright (c) 1998-2000 Paul Le Roux. All rights reserved. -Copyright (c) 1998-2008 Brian Gladman, Worcester, UK. All rights reserved. -Copyright (c) 2002-2004 Mark Adler. All rights reserved. -For more information, please see the legal notices attached to parts of the -source code. - -Trademark Information ---------------------- - -Any trademarks contained in the source code, binaries, and/or in the -documentation, are the sole property of their respective owners. - - - -VI. Further Information -======================= - -http://www.veracrypt.fr - +This archive contains the source code of VeraCrypt. +It is based on original TrueCrypt 7.1a with security enhancements and modifications. + + +Important +========= + +You may use the source code contained in this archive only if you accept and +agree to the license terms contained in the file 'License.txt', which is +included in this archive. + +Note that the license specifies, for example, that a derived work must not be +called 'TrueCrypt' or 'VeraCrypt' + + + +Contents +======== + +I. Windows + Requirements for Building VeraCrypt for Windows + Instructions for Building VeraCrypt for Windows + Instructions for Signing and Packaging VeraCrypt for Windows + +II. Linux and Mac OS X + Requirements for Building VeraCrypt for Linux and Mac OS X + Instructions for Building VeraCrypt for Linux and Mac OS X + Mac OS X specifics + +III. FreeBSD and OpenSolaris + +IV. Third-Party Developers (Contributors) + +V. Legal Information + +VI. Further Information + + + +I. Windows +========== + +Requirements for Building VeraCrypt for Windows: +------------------------------------------------ + +- Microsoft Visual C++ 2008 SP1 (Professional Edition or compatible) +- Microsoft Visual C++ 1.52 (available from MSDN Subscriber Downloads) +- Microsoft Windows SDK for Windows 7 (configured for Visual C++) +- Microsoft Windows SDK for Windows 8.1 (needed for SHA-256 code signing) +- Microsoft Windows Driver Kit 7.1.0 (build 7600.16385.1) +- RSA Security Inc. PKCS #11 Cryptographic Token Interface (Cryptoki) 2.20 + header files (available at ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-11/v2-20) +- NASM assembler 2.08 or compatible +- gzip compressor +- upx packer (available at http://upx.sourceforge.net/) + +IMPORTANT: + +The 64-bit editions of Windows Vista and later versions of Windows, and in +some cases (e.g. playback of HD DVD content) also the 32-bit editions, do not +allow the VeraCrypt driver to run without an appropriate digital signature. +Therefore, all .sys files in official VeraCrypt binary packages are digitally +signed with the digital certificate of the IDRIX, which was +issued by Thawte certification authority. At the end of each official .exe and +.sys file, there are embedded digital signatures and all related certificates +(i.e. all certificates in the relevant certification chain, such as the +certification authority certificates, CA-MS cross-certificate, and the +IDRIX certificate). +Keep this in mind if you compile VeraCrypt +and compare your binaries with the official binaries. If your binaries are +unsigned, the sizes of the official binaries will usually be approximately +10 KB greater than sizes of your binaries (there may be further differences +if you use a different version of the compiler, or if you install a different +or no service pack for Visual Studio, or different hotfixes for it, or if you +use different versions of the required SDKs). + + +Instructions for Building VeraCrypt for Windows: +------------------------------------------------ + +1) Create an environment variable 'MSVC16_ROOT' pointing to the folder 'MSVC15' + extracted from the Visual C++ 1.52 self-extracting package. + + Note: The 16-bit installer MSVC15\SETUP.EXE cannot be run on 64-bit Windows, + but it is actually not necessary to run it. You only need to extract the + folder 'MSVC15', which contains the 32-bit binaries required to build the + VeraCrypt Boot Loader. + +2) If you have installed the Windows Driver Development Kit in another + directory than '%SYSTEMDRIVE%\WinDDK', create an environment variable + 'WINDDK_ROOT' pointing to the DDK installation directory. + +3) Copy the PKCS #11 header files to a standard include path or create an + environment variable 'PKCS11_INC' pointing to the directory where + the PKCS #11 header files are installed. + +4) Open the solution file 'VeraCrypt.sln' in Microsoft Visual Studio 2008. + +5) Select 'All' as the active solution configuration. + +6) Build the solution. + +7) If successful, there should be newly built VeraCrypt binaries in the + 'Release' folder. + +Instructions for Signing and Packaging VeraCrypt for Windows: +------------------------------------------------------------- + +First, create an environment variable 'WSDK81' pointing to the Windows SDK +for Windows 8.1 installation directory. +The folder "Signing" contains a batch file (sign.bat) that will sign all +VeraCrypt components using a code signing certificate present on the +certificate store and also build the final installation setup. +The batch file suppose that the code signing certificate is issued by Thawt. +This is the case for IDRIX's certificate. If yours is issued by another CA, +then you should put the Root and Intermediate certificates in the "Signing" +folder and then modify sign.bat accordingly. + + +II. Linux and Mac OS X +====================== + +Requirements for Building VeraCrypt for Linux and Mac OS X: +----------------------------------------------------------- + +- GNU Make +- GNU C++ Compiler 4.0 or compatible +- Apple Xcode (Mac OS X only) +- NASM assembler 2.08 or compatible (x86/x64 architecture only) +- pkg-config +- makeself (Linux only) +- wxWidgets 3.0 shared library and header files installed or + wxWidgets 3.0 library source code (available at http://www.wxwidgets.org) +- FUSE library and header files (available at https://github.com/libfuse/libfuse + and https://osxfuse.github.io/) +- RSA Security Inc. PKCS #11 Cryptographic Token Interface (Cryptoki) 2.20 + header files (available at ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-11/v2-20). + They are already included in the source tree under the directory PKCS11 but + it is possible to override it using the environment variable 'PKCS11_INC'. + + +Instructions for Building VeraCrypt for Linux and Mac OS X: +----------------------------------------------------------- + +1) Change the current directory to the root of the VeraCrypt source code. + +2) If you have no wxWidgets shared library installed, run the following + command to configure the wxWidgets static library for VeraCrypt and to + build it: + + $ make WXSTATIC=1 WX_ROOT=/usr/src/wxWidgets wxbuild + + The variable WX_ROOT must point to the location of the source code of the + wxWidgets library. Output files will be placed in the './wxrelease/' + directory. + +3) To build VeraCrypt, run the following command: + + $ make + + or if you have no wxWidgets shared library installed: + + $ make WXSTATIC=1 + +4) If successful, the VeraCrypt executable should be located in the directory + 'Main'. + +By default, a universal executable supporting both graphical and text user +interface (through the switch --text) is built. +On Linux, a console-only executable, which requires no GUI library, can be +built using the 'NOGUI' parameter: + + $ make NOGUI=1 WXSTATIC=1 WX_ROOT=/usr/src/wxWidgets wxbuild + $ make NOGUI=1 WXSTATIC=1 + +On MacOSX, building a console-only executable is not supported. + +Mac OS X specifics: +----------------------------------------------------------- + +Under MacOSX, the SDK for OSX 10.7 is used by default. To use another version +of the SDK (i.e. 10.6), you can export the environment variable VC_OSX_TARGET: + + $ export VC_OSX_TARGET=10.6 + + +Before building under MacOSX, pkg-config must be installed if not yet available. +Get it from http://pkgconfig.freedesktop.org/releases/pkg-config-0.28.tar.gz and +compile using the following commands : + + $ ./configure --with-internal-glib + $ make + $ sudo make install + +After making sure pkg-config is available, download and install OSXFuse from +https://osxfuse.github.io/ (MacFUSE compatibility layer must selected) + +The script build_veracrypt_macosx.sh available under "src/Build" performs the +full build of VeraCrypt including the creation of the installer pkg. It expects +to find the wxWidgets 3.0.2 sources at the same level as where you put +VeraCrypt sources (i.e. if "src" path is "/Users/joe/Projects/VeraCrypt/src" +then wxWidgets should be at "/Users/joe/Projects/wxWidgets-wxWidgets-3.0.2") + +The build process uses Code Signing certificates whose ID is specified in +src/Main/Main.make (lines 167 & 169). You'll have to modify these lines to put +the ID of your Code Signing certificates or comment them if you don't have one. + +Because of incompatibility issues with OSXFUSE, the SDK 10.9 generates a +VeraCrypt binary that has issues communicating with the OSXFUSE kernel extension. +Thus, we recommend to use the SDK 10.8 or earlier for building VeraCrypt. + + + +III. FreeBSD and OpenSolaris +============================ + +FreeBSD and OpenSolaris are not yet supported. + + + +IV. Third-Party Developers (Contributors) +========================================= + +If you intend to implement a feature, please contact us first to make sure: + +1) That the feature has not been implemented (we may have already implemented + it, but haven't released the code yet). +2) That the feature is acceptable. +3) Whether we need help of third-party developers with implementing the feature. + +Information on how to contact us can be found at: +https://veracrypt.codeplex.com/ + + + +V. Legal Information +==================== + +Copyright Information +--------------------- + +This software as a whole: +Copyright (c) 2013-2015 IDRIX. All rights reserved. + +Portions of this software: +Copyright (c) 2003-2012 TrueCrypt Developers Association. All rights reserved. +Copyright (c) 1998-2000 Paul Le Roux. All rights reserved. +Copyright (c) 1998-2008 Brian Gladman, Worcester, UK. All rights reserved. +Copyright (c) 2002-2004 Mark Adler. All rights reserved. +For more information, please see the legal notices attached to parts of the +source code. + +Trademark Information +--------------------- + +Any trademarks contained in the source code, binaries, and/or in the +documentation, are the sole property of their respective owners. + + + +VI. Further Information +======================= + +http://www.veracrypt.fr + diff --git a/src/Release/Setup Files/LICENSE b/src/Release/Setup Files/LICENSE index 7c96fa48..cacdfb62 100644 --- a/src/Release/Setup Files/LICENSE +++ b/src/Release/Setup Files/LICENSE @@ -1,190 +1,190 @@ - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -Copyright 2013-2015 IDRIX - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +Copyright 2013-2015 IDRIX + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and limitations under the License. \ No newline at end of file diff --git a/src/Release/Setup Files/License.txt b/src/Release/Setup Files/License.txt index c174ef1b..44c0c657 100644 --- a/src/Release/Setup Files/License.txt +++ b/src/Release/Setup Files/License.txt @@ -1,702 +1,702 @@ -VeraCrypt License -Software distributed under this license is distributed on an "AS -IS" BASIS WITHOUT WARRANTIES OF ANY KIND. THE AUTHORS AND -DISTRIBUTORS OF THE SOFTWARE DISCLAIM ANY LIABILITY. ANYONE WHO -USES, COPIES, MODIFIES, OR (RE)DISTRIBUTES ANY PART OF THE -SOFTWARE IS, BY SUCH ACTION(S), ACCEPTING AND AGREEING TO BE -BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT -ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE -SOFTWARE, NOR ANY PART(S) THEREOF. - -VeraCrypt is multi-licensed under Apache License 2.0 and -the TrueCrypt License version 3.0, a verbatim copy of both -licenses can be found below. - -This license does not grant you rights to use any -contributors' name, logo, or trademarks, including IDRIX, -VeraCrypt and all derivative names. -For example, the following names are not allowed: VeraCrypt, -VeraCrypt+, VeraCrypt Professional, iVeraCrypt, etc. Nor any -other names confusingly similar to the name VeraCrypt (e.g., -Vera-Crypt, Vera Crypt, VerKrypt, etc.) -____________________________________________________________ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. -____________________________________________________________ - -TrueCrypt License Version 3.0 - -Software distributed under this license is distributed on an "AS -IS" BASIS WITHOUT WARRANTIES OF ANY KIND. THE AUTHORS AND -DISTRIBUTORS OF THE SOFTWARE DISCLAIM ANY LIABILITY. ANYONE WHO -USES, COPIES, MODIFIES, OR (RE)DISTRIBUTES ANY PART OF THE -SOFTWARE IS, BY SUCH ACTION(S), ACCEPTING AND AGREEING TO BE -BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT -ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE -SOFTWARE, NOR ANY PART(S) THEREOF. - - -I. Definitions - -1. "This Product" means the work (including, but not limited to, -source code, graphics, texts, and accompanying files) made -available under and governed by this version of this license -("License"), as may be indicated by, but is not limited to, -copyright notice(s) attached to or included in the work. - -2. "You" means (and "Your" refers to) an individual or a legal -entity (e.g., a non-profit organization, commercial -organization, government agency, etc.) exercising permissions -granted by this License. - -3. "Modification" means (and "modify" refers to) any alteration -of This Product, including, but not limited to, addition to or -deletion from the substance or structure of This Product, -translation into another language, repackaging, alteration or -removal of any file included with This Product, and addition of -any new files to This Product. - -4. "Your Product" means This Product modified by You, or any -work You derive from (or base on) any part of This Product. In -addition, "Your Product" means any work in which You include any -(modified or unmodified) portion of This Product. However, if -the work in which you include it is an aggregate software -distribution (such as an operating system distribution or a -cover CD-ROM of a magazine) containing multiple separate -products, then the term "Your Product" includes only those -products (in the aggregate software distribution) that use, -include, or depend on a modified or unmodified version of This -Product (and the term "Your Product" does not include the whole -aggregate software distribution). For the purposes of this -License, a product suite consisting of two or more products is -considered a single product (operating system distributions and -cover media of magazines are not considered product suites). - -5. "Distribution" means (and "distribute" refers to), regardless -of means or methods, conveyance, transfer, providing, or making -available of This/Your Product or portions thereof to third -parties (including, but not limited to, making This/Your -Product, or portions thereof, available for download to third -parties, whether or not any third party has downloaded the -product, or any portion thereof, made available for download). - - - -II. Use, Copying, and Distribution of This Product - -1. Provided that You comply with all applicable terms and -conditions of this License, You may make copies of This Product -(unmodified) and distribute copies of This Product (unmodified) -that are not included in another product forming Your Product -(except as permitted under Chapter III). Note: For terms and -conditions for copying and distribution of modified versions of -This Product, see Chapter III. - -2. Provided that You comply with all applicable terms and -conditions of this License, You may use This Product freely (see -also Chapter III) on any number of computers/systems for non- -commercial and/or commercial purposes. - - - -III. Modification, Derivation, and Inclusion in Other Products - -1. If all conditions specified in the following paragraphs in -this Chapter (III) are met (for exceptions, see Section III.2) -and if You comply with all other applicable terms and conditions -of this License, You may modify This Product (thus forming Your -Product), derive new works from This Product or portions thereof -(thus forming Your Product), include This Product or portions -thereof in another product (thus forming Your Product, unless -defined otherwise in Chapter I), and You may use (for non- -commercial and/or commercial purposes), copy, and/or distribute -Your Product. - - a. The name of Your Product (or of Your modified version of - This Product) must not contain the name TrueCrypt (for - example, the following names are not allowed: TrueCrypt, - TrueCrypt+, TrueCrypt Professional, iTrueCrypt, etc.) nor - any other names confusingly similar to the name TrueCrypt - (e.g., True-Crypt, True Crypt, TruKrypt, etc.) - - All occurrences of the name TrueCrypt that could reasonably - be considered to identify Your Product must be removed from - Your Product and from any associated materials. Logo(s) - included in (or attached to) Your Product (and in/to - associated materials) must not incorporate and must not be - confusingly similar to any of the TrueCrypt logos - (including, but not limited to, the non-textual logo - consisting primarily of a key in stylized form) or - portion(s) thereof. All graphics contained in This Product - (logos, icons, etc.) must be removed from Your Product (or - from Your modified version of This Product) and from any - associated materials. - - b. The following phrases must be removed from Your Product - and from any associated materials, except the text of this - License: "A TrueCrypt Foundation Release", "Released by - TrueCrypt Foundation", "This is a TrueCrypt Foundation - release." - - c. Phrase "Based on TrueCrypt, freely available at - http://www.truecrypt.org/" must be displayed by Your Product - (if technically feasible) and contained in its - documentation. Alternatively, if This Product or its portion - You included in Your Product constitutes only a minor - portion of Your Product, phrase "Portions of this product - are based in part on TrueCrypt, freely available at - http://www.truecrypt.org/" may be displayed instead. In each - of the cases mentioned above in this paragraph, - "http://www.truecrypt.org/" must be a hyperlink (if - technically feasible) pointing to http://www.truecrypt.org/ - and You may freely choose the location within the user - interface (if there is any) of Your Product (e.g., an - "About" window, etc.) and the way in which Your Product will - display the respective phrase. - - Your Product (and any associated materials, e.g., the - documentation, the content of the official web site of Your - Product, etc.) must not present any Internet address - containing the domain name truecrypt.org (or any domain name - that forwards to the domain name truecrypt.org) in a manner - that might suggest that it is where information about Your - Product may be obtained or where bugs found in Your Product - may be reported or where support for Your Product may be - available or otherwise attempt to indicate that the domain - name truecrypt.org is associated with Your Product. - - d. The complete source code of Your Product must be freely - and publicly available (for exceptions, see Section III.2) - at least until You cease to distribute Your Product. This - condition can be met in one or both of the following ways: - (i) You include the complete source code of Your Product - with every copy of Your Product that You make and distribute - and You make all such copies of Your Product available to - the general public free of charge, and/or (ii) You include - information (valid and correct at least until You cease to - distribute Your Product) about where the complete source - code of Your Product can be obtained free of charge (e.g., - an Internet address) or for a reasonable reproduction fee - with every copy of Your Product that You make and distribute - and, if there is a web site officially associated with Your - Product, You include the aforementioned information about - the source code on a freely and publicly accessible web - page to which such web site links via an easily viewable - hyperlink (at least until You cease to distribute Your - Product). - - The source code of Your Product must not be deliberately - obfuscated and it must not be in an intermediate form (e.g., - the output of a preprocessor). Source code means the - preferred form in which a programmer would usually modify - the program. - - Portions of the source code of Your Product not contained in - This Product (e.g., portions added by You in creating Your - Product, whether created by You or by third parties) must be - available under license(s) that (however, see also - Subsection III.1.e) allow(s) anyone to modify and derive new - works from the portions of the source code that are not - contained in This Product and to use, copy, and redistribute - such modifications and/or derivative works. The license(s) - must be perpetual, non-exclusive, royalty-free, no-charge, - and worldwide, and must not invalidate, weaken, restrict, - interpret, amend, modify, interfere with or otherwise affect - any part, term, provision, or clause of this License. The - text(s) of the license(s) must be included with every copy - of Your Product that You make and distribute. - - e. You must not change the license terms of This Product in - any way (adding any new terms is considered changing the - license terms even if the original terms are retained), - which means, e.g., that no part of This Product may be put - under another license. You must keep intact all the legal - notices contained in the source code files. You must include - the following items with every copy of Your Product that You - make and distribute: a clear and conspicuous notice stating - that Your Product or portion(s) thereof is/are governed by - this version of the TrueCrypt License, a verbatim copy of - this version of the TrueCrypt License (as contained herein), - a clear and conspicuous notice containing information about - where the included copy of the License can be found, and an - appropriate copyright notice. - - -2. You are not obligated to comply with Subsection III.1.d if -Your Product is not distributed (i.e., Your Product is available -only to You). - - - -IV. Disclaimer of Liability, Disclaimer of Warranty, -Indemnification - -You expressly acknowledge and agree to the following: - -1. IN NO EVENT WILL ANY (CO)AUTHOR OF THIS PRODUCT, OR ANY -APPLICABLE INTELLECTUAL-PROPERTY OWNER, OR ANY OTHER PARTY WHO -MAY COPY AND/OR (RE)DISTRIBUTE THIS PRODUCT OR PORTIONS THEREOF, -AS MAY BE PERMITTED HEREIN, BE LIABLE TO YOU OR TO ANY OTHER -PARTY FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, ANY -DIRECT, INDIRECT, GENERAL, SPECIAL, INCIDENTAL, PUNITIVE, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, CORRUPTION OR LOSS OF DATA, ANY LOSSES SUSTAINED BY YOU OR -THIRD PARTIES, A FAILURE OF THIS PRODUCT TO OPERATE WITH ANY -OTHER PRODUCT, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR -BUSINESS INTERRUPTION), WHETHER IN CONTRACT, STRICT LIABILITY, -TORT (INCLUDING, BUT NOT LIMITED TO, NEGLIGENCE) OR OTHERWISE, -ARISING OUT OF THE USE, COPYING, MODIFICATION, OR -(RE)DISTRIBUTION OF THIS PRODUCT (OR A PORTION THEREOF) OR OF -YOUR PRODUCT (OR A PORTION THEREOF), OR INABILITY TO USE THIS -PRODUCT (OR A PORTION THEREOF), EVEN IF SUCH DAMAGES (OR THE -POSSIBILITY OF SUCH DAMAGES) ARE/WERE PREDICTABLE OR KNOWN TO -ANY (CO)AUTHOR, INTELLECTUAL-PROPERTY OWNER, OR ANY OTHER PARTY. - -2. THIS PRODUCT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY -KIND, WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT -LIMITED TO, THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE ENTIRE RISK AS TO -THE QUALITY AND PERFORMANCE OF THIS PRODUCT IS WITH YOU. SHOULD -THIS PRODUCT PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL -NECESSARY SERVICING, REPAIR, OR CORRECTION. - -3. THIS PRODUCT MAY INCORPORATE IMPLEMENTATIONS OF CRYPTOGRAPHIC -ALGORITHMS THAT ARE REGULATED (E.G., SUBJECT TO EXPORT/IMPORT -CONTROL REGULATIONS) OR ILLEGAL IN SOME COUNTRIES. IT IS SOLELY -YOUR RESPONSIBILITY TO VERIFY THAT IT IS LEGAL TO IMPORT AND/OR -(RE)EXPORT AND/OR USE THIS PRODUCT (OR PORTIONS THEREOF) IN -COUNTRIES WHERE YOU INTEND TO USE IT AND/OR TO WHICH YOU INTEND -TO IMPORT IT AND/OR FROM WHICH YOU INTEND TO EXPORT IT, AND IT -IS SOLELY YOUR RESPONSIBILITY TO COMPLY WITH ANY APPLICABLE -REGULATIONS, RESTRICTIONS, AND LAWS. - -4. YOU SHALL INDEMNIFY, DEFEND AND HOLD ALL (CO)AUTHORS OF THIS -PRODUCT, AND APPLICABLE INTELLECTUAL-PROPERTY OWNERS, HARMLESS -FROM AND AGAINST ANY AND ALL LIABILITY, DAMAGES, LOSSES, -SETTLEMENTS, PENALTIES, FINES, COSTS, EXPENSES (INCLUDING -REASONABLE ATTORNEYS' FEES), DEMANDS, CAUSES OF ACTION, CLAIMS, -ACTIONS, PROCEEDINGS, AND SUITS, DIRECTLY RELATED TO OR ARISING -OUT OF YOUR USE, INABILITY TO USE, COPYING, (RE)DISTRIBUTION, -IMPORT AND/OR (RE)EXPORT OF THIS PRODUCT (OR PORTIONS THEREOF) -AND/OR YOUR BREACH OF ANY TERM OF THIS LICENSE. - - - -V. Trademarks - -This License does not grant permission to use trademarks -associated with (or applying to) This Product, except for fair -use as defined by applicable law and except for use expressly -permitted or required by this License. Any attempt otherwise to -use trademarks associated with (or applying to) This Product -automatically and immediately terminates Your rights under This -License and may constitute trademark infringement (which may be -prosecuted). - - - -VI. General Terms and Conditions, Miscellaneous Provisions - -1. ANYONE WHO USES AND/OR COPIES AND/OR MODIFIES AND/OR CREATES -DERIVATIVE WORKS OF AND/OR (RE)DISTRIBUTES THIS PRODUCT, OR ANY -PORTION(S) THEREOF, IS, BY SUCH ACTION(S), AGREEING TO BE BOUND -BY AND ACCEPTING ALL TERMS AND CONDITIONS OF THIS LICENSE (AND -THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS LICENSE). -IF YOU DO NOT ACCEPT (AND AGREE TO BE BOUND BY) ALL TERMS AND -CONDITIONS OF THIS LICENSE, DO NOT USE, COPY, MODIFY, CREATE -DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY -PORTION(S) THEREOF. - -2. YOU MAY NOT USE, MODIFY, COPY, CREATE DERIVATIVE WORKS OF, -(RE)DISTRIBUTE, OR SUBLICENSE THIS PRODUCT, OR PORTION(S) -THEREOF, EXCEPT AS EXPRESSLY PROVIDED IN THIS LICENSE (EVEN IF -APPLICABLE LAW GIVES YOU MORE RIGHTS). ANY ATTEMPT (EVEN IF -PERMITTED BY APPLICABLE LAW) OTHERWISE TO USE, MODIFY, COPY, -CREATE DERIVATIVE WORKS OF, (RE)DISTRIBUTE, OR SUBLICENSE THIS -PRODUCT, OR PORTION(S) THEREOF, AUTOMATICALLY AND IMMEDIATELY -TERMINATES YOUR RIGHTS UNDER THIS LICENSE AND CAN CONSTITUTE -COPYRIGHT INFRINGEMENT (WHICH MAY BE PROSECUTED). ANY CONDITIONS -AND RESTRICTIONS CONTAINED IN THIS LICENSE ARE ALSO LIMITATIONS -ON THE SCOPE OF THIS LICENSE AND ALSO DEFINE THE SCOPE OF YOUR -RIGHTS UNDER THIS LICENSE. YOUR FAILURE TO COMPLY WITH THE TERMS -AND CONDITIONS OF THIS LICENSE OR FAILURE TO PERFORM ANY -APPLICABLE OBLIGATION IMPOSED BY THIS LICENSE AUTOMATICALLY AND -IMMEDIATELY TERMINATES YOUR RIGHTS UNDER THIS LICENSE AND CAN -CAUSE OR BE CONSIDERED COPYRIGHT INFRINGEMENT (WHICH MAY BE -PROSECUTED). NOTHING IN THIS LICENSE SHALL IMPLY OR BE CONSTRUED -AS A PROMISE, OBLIGATION, OR COVENANT NOT TO SUE FOR COPYRIGHT -OR TRADEMARK INFRINGEMENT IF YOU DO NOT COMPLY WITH THE TERMS -AND CONDITIONS OF THIS LICENSE. - -3. This License does not constitute or imply a waiver of any -intellectual property rights except as may be otherwise -expressly provided in this License. This License does not -transfer, assign, or convey any intellectual property rights -(e.g., it does not transfer ownership of copyrights or -trademarks). - -4. Subject to the terms and conditions of this License, You may -allow a third party to use Your copy of This Product (or a copy -that You make and distribute, or Your Product) provided that the -third party explicitly accepts and agrees to be bound by all -terms and conditions of this License and the third party is not -prohibited from using This Product (or portions thereof) by this -License (see, e.g., Section VI.7) or by applicable law. However, -You are not obligated to ensure that the third party accepts -(and agrees to be bound by all terms of) this License if You -distribute only the self-extracting package (containing This -Product) that does not allow the user to install (nor extract) -the files contained in the package until he or she accepts and -agrees to be bound by all terms and conditions of this License. - -5. Without specific prior written permission from the authors of -This Product (or from their common representative), You must not -use the name of This Product, the names of the authors of This -Product, or the names of the legal entities (or informal groups) -of which the authors were/are members/employees, to endorse or -promote Your Product or any work in which You include a modified -or unmodified version of This Product, or to endorse or promote -You or Your affiliates, or in a way that might suggest that Your -Product (or any work in which You include a modified or -unmodified version of This Product), You, or Your affiliates -is/are endorsed by one or more authors of This Product, or in a -way that might suggest that one or more authors of This Product -is/are affiliated with You (or Your affiliates) or directly -participated in the creation of Your Product or of any work in -which You include a modified or unmodified version of This -Product. - -6. IF YOU ARE NOT SURE WHETHER YOU UNDERSTAND ALL PARTS OF THIS -LICENSE OR IF YOU ARE NOT SURE WHETHER YOU CAN COMPLY WITH ALL -TERMS AND CONDITIONS OF THIS LICENSE, YOU MUST NOT USE, COPY, -MODIFY, CREATE DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS -PRODUCT, NOR ANY PORTION(S) OF IT. YOU SHOULD CONSULT WITH A -LAWYER. - -7. IF (IN RELEVANT CONTEXT) ANY PROVISION OF CHAPTER IV OF THIS -LICENSE IS UNENFORCEABLE, INVALID, OR PROHIBITED UNDER -APPLICABLE LAW IN YOUR JURISDICTION, YOU HAVE NO RIGHTS UNDER -THIS LICENSE AND YOU MUST NOT USE, COPY, MODIFY, CREATE -DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY -PORTION(S) THEREOF. - -8. Except as otherwise provided in this License, if any -provision of this License, or a portion thereof, is found to be -invalid or unenforceable under applicable law, it shall not -affect the validity or enforceability of the remainder of this -License, and such invalid or unenforceable provision shall be -construed to reflect the original intent of the provision and -shall be enforced to the maximum extent permitted by applicable -law so as to effect the original intent of the provision as -closely as possible. - -____________________________________________________________ - - -Third-Party Licenses - -This Product contains components that were created by third -parties and that are governed by third-party licenses, which are -contained hereinafter (separated by lines consisting of -underscores). Each of the third-party licenses applies only to -(portions of) the source code file(s) in which the third-party -license is contained or in which it is explicitly referenced, -and to compiled or otherwise processed forms of such source -code. None of the third-party licenses applies to This Product -as a whole, even when it uses terms such as "product", -"program", or any other equivalent terms/phrases. This Product -as a whole is governed by the TrueCrypt License (see above). -Some of the third-party components have been modified by the -authors of This Product. Unless otherwise stated, such -modifications and additions are governed by the TrueCrypt -License (see above). Note: Unless otherwise stated, graphics and -files that are not part of the source code are governed by the -TrueCrypt License. - -____________________________________________________________ - -License agreement for Encryption for the Masses. - -Copyright (C) 1998-2000 Paul Le Roux. All Rights Reserved. - -This product can be copied and distributed free of charge, -including source code. - -You may modify this product and source code, and distribute such -modifications, and you may derive new works based on this -product, provided that: - -1. Any product which is simply derived from this product cannot -be called E4M, or Encryption for the Masses. - -2. If you use any of the source code in your product, and your -product is distributed with source code, you must include this -notice with those portions of this source code that you use. - -Or, - -If your product is distributed in binary form only, you must -display on any packaging, and marketing materials which -reference your product, a notice which states: - -"This product uses components written by Paul Le Roux -" - -3. If you use any of the source code originally by Eric Young, -you must in addition follow his terms and conditions. - -4. Nothing requires that you accept this License, as you have -not signed it. However, nothing else grants you permission to -modify or distribute the product or its derivative works. - -These actions are prohibited by law if you do not accept this -License. - -5. If any of these license terms is found to be to broad in -scope, and declared invalid by any court or legal process, you -agree that all other terms shall not be so affected, and shall -remain valid and enforceable. - -6. THIS PROGRAM IS DISTRIBUTED FREE OF CHARGE, THEREFORE THERE -IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. UNLESS OTHERWISE STATED THE PROGRAM IS PROVIDED -"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR -IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE -ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS -WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE -COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -7. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY -MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE -LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, -INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR -INABILITY TO USE THE PROGRAM, INCLUDING BUT NOT LIMITED TO LOSS -OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH -ANY OTHER PROGRAMS, EVEN IF SUCH HOLDER OR OTHER PARTY HAD -PREVIOUSLY BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. -____________________________________________________________ - -Copyright (c) 1998-2008, Brian Gladman, Worcester, UK. -All rights reserved. - -LICENSE TERMS - -The free distribution and use of this software is allowed (with -or without changes) provided that: - - 1. source code distributions include the above copyright - notice, this list of conditions and the following - disclaimer; - - 2. binary distributions include the above copyright notice, - this list of conditions and the following disclaimer in - their documentation; - - 3. the name of the copyright holder is not used to endorse - products built using this software without specific written - permission. - -DISCLAIMER - -This software is provided 'as is' with no explicit or implied -warranties in respect of its properties, including, but not -limited to, correctness and/or fitness for purpose. -____________________________________________________________ - -Copyright (C) 2002-2004 Mark Adler, all rights reserved -version 1.8, 9 Jan 2004 - -This software is provided 'as-is', without any express or -implied warranty. In no event will the author be held liable -for any damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you - must not claim that you wrote the original software. If you - use this software in a product, an acknowledgment in the - product documentation would be appreciated but is not - required. -2. Altered source versions must be plainly marked as such, and - must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source - distribution. -____________________________________________________________ +VeraCrypt License +Software distributed under this license is distributed on an "AS +IS" BASIS WITHOUT WARRANTIES OF ANY KIND. THE AUTHORS AND +DISTRIBUTORS OF THE SOFTWARE DISCLAIM ANY LIABILITY. ANYONE WHO +USES, COPIES, MODIFIES, OR (RE)DISTRIBUTES ANY PART OF THE +SOFTWARE IS, BY SUCH ACTION(S), ACCEPTING AND AGREEING TO BE +BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT +ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE +SOFTWARE, NOR ANY PART(S) THEREOF. + +VeraCrypt is multi-licensed under Apache License 2.0 and +the TrueCrypt License version 3.0, a verbatim copy of both +licenses can be found below. + +This license does not grant you rights to use any +contributors' name, logo, or trademarks, including IDRIX, +VeraCrypt and all derivative names. +For example, the following names are not allowed: VeraCrypt, +VeraCrypt+, VeraCrypt Professional, iVeraCrypt, etc. Nor any +other names confusingly similar to the name VeraCrypt (e.g., +Vera-Crypt, Vera Crypt, VerKrypt, etc.) +____________________________________________________________ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. +____________________________________________________________ + +TrueCrypt License Version 3.0 + +Software distributed under this license is distributed on an "AS +IS" BASIS WITHOUT WARRANTIES OF ANY KIND. THE AUTHORS AND +DISTRIBUTORS OF THE SOFTWARE DISCLAIM ANY LIABILITY. ANYONE WHO +USES, COPIES, MODIFIES, OR (RE)DISTRIBUTES ANY PART OF THE +SOFTWARE IS, BY SUCH ACTION(S), ACCEPTING AND AGREEING TO BE +BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT +ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE +SOFTWARE, NOR ANY PART(S) THEREOF. + + +I. Definitions + +1. "This Product" means the work (including, but not limited to, +source code, graphics, texts, and accompanying files) made +available under and governed by this version of this license +("License"), as may be indicated by, but is not limited to, +copyright notice(s) attached to or included in the work. + +2. "You" means (and "Your" refers to) an individual or a legal +entity (e.g., a non-profit organization, commercial +organization, government agency, etc.) exercising permissions +granted by this License. + +3. "Modification" means (and "modify" refers to) any alteration +of This Product, including, but not limited to, addition to or +deletion from the substance or structure of This Product, +translation into another language, repackaging, alteration or +removal of any file included with This Product, and addition of +any new files to This Product. + +4. "Your Product" means This Product modified by You, or any +work You derive from (or base on) any part of This Product. In +addition, "Your Product" means any work in which You include any +(modified or unmodified) portion of This Product. However, if +the work in which you include it is an aggregate software +distribution (such as an operating system distribution or a +cover CD-ROM of a magazine) containing multiple separate +products, then the term "Your Product" includes only those +products (in the aggregate software distribution) that use, +include, or depend on a modified or unmodified version of This +Product (and the term "Your Product" does not include the whole +aggregate software distribution). For the purposes of this +License, a product suite consisting of two or more products is +considered a single product (operating system distributions and +cover media of magazines are not considered product suites). + +5. "Distribution" means (and "distribute" refers to), regardless +of means or methods, conveyance, transfer, providing, or making +available of This/Your Product or portions thereof to third +parties (including, but not limited to, making This/Your +Product, or portions thereof, available for download to third +parties, whether or not any third party has downloaded the +product, or any portion thereof, made available for download). + + + +II. Use, Copying, and Distribution of This Product + +1. Provided that You comply with all applicable terms and +conditions of this License, You may make copies of This Product +(unmodified) and distribute copies of This Product (unmodified) +that are not included in another product forming Your Product +(except as permitted under Chapter III). Note: For terms and +conditions for copying and distribution of modified versions of +This Product, see Chapter III. + +2. Provided that You comply with all applicable terms and +conditions of this License, You may use This Product freely (see +also Chapter III) on any number of computers/systems for non- +commercial and/or commercial purposes. + + + +III. Modification, Derivation, and Inclusion in Other Products + +1. If all conditions specified in the following paragraphs in +this Chapter (III) are met (for exceptions, see Section III.2) +and if You comply with all other applicable terms and conditions +of this License, You may modify This Product (thus forming Your +Product), derive new works from This Product or portions thereof +(thus forming Your Product), include This Product or portions +thereof in another product (thus forming Your Product, unless +defined otherwise in Chapter I), and You may use (for non- +commercial and/or commercial purposes), copy, and/or distribute +Your Product. + + a. The name of Your Product (or of Your modified version of + This Product) must not contain the name TrueCrypt (for + example, the following names are not allowed: TrueCrypt, + TrueCrypt+, TrueCrypt Professional, iTrueCrypt, etc.) nor + any other names confusingly similar to the name TrueCrypt + (e.g., True-Crypt, True Crypt, TruKrypt, etc.) + + All occurrences of the name TrueCrypt that could reasonably + be considered to identify Your Product must be removed from + Your Product and from any associated materials. Logo(s) + included in (or attached to) Your Product (and in/to + associated materials) must not incorporate and must not be + confusingly similar to any of the TrueCrypt logos + (including, but not limited to, the non-textual logo + consisting primarily of a key in stylized form) or + portion(s) thereof. All graphics contained in This Product + (logos, icons, etc.) must be removed from Your Product (or + from Your modified version of This Product) and from any + associated materials. + + b. The following phrases must be removed from Your Product + and from any associated materials, except the text of this + License: "A TrueCrypt Foundation Release", "Released by + TrueCrypt Foundation", "This is a TrueCrypt Foundation + release." + + c. Phrase "Based on TrueCrypt, freely available at + http://www.truecrypt.org/" must be displayed by Your Product + (if technically feasible) and contained in its + documentation. Alternatively, if This Product or its portion + You included in Your Product constitutes only a minor + portion of Your Product, phrase "Portions of this product + are based in part on TrueCrypt, freely available at + http://www.truecrypt.org/" may be displayed instead. In each + of the cases mentioned above in this paragraph, + "http://www.truecrypt.org/" must be a hyperlink (if + technically feasible) pointing to http://www.truecrypt.org/ + and You may freely choose the location within the user + interface (if there is any) of Your Product (e.g., an + "About" window, etc.) and the way in which Your Product will + display the respective phrase. + + Your Product (and any associated materials, e.g., the + documentation, the content of the official web site of Your + Product, etc.) must not present any Internet address + containing the domain name truecrypt.org (or any domain name + that forwards to the domain name truecrypt.org) in a manner + that might suggest that it is where information about Your + Product may be obtained or where bugs found in Your Product + may be reported or where support for Your Product may be + available or otherwise attempt to indicate that the domain + name truecrypt.org is associated with Your Product. + + d. The complete source code of Your Product must be freely + and publicly available (for exceptions, see Section III.2) + at least until You cease to distribute Your Product. This + condition can be met in one or both of the following ways: + (i) You include the complete source code of Your Product + with every copy of Your Product that You make and distribute + and You make all such copies of Your Product available to + the general public free of charge, and/or (ii) You include + information (valid and correct at least until You cease to + distribute Your Product) about where the complete source + code of Your Product can be obtained free of charge (e.g., + an Internet address) or for a reasonable reproduction fee + with every copy of Your Product that You make and distribute + and, if there is a web site officially associated with Your + Product, You include the aforementioned information about + the source code on a freely and publicly accessible web + page to which such web site links via an easily viewable + hyperlink (at least until You cease to distribute Your + Product). + + The source code of Your Product must not be deliberately + obfuscated and it must not be in an intermediate form (e.g., + the output of a preprocessor). Source code means the + preferred form in which a programmer would usually modify + the program. + + Portions of the source code of Your Product not contained in + This Product (e.g., portions added by You in creating Your + Product, whether created by You or by third parties) must be + available under license(s) that (however, see also + Subsection III.1.e) allow(s) anyone to modify and derive new + works from the portions of the source code that are not + contained in This Product and to use, copy, and redistribute + such modifications and/or derivative works. The license(s) + must be perpetual, non-exclusive, royalty-free, no-charge, + and worldwide, and must not invalidate, weaken, restrict, + interpret, amend, modify, interfere with or otherwise affect + any part, term, provision, or clause of this License. The + text(s) of the license(s) must be included with every copy + of Your Product that You make and distribute. + + e. You must not change the license terms of This Product in + any way (adding any new terms is considered changing the + license terms even if the original terms are retained), + which means, e.g., that no part of This Product may be put + under another license. You must keep intact all the legal + notices contained in the source code files. You must include + the following items with every copy of Your Product that You + make and distribute: a clear and conspicuous notice stating + that Your Product or portion(s) thereof is/are governed by + this version of the TrueCrypt License, a verbatim copy of + this version of the TrueCrypt License (as contained herein), + a clear and conspicuous notice containing information about + where the included copy of the License can be found, and an + appropriate copyright notice. + + +2. You are not obligated to comply with Subsection III.1.d if +Your Product is not distributed (i.e., Your Product is available +only to You). + + + +IV. Disclaimer of Liability, Disclaimer of Warranty, +Indemnification + +You expressly acknowledge and agree to the following: + +1. IN NO EVENT WILL ANY (CO)AUTHOR OF THIS PRODUCT, OR ANY +APPLICABLE INTELLECTUAL-PROPERTY OWNER, OR ANY OTHER PARTY WHO +MAY COPY AND/OR (RE)DISTRIBUTE THIS PRODUCT OR PORTIONS THEREOF, +AS MAY BE PERMITTED HEREIN, BE LIABLE TO YOU OR TO ANY OTHER +PARTY FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, ANY +DIRECT, INDIRECT, GENERAL, SPECIAL, INCIDENTAL, PUNITIVE, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, CORRUPTION OR LOSS OF DATA, ANY LOSSES SUSTAINED BY YOU OR +THIRD PARTIES, A FAILURE OF THIS PRODUCT TO OPERATE WITH ANY +OTHER PRODUCT, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR +BUSINESS INTERRUPTION), WHETHER IN CONTRACT, STRICT LIABILITY, +TORT (INCLUDING, BUT NOT LIMITED TO, NEGLIGENCE) OR OTHERWISE, +ARISING OUT OF THE USE, COPYING, MODIFICATION, OR +(RE)DISTRIBUTION OF THIS PRODUCT (OR A PORTION THEREOF) OR OF +YOUR PRODUCT (OR A PORTION THEREOF), OR INABILITY TO USE THIS +PRODUCT (OR A PORTION THEREOF), EVEN IF SUCH DAMAGES (OR THE +POSSIBILITY OF SUCH DAMAGES) ARE/WERE PREDICTABLE OR KNOWN TO +ANY (CO)AUTHOR, INTELLECTUAL-PROPERTY OWNER, OR ANY OTHER PARTY. + +2. THIS PRODUCT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY +KIND, WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT +LIMITED TO, THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE ENTIRE RISK AS TO +THE QUALITY AND PERFORMANCE OF THIS PRODUCT IS WITH YOU. SHOULD +THIS PRODUCT PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL +NECESSARY SERVICING, REPAIR, OR CORRECTION. + +3. THIS PRODUCT MAY INCORPORATE IMPLEMENTATIONS OF CRYPTOGRAPHIC +ALGORITHMS THAT ARE REGULATED (E.G., SUBJECT TO EXPORT/IMPORT +CONTROL REGULATIONS) OR ILLEGAL IN SOME COUNTRIES. IT IS SOLELY +YOUR RESPONSIBILITY TO VERIFY THAT IT IS LEGAL TO IMPORT AND/OR +(RE)EXPORT AND/OR USE THIS PRODUCT (OR PORTIONS THEREOF) IN +COUNTRIES WHERE YOU INTEND TO USE IT AND/OR TO WHICH YOU INTEND +TO IMPORT IT AND/OR FROM WHICH YOU INTEND TO EXPORT IT, AND IT +IS SOLELY YOUR RESPONSIBILITY TO COMPLY WITH ANY APPLICABLE +REGULATIONS, RESTRICTIONS, AND LAWS. + +4. YOU SHALL INDEMNIFY, DEFEND AND HOLD ALL (CO)AUTHORS OF THIS +PRODUCT, AND APPLICABLE INTELLECTUAL-PROPERTY OWNERS, HARMLESS +FROM AND AGAINST ANY AND ALL LIABILITY, DAMAGES, LOSSES, +SETTLEMENTS, PENALTIES, FINES, COSTS, EXPENSES (INCLUDING +REASONABLE ATTORNEYS' FEES), DEMANDS, CAUSES OF ACTION, CLAIMS, +ACTIONS, PROCEEDINGS, AND SUITS, DIRECTLY RELATED TO OR ARISING +OUT OF YOUR USE, INABILITY TO USE, COPYING, (RE)DISTRIBUTION, +IMPORT AND/OR (RE)EXPORT OF THIS PRODUCT (OR PORTIONS THEREOF) +AND/OR YOUR BREACH OF ANY TERM OF THIS LICENSE. + + + +V. Trademarks + +This License does not grant permission to use trademarks +associated with (or applying to) This Product, except for fair +use as defined by applicable law and except for use expressly +permitted or required by this License. Any attempt otherwise to +use trademarks associated with (or applying to) This Product +automatically and immediately terminates Your rights under This +License and may constitute trademark infringement (which may be +prosecuted). + + + +VI. General Terms and Conditions, Miscellaneous Provisions + +1. ANYONE WHO USES AND/OR COPIES AND/OR MODIFIES AND/OR CREATES +DERIVATIVE WORKS OF AND/OR (RE)DISTRIBUTES THIS PRODUCT, OR ANY +PORTION(S) THEREOF, IS, BY SUCH ACTION(S), AGREEING TO BE BOUND +BY AND ACCEPTING ALL TERMS AND CONDITIONS OF THIS LICENSE (AND +THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS LICENSE). +IF YOU DO NOT ACCEPT (AND AGREE TO BE BOUND BY) ALL TERMS AND +CONDITIONS OF THIS LICENSE, DO NOT USE, COPY, MODIFY, CREATE +DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY +PORTION(S) THEREOF. + +2. YOU MAY NOT USE, MODIFY, COPY, CREATE DERIVATIVE WORKS OF, +(RE)DISTRIBUTE, OR SUBLICENSE THIS PRODUCT, OR PORTION(S) +THEREOF, EXCEPT AS EXPRESSLY PROVIDED IN THIS LICENSE (EVEN IF +APPLICABLE LAW GIVES YOU MORE RIGHTS). ANY ATTEMPT (EVEN IF +PERMITTED BY APPLICABLE LAW) OTHERWISE TO USE, MODIFY, COPY, +CREATE DERIVATIVE WORKS OF, (RE)DISTRIBUTE, OR SUBLICENSE THIS +PRODUCT, OR PORTION(S) THEREOF, AUTOMATICALLY AND IMMEDIATELY +TERMINATES YOUR RIGHTS UNDER THIS LICENSE AND CAN CONSTITUTE +COPYRIGHT INFRINGEMENT (WHICH MAY BE PROSECUTED). ANY CONDITIONS +AND RESTRICTIONS CONTAINED IN THIS LICENSE ARE ALSO LIMITATIONS +ON THE SCOPE OF THIS LICENSE AND ALSO DEFINE THE SCOPE OF YOUR +RIGHTS UNDER THIS LICENSE. YOUR FAILURE TO COMPLY WITH THE TERMS +AND CONDITIONS OF THIS LICENSE OR FAILURE TO PERFORM ANY +APPLICABLE OBLIGATION IMPOSED BY THIS LICENSE AUTOMATICALLY AND +IMMEDIATELY TERMINATES YOUR RIGHTS UNDER THIS LICENSE AND CAN +CAUSE OR BE CONSIDERED COPYRIGHT INFRINGEMENT (WHICH MAY BE +PROSECUTED). NOTHING IN THIS LICENSE SHALL IMPLY OR BE CONSTRUED +AS A PROMISE, OBLIGATION, OR COVENANT NOT TO SUE FOR COPYRIGHT +OR TRADEMARK INFRINGEMENT IF YOU DO NOT COMPLY WITH THE TERMS +AND CONDITIONS OF THIS LICENSE. + +3. This License does not constitute or imply a waiver of any +intellectual property rights except as may be otherwise +expressly provided in this License. This License does not +transfer, assign, or convey any intellectual property rights +(e.g., it does not transfer ownership of copyrights or +trademarks). + +4. Subject to the terms and conditions of this License, You may +allow a third party to use Your copy of This Product (or a copy +that You make and distribute, or Your Product) provided that the +third party explicitly accepts and agrees to be bound by all +terms and conditions of this License and the third party is not +prohibited from using This Product (or portions thereof) by this +License (see, e.g., Section VI.7) or by applicable law. However, +You are not obligated to ensure that the third party accepts +(and agrees to be bound by all terms of) this License if You +distribute only the self-extracting package (containing This +Product) that does not allow the user to install (nor extract) +the files contained in the package until he or she accepts and +agrees to be bound by all terms and conditions of this License. + +5. Without specific prior written permission from the authors of +This Product (or from their common representative), You must not +use the name of This Product, the names of the authors of This +Product, or the names of the legal entities (or informal groups) +of which the authors were/are members/employees, to endorse or +promote Your Product or any work in which You include a modified +or unmodified version of This Product, or to endorse or promote +You or Your affiliates, or in a way that might suggest that Your +Product (or any work in which You include a modified or +unmodified version of This Product), You, or Your affiliates +is/are endorsed by one or more authors of This Product, or in a +way that might suggest that one or more authors of This Product +is/are affiliated with You (or Your affiliates) or directly +participated in the creation of Your Product or of any work in +which You include a modified or unmodified version of This +Product. + +6. IF YOU ARE NOT SURE WHETHER YOU UNDERSTAND ALL PARTS OF THIS +LICENSE OR IF YOU ARE NOT SURE WHETHER YOU CAN COMPLY WITH ALL +TERMS AND CONDITIONS OF THIS LICENSE, YOU MUST NOT USE, COPY, +MODIFY, CREATE DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS +PRODUCT, NOR ANY PORTION(S) OF IT. YOU SHOULD CONSULT WITH A +LAWYER. + +7. IF (IN RELEVANT CONTEXT) ANY PROVISION OF CHAPTER IV OF THIS +LICENSE IS UNENFORCEABLE, INVALID, OR PROHIBITED UNDER +APPLICABLE LAW IN YOUR JURISDICTION, YOU HAVE NO RIGHTS UNDER +THIS LICENSE AND YOU MUST NOT USE, COPY, MODIFY, CREATE +DERIVATIVE WORKS OF, NOR (RE)DISTRIBUTE THIS PRODUCT, NOR ANY +PORTION(S) THEREOF. + +8. Except as otherwise provided in this License, if any +provision of this License, or a portion thereof, is found to be +invalid or unenforceable under applicable law, it shall not +affect the validity or enforceability of the remainder of this +License, and such invalid or unenforceable provision shall be +construed to reflect the original intent of the provision and +shall be enforced to the maximum extent permitted by applicable +law so as to effect the original intent of the provision as +closely as possible. + +____________________________________________________________ + + +Third-Party Licenses + +This Product contains components that were created by third +parties and that are governed by third-party licenses, which are +contained hereinafter (separated by lines consisting of +underscores). Each of the third-party licenses applies only to +(portions of) the source code file(s) in which the third-party +license is contained or in which it is explicitly referenced, +and to compiled or otherwise processed forms of such source +code. None of the third-party licenses applies to This Product +as a whole, even when it uses terms such as "product", +"program", or any other equivalent terms/phrases. This Product +as a whole is governed by the TrueCrypt License (see above). +Some of the third-party components have been modified by the +authors of This Product. Unless otherwise stated, such +modifications and additions are governed by the TrueCrypt +License (see above). Note: Unless otherwise stated, graphics and +files that are not part of the source code are governed by the +TrueCrypt License. + +____________________________________________________________ + +License agreement for Encryption for the Masses. + +Copyright (C) 1998-2000 Paul Le Roux. All Rights Reserved. + +This product can be copied and distributed free of charge, +including source code. + +You may modify this product and source code, and distribute such +modifications, and you may derive new works based on this +product, provided that: + +1. Any product which is simply derived from this product cannot +be called E4M, or Encryption for the Masses. + +2. If you use any of the source code in your product, and your +product is distributed with source code, you must include this +notice with those portions of this source code that you use. + +Or, + +If your product is distributed in binary form only, you must +display on any packaging, and marketing materials which +reference your product, a notice which states: + +"This product uses components written by Paul Le Roux +" + +3. If you use any of the source code originally by Eric Young, +you must in addition follow his terms and conditions. + +4. Nothing requires that you accept this License, as you have +not signed it. However, nothing else grants you permission to +modify or distribute the product or its derivative works. + +These actions are prohibited by law if you do not accept this +License. + +5. If any of these license terms is found to be to broad in +scope, and declared invalid by any court or legal process, you +agree that all other terms shall not be so affected, and shall +remain valid and enforceable. + +6. THIS PROGRAM IS DISTRIBUTED FREE OF CHARGE, THEREFORE THERE +IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. UNLESS OTHERWISE STATED THE PROGRAM IS PROVIDED +"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR +IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE +ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS +WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE +COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +7. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY +MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE +LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, +INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR +INABILITY TO USE THE PROGRAM, INCLUDING BUT NOT LIMITED TO LOSS +OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH +ANY OTHER PROGRAMS, EVEN IF SUCH HOLDER OR OTHER PARTY HAD +PREVIOUSLY BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +____________________________________________________________ + +Copyright (c) 1998-2008, Brian Gladman, Worcester, UK. +All rights reserved. + +LICENSE TERMS + +The free distribution and use of this software is allowed (with +or without changes) provided that: + + 1. source code distributions include the above copyright + notice, this list of conditions and the following + disclaimer; + + 2. binary distributions include the above copyright notice, + this list of conditions and the following disclaimer in + their documentation; + + 3. the name of the copyright holder is not used to endorse + products built using this software without specific written + permission. + +DISCLAIMER + +This software is provided 'as is' with no explicit or implied +warranties in respect of its properties, including, but not +limited to, correctness and/or fitness for purpose. +____________________________________________________________ + +Copyright (C) 2002-2004 Mark Adler, all rights reserved +version 1.8, 9 Jan 2004 + +This software is provided 'as-is', without any express or +implied warranty. In no event will the author be held liable +for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you + use this software in a product, an acknowledgment in the + product documentation would be appreciated but is not + required. +2. Altered source versions must be plainly marked as such, and + must not be misrepresented as being the original software. +3. This notice may not be removed or altered from any source + distribution. +____________________________________________________________ diff --git a/src/Release/Setup Files/NOTICE b/src/Release/Setup Files/NOTICE index 51a0fa62..42ae8da9 100644 --- a/src/Release/Setup Files/NOTICE +++ b/src/Release/Setup Files/NOTICE @@ -1,134 +1,134 @@ -Copyright 2013-2016 IDRIX - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -____________________________________________________________ - -Copyright (c) 2008-2012 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. -____________________________________________________________ - -License agreement for Encryption for the Masses. - -Copyright (C) 1998-2000 Paul Le Roux. All Rights Reserved. - -This product can be copied and distributed free of charge, -including source code. - -You may modify this product and source code, and distribute such -modifications, and you may derive new works based on this -product, provided that: - -1. Any product which is simply derived from this product cannot -be called E4M, or Encryption for the Masses. - -2. If you use any of the source code in your product, and your -product is distributed with source code, you must include this -notice with those portions of this source code that you use. - -Or, - -If your product is distributed in binary form only, you must -display on any packaging, and marketing materials which -reference your product, a notice which states: - -"This product uses components written by Paul Le Roux -" - -3. If you use any of the source code originally by Eric Young, -you must in addition follow his terms and conditions. - -4. Nothing requires that you accept this License, as you have -not signed it. However, nothing else grants you permission to -modify or distribute the product or its derivative works. - -These actions are prohibited by law if you do not accept this -License. - -5. If any of these license terms is found to be to broad in -scope, and declared invalid by any court or legal process, you -agree that all other terms shall not be so affected, and shall -remain valid and enforceable. - -6. THIS PROGRAM IS DISTRIBUTED FREE OF CHARGE, THEREFORE THERE -IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. UNLESS OTHERWISE STATED THE PROGRAM IS PROVIDED -"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR -IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE -ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS -WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE -COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -7. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY -MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE -LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, -INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR -INABILITY TO USE THE PROGRAM, INCLUDING BUT NOT LIMITED TO LOSS -OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH -ANY OTHER PROGRAMS, EVEN IF SUCH HOLDER OR OTHER PARTY HAD -PREVIOUSLY BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. -____________________________________________________________ - -Copyright (c) 1998-2008, Brian Gladman, Worcester, UK. -All rights reserved. - -LICENSE TERMS - -The free distribution and use of this software is allowed (with -or without changes) provided that: - - 1. source code distributions include the above copyright - notice, this list of conditions and the following - disclaimer; - - 2. binary distributions include the above copyright notice, - this list of conditions and the following disclaimer in - their documentation; - - 3. the name of the copyright holder is not used to endorse - products built using this software without specific written - permission. - -DISCLAIMER - -This software is provided 'as is' with no explicit or implied -warranties in respect of its properties, including, but not -limited to, correctness and/or fitness for purpose. -____________________________________________________________ - -Copyright (C) 2002-2004 Mark Adler, all rights reserved -version 1.8, 9 Jan 2004 - -This software is provided 'as-is', without any express or -implied warranty. In no event will the author be held liable -for any damages arising from the use of this software. - -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you - must not claim that you wrote the original software. If you - use this software in a product, an acknowledgment in the - product documentation would be appreciated but is not - required. -2. Altered source versions must be plainly marked as such, and - must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source - distribution. -____________________________________________________________ +Copyright 2013-2016 IDRIX + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +____________________________________________________________ + +Copyright (c) 2008-2012 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. +____________________________________________________________ + +License agreement for Encryption for the Masses. + +Copyright (C) 1998-2000 Paul Le Roux. All Rights Reserved. + +This product can be copied and distributed free of charge, +including source code. + +You may modify this product and source code, and distribute such +modifications, and you may derive new works based on this +product, provided that: + +1. Any product which is simply derived from this product cannot +be called E4M, or Encryption for the Masses. + +2. If you use any of the source code in your product, and your +product is distributed with source code, you must include this +notice with those portions of this source code that you use. + +Or, + +If your product is distributed in binary form only, you must +display on any packaging, and marketing materials which +reference your product, a notice which states: + +"This product uses components written by Paul Le Roux +" + +3. If you use any of the source code originally by Eric Young, +you must in addition follow his terms and conditions. + +4. Nothing requires that you accept this License, as you have +not signed it. However, nothing else grants you permission to +modify or distribute the product or its derivative works. + +These actions are prohibited by law if you do not accept this +License. + +5. If any of these license terms is found to be to broad in +scope, and declared invalid by any court or legal process, you +agree that all other terms shall not be so affected, and shall +remain valid and enforceable. + +6. THIS PROGRAM IS DISTRIBUTED FREE OF CHARGE, THEREFORE THERE +IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. UNLESS OTHERWISE STATED THE PROGRAM IS PROVIDED +"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR +IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE +ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS +WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE +COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +7. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY +MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE +LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, +INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR +INABILITY TO USE THE PROGRAM, INCLUDING BUT NOT LIMITED TO LOSS +OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH +ANY OTHER PROGRAMS, EVEN IF SUCH HOLDER OR OTHER PARTY HAD +PREVIOUSLY BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +____________________________________________________________ + +Copyright (c) 1998-2008, Brian Gladman, Worcester, UK. +All rights reserved. + +LICENSE TERMS + +The free distribution and use of this software is allowed (with +or without changes) provided that: + + 1. source code distributions include the above copyright + notice, this list of conditions and the following + disclaimer; + + 2. binary distributions include the above copyright notice, + this list of conditions and the following disclaimer in + their documentation; + + 3. the name of the copyright holder is not used to endorse + products built using this software without specific written + permission. + +DISCLAIMER + +This software is provided 'as is' with no explicit or implied +warranties in respect of its properties, including, but not +limited to, correctness and/or fitness for purpose. +____________________________________________________________ + +Copyright (C) 2002-2004 Mark Adler, all rights reserved +version 1.8, 9 Jan 2004 + +This software is provided 'as-is', without any express or +implied warranty. In no event will the author be held liable +for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you + use this software in a product, an acknowledgment in the + product documentation would be appreciated but is not + required. +2. Altered source versions must be plainly marked as such, and + must not be misrepresented as being the original software. +3. This notice may not be removed or altered from any source + distribution. +____________________________________________________________ diff --git a/src/Resources/Icons/VeraCrypt-128x128.xpm b/src/Resources/Icons/VeraCrypt-128x128.xpm index 42c5189a..74938988 100644 --- a/src/Resources/Icons/VeraCrypt-128x128.xpm +++ b/src/Resources/Icons/VeraCrypt-128x128.xpm @@ -1,1296 +1,1296 @@ -/* XPM */ -static const char *VeraCryptIcon128x128[] = { -"128 128 1165 2", -" c None", -". c #FFFFFF", -"+ c #FEFEFF", -"@ c #FDFEFF", -"# c #FEFFFF", -"$ c #FEFEFE", -"% c #FEFFFE", -"& c #75D0E9", -"* c #3EBDE0", -"= c #4BC2E2", -"- c #48C1E2", -"; c #49C1E2", -"> c #43C0E2", -", c #5CC5E4", -"' c #F3FAFC", -") c #FDFEFE", -"! c #BDE4D8", -"~ c #89CCB6", -"{ c #93D0BC", -"] c #91D0BB", -"^ c #90CFBB", -"/ c #A7D8C7", -"( c #B3DCCD", -"_ c #B1DBCC", -": c #B2DBCD", -"< c #AEDACA", -"[ c #C0E2D5", -"} c #FCFEFF", -"| c #B4E5F3", -"1 c #00A3D4", -"2 c #01A8D6", -"3 c #00A7D6", -"4 c #03A7D6", -"5 c #009DCF", -"6 c #8CD5EA", -"7 c #FBFEFE", -"8 c #EDF8F4", -"9 c #58BB9F", -"0 c #55B899", -"a c #66BDA0", -"b c #63BC9F", -"c c #61BB9E", -"d c #6DBFA4", -"e c #81C6AE", -"f c #8FCCB5", -"g c #91CCB6", -"h c #90CCB6", -"i c #92CDB7", -"j c #8ACAB2", -"k c #D7EDE5", -"l c #5EC8E5", -"m c #0FADD9", -"n c #0BACD8", -"o c #0BACD9", -"p c #10A9D6", -"q c #0DA5D2", -"r c #18AAD5", -"s c #E2F4FA", -"t c #95D4C1", -"u c #46B494", -"v c #58BB9E", -"w c #6BBFA4", -"x c #6DC0A5", -"y c #6EC0A5", -"z c #85C8B1", -"A c #86C9B2", -"B c #8DCBB5", -"C c #98D0BB", -"D c #97D0BB", -"E c #98D1BC", -"F c #91CDB7", -"G c #DBF3F9", -"H c #11ADD9", -"I c #06AAD8", -"J c #09ABD8", -"K c #08ABD8", -"L c #09AAD7", -"M c #0EA6D3", -"N c #12A7D4", -"O c #00A0D0", -"P c #67C7E3", -"Q c #FCFEFE", -"R c #D8EFE8", -"S c #4FB899", -"T c #53B99B", -"U c #50B99A", -"V c #5CBC9F", -"W c #6DBFA5", -"X c #69BEA3", -"Y c #79C4AB", -"Z c #87C9B2", -"` c #92CDB8", -" . c #97CFBA", -".. c #96CFBA", -"+. c #95CFB9", -"@. c #EAF5F1", -"#. c #81D4EB", -"$. c #00A5D5", -"%. c #0CACD9", -"&. c #0CA7D4", -"*. c #0FA6D3", -"=. c #08A4D2", -"-. c #C5EAF4", -";. c #7CCAB3", -">. c #49B596", -",. c #54BA9C", -"'. c #52B99B", -"). c #66BEA2", -"!. c #6CBFA4", -"~. c #6ABFA3", -"{. c #6FC0A6", -"]. c #84C8B1", -"^. c #89CAB3", -"/. c #C2E3D7", -"(. c #F2FBFD", -"_. c #28B5DC", -":. c #01A8D7", -"<. c #0AACD8", -"[. c #0AA9D6", -"}. c #11A7D4", -"|. c #02A1D1", -"1. c #45BADD", -"2. c #C0E5DB", -"3. c #48B595", -"4. c #58BB9D", -"5. c #7DC5AD", -"6. c #84C8B0", -"7. c #90CCB7", -"8. c #97CFBB", -"9. c #94CEB9", -"0. c #9ED2BF", -"a. c #F5FBF9", -"b. c #A6E1F1", -"c. c #00A6D6", -"d. c #0DA7D4", -"e. c #A3DDEE", -"f. c #F6FBFA", -"g. c #66C1A7", -"h. c #4DB798", -"i. c #53BA9C", -"j. c #63BDA1", -"k. c #72C2A8", -"l. c #86C8B2", -"m. c #95CFBA", -"n. c #D2EAE1", -"o. c #46BFE1", -"p. c #0BA8D5", -"q. c #10A7D3", -"r. c #28AFD8", -"s. c #F1FAFC", -"t. c #A6DBCB", -"u. c #55BA9D", -"v. c #51B99B", -"w. c #55BA9C", -"x. c #81C6AF", -"y. c #A9D8C6", -"z. c #C8ECF6", -"A. c #06A9D7", -"B. c #12A8D4", -"C. c #7ED0E8", -"D. c #E6F5F0", -"E. c #56BB9D", -"F. c #50B89A", -"G. c #5EBCA0", -"H. c #76C3AA", -"I. c #E1F1EB", -"J. c #69CCE7", -"K. c #0CADD9", -"L. c #0CA8D5", -"M. c #0DA5D3", -"N. c #D8F1F8", -"O. c #8CD0BC", -"P. c #47B495", -"Q. c #68BEA3", -"R. c #86C8B1", -"S. c #8BCAB4", -"T. c #99D0BC", -"U. c #8FCCB6", -"V. c #B7DED0", -"W. c #E4F6FB", -"X. c #18B0DA", -"Y. c #06A8D6", -"Z. c #00A1D0", -"`. c #5AC2E1", -" + c #D0ECE4", -".+ c #4CB697", -"++ c #5CBB9F", -"@+ c #84C7B0", -"#+ c #EEF7F4", -"$+ c #8FD8ED", -"%+ c #00A1D1", -"&+ c #13A7D3", -"*+ c #11A7D3", -"=+ c #05A2D1", -"-+ c #BAE5F2", -";+ c #73C6AF", -">+ c #4AB697", -",+ c #4FB89A", -"'+ c #68BFA3", -")+ c #8CCBB5", -"!+ c #89CAB4", -"~+ c #8ACAB4", -"{+ c #C9E6DC", -"]+ c #F9FDFE", -"^+ c #3DACD8", -"/+ c #1099CF", -"(+ c #1B9ED1", -"_+ c #199DD1", -":+ c #0F99CF", -"<+ c #47A7D7", -"[+ c #FDFDFE", -"}+ c #ABE0D3", -"|+ c #35B291", -"1+ c #49B89B", -"2+ c #46B799", -"3+ c #48B89A", -"4+ c #3CB394", -"5+ c #BAE4D8", -"6+ c #FBFDFB", -"7+ c #F0F8F5", -"8+ c #F2F9F6", -"9+ c #F1F9F6", -"0+ c #FBFDFD", -"a+ c #B7E0F1", -"b+ c #0F97CF", -"c+ c #1D9DD1", -"d+ c #1A9CD1", -"e+ c #2199D1", -"f+ c #1584C9", -"g+ c #9FCEE9", -"h+ c #FCFDFE", -"i+ c #EFF9F7", -"j+ c #43B99D", -"k+ c #33B293", -"l+ c #46B89A", -"m+ c #44B799", -"n+ c #47B89A", -"o+ c #3AB393", -"p+ c #73C9B3", -"q+ c #5DB9DE", -"r+ c #0D96CE", -"s+ c #1D9DD2", -"t+ c #2390CE", -"u+ c #1F8ACC", -"v+ c #3295D0", -"w+ c #EBF4FA", -"x+ c #FCFEFD", -"y+ c #8CD4C3", -"z+ c #25AE8D", -"A+ c #36B496", -"B+ c #3FB698", -"C+ c #45B799", -"D+ c #41B698", -"E+ c #D7F0E9", -"F+ c #D5EDF7", -"G+ c #1B9CD1", -"H+ c #199CD1", -"I+ c #1E95CF", -"J+ c #248CCD", -"K+ c #278FCE", -"L+ c #1485C9", -"M+ c #7EBCE1", -"N+ c #D9F1EB", -"O+ c #33B394", -"P+ c #35B495", -"Q+ c #47B89B", -"R+ c #37B292", -"S+ c #8ED4C2", -"T+ c #7FC8E5", -"U+ c #0A95CE", -"V+ c #1E9ED2", -"W+ c #1B9BD1", -"X+ c #238ECD", -"Y+ c #238DCD", -"Z+ c #218CCC", -"`+ c #D2E8F5", -" @ c #6DC9B3", -".@ c #27AF8E", -"+@ c #32B394", -"@@ c #3CB596", -"#@ c #45B79A", -"$@ c #41B697", -"%@ c #4FBB9F", -"&@ c #ECF8F5", -"*@ c #EEF8FC", -"=@ c #2EA5D5", -"-@ c #159AD0", -";@ c #1B9DD1", -">@ c #2093CF", -",@ c #268FCE", -"'@ c #1787CA", -")@ c #5DABDA", -"!@ c #BEE7DD", -"~@ c #29AF8F", -"{@ c #34B394", -"]@ c #42B798", -"^@ c #ABDFD1", -"/@ c #A2D7EC", -"(@ c #0B95CE", -"_@ c #1A9DD1", -":@ c #1C99D0", -"<@ c #268ECE", -"[@ c #B5D8EE", -"}@ c #F9FDFC", -"|@ c #53BEA5", -"1@ c #2BB090", -"2@ c #39B596", -"3@ c #3DB495", -"4@ c #63C3AA", -"5@ c #FBFEFD", -"6@ c #49B0DA", -"7@ c #2190CE", -"8@ c #258ECD", -"9@ c #1C89CB", -"0@ c #419DD4", -"a@ c #F7FBFD", -"b@ c #A0DBCD", -"c@ c #25AE8C", -"d@ c #37B496", -"e@ c #40B698", -"f@ c #3BB494", -"g@ c #C6E9E0", -"h@ c #C3E5F3", -"i@ c #1299CF", -"j@ c #1C9CD1", -"k@ c #1D97D0", -"l@ c #1385CA", -"m@ c #93C7E7", -"n@ c #E8F6F3", -"o@ c #3DB799", -"p@ c #30B292", -"q@ c #34B395", -"r@ c #37B495", -"s@ c #39B393", -"t@ c #7CCDB8", -"u@ c #69BEE1", -"v@ c #0B96CE", -"w@ c #1E9DD2", -"x@ c #228FCD", -"y@ c #248DCD", -"z@ c #208CCC", -"A@ c #2B91CF", -"B@ c #E3F0F9", -"C@ c #80CFBC", -"D@ c #25AD8C", -"E@ c #36B395", -"F@ c #32B293", -"G@ c #3EB597", -"H@ c #44B698", -"I@ c #45B89A", -"J@ c #DFF3EE", -"K@ c #E0F1F9", -"L@ c #20A0D3", -"M@ c #1C94CF", -"N@ c #1486CA", -"O@ c #72B6DF", -"P@ c #D1EFE8", -"Q@ c #2FB595", -"R@ c #35B697", -"S@ c #34B697", -"T@ c #33B697", -"U@ c #39B899", -"V@ c #37B494", -"W@ c #98D7C6", -"X@ c #8DCAE7", -"Y@ c #1385C9", -"Z@ c #288ECD", -"`@ c #248CCC", -" # c #258CCC", -".# c #1E88CB", -"+# c #C9E2F2", -"@# c #60B8A1", -"## c #25A182", -"$# c #33A689", -"%# c #30A588", -"&# c #31A689", -"*# c #2AA384", -"=# c #4AB196", -"-# c #F3FBF9", -";# c #F5F9FC", -"># c #4395CE", -",# c #2182C5", -"'# c #2A87C7", -")# c #2886C7", -"!# c #2B88C8", -"~# c #1D7EC3", -"{# c #5196CC", -"]# c #B2E1E6", -"^# c #197B71", -"/# c #236349", -"(# c #216750", -"_# c #21664E", -":# c #22674F", -"<# c #1F634B", -"[# c #2D8B70", -"}# c #D6EFE8", -"|# c #B2D4EB", -"1# c #1B7FC4", -"2# c #2887C8", -"3# c #277FC2", -"4# c #116DB7", -"5# c #A8CAE5", -"6# c #F4FAFA", -"7# c #45B0B8", -"8# c #269EA6", -"9# c #246D57", -"0# c #21664D", -"a# c #21674F", -"b# c #216850", -"c# c #20644D", -"d# c #27765D", -"e# c #239B7B", -"f# c #63B7A0", -"g# c #5EA4D5", -"h# c #1D80C4", -"i# c #2783C5", -"j# c #2178BC", -"k# c #1A73BA", -"l# c #3685C3", -"m# c #F1F6FB", -"n# c #92D0D4", -"o# c #1E9CA5", -"p# c #32AAB5", -"q# c #288C87", -"r# c #206348", -"s# c #216851", -"t# c #2C9477", -"u# c #32A385", -"v# c #23997A", -"w# c #B8DED4", -"x# c #D0E5F3", -"y# c #2484C6", -"z# c #2986C7", -"A# c #2887C7", -"B# c #227BBF", -"C# c #1F76BB", -"D# c #247ABD", -"E# c #106DB7", -"F# c #86B5DB", -"G# c #DFF1F3", -"H# c #31A6AF", -"I# c #2BA3AC", -"J# c #2EA4AD", -"K# c #2DA5AF", -"L# c #237362", -"M# c #20644B", -"N# c #20634B", -"O# c #277E63", -"P# c #30A384", -"Q# c #319F81", -"R# c #289C7D", -"S# c #4CAC93", -"T# c #F8FCFB", -"U# c #7DB6DD", -"V# c #197EC3", -"W# c #2C88C8", -"X# c #2987C8", -"Y# c #2581C4", -"Z# c #2077BC", -"`# c #2177BC", -" $ c #1F76BC", -".$ c #2378BD", -"+$ c #DAE8F4", -"@$ c #72C2C8", -"#$ c #209EA8", -"$$ c #30A5AE", -"%$ c #2DA3AC", -"&$ c #2EA7B2", -"*$ c #2A9595", -"=$ c #21654B", -"-$ c #226B52", -";$ c #2E9B7D", -">$ c #2FA082", -",$ c #2F9F81", -"'$ c #33A183", -")$ c #209878", -"!$ c #9BD1C2", -"~$ c #E9F3F9", -"{$ c #358DCA", -"]$ c #2987C7", -"^$ c #2179BD", -"/$ c #2076BC", -"($ c #2379BD", -"_$ c #126FB8", -":$ c #65A1D1", -"<$ c #C5E6E8", -"[$ c #25A0AA", -"}$ c #2FA5AE", -"|$ c #2DA4AD", -"1$ c #2EA8B3", -"2$ c #257C6F", -"3$ c #206349", -"4$ c #29876C", -"5$ c #30A385", -"6$ c #2F9E80", -"7$ c #309F82", -"8$ c #2C9E7F", -"9$ c #39A387", -"0$ c #E7F4F0", -"a$ c #9EC8E6", -"b$ c #247EC2", -"c$ c #2278BD", -"d$ c #1671B9", -"e$ c #BDD7EB", -"f$ c #55B5BD", -"g$ c #24A0A9", -"h$ c #2DA4AC", -"i$ c #2DA6B0", -"j$ c #2C9DA1", -"k$ c #247158", -"l$ c #32A183", -"m$ c #219878", -"n$ c #7EC4B1", -"o$ c #FBFDFE", -"p$ c #4C9AD0", -"q$ c #1F81C5", -"r$ c #2784C6", -"s$ c #1771B9", -"t$ c #478FC7", -"u$ c #A6D9DC", -"v$ c #1F9EA7", -"w$ c #2DA3AB", -"x$ c #2EA8B4", -"y$ c #27857E", -"z$ c #21654D", -"A$ c #2C9074", -"B$ c #30A284", -"C$ c #309F81", -"D$ c #2B9D7F", -"E$ c #D1EAE3", -"F$ c #BEDAEE", -"G$ c #1E80C4", -"H$ c #237CC0", -"I$ c #2479BD", -"J$ c #9CC3E1", -"K$ c #FFFEFF", -"L$ c #EDF7F8", -"M$ c #3DABB3", -"N$ c #29A2AB", -"O$ c #2EA5AE", -"P$ c #2DA5AE", -"Q$ c #2DA3AA", -"R$ c #226E5A", -"S$ c #267A60", -"T$ c #32A083", -"U$ c #249A7A", -"V$ c #63B7A1", -"W$ c #69AAD8", -"X$ c #1C80C4", -"Y$ c #2A84C5", -"Z$ c #2076BB", -"`$ c #1C74BB", -" % c #2E7FC0", -".% c #E6F0F7", -"+% c #85CAD0", -"@% c #1E9DA7", -"#% c #31A6AE", -"$% c #298F8D", -"%% c #216349", -"&% c #226951", -"*% c #2D987B", -"=% c #2FA182", -"-% c #B7DED4", -";% c #F9FCFB", -">% c #FCFDFD", -",% c #DAEAF5", -"'% c #2A87C8", -")% c #207BBF", -"!% c #1F78BD", -"~% c #237ABE", -"{% c #0E6EB7", -"]% c #81B2DA", -"^% c #E3F5F3", -"/% c #29A3AC", -"(% c #2DA5AD", -"_% c #2EA8B1", -":% c #227363", -"<% c #278265", -"[% c #31A587", -"}% c #31A183", -"|% c #289D7E", -"1% c #4CAD93", -"2% c #87B5DB", -"3% c #1467B3", -"4% c #2874B9", -"5% c #2472B8", -"6% c #2171B7", -"7% c #2E76BB", -"8% c #4DA7BA", -"9% c #289FAC", -"0% c #30A0AF", -"a% c #2EA0AE", -"b% c #2EA0AD", -"c% c #2CA1B1", -"d% c #329A9F", -"e% c #35997B", -"f% c #319B7E", -"g% c #2C987A", -"h% c #2D987A", -"i% c #2F997C", -"j% c #239374", -"k% c #7FBFAD", -"l% c #B9DDD4", -"m% c #AFD8CD", -"n% c #ACD6CB", -"o% c #AAD5CA", -"p% c #ABD6CA", -"q% c #A5D4C7", -"r% c #E2F3EF", -"s% c #F0F4F9", -"t% c #3E76B7", -"u% c #2664AE", -"v% c #2C69B1", -"w% c #2B68B0", -"x% c #2A68AF", -"y% c #2D69B5", -"z% c #1F639C", -"A% c #127187", -"B% c #339BB3", -"C% c #2E96AE", -"D% c #2F97AF", -"E% c #3299B0", -"F% c #1F8FA8", -"G% c #B1D8E4", -"H% c #7FB9A5", -"I% c #198364", -"J% c #2D8E71", -"K% c #2A8C6F", -"L% c #2B8C6F", -"M% c #1E8464", -"N% c #1F9071", -"O% c #209374", -"P% c #209273", -"Q% c #239273", -"R% c #139474", -"S% c #67C4B0", -"T% c #A9C3E0", -"U% c #1C60AC", -"V% c #2D6BB2", -"W% c #2A69B1", -"X% c #126783", -"Y% c #0C6375", -"Z% c #258AA1", -"`% c #319BB2", -" & c #2F97AE", -".& c #2F98AF", -"+& c #3199B0", -"@& c #2694AC", -"#& c #55ABBD", -"$& c #E1EFEB", -"%& c #309074", -"&& c #288C6F", -"*& c #2B8D71", -"=& c #2A8D70", -"-& c #2A8E71", -";& c #288A6C", -">& c #298667", -",& c #2D9073", -"'& c #329C7F", -")& c #319B7F", -"!& c #30AC90", -"~& c #20A88A", -"{& c #BCE4DB", -"]& c #5788C1", -"^& c #2062AD", -"/& c #2A69B0", -"(& c #2C69B5", -"_& c #1D6798", -":& c #0B6576", -"<& c #0C6379", -"[& c #136E83", -"}& c #2794AC", -"|& c #C5E2E9", -"1& c #93C5B6", -"2& c #1B8566", -"3& c #2E8F73", -"4& c #298C6F", -"5& c #278768", -"6& c #2C9678", -"7& c #2E9A7D", -"8& c #2E997C", -"9& c #2E977A", -"0& c #2CA386", -"a& c #2DAE92", -"b& c #23A98B", -"c& c #4CB9A0", -"d& c #C8D8EB", -"e& c #2364AE", -"f& c #2B6AB1", -"g& c #2B69B2", -"h& c #2769AC", -"i& c #0E657D", -"j& c #0C6579", -"k& c #0E667B", -"l& c #0A6176", -"m& c #208298", -"n& c #329CB3", -"o& c #2E97AE", -"p& c #329AB0", -"q& c #2292AA", -"r& c #73BAC9", -"s& c #F5FAF8", -"t& c #449B82", -"u& c #248A6B", -"v& c #2C8E71", -"w& c #28896B", -"x& c #278767", -"y& c #278667", -"z& c #298C6D", -"A& c #2E987B", -"B& c #2E9B7E", -"C& c #2BAB8E", -"D& c #2BAC8F", -"E& c #2FAD91", -"F& c #1CA687", -"G& c #9CD8CB", -"H& c #749DCC", -"I& c #1C5FAC", -"J& c #18678F", -"K& c #0D657B", -"L& c #0D657A", -"M& c #0C6479", -"N& c #0F687D", -"O& c #2C94AB", -"P& c #3099B0", -"Q& c #3098AF", -"R& c #2D97AE", -"S& c #339AB1", -"T& c #DFEFF3", -"U& c #B3D6CC", -"V& c #1D8667", -"W& c #2D8F72", -"X& c #2A8D71", -"Y& c #298B6E", -"Z& c #2C9376", -"`& c #2CA689", -" * c #2BAD90", -".* c #2CAC90", -"+* c #28AB8D", -"@* c #36B095", -"#* c #E7F6F2", -"$* c #E3EBF5", -"%* c #316EB4", -"&* c #2867B0", -"** c #2C69B4", -"=* c #2468A5", -"-* c #0C6578", -";* c #0B6176", -">* c #1B7A90", -",* c #319CB3", -"'* c #339AB0", -")* c #2091A9", -"!* c #92C9D5", -"~* c #5FA994", -"{* c #1F8769", -"]* c #288869", -"^* c #2D9E81", -"/* c #1DA687", -"(* c #7CCBBA", -"_* c #95B4D8", -":* c #1B5EAB", -"<* c #2E6CB2", -"[* c #2B69B3", -"}* c #146687", -"|* c #0B6577", -"1* c #288EA5", -"2* c #309AB1", -"3* c #2995AD", -"4* c #47A4B8", -"5* c #F4F9FB", -"6* c #D1E6E0", -"7* c #278B6E", -"8* c #298A6C", -"9* c #278666", -"0* c #2A9072", -"a* c #2E9A7E", -"b* c #2CA88B", -"c* c #2CAC8F", -"d* c #27AA8D", -"e* c #CFECE5", -"f* c #F6F9FC", -"g* c #467DBB", -"h* c #1F679D", -"i* c #0D667B", -"j* c #0B6277", -"k* c #167287", -"l* c #B2D9E1", -"m* c #7EBAA8", -"n* c #2E8F72", -"o* c #278869", -"p* c #2D977A", -"q* c #2DA184", -"r* c #2EAD90", -"s* c #20A889", -"t* c #5DC0AA", -"u* c #B5CBE4", -"v* c #1E60AD", -"w* c #2D6BB3", -"x* c #2969AF", -"y* c #106580", -"z* c #24879D", -"A* c #349DB4", -"B* c #2492AA", -"C* c #60B0C2", -"D* c #E9F3F0", -"E* c #379478", -"F* c #268B6D", -"G* c #2B8E71", -"H* c #288A6B", -"I* c #2A8E6F", -"J* c #2EAD91", -"K* c #1EA788", -"L* c #B1E0D6", -"M* c #608FC4", -"N* c #2262B2", -"O* c #226C98", -"P* c #0E6778", -"Q* c #12677D", -"R* c #11677C", -"S* c #10667A", -"T* c #156E83", -"U* c #2B96AE", -"V* c #CFE7EC", -"W* c #9FCBBE", -"X* c #1B8667", -"Y* c #308F73", -"Z* c #2A896A", -"`* c #2A886A", -" = c #30977A", -".= c #329A7E", -"+= c #2FA588", -"@= c #2EAF92", -"#= c #30AE92", -"$= c #28AB8E", -"%= c #47B79E", -"&= c #F5FBFA", -"*= c #D5E1F1", -"== c #1C62A3", -"-= c #005971", -";= c #015A71", -">= c #005A71", -",= c #005B72", -"'= c #01586E", -")= c #026E87", -"!= c #80C2D0", -"~= c #FBFDFC", -"{= c #4C9F86", -"]= c #107B5A", -"^= c #1A805E", -"/= c #187F5D", -"(= c #187E5D", -"_= c #198261", -":= c #1E9677", -"<= c #1CA787", -"[= c #0CA07F", -"}= c #83CEBE", -"|= c #B2CDD9", -"1= c #8FB8C1", -"2= c #96BDC6", -"3= c #95BCC5", -"4= c #95BBC4", -"5= c #94BCC6", -"6= c #E9F4F6", -"7= c #D4E8E2", -"8= c #9AC7B8", -"9= c #A1CBBE", -"0= c #A0CABD", -"a= c #A0C9BC", -"b= c #A2D5C9", -"c= c #A2DCCF", -"d= c #A2DBCE", -"e= c #A3DBCE", -"f= c #A0DACD", -"g= c #AADED2", -"h= c #FDFDFD", -"i= c #FCFCFC", -"j= c #939392", -"k= c #696968", -"l= c #797978", -"m= c #F0F0F0", -"n= c #D3D3D3", -"o= c #6D6D6C", -"p= c #C1C1C0", -"q= c #BEBEBE", -"r= c #626261", -"s= c #3E3E3C", -"t= c #3C3C3A", -"u= c #484846", -"v= c #9F9F9E", -"w= c #FBFBFB", -"x= c #7F7F7E", -"y= c #000000", -"z= c #080806", -"A= c #BBBBBA", -"B= c #F9F9F9", -"C= c #80807F", -"D= c #0E0E0C", -"E= c #CDCDCC", -"F= c #FAFAFA", -"G= c #FCFCFB", -"H= c #F7F7F7", -"I= c #090907", -"J= c #515150", -"K= c #8D8D8C", -"L= c #989898", -"M= c #656563", -"N= c #818180", -"O= c #DBDBDB", -"P= c #CECECE", -"Q= c #D0D0CF", -"R= c #1F1F1D", -"S= c #11110F", -"T= c #7C7C7B", -"U= c #4E4E4C", -"V= c #686866", -"W= c #0C0C0B", -"X= c #C4C4C4", -"Y= c #31312F", -"Z= c #434341", -"`= c #0D0D0B", -" - c #434342", -".- c #D6D6D6", -"+- c #20201E", -"@- c #90908F", -"#- c #CCCCCB", -"$- c #757574", -"%- c #585857", -"&- c #6E6E6D", -"*- c #C5C5C4", -"=- c #DADADA", -"-- c #7B7B7A", -";- c #9E9E9E", -">- c #ECECEC", -",- c #747473", -"'- c #838382", -")- c #C6C6C5", -"!- c #5E5E5D", -"~- c #DEDEDE", -"{- c #CBCBCA", -"]- c #040402", -"^- c #A0A09F", -"/- c #C1C1C1", -"(- c #A9A9A8", -"_- c #F5F5F4", -":- c #737371", -"<- c #AFAFAE", -"[- c #8E8E8D", -"}- c #F3F3F3", -"|- c #B2B2B1", -"1- c #9C9C9B", -"2- c #A5A5A4", -"3- c #EAEAEA", -"4- c #5F5F5D", -"5- c #EDEDED", -"6- c #888886", -"7- c #252523", -"8- c #888885", -"9- c #ABABAA", -"0- c #828281", -"a- c #D2D2D1", -"b- c #979796", -"c- c #D2D2D2", -"d- c #A3A3A2", -"e- c #10100E", -"f- c #070706", -"g- c #1C1C1A", -"h- c #070705", -"i- c #0F0F0D", -"j- c #AAAAA9", -"k- c #B7B7B6", -"l- c #2F2F2E", -"m- c #51514F", -"n- c #3F3F3E", -"o- c #272726", -"p- c #191916", -"q- c #060604", -"r- c #2A2A28", -"s- c #DDDDDC", -"t- c #7D7D7C", -"u- c #191917", -"v- c #7E7E7D", -"w- c #2C2C2A", -"x- c #525250", -"y- c #161614", -"z- c #A7A7A6", -"A- c #C2C2C2", -"B- c #B1B1B0", -"C- c #F8F8F8", -"D- c #3D3D3B", -"E- c #41413F", -"F- c #595958", -"G- c #6C6C6A", -"H- c #131311", -"I- c #343433", -"J- c #F1F1F1", -"K- c #5B5B5A", -"L- c #222220", -"M- c #373735", -"N- c #565655", -"O- c #C7C7C7", -"P- c #0F0F0C", -"Q- c #575756", -"R- c #4C4C4A", -"S- c #E3E3E3", -"T- c #151513", -"U- c #B4B4B3", -"V- c #0B0B09", -"W- c #343432", -"X- c #C6C6C6", -"Y- c #171715", -"Z- c #525251", -"`- c #8E8E8C", -" ; c #B2B2B2", -".; c #D5D5D5", -"+; c #30302F", -"@; c #555554", -"#; c #353534", -"$; c #9B9B9A", -"%; c #030301", -"&; c #767674", -"*; c #353533", -"=; c #575755", -"-; c #0D0D0A", -";; c #CACAC9", -">; c #5E5E5C", -",; c #0C0C0A", -"'; c #777776", -"); c #30302E", -"!; c #717170", -"~; c #646463", -"{; c #F5F5F5", -"]; c #2B2B29", -"^; c #0A0A07", -"/; c #8F8F8E", -"(; c #A8A8A7", -"_; c #949493", -":; c #DFDFDF", -"<; c #141412", -"[; c #121210", -"}; c #848482", -"|; c #A2A2A1", -"1; c #5F5F5E", -"2; c #474745", -"3; c #262624", -"4; c #545452", -"5; c #E2E2E2", -"6; c #666664", -"7; c #3E3E3D", -"8; c #70706F", -"9; c #40403F", -"0; c #B0B0AF", -"a; c #1E1E1D", -"b; c #D4D4D4", -"c; c #030303", -"d; c #040403", -"e; c #050503", -"f; c #D0D0D0", -"g; c #E8E8E7", -"h; c #383836", -"i; c #020200", -"j; c #141413", -"k; c #424240", -"l; c #2B2B2A", -"m; c #EEEEEE", -"n; c #929291", -"o; c #E4E4E4", -"p; c #999998", -"q; c #1E1E1C", -"r; c #919190", -"s; c #4A4A48", -"t; c #232321", -"u; c #C0C0C0", -"v; c #292927", -"w; c #585856", -"x; c #4E4E4D", -"y; c #939393", -"z; c #0A0A08", -"A; c #2E2E2C", -"B; c #BBBBBB", -"C; c #C9C9C8", -"D; c #BCBCBB", -"E; c #C8C8C8", -"F; c #B6B6B6", -"G; c #878786", -"H; c #050502", -"I; c #DCDCDB", -"J; c #535351", -"K; c #B5B5B4", -"L; c #A6A6A5", -"M; c #181816", -"N; c #4B4B49", -"O; c #BDBDBC", -"P; c #181815", -"Q; c #474746", -"R; c #FAFAF9", -"S; c #656564", -"T; c #1A1A18", -"U; c #242423", -"V; c #10100D", -"W; c #959594", -"X; c #D1D1D0", -"Y; c #EEEEED", -"Z; c #CFCFCF", -"`; c #D6D6D5", -" > c #B9B9B8", -".> c #71716F", -"+> c #313130", -"@> c #CBCBCB", -"#> c #616160", -"$> c #484847", -"%> c #EFEFEF", -"&> c #BABAB9", -"*> c #212120", -"=> c #5D5D5B", -"-> c #5C5C5B", -";> c #E8E8E8", -">> c #6B6B69", -",> c #6F6F6E", -"'> c #DBDBDA", -")> c #8A8A89", -"!> c #020201", -"~> c #575757", -"{> c #BDBDBD", -"]> c #060603", -"^> c #0C0C09", -"/> c #131312", -"(> c #50504F", -"_> c #E6E6E6", -":> c #444442", -"<> c #858584", -"[> c #5B5B59", -"}> c #767675", -"|> c #888887", -"1> c #8C8C8B", -"2> c #979795", -"3> c #E9E9E9", -"4> c #626260", -"5> c #6B6B6A", -"6> c #6F6F6D", -"7> c #C0C0BF", -"8> c #565654", -"9> c #737372", -"0> c #D5D5D4", -"a> c #ADADAC", -"b> c #545453", -"c> c #A4A4A3", -"d> c #B5B5B5", -"e> c #444443", -"f> c #595957", -"g> c #C3C3C2", -"h> c #494948", -"i> c #3D3D3C", -"j> c #E7E7E7", -"k> c #666665", -"l> c #323230", -"m> c #9E9E9D", -"n> c #FEFEFD", -"o> c #CFCFCE", -"p> c #A8A8A8", -"q> c #535352", -"r> c #FDFDFC", -"s> c #B8B8B8", -"t> c #60605F", -"u> c #6D6D6B", -"v> c #E0E0DF", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . + @ @ @ @ @ @ @ @ @ @ @ @ @ # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ $ $ $ $ $ $ $ $ $ $ $ $ $ % % % % % % % % % % % % % % . . . . ", -" . . . # # . . . . . . . . . . . . . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . # . & * = - - - - - - - - ; > , ' . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . ! ~ { ] ] ] ] ] ] ] ] ] ] ^ / ( _ _ _ _ _ _ _ _ _ : < [ . . . . . ", -" . . . . } . | 1 2 3 3 3 3 3 3 3 3 3 4 5 6 . 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . % . 8 9 0 a b b b b b b b b b c d e f g h h h h h h h h i j k . $ . . . . ", -" . . . . . @ . l 3 m n n n n n n n o p q r s . + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . t u v w x x x x x x x x x y z A B C D D D D D D D E F ( . # . . . . . ", -" . . . . . . @ . G H I J K K K K K K L M N O P . Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . R S T U V W w w w w w w w X Y Z z z ` ...............+.@.. % . . . . . . ", -" . . . . . . . 7 . #.$.%.K K K K K K &.M M *.=.-.. @ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . % . ;.>.,.'.'.).!.w w w w w ~.{.z z z ].^. ...........C f /.. $ . . . . . . . ", -" . . . . . . . . # . (._.:.<.K K K K [.M M M }.|.1.. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . 2.3.,.'.'.U 4.!.w w w w w X 5.Z z z z 6.7.8....... .9.0.a.. # . . . . . . . . ", -" . . . . . . . . . Q . b.c.o K K K K d.M M M M }.O e.. Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . f.g.h.i.'.'.'.U j.W w w w X k.l.z z z z ].Z m.......C f n.. $ . . . . . . . . . ", -" . . . . . . . . . . . # . o.3 n K K p.M M M M M q.=.r.s.. # . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . t.u u.'.'.'.'.v.w.w w w w w x.l.z z z z z 6.B 8...D i y.$ . . . . . . . . . . . . ", -" . . . . . . . . . . . . @ . z.A.J K L M M M M M M M B.O C.. 7 . . . . . . . . . . . . . . . . . . . . . . . . . . % . D.E.F.T '.'.'.'.'.U G.W w X H.Z z z z z z z z z 9. .8.i I.. $ . . . . . . . . . . . . ", -" . . . . . . . . . . . . . Q . J.$.K.L.M M M M M M M *.M.N N.. @ . . . . . . . . . . . . . . . . . . . . . . . . . ) . O.P.u.'.'.'.'.'.'.'.T Q.w x ].R.z z z z z z z 6.S.T.U.V.. $ . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . # . W.X.Y.*.M M M M M M M M N Z.`.. } . . . . . . . . . . . . . . . . . . . . . . . . ) . +.+i.'.'.'.'.'.'.'.'.U ++w Y R.@+@+@+@+@+@+@+@+@+@+U.C #+. # . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . 7 . $+%+&+*.*.*.*.*.*.*.*.*.*+=+-+. } . . . . . . . . . . . . . . . . . . . . . . . # % ;+>+,.'.'.'.'.'.'.'.'.T ,+'+)+!+!+!+!+!+!+!+!+!+!+~+R.{+. $ . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . # . ]+^+/+(+_+_+_+_+_+_+_+_+(+:+<+[+. . . . . . . . . . . . . . . . . . . . . . . Q . }+|+1+2+2+2+2+2+2+2+2+2+3+4+5+6+7+8+8+8+8+8+8+8+8+8+8+9+0+. . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . Q . a+b+c+d+d+d+d+d+d+d+d+_+e+f+g+. h+. . . . . . . . . . . . . . . . . . . . # . i+j+k+l+m+m+m+m+m+m+m+m+n+o+p+. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . @ . q+r+s+d+d+d+d+d+d+d+d+t+u+v+w+. + . . . . . . . . . . . . . . . . . . . x+. y+z+A+B+C+m+m+m+m+m+m+m+m+D+E+. Q # # # # # # # # # # # # . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . @ . F+G+H+G+d+d+d+d+d+_+I+J+K+L+M+. h+. . . . . . . . . . . . . . . . . . ) . N+O+O+O+P+m+m+m+m+m+m+m+Q+R+S+. Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . Q . T+U+V+d+d+d+d+d+W+X+Y+Y+Y+Z+`+. @ . . . . . . . . . . . . . . . . . ) . @.@A+O++@@@C+m+m+m+m+#@$@%@&@. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . # . *@=@-@;@d+d+d+_+>@J+Y+Y+,@'@)@. @ . . . . . . . . . . . . . . . . ) . !@~@P+O+O+O+{@]@C+m+m+m+Q+R+^@. Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . Q . /@(@V+d+d+_@:@Y+Y+Y+Y+Y+<@'@[@. Q . . . . . . . . . . . . . . # . }@|@1@P+O+O+O++@2@C+m+m+l+3@4@5@. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . # . 6@b+s+d+_@7@J+Y+Y+Y+Y+8@9@0@a@. # . . . . . . . . . . . . . x+. b@c@d@O+O+O+O+O+O+e@C+m+l+f@g@. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . @ . h@i@j@_@k@J+Y+Y+Y+Y+Y+Y+K+l@m@. h+. . . . . . . . . . . . % . n@o@p@q@O+O+O+O+O++@r@C+Q+s@t@. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . u@v@w@x@Y+Y+Y+Y+Y+Y+Y+y@z@A@B@. + . . . . . . . . . . . Q . C@D@E@k+k+k+k+k+k+k+F@G@H@I@J@. $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . K@L@M@J+Y+Y+Y+Y+Y+Y+Y+Y+K+N@O@. h+. . . . . . . . . . ) . P@Q@R@S@S@S@S@S@S@S@S@T@U@V@W@. Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. X@Y@Z@`@`@`@`@`@`@`@`@`@ #.#+#. ) . . . . . . . . . % . @###$#%#%#%#%#%#%#%#%#&#*#=#-#. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . ;#>#,#'#)#)#)#)#)#)#)#)#!#~#{#. # . . . . . . . . Q . ]#^#/#(#_#_#_#_#_#_#_#_#:#<#[#}#. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. |#1#!#)#)#)#)#)#)#)#)#2#3#4#5#. h+. . . . . . # . 6#7#8#9#0#(#a#a#a#a#a#a#b#c#d#e#f#. $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . g#h#!#)#)#)#)#)#)#2#i#j#k#l#m#. + . . . . . Q . n#o#p#q#r#s#a#a#a#a#a#a#a#_#t#u#v#w#. x+. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . x#y#z#)#)#)#)#)#)#A#B#C#D#E#F#. h+. . . . $ . G#H#I#J#K#L#M#b#a#a#a#a#b#N#O#P#Q#R#S#T#. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. U#V#W#)#)#)#)#X#Y#C#Z#`# $.$+$. @ . . . ) . @$#$$$%$&$*$=$(#a#a#a#a#_#-$;$>$,$'$)$!$. x+. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . ~${$y#]$)#)#)#)#^$/$Z#Z#($_$:$. ) . . ) . <$[$}$|$|$%$1$2$3$s#a#a#b#N#4$5$6$,$7$8$9$0$. $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. a$V#W#)#)#X#b$C#Z#Z#Z#Z#c$d$e$. h+. . + f$g$}$|$|$h$i$j$s#_#a#b#c#k$>$,$,$,$,$l$m$n$. x+. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . o$p$q$'#)#r$Z#Z#Z#Z#Z#Z#c$s$t$h+. h+. u$v$$$|$|$|$|$w$x$y$r#s#a#z$A$B$6$,$,$,$,$C$D$E$. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . F$G$'#X#H$C#Z#Z#Z#Z#Z#Z#I$4#J$. K$L$M$N$O$|$|$|$|$|$P$Q$R$0#c#S$P#6$,$,$,$,$,$T$U$V$. $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . W$X$Y$Z$Z#Z#Z#Z#Z#Z#Z#j#`$ %.%. +%@%#%|$|$|$|$|$|$w$1$$%%%&%*%=%,$,$,$,$,$,$,$T$v#-%. ;%>%>%>%>%>%>%>%>%>%>%>%>%% . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . @ . ,%'%)%!%!%!%!%!%!%!%!%!%~%{%]%^%/%(%(%(%(%(%(%(%(%(%h$_%:%<%[%,$>$>$>$>$>$>$>$}%|%1%T#. # . . . . . . . . . . . % . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. 2%3%4%5%5%5%5%5%5%5%5%5%6%7%8%9%0%a%a%a%a%a%a%a%a%b%c%d%e%f%g%h%h%h%h%h%h%h%h%i%j%k%l%m%n%o%o%o%o%o%o%o%o%p%q%r%. % . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . s%t%u%v%w%w%w%w%w%w%w%x%y%z%A%B%C%D%D%D%D%D%D%D%D%E%F%G%H%I%J%K%K%K%K%K%K%K%K%K%L%M%N%O%P%P%P%P%P%P%P%P%P%Q%R%S%. ) . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. T%U%V%W%W%W%W%W%W%W%W%W%X%Y%Z%`% &.&.&.&.&.&.&+&@&#&. $&%&&&*&=&=&=&=&=&=&=&-&;&>&,&'&f%f%f%f%f%f%f%f%f%)&!&~&{&. Q . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . ]&^&V%W%W%W%W%W%/&(&_&:&<&[&.&.&.&.&.&.&.&.&+&}&|&. . 1&2&3&=&=&=&=&=&=&=&4&5&5&5&6&7&8&8&8&8&8&8&8&9&0&a&b&c&}@. # . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . [+. d&e&f&W%W%W%W%W%g&h&i&j&k&l&m&n&o&.&.&.&.&p&q&r&. Q . s&t&u&v&=&=&=&=&=&=&w&x&5&y&z&7&8&8&8&8&8&8&A&B&C&D&E&F&G&. x+. . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. H&I&V%W%W%W%/&(&J&:&K&L&M&N&O&P&.&.&.&Q&R&S&T&. $ x+. U&V&W&=&=&=&=&X&Y&5&5&5&5&y&Z&7&8&8&8&8&8&A&`& *D&.*+*@*#*. % . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ . $*%*&*f&W%/&**=*-*L&L&L&k&;*>*,*o&.&.&'*)*!*. h+. . $ . ~*{*W&=&=&=&=&]*5&5&5&5&y&w&8&8&8&8&8&A&^* *D&D&D&E&/*(*. x+. . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. _*:*<*W%W%[*}*|*K&L&L&L&L&M&1*2* &+&3*4*5*. # . . ) . 6*7*=&=&=&X&8*x&5&5&5&5&5&9*0*a*8&8&8&8&b* *D&D&D&D&c*d*e*. ) . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . f*g*e&f&(&h*|*K&L&L&L&L&i*j*k*2*D%E%q&l*. Q . . . . x+. m*2&n*=&K%5&5&5&5&5&5&5&5&o*p*7&8&A&q* *D&D&D&D&D&r*s*t*. $ . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. u*v*w*x*y*-*L&L&L&L&L&L&i*j*z*A*B*C*. + . . . . . $ . D*E*F*G*H*x&5&5&5&5&5&5&5&y&I*7&A&7&C&D&D&D&D&D&D&D&J*K*L*. Q . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . M*N*O*P*Q*R*R*R*R*R*R*R*S*T*E%U*V*. ) . . . . . . >%. W*X*Y*Z*Z*Z*Z*Z*Z*Z*Z*Z*Z*`* =.=+=@=J*J*J*J*J*J*J*#=$=%=&=. # . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . *===-=;=>=>=>=>=>=>=>=>=,='=)=!=. Q . . . . . . . . . ~={=]=^=/=/=/=/=/=/=/=/=/=(=_=:=<=F&F&F&F&F&F&F&F&F&s*[=}=. Q . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ . |=1=2=3=3=3=3=3=3=3=3=3=4=5=6=. # . . . . . . . . $ . 7=8=9=0=0=0=0=0=0=0=0=0=0=a=b=c=d=d=d=d=d=d=d=d=d=e=f=g=) . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . . . . . . . . . . . . . . + . . . . . . . . . . . # $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+0+0+0+0+0+0+0+0+0+0+0+0+0++ . . . . . . . . . . . . ) >%>%>%>%>%>%>%>%>%>%>%>%>%>%x+x+x+x+x+x+x+x+x+x+x+x+x+. . . . . . . . . . . ", -" . . . . . . . . . . . . . . . h=i=i=. . . . $ i=i=$ . . . . . . . . . . . . . . . . . . . . . . . . . . i=i=$ $ h=i=. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ h=. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h=h=. . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . $ . j=k=l=m=. i=. n=o=k=p=. h=. . . . . . . . . . . . . . . . . . . . . $ h=. q=r=s=t=u=v=. $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . w=. x=y=z=A=. B=. C=y=D=E=. F=G=h=i=i=. . $ w=i=$ G=h=. i=w=h=h=w=h=. $ . H=r=I=J=K=L=M=N=. w=i=$ w=$ h=w=$ . . . i=i=. i=h=$ w=i=w=$ . $ $ O=P=. w=. . . . . . . . . . . . . ", -" . . . . . . . . . . . h=. Q=R=S=T=. i=. u=D=U=. h=$ . . . . h=. . . . $ . . . . . . . . $ $ $ . V=W=X=. h=. . . . . $ $ . . . . $ . . . . . . . $ $ . . . $ h=. . Y=k=. w=. . . . . . . . . . . . . ", -" . . . . . . . . . . $ . h=Z=`= -i=. .-+-`=@-. . #-$-%-&-*-. . =---;->-,-'-. )-N=!-!-C=~-. . {-]-^-. F=w=w=w=i=. /-(-_-:-<-#-[-}-. h=. |-1-. 2-)-3---4-@-5-. >-6-7-u=8-9-. $ . . . . . . . . . . ", -" . . . . . . . . . . . i=. 0-`=R=a-. b-`=R=c-. d-e-f-g-h-i-j-. k-y=l-m-y=n-. o-y=p-`=q-r-s-. t-u->-. $ . . . w=. v-w-x-y-z-A-y=B-. $ C-g-!-. D-E-E-F-G-H-I-J-3-K-L-M-N-[-. h=. . . . . . . . . . ", -" . . . . . . . . . . h=. O-u-P-L=. Q-h-R-. S-+-T-U-. b-V-W-. X-Y-+-y-Z-`-. ;.;h=E=+;h-C=. @;#;. . . . . . w=. $;%;&;. $ . *;=;. . A=-;;;. >;I=k-. . .;,;';. . );!;. G=. . . . . . . . . . . ", -" . . . . . . . . . . $ . B=s=z=~;{;];^;/;. 1-I=);(; ;_;R=u-:;P=<;[;};. i=. H=|;1;2;3;i-1;. 4;M-. . . . . . w=. _;D=:;. B=. /;H-5;. 6;M-. . 4;7;. w=B=. 4-Y=. . l-8;. B=. . . . . . . . . . . ", -" . . . . . . . . . . i=. --q-9;0;T-a;b;. '-D=R=c;y=d;i-e;b;f;H-[;k-. $ g;h;i;j;k;l;D=K-. !;g-m;. $ . . . w=. n;u-5-. i=. o;[;p;. q;r;. . x-s;. h=i=. t-t;C-. l-8;. i=. . . . . . . . . . ", -" . . . . . . . . . i=. u;S=v;w;`=x;. . y;z;A;B;C;p=*-D;i=E;T-H-F;. . G;H;+;I;. J;e;>;. K;y=L;. F=w=w=i=F=. n;M;m;. $ h=. F-N;O;P;o;. . Z-Q;. R;C-. S;+;. . );!;. B=. . . . . . . . . ", -" . . . . . . . . . $ . {;#;T;U;V;W;. . X;<;u-C=o;Y;Z;`;. *-T;Y- >. . .>,;+>o;@>v;[;#>. h=$>H-;;. h=. . w=. _;g-%>. $ i=. &>*>k;=>. F=. ->M;~-. . ;>Y-,-. . Y=>>. i=. . . . . . . . . ", -" . . . . . . . . . i=. ,>y=e-H-'>. w=. )>,;!>I=[;y=~>. {>]>i; ;. . &>^>D=/>S=T;y=(>. . _>:>h-J=<>K=[>}>. |>z=5-. $ $ . i=u=e;B;. F=. =>M;h;1>2>3;w-3>. . 4>S=C=B;. h=. . . . . . ", -" . . . . . . . . . h=. @>5>6>1>. . . $ . 7>!;8>w;8;&>. O=$-9>0>. i=. a>b>x;c>d>k=L=. h=. B=9-[>E-e>f>9-. {>}>{;. $ . B=. r=W-. . i=. m-(>g>h>i>$-j>. h=. S-k>l>m>. i=. . . . . . ", -" . . . . . . . . . . $ . . . $ . . . h=. . . . . . . . . . . . . $ . . . . . . . . . n>$ . . . . . . . . . . . . h=. o>`=p>. i=h=. q>R-. h=. . $ $ . . $ . . . . . . . . . . ", -" . . . . . . . . . . $ i=i=i=. . . . . i=i=h=h=G=i=. $ G=G=$ . . . i=h=h=i=r>G=r>. . . $ i=i=$ $ i=i=. h=G=. . . $ s>T-w;. $ . h=. R-e>. F=$ w=h=. . . $ i=$ h=. . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ . ;>M;t>{;. $ . h=. u>k>. h=. . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i=v>$ $ $ . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h=$ . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h=. . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" "}; +/* XPM */ +static const char *VeraCryptIcon128x128[] = { +"128 128 1165 2", +" c None", +". c #FFFFFF", +"+ c #FEFEFF", +"@ c #FDFEFF", +"# c #FEFFFF", +"$ c #FEFEFE", +"% c #FEFFFE", +"& c #75D0E9", +"* c #3EBDE0", +"= c #4BC2E2", +"- c #48C1E2", +"; c #49C1E2", +"> c #43C0E2", +", c #5CC5E4", +"' c #F3FAFC", +") c #FDFEFE", +"! c #BDE4D8", +"~ c #89CCB6", +"{ c #93D0BC", +"] c #91D0BB", +"^ c #90CFBB", +"/ c #A7D8C7", +"( c #B3DCCD", +"_ c #B1DBCC", +": c #B2DBCD", +"< c #AEDACA", +"[ c #C0E2D5", +"} c #FCFEFF", +"| c #B4E5F3", +"1 c #00A3D4", +"2 c #01A8D6", +"3 c #00A7D6", +"4 c #03A7D6", +"5 c #009DCF", +"6 c #8CD5EA", +"7 c #FBFEFE", +"8 c #EDF8F4", +"9 c #58BB9F", +"0 c #55B899", +"a c #66BDA0", +"b c #63BC9F", +"c c #61BB9E", +"d c #6DBFA4", +"e c #81C6AE", +"f c #8FCCB5", +"g c #91CCB6", +"h c #90CCB6", +"i c #92CDB7", +"j c #8ACAB2", +"k c #D7EDE5", +"l c #5EC8E5", +"m c #0FADD9", +"n c #0BACD8", +"o c #0BACD9", +"p c #10A9D6", +"q c #0DA5D2", +"r c #18AAD5", +"s c #E2F4FA", +"t c #95D4C1", +"u c #46B494", +"v c #58BB9E", +"w c #6BBFA4", +"x c #6DC0A5", +"y c #6EC0A5", +"z c #85C8B1", +"A c #86C9B2", +"B c #8DCBB5", +"C c #98D0BB", +"D c #97D0BB", +"E c #98D1BC", +"F c #91CDB7", +"G c #DBF3F9", +"H c #11ADD9", +"I c #06AAD8", +"J c #09ABD8", +"K c #08ABD8", +"L c #09AAD7", +"M c #0EA6D3", +"N c #12A7D4", +"O c #00A0D0", +"P c #67C7E3", +"Q c #FCFEFE", +"R c #D8EFE8", +"S c #4FB899", +"T c #53B99B", +"U c #50B99A", +"V c #5CBC9F", +"W c #6DBFA5", +"X c #69BEA3", +"Y c #79C4AB", +"Z c #87C9B2", +"` c #92CDB8", +" . c #97CFBA", +".. c #96CFBA", +"+. c #95CFB9", +"@. c #EAF5F1", +"#. c #81D4EB", +"$. c #00A5D5", +"%. c #0CACD9", +"&. c #0CA7D4", +"*. c #0FA6D3", +"=. c #08A4D2", +"-. c #C5EAF4", +";. c #7CCAB3", +">. c #49B596", +",. c #54BA9C", +"'. c #52B99B", +"). c #66BEA2", +"!. c #6CBFA4", +"~. c #6ABFA3", +"{. c #6FC0A6", +"]. c #84C8B1", +"^. c #89CAB3", +"/. c #C2E3D7", +"(. c #F2FBFD", +"_. c #28B5DC", +":. c #01A8D7", +"<. c #0AACD8", +"[. c #0AA9D6", +"}. c #11A7D4", +"|. c #02A1D1", +"1. c #45BADD", +"2. c #C0E5DB", +"3. c #48B595", +"4. c #58BB9D", +"5. c #7DC5AD", +"6. c #84C8B0", +"7. c #90CCB7", +"8. c #97CFBB", +"9. c #94CEB9", +"0. c #9ED2BF", +"a. c #F5FBF9", +"b. c #A6E1F1", +"c. c #00A6D6", +"d. c #0DA7D4", +"e. c #A3DDEE", +"f. c #F6FBFA", +"g. c #66C1A7", +"h. c #4DB798", +"i. c #53BA9C", +"j. c #63BDA1", +"k. c #72C2A8", +"l. c #86C8B2", +"m. c #95CFBA", +"n. c #D2EAE1", +"o. c #46BFE1", +"p. c #0BA8D5", +"q. c #10A7D3", +"r. c #28AFD8", +"s. c #F1FAFC", +"t. c #A6DBCB", +"u. c #55BA9D", +"v. c #51B99B", +"w. c #55BA9C", +"x. c #81C6AF", +"y. c #A9D8C6", +"z. c #C8ECF6", +"A. c #06A9D7", +"B. c #12A8D4", +"C. c #7ED0E8", +"D. c #E6F5F0", +"E. c #56BB9D", +"F. c #50B89A", +"G. c #5EBCA0", +"H. c #76C3AA", +"I. c #E1F1EB", +"J. c #69CCE7", +"K. c #0CADD9", +"L. c #0CA8D5", +"M. c #0DA5D3", +"N. c #D8F1F8", +"O. c #8CD0BC", +"P. c #47B495", +"Q. c #68BEA3", +"R. c #86C8B1", +"S. c #8BCAB4", +"T. c #99D0BC", +"U. c #8FCCB6", +"V. c #B7DED0", +"W. c #E4F6FB", +"X. c #18B0DA", +"Y. c #06A8D6", +"Z. c #00A1D0", +"`. c #5AC2E1", +" + c #D0ECE4", +".+ c #4CB697", +"++ c #5CBB9F", +"@+ c #84C7B0", +"#+ c #EEF7F4", +"$+ c #8FD8ED", +"%+ c #00A1D1", +"&+ c #13A7D3", +"*+ c #11A7D3", +"=+ c #05A2D1", +"-+ c #BAE5F2", +";+ c #73C6AF", +">+ c #4AB697", +",+ c #4FB89A", +"'+ c #68BFA3", +")+ c #8CCBB5", +"!+ c #89CAB4", +"~+ c #8ACAB4", +"{+ c #C9E6DC", +"]+ c #F9FDFE", +"^+ c #3DACD8", +"/+ c #1099CF", +"(+ c #1B9ED1", +"_+ c #199DD1", +":+ c #0F99CF", +"<+ c #47A7D7", +"[+ c #FDFDFE", +"}+ c #ABE0D3", +"|+ c #35B291", +"1+ c #49B89B", +"2+ c #46B799", +"3+ c #48B89A", +"4+ c #3CB394", +"5+ c #BAE4D8", +"6+ c #FBFDFB", +"7+ c #F0F8F5", +"8+ c #F2F9F6", +"9+ c #F1F9F6", +"0+ c #FBFDFD", +"a+ c #B7E0F1", +"b+ c #0F97CF", +"c+ c #1D9DD1", +"d+ c #1A9CD1", +"e+ c #2199D1", +"f+ c #1584C9", +"g+ c #9FCEE9", +"h+ c #FCFDFE", +"i+ c #EFF9F7", +"j+ c #43B99D", +"k+ c #33B293", +"l+ c #46B89A", +"m+ c #44B799", +"n+ c #47B89A", +"o+ c #3AB393", +"p+ c #73C9B3", +"q+ c #5DB9DE", +"r+ c #0D96CE", +"s+ c #1D9DD2", +"t+ c #2390CE", +"u+ c #1F8ACC", +"v+ c #3295D0", +"w+ c #EBF4FA", +"x+ c #FCFEFD", +"y+ c #8CD4C3", +"z+ c #25AE8D", +"A+ c #36B496", +"B+ c #3FB698", +"C+ c #45B799", +"D+ c #41B698", +"E+ c #D7F0E9", +"F+ c #D5EDF7", +"G+ c #1B9CD1", +"H+ c #199CD1", +"I+ c #1E95CF", +"J+ c #248CCD", +"K+ c #278FCE", +"L+ c #1485C9", +"M+ c #7EBCE1", +"N+ c #D9F1EB", +"O+ c #33B394", +"P+ c #35B495", +"Q+ c #47B89B", +"R+ c #37B292", +"S+ c #8ED4C2", +"T+ c #7FC8E5", +"U+ c #0A95CE", +"V+ c #1E9ED2", +"W+ c #1B9BD1", +"X+ c #238ECD", +"Y+ c #238DCD", +"Z+ c #218CCC", +"`+ c #D2E8F5", +" @ c #6DC9B3", +".@ c #27AF8E", +"+@ c #32B394", +"@@ c #3CB596", +"#@ c #45B79A", +"$@ c #41B697", +"%@ c #4FBB9F", +"&@ c #ECF8F5", +"*@ c #EEF8FC", +"=@ c #2EA5D5", +"-@ c #159AD0", +";@ c #1B9DD1", +">@ c #2093CF", +",@ c #268FCE", +"'@ c #1787CA", +")@ c #5DABDA", +"!@ c #BEE7DD", +"~@ c #29AF8F", +"{@ c #34B394", +"]@ c #42B798", +"^@ c #ABDFD1", +"/@ c #A2D7EC", +"(@ c #0B95CE", +"_@ c #1A9DD1", +":@ c #1C99D0", +"<@ c #268ECE", +"[@ c #B5D8EE", +"}@ c #F9FDFC", +"|@ c #53BEA5", +"1@ c #2BB090", +"2@ c #39B596", +"3@ c #3DB495", +"4@ c #63C3AA", +"5@ c #FBFEFD", +"6@ c #49B0DA", +"7@ c #2190CE", +"8@ c #258ECD", +"9@ c #1C89CB", +"0@ c #419DD4", +"a@ c #F7FBFD", +"b@ c #A0DBCD", +"c@ c #25AE8C", +"d@ c #37B496", +"e@ c #40B698", +"f@ c #3BB494", +"g@ c #C6E9E0", +"h@ c #C3E5F3", +"i@ c #1299CF", +"j@ c #1C9CD1", +"k@ c #1D97D0", +"l@ c #1385CA", +"m@ c #93C7E7", +"n@ c #E8F6F3", +"o@ c #3DB799", +"p@ c #30B292", +"q@ c #34B395", +"r@ c #37B495", +"s@ c #39B393", +"t@ c #7CCDB8", +"u@ c #69BEE1", +"v@ c #0B96CE", +"w@ c #1E9DD2", +"x@ c #228FCD", +"y@ c #248DCD", +"z@ c #208CCC", +"A@ c #2B91CF", +"B@ c #E3F0F9", +"C@ c #80CFBC", +"D@ c #25AD8C", +"E@ c #36B395", +"F@ c #32B293", +"G@ c #3EB597", +"H@ c #44B698", +"I@ c #45B89A", +"J@ c #DFF3EE", +"K@ c #E0F1F9", +"L@ c #20A0D3", +"M@ c #1C94CF", +"N@ c #1486CA", +"O@ c #72B6DF", +"P@ c #D1EFE8", +"Q@ c #2FB595", +"R@ c #35B697", +"S@ c #34B697", +"T@ c #33B697", +"U@ c #39B899", +"V@ c #37B494", +"W@ c #98D7C6", +"X@ c #8DCAE7", +"Y@ c #1385C9", +"Z@ c #288ECD", +"`@ c #248CCC", +" # c #258CCC", +".# c #1E88CB", +"+# c #C9E2F2", +"@# c #60B8A1", +"## c #25A182", +"$# c #33A689", +"%# c #30A588", +"&# c #31A689", +"*# c #2AA384", +"=# c #4AB196", +"-# c #F3FBF9", +";# c #F5F9FC", +"># c #4395CE", +",# c #2182C5", +"'# c #2A87C7", +")# c #2886C7", +"!# c #2B88C8", +"~# c #1D7EC3", +"{# c #5196CC", +"]# c #B2E1E6", +"^# c #197B71", +"/# c #236349", +"(# c #216750", +"_# c #21664E", +":# c #22674F", +"<# c #1F634B", +"[# c #2D8B70", +"}# c #D6EFE8", +"|# c #B2D4EB", +"1# c #1B7FC4", +"2# c #2887C8", +"3# c #277FC2", +"4# c #116DB7", +"5# c #A8CAE5", +"6# c #F4FAFA", +"7# c #45B0B8", +"8# c #269EA6", +"9# c #246D57", +"0# c #21664D", +"a# c #21674F", +"b# c #216850", +"c# c #20644D", +"d# c #27765D", +"e# c #239B7B", +"f# c #63B7A0", +"g# c #5EA4D5", +"h# c #1D80C4", +"i# c #2783C5", +"j# c #2178BC", +"k# c #1A73BA", +"l# c #3685C3", +"m# c #F1F6FB", +"n# c #92D0D4", +"o# c #1E9CA5", +"p# c #32AAB5", +"q# c #288C87", +"r# c #206348", +"s# c #216851", +"t# c #2C9477", +"u# c #32A385", +"v# c #23997A", +"w# c #B8DED4", +"x# c #D0E5F3", +"y# c #2484C6", +"z# c #2986C7", +"A# c #2887C7", +"B# c #227BBF", +"C# c #1F76BB", +"D# c #247ABD", +"E# c #106DB7", +"F# c #86B5DB", +"G# c #DFF1F3", +"H# c #31A6AF", +"I# c #2BA3AC", +"J# c #2EA4AD", +"K# c #2DA5AF", +"L# c #237362", +"M# c #20644B", +"N# c #20634B", +"O# c #277E63", +"P# c #30A384", +"Q# c #319F81", +"R# c #289C7D", +"S# c #4CAC93", +"T# c #F8FCFB", +"U# c #7DB6DD", +"V# c #197EC3", +"W# c #2C88C8", +"X# c #2987C8", +"Y# c #2581C4", +"Z# c #2077BC", +"`# c #2177BC", +" $ c #1F76BC", +".$ c #2378BD", +"+$ c #DAE8F4", +"@$ c #72C2C8", +"#$ c #209EA8", +"$$ c #30A5AE", +"%$ c #2DA3AC", +"&$ c #2EA7B2", +"*$ c #2A9595", +"=$ c #21654B", +"-$ c #226B52", +";$ c #2E9B7D", +">$ c #2FA082", +",$ c #2F9F81", +"'$ c #33A183", +")$ c #209878", +"!$ c #9BD1C2", +"~$ c #E9F3F9", +"{$ c #358DCA", +"]$ c #2987C7", +"^$ c #2179BD", +"/$ c #2076BC", +"($ c #2379BD", +"_$ c #126FB8", +":$ c #65A1D1", +"<$ c #C5E6E8", +"[$ c #25A0AA", +"}$ c #2FA5AE", +"|$ c #2DA4AD", +"1$ c #2EA8B3", +"2$ c #257C6F", +"3$ c #206349", +"4$ c #29876C", +"5$ c #30A385", +"6$ c #2F9E80", +"7$ c #309F82", +"8$ c #2C9E7F", +"9$ c #39A387", +"0$ c #E7F4F0", +"a$ c #9EC8E6", +"b$ c #247EC2", +"c$ c #2278BD", +"d$ c #1671B9", +"e$ c #BDD7EB", +"f$ c #55B5BD", +"g$ c #24A0A9", +"h$ c #2DA4AC", +"i$ c #2DA6B0", +"j$ c #2C9DA1", +"k$ c #247158", +"l$ c #32A183", +"m$ c #219878", +"n$ c #7EC4B1", +"o$ c #FBFDFE", +"p$ c #4C9AD0", +"q$ c #1F81C5", +"r$ c #2784C6", +"s$ c #1771B9", +"t$ c #478FC7", +"u$ c #A6D9DC", +"v$ c #1F9EA7", +"w$ c #2DA3AB", +"x$ c #2EA8B4", +"y$ c #27857E", +"z$ c #21654D", +"A$ c #2C9074", +"B$ c #30A284", +"C$ c #309F81", +"D$ c #2B9D7F", +"E$ c #D1EAE3", +"F$ c #BEDAEE", +"G$ c #1E80C4", +"H$ c #237CC0", +"I$ c #2479BD", +"J$ c #9CC3E1", +"K$ c #FFFEFF", +"L$ c #EDF7F8", +"M$ c #3DABB3", +"N$ c #29A2AB", +"O$ c #2EA5AE", +"P$ c #2DA5AE", +"Q$ c #2DA3AA", +"R$ c #226E5A", +"S$ c #267A60", +"T$ c #32A083", +"U$ c #249A7A", +"V$ c #63B7A1", +"W$ c #69AAD8", +"X$ c #1C80C4", +"Y$ c #2A84C5", +"Z$ c #2076BB", +"`$ c #1C74BB", +" % c #2E7FC0", +".% c #E6F0F7", +"+% c #85CAD0", +"@% c #1E9DA7", +"#% c #31A6AE", +"$% c #298F8D", +"%% c #216349", +"&% c #226951", +"*% c #2D987B", +"=% c #2FA182", +"-% c #B7DED4", +";% c #F9FCFB", +">% c #FCFDFD", +",% c #DAEAF5", +"'% c #2A87C8", +")% c #207BBF", +"!% c #1F78BD", +"~% c #237ABE", +"{% c #0E6EB7", +"]% c #81B2DA", +"^% c #E3F5F3", +"/% c #29A3AC", +"(% c #2DA5AD", +"_% c #2EA8B1", +":% c #227363", +"<% c #278265", +"[% c #31A587", +"}% c #31A183", +"|% c #289D7E", +"1% c #4CAD93", +"2% c #87B5DB", +"3% c #1467B3", +"4% c #2874B9", +"5% c #2472B8", +"6% c #2171B7", +"7% c #2E76BB", +"8% c #4DA7BA", +"9% c #289FAC", +"0% c #30A0AF", +"a% c #2EA0AE", +"b% c #2EA0AD", +"c% c #2CA1B1", +"d% c #329A9F", +"e% c #35997B", +"f% c #319B7E", +"g% c #2C987A", +"h% c #2D987A", +"i% c #2F997C", +"j% c #239374", +"k% c #7FBFAD", +"l% c #B9DDD4", +"m% c #AFD8CD", +"n% c #ACD6CB", +"o% c #AAD5CA", +"p% c #ABD6CA", +"q% c #A5D4C7", +"r% c #E2F3EF", +"s% c #F0F4F9", +"t% c #3E76B7", +"u% c #2664AE", +"v% c #2C69B1", +"w% c #2B68B0", +"x% c #2A68AF", +"y% c #2D69B5", +"z% c #1F639C", +"A% c #127187", +"B% c #339BB3", +"C% c #2E96AE", +"D% c #2F97AF", +"E% c #3299B0", +"F% c #1F8FA8", +"G% c #B1D8E4", +"H% c #7FB9A5", +"I% c #198364", +"J% c #2D8E71", +"K% c #2A8C6F", +"L% c #2B8C6F", +"M% c #1E8464", +"N% c #1F9071", +"O% c #209374", +"P% c #209273", +"Q% c #239273", +"R% c #139474", +"S% c #67C4B0", +"T% c #A9C3E0", +"U% c #1C60AC", +"V% c #2D6BB2", +"W% c #2A69B1", +"X% c #126783", +"Y% c #0C6375", +"Z% c #258AA1", +"`% c #319BB2", +" & c #2F97AE", +".& c #2F98AF", +"+& c #3199B0", +"@& c #2694AC", +"#& c #55ABBD", +"$& c #E1EFEB", +"%& c #309074", +"&& c #288C6F", +"*& c #2B8D71", +"=& c #2A8D70", +"-& c #2A8E71", +";& c #288A6C", +">& c #298667", +",& c #2D9073", +"'& c #329C7F", +")& c #319B7F", +"!& c #30AC90", +"~& c #20A88A", +"{& c #BCE4DB", +"]& c #5788C1", +"^& c #2062AD", +"/& c #2A69B0", +"(& c #2C69B5", +"_& c #1D6798", +":& c #0B6576", +"<& c #0C6379", +"[& c #136E83", +"}& c #2794AC", +"|& c #C5E2E9", +"1& c #93C5B6", +"2& c #1B8566", +"3& c #2E8F73", +"4& c #298C6F", +"5& c #278768", +"6& c #2C9678", +"7& c #2E9A7D", +"8& c #2E997C", +"9& c #2E977A", +"0& c #2CA386", +"a& c #2DAE92", +"b& c #23A98B", +"c& c #4CB9A0", +"d& c #C8D8EB", +"e& c #2364AE", +"f& c #2B6AB1", +"g& c #2B69B2", +"h& c #2769AC", +"i& c #0E657D", +"j& c #0C6579", +"k& c #0E667B", +"l& c #0A6176", +"m& c #208298", +"n& c #329CB3", +"o& c #2E97AE", +"p& c #329AB0", +"q& c #2292AA", +"r& c #73BAC9", +"s& c #F5FAF8", +"t& c #449B82", +"u& c #248A6B", +"v& c #2C8E71", +"w& c #28896B", +"x& c #278767", +"y& c #278667", +"z& c #298C6D", +"A& c #2E987B", +"B& c #2E9B7E", +"C& c #2BAB8E", +"D& c #2BAC8F", +"E& c #2FAD91", +"F& c #1CA687", +"G& c #9CD8CB", +"H& c #749DCC", +"I& c #1C5FAC", +"J& c #18678F", +"K& c #0D657B", +"L& c #0D657A", +"M& c #0C6479", +"N& c #0F687D", +"O& c #2C94AB", +"P& c #3099B0", +"Q& c #3098AF", +"R& c #2D97AE", +"S& c #339AB1", +"T& c #DFEFF3", +"U& c #B3D6CC", +"V& c #1D8667", +"W& c #2D8F72", +"X& c #2A8D71", +"Y& c #298B6E", +"Z& c #2C9376", +"`& c #2CA689", +" * c #2BAD90", +".* c #2CAC90", +"+* c #28AB8D", +"@* c #36B095", +"#* c #E7F6F2", +"$* c #E3EBF5", +"%* c #316EB4", +"&* c #2867B0", +"** c #2C69B4", +"=* c #2468A5", +"-* c #0C6578", +";* c #0B6176", +">* c #1B7A90", +",* c #319CB3", +"'* c #339AB0", +")* c #2091A9", +"!* c #92C9D5", +"~* c #5FA994", +"{* c #1F8769", +"]* c #288869", +"^* c #2D9E81", +"/* c #1DA687", +"(* c #7CCBBA", +"_* c #95B4D8", +":* c #1B5EAB", +"<* c #2E6CB2", +"[* c #2B69B3", +"}* c #146687", +"|* c #0B6577", +"1* c #288EA5", +"2* c #309AB1", +"3* c #2995AD", +"4* c #47A4B8", +"5* c #F4F9FB", +"6* c #D1E6E0", +"7* c #278B6E", +"8* c #298A6C", +"9* c #278666", +"0* c #2A9072", +"a* c #2E9A7E", +"b* c #2CA88B", +"c* c #2CAC8F", +"d* c #27AA8D", +"e* c #CFECE5", +"f* c #F6F9FC", +"g* c #467DBB", +"h* c #1F679D", +"i* c #0D667B", +"j* c #0B6277", +"k* c #167287", +"l* c #B2D9E1", +"m* c #7EBAA8", +"n* c #2E8F72", +"o* c #278869", +"p* c #2D977A", +"q* c #2DA184", +"r* c #2EAD90", +"s* c #20A889", +"t* c #5DC0AA", +"u* c #B5CBE4", +"v* c #1E60AD", +"w* c #2D6BB3", +"x* c #2969AF", +"y* c #106580", +"z* c #24879D", +"A* c #349DB4", +"B* c #2492AA", +"C* c #60B0C2", +"D* c #E9F3F0", +"E* c #379478", +"F* c #268B6D", +"G* c #2B8E71", +"H* c #288A6B", +"I* c #2A8E6F", +"J* c #2EAD91", +"K* c #1EA788", +"L* c #B1E0D6", +"M* c #608FC4", +"N* c #2262B2", +"O* c #226C98", +"P* c #0E6778", +"Q* c #12677D", +"R* c #11677C", +"S* c #10667A", +"T* c #156E83", +"U* c #2B96AE", +"V* c #CFE7EC", +"W* c #9FCBBE", +"X* c #1B8667", +"Y* c #308F73", +"Z* c #2A896A", +"`* c #2A886A", +" = c #30977A", +".= c #329A7E", +"+= c #2FA588", +"@= c #2EAF92", +"#= c #30AE92", +"$= c #28AB8E", +"%= c #47B79E", +"&= c #F5FBFA", +"*= c #D5E1F1", +"== c #1C62A3", +"-= c #005971", +";= c #015A71", +">= c #005A71", +",= c #005B72", +"'= c #01586E", +")= c #026E87", +"!= c #80C2D0", +"~= c #FBFDFC", +"{= c #4C9F86", +"]= c #107B5A", +"^= c #1A805E", +"/= c #187F5D", +"(= c #187E5D", +"_= c #198261", +":= c #1E9677", +"<= c #1CA787", +"[= c #0CA07F", +"}= c #83CEBE", +"|= c #B2CDD9", +"1= c #8FB8C1", +"2= c #96BDC6", +"3= c #95BCC5", +"4= c #95BBC4", +"5= c #94BCC6", +"6= c #E9F4F6", +"7= c #D4E8E2", +"8= c #9AC7B8", +"9= c #A1CBBE", +"0= c #A0CABD", +"a= c #A0C9BC", +"b= c #A2D5C9", +"c= c #A2DCCF", +"d= c #A2DBCE", +"e= c #A3DBCE", +"f= c #A0DACD", +"g= c #AADED2", +"h= c #FDFDFD", +"i= c #FCFCFC", +"j= c #939392", +"k= c #696968", +"l= c #797978", +"m= c #F0F0F0", +"n= c #D3D3D3", +"o= c #6D6D6C", +"p= c #C1C1C0", +"q= c #BEBEBE", +"r= c #626261", +"s= c #3E3E3C", +"t= c #3C3C3A", +"u= c #484846", +"v= c #9F9F9E", +"w= c #FBFBFB", +"x= c #7F7F7E", +"y= c #000000", +"z= c #080806", +"A= c #BBBBBA", +"B= c #F9F9F9", +"C= c #80807F", +"D= c #0E0E0C", +"E= c #CDCDCC", +"F= c #FAFAFA", +"G= c #FCFCFB", +"H= c #F7F7F7", +"I= c #090907", +"J= c #515150", +"K= c #8D8D8C", +"L= c #989898", +"M= c #656563", +"N= c #818180", +"O= c #DBDBDB", +"P= c #CECECE", +"Q= c #D0D0CF", +"R= c #1F1F1D", +"S= c #11110F", +"T= c #7C7C7B", +"U= c #4E4E4C", +"V= c #686866", +"W= c #0C0C0B", +"X= c #C4C4C4", +"Y= c #31312F", +"Z= c #434341", +"`= c #0D0D0B", +" - c #434342", +".- c #D6D6D6", +"+- c #20201E", +"@- c #90908F", +"#- c #CCCCCB", +"$- c #757574", +"%- c #585857", +"&- c #6E6E6D", +"*- c #C5C5C4", +"=- c #DADADA", +"-- c #7B7B7A", +";- c #9E9E9E", +">- c #ECECEC", +",- c #747473", +"'- c #838382", +")- c #C6C6C5", +"!- c #5E5E5D", +"~- c #DEDEDE", +"{- c #CBCBCA", +"]- c #040402", +"^- c #A0A09F", +"/- c #C1C1C1", +"(- c #A9A9A8", +"_- c #F5F5F4", +":- c #737371", +"<- c #AFAFAE", +"[- c #8E8E8D", +"}- c #F3F3F3", +"|- c #B2B2B1", +"1- c #9C9C9B", +"2- c #A5A5A4", +"3- c #EAEAEA", +"4- c #5F5F5D", +"5- c #EDEDED", +"6- c #888886", +"7- c #252523", +"8- c #888885", +"9- c #ABABAA", +"0- c #828281", +"a- c #D2D2D1", +"b- c #979796", +"c- c #D2D2D2", +"d- c #A3A3A2", +"e- c #10100E", +"f- c #070706", +"g- c #1C1C1A", +"h- c #070705", +"i- c #0F0F0D", +"j- c #AAAAA9", +"k- c #B7B7B6", +"l- c #2F2F2E", +"m- c #51514F", +"n- c #3F3F3E", +"o- c #272726", +"p- c #191916", +"q- c #060604", +"r- c #2A2A28", +"s- c #DDDDDC", +"t- c #7D7D7C", +"u- c #191917", +"v- c #7E7E7D", +"w- c #2C2C2A", +"x- c #525250", +"y- c #161614", +"z- c #A7A7A6", +"A- c #C2C2C2", +"B- c #B1B1B0", +"C- c #F8F8F8", +"D- c #3D3D3B", +"E- c #41413F", +"F- c #595958", +"G- c #6C6C6A", +"H- c #131311", +"I- c #343433", +"J- c #F1F1F1", +"K- c #5B5B5A", +"L- c #222220", +"M- c #373735", +"N- c #565655", +"O- c #C7C7C7", +"P- c #0F0F0C", +"Q- c #575756", +"R- c #4C4C4A", +"S- c #E3E3E3", +"T- c #151513", +"U- c #B4B4B3", +"V- c #0B0B09", +"W- c #343432", +"X- c #C6C6C6", +"Y- c #171715", +"Z- c #525251", +"`- c #8E8E8C", +" ; c #B2B2B2", +".; c #D5D5D5", +"+; c #30302F", +"@; c #555554", +"#; c #353534", +"$; c #9B9B9A", +"%; c #030301", +"&; c #767674", +"*; c #353533", +"=; c #575755", +"-; c #0D0D0A", +";; c #CACAC9", +">; c #5E5E5C", +",; c #0C0C0A", +"'; c #777776", +"); c #30302E", +"!; c #717170", +"~; c #646463", +"{; c #F5F5F5", +"]; c #2B2B29", +"^; c #0A0A07", +"/; c #8F8F8E", +"(; c #A8A8A7", +"_; c #949493", +":; c #DFDFDF", +"<; c #141412", +"[; c #121210", +"}; c #848482", +"|; c #A2A2A1", +"1; c #5F5F5E", +"2; c #474745", +"3; c #262624", +"4; c #545452", +"5; c #E2E2E2", +"6; c #666664", +"7; c #3E3E3D", +"8; c #70706F", +"9; c #40403F", +"0; c #B0B0AF", +"a; c #1E1E1D", +"b; c #D4D4D4", +"c; c #030303", +"d; c #040403", +"e; c #050503", +"f; c #D0D0D0", +"g; c #E8E8E7", +"h; c #383836", +"i; c #020200", +"j; c #141413", +"k; c #424240", +"l; c #2B2B2A", +"m; c #EEEEEE", +"n; c #929291", +"o; c #E4E4E4", +"p; c #999998", +"q; c #1E1E1C", +"r; c #919190", +"s; c #4A4A48", +"t; c #232321", +"u; c #C0C0C0", +"v; c #292927", +"w; c #585856", +"x; c #4E4E4D", +"y; c #939393", +"z; c #0A0A08", +"A; c #2E2E2C", +"B; c #BBBBBB", +"C; c #C9C9C8", +"D; c #BCBCBB", +"E; c #C8C8C8", +"F; c #B6B6B6", +"G; c #878786", +"H; c #050502", +"I; c #DCDCDB", +"J; c #535351", +"K; c #B5B5B4", +"L; c #A6A6A5", +"M; c #181816", +"N; c #4B4B49", +"O; c #BDBDBC", +"P; c #181815", +"Q; c #474746", +"R; c #FAFAF9", +"S; c #656564", +"T; c #1A1A18", +"U; c #242423", +"V; c #10100D", +"W; c #959594", +"X; c #D1D1D0", +"Y; c #EEEEED", +"Z; c #CFCFCF", +"`; c #D6D6D5", +" > c #B9B9B8", +".> c #71716F", +"+> c #313130", +"@> c #CBCBCB", +"#> c #616160", +"$> c #484847", +"%> c #EFEFEF", +"&> c #BABAB9", +"*> c #212120", +"=> c #5D5D5B", +"-> c #5C5C5B", +";> c #E8E8E8", +">> c #6B6B69", +",> c #6F6F6E", +"'> c #DBDBDA", +")> c #8A8A89", +"!> c #020201", +"~> c #575757", +"{> c #BDBDBD", +"]> c #060603", +"^> c #0C0C09", +"/> c #131312", +"(> c #50504F", +"_> c #E6E6E6", +":> c #444442", +"<> c #858584", +"[> c #5B5B59", +"}> c #767675", +"|> c #888887", +"1> c #8C8C8B", +"2> c #979795", +"3> c #E9E9E9", +"4> c #626260", +"5> c #6B6B6A", +"6> c #6F6F6D", +"7> c #C0C0BF", +"8> c #565654", +"9> c #737372", +"0> c #D5D5D4", +"a> c #ADADAC", +"b> c #545453", +"c> c #A4A4A3", +"d> c #B5B5B5", +"e> c #444443", +"f> c #595957", +"g> c #C3C3C2", +"h> c #494948", +"i> c #3D3D3C", +"j> c #E7E7E7", +"k> c #666665", +"l> c #323230", +"m> c #9E9E9D", +"n> c #FEFEFD", +"o> c #CFCFCE", +"p> c #A8A8A8", +"q> c #535352", +"r> c #FDFDFC", +"s> c #B8B8B8", +"t> c #60605F", +"u> c #6D6D6B", +"v> c #E0E0DF", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . + @ @ @ @ @ @ @ @ @ @ @ @ @ # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ $ $ $ $ $ $ $ $ $ $ $ $ $ % % % % % % % % % % % % % % . . . . ", +" . . . # # . . . . . . . . . . . . . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . # . & * = - - - - - - - - ; > , ' . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . ! ~ { ] ] ] ] ] ] ] ] ] ] ^ / ( _ _ _ _ _ _ _ _ _ : < [ . . . . . ", +" . . . . } . | 1 2 3 3 3 3 3 3 3 3 3 4 5 6 . 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . % . 8 9 0 a b b b b b b b b b c d e f g h h h h h h h h i j k . $ . . . . ", +" . . . . . @ . l 3 m n n n n n n n o p q r s . + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . t u v w x x x x x x x x x y z A B C D D D D D D D E F ( . # . . . . . ", +" . . . . . . @ . G H I J K K K K K K L M N O P . Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . R S T U V W w w w w w w w X Y Z z z ` ...............+.@.. % . . . . . . ", +" . . . . . . . 7 . #.$.%.K K K K K K &.M M *.=.-.. @ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . % . ;.>.,.'.'.).!.w w w w w ~.{.z z z ].^. ...........C f /.. $ . . . . . . . ", +" . . . . . . . . # . (._.:.<.K K K K [.M M M }.|.1.. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . 2.3.,.'.'.U 4.!.w w w w w X 5.Z z z z 6.7.8....... .9.0.a.. # . . . . . . . . ", +" . . . . . . . . . Q . b.c.o K K K K d.M M M M }.O e.. Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . f.g.h.i.'.'.'.U j.W w w w X k.l.z z z z ].Z m.......C f n.. $ . . . . . . . . . ", +" . . . . . . . . . . . # . o.3 n K K p.M M M M M q.=.r.s.. # . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . t.u u.'.'.'.'.v.w.w w w w w x.l.z z z z z 6.B 8...D i y.$ . . . . . . . . . . . . ", +" . . . . . . . . . . . . @ . z.A.J K L M M M M M M M B.O C.. 7 . . . . . . . . . . . . . . . . . . . . . . . . . . % . D.E.F.T '.'.'.'.'.U G.W w X H.Z z z z z z z z z 9. .8.i I.. $ . . . . . . . . . . . . ", +" . . . . . . . . . . . . . Q . J.$.K.L.M M M M M M M *.M.N N.. @ . . . . . . . . . . . . . . . . . . . . . . . . . ) . O.P.u.'.'.'.'.'.'.'.T Q.w x ].R.z z z z z z z 6.S.T.U.V.. $ . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . # . W.X.Y.*.M M M M M M M M N Z.`.. } . . . . . . . . . . . . . . . . . . . . . . . . ) . +.+i.'.'.'.'.'.'.'.'.U ++w Y R.@+@+@+@+@+@+@+@+@+@+U.C #+. # . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . 7 . $+%+&+*.*.*.*.*.*.*.*.*.*+=+-+. } . . . . . . . . . . . . . . . . . . . . . . . # % ;+>+,.'.'.'.'.'.'.'.'.T ,+'+)+!+!+!+!+!+!+!+!+!+!+~+R.{+. $ . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . # . ]+^+/+(+_+_+_+_+_+_+_+_+(+:+<+[+. . . . . . . . . . . . . . . . . . . . . . . Q . }+|+1+2+2+2+2+2+2+2+2+2+3+4+5+6+7+8+8+8+8+8+8+8+8+8+8+9+0+. . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . Q . a+b+c+d+d+d+d+d+d+d+d+_+e+f+g+. h+. . . . . . . . . . . . . . . . . . . . # . i+j+k+l+m+m+m+m+m+m+m+m+n+o+p+. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . @ . q+r+s+d+d+d+d+d+d+d+d+t+u+v+w+. + . . . . . . . . . . . . . . . . . . . x+. y+z+A+B+C+m+m+m+m+m+m+m+m+D+E+. Q # # # # # # # # # # # # . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . @ . F+G+H+G+d+d+d+d+d+_+I+J+K+L+M+. h+. . . . . . . . . . . . . . . . . . ) . N+O+O+O+P+m+m+m+m+m+m+m+Q+R+S+. Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . Q . T+U+V+d+d+d+d+d+W+X+Y+Y+Y+Z+`+. @ . . . . . . . . . . . . . . . . . ) . @.@A+O++@@@C+m+m+m+m+#@$@%@&@. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . # . *@=@-@;@d+d+d+_+>@J+Y+Y+,@'@)@. @ . . . . . . . . . . . . . . . . ) . !@~@P+O+O+O+{@]@C+m+m+m+Q+R+^@. Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . Q . /@(@V+d+d+_@:@Y+Y+Y+Y+Y+<@'@[@. Q . . . . . . . . . . . . . . # . }@|@1@P+O+O+O++@2@C+m+m+l+3@4@5@. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . # . 6@b+s+d+_@7@J+Y+Y+Y+Y+8@9@0@a@. # . . . . . . . . . . . . . x+. b@c@d@O+O+O+O+O+O+e@C+m+l+f@g@. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . @ . h@i@j@_@k@J+Y+Y+Y+Y+Y+Y+K+l@m@. h+. . . . . . . . . . . . % . n@o@p@q@O+O+O+O+O++@r@C+Q+s@t@. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . u@v@w@x@Y+Y+Y+Y+Y+Y+Y+y@z@A@B@. + . . . . . . . . . . . Q . C@D@E@k+k+k+k+k+k+k+F@G@H@I@J@. $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . K@L@M@J+Y+Y+Y+Y+Y+Y+Y+Y+K+N@O@. h+. . . . . . . . . . ) . P@Q@R@S@S@S@S@S@S@S@S@T@U@V@W@. Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. X@Y@Z@`@`@`@`@`@`@`@`@`@ #.#+#. ) . . . . . . . . . % . @###$#%#%#%#%#%#%#%#%#&#*#=#-#. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . ;#>#,#'#)#)#)#)#)#)#)#)#!#~#{#. # . . . . . . . . Q . ]#^#/#(#_#_#_#_#_#_#_#_#:#<#[#}#. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. |#1#!#)#)#)#)#)#)#)#)#2#3#4#5#. h+. . . . . . # . 6#7#8#9#0#(#a#a#a#a#a#a#b#c#d#e#f#. $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . g#h#!#)#)#)#)#)#)#2#i#j#k#l#m#. + . . . . . Q . n#o#p#q#r#s#a#a#a#a#a#a#a#_#t#u#v#w#. x+. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . x#y#z#)#)#)#)#)#)#A#B#C#D#E#F#. h+. . . . $ . G#H#I#J#K#L#M#b#a#a#a#a#b#N#O#P#Q#R#S#T#. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. U#V#W#)#)#)#)#X#Y#C#Z#`# $.$+$. @ . . . ) . @$#$$$%$&$*$=$(#a#a#a#a#_#-$;$>$,$'$)$!$. x+. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . ~${$y#]$)#)#)#)#^$/$Z#Z#($_$:$. ) . . ) . <$[$}$|$|$%$1$2$3$s#a#a#b#N#4$5$6$,$7$8$9$0$. $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. a$V#W#)#)#X#b$C#Z#Z#Z#Z#c$d$e$. h+. . + f$g$}$|$|$h$i$j$s#_#a#b#c#k$>$,$,$,$,$l$m$n$. x+. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . o$p$q$'#)#r$Z#Z#Z#Z#Z#Z#c$s$t$h+. h+. u$v$$$|$|$|$|$w$x$y$r#s#a#z$A$B$6$,$,$,$,$C$D$E$. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Q . F$G$'#X#H$C#Z#Z#Z#Z#Z#Z#I$4#J$. K$L$M$N$O$|$|$|$|$|$P$Q$R$0#c#S$P#6$,$,$,$,$,$T$U$V$. $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . W$X$Y$Z$Z#Z#Z#Z#Z#Z#Z#j#`$ %.%. +%@%#%|$|$|$|$|$|$w$1$$%%%&%*%=%,$,$,$,$,$,$,$T$v#-%. ;%>%>%>%>%>%>%>%>%>%>%>%>%% . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . @ . ,%'%)%!%!%!%!%!%!%!%!%!%~%{%]%^%/%(%(%(%(%(%(%(%(%(%h$_%:%<%[%,$>$>$>$>$>$>$>$}%|%1%T#. # . . . . . . . . . . . % . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. 2%3%4%5%5%5%5%5%5%5%5%5%6%7%8%9%0%a%a%a%a%a%a%a%a%b%c%d%e%f%g%h%h%h%h%h%h%h%h%i%j%k%l%m%n%o%o%o%o%o%o%o%o%p%q%r%. % . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . s%t%u%v%w%w%w%w%w%w%w%x%y%z%A%B%C%D%D%D%D%D%D%D%D%E%F%G%H%I%J%K%K%K%K%K%K%K%K%K%L%M%N%O%P%P%P%P%P%P%P%P%P%Q%R%S%. ) . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. T%U%V%W%W%W%W%W%W%W%W%W%X%Y%Z%`% &.&.&.&.&.&.&+&@&#&. $&%&&&*&=&=&=&=&=&=&=&-&;&>&,&'&f%f%f%f%f%f%f%f%f%)&!&~&{&. Q . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . ]&^&V%W%W%W%W%W%/&(&_&:&<&[&.&.&.&.&.&.&.&.&+&}&|&. . 1&2&3&=&=&=&=&=&=&=&4&5&5&5&6&7&8&8&8&8&8&8&8&9&0&a&b&c&}@. # . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . [+. d&e&f&W%W%W%W%W%g&h&i&j&k&l&m&n&o&.&.&.&.&p&q&r&. Q . s&t&u&v&=&=&=&=&=&=&w&x&5&y&z&7&8&8&8&8&8&8&A&B&C&D&E&F&G&. x+. . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. H&I&V%W%W%W%/&(&J&:&K&L&M&N&O&P&.&.&.&Q&R&S&T&. $ x+. U&V&W&=&=&=&=&X&Y&5&5&5&5&y&Z&7&8&8&8&8&8&A&`& *D&.*+*@*#*. % . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ . $*%*&*f&W%/&**=*-*L&L&L&k&;*>*,*o&.&.&'*)*!*. h+. . $ . ~*{*W&=&=&=&=&]*5&5&5&5&y&w&8&8&8&8&8&A&^* *D&D&D&E&/*(*. x+. . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. _*:*<*W%W%[*}*|*K&L&L&L&L&M&1*2* &+&3*4*5*. # . . ) . 6*7*=&=&=&X&8*x&5&5&5&5&5&9*0*a*8&8&8&8&b* *D&D&D&D&c*d*e*. ) . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . f*g*e&f&(&h*|*K&L&L&L&L&i*j*k*2*D%E%q&l*. Q . . . . x+. m*2&n*=&K%5&5&5&5&5&5&5&5&o*p*7&8&A&q* *D&D&D&D&D&r*s*t*. $ . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+. u*v*w*x*y*-*L&L&L&L&L&L&i*j*z*A*B*C*. + . . . . . $ . D*E*F*G*H*x&5&5&5&5&5&5&5&y&I*7&A&7&C&D&D&D&D&D&D&D&J*K*L*. Q . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . M*N*O*P*Q*R*R*R*R*R*R*R*S*T*E%U*V*. ) . . . . . . >%. W*X*Y*Z*Z*Z*Z*Z*Z*Z*Z*Z*Z*`* =.=+=@=J*J*J*J*J*J*J*#=$=%=&=. # . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . *===-=;=>=>=>=>=>=>=>=>=,='=)=!=. Q . . . . . . . . . ~={=]=^=/=/=/=/=/=/=/=/=/=(=_=:=<=F&F&F&F&F&F&F&F&F&s*[=}=. Q . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ . |=1=2=3=3=3=3=3=3=3=3=3=4=5=6=. # . . . . . . . . $ . 7=8=9=0=0=0=0=0=0=0=0=0=0=a=b=c=d=d=d=d=d=d=d=d=d=e=f=g=) . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . . . . . . . . . . . . . . + . . . . . . . . . . . # $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h+0+0+0+0+0+0+0+0+0+0+0+0+0++ . . . . . . . . . . . . ) >%>%>%>%>%>%>%>%>%>%>%>%>%>%x+x+x+x+x+x+x+x+x+x+x+x+x+. . . . . . . . . . . ", +" . . . . . . . . . . . . . . . h=i=i=. . . . $ i=i=$ . . . . . . . . . . . . . . . . . . . . . . . . . . i=i=$ $ h=i=. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ h=. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h=h=. . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . $ . j=k=l=m=. i=. n=o=k=p=. h=. . . . . . . . . . . . . . . . . . . . . $ h=. q=r=s=t=u=v=. $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . w=. x=y=z=A=. B=. C=y=D=E=. F=G=h=i=i=. . $ w=i=$ G=h=. i=w=h=h=w=h=. $ . H=r=I=J=K=L=M=N=. w=i=$ w=$ h=w=$ . . . i=i=. i=h=$ w=i=w=$ . $ $ O=P=. w=. . . . . . . . . . . . . ", +" . . . . . . . . . . . h=. Q=R=S=T=. i=. u=D=U=. h=$ . . . . h=. . . . $ . . . . . . . . $ $ $ . V=W=X=. h=. . . . . $ $ . . . . $ . . . . . . . $ $ . . . $ h=. . Y=k=. w=. . . . . . . . . . . . . ", +" . . . . . . . . . . $ . h=Z=`= -i=. .-+-`=@-. . #-$-%-&-*-. . =---;->-,-'-. )-N=!-!-C=~-. . {-]-^-. F=w=w=w=i=. /-(-_-:-<-#-[-}-. h=. |-1-. 2-)-3---4-@-5-. >-6-7-u=8-9-. $ . . . . . . . . . . ", +" . . . . . . . . . . . i=. 0-`=R=a-. b-`=R=c-. d-e-f-g-h-i-j-. k-y=l-m-y=n-. o-y=p-`=q-r-s-. t-u->-. $ . . . w=. v-w-x-y-z-A-y=B-. $ C-g-!-. D-E-E-F-G-H-I-J-3-K-L-M-N-[-. h=. . . . . . . . . . ", +" . . . . . . . . . . h=. O-u-P-L=. Q-h-R-. S-+-T-U-. b-V-W-. X-Y-+-y-Z-`-. ;.;h=E=+;h-C=. @;#;. . . . . . w=. $;%;&;. $ . *;=;. . A=-;;;. >;I=k-. . .;,;';. . );!;. G=. . . . . . . . . . . ", +" . . . . . . . . . . $ . B=s=z=~;{;];^;/;. 1-I=);(; ;_;R=u-:;P=<;[;};. i=. H=|;1;2;3;i-1;. 4;M-. . . . . . w=. _;D=:;. B=. /;H-5;. 6;M-. . 4;7;. w=B=. 4-Y=. . l-8;. B=. . . . . . . . . . . ", +" . . . . . . . . . . i=. --q-9;0;T-a;b;. '-D=R=c;y=d;i-e;b;f;H-[;k-. $ g;h;i;j;k;l;D=K-. !;g-m;. $ . . . w=. n;u-5-. i=. o;[;p;. q;r;. . x-s;. h=i=. t-t;C-. l-8;. i=. . . . . . . . . . ", +" . . . . . . . . . i=. u;S=v;w;`=x;. . y;z;A;B;C;p=*-D;i=E;T-H-F;. . G;H;+;I;. J;e;>;. K;y=L;. F=w=w=i=F=. n;M;m;. $ h=. F-N;O;P;o;. . Z-Q;. R;C-. S;+;. . );!;. B=. . . . . . . . . ", +" . . . . . . . . . $ . {;#;T;U;V;W;. . X;<;u-C=o;Y;Z;`;. *-T;Y- >. . .>,;+>o;@>v;[;#>. h=$>H-;;. h=. . w=. _;g-%>. $ i=. &>*>k;=>. F=. ->M;~-. . ;>Y-,-. . Y=>>. i=. . . . . . . . . ", +" . . . . . . . . . i=. ,>y=e-H-'>. w=. )>,;!>I=[;y=~>. {>]>i; ;. . &>^>D=/>S=T;y=(>. . _>:>h-J=<>K=[>}>. |>z=5-. $ $ . i=u=e;B;. F=. =>M;h;1>2>3;w-3>. . 4>S=C=B;. h=. . . . . . ", +" . . . . . . . . . h=. @>5>6>1>. . . $ . 7>!;8>w;8;&>. O=$-9>0>. i=. a>b>x;c>d>k=L=. h=. B=9-[>E-e>f>9-. {>}>{;. $ . B=. r=W-. . i=. m-(>g>h>i>$-j>. h=. S-k>l>m>. i=. . . . . . ", +" . . . . . . . . . . $ . . . $ . . . h=. . . . . . . . . . . . . $ . . . . . . . . . n>$ . . . . . . . . . . . . h=. o>`=p>. i=h=. q>R-. h=. . $ $ . . $ . . . . . . . . . . ", +" . . . . . . . . . . $ i=i=i=. . . . . i=i=h=h=G=i=. $ G=G=$ . . . i=h=h=i=r>G=r>. . . $ i=i=$ $ i=i=. h=G=. . . $ s>T-w;. $ . h=. R-e>. F=$ w=h=. . . $ i=$ h=. . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ . ;>M;t>{;. $ . h=. u>k>. h=. . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i=v>$ $ $ . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h=$ . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h=. . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" "}; diff --git a/src/Resources/Icons/VeraCrypt-16x16.xpm b/src/Resources/Icons/VeraCrypt-16x16.xpm index 082ae182..e243e187 100644 --- a/src/Resources/Icons/VeraCrypt-16x16.xpm +++ b/src/Resources/Icons/VeraCrypt-16x16.xpm @@ -1,105 +1,105 @@ -/* XPM */ -static const char *VeraCryptIcon16x16[] = { -"16 16 86 1", -" c None", -". c #FFFFFF", -"+ c #FDFEFF", -"@ c #FDFEFE", -"# c #FEFEFE", -"$ c #FEFFFE", -"% c #FEFFFF", -"& c #FEFEFF", -"* c #FCFEFE", -"= c #60C9E6", -"- c #6FCDE7", -"; c #C4E7DC", -"> c #8ACCB7", -", c #A0D4C2", -"' c #BFE1D4", -") c #FCFEFD", -"! c #8CD6EC", -"~ c #0096CC", -"{ c #B8E2F1", -"] c #F1F9F7", -"^ c #51BA9C", -"/ c #68C0A5", -"( c #9FD3C0", -"_ c #CFE9E0", -": c #3FA8D7", -"< c #399CD3", -"[ c #F9FCFD", -"} c #87D4C1", -"| c #38B495", -"1 c #E2F4EF", -"2 c #C5E0F1", -"3 c #0C79C1", -"4 c #A0C7E5", -"5 c #E6F8F6", -"6 c #1A7C68", -"7 c #479A80", -"8 c #FBFFFF", -"9 c #FCFDFD", -"0 c #66A1D1", -"a c #2B74BA", -"b c #5AB3C3", -"c c #288F93", -"d c #248C6C", -"e c #89C6B6", -"f c #C5E2DB", -"g c #E4F3EF", -"h c #E1E9F6", -"i c #24679C", -"j c #026B83", -"k c #BAE2ED", -"l c #7CB8A3", -"m c #0E7A59", -"n c #159271", -"o c #60C2AC", -"p c #EEEEEE", -"q c #E6E6E6", -"r c #FFFEFF", -"s c #DCE9EC", -"t c #CEDFE3", -"u c #EEECEC", -"v c #F0F7F4", -"w c #D6E9E3", -"x c #D5EBE5", -"y c #CEEAE4", -"z c #FAFDFD", -"A c #CBCBCA", -"B c #777775", -"C c #8E8E8E", -"D c #A29F9E", -"E c #959190", -"F c #D0D1D0", -"G c #C6C5C5", -"H c #BFBCBC", -"I c #B1ADAD", -"J c #DCD9D9", -"K c #F6F6F6", -"L c #DFDFDE", -"M c #DEDEDE", -"N c #DFDFDF", -"O c #D9DADA", -"P c #EDEDED", -"Q c #E5E6E5", -"R c #CECFCE", -"S c #DEDFDE", -"T c #F4F5F5", -"U c #FDFDFD", -" ", -" ........ ", -" ++....@@#$ ", -" %.&..%%... ", -" *=-.%@.;>,') ", -" .!~{..]^/(_. ", -" %..:<[.}|1.@.. ", -"..@.2345678.@...", -"...9.0abcdefg.$.", -" ..@.hijklmno.$ ", -" .pqrstuvwxyz ", -" .ABCDEFGHIJ. ", -" KLMNOPQRST ", -" ##....#... ", -" UUUU#### ", -" "}; +/* XPM */ +static const char *VeraCryptIcon16x16[] = { +"16 16 86 1", +" c None", +". c #FFFFFF", +"+ c #FDFEFF", +"@ c #FDFEFE", +"# c #FEFEFE", +"$ c #FEFFFE", +"% c #FEFFFF", +"& c #FEFEFF", +"* c #FCFEFE", +"= c #60C9E6", +"- c #6FCDE7", +"; c #C4E7DC", +"> c #8ACCB7", +", c #A0D4C2", +"' c #BFE1D4", +") c #FCFEFD", +"! c #8CD6EC", +"~ c #0096CC", +"{ c #B8E2F1", +"] c #F1F9F7", +"^ c #51BA9C", +"/ c #68C0A5", +"( c #9FD3C0", +"_ c #CFE9E0", +": c #3FA8D7", +"< c #399CD3", +"[ c #F9FCFD", +"} c #87D4C1", +"| c #38B495", +"1 c #E2F4EF", +"2 c #C5E0F1", +"3 c #0C79C1", +"4 c #A0C7E5", +"5 c #E6F8F6", +"6 c #1A7C68", +"7 c #479A80", +"8 c #FBFFFF", +"9 c #FCFDFD", +"0 c #66A1D1", +"a c #2B74BA", +"b c #5AB3C3", +"c c #288F93", +"d c #248C6C", +"e c #89C6B6", +"f c #C5E2DB", +"g c #E4F3EF", +"h c #E1E9F6", +"i c #24679C", +"j c #026B83", +"k c #BAE2ED", +"l c #7CB8A3", +"m c #0E7A59", +"n c #159271", +"o c #60C2AC", +"p c #EEEEEE", +"q c #E6E6E6", +"r c #FFFEFF", +"s c #DCE9EC", +"t c #CEDFE3", +"u c #EEECEC", +"v c #F0F7F4", +"w c #D6E9E3", +"x c #D5EBE5", +"y c #CEEAE4", +"z c #FAFDFD", +"A c #CBCBCA", +"B c #777775", +"C c #8E8E8E", +"D c #A29F9E", +"E c #959190", +"F c #D0D1D0", +"G c #C6C5C5", +"H c #BFBCBC", +"I c #B1ADAD", +"J c #DCD9D9", +"K c #F6F6F6", +"L c #DFDFDE", +"M c #DEDEDE", +"N c #DFDFDF", +"O c #D9DADA", +"P c #EDEDED", +"Q c #E5E6E5", +"R c #CECFCE", +"S c #DEDFDE", +"T c #F4F5F5", +"U c #FDFDFD", +" ", +" ........ ", +" ++....@@#$ ", +" %.&..%%... ", +" *=-.%@.;>,') ", +" .!~{..]^/(_. ", +" %..:<[.}|1.@.. ", +"..@.2345678.@...", +"...9.0abcdefg.$.", +" ..@.hijklmno.$ ", +" .pqrstuvwxyz ", +" .ABCDEFGHIJ. ", +" KLMNOPQRST ", +" ##....#... ", +" UUUU#### ", +" "}; diff --git a/src/Resources/Icons/VeraCrypt-256x256.xpm b/src/Resources/Icons/VeraCrypt-256x256.xpm index 7c9107fe..aa72e83b 100644 --- a/src/Resources/Icons/VeraCrypt-256x256.xpm +++ b/src/Resources/Icons/VeraCrypt-256x256.xpm @@ -1,2029 +1,2029 @@ -/* XPM */ -static const char *VeraCryptIcon256x256[] = { -"256 256 1770 2", -" c None", -". c #FFFFFF", -"+ c #FCFEFF", -"@ c #FBFEFE", -"# c #FCFEFE", -"$ c #FDFEFD", -"% c #FCFEFD", -"& c #FDFEFE", -"* c #FEFFFF", -"= c #9DDEEF", -"- c #7DD3EB", -"; c #85D6EB", -"> c #83D5EB", -", c #7CD2EA", -"' c #B1E3F2", -") c #FDFEFF", -"! c #C4E6DC", -"~ c #B2DDCF", -"{ c #B6DFD2", -"] c #B5DFD2", -"^ c #B3DED1", -"/ c #BDE2D5", -"( c #CBE7DD", -"_ c #CAE7DC", -": c #CAE6DC", -"< c #CFE9DF", -"[ c #96DAEE", -"} c #009FD3", -"| c #03A6D6", -"1 c #00A5D5", -"2 c #01A6D5", -"3 c #00A2D3", -"4 c #13A7D4", -"5 c #DFF3F9", -"6 c #D9EFE9", -"7 c #4CB697", -"8 c #5DBA9C", -"9 c #61BA9D", -"0 c #60BA9D", -"a c #77C2A9", -"b c #8BCAB3", -"c c #8FCBB5", -"d c #8ECBB5", -"e c #90CCB6", -"f c #86C8B0", -"g c #C2E3D7", -"h c #FEFEFE", -"i c #47C0E2", -"j c #00A8D7", -"k c #0FADDA", -"l c #0CACD9", -"m c #0CADD9", -"n c #15AAD6", -"o c #00A0D0", -"p c #62C5E2", -"q c #7DCAB4", -"r c #48B596", -"s c #62BEA2", -"t c #6FC0A6", -"u c #6DC0A6", -"v c #6EC0A6", -"w c #6CBFA5", -"x c #7AC5AC", -"y c #88C9B3", -"z c #8ACAB4", -"A c #98D0BB", -"B c #99D0BC", -"C c #95CEB9", -"D c #A5D6C4", -"E c #FAFDFC", -"F c #C6ECF6", -"G c #05AAD7", -"H c #09ABD8", -"I c #08ABD8", -"J c #0AA9D6", -"K c #0EA6D3", -"L c #0FA7D3", -"M c #07A3D2", -"N c #C2E8F4", -"O c #C0E5DB", -"P c #48B595", -"Q c #54BA9C", -"R c #52B99B", -"S c #66BEA2", -"T c #6CBFA4", -"U c #6BBFA4", -"V c #6ABFA4", -"W c #6EC0A5", -"X c #84C8B0", -"Y c #86C8B1", -"Z c #84C8B1", -"` c #90CCB7", -" . c #97CFBB", -".. c #96CFBA", -"+. c #97D0BB", -"@. c #D9EEE6", -"#. c #67CBE7", -"$. c #0DA7D4", -"%. c #11A7D4", -"&. c #03A2D1", -"*. c #41B9DC", -"=. c #F6FBFA", -"-. c #67C2A7", -";. c #4DB798", -">. c #50B99A", -",. c #59BB9D", -"'. c #69BFA3", -"). c #7CC5AD", -"!. c #87C9B2", -"~. c #85C8B1", -"{. c #95CEBA", -"]. c #91CCB7", -"^. c #B0DBCB", -"/. c #FEFFFE", -"(. c #E2F5FB", -"_. c #17AFDA", -":. c #05AAD8", -"<. c #0BA9D6", -"[. c #12A7D4", -"}. c #9FDBED", -"|. c #A6DBCB", -"1. c #46B494", -"2. c #55BA9D", -"3. c #51B99A", -"4. c #63BDA1", -"5. c #6DBFA5", -"6. c #6ABEA3", -"7. c #71C1A7", -"8. c #8DCBB5", -"9. c #94CEB9", -"0. c #E7F4EF", -"a. c #8CD8ED", -"b. c #09AAD7", -"c. c #10A7D3", -"d. c #08A4D2", -"e. c #25AED7", -"f. c #EEF9FC", -"g. c #E5F4F0", -"h. c #57BB9E", -"i. c #51B89A", -"j. c #53B99B", -"k. c #51B99B", -"l. c #55BA9C", -"m. c #7FC6AE", -"n. c #86C8B2", -"o. c #97CFBA", -"p. c #8FCCB5", -"q. c #BFE2D5", -"r. c #F7FDFE", -"s. c #30B8DE", -"t. c #0AACD8", -"u. c #0CA8D5", -"v. c #12A8D4", -"w. c #7ACEE7", -"x. c #8CD0BC", -"y. c #47B595", -"z. c #5FBCA0", -"A. c #69BEA3", -"B. c #75C3A9", -"C. c #87C8B2", -"D. c #9CD2BE", -"E. c #F4FAF8", -"F. c #B0E4F3", -"G. c #00A7D6", -"H. c #0BACD8", -"I. c #0FA6D3", -"J. c #0DA5D3", -"K. c #10A7D4", -"L. c #D4EFF7", -"M. c #D0ECE4", -"N. c #4CB798", -"O. c #53BA9C", -"P. c #68BEA3", -"Q. c #83C7B0", -"R. c #91CDB8", -"S. c #8FCCB6", -"T. c #50C3E3", -"U. c #00A6D6", -"V. c #0BACD9", -"W. c #00A1D0", -"X. c #56C0E0", -"Y. c #74C7AF", -"Z. c #4AB697", -"`. c #5BBB9E", -" + c #79C4AB", -".+ c #92CDB7", -"++ c #A7D7C5", -"@+ c #D1EFF8", -"#+ c #0BABD8", -"$+ c #07ABD8", -"%+ c #04A2D1", -"&+ c #B6E4F2", -"*+ c #B7E2D5", -"=+ c #47B594", -"-+ c #65BEA2", -";+ c #6ABFA3", -">+ c #6FC1A6", -",+ c #91CDB7", -"'+ c #DEF0EA", -")+ c #74CFE9", -"!+ c #36B5DA", -"~+ c #F9FDFE", -"{+ c #F2F9F7", -"]+ c #61BFA3", -"^+ c #4EB899", -"/+ c #53B99C", -"(+ c #57BA9D", -"_+ c #7DC6AD", -":+ c #86C9B1", -"<+ c #B5DDCE", -"[+ c #EBF8FC", -"}+ c #1FB2DB", -"|+ c #03A9D7", -"1+ c #0BA8D5", -"2+ c #93D7EB", -"3+ c #9DD7C6", -"4+ c #50B99B", -"5+ c #62BDA1", -"6+ c #72C1A8", -"7+ c #86C9B2", -"8+ c #8CCBB5", -"9+ c #95CFBA", -"0+ c #ECF6F2", -"a+ c #99DCEF", -"b+ c #00A6D5", -"c+ c #0AA5D2", -"d+ c #1DACD6", -"e+ c #E6F6FA", -"f+ c #DEF2EC", -"g+ c #80C6AF", -"h+ c #93CEB8", -"i+ c #C5E4D9", -"j+ c #FDFFFF", -"k+ c #3BBCE0", -"l+ c #6DC9E4", -"m+ c #83CDB7", -"n+ c #5EBC9F", -"o+ c #76C3AA", -"p+ c #89CAB3", -"q+ c #A0D4C0", -"r+ c #F7FBFA", -"s+ c #BDE9F5", -"t+ c #02A8D7", -"u+ c #09ACD8", -"v+ c #0BA5D2", -"w+ c #CAEBF5", -"x+ c #C8E8DF", -"y+ c #4AB596", -"z+ c #67BEA3", -"A+ c #6DC0A5", -"B+ c #D4EBE3", -"C+ c #5DC8E5", -"D+ c #01A1D1", -"E+ c #4BBCDE", -"F+ c #6DC4AA", -"G+ c #5ABB9E", -"H+ c #7AC4AC", -"I+ c #ACD9C9", -"J+ c #DBF3F9", -"K+ c #11AED9", -"L+ c #06AAD8", -"M+ c #A9DFEF", -"N+ c #AEDED0", -"O+ c #64BDA2", -"P+ c #70C1A6", -"Q+ c #8DCCB6", -"R+ c #E4F3ED", -"S+ c #2DB2D9", -"T+ c #F3FBFD", -"U+ c #EBF7F3", -"V+ c #5BBDA0", -"W+ c #4FB89A", -"X+ c #56BA9D", -"Y+ c #7EC6AE", -"Z+ c #BAE0D2", -"`+ c #29B5DD", -" @ c #01A8D7", -".@ c #86D2E9", -"+@ c #93D3C0", -"@@ c #47B494", -"#@ c #60BCA0", -"$@ c #74C2A8", -"%@ c #8BCBB4", -"&@ c #95CFB9", -"*@ c #9AD0BC", -"=@ c #F1F8F5", -"-@ c #A7E1F1", -";@ c #0CA5D3", -">@ c #15A9D4", -",@ c #DCF2F9", -"'@ c #D7EFE8", -")@ c #4FB799", -"!@ c #53BA9B", -"~@ c #82C7AF", -"{@ c #92CDB8", -"]@ c #FEFEFF", -"^@ c #48C0E2", -"/@ c #60C4E2", -"(@ c #7BCAB2", -"_@ c #49B596", -":@ c #5CBC9F", -"<@ c #78C4AB", -"[@ c #93CDB8", -"}@ c #A4D5C3", -"|@ c #C9ECF6", -"1@ c #0AAAD7", -"2@ c #C0E8F3", -"3@ c #BFE5D9", -"4@ c #90CDB7", -"5@ c #91CDB6", -"6@ c #DAEEE7", -"7@ c #6ACCE7", -"8@ c #00A0D1", -"9@ c #12A7D3", -"0@ c #40B8DC", -"a@ c #F6FBF9", -"b@ c #66C1A6", -"c@ c #55B99B", -"d@ c #7BC5AC", -"e@ c #85C8B2", -"f@ c #87C9B3", -"g@ c #83C7AF", -"h@ c #B2DCCD", -"i@ c #E5F5FA", -"j@ c #26A3D4", -"k@ c #159CD1", -"l@ c #1A9DD1", -"m@ c #199DD1", -"n@ c #1C9FD2", -"o@ c #0C94CE", -"p@ c #A5D1EB", -"q@ c #98D8C8", -"r@ c #37B291", -"s@ c #4AB89B", -"t@ c #46B799", -"u@ c #47B79A", -"v@ c #41B596", -"w@ c #5BBFA4", -"x@ c #E6F4F0", -"y@ c #ECF7F3", -"z@ c #EAF6F2", -"A@ c #EBF6F2", -"B@ c #EAF5F2", -"C@ c #96D1EA", -"D@ c #0B95CE", -"E@ c #1E9ED2", -"F@ c #1A9CD1", -"G@ c #1B9DD1", -"H@ c #1C8ECD", -"I@ c #3796D1", -"J@ c #EEF7FB", -"K@ c #E0F3EF", -"L@ c #37B597", -"M@ c #38B495", -"N@ c #45B79A", -"O@ c #43B799", -"P@ c #44B799", -"Q@ c #47B89A", -"R@ c #38B392", -"S@ c #B6E3D7", -"T@ c #F9FCFE", -"U@ c #3FACD9", -"V@ c #1198CF", -"W@ c #1C9DD1", -"X@ c #1D97D0", -"Y@ c #278ECE", -"Z@ c #1385CA", -"`@ c #84C0E3", -" # c #FCFDFE", -".# c #77CCB8", -"+# c #26AE8D", -"@# c #36B496", -"## c #41B698", -"$# c #45B799", -"%# c #46B89A", -"&# c #3BB394", -"*# c #6DC7B0", -"=# c #B7E0F0", -"-# c #0F97CF", -";# c #228FCE", -"># c #248DCD", -",# c #228DCD", -"'# c #258ECD", -")# c #D7EAF6", -"!# c #C8EAE2", -"~# c #2CB090", -"{# c #35B495", -"]# c #32B394", -"^# c #37B496", -"/# c #3FB596", -"(# c #D1EDE6", -"_# c #5DB9DF", -":# c #0D96CE", -"<# c #1D9DD2", -"[# c #1E95CF", -"}# c #248CCD", -"|# c #238DCD", -"1# c #268FCE", -"2# c #1686CA", -"3# c #63AEDC", -"4# c #5BC2AA", -"5# c #2AB08F", -"6# c #33B394", -"7# c #3EB697", -"8# c #47B89B", -"9# c #38B292", -"0# c #87D1BD", -"a# c #D5EDF7", -"b# c #199BD1", -"c# c #1B9CD1", -"d# c #1B9AD0", -"e# c #238ECD", -"f# c #1988CB", -"g# c #BADBEF", -"h# c #AADFD3", -"i# c #42B698", -"j# c #4CBA9D", -"k# c #E6F6F2", -"l# c #7FC8E5", -"m# c #0A95CE", -"n# c #1F93CF", -"o# c #1B89CB", -"p# c #469FD5", -"q# c #EEF9F6", -"r# c #44B99D", -"s# c #2FB192", -"t# c #34B395", -"u# c #3CB597", -"v# c #37B292", -"w# c #A4DCCD", -"x# c #EEF8FB", -"y# c #2EA5D5", -"z# c #159AD0", -"A# c #1C99D0", -"B# c #278FCE", -"C# c #1485CA", -"D# c #99CAE8", -"E# c #8AD3C2", -"F# c #25AE8D", -"G# c #34B394", -"H# c #3EB496", -"I# c #5EC1A7", -"J# c #F7FCFB", -"K# c #A2D7EC", -"L# c #0C96CE", -"M# c #2191CE", -"N# c #248ECD", -"O# c #208BCC", -"P# c #3094D0", -"Q# c #E7F3FA", -"R# c #D8F0EB", -"S# c #39B496", -"T# c #3AB394", -"U# c #BFE7DC", -"V# c #4AB1DA", -"W# c #238CCD", -"X# c #78B9E1", -"Y# c #6DC8B3", -"Z# c #27AF8E", -"`# c #40B698", -" $ c #3AB393", -".$ c #76CAB4", -"+$ c #C3E5F3", -"@$ c #1399D0", -"#$ c #1A9BD1", -"$$ c #CEE5F4", -"%$ c #BDE6DD", -"&$ c #29AF8F", -"*$ c #37B495", -"=$ c #43B798", -"-$ c #D8F0EA", -";$ c #69BEE1", -">$ c #0B96CE", -",$ c #1F94CF", -"'$ c #268ECE", -")$ c #1887CA", -"!$ c #59A9D9", -"~$ c #F8FCFC", -"{$ c #52BEA5", -"]$ c #91D4C3", -"^$ c #DFF1F9", -"/$ c #229FD3", -"($ c #189BD1", -"_$ c #1786CA", -":$ c #AED5ED", -"<$ c #9FDBCD", -"[$ c #25AE8C", -"}$ c #40B697", -"|$ c #51BCA0", -"1$ c #EDF8F6", -"2$ c #8DCEE8", -"3$ c #2092CE", -"4$ c #1C89CB", -"5$ c #3E9BD3", -"6$ c #F3F9FC", -"7$ c #E7F6F3", -"8$ c #3DB69A", -"9$ c #30B293", -"0$ c #3BB596", -"a$ c #ADDFD2", -"b$ c #F4FAFD", -"c$ c #38A9D7", -"d$ c #1C98D0", -"e$ c #1385C9", -"f$ c #8EC5E5", -"g$ c #7FCFBD", -"h$ c #3DB495", -"i$ c #65C4AB", -"j$ c #AEDCEF", -"k$ c #0E97CE", -"l$ c #2190CE", -"m$ c #218CCD", -"n$ c #2990CE", -"o$ c #DEEEF8", -"p$ c #CFEDE6", -"q$ c #38B496", -"r$ c #3CB495", -"s$ c #C8EAE1", -"t$ c #55B5DD", -"u$ c #1E96CF", -"v$ c #1586CA", -"w$ c #6DB3DE", -"x$ c #63C5AE", -"y$ c #36B495", -"z$ c #3FB697", -"A$ c #39B393", -"B$ c #7FCDB9", -"C$ c #CEEAF5", -"D$ c #189BD0", -"E$ c #1B9BD1", -"F$ c #228ECD", -"G$ c #C4E0F1", -"H$ c #B3E2D7", -"I$ c #27AE8E", -"J$ c #E0F3EE", -"K$ c #75C4E3", -"L$ c #258ECE", -"M$ c #4EA3D7", -"N$ c #F3FAF9", -"O$ c #4ABBA0", -"P$ c #2DB191", -"Q$ c #3DB597", -"R$ c #9BD8C9", -"S$ c #E8F5FA", -"T$ c #29A2D4", -"U$ c #169AD0", -"V$ c #1C9AD0", -"W$ c #A3CFEA", -"X$ c #94D7C8", -"Y$ c #58BEA4", -"Z$ c #F3FAF8", -"`$ c #99D3EB", -" % c #1E9DD2", -".% c #1E8BCC", -"+% c #3697D1", -"@% c #EDF6FB", -"#% c #DEF3EE", -"$% c #32B293", -"%% c #3AB596", -"&% c #B6E3D8", -"*% c #FAFDFE", -"=% c #42ADD9", -"-% c #1099CF", -";% c #1F98D0", -">% c #82BEE3", -",% c #75CAB6", -"'% c #26AD8C", -")% c #36B395", -"!% c #33B293", -"~% c #43B698", -"{% c #3BB393", -"]% c #6EC7B0", -"^% c #BBE2F1", -"/% c #1098CF", -"(% c #2491CE", -"_% c #D5E9F6", -":% c #C7ECE4", -"<% c #2DB595", -"[% c #36B899", -"}% c #34B898", -"|% c #33B898", -"1% c #39B99A", -"2% c #43B99A", -"3% c #D1EDE5", -"4% c #64B2DC", -"5% c #1883C8", -"6% c #288DCC", -"7% c #258BCB", -"8% c #1884C9", -"9% c #63ABD9", -"0% c #55AD97", -"a% c #249778", -"b% c #2F9C80", -"c% c #2D9B7E", -"d% c #309C80", -"e% c #229576", -"f% c #70BEA9", -"g% c #D9E9F5", -"h% c #2A87C7", -"i% c #2785C7", -"j% c #2986C7", -"k% c #2886C7", -"l% c #2B88C8", -"m% c #1875BC", -"n% c #B7D3E9", -"o% c #A7DCE2", -"p% c #1A817C", -"q% c #236047", -"r% c #20644D", -"s% c #20634B", -"t% c #21624B", -"u% c #1E654D", -"v% c #3A9D82", -"w% c #E2F3EF", -"x% c #88BCE0", -"y% c #197EC3", -"z% c #2C88C8", -"A% c #2887C8", -"B% c #2883C4", -"C% c #1772B9", -"D% c #438DC6", -"E% c #F8FBFD", -"F% c #EDF7F8", -"G% c #3EABB4", -"H% c #29A4AD", -"I% c #257462", -"J% c #21654C", -"K% c #216951", -"L% c #216850", -"M% c #20644C", -"N% c #2D8A6E", -"O% c #219D7C", -"P% c #78C0AC", -"Q% c #F0F6FB", -"R% c #3C91CD", -"S% c #2383C6", -"T% c #2987C7", -"U% c #2179BD", -"V% c #2379BD", -"W% c #116EB7", -"X% c #97C0E0", -"Y% c #85CBD0", -"Z% c #1E9DA6", -"`% c #31A9B4", -" & c #2A9494", -".& c #21654B", -"+& c #21674F", -"@& c #20654D", -"#& c #247258", -"$& c #30A082", -"%& c #309F82", -"&& c #299D7E", -"*& c #CCE7E0", -"=& c #A8CEE8", -"-& c #1B7FC4", -";& c #2987C8", -">& c #247FC2", -",& c #1F76BB", -"'& c #2178BD", -")& c #1D75BB", -"!& c #2C7EC0", -"~& c #E5EFF7", -"{& c #D5EDEF", -"]& c #2CA4AD", -"^& c #2DA4AD", -"/& c #2DA3AC", -"(& c #2EA8B2", -"_& c #257C6E", -":& c #206349", -"<& c #21684F", -"[& c #2B9074", -"}& c #30A284", -"|& c #319F82", -"1& c #259A7B", -"2& c #5EB59E", -"3& c #56A0D3", -"4& c #1E80C4", -"5& c #2B87C8", -"6& c #2784C6", -"7& c #2078BC", -"8& c #2077BC", -"9& c #2479BD", -"0& c #116EB8", -"a& c #74AAD5", -"b& c #67BDC4", -"c& c #219FA8", -"d& c #30A5AE", -"e& c #2DA6B0", -"f& c #2C9CA0", -"g& c #216851", -"h& c #21674E", -"i& c #20634C", -"j& c #267A60", -"k& c #2F9E80", -"l& c #2F9F81", -"m& c #32A083", -"n& c #23997A", -"o& c #B1DBD0", -"p& c #C8E0F1", -"q& c #2283C5", -"r& c #237CC0", -"s& c #2076BB", -"t& c #1C74BB", -"u& c #CBDFEF", -"v& c #BAE1E4", -"w& c #239FA9", -"x& c #2FA5AE", -"y& c #2DA3AB", -"z& c #2EA8B4", -"A& c #27857C", -"B& c #206348", -"C& c #21664F", -"D& c #216950", -"E& c #2D987B", -"F& c #30A183", -"G& c #31A082", -"H& c #299C7D", -"I& c #47AA90", -"J& c #73B0DB", -"K& c #1A7EC3", -"L& c #2683C5", -"M& c #1570B8", -"N& c #5597CC", -"O& c #4CB1B9", -"P& c #26A1AA", -"Q& c #2DA5AE", -"R& c #2DA2AA", -"S& c #226E5A", -"T& c #216750", -"U& c #288369", -"V& c #30A385", -"W& c #33A183", -"X& c #209878", -"Y& c #95CEBF", -"Z& c #E1EEF7", -"`& c #308AC9", -" * c #2685C6", -".* c #227BBE", -"+* c #136FB8", -"@* c #ACCCE6", -"#* c #9BD4D8", -"$* c #1F9EA7", -"%* c #30A6AE", -"&* c #2EA8B3", -"** c #298F8C", -"=* c #236F56", -"-* c #309F81", -";* c #2D9E80", -">* c #36A285", -",* c #E2F2ED", -"'* c #95C3E3", -")* c #197DC3", -"!* c #2581C3", -"~* c #2278BC", -"{* c #1973BA", -"]* c #3A87C4", -"^* c #F3F7FB", -"/* c #E5F4F5", -"(* c #37A8B1", -"_* c #2AA3AC", -":* c #2EA4AD", -"<* c #247665", -"[* c #20644A", -"}* c #2A8D71", -"|* c #30A384", -"1* c #32A183", -"2* c #229979", -"3* c #77C0AD", -"4* c #F6FAFC", -"5* c #4596CE", -"6* c #2182C5", -"7* c #106DB7", -"8* c #8BB8DC", -"9* c #7BC6CB", -"0* c #2EA7B1", -"a* c #2B9799", -"b* c #21664D", -"c* c #25775D", -"d* c #30A283", -"e* c #CAE7DF", -"f* c #B4D5EC", -"g* c #1C80C4", -"h* c #247EC1", -"i* c #2177BC", -"j* c #1E76BB", -"k* c #257ABE", -"l* c #DCEAF4", -"m* c #CDE9EB", -"n* c #28A2AB", -"o* c #267F73", -"p* c #2D9678", -"q* c #2F9E81", -"r* c #31A083", -"s* c #5DB49D", -"t* c #61A6D6", -"u* c #1C7FC4", -"v* c #2887C7", -"w* c #126EB8", -"x* c #68A3D2", -"y* c #5DB9C0", -"z* c #2DA4AC", -"A* c #2DA5AF", -"B* c #2C9FA4", -"C* c #226A54", -"D* c #21664E", -"E* c #278065", -"F* c #239979", -"G* c #AFDACE", -"H* c #D2E6F3", -"I* c #2685C7", -"J* c #227CC0", -"K* c #2278BD", -"L* c #1772BA", -"M* c #C1D9EC", -"N* c #FDFDFE", -"O* c #AFDCE0", -"P* c #209EA8", -"Q* c #278882", -"R* c #226C54", -"S* c #2E9C7E", -"T* c #2FA082", -"U* c #46AA8F", -"V* c #80B7DE", -"W* c #2682C4", -"X* c #1671B9", -"Y* c #4B91C9", -"Z* c #F2FAFA", -"`* c #44AEB6", -" = c #27A1AB", -".= c #23715E", -"+= c #20654B", -"@= c #2A8A6E", -"#= c #94CDBE", -"$= c #EBF3FA", -"%= c #378ECB", -"&= c #2484C6", -"*= c #227ABE", -"== c #A0C5E2", -"-= c #8FCFD3", -";= c #1E9DA7", -">= c #31A6AE", -",= c #2A9291", -"'= c #24735A", -")= c #35A285", -"!= c #E1F1ED", -"~= c #A0CAE6", -"{= c #2580C2", -"]= c #2178BC", -"^= c #1B74BB", -"/= c #3282C2", -"(= c #ECF4F9", -"_= c #DDF0F2", -":= c #31A6AF", -"<= c #2CA3AC", -"[= c #2EA7B2", -"}= c #24796A", -"|= c #20634A", -"1= c #2C9376", -"2= c #77C0AC", -"3= c #FBFDFE", -"4= c #4E9BD1", -"5= c #1F81C5", -"6= c #2A87C8", -"7= c #2885C6", -"8= c #2078BD", -"9= c #7FB1D9", -"0= c #70C1C7", -"a= c #2EA6B1", -"b= c #2B9A9D", -"c= c #267C62", -"d= c #C0DCEF", -"e= c #247DC1", -"f= c #1F77BC", -"g= c #D3E4F2", -"h= c #C3E5E8", -"i= c #25A0AA", -"j= c #268379", -"k= c #226A52", -"l= c #2E9A7C", -"m= c #6BACD8", -"n= c #1B7EC4", -"o= c #2783C5", -"p= c #5E9DCF", -"q= c #54B5BC", -"r= c #24A0AA", -"s= c #2CA1A8", -"t= c #226D57", -"u= c #29866B", -"v= c #DBEBF6", -"w= c #227BBF", -"x= c #2279BD", -"y= c #1570B9", -"z= c #B5D2E9", -"A= c #F9FCFD", -"B= c #A4D8DC", -"C= c #1F9EA8", -"D= c #288C88", -"E= c #237058", -"F= c #8CBEE1", -"G= c #2C89C9", -"H= c #2681C3", -"I= c #1872BA", -"J= c #418BC6", -"K= c #EBF6F7", -"L= c #3CABB3", -"M= c #29A2AC", -"N= c #2EA5AD", -"O= c #247462", -"P= c #21654E", -"Q= c #2B8F73", -"R= c #F1F7FB", -"S= c #3F93CD", -"T= c #237ABE", -"U= c #2076BC", -"V= c #92BDDE", -"W= c #81C7CE", -"X= c #1E9EA7", -"Y= c #2A9696", -"Z= c #216149", -"`= c #25795F", -" - c #2EA283", -".- c #2E9D7F", -"+- c #35A284", -"@- c #FBFDFD", -"#- c #ADD1EA", -"$- c #1778BE", -"%- c #2179BC", -"&- c #1B75BB", -"*- c #3282C3", -"=- c #BADDE8", -"-- c #31A7AE", -";- c #2BA4AD", -">- c #2DA5AD", -",- c #2FA8B2", -"'- c #217D70", -")- c #319778", -"!- c #36A588", -"~- c #35A185", -"{- c #30A083", -"]- c #568DC5", -"^- c #1D66B0", -"/- c #2A6FB5", -"(- c #276DB4", -"_- c #286EB4", -":- c #2569B3", -"<- c #2381A2", -"[- c #2F9FAF", -"}- c #2E9BAE", -"|- c #2E9CAE", -"1- c #309DAE", -"2- c #2899AE", -"3- c #55AEB4", -"4- c #409C7E", -"5- c #339579", -"6- c #35967A", -"7- c #2D9375", -"8- c #2B9274", -"9- c #2B9174", -"0- c #2B9073", -"a- c #5FAE98", -"b- c #65B49F", -"c- c #64B39E", -"d- c #65B39E", -"e- c #60B19B", -"f- c #59AE97", -"g- c #5AAE97", -"h- c #5CAF98", -"i- c #50AA92", -"j- c #97D4C6", -"k- c #CAD9EB", -"l- c #2564AE", -"m- c #2C69B1", -"n- c #2B68B0", -"o- c #2B68AF", -"p- c #2C68B4", -"q- c #22679E", -"r- c #0C6578", -"s- c #2B90A9", -"t- c #3099B1", -"u- c #2F97AF", -"v- c #3097AF", -"w- c #2E97AE", -"x- c #3098AF", -"y- c #E8F3F9", -"z- c #81BBA8", -"A- c #188364", -"B- c #2C8D70", -"C- c #2A8C6F", -"D- c #2A8D70", -"E- c #278769", -"F- c #1E8767", -"G- c #239476", -"H- c #239375", -"I- c #249476", -"J- c #259476", -"K- c #269375", -"L- c #229C7D", -"M- c #28AC8E", -"N- c #D8EFEA", -"O- c #769FCD", -"P- c #1C5FAC", -"Q- c #2D6BB2", -"R- c #2A69B1", -"S- c #2969B0", -"T- c #126783", -"U- c #0A6275", -"V- c #18768C", -"W- c #319BB2", -"X- c #2F97AE", -"Y- c #2F98AF", -"Z- c #339AB0", -"`- c #2091A9", -" ; c #8FC7D3", -".; c #E6F2EF", -"+; c #379479", -"@; c #278B6E", -"#; c #2B8E71", -"$; c #298C6E", -"%; c #298768", -"&; c #2E9578", -"*; c #319B7F", -"=; c #319A7E", -"-; c #309A7D", -";; c #309B7E", -">; c #30AD91", -",; c #1FA889", -"'; c #68C4AF", -"); c #E3EBF5", -"!; c #326FB4", -"~; c #2867B0", -"{; c #2B6AB1", -"]; c #2A69B0", -"^; c #2C69B5", -"/; c #1C6797", -"(; c #0B6576", -"_; c #0E657B", -":; c #0B6378", -"<; c #268AA1", -"[; c #3199B0", -"}; c #2995AD", -"|; c #45A3B8", -"1; c #F2F9FA", -"2; c #9ECBBE", -"3; c #1B8566", -"4; c #2D8F72", -"5; c #28886A", -"6; c #278768", -"7; c #278667", -"8; c #288A6B", -"9; c #2E997C", -"0; c #2E987B", -"a; c #2DA487", -"b; c #2BAD90", -"c; c #2DAD90", -"d; c #21A889", -"e; c #BBE4DB", -"f; c #97B6D9", -"g; c #1B5EAC", -"h; c #2E6CB2", -"i; c #2B69B2", -"j; c #2768AB", -"k; c #0E657C", -"l; c #0D6579", -"m; c #0E667B", -"n; c #136F84", -"o; c #3299B0", -"p; c #2292AA", -"q; c #AFD8E0", -"r; c #FAFCFB", -"s; c #4DA088", -"t; c #22896A", -"u; c #2C8E71", -"v; c #298B6D", -"w; c #278666", -"x; c #2B9173", -"y; c #2E9A7D", -"z; c #2D9C7F", -"A; c #2BAC8F", -"B; c #23A98B", -"C; c #4BB9A0", -"D; c #F8FCFB", -"E; c #F6F9FC", -"F; c #477EBC", -"G; c #2364AE", -"H; c #2C6AB2", -"I; c #18678E", -"J; c #0D657B", -"K; c #0D657A", -"L; c #0A6176", -"M; c #208399", -"N; c #329CB3", -"O; c #2593AB", -"P; c #5EAFC1", -"Q; c #BEDCD3", -"R; c #20886A", -"S; c #2A8D6F", -"T; c #278869", -"U; c #288869", -"V; c #2D977A", -"W; c #2E997D", -"X; c #2CA78A", -"Y; c #2FAD91", -"Z; c #1CA687", -"`; c #9BD8CA", -" > c #B6CCE4", -".> c #1F61AD", -"+> c #2C69B4", -"@> c #2368A4", -"#> c #0C6579", -"$> c #0C6479", -"%> c #0F697E", -"&> c #2D94AB", -"*> c #3099B0", -"=> c #2A95AD", -"-> c #CCE6EC", -";> c #69AF9A", -">> c #1D8667", -",> c #298A6C", -"'> c #278767", -")> c #2A8E70", -"!> c #2D9F82", -"~> c #2CAC90", -"{> c #28AB8E", -"]> c #36B095", -"^> c #E7F5F2", -"/> c #6391C6", -"(> c #1E61AD", -"_> c #2B69B3", -":> c #146687", -"<> c #0B6577", -"[> c #1C7A90", -"}> c #329AB0", -"|> c #2291AA", -"1> c #7BBECC", -"2> c #D9EBE5", -"3> c #298C6F", -"4> c #2B8D70", -"5> c #2D9578", -"6> c #2BA98C", -"7> c #1DA687", -"8> c #7BCCBA", -"9> c #D3E0EF", -"0> c #2968B0", -"a> c #1F689C", -"b> c #298FA5", -"c> c #319AB1", -"d> c #2C97AE", -"e> c #389DB2", -"f> c #E5F2F5", -"g> c #FCFDFD", -"h> c #89C0B0", -"i> c #2E8F72", -"j> c #28896A", -"k> c #298C6D", -"l> c #2DA285", -"m> c #27AB8D", -"n> c #CEECE5", -"o> c #82A7D1", -"p> c #1B5FAC", -"q> c #2A69B2", -"r> c #2969AE", -"s> c #10667F", -"t> c #0D667B", -"u> c #0B6277", -"v> c #167388", -"w> c #309AB1", -"x> c #9BCDD8", -"y> c #F0F7F5", -"z> c #3E987D", -"A> c #258A6C", -"B> c #298B6E", -"C> c #2B9375", -"D> c #2E9B7E", -"E> c #2BAB8E", -"F> c #2EAD90", -"G> c #20A88A", -"H> c #5DC0A9", -"I> c #ECF1F8", -"J> c #3974B7", -"K> c #2666B0", -"L> c #1B6794", -"M> c #24879E", -"N> c #2894AC", -"O> c #4DA7BB", -"P> c #F8FBFC", -"Q> c #A9D1C6", -"R> c #2CA588", -"S> c #2EAD91", -"T> c #1EA788", -"U> c #AFE0D5", -"V> c #A2BEDD", -"W> c #2668A9", -"X> c #0C6378", -"Y> c #126C81", -"Z> c #2492AB", -"`> c #B9DCE4", -" , c #57A58E", -"., c #208869", -"+, c #2D8E72", -"@, c #298A6D", -"#, c #2B9072", -"$, c #2D9D80", -"%, c #25AA8C", -"&, c #43B59C", -"*, c #5184BF", -"=, c #2163AE", -"-, c #2C6BB2", -";, c #16668B", -">, c #1F7F96", -",, c #319CB3", -"', c #68B4C5", -"), c #C9E2DB", -"!, c #24896C", -"~, c #2A8C70", -"{, c #278868", -"], c #2D9779", -"^, c #2CA88B", -"/, c #90D4C5", -"(, c #C2D4E9", -"_, c #2263AE", -":, c #2268A2", -"<, c #0D6479", -"[, c #0E677C", -"}, c #2B92A9", -"|, c #2E98AF", -"1, c #D5EAEF", -"2, c #74B5A2", -"3, c #1C8567", -"4, c #298D6F", -"5, c #2DA083", -"6, c #2CAC8F", -"7, c #29AB8E", -"8, c #30AE92", -"9, c #DEF2ED", -"0, c #6E98CA", -"a, c #1D60AC", -"b, c #126684", -"c, c #19788D", -"d, c #86C3D0", -"e, c #E2EFEB", -"f, c #329175", -"g, c #288C6E", -"h, c #2B8D71", -"i, c #2C9477", -"j, c #2BAA8D", -"k, c #70C7B3", -"l, c #DCE6F2", -"m, c #2B69B1", -"n, c #1E6799", -"o, c #278CA3", -"p, c #3099AF", -"q, c #2B96AD", -"r, c #3FA0B5", -"s, c #EDF6F8", -"t, c #96C7B8", -"u, c #288A6C", -"v, c #2DA386", -"w, c #C4E8E0", -"x, c #8EB0D6", -"y, c #2869AD", -"z, c #0F657E", -"A, c #157086", -"B, c #2191AA", -"C, c #A5D2DD", -"D, c #F6FAF9", -"E, c #479D83", -"F, c #23896B", -"G, c #2E9C7F", -"H, c #22A88A", -"I, c #53BCA4", -"J, c #F2F6FA", -"K, c #4179BA", -"L, c #2465AF", -"M, c #196791", -"N, c #0A6277", -"O, c #22849B", -"P, c #329BB3", -"Q, c #2694AC", -"R, c #56ABBE", -"S, c #B5D7CD", -"T, c #1E8768", -"U, c #2D987A", -"V, c #2CA689", -"W, c #1DA788", -"X, c #A4DBCF", -"Y, c #AEC5E1", -"Z, c #2468A7", -"`, c #106A80", -" ' c #2D95AC", -".' c #2794AC", -"+' c #C4E2E8", -"@' c #61AB95", -"#' c #2A8F70", -"$' c #2D9E81", -"%' c #2CAD90", -"&' c #27AA8D", -"*' c #3CB398", -"=' c #EDF8F5", -"-' c #5B8BC3", -";' c #156689", -">' c #1D7D93", -",' c #329BB2", -"'' c #72B9C9", -")' c #D2E7E1", -"!' c #288C6F", -"~' c #2D9679", -"{' c #2CA98C", -"]' c #1CA688", -"^' c #84CFBE", -"/' c #CCDBEC", -"(' c #2566B0", -"_' c #2A6AB0", -":' c #20689F", -"<' c #2A90A7", -"[' c #2D97AE", -"}' c #DEEEF2", -"|' c #80BBAA", -"1' c #1C8566", -"2' c #28896B", -"3' c #2DA184", -"4' c #2AAC8F", -"5' c #D5EFE9", -"6' c #79A1CE", -"7' c #1D5FAC", -"8' c #2F6CB2", -"9' c #136783", -"0' c #0E6679", -"a' c #0F667B", -"b' c #0F677C", -"c' c #0D6378", -"d' c #19768B", -"e' c #369DB4", -"f' c #2090A9", -"g' c #91C8D5", -"h' c #EBF4F1", -"i' c #38957A", -"j' c #278C6E", -"k' c #2D8D70", -"l' c #298869", -"m' c #288768", -"n' c #2D9477", -"o' c #2DAC8F", -"p' c #67C4AF", -"q' c #E5EDF5", -"r' c #346FB8", -"s' c #0F5F90", -"t' c #046072", -"u' c #056076", -"v' c #046075", -"w' c #045E74", -"x' c #168199", -"y' c #47A6BA", -"z' c #F2F8FA", -"A' c #A2CDC0", -"B' c #178263", -"C' c #228566", -"D' c #1F8363", -"E' c #1F8262", -"F' c #208666", -"G' c #279476", -"H' c #25A284", -"I' c #23AA8C", -"J' c #26AA8C", -"K' c #18A585", -"L' c #B3E1D7", -"M' c #A1BED9", -"N' c #2A768E", -"O' c #36808F", -"P' c #347E8F", -"Q' c #347F90", -"R' c #357D8E", -"S' c #308194", -"T' c #B5DBE3", -"U' c #66AC97", -"V' c #44977C", -"W' c #4B9B81", -"X' c #4A9A80", -"Y' c #4A987E", -"Z' c #4DA58C", -"`' c #4DBAA2", -" ) c #4DB9A1", -".) c #4FBAA2", -"+) c #46B69D", -"@) c #6DC5B1", -"#) c #FDFDFD", -"$) c #FCFCFC", -"%) c #FBFBFB", -"&) c #D5D5D5", -"*) c #C2C2C2", -"=) c #C6C6C6", -"-) c #C5C5C5", -";) c #C4C4C4", -">) c #CACACA", -",) c #E4E4E4", -"') c #C1C1C1", -")) c #F9F9F9", -"!) c #DBDBDA", -"~) c #A9A9A8", -"{) c #848483", -"]) c #747473", -"^) c #757573", -"/) c #767675", -"() c #8A8A89", -"_) c #ADADAC", -":) c #DEDEDE", -"<) c #858584", -"[) c #020200", -"}) c #171715", -"|) c #141412", -"1) c #121210", -"2) c #161614", -"3) c #D9D9D9", -"4) c #6E6E6C", -"5) c #040402", -"6) c #151513", -"7) c #0A0A07", -"8) c #3F3F3D", -"9) c #B1B1B0", -"0) c #4E4E4C", -"a) c #20201E", -"b) c #10100E", -"c) c #090907", -"d) c #060604", -"e) c #050503", -"f) c #070705", -"g) c #131311", -"h) c #181816", -"i) c #8F8F8E", -"j) c #D2D2D2", -"k) c #1C1C1A", -"l) c #1F1F1D", -"m) c #232321", -"n) c #0F0F0D", -"o) c #9F9F9E", -"p) c #F6F6F6", -"q) c #373736", -"r) c #191917", -"s) c #10100D", -"t) c #90908F", -"u) c #E3E3E2", -"v) c #565654", -"w) c #0E0E0C", -"x) c #30302E", -"y) c #444443", -"z) c #4C4C4B", -"A) c #424240", -"B) c #2E2E2C", -"C) c #1B1B19", -"D) c #000000", -"E) c #A6A6A6", -"F) c #434341", -"G) c #5E5E5D", -"H) c #C6C6C5", -"I) c #1E1E1D", -"J) c #1E1E1C", -"K) c #1D1D1B", -"L) c #D4D4D4", -"M) c #D6D6D5", -"N) c #2D2D2B", -"O) c #21211F", -"P) c #777776", -"Q) c #EFEFEE", -"R) c #FDFDFC", -"S) c #EDEDED", -"T) c #C5C5C4", -"U) c #7D7D7C", -"V) c #E6E6E5", -"W) c #EBEBEB", -"X) c #696968", -"Y) c #D8D8D8", -"Z) c #858583", -"`) c #0E0E0B", -" ! c #0D0D0B", -".! c #141411", -"+! c #494947", -"@! c #E8E8E7", -"#! c #31312F", -"$! c #171714", -"%! c #454543", -"&! c #5C5C5A", -"*! c #CDCDCD", -"=! c #C9C9C8", -"-! c #131310", -";! c #BABABA", -">! c #474746", -",! c #929291", -"'! c #646462", -")! c #464645", -"!! c #F3F3F2", -"~! c #D0D0D0", -"{! c #3E3E3C", -"]! c #7A7A79", -"^! c #E3E3E3", -"/! c #B3B3B2", -"(! c #9D9D9C", -"_! c #9B9B9A", -":! c #EFEFEF", -"~ c #F0F0F0", -",~ c #292927", -"'~ c #7B7B7A", -")~ c #D7D7D7", -"!~ c #4F4F4D", -"~~ c #0A0A08", -"{~ c #8C8C8A", -"]~ c #5B5B5A", -"^~ c #9E9E9D", -"/~ c #C0C0C0", -"(~ c #0C0C0B", -"_~ c #A3A3A2", -":~ c #9A9A99", -"<~ c #E8E8E8", -"[~ c #1A1A18", -"}~ c #DADADA", -"|~ c #C2C2C1", -"1~ c #2A2A28", -"2~ c #DBDBDB", -"3~ c #80807F", -"4~ c #828281", -"5~ c #686867", -"6~ c #373735", -"7~ c #424241", -"8~ c #ADADAD", -"9~ c #262624", -"0~ c #191916", -"a~ c #2C2C2B", -"b~ c #EAEAEA", -"c~ c #525251", -"d~ c #B8B8B7", -"e~ c #4F4F4E", -"f~ c #0C0C0A", -"g~ c #AAAAA9", -"h~ c #C1C1C0", -"i~ c #454544", -"j~ c #989897", -"k~ c #C0C0BF", -"l~ c #B5B5B4", -"m~ c #E5E5E4", -"n~ c #5A5A59", -"o~ c #B1B1B1", -"p~ c #11110E", -"q~ c #3B3B3A", -"r~ c #F4F4F4", -"s~ c #F0F0F1", -"t~ c #6B6B69", -"u~ c #898988", -"v~ c #A2A2A2", -"w~ c #DCDCDC", -"x~ c #CECECD", -"y~ c #555554", -"z~ c #343432", -"A~ c #A1A1A1", -"B~ c #6F6F6E", -"C~ c #919190", -"D~ c #444442", -"E~ c #30302F", -"F~ c #F1F1F0", -"G~ c #575756", -"H~ c #D1D1D0", -"I~ c #BBBBBA", -"J~ c #717170", -"K~ c #AFAFAF", -"L~ c #ACACAC", -"M~ c #C9C9C9", -"N~ c #EEEEEE", -"O~ c #E9E9E9", -"P~ c #646463", -"Q~ c #FFFFFE", -"R~ c #81817F", -"S~ c #767674", -"T~ c #595957", -"U~ c #D2D2D1", -"V~ c #A8A8A7", -"W~ c #565655", -"X~ c #323230", -"Y~ c #B9B9B9", -"Z~ c #5D5D5C", -"`~ c #161613", -" { c #B0B0B0", -".{ c #DCDCDB", -"+{ c #868685", -"@{ c #6C6C6A", -"#{ c #ACACAB", -"${ c #656564", -"%{ c #E1E1E1", -"&{ c #151512", -"*{ c #696967", -"={ c #D0D0CF", -"-{ c #6F6F6D", -";{ c #CECECE", -">{ c #353533", -",{ c #4B4B4A", -"'{ c #4E4E4D", -"){ c #A1A1A0", -"!{ c #A4A4A3", -"~{ c #575755", -"{{ c #B0B0AF", -"]{ c #C7C7C6", -"^{ c #494948", -"/{ c #474745", -"({ c #9B9B9B", -"_{ c #20201F", -":{ c #E7E7E7", -"<{ c #0F0F0C", -"[{ c #BDBDBD", -"}{ c #5F5F5E", -"|{ c #555553", -"1{ c #DDDDDD", -"2{ c #12120F", -"3{ c #E0E0DF", -"4{ c #999998", -"5{ c #727271", -"6{ c #878786", -"7{ c #4D4D4C", -"8{ c #DFDFDF", -"9{ c #D4D4D3", -"0{ c #DDDDDC", -"a{ c #3D3D3C", -"b{ c #666665", -"c{ c #545453", -"d{ c #71716F", -"e{ c #1F1F1E", -"f{ c #484847", -"g{ c #959594", -"h{ c #4B4B49", -"i{ c #D1D1D1", -"j{ c #40403F", -"k{ c #7C7C7A", -"l{ c #979796", -"m{ c #262625", -"n{ c #F3F3F3", -"o{ c #585856", -"p{ c #464644", -"q{ c #595958", -"r{ c #BEBEBD", -"s{ c #FCFCFB", -"t{ c #A7A7A6", -"u{ c #1C1C19", -"v{ c #B9B9B8", -"w{ c #BCBCBB", -"x{ c #A5A5A5", -"y{ c #969695", -"z{ c #626261", -"A{ c #B4B4B4", -"B{ c #4A4A49", -"C{ c #CFCFCF", -"D{ c #1B1B18", -"E{ c #60605F", -"F{ c #A6A6A5", -"G{ c #0D0D0A", -"H{ c #272726", -"I{ c #22221F", -"J{ c #777775", -"K{ c #F4F4F3", -"L{ c #6E6E6D", -"M{ c #1C1C1B", -"N{ c #E2E2E1", -"O{ c #080805", -"P{ c #8E8E8E", -"Q{ c #737372", -"R{ c #AFAFAE", -"S{ c #282826", -"T{ c #393937", -"U{ c #A7A7A7", -"V{ c #5A5A58", -"W{ c #2C2C2A", -"X{ c #545452", -"Y{ c #070704", -"Z{ c #B3B3B3", -"`{ c #F9F9F8", -" ] c #8C8C8B", -".] c #70706F", -"+] c #A6A6A4", -"@] c #D3D3D2", -"#] c #949493", -"$] c #393938", -"%] c #030301", -"&] c #050502", -"*] c #ABABAB", -"=] c #838382", -"-] c #B2B2B1", -";] c #CCCCCB", -">] c #CFCFCE", -",] c #C8C8C8", -"'] c #8F8F8D", -")] c #9B9B99", -"!] c #5C5C5B", -"~] c #666664", -"{] c #888887", -"]] c #656563", -"^] c #4F4F4C", -"/] c #CBCBCA", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . + @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ % % % % % % % % % % % % % % % % % % % % % % % % % % & & & & & & & & & & & & & & & & & & & & & & & & & & & & . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . * . = - ; > > > > > > > > > > > > > > > > > > > > > > ; , ' . ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ! ~ { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ^ / ( _ ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( : < & . . . . . . . . . ", -" . . . . . . . . + . [ } | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 4 5 . ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 a b c d d d d d d d d d d d d d d d d d d d d d d e f g . h . . . . . . . . ", -" . . . . . . . . . . * . i j k l l l l l l l l l l l l l l l l l l l l l m n o p . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . q r s t u v v v v v v v v v v v v v v v v v v v v v w x y z A A A A A A A A A A A A A A A A A A A A A A B C D E . . . . . . . . . . . ", -" . . . . . . . . . . ) . F G H I I I I I I I I I I I I I I I I I I I I I J K L M N . + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . O P Q R S T U U U U U U U U U U U U U U U U U U U U V W X Y Z ` .........................................+.e @.. h . . . . . . . . . . ", -" . . . . . . . . . . . . # . #.1 l I I I I I I I I I I I I I I I I I I I I $.K %.&.*.. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . =.-.;.Q >.,.w U U U U U U U U U U U U U U U U U U U U '.).!.~.~.!.{.......................................+.].^.. /.. . . . . . . . . . . . ", -" . . . . . . . . . . . . . * . (._.:.H I I I I I I I I I I I I I I I I I I <.K K K [.o }.. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . |.1.2.R R 3.4.5.U U U U U U U U U U U U U U U U U U 6.7.Y ~.~.~.X 8. .......................................9.0.. /.. . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . @ . a.1 l I I I I I I I I I I I I I I I I I b.K K K K c.d.e.f.. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /.. g.h.i.j.R R k.l.U U U U U U U U U U U U U U U U U U U V m.n.~.~.~.~.~.9.o.................................A p.q.. h . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . * . r.s.j t.I I I I I I I I I I I I I I I I u.K K K K K v.o w.. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . x.y.2.R R R R >.z.5.U U U U U U U U U U U U U U U U A.B.C.~.~.~.~.~.X z ...............................o.9.D.E.. * . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . + . F.G.H.I I I I I I I I I I I I I I I b.K K K K K K I.J.K.L.. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . M.N.O.R R R R R R j.P.T U U U U U U U U U U U U U U U w Q.Y ~.~.~.~.~.~.X R. .............................A S.< . & . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . ) . T.U.V.I I I I I I I I I I I I I I $.K K K K K K K %.W.X.. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h Y.Z.Q R R R R R R >.`.T U U U U U U U U U U U U U U A. +!.~.~.~.~.~.~.~.Z y ............................ ..+++% . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . ) . @+#+$+H I I I I I I I I I I I I J K K K K K K K K K c.%+&+. + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . *+=+l.R R R R R R R R k.-+w U U U U U U U U U U U U ;+>+~.~.~.~.~.~.~.~.~.~.X S. ......................... .,+'+. h . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . + . )+1 l I I I I I I I I I I I I $.K K K K K K K K K c.%+!+~+. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . {+]+^+/+R R R R R R R R 3.(+T U U U U U U U U U U U U A._+!.~.~.~.~.~.~.~.~.~.~.:+C ......................A e <+. /.. . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . * . [+}+|+t.I I I I I I I I I I 1+K K K K K K K K K K K [.o 2+. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . 3+1.2.R R R R R R R R R R 4+5+5.U U U U U U U U U U A.6+7+~.~.~.~.~.~.~.~.~.~.~.X 8+ .....................9+..0+. /.. . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . # . a+b+l I I I I I I I I I b.K K K K K K K K K K K K I.c+d+e+. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . f+j.R R R R R R R R R R R R k.Q V U U U U U U U U U U U g+n.~.~.~.~.~.~.~.~.~.~.~.~.~.h+o.................A p.i+. h . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . j+k+G.H.I I I I I I I I u.K K K K K K K K K K K K K [.o l+. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . m+P Q R R R R R R R R R R R R >.n+5.U U U U U U U U A.o+!.~.~.~.~.~.~.~.~.~.~.~.~.~.X p+o...............o.h+q+r+. . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . + . s+t+u+I I I I I I I J K K K K K K K K K K K K K K K K v+w+. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . x+y+Q R R R R R R R R R R R R R R R z+T U U U U U U V A+X ~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.Z ` .............+.e B+. h . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . + . C+b+l I I I I I I $.K K K K K K K K K K K K K K K %.D+E+. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . E F+7 Q R R R R R R R R R R R R R R >.G+w U U U U U U A.H+!.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.Z !.............+.,+I+. . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . J+K+L+H I I I I <.K K K K K K K K K K K K K K K K K %.D+M+. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . N+1.2.R R R R R R R R R R R R R R R R 3.O+5.U U U U ;+P+Y ~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.X Q+ .........o.h+R+. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . @ . > 1 l I I I H $.K K K K K K K K K K K K K K K K K c.M S+T+. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /.. U+V+W+j.R R R R R R R R R R R R R R R R k.X+U U U U U ;+Y+!.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.9.o.....A p.Z+. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . T+`+ @t.I I 1+K K K K K K K K K K K K K K K K K K K v.o .@. @ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . +@@@2.R R R R R R R R R R R R R R R R R R >.#@5.U U A.$@n.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.X %@o.....&@*@=@. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . -@U.H.I b.K K K K K K K K K K K K K K K K K K K K I.;@>@,@. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . '@)@j.R R R R R R R R R R R R R R R R R R R k.!@A.T V T ~@Y ~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.Z {@o.A p.( . & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. ^@G.V.u.K K K K K K K K K K K K K K K K K K K K K [.o /@. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . (@_@Q R R R R R R R R R R R R R R R R R R R R >.:@5.A.<@!.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.Z p++.[@}@E . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . |@L+1@I.K K K K K K K K K K K K K K K K K K K K K K L M 2@. + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . 3@P Q R R R R R R R R R R R R R R R R R R R R R R k.S t Q.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.X 4@5@6@. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . 7@8@9@K K K K K K K K K K K K K K K K K K K K K K %.&.0@* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . a@b@;.O.R R R R R R R R R R R R R R R R R R R R R R R c@d@y e@n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.f@g@h@. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. i@j@k@l@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@n@o@p@. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . % . q@r@s@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@u@v@w@x@y@z@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@B@a@. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . C@D@E@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@G@H@I@J@. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . K@L@M@N@O@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@Q@R@S@. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . T@U@V@W@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@m@X@Y@Z@`@. #. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . .#+#@###$#P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@%#&#*#. /././././././././././././././././././././././././././.* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . =#-#W@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@;#>#,#'#)#. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . !#~#{#]#^#$#P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@$#/#(#. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . _#:#<#F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@m@[#}#|#1#2#3#. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & 4#5#{#6#]#7#$#P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@8#9#0#. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . a#W@b#c#F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@d#e#|#|#|#'#f#g#. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . h#+#@#6#6#]#{#P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@$#i#j#k#. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . l#m#E@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@l@n#}#|#|#|#'#o#p#T@. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . q#r#s#t#6#6#6#]#u#$#P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@8#v#w#. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . x#y#z#W@F@F@F@F@F@F@F@F@F@F@F@F@F@F@m@A#|#|#|#|#|#|#B#C#D#. #. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . E#F#^#6#6#6#6#6#G#i#$#P@P@P@P@P@P@P@P@P@P@P@P@P@P@%#H#I#J#. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . K#L#<#F@F@F@F@F@F@F@F@F@F@F@F@F@F@l@M#}#|#|#|#|#|#N#O#P#Q#. ]@. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . R#6#6#6#6#6#6#6#6#]#S#$#P@P@P@P@P@P@P@P@P@P@P@P@P@P@%#T#U#. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * * V#-#<#F@F@F@F@F@F@F@F@F@F@F@F@m@X@W#|#|#|#|#|#|#|#B#C#X#. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . Y#Z#@#6#6#6#6#6#6#6#6#`#$#P@P@P@P@P@P@P@P@P@P@P@P@Q@ $.$. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . +$@$G@F@F@F@F@F@F@F@F@F@F@F@F@#$;#|#|#|#|#|#|#|#|#|#|#O#$$. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . %$&${#6#6#6#6#6#6#6#6#]#*$P@P@P@P@P@P@P@P@P@P@P@P@P@P@=$-$. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . ;$>$E@F@F@F@F@F@F@F@F@F@F@m@,$}#|#|#|#|#|#|#|#|#|#'$)$!$. ]@. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . ~${$~#{#6#6#6#6#6#6#6#6#6#]#7#$#P@P@P@P@P@P@P@P@P@P@8#v#]$. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. ^$/$($c#F@F@F@F@F@F@F@F@l@d#|#|#|#|#|#|#|#|#|#|#|#|#'$_$:$. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . % . <$[$@#6#6#6#6#6#6#6#6#6#6#6#{#O@P@P@P@P@P@P@P@P@P@N@}$|$1$. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . 2$m#E@F@F@F@F@F@F@F@F@m@3$}#|#|#|#|#|#|#|#|#|#|#|#'#4$5$6$. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /.. 7$8$9$G#6#6#6#6#6#6#6#6#6#6#6#]#0$$#P@P@P@P@P@P@P@P@8#9#a$. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . b$c$@$W@F@F@F@F@F@F@m@d$}#|#|#|#|#|#|#|#|#|#|#|#|#|#B#e$f$. #. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . g$F#@#6#6#6#6#6#6#6#6#6#6#6#6#6#6#i#$#P@P@P@P@P@P@%#h$i$% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . j$k$<#F@F@F@F@F@F@F@l$W#|#|#|#|#|#|#|#|#|#|#|#|#|#>#m$n$o$. ]@. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . p$s#G#6#6#6#6#6#6#6#6#6#6#6#6#6#6#]#q$$#P@P@P@P@P@P@%#r$s$. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . t$k$<#F@F@F@F@m@u$}#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#1#v$w$. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /.. x$&$y$6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#]#z$$#P@P@P@P@8#A$B$. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . C$D$F@F@F@F@F@E$F$|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#'#o#G$. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . H$I$y$6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#]#y$P@P@P@P@$#=$8#J$. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . K$m#E@F@F@m@n#}#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#L$f#M$) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . N$O$P${#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#]#Q$$#P@P@8#v#R$. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. S$T$U$c#l@V$|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#B#v$W$. #. . . . . . . . . . . . . . . . . . . . . . . . . . . % . X$F#^#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#G#=$P@N@/#Y$Z$. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . `$m# %m@M#}#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#N#.%+%@%. * . . . . . . . . . . . . . . . . . . . . . . . . . h . #%^#$%G#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#]#%%$#Q@A$&%. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . *%=%-%;%}#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#B#C#>%. #. . . . . . . . . . . . . . . . . . . . . . . . . & . ,%'%)%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%~%{%]%. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . ^%/%(%|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#>#,#e#_%. ) . . . . . . . . . . . . . . . . . . . . . . . & . :%<%[%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%|%1%2%3%. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . 4%5%6%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%6%8%9%. ) . . . . . . . . . . . . . . . . . . . . . . . . ) 0%a%b%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%d%e%f%. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . g%h%i%j%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%l%m%n%. #. . . . . . . . . . . . . . . . . . . . . # . o%p%q%r%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%t%u%v%w%. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. x%y%z%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%A%B%C%D%E%. * . . . . . . . . . . . . . . . . . . . * . F%G%H%I%J%K%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%K%M%N%O%P%. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . Q%R%S%T%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%U%V%W%X%. #. . . . . . . . . . . . . . . . . . . # . Y%Z%`% &.&L%+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&L%@&#&$&%&&&*&. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. =&-&l%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%;&>&,&'&)&!&~&. ]@. . . . . . . . . . . . . . . . . & . {&]&^&/&(&_&:&L%+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&<&@&[&}&|&1&2&. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3&4&5&k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%6&7&8&8&9&0&a&. #. . . . . . . . . . . . . . . . . & . b&c&d&/&e&f&g&h&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&L%i&j&}&k&l&m&n&o&. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . p&q&T%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%A%r&s&8&8&8&8&t&u&. & . . . . . . . . . . . . . . . # . v&w&x&^&^&y&z&A&B&g&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&C&D&E&F&l&l&G&H&I&E.. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . J&K&z%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%A%L&8&8&8&8&8&V%M&N&. ]@. . . . . . . . . . . . . . * . ~$O&P&x&^&^&^&Q&R&S&J%T&+&+&+&+&+&+&+&+&+&+&+&+&+&+&L%s%U&V&k&l&l&l&W&X&Y&. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. Z&`& *j%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%.*s&8&8&8&8&8&V%+*@*. #. . . . . . . . . . . . . # . #*$*%*^&^&^&^&y&&***:&L%+&+&+&+&+&+&+&+&+&+&+&+&+&+&@&=*k&l&l&l&l&l&-*;*>*,*. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. '*)*z%k%k%k%k%k%k%k%k%k%k%k%k%k%A%!*s&8&8&8&8&8&8&~*{*]*^*. * . . . . . . . . . . . ]@. /*(*_*:*^&^&^&^&^&/&e&<*[*L%+&+&+&+&+&+&+&+&+&+&+&+&L%M%}*|*k&l&l&l&l&l&1*2*3*. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . 4*5*6*h%k%k%k%k%k%k%k%k%k%k%k%k%i%U%8&8&8&8&8&8&8&8&9&7*8*. #. . . . . . . . . . . # . 9*$*d&^&^&^&^&^&^&/&0*a*b*+&+&+&+&+&+&+&+&+&+&+&+&L%M%c*d*l&l&l&l&l&l&l&l&$&H&e*. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . f*g*l%k%k%k%k%k%k%k%k%k%k%k%;&h*,&8&8&8&8&8&8&8&8&i*j*k*l*. ) . . . . . . . . . & . m*n*:*^&^&^&^&^&^&^&^&/&&*o*B&g&+&+&+&+&+&+&+&+&+&+&+&+&p*F&q*l&l&l&l&l&l&l&r*1&s*. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . t*u*l%k%k%k%k%k%k%k%k%k%v*6&8&8&8&8&8&8&8&8&8&8&8&V%w*x*. & . . . . . . . . . * . y*w&d&^&^&^&^&^&^&^&^&z*A*B*C*D*+&+&+&+&+&+&+&+&+&L%i&E*|*k&l&l&l&l&l&l&l&l&l&m&F*G*. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . H*I*k%k%k%k%k%k%k%k%k%k%A%J*,&8&8&8&8&8&8&8&8&8&8&8&K*L*M*. N*. . . . . . . # . O*P*d&^&^&^&^&^&^&^&^&^&^&y&z&Q*B&g&+&+&+&+&+&+&+&+&D*R*S*T*l&l&l&l&l&l&l&l&l&l&G&H&U*Z$. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . V*y%z%k%k%k%k%k%k%k%;&W*s&8&8&8&8&8&8&8&8&8&8&8&8&K*X*Y*& . . . . . . . * . Z*`* =x&^&^&^&^&^&^&^&^&^&^&^&^&z*.=+=L%+&+&+&+&+&+&L%i&@=|*k&l&l&l&l&l&l&l&l&l&l&l&W&X&#=. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. $=%=&=T%k%k%k%k%k%k%k%*=s&8&8&8&8&8&8&8&8&8&8&8&8&8&V%w*==. #. . . . . # . -=;=>=^&^&^&^&^&^&^&^&^&^&^&^&/&&*,=[*L%+&+&+&+&+&L%M%'=T*l&l&l&l&l&l&l&l&l&l&l&l&l&-*;*)=!=. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. ~=K&l%k%k%k%k%k%A%{=s&8&8&8&8&8&8&8&8&8&8&8&8&8&8&]=^=/=(=. ]@. . . & . _=:=<=:*^&^&^&^&^&^&^&^&^&^&^&^&^&/&[=}=|=L%+&+&+&+&+&D*1=}&k&l&l&l&l&l&l&l&l&l&l&l&l&l&1*2*2=. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3=4=5=6=k%k%k%k%7=8=8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&9&W%9=. #. . . & . 0=P*d&^&^&^&^&^&^&^&^&^&^&^&^&^&^&/&a=b=+&+&+&+&+&L%i&c=|*k&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&$&H&e*. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . d=5=h%k%k%k%A%e=s&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&f=g=. & . & . h=i=x&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&y&z&j=B&g&+&+&D*k=l=T*l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&r*1&s*. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . m=n=l%k%A%o=8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&V%+*p=. ) * . # q=r=x&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&Q&s=t=b*T&L%i&u=|*k&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&m&F*G*. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . v=l%i%j%;&w=,&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&x=y=z=. A=. B=C=d&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&y&z&D=:&K%@&E=l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&G&H&U*Z$. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. F=y%G=H=s&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&K*I=J=4*. K=L=M=N=^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&A*O=+=P=Q=}&k&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&W&X&#=. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . R=S=q&T=U=8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&9&7*V=. W=X=>=^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&/&[=Y=Z=`= -.-l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&-*;*+-!=. @-& & & h * * * * * * * * * * * * * * * * * * * * * /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. #-$-K*7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&%-&-*-=---;->->->->->->->->->->->->->->->->->->->->->->-z*,-'-)-!-~-{-T*l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&1*2*3*. & . . . . . . . . . . . . . . . . . . . . . . . . . . /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. ]-^-/-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-_-:-<-[-}-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-1-2-3-4-5-6-7-8-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-0-a-b-c-c-d-e-f-g-g-g-g-g-g-g-g-g-g-g-g-g-g-g-g-g-g-h-i-j-. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N*. k-l-m-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-o-p-q-r-s-t-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-v-w-x-y-z-A-B-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-D-E-F-G-H-H-H-I-J-J-J-J-J-J-J-J-J-J-J-J-J-J-J-J-J-J-J-K-L-M-N-. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. O-P-Q-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-S-T-U-V-W-X-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Z-`- ;. .;+;@;#;D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-$;E-%;&;*;=;=;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;;;>;,;';. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. );!;~;{;R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-];^;/;(;_;:;<;W-X-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-[;};|;1;h . 2;3;4;D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-5;6;7;8;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;0;a;b;c;d;e;. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. f;g;h;R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-i;j;k;l;m;:;n;Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-o;p;q;. #. r;s;t;u;D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-v;6;6;6;w;x;y;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;0;z;A;A;c;B;C;D;. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . E;F;G;H;R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-];^;I;(;J;K;m;L;M;N;w-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-o;O;P;. * . % . Q;R;u;D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-S;T;6;6;6;6;U;V;W;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;0;X;b;A;A;Y;Z;`;. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. >.>Q-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-];+>@>#>K;K;K;K;$>%>&>*>Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-x-=>->. & . . & . ;>>>4;D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-}*,>'>6;6;6;6;7;)>y;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;0;!>b;A;A;A;~>{>]>^>. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . />(>Q-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-_>:><>J;K;K;K;m;L;[>N;w-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-}>|>1>. # . . . & . 2>u;3>4>D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-C-6;6;6;6;6;6;6;6;5>y;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;6>b;A;A;A;A;Y;7>8>. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . 9>0>R-R-R-R-R-R-R-R-R-R-R-R-R-R-];^;a>(;J;K;K;K;K;K;K;K;b>c>X-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-x-d>e>f>. ]@. . . . g>. h>3;i>D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-j>'>6;6;6;6;6;6;7;k>y;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;0;l>b;A;A;A;A;A;A;A;m>n>. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. o>p>h;R-R-R-R-R-R-R-R-R-R-R-R-q>r>s>#>K;K;K;K;K;K;t>u>v>w>Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Z-`-x>. #. . . . . /.. y>z>A>#;D-D-D-D-D-D-D-D-D-D-D-D-}*B>6;6;6;6;6;6;6;6;6;7;C>y;9;9;9;9;9;9;9;9;9;9;9;9;9;0;D>E>A;A;A;A;A;A;A;F>G>H>. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. I>J>K>{;R-R-R-R-R-R-R-R-R-R-];^;L>(;J;K;K;K;K;K;K;K;t>u>M>W-w-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-[;N>O>P>. * . . . . . . g>. Q>>>4;D-D-D-D-D-D-D-D-D-D-D-D-D-U;6;6;6;6;6;6;6;6;6;7;j>0;9;9;9;9;9;9;9;9;9;9;9;9;9;0;R>b;A;A;A;A;A;A;A;A;S>T>U>. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. V>P-Q-R-R-R-R-R-R-R-R-R-R-_>W>J;K;K;K;K;K;K;K;K;K;K;X>Y>X-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-[;Z>`>. # . . . . . . . . /.. ,.,+,D-D-D-D-D-D-D-D-D-D-D-@,6;6;6;6;6;6;6;6;6;6;6;7;#,y;9;9;9;9;9;9;9;9;9;9;9;0;$,b;A;A;A;A;A;A;A;A;A;c;%,&,N$. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3=*,=,-,R-R-R-R-R-R-R-R-];+>;,<>J;K;K;K;K;K;K;K;K;K;m;L;>,,,w-Y-Y-Y-Y-Y-Y-Y-Y-o;Z>',. & . . . . . . . . . $ . ),!,#;D-D-D-D-D-D-D-D-D-D-~,{,6;6;6;6;6;6;6;6;6;6;6;6;6;],y;9;9;9;9;9;9;9;9;9;9;0;^,b;A;A;A;A;A;A;A;A;A;A;Y;Z;/,. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N*. (,_,H;R-R-R-R-R-R-R-];+>:,r-K;K;K;K;K;K;K;K;K;K;K;K;<,[,},*>Y-Y-Y-Y-Y-Y-Y-Y-Y-|,1,. & . . . . . . . . . . $ . 2,3,i>D-D-D-D-D-D-D-D-D-,>6;6;6;6;6;6;6;6;6;6;6;6;6;7;4,y;9;9;9;9;9;9;9;9;9;0;5,b;A;A;A;A;A;A;A;A;A;A;A;6,7,8,9,. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N*. 0,a,Q-R-R-R-R-R-R-R-R-b,r-J;K;K;K;K;K;K;K;K;K;K;K;m;u>c,W-X-Y-Y-Y-Y-Y-Y-Z-`-d,. # . . . . . . . . . . . h . e,f,g,h,D-D-D-D-D-D-D-3>6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;7;i,y;9;9;9;9;9;9;9;9;y;j,b;A;A;A;A;A;A;A;A;A;A;A;A;S>T>k,. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . l,h;0>m,R-R-R-R-];^;n,(;J;K;K;K;K;K;K;K;K;K;K;K;K;K;K;$>o,W-X-Y-Y-Y-Y-p,q,r,s,. * . . . . . . . . . . . . g>. t,3;i>D-D-D-D-D-D-}*j>'>6;6;6;6;6;6;6;6;6;6;6;6;6;6;7;u,9;9;9;9;9;9;9;9;0;v,b;A;A;A;A;A;A;A;A;A;A;A;A;A;A;c;B;w,. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. x,g;h;R-R-R-R-i;y,z,#>K;K;K;K;K;K;K;K;K;K;K;K;K;K;t>:;A,*>Y-Y-Y-Y-Y-}>B,C,. # . . . . . . . . . . . . . * . D,E,F,u;D-D-D-D-}*B>6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;7;8-y;9;9;9;9;9;0;G,A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;c;H,I,# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. J,K,L,H;R-R-];^;M,(;J;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;t>N,O,P,w-Y-Y-[;Q,R, #. . . . . . . . . . . . . . . . % . S,T,4;D-D-D-D-D-T;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;j>U,9;9;9;9;9;0;V,b;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;S>W,X,. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. Y,a,Q-R-];_>Z,#>K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;$>`, '*>Y-Y-[;.'+'. & . . . . . . . . . . . . . . . . & . @'T,4;D-D-}*,>'>6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;7;#'y;9;9;9;0;$'b;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;%'&'*'='. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. -'.>Q-R-_>;'<>J;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;m;L;>','w-}>p;''. & . . . . . . . . . . . . . . . . . & . )'!'D-D-D-C-E-6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;~'y;9;9;9;{'b;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;Y;]'^'. # . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N*. /'('_'^;:'<>J;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;<'c>['Z-}'. & . . . . . . . . . . . . . . . . . . % . |'1'i>D-2'6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;7;$;y;9;0;3'b;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;4'5'. & . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. 6'7'8'9'0'a'a'a'a'a'a'a'a'a'a'a'a'a'a'a'a'a'a'a'a'b'c'd'e'f'g'. # . . . . . . . . . . . . . . . . . . . h . h'i'j'k'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'm'n';;;;o'c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;8,d;p'. h . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. q'r's't'u'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'u'w'x'y'z'. * . . . . . . . . . . . . . . . . . . . . g>. A'B'C'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'E'F'G'H'I'B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;J'K'L'. # . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. M'N'O'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'Q'R'S'T'. # . . . . . . . . . . . . . . . . . . . . . . . D;U'V'W'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'Y'Z'`' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ).)+)@). . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@h g>N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*g>h * . . . . . . . . . . . . . . . . . . . . . . . . h h $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ & & & & & & & & & & & & & & & & & & & & & & & & & ]@E # . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. . . . . . . . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . . . . . * * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * . . . . . . . . . . . . . . . . . . . . . . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #)$)$)$)$)$). . . . . . . . . h $)$)$)$)$). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #)$)%)$)$)$)%)$)#). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $)h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . h . &)*)=)-);)>)$). . . . . . h . ,)')=)-)-)=))). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #)#). h !)~){)])^)/)()_):). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . %). <)[)})|)1)2)3). #). . . . $). 4)5)2)6)7)8). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #)h N*9)0)a)b)c)d)e)f)c)g)h)i). $). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h $)$). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . #). j)k)l)l)m)n)o). $). . . h . p)q)r)a)m)s)t). $). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #). u)v)b)1)w)h)x)y)z)A)B)C)D)E). $). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . h F)6)l)a)b)G). #). . . #). H)6)I)J)K)C)L). #). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #). M)N)1)h)O)P)=)Q)R)h %)S)T)U)V). h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . W)9)X)Y). #). . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . $). Z)`)O)J)r)N)S). h . . $). <) !O)l).!+!. . . . . . #)$)%)%)$)#). . . . . . . h h h h h . . h $)%)#). . . . h $)$)%)%)%)$)h . . . . . . h . @!#!2)$!%!!). h . . . . . . . h . . . h h . . . . $)$). . h h h . . . . . . . . . h h h . . . h h . . . . #)$)$)#). . . . . . . $). &!e) !*!. $)h . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . #). =!})J)K)l)-!;!. $). . . . >!|)l)O) !,!. $). . #)#). . . . . . #)$). . . . . . . . . . . #)h . . . . . $)#). . . . . . . . $)h . . . . #). '!b)h))!!!. %)$)h h . h h $)$). . . . . . . . #)h . . . . . . . h . . . . . . . h . . . . . . . . . . $)h . . . . #)$). . . . . #). v)|)l)~!. #). . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . h . %){!6)l)a)w)]!. $). #). 3)K)K)J)K)K)Y). #). #)h . ^!/!(!_!~)M)h . #). . . . :!^!)3!4!_!5!6!7!. #)h . . R). 8!6)K)9!0!. %). . . . . . . . . . . . #)a!b!%)h . c!d!-)e!%)f!a!g!h . . . . . . . #)a!c!f!#). h!b!g!#)#). i!j!H)-)k!h . #). . . #)f!. v)1)k)2!. f!c!$). . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . $). l!w)a)l)6)m!#). h $). 4!w)a)l)g)n!. h . $). o!p!O)q!n)n)n)r!s!d!. #). $). t!u!v!w!x!. 9)y!g)D)z!. i!A!B!N)2)b)w)w)n)|)C!D!)). h . $). E!1)q!l!. %). . . . . . . . . . . h . [!F!G!H!. I!{!h)})J!K!L!L!M!!). #). . . $). N!N)x)O!. . P!G!Q!R!. S!A)K)-!2)9!n!T!. #)R). U!x)V!W!k)K)X!Y!Z!N)`!. $). . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . $). *)6)l)J)K)k) ~. #)#). .~q!a)O) !1!. $)$). 9)K)w)K)9!k)K)m)J)q!+~`!. R)$). @~#~O)n)$~%~g)})&~q!*~. :!G!#~J)O)a)l)9!m)l)r)=~-~%). #). ;~x)r)r)U!. #). . . . . . . . . . . h . >~,~[)'~8!1)w)n)q!)~. !~n)~~{~. $). . . #). ]~ !#~^~. . {)e)J)L)4)[)f)k)O)1)g)6)n)i). i!. /~D)(~h)J)K)n)~~w)D)_~. %). . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . h . p)M!})I)O) !:~. i!. <~,~[~J)k)l)}~. %). |~6)[~m)[~g)x)1~q!K)9!r)a)2~. i!. 3~w)m)}){!m!6)m)W!b)4~. . 5~ !q!q!K)m)2)q!J)J)m)=~i). i!. U!h)h)M!p). h . . . . . . . . . . . h . f!6~w)p!8)=~7~]!*~~. R). %{&~g)F!#). %). 4!b)&{n~. $). . . . %). D!q!g)*{. $)#). G~q!k)={. #). . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . $). -{w)a)O)`)U). ;{[~K)a)1)s!. #). p)>{h)l)[~1~0),{z)z)'{Q!C)K)a)w)){. . P!f~O)l)g)z). $)%)$)#). #). |~v)a)n)w)1)1)[~J)K)a)w)^~. . !{q!|)T~. #). . . . . . . . . . . . h . a!6~2)a)Y). #). . . . h . ~{|)g){{. )). ^~q!q!i). $)%). 4!q!b)u~. %). . . . #). ]{h)6)^{. . R). G~q!k)={. #). . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . $). /!q!a)l)g)/{. ({ !_{a)w)4!. i!. :{9~C)J)K)C)6)2)2)2)6)r)a)a)m)q!_!. . P!f~O)a)<{J~. $). . . h . ()q!q!K)m)C)1)n)2)J)K)a)w)_!. . [{|)h)Z!)). h . . . . . . . . . . . h . a!6~6)G!~t~w)O)k)O):). $). K!&~C)J)J)[~b)q!q!q!q!b)w)w)1)D)4{. . P!f~O)a)w)5{. $). . $). 5!7)l)O)J)2{z~${6{7{6)l)a)w)4!. . 8{9!k)k)9{. #). . . . . . . . . . . h . a!6~6)G!K!. h . . . . h . 7!>{2)&~3{. 0{W!n)G). #). %). 4!2{n)D!. %). . . . #). J!&~|)a{i!. $). G~q!k)={. #). . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . #). b{n)a)l)|)`!%!|)O)1)c{. h h . [!1~[~l)r)#!^)d{5{5{5{5{5{5{])E!d!. . P!f~O)a)w)5{. $). h . ))6~})e{l)6){)i!$). {) !O)a)w)4!. %). f{})b){). %). . . . . . . . . . . h . a!6~6)G!K!. h . . . . . $). 3~q!q!g{. :~q!|)o~. $). %). 4!2{s)D!. %). . . . #). x~[~|)h{. h #). G~q!k)={. #). . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . $). #{n)a)l)2)B!y!r)O)`)(!. $). . . F!6)a)h)z~F~. h . . . . . . . . %). P!f~O)a)w)5{. $). #). i{r)J)l)6)j{%). p). k{`)_{a)w)4!. e!. l{w)l)m{8{. %). . . . . . . . . . h . a!6~6)G!K!. h . . . . . #). &)l)1),{. W~f~6~n{. h . %). 4!q!b)4~. %). . . . %). _~q!1)E!. $)#). o{q!k)={. #). . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . h . :{,~[~J)K)a)K)J)C)9!8{. #). $). '~ !O)a)q!O!)). h . . . . $)$)h %). P!f~O)a)w)5{. $). $). %~1)l)l)|)p{. . . i!i~6)l)a)w)4!. i!. >~X~[~|)s!e!. %)$)h h h h #)$)$). h . a!6~6)G!K!. h . . . . . . #). q{n)G!r{x)~~@~. $). . %). 4!b)h)D~s{#)#). . #)$). $~2)b)t{. $)#). ~{1)u{;{. $)h . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . #). G)b)a)K)k)K)a)q!T~. #). . #). L)[~J)J)l)q!V!i)v{H)w{x{z!c{:!. i!. P!f~O)a)w)5{. $). #). U~r)J)K)J)h)y{>~}~z{|)l)K)a)w)4!. %)$). A{b)O)g)n!k!. h . . . . . . . . h . a!6~6)G!K!. h . . . . . . $). {{b)l)B{a)r)C{. #). . %). 4!w)m)2{1!. #)h h #). ){|)D{C!>~. h #). E{g)|)/!. $). . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . $). F{w)a)K)K)K)a)w)5!. $). . . #). ()=~a)a)a)2)G{q!g)1)n)w)2{~!. )). P!f~O)a)w)5{. $). h . $)V!6)O)K)k)g)H{K)|)C)k)K)a)w)(!. %). $). l{ !K)})I{J{|~<~p)a!K{3{v{L{j!. . a!6~6)G!K!. h . . . . . . h . r~>{})M{g)e~. h . . . %). 4!`)9!})|)+{S). . n{,!C)a)#~){. $). %). +{s)r)h{b~h ;~%). . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . #). N{W!K)a)l)a)K)m)%{. #). . . . h . @~w)g)K)9!&~m)m)m)m)W!O{^~. g!. P{ !9!O)n)Q{. $). . $). 9) ![~O)O)m)J)k)g)#!a)K)9!w)g{. %). . R). R{S{n)$!b)})1~T{Z!>{W!6)D)4!. h a!M!2)S{V). h . . . . . . . $). {)w)&~n)U{. $). . . %). 4!n)r)V{1~[)W{X{v)#!1)h)~~@~. #). . #). H~g)K)[~1~D~L!8{. #). . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . #). |{Y{2)g)2)f)T~. #). . . . . . #). A!n!k)n) ! !f~ !b)K)L!Z{. `{. ]=~K)k)~~.]. $). . . #). +]W!`)w)w)w)})J{@]a)})K)c)]!. $). . . $). <~4~>{r)b)~~f)f)O{`)C)B)F{. . p)z~q!m)K!. h . . . . . . . #). x~[~h)>{7!. h . . . %). 4!2{w)#]9{$] ![)%]c)-!x)_~. #). . . . #). #]6)n)G{&]c)j). #). . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . h . 8{')=)-)=)*)m~. h . . . . . . h #). h 3)*]C~=]()l{-] ~i!. . h . @!;]H~H~d!N{. h . . . . #). :{){U)U)j~ ~. %)@]>]H~d!8{. h . . . . $)h . f!,]o)<)*~4~']V~U!r~. h . #)M)x~U~i!. . . . . . . . . %). )]|)b)D!. $). . . . %). 4!2{s) ]. 7!v{()]!+{-]>~. $). . . . . . h . @]D!z!{)V~r~. h . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $)h . . . . . . . . h h . . . . . . . . . . . . . . . . $). . . . . . #)h . . . . . . . . . . . . #)$). . . . . . . . . . h . . . . . . . . . . . . . . . #). <~B)|)B)W). h . . . . %). 4!2{n)P!. i!. . . . . . $). . . . . . . . #). . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . #)$)$)$)$)$)h . . . . . . . . . . . . #)$)%)$)%)%)$)#). . . . . h #)#)#)#)h . . . . . . . . h %)$)$)%)#). . #)#)#)#)h . . . . . . . . . h #)%)%)$)$)%)$)#)h . . . . #)#)#). . . . . . . . %)h . !]6)n)#]. $). . . . . %). 4!2{n)P!. i!$)$)$)%)$)h . . . . . . . . . . #)%)$)%)s{]@. . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . p)~]|)&{/{i!. h . . . . . %). 4!2{n)P!. %). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . c!o~V!|)h)&~Y). #). . . . . . %). (!6)-!t). %). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $). ')#~r)q!,~U!. #). . . . . . . %). l{e)%]{]. %). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . F~S{|)]]^!. $). . . . . . . . $). l~^]n!3!. $). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . {{/]. h #). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #)#). . . . . . . . . . . . h #)#)h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $)#). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" "}; +/* XPM */ +static const char *VeraCryptIcon256x256[] = { +"256 256 1770 2", +" c None", +". c #FFFFFF", +"+ c #FCFEFF", +"@ c #FBFEFE", +"# c #FCFEFE", +"$ c #FDFEFD", +"% c #FCFEFD", +"& c #FDFEFE", +"* c #FEFFFF", +"= c #9DDEEF", +"- c #7DD3EB", +"; c #85D6EB", +"> c #83D5EB", +", c #7CD2EA", +"' c #B1E3F2", +") c #FDFEFF", +"! c #C4E6DC", +"~ c #B2DDCF", +"{ c #B6DFD2", +"] c #B5DFD2", +"^ c #B3DED1", +"/ c #BDE2D5", +"( c #CBE7DD", +"_ c #CAE7DC", +": c #CAE6DC", +"< c #CFE9DF", +"[ c #96DAEE", +"} c #009FD3", +"| c #03A6D6", +"1 c #00A5D5", +"2 c #01A6D5", +"3 c #00A2D3", +"4 c #13A7D4", +"5 c #DFF3F9", +"6 c #D9EFE9", +"7 c #4CB697", +"8 c #5DBA9C", +"9 c #61BA9D", +"0 c #60BA9D", +"a c #77C2A9", +"b c #8BCAB3", +"c c #8FCBB5", +"d c #8ECBB5", +"e c #90CCB6", +"f c #86C8B0", +"g c #C2E3D7", +"h c #FEFEFE", +"i c #47C0E2", +"j c #00A8D7", +"k c #0FADDA", +"l c #0CACD9", +"m c #0CADD9", +"n c #15AAD6", +"o c #00A0D0", +"p c #62C5E2", +"q c #7DCAB4", +"r c #48B596", +"s c #62BEA2", +"t c #6FC0A6", +"u c #6DC0A6", +"v c #6EC0A6", +"w c #6CBFA5", +"x c #7AC5AC", +"y c #88C9B3", +"z c #8ACAB4", +"A c #98D0BB", +"B c #99D0BC", +"C c #95CEB9", +"D c #A5D6C4", +"E c #FAFDFC", +"F c #C6ECF6", +"G c #05AAD7", +"H c #09ABD8", +"I c #08ABD8", +"J c #0AA9D6", +"K c #0EA6D3", +"L c #0FA7D3", +"M c #07A3D2", +"N c #C2E8F4", +"O c #C0E5DB", +"P c #48B595", +"Q c #54BA9C", +"R c #52B99B", +"S c #66BEA2", +"T c #6CBFA4", +"U c #6BBFA4", +"V c #6ABFA4", +"W c #6EC0A5", +"X c #84C8B0", +"Y c #86C8B1", +"Z c #84C8B1", +"` c #90CCB7", +" . c #97CFBB", +".. c #96CFBA", +"+. c #97D0BB", +"@. c #D9EEE6", +"#. c #67CBE7", +"$. c #0DA7D4", +"%. c #11A7D4", +"&. c #03A2D1", +"*. c #41B9DC", +"=. c #F6FBFA", +"-. c #67C2A7", +";. c #4DB798", +">. c #50B99A", +",. c #59BB9D", +"'. c #69BFA3", +"). c #7CC5AD", +"!. c #87C9B2", +"~. c #85C8B1", +"{. c #95CEBA", +"]. c #91CCB7", +"^. c #B0DBCB", +"/. c #FEFFFE", +"(. c #E2F5FB", +"_. c #17AFDA", +":. c #05AAD8", +"<. c #0BA9D6", +"[. c #12A7D4", +"}. c #9FDBED", +"|. c #A6DBCB", +"1. c #46B494", +"2. c #55BA9D", +"3. c #51B99A", +"4. c #63BDA1", +"5. c #6DBFA5", +"6. c #6ABEA3", +"7. c #71C1A7", +"8. c #8DCBB5", +"9. c #94CEB9", +"0. c #E7F4EF", +"a. c #8CD8ED", +"b. c #09AAD7", +"c. c #10A7D3", +"d. c #08A4D2", +"e. c #25AED7", +"f. c #EEF9FC", +"g. c #E5F4F0", +"h. c #57BB9E", +"i. c #51B89A", +"j. c #53B99B", +"k. c #51B99B", +"l. c #55BA9C", +"m. c #7FC6AE", +"n. c #86C8B2", +"o. c #97CFBA", +"p. c #8FCCB5", +"q. c #BFE2D5", +"r. c #F7FDFE", +"s. c #30B8DE", +"t. c #0AACD8", +"u. c #0CA8D5", +"v. c #12A8D4", +"w. c #7ACEE7", +"x. c #8CD0BC", +"y. c #47B595", +"z. c #5FBCA0", +"A. c #69BEA3", +"B. c #75C3A9", +"C. c #87C8B2", +"D. c #9CD2BE", +"E. c #F4FAF8", +"F. c #B0E4F3", +"G. c #00A7D6", +"H. c #0BACD8", +"I. c #0FA6D3", +"J. c #0DA5D3", +"K. c #10A7D4", +"L. c #D4EFF7", +"M. c #D0ECE4", +"N. c #4CB798", +"O. c #53BA9C", +"P. c #68BEA3", +"Q. c #83C7B0", +"R. c #91CDB8", +"S. c #8FCCB6", +"T. c #50C3E3", +"U. c #00A6D6", +"V. c #0BACD9", +"W. c #00A1D0", +"X. c #56C0E0", +"Y. c #74C7AF", +"Z. c #4AB697", +"`. c #5BBB9E", +" + c #79C4AB", +".+ c #92CDB7", +"++ c #A7D7C5", +"@+ c #D1EFF8", +"#+ c #0BABD8", +"$+ c #07ABD8", +"%+ c #04A2D1", +"&+ c #B6E4F2", +"*+ c #B7E2D5", +"=+ c #47B594", +"-+ c #65BEA2", +";+ c #6ABFA3", +">+ c #6FC1A6", +",+ c #91CDB7", +"'+ c #DEF0EA", +")+ c #74CFE9", +"!+ c #36B5DA", +"~+ c #F9FDFE", +"{+ c #F2F9F7", +"]+ c #61BFA3", +"^+ c #4EB899", +"/+ c #53B99C", +"(+ c #57BA9D", +"_+ c #7DC6AD", +":+ c #86C9B1", +"<+ c #B5DDCE", +"[+ c #EBF8FC", +"}+ c #1FB2DB", +"|+ c #03A9D7", +"1+ c #0BA8D5", +"2+ c #93D7EB", +"3+ c #9DD7C6", +"4+ c #50B99B", +"5+ c #62BDA1", +"6+ c #72C1A8", +"7+ c #86C9B2", +"8+ c #8CCBB5", +"9+ c #95CFBA", +"0+ c #ECF6F2", +"a+ c #99DCEF", +"b+ c #00A6D5", +"c+ c #0AA5D2", +"d+ c #1DACD6", +"e+ c #E6F6FA", +"f+ c #DEF2EC", +"g+ c #80C6AF", +"h+ c #93CEB8", +"i+ c #C5E4D9", +"j+ c #FDFFFF", +"k+ c #3BBCE0", +"l+ c #6DC9E4", +"m+ c #83CDB7", +"n+ c #5EBC9F", +"o+ c #76C3AA", +"p+ c #89CAB3", +"q+ c #A0D4C0", +"r+ c #F7FBFA", +"s+ c #BDE9F5", +"t+ c #02A8D7", +"u+ c #09ACD8", +"v+ c #0BA5D2", +"w+ c #CAEBF5", +"x+ c #C8E8DF", +"y+ c #4AB596", +"z+ c #67BEA3", +"A+ c #6DC0A5", +"B+ c #D4EBE3", +"C+ c #5DC8E5", +"D+ c #01A1D1", +"E+ c #4BBCDE", +"F+ c #6DC4AA", +"G+ c #5ABB9E", +"H+ c #7AC4AC", +"I+ c #ACD9C9", +"J+ c #DBF3F9", +"K+ c #11AED9", +"L+ c #06AAD8", +"M+ c #A9DFEF", +"N+ c #AEDED0", +"O+ c #64BDA2", +"P+ c #70C1A6", +"Q+ c #8DCCB6", +"R+ c #E4F3ED", +"S+ c #2DB2D9", +"T+ c #F3FBFD", +"U+ c #EBF7F3", +"V+ c #5BBDA0", +"W+ c #4FB89A", +"X+ c #56BA9D", +"Y+ c #7EC6AE", +"Z+ c #BAE0D2", +"`+ c #29B5DD", +" @ c #01A8D7", +".@ c #86D2E9", +"+@ c #93D3C0", +"@@ c #47B494", +"#@ c #60BCA0", +"$@ c #74C2A8", +"%@ c #8BCBB4", +"&@ c #95CFB9", +"*@ c #9AD0BC", +"=@ c #F1F8F5", +"-@ c #A7E1F1", +";@ c #0CA5D3", +">@ c #15A9D4", +",@ c #DCF2F9", +"'@ c #D7EFE8", +")@ c #4FB799", +"!@ c #53BA9B", +"~@ c #82C7AF", +"{@ c #92CDB8", +"]@ c #FEFEFF", +"^@ c #48C0E2", +"/@ c #60C4E2", +"(@ c #7BCAB2", +"_@ c #49B596", +":@ c #5CBC9F", +"<@ c #78C4AB", +"[@ c #93CDB8", +"}@ c #A4D5C3", +"|@ c #C9ECF6", +"1@ c #0AAAD7", +"2@ c #C0E8F3", +"3@ c #BFE5D9", +"4@ c #90CDB7", +"5@ c #91CDB6", +"6@ c #DAEEE7", +"7@ c #6ACCE7", +"8@ c #00A0D1", +"9@ c #12A7D3", +"0@ c #40B8DC", +"a@ c #F6FBF9", +"b@ c #66C1A6", +"c@ c #55B99B", +"d@ c #7BC5AC", +"e@ c #85C8B2", +"f@ c #87C9B3", +"g@ c #83C7AF", +"h@ c #B2DCCD", +"i@ c #E5F5FA", +"j@ c #26A3D4", +"k@ c #159CD1", +"l@ c #1A9DD1", +"m@ c #199DD1", +"n@ c #1C9FD2", +"o@ c #0C94CE", +"p@ c #A5D1EB", +"q@ c #98D8C8", +"r@ c #37B291", +"s@ c #4AB89B", +"t@ c #46B799", +"u@ c #47B79A", +"v@ c #41B596", +"w@ c #5BBFA4", +"x@ c #E6F4F0", +"y@ c #ECF7F3", +"z@ c #EAF6F2", +"A@ c #EBF6F2", +"B@ c #EAF5F2", +"C@ c #96D1EA", +"D@ c #0B95CE", +"E@ c #1E9ED2", +"F@ c #1A9CD1", +"G@ c #1B9DD1", +"H@ c #1C8ECD", +"I@ c #3796D1", +"J@ c #EEF7FB", +"K@ c #E0F3EF", +"L@ c #37B597", +"M@ c #38B495", +"N@ c #45B79A", +"O@ c #43B799", +"P@ c #44B799", +"Q@ c #47B89A", +"R@ c #38B392", +"S@ c #B6E3D7", +"T@ c #F9FCFE", +"U@ c #3FACD9", +"V@ c #1198CF", +"W@ c #1C9DD1", +"X@ c #1D97D0", +"Y@ c #278ECE", +"Z@ c #1385CA", +"`@ c #84C0E3", +" # c #FCFDFE", +".# c #77CCB8", +"+# c #26AE8D", +"@# c #36B496", +"## c #41B698", +"$# c #45B799", +"%# c #46B89A", +"&# c #3BB394", +"*# c #6DC7B0", +"=# c #B7E0F0", +"-# c #0F97CF", +";# c #228FCE", +"># c #248DCD", +",# c #228DCD", +"'# c #258ECD", +")# c #D7EAF6", +"!# c #C8EAE2", +"~# c #2CB090", +"{# c #35B495", +"]# c #32B394", +"^# c #37B496", +"/# c #3FB596", +"(# c #D1EDE6", +"_# c #5DB9DF", +":# c #0D96CE", +"<# c #1D9DD2", +"[# c #1E95CF", +"}# c #248CCD", +"|# c #238DCD", +"1# c #268FCE", +"2# c #1686CA", +"3# c #63AEDC", +"4# c #5BC2AA", +"5# c #2AB08F", +"6# c #33B394", +"7# c #3EB697", +"8# c #47B89B", +"9# c #38B292", +"0# c #87D1BD", +"a# c #D5EDF7", +"b# c #199BD1", +"c# c #1B9CD1", +"d# c #1B9AD0", +"e# c #238ECD", +"f# c #1988CB", +"g# c #BADBEF", +"h# c #AADFD3", +"i# c #42B698", +"j# c #4CBA9D", +"k# c #E6F6F2", +"l# c #7FC8E5", +"m# c #0A95CE", +"n# c #1F93CF", +"o# c #1B89CB", +"p# c #469FD5", +"q# c #EEF9F6", +"r# c #44B99D", +"s# c #2FB192", +"t# c #34B395", +"u# c #3CB597", +"v# c #37B292", +"w# c #A4DCCD", +"x# c #EEF8FB", +"y# c #2EA5D5", +"z# c #159AD0", +"A# c #1C99D0", +"B# c #278FCE", +"C# c #1485CA", +"D# c #99CAE8", +"E# c #8AD3C2", +"F# c #25AE8D", +"G# c #34B394", +"H# c #3EB496", +"I# c #5EC1A7", +"J# c #F7FCFB", +"K# c #A2D7EC", +"L# c #0C96CE", +"M# c #2191CE", +"N# c #248ECD", +"O# c #208BCC", +"P# c #3094D0", +"Q# c #E7F3FA", +"R# c #D8F0EB", +"S# c #39B496", +"T# c #3AB394", +"U# c #BFE7DC", +"V# c #4AB1DA", +"W# c #238CCD", +"X# c #78B9E1", +"Y# c #6DC8B3", +"Z# c #27AF8E", +"`# c #40B698", +" $ c #3AB393", +".$ c #76CAB4", +"+$ c #C3E5F3", +"@$ c #1399D0", +"#$ c #1A9BD1", +"$$ c #CEE5F4", +"%$ c #BDE6DD", +"&$ c #29AF8F", +"*$ c #37B495", +"=$ c #43B798", +"-$ c #D8F0EA", +";$ c #69BEE1", +">$ c #0B96CE", +",$ c #1F94CF", +"'$ c #268ECE", +")$ c #1887CA", +"!$ c #59A9D9", +"~$ c #F8FCFC", +"{$ c #52BEA5", +"]$ c #91D4C3", +"^$ c #DFF1F9", +"/$ c #229FD3", +"($ c #189BD1", +"_$ c #1786CA", +":$ c #AED5ED", +"<$ c #9FDBCD", +"[$ c #25AE8C", +"}$ c #40B697", +"|$ c #51BCA0", +"1$ c #EDF8F6", +"2$ c #8DCEE8", +"3$ c #2092CE", +"4$ c #1C89CB", +"5$ c #3E9BD3", +"6$ c #F3F9FC", +"7$ c #E7F6F3", +"8$ c #3DB69A", +"9$ c #30B293", +"0$ c #3BB596", +"a$ c #ADDFD2", +"b$ c #F4FAFD", +"c$ c #38A9D7", +"d$ c #1C98D0", +"e$ c #1385C9", +"f$ c #8EC5E5", +"g$ c #7FCFBD", +"h$ c #3DB495", +"i$ c #65C4AB", +"j$ c #AEDCEF", +"k$ c #0E97CE", +"l$ c #2190CE", +"m$ c #218CCD", +"n$ c #2990CE", +"o$ c #DEEEF8", +"p$ c #CFEDE6", +"q$ c #38B496", +"r$ c #3CB495", +"s$ c #C8EAE1", +"t$ c #55B5DD", +"u$ c #1E96CF", +"v$ c #1586CA", +"w$ c #6DB3DE", +"x$ c #63C5AE", +"y$ c #36B495", +"z$ c #3FB697", +"A$ c #39B393", +"B$ c #7FCDB9", +"C$ c #CEEAF5", +"D$ c #189BD0", +"E$ c #1B9BD1", +"F$ c #228ECD", +"G$ c #C4E0F1", +"H$ c #B3E2D7", +"I$ c #27AE8E", +"J$ c #E0F3EE", +"K$ c #75C4E3", +"L$ c #258ECE", +"M$ c #4EA3D7", +"N$ c #F3FAF9", +"O$ c #4ABBA0", +"P$ c #2DB191", +"Q$ c #3DB597", +"R$ c #9BD8C9", +"S$ c #E8F5FA", +"T$ c #29A2D4", +"U$ c #169AD0", +"V$ c #1C9AD0", +"W$ c #A3CFEA", +"X$ c #94D7C8", +"Y$ c #58BEA4", +"Z$ c #F3FAF8", +"`$ c #99D3EB", +" % c #1E9DD2", +".% c #1E8BCC", +"+% c #3697D1", +"@% c #EDF6FB", +"#% c #DEF3EE", +"$% c #32B293", +"%% c #3AB596", +"&% c #B6E3D8", +"*% c #FAFDFE", +"=% c #42ADD9", +"-% c #1099CF", +";% c #1F98D0", +">% c #82BEE3", +",% c #75CAB6", +"'% c #26AD8C", +")% c #36B395", +"!% c #33B293", +"~% c #43B698", +"{% c #3BB393", +"]% c #6EC7B0", +"^% c #BBE2F1", +"/% c #1098CF", +"(% c #2491CE", +"_% c #D5E9F6", +":% c #C7ECE4", +"<% c #2DB595", +"[% c #36B899", +"}% c #34B898", +"|% c #33B898", +"1% c #39B99A", +"2% c #43B99A", +"3% c #D1EDE5", +"4% c #64B2DC", +"5% c #1883C8", +"6% c #288DCC", +"7% c #258BCB", +"8% c #1884C9", +"9% c #63ABD9", +"0% c #55AD97", +"a% c #249778", +"b% c #2F9C80", +"c% c #2D9B7E", +"d% c #309C80", +"e% c #229576", +"f% c #70BEA9", +"g% c #D9E9F5", +"h% c #2A87C7", +"i% c #2785C7", +"j% c #2986C7", +"k% c #2886C7", +"l% c #2B88C8", +"m% c #1875BC", +"n% c #B7D3E9", +"o% c #A7DCE2", +"p% c #1A817C", +"q% c #236047", +"r% c #20644D", +"s% c #20634B", +"t% c #21624B", +"u% c #1E654D", +"v% c #3A9D82", +"w% c #E2F3EF", +"x% c #88BCE0", +"y% c #197EC3", +"z% c #2C88C8", +"A% c #2887C8", +"B% c #2883C4", +"C% c #1772B9", +"D% c #438DC6", +"E% c #F8FBFD", +"F% c #EDF7F8", +"G% c #3EABB4", +"H% c #29A4AD", +"I% c #257462", +"J% c #21654C", +"K% c #216951", +"L% c #216850", +"M% c #20644C", +"N% c #2D8A6E", +"O% c #219D7C", +"P% c #78C0AC", +"Q% c #F0F6FB", +"R% c #3C91CD", +"S% c #2383C6", +"T% c #2987C7", +"U% c #2179BD", +"V% c #2379BD", +"W% c #116EB7", +"X% c #97C0E0", +"Y% c #85CBD0", +"Z% c #1E9DA6", +"`% c #31A9B4", +" & c #2A9494", +".& c #21654B", +"+& c #21674F", +"@& c #20654D", +"#& c #247258", +"$& c #30A082", +"%& c #309F82", +"&& c #299D7E", +"*& c #CCE7E0", +"=& c #A8CEE8", +"-& c #1B7FC4", +";& c #2987C8", +">& c #247FC2", +",& c #1F76BB", +"'& c #2178BD", +")& c #1D75BB", +"!& c #2C7EC0", +"~& c #E5EFF7", +"{& c #D5EDEF", +"]& c #2CA4AD", +"^& c #2DA4AD", +"/& c #2DA3AC", +"(& c #2EA8B2", +"_& c #257C6E", +":& c #206349", +"<& c #21684F", +"[& c #2B9074", +"}& c #30A284", +"|& c #319F82", +"1& c #259A7B", +"2& c #5EB59E", +"3& c #56A0D3", +"4& c #1E80C4", +"5& c #2B87C8", +"6& c #2784C6", +"7& c #2078BC", +"8& c #2077BC", +"9& c #2479BD", +"0& c #116EB8", +"a& c #74AAD5", +"b& c #67BDC4", +"c& c #219FA8", +"d& c #30A5AE", +"e& c #2DA6B0", +"f& c #2C9CA0", +"g& c #216851", +"h& c #21674E", +"i& c #20634C", +"j& c #267A60", +"k& c #2F9E80", +"l& c #2F9F81", +"m& c #32A083", +"n& c #23997A", +"o& c #B1DBD0", +"p& c #C8E0F1", +"q& c #2283C5", +"r& c #237CC0", +"s& c #2076BB", +"t& c #1C74BB", +"u& c #CBDFEF", +"v& c #BAE1E4", +"w& c #239FA9", +"x& c #2FA5AE", +"y& c #2DA3AB", +"z& c #2EA8B4", +"A& c #27857C", +"B& c #206348", +"C& c #21664F", +"D& c #216950", +"E& c #2D987B", +"F& c #30A183", +"G& c #31A082", +"H& c #299C7D", +"I& c #47AA90", +"J& c #73B0DB", +"K& c #1A7EC3", +"L& c #2683C5", +"M& c #1570B8", +"N& c #5597CC", +"O& c #4CB1B9", +"P& c #26A1AA", +"Q& c #2DA5AE", +"R& c #2DA2AA", +"S& c #226E5A", +"T& c #216750", +"U& c #288369", +"V& c #30A385", +"W& c #33A183", +"X& c #209878", +"Y& c #95CEBF", +"Z& c #E1EEF7", +"`& c #308AC9", +" * c #2685C6", +".* c #227BBE", +"+* c #136FB8", +"@* c #ACCCE6", +"#* c #9BD4D8", +"$* c #1F9EA7", +"%* c #30A6AE", +"&* c #2EA8B3", +"** c #298F8C", +"=* c #236F56", +"-* c #309F81", +";* c #2D9E80", +">* c #36A285", +",* c #E2F2ED", +"'* c #95C3E3", +")* c #197DC3", +"!* c #2581C3", +"~* c #2278BC", +"{* c #1973BA", +"]* c #3A87C4", +"^* c #F3F7FB", +"/* c #E5F4F5", +"(* c #37A8B1", +"_* c #2AA3AC", +":* c #2EA4AD", +"<* c #247665", +"[* c #20644A", +"}* c #2A8D71", +"|* c #30A384", +"1* c #32A183", +"2* c #229979", +"3* c #77C0AD", +"4* c #F6FAFC", +"5* c #4596CE", +"6* c #2182C5", +"7* c #106DB7", +"8* c #8BB8DC", +"9* c #7BC6CB", +"0* c #2EA7B1", +"a* c #2B9799", +"b* c #21664D", +"c* c #25775D", +"d* c #30A283", +"e* c #CAE7DF", +"f* c #B4D5EC", +"g* c #1C80C4", +"h* c #247EC1", +"i* c #2177BC", +"j* c #1E76BB", +"k* c #257ABE", +"l* c #DCEAF4", +"m* c #CDE9EB", +"n* c #28A2AB", +"o* c #267F73", +"p* c #2D9678", +"q* c #2F9E81", +"r* c #31A083", +"s* c #5DB49D", +"t* c #61A6D6", +"u* c #1C7FC4", +"v* c #2887C7", +"w* c #126EB8", +"x* c #68A3D2", +"y* c #5DB9C0", +"z* c #2DA4AC", +"A* c #2DA5AF", +"B* c #2C9FA4", +"C* c #226A54", +"D* c #21664E", +"E* c #278065", +"F* c #239979", +"G* c #AFDACE", +"H* c #D2E6F3", +"I* c #2685C7", +"J* c #227CC0", +"K* c #2278BD", +"L* c #1772BA", +"M* c #C1D9EC", +"N* c #FDFDFE", +"O* c #AFDCE0", +"P* c #209EA8", +"Q* c #278882", +"R* c #226C54", +"S* c #2E9C7E", +"T* c #2FA082", +"U* c #46AA8F", +"V* c #80B7DE", +"W* c #2682C4", +"X* c #1671B9", +"Y* c #4B91C9", +"Z* c #F2FAFA", +"`* c #44AEB6", +" = c #27A1AB", +".= c #23715E", +"+= c #20654B", +"@= c #2A8A6E", +"#= c #94CDBE", +"$= c #EBF3FA", +"%= c #378ECB", +"&= c #2484C6", +"*= c #227ABE", +"== c #A0C5E2", +"-= c #8FCFD3", +";= c #1E9DA7", +">= c #31A6AE", +",= c #2A9291", +"'= c #24735A", +")= c #35A285", +"!= c #E1F1ED", +"~= c #A0CAE6", +"{= c #2580C2", +"]= c #2178BC", +"^= c #1B74BB", +"/= c #3282C2", +"(= c #ECF4F9", +"_= c #DDF0F2", +":= c #31A6AF", +"<= c #2CA3AC", +"[= c #2EA7B2", +"}= c #24796A", +"|= c #20634A", +"1= c #2C9376", +"2= c #77C0AC", +"3= c #FBFDFE", +"4= c #4E9BD1", +"5= c #1F81C5", +"6= c #2A87C8", +"7= c #2885C6", +"8= c #2078BD", +"9= c #7FB1D9", +"0= c #70C1C7", +"a= c #2EA6B1", +"b= c #2B9A9D", +"c= c #267C62", +"d= c #C0DCEF", +"e= c #247DC1", +"f= c #1F77BC", +"g= c #D3E4F2", +"h= c #C3E5E8", +"i= c #25A0AA", +"j= c #268379", +"k= c #226A52", +"l= c #2E9A7C", +"m= c #6BACD8", +"n= c #1B7EC4", +"o= c #2783C5", +"p= c #5E9DCF", +"q= c #54B5BC", +"r= c #24A0AA", +"s= c #2CA1A8", +"t= c #226D57", +"u= c #29866B", +"v= c #DBEBF6", +"w= c #227BBF", +"x= c #2279BD", +"y= c #1570B9", +"z= c #B5D2E9", +"A= c #F9FCFD", +"B= c #A4D8DC", +"C= c #1F9EA8", +"D= c #288C88", +"E= c #237058", +"F= c #8CBEE1", +"G= c #2C89C9", +"H= c #2681C3", +"I= c #1872BA", +"J= c #418BC6", +"K= c #EBF6F7", +"L= c #3CABB3", +"M= c #29A2AC", +"N= c #2EA5AD", +"O= c #247462", +"P= c #21654E", +"Q= c #2B8F73", +"R= c #F1F7FB", +"S= c #3F93CD", +"T= c #237ABE", +"U= c #2076BC", +"V= c #92BDDE", +"W= c #81C7CE", +"X= c #1E9EA7", +"Y= c #2A9696", +"Z= c #216149", +"`= c #25795F", +" - c #2EA283", +".- c #2E9D7F", +"+- c #35A284", +"@- c #FBFDFD", +"#- c #ADD1EA", +"$- c #1778BE", +"%- c #2179BC", +"&- c #1B75BB", +"*- c #3282C3", +"=- c #BADDE8", +"-- c #31A7AE", +";- c #2BA4AD", +">- c #2DA5AD", +",- c #2FA8B2", +"'- c #217D70", +")- c #319778", +"!- c #36A588", +"~- c #35A185", +"{- c #30A083", +"]- c #568DC5", +"^- c #1D66B0", +"/- c #2A6FB5", +"(- c #276DB4", +"_- c #286EB4", +":- c #2569B3", +"<- c #2381A2", +"[- c #2F9FAF", +"}- c #2E9BAE", +"|- c #2E9CAE", +"1- c #309DAE", +"2- c #2899AE", +"3- c #55AEB4", +"4- c #409C7E", +"5- c #339579", +"6- c #35967A", +"7- c #2D9375", +"8- c #2B9274", +"9- c #2B9174", +"0- c #2B9073", +"a- c #5FAE98", +"b- c #65B49F", +"c- c #64B39E", +"d- c #65B39E", +"e- c #60B19B", +"f- c #59AE97", +"g- c #5AAE97", +"h- c #5CAF98", +"i- c #50AA92", +"j- c #97D4C6", +"k- c #CAD9EB", +"l- c #2564AE", +"m- c #2C69B1", +"n- c #2B68B0", +"o- c #2B68AF", +"p- c #2C68B4", +"q- c #22679E", +"r- c #0C6578", +"s- c #2B90A9", +"t- c #3099B1", +"u- c #2F97AF", +"v- c #3097AF", +"w- c #2E97AE", +"x- c #3098AF", +"y- c #E8F3F9", +"z- c #81BBA8", +"A- c #188364", +"B- c #2C8D70", +"C- c #2A8C6F", +"D- c #2A8D70", +"E- c #278769", +"F- c #1E8767", +"G- c #239476", +"H- c #239375", +"I- c #249476", +"J- c #259476", +"K- c #269375", +"L- c #229C7D", +"M- c #28AC8E", +"N- c #D8EFEA", +"O- c #769FCD", +"P- c #1C5FAC", +"Q- c #2D6BB2", +"R- c #2A69B1", +"S- c #2969B0", +"T- c #126783", +"U- c #0A6275", +"V- c #18768C", +"W- c #319BB2", +"X- c #2F97AE", +"Y- c #2F98AF", +"Z- c #339AB0", +"`- c #2091A9", +" ; c #8FC7D3", +".; c #E6F2EF", +"+; c #379479", +"@; c #278B6E", +"#; c #2B8E71", +"$; c #298C6E", +"%; c #298768", +"&; c #2E9578", +"*; c #319B7F", +"=; c #319A7E", +"-; c #309A7D", +";; c #309B7E", +">; c #30AD91", +",; c #1FA889", +"'; c #68C4AF", +"); c #E3EBF5", +"!; c #326FB4", +"~; c #2867B0", +"{; c #2B6AB1", +"]; c #2A69B0", +"^; c #2C69B5", +"/; c #1C6797", +"(; c #0B6576", +"_; c #0E657B", +":; c #0B6378", +"<; c #268AA1", +"[; c #3199B0", +"}; c #2995AD", +"|; c #45A3B8", +"1; c #F2F9FA", +"2; c #9ECBBE", +"3; c #1B8566", +"4; c #2D8F72", +"5; c #28886A", +"6; c #278768", +"7; c #278667", +"8; c #288A6B", +"9; c #2E997C", +"0; c #2E987B", +"a; c #2DA487", +"b; c #2BAD90", +"c; c #2DAD90", +"d; c #21A889", +"e; c #BBE4DB", +"f; c #97B6D9", +"g; c #1B5EAC", +"h; c #2E6CB2", +"i; c #2B69B2", +"j; c #2768AB", +"k; c #0E657C", +"l; c #0D6579", +"m; c #0E667B", +"n; c #136F84", +"o; c #3299B0", +"p; c #2292AA", +"q; c #AFD8E0", +"r; c #FAFCFB", +"s; c #4DA088", +"t; c #22896A", +"u; c #2C8E71", +"v; c #298B6D", +"w; c #278666", +"x; c #2B9173", +"y; c #2E9A7D", +"z; c #2D9C7F", +"A; c #2BAC8F", +"B; c #23A98B", +"C; c #4BB9A0", +"D; c #F8FCFB", +"E; c #F6F9FC", +"F; c #477EBC", +"G; c #2364AE", +"H; c #2C6AB2", +"I; c #18678E", +"J; c #0D657B", +"K; c #0D657A", +"L; c #0A6176", +"M; c #208399", +"N; c #329CB3", +"O; c #2593AB", +"P; c #5EAFC1", +"Q; c #BEDCD3", +"R; c #20886A", +"S; c #2A8D6F", +"T; c #278869", +"U; c #288869", +"V; c #2D977A", +"W; c #2E997D", +"X; c #2CA78A", +"Y; c #2FAD91", +"Z; c #1CA687", +"`; c #9BD8CA", +" > c #B6CCE4", +".> c #1F61AD", +"+> c #2C69B4", +"@> c #2368A4", +"#> c #0C6579", +"$> c #0C6479", +"%> c #0F697E", +"&> c #2D94AB", +"*> c #3099B0", +"=> c #2A95AD", +"-> c #CCE6EC", +";> c #69AF9A", +">> c #1D8667", +",> c #298A6C", +"'> c #278767", +")> c #2A8E70", +"!> c #2D9F82", +"~> c #2CAC90", +"{> c #28AB8E", +"]> c #36B095", +"^> c #E7F5F2", +"/> c #6391C6", +"(> c #1E61AD", +"_> c #2B69B3", +":> c #146687", +"<> c #0B6577", +"[> c #1C7A90", +"}> c #329AB0", +"|> c #2291AA", +"1> c #7BBECC", +"2> c #D9EBE5", +"3> c #298C6F", +"4> c #2B8D70", +"5> c #2D9578", +"6> c #2BA98C", +"7> c #1DA687", +"8> c #7BCCBA", +"9> c #D3E0EF", +"0> c #2968B0", +"a> c #1F689C", +"b> c #298FA5", +"c> c #319AB1", +"d> c #2C97AE", +"e> c #389DB2", +"f> c #E5F2F5", +"g> c #FCFDFD", +"h> c #89C0B0", +"i> c #2E8F72", +"j> c #28896A", +"k> c #298C6D", +"l> c #2DA285", +"m> c #27AB8D", +"n> c #CEECE5", +"o> c #82A7D1", +"p> c #1B5FAC", +"q> c #2A69B2", +"r> c #2969AE", +"s> c #10667F", +"t> c #0D667B", +"u> c #0B6277", +"v> c #167388", +"w> c #309AB1", +"x> c #9BCDD8", +"y> c #F0F7F5", +"z> c #3E987D", +"A> c #258A6C", +"B> c #298B6E", +"C> c #2B9375", +"D> c #2E9B7E", +"E> c #2BAB8E", +"F> c #2EAD90", +"G> c #20A88A", +"H> c #5DC0A9", +"I> c #ECF1F8", +"J> c #3974B7", +"K> c #2666B0", +"L> c #1B6794", +"M> c #24879E", +"N> c #2894AC", +"O> c #4DA7BB", +"P> c #F8FBFC", +"Q> c #A9D1C6", +"R> c #2CA588", +"S> c #2EAD91", +"T> c #1EA788", +"U> c #AFE0D5", +"V> c #A2BEDD", +"W> c #2668A9", +"X> c #0C6378", +"Y> c #126C81", +"Z> c #2492AB", +"`> c #B9DCE4", +" , c #57A58E", +"., c #208869", +"+, c #2D8E72", +"@, c #298A6D", +"#, c #2B9072", +"$, c #2D9D80", +"%, c #25AA8C", +"&, c #43B59C", +"*, c #5184BF", +"=, c #2163AE", +"-, c #2C6BB2", +";, c #16668B", +">, c #1F7F96", +",, c #319CB3", +"', c #68B4C5", +"), c #C9E2DB", +"!, c #24896C", +"~, c #2A8C70", +"{, c #278868", +"], c #2D9779", +"^, c #2CA88B", +"/, c #90D4C5", +"(, c #C2D4E9", +"_, c #2263AE", +":, c #2268A2", +"<, c #0D6479", +"[, c #0E677C", +"}, c #2B92A9", +"|, c #2E98AF", +"1, c #D5EAEF", +"2, c #74B5A2", +"3, c #1C8567", +"4, c #298D6F", +"5, c #2DA083", +"6, c #2CAC8F", +"7, c #29AB8E", +"8, c #30AE92", +"9, c #DEF2ED", +"0, c #6E98CA", +"a, c #1D60AC", +"b, c #126684", +"c, c #19788D", +"d, c #86C3D0", +"e, c #E2EFEB", +"f, c #329175", +"g, c #288C6E", +"h, c #2B8D71", +"i, c #2C9477", +"j, c #2BAA8D", +"k, c #70C7B3", +"l, c #DCE6F2", +"m, c #2B69B1", +"n, c #1E6799", +"o, c #278CA3", +"p, c #3099AF", +"q, c #2B96AD", +"r, c #3FA0B5", +"s, c #EDF6F8", +"t, c #96C7B8", +"u, c #288A6C", +"v, c #2DA386", +"w, c #C4E8E0", +"x, c #8EB0D6", +"y, c #2869AD", +"z, c #0F657E", +"A, c #157086", +"B, c #2191AA", +"C, c #A5D2DD", +"D, c #F6FAF9", +"E, c #479D83", +"F, c #23896B", +"G, c #2E9C7F", +"H, c #22A88A", +"I, c #53BCA4", +"J, c #F2F6FA", +"K, c #4179BA", +"L, c #2465AF", +"M, c #196791", +"N, c #0A6277", +"O, c #22849B", +"P, c #329BB3", +"Q, c #2694AC", +"R, c #56ABBE", +"S, c #B5D7CD", +"T, c #1E8768", +"U, c #2D987A", +"V, c #2CA689", +"W, c #1DA788", +"X, c #A4DBCF", +"Y, c #AEC5E1", +"Z, c #2468A7", +"`, c #106A80", +" ' c #2D95AC", +".' c #2794AC", +"+' c #C4E2E8", +"@' c #61AB95", +"#' c #2A8F70", +"$' c #2D9E81", +"%' c #2CAD90", +"&' c #27AA8D", +"*' c #3CB398", +"=' c #EDF8F5", +"-' c #5B8BC3", +";' c #156689", +">' c #1D7D93", +",' c #329BB2", +"'' c #72B9C9", +")' c #D2E7E1", +"!' c #288C6F", +"~' c #2D9679", +"{' c #2CA98C", +"]' c #1CA688", +"^' c #84CFBE", +"/' c #CCDBEC", +"(' c #2566B0", +"_' c #2A6AB0", +":' c #20689F", +"<' c #2A90A7", +"[' c #2D97AE", +"}' c #DEEEF2", +"|' c #80BBAA", +"1' c #1C8566", +"2' c #28896B", +"3' c #2DA184", +"4' c #2AAC8F", +"5' c #D5EFE9", +"6' c #79A1CE", +"7' c #1D5FAC", +"8' c #2F6CB2", +"9' c #136783", +"0' c #0E6679", +"a' c #0F667B", +"b' c #0F677C", +"c' c #0D6378", +"d' c #19768B", +"e' c #369DB4", +"f' c #2090A9", +"g' c #91C8D5", +"h' c #EBF4F1", +"i' c #38957A", +"j' c #278C6E", +"k' c #2D8D70", +"l' c #298869", +"m' c #288768", +"n' c #2D9477", +"o' c #2DAC8F", +"p' c #67C4AF", +"q' c #E5EDF5", +"r' c #346FB8", +"s' c #0F5F90", +"t' c #046072", +"u' c #056076", +"v' c #046075", +"w' c #045E74", +"x' c #168199", +"y' c #47A6BA", +"z' c #F2F8FA", +"A' c #A2CDC0", +"B' c #178263", +"C' c #228566", +"D' c #1F8363", +"E' c #1F8262", +"F' c #208666", +"G' c #279476", +"H' c #25A284", +"I' c #23AA8C", +"J' c #26AA8C", +"K' c #18A585", +"L' c #B3E1D7", +"M' c #A1BED9", +"N' c #2A768E", +"O' c #36808F", +"P' c #347E8F", +"Q' c #347F90", +"R' c #357D8E", +"S' c #308194", +"T' c #B5DBE3", +"U' c #66AC97", +"V' c #44977C", +"W' c #4B9B81", +"X' c #4A9A80", +"Y' c #4A987E", +"Z' c #4DA58C", +"`' c #4DBAA2", +" ) c #4DB9A1", +".) c #4FBAA2", +"+) c #46B69D", +"@) c #6DC5B1", +"#) c #FDFDFD", +"$) c #FCFCFC", +"%) c #FBFBFB", +"&) c #D5D5D5", +"*) c #C2C2C2", +"=) c #C6C6C6", +"-) c #C5C5C5", +";) c #C4C4C4", +">) c #CACACA", +",) c #E4E4E4", +"') c #C1C1C1", +")) c #F9F9F9", +"!) c #DBDBDA", +"~) c #A9A9A8", +"{) c #848483", +"]) c #747473", +"^) c #757573", +"/) c #767675", +"() c #8A8A89", +"_) c #ADADAC", +":) c #DEDEDE", +"<) c #858584", +"[) c #020200", +"}) c #171715", +"|) c #141412", +"1) c #121210", +"2) c #161614", +"3) c #D9D9D9", +"4) c #6E6E6C", +"5) c #040402", +"6) c #151513", +"7) c #0A0A07", +"8) c #3F3F3D", +"9) c #B1B1B0", +"0) c #4E4E4C", +"a) c #20201E", +"b) c #10100E", +"c) c #090907", +"d) c #060604", +"e) c #050503", +"f) c #070705", +"g) c #131311", +"h) c #181816", +"i) c #8F8F8E", +"j) c #D2D2D2", +"k) c #1C1C1A", +"l) c #1F1F1D", +"m) c #232321", +"n) c #0F0F0D", +"o) c #9F9F9E", +"p) c #F6F6F6", +"q) c #373736", +"r) c #191917", +"s) c #10100D", +"t) c #90908F", +"u) c #E3E3E2", +"v) c #565654", +"w) c #0E0E0C", +"x) c #30302E", +"y) c #444443", +"z) c #4C4C4B", +"A) c #424240", +"B) c #2E2E2C", +"C) c #1B1B19", +"D) c #000000", +"E) c #A6A6A6", +"F) c #434341", +"G) c #5E5E5D", +"H) c #C6C6C5", +"I) c #1E1E1D", +"J) c #1E1E1C", +"K) c #1D1D1B", +"L) c #D4D4D4", +"M) c #D6D6D5", +"N) c #2D2D2B", +"O) c #21211F", +"P) c #777776", +"Q) c #EFEFEE", +"R) c #FDFDFC", +"S) c #EDEDED", +"T) c #C5C5C4", +"U) c #7D7D7C", +"V) c #E6E6E5", +"W) c #EBEBEB", +"X) c #696968", +"Y) c #D8D8D8", +"Z) c #858583", +"`) c #0E0E0B", +" ! c #0D0D0B", +".! c #141411", +"+! c #494947", +"@! c #E8E8E7", +"#! c #31312F", +"$! c #171714", +"%! c #454543", +"&! c #5C5C5A", +"*! c #CDCDCD", +"=! c #C9C9C8", +"-! c #131310", +";! c #BABABA", +">! c #474746", +",! c #929291", +"'! c #646462", +")! c #464645", +"!! c #F3F3F2", +"~! c #D0D0D0", +"{! c #3E3E3C", +"]! c #7A7A79", +"^! c #E3E3E3", +"/! c #B3B3B2", +"(! c #9D9D9C", +"_! c #9B9B9A", +":! c #EFEFEF", +"~ c #F0F0F0", +",~ c #292927", +"'~ c #7B7B7A", +")~ c #D7D7D7", +"!~ c #4F4F4D", +"~~ c #0A0A08", +"{~ c #8C8C8A", +"]~ c #5B5B5A", +"^~ c #9E9E9D", +"/~ c #C0C0C0", +"(~ c #0C0C0B", +"_~ c #A3A3A2", +":~ c #9A9A99", +"<~ c #E8E8E8", +"[~ c #1A1A18", +"}~ c #DADADA", +"|~ c #C2C2C1", +"1~ c #2A2A28", +"2~ c #DBDBDB", +"3~ c #80807F", +"4~ c #828281", +"5~ c #686867", +"6~ c #373735", +"7~ c #424241", +"8~ c #ADADAD", +"9~ c #262624", +"0~ c #191916", +"a~ c #2C2C2B", +"b~ c #EAEAEA", +"c~ c #525251", +"d~ c #B8B8B7", +"e~ c #4F4F4E", +"f~ c #0C0C0A", +"g~ c #AAAAA9", +"h~ c #C1C1C0", +"i~ c #454544", +"j~ c #989897", +"k~ c #C0C0BF", +"l~ c #B5B5B4", +"m~ c #E5E5E4", +"n~ c #5A5A59", +"o~ c #B1B1B1", +"p~ c #11110E", +"q~ c #3B3B3A", +"r~ c #F4F4F4", +"s~ c #F0F0F1", +"t~ c #6B6B69", +"u~ c #898988", +"v~ c #A2A2A2", +"w~ c #DCDCDC", +"x~ c #CECECD", +"y~ c #555554", +"z~ c #343432", +"A~ c #A1A1A1", +"B~ c #6F6F6E", +"C~ c #919190", +"D~ c #444442", +"E~ c #30302F", +"F~ c #F1F1F0", +"G~ c #575756", +"H~ c #D1D1D0", +"I~ c #BBBBBA", +"J~ c #717170", +"K~ c #AFAFAF", +"L~ c #ACACAC", +"M~ c #C9C9C9", +"N~ c #EEEEEE", +"O~ c #E9E9E9", +"P~ c #646463", +"Q~ c #FFFFFE", +"R~ c #81817F", +"S~ c #767674", +"T~ c #595957", +"U~ c #D2D2D1", +"V~ c #A8A8A7", +"W~ c #565655", +"X~ c #323230", +"Y~ c #B9B9B9", +"Z~ c #5D5D5C", +"`~ c #161613", +" { c #B0B0B0", +".{ c #DCDCDB", +"+{ c #868685", +"@{ c #6C6C6A", +"#{ c #ACACAB", +"${ c #656564", +"%{ c #E1E1E1", +"&{ c #151512", +"*{ c #696967", +"={ c #D0D0CF", +"-{ c #6F6F6D", +";{ c #CECECE", +">{ c #353533", +",{ c #4B4B4A", +"'{ c #4E4E4D", +"){ c #A1A1A0", +"!{ c #A4A4A3", +"~{ c #575755", +"{{ c #B0B0AF", +"]{ c #C7C7C6", +"^{ c #494948", +"/{ c #474745", +"({ c #9B9B9B", +"_{ c #20201F", +":{ c #E7E7E7", +"<{ c #0F0F0C", +"[{ c #BDBDBD", +"}{ c #5F5F5E", +"|{ c #555553", +"1{ c #DDDDDD", +"2{ c #12120F", +"3{ c #E0E0DF", +"4{ c #999998", +"5{ c #727271", +"6{ c #878786", +"7{ c #4D4D4C", +"8{ c #DFDFDF", +"9{ c #D4D4D3", +"0{ c #DDDDDC", +"a{ c #3D3D3C", +"b{ c #666665", +"c{ c #545453", +"d{ c #71716F", +"e{ c #1F1F1E", +"f{ c #484847", +"g{ c #959594", +"h{ c #4B4B49", +"i{ c #D1D1D1", +"j{ c #40403F", +"k{ c #7C7C7A", +"l{ c #979796", +"m{ c #262625", +"n{ c #F3F3F3", +"o{ c #585856", +"p{ c #464644", +"q{ c #595958", +"r{ c #BEBEBD", +"s{ c #FCFCFB", +"t{ c #A7A7A6", +"u{ c #1C1C19", +"v{ c #B9B9B8", +"w{ c #BCBCBB", +"x{ c #A5A5A5", +"y{ c #969695", +"z{ c #626261", +"A{ c #B4B4B4", +"B{ c #4A4A49", +"C{ c #CFCFCF", +"D{ c #1B1B18", +"E{ c #60605F", +"F{ c #A6A6A5", +"G{ c #0D0D0A", +"H{ c #272726", +"I{ c #22221F", +"J{ c #777775", +"K{ c #F4F4F3", +"L{ c #6E6E6D", +"M{ c #1C1C1B", +"N{ c #E2E2E1", +"O{ c #080805", +"P{ c #8E8E8E", +"Q{ c #737372", +"R{ c #AFAFAE", +"S{ c #282826", +"T{ c #393937", +"U{ c #A7A7A7", +"V{ c #5A5A58", +"W{ c #2C2C2A", +"X{ c #545452", +"Y{ c #070704", +"Z{ c #B3B3B3", +"`{ c #F9F9F8", +" ] c #8C8C8B", +".] c #70706F", +"+] c #A6A6A4", +"@] c #D3D3D2", +"#] c #949493", +"$] c #393938", +"%] c #030301", +"&] c #050502", +"*] c #ABABAB", +"=] c #838382", +"-] c #B2B2B1", +";] c #CCCCCB", +">] c #CFCFCE", +",] c #C8C8C8", +"'] c #8F8F8D", +")] c #9B9B99", +"!] c #5C5C5B", +"~] c #666664", +"{] c #888887", +"]] c #656563", +"^] c #4F4F4C", +"/] c #CBCBCA", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . + @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $ % % % % % % % % % % % % % % % % % % % % % % % % % % & & & & & & & & & & & & & & & & & & & & & & & & & & & & . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . * . = - ; > > > > > > > > > > > > > > > > > > > > > > ; , ' . ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ! ~ { ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ^ / ( _ ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( : < & . . . . . . . . . ", +" . . . . . . . . + . [ } | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 4 5 . ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 a b c d d d d d d d d d d d d d d d d d d d d d d e f g . h . . . . . . . . ", +" . . . . . . . . . . * . i j k l l l l l l l l l l l l l l l l l l l l l m n o p . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . q r s t u v v v v v v v v v v v v v v v v v v v v v w x y z A A A A A A A A A A A A A A A A A A A A A A B C D E . . . . . . . . . . . ", +" . . . . . . . . . . ) . F G H I I I I I I I I I I I I I I I I I I I I I J K L M N . + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . O P Q R S T U U U U U U U U U U U U U U U U U U U U V W X Y Z ` .........................................+.e @.. h . . . . . . . . . . ", +" . . . . . . . . . . . . # . #.1 l I I I I I I I I I I I I I I I I I I I I $.K %.&.*.. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . =.-.;.Q >.,.w U U U U U U U U U U U U U U U U U U U U '.).!.~.~.!.{.......................................+.].^.. /.. . . . . . . . . . . . ", +" . . . . . . . . . . . . . * . (._.:.H I I I I I I I I I I I I I I I I I I <.K K K [.o }.. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . |.1.2.R R 3.4.5.U U U U U U U U U U U U U U U U U U 6.7.Y ~.~.~.X 8. .......................................9.0.. /.. . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . @ . a.1 l I I I I I I I I I I I I I I I I I b.K K K K c.d.e.f.. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /.. g.h.i.j.R R k.l.U U U U U U U U U U U U U U U U U U U V m.n.~.~.~.~.~.9.o.................................A p.q.. h . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . * . r.s.j t.I I I I I I I I I I I I I I I I u.K K K K K v.o w.. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . x.y.2.R R R R >.z.5.U U U U U U U U U U U U U U U U A.B.C.~.~.~.~.~.X z ...............................o.9.D.E.. * . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . + . F.G.H.I I I I I I I I I I I I I I I b.K K K K K K I.J.K.L.. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . M.N.O.R R R R R R j.P.T U U U U U U U U U U U U U U U w Q.Y ~.~.~.~.~.~.X R. .............................A S.< . & . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . ) . T.U.V.I I I I I I I I I I I I I I $.K K K K K K K %.W.X.. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h Y.Z.Q R R R R R R >.`.T U U U U U U U U U U U U U U A. +!.~.~.~.~.~.~.~.Z y ............................ ..+++% . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . ) . @+#+$+H I I I I I I I I I I I I J K K K K K K K K K c.%+&+. + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . *+=+l.R R R R R R R R k.-+w U U U U U U U U U U U U ;+>+~.~.~.~.~.~.~.~.~.~.X S. ......................... .,+'+. h . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . + . )+1 l I I I I I I I I I I I I $.K K K K K K K K K c.%+!+~+. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . {+]+^+/+R R R R R R R R 3.(+T U U U U U U U U U U U U A._+!.~.~.~.~.~.~.~.~.~.~.:+C ......................A e <+. /.. . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . * . [+}+|+t.I I I I I I I I I I 1+K K K K K K K K K K K [.o 2+. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . 3+1.2.R R R R R R R R R R 4+5+5.U U U U U U U U U U A.6+7+~.~.~.~.~.~.~.~.~.~.~.X 8+ .....................9+..0+. /.. . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . # . a+b+l I I I I I I I I I b.K K K K K K K K K K K K I.c+d+e+. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . f+j.R R R R R R R R R R R R k.Q V U U U U U U U U U U U g+n.~.~.~.~.~.~.~.~.~.~.~.~.~.h+o.................A p.i+. h . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . j+k+G.H.I I I I I I I I u.K K K K K K K K K K K K K [.o l+. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . m+P Q R R R R R R R R R R R R >.n+5.U U U U U U U U A.o+!.~.~.~.~.~.~.~.~.~.~.~.~.~.X p+o...............o.h+q+r+. . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . + . s+t+u+I I I I I I I J K K K K K K K K K K K K K K K K v+w+. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . x+y+Q R R R R R R R R R R R R R R R z+T U U U U U U V A+X ~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.Z ` .............+.e B+. h . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . + . C+b+l I I I I I I $.K K K K K K K K K K K K K K K %.D+E+. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . E F+7 Q R R R R R R R R R R R R R R >.G+w U U U U U U A.H+!.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.Z !.............+.,+I+. . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . J+K+L+H I I I I <.K K K K K K K K K K K K K K K K K %.D+M+. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . N+1.2.R R R R R R R R R R R R R R R R 3.O+5.U U U U ;+P+Y ~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.X Q+ .........o.h+R+. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . @ . > 1 l I I I H $.K K K K K K K K K K K K K K K K K c.M S+T+. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /.. U+V+W+j.R R R R R R R R R R R R R R R R k.X+U U U U U ;+Y+!.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.9.o.....A p.Z+. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . T+`+ @t.I I 1+K K K K K K K K K K K K K K K K K K K v.o .@. @ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . +@@@2.R R R R R R R R R R R R R R R R R R >.#@5.U U A.$@n.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.X %@o.....&@*@=@. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . -@U.H.I b.K K K K K K K K K K K K K K K K K K K K I.;@>@,@. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . '@)@j.R R R R R R R R R R R R R R R R R R R k.!@A.T V T ~@Y ~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.Z {@o.A p.( . & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. ^@G.V.u.K K K K K K K K K K K K K K K K K K K K K [.o /@. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . (@_@Q R R R R R R R R R R R R R R R R R R R R >.:@5.A.<@!.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.Z p++.[@}@E . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . |@L+1@I.K K K K K K K K K K K K K K K K K K K K K K L M 2@. + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . 3@P Q R R R R R R R R R R R R R R R R R R R R R R k.S t Q.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.X 4@5@6@. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + . 7@8@9@K K K K K K K K K K K K K K K K K K K K K K %.&.0@* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . a@b@;.O.R R R R R R R R R R R R R R R R R R R R R R R c@d@y e@n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.n.f@g@h@. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. i@j@k@l@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@m@n@o@p@. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . % . q@r@s@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@u@v@w@x@y@z@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@A@B@a@. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . C@D@E@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@G@H@I@J@. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . K@L@M@N@O@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@Q@R@S@. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . T@U@V@W@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@m@X@Y@Z@`@. #. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . .#+#@###$#P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@%#&#*#. /././././././././././././././././././././././././././.* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . =#-#W@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@;#>#,#'#)#. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . !#~#{#]#^#$#P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@$#/#(#. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . _#:#<#F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@m@[#}#|#1#2#3#. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & 4#5#{#6#]#7#$#P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@8#9#0#. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . a#W@b#c#F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@d#e#|#|#|#'#f#g#. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . h#+#@#6#6#]#{#P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@$#i#j#k#. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . l#m#E@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@F@l@n#}#|#|#|#'#o#p#T@. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . q#r#s#t#6#6#6#]#u#$#P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@P@8#v#w#. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . x#y#z#W@F@F@F@F@F@F@F@F@F@F@F@F@F@F@m@A#|#|#|#|#|#|#B#C#D#. #. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . E#F#^#6#6#6#6#6#G#i#$#P@P@P@P@P@P@P@P@P@P@P@P@P@P@%#H#I#J#. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . K#L#<#F@F@F@F@F@F@F@F@F@F@F@F@F@F@l@M#}#|#|#|#|#|#N#O#P#Q#. ]@. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . R#6#6#6#6#6#6#6#6#]#S#$#P@P@P@P@P@P@P@P@P@P@P@P@P@P@%#T#U#. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * * V#-#<#F@F@F@F@F@F@F@F@F@F@F@F@m@X@W#|#|#|#|#|#|#|#B#C#X#. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . Y#Z#@#6#6#6#6#6#6#6#6#`#$#P@P@P@P@P@P@P@P@P@P@P@P@Q@ $.$. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . +$@$G@F@F@F@F@F@F@F@F@F@F@F@F@#$;#|#|#|#|#|#|#|#|#|#|#O#$$. ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . %$&${#6#6#6#6#6#6#6#6#]#*$P@P@P@P@P@P@P@P@P@P@P@P@P@P@=$-$. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . ;$>$E@F@F@F@F@F@F@F@F@F@F@m@,$}#|#|#|#|#|#|#|#|#|#'$)$!$. ]@. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . ~${$~#{#6#6#6#6#6#6#6#6#6#]#7#$#P@P@P@P@P@P@P@P@P@P@8#v#]$. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. ^$/$($c#F@F@F@F@F@F@F@F@l@d#|#|#|#|#|#|#|#|#|#|#|#|#'$_$:$. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . % . <$[$@#6#6#6#6#6#6#6#6#6#6#6#{#O@P@P@P@P@P@P@P@P@P@N@}$|$1$. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . 2$m#E@F@F@F@F@F@F@F@F@m@3$}#|#|#|#|#|#|#|#|#|#|#|#'#4$5$6$. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /.. 7$8$9$G#6#6#6#6#6#6#6#6#6#6#6#]#0$$#P@P@P@P@P@P@P@P@8#9#a$. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . b$c$@$W@F@F@F@F@F@F@m@d$}#|#|#|#|#|#|#|#|#|#|#|#|#|#B#e$f$. #. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . g$F#@#6#6#6#6#6#6#6#6#6#6#6#6#6#6#i#$#P@P@P@P@P@P@%#h$i$% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . j$k$<#F@F@F@F@F@F@F@l$W#|#|#|#|#|#|#|#|#|#|#|#|#|#>#m$n$o$. ]@. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . p$s#G#6#6#6#6#6#6#6#6#6#6#6#6#6#6#]#q$$#P@P@P@P@P@P@%#r$s$. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . t$k$<#F@F@F@F@m@u$}#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#1#v$w$. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /.. x$&$y$6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#]#z$$#P@P@P@P@8#A$B$. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . C$D$F@F@F@F@F@E$F$|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#'#o#G$. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . H$I$y$6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#]#y$P@P@P@P@$#=$8#J$. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . K$m#E@F@F@m@n#}#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#L$f#M$) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . N$O$P${#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#]#Q$$#P@P@8#v#R$. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. S$T$U$c#l@V$|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#B#v$W$. #. . . . . . . . . . . . . . . . . . . . . . . . . . . % . X$F#^#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#G#=$P@N@/#Y$Z$. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . `$m# %m@M#}#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#N#.%+%@%. * . . . . . . . . . . . . . . . . . . . . . . . . . h . #%^#$%G#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#6#]#%%$#Q@A$&%. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . *%=%-%;%}#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#B#C#>%. #. . . . . . . . . . . . . . . . . . . . . . . . . & . ,%'%)%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%!%~%{%]%. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . ^%/%(%|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#>#,#e#_%. ) . . . . . . . . . . . . . . . . . . . . . . . & . :%<%[%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%}%|%1%2%3%. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . 4%5%6%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%7%6%8%9%. ) . . . . . . . . . . . . . . . . . . . . . . . . ) 0%a%b%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%d%e%f%. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . g%h%i%j%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%l%m%n%. #. . . . . . . . . . . . . . . . . . . . . # . o%p%q%r%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%t%u%v%w%. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. x%y%z%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%A%B%C%D%E%. * . . . . . . . . . . . . . . . . . . . * . F%G%H%I%J%K%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%K%M%N%O%P%. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . Q%R%S%T%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%U%V%W%X%. #. . . . . . . . . . . . . . . . . . . # . Y%Z%`% &.&L%+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&L%@&#&$&%&&&*&. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. =&-&l%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%;&>&,&'&)&!&~&. ]@. . . . . . . . . . . . . . . . . & . {&]&^&/&(&_&:&L%+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&<&@&[&}&|&1&2&. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3&4&5&k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%6&7&8&8&9&0&a&. #. . . . . . . . . . . . . . . . . & . b&c&d&/&e&f&g&h&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&L%i&j&}&k&l&m&n&o&. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . p&q&T%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%A%r&s&8&8&8&8&t&u&. & . . . . . . . . . . . . . . . # . v&w&x&^&^&y&z&A&B&g&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&+&C&D&E&F&l&l&G&H&I&E.. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . J&K&z%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%A%L&8&8&8&8&8&V%M&N&. ]@. . . . . . . . . . . . . . * . ~$O&P&x&^&^&^&Q&R&S&J%T&+&+&+&+&+&+&+&+&+&+&+&+&+&+&L%s%U&V&k&l&l&l&W&X&Y&. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. Z&`& *j%k%k%k%k%k%k%k%k%k%k%k%k%k%k%k%.*s&8&8&8&8&8&V%+*@*. #. . . . . . . . . . . . . # . #*$*%*^&^&^&^&y&&***:&L%+&+&+&+&+&+&+&+&+&+&+&+&+&+&@&=*k&l&l&l&l&l&-*;*>*,*. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. '*)*z%k%k%k%k%k%k%k%k%k%k%k%k%k%A%!*s&8&8&8&8&8&8&~*{*]*^*. * . . . . . . . . . . . ]@. /*(*_*:*^&^&^&^&^&/&e&<*[*L%+&+&+&+&+&+&+&+&+&+&+&+&L%M%}*|*k&l&l&l&l&l&1*2*3*. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . 4*5*6*h%k%k%k%k%k%k%k%k%k%k%k%k%i%U%8&8&8&8&8&8&8&8&9&7*8*. #. . . . . . . . . . . # . 9*$*d&^&^&^&^&^&^&/&0*a*b*+&+&+&+&+&+&+&+&+&+&+&+&L%M%c*d*l&l&l&l&l&l&l&l&$&H&e*. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . f*g*l%k%k%k%k%k%k%k%k%k%k%k%;&h*,&8&8&8&8&8&8&8&8&i*j*k*l*. ) . . . . . . . . . & . m*n*:*^&^&^&^&^&^&^&^&/&&*o*B&g&+&+&+&+&+&+&+&+&+&+&+&+&p*F&q*l&l&l&l&l&l&l&r*1&s*. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . t*u*l%k%k%k%k%k%k%k%k%k%v*6&8&8&8&8&8&8&8&8&8&8&8&V%w*x*. & . . . . . . . . . * . y*w&d&^&^&^&^&^&^&^&^&z*A*B*C*D*+&+&+&+&+&+&+&+&+&L%i&E*|*k&l&l&l&l&l&l&l&l&l&m&F*G*. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . H*I*k%k%k%k%k%k%k%k%k%k%A%J*,&8&8&8&8&8&8&8&8&8&8&8&K*L*M*. N*. . . . . . . # . O*P*d&^&^&^&^&^&^&^&^&^&^&y&z&Q*B&g&+&+&+&+&+&+&+&+&D*R*S*T*l&l&l&l&l&l&l&l&l&l&G&H&U*Z$. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . V*y%z%k%k%k%k%k%k%k%;&W*s&8&8&8&8&8&8&8&8&8&8&8&8&K*X*Y*& . . . . . . . * . Z*`* =x&^&^&^&^&^&^&^&^&^&^&^&^&z*.=+=L%+&+&+&+&+&+&L%i&@=|*k&l&l&l&l&l&l&l&l&l&l&l&W&X&#=. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. $=%=&=T%k%k%k%k%k%k%k%*=s&8&8&8&8&8&8&8&8&8&8&8&8&8&V%w*==. #. . . . . # . -=;=>=^&^&^&^&^&^&^&^&^&^&^&^&/&&*,=[*L%+&+&+&+&+&L%M%'=T*l&l&l&l&l&l&l&l&l&l&l&l&l&-*;*)=!=. h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. ~=K&l%k%k%k%k%k%A%{=s&8&8&8&8&8&8&8&8&8&8&8&8&8&8&]=^=/=(=. ]@. . . & . _=:=<=:*^&^&^&^&^&^&^&^&^&^&^&^&^&/&[=}=|=L%+&+&+&+&+&D*1=}&k&l&l&l&l&l&l&l&l&l&l&l&l&l&1*2*2=. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3=4=5=6=k%k%k%k%7=8=8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&9&W%9=. #. . . & . 0=P*d&^&^&^&^&^&^&^&^&^&^&^&^&^&^&/&a=b=+&+&+&+&+&L%i&c=|*k&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&$&H&e*. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . d=5=h%k%k%k%A%e=s&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&f=g=. & . & . h=i=x&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&y&z&j=B&g&+&+&D*k=l=T*l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&r*1&s*. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . m=n=l%k%A%o=8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&V%+*p=. ) * . # q=r=x&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&Q&s=t=b*T&L%i&u=|*k&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&m&F*G*. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ) . v=l%i%j%;&w=,&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&x=y=z=. A=. B=C=d&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&y&z&D=:&K%@&E=l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&G&H&U*Z$. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. F=y%G=H=s&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&K*I=J=4*. K=L=M=N=^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&A*O=+=P=Q=}&k&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&W&X&#=. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . R=S=q&T=U=8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&8&9&7*V=. W=X=>=^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&^&/&[=Y=Z=`= -.-l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&-*;*+-!=. @-& & & h * * * * * * * * * * * * * * * * * * * * * /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. #-$-K*7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&%-&-*-=---;->->->->->->->->->->->->->->->->->->->->->->-z*,-'-)-!-~-{-T*l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&l&1*2*3*. & . . . . . . . . . . . . . . . . . . . . . . . . . . /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. ]-^-/-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-(-_-:-<-[-}-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-1-2-3-4-5-6-7-8-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-0-a-b-c-c-d-e-f-g-g-g-g-g-g-g-g-g-g-g-g-g-g-g-g-g-g-h-i-j-. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N*. k-l-m-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-n-o-p-q-r-s-t-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-u-v-w-x-y-z-A-B-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-C-D-E-F-G-H-H-H-I-J-J-J-J-J-J-J-J-J-J-J-J-J-J-J-J-J-J-J-K-L-M-N-. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. O-P-Q-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-S-T-U-V-W-X-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Z-`- ;. .;+;@;#;D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-$;E-%;&;*;=;=;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;-;;;>;,;';. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. );!;~;{;R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-];^;/;(;_;:;<;W-X-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-[;};|;1;h . 2;3;4;D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-5;6;7;8;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;0;a;b;c;d;e;. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. f;g;h;R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-i;j;k;l;m;:;n;Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-o;p;q;. #. r;s;t;u;D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-v;6;6;6;w;x;y;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;0;z;A;A;c;B;C;D;. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . E;F;G;H;R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-];^;I;(;J;K;m;L;M;N;w-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-o;O;P;. * . % . Q;R;u;D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-S;T;6;6;6;6;U;V;W;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;0;X;b;A;A;Y;Z;`;. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. >.>Q-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-];+>@>#>K;K;K;K;$>%>&>*>Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-x-=>->. & . . & . ;>>>4;D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-}*,>'>6;6;6;6;7;)>y;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;0;!>b;A;A;A;~>{>]>^>. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . />(>Q-R-R-R-R-R-R-R-R-R-R-R-R-R-R-R-_>:><>J;K;K;K;m;L;[>N;w-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-}>|>1>. # . . . & . 2>u;3>4>D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-C-6;6;6;6;6;6;6;6;5>y;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;6>b;A;A;A;A;Y;7>8>. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . 9>0>R-R-R-R-R-R-R-R-R-R-R-R-R-R-];^;a>(;J;K;K;K;K;K;K;K;b>c>X-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-x-d>e>f>. ]@. . . . g>. h>3;i>D-D-D-D-D-D-D-D-D-D-D-D-D-D-D-j>'>6;6;6;6;6;6;7;k>y;9;9;9;9;9;9;9;9;9;9;9;9;9;9;9;0;l>b;A;A;A;A;A;A;A;m>n>. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. o>p>h;R-R-R-R-R-R-R-R-R-R-R-R-q>r>s>#>K;K;K;K;K;K;t>u>v>w>Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Z-`-x>. #. . . . . /.. y>z>A>#;D-D-D-D-D-D-D-D-D-D-D-D-}*B>6;6;6;6;6;6;6;6;6;7;C>y;9;9;9;9;9;9;9;9;9;9;9;9;9;0;D>E>A;A;A;A;A;A;A;F>G>H>. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. I>J>K>{;R-R-R-R-R-R-R-R-R-R-];^;L>(;J;K;K;K;K;K;K;K;t>u>M>W-w-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-[;N>O>P>. * . . . . . . g>. Q>>>4;D-D-D-D-D-D-D-D-D-D-D-D-D-U;6;6;6;6;6;6;6;6;6;7;j>0;9;9;9;9;9;9;9;9;9;9;9;9;9;0;R>b;A;A;A;A;A;A;A;A;S>T>U>. # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. V>P-Q-R-R-R-R-R-R-R-R-R-R-_>W>J;K;K;K;K;K;K;K;K;K;K;X>Y>X-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-Y-[;Z>`>. # . . . . . . . . /.. ,.,+,D-D-D-D-D-D-D-D-D-D-D-@,6;6;6;6;6;6;6;6;6;6;6;7;#,y;9;9;9;9;9;9;9;9;9;9;9;0;$,b;A;A;A;A;A;A;A;A;A;c;%,&,N$. * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3=*,=,-,R-R-R-R-R-R-R-R-];+>;,<>J;K;K;K;K;K;K;K;K;K;m;L;>,,,w-Y-Y-Y-Y-Y-Y-Y-Y-o;Z>',. & . . . . . . . . . $ . ),!,#;D-D-D-D-D-D-D-D-D-D-~,{,6;6;6;6;6;6;6;6;6;6;6;6;6;],y;9;9;9;9;9;9;9;9;9;9;0;^,b;A;A;A;A;A;A;A;A;A;A;Y;Z;/,. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N*. (,_,H;R-R-R-R-R-R-R-];+>:,r-K;K;K;K;K;K;K;K;K;K;K;K;<,[,},*>Y-Y-Y-Y-Y-Y-Y-Y-Y-|,1,. & . . . . . . . . . . $ . 2,3,i>D-D-D-D-D-D-D-D-D-,>6;6;6;6;6;6;6;6;6;6;6;6;6;7;4,y;9;9;9;9;9;9;9;9;9;0;5,b;A;A;A;A;A;A;A;A;A;A;A;6,7,8,9,. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N*. 0,a,Q-R-R-R-R-R-R-R-R-b,r-J;K;K;K;K;K;K;K;K;K;K;K;m;u>c,W-X-Y-Y-Y-Y-Y-Y-Z-`-d,. # . . . . . . . . . . . h . e,f,g,h,D-D-D-D-D-D-D-3>6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;7;i,y;9;9;9;9;9;9;9;9;y;j,b;A;A;A;A;A;A;A;A;A;A;A;A;S>T>k,. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . & . l,h;0>m,R-R-R-R-];^;n,(;J;K;K;K;K;K;K;K;K;K;K;K;K;K;K;$>o,W-X-Y-Y-Y-Y-p,q,r,s,. * . . . . . . . . . . . . g>. t,3;i>D-D-D-D-D-D-}*j>'>6;6;6;6;6;6;6;6;6;6;6;6;6;6;7;u,9;9;9;9;9;9;9;9;0;v,b;A;A;A;A;A;A;A;A;A;A;A;A;A;A;c;B;w,. & . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. x,g;h;R-R-R-R-i;y,z,#>K;K;K;K;K;K;K;K;K;K;K;K;K;K;t>:;A,*>Y-Y-Y-Y-Y-}>B,C,. # . . . . . . . . . . . . . * . D,E,F,u;D-D-D-D-}*B>6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;7;8-y;9;9;9;9;9;0;G,A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;c;H,I,# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. J,K,L,H;R-R-];^;M,(;J;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;t>N,O,P,w-Y-Y-[;Q,R, #. . . . . . . . . . . . . . . . % . S,T,4;D-D-D-D-D-T;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;j>U,9;9;9;9;9;0;V,b;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;S>W,X,. % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. Y,a,Q-R-];_>Z,#>K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;$>`, '*>Y-Y-[;.'+'. & . . . . . . . . . . . . . . . . & . @'T,4;D-D-}*,>'>6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;7;#'y;9;9;9;0;$'b;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;%'&'*'='. /.. . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. -'.>Q-R-_>;'<>J;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;m;L;>','w-}>p;''. & . . . . . . . . . . . . . . . . . & . )'!'D-D-D-C-E-6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;~'y;9;9;9;{'b;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;Y;]'^'. # . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N*. /'('_'^;:'<>J;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;K;<'c>['Z-}'. & . . . . . . . . . . . . . . . . . . % . |'1'i>D-2'6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;6;7;$;y;9;0;3'b;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;A;4'5'. & . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. 6'7'8'9'0'a'a'a'a'a'a'a'a'a'a'a'a'a'a'a'a'a'a'a'a'b'c'd'e'f'g'. # . . . . . . . . . . . . . . . . . . . h . h'i'j'k'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'l'm'n';;;;o'c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;8,d;p'. h . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. q'r's't'u'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'v'u'w'x'y'z'. * . . . . . . . . . . . . . . . . . . . . g>. A'B'C'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'D'E'F'G'H'I'B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;B;J'K'L'. # . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #. M'N'O'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'P'Q'R'S'T'. # . . . . . . . . . . . . . . . . . . . . . . . D;U'V'W'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'X'Y'Z'`' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ).)+)@). . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@h g>N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*N*g>h * . . . . . . . . . . . . . . . . . . . . . . . . h h $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ & & & & & & & & & & & & & & & & & & & & & & & & & ]@E # . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]@. . . . . . . . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . . . . . * * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * . . . . . . . . . . . . . . . . . . . . . . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #)$)$)$)$)$). . . . . . . . . h $)$)$)$)$). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #)$)%)$)$)$)%)$)#). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $)h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . h . &)*)=)-);)>)$). . . . . . h . ,)')=)-)-)=))). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #)#). h !)~){)])^)/)()_):). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . %). <)[)})|)1)2)3). #). . . . $). 4)5)2)6)7)8). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #)h N*9)0)a)b)c)d)e)f)c)g)h)i). $). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h $)$). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . #). j)k)l)l)m)n)o). $). . . h . p)q)r)a)m)s)t). $). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #). u)v)b)1)w)h)x)y)z)A)B)C)D)E). $). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . h F)6)l)a)b)G). #). . . #). H)6)I)J)K)C)L). #). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #). M)N)1)h)O)P)=)Q)R)h %)S)T)U)V). h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . W)9)X)Y). #). . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . $). Z)`)O)J)r)N)S). h . . $). <) !O)l).!+!. . . . . . #)$)%)%)$)#). . . . . . . h h h h h . . h $)%)#). . . . h $)$)%)%)%)$)h . . . . . . h . @!#!2)$!%!!). h . . . . . . . h . . . h h . . . . $)$). . h h h . . . . . . . . . h h h . . . h h . . . . #)$)$)#). . . . . . . $). &!e) !*!. $)h . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . #). =!})J)K)l)-!;!. $). . . . >!|)l)O) !,!. $). . #)#). . . . . . #)$). . . . . . . . . . . #)h . . . . . $)#). . . . . . . . $)h . . . . #). '!b)h))!!!. %)$)h h . h h $)$). . . . . . . . #)h . . . . . . . h . . . . . . . h . . . . . . . . . . $)h . . . . #)$). . . . . #). v)|)l)~!. #). . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . h . %){!6)l)a)w)]!. $). #). 3)K)K)J)K)K)Y). #). #)h . ^!/!(!_!~)M)h . #). . . . :!^!)3!4!_!5!6!7!. #)h . . R). 8!6)K)9!0!. %). . . . . . . . . . . . #)a!b!%)h . c!d!-)e!%)f!a!g!h . . . . . . . #)a!c!f!#). h!b!g!#)#). i!j!H)-)k!h . #). . . #)f!. v)1)k)2!. f!c!$). . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . $). l!w)a)l)6)m!#). h $). 4!w)a)l)g)n!. h . $). o!p!O)q!n)n)n)r!s!d!. #). $). t!u!v!w!x!. 9)y!g)D)z!. i!A!B!N)2)b)w)w)n)|)C!D!)). h . $). E!1)q!l!. %). . . . . . . . . . . h . [!F!G!H!. I!{!h)})J!K!L!L!M!!). #). . . $). N!N)x)O!. . P!G!Q!R!. S!A)K)-!2)9!n!T!. #)R). U!x)V!W!k)K)X!Y!Z!N)`!. $). . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . $). *)6)l)J)K)k) ~. #)#). .~q!a)O) !1!. $)$). 9)K)w)K)9!k)K)m)J)q!+~`!. R)$). @~#~O)n)$~%~g)})&~q!*~. :!G!#~J)O)a)l)9!m)l)r)=~-~%). #). ;~x)r)r)U!. #). . . . . . . . . . . h . >~,~[)'~8!1)w)n)q!)~. !~n)~~{~. $). . . #). ]~ !#~^~. . {)e)J)L)4)[)f)k)O)1)g)6)n)i). i!. /~D)(~h)J)K)n)~~w)D)_~. %). . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . h . p)M!})I)O) !:~. i!. <~,~[~J)k)l)}~. %). |~6)[~m)[~g)x)1~q!K)9!r)a)2~. i!. 3~w)m)}){!m!6)m)W!b)4~. . 5~ !q!q!K)m)2)q!J)J)m)=~i). i!. U!h)h)M!p). h . . . . . . . . . . . h . f!6~w)p!8)=~7~]!*~~. R). %{&~g)F!#). %). 4!b)&{n~. $). . . . %). D!q!g)*{. $)#). G~q!k)={. #). . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . $). -{w)a)O)`)U). ;{[~K)a)1)s!. #). p)>{h)l)[~1~0),{z)z)'{Q!C)K)a)w)){. . P!f~O)l)g)z). $)%)$)#). #). |~v)a)n)w)1)1)[~J)K)a)w)^~. . !{q!|)T~. #). . . . . . . . . . . . h . a!6~2)a)Y). #). . . . h . ~{|)g){{. )). ^~q!q!i). $)%). 4!q!b)u~. %). . . . #). ]{h)6)^{. . R). G~q!k)={. #). . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . $). /!q!a)l)g)/{. ({ !_{a)w)4!. i!. :{9~C)J)K)C)6)2)2)2)6)r)a)a)m)q!_!. . P!f~O)a)<{J~. $). . . h . ()q!q!K)m)C)1)n)2)J)K)a)w)_!. . [{|)h)Z!)). h . . . . . . . . . . . h . a!6~6)G!~t~w)O)k)O):). $). K!&~C)J)J)[~b)q!q!q!q!b)w)w)1)D)4{. . P!f~O)a)w)5{. $). . $). 5!7)l)O)J)2{z~${6{7{6)l)a)w)4!. . 8{9!k)k)9{. #). . . . . . . . . . . h . a!6~6)G!K!. h . . . . h . 7!>{2)&~3{. 0{W!n)G). #). %). 4!2{n)D!. %). . . . #). J!&~|)a{i!. $). G~q!k)={. #). . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . #). b{n)a)l)|)`!%!|)O)1)c{. h h . [!1~[~l)r)#!^)d{5{5{5{5{5{5{])E!d!. . P!f~O)a)w)5{. $). h . ))6~})e{l)6){)i!$). {) !O)a)w)4!. %). f{})b){). %). . . . . . . . . . . h . a!6~6)G!K!. h . . . . . $). 3~q!q!g{. :~q!|)o~. $). %). 4!2{s)D!. %). . . . #). x~[~|)h{. h #). G~q!k)={. #). . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . $). #{n)a)l)2)B!y!r)O)`)(!. $). . . F!6)a)h)z~F~. h . . . . . . . . %). P!f~O)a)w)5{. $). #). i{r)J)l)6)j{%). p). k{`)_{a)w)4!. e!. l{w)l)m{8{. %). . . . . . . . . . h . a!6~6)G!K!. h . . . . . #). &)l)1),{. W~f~6~n{. h . %). 4!q!b)4~. %). . . . %). _~q!1)E!. $)#). o{q!k)={. #). . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . h . :{,~[~J)K)a)K)J)C)9!8{. #). $). '~ !O)a)q!O!)). h . . . . $)$)h %). P!f~O)a)w)5{. $). $). %~1)l)l)|)p{. . . i!i~6)l)a)w)4!. i!. >~X~[~|)s!e!. %)$)h h h h #)$)$). h . a!6~6)G!K!. h . . . . . . #). q{n)G!r{x)~~@~. $). . %). 4!b)h)D~s{#)#). . #)$). $~2)b)t{. $)#). ~{1)u{;{. $)h . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . #). G)b)a)K)k)K)a)q!T~. #). . #). L)[~J)J)l)q!V!i)v{H)w{x{z!c{:!. i!. P!f~O)a)w)5{. $). #). U~r)J)K)J)h)y{>~}~z{|)l)K)a)w)4!. %)$). A{b)O)g)n!k!. h . . . . . . . . h . a!6~6)G!K!. h . . . . . . $). {{b)l)B{a)r)C{. #). . %). 4!w)m)2{1!. #)h h #). ){|)D{C!>~. h #). E{g)|)/!. $). . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . $). F{w)a)K)K)K)a)w)5!. $). . . #). ()=~a)a)a)2)G{q!g)1)n)w)2{~!. )). P!f~O)a)w)5{. $). h . $)V!6)O)K)k)g)H{K)|)C)k)K)a)w)(!. %). $). l{ !K)})I{J{|~<~p)a!K{3{v{L{j!. . a!6~6)G!K!. h . . . . . . h . r~>{})M{g)e~. h . . . %). 4!`)9!})|)+{S). . n{,!C)a)#~){. $). %). +{s)r)h{b~h ;~%). . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . #). N{W!K)a)l)a)K)m)%{. #). . . . h . @~w)g)K)9!&~m)m)m)m)W!O{^~. g!. P{ !9!O)n)Q{. $). . $). 9) ![~O)O)m)J)k)g)#!a)K)9!w)g{. %). . R). R{S{n)$!b)})1~T{Z!>{W!6)D)4!. h a!M!2)S{V). h . . . . . . . $). {)w)&~n)U{. $). . . %). 4!n)r)V{1~[)W{X{v)#!1)h)~~@~. #). . #). H~g)K)[~1~D~L!8{. #). . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . #). |{Y{2)g)2)f)T~. #). . . . . . #). A!n!k)n) ! !f~ !b)K)L!Z{. `{. ]=~K)k)~~.]. $). . . #). +]W!`)w)w)w)})J{@]a)})K)c)]!. $). . . $). <~4~>{r)b)~~f)f)O{`)C)B)F{. . p)z~q!m)K!. h . . . . . . . #). x~[~h)>{7!. h . . . %). 4!2{w)#]9{$] ![)%]c)-!x)_~. #). . . . #). #]6)n)G{&]c)j). #). . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . h . 8{')=)-)=)*)m~. h . . . . . . h #). h 3)*]C~=]()l{-] ~i!. . h . @!;]H~H~d!N{. h . . . . #). :{){U)U)j~ ~. %)@]>]H~d!8{. h . . . . $)h . f!,]o)<)*~4~']V~U!r~. h . #)M)x~U~i!. . . . . . . . . %). )]|)b)D!. $). . . . %). 4!2{s) ]. 7!v{()]!+{-]>~. $). . . . . . h . @]D!z!{)V~r~. h . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $)h . . . . . . . . h h . . . . . . . . . . . . . . . . $). . . . . . #)h . . . . . . . . . . . . #)$). . . . . . . . . . h . . . . . . . . . . . . . . . #). <~B)|)B)W). h . . . . %). 4!2{n)P!. i!. . . . . . $). . . . . . . . #). . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . #)$)$)$)$)$)h . . . . . . . . . . . . #)$)%)$)%)%)$)#). . . . . h #)#)#)#)h . . . . . . . . h %)$)$)%)#). . #)#)#)#)h . . . . . . . . . h #)%)%)$)$)%)$)#)h . . . . #)#)#). . . . . . . . %)h . !]6)n)#]. $). . . . . %). 4!2{n)P!. i!$)$)$)%)$)h . . . . . . . . . . #)%)$)%)s{]@. . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . p)~]|)&{/{i!. h . . . . . %). 4!2{n)P!. %). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . c!o~V!|)h)&~Y). #). . . . . . %). (!6)-!t). %). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $). ')#~r)q!,~U!. #). . . . . . . %). l{e)%]{]. %). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . F~S{|)]]^!. $). . . . . . . . $). l~^]n!3!. $). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . h . {{/]. h #). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #)#). . . . . . . . . . . . h #)#)h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $)#). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" ", +" "}; diff --git a/src/Resources/Icons/VeraCrypt-48x48.xpm b/src/Resources/Icons/VeraCrypt-48x48.xpm index 7debeb8d..1e2966f5 100644 --- a/src/Resources/Icons/VeraCrypt-48x48.xpm +++ b/src/Resources/Icons/VeraCrypt-48x48.xpm @@ -1,486 +1,486 @@ -/* XPM */ -static const char *VeraCryptIcon48x48[] = { -"48 48 435 2", -" c None", -". c #FFFFFF", -"+ c #FEFFFF", -"@ c #FDFEFF", -"# c #FEFEFE", -"$ c #FEFFFE", -"% c #EFF9FC", -"& c #CDEEF7", -"* c #D5F1F8", -"= c #D3F0F8", -"- c #D1EFF8", -"; c #DBF2F9", -"> c #FDFEFE", -", c #E7F5F1", -"' c #E4F3EF", -") c #E5F4EF", -"! c #E4F3EE", -"~ c #EAF6F2", -"{ c #EDF6F3", -"] c #ECF6F3", -"^ c #EAF5F1", -"/ c #F8FCFA", -"( c #EAF8FC", -"_ c #1CB1DB", -": c #01A8D7", -"< c #07ABD8", -"[ c #04AAD8", -"} c #0DA8D5", -"| c #CFEDF6", -"1 c #CFECE4", -"2 c #5ABA9D", -"3 c #6CBFA4", -"4 c #69BEA3", -"5 c #8ACAB3", -"6 c #96CFBA", -"7 c #95CEB9", -"8 c #93CEB8", -"9 c #9BD2BE", -"0 c #F4FAF8", -"a c #FCFEFE", -"b c #99DCEF", -"c c #00A5D5", -"d c #0BADD9", -"e c #0DABD8", -"f c #00A1D0", -"g c #4EBEDF", -"h c #73C6AE", -"i c #4AB696", -"j c #6ABFA4", -"k c #6ABEA3", -"l c #7EC5AD", -"m c #86C9B2", -"n c #92CDB8", -"o c #99D0BC", -"p c #8FCCB5", -"q c #D0EAE0", -"r c #3ABBE0", -"s c #00A8D7", -"t c #10A8D5", -"u c #12A7D3", -"v c #01A1D1", -"w c #AEE1F0", -"x c #B7E2D5", -"y c #46B494", -"z c #53BA9C", -"A c #5ABB9E", -"B c #6CBFA5", -"C c #74C2A9", -"D c #88C9B3", -"E c #85C8B1", -"F c #8BCBB5", -"G c #A8D7C6", -"H c #FCFEFF", -"I c #BCE8F5", -"J c #03A6D5", -"K c #0FA7D3", -"L c #05A3D2", -"M c #2FB3D9", -"N c #F6FCFD", -"O c #F1F9F7", -"P c #61BFA3", -"Q c #4FB899", -"R c #54B99C", -"S c #53B99B", -"T c #5FBC9F", -"U c #7CC4AB", -"V c #80C5AE", -"W c #7FC5AD", -"X c #88C9B2", -"Y c #E1F1EB", -"Z c #63BFE1", -"` c #0898CF", -" . c #1AA0D3", -".. c #1BA1D3", -"+. c #0697CE", -"@. c #91CBE7", -"#. c #FCFDFE", -"$. c #91D5C4", -"%. c #3BB392", -"&. c #4BB99C", -"*. c #4BB99B", -"=. c #3CB393", -"-. c #8DD2BF", -";. c #E8F4EF", -">. c #DBEFE8", -",. c #DDF0E9", -"'. c #DCEFE8", -"). c #E2F2EC", -"!. c #DDF0F8", -"~. c #209ED2", -"{. c #199AD1", -"]. c #1C9DD2", -"^. c #1C94CF", -"/. c #2C90CF", -"(. c #E3F1F9", -"_. c #FEFEFF", -":. c #D9F1EB", -"<. c #31B394", -"[. c #3EB697", -"}. c #46B89A", -"|. c #40B697", -"1. c #4FBB9F", -"2. c #EDF8F5", -"3. c #89CCE7", -"4. c #0995CE", -"5. c #1E9DD1", -"6. c #2690CE", -"7. c #1585CA", -"8. c #72B6DF", -"9. c #6CC7B1", -"0. c #26AD8D", -"a. c #38B495", -"b. c #47B799", -"c. c #37B291", -"d. c #ACDFD2", -"e. c #FAFDFD", -"f. c #F4FAFD", -"g. c #34A9D7", -"h. c #1891CE", -"i. c #268DCD", -"j. c #248ECD", -"k. c #1C8ACC", -"l. c #C8E3F3", -"m. c #BEEAE0", -"n. c #2AB493", -"o. c #37B999", -"p. c #34B899", -"q. c #36B797", -"r. c #67C5AC", -"s. c #FBFDFD", -"t. c #ADD9ED", -"u. c #1785C8", -"v. c #288CCC", -"w. c #1A85C9", -"x. c #54A3D6", -"y. c #F9FCFD", -"z. c #4DA991", -"A. c #26987A", -"B. c #2F9C7F", -"C. c #249779", -"D. c #BCE2D8", -"E. c #FCFEFD", -"F. c #5CA2D4", -"G. c #1D80C4", -"H. c #2B87C8", -"I. c #2C89C8", -"J. c #1575BC", -"K. c #A8C9E4", -"L. c #9DD8DE", -"M. c #177A73", -"N. c #236046", -"O. c #20654D", -"P. c #22614A", -"Q. c #196F54", -"R. c #7FC5B3", -"S. c #CEE4F2", -"T. c #2384C6", -"U. c #2987C8", -"V. c #2884C6", -"W. c #1A73BA", -"X. c #3684C2", -"Y. c #EFF6FA", -"Z. c #E6F4F5", -"`. c #37A9B2", -" + c #2AA2AA", -".+ c #246F5B", -"++ c #21664D", -"@+ c #226951", -"#+ c #2E997C", -"$+ c #289E7F", -"%+ c #CCE7E0", -"&+ c #7BB4DC", -"*+ c #1A7FC4", -"=+ c #267DC0", -"-+ c #2378BC", -";+ c #106DB7", -">+ c #83B4DA", -",+ c #79C4CB", -"'+ c #1E9DA6", -")+ c #31AAB5", -"!+ c #29908D", -"~+ c #215F45", -"{+ c #288469", -"]+ c #33A586", -"^+ c #24997A", -"/+ c #5EB59E", -"(+ c #E8F3FA", -"_+ c #3187C6", -":+ c #1C74BB", -"<+ c #2278BD", -"[+ c #1D75BB", -"}+ c #2C7CC0", -"|+ c #ABD5E3", -"1+ c #2FA6AD", -"2+ c #2CA3AD", -"3+ c #2DA4AD", -"4+ c #2EA5AF", -"5+ c #1E7B6A", -"6+ c #2E9A7B", -"7+ c #30A082", -"8+ c #32A083", -"9+ c #229979", -"0+ c #B1DBD0", -"a+ c #F9FCFB", -"b+ c #FCFDFD", -"c+ c #FDFDFD", -"d+ c #9BBBDC", -"e+ c #1960AD", -"f+ c #2D6EB4", -"g+ c #296CB3", -"h+ c #2768B1", -"i+ c #1A7798", -"j+ c #2F9DAF", -"k+ c #2F99AF", -"l+ c #309AAF", -"m+ c #2B98B0", -"n+ c #81C2C3", -"o+ c #329374", -"p+ c #298E72", -"q+ c #2C8F72", -"r+ c #298E71", -"s+ c #309174", -"t+ c #4DA78F", -"u+ c #4AA78E", -"v+ c #4BA88F", -"w+ c #49A58C", -"x+ c #4FB098", -"y+ c #E3F5F1", -"z+ c #FAFBFD", -"A+ c #4C80BD", -"B+ c #2263AD", -"C+ c #2E6AB5", -"D+ c #21689E", -"E+ c #0B6274", -"F+ c #278AA2", -"G+ c #349CB3", -"H+ c #2492AA", -"I+ c #5BADBF", -"J+ c #77B6A3", -"K+ c #1B8466", -"L+ c #2D8E72", -"M+ c #2A8C6F", -"N+ c #258565", -"O+ c #238D6E", -"P+ c #28987A", -"Q+ c #279577", -"R+ c #2A987B", -"S+ c #17A282", -"T+ c #77CAB8", -"U+ c #BCD0E6", -"V+ c #2062AE", -"W+ c #2F6DB2", -"X+ c #156983", -"Y+ c #0F6578", -"Z+ c #187187", -"`+ c #349CB2", -" @ c #2995AD", -".@ c #CBE5EB", -"+@ c #E3F0ED", -"@@ c #329276", -"#@ c #2A8D71", -"$@ c #2D8C6E", -"%@ c #2B896A", -"&@ c #2C8A6C", -"*@ c #329A7E", -"=@ c #339A7E", -"-@ c #32A68A", -";@ c #31B094", -">@ c #29AB8D", -",@ c #CDEBE5", -"'@ c #6894CB", -")@ c #005487", -"!@ c #015C6D", -"~@ c #015B72", -"{@ c #01586E", -"]@ c #04728B", -"^@ c #7DC1D0", -"/@ c #F9FCFC", -"(@ c #99C9BB", -"_@ c #0E7D5B", -":@ c #197F5E", -"<@ c #177E5D", -"[@ c #177D5C", -"}@ c #1A8463", -"|@ c #1E9778", -"1@ c #1CA687", -"2@ c #1FA788", -"3@ c #12A282", -"4@ c #49B89F", -"5@ c #FCFCFC", -"6@ c #DDE7F1", -"7@ c #79A9B8", -"8@ c #7EADB7", -"9@ c #7EACB7", -"0@ c #7DABB6", -"a@ c #7DAEBA", -"b@ c #E5F2F4", -"c@ c #F3F9F7", -"d@ c #91C3B3", -"e@ c #89BDAD", -"f@ c #8CBEAE", -"g@ c #8BBEAE", -"h@ c #8BBDAD", -"i@ c #8DCDBD", -"j@ c #8DD3C4", -"k@ c #8CD1C2", -"l@ c #8FD3C4", -"m@ c #86D0BF", -"n@ c #E2F4EF", -"o@ c #FCFCFB", -"p@ c #C5C5C4", -"q@ c #949493", -"r@ c #989897", -"s@ c #C4C4C4", -"t@ c #F8F9F9", -"u@ c #A5A5A5", -"v@ c #8E8E8D", -"w@ c #CBCBCB", -"x@ c #FAFCFC", -"y@ c #FAFCFB", -"z@ c #F0F1F0", -"A@ c #FBFEFD", -"B@ c #D2D2D2", -"C@ c #323230", -"D@ c #F0F0EF", -"E@ c #3A3A38", -"F@ c #CCCCCC", -"G@ c #A8A8A7", -"H@ c #ABABAB", -"I@ c #EEEEEE", -"J@ c #A3A3A3", -"K@ c #ACACAB", -"L@ c #C1C1C0", -"M@ c #898988", -"N@ c #E6E6E6", -"O@ c #A5A5A4", -"P@ c #F5F5F5", -"Q@ c #C0C0BF", -"R@ c #B6B6B5", -"S@ c #CACAC9", -"T@ c #FBFBFB", -"U@ c #C9C9C8", -"V@ c #A6A6A6", -"W@ c #BFBFBE", -"X@ c #D3D3D2", -"Y@ c #5D5D5C", -"Z@ c #E7E7E7", -"`@ c #5A5A58", -" # c #7D7D7C", -".# c #717170", -"+# c #969695", -"@# c #4B4B49", -"## c #434342", -"$# c #959594", -"%# c #2C2C2A", -"&# c #AAAAAA", -"*# c #B5B5B4", -"=# c #393938", -"-# c #646463", -";# c #8A8A89", -"># c #E2E2E1", -",# c #666664", -"'# c #DCDCDC", -")# c #8B8B8A", -"!# c #B7B7B7", -"~# c #9C9C9B", -"{# c #80807F", -"]# c #CDCDCD", -"^# c #979796", -"/# c #888887", -"(# c #010100", -"_# c #B7B7B6", -":# c #8D8D8C", -"<# c #3B3B39", -"[# c #939392", -"}# c #AFAFAE", -"|# c #444442", -"1# c #F3F3F3", -"2# c #474746", -"3# c #626261", -"4# c #585856", -"5# c #A1A1A0", -"6# c #A4A4A3", -"7# c #555553", -"8# c #E1E1E1", -"9# c #8C8C8B", -"0# c #EFEFEF", -"a# c #A4A4A4", -"b# c #A9A9A8", -"c# c #929291", -"d# c #E0E0E0", -"e# c #6F6F6D", -"f# c #ECECEC", -"g# c #F1F1F1", -"h# c #818180", -"i# c #DADADA", -"j# c #7E7E7D", -"k# c #9F9F9E", -"l# c #9C9C9C", -"m# c #8F8F8E", -"n# c #CACACA", -"o# c #BCBCBC", -"p# c #E5E5E5", -"q# c #6A6A69", -"r# c #7C7C7B", -"s# c #A7A7A6", -"t# c #D8D8D8", -"u# c #9A9A99", -"v# c #CDCDCC", -"w# c #A0A09F", -"x# c #F0F0F0", -"y# c #FFFFFE", -"z# c #FDFDFC", -"A# c #FEFEFD", -"B# c #F6F6F6", -" ", -" ", -" ", -" . ", -" . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" + @ @ @ @ @ . . . . . . . . . . . . . . . # # # # # $ $ $ $ $ . ", -" . . . . . . + . . . . . . . . . . . . . $ . . . . . . . . . . . ", -" . % & * = - ; + . . . . . . . . . . . . . > , ' ) ) ! ~ { ] { ^ / . ", -" @ . ( _ : < [ } | . @ . . . . . . . . . > . 1 2 3 4 4 3 5 6 7 8 9 0 . $ ", -" . a . b c d e f g . @ . . . . . . . . . . $ h i j 3 k l m n o p q . # . ", -" . . . . + r s t u v w . a . . . . . . . > . x y z A B C D E F 8 G > . . . . ", -" . . . H . I J K K L M N . + . . . . . + . O P Q R S T U V W l X Y . # . . . ", -" . . . . . a . Z ` ...+.@.. #.. . . . . a . $.%.&.*.=.-.;.>.,.'.).$ . . . . . . ", -" . . . . . @ . !.~.{.].^./.(.. _.. . . > . :.<.[.}.|.1.2.. $ . . . + . . . . . . ", -" . . . . . . . a . 3.4.5.6.7.8.. a . . . > . 9.0.a.b.c.d.. e.> > > # . . . . . . . . ", -" . . . . . . . . + . f.g.h.i.j.k.l.. @ . > . m.n.o.p.q.r.s.. . . . . . . . . . . . . . . ", -" . . . . . . . . . a . t.u.v.v.w.x.. + + . y.z.A.B.B.C.D.. E.. . . . . . . . . . . . . . ", -" . . . . . . . . . . . _.. F.G.H.I.J.K.. y.. L.M.N.O.P.Q.R.. > . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . > . S.T.U.V.W.X.Y.. Z.`. +.+++@+#+$+%+. > + + + + . . . . . . . . . . ", -" . . . . . . . . . . . . #.. &+*+=+-+;+>+. ,+'+)+!+~+{+]+^+/+. . . . . + + . . . . . . . . . ", -" . . . . . . . . . . . . _.. (+_+:+<+[+}+|+1+2+3+4+5+6+7+8+9+0+. a+b+b+c+$ . . . . . . . . . ", -" . . . . . . . . . . . . #.. d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s+t+u+v+w+x+y+. # . . . . . . ", -" . . . . . . . . . . . . . . z+A+B+C+D+E+F+G+H+I+. J+K+L+M+N+O+P+Q+R+S+T+. a . . . . . . ", -" . . . . . . . . . . . . #.. U+V+W+X+Y+Z+`+ @.@. +@@@#@$@%@&@*@=@-@;@>@,@. > . . . . ", -" . . . . . . . . . . . . > . '@)@!@~@{@]@^@. /@. (@_@:@<@[@}@|@1@2@3@4@> . + . . ", -" . . . . . . # 5@. c+# . # . 6@7@8@9@0@a@b@. c+. c@d@e@f@g@h@i@j@k@l@m@n@. # . . ", -" . . . . . . . # . . o@5@# 5@. . . . . . . . 5@5@. . . . . . . . . . . . . . ", -" . . . c+. p@q@. r@s@. c+. . _.# . + t@u@v@w@. c+> x@> $ . . y@z@+ A@+ . . . ", -" . . c+. B@C@D@E@F@G@H@I@J@K@L@M@N@G@O@. P@Q@R@S@T@U@w@V@W@X@Y@Z@. # . . ", -" . . . # . `@ #.#+#@###$#%#&#*#=#-#;#>#. c+,#'#)#!#~#{#]#^#G@/#T@. . . . ", -" . . T@. r@(#_#:#<#[#}#|#1#2#3#4#5#6#. I@ #. w@7#8#9#0#a#b#c#. c+. . ", -" . # . d#e#f#g#h#9#i#[#c+q@j#k#T@l#m#n#o#. p#q#. r#/#s#. +#t#. # ", -" . . . # . # . . . . . . . . . # . . . # . u#v#. w#x#. # . . . . ", -" . . # 5@y## 5@c+# z#. 5@5@z#. 5@# # A## B## . . # c+# c+. . ", -" . . . . . . . . . . . . . . . . . . . . # # . # . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . . . ", -" . . . . . . . . . . . . . . . . . . . . . . . . ", -" . ", -" ", -" ", -" "}; +/* XPM */ +static const char *VeraCryptIcon48x48[] = { +"48 48 435 2", +" c None", +". c #FFFFFF", +"+ c #FEFFFF", +"@ c #FDFEFF", +"# c #FEFEFE", +"$ c #FEFFFE", +"% c #EFF9FC", +"& c #CDEEF7", +"* c #D5F1F8", +"= c #D3F0F8", +"- c #D1EFF8", +"; c #DBF2F9", +"> c #FDFEFE", +", c #E7F5F1", +"' c #E4F3EF", +") c #E5F4EF", +"! c #E4F3EE", +"~ c #EAF6F2", +"{ c #EDF6F3", +"] c #ECF6F3", +"^ c #EAF5F1", +"/ c #F8FCFA", +"( c #EAF8FC", +"_ c #1CB1DB", +": c #01A8D7", +"< c #07ABD8", +"[ c #04AAD8", +"} c #0DA8D5", +"| c #CFEDF6", +"1 c #CFECE4", +"2 c #5ABA9D", +"3 c #6CBFA4", +"4 c #69BEA3", +"5 c #8ACAB3", +"6 c #96CFBA", +"7 c #95CEB9", +"8 c #93CEB8", +"9 c #9BD2BE", +"0 c #F4FAF8", +"a c #FCFEFE", +"b c #99DCEF", +"c c #00A5D5", +"d c #0BADD9", +"e c #0DABD8", +"f c #00A1D0", +"g c #4EBEDF", +"h c #73C6AE", +"i c #4AB696", +"j c #6ABFA4", +"k c #6ABEA3", +"l c #7EC5AD", +"m c #86C9B2", +"n c #92CDB8", +"o c #99D0BC", +"p c #8FCCB5", +"q c #D0EAE0", +"r c #3ABBE0", +"s c #00A8D7", +"t c #10A8D5", +"u c #12A7D3", +"v c #01A1D1", +"w c #AEE1F0", +"x c #B7E2D5", +"y c #46B494", +"z c #53BA9C", +"A c #5ABB9E", +"B c #6CBFA5", +"C c #74C2A9", +"D c #88C9B3", +"E c #85C8B1", +"F c #8BCBB5", +"G c #A8D7C6", +"H c #FCFEFF", +"I c #BCE8F5", +"J c #03A6D5", +"K c #0FA7D3", +"L c #05A3D2", +"M c #2FB3D9", +"N c #F6FCFD", +"O c #F1F9F7", +"P c #61BFA3", +"Q c #4FB899", +"R c #54B99C", +"S c #53B99B", +"T c #5FBC9F", +"U c #7CC4AB", +"V c #80C5AE", +"W c #7FC5AD", +"X c #88C9B2", +"Y c #E1F1EB", +"Z c #63BFE1", +"` c #0898CF", +" . c #1AA0D3", +".. c #1BA1D3", +"+. c #0697CE", +"@. c #91CBE7", +"#. c #FCFDFE", +"$. c #91D5C4", +"%. c #3BB392", +"&. c #4BB99C", +"*. c #4BB99B", +"=. c #3CB393", +"-. c #8DD2BF", +";. c #E8F4EF", +">. c #DBEFE8", +",. c #DDF0E9", +"'. c #DCEFE8", +"). c #E2F2EC", +"!. c #DDF0F8", +"~. c #209ED2", +"{. c #199AD1", +"]. c #1C9DD2", +"^. c #1C94CF", +"/. c #2C90CF", +"(. c #E3F1F9", +"_. c #FEFEFF", +":. c #D9F1EB", +"<. c #31B394", +"[. c #3EB697", +"}. c #46B89A", +"|. c #40B697", +"1. c #4FBB9F", +"2. c #EDF8F5", +"3. c #89CCE7", +"4. c #0995CE", +"5. c #1E9DD1", +"6. c #2690CE", +"7. c #1585CA", +"8. c #72B6DF", +"9. c #6CC7B1", +"0. c #26AD8D", +"a. c #38B495", +"b. c #47B799", +"c. c #37B291", +"d. c #ACDFD2", +"e. c #FAFDFD", +"f. c #F4FAFD", +"g. c #34A9D7", +"h. c #1891CE", +"i. c #268DCD", +"j. c #248ECD", +"k. c #1C8ACC", +"l. c #C8E3F3", +"m. c #BEEAE0", +"n. c #2AB493", +"o. c #37B999", +"p. c #34B899", +"q. c #36B797", +"r. c #67C5AC", +"s. c #FBFDFD", +"t. c #ADD9ED", +"u. c #1785C8", +"v. c #288CCC", +"w. c #1A85C9", +"x. c #54A3D6", +"y. c #F9FCFD", +"z. c #4DA991", +"A. c #26987A", +"B. c #2F9C7F", +"C. c #249779", +"D. c #BCE2D8", +"E. c #FCFEFD", +"F. c #5CA2D4", +"G. c #1D80C4", +"H. c #2B87C8", +"I. c #2C89C8", +"J. c #1575BC", +"K. c #A8C9E4", +"L. c #9DD8DE", +"M. c #177A73", +"N. c #236046", +"O. c #20654D", +"P. c #22614A", +"Q. c #196F54", +"R. c #7FC5B3", +"S. c #CEE4F2", +"T. c #2384C6", +"U. c #2987C8", +"V. c #2884C6", +"W. c #1A73BA", +"X. c #3684C2", +"Y. c #EFF6FA", +"Z. c #E6F4F5", +"`. c #37A9B2", +" + c #2AA2AA", +".+ c #246F5B", +"++ c #21664D", +"@+ c #226951", +"#+ c #2E997C", +"$+ c #289E7F", +"%+ c #CCE7E0", +"&+ c #7BB4DC", +"*+ c #1A7FC4", +"=+ c #267DC0", +"-+ c #2378BC", +";+ c #106DB7", +">+ c #83B4DA", +",+ c #79C4CB", +"'+ c #1E9DA6", +")+ c #31AAB5", +"!+ c #29908D", +"~+ c #215F45", +"{+ c #288469", +"]+ c #33A586", +"^+ c #24997A", +"/+ c #5EB59E", +"(+ c #E8F3FA", +"_+ c #3187C6", +":+ c #1C74BB", +"<+ c #2278BD", +"[+ c #1D75BB", +"}+ c #2C7CC0", +"|+ c #ABD5E3", +"1+ c #2FA6AD", +"2+ c #2CA3AD", +"3+ c #2DA4AD", +"4+ c #2EA5AF", +"5+ c #1E7B6A", +"6+ c #2E9A7B", +"7+ c #30A082", +"8+ c #32A083", +"9+ c #229979", +"0+ c #B1DBD0", +"a+ c #F9FCFB", +"b+ c #FCFDFD", +"c+ c #FDFDFD", +"d+ c #9BBBDC", +"e+ c #1960AD", +"f+ c #2D6EB4", +"g+ c #296CB3", +"h+ c #2768B1", +"i+ c #1A7798", +"j+ c #2F9DAF", +"k+ c #2F99AF", +"l+ c #309AAF", +"m+ c #2B98B0", +"n+ c #81C2C3", +"o+ c #329374", +"p+ c #298E72", +"q+ c #2C8F72", +"r+ c #298E71", +"s+ c #309174", +"t+ c #4DA78F", +"u+ c #4AA78E", +"v+ c #4BA88F", +"w+ c #49A58C", +"x+ c #4FB098", +"y+ c #E3F5F1", +"z+ c #FAFBFD", +"A+ c #4C80BD", +"B+ c #2263AD", +"C+ c #2E6AB5", +"D+ c #21689E", +"E+ c #0B6274", +"F+ c #278AA2", +"G+ c #349CB3", +"H+ c #2492AA", +"I+ c #5BADBF", +"J+ c #77B6A3", +"K+ c #1B8466", +"L+ c #2D8E72", +"M+ c #2A8C6F", +"N+ c #258565", +"O+ c #238D6E", +"P+ c #28987A", +"Q+ c #279577", +"R+ c #2A987B", +"S+ c #17A282", +"T+ c #77CAB8", +"U+ c #BCD0E6", +"V+ c #2062AE", +"W+ c #2F6DB2", +"X+ c #156983", +"Y+ c #0F6578", +"Z+ c #187187", +"`+ c #349CB2", +" @ c #2995AD", +".@ c #CBE5EB", +"+@ c #E3F0ED", +"@@ c #329276", +"#@ c #2A8D71", +"$@ c #2D8C6E", +"%@ c #2B896A", +"&@ c #2C8A6C", +"*@ c #329A7E", +"=@ c #339A7E", +"-@ c #32A68A", +";@ c #31B094", +">@ c #29AB8D", +",@ c #CDEBE5", +"'@ c #6894CB", +")@ c #005487", +"!@ c #015C6D", +"~@ c #015B72", +"{@ c #01586E", +"]@ c #04728B", +"^@ c #7DC1D0", +"/@ c #F9FCFC", +"(@ c #99C9BB", +"_@ c #0E7D5B", +":@ c #197F5E", +"<@ c #177E5D", +"[@ c #177D5C", +"}@ c #1A8463", +"|@ c #1E9778", +"1@ c #1CA687", +"2@ c #1FA788", +"3@ c #12A282", +"4@ c #49B89F", +"5@ c #FCFCFC", +"6@ c #DDE7F1", +"7@ c #79A9B8", +"8@ c #7EADB7", +"9@ c #7EACB7", +"0@ c #7DABB6", +"a@ c #7DAEBA", +"b@ c #E5F2F4", +"c@ c #F3F9F7", +"d@ c #91C3B3", +"e@ c #89BDAD", +"f@ c #8CBEAE", +"g@ c #8BBEAE", +"h@ c #8BBDAD", +"i@ c #8DCDBD", +"j@ c #8DD3C4", +"k@ c #8CD1C2", +"l@ c #8FD3C4", +"m@ c #86D0BF", +"n@ c #E2F4EF", +"o@ c #FCFCFB", +"p@ c #C5C5C4", +"q@ c #949493", +"r@ c #989897", +"s@ c #C4C4C4", +"t@ c #F8F9F9", +"u@ c #A5A5A5", +"v@ c #8E8E8D", +"w@ c #CBCBCB", +"x@ c #FAFCFC", +"y@ c #FAFCFB", +"z@ c #F0F1F0", +"A@ c #FBFEFD", +"B@ c #D2D2D2", +"C@ c #323230", +"D@ c #F0F0EF", +"E@ c #3A3A38", +"F@ c #CCCCCC", +"G@ c #A8A8A7", +"H@ c #ABABAB", +"I@ c #EEEEEE", +"J@ c #A3A3A3", +"K@ c #ACACAB", +"L@ c #C1C1C0", +"M@ c #898988", +"N@ c #E6E6E6", +"O@ c #A5A5A4", +"P@ c #F5F5F5", +"Q@ c #C0C0BF", +"R@ c #B6B6B5", +"S@ c #CACAC9", +"T@ c #FBFBFB", +"U@ c #C9C9C8", +"V@ c #A6A6A6", +"W@ c #BFBFBE", +"X@ c #D3D3D2", +"Y@ c #5D5D5C", +"Z@ c #E7E7E7", +"`@ c #5A5A58", +" # c #7D7D7C", +".# c #717170", +"+# c #969695", +"@# c #4B4B49", +"## c #434342", +"$# c #959594", +"%# c #2C2C2A", +"&# c #AAAAAA", +"*# c #B5B5B4", +"=# c #393938", +"-# c #646463", +";# c #8A8A89", +"># c #E2E2E1", +",# c #666664", +"'# c #DCDCDC", +")# c #8B8B8A", +"!# c #B7B7B7", +"~# c #9C9C9B", +"{# c #80807F", +"]# c #CDCDCD", +"^# c #979796", +"/# c #888887", +"(# c #010100", +"_# c #B7B7B6", +":# c #8D8D8C", +"<# c #3B3B39", +"[# c #939392", +"}# c #AFAFAE", +"|# c #444442", +"1# c #F3F3F3", +"2# c #474746", +"3# c #626261", +"4# c #585856", +"5# c #A1A1A0", +"6# c #A4A4A3", +"7# c #555553", +"8# c #E1E1E1", +"9# c #8C8C8B", +"0# c #EFEFEF", +"a# c #A4A4A4", +"b# c #A9A9A8", +"c# c #929291", +"d# c #E0E0E0", +"e# c #6F6F6D", +"f# c #ECECEC", +"g# c #F1F1F1", +"h# c #818180", +"i# c #DADADA", +"j# c #7E7E7D", +"k# c #9F9F9E", +"l# c #9C9C9C", +"m# c #8F8F8E", +"n# c #CACACA", +"o# c #BCBCBC", +"p# c #E5E5E5", +"q# c #6A6A69", +"r# c #7C7C7B", +"s# c #A7A7A6", +"t# c #D8D8D8", +"u# c #9A9A99", +"v# c #CDCDCC", +"w# c #A0A09F", +"x# c #F0F0F0", +"y# c #FFFFFE", +"z# c #FDFDFC", +"A# c #FEFEFD", +"B# c #F6F6F6", +" ", +" ", +" ", +" . ", +" . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" + @ @ @ @ @ . . . . . . . . . . . . . . . # # # # # $ $ $ $ $ . ", +" . . . . . . + . . . . . . . . . . . . . $ . . . . . . . . . . . ", +" . % & * = - ; + . . . . . . . . . . . . . > , ' ) ) ! ~ { ] { ^ / . ", +" @ . ( _ : < [ } | . @ . . . . . . . . . > . 1 2 3 4 4 3 5 6 7 8 9 0 . $ ", +" . a . b c d e f g . @ . . . . . . . . . . $ h i j 3 k l m n o p q . # . ", +" . . . . + r s t u v w . a . . . . . . . > . x y z A B C D E F 8 G > . . . . ", +" . . . H . I J K K L M N . + . . . . . + . O P Q R S T U V W l X Y . # . . . ", +" . . . . . a . Z ` ...+.@.. #.. . . . . a . $.%.&.*.=.-.;.>.,.'.).$ . . . . . . ", +" . . . . . @ . !.~.{.].^./.(.. _.. . . > . :.<.[.}.|.1.2.. $ . . . + . . . . . . ", +" . . . . . . . a . 3.4.5.6.7.8.. a . . . > . 9.0.a.b.c.d.. e.> > > # . . . . . . . . ", +" . . . . . . . . + . f.g.h.i.j.k.l.. @ . > . m.n.o.p.q.r.s.. . . . . . . . . . . . . . . ", +" . . . . . . . . . a . t.u.v.v.w.x.. + + . y.z.A.B.B.C.D.. E.. . . . . . . . . . . . . . ", +" . . . . . . . . . . . _.. F.G.H.I.J.K.. y.. L.M.N.O.P.Q.R.. > . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . > . S.T.U.V.W.X.Y.. Z.`. +.+++@+#+$+%+. > + + + + . . . . . . . . . . ", +" . . . . . . . . . . . . #.. &+*+=+-+;+>+. ,+'+)+!+~+{+]+^+/+. . . . . + + . . . . . . . . . ", +" . . . . . . . . . . . . _.. (+_+:+<+[+}+|+1+2+3+4+5+6+7+8+9+0+. a+b+b+c+$ . . . . . . . . . ", +" . . . . . . . . . . . . #.. d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s+t+u+v+w+x+y+. # . . . . . . ", +" . . . . . . . . . . . . . . z+A+B+C+D+E+F+G+H+I+. J+K+L+M+N+O+P+Q+R+S+T+. a . . . . . . ", +" . . . . . . . . . . . . #.. U+V+W+X+Y+Z+`+ @.@. +@@@#@$@%@&@*@=@-@;@>@,@. > . . . . ", +" . . . . . . . . . . . . > . '@)@!@~@{@]@^@. /@. (@_@:@<@[@}@|@1@2@3@4@> . + . . ", +" . . . . . . # 5@. c+# . # . 6@7@8@9@0@a@b@. c+. c@d@e@f@g@h@i@j@k@l@m@n@. # . . ", +" . . . . . . . # . . o@5@# 5@. . . . . . . . 5@5@. . . . . . . . . . . . . . ", +" . . . c+. p@q@. r@s@. c+. . _.# . + t@u@v@w@. c+> x@> $ . . y@z@+ A@+ . . . ", +" . . c+. B@C@D@E@F@G@H@I@J@K@L@M@N@G@O@. P@Q@R@S@T@U@w@V@W@X@Y@Z@. # . . ", +" . . . # . `@ #.#+#@###$#%#&#*#=#-#;#>#. c+,#'#)#!#~#{#]#^#G@/#T@. . . . ", +" . . T@. r@(#_#:#<#[#}#|#1#2#3#4#5#6#. I@ #. w@7#8#9#0#a#b#c#. c+. . ", +" . # . d#e#f#g#h#9#i#[#c+q@j#k#T@l#m#n#o#. p#q#. r#/#s#. +#t#. # ", +" . . . # . # . . . . . . . . . # . . . # . u#v#. w#x#. # . . . . ", +" . . # 5@y## 5@c+# z#. 5@5@z#. 5@# # A## B## . . # c+# c+. . ", +" . . . . . . . . . . . . . . . . . . . . # # . # . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" . . . . . . . . . . . . . . . . . . . . . . . . ", +" . ", +" ", +" ", +" "}; diff --git a/src/Setup/ComSetup.cpp b/src/Setup/ComSetup.cpp index 5e45f8e3..24e5262f 100644 --- a/src/Setup/ComSetup.cpp +++ b/src/Setup/ComSetup.cpp @@ -1,103 +1,103 @@ -/* - 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. -*/ - -#define TC_MAIN_COM_VERSION_MAJOR 2 -#define TC_MAIN_COM_VERSION_MINOR 7 - -#define TC_FORMAT_COM_VERSION_MAJOR 2 -#define TC_FORMAT_COM_VERSION_MINOR 5 - -#include -#include -#include -#include -#include "ComSetup.h" -#include "Dlgcode.h" -#include "Resource.h" -#include "../Mount/MainCom_i.c" -#include "../Format/FormatCom_i.c" - - -extern "C" BOOL RegisterComServers (wchar_t *modulePath) -{ - BOOL ret = TRUE; - wchar_t mainModule[1024], formatModule[1024]; - CComPtr tl, tl2; - - wsprintfW (mainModule, L"%sVeraCrypt.exe", modulePath); - wsprintfW (formatModule, L"%sVeraCrypt Format.exe", modulePath); - - UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR, 0, SYS_WIN32); - UnRegisterTypeLib (LIBID_TrueCryptFormatCom, TC_FORMAT_COM_VERSION_MAJOR, TC_FORMAT_COM_VERSION_MINOR, 0, SYS_WIN32); - // unregister older versions that may still exist - UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR-3, 0, SYS_WIN32); - UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR-2, 0, SYS_WIN32); - UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR-1, 0, SYS_WIN32); - UnRegisterTypeLib (LIBID_TrueCryptFormatCom, TC_FORMAT_COM_VERSION_MAJOR, TC_FORMAT_COM_VERSION_MINOR-1, 0, SYS_WIN32); - - wchar_t setupModule[MAX_PATH]; - GetModuleFileNameW (NULL, setupModule, sizeof (setupModule) / sizeof (setupModule[0])); - - CRegObject ro; - HRESULT r; - - if (!SUCCEEDED (r = ro.FinalConstruct ()) - || !SUCCEEDED (r = ro.AddReplacement (L"MAIN_MODULE", mainModule)) - || !SUCCEEDED (r = ro.AddReplacement (L"FORMAT_MODULE", formatModule)) - || !SUCCEEDED (r = ro.ResourceRegister (setupModule, IDR_COMREG, L"REGISTRY")) - || !SUCCEEDED (r = LoadTypeLib (mainModule, &tl)) - || !SUCCEEDED (r = RegisterTypeLib (tl, mainModule, 0)) - || !SUCCEEDED (r = LoadTypeLib (formatModule, &tl2)) - || !SUCCEEDED (r = RegisterTypeLib (tl2, formatModule, 0))) - { - MessageBox (MainDlg, _com_error (r).ErrorMessage(), _T(TC_APP_NAME), MB_ICONERROR); - ret = FALSE; - } - - ro.FinalRelease (); - return ret; -} - - -extern "C" BOOL UnregisterComServers (wchar_t *modulePath) -{ - BOOL ret; - - if (UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR, 0, SYS_WIN32) != S_OK) - return FALSE; - if (UnRegisterTypeLib (LIBID_TrueCryptFormatCom, TC_FORMAT_COM_VERSION_MAJOR, TC_FORMAT_COM_VERSION_MINOR, 0, SYS_WIN32) != S_OK) - return FALSE; - - // unregister older versions that may still exist - UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR-3, 0, SYS_WIN32); - UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR-2, 0, SYS_WIN32); - UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR-1, 0, SYS_WIN32); - UnRegisterTypeLib (LIBID_TrueCryptFormatCom, TC_FORMAT_COM_VERSION_MAJOR, TC_FORMAT_COM_VERSION_MINOR-1, 0, SYS_WIN32); - - wchar_t module[1024]; - CRegObject ro; - ro.FinalConstruct (); - - wsprintfW (module, L"%sVeraCrypt.exe", modulePath); - ro.AddReplacement (L"MAIN_MODULE", module); - - wsprintfW (module, L"%sVeraCrypt Format.exe", modulePath); - ro.AddReplacement (L"FORMAT_MODULE", module); - - wchar_t setupModule[MAX_PATH]; - GetModuleFileNameW (NULL, setupModule, sizeof (setupModule) / sizeof (setupModule[0])); - - ret = ro.ResourceUnregister (setupModule, IDR_COMREG, L"REGISTRY") == S_OK; - - ro.FinalRelease (); - return ret; -} +/* + 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. +*/ + +#define TC_MAIN_COM_VERSION_MAJOR 2 +#define TC_MAIN_COM_VERSION_MINOR 7 + +#define TC_FORMAT_COM_VERSION_MAJOR 2 +#define TC_FORMAT_COM_VERSION_MINOR 5 + +#include +#include +#include +#include +#include "ComSetup.h" +#include "Dlgcode.h" +#include "Resource.h" +#include "../Mount/MainCom_i.c" +#include "../Format/FormatCom_i.c" + + +extern "C" BOOL RegisterComServers (wchar_t *modulePath) +{ + BOOL ret = TRUE; + wchar_t mainModule[1024], formatModule[1024]; + CComPtr tl, tl2; + + wsprintfW (mainModule, L"%sVeraCrypt.exe", modulePath); + wsprintfW (formatModule, L"%sVeraCrypt Format.exe", modulePath); + + UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR, 0, SYS_WIN32); + UnRegisterTypeLib (LIBID_TrueCryptFormatCom, TC_FORMAT_COM_VERSION_MAJOR, TC_FORMAT_COM_VERSION_MINOR, 0, SYS_WIN32); + // unregister older versions that may still exist + UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR-3, 0, SYS_WIN32); + UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR-2, 0, SYS_WIN32); + UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR-1, 0, SYS_WIN32); + UnRegisterTypeLib (LIBID_TrueCryptFormatCom, TC_FORMAT_COM_VERSION_MAJOR, TC_FORMAT_COM_VERSION_MINOR-1, 0, SYS_WIN32); + + wchar_t setupModule[MAX_PATH]; + GetModuleFileNameW (NULL, setupModule, sizeof (setupModule) / sizeof (setupModule[0])); + + CRegObject ro; + HRESULT r; + + if (!SUCCEEDED (r = ro.FinalConstruct ()) + || !SUCCEEDED (r = ro.AddReplacement (L"MAIN_MODULE", mainModule)) + || !SUCCEEDED (r = ro.AddReplacement (L"FORMAT_MODULE", formatModule)) + || !SUCCEEDED (r = ro.ResourceRegister (setupModule, IDR_COMREG, L"REGISTRY")) + || !SUCCEEDED (r = LoadTypeLib (mainModule, &tl)) + || !SUCCEEDED (r = RegisterTypeLib (tl, mainModule, 0)) + || !SUCCEEDED (r = LoadTypeLib (formatModule, &tl2)) + || !SUCCEEDED (r = RegisterTypeLib (tl2, formatModule, 0))) + { + MessageBox (MainDlg, _com_error (r).ErrorMessage(), _T(TC_APP_NAME), MB_ICONERROR); + ret = FALSE; + } + + ro.FinalRelease (); + return ret; +} + + +extern "C" BOOL UnregisterComServers (wchar_t *modulePath) +{ + BOOL ret; + + if (UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR, 0, SYS_WIN32) != S_OK) + return FALSE; + if (UnRegisterTypeLib (LIBID_TrueCryptFormatCom, TC_FORMAT_COM_VERSION_MAJOR, TC_FORMAT_COM_VERSION_MINOR, 0, SYS_WIN32) != S_OK) + return FALSE; + + // unregister older versions that may still exist + UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR-3, 0, SYS_WIN32); + UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR-2, 0, SYS_WIN32); + UnRegisterTypeLib (LIBID_TrueCryptMainCom, TC_MAIN_COM_VERSION_MAJOR, TC_MAIN_COM_VERSION_MINOR-1, 0, SYS_WIN32); + UnRegisterTypeLib (LIBID_TrueCryptFormatCom, TC_FORMAT_COM_VERSION_MAJOR, TC_FORMAT_COM_VERSION_MINOR-1, 0, SYS_WIN32); + + wchar_t module[1024]; + CRegObject ro; + ro.FinalConstruct (); + + wsprintfW (module, L"%sVeraCrypt.exe", modulePath); + ro.AddReplacement (L"MAIN_MODULE", module); + + wsprintfW (module, L"%sVeraCrypt Format.exe", modulePath); + ro.AddReplacement (L"FORMAT_MODULE", module); + + wchar_t setupModule[MAX_PATH]; + GetModuleFileNameW (NULL, setupModule, sizeof (setupModule) / sizeof (setupModule[0])); + + ret = ro.ResourceUnregister (setupModule, IDR_COMREG, L"REGISTRY") == S_OK; + + ro.FinalRelease (); + return ret; +} diff --git a/src/Setup/ComSetup.h b/src/Setup/ComSetup.h index 0e3bbd5f..56e30139 100644 --- a/src/Setup/ComSetup.h +++ b/src/Setup/ComSetup.h @@ -8,15 +8,15 @@ 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. -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -BOOL RegisterComServers (wchar_t *modulePath); -BOOL UnregisterComServers (wchar_t *modulePath); - -#ifdef __cplusplus -} -#endif +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +BOOL RegisterComServers (wchar_t *modulePath); +BOOL UnregisterComServers (wchar_t *modulePath); + +#ifdef __cplusplus +} +#endif diff --git a/src/Setup/ComSetup.rgs b/src/Setup/ComSetup.rgs index 19ee8be7..ed927913 100644 --- a/src/Setup/ComSetup.rgs +++ b/src/Setup/ComSetup.rgs @@ -1,92 +1,92 @@ -HKCR -{ - ForceRemove VeraCrypt.1 = s 'VeraCrypt class' - { - CLSID = s '{FE8B3B95-C80C-41f7-830F-FBA271C26F7E}' - } - - ForceRemove VeraCrypt = s 'VeraCrypt class' - { - CLSID = s '{FE8B3B95-C80C-41f7-830F-FBA271C26F7E}' - CurVer = s 'VeraCrypt.1' - } - - NoRemove CLSID - { - ForceRemove {FE8B3B95-C80C-41f7-830F-FBA271C26F7E} = s 'VeraCrypt class' - { - ProgID = s 'VeraCrypt.1' - VersionIndependentProgID = s 'VeraCrypt' - LocalServer32 = s '"%MAIN_MODULE%"' - - TypeLib = s '{9ACF6176-5FC4-4690-A025-B3306A50EB6A}' - - Elevation - { - val Enabled = d 1 - val IconReference = s '@%MAIN_MODULE%,-501' - } - - val AppId = s '{FE8B3B95-C80C-41f7-830F-FBA271C26F7E}' - val LocalizedString = s '@%MAIN_MODULE%,-110' - } - } - - NoRemove AppId - { - ForceRemove {FE8B3B95-C80C-41f7-830F-FBA271C26F7E} = s 'VeraCrypt class' - { - val AccessPermission = b 010004803000000040000000000000001400000002001c000100000000001400070000000101000000000005040000000102000000000005200000002002000001020000000000052000000020020000 - } - - ForceRemove VeraCrypt.exe - { - val AppId = s '{FE8B3B95-C80C-41f7-830F-FBA271C26F7E}' - } - } - - ForceRemove VeraCryptFormat.1 = s 'VeraCryptFormat class' - { - CLSID = s '{A96D3797-9F31-49f4-A0CE-9657392CF789}' - } - - ForceRemove VeraCryptFormat = s 'VeraCryptFormat class' - { - CLSID = s '{A96D3797-9F31-49f4-A0CE-9657392CF789}' - CurVer = s 'VeraCryptFormat.1' - } - - NoRemove CLSID - { - ForceRemove {A96D3797-9F31-49f4-A0CE-9657392CF789} = s 'VeraCryptFormat class' - { - ProgID = s 'VeraCryptFormat.1' - VersionIndependentProgID = s 'VeraCryptFormat' - LocalServer32 = s '"%FORMAT_MODULE%"' - - TypeLib = s '{56327DDA-F1A7-4e13-B128-520D129BDEF6}' - - Elevation - { - val Enabled = d 1 - val IconReference = s '@%FORMAT_MODULE%,-501' - } - - val AppId = s '{A96D3797-9F31-49f4-A0CE-9657392CF789}' - val LocalizedString = s '@%FORMAT_MODULE%,-112' - } - } - - NoRemove AppId - { - ForceRemove {A96D3797-9F31-49f4-A0CE-9657392CF789} = s 'VeraCryptFormat class' - { - val AccessPermission = b 010004803000000040000000000000001400000002001c000100000000001400070000000101000000000005040000000102000000000005200000002002000001020000000000052000000020020000 - } - - ForceRemove 'VeraCrypt Format.exe' - { - val AppId = s '{A96D3797-9F31-49f4-A0CE-9657392CF789}' - } - } +HKCR +{ + ForceRemove VeraCrypt.1 = s 'VeraCrypt class' + { + CLSID = s '{FE8B3B95-C80C-41f7-830F-FBA271C26F7E}' + } + + ForceRemove VeraCrypt = s 'VeraCrypt class' + { + CLSID = s '{FE8B3B95-C80C-41f7-830F-FBA271C26F7E}' + CurVer = s 'VeraCrypt.1' + } + + NoRemove CLSID + { + ForceRemove {FE8B3B95-C80C-41f7-830F-FBA271C26F7E} = s 'VeraCrypt class' + { + ProgID = s 'VeraCrypt.1' + VersionIndependentProgID = s 'VeraCrypt' + LocalServer32 = s '"%MAIN_MODULE%"' + + TypeLib = s '{9ACF6176-5FC4-4690-A025-B3306A50EB6A}' + + Elevation + { + val Enabled = d 1 + val IconReference = s '@%MAIN_MODULE%,-501' + } + + val AppId = s '{FE8B3B95-C80C-41f7-830F-FBA271C26F7E}' + val LocalizedString = s '@%MAIN_MODULE%,-110' + } + } + + NoRemove AppId + { + ForceRemove {FE8B3B95-C80C-41f7-830F-FBA271C26F7E} = s 'VeraCrypt class' + { + val AccessPermission = b 010004803000000040000000000000001400000002001c000100000000001400070000000101000000000005040000000102000000000005200000002002000001020000000000052000000020020000 + } + + ForceRemove VeraCrypt.exe + { + val AppId = s '{FE8B3B95-C80C-41f7-830F-FBA271C26F7E}' + } + } + + ForceRemove VeraCryptFormat.1 = s 'VeraCryptFormat class' + { + CLSID = s '{A96D3797-9F31-49f4-A0CE-9657392CF789}' + } + + ForceRemove VeraCryptFormat = s 'VeraCryptFormat class' + { + CLSID = s '{A96D3797-9F31-49f4-A0CE-9657392CF789}' + CurVer = s 'VeraCryptFormat.1' + } + + NoRemove CLSID + { + ForceRemove {A96D3797-9F31-49f4-A0CE-9657392CF789} = s 'VeraCryptFormat class' + { + ProgID = s 'VeraCryptFormat.1' + VersionIndependentProgID = s 'VeraCryptFormat' + LocalServer32 = s '"%FORMAT_MODULE%"' + + TypeLib = s '{56327DDA-F1A7-4e13-B128-520D129BDEF6}' + + Elevation + { + val Enabled = d 1 + val IconReference = s '@%FORMAT_MODULE%,-501' + } + + val AppId = s '{A96D3797-9F31-49f4-A0CE-9657392CF789}' + val LocalizedString = s '@%FORMAT_MODULE%,-112' + } + } + + NoRemove AppId + { + ForceRemove {A96D3797-9F31-49f4-A0CE-9657392CF789} = s 'VeraCryptFormat class' + { + val AccessPermission = b 010004803000000040000000000000001400000002001c000100000000001400070000000101000000000005040000000102000000000005200000002002000001020000000000052000000020020000 + } + + ForceRemove 'VeraCrypt Format.exe' + { + val AppId = s '{A96D3797-9F31-49f4-A0CE-9657392CF789}' + } + } } \ No newline at end of file diff --git a/src/Setup/Dir.c b/src/Setup/Dir.c index c4bab5d6..342ff748 100644 --- a/src/Setup/Dir.c +++ b/src/Setup/Dir.c @@ -1,110 +1,110 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "Dir.h" - -/* create full directory tree. returns 0 for success, -1 if failure */ -int -mkfulldir (wchar_t *oriPath, BOOL bCheckonly) -{ - struct _stat st; - wchar_t *uniq_file; - wchar_t path [TC_MAX_PATH]; - - StringCbCopyW (path, TC_MAX_PATH, oriPath); - - if (wcslen (path) == 3 && path[1] == L':') - goto is_root; /* keep final slash in root if present */ - - /* strip final forward or backslash if we have one! */ - uniq_file = wcsrchr (path, L'\\'); - if (uniq_file && uniq_file[1] == L'\0') - uniq_file[0] = L'\0'; - else - { - uniq_file = wcsrchr (path, L'/'); - if (uniq_file && uniq_file[1] == L'\0') - uniq_file[0] = L'\0'; - } - - is_root: - if (bCheckonly) - return _wstat (path, &st); - - if (_wstat (path, &st)) - return mkfulldir_internal (path); - else - return 0; -} - - -int -mkfulldir_internal (wchar_t *path) -{ - wchar_t *token; - struct _stat st; - static wchar_t tokpath[_MAX_PATH]; - static wchar_t trail[_MAX_PATH]; - - StringCbCopyW (tokpath, _MAX_PATH, path); - trail[0] = L'\0'; - - token = wcstok (tokpath, L"\\/"); - - if (tokpath[0] == L'\\' && tokpath[1] == L'\\') - { /* unc */ - trail[0] = tokpath[0]; - trail[1] = tokpath[1]; - trail[2] = L'\0'; - if (token) - { - StringCbCatW (trail, _MAX_PATH, token); - StringCbCatW (trail, _MAX_PATH, L"\\"); - token = wcstok (NULL, L"\\/"); - if (token) - { /* get share name */ - StringCbCatW (trail, _MAX_PATH, token); - StringCbCatW (trail, _MAX_PATH, L"\\"); - } - token = wcstok (NULL, L"\\/"); - } - } - - if (tokpath[1] == L':') - { /* drive letter */ - StringCbCatW (trail, _MAX_PATH, tokpath); - StringCbCatW (trail, _MAX_PATH, L"\\"); - token = wcstok (NULL, L"\\/"); - } - - while (token != NULL) - { - int x; - StringCbCatW (trail, _MAX_PATH, token); - x = _wmkdir (trail); - StringCbCatW (trail, _MAX_PATH, L"\\"); - token = wcstok (NULL, L"\\/"); - } - - return _wstat (path, &st); -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "Dir.h" + +/* create full directory tree. returns 0 for success, -1 if failure */ +int +mkfulldir (wchar_t *oriPath, BOOL bCheckonly) +{ + struct _stat st; + wchar_t *uniq_file; + wchar_t path [TC_MAX_PATH]; + + StringCbCopyW (path, TC_MAX_PATH, oriPath); + + if (wcslen (path) == 3 && path[1] == L':') + goto is_root; /* keep final slash in root if present */ + + /* strip final forward or backslash if we have one! */ + uniq_file = wcsrchr (path, L'\\'); + if (uniq_file && uniq_file[1] == L'\0') + uniq_file[0] = L'\0'; + else + { + uniq_file = wcsrchr (path, L'/'); + if (uniq_file && uniq_file[1] == L'\0') + uniq_file[0] = L'\0'; + } + + is_root: + if (bCheckonly) + return _wstat (path, &st); + + if (_wstat (path, &st)) + return mkfulldir_internal (path); + else + return 0; +} + + +int +mkfulldir_internal (wchar_t *path) +{ + wchar_t *token; + struct _stat st; + static wchar_t tokpath[_MAX_PATH]; + static wchar_t trail[_MAX_PATH]; + + StringCbCopyW (tokpath, _MAX_PATH, path); + trail[0] = L'\0'; + + token = wcstok (tokpath, L"\\/"); + + if (tokpath[0] == L'\\' && tokpath[1] == L'\\') + { /* unc */ + trail[0] = tokpath[0]; + trail[1] = tokpath[1]; + trail[2] = L'\0'; + if (token) + { + StringCbCatW (trail, _MAX_PATH, token); + StringCbCatW (trail, _MAX_PATH, L"\\"); + token = wcstok (NULL, L"\\/"); + if (token) + { /* get share name */ + StringCbCatW (trail, _MAX_PATH, token); + StringCbCatW (trail, _MAX_PATH, L"\\"); + } + token = wcstok (NULL, L"\\/"); + } + } + + if (tokpath[1] == L':') + { /* drive letter */ + StringCbCatW (trail, _MAX_PATH, tokpath); + StringCbCatW (trail, _MAX_PATH, L"\\"); + token = wcstok (NULL, L"\\/"); + } + + while (token != NULL) + { + int x; + StringCbCatW (trail, _MAX_PATH, token); + x = _wmkdir (trail); + StringCbCatW (trail, _MAX_PATH, L"\\"); + token = wcstok (NULL, L"\\/"); + } + + return _wstat (path, &st); +} diff --git a/src/Setup/Dir.h b/src/Setup/Dir.h index 42707a38..2126bb42 100644 --- a/src/Setup/Dir.h +++ b/src/Setup/Dir.h @@ -1,23 +1,23 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifdef __cplusplus -extern "C" { -#endif - -int mkfulldir ( wchar_t *path , BOOL bCheckonly ); -int mkfulldir_internal ( wchar_t *path ); - -#ifdef __cplusplus -} -#endif +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifdef __cplusplus +extern "C" { +#endif + +int mkfulldir ( wchar_t *path , BOOL bCheckonly ); +int mkfulldir_internal ( wchar_t *path ); + +#ifdef __cplusplus +} +#endif diff --git a/src/Setup/Resource.h b/src/Setup/Resource.h index 2baaefe0..bbbd4766 100644 --- a/src/Setup/Resource.h +++ b/src/Setup/Resource.h @@ -1,64 +1,64 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by Setup.rc -// -#define IDR_COMREG 10 -#define IDD_INSTALL 101 -#define IDD_INSTALL_OPTIONS_PAGE_DLG 102 -#define IDD_UNINSTALL 103 -#define IDI_SETUP 104 -#define IDR_SETUP_RSRC_HEADER 105 -#define IDD_EXTRACTION_OPTIONS_PAGE_DLG 106 -#define IDB_SETUP_WIZARD 107 -#define IDD_INTRO_PAGE_DLG 108 -#define IDB_SETUP_WIZARD_BKG 109 -#define IDD_INFO_PAGE_DLG 110 -#define IDD_INSTL_DLG 111 -#define IDD_WIZARD_MODE_PAGE_DLG 112 -#define IDD_PROGRESS_PAGE_DLG 113 -#define IDD_DONATIONS_PAGE_DLG 114 -#define IDC_DESTINATION 1000 -#define IDC_BOX_TITLE 1001 -#define IDC_BROWSE 1002 -#define IDC_BOX_INFO 1003 -#define IDC_LICENSE 1004 -#define IDC_BOX_HELP 1005 -#define IDC_LICENSE_TEXT 1006 -#define IDC_BOX_HELP2 1007 -#define IDC_FILE_TYPE 1008 -#define IDT_UNINSTALL_DIR 1009 -#define IDC_PROG_GROUP 1010 -#define IDC_SYSTEM_RESTORE 1011 -#define IDC_DESKTOP_ICON 1012 -#define IDC_ALL_USERS 1013 -#define IDT_INSTALL_DESTINATION 1014 -#define IDC_UNINSTALL 1015 -#define IDC_PROGRESS_BAR 1016 -#define IDC_LOG_WINDOW 1017 -#define IDC_SETUP_WIZARD_BKG 1018 -#define IDC_SETUP_WIZARD_GFX_AREA 1019 -#define IDC_HR 1020 -#define IDC_OPEN_CONTAINING_FOLDER 1021 -#define IDC_AGREE 1022 -#define IDC_HR_BOTTOM 1023 -#define IDC_WIZARD_MODE_INSTALL 1024 -#define IDC_WIZARD_MODE_EXTRACT_ONLY 1025 -#define IDC_NEXT 1026 -#define IDC_PREV 1027 -#define IDT_EXTRACT_DESTINATION 1028 -#define IDC_POS_BOX 1029 -#define IDC_BITMAP_SETUP_WIZARD 1030 -#define IDC_MAIN_CONTENT_CANVAS 1031 -#define IDC_DONATE 1032 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NO_MFC 1 -#define _APS_NEXT_RESOURCE_VALUE 115 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1033 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Setup.rc +// +#define IDR_COMREG 10 +#define IDD_INSTALL 101 +#define IDD_INSTALL_OPTIONS_PAGE_DLG 102 +#define IDD_UNINSTALL 103 +#define IDI_SETUP 104 +#define IDR_SETUP_RSRC_HEADER 105 +#define IDD_EXTRACTION_OPTIONS_PAGE_DLG 106 +#define IDB_SETUP_WIZARD 107 +#define IDD_INTRO_PAGE_DLG 108 +#define IDB_SETUP_WIZARD_BKG 109 +#define IDD_INFO_PAGE_DLG 110 +#define IDD_INSTL_DLG 111 +#define IDD_WIZARD_MODE_PAGE_DLG 112 +#define IDD_PROGRESS_PAGE_DLG 113 +#define IDD_DONATIONS_PAGE_DLG 114 +#define IDC_DESTINATION 1000 +#define IDC_BOX_TITLE 1001 +#define IDC_BROWSE 1002 +#define IDC_BOX_INFO 1003 +#define IDC_LICENSE 1004 +#define IDC_BOX_HELP 1005 +#define IDC_LICENSE_TEXT 1006 +#define IDC_BOX_HELP2 1007 +#define IDC_FILE_TYPE 1008 +#define IDT_UNINSTALL_DIR 1009 +#define IDC_PROG_GROUP 1010 +#define IDC_SYSTEM_RESTORE 1011 +#define IDC_DESKTOP_ICON 1012 +#define IDC_ALL_USERS 1013 +#define IDT_INSTALL_DESTINATION 1014 +#define IDC_UNINSTALL 1015 +#define IDC_PROGRESS_BAR 1016 +#define IDC_LOG_WINDOW 1017 +#define IDC_SETUP_WIZARD_BKG 1018 +#define IDC_SETUP_WIZARD_GFX_AREA 1019 +#define IDC_HR 1020 +#define IDC_OPEN_CONTAINING_FOLDER 1021 +#define IDC_AGREE 1022 +#define IDC_HR_BOTTOM 1023 +#define IDC_WIZARD_MODE_INSTALL 1024 +#define IDC_WIZARD_MODE_EXTRACT_ONLY 1025 +#define IDC_NEXT 1026 +#define IDC_PREV 1027 +#define IDT_EXTRACT_DESTINATION 1028 +#define IDC_POS_BOX 1029 +#define IDC_BITMAP_SETUP_WIZARD 1030 +#define IDC_MAIN_CONTENT_CANVAS 1031 +#define IDC_DONATE 1032 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NO_MFC 1 +#define _APS_NEXT_RESOURCE_VALUE 115 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1033 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/src/Setup/SelfExtract.c b/src/Setup/SelfExtract.c index 42326efc..e427e44c 100644 --- a/src/Setup/SelfExtract.c +++ b/src/Setup/SelfExtract.c @@ -1,788 +1,788 @@ -/* - 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 "Tcdefs.h" - -#include "Inflate.h" -#include "SelfExtract.h" -#include "Wizard.h" -#include "Setup.h" -#include "Crc.h" -#include "Endian.h" -#include "Dlgcode.h" -#include "Dir.h" -#include "Language.h" -#include "Resource.h" -#include -#include - -#ifndef SRC_POS -#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) -#endif - -#define OutputPackageFile L"VeraCrypt Setup " _T(VERSION_STRING) L".exe" - -#define MAG_START_MARKER "TCINSTRT" -#define MAG_END_MARKER_OBFUSCATED "T/C/I/N/S/C/R/C" -#define PIPE_BUFFER_LEN (4 * BYTES_PER_KB) - -unsigned char MagEndMarker [sizeof (MAG_END_MARKER_OBFUSCATED)]; -wchar_t DestExtractPath [TC_MAX_PATH]; -DECOMPRESSED_FILE Decompressed_Files [NBR_COMPRESSED_FILES]; - -volatile char *PipeWriteBuf = NULL; -volatile HANDLE hChildStdinWrite = INVALID_HANDLE_VALUE; -unsigned char *DecompressedData = NULL; - - - -void SelfExtractStartupInit (void) -{ - DeobfuscateMagEndMarker (); -} - - -// The end marker must be included in the self-extracting exe only once, not twice (used e.g. -// by IsSelfExtractingPackage()) and that's why MAG_END_MARKER_OBFUSCATED is obfuscated and -// needs to be deobfuscated using this function at startup. -static void DeobfuscateMagEndMarker (void) -{ - int i; - - for (i = 0; i < sizeof (MAG_END_MARKER_OBFUSCATED); i += 2) - MagEndMarker [i/2] = MAG_END_MARKER_OBFUSCATED [i]; - - MagEndMarker [i/2] = 0; -} - - -static void PkgError (wchar_t *msg) -{ - MessageBox (NULL, msg, L"VeraCrypt", MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); -} - - -static void PkgWarning (wchar_t *msg) -{ - MessageBox (NULL, msg, L"VeraCrypt", MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); -} - - -static void PkgInfo (wchar_t *msg) -{ - MessageBox (NULL, msg, L"VeraCrypt", MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TOPMOST); -} - - -// Returns 0 if decompression fails or, if successful, returns the size of the decompressed data -static int DecompressBuffer (char *out, char *in, int len) -{ - return (DecompressDeflatedData (out, in, len)); // Inflate -} - - -static void __cdecl PipeWriteThread (void *len) -{ - int sendBufSize = PIPE_BUFFER_LEN, bytesSent = 0; - int bytesToSend = *((int *) len), bytesSentTotal = 0; - - if (PipeWriteBuf == NULL || (HANDLE) hChildStdinWrite == INVALID_HANDLE_VALUE) - { - PkgError (L"Failed sending data to the STDIN pipe"); - return; - } - - while (bytesToSend > 0) - { - if (bytesToSend < PIPE_BUFFER_LEN) - sendBufSize = bytesToSend; - - if (!WriteFile ((HANDLE) hChildStdinWrite, (char *) PipeWriteBuf + bytesSentTotal, sendBufSize, &bytesSent, NULL) - || bytesSent == 0 - || bytesSent != sendBufSize) - { - PkgError (L"Failed sending data to the STDIN pipe"); - return; - } - - bytesToSend -= bytesSent; - bytesSentTotal += bytesSent; - } - - // Closing the pipe causes the child process to stop reading from it - - if (!CloseHandle (hChildStdinWrite)) - { - PkgError (L"Cannot close pipe"); - return; - } -} - - -// Returns 0 if compression fails or, if successful, the size of the compressed data -static int CompressBuffer (char *out, char *in, int len) -{ - SECURITY_ATTRIBUTES securityAttrib; - DWORD bytesReceived = 0; - HANDLE hChildStdoutWrite = INVALID_HANDLE_VALUE; - HANDLE hChildStdoutRead = INVALID_HANDLE_VALUE; - HANDLE hChildStdinRead = INVALID_HANDLE_VALUE; - STARTUPINFO startupInfo; - PROCESS_INFORMATION procInfo; - char pipeBuffer [PIPE_BUFFER_LEN]; - int res_len = 0; - BOOL bGzipHeaderRead = FALSE; - wchar_t szGzipCmd[64]; - - ZeroMemory (&startupInfo, sizeof (startupInfo)); - ZeroMemory (&procInfo, sizeof (procInfo)); - - // Pipe handle inheritance - securityAttrib.bInheritHandle = TRUE; - securityAttrib.nLength = sizeof (securityAttrib); - securityAttrib.lpSecurityDescriptor = NULL; - - if (!CreatePipe (&hChildStdoutRead, &hChildStdoutWrite, &securityAttrib, 0)) - { - PkgError (L"Cannot create STDOUT pipe."); - return 0; - } - SetHandleInformation (hChildStdoutRead, HANDLE_FLAG_INHERIT, 0); - - if (!CreatePipe (&hChildStdinRead, &((HANDLE) hChildStdinWrite), &securityAttrib, 0)) - { - PkgError (L"Cannot create STDIN pipe."); - CloseHandle(hChildStdoutWrite); - CloseHandle(hChildStdoutRead); - return 0; - } - SetHandleInformation (hChildStdinWrite, HANDLE_FLAG_INHERIT, 0); - - // Create a child process that will compress the data - - startupInfo.wShowWindow = SW_HIDE; - startupInfo.hStdInput = hChildStdinRead; - startupInfo.hStdOutput = hChildStdoutWrite; - startupInfo.cb = sizeof (startupInfo); - startupInfo.hStdError = hChildStdoutWrite; - startupInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; - - StringCchCopyW (szGzipCmd, ARRAYSIZE (szGzipCmd), L"gzip --best"); - if (!CreateProcess (NULL, szGzipCmd, NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &procInfo)) - { - PkgError (L"Error: Cannot run gzip.\n\nBefore you can create a self-extracting VeraCrypt package, you need to have the open-source 'gzip' compression tool placed in any directory in the search path for executable files (for example, in 'C:\\Windows\\').\n\nNote: gzip can be freely downloaded e.g. from www.gzip.org"); - CloseHandle(hChildStdoutWrite); - CloseHandle(hChildStdoutRead); - CloseHandle(hChildStdinRead); - CloseHandle(hChildStdinWrite); - return 0; - } - - CloseHandle (procInfo.hProcess); - CloseHandle (procInfo.hThread); - - // Start sending the uncompressed data to the pipe (STDIN) - PipeWriteBuf = in; - _beginthread (PipeWriteThread, PIPE_BUFFER_LEN * 2, (void *) &len); - - if (!CloseHandle (hChildStdoutWrite)) - { - PkgError (L"Cannot close STDOUT write"); - CloseHandle(hChildStdoutRead); - CloseHandle(hChildStdinRead); - return 0; - } - - bGzipHeaderRead = FALSE; - - // Read the compressed data from the pipe (sent by the child process to STDOUT) - while (TRUE) - { - if (!ReadFile (hChildStdoutRead, pipeBuffer, bGzipHeaderRead ? PIPE_BUFFER_LEN : 10, &bytesReceived, NULL)) - break; - - if (bGzipHeaderRead) - { - memcpy (out + res_len, pipeBuffer, bytesReceived); - res_len += bytesReceived; - } - else - bGzipHeaderRead = TRUE; // Skip the 10-byte gzip header - } - - CloseHandle(hChildStdoutRead); - CloseHandle(hChildStdinRead); - return res_len - 8; // A gzip stream ends with a CRC-32 hash and a 32-bit size (those 8 bytes need to be chopped off) -} - - -// Clears all bytes that change when an exe file is digitally signed, except the data that are appended. -// If those bytes weren't cleared, CRC-32 checks would fail after signing. -static void WipeSignatureAreas (char *buffer) -{ - // Clear bytes 0x130-0x1ff - memset (buffer + 0x130, 0, 0x200 - 0x130); -} - - -BOOL MakeSelfExtractingPackage (HWND hwndDlg, wchar_t *szDestDir) -{ - int i, x; - wchar_t inputFile [TC_MAX_PATH]; - wchar_t outputFile [TC_MAX_PATH]; - wchar_t szTmpFilePath [TC_MAX_PATH]; - unsigned char szTmp32bit [4] = {0}; - unsigned char *szTmp32bitPtr = szTmp32bit; - unsigned char *buffer = NULL, *compressedBuffer = NULL; - unsigned char *bufIndex = NULL; - wchar_t tmpStr [2048]; - int bufLen = 0, compressedDataLen = 0, uncompressedDataLen = 0; - - x = wcslen (szDestDir); - if (x < 2) - goto err; - - if (szDestDir[x - 1] != L'\\') - StringCbCatW (szDestDir, MAX_PATH, L"\\"); - - GetModuleFileName (NULL, inputFile, ARRAYSIZE (inputFile)); - - StringCchCopyW (outputFile, ARRAYSIZE(outputFile), szDestDir); - StringCchCatW (outputFile, ARRAYSIZE(outputFile), OutputPackageFile); - - // Clone 'VeraCrypt Setup.exe' to create the base of the new self-extracting archive - - if (!TCCopyFile (inputFile, outputFile)) - { - handleWin32Error (hwndDlg, SRC_POS); - PkgError (L"Cannot copy 'VeraCrypt Setup.exe' to the package"); - goto err; - } - - // Determine the buffer size needed for all the files and meta data and check if all required files exist - - bufLen = 0; - - for (i = 0; i < sizeof (szCompressedFiles) / sizeof (szCompressedFiles[0]); i++) - { - StringCbPrintfW (szTmpFilePath, sizeof(szTmpFilePath), L"%s%s", szDestDir, szCompressedFiles[i]); - - if (!FileExists (szTmpFilePath)) - { - wchar_t tmpstr [1000]; - - StringCbPrintfW (tmpstr, sizeof(tmpstr), L"File not found:\n\n'%s'", szTmpFilePath); - if (_wremove (outputFile)) - StringCbCatW (tmpstr, sizeof(tmpstr), L"\nFailed also to delete package file"); - PkgError (tmpstr); - goto err; - } - - bufLen += (int) GetFileSize64 (szTmpFilePath); - - bufLen += 2; // 16-bit filename length - bufLen += (wcslen(szCompressedFiles[i]) * sizeof (wchar_t)); // Filename - bufLen += 4; // CRC-32 - bufLen += 4; // 32-bit file length - } - - buffer = malloc (bufLen + 524288); // + 512K reserve - if (buffer == NULL) - { - PkgError (L"Cannot allocate memory for uncompressed data"); - if (_wremove (outputFile)) - PkgError (L"Cannot allocate memory for uncompressed data.\nFailed also to delete package file"); - else - PkgError (L"Cannot allocate memory for uncompressed data"); - goto err; - } - - - // Write the start marker - if (!SaveBufferToFile (MAG_START_MARKER, outputFile, strlen (MAG_START_MARKER), TRUE, FALSE)) - { - if (_wremove (outputFile)) - PkgError (L"Cannot write the start marker\nFailed also to delete package file"); - else - PkgError (L"Cannot write the start marker"); - goto err; - } - - - bufIndex = buffer; - - // Copy all required files and their meta data to the buffer - for (i = 0; i < sizeof (szCompressedFiles) / sizeof (szCompressedFiles[0]); i++) - { - DWORD tmpFileSize; - unsigned char *tmpBuffer; - - StringCbPrintfW (szTmpFilePath, sizeof(szTmpFilePath), L"%s%s", szDestDir, szCompressedFiles[i]); - - tmpBuffer = LoadFile (szTmpFilePath, &tmpFileSize); - - if (tmpBuffer == NULL) - { - wchar_t tmpstr [1000]; - - StringCbPrintfW (tmpstr, sizeof(tmpstr), L"Cannot load file \n'%s'", szTmpFilePath); - if (_wremove (outputFile)) - StringCbCatW (tmpstr, sizeof(tmpstr), L"\nFailed also to delete package file"); - PkgError (tmpstr); - goto err; - } - - // Copy the filename length to the main buffer - mputWord (bufIndex, (WORD) wcslen(szCompressedFiles[i])); - - // Copy the filename to the main buffer - wmemcpy ((wchar_t*)bufIndex, szCompressedFiles[i], wcslen(szCompressedFiles[i])); - bufIndex += (wcslen(szCompressedFiles[i]) * sizeof (wchar_t)); - - // Compute CRC-32 hash of the uncompressed file and copy it to the main buffer - mputLong (bufIndex, GetCrc32 (tmpBuffer, tmpFileSize)); - - // Copy the file length to the main buffer - mputLong (bufIndex, (unsigned __int32) tmpFileSize); - - // Copy the file contents to the main buffer - memcpy (bufIndex, tmpBuffer, tmpFileSize); - bufIndex += tmpFileSize; - - free (tmpBuffer); - } - - // Calculate the total size of the uncompressed data - uncompressedDataLen = (int) (bufIndex - buffer); - - // Write total size of the uncompressed data - szTmp32bitPtr = szTmp32bit; - mputLong (szTmp32bitPtr, (unsigned __int32) uncompressedDataLen); - if (!SaveBufferToFile (szTmp32bit, outputFile, sizeof (szTmp32bit), TRUE, FALSE)) - { - if (_wremove (outputFile)) - PkgError (L"Cannot write the total size of the uncompressed data.\nFailed also to delete package file"); - else - PkgError (L"Cannot write the total size of the uncompressed data"); - goto err; - } - - // Compress all the files and meta data in the buffer to create a solid archive - - // Test to make Coverity happy. It will always be false - if (uncompressedDataLen >= (INT_MAX - 524288)) - { - if (_wremove (outputFile)) - PkgError (L"Cannot allocate memory for compressed data.\nFailed also to delete package file"); - else - PkgError (L"Cannot allocate memory for compressed data"); - goto err; - } - - compressedBuffer = malloc (uncompressedDataLen + 524288); // + 512K reserve - if (compressedBuffer == NULL) - { - if (_wremove (outputFile)) - PkgError (L"Cannot allocate memory for compressed data.\nFailed also to delete package file"); - else - PkgError (L"Cannot allocate memory for compressed data"); - goto err; - } - - compressedDataLen = CompressBuffer (compressedBuffer, buffer, uncompressedDataLen); - if (compressedDataLen <= 0) - { - if (_wremove (outputFile)) - PkgError (L"Failed to compress the data.\nFailed also to delete package file"); - else - PkgError (L"Failed to compress the data"); - goto err; - } - - free (buffer); - buffer = NULL; - - // Write the total size of the compressed data - szTmp32bitPtr = szTmp32bit; - mputLong (szTmp32bitPtr, (unsigned __int32) compressedDataLen); - if (!SaveBufferToFile (szTmp32bit, outputFile, sizeof (szTmp32bit), TRUE, FALSE)) - { - if (_wremove (outputFile)) - PkgError (L"Cannot write the total size of the compressed data.\nFailed also to delete package file"); - else - PkgError (L"Cannot write the total size of the compressed data"); - goto err; - } - - // Write the compressed data - if (!SaveBufferToFile (compressedBuffer, outputFile, compressedDataLen, TRUE, FALSE)) - { - if (_wremove (outputFile)) - PkgError (L"Cannot write compressed data to the package.\nFailed also to delete package file"); - else - PkgError (L"Cannot write compressed data to the package"); - goto err; - } - - // Write the end marker - if (!SaveBufferToFile (MagEndMarker, outputFile, strlen (MagEndMarker), TRUE, FALSE)) - { - if (_wremove (outputFile)) - PkgError (L"Cannot write the end marker.\nFailed also to delete package file"); - else - PkgError (L"Cannot write the end marker"); - goto err; - } - - free (compressedBuffer); - compressedBuffer = NULL; - - // Compute and write CRC-32 hash of the entire package - { - DWORD tmpFileSize; - char *tmpBuffer; - - tmpBuffer = LoadFile (outputFile, &tmpFileSize); - - if (tmpBuffer == NULL) - { - handleWin32Error (hwndDlg, SRC_POS); - if (_wremove (outputFile)) - PkgError (L"Cannot load the package to compute CRC.\nFailed also to delete package file"); - else - PkgError (L"Cannot load the package to compute CRC"); - goto err; - } - - // Zero all bytes that change when the exe is digitally signed (except appended blocks). - WipeSignatureAreas (tmpBuffer); - - szTmp32bitPtr = szTmp32bit; - mputLong (szTmp32bitPtr, GetCrc32 (tmpBuffer, tmpFileSize)); - free (tmpBuffer); - - if (!SaveBufferToFile (szTmp32bit, outputFile, sizeof (szTmp32bit), TRUE, FALSE)) - { - if (_wremove (outputFile)) - PkgError (L"Cannot write the total size of the compressed data.\nFailed also to delete package file"); - else - PkgError (L"Cannot write the total size of the compressed data"); - goto err; - } - } - - StringCbPrintfW (tmpStr, sizeof(tmpStr), L"Self-extracting package successfully created (%s)", outputFile); - PkgInfo (tmpStr); - return TRUE; - -err: - if (buffer) - free (buffer); - if (compressedBuffer) - free (compressedBuffer); - - return FALSE; -} - - -// Verifies the CRC-32 of the whole self-extracting package (except the digital signature areas, if present) -BOOL VerifyPackageIntegrity (void) -{ - int fileDataEndPos = 0; - int fileDataStartPos = 0; - unsigned __int32 crc = 0; - unsigned char *tmpBuffer; - int tmpFileSize; - wchar_t path [TC_MAX_PATH]; - - GetModuleFileName (NULL, path, ARRAYSIZE (path)); - - fileDataEndPos = (int) FindStringInFile (path, MagEndMarker, strlen (MagEndMarker)); - if (fileDataEndPos < 0) - { - Error ("DIST_PACKAGE_CORRUPTED", NULL); - return FALSE; - } - fileDataEndPos--; - - fileDataStartPos = (int) FindStringInFile (path, MAG_START_MARKER, strlen (MAG_START_MARKER)); - if (fileDataStartPos < 0) - { - Error ("DIST_PACKAGE_CORRUPTED", NULL); - return FALSE; - } - fileDataStartPos += strlen (MAG_START_MARKER); - - - if (!LoadInt32 (path, &crc, fileDataEndPos + strlen (MagEndMarker) + 1)) - { - Error ("CANT_VERIFY_PACKAGE_INTEGRITY", NULL); - return FALSE; - } - - // Compute the CRC-32 hash of the whole file (except the digital signature area, if present) - tmpBuffer = LoadFile (path, &tmpFileSize); - - if (tmpBuffer == NULL) - { - Error ("CANT_VERIFY_PACKAGE_INTEGRITY", NULL); - return FALSE; - } - - // Zero all bytes that change when an exe is digitally signed (except appended blocks). - WipeSignatureAreas (tmpBuffer); - - if (crc != GetCrc32 (tmpBuffer, fileDataEndPos + 1 + strlen (MagEndMarker))) - { - free (tmpBuffer); - Error ("DIST_PACKAGE_CORRUPTED", NULL); - return FALSE; - } - - free (tmpBuffer); - - return TRUE; -} - - -// Determines whether we are a self-extracting package -BOOL IsSelfExtractingPackage (void) -{ - wchar_t path [TC_MAX_PATH]; - - GetModuleFileName (NULL, path, ARRAYSIZE (path)); - - return (FindStringInFile (path, MagEndMarker, strlen (MagEndMarker)) != -1); -} - - -static void FreeAllFileBuffers (void) -{ - int fileNo; - - if (DecompressedData != NULL) - { - free (DecompressedData); - DecompressedData = NULL; - } - - for (fileNo = 0; fileNo < NBR_COMPRESSED_FILES; fileNo++) - { - Decompressed_Files[fileNo].fileName = NULL; - Decompressed_Files[fileNo].fileContent = NULL; - Decompressed_Files[fileNo].fileNameLength = 0; - Decompressed_Files[fileNo].fileLength = 0; - Decompressed_Files[fileNo].crc = 0; - } -} - - -// Assumes that VerifyPackageIntegrity() has been used. Returns TRUE, if successful (otherwise FALSE). -// Creates a table of pointers to buffers containing the following objects for each file: -// filename size, filename (not null-terminated!), file size, file CRC-32, uncompressed file contents. -// For details, see the definition of the DECOMPRESSED_FILE structure. -BOOL SelfExtractInMemory (wchar_t *path) -{ - int filePos = 0, fileNo = 0; - int fileDataEndPos = 0; - int fileDataStartPos = 0; - int uncompressedLen = 0; - int compressedLen = 0; - unsigned char *compressedData = NULL; - unsigned char *bufPos = NULL, *bufEndPos = NULL; - - FreeAllFileBuffers(); - - fileDataEndPos = (int) FindStringInFile (path, MagEndMarker, strlen (MagEndMarker)); - if (fileDataEndPos < 0) - { - Error ("CANNOT_READ_FROM_PACKAGE", NULL); - return FALSE; - } - - fileDataEndPos--; - - fileDataStartPos = (int) FindStringInFile (path, MAG_START_MARKER, strlen (MAG_START_MARKER)); - if (fileDataStartPos < 0) - { - Error ("CANNOT_READ_FROM_PACKAGE", NULL); - return FALSE; - } - - fileDataStartPos += strlen (MAG_START_MARKER); - - filePos = fileDataStartPos; - - // Read the stored total size of the uncompressed data - if (!LoadInt32 (path, &uncompressedLen, filePos)) - { - Error ("CANNOT_READ_FROM_PACKAGE", NULL); - return FALSE; - } - - filePos += 4; - - // Read the stored total size of the compressed data - if (!LoadInt32 (path, &compressedLen, filePos)) - { - Error ("CANNOT_READ_FROM_PACKAGE", NULL); - return FALSE; - } - - filePos += 4; - - if (compressedLen != fileDataEndPos - fileDataStartPos - 8 + 1) - { - Error ("DIST_PACKAGE_CORRUPTED", NULL); - } - - DecompressedData = malloc (uncompressedLen + 524288); // + 512K reserve - if (DecompressedData == NULL) - { - Error ("ERR_MEM_ALLOC", NULL); - return FALSE; - } - - bufPos = DecompressedData; - bufEndPos = bufPos + uncompressedLen - 1; - - compressedData = LoadFileBlock (path, filePos, compressedLen); - - if (compressedData == NULL) - { - free (DecompressedData); - DecompressedData = NULL; - - Error ("CANNOT_READ_FROM_PACKAGE", NULL); - return FALSE; - } - - // Decompress the data - if (DecompressBuffer (DecompressedData, compressedData, compressedLen) != uncompressedLen) - { - Error ("DIST_PACKAGE_CORRUPTED", NULL); - goto sem_end; - } - - while (bufPos <= bufEndPos && fileNo < NBR_COMPRESSED_FILES) - { - // Filename length - Decompressed_Files[fileNo].fileNameLength = mgetWord (bufPos); - - // Filename - Decompressed_Files[fileNo].fileName = (wchar_t*) bufPos; - bufPos += (Decompressed_Files[fileNo].fileNameLength * sizeof (wchar_t)); - - // CRC-32 of the file - Decompressed_Files[fileNo].crc = mgetLong (bufPos); - - // File length - Decompressed_Files[fileNo].fileLength = mgetLong (bufPos); - - // File content - Decompressed_Files[fileNo].fileContent = bufPos; - bufPos += Decompressed_Files[fileNo].fileLength; - - // Verify CRC-32 of the file (to verify that it didn't get corrupted while creating the solid archive). - if (Decompressed_Files[fileNo].crc - != GetCrc32 (Decompressed_Files[fileNo].fileContent, Decompressed_Files[fileNo].fileLength)) - { - Error ("DIST_PACKAGE_CORRUPTED", NULL); - goto sem_end; - } - - fileNo++; - } - - if (fileNo < NBR_COMPRESSED_FILES) - { - Error ("DIST_PACKAGE_CORRUPTED", NULL); - goto sem_end; - } - - free (compressedData); - return TRUE; - -sem_end: - FreeAllFileBuffers(); - free (compressedData); - return FALSE; -} - - -void __cdecl ExtractAllFilesThread (void *hwndDlg) -{ - int fileNo; - BOOL bSuccess = FALSE; - wchar_t packageFile [TC_MAX_PATH]; - - InvalidateRect (GetDlgItem (GetParent (hwndDlg), IDD_INSTL_DLG), NULL, TRUE); - - ClearLogWindow (hwndDlg); - - GetModuleFileName (NULL, packageFile, ARRAYSIZE (packageFile)); - - if (!(bSuccess = SelfExtractInMemory (packageFile))) - goto eaf_end; - - if (mkfulldir (DestExtractPath, TRUE) != 0) - { - if (mkfulldir (DestExtractPath, FALSE) != 0) - { - wchar_t szTmp[TC_MAX_PATH]; - - handleWin32Error (hwndDlg, SRC_POS); - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CANT_CREATE_FOLDER"), DestExtractPath); - MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_ICONHAND); - bSuccess = FALSE; - goto eaf_end; - } - } - - for (fileNo = 0; fileNo < NBR_COMPRESSED_FILES; fileNo++) - { - wchar_t fileName [TC_MAX_PATH] = {0}; - wchar_t filePath [TC_MAX_PATH] = {0}; - - // Filename - StringCchCopyNW (fileName, ARRAYSIZE(fileName), Decompressed_Files[fileNo].fileName, Decompressed_Files[fileNo].fileNameLength); - StringCchCopyW (filePath, ARRAYSIZE(filePath), DestExtractPath); - StringCchCatW (filePath, ARRAYSIZE(filePath), fileName); - - StatusMessageParam (hwndDlg, "EXTRACTING_VERB", filePath); - - // Write the file - if (!SaveBufferToFile ( - Decompressed_Files[fileNo].fileContent, - filePath, - Decompressed_Files[fileNo].fileLength, - FALSE, FALSE)) - { - wchar_t szTmp[512]; - - StringCbPrintfW (szTmp, sizeof (szTmp), GetString ("CANNOT_WRITE_FILE_X"), filePath); - MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); - bSuccess = FALSE; - goto eaf_end; - } - UpdateProgressBarProc ((int) (100 * ((float) fileNo / NBR_COMPRESSED_FILES))); - } - -eaf_end: - FreeAllFileBuffers(); - - if (bSuccess) - PostMessage (MainDlg, TC_APPMSG_EXTRACTION_SUCCESS, 0, 0); - else - PostMessage (MainDlg, TC_APPMSG_EXTRACTION_FAILURE, 0, 0); -} - +/* + 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 "Tcdefs.h" + +#include "Inflate.h" +#include "SelfExtract.h" +#include "Wizard.h" +#include "Setup.h" +#include "Crc.h" +#include "Endian.h" +#include "Dlgcode.h" +#include "Dir.h" +#include "Language.h" +#include "Resource.h" +#include +#include + +#ifndef SRC_POS +#define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) +#endif + +#define OutputPackageFile L"VeraCrypt Setup " _T(VERSION_STRING) L".exe" + +#define MAG_START_MARKER "TCINSTRT" +#define MAG_END_MARKER_OBFUSCATED "T/C/I/N/S/C/R/C" +#define PIPE_BUFFER_LEN (4 * BYTES_PER_KB) + +unsigned char MagEndMarker [sizeof (MAG_END_MARKER_OBFUSCATED)]; +wchar_t DestExtractPath [TC_MAX_PATH]; +DECOMPRESSED_FILE Decompressed_Files [NBR_COMPRESSED_FILES]; + +volatile char *PipeWriteBuf = NULL; +volatile HANDLE hChildStdinWrite = INVALID_HANDLE_VALUE; +unsigned char *DecompressedData = NULL; + + + +void SelfExtractStartupInit (void) +{ + DeobfuscateMagEndMarker (); +} + + +// The end marker must be included in the self-extracting exe only once, not twice (used e.g. +// by IsSelfExtractingPackage()) and that's why MAG_END_MARKER_OBFUSCATED is obfuscated and +// needs to be deobfuscated using this function at startup. +static void DeobfuscateMagEndMarker (void) +{ + int i; + + for (i = 0; i < sizeof (MAG_END_MARKER_OBFUSCATED); i += 2) + MagEndMarker [i/2] = MAG_END_MARKER_OBFUSCATED [i]; + + MagEndMarker [i/2] = 0; +} + + +static void PkgError (wchar_t *msg) +{ + MessageBox (NULL, msg, L"VeraCrypt", MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); +} + + +static void PkgWarning (wchar_t *msg) +{ + MessageBox (NULL, msg, L"VeraCrypt", MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); +} + + +static void PkgInfo (wchar_t *msg) +{ + MessageBox (NULL, msg, L"VeraCrypt", MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TOPMOST); +} + + +// Returns 0 if decompression fails or, if successful, returns the size of the decompressed data +static int DecompressBuffer (char *out, char *in, int len) +{ + return (DecompressDeflatedData (out, in, len)); // Inflate +} + + +static void __cdecl PipeWriteThread (void *len) +{ + int sendBufSize = PIPE_BUFFER_LEN, bytesSent = 0; + int bytesToSend = *((int *) len), bytesSentTotal = 0; + + if (PipeWriteBuf == NULL || (HANDLE) hChildStdinWrite == INVALID_HANDLE_VALUE) + { + PkgError (L"Failed sending data to the STDIN pipe"); + return; + } + + while (bytesToSend > 0) + { + if (bytesToSend < PIPE_BUFFER_LEN) + sendBufSize = bytesToSend; + + if (!WriteFile ((HANDLE) hChildStdinWrite, (char *) PipeWriteBuf + bytesSentTotal, sendBufSize, &bytesSent, NULL) + || bytesSent == 0 + || bytesSent != sendBufSize) + { + PkgError (L"Failed sending data to the STDIN pipe"); + return; + } + + bytesToSend -= bytesSent; + bytesSentTotal += bytesSent; + } + + // Closing the pipe causes the child process to stop reading from it + + if (!CloseHandle (hChildStdinWrite)) + { + PkgError (L"Cannot close pipe"); + return; + } +} + + +// Returns 0 if compression fails or, if successful, the size of the compressed data +static int CompressBuffer (char *out, char *in, int len) +{ + SECURITY_ATTRIBUTES securityAttrib; + DWORD bytesReceived = 0; + HANDLE hChildStdoutWrite = INVALID_HANDLE_VALUE; + HANDLE hChildStdoutRead = INVALID_HANDLE_VALUE; + HANDLE hChildStdinRead = INVALID_HANDLE_VALUE; + STARTUPINFO startupInfo; + PROCESS_INFORMATION procInfo; + char pipeBuffer [PIPE_BUFFER_LEN]; + int res_len = 0; + BOOL bGzipHeaderRead = FALSE; + wchar_t szGzipCmd[64]; + + ZeroMemory (&startupInfo, sizeof (startupInfo)); + ZeroMemory (&procInfo, sizeof (procInfo)); + + // Pipe handle inheritance + securityAttrib.bInheritHandle = TRUE; + securityAttrib.nLength = sizeof (securityAttrib); + securityAttrib.lpSecurityDescriptor = NULL; + + if (!CreatePipe (&hChildStdoutRead, &hChildStdoutWrite, &securityAttrib, 0)) + { + PkgError (L"Cannot create STDOUT pipe."); + return 0; + } + SetHandleInformation (hChildStdoutRead, HANDLE_FLAG_INHERIT, 0); + + if (!CreatePipe (&hChildStdinRead, &((HANDLE) hChildStdinWrite), &securityAttrib, 0)) + { + PkgError (L"Cannot create STDIN pipe."); + CloseHandle(hChildStdoutWrite); + CloseHandle(hChildStdoutRead); + return 0; + } + SetHandleInformation (hChildStdinWrite, HANDLE_FLAG_INHERIT, 0); + + // Create a child process that will compress the data + + startupInfo.wShowWindow = SW_HIDE; + startupInfo.hStdInput = hChildStdinRead; + startupInfo.hStdOutput = hChildStdoutWrite; + startupInfo.cb = sizeof (startupInfo); + startupInfo.hStdError = hChildStdoutWrite; + startupInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; + + StringCchCopyW (szGzipCmd, ARRAYSIZE (szGzipCmd), L"gzip --best"); + if (!CreateProcess (NULL, szGzipCmd, NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &procInfo)) + { + PkgError (L"Error: Cannot run gzip.\n\nBefore you can create a self-extracting VeraCrypt package, you need to have the open-source 'gzip' compression tool placed in any directory in the search path for executable files (for example, in 'C:\\Windows\\').\n\nNote: gzip can be freely downloaded e.g. from www.gzip.org"); + CloseHandle(hChildStdoutWrite); + CloseHandle(hChildStdoutRead); + CloseHandle(hChildStdinRead); + CloseHandle(hChildStdinWrite); + return 0; + } + + CloseHandle (procInfo.hProcess); + CloseHandle (procInfo.hThread); + + // Start sending the uncompressed data to the pipe (STDIN) + PipeWriteBuf = in; + _beginthread (PipeWriteThread, PIPE_BUFFER_LEN * 2, (void *) &len); + + if (!CloseHandle (hChildStdoutWrite)) + { + PkgError (L"Cannot close STDOUT write"); + CloseHandle(hChildStdoutRead); + CloseHandle(hChildStdinRead); + return 0; + } + + bGzipHeaderRead = FALSE; + + // Read the compressed data from the pipe (sent by the child process to STDOUT) + while (TRUE) + { + if (!ReadFile (hChildStdoutRead, pipeBuffer, bGzipHeaderRead ? PIPE_BUFFER_LEN : 10, &bytesReceived, NULL)) + break; + + if (bGzipHeaderRead) + { + memcpy (out + res_len, pipeBuffer, bytesReceived); + res_len += bytesReceived; + } + else + bGzipHeaderRead = TRUE; // Skip the 10-byte gzip header + } + + CloseHandle(hChildStdoutRead); + CloseHandle(hChildStdinRead); + return res_len - 8; // A gzip stream ends with a CRC-32 hash and a 32-bit size (those 8 bytes need to be chopped off) +} + + +// Clears all bytes that change when an exe file is digitally signed, except the data that are appended. +// If those bytes weren't cleared, CRC-32 checks would fail after signing. +static void WipeSignatureAreas (char *buffer) +{ + // Clear bytes 0x130-0x1ff + memset (buffer + 0x130, 0, 0x200 - 0x130); +} + + +BOOL MakeSelfExtractingPackage (HWND hwndDlg, wchar_t *szDestDir) +{ + int i, x; + wchar_t inputFile [TC_MAX_PATH]; + wchar_t outputFile [TC_MAX_PATH]; + wchar_t szTmpFilePath [TC_MAX_PATH]; + unsigned char szTmp32bit [4] = {0}; + unsigned char *szTmp32bitPtr = szTmp32bit; + unsigned char *buffer = NULL, *compressedBuffer = NULL; + unsigned char *bufIndex = NULL; + wchar_t tmpStr [2048]; + int bufLen = 0, compressedDataLen = 0, uncompressedDataLen = 0; + + x = wcslen (szDestDir); + if (x < 2) + goto err; + + if (szDestDir[x - 1] != L'\\') + StringCbCatW (szDestDir, MAX_PATH, L"\\"); + + GetModuleFileName (NULL, inputFile, ARRAYSIZE (inputFile)); + + StringCchCopyW (outputFile, ARRAYSIZE(outputFile), szDestDir); + StringCchCatW (outputFile, ARRAYSIZE(outputFile), OutputPackageFile); + + // Clone 'VeraCrypt Setup.exe' to create the base of the new self-extracting archive + + if (!TCCopyFile (inputFile, outputFile)) + { + handleWin32Error (hwndDlg, SRC_POS); + PkgError (L"Cannot copy 'VeraCrypt Setup.exe' to the package"); + goto err; + } + + // Determine the buffer size needed for all the files and meta data and check if all required files exist + + bufLen = 0; + + for (i = 0; i < sizeof (szCompressedFiles) / sizeof (szCompressedFiles[0]); i++) + { + StringCbPrintfW (szTmpFilePath, sizeof(szTmpFilePath), L"%s%s", szDestDir, szCompressedFiles[i]); + + if (!FileExists (szTmpFilePath)) + { + wchar_t tmpstr [1000]; + + StringCbPrintfW (tmpstr, sizeof(tmpstr), L"File not found:\n\n'%s'", szTmpFilePath); + if (_wremove (outputFile)) + StringCbCatW (tmpstr, sizeof(tmpstr), L"\nFailed also to delete package file"); + PkgError (tmpstr); + goto err; + } + + bufLen += (int) GetFileSize64 (szTmpFilePath); + + bufLen += 2; // 16-bit filename length + bufLen += (wcslen(szCompressedFiles[i]) * sizeof (wchar_t)); // Filename + bufLen += 4; // CRC-32 + bufLen += 4; // 32-bit file length + } + + buffer = malloc (bufLen + 524288); // + 512K reserve + if (buffer == NULL) + { + PkgError (L"Cannot allocate memory for uncompressed data"); + if (_wremove (outputFile)) + PkgError (L"Cannot allocate memory for uncompressed data.\nFailed also to delete package file"); + else + PkgError (L"Cannot allocate memory for uncompressed data"); + goto err; + } + + + // Write the start marker + if (!SaveBufferToFile (MAG_START_MARKER, outputFile, strlen (MAG_START_MARKER), TRUE, FALSE)) + { + if (_wremove (outputFile)) + PkgError (L"Cannot write the start marker\nFailed also to delete package file"); + else + PkgError (L"Cannot write the start marker"); + goto err; + } + + + bufIndex = buffer; + + // Copy all required files and their meta data to the buffer + for (i = 0; i < sizeof (szCompressedFiles) / sizeof (szCompressedFiles[0]); i++) + { + DWORD tmpFileSize; + unsigned char *tmpBuffer; + + StringCbPrintfW (szTmpFilePath, sizeof(szTmpFilePath), L"%s%s", szDestDir, szCompressedFiles[i]); + + tmpBuffer = LoadFile (szTmpFilePath, &tmpFileSize); + + if (tmpBuffer == NULL) + { + wchar_t tmpstr [1000]; + + StringCbPrintfW (tmpstr, sizeof(tmpstr), L"Cannot load file \n'%s'", szTmpFilePath); + if (_wremove (outputFile)) + StringCbCatW (tmpstr, sizeof(tmpstr), L"\nFailed also to delete package file"); + PkgError (tmpstr); + goto err; + } + + // Copy the filename length to the main buffer + mputWord (bufIndex, (WORD) wcslen(szCompressedFiles[i])); + + // Copy the filename to the main buffer + wmemcpy ((wchar_t*)bufIndex, szCompressedFiles[i], wcslen(szCompressedFiles[i])); + bufIndex += (wcslen(szCompressedFiles[i]) * sizeof (wchar_t)); + + // Compute CRC-32 hash of the uncompressed file and copy it to the main buffer + mputLong (bufIndex, GetCrc32 (tmpBuffer, tmpFileSize)); + + // Copy the file length to the main buffer + mputLong (bufIndex, (unsigned __int32) tmpFileSize); + + // Copy the file contents to the main buffer + memcpy (bufIndex, tmpBuffer, tmpFileSize); + bufIndex += tmpFileSize; + + free (tmpBuffer); + } + + // Calculate the total size of the uncompressed data + uncompressedDataLen = (int) (bufIndex - buffer); + + // Write total size of the uncompressed data + szTmp32bitPtr = szTmp32bit; + mputLong (szTmp32bitPtr, (unsigned __int32) uncompressedDataLen); + if (!SaveBufferToFile (szTmp32bit, outputFile, sizeof (szTmp32bit), TRUE, FALSE)) + { + if (_wremove (outputFile)) + PkgError (L"Cannot write the total size of the uncompressed data.\nFailed also to delete package file"); + else + PkgError (L"Cannot write the total size of the uncompressed data"); + goto err; + } + + // Compress all the files and meta data in the buffer to create a solid archive + + // Test to make Coverity happy. It will always be false + if (uncompressedDataLen >= (INT_MAX - 524288)) + { + if (_wremove (outputFile)) + PkgError (L"Cannot allocate memory for compressed data.\nFailed also to delete package file"); + else + PkgError (L"Cannot allocate memory for compressed data"); + goto err; + } + + compressedBuffer = malloc (uncompressedDataLen + 524288); // + 512K reserve + if (compressedBuffer == NULL) + { + if (_wremove (outputFile)) + PkgError (L"Cannot allocate memory for compressed data.\nFailed also to delete package file"); + else + PkgError (L"Cannot allocate memory for compressed data"); + goto err; + } + + compressedDataLen = CompressBuffer (compressedBuffer, buffer, uncompressedDataLen); + if (compressedDataLen <= 0) + { + if (_wremove (outputFile)) + PkgError (L"Failed to compress the data.\nFailed also to delete package file"); + else + PkgError (L"Failed to compress the data"); + goto err; + } + + free (buffer); + buffer = NULL; + + // Write the total size of the compressed data + szTmp32bitPtr = szTmp32bit; + mputLong (szTmp32bitPtr, (unsigned __int32) compressedDataLen); + if (!SaveBufferToFile (szTmp32bit, outputFile, sizeof (szTmp32bit), TRUE, FALSE)) + { + if (_wremove (outputFile)) + PkgError (L"Cannot write the total size of the compressed data.\nFailed also to delete package file"); + else + PkgError (L"Cannot write the total size of the compressed data"); + goto err; + } + + // Write the compressed data + if (!SaveBufferToFile (compressedBuffer, outputFile, compressedDataLen, TRUE, FALSE)) + { + if (_wremove (outputFile)) + PkgError (L"Cannot write compressed data to the package.\nFailed also to delete package file"); + else + PkgError (L"Cannot write compressed data to the package"); + goto err; + } + + // Write the end marker + if (!SaveBufferToFile (MagEndMarker, outputFile, strlen (MagEndMarker), TRUE, FALSE)) + { + if (_wremove (outputFile)) + PkgError (L"Cannot write the end marker.\nFailed also to delete package file"); + else + PkgError (L"Cannot write the end marker"); + goto err; + } + + free (compressedBuffer); + compressedBuffer = NULL; + + // Compute and write CRC-32 hash of the entire package + { + DWORD tmpFileSize; + char *tmpBuffer; + + tmpBuffer = LoadFile (outputFile, &tmpFileSize); + + if (tmpBuffer == NULL) + { + handleWin32Error (hwndDlg, SRC_POS); + if (_wremove (outputFile)) + PkgError (L"Cannot load the package to compute CRC.\nFailed also to delete package file"); + else + PkgError (L"Cannot load the package to compute CRC"); + goto err; + } + + // Zero all bytes that change when the exe is digitally signed (except appended blocks). + WipeSignatureAreas (tmpBuffer); + + szTmp32bitPtr = szTmp32bit; + mputLong (szTmp32bitPtr, GetCrc32 (tmpBuffer, tmpFileSize)); + free (tmpBuffer); + + if (!SaveBufferToFile (szTmp32bit, outputFile, sizeof (szTmp32bit), TRUE, FALSE)) + { + if (_wremove (outputFile)) + PkgError (L"Cannot write the total size of the compressed data.\nFailed also to delete package file"); + else + PkgError (L"Cannot write the total size of the compressed data"); + goto err; + } + } + + StringCbPrintfW (tmpStr, sizeof(tmpStr), L"Self-extracting package successfully created (%s)", outputFile); + PkgInfo (tmpStr); + return TRUE; + +err: + if (buffer) + free (buffer); + if (compressedBuffer) + free (compressedBuffer); + + return FALSE; +} + + +// Verifies the CRC-32 of the whole self-extracting package (except the digital signature areas, if present) +BOOL VerifyPackageIntegrity (void) +{ + int fileDataEndPos = 0; + int fileDataStartPos = 0; + unsigned __int32 crc = 0; + unsigned char *tmpBuffer; + int tmpFileSize; + wchar_t path [TC_MAX_PATH]; + + GetModuleFileName (NULL, path, ARRAYSIZE (path)); + + fileDataEndPos = (int) FindStringInFile (path, MagEndMarker, strlen (MagEndMarker)); + if (fileDataEndPos < 0) + { + Error ("DIST_PACKAGE_CORRUPTED", NULL); + return FALSE; + } + fileDataEndPos--; + + fileDataStartPos = (int) FindStringInFile (path, MAG_START_MARKER, strlen (MAG_START_MARKER)); + if (fileDataStartPos < 0) + { + Error ("DIST_PACKAGE_CORRUPTED", NULL); + return FALSE; + } + fileDataStartPos += strlen (MAG_START_MARKER); + + + if (!LoadInt32 (path, &crc, fileDataEndPos + strlen (MagEndMarker) + 1)) + { + Error ("CANT_VERIFY_PACKAGE_INTEGRITY", NULL); + return FALSE; + } + + // Compute the CRC-32 hash of the whole file (except the digital signature area, if present) + tmpBuffer = LoadFile (path, &tmpFileSize); + + if (tmpBuffer == NULL) + { + Error ("CANT_VERIFY_PACKAGE_INTEGRITY", NULL); + return FALSE; + } + + // Zero all bytes that change when an exe is digitally signed (except appended blocks). + WipeSignatureAreas (tmpBuffer); + + if (crc != GetCrc32 (tmpBuffer, fileDataEndPos + 1 + strlen (MagEndMarker))) + { + free (tmpBuffer); + Error ("DIST_PACKAGE_CORRUPTED", NULL); + return FALSE; + } + + free (tmpBuffer); + + return TRUE; +} + + +// Determines whether we are a self-extracting package +BOOL IsSelfExtractingPackage (void) +{ + wchar_t path [TC_MAX_PATH]; + + GetModuleFileName (NULL, path, ARRAYSIZE (path)); + + return (FindStringInFile (path, MagEndMarker, strlen (MagEndMarker)) != -1); +} + + +static void FreeAllFileBuffers (void) +{ + int fileNo; + + if (DecompressedData != NULL) + { + free (DecompressedData); + DecompressedData = NULL; + } + + for (fileNo = 0; fileNo < NBR_COMPRESSED_FILES; fileNo++) + { + Decompressed_Files[fileNo].fileName = NULL; + Decompressed_Files[fileNo].fileContent = NULL; + Decompressed_Files[fileNo].fileNameLength = 0; + Decompressed_Files[fileNo].fileLength = 0; + Decompressed_Files[fileNo].crc = 0; + } +} + + +// Assumes that VerifyPackageIntegrity() has been used. Returns TRUE, if successful (otherwise FALSE). +// Creates a table of pointers to buffers containing the following objects for each file: +// filename size, filename (not null-terminated!), file size, file CRC-32, uncompressed file contents. +// For details, see the definition of the DECOMPRESSED_FILE structure. +BOOL SelfExtractInMemory (wchar_t *path) +{ + int filePos = 0, fileNo = 0; + int fileDataEndPos = 0; + int fileDataStartPos = 0; + int uncompressedLen = 0; + int compressedLen = 0; + unsigned char *compressedData = NULL; + unsigned char *bufPos = NULL, *bufEndPos = NULL; + + FreeAllFileBuffers(); + + fileDataEndPos = (int) FindStringInFile (path, MagEndMarker, strlen (MagEndMarker)); + if (fileDataEndPos < 0) + { + Error ("CANNOT_READ_FROM_PACKAGE", NULL); + return FALSE; + } + + fileDataEndPos--; + + fileDataStartPos = (int) FindStringInFile (path, MAG_START_MARKER, strlen (MAG_START_MARKER)); + if (fileDataStartPos < 0) + { + Error ("CANNOT_READ_FROM_PACKAGE", NULL); + return FALSE; + } + + fileDataStartPos += strlen (MAG_START_MARKER); + + filePos = fileDataStartPos; + + // Read the stored total size of the uncompressed data + if (!LoadInt32 (path, &uncompressedLen, filePos)) + { + Error ("CANNOT_READ_FROM_PACKAGE", NULL); + return FALSE; + } + + filePos += 4; + + // Read the stored total size of the compressed data + if (!LoadInt32 (path, &compressedLen, filePos)) + { + Error ("CANNOT_READ_FROM_PACKAGE", NULL); + return FALSE; + } + + filePos += 4; + + if (compressedLen != fileDataEndPos - fileDataStartPos - 8 + 1) + { + Error ("DIST_PACKAGE_CORRUPTED", NULL); + } + + DecompressedData = malloc (uncompressedLen + 524288); // + 512K reserve + if (DecompressedData == NULL) + { + Error ("ERR_MEM_ALLOC", NULL); + return FALSE; + } + + bufPos = DecompressedData; + bufEndPos = bufPos + uncompressedLen - 1; + + compressedData = LoadFileBlock (path, filePos, compressedLen); + + if (compressedData == NULL) + { + free (DecompressedData); + DecompressedData = NULL; + + Error ("CANNOT_READ_FROM_PACKAGE", NULL); + return FALSE; + } + + // Decompress the data + if (DecompressBuffer (DecompressedData, compressedData, compressedLen) != uncompressedLen) + { + Error ("DIST_PACKAGE_CORRUPTED", NULL); + goto sem_end; + } + + while (bufPos <= bufEndPos && fileNo < NBR_COMPRESSED_FILES) + { + // Filename length + Decompressed_Files[fileNo].fileNameLength = mgetWord (bufPos); + + // Filename + Decompressed_Files[fileNo].fileName = (wchar_t*) bufPos; + bufPos += (Decompressed_Files[fileNo].fileNameLength * sizeof (wchar_t)); + + // CRC-32 of the file + Decompressed_Files[fileNo].crc = mgetLong (bufPos); + + // File length + Decompressed_Files[fileNo].fileLength = mgetLong (bufPos); + + // File content + Decompressed_Files[fileNo].fileContent = bufPos; + bufPos += Decompressed_Files[fileNo].fileLength; + + // Verify CRC-32 of the file (to verify that it didn't get corrupted while creating the solid archive). + if (Decompressed_Files[fileNo].crc + != GetCrc32 (Decompressed_Files[fileNo].fileContent, Decompressed_Files[fileNo].fileLength)) + { + Error ("DIST_PACKAGE_CORRUPTED", NULL); + goto sem_end; + } + + fileNo++; + } + + if (fileNo < NBR_COMPRESSED_FILES) + { + Error ("DIST_PACKAGE_CORRUPTED", NULL); + goto sem_end; + } + + free (compressedData); + return TRUE; + +sem_end: + FreeAllFileBuffers(); + free (compressedData); + return FALSE; +} + + +void __cdecl ExtractAllFilesThread (void *hwndDlg) +{ + int fileNo; + BOOL bSuccess = FALSE; + wchar_t packageFile [TC_MAX_PATH]; + + InvalidateRect (GetDlgItem (GetParent (hwndDlg), IDD_INSTL_DLG), NULL, TRUE); + + ClearLogWindow (hwndDlg); + + GetModuleFileName (NULL, packageFile, ARRAYSIZE (packageFile)); + + if (!(bSuccess = SelfExtractInMemory (packageFile))) + goto eaf_end; + + if (mkfulldir (DestExtractPath, TRUE) != 0) + { + if (mkfulldir (DestExtractPath, FALSE) != 0) + { + wchar_t szTmp[TC_MAX_PATH]; + + handleWin32Error (hwndDlg, SRC_POS); + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CANT_CREATE_FOLDER"), DestExtractPath); + MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_ICONHAND); + bSuccess = FALSE; + goto eaf_end; + } + } + + for (fileNo = 0; fileNo < NBR_COMPRESSED_FILES; fileNo++) + { + wchar_t fileName [TC_MAX_PATH] = {0}; + wchar_t filePath [TC_MAX_PATH] = {0}; + + // Filename + StringCchCopyNW (fileName, ARRAYSIZE(fileName), Decompressed_Files[fileNo].fileName, Decompressed_Files[fileNo].fileNameLength); + StringCchCopyW (filePath, ARRAYSIZE(filePath), DestExtractPath); + StringCchCatW (filePath, ARRAYSIZE(filePath), fileName); + + StatusMessageParam (hwndDlg, "EXTRACTING_VERB", filePath); + + // Write the file + if (!SaveBufferToFile ( + Decompressed_Files[fileNo].fileContent, + filePath, + Decompressed_Files[fileNo].fileLength, + FALSE, FALSE)) + { + wchar_t szTmp[512]; + + StringCbPrintfW (szTmp, sizeof (szTmp), GetString ("CANNOT_WRITE_FILE_X"), filePath); + MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); + bSuccess = FALSE; + goto eaf_end; + } + UpdateProgressBarProc ((int) (100 * ((float) fileNo / NBR_COMPRESSED_FILES))); + } + +eaf_end: + FreeAllFileBuffers(); + + if (bSuccess) + PostMessage (MainDlg, TC_APPMSG_EXTRACTION_SUCCESS, 0, 0); + else + PostMessage (MainDlg, TC_APPMSG_EXTRACTION_FAILURE, 0, 0); +} + diff --git a/src/Setup/SelfExtract.h b/src/Setup/SelfExtract.h index a93f4901..529b24d7 100644 --- a/src/Setup/SelfExtract.h +++ b/src/Setup/SelfExtract.h @@ -1,43 +1,43 @@ -/* - 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 "Setup.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct -{ - // WARNING: file name is NOT null-terminated (use fileNameLength). - wchar_t *fileName; - int fileNameLength; - uint32 crc; - __int32 fileLength; - unsigned char *fileContent; -} DECOMPRESSED_FILE; - -extern DECOMPRESSED_FILE Decompressed_Files [NBR_COMPRESSED_FILES]; - -void SelfExtractStartupInit (void); -BOOL SelfExtractInMemory (wchar_t *path); -void __cdecl ExtractAllFilesThread (void *hwndDlg); -BOOL MakeSelfExtractingPackage (HWND hwndDlg, wchar_t *szDestDir); -BOOL VerifyPackageIntegrity (void); -BOOL IsSelfExtractingPackage (void); -static void DeobfuscateMagEndMarker (void); - -extern wchar_t DestExtractPath [TC_MAX_PATH]; - -#ifdef __cplusplus -} -#endif +/* + 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 "Setup.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct +{ + // WARNING: file name is NOT null-terminated (use fileNameLength). + wchar_t *fileName; + int fileNameLength; + uint32 crc; + __int32 fileLength; + unsigned char *fileContent; +} DECOMPRESSED_FILE; + +extern DECOMPRESSED_FILE Decompressed_Files [NBR_COMPRESSED_FILES]; + +void SelfExtractStartupInit (void); +BOOL SelfExtractInMemory (wchar_t *path); +void __cdecl ExtractAllFilesThread (void *hwndDlg); +BOOL MakeSelfExtractingPackage (HWND hwndDlg, wchar_t *szDestDir); +BOOL VerifyPackageIntegrity (void); +BOOL IsSelfExtractingPackage (void); +static void DeobfuscateMagEndMarker (void); + +extern wchar_t DestExtractPath [TC_MAX_PATH]; + +#ifdef __cplusplus +} +#endif diff --git a/src/Setup/Setup.c b/src/Setup/Setup.c index 7c382986..899c1583 100644 --- a/src/Setup/Setup.c +++ b/src/Setup/Setup.c @@ -1,2632 +1,2632 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" -#include -#include -#include -#include -#include -#include -#include - -#include "Apidrvr.h" -#include "BootEncryption.h" -#include "Boot/Windows/BootCommon.h" -#include "Combo.h" -#include "ComSetup.h" -#include "Dlgcode.h" -#include "Language.h" -#include "Registry.h" -#include "Resource.h" - -#include "Dir.h" -#include "Setup.h" -#include "SelfExtract.h" -#include "Wizard.h" - -#include "../Common/Resource.h" - -using namespace VeraCrypt; - -#pragma warning( disable : 4201 ) -#pragma warning( disable : 4115 ) - -#include - -#pragma warning( default : 4201 ) -#pragma warning( default : 4115 ) - -#include - -wchar_t InstallationPath[TC_MAX_PATH]; -wchar_t SetupFilesDir[TC_MAX_PATH]; -wchar_t UninstallBatch[MAX_PATH]; - -BOOL bUninstall = FALSE; -BOOL bRestartRequired = FALSE; -BOOL bMakePackage = FALSE; -BOOL bDone = FALSE; -BOOL Rollback = FALSE; -BOOL bUpgrade = FALSE; -BOOL bDowngrade = FALSE; -BOOL SystemEncryptionUpdate = FALSE; -BOOL PortableMode = FALSE; -BOOL bRepairMode = FALSE; -BOOL bReinstallMode = FALSE; -BOOL bChangeMode = FALSE; -BOOL bDevm = FALSE; -BOOL bPossiblyFirstTimeInstall = FALSE; -BOOL bUninstallInProgress = FALSE; -BOOL UnloadDriver = TRUE; - -BOOL bSystemRestore = TRUE; -BOOL bDisableSwapFiles = FALSE; -BOOL bForAllUsers = TRUE; -BOOL bRegisterFileExt = TRUE; -BOOL bAddToStartMenu = TRUE; -BOOL bDesktopIcon = TRUE; - -BOOL bDesktopIconStatusDetermined = FALSE; - -HMODULE volatile SystemRestoreDll = 0; - -void localcleanup (void) -{ - localcleanupwiz (); - cleanup (); - - CloseAppSetupMutex (); -} - -BOOL ForceDeleteFile (LPCWSTR szFileName) -{ - if (!DeleteFile (szFileName)) - { - /* delete the renamed file when the machine reboots */ - return MoveFileEx (szFileName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); - } - else - return TRUE; -} - -BOOL StatDeleteFile (wchar_t *lpszFile, BOOL bCheckForOldFile) -{ - struct __stat64 st; - - if (bCheckForOldFile) - { - wchar_t szOldPath[MAX_PATH + 1]; - StringCbCopyW (szOldPath, sizeof(szOldPath), lpszFile); - StringCbCatW (szOldPath, sizeof(szOldPath), VC_FILENAME_RENAMED_SUFFIX); - - if (_wstat64 (szOldPath, &st) == 0) - { - ForceDeleteFile (szOldPath); - } - } - - if (_wstat64 (lpszFile, &st) == 0) - return ForceDeleteFile (lpszFile); - else - return TRUE; -} - -BOOL StatRemoveDirectory (wchar_t *lpszDir) -{ - struct __stat64 st; - - if (_wstat64 (lpszDir, &st) == 0) - { - BOOL bStatus = RemoveDirectory (lpszDir); - if (!bStatus) - { - /* force removal of the non empty directory */ - wchar_t szOpPath[TC_MAX_PATH + 1] = {0}; - SHFILEOPSTRUCTW op; - - StringCchCopyW(szOpPath, ARRAYSIZE(szOpPath)-1, lpszDir); - ZeroMemory(&op, sizeof(op)); - op.wFunc = FO_DELETE; - op.pFrom = szOpPath; - op.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR; - - if ((0 == SHFileOperation(&op)) && (!op.fAnyOperationsAborted)) - bStatus = TRUE; - } - return bStatus; - } - else - return TRUE; -} - - -/* Recursively set the given OWNER security descriptor to the key and its subkeys */ -static void RecursiveSetOwner (HKEY hKey, PSECURITY_DESCRIPTOR pSD) -{ - LSTATUS status = 0; - DWORD dwIndex = 0, dwMaxNameLen = 0, dwNameLen = 0, numberSubKeys = 0; - HKEY hSubKey; - - if ( (ERROR_SUCCESS == status) && (ERROR_SUCCESS == RegQueryInfoKey(hKey, NULL, NULL, NULL, &numberSubKeys, &dwMaxNameLen, NULL, NULL, NULL, NULL, NULL, NULL)) - && (numberSubKeys >= 1) - ) - { - dwMaxNameLen++; - wchar_t* szNameValue = new wchar_t[dwMaxNameLen]; - while (true) - { - dwNameLen = dwMaxNameLen; - status = RegEnumKeyExW (hKey, dwIndex++, szNameValue, &dwNameLen, NULL, NULL, NULL, NULL); - if (status == ERROR_SUCCESS) - { - status = RegOpenKeyExW (hKey, szNameValue, 0, WRITE_OWNER | KEY_READ , &hSubKey); - if (ERROR_SUCCESS == status) - { - RecursiveSetOwner (hSubKey, pSD); - RegCloseKey(hSubKey); - } - } - else - break; - } - delete [] szNameValue; - } - - RegSetKeySecurity (hKey, OWNER_SECURITY_INFORMATION, pSD); -} - -/* Recursively set the given DACL security descriptor to the key and its subkeys */ -static void RecursiveSetDACL (HKEY hKey, const wchar_t* SubKeyName, PSECURITY_DESCRIPTOR pSD) -{ - HKEY hSubKey; - DWORD dwIndex = 0, dwMaxNameLen = 0, dwNameLen = 0, numberSubKeys = 0; - LSTATUS status = RegOpenKeyExW(hKey, SubKeyName, 0, WRITE_DAC | KEY_READ /*| ACCESS_SYSTEM_SECURITY*/, &hSubKey); - if (status == ERROR_SUCCESS) - { - status = RegSetKeySecurity (hSubKey, DACL_SECURITY_INFORMATION, pSD); - if (status == ERROR_SUCCESS) - { - RegCloseKey(hSubKey); - status = RegOpenKeyExW(hKey, SubKeyName, 0, WRITE_DAC | KEY_READ , &hSubKey); - } - - if ( (ERROR_SUCCESS == status) - && (ERROR_SUCCESS == RegQueryInfoKeyW(hSubKey, NULL, NULL, NULL, &numberSubKeys, &dwMaxNameLen, NULL, NULL, NULL, NULL, NULL, NULL)) - && (numberSubKeys >= 1) - ) - { - dwMaxNameLen++; - wchar_t* szNameValue = new wchar_t[dwMaxNameLen]; - while (true) - { - dwNameLen = dwMaxNameLen; - status = RegEnumKeyExW (hSubKey, dwIndex++, szNameValue, &dwNameLen, NULL, NULL, NULL, NULL); - if (status == ERROR_SUCCESS) - { - RecursiveSetDACL (hSubKey, szNameValue, pSD); - } - else - break; - } - delete [] szNameValue; - } - } -} - -/* Correct the key permissions to allow its deletion */ -static void AllowKeyAccess(HKEY Key,const wchar_t* SubKeyName) -{ - LSTATUS RegResult; - HKEY SvcKey = NULL; - DWORD dwLength = 0; - HANDLE Token = NULL; - PTOKEN_USER pTokenUser = NULL; - std::string sNewSD; - - RegResult = RegOpenKeyExW(Key, SubKeyName, 0, WRITE_OWNER | KEY_READ, &SvcKey); - if (RegResult==ERROR_SUCCESS) - { - if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &Token)) - { - if (!GetTokenInformation(Token, TokenUser, pTokenUser, 0, &dwLength)) - { - if (GetLastError() ==ERROR_INSUFFICIENT_BUFFER) - { - pTokenUser = (PTOKEN_USER) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength); - if (pTokenUser) - { - if (GetTokenInformation(Token, TokenUser, pTokenUser, dwLength, &dwLength)) - { - SECURITY_DESCRIPTOR SecDesc; - if ( InitializeSecurityDescriptor(&SecDesc, SECURITY_DESCRIPTOR_REVISION) - && SetSecurityDescriptorDacl(&SecDesc, TRUE, NULL, FALSE) // NULL DACL: full access to everyone - && SetSecurityDescriptorOwner(&SecDesc, pTokenUser->User.Sid, FALSE) - ) - { - RecursiveSetOwner(SvcKey, &SecDesc); - } - } - - } - } - } - } - RegCloseKey(SvcKey); - } - - if (pTokenUser) - { - PSID pSid = pTokenUser->User.Sid; - DWORD dwAclSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + ::GetLengthSid(pSid) - sizeof(DWORD); - PACL pDacl = (PACL) new BYTE[dwAclSize]; - if (pDacl) - { - if (TRUE == ::InitializeAcl(pDacl, dwAclSize, ACL_REVISION)) - { - if (TRUE == AddAccessAllowedAceEx(pDacl, ACL_REVISION, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE, WRITE_DAC | KEY_ALL_ACCESS, pSid)) - { - SECURITY_DESCRIPTOR SecDesc; - if (TRUE == ::InitializeSecurityDescriptor(&SecDesc, SECURITY_DESCRIPTOR_REVISION)) - { - if (TRUE == ::SetSecurityDescriptorDacl(&SecDesc, TRUE, pDacl, FALSE)) - { - RecursiveSetDACL (Key, SubKeyName, &SecDesc); - } - } - } - } - delete [] pDacl; - } - } - - if (pTokenUser) - HeapFree(GetProcessHeap(), 0, pTokenUser); - if (Token) - CloseHandle(Token); -} - -void SearchAndDeleteRegistrySubString (HKEY hKey, const wchar_t *subKey, const wchar_t *str, BOOL bEnumSubKeys, const wchar_t* enumMatchSubStr) -{ - HKEY hSubKey = 0; - LSTATUS status = 0; - DWORD dwIndex = 0, dwType, dwValueNameLen, dwDataLen; - std::list subKeysList; - size_t subStringLength = str? wcslen(str) : 0; - - if (bEnumSubKeys) - { - DWORD dwMaxNameLen = 0; - if (ERROR_SUCCESS == RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, &dwMaxNameLen, NULL, NULL, NULL, NULL, NULL, NULL)) - { - dwMaxNameLen++; - wchar_t* szNameValue = new wchar_t[dwMaxNameLen]; - dwIndex = 0; - while (true) - { - dwValueNameLen = dwMaxNameLen; - status = RegEnumKeyExW (hKey, dwIndex++, szNameValue, &dwValueNameLen, NULL, NULL, NULL, NULL); - if (status == ERROR_SUCCESS) - { - if (enumMatchSubStr && !wcsstr(szNameValue, enumMatchSubStr)) - continue; - std::wstring entryName = szNameValue; - entryName += L"\\"; - entryName += subKey; - entryName += L"\\"; - subKeysList.push_back(entryName); - } - else - break; - } - delete [] szNameValue; - } - } - else - { - subKeysList.push_back(subKey); - } - - for (std::list::iterator ItSubKey = subKeysList.begin(); ItSubKey != subKeysList.end(); ItSubKey++) - { - // if the string to search for is empty, delete the sub key, otherwise, look for matching value and delete them - if (subStringLength == 0) - { - if (ERROR_ACCESS_DENIED == DeleteRegistryKey (hKey, ItSubKey->c_str())) - { - // grant permission to delete - AllowKeyAccess (hKey, ItSubKey->c_str()); - - // try again - DeleteRegistryKey (hKey, ItSubKey->c_str()); - } - } - else - { - if (RegOpenKeyExW (hKey, ItSubKey->c_str(), 0, KEY_ALL_ACCESS, &hSubKey) == ERROR_SUCCESS) - { - DWORD dwMaxNameLen = 0, dwMaxDataLen = 0; - if (ERROR_SUCCESS == RegQueryInfoKey(hSubKey, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &dwMaxNameLen, &dwMaxDataLen, NULL, NULL)) - { - dwMaxNameLen++; - wchar_t* szNameValue = new wchar_t[dwMaxNameLen]; - LPBYTE pbData = new BYTE[dwMaxDataLen]; - - std::list foundEntries; - dwIndex = 0; - do - { - dwValueNameLen = dwMaxNameLen; - dwDataLen = dwMaxDataLen; - status = RegEnumValueW(hSubKey, dwIndex++, szNameValue, &dwValueNameLen, NULL, &dwType, pbData, &dwDataLen); - if (status == ERROR_SUCCESS) - { - if ( (wcslen(szNameValue) >= subStringLength && wcsstr(szNameValue, str)) - || (dwType == REG_SZ && wcslen((wchar_t*) pbData) >= subStringLength && wcsstr((wchar_t*) pbData, str)) - ) - { - foundEntries.push_back(szNameValue); - } - } - } while ((status == ERROR_SUCCESS) || (status == ERROR_MORE_DATA)); // we ignore ERROR_MORE_DATA errors since - // we are sure to use the correct sizes - - // delete the entries - if (!foundEntries.empty()) - { - for (std::list::iterator It = foundEntries.begin(); - It != foundEntries.end(); It++) - { - RegDeleteValueW (hSubKey, It->c_str()); - } - } - - delete [] szNameValue; - delete [] pbData; - } - - - RegCloseKey (hSubKey); - } - } - } -} - -/* Set the given privilege of the current process */ -BOOL SetPrivilege(LPTSTR szPrivilegeName, BOOL bEnable) -{ - TOKEN_PRIVILEGES tp; - LUID luid; - HANDLE hProcessToken; - BOOL bStatus = FALSE; - - if ( OpenProcessToken(GetCurrentProcess(), - TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, - &hProcessToken) ) - { - if ( LookupPrivilegeValue( - NULL, - szPrivilegeName, - &luid ) ) - { - - tp.PrivilegeCount = 1; - tp.Privileges[0].Luid = luid; - tp.Privileges[0].Attributes = bEnable? SE_PRIVILEGE_ENABLED : SE_PRIVILEGE_REMOVED; - - // Enable the privilege - bStatus = AdjustTokenPrivileges( - hProcessToken, - FALSE, - &tp, - sizeof(TOKEN_PRIVILEGES), - (PTOKEN_PRIVILEGES) NULL, - (PDWORD) NULL); - } - - CloseHandle(hProcessToken); - } - - return bStatus; -} - -/* - * Creates a VT_LPWSTR propvariant. - * we use our own implementation to use SHStrDupW function pointer - * that we retreive ourselves to avoid dll hijacking attacks - */ -inline HRESULT VCInitPropVariantFromString(__in PCWSTR psz, __out PROPVARIANT *ppropvar) -{ - ppropvar->vt = VT_LPWSTR; - HRESULT hr = VCStrDupW(psz, &ppropvar->pwszVal); - if (FAILED(hr)) - { - PropVariantInit(ppropvar); - } - return hr; -} - -HRESULT CreateLink (wchar_t *lpszPathObj, wchar_t *lpszArguments, - wchar_t *lpszPathLink, const wchar_t* iconFile, int iconIndex) -{ - HRESULT hres; - IShellLink *psl; - - /* Get a pointer to the IShellLink interface. */ - hres = CoCreateInstance (CLSID_ShellLink, NULL, - CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *) &psl); - if (SUCCEEDED (hres)) - { - IPersistFile *ppf; - - /* Set the path to the shortcut target, and add the - description. */ - psl->SetPath (lpszPathObj); - psl->SetArguments (lpszArguments); - if (iconFile) - { - psl->SetIconLocation (iconFile, iconIndex); - } - - // Application ID - if (_tcsstr (lpszPathObj, _T(TC_APP_NAME) _T(".exe"))) - { - IPropertyStore *propStore; - - if (SUCCEEDED (psl->QueryInterface (IID_PPV_ARGS (&propStore)))) - { - PROPVARIANT propVariant; - if (SUCCEEDED (VCInitPropVariantFromString (TC_APPLICATION_ID, &propVariant))) - { - if (SUCCEEDED (propStore->SetValue (PKEY_AppUserModel_ID, propVariant))) - propStore->Commit(); - - PropVariantClear (&propVariant); - } - - propStore->Release(); - } - } - - /* Query IShellLink for the IPersistFile interface for saving - the shortcut in persistent storage. */ - hres = psl->QueryInterface (IID_IPersistFile, - (void **) &ppf); - - if (SUCCEEDED (hres)) - { - /* Save the link by calling IPersistFile::Save. */ - hres = ppf->Save (lpszPathLink, TRUE); - ppf->Release (); - } - psl->Release (); - } - return hres; -} - -BOOL IsSystemRestoreEnabled () -{ - BOOL bEnabled = FALSE; - HKEY hKey; - DWORD dwValue = 0, cbValue = sizeof (DWORD); - wchar_t szRegPath[MAX_PATH]; - GetRestorePointRegKeyName (szRegPath, sizeof (szRegPath)); - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, szRegPath, 0, KEY_READ | KEY_WOW64_64KEY, &hKey) == ERROR_SUCCESS) - { - if (IsOSAtLeast (WIN_VISTA)) - { - if ( (ERROR_SUCCESS == RegQueryValueEx (hKey, L"RPSessionInterval", NULL, NULL, (LPBYTE) &dwValue, &cbValue)) - && (dwValue == 1) - ) - { - bEnabled = TRUE; - } - } - else - { - if ( (ERROR_SUCCESS == RegQueryValueEx (hKey, L"DisableSR", NULL, NULL, (LPBYTE) &dwValue, &cbValue)) - && (dwValue == 0) - ) - { - bEnabled = TRUE; - } - } - - - RegCloseKey (hKey); - } - - return bEnabled; -} - -void GetProgramPath (HWND hwndDlg, wchar_t *path) -{ - ITEMIDLIST *i; - HRESULT res; - - if (bForAllUsers) - res = SHGetSpecialFolderLocation (hwndDlg, CSIDL_COMMON_PROGRAMS, &i); - else - res = SHGetSpecialFolderLocation (hwndDlg, CSIDL_PROGRAMS, &i); - - SHGetPathFromIDList (i, path); -} - -void StatusMessage (HWND hwndDlg, char *stringId) -{ - if (Rollback) - return; - - SendMessageW (GetDlgItem (hwndDlg, IDC_LOG_WINDOW), LB_ADDSTRING, 0, (LPARAM) GetString (stringId)); - - SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_SETTOPINDEX, - SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_GETCOUNT, 0, 0) - 1, 0); -} - -void StatusMessageParam (HWND hwndDlg, char *stringId, wchar_t *param) -{ - wchar_t szTmp[1024]; - - if (Rollback) - return; - - StringCbPrintfW (szTmp, sizeof(szTmp), L"%s %s", GetString (stringId), param); - SendMessageW (GetDlgItem (hwndDlg, IDC_LOG_WINDOW), LB_ADDSTRING, 0, (LPARAM) szTmp); - - SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_SETTOPINDEX, - SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_GETCOUNT, 0, 0) - 1, 0); -} - -void ClearLogWindow (HWND hwndDlg) -{ - SendMessage (GetDlgItem (hwndDlg, IDC_LOG_WINDOW), LB_RESETCONTENT, 0, 0); -} - -void RegMessage (HWND hwndDlg, wchar_t *txt) -{ - StatusMessageParam (hwndDlg, "ADDING_REG", txt); -} - -void CopyMessage (HWND hwndDlg, wchar_t *txt) -{ - StatusMessageParam (hwndDlg, "INSTALLING", txt); -} - -void RemoveMessage (HWND hwndDlg, wchar_t *txt) -{ - if (!Rollback) - StatusMessageParam (hwndDlg, "REMOVING", txt); -} - -void IconMessage (HWND hwndDlg, wchar_t *txt) -{ - StatusMessageParam (hwndDlg, "ADDING_ICON", txt); -} - -void DetermineUpgradeDowngradeStatus (BOOL bCloseDriverHandle, LONG *driverVersionPtr) -{ - LONG driverVersion = VERSION_NUM; - int status = 0; - - if (hDriver == INVALID_HANDLE_VALUE) - status = DriverAttach(); - - if ((status == 0) && (hDriver != INVALID_HANDLE_VALUE)) - { - DWORD dwResult; - BOOL bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVER_VERSION, NULL, 0, &driverVersion, sizeof (driverVersion), &dwResult, NULL); - - if (!bResult) - bResult = DeviceIoControl (hDriver, TC_IOCTL_LEGACY_GET_DRIVER_VERSION, NULL, 0, &driverVersion, sizeof (driverVersion), &dwResult, NULL); - - - bUpgrade = (bResult && driverVersion <= VERSION_NUM); - bDowngrade = (bResult && driverVersion > VERSION_NUM); - bReinstallMode = (bResult && driverVersion == VERSION_NUM); - - PortableMode = DeviceIoControl (hDriver, TC_IOCTL_GET_PORTABLE_MODE_STATUS, NULL, 0, NULL, 0, &dwResult, NULL); - - if (bCloseDriverHandle) - { - CloseHandle (hDriver); - hDriver = INVALID_HANDLE_VALUE; - } - } - - *driverVersionPtr = driverVersion; -} - - -static BOOL IsFileInUse (const wstring &filePath) -{ - HANDLE useTestHandle = CreateFile (filePath.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); - - if (useTestHandle != INVALID_HANDLE_VALUE) - CloseHandle (useTestHandle); - else if (GetLastError() == ERROR_SHARING_VIOLATION) - return TRUE; - - return FALSE; -} - - -BOOL DoFilesInstall (HWND hwndDlg, wchar_t *szDestDir) -{ - /* WARNING: Note that, despite its name, this function is used during UNinstallation as well. */ - - wchar_t szTmp[TC_MAX_PATH]; - BOOL bOK = TRUE; - int i, x, fileNo; - wchar_t curFileName [TC_MAX_PATH] = {0}; - - if (!bUninstall && !bDevm) - { - // Self-extract all files to memory - - GetModuleFileName (NULL, szTmp, ARRAYSIZE (szTmp)); - - if (!SelfExtractInMemory (szTmp)) - return FALSE; - } - - x = wcslen (szDestDir); - if (x < 2) - return FALSE; - - if (szDestDir[x - 1] != L'\\') - StringCbCatW (szDestDir, MAX_PATH, L"\\"); - - for (i = 0; i < sizeof (szFiles) / sizeof (szFiles[0]); i++) - { - BOOL bResult, driver64 = FALSE; - wchar_t szDir[TC_MAX_PATH]; - - if (wcsstr (szFiles[i], L"VeraCrypt Setup") != 0) - { - if (bUninstall) - continue; // Prevent 'access denied' error - - if (bRepairMode) - continue; // Destination = target - } - - // skip files that don't apply to the current architecture - if ( (Is64BitOs () && (wcscmp (szFiles[i], L"AVeraCrypt-x64.exe") == 0)) - || (Is64BitOs () && (wcscmp (szFiles[i], L"AVeraCryptExpander-x64.exe") == 0)) - || (Is64BitOs () && (wcscmp (szFiles[i], L"AVeraCrypt Format-x64.exe") == 0)) - || (!Is64BitOs () && (wcscmp (szFiles[i], L"AVeraCrypt-x86.exe") == 0)) - || (!Is64BitOs () && (wcscmp (szFiles[i], L"AVeraCryptExpander-x86.exe") == 0)) - || (!Is64BitOs () && (wcscmp (szFiles[i], L"AVeraCrypt Format-x86.exe") == 0)) - ) - { - continue; - } - - if (*szFiles[i] == L'A') - StringCbCopyW (szDir, sizeof(szDir), szDestDir); - else if (*szFiles[i] == L'D') - { - if (Is64BitOs ()) - driver64 = TRUE; - - GetSystemDirectory (szDir, ARRAYSIZE (szDir)); - - x = wcslen (szDir); - if (szDir[x - 1] != L'\\') - StringCbCatW (szDir, sizeof(szDir), L"\\"); - - StringCbCatW (szDir, sizeof(szDir), L"Drivers\\"); - } - else if (*szFiles[i] == L'W') - GetWindowsDirectory (szDir, ARRAYSIZE (szDir)); - - if (*szFiles[i] == L'I') - continue; - - StringCbPrintfW (szTmp, sizeof(szTmp), L"%s%s", szDir, szFiles[i] + 1); - - if (bUninstall == FALSE) - CopyMessage (hwndDlg, szTmp); - else - RemoveMessage (hwndDlg, szTmp); - - if (bUninstall == FALSE) - { - SetCurrentDirectory (SetupFilesDir); - - if (wcsstr (szFiles[i], L"VeraCrypt Setup") != 0) - { - // Copy ourselves (the distribution package) to the destination location as 'VeraCrypt Setup.exe' - - wchar_t mp[MAX_PATH]; - - GetModuleFileName (NULL, mp, ARRAYSIZE (mp)); - bResult = TCCopyFile (mp, szTmp); - } - else - { - StringCchCopyNW (curFileName, ARRAYSIZE(curFileName), szFiles[i] + 1, wcslen (szFiles[i]) - 1); - curFileName [wcslen (szFiles[i]) - 1] = 0; - - if (Is64BitOs () - && wcscmp (szFiles[i], L"Dveracrypt.sys") == 0) - { - StringCbCopyNW (curFileName, sizeof(curFileName), FILENAME_64BIT_DRIVER, sizeof (FILENAME_64BIT_DRIVER)); - } - - if (Is64BitOs () - && wcscmp (szFiles[i], L"AVeraCrypt.exe") == 0) - { - StringCbCopyNW (curFileName, sizeof(curFileName), L"VeraCrypt-x64.exe", sizeof (L"VeraCrypt-x64.exe")); - } - - if (Is64BitOs () - && wcscmp (szFiles[i], L"AVeraCrypt-x86.exe") == 0) - { - StringCbCopyNW (curFileName, sizeof(curFileName), L"VeraCrypt.exe", sizeof (L"VeraCrypt.exe")); - } - - if (Is64BitOs () - && wcscmp (szFiles[i], L"AVeraCryptExpander.exe") == 0) - { - StringCbCopyNW (curFileName, sizeof(curFileName), L"VeraCryptExpander-x64.exe", sizeof (L"VeraCryptExpander-x64.exe")); - } - - if (Is64BitOs () - && wcscmp (szFiles[i], L"AVeraCryptExpander-x86.exe") == 0) - { - StringCbCopyNW (curFileName, sizeof(curFileName), L"VeraCryptExpander.exe", sizeof (L"VeraCryptExpander.exe")); - } - - if (Is64BitOs () - && wcscmp (szFiles[i], L"AVeraCrypt Format.exe") == 0) - { - StringCbCopyNW (curFileName, sizeof(curFileName), L"VeraCrypt Format-x64.exe", sizeof (L"VeraCrypt Format-x64.exe")); - } - - if (Is64BitOs () - && wcscmp (szFiles[i], L"AVeraCrypt Format-x86.exe") == 0) - { - StringCbCopyNW (curFileName, sizeof(curFileName), L"VeraCrypt Format.exe", sizeof (L"VeraCrypt Format.exe")); - } - - if (!bDevm) - { - bResult = FALSE; - - // Find the correct decompressed file in memory - for (fileNo = 0; fileNo < NBR_COMPRESSED_FILES; fileNo++) - { - // Write the file (stored in memory) directly to the destination location - // (there will be no temporary files). - if (wmemcmp ( - curFileName, - Decompressed_Files[fileNo].fileName, - min (wcslen (curFileName), (size_t) Decompressed_Files[fileNo].fileNameLength)) == 0) - { - // Dump filter driver cannot be installed to SysWOW64 directory - if (driver64 && !EnableWow64FsRedirection (FALSE)) - { - handleWin32Error (hwndDlg, SRC_POS); - bResult = FALSE; - goto err; - } - - bResult = SaveBufferToFile ( - (char *) Decompressed_Files[fileNo].fileContent, - szTmp, - Decompressed_Files[fileNo].fileLength, - FALSE, - TRUE); - - if (driver64) - { - if (!EnableWow64FsRedirection (TRUE)) - { - handleWin32Error (hwndDlg, SRC_POS); - bResult = FALSE; - goto err; - } - - if (!bResult) - goto err; - - } - - break; - } - } - } - else - { - if (driver64) - EnableWow64FsRedirection (FALSE); - - bResult = TCCopyFile (curFileName, szTmp); - - if (driver64) - EnableWow64FsRedirection (TRUE); - } - - if (bResult && wcscmp (szFiles[i], L"AVeraCrypt.exe") == 0) - { - if (Is64BitOs ()) - EnableWow64FsRedirection (FALSE); - - wstring servicePath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", false); - wstring serviceLegacyPath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", true); - wstring favoritesFile = GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false); - wstring favoritesLegacyFile = GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, true); - - if ( FileExists (servicePath.c_str()) - || (Is64BitOs () && FileExists (serviceLegacyPath.c_str())) - ) - { - CopyMessage (hwndDlg, (wchar_t *) servicePath.c_str()); - bResult = CopyFile (szTmp, servicePath.c_str(), FALSE); - } - - if (bResult && Is64BitOs () - && FileExists (favoritesLegacyFile.c_str()) - && !FileExists (favoritesFile.c_str())) - { - // copy the favorites XML file to the native system directory - bResult = CopyFile (favoritesLegacyFile.c_str(), favoritesFile.c_str(), FALSE); - } - - if (bResult && Is64BitOs () && FileExists (favoritesFile.c_str()) && FileExists (servicePath.c_str())) - { - // Update the path of the service - BootEncryption BootEncObj (hwndDlg); - - try - { - if (BootEncObj.GetDriverServiceStartType() == SERVICE_BOOT_START) - { - BootEncObj.UpdateSystemFavoritesService (); - } - } - catch (...) {} - } - - if (Is64BitOs ()) - { - // delete files from legacy path - if (FileExists (favoritesLegacyFile.c_str())) - { - RemoveMessage (hwndDlg, (wchar_t *) favoritesLegacyFile.c_str()); - ForceDeleteFile (favoritesLegacyFile.c_str()); - } - - if (FileExists (serviceLegacyPath.c_str())) - { - RemoveMessage (hwndDlg, (wchar_t *) serviceLegacyPath.c_str()); - ForceDeleteFile (serviceLegacyPath.c_str()); - } - - EnableWow64FsRedirection (TRUE); - } - } - } - } - else - { - if (driver64) - EnableWow64FsRedirection (FALSE); - bResult = StatDeleteFile (szTmp, TRUE); - if (driver64) - EnableWow64FsRedirection (TRUE); - - if (bResult && wcscmp (szFiles[i], L"AVeraCrypt.exe") == 0) - { - if (Is64BitOs ()) - EnableWow64FsRedirection (FALSE); - - wstring servicePath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", false); - wstring serviceLegacyPath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", true); - wstring favoritesFile = GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false); - wstring favoritesLegacyFile = GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, true); - - // delete all files related to system favorites service - if (FileExists (favoritesFile.c_str())) - { - RemoveMessage (hwndDlg, (wchar_t *) favoritesFile.c_str()); - ForceDeleteFile (favoritesFile.c_str()); - } - - if (FileExists (servicePath.c_str())) - { - RemoveMessage (hwndDlg, (wchar_t *) servicePath.c_str()); - ForceDeleteFile (servicePath.c_str()); - } - - if (Is64BitOs ()) - { - if (FileExists (favoritesLegacyFile.c_str())) - { - RemoveMessage (hwndDlg, (wchar_t *) favoritesLegacyFile.c_str()); - ForceDeleteFile (favoritesLegacyFile.c_str()); - } - - if (FileExists (serviceLegacyPath.c_str())) - { - RemoveMessage (hwndDlg, (wchar_t *) serviceLegacyPath.c_str()); - ForceDeleteFile (serviceLegacyPath.c_str()); - } - - EnableWow64FsRedirection (TRUE); - } - } - } - -err: - if (bResult == FALSE) - { - LPVOID lpMsgBuf; - DWORD dwError = GetLastError (); - wchar_t szTmp2[700]; - wchar_t szErrorValue[16]; - wchar_t* pszDesc; - - FormatMessage ( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - dwError, - MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ - (wchar_t *) &lpMsgBuf, - 0, - NULL - ); - - if (lpMsgBuf) - pszDesc = (wchar_t*) lpMsgBuf; - else - { - StringCbPrintfW (szErrorValue, sizeof (szErrorValue), L"0x%.8X", dwError); - pszDesc = szErrorValue; - } - - if (bUninstall == FALSE) - StringCbPrintfW (szTmp2, sizeof(szTmp2), GetString ("INSTALL_OF_FAILED"), szTmp, pszDesc); - else - StringCbPrintfW (szTmp2, sizeof(szTmp2), GetString ("UNINSTALL_OF_FAILED"), szTmp, pszDesc); - - if (lpMsgBuf) LocalFree (lpMsgBuf); - - if (!Silent && MessageBoxW (hwndDlg, szTmp2, lpszTitle, MB_YESNO | MB_ICONHAND) != IDYES) - return FALSE; - } - } - - // Language pack - if (bUninstall == FALSE) - { - WIN32_FIND_DATA f; - HANDLE h; - - SetCurrentDirectory (SetupFilesDir); - h = FindFirstFile (L"Language.*.xml", &f); - - if (h != INVALID_HANDLE_VALUE) - { - wchar_t d[MAX_PATH*2]; - StringCbPrintfW (d, sizeof(d), L"%s%s", szDestDir, f.cFileName); - CopyMessage (hwndDlg, d); - TCCopyFile (f.cFileName, d); - FindClose (h); - } - - SetCurrentDirectory (SetupFilesDir); - SetCurrentDirectory (L"Setup files"); - h = FindFirstFile (L"VeraCrypt User Guide.*.pdf", &f); - if (h != INVALID_HANDLE_VALUE) - { - wchar_t d[MAX_PATH*2]; - StringCbPrintfW (d, sizeof(d), L"%s%s", szDestDir, f.cFileName); - CopyMessage (hwndDlg, d); - TCCopyFile (f.cFileName, d); - FindClose (h); - } - SetCurrentDirectory (SetupFilesDir); - } - - return bOK; -} - -BOOL DoRegInstall (HWND hwndDlg, wchar_t *szDestDir, BOOL bInstallType) -{ - wchar_t szDir[TC_MAX_PATH], *key; - wchar_t szTmp[TC_MAX_PATH*4]; - HKEY hkey = 0; - BOOL bSlash, bOK = FALSE; - DWORD dw; - int x; - - if (SystemEncryptionUpdate) - { - if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VeraCrypt", - 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_WOW64_32KEY, NULL, &hkey, &dw) == ERROR_SUCCESS) - { - StringCbCopyW (szTmp, sizeof(szTmp), _T(VERSION_STRING)); - RegSetValueEx (hkey, L"DisplayVersion", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)); - - StringCbCopyW (szTmp, sizeof(szTmp), _T(TC_HOMEPAGE)); - RegSetValueEx (hkey, L"URLInfoAbout", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)); - - RegCloseKey (hkey); - } - - return TRUE; - } - - StringCbCopyW (szDir, sizeof(szDir), szDestDir); - x = wcslen (szDestDir); - if (szDestDir[x - 1] == L'\\') - bSlash = TRUE; - else - bSlash = FALSE; - - if (bSlash == FALSE) - StringCbCatW (szDir, sizeof(szDir), L"\\"); - - if (bInstallType) - { - - key = L"Software\\Classes\\VeraCryptVolume"; - RegMessage (hwndDlg, key); - if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, - key, - 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &dw) != ERROR_SUCCESS) - goto error; - - StringCbCopyW (szTmp, sizeof(szTmp), L"VeraCrypt Volume"); - if (RegSetValueEx (hkey, L"", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) - goto error; - - StringCbPrintfW (szTmp, sizeof(szTmp), L"%ws", TC_APPLICATION_ID); - if (RegSetValueEx (hkey, L"AppUserModelID", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) - goto error; - - RegCloseKey (hkey); - hkey = 0; - - key = L"Software\\Classes\\VeraCryptVolume\\DefaultIcon"; - RegMessage (hwndDlg, key); - if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, - key, - 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &dw) != ERROR_SUCCESS) - goto error; - - StringCbPrintfW (szTmp, sizeof(szTmp), L"%sVeraCrypt.exe,1", szDir); - if (RegSetValueEx (hkey, L"", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) - goto error; - - RegCloseKey (hkey); - hkey = 0; - - key = L"Software\\Classes\\VeraCryptVolume\\Shell\\open\\command"; - RegMessage (hwndDlg, key); - if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, - key, - 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &dw) != ERROR_SUCCESS) - goto error; - - StringCbPrintfW (szTmp, sizeof(szTmp), L"\"%sVeraCrypt.exe\" /v \"%%1\"", szDir ); - if (RegSetValueEx (hkey, L"", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) - goto error; - - RegCloseKey (hkey); - hkey = 0; - - key = L"Software\\Classes\\.hc"; - BOOL typeClassChanged = TRUE; - wchar_t typeClass[256]; - DWORD typeClassSize = sizeof (typeClass); - - if (ReadLocalMachineRegistryString (key, L"", typeClass, &typeClassSize) && typeClassSize > 0 && wcscmp (typeClass, L"VeraCryptVolume") == 0) - typeClassChanged = FALSE; - - RegMessage (hwndDlg, key); - if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, - key, - 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &dw) != ERROR_SUCCESS) - goto error; - - StringCbCopyW (szTmp, sizeof(szTmp), L"VeraCryptVolume"); - if (RegSetValueEx (hkey, L"", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) - goto error; - - RegCloseKey (hkey); - hkey = 0; - - if (typeClassChanged) - SHChangeNotify (SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); - } - - key = L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VeraCrypt"; - RegMessage (hwndDlg, key); - if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, - key, - 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_WOW64_32KEY, NULL, &hkey, &dw) != ERROR_SUCCESS) - goto error; - - /* IMPORTANT: IF YOU CHANGE THIS IN ANY WAY, REVISE AND UPDATE SetInstallationPath() ACCORDINGLY! */ - StringCbPrintfW (szTmp, sizeof(szTmp), L"\"%sVeraCrypt Setup.exe\" /u", szDir); - if (RegSetValueEx (hkey, L"UninstallString", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) - goto error; - - StringCbPrintfW (szTmp, sizeof(szTmp), L"\"%sVeraCrypt Setup.exe\" /c", szDir); - if (RegSetValueEx (hkey, L"ModifyPath", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) - goto error; - - StringCbPrintfW (szTmp, sizeof(szTmp), L"\"%sVeraCrypt Setup.exe\"", szDir); - if (RegSetValueEx (hkey, L"DisplayIcon", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) - goto error; - - StringCbCopyW (szTmp, sizeof(szTmp), _T(VERSION_STRING)); - if (RegSetValueEx (hkey, L"DisplayVersion", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) - goto error; - - StringCbCopyW (szTmp, sizeof(szTmp), L"VeraCrypt"); - if (RegSetValueEx (hkey, L"DisplayName", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) - goto error; - - StringCbCopyW (szTmp, sizeof(szTmp), L"IDRIX"); - if (RegSetValueEx (hkey, L"Publisher", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) - goto error; - - StringCbCopyW (szTmp, sizeof(szTmp), _T(TC_HOMEPAGE)); - if (RegSetValueEx (hkey, L"URLInfoAbout", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) - goto error; - - bOK = TRUE; - -error: - if (hkey != 0) - RegCloseKey (hkey); - - if (bOK == FALSE) - { - handleWin32Error (hwndDlg, SRC_POS); - Error ("REG_INSTALL_FAILED", hwndDlg); - } - - // Register COM servers for UAC - if (IsOSAtLeast (WIN_VISTA)) - { - if (!RegisterComServers (szDir)) - { - Error ("COM_REG_FAILED", hwndDlg); - return FALSE; - } - } - - return bOK; -} - -BOOL DoApplicationDataUninstall (HWND hwndDlg) -{ - wchar_t path[MAX_PATH]; - wchar_t path2[MAX_PATH]; - BOOL bOK = TRUE; - - StatusMessage (hwndDlg, "REMOVING_APPDATA"); - - SHGetFolderPath (NULL, CSIDL_APPDATA, NULL, 0, path); - StringCbCatW (path, sizeof(path), L"\\VeraCrypt\\"); - - // Delete favorite volumes file - StringCbPrintfW (path2, sizeof(path2), L"%s%s", path, TC_APPD_FILENAME_FAVORITE_VOLUMES); - RemoveMessage (hwndDlg, path2); - StatDeleteFile (path2, FALSE); - - // Delete keyfile defaults - StringCbPrintfW (path2, sizeof(path2), L"%s%s", path, TC_APPD_FILENAME_DEFAULT_KEYFILES); - RemoveMessage (hwndDlg, path2); - StatDeleteFile (path2, FALSE); - - // Delete history file - StringCbPrintfW (path2, sizeof(path2), L"%s%s", path, TC_APPD_FILENAME_HISTORY); - RemoveMessage (hwndDlg, path2); - StatDeleteFile (path2, FALSE); - - // Delete configuration file - StringCbPrintfW (path2, sizeof(path2), L"%s%s", path, TC_APPD_FILENAME_CONFIGURATION); - RemoveMessage (hwndDlg, path2); - StatDeleteFile (path2, FALSE); - - // Delete system encryption configuration file - StringCbPrintfW (path2, sizeof(path2), L"%s%s", path, TC_APPD_FILENAME_SYSTEM_ENCRYPTION); - RemoveMessage (hwndDlg, path2); - StatDeleteFile (path2, FALSE); - - SHGetFolderPath (NULL, CSIDL_APPDATA, NULL, 0, path); - StringCbCatW (path, sizeof(path), L"\\VeraCrypt"); - RemoveMessage (hwndDlg, path); - if (!StatRemoveDirectory (path)) - { - handleWin32Error (hwndDlg, SRC_POS); - bOK = FALSE; - } - - // remove VeraCrypt under common appdata - if (SUCCEEDED (SHGetFolderPath (NULL, CSIDL_COMMON_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, path))) - { - StringCbCatW (path, sizeof(path), L"\\VeraCrypt"); - - // Delete original bootloader - StringCbPrintfW (path2, sizeof(path2), L"%s\\%s", path, TC_SYS_BOOT_LOADER_BACKUP_NAME); - RemoveMessage (hwndDlg, path2); - StatDeleteFile (path2, FALSE); - - // remove VeraCrypt folder - RemoveMessage (hwndDlg, path); - StatRemoveDirectory (path); - } - - - return bOK; -} - -BOOL DoRegUninstall (HWND hwndDlg, BOOL bRemoveDeprecated) -{ - wchar_t regk [64]; - typedef LSTATUS (WINAPI *RegDeleteKeyExWFn) (HKEY hKey,LPCWSTR lpSubKey,REGSAM samDesired,WORD Reserved); - RegDeleteKeyExWFn RegDeleteKeyExWPtr = NULL; - HMODULE hAdvapiDll = LoadLibrary (L"Advapi32.dll"); - if (hAdvapiDll) - { - RegDeleteKeyExWPtr = (RegDeleteKeyExWFn) GetProcAddress(hAdvapiDll, "RegDeleteKeyExW"); - } - - // Unregister COM servers - if (!bRemoveDeprecated && IsOSAtLeast (WIN_VISTA)) - { - if (!UnregisterComServers (InstallationPath)) - StatusMessage (hwndDlg, "COM_DEREG_FAILED"); - } - - if (!bRemoveDeprecated) - StatusMessage (hwndDlg, "REMOVING_REG"); - - if (RegDeleteKeyExWPtr) - { - RegDeleteKeyExWPtr (HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VeraCrypt", KEY_WOW64_32KEY, 0); - RegDeleteKeyExWPtr (HKEY_CURRENT_USER, L"Software\\VeraCrypt", KEY_WOW64_32KEY, 0); - } - else - { - RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VeraCrypt"); - RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\VeraCrypt"); - } - RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume\\Shell\\open\\command"); - RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume\\Shell\\open"); - RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume\\Shell"); - RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume\\DefaultIcon"); - RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume"); - - if (!bRemoveDeprecated) - { - HKEY hKey; - GetStartupRegKeyName (regk, sizeof(regk)); - DeleteRegistryValue (regk, L"VeraCrypt"); - - DeleteRegistryKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\.hc"); - - // enable the SE_TAKE_OWNERSHIP_NAME privilege for this operation - SetPrivilege (SE_TAKE_OWNERSHIP_NAME, TRUE); - - // clean MuiCache list from VeraCrypt entries - SearchAndDeleteRegistrySubString (HKEY_CLASSES_ROOT, L"Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache", L"VeraCrypt", FALSE, NULL); - - // clean other VeraCrypt entries from all users - SearchAndDeleteRegistrySubString (HKEY_USERS, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.hc", NULL, TRUE, NULL); - SearchAndDeleteRegistrySubString (HKEY_USERS, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Compatibility Assistant\\Persisted", L"VeraCrypt", TRUE, NULL); - SearchAndDeleteRegistrySubString (HKEY_USERS, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartPage\\NewShortcuts", L"VeraCrypt", TRUE, NULL); - - if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SYSTEM", 0, KEY_ALL_ACCESS | WRITE_DAC | WRITE_OWNER, &hKey) == ERROR_SUCCESS) - { - SearchAndDeleteRegistrySubString (hKey, L"Enum\\Root\\LEGACY_VERACRYPT", NULL, TRUE, L"ControlSet"); - SearchAndDeleteRegistrySubString (hKey, L"services\\veracrypt", NULL, TRUE, L"ControlSet"); - RegCloseKey(hKey); - } - - // disable the SE_TAKE_OWNERSHIP_NAME privilege for this operation - SetPrivilege (SE_TAKE_OWNERSHIP_NAME, FALSE); - - SHChangeNotify (SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); - } - - if (hAdvapiDll) - FreeLibrary (hAdvapiDll); - - return TRUE; -} - - -BOOL DoServiceUninstall (HWND hwndDlg, wchar_t *lpszService) -{ - SC_HANDLE hManager, hService = NULL; - BOOL bOK = FALSE, bRet; - SERVICE_STATUS status; - BOOL firstTry = TRUE; - int x; - - memset (&status, 0, sizeof (status)); /* Keep VC6 quiet */ - -retry: - - hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (hManager == NULL) - goto error; - - hService = OpenService (hManager, lpszService, SERVICE_ALL_ACCESS); - if (hService == NULL) - goto error; - - if (wcscmp (L"veracrypt", lpszService) == 0) - { - try - { - BootEncryption bootEnc (hwndDlg); - if (bootEnc.GetDriverServiceStartType() == SERVICE_BOOT_START) - { - try { bootEnc.RegisterFilterDriver (false, BootEncryption::DriveFilter); } catch (...) { } - try { bootEnc.RegisterFilterDriver (false, BootEncryption::VolumeFilter); } catch (...) { } - try { bootEnc.RegisterFilterDriver (false, BootEncryption::DumpFilter); } catch (...) { } - } - } - catch (...) { } - - StatusMessage (hwndDlg, "STOPPING_DRIVER"); - } - else - StatusMessageParam (hwndDlg, "STOPPING", lpszService); - -#define WAIT_PERIOD 3 - - for (x = 0; x < WAIT_PERIOD; x++) - { - bRet = QueryServiceStatus (hService, &status); - if (bRet != TRUE) - goto error; - - if (status.dwCurrentState != SERVICE_START_PENDING && - status.dwCurrentState != SERVICE_STOP_PENDING && - status.dwCurrentState != SERVICE_CONTINUE_PENDING) - break; - - Sleep (1000); - } - - if (status.dwCurrentState != SERVICE_STOPPED) - { - bRet = ControlService (hService, SERVICE_CONTROL_STOP, &status); - if (bRet == FALSE) - goto try_delete; - - for (x = 0; x < WAIT_PERIOD; x++) - { - bRet = QueryServiceStatus (hService, &status); - if (bRet != TRUE) - goto error; - - if (status.dwCurrentState != SERVICE_START_PENDING && - status.dwCurrentState != SERVICE_STOP_PENDING && - status.dwCurrentState != SERVICE_CONTINUE_PENDING) - break; - - Sleep (1000); - } - - if (status.dwCurrentState != SERVICE_STOPPED && status.dwCurrentState != SERVICE_STOP_PENDING) - goto error; - } - -try_delete: - - if (wcscmp (L"veracrypt", lpszService) == 0) - StatusMessage (hwndDlg, "REMOVING_DRIVER"); - else - StatusMessageParam (hwndDlg, "REMOVING", lpszService); - - if (hService != NULL) - { - CloseServiceHandle (hService); - hService = NULL; - } - - if (hManager != NULL) - { - CloseServiceHandle (hManager); - hManager = NULL; - } - - hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); - if (hManager == NULL) - goto error; - - hService = OpenService (hManager, lpszService, SERVICE_ALL_ACCESS); - if (hService == NULL) - goto error; - - bRet = DeleteService (hService); - if (bRet == FALSE) - { - if (firstTry && GetLastError () == ERROR_SERVICE_MARKED_FOR_DELETE) - { - // Second try for an eventual no-install driver instance - CloseServiceHandle (hService); - CloseServiceHandle (hManager); - hService = NULL; - hManager = NULL; - - Sleep(1000); - firstTry = FALSE; - goto retry; - } - - goto error; - } - - bOK = TRUE; - -error: - - if (bOK == FALSE && GetLastError ()!= ERROR_SERVICE_DOES_NOT_EXIST) - { - handleWin32Error (hwndDlg, SRC_POS); - MessageBoxW (hwndDlg, GetString ("DRIVER_UINSTALL_FAILED"), lpszTitle, MB_ICONHAND); - } - else - bOK = TRUE; - - if (hService != NULL) - CloseServiceHandle (hService); - - if (hManager != NULL) - CloseServiceHandle (hManager); - - return bOK; -} - - -BOOL DoDriverUnload (HWND hwndDlg) -{ - BOOL bOK = TRUE; - int status; - - status = DriverAttach (); - if (status != 0) - { - if (status == ERR_OS_ERROR && GetLastError () != ERROR_FILE_NOT_FOUND) - { - handleWin32Error (hwndDlg, SRC_POS); - AbortProcess ("NODRIVER"); - } - - if (status != ERR_OS_ERROR) - { - handleError (NULL, status, SRC_POS); - AbortProcess ("NODRIVER"); - } - } - - if (hDriver != INVALID_HANDLE_VALUE) - { - MOUNT_LIST_STRUCT driver; - LONG driverVersion = VERSION_NUM; - int refCount; - DWORD dwResult; - BOOL bResult; - - // Try to determine if it's upgrade (and not reinstall, downgrade, or first-time install). - DetermineUpgradeDowngradeStatus (FALSE, &driverVersion); - - // Test for encrypted boot drive - try - { - BootEncryption bootEnc (hwndDlg); - if (bootEnc.GetDriverServiceStartType() == SERVICE_BOOT_START) - { - try - { - // Check hidden OS update consistency - if (IsHiddenOSRunning()) - { - if (bootEnc.GetInstalledBootLoaderVersion() != VERSION_NUM) - { - if (AskWarnNoYes ("UPDATE_TC_IN_DECOY_OS_FIRST", hwndDlg) == IDNO) - AbortProcessSilent (); - } - } - } - catch (...) { } - - if (bUninstallInProgress && !bootEnc.GetStatus().DriveMounted) - { - try { bootEnc.RegisterFilterDriver (false, BootEncryption::DriveFilter); } catch (...) { } - try { bootEnc.RegisterFilterDriver (false, BootEncryption::VolumeFilter); } catch (...) { } - try { bootEnc.RegisterFilterDriver (false, BootEncryption::DumpFilter); } catch (...) { } - bootEnc.SetDriverServiceStartType (SERVICE_SYSTEM_START); - } - else if (bUninstallInProgress || bDowngrade) - { - Error (bDowngrade ? "SETUP_FAILED_BOOT_DRIVE_ENCRYPTED_DOWNGRADE" : "SETUP_FAILED_BOOT_DRIVE_ENCRYPTED", hwndDlg); - return FALSE; - } - else - { - if (CurrentOSMajor == 6 && CurrentOSMinor == 0 && CurrentOSServicePack < 1) - AbortProcess ("SYS_ENCRYPTION_UPGRADE_UNSUPPORTED_ON_VISTA_SP0"); - - SystemEncryptionUpdate = TRUE; - PortableMode = FALSE; - } - } - } - catch (...) { } - - if (!bUninstall - && (bUpgrade || SystemEncryptionUpdate) - && (!bDevm || SystemEncryptionUpdate)) - { - UnloadDriver = FALSE; - } - - if (PortableMode && !SystemEncryptionUpdate) - UnloadDriver = TRUE; - - if (UnloadDriver) - { - int volumesMounted = 0; - - // Check mounted volumes - bResult = DeviceIoControl (hDriver, TC_IOCTL_IS_ANY_VOLUME_MOUNTED, NULL, 0, &volumesMounted, sizeof (volumesMounted), &dwResult, NULL); - - if (!bResult) - { - bResult = DeviceIoControl (hDriver, TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES, NULL, 0, &driver, sizeof (driver), &dwResult, NULL); - if (bResult) - volumesMounted = driver.ulMountedDrives; - } - - if (bResult) - { - if (volumesMounted != 0) - { - bOK = FALSE; - MessageBoxW (hwndDlg, GetString ("DISMOUNT_ALL_FIRST"), lpszTitle, MB_ICONHAND); - } - } - else - { - bOK = FALSE; - handleWin32Error (hwndDlg, SRC_POS); - } - } - - // Try to close all open TC windows - if (bOK) - { - BOOL TCWindowClosed = FALSE; - - EnumWindows (CloseTCWindowsEnum, (LPARAM) &TCWindowClosed); - - if (TCWindowClosed) - Sleep (2000); - } - - // Test for any applications attached to driver - if (!bUpgrade) - { - bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DEVICE_REFCOUNT, &refCount, sizeof (refCount), &refCount, - sizeof (refCount), &dwResult, NULL); - - if (bOK && bResult && refCount > 1) - { - MessageBoxW (hwndDlg, GetString ("CLOSE_TC_FIRST"), lpszTitle, MB_ICONSTOP); - bOK = FALSE; - } - } - - if (!bOK || UnloadDriver) - { - CloseHandle (hDriver); - hDriver = INVALID_HANDLE_VALUE; - } - } - else - { - // Note that the driver may have already been unloaded during this session (e.g. retry after an error, etc.) so it is not - // guaranteed that the user is installing VeraCrypt for the first time now (we also cannot know if the user has already - // installed and used VeraCrypt on another system before). - bPossiblyFirstTimeInstall = TRUE; - } - - return bOK; -} - - -BOOL UpgradeBootLoader (HWND hwndDlg) -{ - if (!SystemEncryptionUpdate) - return TRUE; - - try - { - BootEncryption bootEnc (hwndDlg); - uint64 bootLoaderVersion = bootEnc.GetInstalledBootLoaderVersion(); - if ((bootLoaderVersion < VERSION_NUM) || (bReinstallMode && (bootLoaderVersion == VERSION_NUM))) - { - StatusMessage (hwndDlg, "INSTALLER_UPDATING_BOOT_LOADER"); - - bootEnc.InstallBootLoader (true); - - if (bootEnc.GetInstalledBootLoaderVersion() <= TC_RESCUE_DISK_UPGRADE_NOTICE_MAX_VERSION) - Info (IsHiddenOSRunning() ? "BOOT_LOADER_UPGRADE_OK_HIDDEN_OS" : "BOOT_LOADER_UPGRADE_OK", hwndDlg); - } - return TRUE; - } - catch (Exception &e) - { - e.Show (hwndDlg); - } - catch (...) { } - - Error ("BOOT_LOADER_UPGRADE_FAILED", hwndDlg); - return FALSE; -} - - -BOOL DoShortcutsUninstall (HWND hwndDlg, wchar_t *szDestDir) -{ - wchar_t szLinkDir[TC_MAX_PATH]; - wchar_t szTmp2[TC_MAX_PATH]; - BOOL bSlash, bOK = FALSE; - HRESULT hOle; - int x; - BOOL allUsers = FALSE; - - hOle = OleInitialize (NULL); - - // User start menu - SHGetSpecialFolderPath (hwndDlg, szLinkDir, CSIDL_PROGRAMS, 0); - x = wcslen (szLinkDir); - if (szLinkDir[x - 1] == L'\\') - bSlash = TRUE; - else - bSlash = FALSE; - - if (bSlash == FALSE) - StringCbCatW (szLinkDir, sizeof(szLinkDir), L"\\"); - - StringCbCatW (szLinkDir, sizeof(szLinkDir), L"VeraCrypt"); - - // Global start menu - { - struct _stat st; - wchar_t path[TC_MAX_PATH]; - - SHGetSpecialFolderPath (hwndDlg, path, CSIDL_COMMON_PROGRAMS, 0); - StringCbCatW (path, sizeof(path), L"\\VeraCrypt"); - - if (_wstat (path, &st) == 0) - { - StringCbCopyW (szLinkDir, sizeof(szLinkDir), path); - allUsers = TRUE; - } - } - - // Start menu entries - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt.lnk"); - RemoveMessage (hwndDlg, szTmp2); - if (StatDeleteFile (szTmp2, FALSE) == FALSE) - goto error; - - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCryptExpander.lnk"); - RemoveMessage (hwndDlg, szTmp2); - if (StatDeleteFile (szTmp2, FALSE) == FALSE) - goto error; - - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt Website.url"); - RemoveMessage (hwndDlg, szTmp2); - if (StatDeleteFile (szTmp2, FALSE) == FALSE) - goto error; - - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\Uninstall VeraCrypt.lnk"); - RemoveMessage (hwndDlg, szTmp2); - if (StatDeleteFile (szTmp2, FALSE) == FALSE) - goto error; - - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt User's Guide.lnk"); - StatDeleteFile (szTmp2, FALSE); - - // Start menu group - RemoveMessage ((HWND) hwndDlg, szLinkDir); - if (StatRemoveDirectory (szLinkDir) == FALSE) - handleWin32Error ((HWND) hwndDlg, SRC_POS); - - // Desktop icon - - if (allUsers) - SHGetSpecialFolderPath (hwndDlg, szLinkDir, CSIDL_COMMON_DESKTOPDIRECTORY, 0); - else - SHGetSpecialFolderPath (hwndDlg, szLinkDir, CSIDL_DESKTOPDIRECTORY, 0); - - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt.lnk"); - - RemoveMessage (hwndDlg, szTmp2); - if (StatDeleteFile (szTmp2, FALSE) == FALSE) - goto error; - - bOK = TRUE; - -error: - OleUninitialize (); - - return bOK; -} - -BOOL DoShortcutsInstall (HWND hwndDlg, wchar_t *szDestDir, BOOL bProgGroup, BOOL bDesktopIcon) -{ - wchar_t szLinkDir[TC_MAX_PATH], szDir[TC_MAX_PATH]; - wchar_t szTmp[TC_MAX_PATH], szTmp2[TC_MAX_PATH], szTmp3[TC_MAX_PATH]; - BOOL bSlash, bOK = FALSE; - HRESULT hOle; - int x; - - if (bProgGroup == FALSE && bDesktopIcon == FALSE) - return TRUE; - - hOle = OleInitialize (NULL); - - GetProgramPath (hwndDlg, szLinkDir); - - x = wcslen (szLinkDir); - if (szLinkDir[x - 1] == L'\\') - bSlash = TRUE; - else - bSlash = FALSE; - - if (bSlash == FALSE) - StringCbCatW (szLinkDir, sizeof(szLinkDir), L"\\"); - - StringCbCatW (szLinkDir, sizeof(szLinkDir), L"VeraCrypt"); - - StringCbCopyW (szDir, sizeof(szDir), szDestDir); - x = wcslen (szDestDir); - if (szDestDir[x - 1] == L'\\') - bSlash = TRUE; - else - bSlash = FALSE; - - if (bSlash == FALSE) - StringCbCatW (szDir, sizeof(szDir), L"\\"); - - if (bProgGroup) - { - FILE *f; - - if (mkfulldir (szLinkDir, TRUE) != 0) - { - if (mkfulldir (szLinkDir, FALSE) != 0) - { - wchar_t szTmpW[TC_MAX_PATH]; - - handleWin32Error (hwndDlg, SRC_POS); - StringCbPrintfW (szTmpW, sizeof(szTmpW), GetString ("CANT_CREATE_FOLDER"), szLinkDir); - MessageBoxW (hwndDlg, szTmpW, lpszTitle, MB_ICONHAND); - goto error; - } - } - - StringCbPrintfW (szTmp, sizeof(szTmp), L"%s%s", szDir, L"VeraCrypt.exe"); - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt.lnk"); - - IconMessage (hwndDlg, szTmp2); - if (CreateLink (szTmp, L"", szTmp2, NULL, -1) != S_OK) - goto error; - - StringCbPrintfW (szTmp, sizeof(szTmp), L"%s%s", szDir, L"VeraCryptExpander.exe"); - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCryptExpander.lnk"); - - IconMessage (hwndDlg, szTmp2); - if (CreateLink (szTmp, L"", szTmp2, NULL, -1) != S_OK) - goto error; - - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt Website.url"); - IconMessage (hwndDlg, szTmp2); - f = _wfopen (szTmp2, L"w"); - if (f) - { - fprintf (f, "[InternetShortcut]\nURL=%s\n", TC_APPLINK); - - CheckFileStreamWriteErrors (hwndDlg, f, szTmp2); - fclose (f); - } - else - goto error; - - StringCbPrintfW (szTmp, sizeof(szTmp), L"%s%s", szDir, L"VeraCrypt Setup.exe"); - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\Uninstall VeraCrypt.lnk"); - if (GetSystemDirectory (szTmp3, ARRAYSIZE(szTmp3))) - { - StringCbCatW (szTmp3, sizeof(szTmp3), L"\\control.exe"); - } - else - StringCbCopyW(szTmp3, sizeof(szTmp3), L"C:\\Windows\\System32\\control.exe"); - - IconMessage (hwndDlg, szTmp2); - if (CreateLink (szTmp3, L"appwiz.cpl", szTmp2, szTmp, 0) != S_OK) - goto error; - - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt User's Guide.lnk"); - StatDeleteFile (szTmp2, FALSE); - } - - if (bDesktopIcon) - { - StringCbCopyW (szDir, sizeof(szDir), szDestDir); - x = wcslen (szDestDir); - if (szDestDir[x - 1] == L'\\') - bSlash = TRUE; - else - bSlash = FALSE; - - if (bSlash == FALSE) - StringCbCatW (szDir, sizeof(szDir), L"\\"); - - if (bForAllUsers) - SHGetSpecialFolderPath (hwndDlg, szLinkDir, CSIDL_COMMON_DESKTOPDIRECTORY, 0); - else - SHGetSpecialFolderPath (hwndDlg, szLinkDir, CSIDL_DESKTOPDIRECTORY, 0); - - StringCbPrintfW (szTmp, sizeof(szTmp), L"%s%s", szDir, L"VeraCrypt.exe"); - StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt.lnk"); - - IconMessage (hwndDlg, szTmp2); - - if (CreateLink (szTmp, L"", szTmp2, NULL, -1) != S_OK) - goto error; - } - - bOK = TRUE; - -error: - OleUninitialize (); - - return bOK; -} - - -void OutcomePrompt (HWND hwndDlg, BOOL bOK) -{ - if (bOK) - { - EnableWindow (GetDlgItem ((HWND) hwndDlg, IDCANCEL), FALSE); - - bDone = TRUE; - - if (bUninstall == FALSE) - { - if (bDevm) - PostMessage (MainDlg, WM_CLOSE, 0, 0); - else if (bPossiblyFirstTimeInstall || bRepairMode || (!bUpgrade && !bDowngrade)) - Info ("INSTALL_OK", hwndDlg); - else - Info ("SETUP_UPDATE_OK", hwndDlg); - } - else - { - wchar_t str[4096]; - - StringCbPrintfW (str, sizeof(str), GetString ("UNINSTALL_OK"), InstallationPath); - MessageBoxW (hwndDlg, str, lpszTitle, MB_ICONASTERISK); - } - } - else - { - if (bUninstall == FALSE) - Error ("INSTALL_FAILED", hwndDlg); - else - Error ("UNINSTALL_FAILED", hwndDlg); - } -} - -static void SetSystemRestorePoint (HWND hwndDlg, BOOL finalize) -{ - static RESTOREPOINTINFO RestPtInfo; - static STATEMGRSTATUS SMgrStatus; - static BOOL failed = FALSE; - static BOOL (__stdcall *_SRSetRestorePoint)(PRESTOREPOINTINFO, PSTATEMGRSTATUS); - - if (!SystemRestoreDll) return; - - _SRSetRestorePoint = (BOOL (__stdcall *)(PRESTOREPOINTINFO, PSTATEMGRSTATUS))GetProcAddress (SystemRestoreDll,"SRSetRestorePointW"); - if (_SRSetRestorePoint == 0) - { - FreeLibrary (SystemRestoreDll); - SystemRestoreDll = 0; - return; - } - - if (!finalize) - { - StatusMessage (hwndDlg, "CREATING_SYS_RESTORE"); - - RestPtInfo.dwEventType = BEGIN_SYSTEM_CHANGE; - RestPtInfo.dwRestorePtType = bUninstall ? APPLICATION_UNINSTALL : APPLICATION_INSTALL | DEVICE_DRIVER_INSTALL; - RestPtInfo.llSequenceNumber = 0; - StringCbCopyW (RestPtInfo.szDescription, sizeof(RestPtInfo.szDescription), bUninstall ? L"VeraCrypt uninstallation" : L"VeraCrypt installation"); - - if(!_SRSetRestorePoint (&RestPtInfo, &SMgrStatus)) - { - StatusMessage (hwndDlg, "FAILED_SYS_RESTORE"); - failed = TRUE; - } - } - else if (!failed) - { - RestPtInfo.dwEventType = END_SYSTEM_CHANGE; - RestPtInfo.llSequenceNumber = SMgrStatus.llSequenceNumber; - - if(!_SRSetRestorePoint(&RestPtInfo, &SMgrStatus)) - { - StatusMessage (hwndDlg, "FAILED_SYS_RESTORE"); - } - } -} - -void DoUninstall (void *arg) -{ - HWND hwndDlg = (HWND) arg; - BOOL bOK = TRUE; - BOOL bTempSkipSysRestore = FALSE; - - if (!Rollback) - EnableWindow (GetDlgItem ((HWND) hwndDlg, IDC_UNINSTALL), FALSE); - - WaitCursor (); - - if (!Rollback) - { - ClearLogWindow (hwndDlg); - } - - if (DoDriverUnload (hwndDlg) == FALSE) - { - bOK = FALSE; - bTempSkipSysRestore = TRUE; // Volumes are possibly mounted; defer System Restore point creation for this uninstall attempt. - } - else - { - if (!Rollback && bSystemRestore && !bTempSkipSysRestore) - SetSystemRestorePoint (hwndDlg, FALSE); - - if (DoServiceUninstall (hwndDlg, L"veracrypt") == FALSE) - { - bOK = FALSE; - } - else if (DoRegUninstall ((HWND) hwndDlg, FALSE) == FALSE) - { - bOK = FALSE; - } - else if (DoFilesInstall ((HWND) hwndDlg, InstallationPath) == FALSE) - { - bOK = FALSE; - } - else if (DoShortcutsUninstall (hwndDlg, InstallationPath) == FALSE) - { - bOK = FALSE; - } - else if (!DoApplicationDataUninstall (hwndDlg)) - { - bOK = FALSE; - } - else - { - wchar_t temp[MAX_PATH]; - FILE *f; - - // Deprecated service - DoServiceUninstall (hwndDlg, L"VeraCryptService"); - - GetTempPath (ARRAYSIZE (temp), temp); - StringCbPrintfW (UninstallBatch, sizeof (UninstallBatch), L"%sVeraCrypt-Uninstall.bat", temp); - - UninstallBatch [ARRAYSIZE(UninstallBatch)-1] = 0; - - // Create uninstall batch - f = _wfopen (UninstallBatch, L"w"); - if (!f) - bOK = FALSE; - else - { - fwprintf (f,L":loop\n" - L"del \"%s%s\"\n" - L"if exist \"%s%s\" goto loop\n" - L"rmdir \"%s\"\n" - L"del \"%s\"", - InstallationPath, L"VeraCrypt Setup.exe", - InstallationPath, L"VeraCrypt Setup.exe", - InstallationPath, - UninstallBatch - ); - - CheckFileStreamWriteErrors (hwndDlg, f, UninstallBatch); - fclose (f); - } - } - } - - NormalCursor (); - - if (Rollback) - return; - - if (bSystemRestore && !bTempSkipSysRestore) - SetSystemRestorePoint (hwndDlg, TRUE); - - if (bOK) - PostMessage (hwndDlg, TC_APPMSG_UNINSTALL_SUCCESS, 0, 0); - else - bUninstallInProgress = FALSE; - - EnableWindow (GetDlgItem ((HWND) hwndDlg, IDC_UNINSTALL), TRUE); - OutcomePrompt (hwndDlg, bOK); -} - -void DoInstall (void *arg) -{ - HWND hwndDlg = (HWND) arg; - BOOL bOK = TRUE; - wchar_t path[MAX_PATH]; - - BootEncryption bootEnc (hwndDlg); - - // Refresh the main GUI (wizard thread) - InvalidateRect (MainDlg, NULL, TRUE); - - ClearLogWindow (hwndDlg); - - if (mkfulldir (InstallationPath, TRUE) != 0) - { - if (mkfulldir (InstallationPath, FALSE) != 0) - { - wchar_t szTmp[TC_MAX_PATH]; - - handleWin32Error (hwndDlg, SRC_POS); - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CANT_CREATE_FOLDER"), InstallationPath); - MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_ICONHAND); - Error ("INSTALL_FAILED", hwndDlg); - PostMessage (MainDlg, TC_APPMSG_INSTALL_FAILURE, 0, 0); - return; - } - } - - UpdateProgressBarProc(2); - - if (DoDriverUnload (hwndDlg) == FALSE) - { - NormalCursor (); - PostMessage (MainDlg, TC_APPMSG_INSTALL_FAILURE, 0, 0); - return; - } - - if (bUpgrade - && (IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L".exe") - || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L"-x86.exe") - || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L"-x64.exe") - || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L" Format.exe") - || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L" Format-x86.exe") - || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L" Format-x64.exe") - || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L"Expander.exe") - || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L"Expander-x86.exe") - || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L"Expander-x64.exe") - || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L" Setup.exe") - ) - ) - { - NormalCursor (); - Error ("CLOSE_TC_FIRST", hwndDlg); - PostMessage (MainDlg, TC_APPMSG_INSTALL_FAILURE, 0, 0); - return; - } - - UpdateProgressBarProc(12); - - if (bSystemRestore) - SetSystemRestorePoint (hwndDlg, FALSE); - - UpdateProgressBarProc(48); - - if (bDisableSwapFiles - && IsPagingFileActive (FALSE)) - { - if (!DisablePagingFile()) - { - handleWin32Error (hwndDlg, SRC_POS); - Error ("FAILED_TO_DISABLE_PAGING_FILES", hwndDlg); - } - else - bRestartRequired = TRUE; - } - - UpdateProgressBarProc(50); - - // Remove deprecated - DoServiceUninstall (hwndDlg, L"VeraCryptService"); - - UpdateProgressBarProc(55); - - if (!SystemEncryptionUpdate) - DoRegUninstall ((HWND) hwndDlg, TRUE); - - UpdateProgressBarProc(61); - - GetWindowsDirectory (path, ARRAYSIZE (path)); - StringCbCatW (path, sizeof (path), L"\\VeraCrypt Setup.exe"); - StatDeleteFile (path, FALSE); - - if (UpdateProgressBarProc(63) && UnloadDriver && DoServiceUninstall (hwndDlg, L"veracrypt") == FALSE) - { - bOK = FALSE; - } - else if (UpdateProgressBarProc(72) && DoFilesInstall ((HWND) hwndDlg, InstallationPath) == FALSE) - { - bOK = FALSE; - } - else if (UpdateProgressBarProc(80) && DoRegInstall ((HWND) hwndDlg, InstallationPath, bRegisterFileExt) == FALSE) - { - bOK = FALSE; - } - else if (UpdateProgressBarProc(85) && UnloadDriver && DoDriverInstall (hwndDlg) == FALSE) - { - bOK = FALSE; - } - else if (UpdateProgressBarProc(90) && SystemEncryptionUpdate && UpgradeBootLoader (hwndDlg) == FALSE) - { - bOK = FALSE; - } - else if (UpdateProgressBarProc(93) && DoShortcutsInstall (hwndDlg, InstallationPath, bAddToStartMenu, bDesktopIcon) == FALSE) - { - bOK = FALSE; - } - - if (!UnloadDriver) - bRestartRequired = TRUE; - - try - { - bootEnc.RenameDeprecatedSystemLoaderBackup(); - } - catch (...) { } - - if (bOK) - UpdateProgressBarProc(97); - - if (bSystemRestore) - SetSystemRestorePoint (hwndDlg, TRUE); - - if (bOK) - { - UpdateProgressBarProc(100); - UninstallBatch[0] = 0; - StatusMessage (hwndDlg, "INSTALL_COMPLETED"); - } - else - { - UpdateProgressBarProc(0); - - if (!SystemEncryptionUpdate) - { - bUninstall = TRUE; - Rollback = TRUE; - Silent = TRUE; - - DoUninstall (hwndDlg); - - bUninstall = FALSE; - Rollback = FALSE; - Silent = FALSE; - - StatusMessage (hwndDlg, "ROLLBACK"); - } - else - { - Warning ("SYS_ENC_UPGRADE_FAILED", hwndDlg); - } - } - - OutcomePrompt (hwndDlg, bOK); - - if (bOK && !bUninstall && !bDowngrade && !bRepairMode && !bDevm) - { - if (!IsHiddenOSRunning()) // A hidden OS user should not see the post-install notes twice (on decoy OS and then on hidden OS). - { - if (bRestartRequired || SystemEncryptionUpdate) - { - // Restart required - - if (bUpgrade) - { - SavePostInstallTasksSettings (TC_POST_INSTALL_CFG_RELEASE_NOTES); - } - else if (bPossiblyFirstTimeInstall) - { - SavePostInstallTasksSettings (TC_POST_INSTALL_CFG_TUTORIAL); - } - } - else - { - // No restart will be required - - if (bUpgrade) - { - bPromptReleaseNotes = TRUE; - } - else if (bPossiblyFirstTimeInstall) - { - bPromptTutorial = TRUE; - } - } - } - } - - PostMessage (MainDlg, bOK ? TC_APPMSG_INSTALL_SUCCESS : TC_APPMSG_INSTALL_FAILURE, 0, 0); -} - - -void SetInstallationPath (HWND hwndDlg) -{ - HKEY hkey; - BOOL bInstallPathDetermined = FALSE; - wchar_t path[MAX_PATH+20]; - ITEMIDLIST *itemList; - - memset (InstallationPath, 0, sizeof (InstallationPath)); - - // Determine if VeraCrypt is already installed and try to determine its "Program Files" location - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VeraCrypt", 0, KEY_READ | KEY_WOW64_32KEY, &hkey) == ERROR_SUCCESS) - { - /* Default 'UninstallString' registry strings written by VeraCrypt: - ------------------------------------------------------------------------------------ - 5.0+ "C:\Program Files\VeraCrypt\VeraCrypt Setup.exe" /u - */ - - wchar_t rv[MAX_PATH*4]; - DWORD size = sizeof (rv); - if (RegQueryValueEx (hkey, L"UninstallString", 0, 0, (LPBYTE) &rv, &size) == ERROR_SUCCESS && wcsrchr (rv, L'/')) - { - size_t len = 0; - - // Cut and paste the location (path) where VeraCrypt is installed to InstallationPath - if (rv[0] == L'"') - { - len = wcsrchr (rv, L'/') - rv - 2; - StringCchCopyNW (InstallationPath, ARRAYSIZE(InstallationPath), rv + 1, len); - InstallationPath [len] = 0; - bInstallPathDetermined = TRUE; - - if (InstallationPath [wcslen (InstallationPath) - 1] != L'\\') - { - len = wcsrchr (InstallationPath, L'\\') - InstallationPath; - InstallationPath [len] = 0; - } - } - - } - RegCloseKey (hkey); - } - - if (bInstallPathDetermined) - { - wchar_t mp[MAX_PATH]; - - // Determine whether we were launched from the folder where VeraCrypt is installed - GetModuleFileName (NULL, mp, ARRAYSIZE (mp)); - if (wcsncmp (InstallationPath, mp, min (wcslen(InstallationPath), wcslen(mp))) == 0) - { - // We were launched from the folder where VeraCrypt is installed - - if (!IsNonInstallMode() && !bDevm) - bChangeMode = TRUE; - } - } - else - { - /* VeraCrypt is not installed or it wasn't possible to determine where it is installed. */ - - // Default "Program Files" path. - SHGetSpecialFolderLocation (hwndDlg, CSIDL_PROGRAM_FILES, &itemList); - SHGetPathFromIDList (itemList, path); - - if (Is64BitOs()) - { - // Use a unified default installation path (registry redirection of %ProgramFiles% does not work if the installation path is user-selectable) - wstring s = path; - size_t p = s.find (L" (x86)"); - if (p != wstring::npos) - { - s = s.substr (0, p); - if (_waccess (s.c_str(), 0) != -1) - StringCbCopyW (path, sizeof (path), s.c_str()); - } - } - - StringCbCatW (path, sizeof(path), L"\\VeraCrypt\\"); - StringCbCopyW (InstallationPath, sizeof(InstallationPath), path); - } - - // Make sure the path ends with a backslash - if (InstallationPath [wcslen (InstallationPath) - 1] != L'\\') - { - StringCbCatW (InstallationPath, sizeof(InstallationPath), L"\\"); - } -} - - -// Handler for uninstall only (install is handled by the wizard) -BOOL CALLBACK UninstallDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - - switch (msg) - { - case WM_INITDIALOG: - - MainDlg = hwndDlg; - - if (!CreateAppSetupMutex ()) - AbortProcess ("TC_INSTALLER_IS_RUNNING"); - - InitDialog (hwndDlg); - LocalizeDialog (hwndDlg, NULL); - - SetWindowTextW (hwndDlg, lpszTitle); - - // System Restore - SetCheckBox (hwndDlg, IDC_SYSTEM_RESTORE, bSystemRestore); - if (SystemRestoreDll == 0) - { - SetCheckBox (hwndDlg, IDC_SYSTEM_RESTORE, FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_SYSTEM_RESTORE), FALSE); - } - - SetFocus (GetDlgItem (hwndDlg, IDC_UNINSTALL)); - - return 1; - - case WM_SYSCOMMAND: - if (lw == IDC_ABOUT) - { - DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_ABOUT_DLG), hwndDlg, (DLGPROC) AboutDlgProc); - return 1; - } - return 0; - - case WM_COMMAND: - if (lw == IDC_UNINSTALL) - { - if (bDone) - { - bUninstallInProgress = FALSE; - PostMessage (hwndDlg, WM_CLOSE, 0, 0); - return 1; - } - - bUninstallInProgress = TRUE; - - WaitCursor (); - - if (bUninstall) - _beginthread (DoUninstall, 0, (void *) hwndDlg); - - return 1; - } - - if (lw == IDC_SYSTEM_RESTORE) - { - bSystemRestore = IsButtonChecked (GetDlgItem (hwndDlg, IDC_SYSTEM_RESTORE)); - return 1; - } - - if (lw == IDCANCEL) - { - PostMessage (hwndDlg, WM_CLOSE, 0, 0); - return 1; - } - - return 0; - - case TC_APPMSG_UNINSTALL_SUCCESS: - SetWindowTextW (GetDlgItem ((HWND) hwndDlg, IDC_UNINSTALL), GetString ("FINALIZE")); - NormalCursor (); - return 1; - - case WM_CLOSE: - if (bUninstallInProgress) - { - NormalCursor(); - if (AskNoYes("CONFIRM_EXIT_UNIVERSAL", hwndDlg) == IDNO) - { - return 1; - } - WaitCursor (); - } - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - return 0; -} - - -int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpszCommandLine, int nCmdShow) -{ - atexit (localcleanup); - - SelfExtractStartupInit(); - - lpszTitle = L"VeraCrypt Setup"; - - /* Call InitApp to initialize the common code */ - InitApp (hInstance, NULL); - - if (IsAdmin () != TRUE) - if (MessageBoxW (NULL, GetString ("SETUP_ADMIN"), lpszTitle, MB_YESNO | MB_ICONQUESTION) != IDYES) - { - FinalizeApp (); - exit (1); - } - - /* Setup directory */ - { - wchar_t *s; - GetModuleFileName (NULL, SetupFilesDir, ARRAYSIZE (SetupFilesDir)); - s = wcsrchr (SetupFilesDir, L'\\'); - if (s) - s[1] = 0; - } - - /* Parse command line arguments */ - - if (lpszCommandLine[0] == L'/') - { - if (lpszCommandLine[1] == L'u') - { - // Uninstall: /u - - bUninstall = TRUE; - } - else if (lpszCommandLine[1] == L'c') - { - // Change: /c - - bChangeMode = TRUE; - } - else if (lpszCommandLine[1] == L'p') - { - // Create self-extracting package: /p - - bMakePackage = TRUE; - } - else if (lpszCommandLine[1] == L'd') - { - // Dev mode: /d - bDevm = TRUE; - } - } - - if (bMakePackage) - { - /* Create self-extracting package */ - - MakeSelfExtractingPackage (NULL, SetupFilesDir); - } - else - { - SetInstallationPath (NULL); - - if (!bUninstall) - { - if (IsSelfExtractingPackage()) - { - if (!VerifyPackageIntegrity()) - { - // Package corrupted - exit (1); - } - bDevm = FALSE; - } - else if (!bDevm) - { - MessageBox (NULL, L"Error: This installer file does not contain any compressed files.\n\nTo create a self-extracting installation package (with embedded compressed files), run:\n\"VeraCrypt Setup.exe\" /p", L"VeraCrypt", MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); - FinalizeApp (); - exit (1); - } - - if (bChangeMode) - { - /* VeraCrypt is already installed on this system and we were launched from the Program Files folder */ - - char *tmpStr[] = {0, "SELECT_AN_ACTION", "REPAIR_REINSTALL", "UNINSTALL", "EXIT", 0}; - - // Ask the user to select either Repair or Unistallation - switch (AskMultiChoice ((void **) tmpStr, FALSE, NULL)) - { - case 1: - bRepairMode = TRUE; - break; - case 2: - bUninstall = TRUE; - break; - default: - FinalizeApp (); - exit (1); - } - } - } - - // System Restore - if (IsSystemRestoreEnabled ()) - { - wchar_t dllPath[MAX_PATH]; - if (GetSystemDirectory (dllPath, MAX_PATH)) - { - StringCbCatW(dllPath, sizeof(dllPath), L"\\srclient.dll"); - } - else - StringCbCopyW(dllPath, sizeof(dllPath), L"C:\\Windows\\System32\\srclient.dll"); - SystemRestoreDll = LoadLibrary (dllPath); - } - else - SystemRestoreDll = 0; - - if (!bUninstall) - { - /* Create the main dialog for install */ - - DialogBoxParamW (hInstance, MAKEINTRESOURCEW (IDD_INSTL_DLG), NULL, (DLGPROC) MainDialogProc, - (LPARAM)lpszCommandLine); - } - else - { - /* Create the main dialog for uninstall */ - - DialogBoxW (hInstance, MAKEINTRESOURCEW (IDD_UNINSTALL), NULL, (DLGPROC) UninstallDlgProc); - - if (UninstallBatch[0]) - { - STARTUPINFO si; - PROCESS_INFORMATION pi; - - ZeroMemory (&si, sizeof (si)); - si.cb = sizeof (si); - si.dwFlags = STARTF_USESHOWWINDOW; - si.wShowWindow = SW_HIDE; - - if (!CreateProcess (UninstallBatch, NULL, NULL, NULL, FALSE, IDLE_PRIORITY_CLASS, NULL, NULL, &si, &pi)) - DeleteFile (UninstallBatch); - else - { - CloseHandle (pi.hProcess); - CloseHandle (pi.hThread); - } - } - } - } - FinalizeApp (); - return 0; -} +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" +#include +#include +#include +#include +#include +#include +#include + +#include "Apidrvr.h" +#include "BootEncryption.h" +#include "Boot/Windows/BootCommon.h" +#include "Combo.h" +#include "ComSetup.h" +#include "Dlgcode.h" +#include "Language.h" +#include "Registry.h" +#include "Resource.h" + +#include "Dir.h" +#include "Setup.h" +#include "SelfExtract.h" +#include "Wizard.h" + +#include "../Common/Resource.h" + +using namespace VeraCrypt; + +#pragma warning( disable : 4201 ) +#pragma warning( disable : 4115 ) + +#include + +#pragma warning( default : 4201 ) +#pragma warning( default : 4115 ) + +#include + +wchar_t InstallationPath[TC_MAX_PATH]; +wchar_t SetupFilesDir[TC_MAX_PATH]; +wchar_t UninstallBatch[MAX_PATH]; + +BOOL bUninstall = FALSE; +BOOL bRestartRequired = FALSE; +BOOL bMakePackage = FALSE; +BOOL bDone = FALSE; +BOOL Rollback = FALSE; +BOOL bUpgrade = FALSE; +BOOL bDowngrade = FALSE; +BOOL SystemEncryptionUpdate = FALSE; +BOOL PortableMode = FALSE; +BOOL bRepairMode = FALSE; +BOOL bReinstallMode = FALSE; +BOOL bChangeMode = FALSE; +BOOL bDevm = FALSE; +BOOL bPossiblyFirstTimeInstall = FALSE; +BOOL bUninstallInProgress = FALSE; +BOOL UnloadDriver = TRUE; + +BOOL bSystemRestore = TRUE; +BOOL bDisableSwapFiles = FALSE; +BOOL bForAllUsers = TRUE; +BOOL bRegisterFileExt = TRUE; +BOOL bAddToStartMenu = TRUE; +BOOL bDesktopIcon = TRUE; + +BOOL bDesktopIconStatusDetermined = FALSE; + +HMODULE volatile SystemRestoreDll = 0; + +void localcleanup (void) +{ + localcleanupwiz (); + cleanup (); + + CloseAppSetupMutex (); +} + +BOOL ForceDeleteFile (LPCWSTR szFileName) +{ + if (!DeleteFile (szFileName)) + { + /* delete the renamed file when the machine reboots */ + return MoveFileEx (szFileName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); + } + else + return TRUE; +} + +BOOL StatDeleteFile (wchar_t *lpszFile, BOOL bCheckForOldFile) +{ + struct __stat64 st; + + if (bCheckForOldFile) + { + wchar_t szOldPath[MAX_PATH + 1]; + StringCbCopyW (szOldPath, sizeof(szOldPath), lpszFile); + StringCbCatW (szOldPath, sizeof(szOldPath), VC_FILENAME_RENAMED_SUFFIX); + + if (_wstat64 (szOldPath, &st) == 0) + { + ForceDeleteFile (szOldPath); + } + } + + if (_wstat64 (lpszFile, &st) == 0) + return ForceDeleteFile (lpszFile); + else + return TRUE; +} + +BOOL StatRemoveDirectory (wchar_t *lpszDir) +{ + struct __stat64 st; + + if (_wstat64 (lpszDir, &st) == 0) + { + BOOL bStatus = RemoveDirectory (lpszDir); + if (!bStatus) + { + /* force removal of the non empty directory */ + wchar_t szOpPath[TC_MAX_PATH + 1] = {0}; + SHFILEOPSTRUCTW op; + + StringCchCopyW(szOpPath, ARRAYSIZE(szOpPath)-1, lpszDir); + ZeroMemory(&op, sizeof(op)); + op.wFunc = FO_DELETE; + op.pFrom = szOpPath; + op.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR; + + if ((0 == SHFileOperation(&op)) && (!op.fAnyOperationsAborted)) + bStatus = TRUE; + } + return bStatus; + } + else + return TRUE; +} + + +/* Recursively set the given OWNER security descriptor to the key and its subkeys */ +static void RecursiveSetOwner (HKEY hKey, PSECURITY_DESCRIPTOR pSD) +{ + LSTATUS status = 0; + DWORD dwIndex = 0, dwMaxNameLen = 0, dwNameLen = 0, numberSubKeys = 0; + HKEY hSubKey; + + if ( (ERROR_SUCCESS == status) && (ERROR_SUCCESS == RegQueryInfoKey(hKey, NULL, NULL, NULL, &numberSubKeys, &dwMaxNameLen, NULL, NULL, NULL, NULL, NULL, NULL)) + && (numberSubKeys >= 1) + ) + { + dwMaxNameLen++; + wchar_t* szNameValue = new wchar_t[dwMaxNameLen]; + while (true) + { + dwNameLen = dwMaxNameLen; + status = RegEnumKeyExW (hKey, dwIndex++, szNameValue, &dwNameLen, NULL, NULL, NULL, NULL); + if (status == ERROR_SUCCESS) + { + status = RegOpenKeyExW (hKey, szNameValue, 0, WRITE_OWNER | KEY_READ , &hSubKey); + if (ERROR_SUCCESS == status) + { + RecursiveSetOwner (hSubKey, pSD); + RegCloseKey(hSubKey); + } + } + else + break; + } + delete [] szNameValue; + } + + RegSetKeySecurity (hKey, OWNER_SECURITY_INFORMATION, pSD); +} + +/* Recursively set the given DACL security descriptor to the key and its subkeys */ +static void RecursiveSetDACL (HKEY hKey, const wchar_t* SubKeyName, PSECURITY_DESCRIPTOR pSD) +{ + HKEY hSubKey; + DWORD dwIndex = 0, dwMaxNameLen = 0, dwNameLen = 0, numberSubKeys = 0; + LSTATUS status = RegOpenKeyExW(hKey, SubKeyName, 0, WRITE_DAC | KEY_READ /*| ACCESS_SYSTEM_SECURITY*/, &hSubKey); + if (status == ERROR_SUCCESS) + { + status = RegSetKeySecurity (hSubKey, DACL_SECURITY_INFORMATION, pSD); + if (status == ERROR_SUCCESS) + { + RegCloseKey(hSubKey); + status = RegOpenKeyExW(hKey, SubKeyName, 0, WRITE_DAC | KEY_READ , &hSubKey); + } + + if ( (ERROR_SUCCESS == status) + && (ERROR_SUCCESS == RegQueryInfoKeyW(hSubKey, NULL, NULL, NULL, &numberSubKeys, &dwMaxNameLen, NULL, NULL, NULL, NULL, NULL, NULL)) + && (numberSubKeys >= 1) + ) + { + dwMaxNameLen++; + wchar_t* szNameValue = new wchar_t[dwMaxNameLen]; + while (true) + { + dwNameLen = dwMaxNameLen; + status = RegEnumKeyExW (hSubKey, dwIndex++, szNameValue, &dwNameLen, NULL, NULL, NULL, NULL); + if (status == ERROR_SUCCESS) + { + RecursiveSetDACL (hSubKey, szNameValue, pSD); + } + else + break; + } + delete [] szNameValue; + } + } +} + +/* Correct the key permissions to allow its deletion */ +static void AllowKeyAccess(HKEY Key,const wchar_t* SubKeyName) +{ + LSTATUS RegResult; + HKEY SvcKey = NULL; + DWORD dwLength = 0; + HANDLE Token = NULL; + PTOKEN_USER pTokenUser = NULL; + std::string sNewSD; + + RegResult = RegOpenKeyExW(Key, SubKeyName, 0, WRITE_OWNER | KEY_READ, &SvcKey); + if (RegResult==ERROR_SUCCESS) + { + if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &Token)) + { + if (!GetTokenInformation(Token, TokenUser, pTokenUser, 0, &dwLength)) + { + if (GetLastError() ==ERROR_INSUFFICIENT_BUFFER) + { + pTokenUser = (PTOKEN_USER) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength); + if (pTokenUser) + { + if (GetTokenInformation(Token, TokenUser, pTokenUser, dwLength, &dwLength)) + { + SECURITY_DESCRIPTOR SecDesc; + if ( InitializeSecurityDescriptor(&SecDesc, SECURITY_DESCRIPTOR_REVISION) + && SetSecurityDescriptorDacl(&SecDesc, TRUE, NULL, FALSE) // NULL DACL: full access to everyone + && SetSecurityDescriptorOwner(&SecDesc, pTokenUser->User.Sid, FALSE) + ) + { + RecursiveSetOwner(SvcKey, &SecDesc); + } + } + + } + } + } + } + RegCloseKey(SvcKey); + } + + if (pTokenUser) + { + PSID pSid = pTokenUser->User.Sid; + DWORD dwAclSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + ::GetLengthSid(pSid) - sizeof(DWORD); + PACL pDacl = (PACL) new BYTE[dwAclSize]; + if (pDacl) + { + if (TRUE == ::InitializeAcl(pDacl, dwAclSize, ACL_REVISION)) + { + if (TRUE == AddAccessAllowedAceEx(pDacl, ACL_REVISION, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE, WRITE_DAC | KEY_ALL_ACCESS, pSid)) + { + SECURITY_DESCRIPTOR SecDesc; + if (TRUE == ::InitializeSecurityDescriptor(&SecDesc, SECURITY_DESCRIPTOR_REVISION)) + { + if (TRUE == ::SetSecurityDescriptorDacl(&SecDesc, TRUE, pDacl, FALSE)) + { + RecursiveSetDACL (Key, SubKeyName, &SecDesc); + } + } + } + } + delete [] pDacl; + } + } + + if (pTokenUser) + HeapFree(GetProcessHeap(), 0, pTokenUser); + if (Token) + CloseHandle(Token); +} + +void SearchAndDeleteRegistrySubString (HKEY hKey, const wchar_t *subKey, const wchar_t *str, BOOL bEnumSubKeys, const wchar_t* enumMatchSubStr) +{ + HKEY hSubKey = 0; + LSTATUS status = 0; + DWORD dwIndex = 0, dwType, dwValueNameLen, dwDataLen; + std::list subKeysList; + size_t subStringLength = str? wcslen(str) : 0; + + if (bEnumSubKeys) + { + DWORD dwMaxNameLen = 0; + if (ERROR_SUCCESS == RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, &dwMaxNameLen, NULL, NULL, NULL, NULL, NULL, NULL)) + { + dwMaxNameLen++; + wchar_t* szNameValue = new wchar_t[dwMaxNameLen]; + dwIndex = 0; + while (true) + { + dwValueNameLen = dwMaxNameLen; + status = RegEnumKeyExW (hKey, dwIndex++, szNameValue, &dwValueNameLen, NULL, NULL, NULL, NULL); + if (status == ERROR_SUCCESS) + { + if (enumMatchSubStr && !wcsstr(szNameValue, enumMatchSubStr)) + continue; + std::wstring entryName = szNameValue; + entryName += L"\\"; + entryName += subKey; + entryName += L"\\"; + subKeysList.push_back(entryName); + } + else + break; + } + delete [] szNameValue; + } + } + else + { + subKeysList.push_back(subKey); + } + + for (std::list::iterator ItSubKey = subKeysList.begin(); ItSubKey != subKeysList.end(); ItSubKey++) + { + // if the string to search for is empty, delete the sub key, otherwise, look for matching value and delete them + if (subStringLength == 0) + { + if (ERROR_ACCESS_DENIED == DeleteRegistryKey (hKey, ItSubKey->c_str())) + { + // grant permission to delete + AllowKeyAccess (hKey, ItSubKey->c_str()); + + // try again + DeleteRegistryKey (hKey, ItSubKey->c_str()); + } + } + else + { + if (RegOpenKeyExW (hKey, ItSubKey->c_str(), 0, KEY_ALL_ACCESS, &hSubKey) == ERROR_SUCCESS) + { + DWORD dwMaxNameLen = 0, dwMaxDataLen = 0; + if (ERROR_SUCCESS == RegQueryInfoKey(hSubKey, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &dwMaxNameLen, &dwMaxDataLen, NULL, NULL)) + { + dwMaxNameLen++; + wchar_t* szNameValue = new wchar_t[dwMaxNameLen]; + LPBYTE pbData = new BYTE[dwMaxDataLen]; + + std::list foundEntries; + dwIndex = 0; + do + { + dwValueNameLen = dwMaxNameLen; + dwDataLen = dwMaxDataLen; + status = RegEnumValueW(hSubKey, dwIndex++, szNameValue, &dwValueNameLen, NULL, &dwType, pbData, &dwDataLen); + if (status == ERROR_SUCCESS) + { + if ( (wcslen(szNameValue) >= subStringLength && wcsstr(szNameValue, str)) + || (dwType == REG_SZ && wcslen((wchar_t*) pbData) >= subStringLength && wcsstr((wchar_t*) pbData, str)) + ) + { + foundEntries.push_back(szNameValue); + } + } + } while ((status == ERROR_SUCCESS) || (status == ERROR_MORE_DATA)); // we ignore ERROR_MORE_DATA errors since + // we are sure to use the correct sizes + + // delete the entries + if (!foundEntries.empty()) + { + for (std::list::iterator It = foundEntries.begin(); + It != foundEntries.end(); It++) + { + RegDeleteValueW (hSubKey, It->c_str()); + } + } + + delete [] szNameValue; + delete [] pbData; + } + + + RegCloseKey (hSubKey); + } + } + } +} + +/* Set the given privilege of the current process */ +BOOL SetPrivilege(LPTSTR szPrivilegeName, BOOL bEnable) +{ + TOKEN_PRIVILEGES tp; + LUID luid; + HANDLE hProcessToken; + BOOL bStatus = FALSE; + + if ( OpenProcessToken(GetCurrentProcess(), + TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, + &hProcessToken) ) + { + if ( LookupPrivilegeValue( + NULL, + szPrivilegeName, + &luid ) ) + { + + tp.PrivilegeCount = 1; + tp.Privileges[0].Luid = luid; + tp.Privileges[0].Attributes = bEnable? SE_PRIVILEGE_ENABLED : SE_PRIVILEGE_REMOVED; + + // Enable the privilege + bStatus = AdjustTokenPrivileges( + hProcessToken, + FALSE, + &tp, + sizeof(TOKEN_PRIVILEGES), + (PTOKEN_PRIVILEGES) NULL, + (PDWORD) NULL); + } + + CloseHandle(hProcessToken); + } + + return bStatus; +} + +/* + * Creates a VT_LPWSTR propvariant. + * we use our own implementation to use SHStrDupW function pointer + * that we retreive ourselves to avoid dll hijacking attacks + */ +inline HRESULT VCInitPropVariantFromString(__in PCWSTR psz, __out PROPVARIANT *ppropvar) +{ + ppropvar->vt = VT_LPWSTR; + HRESULT hr = VCStrDupW(psz, &ppropvar->pwszVal); + if (FAILED(hr)) + { + PropVariantInit(ppropvar); + } + return hr; +} + +HRESULT CreateLink (wchar_t *lpszPathObj, wchar_t *lpszArguments, + wchar_t *lpszPathLink, const wchar_t* iconFile, int iconIndex) +{ + HRESULT hres; + IShellLink *psl; + + /* Get a pointer to the IShellLink interface. */ + hres = CoCreateInstance (CLSID_ShellLink, NULL, + CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *) &psl); + if (SUCCEEDED (hres)) + { + IPersistFile *ppf; + + /* Set the path to the shortcut target, and add the + description. */ + psl->SetPath (lpszPathObj); + psl->SetArguments (lpszArguments); + if (iconFile) + { + psl->SetIconLocation (iconFile, iconIndex); + } + + // Application ID + if (_tcsstr (lpszPathObj, _T(TC_APP_NAME) _T(".exe"))) + { + IPropertyStore *propStore; + + if (SUCCEEDED (psl->QueryInterface (IID_PPV_ARGS (&propStore)))) + { + PROPVARIANT propVariant; + if (SUCCEEDED (VCInitPropVariantFromString (TC_APPLICATION_ID, &propVariant))) + { + if (SUCCEEDED (propStore->SetValue (PKEY_AppUserModel_ID, propVariant))) + propStore->Commit(); + + PropVariantClear (&propVariant); + } + + propStore->Release(); + } + } + + /* Query IShellLink for the IPersistFile interface for saving + the shortcut in persistent storage. */ + hres = psl->QueryInterface (IID_IPersistFile, + (void **) &ppf); + + if (SUCCEEDED (hres)) + { + /* Save the link by calling IPersistFile::Save. */ + hres = ppf->Save (lpszPathLink, TRUE); + ppf->Release (); + } + psl->Release (); + } + return hres; +} + +BOOL IsSystemRestoreEnabled () +{ + BOOL bEnabled = FALSE; + HKEY hKey; + DWORD dwValue = 0, cbValue = sizeof (DWORD); + wchar_t szRegPath[MAX_PATH]; + GetRestorePointRegKeyName (szRegPath, sizeof (szRegPath)); + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, szRegPath, 0, KEY_READ | KEY_WOW64_64KEY, &hKey) == ERROR_SUCCESS) + { + if (IsOSAtLeast (WIN_VISTA)) + { + if ( (ERROR_SUCCESS == RegQueryValueEx (hKey, L"RPSessionInterval", NULL, NULL, (LPBYTE) &dwValue, &cbValue)) + && (dwValue == 1) + ) + { + bEnabled = TRUE; + } + } + else + { + if ( (ERROR_SUCCESS == RegQueryValueEx (hKey, L"DisableSR", NULL, NULL, (LPBYTE) &dwValue, &cbValue)) + && (dwValue == 0) + ) + { + bEnabled = TRUE; + } + } + + + RegCloseKey (hKey); + } + + return bEnabled; +} + +void GetProgramPath (HWND hwndDlg, wchar_t *path) +{ + ITEMIDLIST *i; + HRESULT res; + + if (bForAllUsers) + res = SHGetSpecialFolderLocation (hwndDlg, CSIDL_COMMON_PROGRAMS, &i); + else + res = SHGetSpecialFolderLocation (hwndDlg, CSIDL_PROGRAMS, &i); + + SHGetPathFromIDList (i, path); +} + +void StatusMessage (HWND hwndDlg, char *stringId) +{ + if (Rollback) + return; + + SendMessageW (GetDlgItem (hwndDlg, IDC_LOG_WINDOW), LB_ADDSTRING, 0, (LPARAM) GetString (stringId)); + + SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_SETTOPINDEX, + SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_GETCOUNT, 0, 0) - 1, 0); +} + +void StatusMessageParam (HWND hwndDlg, char *stringId, wchar_t *param) +{ + wchar_t szTmp[1024]; + + if (Rollback) + return; + + StringCbPrintfW (szTmp, sizeof(szTmp), L"%s %s", GetString (stringId), param); + SendMessageW (GetDlgItem (hwndDlg, IDC_LOG_WINDOW), LB_ADDSTRING, 0, (LPARAM) szTmp); + + SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_SETTOPINDEX, + SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_GETCOUNT, 0, 0) - 1, 0); +} + +void ClearLogWindow (HWND hwndDlg) +{ + SendMessage (GetDlgItem (hwndDlg, IDC_LOG_WINDOW), LB_RESETCONTENT, 0, 0); +} + +void RegMessage (HWND hwndDlg, wchar_t *txt) +{ + StatusMessageParam (hwndDlg, "ADDING_REG", txt); +} + +void CopyMessage (HWND hwndDlg, wchar_t *txt) +{ + StatusMessageParam (hwndDlg, "INSTALLING", txt); +} + +void RemoveMessage (HWND hwndDlg, wchar_t *txt) +{ + if (!Rollback) + StatusMessageParam (hwndDlg, "REMOVING", txt); +} + +void IconMessage (HWND hwndDlg, wchar_t *txt) +{ + StatusMessageParam (hwndDlg, "ADDING_ICON", txt); +} + +void DetermineUpgradeDowngradeStatus (BOOL bCloseDriverHandle, LONG *driverVersionPtr) +{ + LONG driverVersion = VERSION_NUM; + int status = 0; + + if (hDriver == INVALID_HANDLE_VALUE) + status = DriverAttach(); + + if ((status == 0) && (hDriver != INVALID_HANDLE_VALUE)) + { + DWORD dwResult; + BOOL bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVER_VERSION, NULL, 0, &driverVersion, sizeof (driverVersion), &dwResult, NULL); + + if (!bResult) + bResult = DeviceIoControl (hDriver, TC_IOCTL_LEGACY_GET_DRIVER_VERSION, NULL, 0, &driverVersion, sizeof (driverVersion), &dwResult, NULL); + + + bUpgrade = (bResult && driverVersion <= VERSION_NUM); + bDowngrade = (bResult && driverVersion > VERSION_NUM); + bReinstallMode = (bResult && driverVersion == VERSION_NUM); + + PortableMode = DeviceIoControl (hDriver, TC_IOCTL_GET_PORTABLE_MODE_STATUS, NULL, 0, NULL, 0, &dwResult, NULL); + + if (bCloseDriverHandle) + { + CloseHandle (hDriver); + hDriver = INVALID_HANDLE_VALUE; + } + } + + *driverVersionPtr = driverVersion; +} + + +static BOOL IsFileInUse (const wstring &filePath) +{ + HANDLE useTestHandle = CreateFile (filePath.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + + if (useTestHandle != INVALID_HANDLE_VALUE) + CloseHandle (useTestHandle); + else if (GetLastError() == ERROR_SHARING_VIOLATION) + return TRUE; + + return FALSE; +} + + +BOOL DoFilesInstall (HWND hwndDlg, wchar_t *szDestDir) +{ + /* WARNING: Note that, despite its name, this function is used during UNinstallation as well. */ + + wchar_t szTmp[TC_MAX_PATH]; + BOOL bOK = TRUE; + int i, x, fileNo; + wchar_t curFileName [TC_MAX_PATH] = {0}; + + if (!bUninstall && !bDevm) + { + // Self-extract all files to memory + + GetModuleFileName (NULL, szTmp, ARRAYSIZE (szTmp)); + + if (!SelfExtractInMemory (szTmp)) + return FALSE; + } + + x = wcslen (szDestDir); + if (x < 2) + return FALSE; + + if (szDestDir[x - 1] != L'\\') + StringCbCatW (szDestDir, MAX_PATH, L"\\"); + + for (i = 0; i < sizeof (szFiles) / sizeof (szFiles[0]); i++) + { + BOOL bResult, driver64 = FALSE; + wchar_t szDir[TC_MAX_PATH]; + + if (wcsstr (szFiles[i], L"VeraCrypt Setup") != 0) + { + if (bUninstall) + continue; // Prevent 'access denied' error + + if (bRepairMode) + continue; // Destination = target + } + + // skip files that don't apply to the current architecture + if ( (Is64BitOs () && (wcscmp (szFiles[i], L"AVeraCrypt-x64.exe") == 0)) + || (Is64BitOs () && (wcscmp (szFiles[i], L"AVeraCryptExpander-x64.exe") == 0)) + || (Is64BitOs () && (wcscmp (szFiles[i], L"AVeraCrypt Format-x64.exe") == 0)) + || (!Is64BitOs () && (wcscmp (szFiles[i], L"AVeraCrypt-x86.exe") == 0)) + || (!Is64BitOs () && (wcscmp (szFiles[i], L"AVeraCryptExpander-x86.exe") == 0)) + || (!Is64BitOs () && (wcscmp (szFiles[i], L"AVeraCrypt Format-x86.exe") == 0)) + ) + { + continue; + } + + if (*szFiles[i] == L'A') + StringCbCopyW (szDir, sizeof(szDir), szDestDir); + else if (*szFiles[i] == L'D') + { + if (Is64BitOs ()) + driver64 = TRUE; + + GetSystemDirectory (szDir, ARRAYSIZE (szDir)); + + x = wcslen (szDir); + if (szDir[x - 1] != L'\\') + StringCbCatW (szDir, sizeof(szDir), L"\\"); + + StringCbCatW (szDir, sizeof(szDir), L"Drivers\\"); + } + else if (*szFiles[i] == L'W') + GetWindowsDirectory (szDir, ARRAYSIZE (szDir)); + + if (*szFiles[i] == L'I') + continue; + + StringCbPrintfW (szTmp, sizeof(szTmp), L"%s%s", szDir, szFiles[i] + 1); + + if (bUninstall == FALSE) + CopyMessage (hwndDlg, szTmp); + else + RemoveMessage (hwndDlg, szTmp); + + if (bUninstall == FALSE) + { + SetCurrentDirectory (SetupFilesDir); + + if (wcsstr (szFiles[i], L"VeraCrypt Setup") != 0) + { + // Copy ourselves (the distribution package) to the destination location as 'VeraCrypt Setup.exe' + + wchar_t mp[MAX_PATH]; + + GetModuleFileName (NULL, mp, ARRAYSIZE (mp)); + bResult = TCCopyFile (mp, szTmp); + } + else + { + StringCchCopyNW (curFileName, ARRAYSIZE(curFileName), szFiles[i] + 1, wcslen (szFiles[i]) - 1); + curFileName [wcslen (szFiles[i]) - 1] = 0; + + if (Is64BitOs () + && wcscmp (szFiles[i], L"Dveracrypt.sys") == 0) + { + StringCbCopyNW (curFileName, sizeof(curFileName), FILENAME_64BIT_DRIVER, sizeof (FILENAME_64BIT_DRIVER)); + } + + if (Is64BitOs () + && wcscmp (szFiles[i], L"AVeraCrypt.exe") == 0) + { + StringCbCopyNW (curFileName, sizeof(curFileName), L"VeraCrypt-x64.exe", sizeof (L"VeraCrypt-x64.exe")); + } + + if (Is64BitOs () + && wcscmp (szFiles[i], L"AVeraCrypt-x86.exe") == 0) + { + StringCbCopyNW (curFileName, sizeof(curFileName), L"VeraCrypt.exe", sizeof (L"VeraCrypt.exe")); + } + + if (Is64BitOs () + && wcscmp (szFiles[i], L"AVeraCryptExpander.exe") == 0) + { + StringCbCopyNW (curFileName, sizeof(curFileName), L"VeraCryptExpander-x64.exe", sizeof (L"VeraCryptExpander-x64.exe")); + } + + if (Is64BitOs () + && wcscmp (szFiles[i], L"AVeraCryptExpander-x86.exe") == 0) + { + StringCbCopyNW (curFileName, sizeof(curFileName), L"VeraCryptExpander.exe", sizeof (L"VeraCryptExpander.exe")); + } + + if (Is64BitOs () + && wcscmp (szFiles[i], L"AVeraCrypt Format.exe") == 0) + { + StringCbCopyNW (curFileName, sizeof(curFileName), L"VeraCrypt Format-x64.exe", sizeof (L"VeraCrypt Format-x64.exe")); + } + + if (Is64BitOs () + && wcscmp (szFiles[i], L"AVeraCrypt Format-x86.exe") == 0) + { + StringCbCopyNW (curFileName, sizeof(curFileName), L"VeraCrypt Format.exe", sizeof (L"VeraCrypt Format.exe")); + } + + if (!bDevm) + { + bResult = FALSE; + + // Find the correct decompressed file in memory + for (fileNo = 0; fileNo < NBR_COMPRESSED_FILES; fileNo++) + { + // Write the file (stored in memory) directly to the destination location + // (there will be no temporary files). + if (wmemcmp ( + curFileName, + Decompressed_Files[fileNo].fileName, + min (wcslen (curFileName), (size_t) Decompressed_Files[fileNo].fileNameLength)) == 0) + { + // Dump filter driver cannot be installed to SysWOW64 directory + if (driver64 && !EnableWow64FsRedirection (FALSE)) + { + handleWin32Error (hwndDlg, SRC_POS); + bResult = FALSE; + goto err; + } + + bResult = SaveBufferToFile ( + (char *) Decompressed_Files[fileNo].fileContent, + szTmp, + Decompressed_Files[fileNo].fileLength, + FALSE, + TRUE); + + if (driver64) + { + if (!EnableWow64FsRedirection (TRUE)) + { + handleWin32Error (hwndDlg, SRC_POS); + bResult = FALSE; + goto err; + } + + if (!bResult) + goto err; + + } + + break; + } + } + } + else + { + if (driver64) + EnableWow64FsRedirection (FALSE); + + bResult = TCCopyFile (curFileName, szTmp); + + if (driver64) + EnableWow64FsRedirection (TRUE); + } + + if (bResult && wcscmp (szFiles[i], L"AVeraCrypt.exe") == 0) + { + if (Is64BitOs ()) + EnableWow64FsRedirection (FALSE); + + wstring servicePath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", false); + wstring serviceLegacyPath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", true); + wstring favoritesFile = GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false); + wstring favoritesLegacyFile = GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, true); + + if ( FileExists (servicePath.c_str()) + || (Is64BitOs () && FileExists (serviceLegacyPath.c_str())) + ) + { + CopyMessage (hwndDlg, (wchar_t *) servicePath.c_str()); + bResult = CopyFile (szTmp, servicePath.c_str(), FALSE); + } + + if (bResult && Is64BitOs () + && FileExists (favoritesLegacyFile.c_str()) + && !FileExists (favoritesFile.c_str())) + { + // copy the favorites XML file to the native system directory + bResult = CopyFile (favoritesLegacyFile.c_str(), favoritesFile.c_str(), FALSE); + } + + if (bResult && Is64BitOs () && FileExists (favoritesFile.c_str()) && FileExists (servicePath.c_str())) + { + // Update the path of the service + BootEncryption BootEncObj (hwndDlg); + + try + { + if (BootEncObj.GetDriverServiceStartType() == SERVICE_BOOT_START) + { + BootEncObj.UpdateSystemFavoritesService (); + } + } + catch (...) {} + } + + if (Is64BitOs ()) + { + // delete files from legacy path + if (FileExists (favoritesLegacyFile.c_str())) + { + RemoveMessage (hwndDlg, (wchar_t *) favoritesLegacyFile.c_str()); + ForceDeleteFile (favoritesLegacyFile.c_str()); + } + + if (FileExists (serviceLegacyPath.c_str())) + { + RemoveMessage (hwndDlg, (wchar_t *) serviceLegacyPath.c_str()); + ForceDeleteFile (serviceLegacyPath.c_str()); + } + + EnableWow64FsRedirection (TRUE); + } + } + } + } + else + { + if (driver64) + EnableWow64FsRedirection (FALSE); + bResult = StatDeleteFile (szTmp, TRUE); + if (driver64) + EnableWow64FsRedirection (TRUE); + + if (bResult && wcscmp (szFiles[i], L"AVeraCrypt.exe") == 0) + { + if (Is64BitOs ()) + EnableWow64FsRedirection (FALSE); + + wstring servicePath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", false); + wstring serviceLegacyPath = GetServiceConfigPath (_T(TC_APP_NAME) L".exe", true); + wstring favoritesFile = GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, false); + wstring favoritesLegacyFile = GetServiceConfigPath (TC_APPD_FILENAME_SYSTEM_FAVORITE_VOLUMES, true); + + // delete all files related to system favorites service + if (FileExists (favoritesFile.c_str())) + { + RemoveMessage (hwndDlg, (wchar_t *) favoritesFile.c_str()); + ForceDeleteFile (favoritesFile.c_str()); + } + + if (FileExists (servicePath.c_str())) + { + RemoveMessage (hwndDlg, (wchar_t *) servicePath.c_str()); + ForceDeleteFile (servicePath.c_str()); + } + + if (Is64BitOs ()) + { + if (FileExists (favoritesLegacyFile.c_str())) + { + RemoveMessage (hwndDlg, (wchar_t *) favoritesLegacyFile.c_str()); + ForceDeleteFile (favoritesLegacyFile.c_str()); + } + + if (FileExists (serviceLegacyPath.c_str())) + { + RemoveMessage (hwndDlg, (wchar_t *) serviceLegacyPath.c_str()); + ForceDeleteFile (serviceLegacyPath.c_str()); + } + + EnableWow64FsRedirection (TRUE); + } + } + } + +err: + if (bResult == FALSE) + { + LPVOID lpMsgBuf; + DWORD dwError = GetLastError (); + wchar_t szTmp2[700]; + wchar_t szErrorValue[16]; + wchar_t* pszDesc; + + FormatMessage ( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + dwError, + MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ + (wchar_t *) &lpMsgBuf, + 0, + NULL + ); + + if (lpMsgBuf) + pszDesc = (wchar_t*) lpMsgBuf; + else + { + StringCbPrintfW (szErrorValue, sizeof (szErrorValue), L"0x%.8X", dwError); + pszDesc = szErrorValue; + } + + if (bUninstall == FALSE) + StringCbPrintfW (szTmp2, sizeof(szTmp2), GetString ("INSTALL_OF_FAILED"), szTmp, pszDesc); + else + StringCbPrintfW (szTmp2, sizeof(szTmp2), GetString ("UNINSTALL_OF_FAILED"), szTmp, pszDesc); + + if (lpMsgBuf) LocalFree (lpMsgBuf); + + if (!Silent && MessageBoxW (hwndDlg, szTmp2, lpszTitle, MB_YESNO | MB_ICONHAND) != IDYES) + return FALSE; + } + } + + // Language pack + if (bUninstall == FALSE) + { + WIN32_FIND_DATA f; + HANDLE h; + + SetCurrentDirectory (SetupFilesDir); + h = FindFirstFile (L"Language.*.xml", &f); + + if (h != INVALID_HANDLE_VALUE) + { + wchar_t d[MAX_PATH*2]; + StringCbPrintfW (d, sizeof(d), L"%s%s", szDestDir, f.cFileName); + CopyMessage (hwndDlg, d); + TCCopyFile (f.cFileName, d); + FindClose (h); + } + + SetCurrentDirectory (SetupFilesDir); + SetCurrentDirectory (L"Setup files"); + h = FindFirstFile (L"VeraCrypt User Guide.*.pdf", &f); + if (h != INVALID_HANDLE_VALUE) + { + wchar_t d[MAX_PATH*2]; + StringCbPrintfW (d, sizeof(d), L"%s%s", szDestDir, f.cFileName); + CopyMessage (hwndDlg, d); + TCCopyFile (f.cFileName, d); + FindClose (h); + } + SetCurrentDirectory (SetupFilesDir); + } + + return bOK; +} + +BOOL DoRegInstall (HWND hwndDlg, wchar_t *szDestDir, BOOL bInstallType) +{ + wchar_t szDir[TC_MAX_PATH], *key; + wchar_t szTmp[TC_MAX_PATH*4]; + HKEY hkey = 0; + BOOL bSlash, bOK = FALSE; + DWORD dw; + int x; + + if (SystemEncryptionUpdate) + { + if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VeraCrypt", + 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_WOW64_32KEY, NULL, &hkey, &dw) == ERROR_SUCCESS) + { + StringCbCopyW (szTmp, sizeof(szTmp), _T(VERSION_STRING)); + RegSetValueEx (hkey, L"DisplayVersion", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)); + + StringCbCopyW (szTmp, sizeof(szTmp), _T(TC_HOMEPAGE)); + RegSetValueEx (hkey, L"URLInfoAbout", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)); + + RegCloseKey (hkey); + } + + return TRUE; + } + + StringCbCopyW (szDir, sizeof(szDir), szDestDir); + x = wcslen (szDestDir); + if (szDestDir[x - 1] == L'\\') + bSlash = TRUE; + else + bSlash = FALSE; + + if (bSlash == FALSE) + StringCbCatW (szDir, sizeof(szDir), L"\\"); + + if (bInstallType) + { + + key = L"Software\\Classes\\VeraCryptVolume"; + RegMessage (hwndDlg, key); + if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, + key, + 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &dw) != ERROR_SUCCESS) + goto error; + + StringCbCopyW (szTmp, sizeof(szTmp), L"VeraCrypt Volume"); + if (RegSetValueEx (hkey, L"", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) + goto error; + + StringCbPrintfW (szTmp, sizeof(szTmp), L"%ws", TC_APPLICATION_ID); + if (RegSetValueEx (hkey, L"AppUserModelID", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) + goto error; + + RegCloseKey (hkey); + hkey = 0; + + key = L"Software\\Classes\\VeraCryptVolume\\DefaultIcon"; + RegMessage (hwndDlg, key); + if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, + key, + 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &dw) != ERROR_SUCCESS) + goto error; + + StringCbPrintfW (szTmp, sizeof(szTmp), L"%sVeraCrypt.exe,1", szDir); + if (RegSetValueEx (hkey, L"", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) + goto error; + + RegCloseKey (hkey); + hkey = 0; + + key = L"Software\\Classes\\VeraCryptVolume\\Shell\\open\\command"; + RegMessage (hwndDlg, key); + if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, + key, + 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &dw) != ERROR_SUCCESS) + goto error; + + StringCbPrintfW (szTmp, sizeof(szTmp), L"\"%sVeraCrypt.exe\" /v \"%%1\"", szDir ); + if (RegSetValueEx (hkey, L"", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) + goto error; + + RegCloseKey (hkey); + hkey = 0; + + key = L"Software\\Classes\\.hc"; + BOOL typeClassChanged = TRUE; + wchar_t typeClass[256]; + DWORD typeClassSize = sizeof (typeClass); + + if (ReadLocalMachineRegistryString (key, L"", typeClass, &typeClassSize) && typeClassSize > 0 && wcscmp (typeClass, L"VeraCryptVolume") == 0) + typeClassChanged = FALSE; + + RegMessage (hwndDlg, key); + if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, + key, + 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, &dw) != ERROR_SUCCESS) + goto error; + + StringCbCopyW (szTmp, sizeof(szTmp), L"VeraCryptVolume"); + if (RegSetValueEx (hkey, L"", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) + goto error; + + RegCloseKey (hkey); + hkey = 0; + + if (typeClassChanged) + SHChangeNotify (SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); + } + + key = L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VeraCrypt"; + RegMessage (hwndDlg, key); + if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, + key, + 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_WOW64_32KEY, NULL, &hkey, &dw) != ERROR_SUCCESS) + goto error; + + /* IMPORTANT: IF YOU CHANGE THIS IN ANY WAY, REVISE AND UPDATE SetInstallationPath() ACCORDINGLY! */ + StringCbPrintfW (szTmp, sizeof(szTmp), L"\"%sVeraCrypt Setup.exe\" /u", szDir); + if (RegSetValueEx (hkey, L"UninstallString", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) + goto error; + + StringCbPrintfW (szTmp, sizeof(szTmp), L"\"%sVeraCrypt Setup.exe\" /c", szDir); + if (RegSetValueEx (hkey, L"ModifyPath", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) + goto error; + + StringCbPrintfW (szTmp, sizeof(szTmp), L"\"%sVeraCrypt Setup.exe\"", szDir); + if (RegSetValueEx (hkey, L"DisplayIcon", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) + goto error; + + StringCbCopyW (szTmp, sizeof(szTmp), _T(VERSION_STRING)); + if (RegSetValueEx (hkey, L"DisplayVersion", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) + goto error; + + StringCbCopyW (szTmp, sizeof(szTmp), L"VeraCrypt"); + if (RegSetValueEx (hkey, L"DisplayName", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) + goto error; + + StringCbCopyW (szTmp, sizeof(szTmp), L"IDRIX"); + if (RegSetValueEx (hkey, L"Publisher", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) + goto error; + + StringCbCopyW (szTmp, sizeof(szTmp), _T(TC_HOMEPAGE)); + if (RegSetValueEx (hkey, L"URLInfoAbout", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) + goto error; + + bOK = TRUE; + +error: + if (hkey != 0) + RegCloseKey (hkey); + + if (bOK == FALSE) + { + handleWin32Error (hwndDlg, SRC_POS); + Error ("REG_INSTALL_FAILED", hwndDlg); + } + + // Register COM servers for UAC + if (IsOSAtLeast (WIN_VISTA)) + { + if (!RegisterComServers (szDir)) + { + Error ("COM_REG_FAILED", hwndDlg); + return FALSE; + } + } + + return bOK; +} + +BOOL DoApplicationDataUninstall (HWND hwndDlg) +{ + wchar_t path[MAX_PATH]; + wchar_t path2[MAX_PATH]; + BOOL bOK = TRUE; + + StatusMessage (hwndDlg, "REMOVING_APPDATA"); + + SHGetFolderPath (NULL, CSIDL_APPDATA, NULL, 0, path); + StringCbCatW (path, sizeof(path), L"\\VeraCrypt\\"); + + // Delete favorite volumes file + StringCbPrintfW (path2, sizeof(path2), L"%s%s", path, TC_APPD_FILENAME_FAVORITE_VOLUMES); + RemoveMessage (hwndDlg, path2); + StatDeleteFile (path2, FALSE); + + // Delete keyfile defaults + StringCbPrintfW (path2, sizeof(path2), L"%s%s", path, TC_APPD_FILENAME_DEFAULT_KEYFILES); + RemoveMessage (hwndDlg, path2); + StatDeleteFile (path2, FALSE); + + // Delete history file + StringCbPrintfW (path2, sizeof(path2), L"%s%s", path, TC_APPD_FILENAME_HISTORY); + RemoveMessage (hwndDlg, path2); + StatDeleteFile (path2, FALSE); + + // Delete configuration file + StringCbPrintfW (path2, sizeof(path2), L"%s%s", path, TC_APPD_FILENAME_CONFIGURATION); + RemoveMessage (hwndDlg, path2); + StatDeleteFile (path2, FALSE); + + // Delete system encryption configuration file + StringCbPrintfW (path2, sizeof(path2), L"%s%s", path, TC_APPD_FILENAME_SYSTEM_ENCRYPTION); + RemoveMessage (hwndDlg, path2); + StatDeleteFile (path2, FALSE); + + SHGetFolderPath (NULL, CSIDL_APPDATA, NULL, 0, path); + StringCbCatW (path, sizeof(path), L"\\VeraCrypt"); + RemoveMessage (hwndDlg, path); + if (!StatRemoveDirectory (path)) + { + handleWin32Error (hwndDlg, SRC_POS); + bOK = FALSE; + } + + // remove VeraCrypt under common appdata + if (SUCCEEDED (SHGetFolderPath (NULL, CSIDL_COMMON_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, path))) + { + StringCbCatW (path, sizeof(path), L"\\VeraCrypt"); + + // Delete original bootloader + StringCbPrintfW (path2, sizeof(path2), L"%s\\%s", path, TC_SYS_BOOT_LOADER_BACKUP_NAME); + RemoveMessage (hwndDlg, path2); + StatDeleteFile (path2, FALSE); + + // remove VeraCrypt folder + RemoveMessage (hwndDlg, path); + StatRemoveDirectory (path); + } + + + return bOK; +} + +BOOL DoRegUninstall (HWND hwndDlg, BOOL bRemoveDeprecated) +{ + wchar_t regk [64]; + typedef LSTATUS (WINAPI *RegDeleteKeyExWFn) (HKEY hKey,LPCWSTR lpSubKey,REGSAM samDesired,WORD Reserved); + RegDeleteKeyExWFn RegDeleteKeyExWPtr = NULL; + HMODULE hAdvapiDll = LoadLibrary (L"Advapi32.dll"); + if (hAdvapiDll) + { + RegDeleteKeyExWPtr = (RegDeleteKeyExWFn) GetProcAddress(hAdvapiDll, "RegDeleteKeyExW"); + } + + // Unregister COM servers + if (!bRemoveDeprecated && IsOSAtLeast (WIN_VISTA)) + { + if (!UnregisterComServers (InstallationPath)) + StatusMessage (hwndDlg, "COM_DEREG_FAILED"); + } + + if (!bRemoveDeprecated) + StatusMessage (hwndDlg, "REMOVING_REG"); + + if (RegDeleteKeyExWPtr) + { + RegDeleteKeyExWPtr (HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VeraCrypt", KEY_WOW64_32KEY, 0); + RegDeleteKeyExWPtr (HKEY_CURRENT_USER, L"Software\\VeraCrypt", KEY_WOW64_32KEY, 0); + } + else + { + RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VeraCrypt"); + RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\VeraCrypt"); + } + RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume\\Shell\\open\\command"); + RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume\\Shell\\open"); + RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume\\Shell"); + RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume\\DefaultIcon"); + RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume"); + + if (!bRemoveDeprecated) + { + HKEY hKey; + GetStartupRegKeyName (regk, sizeof(regk)); + DeleteRegistryValue (regk, L"VeraCrypt"); + + DeleteRegistryKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\.hc"); + + // enable the SE_TAKE_OWNERSHIP_NAME privilege for this operation + SetPrivilege (SE_TAKE_OWNERSHIP_NAME, TRUE); + + // clean MuiCache list from VeraCrypt entries + SearchAndDeleteRegistrySubString (HKEY_CLASSES_ROOT, L"Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache", L"VeraCrypt", FALSE, NULL); + + // clean other VeraCrypt entries from all users + SearchAndDeleteRegistrySubString (HKEY_USERS, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.hc", NULL, TRUE, NULL); + SearchAndDeleteRegistrySubString (HKEY_USERS, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Compatibility Assistant\\Persisted", L"VeraCrypt", TRUE, NULL); + SearchAndDeleteRegistrySubString (HKEY_USERS, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartPage\\NewShortcuts", L"VeraCrypt", TRUE, NULL); + + if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SYSTEM", 0, KEY_ALL_ACCESS | WRITE_DAC | WRITE_OWNER, &hKey) == ERROR_SUCCESS) + { + SearchAndDeleteRegistrySubString (hKey, L"Enum\\Root\\LEGACY_VERACRYPT", NULL, TRUE, L"ControlSet"); + SearchAndDeleteRegistrySubString (hKey, L"services\\veracrypt", NULL, TRUE, L"ControlSet"); + RegCloseKey(hKey); + } + + // disable the SE_TAKE_OWNERSHIP_NAME privilege for this operation + SetPrivilege (SE_TAKE_OWNERSHIP_NAME, FALSE); + + SHChangeNotify (SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); + } + + if (hAdvapiDll) + FreeLibrary (hAdvapiDll); + + return TRUE; +} + + +BOOL DoServiceUninstall (HWND hwndDlg, wchar_t *lpszService) +{ + SC_HANDLE hManager, hService = NULL; + BOOL bOK = FALSE, bRet; + SERVICE_STATUS status; + BOOL firstTry = TRUE; + int x; + + memset (&status, 0, sizeof (status)); /* Keep VC6 quiet */ + +retry: + + hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); + if (hManager == NULL) + goto error; + + hService = OpenService (hManager, lpszService, SERVICE_ALL_ACCESS); + if (hService == NULL) + goto error; + + if (wcscmp (L"veracrypt", lpszService) == 0) + { + try + { + BootEncryption bootEnc (hwndDlg); + if (bootEnc.GetDriverServiceStartType() == SERVICE_BOOT_START) + { + try { bootEnc.RegisterFilterDriver (false, BootEncryption::DriveFilter); } catch (...) { } + try { bootEnc.RegisterFilterDriver (false, BootEncryption::VolumeFilter); } catch (...) { } + try { bootEnc.RegisterFilterDriver (false, BootEncryption::DumpFilter); } catch (...) { } + } + } + catch (...) { } + + StatusMessage (hwndDlg, "STOPPING_DRIVER"); + } + else + StatusMessageParam (hwndDlg, "STOPPING", lpszService); + +#define WAIT_PERIOD 3 + + for (x = 0; x < WAIT_PERIOD; x++) + { + bRet = QueryServiceStatus (hService, &status); + if (bRet != TRUE) + goto error; + + if (status.dwCurrentState != SERVICE_START_PENDING && + status.dwCurrentState != SERVICE_STOP_PENDING && + status.dwCurrentState != SERVICE_CONTINUE_PENDING) + break; + + Sleep (1000); + } + + if (status.dwCurrentState != SERVICE_STOPPED) + { + bRet = ControlService (hService, SERVICE_CONTROL_STOP, &status); + if (bRet == FALSE) + goto try_delete; + + for (x = 0; x < WAIT_PERIOD; x++) + { + bRet = QueryServiceStatus (hService, &status); + if (bRet != TRUE) + goto error; + + if (status.dwCurrentState != SERVICE_START_PENDING && + status.dwCurrentState != SERVICE_STOP_PENDING && + status.dwCurrentState != SERVICE_CONTINUE_PENDING) + break; + + Sleep (1000); + } + + if (status.dwCurrentState != SERVICE_STOPPED && status.dwCurrentState != SERVICE_STOP_PENDING) + goto error; + } + +try_delete: + + if (wcscmp (L"veracrypt", lpszService) == 0) + StatusMessage (hwndDlg, "REMOVING_DRIVER"); + else + StatusMessageParam (hwndDlg, "REMOVING", lpszService); + + if (hService != NULL) + { + CloseServiceHandle (hService); + hService = NULL; + } + + if (hManager != NULL) + { + CloseServiceHandle (hManager); + hManager = NULL; + } + + hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS); + if (hManager == NULL) + goto error; + + hService = OpenService (hManager, lpszService, SERVICE_ALL_ACCESS); + if (hService == NULL) + goto error; + + bRet = DeleteService (hService); + if (bRet == FALSE) + { + if (firstTry && GetLastError () == ERROR_SERVICE_MARKED_FOR_DELETE) + { + // Second try for an eventual no-install driver instance + CloseServiceHandle (hService); + CloseServiceHandle (hManager); + hService = NULL; + hManager = NULL; + + Sleep(1000); + firstTry = FALSE; + goto retry; + } + + goto error; + } + + bOK = TRUE; + +error: + + if (bOK == FALSE && GetLastError ()!= ERROR_SERVICE_DOES_NOT_EXIST) + { + handleWin32Error (hwndDlg, SRC_POS); + MessageBoxW (hwndDlg, GetString ("DRIVER_UINSTALL_FAILED"), lpszTitle, MB_ICONHAND); + } + else + bOK = TRUE; + + if (hService != NULL) + CloseServiceHandle (hService); + + if (hManager != NULL) + CloseServiceHandle (hManager); + + return bOK; +} + + +BOOL DoDriverUnload (HWND hwndDlg) +{ + BOOL bOK = TRUE; + int status; + + status = DriverAttach (); + if (status != 0) + { + if (status == ERR_OS_ERROR && GetLastError () != ERROR_FILE_NOT_FOUND) + { + handleWin32Error (hwndDlg, SRC_POS); + AbortProcess ("NODRIVER"); + } + + if (status != ERR_OS_ERROR) + { + handleError (NULL, status, SRC_POS); + AbortProcess ("NODRIVER"); + } + } + + if (hDriver != INVALID_HANDLE_VALUE) + { + MOUNT_LIST_STRUCT driver; + LONG driverVersion = VERSION_NUM; + int refCount; + DWORD dwResult; + BOOL bResult; + + // Try to determine if it's upgrade (and not reinstall, downgrade, or first-time install). + DetermineUpgradeDowngradeStatus (FALSE, &driverVersion); + + // Test for encrypted boot drive + try + { + BootEncryption bootEnc (hwndDlg); + if (bootEnc.GetDriverServiceStartType() == SERVICE_BOOT_START) + { + try + { + // Check hidden OS update consistency + if (IsHiddenOSRunning()) + { + if (bootEnc.GetInstalledBootLoaderVersion() != VERSION_NUM) + { + if (AskWarnNoYes ("UPDATE_TC_IN_DECOY_OS_FIRST", hwndDlg) == IDNO) + AbortProcessSilent (); + } + } + } + catch (...) { } + + if (bUninstallInProgress && !bootEnc.GetStatus().DriveMounted) + { + try { bootEnc.RegisterFilterDriver (false, BootEncryption::DriveFilter); } catch (...) { } + try { bootEnc.RegisterFilterDriver (false, BootEncryption::VolumeFilter); } catch (...) { } + try { bootEnc.RegisterFilterDriver (false, BootEncryption::DumpFilter); } catch (...) { } + bootEnc.SetDriverServiceStartType (SERVICE_SYSTEM_START); + } + else if (bUninstallInProgress || bDowngrade) + { + Error (bDowngrade ? "SETUP_FAILED_BOOT_DRIVE_ENCRYPTED_DOWNGRADE" : "SETUP_FAILED_BOOT_DRIVE_ENCRYPTED", hwndDlg); + return FALSE; + } + else + { + if (CurrentOSMajor == 6 && CurrentOSMinor == 0 && CurrentOSServicePack < 1) + AbortProcess ("SYS_ENCRYPTION_UPGRADE_UNSUPPORTED_ON_VISTA_SP0"); + + SystemEncryptionUpdate = TRUE; + PortableMode = FALSE; + } + } + } + catch (...) { } + + if (!bUninstall + && (bUpgrade || SystemEncryptionUpdate) + && (!bDevm || SystemEncryptionUpdate)) + { + UnloadDriver = FALSE; + } + + if (PortableMode && !SystemEncryptionUpdate) + UnloadDriver = TRUE; + + if (UnloadDriver) + { + int volumesMounted = 0; + + // Check mounted volumes + bResult = DeviceIoControl (hDriver, TC_IOCTL_IS_ANY_VOLUME_MOUNTED, NULL, 0, &volumesMounted, sizeof (volumesMounted), &dwResult, NULL); + + if (!bResult) + { + bResult = DeviceIoControl (hDriver, TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES, NULL, 0, &driver, sizeof (driver), &dwResult, NULL); + if (bResult) + volumesMounted = driver.ulMountedDrives; + } + + if (bResult) + { + if (volumesMounted != 0) + { + bOK = FALSE; + MessageBoxW (hwndDlg, GetString ("DISMOUNT_ALL_FIRST"), lpszTitle, MB_ICONHAND); + } + } + else + { + bOK = FALSE; + handleWin32Error (hwndDlg, SRC_POS); + } + } + + // Try to close all open TC windows + if (bOK) + { + BOOL TCWindowClosed = FALSE; + + EnumWindows (CloseTCWindowsEnum, (LPARAM) &TCWindowClosed); + + if (TCWindowClosed) + Sleep (2000); + } + + // Test for any applications attached to driver + if (!bUpgrade) + { + bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DEVICE_REFCOUNT, &refCount, sizeof (refCount), &refCount, + sizeof (refCount), &dwResult, NULL); + + if (bOK && bResult && refCount > 1) + { + MessageBoxW (hwndDlg, GetString ("CLOSE_TC_FIRST"), lpszTitle, MB_ICONSTOP); + bOK = FALSE; + } + } + + if (!bOK || UnloadDriver) + { + CloseHandle (hDriver); + hDriver = INVALID_HANDLE_VALUE; + } + } + else + { + // Note that the driver may have already been unloaded during this session (e.g. retry after an error, etc.) so it is not + // guaranteed that the user is installing VeraCrypt for the first time now (we also cannot know if the user has already + // installed and used VeraCrypt on another system before). + bPossiblyFirstTimeInstall = TRUE; + } + + return bOK; +} + + +BOOL UpgradeBootLoader (HWND hwndDlg) +{ + if (!SystemEncryptionUpdate) + return TRUE; + + try + { + BootEncryption bootEnc (hwndDlg); + uint64 bootLoaderVersion = bootEnc.GetInstalledBootLoaderVersion(); + if ((bootLoaderVersion < VERSION_NUM) || (bReinstallMode && (bootLoaderVersion == VERSION_NUM))) + { + StatusMessage (hwndDlg, "INSTALLER_UPDATING_BOOT_LOADER"); + + bootEnc.InstallBootLoader (true); + + if (bootEnc.GetInstalledBootLoaderVersion() <= TC_RESCUE_DISK_UPGRADE_NOTICE_MAX_VERSION) + Info (IsHiddenOSRunning() ? "BOOT_LOADER_UPGRADE_OK_HIDDEN_OS" : "BOOT_LOADER_UPGRADE_OK", hwndDlg); + } + return TRUE; + } + catch (Exception &e) + { + e.Show (hwndDlg); + } + catch (...) { } + + Error ("BOOT_LOADER_UPGRADE_FAILED", hwndDlg); + return FALSE; +} + + +BOOL DoShortcutsUninstall (HWND hwndDlg, wchar_t *szDestDir) +{ + wchar_t szLinkDir[TC_MAX_PATH]; + wchar_t szTmp2[TC_MAX_PATH]; + BOOL bSlash, bOK = FALSE; + HRESULT hOle; + int x; + BOOL allUsers = FALSE; + + hOle = OleInitialize (NULL); + + // User start menu + SHGetSpecialFolderPath (hwndDlg, szLinkDir, CSIDL_PROGRAMS, 0); + x = wcslen (szLinkDir); + if (szLinkDir[x - 1] == L'\\') + bSlash = TRUE; + else + bSlash = FALSE; + + if (bSlash == FALSE) + StringCbCatW (szLinkDir, sizeof(szLinkDir), L"\\"); + + StringCbCatW (szLinkDir, sizeof(szLinkDir), L"VeraCrypt"); + + // Global start menu + { + struct _stat st; + wchar_t path[TC_MAX_PATH]; + + SHGetSpecialFolderPath (hwndDlg, path, CSIDL_COMMON_PROGRAMS, 0); + StringCbCatW (path, sizeof(path), L"\\VeraCrypt"); + + if (_wstat (path, &st) == 0) + { + StringCbCopyW (szLinkDir, sizeof(szLinkDir), path); + allUsers = TRUE; + } + } + + // Start menu entries + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt.lnk"); + RemoveMessage (hwndDlg, szTmp2); + if (StatDeleteFile (szTmp2, FALSE) == FALSE) + goto error; + + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCryptExpander.lnk"); + RemoveMessage (hwndDlg, szTmp2); + if (StatDeleteFile (szTmp2, FALSE) == FALSE) + goto error; + + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt Website.url"); + RemoveMessage (hwndDlg, szTmp2); + if (StatDeleteFile (szTmp2, FALSE) == FALSE) + goto error; + + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\Uninstall VeraCrypt.lnk"); + RemoveMessage (hwndDlg, szTmp2); + if (StatDeleteFile (szTmp2, FALSE) == FALSE) + goto error; + + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt User's Guide.lnk"); + StatDeleteFile (szTmp2, FALSE); + + // Start menu group + RemoveMessage ((HWND) hwndDlg, szLinkDir); + if (StatRemoveDirectory (szLinkDir) == FALSE) + handleWin32Error ((HWND) hwndDlg, SRC_POS); + + // Desktop icon + + if (allUsers) + SHGetSpecialFolderPath (hwndDlg, szLinkDir, CSIDL_COMMON_DESKTOPDIRECTORY, 0); + else + SHGetSpecialFolderPath (hwndDlg, szLinkDir, CSIDL_DESKTOPDIRECTORY, 0); + + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt.lnk"); + + RemoveMessage (hwndDlg, szTmp2); + if (StatDeleteFile (szTmp2, FALSE) == FALSE) + goto error; + + bOK = TRUE; + +error: + OleUninitialize (); + + return bOK; +} + +BOOL DoShortcutsInstall (HWND hwndDlg, wchar_t *szDestDir, BOOL bProgGroup, BOOL bDesktopIcon) +{ + wchar_t szLinkDir[TC_MAX_PATH], szDir[TC_MAX_PATH]; + wchar_t szTmp[TC_MAX_PATH], szTmp2[TC_MAX_PATH], szTmp3[TC_MAX_PATH]; + BOOL bSlash, bOK = FALSE; + HRESULT hOle; + int x; + + if (bProgGroup == FALSE && bDesktopIcon == FALSE) + return TRUE; + + hOle = OleInitialize (NULL); + + GetProgramPath (hwndDlg, szLinkDir); + + x = wcslen (szLinkDir); + if (szLinkDir[x - 1] == L'\\') + bSlash = TRUE; + else + bSlash = FALSE; + + if (bSlash == FALSE) + StringCbCatW (szLinkDir, sizeof(szLinkDir), L"\\"); + + StringCbCatW (szLinkDir, sizeof(szLinkDir), L"VeraCrypt"); + + StringCbCopyW (szDir, sizeof(szDir), szDestDir); + x = wcslen (szDestDir); + if (szDestDir[x - 1] == L'\\') + bSlash = TRUE; + else + bSlash = FALSE; + + if (bSlash == FALSE) + StringCbCatW (szDir, sizeof(szDir), L"\\"); + + if (bProgGroup) + { + FILE *f; + + if (mkfulldir (szLinkDir, TRUE) != 0) + { + if (mkfulldir (szLinkDir, FALSE) != 0) + { + wchar_t szTmpW[TC_MAX_PATH]; + + handleWin32Error (hwndDlg, SRC_POS); + StringCbPrintfW (szTmpW, sizeof(szTmpW), GetString ("CANT_CREATE_FOLDER"), szLinkDir); + MessageBoxW (hwndDlg, szTmpW, lpszTitle, MB_ICONHAND); + goto error; + } + } + + StringCbPrintfW (szTmp, sizeof(szTmp), L"%s%s", szDir, L"VeraCrypt.exe"); + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt.lnk"); + + IconMessage (hwndDlg, szTmp2); + if (CreateLink (szTmp, L"", szTmp2, NULL, -1) != S_OK) + goto error; + + StringCbPrintfW (szTmp, sizeof(szTmp), L"%s%s", szDir, L"VeraCryptExpander.exe"); + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCryptExpander.lnk"); + + IconMessage (hwndDlg, szTmp2); + if (CreateLink (szTmp, L"", szTmp2, NULL, -1) != S_OK) + goto error; + + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt Website.url"); + IconMessage (hwndDlg, szTmp2); + f = _wfopen (szTmp2, L"w"); + if (f) + { + fprintf (f, "[InternetShortcut]\nURL=%s\n", TC_APPLINK); + + CheckFileStreamWriteErrors (hwndDlg, f, szTmp2); + fclose (f); + } + else + goto error; + + StringCbPrintfW (szTmp, sizeof(szTmp), L"%s%s", szDir, L"VeraCrypt Setup.exe"); + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\Uninstall VeraCrypt.lnk"); + if (GetSystemDirectory (szTmp3, ARRAYSIZE(szTmp3))) + { + StringCbCatW (szTmp3, sizeof(szTmp3), L"\\control.exe"); + } + else + StringCbCopyW(szTmp3, sizeof(szTmp3), L"C:\\Windows\\System32\\control.exe"); + + IconMessage (hwndDlg, szTmp2); + if (CreateLink (szTmp3, L"appwiz.cpl", szTmp2, szTmp, 0) != S_OK) + goto error; + + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt User's Guide.lnk"); + StatDeleteFile (szTmp2, FALSE); + } + + if (bDesktopIcon) + { + StringCbCopyW (szDir, sizeof(szDir), szDestDir); + x = wcslen (szDestDir); + if (szDestDir[x - 1] == L'\\') + bSlash = TRUE; + else + bSlash = FALSE; + + if (bSlash == FALSE) + StringCbCatW (szDir, sizeof(szDir), L"\\"); + + if (bForAllUsers) + SHGetSpecialFolderPath (hwndDlg, szLinkDir, CSIDL_COMMON_DESKTOPDIRECTORY, 0); + else + SHGetSpecialFolderPath (hwndDlg, szLinkDir, CSIDL_DESKTOPDIRECTORY, 0); + + StringCbPrintfW (szTmp, sizeof(szTmp), L"%s%s", szDir, L"VeraCrypt.exe"); + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt.lnk"); + + IconMessage (hwndDlg, szTmp2); + + if (CreateLink (szTmp, L"", szTmp2, NULL, -1) != S_OK) + goto error; + } + + bOK = TRUE; + +error: + OleUninitialize (); + + return bOK; +} + + +void OutcomePrompt (HWND hwndDlg, BOOL bOK) +{ + if (bOK) + { + EnableWindow (GetDlgItem ((HWND) hwndDlg, IDCANCEL), FALSE); + + bDone = TRUE; + + if (bUninstall == FALSE) + { + if (bDevm) + PostMessage (MainDlg, WM_CLOSE, 0, 0); + else if (bPossiblyFirstTimeInstall || bRepairMode || (!bUpgrade && !bDowngrade)) + Info ("INSTALL_OK", hwndDlg); + else + Info ("SETUP_UPDATE_OK", hwndDlg); + } + else + { + wchar_t str[4096]; + + StringCbPrintfW (str, sizeof(str), GetString ("UNINSTALL_OK"), InstallationPath); + MessageBoxW (hwndDlg, str, lpszTitle, MB_ICONASTERISK); + } + } + else + { + if (bUninstall == FALSE) + Error ("INSTALL_FAILED", hwndDlg); + else + Error ("UNINSTALL_FAILED", hwndDlg); + } +} + +static void SetSystemRestorePoint (HWND hwndDlg, BOOL finalize) +{ + static RESTOREPOINTINFO RestPtInfo; + static STATEMGRSTATUS SMgrStatus; + static BOOL failed = FALSE; + static BOOL (__stdcall *_SRSetRestorePoint)(PRESTOREPOINTINFO, PSTATEMGRSTATUS); + + if (!SystemRestoreDll) return; + + _SRSetRestorePoint = (BOOL (__stdcall *)(PRESTOREPOINTINFO, PSTATEMGRSTATUS))GetProcAddress (SystemRestoreDll,"SRSetRestorePointW"); + if (_SRSetRestorePoint == 0) + { + FreeLibrary (SystemRestoreDll); + SystemRestoreDll = 0; + return; + } + + if (!finalize) + { + StatusMessage (hwndDlg, "CREATING_SYS_RESTORE"); + + RestPtInfo.dwEventType = BEGIN_SYSTEM_CHANGE; + RestPtInfo.dwRestorePtType = bUninstall ? APPLICATION_UNINSTALL : APPLICATION_INSTALL | DEVICE_DRIVER_INSTALL; + RestPtInfo.llSequenceNumber = 0; + StringCbCopyW (RestPtInfo.szDescription, sizeof(RestPtInfo.szDescription), bUninstall ? L"VeraCrypt uninstallation" : L"VeraCrypt installation"); + + if(!_SRSetRestorePoint (&RestPtInfo, &SMgrStatus)) + { + StatusMessage (hwndDlg, "FAILED_SYS_RESTORE"); + failed = TRUE; + } + } + else if (!failed) + { + RestPtInfo.dwEventType = END_SYSTEM_CHANGE; + RestPtInfo.llSequenceNumber = SMgrStatus.llSequenceNumber; + + if(!_SRSetRestorePoint(&RestPtInfo, &SMgrStatus)) + { + StatusMessage (hwndDlg, "FAILED_SYS_RESTORE"); + } + } +} + +void DoUninstall (void *arg) +{ + HWND hwndDlg = (HWND) arg; + BOOL bOK = TRUE; + BOOL bTempSkipSysRestore = FALSE; + + if (!Rollback) + EnableWindow (GetDlgItem ((HWND) hwndDlg, IDC_UNINSTALL), FALSE); + + WaitCursor (); + + if (!Rollback) + { + ClearLogWindow (hwndDlg); + } + + if (DoDriverUnload (hwndDlg) == FALSE) + { + bOK = FALSE; + bTempSkipSysRestore = TRUE; // Volumes are possibly mounted; defer System Restore point creation for this uninstall attempt. + } + else + { + if (!Rollback && bSystemRestore && !bTempSkipSysRestore) + SetSystemRestorePoint (hwndDlg, FALSE); + + if (DoServiceUninstall (hwndDlg, L"veracrypt") == FALSE) + { + bOK = FALSE; + } + else if (DoRegUninstall ((HWND) hwndDlg, FALSE) == FALSE) + { + bOK = FALSE; + } + else if (DoFilesInstall ((HWND) hwndDlg, InstallationPath) == FALSE) + { + bOK = FALSE; + } + else if (DoShortcutsUninstall (hwndDlg, InstallationPath) == FALSE) + { + bOK = FALSE; + } + else if (!DoApplicationDataUninstall (hwndDlg)) + { + bOK = FALSE; + } + else + { + wchar_t temp[MAX_PATH]; + FILE *f; + + // Deprecated service + DoServiceUninstall (hwndDlg, L"VeraCryptService"); + + GetTempPath (ARRAYSIZE (temp), temp); + StringCbPrintfW (UninstallBatch, sizeof (UninstallBatch), L"%sVeraCrypt-Uninstall.bat", temp); + + UninstallBatch [ARRAYSIZE(UninstallBatch)-1] = 0; + + // Create uninstall batch + f = _wfopen (UninstallBatch, L"w"); + if (!f) + bOK = FALSE; + else + { + fwprintf (f,L":loop\n" + L"del \"%s%s\"\n" + L"if exist \"%s%s\" goto loop\n" + L"rmdir \"%s\"\n" + L"del \"%s\"", + InstallationPath, L"VeraCrypt Setup.exe", + InstallationPath, L"VeraCrypt Setup.exe", + InstallationPath, + UninstallBatch + ); + + CheckFileStreamWriteErrors (hwndDlg, f, UninstallBatch); + fclose (f); + } + } + } + + NormalCursor (); + + if (Rollback) + return; + + if (bSystemRestore && !bTempSkipSysRestore) + SetSystemRestorePoint (hwndDlg, TRUE); + + if (bOK) + PostMessage (hwndDlg, TC_APPMSG_UNINSTALL_SUCCESS, 0, 0); + else + bUninstallInProgress = FALSE; + + EnableWindow (GetDlgItem ((HWND) hwndDlg, IDC_UNINSTALL), TRUE); + OutcomePrompt (hwndDlg, bOK); +} + +void DoInstall (void *arg) +{ + HWND hwndDlg = (HWND) arg; + BOOL bOK = TRUE; + wchar_t path[MAX_PATH]; + + BootEncryption bootEnc (hwndDlg); + + // Refresh the main GUI (wizard thread) + InvalidateRect (MainDlg, NULL, TRUE); + + ClearLogWindow (hwndDlg); + + if (mkfulldir (InstallationPath, TRUE) != 0) + { + if (mkfulldir (InstallationPath, FALSE) != 0) + { + wchar_t szTmp[TC_MAX_PATH]; + + handleWin32Error (hwndDlg, SRC_POS); + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CANT_CREATE_FOLDER"), InstallationPath); + MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_ICONHAND); + Error ("INSTALL_FAILED", hwndDlg); + PostMessage (MainDlg, TC_APPMSG_INSTALL_FAILURE, 0, 0); + return; + } + } + + UpdateProgressBarProc(2); + + if (DoDriverUnload (hwndDlg) == FALSE) + { + NormalCursor (); + PostMessage (MainDlg, TC_APPMSG_INSTALL_FAILURE, 0, 0); + return; + } + + if (bUpgrade + && (IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L".exe") + || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L"-x86.exe") + || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L"-x64.exe") + || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L" Format.exe") + || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L" Format-x86.exe") + || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L" Format-x64.exe") + || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L"Expander.exe") + || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L"Expander-x86.exe") + || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L"Expander-x64.exe") + || IsFileInUse (wstring (InstallationPath) + L'\\' + _T(TC_APP_NAME) L" Setup.exe") + ) + ) + { + NormalCursor (); + Error ("CLOSE_TC_FIRST", hwndDlg); + PostMessage (MainDlg, TC_APPMSG_INSTALL_FAILURE, 0, 0); + return; + } + + UpdateProgressBarProc(12); + + if (bSystemRestore) + SetSystemRestorePoint (hwndDlg, FALSE); + + UpdateProgressBarProc(48); + + if (bDisableSwapFiles + && IsPagingFileActive (FALSE)) + { + if (!DisablePagingFile()) + { + handleWin32Error (hwndDlg, SRC_POS); + Error ("FAILED_TO_DISABLE_PAGING_FILES", hwndDlg); + } + else + bRestartRequired = TRUE; + } + + UpdateProgressBarProc(50); + + // Remove deprecated + DoServiceUninstall (hwndDlg, L"VeraCryptService"); + + UpdateProgressBarProc(55); + + if (!SystemEncryptionUpdate) + DoRegUninstall ((HWND) hwndDlg, TRUE); + + UpdateProgressBarProc(61); + + GetWindowsDirectory (path, ARRAYSIZE (path)); + StringCbCatW (path, sizeof (path), L"\\VeraCrypt Setup.exe"); + StatDeleteFile (path, FALSE); + + if (UpdateProgressBarProc(63) && UnloadDriver && DoServiceUninstall (hwndDlg, L"veracrypt") == FALSE) + { + bOK = FALSE; + } + else if (UpdateProgressBarProc(72) && DoFilesInstall ((HWND) hwndDlg, InstallationPath) == FALSE) + { + bOK = FALSE; + } + else if (UpdateProgressBarProc(80) && DoRegInstall ((HWND) hwndDlg, InstallationPath, bRegisterFileExt) == FALSE) + { + bOK = FALSE; + } + else if (UpdateProgressBarProc(85) && UnloadDriver && DoDriverInstall (hwndDlg) == FALSE) + { + bOK = FALSE; + } + else if (UpdateProgressBarProc(90) && SystemEncryptionUpdate && UpgradeBootLoader (hwndDlg) == FALSE) + { + bOK = FALSE; + } + else if (UpdateProgressBarProc(93) && DoShortcutsInstall (hwndDlg, InstallationPath, bAddToStartMenu, bDesktopIcon) == FALSE) + { + bOK = FALSE; + } + + if (!UnloadDriver) + bRestartRequired = TRUE; + + try + { + bootEnc.RenameDeprecatedSystemLoaderBackup(); + } + catch (...) { } + + if (bOK) + UpdateProgressBarProc(97); + + if (bSystemRestore) + SetSystemRestorePoint (hwndDlg, TRUE); + + if (bOK) + { + UpdateProgressBarProc(100); + UninstallBatch[0] = 0; + StatusMessage (hwndDlg, "INSTALL_COMPLETED"); + } + else + { + UpdateProgressBarProc(0); + + if (!SystemEncryptionUpdate) + { + bUninstall = TRUE; + Rollback = TRUE; + Silent = TRUE; + + DoUninstall (hwndDlg); + + bUninstall = FALSE; + Rollback = FALSE; + Silent = FALSE; + + StatusMessage (hwndDlg, "ROLLBACK"); + } + else + { + Warning ("SYS_ENC_UPGRADE_FAILED", hwndDlg); + } + } + + OutcomePrompt (hwndDlg, bOK); + + if (bOK && !bUninstall && !bDowngrade && !bRepairMode && !bDevm) + { + if (!IsHiddenOSRunning()) // A hidden OS user should not see the post-install notes twice (on decoy OS and then on hidden OS). + { + if (bRestartRequired || SystemEncryptionUpdate) + { + // Restart required + + if (bUpgrade) + { + SavePostInstallTasksSettings (TC_POST_INSTALL_CFG_RELEASE_NOTES); + } + else if (bPossiblyFirstTimeInstall) + { + SavePostInstallTasksSettings (TC_POST_INSTALL_CFG_TUTORIAL); + } + } + else + { + // No restart will be required + + if (bUpgrade) + { + bPromptReleaseNotes = TRUE; + } + else if (bPossiblyFirstTimeInstall) + { + bPromptTutorial = TRUE; + } + } + } + } + + PostMessage (MainDlg, bOK ? TC_APPMSG_INSTALL_SUCCESS : TC_APPMSG_INSTALL_FAILURE, 0, 0); +} + + +void SetInstallationPath (HWND hwndDlg) +{ + HKEY hkey; + BOOL bInstallPathDetermined = FALSE; + wchar_t path[MAX_PATH+20]; + ITEMIDLIST *itemList; + + memset (InstallationPath, 0, sizeof (InstallationPath)); + + // Determine if VeraCrypt is already installed and try to determine its "Program Files" location + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VeraCrypt", 0, KEY_READ | KEY_WOW64_32KEY, &hkey) == ERROR_SUCCESS) + { + /* Default 'UninstallString' registry strings written by VeraCrypt: + ------------------------------------------------------------------------------------ + 5.0+ "C:\Program Files\VeraCrypt\VeraCrypt Setup.exe" /u + */ + + wchar_t rv[MAX_PATH*4]; + DWORD size = sizeof (rv); + if (RegQueryValueEx (hkey, L"UninstallString", 0, 0, (LPBYTE) &rv, &size) == ERROR_SUCCESS && wcsrchr (rv, L'/')) + { + size_t len = 0; + + // Cut and paste the location (path) where VeraCrypt is installed to InstallationPath + if (rv[0] == L'"') + { + len = wcsrchr (rv, L'/') - rv - 2; + StringCchCopyNW (InstallationPath, ARRAYSIZE(InstallationPath), rv + 1, len); + InstallationPath [len] = 0; + bInstallPathDetermined = TRUE; + + if (InstallationPath [wcslen (InstallationPath) - 1] != L'\\') + { + len = wcsrchr (InstallationPath, L'\\') - InstallationPath; + InstallationPath [len] = 0; + } + } + + } + RegCloseKey (hkey); + } + + if (bInstallPathDetermined) + { + wchar_t mp[MAX_PATH]; + + // Determine whether we were launched from the folder where VeraCrypt is installed + GetModuleFileName (NULL, mp, ARRAYSIZE (mp)); + if (wcsncmp (InstallationPath, mp, min (wcslen(InstallationPath), wcslen(mp))) == 0) + { + // We were launched from the folder where VeraCrypt is installed + + if (!IsNonInstallMode() && !bDevm) + bChangeMode = TRUE; + } + } + else + { + /* VeraCrypt is not installed or it wasn't possible to determine where it is installed. */ + + // Default "Program Files" path. + SHGetSpecialFolderLocation (hwndDlg, CSIDL_PROGRAM_FILES, &itemList); + SHGetPathFromIDList (itemList, path); + + if (Is64BitOs()) + { + // Use a unified default installation path (registry redirection of %ProgramFiles% does not work if the installation path is user-selectable) + wstring s = path; + size_t p = s.find (L" (x86)"); + if (p != wstring::npos) + { + s = s.substr (0, p); + if (_waccess (s.c_str(), 0) != -1) + StringCbCopyW (path, sizeof (path), s.c_str()); + } + } + + StringCbCatW (path, sizeof(path), L"\\VeraCrypt\\"); + StringCbCopyW (InstallationPath, sizeof(InstallationPath), path); + } + + // Make sure the path ends with a backslash + if (InstallationPath [wcslen (InstallationPath) - 1] != L'\\') + { + StringCbCatW (InstallationPath, sizeof(InstallationPath), L"\\"); + } +} + + +// Handler for uninstall only (install is handled by the wizard) +BOOL CALLBACK UninstallDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + + switch (msg) + { + case WM_INITDIALOG: + + MainDlg = hwndDlg; + + if (!CreateAppSetupMutex ()) + AbortProcess ("TC_INSTALLER_IS_RUNNING"); + + InitDialog (hwndDlg); + LocalizeDialog (hwndDlg, NULL); + + SetWindowTextW (hwndDlg, lpszTitle); + + // System Restore + SetCheckBox (hwndDlg, IDC_SYSTEM_RESTORE, bSystemRestore); + if (SystemRestoreDll == 0) + { + SetCheckBox (hwndDlg, IDC_SYSTEM_RESTORE, FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_SYSTEM_RESTORE), FALSE); + } + + SetFocus (GetDlgItem (hwndDlg, IDC_UNINSTALL)); + + return 1; + + case WM_SYSCOMMAND: + if (lw == IDC_ABOUT) + { + DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_ABOUT_DLG), hwndDlg, (DLGPROC) AboutDlgProc); + return 1; + } + return 0; + + case WM_COMMAND: + if (lw == IDC_UNINSTALL) + { + if (bDone) + { + bUninstallInProgress = FALSE; + PostMessage (hwndDlg, WM_CLOSE, 0, 0); + return 1; + } + + bUninstallInProgress = TRUE; + + WaitCursor (); + + if (bUninstall) + _beginthread (DoUninstall, 0, (void *) hwndDlg); + + return 1; + } + + if (lw == IDC_SYSTEM_RESTORE) + { + bSystemRestore = IsButtonChecked (GetDlgItem (hwndDlg, IDC_SYSTEM_RESTORE)); + return 1; + } + + if (lw == IDCANCEL) + { + PostMessage (hwndDlg, WM_CLOSE, 0, 0); + return 1; + } + + return 0; + + case TC_APPMSG_UNINSTALL_SUCCESS: + SetWindowTextW (GetDlgItem ((HWND) hwndDlg, IDC_UNINSTALL), GetString ("FINALIZE")); + NormalCursor (); + return 1; + + case WM_CLOSE: + if (bUninstallInProgress) + { + NormalCursor(); + if (AskNoYes("CONFIRM_EXIT_UNIVERSAL", hwndDlg) == IDNO) + { + return 1; + } + WaitCursor (); + } + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + return 0; +} + + +int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpszCommandLine, int nCmdShow) +{ + atexit (localcleanup); + + SelfExtractStartupInit(); + + lpszTitle = L"VeraCrypt Setup"; + + /* Call InitApp to initialize the common code */ + InitApp (hInstance, NULL); + + if (IsAdmin () != TRUE) + if (MessageBoxW (NULL, GetString ("SETUP_ADMIN"), lpszTitle, MB_YESNO | MB_ICONQUESTION) != IDYES) + { + FinalizeApp (); + exit (1); + } + + /* Setup directory */ + { + wchar_t *s; + GetModuleFileName (NULL, SetupFilesDir, ARRAYSIZE (SetupFilesDir)); + s = wcsrchr (SetupFilesDir, L'\\'); + if (s) + s[1] = 0; + } + + /* Parse command line arguments */ + + if (lpszCommandLine[0] == L'/') + { + if (lpszCommandLine[1] == L'u') + { + // Uninstall: /u + + bUninstall = TRUE; + } + else if (lpszCommandLine[1] == L'c') + { + // Change: /c + + bChangeMode = TRUE; + } + else if (lpszCommandLine[1] == L'p') + { + // Create self-extracting package: /p + + bMakePackage = TRUE; + } + else if (lpszCommandLine[1] == L'd') + { + // Dev mode: /d + bDevm = TRUE; + } + } + + if (bMakePackage) + { + /* Create self-extracting package */ + + MakeSelfExtractingPackage (NULL, SetupFilesDir); + } + else + { + SetInstallationPath (NULL); + + if (!bUninstall) + { + if (IsSelfExtractingPackage()) + { + if (!VerifyPackageIntegrity()) + { + // Package corrupted + exit (1); + } + bDevm = FALSE; + } + else if (!bDevm) + { + MessageBox (NULL, L"Error: This installer file does not contain any compressed files.\n\nTo create a self-extracting installation package (with embedded compressed files), run:\n\"VeraCrypt Setup.exe\" /p", L"VeraCrypt", MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); + FinalizeApp (); + exit (1); + } + + if (bChangeMode) + { + /* VeraCrypt is already installed on this system and we were launched from the Program Files folder */ + + char *tmpStr[] = {0, "SELECT_AN_ACTION", "REPAIR_REINSTALL", "UNINSTALL", "EXIT", 0}; + + // Ask the user to select either Repair or Unistallation + switch (AskMultiChoice ((void **) tmpStr, FALSE, NULL)) + { + case 1: + bRepairMode = TRUE; + break; + case 2: + bUninstall = TRUE; + break; + default: + FinalizeApp (); + exit (1); + } + } + } + + // System Restore + if (IsSystemRestoreEnabled ()) + { + wchar_t dllPath[MAX_PATH]; + if (GetSystemDirectory (dllPath, MAX_PATH)) + { + StringCbCatW(dllPath, sizeof(dllPath), L"\\srclient.dll"); + } + else + StringCbCopyW(dllPath, sizeof(dllPath), L"C:\\Windows\\System32\\srclient.dll"); + SystemRestoreDll = LoadLibrary (dllPath); + } + else + SystemRestoreDll = 0; + + if (!bUninstall) + { + /* Create the main dialog for install */ + + DialogBoxParamW (hInstance, MAKEINTRESOURCEW (IDD_INSTL_DLG), NULL, (DLGPROC) MainDialogProc, + (LPARAM)lpszCommandLine); + } + else + { + /* Create the main dialog for uninstall */ + + DialogBoxW (hInstance, MAKEINTRESOURCEW (IDD_UNINSTALL), NULL, (DLGPROC) UninstallDlgProc); + + if (UninstallBatch[0]) + { + STARTUPINFO si; + PROCESS_INFORMATION pi; + + ZeroMemory (&si, sizeof (si)); + si.cb = sizeof (si); + si.dwFlags = STARTF_USESHOWWINDOW; + si.wShowWindow = SW_HIDE; + + if (!CreateProcess (UninstallBatch, NULL, NULL, NULL, FALSE, IDLE_PRIORITY_CLASS, NULL, NULL, &si, &pi)) + DeleteFile (UninstallBatch); + else + { + CloseHandle (pi.hProcess); + CloseHandle (pi.hThread); + } + } + } + } + FinalizeApp (); + return 0; +} diff --git a/src/Setup/Setup.h b/src/Setup/Setup.h index 0de3417a..da31f3cd 100644 --- a/src/Setup/Setup.h +++ b/src/Setup/Setup.h @@ -1,190 +1,190 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifndef SETUP_H -#define SETUP_H - -#ifdef __cplusplus -extern "C" { -#endif - -// Specifies what files to install, where (determined by the prefix), and in what order -static wchar_t *szFiles[]= -{ - L"AVeraCrypt User Guide.pdf", - L"ALicense.txt", - L"ALICENSE", - L"ANOTICE", - L"AVeraCrypt.exe", - L"AVeraCryptExpander.exe", - L"AVeraCrypt Format.exe", - L"AVeraCrypt-x86.exe", - L"AVeraCryptExpander-x86.exe", - L"AVeraCrypt Format-x86.exe", - L"AVeraCrypt-x64.exe", - L"AVeraCryptExpander-x64.exe", - L"AVeraCrypt Format-x64.exe", - L"Averacrypt.sys", - L"Averacrypt-x64.sys", - L"Dveracrypt.sys", - L"AVeraCrypt Setup.exe", - L"ALanguage.ar.xml", - L"ALanguage.be.xml", - L"ALanguage.bg.xml", - L"ALanguage.ca.xml", - L"ALanguage.cs.xml", - L"ALanguage.da.xml", - L"ALanguage.de.xml", - L"ALanguage.el.xml", - L"ALanguage.es.xml", - L"ALanguage.et.xml", - L"ALanguage.eu.xml", - L"ALanguage.fa.xml", - L"ALanguage.fi.xml", - L"ALanguage.fr.xml", - L"ALanguage.hu.xml", - L"ALanguage.id.xml", - L"ALanguage.it.xml", - L"ALanguage.ja.xml", - L"ALanguage.ka.xml", - L"ALanguage.ko.xml", - L"ALanguage.lv.xml", - L"ALanguage.my.xml", - L"ALanguage.nl.xml", - L"ALanguage.nn.xml", - L"ALanguage.pl.xml", - L"ALanguage.pt-br.xml", - L"ALanguage.ru.xml", - L"ALanguage.sk.xml", - L"ALanguage.sl.xml", - L"ALanguage.sv.xml", - L"ALanguage.tr.xml", - L"ALanguage.uk.xml", - L"ALanguage.uz.xml", - L"ALanguage.vi.xml", - L"ALanguage.zh-cn.xml", - L"ALanguage.zh-hk.xml", - L"ALanguage.zh-tw.xml" -}; - -// Specifies what files are included in self-extracting packages (no other files will be packaged or extracted). -static wchar_t *szCompressedFiles[]= -{ - L"VeraCrypt User Guide.pdf", - L"License.txt", - L"LICENSE", - L"NOTICE", - L"VeraCrypt.exe", - L"VeraCryptExpander.exe", - L"VeraCrypt Format.exe", - L"VeraCrypt-x64.exe", - L"VeraCryptExpander-x64.exe", - L"VeraCrypt Format-x64.exe", - L"veracrypt.sys", - L"veracrypt-x64.sys", - L"Language.ar.xml", - L"Language.be.xml", - L"Language.bg.xml", - L"Language.ca.xml", - L"Language.cs.xml", - L"Language.da.xml", - L"Language.de.xml", - L"Language.el.xml", - L"Language.es.xml", - L"Language.et.xml", - L"Language.eu.xml", - L"Language.fa.xml", - L"Language.fi.xml", - L"Language.fr.xml", - L"Language.hu.xml", - L"Language.id.xml", - L"Language.it.xml", - L"Language.ja.xml", - L"Language.ka.xml", - L"Language.ko.xml", - L"Language.lv.xml", - L"Language.my.xml", - L"Language.nl.xml", - L"Language.nn.xml", - L"Language.pl.xml", - L"Language.pt-br.xml", - L"Language.ru.xml", - L"Language.sk.xml", - L"Language.sl.xml", - L"Language.sv.xml", - L"Language.tr.xml", - L"Language.uk.xml", - L"Language.uz.xml", - L"Language.vi.xml", - L"Language.zh-cn.xml", - L"Language.zh-hk.xml", - L"Language.zh-tw.xml" -}; - -#define FILENAME_64BIT_DRIVER L"veracrypt-x64.sys" -#define NBR_COMPRESSED_FILES (sizeof(szCompressedFiles) / sizeof(szCompressedFiles[0])) - -void localcleanup (void); -BOOL StatDeleteFile ( wchar_t *lpszFile, BOOL bCheckForOldFile ); -BOOL StatRemoveDirectory ( wchar_t *lpszDir ); -HRESULT CreateLink ( wchar_t *lpszPathObj , wchar_t *lpszArguments , wchar_t *lpszPathLink ); -void GetProgramPath ( HWND hwndDlg , wchar_t *path ); -void StatusMessage (HWND hwndDlg, char *stringId); -void StatusMessageParam (HWND hwndDlg, char *stringId, wchar_t *param); -void ClearLogWindow (HWND hwndDlg); -void RegMessage ( HWND hwndDlg , wchar_t *txt ); -void RegRemoveMessage (HWND hwndDlg, wchar_t *txt); -void CopyMessage ( HWND hwndDlg , wchar_t *txt ); -void RemoveMessage ( HWND hwndDlg , wchar_t *txt ); -void IconMessage ( HWND hwndDlg , wchar_t *txt ); -static int CALLBACK BrowseCallbackProc ( HWND hwnd , UINT uMsg , LPARAM lp , LPARAM pData ); -void LoadLicense ( HWND hwndDlg ); -void DetermineUpgradeDowngradeStatus (BOOL bCloseDriverHandle, LONG *driverVersionPtr); -BOOL DoFilesInstall ( HWND hwndDlg , wchar_t *szDestDir ); -BOOL DoRegInstall ( HWND hwndDlg , wchar_t *szDestDir , BOOL bInstallType ); -BOOL DoRegUninstall (HWND hwndDlg, BOOL bRemoveDeprecated); -BOOL DoServiceUninstall ( HWND hwndDlg , wchar_t *lpszService ); -BOOL DoDriverUnload ( HWND hwndDlg ); -BOOL DoShortcutsInstall ( HWND hwndDlg , wchar_t *szDestDir , BOOL bProgGroup, BOOL bDesktopIcon ); -BOOL DoShortcutsUninstall (HWND hwndDlg, wchar_t *szDestDir); -void OutcomePrompt ( HWND hwndDlg , BOOL bOK ); -void DoUninstall ( void *hwndDlg ); -void DoInstall ( void *hwndDlg ); -void SetInstallationPath (HWND hwndDlg); -BOOL UpgradeBootLoader (HWND hwndDlg); -BOOL CALLBACK InstallDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); - -extern BOOL bDevm; -extern BOOL Rollback; -extern BOOL bUpgrade; -extern BOOL bPossiblyFirstTimeInstall; -extern BOOL bRepairMode; -extern BOOL bReinstallMode; -extern BOOL bSystemRestore; -extern BOOL bDisableSwapFiles; -extern BOOL bForAllUsers; -extern BOOL bRegisterFileExt; -extern BOOL bAddToStartMenu; -extern BOOL bDesktopIcon; -extern BOOL bDesktopIconStatusDetermined; -extern BOOL SystemEncryptionUpdate; -extern BOOL bRestartRequired; -extern HMODULE volatile SystemRestoreDll; -extern wchar_t InstallationPath[TC_MAX_PATH]; -extern wchar_t SetupFilesDir[TC_MAX_PATH]; - -#ifdef __cplusplus -} -#endif - -#endif // #ifndef SETUP_H +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifndef SETUP_H +#define SETUP_H + +#ifdef __cplusplus +extern "C" { +#endif + +// Specifies what files to install, where (determined by the prefix), and in what order +static wchar_t *szFiles[]= +{ + L"AVeraCrypt User Guide.pdf", + L"ALicense.txt", + L"ALICENSE", + L"ANOTICE", + L"AVeraCrypt.exe", + L"AVeraCryptExpander.exe", + L"AVeraCrypt Format.exe", + L"AVeraCrypt-x86.exe", + L"AVeraCryptExpander-x86.exe", + L"AVeraCrypt Format-x86.exe", + L"AVeraCrypt-x64.exe", + L"AVeraCryptExpander-x64.exe", + L"AVeraCrypt Format-x64.exe", + L"Averacrypt.sys", + L"Averacrypt-x64.sys", + L"Dveracrypt.sys", + L"AVeraCrypt Setup.exe", + L"ALanguage.ar.xml", + L"ALanguage.be.xml", + L"ALanguage.bg.xml", + L"ALanguage.ca.xml", + L"ALanguage.cs.xml", + L"ALanguage.da.xml", + L"ALanguage.de.xml", + L"ALanguage.el.xml", + L"ALanguage.es.xml", + L"ALanguage.et.xml", + L"ALanguage.eu.xml", + L"ALanguage.fa.xml", + L"ALanguage.fi.xml", + L"ALanguage.fr.xml", + L"ALanguage.hu.xml", + L"ALanguage.id.xml", + L"ALanguage.it.xml", + L"ALanguage.ja.xml", + L"ALanguage.ka.xml", + L"ALanguage.ko.xml", + L"ALanguage.lv.xml", + L"ALanguage.my.xml", + L"ALanguage.nl.xml", + L"ALanguage.nn.xml", + L"ALanguage.pl.xml", + L"ALanguage.pt-br.xml", + L"ALanguage.ru.xml", + L"ALanguage.sk.xml", + L"ALanguage.sl.xml", + L"ALanguage.sv.xml", + L"ALanguage.tr.xml", + L"ALanguage.uk.xml", + L"ALanguage.uz.xml", + L"ALanguage.vi.xml", + L"ALanguage.zh-cn.xml", + L"ALanguage.zh-hk.xml", + L"ALanguage.zh-tw.xml" +}; + +// Specifies what files are included in self-extracting packages (no other files will be packaged or extracted). +static wchar_t *szCompressedFiles[]= +{ + L"VeraCrypt User Guide.pdf", + L"License.txt", + L"LICENSE", + L"NOTICE", + L"VeraCrypt.exe", + L"VeraCryptExpander.exe", + L"VeraCrypt Format.exe", + L"VeraCrypt-x64.exe", + L"VeraCryptExpander-x64.exe", + L"VeraCrypt Format-x64.exe", + L"veracrypt.sys", + L"veracrypt-x64.sys", + L"Language.ar.xml", + L"Language.be.xml", + L"Language.bg.xml", + L"Language.ca.xml", + L"Language.cs.xml", + L"Language.da.xml", + L"Language.de.xml", + L"Language.el.xml", + L"Language.es.xml", + L"Language.et.xml", + L"Language.eu.xml", + L"Language.fa.xml", + L"Language.fi.xml", + L"Language.fr.xml", + L"Language.hu.xml", + L"Language.id.xml", + L"Language.it.xml", + L"Language.ja.xml", + L"Language.ka.xml", + L"Language.ko.xml", + L"Language.lv.xml", + L"Language.my.xml", + L"Language.nl.xml", + L"Language.nn.xml", + L"Language.pl.xml", + L"Language.pt-br.xml", + L"Language.ru.xml", + L"Language.sk.xml", + L"Language.sl.xml", + L"Language.sv.xml", + L"Language.tr.xml", + L"Language.uk.xml", + L"Language.uz.xml", + L"Language.vi.xml", + L"Language.zh-cn.xml", + L"Language.zh-hk.xml", + L"Language.zh-tw.xml" +}; + +#define FILENAME_64BIT_DRIVER L"veracrypt-x64.sys" +#define NBR_COMPRESSED_FILES (sizeof(szCompressedFiles) / sizeof(szCompressedFiles[0])) + +void localcleanup (void); +BOOL StatDeleteFile ( wchar_t *lpszFile, BOOL bCheckForOldFile ); +BOOL StatRemoveDirectory ( wchar_t *lpszDir ); +HRESULT CreateLink ( wchar_t *lpszPathObj , wchar_t *lpszArguments , wchar_t *lpszPathLink ); +void GetProgramPath ( HWND hwndDlg , wchar_t *path ); +void StatusMessage (HWND hwndDlg, char *stringId); +void StatusMessageParam (HWND hwndDlg, char *stringId, wchar_t *param); +void ClearLogWindow (HWND hwndDlg); +void RegMessage ( HWND hwndDlg , wchar_t *txt ); +void RegRemoveMessage (HWND hwndDlg, wchar_t *txt); +void CopyMessage ( HWND hwndDlg , wchar_t *txt ); +void RemoveMessage ( HWND hwndDlg , wchar_t *txt ); +void IconMessage ( HWND hwndDlg , wchar_t *txt ); +static int CALLBACK BrowseCallbackProc ( HWND hwnd , UINT uMsg , LPARAM lp , LPARAM pData ); +void LoadLicense ( HWND hwndDlg ); +void DetermineUpgradeDowngradeStatus (BOOL bCloseDriverHandle, LONG *driverVersionPtr); +BOOL DoFilesInstall ( HWND hwndDlg , wchar_t *szDestDir ); +BOOL DoRegInstall ( HWND hwndDlg , wchar_t *szDestDir , BOOL bInstallType ); +BOOL DoRegUninstall (HWND hwndDlg, BOOL bRemoveDeprecated); +BOOL DoServiceUninstall ( HWND hwndDlg , wchar_t *lpszService ); +BOOL DoDriverUnload ( HWND hwndDlg ); +BOOL DoShortcutsInstall ( HWND hwndDlg , wchar_t *szDestDir , BOOL bProgGroup, BOOL bDesktopIcon ); +BOOL DoShortcutsUninstall (HWND hwndDlg, wchar_t *szDestDir); +void OutcomePrompt ( HWND hwndDlg , BOOL bOK ); +void DoUninstall ( void *hwndDlg ); +void DoInstall ( void *hwndDlg ); +void SetInstallationPath (HWND hwndDlg); +BOOL UpgradeBootLoader (HWND hwndDlg); +BOOL CALLBACK InstallDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); + +extern BOOL bDevm; +extern BOOL Rollback; +extern BOOL bUpgrade; +extern BOOL bPossiblyFirstTimeInstall; +extern BOOL bRepairMode; +extern BOOL bReinstallMode; +extern BOOL bSystemRestore; +extern BOOL bDisableSwapFiles; +extern BOOL bForAllUsers; +extern BOOL bRegisterFileExt; +extern BOOL bAddToStartMenu; +extern BOOL bDesktopIcon; +extern BOOL bDesktopIconStatusDetermined; +extern BOOL SystemEncryptionUpdate; +extern BOOL bRestartRequired; +extern HMODULE volatile SystemRestoreDll; +extern wchar_t InstallationPath[TC_MAX_PATH]; +extern wchar_t SetupFilesDir[TC_MAX_PATH]; + +#ifdef __cplusplus +} +#endif + +#endif // #ifndef SETUP_H diff --git a/src/Setup/Setup.manifest b/src/Setup/Setup.manifest index db2b8e62..afd4c1c0 100644 --- a/src/Setup/Setup.manifest +++ b/src/Setup/Setup.manifest @@ -1,33 +1,33 @@ - - - - - - - - - - - - true - - - - - - - - - - - - - + + + + + + + + + + + + true + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Setup/Setup.rc b/src/Setup/Setup.rc index 2223505b..bdb89be1 100644 --- a/src/Setup/Setup.rc +++ b/src/Setup/Setup.rc @@ -1,327 +1,327 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" -#include "..\\common\\resource.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,17,22,0 - PRODUCTVERSION 1,17,22,0 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "IDRIX" - VALUE "FileDescription", "VeraCrypt Setup" - VALUE "FileVersion", "1.17" - VALUE "LegalTrademarks", "VeraCrypt" - VALUE "OriginalFilename", "VeraCrypt Setup.exe" - VALUE "ProductName", "VeraCrypt" - VALUE "ProductVersion", "1.17" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - - -///////////////////////////////////////////////////////////////////////////// -// -// HEADER -// - -IDR_SETUP_RSRC_HEADER HEADER "resource.h" - -///////////////////////////////////////////////////////////////////////////// -// -// REGISTRY -// - -IDR_COMREG REGISTRY "ComSetup.rgs" - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_UNINSTALL DIALOGEX 0, 0, 349, 234 -STYLE DS_SETFONT | DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Uninstall VeraCrypt" -CLASS "VeraCryptCustomDlg" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - LTEXT "Click Uninstall to remove VeraCrypt from this system.",IDT_UNINSTALL_DIR,8,8,334,8 - LISTBOX IDC_LOG_WINDOW,7,21,335,179,LBS_NOINTEGRALHEIGHT | LBS_NOSEL | WS_VSCROLL - DEFPUSHBUTTON "&Uninstall",IDC_UNINSTALL,236,213,50,14 - PUSHBUTTON "Cancel",IDCANCEL,292,213,50,14 - CONTROL "Create System &Restore point",IDC_SYSTEM_RESTORE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,10,215,194,10 - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,2,206,347,1,WS_EX_STATICEDGE - CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,1,348,1,WS_EX_STATICEDGE -END - -IDD_INSTALL_OPTIONS_PAGE_DLG DIALOGEX 0, 0, 346, 152 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - EDITTEXT IDC_DESTINATION,11,41,260,13,ES_AUTOHSCROLL - PUSHBUTTON "Bro&wse...",IDC_BROWSE,278,40,59,14 - CONTROL "Install &for all users",IDC_ALL_USERS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,16,77,168,11 - CONTROL "Associate the .hc file &extension with VeraCrypt",IDC_FILE_TYPE, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,16,113,232,11 - CONTROL "Add VeraCrypt to &Start menu",IDC_PROG_GROUP,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,16,89,168,11 - CONTROL "Create System &Restore point",IDC_SYSTEM_RESTORE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,16,125,194,11 - CONTROL "Add VeraCrypt icon to &desktop",IDC_DESKTOP_ICON,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,16,101,168,11 - LTEXT "Please select or type the location where you want to install the VeraCrypt program files. If the specified folder does not exist, it will be automatically created.",IDT_INSTALL_DESTINATION,11,14,319,25 -END - -IDD_INFO_PAGE_DLG DIALOGEX 0, 0, 217, 156 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - LTEXT "",IDC_BOX_HELP,0,10,217,146 -END - -IDD_INTRO_PAGE_DLG DIALOGEX 0, 0, 346, 152 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "",IDC_LICENSE_TEXT,"RichEdit20A",ES_MULTILINE | ES_READONLY | ES_NUMBER | WS_BORDER | WS_VSCROLL | WS_TABSTOP,0,23,345,108 - CONTROL "",IDC_AGREE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,2,137,126,10 - LTEXT "",IDC_BOX_HELP,0,0,346,22 -END - -IDD_INSTL_DLG DIALOGEX 0, 0, 374, 231 -STYLE DS_SETFONT | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "VeraCrypt Setup Wizard" -CLASS "VeraCryptCustomDlg" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - PUSHBUTTON "&Help",IDHELP,150,211,50,14 - PUSHBUTTON "",IDC_PREV,209,211,50,14 - DEFPUSHBUTTON "",IDC_NEXT,259,211,50,14 - PUSHBUTTON "Cancel",IDCANCEL,317,211,50,14 - LTEXT "",IDC_BOX_TITLE,11,5,324,12,0,WS_EX_TRANSPARENT - CONTROL 107,IDC_BITMAP_SETUP_WIZARD,"Static",SS_BITMAP | SS_NOTIFY,139,3,228,30 - CONTROL 109,IDC_SETUP_WIZARD_BKG,"Static",SS_BITMAP,0,0,11,10 - CONTROL "",IDC_SETUP_WIZARD_GFX_AREA,"Static",SS_GRAYRECT | NOT WS_VISIBLE,0,0,378,36,WS_EX_TRANSPARENT | WS_EX_STATICEDGE - CONTROL "",IDC_HR_BOTTOM,"Static",SS_ETCHEDHORZ,67,204,306,1,WS_EX_STATICEDGE - CONTROL "",IDC_HR,"Static",SS_ETCHEDHORZ,0,35,399,1,WS_EX_STATICEDGE - LTEXT "VeraCrypt Installer",IDC_STATIC,4,200,62,8,WS_DISABLED - LTEXT "",IDC_BOX_INFO,18,18,317,13,0,WS_EX_TRANSPARENT - LTEXT "",IDC_MAIN_CONTENT_CANVAS,0,36,374,164 - LTEXT "",IDC_POS_BOX,14,42,346,155,0,WS_EX_TRANSPARENT -END - -IDD_EXTRACTION_OPTIONS_PAGE_DLG DIALOGEX 0, 0, 346, 152 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - PUSHBUTTON "Bro&wse...",IDC_BROWSE,277,32,62,14 - EDITTEXT IDC_DESTINATION,6,33,264,12,ES_AUTOHSCROLL - LTEXT "Please select or type the location where you want to place the extracted files:",IDT_EXTRACT_DESTINATION,6,15,333,17 - CONTROL "&Open the destination location when finished",IDC_OPEN_CONTAINING_FOLDER, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,91,318,16 - LTEXT "",IDC_BOX_HELP,6,56,333,32 -END - -IDD_WIZARD_MODE_PAGE_DLG DIALOGEX 0, 0, 346, 152 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - CONTROL "&Install",IDC_WIZARD_MODE_INSTALL,"Button",BS_AUTORADIOBUTTON,6,14,232,10 - CONTROL "&Extract",IDC_WIZARD_MODE_EXTRACT_ONLY,"Button",BS_AUTORADIOBUTTON,6,60,232,10 - LTEXT "",IDC_BOX_HELP,42,77,286,64 - LTEXT "",IDC_BOX_HELP2,42,30,286,29 -END - -IDD_PROGRESS_PAGE_DLG DIALOGEX 0, 0, 346, 152 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -FONT 8, "MS Shell Dlg", 400, 0, 0x1 -BEGIN - LISTBOX IDC_LOG_WINDOW,0,1,345,131,LBS_NOINTEGRALHEIGHT | LBS_DISABLENOSCROLL | LBS_NOSEL | WS_VSCROLL - CONTROL "",IDC_PROGRESS_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,0,139,345,12 -END - -IDD_DONATIONS_PAGE_DLG DIALOGEX 0, 0, 346, 152 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD -EXSTYLE WS_EX_TRANSPARENT -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - PUSHBUTTON "Donate now...",IDC_DONATE,124,94,96,14 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_SETUP ICON "Setup.ico" - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "#include ""..\\\\common\\\\resource.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "#include ""..\\\\common\\\\common.rc""\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_UNINSTALL, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 342 - TOPMARGIN, 7 - BOTTOMMARGIN, 229 - END - - IDD_INSTALL_OPTIONS_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 339 - TOPMARGIN, 7 - BOTTOMMARGIN, 147 - END - - IDD_INFO_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 210 - TOPMARGIN, 7 - BOTTOMMARGIN, 149 - END - - IDD_INTRO_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 339 - TOPMARGIN, 7 - BOTTOMMARGIN, 145 - END - - IDD_INSTL_DLG, DIALOG - BEGIN - RIGHTMARGIN, 367 - TOPMARGIN, 1 - BOTTOMMARGIN, 229 - HORZGUIDE, 196 - END - - IDD_EXTRACTION_OPTIONS_PAGE_DLG, DIALOG - BEGIN - RIGHTMARGIN, 343 - BOTTOMMARGIN, 147 - END - - IDD_WIZARD_MODE_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 339 - TOPMARGIN, 7 - BOTTOMMARGIN, 145 - END - - IDD_PROGRESS_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 339 - TOPMARGIN, 7 - BOTTOMMARGIN, 145 - END - - IDD_DONATIONS_PAGE_DLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 339 - TOPMARGIN, 7 - BOTTOMMARGIN, 147 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_SETUP_WIZARD BITMAP "VeraCrypt_setup.bmp" -IDB_SETUP_WIZARD_BKG BITMAP "VeraCrypt_setup_background.bmp" -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// -#include "..\\common\\common.rc" - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" +#include "..\\common\\resource.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,17,22,0 + PRODUCTVERSION 1,17,22,0 + FILEFLAGSMASK 0x17L +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "IDRIX" + VALUE "FileDescription", "VeraCrypt Setup" + VALUE "FileVersion", "1.17" + VALUE "LegalTrademarks", "VeraCrypt" + VALUE "OriginalFilename", "VeraCrypt Setup.exe" + VALUE "ProductName", "VeraCrypt" + VALUE "ProductVersion", "1.17" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// HEADER +// + +IDR_SETUP_RSRC_HEADER HEADER "resource.h" + +///////////////////////////////////////////////////////////////////////////// +// +// REGISTRY +// + +IDR_COMREG REGISTRY "ComSetup.rgs" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_UNINSTALL DIALOGEX 0, 0, 349, 234 +STYLE DS_SETFONT | DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Uninstall VeraCrypt" +CLASS "VeraCryptCustomDlg" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + LTEXT "Click Uninstall to remove VeraCrypt from this system.",IDT_UNINSTALL_DIR,8,8,334,8 + LISTBOX IDC_LOG_WINDOW,7,21,335,179,LBS_NOINTEGRALHEIGHT | LBS_NOSEL | WS_VSCROLL + DEFPUSHBUTTON "&Uninstall",IDC_UNINSTALL,236,213,50,14 + PUSHBUTTON "Cancel",IDCANCEL,292,213,50,14 + CONTROL "Create System &Restore point",IDC_SYSTEM_RESTORE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,10,215,194,10 + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,2,206,347,1,WS_EX_STATICEDGE + CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,1,1,348,1,WS_EX_STATICEDGE +END + +IDD_INSTALL_OPTIONS_PAGE_DLG DIALOGEX 0, 0, 346, 152 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + EDITTEXT IDC_DESTINATION,11,41,260,13,ES_AUTOHSCROLL + PUSHBUTTON "Bro&wse...",IDC_BROWSE,278,40,59,14 + CONTROL "Install &for all users",IDC_ALL_USERS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,16,77,168,11 + CONTROL "Associate the .hc file &extension with VeraCrypt",IDC_FILE_TYPE, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,16,113,232,11 + CONTROL "Add VeraCrypt to &Start menu",IDC_PROG_GROUP,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,16,89,168,11 + CONTROL "Create System &Restore point",IDC_SYSTEM_RESTORE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,16,125,194,11 + CONTROL "Add VeraCrypt icon to &desktop",IDC_DESKTOP_ICON,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,16,101,168,11 + LTEXT "Please select or type the location where you want to install the VeraCrypt program files. If the specified folder does not exist, it will be automatically created.",IDT_INSTALL_DESTINATION,11,14,319,25 +END + +IDD_INFO_PAGE_DLG DIALOGEX 0, 0, 217, 156 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + LTEXT "",IDC_BOX_HELP,0,10,217,146 +END + +IDD_INTRO_PAGE_DLG DIALOGEX 0, 0, 346, 152 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "",IDC_LICENSE_TEXT,"RichEdit20A",ES_MULTILINE | ES_READONLY | ES_NUMBER | WS_BORDER | WS_VSCROLL | WS_TABSTOP,0,23,345,108 + CONTROL "",IDC_AGREE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,2,137,126,10 + LTEXT "",IDC_BOX_HELP,0,0,346,22 +END + +IDD_INSTL_DLG DIALOGEX 0, 0, 374, 231 +STYLE DS_SETFONT | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "VeraCrypt Setup Wizard" +CLASS "VeraCryptCustomDlg" +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + PUSHBUTTON "&Help",IDHELP,150,211,50,14 + PUSHBUTTON "",IDC_PREV,209,211,50,14 + DEFPUSHBUTTON "",IDC_NEXT,259,211,50,14 + PUSHBUTTON "Cancel",IDCANCEL,317,211,50,14 + LTEXT "",IDC_BOX_TITLE,11,5,324,12,0,WS_EX_TRANSPARENT + CONTROL 107,IDC_BITMAP_SETUP_WIZARD,"Static",SS_BITMAP | SS_NOTIFY,139,3,228,30 + CONTROL 109,IDC_SETUP_WIZARD_BKG,"Static",SS_BITMAP,0,0,11,10 + CONTROL "",IDC_SETUP_WIZARD_GFX_AREA,"Static",SS_GRAYRECT | NOT WS_VISIBLE,0,0,378,36,WS_EX_TRANSPARENT | WS_EX_STATICEDGE + CONTROL "",IDC_HR_BOTTOM,"Static",SS_ETCHEDHORZ,67,204,306,1,WS_EX_STATICEDGE + CONTROL "",IDC_HR,"Static",SS_ETCHEDHORZ,0,35,399,1,WS_EX_STATICEDGE + LTEXT "VeraCrypt Installer",IDC_STATIC,4,200,62,8,WS_DISABLED + LTEXT "",IDC_BOX_INFO,18,18,317,13,0,WS_EX_TRANSPARENT + LTEXT "",IDC_MAIN_CONTENT_CANVAS,0,36,374,164 + LTEXT "",IDC_POS_BOX,14,42,346,155,0,WS_EX_TRANSPARENT +END + +IDD_EXTRACTION_OPTIONS_PAGE_DLG DIALOGEX 0, 0, 346, 152 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + PUSHBUTTON "Bro&wse...",IDC_BROWSE,277,32,62,14 + EDITTEXT IDC_DESTINATION,6,33,264,12,ES_AUTOHSCROLL + LTEXT "Please select or type the location where you want to place the extracted files:",IDT_EXTRACT_DESTINATION,6,15,333,17 + CONTROL "&Open the destination location when finished",IDC_OPEN_CONTAINING_FOLDER, + "Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,91,318,16 + LTEXT "",IDC_BOX_HELP,6,56,333,32 +END + +IDD_WIZARD_MODE_PAGE_DLG DIALOGEX 0, 0, 346, 152 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + CONTROL "&Install",IDC_WIZARD_MODE_INSTALL,"Button",BS_AUTORADIOBUTTON,6,14,232,10 + CONTROL "&Extract",IDC_WIZARD_MODE_EXTRACT_ONLY,"Button",BS_AUTORADIOBUTTON,6,60,232,10 + LTEXT "",IDC_BOX_HELP,42,77,286,64 + LTEXT "",IDC_BOX_HELP2,42,30,286,29 +END + +IDD_PROGRESS_PAGE_DLG DIALOGEX 0, 0, 346, 152 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + LISTBOX IDC_LOG_WINDOW,0,1,345,131,LBS_NOINTEGRALHEIGHT | LBS_DISABLENOSCROLL | LBS_NOSEL | WS_VSCROLL + CONTROL "",IDC_PROGRESS_BAR,"msctls_progress32",PBS_SMOOTH | WS_BORDER,0,139,345,12 +END + +IDD_DONATIONS_PAGE_DLG DIALOGEX 0, 0, 346, 152 +STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD +EXSTYLE WS_EX_TRANSPARENT +FONT 8, "MS Shell Dlg", 0, 0, 0x0 +BEGIN + PUSHBUTTON "Donate now...",IDC_DONATE,124,94,96,14 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_SETUP ICON "Setup.ico" + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "#include ""..\\\\common\\\\resource.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "#include ""..\\\\common\\\\common.rc""\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO +BEGIN + IDD_UNINSTALL, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 342 + TOPMARGIN, 7 + BOTTOMMARGIN, 229 + END + + IDD_INSTALL_OPTIONS_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 339 + TOPMARGIN, 7 + BOTTOMMARGIN, 147 + END + + IDD_INFO_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 210 + TOPMARGIN, 7 + BOTTOMMARGIN, 149 + END + + IDD_INTRO_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 339 + TOPMARGIN, 7 + BOTTOMMARGIN, 145 + END + + IDD_INSTL_DLG, DIALOG + BEGIN + RIGHTMARGIN, 367 + TOPMARGIN, 1 + BOTTOMMARGIN, 229 + HORZGUIDE, 196 + END + + IDD_EXTRACTION_OPTIONS_PAGE_DLG, DIALOG + BEGIN + RIGHTMARGIN, 343 + BOTTOMMARGIN, 147 + END + + IDD_WIZARD_MODE_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 339 + TOPMARGIN, 7 + BOTTOMMARGIN, 145 + END + + IDD_PROGRESS_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 339 + TOPMARGIN, 7 + BOTTOMMARGIN, 145 + END + + IDD_DONATIONS_PAGE_DLG, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 339 + TOPMARGIN, 7 + BOTTOMMARGIN, 147 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Bitmap +// + +IDB_SETUP_WIZARD BITMAP "VeraCrypt_setup.bmp" +IDB_SETUP_WIZARD_BKG BITMAP "VeraCrypt_setup_background.bmp" +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// +#include "..\\common\\common.rc" + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/src/Setup/Setup.vcproj b/src/Setup/Setup.vcproj index 05a67aa0..a1a6a81f 100644 --- a/src/Setup/Setup.vcproj +++ b/src/Setup/Setup.vcproj @@ -1,484 +1,484 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Setup/Wizard.c b/src/Setup/Wizard.c index a5ee418b..42ea42c9 100644 --- a/src/Setup/Wizard.c +++ b/src/Setup/Wizard.c @@ -1,1195 +1,1195 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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 "Tcdefs.h" -#include -#include -#include -#include -#include "SelfExtract.h" -#include "Wizard.h" -#include "Dlgcode.h" -#include "Language.h" -#include "Common/Resource.h" -#include "Resource.h" -#include "Setup.h" -#include -#include - -using namespace std; - -enum wizard_pages -{ - INTRO_PAGE, - WIZARD_MODE_PAGE, - INSTALL_OPTIONS_PAGE, - INSTALL_PROGRESS_PAGE, - EXTRACTION_OPTIONS_PAGE, - EXTRACTION_PROGRESS_PAGE, - DONATIONS_PAGE -}; - -HWND hCurPage = NULL; /* Handle to current wizard page */ -int nCurPageNo = -1; /* The current wizard page */ -wchar_t WizardDestInstallPath [TC_MAX_PATH]; -wchar_t WizardDestExtractPath [TC_MAX_PATH]; -wchar_t SelfFile [TC_MAX_PATH]; - -HBITMAP hbmWizardBitmapRescaled = NULL; - -BOOL bExtractOnly = FALSE; -BOOL bLicenseAccepted = FALSE; -BOOL bOpenContainingFolder = TRUE; -BOOL bExtractionSuccessful = FALSE; -BOOL bStartInstall = FALSE; -BOOL bStartExtraction = FALSE; -BOOL bInProgress = FALSE; -BOOL bPromptTutorial = FALSE; -BOOL bPromptReleaseNotes = FALSE; - -int nPbar = 0; /* Control ID of progress bar */ - -static HFONT hDonTextFont; -static BOOL OsPrngAvailable; -static HCRYPTPROV hCryptProv; -static int DonColorSchemeId; -static COLORREF DonTextColor; -static COLORREF DonBkgColor; - -wstring DonText = L""; - -void localcleanupwiz (void) -{ - /* Delete buffered bitmaps (if any) */ - if (hbmWizardBitmapRescaled != NULL) - { - DeleteObject ((HGDIOBJ) hbmWizardBitmapRescaled); - hbmWizardBitmapRescaled = NULL; - } - - if (hCryptProv != 0) - { - OsPrngAvailable = FALSE; - CryptReleaseContext (hCryptProv, 0); - hCryptProv = 0; - } - - if (hDonTextFont != NULL) - { - DeleteObject (hDonTextFont); - hDonTextFont = NULL; - } -} - -static void InitWizardDestInstallPath (void) -{ - if (wcslen (WizardDestInstallPath) < 2) - { - StringCbCopyW (WizardDestInstallPath, sizeof(WizardDestInstallPath), InstallationPath); - if (WizardDestInstallPath [wcslen (WizardDestInstallPath) - 1] != L'\\') - { - StringCbCatW (WizardDestInstallPath, sizeof(WizardDestInstallPath), L"\\"); - } - } -} - -void LoadPage (HWND hwndDlg, int nPageNo) -{ - RECT rD, rW; - - if (hCurPage != NULL) - { - DestroyWindow (hCurPage); - } - - InvalidateRect (GetDlgItem (MainDlg, IDC_MAIN_CONTENT_CANVAS), NULL, TRUE); - - GetWindowRect (GetDlgItem (hwndDlg, IDC_POS_BOX), &rW); - - nCurPageNo = nPageNo; - - switch (nPageNo) - { - case INTRO_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INTRO_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case WIZARD_MODE_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_WIZARD_MODE_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case INSTALL_OPTIONS_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INSTALL_OPTIONS_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case INSTALL_PROGRESS_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_PROGRESS_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case EXTRACTION_OPTIONS_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_EXTRACTION_OPTIONS_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case EXTRACTION_PROGRESS_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_PROGRESS_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - - case DONATIONS_PAGE: - hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_DONATIONS_PAGE_DLG), hwndDlg, - (DLGPROC) PageDialogProc); - break; - } - - rD.left = 15; - rD.top = 45; - rD.right = 0; - rD.bottom = 0; - MapDialogRect (hwndDlg, &rD); - - if (hCurPage != NULL) - { - MoveWindow (hCurPage, rD.left, rD.top, rW.right - rW.left, rW.bottom - rW.top, TRUE); - ShowWindow (hCurPage, SW_SHOWNORMAL); - } - - /* Refresh the graphics (white background of some texts, etc.) */ - RefreshUIGFX (); -} - - -static int GetDonVal (int minVal, int maxVal) -{ - static BOOL prngInitialized = FALSE; - static unsigned __int8 buffer [2]; - - if (!prngInitialized) - { - if (!CryptAcquireContext (&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0) - && !CryptAcquireContext (&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) - OsPrngAvailable = FALSE; - else - OsPrngAvailable = TRUE; - - srand ((unsigned int) time (NULL)); - rand(); // Generate and discard the inital value, as it always appears to be somewhat non-random. - - prngInitialized = TRUE; - } - - if (OsPrngAvailable && CryptGenRandom (hCryptProv, sizeof (buffer), buffer) != 0) - { - return ((int) ((double) *((uint16 *) buffer) / (0xFFFF+1) * (maxVal + 1 - minVal)) + minVal); - } - else - return ((int) ((double) rand() / (RAND_MAX+1) * (maxVal + 1 - minVal)) + minVal); -} - - -/* Except in response to the WM_INITDIALOG message, the dialog box procedure - should return nonzero if it processes the message, and zero if it does - not. - see DialogProc */ -BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - static char PageDebugId[128]; - WORD lw = LOWORD (wParam); - WORD hw = HIWORD (wParam); - - hCurPage = hwndDlg; - - switch (uMsg) - { - case WM_INITDIALOG: - LocalizeDialog (hwndDlg, "IDD_INSTL_DLG"); - - StringCbPrintfA (PageDebugId, sizeof(PageDebugId), "SETUP_WIZARD_PAGE_%d", nCurPageNo); - LastDialogId = PageDebugId; - - switch (nCurPageNo) - { - case INTRO_PAGE: - { - char *licenseText = NULL; - - licenseText = GetLegalNotices (); - if (licenseText != NULL) - { - SetWindowTextA (GetDlgItem (hwndDlg, IDC_LICENSE_TEXT), licenseText); - free (licenseText); - } - else - { - Error("CANNOT_DISPLAY_LICENSE", hwndDlg); - exit (1); - } - - /* For legal reasons, some of the following texts cannot be localized by third parties. */ - - SetCheckBox (hwndDlg, IDC_AGREE, bLicenseAccepted); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), L"Please read the license terms"); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), L"You must accept these license terms before you can use, extract, or install VeraCrypt."); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), L"IMPORTANT: By checking the checkbox below, you accept these license terms and signify that you understand and agree to them. Please click the 'arrow down' icon to see the rest of the license."); // Cannot be localized by third parties (for legal reasons). - //SendMessage (GetDlgItem (hwndDlg, IDC_BOX_HELP), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_AGREE), L"I &accept the license terms"); // Cannot be localized by third parties (for legal reasons). - //SetWindowTextW (GetDlgItem (hwndDlg, IDC_DISAGREE), L"I &do not accept the license terms"); - - //SendMessage (GetDlgItem (hwndDlg, IDC_AGREE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - //SendMessage (GetDlgItem (hwndDlg, IDC_DISAGREE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - - EnableWindow (GetDlgItem (hwndDlg, IDC_AGREE), TRUE); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), bLicenseAccepted); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), bLicenseAccepted); - - // Left margin for license text - SendMessage (GetDlgItem (hwndDlg, IDC_LICENSE_TEXT), EM_SETMARGINS, (WPARAM) EC_LEFTMARGIN, (LPARAM) CompensateXDPI (4)); - } - return 1; - - case WIZARD_MODE_PAGE: - { - LONG driverVersion; - - DetermineUpgradeDowngradeStatus (TRUE, &driverVersion); - - if (bRepairMode || bReinstallMode) - { - SetWindowTextW (GetDlgItem (hwndDlg, IDC_WIZARD_MODE_INSTALL), GetString ("REPAIR_REINSTALL")); - bExtractOnly = FALSE; - } - else if (bUpgrade) - SetWindowTextW (GetDlgItem (hwndDlg, IDC_WIZARD_MODE_INSTALL), GetString ("UPGRADE")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SETUP_MODE_TITLE")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), GetString ("SETUP_MODE_INFO")); - - SendMessage (GetDlgItem (hwndDlg, IDC_WIZARD_MODE_INSTALL), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - SendMessage (GetDlgItem (hwndDlg, IDC_WIZARD_MODE_EXTRACT_ONLY), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - - CheckButton (GetDlgItem (hwndDlg, bExtractOnly ? IDC_WIZARD_MODE_EXTRACT_ONLY : IDC_WIZARD_MODE_INSTALL)); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SETUP_MODE_HELP_EXTRACT")); - - if (!bRepairMode) - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP2), GetString (bUpgrade ? "SETUP_MODE_HELP_UPGRADE" : "SETUP_MODE_HELP_INSTALL")); - - EnableWindow (GetDlgItem (hwndDlg, IDC_WIZARD_MODE_EXTRACT_ONLY), !bRepairMode); - EnableWindow (GetDlgItem (hwndDlg, IDC_BOX_HELP), !bRepairMode); - EnableWindow (GetDlgItem (hwndDlg, IDC_WIZARD_MODE_INSTALL), TRUE); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - } - return 1; - - case EXTRACTION_OPTIONS_PAGE: - - if (wcslen(WizardDestExtractPath) < 2) - { - StringCbCopyW (WizardDestExtractPath, sizeof(WizardDestExtractPath), SetupFilesDir); - StringCbCatNW (WizardDestExtractPath, sizeof(WizardDestExtractPath), L"VeraCrypt\\", ARRAYSIZE (WizardDestExtractPath) - wcslen (WizardDestExtractPath) - 1); - } - - SendMessage (GetDlgItem (hwndDlg, IDC_DESTINATION), EM_LIMITTEXT, TC_MAX_PATH - 1, 0); - - SetDlgItemText (hwndDlg, IDC_DESTINATION, WizardDestExtractPath); - - SetCheckBox (hwndDlg, IDC_OPEN_CONTAINING_FOLDER, bOpenContainingFolder); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("EXTRACTION_OPTIONS_TITLE")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), GetString ("EXTRACTION_OPTIONS_INFO")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("AUTO_FOLDER_CREATION")); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("EXTRACT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); - - return 1; - - case EXTRACTION_PROGRESS_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("EXTRACTING_VERB")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), GetString ("EXTRACTION_PROGRESS_INFO")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - - if (bStartExtraction) - { - /* Start extraction */ - - LastDialogId = "EXTRACTION_IN_PROGRESS"; - - WaitCursor (); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), FALSE); - - if (WizardDestExtractPath [wcslen(WizardDestExtractPath)-1] != L'\\') - StringCbCatW (WizardDestExtractPath, sizeof(WizardDestExtractPath), L"\\"); - - StringCbCopyW (DestExtractPath, sizeof(DestExtractPath), WizardDestExtractPath); - - InitProgressBar (); - - bInProgress = TRUE; - bStartExtraction = FALSE; - - _beginthread (ExtractAllFilesThread, 0, (void *) hwndDlg); - } - else - { - NormalCursor (); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); - } - - return 1; - - case INSTALL_OPTIONS_PAGE: - { - LONG driverVersion; - - DetermineUpgradeDowngradeStatus (TRUE, &driverVersion); - - if (!bDesktopIconStatusDetermined) - { - bDesktopIcon = !bUpgrade; - bDesktopIconStatusDetermined = TRUE; - } - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SETUP_OPTIONS_TITLE")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), GetString ("SETUP_OPTIONS_INFO")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("AUTO_FOLDER_CREATION")); - - InitWizardDestInstallPath (); - - SendMessage (GetDlgItem (hwndDlg, IDC_DESTINATION), EM_LIMITTEXT, TC_MAX_PATH - 1, 0); - - SetDlgItemText (hwndDlg, IDC_DESTINATION, WizardDestInstallPath); - - if (bUpgrade) - { - SetWindowTextW (GetDlgItem (hwndDlg, IDT_INSTALL_DESTINATION), GetString ("SETUP_UPGRADE_DESTINATION")); - EnableWindow (GetDlgItem (hwndDlg, IDC_DESTINATION), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_BROWSE), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_ALL_USERS), FALSE); - - wchar_t path[MAX_PATH]; - SHGetSpecialFolderPath (hwndDlg, path, CSIDL_COMMON_PROGRAMS, 0); - bForAllUsers = (_waccess ((wstring (path) + L"\\" _T(TC_APP_NAME)).c_str(), 0) == 0); - } - - // System Restore - SetCheckBox (hwndDlg, IDC_SYSTEM_RESTORE, bSystemRestore); - if (SystemRestoreDll == 0) - { - SetCheckBox (hwndDlg, IDC_SYSTEM_RESTORE, FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_SYSTEM_RESTORE), FALSE); - } - - SetCheckBox (hwndDlg, IDC_ALL_USERS, bForAllUsers); - SetCheckBox (hwndDlg, IDC_FILE_TYPE, bRegisterFileExt); - SetCheckBox (hwndDlg, IDC_PROG_GROUP, bAddToStartMenu); - SetCheckBox (hwndDlg, IDC_DESKTOP_ICON, bDesktopIcon); - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString (bUpgrade ? "UPGRADE" : "INSTALL")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); - } - return 1; - - case INSTALL_PROGRESS_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SETUP_PROGRESS_TITLE")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), GetString ("SETUP_PROGRESS_INFO")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); - - if (bStartInstall) - { - /* Start install */ - - LastDialogId = "INSTALL_IN_PROGRESS"; - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), FALSE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), FALSE); - - InitProgressBar (); - - if (WizardDestInstallPath [wcslen(WizardDestInstallPath)-1] != L'\\') - StringCbCatW (WizardDestInstallPath, sizeof(WizardDestInstallPath), L"\\"); - - StringCbCopyW (InstallationPath, sizeof(InstallationPath), WizardDestInstallPath); - - WaitCursor (); - - bInProgress = TRUE; - bStartInstall = FALSE; - - _beginthread (DoInstall, 0, (void *) hwndDlg); - } - else - { - NormalCursor (); - - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), TRUE); - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); - - } - - return 1; - - case DONATIONS_PAGE: - - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bExtractOnly ? "EXTRACTION_FINISHED_TITLE_DON" : (bUpgrade ? "SETUP_FINISHED_UPGRADE_TITLE_DON" : "SETUP_FINISHED_TITLE_DON"))); - SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), GetString ("SETUP_FINISHED_INFO_DON")); - - DonText = L"Please consider making a donation."; - - - // Colors - - switch (DonColorSchemeId) - { - case 2: - // NOP - Default OS colors (foreground and background) - break; - - case 3: - // Red - DonTextColor = RGB (255, 255, 255); - DonBkgColor = RGB (255, 0, 0); - break; - - case 4: - // Yellow - DonTextColor = RGB (255, 15, 49); - DonBkgColor = RGB (255, 255, 0); - break; - - case 5: - // Light red - DonTextColor = RGB (255, 255, 255); - DonBkgColor = RGB (255, 141, 144); - break; - - case 6: - // Pink - DonTextColor = RGB (255, 255, 255); - DonBkgColor = RGB (248, 148, 207); - break; - - case 7: - // White + red text - DonTextColor = RGB (255, 15, 49); - DonBkgColor = RGB (255, 255, 255); - break; - - case 8: - // Blue - DonTextColor = RGB (255, 255, 255); - DonBkgColor = RGB (54, 140, 255); - break; - - case 9: - // Green - DonTextColor = RGB (255, 255, 255); - DonBkgColor = RGB (70, 180, 80); - break; - } - - { - // Font - - LOGFONTW lf; - memset (&lf, 0, sizeof(lf)); - - // Main font - StringCbCopyW (lf.lfFaceName, sizeof (lf.lfFaceName),L"Times New Roman"); - lf.lfHeight = CompensateDPIFont (-21); - lf.lfWeight = FW_NORMAL; - lf.lfWidth = 0; - lf.lfEscapement = 0; - lf.lfOrientation = 0; - lf.lfItalic = FALSE; - lf.lfUnderline = FALSE; - lf.lfStrikeOut = FALSE; - lf.lfCharSet = DEFAULT_CHARSET; - lf.lfOutPrecision = OUT_DEFAULT_PRECIS; - lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; - lf.lfQuality = PROOF_QUALITY; - lf.lfPitchAndFamily = FF_DONTCARE; - hDonTextFont = CreateFontIndirectW (&lf); - - if (hDonTextFont == NULL) - AbortProcessSilent (); - } - - return 1; - } - - return 0; - - case WM_HELP: - if (bLicenseAccepted) - OpenPageHelp (GetParent (hwndDlg), nCurPageNo); - - return 1; - - case WM_ENDSESSION: - - bPromptTutorial = FALSE; - bPromptReleaseNotes = FALSE; - - EndDialog (MainDlg, 0); - localcleanup (); - return 0; - - - case WM_COMMAND: - - if (lw == IDC_AGREE && nCurPageNo == INTRO_PAGE) - { - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), IsButtonChecked (GetDlgItem (hwndDlg, IDC_AGREE))); - return 1; - } - - if (lw == IDC_WIZARD_MODE_EXTRACT_ONLY && nCurPageNo == WIZARD_MODE_PAGE) - { - bExtractOnly = TRUE; - return 1; - } - - if (lw == IDC_WIZARD_MODE_INSTALL && nCurPageNo == WIZARD_MODE_PAGE) - { - bExtractOnly = FALSE; - return 1; - } - - if ( nCurPageNo == EXTRACTION_OPTIONS_PAGE && hw == EN_CHANGE ) - { - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), (GetWindowTextLength (GetDlgItem (hCurPage, IDC_DESTINATION)) > 1)); - return 1; - } - - if ( nCurPageNo == INSTALL_OPTIONS_PAGE && hw == EN_CHANGE ) - { - EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), (GetWindowTextLength (GetDlgItem (hCurPage, IDC_DESTINATION)) > 1)); - return 1; - } - - if ( nCurPageNo == EXTRACTION_OPTIONS_PAGE ) - { - switch (lw) - { - case IDC_BROWSE: - if (BrowseDirectories (hwndDlg, "SELECT_DEST_DIR", WizardDestExtractPath)) - { - if (WizardDestExtractPath [wcslen(WizardDestExtractPath)-1] != L'\\') - { - StringCbCatW (WizardDestExtractPath, sizeof(WizardDestExtractPath), L"\\"); - } - SetDlgItemText (hwndDlg, IDC_DESTINATION, WizardDestExtractPath); - } - return 1; - - case IDC_OPEN_CONTAINING_FOLDER: - bOpenContainingFolder = IsButtonChecked (GetDlgItem (hCurPage, IDC_OPEN_CONTAINING_FOLDER)); - return 1; - } - } - - if ( nCurPageNo == INSTALL_OPTIONS_PAGE ) - { - switch (lw) - { - case IDC_BROWSE: - if (BrowseDirectories (hwndDlg, "SELECT_DEST_DIR", WizardDestInstallPath)) - { - if (WizardDestInstallPath [wcslen(WizardDestInstallPath)-1] != L'\\') - { - StringCbCatW (WizardDestInstallPath, sizeof(WizardDestInstallPath), L"\\"); - } - SetDlgItemText (hwndDlg, IDC_DESTINATION, WizardDestInstallPath); - } - return 1; - - case IDC_SYSTEM_RESTORE: - bSystemRestore = IsButtonChecked (GetDlgItem (hCurPage, IDC_SYSTEM_RESTORE)); - return 1; - - case IDC_ALL_USERS: - bForAllUsers = IsButtonChecked (GetDlgItem (hCurPage, IDC_ALL_USERS)); - return 1; - - case IDC_FILE_TYPE: - bRegisterFileExt = IsButtonChecked (GetDlgItem (hCurPage, IDC_FILE_TYPE)); - return 1; - - case IDC_PROG_GROUP: - bAddToStartMenu = IsButtonChecked (GetDlgItem (hCurPage, IDC_PROG_GROUP)); - return 1; - - case IDC_DESKTOP_ICON: - bDesktopIcon = IsButtonChecked (GetDlgItem (hCurPage, IDC_DESKTOP_ICON)); - return 1; - - } - } - - if (nCurPageNo == DONATIONS_PAGE) - { - switch (lw) - { - case IDC_DONATE: - { - char tmpstr [200]; - - StringCbPrintfA (tmpstr, sizeof(tmpstr), "&ref=%d", DonColorSchemeId); - - Applink ("donate", FALSE, tmpstr); - } - return 1; - } - } - - return 0; - - - case WM_PAINT: - - if (nCurPageNo == DONATIONS_PAGE) - { - PAINTSTRUCT tmpPaintStruct; - HDC hdc = BeginPaint (hCurPage, &tmpPaintStruct); - - if (hdc == NULL) - AbortProcessSilent (); - - SelectObject (hdc, hDonTextFont); - - if (DonColorSchemeId != 2) - { - HBRUSH tmpBrush = CreateSolidBrush (DonBkgColor); - - if (tmpBrush == NULL) - AbortProcessSilent (); - - RECT trect; - - trect.left = 0; - trect.right = CompensateXDPI (526); - trect.top = 0; - trect.bottom = CompensateYDPI (246); - - FillRect (hdc, &trect, tmpBrush); - - SetTextColor (hdc, DonTextColor); - SetBkColor (hdc, DonBkgColor); - } - - SetTextAlign(hdc, TA_CENTER); - - TextOutW (hdc, - CompensateXDPI (258), - CompensateYDPI (70), - DonText.c_str(), - DonText.length()); - - EndPaint (hCurPage, &tmpPaintStruct); - ReleaseDC (hCurPage, hdc); - } - return 0; - - } - - return 0; -} - -void InitProgressBar (void) -{ - HWND hProgressBar = GetDlgItem (hCurPage, nPbar); - SendMessage (hProgressBar, PBM_SETRANGE32, 0, 100); - SendMessage (hProgressBar, PBM_SETSTEP, 1, 0); - InvalidateRect (hProgressBar, NULL, TRUE); -} - -// Must always return TRUE -BOOL UpdateProgressBarProc (int nPercent) -{ - HWND hProgressBar = GetDlgItem (hCurPage, nPbar); - SendMessage (hProgressBar, PBM_SETPOS, (int) (100.0 * nPercent / 100), 0); - InvalidateRect (hProgressBar, NULL, TRUE); - ShowWindow(hProgressBar, SW_HIDE); - ShowWindow(hProgressBar, SW_SHOW); - // Prevent the IDC_LOG_WINDOW item from partially disappearing at higher DPIs - ShowWindow(GetDlgItem (hCurPage, IDC_LOG_WINDOW), SW_HIDE); - ShowWindow(GetDlgItem (hCurPage, IDC_LOG_WINDOW), SW_SHOW); - RefreshUIGFX(); - return TRUE; -} - -void RefreshUIGFX (void) -{ - InvalidateRect (GetDlgItem (MainDlg, IDC_SETUP_WIZARD_BKG), NULL, TRUE); - InvalidateRect (GetDlgItem (MainDlg, IDC_BOX_TITLE), NULL, TRUE); - InvalidateRect (GetDlgItem (MainDlg, IDC_BOX_INFO), NULL, TRUE); - InvalidateRect (GetDlgItem (MainDlg, IDC_BITMAP_SETUP_WIZARD), NULL, TRUE); - InvalidateRect (GetDlgItem (MainDlg, IDC_HR), NULL, TRUE); - // Prevent these items from disappearing at higher DPIs - ShowWindow(GetDlgItem(MainDlg, IDC_HR), SW_HIDE); - ShowWindow(GetDlgItem(MainDlg, IDC_HR), SW_SHOW); - ShowWindow(GetDlgItem(MainDlg, IDC_HR_BOTTOM), SW_HIDE); - ShowWindow(GetDlgItem(MainDlg, IDC_HR_BOTTOM), SW_SHOW); - ShowWindow(GetDlgItem(MainDlg, IDC_BOX_INFO), SW_HIDE); - ShowWindow(GetDlgItem(MainDlg, IDC_BOX_INFO), SW_SHOW); - ShowWindow(GetDlgItem(MainDlg, IDC_BOX_TITLE), SW_HIDE); - ShowWindow(GetDlgItem(MainDlg, IDC_BOX_TITLE), SW_SHOW); -} - - -/* Except in response to the WM_INITDIALOG message, the dialog box procedure - should return nonzero if it processes the message, and zero if it does - not. - see DialogProc */ -BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - WORD lw = LOWORD (wParam); - - switch (uMsg) - { - case WM_INITDIALOG: - { - RECT rec; - - GetModuleFileName (NULL, SelfFile, ARRAYSIZE (SelfFile)); - - MainDlg = hwndDlg; - - if (!CreateAppSetupMutex ()) - AbortProcess ("TC_INSTALLER_IS_RUNNING"); - - InitDialog (hwndDlg); - LocalizeDialog (hwndDlg, "IDD_INSTL_DLG"); - - // Resize the bitmap if the user has a non-default DPI - if (ScreenDPI != USER_DEFAULT_SCREEN_DPI) - { - hbmWizardBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_SETUP_WIZARD), - GetDlgItem (hwndDlg, IDC_BITMAP_SETUP_WIZARD), - 0, 0, 0, 0, FALSE, TRUE); - } - - // Gfx area background (must not keep aspect ratio; must retain Windows-imposed distortion) - GetClientRect (GetDlgItem (hwndDlg, IDC_SETUP_WIZARD_GFX_AREA), &rec); - SetWindowPos (GetDlgItem (hwndDlg, IDC_SETUP_WIZARD_BKG), HWND_TOP, 0, 0, rec.right, rec.bottom, SWP_NOMOVE); - - nPbar = IDC_PROGRESS_BAR; - - SendMessage (GetDlgItem (hwndDlg, IDC_BOX_TITLE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); - - SetWindowText (hwndDlg, L"VeraCrypt Setup " _T(VERSION_STRING)); - - DonColorSchemeId = GetDonVal (2, 9); - - if (bDevm) - { - InitWizardDestInstallPath (); - bSystemRestore = FALSE; - bRegisterFileExt = FALSE; - bAddToStartMenu = FALSE; - bDesktopIcon = TRUE; - bLicenseAccepted = TRUE; - bStartInstall = TRUE; - LoadPage (hwndDlg, INSTALL_PROGRESS_PAGE); - } - else - LoadPage (hwndDlg, INTRO_PAGE); - - } - return 0; - - case WM_SYSCOMMAND: - if (lw == IDC_ABOUT) - { - if (bLicenseAccepted) - DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_ABOUT_DLG), hwndDlg, (DLGPROC) AboutDlgProc); - - return 1; - } - return 0; - - case WM_HELP: - if (bLicenseAccepted) - OpenPageHelp (hwndDlg, nCurPageNo); - - return 1; - - - case WM_COMMAND: - if (lw == IDHELP) - { - if (bLicenseAccepted) - OpenPageHelp (hwndDlg, nCurPageNo); - - return 1; - } - if (lw == IDCANCEL) - { - PostMessage (hwndDlg, WM_CLOSE, 0, 0); - return 1; - } - if (lw == IDC_NEXT) - { - if (nCurPageNo == INTRO_PAGE) - { - if (!IsButtonChecked (GetDlgItem (hCurPage, IDC_AGREE))) - { - bLicenseAccepted = FALSE; - return 1; - } - bLicenseAccepted = TRUE; - EnableWindow (GetDlgItem (hwndDlg, IDHELP), TRUE); - - if (nCurrentOS == WIN_2000) - { - WarningDirect (L"Warning: Please note that this may be the last version of VeraCrypt that supports Windows 2000. If you want to be able to upgrade to future versions of VeraCrypt (which is highly recommended), you will need to upgrade to Windows XP or a later version of Windows.\n\nNote: Microsoft stopped issuing security updates for Windows 2000 to the general public on 7/13/2010 (the last non-security update for Windows 2000 was issued to the general public in 2005).", hwndDlg); - - - HKEY hkey; - - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Updates\\Windows 2000\\SP5\\Update Rollup 1", 0, KEY_READ, &hkey) != ERROR_SUCCESS) - { - ErrorDirect (L"VeraCrypt requires Update Rollup 1 for Windows 2000 SP4 to be installed.\n\nFor more information, see http://support.microsoft.com/kb/891861", hwndDlg); - AbortProcessSilent (); - } - - RegCloseKey (hkey); - } - } - - else if (nCurPageNo == WIZARD_MODE_PAGE) - { - if (IsButtonChecked (GetDlgItem (hCurPage, IDC_WIZARD_MODE_EXTRACT_ONLY))) - { - Info ("TRAVELER_LIMITATIONS_NOTE", hwndDlg); - - if (IsUacSupported() - && AskWarnYesNo ("TRAVELER_UAC_NOTE", hwndDlg) == IDNO) - { - return 1; - } - - bExtractOnly = TRUE; - nCurPageNo = EXTRACTION_OPTIONS_PAGE - 1; - } - } - - else if (nCurPageNo == EXTRACTION_OPTIONS_PAGE) - { - GetWindowText (GetDlgItem (hCurPage, IDC_DESTINATION), WizardDestExtractPath, ARRAYSIZE (WizardDestExtractPath)); - - bStartExtraction = TRUE; - } - - else if (nCurPageNo == INSTALL_OPTIONS_PAGE) - { - GetWindowText (GetDlgItem (hCurPage, IDC_DESTINATION), WizardDestInstallPath, ARRAYSIZE (WizardDestInstallPath)); - - bStartInstall = TRUE; - } - - else if (nCurPageNo == INSTALL_PROGRESS_PAGE) - { - PostMessage (hwndDlg, WM_CLOSE, 0, 0); - return 1; - } - - else if (nCurPageNo == EXTRACTION_PROGRESS_PAGE) - { - PostMessage (hwndDlg, WM_CLOSE, 0, 0); - return 1; - } - - else if (nCurPageNo == DONATIONS_PAGE) - { - // 'Finish' button clicked - - PostMessage (hwndDlg, WM_CLOSE, 0, 0); - - return 1; - } - - LoadPage (hwndDlg, ++nCurPageNo); - - return 1; - } - - if (lw == IDC_PREV) - { - if (nCurPageNo == WIZARD_MODE_PAGE) - { - bExtractOnly = IsButtonChecked (GetDlgItem (hCurPage, IDC_WIZARD_MODE_EXTRACT_ONLY)); - } - - else if (nCurPageNo == EXTRACTION_OPTIONS_PAGE) - { - GetWindowText (GetDlgItem (hCurPage, IDC_DESTINATION), WizardDestExtractPath, ARRAYSIZE (WizardDestExtractPath)); - nCurPageNo = WIZARD_MODE_PAGE + 1; - } - - else if (nCurPageNo == INSTALL_OPTIONS_PAGE) - { - GetWindowText (GetDlgItem (hCurPage, IDC_DESTINATION), WizardDestInstallPath, ARRAYSIZE (WizardDestInstallPath)); - } - - LoadPage (hwndDlg, --nCurPageNo); - - return 1; - } - - return 0; - - - - case WM_PAINT: - - if (nCurPageNo == DONATIONS_PAGE && DonColorSchemeId != 2) - { - HWND hwndItem = GetDlgItem (MainDlg, IDC_MAIN_CONTENT_CANVAS); - - PAINTSTRUCT tmpPaintStruct; - HDC hdc = BeginPaint (hwndItem, &tmpPaintStruct); - - if (DonColorSchemeId != 2) - { - HBRUSH tmpBrush = CreateSolidBrush (DonBkgColor); - - RECT trect; - - trect.left = CompensateXDPI (1); - trect.right = CompensateXDPI (560); - trect.top = CompensateYDPI (DonColorSchemeId == 7 ? 11 : 0); - trect.bottom = CompensateYDPI (260); - - FillRect (hdc, &trect, tmpBrush); - } - - EndPaint(hwndItem, &tmpPaintStruct); - ReleaseDC (hwndItem, hdc); - } - return 0; - - - - case WM_CTLCOLORSTATIC: - - if ((HWND) lParam != GetDlgItem (MainDlg, IDC_MAIN_CONTENT_CANVAS)) - { - /* This maintains the background under the transparent-backround texts. The above 'if' statement allows - colored background to be erased automatically when leaving a page that uses it. */ - - SetBkMode ((HDC) wParam, TRANSPARENT); - return ((LONG) (HBRUSH) (GetStockObject (NULL_BRUSH))); - } - - - case WM_ERASEBKGND: - - return 0; - - - - case TC_APPMSG_INSTALL_SUCCESS: - - /* Installation completed successfully */ - - bInProgress = FALSE; - - nCurPageNo = DONATIONS_PAGE; - LoadPage (hwndDlg, DONATIONS_PAGE); - - NormalCursor (); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_NEXT), GetString ("FINALIZE")); - - EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDHELP), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE); - - - RefreshUIGFX (); - return 1; - - case TC_APPMSG_INSTALL_FAILURE: - - /* Installation failed */ - - bInProgress = FALSE; - - NormalCursor (); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_TITLE), GetString ("INSTALL_FAILED")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_INFO), L""); - - SetWindowTextW (GetDlgItem (hwndDlg, IDCANCEL), GetString ("IDCLOSE")); - EnableWindow (GetDlgItem (hwndDlg, IDHELP), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), TRUE); - - RefreshUIGFX(); - - return 1; - - case TC_APPMSG_EXTRACTION_SUCCESS: - - /* Extraction completed successfully */ - - UpdateProgressBarProc(100); - - bInProgress = FALSE; - bExtractionSuccessful = TRUE; - - NormalCursor (); - - StatusMessage (hCurPage, "EXTRACTION_FINISHED_INFO"); - - EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDHELP), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE); - - RefreshUIGFX (); - - Info ("EXTRACTION_FINISHED_INFO", hwndDlg); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_NEXT), GetString ("FINALIZE")); - - nCurPageNo = DONATIONS_PAGE; - LoadPage (hwndDlg, DONATIONS_PAGE); - - return 1; - - case TC_APPMSG_EXTRACTION_FAILURE: - - /* Extraction failed */ - - bInProgress = FALSE; - - NormalCursor (); - - StatusMessage (hCurPage, "EXTRACTION_FAILED"); - - UpdateProgressBarProc(0); - - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_TITLE), GetString ("EXTRACTION_FAILED")); - SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_INFO), L""); - - SetWindowTextW (GetDlgItem (hwndDlg, IDCANCEL), GetString ("IDCLOSE")); - EnableWindow (GetDlgItem (hwndDlg, IDHELP), TRUE); - EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), TRUE); - - RefreshUIGFX(); - - Error ("EXTRACTION_FAILED", hwndDlg); - - return 1; - - case WM_CLOSE: - - if (!bDevm) - { - if (bInProgress) - { - NormalCursor(); - if (AskNoYes("CONFIRM_EXIT_UNIVERSAL", hwndDlg) == IDNO) - { - return 1; - } - WaitCursor (); - } - - if (bOpenContainingFolder && bExtractOnly && bExtractionSuccessful) - { - ShellExecute (NULL, L"open", WizardDestExtractPath, NULL, NULL, SW_SHOWNORMAL); - } - else - { - if (bPromptReleaseNotes - && AskYesNo ("AFTER_UPGRADE_RELEASE_NOTES", hwndDlg) == IDYES) - { - Applink ("releasenotes", TRUE, ""); - } - - bPromptReleaseNotes = FALSE; - - if (bPromptTutorial - && AskYesNo ("AFTER_INSTALL_TUTORIAL", hwndDlg) == IDYES) - { - Applink ("beginnerstutorial", TRUE, ""); - } - - bPromptTutorial = FALSE; - } - - if (bRestartRequired - && AskYesNo (bUpgrade ? "UPGRADE_OK_REBOOT_REQUIRED" : "CONFIRM_RESTART", hwndDlg) == IDYES) - { - RestartComputer(); - } - } - - EndDialog (hwndDlg, IDCANCEL); - return 1; - } - - return 0; -} - - +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 "Tcdefs.h" +#include +#include +#include +#include +#include "SelfExtract.h" +#include "Wizard.h" +#include "Dlgcode.h" +#include "Language.h" +#include "Common/Resource.h" +#include "Resource.h" +#include "Setup.h" +#include +#include + +using namespace std; + +enum wizard_pages +{ + INTRO_PAGE, + WIZARD_MODE_PAGE, + INSTALL_OPTIONS_PAGE, + INSTALL_PROGRESS_PAGE, + EXTRACTION_OPTIONS_PAGE, + EXTRACTION_PROGRESS_PAGE, + DONATIONS_PAGE +}; + +HWND hCurPage = NULL; /* Handle to current wizard page */ +int nCurPageNo = -1; /* The current wizard page */ +wchar_t WizardDestInstallPath [TC_MAX_PATH]; +wchar_t WizardDestExtractPath [TC_MAX_PATH]; +wchar_t SelfFile [TC_MAX_PATH]; + +HBITMAP hbmWizardBitmapRescaled = NULL; + +BOOL bExtractOnly = FALSE; +BOOL bLicenseAccepted = FALSE; +BOOL bOpenContainingFolder = TRUE; +BOOL bExtractionSuccessful = FALSE; +BOOL bStartInstall = FALSE; +BOOL bStartExtraction = FALSE; +BOOL bInProgress = FALSE; +BOOL bPromptTutorial = FALSE; +BOOL bPromptReleaseNotes = FALSE; + +int nPbar = 0; /* Control ID of progress bar */ + +static HFONT hDonTextFont; +static BOOL OsPrngAvailable; +static HCRYPTPROV hCryptProv; +static int DonColorSchemeId; +static COLORREF DonTextColor; +static COLORREF DonBkgColor; + +wstring DonText = L""; + +void localcleanupwiz (void) +{ + /* Delete buffered bitmaps (if any) */ + if (hbmWizardBitmapRescaled != NULL) + { + DeleteObject ((HGDIOBJ) hbmWizardBitmapRescaled); + hbmWizardBitmapRescaled = NULL; + } + + if (hCryptProv != 0) + { + OsPrngAvailable = FALSE; + CryptReleaseContext (hCryptProv, 0); + hCryptProv = 0; + } + + if (hDonTextFont != NULL) + { + DeleteObject (hDonTextFont); + hDonTextFont = NULL; + } +} + +static void InitWizardDestInstallPath (void) +{ + if (wcslen (WizardDestInstallPath) < 2) + { + StringCbCopyW (WizardDestInstallPath, sizeof(WizardDestInstallPath), InstallationPath); + if (WizardDestInstallPath [wcslen (WizardDestInstallPath) - 1] != L'\\') + { + StringCbCatW (WizardDestInstallPath, sizeof(WizardDestInstallPath), L"\\"); + } + } +} + +void LoadPage (HWND hwndDlg, int nPageNo) +{ + RECT rD, rW; + + if (hCurPage != NULL) + { + DestroyWindow (hCurPage); + } + + InvalidateRect (GetDlgItem (MainDlg, IDC_MAIN_CONTENT_CANVAS), NULL, TRUE); + + GetWindowRect (GetDlgItem (hwndDlg, IDC_POS_BOX), &rW); + + nCurPageNo = nPageNo; + + switch (nPageNo) + { + case INTRO_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INTRO_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case WIZARD_MODE_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_WIZARD_MODE_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case INSTALL_OPTIONS_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_INSTALL_OPTIONS_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case INSTALL_PROGRESS_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_PROGRESS_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case EXTRACTION_OPTIONS_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_EXTRACTION_OPTIONS_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case EXTRACTION_PROGRESS_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_PROGRESS_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + + case DONATIONS_PAGE: + hCurPage = CreateDialogW (hInst, MAKEINTRESOURCEW (IDD_DONATIONS_PAGE_DLG), hwndDlg, + (DLGPROC) PageDialogProc); + break; + } + + rD.left = 15; + rD.top = 45; + rD.right = 0; + rD.bottom = 0; + MapDialogRect (hwndDlg, &rD); + + if (hCurPage != NULL) + { + MoveWindow (hCurPage, rD.left, rD.top, rW.right - rW.left, rW.bottom - rW.top, TRUE); + ShowWindow (hCurPage, SW_SHOWNORMAL); + } + + /* Refresh the graphics (white background of some texts, etc.) */ + RefreshUIGFX (); +} + + +static int GetDonVal (int minVal, int maxVal) +{ + static BOOL prngInitialized = FALSE; + static unsigned __int8 buffer [2]; + + if (!prngInitialized) + { + if (!CryptAcquireContext (&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0) + && !CryptAcquireContext (&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) + OsPrngAvailable = FALSE; + else + OsPrngAvailable = TRUE; + + srand ((unsigned int) time (NULL)); + rand(); // Generate and discard the inital value, as it always appears to be somewhat non-random. + + prngInitialized = TRUE; + } + + if (OsPrngAvailable && CryptGenRandom (hCryptProv, sizeof (buffer), buffer) != 0) + { + return ((int) ((double) *((uint16 *) buffer) / (0xFFFF+1) * (maxVal + 1 - minVal)) + minVal); + } + else + return ((int) ((double) rand() / (RAND_MAX+1) * (maxVal + 1 - minVal)) + minVal); +} + + +/* Except in response to the WM_INITDIALOG message, the dialog box procedure + should return nonzero if it processes the message, and zero if it does + not. - see DialogProc */ +BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + static char PageDebugId[128]; + WORD lw = LOWORD (wParam); + WORD hw = HIWORD (wParam); + + hCurPage = hwndDlg; + + switch (uMsg) + { + case WM_INITDIALOG: + LocalizeDialog (hwndDlg, "IDD_INSTL_DLG"); + + StringCbPrintfA (PageDebugId, sizeof(PageDebugId), "SETUP_WIZARD_PAGE_%d", nCurPageNo); + LastDialogId = PageDebugId; + + switch (nCurPageNo) + { + case INTRO_PAGE: + { + char *licenseText = NULL; + + licenseText = GetLegalNotices (); + if (licenseText != NULL) + { + SetWindowTextA (GetDlgItem (hwndDlg, IDC_LICENSE_TEXT), licenseText); + free (licenseText); + } + else + { + Error("CANNOT_DISPLAY_LICENSE", hwndDlg); + exit (1); + } + + /* For legal reasons, some of the following texts cannot be localized by third parties. */ + + SetCheckBox (hwndDlg, IDC_AGREE, bLicenseAccepted); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), L"Please read the license terms"); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), L"You must accept these license terms before you can use, extract, or install VeraCrypt."); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), L"IMPORTANT: By checking the checkbox below, you accept these license terms and signify that you understand and agree to them. Please click the 'arrow down' icon to see the rest of the license."); // Cannot be localized by third parties (for legal reasons). + //SendMessage (GetDlgItem (hwndDlg, IDC_BOX_HELP), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_AGREE), L"I &accept the license terms"); // Cannot be localized by third parties (for legal reasons). + //SetWindowTextW (GetDlgItem (hwndDlg, IDC_DISAGREE), L"I &do not accept the license terms"); + + //SendMessage (GetDlgItem (hwndDlg, IDC_AGREE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + //SendMessage (GetDlgItem (hwndDlg, IDC_DISAGREE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + + EnableWindow (GetDlgItem (hwndDlg, IDC_AGREE), TRUE); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), bLicenseAccepted); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), bLicenseAccepted); + + // Left margin for license text + SendMessage (GetDlgItem (hwndDlg, IDC_LICENSE_TEXT), EM_SETMARGINS, (WPARAM) EC_LEFTMARGIN, (LPARAM) CompensateXDPI (4)); + } + return 1; + + case WIZARD_MODE_PAGE: + { + LONG driverVersion; + + DetermineUpgradeDowngradeStatus (TRUE, &driverVersion); + + if (bRepairMode || bReinstallMode) + { + SetWindowTextW (GetDlgItem (hwndDlg, IDC_WIZARD_MODE_INSTALL), GetString ("REPAIR_REINSTALL")); + bExtractOnly = FALSE; + } + else if (bUpgrade) + SetWindowTextW (GetDlgItem (hwndDlg, IDC_WIZARD_MODE_INSTALL), GetString ("UPGRADE")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SETUP_MODE_TITLE")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), GetString ("SETUP_MODE_INFO")); + + SendMessage (GetDlgItem (hwndDlg, IDC_WIZARD_MODE_INSTALL), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + SendMessage (GetDlgItem (hwndDlg, IDC_WIZARD_MODE_EXTRACT_ONLY), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + + CheckButton (GetDlgItem (hwndDlg, bExtractOnly ? IDC_WIZARD_MODE_EXTRACT_ONLY : IDC_WIZARD_MODE_INSTALL)); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SETUP_MODE_HELP_EXTRACT")); + + if (!bRepairMode) + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP2), GetString (bUpgrade ? "SETUP_MODE_HELP_UPGRADE" : "SETUP_MODE_HELP_INSTALL")); + + EnableWindow (GetDlgItem (hwndDlg, IDC_WIZARD_MODE_EXTRACT_ONLY), !bRepairMode); + EnableWindow (GetDlgItem (hwndDlg, IDC_BOX_HELP), !bRepairMode); + EnableWindow (GetDlgItem (hwndDlg, IDC_WIZARD_MODE_INSTALL), TRUE); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + } + return 1; + + case EXTRACTION_OPTIONS_PAGE: + + if (wcslen(WizardDestExtractPath) < 2) + { + StringCbCopyW (WizardDestExtractPath, sizeof(WizardDestExtractPath), SetupFilesDir); + StringCbCatNW (WizardDestExtractPath, sizeof(WizardDestExtractPath), L"VeraCrypt\\", ARRAYSIZE (WizardDestExtractPath) - wcslen (WizardDestExtractPath) - 1); + } + + SendMessage (GetDlgItem (hwndDlg, IDC_DESTINATION), EM_LIMITTEXT, TC_MAX_PATH - 1, 0); + + SetDlgItemText (hwndDlg, IDC_DESTINATION, WizardDestExtractPath); + + SetCheckBox (hwndDlg, IDC_OPEN_CONTAINING_FOLDER, bOpenContainingFolder); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("EXTRACTION_OPTIONS_TITLE")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), GetString ("EXTRACTION_OPTIONS_INFO")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("AUTO_FOLDER_CREATION")); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("EXTRACT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); + + return 1; + + case EXTRACTION_PROGRESS_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("EXTRACTING_VERB")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), GetString ("EXTRACTION_PROGRESS_INFO")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + + if (bStartExtraction) + { + /* Start extraction */ + + LastDialogId = "EXTRACTION_IN_PROGRESS"; + + WaitCursor (); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), FALSE); + + if (WizardDestExtractPath [wcslen(WizardDestExtractPath)-1] != L'\\') + StringCbCatW (WizardDestExtractPath, sizeof(WizardDestExtractPath), L"\\"); + + StringCbCopyW (DestExtractPath, sizeof(DestExtractPath), WizardDestExtractPath); + + InitProgressBar (); + + bInProgress = TRUE; + bStartExtraction = FALSE; + + _beginthread (ExtractAllFilesThread, 0, (void *) hwndDlg); + } + else + { + NormalCursor (); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); + } + + return 1; + + case INSTALL_OPTIONS_PAGE: + { + LONG driverVersion; + + DetermineUpgradeDowngradeStatus (TRUE, &driverVersion); + + if (!bDesktopIconStatusDetermined) + { + bDesktopIcon = !bUpgrade; + bDesktopIconStatusDetermined = TRUE; + } + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SETUP_OPTIONS_TITLE")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), GetString ("SETUP_OPTIONS_INFO")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("AUTO_FOLDER_CREATION")); + + InitWizardDestInstallPath (); + + SendMessage (GetDlgItem (hwndDlg, IDC_DESTINATION), EM_LIMITTEXT, TC_MAX_PATH - 1, 0); + + SetDlgItemText (hwndDlg, IDC_DESTINATION, WizardDestInstallPath); + + if (bUpgrade) + { + SetWindowTextW (GetDlgItem (hwndDlg, IDT_INSTALL_DESTINATION), GetString ("SETUP_UPGRADE_DESTINATION")); + EnableWindow (GetDlgItem (hwndDlg, IDC_DESTINATION), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_BROWSE), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_ALL_USERS), FALSE); + + wchar_t path[MAX_PATH]; + SHGetSpecialFolderPath (hwndDlg, path, CSIDL_COMMON_PROGRAMS, 0); + bForAllUsers = (_waccess ((wstring (path) + L"\\" _T(TC_APP_NAME)).c_str(), 0) == 0); + } + + // System Restore + SetCheckBox (hwndDlg, IDC_SYSTEM_RESTORE, bSystemRestore); + if (SystemRestoreDll == 0) + { + SetCheckBox (hwndDlg, IDC_SYSTEM_RESTORE, FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_SYSTEM_RESTORE), FALSE); + } + + SetCheckBox (hwndDlg, IDC_ALL_USERS, bForAllUsers); + SetCheckBox (hwndDlg, IDC_FILE_TYPE, bRegisterFileExt); + SetCheckBox (hwndDlg, IDC_PROG_GROUP, bAddToStartMenu); + SetCheckBox (hwndDlg, IDC_DESKTOP_ICON, bDesktopIcon); + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString (bUpgrade ? "UPGRADE" : "INSTALL")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); + } + return 1; + + case INSTALL_PROGRESS_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SETUP_PROGRESS_TITLE")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), GetString ("SETUP_PROGRESS_INFO")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV")); + + if (bStartInstall) + { + /* Start install */ + + LastDialogId = "INSTALL_IN_PROGRESS"; + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT")); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), FALSE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), FALSE); + + InitProgressBar (); + + if (WizardDestInstallPath [wcslen(WizardDestInstallPath)-1] != L'\\') + StringCbCatW (WizardDestInstallPath, sizeof(WizardDestInstallPath), L"\\"); + + StringCbCopyW (InstallationPath, sizeof(InstallationPath), WizardDestInstallPath); + + WaitCursor (); + + bInProgress = TRUE; + bStartInstall = FALSE; + + _beginthread (DoInstall, 0, (void *) hwndDlg); + } + else + { + NormalCursor (); + + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDHELP), TRUE); + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), TRUE); + + } + + return 1; + + case DONATIONS_PAGE: + + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bExtractOnly ? "EXTRACTION_FINISHED_TITLE_DON" : (bUpgrade ? "SETUP_FINISHED_UPGRADE_TITLE_DON" : "SETUP_FINISHED_TITLE_DON"))); + SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_INFO), GetString ("SETUP_FINISHED_INFO_DON")); + + DonText = L"Please consider making a donation."; + + + // Colors + + switch (DonColorSchemeId) + { + case 2: + // NOP - Default OS colors (foreground and background) + break; + + case 3: + // Red + DonTextColor = RGB (255, 255, 255); + DonBkgColor = RGB (255, 0, 0); + break; + + case 4: + // Yellow + DonTextColor = RGB (255, 15, 49); + DonBkgColor = RGB (255, 255, 0); + break; + + case 5: + // Light red + DonTextColor = RGB (255, 255, 255); + DonBkgColor = RGB (255, 141, 144); + break; + + case 6: + // Pink + DonTextColor = RGB (255, 255, 255); + DonBkgColor = RGB (248, 148, 207); + break; + + case 7: + // White + red text + DonTextColor = RGB (255, 15, 49); + DonBkgColor = RGB (255, 255, 255); + break; + + case 8: + // Blue + DonTextColor = RGB (255, 255, 255); + DonBkgColor = RGB (54, 140, 255); + break; + + case 9: + // Green + DonTextColor = RGB (255, 255, 255); + DonBkgColor = RGB (70, 180, 80); + break; + } + + { + // Font + + LOGFONTW lf; + memset (&lf, 0, sizeof(lf)); + + // Main font + StringCbCopyW (lf.lfFaceName, sizeof (lf.lfFaceName),L"Times New Roman"); + lf.lfHeight = CompensateDPIFont (-21); + lf.lfWeight = FW_NORMAL; + lf.lfWidth = 0; + lf.lfEscapement = 0; + lf.lfOrientation = 0; + lf.lfItalic = FALSE; + lf.lfUnderline = FALSE; + lf.lfStrikeOut = FALSE; + lf.lfCharSet = DEFAULT_CHARSET; + lf.lfOutPrecision = OUT_DEFAULT_PRECIS; + lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; + lf.lfQuality = PROOF_QUALITY; + lf.lfPitchAndFamily = FF_DONTCARE; + hDonTextFont = CreateFontIndirectW (&lf); + + if (hDonTextFont == NULL) + AbortProcessSilent (); + } + + return 1; + } + + return 0; + + case WM_HELP: + if (bLicenseAccepted) + OpenPageHelp (GetParent (hwndDlg), nCurPageNo); + + return 1; + + case WM_ENDSESSION: + + bPromptTutorial = FALSE; + bPromptReleaseNotes = FALSE; + + EndDialog (MainDlg, 0); + localcleanup (); + return 0; + + + case WM_COMMAND: + + if (lw == IDC_AGREE && nCurPageNo == INTRO_PAGE) + { + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), IsButtonChecked (GetDlgItem (hwndDlg, IDC_AGREE))); + return 1; + } + + if (lw == IDC_WIZARD_MODE_EXTRACT_ONLY && nCurPageNo == WIZARD_MODE_PAGE) + { + bExtractOnly = TRUE; + return 1; + } + + if (lw == IDC_WIZARD_MODE_INSTALL && nCurPageNo == WIZARD_MODE_PAGE) + { + bExtractOnly = FALSE; + return 1; + } + + if ( nCurPageNo == EXTRACTION_OPTIONS_PAGE && hw == EN_CHANGE ) + { + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), (GetWindowTextLength (GetDlgItem (hCurPage, IDC_DESTINATION)) > 1)); + return 1; + } + + if ( nCurPageNo == INSTALL_OPTIONS_PAGE && hw == EN_CHANGE ) + { + EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), (GetWindowTextLength (GetDlgItem (hCurPage, IDC_DESTINATION)) > 1)); + return 1; + } + + if ( nCurPageNo == EXTRACTION_OPTIONS_PAGE ) + { + switch (lw) + { + case IDC_BROWSE: + if (BrowseDirectories (hwndDlg, "SELECT_DEST_DIR", WizardDestExtractPath)) + { + if (WizardDestExtractPath [wcslen(WizardDestExtractPath)-1] != L'\\') + { + StringCbCatW (WizardDestExtractPath, sizeof(WizardDestExtractPath), L"\\"); + } + SetDlgItemText (hwndDlg, IDC_DESTINATION, WizardDestExtractPath); + } + return 1; + + case IDC_OPEN_CONTAINING_FOLDER: + bOpenContainingFolder = IsButtonChecked (GetDlgItem (hCurPage, IDC_OPEN_CONTAINING_FOLDER)); + return 1; + } + } + + if ( nCurPageNo == INSTALL_OPTIONS_PAGE ) + { + switch (lw) + { + case IDC_BROWSE: + if (BrowseDirectories (hwndDlg, "SELECT_DEST_DIR", WizardDestInstallPath)) + { + if (WizardDestInstallPath [wcslen(WizardDestInstallPath)-1] != L'\\') + { + StringCbCatW (WizardDestInstallPath, sizeof(WizardDestInstallPath), L"\\"); + } + SetDlgItemText (hwndDlg, IDC_DESTINATION, WizardDestInstallPath); + } + return 1; + + case IDC_SYSTEM_RESTORE: + bSystemRestore = IsButtonChecked (GetDlgItem (hCurPage, IDC_SYSTEM_RESTORE)); + return 1; + + case IDC_ALL_USERS: + bForAllUsers = IsButtonChecked (GetDlgItem (hCurPage, IDC_ALL_USERS)); + return 1; + + case IDC_FILE_TYPE: + bRegisterFileExt = IsButtonChecked (GetDlgItem (hCurPage, IDC_FILE_TYPE)); + return 1; + + case IDC_PROG_GROUP: + bAddToStartMenu = IsButtonChecked (GetDlgItem (hCurPage, IDC_PROG_GROUP)); + return 1; + + case IDC_DESKTOP_ICON: + bDesktopIcon = IsButtonChecked (GetDlgItem (hCurPage, IDC_DESKTOP_ICON)); + return 1; + + } + } + + if (nCurPageNo == DONATIONS_PAGE) + { + switch (lw) + { + case IDC_DONATE: + { + char tmpstr [200]; + + StringCbPrintfA (tmpstr, sizeof(tmpstr), "&ref=%d", DonColorSchemeId); + + Applink ("donate", FALSE, tmpstr); + } + return 1; + } + } + + return 0; + + + case WM_PAINT: + + if (nCurPageNo == DONATIONS_PAGE) + { + PAINTSTRUCT tmpPaintStruct; + HDC hdc = BeginPaint (hCurPage, &tmpPaintStruct); + + if (hdc == NULL) + AbortProcessSilent (); + + SelectObject (hdc, hDonTextFont); + + if (DonColorSchemeId != 2) + { + HBRUSH tmpBrush = CreateSolidBrush (DonBkgColor); + + if (tmpBrush == NULL) + AbortProcessSilent (); + + RECT trect; + + trect.left = 0; + trect.right = CompensateXDPI (526); + trect.top = 0; + trect.bottom = CompensateYDPI (246); + + FillRect (hdc, &trect, tmpBrush); + + SetTextColor (hdc, DonTextColor); + SetBkColor (hdc, DonBkgColor); + } + + SetTextAlign(hdc, TA_CENTER); + + TextOutW (hdc, + CompensateXDPI (258), + CompensateYDPI (70), + DonText.c_str(), + DonText.length()); + + EndPaint (hCurPage, &tmpPaintStruct); + ReleaseDC (hCurPage, hdc); + } + return 0; + + } + + return 0; +} + +void InitProgressBar (void) +{ + HWND hProgressBar = GetDlgItem (hCurPage, nPbar); + SendMessage (hProgressBar, PBM_SETRANGE32, 0, 100); + SendMessage (hProgressBar, PBM_SETSTEP, 1, 0); + InvalidateRect (hProgressBar, NULL, TRUE); +} + +// Must always return TRUE +BOOL UpdateProgressBarProc (int nPercent) +{ + HWND hProgressBar = GetDlgItem (hCurPage, nPbar); + SendMessage (hProgressBar, PBM_SETPOS, (int) (100.0 * nPercent / 100), 0); + InvalidateRect (hProgressBar, NULL, TRUE); + ShowWindow(hProgressBar, SW_HIDE); + ShowWindow(hProgressBar, SW_SHOW); + // Prevent the IDC_LOG_WINDOW item from partially disappearing at higher DPIs + ShowWindow(GetDlgItem (hCurPage, IDC_LOG_WINDOW), SW_HIDE); + ShowWindow(GetDlgItem (hCurPage, IDC_LOG_WINDOW), SW_SHOW); + RefreshUIGFX(); + return TRUE; +} + +void RefreshUIGFX (void) +{ + InvalidateRect (GetDlgItem (MainDlg, IDC_SETUP_WIZARD_BKG), NULL, TRUE); + InvalidateRect (GetDlgItem (MainDlg, IDC_BOX_TITLE), NULL, TRUE); + InvalidateRect (GetDlgItem (MainDlg, IDC_BOX_INFO), NULL, TRUE); + InvalidateRect (GetDlgItem (MainDlg, IDC_BITMAP_SETUP_WIZARD), NULL, TRUE); + InvalidateRect (GetDlgItem (MainDlg, IDC_HR), NULL, TRUE); + // Prevent these items from disappearing at higher DPIs + ShowWindow(GetDlgItem(MainDlg, IDC_HR), SW_HIDE); + ShowWindow(GetDlgItem(MainDlg, IDC_HR), SW_SHOW); + ShowWindow(GetDlgItem(MainDlg, IDC_HR_BOTTOM), SW_HIDE); + ShowWindow(GetDlgItem(MainDlg, IDC_HR_BOTTOM), SW_SHOW); + ShowWindow(GetDlgItem(MainDlg, IDC_BOX_INFO), SW_HIDE); + ShowWindow(GetDlgItem(MainDlg, IDC_BOX_INFO), SW_SHOW); + ShowWindow(GetDlgItem(MainDlg, IDC_BOX_TITLE), SW_HIDE); + ShowWindow(GetDlgItem(MainDlg, IDC_BOX_TITLE), SW_SHOW); +} + + +/* Except in response to the WM_INITDIALOG message, the dialog box procedure + should return nonzero if it processes the message, and zero if it does + not. - see DialogProc */ +BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + WORD lw = LOWORD (wParam); + + switch (uMsg) + { + case WM_INITDIALOG: + { + RECT rec; + + GetModuleFileName (NULL, SelfFile, ARRAYSIZE (SelfFile)); + + MainDlg = hwndDlg; + + if (!CreateAppSetupMutex ()) + AbortProcess ("TC_INSTALLER_IS_RUNNING"); + + InitDialog (hwndDlg); + LocalizeDialog (hwndDlg, "IDD_INSTL_DLG"); + + // Resize the bitmap if the user has a non-default DPI + if (ScreenDPI != USER_DEFAULT_SCREEN_DPI) + { + hbmWizardBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_SETUP_WIZARD), + GetDlgItem (hwndDlg, IDC_BITMAP_SETUP_WIZARD), + 0, 0, 0, 0, FALSE, TRUE); + } + + // Gfx area background (must not keep aspect ratio; must retain Windows-imposed distortion) + GetClientRect (GetDlgItem (hwndDlg, IDC_SETUP_WIZARD_GFX_AREA), &rec); + SetWindowPos (GetDlgItem (hwndDlg, IDC_SETUP_WIZARD_BKG), HWND_TOP, 0, 0, rec.right, rec.bottom, SWP_NOMOVE); + + nPbar = IDC_PROGRESS_BAR; + + SendMessage (GetDlgItem (hwndDlg, IDC_BOX_TITLE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE); + + SetWindowText (hwndDlg, L"VeraCrypt Setup " _T(VERSION_STRING)); + + DonColorSchemeId = GetDonVal (2, 9); + + if (bDevm) + { + InitWizardDestInstallPath (); + bSystemRestore = FALSE; + bRegisterFileExt = FALSE; + bAddToStartMenu = FALSE; + bDesktopIcon = TRUE; + bLicenseAccepted = TRUE; + bStartInstall = TRUE; + LoadPage (hwndDlg, INSTALL_PROGRESS_PAGE); + } + else + LoadPage (hwndDlg, INTRO_PAGE); + + } + return 0; + + case WM_SYSCOMMAND: + if (lw == IDC_ABOUT) + { + if (bLicenseAccepted) + DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_ABOUT_DLG), hwndDlg, (DLGPROC) AboutDlgProc); + + return 1; + } + return 0; + + case WM_HELP: + if (bLicenseAccepted) + OpenPageHelp (hwndDlg, nCurPageNo); + + return 1; + + + case WM_COMMAND: + if (lw == IDHELP) + { + if (bLicenseAccepted) + OpenPageHelp (hwndDlg, nCurPageNo); + + return 1; + } + if (lw == IDCANCEL) + { + PostMessage (hwndDlg, WM_CLOSE, 0, 0); + return 1; + } + if (lw == IDC_NEXT) + { + if (nCurPageNo == INTRO_PAGE) + { + if (!IsButtonChecked (GetDlgItem (hCurPage, IDC_AGREE))) + { + bLicenseAccepted = FALSE; + return 1; + } + bLicenseAccepted = TRUE; + EnableWindow (GetDlgItem (hwndDlg, IDHELP), TRUE); + + if (nCurrentOS == WIN_2000) + { + WarningDirect (L"Warning: Please note that this may be the last version of VeraCrypt that supports Windows 2000. If you want to be able to upgrade to future versions of VeraCrypt (which is highly recommended), you will need to upgrade to Windows XP or a later version of Windows.\n\nNote: Microsoft stopped issuing security updates for Windows 2000 to the general public on 7/13/2010 (the last non-security update for Windows 2000 was issued to the general public in 2005).", hwndDlg); + + + HKEY hkey; + + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Updates\\Windows 2000\\SP5\\Update Rollup 1", 0, KEY_READ, &hkey) != ERROR_SUCCESS) + { + ErrorDirect (L"VeraCrypt requires Update Rollup 1 for Windows 2000 SP4 to be installed.\n\nFor more information, see http://support.microsoft.com/kb/891861", hwndDlg); + AbortProcessSilent (); + } + + RegCloseKey (hkey); + } + } + + else if (nCurPageNo == WIZARD_MODE_PAGE) + { + if (IsButtonChecked (GetDlgItem (hCurPage, IDC_WIZARD_MODE_EXTRACT_ONLY))) + { + Info ("TRAVELER_LIMITATIONS_NOTE", hwndDlg); + + if (IsUacSupported() + && AskWarnYesNo ("TRAVELER_UAC_NOTE", hwndDlg) == IDNO) + { + return 1; + } + + bExtractOnly = TRUE; + nCurPageNo = EXTRACTION_OPTIONS_PAGE - 1; + } + } + + else if (nCurPageNo == EXTRACTION_OPTIONS_PAGE) + { + GetWindowText (GetDlgItem (hCurPage, IDC_DESTINATION), WizardDestExtractPath, ARRAYSIZE (WizardDestExtractPath)); + + bStartExtraction = TRUE; + } + + else if (nCurPageNo == INSTALL_OPTIONS_PAGE) + { + GetWindowText (GetDlgItem (hCurPage, IDC_DESTINATION), WizardDestInstallPath, ARRAYSIZE (WizardDestInstallPath)); + + bStartInstall = TRUE; + } + + else if (nCurPageNo == INSTALL_PROGRESS_PAGE) + { + PostMessage (hwndDlg, WM_CLOSE, 0, 0); + return 1; + } + + else if (nCurPageNo == EXTRACTION_PROGRESS_PAGE) + { + PostMessage (hwndDlg, WM_CLOSE, 0, 0); + return 1; + } + + else if (nCurPageNo == DONATIONS_PAGE) + { + // 'Finish' button clicked + + PostMessage (hwndDlg, WM_CLOSE, 0, 0); + + return 1; + } + + LoadPage (hwndDlg, ++nCurPageNo); + + return 1; + } + + if (lw == IDC_PREV) + { + if (nCurPageNo == WIZARD_MODE_PAGE) + { + bExtractOnly = IsButtonChecked (GetDlgItem (hCurPage, IDC_WIZARD_MODE_EXTRACT_ONLY)); + } + + else if (nCurPageNo == EXTRACTION_OPTIONS_PAGE) + { + GetWindowText (GetDlgItem (hCurPage, IDC_DESTINATION), WizardDestExtractPath, ARRAYSIZE (WizardDestExtractPath)); + nCurPageNo = WIZARD_MODE_PAGE + 1; + } + + else if (nCurPageNo == INSTALL_OPTIONS_PAGE) + { + GetWindowText (GetDlgItem (hCurPage, IDC_DESTINATION), WizardDestInstallPath, ARRAYSIZE (WizardDestInstallPath)); + } + + LoadPage (hwndDlg, --nCurPageNo); + + return 1; + } + + return 0; + + + + case WM_PAINT: + + if (nCurPageNo == DONATIONS_PAGE && DonColorSchemeId != 2) + { + HWND hwndItem = GetDlgItem (MainDlg, IDC_MAIN_CONTENT_CANVAS); + + PAINTSTRUCT tmpPaintStruct; + HDC hdc = BeginPaint (hwndItem, &tmpPaintStruct); + + if (DonColorSchemeId != 2) + { + HBRUSH tmpBrush = CreateSolidBrush (DonBkgColor); + + RECT trect; + + trect.left = CompensateXDPI (1); + trect.right = CompensateXDPI (560); + trect.top = CompensateYDPI (DonColorSchemeId == 7 ? 11 : 0); + trect.bottom = CompensateYDPI (260); + + FillRect (hdc, &trect, tmpBrush); + } + + EndPaint(hwndItem, &tmpPaintStruct); + ReleaseDC (hwndItem, hdc); + } + return 0; + + + + case WM_CTLCOLORSTATIC: + + if ((HWND) lParam != GetDlgItem (MainDlg, IDC_MAIN_CONTENT_CANVAS)) + { + /* This maintains the background under the transparent-backround texts. The above 'if' statement allows + colored background to be erased automatically when leaving a page that uses it. */ + + SetBkMode ((HDC) wParam, TRANSPARENT); + return ((LONG) (HBRUSH) (GetStockObject (NULL_BRUSH))); + } + + + case WM_ERASEBKGND: + + return 0; + + + + case TC_APPMSG_INSTALL_SUCCESS: + + /* Installation completed successfully */ + + bInProgress = FALSE; + + nCurPageNo = DONATIONS_PAGE; + LoadPage (hwndDlg, DONATIONS_PAGE); + + NormalCursor (); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_NEXT), GetString ("FINALIZE")); + + EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDHELP), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE); + + + RefreshUIGFX (); + return 1; + + case TC_APPMSG_INSTALL_FAILURE: + + /* Installation failed */ + + bInProgress = FALSE; + + NormalCursor (); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_TITLE), GetString ("INSTALL_FAILED")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_INFO), L""); + + SetWindowTextW (GetDlgItem (hwndDlg, IDCANCEL), GetString ("IDCLOSE")); + EnableWindow (GetDlgItem (hwndDlg, IDHELP), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), TRUE); + + RefreshUIGFX(); + + return 1; + + case TC_APPMSG_EXTRACTION_SUCCESS: + + /* Extraction completed successfully */ + + UpdateProgressBarProc(100); + + bInProgress = FALSE; + bExtractionSuccessful = TRUE; + + NormalCursor (); + + StatusMessage (hCurPage, "EXTRACTION_FINISHED_INFO"); + + EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDHELP), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE); + + RefreshUIGFX (); + + Info ("EXTRACTION_FINISHED_INFO", hwndDlg); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_NEXT), GetString ("FINALIZE")); + + nCurPageNo = DONATIONS_PAGE; + LoadPage (hwndDlg, DONATIONS_PAGE); + + return 1; + + case TC_APPMSG_EXTRACTION_FAILURE: + + /* Extraction failed */ + + bInProgress = FALSE; + + NormalCursor (); + + StatusMessage (hCurPage, "EXTRACTION_FAILED"); + + UpdateProgressBarProc(0); + + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_TITLE), GetString ("EXTRACTION_FAILED")); + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_INFO), L""); + + SetWindowTextW (GetDlgItem (hwndDlg, IDCANCEL), GetString ("IDCLOSE")); + EnableWindow (GetDlgItem (hwndDlg, IDHELP), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_PREV), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), TRUE); + + RefreshUIGFX(); + + Error ("EXTRACTION_FAILED", hwndDlg); + + return 1; + + case WM_CLOSE: + + if (!bDevm) + { + if (bInProgress) + { + NormalCursor(); + if (AskNoYes("CONFIRM_EXIT_UNIVERSAL", hwndDlg) == IDNO) + { + return 1; + } + WaitCursor (); + } + + if (bOpenContainingFolder && bExtractOnly && bExtractionSuccessful) + { + ShellExecute (NULL, L"open", WizardDestExtractPath, NULL, NULL, SW_SHOWNORMAL); + } + else + { + if (bPromptReleaseNotes + && AskYesNo ("AFTER_UPGRADE_RELEASE_NOTES", hwndDlg) == IDYES) + { + Applink ("releasenotes", TRUE, ""); + } + + bPromptReleaseNotes = FALSE; + + if (bPromptTutorial + && AskYesNo ("AFTER_INSTALL_TUTORIAL", hwndDlg) == IDYES) + { + Applink ("beginnerstutorial", TRUE, ""); + } + + bPromptTutorial = FALSE; + } + + if (bRestartRequired + && AskYesNo (bUpgrade ? "UPGRADE_OK_REBOOT_REQUIRED" : "CONFIRM_RESTART", hwndDlg) == IDYES) + { + RestartComputer(); + } + } + + EndDialog (hwndDlg, IDCANCEL); + return 1; + } + + return 0; +} + + diff --git a/src/Setup/Wizard.h b/src/Setup/Wizard.h index fefc297f..3d178e24 100644 --- a/src/Setup/Wizard.h +++ b/src/Setup/Wizard.h @@ -1,31 +1,31 @@ -/* - Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is - governed by the TrueCrypt License 3.0, also from the source code of - Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - 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. */ - -#ifdef __cplusplus -extern "C" { -#endif - -void InitProgressBar (void); -BOOL UpdateProgressBarProc (int nPercent); -void RefreshUIGFX (void); -void localcleanupwiz (void); - -BOOL CALLBACK PageDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); -BOOL CALLBACK MainDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); - -extern BOOL bPromptTutorial; -extern BOOL bPromptReleaseNotes; - -#ifdef __cplusplus -} -#endif +/* + Legal Notice: Some portions of the source code contained in this file were + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + governed by the TrueCrypt License 3.0, also from the source code of + Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux + and which is governed by the 'License Agreement for Encryption for the Masses' + 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. */ + +#ifdef __cplusplus +extern "C" { +#endif + +void InitProgressBar (void); +BOOL UpdateProgressBarProc (int nPercent); +void RefreshUIGFX (void); +void localcleanupwiz (void); + +BOOL CALLBACK PageDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); +BOOL CALLBACK MainDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); + +extern BOOL bPromptTutorial; +extern BOOL bPromptReleaseNotes; + +#ifdef __cplusplus +} +#endif diff --git a/src/Signing/GlobalSign_R1Cross.cer b/src/Signing/GlobalSign_R1Cross.cer index 9274e71e..d90a4800 100644 --- a/src/Signing/GlobalSign_R1Cross.cer +++ b/src/Signing/GlobalSign_R1Cross.cer @@ -1,26 +1,26 @@ ------BEGIN CERTIFICATE----- -MIIEXTCCA0WgAwIBAgILBAAAAAABJQcd+a8wDQYJKoZIhvcNAQELBQAwVzELMAkG -A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv -b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0wOTExMTgxMDAw -MDBaFw0xOTAzMTgxMDAwMDBaMEwxIDAeBgNVBAsTF0dsb2JhbFNpZ24gUm9vdCBD -QSAtIFIzMRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzCV2kHkGeCIW9cCDtoTK -KJ79BXYRxa2IcvxGAkPHsoqdBF8kyy5L4WCCRuFSqwyBR3Bs3WTR6/Usow+CPQwr -rpfXthSGEHm7OxOAd4wI4UnSamIvH176lmjfiSeVOJ8G1z7JyyZZDXPesMjpJg6D -FcbvW4vSBGDKSaYo9mk79svIKJHlnYphVzesdBTcdOA67nIvLpz70Lu/9T0A4QYz -6IIrrlOmOhZzjN1BDiA6wLSnoemyT5AuMmDpV8u5BJJoaOU4JmB1sp93/5EU764g -SfytQBVI0QIxYRleuJfvrXe3ZJp6v1/BE++bYvsNbOBUaRapA9pu6YOTcXbGaYWC -FwIDAQABo4IBMzCCAS8wDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8w -HQYDVR0OBBYEFI/wS3+oLkUkrk1Q+mOai97i3Ru8MEYGA1UdIAQ/MD0wOwYEVR0g -ADAzMDEGCCsGAQUFBwIBFiVodHRwOi8vd3d3Lmdsb2JhbHNpZ24ubmV0L3JlcG9z -aXRvcnkvMDMGA1UdHwQsMCowKKAmoCSGImh0dHA6Ly9jcmwuZ2xvYmFsc2lnbi5u -ZXQvcm9vdC5jcmwwTwYIKwYBBQUHAQEEQzBBMD8GCCsGAQUFBzABhjNodHRwOi8v -b2NzcC5nbG9iYWxzaWduLmNvbS9FeHRlbmRlZFNTTFNIQTI1NkNBQ3Jvc3MwHwYD -VR0jBBgwFoAUYHtmGkUNl8qJUC99BM00qP/8/UswDQYJKoZIhvcNAQELBQADggEB -AEJSqX6iz1s7y0vduvhXWdMkpHdy72JEN4LtBu4E1RZfJKMU3GxUBWqwmz3agTna -rSjblW+Bg/XNYrFFJLHdKeUIVJWVjPAdBl8a1kY/E0AXSBEWm0dN0Tq1D1cckjDQ -+LIlOwrN9of5x7JX0z99pYwUzpyox59Gk9pZ+nldZSA1RFpPwZCdwVSSVtw0yPXB -A9BdwFlInAD8laDx0Xb3FjbIE5J/LSvAuIDxJiYfQU1Svx6XuwGCCOcV9sHVNCrM -9eTDh3pXgeHW10KGYgF34qnEeob0BDh6B2p9AOxz96gLNHjFnrPvuDhADowzU8h1 -7F8+6nVe/4IOdBXcGQXzujE= ------END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIEXTCCA0WgAwIBAgILBAAAAAABJQcd+a8wDQYJKoZIhvcNAQELBQAwVzELMAkG +A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv +b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0wOTExMTgxMDAw +MDBaFw0xOTAzMTgxMDAwMDBaMEwxIDAeBgNVBAsTF0dsb2JhbFNpZ24gUm9vdCBD +QSAtIFIzMRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzCV2kHkGeCIW9cCDtoTK +KJ79BXYRxa2IcvxGAkPHsoqdBF8kyy5L4WCCRuFSqwyBR3Bs3WTR6/Usow+CPQwr +rpfXthSGEHm7OxOAd4wI4UnSamIvH176lmjfiSeVOJ8G1z7JyyZZDXPesMjpJg6D +FcbvW4vSBGDKSaYo9mk79svIKJHlnYphVzesdBTcdOA67nIvLpz70Lu/9T0A4QYz +6IIrrlOmOhZzjN1BDiA6wLSnoemyT5AuMmDpV8u5BJJoaOU4JmB1sp93/5EU764g +SfytQBVI0QIxYRleuJfvrXe3ZJp6v1/BE++bYvsNbOBUaRapA9pu6YOTcXbGaYWC +FwIDAQABo4IBMzCCAS8wDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8w +HQYDVR0OBBYEFI/wS3+oLkUkrk1Q+mOai97i3Ru8MEYGA1UdIAQ/MD0wOwYEVR0g +ADAzMDEGCCsGAQUFBwIBFiVodHRwOi8vd3d3Lmdsb2JhbHNpZ24ubmV0L3JlcG9z +aXRvcnkvMDMGA1UdHwQsMCowKKAmoCSGImh0dHA6Ly9jcmwuZ2xvYmFsc2lnbi5u +ZXQvcm9vdC5jcmwwTwYIKwYBBQUHAQEEQzBBMD8GCCsGAQUFBzABhjNodHRwOi8v +b2NzcC5nbG9iYWxzaWduLmNvbS9FeHRlbmRlZFNTTFNIQTI1NkNBQ3Jvc3MwHwYD +VR0jBBgwFoAUYHtmGkUNl8qJUC99BM00qP/8/UswDQYJKoZIhvcNAQELBQADggEB +AEJSqX6iz1s7y0vduvhXWdMkpHdy72JEN4LtBu4E1RZfJKMU3GxUBWqwmz3agTna +rSjblW+Bg/XNYrFFJLHdKeUIVJWVjPAdBl8a1kY/E0AXSBEWm0dN0Tq1D1cckjDQ ++LIlOwrN9of5x7JX0z99pYwUzpyox59Gk9pZ+nldZSA1RFpPwZCdwVSSVtw0yPXB +A9BdwFlInAD8laDx0Xb3FjbIE5J/LSvAuIDxJiYfQU1Svx6XuwGCCOcV9sHVNCrM +9eTDh3pXgeHW10KGYgF34qnEeob0BDh6B2p9AOxz96gLNHjFnrPvuDhADowzU8h1 +7F8+6nVe/4IOdBXcGQXzujE= +-----END CERTIFICATE----- diff --git a/src/Signing/GlobalSign_Root_CA_MS_Cross_Cert.crt b/src/Signing/GlobalSign_Root_CA_MS_Cross_Cert.crt index 32c4b620..c66b91d2 100644 --- a/src/Signing/GlobalSign_Root_CA_MS_Cross_Cert.crt +++ b/src/Signing/GlobalSign_Root_CA_MS_Cross_Cert.crt @@ -1,30 +1,30 @@ ------BEGIN CERTIFICATE----- -MIIFJjCCAw6gAwIBAgIKYSkVJwAAAAAAKjANBgkqhkiG9w0BAQUFADB/MQswCQYD -VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe -MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSkwJwYDVQQDEyBNaWNyb3Nv -ZnQgQ29kZSBWZXJpZmljYXRpb24gUm9vdDAeFw0xMTA0MTUxOTU1MDhaFw0yMTA0 -MTUyMDA1MDhaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52 -LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxTaWduIFJvb3Qg -Q0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZjc6j40+Kfvvx -i4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6scTHAH -oT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4 -bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVt -bNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlw -R5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N89iFo7+ryUp9/ -k5DPAgMBAAGjgcswgcgwEQYDVR0gBAowCDAGBgRVHSAAMAsGA1UdDwQEAwIBhjAP -BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzAf -BgNVHSMEGDAWgBRi+wohW39DbhHaCVRQa/XSlnHxnjBVBgNVHR8ETjBMMEqgSKBG -hkRodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0cy9NaWNy -b3NvZnRDb2RlVmVyaWZSb290LmNybDANBgkqhkiG9w0BAQUFAAOCAgEAX/jQZXRq -gcamylsDtpFK6Eu97yuhQvDvtKWtzTOJ7AuVhaxiUBEIqljSWqCDEOWmM3ryWvLF -/nh88JyD3xkK2XOWAC3WLM3pFNQdneg/PBp295BO+wE1CmyTE6DDVutnoOTRepbe -wmfxkPgKe/UyG5TsX3UfjRs02mxYp8stJ54iJrfJqjDMB3e4NuOCAbU5PMyN2adf -fyOzh3/bV5iRi9fOJSDjnWRP3Yf3K2hJAxjgpd98X2hkTTaDjUeB8ungqGmr+nsW -PAWkSeqIMBkKbHMFUXjf1B3dOtR/LeROVL6DQx56dDO0pOvXcHO8KgKYiWbu9ryP -dJN44ykCWlpD4ljOfM+aytI2iTviX9omBU7I1OcskQ4Xl8W+7osTESMjKU/6g9BQ -9rr61T2zFz30/wNKoyXc5nVh0fo1CGvWJ0TQaLeNReDrhSzIoV1hRHQWDllYrtK1 -7qW81tcHarYpeP2XZ2fdjU8XlE/S7QyvlyQ3w6Kcgdpr4UO2V3tM7L95Exnnn+hE -6UeBt15wHpH4PdF7J/ULcFZDSAXdqS+rhhAdCxLjGtBMbnXe1kWzC3SIh5NcVkpB -Apr3rreZ2LZ/iPoR8kV89NcbkcAc8aD71AgKQRoUKs706zRIbmaHntVLejl/uw49 -OGHPc1cG5BIGa9lrUwjNcBjCLU+XRpG8qfA= ------END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIFJjCCAw6gAwIBAgIKYSkVJwAAAAAAKjANBgkqhkiG9w0BAQUFADB/MQswCQYD +VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe +MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSkwJwYDVQQDEyBNaWNyb3Nv +ZnQgQ29kZSBWZXJpZmljYXRpb24gUm9vdDAeFw0xMTA0MTUxOTU1MDhaFw0yMTA0 +MTUyMDA1MDhaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52 +LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxTaWduIFJvb3Qg +Q0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZjc6j40+Kfvvx +i4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6scTHAH +oT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4 +bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVt +bNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlw +R5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N89iFo7+ryUp9/ +k5DPAgMBAAGjgcswgcgwEQYDVR0gBAowCDAGBgRVHSAAMAsGA1UdDwQEAwIBhjAP +BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzAf +BgNVHSMEGDAWgBRi+wohW39DbhHaCVRQa/XSlnHxnjBVBgNVHR8ETjBMMEqgSKBG +hkRodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0cy9NaWNy +b3NvZnRDb2RlVmVyaWZSb290LmNybDANBgkqhkiG9w0BAQUFAAOCAgEAX/jQZXRq +gcamylsDtpFK6Eu97yuhQvDvtKWtzTOJ7AuVhaxiUBEIqljSWqCDEOWmM3ryWvLF +/nh88JyD3xkK2XOWAC3WLM3pFNQdneg/PBp295BO+wE1CmyTE6DDVutnoOTRepbe +wmfxkPgKe/UyG5TsX3UfjRs02mxYp8stJ54iJrfJqjDMB3e4NuOCAbU5PMyN2adf +fyOzh3/bV5iRi9fOJSDjnWRP3Yf3K2hJAxjgpd98X2hkTTaDjUeB8ungqGmr+nsW +PAWkSeqIMBkKbHMFUXjf1B3dOtR/LeROVL6DQx56dDO0pOvXcHO8KgKYiWbu9ryP +dJN44ykCWlpD4ljOfM+aytI2iTviX9omBU7I1OcskQ4Xl8W+7osTESMjKU/6g9BQ +9rr61T2zFz30/wNKoyXc5nVh0fo1CGvWJ0TQaLeNReDrhSzIoV1hRHQWDllYrtK1 +7qW81tcHarYpeP2XZ2fdjU8XlE/S7QyvlyQ3w6Kcgdpr4UO2V3tM7L95Exnnn+hE +6UeBt15wHpH4PdF7J/ULcFZDSAXdqS+rhhAdCxLjGtBMbnXe1kWzC3SIh5NcVkpB +Apr3rreZ2LZ/iPoR8kV89NcbkcAc8aD71AgKQRoUKs706zRIbmaHntVLejl/uw49 +OGHPc1cG5BIGa9lrUwjNcBjCLU+XRpG8qfA= +-----END CERTIFICATE----- diff --git a/src/Signing/Thawt_CodeSigning_CA.crt b/src/Signing/Thawt_CodeSigning_CA.crt index e46f7b48..8a257922 100644 --- a/src/Signing/Thawt_CodeSigning_CA.crt +++ b/src/Signing/Thawt_CodeSigning_CA.crt @@ -1,27 +1,27 @@ ------BEGIN CERTIFICATE----- -MIIEnDCCA4SgAwIBAgIQR5dNeHOlvKsNL7NwGS/OXjANBgkqhkiG9w0BAQUFADCB -qTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf -Q2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIw -MDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNV -BAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMTAwMjA4MDAwMDAwWhcNMjAw -MjA3MjM1OTU5WjBKMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMVGhhd3RlLCBJbmMu -MSQwIgYDVQQDExtUaGF3dGUgQ29kZSBTaWduaW5nIENBIC0gRzIwggEiMA0GCSqG -SIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3i891W58l2n45sJPbONOpI9CC+ukkflwL -joP45npZ5qPFmKeZ0kT/AKalOQSK2imI6tui8xyZFSbCsfT84QxHqQkRBgogkrnH -oASMXJQZq1slLB1ifnANzmFs3SuCyc5dSF/3wr68QSMeTyld10+89MUq/GPmfCZO -mad5QZ4QSnp5ycaG94aV0ibOPBgq1nzOr82tu/eCLHAmN0XlD0cixgEovS6DXGqk -R8Hn0NhrgUY/IRf1B8VDWqZnLLh7YBG1g+71dApycUQ9WP7oGqs4w1nbf244fXbH -cmmYNpZX02Yc0lSRBC5UGbDcPbUiXobVKn4g313merFl/sUCTjEtAgMBAAGjggEc -MIIBGDASBgNVHRMBAf8ECDAGAQH/AgEAMDQGA1UdHwQtMCswKaAnoCWGI2h0dHA6 -Ly9jcmwudGhhd3RlLmNvbS9UaGF3dGVQQ0EuY3JsMA4GA1UdDwEB/wQEAwIBBjAy -BggrBgEFBQcBAQQmMCQwIgYIKwYBBQUHMAGGFmh0dHA6Ly9vY3NwLnRoYXd0ZS5j -b20wHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMDMCkGA1UdEQQiMCCkHjAc -MRowGAYDVQQDExFWZXJpU2lnbk1QS0ktMi0xMDAdBgNVHQ4EFgQU1A1lP3q9NMb+ -R+dMDcC98t4Vq3EwHwYDVR0jBBgwFoAUe1tFz6/Oy3r9MZIaarbzRutXSFAwDQYJ -KoZIhvcNAQEFBQADggEBAFb+U1zhx568p+1+U21qFEtRjEBegF+qpOgv7zjIBMnK -Ps/fOlhOsNS2Y8UpV/oCBZpFTWjbKhvUND2fAMNay5VJpW7hsMX8QU1BSm/Td8jX -OI3kGd4Y8x8VZYNtRQxT+QqaLqVdv28ygRiSGWpVAK1jHFIGflXZKWiuSnwYmnmI -ayMj2Cc4KimHdsr7x7ZiIx/telZM3ZwyW/U9DEYYlTsqI2iDZEHZAG0PGSQVaHK9 -xXFnbqxM25DrUaUaYgfQvmoARzxyL+xPYT5zhc5aCre6wBwTdeMiOSjdbR0JRp1P -uuhAgZHGpM6UchsBzypuFWeVia59t7fN+Qo9dbZrPCU= +-----BEGIN CERTIFICATE----- +MIIEnDCCA4SgAwIBAgIQR5dNeHOlvKsNL7NwGS/OXjANBgkqhkiG9w0BAQUFADCB +qTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf +Q2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIw +MDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNV +BAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMTAwMjA4MDAwMDAwWhcNMjAw +MjA3MjM1OTU5WjBKMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMVGhhd3RlLCBJbmMu +MSQwIgYDVQQDExtUaGF3dGUgQ29kZSBTaWduaW5nIENBIC0gRzIwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3i891W58l2n45sJPbONOpI9CC+ukkflwL +joP45npZ5qPFmKeZ0kT/AKalOQSK2imI6tui8xyZFSbCsfT84QxHqQkRBgogkrnH +oASMXJQZq1slLB1ifnANzmFs3SuCyc5dSF/3wr68QSMeTyld10+89MUq/GPmfCZO +mad5QZ4QSnp5ycaG94aV0ibOPBgq1nzOr82tu/eCLHAmN0XlD0cixgEovS6DXGqk +R8Hn0NhrgUY/IRf1B8VDWqZnLLh7YBG1g+71dApycUQ9WP7oGqs4w1nbf244fXbH +cmmYNpZX02Yc0lSRBC5UGbDcPbUiXobVKn4g313merFl/sUCTjEtAgMBAAGjggEc +MIIBGDASBgNVHRMBAf8ECDAGAQH/AgEAMDQGA1UdHwQtMCswKaAnoCWGI2h0dHA6 +Ly9jcmwudGhhd3RlLmNvbS9UaGF3dGVQQ0EuY3JsMA4GA1UdDwEB/wQEAwIBBjAy +BggrBgEFBQcBAQQmMCQwIgYIKwYBBQUHMAGGFmh0dHA6Ly9vY3NwLnRoYXd0ZS5j +b20wHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMDMCkGA1UdEQQiMCCkHjAc +MRowGAYDVQQDExFWZXJpU2lnbk1QS0ktMi0xMDAdBgNVHQ4EFgQU1A1lP3q9NMb+ +R+dMDcC98t4Vq3EwHwYDVR0jBBgwFoAUe1tFz6/Oy3r9MZIaarbzRutXSFAwDQYJ +KoZIhvcNAQEFBQADggEBAFb+U1zhx568p+1+U21qFEtRjEBegF+qpOgv7zjIBMnK +Ps/fOlhOsNS2Y8UpV/oCBZpFTWjbKhvUND2fAMNay5VJpW7hsMX8QU1BSm/Td8jX +OI3kGd4Y8x8VZYNtRQxT+QqaLqVdv28ygRiSGWpVAK1jHFIGflXZKWiuSnwYmnmI +ayMj2Cc4KimHdsr7x7ZiIx/telZM3ZwyW/U9DEYYlTsqI2iDZEHZAG0PGSQVaHK9 +xXFnbqxM25DrUaUaYgfQvmoARzxyL+xPYT5zhc5aCre6wBwTdeMiOSjdbR0JRp1P +uuhAgZHGpM6UchsBzypuFWeVia59t7fN+Qo9dbZrPCU= -----END CERTIFICATE----- \ No newline at end of file diff --git a/src/Signing/sign.bat b/src/Signing/sign.bat index bf53325c..a163dac5 100644 --- a/src/Signing/sign.bat +++ b/src/Signing/sign.bat @@ -1,27 +1,27 @@ -PATH=%PATH%;%WSDK81%\bin\x86 - -rem sign using SHA-1 -signtool sign /v /a /n IDRIX /i Thawte /ac thawte_Primary_MS_Cross_Cert.cer /fd sha1 /t http://timestamp.verisign.com/scripts/timestamp.dll "..\Release\Setup Files\veracrypt.sys" "..\Release\Setup Files\veracrypt-x64.sys" -signtool sign /v /a /n IDRIX /i Thawte /ac Thawt_CodeSigning_CA.crt /fd sha1 /t http://timestamp.verisign.com/scripts/timestamp.dll "..\Release\Setup Files\VeraCrypt.exe" "..\Release\Setup Files\VeraCrypt Format.exe" "..\Release\Setup Files\VeraCryptExpander.exe" "..\Release\Setup Files\VeraCrypt-x64.exe" "..\Release\Setup Files\VeraCrypt Format-x64.exe" "..\Release\Setup Files\VeraCryptExpander-x64.exe" - -rem sign using SHA-256 -signtool sign /v /a /n "IDRIX SARL" /i GlobalSign /ac GlobalSign_Root_CA_MS_Cross_Cert.crt /as /fd sha256 /tr http://timestamp.globalsign.com/?signature=sha2 /td SHA256 "..\Release\Setup Files\veracrypt.sys" "..\Release\Setup Files\veracrypt-x64.sys" -signtool sign /v /a /n "IDRIX SARL" /i GlobalSign /ac GlobalSign_SHA256_EV_CodeSigning_CA.cer /as /fd sha256 /tr http://timestamp.globalsign.com/?signature=sha2 /td SHA256 "..\Release\Setup Files\VeraCrypt.exe" "..\Release\Setup Files\VeraCrypt Format.exe" "..\Release\Setup Files\VeraCryptExpander.exe" "..\Release\Setup Files\VeraCrypt-x64.exe" "..\Release\Setup Files\VeraCrypt Format-x64.exe" "..\Release\Setup Files\VeraCryptExpander-x64.exe" - - -cd "..\Release\Setup Files\" - -copy /V /Y ..\..\..\Translations\*.xml . - -"VeraCrypt Setup.exe" /p - -del *.xml - -cd "..\..\Signing" - -rem sign using SHA-1 -signtool sign /v /a /n IDRIX /i Thawte /ac Thawt_CodeSigning_CA.crt /fd sha1 /t http://timestamp.verisign.com/scripts/timestamp.dll "..\Release\Setup Files\VeraCrypt Setup 1.17.exe" -rem sign using SHA-256 -signtool sign /v /a /n "IDRIX SARL" /i GlobalSign /ac GlobalSign_SHA256_EV_CodeSigning_CA.cer /as /fd sha256 /tr http://timestamp.globalsign.com/?signature=sha2 /td SHA256 "..\Release\Setup Files\VeraCrypt Setup 1.17.exe" - -pause +PATH=%PATH%;%WSDK81%\bin\x86 + +rem sign using SHA-1 +signtool sign /v /a /n IDRIX /i Thawte /ac thawte_Primary_MS_Cross_Cert.cer /fd sha1 /t http://timestamp.verisign.com/scripts/timestamp.dll "..\Release\Setup Files\veracrypt.sys" "..\Release\Setup Files\veracrypt-x64.sys" +signtool sign /v /a /n IDRIX /i Thawte /ac Thawt_CodeSigning_CA.crt /fd sha1 /t http://timestamp.verisign.com/scripts/timestamp.dll "..\Release\Setup Files\VeraCrypt.exe" "..\Release\Setup Files\VeraCrypt Format.exe" "..\Release\Setup Files\VeraCryptExpander.exe" "..\Release\Setup Files\VeraCrypt-x64.exe" "..\Release\Setup Files\VeraCrypt Format-x64.exe" "..\Release\Setup Files\VeraCryptExpander-x64.exe" + +rem sign using SHA-256 +signtool sign /v /a /n "IDRIX SARL" /i GlobalSign /ac GlobalSign_Root_CA_MS_Cross_Cert.crt /as /fd sha256 /tr http://timestamp.globalsign.com/?signature=sha2 /td SHA256 "..\Release\Setup Files\veracrypt.sys" "..\Release\Setup Files\veracrypt-x64.sys" +signtool sign /v /a /n "IDRIX SARL" /i GlobalSign /ac GlobalSign_SHA256_EV_CodeSigning_CA.cer /as /fd sha256 /tr http://timestamp.globalsign.com/?signature=sha2 /td SHA256 "..\Release\Setup Files\VeraCrypt.exe" "..\Release\Setup Files\VeraCrypt Format.exe" "..\Release\Setup Files\VeraCryptExpander.exe" "..\Release\Setup Files\VeraCrypt-x64.exe" "..\Release\Setup Files\VeraCrypt Format-x64.exe" "..\Release\Setup Files\VeraCryptExpander-x64.exe" + + +cd "..\Release\Setup Files\" + +copy /V /Y ..\..\..\Translations\*.xml . + +"VeraCrypt Setup.exe" /p + +del *.xml + +cd "..\..\Signing" + +rem sign using SHA-1 +signtool sign /v /a /n IDRIX /i Thawte /ac Thawt_CodeSigning_CA.crt /fd sha1 /t http://timestamp.verisign.com/scripts/timestamp.dll "..\Release\Setup Files\VeraCrypt Setup 1.17.exe" +rem sign using SHA-256 +signtool sign /v /a /n "IDRIX SARL" /i GlobalSign /ac GlobalSign_SHA256_EV_CodeSigning_CA.cer /as /fd sha256 /tr http://timestamp.globalsign.com/?signature=sha2 /td SHA256 "..\Release\Setup Files\VeraCrypt Setup 1.17.exe" + +pause diff --git a/src/Signing/sign_test.bat b/src/Signing/sign_test.bat index 1cfe94aa..eb9c492a 100644 --- a/src/Signing/sign_test.bat +++ b/src/Signing/sign_test.bat @@ -1,32 +1,32 @@ -PATH=%PATH%;%WSDK81%\bin\x86 - -set PFXNAME=TestCertificate\idrix_codeSign.pfx -set PFXPASSWORD=idrix -set PFXCA=TestCertificate\idrix_TestRootCA.crt -set SHA256PFXNAME=TestCertificate\idrix_Sha256CodeSign.pfx -set SHA256PFXPASSWORD=idrix -set SHA256PFXCA=TestCertificate\idrix_SHA256TestRootCA.crt - -rem sign using SHA-1 -signtool sign /v /a /f %PFXNAME% /p %PFXPASSWORD% /ac %PFXCA% /fd sha1 /t http://timestamp.verisign.com/scripts/timestamp.dll "..\Release\Setup Files\veracrypt.sys" "..\Release\Setup Files\veracrypt-x64.sys" "..\Release\Setup Files\VeraCrypt.exe" "..\Release\Setup Files\VeraCrypt Format.exe" "..\Release\Setup Files\VeraCryptExpander.exe" "..\Release\Setup Files\VeraCrypt-x64.exe" "..\Release\Setup Files\VeraCrypt Format-x64.exe" "..\Release\Setup Files\VeraCryptExpander-x64.exe" - -rem sign using SHA-256 -signtool sign /v /a /f %SHA256PFXNAME% /p %SHA256PFXPASSWORD% /ac %SHA256PFXCA% /as /fd sha256 /tr http://timestamp.globalsign.com/?signature=sha2 /td SHA256 "..\Release\Setup Files\veracrypt.sys" "..\Release\Setup Files\veracrypt-x64.sys" "..\Release\Setup Files\VeraCrypt.exe" "..\Release\Setup Files\VeraCrypt Format.exe" "..\Release\Setup Files\VeraCryptExpander.exe" "..\Release\Setup Files\VeraCrypt-x64.exe" "..\Release\Setup Files\VeraCrypt Format-x64.exe" "..\Release\Setup Files\VeraCryptExpander-x64.exe" - -cd "..\Release\Setup Files\" - -copy /V /Y ..\..\..\Translations\*.xml . - -"VeraCrypt Setup.exe" /p - -del *.xml - -cd "..\..\Signing" - -rem sign using SHA-1 -signtool sign /v /a /f %PFXNAME% /p %PFXPASSWORD% /ac %PFXCA% /fd sha1 /t http://timestamp.verisign.com/scripts/timestamp.dll "..\Release\Setup Files\VeraCrypt Setup 1.17.exe" - -rem sign using SHA-256 -signtool sign /v /a /f %SHA256PFXNAME% /p %SHA256PFXPASSWORD% /ac %SHA256PFXCA% /as /fd sha256 /tr http://timestamp.globalsign.com/?signature=sha2 /td SHA256 "..\Release\Setup Files\VeraCrypt Setup 1.17.exe" - +PATH=%PATH%;%WSDK81%\bin\x86 + +set PFXNAME=TestCertificate\idrix_codeSign.pfx +set PFXPASSWORD=idrix +set PFXCA=TestCertificate\idrix_TestRootCA.crt +set SHA256PFXNAME=TestCertificate\idrix_Sha256CodeSign.pfx +set SHA256PFXPASSWORD=idrix +set SHA256PFXCA=TestCertificate\idrix_SHA256TestRootCA.crt + +rem sign using SHA-1 +signtool sign /v /a /f %PFXNAME% /p %PFXPASSWORD% /ac %PFXCA% /fd sha1 /t http://timestamp.verisign.com/scripts/timestamp.dll "..\Release\Setup Files\veracrypt.sys" "..\Release\Setup Files\veracrypt-x64.sys" "..\Release\Setup Files\VeraCrypt.exe" "..\Release\Setup Files\VeraCrypt Format.exe" "..\Release\Setup Files\VeraCryptExpander.exe" "..\Release\Setup Files\VeraCrypt-x64.exe" "..\Release\Setup Files\VeraCrypt Format-x64.exe" "..\Release\Setup Files\VeraCryptExpander-x64.exe" + +rem sign using SHA-256 +signtool sign /v /a /f %SHA256PFXNAME% /p %SHA256PFXPASSWORD% /ac %SHA256PFXCA% /as /fd sha256 /tr http://timestamp.globalsign.com/?signature=sha2 /td SHA256 "..\Release\Setup Files\veracrypt.sys" "..\Release\Setup Files\veracrypt-x64.sys" "..\Release\Setup Files\VeraCrypt.exe" "..\Release\Setup Files\VeraCrypt Format.exe" "..\Release\Setup Files\VeraCryptExpander.exe" "..\Release\Setup Files\VeraCrypt-x64.exe" "..\Release\Setup Files\VeraCrypt Format-x64.exe" "..\Release\Setup Files\VeraCryptExpander-x64.exe" + +cd "..\Release\Setup Files\" + +copy /V /Y ..\..\..\Translations\*.xml . + +"VeraCrypt Setup.exe" /p + +del *.xml + +cd "..\..\Signing" + +rem sign using SHA-1 +signtool sign /v /a /f %PFXNAME% /p %PFXPASSWORD% /ac %PFXCA% /fd sha1 /t http://timestamp.verisign.com/scripts/timestamp.dll "..\Release\Setup Files\VeraCrypt Setup 1.17.exe" + +rem sign using SHA-256 +signtool sign /v /a /f %SHA256PFXNAME% /p %SHA256PFXPASSWORD% /ac %SHA256PFXCA% /as /fd sha256 /tr http://timestamp.globalsign.com/?signature=sha2 /td SHA256 "..\Release\Setup Files\VeraCrypt Setup 1.17.exe" + pause \ No newline at end of file diff --git a/src/Signing/thawte_Primary_MS_Cross_Cert.cer b/src/Signing/thawte_Primary_MS_Cross_Cert.cer index d5e09da0..4389935b 100644 --- a/src/Signing/thawte_Primary_MS_Cross_Cert.cer +++ b/src/Signing/thawte_Primary_MS_Cross_Cert.cer @@ -1,32 +1,32 @@ ------BEGIN CERTIFICATE----- -MIIFeTCCA2GgAwIBAgIKYR+wpAAAAAAAHTANBgkqhkiG9w0BAQUFADB/MQswCQYD -VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe -MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSkwJwYDVQQDEyBNaWNyb3Nv -ZnQgQ29kZSBWZXJpZmljYXRpb24gUm9vdDAeFw0xMTAyMjIxOTMxNTdaFw0yMTAy -MjIxOTQxNTdaMIGpMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhhd3RlLCBJbmMu -MSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9uMTgwNgYD -VQQLEy8oYykgMjAwNiB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ug -b25seTEfMB0GA1UEAxMWdGhhd3RlIFByaW1hcnkgUm9vdCBDQTCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAKyg8PuAWdScx6TPnaFZcwkQRQwNLG5o8Wxb -SGhJWTf8CzMZwnd/zBAtlTQc5utNCacc0rjJlzYCt4nUJF8GwMxElJSNAmJv61rd -EY0omlyEkBB6Db10Zi9qOKDi1VRE6x0Hnwe6b+7p/U4LKfU+hKAB8Zyr+Bx+iaTo -odhxZQ2jUXvuvNIiYA25W53fuvxRWwuvmLLpLukE6GKH3ivI107BTGQe3c+HWLpK -T8poBx0cnUrG1S+RzHxxchzFwGfrMv3JklyU2oXAm79TfSsJ9IydkR+XalLL3gk2 -pHfYe4dQRNU+bilp+zlJJh4JpYB7QC3r6CeFyf5h/X7mfJcd1Z0CAwEAAaOByzCB -yDARBgNVHSAECjAIMAYGBFUdIAAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMC -AYYwHQYDVR0OBBYEFHtbRc+vzst6/TGSGmq280brV0hQMB8GA1UdIwQYMBaAFGL7 -CiFbf0NuEdoJVFBr9dKWcfGeMFUGA1UdHwROMEwwSqBIoEaGRGh0dHA6Ly9jcmwu -bWljcm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1Y3RzL01pY3Jvc29mdENvZGVWZXJp -ZlJvb3QuY3JsMA0GCSqGSIb3DQEBBQUAA4ICAQAtzHG16LqU/17mRGcAe2r8QSw+ -5w5BhVqxKpMrqVuJ8vcrSZyAA/KXuOdgqA7X/V3lRUZ1lPTtHJ3hZiKLYfsp8sao -vfOHyY9/R+HAWLZKGqLn9xhgaWnggwaeJsd1xAwNedp0a1K5+ujqM1m5uxjdKRoU -39NqNyd6naDaz//8IsT68An/M+k+F7ocx0LPzidD0wwMVYEwPblgYM4C7OGe6B3c -hSzgoY2WbZWsF6RxPqFnQbYoHSzjthXlt+Wi9iVthuMgrPn4MU+OYpuYMzdtavc1 -Uj6Q/rA7X8W4UqngbqBHmieel66iSp5TGTnsNX7GWd464Kr1M/BqvaCCGBLeoYxF -cMor1i6VkUWZWlwkAEm9I7MM7KQ99bnh0bGCWjjuo/uhq0g6jF3/oGUiP9PT/kmQ -2xRGo4UuilVLCas4sqtjoAjR/a1I4nPYErzCbKUW+tCawF44ODorcY5VOqxCGXof -DUIg56tdjGiAUkyhwNSI0CMh+5ATCQB7STevqd9IYCKr9PbCNjv4UTw0u8WG5Drh -n0uQ/lRhAksVnDQXaqlLjUy2nSMmyDrx1rgFzdodYkAYOi8bQc06mToKqdHXfrjE -r/e4yYAQXtVd9s56mgLFD2OB77Vk6fxb2NJhmmjDfPnHjfkeh9X6LPgWrp2rBo/I -bcdBzaFOhOPawm68+w== ------END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIFeTCCA2GgAwIBAgIKYR+wpAAAAAAAHTANBgkqhkiG9w0BAQUFADB/MQswCQYD +VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe +MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSkwJwYDVQQDEyBNaWNyb3Nv +ZnQgQ29kZSBWZXJpZmljYXRpb24gUm9vdDAeFw0xMTAyMjIxOTMxNTdaFw0yMTAy +MjIxOTQxNTdaMIGpMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhhd3RlLCBJbmMu +MSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9uMTgwNgYD +VQQLEy8oYykgMjAwNiB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ug +b25seTEfMB0GA1UEAxMWdGhhd3RlIFByaW1hcnkgUm9vdCBDQTCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAKyg8PuAWdScx6TPnaFZcwkQRQwNLG5o8Wxb +SGhJWTf8CzMZwnd/zBAtlTQc5utNCacc0rjJlzYCt4nUJF8GwMxElJSNAmJv61rd +EY0omlyEkBB6Db10Zi9qOKDi1VRE6x0Hnwe6b+7p/U4LKfU+hKAB8Zyr+Bx+iaTo +odhxZQ2jUXvuvNIiYA25W53fuvxRWwuvmLLpLukE6GKH3ivI107BTGQe3c+HWLpK +T8poBx0cnUrG1S+RzHxxchzFwGfrMv3JklyU2oXAm79TfSsJ9IydkR+XalLL3gk2 +pHfYe4dQRNU+bilp+zlJJh4JpYB7QC3r6CeFyf5h/X7mfJcd1Z0CAwEAAaOByzCB +yDARBgNVHSAECjAIMAYGBFUdIAAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMC +AYYwHQYDVR0OBBYEFHtbRc+vzst6/TGSGmq280brV0hQMB8GA1UdIwQYMBaAFGL7 +CiFbf0NuEdoJVFBr9dKWcfGeMFUGA1UdHwROMEwwSqBIoEaGRGh0dHA6Ly9jcmwu +bWljcm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1Y3RzL01pY3Jvc29mdENvZGVWZXJp +ZlJvb3QuY3JsMA0GCSqGSIb3DQEBBQUAA4ICAQAtzHG16LqU/17mRGcAe2r8QSw+ +5w5BhVqxKpMrqVuJ8vcrSZyAA/KXuOdgqA7X/V3lRUZ1lPTtHJ3hZiKLYfsp8sao +vfOHyY9/R+HAWLZKGqLn9xhgaWnggwaeJsd1xAwNedp0a1K5+ujqM1m5uxjdKRoU +39NqNyd6naDaz//8IsT68An/M+k+F7ocx0LPzidD0wwMVYEwPblgYM4C7OGe6B3c +hSzgoY2WbZWsF6RxPqFnQbYoHSzjthXlt+Wi9iVthuMgrPn4MU+OYpuYMzdtavc1 +Uj6Q/rA7X8W4UqngbqBHmieel66iSp5TGTnsNX7GWd464Kr1M/BqvaCCGBLeoYxF +cMor1i6VkUWZWlwkAEm9I7MM7KQ99bnh0bGCWjjuo/uhq0g6jF3/oGUiP9PT/kmQ +2xRGo4UuilVLCas4sqtjoAjR/a1I4nPYErzCbKUW+tCawF44ODorcY5VOqxCGXof +DUIg56tdjGiAUkyhwNSI0CMh+5ATCQB7STevqd9IYCKr9PbCNjv4UTw0u8WG5Drh +n0uQ/lRhAksVnDQXaqlLjUy2nSMmyDrx1rgFzdodYkAYOi8bQc06mToKqdHXfrjE +r/e4yYAQXtVd9s56mgLFD2OB77Vk6fxb2NJhmmjDfPnHjfkeh9X6LPgWrp2rBo/I +bcdBzaFOhOPawm68+w== +-----END CERTIFICATE----- diff --git a/src/VeraCrypt.sln b/src/VeraCrypt.sln index c4caa8ab..c5b77d86 100644 --- a/src/VeraCrypt.sln +++ b/src/VeraCrypt.sln @@ -1,474 +1,474 @@ -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Crypto", "Crypto\Crypto.vcproj", "{993245CF-6B70-47EE-91BB-39F8FC6DC0E7}" - ProjectSection(ProjectDependencies) = postProject - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} = {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Driver", "Driver\Driver.vcproj", "{EF5EF444-18D0-40D7-8DFA-775EC4448602}" - ProjectSection(ProjectDependencies) = postProject - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} = {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Format", "Format\Format.vcproj", "{9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}" - ProjectSection(ProjectDependencies) = postProject - {EF5EF444-18D0-40D7-8DFA-775EC4448602} = {EF5EF444-18D0-40D7-8DFA-775EC4448602} - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} = {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7} = {993245CF-6B70-47EE-91BB-39F8FC6DC0E7} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Mount", "Mount\Mount.vcproj", "{E4C40F94-E7F9-4981-86E4-186B46F993F3}" - ProjectSection(ProjectDependencies) = postProject - {EF5EF444-18D0-40D7-8DFA-775EC4448602} = {EF5EF444-18D0-40D7-8DFA-775EC4448602} - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} = {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7} = {993245CF-6B70-47EE-91BB-39F8FC6DC0E7} - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF} = {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Setup", "Setup\Setup.vcproj", "{DF5F654D-BD44-4E31-B92E-B68074DC37A8}" - ProjectSection(ProjectDependencies) = postProject - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827} = {9715FF1D-599B-4BBC-AD96-BEF6E08FF827} - {E4C40F94-E7F9-4981-86E4-186B46F993F3} = {E4C40F94-E7F9-4981-86E4-186B46F993F3} - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} = {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF} = {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Boot", "Boot\Windows\Boot.vcproj", "{8B7F059F-E4C7-4E11-88F5-EE8B8433072E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ExpandVolume", "ExpandVolume\ExpandVolume.vcproj", "{9715FF1D-599B-4BBC-AD96-BEF6E08FF827}" - ProjectSection(ProjectDependencies) = postProject - {EF5EF444-18D0-40D7-8DFA-775EC4448602} = {EF5EF444-18D0-40D7-8DFA-775EC4448602} - {E4C40F94-E7F9-4981-86E4-186B46F993F3} = {E4C40F94-E7F9-4981-86E4-186B46F993F3} - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} = {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF} = {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - All Debug|Win32 = All Debug|Win32 - All Debug|x64 = All Debug|x64 - All|Win32 = All|Win32 - All|x64 = All|x64 - Boot Loader|Win32 = Boot Loader|Win32 - Boot Loader|x64 = Boot Loader|x64 - Boot|Win32 = Boot|Win32 - Boot|x64 = Boot|x64 - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Driver Debug|Win32 = Driver Debug|Win32 - Driver Debug|x64 = Driver Debug|x64 - Driver x64 Debug|Win32 = Driver x64 Debug|Win32 - Driver x64 Debug|x64 = Driver x64 Debug|x64 - Driver x64|Win32 = Driver x64|Win32 - Driver x64|x64 = Driver x64|x64 - Driver x86 Debug|Win32 = Driver x86 Debug|Win32 - Driver x86 Debug|x64 = Driver x86 Debug|x64 - Driver x86|Win32 = Driver x86|Win32 - Driver x86|x64 = Driver x86|x64 - Driver|Win32 = Driver|Win32 - Driver|x64 = Driver|x64 - Format Debug|Win32 = Format Debug|Win32 - Format Debug|x64 = Format Debug|x64 - Format|Win32 = Format|Win32 - Format|x64 = Format|x64 - Mount Debug|Win32 = Mount Debug|Win32 - Mount Debug|x64 = Mount Debug|x64 - Mount|Win32 = Mount|Win32 - Mount|x64 = Mount|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - Setup Debug|Win32 = Setup Debug|Win32 - Setup Debug|x64 = Setup Debug|x64 - Setup|Win32 = Setup|Win32 - Setup|x64 = Setup|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All Debug|Win32.ActiveCfg = Debug|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All Debug|Win32.Build.0 = Debug|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All Debug|x64.ActiveCfg = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All Debug|x64.Build.0 = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All|Win32.ActiveCfg = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All|Win32.Build.0 = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All|x64.ActiveCfg = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All|x64.Build.0 = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Boot Loader|Win32.ActiveCfg = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Boot Loader|x64.ActiveCfg = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Boot Loader|x64.Build.0 = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Boot|Win32.ActiveCfg = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Boot|x64.ActiveCfg = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Boot|x64.Build.0 = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Debug|Win32.ActiveCfg = Debug|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Debug|Win32.Build.0 = Debug|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Debug|x64.ActiveCfg = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Debug|x64.Build.0 = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver Debug|Win32.ActiveCfg = Debug|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver Debug|x64.ActiveCfg = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver Debug|x64.Build.0 = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x64 Debug|Win32.ActiveCfg = Debug|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x64 Debug|x64.ActiveCfg = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x64 Debug|x64.Build.0 = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x64|Win32.ActiveCfg = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x64|x64.ActiveCfg = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x64|x64.Build.0 = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x86 Debug|Win32.ActiveCfg = Debug|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x86 Debug|x64.ActiveCfg = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x86 Debug|x64.Build.0 = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x86|Win32.ActiveCfg = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x86|x64.ActiveCfg = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x86|x64.Build.0 = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver|Win32.ActiveCfg = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver|x64.ActiveCfg = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver|x64.Build.0 = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format Debug|Win32.ActiveCfg = Debug|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format Debug|Win32.Build.0 = Debug|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format Debug|x64.ActiveCfg = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format Debug|x64.Build.0 = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format|Win32.ActiveCfg = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format|Win32.Build.0 = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format|x64.ActiveCfg = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format|x64.Build.0 = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount Debug|Win32.ActiveCfg = Debug|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount Debug|Win32.Build.0 = Debug|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount Debug|x64.ActiveCfg = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount Debug|x64.Build.0 = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount|Win32.ActiveCfg = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount|Win32.Build.0 = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount|x64.ActiveCfg = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount|x64.Build.0 = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Release|Win32.ActiveCfg = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Release|Win32.Build.0 = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Release|x64.ActiveCfg = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Release|x64.Build.0 = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Setup Debug|Win32.ActiveCfg = Debug|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Setup Debug|x64.ActiveCfg = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Setup Debug|x64.Build.0 = Debug|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Setup|Win32.ActiveCfg = Release|Win32 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Setup|x64.ActiveCfg = Release|x64 - {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Setup|x64.Build.0 = Release|x64 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.All Debug|Win32.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.All Debug|Win32.Build.0 = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.All Debug|x64.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.All|Win32.ActiveCfg = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.All|Win32.Build.0 = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.All|x64.ActiveCfg = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Boot Loader|Win32.ActiveCfg = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Boot Loader|x64.ActiveCfg = Debug x64|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Boot|Win32.ActiveCfg = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Boot|x64.ActiveCfg = Debug x64|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Debug|Win32.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Debug|Win32.Build.0 = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Debug|x64.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver Debug|Win32.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver Debug|Win32.Build.0 = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver Debug|x64.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x64 Debug|Win32.ActiveCfg = Debug x64|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x64 Debug|Win32.Build.0 = Debug x64|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x64 Debug|x64.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x64|Win32.ActiveCfg = Release x64|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x64|Win32.Build.0 = Release x64|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x64|x64.ActiveCfg = Debug x64|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x86 Debug|Win32.ActiveCfg = Debug x86|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x86 Debug|Win32.Build.0 = Debug x86|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x86 Debug|x64.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x86|Win32.ActiveCfg = Release x86|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x86|Win32.Build.0 = Release x86|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x86|x64.ActiveCfg = Debug x64|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver|Win32.ActiveCfg = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver|Win32.Build.0 = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver|x64.ActiveCfg = Debug x64|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Format Debug|Win32.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Format Debug|x64.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Format|Win32.ActiveCfg = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Format|x64.ActiveCfg = Debug x64|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Mount Debug|Win32.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Mount Debug|x64.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Mount|Win32.ActiveCfg = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Mount|x64.ActiveCfg = Debug x64|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Release|Win32.ActiveCfg = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Release|Win32.Build.0 = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Release|x64.ActiveCfg = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Setup Debug|Win32.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Setup Debug|x64.ActiveCfg = Debug|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Setup|Win32.ActiveCfg = Release|Win32 - {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Setup|x64.ActiveCfg = Debug x64|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All Debug|Win32.ActiveCfg = Debug|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All Debug|Win32.Build.0 = Debug|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All Debug|x64.ActiveCfg = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All Debug|x64.Build.0 = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All|Win32.ActiveCfg = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All|Win32.Build.0 = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All|x64.ActiveCfg = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All|x64.Build.0 = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Boot Loader|Win32.ActiveCfg = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Boot Loader|x64.ActiveCfg = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Boot Loader|x64.Build.0 = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Boot|Win32.ActiveCfg = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Boot|x64.ActiveCfg = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Boot|x64.Build.0 = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Debug|Win32.ActiveCfg = Debug|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Debug|Win32.Build.0 = Debug|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Debug|x64.ActiveCfg = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Debug|x64.Build.0 = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver Debug|Win32.ActiveCfg = Debug|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver Debug|x64.ActiveCfg = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver Debug|x64.Build.0 = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x64 Debug|Win32.ActiveCfg = Debug|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x64 Debug|x64.ActiveCfg = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x64 Debug|x64.Build.0 = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x64|Win32.ActiveCfg = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x64|x64.ActiveCfg = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x64|x64.Build.0 = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x86 Debug|Win32.ActiveCfg = Debug|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x86 Debug|x64.ActiveCfg = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x86 Debug|x64.Build.0 = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x86|Win32.ActiveCfg = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x86|x64.ActiveCfg = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x86|x64.Build.0 = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver|Win32.ActiveCfg = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver|x64.ActiveCfg = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver|x64.Build.0 = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format Debug|Win32.ActiveCfg = Debug|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format Debug|Win32.Build.0 = Debug|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format Debug|x64.ActiveCfg = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format Debug|x64.Build.0 = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format|Win32.ActiveCfg = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format|Win32.Build.0 = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format|x64.ActiveCfg = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format|x64.Build.0 = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Mount Debug|Win32.ActiveCfg = Debug|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Mount Debug|x64.ActiveCfg = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Mount Debug|x64.Build.0 = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Mount|Win32.ActiveCfg = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Mount|x64.ActiveCfg = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Mount|x64.Build.0 = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Release|Win32.ActiveCfg = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Release|Win32.Build.0 = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Release|x64.ActiveCfg = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Release|x64.Build.0 = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Setup Debug|Win32.ActiveCfg = Debug|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Setup Debug|x64.ActiveCfg = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Setup Debug|x64.Build.0 = Debug|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Setup|Win32.ActiveCfg = Release|Win32 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Setup|x64.ActiveCfg = Release|x64 - {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Setup|x64.Build.0 = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All Debug|Win32.ActiveCfg = Debug|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All Debug|Win32.Build.0 = Debug|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All Debug|x64.ActiveCfg = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All Debug|x64.Build.0 = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All|Win32.ActiveCfg = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All|Win32.Build.0 = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All|x64.ActiveCfg = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All|x64.Build.0 = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Boot Loader|Win32.ActiveCfg = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Boot Loader|x64.ActiveCfg = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Boot Loader|x64.Build.0 = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Boot|Win32.ActiveCfg = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Boot|x64.ActiveCfg = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Boot|x64.Build.0 = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Debug|Win32.ActiveCfg = Debug|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Debug|Win32.Build.0 = Debug|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Debug|x64.ActiveCfg = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Debug|x64.Build.0 = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver Debug|Win32.ActiveCfg = Debug|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver Debug|x64.ActiveCfg = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver Debug|x64.Build.0 = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x64 Debug|Win32.ActiveCfg = Debug|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x64 Debug|x64.ActiveCfg = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x64 Debug|x64.Build.0 = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x64|Win32.ActiveCfg = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x64|x64.ActiveCfg = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x64|x64.Build.0 = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x86 Debug|Win32.ActiveCfg = Debug|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x86 Debug|x64.ActiveCfg = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x86 Debug|x64.Build.0 = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x86|Win32.ActiveCfg = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x86|x64.ActiveCfg = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x86|x64.Build.0 = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver|Win32.ActiveCfg = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver|x64.ActiveCfg = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver|x64.Build.0 = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Format Debug|Win32.ActiveCfg = Debug|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Format Debug|x64.ActiveCfg = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Format Debug|x64.Build.0 = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Format|Win32.ActiveCfg = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Format|x64.ActiveCfg = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Format|x64.Build.0 = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount Debug|Win32.ActiveCfg = Debug|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount Debug|Win32.Build.0 = Debug|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount Debug|x64.ActiveCfg = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount Debug|x64.Build.0 = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount|Win32.ActiveCfg = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount|Win32.Build.0 = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount|x64.ActiveCfg = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount|x64.Build.0 = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Release|Win32.ActiveCfg = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Release|Win32.Build.0 = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Release|x64.ActiveCfg = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Release|x64.Build.0 = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Setup Debug|Win32.ActiveCfg = Debug|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Setup Debug|x64.ActiveCfg = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Setup Debug|x64.Build.0 = Debug|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Setup|Win32.ActiveCfg = Release|Win32 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Setup|x64.ActiveCfg = Release|x64 - {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Setup|x64.Build.0 = Release|x64 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.All Debug|Win32.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.All Debug|Win32.Build.0 = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.All Debug|x64.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.All|Win32.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.All|Win32.Build.0 = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.All|x64.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Boot Loader|Win32.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Boot Loader|x64.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Boot|Win32.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Boot|x64.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Debug|Win32.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Debug|Win32.Build.0 = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Debug|x64.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver Debug|Win32.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver Debug|x64.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x64 Debug|Win32.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x64 Debug|x64.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x64|Win32.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x64|x64.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x86 Debug|Win32.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x86 Debug|x64.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x86|Win32.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x86|x64.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver|Win32.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver|x64.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Format Debug|Win32.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Format Debug|x64.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Format|Win32.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Format|x64.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Mount Debug|Win32.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Mount Debug|x64.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Mount|Win32.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Mount|x64.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Release|Win32.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Release|Win32.Build.0 = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Release|x64.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Setup Debug|Win32.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Setup Debug|Win32.Build.0 = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Setup Debug|x64.ActiveCfg = Debug|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Setup|Win32.ActiveCfg = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Setup|Win32.Build.0 = Release|Win32 - {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Setup|x64.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.All Debug|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.All Debug|Win32.Build.0 = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.All Debug|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.All|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.All|Win32.Build.0 = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.All|x64.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Boot Loader|Win32.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Boot Loader|Win32.Build.0 = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Boot Loader|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Boot|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Boot|Win32.Build.0 = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Boot|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Debug|Win32.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Debug|Win32.Build.0 = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Debug|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver Debug|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver Debug|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x64 Debug|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x64 Debug|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x64|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x64|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x86 Debug|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x86 Debug|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x86|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x86|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Format Debug|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Format Debug|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Format|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Format|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Mount Debug|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Mount Debug|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Mount|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Mount|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Release|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Release|Win32.Build.0 = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Release|x64.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Setup Debug|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Setup Debug|x64.ActiveCfg = Release Loader|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Setup|Win32.ActiveCfg = Release|Win32 - {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Setup|x64.ActiveCfg = Release Loader|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All Debug|Win32.ActiveCfg = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All Debug|Win32.Build.0 = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All Debug|x64.ActiveCfg = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All Debug|x64.Build.0 = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All|Win32.ActiveCfg = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All|Win32.Build.0 = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All|x64.ActiveCfg = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All|x64.Build.0 = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot Loader|Win32.ActiveCfg = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot Loader|Win32.Build.0 = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot Loader|x64.ActiveCfg = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot Loader|x64.Build.0 = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot|Win32.ActiveCfg = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot|Win32.Build.0 = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot|x64.ActiveCfg = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot|x64.Build.0 = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Debug|Win32.ActiveCfg = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Debug|Win32.Build.0 = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Debug|x64.ActiveCfg = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Debug|x64.Build.0 = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver Debug|Win32.ActiveCfg = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver Debug|Win32.Build.0 = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver Debug|x64.ActiveCfg = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver Debug|x64.Build.0 = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64 Debug|Win32.ActiveCfg = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64 Debug|Win32.Build.0 = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64 Debug|x64.ActiveCfg = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64 Debug|x64.Build.0 = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64|Win32.ActiveCfg = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64|Win32.Build.0 = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64|x64.ActiveCfg = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64|x64.Build.0 = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86 Debug|Win32.ActiveCfg = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86 Debug|Win32.Build.0 = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86 Debug|x64.ActiveCfg = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86 Debug|x64.Build.0 = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86|Win32.ActiveCfg = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86|Win32.Build.0 = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86|x64.ActiveCfg = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86|x64.Build.0 = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver|Win32.ActiveCfg = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver|Win32.Build.0 = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver|x64.ActiveCfg = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver|x64.Build.0 = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format Debug|Win32.ActiveCfg = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format Debug|Win32.Build.0 = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format Debug|x64.ActiveCfg = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format Debug|x64.Build.0 = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format|Win32.ActiveCfg = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format|Win32.Build.0 = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format|x64.ActiveCfg = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format|x64.Build.0 = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount Debug|Win32.ActiveCfg = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount Debug|Win32.Build.0 = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount Debug|x64.ActiveCfg = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount Debug|x64.Build.0 = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount|Win32.ActiveCfg = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount|Win32.Build.0 = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount|x64.ActiveCfg = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount|x64.Build.0 = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Release|Win32.ActiveCfg = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Release|Win32.Build.0 = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Release|x64.ActiveCfg = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Release|x64.Build.0 = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup Debug|Win32.ActiveCfg = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup Debug|Win32.Build.0 = Debug|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup Debug|x64.ActiveCfg = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup Debug|x64.Build.0 = Debug|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup|Win32.ActiveCfg = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup|Win32.Build.0 = Release|Win32 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup|x64.ActiveCfg = Release|x64 - {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Crypto", "Crypto\Crypto.vcproj", "{993245CF-6B70-47EE-91BB-39F8FC6DC0E7}" + ProjectSection(ProjectDependencies) = postProject + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} = {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Driver", "Driver\Driver.vcproj", "{EF5EF444-18D0-40D7-8DFA-775EC4448602}" + ProjectSection(ProjectDependencies) = postProject + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} = {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Format", "Format\Format.vcproj", "{9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}" + ProjectSection(ProjectDependencies) = postProject + {EF5EF444-18D0-40D7-8DFA-775EC4448602} = {EF5EF444-18D0-40D7-8DFA-775EC4448602} + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} = {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7} = {993245CF-6B70-47EE-91BB-39F8FC6DC0E7} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Mount", "Mount\Mount.vcproj", "{E4C40F94-E7F9-4981-86E4-186B46F993F3}" + ProjectSection(ProjectDependencies) = postProject + {EF5EF444-18D0-40D7-8DFA-775EC4448602} = {EF5EF444-18D0-40D7-8DFA-775EC4448602} + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} = {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7} = {993245CF-6B70-47EE-91BB-39F8FC6DC0E7} + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF} = {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Setup", "Setup\Setup.vcproj", "{DF5F654D-BD44-4E31-B92E-B68074DC37A8}" + ProjectSection(ProjectDependencies) = postProject + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827} = {9715FF1D-599B-4BBC-AD96-BEF6E08FF827} + {E4C40F94-E7F9-4981-86E4-186B46F993F3} = {E4C40F94-E7F9-4981-86E4-186B46F993F3} + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} = {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF} = {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Boot", "Boot\Windows\Boot.vcproj", "{8B7F059F-E4C7-4E11-88F5-EE8B8433072E}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ExpandVolume", "ExpandVolume\ExpandVolume.vcproj", "{9715FF1D-599B-4BBC-AD96-BEF6E08FF827}" + ProjectSection(ProjectDependencies) = postProject + {EF5EF444-18D0-40D7-8DFA-775EC4448602} = {EF5EF444-18D0-40D7-8DFA-775EC4448602} + {E4C40F94-E7F9-4981-86E4-186B46F993F3} = {E4C40F94-E7F9-4981-86E4-186B46F993F3} + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} = {8B7F059F-E4C7-4E11-88F5-EE8B8433072E} + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF} = {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + All Debug|Win32 = All Debug|Win32 + All Debug|x64 = All Debug|x64 + All|Win32 = All|Win32 + All|x64 = All|x64 + Boot Loader|Win32 = Boot Loader|Win32 + Boot Loader|x64 = Boot Loader|x64 + Boot|Win32 = Boot|Win32 + Boot|x64 = Boot|x64 + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Driver Debug|Win32 = Driver Debug|Win32 + Driver Debug|x64 = Driver Debug|x64 + Driver x64 Debug|Win32 = Driver x64 Debug|Win32 + Driver x64 Debug|x64 = Driver x64 Debug|x64 + Driver x64|Win32 = Driver x64|Win32 + Driver x64|x64 = Driver x64|x64 + Driver x86 Debug|Win32 = Driver x86 Debug|Win32 + Driver x86 Debug|x64 = Driver x86 Debug|x64 + Driver x86|Win32 = Driver x86|Win32 + Driver x86|x64 = Driver x86|x64 + Driver|Win32 = Driver|Win32 + Driver|x64 = Driver|x64 + Format Debug|Win32 = Format Debug|Win32 + Format Debug|x64 = Format Debug|x64 + Format|Win32 = Format|Win32 + Format|x64 = Format|x64 + Mount Debug|Win32 = Mount Debug|Win32 + Mount Debug|x64 = Mount Debug|x64 + Mount|Win32 = Mount|Win32 + Mount|x64 = Mount|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + Setup Debug|Win32 = Setup Debug|Win32 + Setup Debug|x64 = Setup Debug|x64 + Setup|Win32 = Setup|Win32 + Setup|x64 = Setup|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All Debug|Win32.ActiveCfg = Debug|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All Debug|Win32.Build.0 = Debug|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All Debug|x64.ActiveCfg = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All Debug|x64.Build.0 = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All|Win32.ActiveCfg = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All|Win32.Build.0 = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All|x64.ActiveCfg = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.All|x64.Build.0 = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Boot Loader|Win32.ActiveCfg = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Boot Loader|x64.ActiveCfg = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Boot Loader|x64.Build.0 = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Boot|Win32.ActiveCfg = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Boot|x64.ActiveCfg = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Boot|x64.Build.0 = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Debug|Win32.ActiveCfg = Debug|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Debug|Win32.Build.0 = Debug|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Debug|x64.ActiveCfg = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Debug|x64.Build.0 = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver Debug|Win32.ActiveCfg = Debug|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver Debug|x64.ActiveCfg = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver Debug|x64.Build.0 = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x64 Debug|Win32.ActiveCfg = Debug|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x64 Debug|x64.ActiveCfg = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x64 Debug|x64.Build.0 = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x64|Win32.ActiveCfg = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x64|x64.ActiveCfg = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x64|x64.Build.0 = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x86 Debug|Win32.ActiveCfg = Debug|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x86 Debug|x64.ActiveCfg = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x86 Debug|x64.Build.0 = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x86|Win32.ActiveCfg = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x86|x64.ActiveCfg = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver x86|x64.Build.0 = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver|Win32.ActiveCfg = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver|x64.ActiveCfg = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Driver|x64.Build.0 = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format Debug|Win32.ActiveCfg = Debug|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format Debug|Win32.Build.0 = Debug|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format Debug|x64.ActiveCfg = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format Debug|x64.Build.0 = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format|Win32.ActiveCfg = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format|Win32.Build.0 = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format|x64.ActiveCfg = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Format|x64.Build.0 = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount Debug|Win32.ActiveCfg = Debug|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount Debug|Win32.Build.0 = Debug|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount Debug|x64.ActiveCfg = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount Debug|x64.Build.0 = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount|Win32.ActiveCfg = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount|Win32.Build.0 = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount|x64.ActiveCfg = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Mount|x64.Build.0 = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Release|Win32.ActiveCfg = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Release|Win32.Build.0 = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Release|x64.ActiveCfg = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Release|x64.Build.0 = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Setup Debug|Win32.ActiveCfg = Debug|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Setup Debug|x64.ActiveCfg = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Setup Debug|x64.Build.0 = Debug|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Setup|Win32.ActiveCfg = Release|Win32 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Setup|x64.ActiveCfg = Release|x64 + {993245CF-6B70-47EE-91BB-39F8FC6DC0E7}.Setup|x64.Build.0 = Release|x64 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.All Debug|Win32.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.All Debug|Win32.Build.0 = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.All Debug|x64.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.All|Win32.ActiveCfg = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.All|Win32.Build.0 = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.All|x64.ActiveCfg = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Boot Loader|Win32.ActiveCfg = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Boot Loader|x64.ActiveCfg = Debug x64|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Boot|Win32.ActiveCfg = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Boot|x64.ActiveCfg = Debug x64|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Debug|Win32.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Debug|Win32.Build.0 = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Debug|x64.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver Debug|Win32.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver Debug|Win32.Build.0 = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver Debug|x64.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x64 Debug|Win32.ActiveCfg = Debug x64|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x64 Debug|Win32.Build.0 = Debug x64|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x64 Debug|x64.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x64|Win32.ActiveCfg = Release x64|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x64|Win32.Build.0 = Release x64|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x64|x64.ActiveCfg = Debug x64|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x86 Debug|Win32.ActiveCfg = Debug x86|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x86 Debug|Win32.Build.0 = Debug x86|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x86 Debug|x64.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x86|Win32.ActiveCfg = Release x86|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x86|Win32.Build.0 = Release x86|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver x86|x64.ActiveCfg = Debug x64|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver|Win32.ActiveCfg = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver|Win32.Build.0 = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Driver|x64.ActiveCfg = Debug x64|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Format Debug|Win32.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Format Debug|x64.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Format|Win32.ActiveCfg = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Format|x64.ActiveCfg = Debug x64|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Mount Debug|Win32.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Mount Debug|x64.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Mount|Win32.ActiveCfg = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Mount|x64.ActiveCfg = Debug x64|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Release|Win32.ActiveCfg = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Release|Win32.Build.0 = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Release|x64.ActiveCfg = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Setup Debug|Win32.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Setup Debug|x64.ActiveCfg = Debug|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Setup|Win32.ActiveCfg = Release|Win32 + {EF5EF444-18D0-40D7-8DFA-775EC4448602}.Setup|x64.ActiveCfg = Debug x64|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All Debug|Win32.ActiveCfg = Debug|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All Debug|Win32.Build.0 = Debug|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All Debug|x64.ActiveCfg = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All Debug|x64.Build.0 = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All|Win32.ActiveCfg = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All|Win32.Build.0 = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All|x64.ActiveCfg = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.All|x64.Build.0 = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Boot Loader|Win32.ActiveCfg = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Boot Loader|x64.ActiveCfg = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Boot Loader|x64.Build.0 = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Boot|Win32.ActiveCfg = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Boot|x64.ActiveCfg = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Boot|x64.Build.0 = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Debug|Win32.ActiveCfg = Debug|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Debug|Win32.Build.0 = Debug|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Debug|x64.ActiveCfg = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Debug|x64.Build.0 = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver Debug|Win32.ActiveCfg = Debug|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver Debug|x64.ActiveCfg = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver Debug|x64.Build.0 = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x64 Debug|Win32.ActiveCfg = Debug|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x64 Debug|x64.ActiveCfg = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x64 Debug|x64.Build.0 = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x64|Win32.ActiveCfg = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x64|x64.ActiveCfg = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x64|x64.Build.0 = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x86 Debug|Win32.ActiveCfg = Debug|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x86 Debug|x64.ActiveCfg = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x86 Debug|x64.Build.0 = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x86|Win32.ActiveCfg = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x86|x64.ActiveCfg = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver x86|x64.Build.0 = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver|Win32.ActiveCfg = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver|x64.ActiveCfg = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Driver|x64.Build.0 = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format Debug|Win32.ActiveCfg = Debug|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format Debug|Win32.Build.0 = Debug|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format Debug|x64.ActiveCfg = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format Debug|x64.Build.0 = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format|Win32.ActiveCfg = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format|Win32.Build.0 = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format|x64.ActiveCfg = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Format|x64.Build.0 = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Mount Debug|Win32.ActiveCfg = Debug|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Mount Debug|x64.ActiveCfg = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Mount Debug|x64.Build.0 = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Mount|Win32.ActiveCfg = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Mount|x64.ActiveCfg = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Mount|x64.Build.0 = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Release|Win32.ActiveCfg = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Release|Win32.Build.0 = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Release|x64.ActiveCfg = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Release|x64.Build.0 = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Setup Debug|Win32.ActiveCfg = Debug|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Setup Debug|x64.ActiveCfg = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Setup Debug|x64.Build.0 = Debug|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Setup|Win32.ActiveCfg = Release|Win32 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Setup|x64.ActiveCfg = Release|x64 + {9DC1ABE2-D18B-48FB-81D2-8C50ADC57BCF}.Setup|x64.Build.0 = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All Debug|Win32.ActiveCfg = Debug|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All Debug|Win32.Build.0 = Debug|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All Debug|x64.ActiveCfg = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All Debug|x64.Build.0 = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All|Win32.ActiveCfg = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All|Win32.Build.0 = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All|x64.ActiveCfg = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.All|x64.Build.0 = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Boot Loader|Win32.ActiveCfg = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Boot Loader|x64.ActiveCfg = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Boot Loader|x64.Build.0 = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Boot|Win32.ActiveCfg = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Boot|x64.ActiveCfg = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Boot|x64.Build.0 = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Debug|Win32.ActiveCfg = Debug|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Debug|Win32.Build.0 = Debug|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Debug|x64.ActiveCfg = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Debug|x64.Build.0 = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver Debug|Win32.ActiveCfg = Debug|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver Debug|x64.ActiveCfg = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver Debug|x64.Build.0 = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x64 Debug|Win32.ActiveCfg = Debug|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x64 Debug|x64.ActiveCfg = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x64 Debug|x64.Build.0 = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x64|Win32.ActiveCfg = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x64|x64.ActiveCfg = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x64|x64.Build.0 = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x86 Debug|Win32.ActiveCfg = Debug|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x86 Debug|x64.ActiveCfg = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x86 Debug|x64.Build.0 = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x86|Win32.ActiveCfg = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x86|x64.ActiveCfg = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver x86|x64.Build.0 = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver|Win32.ActiveCfg = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver|x64.ActiveCfg = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Driver|x64.Build.0 = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Format Debug|Win32.ActiveCfg = Debug|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Format Debug|x64.ActiveCfg = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Format Debug|x64.Build.0 = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Format|Win32.ActiveCfg = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Format|x64.ActiveCfg = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Format|x64.Build.0 = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount Debug|Win32.ActiveCfg = Debug|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount Debug|Win32.Build.0 = Debug|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount Debug|x64.ActiveCfg = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount Debug|x64.Build.0 = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount|Win32.ActiveCfg = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount|Win32.Build.0 = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount|x64.ActiveCfg = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Mount|x64.Build.0 = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Release|Win32.ActiveCfg = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Release|Win32.Build.0 = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Release|x64.ActiveCfg = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Release|x64.Build.0 = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Setup Debug|Win32.ActiveCfg = Debug|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Setup Debug|x64.ActiveCfg = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Setup Debug|x64.Build.0 = Debug|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Setup|Win32.ActiveCfg = Release|Win32 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Setup|x64.ActiveCfg = Release|x64 + {E4C40F94-E7F9-4981-86E4-186B46F993F3}.Setup|x64.Build.0 = Release|x64 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.All Debug|Win32.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.All Debug|Win32.Build.0 = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.All Debug|x64.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.All|Win32.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.All|Win32.Build.0 = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.All|x64.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Boot Loader|Win32.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Boot Loader|x64.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Boot|Win32.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Boot|x64.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Debug|Win32.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Debug|Win32.Build.0 = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Debug|x64.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver Debug|Win32.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver Debug|x64.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x64 Debug|Win32.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x64 Debug|x64.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x64|Win32.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x64|x64.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x86 Debug|Win32.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x86 Debug|x64.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x86|Win32.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver x86|x64.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver|Win32.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Driver|x64.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Format Debug|Win32.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Format Debug|x64.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Format|Win32.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Format|x64.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Mount Debug|Win32.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Mount Debug|x64.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Mount|Win32.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Mount|x64.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Release|Win32.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Release|Win32.Build.0 = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Release|x64.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Setup Debug|Win32.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Setup Debug|Win32.Build.0 = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Setup Debug|x64.ActiveCfg = Debug|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Setup|Win32.ActiveCfg = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Setup|Win32.Build.0 = Release|Win32 + {DF5F654D-BD44-4E31-B92E-B68074DC37A8}.Setup|x64.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.All Debug|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.All Debug|Win32.Build.0 = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.All Debug|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.All|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.All|Win32.Build.0 = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.All|x64.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Boot Loader|Win32.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Boot Loader|Win32.Build.0 = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Boot Loader|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Boot|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Boot|Win32.Build.0 = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Boot|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Debug|Win32.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Debug|Win32.Build.0 = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Debug|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver Debug|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver Debug|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x64 Debug|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x64 Debug|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x64|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x64|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x86 Debug|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x86 Debug|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x86|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver x86|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Driver|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Format Debug|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Format Debug|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Format|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Format|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Mount Debug|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Mount Debug|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Mount|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Mount|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Release|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Release|Win32.Build.0 = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Release|x64.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Setup Debug|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Setup Debug|x64.ActiveCfg = Release Loader|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Setup|Win32.ActiveCfg = Release|Win32 + {8B7F059F-E4C7-4E11-88F5-EE8B8433072E}.Setup|x64.ActiveCfg = Release Loader|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All Debug|Win32.ActiveCfg = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All Debug|Win32.Build.0 = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All Debug|x64.ActiveCfg = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All Debug|x64.Build.0 = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All|Win32.ActiveCfg = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All|Win32.Build.0 = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All|x64.ActiveCfg = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.All|x64.Build.0 = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot Loader|Win32.ActiveCfg = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot Loader|Win32.Build.0 = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot Loader|x64.ActiveCfg = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot Loader|x64.Build.0 = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot|Win32.ActiveCfg = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot|Win32.Build.0 = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot|x64.ActiveCfg = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Boot|x64.Build.0 = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Debug|Win32.ActiveCfg = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Debug|Win32.Build.0 = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Debug|x64.ActiveCfg = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Debug|x64.Build.0 = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver Debug|Win32.ActiveCfg = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver Debug|Win32.Build.0 = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver Debug|x64.ActiveCfg = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver Debug|x64.Build.0 = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64 Debug|Win32.ActiveCfg = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64 Debug|Win32.Build.0 = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64 Debug|x64.ActiveCfg = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64 Debug|x64.Build.0 = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64|Win32.ActiveCfg = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64|Win32.Build.0 = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64|x64.ActiveCfg = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x64|x64.Build.0 = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86 Debug|Win32.ActiveCfg = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86 Debug|Win32.Build.0 = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86 Debug|x64.ActiveCfg = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86 Debug|x64.Build.0 = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86|Win32.ActiveCfg = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86|Win32.Build.0 = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86|x64.ActiveCfg = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver x86|x64.Build.0 = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver|Win32.ActiveCfg = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver|Win32.Build.0 = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver|x64.ActiveCfg = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Driver|x64.Build.0 = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format Debug|Win32.ActiveCfg = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format Debug|Win32.Build.0 = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format Debug|x64.ActiveCfg = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format Debug|x64.Build.0 = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format|Win32.ActiveCfg = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format|Win32.Build.0 = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format|x64.ActiveCfg = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Format|x64.Build.0 = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount Debug|Win32.ActiveCfg = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount Debug|Win32.Build.0 = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount Debug|x64.ActiveCfg = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount Debug|x64.Build.0 = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount|Win32.ActiveCfg = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount|Win32.Build.0 = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount|x64.ActiveCfg = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Mount|x64.Build.0 = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Release|Win32.ActiveCfg = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Release|Win32.Build.0 = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Release|x64.ActiveCfg = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Release|x64.Build.0 = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup Debug|Win32.ActiveCfg = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup Debug|Win32.Build.0 = Debug|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup Debug|x64.ActiveCfg = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup Debug|x64.Build.0 = Debug|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup|Win32.ActiveCfg = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup|Win32.Build.0 = Release|Win32 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup|x64.ActiveCfg = Release|x64 + {9715FF1D-599B-4BBC-AD96-BEF6E08FF827}.Setup|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal -- cgit v1.2.3 From 191075155835172e5596e191cf0679ff9022f0fd Mon Sep 17 00:00:00 2001 From: David Foerster Date: Tue, 10 May 2016 21:58:40 +0200 Subject: Fix issues with .gitattributes - Revert accidentally converted binary file --- src/Build/Tools/MacOSX/nasm | Bin 1818750 -> 1818752 bytes 1 file changed, 0 insertions(+), 0 deletions(-) (limited to 'src') diff --git a/src/Build/Tools/MacOSX/nasm b/src/Build/Tools/MacOSX/nasm index 62a6702a..7d2c38ac 100755 Binary files a/src/Build/Tools/MacOSX/nasm and b/src/Build/Tools/MacOSX/nasm differ -- cgit v1.2.3 From 11716ed2dacbb104f8f59867fe66f2c0a6984291 Mon Sep 17 00:00:00 2001 From: David Foerster Date: Tue, 10 May 2016 22:16:32 +0200 Subject: Remove trailing whitespace --- src/Boot/Windows/Bios.h | 2 +- src/Boot/Windows/BootCommon.h | 2 +- src/Boot/Windows/BootConfig.cpp | 2 +- src/Boot/Windows/BootConfig.h | 2 +- src/Boot/Windows/BootConsoleIo.cpp | 8 +- src/Boot/Windows/BootConsoleIo.h | 2 +- src/Boot/Windows/BootCrt.asm | 2 +- src/Boot/Windows/BootDebug.cpp | 6 +- src/Boot/Windows/BootDebug.h | 2 +- src/Boot/Windows/BootDefs.h | 6 +- src/Boot/Windows/BootDiskIo.cpp | 12 +- src/Boot/Windows/BootDiskIo.h | 2 +- src/Boot/Windows/BootEncryptedIo.cpp | 2 +- src/Boot/Windows/BootEncryptedIo.h | 2 +- src/Boot/Windows/BootMain.cpp | 22 +- src/Boot/Windows/BootMain.h | 2 +- src/Boot/Windows/BootMemory.cpp | 4 +- src/Boot/Windows/BootMemory.h | 2 +- src/Boot/Windows/BootSector.asm | 56 +- src/Boot/Windows/BootStrings.h | 2 +- src/Boot/Windows/IntFilter.cpp | 18 +- src/Boot/Windows/IntFilter.h | 2 +- src/Boot/Windows/Makefile | 14 +- src/Boot/Windows/Platform.cpp | 14 +- src/Boot/Windows/Platform.h | 4 +- src/Build/Include/Makefile.inc | 4 +- src/Common/Apidrvr.h | 8 +- src/Common/BaseCom.cpp | 2 +- src/Common/BaseCom.h | 8 +- src/Common/BootEncryption.cpp | 80 +- src/Common/BootEncryption.h | 2 +- src/Common/Cache.c | 8 +- src/Common/Cache.h | 10 +- src/Common/Cmdline.c | 10 +- src/Common/Cmdline.h | 8 +- src/Common/Combo.c | 12 +- src/Common/Combo.h | 8 +- src/Common/Common.h | 2 +- src/Common/Common.rc | 8 +- src/Common/Crc.c | 10 +- src/Common/Crc.h | 8 +- src/Common/Crypto.c | 38 +- src/Common/Crypto.h | 22 +- src/Common/Dictionary.c | 4 +- src/Common/Dictionary.h | 2 +- src/Common/Dlgcode.c | 566 ++--- src/Common/Dlgcode.h | 14 +- src/Common/EncryptionThreadPool.c | 20 +- src/Common/EncryptionThreadPool.h | 2 +- src/Common/Endian.c | 8 +- src/Common/Endian.h | 12 +- src/Common/Exception.h | 2 +- src/Common/Fat.c | 42 +- src/Common/Fat.h | 8 +- src/Common/Format.c | 82 +- src/Common/Format.h | 10 +- src/Common/GfMul.c | 12 +- src/Common/Inflate.c | 2 +- src/Common/Inflate.h | 6 +- src/Common/Keyfiles.c | 30 +- src/Common/Keyfiles.h | 4 +- src/Common/Language.c | 20 +- src/Common/Language.h | 2 +- src/Common/Password.c | 30 +- src/Common/Password.h | 12 +- src/Common/Pkcs5.c | 54 +- src/Common/Pkcs5.h | 8 +- src/Common/Progress.c | 10 +- src/Common/Progress.h | 8 +- src/Common/Random.c | 50 +- src/Common/Random.h | 8 +- src/Common/Registry.c | 6 +- src/Common/Registry.h | 2 +- src/Common/Resource.h | 2 +- src/Common/SecurityToken.cpp | 10 +- src/Common/SecurityToken.h | 6 +- src/Common/Tcdefs.h | 18 +- src/Common/Tests.c | 148 +- src/Common/Tests.h | 10 +- src/Common/Volumes.c | 52 +- src/Common/Volumes.h | 12 +- src/Common/Wipe.c | 2 +- src/Common/Wipe.h | 2 +- src/Common/Xml.c | 6 +- src/Common/Xml.h | 2 +- src/Common/Xts.c | 66 +- src/Common/Xts.h | 6 +- src/Core/Core.h | 4 +- src/Core/Core.make | 2 +- src/Core/CoreBase.cpp | 8 +- src/Core/CoreBase.h | 4 +- src/Core/CoreException.cpp | 2 +- src/Core/CoreException.h | 2 +- src/Core/FatFormatter.cpp | 36 +- src/Core/FatFormatter.h | 2 +- src/Core/HostDevice.cpp | 4 +- src/Core/HostDevice.h | 2 +- src/Core/MountOptions.cpp | 12 +- src/Core/MountOptions.h | 2 +- src/Core/RandomNumberGenerator.cpp | 6 +- src/Core/RandomNumberGenerator.h | 2 +- src/Core/Unix/CoreService.cpp | 18 +- src/Core/Unix/CoreService.h | 2 +- src/Core/Unix/CoreServiceProxy.h | 4 +- src/Core/Unix/CoreServiceRequest.cpp | 6 +- src/Core/Unix/CoreServiceRequest.h | 2 +- src/Core/Unix/CoreServiceResponse.cpp | 4 +- src/Core/Unix/CoreServiceResponse.h | 2 +- src/Core/Unix/CoreUnix.cpp | 30 +- src/Core/Unix/CoreUnix.h | 6 +- src/Core/Unix/FreeBSD/CoreFreeBSD.cpp | 6 +- src/Core/Unix/FreeBSD/CoreFreeBSD.h | 4 +- src/Core/Unix/FreeBSD/System.h | 2 +- src/Core/Unix/Linux/CoreLinux.cpp | 12 +- src/Core/Unix/Linux/CoreLinux.h | 4 +- src/Core/Unix/Linux/System.h | 2 +- src/Core/Unix/MacOSX/CoreMacOSX.cpp | 8 +- src/Core/Unix/MacOSX/CoreMacOSX.h | 4 +- src/Core/Unix/MacOSX/System.h | 2 +- src/Core/Unix/MountedFilesystem.h | 2 +- src/Core/Unix/Solaris/CoreSolaris.cpp | 8 +- src/Core/Unix/Solaris/CoreSolaris.h | 4 +- src/Core/Unix/Solaris/System.h | 2 +- src/Core/Unix/System.h | 2 +- src/Core/VolumeCreator.cpp | 4 +- src/Core/VolumeCreator.h | 4 +- src/Crypto/AesSmall_x86.asm | 30 +- src/Crypto/Aes_hw_cpu.asm | 4 +- src/Crypto/Aes_hw_cpu.h | 2 +- src/Crypto/Aes_x64.asm | 14 +- src/Crypto/Aes_x86.asm | 14 +- src/Crypto/Aestab.c | 2 +- src/Crypto/Rmd160.c | 8 +- src/Crypto/Serpent.c | 66 +- src/Crypto/Sha2Small.c | 10 +- src/Crypto/Twofish.c | 64 +- src/Crypto/Whirlpool.c | 12 +- src/Crypto/cpu.c | 2 +- src/Crypto/cpu.h | 2 +- src/Driver/BuildDriver.cmd | 6 +- src/Driver/DriveFilter.c | 66 +- src/Driver/DriveFilter.h | 2 +- src/Driver/Driver.rc | 6 +- src/Driver/DumpFilter.c | 2 +- src/Driver/DumpFilter.h | 2 +- src/Driver/EncryptedIoQueue.c | 26 +- src/Driver/EncryptedIoQueue.h | 8 +- src/Driver/Fuse/Driver.make | 2 +- src/Driver/Fuse/FuseService.cpp | 12 +- src/Driver/Fuse/FuseService.h | 2 +- src/Driver/Ntdriver.c | 90 +- src/Driver/Ntdriver.h | 10 +- src/Driver/Ntvol.c | 42 +- src/Driver/Ntvol.h | 8 +- src/Driver/Resource.h | 2 +- src/Driver/VolumeFilter.c | 4 +- src/Driver/VolumeFilter.h | 2 +- src/ExpandVolume/DlgExpandVolume.cpp | 18 +- src/ExpandVolume/ExpandVolume.c | 10 +- src/ExpandVolume/ExpandVolume.h | 8 +- src/ExpandVolume/ExpandVolume.rc | 12 +- src/ExpandVolume/InitDataArea.c | 8 +- src/ExpandVolume/InitDataArea.h | 4 +- src/ExpandVolume/WinMain.cpp | 32 +- src/ExpandVolume/resource.h | 2 +- src/Format/Format.rc | 10 +- src/Format/FormatCom.cpp | 4 +- src/Format/FormatCom.h | 2 +- src/Format/FormatCom.idl | 2 +- src/Format/InPlace.c | 94 +- src/Format/InPlace.h | 2 +- src/Format/Resource.h | 2 +- src/Format/Tcformat.c | 406 ++-- src/Format/Tcformat.h | 8 +- src/License.txt | 14 +- src/Main/Application.h | 2 +- src/Main/CommandLineInterface.cpp | 30 +- src/Main/CommandLineInterface.h | 4 +- src/Main/FatalErrorHandler.cpp | 8 +- src/Main/FatalErrorHandler.h | 2 +- src/Main/FavoriteVolume.cpp | 4 +- src/Main/FavoriteVolume.h | 2 +- src/Main/Forms/AboutDialog.cpp | 2 +- src/Main/Forms/AboutDialog.h | 4 +- src/Main/Forms/BenchmarkDialog.cpp | 10 +- src/Main/Forms/BenchmarkDialog.h | 4 +- src/Main/Forms/ChangePasswordDialog.cpp | 18 +- src/Main/Forms/ChangePasswordDialog.h | 2 +- src/Main/Forms/DeviceSelectionDialog.cpp | 12 +- src/Main/Forms/DeviceSelectionDialog.h | 2 +- src/Main/Forms/EncryptionOptionsWizardPage.cpp | 6 +- src/Main/Forms/EncryptionOptionsWizardPage.h | 2 +- src/Main/Forms/EncryptionTestDialog.cpp | 8 +- src/Main/Forms/EncryptionTestDialog.h | 2 +- src/Main/Forms/FavoriteVolumesDialog.cpp | 8 +- src/Main/Forms/FavoriteVolumesDialog.h | 4 +- src/Main/Forms/Forms.cpp | 2402 ++++++++++---------- src/Main/Forms/Forms.h | 516 ++--- src/Main/Forms/InfoWizardPage.cpp | 2 +- src/Main/Forms/InfoWizardPage.h | 2 +- src/Main/Forms/KeyfileGeneratorDialog.cpp | 44 +- src/Main/Forms/KeyfileGeneratorDialog.h | 4 +- src/Main/Forms/KeyfilesDialog.cpp | 4 +- src/Main/Forms/KeyfilesDialog.h | 2 +- src/Main/Forms/KeyfilesPanel.cpp | 4 +- src/Main/Forms/KeyfilesPanel.h | 2 +- src/Main/Forms/LegalNoticesDialog.cpp | 4 +- src/Main/Forms/LegalNoticesDialog.h | 2 +- src/Main/Forms/MainFrame.cpp | 62 +- src/Main/Forms/MainFrame.h | 6 +- src/Main/Forms/MountOptionsDialog.cpp | 12 +- src/Main/Forms/MountOptionsDialog.h | 2 +- src/Main/Forms/NewSecurityTokenKeyfileDialog.cpp | 2 +- src/Main/Forms/NewSecurityTokenKeyfileDialog.h | 2 +- src/Main/Forms/PreferencesDialog.cpp | 22 +- src/Main/Forms/PreferencesDialog.h | 4 +- src/Main/Forms/ProgressWizardPage.cpp | 2 +- src/Main/Forms/ProgressWizardPage.h | 2 +- src/Main/Forms/RandomPoolEnrichmentDialog.cpp | 12 +- src/Main/Forms/RandomPoolEnrichmentDialog.h | 4 +- src/Main/Forms/SecurityTokenKeyfilesDialog.cpp | 6 +- src/Main/Forms/SecurityTokenKeyfilesDialog.h | 2 +- src/Main/Forms/SelectDirectoryWizardPage.cpp | 4 +- src/Main/Forms/SelectDirectoryWizardPage.h | 2 +- src/Main/Forms/SingleChoiceWizardPage.h | 2 +- .../Forms/VolumeCreationProgressWizardPage.cpp | 14 +- src/Main/Forms/VolumeCreationProgressWizardPage.h | 2 +- src/Main/Forms/VolumeCreationWizard.cpp | 76 +- src/Main/Forms/VolumeCreationWizard.h | 2 +- src/Main/Forms/VolumeFormatOptionsWizardPage.cpp | 2 +- src/Main/Forms/VolumeFormatOptionsWizardPage.h | 2 +- src/Main/Forms/VolumeLocationWizardPage.cpp | 4 +- src/Main/Forms/VolumeLocationWizardPage.h | 2 +- src/Main/Forms/VolumePasswordPanel.cpp | 42 +- src/Main/Forms/VolumePasswordPanel.h | 4 +- src/Main/Forms/VolumePasswordWizardPage.cpp | 2 +- src/Main/Forms/VolumePasswordWizardPage.h | 4 +- src/Main/Forms/VolumePimWizardPage.cpp | 18 +- src/Main/Forms/VolumePimWizardPage.h | 6 +- src/Main/Forms/VolumePropertiesDialog.cpp | 6 +- src/Main/Forms/VolumePropertiesDialog.h | 4 +- src/Main/Forms/VolumeSizeWizardPage.cpp | 6 +- src/Main/Forms/VolumeSizeWizardPage.h | 2 +- src/Main/Forms/WaitDialog.cpp | 8 +- src/Main/Forms/WaitDialog.h | 24 +- src/Main/Forms/WizardFrame.cpp | 10 +- src/Main/Forms/WizardFrame.h | 2 +- src/Main/Forms/WizardPage.h | 2 +- src/Main/GraphicUserInterface.cpp | 130 +- src/Main/GraphicUserInterface.h | 4 +- src/Main/Hotkey.cpp | 14 +- src/Main/Hotkey.h | 2 +- src/Main/LanguageStrings.cpp | 2 +- src/Main/LanguageStrings.h | 2 +- src/Main/Main.h | 2 +- src/Main/Main.make | 12 +- src/Main/Resources.cpp | 4 +- src/Main/Resources.h | 2 +- src/Main/StringFormatter.cpp | 2 +- src/Main/StringFormatter.h | 2 +- src/Main/System.cpp | 2 +- src/Main/System.h | 6 +- src/Main/SystemPrecompiled.h | 2 +- src/Main/TextUserInterface.cpp | 52 +- src/Main/TextUserInterface.h | 2 +- src/Main/Unix/Main.cpp | 4 +- src/Main/UserInterface.cpp | 40 +- src/Main/UserInterface.h | 2 +- src/Main/UserInterfaceException.h | 2 +- src/Main/UserInterfaceType.h | 2 +- src/Main/UserPreferences.cpp | 26 +- src/Main/UserPreferences.h | 2 +- src/Main/VolumeHistory.cpp | 2 +- src/Main/VolumeHistory.h | 2 +- src/Main/Xml.cpp | 2 +- src/Main/Xml.h | 2 +- src/Mount/Favorites.cpp | 16 +- src/Mount/Favorites.h | 4 +- src/Mount/Hotkeys.c | 50 +- src/Mount/Hotkeys.h | 2 +- src/Mount/MainCom.cpp | 2 +- src/Mount/MainCom.h | 2 +- src/Mount/MainCom.idl | 2 +- src/Mount/Mount.c | 640 +++--- src/Mount/Mount.h | 8 +- src/Mount/Mount.rc | 12 +- src/Mount/Resource.h | 2 +- src/PKCS11/cryptoki.h | 8 +- src/PKCS11/pkcs11.h | 6 +- src/PKCS11/pkcs11f.h | 16 +- src/Platform/Buffer.cpp | 4 +- src/Platform/Buffer.h | 2 +- src/Platform/Directory.h | 2 +- src/Platform/Event.cpp | 4 +- src/Platform/Event.h | 2 +- src/Platform/Exception.cpp | 2 +- src/Platform/Exception.h | 2 +- src/Platform/File.h | 6 +- src/Platform/FileCommon.cpp | 6 +- src/Platform/FileStream.h | 2 +- src/Platform/FilesystemPath.h | 6 +- src/Platform/Finally.h | 4 +- src/Platform/ForEach.h | 4 +- src/Platform/Functor.h | 2 +- src/Platform/Memory.cpp | 4 +- src/Platform/Memory.h | 2 +- src/Platform/MemoryStream.cpp | 2 +- src/Platform/MemoryStream.h | 2 +- src/Platform/Mutex.h | 2 +- src/Platform/Platform.h | 2 +- src/Platform/Platform.make | 2 +- src/Platform/PlatformBase.h | 2 +- src/Platform/PlatformTest.cpp | 10 +- src/Platform/PlatformTest.h | 2 +- src/Platform/Serializable.cpp | 2 +- src/Platform/Serializable.h | 8 +- src/Platform/Serializer.cpp | 18 +- src/Platform/Serializer.h | 2 +- src/Platform/SerializerFactory.cpp | 2 +- src/Platform/SerializerFactory.h | 2 +- src/Platform/SharedPtr.h | 6 +- src/Platform/SharedVal.h | 2 +- src/Platform/Stream.h | 2 +- src/Platform/StringConverter.cpp | 8 +- src/Platform/StringConverter.h | 2 +- src/Platform/SyncEvent.h | 2 +- src/Platform/System.h | 2 +- src/Platform/SystemException.h | 2 +- src/Platform/SystemInfo.h | 2 +- src/Platform/SystemLog.h | 4 +- src/Platform/TextReader.cpp | 2 +- src/Platform/TextReader.h | 2 +- src/Platform/Thread.h | 2 +- src/Platform/Time.h | 2 +- src/Platform/Unix/Directory.cpp | 4 +- src/Platform/Unix/File.cpp | 12 +- src/Platform/Unix/FilesystemPath.cpp | 4 +- src/Platform/Unix/Mutex.cpp | 2 +- src/Platform/Unix/Pipe.cpp | 4 +- src/Platform/Unix/Pipe.h | 2 +- src/Platform/Unix/Poller.cpp | 2 +- src/Platform/Unix/Poller.h | 2 +- src/Platform/Unix/Process.cpp | 18 +- src/Platform/Unix/Process.h | 4 +- src/Platform/Unix/SyncEvent.cpp | 4 +- src/Platform/Unix/System.h | 2 +- src/Platform/Unix/SystemException.cpp | 6 +- src/Platform/Unix/SystemInfo.cpp | 2 +- src/Platform/Unix/SystemLog.cpp | 2 +- src/Platform/Unix/Thread.cpp | 2 +- src/Platform/Unix/Time.cpp | 2 +- src/Platform/User.h | 2 +- src/Readme.txt | 50 +- src/Release/Setup Files/License.txt | 14 +- src/Release/Setup Files/NOTICE | 4 +- src/Setup/ComSetup.cpp | 2 +- src/Setup/ComSetup.h | 2 +- src/Setup/ComSetup.rgs | 14 +- src/Setup/Dir.c | 8 +- src/Setup/Dir.h | 8 +- src/Setup/Linux/veracrypt_install_template.sh | 66 +- src/Setup/MacOSX/veracrypt.pkgproj | 2 +- src/Setup/Resource.h | 2 +- src/Setup/SelfExtract.c | 62 +- src/Setup/SelfExtract.h | 2 +- src/Setup/Setup.c | 112 +- src/Setup/Setup.h | 8 +- src/Setup/Setup.rc | 8 +- src/Setup/Wizard.c | 50 +- src/Setup/Wizard.h | 8 +- src/Volume/Cipher.cpp | 4 +- src/Volume/Cipher.h | 6 +- src/Volume/Crc32.h | 2 +- src/Volume/EncryptionAlgorithm.cpp | 14 +- src/Volume/EncryptionAlgorithm.h | 2 +- src/Volume/EncryptionMode.cpp | 2 +- src/Volume/EncryptionMode.h | 2 +- src/Volume/EncryptionModeXTS.cpp | 32 +- src/Volume/EncryptionModeXTS.h | 2 +- src/Volume/EncryptionTest.cpp | 134 +- src/Volume/EncryptionTest.h | 4 +- src/Volume/EncryptionThreadPool.cpp | 6 +- src/Volume/EncryptionThreadPool.h | 2 +- src/Volume/Hash.cpp | 6 +- src/Volume/Hash.h | 4 +- src/Volume/Keyfile.cpp | 4 +- src/Volume/Keyfile.h | 2 +- src/Volume/Pkcs5Kdf.cpp | 8 +- src/Volume/Pkcs5Kdf.h | 6 +- src/Volume/Version.h | 2 +- src/Volume/Volume.cpp | 16 +- src/Volume/Volume.h | 4 +- src/Volume/Volume.make | 2 +- src/Volume/VolumeException.cpp | 4 +- src/Volume/VolumeException.h | 2 +- src/Volume/VolumeHeader.cpp | 12 +- src/Volume/VolumeHeader.h | 2 +- src/Volume/VolumeInfo.cpp | 4 +- src/Volume/VolumeInfo.h | 4 +- src/Volume/VolumeLayout.cpp | 2 +- src/Volume/VolumeLayout.h | 2 +- src/Volume/VolumePassword.cpp | 8 +- src/Volume/VolumePassword.h | 2 +- src/Volume/VolumePasswordCache.cpp | 2 +- src/Volume/VolumePasswordCache.h | 2 +- src/Volume/VolumeSlot.h | 2 +- 406 files changed, 4394 insertions(+), 4394 deletions(-) (limited to 'src') diff --git a/src/Boot/Windows/Bios.h b/src/Boot/Windows/Bios.h index dd2da6be..e6f9ec89 100644 --- a/src/Boot/Windows/Bios.h +++ b/src/Boot/Windows/Bios.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/BootCommon.h b/src/Boot/Windows/BootCommon.h index 1dc86560..0d4f710d 100644 --- a/src/Boot/Windows/BootCommon.h +++ b/src/Boot/Windows/BootCommon.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/BootConfig.cpp b/src/Boot/Windows/BootConfig.cpp index 75baf19e..3e41d610 100644 --- a/src/Boot/Windows/BootConfig.cpp +++ b/src/Boot/Windows/BootConfig.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/BootConfig.h b/src/Boot/Windows/BootConfig.h index 0a06a987..428d713c 100644 --- a/src/Boot/Windows/BootConfig.h +++ b/src/Boot/Windows/BootConfig.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/BootConsoleIo.cpp b/src/Boot/Windows/BootConsoleIo.cpp index 8b5a1905..2fee84fc 100644 --- a/src/Boot/Windows/BootConsoleIo.cpp +++ b/src/Boot/Windows/BootConsoleIo.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -84,7 +84,7 @@ void Print (uint32 number) number /= 10; } str[pos] = (char) (number % 10) + '0'; - + while (pos >= 0) PrintChar (str[pos--]); } @@ -251,7 +251,7 @@ byte GetKeyboardChar (byte *scanCode) mov asciiCode, al mov scan, ah } - + if (scanCode) *scanCode = scan; @@ -327,7 +327,7 @@ int GetString (char *buffer, size_t bufferSize) if (scanCode == TC_BIOS_KEY_ENTER) break; - + if (scanCode == TC_BIOS_KEY_ESC) return 0; diff --git a/src/Boot/Windows/BootConsoleIo.h b/src/Boot/Windows/BootConsoleIo.h index b95036d5..52a054fe 100644 --- a/src/Boot/Windows/BootConsoleIo.h +++ b/src/Boot/Windows/BootConsoleIo.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/BootCrt.asm b/src/Boot/Windows/BootCrt.asm index fd2c2ef0..92ac1563 100644 --- a/src/Boot/Windows/BootCrt.asm +++ b/src/Boot/Windows/BootCrt.asm @@ -3,7 +3,7 @@ ; 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) +; 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 diff --git a/src/Boot/Windows/BootDebug.cpp b/src/Boot/Windows/BootDebug.cpp index 2c796437..dd0863a0 100644 --- a/src/Boot/Windows/BootDebug.cpp +++ b/src/Boot/Windows/BootDebug.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -61,12 +61,12 @@ void PrintVal (const char *message, const uint32 value, bool newLine, bool hex) { Print (message); Print (": "); - + if (hex) PrintHex (value); else Print (value); - + if (newLine) PrintEndl(); } diff --git a/src/Boot/Windows/BootDebug.h b/src/Boot/Windows/BootDebug.h index a10c7fec..e7ae4134 100644 --- a/src/Boot/Windows/BootDebug.h +++ b/src/Boot/Windows/BootDebug.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/BootDefs.h b/src/Boot/Windows/BootDefs.h index 2e69d5a3..1fc923ae 100644 --- a/src/Boot/Windows/BootDefs.h +++ b/src/Boot/Windows/BootDefs.h @@ -3,7 +3,7 @@ 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) + 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 @@ -42,9 +42,9 @@ #define TC__BOOT_LOADER_SEGMENT TC_HEX (9000) // Some buggy BIOS routines fail if CS bits 0-10 are not zero #if TC__BOOT_MEMORY_REQUIRED <= 32 -# define TC__BOOT_LOADER_SEGMENT_LOW (TC__BOOT_LOADER_SEGMENT - 32 * 1024 / 16) +# define TC__BOOT_LOADER_SEGMENT_LOW (TC__BOOT_LOADER_SEGMENT - 32 * 1024 / 16) #else -# define TC__BOOT_LOADER_SEGMENT_LOW (TC__BOOT_LOADER_SEGMENT - 64 * 1024 / 16) +# define TC__BOOT_LOADER_SEGMENT_LOW (TC__BOOT_LOADER_SEGMENT - 64 * 1024 / 16) #endif #define TC__COM_EXECUTABLE_OFFSET TC_HEX (100) diff --git a/src/Boot/Windows/BootDiskIo.cpp b/src/Boot/Windows/BootDiskIo.cpp index bf3fe9fc..15d6f711 100644 --- a/src/Boot/Windows/BootDiskIo.cpp +++ b/src/Boot/Windows/BootDiskIo.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -201,7 +201,7 @@ static BiosResult ReadWriteSectors (bool write, BiosLbaPacket &dapPacket, byte d dapPacket.Sector = sector; byte function = write ? 0x43 : 0x42; - + BiosResult result; byte tryCount = TC_MAX_BIOS_DISK_IO_RETRIES; @@ -261,7 +261,7 @@ BiosResult ReadSectors (byte *buffer, byte drive, const uint64 §or, uint16 s BiosResult result; uint16 codeSeg; __asm mov codeSeg, cs - + result = ReadSectors (BootStarted ? codeSeg : TC_BOOT_LOADER_ALT_SEGMENT, (uint16) buffer, drive, sector, sectorCount, silent); // Alternative segment is used to prevent memory corruption caused by buggy BIOSes @@ -389,13 +389,13 @@ BiosResult GetDrivePartitions (byte drive, Partition *partitionArray, size_t par PartitionEntryMBR mbrPartitions[4]; memcpy (mbrPartitions, mbr->Partitions, sizeof (mbrPartitions)); size_t partitionArrayPos = 0, partitionNumber; - + for (partitionNumber = 0; partitionNumber < array_capacity (mbrPartitions) && partitionArrayPos < partitionArrayCapacity; ++partitionNumber) { const PartitionEntryMBR &partEntry = mbrPartitions[partitionNumber]; - + if (partEntry.SectorCountLBA > 0) { Partition &partition = partitionArray[partitionArrayPos]; @@ -486,6 +486,6 @@ bool GetActivePartition (byte drive) PrintError (TC_BOOT_STR_NO_BOOT_PARTITION); return false; } - + return true; } diff --git a/src/Boot/Windows/BootDiskIo.h b/src/Boot/Windows/BootDiskIo.h index b09220a8..ad9d1437 100644 --- a/src/Boot/Windows/BootDiskIo.h +++ b/src/Boot/Windows/BootDiskIo.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/BootEncryptedIo.cpp b/src/Boot/Windows/BootEncryptedIo.cpp index 84a4bf14..63fd0f47 100644 --- a/src/Boot/Windows/BootEncryptedIo.cpp +++ b/src/Boot/Windows/BootEncryptedIo.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/BootEncryptedIo.h b/src/Boot/Windows/BootEncryptedIo.h index 6402e705..d27ec9ea 100644 --- a/src/Boot/Windows/BootEncryptedIo.h +++ b/src/Boot/Windows/BootEncryptedIo.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/BootMain.cpp b/src/Boot/Windows/BootMain.cpp index 24acd23f..57697a4f 100644 --- a/src/Boot/Windows/BootMain.cpp +++ b/src/Boot/Windows/BootMain.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -72,7 +72,7 @@ static void PrintMainMenu () 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)"); @@ -184,7 +184,7 @@ static byte AskPassword (Password &password, int& pim) ClearBiosKeystrokeBuffer(); PrintEndl(); - + break; case TC_BIOS_KEY_BACKSPACE: @@ -262,7 +262,7 @@ static byte AskPassword (Password &password, int& pim) ClearBiosKeystrokeBuffer(); PrintEndl(); - + return TC_BIOS_KEY_ENTER; case TC_BIOS_KEY_BACKSPACE: @@ -301,7 +301,7 @@ static byte AskPassword (Password &password, int& pim) pim = 10*pim + (asciiCode - '0'); pos++; - + if (hidePassword) asciiCode = '*'; if (pos < MAX_PIM) PrintChar (asciiCode); @@ -343,7 +343,7 @@ static bool OpenVolume (byte drive, Password &password, int pim, CRYPTO_INFO **c int volumeType; bool hiddenVolume; uint64 headerSec; - + AcquireSectorBuffer(); for (volumeType = 1; volumeType <= 2; ++volumeType) @@ -479,7 +479,7 @@ static bool MountVolume (byte drive, byte &exitKey, bool skipNormal, bool skipHi EncryptedVirtualPartition.Drive = BootDrive; EncryptedVirtualPartition.StartSector = BootCryptoInfo->EncryptedAreaStart >> TC_LB_SIZE_BIT_SHIFT_DIVISOR; - + PimValueOrHiddenVolumeStartUnitNo = EncryptedVirtualPartition.StartSector; HiddenVolumeStartSector = PartitionFollowingActive.StartSector; HiddenVolumeStartSector += EncryptedVirtualPartition.StartSector; @@ -535,7 +535,7 @@ static byte BootEncryptedDrive () if (!MountVolume (BootDrive, exitKey, PreventNormalSystemBoot, false)) return exitKey; - + if (!CheckMemoryRequirements ()) goto err; @@ -765,7 +765,7 @@ static bool CopySystemPartitionToHiddenVolume (byte drive, byte &exitKey) EncryptDataUnits (SectorBuffer, &s, 1, BootCryptoInfo); CopyMemory (SectorBuffer, TC_BOOT_LOADER_BUFFER_SEGMENT, i * TC_LB_SIZE, TC_LB_SIZE); - } + } ReleaseSectorBuffer(); @@ -875,7 +875,7 @@ static void DecryptDrive (byte drive) DecryptDataUnits (SectorBuffer, &s, 1, BootCryptoInfo); CopyMemory (SectorBuffer, TC_BOOT_LOADER_BUFFER_SEGMENT, i * TC_LB_SIZE, TC_LB_SIZE); - } + } ReleaseSectorBuffer(); @@ -1250,7 +1250,7 @@ void main () exitKey = BootEncryptedDrive(); #else // TC_WINDOWS_BOOT_RESCUE_DISK_MODE - + PrintMainMenu(); exitKey = BootEncryptedDrive(); diff --git a/src/Boot/Windows/BootMain.h b/src/Boot/Windows/BootMain.h index 2f212a18..0f89179a 100644 --- a/src/Boot/Windows/BootMain.h +++ b/src/Boot/Windows/BootMain.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/BootMemory.cpp b/src/Boot/Windows/BootMemory.cpp index 505b731a..5729142f 100644 --- a/src/Boot/Windows/BootMemory.cpp +++ b/src/Boot/Windows/BootMemory.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -44,7 +44,7 @@ static bool GetMemoryMapEntry (BiosMemoryMapEntry &entry) push TC_BOOT_LOADER_ALT_SEGMENT pop es mov di, 0 - + int 0x15 jnc no_carry mov carry, true diff --git a/src/Boot/Windows/BootMemory.h b/src/Boot/Windows/BootMemory.h index d4ad1561..d08e88ac 100644 --- a/src/Boot/Windows/BootMemory.h +++ b/src/Boot/Windows/BootMemory.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/BootSector.asm b/src/Boot/Windows/BootSector.asm index 0518414f..833ff616 100644 --- a/src/Boot/Windows/BootSector.asm +++ b/src/Boot/Windows/BootSector.asm @@ -3,7 +3,7 @@ ; 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) +; 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 @@ -26,9 +26,9 @@ start: loader_name_msg: db ' VeraCrypt Boot Loader', 13, 10, 0 - + main: - cli + cli xor ax, ax mov ds, ax mov ss, ax @@ -49,12 +49,12 @@ skip_loader_name_msg: ; Check available memory cmp word ptr [ds:413h], TC_BOOT_LOADER_SEGMENT / 1024 * 16 + TC_BOOT_MEMORY_REQUIRED jge memory_ok - + mov ax, TC_BOOT_LOADER_SEGMENT_LOW - + cmp word ptr [ds:413h], TC_BOOT_LOADER_SEGMENT_LOW / 1024 * 16 + TC_BOOT_MEMORY_REQUIRED jge memory_ok - + ; Insufficient memory mov ax, TC_BOOT_LOADER_LOWMEM_SEGMENT @@ -67,11 +67,11 @@ memory_ok: mov cx, TC_BOOT_MEMORY_REQUIRED * 1024 - TC_COM_EXECUTABLE_OFFSET - 1 cld rep stosb - + mov ax, es sub ax, TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE / 16 ; Decompressor segment mov es, ax - + ; Load decompressor mov cl, TC_BOOT_LOADER_DECOMPRESSOR_START_SECTOR retry_backup: @@ -85,17 +85,17 @@ retry_backup: mov cx, TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_LB_SIZE call checksum push ebx - + ; Load compressed boot loader mov bx, TC_BOOT_LOADER_COMPRESSED_BUFFER_OFFSET mov cl, TC_BOOT_LOADER_START_SECTOR mov al, TC_MAX_BOOT_LOADER_SECTOR_COUNT - + test backup_loader_used, 1 jz non_backup mov al, TC_BOOT_LOADER_BACKUP_SECTOR_COUNT - TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT mov cl, TC_BOOT_LOADER_START_SECTOR + TC_BOOT_LOADER_BACKUP_SECTOR_COUNT - + non_backup: call read_sectors @@ -104,21 +104,21 @@ non_backup: mov si, TC_BOOT_LOADER_COMPRESSED_BUFFER_OFFSET mov cx, word ptr [start + TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET] call checksum - + ; Verify checksum - cmp ebx, dword ptr [start + TC_BOOT_SECTOR_LOADER_CHECKSUM_OFFSET] + cmp ebx, dword ptr [start + TC_BOOT_SECTOR_LOADER_CHECKSUM_OFFSET] je checksum_ok ; Checksum incorrect - try using backup if available test backup_loader_used, 1 jnz loader_damaged - + mov backup_loader_used, 1 mov cl, TC_BOOT_LOADER_DECOMPRESSOR_START_SECTOR + TC_BOOT_LOADER_BACKUP_SECTOR_COUNT - + test TC_BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE, byte ptr [start + TC_BOOT_SECTOR_CONFIG_OFFSET] jnz retry_backup - + loader_damaged: lea si, loader_damaged_msg call print @@ -134,9 +134,9 @@ checksum_ok: mov ss, ax mov sp, TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE sti - + push dx - + ; Decompress boot loader mov cx, word ptr [start + TC_BOOT_SECTOR_LOADER_LENGTH_OFFSET] sub cx, TC_GZIP_HEADER_SIZE @@ -154,7 +154,7 @@ decompressor_ret: add sp, 8 pop dx - + ; Restore boot sector segment push cs pop ds @@ -170,7 +170,7 @@ decompression_ok: ; DH = boot sector flags mov dh, byte ptr [start + TC_BOOT_SECTOR_CONFIG_OFFSET] - + ; Set up boot loader segment mov ax, es add ax, TC_BOOT_LOADER_DECOMPRESSOR_MEMORY_SIZE / 16 @@ -185,17 +185,17 @@ decompression_ok: push es push TC_COM_EXECUTABLE_OFFSET retf - + ; Print string print: xor bx, bx mov ah, 0eh cld - + @@: lodsb test al, al jz print_end - + int 10h jmp @B @@ -210,12 +210,12 @@ read_sectors: mov ah, 2 int 13h jnc read_ok - + lea si, disk_error_msg call print read_ok: ret - + ; Calculate checksum checksum: push ds @@ -223,17 +223,17 @@ checksum: pop ds xor eax, eax cld - + @@: lodsb add ebx, eax rol ebx, 1 loop @B - + pop ds ret backup_loader_used db 0 - + disk_error_msg db 'Disk error', 13, 10, 7, 0 loader_damaged_msg db 7, 'Loader damaged! Repair with Rescue Disk', 0 diff --git a/src/Boot/Windows/BootStrings.h b/src/Boot/Windows/BootStrings.h index 99c4dc4f..6c5d7847 100644 --- a/src/Boot/Windows/BootStrings.h +++ b/src/Boot/Windows/BootStrings.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/IntFilter.cpp b/src/Boot/Windows/IntFilter.cpp index d9cd92df..4a39fd14 100644 --- a/src/Boot/Windows/IntFilter.cpp +++ b/src/Boot/Windows/IntFilter.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -98,7 +98,7 @@ bool Int13Filter () if (ReEntryCount == 0 && drive == EncryptedVirtualPartition.Drive) { BiosResult result; - + if (function == 0x3) result = WriteEncryptedSectors (regs.ES, regs.BX, drive, sector, sectorCount); else @@ -126,7 +126,7 @@ bool Int13Filter () case 0x43: // Write sectors LBA { byte drive = (byte) regs.DX; - + BiosLbaPacket lba; CopyMemory (regs.DS, regs.SI, (byte *) &lba, sizeof (lba)); @@ -141,7 +141,7 @@ bool Int13Filter () if (ReEntryCount == 0 && drive == EncryptedVirtualPartition.Drive) { BiosResult result; - + uint16 segment = (uint16) (lba.Buffer >> 16); uint16 offset = (uint16) lba.Buffer; @@ -524,7 +524,7 @@ void IntFilterEntry () popf leave add sp, 2 - jmp cs:OriginalInt13Handler + jmp cs:OriginalInt13Handler pass15: popad @@ -554,7 +554,7 @@ static void Int15FilterEntry () pushf cmp ax, 0xe820 // Get system memory map je filter - + popf leave jmp cs:OriginalInt15Handler @@ -600,7 +600,7 @@ bool InstallInterruptFilters () // Save original INT 13 handler xor ax, ax mov es, ax - + mov si, 0x13 * 4 lea di, OriginalInt13Handler @@ -608,14 +608,14 @@ bool InstallInterruptFilters () mov [di], ax mov ax, es:[si + 2] mov [di + 2], ax - + // Install INT 13 filter lea ax, Int13FilterEntry mov es:[si], ax mov es:[si + 2], cs // Save original INT 15 handler - mov si, 0x15 * 4 + mov si, 0x15 * 4 lea di, OriginalInt15Handler mov ax, es:[si] diff --git a/src/Boot/Windows/IntFilter.h b/src/Boot/Windows/IntFilter.h index 1ef42512..3f3a486a 100644 --- a/src/Boot/Windows/IntFilter.h +++ b/src/Boot/Windows/IntFilter.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Boot/Windows/Makefile b/src/Boot/Windows/Makefile index 65e668cb..8377520b 100644 --- a/src/Boot/Windows/Makefile +++ b/src/Boot/Windows/Makefile @@ -3,7 +3,7 @@ # 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) +# 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 @@ -111,7 +111,7 @@ env: set INCLUDE=. set LIB=. set LIBPATH=. - + clean: -del /q /s $(OBJDIR) >NUL: @@ -133,7 +133,7 @@ clean: $(CC) $(CFLAGS) /c "$(SRCDIR)\$<" set PATH=$(ENVPATH) cd .. - + {..\..\Common}.c{$(OUTDIR)}.obj: cd $(OBJDIR) set PATH=. @@ -147,7 +147,7 @@ clean: $(CC) $(CFLAGS) /c "$(SRCDIR)\$<" set PATH=$(ENVPATH) cd .. - + .cpp{$(OUTDIR)}.obj: cd $(OBJDIR) set PATH=. @@ -161,7 +161,7 @@ $(OUTDIR)\BootDefs.i: BootDefs.h $(CC) $(CFLAGS) /D TC_ASM_PREPROCESS /P /EP "$(SRCDIR)\BootDefs.h" set PATH=$(ENVPATH) cd .. - + $(OUTDIR)\BootSector.bin: $(OUTDIR)\BootSector.obj cd $(OBJDIR) $(LD) $(LFLAGS) BootSector.obj,BootSector.bin,,,, >NUL: @@ -177,7 +177,7 @@ $(OUTDIR)\Decompressor.com: $(OUTDIR)\BootCrt.obj $(OUTDIR)\Decompressor.obj $(OUTDIR)\$(PROJ).$(TARGETEXT): $(OBJS) @echo Linking... cd $(OBJDIR) - + echo >NUL: @<<$(PROJ).crf2 $(PROJ).$(TARGETEXT) @@ -189,7 +189,7 @@ $(LIBS) del $(PROJ).crf >NUL: 2>NUL: for %F in ($(**F)) do @echo %F + >>$(PROJ).crf type $(PROJ).crf2 >>$(PROJ).crf - + $(LD) $(LFLAGS) @$(PROJ).crf del $(PROJ).crf $(PROJ).crf2 diff --git a/src/Boot/Windows/Platform.cpp b/src/Boot/Windows/Platform.cpp index 316e71b3..0a45bba6 100644 --- a/src/Boot/Windows/Platform.cpp +++ b/src/Boot/Windows/Platform.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -83,7 +83,7 @@ uint64 operator>> (const uint64 &a, int shiftCount) while (shiftCount--) { r.LowPart >>= 1; - + if ((byte) r.HighPart & 1) r.LowPart |= 0x80000000UL; @@ -96,7 +96,7 @@ uint64 operator>> (const uint64 &a, int shiftCount) uint64 operator<< (const uint64 &a, int shiftCount) { uint64 r = a; - + while (shiftCount--) r += r; @@ -148,9 +148,9 @@ bool TestInt64 () a += b; a -= b; - + ++a; - + b = b + (uint32) 1UL; c = (a - ((a + b) >> 32) - (uint32) 1UL); @@ -214,11 +214,11 @@ bool RegionsIntersect (const uint64 &start1, uint32 length1, const uint64 &start { uint64 end1 = start1 + length1 - 1UL; uint64 intersectEnd = (end1 <= end2) ? end1 : end2; - + uint64 intersectStart = (start1 >= start2) ? start1 : start2; if (intersectStart > intersectEnd) return false; - + return (intersectEnd + 1UL - intersectStart).LowPart != 0; } diff --git a/src/Boot/Windows/Platform.h b/src/Boot/Windows/Platform.h index 879b1c39..a8e83bec 100644 --- a/src/Boot/Windows/Platform.h +++ b/src/Boot/Windows/Platform.h @@ -3,7 +3,7 @@ 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) + 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 @@ -37,7 +37,7 @@ typedef UINT64_STRUCT uint64; #define TC_ASM_EMIT(A,B) __asm _emit 0x##A __asm _emit 0x##B #define TC_ASM_EMIT3(A,B,C) __asm _emit 0x##A __asm _emit 0x##B __asm _emit 0x##C -#define TC_ASM_EMIT4(A,B,C,D) __asm _emit 0x##A __asm _emit 0x##B __asm _emit 0x##C __asm _emit 0x##D +#define TC_ASM_EMIT4(A,B,C,D) __asm _emit 0x##A __asm _emit 0x##B __asm _emit 0x##C __asm _emit 0x##D #define TC_ASM_MOV_EAX_DI TC_ASM_EMIT3 (66, 8B, 05) #define TC_ASM_MOV_EBX_DI TC_ASM_EMIT3 (66, 8B, 1D) diff --git a/src/Build/Include/Makefile.inc b/src/Build/Include/Makefile.inc index 95d8ba60..35d1f29c 100644 --- a/src/Build/Include/Makefile.inc +++ b/src/Build/Include/Makefile.inc @@ -3,7 +3,7 @@ # 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) +# 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 @@ -53,7 +53,7 @@ TR_SED_BIN := tr '\n' ' ' | tr -s ' ' ',' | sed -e 's/^,//g' -e 's/,$$/n/' | tr %.txt.h: %.txt @echo Converting $($@ - + %.bmp.h: %.bmp @echo Converting $($@ diff --git a/src/Common/Apidrvr.h b/src/Common/Apidrvr.h index 5ea89770..9c16b378 100644 --- a/src/Common/Apidrvr.h +++ b/src/Common/Apidrvr.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Common/BaseCom.cpp b/src/Common/BaseCom.cpp index f6c55974..5905b6a8 100644 --- a/src/Common/BaseCom.cpp +++ b/src/Common/BaseCom.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Common/BaseCom.h b/src/Common/BaseCom.h index 97009410..a5b27473 100644 --- a/src/Common/BaseCom.h +++ b/src/Common/BaseCom.h @@ -3,7 +3,7 @@ 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) + 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 @@ -20,11 +20,11 @@ class TrueCryptFactory : public IClassFactory { public: - TrueCryptFactory (DWORD messageThreadId) : + TrueCryptFactory (DWORD messageThreadId) : RefCount (1), ServerLockCount (0), MessageThreadId (messageThreadId) { } ~TrueCryptFactory () { } - + virtual ULONG STDMETHODCALLTYPE AddRef () { return InterlockedIncrement (&RefCount) - 1; @@ -53,7 +53,7 @@ public: AddRef (); return S_OK; } - + virtual HRESULT STDMETHODCALLTYPE CreateInstance (IUnknown *pUnkOuter, REFIID riid, void **ppvObject) { if (pUnkOuter != NULL) diff --git a/src/Common/BootEncryption.cpp b/src/Common/BootEncryption.cpp index 73b64458..7148ca24 100644 --- a/src/Common/BootEncryption.cpp +++ b/src/Common/BootEncryption.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -44,7 +44,7 @@ namespace VeraCrypt class Elevator { public: - + static void AddReference () { ++ReferenceCount; @@ -193,7 +193,7 @@ namespace VeraCrypt { result = ERROR_OUTOFMEMORY; } - + if (result != ERROR_SUCCESS) { SetLastError (result); @@ -263,7 +263,7 @@ namespace VeraCrypt ElevatedComInstanceThreadId = GetCurrentThreadId(); } } - + #if defined (TCMOUNT) static ITrueCryptMainCom *ElevatedComInstance; #elif defined (VOLFORMAT) @@ -282,7 +282,7 @@ namespace VeraCrypt int Elevator::ReferenceCount = 0; #else // SETUP - + class Elevator { public: @@ -308,7 +308,7 @@ namespace VeraCrypt { FileOpen = true; } - else + else { LastError = GetLastError(); if (LastError == ERROR_ACCESS_DENIED && IsUacSupported()) @@ -436,7 +436,7 @@ namespace VeraCrypt { FileOpen = true; } - else + else { LastError = GetLastError (); if (LastError == ERROR_ACCESS_DENIED && IsUacSupported()) @@ -477,7 +477,7 @@ namespace VeraCrypt { if (RescueIsoImage) delete[] RescueIsoImage; - + Elevator::Release(); } @@ -516,7 +516,7 @@ namespace VeraCrypt 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 + // Find the first active partition on the system drive foreach (const Partition &partition, config.Partitions) { if (partition.Info.BootIndicator) @@ -558,11 +558,11 @@ namespace VeraCrypt } /* 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 + 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) { @@ -692,7 +692,7 @@ namespace VeraCrypt ProbeRealDriveSizeRequest request; StringCchCopyW (request.DeviceName, ARRAYSIZE (request.DeviceName), DriveConfig.DrivePartition.DevicePath.c_str()); - + CallDriver (TC_IOCTL_PROBE_REAL_DRIVE_SIZE, &request, sizeof (request), &request, sizeof (request)); DriveConfig.DrivePartition.Info.PartitionLength = request.RealDriveSize; @@ -787,7 +787,7 @@ namespace VeraCrypt return partList; } - + DISK_GEOMETRY BootEncryption::GetDriveGeometry (int driveNumber) { @@ -799,12 +799,12 @@ namespace VeraCrypt return geometry; } - + wstring BootEncryption::GetWindowsDirectory () { wchar_t buf[MAX_PATH]; throw_sys_if (GetSystemDirectory (buf, ARRAYSIZE (buf)) == 0); - + return wstring (buf); } @@ -827,7 +827,7 @@ namespace VeraCrypt // Note that this does not require admin rights (it just requires the driver to be running) bool BootEncryption::IsBootLoaderOnDrive (wchar_t *devicePath) { - try + try { OPEN_TEST_STRUCT openTestStruct; memset (&openTestStruct, 0, sizeof (openTestStruct)); @@ -871,7 +871,7 @@ namespace VeraCrypt bool BootEncryption::IsHiddenSystemRunning () { int hiddenSystemStatus; - + CallDriver (TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING, nullptr, 0, &hiddenSystemStatus, sizeof (hiddenSystemStatus)); return hiddenSystemStatus != 0; } @@ -1250,7 +1250,7 @@ namespace VeraCrypt if (userConfig) *userConfig = request.UserConfiguration; - + if (customUserMessage) { request.CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH] = 0; @@ -1267,7 +1267,7 @@ namespace VeraCrypt if (userConfig) *userConfig = 0; - + if (customUserMessage) customUserMessage->clear(); @@ -1326,7 +1326,7 @@ namespace VeraCrypt memcpy (mbr + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, customUserMessage.c_str(), customUserMessage.size()); } - + if (userConfig & TC_BOOT_USER_CFG_FLAG_DISABLE_PIM) { // PIM for pre-boot authentication can be encoded on two bytes since its maximum @@ -1386,7 +1386,7 @@ namespace VeraCrypt ZeroMemory (&request, sizeof (request)); request.WipeAlgorithm = wipeAlgorithm; - + if (Randinit() != ERR_SUCCESS) { if (CryptoAPILastError == ERROR_SUCCESS) @@ -1414,7 +1414,7 @@ namespace VeraCrypt CallDriver (TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE); } - + DecoySystemWipeStatus BootEncryption::GetDecoyOSWipeStatus () { DecoySystemWipeStatus status; @@ -1448,7 +1448,7 @@ namespace VeraCrypt device.SeekAt (0); device.Read (mbr, sizeof (mbr)); - + finally_do_arg (BootEncryption *, this, { try @@ -1594,7 +1594,7 @@ namespace VeraCrypt WCHAR pathBuf[MAX_PATH]; throw_sys_if (!SUCCEEDED (SHGetFolderPath (NULL, CSIDL_COMMON_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, pathBuf))); - + wstring path = wstring (pathBuf) + L"\\" _T(TC_APP_NAME); CreateDirectory (path.c_str(), NULL); @@ -1624,7 +1624,7 @@ namespace VeraCrypt throw ParameterIncorrect (SRC_POS); Buffer imageBuf (RescueIsoImageSize); - + byte *image = imageBuf.Ptr(); memset (image, 0, RescueIsoImageSize); @@ -1721,7 +1721,7 @@ namespace VeraCrypt File sysBakFile (GetSystemLoaderBackupPath(), true); sysBakFile.CheckOpened (SRC_POS); 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) @@ -1729,7 +1729,7 @@ namespace VeraCrypt e.Show (ParentWindow); Warning ("SYS_LOADER_UNAVAILABLE_FOR_RESCUE_DISK", ParentWindow); } - + // Boot loader backup CreateBootLoaderInMemory (image + TC_CD_BOOTSECTOR_OFFSET + TC_BOOT_LOADER_BACKUP_RESCUE_DISK_SECTOR_OFFSET, TC_BOOT_LOADER_AREA_SIZE, false); @@ -1777,7 +1777,7 @@ namespace VeraCrypt UINT driveType = GetDriveType (rootPath); // check that it is a CD/DVD drive or a removable media in case a bootable // USB key was created from the rescue disk ISO file - if ((DRIVE_CDROM == driveType) || (DRIVE_REMOVABLE == driveType)) + if ((DRIVE_CDROM == driveType) || (DRIVE_REMOVABLE == driveType)) { rootPath[2] = 0; // remove trailing backslash @@ -1813,7 +1813,7 @@ namespace VeraCrypt Buffer buffer ((verifiedSectorCount + 1) * 2048); DWORD bytesRead = isoFile.Read (buffer.Ptr(), (DWORD) buffer.Size()); - if ( (bytesRead == buffer.Size()) + if ( (bytesRead == buffer.Size()) && (memcmp (buffer.Ptr(), RescueIsoImage, buffer.Size()) == 0) ) { @@ -2187,7 +2187,7 @@ namespace VeraCrypt { if (nCurrentOS == WIN_2000) throw ErrorException ("SYS_ENCRYPTION_UNSUPPORTED_ON_CURRENT_OS", SRC_POS); - + if (CurrentOSMajor == 6 && CurrentOSMinor == 0 && CurrentOSServicePack < 1) throw ErrorException ("SYS_ENCRYPTION_UNSUPPORTED_ON_VISTA_SP0", SRC_POS); @@ -2272,7 +2272,7 @@ namespace VeraCrypt if (!pagingFilesOk) { - if (AskWarnYesNoString ((wchar_t *) (wstring (GetString ("PAGING_FILE_NOT_ON_SYS_PARTITION")) + if (AskWarnYesNoString ((wchar_t *) (wstring (GetString ("PAGING_FILE_NOT_ON_SYS_PARTITION")) + GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION") + L"\n\n\n" + GetString ("RESTRICT_PAGING_FILES_TO_SYS_PARTITION") @@ -2283,7 +2283,7 @@ namespace VeraCrypt AbortProcessSilent(); } - throw ErrorException (wstring (GetString ("PAGING_FILE_NOT_ON_SYS_PARTITION")) + throw ErrorException (wstring (GetString ("PAGING_FILE_NOT_ON_SYS_PARTITION")) + GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION"), SRC_POS); } @@ -2291,14 +2291,14 @@ namespace VeraCrypt wchar_t *configPath = GetConfigPath (L"dummy"); if (configPath && towupper (configPath[0]) != windowsDrive) { - throw ErrorException (wstring (GetString ("USER_PROFILE_NOT_ON_SYS_PARTITION")) + throw ErrorException (wstring (GetString ("USER_PROFILE_NOT_ON_SYS_PARTITION")) + GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION"), SRC_POS); } // Temporary files if (towupper (GetTempPathString()[0]) != windowsDrive) { - throw ErrorException (wstring (GetString ("TEMP_NOT_ON_SYS_PARTITION")) + throw ErrorException (wstring (GetString ("TEMP_NOT_ON_SYS_PARTITION")) + GetString ("LEAKS_OUTSIDE_SYSPART_UNIVERSAL_EXPLANATION"), SRC_POS); } } @@ -2414,7 +2414,7 @@ namespace VeraCrypt device.Read ((byte *) header, sizeof (header)); PCRYPTO_INFO cryptoInfo = NULL; - + int status = ReadVolumeHeader (!encStatus.HiddenSystem, header, oldPassword, old_pkcs5, old_pim, FALSE, &cryptoInfo, NULL); finally_do_arg (PCRYPTO_INFO, cryptoInfo, { if (finally_arg) crypto_close (finally_arg); }); @@ -2447,7 +2447,7 @@ namespace VeraCrypt UserEnrichRandomPool (hwndDlg); WaitCursor(); - /* The header will be re-encrypted wipePassCount times to prevent adversaries from using + /* The header will be re-encrypted wipePassCount times to prevent adversaries from using techniques such as magnetic force microscopy or magnetic force scanning tunnelling microscopy to recover the overwritten header. According to Peter Gutmann, data should be overwritten 22 times (ideally, 35 times) using non-random patterns and pseudorandom data. However, as users might @@ -2663,7 +2663,7 @@ namespace VeraCrypt SelectedEncryptionAlgorithmId = ea; SelectedPrfAlgorithmId = pkcs5; CreateVolumeHeader (volumeSize, encryptedAreaStart, &password, ea, mode, pkcs5, pim); - + if (!rescueIsoImagePath.empty()) CreateRescueIsoImage (true, rescueIsoImagePath); } @@ -2705,7 +2705,7 @@ namespace VeraCrypt BootEncryptionSetupRequest request; ZeroMemory (&request, sizeof (request)); - + request.SetupMode = SetupDecryption; request.DiscardUnreadableEncryptedSectors = discardUnreadableEncryptedSectors; @@ -2721,7 +2721,7 @@ namespace VeraCrypt BootEncryptionSetupRequest request; ZeroMemory (&request, sizeof (request)); - + request.SetupMode = SetupEncryption; request.WipeAlgorithm = wipeAlgorithm; request.ZeroUnreadableSectors = zeroUnreadableSectors; diff --git a/src/Common/BootEncryption.h b/src/Common/BootEncryption.h index a89b2ec6..d75b650c 100644 --- a/src/Common/BootEncryption.h +++ b/src/Common/BootEncryption.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Common/Cache.c b/src/Common/Cache.c index ba6c6df8..e5b36590 100644 --- a/src/Common/Cache.c +++ b/src/Common/Cache.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Common/Cache.h b/src/Common/Cache.h index c4587d03..1cadf79d 100644 --- a/src/Common/Cache.h +++ b/src/Common/Cache.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -15,7 +15,7 @@ #ifndef CACHE_SIZE /* WARNING: Changing this value might not be safe (some items may be hard coded for 4)! Inspection necessary. */ -#define CACHE_SIZE 4 +#define CACHE_SIZE 4 #endif extern int cacheEmpty; diff --git a/src/Common/Cmdline.c b/src/Common/Cmdline.c index 4a055c16..e5fe5969 100644 --- a/src/Common/Cmdline.c +++ b/src/Common/Cmdline.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -74,7 +74,7 @@ BOOL CALLBACK CommandHelpDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM StringCchCatW (tmp, 8192, L"\nExamples:\n\nMount a volume as X:\tveracrypt.exe /q /v volume.hc /l X\nDismount a volume X:\tveracrypt.exe /q /d X"); SetWindowTextW (GetDlgItem (hwndDlg, IDC_COMMANDHELP_TEXT), tmp); - + TCfree(tmp); return 1; } diff --git a/src/Common/Cmdline.h b/src/Common/Cmdline.h index 51c173c6..09e59924 100644 --- a/src/Common/Cmdline.h +++ b/src/Common/Cmdline.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Common/Combo.c b/src/Common/Combo.c index fe456853..50e9761c 100644 --- a/src/Common/Combo.c +++ b/src/Common/Combo.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -171,7 +171,7 @@ void LoadCombo (HWND hComboBox, BOOL bEnabled, BOOL bOnlyCheckModified, BOOL *pb { wchar_t szTmp[MAX_PATH] = { 0 }; wchar_t wszVolume[MAX_PATH] = {0}; - + if (i < count) { if (SendMessage (hComboBox, CB_GETLBTEXTLEN, nComboIdx[i], 0) < ARRAYSIZE (szTmp)) @@ -225,7 +225,7 @@ void DumpCombo (HWND hComboBox, int bClear) for (i = 0; i < SIZEOF_MRU_LIST; i++) { wchar_t szTmp[MAX_PATH] = { 0 }; - + if (SendMessage (hComboBox, CB_GETLBTEXTLEN, nComboIdx[i], 0) < ARRAYSIZE (szTmp)) SendMessage (hComboBox, CB_GETLBTEXT, nComboIdx[i], (LPARAM) & szTmp[0]); diff --git a/src/Common/Combo.h b/src/Common/Combo.h index cacbc413..4f85c6bd 100644 --- a/src/Common/Combo.h +++ b/src/Common/Combo.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Common/Common.h b/src/Common/Common.h index 05e2e12f..cd88882f 100644 --- a/src/Common/Common.h +++ b/src/Common/Common.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Common/Common.rc b/src/Common/Common.rc index 1e529c63..b84fba8e 100644 --- a/src/Common/Common.rc +++ b/src/Common/Common.rc @@ -337,7 +337,7 @@ END // #ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO +GUIDELINES DESIGNINFO BEGIN IDD_ABOUT_DLG, DIALOG BEGIN @@ -547,18 +547,18 @@ IDR_LICENSE TEXT "..\\Resources\\Texts\\License.r // TEXTINCLUDE // -1 TEXTINCLUDE +1 TEXTINCLUDE BEGIN "resource.h\0" END -2 TEXTINCLUDE +2 TEXTINCLUDE BEGIN "#include ""afxres.h""\r\n" "\0" END -3 TEXTINCLUDE +3 TEXTINCLUDE BEGIN "\r\n" "\0" diff --git a/src/Common/Crc.c b/src/Common/Crc.c index ba8777e6..5a73fc86 100644 --- a/src/Common/Crc.c +++ b/src/Common/Crc.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -19,7 +19,7 @@ /* CRC polynomial 0x04c11db7 */ unsigned __int32 crc_32_tab[]= -{ +{ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, diff --git a/src/Common/Crc.h b/src/Common/Crc.h index c89a6191..c5be1778 100644 --- a/src/Common/Crc.h +++ b/src/Common/Crc.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Common/Crypto.c b/src/Common/Crypto.c index a524fd97..e5a3218e 100644 --- a/src/Common/Crypto.c +++ b/src/Common/Crypto.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -129,7 +129,7 @@ int CipherInit (int cipher, unsigned char *key, unsigned __int8 *ks) case SERPENT: serpent_set_key (key, ks); break; - + case TWOFISH: twofish_set_key ((TwofishInstance *)ks, (const u4byte *)key); break; @@ -146,7 +146,7 @@ void EncipherBlock(int cipher, void *data, void *ks) { switch (cipher) { - case AES: + case AES: // In 32-bit kernel mode, due to KeSaveFloatingPointState() overhead, AES instructions can be used only when processing the whole data unit. #if (defined (_WIN64) || !defined (TC_WINDOWS_DRIVER)) && !defined (TC_WINDOWS_BOOT) if (IsAesHwCpuSupported()) @@ -399,11 +399,11 @@ BOOL EAInitMode (PCRYPTO_INFO ci) /* Note: XTS mode could potentially be initialized with a weak key causing all blocks in one data unit on the volume to be tweaked with zero tweaks (i.e. 512 bytes of the volume would be encrypted in ECB mode). However, to create a TrueCrypt volume with such a weak key, each human being on Earth would have - to create approximately 11,378,125,361,078,862 (about eleven quadrillion) TrueCrypt volumes (provided + to create approximately 11,378,125,361,078,862 (about eleven quadrillion) TrueCrypt volumes (provided that the size of each of the volumes is 1024 terabytes). */ break; - default: + default: // Unknown/wrong ID TC_THROW_FATAL_EXCEPTION; } @@ -488,7 +488,7 @@ int EAGetNextMode (int ea, int previousModeId) int c, i = 0; while (c = EncryptionAlgorithms[ea].Modes[i++]) { - if (c == previousModeId) + if (c == previousModeId) return EncryptionAlgorithms[ea].Modes[i]; } @@ -591,7 +591,7 @@ int EAGetNextCipher (int ea, int previousCipherId) int c, i = 0; while (c = EncryptionAlgorithms[ea].Ciphers[i++]) { - if (c == previousCipherId) + if (c == previousCipherId) return EncryptionAlgorithms[ea].Ciphers[i]; } @@ -608,7 +608,7 @@ int EAGetPreviousCipher (int ea, int previousCipherId) while (c = EncryptionAlgorithms[ea].Ciphers[i++]) { - if (c == previousCipherId) + if (c == previousCipherId) return EncryptionAlgorithms[ea].Ciphers[i - 2]; } @@ -777,7 +777,7 @@ void crypto_close (PCRYPTO_INFO cryptoInfo) // EncryptBuffer // // buf: data to be encrypted; the start of the buffer is assumed to be aligned with the start of a data unit. -// len: number of bytes to encrypt; must be divisible by the block size (for cascaded ciphers, divisible +// len: number of bytes to encrypt; must be divisible by the block size (for cascaded ciphers, divisible // by the largest block size used within the cascade) void EncryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo) { @@ -808,7 +808,7 @@ void EncryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_ } break; - default: + default: // Unknown/wrong ID TC_THROW_FATAL_EXCEPTION; } @@ -850,7 +850,7 @@ void EncryptDataUnitsCurrentThread (unsigned __int8 *buf, const UINT64_STRUCT *s } break; - default: + default: // Unknown/wrong ID TC_THROW_FATAL_EXCEPTION; } @@ -859,7 +859,7 @@ void EncryptDataUnitsCurrentThread (unsigned __int8 *buf, const UINT64_STRUCT *s // DecryptBuffer // // buf: data to be decrypted; the start of the buffer is assumed to be aligned with the start of a data unit. -// len: number of bytes to decrypt; must be divisible by the block size (for cascaded ciphers, divisible +// len: number of bytes to decrypt; must be divisible by the block size (for cascaded ciphers, divisible // by the largest block size used within the cascade) void DecryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_INFO cryptoInfo) { @@ -890,7 +890,7 @@ void DecryptBuffer (unsigned __int8 *buf, TC_LARGEST_COMPILER_UINT len, PCRYPTO_ } break; - default: + default: // Unknown/wrong ID TC_THROW_FATAL_EXCEPTION; } @@ -935,7 +935,7 @@ void DecryptDataUnitsCurrentThread (unsigned __int8 *buf, const UINT64_STRUCT *s } break; - default: + default: // Unknown/wrong ID TC_THROW_FATAL_EXCEPTION; } @@ -955,7 +955,7 @@ void EncipherBlock(int cipher, void *data, void *ks) if (IsAesHwCpuSupported()) aes_hw_cpu_encrypt ((byte *) ks, data); else - aes_encrypt (data, data, ks); + aes_encrypt (data, data, ks); #elif defined (TC_WINDOWS_BOOT_SERPENT) serpent_encrypt (data, data, ks); #elif defined (TC_WINDOWS_BOOT_TWOFISH) @@ -969,7 +969,7 @@ void DecipherBlock(int cipher, void *data, void *ks) if (IsAesHwCpuSupported()) aes_hw_cpu_decrypt ((byte *) ks + sizeof (aes_encrypt_ctx) + 14 * 16, data); else - aes_decrypt (data, data, (aes_decrypt_ctx *) ((byte *) ks + sizeof(aes_encrypt_ctx))); + aes_decrypt (data, data, (aes_decrypt_ctx *) ((byte *) ks + sizeof(aes_encrypt_ctx))); #elif defined (TC_WINDOWS_BOOT_SERPENT) serpent_decrypt (data, data, ks); #elif defined (TC_WINDOWS_BOOT_TWOFISH) diff --git a/src/Common/Crypto.h b/src/Common/Crypto.h index 96f0a9a6..5d9fff97 100644 --- a/src/Common/Crypto.h +++ b/src/Common/Crypto.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -45,9 +45,9 @@ extern "C" { #define MASTER_KEYDATA_SIZE 256 // The first PRF to try when mounting -#define FIRST_PRF_ID 1 +#define FIRST_PRF_ID 1 -// Hash algorithms (pseudorandom functions). +// Hash algorithms (pseudorandom functions). enum { SHA512 = FIRST_PRF_ID, @@ -58,7 +58,7 @@ enum }; // The last PRF to try when mounting and also the number of implemented PRFs -#define LAST_PRF_ID (HASH_ENUM_END_ID - 1) +#define LAST_PRF_ID (HASH_ENUM_END_ID - 1) #define RIPEMD160_BLOCKSIZE 64 #define RIPEMD160_DIGESTSIZE 20 @@ -105,7 +105,7 @@ enum { NONE = 0, AES, - SERPENT, + SERPENT, TWOFISH }; @@ -221,12 +221,12 @@ typedef struct CRYPTO_INFO_t #ifndef TC_WINDOWS_BOOT uint16 HeaderVersion; - GfCtx gf_ctx; + GfCtx gf_ctx; unsigned __int8 master_keydata[MASTER_KEYDATA_SIZE]; /* This holds the volume header area containing concatenated master key(s) and secondary key(s) (XTS mode). For LRW (deprecated/legacy), it contains the tweak key before the master key(s). For CBC (deprecated/legacy), it contains the IV seed before the master key(s). */ unsigned __int8 k2[MASTER_KEYDATA_SIZE]; /* For XTS, this contains the secondary key (if cascade, multiple concatenated). For LRW (deprecated/legacy), it contains the tweak key. For CBC (deprecated/legacy), it contains the IV seed. */ unsigned __int8 salt[PKCS5_SALT_SIZE]; - int noIterations; + int noIterations; BOOL bTrueCryptMode; int volumePim; @@ -235,7 +235,7 @@ typedef struct CRYPTO_INFO_t BOOL bProtectHiddenVolume; // Indicates whether the volume contains a hidden volume to be protected against overwriting BOOL bHiddenVolProtectionAction; // TRUE if a write operation has been denied by the driver in order to prevent the hidden volume from being overwritten (set to FALSE upon volume mount). - + uint64 volDataAreaOffset; // Absolute position, in bytes, of the first data sector of the volume. uint64 hiddenVolumeSize; // Size of the hidden volume excluding the header (in bytes). Set to 0 for standard volumes. diff --git a/src/Common/Dictionary.c b/src/Common/Dictionary.c index 34741951..c6135e3e 100644 --- a/src/Common/Dictionary.c +++ b/src/Common/Dictionary.c @@ -3,7 +3,7 @@ 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) + 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 @@ -41,7 +41,7 @@ void AddDictionaryEntry (char *key, int intKey, void *value) void *GetDictionaryValue (const char *key) { map ::const_iterator i = StringKeyMap.find (key); - + if (i == StringKeyMap.end()) return NULL; diff --git a/src/Common/Dictionary.h b/src/Common/Dictionary.h index 0fa9c7ee..97c7938c 100644 --- a/src/Common/Dictionary.h +++ b/src/Common/Dictionary.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Common/Dlgcode.c b/src/Common/Dlgcode.c index ef6a942f..fd2601b4 100644 --- a/src/Common/Dlgcode.c +++ b/src/Common/Dlgcode.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -113,9 +113,9 @@ BOOL bMountFavoritesOnLogon = FALSE; BOOL bHistory = FALSE; -// Status of detection of hidden sectors (whole-system-drive encryption). +// Status of detection of hidden sectors (whole-system-drive encryption). // 0 - Unknown/undetermined/completed, 1: Detection is or was in progress (but did not complete e.g. due to system crash). -int HiddenSectorDetectionStatus = 0; +int HiddenSectorDetectionStatus = 0; OSVersionEnum nCurrentOS = WIN_UNKNOWN; int CurrentOSMajor = 0; @@ -128,7 +128,7 @@ BOOL bPortableModeConfirmed = FALSE; // TRUE if it is certain that the instance BOOL bInPlaceEncNonSysPending = FALSE; // TRUE if the non-system in-place encryption config file indicates that one or more partitions are scheduled to be encrypted. This flag is set only when config files are loaded during app startup. -/* Globals used by Mount and Format (separately per instance) */ +/* Globals used by Mount and Format (separately per instance) */ BOOL PimEnable = FALSE; BOOL KeyFilesEnable = FALSE; KeyFile *FirstKeyFile = NULL; @@ -147,7 +147,7 @@ BOOL WaitDialogDisplaying = FALSE; HANDLE hDriver = INVALID_HANDLE_VALUE; /* This mutex is used to prevent multiple instances of the wizard or main app from dealing with system encryption */ -volatile HANDLE hSysEncMutex = NULL; +volatile HANDLE hSysEncMutex = NULL; /* This mutex is used for non-system in-place encryption but only for informative (non-blocking) purposes, such as whether an app should prompt the user whether to resume scheduled process. */ @@ -171,7 +171,7 @@ ATOM hDlgClass, hSplashClass; /* This value may changed only by calling ChangeSystemEncryptionStatus(). Only the wizard can change it (others may still read it though). */ -int SystemEncryptionStatus = SYSENC_STATUS_NONE; +int SystemEncryptionStatus = SYSENC_STATUS_NONE; /* Only the wizard can change this value (others may only read it). */ WipeAlgorithmId nWipeMode = TC_WIPE_NONE; @@ -294,13 +294,13 @@ ChangeWindowMessageFilterPtr ChangeWindowMessageFilterFn = NULL; #error PKCS5_BENCHMARKS and HASH_FNC_BENCHMARKS are both TRUE (at least one of them should be FALSE). #endif -enum +enum { BENCHMARK_SORT_BY_NAME = 0, BENCHMARK_SORT_BY_SPEED }; -typedef struct +typedef struct { int id; wchar_t name[100]; @@ -319,7 +319,7 @@ LARGE_INTEGER benchmarkPerformanceFrequency; #endif // #ifndef SETUP -typedef struct +typedef struct { void *strings; BOOL bold; @@ -356,7 +356,7 @@ void cleanup () /* Close the device driver handle */ if (hDriver != INVALID_HANDLE_VALUE) { - // Unload driver mode if possible (non-install mode) + // Unload driver mode if possible (non-install mode) if (IsNonInstallMode ()) { // If a dismount was forced in the lifetime of the driver, Windows may later prevent it to be loaded again from @@ -710,7 +710,7 @@ BOOL IsDiskError (DWORD error) DWORD handleWin32Error (HWND hwndDlg, const char* srcPos) { PWSTR lpMsgBuf; - DWORD dwError = GetLastError (); + DWORD dwError = GetLastError (); wchar_t szErrorValue[32]; wchar_t* pszDesc; @@ -833,7 +833,7 @@ int GetTextGfxWidth (HWND hwndDlgItem, const wchar_t *text, HFONT hFont) { SIZE sizes; TEXTMETRIC textMetrics; - HDC hdc = GetDC (hwndDlgItem); + HDC hdc = GetDC (hwndDlgItem); SelectObject(hdc, (HGDIOBJ) hFont); @@ -841,7 +841,7 @@ int GetTextGfxWidth (HWND hwndDlgItem, const wchar_t *text, HFONT hFont) GetTextMetrics(hdc, &textMetrics); // Necessary for non-TrueType raster fonts (tmOverhang) - ReleaseDC (hwndDlgItem, hdc); + ReleaseDC (hwndDlgItem, hdc); return ((int) sizes.cx - (int) textMetrics.tmOverhang); } @@ -850,13 +850,13 @@ int GetTextGfxWidth (HWND hwndDlgItem, const wchar_t *text, HFONT hFont) int GetTextGfxHeight (HWND hwndDlgItem, const wchar_t *text, HFONT hFont) { SIZE sizes; - HDC hdc = GetDC (hwndDlgItem); + HDC hdc = GetDC (hwndDlgItem); SelectObject(hdc, (HGDIOBJ) hFont); GetTextExtentPoint32W (hdc, text, (int) wcslen (text), &sizes); - ReleaseDC (hwndDlgItem, hdc); + ReleaseDC (hwndDlgItem, hdc); return ((int) sizes.cy); } @@ -872,7 +872,7 @@ std::wstring FitPathInGfxWidth (HWND hwnd, HFONT hFont, LONG width, const std::w rect.right = width; rect.bottom = LONG_MAX; - HDC hdc = GetDC (hwnd); + HDC hdc = GetDC (hwnd); SelectObject (hdc, (HGDIOBJ) hFont); wchar_t pathBuf[TC_MAX_PATH]; @@ -881,7 +881,7 @@ std::wstring FitPathInGfxWidth (HWND hwnd, HFONT hFont, LONG width, const std::w if (DrawText (hdc, pathBuf, (int) path.size(), &rect, DT_CALCRECT | DT_MODIFYSTRING | DT_PATH_ELLIPSIS | DT_SINGLELINE) != 0) newPath = pathBuf; - ReleaseDC (hwnd, hdc); + ReleaseDC (hwnd, hdc); return newPath; } @@ -961,12 +961,12 @@ void AccommodateTextField (HWND hwndDlg, UINT ctrlId, BOOL bFirstUpdate, HFONT h width = GetTextGfxWidth (hwndCtrl, text, hFont); height = GetTextGfxHeight (hwndCtrl, text, hFont); - GetClientRect (hwndCtrl, &rec); + GetClientRect (hwndCtrl, &rec); origWidth = rec.right; origHeight = rec.bottom; if (width >= 0 - && (!bFirstUpdate || origWidth > width)) // The original width of the field is the maximum allowed size + && (!bFirstUpdate || origWidth > width)) // The original width of the field is the maximum allowed size { horizSubOffset = origWidth - width; vertSubOffset = origHeight - height; @@ -989,7 +989,7 @@ void AccommodateTextField (HWND hwndDlg, UINT ctrlId, BOOL bFirstUpdate, HFONT h alignPosDiff = horizSubOffset / 2; else if (windowInfo.dwStyle & SS_RIGHT) alignPosDiff = horizSubOffset; - + // Resize/move if (alignPosDiff > 0) { @@ -1044,7 +1044,7 @@ static LRESULT CALLBACK BootPwdFieldProc (HWND hwnd, UINT message, WPARAM wParam // Protects an input field from having its content updated by a Paste action. Used for pre-boot password -// input fields (only the US keyboard layout is supported in pre-boot environment so we must prevent the +// input fields (only the US keyboard layout is supported in pre-boot environment so we must prevent the // user from pasting a password typed using a non-US keyboard layout). void ToBootPwdField (HWND hwndDlg, UINT ctrlId) { @@ -1071,7 +1071,7 @@ BOOL CALLBACK AuxiliaryDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lP if (hDC) { ScreenDPI = GetDeviceCaps (hDC, LOGPIXELSY); - ReleaseDC (hwndDlg, hDC); + ReleaseDC (hwndDlg, hDC); } DPIScaleFactorX = 1; @@ -1080,7 +1080,7 @@ BOOL CALLBACK AuxiliaryDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lP if (ScreenDPI != USER_DEFAULT_SCREEN_DPI) { - // Windows skews the GUI aspect ratio if the user has a non-default DPI. Hence, working with + // Windows skews the GUI aspect ratio if the user has a non-default DPI. Hence, working with // actual screen DPI is redundant and leads to incorrect results. What really matters here is // how Windows actually renders our GUI. This is determined by comparing the expected and current // sizes of a hidden calibration text field. @@ -1139,7 +1139,7 @@ BOOL CALLBACK AboutDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam GetClientRect (GetDlgItem (hwndDlg, IDC_ABOUT_LOGO_AREA), &rec); SetWindowPos (GetDlgItem (hwndDlg, IDC_ABOUT_BKG), HWND_TOP, 0, 0, rec.right, rec.bottom, SWP_NOMOVE); - // Resize the logo bitmap if the user has a non-default DPI + // Resize the logo bitmap if the user has a non-default DPI if (ScreenDPI != USER_DEFAULT_SCREEN_DPI) { // Logo (must recreate and keep the original aspect ratio as Windows distorts it) @@ -1455,7 +1455,7 @@ void InitDialog (HWND hwndDlg) void ProcessPaintMessages (HWND hwnd, int maxMessagesToProcess) { MSG paintMsg; - int msgCounter = maxMessagesToProcess; + int msgCounter = maxMessagesToProcess; while (PeekMessageW (&paintMsg, hwnd, 0, 0, PM_REMOVE | PM_QS_PAINT) != 0 && msgCounter-- > 0) { @@ -1483,16 +1483,16 @@ HDC CreateMemBitmap (HINSTANCE hInstance, HWND hwnd, wchar_t *resource) } -/* Renders the specified bitmap at the specified location and stretches it to fit (anti-aliasing is applied). +/* Renders the specified bitmap at the specified location and stretches it to fit (anti-aliasing is applied). If bDirectRender is FALSE and both nWidth and nHeight are zero, the width and height of hwndDest are retrieved and adjusted according to screen DPI (the width and height of the resultant image are adjusted the same way); furthermore, if bKeepAspectRatio is TRUE, the smaller DPI factor of the two (i.e. horiz. or vert.) is used both for horiz. and vert. scaling (note that the overall GUI aspect ratio changes irregularly in -both directions depending on the DPI). If bDirectRender is TRUE, bKeepAspectRatio is ignored. +both directions depending on the DPI). If bDirectRender is TRUE, bKeepAspectRatio is ignored. This function returns a handle to the scaled bitmap. When the bitmap is no longer needed, it should be -deleted by calling DeleteObject() with the handle passed as the parameter. -Known Windows issues: -- For some reason, anti-aliasing is not applied if the source bitmap contains less than 16K pixels. +deleted by calling DeleteObject() with the handle passed as the parameter. +Known Windows issues: +- For some reason, anti-aliasing is not applied if the source bitmap contains less than 16K pixels. - Windows 2000 may produce slightly inaccurate colors even when source, buffer, and target are 24-bit true color. */ HBITMAP RenderBitmap (wchar_t *resource, HWND hwndDest, int x, int y, int nWidth, int nHeight, BOOL bDirectRender, BOOL bKeepAspectRatio) { @@ -1541,11 +1541,11 @@ HBITMAP RenderBitmap (wchar_t *resource, HWND hwndDest, int x, int y, int nWidth GetObject (picture, sizeof (BITMAP), &bitmap); - hdcRescaled = CreateCompatibleDC (hdcSrc); + hdcRescaled = CreateCompatibleDC (hdcSrc); if (hdcRescaled) { - hbmpRescaled = CreateCompatibleBitmap (hdcSrc, nWidth, nHeight); + hbmpRescaled = CreateCompatibleBitmap (hdcSrc, nWidth, nHeight); SelectObject (hdcRescaled, hbmpRescaled); @@ -1561,7 +1561,7 @@ HBITMAP RenderBitmap (wchar_t *resource, HWND hwndDest, int x, int y, int nWidth hdcSrc, 0, 0, - bitmap.bmWidth, + bitmap.bmWidth, bitmap.bmHeight, SRCCOPY); @@ -1670,8 +1670,8 @@ RegisterRedTick (HINSTANCE hInstance) wc.hCursor = NULL; wc.hbrBackground = (HBRUSH) GetStockObject (LTGRAY_BRUSH); wc.lpszClassName = L"VCREDTICK"; - wc.lpfnWndProc = &RedTick; - + wc.lpfnWndProc = &RedTick; + rc = (ULONG) RegisterClassW (&wc); return rc == 0 ? FALSE : TRUE; @@ -1788,7 +1788,7 @@ void PopulateWipeModeCombo (HWND hComboBox, BOOL bNA, BOOL bInPlaceEncryption, B { if (!bHeaderWipe) { - AddComboPair (hComboBox, GetString ("WIPE_MODE_NONE"), TC_WIPE_NONE); + AddComboPair (hComboBox, GetString ("WIPE_MODE_NONE"), TC_WIPE_NONE); } AddComboPair (hComboBox, GetString ("WIPE_MODE_1_RAND"), TC_WIPE_1_RAND); @@ -2055,7 +2055,7 @@ void ExceptionHandlerThread (void *threadArg) else lpack[0] = 0; - + sprintf (url, TC_APPLINK_SECURE "&dest=err-report%s&os=%s&osver=%d.%d.%d&arch=%s&cpus=%d&app=%s&cksum=%x&dlg=%s&err=%x&addr=%x" , lpack , GetWindowsEdition().c_str() @@ -2124,7 +2124,7 @@ static LRESULT CALLBACK NonInstallUacWndProc (HWND hWnd, UINT message, WPARAM wP // Mutex handling to prevent multiple instances of the wizard or main app from dealing with system encryption. -// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). +// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). BOOL CreateSysEncMutex (void) { return TCCreateMutex (&hSysEncMutex, TC_MUTEX_NAME_SYSENC); @@ -2144,7 +2144,7 @@ void CloseSysEncMutex (void) } -// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). +// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). BOOL CreateNonSysInplaceEncMutex (void) { return TCCreateMutex (&hNonSysInplaceEncMutex, TC_MUTEX_NAME_NONSYS_INPLACE_ENC); @@ -2166,14 +2166,14 @@ void CloseNonSysInplaceEncMutex (void) // Returns TRUE if another instance of the wizard is preparing, resuming or performing non-system in-place encryption BOOL NonSysInplaceEncInProgressElsewhere (void) { - return (!InstanceHasNonSysInplaceEncMutex () + return (!InstanceHasNonSysInplaceEncMutex () && MutexExistsOnSystem (TC_MUTEX_NAME_NONSYS_INPLACE_ENC)); } // Mutex handling to prevent multiple instances of the wizard or main app from trying to install // or register the driver or from trying to launch it in portable mode at the same time. -// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). +// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). BOOL CreateDriverSetupMutex (void) { return TCCreateMutex (&hDriverSetupMutex, TC_MUTEX_NAME_DRIVER_SETUP); @@ -2204,7 +2204,7 @@ BOOL IsTrueCryptInstallerRunning (void) } -// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). +// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). BOOL TCCreateMutex (volatile HANDLE *hMutex, wchar_t *name) { if (*hMutex != NULL) @@ -2244,7 +2244,7 @@ void TCCloseMutex (volatile HANDLE *hMutex) } -// Returns TRUE if a process running on the system has the specified mutex (otherwise FALSE). +// Returns TRUE if a process running on the system has the specified mutex (otherwise FALSE). BOOL MutexExistsOnSystem (wchar_t *name) { if (name[0] == 0) @@ -2258,7 +2258,7 @@ BOOL MutexExistsOnSystem (wchar_t *name) return FALSE; if (GetLastError () == ERROR_ACCESS_DENIED) // On Vista, this is returned if the owner of the mutex is elevated while we are not - return TRUE; + return TRUE; // The call failed and it is not certain whether the mutex exists or not return FALSE; @@ -2530,8 +2530,8 @@ static void LoadSystemDll (LPCTSTR szModuleName, HMODULE *pHandle, BOOL bIgnoreE void InitApp (HINSTANCE hInstance, wchar_t *lpszCommandLine) { WNDCLASSW wc; - char langId[6]; - InitCommonControlsPtr InitCommonControlsFn = NULL; + char langId[6]; + InitCommonControlsPtr InitCommonControlsFn = NULL; InitOSVersionInfo(); @@ -2553,9 +2553,9 @@ void InitApp (HINSTANCE hInstance, wchar_t *lpszCommandLine) LoadSystemDll (L"Usp10.DLL", &hUsp10Dll, TRUE, SRC_POS); LoadSystemDll (L"UXTheme.dll", &hUXThemeDll, TRUE, SRC_POS); - LoadSystemDll (L"msls31.dll", &hMsls31, TRUE, SRC_POS); + LoadSystemDll (L"msls31.dll", &hMsls31, TRUE, SRC_POS); LoadSystemDll (L"SETUPAPI.DLL", &hSetupDll, FALSE, SRC_POS); - LoadSystemDll (L"SHLWAPI.DLL", &hShlwapiDll, FALSE, SRC_POS); + LoadSystemDll (L"SHLWAPI.DLL", &hShlwapiDll, FALSE, SRC_POS); LoadSystemDll (L"userenv.dll", &hUserenvDll, TRUE, SRC_POS); LoadSystemDll (L"rsaenh.dll", &hRsaenhDll, TRUE, SRC_POS); @@ -2572,7 +2572,7 @@ void InitApp (HINSTANCE hInstance, wchar_t *lpszCommandLine) } if (IsOSAtLeast (WIN_VISTA)) - { + { LoadSystemDll (L"netapi32.dll", &hnetapi32dll, TRUE, SRC_POS); LoadSystemDll (L"authz.dll", &hauthzdll, TRUE, SRC_POS); LoadSystemDll (L"xmllite.dll", &hxmllitedll, TRUE, SRC_POS); @@ -2580,7 +2580,7 @@ void InitApp (HINSTANCE hInstance, wchar_t *lpszCommandLine) } if (IsOSAtLeast (WIN_VISTA)) - { + { LoadSystemDll (L"spp.dll", &hsppdll, TRUE, SRC_POS); LoadSystemDll (L"vssapi.dll", &vssapidll, TRUE, SRC_POS); LoadSystemDll (L"vsstrace.dll", &hvsstracedll, TRUE, SRC_POS); @@ -2592,21 +2592,21 @@ void InitApp (HINSTANCE hInstance, wchar_t *lpszCommandLine) LoadSystemDll (L"cfgmgr32.dll", &hcfgmgr32dll, TRUE, SRC_POS); LoadSystemDll (L"devobj.dll", &hdevobjdll, TRUE, SRC_POS); LoadSystemDll (L"powrprof.dll", &hpowrprofdll, TRUE, SRC_POS); - + LoadSystemDll (L"dwmapi.dll", &hdwmapidll, TRUE, SRC_POS); - + LoadSystemDll (L"crypt32.dll", &hcrypt32dll, TRUE, SRC_POS); LoadSystemDll (L"bcrypt.dll", &hbcryptdll, TRUE, SRC_POS); - LoadSystemDll (L"bcryptprimitives.dll", &hbcryptprimitivesdll, TRUE, SRC_POS); + LoadSystemDll (L"bcryptprimitives.dll", &hbcryptprimitivesdll, TRUE, SRC_POS); } - } + } #else LoadSystemDll (L"WINSCARD.DLL", &hwinscarddll, TRUE, SRC_POS); #endif LoadSystemDll (L"COMCTL32.DLL", &hComctl32Dll, FALSE, SRC_POS); - + // call InitCommonControls function InitCommonControlsFn = (InitCommonControlsPtr) GetProcAddress (hComctl32Dll, "InitCommonControls"); ImageList_AddFn = (ImageList_AddPtr) GetProcAddress (hComctl32Dll, "ImageList_Add"); @@ -2667,7 +2667,7 @@ void InitApp (HINSTANCE hInstance, wchar_t *lpszCommandLine) // Language langId[0] = 0; SetPreferredLangId (ConfigReadString ("Language", "", langId, sizeof (langId))); - + if (langId[0] == 0) { if (IsNonInstallMode ()) @@ -2703,7 +2703,7 @@ void InitApp (HINSTANCE hInstance, wchar_t *lpszCommandLine) } memset (&wcex, 0, sizeof (wcex)); - wcex.cbSize = sizeof(WNDCLASSEX); + wcex.cbSize = sizeof(WNDCLASSEX); wcex.lpfnWndProc = (WNDPROC) NonInstallUacWndProc; wcex.hInstance = hInstance; wcex.lpszClassName = L"VeraCrypt"; @@ -2781,7 +2781,7 @@ void InitApp (HINSTANCE hInstance, wchar_t *lpszCommandLine) break; } } - + /* Get the attributes for the standard dialog class */ if ((GetClassInfoW (hInst, WINDOWS_DIALOG_CLASS, &wc)) == 0) { @@ -2972,7 +2972,7 @@ BOOL OpenDevice (const wchar_t *lpszPath, OPEN_TEST_STRUCT *driver, BOOL detectF &dwResult, NULL); // check variable driver - if ( bResult + if ( bResult && ( (driver->bDetectTCBootLoader != TRUE && driver->bDetectTCBootLoader != FALSE) || (driver->TCBootLoaderDetected != TRUE && driver->TCBootLoaderDetected != FALSE) || (driver->DetectFilesystem != TRUE && driver->DetectFilesystem != FALSE) || @@ -2998,7 +2998,7 @@ BOOL OpenDevice (const wchar_t *lpszPath, OPEN_TEST_STRUCT *driver, BOOL detectF else return FALSE; } - + return TRUE; } @@ -3026,10 +3026,10 @@ BOOL GetDriveLabel (int driveNo, wchar_t *label, int labelSize) /* Stores the device path of the system partition in SysPartitionDevicePath and the device path of the system drive in SysDriveDevicePath. -IMPORTANT: As this may take a very long time if called for the first time, it should be called only before performing - a dangerous operation (such as header backup restore or formatting a supposedly non-system device) never - at WM_INITDIALOG or any other GUI events -- instead call IsSystemDevicePath (path, hwndDlg, FALSE) for - very fast preliminary GUI checks; also note that right after the "Select Device" dialog exits with an OK +IMPORTANT: As this may take a very long time if called for the first time, it should be called only before performing + a dangerous operation (such as header backup restore or formatting a supposedly non-system device) never + at WM_INITDIALOG or any other GUI events -- instead call IsSystemDevicePath (path, hwndDlg, FALSE) for + very fast preliminary GUI checks; also note that right after the "Select Device" dialog exits with an OK return code, you can use the global flags bSysPartitionSelected and bSysDriveSelected to see if the user selected the system partition/device. After this function completes successfully, the results are cached for the rest of the session and repeated @@ -3037,13 +3037,13 @@ executions complete very fast. Returns TRUE if successful (otherwise FALSE). */ BOOL GetSysDevicePaths (HWND hwndDlg) { if (!bCachedSysDevicePathsValid - || wcslen (SysPartitionDevicePath) <= 1 + || wcslen (SysPartitionDevicePath) <= 1 || wcslen (SysDriveDevicePath) <= 1) { foreach (const HostDevice &device, GetAvailableHostDevices (false, true)) { if (device.ContainsSystem) - StringCchCopyW (device.IsPartition ? SysPartitionDevicePath : SysDriveDevicePath, TC_MAX_PATH, device.Path.c_str()); + StringCchCopyW (device.IsPartition ? SysPartitionDevicePath : SysDriveDevicePath, TC_MAX_PATH, device.Path.c_str()); } if (IsOSAtLeast (WIN_7)) @@ -3070,24 +3070,24 @@ BOOL GetSysDevicePaths (HWND hwndDlg) bCachedSysDevicePathsValid = 1; } - return (bCachedSysDevicePathsValid - && wcslen (SysPartitionDevicePath) > 1 + return (bCachedSysDevicePathsValid + && wcslen (SysPartitionDevicePath) > 1 && wcslen (SysDriveDevicePath) > 1); } -/* Determines whether the device path is the path of the system partition or of the system drive (or neither). -If bReliableRequired is TRUE, very fast execution is guaranteed, but the results cannot be relied upon. +/* Determines whether the device path is the path of the system partition or of the system drive (or neither). +If bReliableRequired is TRUE, very fast execution is guaranteed, but the results cannot be relied upon. If it's FALSE and the function is called for the first time, execution may take up to one minute but the results are reliable. IMPORTANT: As the execution may take a very long time if called for the first time with bReliableRequired set to TRUE, it should be called with bReliableRequired set to TRUE only before performing a dangerous - operation (such as header backup restore or formatting a supposedly non-system device) never at - WM_INITDIALOG or any other GUI events (use IsSystemDevicePath(path, hwndDlg, FALSE) for fast - preliminary GUI checks; also note that right after the "Select Device" dialog exits with an OK + operation (such as header backup restore or formatting a supposedly non-system device) never at + WM_INITDIALOG or any other GUI events (use IsSystemDevicePath(path, hwndDlg, FALSE) for fast + preliminary GUI checks; also note that right after the "Select Device" dialog exits with an OK return code, you can use the global flags bSysPartitionSelected and bSysDriveSelected to see if the user selected the system partition/device). After this function completes successfully, the results are cached for the rest of the session, bReliableRequired -is ignored (TRUE implied), repeated executions complete very fast, and the results are always reliable. +is ignored (TRUE implied), repeated executions complete very fast, and the results are always reliable. Return codes: 1 - it is the system partition path (e.g. \Device\Harddisk0\Partition1) 2 - it is the system drive path (e.g. \Device\Harddisk0\Partition0) @@ -3122,10 +3122,10 @@ int IsSystemDevicePath (const wchar_t *path, HWND hwndDlg, BOOL bReliableRequire /* Determines whether the path points to a non-system partition on the system drive. IMPORTANT: As this may take a very long time if called for the first time, it should be called - only before performing a dangerous operation, never at WM_INITDIALOG or any other GUI events. + only before performing a dangerous operation, never at WM_INITDIALOG or any other GUI events. Return codes: -0 - it isn't a non-system partition on the system drive -1 - it's a non-system partition on the system drive +0 - it isn't a non-system partition on the system drive +1 - it's a non-system partition on the system drive -1 - the result can't be determined, isn't reliable, or there was an error. */ int IsNonSysPartitionOnSysDrive (const wchar_t *path) { @@ -3165,12 +3165,12 @@ int IsNonSysPartitionOnSysDrive (const wchar_t *path) if (wcsncmp (tmpPath, SysDriveDevicePath, max (wcslen(tmpPath), wcslen(SysDriveDevicePath))) == 0) { - // It is a non-system partition on the system drive + // It is a non-system partition on the system drive return 1; } - else + else { - // The partition is not on the system drive + // The partition is not on the system drive return 0; } } @@ -3415,17 +3415,17 @@ BOOL CALLBACK RawDevicesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM l LocalizeDialog (hwndDlg, "IDD_RAWDEVICES_DLG"); SendMessage (hList,LVM_SETEXTENDEDLISTVIEWSTYLE,0, - LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_TWOCLICKACTIVATE|LVS_EX_LABELTIP - ); + LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_TWOCLICKACTIVATE|LVS_EX_LABELTIP + ); - memset (&LvCol,0,sizeof(LvCol)); - LvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; + memset (&LvCol,0,sizeof(LvCol)); + LvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; LvCol.pszText = GetString ("DEVICE"); LvCol.cx = CompensateXDPI (186); LvCol.fmt = LVCFMT_LEFT; SendMessage (hList,LVM_INSERTCOLUMNW,0,(LPARAM)&LvCol); - LvCol.pszText = GetString ("DRIVE"); + LvCol.pszText = GetString ("DRIVE"); LvCol.cx = CompensateXDPI (38); LvCol.fmt = LVCFMT_LEFT; SendMessage (hList,LVM_INSERTCOLUMNW,1,(LPARAM)&LvCol); @@ -3479,7 +3479,7 @@ BOOL CALLBACK RawDevicesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM l // Path if (!device.IsPartition || device.DynamicVolume) { - if (!device.Floppy && (device.Size == 0) + if (!device.Floppy && (device.Size == 0) && (device.IsPartition || device.Partitions.empty() || device.Partitions[0].Size == 0) ) continue; @@ -3487,7 +3487,7 @@ BOOL CALLBACK RawDevicesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM l if (line > 1) { ListItemAdd (hList, item.iItem, L""); - item.iItem = line++; + item.iItem = line++; } if (device.Floppy || device.DynamicVolume) @@ -3540,7 +3540,7 @@ BOOL CALLBACK RawDevicesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM l } #endif - item.iItem = line++; + item.iItem = line++; } SendMessageW(hList, LVM_SETCOLUMNWIDTH, 0, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); @@ -3563,8 +3563,8 @@ BOOL CALLBACK RawDevicesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM l { BOOL bEnableOkButton = FALSE; LVITEM LvItem; - memset(&LvItem,0,sizeof(LvItem)); - LvItem.mask = LVIF_TEXT | LVIF_PARAM; + memset(&LvItem,0,sizeof(LvItem)); + LvItem.mask = LVIF_TEXT | LVIF_PARAM; LvItem.iItem = ((LPNMLISTVIEW) lParam)->iItem; LvItem.pszText = lpszFileName; LvItem.cchTextMax = TC_MAX_PATH; @@ -3597,7 +3597,7 @@ BOOL CALLBACK RawDevicesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM l int selectedItem = ListView_GetSelectionMark (GetDlgItem (hwndDlg, IDC_DEVICELIST)); if (selectedItem == -1 || itemToDeviceMap.find (selectedItem) == itemToDeviceMap.end()) - return 1; // non-device line selected + return 1; // non-device line selected const HostDevice selectedDevice = itemToDeviceMap[selectedItem]; StringCchCopyW (lpszFileName, TC_MAX_PATH, selectedDevice.Path.c_str()); @@ -3710,7 +3710,7 @@ BOOL CALLBACK RawDevicesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM l } } - // Disallow format if the device contains partitions, but not if the partition is virtual or system + // Disallow format if the device contains partitions, but not if the partition is virtual or system if (!selectedDevice.IsVirtualPartition && !bHiddenVolDirect) { @@ -3731,7 +3731,7 @@ BOOL CALLBACK RawDevicesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM l #endif // #ifdef VOLFORMAT } - else + else bSysDriveSelected = FALSE; #ifdef VOLFORMAT @@ -3908,7 +3908,7 @@ BOOL DriverUnload () if (hDriver == INVALID_HANDLE_VALUE) return TRUE; - + try { if (BootEncryption (NULL).GetStatus().DeviceFilterActive) @@ -4025,7 +4025,7 @@ start: } // Try to open a handle to the driver again (keep the mutex in case the other instance failed) - goto start; + goto start; } else { @@ -4034,7 +4034,7 @@ start: if (SystemEncryptionStatus != SYSENC_STATUS_NONE) { // This is an inconsistent state. The config file indicates system encryption should be - // active, but the driver is not running. This may happen e.g. when the pretest fails and + // active, but the driver is not running. This may happen e.g. when the pretest fails and // the user selects "Last Known Good Configuration" from the Windows boot menu. // To fix this, we're going to reinstall the driver, start it, and register it for boot. @@ -4068,7 +4068,7 @@ load: return res; bPortableModeConfirmed = TRUE; - + if (hDriver != INVALID_HANDLE_VALUE) CloseHandle (hDriver); hDriver = CreateFile (WIN32_ROOT_PREFIX, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); @@ -4242,7 +4242,7 @@ BOOL SelectMultipleFiles (HWND hwndDlg, const char *stringId, wchar_t *lpszFileN | OFN_PATHMUSTEXIST | OFN_ALLOWMULTISELECT | (keepHistory ? 0 : OFN_DONTADDTORECENT); - + if (!keepHistory) CleanLastVisitedMRU (); @@ -4272,7 +4272,7 @@ BOOL SelectMultipleFiles (HWND hwndDlg, const char *stringId, wchar_t *lpszFileN CleanLastVisitedMRU (); status = TRUE; - + ret: SystemFileSelectorCallPending = FALSE; ResetCurrentDirectory(); @@ -4306,10 +4306,10 @@ BOOL SelectMultipleFilesNext (wchar_t *lpszFileName, size_t cbFileName) } -static int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lp, LPARAM pData) +static int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lp, LPARAM pData) { switch(uMsg) { - case BFFM_INITIALIZED: + case BFFM_INITIALIZED: { /* WParam is TRUE since we are passing a path. It would be FALSE if we were passing a pidl. */ @@ -4317,12 +4317,12 @@ static int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lp, LPARAM pDa break; } - case BFFM_SELCHANGED: + case BFFM_SELCHANGED: { wchar_t szDir[TC_MAX_PATH]; /* Set the status window to the currently selected path. */ - if (SHGetPathFromIDList((LPITEMIDLIST) lp ,szDir)) + if (SHGetPathFromIDList((LPITEMIDLIST) lp ,szDir)) { SendMessage (hwnd,BFFM_SETSTATUSTEXT,0,(LPARAM)szDir); } @@ -4346,7 +4346,7 @@ BOOL BrowseDirectories (HWND hwndDlg, char *lpszTitle, wchar_t *dirName) CoInitialize (NULL); - if (SUCCEEDED (SHGetMalloc (&pMalloc))) + if (SUCCEEDED (SHGetMalloc (&pMalloc))) { ZeroMemory (&bi, sizeof(bi)); bi.hwndOwner = hwndDlg; @@ -4358,9 +4358,9 @@ BOOL BrowseDirectories (HWND hwndDlg, char *lpszTitle, wchar_t *dirName) bi.lParam = (LPARAM)dirName; pidl = SHBrowseForFolderW (&bi); - if (pidl != NULL) + if (pidl != NULL) { - if (SHGetPathFromIDList(pidl, dirName)) + if (SHGetPathFromIDList(pidl, dirName)) { bOK = TRUE; } @@ -4574,7 +4574,7 @@ static BOOL CALLBACK LocalizeDialogEnum( HWND hwnd, LPARAM font) // Font SendMessageW (hwnd, WM_SETFONT, (WPARAM) font, 0); - + return TRUE; } @@ -4588,7 +4588,7 @@ void LocalizeDialog (HWND hwnd, char *stringId) SetWindowTextW (hwnd, L"VeraCrypt"); else SetWindowTextW (hwnd, GetString (stringId)); - + if (hUserFont != 0) EnumChildWindows (hwnd, LocalizeDialogEnum, (LPARAM) hUserFont); } @@ -4669,10 +4669,10 @@ BOOL UpdateDriveCustomLabel (int driveNo, wchar_t* effectiveLabel, BOOL bSetValu DWORD cbLabelLen = (DWORD) ((wcslen (effectiveLabel) + 1) * sizeof (wchar_t)); BOOL bToBeDeleted = FALSE; - StringCbPrintfW (wszRegPath, sizeof (wszRegPath), L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\DriveIcons\\%s\\DefaultLabel", driveStr); - + StringCbPrintfW (wszRegPath, sizeof (wszRegPath), L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\DriveIcons\\%s\\DefaultLabel", driveStr); + if (bSetValue) - lStatus = RegCreateKeyExW (HKEY_CURRENT_USER, wszRegPath, NULL, NULL, 0, + lStatus = RegCreateKeyExW (HKEY_CURRENT_USER, wszRegPath, NULL, NULL, 0, KEY_READ | KEY_WRITE | KEY_SET_VALUE, NULL, &hKey, NULL); else lStatus = RegOpenKeyExW (HKEY_CURRENT_USER, wszRegPath, 0, KEY_READ | KEY_WRITE | KEY_SET_VALUE, &hKey); @@ -4696,7 +4696,7 @@ BOOL UpdateDriveCustomLabel (int driveNo, wchar_t* effectiveLabel, BOOL bSetValu if (bToBeDeleted) { - StringCbPrintfW (wszRegPath, sizeof (wszRegPath), L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\DriveIcons\\%s", driveStr); + StringCbPrintfW (wszRegPath, sizeof (wszRegPath), L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\DriveIcons\\%s", driveStr); lStatus = RegOpenKeyExW (HKEY_CURRENT_USER, wszRegPath, 0, KEY_READ | KEY_WRITE | KEY_SET_VALUE, &hKey); if (ERROR_SUCCESS == lStatus) { @@ -4722,7 +4722,7 @@ wstring GetUserFriendlyVersionString (int version) versionString.insert (version > 0xfff ? 2 : 1,L"."); if (versionString[versionString.length()-1] == L'0') - versionString.erase (versionString.length()-1, 1); + versionString.erase (versionString.length()-1, 1); return (versionString); } @@ -4774,7 +4774,7 @@ bool HexWideStringToArray (const wchar_t* hexStr, std::vector& arr) arr.clear(); if (len %2) return false; - + for (i = 0; i < len/2; i++) { if (!HexToByte (*hexStr++, b1) || !HexToByte (*hexStr++, b2)) @@ -4837,7 +4837,7 @@ void GetSpeedString (unsigned __int64 speed, wchar_t *str, size_t cbStr) { static wchar_t *b, *kb, *mb, *gb, *tb, *pb; static int serNo; - + if (b == NULL || serNo != LocalizationSerialNo) { serNo = LocalizationSerialNo; @@ -4920,7 +4920,7 @@ static void DisplayBenchmarkResults (HWND hwndDlg) } break; } - + /* Render the results */ SendMessage (hList,LVM_DELETEALLITEMS,0,(LPARAM)&LvItem); @@ -4934,7 +4934,7 @@ static void DisplayBenchmarkResults (HWND hwndDlg) LvItem.iItem = i; LvItem.iSubItem = 0; LvItem.pszText = (LPWSTR) benchmarkTable[i].name; - SendMessageW (hList, LVM_INSERTITEM, 0, (LPARAM)&LvItem); + SendMessageW (hList, LVM_INSERTITEM, 0, (LPARAM)&LvItem); #if PKCS5_BENCHMARKS wcscpy (item1, L"-"); @@ -4944,7 +4944,7 @@ static void DisplayBenchmarkResults (HWND hwndDlg) LvItem.iSubItem = 1; LvItem.pszText = item1; - SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem); + SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem); #if PKCS5_BENCHMARKS wcscpy (item1, L"-"); @@ -4954,7 +4954,7 @@ static void DisplayBenchmarkResults (HWND hwndDlg) LvItem.iSubItem = 2; LvItem.pszText = item1; - SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem); + SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem); #if PKCS5_BENCHMARKS swprintf (item1, L"%d t", benchmarkTable[i].encSpeed); @@ -4964,7 +4964,7 @@ static void DisplayBenchmarkResults (HWND hwndDlg) LvItem.iSubItem = 3; LvItem.pszText = item1; - SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem); + SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem); } SendMessageW(hList, LVM_SETCOLUMNWIDTH, 0, MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER, 0)); @@ -4978,7 +4978,7 @@ static void DisplayBenchmarkResults (HWND hwndDlg) typedef struct { HWND hBenchDlg; - BOOL bStatus; + BOOL bStatus; } BenchmarkThreadParam; static BOOL PerformBenchmark(HWND hBenchDlg, HWND hwndDlg); @@ -5049,9 +5049,9 @@ static BOOL PerformBenchmark(HWND hBenchDlg, HWND hwndDlg) #if HASH_FNC_BENCHMARKS /* Measures the speed at which each of the hash algorithms processes the message to produce - a single digest. + a single digest. - The hash algorithm benchmarks are included here for development purposes only. Do not enable + The hash algorithm benchmarks are included here for development purposes only. Do not enable them when building a public release (the benchmark GUI strings wouldn't make sense). */ { @@ -5062,7 +5062,7 @@ static BOOL PerformBenchmark(HWND hBenchDlg, HWND hwndDlg) sha256_ctx s256ctx; int hid; - for (hid = FIRST_PRF_ID; hid <= LAST_PRF_ID; hid++) + for (hid = FIRST_PRF_ID; hid <= LAST_PRF_ID; hid++) { if (QueryPerformanceCounter (&performanceCountStart) == 0) goto counter_error; @@ -5112,21 +5112,21 @@ static BOOL PerformBenchmark(HWND hBenchDlg, HWND hwndDlg) #elif PKCS5_BENCHMARKS // #if HASH_FNC_BENCHMARKS /* Measures the time that it takes for the PKCS-5 routine to derive a header key using - each of the implemented PRF algorithms. + each of the implemented PRF algorithms. - The PKCS-5 benchmarks are included here for development purposes only. Do not enable + The PKCS-5 benchmarks are included here for development purposes only. Do not enable them when building a public release (the benchmark GUI strings wouldn't make sense). */ { int thid, i; char dk[MASTER_KEYDATA_SIZE]; char *tmp_salt = {"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF\x01\x23\x45\x67\x89\xAB\xCD\xEF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF\x01\x23\x45\x67\x89\xAB\xCD\xEF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF"}; - for (thid = FIRST_PRF_ID; thid <= LAST_PRF_ID; thid++) + for (thid = FIRST_PRF_ID; thid <= LAST_PRF_ID; thid++) { if (QueryPerformanceCounter (&performanceCountStart) == 0) goto counter_error; - for (i = 1; i <= 5; i++) + for (i = 1; i <= 5; i++) { switch (thid) { @@ -5167,7 +5167,7 @@ static BOOL PerformBenchmark(HWND hBenchDlg, HWND hwndDlg) #else // #elif PKCS5_BENCHMARKS /* Encryption algorithm benchmarks */ - + for (ci->ea = EAGetFirst(); ci->ea != 0; ci->ea = EAGetNext(ci->ea)) { if (!EAIsFormatEnabled (ci->ea)) @@ -5226,7 +5226,7 @@ static BOOL PerformBenchmark(HWND hBenchDlg, HWND hwndDlg) return TRUE; counter_error: - + if (ci) crypto_close (ci); @@ -5265,11 +5265,11 @@ BOOL CALLBACK BenchmarkDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lP benchmarkSortMethod = BENCHMARK_SORT_BY_SPEED; SendMessage (hList,LVM_SETEXTENDEDLISTVIEWSTYLE,0, - LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_LABELTIP - ); + LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_LABELTIP + ); - memset (&LvCol,0,sizeof(LvCol)); - LvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; + memset (&LvCol,0,sizeof(LvCol)); + LvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; LvCol.pszText = GetString ("ALGORITHM"); LvCol.cx = CompensateXDPI (114); LvCol.fmt = LVCFMT_LEFT; @@ -5518,7 +5518,7 @@ static BOOL CALLBACK RandomPoolEnrichementDlgProc (HWND hwndDlg, UINT msg, WPARA SetTimer (hwndDlg, 0xfd, RANDPOOL_DISPLAY_REFRESH_INTERVAL, NULL); SendMessage (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE); - + hEntropyBar = GetDlgItem (hwndDlg, IDC_ENTROPY_BAR); SendMessage (hEntropyBar, PBM_SETRANGE32, 0, maxEntropyLevel); SendMessage (hEntropyBar, PBM_SETSTEP, 1, 0); @@ -5553,7 +5553,7 @@ static BOOL CALLBACK RandomPoolEnrichementDlgProc (HWND hwndDlg, UINT msg, WPARA else if (bUseMask) { /* use mask to compute a randomized ascii representation */ - tmpByte = (randPool[row * RANDPOOL_DISPLAY_COLUMNS + col] - + tmpByte = (randPool[row * RANDPOOL_DISPLAY_COLUMNS + col] - lastRandPool[row * RANDPOOL_DISPLAY_COLUMNS + col]) ^ maskRandPool [row * RANDPOOL_DISPLAY_COLUMNS + col]; tmp[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); tmp[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); @@ -5714,8 +5714,8 @@ BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP SendMessage (hEntropyBar, PBM_SETSTEP, 1, 0); SendMessage (hEntropyBar, PBM_SETSTATE, PBST_ERROR, 0); -#ifndef VOLFORMAT - if (Randinit ()) +#ifndef VOLFORMAT + if (Randinit ()) { handleError (hwndDlg, (CryptoAPILastError == ERROR_SUCCESS)? ERR_RAND_INIT_FAILED : ERR_CAPI_INIT_FAILED, SRC_POS); EndDialog (hwndDlg, IDCLOSE); @@ -5761,7 +5761,7 @@ BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP else if (bUseMask) { /* use mask to compute a randomized ASCII representation */ - tmpByte = (randPool[row * RANDPOOL_DISPLAY_COLUMNS + col] - + tmpByte = (randPool[row * RANDPOOL_DISPLAY_COLUMNS + col] - lastRandPool[row * RANDPOOL_DISPLAY_COLUMNS + col]) ^ maskRandPool [row * RANDPOOL_DISPLAY_COLUMNS + col]; tmp[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); tmp[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); @@ -5889,7 +5889,7 @@ BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP for (i= 0; i < keyfilesCount; i++) { StringCbCopyW(szFileName, sizeof(szFileName), szDirName); - + if (i > 0) { StringCbPrintfW(szSuffix, sizeof(szSuffix), L"_%d", i); @@ -5946,7 +5946,7 @@ BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP NormalCursor(); return 1; } - + /* since keyfilesSize < 1024 * 1024, we mask with 0x000FFFFF */ keyfilesSize = (long) (((unsigned long) keyfilesSize) & 0x000FFFFF); @@ -5954,7 +5954,7 @@ BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP keyfilesSize += 64; } - /* Generate the keyfile */ + /* Generate the keyfile */ if (!RandgetBytesFull (hwndDlg, keyfile, keyfilesSize, TRUE, TRUE)) { _close (fhKeyfile); @@ -5962,7 +5962,7 @@ BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP TCfree(keyfile); NormalCursor(); return 1; - } + } /* Write the keyfile */ status = _write (fhKeyfile, keyfile, keyfilesSize); @@ -5975,7 +5975,7 @@ BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP NormalCursor(); handleWin32Error (hwndDlg, SRC_POS); return 1; - } + } } TCfree(keyfile); @@ -5994,7 +5994,7 @@ exit: WaitCursor(); KillTimer (hwndDlg, 0xfd); -#ifndef VOLFORMAT +#ifndef VOLFORMAT RandStop (FALSE); #endif /* Cleanup */ @@ -6109,7 +6109,7 @@ CipherTestDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { ShowWindow(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), SW_SHOWNORMAL); SetWindowTextW(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), GetString ("TESTS_FAILED")); - } + } else { ShowWindow(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), SW_SHOWNORMAL); @@ -6215,7 +6215,7 @@ CipherTestDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) inputtext[n] = (char) x; } - + // XTS if (bXTSTestEnabled) { @@ -6272,10 +6272,10 @@ CipherTestDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) blockNo = (int) SendMessage (GetDlgItem (hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_GETCURSEL, 0, 0), 0); } // if (bXTSTestEnabled) - + /* Perform the actual tests */ - if (ks != CB_ERR && pt != CB_ERR) + if (ks != CB_ERR && pt != CB_ERR) { char tmp[128]; int tmpRetVal; @@ -6372,7 +6372,7 @@ CipherTestDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) return 0; } -void +void ResetCipherTest(HWND hwndDlg, int idTestCipher) { int ndx; @@ -6406,7 +6406,7 @@ ResetCipherTest(HWND hwndDlg, int idTestCipher) SetWindowText(GetDlgItem(hwndDlg, IDC_SECONDARY_KEY), L"0000000000000000000000000000000000000000000000000000000000000000"); SetWindowText(GetDlgItem(hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), L"0"); - + SetWindowText(GetDlgItem(hwndDlg, IDC_PLAINTEXT), L"0000000000000000"); SetWindowText(GetDlgItem(hwndDlg, IDC_CIPHERTEXT), L"0000000000000000"); @@ -6476,7 +6476,7 @@ BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPA pStr++; pwStr++; - do + do { if (*pStr != 0) { @@ -6490,7 +6490,7 @@ BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPA hUserFont), nLongestButtonCaptionWidth); - nLongestButtonCaptionCharLen = max (nLongestButtonCaptionCharLen, + nLongestButtonCaptionCharLen = max (nLongestButtonCaptionCharLen, (int) wcslen ((const wchar_t *) (bResolve ? GetString(*pStr) : *pwStr))); } @@ -6509,14 +6509,14 @@ BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPA // Length of main message in characters (not bytes) nMainTextLenInChars = (int) wcslen ((const wchar_t *) (bResolve ? GetString(*(pStrOrig+1)) : *(pwStrOrig+1))); - if (nMainTextLenInChars > 200 + if (nMainTextLenInChars > 200 && nMainTextLenInChars / nLongestButtonCaptionCharLen >= 10) { - // As the main text is longer than 200 characters, we will "pad" the widest button caption with - // spaces (if it is not wide enough) so as to increase the width of the whole dialog window. + // As the main text is longer than 200 characters, we will "pad" the widest button caption with + // spaces (if it is not wide enough) so as to increase the width of the whole dialog window. // Otherwise, it would look too tall (dialog boxes look better when they are more wide than tall). nLongestButtonCaptionWidth = CompensateXDPI (max ( - nLongestButtonCaptionWidth, + nLongestButtonCaptionWidth, min (350, nMainTextLenInChars))); } @@ -6544,10 +6544,10 @@ BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPA do { - offset = FindString ((char *) (bResolve ? GetString(*(pStrOrig+1)) : *(pwStrOrig+1)), + offset = FindString ((char *) (bResolve ? GetString(*(pStrOrig+1)) : *(pwStrOrig+1)), (char *) L"\n", - nMainTextLenInChars * 2, - (int) wcslen (L"\n") * 2, + nMainTextLenInChars * 2, + (int) wcslen (L"\n") * 2, offset + 1); newLineSeqCount++; @@ -6568,8 +6568,8 @@ BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPA // Reduction in height according to the number of shown buttons vertSubOffset = ((MAX_MULTI_CHOICES - nActiveChoices) * nBaseButtonHeight); - if (horizSubOffset > 0 - || vertMsgHeightOffset > 0 + if (horizSubOffset > 0 + || vertMsgHeightOffset > 0 || vertOffset > 0) { // Resize/move each button if necessary @@ -6603,7 +6603,7 @@ BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPA trec.right + 2 + horizSubOffset, trec.bottom + 2, TRUE); - + GetWindowRect(GetDlgItem(hwndDlg, IDC_MC_DLG_HR2), &rec); GetClientRect(GetDlgItem(hwndDlg, IDC_MC_DLG_HR2), &trec); MoveWindow (GetDlgItem(hwndDlg, IDC_MC_DLG_HR2), @@ -6657,7 +6657,7 @@ BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPA BOOL CheckCapsLock (HWND hwnd, BOOL quiet) { - if ((GetKeyState(VK_CAPITAL) & 1) != 0) + if ((GetKeyState(VK_CAPITAL) & 1) != 0) { if (!quiet) { @@ -6686,7 +6686,7 @@ BOOL CheckFileExtension (wchar_t *fileName) L".vb", L".vbe", L".vbs", L".vsmacros", L".vss", L".vst", L".vsw", L".ws", L".wsc", L".wsf", L".wsh", L".xsd", L".xsl", // These additional file extensions are usually watched by antivirus programs L".386", L".acm", L".ade", L".adp", L".ani", L".app", L".asd", L".asf", L".asx", L".awx", L".ax", L".boo", L".bz2", L".cdf", - L".class", L".dhtm", L".dhtml",L".dlo", L".emf", L".eml", L".flt", L".fot", L".gz", L".hlp", L".htm", L".html", L".ini", + L".class", L".dhtm", L".dhtml",L".dlo", L".emf", L".eml", L".flt", L".fot", L".gz", L".hlp", L".htm", L".html", L".ini", L".j2k", L".jar", L".jff", L".jif", L".jmh", L".jng", L".jp2", L".jpe", L".jpeg", L".jpg", L".lsp", L".mod", L".nws", L".obj", L".olb", L".osd", L".ov1", L".ov2", L".ov3", L".ovl", L".ovl", L".ovr", L".pdr", L".pgm", L".php", L".pkg", L".pl", L".png", L".pot", L".pps", L".ppt", L".ps1", L".ps1xml", L".psc1", L".rar", L".rpl", L".rtf", L".sbf", L".script", L".sh", L".sha", L".shtm", @@ -6858,7 +6858,7 @@ int DriverUnmountVolume (HWND hwndDlg, int nDosDriveNo, BOOL forced) memcpy (wszLabel, prop.wszLabel, sizeof (wszLabel)); bDriverSetLabel = prop.bDriverSetLabel; } - + unmount.nDosDriveNo = nDosDriveNo; unmount.ignoreOpenFiles = forced; @@ -6928,11 +6928,11 @@ void BroadcastDeviceChange (WPARAM message, int nDosDriveNo, DWORD driveMap) } } - dbv.dbcv_size = sizeof (dbv); - dbv.dbcv_devicetype = DBT_DEVTYP_VOLUME; + dbv.dbcv_size = sizeof (dbv); + dbv.dbcv_devicetype = DBT_DEVTYP_VOLUME; dbv.dbcv_reserved = 0; dbv.dbcv_unitmask = driveMap; - dbv.dbcv_flags = 0; + dbv.dbcv_flags = 0; UINT timeOut = 1000; @@ -7032,8 +7032,8 @@ BOOL CALLBACK WaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) SetWindowLongPtrW (hProgress, GWL_STYLE, PBS_MARQUEE | GetWindowLongPtrW (hProgress, GWL_STYLE)); ::SendMessageW(hProgress, PBM_SETMARQUEE, (WPARAM) TRUE, (LPARAM) 0); } - - thParam->hwnd = hwndDlg; + + thParam->hwnd = hwndDlg; // For now, we don't have system menu is the resources but we leave this code // if it is enabled in the future @@ -7047,8 +7047,8 @@ BOOL CALLBACK WaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) HICON hIcon = (HICON)::LoadImage(hInst, MAKEINTRESOURCE(IDI_TRUECRYPT_ICON), IMAGE_ICON, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR); ::SendMessage(hwndDlg, WM_SETICON, TRUE, (LPARAM)hIcon); HICON hIconSmall = (HICON)::LoadImage(hInst, MAKEINTRESOURCE(IDI_TRUECRYPT_ICON), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR); - ::SendMessage(hwndDlg, WM_SETICON, FALSE, (LPARAM)hIconSmall); - } + ::SendMessage(hwndDlg, WM_SETICON, FALSE, (LPARAM)hIconSmall); + } LocalizeDialog (hwndDlg, NULL); _beginthread(WaitThread, 0, thParam); @@ -7076,26 +7076,26 @@ BOOL CALLBACK WaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) void BringToForeground(HWND hWnd) { if(!::IsWindow(hWnd)) return; - + DWORD lockTimeOut = 0; HWND hCurrWnd = ::GetForegroundWindow(); DWORD dwThisTID = ::GetCurrentThreadId(), dwCurrTID = ::GetWindowThreadProcessId(hCurrWnd,0); - + if (hCurrWnd != hWnd) { if(dwThisTID != dwCurrTID) { ::AttachThreadInput(dwThisTID, dwCurrTID, TRUE); - + ::SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT,0,&lockTimeOut,0); ::SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT,0,0,SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE); - + ::AllowSetForegroundWindow(ASFW_ANY); } - + ::SetForegroundWindow(hWnd); - + if(dwThisTID != dwCurrTID) { ::SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT,0,(PVOID)lockTimeOut,SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE); @@ -7168,12 +7168,12 @@ static BOOL PerformMountIoctl (MOUNT_STRUCT* pmount, LPDWORD pdwResult, BOOL use CreateFullVolumePath (pmount->wszVolume, sizeof(pmount->wszVolume), devicePath.c_str(), &bDevice); } } - + return DeviceIoControl (hDriver, TC_IOCTL_MOUNT_VOLUME, pmount, sizeof (MOUNT_STRUCT), pmount, sizeof (MOUNT_STRUCT), pdwResult, NULL); } -// specific definitions and implementation for support of mount operation +// specific definitions and implementation for support of mount operation // in wait dialog mechanism typedef struct @@ -7306,7 +7306,7 @@ retry: path = path.substr (4); StringCchCopyW (volumePath, TC_MAX_PATH, path.c_str()); } - + if (path.find (L"Volume{") == 0 && path.rfind (L"}\\") == path.size() - 2) { wstring resolvedPath = VolumeGuidPathToDevicePath (path); @@ -7318,7 +7318,7 @@ retry: if ((path.length () >= 3) && (_wcsnicmp (path.c_str(), L"ID:", 3) == 0)) { std::vector arr; - if ( (path.length() == (3 + 2*VOLUME_ID_SIZE)) + if ( (path.length() == (3 + 2*VOLUME_ID_SIZE)) && HexWideStringToArray (path.c_str() + 3, arr) && (arr.size() == VOLUME_ID_SIZE) ) @@ -7355,7 +7355,7 @@ retry: mount.BytesPerSector = bps; mount.BytesPerPhysicalSector = bps; } - + if (IsOSAtLeast (WIN_VISTA)) { if ( (wcslen(root) >= 2) @@ -7463,7 +7463,7 @@ retry: goto retry; } - // Ask user + // Ask user if (IDYES == AskWarnNoYes ("FILE_IN_USE", hwndDlg)) { mount.bExclusiveAccess = FALSE; @@ -7484,12 +7484,12 @@ retry: { if (mount.nReturnCode == ERR_PASSWORD_WRONG) { - // Do not report wrong password, if not instructed to + // Do not report wrong password, if not instructed to if (bReportWrongPassword) { IncreaseWrongPwdRetryCount (1); // We increase the count here only if bReportWrongPassword is TRUE, because "Auto-Mount All Devices" and other callers do it separately - if (WrongPwdRetryCountOverLimit () + if (WrongPwdRetryCountOverLimit () && !mount.UseBackupHeader) { // Retry using embedded header backup (if any) @@ -7537,7 +7537,7 @@ retry: if (bReportWrongPassword && !Silent) Warning ("HEADER_DAMAGED_AUTO_USED_HEADER_BAK", hwndDlg); } - + LastMountedVolumeDirty = mount.FilesystemDirty; if (mount.FilesystemDirty) @@ -7661,7 +7661,7 @@ retry: } else { - ShowWaitDialog (hwndDlg, FALSE, UnmountWaitThreadProc, ¶m); + ShowWaitDialog (hwndDlg, FALSE, UnmountWaitThreadProc, ¶m); } SetLastError (param.dwLastError); @@ -7689,8 +7689,8 @@ retry: Error ("UNMOUNT_FAILED", hwndDlg); return FALSE; - } - + } + BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, nDosDriveNo, 0); return TRUE; @@ -7939,7 +7939,7 @@ BOOL GetPhysicalDriveGeometry (int driveNumber, PDISK_GEOMETRY diskGeometry) ZeroMemory (diskGeometry, sizeof (DISK_GEOMETRY)); if ( DeviceIoControl (hDev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, diskGeometry, sizeof (DISK_GEOMETRY), &bytesRead, NULL) - && (bytesRead == sizeof (DISK_GEOMETRY)) + && (bytesRead == sizeof (DISK_GEOMETRY)) && diskGeometry->BytesPerSector) { bResult = TRUE; @@ -8006,7 +8006,7 @@ int FileSystemAppearsEmpty (const wchar_t *devicePath) // Returns the free space on the specified partition (volume) in bytes. If the 'occupiedBytes' pointer // is not NULL, size of occupied space (in bytes) is written to the pointed location. In addition, if the -// 'percent' pointer is not NULL, % of free space is stored in the pointed location. If there's an error, +// 'percent' pointer is not NULL, % of free space is stored in the pointed location. If there's an error, // returns -1. __int64 GetStatsFreeSpaceOnPartition (const wchar_t *devicePath, float *percentFree, __int64 *occupiedBytes, BOOL silent) { @@ -8094,12 +8094,12 @@ HANDLE DismountDrive (wchar_t *devName, wchar_t *devicePath) return INVALID_HANDLE_VALUE; - // Try to lock the volume first so that dismount is not forced. + // Try to lock the volume first so that dismount is not forced. // If we fail, we will dismount anyway even if it needs to be forced. CloseVolumeExplorerWindows (MainDlg, driveLetterNo); - while (!(bResult = DeviceIoControl (hVolume, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) + while (!(bResult = DeviceIoControl (hVolume, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) && attempt > 0) { Sleep (UNMOUNT_AUTO_RETRY_DELAY); @@ -8111,7 +8111,7 @@ HANDLE DismountDrive (wchar_t *devName, wchar_t *devicePath) attempt = UNMOUNT_MAX_AUTO_RETRIES; - while (!(bResult = DeviceIoControl (hVolume, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) + while (!(bResult = DeviceIoControl (hVolume, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) && attempt > 0) { Sleep (UNMOUNT_AUTO_RETRY_DELAY); @@ -8125,12 +8125,12 @@ HANDLE DismountDrive (wchar_t *devName, wchar_t *devicePath) } // Returns -1 if the specified string is not found in the buffer. Otherwise, returns the -// offset of the first occurrence of the string. The string and the buffer may contain zeroes, +// offset of the first occurrence of the string. The string and the buffer may contain zeroes, // which do NOT terminate them. int64 FindString (const char *buf, const char *str, int64 bufLen, int64 strLen, int64 startOffset) { - if (buf == NULL - || str == NULL + if (buf == NULL + || str == NULL || strLen > bufLen || bufLen < 1 || strLen < 1 @@ -8172,7 +8172,7 @@ BOOL FileExists (const wchar_t *filePathPtr) // Searches the file from its end for the LAST occurrence of the string str. // The string may contain zeroes, which do NOT terminate the string. -// If the string is found, its offset from the start of the file is returned. +// If the string is found, its offset from the start of the file is returned. // If the string isn't found or if any error occurs, -1 is returned. __int64 FindStringInFile (const wchar_t *filePath, const char* str, int strLen) { @@ -8188,8 +8188,8 @@ __int64 FindStringInFile (const wchar_t *filePath, const char* str, int strLen) int filePosStep; __int64 retVal = -1; - if (filePos <= 0 - || buffer == NULL + if (filePos <= 0 + || buffer == NULL || strLen > bufSize || strLen < 1) { @@ -8223,7 +8223,7 @@ __int64 FindStringInFile (const wchar_t *filePath, const char* str, int strLen) if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0) goto fsif_end; - if ((readRetVal = ReadFile (src, buffer, bufSize, &bytesRead, NULL)) == 0 + if ((readRetVal = ReadFile (src, buffer, bufSize, &bytesRead, NULL)) == 0 || bytesRead == 0) goto fsif_end; @@ -8316,7 +8316,7 @@ BOOL TCCopyFile (wchar_t *sourceFileName, wchar_t *destinationFile) return TCCopyFileBase (src, dst); } -// If bAppend is TRUE, the buffer is appended to an existing file. If bAppend is FALSE, any existing file +// If bAppend is TRUE, the buffer is appended to an existing file. If bAppend is FALSE, any existing file // is replaced. If an error occurs, the incomplete file is deleted (provided that bAppend is FALSE). BOOL SaveBufferToFile (const char *inputBuffer, const wchar_t *destinationFile, DWORD inputLength, BOOL bAppend, BOOL bRenameIfFailed) { @@ -8355,7 +8355,7 @@ BOOL SaveBufferToFile (const char *inputBuffer, const wchar_t *destinationFile, } } } - + if (dst == INVALID_HANDLE_VALUE) { SetLastError (dwLastError); @@ -8376,7 +8376,7 @@ BOOL SaveBufferToFile (const char *inputBuffer, const wchar_t *destinationFile, { // If CREATE_ALWAYS is used, ERROR_ALREADY_EXISTS is returned after successful overwrite // of an existing file (it's not an error) - if (! (GetLastError() == ERROR_ALREADY_EXISTS && !bAppend) ) + if (! (GetLastError() == ERROR_ALREADY_EXISTS && !bAppend) ) handleWin32Error (MainDlg, SRC_POS); } @@ -8405,7 +8405,7 @@ BOOL TCFlushFile (FILE *f) // Prints a UTF-16 text (note that this involves a real printer, not a screen). // textByteLen - length of the text in bytes -// title - printed as part of the page header and used as the filename for a temporary file +// title - printed as part of the page header and used as the filename for a temporary file BOOL PrintHardCopyTextUTF16 (wchar_t *text, wchar_t *title, size_t textByteLen) { wchar_t cl [MAX_PATH*3] = {L"/p \""}; @@ -8486,7 +8486,7 @@ BOOL IsNonInstallMode () else { // This is also returned if we fail to determine the status (it does not mean that portable mode is disproved). - return FALSE; + return FALSE; } } else @@ -8510,7 +8510,7 @@ BOOL IsNonInstallMode () if (FileExists (path)) { // To maintain consistency and safety, if the system encryption config file exits, we cannot - // allow portable mode. (This happens e.g. when the pretest fails and the user selects + // allow portable mode. (This happens e.g. when the pretest fails and the user selects // "Last Known Good Configuration" from the Windows boot menu.) // However, if UAC elevation is needed, we have to confirm portable mode first (after we are elevated, we won't). @@ -8522,7 +8522,7 @@ BOOL IsNonInstallMode () } // As the driver was not found in the system path, we can predict that we will run in portable mode - return TRUE; + return TRUE; } else CloseHandle (hDriverTmp); @@ -8669,7 +8669,7 @@ void CleanLastVisitedMRU (void) if ((len = ReadRegistryBytes (regPath, key, (char *) strTmp, sizeof (strTmp))) > 0) { - if (_wcsicmp (strTmp, strToMatch) == 0) + if (_wcsicmp (strTmp, strToMatch) == 0) { char buf[65536], bufout[sizeof (buf)]; @@ -8752,7 +8752,7 @@ LRESULT ListItemAdd (HWND list, int index, const wchar_t *string) li.mask = LVIF_TEXT; li.pszText = (wchar_t*) string; - li.iItem = index; + li.iItem = index; li.iSubItem = 0; return ListView_InsertItem (list, &li); } @@ -8765,7 +8765,7 @@ LRESULT ListSubItemSet (HWND list, int index, int subIndex, const wchar_t *strin li.mask = LVIF_TEXT; li.pszText = (wchar_t*) string; - li.iItem = index; + li.iItem = index; li.iSubItem = subIndex; return ListView_SetItem (list, &li); } @@ -8825,7 +8825,7 @@ BOOL LoadInt32 (const wchar_t *filePath, unsigned __int32 *result, __int64 fileO if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0) goto fsif_end; - if (ReadFile (src, buffer, bufSize, &bytesRead, NULL) == 0 + if (ReadFile (src, buffer, bufSize, &bytesRead, NULL) == 0 || bytesRead != bufSize) goto fsif_end; @@ -8869,7 +8869,7 @@ BOOL LoadInt16 (const wchar_t *filePath, int *result, __int64 fileOffset) if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0) goto fsif_end; - if (ReadFile (src, buffer, bufSize, &bytesRead, NULL) == 0 + if (ReadFile (src, buffer, bufSize, &bytesRead, NULL) == 0 || bytesRead != bufSize) goto fsif_end; @@ -9038,7 +9038,7 @@ wchar_t *GetProgramConfigPath (wchar_t *fileName) std::wstring GetServiceConfigPath (const wchar_t *fileName, bool useLegacy) { wchar_t sysPath[TC_MAX_PATH]; - + if (Is64BitOs() && useLegacy) { typedef UINT (WINAPI *GetSystemWow64Directory_t) (LPWSTR lpBuffer, UINT uSize); @@ -9073,18 +9073,18 @@ void TaskBarIconDisplayBalloonTooltip (HWND hwnd, wchar_t *headline, wchar_t *te return; } - NOTIFYICONDATAW tnid; + NOTIFYICONDATAW tnid; ZeroMemory (&tnid, sizeof (tnid)); - tnid.cbSize = sizeof (tnid); - tnid.hWnd = hwnd; - tnid.uID = IDI_TRUECRYPT_ICON; + tnid.cbSize = sizeof (tnid); + tnid.hWnd = hwnd; + tnid.uID = IDI_TRUECRYPT_ICON; //tnid.uVersion = (IsOSAtLeast (WIN_VISTA) ? NOTIFYICON_VERSION_4 : NOTIFYICON_VERSION); //Shell_NotifyIconW (NIM_SETVERSION, &tnid); - tnid.uFlags = NIF_INFO; + tnid.uFlags = NIF_INFO; tnid.dwInfoFlags = (warning ? NIIF_WARNING : NIIF_INFO); tnid.uTimeout = (IsOSAtLeast (WIN_VISTA) ? 1000 : 5000); // in ms @@ -9100,12 +9100,12 @@ void TaskBarIconDisplayBalloonTooltip (HWND hwnd, wchar_t *headline, wchar_t *te // Either of the pointers may be NULL void InfoBalloon (char *headingStringId, char *textStringId, HWND hwnd) { - if (Silent) + if (Silent) return; TaskBarIconDisplayBalloonTooltip (hwnd, - headingStringId == NULL ? L"VeraCrypt" : GetString (headingStringId), - textStringId == NULL ? L" " : GetString (textStringId), + headingStringId == NULL ? L"VeraCrypt" : GetString (headingStringId), + textStringId == NULL ? L" " : GetString (textStringId), FALSE); } @@ -9113,12 +9113,12 @@ void InfoBalloon (char *headingStringId, char *textStringId, HWND hwnd) // Either of the pointers may be NULL void InfoBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd) { - if (Silent) + if (Silent) return; TaskBarIconDisplayBalloonTooltip (hwnd, - headingString == NULL ? L"VeraCrypt" : headingString, - textString == NULL ? L" " : textString, + headingString == NULL ? L"VeraCrypt" : headingString, + textString == NULL ? L" " : textString, FALSE); } @@ -9126,12 +9126,12 @@ void InfoBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd) // Either of the pointers may be NULL void WarningBalloon (char *headingStringId, char *textStringId, HWND hwnd) { - if (Silent) + if (Silent) return; TaskBarIconDisplayBalloonTooltip (hwnd, - headingStringId == NULL ? L"VeraCrypt" : GetString (headingStringId), - textStringId == NULL ? L" " : GetString (textStringId), + headingStringId == NULL ? L"VeraCrypt" : GetString (headingStringId), + textStringId == NULL ? L" " : GetString (textStringId), TRUE); } @@ -9139,12 +9139,12 @@ void WarningBalloon (char *headingStringId, char *textStringId, HWND hwnd) // Either of the pointers may be NULL void WarningBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd) { - if (Silent) + if (Silent) return; TaskBarIconDisplayBalloonTooltip (hwnd, - headingString == NULL ? L"VeraCrypt" : headingString, - textString == NULL ? L" " : textString, + headingString == NULL ? L"VeraCrypt" : headingString, + textString == NULL ? L" " : textString, TRUE); } @@ -9347,7 +9347,7 @@ int AskMultiChoice (void *strings[], BOOL bBold, HWND hwnd) params.strings = &strings[0]; params.bold = bBold; - return (int) DialogBoxParamW (hInst, + return (int) DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_MULTI_CHOICE_DLG), hwnd, (DLGPROC) MultiChoiceDialogProc, (LPARAM) ¶ms); } @@ -9356,7 +9356,7 @@ int AskMultiChoice (void *strings[], BOOL bBold, HWND hwnd) BOOL ConfigWriteBegin () { DWORD size; - if (ConfigFileHandle != NULL) + if (ConfigFileHandle != NULL) return FALSE; if (ConfigBuffer == NULL) @@ -9540,7 +9540,7 @@ void ConfigReadCompareString (char *configKey, char *defaultValue, char *str, in *pbModified = TRUE; if (!bOnlyCheckModified) ConfigReadString (configKey, defaultValue, str, maxLen); - + } } @@ -9597,7 +9597,7 @@ BOOL LoadDefaultKeyFilesParam (void) char *xml = defaultKeyfilesFile; KeyFile *kf; - if (xml == NULL) + if (xml == NULL) return FALSE; KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile); @@ -9738,7 +9738,7 @@ BOOL IsServerOS () } -// Returns TRUE, if the currently running operating system is installed in a hidden volume. If it's not, or if +// Returns TRUE, if the currently running operating system is installed in a hidden volume. If it's not, or if // there's an error, returns FALSE. BOOL IsHiddenOSRunning (void) { @@ -9777,30 +9777,30 @@ BOOL EnableWow64FsRedirection (BOOL enable) BOOL RestartComputer (void) { - TOKEN_PRIVILEGES tokenPrivil; - HANDLE hTkn; + TOKEN_PRIVILEGES tokenPrivil; + HANDLE hTkn; if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES, &hTkn)) { - return false; + return false; } - LookupPrivilegeValue (NULL, SE_SHUTDOWN_NAME, &tokenPrivil.Privileges[0].Luid); - tokenPrivil.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - tokenPrivil.PrivilegeCount = 1; + LookupPrivilegeValue (NULL, SE_SHUTDOWN_NAME, &tokenPrivil.Privileges[0].Luid); + tokenPrivil.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + tokenPrivil.PrivilegeCount = 1; - AdjustTokenPrivileges (hTkn, false, &tokenPrivil, 0, (PTOKEN_PRIVILEGES) NULL, 0); - if (GetLastError() != ERROR_SUCCESS) + AdjustTokenPrivileges (hTkn, false, &tokenPrivil, 0, (PTOKEN_PRIVILEGES) NULL, 0); + if (GetLastError() != ERROR_SUCCESS) { CloseHandle(hTkn); - return false; + return false; } if (!ExitWindowsEx (EWX_REBOOT, - SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED)) + SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED)) { CloseHandle(hTkn); - return false; + return false; } CloseHandle(hTkn); @@ -9873,7 +9873,7 @@ std::wstring GetWindowsEdition () osname += L"-server"; if (IsOSAtLeast (WIN_VISTA)) - { + { if (home) osname += L"-home"; else if (wcsstr (productName, L"Standard") != 0) @@ -10068,7 +10068,7 @@ void HandleDriveNotReadyError (HWND hwnd) 0, KEY_READ, &hkey) != ERROR_SUCCESS) return; - if (RegQueryValueEx (hkey, L"NoAutoMount", 0, 0, (LPBYTE) &value, &size) == ERROR_SUCCESS + if (RegQueryValueEx (hkey, L"NoAutoMount", 0, 0, (LPBYTE) &value, &size) == ERROR_SUCCESS && value != 0) { Warning ("SYS_AUTOMOUNT_DISABLED", hwnd); @@ -10124,7 +10124,7 @@ BOOL CALLBACK FindTCWindowEnum (HWND hwnd, LPARAM lParam) BYTE *MapResource (wchar_t *resourceType, int resourceId, PDWORD size) { - HGLOBAL hResL; + HGLOBAL hResL; HRSRC hRes; hRes = FindResource (NULL, MAKEINTRESOURCE(resourceId), resourceType); @@ -10132,7 +10132,7 @@ BYTE *MapResource (wchar_t *resourceType, int resourceId, PDWORD size) if (size != NULL) *size = SizeofResource (NULL, hRes); - + return (BYTE *) LockResource (hResL); } @@ -10205,8 +10205,8 @@ int OpenVolume (OpenVolumeContext *context, const wchar_t *volumePath, Password if (context->IsDevice) { - // Try to gain "raw" access to the partition in case there is a live filesystem on it (otherwise, - // the NTFS driver guards hidden sectors and prevents e.g. header backup restore after the user + // Try to gain "raw" access to the partition in case there is a live filesystem on it (otherwise, + // the NTFS driver guards hidden sectors and prevents e.g. header backup restore after the user // accidentally quick-formats a dismounted partition-hosted TrueCrypt volume as NTFS, etc.) DeviceIoControl (context->HostFileHandle, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, 0, NULL, 0, &dwResult, NULL); @@ -10299,7 +10299,7 @@ int OpenVolume (OpenVolumeContext *context, const wchar_t *volumePath, Password && context->IsDevice) { // If FSCTL_ALLOW_EXTENDED_DASD_IO failed and there is a live filesystem on the partition, then the - // filesystem driver may report EOF when we are reading hidden sectors (when the filesystem is + // filesystem driver may report EOF when we are reading hidden sectors (when the filesystem is // shorter than the partition). This can happen for example after the user quick-formats a dismounted // partition-hosted TrueCrypt volume and then tries to read the embedded backup header. @@ -10355,7 +10355,7 @@ void CloseVolume (OpenVolumeContext *context) int ReEncryptVolumeHeader (HWND hwndDlg, char *buffer, BOOL bBoot, CRYPTO_INFO *cryptoInfo, Password *password, int pim, BOOL wipeMode) { CRYPTO_INFO *newCryptoInfo = NULL; - + RandSetHashFunction (cryptoInfo->pkcs5); if (Randinit() != ERR_SUCCESS) @@ -10401,7 +10401,7 @@ BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) wchar_t data[65536]; DWORD size = sizeof (data); - + if (IsPagingFileWildcardActive()) return TRUE; @@ -10426,7 +10426,7 @@ BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) } HANDLE handle = CreateFile (drivePath.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - + if (handle == INVALID_HANDLE_VALUE) continue; @@ -10446,7 +10446,7 @@ BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) path[0] = drive; handle = CreateFile (path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); - + if (handle != INVALID_HANDLE_VALUE) CloseHandle (handle); else if (GetLastError() == ERROR_SHARING_VIOLATION) @@ -10488,7 +10488,7 @@ std::wstring SingleStringToWide (const std::string &singleString) WCHAR wbuf[65536]; int wideLen = MultiByteToWideChar (CP_ACP, 0, singleString.c_str(), -1, wbuf, array_capacity (wbuf) - 1); - + // We don't throw exception here and only return empty string. // All calls to this function use valid strings. // throw_sys_if (wideLen == 0); @@ -10531,7 +10531,7 @@ std::string WideToUtf8String (const std::wstring &wideString) BOOL CALLBACK SecurityTokenPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { WORD lw = LOWORD (wParam); - static string *password; + static string *password; switch (msg) { @@ -10578,7 +10578,7 @@ BOOL CALLBACK SecurityTokenPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wPara wchar_t tmp[SecurityToken::MaxPasswordLength+1]; wmemset (tmp, 'X', SecurityToken::MaxPasswordLength); tmp[SecurityToken::MaxPasswordLength] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD), tmp); EndDialog (hwndDlg, lw); } @@ -10699,8 +10699,8 @@ static void SecurityTokenKeyfileDlgFillList (HWND hwndDlg, const vector push_back (SecurityTokenKeyfilePath (keyfile)); - } + } } EndDialog (hwndDlg, IDOK); @@ -11062,7 +11062,7 @@ std::vector GetAvailableHostDevices (bool noDeviceProperties, bool || ((partNumber == 0) && GetPhysicalDriveGeometry (devNumber, &deviceGeometry)) ) { - device.Size = deviceGeometry.Cylinders.QuadPart * (LONGLONG) deviceGeometry.BytesPerSector + device.Size = deviceGeometry.Cylinders.QuadPart * (LONGLONG) deviceGeometry.BytesPerSector * (LONGLONG) deviceGeometry.SectorsPerTrack * (LONGLONG) deviceGeometry.TracksPerCylinder; } } @@ -11306,7 +11306,7 @@ int AskNonSysInPlaceEncryptionResume (HWND hwndDlg, BOOL *pbDecrypt) return IDYES; default: break; - } + } } char *multiChoiceStr[] = { 0, "ASK_NONSYS_INPLACE_ENC_NOTIFICATION_REMOVAL", "DO_NOT_PROMPT_ME", "KEEP_PROMPTING_ME", 0 }; @@ -11399,7 +11399,7 @@ void EnableElevatedCursorChange (HWND parent) HWND hWnd; memset (&winClass, 0, sizeof (winClass)); - winClass.cbSize = sizeof (WNDCLASSEX); + winClass.cbSize = sizeof (WNDCLASSEX); winClass.lpfnWndProc = (WNDPROC) EnableElevatedCursorChangeWndProc; winClass.hInstance = hInst; winClass.lpszClassName = className; @@ -11430,7 +11430,7 @@ BOOL DisableFileCompression (HANDLE file) return TRUE; format = COMPRESSION_FORMAT_NONE; - return DeviceIoControl (file, FSCTL_SET_COMPRESSION, &format, sizeof (format), NULL, 0, &bytesOut, NULL); + return DeviceIoControl (file, FSCTL_SET_COMPRESSION, &format, sizeof (format), NULL, 0, &bytesOut, NULL); } @@ -11779,8 +11779,8 @@ void ProcessEntropyEstimate (HWND hProgress, DWORD* pdwInitialValue, DWORD dwCou } else { - if ( *pdwEntropy < dwMaxLevel - && (dwCounter >= *pdwInitialValue) + if ( *pdwEntropy < dwMaxLevel + && (dwCounter >= *pdwInitialValue) && (dwCounter - *pdwInitialValue) <= dwMaxLevel) *pdwEntropy = dwCounter - *pdwInitialValue; else @@ -11797,7 +11797,7 @@ void ProcessEntropyEstimate (HWND hProgress, DWORD* pdwInitialValue, DWORD dwCou SendMessage (hProgress, PBM_SETSTATE, state, 0); } - SendMessage (hProgress, PBM_SETPOS, + SendMessage (hProgress, PBM_SETPOS, (WPARAM) (*pdwEntropy), 0); } @@ -11834,7 +11834,7 @@ BOOL TranslateVolumeID (HWND hwndDlg, wchar_t* pathValue, size_t cchPathValue) if ((pathLen >= 3) && (_wcsnicmp (pathValue, L"ID:", 3) == 0)) { std::vector arr; - if ( (pathLen == (3 + 2*VOLUME_ID_SIZE)) + if ( (pathLen == (3 + 2*VOLUME_ID_SIZE)) && HexWideStringToArray (pathValue + 3, arr) && (arr.size() == VOLUME_ID_SIZE) ) @@ -11859,7 +11859,7 @@ BOOL TranslateVolumeID (HWND hwndDlg, wchar_t* pathValue, size_t cchPathValue) bRet = FALSE; } } - + return bRet; } diff --git a/src/Common/Dlgcode.h b/src/Common/Dlgcode.h index dd6eb801..9387336e 100644 --- a/src/Common/Dlgcode.h +++ b/src/Common/Dlgcode.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -132,7 +132,7 @@ extern int CurrentOSServicePack; extern BOOL RemoteSession; extern HANDLE hDriver; extern HINSTANCE hInst; -extern int SystemEncryptionStatus; +extern int SystemEncryptionStatus; extern WipeAlgorithmId nWipeMode; extern BOOL bSysPartitionSelected; extern BOOL bSysDriveSelected; @@ -170,11 +170,11 @@ enum tc_app_msg_ids TC_APPMSG_SYSENC_CONFIG_UPDATE = WM_APP + 101, TC_APPMSG_TASKBAR_ICON = WM_APP + 102, TC_APPMSG_LOAD_TEXT_BOX_CONTENT = WM_APP + 103, - // Mount + // Mount TC_APPMSG_MOUNT_ENABLE_DISABLE_CONTROLS = WM_APP + 201, TC_APPMSG_MOUNT_SHOW_WINDOW = WM_APP + 202, TC_APPMSG_PREBOOT_PASSWORD_MODE = WM_APP + 203, - // Format + // Format TC_APPMSG_VOL_TRANSFORM_THREAD_ENDED = WM_APP + 301, TC_APPMSG_FORMAT_FINISHED = WM_APP + 302, TC_APPMSG_FORMAT_USER_QUIT = WM_APP + 303, diff --git a/src/Common/EncryptionThreadPool.c b/src/Common/EncryptionThreadPool.c index 9cc641cc..f0889a34 100644 --- a/src/Common/EncryptionThreadPool.c +++ b/src/Common/EncryptionThreadPool.c @@ -3,7 +3,7 @@ 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) + 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 @@ -182,13 +182,13 @@ static TC_THREAD_PROC EncryptionThreadProc (void *threadArg) workItem->KeyDerivation.IterationCount, workItem->KeyDerivation.DerivedKey, GetMaxPkcs5OutSize()); break; - default: + default: TC_THROW_FATAL_EXCEPTION; - } + } InterlockedExchange (workItem->KeyDerivation.CompletionFlag, TRUE); TC_SET_EVENT (*workItem->KeyDerivation.CompletionEvent); - + if (InterlockedDecrement (workItem->KeyDerivation.OutstandingWorkItemCount) == 0) TC_SET_EVENT (*workItem->KeyDerivation.NoOutstandingWorkItemEvent); @@ -256,12 +256,12 @@ BOOL EncryptionThreadPoolStart (size_t encryptionFreeCpuCount) WorkItemReadyEvent = CreateEvent (NULL, FALSE, FALSE, NULL); if (!WorkItemReadyEvent) return FALSE; - + WorkItemCompletedEvent = CreateEvent (NULL, FALSE, FALSE, NULL); if (!WorkItemCompletedEvent) return FALSE; #endif - + #ifdef DEVICE_DRIVER ExInitializeFastMutex (&DequeueMutex); ExInitializeFastMutex (&EnqueueMutex); @@ -400,10 +400,10 @@ void EncryptionThreadPoolDoWork (EncryptionThreadPoolWorkType type, byte *data, EncryptionThreadPoolWorkItem *workItem; EncryptionThreadPoolWorkItem *firstFragmentWorkItem; - + if (unitCount == 0) return; - + if (!ThreadPoolRunning || unitCount == 1) { switch (type) @@ -432,7 +432,7 @@ void EncryptionThreadPoolDoWork (EncryptionThreadPoolWorkType type, byte *data, else { /* Note that it is not efficient to divide the data into fragments smaller than a few hundred bytes. - The reason is that the overhead associated with thread handling would in most cases make a multi-threaded + The reason is that the overhead associated with thread handling would in most cases make a multi-threaded process actually slower than a single-threaded process. */ fragmentCount = ThreadCount; @@ -442,7 +442,7 @@ void EncryptionThreadPoolDoWork (EncryptionThreadPoolWorkType type, byte *data, if (remainder > 0) ++unitsPerFragment; } - + fragmentData = data; fragmentStartUnitNo = startUnitNo->Value; diff --git a/src/Common/EncryptionThreadPool.h b/src/Common/EncryptionThreadPool.h index 5ca131f5..9bc10c94 100644 --- a/src/Common/EncryptionThreadPool.h +++ b/src/Common/EncryptionThreadPool.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Common/Endian.c b/src/Common/Endian.c index 44d96e40..0327a102 100644 --- a/src/Common/Endian.c +++ b/src/Common/Endian.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Common/Endian.h b/src/Common/Endian.h index 7d97e5fb..00fed048 100644 --- a/src/Common/Endian.h +++ b/src/Common/Endian.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -110,7 +110,7 @@ extern "C" ( ( unsigned __int32 ) memPtr[ -2 ] << 8 ) | ( unsigned __int32 ) memPtr[ -1 ] ) #define mgetWord(memPtr) \ - ( memPtr += 2, ((( unsigned short ) memPtr[ -2 ] << 8 ) | ( ( unsigned short ) memPtr[ -1 ] )) ) + ( memPtr += 2, ((( unsigned short ) memPtr[ -2 ] << 8 ) | ( ( unsigned short ) memPtr[ -1 ] )) ) #define mgetByte(memPtr) \ ( ( unsigned char ) *memPtr++ ) @@ -139,7 +139,7 @@ unsigned __int16 MirrorBytes16 (unsigned __int16 x); unsigned __int32 MirrorBytes32 (unsigned __int32 x); #ifndef TC_NO_COMPILER_INT64 uint64 MirrorBytes64 (uint64 x); -#endif +#endif void LongReverse ( unsigned __int32 *buffer , unsigned byteCount ); #if defined(__cplusplus) diff --git a/src/Common/Exception.h b/src/Common/Exception.h index c4cd1b10..e7a790a1 100644 --- a/src/Common/Exception.h +++ b/src/Common/Exception.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Common/Fat.c b/src/Common/Fat.c index fadb80b1..fb7dc1ff 100644 --- a/src/Common/Fat.c +++ b/src/Common/Fat.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -58,7 +58,7 @@ GetFatParams (fatparams * ft) clusterSize = 512; ft->cluster_size = clusterSize / ft->sector_size; - + if (ft->cluster_size == 0) ft->cluster_size = 1; @@ -73,8 +73,8 @@ GetFatParams (fatparams * ft) ft->cluster_size = 1; // Geometry always set to SECTORS/1/1 - ft->secs_track = 1; - ft->heads = 1; + ft->secs_track = 1; + ft->heads = 1; ft->dir_entries = 512; ft->fats = 2; @@ -98,7 +98,7 @@ GetFatParams (fatparams * ft) ft->cluster_count = (int) (((__int64) fatsecs * ft->sector_size) / (ft->cluster_size * ft->sector_size)); ft->fat_length = (ft->cluster_count * 2 + ft->sector_size - 1) / ft->sector_size; } - + if(ft->cluster_count >= 65525) // FAT32 { ft->size_fat = 32; @@ -165,13 +165,13 @@ PutBoot (fatparams * ft, unsigned char *boot) cnt += 2; boot[cnt++] = (__int8) ft->media; /* media byte */ - if(ft->size_fat == 32) + if(ft->size_fat == 32) { boot[cnt++] = 0x00; boot[cnt++] = 0x00; } - else - { + else + { *(__int16 *)(boot + cnt) = LE16((uint16) ft->fat_length); /* fat size */ cnt += 2; } @@ -233,13 +233,13 @@ static void PutFSInfo (unsigned char *sector, fatparams *ft) { memset (sector, 0, ft->sector_size); sector[3]=0x41; /* LeadSig */ - sector[2]=0x61; - sector[1]=0x52; - sector[0]=0x52; + sector[2]=0x61; + sector[1]=0x52; + sector[0]=0x52; sector[484+3]=0x61; /* StrucSig */ - sector[484+2]=0x41; - sector[484+1]=0x72; - sector[484+0]=0x72; + sector[484+2]=0x41; + sector[484+1]=0x72; + sector[484+0]=0x72; // Free cluster count *(uint32 *)(sector + 488) = LE32 (ft->cluster_count - ft->size_root_dir / ft->sector_size / ft->cluster_size); @@ -293,7 +293,7 @@ FormatFat (void* hwndDlgPtr, unsigned __int64 startSector, fatparams * ft, void goto fail; /* fat32 boot area */ - if (ft->size_fat == 32) + if (ft->size_fat == 32) { /* fsinfo */ PutFSInfo((unsigned char *) sector, ft); @@ -311,7 +311,7 @@ FormatFat (void* hwndDlgPtr, unsigned __int64 startSector, fatparams * ft, void cryptoInfo) == FALSE) goto fail; } - + /* bootsector backup */ memset (sector, 0, ft->sector_size); PutBoot (ft, (unsigned char *) sector); @@ -354,7 +354,7 @@ FormatFat (void* hwndDlgPtr, unsigned __int64 startSector, fatparams * ft, void fat_sig[8] = fat_sig[9] = fat_sig[10] = 0xff; fat_sig[11] = 0x0f; memcpy (sector, fat_sig, 12); - } + } else if (ft->size_fat == 16) { fat_sig[0] = (unsigned char) ft->media; @@ -407,7 +407,7 @@ FormatFat (void* hwndDlgPtr, unsigned __int64 startSector, fatparams * ft, void goto fail; // Temporary secondary key (XTS mode) - if (!RandgetBytes (hwndDlg, cryptoInfo->k2, sizeof cryptoInfo->k2, FALSE)) + if (!RandgetBytes (hwndDlg, cryptoInfo->k2, sizeof cryptoInfo->k2, FALSE)) goto fail; retVal = EAInit (cryptoInfo->ea, temporaryKey, cryptoInfo->ks); diff --git a/src/Common/Fat.h b/src/Common/Fat.h index b637f8ec..2d1264c8 100644 --- a/src/Common/Fat.h +++ b/src/Common/Fat.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Common/Format.c b/src/Common/Format.c index 43a96d04..f3114e5e 100644 --- a/src/Common/Format.c +++ b/src/Common/Format.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -60,7 +60,7 @@ uint64 GetVolumeDataAreaSize (BOOL hiddenVolume, uint64 volumeSize) #if TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH < TC_MAX_VOLUME_SECTOR_SIZE # error TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH too small. #endif - + if (volumeSize < TC_VOLUME_SMALL_SIZE_THRESHOLD) reservedSize = TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE; else @@ -108,16 +108,16 @@ int TCFormatVolume (volatile FORMAT_VOL_PARAMETERS *volParams) || FormatSectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0) { Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg); - return ERR_DONT_REPORT; + return ERR_DONT_REPORT; } /* WARNING: Note that if Windows fails to format the volume as NTFS and the volume size is less than the maximum FAT size, the user is asked within this function whether he wants to instantly retry FAT format instead (to avoid having to re-create the whole container again). If the user - answers yes, some of the input parameters are modified, the code below 'begin_format' is re-executed - and some destructive operations that were performed during the first attempt must be (and are) skipped. + answers yes, some of the input parameters are modified, the code below 'begin_format' is re-executed + and some destructive operations that were performed during the first attempt must be (and are) skipped. Therefore, whenever adding or modifying any potentially destructive operations below 'begin_format', - determine whether they (or their portions) need to be skipped during such a second attempt; if so, + determine whether they (or their portions) need to be skipped during such a second attempt; if so, use the 'bInstantRetryOtherFilesys' flag to skip them. */ if (volParams->hiddenVol) @@ -187,17 +187,17 @@ begin_format: if ((dev = DismountDrive (devName, volParams->volumePath)) == INVALID_HANDLE_VALUE) { Error ("FORMAT_CANT_DISMOUNT_FILESYS", hwndDlg); - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto error; } - /* Gain "raw" access to the partition (it contains a live filesystem and the filesystem driver + /* Gain "raw" access to the partition (it contains a live filesystem and the filesystem driver would otherwise prevent us from writing to hidden sectors). */ if (!DeviceIoControl (dev, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, - 0, + 0, NULL, 0, &dwResult, @@ -208,7 +208,7 @@ begin_format: } else if (IsOSAtLeast (WIN_VISTA) && driveLetter == -1) { - // Windows Vista doesn't allow overwriting sectors belonging to an unformatted partition + // Windows Vista doesn't allow overwriting sectors belonging to an unformatted partition // to which no drive letter has been assigned under the system. This problem can be worked // around by assigning a drive letter to the partition temporarily. @@ -219,7 +219,7 @@ begin_format: BOOL bResult = FALSE; tmpDriveLetter = GetFirstAvailableDrive (); - + if (tmpDriveLetter != -1) { rootPath[0] += (wchar_t) tmpDriveLetter; @@ -233,7 +233,7 @@ begin_format: szDriveLetter, volParams->volumePath); - if (bResult + if (bResult && SetVolumeMountPoint (rootPath, uniqVolName)) { // The drive letter can be removed now @@ -245,21 +245,21 @@ begin_format: // For extra safety, we will try to gain "raw" access to the partition. Note that this should actually be // redundant because if the filesystem was mounted, we already tried to obtain DASD above. If we failed, - // bFailedRequiredDASD was set to TRUE and therefore we will perform pseudo "quick format" below. However, + // bFailedRequiredDASD was set to TRUE and therefore we will perform pseudo "quick format" below. However, // for extra safety, in case IsDeviceMounted() failed to detect a live filesystem, we will blindly // send FSCTL_ALLOW_EXTENDED_DASD_IO (possibly for a second time) without checking the result. DeviceIoControl (dev, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, - 0, + 0, NULL, 0, &dwResult, NULL); - // If DASD is needed but we failed to obtain it, perform open - 'quick format' - close - open + // If DASD is needed but we failed to obtain it, perform open - 'quick format' - close - open // so that the filesystem driver does not prevent us from formatting hidden sectors. for (nPass = (bFailedRequiredDASD ? 0 : 1); nPass < 2; nPass++) { @@ -285,7 +285,7 @@ begin_format: { if (!volParams->bForceOperation && (Silent || (IDNO == MessageBoxW (volParams->hwndDlg, GetString ("DEVICE_IN_USE_FORMAT"), lpszTitle, MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2)))) { - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto error; } } @@ -293,7 +293,7 @@ begin_format: { handleWin32Error (volParams->hwndDlg, SRC_POS); Error ("CANT_ACCESS_VOL", hwndDlg); - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto error; } } @@ -306,13 +306,13 @@ begin_format: char buf [2 * TC_MAX_VOLUME_SECTOR_SIZE]; DWORD bw; - // Perform pseudo "quick format" so that the filesystem driver does not prevent us from + // Perform pseudo "quick format" so that the filesystem driver does not prevent us from // formatting hidden sectors memset (buf, 0, sizeof (buf)); if (!WriteFile (dev, buf, sizeof (buf), &bw, NULL)) { - nStatus = ERR_OS_ERROR; + nStatus = ERR_OS_ERROR; goto error; } @@ -325,7 +325,7 @@ begin_format: if (DeviceIoControl (dev, FSCTL_IS_VOLUME_MOUNTED, NULL, 0, NULL, 0, &dwResult, NULL)) { Error ("FORMAT_CANT_DISMOUNT_FILESYS", hwndDlg); - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto error; } } @@ -339,7 +339,7 @@ begin_format: if (dev == INVALID_HANDLE_VALUE) { - nStatus = ERR_OS_ERROR; + nStatus = ERR_OS_ERROR; goto error; } @@ -356,7 +356,7 @@ begin_format: DWORD tmp; if (!DeviceIoControl (dev, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &tmp, NULL)) { - nStatus = ERR_OS_ERROR; + nStatus = ERR_OS_ERROR; goto error; } } @@ -391,13 +391,13 @@ begin_format: // Check hidden volume size if (volParams->hiddenVolHostSize < TC_MIN_HIDDEN_VOLUME_HOST_SIZE || volParams->hiddenVolHostSize > TC_MAX_HIDDEN_VOLUME_HOST_SIZE) - { + { nStatus = ERR_VOL_SIZE_WRONG; goto error; } // Seek to hidden volume header location - + headerOffset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET; if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN)) @@ -458,7 +458,7 @@ begin_format: // Validate the offset if (dataOffset % FormatSectorSize != 0) { - nStatus = ERR_VOL_SIZE_WRONG; + nStatus = ERR_VOL_SIZE_WRONG; goto error; } @@ -478,7 +478,7 @@ begin_format: if (volParams->bDevice && !StartFormatWriteThread()) { - nStatus = ERR_OS_ERROR; + nStatus = ERR_OS_ERROR; goto error; } @@ -488,11 +488,11 @@ begin_format: StopFormatWriteThread(); break; - + case FILESYS_FAT: if (num_sectors > 0xFFFFffff) { - nStatus = ERR_VOL_SIZE_WRONG; + nStatus = ERR_VOL_SIZE_WRONG; goto error; } @@ -506,12 +506,12 @@ begin_format: ft.sector_size = (uint16) FormatSectorSize; ft.cluster_size = volParams->clusterSize; memcpy (ft.volume_name, "NO NAME ", 11); - GetFatParams (&ft); + GetFatParams (&ft); *(volParams->realClusterSize) = ft.cluster_size * FormatSectorSize; if (volParams->bDevice && !StartFormatWriteThread()) { - nStatus = ERR_OS_ERROR; + nStatus = ERR_OS_ERROR; goto error; } @@ -523,7 +523,7 @@ begin_format: break; default: - nStatus = ERR_PARAMETER_INCORRECT; + nStatus = ERR_PARAMETER_INCORRECT; goto error; } @@ -883,14 +883,14 @@ BOOL FormatFs (int driveNo, int clusterSize, int fsType) return FALSE; } - + if (GetSystemDirectory (dllPath, MAX_PATH)) { StringCchCatW(dllPath, ARRAYSIZE(dllPath), L"\\fmifs.dll"); } else StringCchCopyW(dllPath, ARRAYSIZE(dllPath), L"C:\\Windows\\System32\\fmifs.dll"); - + hModule = LoadLibrary (dllPath); if (hModule == NULL) @@ -905,7 +905,7 @@ BOOL FormatFs (int driveNo, int clusterSize, int fsType) StringCchCatW (dir, ARRAYSIZE(dir), L":\\"); FormatExError = TRUE; - + // Windows sometimes fails to format a volume (hosted on a removable medium) as NTFS. // It often helps to retry several times. for (i = 0; i < 50 && FormatExError; i++) @@ -939,7 +939,7 @@ BOOL WriteSector (void *dev, char *sector, if (*write_buf_cnt == FormatWriteBufferSize && !FlushFormatWriteBuffer (dev, write_buf, write_buf_cnt, nSecNo, cryptoInfo)) return FALSE; - + if (GetTickCount () - updateTime > 25) { if (UpdateProgressBar (*nSecNo * FormatSectorSize)) @@ -962,7 +962,7 @@ static HANDLE WriteBufferEmptyEvent; static HANDLE WriteBufferFullEvent; static volatile HANDLE WriteRequestHandle; -static volatile int WriteRequestSize; +static volatile int WriteRequestSize; static volatile DWORD WriteRequestResult; @@ -985,7 +985,7 @@ static void __cdecl FormatWriteThreadProc (void *arg) if (!WriteFile (WriteRequestHandle, WriteThreadBuffer, WriteRequestSize, &bytesWritten, NULL)) WriteRequestResult = GetLastError(); - else + else WriteRequestResult = ERROR_SUCCESS; if (!SetEvent (WriteBufferEmptyEvent)) @@ -1082,7 +1082,7 @@ BOOL FlushFormatWriteBuffer (void *dev, char *write_buf, int *write_buf_cnt, __i { if (WaitForSingleObject (WriteBufferEmptyEvent, INFINITE) == WAIT_FAILED) return FALSE; - + if (WriteRequestResult != ERROR_SUCCESS) { SetEvent (WriteBufferEmptyEvent); diff --git a/src/Common/Format.h b/src/Common/Format.h index de342b93..0d29ab3b 100644 --- a/src/Common/Format.h +++ b/src/Common/Format.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -21,7 +21,7 @@ extern "C" { #endif // FMIFS -typedef BOOLEAN (__stdcall *PFMIFSCALLBACK)( int command, DWORD subCommand, PVOID parameter ); +typedef BOOLEAN (__stdcall *PFMIFSCALLBACK)( int command, DWORD subCommand, PVOID parameter ); typedef VOID (__stdcall *PFORMATEX)( PWCHAR DriveRoot, DWORD MediaFlag, PWCHAR Format, PWCHAR Label, BOOL QuickFormat, DWORD ClusterSize, PFMIFSCALLBACK Callback ); typedef struct diff --git a/src/Common/GfMul.c b/src/Common/GfMul.c index 9cd74a89..970e6318 100644 --- a/src/Common/GfMul.c +++ b/src/Common/GfMul.c @@ -24,11 +24,11 @@ --------------------------------------------------------------------------- Issue Date: 31/01/2004 - My thanks to John Viega and David McGrew for their support in developing + My thanks to John Viega and David McGrew for their support in developing this code and to David for testing it on a big-endain system. */ -/* +/* --------------------------------------------------------------------------- Portions Copyright (c) 2005 TrueCrypt Developers Association @@ -630,9 +630,9 @@ int Gf128Tab64Init (unsigned __int8 *a, GfCtx *ctx) compile_8k_table (am, ctx8k); /* Convert 8k LSB-first table to 4k MSB-first */ - for (i = 16; i < 32; i++) + for (i = 16; i < 32; i++) { - for (j = 0; j < 16; j++) + for (j = 0; j < 16; j++) { int jm = 0; jm |= (j & 0x1) << 3; @@ -658,7 +658,7 @@ int Gf128Tab64Init (unsigned __int8 *a, GfCtx *ctx) /* Multiply a 128-bit number by a 64-bit number in the finite field GF(2^128) */ void Gf128MulBy64Tab (unsigned __int8 a[8], unsigned __int8 p[16], GfCtx *ctx) -{ +{ unsigned __int32 r[CBLK_LEN >> 2]; move_block_aligned(r, ctx->gf_t128[7*2][a[7] & 15]); @@ -751,7 +751,7 @@ BOOL GfMulSelfTest () } GfMul128Basic (a, b, p1); - + Gf128Tab64Init (a, gfCtx); Gf128MulBy64Tab (b + 8, p2, gfCtx); diff --git a/src/Common/Inflate.c b/src/Common/Inflate.c index 2d8c96b6..cb46b098 100644 --- a/src/Common/Inflate.c +++ b/src/Common/Inflate.c @@ -1311,7 +1311,7 @@ int DecompressDeflatedData (char *out, char *in, int inLength) G.incnt = inLength; G.outCounter = 0; - if (inflate(__G) != 0) + if (inflate(__G) != 0) { // Error decompressing return 0; diff --git a/src/Common/Inflate.h b/src/Common/Inflate.h index c2810c82..8420f3dc 100644 --- a/src/Common/Inflate.h +++ b/src/Common/Inflate.h @@ -10,17 +10,17 @@ typedef unsigned char uch; typedef unsigned short ush; typedef void zvoid; -typedef struct huft +typedef struct huft { uch b, e; - union + union { ush n; struct huft *t; }v; }; -typedef struct +typedef struct { uch *inptr, *outbufptr; int incnt; diff --git a/src/Common/Keyfiles.c b/src/Common/Keyfiles.c index c59ab374..10f49b5d 100644 --- a/src/Common/Keyfiles.c +++ b/src/Common/Keyfiles.c @@ -3,7 +3,7 @@ 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) + 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 @@ -218,7 +218,7 @@ static BOOL KeyFileProcess (unsigned __int8 *keyPool, KeyFile *keyFile) else if (totalRead == 0) { status = FALSE; - SetLastError (ERROR_HANDLE_EOF); + SetLastError (ERROR_HANDLE_EOF); } close: @@ -275,7 +275,7 @@ BOOL KeyFilesApplyWithPin (HWND hwndDlg, Password *password, char* pin, KeyFile if (keyfileData.empty()) { - SetLastError (ERROR_HANDLE_EOF); + SetLastError (ERROR_HANDLE_EOF); handleWin32Error (hwndDlg, SRC_POS); Error ("ERR_PROCESS_KEYFILE", hwndDlg); status = FALSE; @@ -342,7 +342,7 @@ BOOL KeyFilesApplyWithPin (HWND hwndDlg, Password *password, char* pin, KeyFile 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) @@ -355,7 +355,7 @@ BOOL KeyFilesApplyWithPin (HWND hwndDlg, Password *password, char* pin, KeyFile else if (statStruct.st_mode & S_IFDIR) // If it's a directory { // Prevent recursive folder scanning - continue; + continue; } // Skip hidden files @@ -363,7 +363,7 @@ BOOL KeyFilesApplyWithPin (HWND hwndDlg, Password *password, char* pin, KeyFile && (fileAttributes.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0) { HiddenFilesPresentInKeyfilePath = TRUE; - continue; + continue; } CorrectFileName (kfSub->FileName); @@ -474,18 +474,18 @@ BOOL CALLBACK KeyFilesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa 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"); + 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) @@ -580,15 +580,15 @@ BOOL CALLBACK KeyFilesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa HWND list = GetDlgItem (hwndDlg, IDC_KEYLIST); LVITEM LvItem; memset (&LvItem, 0, sizeof(LvItem)); - LvItem.mask = LVIF_PARAM; + 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; } @@ -602,7 +602,7 @@ BOOL CALLBACK KeyFilesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa if (lw == IDC_GENERATE_KEYFILE) { - DialogBoxParamW (hInst, + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_KEYFILE_GENERATOR), hwndDlg, (DLGPROC) KeyfileGeneratorDlgProc, (LPARAM) 0); return 1; diff --git a/src/Common/Keyfiles.h b/src/Common/Keyfiles.h index dea906b1..c94f1378 100644 --- a/src/Common/Keyfiles.h +++ b/src/Common/Keyfiles.h @@ -3,7 +3,7 @@ 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) + 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 @@ -51,4 +51,4 @@ extern BOOL HiddenFilesPresentInKeyfilePath; } #endif -#endif /* #ifndef KEYFILES_H */ +#endif /* #ifndef KEYFILES_H */ diff --git a/src/Common/Language.c b/src/Common/Language.c index 3d9b22d3..f03a4e54 100644 --- a/src/Common/Language.c +++ b/src/Common/Language.c @@ -3,7 +3,7 @@ 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) + 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 @@ -101,7 +101,7 @@ static char *MapNextLanguageFile () GetModuleFileNameW (NULL, f, sizeof (f) / sizeof (f[0])); t = wcsrchr (f, L'\\'); if (t == NULL) return NULL; - + *t = 0; StringCbCatW (f, sizeof(f), L"\\Language*.xml"); @@ -236,10 +236,10 @@ BOOL LoadLanguageFile () memset (&font, 0, sizeof (font)); XmlGetAttributeText (xml, "face", attr, sizeof (attr)); - + len = MultiByteToWideChar (CP_UTF8, 0, attr, -1, wattr, sizeof (wattr) / sizeof(wattr[0])); font.FaceName = AddPoolData ((void *) wattr, len * 2); - + XmlGetAttributeText (xml, "size", attr, sizeof (attr)); sscanf (attr, "%d", &font.Size); @@ -332,7 +332,7 @@ BOOL LoadLanguageFile () LocalizationSerialNo++; // Create control ID dictionary - + // Default controls AddDictionaryEntry (NULL, 1, GetString ("IDOK")); AddDictionaryEntry (NULL, 2, GetString ("IDCANCEL")); @@ -440,7 +440,7 @@ BOOL CALLBACK LanguageDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_SETCURSEL, i, 0); - // Language pack version + // Language pack version if (!ActiveLangPackVersion[0] || memcmp (ActiveLangPackVersion, "0.0.0", 5) == 0) { StringCbPrintfW (szVers, sizeof(szVers), GetString("LANG_PACK_VERSION"), L"--"); @@ -474,12 +474,12 @@ BOOL CALLBACK LanguageDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa if (lParam == 1) { // Auto mode - if (langCount < 2) + if (langCount < 2) EndDialog (hwndDlg, IDCANCEL); if (langCount == 2) StringCbCopyA (PreferredLangId, sizeof(PreferredLangId), lastLangId); - + EndDialog (hwndDlg, IDOK); } @@ -511,8 +511,8 @@ BOOL CALLBACK LanguageDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa l[3] = (char) (id >> 16); l[4] = id >> 24; l[5] = 0; - } - + } + if (SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_GETCOUNT, 0, 0) > 1) StringCbCopyA (PreferredLangId, sizeof(PreferredLangId), l); } diff --git a/src/Common/Language.h b/src/Common/Language.h index 4e4c1795..3b5501d9 100644 --- a/src/Common/Language.h +++ b/src/Common/Language.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Common/Password.c b/src/Common/Password.c index 4d7c7952..2c9e77c3 100644 --- a/src/Common/Password.c +++ b/src/Common/Password.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -89,7 +89,7 @@ void VerifyPasswordAndUpdate (HWND hwndDlg, HWND hButton, HWND hPassword, BOOL CheckPasswordCharEncoding (HWND hPassword, Password *ptrPw) { int i, len; - + if (hPassword == NULL) { if (ptrPw) @@ -113,7 +113,7 @@ BOOL CheckPasswordCharEncoding (HWND hPassword, Password *ptrPw) len = GetWindowTextLength (hPassword); if (len > MAX_PASSWORD) - return FALSE; + return FALSE; GetWindowTextW (hPassword, s, sizeof (s) / sizeof (wchar_t)); @@ -126,7 +126,7 @@ BOOL CheckPasswordCharEncoding (HWND hPassword, Password *ptrPw) burn (s, sizeof(s)); if (i < len) - return FALSE; + return FALSE; } return TRUE; @@ -141,7 +141,7 @@ BOOL CheckPasswordLength (HWND hwndDlg, unsigned __int32 passwordLength, int pim if (bCustomPimSmall) { Error (bForBoot? "BOOT_PIM_REQUIRE_LONG_PASSWORD": "PIM_REQUIRE_LONG_PASSWORD", hwndDlg); - return FALSE; + return FALSE; } #ifndef _DEBUG @@ -215,14 +215,14 @@ int ChangePwd (const wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, else { nDosLinkCreated = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice), szCFDevice, sizeof(szCFDevice),FALSE); - + if (nDosLinkCreated != 0) goto error; } dev = CreateFile (szCFDevice, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - if (dev == INVALID_HANDLE_VALUE) + if (dev == INVALID_HANDLE_VALUE) goto error; if (bDevice) @@ -328,7 +328,7 @@ int ChangePwd (const wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, if (bytesRead != sizeof (buffer)) { - // Windows may report EOF when reading sectors from the last cluster of a device formatted as NTFS + // Windows may report EOF when reading sectors from the last cluster of a device formatted as NTFS memset (buffer, 0, sizeof (buffer)); } @@ -347,7 +347,7 @@ int ChangePwd (const wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, cryptoInfo = NULL; goto error; } - else + else break; } @@ -374,12 +374,12 @@ int ChangePwd (const wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, EnableElevatedCursorChange (hwndDlg); WaitCursor(); - /* Re-encrypt the volume header */ + /* Re-encrypt the volume header */ backupHeader = FALSE; while (TRUE) { - /* The header will be re-encrypted wipePassCount times to prevent adversaries from using + /* The header will be re-encrypted wipePassCount times to prevent adversaries from using techniques such as magnetic force microscopy or magnetic force scanning tunnelling microscopy to recover the overwritten header. According to Peter Gutmann, data should be overwritten 22 times (ideally, 35 times) using non-random patterns and pseudorandom data. However, as users might @@ -447,7 +447,7 @@ int ChangePwd (const wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, if (backupHeader || cryptoInfo->LegacyVolume) break; - + backupHeader = TRUE; headerOffset.QuadPart += hostSize - TC_VOLUME_HEADER_GROUP_SIZE; } diff --git a/src/Common/Password.h b/src/Common/Password.h index 8cc0b7ea..8818804e 100644 --- a/src/Common/Password.h +++ b/src/Common/Password.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -39,8 +39,8 @@ typedef struct #if defined(_WIN32) && !defined(TC_WINDOWS_DRIVER) void VerifyPasswordAndUpdate ( HWND hwndDlg , HWND hButton , HWND hPassword , HWND hVerify , unsigned char *szPassword , char *szVerify, BOOL keyFilesEnabled ); -BOOL CheckPasswordLength (HWND hwndDlg, unsigned __int32 passwordLength, int pim, BOOL bForBoot, BOOL bSkipPasswordWarning, BOOL bSkipPimWarning); -BOOL CheckPasswordCharEncoding (HWND hPassword, Password *ptrPw); +BOOL CheckPasswordLength (HWND hwndDlg, unsigned __int32 passwordLength, int pim, BOOL bForBoot, BOOL bSkipPasswordWarning, BOOL bSkipPimWarning); +BOOL CheckPasswordCharEncoding (HWND hPassword, Password *ptrPw); int ChangePwd (const wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg); #endif // defined(_WIN32) && !defined(TC_WINDOWS_DRIVER) diff --git a/src/Common/Pkcs5.c b/src/Common/Pkcs5.c index a71be573..8bc828ef 100644 --- a/src/Common/Pkcs5.c +++ b/src/Common/Pkcs5.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -150,7 +150,7 @@ static void derive_u_sha256 (char *pwd, int pwd_len, char *salt, int salt_len, u char* k = hmac->k; char* u = hmac->u; uint32 c; - int i; + int i; #ifdef TC_WINDOWS_BOOT /* In bootloader mode, least significant bit of iterations is a boolean (TRUE for boot derivation mode, FALSE otherwise) @@ -169,7 +169,7 @@ static void derive_u_sha256 (char *pwd, int pwd_len, char *salt, int salt_len, u /* iteration 1 */ memcpy (k, salt, salt_len); /* salt */ - + /* big-endian block number */ memset (&k[salt_len], 0, 3); k[salt_len + 3] = (char) b; @@ -191,7 +191,7 @@ static void derive_u_sha256 (char *pwd, int pwd_len, char *salt, int salt_len, u void derive_key_sha256 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) -{ +{ hmac_sha256_ctx hmac; sha256_ctx* ctx; char* buf = hmac.k; @@ -315,7 +315,7 @@ void hmac_sha512 char *k, /* secret key */ int lk, /* length of the key in bytes */ char *d, /* data and also output buffer of at least 64 bytes */ - int ld /* length of data in bytes */ + int ld /* length of data in bytes */ ) { hmac_sha512_ctx hmac; @@ -521,7 +521,7 @@ void hmac_ripemd160 (char *key, int keylen, char *input_digest, int len) /* If the key is longer than the hash algorithm block size, let key = ripemd160(key), as per HMAC specifications. */ - if (keylen > RIPEMD160_BLOCKSIZE) + if (keylen > RIPEMD160_BLOCKSIZE) { RMD160_CTX tctx; @@ -533,14 +533,14 @@ void hmac_ripemd160 (char *key, int keylen, char *input_digest, int len) keylen = RIPEMD160_DIGESTSIZE; burn (&tctx, sizeof(tctx)); // Prevent leaks - } + } /* perform inner RIPEMD-160 */ ctx = &(hmac.inner_digest_ctx); /* start out by storing key in pads */ memset(k_pad, 0x36, 64); /* XOR key with ipad and opad values */ - for (i=0; i RIPEMD160_BLOCKSIZE) + if (pwd_len > RIPEMD160_BLOCKSIZE) { RMD160_CTX tctx; @@ -652,7 +652,7 @@ void derive_key_ripemd160 (char *pwd, int pwd_len, char *salt, int salt_len, uin /* start out by storing key in pads */ memset(k_pad, 0x36, 64); /* XOR key with ipad and opad values */ - for (b=0; b> 8)); + RandaddByte(x); + RandaddByte((x >> 8)); RandaddByte((x >> 16)); RandaddByte((x >> 24)); } void RandAddInt64 (unsigned __int64 x) { - RandaddByte(x); - RandaddByte((x >> 8)); + RandaddByte(x); + RandaddByte((x >> 8)); RandaddByte((x >> 16)); RandaddByte((x >> 24)); @@ -97,7 +97,7 @@ int Randinit () if (GetMaxPkcs5OutSize() > RNG_POOL_SIZE) TC_THROW_FATAL_EXCEPTION; - if(bRandDidInit) + if(bRandDidInit) return 0; InitializeCriticalSection (&critRandProt); @@ -128,9 +128,9 @@ int Randinit () handleWin32Error (0, SRC_POS); goto error; } - + if (!CryptAcquireContext (&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) - { + { CryptoAPIAvailable = FALSE; CryptoAPILastError = GetLastError (); goto error; @@ -274,7 +274,7 @@ BOOL Randmix () if (RNG_POOL_SIZE % digestSize) TC_THROW_FATAL_EXCEPTION; - for (poolIndex = 0; poolIndex < RNG_POOL_SIZE; poolIndex += digestSize) + for (poolIndex = 0; poolIndex < RNG_POOL_SIZE; poolIndex += digestSize) { /* Compute the message digest of the entire pool using the selected hash function. */ switch (HashFunction) @@ -303,7 +303,7 @@ BOOL Randmix () WHIRLPOOL_finalize (&wctx, hashOutputBuffer); break; - default: + default: // Unknown/wrong ID TC_THROW_FATAL_EXCEPTION; } @@ -316,26 +316,26 @@ BOOL Randmix () } /* Prevent leaks */ - burn (hashOutputBuffer, MAX_DIGESTSIZE); + burn (hashOutputBuffer, MAX_DIGESTSIZE); switch (HashFunction) { case RIPEMD160: - burn (&rctx, sizeof(rctx)); + burn (&rctx, sizeof(rctx)); break; case SHA512: - burn (&sctx, sizeof(sctx)); + burn (&sctx, sizeof(sctx)); break; case SHA256: - burn (&s256ctx, sizeof(s256ctx)); + burn (&s256ctx, sizeof(s256ctx)); break; case WHIRLPOOL: - burn (&wctx, sizeof(wctx)); + burn (&wctx, sizeof(wctx)); break; - default: + default: // Unknown/wrong ID TC_THROW_FATAL_EXCEPTION; } @@ -360,7 +360,7 @@ BOOL RandpeekBytes (void* hwndDlg, unsigned char *buf, int len, DWORD* mouseCoun if (len > RNG_POOL_SIZE) { - Error ("ERR_NOT_ENOUGH_RANDOM_DATA", (HWND) hwndDlg); + Error ("ERR_NOT_ENOUGH_RANDOM_DATA", (HWND) hwndDlg); len = RNG_POOL_SIZE; } @@ -413,7 +413,7 @@ BOOL RandgetBytesFull ( void* hwndDlg, unsigned char *buf , int len, BOOL forceS /* There's never more than RNG_POOL_SIZE worth of randomess */ if ( (!allowAnyLength) && (len > RNG_POOL_SIZE)) { - Error ("ERR_NOT_ENOUGH_RANDOM_DATA", (HWND) hwndDlg); + Error ("ERR_NOT_ENOUGH_RANDOM_DATA", (HWND) hwndDlg); len = RNG_POOL_SIZE; LeaveCriticalSection (&critRandProt); return FALSE; @@ -515,7 +515,7 @@ LRESULT CALLBACK MouseProc (int nCode, WPARAM wParam, LPARAM lParam) EnterCriticalSection (&critRandProt); /* only count real mouse messages in entropy estimation */ - if ( (nCode == HC_ACTION) && (wParam == WM_MOUSEMOVE) + if ( (nCode == HC_ACTION) && (wParam == WM_MOUSEMOVE) && ((pt.x != lastPoint.x) || (pt.y != lastPoint.y))) { ProcessedMouseEventsCounter++; @@ -748,7 +748,7 @@ BOOL SlowPoll (void) // we keep the check for clarity purpose if ( !CryptoAPIAvailable ) return FALSE; - if (CryptGenRandom (hCryptProv, sizeof (buffer), buffer)) + if (CryptGenRandom (hCryptProv, sizeof (buffer), buffer)) { RandaddBuf (buffer, sizeof (buffer)); @@ -759,7 +759,7 @@ BOOL SlowPoll (void) else { /* return error in case CryptGenRandom fails */ - CryptoAPILastError = GetLastError (); + CryptoAPILastError = GetLastError (); return FALSE; } } @@ -870,7 +870,7 @@ BOOL FastPoll (void) // we keep the check for clarity purpose if ( !CryptoAPIAvailable ) return FALSE; - if (CryptGenRandom (hCryptProv, sizeof (buffer), buffer)) + if (CryptGenRandom (hCryptProv, sizeof (buffer), buffer)) { RandaddBuf (buffer, sizeof (buffer)); burn (buffer, sizeof(buffer)); diff --git a/src/Common/Random.h b/src/Common/Random.h index ecf04ca3..f41428f4 100644 --- a/src/Common/Random.h +++ b/src/Common/Random.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Common/Registry.c b/src/Common/Registry.c index 1e5883a2..3daf3a45 100644 --- a/src/Common/Registry.c +++ b/src/Common/Registry.c @@ -3,7 +3,7 @@ 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) + 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 @@ -287,14 +287,14 @@ void DeleteRegistryValue (wchar_t *subKey, wchar_t *name) void GetStartupRegKeyName (wchar_t *regk, size_t cbRegk) { - // The string is split in order to prevent some antivirus packages from falsely reporting + // The string is split in order to prevent some antivirus packages from falsely reporting // VeraCrypt.exe to contain a possible Trojan horse because of this string (heuristic scan). StringCbPrintfW (regk, cbRegk,L"%s%s", L"Software\\Microsoft\\Windows\\Curren", L"tVersion\\Run"); } void GetRestorePointRegKeyName (wchar_t *regk, size_t cbRegk) { - // The string is split in order to prevent some antivirus packages from falsely reporting + // The string is split in order to prevent some antivirus packages from falsely reporting // VeraCrypt.exe to contain a possible Trojan horse because of this string (heuristic scan). StringCbPrintfW (regk, cbRegk,L"%s%s%s%s", L"Software\\Microsoft\\Windows", L" NT\\Curren", L"tVersion\\Sy", L"stemRestore"); } \ No newline at end of file diff --git a/src/Common/Registry.h b/src/Common/Registry.h index be80fa4d..37bb1bdf 100644 --- a/src/Common/Registry.h +++ b/src/Common/Registry.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Common/Resource.h b/src/Common/Resource.h index 3eca197e..03d42664 100644 --- a/src/Common/Resource.h +++ b/src/Common/Resource.h @@ -199,7 +199,7 @@ #define IDT_ENTROPY_BAR 5137 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 diff --git a/src/Common/SecurityToken.cpp b/src/Common/SecurityToken.cpp index 8909059d..78a3e6c1 100644 --- a/src/Common/SecurityToken.cpp +++ b/src/Common/SecurityToken.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -174,7 +174,7 @@ namespace VeraCrypt void SecurityToken::DeleteKeyfile (const SecurityTokenKeyfile &keyfile) { LoginUserIfRequired (keyfile.SlotId); - + CK_RV status = Pkcs11Functions->C_DestroyObject (Sessions[keyfile.SlotId].Handle, keyfile.Handle); if (status != CKR_OK) throw Pkcs11Exception (status); @@ -339,7 +339,7 @@ namespace VeraCrypt finally_do_arg (CK_SLOT_ID, slotId, { Pkcs11Functions->C_FindObjectsFinal (Sessions[finally_arg].Handle); }); - CK_ULONG objectCount; + CK_ULONG objectCount; vector objects; while (true) @@ -451,7 +451,7 @@ namespace VeraCrypt { CK_SESSION_INFO sessionInfo; status = Pkcs11Functions->C_GetSessionInfo (Sessions[slotId].Handle, &sessionInfo); - + if (status == CKR_OK) { Sessions[slotId].UserLoggedIn = (sessionInfo.state == CKS_RO_USER_FUNCTIONS || sessionInfo.state == CKS_RW_USER_FUNCTIONS); @@ -542,7 +542,7 @@ namespace VeraCrypt Pkcs11LibraryHandle = dlopen (pkcs11LibraryPath.c_str(), RTLD_NOW | RTLD_LOCAL); throw_sys_sub_if (!Pkcs11LibraryHandle, dlerror()); #endif - + typedef CK_RV (*C_GetFunctionList_t) (CK_FUNCTION_LIST_PTR_PTR ppFunctionList); #ifdef TC_WINDOWS diff --git a/src/Common/SecurityToken.h b/src/Common/SecurityToken.h index 00d543a2..95d95fc8 100644 --- a/src/Common/SecurityToken.h +++ b/src/Common/SecurityToken.h @@ -3,7 +3,7 @@ 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) + 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 @@ -139,7 +139,7 @@ namespace VeraCrypt { void Show (HWND parent) const { Error (SecurityTokenLibraryPath[0] == 0 ? "NO_PKCS11_MODULE_SPECIFIED" : "PKCS11_MODULE_INIT_FAILED", parent); } }; - + struct InvalidSecurityTokenKeyfilePath : public Exception { void Show (HWND parent) const { Error ("INVALID_TOKEN_KEYFILE_PATH", parent); } @@ -197,7 +197,7 @@ namespace VeraCrypt #endif static bool IsInitialized () { return Initialized; } static bool IsKeyfilePathValid (const wstring &securityTokenKeyfilePath); - + static const size_t MaxPasswordLength = 128; protected: diff --git a/src/Common/Tcdefs.h b/src/Common/Tcdefs.h index 85cb01d0..2d8a6fe3 100644 --- a/src/Common/Tcdefs.h +++ b/src/Common/Tcdefs.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -16,7 +16,7 @@ #define TC_APP_NAME "VeraCrypt" -// Version displayed to user +// Version displayed to user #define VERSION_STRING "1.17" // Version number to compare against driver @@ -106,9 +106,9 @@ typedef unsigned __int32 uint_32t; typedef uint64 uint_64t; #endif -typedef union +typedef union { - struct + struct { unsigned __int32 LowPart; unsigned __int32 HighPart; @@ -276,9 +276,9 @@ void EraseMemory (void *memory, int size); enum { - /* WARNING: ADD ANY NEW CODES AT THE END (DO NOT INSERT THEM BETWEEN EXISTING). DO *NOT* DELETE ANY + /* WARNING: ADD ANY NEW CODES AT THE END (DO NOT INSERT THEM BETWEEN EXISTING). DO *NOT* DELETE ANY EXISTING CODES! Changing these values or their meanings may cause incompatibility with other versions - (for example, if a new version of the TrueCrypt installer receives an error code from an installed + (for example, if a new version of the TrueCrypt installer receives an error code from an installed driver whose version is lower, it will report and interpret the error incorrectly). */ ERR_SUCCESS = 0, diff --git a/src/Common/Tests.c b/src/Common/Tests.c index 8dc72d2c..9d9e8118 100644 --- a/src/Common/Tests.c +++ b/src/Common/Tests.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -40,7 +40,7 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff }, 0, - { + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, @@ -56,9 +56,9 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, - { + { 0x1c, 0x3b, 0x3a, 0x10, 0x2f, 0x77, 0x03, 0x86, 0xe4, 0x83, 0x6c, 0x99, 0xe3, 0x70, 0xcf, 0x9b, 0xea, 0x00, 0x80, 0x3f, 0x5e, 0x48, 0x23, 0x57, 0xa4, 0xae, 0x12, 0xd4, 0x14, 0xa3, 0xe6, 0x3b, 0x5d, 0x31, 0xe2, 0x76, 0xf8, 0xfe, 0x4a, 0x8d, 0x66, 0xb3, 0x17, 0xf9, 0xac, 0x68, 0x3f, 0x44, 0x68, 0x0a, 0x86, 0xac, 0x35, 0xad, 0xfc, 0x33, 0x45, 0xbe, 0xfe, 0xcb, 0x4b, 0xb1, 0x88, 0xfd, 0x57, 0x76, 0x92, 0x6c, 0x49, 0xa3, 0x09, 0x5e, 0xb1, 0x08, 0xfd, 0x10, 0x98, 0xba, 0xec, 0x70, 0xaa, 0xa6, 0x69, 0x99, 0xa7, 0x2a, 0x82, 0xf2, 0x7d, 0x84, 0x8b, 0x21, 0xd4, 0xa7, 0x41, 0xb0, @@ -74,7 +74,7 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { 0x6e, 0x33, 0x3b, 0x93, 0xeb, 0x4a, 0xff, 0x04, 0x79, 0xda, 0x9a, 0x41, 0x0e, 0x44, 0x50, 0xe0, 0xdd, 0x7a, 0xe4, 0xc6, 0xe2, 0x91, 0x09, 0x00, 0x57, 0x5d, 0xa4, 0x01, 0xfc, 0x07, 0x05, 0x9f, 0x64, 0x5e, 0x8b, 0x7e, 0x9b, 0xfd, 0xef, 0x33, 0x94, 0x30, 0x54, 0xff, 0x84, 0x01, 0x14, 0x93, 0xc2, 0x7b, 0x34, 0x29, 0xea, 0xed, 0xb4, 0xed, 0x53, 0x76, 0x44, 0x1a, 0x77, 0xed, 0x43, 0x85, 0x1a, 0xd7, 0x7f, 0x16, 0xf5, 0x41, 0xdf, 0xd2, 0x69, 0xd5, 0x0d, 0x6a, 0x5f, 0x14, 0xfb, 0x0a, 0xab, 0x1c, 0xbb, 0x4c, 0x15, 0x50, 0xbe, 0x97, 0xf7, 0xab, 0x40, 0x66, 0x19, 0x3c, 0x4c, 0xaa, - 0x77, 0x3d, 0xad, 0x38, 0x01, 0x4b, 0xd2, 0x09, 0x2f, 0xa7, 0x55, 0xc8, 0x24, 0xbb, 0x5e, 0x54, 0xc4, 0xf3, 0x6f, 0xfd, 0xa9, 0xfc, 0xea, 0x70, 0xb9, 0xc6, 0xe6, 0x93, 0xe1, 0x48, 0xc1, 0x51 + 0x77, 0x3d, 0xad, 0x38, 0x01, 0x4b, 0xd2, 0x09, 0x2f, 0xa7, 0x55, 0xc8, 0x24, 0xbb, 0x5e, 0x54, 0xc4, 0xf3, 0x6f, 0xfd, 0xa9, 0xfc, 0xea, 0x70, 0xb9, 0xc6, 0xe6, 0x93, 0xe1, 0x48, 0xc1, 0x51 } }, { @@ -83,8 +83,8 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff }, - 0, - { + 0, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, @@ -100,9 +100,9 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, - { + { 0x77, 0xa3, 0x12, 0x51, 0x61, 0x8a, 0x15, 0xe6, 0xb9, 0x2d, 0x1d, 0x66, 0xdf, 0xfe, 0x7b, 0x50, 0xb5, 0x0b, 0xad, 0x55, 0x23, 0x05, 0xba, 0x02, 0x17, 0xa6, 0x10, 0x68, 0x8e, 0xff, 0x7e, 0x11, 0xe1, 0xd0, 0x22, 0x54, 0x38, 0xe0, 0x93, 0x24, 0x2d, 0x6d, 0xb2, 0x74, 0xfd, 0xe8, 0x01, 0xd4, 0xca, 0xe0, 0x6f, 0x20, 0x92, 0xc7, 0x28, 0xb2, 0x47, 0x85, 0x59, 0xdf, 0x58, 0xe8, 0x37, 0xc2, 0x46, 0x9e, 0xe4, 0xa4, 0xfa, 0x79, 0x4e, 0x4b, 0xbc, 0x7f, 0x39, 0xbc, 0x02, 0x6e, 0x3c, 0xb7, 0x2c, 0x33, 0xb0, 0x88, 0x8f, 0x25, 0xb4, 0xac, 0xf5, 0x6a, 0x2a, 0x98, 0x04, 0xf1, 0xce, 0x6d, @@ -118,7 +118,7 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { 0x09, 0x4f, 0x7c, 0x45, 0x3b, 0x7f, 0xf8, 0x7c, 0xb5, 0xbb, 0x36, 0xb7, 0xc7, 0x9e, 0xfb, 0x08, 0x72, 0xd1, 0x70, 0x58, 0xb8, 0x3b, 0x15, 0xab, 0x08, 0x66, 0xad, 0x8a, 0x58, 0x65, 0x6c, 0x5a, 0x7e, 0x20, 0xdb, 0xdf, 0x30, 0x8b, 0x24, 0x61, 0xd9, 0x7c, 0x0e, 0xc0, 0x02, 0x4a, 0x27, 0x15, 0x05, 0x52, 0x49, 0xcf, 0x3b, 0x47, 0x8d, 0xdd, 0x47, 0x40, 0xde, 0x65, 0x4f, 0x75, 0xca, 0x68, 0x6e, 0x0d, 0x73, 0x45, 0xc6, 0x9e, 0xd5, 0x0c, 0xdc, 0x2a, 0x8b, 0x33, 0x2b, 0x1f, 0x88, 0x24, 0x10, 0x8a, 0xc9, 0x37, 0xeb, 0x05, 0x05, 0x85, 0x60, 0x8e, 0xe7, 0x34, 0x09, 0x7f, 0xc0, 0x90, - 0x54, 0xfb, 0xff, 0x89, 0xee, 0xae, 0xea, 0x79, 0x1f, 0x4a, 0x7a, 0xb1, 0xf9, 0x86, 0x82, 0x94, 0xa4, 0xf9, 0xe2, 0x7b, 0x42, 0xaf, 0x81, 0x00, 0xcb, 0x9d, 0x59, 0xce, 0xf9, 0x64, 0x58, 0x03 + 0x54, 0xfb, 0xff, 0x89, 0xee, 0xae, 0xea, 0x79, 0x1f, 0x4a, 0x7a, 0xb1, 0xf9, 0x86, 0x82, 0x94, 0xa4, 0xf9, 0xe2, 0x7b, 0x42, 0xaf, 0x81, 0x00, 0xcb, 0x9d, 0x59, 0xce, 0xf9, 0x64, 0x58, 0x03 } }, { @@ -127,8 +127,8 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff }, - 0, - { + 0, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, @@ -144,9 +144,9 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, - { + { 0xe3, 0x87, 0xaa, 0xa5, 0x8b, 0xa4, 0x83, 0xaf, 0xa7, 0xe8, 0xeb, 0x46, 0x97, 0x78, 0x31, 0x7e, 0xcf, 0x4c, 0xf5, 0x73, 0xaa, 0x9d, 0x4e, 0xac, 0x23, 0xf2, 0xcd, 0xf9, 0x14, 0xe4, 0xe2, 0x00, 0xa8, 0xb4, 0x90, 0xe4, 0x2e, 0xe6, 0x46, 0x80, 0x2d, 0xc6, 0xee, 0x2b, 0x47, 0x1b, 0x27, 0x81, 0x95, 0xd6, 0x09, 0x18, 0xec, 0xec, 0xb4, 0x4b, 0xf7, 0x99, 0x66, 0xf8, 0x3f, 0xab, 0xa0, 0x49, 0x92, 0x98, 0xeb, 0xc6, 0x99, 0xc0, 0xc8, 0x63, 0x47, 0x15, 0xa3, 0x20, 0xbb, 0x4f, 0x07, 0x5d, 0x62, 0x2e, 0x74, 0xc8, 0xc9, 0x32, 0x00, 0x4f, 0x25, 0xb4, 0x1e, 0x36, 0x10, 0x25, 0xb5, 0xa8, @@ -162,7 +162,7 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { 0xf0, 0x8a, 0xd7, 0xba, 0x89, 0x21, 0x28, 0x7e, 0x3b, 0xbe, 0xe3, 0x1b, 0x76, 0x7b, 0xe0, 0x6a, 0x0e, 0x70, 0x5c, 0x86, 0x4a, 0x76, 0x91, 0x37, 0xdf, 0x28, 0x29, 0x22, 0x83, 0xea, 0x81, 0xa2, 0x48, 0x02, 0x41, 0xb4, 0x4d, 0x99, 0x21, 0xcd, 0xbe, 0xc1, 0xbc, 0x28, 0xdc, 0x1f, 0xda, 0x11, 0x4b, 0xd8, 0xe5, 0x21, 0x7a, 0xc9, 0xd8, 0xeb, 0xaf, 0xa7, 0x20, 0xe9, 0xda, 0x4f, 0x9a, 0xce, 0x23, 0x1c, 0xc9, 0x49, 0xe5, 0xb9, 0x6f, 0xe7, 0x6f, 0xfc, 0x21, 0x06, 0x3f, 0xdd, 0xc8, 0x3a, 0x6b, 0x86, 0x79, 0xc0, 0x0d, 0x35, 0xe0, 0x95, 0x76, 0xa8, 0x75, 0x30, 0x5b, 0xed, 0x5f, 0x36, - 0xed, 0x24, 0x2c, 0x89, 0x00, 0xdd, 0x1f, 0xa9, 0x65, 0xbc, 0x95, 0x0d, 0xfc, 0xe0, 0x9b, 0x13, 0x22, 0x63, 0xa1, 0xee, 0xf5, 0x2d, 0xd6, 0x88, 0x8c, 0x30, 0x9f, 0x5a, 0x7d, 0x71, 0x28, 0x26 + 0xed, 0x24, 0x2c, 0x89, 0x00, 0xdd, 0x1f, 0xa9, 0x65, 0xbc, 0x95, 0x0d, 0xfc, 0xe0, 0x9b, 0x13, 0x22, 0x63, 0xa1, 0xee, 0xf5, 0x2d, 0xd6, 0x88, 0x8c, 0x30, 0x9f, 0x5a, 0x7d, 0x71, 0x28, 0x26 } }, { @@ -171,8 +171,8 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, { 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff }, - 0, - { + 0, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, @@ -188,9 +188,9 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, - { + { 0xbf, 0x53, 0xd2, 0xda, 0xde, 0x78, 0xe8, 0x22, 0xa4, 0xd9, 0x49, 0xa9, 0xbc, 0x67, 0x66, 0xb0, 0x1b, 0x06, 0xa8, 0xef, 0x70, 0xd2, 0x67, 0x48, 0xc6, 0xa7, 0xfc, 0x36, 0xd8, 0x0a, 0xe4, 0xc5, 0x52, 0x0f, 0x7c, 0x4a, 0xb0, 0xac, 0x85, 0x44, 0x42, 0x4f, 0xa4, 0x05, 0x16, 0x2f, 0xef, 0x5a, 0x6b, 0x7f, 0x22, 0x94, 0x98, 0x06, 0x36, 0x18, 0xd3, 0x9f, 0x00, 0x03, 0xcb, 0x5f, 0xb8, 0xd1, 0xc8, 0x6b, 0x64, 0x34, 0x97, 0xda, 0x1f, 0xf9, 0x45, 0xc8, 0xd3, 0xbe, 0xde, 0xca, 0x4f, 0x47, 0x97, 0x02, 0xa7, 0xa7, 0x35, 0xf0, 0x43, 0xdd, 0xb1, 0xd6, 0xaa, 0xad, 0xe3, 0xc4, 0xa0, 0xac, @@ -206,7 +206,7 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { 0x77, 0xad, 0x22, 0x00, 0x0f, 0x1d, 0x50, 0x78, 0xf6, 0xb8, 0x66, 0x31, 0x8c, 0x66, 0x8f, 0x1a, 0xd0, 0x3d, 0x5a, 0x5f, 0xce, 0xd5, 0x21, 0x9f, 0x2e, 0xab, 0xbd, 0x0a, 0xa5, 0xc0, 0xf4, 0x60, 0xd1, 0x83, 0xf0, 0x44, 0x04, 0xa0, 0xd6, 0xf4, 0x69, 0x55, 0x8e, 0x81, 0xfa, 0xb2, 0x4a, 0x16, 0x79, 0x05, 0xab, 0x4c, 0x78, 0x78, 0x50, 0x2a, 0xd3, 0xe3, 0x8f, 0xdb, 0xe6, 0x2a, 0x41, 0x55, 0x6c, 0xec, 0x37, 0x32, 0x57, 0x59, 0x53, 0x3c, 0xe8, 0xf2, 0x5f, 0x36, 0x7c, 0x87, 0xbb, 0x55, 0x78, 0xd6, 0x67, 0xae, 0x93, 0xf9, 0xe2, 0xfd, 0x99, 0xbc, 0xbc, 0x5f, 0x2f, 0xbb, 0xa8, 0x8c, - 0xf6, 0x51, 0x61, 0x39, 0x42, 0x0f, 0xcf, 0xf3, 0xb7, 0x36, 0x1d, 0x86, 0x32, 0x2c, 0x4b, 0xd8, 0x4c, 0x82, 0xf3, 0x35, 0xab, 0xb1, 0x52, 0xc4, 0xa9, 0x34, 0x11, 0x37, 0x3a, 0xaa, 0x82, 0x20 + 0xf6, 0x51, 0x61, 0x39, 0x42, 0x0f, 0xcf, 0xf3, 0xb7, 0x36, 0x1d, 0x86, 0x32, 0x2c, 0x4b, 0xd8, 0x4c, 0x82, 0xf3, 0x35, 0xab, 0xb1, 0x52, 0xc4, 0xa9, 0x34, 0x11, 0x37, 0x3a, 0xaa, 0x82, 0x20 } }, { @@ -217,42 +217,42 @@ XTS_TEST XTS_vectors[XTS_TEST_COUNT] = { { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, { 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff }, - 0, - { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + 0, + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, - { - 0x64, 0x49, 0x7e, 0x5a, 0x83, 0x1e, 0x4a, 0x93, 0x2c, 0x09, 0xbe, 0x3e, 0x53, 0x93, 0x37, 0x6d, 0xaa, 0x59, 0x95, 0x48, 0xb8, 0x16, 0x03, 0x1d, 0x22, 0x4b, 0xbf, 0x50, 0xa8, 0x18, 0xed, 0x23, - 0x50, 0xea, 0xe7, 0xe9, 0x60, 0x87, 0xc8, 0xa0, 0xdb, 0x51, 0xad, 0x29, 0x0b, 0xd0, 0x0c, 0x1a, 0xc1, 0x62, 0x08, 0x57, 0x63, 0x5b, 0xf2, 0x46, 0xc1, 0x76, 0xab, 0x46, 0x3b, 0xe3, 0x0b, 0x80, - 0x8d, 0xa5, 0x48, 0x08, 0x1a, 0xc8, 0x47, 0xb1, 0x58, 0xe1, 0x26, 0x4b, 0xe2, 0x5b, 0xb0, 0x91, 0x0b, 0xbc, 0x92, 0x64, 0x71, 0x08, 0x08, 0x94, 0x15, 0xd4, 0x5f, 0xab, 0x1b, 0x3d, 0x26, 0x04, - 0xe8, 0xa8, 0xef, 0xf1, 0xae, 0x40, 0x20, 0xcf, 0xa3, 0x99, 0x36, 0xb6, 0x68, 0x27, 0xb2, 0x3f, 0x37, 0x1b, 0x92, 0x20, 0x0b, 0xe9, 0x02, 0x51, 0xe6, 0xd7, 0x3c, 0x5f, 0x86, 0xde, 0x5f, 0xd4, - 0xa9, 0x50, 0x78, 0x19, 0x33, 0xd7, 0x9a, 0x28, 0x27, 0x2b, 0x78, 0x2a, 0x2e, 0xc3, 0x13, 0xef, 0xdf, 0xcc, 0x06, 0x28, 0xf4, 0x3d, 0x74, 0x4c, 0x2d, 0xc2, 0xff, 0x3d, 0xcb, 0x66, 0x99, 0x9b, - 0x50, 0xc7, 0xca, 0x89, 0x5b, 0x0c, 0x64, 0x79, 0x1e, 0xea, 0xa5, 0xf2, 0x94, 0x99, 0xfb, 0x1c, 0x02, 0x6f, 0x84, 0xce, 0x5b, 0x5c, 0x72, 0xba, 0x10, 0x83, 0xcd, 0xdb, 0x5c, 0xe4, 0x54, 0x34, - 0x63, 0x16, 0x65, 0xc3, 0x33, 0xb6, 0x0b, 0x11, 0x59, 0x3f, 0xb2, 0x53, 0xc5, 0x17, 0x9a, 0x2c, 0x8d, 0xb8, 0x13, 0x78, 0x2a, 0x00, 0x48, 0x56, 0xa1, 0x65, 0x30, 0x11, 0xe9, 0x3f, 0xb6, 0xd8, - 0x76, 0xc1, 0x83, 0x66, 0xdd, 0x86, 0x83, 0xf5, 0x34, 0x12, 0xc0, 0xc1, 0x80, 0xf9, 0xc8, 0x48, 0x59, 0x2d, 0x59, 0x3f, 0x86, 0x09, 0xca, 0x73, 0x63, 0x17, 0xd3, 0x56, 0xe1, 0x3e, 0x2b, 0xff, - 0x3a, 0x9f, 0x59, 0xcd, 0x9a, 0xeb, 0x19, 0xcd, 0x48, 0x25, 0x93, 0xd8, 0xc4, 0x61, 0x28, 0xbb, 0x32, 0x42, 0x3b, 0x37, 0xa9, 0xad, 0xfb, 0x48, 0x2b, 0x99, 0x45, 0x3f, 0xbe, 0x25, 0xa4, 0x1b, - 0xf6, 0xfe, 0xb4, 0xaa, 0x0b, 0xef, 0x5e, 0xd2, 0x4b, 0xf7, 0x3c, 0x76, 0x29, 0x78, 0x02, 0x54, 0x82, 0xc1, 0x31, 0x15, 0xe4, 0x01, 0x5a, 0xac, 0x99, 0x2e, 0x56, 0x13, 0xa3, 0xb5, 0xc2, 0xf6, - 0x85, 0xb8, 0x47, 0x95, 0xcb, 0x6e, 0x9b, 0x26, 0x56, 0xd8, 0xc8, 0x81, 0x57, 0xe5, 0x2c, 0x42, 0xf9, 0x78, 0xd8, 0x63, 0x4c, 0x43, 0xd0, 0x6f, 0xea, 0x92, 0x8f, 0x28, 0x22, 0xe4, 0x65, 0xaa, - 0x65, 0x76, 0xe9, 0xbf, 0x41, 0x93, 0x84, 0x50, 0x6c, 0xc3, 0xce, 0x3c, 0x54, 0xac, 0x1a, 0x6f, 0x67, 0xdc, 0x66, 0xf3, 0xb3, 0x01, 0x91, 0xe6, 0x98, 0x38, 0x0b, 0xc9, 0x99, 0xb0, 0x5a, 0xbc, - 0xe1, 0x9d, 0xc0, 0xc6, 0xdc, 0xc2, 0xdd, 0x00, 0x1e, 0xc5, 0x35, 0xba, 0x18, 0xde, 0xb2, 0xdf, 0x1a, 0x10, 0x10, 0x23, 0x10, 0x83, 0x18, 0xc7, 0x5d, 0xc9, 0x86, 0x11, 0xa0, 0x9d, 0xc4, 0x8a, - 0x0a, 0xcd, 0xec, 0x67, 0x6f, 0xab, 0xdf, 0x22, 0x2f, 0x07, 0xe0, 0x26, 0xf0, 0x59, 0xb6, 0x72, 0xb5, 0x6e, 0x5c, 0xbc, 0x8e, 0x1d, 0x21, 0xbb, 0xd8, 0x67, 0xdd, 0x92, 0x72, 0x12, 0x05, 0x46, - 0x81, 0xd7, 0x0e, 0xa7, 0x37, 0x13, 0x4c, 0xdf, 0xce, 0x93, 0xb6, 0xf8, 0x2a, 0xe2, 0x24, 0x23, 0x27, 0x4e, 0x58, 0xa0, 0x82, 0x1c, 0xc5, 0x50, 0x2e, 0x2d, 0x0a, 0xb4, 0x58, 0x5e, 0x94, 0xde, - 0x69, 0x75, 0xbe, 0x5e, 0x0b, 0x4e, 0xfc, 0xe5, 0x1c, 0xd3, 0xe7, 0x0c, 0x25, 0xa1, 0xfb, 0xbb, 0xd6, 0x09, 0xd2, 0x73, 0xad, 0x5b, 0x0d, 0x59, 0x63, 0x1c, 0x53, 0x1f, 0x6a, 0x0a, 0x57, 0xb9 + { + 0x64, 0x49, 0x7e, 0x5a, 0x83, 0x1e, 0x4a, 0x93, 0x2c, 0x09, 0xbe, 0x3e, 0x53, 0x93, 0x37, 0x6d, 0xaa, 0x59, 0x95, 0x48, 0xb8, 0x16, 0x03, 0x1d, 0x22, 0x4b, 0xbf, 0x50, 0xa8, 0x18, 0xed, 0x23, + 0x50, 0xea, 0xe7, 0xe9, 0x60, 0x87, 0xc8, 0xa0, 0xdb, 0x51, 0xad, 0x29, 0x0b, 0xd0, 0x0c, 0x1a, 0xc1, 0x62, 0x08, 0x57, 0x63, 0x5b, 0xf2, 0x46, 0xc1, 0x76, 0xab, 0x46, 0x3b, 0xe3, 0x0b, 0x80, + 0x8d, 0xa5, 0x48, 0x08, 0x1a, 0xc8, 0x47, 0xb1, 0x58, 0xe1, 0x26, 0x4b, 0xe2, 0x5b, 0xb0, 0x91, 0x0b, 0xbc, 0x92, 0x64, 0x71, 0x08, 0x08, 0x94, 0x15, 0xd4, 0x5f, 0xab, 0x1b, 0x3d, 0x26, 0x04, + 0xe8, 0xa8, 0xef, 0xf1, 0xae, 0x40, 0x20, 0xcf, 0xa3, 0x99, 0x36, 0xb6, 0x68, 0x27, 0xb2, 0x3f, 0x37, 0x1b, 0x92, 0x20, 0x0b, 0xe9, 0x02, 0x51, 0xe6, 0xd7, 0x3c, 0x5f, 0x86, 0xde, 0x5f, 0xd4, + 0xa9, 0x50, 0x78, 0x19, 0x33, 0xd7, 0x9a, 0x28, 0x27, 0x2b, 0x78, 0x2a, 0x2e, 0xc3, 0x13, 0xef, 0xdf, 0xcc, 0x06, 0x28, 0xf4, 0x3d, 0x74, 0x4c, 0x2d, 0xc2, 0xff, 0x3d, 0xcb, 0x66, 0x99, 0x9b, + 0x50, 0xc7, 0xca, 0x89, 0x5b, 0x0c, 0x64, 0x79, 0x1e, 0xea, 0xa5, 0xf2, 0x94, 0x99, 0xfb, 0x1c, 0x02, 0x6f, 0x84, 0xce, 0x5b, 0x5c, 0x72, 0xba, 0x10, 0x83, 0xcd, 0xdb, 0x5c, 0xe4, 0x54, 0x34, + 0x63, 0x16, 0x65, 0xc3, 0x33, 0xb6, 0x0b, 0x11, 0x59, 0x3f, 0xb2, 0x53, 0xc5, 0x17, 0x9a, 0x2c, 0x8d, 0xb8, 0x13, 0x78, 0x2a, 0x00, 0x48, 0x56, 0xa1, 0x65, 0x30, 0x11, 0xe9, 0x3f, 0xb6, 0xd8, + 0x76, 0xc1, 0x83, 0x66, 0xdd, 0x86, 0x83, 0xf5, 0x34, 0x12, 0xc0, 0xc1, 0x80, 0xf9, 0xc8, 0x48, 0x59, 0x2d, 0x59, 0x3f, 0x86, 0x09, 0xca, 0x73, 0x63, 0x17, 0xd3, 0x56, 0xe1, 0x3e, 0x2b, 0xff, + 0x3a, 0x9f, 0x59, 0xcd, 0x9a, 0xeb, 0x19, 0xcd, 0x48, 0x25, 0x93, 0xd8, 0xc4, 0x61, 0x28, 0xbb, 0x32, 0x42, 0x3b, 0x37, 0xa9, 0xad, 0xfb, 0x48, 0x2b, 0x99, 0x45, 0x3f, 0xbe, 0x25, 0xa4, 0x1b, + 0xf6, 0xfe, 0xb4, 0xaa, 0x0b, 0xef, 0x5e, 0xd2, 0x4b, 0xf7, 0x3c, 0x76, 0x29, 0x78, 0x02, 0x54, 0x82, 0xc1, 0x31, 0x15, 0xe4, 0x01, 0x5a, 0xac, 0x99, 0x2e, 0x56, 0x13, 0xa3, 0xb5, 0xc2, 0xf6, + 0x85, 0xb8, 0x47, 0x95, 0xcb, 0x6e, 0x9b, 0x26, 0x56, 0xd8, 0xc8, 0x81, 0x57, 0xe5, 0x2c, 0x42, 0xf9, 0x78, 0xd8, 0x63, 0x4c, 0x43, 0xd0, 0x6f, 0xea, 0x92, 0x8f, 0x28, 0x22, 0xe4, 0x65, 0xaa, + 0x65, 0x76, 0xe9, 0xbf, 0x41, 0x93, 0x84, 0x50, 0x6c, 0xc3, 0xce, 0x3c, 0x54, 0xac, 0x1a, 0x6f, 0x67, 0xdc, 0x66, 0xf3, 0xb3, 0x01, 0x91, 0xe6, 0x98, 0x38, 0x0b, 0xc9, 0x99, 0xb0, 0x5a, 0xbc, + 0xe1, 0x9d, 0xc0, 0xc6, 0xdc, 0xc2, 0xdd, 0x00, 0x1e, 0xc5, 0x35, 0xba, 0x18, 0xde, 0xb2, 0xdf, 0x1a, 0x10, 0x10, 0x23, 0x10, 0x83, 0x18, 0xc7, 0x5d, 0xc9, 0x86, 0x11, 0xa0, 0x9d, 0xc4, 0x8a, + 0x0a, 0xcd, 0xec, 0x67, 0x6f, 0xab, 0xdf, 0x22, 0x2f, 0x07, 0xe0, 0x26, 0xf0, 0x59, 0xb6, 0x72, 0xb5, 0x6e, 0x5c, 0xbc, 0x8e, 0x1d, 0x21, 0xbb, 0xd8, 0x67, 0xdd, 0x92, 0x72, 0x12, 0x05, 0x46, + 0x81, 0xd7, 0x0e, 0xa7, 0x37, 0x13, 0x4c, 0xdf, 0xce, 0x93, 0xb6, 0xf8, 0x2a, 0xe2, 0x24, 0x23, 0x27, 0x4e, 0x58, 0xa0, 0x82, 0x1c, 0xc5, 0x50, 0x2e, 0x2d, 0x0a, 0xb4, 0x58, 0x5e, 0x94, 0xde, + 0x69, 0x75, 0xbe, 0x5e, 0x0b, 0x4e, 0xfc, 0xe5, 0x1c, 0xd3, 0xe7, 0x0c, 0x25, 0xa1, 0xfb, 0xbb, 0xd6, 0x09, 0xd2, 0x73, 0xad, 0x5b, 0x0d, 0x59, 0x63, 0x1c, 0x53, 0x1f, 0x6a, 0x0a, 0x57, 0xb9 } } }; // XTS_TEST XTS_vectors[] @@ -446,9 +446,9 @@ char *hmac_whirlpool_test_vectors = "\x6a\xbf\xa4\x02" }; -unsigned char ks_tmp[MAX_EXPANDED_KEY]; +unsigned char ks_tmp[MAX_EXPANDED_KEY]; -void CipherInit2(int cipher, void* key, void* ks, int key_len) +void CipherInit2(int cipher, void* key, void* ks, int key_len) { switch (cipher) { @@ -465,7 +465,7 @@ void CipherInit2(int cipher, void* key, void* ks, int key_len) CipherInit(cipher,key,ks); break; - default: + default: /* Unknown/wrong ID */ TC_THROW_FATAL_EXCEPTION; } @@ -485,7 +485,7 @@ BOOL TestSectorBufEncryption (PCRYPTO_INFO ci) int nTestsPerformed = 0; static unsigned char key1[] = - { + { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27, 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13 @@ -501,8 +501,8 @@ BOOL TestSectorBufEncryption (PCRYPTO_INFO ci) /* The buffer can accommodate 4 data units and we'll test 4 cases by "scrolling". The data unit 0xFFFFFFFFFF will "move" from the start of the buffer to its end. For a 512-byte data unit, the byte offset 562949953420800 corresponds to the data unit 0xFFFFFFFFFF. */ - for (writeOffset = 562949953420800ULL; - writeOffset > 562949953420800ULL - nbrUnits * ENCRYPTION_DATA_UNIT_SIZE; + for (writeOffset = 562949953420800ULL; + writeOffset > 562949953420800ULL - nbrUnits * ENCRYPTION_DATA_UNIT_SIZE; writeOffset -= ENCRYPTION_DATA_UNIT_SIZE) { unitNo.Value = writeOffset / ENCRYPTION_DATA_UNIT_SIZE; @@ -529,8 +529,8 @@ BOOL TestSectorBufEncryption (PCRYPTO_INFO ci) // Each data unit will contain the same plaintext for (i = 0; i < nbrUnits; i++) { - memcpy ((unsigned char *) buf + i * ENCRYPTION_DATA_UNIT_SIZE, - XTS_vectors[XTS_TEST_COUNT-1].plaintext, + memcpy ((unsigned char *) buf + i * ENCRYPTION_DATA_UNIT_SIZE, + XTS_vectors[XTS_TEST_COUNT-1].plaintext, ENCRYPTION_DATA_UNIT_SIZE); } @@ -551,7 +551,7 @@ BOOL TestSectorBufEncryption (PCRYPTO_INFO ci) // CRC of all data units in the buffer for each test case switch (testCase) { - case 0: + case 0: if (crc != 0x888f2990) return FALSE; nTestsPerformed++; @@ -792,8 +792,8 @@ BOOL TestSectorBufEncryption (PCRYPTO_INFO ci) // Each data unit will contain the same plaintext for (i = 0; i < nbrUnits; i++) { - memcpy ((unsigned char *) buf + i * ENCRYPTION_DATA_UNIT_SIZE, - XTS_vectors[XTS_TEST_COUNT-1].plaintext, + memcpy ((unsigned char *) buf + i * ENCRYPTION_DATA_UNIT_SIZE, + XTS_vectors[XTS_TEST_COUNT-1].plaintext, ENCRYPTION_DATA_UNIT_SIZE); } @@ -881,7 +881,7 @@ static BOOL DoAutoTestAlgorithms (void) /* AES */ for (i = 0; i < AES_TEST_COUNT; i++) - { + { int cipher = AES; memcpy(key, aes_ecb_vectors[i].key, 32); memcpy(tmp, aes_ecb_vectors[i].plaintext, 16); @@ -926,7 +926,7 @@ static BOOL DoAutoTestAlgorithms (void) /* Serpent */ for (i = 0; i < SERPENT_TEST_COUNT; i++) - { + { int cipher = SERPENT; memcpy(key, serpent_vectors[i].key, 32); memcpy(tmp, serpent_vectors[i].plaintext, 16); @@ -947,7 +947,7 @@ static BOOL DoAutoTestAlgorithms (void) /* Twofish */ for (i = 0; i < TWOFISH_TEST_COUNT; i++) - { + { int cipher = TWOFISH; memcpy(key, twofish_vectors[i].key, 32); memcpy(tmp, twofish_vectors[i].plaintext, 16); @@ -964,7 +964,7 @@ static BOOL DoAutoTestAlgorithms (void) if (i != TWOFISH_TEST_COUNT) bFailed = TRUE; - + /* PKCS #5 and HMACs */ if (!test_pkcs5 ()) bFailed = TRUE; @@ -986,7 +986,7 @@ static BOOL DoAutoTestAlgorithms (void) /* Sector and buffer related algorithms */ if (!TestSectorBufEncryption (ci)) bFailed = TRUE; - + crypto_close (ci); return !bFailed; } diff --git a/src/Common/Tests.h b/src/Common/Tests.h index 5e56ff55..f2f99502 100644 --- a/src/Common/Tests.h +++ b/src/Common/Tests.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -15,7 +15,7 @@ extern "C" { #endif -extern unsigned char ks_tmp[MAX_EXPANDED_KEY]; +extern unsigned char ks_tmp[MAX_EXPANDED_KEY]; void CipherInit2(int cipher, void* key, void* ks, int key_len); BOOL test_hmac_sha512 (void); diff --git a/src/Common/Volumes.c b/src/Common/Volumes.c index d2a54b5c..007a1c08 100644 --- a/src/Common/Volumes.c +++ b/src/Common/Volumes.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -243,7 +243,7 @@ int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, int } #endif } - + #ifndef DEVICE_DRIVER VirtualLock (&keyInfo, sizeof (keyInfo)); VirtualLock (&dk, sizeof (dk)); @@ -256,7 +256,7 @@ int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, int // Test all available PKCS5 PRFs for (enqPkcs5Prf = FIRST_PRF_ID; enqPkcs5Prf <= LAST_PRF_ID || queuedWorkItems > 0; ++enqPkcs5Prf) - { + { // if a PRF is specified, we skip all other PRFs if (selected_pkcs5_prf != 0 && enqPkcs5Prf != selected_pkcs5_prf) continue; @@ -282,7 +282,7 @@ int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, int EncryptionThreadPoolBeginKeyDerivation (&keyDerivationCompletedEvent, &noOutstandingWorkItemEvent, &item->KeyReady, &outstandingWorkItemCount, enqPkcs5Prf, keyInfo.userKey, keyInfo.keyLength, keyInfo.salt, get_pkcs5_iteration_count (enqPkcs5Prf, pim, truecryptMode, bBoot), item->DerivedKey); - + ++queuedWorkItems; break; } @@ -345,10 +345,10 @@ KeyReady: ; PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); break; - default: + default: // Unknown/wrong ID TC_THROW_FATAL_EXCEPTION; - } + } } // Test all available modes of operation @@ -401,7 +401,7 @@ KeyReady: ; // Copy the header for decryption memcpy (header, encryptedHeader, sizeof (header)); - // Try to decrypt header + // Try to decrypt header DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo); @@ -413,7 +413,7 @@ KeyReady: ; // Header version headerVersion = GetHeaderField16 (header, TC_HEADER_OFFSET_VERSION); - + if (headerVersion > VOLUME_HEADER_VERSION) { status = ERR_NEW_VERSION_REQUIRED; @@ -471,7 +471,7 @@ KeyReady: ; // Volume size cryptoInfo->VolumeSize = GetHeaderField64 (header, TC_HEADER_OFFSET_VOLUME_SIZE); - + // Encrypted area size and length cryptoInfo->EncryptedAreaStart = GetHeaderField64 (header, TC_HEADER_OFFSET_ENCRYPTED_AREA_START); cryptoInfo->EncryptedAreaLength = GetHeaderField64 (header, TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH); @@ -493,7 +493,7 @@ KeyReady: ; goto err; } - // Preserve scheduled header keys if requested + // Preserve scheduled header keys if requested if (retHeaderCryptoInfo) { if (retInfo == NULL) @@ -557,7 +557,7 @@ err: if (cryptoInfo != retHeaderCryptoInfo) { crypto_close(cryptoInfo); - *retInfo = NULL; + *retInfo = NULL; } ret: @@ -601,7 +601,7 @@ void ComputeBootloaderFingerprint (byte *bootLoaderBuf, unsigned int bootLoaderS WHIRLPOOL_CTX whirlpool; sha512_ctx sha2; - + WHIRLPOOL_init (&whirlpool); sha512_begin (&sha2); @@ -690,9 +690,9 @@ int ReadVolumeHeader (BOOL bBoot, char *header, Password *password, int pim, PCR EAInit (cryptoInfo->ea, dk + EAGetKeySize (cryptoInfo->ea), cryptoInfo->ks2); #endif - // Try to decrypt header + // Try to decrypt header DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, cryptoInfo); - + // Check magic 'VERA' and CRC-32 of header fields and master keydata if (GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x56455241 || (GetHeaderField16 (header, TC_HEADER_OFFSET_VERSION) >= 4 && GetHeaderField32 (header, TC_HEADER_OFFSET_HEADER_CRC) != GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC)) @@ -774,7 +774,7 @@ err: if (cryptoInfo != retHeaderCryptoInfo) { crypto_close(cryptoInfo); - *retInfo = NULL; + *retInfo = NULL; } ret: @@ -844,7 +844,7 @@ int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, char *header, int ea, memcpy (keyInfo.master_keydata, masterKeydata, MASTER_KEYDATA_SIZE); } - // User key + // User key memcpy (keyInfo.userKey, password->Text, nUserKeyLen); keyInfo.keyLength = nUserKeyLen; keyInfo.noIterations = get_pkcs5_iteration_count (pkcs5_prf, pim, FALSE, bBoot); @@ -863,7 +863,7 @@ int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, char *header, int ea, // Salt for header key derivation if (!RandgetBytes (hwndDlg, keyInfo.salt, PKCS5_SALT_SIZE, !bWipeMode)) - return ERR_CIPHER_INIT_WEAK_KEY; + return ERR_CIPHER_INIT_WEAK_KEY; // PBKDF2 (PKCS5) is used to derive primary header key(s) and secondary header key(s) (XTS) from the password/keyfiles switch (pkcs5_prf) @@ -888,15 +888,15 @@ int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, char *header, int ea, PKCS5_SALT_SIZE, keyInfo.noIterations, dk, GetMaxPkcs5OutSize()); break; - default: + default: // Unknown/wrong ID TC_THROW_FATAL_EXCEPTION; - } + } /* Header setup */ // Salt - mputBytes (p, keyInfo.salt, PKCS5_SALT_SIZE); + mputBytes (p, keyInfo.salt, PKCS5_SALT_SIZE); // Magic mputLong (p, 0x56455241); @@ -985,7 +985,7 @@ int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, char *header, int ea, /* cryptoInfo setup for further use (disk format) */ - // Init with the master key(s) + // Init with the master key(s) retVal = EAInit (cryptoInfo->ea, keyInfo.master_keydata + primaryKeyOffset, cryptoInfo->ks); if (retVal != ERR_SUCCESS) return retVal; @@ -1080,7 +1080,7 @@ BOOL ReadEffectiveVolumeHeader (BOOL device, HANDLE fileHandle, byte *header, DW return FALSE; memcpy (header, sectorBuffer, min (*bytesRead, TC_VOLUME_HEADER_EFFECTIVE_SIZE)); - + if (*bytesRead > TC_VOLUME_HEADER_EFFECTIVE_SIZE) *bytesRead = TC_VOLUME_HEADER_EFFECTIVE_SIZE; @@ -1181,7 +1181,7 @@ int WriteRandomDataToReservedHeaderAreas (HWND hwndDlg, HANDLE dev, CRYPTO_INFO if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (cryptoInfo->ea), FALSE) || !RandgetBytes (hwndDlg, cryptoInfo->k2, sizeof (cryptoInfo->k2), FALSE)) { - nStatus = ERR_PARAMETER_INCORRECT; + nStatus = ERR_PARAMETER_INCORRECT; goto final_seq; } diff --git a/src/Common/Volumes.h b/src/Common/Volumes.h index 43aaaf73..fdd1444f 100644 --- a/src/Common/Volumes.h +++ b/src/Common/Volumes.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -19,7 +19,7 @@ extern "C" { #endif // Volume header version -#define VOLUME_HEADER_VERSION 0x0005 +#define VOLUME_HEADER_VERSION 0x0005 // Version number written to volume header during format; // specifies the minimum program version required to mount the volume @@ -101,7 +101,7 @@ extern "C" { #define HEADER_SALT_OFFSET 0 #define HEADER_ENCRYPTED_DATA_OFFSET PKCS5_SALT_SIZE #define HEADER_MASTER_KEYDATA_OFFSET 256 - + #define TC_HEADER_OFFSET_MAGIC 64 #define TC_HEADER_OFFSET_VERSION 68 #define TC_HEADER_OFFSET_REQUIRED_VERSION 70 diff --git a/src/Common/Wipe.c b/src/Common/Wipe.c index 83099547..5b07ced5 100644 --- a/src/Common/Wipe.c +++ b/src/Common/Wipe.c @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Common/Wipe.h b/src/Common/Wipe.h index 97011085..a6ca748f 100644 --- a/src/Common/Wipe.h +++ b/src/Common/Wipe.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Common/Xml.c b/src/Common/Xml.c index 60dd8266..d733dac1 100644 --- a/src/Common/Xml.c +++ b/src/Common/Xml.c @@ -3,7 +3,7 @@ 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) + 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 @@ -172,7 +172,7 @@ char *XmlQuoteText (const char *textSrc, char *textDst, int textDstMaxSize) if (textDstMaxSize == 0) return NULL; - while (*textSrc != 0 && textDst <= textDstLast) + while (*textSrc != 0 && textDst <= textDstLast) { char c = *textSrc++; switch (c) @@ -217,7 +217,7 @@ wchar_t *XmlQuoteTextW (const wchar_t *textSrc, wchar_t *textDst, int textDstMax if (textDstMaxSize == 0) return NULL; - while (*textSrc != 0 && textDst <= textDstLast) + while (*textSrc != 0 && textDst <= textDstLast) { wchar_t c = *textSrc++; switch (c) diff --git a/src/Common/Xml.h b/src/Common/Xml.h index 41daf40f..3dfb58e1 100644 --- a/src/Common/Xml.h +++ b/src/Common/Xml.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Common/Xts.c b/src/Common/Xts.c index 0bdb8271..02977887 100644 --- a/src/Common/Xts.c +++ b/src/Common/Xts.c @@ -3,14 +3,14 @@ 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) + 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. */ -/* If native 64-bit data types are not available, define TC_NO_COMPILER_INT64. +/* If native 64-bit data types are not available, define TC_NO_COMPILER_INT64. For big-endian platforms define BYTE_ORDER as BIG_ENDIAN. */ @@ -37,7 +37,7 @@ For big-endian platforms define BYTE_ORDER as BIG_ENDIAN. */ // ks2: the secondary key schedule // startDataUnitNo: The sequential number of the data unit with which the buffer starts. // startCipherBlockNo: The sequential number of the first plaintext block to encrypt inside the data unit startDataUnitNo. -// When encrypting the data unit from its first block, startCipherBlockNo is 0. +// When encrypting the data unit from its first block, startCipherBlockNo is 0. // The startCipherBlockNo value applies only to the first data unit in the buffer; each successive // data unit is encrypted from its first block. The start of the buffer does not have to be // aligned with the start of a data unit. If it is aligned, startCipherBlockNo must be 0; if it @@ -85,7 +85,7 @@ static void EncryptBufferXTSParallel (unsigned __int8 *buffer, the shift of the highest byte results in a carry, 135 is XORed into the lowest byte. The value 135 is derived from the modulus of the Galois Field (x^128+x^7+x^2+x+1). */ - // Convert the 64-bit data unit number into a little-endian 16-byte array. + // Convert the 64-bit data unit number into a little-endian 16-byte array. // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. dataUnitNo = startDataUnitNo->Value; *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); @@ -107,7 +107,7 @@ static void EncryptBufferXTSParallel (unsigned __int8 *buffer, whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; - // Encrypt the data unit number using the secondary key (in order to generate the first + // Encrypt the data unit number using the secondary key (in order to generate the first // whitening value for this data unit) *whiteningValuePtr64 = *((unsigned __int64 *) byteBufUnitNo); *(whiteningValuePtr64 + 1) = 0; @@ -131,21 +131,21 @@ static void EncryptBufferXTSParallel (unsigned __int8 *buffer, // Little-endian platforms - finalCarry = + finalCarry = (*whiteningValuePtr64 & 0x8000000000000000) ? 135 : 0; *whiteningValuePtr64-- <<= 1; if (*whiteningValuePtr64 & 0x8000000000000000) - *(whiteningValuePtr64 + 1) |= 1; + *(whiteningValuePtr64 + 1) |= 1; *whiteningValuePtr64 <<= 1; #else // Big-endian platforms - finalCarry = + finalCarry = (*whiteningValuePtr64 & 0x80) ? 135 : 0; @@ -154,7 +154,7 @@ static void EncryptBufferXTSParallel (unsigned __int8 *buffer, whiteningValuePtr64--; if (*whiteningValuePtr64 & 0x80) - *(whiteningValuePtr64 + 1) |= 0x0100000000000000; + *(whiteningValuePtr64 + 1) |= 0x0100000000000000; *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); #endif @@ -176,7 +176,7 @@ static void EncryptBufferXTSParallel (unsigned __int8 *buffer, // Actual encryption EncipherBlocks (cipher, dataUnitBufPtr, ks, endBlock - startBlock); - + bufPtr = dataUnitBufPtr; whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; @@ -222,7 +222,7 @@ static void EncryptBufferXTSNonParallel (unsigned __int8 *buffer, the shift of the highest byte results in a carry, 135 is XORed into the lowest byte. The value 135 is derived from the modulus of the Galois Field (x^128+x^7+x^2+x+1). */ - // Convert the 64-bit data unit number into a little-endian 16-byte array. + // Convert the 64-bit data unit number into a little-endian 16-byte array. // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. dataUnitNo = startDataUnitNo->Value; *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); @@ -243,7 +243,7 @@ static void EncryptBufferXTSNonParallel (unsigned __int8 *buffer, whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; - // Encrypt the data unit number using the secondary key (in order to generate the first + // Encrypt the data unit number using the secondary key (in order to generate the first // whitening value for this data unit) *whiteningValuePtr64 = *((unsigned __int64 *) byteBufUnitNo); *(whiteningValuePtr64 + 1) = 0; @@ -275,21 +275,21 @@ static void EncryptBufferXTSNonParallel (unsigned __int8 *buffer, // Little-endian platforms - finalCarry = + finalCarry = (*whiteningValuePtr64 & 0x8000000000000000) ? 135 : 0; *whiteningValuePtr64-- <<= 1; if (*whiteningValuePtr64 & 0x8000000000000000) - *(whiteningValuePtr64 + 1) |= 1; + *(whiteningValuePtr64 + 1) |= 1; *whiteningValuePtr64 <<= 1; #else // Big-endian platforms - finalCarry = + finalCarry = (*whiteningValuePtr64 & 0x80) ? 135 : 0; @@ -298,7 +298,7 @@ static void EncryptBufferXTSNonParallel (unsigned __int8 *buffer, whiteningValuePtr64--; if (*whiteningValuePtr64 & 0x80) - *(whiteningValuePtr64 + 1) |= 0x0100000000000000; + *(whiteningValuePtr64 + 1) |= 0x0100000000000000; *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); #endif @@ -353,7 +353,7 @@ static void DecryptBufferXTSParallel (unsigned __int8 *buffer, unsigned __int64 *const finalInt64WhiteningValuesPtr = whiteningValuesPtr64 + sizeof (whiteningValues) / sizeof (*whiteningValuesPtr64) - 1; TC_LARGEST_COMPILER_UINT blockCount, dataUnitNo; - // Convert the 64-bit data unit number into a little-endian 16-byte array. + // Convert the 64-bit data unit number into a little-endian 16-byte array. // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. dataUnitNo = startDataUnitNo->Value; *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); @@ -375,7 +375,7 @@ static void DecryptBufferXTSParallel (unsigned __int8 *buffer, whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; - // Encrypt the data unit number using the secondary key (in order to generate the first + // Encrypt the data unit number using the secondary key (in order to generate the first // whitening value for this data unit) *whiteningValuePtr64 = *((unsigned __int64 *) byteBufUnitNo); *(whiteningValuePtr64 + 1) = 0; @@ -399,21 +399,21 @@ static void DecryptBufferXTSParallel (unsigned __int8 *buffer, // Little-endian platforms - finalCarry = + finalCarry = (*whiteningValuePtr64 & 0x8000000000000000) ? 135 : 0; *whiteningValuePtr64-- <<= 1; if (*whiteningValuePtr64 & 0x8000000000000000) - *(whiteningValuePtr64 + 1) |= 1; + *(whiteningValuePtr64 + 1) |= 1; *whiteningValuePtr64 <<= 1; #else // Big-endian platforms - finalCarry = + finalCarry = (*whiteningValuePtr64 & 0x80) ? 135 : 0; @@ -422,7 +422,7 @@ static void DecryptBufferXTSParallel (unsigned __int8 *buffer, whiteningValuePtr64--; if (*whiteningValuePtr64 & 0x80) - *(whiteningValuePtr64 + 1) |= 0x0100000000000000; + *(whiteningValuePtr64 + 1) |= 0x0100000000000000; *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); #endif @@ -481,7 +481,7 @@ static void DecryptBufferXTSNonParallel (unsigned __int8 *buffer, unsigned int startBlock = startCipherBlockNo, endBlock, block; TC_LARGEST_COMPILER_UINT blockCount, dataUnitNo; - // Convert the 64-bit data unit number into a little-endian 16-byte array. + // Convert the 64-bit data unit number into a little-endian 16-byte array. // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. dataUnitNo = startDataUnitNo->Value; *((unsigned __int64 *) byteBufUnitNo) = LE64 (dataUnitNo); @@ -502,7 +502,7 @@ static void DecryptBufferXTSNonParallel (unsigned __int8 *buffer, whiteningValuePtr64 = (unsigned __int64 *) whiteningValue; - // Encrypt the data unit number using the secondary key (in order to generate the first + // Encrypt the data unit number using the secondary key (in order to generate the first // whitening value for this data unit) *whiteningValuePtr64 = *((unsigned __int64 *) byteBufUnitNo); *(whiteningValuePtr64 + 1) = 0; @@ -534,21 +534,21 @@ static void DecryptBufferXTSNonParallel (unsigned __int8 *buffer, // Little-endian platforms - finalCarry = + finalCarry = (*whiteningValuePtr64 & 0x8000000000000000) ? 135 : 0; *whiteningValuePtr64-- <<= 1; if (*whiteningValuePtr64 & 0x8000000000000000) - *(whiteningValuePtr64 + 1) |= 1; + *(whiteningValuePtr64 + 1) |= 1; *whiteningValuePtr64 <<= 1; #else // Big-endian platforms - finalCarry = + finalCarry = (*whiteningValuePtr64 & 0x80) ? 135 : 0; @@ -557,7 +557,7 @@ static void DecryptBufferXTSNonParallel (unsigned __int8 *buffer, whiteningValuePtr64--; if (*whiteningValuePtr64 & 0x80) - *(whiteningValuePtr64 + 1) |= 0x0100000000000000; + *(whiteningValuePtr64 + 1) |= 0x0100000000000000; *whiteningValuePtr64 = LE64 (LE64 (*whiteningValuePtr64) << 1); #endif @@ -581,7 +581,7 @@ static void DecryptBufferXTSNonParallel (unsigned __int8 *buffer, #if BYTE_ORDER == BIG_ENDIAN #error The TC_NO_COMPILER_INT64 version of the XTS code is not compatible with big-endian platforms -#endif +#endif // Converts a 64-bit unsigned integer (passed as two 32-bit integers for compatibility with non-64-bit @@ -627,7 +627,7 @@ static void EncryptDecryptBufferXTS32 (const unsigned __int8 *buffer, blockCount = length / BYTES_PER_XTS_BLOCK; - // Convert the 64-bit data unit number into a little-endian 16-byte array. + // Convert the 64-bit data unit number into a little-endian 16-byte array. // (Passed as two 32-bit integers for compatibility with non-64-bit environments/platforms.) Uint64ToLE16ByteArray (byteBufUnitNo, dataUnitNo.HighPart, dataUnitNo.LowPart); @@ -639,7 +639,7 @@ static void EncryptDecryptBufferXTS32 (const unsigned __int8 *buffer, else endBlock = BLOCKS_PER_XTS_DATA_UNIT; - // Encrypt the data unit number using the secondary key (in order to generate the first + // Encrypt the data unit number using the secondary key (in order to generate the first // whitening value for this data unit) memcpy (whiteningValue, byteBufUnitNo, BYTES_PER_XTS_BLOCK); EncipherBlock (cipher, whiteningValue, ks2); @@ -690,7 +690,7 @@ static void EncryptDecryptBufferXTS32 (const unsigned __int8 *buffer, // A regular carry *(whiteningValuePtr32 + 1) |= 1; } - else + else { // The highest byte shift will result in a carry finalCarry = 135; @@ -712,7 +712,7 @@ static void EncryptDecryptBufferXTS32 (const unsigned __int8 *buffer, dataUnitNo.HighPart++; } - // Convert the 64-bit data unit number into a little-endian 16-byte array. + // Convert the 64-bit data unit number into a little-endian 16-byte array. Uint64ToLE16ByteArray (byteBufUnitNo, dataUnitNo.HighPart, dataUnitNo.LowPart); } diff --git a/src/Common/Xts.h b/src/Common/Xts.h index f4f4ab5b..2cf0a95d 100644 --- a/src/Common/Xts.h +++ b/src/Common/Xts.h @@ -3,7 +3,7 @@ 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) + 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 @@ -54,9 +54,9 @@ extern "C" { #endif #ifndef TCDEFS_H -typedef union +typedef union { - struct + struct { unsigned __int32 LowPart; unsigned __int32 HighPart; diff --git a/src/Core/Core.h b/src/Core/Core.h index 07a055a0..50c00e91 100644 --- a/src/Core/Core.h +++ b/src/Core/Core.h @@ -3,7 +3,7 @@ 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) + 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 @@ -157,7 +157,7 @@ namespace VeraCrypt public: WaitThreadUI(WaitThreadRoutine* pRoutine): m_pRoutine(pRoutine) {} virtual ~WaitThreadUI() {} - virtual void Run(void) { m_pRoutine->ExecutionCode();} + virtual void Run(void) { m_pRoutine->ExecutionCode();} WaitThreadRoutine* m_pRoutine; }; } diff --git a/src/Core/Core.make b/src/Core/Core.make index 9764f34d..f3fc3406 100644 --- a/src/Core/Core.make +++ b/src/Core/Core.make @@ -3,7 +3,7 @@ # 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) +# 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 diff --git a/src/Core/CoreBase.cpp b/src/Core/CoreBase.cpp index b39e56d8..1703feea 100644 --- a/src/Core/CoreBase.cpp +++ b/src/Core/CoreBase.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -79,7 +79,7 @@ namespace VeraCrypt backupHeader = true; } } - + void CoreBase::ChangePassword (shared_ptr volumePath, bool preserveTimestamps, shared_ptr password, int pim, shared_ptr kdf, bool truecryptMode, shared_ptr keyfiles, shared_ptr newPassword, int newPim, shared_ptr newKeyfiles, shared_ptr newPkcs5Kdf, int wipeCount) const { shared_ptr volume = OpenVolume (volumePath, preserveTimestamps, password, pim, kdf, truecryptMode, keyfiles); @@ -147,7 +147,7 @@ namespace VeraCrypt outerVolume->ReadSectors (bootSectorBuffer, 0); int fatType; - byte *bootSector = bootSectorBuffer.Ptr(); + byte *bootSector = bootSectorBuffer.Ptr(); if (memcmp (bootSector + 54, "FAT12", 5) == 0) fatType = 12; @@ -260,7 +260,7 @@ namespace VeraCrypt volume->Open (*volumePath, preserveTimestamps, password, pim, kdf, truecryptMode, keyfiles, protection, protectionPassword, protectionPim, protectionKdf, protectionKeyfiles, sharedAccessAllowed, volumeType, useBackupHeaders, partitionInSystemEncryptionScope); return volume; } - + void CoreBase::RandomizeEncryptionAlgorithmKey (shared_ptr encryptionAlgorithm) const { SecureBuffer eaKey (encryptionAlgorithm->GetKeySize()); diff --git a/src/Core/CoreBase.h b/src/Core/CoreBase.h index 15bfce3f..34ce9b42 100644 --- a/src/Core/CoreBase.h +++ b/src/Core/CoreBase.h @@ -3,7 +3,7 @@ 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) + 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 @@ -35,7 +35,7 @@ namespace VeraCrypt virtual void ChangePassword (shared_ptr openVolume, shared_ptr newPassword, int newPim, shared_ptr newKeyfiles, shared_ptr newPkcs5Kdf = shared_ptr (), int wipeCount = PRAND_HEADER_WIPE_PASSES) const; virtual void ChangePassword (shared_ptr volumePath, bool preserveTimestamps, shared_ptr password, int pim, shared_ptr kdf, bool truecryptMode, shared_ptr keyfiles, shared_ptr newPassword, int newPim, shared_ptr newKeyfiles, shared_ptr newPkcs5Kdf = shared_ptr (), int wipeCount = PRAND_HEADER_WIPE_PASSES) const; - virtual void CheckFilesystem (shared_ptr mountedVolume, bool repair = false) const = 0; + virtual void CheckFilesystem (shared_ptr mountedVolume, bool repair = false) const = 0; virtual void CoalesceSlotNumberAndMountPoint (MountOptions &options) const; virtual void CreateKeyfile (const FilePath &keyfilePath) const; virtual void DismountFilesystem (const DirectoryPath &mountPoint, bool force) const = 0; diff --git a/src/Core/CoreException.cpp b/src/Core/CoreException.cpp index fd4ea2af..9f0bf04b 100644 --- a/src/Core/CoreException.cpp +++ b/src/Core/CoreException.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/CoreException.h b/src/Core/CoreException.h index 62c56661..36dc1822 100644 --- a/src/Core/CoreException.h +++ b/src/Core/CoreException.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/FatFormatter.cpp b/src/Core/FatFormatter.cpp index 807fa30c..9fb54ff7 100644 --- a/src/Core/FatFormatter.cpp +++ b/src/Core/FatFormatter.cpp @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -89,8 +89,8 @@ namespace VeraCrypt ft->cluster_size = 1; // Geometry always set to SECTORS/1/1 - ft->secs_track = 1; - ft->heads = 1; + ft->secs_track = 1; + ft->heads = 1; ft->dir_entries = 512; ft->fats = 2; @@ -180,13 +180,13 @@ namespace VeraCrypt cnt += 2; boot[cnt++] = (int8) ft->media; /* media byte */ - if(ft->size_fat == 32) + if(ft->size_fat == 32) { boot[cnt++] = 0x00; boot[cnt++] = 0x00; } - else - { + else + { *(uint16 *)(boot + cnt) = Endian::Little ((uint16) ft->fat_length); /* fat size */ cnt += 2; } @@ -248,13 +248,13 @@ namespace VeraCrypt { memset (sector, 0, ft->sector_size); sector[3] = 0x41; /* LeadSig */ - sector[2] = 0x61; - sector[1] = 0x52; - sector[0] = 0x52; + sector[2] = 0x61; + sector[1] = 0x52; + sector[0] = 0x52; sector[484+3] = 0x61; /* StrucSig */ - sector[484+2] = 0x41; - sector[484+1] = 0x72; - sector[484+0] = 0x72; + sector[484+2] = 0x41; + sector[484+1] = 0x72; + sector[484+0] = 0x72; // Free cluster count *(uint32 *)(sector + 488) = Endian::Little (ft->cluster_count - ft->size_root_dir / ft->sector_size / ft->cluster_size); @@ -283,7 +283,7 @@ namespace VeraCrypt fatParams.num_sectors = (uint32) (deviceSize / fatParams.sector_size); fatParams.cluster_size = clusterSize / fatParams.sector_size; memcpy (fatParams.volume_name, "NO NAME ", 11); - GetFatParams (&fatParams); + GetFatParams (&fatParams); fatparams *ft = &fatParams; SecureBuffer sector (ft->sector_size); @@ -300,7 +300,7 @@ namespace VeraCrypt writeSector (sector); ++sectorNumber; /* fat32 boot area */ - if (ft->size_fat == 32) + if (ft->size_fat == 32) { /* fsinfo */ PutFSInfo((byte *) sector, ft); @@ -351,7 +351,7 @@ namespace VeraCrypt fat_sig[8] = fat_sig[9] = fat_sig[10] = 0xff; fat_sig[11] = 0x0f; memcpy (sector, fat_sig, 12); - } + } else if (ft->size_fat == 16) { fat_sig[0] = (byte) ft->media; diff --git a/src/Core/FatFormatter.h b/src/Core/FatFormatter.h index 520e58b1..3b129527 100644 --- a/src/Core/FatFormatter.h +++ b/src/Core/FatFormatter.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/HostDevice.cpp b/src/Core/HostDevice.cpp index 61229983..69788095 100644 --- a/src/Core/HostDevice.cpp +++ b/src/Core/HostDevice.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -41,7 +41,7 @@ namespace VeraCrypt sr.Serialize ("Removable", Removable); sr.Serialize ("Size", Size); sr.Serialize ("SystemNumber", SystemNumber); - + sr.Serialize ("Partitions", (uint32) Partitions.size()); foreach_ref (const HostDevice &partition, Partitions) partition.Serialize (stream); diff --git a/src/Core/HostDevice.h b/src/Core/HostDevice.h index 47e478c6..a790878e 100644 --- a/src/Core/HostDevice.h +++ b/src/Core/HostDevice.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/MountOptions.cpp b/src/Core/MountOptions.cpp index c3529efb..29f554e6 100644 --- a/src/Core/MountOptions.cpp +++ b/src/Core/MountOptions.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -102,14 +102,14 @@ namespace VeraCrypt sr.Deserialize ("UseBackupHeaders", UseBackupHeaders); sr.Deserialize ("TrueCryptMode", TrueCryptMode); - + try { if (!sr.DeserializeBool ("KdfNull")) { sr.Deserialize ("Kdf", nameValue); Kdf = Pkcs5Kdf::GetAlgorithm (nameValue, TrueCryptMode); - } + } } catch(...) {} @@ -122,7 +122,7 @@ namespace VeraCrypt } } catch(...) {} - + sr.Deserialize ("Pim", Pim); sr.Deserialize ("ProtectionPim", ProtectionPim); } @@ -144,7 +144,7 @@ namespace VeraCrypt sr.Serialize ("NoFilesystem", NoFilesystem); sr.Serialize ("NoHardwareCrypto", NoHardwareCrypto); sr.Serialize ("NoKernelCrypto", NoKernelCrypto); - + sr.Serialize ("PasswordNull", Password == nullptr); if (Password) Password->Serialize (stream); @@ -176,7 +176,7 @@ namespace VeraCrypt sr.Serialize ("ProtectionKdfNull", ProtectionKdf == nullptr); if (ProtectionKdf) sr.Serialize ("ProtectionKdf", ProtectionKdf->GetName()); - + sr.Serialize ("Pim", Pim); sr.Serialize ("ProtectionPim", ProtectionPim); } diff --git a/src/Core/MountOptions.h b/src/Core/MountOptions.h index b9319b55..2dcc5e1b 100644 --- a/src/Core/MountOptions.h +++ b/src/Core/MountOptions.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/RandomNumberGenerator.cpp b/src/Core/RandomNumberGenerator.cpp index 403eb288..9551f585 100644 --- a/src/Core/RandomNumberGenerator.cpp +++ b/src/Core/RandomNumberGenerator.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -124,7 +124,7 @@ namespace VeraCrypt if (ReadOffset >= PoolSize) ReadOffset = 0; } - + pbBuffer += loopLen; } } @@ -186,7 +186,7 @@ namespace VeraCrypt } void RandomNumberGenerator::Stop () - { + { ScopeLock lock (AccessMutex); if (Pool.IsAllocated()) diff --git a/src/Core/RandomNumberGenerator.h b/src/Core/RandomNumberGenerator.h index c7608a1a..53482301 100644 --- a/src/Core/RandomNumberGenerator.h +++ b/src/Core/RandomNumberGenerator.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/Unix/CoreService.cpp b/src/Core/Unix/CoreService.cpp index a4f85ba7..caa8c2b0 100644 --- a/src/Core/Unix/CoreService.cpp +++ b/src/Core/Unix/CoreService.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -30,7 +30,7 @@ namespace VeraCrypt auto_ptr CoreService::GetResponse () { auto_ptr deserializedObject (Serializable::DeserializeNew (ServiceOutputStream)); - + Exception *deserializedException = dynamic_cast (deserializedObject.get()); if (deserializedException) deserializedException->Throw(); @@ -60,11 +60,11 @@ namespace VeraCrypt throw_sys_if (read (STDIN_FILENO, &b, 1) != 1); if (b != 0x00) continue; - + throw_sys_if (read (STDIN_FILENO, &b, 1) != 1); if (b != 0x11) continue; - + throw_sys_if (read (STDIN_FILENO, &b, 1) != 1); if (b == 0x22) break; @@ -113,7 +113,7 @@ namespace VeraCrypt if (!ElevatedServiceAvailable) { finally_do_arg (string *, &request->AdminPassword, { StringConverter::Erase (*finally_arg); }); - + CoreService::StartElevated (*request); ElevatedServiceAvailable = true; } @@ -128,7 +128,7 @@ namespace VeraCrypt if (checkRequest) { Core->CheckFilesystem (checkRequest->MountedVolumeInfo, checkRequest->Repair); - + CheckFilesystemResponse().Serialize (outputStream); continue; } @@ -263,7 +263,7 @@ namespace VeraCrypt GetHostDevicesRequest request (pathListOnly); return SendRequest (request)->HostDevices; } - + shared_ptr CoreService::RequestMountVolume (MountOptions &options) { MountVolumeRequest request (&options); @@ -456,7 +456,7 @@ namespace VeraCrypt inPipe->Close(); outPipe->Close(); errPipe.Close(); - + if (request.FastElevation) { // Prevent defunct process @@ -532,7 +532,7 @@ namespace VeraCrypt ExitRequest exitRequest; exitRequest.Serialize (ServiceInputStream); } - + shared_ptr CoreService::AdminPasswordCallback; auto_ptr CoreService::AdminInputPipe; diff --git a/src/Core/Unix/CoreService.h b/src/Core/Unix/CoreService.h index da6d2321..4dce35a0 100644 --- a/src/Core/Unix/CoreService.h +++ b/src/Core/Unix/CoreService.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/Unix/CoreServiceProxy.h b/src/Core/Unix/CoreServiceProxy.h index 9198dd56..33b2be01 100644 --- a/src/Core/Unix/CoreServiceProxy.h +++ b/src/Core/Unix/CoreServiceProxy.h @@ -3,7 +3,7 @@ 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) + 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 @@ -97,7 +97,7 @@ namespace VeraCrypt else { MountOptions newOptions = options; - + newOptions.Password = Keyfile::ApplyListToPassword (options.Keyfiles, options.Password); if (newOptions.Keyfiles) newOptions.Keyfiles->clear(); diff --git a/src/Core/Unix/CoreServiceRequest.cpp b/src/Core/Unix/CoreServiceRequest.cpp index b19f0f81..51e26c0c 100644 --- a/src/Core/Unix/CoreServiceRequest.cpp +++ b/src/Core/Unix/CoreServiceRequest.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -229,13 +229,13 @@ namespace VeraCrypt Serializer sr (stream); Options->Serialize (stream); } - + // SetFileOwnerRequest void SetFileOwnerRequest::Deserialize (shared_ptr stream) { CoreServiceRequest::Deserialize (stream); Serializer sr (stream); - + uint64 owner; sr.Deserialize ("Owner", owner); Owner.SystemId = static_cast (owner); diff --git a/src/Core/Unix/CoreServiceRequest.h b/src/Core/Unix/CoreServiceRequest.h index 61b673ec..b6798e41 100644 --- a/src/Core/Unix/CoreServiceRequest.h +++ b/src/Core/Unix/CoreServiceRequest.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/Unix/CoreServiceResponse.cpp b/src/Core/Unix/CoreServiceResponse.cpp index 9980cc91..e56ac123 100644 --- a/src/Core/Unix/CoreServiceResponse.cpp +++ b/src/Core/Unix/CoreServiceResponse.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -75,7 +75,7 @@ namespace VeraCrypt Serializer sr (stream); sr.Serialize ("Size", Size); } - + // GetHostDevicesResponse void GetHostDevicesResponse::Deserialize (shared_ptr stream) { diff --git a/src/Core/Unix/CoreServiceResponse.h b/src/Core/Unix/CoreServiceResponse.h index d5956f8e..24c7b64c 100644 --- a/src/Core/Unix/CoreServiceResponse.h +++ b/src/Core/Unix/CoreServiceResponse.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/Unix/CoreUnix.cpp b/src/Core/Unix/CoreUnix.cpp index 43c37a28..12287038 100644 --- a/src/Core/Unix/CoreUnix.cpp +++ b/src/Core/Unix/CoreUnix.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -27,7 +27,7 @@ namespace VeraCrypt CoreUnix::CoreUnix () { signal (SIGPIPE, SIG_IGN); - + char *loc = setlocale (LC_ALL, ""); if (!loc || string (loc) == "C") setlocale (LC_ALL, "en_US.UTF-8"); @@ -36,7 +36,7 @@ namespace VeraCrypt CoreUnix::~CoreUnix () { } - + void CoreUnix::CheckFilesystem (shared_ptr mountedVolume, bool repair) const { if (!mountedVolume->MountPoint.IsEmpty()) @@ -77,9 +77,9 @@ namespace VeraCrypt args.push_back ("fsck"); args.push_back ("--caption"); args.push_back ("fsck"); - args.push_back ("-e"); - args.push_back ("sh"); - args.push_back ("-c"); + args.push_back ("-e"); + args.push_back ("sh"); + args.push_back ("-c"); args.push_back (xargs); try { @@ -176,7 +176,7 @@ namespace VeraCrypt { string path = filePath; size_t pos; - + while ((pos = path.find_last_of ('/')) != string::npos) { path = path.substr (0, pos); @@ -224,7 +224,7 @@ namespace VeraCrypt device.SeekAt (0); device.ReadCompleteBuffer (bootSector); - byte *b = bootSector.Ptr(); + byte *b = bootSector.Ptr(); return memcmp (b + 3, "NTFS", 4) != 0 && memcmp (b + 54, "FAT", 3) != 0 @@ -237,13 +237,13 @@ namespace VeraCrypt const char *envPrefix = getenv ("VERACRYPT_MOUNT_PREFIX"); if (envPrefix && !string (envPrefix).empty()) return envPrefix; - + if (FilesystemPath ("/media").IsDirectory()) return "/media/veracrypt"; - + if (FilesystemPath ("/mnt").IsDirectory()) return "/mnt/veracrypt"; - + return GetTempDirectory() + "/veracrypt_mnt"; } @@ -298,7 +298,7 @@ namespace VeraCrypt { continue; } - + if (!volumePath.IsEmpty() && wstring (mountedVol->Path).compare (volumePath) != 0) continue; @@ -320,7 +320,7 @@ namespace VeraCrypt return volumes; } - + gid_t CoreUnix::GetRealGroupId () const { const char *env = getenv ("SUDO_GID"); @@ -352,7 +352,7 @@ namespace VeraCrypt return getuid(); } - + string CoreUnix::GetTempDirectory () const { char *envDir = getenv ("TMPDIR"); @@ -583,7 +583,7 @@ namespace VeraCrypt throw; } -#ifndef TC_MACOSX +#ifndef TC_MACOSX // set again correct ownership of the mount point to avoid any issues if (!options.NoFilesystem && options.MountPoint) { diff --git a/src/Core/Unix/CoreUnix.h b/src/Core/Unix/CoreUnix.h index e4c3aa3e..4d12d4b0 100644 --- a/src/Core/Unix/CoreUnix.h +++ b/src/Core/Unix/CoreUnix.h @@ -3,7 +3,7 @@ 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) + 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 @@ -26,7 +26,7 @@ namespace VeraCrypt CoreUnix (); virtual ~CoreUnix (); - virtual void CheckFilesystem (shared_ptr mountedVolume, bool repair = false) const; + virtual void CheckFilesystem (shared_ptr mountedVolume, bool repair = false) const; virtual void DismountFilesystem (const DirectoryPath &mountPoint, bool force) const; virtual shared_ptr DismountVolume (shared_ptr mountedVolume, bool ignoreOpenFiles = false, bool syncVolumeInfo = false); virtual bool FilesystemSupportsLargeFiles (const FilePath &filePath) const; @@ -63,7 +63,7 @@ namespace VeraCrypt virtual void MountFilesystem (const DevicePath &devicePath, const DirectoryPath &mountPoint, const string &filesystemType, bool readOnly, const string &systemMountOptions) const; virtual void MountAuxVolumeImage (const DirectoryPath &auxMountPoint, const MountOptions &options) const; virtual void MountVolumeNative (shared_ptr volume, MountOptions &options, const DirectoryPath &auxMountPoint) const { throw NotApplicable (SRC_POS); } - + private: CoreUnix (const CoreUnix &); CoreUnix &operator= (const CoreUnix &); diff --git a/src/Core/Unix/FreeBSD/CoreFreeBSD.cpp b/src/Core/Unix/FreeBSD/CoreFreeBSD.cpp index 20575067..2dd6be0b 100644 --- a/src/Core/Unix/FreeBSD/CoreFreeBSD.cpp +++ b/src/Core/Unix/FreeBSD/CoreFreeBSD.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -127,8 +127,8 @@ namespace VeraCrypt partition->Path = partPath.str(); if (!pathListOnly) { - try - { + try + { partition->Size = GetDeviceSize (partition->Path); } catch (...) diff --git a/src/Core/Unix/FreeBSD/CoreFreeBSD.h b/src/Core/Unix/FreeBSD/CoreFreeBSD.h index 6c6b8062..c7d496fb 100644 --- a/src/Core/Unix/FreeBSD/CoreFreeBSD.h +++ b/src/Core/Unix/FreeBSD/CoreFreeBSD.h @@ -3,7 +3,7 @@ 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) + 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 @@ -24,7 +24,7 @@ namespace VeraCrypt CoreFreeBSD (); virtual ~CoreFreeBSD (); - virtual HostDeviceList GetHostDevices (bool pathListOnly = false) const; + virtual HostDeviceList GetHostDevices (bool pathListOnly = false) const; protected: virtual DevicePath AttachFileToLoopDevice (const FilePath &filePath, bool readOnly) const; diff --git a/src/Core/Unix/FreeBSD/System.h b/src/Core/Unix/FreeBSD/System.h index c97f60d2..26daade0 100644 --- a/src/Core/Unix/FreeBSD/System.h +++ b/src/Core/Unix/FreeBSD/System.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/Unix/Linux/CoreLinux.cpp b/src/Core/Unix/Linux/CoreLinux.cpp index 50d546d4..eb4545fd 100644 --- a/src/Core/Unix/Linux/CoreLinux.cpp +++ b/src/Core/Unix/Linux/CoreLinux.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -41,7 +41,7 @@ namespace VeraCrypt loopPaths.push_back ("/dev/loop"); loopPaths.push_back ("/dev/loop/"); loopPaths.push_back ("/dev/.static/dev/loop"); - + // On Fedora 23,"losetup -f" must be called first to create a default loop device list args; args.push_back ("-f"); @@ -171,7 +171,7 @@ namespace VeraCrypt while (tr.ReadLine (line)) { vector fields = StringConverter::Split (line); - + if (fields.size() != 4 || fields[3].find ("loop") == 0 // skip loop devices || fields[3].find ("cloop") == 0 @@ -390,10 +390,10 @@ namespace VeraCrypt stringstream nativeDevName; nativeDevName << "veracrypt" << options.SlotNumber; - + if (nativeDevCount != cipherCount - 1) nativeDevName << "_" << cipherCount - nativeDevCount - 2; - + nativeDevPath = "/dev/mapper/" + nativeDevName.str(); execArgs.clear(); @@ -401,7 +401,7 @@ namespace VeraCrypt execArgs.push_back (nativeDevName.str()); Process::Execute ("dmsetup", execArgs, -1, nullptr, &dmCreateArgsBuf); - + // Wait for the device to be created for (int t = 0; true; t++) { diff --git a/src/Core/Unix/Linux/CoreLinux.h b/src/Core/Unix/Linux/CoreLinux.h index 949313bf..d31ba570 100644 --- a/src/Core/Unix/Linux/CoreLinux.h +++ b/src/Core/Unix/Linux/CoreLinux.h @@ -3,7 +3,7 @@ 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) + 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 @@ -24,7 +24,7 @@ namespace VeraCrypt CoreLinux (); virtual ~CoreLinux (); - virtual HostDeviceList GetHostDevices (bool pathListOnly = false) const; + virtual HostDeviceList GetHostDevices (bool pathListOnly = false) const; protected: virtual DevicePath AttachFileToLoopDevice (const FilePath &filePath, bool readOnly) const; diff --git a/src/Core/Unix/Linux/System.h b/src/Core/Unix/Linux/System.h index df7d9ba7..3acfa166 100644 --- a/src/Core/Unix/Linux/System.h +++ b/src/Core/Unix/Linux/System.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/Unix/MacOSX/CoreMacOSX.cpp b/src/Core/Unix/MacOSX/CoreMacOSX.cpp index b2a10017..e7572e68 100644 --- a/src/Core/Unix/MacOSX/CoreMacOSX.cpp +++ b/src/Core/Unix/MacOSX/CoreMacOSX.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -139,7 +139,7 @@ namespace VeraCrypt } else throw HigherFuseVersionRequired (SRC_POS); - + } vector fuseVersion = StringConverter::Split (string (fuseVersionString), "."); @@ -187,7 +187,7 @@ namespace VeraCrypt args.push_back ("-readonly"); string xml; - + while (true) { try @@ -202,7 +202,7 @@ namespace VeraCrypt args.remove ("-noautofsck"); continue; } - + throw; } } diff --git a/src/Core/Unix/MacOSX/CoreMacOSX.h b/src/Core/Unix/MacOSX/CoreMacOSX.h index f3bf6bf7..5b190e4a 100644 --- a/src/Core/Unix/MacOSX/CoreMacOSX.h +++ b/src/Core/Unix/MacOSX/CoreMacOSX.h @@ -3,7 +3,7 @@ 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) + 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 @@ -24,7 +24,7 @@ namespace VeraCrypt CoreMacOSX (); virtual ~CoreMacOSX (); - virtual void CheckFilesystem (shared_ptr mountedVolume, bool repair = false) const; + virtual void CheckFilesystem (shared_ptr mountedVolume, bool repair = false) const; virtual shared_ptr DismountVolume (shared_ptr mountedVolume, bool ignoreOpenFiles = false, bool syncVolumeInfo = false); virtual string GetDefaultMountPointPrefix () const { return "/Volumes/veracrypt"; } diff --git a/src/Core/Unix/MacOSX/System.h b/src/Core/Unix/MacOSX/System.h index 04d08a57..5931628b 100644 --- a/src/Core/Unix/MacOSX/System.h +++ b/src/Core/Unix/MacOSX/System.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/Unix/MountedFilesystem.h b/src/Core/Unix/MountedFilesystem.h index 741c49d6..f47fc946 100644 --- a/src/Core/Unix/MountedFilesystem.h +++ b/src/Core/Unix/MountedFilesystem.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/Unix/Solaris/CoreSolaris.cpp b/src/Core/Unix/Solaris/CoreSolaris.cpp index 9101e4f8..1e99d98f 100644 --- a/src/Core/Unix/Solaris/CoreSolaris.cpp +++ b/src/Core/Unix/Solaris/CoreSolaris.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -80,7 +80,7 @@ namespace VeraCrypt { device->Size = 0; } - + if (device->Size == 0) continue; @@ -99,8 +99,8 @@ namespace VeraCrypt make_shared_auto (HostDevice, partition); partition->Path = partPath.str(); - try - { + try + { partition->Size = GetDeviceSize (partition->Path); } catch (...) diff --git a/src/Core/Unix/Solaris/CoreSolaris.h b/src/Core/Unix/Solaris/CoreSolaris.h index 26543220..2e9dbc1c 100644 --- a/src/Core/Unix/Solaris/CoreSolaris.h +++ b/src/Core/Unix/Solaris/CoreSolaris.h @@ -3,7 +3,7 @@ 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) + 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 @@ -24,7 +24,7 @@ namespace VeraCrypt CoreSolaris (); virtual ~CoreSolaris (); - virtual HostDeviceList GetHostDevices (bool pathListOnly = false) const; + virtual HostDeviceList GetHostDevices (bool pathListOnly = false) const; protected: virtual DevicePath AttachFileToLoopDevice (const FilePath &filePath, bool readOnly) const; diff --git a/src/Core/Unix/Solaris/System.h b/src/Core/Unix/Solaris/System.h index 5bff4c5e..e8b05dac 100644 --- a/src/Core/Unix/Solaris/System.h +++ b/src/Core/Unix/Solaris/System.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/Unix/System.h b/src/Core/Unix/System.h index e322d331..30384907 100644 --- a/src/Core/Unix/System.h +++ b/src/Core/Unix/System.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Core/VolumeCreator.cpp b/src/Core/VolumeCreator.cpp index a920eba1..94aba4bc 100644 --- a/src/Core/VolumeCreator.cpp +++ b/src/Core/VolumeCreator.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -33,7 +33,7 @@ namespace VeraCrypt VolumeCreator::~VolumeCreator () { } - + void VolumeCreator::Abort () { AbortRequested = true; diff --git a/src/Core/VolumeCreator.h b/src/Core/VolumeCreator.h index 2c9fff3a..55f51e50 100644 --- a/src/Core/VolumeCreator.h +++ b/src/Core/VolumeCreator.h @@ -3,7 +3,7 @@ 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) + 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 @@ -19,7 +19,7 @@ namespace VeraCrypt { - + struct VolumeCreationOptions { VolumePath Path; diff --git a/src/Crypto/AesSmall_x86.asm b/src/Crypto/AesSmall_x86.asm index de32fc66..20008194 100644 --- a/src/Crypto/AesSmall_x86.asm +++ b/src/Crypto/AesSmall_x86.asm @@ -1,23 +1,23 @@ ; --------------------------------------------------------------------------- ; Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. -; +; ; LICENSE TERMS -; +; ; The free distribution and use of this software is allowed (with or without ; changes) provided that: -; +; ; 1. source code distributions include the above copyright notice, this ; list of conditions and the following disclaimer; -; +; ; 2. binary distributions include the above copyright notice, this list ; of conditions and the following disclaimer in their documentation; -; +; ; 3. the name of the copyright holder is not used to endorse products ; built using this software without specific written permission. -; +; ; DISCLAIMER -; +; ; This software is provided 'as is' with no explicit or implied warranties ; in respect of its properties, including, but not limited to, correctness ; and/or fitness for purpose. @@ -367,7 +367,7 @@ extern _aes_enc_tab ; Apply S-Box to the 4 bytes in a 32-bit word and rotate byte positions %ifdef REDUCE_CODE_SIZE - + l3s_col: movzx ecx,al ; in eax movzx ecx, etab_b(ecx) ; out eax @@ -413,7 +413,7 @@ l3s_col: %endmacro %endif - + ; offsets to parameters in_blk equ 2 ; input byte array address parameter @@ -444,7 +444,7 @@ enc_round: xor ebx,[ebp+4] add sp, 2 ret - + %else %macro enc_round 0 @@ -724,7 +724,7 @@ enc_round: mov ax, sp movzx esp, ax - + push ebp push ebx push esi @@ -1000,7 +1000,7 @@ dec_round: ; AES Decryption Subroutine do_name _aes_decrypt,12 - + mov ax, sp movzx esp, ax @@ -1095,7 +1095,7 @@ inv_mix_col: %else -%macro inv_mix_col 0 +%macro inv_mix_col 0 movzx ecx,dl ; input eax, edx movzx ecx,etab_b(ecx) ; output eax @@ -1243,14 +1243,14 @@ inv_mix_col: %endif do_name _aes_decrypt_key256,8 - + mov ax, sp movzx esp, ax push ebp push ebx push esi push edi - + movzx eax, word [esp+20] ; ks movzx edx, word [esp+18] ; key push ax diff --git a/src/Crypto/Aes_hw_cpu.asm b/src/Crypto/Aes_hw_cpu.asm index 53852665..faaba4f3 100644 --- a/src/Crypto/Aes_hw_cpu.asm +++ b/src/Crypto/Aes_hw_cpu.asm @@ -254,7 +254,7 @@ cmp ax, 0 jl .decrypt - + aesenc xmm1, xmm0 jmp .2 .decrypt: @@ -264,7 +264,7 @@ add si, ax movdqu xmm0, [si] - + cmp ax, 0 jl .decrypt_last diff --git a/src/Crypto/Aes_hw_cpu.h b/src/Crypto/Aes_hw_cpu.h index e2fed1a1..1265ac47 100644 --- a/src/Crypto/Aes_hw_cpu.h +++ b/src/Crypto/Aes_hw_cpu.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Crypto/Aes_x64.asm b/src/Crypto/Aes_x64.asm index 06d57ac2..f74d0328 100644 --- a/src/Crypto/Aes_x64.asm +++ b/src/Crypto/Aes_x64.asm @@ -1,23 +1,23 @@ ; --------------------------------------------------------------------------- ; Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. -; +; ; LICENSE TERMS -; +; ; The free distribution and use of this software is allowed (with or without ; changes) provided that: -; +; ; 1. source code distributions include the above copyright notice, this ; list of conditions and the following disclaimer; -; +; ; 2. binary distributions include the above copyright notice, this list ; of conditions and the following disclaimer in their documentation; -; +; ; 3. the name of the copyright holder is not used to endorse products ; built using this software without specific written permission. -; +; ; DISCLAIMER -; +; ; This software is provided 'as is' with no explicit or implied warranties ; in respect of its properties, including, but not limited to, correctness ; and/or fitness for purpose. diff --git a/src/Crypto/Aes_x86.asm b/src/Crypto/Aes_x86.asm index 3825deee..484e31a7 100644 --- a/src/Crypto/Aes_x86.asm +++ b/src/Crypto/Aes_x86.asm @@ -1,23 +1,23 @@ ; --------------------------------------------------------------------------- ; Copyright (c) 1998-2007, Brian Gladman, Worcester, UK. All rights reserved. -; +; ; LICENSE TERMS -; +; ; The free distribution and use of this software is allowed (with or without ; changes) provided that: -; +; ; 1. source code distributions include the above copyright notice, this ; list of conditions and the following disclaimer; -; +; ; 2. binary distributions include the above copyright notice, this list ; of conditions and the following disclaimer in their documentation; -; +; ; 3. the name of the copyright holder is not used to endorse products ; built using this software without specific written permission. -; +; ; DISCLAIMER -; +; ; This software is provided 'as is' with no explicit or implied warranties ; in respect of its properties, including, but not limited to, correctness ; and/or fitness for purpose. diff --git a/src/Crypto/Aestab.c b/src/Crypto/Aestab.c index 1effb6f6..afa633ec 100644 --- a/src/Crypto/Aestab.c +++ b/src/Crypto/Aestab.c @@ -280,7 +280,7 @@ AES_RETURN aes_init(void) return EXIT_SUCCESS; for (i = 0; i < 256; ++i) - { + { uint_8t x = fwd_affine(fi((uint_8t)i)); aes_enc_tab[i][0] = 0; aes_enc_tab[i][1] = x; diff --git a/src/Crypto/Rmd160.c b/src/Crypto/Rmd160.c index 75a34c3e..9387f9ba 100644 --- a/src/Crypto/Rmd160.c +++ b/src/Crypto/Rmd160.c @@ -15,7 +15,7 @@ #include "Common/Endian.h" #include "Rmd160.h" -#define F(x, y, z) (x ^ y ^ z) +#define F(x, y, z) (x ^ y ^ z) #define G(x, y, z) (z ^ (x & (y^z))) #define H(x, y, z) (z ^ (x | ~y)) #define I(x, y, z) (y ^ (z & (x^y))) @@ -300,7 +300,7 @@ void RMD160Transform (unsigned __int32 *digest, const unsigned __int32 *data) Subround(J, b2, c2, d2, e2, a2, X[ 3], 12, k5); Subround(J, a2, b2, c2, d2, e2, X[12], 6, k5); - Subround(I, e2, a2, b2, c2, d2, X[ 6], 9, k6); + Subround(I, e2, a2, b2, c2, d2, X[ 6], 9, k6); Subround(I, d2, e2, a2, b2, c2, X[11], 13, k6); Subround(I, c2, d2, e2, a2, b2, X[ 3], 15, k6); Subround(I, b2, c2, d2, e2, a2, X[ 7], 7, k6); @@ -383,7 +383,7 @@ void RMD160Transform (unsigned __int32 *digest, const unsigned __int32 *data) 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) + 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 @@ -454,7 +454,7 @@ void RMD160Transform (unsigned __int32 *state, const unsigned __int32 *data) for (pos = 0; pos < 160; ++pos) { tmp = a + data[OrderTab[pos]] + KTab[pos >> 4]; - + switch (pos >> 4) { case 0: case 9: tmp += F (b, c, d); break; diff --git a/src/Crypto/Serpent.c b/src/Crypto/Serpent.c index a8c528de..2db76deb 100644 --- a/src/Crypto/Serpent.c +++ b/src/Crypto/Serpent.c @@ -64,7 +64,7 @@ #define afterI1(f) f(1,a,b,c,e,d) #define afterI0(f) f(0,a,d,b,e,c) -// The instruction sequences for the S-box functions +// The instruction sequences for the S-box functions // come from Dag Arne Osvik's paper "Speeding up Serpent". #define S0(i, r0, r1, r2, r3, r4) \ @@ -462,9 +462,9 @@ static void S0f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r } static void S1f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ - *r0 = ~*r0; - *r2 = ~*r2; +{ + *r0 = ~*r0; + *r2 = ~*r2; *r4 = *r0; *r0 &= *r1; *r2 ^= *r0; @@ -484,7 +484,7 @@ static void S1f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r } static void S2f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ +{ *r4 = *r0; *r0 &= *r2; *r0 ^= *r3; @@ -500,11 +500,11 @@ static void S2f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r *r4 ^= *r0; *r1 ^= *r3; *r1 ^= *r4; - *r4 = ~*r4; + *r4 = ~*r4; } static void S3f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ +{ *r4 = *r0; *r0 |= *r3; *r3 ^= *r1; @@ -527,9 +527,9 @@ static void S3f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r } static void S4f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ +{ *r1 ^= *r3; - *r3 = ~*r3; + *r3 = ~*r3; *r2 ^= *r3; *r3 ^= *r0; *r4 = *r1; @@ -546,15 +546,15 @@ static void S4f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r *r0 |= *r3; *r0 ^= *r2; *r2 &= *r3; - *r0 = ~*r0; + *r0 = ~*r0; *r4 ^= *r2; } static void S5f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ +{ *r0 ^= *r1; *r1 ^= *r3; - *r3 = ~*r3; + *r3 = ~*r3; *r4 = *r1; *r1 &= *r0; *r2 ^= *r3; @@ -567,15 +567,15 @@ static void S5f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r *r4 ^= *r2; *r2 ^= *r0; *r0 &= *r3; - *r2 = ~*r2; + *r2 = ~*r2; *r0 ^= *r4; *r4 |= *r3; *r2 ^= *r4; } static void S6f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ - *r2 = ~*r2; +{ + *r2 = ~*r2; *r4 = *r3; *r3 &= *r0; *r0 ^= *r4; @@ -590,13 +590,13 @@ static void S6f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r *r0 ^= *r2; *r4 ^= *r3; *r4 ^= *r0; - *r3 = ~*r3; + *r3 = ~*r3; *r2 &= *r4; *r2 ^= *r3; } static void S7f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r2, unsigned __int32 *r3, unsigned __int32 *r4) -{ +{ *r4 = *r2; *r2 &= *r1; *r2 ^= *r3; @@ -612,7 +612,7 @@ static void S7f (unsigned __int32 *r0, unsigned __int32 *r1, unsigned __int32 *r *r3 ^= *r4; *r4 ^= *r2; *r2 &= *r0; - *r4 = ~*r4; + *r4 = ~*r4; *r2 ^= *r4; *r4 &= *r0; *r1 ^= *r3; @@ -767,7 +767,7 @@ void serpent_encrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, while (1); afterS7(KX); - + out[0] = LE32(d); out[1] = LE32(e); out[2] = LE32(b); @@ -827,7 +827,7 @@ void serpent_encrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, while (1); KXf (k, 32, &d, &e, &b, &a); - + out[0] = LE32(d); out[1] = LE32(e); out[2] = LE32(b); @@ -862,17 +862,17 @@ void serpent_decrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, k -= 32; beforeI7(ILT); start: - beforeI7(I7); afterI7(KX); - afterI7(ILT); afterI7(I6); afterI6(KX); - afterI6(ILT); afterI6(I5); afterI5(KX); - afterI5(ILT); afterI5(I4); afterI4(KX); - afterI4(ILT); afterI4(I3); afterI3(KX); - afterI3(ILT); afterI3(I2); afterI2(KX); - afterI2(ILT); afterI2(I1); afterI1(KX); + beforeI7(I7); afterI7(KX); + afterI7(ILT); afterI7(I6); afterI6(KX); + afterI6(ILT); afterI6(I5); afterI5(KX); + afterI5(ILT); afterI5(I4); afterI4(KX); + afterI4(ILT); afterI4(I3); afterI3(KX); + afterI3(ILT); afterI3(I2); afterI2(KX); + afterI2(ILT); afterI2(I1); afterI1(KX); afterI1(ILT); afterI1(I0); afterI0(KX); } while (--i != 0); - + out[0] = LE32(a); out[1] = LE32(d); out[2] = LE32(b); @@ -882,7 +882,7 @@ start: #else // TC_MINIMIZE_CODE_SIZE static void ILTf (uint32 *a, uint32 *b, uint32 *c, uint32 *d) -{ +{ *c = rotrFixed(*c, 22); *a = rotrFixed(*a, 5); *c ^= *d ^ (*b << 7); @@ -919,16 +919,16 @@ void serpent_decrypt(const unsigned __int8 *inBlock, unsigned __int8 *outBlock, beforeI7(ILT); start: beforeI7(I7); KXf (k, 28, &d, &a, &b, &e); - ILTf (&d, &a, &b, &e); afterI7(I6); KXf (k, 24, &a, &b, &c, &e); - ILTf (&a, &b, &c, &e); afterI6(I5); KXf (k, 20, &b, &d, &e, &c); - ILTf (&b, &d, &e, &c); afterI5(I4); KXf (k, 16, &b, &c, &e, &a); + ILTf (&d, &a, &b, &e); afterI7(I6); KXf (k, 24, &a, &b, &c, &e); + ILTf (&a, &b, &c, &e); afterI6(I5); KXf (k, 20, &b, &d, &e, &c); + ILTf (&b, &d, &e, &c); afterI5(I4); KXf (k, 16, &b, &c, &e, &a); ILTf (&b, &c, &e, &a); afterI4(I3); KXf (k, 12, &a, &b, &e, &c); ILTf (&a, &b, &e, &c); afterI3(I2); KXf (k, 8, &b, &d, &e, &c); ILTf (&b, &d, &e, &c); afterI2(I1); KXf (k, 4, &a, &b, &c, &e); ILTf (&a, &b, &c, &e); afterI1(I0); KXf (k, 0, &a, &d, &b, &e); } while (--i != 0); - + out[0] = LE32(a); out[1] = LE32(d); out[2] = LE32(b); diff --git a/src/Crypto/Sha2Small.c b/src/Crypto/Sha2Small.c index 539ff05d..08318833 100644 --- a/src/Crypto/Sha2Small.c +++ b/src/Crypto/Sha2Small.c @@ -52,7 +52,7 @@ static const uint32 K[64] = { Various logical functions */ #define Ch(x,y,z) (z ^ (x & (y ^ z))) -#define Maj(x,y,z) (((x | y) & z) | (x & y)) +#define Maj(x,y,z) (((x | y) & z) | (x & y)) #define S(x, n) RORc((x),(n)) #define R(x, n) ((x)>>(n)) #define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22)) @@ -119,7 +119,7 @@ static void sha256_compress(sha256_ctx * ctx, unsigned char *buf) for (i = 0; i < 64; ++i) { RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i); - t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4]; + t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4]; S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t; } @@ -154,7 +154,7 @@ VOID_RETURN sha256_hash(unsigned char* data, unsigned int len, sha256_ctx* ctx) { uint32 n; while (len > 0) { - if (ctx->curlen == 0 && len >= 64) { + if (ctx->curlen == 0 && len >= 64) { sha256_compress(ctx, (unsigned char *)data); n = ctx->lowLength + 512; @@ -178,7 +178,7 @@ VOID_RETURN sha256_hash(unsigned char* data, unsigned int len, sha256_ctx* ctx) if (n < ctx->lowLength) { ctx->highLength++; } - ctx->lowLength = n; + ctx->lowLength = n; ctx->curlen = 0; } } @@ -232,7 +232,7 @@ VOID_RETURN sha256_end(unsigned char* hval, sha256_ctx* ctx) STORE32H(ctx->highLength, ctx->buf, 56); STORE32H(ctx->lowLength, ctx->buf, 60); - + sha256_compress(ctx, ctx->buf); /* diff --git a/src/Crypto/Twofish.c b/src/Crypto/Twofish.c index 7c58c91e..09f6edaf 100644 --- a/src/Crypto/Twofish.c +++ b/src/Crypto/Twofish.c @@ -63,26 +63,26 @@ static u1byte tab_ef[4] = { 0, (G_M >> 1) ^ (G_M >> 2), G_M >> 1, G_M >> 2 }; static u1byte ror4[16] = { 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15 }; static u1byte ashx[16] = { 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7 }; -static u1byte qt0[2][16] = +static u1byte qt0[2][16] = { { 8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4 }, { 2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5 } }; static u1byte qt1[2][16] = -{ { 14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13 }, +{ { 14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13 }, { 1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8 } }; -static u1byte qt2[2][16] = +static u1byte qt2[2][16] = { { 11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1 }, { 4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15 } }; -static u1byte qt3[2][16] = +static u1byte qt3[2][16] = { { 13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10 }, { 11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10 } }; - + static u1byte qp(const u4byte n, const u1byte x) { u1byte a0, a1, a2, a3, a4, b0, b1, b2, b3, b4; @@ -105,7 +105,7 @@ static void gen_qtab(void) { u4byte i; for(i = 0; i < 256; ++i) - { + { q(0,i) = qp(0, (u1byte)i); q(1,i) = qp(1, (u1byte)i); } @@ -124,7 +124,7 @@ static u4byte m_tab[4][256]; static void gen_mtab(void) { u4byte i, f01, f5b, fef; - + for(i = 0; i < 256; ++i) { f01 = q(1,i); f5b = ffm_5b(f01); fef = ffm_ef(f01); @@ -254,12 +254,12 @@ static void gen_mk_tab(TwofishInstance *instance, u4byte key[]) mk_tab[0 + 4*i] = mds(0, q20(by)); mk_tab[1 + 4*i] = mds(1, q21(by)); mk_tab[2 + 4*i] = mds(2, q22(by)); mk_tab[3 + 4*i] = mds(3, q23(by)); #else - sb[0][i] = q20(by); sb[1][i] = q21(by); + sb[0][i] = q20(by); sb[1][i] = q21(by); sb[2][i] = q22(by); sb[3][i] = q23(by); #endif } break; - + case 3: for(i = 0; i < 256; ++i) { by = (u1byte)i; @@ -267,12 +267,12 @@ static void gen_mk_tab(TwofishInstance *instance, u4byte key[]) mk_tab[0 + 4*i] = mds(0, q30(by)); mk_tab[1 + 4*i] = mds(1, q31(by)); mk_tab[2 + 4*i] = mds(2, q32(by)); mk_tab[3 + 4*i] = mds(3, q33(by)); #else - sb[0][i] = q30(by); sb[1][i] = q31(by); + sb[0][i] = q30(by); sb[1][i] = q31(by); sb[2][i] = q32(by); sb[3][i] = q33(by); #endif } break; - + case 4: for(i = 0; i < 256; ++i) { by = (u1byte)i; @@ -280,7 +280,7 @@ static void gen_mk_tab(TwofishInstance *instance, u4byte key[]) mk_tab[0 + 4*i] = mds(0, q40(by)); mk_tab[1 + 4*i] = mds(1, q41(by)); mk_tab[2 + 4*i] = mds(2, q42(by)); mk_tab[3 + 4*i] = mds(3, q43(by)); #else - sb[0][i] = q40(by); sb[1][i] = q41(by); + sb[0][i] = q40(by); sb[1][i] = q41(by); sb[2][i] = q42(by); sb[3][i] = q43(by); #endif } @@ -315,22 +315,22 @@ static void gen_mk_tab(TwofishInstance *instance, u4byte key[]) where the coefficients are in the finite field GF(2^8) with a modular polynomial a^8 + a^6 + a^3 + a^2 + 1. To generate the remainder we have to start with a 12th order polynomial with our -eight input bytes as the coefficients of the 4th to 11th terms. +eight input bytes as the coefficients of the 4th to 11th terms. That is: m[7] * x^11 + m[6] * x^10 ... + m[0] * x^4 + 0 * x^3 +... + 0 - + We then multiply the generator polynomial by m[7] * x^7 and subtract -it - xor in GF(2^8) - from the above to eliminate the x^7 term (the -artihmetic on the coefficients is done in GF(2^8). We then multiply +it - xor in GF(2^8) - from the above to eliminate the x^7 term (the +artihmetic on the coefficients is done in GF(2^8). We then multiply the generator polynomial by x^6 * coeff(x^10) and use this to remove the x^10 term. We carry on in this way until the x^4 term is removed so that we are left with: r[3] * x^3 + r[2] * x^2 + r[1] 8 x^1 + r[0] -which give the resulting 4 bytes of the remainder. This is equivalent -to the matrix multiplication in the Twofish description but much faster +which give the resulting 4 bytes of the remainder. This is equivalent +to the matrix multiplication in the Twofish description but much faster to implement. */ @@ -343,23 +343,23 @@ static u4byte mds_rem(u4byte p0, u4byte p1) for(i = 0; i < 8; ++i) { t = p1 >> 24; // get most significant coefficient - + p1 = (p1 << 8) | (p0 >> 24); p0 <<= 8; // shift others up - + // multiply t by a (the primitive element - i.e. left shift) - u = (t << 1); - + u = (t << 1); + if(t & 0x80) // subtract modular polynomial on overflow - - u ^= G_MOD; - p1 ^= t ^ (u << 16); // remove t * (a * x^2 + 1) + u ^= G_MOD; + + p1 ^= t ^ (u << 16); // remove t * (a * x^2 + 1) + + u ^= (t >> 1); // form u = a * t + t / a = t * (a + 1 / a); - u ^= (t >> 1); // form u = a * t + t / a = t * (a + 1 / a); - if(t & 0x01) // add the modular polynomial on underflow - + u ^= G_MOD >> 1; p1 ^= (u << 24) | (u << 8); // remove t * (a + 1/a) * (x^3 + x) @@ -445,7 +445,7 @@ void twofish_encrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte o out_blk[0] = LE32(blk[2] ^ l_key[4]); out_blk[1] = LE32(blk[3] ^ l_key[5]); out_blk[2] = LE32(blk[0] ^ l_key[6]); - out_blk[3] = LE32(blk[1] ^ l_key[7]); + out_blk[3] = LE32(blk[1] ^ l_key[7]); }; #else // TC_MINIMIZE_CODE_SIZE @@ -477,7 +477,7 @@ void twofish_encrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte o out_blk[0] = LE32(blk[2] ^ l_key[4]); out_blk[1] = LE32(blk[3] ^ l_key[5]); out_blk[2] = LE32(blk[0] ^ l_key[6]); - out_blk[3] = LE32(blk[1] ^ l_key[7]); + out_blk[3] = LE32(blk[1] ^ l_key[7]); }; #endif // TC_MINIMIZE_CODE_SIZE @@ -511,7 +511,7 @@ void twofish_decrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte o out_blk[0] = LE32(blk[2] ^ l_key[0]); out_blk[1] = LE32(blk[3] ^ l_key[1]); out_blk[2] = LE32(blk[0] ^ l_key[2]); - out_blk[3] = LE32(blk[1] ^ l_key[3]); + out_blk[3] = LE32(blk[1] ^ l_key[3]); }; #else // TC_MINIMIZE_CODE_SIZE @@ -543,7 +543,7 @@ void twofish_decrypt(TwofishInstance *instance, const u4byte in_blk[4], u4byte o out_blk[0] = LE32(blk[2] ^ l_key[0]); out_blk[1] = LE32(blk[3] ^ l_key[1]); out_blk[2] = LE32(blk[0] ^ l_key[2]); - out_blk[3] = LE32(blk[1] ^ l_key[3]); + out_blk[3] = LE32(blk[1] ^ l_key[3]); }; #endif // TC_MINIMIZE_CODE_SIZE diff --git a/src/Crypto/Whirlpool.c b/src/Crypto/Whirlpool.c index c0e5b884..ee109d81 100644 --- a/src/Crypto/Whirlpool.c +++ b/src/Crypto/Whirlpool.c @@ -26,7 +26,7 @@ * ``The Whirlpool hashing function,'' * NESSIE submission, 2000 (tweaked version, 2001), * - * + * * @author Paulo S.L.M. Barreto * @author Vincent Rijmen. * @@ -397,7 +397,7 @@ void WhirlpoolTransform(uint64 *digest, const uint64 *block) AS2( and esp, -16) AS2( sub esp, 16*8) AS_PUSH_IF86( ax) - + #if CRYPTOPP_BOOL_X86 #define SSE2_workspace esp+WORD_SZ #elif CRYPTOPP_BOOL_X32 @@ -722,7 +722,7 @@ void WHIRLPOOL_init(WHIRLPOOL_CTX * const ctx) { */ void WHIRLPOOL_add(const unsigned char * input, unsigned __int32 sourceBits, - WHIRLPOOL_CTX * const ctx) + WHIRLPOOL_CTX * const ctx) { uint64 num, oldCountLo = ctx->countLo, oldCountHi = ctx->countHi; uint64 len = sourceBits >> 3; @@ -734,7 +734,7 @@ void WHIRLPOOL_add(const unsigned char * input, else { uint64* dataBuf = ctx->data; - byte* data = (byte *)dataBuf; + byte* data = (byte *)dataBuf; num = oldCountLo & 63; if (num != 0) // process left over data @@ -786,11 +786,11 @@ void WHIRLPOOL_add(const unsigned char * input, /** * Get the hash value from the hashing state. - * + * * This method uses the invariant: bufferBits < DIGESTBITS */ void WHIRLPOOL_finalize(WHIRLPOOL_CTX * const ctx, - unsigned char * result) + unsigned char * result) { unsigned int num = ctx->countLo & 63; uint64* dataBuf = ctx->data; diff --git a/src/Crypto/cpu.c b/src/Crypto/cpu.c index 4274a8ae..3de87069 100644 --- a/src/Crypto/cpu.c +++ b/src/Crypto/cpu.c @@ -76,7 +76,7 @@ int CpuId(uint32 input, uint32 output[4]) { return 0; } - + // function 0 returns the highest basic function understood in EAX if(input == 0) return !!output[0]? 1 : 0; diff --git a/src/Crypto/cpu.h b/src/Crypto/cpu.h index 7ef509ec..44da8cc3 100644 --- a/src/Crypto/cpu.h +++ b/src/Crypto/cpu.h @@ -36,7 +36,7 @@ extern __m128i _mm_insert_epi32(__m128i dst, int s, const int ndx); #if (defined(__AES__) && defined(__PCLMUL__)) || defined(__INTEL_COMPILER) #ifdef TC_WINDOWS_DRIVER -extern __m128i _mm_clmulepi64_si128(__m128i v1, __m128i v2, +extern __m128i _mm_clmulepi64_si128(__m128i v1, __m128i v2, const int imm8); extern __m128i _mm_aeskeygenassist_si128(__m128i ckey, const int rcon); extern __m128i _mm_aesimc_si128(__m128i v); diff --git a/src/Driver/BuildDriver.cmd b/src/Driver/BuildDriver.cmd index bfeee2db..42f715dc 100644 --- a/src/Driver/BuildDriver.cmd +++ b/src/Driver/BuildDriver.cmd @@ -3,7 +3,7 @@ :: 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) +:: 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 @@ -128,7 +128,7 @@ pushd . set BUILD_ALT_DIR=%TC_BUILD_ALT_DIR% build %TC_BUILD_OPTS% -w -nmake /S -nmake /C 2>build_errors.log 1>&2 - + if errorlevel 1 ( type build_errors.log type build_errors_asm.log 2>NUL: @@ -138,7 +138,7 @@ pushd . ) shift - + goto build_dirs :done popd diff --git a/src/Driver/DriveFilter.c b/src/Driver/DriveFilter.c index c090ee8c..49563592 100644 --- a/src/Driver/DriveFilter.c +++ b/src/Driver/DriveFilter.c @@ -3,7 +3,7 @@ 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) + 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 @@ -167,7 +167,7 @@ NTSTATUS DriveFilterAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo) Extension = (DriveFilterExtension *) filterDeviceObject->DeviceExtension; memset (Extension, 0, sizeof (DriveFilterExtension)); - status = IoAttachDeviceToDeviceStackSafe (filterDeviceObject, pdo, &(Extension->LowerDeviceObject)); + status = IoAttachDeviceToDeviceStackSafe (filterDeviceObject, pdo, &(Extension->LowerDeviceObject)); if (!NT_SUCCESS (status)) { goto err; @@ -182,7 +182,7 @@ NTSTATUS DriveFilterAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo) Extension->IsDriveFilterDevice = Extension->Queue.IsFilterDevice = TRUE; Extension->DeviceObject = Extension->Queue.DeviceObject = filterDeviceObject; Extension->Pdo = pdo; - + Extension->Queue.LowerDeviceObject = Extension->LowerDeviceObject; IoInitializeRemoveLock (&Extension->Queue.RemoveLock, 'LRCV', 0, 0); @@ -215,7 +215,7 @@ static void DismountDrive (DriveFilterExtension *Extension, BOOL stopIoQueue) { Dump ("Dismounting drive\n"); ASSERT (Extension->DriveMounted); - + if (stopIoQueue && EncryptedIoQueueIsRunning (&Extension->Queue)) EncryptedIoQueueStop (&Extension->Queue); @@ -249,7 +249,7 @@ static void ComputeBootLoaderFingerprint(PDEVICE_OBJECT LowerDeviceObject, byte* // TC_BOOT_SECTOR_USER_CONFIG_OFFSET = 438 // // we have: TC_BOOT_SECTOR_USER_MESSAGE_OFFSET = TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_OFFSET + TC_BOOT_SECTOR_OUTER_VOLUME_BAK_HEADER_CRC_SIZE - + WHIRLPOOL_init (&whirlpool); sha512_begin (&sha2); // read the first 512 bytes @@ -362,8 +362,8 @@ static NTSTATUS MountDrive (DriveFilterExtension *Extension, Password *password, if (BootArgs.CryptoInfoLength > 0) { - PHYSICAL_ADDRESS cryptoInfoAddress; - + PHYSICAL_ADDRESS cryptoInfoAddress; + cryptoInfoAddress.QuadPart = (BootLoaderSegment << 4) + BootArgs.CryptoInfoOffset; #ifdef DEBUG Dump ("Wiping memory %x %d\n", cryptoInfoAddress.LowPart, BootArgs.CryptoInfoLength); @@ -389,20 +389,20 @@ static NTSTATUS MountDrive (DriveFilterExtension *Extension, Password *password, // calculate Fingerprint ComputeBootLoaderFingerprint (Extension->LowerDeviceObject, header); - + if (Extension->Queue.CryptoInfo->hiddenVolume) { int64 hiddenPartitionOffset = BootArgs.HiddenSystemPartitionStart; Dump ("Hidden volume start offset = %I64d\n", Extension->Queue.CryptoInfo->EncryptedAreaStart.Value + hiddenPartitionOffset); - + Extension->HiddenSystem = TRUE; Extension->Queue.RemapEncryptedArea = TRUE; Extension->Queue.RemappedAreaOffset = hiddenPartitionOffset + Extension->Queue.CryptoInfo->EncryptedAreaStart.Value - BootArgs.DecoySystemPartitionStart; Extension->Queue.RemappedAreaDataUnitOffset = Extension->Queue.CryptoInfo->EncryptedAreaStart.Value / ENCRYPTION_DATA_UNIT_SIZE - BootArgs.DecoySystemPartitionStart / ENCRYPTION_DATA_UNIT_SIZE; - + Extension->Queue.CryptoInfo->EncryptedAreaStart.Value = BootArgs.DecoySystemPartitionStart; - + if (Extension->Queue.CryptoInfo->VolumeSize.Value > hiddenPartitionOffset - BootArgs.DecoySystemPartitionStart) TC_THROW_FATAL_EXCEPTION; @@ -461,7 +461,7 @@ static NTSTATUS MountDrive (DriveFilterExtension *Extension, Password *password, } status = SendDeviceIoControlRequest (Extension->LowerDeviceObject, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &BootDriveLength, sizeof (BootDriveLength)); - + if (!NT_SUCCESS (status)) { Dump ("Failed to get drive length - error %x\n", status); @@ -470,7 +470,7 @@ static NTSTATUS MountDrive (DriveFilterExtension *Extension, Password *password, } else Extension->Queue.MaxReadAheadOffset = BootDriveLength; - + status = EncryptedIoQueueStart (&Extension->Queue); if (!NT_SUCCESS (status)) TC_BUG_CHECK (status); @@ -526,7 +526,7 @@ static NTSTATUS SaveDriveVolumeHeader (DriveFilterExtension *Extension) Dump ("Saving: ConfiguredEncryptedAreaStart=%I64d (%I64d) ConfiguredEncryptedAreaEnd=%I64d (%I64d)\n", Extension->ConfiguredEncryptedAreaStart / 1024 / 1024, Extension->ConfiguredEncryptedAreaStart, Extension->ConfiguredEncryptedAreaEnd / 1024 / 1024, Extension->ConfiguredEncryptedAreaEnd); Dump ("Saving: EncryptedAreaStart=%I64d (%I64d) EncryptedAreaEnd=%I64d (%I64d)\n", Extension->Queue.EncryptedAreaStart / 1024 / 1024, Extension->Queue.EncryptedAreaStart, Extension->Queue.EncryptedAreaEnd / 1024 / 1024, Extension->Queue.EncryptedAreaEnd); - + if (Extension->Queue.EncryptedAreaStart == -1 || Extension->Queue.EncryptedAreaEnd == -1 || Extension->Queue.EncryptedAreaEnd <= Extension->Queue.EncryptedAreaStart) { @@ -678,7 +678,7 @@ static NTSTATUS OnStartDeviceCompleted (PDEVICE_OBJECT filterDeviceObject, PIRP } KeInitializeEvent (&Extension->MountWorkItemCompletedEvent, SynchronizationEvent, FALSE); - IoQueueWorkItem (workItem, MountDriveWorkItemRoutine, DelayedWorkQueue, Extension); + IoQueueWorkItem (workItem, MountDriveWorkItemRoutine, DelayedWorkQueue, Extension); KeWaitForSingleObject (&Extension->MountWorkItemCompletedEvent, Executive, KernelMode, FALSE, NULL); IoFreeWorkItem (workItem); @@ -817,7 +817,7 @@ NTSTATUS DriveFilterDispatchIrp (PDEVICE_OBJECT DeviceObject, PIRP Irp) if (Extension->BootDrive) { status = EncryptedIoQueueAddIrp (&Extension->Queue, Irp); - + if (status != STATUS_PENDING) TCCompleteDiskIrp (Irp, status, 0); @@ -895,7 +895,7 @@ void ReopenBootVolumeHeader (PIRP irp, PIO_STACK_LOCATION irpSp) { Dump ("Header reopened\n"); ComputeBootLoaderFingerprint (BootDriveFilterExtension->LowerDeviceObject, header); - + BootDriveFilterExtension->Queue.CryptoInfo->header_creation_time = BootDriveFilterExtension->HeaderCryptoInfo->header_creation_time; BootDriveFilterExtension->Queue.CryptoInfo->pkcs5 = BootDriveFilterExtension->HeaderCryptoInfo->pkcs5; BootDriveFilterExtension->Queue.CryptoInfo->noIterations = BootDriveFilterExtension->HeaderCryptoInfo->noIterations; @@ -1025,7 +1025,7 @@ static NTSTATUS HiberDriverWriteFunctionFilter (int filterNumber, PLARGE_INTEGER if (writeB) return (*OriginalHiberDriverWriteFunctionsB[filterNumber]) (writeOffset, encryptedDataMdl); - + return (*OriginalHiberDriverWriteFunctionsA[filterNumber]) (arg0WriteA, writeOffset, encryptedDataMdl, arg3WriteA); } @@ -1269,11 +1269,11 @@ static VOID SetupThreadProc (PVOID threadArg) byte *wipeBuffer = NULL; byte wipeRandChars[TC_WIPE_RAND_CHAR_COUNT]; byte wipeRandCharsUpdate[TC_WIPE_RAND_CHAR_COUNT]; - + KIRQL irql; NTSTATUS status; - // generate real random values for wipeRandChars and + // generate real random values for wipeRandChars and // wipeRandCharsUpdate instead of relying on uninitialized stack memory LARGE_INTEGER iSeed; KeQuerySystemTime( &iSeed ); @@ -1300,7 +1300,7 @@ static VOID SetupThreadProc (PVOID threadArg) burn (digest, SHA512_DIGESTSIZE); burn (&tctx, sizeof (tctx)); } - + burn (&iSeed, sizeof(iSeed)); SetupResult = STATUS_UNSUCCESSFUL; @@ -1376,7 +1376,7 @@ static VOID SetupThreadProc (PVOID threadArg) } EncryptedIoQueueResumeFromHold (&Extension->Queue); - + Dump ("EncryptedAreaStart=%I64d\n", Extension->Queue.EncryptedAreaStart); Dump ("EncryptedAreaEnd=%I64d\n", Extension->Queue.EncryptedAreaEnd); Dump ("ConfiguredEncryptedAreaStart=%I64d\n", Extension->ConfiguredEncryptedAreaStart); @@ -1485,7 +1485,7 @@ static VOID SetupThreadProc (PVOID threadArg) } EncryptDataUnits (wipeBuffer, &dataUnit, setupBlockSize / ENCRYPTION_DATA_UNIT_SIZE, Extension->Queue.CryptoInfo); - memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate)); + memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate)); } status = TCWriteDevice (BootDriveFilterExtension->LowerDeviceObject, wipeBuffer, offset, setupBlockSize); @@ -1500,7 +1500,7 @@ static VOID SetupThreadProc (PVOID threadArg) } } - memcpy (wipeRandChars, wipeRandCharsUpdate, sizeof (wipeRandCharsUpdate)); + memcpy (wipeRandChars, wipeRandCharsUpdate, sizeof (wipeRandCharsUpdate)); } } else @@ -1646,7 +1646,7 @@ NTSTATUS StartBootEncryptionSetup (PDEVICE_OBJECT DeviceObject, PIRP irp, PIO_ST SetupInProgress = TRUE; status = TCStartThread (SetupThreadProc, DeviceObject, &EncryptionSetupThread); - + if (!NT_SUCCESS (status)) SetupInProgress = FALSE; @@ -1742,7 +1742,7 @@ void GetBootEncryptionStatus (PIRP irp, PIO_STACK_LOCATION irpSp) bootEncStatus->HiddenSysLeakProtectionCount = HiddenSysLeakProtectionCount; bootEncStatus->HiddenSystem = Extension->HiddenSystem; - + if (Extension->HiddenSystem) bootEncStatus->HiddenSystemPartitionStart = BootArgs.HiddenSystemPartitionStart; } @@ -1778,7 +1778,7 @@ void GetBootLoaderFingerprint (PIRP irp, PIO_STACK_LOCATION irpSp) irp->IoStatus.Information = 0; if (BootArgsValid && BootDriveFound && BootDriveFilterExtension && BootDriveFilterExtension->DriveMounted && BootDriveFilterExtension->HeaderCryptoInfo) { - BootLoaderFingerprintRequest *bootLoaderFingerprint = (BootLoaderFingerprintRequest *) irp->AssociatedIrp.SystemBuffer; + BootLoaderFingerprintRequest *bootLoaderFingerprint = (BootLoaderFingerprintRequest *) irp->AssociatedIrp.SystemBuffer; /* compute the fingerprint again and check if it is the same as the one retrieved during boot */ char *header = TCalloc (TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE); @@ -1808,7 +1808,7 @@ void GetBootLoaderFingerprint (PIRP irp, PIO_STACK_LOCATION irpSp) } else { - irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + irp->IoStatus.Status = STATUS_INVALID_PARAMETER; } } } @@ -1919,7 +1919,7 @@ static VOID DecoySystemWipeThreadProc (PVOID threadArg) DecoySystemWipeResult = STATUS_INSUFFICIENT_RESOURCES; goto ret; } - + wipeRandBuffer = TCalloc (TC_ENCRYPTION_SETUP_IO_BLOCK_SIZE); if (!wipeRandBuffer) { @@ -1944,7 +1944,7 @@ static VOID DecoySystemWipeThreadProc (PVOID threadArg) } memcpy (wipeCryptoInfo->k2, WipeDecoyRequest.WipeKey + EAGetKeySize (ea), EAGetKeySize (ea)); - + if (!EAInitMode (wipeCryptoInfo)) { DecoySystemWipeResult = STATUS_INVALID_PARAMETER; @@ -1957,7 +1957,7 @@ static VOID DecoySystemWipeThreadProc (PVOID threadArg) burn (WipeDecoyRequest.WipeKey, sizeof (WipeDecoyRequest.WipeKey)); offset.QuadPart = Extension->ConfiguredEncryptedAreaStart; - + Dump ("Wiping decoy system: start offset = %I64d\n", offset.QuadPart); while (!DecoySystemWipeThreadAbortRequested) @@ -2061,7 +2061,7 @@ NTSTATUS StartDecoySystemWipe (PDEVICE_OBJECT DeviceObject, PIRP irp, PIO_STACK_ DecoySystemWipeInProgress = TRUE; status = TCStartThread (DecoySystemWipeThreadProc, DeviceObject, &DecoySystemWipeThread); - + if (!NT_SUCCESS (status)) DecoySystemWipeInProgress = FALSE; @@ -2100,7 +2100,7 @@ void GetDecoySystemWipeStatus (PIRP irp, PIO_STACK_LOCATION irpSp) } else wipeStatus->WipedAreaEnd = DecoySystemWipedAreaEnd; - + irp->IoStatus.Information = sizeof (DecoySystemWipeStatus); irp->IoStatus.Status = STATUS_SUCCESS; } diff --git a/src/Driver/DriveFilter.h b/src/Driver/DriveFilter.h index e0c1bdff..fbbfcac0 100644 --- a/src/Driver/DriveFilter.h +++ b/src/Driver/DriveFilter.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Driver/Driver.rc b/src/Driver/Driver.rc index 51030c5c..a3f177a5 100644 --- a/src/Driver/Driver.rc +++ b/src/Driver/Driver.rc @@ -65,18 +65,18 @@ END // TEXTINCLUDE // -1 TEXTINCLUDE +1 TEXTINCLUDE BEGIN "resource.h\0" END -2 TEXTINCLUDE +2 TEXTINCLUDE BEGIN "#include ""afxres.h""\r\n" "\0" END -3 TEXTINCLUDE +3 TEXTINCLUDE BEGIN "\r\n" "\0" diff --git a/src/Driver/DumpFilter.c b/src/Driver/DumpFilter.c index d67b1654..ce3365d5 100644 --- a/src/Driver/DumpFilter.c +++ b/src/Driver/DumpFilter.c @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Driver/DumpFilter.h b/src/Driver/DumpFilter.h index ea6599a5..7582e939 100644 --- a/src/Driver/DumpFilter.h +++ b/src/Driver/DumpFilter.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Driver/EncryptedIoQueue.c b/src/Driver/EncryptedIoQueue.c index 637f8504..029a42f5 100644 --- a/src/Driver/EncryptedIoQueue.c +++ b/src/Driver/EncryptedIoQueue.c @@ -3,7 +3,7 @@ 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) + 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 @@ -112,7 +112,7 @@ static void ReleasePoolBuffer (EncryptedIoQueue *queue, void *address) { EncryptedIoQueueBuffer *buffer; AcquireBufferPoolMutex (queue); - + for (buffer = queue->FirstPoolBuffer; buffer != NULL; buffer = buffer->NextBuffer) { if (buffer->Address == address) @@ -329,7 +329,7 @@ static VOID IoThreadProc (PVOID threadArg) { InterlockedDecrement (&queue->IoThreadPendingRequestCount); request = CONTAINING_RECORD (listEntry, EncryptedIoRequest, ListEntry); - + #ifdef TC_TRACE_IO_QUEUE Dump ("%c %I64d [%I64d] roff=%I64d rlen=%d\n", request->Item->Write ? 'W' : 'R', request->Item->OriginalIrpOffset.QuadPart, GetElapsedTime (&queue->LastPerformanceCounter), request->Offset.QuadPart, request->Length); #endif @@ -512,7 +512,7 @@ static VOID MainThreadProc (PVOID threadArg) { PIRP irp = CONTAINING_RECORD (listEntry, IRP, Tail.Overlay.ListEntry); PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (irp); - + if (queue->Suspended) KeWaitForSingleObject (&queue->QueueResumedEvent, Executive, KernelMode, FALSE, NULL); @@ -622,7 +622,7 @@ static VOID MainThreadProc (PVOID threadArg) if (item->OriginalLength == 0 || (item->OriginalLength & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0 || (item->OriginalOffset.QuadPart & (ENCRYPTION_DATA_UNIT_SIZE - 1)) != 0 - || ( !queue->IsFilterDevice && + || ( !queue->IsFilterDevice && ( (S_OK != ULongLongAdd(item->OriginalOffset.QuadPart, item->OriginalLength, &addResult)) || (addResult > (ULONGLONG) queue->VirtualDeviceLength) ) @@ -643,7 +643,7 @@ static VOID MainThreadProc (PVOID threadArg) if (queue->CryptoInfo->hiddenVolume) hResult = ULongLongAdd(item->OriginalOffset.QuadPart, queue->CryptoInfo->hiddenVolumeOffset, &addResult); else - hResult = ULongLongAdd(item->OriginalOffset.QuadPart, queue->CryptoInfo->volDataAreaOffset, &addResult); + hResult = ULongLongAdd(item->OriginalOffset.QuadPart, queue->CryptoInfo->volDataAreaOffset, &addResult); if (hResult != S_OK) { @@ -658,7 +658,7 @@ static VOID MainThreadProc (PVOID threadArg) { // If there has already been a write operation denied in order to protect the // hidden volume (since the volume mount time) - if (queue->CryptoInfo->bHiddenVolProtectionAction) + if (queue->CryptoInfo->bHiddenVolProtectionAction) { // Do not allow writing to this volume anymore. This is to fake a complete volume // or system failure (otherwise certain kinds of inconsistency within the file @@ -715,7 +715,7 @@ static VOID MainThreadProc (PVOID threadArg) while (dataRemaining > 0) { BOOL isLastFragment = dataRemaining <= TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; - + ULONG dataFragmentLength = isLastFragment ? dataRemaining : TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; activeFragmentBuffer = (activeFragmentBuffer == queue->FragmentBufferA ? queue->FragmentBufferB : queue->FragmentBufferA); @@ -774,7 +774,7 @@ static VOID MainThreadProc (PVOID threadArg) dataUnit.Value += queue->CryptoInfo->FirstDataUnitNo.Value; else if (queue->RemapEncryptedArea) dataUnit.Value += queue->RemappedAreaDataUnitOffset; - + EncryptDataUnits (activeFragmentBuffer + request->EncryptedOffset, &dataUnit, request->EncryptedLength / ENCRYPTION_DATA_UNIT_SIZE, queue->CryptoInfo); } } @@ -824,7 +824,7 @@ NTSTATUS EncryptedIoQueueAddIrp (EncryptedIoQueue *queue, PIRP irp) ExInterlockedInsertTailList (&queue->MainThreadQueue, &irp->Tail.Overlay.ListEntry, &queue->MainThreadQueueLock); KeSetEvent (&queue->MainThreadQueueNotEmptyEvent, IO_DISK_INCREMENT, FALSE); - + return STATUS_PENDING; err: @@ -839,7 +839,7 @@ NTSTATUS EncryptedIoQueueHoldWhenIdle (EncryptedIoQueue *queue, int64 timeout) ASSERT (!queue->Suspended); queue->SuspendPending = TRUE; - + while (TRUE) { while (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) > 0) @@ -898,7 +898,7 @@ BOOL EncryptedIoQueueIsRunning (EncryptedIoQueue *queue) NTSTATUS EncryptedIoQueueResumeFromHold (EncryptedIoQueue *queue) { ASSERT (queue->Suspended); - + queue->Suspended = FALSE; KeSetEvent (&queue->QueueResumedEvent, IO_DISK_INCREMENT, FALSE); @@ -1024,7 +1024,7 @@ NTSTATUS EncryptedIoQueueStop (EncryptedIoQueue *queue) { ASSERT (!queue->StopPending); queue->StopPending = TRUE; - + while (InterlockedExchangeAdd (&queue->OutstandingIoCount, 0) > 0) { KeWaitForSingleObject (&queue->NoOutstandingIoEvent, Executive, KernelMode, FALSE, NULL); diff --git a/src/Driver/EncryptedIoQueue.h b/src/Driver/EncryptedIoQueue.h index 044009b7..ffe71471 100644 --- a/src/Driver/EncryptedIoQueue.h +++ b/src/Driver/EncryptedIoQueue.h @@ -3,7 +3,7 @@ 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) + 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 @@ -40,12 +40,12 @@ typedef struct EncryptedIoQueueBufferStruct typedef struct { PDEVICE_OBJECT DeviceObject; - + KMUTEX BufferPoolMutex; EncryptedIoQueueBuffer *FirstPoolBuffer; CRYPTO_INFO *CryptoInfo; - + // File-handle-based IO HANDLE HostFileHandle; int64 VirtualDeviceLength; @@ -106,7 +106,7 @@ typedef struct volatile BOOL StartPending; volatile BOOL ThreadExitRequested; - + volatile BOOL Suspended; volatile BOOL SuspendPending; volatile BOOL StopPending; diff --git a/src/Driver/Fuse/Driver.make b/src/Driver/Fuse/Driver.make index 61e57577..169d0354 100644 --- a/src/Driver/Fuse/Driver.make +++ b/src/Driver/Fuse/Driver.make @@ -3,7 +3,7 @@ # 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) +# 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 diff --git a/src/Driver/Fuse/FuseService.cpp b/src/Driver/Fuse/FuseService.cpp index bf0fad8e..97316532 100644 --- a/src/Driver/Fuse/FuseService.cpp +++ b/src/Driver/Fuse/FuseService.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -320,7 +320,7 @@ namespace VeraCrypt { return fuse_get_context()->uid == 0 || fuse_get_context()->uid == UserId; } - + void FuseService::CloseMountedVolume () { if (MountedVolume) @@ -403,7 +403,7 @@ namespace VeraCrypt return outBuf; } - + const char *FuseService::GetVolumeImagePath () { #ifdef TC_MACOSX @@ -439,7 +439,7 @@ namespace VeraCrypt args.push_back ("-o"); args.push_back ("allow_other"); } - + ExecFunctor execFunctor (openVolume, slotNumber); Process::Execute ("fuse", args, -1, &execFunctor); @@ -498,13 +498,13 @@ namespace VeraCrypt MountedVolume->WriteSectors (buffer, byteOffset); } - + void FuseService::OnSignal (int signal) { try { shared_ptr volume = Core->GetMountedVolume (SlotNumber); - + if (volume) Core->DismountVolume (volume, true); } diff --git a/src/Driver/Fuse/FuseService.h b/src/Driver/Fuse/FuseService.h index 0c3a6920..0498a42a 100644 --- a/src/Driver/Fuse/FuseService.h +++ b/src/Driver/Fuse/FuseService.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Driver/Ntdriver.c b/src/Driver/Ntdriver.c index c771b3ce..9b683f9b 100644 --- a/src/Driver/Ntdriver.c +++ b/src/Driver/Ntdriver.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -89,7 +89,7 @@ NTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) SelfTestsPassed = AutoTestAlgorithms(); // Enable device class filters and load boot arguments if the driver is set to start at system boot - + if (NT_SUCCESS (TCReadRegistryKey (RegistryPath, L"Start", &startKeyValue))) { if (startKeyValue->Type == REG_DWORD && *((uint32 *) startKeyValue->Data) == SERVICE_BOOT_START) @@ -156,7 +156,7 @@ void DumpMemory (void *mem, int size) for (j = 0; j < size / 8; j++) { memset (str,0,sizeof str); - for (i = 0; i < 8; i++) + for (i = 0; i < 8; i++) { if (m[i] > ' ' && m[i] <= '~') str[i]=m[i]; @@ -330,10 +330,10 @@ NTSTATUS TCDispatchQueueIRP (PDEVICE_OBJECT DeviceObject, PIRP Irp) return TCCompleteIrp (Irp, ntStatus, 0); IoMarkIrpPending (Irp); - + ExInterlockedInsertTailList (&Extension->ListEntry, &Irp->Tail.Overlay.ListEntry, &Extension->ListSpinLock); KeReleaseSemaphore (&Extension->RequestSemaphore, IO_DISK_INCREMENT, 1, FALSE); - + return STATUS_PENDING; case IRP_MJ_FLUSH_BUFFERS: @@ -375,7 +375,7 @@ NTSTATUS TCCreateRootDeviceObject (PDRIVER_OBJECT DriverObject) RtlInitUnicodeString (&Win32NameString, dosname); Dump ("Creating root device nt=%ls dos=%ls\n", ntname, dosname); - + ntStatus = IoCreateDevice ( DriverObject, sizeof (BOOL), @@ -559,10 +559,10 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION UCHAR volId[128], tmp[] = { 0,0 }; PMOUNTDEV_UNIQUE_ID outputBuffer = (PMOUNTDEV_UNIQUE_ID) Irp->AssociatedIrp.SystemBuffer; - RtlStringCbCopyA (volId, sizeof(volId),TC_UNIQUE_ID_PREFIX); + RtlStringCbCopyA (volId, sizeof(volId),TC_UNIQUE_ID_PREFIX); tmp[0] = 'A' + (UCHAR) Extension->nDosDriveNo; RtlStringCbCatA (volId, sizeof(volId),tmp); - + outputBuffer->UniqueIdLength = (USHORT) strlen (volId); outLength = (ULONG) (strlen (volId) + sizeof (USHORT)); @@ -593,7 +593,7 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION { Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; - break; + break; } TCGetDosNameFromNumber (ntName, sizeof(ntName),Extension->nDosDriveNo, DeviceNamespaceDefault); @@ -612,7 +612,7 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION } RtlCopyMemory ((PCHAR)outputBuffer->Name,ntUnicodeString.Buffer, ntUnicodeString.Length); - + Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = outLength; @@ -643,7 +643,7 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION if (EnableExtendedIoctlSupport) { if (ValidateIOBufferSize (Irp, sizeof (STORAGE_PROPERTY_QUERY), ValidateInput)) - { + { PSTORAGE_PROPERTY_QUERY pStoragePropQuery = (PSTORAGE_PROPERTY_QUERY) Irp->AssociatedIrp.SystemBuffer; STORAGE_QUERY_TYPE type = pStoragePropQuery->QueryType; @@ -702,7 +702,7 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION } else return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); - + break; case IOCTL_DISK_GET_PARTITION_INFO: @@ -783,13 +783,13 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION if (ValidateIOBufferSize (Irp, sizeof (VERIFY_INFORMATION), ValidateInput)) { HRESULT hResult; - ULONGLONG ullStartingOffset, ullNewOffset, ullEndOffset; + ULONGLONG ullStartingOffset, ullNewOffset, ullEndOffset; PVERIFY_INFORMATION pVerifyInformation; pVerifyInformation = (PVERIFY_INFORMATION) Irp->AssociatedIrp.SystemBuffer; ullStartingOffset = (ULONGLONG) pVerifyInformation->StartingOffset.QuadPart; - hResult = ULongLongAdd(ullStartingOffset, - (ULONGLONG) Extension->cryptoInfo->hiddenVolume ? Extension->cryptoInfo->hiddenVolumeOffset : Extension->cryptoInfo->volDataAreaOffset, + hResult = ULongLongAdd(ullStartingOffset, + (ULONGLONG) Extension->cryptoInfo->hiddenVolume ? Extension->cryptoInfo->hiddenVolumeOffset : Extension->cryptoInfo->volDataAreaOffset, &ullNewOffset); if (hResult != S_OK) Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; @@ -801,7 +801,7 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION { IO_STATUS_BLOCK ioStatus; PVOID buffer = TCalloc (max (pVerifyInformation->Length, PAGE_SIZE)); - + if (!buffer) { Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; @@ -847,7 +847,7 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION } break; - + case IOCTL_VOLUME_ONLINE: Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; @@ -1054,7 +1054,7 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex // Go through all volume types (e.g., normal, hidden) for (volumeType = TC_VOLUME_TYPE_NORMAL; volumeType < TC_VOLUME_TYPE_COUNT; - volumeType++) + volumeType++) { /* Read the volume header */ switch (volumeType) @@ -1121,7 +1121,7 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex IO_STATUS_BLOCK IoStatus; LARGE_INTEGER offset; byte readBuffer [TC_SECTOR_SIZE_BIOS]; - + if (!ValidateIOBufferSize (Irp, sizeof (GetSystemDriveConfigurationRequest), ValidateInputOutput)) break; @@ -1254,7 +1254,7 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) { PEXTENSION ListExtension; - + ListDevice = GetVirtualVolumeDeviceObject (drive); if (!ListDevice) continue; @@ -1500,9 +1500,9 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex MOUNT_STRUCT *mount = (MOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; if (mount->VolumePassword.Length > MAX_PASSWORD || mount->ProtectedHidVolPassword.Length > MAX_PASSWORD - || mount->pkcs5_prf < 0 || mount->pkcs5_prf > LAST_PRF_ID + || mount->pkcs5_prf < 0 || mount->pkcs5_prf > LAST_PRF_ID || mount->VolumePim < -1 || mount->VolumePim == INT_MAX - || mount->ProtectedHidVolPkcs5Prf < 0 || mount->ProtectedHidVolPkcs5Prf > LAST_PRF_ID + || mount->ProtectedHidVolPkcs5Prf < 0 || mount->ProtectedHidVolPkcs5Prf > LAST_PRF_ID || (mount->bTrueCryptMode != FALSE && mount->bTrueCryptMode != TRUE) ) { @@ -1690,7 +1690,7 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); } - + #ifdef DEBUG if (!NT_SUCCESS (Irp->IoStatus.Status)) { @@ -1739,7 +1739,7 @@ NTSTATUS TCStartThreadInProcess (PKSTART_ROUTINE threadProc, PVOID threadArg, PK } InitializeObjectAttributes (&threadObjAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); - + status = PsCreateSystemThread (&threadHandle, THREAD_ALL_ACCESS, &threadObjAttributes, processHandle, NULL, threadProc, threadArg); if (!NT_SUCCESS (status)) return status; @@ -2255,7 +2255,7 @@ void TCDeleteDeviceObject (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension) PsDereferenceImpersonationTokenD = MmGetSystemRoutineAddress (&name); if (!PsDereferenceImpersonationTokenD) TC_BUG_CHECK (STATUS_NOT_IMPLEMENTED); - + # define PsDereferencePrimaryToken # define PsDereferenceImpersonationToken PsDereferenceImpersonationTokenD @@ -2390,11 +2390,11 @@ NTSTATUS SendDeviceIoControlRequest (PDEVICE_OBJECT deviceObject, ULONG ioContro args.outputBufferSize = outputBufferSize; KeInitializeEvent (&args.WorkItemCompletedEvent, SynchronizationEvent, FALSE); - IoQueueWorkItem (workItem, SendDeviceIoControlRequestWorkItemRoutine, DelayedWorkQueue, &args); + IoQueueWorkItem (workItem, SendDeviceIoControlRequestWorkItemRoutine, DelayedWorkQueue, &args); KeWaitForSingleObject (&args.WorkItemCompletedEvent, Executive, KernelMode, FALSE, NULL); IoFreeWorkItem (workItem); - + return args.Status; } @@ -2449,7 +2449,7 @@ NTSTATUS ProbeRealDriveSize (PDEVICE_OBJECT driveDeviceObject, LARGE_INTEGER *dr for (offset.QuadPart = sysLength.QuadPart; ; offset.QuadPart += TC_SECTOR_SIZE_BIOS) { status = TCReadDevice (driveDeviceObject, sectorBuffer, offset, TC_SECTOR_SIZE_BIOS); - + if (NT_SUCCESS (status)) status = TCWriteDevice (driveDeviceObject, sectorBuffer, offset, TC_SECTOR_SIZE_BIOS); @@ -2587,7 +2587,7 @@ NTSTATUS TCFsctlCall (PFILE_OBJECT fileObject, LONG IoControlCode, return STATUS_INSUFFICIENT_RESOURCES; stack = IoGetNextIrpStackLocation(irp); - + stack->MajorFunction = IRP_MJ_FILE_SYSTEM_CONTROL; stack->MinorFunction = IRP_MN_USER_FS_REQUEST; stack->FileObject = fileObject; @@ -2638,7 +2638,7 @@ NTSTATUS RemoveDriveLink (int nDosDriveNo) NTSTATUS MountManagerMount (MOUNT_STRUCT *mount) { - NTSTATUS ntStatus; + NTSTATUS ntStatus; WCHAR arrVolume[256]; char buf[200]; PMOUNTMGR_TARGET_NAME in = (PMOUNTMGR_TARGET_NAME) buf; @@ -2670,7 +2670,7 @@ NTSTATUS MountManagerMount (MOUNT_STRUCT *mount) NTSTATUS MountManagerUnmount (int nDosDriveNo) { - NTSTATUS ntStatus; + NTSTATUS ntStatus; char buf[256], out[300]; PMOUNTMGR_MOUNT_POINT in = (PMOUNTMGR_MOUNT_POINT) buf; @@ -2694,10 +2694,10 @@ NTSTATUS MountManagerUnmount (int nDosDriveNo) NTSTATUS MountDevice (PDEVICE_OBJECT DeviceObject, MOUNT_STRUCT *mount) { PDEVICE_OBJECT NewDeviceObject; - NTSTATUS ntStatus; + NTSTATUS ntStatus; // Make sure the user is asking for a reasonable nDosDriveNo - if (mount->nDosDriveNo >= 0 && mount->nDosDriveNo <= 25 + if (mount->nDosDriveNo >= 0 && mount->nDosDriveNo <= 25 && IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceDefault) // drive letter must not exist both locally and globally && IsDriveLetterAvailable (mount->nDosDriveNo, DeviceNamespaceGlobal) ) @@ -2868,7 +2868,7 @@ NTSTATUS MountDevice (PDEVICE_OBJECT DeviceObject, MOUNT_STRUCT *mount) FILE_FS_LABEL_INFORMATION* labelInfo = (FILE_FS_LABEL_INFORMATION*) TCalloc (labelInfoSize); labelInfo->VolumeLabelLength = labelEffectiveLen * sizeof(WCHAR); memcpy (labelInfo->VolumeLabel, mount->wszLabel, labelInfo->VolumeLabelLength); - + if (STATUS_SUCCESS == ZwSetVolumeInformationFile (volumeHandle, &ioblock, labelInfo, labelInfoSize, FileFsLabelInformation)) { mount->bDriverSetLabel = TRUE; @@ -2891,7 +2891,7 @@ NTSTATUS MountDevice (PDEVICE_OBJECT DeviceObject, MOUNT_STRUCT *mount) Dump ("Mount FAILURE TC code = 0x%08x\n", mount->nReturnCode); TCDeleteDeviceObject (NewDeviceObject, NewExtension); } - + return STATUS_SUCCESS; } } @@ -2949,7 +2949,7 @@ NTSTATUS UnmountDevice (UNMOUNT_STRUCT *unmountRequest, PDEVICE_OBJECT deviceObj TCSleep (100); } } - else + else { // Volume cannot be opened => force dismount if allowed if (!ignoreOpenFiles) @@ -3084,10 +3084,10 @@ void GetIntersection (uint64 start1, uint32 length1, uint64 start2, uint64 end2, { uint64 end1 = start1 + length1 - 1; uint64 intersectEnd = (end1 <= end2) ? end1 : end2; - + *intersectStart = (start1 >= start2) ? start1 : start2; *intersectLength = (uint32) ((*intersectStart > intersectEnd) ? 0 : intersectEnd + 1 - *intersectStart); - + if (*intersectLength == 0) *intersectStart = start1; } @@ -3103,7 +3103,7 @@ BOOL IsAccessibleByUser (PUNICODE_STRING objectFileName, BOOL readOnly) ASSERT (!IoIsSystemThread (PsGetCurrentThread())); InitializeObjectAttributes (&fileObjAttributes, objectFileName, OBJ_CASE_INSENSITIVE | OBJ_FORCE_ACCESS_CHECK | OBJ_KERNEL_HANDLE, NULL, NULL); - + status = ZwCreateFile (&fileHandle, readOnly ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE, &fileObjAttributes, @@ -3243,7 +3243,7 @@ NTSTATUS TCReadRegistryKey (PUNICODE_STRING keyPath, wchar_t *keyValueName, PKEY RtlInitUnicodeString (&valName, keyValueName); status = ZwQueryValueKey (regKeyHandle, &valName, KeyValuePartialInformation, NULL, 0, &size); - + if (!NT_SUCCESS (status) && status != STATUS_BUFFER_OVERFLOW && status != STATUS_BUFFER_TOO_SMALL) { ZwClose (regKeyHandle); @@ -3356,7 +3356,7 @@ NTSTATUS ReadRegistryConfigFlags (BOOL driverEntry) } EnableHwEncryption ((flags & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? FALSE : TRUE); - + EnableExtendedIoctlSupport = (flags & TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL)? TRUE : FALSE; } else @@ -3495,7 +3495,7 @@ BOOL IsVolumeAccessibleByCurrentUser (PEXTENSION volumeDeviceExtension) if (!accessToken) goto ret; - + if (SeTokenIsAdmin (accessToken)) { result = TRUE; diff --git a/src/Driver/Ntdriver.h b/src/Driver/Ntdriver.h index d5d548e8..2c5f13da 100644 --- a/src/Driver/Ntdriver.h +++ b/src/Driver/Ntdriver.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -54,7 +54,7 @@ typedef struct EXTENSION CRYPTO_INFO *cryptoInfo; /* Cryptographic and other information for this device */ __int64 HostLength; - __int64 DiskLength; /* The length of the disk referred to by this device */ + __int64 DiskLength; /* The length of the disk referred to by this device */ __int64 NumberOfCylinders; /* Partition info */ ULONG TracksPerCylinder; /* Partition info */ ULONG SectorsPerTrack; /* Partition info */ diff --git a/src/Driver/Ntvol.c b/src/Driver/Ntvol.c index 34ee2dbb..cfcc45e6 100644 --- a/src/Driver/Ntvol.c +++ b/src/Driver/Ntvol.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -82,7 +82,7 @@ NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, PARTITION_INFORMATION pi; PARTITION_INFORMATION_EX pix; LARGE_INTEGER diskLengthInfo; - DISK_GEOMETRY dg; + DISK_GEOMETRY dg; STORAGE_PROPERTY_QUERY storagePropertyQuery = {0}; STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR storageDescriptor = {0}; @@ -105,8 +105,8 @@ NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, storagePropertyQuery.QueryType = PropertyStandardQuery; /* IOCTL_STORAGE_QUERY_PROPERTY supported only on Vista and above */ - if (NT_SUCCESS (TCSendHostDeviceIoControlRequestEx (DeviceObject, Extension, IOCTL_STORAGE_QUERY_PROPERTY, - (char*) &storagePropertyQuery, sizeof(storagePropertyQuery), + if (NT_SUCCESS (TCSendHostDeviceIoControlRequestEx (DeviceObject, Extension, IOCTL_STORAGE_QUERY_PROPERTY, + (char*) &storagePropertyQuery, sizeof(storagePropertyQuery), (char *) &storageDescriptor, sizeof (storageDescriptor)))) { Extension->HostBytesPerPhysicalSector = storageDescriptor.BytesPerPhysicalSector; @@ -300,8 +300,8 @@ NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, } else { - // Try to gain "raw" access to the partition in case there is a live filesystem on it (otherwise, - // the NTFS driver guards hidden sectors and prevents mounting using a backup header e.g. after the user + // Try to gain "raw" access to the partition in case there is a live filesystem on it (otherwise, + // the NTFS driver guards hidden sectors and prevents mounting using a backup header e.g. after the user // accidentally quick-formats a dismounted partition-hosted TrueCrypt volume as NTFS). PFILE_OBJECT pfoTmpDeviceFile = NULL; @@ -335,7 +335,7 @@ NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, // Go through all volume types (e.g., normal, hidden) for (volumeType = TC_VOLUME_TYPE_NORMAL; volumeType < TC_VOLUME_TYPE_COUNT; - volumeType++) + volumeType++) { Dump ("Trying to open volume type %d\n", volumeType); @@ -451,7 +451,7 @@ NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, Dump ("Read didn't read enough data\n"); // If FSCTL_ALLOW_EXTENDED_DASD_IO failed and there is a live filesystem on the partition, then the - // filesystem driver may report EOF when we are reading hidden sectors (when the filesystem is + // filesystem driver may report EOF when we are reading hidden sectors (when the filesystem is // shorter than the partition). This can happen for example after the user quick-formats a dismounted // partition-hosted TrueCrypt volume and then tries to mount the volume using the embedded backup header. memset (readBuffer, 0, TC_VOLUME_HEADER_EFFECTIVE_SIZE); @@ -610,7 +610,7 @@ NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, } // If we are supposed to actually mount the hidden volume (not just to protect it) - if (!mount->bProtectHiddenVolume) + if (!mount->bProtectHiddenVolume) { Extension->DiskLength = cryptoInfoPtr->hiddenVolumeSize; Extension->cryptoInfo->hiddenVolume = TRUE; @@ -621,7 +621,7 @@ NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, // Hidden volume protection Extension->cryptoInfo->hiddenVolume = FALSE; Extension->cryptoInfo->bProtectHiddenVolume = TRUE; - + Extension->cryptoInfo->hiddenVolumeProtectedSize = tmpCryptoInfo->hiddenVolumeSize; Dump ("Hidden volume protection active: %I64d-%I64d (%I64d)\n", Extension->cryptoInfo->hiddenVolumeOffset, Extension->cryptoInfo->hiddenVolumeProtectedSize + Extension->cryptoInfo->hiddenVolumeOffset - 1, Extension->cryptoInfo->hiddenVolumeProtectedSize); @@ -642,7 +642,7 @@ NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, // If this is a hidden volume, make sure we are supposed to actually // mount it (i.e. not just to protect it) - if (volumeType == TC_VOLUME_TYPE_NORMAL || !mount->bProtectHiddenVolume) + if (volumeType == TC_VOLUME_TYPE_NORMAL || !mount->bProtectHiddenVolume) { // Validate sector size if (bRawDevice && Extension->cryptoInfo->SectorSize != Extension->HostBytesPerSector) @@ -660,7 +660,7 @@ NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, Extension->PartitionType = 0; Extension->bRawDevice = bRawDevice; - + memset (Extension->wszVolume, 0, sizeof (Extension->wszVolume)); if (wcsstr (pwszMountVolume, WIDE ("\\??\\UNC\\")) == pwszMountVolume) { @@ -690,7 +690,7 @@ NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, crypto_close (tmpCryptoInfo); tmpCryptoInfo = NULL; } - + return STATUS_SUCCESS; } } @@ -698,7 +698,7 @@ NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject, || mount->nReturnCode != ERR_PASSWORD_WRONG) { /* If we are not supposed to protect a hidden volume, the only error that is - tolerated is ERR_PASSWORD_WRONG (to allow mounting a possible hidden volume). + tolerated is ERR_PASSWORD_WRONG (to allow mounting a possible hidden volume). If we _are_ supposed to protect a hidden volume, we do not tolerate any error (both volume headers must be successfully decrypted). */ @@ -863,8 +863,8 @@ static void RestoreTimeStamp (PEXTENSION Extension) FILE_BASIC_INFORMATION FileBasicInfo; IO_STATUS_BLOCK IoStatusBlock; - if (Extension->hDeviceFile != NULL - && Extension->bRawDevice == FALSE + if (Extension->hDeviceFile != NULL + && Extension->bRawDevice == FALSE && Extension->bReadOnly == FALSE && Extension->bTimeStampValid) { @@ -872,7 +872,7 @@ static void RestoreTimeStamp (PEXTENSION Extension) &IoStatusBlock, &FileBasicInfo, sizeof (FileBasicInfo), - FileBasicInformation); + FileBasicInformation); if (!NT_SUCCESS (ntStatus)) { @@ -891,7 +891,7 @@ static void RestoreTimeStamp (PEXTENSION Extension) &IoStatusBlock, &FileBasicInfo, sizeof (FileBasicInfo), - FileBasicInformation); + FileBasicInformation); if (!NT_SUCCESS (ntStatus)) Dump ("ZwSetInformationFile failed in RestoreTimeStamp: NTSTATUS 0x%08x\n",ntStatus); diff --git a/src/Driver/Ntvol.h b/src/Driver/Ntvol.h index 912c02b0..ae7d9cb3 100644 --- a/src/Driver/Ntvol.h +++ b/src/Driver/Ntvol.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Driver/Resource.h b/src/Driver/Resource.h index a3e73646..ea7f5c74 100644 --- a/src/Driver/Resource.h +++ b/src/Driver/Resource.h @@ -4,7 +4,7 @@ // // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 diff --git a/src/Driver/VolumeFilter.c b/src/Driver/VolumeFilter.c index 8cb675f6..50ac74da 100644 --- a/src/Driver/VolumeFilter.c +++ b/src/Driver/VolumeFilter.c @@ -3,7 +3,7 @@ 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) + 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 @@ -57,7 +57,7 @@ NTSTATUS VolumeFilterAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo) status = STATUS_DEVICE_REMOVED; goto err; } - + Extension->IsVolumeFilterDevice = TRUE; Extension->DeviceObject = filterDeviceObject; Extension->Pdo = pdo; diff --git a/src/Driver/VolumeFilter.h b/src/Driver/VolumeFilter.h index be0cbd0b..b73b4f48 100644 --- a/src/Driver/VolumeFilter.h +++ b/src/Driver/VolumeFilter.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/ExpandVolume/DlgExpandVolume.cpp b/src/ExpandVolume/DlgExpandVolume.cpp index e08721b3..d0a98fef 100644 --- a/src/ExpandVolume/DlgExpandVolume.cpp +++ b/src/ExpandVolume/DlgExpandVolume.cpp @@ -1,14 +1,14 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' + and which is governed by the 'License Agreement for Encryption for the Masses' and also from the source code of extcv, which is Copyright (c) 2009-2010 Kih-Oskh or Copyright (c) 2012-2013 Josef Schneider - Modifications and additions to the original source code (contained in this file) + 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 @@ -198,7 +198,7 @@ BOOL CALLBACK ExpandVolSizeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARA pVolExpandParam->bInitFreeSpace = IsButtonChecked (GetDlgItem (hwndDlg, IDC_INIT_NEWSPACE)); if (!pVolExpandParam->bIsDevice) // for devices new size is set by calling function - { + { GetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTemp, ARRAYSIZE (szTemp)); pVolExpandParam->newSize = _wtoi64(szTemp) * GetSizeBoxMultiplier(hwndDlg); } @@ -349,7 +349,7 @@ BOOL CALLBACK ExpandVolProgressDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, L ProcessEntropyEstimate (hEntropyBar, &mouseEventsInitialCount, mouseEventsCounter, maxEntropyLevel, &mouseEntropyGathered); if (showRandPool) - StringCbPrintfW (szRndPool, sizeof(szRndPool), L"%08X%08X%08X%08X", + StringCbPrintfW (szRndPool, sizeof(szRndPool), L"%08X%08X%08X%08X", *((DWORD*) (randPool + 12)), *((DWORD*) (randPool + 8)), *((DWORD*) (randPool + 4)), *((DWORD*) (randPool))); else if (bUseMask) { @@ -585,11 +585,11 @@ void ExpandVolumeWizard (HWND hwndDlg, wchar_t *lpszVolume) { bIsDevice = expandVol.IsDevice; bIsLegacy = expandVol.CryptoInfo->LegacyVolume; - hostSize = expandVol.HostSize; + hostSize = expandVol.HostSize; VolumePkcs5 = expandVol.CryptoInfo->pkcs5; if ( bIsLegacy ) { - if ( bIsDevice ) + if ( bIsDevice ) volSize = 0; // updated later else volSize = hostSize; @@ -629,7 +629,7 @@ void ExpandVolumeWizard (HWND hwndDlg, wchar_t *lpszVolume) { uint64 NumberOfSectors; DWORD BytesPerSector; - + if ( !GetNtfsNumberOfSectors(rootPath, &NumberOfSectors, &BytesPerSector) ) nStatus = ERR_OS_ERROR; diff --git a/src/ExpandVolume/ExpandVolume.c b/src/ExpandVolume/ExpandVolume.c index 9deb3af4..abe09557 100644 --- a/src/ExpandVolume/ExpandVolume.c +++ b/src/ExpandVolume/ExpandVolume.c @@ -1,14 +1,14 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' + and which is governed by the 'License Agreement for Encryption for the Masses' and also from the source code of extcv, which is Copyright (c) 2009-2010 Kih-Oskh or Copyright (c) 2012-2013 Josef Schneider - Modifications and additions to the original source code (contained in this file) + 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 @@ -860,7 +860,7 @@ static int ExpandVolume (HWND hwndDlg, wchar_t *lpszVolume, Password *pVolumePas /* wipe old backup header */ if ( !cryptoInfo->LegacyVolume ) - { + { byte wipeRandChars [TC_WIPE_RAND_CHAR_COUNT]; byte wipeRandCharsUpdate [TC_WIPE_RAND_CHAR_COUNT]; byte wipePass; diff --git a/src/ExpandVolume/ExpandVolume.h b/src/ExpandVolume/ExpandVolume.h index 87f0e42d..8a9ace64 100644 --- a/src/ExpandVolume/ExpandVolume.h +++ b/src/ExpandVolume/ExpandVolume.h @@ -1,14 +1,14 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' + and which is governed by the 'License Agreement for Encryption for the Masses' and also from the source code of extcv, which is Copyright (c) 2009-2010 Kih-Oskh or Copyright (c) 2012-2013 Josef Schneider - Modifications and additions to the original source code (contained in this file) + 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 diff --git a/src/ExpandVolume/ExpandVolume.rc b/src/ExpandVolume/ExpandVolume.rc index 31f71d95..6659d0f3 100644 --- a/src/ExpandVolume/ExpandVolume.rc +++ b/src/ExpandVolume/ExpandVolume.rc @@ -141,7 +141,7 @@ END // #ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO +GUIDELINES DESIGNINFO BEGIN IDD_SIZE_DIALOG, DIALOG BEGIN @@ -230,19 +230,19 @@ END // TEXTINCLUDE // -1 TEXTINCLUDE +1 TEXTINCLUDE BEGIN "resource.h\0" END -2 TEXTINCLUDE +2 TEXTINCLUDE BEGIN "#include ""afxres.h""\r\n" "#include ""..\\\\common\\\\resource.h""\r\n" "\0" END -3 TEXTINCLUDE +3 TEXTINCLUDE BEGIN "#include ""..\\\\common\\\\common.rc""\r\n" "\0" @@ -264,7 +264,7 @@ IDB_LOGO_288DPI BITMAP "Logo_288dpi.bmp" // Menu // -IDR_MENU MENUEX +IDR_MENU MENUEX BEGIN MENUITEM "About", IDM_ABOUT,MFT_STRING,MFS_ENABLED MENUITEM "Homepage", IDM_HOMEPAGE,MFT_STRING | MFT_RIGHTJUSTIFY,MFS_ENABLED @@ -276,7 +276,7 @@ END // String Table // -STRINGTABLE +STRINGTABLE BEGIN IDS_UACSTRING "VeraCrypt Expander" END diff --git a/src/ExpandVolume/InitDataArea.c b/src/ExpandVolume/InitDataArea.c index 4e6417be..3e2bf494 100644 --- a/src/ExpandVolume/InitDataArea.c +++ b/src/ExpandVolume/InitDataArea.c @@ -1,14 +1,14 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' + and which is governed by the 'License Agreement for Encryption for the Masses' and also from the source code of extcv, which is Copyright (c) 2009-2010 Kih-Oskh or Copyright (c) 2012-2013 Josef Schneider - Modifications and additions to the original source code (contained in this file) + 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 diff --git a/src/ExpandVolume/InitDataArea.h b/src/ExpandVolume/InitDataArea.h index 35c6bbd5..49958a00 100644 --- a/src/ExpandVolume/InitDataArea.h +++ b/src/ExpandVolume/InitDataArea.h @@ -2,10 +2,10 @@ 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, and also derived from source code of extcv which - is Copyright (c) 2009-2010 by Kih-Oskh or Copyright (c) 2012-2013 Josef Schneider + is Copyright (c) 2009-2010 by Kih-Oskh or Copyright (c) 2012-2013 Josef Schneider - Modifications and additions to the original source code (contained in this file) + 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 diff --git a/src/ExpandVolume/WinMain.cpp b/src/ExpandVolume/WinMain.cpp index 630fc79d..ad0d2f50 100644 --- a/src/ExpandVolume/WinMain.cpp +++ b/src/ExpandVolume/WinMain.cpp @@ -1,14 +1,14 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' + and which is governed by the 'License Agreement for Encryption for the Masses' and also from the source code of extcv, which is Copyright (c) 2009-2010 Kih-Oskh or Copyright (c) 2012-2013 Josef Schneider - Modifications and additions to the original source code (contained in this file) + 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 @@ -469,7 +469,7 @@ BOOL CALLBACK ExtcvPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARA EnableWindow (GetDlgItem (hwndDlg, IDC_MOUNT_OPTIONS), FALSE); } - /* No support for mounting TrueCrypt volumes */ + /* No support for mounting TrueCrypt volumes */ SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE); EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE); @@ -493,7 +493,7 @@ BOOL CALLBACK ExtcvPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARA case TC_APPMSG_PREBOOT_PASSWORD_MODE: { - /* No support for mounting TrueCrypt system partition */ + /* No support for mounting TrueCrypt system partition */ SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE); EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE); @@ -605,7 +605,7 @@ BOOL CALLBACK ExtcvPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARA if (lw == IDC_MOUNT_OPTIONS) { - DialogBoxParamW (hInst, + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions); @@ -670,16 +670,16 @@ BOOL CALLBACK ExtcvPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARA if (GetPassword (hwndDlg, IDC_PASSWORD, (LPSTR) szXPwd->Text, MAX_PASSWORD + 1, TRUE)) szXPwd->Length = strlen ((char *) szXPwd->Text); else - return 1; + return 1; - bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_CACHE)); + bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_CACHE)); *pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); *truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); *pim = GetPim (hwndDlg, IDC_PIM); /* SHA-256 is not supported by TrueCrypt */ - if ( (*truecryptMode) + if ( (*truecryptMode) && ((*pkcs5 == SHA256) || (mountOptions.ProtectHiddenVolume && mountOptions.ProtectedHidVolPkcs5Prf == SHA256)) ) { @@ -687,7 +687,7 @@ BOOL CALLBACK ExtcvPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARA return 1; } - if ( (*truecryptMode) + if ( (*truecryptMode) && (*pim != 0) ) { @@ -699,8 +699,8 @@ BOOL CALLBACK ExtcvPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARA // Attempt to wipe password stored in the input field buffer wmemset (tmp, L'X', MAX_PASSWORD); tmp[MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); if (hidVolProtKeyFilesParam.FirstKeyFile != NULL) { @@ -713,7 +713,7 @@ BOOL CALLBACK ExtcvPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARA KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); // Restore the original keyboard layout - if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) + if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); } @@ -748,7 +748,7 @@ BOOL CALLBACK ExtcvPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARA } } } - break; + break; case WM_DROPFILES: { @@ -807,7 +807,7 @@ int ExtcvAskVolumePassword (HWND hwndDlg, const wchar_t* fileName, Password *pas StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume), fileName); - result = DialogBoxParamW (hInst, + result = DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_PASSWORD_DLG), hwndDlg, (DLGPROC) ExtcvPasswordDlgProc, (LPARAM) &dlgParam); diff --git a/src/ExpandVolume/resource.h b/src/ExpandVolume/resource.h index 42b9f2b4..993c414f 100644 --- a/src/ExpandVolume/resource.h +++ b/src/ExpandVolume/resource.h @@ -135,7 +135,7 @@ #define IDM_MANAGE_TOKEN_KEYFILES 40062 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 diff --git a/src/Format/Format.rc b/src/Format/Format.rc index 1f2cc41d..eb2fcfa0 100644 --- a/src/Format/Format.rc +++ b/src/Format/Format.rc @@ -459,19 +459,19 @@ END // TEXTINCLUDE // -1 TEXTINCLUDE +1 TEXTINCLUDE BEGIN "resource.h\0" END -2 TEXTINCLUDE +2 TEXTINCLUDE BEGIN "#include ""afxres.h""\r\n" "#include ""..\\\\common\\\\resource.h""\r\n" "\0" END -3 TEXTINCLUDE +3 TEXTINCLUDE BEGIN "#include ""..\\\\common\\\\common.rc""\r\n" "\0" @@ -486,7 +486,7 @@ END // #ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO +GUIDELINES DESIGNINFO BEGIN IDD_VOL_CREATION_WIZARD_DLG, DIALOG BEGIN @@ -725,7 +725,7 @@ IDB_WIZARD BITMAP "VeraCrypt_wizard.bmp" // String Table // -STRINGTABLE +STRINGTABLE BEGIN IDS_UACSTRING_FMT "VeraCrypt" END diff --git a/src/Format/FormatCom.cpp b/src/Format/FormatCom.cpp index 8ba2372f..96e3e3cd 100644 --- a/src/Format/FormatCom.cpp +++ b/src/Format/FormatCom.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -74,7 +74,7 @@ public: AddRef (); return S_OK; } - + virtual DWORD STDMETHODCALLTYPE CallDriver (DWORD ioctl, BSTR input, BSTR *output) { return BaseCom::CallDriver (ioctl, input, output); diff --git a/src/Format/FormatCom.h b/src/Format/FormatCom.h index 3d545b20..65fadbe9 100644 --- a/src/Format/FormatCom.h +++ b/src/Format/FormatCom.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Format/FormatCom.idl b/src/Format/FormatCom.idl index 764663b1..23d987a7 100644 --- a/src/Format/FormatCom.idl +++ b/src/Format/FormatCom.idl @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Format/InPlace.c b/src/Format/InPlace.c index ff7fed1b..d3b3212b 100644 --- a/src/Format/InPlace.c +++ b/src/Format/InPlace.c @@ -3,7 +3,7 @@ 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) + 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 @@ -63,7 +63,7 @@ using namespace VeraCrypt; #define TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE (TC_TOTAL_VOLUME_HEADERS_SIZE + TC_MIN_NTFS_FS_SIZE * 2) -// If the returned value is greater than 0, it is the desired volume size in NTFS sectors (not in bytes) +// If the returned value is greater than 0, it is the desired volume size in NTFS sectors (not in bytes) // after shrinking has been performed. If there's any error, returns -1. static __int64 NewFileSysSizeAfterShrink (HANDLE dev, const wchar_t *devicePath, int64 *totalClusterCount, DWORD *bytesPerCluster, BOOL silent) { @@ -78,7 +78,7 @@ static __int64 NewFileSysSizeAfterShrink (HANDLE dev, const wchar_t *devicePath, NULL, 0, (LPVOID) &ntfsVolData, - sizeof (ntfsVolData), + sizeof (ntfsVolData), &nBytesReturned, NULL)) { @@ -97,7 +97,7 @@ static __int64 NewFileSysSizeAfterShrink (HANDLE dev, const wchar_t *devicePath, handleWin32Error (MainDlg, SRC_POS); return -1; - } + } fileSysSize = ntfsVolData.NumberSectors.QuadPart * ntfsVolData.BytesPerSector; @@ -105,7 +105,7 @@ static __int64 NewFileSysSizeAfterShrink (HANDLE dev, const wchar_t *devicePath, if (desiredNbrSectors <= 0) return -1; - + if (totalClusterCount) *totalClusterCount = ntfsVolData.TotalClusters.QuadPart; if (bytesPerCluster) @@ -168,7 +168,7 @@ BOOL CheckRequirementsForNonSysInPlaceEnc (HWND hwndDlg, const wchar_t *devicePa if (!IsAdmin()) { - // We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC + // We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC // status can be ignored). In case the IsAdmin() detection somehow fails, we allow the user to continue. if (!silent) @@ -222,7 +222,7 @@ BOOL CheckRequirementsForNonSysInPlaceEnc (HWND hwndDlg, const wchar_t *devicePa NULL, 0, (LPVOID) &ntfsVolData, - sizeof (ntfsVolData), + sizeof (ntfsVolData), &nBytesReturned, NULL)) { @@ -289,7 +289,7 @@ BOOL CheckRequirementsForNonSysInPlaceEnc (HWND hwndDlg, const wchar_t *devicePa NULL, 0, (LPVOID) &ntfsVolData, - sizeof (ntfsVolData), + sizeof (ntfsVolData), &nBytesReturned, NULL)) { @@ -348,7 +348,7 @@ BOOL CheckRequirementsForNonSysInPlaceDec (HWND hwndDlg, const wchar_t *devicePa /* Admin rights */ if (!IsAdmin()) { - // We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC + // We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC // status can be ignored). In case the IsAdmin() detection somehow fails, we allow the user to continue. if (!silent) @@ -436,7 +436,7 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol if (dev == INVALID_HANDLE_VALUE) { - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto closing_seq; } } @@ -444,7 +444,7 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol { // The volume is not mounted so we can't work with the filesystem. Error ("ONLY_MOUNTED_VOL_SUPPORTED_FOR_NONSYS_INPLACE_ENC", hwndDlg); - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto closing_seq; } @@ -454,7 +454,7 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol if (!DeviceIoControl (dev, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, - 0, + 0, NULL, 0, &dwResult, @@ -462,7 +462,7 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol { handleWin32Error (MainDlg, SRC_POS); ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE); - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto closing_seq; } @@ -478,7 +478,7 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol if (sizeToShrinkTo == -1) { ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE); - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto closing_seq; } @@ -492,7 +492,7 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol if (!DeviceIoControl (dev, FSCTL_SHRINK_VOLUME, (LPVOID) &shrinkVolInfo, - sizeof (shrinkVolInfo), + sizeof (shrinkVolInfo), NULL, 0, &dwResult, @@ -500,7 +500,7 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol { handleWin32Error (hwndDlg, SRC_POS); ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "CANNOT_RESIZE_FILESYS", TRUE); - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto closing_seq; } @@ -514,7 +514,7 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol if (!DeviceIoControl (dev, FSCTL_SHRINK_VOLUME, &shrinkVolInfo, sizeof (shrinkVolInfo), NULL, 0, &dwResult, NULL)) { // If there are any occupied clusters beyond the new desired end of the volume, the call fails with - // ERROR_ACCESS_DENIED (STATUS_ALREADY_COMMITTED). + // ERROR_ACCESS_DENIED (STATUS_ALREADY_COMMITTED). if (GetLastError () == ERROR_ACCESS_DENIED) { if (!clustersMovedBeforeVolumeEnd) @@ -532,7 +532,7 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol handleWin32Error (hwndDlg, SRC_POS); ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "CANNOT_RESIZE_FILESYS", TRUE); - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto closing_seq; } @@ -552,15 +552,15 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol if (nStatus != ERR_SUCCESS) { - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto closing_seq; } - /* Create header backup on the partition. Until the volume is fully encrypted, the backup header will provide - us with the master key, encrypted range, and other data for pause/resume operations. We cannot create the - primary header until the entire partition is encrypted (because we encrypt backwards and the primary header + /* Create header backup on the partition. Until the volume is fully encrypted, the backup header will provide + us with the master key, encrypted range, and other data for pause/resume operations. We cannot create the + primary header until the entire partition is encrypted (because we encrypt backwards and the primary header area is occuppied by data until the very end of the process). */ // Prepare the backup header @@ -624,12 +624,12 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol goto closing_seq; } - // The backup header is valid so we know we should be able to safely resume in-place encryption + // The backup header is valid so we know we should be able to safely resume in-place encryption // of this partition even if the system/app crashes. - /* Conceal the NTFS filesystem (by performing an easy-to-undo modification). This will prevent Windows + /* Conceal the NTFS filesystem (by performing an easy-to-undo modification). This will prevent Windows and apps from interfering with the volume until it has been fully encrypted. */ nStatus = ConcealNTFS (dev); @@ -642,7 +642,7 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol // /* If a drive letter is assigned to the device, remove it (so that users do not try to open it, which //would cause Windows to ask them if they want to format the volume and other dangerous things). */ - //if (driveLetter >= 0) + //if (driveLetter >= 0) //{ // char rootPath[] = { driveLetter + 'A', ':', '\\', 0 }; @@ -796,7 +796,7 @@ int EncryptPartitionInPlaceResume (HANDLE dev, if (dev == INVALID_HANDLE_VALUE) { - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto closing_seq; } } @@ -805,7 +805,7 @@ int EncryptPartitionInPlaceResume (HANDLE dev, DeviceIoControl (dev, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, - 0, + 0, NULL, 0, &dwResult, @@ -910,7 +910,7 @@ inplace_enc_read: if (remainingBytes - workChunkSize < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE) { // We reached the inital portion of the filesystem, which we had concealed (in order to prevent - // Windows from interfering with the volume). Now we need to undo that modification. + // Windows from interfering with the volume). Now we need to undo that modification. for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE - (remainingBytes - workChunkSize); i++) buf[i] ^= TC_NTFS_CONCEAL_CONSTANT; @@ -949,7 +949,7 @@ inplace_enc_read: } EncryptDataUnits (wipeBuffer, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo); - memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate)); + memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate)); } if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0 @@ -971,7 +971,7 @@ inplace_enc_read: } } - memcpy (wipeRandChars, wipeRandCharsUpdate, sizeof (wipeRandCharsUpdate)); + memcpy (wipeRandChars, wipeRandCharsUpdate, sizeof (wipeRandCharsUpdate)); } @@ -1164,7 +1164,7 @@ closing_seq: GetSizeString (zeroedSectorCount * sectorSize, sizeStr, sizeof(sizeStr)); - StringCbPrintfW (msg, sizeof(msg), + StringCbPrintfW (msg, sizeof(msg), GetString ("ZEROED_BAD_SECTOR_COUNT"), zeroedSectorCount, sizeStr); @@ -1261,7 +1261,7 @@ int DecryptPartitionInPlace (volatile FORMAT_VOL_PARAMETERS *volParams, volatile if (dev == INVALID_HANDLE_VALUE) { - nStatus = ERR_DONT_REPORT; + nStatus = ERR_DONT_REPORT; goto closing_seq; } @@ -1271,7 +1271,7 @@ int DecryptPartitionInPlace (volatile FORMAT_VOL_PARAMETERS *volParams, volatile DeviceIoControl (dev, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, - 0, + 0, NULL, 0, &dwResult, @@ -1344,7 +1344,7 @@ int DecryptPartitionInPlace (volatile FORMAT_VOL_PARAMETERS *volParams, volatile switch (AskMultiChoice ((void **) tmpStr, FALSE, hwndDlg)) { case 1: - // NOP + // NOP break; case 2: default: @@ -1475,7 +1475,7 @@ int DecryptPartitionInPlace (volatile FORMAT_VOL_PARAMETERS *volParams, volatile goto closing_seq; } } - + // Decrypt the ciphertext in RAM DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo); @@ -1486,7 +1486,7 @@ int DecryptPartitionInPlace (volatile FORMAT_VOL_PARAMETERS *volParams, volatile if (workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE) { - // We are decrypting the initial TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE bytes of the filesystem. We will + // We are decrypting the initial TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE bytes of the filesystem. We will // conceal this portion to prevent Windows and applications from interfering with the volume. for (i = 0; i < min (TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET + workChunkSize); i++) @@ -1821,7 +1821,7 @@ static HANDLE OpenPartitionVolume (HWND hwndDlg, const wchar_t *devName, dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL); if (dev != INVALID_HANDLE_VALUE) { - if (bSharedRequiresConfirmation + if (bSharedRequiresConfirmation && !bSilent && AskWarnNoYes ("DEVICE_IN_USE_INPLACE_ENC", hwndDlg) == IDNO) { @@ -1862,7 +1862,7 @@ static int DismountFileSystem (HWND hwndDlg, HANDLE dev, attempt = UNMOUNT_MAX_AUTO_RETRIES * 10; - while (!(bResult = DeviceIoControl (dev, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) + while (!(bResult = DeviceIoControl (dev, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) && attempt > 0) { Sleep (UNMOUNT_AUTO_RETRY_DELAY); @@ -1891,7 +1891,7 @@ static int DismountFileSystem (HWND hwndDlg, HANDLE dev, attempt = UNMOUNT_MAX_AUTO_RETRIES * 10; - while (!(bResult = DeviceIoControl (dev, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) + while (!(bResult = DeviceIoControl (dev, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL)) && attempt > 0) { Sleep (UNMOUNT_AUTO_RETRY_DELAY); @@ -1903,14 +1903,14 @@ static int DismountFileSystem (HWND hwndDlg, HANDLE dev, if (!bSilent) ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_LOCK_OR_DISMOUNT_FILESYS", TRUE); - return ERR_DONT_REPORT; + return ERR_DONT_REPORT; } - return ERR_SUCCESS; + return ERR_SUCCESS; } -// Easy-to-undo modification applied to conceal the NTFS filesystem (to prevent Windows and apps from +// Easy-to-undo modification applied to conceal the NTFS filesystem (to prevent Windows and apps from // interfering with it until the volume has been fully encrypted). Note that this function will precisely // undo any modifications it made to the filesystem automatically if an error occurs when writing (including // physical drive defects). @@ -1923,7 +1923,7 @@ static int ConcealNTFS (HANDLE dev) DWORD dwError; offset.QuadPart = 0; - + if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0) return ERR_OS_ERROR; @@ -2018,20 +2018,20 @@ BOOL SaveNonSysInPlaceEncSettings (int delta, WipeAlgorithmId newWipeAlgorithm, StringCbPrintfA (str, sizeof(str), "%d", (int) newWipeAlgorithm); SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE), (DWORD) strlen(str), FALSE, FALSE); - } + } else if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE))) { _wremove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE)); } } - + StringCbPrintfA (str, sizeof(str), "%d", count); return SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC), (DWORD) strlen(str), FALSE, FALSE); } -// Repairs damaged sectors (i.e. those with read errors) by zeroing them. +// Repairs damaged sectors (i.e. those with read errors) by zeroing them. // Note that this operating fails if there are any write errors. int ZeroUnreadableSectors (HANDLE dev, LARGE_INTEGER startOffset, int64 size, int sectorSize, uint64 *zeroedSectorCount) { @@ -2179,7 +2179,7 @@ static BOOL GetFreeClusterBeforeThreshold (HANDLE volumeHandle, int64 *freeClust startLcn.StartingLcn.QuadPart += min (bitmapSize * 8, bitmap->BitmapSize.QuadPart); } - + err: SetLastError (ERROR_DISK_FULL); return FALSE; diff --git a/src/Format/InPlace.h b/src/Format/InPlace.h index 75cb9e94..ed24cb89 100644 --- a/src/Format/InPlace.h +++ b/src/Format/InPlace.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Format/Resource.h b/src/Format/Resource.h index c407a7f6..1bdc2f5c 100644 --- a/src/Format/Resource.h +++ b/src/Format/Resource.h @@ -147,7 +147,7 @@ #define IDC_SKIP_RESCUE_VERIFICATION 1108 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 diff --git a/src/Format/Tcformat.c b/src/Format/Tcformat.c index 2065cb5f..bb479395 100644 --- a/src/Format/Tcformat.c +++ b/src/Format/Tcformat.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -127,7 +127,7 @@ enum sys_encryption_cmd_line_switches SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV }; -typedef struct +typedef struct { int NumberOfSysDrives; // Number of drives that contain an operating system. -1: unknown, 1: one, 2: two or more int MultipleSystemsOnDrive; // Multiple systems are installed on the drive where the currently running system resides. -1: unknown, 0: no, 1: yes @@ -139,7 +139,7 @@ typedef struct #define SYSENC_PAUSE_RETRY_INTERVAL 100 #define SYSENC_PAUSE_RETRIES 200 -// Expected duration of system drive analysis, in ms +// Expected duration of system drive analysis, in ms #define SYSENC_DRIVE_ANALYSIS_ETA (4*60000) BootEncryption *BootEncObj = NULL; @@ -219,8 +219,8 @@ volatile HWND hVerifyPasswordInputField = NULL; /* Verify-password input field HBITMAP hbmWizardBitmapRescaled = NULL; wchar_t OrigKeyboardLayout [8+1] = L"00000409"; -BOOL bKeyboardLayoutChanged = FALSE; /* TRUE if the keyboard layout was changed to the standard US keyboard layout (from any other layout). */ -BOOL bKeybLayoutAltKeyWarningShown = FALSE; /* TRUE if the user has been informed that it is not possible to type characters by pressing keys while the right Alt key is held down. */ +BOOL bKeyboardLayoutChanged = FALSE; /* TRUE if the keyboard layout was changed to the standard US keyboard layout (from any other layout). */ +BOOL bKeybLayoutAltKeyWarningShown = FALSE; /* TRUE if the user has been informed that it is not possible to type characters by pressing keys while the right Alt key is held down. */ #ifndef _DEBUG BOOL bWarnDeviceFormatAdvanced = TRUE; @@ -277,7 +277,7 @@ BOOL bDisplayPoolContents = TRUE; volatile BOOL bSparseFileSwitch = FALSE; volatile BOOL quickFormat = FALSE; /* WARNING: Meaning of this variable depends on bSparseFileSwitch. If bSparseFileSwitch is TRUE, this variable represents the sparse file flag. */ -volatile int fileSystem = FILESYS_NONE; +volatile int fileSystem = FILESYS_NONE; volatile int clusterSize = 0; SYSENC_MULTIBOOT_CFG SysEncMultiBootCfg; @@ -286,7 +286,7 @@ volatile int NonSysInplaceEncStatus = NONSYS_INPLACE_ENC_STATUS_NONE; vector DeferredNonSysInPlaceEncDevices; -// specific definitions and implementation for support of resume operation +// specific definitions and implementation for support of resume operation // in wait dialog mechanism void CALLBACK ResumeInPlaceEncWaitThreadProc(void* pArg, HWND hwndDlg) @@ -384,7 +384,7 @@ static BOOL ElevateWholeWizardProcess (wstring arguments) while (true) { if ((int)ShellExecute (MainDlg, L"runas", modPath, (wstring(L"/q UAC ") + arguments).c_str(), NULL, SW_SHOWNORMAL) > 32) - { + { exit (0); } else @@ -452,7 +452,7 @@ static void localcleanup (void) } CloseNonSysInplaceEncMutex (); - + // Device wipe @@ -608,7 +608,7 @@ static unsigned int DetermineHiddenOSCreationPhase (void) // IMPORTANT: This function may be called only by Format (other modules can only _read_ the status). // Returns TRUE if successful (otherwise FALSE) -static BOOL ChangeHiddenOSCreationPhase (int newPhase) +static BOOL ChangeHiddenOSCreationPhase (int newPhase) { if (!CreateSysEncMutex ()) { @@ -676,7 +676,7 @@ static BOOL ChangeSystemEncryptionStatus (int newStatus) // may be called only after CreateSysEncMutex() returns TRUE. It returns TRUE if successful (otherwise FALSE). static BOOL ChangeWizardMode (int newWizardMode) { - if (WizardMode != newWizardMode) + if (WizardMode != newWizardMode) { if (WizardMode == WIZARD_MODE_SYS_DEVICE || newWizardMode == WIZARD_MODE_SYS_DEVICE) { @@ -692,7 +692,7 @@ static BOOL ChangeWizardMode (int newWizardMode) // If the previous mode was different, the password may have been typed using a different // keyboard layout (which might confuse the user and cause other problems if system encryption // was or will be involved). - WipePasswordsAndKeyfiles(); + WipePasswordsAndKeyfiles(); } if (newWizardMode != WIZARD_MODE_NONSYS_DEVICE) @@ -719,10 +719,10 @@ static BOOL ChangeWizardMode (int newWizardMode) bDevice = (WizardMode != WIZARD_MODE_FILE_CONTAINER); - if (newWizardMode != WIZARD_MODE_SYS_DEVICE + if (newWizardMode != WIZARD_MODE_SYS_DEVICE && !bHiddenOS) { - CloseSysEncMutex (); + CloseSysEncMutex (); } return TRUE; @@ -730,7 +730,7 @@ static BOOL ChangeWizardMode (int newWizardMode) // Determines whether the wizard directly affects system encryption in any way. // Note, for example, that when the user enters a password for a hidden volume that is to host a hidden OS, -// WizardMode is NOT set to WIZARD_MODE_SYS_DEVICE. The keyboard layout, however, has to be US. That's why +// WizardMode is NOT set to WIZARD_MODE_SYS_DEVICE. The keyboard layout, however, has to be US. That's why // this function has to be called instead of checking the value of WizardMode. static BOOL SysEncInEffect (void) { @@ -740,7 +740,7 @@ static BOOL SysEncInEffect (void) static BOOL CreatingHiddenSysVol (void) { - return (bHiddenOS + return (bHiddenOS && bHiddenVol && !bHiddenVolHost); } @@ -791,7 +791,7 @@ static void LoadSettingsAndCheckModified (HWND hwndDlg, BOOL bOnlyCheckModified, StringCbCopyA (langid, sizeof(langid), "en"); if (pbSettingsModified && strcmp (langid, GetPreferredLangId ())) - *pbSettingsModified = TRUE; + *pbSettingsModified = TRUE; } else { @@ -858,7 +858,7 @@ static void EndMainDlg (HWND hwndDlg) MoveEditToCombo (GetDlgItem (hCurPage, IDC_COMBO_BOX), bHistory); SaveSettings (hCurPage); } - else + else { SaveSettings (NULL); } @@ -889,10 +889,10 @@ static BOOL SysEncryptionOrDecryptionRequired (void) return (SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING || SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING - || + || ( - locBootEncStatus.DriveMounted - && + locBootEncStatus.DriveMounted + && ( locBootEncStatus.ConfiguredEncryptedAreaStart != locBootEncStatus.EncryptedAreaStart || locBootEncStatus.ConfiguredEncryptedAreaEnd != locBootEncStatus.EncryptedAreaEnd @@ -963,7 +963,7 @@ BOOL SwitchWizardToSysEncMode (void) // The config file with status was lost or not written correctly if (!ResolveUnknownSysEncDirection ()) { - CloseSysEncMutex (); + CloseSysEncMutex (); NormalCursor (); return FALSE; } @@ -977,7 +977,7 @@ BOOL SwitchWizardToSysEncMode (void) } else { - CloseSysEncMutex (); + CloseSysEncMutex (); Error ("SYS_ENCRYPTION_OR_DECRYPTION_IN_PROGRESS", MainDlg); NormalCursor (); return FALSE; @@ -996,11 +996,11 @@ BOOL SwitchWizardToSysEncMode (void) { // If the config file with status was lost or not written correctly, we // don't know whether to encrypt or decrypt (but we know that encryption or - // decryption is required). Ask the user to select encryption, decryption, + // decryption is required). Ask the user to select encryption, decryption, // or cancel if (!ResolveUnknownSysEncDirection ()) { - CloseSysEncMutex (); + CloseSysEncMutex (); NormalCursor (); return FALSE; } @@ -1014,7 +1014,7 @@ BOOL SwitchWizardToSysEncMode (void) } else { - CloseSysEncMutex (); + CloseSysEncMutex (); Error ("SETUP_FAILED_BOOT_DRIVE_ENCRYPTED", MainDlg); NormalCursor (); return FALSE; @@ -1038,7 +1038,7 @@ BOOL SwitchWizardToSysEncMode (void) } catch (Exception &e) { - CloseSysEncMutex (); + CloseSysEncMutex (); e.Show (MainDlg); NormalCursor (); return FALSE; @@ -1089,7 +1089,7 @@ BOOL SwitchWizardToSysEncMode (void) Warning ("WDE_EXTENDED_PARTITIONS_WARNING", MainDlg); } } - else if (BootEncObj->SystemPartitionCoversWholeDrive() + else if (BootEncObj->SystemPartitionCoversWholeDrive() && !bWholeSysDrive) bWholeSysDrive = (AskYesNo ("WHOLE_SYC_DEVICE_RECOM", MainDlg) == IDYES); } @@ -1104,7 +1104,7 @@ BOOL SwitchWizardToSysEncMode (void) if (!bHiddenVol) { // Skip SYSENC_SPAN_PAGE and SYSENC_TYPE_PAGE as the user already made the choice - LoadPage (MainDlg, bWholeSysDrive ? SYSENC_PRE_DRIVE_ANALYSIS_PAGE : SYSENC_MULTI_BOOT_MODE_PAGE); + LoadPage (MainDlg, bWholeSysDrive ? SYSENC_PRE_DRIVE_ANALYSIS_PAGE : SYSENC_MULTI_BOOT_MODE_PAGE); } else { @@ -1162,7 +1162,7 @@ BOOL SwitchWizardToHiddenOSMode (void) if (bDirectSysEncModeCommand == SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV) { // Some of the requirements for hidden OS should have already been checked by the wizard process - // that launched us (in order to elevate), but we must recheck them. Otherwise, an advanced user + // that launched us (in order to elevate), but we must recheck them. Otherwise, an advanced user // could bypass the checks by using the undocumented CLI switch. Moreover, some requirements // can be checked only at this point (when we are elevated). try @@ -1299,7 +1299,7 @@ static BOOL ResolveUnknownSysEncDirection (void) } // This function should be used to resolve inconsistencies that might lead to a deadlock (inability to encrypt or -// decrypt the system partition/drive and to uninstall TrueCrypt). The function removes the system encryption key +// decrypt the system partition/drive and to uninstall TrueCrypt). The function removes the system encryption key // data ("volume header"), the TrueCrypt boot loader, restores the original system loader (if available), // unregisters the boot driver, etc. Note that if the system partition/drive is encrypted, it will start decrypting // it in the background (therefore, it should be used when the system partition/drive is not encrypted, ideally). @@ -1322,7 +1322,7 @@ static BOOL ForceRemoveSysEnc (void) if (locBootEncStatus.DriveMounted) { // Remove the header - BootEncObj->StartDecryption (DiscardUnreadableEncryptedSectors); + BootEncObj->StartDecryption (DiscardUnreadableEncryptedSectors); locBootEncStatus = BootEncObj->GetStatus(); while (locBootEncStatus.SetupInProgress) @@ -1403,7 +1403,7 @@ void ComboSelChangeEA (HWND hwndDlg) else if (wcscmp (name, L"Serpent") == 0) { StringCbPrintfW (hyperLink, sizeof(hyperLink) / 2, GetString ("MORE_INFO_ABOUT"), name); - + SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SERPENT_HELP")); } else if (wcscmp (name, L"Twofish") == 0) @@ -1419,13 +1419,13 @@ void ComboSelChangeEA (HWND hwndDlg) while (i = EAGetPreviousCipher(nIndex, i)) { cipherIDs[cnt] = i; - cnt++; + cnt++; } switch (cnt) // Number of ciphers in the cascade { case 2: - StringCbPrintfW (auxLine, sizeof(auxLine), GetString ("TWO_LAYER_CASCADE_HELP"), + StringCbPrintfW (auxLine, sizeof(auxLine), GetString ("TWO_LAYER_CASCADE_HELP"), CipherGetName (cipherIDs[1]), CipherGetKeySize (cipherIDs[1])*8, CipherGetName (cipherIDs[0]), @@ -1433,7 +1433,7 @@ void ComboSelChangeEA (HWND hwndDlg) break; case 3: - StringCbPrintfW (auxLine, sizeof(auxLine), GetString ("THREE_LAYER_CASCADE_HELP"), + StringCbPrintfW (auxLine, sizeof(auxLine), GetString ("THREE_LAYER_CASCADE_HELP"), CipherGetName (cipherIDs[2]), CipherGetKeySize (cipherIDs[2])*8, CipherGetName (cipherIDs[1]), @@ -1538,7 +1538,7 @@ static void VerifySizeAndUpdate (HWND hwndDlg, BOOL bUpdate) { // Change of volume size may make some file systems allowed or disallowed, so the default filesystem must // be reselected. - fileSystem = FILESYS_NONE; + fileSystem = FILESYS_NONE; nLastVolumeSize = nVolumeSize; } } @@ -1648,7 +1648,7 @@ static void UpdateSysEncProgressBar (void) return; } - if (locBootEncStatus.EncryptedAreaEnd == -1 + if (locBootEncStatus.EncryptedAreaEnd == -1 || locBootEncStatus.EncryptedAreaStart == -1) { UpdateProgressBarProc (0); @@ -1688,11 +1688,11 @@ static void InitSysEncProgressBar (void) return; } - if (locBootEncStatus.ConfiguredEncryptedAreaEnd == -1 + if (locBootEncStatus.ConfiguredEncryptedAreaEnd == -1 || locBootEncStatus.ConfiguredEncryptedAreaStart == -1) return; - InitProgressBar (locBootEncStatus.ConfiguredEncryptedAreaEnd + InitProgressBar (locBootEncStatus.ConfiguredEncryptedAreaEnd - locBootEncStatus.ConfiguredEncryptedAreaStart + 1, (locBootEncStatus.EncryptedAreaEnd == locBootEncStatus.EncryptedAreaStart || locBootEncStatus.EncryptedAreaEnd == -1) ? 0 : locBootEncStatus.EncryptedAreaEnd - locBootEncStatus.EncryptedAreaStart + 1, @@ -1715,8 +1715,8 @@ static void UpdateSysEncControls (void) return; } - EnableWindow (GetDlgItem (hCurPage, IDC_WIPE_MODE), - !locBootEncStatus.SetupInProgress + EnableWindow (GetDlgItem (hCurPage, IDC_WIPE_MODE), + !locBootEncStatus.SetupInProgress && SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING); SetWindowTextW (GetDlgItem (hCurPage, IDC_PAUSE), @@ -1808,7 +1808,7 @@ static void SysEncPause (void) Error ("FAILED_TO_INTERRUPT_SYSTEM_ENCRYPTION", MainDlg); return; } - + UpdateSysEncControls (); EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE); } @@ -1859,13 +1859,13 @@ static void SysEncResume (void) { case SYSENC_STATUS_ENCRYPTING: - BootEncObj->StartEncryption (nWipeMode, bTryToCorrectReadErrors ? true : false); + BootEncObj->StartEncryption (nWipeMode, bTryToCorrectReadErrors ? true : false); break; case SYSENC_STATUS_DECRYPTING: if (locBootEncStatus.DriveMounted) // If the drive is not encrypted we will just deinstall - BootEncObj->StartDecryption (DiscardUnreadableEncryptedSectors); + BootEncObj->StartDecryption (DiscardUnreadableEncryptedSectors); break; } @@ -1920,13 +1920,13 @@ static BOOL GetDevicePathForHiddenOS (void) return FALSE; } - return (szFileName[0] != 0 - && szDiskFile[0] != 0 + return (szFileName[0] != 0 + && szDiskFile[0] != 0 && tmpbDevice); } -// Returns TRUE if there is unallocated space greater than 64 MB (max possible slack space size) between the +// Returns TRUE if there is unallocated space greater than 64 MB (max possible slack space size) between the // boot partition and the first partition behind it. If there's none or if an error occurs, returns FALSE. static BOOL CheckGapBetweenSysAndHiddenOS (void) { @@ -1934,7 +1934,7 @@ static BOOL CheckGapBetweenSysAndHiddenOS (void) { SystemDriveConfiguration sysDriveCfg = BootEncObj->GetSystemDriveConfiguration(); - return (sysDriveCfg.SystemPartition.Info.StartingOffset.QuadPart + return (sysDriveCfg.SystemPartition.Info.StartingOffset.QuadPart + sysDriveCfg.SystemPartition.Info.PartitionLength.QuadPart + 64 * BYTES_PER_MB + 128 * BYTES_PER_KB @@ -1956,7 +1956,7 @@ static void NonSysInplaceEncPause (void) WaitCursor (); int waitThreshold = 100; // Do not block GUI events for more than 10 seconds. IMPORTANT: This prevents deadlocks when the thread calls us back e.g. to update GUI! - + while (bVolTransformThreadRunning || bVolTransformThreadToRun) { MSG guiMsg; @@ -2071,15 +2071,15 @@ void UpdateNonSysInPlaceEncControls (void) lastbInPlaceEncNonSysResumed = bInPlaceEncNonSysResumed; } - EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), bFirstNonSysInPlaceEncResumeDone + EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), bFirstNonSysInPlaceEncResumeDone && NonSysInplaceEncStatus != NONSYS_INPLACE_ENC_STATUS_FINALIZING && NonSysInplaceEncStatus != NONSYS_INPLACE_ENC_STATUS_FINISHED); EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), !(bVolTransformThreadRunning || bVolTransformThreadToRun) && !bFirstNonSysInPlaceEncResumeDone); EnableWindow (GetDlgItem (MainDlg, IDC_PREV), !(bVolTransformThreadRunning || bVolTransformThreadToRun) && !bInPlaceEncNonSysResumed); - EnableWindow (GetDlgItem (MainDlg, IDCANCEL), - !(bVolTransformThreadToRun - || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_PREPARING + EnableWindow (GetDlgItem (MainDlg, IDCANCEL), + !(bVolTransformThreadToRun + || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_PREPARING || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_RESIZING || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINALIZING || NonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINISHED)); @@ -2132,7 +2132,7 @@ static void UpdateNonSysInplaceEncProgressBar (void) int nonSysInplaceEncStatus = NonSysInplaceEncStatus; __int64 totalSize = NonSysInplaceEncTotalSize; - if (bVolTransformThreadRunning + if (bVolTransformThreadRunning && (nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_ENCRYPTING || nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_DECRYPTING || nonSysInplaceEncStatus == NONSYS_INPLACE_ENC_STATUS_FINALIZING @@ -2181,7 +2181,7 @@ static void InitNonSysInplaceEncProgressBar (void) void DisplayRandPool (HWND hwndDlg, HWND hPoolDisplay, BOOL bShow) -{ +{ wchar_t tmp[4]; unsigned char tmpByte; int col, row; @@ -2209,7 +2209,7 @@ void DisplayRandPool (HWND hwndDlg, HWND hPoolDisplay, BOOL bShow) else if (bUseMask) { /* use mask to compute a randomized ASCII representation */ - tmpByte = (randPool[row * RANDPOOL_DISPLAY_COLUMNS + col] - + tmpByte = (randPool[row * RANDPOOL_DISPLAY_COLUMNS + col] - lastRandPool[row * RANDPOOL_DISPLAY_COLUMNS + col]) ^ maskRandPool [row * RANDPOOL_DISPLAY_COLUMNS + col]; tmp[0] = (wchar_t) (((tmpByte >> 4) % 6) + L'*'); tmp[1] = (wchar_t) (((tmpByte & 0x0F) % 6) + L'*'); @@ -2248,8 +2248,8 @@ static void WipeAbort (void) if (bHiddenOS && IsHiddenOSRunning()) { - /* Decoy system partition wipe */ - + /* Decoy system partition wipe */ + DecoySystemWipeStatus decoySysPartitionWipeStatus; try @@ -2328,7 +2328,7 @@ static void WipeStart (void) try { - BootEncObj->StartDecoyOSWipe (nWipeMode); + BootEncObj->StartDecoyOSWipe (nWipeMode); bDeviceWipeInProgress = TRUE; } @@ -2407,7 +2407,7 @@ static void InitWipeProgressBar (void) return; } - if (BootEncStatus.ConfiguredEncryptedAreaEnd == -1 + if (BootEncStatus.ConfiguredEncryptedAreaEnd == -1 || BootEncStatus.ConfiguredEncryptedAreaStart == -1) return; @@ -2510,7 +2510,7 @@ static void __cdecl volTransformThreadFunction (void *hwndDlgArg) int nStatus; DWORD dwWin32FormatError; BOOL bHidden; - HWND hwndDlg = (HWND) hwndDlgArg; + HWND hwndDlg = (HWND) hwndDlgArg; volatile FORMAT_VOL_PARAMETERS *volParams = (FORMAT_VOL_PARAMETERS *) malloc (sizeof(FORMAT_VOL_PARAMETERS)); if (volParams == NULL) @@ -2785,7 +2785,7 @@ static void __cdecl volTransformThreadFunction (void *hwndDlgArg) // NOP - Final steps for in-place decryption are handled with the TC_APPMSG_NONSYS_INPLACE_ENC_FINISHED message. } } - else + else { Info("FORMAT_FINISHED_INFO", hwndDlg); @@ -2797,7 +2797,7 @@ static void __cdecl volTransformThreadFunction (void *hwndDlgArg) { /* We've just created an outer volume (to host a hidden volume within) */ - bHiddenVolHost = FALSE; + bHiddenVolHost = FALSE; bHiddenVolFinished = FALSE; nHiddenVolHostSize = nVolumeSize; @@ -2872,15 +2872,15 @@ static void LoadPage (HWND hwndDlg, int nPageNo) if (hCurPage != NULL) { // WARNING: nCurPageNo must be set to a non-existent ID here before wiping the password fields below in - // this function, etc. Otherwise, such actions (SetWindowText) would invoke the EN_CHANGE handlers, which - // would, if keyfiles were applied, e.g. use strlen() on a buffer full of random data, in most cases + // this function, etc. Otherwise, such actions (SetWindowText) would invoke the EN_CHANGE handlers, which + // would, if keyfiles were applied, e.g. use strlen() on a buffer full of random data, in most cases // not null-terminated. nCurPageNo = -1; // Place here any actions that need to be performed at the latest possible time when leaving a wizard page // (i.e. right before "destroying" the page). Also, code that needs to be executed both on IDC_NEXT and - // on IDC_PREV can be placed here so as to avoid code doubling. + // on IDC_PREV can be placed here so as to avoid code doubling. switch (nLastPageNo) { @@ -2888,7 +2888,7 @@ static void LoadPage (HWND hwndDlg, int nPageNo) { wchar_t tmp[MAX_PASSWORD+1]; - // Attempt to wipe passwords stored in the input field buffers. This is performed here (and + // Attempt to wipe passwords stored in the input field buffers. This is performed here (and // not in the IDC_PREV or IDC_NEXT sections) in order to prevent certain race conditions // when keyfiles are used. wmemset (tmp, 'X', MAX_PASSWORD); @@ -2980,7 +2980,7 @@ static void LoadPage (HWND hwndDlg, int nPageNo) EnableWindow (GetDlgItem(hCurPage, IDC_NO_HISTORY), !bHistoryCmdLine); - EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), + EnableWindow (GetDlgItem (hwndDlg, IDC_NEXT), GetWindowTextLength (GetDlgItem (hCurPage, IDC_COMBO_BOX)) > 0); break; @@ -3122,7 +3122,7 @@ static void LoadPage (HWND hwndDlg, int nPageNo) MoveWindow (hCurPage, rD.left, rD.top, rW.right - rW.left, rW.bottom - rW.top, TRUE); ShowWindow (hCurPage, SW_SHOWNORMAL); - // Place here any message boxes that need to be displayed as soon as a new page is displayed. This + // Place here any message boxes that need to be displayed as soon as a new page is displayed. This // ensures that the page is fully rendered (otherwise it would remain blank, until the message box // is closed). switch (nPageNo) @@ -3200,7 +3200,7 @@ __int64 PrintFreeSpace (HWND hwndTextBox, wchar_t *lpszDrive, PLARGE_INTEGER lDi else nResourceString = "DISK_FREE_GB"; } - else + else { if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume nResourceString = "MAX_HIDVOL_SIZE_TB"; @@ -3545,7 +3545,7 @@ static BOOL FinalPreTransformPrompts (void) switch (AskMultiChoice ((void **) tmpStr, TRUE, MainDlg)) { case 1: - // Proceed + // Proceed // NOP break; @@ -4012,7 +4012,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa else { // The hidden volume must be as large as the system partition - nVolumeSize = GetSystemPartitionSize() + TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH; + nVolumeSize = GetSystemPartitionSize() + TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH; SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDDEN_OS_PRE_CIPHER_HELP")); } @@ -4062,7 +4062,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa // For now, we keep RIPEMD160 for system encryption if (((hid == RIPEMD160) || !HashIsDeprecated (hid)) && HashForSystemEncryption (hid)) AddComboPair (GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO), HashGetName(hid), hid); - } + } } else { @@ -4239,7 +4239,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa wchar_t str[1000]; hPasswordInputField = GetDlgItem (hwndDlg, IDC_PASSWORD); - hVerifyPasswordInputField = GetDlgItem (hwndDlg, IDC_VERIFY); + hVerifyPasswordInputField = GetDlgItem (hwndDlg, IDC_VERIFY); if (SysEncInEffect ()) { @@ -4292,7 +4292,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa SetPassword (hwndDlg, IDC_VERIFY, szVerify); SetFocus (GetDlgItem (hwndDlg, IDC_PASSWORD)); - + SetCheckBox (hwndDlg, IDC_PIM_ENABLE, PimEnable); SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable && !SysEncInEffect()); @@ -4515,7 +4515,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("WIPE_MODE_TITLE")); SetWindowTextW (GetDlgItem (hwndDlg, IDT_WIPE_MODE_INFO), GetString ("INPLACE_ENC_WIPE_MODE_INFO")); - PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), + PopulateWipeModeCombo (GetDlgItem (hwndDlg, IDC_WIPE_MODE), SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING && !bInPlaceEncNonSys, TRUE, FALSE); @@ -4548,7 +4548,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa try { StringCbPrintfW (finalMsg, sizeof(finalMsg), - GetString ("SYS_ENCRYPTION_PRETEST_INFO"), + GetString ("SYS_ENCRYPTION_PRETEST_INFO"), BootEncObj->GetSystemDriveConfiguration().DriveNumber); } catch (Exception &e) @@ -4656,12 +4656,12 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE); EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE); - + foreach (const HostDevice &device, DeferredNonSysInPlaceEncDevices) { SendMessage (GetDlgItem (hwndDlg, IDC_LIST_BOX), LB_ADDSTRING, 0, (LPARAM) device.Path.c_str()); } - + // Deselect all SendMessage (GetDlgItem (hwndDlg, IDC_LIST_BOX), LB_SETCURSEL, (WPARAM) -1, 0); } @@ -4744,14 +4744,14 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDCANCEL), GetString ("CANCEL")); - // The Cancel button and the X button must be disabled to prevent the user from forgetting to assign a drive letter to the partition by closing + // The Cancel button and the X button must be disabled to prevent the user from forgetting to assign a drive letter to the partition by closing // the window accidentally or clicking Cancel. The user is forced to click Finish to assign at least the pre-selected free drive letter. // This is critical because inexperienced users would not know how to access data on the decrypted volume without a drive letter. EnableWindow (GetDlgItem (GetParent (hwndDlg), IDCANCEL), FALSE); DisableCloseButton (MainDlg); bConfirmQuit = TRUE; // Alt-F4 will still work but the user will be prompted to confirm the action. - // Decryption of non-system volume finished, no drive letter is assigned to the decrypted volume, and free drive letters are available. + // Decryption of non-system volume finished, no drive letter is assigned to the decrypted volume, and free drive letters are available. // This is critical because inexperienced users would not know how to access data on the decrypted volume. We cannot allow exit // until a drive letter is freed up and assigned to the decrypted volume. @@ -4900,7 +4900,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa uint64 dataAreaSize = GetVolumeDataAreaSize (bHiddenVol && !bHiddenVolHost, nVolumeSize); - if (!CreatingHiddenSysVol()) + if (!CreatingHiddenSysVol()) { if (dataAreaSize >= TC_MIN_NTFS_FS_SIZE && dataAreaSize <= TC_MAX_NTFS_FS_SIZE) { @@ -4987,14 +4987,14 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa // Determine the maximum recommended total size of files that can be copied to the outer volume // while leaving enough space for the hidden volume, which must contain a clone of the OS - maxRecomOuterVolFillSize = nVolumeSize - GetSystemPartitionSize(); + maxRecomOuterVolFillSize = nVolumeSize - GetSystemPartitionSize(); // -50% reserve for filesystem "peculiarities" - maxRecomOuterVolFillSize /= 2; + maxRecomOuterVolFillSize /= 2; StringCbPrintfW (szMaxRecomOuterVolFillSize, sizeof(szMaxRecomOuterVolFillSize), L"%I64d %s", maxRecomOuterVolFillSize / BYTES_PER_MB, GetString ("MB")); - StringCbPrintfW (msg, sizeof(msg), GetString ("HIDVOL_HOST_FILLING_HELP_SYSENC"), hiddenVolHostDriveNo + 'A', szMaxRecomOuterVolFillSize); + StringCbPrintfW (msg, sizeof(msg), GetString ("HIDVOL_HOST_FILLING_HELP_SYSENC"), hiddenVolHostDriveNo + 'A', szMaxRecomOuterVolFillSize); } else StringCbPrintfW (msg, sizeof(msg), GetString ("HIDVOL_HOST_FILLING_HELP"), hiddenVolHostDriveNo + 'A'); @@ -5002,7 +5002,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), msg); SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDVOL_HOST_FILLING_TITLE")); } - else + else { if (bHiddenOS) SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_HIDDEN_VOL_FORMAT_FINISHED_HELP")); @@ -5307,7 +5307,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (hw == CBN_SELCHANGE) { nWipeMode = (WipeAlgorithmId) SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), - CB_GETITEMDATA, + CB_GETITEMDATA, SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), 0); @@ -5327,7 +5327,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { case NONSYS_INPLACE_ENC_RESUME_PARTITION_SEL_PAGE: - if (lw == IDC_LIST_BOX + if (lw == IDC_LIST_BOX && (hw == LBN_SELCHANGE || hw == LBN_DBLCLK)) { BOOL tmpbDevice = FALSE; @@ -5385,7 +5385,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (hw == CBN_SELCHANGE) { nWipeMode = (WipeAlgorithmId) SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), - CB_GETITEMDATA, + CB_GETITEMDATA, SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), 0); @@ -5428,7 +5428,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa for (c = EAGetLastCipher (nVolumeEA); c != 0; c = EAGetPreviousCipher (nVolumeEA, c)) { - DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_CIPHER_TEST_DLG), + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_CIPHER_TEST_DLG), GetParent (hwndDlg), (DLGPROC) CipherTestDialogProc, (LPARAM) c); } return 1; @@ -5437,7 +5437,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (lw == IDC_BENCHMARK && nCurPageNo == CIPHER_PAGE) { // Reduce CPU load - bFastPollEnabled = FALSE; + bFastPollEnabled = FALSE; bRandmixEnabled = FALSE; DialogBoxParamW (hInst, @@ -5484,7 +5484,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (hw == CBN_EDITCHANGE && nCurPageNo == VOLUME_LOCATION_PAGE) { - EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), + EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetWindowTextLength (GetDlgItem (hCurPage, IDC_COMBO_BOX)) > 0); bDeviceTransformModeChoiceMade = FALSE; @@ -5492,7 +5492,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa return 1; } - + if (hw == CBN_SELCHANGE && nCurPageNo == VOLUME_LOCATION_PAGE) { LPARAM nIndex; @@ -5510,13 +5510,13 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa return 1; } - + if (hw == EN_CHANGE && nCurPageNo == SIZE_PAGE) { VerifySizeAndUpdate (hwndDlg, FALSE); return 1; } - + if (hw == EN_CHANGE && nCurPageNo == PASSWORD_PAGE) { VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (GetParent (hwndDlg), IDC_NEXT), @@ -5581,9 +5581,9 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa } return 1; } - - if (nCurPageNo == PASSWORD_PAGE - || nCurPageNo == HIDDEN_VOL_HOST_PASSWORD_PAGE + + if (nCurPageNo == PASSWORD_PAGE + || nCurPageNo == HIDDEN_VOL_HOST_PASSWORD_PAGE || nCurPageNo == NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE) { if (lw == IDC_KEY_FILES) @@ -5770,7 +5770,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa bHiddenVolDirect = FALSE; return 1; } - + if (hw == CBN_SELCHANGE && nCurPageNo == CIPHER_PAGE) { switch (lw) @@ -5803,12 +5803,12 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (bSparseFileSwitch) { if (AskWarnYesNo("CONFIRM_SPARSE_FILE", MainDlg) == IDNO) - SetCheckBox (hwndDlg, IDC_QUICKFORMAT, FALSE); + SetCheckBox (hwndDlg, IDC_QUICKFORMAT, FALSE); } else { if (AskWarnYesNo("WARN_QUICK_FORMAT", MainDlg) == IDNO) - SetCheckBox (hwndDlg, IDC_QUICKFORMAT, FALSE); + SetCheckBox (hwndDlg, IDC_QUICKFORMAT, FALSE); } return 1; } @@ -5830,8 +5830,8 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa SetWindowText (GetDlgItem (hCurPage, IDC_DISK_KEY), showKeys ? L"" : L"******************************** "); return 1; } - - if (lw == IDC_DISPLAY_POOL_CONTENTS + + if (lw == IDC_DISPLAY_POOL_CONTENTS && (nCurPageNo == SYSENC_COLLECTING_RANDOM_DATA_PAGE || nCurPageNo == NONSYS_INPLACE_ENC_RAND_DATA_PAGE)) { showKeys = IsButtonChecked (GetDlgItem (hCurPage, IDC_DISPLAY_POOL_CONTENTS)); @@ -5882,13 +5882,13 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa return 1; } - if ((nCurPageNo == SYSENC_WIPE_MODE_PAGE - || nCurPageNo == NONSYS_INPLACE_ENC_WIPE_MODE_PAGE + if ((nCurPageNo == SYSENC_WIPE_MODE_PAGE + || nCurPageNo == NONSYS_INPLACE_ENC_WIPE_MODE_PAGE || nCurPageNo == DEVICE_WIPE_MODE_PAGE) && hw == CBN_SELCHANGE) { nWipeMode = (WipeAlgorithmId) SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), - CB_GETITEMDATA, + CB_GETITEMDATA, SendMessage (GetDlgItem (hCurPage, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), 0); @@ -5941,7 +5941,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (IsTrueCryptInstallerRunning()) AbortProcess ("TC_INSTALLER_IS_RUNNING"); - // Resize the bitmap if the user has a non-default DPI + // Resize the bitmap if the user has a non-default DPI if (ScreenDPI != USER_DEFAULT_SCREEN_DPI) { hbmWizardBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_WIZARD), @@ -6002,7 +6002,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (CmdVolumePassword.Length == 0) AbortProcess ("ERR_PASSWORD_MISSING"); - + if (CmdVolumeFileSize == 0) AbortProcess ("ERR_SIZE_MISSING"); @@ -6056,7 +6056,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa handleWin32Error (hwndDlg, SRC_POS); exit (1); } - + if (CmdSparseFileSwitch) { /* Check if the host file system supports sparse files */ @@ -6098,21 +6098,21 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa dataAreaSize = GetVolumeDataAreaSize (bHiddenVol && !bHiddenVolHost, nVolumeSize); - if ( (fileSystem == FILESYS_NTFS) && + if ( (fileSystem == FILESYS_NTFS) && (dataAreaSize < TC_MIN_NTFS_FS_SIZE || dataAreaSize > TC_MAX_NTFS_FS_SIZE) ) { AbortProcess ("ERR_NTFS_INVALID_VOLUME_SIZE"); } - if ( (fileSystem == FILESYS_EXFAT) && + if ( (fileSystem == FILESYS_EXFAT) && (dataAreaSize < TC_MIN_EXFAT_FS_SIZE || dataAreaSize > TC_MAX_EXFAT_FS_SIZE) ) { AbortProcess ("ERR_EXFAT_INVALID_VOLUME_SIZE"); } - if ( (fileSystem == FILESYS_FAT) && + if ( (fileSystem == FILESYS_FAT) && (dataAreaSize < TC_MIN_FAT_FS_SIZE || dataAreaSize > (TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize())) ) { @@ -6139,7 +6139,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa } if (volumePassword.Length > 0) - { + { // Check password length (check also done for outer volume which is not the case in TrueCrypt). if (!CheckPasswordLength (NULL, volumePassword.Length, volumePim, FALSE, Silent, Silent)) { @@ -6159,7 +6159,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { // Availability of in-place encryption (which is pre-selected by default whenever // possible) makes partition-hosted volume creation safer. - bWarnDeviceFormatAdvanced = FALSE; + bWarnDeviceFormatAdvanced = FALSE; } #ifdef _DEBUG @@ -6360,7 +6360,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { e.Show (hwndDlg); } - + ManageStartupSeqWiz (TRUE, L""); ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); @@ -6499,7 +6499,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (bHiddenOS && IsHiddenOSRunning()) { - // Decoy system partition wipe + // Decoy system partition wipe DecoySystemWipeStatus decoySysPartitionWipeStatus; @@ -6637,7 +6637,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa StringCbCopyW (deviceName, sizeof(deviceName), szDiskFile); - if (GetDiskDeviceDriveLetter (deviceName) < 0) + if (GetDiskDeviceDriveLetter (deviceName) < 0) { // No drive letter is assigned to the device MessageBeep (MB_OK); @@ -6722,7 +6722,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { // System encryption/decryption in progress - if (AskYesNo (SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING ? + if (AskYesNo (SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING ? "SYSTEM_DECRYPTION_DEFER_CONFIRM" : "SYSTEM_ENCRYPTION_DEFER_CONFIRM", MainDlg) == IDYES) { if (nCurPageNo == SYSENC_PRETEST_RESULT_PAGE) @@ -6983,7 +6983,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { if (nMultiBoot > 1) { - // Multi-boot + // Multi-boot if (AskWarnNoYes ("MULTI_BOOT_FOR_ADVANCED_ONLY", hwndDlg) == IDNO) return 1; @@ -7027,7 +7027,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa else if (nMultiBoot <= 1) { // Single-boot (not creating a hidden OS) - + // Skip irrelevant pages nNewPageNo = CIPHER_PAGE - 1; } @@ -7049,13 +7049,13 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { // 2 or more drives contain an OS - SysEncMultiBootCfg.NumberOfSysDrives = 2; + SysEncMultiBootCfg.NumberOfSysDrives = 2; } else if (Get2RadButtonPageAnswer () == 1) { // Only 1 drive contains an OS - SysEncMultiBootCfg.NumberOfSysDrives = 1; + SysEncMultiBootCfg.NumberOfSysDrives = 1; if (bWholeSysDrive) { @@ -7236,7 +7236,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa } else { - if (CheckFileExtension(szFileName) + if (CheckFileExtension(szFileName) && AskWarnNoYes ("EXE_FILE_EXTENSION_CONFIRM", hwndDlg) == IDNO) { NormalCursor (); @@ -7406,7 +7406,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa volumePassword.Length = (unsigned __int32) strlen ((char *) volumePassword.Text); if (volumePassword.Length > 0) - { + { // Password character encoding if (SysEncInEffect () && !CheckPasswordCharEncoding (GetDlgItem (hCurPage, IDC_PASSWORD), NULL)) { @@ -7424,7 +7424,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (!GetPassword (hCurPage, IDC_PASSWORD, szRawPassword, sizeof (szRawPassword), TRUE)) return 1; - if (!SysEncInEffect ()) + if (!SysEncInEffect ()) { if (KeyFilesEnable) { @@ -7447,7 +7447,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (bKeyboardLayoutChanged) { // Restore the original keyboard layout - if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) + if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); else bKeyboardLayoutChanged = FALSE; @@ -7461,7 +7461,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa nNewPageNo = PIM_PAGE; volumePim = 0; - if (SysEncInEffect ()) + if (SysEncInEffect ()) { nNewPageNo = SYSENC_COLLECTING_RANDOM_DATA_PAGE - 1; // Skip irrelevant pages } @@ -7471,7 +7471,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa nNewPageNo = NONSYS_INPLACE_ENC_RAND_DATA_PAGE - 1; // Skip irrelevant pages } else if (WizardMode != WIZARD_MODE_SYS_DEVICE - && !FileSize4GBLimitQuestionNeeded () + && !FileSize4GBLimitQuestionNeeded () || CreatingHiddenSysVol()) // If we're creating a hidden volume for a hidden OS, we don't need to format it with any filesystem (the entire OS will be copied to the hidden volume sector by sector). { nNewPageNo = FORMAT_PAGE - 1; // Skip irrelevant pages @@ -7492,7 +7492,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa } if (volumePassword.Length > 0) - { + { // Password character encoding if (SysEncInEffect() && (volumePim > MAX_BOOT_PIM_VALUE)) { @@ -7507,7 +7507,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa } } - if (SysEncInEffect ()) + if (SysEncInEffect ()) { nNewPageNo = SYSENC_COLLECTING_RANDOM_DATA_PAGE - 1; // Skip irrelevant pages @@ -7518,7 +7518,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa nNewPageNo = NONSYS_INPLACE_ENC_RAND_DATA_PAGE - 1; // Skip irrelevant pages } else if (WizardMode != WIZARD_MODE_SYS_DEVICE - && !FileSize4GBLimitQuestionNeeded () + && !FileSize4GBLimitQuestionNeeded () || CreatingHiddenSysVol()) // If we're creating a hidden volume for a hidden OS, we don't need to format it with any filesystem (the entire OS will be copied to the hidden volume sector by sector). { nNewPageNo = FORMAT_PAGE - 1; // Skip irrelevant pages @@ -7552,7 +7552,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { KeyFilesApply (hwndDlg, &volumePassword, FirstKeyFile, NULL); } - + if (!bInPlaceEncNonSys) { @@ -7598,7 +7598,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa WaitCursor (); - // Verify that the outer volume contains a suitable file system, retrieve cluster size, and + // Verify that the outer volume contains a suitable file system, retrieve cluster size, and // scan the volume bitmap if (!IsAdmin () && IsUacSupported ()) retCode = UacAnalyzeHiddenVolumeHost (hwndDlg, &hiddenVolHostDriveNo, GetVolumeDataAreaSize (FALSE, nHiddenVolHostSize), &realClusterSize, &nbrFreeClusters); @@ -7657,7 +7657,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { hiddenVolHostDriveNo = -1; - bHiddenVolHost = FALSE; + bHiddenVolHost = FALSE; bHiddenVolFinished = FALSE; // Clear the outer volume password @@ -7682,7 +7682,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa /* Scan all available partitions to discover all partitions where non-system in-place encryption/decryption has been interrupted. */ - BOOL tmpbDevice; + BOOL tmpbDevice; NormalCursor (); @@ -7716,14 +7716,14 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa } else { - /* Try to mount the non-system volume to decrypt in place (the process has not started yet, we are NOT trying to resume it). + /* Try to mount the non-system volume to decrypt in place (the process has not started yet, we are NOT trying to resume it). We will try to mount it using the backup header, which we require to work (i.e. be non-damaged) before we start writing - to the volume (the primary header will be overwritten by decrypted data soon after the decryption process begins, so the + to the volume (the primary header will be overwritten by decrypted data soon after the decryption process begins, so the backup header will contain the only copy of the master key). */ int driveNo = -1; - // The volume may already be mounted. We need to dismount it first in order to verify the supplied password/keyfile(s) is/are correct. + // The volume may already be mounted. We need to dismount it first in order to verify the supplied password/keyfile(s) is/are correct. if (IsMountedVolume (szFileName)) { driveNo = GetMountedVolumeDriveNo (szFileName); @@ -7840,7 +7840,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (nNeedToStoreFilesOver4GB != Get2RadButtonPageAnswer()) fileSystem = FILESYS_NONE; // The user may have gone back and changed the answer, so default file system must be reselected - + nNeedToStoreFilesOver4GB = Get2RadButtonPageAnswer(); nNewPageNo = FORMAT_PAGE - 1; // Skip irrelevant pages @@ -7961,7 +7961,7 @@ retryCDDriveCheck: { wchar_t szTmp[8000]; - StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("RESCUE_DISK_CHECK_FAILED"), + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("RESCUE_DISK_CHECK_FAILED"), IsWindowsIsoBurnerAvailable () ? L"" : GetString ("RESCUE_DISK_CHECK_FAILED_SENTENCE_APPENDIX")); ErrorDirect (szTmp, hwndDlg); @@ -7990,7 +7990,7 @@ retryCDDriveCheck: else if (nCurPageNo == SYSENC_WIPE_MODE_PAGE || nCurPageNo == NONSYS_INPLACE_ENC_WIPE_MODE_PAGE) { - if (nWipeMode > 0 + if (nWipeMode > 0 && AskWarnYesNo ("WIPE_MODE_WARN", hwndDlg) == IDNO) return 1; } @@ -8002,7 +8002,7 @@ retryCDDriveCheck: return 1; bConfirmQuitSysEncPretest = TRUE; - + if (!bHiddenOS) // This text is not tailored to hidden OS TextInfoDialogBox (TC_TBXID_SYS_ENCRYPTION_PRETEST); @@ -8036,7 +8036,7 @@ retryCDDriveCheck: /* Add the main TrueCrypt app to the system startup sequence (the TrueCrypt Background Task), which - we need e.g. for notifications about prevented hibernation, about hidden OS leak protection, about + we need e.g. for notifications about prevented hibernation, about hidden OS leak protection, about inconsistent hidden OS installs (TrueCrypt upgraded in the decoy system but not in the hidden one), etc. Note that this must be done before calling ChangeSystemEncryptionStatus(), which broadcasts the change, so that the main app (if it's running with different cached settings) will not overwrite our new @@ -8049,7 +8049,7 @@ retryCDDriveCheck: if (bHiddenOS) { /* When we are going to create a hidden OS, the system encryption status is set - to SYSENC_STATUS_PRETEST (not to any special hidden-OS status), in case the XML + to SYSENC_STATUS_PRETEST (not to any special hidden-OS status), in case the XML configuration file and its properties somehow leaks somewhere outside the system partition (which will be wiped later on) indicating that a hidden OS has been created on the computer. Instead, we update our raw config flags in the master boot record @@ -8150,7 +8150,7 @@ retryCDDriveCheck: BOOL bDrvLetterAssignResult = FALSE; int tmpDriveLetter = (int) SendMessage (GetDlgItem (hCurPage, IDC_DRIVE_LETTER_LIST), - CB_GETITEMDATA, + CB_GETITEMDATA, SendMessage (GetDlgItem (hCurPage, IDC_DRIVE_LETTER_LIST), CB_GETCURSEL, 0, 0), 0); @@ -8174,7 +8174,7 @@ retryCDDriveCheck: szDriveLetter, szDiskFile); - if (bDrvLetterAssignResult) + if (bDrvLetterAssignResult) { if (SetVolumeMountPoint (rootPath, uniqVolName) == 0) bDrvLetterAssignResult = FALSE; @@ -8200,7 +8200,7 @@ retryCDDriveCheck: if (bVolTransformThreadRunning || bVolTransformThreadToRun) return 1; - + bVolTransformThreadCancel = FALSE; bVolTransformThreadToRun = TRUE; @@ -8218,7 +8218,7 @@ retryCDDriveCheck: { // Creating a non-hidden volume under a hidden OS - if (fileSystem == FILESYS_NTFS || fileSystem == FILESYS_EXFAT) + if (fileSystem == FILESYS_NTFS || fileSystem == FILESYS_EXFAT) { WarningDirect ((wstring (GetString ("CANNOT_CREATE_NON_HIDDEN_NTFS_VOLUMES_UNDER_HIDDEN_OS")) + L"\n\n" @@ -8249,7 +8249,7 @@ retryCDDriveCheck: hiddenVolHostDriveNo = -1; nMaximumHiddenVolSize = 0; - if (fileSystem == FILESYS_NTFS || fileSystem == FILESYS_EXFAT) + if (fileSystem == FILESYS_NTFS || fileSystem == FILESYS_EXFAT) { if (bHiddenOS && (fileSystem == FILESYS_NTFS) && (double) nVolumeSize / GetSystemPartitionSize() < MIN_HIDDENOS_DECOY_PARTITION_SIZE_RATIO_NTFS) @@ -8291,9 +8291,9 @@ retryCDDriveCheck: } else if (bHiddenVol) { - // Hidden volume is always quick-formatted (if, however, the meaning of quickFormat is + // Hidden volume is always quick-formatted (if, however, the meaning of quickFormat is // whether to create a sparse file, it must be set to FALSE). - quickFormat = !bSparseFileSwitch; + quickFormat = !bSparseFileSwitch; } @@ -8321,7 +8321,7 @@ retryCDDriveCheck: if (fileSystem == FILESYS_FAT && clusterSize > 0) { BOOL fixed = FALSE; - while (clusterSize < 128 + while (clusterSize < 128 && nVolumeSize / (clusterSize * GetFormatSectorSize()) > 0x2000000) { clusterSize *= 2; @@ -8350,7 +8350,7 @@ retryCDDriveCheck: return 1; // Hidden volume for hidden OS has been created. Now we will prepare our boot loader - // that will handle the OS cloning. + // that will handle the OS cloning. try { WaitCursor(); @@ -8422,7 +8422,7 @@ retryCDDriveCheck: /* Hidden volume host successfully mounted as read-only */ - // Verify that the outer volume contains a suitable file system, retrieve cluster size, and + // Verify that the outer volume contains a suitable file system, retrieve cluster size, and // scan the volume bitmap if (!IsAdmin () && IsUacSupported ()) retCode = UacAnalyzeHiddenVolumeHost (hwndDlg, &hiddenVolHostDriveNo, GetVolumeDataAreaSize (FALSE, nHiddenVolHostSize), &realClusterSize, &nbrFreeClusters); @@ -8518,9 +8518,9 @@ ovf_end: if (bHiddenOS) nNewPageNo = SYSENC_HIDDEN_OS_REQ_CHECK_PAGE + 1; else if (bWholeSysDrive) - nNewPageNo = SYSENC_PRE_DRIVE_ANALYSIS_PAGE + 1; + nNewPageNo = SYSENC_PRE_DRIVE_ANALYSIS_PAGE + 1; else - nNewPageNo = SYSENC_SPAN_PAGE + 1; + nNewPageNo = SYSENC_SPAN_PAGE + 1; } else if (nCurPageNo == SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE) { @@ -8543,7 +8543,7 @@ ovf_end: // Skip irrelevant pages. // Note that we're ignoring nMultiBoot here, as the multi-boot question pages are skipped // when creating a hidden OS (only a single message box is displayed with requirements). - nNewPageNo = SYSENC_MULTI_BOOT_MODE_PAGE + 1; + nNewPageNo = SYSENC_MULTI_BOOT_MODE_PAGE + 1; } else { @@ -8598,7 +8598,7 @@ ovf_end: nNewPageNo = SYSENC_MULTI_BOOT_MODE_PAGE + 1; // Skip irrelevant pages } else if (!bHiddenVol) - nNewPageNo = (bDevice ? DEVICE_TRANSFORM_MODE_PAGE : VOLUME_LOCATION_PAGE) + 1; + nNewPageNo = (bDevice ? DEVICE_TRANSFORM_MODE_PAGE : VOLUME_LOCATION_PAGE) + 1; else if (bHiddenVolHost) nNewPageNo = HIDDEN_VOL_HOST_PRE_CIPHER_PAGE + 1; // Skip the info on the hidden volume } @@ -8612,7 +8612,7 @@ ovf_end: { if (nNeedToStoreFilesOver4GB != Get2RadButtonPageAnswer()) fileSystem = FILESYS_NONE; // The user may have gone back and changed the answer, so default file system must be reselected - + nNeedToStoreFilesOver4GB = Get2RadButtonPageAnswer(); nNewPageNo = (PimEnable? PIM_PAGE : PASSWORD_PAGE) + 1; // Skip PIM page if it is not enabled @@ -8644,7 +8644,7 @@ ovf_end: if (bKeyboardLayoutChanged) { // Restore the original keyboard layout - if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) + if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); else bKeyboardLayoutChanged = FALSE; @@ -8728,7 +8728,7 @@ ovf_end: nNewPageNo = FILESYS_PAGE + 1; } else - nNewPageNo = (PimEnable? PIM_PAGE : PASSWORD_PAGE) + 1; + nNewPageNo = (PimEnable? PIM_PAGE : PASSWORD_PAGE) + 1; } } @@ -8818,15 +8818,15 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) { OptionDynamic, L"/dynamic", NULL, FALSE }, { OptionForce, L"/force", NULL, FALSE }, - // Internal + // Internal { CommandResumeSysEncLogOn, L"/acsysenc", L"/a", TRUE }, { CommandResumeSysEnc, L"/csysenc", L"/c", TRUE }, { CommandDecryptSysEnc, L"/dsysenc", L"/d", TRUE }, { CommandEncDev, L"/encdev", L"/e", TRUE }, - { CommandHiddenSys, L"/isysenc", L"/i", TRUE }, + { CommandHiddenSys, L"/isysenc", L"/i", TRUE }, { CommandResumeNonSysInplaceLogOn, L"/prinplace", L"/p", TRUE }, - { CommandResumeHiddenSys, L"/risysenc", L"/r", TRUE }, - { CommandSysEnc, L"/sysenc", L"/s", TRUE }, + { CommandResumeHiddenSys, L"/risysenc", L"/r", TRUE }, + { CommandSysEnc, L"/sysenc", L"/s", TRUE }, { CommandInplaceDec, L"/inplacedec", NULL, TRUE }, { CommandResumeInplaceDec, L"/resumeinplacedec",NULL, TRUE }, { CommandResumeInplace, L"/zinplace", L"/z", TRUE } @@ -8841,7 +8841,7 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) as.args = args; as.arg_cnt = sizeof(args)/ sizeof(args[0]); - + x = GetArgumentID (&as, lpszCommandLineArgs[i]); switch (x) @@ -8907,7 +8907,7 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) if (iLen > 0) CmdVolumePassword.Length = (unsigned __int32) (iLen - 1); else - AbortProcess ("COMMAND_LINE_ERROR"); + AbortProcess ("COMMAND_LINE_ERROR"); } else AbortProcess ("COMMAND_LINE_ERROR"); @@ -8971,7 +8971,7 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) { wchar_t szTmp[32] = {0}; if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, - &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp)) + &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp)) && (wcslen (szTmp) >= 2) ) { @@ -8998,7 +8998,7 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) szTmp [wcslen (szTmp) - 1] = 0; CmdVolumeFileSize = _wcstoui64(szTmp, &endPtr, 0); - if (CmdVolumeFileSize == 0 || CmdVolumeFileSize == _UI64_MAX + if (CmdVolumeFileSize == 0 || CmdVolumeFileSize == _UI64_MAX || endPtr == szTmp || *endPtr != L'\0') { AbortProcess ("COMMAND_LINE_ERROR"); @@ -9082,7 +9082,7 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) break; case CommandResumeSysEnc: - // Resume previous system-encryption operation (passed by Mount) e.g. encryption, decryption, or pretest + // Resume previous system-encryption operation (passed by Mount) e.g. encryption, decryption, or pretest // From now on, we should be the only instance of the TC wizard allowed to deal with system encryption if (CreateSysEncMutex ()) @@ -9181,7 +9181,7 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) } } break; - + case OptionTokenLib: if (GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, SecurityTokenLibraryPath, ARRAYSIZE (SecurityTokenLibraryPath)) == HAS_ARGUMENT) InitSecurityTokenLibrary(hwndDlg); @@ -9353,7 +9353,7 @@ int AnalyzeHiddenVolumeHost (HWND hwndDlg, int *driveNo, __int64 hiddenVolHostSi // FAT12/FAT16/FAT32 // Retrieve the cluster size - *realClusterSize = ((int) readBuffer[0xb] + ((int) readBuffer[0xc] << 8)) * (int) readBuffer[0xd]; + *realClusterSize = ((int) readBuffer[0xb] + ((int) readBuffer[0xc] << 8)) * (int) readBuffer[0xd]; // Get the map of the clusters that are free and in use on the outer volume. // The map will be scanned to determine the size of the uninterrupted block of free @@ -9379,10 +9379,10 @@ int AnalyzeHiddenVolumeHost (HWND hwndDlg, int *driveNo, __int64 hiddenVolHostSi if (bIsNtfs && bHiddenVolDirect && GetVolumeDataAreaSize (FALSE, hiddenVolHostSize) <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize()) Info ("HIDDEN_VOL_HOST_NTFS", hwndDlg); - if (!GetDiskFreeSpace(szRootPathName, - &dwSectorsPerCluster, - &dwBytesPerSector, - &dwNumberOfFreeClusters, + if (!GetDiskFreeSpace(szRootPathName, + &dwSectorsPerCluster, + &dwBytesPerSector, + &dwNumberOfFreeClusters, &dwTotalNumberOfClusters)) { handleWin32Error (hwndDlg, SRC_POS); @@ -9494,7 +9494,7 @@ int ScanVolClusterBitmap (HWND hwndDlg, int *driveNo, __int64 nbrClusters, __int &lpInBuffer, sizeof(lpInBuffer), lpOutBuffer, - bufLen, + bufLen, &lBytesReturned, NULL)) { @@ -9506,7 +9506,7 @@ int ScanVolClusterBitmap (HWND hwndDlg, int *driveNo, __int64 nbrClusters, __int rmnd = (BYTE) (lpOutBuffer->BitmapSize.QuadPart % 8); - if ((rmnd != 0) + if ((rmnd != 0) && ((lpOutBuffer->Buffer[lpOutBuffer->BitmapSize.QuadPart / 8] & ((1 << rmnd)-1) ) != 0)) { *nbrFreeClusters = 0; @@ -9521,9 +9521,9 @@ int ScanVolClusterBitmap (HWND hwndDlg, int *driveNo, __int64 nbrClusters, __int { if (lpOutBuffer->Buffer[bitmapCnt] != 0) { - // There might be up to 7 extra free clusters in this byte of the bitmap. + // There might be up to 7 extra free clusters in this byte of the bitmap. // These are ignored because there is always a cluster reserve added anyway. - *nbrFreeClusters = lpOutBuffer->BitmapSize.QuadPart - ((bitmapCnt + 1) * 8); + *nbrFreeClusters = lpOutBuffer->BitmapSize.QuadPart - ((bitmapCnt + 1) * 8); break; } } @@ -9566,7 +9566,7 @@ static BOOL WipeHiddenOSCreationConfig (void) // Tasks that need to be performed after the WM_INITDIALOG message for the SYSENC_ENCRYPTION_PAGE dialog is -// handled should be done here (otherwise the UAC prompt causes the GUI to be only half-rendered). +// handled should be done here (otherwise the UAC prompt causes the GUI to be only half-rendered). static void AfterSysEncProgressWMInitTasks (HWND hwndDlg) { try @@ -9625,7 +9625,7 @@ static void AfterSysEncProgressWMInitTasks (HWND hwndDlg) } -// Tasks that need to be performed after the WM_INITDIALOG message is handled must be done here. +// Tasks that need to be performed after the WM_INITDIALOG message is handled must be done here. // For example, any tasks that may invoke the UAC prompt (otherwise the UAC dialog box would not be on top). static void AfterWMInitTasks (HWND hwndDlg) { @@ -9675,14 +9675,14 @@ static void AfterWMInitTasks (HWND hwndDlg) } else if (bDirectSysEncMode) { - // This is an inconsistent state. We have a direct system encryption command, + // This is an inconsistent state. We have a direct system encryption command, // SystemEncryptionStatus is SYSENC_STATUS_ENCRYPTING or SYSENC_STATUS_DECRYPTING, the // system drive is not 'mounted' and drive filter is active. Possible causes: 1) The drive had // been decrypted in the pre-boot environment. 2) The OS is not located on the lowest partition, - // the drive is to be fully encrypted, but the user rebooted before encryption reached the + // the drive is to be fully encrypted, but the user rebooted before encryption reached the // system partition and then pressed Esc in the boot loader screen. 3) Corrupted or stale config // file. 4) Damaged system. - + Warning ("SYSTEM_ENCRYPTION_SCHEDULED_BUT_PBA_FAILED", hwndDlg); EndMainDlg (MainDlg); return; @@ -9721,7 +9721,7 @@ static void AfterWMInitTasks (HWND hwndDlg) { // If the config file with status was lost or not written correctly, we // don't know whether to encrypt or decrypt (but we know that encryption or - // decryption is required). Ask the user to select encryption, decryption, + // decryption is required). Ask the user to select encryption, decryption, // or cancel if (!ResolveUnknownSysEncDirection ()) { @@ -9755,7 +9755,7 @@ static void AfterWMInitTasks (HWND hwndDlg) if (SysEncryptionOrDecryptionRequired ()) { // System partition/drive encryption process already initiated but is incomplete. - // If we were encrypting, resume the process directly. If we were decrypting, reverse + // If we were encrypting, resume the process directly. If we were decrypting, reverse // the process and start encrypting. ChangeSystemEncryptionStatus (SYSENC_STATUS_ENCRYPTING); @@ -9829,12 +9829,12 @@ static void AfterWMInitTasks (HWND hwndDlg) } else if ((SystemEncryptionStatus == SYSENC_STATUS_NONE || SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING) - && !BootEncStatus.DriveEncrypted + && !BootEncStatus.DriveEncrypted && (BootEncStatus.DriveMounted || BootEncStatus.VolumeHeaderPresent)) { // The pretest may have been in progress but we can't be sure (it is not in the config file). // Another possibility is that the user had finished decrypting the drive, but the config file - // was not correctly updated. In both cases the best thing we can do is remove the header and + // was not correctly updated. In both cases the best thing we can do is remove the header and // deinstall. Otherwise, the result might be some kind of deadlock. if (CreateSysEncMutex ()) // If no other instance is currently taking care of system encryption @@ -9853,8 +9853,8 @@ static void AfterWMInitTasks (HWND hwndDlg) if (bDirectSysEncMode && CreateSysEncMutex ()) { - // We were launched either by Mount or by the system (startup sequence). Most of such cases should have - // been handled above already. Here we handle only the pretest phase (which can also be a hidden OS + // We were launched either by Mount or by the system (startup sequence). Most of such cases should have + // been handled above already. Here we handle only the pretest phase (which can also be a hidden OS // creation phase actually) and possible inconsistencies. switch (SystemEncryptionStatus) @@ -9893,7 +9893,7 @@ static void AfterWMInitTasks (HWND hwndDlg) { // The hidden OS has been booted for the first time since the user started installing a // new decoy OS (presumably, our MBR config flags have been erased). - + // As for things we are responsible for, the process of hidden OS creation is completed // (the rest is up to the user). @@ -9901,7 +9901,7 @@ static void AfterWMInitTasks (HWND hwndDlg) ChangeSystemEncryptionStatus (SYSENC_STATUS_NONE); EndMainDlg (MainDlg); - + return; } @@ -9938,7 +9938,7 @@ static void AfterWMInitTasks (HWND hwndDlg) { BOOL bAnswerTerminate = FALSE, bAnswerRetry = FALSE; - /* Pretest failed + /* Pretest failed or hidden OS cloning has been interrupted (and non-hidden OS is running) or wiping of the original OS has not been started (and non-hidden OS is running) */ @@ -9962,7 +9962,7 @@ static void AfterWMInitTasks (HWND hwndDlg) else { // Hidden OS cloning was interrupted or wiping of the original OS has not been started - + char *tmpStr[] = {0, hiddenOSCreationPhase == TC_HIDDEN_OS_CREATION_PHASE_WIPING ? "OS_WIPING_NOT_FINISHED_ASK" : "HIDDEN_OS_CREATION_NOT_FINISHED_ASK", "HIDDEN_OS_CREATION_NOT_FINISHED_CHOICE_RETRY", @@ -9998,7 +9998,7 @@ static void AfterWMInitTasks (HWND hwndDlg) // We re-register the driver for boot because the user may have selected // "Last Known Good Configuration" from the Windows boot menu. - // Note that we need to do this even when creating a hidden OS (because + // Note that we need to do this even when creating a hidden OS (because // the hidden OS needs our boot driver and it will be a clone of this OS). try { @@ -10047,7 +10047,7 @@ static void AfterWMInitTasks (HWND hwndDlg) EndMainDlg (MainDlg); return; } - else + else { // User doesn't want to take any action now @@ -10180,7 +10180,7 @@ int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpsz if (Randinit ()) { DWORD dwLastError = GetLastError (); - wchar_t szTmp[4096]; + wchar_t szTmp[4096]; if (CryptoAPILastError == ERROR_SUCCESS) StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("INIT_RAND"), SRC_POS, dwLastError); else @@ -10208,7 +10208,7 @@ int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpsz AbortProcess ("ERR_SELF_TESTS_FAILED"); /* Create the main dialog box */ - DialogBoxParamW (hInstance, MAKEINTRESOURCEW (IDD_VOL_CREATION_WIZARD_DLG), NULL, (DLGPROC) MainDialogProc, + DialogBoxParamW (hInstance, MAKEINTRESOURCEW (IDD_VOL_CREATION_WIZARD_DLG), NULL, (DLGPROC) MainDialogProc, (LPARAM)lpszCommandLine); FinalizeApp (); diff --git a/src/Format/Tcformat.h b/src/Format/Tcformat.h index c45e6916..14b0ff1c 100644 --- a/src/Format/Tcformat.h +++ b/src/Format/Tcformat.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/License.txt b/src/License.txt index 44c0c657..dc686dd1 100644 --- a/src/License.txt +++ b/src/License.txt @@ -8,16 +8,16 @@ BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE SOFTWARE, NOR ANY PART(S) THEREOF. -VeraCrypt is multi-licensed under Apache License 2.0 and -the TrueCrypt License version 3.0, a verbatim copy of both +VeraCrypt is multi-licensed under Apache License 2.0 and +the TrueCrypt License version 3.0, a verbatim copy of both licenses can be found below. -This license does not grant you rights to use any -contributors' name, logo, or trademarks, including IDRIX, +This license does not grant you rights to use any +contributors' name, logo, or trademarks, including IDRIX, VeraCrypt and all derivative names. -For example, the following names are not allowed: VeraCrypt, -VeraCrypt+, VeraCrypt Professional, iVeraCrypt, etc. Nor any -other names confusingly similar to the name VeraCrypt (e.g., +For example, the following names are not allowed: VeraCrypt, +VeraCrypt+, VeraCrypt Professional, iVeraCrypt, etc. Nor any +other names confusingly similar to the name VeraCrypt (e.g., Vera-Crypt, Vera Crypt, VerKrypt, etc.) ____________________________________________________________ diff --git a/src/Main/Application.h b/src/Main/Application.h index 23d281b6..b961ef4e 100644 --- a/src/Main/Application.h +++ b/src/Main/Application.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/CommandLineInterface.cpp b/src/Main/CommandLineInterface.cpp index e48a495f..0a4f41b3 100644 --- a/src/Main/CommandLineInterface.cpp +++ b/src/Main/CommandLineInterface.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -104,7 +104,7 @@ namespace VeraCrypt if (parser.Parse () > 0) throw_err (_("Incorrect command line specified.")); - + if (parser.Found (L"help")) { ArgCommand = CommandId::Help; @@ -192,7 +192,7 @@ namespace VeraCrypt ArgCommand = CommandId::CreateKeyfile; param1IsFile = true; } - + if (parser.Found (L"delete-token-keyfiles")) { CheckCommandSingle(); @@ -205,7 +205,7 @@ namespace VeraCrypt ArgCommand = CommandId::DismountVolumes; param1IsMountedVolumeSpec = true; } - + if (parser.Found (L"export-token-keyfile")) { CheckCommandSingle(); @@ -294,7 +294,7 @@ namespace VeraCrypt else { ArgMountOptions.FilesystemType = wstring (str); - + if (str.IsSameAs (L"FAT", false)) ArgFilesystem = VolumeCreationOptions::FilesystemType::FAT; #ifdef TC_LINUX @@ -309,7 +309,7 @@ namespace VeraCrypt else if (str.IsSameAs (L"exFAT", false)) ArgFilesystem = VolumeCreationOptions::FilesystemType::exFAT; #elif defined (TC_MACOSX) - else if ( str.IsSameAs (L"HFS", false) + else if ( str.IsSameAs (L"HFS", false) || str.IsSameAs (L"HFS+", false) || str.IsSameAs (L"MacOsExt", false) ) @@ -328,7 +328,7 @@ namespace VeraCrypt } ArgForce = parser.Found (L"force"); - + ArgTrueCryptMode = parser.Found (L"truecrypt"); #if !defined(TC_WINDOWS) && !defined(TC_MACOSX) @@ -402,7 +402,7 @@ namespace VeraCrypt if (parser.Found (L"new-password", &str)) ArgNewPassword = ToUTF8Password (str.c_str()); - + if (parser.Found (L"new-pim", &str)) { try @@ -419,7 +419,7 @@ namespace VeraCrypt else if (ArgNewPim > 0 && ArgTrueCryptMode) throw_err (LangString["PIM_NOT_SUPPORTED_FOR_TRUECRYPT_MODE"]); } - + if (parser.Found (L"non-interactive")) { if (interfaceType != UserInterfaceType::Text) @@ -478,13 +478,13 @@ namespace VeraCrypt ArgMountOptions.ProtectionKeyfiles = ToKeyfileList (str); ArgMountOptions.Protection = VolumeProtection::HiddenVolumeReadOnly; } - + if (parser.Found (L"protection-password", &str)) { ArgMountOptions.ProtectionPassword = ToUTF8Password (str.c_str()); ArgMountOptions.Protection = VolumeProtection::HiddenVolumeReadOnly; } - + if (parser.Found (L"protection-pim", &str)) { int pim = -1; @@ -609,7 +609,7 @@ namespace VeraCrypt // Parameters if (parser.GetParamCount() > 0) { - // in case of GUI interface, we load the preference when only + // in case of GUI interface, we load the preference when only // specifying volume path without any option/switch if (Application::GetUserInterfaceType() != UserInterfaceType::Text) { @@ -634,7 +634,7 @@ namespace VeraCrypt if (param1IsVolume) { wxFileName volPath (parser.GetParam (0)); - + #ifdef TC_WINDOWS if (!parser.GetParam (0).StartsWith (L"\\Device\\")) #endif @@ -699,7 +699,7 @@ namespace VeraCrypt continue; } } - + if (token.empty() && !tokenizer.HasMoreTokens()) break; @@ -758,7 +758,7 @@ namespace VeraCrypt filteredVolumes.push_back (volume); } } - + if (!mountedVolumeSpec.IsEmpty() && filteredVolumes.size() < 1) throw_err (_("No such volume is mounted.")); diff --git a/src/Main/CommandLineInterface.h b/src/Main/CommandLineInterface.h index ee6566d5..9bca2614 100644 --- a/src/Main/CommandLineInterface.h +++ b/src/Main/CommandLineInterface.h @@ -3,7 +3,7 @@ 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) + 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 @@ -95,7 +95,7 @@ namespace VeraCrypt CommandLineInterface (const CommandLineInterface &); CommandLineInterface &operator= (const CommandLineInterface &); }; - + shared_ptr ToUTF8Password (const wchar_t* str, size_t charCount = (size_t) -1); shared_ptr ToUTF8Buffer (const wchar_t* str, size_t charCount = (size_t) -1); diff --git a/src/Main/FatalErrorHandler.cpp b/src/Main/FatalErrorHandler.cpp index 5bea2dd9..37a10e73 100644 --- a/src/Main/FatalErrorHandler.cpp +++ b/src/Main/FatalErrorHandler.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -111,7 +111,7 @@ namespace VeraCrypt std::set_terminate (DefaultTerminateHandler); #endif } - + uint32 FatalErrorHandler::GetAppChecksum () { uint32 checkSum = 0; @@ -130,7 +130,7 @@ namespace VeraCrypt } wstring FatalErrorHandler::GetCallStack (int depth) - { + { #if wxUSE_STACKWALKER == 1 class StackWalker : public wxStackWalker @@ -176,7 +176,7 @@ namespace VeraCrypt return stackWalker.StackVars.str(); #else // wxUSE_STACKWALKER - + return wstring(); #endif // wxUSE_STACKWALKER diff --git a/src/Main/FatalErrorHandler.h b/src/Main/FatalErrorHandler.h index bed16fa2..92139655 100644 --- a/src/Main/FatalErrorHandler.h +++ b/src/Main/FatalErrorHandler.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/FavoriteVolume.cpp b/src/Main/FavoriteVolume.cpp index e88bcd2f..9022d601 100644 --- a/src/Main/FavoriteVolume.cpp +++ b/src/Main/FavoriteVolume.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -31,7 +31,7 @@ namespace VeraCrypt wstring attr = wstring (node.Attributes[L"slotnumber"]); if (!attr.empty()) slotNumber = StringConverter::ToUInt64 (attr); - + bool readOnly = false; attr = wstring (node.Attributes[L"readonly"]); if (!attr.empty()) diff --git a/src/Main/FavoriteVolume.h b/src/Main/FavoriteVolume.h index 64055b4d..2a902c30 100644 --- a/src/Main/FavoriteVolume.h +++ b/src/Main/FavoriteVolume.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/AboutDialog.cpp b/src/Main/Forms/AboutDialog.cpp index e32c6263..8949673c 100644 --- a/src/Main/Forms/AboutDialog.cpp +++ b/src/Main/Forms/AboutDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/AboutDialog.h b/src/Main/Forms/AboutDialog.h index e481a12e..53dfdcb3 100644 --- a/src/Main/Forms/AboutDialog.h +++ b/src/Main/Forms/AboutDialog.h @@ -3,7 +3,7 @@ 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) + 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 @@ -21,7 +21,7 @@ namespace VeraCrypt { public: AboutDialog (wxWindow* parent); - + void OnWebsiteHyperlinkClick (wxHyperlinkEvent& event) { Gui->OpenHomepageLink (this, L"main"); } }; } diff --git a/src/Main/Forms/BenchmarkDialog.cpp b/src/Main/Forms/BenchmarkDialog.cpp index 0f497650..95e225e2 100644 --- a/src/Main/Forms/BenchmarkDialog.cpp +++ b/src/Main/Forms/BenchmarkDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -68,7 +68,7 @@ namespace VeraCrypt wxBusyCursor busy; Buffer buffer ((size_t) Gui->GetSelectedData (BufferSizeChoice)); - + BenchmarkThreadRoutine routine(this, results, buffer); Gui->ExecuteWaitThreadRoutine (this, &routine); @@ -77,7 +77,7 @@ namespace VeraCrypt foreach (const BenchmarkResult &result, results) { vector fields (BenchmarkListCtrl->GetColumnCount()); - + fields[ColumnAlgorithm] = result.AlgorithmName; fields[ColumnEncryption] = Gui->SpeedToString (result.EncryptionSpeed); fields[ColumnDecryption] = Gui->SpeedToString (result.DecryptionSpeed); @@ -85,10 +85,10 @@ namespace VeraCrypt Gui->AppendToListCtrl (BenchmarkListCtrl, fields); } - + BenchmarkListCtrl->SetColumnWidth(0, wxLIST_AUTOSIZE); } - + void BenchmarkDialog::DoBenchmark (list& results, Buffer& buffer) { try diff --git a/src/Main/Forms/BenchmarkDialog.h b/src/Main/Forms/BenchmarkDialog.h index 228bbf21..403f3839 100644 --- a/src/Main/Forms/BenchmarkDialog.h +++ b/src/Main/Forms/BenchmarkDialog.h @@ -3,7 +3,7 @@ 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) + 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 @@ -42,7 +42,7 @@ namespace VeraCrypt void DoBenchmark (list& results, Buffer& buffer); void OnBenchmarkButtonClick (wxCommandEvent& event); - + class BenchmarkThreadRoutine : public WaitThreadRoutine { public: diff --git a/src/Main/Forms/ChangePasswordDialog.cpp b/src/Main/Forms/ChangePasswordDialog.cpp index b3e0bd04..ac8e8147 100644 --- a/src/Main/Forms/ChangePasswordDialog.cpp +++ b/src/Main/Forms/ChangePasswordDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -59,7 +59,7 @@ namespace VeraCrypt NewPasswordPanel = new VolumePasswordPanel (this, NULL, newPassword, true, newKeyfiles, false, enableNewPassword, enableNewKeyfiles, enableNewPassword, enablePkcs5Prf); NewPasswordPanel->UpdateEvent.Connect (EventConnector (this, &ChangePasswordDialog::OnPasswordPanelUpdate)); NewPasswordPanelSizer->Add (NewPasswordPanel, 1, wxALL | wxEXPAND); - + if (mode == Mode::RemoveAllKeyfiles) NewSizer->Show (false); @@ -98,7 +98,7 @@ namespace VeraCrypt CurrentPasswordPanel->SetFocusToPimTextCtrl(); return; } - + shared_ptr newPassword; int newPim = 0; if (DialogMode == Mode::ChangePasswordAndKeyfiles) @@ -110,7 +110,7 @@ namespace VeraCrypt catch (PasswordException& e) { Gui->ShowWarning (e); - NewPasswordPanel->SetFocusToPasswordTextCtrl(); + NewPasswordPanel->SetFocusToPasswordTextCtrl(); return; } newPim = NewPasswordPanel->GetVolumePim(); @@ -126,7 +126,7 @@ namespace VeraCrypt { if (newPim > 0 && newPim < 485) { - Gui->ShowError ("PIM_REQUIRE_LONG_PASSWORD"); + Gui->ShowError ("PIM_REQUIRE_LONG_PASSWORD"); return; } @@ -235,7 +235,7 @@ namespace VeraCrypt if (passwordEmpty && keyfilesEmpty) ok = false; - + if (CurrentPasswordPanel->GetVolumePim () == -1) ok = false; @@ -251,7 +251,7 @@ namespace VeraCrypt ok = false; if (DialogMode == Mode::ChangePasswordAndKeyfiles - && ( (NewPasswordPanel->GetPassword()->IsEmpty() && newKeyfilesEmpty) + && ( (NewPasswordPanel->GetPassword()->IsEmpty() && newKeyfilesEmpty) || !NewPasswordPanel->PasswordsMatch() || (NewPasswordPanel->GetVolumePim() == -1) ) @@ -265,12 +265,12 @@ namespace VeraCrypt } OKButton->Enable (ok); - + if (DialogMode == Mode::ChangePasswordAndKeyfiles) { bool pimChanged = (CurrentPasswordPanel->GetVolumePim() != NewPasswordPanel->GetVolumePim()); NewPasswordPanel->UpdatePimHelpText(pimChanged); } - + } } diff --git a/src/Main/Forms/ChangePasswordDialog.h b/src/Main/Forms/ChangePasswordDialog.h index 6caaaeab..2ba83991 100644 --- a/src/Main/Forms/ChangePasswordDialog.h +++ b/src/Main/Forms/ChangePasswordDialog.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/DeviceSelectionDialog.cpp b/src/Main/Forms/DeviceSelectionDialog.cpp index 9d706239..764edf3a 100644 --- a/src/Main/Forms/DeviceSelectionDialog.cpp +++ b/src/Main/Forms/DeviceSelectionDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -39,7 +39,7 @@ namespace VeraCrypt DeviceListCtrl->InsertColumn (ColumnMountPoint, LangString["MOUNT_POINT"], wxLIST_FORMAT_LEFT, 1); colPermilles.push_back (396); #endif - + wxImageList *imageList = new wxImageList (16, 12, true); imageList->Add (Resources::GetDriveIconBitmap(), Resources::GetDriveIconMaskBitmap()); DeviceListCtrl->AssignImageList (imageList, wxIMAGE_LIST_SMALL); @@ -65,13 +65,13 @@ namespace VeraCrypt fields[ColumnMountPoint] = device.MountPoint; #endif fields[ColumnSize] = Gui->SizeToString (device.Size); - Gui->AppendToListCtrl (DeviceListCtrl, fields, 0, &device); + Gui->AppendToListCtrl (DeviceListCtrl, fields, 0, &device); foreach_ref (HostDevice &partition, device.Partitions) { - fields[ColumnDevice] = + fields[ColumnDevice] = #ifndef TC_WINDOWS - wstring (L" ") + + wstring (L" ") + #endif wstring (partition.Path); @@ -97,7 +97,7 @@ namespace VeraCrypt StdButtonsOK->Disable(); StdButtonsOK->SetDefault(); } - + void DeviceSelectionDialog::OnListItemActivated (wxListEvent& event) { if (StdButtonsOK->IsEnabled()) diff --git a/src/Main/Forms/DeviceSelectionDialog.h b/src/Main/Forms/DeviceSelectionDialog.h index db19e150..76aaa6f2 100644 --- a/src/Main/Forms/DeviceSelectionDialog.h +++ b/src/Main/Forms/DeviceSelectionDialog.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/EncryptionOptionsWizardPage.cpp b/src/Main/Forms/EncryptionOptionsWizardPage.cpp index cedc9371..5af01d02 100644 --- a/src/Main/Forms/EncryptionOptionsWizardPage.cpp +++ b/src/Main/Forms/EncryptionOptionsWizardPage.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -32,7 +32,7 @@ namespace VeraCrypt } EncryptionAlgorithmChoice->Select (0); - + Hashes = Hash::GetAvailableAlgorithms(); foreach (shared_ptr hash, Hashes) { @@ -117,7 +117,7 @@ namespace VeraCrypt { Gui->OpenHomepageLink (this, L"hashalgorithms"); } - + void EncryptionOptionsWizardPage::OnTestButtonClick (wxCommandEvent& event) { EncryptionTestDialog dialog (this); diff --git a/src/Main/Forms/EncryptionOptionsWizardPage.h b/src/Main/Forms/EncryptionOptionsWizardPage.h index f9df752b..58a7b5dd 100644 --- a/src/Main/Forms/EncryptionOptionsWizardPage.h +++ b/src/Main/Forms/EncryptionOptionsWizardPage.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/EncryptionTestDialog.cpp b/src/Main/Forms/EncryptionTestDialog.cpp index 9d0b2ca3..36982340 100644 --- a/src/Main/Forms/EncryptionTestDialog.cpp +++ b/src/Main/Forms/EncryptionTestDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -46,7 +46,7 @@ namespace VeraCrypt Buffer key; GetTextCtrlData (KeyTextCtrl, key); - + if (key.Size() != ea->GetKeySize()) throw_err (LangString["TEST_KEY_SIZE"]); @@ -100,7 +100,7 @@ namespace VeraCrypt Buffer sector (ENCRYPTION_DATA_UNIT_SIZE); BufferPtr block = sector.GetRange (blockNumber * ea->GetMaxBlockSize(), ea->GetMaxBlockSize()); - + block.CopyFrom (data); if (encrypt) @@ -130,7 +130,7 @@ namespace VeraCrypt { return Gui->GetSelectedData (EncryptionAlgorithmChoice)->GetNew(); } - + void EncryptionTestDialog::GetTextCtrlData (wxTextCtrl *textCtrl, Buffer &buffer) const { vector data; diff --git a/src/Main/Forms/EncryptionTestDialog.h b/src/Main/Forms/EncryptionTestDialog.h index fc4551a1..1d0ccfbd 100644 --- a/src/Main/Forms/EncryptionTestDialog.h +++ b/src/Main/Forms/EncryptionTestDialog.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/FavoriteVolumesDialog.cpp b/src/Main/Forms/FavoriteVolumesDialog.cpp index 858339e7..f6d5f7b5 100644 --- a/src/Main/Forms/FavoriteVolumesDialog.cpp +++ b/src/Main/Forms/FavoriteVolumesDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -32,7 +32,7 @@ namespace VeraCrypt Layout(); Fit(); Center(); - + #ifdef TC_MACOSX // wxMac cannot insert items to wxListCtrl due to a bug MoveUpButton->Show (false); @@ -46,7 +46,7 @@ namespace VeraCrypt fields[ColumnVolumePath] = favorite->Path; fields[ColumnMountPoint] = favorite->MountPoint; Gui->AppendToListCtrl (FavoritesListCtrl, fields, -1, favorite.get()); - + if (++itemCount > Favorites.size() - newItemCount) { FavoritesListCtrl->SetItemState (itemCount - 1, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED); @@ -57,7 +57,7 @@ namespace VeraCrypt UpdateButtons(); FavoritesListCtrl->SetFocus(); } - + void FavoriteVolumesDialog::OnMoveDownButtonClick (wxCommandEvent& event) { FreezeScope freeze (this); diff --git a/src/Main/Forms/FavoriteVolumesDialog.h b/src/Main/Forms/FavoriteVolumesDialog.h index 8da274e1..bff08e97 100644 --- a/src/Main/Forms/FavoriteVolumesDialog.h +++ b/src/Main/Forms/FavoriteVolumesDialog.h @@ -3,7 +3,7 @@ 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) + 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 @@ -35,7 +35,7 @@ namespace VeraCrypt void OnRemoveAllButtonClick (wxCommandEvent& event); void OnRemoveButtonClick (wxCommandEvent& event); void UpdateButtons (); - + enum { ColumnVolumePath = 0, diff --git a/src/Main/Forms/Forms.cpp b/src/Main/Forms/Forms.cpp index 3f0fcc9e..3b6dc2cc 100644 --- a/src/Main/Forms/Forms.cpp +++ b/src/Main/Forms/Forms.cpp @@ -15,395 +15,395 @@ using namespace VeraCrypt; MainFrameBase::MainFrameBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style ) { this->SetSizeHints( wxSize( -1,496 ), wxDefaultSize ); - + MainMenuBar = new wxMenuBar( 0 ); VolumesMenu = new wxMenu(); wxMenuItem* CreateNewVolumeMenuItem; CreateNewVolumeMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Create New Volume...") ) , wxEmptyString, wxITEM_NORMAL ); VolumesMenu->Append( CreateNewVolumeMenuItem ); - + VolumesMenu->AppendSeparator(); - + MountVolumeMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Mount Volume") ) , wxEmptyString, wxITEM_NORMAL ); VolumesMenu->Append( MountVolumeMenuItem ); - + wxMenuItem* AutoMountDevicesMenuItem; AutoMountDevicesMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Auto-Mount All Device-Hosted Volumes") ) , wxEmptyString, wxITEM_NORMAL ); VolumesMenu->Append( AutoMountDevicesMenuItem ); - + VolumesMenu->AppendSeparator(); - + DismountVolumeMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Dismount Volume") ) , wxEmptyString, wxITEM_NORMAL ); VolumesMenu->Append( DismountVolumeMenuItem ); - + DismountAllMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Dismount All Mounted Volumes") ) , wxEmptyString, wxITEM_NORMAL ); VolumesMenu->Append( DismountAllMenuItem ); - + VolumesMenu->AppendSeparator(); - + wxMenuItem* ChangePasswordMenuItem; ChangePasswordMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Change Volume Password...") ) , wxEmptyString, wxITEM_NORMAL ); VolumesMenu->Append( ChangePasswordMenuItem ); - + wxMenuItem* ChangePkcs5PrfMenuItem; ChangePkcs5PrfMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Change Header Key Derivation Algorithm...") ) , wxEmptyString, wxITEM_NORMAL ); VolumesMenu->Append( ChangePkcs5PrfMenuItem ); - + wxMenuItem* ChangeKeyfilesMenuItem; ChangeKeyfilesMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Add/Remove Keyfiles to/from Volume...") ) , wxEmptyString, wxITEM_NORMAL ); VolumesMenu->Append( ChangeKeyfilesMenuItem ); - + wxMenuItem* RemoveKeyfilesMenuItem; RemoveKeyfilesMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Remove All Keyfiles from Volume...") ) , wxEmptyString, wxITEM_NORMAL ); VolumesMenu->Append( RemoveKeyfilesMenuItem ); - + VolumesMenu->AppendSeparator(); - + VolumePropertiesMenuItem = new wxMenuItem( VolumesMenu, wxID_ANY, wxString( _("Volume Properties...") ) , wxEmptyString, wxITEM_NORMAL ); VolumesMenu->Append( VolumePropertiesMenuItem ); - - MainMenuBar->Append( VolumesMenu, _("&Volumes") ); - + + MainMenuBar->Append( VolumesMenu, _("&Volumes") ); + FavoritesMenu = new wxMenu(); AddToFavoritesMenuItem = new wxMenuItem( FavoritesMenu, wxID_ANY, wxString( _("Add Selected Volume to Favorites...") ) , wxEmptyString, wxITEM_NORMAL ); FavoritesMenu->Append( AddToFavoritesMenuItem ); - + AddAllMountedToFavoritesMenuItem = new wxMenuItem( FavoritesMenu, wxID_ANY, wxString( _("Add All Mounted Volumes to Favorites...") ) , wxEmptyString, wxITEM_NORMAL ); FavoritesMenu->Append( AddAllMountedToFavoritesMenuItem ); - + wxMenuItem* OrganizeFavoritesMenuItem; OrganizeFavoritesMenuItem = new wxMenuItem( FavoritesMenu, wxID_ANY, wxString( _("Organize Favorite Volumes...") ) , wxEmptyString, wxITEM_NORMAL ); FavoritesMenu->Append( OrganizeFavoritesMenuItem ); - + FavoritesMenu->AppendSeparator(); - + wxMenuItem* MountAllFavoritesMenuItem; MountAllFavoritesMenuItem = new wxMenuItem( FavoritesMenu, wxID_ANY, wxString( _("Mount Favorite Volumes") ) , wxEmptyString, wxITEM_NORMAL ); FavoritesMenu->Append( MountAllFavoritesMenuItem ); - + FavoritesMenu->AppendSeparator(); - - MainMenuBar->Append( FavoritesMenu, _("&Favorites") ); - + + MainMenuBar->Append( FavoritesMenu, _("&Favorites") ); + ToolsMenu = new wxMenu(); wxMenuItem* BenchmarkMenuItem; BenchmarkMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Benchmark...") ) , wxEmptyString, wxITEM_NORMAL ); ToolsMenu->Append( BenchmarkMenuItem ); - + wxMenuItem* EncryptionTestMenuItem; EncryptionTestMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Test Vectors...") ) , wxEmptyString, wxITEM_NORMAL ); ToolsMenu->Append( EncryptionTestMenuItem ); - + ToolsMenu->AppendSeparator(); - + wxMenuItem* VolumeCreationWizardMenuItem; VolumeCreationWizardMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Volume Creation Wizard") ) , wxEmptyString, wxITEM_NORMAL ); ToolsMenu->Append( VolumeCreationWizardMenuItem ); - + ToolsMenu->AppendSeparator(); - + BackupVolumeHeadersMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Backup Volume Header...") ) , wxEmptyString, wxITEM_NORMAL ); ToolsMenu->Append( BackupVolumeHeadersMenuItem ); - + RestoreVolumeHeaderMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Restore Volume Header...") ) , wxEmptyString, wxITEM_NORMAL ); ToolsMenu->Append( RestoreVolumeHeaderMenuItem ); - + ToolsMenu->AppendSeparator(); - + wxMenuItem* CreateKeyfileMenuItem; CreateKeyfileMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Keyfile Generator") ) , wxEmptyString, wxITEM_NORMAL ); ToolsMenu->Append( CreateKeyfileMenuItem ); - + wxMenuItem* ManageSecurityTokenKeyfilesMenuItem; ManageSecurityTokenKeyfilesMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Manage Security Token Keyfiles...") ) , wxEmptyString, wxITEM_NORMAL ); ToolsMenu->Append( ManageSecurityTokenKeyfilesMenuItem ); - + wxMenuItem* CloseAllSecurityTokenSessionsMenuItem; CloseAllSecurityTokenSessionsMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Close All Security Token Sessions") ) , wxEmptyString, wxITEM_NORMAL ); ToolsMenu->Append( CloseAllSecurityTokenSessionsMenuItem ); - + ToolsMenu->AppendSeparator(); - + WipeCachedPasswordsMenuItem = new wxMenuItem( ToolsMenu, wxID_ANY, wxString( _("Wipe Cached Passwords") ) , wxEmptyString, wxITEM_NORMAL ); ToolsMenu->Append( WipeCachedPasswordsMenuItem ); - - MainMenuBar->Append( ToolsMenu, _("T&ools") ); - + + MainMenuBar->Append( ToolsMenu, _("T&ools") ); + SettingsMenu = new wxMenu(); HotkeysMenuItem = new wxMenuItem( SettingsMenu, wxID_ANY, wxString( _("Hotkeys...") ) , wxEmptyString, wxITEM_NORMAL ); SettingsMenu->Append( HotkeysMenuItem ); - + wxMenuItem* DefaultKeyfilesMenuItem; DefaultKeyfilesMenuItem = new wxMenuItem( SettingsMenu, wxID_ANY, wxString( _("Default Keyfiles...") ) , wxEmptyString, wxITEM_NORMAL ); SettingsMenu->Append( DefaultKeyfilesMenuItem ); - + wxMenuItem* DefaultMountParametersMenuItem; DefaultMountParametersMenuItem = new wxMenuItem( SettingsMenu, wxID_ANY, wxString( _("Default Mount Parameters...") ) , wxEmptyString, wxITEM_NORMAL ); SettingsMenu->Append( DefaultMountParametersMenuItem ); - + wxMenuItem* SecurityTokenPreferencesMenuItem; SecurityTokenPreferencesMenuItem = new wxMenuItem( SettingsMenu, wxID_ANY, wxString( _("Security Tokens...") ) , wxEmptyString, wxITEM_NORMAL ); SettingsMenu->Append( SecurityTokenPreferencesMenuItem ); - + SettingsMenu->AppendSeparator(); - + PreferencesMenuItem = new wxMenuItem( SettingsMenu, wxID_PREFERENCES, wxString( _("&Preferences...") ) , wxEmptyString, wxITEM_NORMAL ); SettingsMenu->Append( PreferencesMenuItem ); - - MainMenuBar->Append( SettingsMenu, _("Settin&gs") ); - + + MainMenuBar->Append( SettingsMenu, _("Settin&gs") ); + HelpMenu = new wxMenu(); wxMenuItem* UserGuideMenuItem; UserGuideMenuItem = new wxMenuItem( HelpMenu, wxID_HELP, wxString( _("User's Guide") ) , wxEmptyString, wxITEM_NORMAL ); HelpMenu->Append( UserGuideMenuItem ); - + wxMenuItem* OnlineHelpMenuItem; OnlineHelpMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Online Help") ) , wxEmptyString, wxITEM_NORMAL ); HelpMenu->Append( OnlineHelpMenuItem ); - + wxMenuItem* BeginnersTutorialMenuItem; BeginnersTutorialMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Beginner's Tutorial") ) , wxEmptyString, wxITEM_NORMAL ); HelpMenu->Append( BeginnersTutorialMenuItem ); - + wxMenuItem* FaqMenuItem; FaqMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Frequently Asked Questions") ) , wxEmptyString, wxITEM_NORMAL ); HelpMenu->Append( FaqMenuItem ); - + HelpMenu->AppendSeparator(); - + wxMenuItem* WebsiteMenuItem; WebsiteMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("VeraCrypt Website") ) , wxEmptyString, wxITEM_NORMAL ); HelpMenu->Append( WebsiteMenuItem ); - + wxMenuItem* DownloadsMenuItem; DownloadsMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Downloads") ) , wxEmptyString, wxITEM_NORMAL ); HelpMenu->Append( DownloadsMenuItem ); - + wxMenuItem* NewsMenuItem; NewsMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("News") ) , wxEmptyString, wxITEM_NORMAL ); HelpMenu->Append( NewsMenuItem ); - + wxMenuItem* VersionHistoryMenuItem; VersionHistoryMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Version History") ) , wxEmptyString, wxITEM_NORMAL ); HelpMenu->Append( VersionHistoryMenuItem ); - + HelpMenu->AppendSeparator(); - + wxMenuItem* DonateMenuItem; DonateMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Donate") ) , wxEmptyString, wxITEM_NORMAL ); HelpMenu->Append( DonateMenuItem ); - + wxMenuItem* ContactMenuItem; ContactMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Contact") ) , wxEmptyString, wxITEM_NORMAL ); HelpMenu->Append( ContactMenuItem ); - + wxMenuItem* LegalNoticesMenuItem; LegalNoticesMenuItem = new wxMenuItem( HelpMenu, wxID_ANY, wxString( _("Legal Notices") ) , wxEmptyString, wxITEM_NORMAL ); HelpMenu->Append( LegalNoticesMenuItem ); - + wxMenuItem* AboutMenuItem; AboutMenuItem = new wxMenuItem( HelpMenu, wxID_ABOUT, wxString( _("About") ) , wxEmptyString, wxITEM_NORMAL ); HelpMenu->Append( AboutMenuItem ); - - MainMenuBar->Append( HelpMenu, _("&Help") ); - + + MainMenuBar->Append( HelpMenu, _("&Help") ); + this->SetMenuBar( MainMenuBar ); - + wxBoxSizer* bSizer1; bSizer1 = new wxBoxSizer( wxVERTICAL ); - + MainPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer2; bSizer2 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer48; bSizer48 = new wxBoxSizer( wxVERTICAL ); - + wxStaticBoxSizer* sbSizer1; sbSizer1 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - + SlotListCtrl = new wxListCtrl( MainPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES|wxSUNKEN_BORDER ); sbSizer1->Add( SlotListCtrl, 1, wxALL|wxEXPAND, 5 ); - - + + bSizer48->Add( sbSizer1, 1, wxEXPAND, 5 ); - + LowStaticBoxSizer = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - + HigherButtonSizer = new wxBoxSizer( wxVERTICAL ); - - + + LowStaticBoxSizer->Add( HigherButtonSizer, 0, wxEXPAND|wxTOP, 2 ); - + wxGridSizer* gSizer1; gSizer1 = new wxGridSizer( 1, 3, 0, 0 ); - + wxBoxSizer* bSizer17; bSizer17 = new wxBoxSizer( wxVERTICAL ); - - bSizer17->SetMinSize( wxSize( 138,34 ) ); + + bSizer17->SetMinSize( wxSize( 138,34 ) ); CreateVolumeButton = new wxButton( MainPanel, wxID_ANY, _("&Create Volume"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer17->Add( CreateVolumeButton, 1, wxALL|wxEXPAND, 5 ); - - + + gSizer1->Add( bSizer17, 0, 0, 5 ); - + wxBoxSizer* bSizer18; bSizer18 = new wxBoxSizer( wxVERTICAL ); - - bSizer18->SetMinSize( wxSize( 138,34 ) ); + + bSizer18->SetMinSize( wxSize( 138,34 ) ); VolumePropertiesButton = new wxButton( MainPanel, wxID_ANY, _("&Volume Properties..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer18->Add( VolumePropertiesButton, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxEXPAND, 5 ); - - + + gSizer1->Add( bSizer18, 0, wxALIGN_CENTER_HORIZONTAL, 5 ); - + wxBoxSizer* bSizer19; bSizer19 = new wxBoxSizer( wxVERTICAL ); - - bSizer19->SetMinSize( wxSize( 138,34 ) ); + + bSizer19->SetMinSize( wxSize( 138,34 ) ); WipeCacheButton = new wxButton( MainPanel, wxID_ANY, _("&Wipe Cache"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer19->Add( WipeCacheButton, 1, wxALL|wxALIGN_RIGHT|wxEXPAND, 5 ); - - + + gSizer1->Add( bSizer19, 0, wxALIGN_RIGHT, 5 ); - - + + LowStaticBoxSizer->Add( gSizer1, 0, wxEXPAND|wxRIGHT|wxLEFT, 5 ); - - + + LowStaticBoxSizer->Add( 0, 0, 0, 0, 5 ); - + VolumeStaticBoxSizer = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, _("Volume") ), wxVERTICAL ); - + VolumeGridBagSizer = new wxGridBagSizer( 0, 0 ); VolumeGridBagSizer->SetFlexibleDirection( wxBOTH ); VolumeGridBagSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - + LogoBitmap = new wxStaticBitmap( MainPanel, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER ); LogoBitmap->SetMinSize( wxSize( 42,52 ) ); - + VolumeGridBagSizer->Add( LogoBitmap, wxGBPosition( 0, 0 ), wxGBSpan( 2, 1 ), wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - VolumePathComboBox = new wxComboBox( MainPanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_DROPDOWN ); + + VolumePathComboBox = new wxComboBox( MainPanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_DROPDOWN ); VolumeGridBagSizer->Add( VolumePathComboBox, wxGBPosition( 0, 1 ), wxGBSpan( 1, 2 ), wxEXPAND|wxALL, 5 ); - + wxBoxSizer* bSizer191; bSizer191 = new wxBoxSizer( wxVERTICAL ); - - bSizer191->SetMinSize( wxSize( 138,34 ) ); + + bSizer191->SetMinSize( wxSize( 138,34 ) ); SelectFileButton = new wxButton( MainPanel, wxID_ANY, _("Select &File..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer191->Add( SelectFileButton, 1, wxALL|wxEXPAND, 5 ); - - + + VolumeGridBagSizer->Add( bSizer191, wxGBPosition( 0, 3 ), wxGBSpan( 1, 1 ), wxEXPAND, 5 ); - + NoHistoryCheckBox = new wxCheckBox( MainPanel, wxID_ANY, _("&Never save history"), wxDefaultPosition, wxDefaultSize, 0 ); VolumeGridBagSizer->Add( NoHistoryCheckBox, wxGBPosition( 1, 1 ), wxGBSpan( 1, 1 ), wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - + wxBoxSizer* bSizer20; bSizer20 = new wxBoxSizer( wxVERTICAL ); - - bSizer20->SetMinSize( wxSize( 138,34 ) ); + + bSizer20->SetMinSize( wxSize( 138,34 ) ); VolumeToolsButton = new wxButton( MainPanel, wxID_ANY, _("Volume &Tools..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer20->Add( VolumeToolsButton, 1, wxALL|wxEXPAND, 5 ); - - + + VolumeGridBagSizer->Add( bSizer20, wxGBPosition( 1, 2 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT, 5 ); - + wxBoxSizer* bSizer21; bSizer21 = new wxBoxSizer( wxVERTICAL ); - - bSizer21->SetMinSize( wxSize( 138,34 ) ); + + bSizer21->SetMinSize( wxSize( 138,34 ) ); SelectDeviceButton = new wxButton( MainPanel, wxID_ANY, _("Select D&evice..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer21->Add( SelectDeviceButton, 1, wxEXPAND|wxALL, 5 ); - - + + VolumeGridBagSizer->Add( bSizer21, wxGBPosition( 1, 3 ), wxGBSpan( 1, 1 ), wxEXPAND, 5 ); - - + + VolumeGridBagSizer->AddGrowableCol( 1 ); VolumeGridBagSizer->AddGrowableRow( 0 ); - + VolumeStaticBoxSizer->Add( VolumeGridBagSizer, 1, wxEXPAND|wxALL, 4 ); - - + + LowStaticBoxSizer->Add( VolumeStaticBoxSizer, 1, wxEXPAND, 5 ); - - + + LowStaticBoxSizer->Add( 0, 0, 0, 0, 5 ); - + wxGridSizer* gSizer2; gSizer2 = new wxGridSizer( 1, 4, 0, 0 ); - + wxStaticBoxSizer* sbSizer4; sbSizer4 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - sbSizer4->SetMinSize( wxSize( 139,-1 ) ); + + sbSizer4->SetMinSize( wxSize( 139,-1 ) ); VolumeButton = new wxButton( MainPanel, wxID_ANY, _("&Mount"), wxDefaultPosition, wxDefaultSize, 0 ); - VolumeButton->SetDefault(); + VolumeButton->SetDefault(); VolumeButton->SetMinSize( wxSize( -1,32 ) ); - + sbSizer4->Add( VolumeButton, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP, 2 ); - - + + gSizer2->Add( sbSizer4, 1, wxEXPAND, 0 ); - + wxStaticBoxSizer* sbSizer41; sbSizer41 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - + MountAllDevicesButton = new wxButton( MainPanel, wxID_ANY, _("&Auto-Mount Devices"), wxDefaultPosition, wxDefaultSize, 0 ); MountAllDevicesButton->SetMinSize( wxSize( -1,32 ) ); - + sbSizer41->Add( MountAllDevicesButton, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP, 2 ); - - + + gSizer2->Add( sbSizer41, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND, 5 ); - + wxStaticBoxSizer* sbSizer42; sbSizer42 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - + DismountAllButton = new wxButton( MainPanel, wxID_ANY, _("Di&smount All"), wxDefaultPosition, wxDefaultSize, 0 ); DismountAllButton->SetMinSize( wxSize( -1,32 ) ); - + sbSizer42->Add( DismountAllButton, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP, 2 ); - - + + gSizer2->Add( sbSizer42, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND, 5 ); - + wxStaticBoxSizer* sbSizer43; sbSizer43 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - + ExitButton = new wxButton( MainPanel, wxID_ANY, _("E&xit"), wxDefaultPosition, wxDefaultSize, 0 ); ExitButton->SetMinSize( wxSize( -1,32 ) ); - + sbSizer43->Add( ExitButton, 1, wxALIGN_CENTER_HORIZONTAL|wxEXPAND|wxTOP, 2 ); - - + + gSizer2->Add( sbSizer43, 1, wxALIGN_RIGHT|wxEXPAND, 5 ); - - + + LowStaticBoxSizer->Add( gSizer2, 0, wxEXPAND, 5 ); - - + + bSizer48->Add( LowStaticBoxSizer, 0, wxEXPAND, 5 ); - - + + bSizer2->Add( bSizer48, 1, wxEXPAND, 5 ); - - + + MainPanel->SetSizer( bSizer2 ); MainPanel->Layout(); bSizer2->Fit( MainPanel ); bSizer1->Add( MainPanel, 1, wxEXPAND, 0 ); - - + + this->SetSizer( bSizer1 ); this->Layout(); bSizer1->Fit( this ); - + this->Centre( wxBOTH ); - + // Connect Events this->Connect( wxEVT_ACTIVATE, wxActivateEventHandler( MainFrameBase::OnActivate ) ); this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( MainFrameBase::OnClose ) ); @@ -526,96 +526,96 @@ MainFrameBase::~MainFrameBase() MountAllDevicesButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnMountAllDevicesButtonClick ), NULL, this ); DismountAllButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnDismountAllButtonClick ), NULL, this ); ExitButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MainFrameBase::OnExitButtonClick ), NULL, this ); - + } WizardFrameBase::WizardFrameBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style ) { this->SetSizeHints( wxSize( 800,500 ), wxDefaultSize ); - + MainSizer = new wxBoxSizer( wxVERTICAL ); - + MainPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer63; bSizer63 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer64; bSizer64 = new wxBoxSizer( wxVERTICAL ); - + wxStaticBoxSizer* sbSizer27; sbSizer27 = new wxStaticBoxSizer( new wxStaticBox( MainPanel, wxID_ANY, wxEmptyString ), wxHORIZONTAL ); - + WizardBitmap = new wxStaticBitmap( MainPanel, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxDefaultSize, 0 ); sbSizer27->Add( WizardBitmap, 0, wxALL|wxEXPAND, 5 ); - + wxBoxSizer* bSizer66; bSizer66 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer126; bSizer126 = new wxBoxSizer( wxHORIZONTAL ); - + PageTitleStaticText = new wxStaticText( MainPanel, wxID_ANY, _("Page Title"), wxDefaultPosition, wxDefaultSize, 0 ); PageTitleStaticText->Wrap( -1 ); PageTitleStaticText->SetFont( wxFont( 16, 70, 90, 90, false, wxT("Times New Roman") ) ); - + bSizer126->Add( PageTitleStaticText, 0, wxALL, 5 ); - - + + bSizer66->Add( bSizer126, 0, wxLEFT, 5 ); - + PageSizer = new wxBoxSizer( wxVERTICAL ); - - + + bSizer66->Add( PageSizer, 1, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - + + sbSizer27->Add( bSizer66, 1, wxEXPAND|wxLEFT, 5 ); - - + + bSizer64->Add( sbSizer27, 1, wxEXPAND|wxRIGHT|wxLEFT, 5 ); - + wxBoxSizer* bSizer70; bSizer70 = new wxBoxSizer( wxHORIZONTAL ); - - + + bSizer70->Add( 0, 0, 1, wxEXPAND, 5 ); - + HelpButton = new wxButton( MainPanel, wxID_HELP, _("&Help"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer70->Add( HelpButton, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); - - + + bSizer70->Add( 0, 0, 0, wxLEFT|wxALIGN_RIGHT, 5 ); - + PreviousButton = new wxButton( MainPanel, wxID_ANY, _("< &Prev"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer70->Add( PreviousButton, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); - + NextButton = new wxButton( MainPanel, wxID_ANY, _("&Next >"), wxDefaultPosition, wxDefaultSize, 0|wxWANTS_CHARS ); - NextButton->SetDefault(); + NextButton->SetDefault(); bSizer70->Add( NextButton, 0, wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); - - + + bSizer70->Add( 0, 0, 0, wxLEFT|wxALIGN_RIGHT, 5 ); - + CancelButton = new wxButton( MainPanel, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer70->Add( CancelButton, 0, wxALL|wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL, 5 ); - - + + bSizer64->Add( bSizer70, 0, wxEXPAND|wxALIGN_RIGHT|wxALL, 5 ); - - + + bSizer63->Add( bSizer64, 1, wxEXPAND, 5 ); - - + + MainPanel->SetSizer( bSizer63 ); MainPanel->Layout(); bSizer63->Fit( MainPanel ); MainSizer->Add( MainPanel, 1, wxEXPAND, 5 ); - - + + this->SetSizer( MainSizer ); this->Layout(); MainSizer->Fit( this ); - + // Connect Events this->Connect( wxEVT_ACTIVATE, wxActivateEventHandler( WizardFrameBase::OnActivate ) ); this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( WizardFrameBase::OnClose ) ); @@ -636,123 +636,123 @@ WizardFrameBase::~WizardFrameBase() PreviousButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnPreviousButtonClick ), NULL, this ); NextButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnNextButtonClick ), NULL, this ); CancelButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( WizardFrameBase::OnCancelButtonClick ), NULL, this ); - + } AboutDialogBase::AboutDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - + wxBoxSizer* bSizer116; bSizer116 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer117; bSizer117 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer120; bSizer120 = new wxBoxSizer( wxVERTICAL ); - - bSizer120->SetMinSize( wxSize( -1,78 ) ); + + bSizer120->SetMinSize( wxSize( -1,78 ) ); m_panel14 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); m_panel14->SetBackgroundColour( wxColour( 10, 108, 206 ) ); - + wxBoxSizer* bSizer121; bSizer121 = new wxBoxSizer( wxVERTICAL ); - - + + bSizer121->Add( 0, 0, 1, wxEXPAND|wxALL, 5 ); - + wxBoxSizer* bSizer122; bSizer122 = new wxBoxSizer( wxVERTICAL ); - + LogoBitmap = new wxStaticBitmap( m_panel14, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxDefaultSize, 0 ); bSizer122->Add( LogoBitmap, 0, wxALL, 10 ); - - + + bSizer121->Add( bSizer122, 0, wxEXPAND|wxLEFT, 8 ); - - + + m_panel14->SetSizer( bSizer121 ); m_panel14->Layout(); bSizer121->Fit( m_panel14 ); bSizer120->Add( m_panel14, 1, wxEXPAND, 5 ); - - + + bSizer117->Add( bSizer120, 0, wxEXPAND, 5 ); - + wxBoxSizer* bSizer118; bSizer118 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer123; bSizer123 = new wxBoxSizer( wxVERTICAL ); - + VersionStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); VersionStaticText->Wrap( -1 ); bSizer123->Add( VersionStaticText, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); - - + + bSizer123->Add( 0, 0, 0, wxTOP, 3 ); - + CopyrightStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); CopyrightStaticText->Wrap( -1 ); bSizer123->Add( CopyrightStaticText, 0, wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - - + + bSizer123->Add( 0, 0, 0, wxTOP, 3 ); - + WebsiteHyperlink = new wxHyperlinkCtrl( this, wxID_ANY, wxEmptyString, wxT("."), wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); - + WebsiteHyperlink->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); WebsiteHyperlink->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); WebsiteHyperlink->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); bSizer123->Add( WebsiteHyperlink, 0, wxALL, 5 ); - - + + bSizer118->Add( bSizer123, 1, wxEXPAND|wxLEFT, 5 ); - - + + bSizer117->Add( bSizer118, 1, wxALL|wxEXPAND, 15 ); - + m_staticline3 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); bSizer117->Add( m_staticline3, 0, wxEXPAND|wxBOTTOM, 5 ); - + CreditsTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY|wxSUNKEN_BORDER ); bSizer117->Add( CreditsTextCtrl, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 10 ); - - + + bSizer117->Add( 0, 0, 0, wxTOP, 5 ); - + m_staticline4 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); bSizer117->Add( m_staticline4, 0, wxEXPAND|wxTOP|wxBOTTOM, 3 ); - + m_staticline5 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); bSizer117->Add( m_staticline5, 0, wxEXPAND|wxBOTTOM, 5 ); - + wxBoxSizer* bSizer119; bSizer119 = new wxBoxSizer( wxHORIZONTAL ); - - + + bSizer119->Add( 0, 0, 1, wxEXPAND|wxALL, 5 ); - + wxButton* OKButton; OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); + OKButton->SetDefault(); bSizer119->Add( OKButton, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - + + bSizer119->Add( 0, 0, 0, wxLEFT, 5 ); - - + + bSizer117->Add( bSizer119, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 6 ); - - + + bSizer116->Add( bSizer117, 1, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer116 ); this->Layout(); bSizer116->Fit( this ); - + // Connect Events WebsiteHyperlink->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( AboutDialogBase::OnWebsiteHyperlinkClick ), NULL, this ); } @@ -761,76 +761,76 @@ AboutDialogBase::~AboutDialogBase() { // Disconnect Events WebsiteHyperlink->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( AboutDialogBase::OnWebsiteHyperlinkClick ), NULL, this ); - + } BenchmarkDialogBase::BenchmarkDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - + wxBoxSizer* bSizer153; bSizer153 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer154; bSizer154 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer155; bSizer155 = new wxBoxSizer( wxHORIZONTAL ); - + wxStaticText* m_staticText54; m_staticText54 = new wxStaticText( this, wxID_ANY, _("Buffer Size:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText54->Wrap( -1 ); bSizer155->Add( m_staticText54, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + wxArrayString BufferSizeChoiceChoices; BufferSizeChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, BufferSizeChoiceChoices, 0 ); BufferSizeChoice->SetSelection( 0 ); bSizer155->Add( BufferSizeChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - + + bSizer154->Add( bSizer155, 0, wxEXPAND, 5 ); - + wxStaticLine* m_staticline6; m_staticline6 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); bSizer154->Add( m_staticline6, 0, wxEXPAND | wxALL, 5 ); - + wxBoxSizer* bSizer156; bSizer156 = new wxBoxSizer( wxHORIZONTAL ); - + BenchmarkListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxSUNKEN_BORDER ); bSizer156->Add( BenchmarkListCtrl, 1, wxALL|wxEXPAND, 5 ); - + RightSizer = new wxBoxSizer( wxVERTICAL ); - + BenchmarkButton = new wxButton( this, wxID_OK, _("Benchmark"), wxDefaultPosition, wxDefaultSize, 0 ); - BenchmarkButton->SetDefault(); + BenchmarkButton->SetDefault(); RightSizer->Add( BenchmarkButton, 0, wxALL|wxEXPAND, 5 ); - + wxButton* CancelButton; CancelButton = new wxButton( this, wxID_CANCEL, _("Close"), wxDefaultPosition, wxDefaultSize, 0 ); RightSizer->Add( CancelButton, 0, wxALL|wxEXPAND, 5 ); - - + + RightSizer->Add( 0, 0, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 ); - + BenchmarkNoteStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); BenchmarkNoteStaticText->Wrap( -1 ); RightSizer->Add( BenchmarkNoteStaticText, 1, wxALL|wxEXPAND, 5 ); - - + + bSizer156->Add( RightSizer, 0, wxEXPAND, 5 ); - - + + bSizer154->Add( bSizer156, 1, wxEXPAND, 5 ); - - + + bSizer153->Add( bSizer154, 1, wxEXPAND|wxALL, 5 ); - - + + this->SetSizer( bSizer153 ); this->Layout(); bSizer153->Fit( this ); - + // Connect Events BenchmarkButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( BenchmarkDialogBase::OnBenchmarkButtonClick ), NULL, this ); } @@ -839,67 +839,67 @@ BenchmarkDialogBase::~BenchmarkDialogBase() { // Disconnect Events BenchmarkButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( BenchmarkDialogBase::OnBenchmarkButtonClick ), NULL, this ); - + } ChangePasswordDialogBase::ChangePasswordDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); - + wxBoxSizer* bSizer30; bSizer30 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer31; bSizer31 = new wxBoxSizer( wxHORIZONTAL ); - + wxBoxSizer* bSizer32; bSizer32 = new wxBoxSizer( wxVERTICAL ); - + CurrentSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Current") ), wxVERTICAL ); - + CurrentPasswordPanelSizer = new wxBoxSizer( wxVERTICAL ); - - + + CurrentSizer->Add( CurrentPasswordPanelSizer, 0, wxALIGN_LEFT, 5 ); - - + + bSizer32->Add( CurrentSizer, 0, wxEXPAND, 5 ); - + NewSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("New") ), wxVERTICAL ); - + NewPasswordPanelSizer = new wxBoxSizer( wxVERTICAL ); - - + + NewSizer->Add( NewPasswordPanelSizer, 0, wxALIGN_LEFT, 5 ); - - + + bSizer32->Add( NewSizer, 0, wxTOP|wxEXPAND, 5 ); - - + + bSizer31->Add( bSizer32, 1, wxEXPAND|wxALL, 5 ); - + wxBoxSizer* bSizer33; bSizer33 = new wxBoxSizer( wxVERTICAL ); - + OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); + OKButton->SetDefault(); bSizer33->Add( OKButton, 0, wxALL|wxEXPAND, 5 ); - + CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer33->Add( CancelButton, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer31->Add( bSizer33, 0, 0, 5 ); - - + + bSizer30->Add( bSizer31, 1, wxEXPAND|wxALL, 5 ); - - + + this->SetSizer( bSizer30 ); this->Layout(); bSizer30->Fit( this ); - + // Connect Events OKButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ChangePasswordDialogBase::OnOKButtonClick ), NULL, this ); } @@ -908,42 +908,42 @@ ChangePasswordDialogBase::~ChangePasswordDialogBase() { // Disconnect Events OKButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ChangePasswordDialogBase::OnOKButtonClick ), NULL, this ); - + } DeviceSelectionDialogBase::DeviceSelectionDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxSize( -1,-1 ), wxDefaultSize ); this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); - + wxBoxSizer* bSizer3; bSizer3 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer4; bSizer4 = new wxBoxSizer( wxVERTICAL ); - + DeviceListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES|wxSUNKEN_BORDER ); bSizer4->Add( DeviceListCtrl, 1, wxALL|wxEXPAND, 5 ); - + StdButtons = new wxStdDialogButtonSizer(); StdButtonsOK = new wxButton( this, wxID_OK ); StdButtons->AddButton( StdButtonsOK ); StdButtonsCancel = new wxButton( this, wxID_CANCEL ); StdButtons->AddButton( StdButtonsCancel ); StdButtons->Realize(); - + bSizer4->Add( StdButtons, 0, wxEXPAND|wxALL, 5 ); - - + + bSizer3->Add( bSizer4, 1, wxEXPAND|wxALL, 5 ); - - + + this->SetSizer( bSizer3 ); this->Layout(); bSizer3->Fit( this ); - + this->Centre( wxBOTH ); - + // Connect Events DeviceListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemActivated ), NULL, this ); DeviceListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemDeselected ), NULL, this ); @@ -956,154 +956,154 @@ DeviceSelectionDialogBase::~DeviceSelectionDialogBase() DeviceListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemActivated ), NULL, this ); DeviceListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemDeselected ), NULL, this ); DeviceListCtrl->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( DeviceSelectionDialogBase::OnListItemSelected ), NULL, this ); - + } EncryptionTestDialogBase::EncryptionTestDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - + wxBoxSizer* bSizer132; bSizer132 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer133; bSizer133 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer134; bSizer134 = new wxBoxSizer( wxHORIZONTAL ); - + wxStaticText* m_staticText41; m_staticText41 = new wxStaticText( this, wxID_ANY, _("Encryption algorithm:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText41->Wrap( -1 ); bSizer134->Add( m_staticText41, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + wxArrayString EncryptionAlgorithmChoiceChoices; EncryptionAlgorithmChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, EncryptionAlgorithmChoiceChoices, 0 ); EncryptionAlgorithmChoice->SetSelection( 0 ); bSizer134->Add( EncryptionAlgorithmChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - + XtsModeCheckBox = new wxCheckBox( this, wxID_ANY, _("XTS mode"), wxDefaultPosition, wxDefaultSize, 0 ); - XtsModeCheckBox->SetValue(true); + XtsModeCheckBox->SetValue(true); bSizer134->Add( XtsModeCheckBox, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - + + bSizer133->Add( bSizer134, 0, wxALIGN_CENTER_HORIZONTAL, 5 ); - + wxStaticBoxSizer* sbSizer38; sbSizer38 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Key (hexadecimal)") ), wxVERTICAL ); - + KeyTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - KeyTextCtrl->SetMaxLength( 0 ); + KeyTextCtrl->SetMaxLength( 0 ); KeyTextCtrl->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier") ) ); - + sbSizer38->Add( KeyTextCtrl, 1, wxALL|wxEXPAND, 5 ); - + wxBoxSizer* bSizer135; bSizer135 = new wxBoxSizer( wxHORIZONTAL ); - + wxStaticText* m_staticText43; m_staticText43 = new wxStaticText( this, wxID_ANY, _("Key size:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText43->Wrap( -1 ); bSizer135->Add( m_staticText43, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - + KeySizeStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); KeySizeStaticText->Wrap( -1 ); bSizer135->Add( KeySizeStaticText, 0, wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT, 5 ); - - + + sbSizer38->Add( bSizer135, 0, wxEXPAND, 5 ); - - + + bSizer133->Add( sbSizer38, 0, wxEXPAND|wxALL, 5 ); - + wxStaticBoxSizer* sbSizer39; sbSizer39 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("XTS mode") ), wxVERTICAL ); - + wxStaticText* m_staticText45; m_staticText45 = new wxStaticText( this, wxID_ANY, _("Secondary key (hexadecimal)"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText45->Wrap( -1 ); sbSizer39->Add( m_staticText45, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); - + SecondaryKeyTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - SecondaryKeyTextCtrl->SetMaxLength( 0 ); + SecondaryKeyTextCtrl->SetMaxLength( 0 ); SecondaryKeyTextCtrl->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier") ) ); - + sbSizer39->Add( SecondaryKeyTextCtrl, 0, wxEXPAND|wxALL, 5 ); - + wxStaticText* m_staticText46; m_staticText46 = new wxStaticText( this, wxID_ANY, _("Data unit number (64-bit, data unit size is 512 bytes)"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText46->Wrap( -1 ); sbSizer39->Add( m_staticText46, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); - + DataUnitNumberTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - DataUnitNumberTextCtrl->SetMaxLength( 0 ); + DataUnitNumberTextCtrl->SetMaxLength( 0 ); sbSizer39->Add( DataUnitNumberTextCtrl, 0, wxALL, 5 ); - + wxStaticText* m_staticText47; m_staticText47 = new wxStaticText( this, wxID_ANY, _("Block number:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText47->Wrap( -1 ); sbSizer39->Add( m_staticText47, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); - + BlockNumberTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - BlockNumberTextCtrl->SetMaxLength( 0 ); + BlockNumberTextCtrl->SetMaxLength( 0 ); sbSizer39->Add( BlockNumberTextCtrl, 0, wxALL, 5 ); - - + + bSizer133->Add( sbSizer39, 1, wxEXPAND|wxALL, 5 ); - + wxStaticBoxSizer* sbSizer40; sbSizer40 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Plaintext (hexadecimal)") ), wxVERTICAL ); - + PlainTextTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - PlainTextTextCtrl->SetMaxLength( 0 ); + PlainTextTextCtrl->SetMaxLength( 0 ); PlainTextTextCtrl->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier") ) ); - + sbSizer40->Add( PlainTextTextCtrl, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer133->Add( sbSizer40, 0, wxEXPAND|wxALL, 5 ); - + wxStaticBoxSizer* sbSizer41; sbSizer41 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Ciphertext (hexadecimal)") ), wxVERTICAL ); - + CipherTextTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - CipherTextTextCtrl->SetMaxLength( 0 ); + CipherTextTextCtrl->SetMaxLength( 0 ); CipherTextTextCtrl->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier") ) ); - + sbSizer41->Add( CipherTextTextCtrl, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer133->Add( sbSizer41, 0, wxEXPAND|wxALL, 5 ); - + wxBoxSizer* bSizer136; bSizer136 = new wxBoxSizer( wxHORIZONTAL ); - + EncryptButton = new wxButton( this, wxID_ANY, _("&Encrypt"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer136->Add( EncryptButton, 0, wxALL, 5 ); - + DecryptButton = new wxButton( this, wxID_ANY, _("&Decrypt"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer136->Add( DecryptButton, 0, wxALL, 5 ); - + AutoTestAllButton = new wxButton( this, wxID_ANY, _("&Auto-Test All"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer136->Add( AutoTestAllButton, 0, wxALL, 5 ); - + ResetButton = new wxButton( this, wxID_ANY, _("&Reset"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer136->Add( ResetButton, 0, wxALL, 5 ); - + CloseButton = new wxButton( this, wxID_CANCEL, _("Close"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer136->Add( CloseButton, 0, wxALL, 5 ); - - + + bSizer133->Add( bSizer136, 0, wxEXPAND, 5 ); - - + + bSizer132->Add( bSizer133, 1, wxEXPAND|wxALL, 5 ); - - + + this->SetSizer( bSizer132 ); this->Layout(); bSizer132->Fit( this ); - + // Connect Events EncryptionAlgorithmChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( EncryptionTestDialogBase::OnEncryptionAlgorithmSelected ), NULL, this ); XtsModeCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnXtsModeCheckBoxClick ), NULL, this ); @@ -1122,79 +1122,79 @@ EncryptionTestDialogBase::~EncryptionTestDialogBase() DecryptButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnDecryptButtonClick ), NULL, this ); AutoTestAllButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnAutoTestAllButtonClick ), NULL, this ); ResetButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionTestDialogBase::OnResetButtonClick ), NULL, this ); - + } FavoriteVolumesDialogBase::FavoriteVolumesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - + wxBoxSizer* bSizer57; bSizer57 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer60; bSizer60 = new wxBoxSizer( wxHORIZONTAL ); - + wxBoxSizer* bSizer58; bSizer58 = new wxBoxSizer( wxVERTICAL ); - + FavoritesListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES|wxSUNKEN_BORDER ); bSizer58->Add( FavoritesListCtrl, 1, wxALL|wxEXPAND, 5 ); - + wxGridSizer* gSizer5; gSizer5 = new wxGridSizer( 1, 4, 0, 0 ); - + MoveUpButton = new wxButton( this, wxID_ANY, _("Move &Up"), wxDefaultPosition, wxDefaultSize, 0 ); gSizer5->Add( MoveUpButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 ); - + MoveDownButton = new wxButton( this, wxID_ANY, _("Move &Down"), wxDefaultPosition, wxDefaultSize, 0 ); gSizer5->Add( MoveDownButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 ); - + RemoveButton = new wxButton( this, wxID_ANY, _("&Remove"), wxDefaultPosition, wxDefaultSize, 0 ); gSizer5->Add( RemoveButton, 0, wxALIGN_RIGHT|wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + RemoveAllButton = new wxButton( this, wxID_ANY, _("Remove &All"), wxDefaultPosition, wxDefaultSize, 0 ); gSizer5->Add( RemoveAllButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - - + + bSizer58->Add( gSizer5, 0, wxEXPAND|wxRIGHT|wxLEFT, 5 ); - + wxFlexGridSizer* fgSizer4; fgSizer4 = new wxFlexGridSizer( 1, 5, 0, 0 ); fgSizer4->AddGrowableCol( 2 ); fgSizer4->SetFlexibleDirection( wxBOTH ); fgSizer4->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - - + + fgSizer4->Add( 0, 0, 1, wxEXPAND, 5 ); - - + + bSizer58->Add( fgSizer4, 0, wxEXPAND, 5 ); - - + + bSizer60->Add( bSizer58, 1, wxEXPAND, 5 ); - + wxBoxSizer* bSizer59; bSizer59 = new wxBoxSizer( wxVERTICAL ); - + OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); + OKButton->SetDefault(); bSizer59->Add( OKButton, 0, wxALL, 5 ); - + CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer59->Add( CancelButton, 0, wxALL, 5 ); - - + + bSizer60->Add( bSizer59, 0, wxEXPAND, 5 ); - - + + bSizer57->Add( bSizer60, 1, wxEXPAND|wxALL, 5 ); - - + + this->SetSizer( bSizer57 ); this->Layout(); bSizer57->Fit( this ); - + // Connect Events FavoritesListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( FavoriteVolumesDialogBase::OnListItemDeselected ), NULL, this ); FavoritesListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( FavoriteVolumesDialogBase::OnListItemSelected ), NULL, this ); @@ -1215,91 +1215,91 @@ FavoriteVolumesDialogBase::~FavoriteVolumesDialogBase() RemoveButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnRemoveButtonClick ), NULL, this ); RemoveAllButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnRemoveAllButtonClick ), NULL, this ); OKButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( FavoriteVolumesDialogBase::OnOKButtonClick ), NULL, this ); - + } KeyfilesDialogBase::KeyfilesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); - + wxBoxSizer* bSizer26; bSizer26 = new wxBoxSizer( wxVERTICAL ); - + UpperSizer = new wxBoxSizer( wxHORIZONTAL ); - + PanelSizer = new wxBoxSizer( wxVERTICAL ); - - + + UpperSizer->Add( PanelSizer, 1, wxEXPAND, 5 ); - + wxBoxSizer* bSizer22; bSizer22 = new wxBoxSizer( wxVERTICAL ); - + OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); + OKButton->SetDefault(); bSizer22->Add( OKButton, 0, wxALL|wxEXPAND, 5 ); - + CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer22->Add( CancelButton, 0, wxALL|wxEXPAND, 5 ); - + WarningStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); WarningStaticText->Wrap( -1 ); bSizer22->Add( WarningStaticText, 1, wxALL|wxEXPAND, 5 ); - - + + UpperSizer->Add( bSizer22, 0, wxEXPAND, 5 ); - - + + bSizer26->Add( UpperSizer, 1, wxTOP|wxRIGHT|wxLEFT, 5 ); - + wxBoxSizer* bSizer23; bSizer23 = new wxBoxSizer( wxVERTICAL ); - + KeyfilesNoteSizer = new wxBoxSizer( wxVERTICAL ); - + wxStaticLine* m_staticline1; m_staticline1 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); KeyfilesNoteSizer->Add( m_staticline1, 0, wxEXPAND | wxALL, 5 ); - + KeyfilesNoteStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); KeyfilesNoteStaticText->Wrap( -1 ); KeyfilesNoteSizer->Add( KeyfilesNoteStaticText, 0, wxALL|wxEXPAND, 5 ); - + wxStaticLine* m_staticline2; m_staticline2 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); KeyfilesNoteSizer->Add( m_staticline2, 0, wxEXPAND | wxALL, 5 ); - - + + bSizer23->Add( KeyfilesNoteSizer, 1, wxEXPAND, 5 ); - + wxFlexGridSizer* fgSizer2; fgSizer2 = new wxFlexGridSizer( 1, 2, 0, 0 ); fgSizer2->AddGrowableCol( 0 ); fgSizer2->SetFlexibleDirection( wxBOTH ); fgSizer2->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - + KeyfilesHyperlink = new wxHyperlinkCtrl( this, wxID_ANY, _("More information on keyfiles"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); - + KeyfilesHyperlink->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); KeyfilesHyperlink->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); KeyfilesHyperlink->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); fgSizer2->Add( KeyfilesHyperlink, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - + CreateKeyfileButtton = new wxButton( this, wxID_ANY, _("&Generate Random Keyfile..."), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer2->Add( CreateKeyfileButtton, 0, wxALL, 5 ); - - + + bSizer23->Add( fgSizer2, 0, wxEXPAND, 5 ); - - + + bSizer26->Add( bSizer23, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - - + + this->SetSizer( bSizer26 ); this->Layout(); bSizer26->Fit( this ); - + // Connect Events KeyfilesHyperlink->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( KeyfilesDialogBase::OnKeyfilesHyperlinkClick ), NULL, this ); CreateKeyfileButtton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesDialogBase::OnCreateKeyfileButttonClick ), NULL, this ); @@ -1310,158 +1310,158 @@ KeyfilesDialogBase::~KeyfilesDialogBase() // Disconnect Events KeyfilesHyperlink->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( KeyfilesDialogBase::OnKeyfilesHyperlinkClick ), NULL, this ); CreateKeyfileButtton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesDialogBase::OnCreateKeyfileButttonClick ), NULL, this ); - + } KeyfileGeneratorDialogBase::KeyfileGeneratorDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - + MainSizer = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer144; bSizer144 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer145; bSizer145 = new wxBoxSizer( wxHORIZONTAL ); - - + + bSizer145->Add( 0, 0, 1, wxEXPAND, 5 ); - + wxStaticText* m_staticText49; m_staticText49 = new wxStaticText( this, wxID_ANY, _("Mixing PRF:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText49->Wrap( -1 ); bSizer145->Add( m_staticText49, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - + wxArrayString HashChoiceChoices; HashChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, HashChoiceChoices, 0 ); HashChoice->SetSelection( 0 ); bSizer145->Add( HashChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - + + bSizer145->Add( 0, 0, 1, wxEXPAND, 5 ); - - + + bSizer144->Add( bSizer145, 0, wxEXPAND, 5 ); - + wxStaticBoxSizer* sbSizer43; sbSizer43 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); - + wxBoxSizer* bSizer147; bSizer147 = new wxBoxSizer( wxHORIZONTAL ); - + wxStaticText* m_staticText52; m_staticText52 = new wxStaticText( this, wxID_ANY, _("Random Pool:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText52->Wrap( -1 ); bSizer147->Add( m_staticText52, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); - + RandomPoolStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); RandomPoolStaticText->Wrap( -1 ); RandomPoolStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); - + bSizer147->Add( RandomPoolStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - + ShowRandomPoolCheckBox = new wxCheckBox( this, wxID_ANY, _("Show"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer147->Add( ShowRandomPoolCheckBox, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - + + sbSizer43->Add( bSizer147, 0, wxEXPAND|wxTOP, 5 ); - - + + sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); - + wxStaticBoxSizer* sbSizer45; sbSizer45 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Randomness Collected From Mouse Movements") ), wxVERTICAL ); - + CollectedEntropy = new wxGauge( this, wxID_ANY, 2560, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); - CollectedEntropy->SetValue( 0 ); + CollectedEntropy->SetValue( 0 ); sbSizer45->Add( CollectedEntropy, 1, wxALL|wxEXPAND, 5 ); - - + + sbSizer43->Add( sbSizer45, 0, wxBOTTOM|wxEXPAND|wxTOP, 5 ); - - + + sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); - + MouseStaticText = new wxStaticText( this, wxID_ANY, _("IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the keyfile."), wxDefaultPosition, wxDefaultSize, 0 ); MouseStaticText->Wrap( -1 ); sbSizer43->Add( MouseStaticText, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 ); - - + + sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); - - + + bSizer144->Add( sbSizer43, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - + wxBoxSizer* bSizer162; bSizer162 = new wxBoxSizer( wxVERTICAL ); - + wxFlexGridSizer* fgSizer8; fgSizer8 = new wxFlexGridSizer( 3, 3, 0, 0 ); fgSizer8->AddGrowableCol( 2 ); fgSizer8->SetFlexibleDirection( wxBOTH ); fgSizer8->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - + m_staticText60 = new wxStaticText( this, wxID_ANY, _("Number of keyfiles:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText60->Wrap( -1 ); fgSizer8->Add( m_staticText60, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - + NumberOfKeyfiles = new wxSpinCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 1, 9999999, 1 ); fgSizer8->Add( NumberOfKeyfiles, 0, wxALL, 5 ); - + m_panel18 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); fgSizer8->Add( m_panel18, 1, wxEXPAND | wxALL, 5 ); - + m_staticText63 = new wxStaticText( this, wxID_ANY, _("Keyfiles size (in Bytes):"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText63->Wrap( -1 ); fgSizer8->Add( m_staticText63, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - + KeyfilesSize = new wxSpinCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 64, 1048576, 64 ); fgSizer8->Add( KeyfilesSize, 0, wxALL, 5 ); - + RandomSizeCheckBox = new wxCheckBox( this, wxID_ANY, _("Random size (64 <-> 1048576)"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer8->Add( RandomSizeCheckBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - + m_staticText65 = new wxStaticText( this, wxID_ANY, _("Keyfiles base name:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText65->Wrap( -1 ); fgSizer8->Add( m_staticText65, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - + KeyfilesBaseName = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); fgSizer8->Add( KeyfilesBaseName, 0, wxALL, 5 ); - + m_panel19 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); fgSizer8->Add( m_panel19, 1, wxEXPAND | wxALL, 5 ); - - + + bSizer162->Add( fgSizer8, 1, wxEXPAND, 5 ); - - + + bSizer144->Add( bSizer162, 0, wxALL|wxEXPAND, 5 ); - + wxBoxSizer* bSizer146; bSizer146 = new wxBoxSizer( wxHORIZONTAL ); - + GenerateButton = new wxButton( this, wxID_ANY, _("Generate and Save Keyfile..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer146->Add( GenerateButton, 0, wxALL, 5 ); - - + + bSizer146->Add( 0, 0, 1, wxEXPAND, 5 ); - + wxButton* m_button61; m_button61 = new wxButton( this, wxID_CANCEL, _("Close"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer146->Add( m_button61, 0, wxALL, 5 ); - - + + bSizer144->Add( bSizer146, 0, wxEXPAND, 5 ); - - + + MainSizer->Add( bSizer144, 1, wxEXPAND|wxALL, 5 ); - - + + this->SetSizer( MainSizer ); this->Layout(); MainSizer->Fit( this ); - + // Connect Events this->Connect( wxEVT_MOTION, wxMouseEventHandler( KeyfileGeneratorDialogBase::OnMouseMotion ) ); HashChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnHashSelected ), NULL, this ); @@ -1478,31 +1478,31 @@ KeyfileGeneratorDialogBase::~KeyfileGeneratorDialogBase() ShowRandomPoolCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnShowRandomPoolCheckBoxClicked ), NULL, this ); RandomSizeCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnRandomSizeCheckBoxClicked ), NULL, this ); GenerateButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfileGeneratorDialogBase::OnGenerateButtonClick ), NULL, this ); - + } LegalNoticesDialogBase::LegalNoticesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - + wxBoxSizer* bSizer114; bSizer114 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer115; bSizer115 = new wxBoxSizer( wxVERTICAL ); - + LegalNoticesTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY ); bSizer115->Add( LegalNoticesTextCtrl, 1, wxALL|wxEXPAND, 5 ); - + wxButton* OKButton; OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); + OKButton->SetDefault(); bSizer115->Add( OKButton, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 ); - - + + bSizer114->Add( bSizer115, 1, wxEXPAND|wxALL, 5 ); - - + + this->SetSizer( bSizer114 ); this->Layout(); bSizer114->Fit( this ); @@ -1516,163 +1516,163 @@ MountOptionsDialogBase::MountOptionsDialogBase( wxWindow* parent, wxWindowID id, { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); - + MainSizer = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer19; bSizer19 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer14; bSizer14 = new wxBoxSizer( wxHORIZONTAL ); - + PasswordSizer = new wxBoxSizer( wxVERTICAL ); - - + + bSizer14->Add( PasswordSizer, 1, wxEXPAND, 5 ); - + wxBoxSizer* bSizer9; bSizer9 = new wxBoxSizer( wxVERTICAL ); - + OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); + OKButton->SetDefault(); bSizer9->Add( OKButton, 0, wxALL|wxEXPAND, 5 ); - + CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer9->Add( CancelButton, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer9->Add( 0, 0, 1, wxTOP|wxEXPAND, 5 ); - + OptionsButton = new wxButton( this, wxID_ANY, _("Op&tions"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer9->Add( OptionsButton, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer14->Add( bSizer9, 0, wxEXPAND, 5 ); - - + + bSizer19->Add( bSizer14, 0, wxEXPAND|wxALL, 5 ); - + wxBoxSizer* bSizer6; bSizer6 = new wxBoxSizer( wxVERTICAL ); - + OptionsPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); OptionsSizer = new wxStaticBoxSizer( new wxStaticBox( OptionsPanel, wxID_ANY, wxEmptyString ), wxVERTICAL ); - - + + OptionsSizer->Add( 0, 0, 0, wxTOP, 5 ); - + ReadOnlyCheckBox = new wxCheckBox( OptionsPanel, wxID_ANY, _("Mount volume as &read-only"), wxDefaultPosition, wxDefaultSize, 0 ); OptionsSizer->Add( ReadOnlyCheckBox, 0, wxALL, 5 ); - + RemovableCheckBox = new wxCheckBox( OptionsPanel, wxID_ANY, _("Mount volume as removable &medium"), wxDefaultPosition, wxDefaultSize, 0 ); OptionsSizer->Add( RemovableCheckBox, 0, wxALL, 5 ); - + PartitionInSystemEncryptionScopeCheckBox = new wxCheckBox( OptionsPanel, wxID_ANY, _("Mount partition &using system encryption (preboot authentication)"), wxDefaultPosition, wxDefaultSize, 0 ); OptionsSizer->Add( PartitionInSystemEncryptionScopeCheckBox, 0, wxALL, 5 ); - + ProtectionSizer = new wxStaticBoxSizer( new wxStaticBox( OptionsPanel, wxID_ANY, _("Hidden Volume Protection") ), wxVERTICAL ); - + ProtectionCheckBox = new wxCheckBox( OptionsPanel, wxID_ANY, _("&Protect hidden volume when mounting outer volume"), wxDefaultPosition, wxDefaultSize, 0 ); ProtectionSizer->Add( ProtectionCheckBox, 0, wxALL, 5 ); - + ProtectionPasswordSizer = new wxBoxSizer( wxVERTICAL ); - - + + ProtectionSizer->Add( ProtectionPasswordSizer, 1, wxEXPAND|wxLEFT, 5 ); - + ProtectionHyperlinkCtrl = new wxHyperlinkCtrl( OptionsPanel, wxID_ANY, _("What is hidden volume protection?"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); - + ProtectionHyperlinkCtrl->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); ProtectionHyperlinkCtrl->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); ProtectionHyperlinkCtrl->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); ProtectionSizer->Add( ProtectionHyperlinkCtrl, 0, wxALL, 5 ); - - + + OptionsSizer->Add( ProtectionSizer, 1, wxEXPAND|wxALL, 5 ); - + FilesystemSizer = new wxBoxSizer( wxVERTICAL ); - + m_panel8 = new wxPanel( OptionsPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxStaticBoxSizer* sbSizer28; sbSizer28 = new wxStaticBoxSizer( new wxStaticBox( m_panel8, wxID_ANY, _("Filesystem") ), wxVERTICAL ); - + wxBoxSizer* bSizer54; bSizer54 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer55; bSizer55 = new wxBoxSizer( wxVERTICAL ); - + NoFilesystemCheckBox = new wxCheckBox( m_panel8, wxID_ANY, _("Do ¬ mount"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer55->Add( NoFilesystemCheckBox, 0, wxTOP|wxRIGHT|wxLEFT, 5 ); - - + + bSizer54->Add( bSizer55, 1, wxEXPAND, 5 ); - + FilesystemOptionsSizer = new wxGridBagSizer( 0, 0 ); FilesystemOptionsSizer->SetFlexibleDirection( wxBOTH ); FilesystemOptionsSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); FilesystemOptionsSizer->SetEmptyCellSize( wxSize( 0,0 ) ); - + FilesystemSpacer = new wxBoxSizer( wxVERTICAL ); - - + + FilesystemOptionsSizer->Add( FilesystemSpacer, wxGBPosition( 0, 0 ), wxGBSpan( 1, 1 ), wxEXPAND|wxTOP, 5 ); - + MountPointTextCtrlStaticText = new wxStaticText( m_panel8, wxID_ANY, _("Mount at directory:"), wxDefaultPosition, wxDefaultSize, 0 ); MountPointTextCtrlStaticText->Wrap( -1 ); FilesystemOptionsSizer->Add( MountPointTextCtrlStaticText, wxGBPosition( 1, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + MountPointTextCtrl = new wxTextCtrl( m_panel8, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - MountPointTextCtrl->SetMaxLength( 0 ); + MountPointTextCtrl->SetMaxLength( 0 ); FilesystemOptionsSizer->Add( MountPointTextCtrl, wxGBPosition( 1, 1 ), wxGBSpan( 1, 1 ), wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); - + MountPointButton = new wxButton( m_panel8, wxID_ANY, _("Se&lect..."), wxDefaultPosition, wxDefaultSize, 0 ); FilesystemOptionsSizer->Add( MountPointButton, wxGBPosition( 1, 2 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxRIGHT|wxLEFT, 5 ); - + FilesystemOptionsStaticText = new wxStaticText( m_panel8, wxID_ANY, _("Mount options:"), wxDefaultPosition, wxDefaultSize, 0 ); FilesystemOptionsStaticText->Wrap( -1 ); FilesystemOptionsSizer->Add( FilesystemOptionsStaticText, wxGBPosition( 2, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxLEFT, 5 ); - + FilesystemOptionsTextCtrl = new wxTextCtrl( m_panel8, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - FilesystemOptionsTextCtrl->SetMaxLength( 0 ); + FilesystemOptionsTextCtrl->SetMaxLength( 0 ); FilesystemOptionsSizer->Add( FilesystemOptionsTextCtrl, wxGBPosition( 2, 1 ), wxGBSpan( 1, 2 ), wxALIGN_CENTER_VERTICAL|wxEXPAND|wxTOP|wxRIGHT|wxLEFT, 5 ); - - + + FilesystemOptionsSizer->AddGrowableCol( 1 ); - + bSizer54->Add( FilesystemOptionsSizer, 0, wxEXPAND, 5 ); - - + + sbSizer28->Add( bSizer54, 0, wxEXPAND|wxBOTTOM, 5 ); - - + + m_panel8->SetSizer( sbSizer28 ); m_panel8->Layout(); sbSizer28->Fit( m_panel8 ); FilesystemSizer->Add( m_panel8, 0, wxEXPAND | wxALL, 5 ); - - + + OptionsSizer->Add( FilesystemSizer, 0, wxEXPAND, 5 ); - - + + OptionsPanel->SetSizer( OptionsSizer ); OptionsPanel->Layout(); OptionsSizer->Fit( OptionsPanel ); bSizer6->Add( OptionsPanel, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - - + + bSizer19->Add( bSizer6, 0, wxEXPAND, 5 ); - - + + MainSizer->Add( bSizer19, 1, wxEXPAND, 5 ); - - + + this->SetSizer( MainSizer ); this->Layout(); MainSizer->Fit( this ); - + this->Centre( wxBOTH ); - + // Connect Events this->Connect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( MountOptionsDialogBase::OnInitDialog ) ); OKButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnOKButtonClick ), NULL, this ); @@ -1695,69 +1695,69 @@ MountOptionsDialogBase::~MountOptionsDialogBase() ProtectionHyperlinkCtrl->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( MountOptionsDialogBase::OnProtectionHyperlinkClick ), NULL, this ); NoFilesystemCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnNoFilesystemCheckBoxClick ), NULL, this ); MountPointButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( MountOptionsDialogBase::OnMountPointButtonClick ), NULL, this ); - + } NewSecurityTokenKeyfileDialogBase::NewSecurityTokenKeyfileDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - + wxBoxSizer* bSizer143; bSizer143 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer144; bSizer144 = new wxBoxSizer( wxVERTICAL ); - + wxStaticBoxSizer* sbSizer42; sbSizer42 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); - + wxFlexGridSizer* fgSizer7; fgSizer7 = new wxFlexGridSizer( 2, 2, 0, 0 ); fgSizer7->SetFlexibleDirection( wxBOTH ); fgSizer7->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - + wxStaticText* m_staticText47; m_staticText47 = new wxStaticText( this, wxID_ANY, _("Security token:"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT ); m_staticText47->Wrap( -1 ); fgSizer7->Add( m_staticText47, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + wxArrayString SecurityTokenChoiceChoices; SecurityTokenChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, SecurityTokenChoiceChoices, 0 ); SecurityTokenChoice->SetSelection( 0 ); fgSizer7->Add( SecurityTokenChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); - + wxStaticText* m_staticText48; m_staticText48 = new wxStaticText( this, wxID_ANY, _("Keyfile name:"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT ); m_staticText48->Wrap( -1 ); fgSizer7->Add( m_staticText48, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + KeyfileNameTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - KeyfileNameTextCtrl->SetMaxLength( 0 ); + KeyfileNameTextCtrl->SetMaxLength( 0 ); fgSizer7->Add( KeyfileNameTextCtrl, 0, wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL, 5 ); - - + + sbSizer42->Add( fgSizer7, 1, wxEXPAND|wxTOP, 5 ); - - + + bSizer144->Add( sbSizer42, 1, wxEXPAND|wxALL, 5 ); - + StdButtons = new wxStdDialogButtonSizer(); StdButtonsOK = new wxButton( this, wxID_OK ); StdButtons->AddButton( StdButtonsOK ); StdButtonsCancel = new wxButton( this, wxID_CANCEL ); StdButtons->AddButton( StdButtonsCancel ); StdButtons->Realize(); - + bSizer144->Add( StdButtons, 0, wxALIGN_RIGHT|wxALL, 5 ); - - + + bSizer143->Add( bSizer144, 1, wxEXPAND|wxALL, 5 ); - - + + this->SetSizer( bSizer143 ); this->Layout(); bSizer143->Fit( this ); - + // Connect Events KeyfileNameTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( NewSecurityTokenKeyfileDialogBase::OnKeyfileNameChanged ), NULL, this ); } @@ -1766,94 +1766,94 @@ NewSecurityTokenKeyfileDialogBase::~NewSecurityTokenKeyfileDialogBase() { // Disconnect Events KeyfileNameTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( NewSecurityTokenKeyfileDialogBase::OnKeyfileNameChanged ), NULL, this ); - + } PreferencesDialogBase::PreferencesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); - + wxBoxSizer* bSizer32; bSizer32 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer41; bSizer41 = new wxBoxSizer( wxVERTICAL ); - + PreferencesNotebook = new wxNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 ); SecurityPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer44; bSizer44 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer33; bSizer33 = new wxBoxSizer( wxVERTICAL ); - + AutoDismountSizer = new wxStaticBoxSizer( new wxStaticBox( SecurityPage, wxID_ANY, _("Auto-Dismount") ), wxVERTICAL ); - + wxStaticBoxSizer* sbSizer13; sbSizer13 = new wxStaticBoxSizer( new wxStaticBox( SecurityPage, wxID_ANY, _("Dismount All Volumes When") ), wxVERTICAL ); - + DismountOnLogOffCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("User logs off"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer13->Add( DismountOnLogOffCheckBox, 0, wxALL, 5 ); - + DismountOnScreenSaverCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Screen saver is launched"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer13->Add( DismountOnScreenSaverCheckBox, 0, wxALL, 5 ); - + DismountOnPowerSavingCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("System is entering power saving mode"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer13->Add( DismountOnPowerSavingCheckBox, 0, wxALL, 5 ); - - + + AutoDismountSizer->Add( sbSizer13, 0, wxEXPAND|wxALL, 5 ); - + wxBoxSizer* bSizer34; bSizer34 = new wxBoxSizer( wxHORIZONTAL ); - + DismountOnInactivityCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Auto-dismount volume after no data has been read/written to it for"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer34->Add( DismountOnInactivityCheckBox, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); - + DismountOnInactivitySpinCtrl = new wxSpinCtrl( SecurityPage, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize( -1,-1 ), wxSP_ARROW_KEYS, 1, 9999, 1 ); DismountOnInactivitySpinCtrl->SetMinSize( wxSize( 60,-1 ) ); - + bSizer34->Add( DismountOnInactivitySpinCtrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - + wxStaticText* m_staticText5; m_staticText5 = new wxStaticText( SecurityPage, wxID_ANY, _("minutes"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText5->Wrap( -1 ); bSizer34->Add( m_staticText5, 1, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxRIGHT, 5 ); - - + + AutoDismountSizer->Add( bSizer34, 0, wxEXPAND, 5 ); - + ForceAutoDismountCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Force auto-dismount even if volume contains open files or directories"), wxDefaultPosition, wxDefaultSize, 0 ); AutoDismountSizer->Add( ForceAutoDismountCheckBox, 0, wxALL, 5 ); - - + + bSizer33->Add( AutoDismountSizer, 0, wxEXPAND|wxALL, 5 ); - + FilesystemSecuritySizer = new wxStaticBoxSizer( new wxStaticBox( SecurityPage, wxID_ANY, _("Filesystem") ), wxVERTICAL ); - + PreserveTimestampsCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Preserve modification timestamp of file containers"), wxDefaultPosition, wxDefaultSize, 0 ); FilesystemSecuritySizer->Add( PreserveTimestampsCheckBox, 0, wxALL, 5 ); - - + + bSizer33->Add( FilesystemSecuritySizer, 0, wxEXPAND|wxALL, 5 ); - + wxStaticBoxSizer* sbSizer14; sbSizer14 = new wxStaticBoxSizer( new wxStaticBox( SecurityPage, wxID_ANY, _("Password Cache") ), wxVERTICAL ); - + WipeCacheOnCloseCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Wipe after VeraCrypt window has been closed"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer14->Add( WipeCacheOnCloseCheckBox, 0, wxALL, 5 ); - + WipeCacheOnAutoDismountCheckBox = new wxCheckBox( SecurityPage, wxID_ANY, _("Wipe after volume has been auto-dismounted"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer14->Add( WipeCacheOnAutoDismountCheckBox, 0, wxALL, 5 ); - - + + bSizer33->Add( sbSizer14, 0, wxEXPAND|wxALL, 5 ); - - + + bSizer44->Add( bSizer33, 1, wxEXPAND|wxALL, 5 ); - - + + SecurityPage->SetSizer( bSizer44 ); SecurityPage->Layout(); bSizer44->Fit( SecurityPage ); @@ -1861,70 +1861,70 @@ PreferencesDialogBase::PreferencesDialogBase( wxWindow* parent, wxWindowID id, c DefaultMountOptionsPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer46; bSizer46 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer35; bSizer35 = new wxBoxSizer( wxVERTICAL ); - + wxStaticBoxSizer* sbSizer15; sbSizer15 = new wxStaticBoxSizer( new wxStaticBox( DefaultMountOptionsPage, wxID_ANY, _("Default Mount Options") ), wxVERTICAL ); - + MountReadOnlyCheckBox = new wxCheckBox( DefaultMountOptionsPage, wxID_ANY, _("Mount volumes as read-only"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer15->Add( MountReadOnlyCheckBox, 0, wxALL, 5 ); - + MountRemovableCheckBox = new wxCheckBox( DefaultMountOptionsPage, wxID_ANY, _("Mount volumes as removable media"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer15->Add( MountRemovableCheckBox, 0, wxALL, 5 ); - + CachePasswordsCheckBox = new wxCheckBox( DefaultMountOptionsPage, wxID_ANY, _("Cache passwords in memory"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer15->Add( CachePasswordsCheckBox, 0, wxALL, 5 ); - + TrueCryptModeCheckBox = new wxCheckBox( DefaultMountOptionsPage, wxID_ANY, _("TrueCrypt Mode"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer15->Add( TrueCryptModeCheckBox, 0, wxALL, 5 ); - + wxBoxSizer* bSizer163; bSizer163 = new wxBoxSizer( wxHORIZONTAL ); - + Pkcs5PrfStaticText = new wxStaticText( DefaultMountOptionsPage, wxID_ANY, _("PKCS5-PRF:"), wxDefaultPosition, wxDefaultSize, 0 ); Pkcs5PrfStaticText->Wrap( -1 ); bSizer163->Add( Pkcs5PrfStaticText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - + wxArrayString Pkcs5PrfChoiceChoices; Pkcs5PrfChoice = new wxChoice( DefaultMountOptionsPage, wxID_ANY, wxDefaultPosition, wxDefaultSize, Pkcs5PrfChoiceChoices, 0 ); Pkcs5PrfChoice->SetSelection( 0 ); bSizer163->Add( Pkcs5PrfChoice, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - + + sbSizer15->Add( bSizer163, 0, wxEXPAND, 5 ); - - + + bSizer35->Add( sbSizer15, 0, wxEXPAND|wxALL, 5 ); - + FilesystemSizer = new wxStaticBoxSizer( new wxStaticBox( DefaultMountOptionsPage, wxID_ANY, _("Filesystem") ), wxVERTICAL ); - + wxFlexGridSizer* fgSizer3; fgSizer3 = new wxFlexGridSizer( 1, 2, 0, 0 ); fgSizer3->AddGrowableCol( 1 ); fgSizer3->SetFlexibleDirection( wxBOTH ); fgSizer3->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - + wxStaticText* m_staticText6; m_staticText6 = new wxStaticText( DefaultMountOptionsPage, wxID_ANY, _("Mount options:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText6->Wrap( -1 ); fgSizer3->Add( m_staticText6, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); - + FilesystemOptionsTextCtrl = new wxTextCtrl( DefaultMountOptionsPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - FilesystemOptionsTextCtrl->SetMaxLength( 0 ); + FilesystemOptionsTextCtrl->SetMaxLength( 0 ); fgSizer3->Add( FilesystemOptionsTextCtrl, 0, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); - - + + FilesystemSizer->Add( fgSizer3, 1, wxEXPAND, 5 ); - - + + bSizer35->Add( FilesystemSizer, 0, wxEXPAND|wxALL, 5 ); - - + + bSizer46->Add( bSizer35, 1, wxEXPAND|wxALL, 5 ); - - + + DefaultMountOptionsPage->SetSizer( bSizer46 ); DefaultMountOptionsPage->Layout(); bSizer46->Fit( DefaultMountOptionsPage ); @@ -1932,41 +1932,41 @@ PreferencesDialogBase::PreferencesDialogBase( wxWindow* parent, wxWindowID id, c BackgroundTaskPanel = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer61; bSizer61 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer62; bSizer62 = new wxBoxSizer( wxVERTICAL ); - + wxStaticBoxSizer* sbSizer18; sbSizer18 = new wxStaticBoxSizer( new wxStaticBox( BackgroundTaskPanel, wxID_ANY, _("VeraCrypt Background Task") ), wxVERTICAL ); - + BackgroundTaskEnabledCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Enabled"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer18->Add( BackgroundTaskEnabledCheckBox, 0, wxALL, 5 ); - + CloseBackgroundTaskOnNoVolumesCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Exit when there are no mounted volumes"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer18->Add( CloseBackgroundTaskOnNoVolumesCheckBox, 0, wxALL, 5 ); - + wxStaticBoxSizer* sbSizer26; sbSizer26 = new wxStaticBoxSizer( new wxStaticBox( BackgroundTaskPanel, wxID_ANY, _("Task Icon Menu Items") ), wxVERTICAL ); - + BackgroundTaskMenuMountItemsEnabledCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Mount Favorite Volumes"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer26->Add( BackgroundTaskMenuMountItemsEnabledCheckBox, 0, wxALL, 5 ); - + BackgroundTaskMenuOpenItemsEnabledCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Open Mounted Volumes"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer26->Add( BackgroundTaskMenuOpenItemsEnabledCheckBox, 0, wxALL, 5 ); - + BackgroundTaskMenuDismountItemsEnabledCheckBox = new wxCheckBox( BackgroundTaskPanel, wxID_ANY, _("Dismount Mounted Volumes"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer26->Add( BackgroundTaskMenuDismountItemsEnabledCheckBox, 0, wxALL, 5 ); - - + + sbSizer18->Add( sbSizer26, 1, wxEXPAND|wxALL, 5 ); - - + + bSizer62->Add( sbSizer18, 0, wxEXPAND|wxALL, 5 ); - - + + bSizer61->Add( bSizer62, 1, wxEXPAND|wxALL, 5 ); - - + + BackgroundTaskPanel->SetSizer( bSizer61 ); BackgroundTaskPanel->Layout(); bSizer61->Fit( BackgroundTaskPanel ); @@ -1974,47 +1974,47 @@ PreferencesDialogBase::PreferencesDialogBase( wxWindow* parent, wxWindowID id, c SystemIntegrationPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer49; bSizer49 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer37; bSizer37 = new wxBoxSizer( wxVERTICAL ); - + LogOnSizer = new wxStaticBoxSizer( new wxStaticBox( SystemIntegrationPage, wxID_ANY, _("Actions to Perform when User Logs On") ), wxVERTICAL ); - + StartOnLogonCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Start VeraCrypt Background Task"), wxDefaultPosition, wxDefaultSize, 0 ); LogOnSizer->Add( StartOnLogonCheckBox, 0, wxALL, 5 ); - + MountFavoritesOnLogonCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Mount favorite volumes"), wxDefaultPosition, wxDefaultSize, 0 ); LogOnSizer->Add( MountFavoritesOnLogonCheckBox, 0, wxALL, 5 ); - + MountDevicesOnLogonCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Mount all device-hosted VeraCrypt volumes"), wxDefaultPosition, wxDefaultSize, 0 ); LogOnSizer->Add( MountDevicesOnLogonCheckBox, 0, wxALL, 5 ); - - + + bSizer37->Add( LogOnSizer, 0, wxALL|wxEXPAND, 5 ); - + ExplorerSizer = new wxStaticBoxSizer( new wxStaticBox( SystemIntegrationPage, wxID_ANY, _("Filesystem Explorer") ), wxVERTICAL ); - + OpenExplorerWindowAfterMountCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Open Explorer window for successfully mounted volume"), wxDefaultPosition, wxDefaultSize, 0 ); ExplorerSizer->Add( OpenExplorerWindowAfterMountCheckBox, 0, wxALL, 5 ); - + CloseExplorerWindowsOnDismountCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Close all Explorer windows of volume being dismounted"), wxDefaultPosition, wxDefaultSize, 0 ); ExplorerSizer->Add( CloseExplorerWindowsOnDismountCheckBox, 0, wxALL, 5 ); - - + + bSizer37->Add( ExplorerSizer, 0, wxEXPAND|wxALL, 5 ); - + KernelServicesSizer = new wxStaticBoxSizer( new wxStaticBox( SystemIntegrationPage, wxID_ANY, _("Kernel Services") ), wxVERTICAL ); - + NoKernelCryptoCheckBox = new wxCheckBox( SystemIntegrationPage, wxID_ANY, _("Do not use kernel cryptographic services"), wxDefaultPosition, wxDefaultSize, 0 ); KernelServicesSizer->Add( NoKernelCryptoCheckBox, 0, wxALL, 5 ); - - + + bSizer37->Add( KernelServicesSizer, 0, wxEXPAND|wxALL, 5 ); - - + + bSizer49->Add( bSizer37, 1, wxEXPAND|wxALL, 5 ); - - + + SystemIntegrationPage->SetSizer( bSizer49 ); SystemIntegrationPage->Layout(); bSizer49->Fit( SystemIntegrationPage ); @@ -2022,41 +2022,41 @@ PreferencesDialogBase::PreferencesDialogBase( wxWindow* parent, wxWindowID id, c PerformanceOptionsPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer151; bSizer151 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer152; bSizer152 = new wxBoxSizer( wxVERTICAL ); - + wxStaticBoxSizer* sbSizer44; sbSizer44 = new wxStaticBoxSizer( new wxStaticBox( PerformanceOptionsPage, wxID_ANY, _("Hardware Acceleration") ), wxVERTICAL ); - + wxBoxSizer* bSizer158; bSizer158 = new wxBoxSizer( wxHORIZONTAL ); - + wxStaticText* m_staticText57; m_staticText57 = new wxStaticText( PerformanceOptionsPage, wxID_ANY, _("Processor (CPU) in this computer supports hardware acceleration for AES:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText57->Wrap( -1 ); bSizer158->Add( m_staticText57, 0, wxALL, 5 ); - + AesHwCpuSupportedStaticText = new wxStaticText( PerformanceOptionsPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0|wxSUNKEN_BORDER ); AesHwCpuSupportedStaticText->Wrap( -1 ); bSizer158->Add( AesHwCpuSupportedStaticText, 0, wxALL, 5 ); - - + + sbSizer44->Add( bSizer158, 1, wxEXPAND, 5 ); - - + + sbSizer44->Add( 0, 0, 0, wxBOTTOM, 5 ); - + NoHardwareCryptoCheckBox = new wxCheckBox( PerformanceOptionsPage, wxID_ANY, _("Do not accelerate AES encryption/decryption by using the AES instructions of the processor"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer44->Add( NoHardwareCryptoCheckBox, 0, wxALL, 5 ); - - + + bSizer152->Add( sbSizer44, 0, wxEXPAND|wxALL, 5 ); - - + + bSizer151->Add( bSizer152, 1, wxALL|wxEXPAND, 5 ); - - + + PerformanceOptionsPage->SetSizer( bSizer151 ); PerformanceOptionsPage->Layout(); bSizer151->Fit( PerformanceOptionsPage ); @@ -2064,28 +2064,28 @@ PreferencesDialogBase::PreferencesDialogBase( wxWindow* parent, wxWindowID id, c DefaultKeyfilesPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer40; bSizer40 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer43; bSizer43 = new wxBoxSizer( wxVERTICAL ); - + wxStaticBoxSizer* bSizer42; bSizer42 = new wxStaticBoxSizer( new wxStaticBox( DefaultKeyfilesPage, wxID_ANY, _("Default Keyfiles") ), wxVERTICAL ); - + DefaultKeyfilesSizer = new wxBoxSizer( wxVERTICAL ); - - + + bSizer42->Add( DefaultKeyfilesSizer, 1, wxEXPAND, 5 ); - - + + bSizer43->Add( bSizer42, 1, wxEXPAND|wxALL, 5 ); - + UseKeyfilesCheckBox = new wxCheckBox( DefaultKeyfilesPage, wxID_ANY, _("Use keyfiles by default"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer43->Add( UseKeyfilesCheckBox, 0, wxALL, 5 ); - - + + bSizer40->Add( bSizer43, 1, wxEXPAND|wxALL, 5 ); - - + + DefaultKeyfilesPage->SetSizer( bSizer40 ); DefaultKeyfilesPage->Layout(); bSizer40->Fit( DefaultKeyfilesPage ); @@ -2093,42 +2093,42 @@ PreferencesDialogBase::PreferencesDialogBase( wxWindow* parent, wxWindowID id, c SecurityTokensPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer127; bSizer127 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer128; bSizer128 = new wxBoxSizer( wxVERTICAL ); - + wxStaticBoxSizer* sbSizer36; sbSizer36 = new wxStaticBoxSizer( new wxStaticBox( SecurityTokensPage, wxID_ANY, _("PKCS #11 Library Path") ), wxVERTICAL ); - + wxBoxSizer* bSizer129; bSizer129 = new wxBoxSizer( wxHORIZONTAL ); - + Pkcs11ModulePathTextCtrl = new wxTextCtrl( SecurityTokensPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - Pkcs11ModulePathTextCtrl->SetMaxLength( 0 ); + Pkcs11ModulePathTextCtrl->SetMaxLength( 0 ); bSizer129->Add( Pkcs11ModulePathTextCtrl, 1, wxALL, 5 ); - + SelectPkcs11ModuleButton = new wxButton( SecurityTokensPage, wxID_ANY, _("Select &Library..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer129->Add( SelectPkcs11ModuleButton, 0, wxALL, 5 ); - - + + sbSizer36->Add( bSizer129, 1, wxEXPAND, 5 ); - - + + bSizer128->Add( sbSizer36, 0, wxEXPAND|wxALL, 5 ); - + wxStaticBoxSizer* sbSizer37; sbSizer37 = new wxStaticBoxSizer( new wxStaticBox( SecurityTokensPage, wxID_ANY, _("Security Options") ), wxVERTICAL ); - + CloseSecurityTokenSessionsAfterMountCheckBox = new wxCheckBox( SecurityTokensPage, wxID_ANY, _("&Close token session (log out) after a volume is successfully mounted"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer37->Add( CloseSecurityTokenSessionsAfterMountCheckBox, 0, wxALL, 5 ); - - + + bSizer128->Add( sbSizer37, 0, wxEXPAND|wxALL, 5 ); - - + + bSizer127->Add( bSizer128, 1, wxEXPAND|wxALL, 5 ); - - + + SecurityTokensPage->SetSizer( bSizer127 ); SecurityTokensPage->Layout(); bSizer127->Fit( SecurityTokensPage ); @@ -2136,109 +2136,109 @@ PreferencesDialogBase::PreferencesDialogBase( wxWindow* parent, wxWindowID id, c HotkeysPage = new wxPanel( PreferencesNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer51; bSizer51 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer38; bSizer38 = new wxBoxSizer( wxVERTICAL ); - + wxStaticBoxSizer* sbSizer21; sbSizer21 = new wxStaticBoxSizer( new wxStaticBox( HotkeysPage, wxID_ANY, _("System-Wide Hotkeys") ), wxVERTICAL ); - + HotkeyListCtrl = new wxListCtrl( HotkeysPage, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL|wxLC_VRULES|wxSUNKEN_BORDER ); sbSizer21->Add( HotkeyListCtrl, 1, wxALL|wxEXPAND, 5 ); - + wxStaticBoxSizer* sbSizer23; sbSizer23 = new wxStaticBoxSizer( new wxStaticBox( HotkeysPage, wxID_ANY, _("Shortcut") ), wxVERTICAL ); - + wxFlexGridSizer* fgSizer4; fgSizer4 = new wxFlexGridSizer( 2, 3, 0, 0 ); fgSizer4->SetFlexibleDirection( wxBOTH ); fgSizer4->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - + wxStaticText* m_staticText10; m_staticText10 = new wxStaticText( HotkeysPage, wxID_ANY, _("Key to assign:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText10->Wrap( -1 ); fgSizer4->Add( m_staticText10, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + HotkeyTextCtrl = new wxTextCtrl( HotkeysPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - HotkeyTextCtrl->SetMaxLength( 0 ); + HotkeyTextCtrl->SetMaxLength( 0 ); fgSizer4->Add( HotkeyTextCtrl, 0, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); - + AssignHotkeyButton = new wxButton( HotkeysPage, wxID_ANY, _("Assign"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer4->Add( AssignHotkeyButton, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - + + fgSizer4->Add( 0, 0, 1, wxEXPAND, 5 ); - + wxGridSizer* gSizer4; gSizer4 = new wxGridSizer( 1, 4, 0, 0 ); - + HotkeyControlCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Control"), wxDefaultPosition, wxDefaultSize, 0 ); gSizer4->Add( HotkeyControlCheckBox, 0, wxALL, 5 ); - + HotkeyShiftCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Shift"), wxDefaultPosition, wxDefaultSize, 0 ); gSizer4->Add( HotkeyShiftCheckBox, 0, wxALL, 5 ); - + HotkeyAltCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Alt"), wxDefaultPosition, wxDefaultSize, 0 ); gSizer4->Add( HotkeyAltCheckBox, 0, wxALL, 5 ); - + HotkeyWinCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Win"), wxDefaultPosition, wxDefaultSize, 0 ); gSizer4->Add( HotkeyWinCheckBox, 0, wxALL, 5 ); - - + + fgSizer4->Add( gSizer4, 1, wxEXPAND, 5 ); - + RemoveHotkeyButton = new wxButton( HotkeysPage, wxID_ANY, _("Remove"), wxDefaultPosition, wxDefaultSize, 0 ); fgSizer4->Add( RemoveHotkeyButton, 1, wxALL, 5 ); - - + + sbSizer23->Add( fgSizer4, 1, wxALIGN_RIGHT, 5 ); - - + + sbSizer21->Add( sbSizer23, 0, wxEXPAND|wxALL, 5 ); - + wxStaticBoxSizer* sbSizer24; sbSizer24 = new wxStaticBoxSizer( new wxStaticBox( HotkeysPage, wxID_ANY, _("Options") ), wxVERTICAL ); - + BeepAfterHotkeyMountDismountCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Play system notification sound after mount/dismount"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer24->Add( BeepAfterHotkeyMountDismountCheckBox, 0, wxALL, 5 ); - + DisplayMessageAfterHotkeyDismountCheckBox = new wxCheckBox( HotkeysPage, wxID_ANY, _("Display confirmation message box after dismount"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer24->Add( DisplayMessageAfterHotkeyDismountCheckBox, 0, wxALL, 5 ); - - + + sbSizer21->Add( sbSizer24, 0, wxEXPAND|wxALL, 5 ); - - + + bSizer38->Add( sbSizer21, 1, wxEXPAND|wxALL, 5 ); - - + + bSizer51->Add( bSizer38, 1, wxEXPAND|wxALL, 5 ); - - + + HotkeysPage->SetSizer( bSizer51 ); HotkeysPage->Layout(); bSizer51->Fit( HotkeysPage ); PreferencesNotebook->AddPage( HotkeysPage, _("Hotkeys"), false ); - + bSizer41->Add( PreferencesNotebook, 1, wxEXPAND | wxALL, 5 ); - + StdButtons = new wxStdDialogButtonSizer(); StdButtonsOK = new wxButton( this, wxID_OK ); StdButtons->AddButton( StdButtonsOK ); StdButtonsCancel = new wxButton( this, wxID_CANCEL ); StdButtons->AddButton( StdButtonsCancel ); StdButtons->Realize(); - + bSizer41->Add( StdButtons, 0, wxEXPAND|wxALL, 5 ); - - + + bSizer32->Add( bSizer41, 1, wxEXPAND|wxALL, 5 ); - - + + this->SetSizer( bSizer32 ); this->Layout(); bSizer32->Fit( this ); - + // Connect Events this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( PreferencesDialogBase::OnClose ) ); DismountOnScreenSaverCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnDismountOnScreenSaverCheckBoxClick ), NULL, this ); @@ -2275,115 +2275,115 @@ PreferencesDialogBase::~PreferencesDialogBase() RemoveHotkeyButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnRemoveHotkeyButtonClick ), NULL, this ); StdButtonsCancel->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnCancelButtonClick ), NULL, this ); StdButtonsOK->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( PreferencesDialogBase::OnOKButtonClick ), NULL, this ); - + } RandomPoolEnrichmentDialogBase::RandomPoolEnrichmentDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - + MainSizer = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer144; bSizer144 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer145; bSizer145 = new wxBoxSizer( wxHORIZONTAL ); - - + + bSizer145->Add( 0, 0, 1, wxEXPAND, 5 ); - + wxStaticText* m_staticText49; m_staticText49 = new wxStaticText( this, wxID_ANY, _("Mixing PRF:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText49->Wrap( -1 ); bSizer145->Add( m_staticText49, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - + wxArrayString HashChoiceChoices; HashChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, HashChoiceChoices, 0 ); HashChoice->SetSelection( 0 ); bSizer145->Add( HashChoice, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - + + bSizer145->Add( 0, 0, 1, wxEXPAND, 5 ); - - + + bSizer144->Add( bSizer145, 0, wxEXPAND, 5 ); - + wxStaticBoxSizer* sbSizer43; sbSizer43 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); - + wxBoxSizer* bSizer147; bSizer147 = new wxBoxSizer( wxHORIZONTAL ); - + wxStaticText* m_staticText52; m_staticText52 = new wxStaticText( this, wxID_ANY, _("Random Pool:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText52->Wrap( -1 ); bSizer147->Add( m_staticText52, 0, wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); - + RandomPoolStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); RandomPoolStaticText->Wrap( -1 ); RandomPoolStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); - + bSizer147->Add( RandomPoolStaticText, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - + ShowRandomPoolCheckBox = new wxCheckBox( this, wxID_ANY, _("Show"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer147->Add( ShowRandomPoolCheckBox, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - + + sbSizer43->Add( bSizer147, 0, wxEXPAND|wxTOP, 5 ); - - + + sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); - + wxStaticBoxSizer* sbSizer45; sbSizer45 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Randomness Collected From Mouse Movements") ), wxVERTICAL ); - + CollectedEntropy = new wxGauge( this, wxID_ANY, 2560, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); - CollectedEntropy->SetValue( 0 ); + CollectedEntropy->SetValue( 0 ); sbSizer45->Add( CollectedEntropy, 0, wxALL|wxEXPAND, 5 ); - - + + sbSizer43->Add( sbSizer45, 0, wxBOTTOM|wxEXPAND|wxTOP, 5 ); - - + + sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); - + MouseStaticText = new wxStaticText( this, wxID_ANY, _("IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases security. When done, click 'Continue'."), wxDefaultPosition, wxDefaultSize, 0 ); MouseStaticText->Wrap( -1 ); sbSizer43->Add( MouseStaticText, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 ); - - + + sbSizer43->Add( 0, 0, 1, wxEXPAND, 5 ); - - + + bSizer144->Add( sbSizer43, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - + wxBoxSizer* bSizer146; bSizer146 = new wxBoxSizer( wxHORIZONTAL ); - - + + bSizer146->Add( 0, 0, 1, wxEXPAND, 5 ); - + ContinueButton = new wxButton( this, wxID_OK, _("&Continue"), wxDefaultPosition, wxDefaultSize, 0 ); - ContinueButton->SetDefault(); + ContinueButton->SetDefault(); bSizer146->Add( ContinueButton, 0, wxALL, 5 ); - - + + bSizer146->Add( 0, 0, 1, wxEXPAND, 5 ); - - + + bSizer144->Add( bSizer146, 0, wxEXPAND, 5 ); - - + + MainSizer->Add( bSizer144, 1, wxEXPAND|wxALL, 5 ); - - + + this->SetSizer( MainSizer ); this->Layout(); MainSizer->Fit( this ); - + this->Centre( wxBOTH ); - + // Connect Events this->Connect( wxEVT_MOTION, wxMouseEventHandler( RandomPoolEnrichmentDialogBase::OnMouseMotion ) ); HashChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( RandomPoolEnrichmentDialogBase::OnHashSelected ), NULL, this ); @@ -2396,68 +2396,68 @@ RandomPoolEnrichmentDialogBase::~RandomPoolEnrichmentDialogBase() this->Disconnect( wxEVT_MOTION, wxMouseEventHandler( RandomPoolEnrichmentDialogBase::OnMouseMotion ) ); HashChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( RandomPoolEnrichmentDialogBase::OnHashSelected ), NULL, this ); ShowRandomPoolCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( RandomPoolEnrichmentDialogBase::OnShowRandomPoolCheckBoxClicked ), NULL, this ); - + } SecurityTokenKeyfilesDialogBase::SecurityTokenKeyfilesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxSize( -1,-1 ), wxDefaultSize ); this->SetExtraStyle( GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY ); - + wxBoxSizer* bSizer3; bSizer3 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer138; bSizer138 = new wxBoxSizer( wxHORIZONTAL ); - + wxBoxSizer* bSizer142; bSizer142 = new wxBoxSizer( wxVERTICAL ); - + SecurityTokenKeyfileListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES|wxSUNKEN_BORDER ); bSizer142->Add( SecurityTokenKeyfileListCtrl, 1, wxALL|wxEXPAND, 5 ); - + wxBoxSizer* bSizer141; bSizer141 = new wxBoxSizer( wxHORIZONTAL ); - + ExportButton = new wxButton( this, wxID_ANY, _("&Export..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer141->Add( ExportButton, 0, wxALL, 5 ); - + DeleteButton = new wxButton( this, wxID_ANY, _("&Delete"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer141->Add( DeleteButton, 0, wxALL, 5 ); - - + + bSizer141->Add( 0, 0, 1, wxEXPAND|wxLEFT, 5 ); - + ImportButton = new wxButton( this, wxID_ANY, _("&Import Keyfile to Token..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer141->Add( ImportButton, 0, wxALL, 5 ); - - + + bSizer142->Add( bSizer141, 0, wxEXPAND, 5 ); - - + + bSizer138->Add( bSizer142, 1, wxEXPAND, 5 ); - + wxBoxSizer* bSizer139; bSizer139 = new wxBoxSizer( wxVERTICAL ); - + OKButton = new wxButton( this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); - OKButton->SetDefault(); + OKButton->SetDefault(); bSizer139->Add( OKButton, 0, wxALL, 5 ); - + CancelButton = new wxButton( this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer139->Add( CancelButton, 0, wxALL, 5 ); - - + + bSizer138->Add( bSizer139, 0, wxEXPAND, 5 ); - - + + bSizer3->Add( bSizer138, 1, wxEXPAND|wxALL, 5 ); - - + + this->SetSizer( bSizer3 ); this->Layout(); bSizer3->Fit( this ); - + // Connect Events SecurityTokenKeyfileListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemActivated ), NULL, this ); SecurityTokenKeyfileListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( SecurityTokenKeyfilesDialogBase::OnListItemDeselected ), NULL, this ); @@ -2478,33 +2478,33 @@ SecurityTokenKeyfilesDialogBase::~SecurityTokenKeyfilesDialogBase() DeleteButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnDeleteButtonClick ), NULL, this ); ImportButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnImportButtonClick ), NULL, this ); OKButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SecurityTokenKeyfilesDialogBase::OnOKButtonClick ), NULL, this ); - + } VolumePropertiesDialogBase::VolumePropertiesDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - + wxBoxSizer* bSizer49; bSizer49 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer50; bSizer50 = new wxBoxSizer( wxVERTICAL ); - + PropertiesListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxLC_VRULES|wxSUNKEN_BORDER ); bSizer50->Add( PropertiesListCtrl, 1, wxALL|wxEXPAND, 5 ); - + StdButtons = new wxStdDialogButtonSizer(); StdButtonsOK = new wxButton( this, wxID_OK ); StdButtons->AddButton( StdButtonsOK ); StdButtons->Realize(); - + bSizer50->Add( StdButtons, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 ); - - + + bSizer49->Add( bSizer50, 1, wxEXPAND|wxALL, 5 ); - - + + this->SetSizer( bSizer49 ); this->Layout(); bSizer49->Fit( this ); @@ -2518,85 +2518,85 @@ EncryptionOptionsWizardPageBase::EncryptionOptionsWizardPageBase( wxWindow* pare { wxBoxSizer* bSizer93; bSizer93 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer94; bSizer94 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer95; bSizer95 = new wxBoxSizer( wxVERTICAL ); - + wxStaticBoxSizer* sbSizer29; sbSizer29 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Encryption Algorithm") ), wxVERTICAL ); - + wxBoxSizer* bSizer96; bSizer96 = new wxBoxSizer( wxHORIZONTAL ); - + wxArrayString EncryptionAlgorithmChoiceChoices; EncryptionAlgorithmChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, EncryptionAlgorithmChoiceChoices, 0 ); EncryptionAlgorithmChoice->SetSelection( 0 ); bSizer96->Add( EncryptionAlgorithmChoice, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - + TestButton = new wxButton( this, wxID_ANY, _("&Test"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer96->Add( TestButton, 0, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); - - + + sbSizer29->Add( bSizer96, 0, wxEXPAND, 5 ); - + EncryptionAlgorithmStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); EncryptionAlgorithmStaticText->Wrap( -1 ); sbSizer29->Add( EncryptionAlgorithmStaticText, 1, wxALL|wxEXPAND, 5 ); - + wxBoxSizer* bSizer97; bSizer97 = new wxBoxSizer( wxHORIZONTAL ); - + EncryptionAlgorithmHyperlink = new wxHyperlinkCtrl( this, wxID_ANY, _("More information"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); - + EncryptionAlgorithmHyperlink->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); EncryptionAlgorithmHyperlink->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); EncryptionAlgorithmHyperlink->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); bSizer97->Add( EncryptionAlgorithmHyperlink, 0, wxALL, 5 ); - - + + bSizer97->Add( 0, 0, 1, wxEXPAND, 5 ); - + BenchmarkButton = new wxButton( this, wxID_ANY, _("&Benchmark"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer97->Add( BenchmarkButton, 0, wxALL, 5 ); - - + + sbSizer29->Add( bSizer97, 0, wxEXPAND, 5 ); - - + + bSizer95->Add( sbSizer29, 1, wxEXPAND|wxALL, 5 ); - + wxStaticBoxSizer* sbSizer30; sbSizer30 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Hash Algorithm") ), wxHORIZONTAL ); - + wxArrayString HashChoiceChoices; HashChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, HashChoiceChoices, 0 ); HashChoice->SetSelection( 0 ); sbSizer30->Add( HashChoice, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - + HashHyperlink = new wxHyperlinkCtrl( this, wxID_ANY, _("Information on hash algorithms"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE ); - + HashHyperlink->SetHoverColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); HashHyperlink->SetNormalColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); HashHyperlink->SetVisitedColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) ); sbSizer30->Add( HashHyperlink, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - + + bSizer95->Add( sbSizer30, 0, wxEXPAND|wxALL, 5 ); - - + + bSizer94->Add( bSizer95, 1, wxEXPAND, 5 ); - - + + bSizer93->Add( bSizer94, 1, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer93 ); this->Layout(); bSizer93->Fit( this ); - + // Connect Events EncryptionAlgorithmChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnEncryptionAlgorithmSelected ), NULL, this ); TestButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnTestButtonClick ), NULL, this ); @@ -2613,24 +2613,24 @@ EncryptionOptionsWizardPageBase::~EncryptionOptionsWizardPageBase() EncryptionAlgorithmHyperlink->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( EncryptionOptionsWizardPageBase::OnEncryptionAlgorithmHyperlinkClick ), NULL, this ); BenchmarkButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( EncryptionOptionsWizardPageBase::OnBenchmarkButtonClick ), NULL, this ); HashHyperlink->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler( EncryptionOptionsWizardPageBase::OnHashHyperlinkClick ), NULL, this ); - + } InfoWizardPageBase::InfoWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) { wxBoxSizer* bSizer71; bSizer71 = new wxBoxSizer( wxVERTICAL ); - + InfoPageSizer = new wxBoxSizer( wxVERTICAL ); - + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); InfoStaticText->Wrap( -1 ); InfoPageSizer->Add( InfoStaticText, 1, wxALL|wxEXPAND, 5 ); - - + + bSizer71->Add( InfoPageSizer, 1, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer71 ); this->Layout(); bSizer71->Fit( this ); @@ -2643,51 +2643,51 @@ InfoWizardPageBase::~InfoWizardPageBase() KeyfilesPanelBase::KeyfilesPanelBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { this->SetMinSize( wxSize( 500,300 ) ); - + wxBoxSizer* bSizer19; bSizer19 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer20; bSizer20 = new wxBoxSizer( wxHORIZONTAL ); - + wxBoxSizer* bSizer21; bSizer21 = new wxBoxSizer( wxVERTICAL ); - + KeyfilesListCtrl = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_SORT_HEADER|wxLC_REPORT|wxSUNKEN_BORDER ); bSizer21->Add( KeyfilesListCtrl, 1, wxEXPAND|wxALL, 5 ); - + wxBoxSizer* bSizer137; bSizer137 = new wxBoxSizer( wxHORIZONTAL ); - + AddFilesButton = new wxButton( this, wxID_ANY, _("Add &Files..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer137->Add( AddFilesButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + AddDirectoryButton = new wxButton( this, wxID_ANY, _("Add &Path..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer137->Add( AddDirectoryButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + AddSecurityTokenSignatureButton = new wxButton( this, wxID_ANY, _("Add &Token Files..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer137->Add( AddSecurityTokenSignatureButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + RemoveButton = new wxButton( this, wxID_ANY, _("&Remove"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer137->Add( RemoveButton, 0, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + RemoveAllButton = new wxButton( this, wxID_ANY, _("Remove &All"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer137->Add( RemoveAllButton, 0, wxEXPAND|wxALL, 5 ); - - + + bSizer21->Add( bSizer137, 0, wxEXPAND, 5 ); - - + + bSizer20->Add( bSizer21, 1, wxEXPAND, 5 ); - - + + bSizer19->Add( bSizer20, 1, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer19 ); this->Layout(); bSizer19->Fit( this ); - + // Connect Events KeyfilesListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_DESELECTED, wxListEventHandler( KeyfilesPanelBase::OnListItemDeselected ), NULL, this ); KeyfilesListCtrl->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( KeyfilesPanelBase::OnListItemSelected ), NULL, this ); @@ -2710,43 +2710,43 @@ KeyfilesPanelBase::~KeyfilesPanelBase() AddSecurityTokenSignatureButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnAddSecurityTokenSignatureButtonClick ), NULL, this ); RemoveButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnRemoveButtonClick ), NULL, this ); RemoveAllButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( KeyfilesPanelBase::OnRemoveAllButtonClick ), NULL, this ); - + } ProgressWizardPageBase::ProgressWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) { wxBoxSizer* bSizer81; bSizer81 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer82; bSizer82 = new wxBoxSizer( wxVERTICAL ); - + ProgressSizer = new wxBoxSizer( wxHORIZONTAL ); - + ProgressGauge = new wxGauge( this, wxID_ANY, 100, wxDefaultPosition, wxSize( -1,-1 ), wxGA_HORIZONTAL|wxGA_SMOOTH ); - ProgressGauge->SetValue( 0 ); + ProgressGauge->SetValue( 0 ); ProgressSizer->Add( ProgressGauge, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - + AbortButton = new wxButton( this, wxID_ANY, _("&Abort"), wxDefaultPosition, wxDefaultSize, 0 ); AbortButton->Enable( false ); - + ProgressSizer->Add( AbortButton, 0, wxTOP|wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 ); - - + + bSizer82->Add( ProgressSizer, 0, wxEXPAND, 5 ); - + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); InfoStaticText->Wrap( -1 ); bSizer82->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer81->Add( bSizer82, 0, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer81 ); this->Layout(); bSizer81->Fit( this ); - + // Connect Events AbortButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ProgressWizardPageBase::OnAbortButtonClick ), NULL, this ); } @@ -2755,44 +2755,44 @@ ProgressWizardPageBase::~ProgressWizardPageBase() { // Disconnect Events AbortButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ProgressWizardPageBase::OnAbortButtonClick ), NULL, this ); - + } SelectDirectoryWizardPageBase::SelectDirectoryWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) { this->SetMinSize( wxSize( 200,65 ) ); - + wxBoxSizer* bSizer68; bSizer68 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer69; bSizer69 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer70; bSizer70 = new wxBoxSizer( wxHORIZONTAL ); - + DirectoryTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - DirectoryTextCtrl->SetMaxLength( 0 ); + DirectoryTextCtrl->SetMaxLength( 0 ); bSizer70->Add( DirectoryTextCtrl, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - + BrowseButton = new wxButton( this, wxID_ANY, _("&Browse..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer70->Add( BrowseButton, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - - + + bSizer69->Add( bSizer70, 0, wxEXPAND, 5 ); - + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); InfoStaticText->Wrap( 300 ); bSizer69->Add( InfoStaticText, 1, wxALL|wxEXPAND, 5 ); - - + + bSizer68->Add( bSizer69, 1, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer68 ); this->Layout(); bSizer68->Fit( this ); - + // Connect Events DirectoryTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( SelectDirectoryWizardPageBase::OnDirectoryTextChanged ), NULL, this ); BrowseButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SelectDirectoryWizardPageBase::OnBrowseButtonClick ), NULL, this ); @@ -2803,38 +2803,38 @@ SelectDirectoryWizardPageBase::~SelectDirectoryWizardPageBase() // Disconnect Events DirectoryTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( SelectDirectoryWizardPageBase::OnDirectoryTextChanged ), NULL, this ); BrowseButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( SelectDirectoryWizardPageBase::OnBrowseButtonClick ), NULL, this ); - + } SingleChoiceWizardPageBase::SingleChoiceWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) { wxBoxSizer* bSizer71; bSizer71 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer77; bSizer77 = new wxBoxSizer( wxVERTICAL ); - - + + bSizer77->Add( 0, 0, 0, wxEXPAND|wxTOP, 5 ); - + OuterChoicesSizer = new wxBoxSizer( wxVERTICAL ); - + ChoicesSizer = new wxBoxSizer( wxVERTICAL ); - - + + OuterChoicesSizer->Add( ChoicesSizer, 0, wxEXPAND, 5 ); - - + + bSizer77->Add( OuterChoicesSizer, 0, wxEXPAND, 5 ); - + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); InfoStaticText->Wrap( -1 ); bSizer77->Add( InfoStaticText, 1, wxALL|wxEXPAND, 5 ); - - + + bSizer71->Add( bSizer77, 1, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer71 ); this->Layout(); bSizer71->Fit( this ); @@ -2848,194 +2848,194 @@ VolumeCreationProgressWizardPageBase::VolumeCreationProgressWizardPageBase( wxWi { wxBoxSizer* bSizer104; bSizer104 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer105; bSizer105 = new wxBoxSizer( wxVERTICAL ); - + wxStaticBoxSizer* sbSizer31; sbSizer31 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); - + KeySamplesUpperSizer = new wxBoxSizer( wxVERTICAL ); - + KeySamplesUpperInnerSizer = new wxBoxSizer( wxVERTICAL ); - - + + KeySamplesUpperSizer->Add( KeySamplesUpperInnerSizer, 1, wxEXPAND|wxTOP, 3 ); - - + + sbSizer31->Add( KeySamplesUpperSizer, 1, wxEXPAND, 30 ); - + wxFlexGridSizer* fgSizer5; fgSizer5 = new wxFlexGridSizer( 3, 2, 0, 0 ); fgSizer5->SetFlexibleDirection( wxBOTH ); fgSizer5->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - + wxStaticText* m_staticText25; m_staticText25 = new wxStaticText( this, wxID_ANY, _("Random Pool:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText25->Wrap( -1 ); fgSizer5->Add( m_staticText25, 0, wxALL|wxALIGN_RIGHT|wxALIGN_BOTTOM, 5 ); - + wxBoxSizer* bSizer126; bSizer126 = new wxBoxSizer( wxHORIZONTAL ); - + RandomPoolSampleStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); RandomPoolSampleStaticText->Wrap( -1 ); RandomPoolSampleStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); - + bSizer126->Add( RandomPoolSampleStaticText, 0, wxEXPAND|wxTOP|wxRIGHT|wxALIGN_BOTTOM, 7 ); - + DisplayKeysCheckBox = new wxCheckBox( this, wxID_ANY, _("Show"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer126->Add( DisplayKeysCheckBox, 0, wxEXPAND|wxRIGHT, 5 ); - - + + fgSizer5->Add( bSizer126, 1, wxEXPAND|wxALIGN_BOTTOM, 5 ); - + wxStaticText* m_staticText28; m_staticText28 = new wxStaticText( this, wxID_ANY, _("Header Key:"), wxDefaultPosition, wxSize( -1,-1 ), 0 ); m_staticText28->Wrap( -1 ); fgSizer5->Add( m_staticText28, 0, wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_BOTTOM, 5 ); - + HeaderKeySampleStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); HeaderKeySampleStaticText->Wrap( -1 ); HeaderKeySampleStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); - + fgSizer5->Add( HeaderKeySampleStaticText, 0, wxALIGN_BOTTOM|wxEXPAND|wxTOP|wxRIGHT, 2 ); - + wxStaticText* m_staticText29; m_staticText29 = new wxStaticText( this, wxID_ANY, _("Master Key:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText29->Wrap( -1 ); fgSizer5->Add( m_staticText29, 0, wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT|wxALIGN_BOTTOM, 5 ); - + MasterKeySampleStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); MasterKeySampleStaticText->Wrap( -1 ); MasterKeySampleStaticText->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxT("Courier New") ) ); - + fgSizer5->Add( MasterKeySampleStaticText, 0, wxEXPAND|wxALIGN_BOTTOM|wxTOP|wxRIGHT, 2 ); - - + + sbSizer31->Add( fgSizer5, 0, wxEXPAND, 5 ); - - + + bSizer105->Add( sbSizer31, 0, wxALL|wxEXPAND, 5 ); - + wxStaticBoxSizer* sbSizer45; sbSizer45 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Randomness Collected From Mouse Movements") ), wxVERTICAL ); - + CollectedEntropy = new wxGauge( this, wxID_ANY, 2560, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); - CollectedEntropy->SetValue( 0 ); + CollectedEntropy->SetValue( 0 ); sbSizer45->Add( CollectedEntropy, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer105->Add( sbSizer45, 0, wxEXPAND|wxLEFT|wxRIGHT, 5 ); - + wxStaticBoxSizer* sbSizer32; sbSizer32 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxEmptyString ), wxVERTICAL ); - + wxBoxSizer* bSizer106; bSizer106 = new wxBoxSizer( wxHORIZONTAL ); - + ProgressGauge = new wxGauge( this, wxID_ANY, 100, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); bSizer106->Add( ProgressGauge, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - + AbortButton = new wxButton( this, wxID_ANY, _("Abort"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer106->Add( AbortButton, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - + + sbSizer32->Add( bSizer106, 0, wxEXPAND, 5 ); - + wxGridSizer* gSizer6; gSizer6 = new wxGridSizer( 1, 3, 0, 0 ); - + wxBoxSizer* bSizer108; bSizer108 = new wxBoxSizer( wxHORIZONTAL ); - + m_staticText31 = new wxStaticText( this, wxID_ANY, _("Done"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText31->Wrap( -1 ); bSizer108->Add( m_staticText31, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + m_panel12 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxSize( -1,-1 ), wxSUNKEN_BORDER ); wxBoxSizer* bSizer115; bSizer115 = new wxBoxSizer( wxHORIZONTAL ); - + SizeDoneStaticText = new wxStaticText( m_panel12, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT|wxST_NO_AUTORESIZE ); SizeDoneStaticText->Wrap( -1 ); bSizer115->Add( SizeDoneStaticText, 1, wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL, 3 ); - - + + m_panel12->SetSizer( bSizer115 ); m_panel12->Layout(); bSizer115->Fit( m_panel12 ); bSizer108->Add( m_panel12, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - + + gSizer6->Add( bSizer108, 1, wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); - + wxBoxSizer* bSizer1081; bSizer1081 = new wxBoxSizer( wxHORIZONTAL ); - + m_staticText311 = new wxStaticText( this, wxID_ANY, _("Speed"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText311->Wrap( -1 ); bSizer1081->Add( m_staticText311, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + m_panel121 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER ); wxBoxSizer* bSizer1151; bSizer1151 = new wxBoxSizer( wxHORIZONTAL ); - + SpeedStaticText = new wxStaticText( m_panel121, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT|wxST_NO_AUTORESIZE ); SpeedStaticText->Wrap( -1 ); bSizer1151->Add( SpeedStaticText, 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 3 ); - - + + m_panel121->SetSizer( bSizer1151 ); m_panel121->Layout(); bSizer1151->Fit( m_panel121 ); bSizer1081->Add( m_panel121, 1, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 ); - - + + gSizer6->Add( bSizer1081, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL, 5 ); - + wxBoxSizer* bSizer1082; bSizer1082 = new wxBoxSizer( wxHORIZONTAL ); - + m_staticText312 = new wxStaticText( this, wxID_ANY, _("Left"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText312->Wrap( -1 ); bSizer1082->Add( m_staticText312, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + m_panel122 = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); wxBoxSizer* bSizer1152; bSizer1152 = new wxBoxSizer( wxHORIZONTAL ); - + TimeLeftStaticText = new wxStaticText( m_panel122, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT|wxST_NO_AUTORESIZE ); TimeLeftStaticText->Wrap( -1 ); bSizer1152->Add( TimeLeftStaticText, 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 3 ); - - + + m_panel122->SetSizer( bSizer1152 ); m_panel122->Layout(); bSizer1152->Fit( m_panel122 ); bSizer1082->Add( m_panel122, 1, wxALL|wxEXPAND, 5 ); - - + + gSizer6->Add( bSizer1082, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); - - + + sbSizer32->Add( gSizer6, 0, wxEXPAND|wxTOP, 2 ); - - + + bSizer105->Add( sbSizer32, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 ); - + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); InfoStaticText->Wrap( -1 ); bSizer105->Add( InfoStaticText, 0, wxBOTTOM|wxLEFT|wxRIGHT, 5 ); - - + + bSizer104->Add( bSizer105, 1, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer104 ); this->Layout(); bSizer104->Fit( this ); - + // Connect Events DisplayKeysCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeCreationProgressWizardPageBase::OnDisplayKeysCheckBoxClick ), NULL, this ); AbortButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeCreationProgressWizardPageBase::OnAbortButtonClick ), NULL, this ); @@ -3046,80 +3046,80 @@ VolumeCreationProgressWizardPageBase::~VolumeCreationProgressWizardPageBase() // Disconnect Events DisplayKeysCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeCreationProgressWizardPageBase::OnDisplayKeysCheckBoxClick ), NULL, this ); AbortButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeCreationProgressWizardPageBase::OnAbortButtonClick ), NULL, this ); - + } VolumeLocationWizardPageBase::VolumeLocationWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) { wxBoxSizer* bSizer86; bSizer86 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer87; bSizer87 = new wxBoxSizer( wxVERTICAL ); - - + + bSizer87->Add( 0, 0, 0, wxEXPAND|wxTOP, 5 ); - + wxBoxSizer* bSizer88; bSizer88 = new wxBoxSizer( wxHORIZONTAL ); - + wxBoxSizer* bSizer89; bSizer89 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer126; bSizer126 = new wxBoxSizer( wxHORIZONTAL ); - - VolumePathComboBox = new wxComboBox( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_DROPDOWN ); + + VolumePathComboBox = new wxComboBox( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_DROPDOWN ); bSizer126->Add( VolumePathComboBox, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); - + wxBoxSizer* bSizer90; bSizer90 = new wxBoxSizer( wxVERTICAL ); - + SelectFileButton = new wxButton( this, wxID_ANY, _("Select &File..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer90->Add( SelectFileButton, 0, wxALL|wxEXPAND, 5 ); - + SelectDeviceButton = new wxButton( this, wxID_ANY, _("Select D&evice..."), wxDefaultPosition, wxDefaultSize, 0 ); bSizer90->Add( SelectDeviceButton, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer126->Add( bSizer90, 0, wxALIGN_CENTER_VERTICAL, 5 ); - - + + bSizer89->Add( bSizer126, 0, wxEXPAND, 5 ); - + wxBoxSizer* bSizer91; bSizer91 = new wxBoxSizer( wxHORIZONTAL ); - - + + bSizer91->Add( 0, 0, 0, wxLEFT, 5 ); - + NoHistoryCheckBox = new wxCheckBox( this, wxID_ANY, _("&Never save history"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer91->Add( NoHistoryCheckBox, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer89->Add( bSizer91, 0, wxEXPAND, 5 ); - - + + bSizer88->Add( bSizer89, 1, wxEXPAND, 5 ); - - + + bSizer87->Add( bSizer88, 0, wxEXPAND, 5 ); - - + + bSizer87->Add( 0, 0, 0, wxEXPAND|wxBOTTOM, 5 ); - + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); InfoStaticText->Wrap( -1 ); bSizer87->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer86->Add( bSizer87, 1, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer86 ); this->Layout(); bSizer86->Fit( this ); - + // Connect Events VolumePathComboBox->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnVolumePathTextChanged ), NULL, this ); SelectFileButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnSelectFileButtonClick ), NULL, this ); @@ -3134,64 +3134,64 @@ VolumeLocationWizardPageBase::~VolumeLocationWizardPageBase() SelectFileButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnSelectFileButtonClick ), NULL, this ); SelectDeviceButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnSelectDeviceButtonClick ), NULL, this ); NoHistoryCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeLocationWizardPageBase::OnNoHistoryCheckBoxClick ), NULL, this ); - + } VolumeFormatOptionsWizardPageBase::VolumeFormatOptionsWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) { wxBoxSizer* bSizer124; bSizer124 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer125; bSizer125 = new wxBoxSizer( wxVERTICAL ); - + wxStaticBoxSizer* sbSizer33; sbSizer33 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Filesystem Options") ), wxVERTICAL ); - + wxFlexGridSizer* fgSizer6; fgSizer6 = new wxFlexGridSizer( 2, 2, 0, 0 ); fgSizer6->SetFlexibleDirection( wxBOTH ); fgSizer6->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); - + m_staticText43 = new wxStaticText( this, wxID_ANY, _("Filesystem type:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText43->Wrap( -1 ); fgSizer6->Add( m_staticText43, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxTOP|wxBOTTOM|wxLEFT, 5 ); - + wxArrayString FilesystemTypeChoiceChoices; FilesystemTypeChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, FilesystemTypeChoiceChoices, 0 ); FilesystemTypeChoice->SetSelection( 0 ); fgSizer6->Add( FilesystemTypeChoice, 0, wxALL, 5 ); - - + + sbSizer33->Add( fgSizer6, 1, wxEXPAND, 5 ); - - + + bSizer125->Add( sbSizer33, 0, wxEXPAND|wxALL, 5 ); - + wxStaticBoxSizer* sbSizer34; sbSizer34 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Volume Format Options") ), wxVERTICAL ); - + QuickFormatCheckBox = new wxCheckBox( this, wxID_ANY, _("Quick format"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer34->Add( QuickFormatCheckBox, 0, wxALL, 5 ); - - + + bSizer125->Add( sbSizer34, 0, wxEXPAND|wxALL, 5 ); - - + + bSizer125->Add( 0, 0, 1, wxEXPAND|wxTOP|wxBOTTOM, 5 ); - + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); InfoStaticText->Wrap( -1 ); bSizer125->Add( InfoStaticText, 0, wxALL, 5 ); - - + + bSizer124->Add( bSizer125, 0, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer124 ); this->Layout(); bSizer124->Fit( this ); - + // Connect Events FilesystemTypeChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( VolumeFormatOptionsWizardPageBase::OnFilesystemTypeSelected ), NULL, this ); QuickFormatCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeFormatOptionsWizardPageBase::OnQuickFormatCheckBoxClick ), NULL, this ); @@ -3202,109 +3202,109 @@ VolumeFormatOptionsWizardPageBase::~VolumeFormatOptionsWizardPageBase() // Disconnect Events FilesystemTypeChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( VolumeFormatOptionsWizardPageBase::OnFilesystemTypeSelected ), NULL, this ); QuickFormatCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumeFormatOptionsWizardPageBase::OnQuickFormatCheckBoxClick ), NULL, this ); - + } VolumePasswordPanelBase::VolumePasswordPanelBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style ) { wxBoxSizer* bSizer7; bSizer7 = new wxBoxSizer( wxVERTICAL ); - + GridBagSizer = new wxGridBagSizer( 0, 0 ); GridBagSizer->SetFlexibleDirection( wxBOTH ); GridBagSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); GridBagSizer->SetEmptyCellSize( wxSize( 0,0 ) ); - + PasswordStaticText = new wxStaticText( this, wxID_ANY, _("Password:"), wxDefaultPosition, wxDefaultSize, 0 ); PasswordStaticText->Wrap( -1 ); GridBagSizer->Add( PasswordStaticText, wxGBPosition( 1, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxRIGHT, 5 ); - + PasswordTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD ); - PasswordTextCtrl->SetMaxLength( 1 ); + PasswordTextCtrl->SetMaxLength( 1 ); PasswordTextCtrl->SetMinSize( wxSize( 232,-1 ) ); - + GridBagSizer->Add( PasswordTextCtrl, wxGBPosition( 1, 1 ), wxGBSpan( 1, 2 ), wxBOTTOM|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); - + ConfirmPasswordStaticText = new wxStaticText( this, wxID_ANY, _("Confirm password:"), wxDefaultPosition, wxDefaultSize, 0 ); ConfirmPasswordStaticText->Wrap( -1 ); GridBagSizer->Add( ConfirmPasswordStaticText, wxGBPosition( 2, 0 ), wxGBSpan( 1, 1 ), wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT, 5 ); - + ConfirmPasswordTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD ); - ConfirmPasswordTextCtrl->SetMaxLength( 1 ); + ConfirmPasswordTextCtrl->SetMaxLength( 1 ); ConfirmPasswordTextCtrl->SetMinSize( wxSize( 232,-1 ) ); - + GridBagSizer->Add( ConfirmPasswordTextCtrl, wxGBPosition( 2, 1 ), wxGBSpan( 1, 2 ), wxBOTTOM|wxALIGN_CENTER_VERTICAL|wxEXPAND, 5 ); - + VolumePimStaticText = new wxStaticText( this, wxID_ANY, _("Volume PIM:"), wxDefaultPosition, wxDefaultSize, 0 ); VolumePimStaticText->Wrap( -1 ); GridBagSizer->Add( VolumePimStaticText, wxGBPosition( 3, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxRIGHT, 5 ); - + VolumePimTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD ); - VolumePimTextCtrl->SetMaxLength( 7 ); + VolumePimTextCtrl->SetMaxLength( 7 ); GridBagSizer->Add( VolumePimTextCtrl, wxGBPosition( 3, 1 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxEXPAND, 5 ); - + VolumePimHelpStaticText = new wxStaticText( this, wxID_ANY, _("(Empty or 0 for default iterations)"), wxDefaultPosition, wxDefaultSize, 0 ); VolumePimHelpStaticText->Wrap( -1 ); GridBagSizer->Add( VolumePimHelpStaticText, wxGBPosition( 3, 2 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxBOTTOM|wxLEFT|wxRIGHT, 5 ); - + PimCheckBox = new wxCheckBox( this, wxID_ANY, _("Use PIM"), wxDefaultPosition, wxDefaultSize, 0 ); GridBagSizer->Add( PimCheckBox, wxGBPosition( 4, 1 ), wxGBSpan( 1, 2 ), wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); - + CacheCheckBox = new wxCheckBox( this, wxID_ANY, _("Cach&e passwords and keyfiles in memory "), wxDefaultPosition, wxDefaultSize, 0 ); GridBagSizer->Add( CacheCheckBox, wxGBPosition( 5, 1 ), wxGBSpan( 1, 2 ), wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); - + DisplayPasswordCheckBox = new wxCheckBox( this, wxID_ANY, _("&Display password"), wxDefaultPosition, wxDefaultSize, 0 ); GridBagSizer->Add( DisplayPasswordCheckBox, wxGBPosition( 6, 1 ), wxGBSpan( 1, 2 ), wxTOP|wxBOTTOM|wxLEFT|wxALIGN_CENTER_VERTICAL, 5 ); - + UseKeyfilesCheckBox = new wxCheckBox( this, wxID_ANY, _("U&se keyfiles"), wxDefaultPosition, wxDefaultSize, 0 ); GridBagSizer->Add( UseKeyfilesCheckBox, wxGBPosition( 7, 1 ), wxGBSpan( 1, 1 ), wxTOP|wxRIGHT|wxLEFT, 5 ); - + KeyfilesButton = new wxButton( this, wxID_ANY, _("&Keyfiles..."), wxDefaultPosition, wxDefaultSize, 0 ); GridBagSizer->Add( KeyfilesButton, wxGBPosition( 7, 2 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT|wxALIGN_BOTTOM|wxLEFT, 5 ); - + Pkcs5PrfSizer = new wxBoxSizer( wxVERTICAL ); - - + + GridBagSizer->Add( Pkcs5PrfSizer, wxGBPosition( 8, 1 ), wxGBSpan( 1, 1 ), wxEXPAND|wxTOP|wxBOTTOM, 5 ); - + Pkcs5PrfStaticText = new wxStaticText( this, wxID_ANY, _("PKCS-5 PRF:"), wxDefaultPosition, wxDefaultSize, 0 ); Pkcs5PrfStaticText->Wrap( -1 ); GridBagSizer->Add( Pkcs5PrfStaticText, wxGBPosition( 9, 0 ), wxGBSpan( 1, 1 ), wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxRIGHT, 5 ); - + wxString Pkcs5PrfChoiceChoices[] = { _("Unchanged") }; int Pkcs5PrfChoiceNChoices = sizeof( Pkcs5PrfChoiceChoices ) / sizeof( wxString ); Pkcs5PrfChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, Pkcs5PrfChoiceNChoices, Pkcs5PrfChoiceChoices, 0 ); Pkcs5PrfChoice->SetSelection( 0 ); GridBagSizer->Add( Pkcs5PrfChoice, wxGBPosition( 9, 1 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxLEFT, 5 ); - + TrueCryptModeCheckBox = new wxCheckBox( this, wxID_ANY, _("TrueCrypt Mode"), wxDefaultPosition, wxDefaultSize, 0 ); GridBagSizer->Add( TrueCryptModeCheckBox, wxGBPosition( 9, 2 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxLEFT, 5 ); - + HeaderWipeCountText = new wxStaticText( this, wxID_ANY, _("Header Wipe:"), wxDefaultPosition, wxDefaultSize, 0 ); HeaderWipeCountText->Wrap( -1 ); GridBagSizer->Add( HeaderWipeCountText, wxGBPosition( 10, 0 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxRIGHT, 5 ); - + wxString HeaderWipeCountChoices[] = { _("1-pass"), _("3-pass"), _("7-pass"), _("35-pass"), _("256-pass") }; int HeaderWipeCountNChoices = sizeof( HeaderWipeCountChoices ) / sizeof( wxString ); HeaderWipeCount = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, HeaderWipeCountNChoices, HeaderWipeCountChoices, 0 ); HeaderWipeCount->SetSelection( 1 ); GridBagSizer->Add( HeaderWipeCount, wxGBPosition( 10, 1 ), wxGBSpan( 1, 1 ), wxALL, 5 ); - + PasswordPlaceholderSizer = new wxBoxSizer( wxVERTICAL ); - - + + GridBagSizer->Add( PasswordPlaceholderSizer, wxGBPosition( 11, 1 ), wxGBSpan( 1, 2 ), wxTOP|wxEXPAND, 5 ); - - + + GridBagSizer->AddGrowableCol( 1 ); - + bSizer7->Add( GridBagSizer, 1, wxALL|wxEXPAND, 5 ); - - + + this->SetSizer( bSizer7 ); this->Layout(); bSizer7->Fit( this ); - + // Connect Events PasswordTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnTextChanged ), NULL, this ); ConfirmPasswordTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePasswordPanelBase::OnTextChanged ), NULL, this ); @@ -3331,30 +3331,30 @@ VolumePasswordPanelBase::~VolumePasswordPanelBase() KeyfilesButton->Disconnect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonRightDown ), NULL, this ); KeyfilesButton->Disconnect( wxEVT_RIGHT_UP, wxMouseEventHandler( VolumePasswordPanelBase::OnKeyfilesButtonRightClick ), NULL, this ); TrueCryptModeCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePasswordPanelBase::OnTrueCryptModeChecked ), NULL, this ); - + } VolumePasswordWizardPageBase::VolumePasswordWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) { wxBoxSizer* bSizer101; bSizer101 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer102; bSizer102 = new wxBoxSizer( wxVERTICAL ); - + PasswordPanelSizer = new wxBoxSizer( wxVERTICAL ); - - + + bSizer102->Add( PasswordPanelSizer, 0, wxEXPAND, 5 ); - + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); InfoStaticText->Wrap( -1 ); bSizer102->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer101->Add( bSizer102, 1, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer101 ); this->Layout(); bSizer101->Fit( this ); @@ -3368,53 +3368,53 @@ VolumePimWizardPageBase::VolumePimWizardPageBase( wxWindow* parent, wxWindowID i { wxBoxSizer* bSizer101; bSizer101 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer102; bSizer102 = new wxBoxSizer( wxVERTICAL ); - + PimPanelSizer = new wxBoxSizer( wxVERTICAL ); - + PimSizer = new wxBoxSizer( wxHORIZONTAL ); - + VolumePimStaticText = new wxStaticText( this, wxID_ANY, _("Volume PIM:"), wxDefaultPosition, wxDefaultSize, 0 ); VolumePimStaticText->Wrap( -1 ); PimSizer->Add( VolumePimStaticText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - + VolumePimTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD ); - VolumePimTextCtrl->SetMaxLength( 7 ); + VolumePimTextCtrl->SetMaxLength( 7 ); PimSizer->Add( VolumePimTextCtrl, 0, wxALL, 5 ); - + VolumePimHelpStaticText = new wxStaticText( this, wxID_ANY, _("(Empty or 0 for default iterations)"), wxDefaultPosition, wxDefaultSize, 0 ); VolumePimHelpStaticText->Wrap( -1 ); PimSizer->Add( VolumePimHelpStaticText, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); - - + + PimPanelSizer->Add( PimSizer, 1, wxEXPAND, 5 ); - + wxBoxSizer* bSizer166; bSizer166 = new wxBoxSizer( wxHORIZONTAL ); - + DisplayPimCheckBox = new wxCheckBox( this, wxID_ANY, _("&Display PIM"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer166->Add( DisplayPimCheckBox, 1, wxALL|wxEXPAND, 5 ); - - + + PimPanelSizer->Add( bSizer166, 1, wxEXPAND, 5 ); - - + + bSizer102->Add( PimPanelSizer, 0, wxEXPAND, 5 ); - + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); InfoStaticText->Wrap( -1 ); bSizer102->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer101->Add( bSizer102, 1, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer101 ); this->Layout(); bSizer101->Fit( this ); - + // Connect Events VolumePimTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePimWizardPageBase::OnPimChanged ), NULL, this ); DisplayPimCheckBox->Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePimWizardPageBase::OnDisplayPimCheckBoxClick ), NULL, this ); @@ -3425,57 +3425,57 @@ VolumePimWizardPageBase::~VolumePimWizardPageBase() // Disconnect Events VolumePimTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumePimWizardPageBase::OnPimChanged ), NULL, this ); DisplayPimCheckBox->Disconnect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( VolumePimWizardPageBase::OnDisplayPimCheckBoxClick ), NULL, this ); - + } VolumeSizeWizardPageBase::VolumeSizeWizardPageBase( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : WizardPage( parent, id, pos, size, style ) { wxBoxSizer* bSizer98; bSizer98 = new wxBoxSizer( wxVERTICAL ); - + wxBoxSizer* bSizer99; bSizer99 = new wxBoxSizer( wxVERTICAL ); - - + + bSizer99->Add( 0, 0, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 ); - + wxBoxSizer* bSizer100; bSizer100 = new wxBoxSizer( wxHORIZONTAL ); - + VolumeSizeTextCtrl = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); - VolumeSizeTextCtrl->SetMaxLength( 0 ); + VolumeSizeTextCtrl->SetMaxLength( 0 ); bSizer100->Add( VolumeSizeTextCtrl, 0, wxALL, 5 ); - + wxArrayString VolumeSizePrefixChoiceChoices; VolumeSizePrefixChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, VolumeSizePrefixChoiceChoices, 0 ); VolumeSizePrefixChoice->SetSelection( 0 ); bSizer100->Add( VolumeSizePrefixChoice, 0, wxALL, 5 ); - - + + bSizer99->Add( bSizer100, 0, wxEXPAND, 5 ); - - + + bSizer99->Add( 0, 0, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 ); - + FreeSpaceStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); FreeSpaceStaticText->Wrap( -1 ); bSizer99->Add( FreeSpaceStaticText, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer99->Add( 0, 0, 0, wxEXPAND|wxTOP|wxBOTTOM, 5 ); - + InfoStaticText = new wxStaticText( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); InfoStaticText->Wrap( -1 ); bSizer99->Add( InfoStaticText, 0, wxALL|wxEXPAND, 5 ); - - + + bSizer98->Add( bSizer99, 0, wxEXPAND, 5 ); - - + + this->SetSizer( bSizer98 ); this->Layout(); bSizer98->Fit( this ); - + // Connect Events VolumeSizeTextCtrl->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumeSizeWizardPageBase::OnVolumeSizeTextChanged ), NULL, this ); VolumeSizePrefixChoice->Connect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( VolumeSizeWizardPageBase::OnVolumeSizePrefixSelected ), NULL, this ); @@ -3486,31 +3486,31 @@ VolumeSizeWizardPageBase::~VolumeSizeWizardPageBase() // Disconnect Events VolumeSizeTextCtrl->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler( VolumeSizeWizardPageBase::OnVolumeSizeTextChanged ), NULL, this ); VolumeSizePrefixChoice->Disconnect( wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler( VolumeSizeWizardPageBase::OnVolumeSizePrefixSelected ), NULL, this ); - + } WaitDialogBase::WaitDialogBase( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); - + wxBoxSizer* bSizer160; bSizer160 = new wxBoxSizer( wxVERTICAL ); - + WaitStaticText = new wxStaticText( this, wxID_ANY, _("MyLabel"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE ); WaitStaticText->Wrap( -1 ); bSizer160->Add( WaitStaticText, 0, wxALIGN_CENTER_HORIZONTAL|wxALL|wxEXPAND, 5 ); - + WaitProgessBar = new wxGauge( this, wxID_ANY, 100, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL|wxGA_SMOOTH ); - WaitProgessBar->SetValue( 0 ); + WaitProgessBar->SetValue( 0 ); bSizer160->Add( WaitProgessBar, 0, wxALL|wxEXPAND, 5 ); - - + + this->SetSizer( bSizer160 ); this->Layout(); bSizer160->Fit( this ); - + this->Centre( wxBOTH ); - + // Connect Events this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( WaitDialogBase::OnWaitDialogClose ) ); this->Connect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( WaitDialogBase::OnWaitDialogInit ) ); @@ -3521,5 +3521,5 @@ WaitDialogBase::~WaitDialogBase() // Disconnect Events this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( WaitDialogBase::OnWaitDialogClose ) ); this->Disconnect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( WaitDialogBase::OnWaitDialogInit ) ); - + } diff --git a/src/Main/Forms/Forms.h b/src/Main/Forms/Forms.h index fd558e94..129ae153 100644 --- a/src/Main/Forms/Forms.h +++ b/src/Main/Forms/Forms.h @@ -50,10 +50,10 @@ namespace VeraCrypt /////////////////////////////////////////////////////////////////////////////// /// Class MainFrameBase /////////////////////////////////////////////////////////////////////////////// - class MainFrameBase : public wxFrame + class MainFrameBase : public wxFrame { private: - + protected: wxMenuBar* MainMenuBar; wxMenu* VolumesMenu; @@ -91,7 +91,7 @@ namespace VeraCrypt wxButton* MountAllDevicesButton; wxButton* DismountAllButton; wxButton* ExitButton; - + // Virtual event handlers, overide them in your derived class virtual void OnActivate( wxActivateEvent& event ) { event.Skip(); } virtual void OnClose( wxCloseEvent& event ) { event.Skip(); } @@ -145,23 +145,23 @@ namespace VeraCrypt virtual void OnSelectDeviceButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnVolumeButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnExitButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - + MainFrameBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxCAPTION|wxCLOSE_BOX|wxMINIMIZE_BOX|wxSYSTEM_MENU|wxTAB_TRAVERSAL ); - + ~MainFrameBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class WizardFrameBase /////////////////////////////////////////////////////////////////////////////// - class WizardFrameBase : public wxFrame + class WizardFrameBase : public wxFrame { private: - + protected: wxBoxSizer* MainSizer; wxPanel* MainPanel; @@ -172,7 +172,7 @@ namespace VeraCrypt wxButton* PreviousButton; wxButton* NextButton; wxButton* CancelButton; - + // Virtual event handlers, overide them in your derived class virtual void OnActivate( wxActivateEvent& event ) { event.Skip(); } virtual void OnClose( wxCloseEvent& event ) { event.Skip(); } @@ -181,23 +181,23 @@ namespace VeraCrypt virtual void OnPreviousButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnNextButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnCancelButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - + WizardFrameBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxCAPTION|wxCLOSE_BOX|wxMINIMIZE_BOX|wxSYSTEM_MENU|wxTAB_TRAVERSAL ); - + ~WizardFrameBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class AboutDialogBase /////////////////////////////////////////////////////////////////////////////// - class AboutDialogBase : public wxDialog + class AboutDialogBase : public wxDialog { private: - + protected: wxPanel* m_panel14; wxStaticBitmap* LogoBitmap; @@ -208,50 +208,50 @@ namespace VeraCrypt wxTextCtrl* CreditsTextCtrl; wxStaticLine* m_staticline4; wxStaticLine* m_staticline5; - + // Virtual event handlers, overide them in your derived class virtual void OnWebsiteHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } - - + + public: - - AboutDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + + AboutDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~AboutDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class BenchmarkDialogBase /////////////////////////////////////////////////////////////////////////////// - class BenchmarkDialogBase : public wxDialog + class BenchmarkDialogBase : public wxDialog { private: - + protected: wxChoice* BufferSizeChoice; wxListCtrl* BenchmarkListCtrl; wxBoxSizer* RightSizer; wxButton* BenchmarkButton; wxStaticText* BenchmarkNoteStaticText; - + // Virtual event handlers, overide them in your derived class virtual void OnBenchmarkButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - BenchmarkDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Encryption Algorithm Benchmark"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + + BenchmarkDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Encryption Algorithm Benchmark"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~BenchmarkDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class ChangePasswordDialogBase /////////////////////////////////////////////////////////////////////////////// - class ChangePasswordDialogBase : public wxDialog + class ChangePasswordDialogBase : public wxDialog { private: - + protected: wxStaticBoxSizer* CurrentSizer; wxBoxSizer* CurrentPasswordPanelSizer; @@ -259,51 +259,51 @@ namespace VeraCrypt wxBoxSizer* NewPasswordPanelSizer; wxButton* OKButton; wxButton* CancelButton; - + // Virtual event handlers, overide them in your derived class virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - ChangePasswordDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + + ChangePasswordDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~ChangePasswordDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class DeviceSelectionDialogBase /////////////////////////////////////////////////////////////////////////////// - class DeviceSelectionDialogBase : public wxDialog + class DeviceSelectionDialogBase : public wxDialog { private: - + protected: wxListCtrl* DeviceListCtrl; wxStdDialogButtonSizer* StdButtons; wxButton* StdButtonsOK; wxButton* StdButtonsCancel; - + // Virtual event handlers, overide them in your derived class virtual void OnListItemActivated( wxListEvent& event ) { event.Skip(); } virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } - - + + public: - - DeviceSelectionDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Select a Partition or Device"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxDEFAULT_DIALOG_STYLE ); + + DeviceSelectionDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Select a Partition or Device"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxDEFAULT_DIALOG_STYLE ); ~DeviceSelectionDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class EncryptionTestDialogBase /////////////////////////////////////////////////////////////////////////////// - class EncryptionTestDialogBase : public wxDialog + class EncryptionTestDialogBase : public wxDialog { private: - + protected: wxChoice* EncryptionAlgorithmChoice; wxCheckBox* XtsModeCheckBox; @@ -319,7 +319,7 @@ namespace VeraCrypt wxButton* AutoTestAllButton; wxButton* ResetButton; wxButton* CloseButton; - + // Virtual event handlers, overide them in your derived class virtual void OnEncryptionAlgorithmSelected( wxCommandEvent& event ) { event.Skip(); } virtual void OnXtsModeCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } @@ -327,22 +327,22 @@ namespace VeraCrypt virtual void OnDecryptButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnAutoTestAllButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnResetButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - EncryptionTestDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Test Vectors"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + + EncryptionTestDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Test Vectors"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~EncryptionTestDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class FavoriteVolumesDialogBase /////////////////////////////////////////////////////////////////////////////// - class FavoriteVolumesDialogBase : public wxDialog + class FavoriteVolumesDialogBase : public wxDialog { private: - + protected: wxListCtrl* FavoritesListCtrl; wxButton* MoveUpButton; @@ -351,7 +351,7 @@ namespace VeraCrypt wxButton* RemoveAllButton; wxButton* OKButton; wxButton* CancelButton; - + // Virtual event handlers, overide them in your derived class virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } @@ -360,22 +360,22 @@ namespace VeraCrypt virtual void OnRemoveButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnRemoveAllButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - FavoriteVolumesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Favorite Volumes"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + + FavoriteVolumesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Favorite Volumes"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~FavoriteVolumesDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class KeyfilesDialogBase /////////////////////////////////////////////////////////////////////////////// - class KeyfilesDialogBase : public wxDialog + class KeyfilesDialogBase : public wxDialog { private: - + protected: wxBoxSizer* UpperSizer; wxBoxSizer* PanelSizer; @@ -386,26 +386,26 @@ namespace VeraCrypt wxStaticText* KeyfilesNoteStaticText; wxHyperlinkCtrl* KeyfilesHyperlink; wxButton* CreateKeyfileButtton; - + // Virtual event handlers, overide them in your derived class virtual void OnKeyfilesHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } virtual void OnCreateKeyfileButttonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - KeyfilesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Select Keyfiles"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + + KeyfilesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Select Keyfiles"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~KeyfilesDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class KeyfileGeneratorDialogBase /////////////////////////////////////////////////////////////////////////////// - class KeyfileGeneratorDialogBase : public wxDialog + class KeyfileGeneratorDialogBase : public wxDialog { private: - + protected: wxBoxSizer* MainSizer; wxChoice* HashChoice; @@ -423,46 +423,46 @@ namespace VeraCrypt wxTextCtrl* KeyfilesBaseName; wxPanel* m_panel19; wxButton* GenerateButton; - + // Virtual event handlers, overide them in your derived class virtual void OnMouseMotion( wxMouseEvent& event ) { event.Skip(); } virtual void OnHashSelected( wxCommandEvent& event ) { event.Skip(); } virtual void OnShowRandomPoolCheckBoxClicked( wxCommandEvent& event ) { event.Skip(); } virtual void OnRandomSizeCheckBoxClicked( wxCommandEvent& event ) { event.Skip(); } virtual void OnGenerateButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - KeyfileGeneratorDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + + KeyfileGeneratorDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~KeyfileGeneratorDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class LegalNoticesDialogBase /////////////////////////////////////////////////////////////////////////////// - class LegalNoticesDialogBase : public wxDialog + class LegalNoticesDialogBase : public wxDialog { private: - + protected: wxTextCtrl* LegalNoticesTextCtrl; - + public: - - LegalNoticesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Legal Notices"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + + LegalNoticesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Legal Notices"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~LegalNoticesDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class MountOptionsDialogBase /////////////////////////////////////////////////////////////////////////////// - class MountOptionsDialogBase : public wxDialog + class MountOptionsDialogBase : public wxDialog { private: - + protected: wxBoxSizer* MainSizer; wxBoxSizer* PasswordSizer; @@ -488,7 +488,7 @@ namespace VeraCrypt wxButton* MountPointButton; wxStaticText* FilesystemOptionsStaticText; wxTextCtrl* FilesystemOptionsTextCtrl; - + // Virtual event handlers, overide them in your derived class virtual void OnInitDialog( wxInitDialogEvent& event ) { event.Skip(); } virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } @@ -498,47 +498,47 @@ namespace VeraCrypt virtual void OnProtectionHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } virtual void OnNoFilesystemCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnMountPointButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - MountOptionsDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Enter VeraCrypt Volume Password"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxDEFAULT_DIALOG_STYLE ); + + MountOptionsDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Enter VeraCrypt Volume Password"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxDEFAULT_DIALOG_STYLE ); ~MountOptionsDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class NewSecurityTokenKeyfileDialogBase /////////////////////////////////////////////////////////////////////////////// - class NewSecurityTokenKeyfileDialogBase : public wxDialog + class NewSecurityTokenKeyfileDialogBase : public wxDialog { private: - + protected: wxChoice* SecurityTokenChoice; wxTextCtrl* KeyfileNameTextCtrl; wxStdDialogButtonSizer* StdButtons; wxButton* StdButtonsOK; wxButton* StdButtonsCancel; - + // Virtual event handlers, overide them in your derived class virtual void OnKeyfileNameChanged( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - NewSecurityTokenKeyfileDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("New Security Token Keyfile Properties"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + + NewSecurityTokenKeyfileDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("New Security Token Keyfile Properties"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~NewSecurityTokenKeyfileDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class PreferencesDialogBase /////////////////////////////////////////////////////////////////////////////// - class PreferencesDialogBase : public wxDialog + class PreferencesDialogBase : public wxDialog { private: - + protected: wxNotebook* PreferencesNotebook; wxPanel* SecurityPage; @@ -598,7 +598,7 @@ namespace VeraCrypt wxStdDialogButtonSizer* StdButtons; wxButton* StdButtonsOK; wxButton* StdButtonsCancel; - + // Virtual event handlers, overide them in your derived class virtual void OnClose( wxCloseEvent& event ) { event.Skip(); } virtual void OnDismountOnScreenSaverCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } @@ -615,26 +615,26 @@ namespace VeraCrypt virtual void OnRemoveHotkeyButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnCancelButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: wxPanel* DefaultMountOptionsPage; wxPanel* DefaultKeyfilesPage; wxPanel* SecurityTokensPage; wxPanel* HotkeysPage; - - PreferencesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Preferences"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + + PreferencesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Preferences"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~PreferencesDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class RandomPoolEnrichmentDialogBase /////////////////////////////////////////////////////////////////////////////// - class RandomPoolEnrichmentDialogBase : public wxDialog + class RandomPoolEnrichmentDialogBase : public wxDialog { private: - + protected: wxBoxSizer* MainSizer; wxChoice* HashChoice; @@ -643,27 +643,27 @@ namespace VeraCrypt wxGauge* CollectedEntropy; wxStaticText* MouseStaticText; wxButton* ContinueButton; - + // Virtual event handlers, overide them in your derived class virtual void OnMouseMotion( wxMouseEvent& event ) { event.Skip(); } virtual void OnHashSelected( wxCommandEvent& event ) { event.Skip(); } virtual void OnShowRandomPoolCheckBoxClicked( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - RandomPoolEnrichmentDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Random Pool Enrichment"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + + RandomPoolEnrichmentDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt - Random Pool Enrichment"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~RandomPoolEnrichmentDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class SecurityTokenKeyfilesDialogBase /////////////////////////////////////////////////////////////////////////////// - class SecurityTokenKeyfilesDialogBase : public wxDialog + class SecurityTokenKeyfilesDialogBase : public wxDialog { private: - + protected: wxListCtrl* SecurityTokenKeyfileListCtrl; wxButton* ExportButton; @@ -671,7 +671,7 @@ namespace VeraCrypt wxButton* ImportButton; wxButton* OKButton; wxButton* CancelButton; - + // Virtual event handlers, overide them in your derived class virtual void OnListItemActivated( wxListEvent& event ) { event.Skip(); } virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } @@ -680,41 +680,41 @@ namespace VeraCrypt virtual void OnDeleteButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnImportButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnOKButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - SecurityTokenKeyfilesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Security Token Keyfiles"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxDEFAULT_DIALOG_STYLE ); + + SecurityTokenKeyfilesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Security Token Keyfiles"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxDEFAULT_DIALOG_STYLE ); ~SecurityTokenKeyfilesDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class VolumePropertiesDialogBase /////////////////////////////////////////////////////////////////////////////// - class VolumePropertiesDialogBase : public wxDialog + class VolumePropertiesDialogBase : public wxDialog { private: - + protected: wxListCtrl* PropertiesListCtrl; wxStdDialogButtonSizer* StdButtons; wxButton* StdButtonsOK; - + public: - - VolumePropertiesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Volume Properties"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); + + VolumePropertiesDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Volume Properties"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~VolumePropertiesDialogBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class EncryptionOptionsWizardPageBase /////////////////////////////////////////////////////////////////////////////// class EncryptionOptionsWizardPageBase : public WizardPage { private: - + protected: wxChoice* EncryptionAlgorithmChoice; wxButton* TestButton; @@ -723,47 +723,47 @@ namespace VeraCrypt wxButton* BenchmarkButton; wxChoice* HashChoice; wxHyperlinkCtrl* HashHyperlink; - + // Virtual event handlers, overide them in your derived class virtual void OnEncryptionAlgorithmSelected( wxCommandEvent& event ) { event.Skip(); } virtual void OnTestButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnEncryptionAlgorithmHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } virtual void OnBenchmarkButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnHashHyperlinkClick( wxHyperlinkEvent& event ) { event.Skip(); } - - + + public: - - EncryptionOptionsWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + EncryptionOptionsWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~EncryptionOptionsWizardPageBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class InfoWizardPageBase /////////////////////////////////////////////////////////////////////////////// class InfoWizardPageBase : public WizardPage { private: - + protected: wxBoxSizer* InfoPageSizer; wxStaticText* InfoStaticText; - + public: - - InfoWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + InfoWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~InfoWizardPageBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class KeyfilesPanelBase /////////////////////////////////////////////////////////////////////////////// - class KeyfilesPanelBase : public wxPanel + class KeyfilesPanelBase : public wxPanel { private: - + protected: wxListCtrl* KeyfilesListCtrl; wxButton* AddFilesButton; @@ -771,7 +771,7 @@ namespace VeraCrypt wxButton* AddSecurityTokenSignatureButton; wxButton* RemoveButton; wxButton* RemoveAllButton; - + // Virtual event handlers, overide them in your derived class virtual void OnListItemDeselected( wxListEvent& event ) { event.Skip(); } virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); } @@ -781,89 +781,89 @@ namespace VeraCrypt virtual void OnAddSecurityTokenSignatureButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnRemoveButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnRemoveAllButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - KeyfilesPanelBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + KeyfilesPanelBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~KeyfilesPanelBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class ProgressWizardPageBase /////////////////////////////////////////////////////////////////////////////// class ProgressWizardPageBase : public WizardPage { private: - + protected: wxBoxSizer* ProgressSizer; wxGauge* ProgressGauge; wxButton* AbortButton; wxStaticText* InfoStaticText; - + // Virtual event handlers, overide them in your derived class virtual void OnAbortButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - ProgressWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + ProgressWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~ProgressWizardPageBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class SelectDirectoryWizardPageBase /////////////////////////////////////////////////////////////////////////////// class SelectDirectoryWizardPageBase : public WizardPage { private: - + protected: wxTextCtrl* DirectoryTextCtrl; wxButton* BrowseButton; wxStaticText* InfoStaticText; - + // Virtual event handlers, overide them in your derived class virtual void OnDirectoryTextChanged( wxCommandEvent& event ) { event.Skip(); } virtual void OnBrowseButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - SelectDirectoryWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + SelectDirectoryWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~SelectDirectoryWizardPageBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class SingleChoiceWizardPageBase /////////////////////////////////////////////////////////////////////////////// class SingleChoiceWizardPageBase : public WizardPage { private: - + protected: wxBoxSizer* OuterChoicesSizer; wxBoxSizer* ChoicesSizer; wxStaticText* InfoStaticText; - + public: - - SingleChoiceWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + SingleChoiceWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~SingleChoiceWizardPageBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class VolumeCreationProgressWizardPageBase /////////////////////////////////////////////////////////////////////////////// class VolumeCreationProgressWizardPageBase : public WizardPage { private: - + protected: wxBoxSizer* KeySamplesUpperSizer; wxBoxSizer* KeySamplesUpperInnerSizer; @@ -884,79 +884,79 @@ namespace VeraCrypt wxPanel* m_panel122; wxStaticText* TimeLeftStaticText; wxStaticText* InfoStaticText; - + // Virtual event handlers, overide them in your derived class virtual void OnDisplayKeysCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnAbortButtonClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - VolumeCreationProgressWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + VolumeCreationProgressWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~VolumeCreationProgressWizardPageBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class VolumeLocationWizardPageBase /////////////////////////////////////////////////////////////////////////////// class VolumeLocationWizardPageBase : public WizardPage { private: - + protected: wxComboBox* VolumePathComboBox; wxButton* SelectFileButton; wxButton* SelectDeviceButton; wxCheckBox* NoHistoryCheckBox; wxStaticText* InfoStaticText; - + // Virtual event handlers, overide them in your derived class virtual void OnVolumePathTextChanged( wxCommandEvent& event ) { event.Skip(); } virtual void OnSelectFileButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnSelectDeviceButtonClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnNoHistoryCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - VolumeLocationWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + VolumeLocationWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~VolumeLocationWizardPageBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class VolumeFormatOptionsWizardPageBase /////////////////////////////////////////////////////////////////////////////// class VolumeFormatOptionsWizardPageBase : public WizardPage { private: - + protected: wxStaticText* m_staticText43; wxChoice* FilesystemTypeChoice; wxCheckBox* QuickFormatCheckBox; wxStaticText* InfoStaticText; - + // Virtual event handlers, overide them in your derived class virtual void OnFilesystemTypeSelected( wxCommandEvent& event ) { event.Skip(); } virtual void OnQuickFormatCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - VolumeFormatOptionsWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + VolumeFormatOptionsWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~VolumeFormatOptionsWizardPageBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class VolumePasswordPanelBase /////////////////////////////////////////////////////////////////////////////// - class VolumePasswordPanelBase : public wxPanel + class VolumePasswordPanelBase : public wxPanel { private: - + protected: wxGridBagSizer* GridBagSizer; wxStaticText* PasswordStaticText; @@ -978,7 +978,7 @@ namespace VeraCrypt wxStaticText* HeaderWipeCountText; wxChoice* HeaderWipeCount; wxBoxSizer* PasswordPlaceholderSizer; - + // Virtual event handlers, overide them in your derived class virtual void OnTextChanged( wxCommandEvent& event ) { event.Skip(); } virtual void OnPimChanged( wxCommandEvent& event ) { event.Skip(); } @@ -989,40 +989,40 @@ namespace VeraCrypt virtual void OnKeyfilesButtonRightDown( wxMouseEvent& event ) { event.Skip(); } virtual void OnKeyfilesButtonRightClick( wxMouseEvent& event ) { event.Skip(); } virtual void OnTrueCryptModeChecked( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - VolumePasswordPanelBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + VolumePasswordPanelBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~VolumePasswordPanelBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class VolumePasswordWizardPageBase /////////////////////////////////////////////////////////////////////////////// class VolumePasswordWizardPageBase : public WizardPage { private: - + protected: wxBoxSizer* PasswordPanelSizer; wxStaticText* InfoStaticText; - + public: - - VolumePasswordWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + VolumePasswordWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~VolumePasswordWizardPageBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class VolumePimWizardPageBase /////////////////////////////////////////////////////////////////////////////// class VolumePimWizardPageBase : public WizardPage { private: - + protected: wxBoxSizer* PimPanelSizer; wxBoxSizer* PimSizer; @@ -1031,67 +1031,67 @@ namespace VeraCrypt wxStaticText* VolumePimHelpStaticText; wxCheckBox* DisplayPimCheckBox; wxStaticText* InfoStaticText; - + // Virtual event handlers, overide them in your derived class virtual void OnPimChanged( wxCommandEvent& event ) { event.Skip(); } virtual void OnDisplayPimCheckBoxClick( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - VolumePimWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + VolumePimWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~VolumePimWizardPageBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class VolumeSizeWizardPageBase /////////////////////////////////////////////////////////////////////////////// class VolumeSizeWizardPageBase : public WizardPage { private: - + protected: wxTextCtrl* VolumeSizeTextCtrl; wxChoice* VolumeSizePrefixChoice; wxStaticText* FreeSpaceStaticText; wxStaticText* InfoStaticText; - + // Virtual event handlers, overide them in your derived class virtual void OnVolumeSizeTextChanged( wxCommandEvent& event ) { event.Skip(); } virtual void OnVolumeSizePrefixSelected( wxCommandEvent& event ) { event.Skip(); } - - + + public: - - VolumeSizeWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); + + VolumeSizeWizardPageBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxTAB_TRAVERSAL ); ~VolumeSizeWizardPageBase(); - + }; - + /////////////////////////////////////////////////////////////////////////////// /// Class WaitDialogBase /////////////////////////////////////////////////////////////////////////////// - class WaitDialogBase : public wxDialog + class WaitDialogBase : public wxDialog { private: - + protected: wxStaticText* WaitStaticText; wxGauge* WaitProgessBar; - + // Virtual event handlers, overide them in your derived class virtual void OnWaitDialogClose( wxCloseEvent& event ) { event.Skip(); } virtual void OnWaitDialogInit( wxInitDialogEvent& event ) { event.Skip(); } - - + + public: - - WaitDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxCAPTION ); + + WaitDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("VeraCrypt"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxCAPTION ); ~WaitDialogBase(); - + }; - + } // namespace VeraCrypt #endif //__FORMS_H__ diff --git a/src/Main/Forms/InfoWizardPage.cpp b/src/Main/Forms/InfoWizardPage.cpp index f41b1d51..1c36d116 100644 --- a/src/Main/Forms/InfoWizardPage.cpp +++ b/src/Main/Forms/InfoWizardPage.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/InfoWizardPage.h b/src/Main/Forms/InfoWizardPage.h index 15402041..f44061c0 100644 --- a/src/Main/Forms/InfoWizardPage.h +++ b/src/Main/Forms/InfoWizardPage.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/KeyfileGeneratorDialog.cpp b/src/Main/Forms/KeyfileGeneratorDialog.cpp index 61f16287..885f56d2 100644 --- a/src/Main/Forms/KeyfileGeneratorDialog.cpp +++ b/src/Main/Forms/KeyfileGeneratorDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -17,10 +17,10 @@ namespace VeraCrypt { - KeyfileGeneratorDialog::KeyfileGeneratorDialog (wxWindow* parent) : KeyfileGeneratorDialogBase (parent) + KeyfileGeneratorDialog::KeyfileGeneratorDialog (wxWindow* parent) : KeyfileGeneratorDialogBase (parent) { RandomNumberGenerator::Start(); - + Hashes = Hash::GetAvailableAlgorithms(); foreach (shared_ptr hash, Hashes) { @@ -33,7 +33,7 @@ namespace VeraCrypt HideBytes (RandomPoolStaticText, 24); MouseStaticText->Wrap (Gui->GetCharWidth (MouseStaticText) * 70); - + CollectedEntropy->SetRange (RNG_POOL_SIZE * 8); MainSizer->SetMinSize (wxSize (-1, Gui->GetCharHeight (this) * 24)); @@ -41,7 +41,7 @@ namespace VeraCrypt Layout(); Fit(); Center(); - + MouseEventsCounter = 0; foreach (wxWindow *c, this->GetChildren()) @@ -57,36 +57,36 @@ namespace VeraCrypt try { int keyfilesCount = NumberOfKeyfiles->GetValue(); - int keyfilesSize = KeyfilesSize->GetValue(); + int keyfilesSize = KeyfilesSize->GetValue(); bool useRandomSize = RandomSizeCheckBox->IsChecked(); wxString keyfileBaseName = KeyfilesBaseName->GetValue(); keyfileBaseName.Trim(true); keyfileBaseName.Trim(false); - + if (keyfileBaseName.IsEmpty()) { Gui->ShowWarning("KEYFILE_EMPTY_BASE_NAME"); return; } - + wxFileName baseFileName = wxFileName::FileName (keyfileBaseName); if (!baseFileName.IsOk()) { Gui->ShowWarning("KEYFILE_INVALID_BASE_NAME"); return; } - + DirectoryPath keyfilesDir = Gui->SelectDirectory (Gui->GetActiveWindow(), LangString["SELECT_KEYFILE_GENERATION_DIRECTORY"], false); if (keyfilesDir.IsEmpty()) return; - + wxFileName dirFileName = wxFileName::DirName( wstring(keyfilesDir).c_str() ); if (!dirFileName.IsDirWritable ()) { Gui->ShowWarning(L"You don't have write permission on the selected directory"); return; } - + wxBusyCursor busy; for (int i = 0; i < keyfilesCount; i++) { @@ -95,26 +95,26 @@ namespace VeraCrypt { SecureBuffer sizeBuffer (sizeof(int)); RandomNumberGenerator::GetData (sizeBuffer, true); - + memcpy(&bufferLen, sizeBuffer.Ptr(), sizeof(int)); /* since keyfilesSize < 1024 * 1024, we mask with 0x000FFFFF */ bufferLen = (long) (((unsigned long) bufferLen) & 0x000FFFFF); bufferLen %= ((1024*1024 - 64) + 1); - bufferLen += 64; + bufferLen += 64; } else bufferLen = keyfilesSize; SecureBuffer keyfileBuffer (bufferLen); RandomNumberGenerator::GetData (keyfileBuffer, true); - + wstringstream convertStream; convertStream << i; - wxString suffix = L"_"; - suffix += convertStream.str().c_str(); - + wxString suffix = L"_"; + suffix += convertStream.str().c_str(); + wxFileName keyfileName; if (i == 0) { @@ -131,12 +131,12 @@ namespace VeraCrypt keyfileName.Assign(dirFileName.GetPath(), keyfileBaseName + suffix); } } - + if (keyfileName.Exists()) { wxString msg = wxString::Format(LangString["KEYFILE_ALREADY_EXISTS"], keyfileName.GetFullPath()); if (!Gui->AskYesNo (msg, false, true)) - return; + return; } { @@ -175,7 +175,7 @@ namespace VeraCrypt ShowBytes (RandomPoolStaticText, RandomNumberGenerator::PeekPool().GetRange (0, 24)); else HideBytes (RandomPoolStaticText, 24); - + /* conservative estimate: 1 mouse move event brings 1 bit of entropy * https://security.stackexchange.com/questions/32844/for-how-much-time-should-i-randomly-move-the-mouse-for-generating-encryption-key/32848#32848 */ @@ -183,7 +183,7 @@ namespace VeraCrypt if (MouseEventsCounter < (RNG_POOL_SIZE * 8)) CollectedEntropy->SetValue (++MouseEventsCounter); } - + void KeyfileGeneratorDialog::OnShowRandomPoolCheckBoxClicked (wxCommandEvent& event) { if (!event.IsChecked()) @@ -217,7 +217,7 @@ namespace VeraCrypt str[i] = L'X'; } } - + void KeyfileGeneratorDialog::HideBytes (wxStaticText *textCtrl, size_t len) { wxString str; diff --git a/src/Main/Forms/KeyfileGeneratorDialog.h b/src/Main/Forms/KeyfileGeneratorDialog.h index e4fd3633..e990a70b 100644 --- a/src/Main/Forms/KeyfileGeneratorDialog.h +++ b/src/Main/Forms/KeyfileGeneratorDialog.h @@ -3,7 +3,7 @@ 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) + 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 @@ -32,7 +32,7 @@ namespace VeraCrypt void OnRandomSizeCheckBoxClicked( wxCommandEvent& event ); void ShowBytes (wxStaticText *textCtrl, const ConstBufferPtr &buffer, bool appendDots = true); void HideBytes (wxStaticText *textCtrl, size_t len); - + HashList Hashes; int MouseEventsCounter; Mutex AccessMutex; diff --git a/src/Main/Forms/KeyfilesDialog.cpp b/src/Main/Forms/KeyfilesDialog.cpp index 9c7d4560..f07df6b7 100644 --- a/src/Main/Forms/KeyfilesDialog.cpp +++ b/src/Main/Forms/KeyfilesDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -35,7 +35,7 @@ namespace VeraCrypt Fit(); Center(); } - + void KeyfilesDialog::OnCreateKeyfileButttonClick (wxCommandEvent& event) { Gui->CreateKeyfile(); diff --git a/src/Main/Forms/KeyfilesDialog.h b/src/Main/Forms/KeyfilesDialog.h index 01c52733..24715069 100644 --- a/src/Main/Forms/KeyfilesDialog.h +++ b/src/Main/Forms/KeyfilesDialog.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/KeyfilesPanel.cpp b/src/Main/Forms/KeyfilesPanel.cpp index d7e4835c..782a5cd6 100644 --- a/src/Main/Forms/KeyfilesPanel.cpp +++ b/src/Main/Forms/KeyfilesPanel.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -84,7 +84,7 @@ namespace VeraCrypt return keyfiles; } - + void KeyfilesPanel::OnAddDirectoryButtonClick (wxCommandEvent& event) { DirectoryPath dir = Gui->SelectDirectory (this, LangString["SELECT_KEYFILE_PATH"]); diff --git a/src/Main/Forms/KeyfilesPanel.h b/src/Main/Forms/KeyfilesPanel.h index 104a96d2..e929732c 100644 --- a/src/Main/Forms/KeyfilesPanel.h +++ b/src/Main/Forms/KeyfilesPanel.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/LegalNoticesDialog.cpp b/src/Main/Forms/LegalNoticesDialog.cpp index 5ed18ac0..1bbdb2dc 100644 --- a/src/Main/Forms/LegalNoticesDialog.cpp +++ b/src/Main/Forms/LegalNoticesDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -22,7 +22,7 @@ namespace VeraCrypt LegalNoticesTextCtrl->SetMinSize (wxSize ( Gui->GetCharWidth (LegalNoticesTextCtrl) * 88, Gui->GetCharHeight (LegalNoticesTextCtrl) * 28)); - + Layout(); Fit(); Center(); diff --git a/src/Main/Forms/LegalNoticesDialog.h b/src/Main/Forms/LegalNoticesDialog.h index e33f35cc..49b1878d 100644 --- a/src/Main/Forms/LegalNoticesDialog.h +++ b/src/Main/Forms/LegalNoticesDialog.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/MainFrame.cpp b/src/Main/Forms/MainFrame.cpp index e467eba4..b693fbe0 100644 --- a/src/Main/Forms/MainFrame.cpp +++ b/src/Main/Forms/MainFrame.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -208,7 +208,7 @@ namespace VeraCrypt wstring args = StringFormatter (repair ? L"/C echo {0} & chkdsk {1} /F /X & pause" : L"/C echo {0} & chkdsk {1} & pause", StringFormatter (LangString[repair ? "REPAIRING_FS" : "CHECKING_FS"], mountPoint), mountPoint); - ShellExecute (static_cast (GetHandle()), + ShellExecute (static_cast (GetHandle()), L"runas", L"cmd.exe", args.c_str(), nullptr, SW_SHOW); #else @@ -260,7 +260,7 @@ namespace VeraCrypt void MainFrame::InitControls () { LogoBitmap->SetBitmap (Resources::GetLogoBitmap()); - + list colPermilles; #ifndef TC_WINDOWS @@ -280,7 +280,7 @@ namespace VeraCrypt MountAllDevicesButton->SetLabel (_("Mount All Devices")); #endif -#ifdef TC_WINDOWS +#ifdef TC_WINDOWS SlotListCtrl->InsertColumn (ColumnSlot, LangString["DRIVE"], wxLIST_FORMAT_LEFT, 1); colPermilles.push_back (75); #else @@ -289,20 +289,20 @@ namespace VeraCrypt #endif SlotListCtrl->InsertColumn (ColumnPath, LangString["VOLUME"], wxLIST_FORMAT_LEFT, 1); -#ifdef TC_WINDOWS +#ifdef TC_WINDOWS colPermilles.push_back (487); #else colPermilles.push_back (429); #endif SlotListCtrl->InsertColumn (ColumnSize, LangString["SIZE"], wxLIST_FORMAT_RIGHT, 1); -#ifdef TC_WINDOWS +#ifdef TC_WINDOWS colPermilles.push_back (126); #else colPermilles.push_back (130); #endif -#ifdef TC_WINDOWS +#ifdef TC_WINDOWS SlotListCtrl->InsertColumn (ColumnEA, LangString["ENCRYPTION_ALGORITHM_LV"], wxLIST_FORMAT_LEFT, 1); colPermilles.push_back (233); #else @@ -323,7 +323,7 @@ namespace VeraCrypt #ifndef TC_WINDOWS int screenHeight = wxSystemSettings::GetMetric (wxSYS_SCREEN_Y); - + if (screenHeight < 480) slotListRowCount = 1; else if (screenHeight <= 600) @@ -355,7 +355,7 @@ namespace VeraCrypt SetMaxSize (GetSize()); Gui->SetListCtrlColumnWidths (SlotListCtrl, colPermilles); - + UpdateVolumeList(); UpdateWipeCacheButton(); } @@ -434,7 +434,7 @@ namespace VeraCrypt { MainFrame *frame = dynamic_cast (Gui->GetMainFrame()); PDEV_BROADCAST_HDR hdr = (PDEV_BROADCAST_HDR) lParam; - + if (wParam == DBT_DEVICEREMOVECOMPLETE && hdr->dbch_devicetype == DBT_DEVTYP_VOLUME) { PDEV_BROADCAST_VOLUME vol = (PDEV_BROADCAST_VOLUME) lParam; @@ -504,15 +504,15 @@ namespace VeraCrypt } wxMenu *CreatePopupMenu () - { + { auto_ptr popup (new wxMenu); Gui->AppendToMenu (*popup, LangString[Gui->IsInBackgroundMode() ? "SHOW_TC" : "HIDE_TC"], this, wxCommandEventHandler (TaskBarIcon::OnShowHideMenuItemSelected)); - + popup->AppendSeparator(); Gui->AppendToMenu (*popup, _("Mount All Favorite Volumes"), this, wxCommandEventHandler (TaskBarIcon::OnMountAllFavoritesMenuItemSelected))->Enable (!Busy); Gui->AppendToMenu (*popup, _("Dismount All Mounted Volumes"), this, wxCommandEventHandler (TaskBarIcon::OnDismountAllMenuItemSelected))->Enable (!Busy); - + // Favorite volumes if (Gui->GetPreferences().BackgroundTaskMenuMountItemsEnabled && !Frame->FavoriteVolumesMenuMap.empty()) { @@ -628,7 +628,7 @@ namespace VeraCrypt Gui->SetPreferences (prefs); NoHistoryCheckBox->SetValue (!prefs.SaveHistory); } - + void MainFrame::MountAllDevices () { try @@ -891,7 +891,7 @@ namespace VeraCrypt } void MainFrame::OnDefaultMountParametersMenuItemSelected(wxCommandEvent& event) - { + { #ifdef TC_MACOSX if (Gui->IsInBackgroundMode()) Gui->SetBackgroundMode (false); @@ -921,7 +921,7 @@ namespace VeraCrypt if (volume->Path.IsDevice() && !Core->IsDevicePresent (volume->Path)) removedVolumes.push_back (volume); } - + if (!removedVolumes.empty()) Gui->AutoDismountVolumes (removedVolumes, true); } @@ -1035,7 +1035,7 @@ namespace VeraCrypt case Hotkey::Id::MountAllFavorites: { size_t mountedCount = Core->GetMountedVolumes().size(); - + if (event.GetId() == Hotkey::Id::MountAllDevices) MountAllDevices(); else @@ -1102,7 +1102,7 @@ namespace VeraCrypt if (SelectedItemIndex > itemIndex) --SelectedItemIndex; } - + void MainFrame::OnListItemDeselected (wxListEvent& event) { OnListItemSelectionChanged(); @@ -1155,7 +1155,7 @@ namespace VeraCrypt else if (IsFreeSlotSelected()) { Gui->AppendToMenu (popup, _("Mount Volume"), this, wxCommandEventHandler (MainFrame::OnMountVolumeMenuItemSelected)); - + popup.AppendSeparator(); Gui->AppendToMenu (popup, LangString["SELECT_FILE_AND_MOUNT"], this, wxCommandEventHandler (MainFrame::OnSelectFileAndMountMenuItemSelected)); @@ -1174,12 +1174,12 @@ namespace VeraCrypt SelectedItemIndex = event.GetIndex(); OnListItemSelectionChanged(); } - + void MainFrame::OnListItemSelectionChanged () { if (SlotListCtrl->GetSelectedItemCount() < 1) SelectedItemIndex = -1; - + if (SelectedItemIndex >= 0) SelectedSlotNumber = (VolumeSlotNumber) SlotListCtrl->GetItemData (SelectedItemIndex); else @@ -1187,7 +1187,7 @@ namespace VeraCrypt UpdateControls(); } - + void MainFrame::OnManageSecurityTokenKeyfilesMenuItemSelected (wxCommandEvent& event) { try @@ -1280,7 +1280,7 @@ namespace VeraCrypt SavePreferences(); } - + void MainFrame::OnRestoreVolumeHeaderMenuItemSelected (wxCommandEvent& event) { if (!CheckVolumePathNotEmpty ()) @@ -1307,7 +1307,7 @@ namespace VeraCrypt dialog.ShowModal(); } - + void MainFrame::OnSelectDeviceAndMountMenuItemSelected (wxCommandEvent& event) { DevicePath path = Gui->SelectDevice (this); @@ -1344,7 +1344,7 @@ namespace VeraCrypt if (!path.IsEmpty()) SetVolumePath (path); } - + void MainFrame::OnTimer () { try @@ -1502,7 +1502,7 @@ namespace VeraCrypt WipeCache(); Gui->ShowInfo ("PASSWORD_CACHE_WIPED"); } - + void MainFrame::OpenSelectedVolume () const { shared_ptr selectedVolume = GetSelectedVolume(); @@ -1577,7 +1577,7 @@ namespace VeraCrypt } return -1; } - + void MainFrame::UpdateControls () { bool mounted = IsMountedSlotSelected(); @@ -1585,7 +1585,7 @@ namespace VeraCrypt VolumeButton->SetLabel (mounted ? LangString["DISMOUNT"] : wxString (_("Mount"))); VolumePropertiesButton->Enable (mounted); - DismountVolumeMenuItem->Enable (mounted); + DismountVolumeMenuItem->Enable (mounted); MountVolumeMenuItem->Enable (!mounted); VolumePropertiesMenuItem->Enable (mounted); AddToFavoritesMenuItem->Enable (mounted); @@ -1601,7 +1601,7 @@ namespace VeraCrypt bool listChanged = false; MountedVolumes = Core->GetMountedVolumes(); - + map < VolumeSlotNumber, shared_ptr > mountedVolumesMap; foreach (shared_ptr volume, MountedVolumes) { @@ -1632,7 +1632,7 @@ namespace VeraCrypt fields[ColumnPath] = volume->Path; fields[ColumnSize] = Gui->SizeToString (volume->Size); fields[ColumnType] = Gui->VolumeTypeToString (volume->Type, volume->TrueCryptMode, volume->Protection); - + if (volume->HiddenVolumeProtectionTriggered) { fields[ColumnType] += L"(!)"; @@ -1667,7 +1667,7 @@ namespace VeraCrypt #else fields[ColumnSlot] = StringConverter::FromNumber (slotNumber); #endif - + #ifdef TC_WINDOWS if (Core->IsMountPointAvailable (fields[ColumnSlot])) #else diff --git a/src/Main/Forms/MainFrame.h b/src/Main/Forms/MainFrame.h index 9ae1907e..15c08b36 100644 --- a/src/Main/Forms/MainFrame.h +++ b/src/Main/Forms/MainFrame.h @@ -3,7 +3,7 @@ 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) + 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 @@ -87,7 +87,7 @@ namespace VeraCrypt void OnCloseAllSecurityTokenSessionsMenuItemSelected (wxCommandEvent& event); void OnDonateMenuItemSelected (wxCommandEvent& event) { Gui->OpenHomepageLink (this, L"donate"); } void OnContactMenuItemSelected (wxCommandEvent& event) { Gui->OpenHomepageLink (this, L"contact"); } - void OnCreateKeyfileMenuItemSelected (wxCommandEvent& event) + void OnCreateKeyfileMenuItemSelected (wxCommandEvent& event) { #ifdef TC_MACOSX if (Gui->IsInBackgroundMode()) @@ -161,7 +161,7 @@ namespace VeraCrypt void UpdateVolumeList (); void UpdateWipeCacheButton (); void WipeCache (); - + struct VolumeActivityMapEntry { VolumeActivityMapEntry () { } diff --git a/src/Main/Forms/MountOptionsDialog.cpp b/src/Main/Forms/MountOptionsDialog.cpp index 55098b0e..c6b47fd5 100644 --- a/src/Main/Forms/MountOptionsDialog.cpp +++ b/src/Main/Forms/MountOptionsDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -85,21 +85,21 @@ namespace VeraCrypt } void MountOptionsDialog::OnOKButtonClick (wxCommandEvent& event) - { + { bool bUnsupportedKdf = false; - + /* verify that PIM values are valid before continuing*/ int Pim = PasswordPanel->GetVolumePim(); int ProtectionPim = (!ReadOnlyCheckBox->IsChecked() && ProtectionCheckBox->IsChecked())? ProtectionPasswordPanel->GetVolumePim() : 0; - + /* invalid PIM: set focus to PIM field and stop processing */ if (-1 == Pim || (PartitionInSystemEncryptionScopeCheckBox->IsChecked() && Pim > MAX_BOOT_PIM_VALUE)) { PasswordPanel->SetFocusToPimTextCtrl(); return; } - + if (-1 == ProtectionPim || (PartitionInSystemEncryptionScopeCheckBox->IsChecked() && ProtectionPim > MAX_BOOT_PIM_VALUE)) { ProtectionPasswordPanel->SetFocusToPimTextCtrl(); @@ -142,7 +142,7 @@ namespace VeraCrypt Gui->ShowWarning (e); return; } - Options.Protection = VolumeProtection::HiddenVolumeReadOnly; + Options.Protection = VolumeProtection::HiddenVolumeReadOnly; Options.ProtectionPim = ProtectionPim; Options.ProtectionKdf = ProtectionPasswordPanel->GetPkcs5Kdf(Options.TrueCryptMode, bUnsupportedKdf); if (bUnsupportedKdf) diff --git a/src/Main/Forms/MountOptionsDialog.h b/src/Main/Forms/MountOptionsDialog.h index bf50057b..77214e69 100644 --- a/src/Main/Forms/MountOptionsDialog.h +++ b/src/Main/Forms/MountOptionsDialog.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/NewSecurityTokenKeyfileDialog.cpp b/src/Main/Forms/NewSecurityTokenKeyfileDialog.cpp index 34cd08ff..e3019a7e 100644 --- a/src/Main/Forms/NewSecurityTokenKeyfileDialog.cpp +++ b/src/Main/Forms/NewSecurityTokenKeyfileDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/NewSecurityTokenKeyfileDialog.h b/src/Main/Forms/NewSecurityTokenKeyfileDialog.h index dad2879e..ca3d5258 100644 --- a/src/Main/Forms/NewSecurityTokenKeyfileDialog.h +++ b/src/Main/Forms/NewSecurityTokenKeyfileDialog.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/PreferencesDialog.cpp b/src/Main/Forms/PreferencesDialog.cpp index 436b9508..3f38c7c0 100644 --- a/src/Main/Forms/PreferencesDialog.cpp +++ b/src/Main/Forms/PreferencesDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -52,16 +52,16 @@ namespace VeraCrypt MountRemovableCheckBox->SetValidator (wxGenericValidator (&Preferences.DefaultMountOptions.Removable)); FilesystemOptionsTextCtrl->SetValue (Preferences.DefaultMountOptions.FilesystemOptions); - + TrueCryptModeCheckBox->SetValidator (wxGenericValidator (&Preferences.DefaultMountOptions.TrueCryptMode)); - + int index, prfInitialIndex = 0; - Pkcs5PrfChoice->Append (LangString["AUTODETECTION"]); + Pkcs5PrfChoice->Append (LangString["AUTODETECTION"]); foreach_ref (const Pkcs5Kdf &kdf, Pkcs5Kdf::GetAvailableAlgorithms(false)) { index = Pkcs5PrfChoice->Append (kdf.GetName()); - if (Preferences.DefaultMountOptions.Kdf + if (Preferences.DefaultMountOptions.Kdf && (Preferences.DefaultMountOptions.Kdf->GetName() == kdf.GetName()) ) { @@ -157,7 +157,7 @@ namespace VeraCrypt colPermilles.push_back (358); vector fields (HotkeyListCtrl->GetColumnCount()); - + UnregisteredHotkeys = Preferences.Hotkeys; Hotkey::UnregisterList (Gui->GetMainFrame(), UnregisteredHotkeys); @@ -363,7 +363,7 @@ namespace VeraCrypt #endif if (!Validate()) return; - + shared_ptr selectedKdf; if (Pkcs5PrfChoice->GetSelection () != 0) { @@ -383,7 +383,7 @@ namespace VeraCrypt Preferences.DefaultMountOptions.Protection = MountReadOnlyCheckBox->IsChecked() ? VolumeProtection::ReadOnly : VolumeProtection::None; Preferences.DefaultMountOptions.FilesystemOptions = FilesystemOptionsTextCtrl->GetValue(); Preferences.DefaultKeyfiles = *DefaultKeyfilesPanel->GetKeyfiles(); - + Preferences.DefaultMountOptions.Kdf = selectedKdf; Preferences.DefaultMountOptions.ProtectionKdf = selectedKdf; @@ -403,7 +403,7 @@ namespace VeraCrypt } else { - Gui->InitSecurityTokenLibrary(); + Gui->InitSecurityTokenLibrary(); } } } @@ -419,7 +419,7 @@ namespace VeraCrypt EndModal (wxID_OK); } - + void PreferencesDialog::OnPreserveTimestampsCheckBoxClick (wxCommandEvent& event) { #ifdef TC_LINUX @@ -504,7 +504,7 @@ namespace VeraCrypt HotkeyAltCheckBox->SetValue (alt); HotkeyWinCheckBox->SetValue (win); - HotkeyTextCtrl->ChangeValue (Hotkey::GetVirtualKeyCodeString (LastVirtualKeyPressed)); + HotkeyTextCtrl->ChangeValue (Hotkey::GetVirtualKeyCodeString (LastVirtualKeyPressed)); UpdateHotkeyButtons(); return; } diff --git a/src/Main/Forms/PreferencesDialog.h b/src/Main/Forms/PreferencesDialog.h index f45145c2..0f892381 100644 --- a/src/Main/Forms/PreferencesDialog.h +++ b/src/Main/Forms/PreferencesDialog.h @@ -3,7 +3,7 @@ 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) + 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 @@ -53,7 +53,7 @@ namespace VeraCrypt }; KeyfilesPanel *DefaultKeyfilesPanel; - int LastVirtualKeyPressed; + int LastVirtualKeyPressed; auto_ptr mTimer; UserPreferences Preferences; bool RestoreValidatorBell; diff --git a/src/Main/Forms/ProgressWizardPage.cpp b/src/Main/Forms/ProgressWizardPage.cpp index bba162af..5ad739d9 100644 --- a/src/Main/Forms/ProgressWizardPage.cpp +++ b/src/Main/Forms/ProgressWizardPage.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/ProgressWizardPage.h b/src/Main/Forms/ProgressWizardPage.h index 57a34dac..be774063 100644 --- a/src/Main/Forms/ProgressWizardPage.h +++ b/src/Main/Forms/ProgressWizardPage.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/RandomPoolEnrichmentDialog.cpp b/src/Main/Forms/RandomPoolEnrichmentDialog.cpp index ecbfe7ac..fa9b0729 100644 --- a/src/Main/Forms/RandomPoolEnrichmentDialog.cpp +++ b/src/Main/Forms/RandomPoolEnrichmentDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -17,10 +17,10 @@ namespace VeraCrypt { - RandomPoolEnrichmentDialog::RandomPoolEnrichmentDialog (wxWindow* parent) : RandomPoolEnrichmentDialogBase (parent) + RandomPoolEnrichmentDialog::RandomPoolEnrichmentDialog (wxWindow* parent) : RandomPoolEnrichmentDialogBase (parent) { RandomNumberGenerator::Start(); - + Hashes = Hash::GetAvailableAlgorithms(); foreach (shared_ptr hash, Hashes) { @@ -35,7 +35,7 @@ namespace VeraCrypt HideBytes (RandomPoolStaticText, 24); MouseStaticText->Wrap (Gui->GetCharWidth (MouseStaticText) * 70); - + CollectedEntropy->SetRange (RNG_POOL_SIZE * 8); MainSizer->SetMinSize (wxSize (-1, Gui->GetCharHeight (this) * 24)); @@ -43,7 +43,7 @@ namespace VeraCrypt Layout(); Fit(); Center(); - + MouseEventsCounter = 0; foreach (wxWindow *c, this->GetChildren()) @@ -107,7 +107,7 @@ namespace VeraCrypt str[i] = L'X'; } } - + void RandomPoolEnrichmentDialog::HideBytes (wxStaticText *textCtrl, size_t len) { wxString str; diff --git a/src/Main/Forms/RandomPoolEnrichmentDialog.h b/src/Main/Forms/RandomPoolEnrichmentDialog.h index 4135ff28..aa118727 100644 --- a/src/Main/Forms/RandomPoolEnrichmentDialog.h +++ b/src/Main/Forms/RandomPoolEnrichmentDialog.h @@ -3,7 +3,7 @@ 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) + 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 @@ -30,7 +30,7 @@ namespace VeraCrypt void OnShowRandomPoolCheckBoxClicked (wxCommandEvent& event); void ShowBytes (wxStaticText *textCtrl, const ConstBufferPtr &buffer); void HideBytes (wxStaticText *textCtrl, size_t len); - + HashList Hashes; int MouseEventsCounter; Mutex AccessMutex; diff --git a/src/Main/Forms/SecurityTokenKeyfilesDialog.cpp b/src/Main/Forms/SecurityTokenKeyfilesDialog.cpp index 05ae4290..abc06a77 100644 --- a/src/Main/Forms/SecurityTokenKeyfilesDialog.cpp +++ b/src/Main/Forms/SecurityTokenKeyfilesDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -65,7 +65,7 @@ namespace VeraCrypt fields[ColumnSecurityTokenLabel] = key.Token.Label; fields[ColumnSecurityTokenKeyfileLabel] = key.Id; - Gui->AppendToListCtrl (SecurityTokenKeyfileListCtrl, fields, 0, &SecurityTokenKeyfileList[i++]); + Gui->AppendToListCtrl (SecurityTokenKeyfileListCtrl, fields, 0, &SecurityTokenKeyfileList[i++]); } } @@ -155,7 +155,7 @@ namespace VeraCrypt { wxBusyCursor busy; SecurityToken::CreateKeyfile (newKeyfileDialog.GetSelectedSlotId(), keyfileData, StringConverter::ToSingle (newKeyfileDialog.GetKeyfileName())); - + FillSecurityTokenKeyfileListCtrl(); } } diff --git a/src/Main/Forms/SecurityTokenKeyfilesDialog.h b/src/Main/Forms/SecurityTokenKeyfilesDialog.h index 6a8b51fd..de0e1f44 100644 --- a/src/Main/Forms/SecurityTokenKeyfilesDialog.h +++ b/src/Main/Forms/SecurityTokenKeyfilesDialog.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/SelectDirectoryWizardPage.cpp b/src/Main/Forms/SelectDirectoryWizardPage.cpp index 725371ac..28b4fc9b 100644 --- a/src/Main/Forms/SelectDirectoryWizardPage.cpp +++ b/src/Main/Forms/SelectDirectoryWizardPage.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -25,7 +25,7 @@ namespace VeraCrypt return false; } - + void SelectDirectoryWizardPage::OnBrowseButtonClick (wxCommandEvent& event) { DirectoryPath dir = Gui->SelectDirectory (this); diff --git a/src/Main/Forms/SelectDirectoryWizardPage.h b/src/Main/Forms/SelectDirectoryWizardPage.h index b50699ee..f2571348 100644 --- a/src/Main/Forms/SelectDirectoryWizardPage.h +++ b/src/Main/Forms/SelectDirectoryWizardPage.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/SingleChoiceWizardPage.h b/src/Main/Forms/SingleChoiceWizardPage.h index 751ec402..865e2b21 100644 --- a/src/Main/Forms/SingleChoiceWizardPage.h +++ b/src/Main/Forms/SingleChoiceWizardPage.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/VolumeCreationProgressWizardPage.cpp b/src/Main/Forms/VolumeCreationProgressWizardPage.cpp index 08986f5e..ccc4cb73 100644 --- a/src/Main/Forms/VolumeCreationProgressWizardPage.cpp +++ b/src/Main/Forms/VolumeCreationProgressWizardPage.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -54,7 +54,7 @@ namespace VeraCrypt } VolumeCreationProgressWizardPage *Page; - }; + }; RandomPoolTimer.reset (dynamic_cast (new Timer (this))); RandomPoolTimer->Start (30); @@ -73,9 +73,9 @@ namespace VeraCrypt { if (!event.IsChecked()) { - ShowAsterisks (RandomPoolSampleStaticText); - ShowAsterisks (HeaderKeySampleStaticText); - ShowAsterisks (MasterKeySampleStaticText); + ShowAsterisks (RandomPoolSampleStaticText); + ShowAsterisks (HeaderKeySampleStaticText); + ShowAsterisks (MasterKeySampleStaticText); } else { @@ -84,7 +84,7 @@ namespace VeraCrypt MasterKeySampleStaticText->SetLabel (L""); } } - + void VolumeCreationProgressWizardPage::OnRandomPoolTimer () { if (!VolumeCreatorRunning && DisplayKeysCheckBox->IsChecked()) @@ -187,7 +187,7 @@ namespace VeraCrypt RealProgressBarRange = ProgressGauge->GetSize().GetWidth(); ProgressGauge->SetRange (RealProgressBarRange); } - + void VolumeCreationProgressWizardPage::IncrementEntropyProgress () { ScopeLock lock (AccessMutex); diff --git a/src/Main/Forms/VolumeCreationProgressWizardPage.h b/src/Main/Forms/VolumeCreationProgressWizardPage.h index 417766e4..82144269 100644 --- a/src/Main/Forms/VolumeCreationProgressWizardPage.h +++ b/src/Main/Forms/VolumeCreationProgressWizardPage.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/VolumeCreationWizard.cpp b/src/Main/Forms/VolumeCreationWizard.cpp index e9ceb3a3..05568f82 100644 --- a/src/Main/Forms/VolumeCreationWizard.cpp +++ b/src/Main/Forms/VolumeCreationWizard.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -69,7 +69,7 @@ namespace VeraCrypt } VolumeCreationWizard *Wizard; - }; + }; RandomPoolUpdateTimer.reset (dynamic_cast (new Timer (this))); RandomPoolUpdateTimer->Start (200); @@ -129,11 +129,11 @@ namespace VeraCrypt page->SetVolumePath (SelectedVolumePath); return page; } - + case Step::EncryptionOptions: { EncryptionOptionsWizardPage *page = new EncryptionOptionsWizardPage (GetPageParent()); - + if (OuterVolume) page->SetPageTitle (LangString["CIPHER_HIDVOL_HOST_TITLE"]); else if (SelectedVolumeType == VolumeType::Hidden) @@ -170,10 +170,10 @@ namespace VeraCrypt } VolumeSizeWizardPage *page = new VolumeSizeWizardPage (GetPageParent(), SelectedVolumePath, SectorSize, freeSpaceText); - + page->SetPageTitle (pageTitle); page->SetPageText (pageText); - + if (!OuterVolume && SelectedVolumeType == VolumeType::Hidden) page->SetMaxVolumeSize (MaxHiddenVolumeSize); else @@ -194,29 +194,29 @@ namespace VeraCrypt VolumePasswordWizardPage *page = new VolumePasswordWizardPage (GetPageParent(), Password, Keyfiles); page->EnableUsePim (); // force displaying "Use PIM" page->SetPimSelected (Pim > 0); - + if (OuterVolume) page->SetPageTitle (LangString["PASSWORD_HIDVOL_HOST_TITLE"]); else if (SelectedVolumeType == VolumeType::Hidden) page->SetPageTitle (LangString["PASSWORD_HIDVOL_TITLE"]); else page->SetPageTitle (LangString["PASSWORD_TITLE"]); - + page->SetPageText (LangString[OuterVolume ? "PASSWORD_HIDDENVOL_HOST_HELP" : "PASSWORD_HELP"]); return page; } - + case Step::VolumePim: { VolumePimWizardPage *page = new VolumePimWizardPage (GetPageParent()); - + if (OuterVolume) page->SetPageTitle (LangString["PIM_HIDVOL_HOST_TITLE"]); else if (SelectedVolumeType == VolumeType::Hidden) page->SetPageTitle (LangString["PIM_HIDVOL_TITLE"]); else page->SetPageTitle (LangString["PIM_TITLE"]); - + page->SetPageText (LangString["PIM_HELP"]); page->SetVolumePim (Pim); return page; @@ -244,14 +244,14 @@ namespace VeraCrypt page->SetPageTitle (_("Format Options")); page->SetFilesystemType (SelectedFilesystemType); - + if (!OuterVolume && SelectedVolumeType == VolumeType::Hidden) QuickFormatEnabled = true; page->SetQuickFormat (QuickFormatEnabled); return page; } - + case Step::CrossPlatformSupport: { SingleChoiceWizardPage *page = new SingleChoiceWizardPage (GetPageParent(), wxEmptyString, true); @@ -289,7 +289,7 @@ namespace VeraCrypt InfoWizardPage *page = new InfoWizardPage (GetPageParent()); page->SetPageTitle (LangString["FORMAT_FINISHED_TITLE"]); page->SetPageText (LangString["FORMAT_FINISHED_HELP"]); - + SetCancelButtonText (_("Exit")); return page; } @@ -318,16 +318,16 @@ namespace VeraCrypt Close(); return new InfoWizardPage (GetPageParent()); } - + struct OpenOuterVolumeFunctor : public Functor { OpenOuterVolumeFunctor (const DirectoryPath &outerVolumeMountPoint) : OuterVolumeMountPoint (outerVolumeMountPoint) { } - + virtual void operator() () { Gui->OpenExplorerWindow (OuterVolumeMountPoint); } - + DirectoryPath OuterVolumeMountPoint; }; @@ -335,11 +335,11 @@ namespace VeraCrypt shared_ptr (new OpenOuterVolumeFunctor (MountedOuterVolume->MountPoint))); page->SetPageTitle (LangString["HIDVOL_HOST_FILLING_TITLE"]); - + page->SetPageText (StringFormatter ( _("Outer volume has been successfully created and mounted as '{0}'. To this volume you should now copy some sensitive-looking files that you actually do NOT want to hide. The files will be there for anyone forcing you to disclose your password. You will reveal only the password for this outer volume, not for the hidden one. The files that you really care about will be stored in the hidden volume, which will be created later on. When you finish copying, click Next. Do not dismount the volume.\n\nNote: After you click Next, the outer volume will be analyzed to determine the size of uninterrupted area of free space whose end is aligned with the end of the volume. This area will accommodate the hidden volume, so it will limit its maximum possible size. The procedure ensures no data on the outer volume are overwritten by the hidden volume."), wstring (MountedOuterVolume->MountPoint))); - + return page; } @@ -373,12 +373,12 @@ namespace VeraCrypt if (!IsWorkInProgress() && RandomNumberGenerator::IsRunning()) { RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast (&event), sizeof (event))); - + long coord = event.GetX(); RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast (&coord), sizeof (coord))); coord = event.GetY(); RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast (&coord), sizeof (coord))); - + VolumeCreationProgressWizardPage *page = dynamic_cast (GetCurrentPage()); if (page) { @@ -386,7 +386,7 @@ namespace VeraCrypt } } } - + void VolumeCreationWizard::OnProgressTimer () { if (!IsWorkInProgress()) @@ -408,7 +408,7 @@ namespace VeraCrypt } VolumeCreator::ProgressInfo progress = Creator->GetProgressInfo(); - + VolumeCreationProgressWizardPage *page = dynamic_cast (GetCurrentPage()); page->SetProgressValue (progress.SizeDone); @@ -418,9 +418,9 @@ namespace VeraCrypt OnVolumeCreatorFinished (); } } - + void VolumeCreationWizard::OnRandomPoolUpdateTimer () - { + { if (!IsWorkInProgress()) { wxLongLong time = wxGetLocalTimeMillis(); @@ -519,7 +519,7 @@ namespace VeraCrypt if (SelectedFilesystemType == VolumeCreationOptions::FilesystemType::MacOsExt && VolumeSize >= 10 * BYTES_PER_MB) args.push_back ("-J"); - + // Perform a quick NTFS formatting if (SelectedFilesystemType == VolumeCreationOptions::FilesystemType::NTFS) args.push_back ("-f"); @@ -566,7 +566,7 @@ namespace VeraCrypt case Step::VolumeHostType: { SingleChoiceWizardPage *page = dynamic_cast *> (GetCurrentPage()); - + try { SelectedVolumeHostType = page->GetSelection(); @@ -657,7 +657,7 @@ namespace VeraCrypt try { mountPoint = Core->GetDeviceMountPoint (SelectedVolumePath); - + if (!mountPoint.IsEmpty()) { if (mountPoint == "/") @@ -689,7 +689,7 @@ namespace VeraCrypt return Step::EncryptionOptions; } - + case Step::EncryptionOptions: { EncryptionOptionsWizardPage *page = dynamic_cast (GetCurrentPage()); @@ -704,7 +704,7 @@ namespace VeraCrypt else return Step::VolumeSize; } - + case Step::VolumeSize: { VolumeSizeWizardPage *page = dynamic_cast (GetCurrentPage()); @@ -754,7 +754,7 @@ namespace VeraCrypt Gui->ShowWarning (e); return GetCurrentStep(); } - + Kdf = page->GetPkcs5Kdf(); Keyfiles = page->GetKeyfiles(); @@ -768,7 +768,7 @@ namespace VeraCrypt } } } - + if (page->IsPimSelected ()) return Step::VolumePim; else @@ -776,7 +776,7 @@ namespace VeraCrypt // Clear PIM Pim = 0; - // Skip PIM + // Skip PIM if (forward && OuterVolume) { // Use FAT to prevent problems with free space @@ -815,7 +815,7 @@ namespace VeraCrypt if (Pim > 0 && Pim < 485) { Gui->ShowError ("PIM_REQUIRE_LONG_PASSWORD"); - return GetCurrentStep(); + return GetCurrentStep(); } } else if (Pim > 0 && Pim < 485) @@ -826,7 +826,7 @@ namespace VeraCrypt } } } - + if (forward && OuterVolume) { @@ -895,7 +895,7 @@ namespace VeraCrypt } if (forward && CrossPlatformSupport) - Gui->ShowWarning (StringFormatter (_("Please note that the volume will not be formatted with a FAT filesystem and, therefore, you may be required to install additional filesystem drivers on platforms other than {0}, which will enable you to mount the volume."), SystemInfo::GetPlatformName())); + Gui->ShowWarning (StringFormatter (_("Please note that the volume will not be formatted with a FAT filesystem and, therefore, you may be required to install additional filesystem drivers on platforms other than {0}, which will enable you to mount the volume."), SystemInfo::GetPlatformName())); return Step::CreationProgress; } @@ -987,7 +987,7 @@ namespace VeraCrypt } VolumeCreationWizard *Wizard; - }; + }; page->SetProgressRange (options->Size); page->SetProgressState (true); @@ -1055,7 +1055,7 @@ namespace VeraCrypt uint64 reservedSize = outerVolume->GetSize() / 200; if (reservedSize > 10 * BYTES_PER_MB) reservedSize = 10 * BYTES_PER_MB; - + if (MaxHiddenVolumeSize < reservedSize) MaxHiddenVolumeSize = 0; else diff --git a/src/Main/Forms/VolumeCreationWizard.h b/src/Main/Forms/VolumeCreationWizard.h index 1622b4c3..8e6e15d4 100644 --- a/src/Main/Forms/VolumeCreationWizard.h +++ b/src/Main/Forms/VolumeCreationWizard.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/VolumeFormatOptionsWizardPage.cpp b/src/Main/Forms/VolumeFormatOptionsWizardPage.cpp index 8a60a346..d8ec6016 100644 --- a/src/Main/Forms/VolumeFormatOptionsWizardPage.cpp +++ b/src/Main/Forms/VolumeFormatOptionsWizardPage.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/VolumeFormatOptionsWizardPage.h b/src/Main/Forms/VolumeFormatOptionsWizardPage.h index af11205e..371f51f7 100644 --- a/src/Main/Forms/VolumeFormatOptionsWizardPage.h +++ b/src/Main/Forms/VolumeFormatOptionsWizardPage.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/VolumeLocationWizardPage.cpp b/src/Main/Forms/VolumeLocationWizardPage.cpp index 19ff1d69..2765b5ed 100644 --- a/src/Main/Forms/VolumeLocationWizardPage.cpp +++ b/src/Main/Forms/VolumeLocationWizardPage.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -62,7 +62,7 @@ namespace VeraCrypt catch (exception &e) { Gui->ShowError (e); } } } - + void VolumeLocationWizardPage::OnPageChanging (bool forward) { if (forward) diff --git a/src/Main/Forms/VolumeLocationWizardPage.h b/src/Main/Forms/VolumeLocationWizardPage.h index fb1ca671..77b48f21 100644 --- a/src/Main/Forms/VolumeLocationWizardPage.h +++ b/src/Main/Forms/VolumeLocationWizardPage.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/VolumePasswordPanel.cpp b/src/Main/Forms/VolumePasswordPanel.cpp index 27d66bd8..920d4f96 100644 --- a/src/Main/Forms/VolumePasswordPanel.cpp +++ b/src/Main/Forms/VolumePasswordPanel.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -43,7 +43,7 @@ namespace VeraCrypt } CacheCheckBox->Show (enableCache); - + if (!enablePassword && enableKeyfiles) { Layout(); @@ -58,8 +58,8 @@ namespace VeraCrypt PasswordStaticText->Show (enablePassword); PasswordTextCtrl->Show (enablePassword); DisplayPasswordCheckBox->Show (enablePassword); - - + + EnablePimEntry = enablePassword && (!enableConfirmation || (enablePkcs5Prf && !isMountPassword)); PimCheckBox->Show (EnablePimEntry); VolumePimStaticText->Show (false); @@ -71,12 +71,12 @@ namespace VeraCrypt ConfirmPasswordStaticText->Show (enableConfirmation); ConfirmPasswordTextCtrl->Show (enableConfirmation); - + UseKeyfilesCheckBox->Show (enableKeyfiles); KeyfilesButton->Show (enableKeyfiles); Pkcs5PrfStaticText->Show (enablePkcs5Prf); - Pkcs5PrfChoice->Show (enablePkcs5Prf); + Pkcs5PrfChoice->Show (enablePkcs5Prf); TrueCryptModeCheckBox->Show (!disableTruecryptMode); HeaderWipeCountText->Show (enablePkcs5Prf && !isMountPassword); HeaderWipeCount->Show (enablePkcs5Prf && !isMountPassword); @@ -104,20 +104,20 @@ namespace VeraCrypt } if (enablePkcs5Prf) - { + { int index, prfInitialIndex = 0; if (isMountPassword) { // case of password for mounting Pkcs5PrfChoice->Delete (0); - Pkcs5PrfChoice->Append (LangString["AUTODETECTION"]); + Pkcs5PrfChoice->Append (LangString["AUTODETECTION"]); } foreach_ref (const Pkcs5Kdf &kdf, Pkcs5Kdf::GetAvailableAlgorithms(false)) { if (!kdf.IsDeprecated() || isMountPassword) { index = Pkcs5PrfChoice->Append (kdf.GetName()); - if (isMountPassword && options && options->Kdf + if (isMountPassword && options && options->Kdf && (options->Kdf->GetName() == kdf.GetName()) ) { @@ -199,7 +199,7 @@ namespace VeraCrypt int colspan = isPim? 1 : 2; wxTextCtrl *newTextCtrl = new wxTextCtrl (this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, display ? 0 : wxTE_PASSWORD); - newTextCtrl->SetMaxLength (isPim? MAX_PIM_DIGITS : VolumePassword::MaxSize); + newTextCtrl->SetMaxLength (isPim? MAX_PIM_DIGITS : VolumePassword::MaxSize); newTextCtrl->SetValue ((*textCtrl)->GetValue()); newTextCtrl->SetMinSize ((*textCtrl)->GetSize()); @@ -270,7 +270,7 @@ namespace VeraCrypt return shared_ptr (); } } - + int VolumePasswordPanel::GetVolumePim () const { if (VolumePimTextCtrl->IsEnabled () && VolumePimTextCtrl->IsShown ()) @@ -279,7 +279,7 @@ namespace VeraCrypt long pim = 0; if (pimStr.IsEmpty()) return 0; - if (((size_t) wxNOT_FOUND == pimStr.find_first_not_of (wxT("0123456789"))) + if (((size_t) wxNOT_FOUND == pimStr.find_first_not_of (wxT("0123456789"))) && pimStr.ToLong (&pim) && pim <= MAX_PIM_VALUE) return (int) pim; @@ -288,7 +288,7 @@ namespace VeraCrypt } else return 0; - } + } void VolumePasswordPanel::SetVolumePim (int pim) { @@ -306,7 +306,7 @@ namespace VeraCrypt { return TrueCryptModeCheckBox->GetValue (); } - + int VolumePasswordPanel::GetHeaderWipeCount () const { try @@ -393,10 +393,10 @@ namespace VeraCrypt void VolumePasswordPanel::OnDisplayPasswordCheckBoxClick (wxCommandEvent& event) { DisplayPassword (event.IsChecked(), &PasswordTextCtrl, 1); - + if (ConfirmPasswordTextCtrl->IsShown()) DisplayPassword (event.IsChecked(), &ConfirmPasswordTextCtrl, 2); - + if (VolumePimTextCtrl->IsShown()) DisplayPassword (event.IsChecked(), &VolumePimTextCtrl, 3); @@ -467,7 +467,7 @@ namespace VeraCrypt VolumePimHelpStaticText->SetLabel(LangString["IDC_PIM_HELP"]); guiUpdated = true; } - + if (guiUpdated) { Layout(); @@ -485,8 +485,8 @@ namespace VeraCrypt PimCheckBox->Show (false); VolumePimStaticText->Show (true); VolumePimTextCtrl->Show (true); - VolumePimHelpStaticText->Show (true); - + VolumePimHelpStaticText->Show (true); + if (DisplayPasswordCheckBox->IsChecked ()) DisplayPassword (true, &VolumePimTextCtrl, 3); else @@ -494,12 +494,12 @@ namespace VeraCrypt Layout(); Fit(); } - + GetParent()->Layout(); GetParent()->Fit(); } } - + void VolumePasswordPanel::OnTrueCryptModeChecked( wxCommandEvent& event ) { bool bEnablePIM = !GetTrueCryptMode (); diff --git a/src/Main/Forms/VolumePasswordPanel.h b/src/Main/Forms/VolumePasswordPanel.h index a1f935df..e692d447 100644 --- a/src/Main/Forms/VolumePasswordPanel.h +++ b/src/Main/Forms/VolumePasswordPanel.h @@ -3,7 +3,7 @@ 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) + 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 @@ -35,7 +35,7 @@ namespace VeraCrypt int GetHeaderWipeCount () const; void SetCacheCheckBoxValidator (const wxGenericValidator &validator) { CacheCheckBox->SetValidator (validator); } void SetFocusToPasswordTextCtrl () { PasswordTextCtrl->SetSelection (-1, -1); PasswordTextCtrl->SetFocus(); } - void SetFocusToPimTextCtrl () { VolumePimTextCtrl->SetSelection (-1, -1); VolumePimTextCtrl->SetFocus(); } + void SetFocusToPimTextCtrl () { VolumePimTextCtrl->SetSelection (-1, -1); VolumePimTextCtrl->SetFocus(); } void SetVolumePim (int pim); bool PasswordsMatch () const; void EnableUsePim () { PimCheckBox->Enable (true); PimCheckBox->Show (true); } diff --git a/src/Main/Forms/VolumePasswordWizardPage.cpp b/src/Main/Forms/VolumePasswordWizardPage.cpp index c7035b56..f753bb33 100644 --- a/src/Main/Forms/VolumePasswordWizardPage.cpp +++ b/src/Main/Forms/VolumePasswordWizardPage.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/VolumePasswordWizardPage.h b/src/Main/Forms/VolumePasswordWizardPage.h index 43f39f7f..06e89c30 100644 --- a/src/Main/Forms/VolumePasswordWizardPage.h +++ b/src/Main/Forms/VolumePasswordWizardPage.h @@ -3,7 +3,7 @@ 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) + 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 @@ -29,7 +29,7 @@ namespace VeraCrypt void EnableUsePim () { PasswordPanel->EnableUsePim (); } bool IsPimSelected () const { return PasswordPanel->IsUsePimChecked ();} void SetPimSelected (bool selected) const { PasswordPanel->SetUsePimChecked (selected);} - + shared_ptr GetPkcs5Kdf () const { bool bUnsupportedKdf; return PasswordPanel->GetPkcs5Kdf(bUnsupportedKdf); } bool IsValid (); void SetMaxStaticTextWidth (int width) { InfoStaticText->Wrap (width); } diff --git a/src/Main/Forms/VolumePimWizardPage.cpp b/src/Main/Forms/VolumePimWizardPage.cpp index 2d61a719..723ca8cc 100644 --- a/src/Main/Forms/VolumePimWizardPage.cpp +++ b/src/Main/Forms/VolumePimWizardPage.cpp @@ -10,8 +10,8 @@ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + See the License for the specific language governing permissions and + limitations under the License. */ #include "System.h" @@ -29,7 +29,7 @@ namespace VeraCrypt VolumePimWizardPage::~VolumePimWizardPage () { } - + int VolumePimWizardPage::GetVolumePim () const { if (VolumePimTextCtrl->IsEnabled ()) @@ -38,7 +38,7 @@ namespace VeraCrypt long pim = 0; if (pimStr.IsEmpty()) return 0; - if (((size_t) wxNOT_FOUND == pimStr.find_first_not_of (wxT("0123456789"))) + if (((size_t) wxNOT_FOUND == pimStr.find_first_not_of (wxT("0123456789"))) && pimStr.ToLong (&pim)) return (int) pim; else @@ -66,7 +66,7 @@ namespace VeraCrypt { return true; } - + void VolumePimWizardPage::OnPimChanged (wxCommandEvent& event) { OnPimValueChanged (GetVolumePim ()); @@ -83,7 +83,7 @@ namespace VeraCrypt { VolumePimHelpStaticText->SetForegroundColour(*wxBLACK); VolumePimHelpStaticText->SetLabel(LangString["IDC_PIM_HELP"]); - } + } Fit(); Layout(); } @@ -99,15 +99,15 @@ namespace VeraCrypt void VolumePimWizardPage::OnDisplayPimCheckBoxClick( wxCommandEvent& event ) { FreezeScope freeze (this); - + bool display = event.IsChecked (); wxTextCtrl *newTextCtrl = new wxTextCtrl (this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, display ? 0 : wxTE_PASSWORD); - newTextCtrl->SetMaxLength (MAX_PIM_DIGITS); + newTextCtrl->SetMaxLength (MAX_PIM_DIGITS); newTextCtrl->SetValue (VolumePimTextCtrl->GetValue()); newTextCtrl->SetMinSize (VolumePimTextCtrl->GetSize()); - PimSizer->Replace (VolumePimTextCtrl, newTextCtrl); + PimSizer->Replace (VolumePimTextCtrl, newTextCtrl); VolumePimTextCtrl->Show (false); VolumePimTextCtrl->SetValue (wxString (L'X', VolumePimTextCtrl->GetLineLength(0))); GetVolumePim (); diff --git a/src/Main/Forms/VolumePimWizardPage.h b/src/Main/Forms/VolumePimWizardPage.h index 7872346e..542a2e3a 100644 --- a/src/Main/Forms/VolumePimWizardPage.h +++ b/src/Main/Forms/VolumePimWizardPage.h @@ -10,8 +10,8 @@ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. + See the License for the specific language governing permissions and + limitations under the License. */ #ifndef VC_HEADER_Main_Forms_VolumePimWizardPage @@ -33,7 +33,7 @@ namespace VeraCrypt void SetMaxStaticTextWidth (int width) { InfoStaticText->Wrap (width); } void SetPageText (const wxString &text) { InfoStaticText->SetLabel (text); } void OnDisplayPimCheckBoxClick( wxCommandEvent& event ); - + protected: void SetPimValidator (); void OnPimChanged (wxCommandEvent& event); diff --git a/src/Main/Forms/VolumePropertiesDialog.cpp b/src/Main/Forms/VolumePropertiesDialog.cpp index bc802500..5514d300 100644 --- a/src/Main/Forms/VolumePropertiesDialog.cpp +++ b/src/Main/Forms/VolumePropertiesDialog.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -38,7 +38,7 @@ namespace VeraCrypt AppendToList ("SIZE", Gui->SizeToString (volumeInfo.Size)); AppendToList ("TYPE", Gui->VolumeTypeToString (volumeInfo.Type, volumeInfo.TrueCryptMode, volumeInfo.Protection)); AppendToList ("READ_ONLY", LangString [volumeInfo.Protection == VolumeProtection::ReadOnly ? "UISTR_YES" : "UISTR_NO"]); - + wxString protection; if (volumeInfo.Type == VolumeType::Hidden) protection = LangString["NOT_APPLICABLE_OR_NOT_AVAILABLE"]; @@ -84,7 +84,7 @@ namespace VeraCrypt #ifdef TC_LINUX } #endif - + Layout(); Fit(); Center(); diff --git a/src/Main/Forms/VolumePropertiesDialog.h b/src/Main/Forms/VolumePropertiesDialog.h index c9273bdf..171cf6e7 100644 --- a/src/Main/Forms/VolumePropertiesDialog.h +++ b/src/Main/Forms/VolumePropertiesDialog.h @@ -3,7 +3,7 @@ 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) + 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 @@ -22,7 +22,7 @@ namespace VeraCrypt { public: VolumePropertiesDialog (wxWindow* parent, const VolumeInfo &volumeInfo); - + void AppendToList (const string &name, const wxString &value); }; } diff --git a/src/Main/Forms/VolumeSizeWizardPage.cpp b/src/Main/Forms/VolumeSizeWizardPage.cpp index cdfb788f..c4f855a2 100644 --- a/src/Main/Forms/VolumeSizeWizardPage.cpp +++ b/src/Main/Forms/VolumeSizeWizardPage.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -74,7 +74,7 @@ namespace VeraCrypt return 0; prefixMult = reinterpret_cast (VolumeSizePrefixChoice->GetClientData (selection)); - + uint64 val = StringConverter::ToUInt64 (wstring (VolumeSizeTextCtrl->GetValue())); if (val <= 0x7fffFFFFffffFFFFull / prefixMult) { @@ -119,7 +119,7 @@ namespace VeraCrypt VolumeSizeTextCtrl->SetValue (L""); return; } - + if (size % (1024 * 1024 * 1024) == 0) { size /= 1024 * 1024 * 1024; diff --git a/src/Main/Forms/VolumeSizeWizardPage.h b/src/Main/Forms/VolumeSizeWizardPage.h index c64b4d39..9779da42 100644 --- a/src/Main/Forms/VolumeSizeWizardPage.h +++ b/src/Main/Forms/VolumeSizeWizardPage.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/WaitDialog.cpp b/src/Main/Forms/WaitDialog.cpp index f53f5ad0..4780f7ef 100644 --- a/src/Main/Forms/WaitDialog.cpp +++ b/src/Main/Forms/WaitDialog.cpp @@ -20,7 +20,7 @@ namespace VeraCrypt DEFINE_EVENT_TYPE(wxEVT_COMMAND_WAITDIALOG_SHOW_MSG) wxThread::ExitCode WaitThread::Entry() - { + { m_pRoutine->Execute(); wxQueueEvent (m_pHandler, new wxCommandEvent( wxEVT_COMMAND_WAITDIALOGTHREAD_COMPLETED,0)); return (wxThread::ExitCode)0; // success @@ -59,7 +59,7 @@ namespace VeraCrypt VC_CONVERT_EXCEPTION (UserInterfaceException); VC_CONVERT_EXCEPTION (MissingArgument); VC_CONVERT_EXCEPTION (NoItemSelected); - VC_CONVERT_EXCEPTION (StringFormatterException); + VC_CONVERT_EXCEPTION (StringFormatterException); VC_CONVERT_EXCEPTION (ExecutedProcessFailed); VC_CONVERT_EXCEPTION (AlreadyInitialized); VC_CONVERT_EXCEPTION (AssertionFailed); @@ -77,7 +77,7 @@ namespace VeraCrypt VC_CONVERT_EXCEPTION (UnknownException); VC_CONVERT_EXCEPTION (UserAbort) VC_CONVERT_EXCEPTION (CipherInitError); - VC_CONVERT_EXCEPTION (WeakKeyDetected); + VC_CONVERT_EXCEPTION (WeakKeyDetected); VC_CONVERT_EXCEPTION (HigherVersionRequired); VC_CONVERT_EXCEPTION (KeyfilePathEmpty); VC_CONVERT_EXCEPTION (MissingVolumeData); @@ -92,7 +92,7 @@ namespace VeraCrypt VC_CONVERT_EXCEPTION (SecurityTokenLibraryNotInitialized); VC_CONVERT_EXCEPTION (SecurityTokenKeyfileAlreadyExists); VC_CONVERT_EXCEPTION (SecurityTokenKeyfileNotFound); - VC_CONVERT_EXCEPTION (UnsupportedAlgoInTrueCryptMode); + VC_CONVERT_EXCEPTION (UnsupportedAlgoInTrueCryptMode); VC_CONVERT_EXCEPTION (UnsupportedTrueCryptFormat); VC_CONVERT_EXCEPTION (SystemException); VC_CONVERT_EXCEPTION (CipherException); diff --git a/src/Main/Forms/WaitDialog.h b/src/Main/Forms/WaitDialog.h index a33e7e5a..e9c9fa3a 100644 --- a/src/Main/Forms/WaitDialog.h +++ b/src/Main/Forms/WaitDialog.h @@ -21,7 +21,7 @@ namespace VeraCrypt DECLARE_LOCAL_EVENT_TYPE(wxEVT_COMMAND_WAITDIALOG_ADMIN_PASSWORD, -1); DECLARE_LOCAL_EVENT_TYPE(wxEVT_COMMAND_WAITDIALOG_PIN, -1); DECLARE_LOCAL_EVENT_TYPE(wxEVT_COMMAND_WAITDIALOG_SHOW_MSG, -1); - + class WaitDialog; @@ -31,12 +31,12 @@ namespace VeraCrypt public: WaitThread(WaitDialog *handler, WaitThreadRoutine* pRoutine) : wxThread(wxTHREAD_DETACHED), m_pRoutine(pRoutine) { - m_pHandler = handler; + m_pHandler = handler; } ~WaitThread() - { + { } - + protected: virtual ExitCode Entry(); WaitDialog *m_pHandler; @@ -46,7 +46,7 @@ namespace VeraCrypt class WaitDialog : public WaitDialogBase, public WaitThreadUI { public: - WaitDialog (wxWindow *parent, const wxString& label, WaitThreadRoutine* pRoutine) + WaitDialog (wxWindow *parent, const wxString& label, WaitThreadRoutine* pRoutine) : WaitDialogBase(parent), WaitThreadUI(pRoutine), m_timer (this) { WaitStaticText->SetLabel (label); @@ -58,11 +58,11 @@ namespace VeraCrypt Connect( wxID_ANY, wxEVT_COMMAND_WAITDIALOG_ADMIN_PASSWORD, wxCommandEventHandler( WaitDialog::OnAdminPasswordRequest ) ); Connect( wxID_ANY, wxEVT_COMMAND_WAITDIALOG_PIN, wxCommandEventHandler( WaitDialog::OnPinRequest ) ); Connect( wxID_ANY, wxEVT_COMMAND_WAITDIALOG_SHOW_MSG, wxCommandEventHandler( WaitDialog::OnShowMsg ) ); - + Connect( wxEVT_TIMER, wxTimerEventHandler( WaitDialog::OnProgressTimer ), NULL, this ); m_thread = new WaitThread(this, pRoutine); } - + ~WaitDialog() { Disconnect( wxEVT_TIMER, wxTimerEventHandler( WaitDialog::OnProgressTimer )); @@ -73,7 +73,7 @@ namespace VeraCrypt } virtual void OnWaitDialogInit( wxInitDialogEvent& event ) - { + { m_thread->Run(); m_timer.Start(100); } @@ -114,7 +114,7 @@ namespace VeraCrypt wxQueueEvent (this, pEvent); m_queue.Receive (sResult); sResult.ToLong(&lResult); - } + } return (int) lResult; } @@ -143,7 +143,7 @@ namespace VeraCrypt else pin = wxT(""); } - + // virtual void OnWaitDialogClose( wxCloseEvent& event ) { } void OnThreadCompletion(wxCommandEvent &) { @@ -187,10 +187,10 @@ namespace VeraCrypt } int iResult = wxMessageBox (pParam->m_message, pParam->m_caption, pParam->m_style, this); - delete pParam; + delete pParam; m_queue.Post(wxString::Format(wxT("%d"), iResult)); } - + void OnProgressTimer(wxTimerEvent& event) { WaitProgessBar->Pulse(); diff --git a/src/Main/Forms/WizardFrame.cpp b/src/Main/Forms/WizardFrame.cpp index af38cdd6..b5fe3be7 100644 --- a/src/Main/Forms/WizardFrame.cpp +++ b/src/Main/Forms/WizardFrame.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -61,7 +61,7 @@ namespace VeraCrypt Gui->SetActiveFrame (this); event.Skip(); } - + void WizardFrame::OnClose (wxCloseEvent& event) { if (WorkInProgress) @@ -97,12 +97,12 @@ namespace VeraCrypt SetStep (prevStep, false); } } - + void WizardFrame::SetCancelButtonText (const wxString &text) { CancelButton->SetLabel (text.empty() ? wxString (_("Cancel")) : text); } - + void WizardFrame::SetImage (const wxBitmap &bitmap) { WizardBitmap->SetBitmap (bitmap); @@ -143,7 +143,7 @@ namespace VeraCrypt CurrentPage = GetPage (newStep); CurrentPage->PageUpdatedEvent.Connect (EventConnector (this, &WizardFrame::OnPageUpdated)); - + CurrentPage->Connect (wxEVT_MOTION, wxMouseEventHandler (WizardFrame::OnMouseMotion), nullptr, this); foreach (wxWindow *c, CurrentPage->GetChildren()) c->Connect (wxEVT_MOTION, wxMouseEventHandler (WizardFrame::OnMouseMotion), nullptr, this); diff --git a/src/Main/Forms/WizardFrame.h b/src/Main/Forms/WizardFrame.h index 90111120..ac4f1c4c 100644 --- a/src/Main/Forms/WizardFrame.h +++ b/src/Main/Forms/WizardFrame.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Forms/WizardPage.h b/src/Main/Forms/WizardPage.h index f8c7d827..d47a4e90 100644 --- a/src/Main/Forms/WizardPage.h +++ b/src/Main/Forms/WizardPage.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/GraphicUserInterface.cpp b/src/Main/GraphicUserInterface.cpp index 3526dcad..cd5c6fe9 100644 --- a/src/Main/GraphicUserInterface.cpp +++ b/src/Main/GraphicUserInterface.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -73,7 +73,7 @@ namespace VeraCrypt signal (SIGTERM, SIG_DFL); #endif } - + void GraphicUserInterface::AppendToListCtrl (wxListCtrl *listCtrl, const vector &itemFields, int imageIndex, void *itemDataPtr) const { InsertToListCtrl (listCtrl, listCtrl->GetItemCount(), itemFields, imageIndex, itemDataPtr); @@ -83,7 +83,7 @@ namespace VeraCrypt { wxMenuItem *item = new wxMenuItem (&menu, itemId, label); menu.Append (item); - + if (handler) handler->Connect (item->GetId(), wxEVT_COMMAND_MENU_SELECTED, handlerFunction); @@ -110,7 +110,7 @@ namespace VeraCrypt if (Core->GetMountedVolumes().size() < mountedVolumeCount) OnVolumesAutoDismounted(); } - + void GraphicUserInterface::BackupVolumeHeaders (shared_ptr volumePath) const { wxWindow *parent = GetActiveWindow(); @@ -196,7 +196,7 @@ namespace VeraCrypt options->UseBackupHeaders ); - ExecuteWaitThreadRoutine (parent, &routine); + ExecuteWaitThreadRoutine (parent, &routine); volume = routine.m_pVolume; } catch (PasswordException &e) @@ -332,12 +332,12 @@ namespace VeraCrypt wxHyperlinkCtrl *GraphicUserInterface::CreateHyperlink (wxWindow *parent, const wxString &linkUrl, const wxString &linkText) const { wxHyperlinkCtrl *hyperlink = new wxHyperlinkCtrl (parent, wxID_ANY, linkText, linkUrl, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE); - + wxColour color = wxSystemSettings::GetColour (wxSYS_COLOUR_WINDOWTEXT); hyperlink->SetHoverColour (color); hyperlink->SetNormalColour (color); hyperlink->SetVisitedColour (color); - + return hyperlink; } @@ -345,7 +345,7 @@ namespace VeraCrypt { ShowMessage (message, wxOK | wxICON_ERROR); } - + void GraphicUserInterface::DoShowInfo (const wxString &message) const { ShowMessage (message, wxOK | wxICON_INFORMATION); @@ -358,13 +358,13 @@ namespace VeraCrypt void GraphicUserInterface::DoShowWarning (const wxString &message) const { - ShowMessage (message, wxOK + ShowMessage (message, wxOK #ifndef TC_MACOSX | wxICON_EXCLAMATION #endif ); } - + void GraphicUserInterface::EndInteractiveBusyState (wxWindow *window) const { static auto_ptr arrowCursor; @@ -438,7 +438,7 @@ namespace VeraCrypt return shared_ptr (new AdminPasswordRequestHandler); } - + int GraphicUserInterface::GetCharHeight (wxWindow *window) const { int width; @@ -471,9 +471,9 @@ namespace VeraCrypt #elif defined(TC_MACOSX) 13 #else - 10 + 10 #endif - * GetCharHeight (window) / 13, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, + * GetCharHeight (window) / 13, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, #ifdef __WXGTK__ wxFONTWEIGHT_BOLD, false); #elif defined(TC_MACOSX) @@ -486,7 +486,7 @@ namespace VeraCrypt list GraphicUserInterface::GetListCtrlSelectedItems (wxListCtrl *listCtrl) const { list selectedItems; - + long item = -1; while ((item = listCtrl->GetNextItem (item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED)) != -1) selectedItems.push_back (item); @@ -500,7 +500,7 @@ namespace VeraCrypt item.SetId (itemIndex); item.SetColumn (columnIndex); item.SetText (L""); - + if (!listCtrl->GetItem (item)) throw ParameterIncorrect (SRC_POS); @@ -605,7 +605,7 @@ namespace VeraCrypt listCtrl->SetItem (item); } } - + bool GraphicUserInterface::IsTheOnlyTopLevelWindow (const wxWindow *window) const { foreach (wxWindow *w, wxTopLevelWindows) @@ -654,7 +654,7 @@ namespace VeraCrypt item.SetId (itemIndex); item.SetData ((void *) nullptr); item.SetImage (-1); - + if (!listCtrl->GetItem (item)) throw ParameterIncorrect (SRC_POS); @@ -667,7 +667,7 @@ namespace VeraCrypt } listCtrl->DeleteItem (itemIndex); - + if (newItemIndex > listCtrl->GetItemCount() - 1) AppendToListCtrl (listCtrl, itemFields, item.GetImage(), (void *) item.GetData()); else @@ -688,7 +688,7 @@ namespace VeraCrypt return VolumeInfoList(); VolumeInfoList mountedVolumes = UserInterface::MountAllDeviceHostedVolumes (options); - + if (!mountedVolumes.empty()) return mountedVolumes; } @@ -857,7 +857,7 @@ namespace VeraCrypt wxLogLevel logLevel = wxLog::GetLogLevel(); wxLog::SetLogLevel (wxLOG_Error); - + const wxString instanceCheckerName = wxString (L".") + Application::GetName() + L"-lock-" + wxGetUserId(); SingleInstanceChecker.reset (new wxSingleInstanceChecker (instanceCheckerName)); @@ -978,7 +978,7 @@ namespace VeraCrypt return true; } - + void GraphicUserInterface::OnLogOff () { VolumeInfoList mountedVolumes = Core->GetMountedVolumes(); @@ -994,10 +994,10 @@ namespace VeraCrypt try { timeOver = (wxGetLocalTimeMillis() - startTime >= 4000); - + DismountVolumes (mountedVolumes, !timeOver ? false : GetPreferences().ForceAutoDismount, timeOver); OnVolumesAutoDismounted(); - + break; } catch (UserAbort&) @@ -1075,112 +1075,112 @@ namespace VeraCrypt wxString GraphicUserInterface::GetHomepageLinkURL (const wxString &linkId, bool secure, const wxString &extraVars) const { wxString url = wxString (StringConverter::ToWide (secure ? TC_APPLINK_SECURE : TC_APPLINK)); - - if (linkId == L"donate") + + if (linkId == L"donate") { url = L"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5BCXVMTTNJDCY"; } - else if (linkId == L"main") + else if (linkId == L"main") { url = wxString (StringConverter::ToWide (TC_HOMEPAGE)); } - else if (linkId == L"localizations") + else if (linkId == L"localizations") { url = L"https://veracrypt.codeplex.com/wikipage?title=Language%20Packs"; } - else if (linkId == L"beginnerstutorial" || linkId == L"tutorial") + else if (linkId == L"beginnerstutorial" || linkId == L"tutorial") { url = L"https://veracrypt.codeplex.com/wikipage?title=Beginner%27s%20Tutorial"; } - else if (linkId == L"releasenotes" || linkId == L"history") + else if (linkId == L"releasenotes" || linkId == L"history") { url = L"https://veracrypt.codeplex.com/wikipage?title=Release%20Notes"; } - else if (linkId == L"hwacceleration") + else if (linkId == L"hwacceleration") { url = L"https://veracrypt.codeplex.com/wikipage?title=Hardware%20Acceleration"; } - else if (linkId == L"parallelization") + else if (linkId == L"parallelization") { url = L"https://veracrypt.codeplex.com/wikipage?title=Parallelization"; } - else if (linkId == L"help") + else if (linkId == L"help") { url = L"https://veracrypt.codeplex.com/documentation"; } - else if (linkId == L"keyfiles") + else if (linkId == L"keyfiles") { url = L"https://veracrypt.codeplex.com/wikipage?title=Keyfiles"; } - else if (linkId == L"introcontainer") + else if (linkId == L"introcontainer") { url = L"https://veracrypt.codeplex.com/wikipage?title=Creating%20New%20Volumes"; } - else if (linkId == L"introsysenc") + else if (linkId == L"introsysenc") { url = L"https://veracrypt.codeplex.com/wikipage?title=System%20Encryption"; } - else if (linkId == L"hiddensysenc") + else if (linkId == L"hiddensysenc") { url = L"https://veracrypt.codeplex.com/wikipage?title=VeraCrypt%20Hidden%20Operating%20System"; } - else if (linkId == L"sysencprogressinfo") + else if (linkId == L"sysencprogressinfo") { url = L"https://veracrypt.codeplex.com/wikipage?title=System%20Encryption"; } - else if (linkId == L"hiddenvolume") + else if (linkId == L"hiddenvolume") { url = L"https://veracrypt.codeplex.com/wikipage?title=Hidden%20Volume"; } - else if (linkId == L"aes") + else if (linkId == L"aes") { url = L"https://veracrypt.codeplex.com/wikipage?title=AES"; } - else if (linkId == L"serpent") + else if (linkId == L"serpent") { url = L"https://veracrypt.codeplex.com/wikipage?title=Serpent"; } - else if (linkId == L"twofish") + else if (linkId == L"twofish") { url = L"https://veracrypt.codeplex.com/wikipage?title=Twofish"; } - else if (linkId == L"cascades") + else if (linkId == L"cascades") { url = L"https://veracrypt.codeplex.com/wikipage?title=Cascades"; } - else if (linkId == L"hashalgorithms") + else if (linkId == L"hashalgorithms") { url = L"https://veracrypt.codeplex.com/wikipage?title=Hash%20Algorithms"; } - else if (linkId == L"isoburning") + else if (linkId == L"isoburning") { url = L"https://cdburnerxp.se/en/home"; } - else if (linkId == L"sysfavorites") + else if (linkId == L"sysfavorites") { url = L"https://veracrypt.codeplex.com/wikipage?title=System%20Favorite%20Volumes"; } - else if (linkId == L"favorites") + else if (linkId == L"favorites") { url = L"https://veracrypt.codeplex.com/wikipage?title=Favorite%20Volumes"; } - else if (linkId == L"hiddenvolprotection") + else if (linkId == L"hiddenvolprotection") { url = L"https://veracrypt.codeplex.com/wikipage?title=Protection%20of%20Hidden%20Volumes"; } - else if (linkId == L"faq") + else if (linkId == L"faq") { url = L"https://veracrypt.codeplex.com/wikipage?title=FAQ"; } - else if (linkId == L"downloads") + else if (linkId == L"downloads") { url = L"https://veracrypt.codeplex.com/wikipage?title=Downloads"; } - else if (linkId == L"news") + else if (linkId == L"news") { url = L"https://veracrypt.codeplex.com/wikipage?title=News"; } - else if (linkId == L"contact") + else if (linkId == L"contact") { url = L"https://veracrypt.codeplex.com/wikipage?title=Contact"; } @@ -1191,7 +1191,7 @@ namespace VeraCrypt void GraphicUserInterface::OpenHomepageLink (wxWindow *parent, const wxString &linkId, const wxString &extraVars) { wxString url; - + BeginInteractiveBusyState (parent); wxLaunchDefaultBrowser (GetHomepageLinkURL (linkId, false, extraVars), wxBROWSER_NEW_WINDOW); Thread::Sleep (200); @@ -1301,7 +1301,7 @@ namespace VeraCrypt default: return; } - + /* force the display of the random enriching interface */ RandomNumberGenerator::SetEnrichedByUserStatus (false); @@ -1341,7 +1341,7 @@ namespace VeraCrypt true ); - ExecuteWaitThreadRoutine (parent, &routine); + ExecuteWaitThreadRoutine (parent, &routine); volume = routine.m_pVolume; } catch (PasswordException &e) @@ -1449,7 +1449,7 @@ namespace VeraCrypt EncryptionAlgorithmList encryptionAlgorithms = layout->GetSupportedEncryptionAlgorithms(); EncryptionModeList encryptionModes = layout->GetSupportedEncryptionModes(); - DecryptThreadRoutine decryptRoutine(layout->GetHeader(), headerBuffer, *passwordKey, options.Pim, options.Kdf, options.TrueCryptMode, keyDerivationFunctions, encryptionAlgorithms, encryptionModes); + DecryptThreadRoutine decryptRoutine(layout->GetHeader(), headerBuffer, *passwordKey, options.Pim, options.Kdf, options.TrueCryptMode, keyDerivationFunctions, encryptionAlgorithms, encryptionModes); ExecuteWaitThreadRoutine (parent, &decryptRoutine); @@ -1471,7 +1471,7 @@ namespace VeraCrypt File volumeFile; volumeFile.Open (*volumePath, File::OpenReadWrite, File::ShareNone, File::PreserveTimestamps); - + RandomNumberGenerator::Start(); UserEnrichRandomPool (nullptr); @@ -1497,7 +1497,7 @@ namespace VeraCrypt ReEncryptHeaderThreadRoutine backupRoutine(newHeaderBuffer, decryptedLayout->GetHeader(), options.Password, options.Pim, options.Keyfiles); ExecuteWaitThreadRoutine (parent, &backupRoutine); - + // Write backup volume header headerOffset = decryptedLayout->GetBackupHeaderOffset(); if (headerOffset >= 0) @@ -1557,7 +1557,7 @@ namespace VeraCrypt if (!fileExtensions.empty()) #endif { - wildcards = LangString["ALL_FILES"] + + wildcards = LangString["ALL_FILES"] + #ifdef TC_WINDOWS L" (*.*)|*.*"; #else @@ -1595,7 +1595,7 @@ namespace VeraCrypt return files; } - + FilePath GraphicUserInterface::SelectVolumeFile (wxWindow *parent, bool saveMode, const DirectoryPath &directory) const { list < pair > extensions; @@ -1639,14 +1639,14 @@ namespace VeraCrypt listWidth = minListWidth; listWidth -= GetScrollbarWidth (listCtrl, !hasVerticalScrollbar); - + int col = 0; int totalColWidth = 0; foreach (int colWidth, columnWidthPermilles) { int width = listWidth * colWidth / 1000; totalColWidth += width; - + if (col == listCtrl->GetColumnCount() - 1) width += listWidth - totalColWidth; @@ -1712,7 +1712,7 @@ namespace VeraCrypt { ShowMessage (message, wxOK | wxICON_INFORMATION, true); } - + int GraphicUserInterface::ShowMessage (const wxString &message, long style, bool topMost) const { wxString caption = Application::GetName(); @@ -1786,7 +1786,7 @@ namespace VeraCrypt void GraphicUserInterface::ShowWarningTopMost (const wxString &message) const { - ShowMessage (message, wxOK + ShowMessage (message, wxOK #ifndef TC_MACOSX | wxICON_EXCLAMATION #endif @@ -1810,7 +1810,7 @@ namespace VeraCrypt foreach (wxString field, itemFields) { item.SetColumn (col++); - + if (!listCtrl->GetItem (item)) throw ParameterIncorrect (SRC_POS); @@ -1829,7 +1829,7 @@ namespace VeraCrypt void GraphicUserInterface::UserEnrichRandomPool (wxWindow *parent, shared_ptr hash) const { RandomNumberGenerator::Start(); - + if (hash) RandomNumberGenerator::SetHash (hash); diff --git a/src/Main/GraphicUserInterface.h b/src/Main/GraphicUserInterface.h index c2a9fa32..a7056f08 100644 --- a/src/Main/GraphicUserInterface.h +++ b/src/Main/GraphicUserInterface.h @@ -3,7 +3,7 @@ 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) + 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 @@ -89,7 +89,7 @@ namespace VeraCrypt virtual void ShowInfoTopMost (char *langStringId) const { ShowInfoTopMost (LangString[langStringId]); } virtual void ShowInfoTopMost (const wxString &message) const; virtual void ShowWarningTopMost (char *langStringId) const { ShowWarningTopMost (LangString[langStringId]); } - virtual void ShowWarningTopMost (const wxString &message) const; + virtual void ShowWarningTopMost (const wxString &message) const; virtual bool UpdateListCtrlItem (wxListCtrl *listCtrl, long itemIndex, const vector &itemFields) const; virtual void UserEnrichRandomPool (wxWindow *parent, shared_ptr hash = shared_ptr ()) const; virtual void Yield () const; diff --git a/src/Main/Hotkey.cpp b/src/Main/Hotkey.cpp index 31f0243b..132b7cb6 100644 --- a/src/Main/Hotkey.cpp +++ b/src/Main/Hotkey.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -50,13 +50,13 @@ namespace VeraCrypt if (VirtualKeyModifiers & wxMOD_SHIFT) str += LangString["VK_SHIFT"] + L"+"; - + if (VirtualKeyModifiers & wxMOD_CONTROL) str += LangString["VK_CONTROL"] + L"+"; - + if (VirtualKeyModifiers & wxMOD_ALT) str += LangString["VK_ALT"] + L"+"; - + if (VirtualKeyModifiers & wxMOD_WIN ) str += LangString["VK_WIN"] + L"+"; @@ -67,11 +67,11 @@ namespace VeraCrypt { #ifdef TC_WINDOWS // ASCII characters - if (virtualKeyCode >= 0x30 && virtualKeyCode <= 0x5a) + if (virtualKeyCode >= 0x30 && virtualKeyCode <= 0x5a) return StringFormatter (L"{0}", char (virtualKeyCode)); // OEM-specific - if (virtualKeyCode >= 0xE9 && virtualKeyCode <= 0xF5) + if (virtualKeyCode >= 0xE9 && virtualKeyCode <= 0xF5) return StringFormatter (L"OEM-{0}", virtualKeyCode); // F1-F24 @@ -147,7 +147,7 @@ namespace VeraCrypt { hotkey->VirtualKeyCode = StringConverter::ToUInt32 (wstring (node.Attributes[L"vkeycode"])); hotkey->VirtualKeyModifiers = 0; - + if (node.Attributes[L"modshift"] == L"1") hotkey->VirtualKeyModifiers |= wxMOD_SHIFT; diff --git a/src/Main/Hotkey.h b/src/Main/Hotkey.h index c23feaaf..86b40f7f 100644 --- a/src/Main/Hotkey.h +++ b/src/Main/Hotkey.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/LanguageStrings.cpp b/src/Main/LanguageStrings.cpp index aa5a9e48..8892946a 100644 --- a/src/Main/LanguageStrings.cpp +++ b/src/Main/LanguageStrings.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/LanguageStrings.h b/src/Main/LanguageStrings.h index d9cc9579..a55fc08d 100644 --- a/src/Main/LanguageStrings.h +++ b/src/Main/LanguageStrings.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Main.h b/src/Main/Main.h index e9d7e838..18d5eda8 100644 --- a/src/Main/Main.h +++ b/src/Main/Main.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Main.make b/src/Main/Main.make index 99700ce5..f4f254e1 100644 --- a/src/Main/Main.make +++ b/src/Main/Main.make @@ -3,7 +3,7 @@ # 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) +# 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 @@ -152,7 +152,7 @@ ifeq "$(PLATFORM)" "MacOSX" mkdir -p $(APPNAME).app/Contents/MacOS $(APPNAME).app/Contents/Resources -rm -f $(APPNAME).app/Contents/MacOS/$(APPNAME) -rm -f $(APPNAME).app/Contents/MacOS/$(APPNAME)_console - + ifeq "$(TC_BUILD_CONFIG)" "Release" ifdef TC_NO_GUI cp $(PWD)/Main/$(APPNAME) $(APPNAME).app/Contents/MacOS/$(APPNAME)_console @@ -171,7 +171,7 @@ endif cp $(PWD)/Resources/Icons/VeraCrypt.icns $(APPNAME).app/Contents/Resources cp "$(PWD)/Release/Setup Files/VeraCrypt User Guide.pdf" $(APPNAME).app/Contents/Resources - + echo -n APPLTRUE >$(APPNAME).app/Contents/PkgInfo sed -e 's/_VERSION_/$(patsubst %a,%.1,$(patsubst %b,%.2,$(TC_VERSION)))/' ../Build/Resources/MacOSX/Info.plist.xml >$(APPNAME).app/Contents/Info.plist codesign -s "Developer ID Application: Mounir IDRASSI" --timestamp $(APPNAME).app @@ -192,7 +192,7 @@ endif -ifeq "$(PLATFORM)" "Linux" +ifeq "$(PLATFORM)" "Linux" ifeq "$(TC_BUILD_CONFIG)" "Release" mkdir -p $(PWD)/Setup/Linux/usr/bin mkdir -p $(PWD)/Setup/Linux/usr/share/$(APPNAME)/doc @@ -211,7 +211,7 @@ endif tar cfz $(PWD)/Setup/Linux/$(PACKAGE_NAME) --directory $(PWD)/Setup/Linux usr - + @rm -fr $(INTERNAL_INSTALLER_NAME) @echo "#!/bin/sh" > $(INTERNAL_INSTALLER_NAME) @echo "VERSION=$(TC_VERSION)" >> $(INTERNAL_INSTALLER_NAME) @@ -219,7 +219,7 @@ endif @echo "PACKAGE_NAME=$(PACKAGE_NAME)" >> $(INTERNAL_INSTALLER_NAME) @echo "PACKAGE_START=1107" >> $(INTERNAL_INSTALLER_NAME) @echo "INSTALLER_TYPE=$(INSTALLER_TYPE)" >> $(INTERNAL_INSTALLER_NAME) - + @cat $(PWD)/Setup/Linux/veracrypt_install_template.sh >> $(INTERNAL_INSTALLER_NAME) @cat $(PWD)/Setup/Linux/$(PACKAGE_NAME) >> $(INTERNAL_INSTALLER_NAME) chmod +x $(INTERNAL_INSTALLER_NAME) diff --git a/src/Main/Resources.cpp b/src/Main/Resources.cpp index 915134d4..8b0dcdfd 100644 --- a/src/Main/Resources.cpp +++ b/src/Main/Resources.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -24,7 +24,7 @@ namespace VeraCrypt #ifdef TC_WINDOWS static ConstBufferPtr GetWindowsResource (const wchar_t *resourceType, const wchar_t *resourceName) { - HGLOBAL hResL; + HGLOBAL hResL; HRSRC hRes; hRes = FindResource (NULL, resourceName, resourceType); diff --git a/src/Main/Resources.h b/src/Main/Resources.h index 13077f8f..45b5c324 100644 --- a/src/Main/Resources.h +++ b/src/Main/Resources.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/StringFormatter.cpp b/src/Main/StringFormatter.cpp index 1b184751..39f7da5e 100644 --- a/src/Main/StringFormatter.cpp +++ b/src/Main/StringFormatter.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/StringFormatter.h b/src/Main/StringFormatter.h index 29bbac36..0d5fdc58 100644 --- a/src/Main/StringFormatter.h +++ b/src/Main/StringFormatter.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/System.cpp b/src/Main/System.cpp index 44314c85..4cfba366 100644 --- a/src/Main/System.cpp +++ b/src/Main/System.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/System.h b/src/Main/System.h index 21510fbc..5c628925 100644 --- a/src/Main/System.h +++ b/src/Main/System.h @@ -3,7 +3,7 @@ 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) + 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 @@ -26,8 +26,8 @@ #ifndef TC_LOCAL_WIN32_WINNT_OVERRIDE # ifndef _WIN32_WINNT # define _WIN32_WINNT 0x0501 -# endif -#endif +# endif +#endif #ifndef _WIN32_WINDOWS #define _WIN32_WINDOWS 0x0410 diff --git a/src/Main/SystemPrecompiled.h b/src/Main/SystemPrecompiled.h index 6d537e13..168642af 100644 --- a/src/Main/SystemPrecompiled.h +++ b/src/Main/SystemPrecompiled.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/TextUserInterface.cpp b/src/Main/TextUserInterface.cpp index bddfc0b2..902f4616 100644 --- a/src/Main/TextUserInterface.cpp +++ b/src/Main/TextUserInterface.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -165,7 +165,7 @@ namespace VeraCrypt return password; } - + int TextUserInterface::AskPim (const wxString &message) const { int pim = -1; @@ -196,10 +196,10 @@ namespace VeraCrypt } } } - + return pim; } - + ssize_t TextUserInterface::AskSelection (ssize_t optionCount, ssize_t defaultOption) const { while (true) @@ -229,7 +229,7 @@ namespace VeraCrypt ShowString (message); return wstring (ReadInputStreamLine()); } - + bool TextUserInterface::AskYesNo (const wxString &message, bool defaultYes, bool warning) const { while (true) @@ -264,7 +264,7 @@ namespace VeraCrypt #endif ShowInfo ("EXTERNAL_VOL_HEADER_BAK_FIRST_INFO"); - + shared_ptr kdf; if (CmdLine->ArgHash) { @@ -426,7 +426,7 @@ namespace VeraCrypt { password = AskPassword (); } - + // current PIM if (!truecryptMode && !Preferences.NonInteractive && (pim < 0)) { @@ -449,7 +449,7 @@ namespace VeraCrypt if (!Preferences.NonInteractive) keyfiles = AskKeyfiles (); } - } + } if (!volume.get()) volume = Core->OpenVolume (volumePath, Preferences.DefaultMountOptions.PreserveTimestamps, password, pim, kdf, truecryptMode, keyfiles); @@ -469,7 +469,7 @@ namespace VeraCrypt // New password if (!newPassword.get() && !Preferences.NonInteractive) newPassword = AskPassword (_("Enter new password"), true); - + // New PIM if ((newPim < 0) && !Preferences.NonInteractive) newPim = AskPim (_("Enter new PIM")); @@ -769,7 +769,7 @@ namespace VeraCrypt ShowString (L"\n"); options->Password = AskPassword (_("Enter password"), true); } - + // PIM if ((options->Pim < 0) && !Preferences.NonInteractive) { @@ -784,7 +784,7 @@ namespace VeraCrypt options->Keyfiles = AskKeyfiles (_("Enter keyfile path")); } - if ((!options->Keyfiles || options->Keyfiles->empty()) + if ((!options->Keyfiles || options->Keyfiles->empty()) && (!options->Password || options->Password->IsEmpty())) { throw_err (_("Password cannot be empty when no keyfile is specified")); @@ -909,7 +909,7 @@ namespace VeraCrypt ShowInfo (options->Type == VolumeType::Hidden ? "HIDVOL_FORMAT_FINISHED_HELP" : "FORMAT_FINISHED_INFO"); } - + void TextUserInterface::DeleteSecurityTokenKeyfiles () const { shared_ptr keyfiles = AskKeyfiles(); @@ -956,7 +956,7 @@ namespace VeraCrypt BufferPtr keyfileDataBuf (&keyfileData.front(), keyfileData.size()); finally_do_arg (BufferPtr, keyfileDataBuf, { finally_arg.Erase(); }); - + FilePath exportFilePath = AskFilePath(); if (exportFilePath.IsEmpty()) @@ -978,7 +978,7 @@ namespace VeraCrypt TextUserInterface::SetTerminalEcho (false); finally_do ({ TextUserInterface::SetTerminalEcho (true); }); - + wstring wPassword (UI->ReadInputStreamLine()); finally_do_arg (wstring *, &wPassword, { StringConverter::Erase (*finally_arg); }); @@ -988,7 +988,7 @@ namespace VeraCrypt } TextUserInterface *UI; }; - + return shared_ptr (new AdminPasswordRequestHandler (this)); } @@ -1060,7 +1060,7 @@ namespace VeraCrypt TextUserInterface::SetTerminalEcho (false); finally_do ({ TextUserInterface::SetTerminalEcho (true); }); - + wstring wPassword (UI->ReadInputStreamLine()); finally_do_arg (wstring *, &wPassword, { StringConverter::Erase (*finally_arg); }); @@ -1110,7 +1110,7 @@ namespace VeraCrypt { if (!options.Password) options.Password = AskPassword(); - + if (!options.TrueCryptMode && (options.Pim < 0)) options.Pim = AskPim (_("Enter PIM")); @@ -1118,7 +1118,7 @@ namespace VeraCrypt options.Keyfiles = AskKeyfiles(); VolumeInfoList mountedVolumes = UserInterface::MountAllDeviceHostedVolumes (options); - + if (!mountedVolumes.empty()) return mountedVolumes; @@ -1126,7 +1126,7 @@ namespace VeraCrypt options.Pim = -1; } } - + shared_ptr TextUserInterface::MountVolume (MountOptions &options) const { shared_ptr volume; @@ -1151,7 +1151,7 @@ namespace VeraCrypt // Mount point if (!options.MountPoint && !options.NoFilesystem) options.MountPoint.reset (new DirectoryPath (AskString (_("Enter mount directory [default]: ")))); - + VolumePassword password; KeyfileList keyfiles; @@ -1176,7 +1176,7 @@ namespace VeraCrypt { options.Password = AskPassword (StringFormatter (_("Enter password for {0}"), wstring (*options.Path))); } - + if (!options.TrueCryptMode && (options.Pim < 0)) { options.Pim = AskPim (StringFormatter (_("Enter PIM for {0}"), wstring (*options.Path))); @@ -1276,7 +1276,7 @@ namespace VeraCrypt } int TextUserInterface::OnRun() - { + { try { if (ProcessCommandLine ()) @@ -1362,7 +1362,7 @@ namespace VeraCrypt default: throw UserAbort (SRC_POS); } - + /* force the display of the random enriching interface */ RandomNumberGenerator::SetEnrichedByUserStatus (false); @@ -1513,7 +1513,7 @@ namespace VeraCrypt File volumeFile; volumeFile.Open (*volumePath, File::OpenReadWrite, File::ShareNone, File::PreserveTimestamps); - + RandomNumberGenerator::Start(); UserEnrichRandomPool(); @@ -1534,7 +1534,7 @@ namespace VeraCrypt { // Re-encrypt backup volume header Core->ReEncryptVolumeHeaderWithNewSalt (newHeaderBuffer, decryptedLayout->GetHeader(), options.Password, options.Pim, options.Keyfiles); - + // Write backup volume header headerOffset = decryptedLayout->GetBackupHeaderOffset(); if (headerOffset >= 0) @@ -1572,7 +1572,7 @@ namespace VeraCrypt } #endif } - + void TextUserInterface::UserEnrichRandomPool () const { RandomNumberGenerator::Start(); diff --git a/src/Main/TextUserInterface.h b/src/Main/TextUserInterface.h index fc25388d..7e562b01 100644 --- a/src/Main/TextUserInterface.h +++ b/src/Main/TextUserInterface.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Unix/Main.cpp b/src/Main/Unix/Main.cpp index b43ea1ea..8b08a919 100644 --- a/src/Main/Unix/Main.cpp +++ b/src/Main/Unix/Main.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -33,7 +33,7 @@ int main (int argc, char **argv) { // Make sure all required commands can be executed via default search path string sysPathStr = "/usr/sbin:/sbin:/usr/bin:/bin"; - + char *sysPath = getenv ("PATH"); if (sysPath) { diff --git a/src/Main/UserInterface.cpp b/src/Main/UserInterface.cpp index db53b7cc..8d4b701a 100644 --- a/src/Main/UserInterface.cpp +++ b/src/Main/UserInterface.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -73,7 +73,7 @@ namespace VeraCrypt static BOOL CALLBACK ChildWindows (HWND hwnd, LPARAM argsLP) { Args *args = reinterpret_cast (argsLP); - + char s[4096]; SendMessageA (hwnd, WM_GETTEXT, sizeof (s), (LPARAM) s); @@ -116,7 +116,7 @@ namespace VeraCrypt return; args.DriveRootPath = string() + mountPoint[0] + string (":\\"); - + EnumWindows (Enumerator::TopLevelWindows, (LPARAM) &args); #endif } @@ -237,7 +237,7 @@ namespace VeraCrypt if (Preferences.Verbose && !message.IsEmpty()) ShowInfo (message); } - + void UserInterface::DisplayVolumeProperties (const VolumeInfoList &volumes) const { if (volumes.size() < 1) @@ -281,7 +281,7 @@ namespace VeraCrypt prop << LangString["BLOCK_SIZE"] << L": " << blockSize.str() + L" " + LangString ["BITS"] << L'\n'; prop << LangString["MODE_OF_OPERATION"] << L": " << volume.EncryptionModeName << L'\n'; prop << LangString["PKCS5_PRF"] << L": " << volume.Pkcs5PrfName << L'\n'; - + prop << LangString["VOLUME_FORMAT_VERSION"] << L": " << (volume.MinRequiredProgramVersion < 0x10b ? 1 : 2) << L'\n'; prop << LangString["BACKUP_HEADER"] << L": " << LangString[volume.MinRequiredProgramVersion >= 0x10b ? "UISTR_YES" : "UISTR_NO"] << L'\n'; @@ -294,7 +294,7 @@ namespace VeraCrypt #ifdef TC_LINUX } #endif - + prop << L'\n'; } @@ -304,7 +304,7 @@ namespace VeraCrypt wxString UserInterface::ExceptionToMessage (const exception &ex) { wxString message; - + const Exception *e = dynamic_cast (&ex); if (e) { @@ -394,7 +394,7 @@ namespace VeraCrypt return wxString (errOutput).Trim (true); } - // PasswordIncorrect + // PasswordIncorrect if (dynamic_cast (&ex)) { wxString message = ExceptionTypeToString (typeid (ex)); @@ -419,7 +419,7 @@ namespace VeraCrypt if (dynamic_cast (&ex)) { string errorString = string (dynamic_cast (ex)); - + if (LangString.Exists (errorString)) return LangString[errorString]; @@ -510,7 +510,7 @@ namespace VeraCrypt #endif LangString.Init(); Core->Init(); - + CmdLine.reset (new CommandLineInterface (argc, argv, InterfaceType)); SetPreferences (CmdLine->Preferences); @@ -551,7 +551,7 @@ namespace VeraCrypt } } } - + void UserInterface::ListMountedVolumes (const VolumeInfoList &volumes) const { if (volumes.size() < 1) @@ -683,7 +683,7 @@ namespace VeraCrypt VolumeInfoList UserInterface::MountAllFavoriteVolumes (MountOptions &options) { BusyScope busy (this); - + VolumeInfoList newMountedVolumes; foreach_ref (const FavoriteVolume &favorite, FavoriteVolume::LoadList()) { @@ -805,7 +805,7 @@ namespace VeraCrypt if (Preferences.OpenExplorerWindowAfterMount && !mountedVolume->MountPoint.IsEmpty()) OpenExplorerWindow (mountedVolume->MountPoint); } - + void UserInterface::OnWarning (EventArgs &args) { ExceptionEventArgs &e = dynamic_cast (args); @@ -876,7 +876,7 @@ namespace VeraCrypt } else if (xdgOpenPresent) { - // Fallback on the standard xdg-open command + // Fallback on the standard xdg-open command // which is not always available by default args.push_back (string (path)); try @@ -905,7 +905,7 @@ namespace VeraCrypt wstring pwdInput; getline(wcin, pwdInput); - cmdLine.ArgPassword = ToUTF8Password ( pwdInput.c_str (), pwdInput.size ()); + cmdLine.ArgPassword = ToUTF8Password ( pwdInput.c_str (), pwdInput.size ()); } switch (cmdLine.ArgCommand) @@ -1025,7 +1025,7 @@ namespace VeraCrypt options->VolumeHeaderKdf = Pkcs5Kdf::GetAlgorithm (*cmdLine.ArgHash, false); RandomNumberGenerator::SetHash (cmdLine.ArgHash); } - + options->EA = cmdLine.ArgEncryptionAlgorithm; options->Filesystem = cmdLine.ArgFilesystem; options->Keyfiles = cmdLine.ArgKeyfiles; @@ -1494,7 +1494,7 @@ namespace VeraCrypt return s.str(); } - + bool UserInterface::VolumeHasUnrecommendedExtension (const VolumePath &path) const { wxString ext = wxFileName (wxString (wstring (path)).Lower()).GetExt(); @@ -1580,7 +1580,7 @@ namespace VeraCrypt VC_CONVERT_EXCEPTION (UserInterfaceException); VC_CONVERT_EXCEPTION (MissingArgument); VC_CONVERT_EXCEPTION (NoItemSelected); - VC_CONVERT_EXCEPTION (StringFormatterException); + VC_CONVERT_EXCEPTION (StringFormatterException); VC_CONVERT_EXCEPTION (ExecutedProcessFailed); VC_CONVERT_EXCEPTION (AlreadyInitialized); VC_CONVERT_EXCEPTION (AssertionFailed); @@ -1598,7 +1598,7 @@ namespace VeraCrypt VC_CONVERT_EXCEPTION (UnknownException); VC_CONVERT_EXCEPTION (UserAbort) VC_CONVERT_EXCEPTION (CipherInitError); - VC_CONVERT_EXCEPTION (WeakKeyDetected); + VC_CONVERT_EXCEPTION (WeakKeyDetected); VC_CONVERT_EXCEPTION (HigherVersionRequired); VC_CONVERT_EXCEPTION (KeyfilePathEmpty); VC_CONVERT_EXCEPTION (MissingVolumeData); @@ -1613,7 +1613,7 @@ namespace VeraCrypt VC_CONVERT_EXCEPTION (SecurityTokenLibraryNotInitialized); VC_CONVERT_EXCEPTION (SecurityTokenKeyfileAlreadyExists); VC_CONVERT_EXCEPTION (SecurityTokenKeyfileNotFound); - VC_CONVERT_EXCEPTION (UnsupportedAlgoInTrueCryptMode); + VC_CONVERT_EXCEPTION (UnsupportedAlgoInTrueCryptMode); VC_CONVERT_EXCEPTION (UnsupportedTrueCryptFormat); VC_CONVERT_EXCEPTION (SystemException); VC_CONVERT_EXCEPTION (CipherException); diff --git a/src/Main/UserInterface.h b/src/Main/UserInterface.h index 31f83e86..4f2d7695 100644 --- a/src/Main/UserInterface.h +++ b/src/Main/UserInterface.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/UserInterfaceException.h b/src/Main/UserInterfaceException.h index d87830f3..1ceacf7b 100644 --- a/src/Main/UserInterfaceException.h +++ b/src/Main/UserInterfaceException.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/UserInterfaceType.h b/src/Main/UserInterfaceType.h index 551b7845..dd5ef7a4 100644 --- a/src/Main/UserInterfaceType.h +++ b/src/Main/UserInterfaceType.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/UserPreferences.cpp b/src/Main/UserPreferences.cpp index 9e48b928..fafd0824 100644 --- a/src/Main/UserPreferences.cpp +++ b/src/Main/UserPreferences.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -32,7 +32,7 @@ namespace VeraCrypt else cfgVar = StringConverter::ToUInt32 (wstring (cfgText)); } - + void UserPreferences::SetValue (const wxString &cfgText, uint64 &cfgVar) { if (cfgText.empty()) @@ -108,12 +108,12 @@ namespace VeraCrypt TC_CONFIG_SET (UseKeyfiles); TC_CONFIG_SET (WipeCacheOnAutoDismount); TC_CONFIG_SET (WipeCacheOnClose); - + SetValue (configMap[L"DefaultTrueCryptMode"], DefaultMountOptions.TrueCryptMode); - + wstring defaultPrf; SetValue (configMap[L"DefaultPRF"], defaultPrf); - + shared_ptr savedKdf; try { @@ -123,9 +123,9 @@ namespace VeraCrypt catch (ParameterIncorrect&) { } - + DefaultMountOptions.Kdf = savedKdf; - DefaultMountOptions.ProtectionKdf = savedKdf; + DefaultMountOptions.ProtectionKdf = savedKdf; } // Default keyfiles @@ -137,7 +137,7 @@ namespace VeraCrypt DefaultKeyfiles.push_back (make_shared ((wstring) node.InnerText)); } } - + #ifdef TC_WINDOWS // Hotkeys Hotkeys = Hotkey::LoadList(); @@ -222,12 +222,12 @@ namespace VeraCrypt TC_CONFIG_ADD (UseKeyfiles); TC_CONFIG_ADD (WipeCacheOnAutoDismount); TC_CONFIG_ADD (WipeCacheOnClose); - - formatter.AddEntry (L"DefaultTrueCryptMode", DefaultMountOptions.TrueCryptMode); - + + formatter.AddEntry (L"DefaultTrueCryptMode", DefaultMountOptions.TrueCryptMode); + wstring defaultPrf = L"autodetection"; if (DefaultMountOptions.Kdf) - defaultPrf = DefaultMountOptions.Kdf->GetName (); + defaultPrf = DefaultMountOptions.Kdf->GetName (); formatter.AddEntry (L"DefaultPRF", defaultPrf); XmlWriter writer (Application::GetConfigFilePath (GetPreferencesFileName(), true)); @@ -236,7 +236,7 @@ namespace VeraCrypt // Default keyfiles FilePath keyfilesCfgPath = Application::GetConfigFilePath (GetDefaultKeyfilesFileName(), true); - + if (DefaultKeyfiles.empty()) { if (keyfilesCfgPath.IsFile()) diff --git a/src/Main/UserPreferences.h b/src/Main/UserPreferences.h index 35d74390..cff8fabe 100644 --- a/src/Main/UserPreferences.h +++ b/src/Main/UserPreferences.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/VolumeHistory.cpp b/src/Main/VolumeHistory.cpp index 44f43c4e..67824bc1 100644 --- a/src/Main/VolumeHistory.cpp +++ b/src/Main/VolumeHistory.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/VolumeHistory.h b/src/Main/VolumeHistory.h index 5eb0eab2..7667a18a 100644 --- a/src/Main/VolumeHistory.h +++ b/src/Main/VolumeHistory.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Xml.cpp b/src/Main/Xml.cpp index e57678bd..7197588e 100644 --- a/src/Main/Xml.cpp +++ b/src/Main/Xml.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Main/Xml.h b/src/Main/Xml.h index beac8dd6..bdfcce3c 100644 --- a/src/Main/Xml.h +++ b/src/Main/Xml.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Mount/Favorites.cpp b/src/Mount/Favorites.cpp index 77127c27..c27fed5f 100644 --- a/src/Mount/Favorites.cpp +++ b/src/Mount/Favorites.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -113,7 +113,7 @@ namespace VeraCrypt static BOOL CALLBACK FavoriteVolumesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { - /* This dialog is used both for System Favorites and non-system Favorites. + /* This dialog is used both for System Favorites and non-system Favorites. The following options have different meaning in System Favorites mode: @@ -157,14 +157,14 @@ namespace VeraCrypt // MOUNT_SYSTEM_FAVORITES_ON_BOOT SetWindowTextW (GetDlgItem (hwndDlg, IDC_FAVORITE_OPEN_EXPLORER_WIN_ON_MOUNT), GetString ("MOUNT_SYSTEM_FAVORITES_ON_BOOT")); - + // DISABLE_NONADMIN_SYS_FAVORITES_ACCESS SetWindowTextW (GetDlgItem (hwndDlg, IDC_FAVORITE_DISABLE_HOTKEY), GetString ("DISABLE_NONADMIN_SYS_FAVORITES_ACCESS")); // Group box - GetClientRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), &rec); + GetClientRect (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), &rec); SetWindowPos (GetDlgItem (hwndDlg, IDC_FAV_VOL_OPTIONS_GROUP_BOX), 0, 0, 0, rec.right, @@ -181,7 +181,7 @@ namespace VeraCrypt Favorites.clear(); LVCOLUMNW column; - SendMessageW (FavoriteListControl, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT); + SendMessageW (FavoriteListControl, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT); memset (&column, 0, sizeof (column)); column.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; @@ -459,7 +459,7 @@ namespace VeraCrypt return; AppendMenu (FavoriteVolumesMenu, MF_SEPARATOR, 0, L""); - + int i = 0; foreach (const FavoriteVolume &favorite, FavoriteVolumes) { @@ -764,7 +764,7 @@ namespace VeraCrypt if (favorite.ReadOnly) s += L" readonly=\"1\""; - + if (favorite.Removable) s += L" removable=\"1\""; @@ -776,7 +776,7 @@ namespace VeraCrypt if (favorite.MountOnLogOn) s += L" mountOnLogOn=\"1\""; - + if (favorite.DisableHotkeyMount) s += L" noHotKeyMount=\"1\""; diff --git a/src/Mount/Favorites.h b/src/Mount/Favorites.h index 3c8b1c9b..acb9c8d4 100644 --- a/src/Mount/Favorites.h +++ b/src/Mount/Favorites.h @@ -3,7 +3,7 @@ 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) + 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 @@ -20,7 +20,7 @@ namespace VeraCrypt struct FavoriteVolume { FavoriteVolume() - : + : Pim (0), DisableHotkeyMount (false), DisconnectedDevice (false), diff --git a/src/Mount/Hotkeys.c b/src/Mount/Hotkeys.c index 0403c634..007b2fb4 100644 --- a/src/Mount/Hotkeys.c +++ b/src/Mount/Hotkeys.c @@ -3,7 +3,7 @@ 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) + 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 @@ -60,12 +60,12 @@ BOOL GetKeyName (UINT vKey, wchar_t *keyName) { BOOL result = TRUE; - if (vKey >= 0x30 && vKey <= 0x5a) + if (vKey >= 0x30 && vKey <= 0x5a) { // ASCII characters StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%hc", (char) vKey); } - else if (vKey >= 0xE9 && vKey <= 0xF5) + else if (vKey >= 0xE9 && vKey <= 0xF5) { // OEM-specific StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM-%d", vKey); @@ -128,7 +128,7 @@ BOOL GetKeyName (UINT vKey, wchar_t *keyName) else if (vKey >= VK_NUMPAD0 && vKey <= VK_NUMPAD9) { // Numpad numbers - StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s %d", GetString ("VK_NUMPAD"), vKey - VK_NUMPAD0); + StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s %d", GetString ("VK_NUMPAD"), vKey - VK_NUMPAD0); } else { @@ -249,36 +249,36 @@ static void DisplayHotkeyList (HWND hwndDlg) switch (i) { - - case HK_AUTOMOUNT_DEVICES: + + case HK_AUTOMOUNT_DEVICES: item.pszText = GetString ("HK_AUTOMOUNT_DEVICES"); break; - case HK_DISMOUNT_ALL: + case HK_DISMOUNT_ALL: item.pszText = GetString ("HK_DISMOUNT_ALL"); break; - case HK_WIPE_CACHE: + case HK_WIPE_CACHE: item.pszText = GetString ("HK_WIPE_CACHE"); break; - case HK_DISMOUNT_ALL_AND_WIPE: + case HK_DISMOUNT_ALL_AND_WIPE: item.pszText = GetString ("HK_DISMOUNT_ALL_AND_WIPE"); break; - case HK_FORCE_DISMOUNT_ALL_AND_WIPE: + case HK_FORCE_DISMOUNT_ALL_AND_WIPE: item.pszText = GetString ("HK_FORCE_DISMOUNT_ALL_AND_WIPE"); break; - case HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT: + case HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT: item.pszText = GetString ("HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT"); break; - case HK_MOUNT_FAVORITE_VOLUMES: + case HK_MOUNT_FAVORITE_VOLUMES: item.pszText = GetString ("HK_MOUNT_FAVORITE_VOLUMES"); break; - case HK_SHOW_HIDE_MAIN_WINDOW: + case HK_SHOW_HIDE_MAIN_WINDOW: item.pszText = GetString ("HK_SHOW_HIDE_MAIN_WINDOW"); break; @@ -286,7 +286,7 @@ static void DisplayHotkeyList (HWND hwndDlg) item.pszText = GetString ("IDM_CLOSE_ALL_TOKEN_SESSIONS"); break; - default: + default: item.pszText = L"[?]"; } @@ -328,14 +328,14 @@ static void DisplayHotkeyList (HWND hwndDlg) else item.pszText = L""; - SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&item); + SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&item); } } BOOL CALLBACK HotkeysDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ +{ WORD lw = LOWORD (wParam); WORD hw = HIWORD (wParam); static BOOL bKeyScanOn; @@ -356,18 +356,18 @@ BOOL CALLBACK HotkeysDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPar memset (vkeysDown, 0, sizeof(vkeysDown)); SendMessageW (hList,LVM_SETEXTENDEDLISTVIEWSTYLE,0, - LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_LABELTIP - ); + LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_LABELTIP + ); - memset (&col,0,sizeof(col)); - col.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; - col.pszText = GetString ("ACTION"); + memset (&col,0,sizeof(col)); + col.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; + col.pszText = GetString ("ACTION"); col.cx = CompensateXDPI (341); col.fmt = LVCFMT_LEFT; SendMessageW (hList,LVM_INSERTCOLUMNW,0,(LPARAM)&col); - col.pszText = GetString ("SHORTCUT"); - col.cx = CompensateXDPI (190); + col.pszText = GetString ("SHORTCUT"); + col.cx = CompensateXDPI (190); col.fmt = LVCFMT_LEFT; SendMessageW (hList,LVM_INSERTCOLUMNW,1,(LPARAM)&col); @@ -388,7 +388,7 @@ BOOL CALLBACK HotkeysDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPar EnableWindow (GetDlgItem (hwndDlg, IDC_HOTKEY_REMOVE), FALSE); DisplayHotkeyList(hwndDlg); - + if (SetTimer (hwndDlg, 0xfe, 10, NULL) == 0) { Error ("CANNOT_SET_TIMER", MainDlg); @@ -459,7 +459,7 @@ BOOL CALLBACK HotkeysDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPar if (nSelectedHotkeyId >= 0 && currentVKeyCode != 0) { - UINT modifiers = 0; + UINT modifiers = 0; if (GetCheckBox (hwndDlg, IDC_HK_MOD_CTRL)) modifiers = MOD_CONTROL; diff --git a/src/Mount/Hotkeys.h b/src/Mount/Hotkeys.h index 167ddc54..db26af0f 100644 --- a/src/Mount/Hotkeys.h +++ b/src/Mount/Hotkeys.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Mount/MainCom.cpp b/src/Mount/MainCom.cpp index 6955897d..8f3927ad 100644 --- a/src/Mount/MainCom.cpp +++ b/src/Mount/MainCom.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Mount/MainCom.h b/src/Mount/MainCom.h index 5bd8e222..7195e8ea 100644 --- a/src/Mount/MainCom.h +++ b/src/Mount/MainCom.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Mount/MainCom.idl b/src/Mount/MainCom.idl index 4999dba5..9362fd42 100644 --- a/src/Mount/MainCom.idl +++ b/src/Mount/MainCom.idl @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Mount/Mount.c b/src/Mount/Mount.c index ef665a5a..62ac5e0f 100644 --- a/src/Mount/Mount.c +++ b/src/Mount/Mount.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -147,13 +147,13 @@ KeyFile *FirstCmdKeyFile; HBITMAP hbmLogoBitmapRescaled = NULL; wchar_t OrigKeyboardLayout [8+1] = L"00000409"; -BOOL bKeyboardLayoutChanged = FALSE; /* TRUE if the keyboard layout was changed to the standard US keyboard layout (from any other layout). */ -BOOL bKeybLayoutAltKeyWarningShown = FALSE; /* TRUE if the user has been informed that it is not possible to type characters by pressing keys while the right Alt key is held down. */ +BOOL bKeyboardLayoutChanged = FALSE; /* TRUE if the keyboard layout was changed to the standard US keyboard layout (from any other layout). */ +BOOL bKeybLayoutAltKeyWarningShown = FALSE; /* TRUE if the user has been informed that it is not possible to type characters by pressing keys while the right Alt key is held down. */ static KeyFilesDlgParam hidVolProtKeyFilesParam; static MOUNT_LIST_STRUCT LastKnownMountList; -VOLUME_NOTIFICATIONS_LIST VolumeNotificationsList; +VOLUME_NOTIFICATIONS_LIST VolumeNotificationsList; static DWORD LastKnownLogicalDrives; static HANDLE TaskBarIconMutex = NULL; @@ -184,8 +184,8 @@ static void RegisterWtsNotification(HWND hWnd) { fnWtsRegisterSessionNotification = (WTSREGISTERSESSIONNOTIFICATION) GetProcAddress(hWtsLib, "WTSRegisterSessionNotification" ); fnWtsUnRegisterSessionNotification = (WTSUNREGISTERSESSIONNOTIFICATION) GetProcAddress(hWtsLib, "WTSUnRegisterSessionNotification" ); - if ( !fnWtsRegisterSessionNotification - || !fnWtsUnRegisterSessionNotification + if ( !fnWtsRegisterSessionNotification + || !fnWtsUnRegisterSessionNotification || !fnWtsRegisterSessionNotification( hWnd, NOTIFY_FOR_THIS_SESSION ) ) { @@ -264,8 +264,8 @@ void RefreshMainDlg (HWND hwndDlg) void EndMainDlg (HWND hwndDlg) { MoveEditToCombo (GetDlgItem (hwndDlg, IDC_VOLUME), bHistory); - - if (UsePreferences) + + if (UsePreferences) SaveSettings (hwndDlg); if (bWipeCacheOnExit) @@ -324,7 +324,7 @@ static void InitMainDialog (HWND hwndDlg) info.dwTypeData = str; info.cch = (UINT) wcslen (str); - SetMenuItemInfoW (GetMenu (hwndDlg), i, FALSE, &info); + SetMenuItemInfoW (GetMenu (hwndDlg), i, FALSE, &info); } for (i = 0; popupTexts[i] != 0; i++) @@ -345,7 +345,7 @@ static void InitMainDialog (HWND hwndDlg) info.dwTypeData = str; info.cch = (UINT) wcslen (str); - SetMenuItemInfoW (GetMenu (hwndDlg), i, TRUE, &info); + SetMenuItemInfoW (GetMenu (hwndDlg), i, TRUE, &info); } // Disable menu item for changing system header key derivation algorithm until it's implemented @@ -375,7 +375,7 @@ static void InitMainDialog (HWND hwndDlg) { SelectItem (GetDlgItem (hwndDlg, IDC_DRIVELIST), *szDriveLetter); - if(nSelectedDriveIndex > SendMessage (GetDlgItem (hwndDlg, IDC_DRIVELIST), LVM_GETITEMCOUNT, 0, 0)/2) + if(nSelectedDriveIndex > SendMessage (GetDlgItem (hwndDlg, IDC_DRIVELIST), LVM_GETITEMCOUNT, 0, 0)/2) SendMessage(GetDlgItem (hwndDlg, IDC_DRIVELIST), LVM_SCROLL, 0, 10000); } else @@ -446,13 +446,13 @@ void GetVolumePath (HWND hwndDlg, LPWSTR szPath, int nMaxCount) CorrectFileName (szPath); } -/* Returns TRUE if the last partition/drive selected via the Select Device dialog box was the system -partition/drive and if it is encrypted. +/* Returns TRUE if the last partition/drive selected via the Select Device dialog box was the system +partition/drive and if it is encrypted. WARNING: This function is very fast but not always reliable (for example, if the user manually types - a device path before Select Device is invoked during the session; after the Select Device dialog + a device path before Select Device is invoked during the session; after the Select Device dialog has been invoked at least once, the correct system device paths are cached). Therefore, it must NOT - be used before performing any dangerous operations (such as header backup restore or formatting a - supposedly non-system device) -- instead use IsSystemDevicePath(path, hwndDlg, TRUE) for such + be used before performing any dangerous operations (such as header backup restore or formatting a + supposedly non-system device) -- instead use IsSystemDevicePath(path, hwndDlg, TRUE) for such purposes. This function can be used only for preliminary GUI checks requiring very fast responses. */ BOOL ActiveSysEncDeviceSelected (void) { @@ -481,9 +481,9 @@ BOOL ActiveSysEncDeviceSelected (void) // When a function does not require the affected volume to be dismounted, there may be cases where we have two valid // paths selected in the main window and we cannot be sure which of them the user really intends to apply the function to. -// This function asks the user to explicitly select either the volume path specified in the input field below the main +// This function asks the user to explicitly select either the volume path specified in the input field below the main // drive list (whether mounted or not), or the path to the volume selected in the main drive list. If, however, both -// of the GUI elements contain the same volume (or one of them does not contain any path), this function does not +// of the GUI elements contain the same volume (or one of them does not contain any path), this function does not // ask the user and returns the volume path directly (no selection ambiguity). // If driveNoPtr is not NULL, and the volume is mounted, its drive letter is returned in *driveNoPtr (if no valid drive // letter is resolved, -1 is stored instead). @@ -510,7 +510,7 @@ static wstring ResolveAmbiguousSelection (HWND hwndDlg, int *driveNoPtr) if (VolumeSelected (MainDlg)) { - // volPathInputField will contain the volume path (if any) from the input field below the drive list + // volPathInputField will contain the volume path (if any) from the input field below the drive list GetVolumePath (MainDlg, volPathInputField, ARRAYSIZE (volPathInputField)); if (!ambig) @@ -541,7 +541,7 @@ static wstring ResolveAmbiguousSelection (HWND hwndDlg, int *driveNoPtr) case TC_MLIST_ITEM_SYS_PARTITION: GetSysDevicePaths (MainDlg); - + if (bCachedSysDevicePathsValid) { volPathDriveListStr = (wstring) SysPartitionDevicePath; @@ -796,12 +796,12 @@ void LoadSettingsAndCheckModified (HWND hwndDlg, BOOL bOnlyCheckModified, BOOL* ConfigReadCompareInt ("DefaultTrueCryptMode", FALSE, &DefaultVolumeTrueCryptMode, bOnlyCheckModified, pbSettingsModified); if (bOnlyCheckModified) - { + { if (!IsNonInstallMode ()) { ConfigReadString ("Language", "", langid, sizeof (langid)); // when installed, if no preferred language set by user, English is set default - // + // if (langid [0] == 0) StringCbCopyA (langid, sizeof(langid), "en"); @@ -958,10 +958,10 @@ static BOOL SysEncryptionOrDecryptionRequired (void) return (SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING || SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING - || + || ( - BootEncStatus.DriveMounted - && + BootEncStatus.DriveMounted + && ( BootEncStatus.ConfiguredEncryptedAreaStart != BootEncStatus.EncryptedAreaStart || BootEncStatus.ConfiguredEncryptedAreaEnd != BootEncStatus.EncryptedAreaEnd @@ -1071,7 +1071,7 @@ unsigned __int64 GetSysEncDeviceEncryptedPartSize (BOOL bSilent) return 0; } - if ( BootEncStatus.EncryptedAreaEnd < 0 + if ( BootEncStatus.EncryptedAreaEnd < 0 || BootEncStatus.EncryptedAreaStart < 0 || BootEncStatus.EncryptedAreaEnd < BootEncStatus.EncryptedAreaStart ) @@ -1101,7 +1101,7 @@ static void PopulateSysEncContextMenu (HMENU popup, BOOL bToolsOnly) if (SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING) AppendMenuW (popup, MF_STRING, IDM_PERMANENTLY_DECRYPT_SYS, GetString ("PERMANENTLY_DECRYPT")); - + AppendMenuW (popup, MF_STRING, IDM_ENCRYPT_SYSTEM_DEVICE, GetString ("ENCRYPT")); AppendMenu (popup, MF_SEPARATOR, 0, L""); } @@ -1239,7 +1239,7 @@ BOOL CheckSysEncMountWithoutPBA (HWND hwndDlg, const wchar_t *devicePath, BOOL q // Returns TRUE if the host drive of the specified partition contains a portion of the TrueCrypt Boot Loader // and if the drive is not within key scope of active system encryption (e.g. the system drive of the running OS). // If bPrebootPasswordDlgMode is TRUE, this function returns FALSE (because the check would be redundant). -BOOL TCBootLoaderOnInactiveSysEncDrive (wchar_t *szDevicePath) +BOOL TCBootLoaderOnInactiveSysEncDrive (wchar_t *szDevicePath) { try { @@ -1281,14 +1281,14 @@ BOOL SelectItem (HWND hTree, wchar_t nLetter) { if (nLetter == 0) { - // The caller specified an invalid drive letter (typically because it is unknown). + // The caller specified an invalid drive letter (typically because it is unknown). // Find out which drive letter is currently selected in the list and use it. nLetter = (wchar_t) (HIWORD (GetSelectedLong (hTree))); } int i; LVITEM item; - + for (i = 0; i < ListView_GetItemCount(hTree); i++) { memset(&item, 0, sizeof(LVITEM)); @@ -1412,7 +1412,7 @@ static void LaunchVolExpander (HWND hwndDlg) // drive>0 = update only the corresponding drive subitems void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) { - // Remember the top-most visible item + // Remember the top-most visible item int lastTopMostVisibleItem = ListView_GetTopIndex (hTree); wchar_t *szDriveLetters[]= @@ -1423,7 +1423,7 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) L"Z:"}; DWORD dwResult; - BOOL bResult; + BOOL bResult; DWORD dwUsedDrives; MOUNT_LIST_STRUCT driver; VOLUME_PROPERTIES_STRUCT propSysEnc; @@ -1500,20 +1500,20 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) listItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; listItem.iImage = 2; - listItem.iItem = item++; + listItem.iItem = item++; listItem.pszText = szTmp; szTmp[0] = L' '; szTmp[1] = 0; - listItem.lParam = MAKELONG (TC_MLIST_ITEM_SYS_DRIVE, ENC_SYSDRIVE_PSEUDO_DRIVE_LETTER); + listItem.lParam = MAKELONG (TC_MLIST_ITEM_SYS_DRIVE, ENC_SYSDRIVE_PSEUDO_DRIVE_LETTER); - if(drive == 0) + if(drive == 0) ListView_InsertItem (hTree, &listItem); else ListView_SetItem (hTree, &listItem); - listItem.mask=LVIF_TEXT; + listItem.mask=LVIF_TEXT; // Fully encrypted if (SysDriveOrPartitionFullyEncrypted (TRUE)) @@ -1530,14 +1530,14 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) if (BootEncStatus.SetupMode != SetupDecryption) { - StringCbPrintfW (szTmpW, + StringCbPrintfW (szTmpW, sizeof szTmpW, GetString ("SYSTEM_DRIVE_ENCRYPTING"), (double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0); } else { - StringCbPrintfW (szTmpW, + StringCbPrintfW (szTmpW, sizeof szTmpW, GetString ("SYSTEM_DRIVE_DECRYPTING"), 100.0 - ((double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0)); @@ -1545,13 +1545,13 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) } else { - StringCbPrintfW (szTmpW, + StringCbPrintfW (szTmpW, sizeof szTmpW, GetString ("SYSTEM_DRIVE_PARTIALLY_ENCRYPTED"), (double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0); } } - + ListSubItemSet (hTree, listItem.iItem, 1, szTmpW); GetSizeString (GetSysEncDeviceSize(TRUE), szTmpW, sizeof(szTmpW)); @@ -1602,23 +1602,23 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) listItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; listItem.iImage = bSysEncPartition ? 2 : 1; - listItem.iItem = item++; + listItem.iItem = item++; if (drive > 0 && drive != curDrive) continue; listItem.lParam = MAKELONG ( - bSysEncPartition ? TC_MLIST_ITEM_SYS_PARTITION : TC_MLIST_ITEM_NONSYS_VOL, + bSysEncPartition ? TC_MLIST_ITEM_SYS_PARTITION : TC_MLIST_ITEM_NONSYS_VOL, i + L'A'); listItem.pszText = szDriveLetters[i]; - - if (drive == 0) + + if (drive == 0) ListView_InsertItem (hTree, &listItem); else ListView_SetItem (hTree, &listItem); - listItem.mask=LVIF_TEXT; + listItem.mask=LVIF_TEXT; listItem.pszText = szTmp; if (bSysEncPartition) @@ -1638,14 +1638,14 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) if (BootEncStatus.SetupMode != SetupDecryption) { - StringCbPrintfW (szTmpW, + StringCbPrintfW (szTmpW, sizeof szTmpW, GetString ("SYSTEM_PARTITION_ENCRYPTING"), (double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0); } else { - StringCbPrintfW (szTmpW, + StringCbPrintfW (szTmpW, sizeof szTmpW, GetString ("SYSTEM_PARTITION_DECRYPTING"), 100.0 - ((double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0)); @@ -1653,7 +1653,7 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) } else { - StringCbPrintfW (szTmpW, + StringCbPrintfW (szTmpW, sizeof szTmpW, GetString ("SYSTEM_PARTITION_PARTIALLY_ENCRYPTED"), (double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0); @@ -1714,7 +1714,7 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) default: ws = L"?"; } - + if (driver.truecryptMode[i]) { StringCbPrintfW (szTmpW, sizeof(szTmpW), L"TrueCrypt-%s", ws); @@ -1724,7 +1724,7 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) ListSubItemSet (hTree, listItem.iItem, 4, ws); if (driver.volumeType[i] == PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED) // Normal/outer volume (hidden volume protected AND write denied) - { + { if (!VolumeNotificationsList.bHidVolDamagePrevReported[i]) { wchar_t szTmp[4096]; @@ -1757,16 +1757,16 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) listItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; listItem.iImage = 0; - listItem.iItem = item++; + listItem.iItem = item++; listItem.pszText = szDriveLetters[i]; listItem.lParam = MAKELONG (TC_MLIST_ITEM_FREE, i + 'A'); - if(drive == 0) + if(drive == 0) ListView_InsertItem (hTree, &listItem); else ListView_SetItem (hTree, &listItem); - listItem.mask=LVIF_TEXT; + listItem.mask=LVIF_TEXT; listItem.pszText = L""; listItem.iSubItem = 1; ListView_SetItem (hTree, &listItem); @@ -1970,7 +1970,7 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; int EffectiveVolumePim = CmdVolumePim; - /* Priority is given to command line parameters + /* Priority is given to command line parameters * Default values used only when nothing specified in command line */ if (EffectiveVolumePkcs5 == 0) @@ -2259,9 +2259,9 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR wchar_t tmp[MAX_PASSWORD+1]; wmemset (tmp, L'X', MAX_PASSWORD); tmp[MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), tmp); RestoreDefaultKeyFilesParam (); EndDialog (hwndDlg, IDCANCEL); @@ -2273,8 +2273,8 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR PasswordChangeEnable (hwndDlg, IDOK, IDC_OLD_PASSWORD, KeyFilesEnable && FirstKeyFile != NULL, - IDC_PASSWORD, IDC_VERIFY, - newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); + IDC_PASSWORD, IDC_VERIFY, + newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); if ((lw == IDC_OLD_PIM) && IsWindowEnabled (GetDlgItem (hwndDlg, IDC_PIM))) { @@ -2353,20 +2353,20 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR { KeyFilesEnable = param.EnableKeyFiles; FirstKeyFile = param.FirstKeyFile; - + SetCheckBox (hwndDlg, IDC_ENABLE_KEYFILES, KeyFilesEnable); } PasswordChangeEnable (hwndDlg, IDOK, IDC_OLD_PASSWORD, KeyFilesEnable && FirstKeyFile != NULL, - IDC_PASSWORD, IDC_VERIFY, - newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); + IDC_PASSWORD, IDC_VERIFY, + newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); return 1; } - + if (lw == IDC_NEW_KEYFILES) { if (bSysEncPwdChangeDlgMode) @@ -2383,14 +2383,14 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (hwndDlg, IDOK), GetDlgItem (hwndDlg, IDC_PASSWORD), GetDlgItem (hwndDlg, IDC_VERIFY), NULL, NULL, - newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); + newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); } PasswordChangeEnable (hwndDlg, IDOK, IDC_OLD_PASSWORD, KeyFilesEnable && FirstKeyFile != NULL, - IDC_PASSWORD, IDC_VERIFY, - newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); + IDC_PASSWORD, IDC_VERIFY, + newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); return 1; } @@ -2402,8 +2402,8 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR PasswordChangeEnable (hwndDlg, IDOK, IDC_OLD_PASSWORD, KeyFilesEnable && FirstKeyFile != NULL, - IDC_PASSWORD, IDC_VERIFY, - newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); + IDC_PASSWORD, IDC_VERIFY, + newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); return 1; } @@ -2415,8 +2415,8 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR PasswordChangeEnable (hwndDlg, IDOK, IDC_OLD_PASSWORD, KeyFilesEnable && FirstKeyFile != NULL, - IDC_PASSWORD, IDC_VERIFY, - newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); + IDC_PASSWORD, IDC_VERIFY, + newKeyFilesParam.EnableKeyFiles && newKeyFilesParam.FirstKeyFile != NULL); return 1; } @@ -2428,7 +2428,7 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR case IDC_PKCS5_PRF_ID: if (bSysEncPwdChangeDlgMode) { - int new_hash_algo_id = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, + int new_hash_algo_id = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); if (new_hash_algo_id != 0 && !HashForSystemEncryption(new_hash_algo_id)) @@ -2471,14 +2471,14 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR Password oldPassword; Password newPassword; WipeAlgorithmId headerWiperMode = (WipeAlgorithmId) SendMessage ( - GetDlgItem (hwndDlg, IDC_WIPE_MODE), - CB_GETITEMDATA, - SendMessage (GetDlgItem (hwndDlg, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), + GetDlgItem (hwndDlg, IDC_WIPE_MODE), + CB_GETITEMDATA, + SendMessage (GetDlgItem (hwndDlg, IDC_WIPE_MODE), CB_GETCURSEL, 0, 0), 0); int nStatus; - int old_pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_OLD_PRF_ID), CB_GETITEMDATA, + int old_pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_OLD_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_OLD_PRF_ID), CB_GETCURSEL, 0, 0), 0); - int pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, + int pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); BOOL truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); @@ -2603,9 +2603,9 @@ err: wchar_t tmp[MAX_PASSWORD+1]; wmemset (tmp, L'X', MAX_PASSWORD); tmp[MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), tmp); KeyFileRemoveAll (&newKeyFilesParam.FirstKeyFile); RestoreDefaultKeyFilesParam (); @@ -2871,7 +2871,7 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa mountOptions.ProtectedHidVolPkcs5Prf = *pkcs5; if (mountOptions.ProtectedHidVolPim == 0) mountOptions.ProtectedHidVolPim = *pim; - DialogBoxParamW (hInst, + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions); @@ -2935,7 +2935,7 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa if (lw == IDCANCEL || lw == IDOK) { wchar_t tmp[MAX_PASSWORD+1]; - + if (lw == IDOK) { if (mountOptions.ProtectHiddenVolume && hidVolProtKeyFilesParam.EnableKeyFiles) @@ -2946,14 +2946,14 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa else return 1; - bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_CACHE)); + bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_CACHE)); *pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); *truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); *pim = GetPim (hwndDlg, IDC_PIM); /* SHA-256 is not supported by TrueCrypt */ - if ( (*truecryptMode) + if ( (*truecryptMode) && ((*pkcs5 == SHA256) || (mountOptions.ProtectHiddenVolume && mountOptions.ProtectedHidVolPkcs5Prf == SHA256)) ) { @@ -2961,7 +2961,7 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa return 1; } - if ( (*truecryptMode) + if ( (*truecryptMode) && (*pim != 0) ) { @@ -2973,8 +2973,8 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa // Attempt to wipe password stored in the input field buffer wmemset (tmp, L'X', MAX_PASSWORD); tmp[MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); if (hidVolProtKeyFilesParam.FirstKeyFile != NULL) { @@ -2987,7 +2987,7 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD); // Restore the original keyboard layout - if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) + if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); } @@ -3022,7 +3022,7 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa } } } - break; + break; case WM_DROPFILES: { @@ -3095,71 +3095,71 @@ BOOL CALLBACK PreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM PreferencesDialogActive = TRUE; LocalizeDialog (hwndDlg, "IDD_PREFERENCES_DLG"); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_OPEN_EXPLORER), BM_SETCHECK, + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_OPEN_EXPLORER), BM_SETCHECK, bExplore ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_USE_DIFF_TRAY_ICON_IF_VOL_MOUNTED), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_USE_DIFF_TRAY_ICON_IF_VOL_MOUNTED), BM_SETCHECK, bUseDifferentTrayIconIfVolMounted ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PRESERVE_TIMESTAMPS), BM_SETCHECK, + + SendMessage (GetDlgItem (hwndDlg, IDC_PRESERVE_TIMESTAMPS), BM_SETCHECK, defaultMountOptions.PreserveTimestamp ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_SHOW_DISCONNECTED_NETWORK_DRIVES), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_SHOW_DISCONNECTED_NETWORK_DRIVES), BM_SETCHECK, bShowDisconnectedNetworkDrives ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_HIDE_WAITING_DIALOG), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_HIDE_WAITING_DIALOG), BM_SETCHECK, bHideWaitingDialog ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT), BM_SETCHECK, + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT), BM_SETCHECK, bCacheDuringMultipleMount ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_EXIT), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_EXIT), BM_SETCHECK, bWipeCacheOnExit ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_AUTODISMOUNT), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_AUTODISMOUNT), BM_SETCHECK, bWipeCacheOnAutoDismount ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PASSWORDS), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PASSWORDS), BM_SETCHECK, bCacheInDriver ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PIM), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PIM), BM_SETCHECK, bIncludePimInCache? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_READONLY), BM_SETCHECK, + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_READONLY), BM_SETCHECK, defaultMountOptions.ReadOnly ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_REMOVABLE), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_REMOVABLE), BM_SETCHECK, defaultMountOptions.Removable ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_LOGON_START), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_LOGON_START), BM_SETCHECK, bStartOnLogon ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_LOGON_MOUNT_DEVICES), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_LOGON_MOUNT_DEVICES), BM_SETCHECK, bMountDevicesOnLogon ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_BKG_TASK_ENABLE), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_BKG_TASK_ENABLE), BM_SETCHECK, bEnableBkgTask ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_CLOSE_BKG_TASK_WHEN_NOVOL), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_CLOSE_BKG_TASK_WHEN_NOVOL), BM_SETCHECK, bCloseBkgTaskWhenNoVolumes || IsNonInstallMode() ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_LOGOFF), BM_SETCHECK, + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_LOGOFF), BM_SETCHECK, bDismountOnLogOff ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SESSION_LOCKED), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SESSION_LOCKED), BM_SETCHECK, bDismountOnSessionLocked ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_POWERSAVING), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_POWERSAVING), BM_SETCHECK, bDismountOnPowerSaving ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SCREENSAVER), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_SCREENSAVER), BM_SETCHECK, bDismountOnScreenSaver ? BST_CHECKED:BST_UNCHECKED, 0); - - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT), BM_SETCHECK, + + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT), BM_SETCHECK, bForceAutoDismount ? BST_CHECKED:BST_UNCHECKED, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE), BM_SETCHECK, MaxVolumeIdleTime > 0 ? BST_CHECKED:BST_UNCHECKED, 0); SetDlgItemInt (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE_TIME, abs (MaxVolumeIdleTime), FALSE); @@ -3221,15 +3221,15 @@ BOOL CALLBACK PreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM { WaitCursor (); - bExplore = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_OPEN_EXPLORER)); - bUseDifferentTrayIconIfVolMounted = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_USE_DIFF_TRAY_ICON_IF_VOL_MOUNTED)); - bPreserveTimestamp = defaultMountOptions.PreserveTimestamp = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PRESERVE_TIMESTAMPS)); - bShowDisconnectedNetworkDrives = IsButtonChecked (GetDlgItem (hwndDlg, IDC_SHOW_DISCONNECTED_NETWORK_DRIVES)); - bHideWaitingDialog = IsButtonChecked (GetDlgItem (hwndDlg, IDC_HIDE_WAITING_DIALOG)); + bExplore = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_OPEN_EXPLORER)); + bUseDifferentTrayIconIfVolMounted = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_USE_DIFF_TRAY_ICON_IF_VOL_MOUNTED)); + bPreserveTimestamp = defaultMountOptions.PreserveTimestamp = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PRESERVE_TIMESTAMPS)); + bShowDisconnectedNetworkDrives = IsButtonChecked (GetDlgItem (hwndDlg, IDC_SHOW_DISCONNECTED_NETWORK_DRIVES)); + bHideWaitingDialog = IsButtonChecked (GetDlgItem (hwndDlg, IDC_HIDE_WAITING_DIALOG)); bCacheDuringMultipleMount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT)); bWipeCacheOnExit = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_EXIT)); bWipeCacheOnAutoDismount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_AUTODISMOUNT)); - bCacheInDriverDefault = bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PASSWORDS)); + bCacheInDriverDefault = bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PASSWORDS)); bIncludePimInCache = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_CACHE_PIM)); defaultMountOptions.ReadOnly = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_READONLY)); defaultMountOptions.Removable = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_MOUNT_REMOVABLE)); @@ -3242,8 +3242,8 @@ BOOL CALLBACK PreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM bForceAutoDismount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT)); MaxVolumeIdleTime = GetDlgItemInt (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE_TIME, NULL, FALSE) * (IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE)) ? 1 : -1); - bStartOnLogon = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_LOGON_START)); - bMountDevicesOnLogon = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_LOGON_MOUNT_DEVICES)); + bStartOnLogon = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_LOGON_START)); + bMountDevicesOnLogon = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_LOGON_MOUNT_DEVICES)); ManageStartupSeq (); @@ -3307,11 +3307,11 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM case WM_INITDIALOG: { BOOL protect; - + mountOptions = (MountOptions *) lParam; LocalizeDialog (hwndDlg, "IDD_MOUNT_OPTIONS"); - + SendDlgItemMessage (hwndDlg, IDC_MOUNT_READONLY, BM_SETCHECK, mountOptions->ReadOnly ? BST_CHECKED : BST_UNCHECKED, 0); SendDlgItemMessage (hwndDlg, IDC_MOUNT_REMOVABLE, BM_SETCHECK, @@ -3329,7 +3329,7 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM SendDlgItemMessage (hwndDlg, IDC_USE_EMBEDDED_HEADER_BAK, BM_SETCHECK, mountOptions->UseBackupHeader ? BST_CHECKED : BST_UNCHECKED, 0); - + EnableWindow (GetDlgItem (hwndDlg, IDC_MOUNT_SYSENC_PART_WITHOUT_PBA), !bPrebootPasswordDlgMode); SetDlgItemTextW (hwndDlg, IDC_VOLUME_LABEL, mountOptions->Label); @@ -3394,7 +3394,7 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW); ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW); } - + ToHyperlink (hwndDlg, IDC_LINK_HIDVOL_PROTECTION_INFO); } @@ -3469,7 +3469,7 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM // Cleanup wmemset (tmp, L'X', MAX_PASSWORD); tmp[MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); EndDialog (hwndDlg, lw); return 1; @@ -3478,7 +3478,7 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM if (lw == IDOK) { wchar_t tmp[MAX_PASSWORD+1]; - + mountOptions->ReadOnly = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY)); mountOptions->Removable = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_REMOVABLE)); mountOptions->ProtectHiddenVolume = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL)); @@ -3486,7 +3486,7 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM mountOptions->UseBackupHeader = IsButtonChecked (GetDlgItem (hwndDlg, IDC_USE_EMBEDDED_HEADER_BAK)); GetDlgItemTextW (hwndDlg, IDC_VOLUME_LABEL, mountOptions->Label, sizeof (mountOptions->Label) /sizeof (wchar_t)); - + if (mountOptions->ProtectHiddenVolume) { GetPassword (hwndDlg, IDC_PASSWORD_PROT_HIDVOL, @@ -3495,7 +3495,7 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM mountOptions->ProtectedHidVolPassword.Length = (unsigned __int32) strlen ((char *) mountOptions->ProtectedHidVolPassword.Text); - mountOptions->ProtectedHidVolPkcs5Prf = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, + mountOptions->ProtectedHidVolPkcs5Prf = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); mountOptions->ProtectedHidVolPim = GetPim (hwndDlg, IDC_PIM); @@ -3504,7 +3504,7 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM // Cleanup wmemset (tmp, L'X', MAX_PASSWORD); tmp[MAX_PASSWORD] = 0; - SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); + SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp); if ((mountOptions->ProtectHiddenVolume && !bEnableBkgTask) && (AskWarnYesNo ("HIDVOL_PROT_BKG_TASK_WARNING", hwndDlg) == IDYES)) @@ -3587,7 +3587,7 @@ int GetCipherBlockSizeByDriveNo (int nDosDriveNo) } -// Returns the mode of operation in which the volume mounted as the specified drive letter is encrypted. +// Returns the mode of operation in which the volume mounted as the specified drive letter is encrypted. int GetModeOfOperationByDriveNo (int nDosDriveNo) { VOLUME_PROPERTIES_STRUCT prop; @@ -3803,9 +3803,9 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP else { bool truecryptMode = prop.pkcs5Iterations == get_pkcs5_iteration_count(prop.pkcs5, 0, TRUE, prop.partitionInInactiveSysEncScope); - s = prop.hiddenVolume ? GetString ("HIDDEN") : + s = prop.hiddenVolume ? GetString ("HIDDEN") : (prop.hiddenVolProtection != HIDVOL_PROT_STATUS_NONE ? GetString ("OUTER") : GetString ("NORMAL")); - + if (truecryptMode) { StringCbPrintfW (sw, sizeof(sw), L"TrueCrypt - %s", s); @@ -3814,7 +3814,7 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP else ListSubItemSet (list, i++, 1, s); } - + if (!bSysEnc) { // Write protection @@ -3856,7 +3856,7 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP // Key size(s) { wchar_t name[128]; - int size = EAGetKeySize (prop.ea); + int size = EAGetKeySize (prop.ea); EAGetName (name, prop.ea, 1); // Primary key @@ -3875,7 +3875,7 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP // Block size ListItemAdd (list, i, GetString ("BLOCK_SIZE")); - + StringCbPrintfW (sw, sizeof(sw), L"%d ", CipherGetBlockSize (EAGetFirstCipher(prop.ea))*8); StringCbCatW (sw, sizeof(sw), GetString ("BITS")); ListSubItemSet (list, i++, 1, sw); @@ -3979,7 +3979,7 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP else { - StringCbPrintfW (sw, + StringCbPrintfW (sw, sizeof sw, GetString ("PROCESSED_PORTION_X_PERCENT"), (double) GetSysEncDeviceEncryptedPartSize (FALSE) / (double) GetSysEncDeviceSize (FALSE) * 100.0); @@ -4005,7 +4005,7 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP not open, because drag&drop operation would be initiated. Therefore, we're handling RMB drag-and-drop operations as well. */ { - + DisplayVolumePropertiesListContextMenu (hwndDlg, lParam); return 1; @@ -4019,9 +4019,9 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP HWND hList = GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES_LIST); // only handle if it is coming from keyboard and if the drive // list has focus. The other cases are handled elsewhere - if ( (-1 == GET_X_LPARAM(lParam)) + if ( (-1 == GET_X_LPARAM(lParam)) && (-1 == GET_Y_LPARAM(lParam)) - && (GetFocus () == hList) + && (GetFocus () == hList) ) { DisplayVolumePropertiesListContextMenu (hwndDlg, NULL); @@ -4061,16 +4061,16 @@ BOOL CALLBACK TravelerDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa LocalizeDialog (hwndDlg, "IDD_TRAVELER_DLG"); - SendDlgItemMessage (hwndDlg, IDC_COPY_WIZARD, BM_SETCHECK, + SendDlgItemMessage (hwndDlg, IDC_COPY_WIZARD, BM_SETCHECK, BST_CHECKED, 0); - SendDlgItemMessage (hwndDlg, IDC_COPY_EXPANDER, BM_SETCHECK, + SendDlgItemMessage (hwndDlg, IDC_COPY_EXPANDER, BM_SETCHECK, BST_CHECKED, 0); - SendDlgItemMessage (hwndDlg, IDC_TRAVEL_OPEN_EXPLORER, BM_SETCHECK, + SendDlgItemMessage (hwndDlg, IDC_TRAVEL_OPEN_EXPLORER, BM_SETCHECK, BST_CHECKED, 0); - SendDlgItemMessage (hwndDlg, IDC_AUTORUN_DISABLE, BM_SETCHECK, + SendDlgItemMessage (hwndDlg, IDC_AUTORUN_DISABLE, BM_SETCHECK, BST_CHECKED, 0); SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_RESETCONTENT, 0, 0); @@ -4086,7 +4086,7 @@ BOOL CALLBACK TravelerDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa index = (int) SendDlgItemMessageW (hwndDlg, IDC_DRIVELIST, CB_ADDSTRING, 0, (LPARAM) drive); SendDlgItemMessageW (hwndDlg, IDC_DRIVELIST, CB_SETITEMDATA, index, (LPARAM) i); } - + SendDlgItemMessageW (hwndDlg, IDC_DRIVELIST, CB_SETCURSEL, 0, 0); return 0; @@ -4112,7 +4112,7 @@ BOOL CALLBACK TravelerDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa && (lw == IDC_AUTORUN_DISABLE || lw == IDC_AUTORUN_MOUNT || lw == IDC_AUTORUN_START )) { BOOL enabled = IsButtonChecked (GetDlgItem (hwndDlg, IDC_AUTORUN_MOUNT)); - + EnableWindow (GetDlgItem (hwndDlg, IDC_BROWSE_FILES), enabled); EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_NAME), enabled); EnableWindow (GetDlgItem (hwndDlg, IDC_TRAVEL_OPEN_EXPLORER), enabled); @@ -4179,7 +4179,7 @@ BOOL CALLBACK TravelerDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa GetDlgItemTextW (hwndDlg, IDC_DIRECTORY, dstDir, array_capacity (dstDir)); volName[0] = 0; GetDlgItemTextW (hwndDlg, IDC_VOLUME_NAME, volName + 1, (array_capacity (volName)) - 1); - + drive = (int) SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_GETCURSEL, 0, 0); drive = (int) SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_GETITEMDATA, drive, 0); @@ -4199,7 +4199,7 @@ BOOL CALLBACK TravelerDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa return 1; } - + if (bAutoMount && volName[1] == 0) { SetFocus (GetDlgItem (hwndDlg, IDC_VOLUME_NAME)); @@ -4392,34 +4392,34 @@ void BuildTree (HWND hwndDlg, HWND hTree) SendMessage(hTree,LVM_SETEXTENDEDLISTVIEWSTYLE,0, LVS_EX_FULLROWSELECT - |LVS_EX_HEADERDRAGDROP - ); + |LVS_EX_HEADERDRAGDROP + ); - memset(&lvCol,0,sizeof(lvCol)); + memset(&lvCol,0,sizeof(lvCol)); - lvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; - lvCol.pszText = GetString ("DRIVE"); + lvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT; + lvCol.pszText = GetString ("DRIVE"); lvCol.cx = CompensateXDPI (38); lvCol.fmt = LVCFMT_COL_HAS_IMAGES|LVCFMT_LEFT ; SendMessage (hTree,LVM_INSERTCOLUMNW,0,(LPARAM)&lvCol); - lvCol.pszText = GetString ("VOLUME"); - lvCol.cx = CompensateXDPI (200); + lvCol.pszText = GetString ("VOLUME"); + lvCol.cx = CompensateXDPI (200); lvCol.fmt = LVCFMT_LEFT; SendMessage (hTree,LVM_INSERTCOLUMNW,1,(LPARAM)&lvCol); LastDriveListVolumeColumnWidth = ListView_GetColumnWidth (hTree, 1); - lvCol.pszText = GetString ("SIZE"); + lvCol.pszText = GetString ("SIZE"); lvCol.cx = CompensateXDPI (55); lvCol.fmt = LVCFMT_RIGHT; SendMessage (hTree,LVM_INSERTCOLUMNW,2,(LPARAM)&lvCol); - lvCol.pszText = GetString ("ENCRYPTION_ALGORITHM_LV"); + lvCol.pszText = GetString ("ENCRYPTION_ALGORITHM_LV"); lvCol.cx = CompensateXDPI (123); lvCol.fmt = LVCFMT_LEFT; SendMessage (hTree,LVM_INSERTCOLUMNW,3,(LPARAM)&lvCol); - lvCol.pszText = GetString ("TYPE"); + lvCol.pszText = GetString ("TYPE"); lvCol.cx = CompensateXDPI (100); lvCol.fmt = LVCFMT_LEFT; SendMessage (hTree,LVM_INSERTCOLUMNW,4,(LPARAM)&lvCol); @@ -4463,7 +4463,7 @@ void BuildTree (HWND hwndDlg, HWND hTree) DeleteObject (hBitmapMask); } - ListView_SetImageList (hTree, hList, LVSIL_NORMAL); + ListView_SetImageList (hTree, hList, LVSIL_NORMAL); ListView_SetImageList (hTree, hList, LVSIL_SMALL); LoadDriveLetters (hwndDlg, hTree, 0); @@ -4516,7 +4516,7 @@ static int AskVolumePassword (HWND hwndDlg, Password *password, int *pkcs5, int dlgParam.pim = pim; dlgParam.truecryptMode = truecryptMode; - result = DialogBoxParamW (hInst, + result = DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_PASSWORD_DLG), hwndDlg, (DLGPROC) PasswordDlgProc, (LPARAM) &dlgParam); @@ -4546,7 +4546,7 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim) BOOL bEffectiveTryEmptyPasswordWhenKeyfileUsed = bCmdTryEmptyPasswordWhenKeyfileUsedValid? bCmdTryEmptyPasswordWhenKeyfileUsed : bTryEmptyPasswordWhenKeyfileUsed; BOOL bUseCmdVolumePassword = CmdVolumePasswordValid && ((CmdVolumePassword.Length > 0) || (KeyFilesEnable && FirstKeyFile)); - /* Priority is given to command line parameters + /* Priority is given to command line parameters * Default values used only when nothing specified in command line */ if (EffectiveVolumePkcs5 == 0) @@ -4616,7 +4616,7 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim) mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, 0, 0, TRUE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); if (!mounted) mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, 0, EffectiveVolumePim, FALSE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); - + // If keyfiles are enabled, test empty password first if (!mounted && KeyFilesEnable && FirstKeyFile && bEffectiveTryEmptyPasswordWhenKeyfileUsed) { @@ -4629,7 +4629,7 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim) mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &emptyPassword, 0, 0, TRUE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); if (!mounted) mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &emptyPassword, 0, EffectiveVolumePim, FALSE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); - + burn (&emptyPassword, sizeof (emptyPassword)); } } @@ -4655,7 +4655,7 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim) } while (mounted == 0) - { + { if (bUseCmdVolumePassword) { VolumePassword = CmdVolumePassword; @@ -4682,7 +4682,7 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim) burn (&GuiPim, sizeof(GuiPim)); } } - + WaitCursor (); if (KeyFilesEnable) @@ -4720,7 +4720,7 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim) RefreshMainDlg(MainDlg); if (bExplore) - { + { WaitCursor(); OpenVolumeExplorerWindow (nDosDriveNo); NormalCursor(); @@ -4791,7 +4791,7 @@ void __cdecl mountThreadFunction (void *hwndDlgArg) EnableWindow(hwndDlg, FALSE); finally_do_arg2 (HWND, hwndDlg, BOOL, bIsForeground, { EnableWindow(finally_arg, TRUE); if (finally_arg2) BringToForeground (finally_arg); bPrebootPasswordDlgMode = FALSE;}); - Mount (hwndDlg, -1, 0, -1); + Mount (hwndDlg, -1, 0, -1); } typedef struct @@ -4820,7 +4820,7 @@ void CALLBACK DismountAllThreadProc(void* pArg, HWND hwndDlg) *pbResult = DeviceIoControl (hDriver, TC_IOCTL_DISMOUNT_ALL_VOLUMES, punmount, sizeof (UNMOUNT_STRUCT), punmount, sizeof (UNMOUNT_STRUCT), pdwResult, NULL); - if ( punmount->nDosDriveNo < 0 || punmount->nDosDriveNo > 25 + if ( punmount->nDosDriveNo < 0 || punmount->nDosDriveNo > 25 || (punmount->ignoreOpenFiles != TRUE && punmount->ignoreOpenFiles != FALSE) || (punmount->HiddenVolumeProtectionTriggered != TRUE && punmount->HiddenVolumeProtectionTriggered != FALSE) || (punmount->nReturnCode < 0) @@ -4849,7 +4849,7 @@ void CALLBACK DismountAllThreadProc(void* pArg, HWND hwndDlg) wchar_t msg[4096]; VolumeNotificationsList.bHidVolDamagePrevReported [punmount->nDosDriveNo] = TRUE; - + StringCbPrintfW (msg, sizeof(msg), GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), punmount->nDosDriveNo + L'A'); SetForegroundWindow (hwndDlg); MessageBoxW (hwndDlg, msg, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); @@ -4906,7 +4906,7 @@ retry: unmount.nDosDriveNo = 0; unmount.ignoreOpenFiles = forceUnmount; - + dismountAllThreadParam.punmount = &unmount; dismountAllThreadParam.interact = interact; dismountAllThreadParam.dismountMaxRetries = dismountMaxRetries; @@ -4919,7 +4919,7 @@ retry: if (interact && !Silent) { - ShowWaitDialog (hwndDlg, FALSE, DismountAllThreadProc, &dismountAllThreadParam); + ShowWaitDialog (hwndDlg, FALSE, DismountAllThreadProc, &dismountAllThreadParam); } else DismountAllThreadProc (&dismountAllThreadParam, hwndDlg); @@ -4980,7 +4980,7 @@ retry: return FALSE; } - + if (interact) MessageBoxW (hwndDlg, GetString ("UNMOUNT_FAILED"), lpszTitle, MB_ICONERROR); } @@ -5003,7 +5003,7 @@ static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) int EffectiveVolumePkcs5 = CmdVolumePkcs5; BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; - /* Priority is given to command line parameters + /* Priority is given to command line parameters * Default values used only when nothing specified in command line */ if (EffectiveVolumePkcs5 == 0) @@ -5016,7 +5016,7 @@ static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) bPrebootPasswordDlgMode = FALSE; VolumePim = -1; - if (selDrive == -1) + if (selDrive == -1) selDrive = 0; ResetWrongPwdRetryCount (); @@ -5087,7 +5087,7 @@ static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) continue; if (!mounted) - { + { int nDosDriveNo; int driveAItem = -1, driveBItem = -1; @@ -5104,7 +5104,7 @@ static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) if (nDosDriveNo == 0) { driveAItem = selDrive; - selDrive++; + selDrive++; continue; } if (nDosDriveNo == 1) @@ -5148,7 +5148,7 @@ static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) selDrive++; if (bExplore) - { + { WaitCursor(); OpenVolumeExplorerWindow (nDosDriveNo); NormalCursor(); @@ -5231,7 +5231,7 @@ static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) if (mountOptions.ProtectHiddenVolume) { - if (mountedVolCount > 1) + if (mountedVolCount > 1) Info ("HIDVOL_PROT_WARN_AFTER_MOUNT_PLURAL", hwndDlg); else if (mountedVolCount == 1) Info ("HIDVOL_PROT_WARN_AFTER_MOUNT", hwndDlg); @@ -5274,7 +5274,7 @@ void CALLBACK mountAllDevicesThreadProc(void* pArg, HWND hwndDlg) { MountAllDevicesThreadParam* threadParam =(MountAllDevicesThreadParam*) pArg; BOOL bPasswordPrompt = threadParam->bPasswordPrompt; - + threadParam->bRet = MountAllDevicesThreadCode (hwndDlg, bPasswordPrompt); } @@ -5293,7 +5293,7 @@ static void ChangePassword (HWND hwndDlg) { INT_PTR result; int newPimValue = -1; - + GetVolumePath (hwndDlg, szFileName, ARRAYSIZE (szFileName)); if (!TranslateVolumeID (hwndDlg, szFileName, ARRAYSIZE (szFileName))) @@ -5360,7 +5360,7 @@ static void ChangePassword (HWND hwndDlg) { bFavoriteFound = true; favorite->Pim = newPimValue; - + if (AskYesNo("FAVORITE_PIM_CHANGED", hwndDlg) == IDYES) { SaveFavoriteVolumes (hwndDlg, SystemFavoriteVolumes, true); @@ -5387,7 +5387,7 @@ static void ChangeSysEncPassword (HWND hwndDlg, BOOL bOnlyChangeKDF) e.Show (MainDlg); } - if (!BootEncStatus.DriveEncrypted + if (!BootEncStatus.DriveEncrypted && !BootEncStatus.DriveMounted && !BootEncStatus.VolumeHeaderPresent && !SysEncryptionOrDecryptionRequired ()) @@ -5396,7 +5396,7 @@ static void ChangeSysEncPassword (HWND hwndDlg, BOOL bOnlyChangeKDF) return; } - if (SysEncryptionOrDecryptionRequired () + if (SysEncryptionOrDecryptionRequired () || BootEncStatus.SetupInProgress) { Warning ("SYSTEM_ENCRYPTION_NOT_COMPLETED", hwndDlg); @@ -5422,7 +5422,7 @@ static void ChangeSysEncPassword (HWND hwndDlg, BOOL bOnlyChangeKDF) if (bKeyboardLayoutChanged) { // Restore the original keyboard layout - if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) + if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg); else bKeyboardLayoutChanged = FALSE; @@ -5480,7 +5480,7 @@ static void EncryptSystemDevice (HWND hwndDlg) e.Show (MainDlg); } - if (!BootEncStatus.DriveEncrypted + if (!BootEncStatus.DriveEncrypted && !BootEncStatus.DriveMounted && !SysEncryptionOrDecryptionRequired ()) { @@ -5527,7 +5527,7 @@ static void DecryptSystemDevice (HWND hwndDlg) e.Show (MainDlg); } - if (!BootEncStatus.DriveEncrypted + if (!BootEncStatus.DriveEncrypted && !BootEncStatus.DriveMounted && !BootEncStatus.DeviceFilterActive && !BootEncStatus.VolumeHeaderPresent @@ -5576,12 +5576,12 @@ static void DecryptSystemDevice (HWND hwndDlg) if (BootEncStatus.SetupInProgress) { - CloseSysEncMutex (); + CloseSysEncMutex (); Error ("SYS_ENCRYPTION_OR_DECRYPTION_IN_PROGRESS", hwndDlg); return; } - CloseSysEncMutex (); + CloseSysEncMutex (); LaunchVolCreationWizard (hwndDlg, L"/dsysenc"); } else @@ -5695,13 +5695,13 @@ static void DecryptNonSysDevice (HWND hwndDlg, BOOL bResolveAmbiguousSelection, // We allow the user to continue as we don't know if the drive is really an encrypted system drive. // If it is, the user has been warned and he will not be able to start decrypting, because the - // format wizard will not enable (nor will it allow the user to enable) the mount option for + // format wizard will not enable (nor will it allow the user to enable) the mount option for // external without-PBA access (the user will receive the 'Incorrect password' error message). } NormalCursor (); - + if (AskNoYesString ((wstring (GetString ("CONFIRM_DECRYPT_NON_SYS_DEVICE")) + L"\n\n" + scPath).c_str(), hwndDlg) == IDNO) return; @@ -5740,7 +5740,7 @@ void CreateRescueDisk (HWND hwndDlg) return; } - if (!BootEncStatus.DriveEncrypted + if (!BootEncStatus.DriveEncrypted && !BootEncStatus.DriveMounted && !BootEncStatus.VolumeHeaderPresent && !SysEncryptionOrDecryptionRequired ()) @@ -5749,7 +5749,7 @@ void CreateRescueDisk (HWND hwndDlg) return; } - if (SysEncryptionOrDecryptionRequired () + if (SysEncryptionOrDecryptionRequired () || BootEncStatus.SetupInProgress) { Warning ("SYSTEM_ENCRYPTION_NOT_COMPLETED", hwndDlg); @@ -5764,7 +5764,7 @@ void CreateRescueDisk (HWND hwndDlg) wchar_t szRescueDiskISO [TC_MAX_PATH+1]; if (AskOkCancel ("RESCUE_DISK_NON_WIZARD_CREATION_SELECT_PATH", hwndDlg) != IDOK) - { + { CloseSysEncMutex (); return; } @@ -5773,7 +5773,7 @@ void CreateRescueDisk (HWND hwndDlg) SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, 0, initialDir); if (!BrowseFilesInDir (hwndDlg, "OPEN_TITLE", initialDir, szRescueDiskISO, FALSE, TRUE, NULL, L"VeraCrypt Rescue Disk.iso", L"iso")) - { + { CloseSysEncMutex (); return; } @@ -5817,7 +5817,7 @@ static void VerifyRescueDisk (HWND hwndDlg, bool checkIsoFile) e.Show (MainDlg); } - if (!BootEncStatus.DriveEncrypted + if (!BootEncStatus.DriveEncrypted && !BootEncStatus.DriveMounted && !BootEncStatus.VolumeHeaderPresent && !SysEncryptionOrDecryptionRequired ()) @@ -5826,7 +5826,7 @@ static void VerifyRescueDisk (HWND hwndDlg, bool checkIsoFile) return; } - if (SysEncryptionOrDecryptionRequired () + if (SysEncryptionOrDecryptionRequired () || BootEncStatus.SetupInProgress) { Warning ("SYSTEM_ENCRYPTION_NOT_COMPLETED", hwndDlg); @@ -5838,7 +5838,7 @@ static void VerifyRescueDisk (HWND hwndDlg, bool checkIsoFile) try { if (!checkIsoFile && (AskOkCancel ("RESCUE_DISK_NON_WIZARD_CHECK_INSERT", hwndDlg) != IDOK)) - { + { CloseSysEncMutex (); return; } @@ -5846,7 +5846,7 @@ static void VerifyRescueDisk (HWND hwndDlg, bool checkIsoFile) // Create a temporary up-to-date rescue disk image in RAM (with it the CD/DVD content will be compared) BootEncObj->CreateRescueIsoImage (false, L""); - + if (checkIsoFile) { wchar_t szRescueDiskISO [TC_MAX_PATH+1]; @@ -5854,7 +5854,7 @@ static void VerifyRescueDisk (HWND hwndDlg, bool checkIsoFile) SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, 0, initialDir); if (!BrowseFilesInDir (hwndDlg, "OPEN_TITLE", initialDir, szRescueDiskISO, FALSE, FALSE, NULL, L"VeraCrypt Rescue Disk.iso", L"iso")) - { + { CloseSysEncMutex (); return; } @@ -5863,7 +5863,7 @@ static void VerifyRescueDisk (HWND hwndDlg, bool checkIsoFile) if (!BootEncObj->VerifyRescueDiskIsoImage (szRescueDiskISO)) Error ("RESCUE_DISK_ISO_IMAGE_CHECK_FAILED", hwndDlg); else - Info ("RESCUE_DISK_ISO_IMAGE_CHECK_PASSED", hwndDlg); + Info ("RESCUE_DISK_ISO_IMAGE_CHECK_PASSED", hwndDlg); } else { @@ -5927,7 +5927,7 @@ static void ShowSystemEncryptionStatus (HWND hwndDlg) return; } - DialogBoxParamW (hInst, + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_VOLUME_PROPERTIES), hwndDlg, (DLGPROC) VolumePropertiesDlgProc, (LPARAM) TRUE); @@ -5935,7 +5935,7 @@ static void ShowSystemEncryptionStatus (HWND hwndDlg) static void ResumeInterruptedNonSysInplaceEncProcess (BOOL bDecrypt) { - // IMPORTANT: This function must not check any config files! Otherwise, if a config file was lost or corrupt, + // IMPORTANT: This function must not check any config files! Otherwise, if a config file was lost or corrupt, // the user would not be able resume encryption and the data on the volume would be inaccessible. LaunchVolCreationWizard (MainDlg, bDecrypt? L"/resumeinplacedec" : L"/zinplace"); @@ -6067,14 +6067,14 @@ static BOOL CheckMountList (HWND hwndDlg, BOOL bForceTaskBarUpdate) } else { - // System partition + // System partition driveLetterToRefresh = GetSystemDriveLetter (); } } else { // Full rebuild of the mount list - driveLetterToRefresh = 0; + driveLetterToRefresh = 0; } selDrive = (wchar_t) HIWORD (GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST))); @@ -6136,9 +6136,9 @@ static BOOL CheckMountList (HWND hwndDlg, BOOL bForceTaskBarUpdate) if (ConfigBuffer == NULL) { // We need to load the config file because it is not done automatically when - // launched from the sys startup sequence (and SaveSettings would start by _loading_ + // launched from the sys startup sequence (and SaveSettings would start by _loading_ // the settings to cache). - LoadSettings (MainDlg); + LoadSettings (MainDlg); } HiddenSysLeakProtectionNotificationStatus = TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_DISABLED; SaveSettings (MainDlg); @@ -6170,9 +6170,9 @@ static BOOL CheckMountList (HWND hwndDlg, BOOL bForceTaskBarUpdate) if (ConfigBuffer == NULL) { // We need to load the config file because it is not done automatically when - // launched from the sys startup sequence (and SaveSettings would start by _loading_ + // launched from the sys startup sequence (and SaveSettings would start by _loading_ // the settings to cache). - LoadSettings (MainDlg); + LoadSettings (MainDlg); } HiddenSysLeakProtectionNotificationStatus = TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_COMPACT; SaveSettings (MainDlg); @@ -6314,7 +6314,7 @@ void DisplayDriveListContextMenu (HWND hwndDlg, LPARAM lParam) break; case IDM_VOLUME_PROPERTIES: - DialogBoxParamW (hInst, + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_VOLUME_PROPERTIES), hwndDlg, (DLGPROC) VolumePropertiesDlgProc, (LPARAM) FALSE); break; @@ -6444,7 +6444,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa && !BootEncObj->CheckBootloaderFingerprint ()) Warning ("BOOT_LOADER_FINGERPRINT_CHECK_FAILED", hwndDlg); } - } + } catch (...) { } // Automount @@ -6499,7 +6499,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa } else { - /* Priority is given to command line parameters + /* Priority is given to command line parameters * Default values used only when nothing specified in command line */ if (EffectiveVolumePkcs5 == 0) @@ -6581,10 +6581,10 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (mounted > 0) { - if (bBeep) + if (bBeep) MessageBeep (0xFFFFFFFF); - if (bExplore) + if (bExplore) OpenVolumeExplorerWindow (szDriveLetter[0] - L'A'); RefreshMainDlg(hwndDlg); @@ -6603,11 +6603,11 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa OpenVolumeExplorerWindow (GetMountedVolumeDriveNo (szFileName)); else if (szFileName[0] != 0 && IsMountedVolume (szFileName)) Warning ("VOL_ALREADY_MOUNTED", hwndDlg); - + if (!Quit) RefreshMainDlg(hwndDlg); } - + // Wipe cache if (bWipe) WipeCache (hwndDlg, Silent); @@ -6720,7 +6720,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa Silent = FALSE; GetMountList (&LastKnownMountList); - SetTimer (hwndDlg, TIMER_ID_MAIN, TIMER_INTERVAL_MAIN, NULL); + SetTimer (hwndDlg, TIMER_ID_MAIN, TIMER_INTERVAL_MAIN, NULL); taskBarCreatedMsg = RegisterWindowMessage (L"TaskbarCreated"); @@ -6764,7 +6764,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa ResetCurrentDirectory (); } return 0; - + case WM_MOUSEWHEEL: return HandleDriveListMouseWheelEvent (uMsg, wParam, lParam, FALSE); @@ -6773,9 +6773,9 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa HWND hList = GetDlgItem (hwndDlg, IDC_DRIVELIST); // only handle if it is coming from keyboard and if the drive // list has focus. The other cases are handled elsewhere - if ( (-1 == GET_X_LPARAM(lParam)) + if ( (-1 == GET_X_LPARAM(lParam)) && (-1 == GET_Y_LPARAM(lParam)) - && (GetFocus () == hList) + && (GetFocus () == hList) ) { INT item = ListView_GetSelectionMark (hList); @@ -6823,7 +6823,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); SecurityToken::CloseAllSessions(); } - + DismountAll (hwndDlg, bForceAutoDismount, TRUE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); } } @@ -6839,7 +6839,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (bWipeCacheOnAutoDismount) DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - + DismountAll (hwndDlg, bForceAutoDismount, FALSE, 1, 0); } @@ -7049,7 +7049,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (LastKnownMountList.ulMountedDrives == 0 && MainWindowHidden #ifndef _DEBUG - && (bCloseBkgTaskWhenNoVolumes || IsNonInstallMode ()) + && (bCloseBkgTaskWhenNoVolumes || IsNonInstallMode ()) && !SysEncDeviceActive (TRUE) #endif && GetDriverRefCount () < 2) @@ -7077,7 +7077,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa POINT pos; HMENU popup = CreatePopupMenu (); int sel, i, n; - + if (MainWindowHidden) { AppendMenuW (popup, MF_STRING, IDM_SHOW_HIDE, GetString ("SHOW_TC")); @@ -7085,7 +7085,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa } else if (bEnableBkgTask && (!(LastKnownMountList.ulMountedDrives == 0 - && (bCloseBkgTaskWhenNoVolumes || IsNonInstallMode ()) + && (bCloseBkgTaskWhenNoVolumes || IsNonInstallMode ()) && !SysEncDeviceActive (TRUE) && GetDriverRefCount () < 2))) { @@ -7116,7 +7116,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa StringCbPrintfW (s, sizeof(s), L"%s %c: (%s)", GetString (n==0 ? "OPEN" : "DISMOUNT"), - i + L'A', + i + L'A', label.empty() ? vol : label.c_str()); AppendMenuW (popup, MF_STRING, n*26 + TRAYICON_MENU_DRIVE_OFFSET + i, s); } @@ -7155,7 +7155,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (Dismount (hwndDlg, sel - TRAYICON_MENU_DRIVE_OFFSET - 26)) { wchar_t txt [2048]; - StringCbPrintfW (txt, sizeof(txt), GetString ("VOLUME_MOUNTED_AS_DRIVE_LETTER_X_DISMOUNTED"), sel - TRAYICON_MENU_DRIVE_OFFSET - 26 + L'A'); + StringCbPrintfW (txt, sizeof(txt), GetString ("VOLUME_MOUNTED_AS_DRIVE_LETTER_X_DISMOUNTED"), sel - TRAYICON_MENU_DRIVE_OFFSET - 26 + L'A'); InfoBalloonDirect (GetString ("SUCCESSFULLY_DISMOUNTED"), txt, hwndDlg); } @@ -7207,7 +7207,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa case TC_APPMSG_SYSENC_CONFIG_UPDATE: LoadSysEncSettings (); - // The wizard added VeraCrypt.exe to the system startup sequence or performed other operations that + // The wizard added VeraCrypt.exe to the system startup sequence or performed other operations that // require us to update our cached settings. LoadSettings (hwndDlg); @@ -7324,7 +7324,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (GetAsyncKeyState (VK_CONTROL) < 0) { - /* Priority is given to command line parameters + /* Priority is given to command line parameters * Default values used only when nothing specified in command line */ if (CmdVolumePkcs5 == 0) @@ -7333,7 +7333,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa mountOptions.ProtectedHidVolPkcs5Prf = CmdVolumePkcs5; mountOptions.ProtectedHidVolPim = CmdVolumePim; - if (IDCANCEL == DialogBoxParamW (hInst, + if (IDCANCEL == DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions)) return 1; @@ -7362,7 +7362,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa not open, because drag&drop operation would be initiated. Therefore, we're handling RMB drag-and-drop operations as well. */ { - + DisplayDriveListContextMenu (hwndDlg, lParam); return 1; @@ -7408,7 +7408,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa return 1; } - if ((lw == IDOK || lw == IDM_MOUNT_VOLUME || lw == IDM_MOUNT_VOLUME_OPTIONS || lw == IDC_MOUNTALL || lw == IDM_MOUNTALL) + if ((lw == IDOK || lw == IDM_MOUNT_VOLUME || lw == IDM_MOUNT_VOLUME_OPTIONS || lw == IDC_MOUNTALL || lw == IDM_MOUNTALL) && LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) == 0xffff) { MessageBoxW (hwndDlg, GetString ("SELECT_FREE_DRIVE"), L"VeraCrypt", MB_ICONEXCLAMATION); @@ -7438,7 +7438,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa MountAllDevices (hwndDlg, !(GetAsyncKeyState (VK_SHIFT) < 0 && !IsPasswordCacheEmpty())); return 1; } - + if (lw == IDC_SELECT_FILE || lw == IDM_SELECT_FILE) { SelectContainer (hwndDlg); @@ -7493,7 +7493,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa bPrebootPasswordDlgMode = TRUE; if (CheckMountList (hwndDlg, FALSE)) - _beginthread(mountThreadFunction, 0, hwndDlg); + _beginthread(mountThreadFunction, 0, hwndDlg); } break; } @@ -7756,7 +7756,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa Warning ("NO_VOLUME_SELECTED", hwndDlg); } else - { + { pwdChangeDlgMode = PCDM_REMOVE_ALL_KEYFILES_FROM_VOL; ChangePassword (hwndDlg); } @@ -7785,7 +7785,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (lw == IDM_KEYFILE_GENERATOR) { - DialogBoxParamW (hInst, + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_KEYFILE_GENERATOR), hwndDlg, (DLGPROC) KeyfileGeneratorDlgProc, (LPARAM) 0); @@ -7803,7 +7803,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa TextInfoDialogBox (TC_TBXID_LEGAL_NOTICES); return 1; } - + if (lw == IDM_WEBSITE) { Applink ("website", TRUE, ""); @@ -7852,7 +7852,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (lw == IDM_PREFERENCES) { - if (IDOK == DialogBoxParamW (hInst, + if (IDOK == DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_PREFERENCES_DLG), hwndDlg, (DLGPROC) PreferencesDlgProc, (LPARAM) 0)) { @@ -7874,7 +7874,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (lw == IDM_HOTKEY_SETTINGS) { - DialogBoxParamW (hInst, + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_HOTKEYS_DLG), hwndDlg, (DLGPROC) HotkeysDlgProc, (LPARAM) 0); return 1; @@ -7904,7 +7904,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa wchar_t volPathLower[TC_MAX_PATH]; - // volPathLower will contain the volume path (if any) from the input field below the drive list + // volPathLower will contain the volume path (if any) from the input field below the drive list GetVolumePath (hwndDlg, volPathLower, ARRAYSIZE (volPathLower)); if (LOWORD (selectedDrive) != TC_MLIST_ITEM_NONSYS_VOL @@ -8033,7 +8033,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (lw == IDM_TRAVELER) { - DialogBoxParamW (hInst, + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TRAVELER_DLG), hwndDlg, (DLGPROC) TravelerDlgProc, (LPARAM) 0); return 1; @@ -8122,7 +8122,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (lw == IDM_REFRESH_DRIVE_LETTERS) { DWORD driveMap = GetUsedLogicalDrives (); - + WaitCursor (); if (!(nCurrentOS == WIN_2000 && RemoteSession)) @@ -8178,7 +8178,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (lw == IDC_VOLUME_PROPERTIES || lw == IDM_VOLUME_PROPERTIES) { - DialogBoxParamW (hInst, + DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_VOLUME_PROPERTIES), hwndDlg, (DLGPROC) VolumePropertiesDlgProc, (LPARAM) 0); return 1; @@ -8321,7 +8321,7 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) /* Defaults */ mountOptions.PreserveTimestamp = TRUE; - + if (_wcsicmp (lpszCommandLine, L"-Embedding") == 0) { ComServerMode = TRUE; @@ -8395,7 +8395,7 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) as.args = args; as.arg_cnt = sizeof(args)/ sizeof(args[0]); - + switch (GetArgumentID (&as, lpszCommandLineArgs[i])) { case OptionAuto: @@ -8506,7 +8506,7 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) AbortProcess ("BAD_DRIVE_LETTER"); } - else + else cmdUnmountDrive = -1; break; @@ -8594,7 +8594,7 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) else if (!_wcsicmp (szTmp, L"sm") || !_wcsicmp (szTmp, L"system")) mountOptions.PartitionInInactiveSysEncScope = bPrebootPasswordDlgMode = TRUE; - + else if (!_wcsicmp (szTmp, L"bk") || !_wcsicmp (szTmp, L"headerbak")) mountOptions.UseBackupHeader = TRUE; @@ -8623,14 +8623,14 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) szTmp, ARRAYSIZE (szTmp))) { int iLen = WideCharToMultiByte (CP_UTF8, 0, szTmp, -1, (char*) CmdVolumePassword.Text, MAX_PASSWORD + 1, NULL, NULL); - burn (szTmp, sizeof (szTmp)); + burn (szTmp, sizeof (szTmp)); if (iLen > 0) { CmdVolumePassword.Length = (unsigned __int32) (iLen - 1); CmdVolumePasswordValid = TRUE; } else - AbortProcess ("COMMAND_LINE_ERROR"); + AbortProcess ("COMMAND_LINE_ERROR"); } else AbortProcess ("COMMAND_LINE_ERROR"); @@ -8797,7 +8797,7 @@ static SERVICE_STATUS SystemFavoritesServiceStatus; static SERVICE_STATUS_HANDLE SystemFavoritesServiceStatusHandle; static void SystemFavoritesServiceLogMessage (const wstring &errorMessage, WORD wType) -{ +{ HANDLE eventSource = RegisterEventSource (NULL, TC_SYSTEM_FAVORITES_SERVICE_NAME); if (eventSource) @@ -8810,17 +8810,17 @@ static void SystemFavoritesServiceLogMessage (const wstring &errorMessage, WORD } static void SystemFavoritesServiceLogError (const wstring &errorMessage) -{ +{ SystemFavoritesServiceLogMessage (errorMessage, EVENTLOG_ERROR_TYPE); } static void SystemFavoritesServiceLogWarning (const wstring &warningMessage) -{ +{ SystemFavoritesServiceLogMessage (warningMessage, EVENTLOG_WARNING_TYPE); } static void SystemFavoritesServiceLogInfo (const wstring &infoMessage) -{ +{ SystemFavoritesServiceLogMessage (infoMessage, EVENTLOG_INFORMATION_TYPE); } @@ -8837,7 +8837,7 @@ static void SystemFavoritesServiceSetStatus (DWORD status, DWORD waitHint = 0) static VOID WINAPI SystemFavoritesServiceCtrlHandler (DWORD control) { - if (control == SERVICE_CONTROL_STOP) + if (control == SERVICE_CONTROL_STOP) SystemFavoritesServiceSetStatus (SERVICE_STOP_PENDING); else SystemFavoritesServiceSetStatus (SystemFavoritesServiceStatus.dwCurrentState); @@ -8969,9 +8969,9 @@ int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpsz #endif -BOOL TaskBarIconAdd (HWND hwnd) -{ - NOTIFYICONDATAW tnid; +BOOL TaskBarIconAdd (HWND hwnd) +{ + NOTIFYICONDATAW tnid; ZeroMemory (&tnid, sizeof (tnid)); @@ -8989,36 +8989,36 @@ BOOL TaskBarIconAdd (HWND hwnd) return FALSE; } - tnid.cbSize = sizeof (NOTIFYICONDATAW); - tnid.hWnd = hwnd; - tnid.uID = IDI_TRUECRYPT_ICON; - tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; - tnid.uCallbackMessage = TC_APPMSG_TASKBAR_ICON; - tnid.hIcon = (HICON) LoadImage (hInst, MAKEINTRESOURCE (IDI_TRUECRYPT_ICON), - IMAGE_ICON, - ScreenDPI >= 120 ? 0 : 16, + tnid.cbSize = sizeof (NOTIFYICONDATAW); + tnid.hWnd = hwnd; + tnid.uID = IDI_TRUECRYPT_ICON; + tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; + tnid.uCallbackMessage = TC_APPMSG_TASKBAR_ICON; + tnid.hIcon = (HICON) LoadImage (hInst, MAKEINTRESOURCE (IDI_TRUECRYPT_ICON), + IMAGE_ICON, + ScreenDPI >= 120 ? 0 : 16, ScreenDPI >= 120 ? 0 : 16, - (ScreenDPI >= 120 ? LR_DEFAULTSIZE : 0) + (ScreenDPI >= 120 ? LR_DEFAULTSIZE : 0) | LR_SHARED | (nCurrentOS != WIN_2000 ? LR_DEFAULTCOLOR : LR_VGACOLOR)); // Windows 2000 cannot display more than 16 fixed colors in notification tray StringCbCopyW (tnid.szTip, sizeof(tnid.szTip), L"VeraCrypt"); - return Shell_NotifyIconW (NIM_ADD, &tnid); + return Shell_NotifyIconW (NIM_ADD, &tnid); } -BOOL TaskBarIconRemove (HWND hwnd) -{ +BOOL TaskBarIconRemove (HWND hwnd) +{ if (TaskBarIconMutex != NULL) { - NOTIFYICONDATA tnid; + NOTIFYICONDATA tnid; BOOL res; ZeroMemory (&tnid, sizeof (tnid)); - tnid.cbSize = sizeof(NOTIFYICONDATA); - tnid.hWnd = hwnd; - tnid.uID = IDI_TRUECRYPT_ICON; + tnid.cbSize = sizeof(NOTIFYICONDATA); + tnid.hWnd = hwnd; + tnid.uID = IDI_TRUECRYPT_ICON; res = Shell_NotifyIcon (NIM_DELETE, &tnid); if (TaskBarIconMutex) @@ -9033,28 +9033,28 @@ BOOL TaskBarIconRemove (HWND hwnd) } -BOOL TaskBarIconChange (HWND hwnd, int iconId) -{ +BOOL TaskBarIconChange (HWND hwnd, int iconId) +{ if (TaskBarIconMutex == NULL) return FALSE; - NOTIFYICONDATA tnid; + NOTIFYICONDATA tnid; ZeroMemory (&tnid, sizeof (tnid)); - tnid.cbSize = sizeof (tnid); - tnid.hWnd = hwnd; - tnid.uID = IDI_TRUECRYPT_ICON; - tnid.uFlags = NIF_ICON; - tnid.hIcon = (HICON) LoadImage (hInst, MAKEINTRESOURCE (iconId), - IMAGE_ICON, - ScreenDPI >= 120 ? 0 : 16, + tnid.cbSize = sizeof (tnid); + tnid.hWnd = hwnd; + tnid.uID = IDI_TRUECRYPT_ICON; + tnid.uFlags = NIF_ICON; + tnid.hIcon = (HICON) LoadImage (hInst, MAKEINTRESOURCE (iconId), + IMAGE_ICON, + ScreenDPI >= 120 ? 0 : 16, ScreenDPI >= 120 ? 0 : 16, - (ScreenDPI >= 120 ? LR_DEFAULTSIZE : 0) + (ScreenDPI >= 120 ? LR_DEFAULTSIZE : 0) | LR_SHARED | (nCurrentOS != WIN_2000 ? LR_DEFAULTCOLOR : LR_VGACOLOR)); // Windows 2000 cannot display more than 16 fixed colors in notification tray - return Shell_NotifyIcon (NIM_MODIFY, &tnid); + return Shell_NotifyIcon (NIM_MODIFY, &tnid); } @@ -9072,7 +9072,7 @@ void DismountIdleVolumes () if (GetTickCount() > lastMinTickCount && GetTickCount() - lastMinTickCount < 60 * 1000) return; - + lastMinTickCount = GetTickCount(); for (i = 0; i < 26; i++) @@ -9085,18 +9085,18 @@ void DismountIdleVolumes () bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL); - if ( bResult - && ( (prop.driveNo == i) && prop.uniqueId >= 0 + if ( bResult + && ( (prop.driveNo == i) && prop.uniqueId >= 0 && prop.ea >= EAGetFirst() && prop.ea <= EAGetCount() - && prop.mode >= FIRST_MODE_OF_OPERATION_ID && prop.mode <= LAST_MODE_OF_OPERATION - && prop.pkcs5 >= FIRST_PRF_ID && prop.pkcs5 <= LAST_PRF_ID + && prop.mode >= FIRST_MODE_OF_OPERATION_ID && prop.mode <= LAST_MODE_OF_OPERATION + && prop.pkcs5 >= FIRST_PRF_ID && prop.pkcs5 <= LAST_PRF_ID && prop.pkcs5Iterations > 0 && prop.hiddenVolProtection >= 0 && prop.volFormatVersion >= 0 && prop.volumePim >= 0 ) ) { - if (LastRead[i] == prop.totalBytesRead + if (LastRead[i] == prop.totalBytesRead && LastWritten[i] == prop.totalBytesWritten && LastId[i] == prop.uniqueId) { @@ -9149,7 +9149,7 @@ static BOOL MountFavoriteVolumeBase (HWND hwnd, const FavoriteVolume &favorite, } return FALSE; } - + mountOptions.ReadOnly = favorite.ReadOnly || userForcedReadOnly; mountOptions.Removable = favorite.Removable; if (favorite.UseLabelInExplorer && !favorite.Label.empty()) @@ -9203,7 +9203,7 @@ static BOOL MountFavoriteVolumeBase (HWND hwnd, const FavoriteVolume &favorite, && !favoriteVolumeToMount.Path.empty() && GetAsyncKeyState (VK_CONTROL) < 0) { - /* Priority is given to command line parameters + /* Priority is given to command line parameters * Default values used only when nothing specified in command line */ if (CmdVolumePkcs5 == 0) @@ -9320,7 +9320,7 @@ BOOL MountFavoriteVolumes (HWND hwnd, BOOL systemFavorites, BOOL logOnMount, BOO SystemFavoritesServiceLogInfo (wstring (L"Loaded ") + szTmp + wstring (L" favorites from the file")); /* correct set the connected state of the system favorites */ - for (vector ::iterator favorite = favorites.begin(); + for (vector ::iterator favorite = favorites.begin(); favorite != favorites.end(); favorite++) { if (favorite->UseVolumeID) @@ -9378,7 +9378,7 @@ BOOL MountFavoriteVolumes (HWND hwnd, BOOL systemFavorites, BOOL logOnMount, BOO if (systemFavorites && ServiceMode && !skippedSystemFavorites.empty()) { // Some drives need more time to initialize correctly. - // We retry 4 times after sleeping 5 seconds + // We retry 4 times after sleeping 5 seconds int retryCounter = 0; size_t remainingFavorites = skippedSystemFavorites.size(); while ((remainingFavorites > 0) && (retryCounter++ < 4)) @@ -9391,7 +9391,7 @@ BOOL MountFavoriteVolumes (HWND hwnd, BOOL systemFavorites, BOOL logOnMount, BOO SystemFavoritesServiceStatus.dwCheckPoint++; SystemFavoritesServiceSetStatus (SERVICE_START_PENDING, 120000); - for (vector ::iterator favorite = skippedSystemFavorites.begin(); + for (vector ::iterator favorite = skippedSystemFavorites.begin(); favorite != skippedSystemFavorites.end(); favorite++) { if (favorite->DisconnectedDevice) @@ -9412,7 +9412,7 @@ BOOL MountFavoriteVolumes (HWND hwnd, BOOL systemFavorites, BOOL logOnMount, BOO remainingFavorites--; - // favorite OK. + // favorite OK. if (favorite->UseVolumeID) SystemFavoritesServiceLogInfo (wstring (L"Favorite \"ID:") + ArrayToHexWideString (favorite->VolumeID, sizeof (favorite->VolumeID)) + L"\" is connected. Performing mount."); else @@ -9474,7 +9474,7 @@ static void SaveDefaultKeyFilesParam (HWND hwnd) { if (defaultKeyFilesParam.FirstKeyFile == NULL) { - /* No keyfiles selected */ + /* No keyfiles selected */ _wremove (GetConfigPath (TC_APPD_FILENAME_DEFAULT_KEYFILES)); } else @@ -9498,12 +9498,12 @@ static void SaveDefaultKeyFilesParam (HWND hwnd) wchar_t q[TC_MAX_PATH * 2]; XmlQuoteTextW (kf->FileName, q, ARRAYSIZE (q)); - fwprintf (f, L"\n\t\t%s", q); + fwprintf (f, L"\n\t\t%s", q); kf = kf->Next; } - fputws (L"\n\t", f); + fputws (L"\n\t", f); XmlWriteFooter (f); @@ -9654,7 +9654,7 @@ int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, const wchar_t * int EffectiveVolumePkcs5 = CmdVolumePkcs5; int EffectiveVolumePim = CmdVolumePim; - /* Priority is given to command line parameters + /* Priority is given to command line parameters * Default values used only when nothing specified in command line */ if (EffectiveVolumePkcs5 == 0) @@ -9779,7 +9779,7 @@ noHidden: StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CONFIRM_VOL_HEADER_BAK"), lpszVolume); - if (bRequireConfirmation + if (bRequireConfirmation && (MessageBoxW (hwndDlg, szTmp, lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON1) == IDNO)) goto ret; @@ -9824,7 +9824,7 @@ noHidden: if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (volume.CryptoInfo->ea), TRUE) || !RandgetBytes (hwndDlg, volume.CryptoInfo->k2, sizeof (volume.CryptoInfo->k2), FALSE)) { - nStatus = ERR_PARAMETER_INCORRECT; + nStatus = ERR_PARAMETER_INCORRECT; goto error; } @@ -9889,7 +9889,7 @@ error: burn (&hiddenVolPassword, sizeof (hiddenVolPassword)); burn (temporaryKey, sizeof (temporaryKey)); burn (originalK2, sizeof (originalK2)); - + RestoreDefaultKeyFilesParam(); RandStop (FALSE); NormalCursor(); @@ -9919,7 +9919,7 @@ int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume) int EffectiveVolumePkcs5 = CmdVolumePkcs5; int EffectiveVolumePim = CmdVolumePim; - /* Priority is given to command line parameters + /* Priority is given to command line parameters * Default values used only when nothing specified in command line */ if (EffectiveVolumePkcs5 == 0) @@ -10058,7 +10058,7 @@ int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume) else { // Restore header from an external backup - + StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CONFIRM_VOL_HEADER_RESTORE"), lpszVolume); if (MessageBoxW (hwndDlg, szTmp, lpszTitle, YES_NO|MB_ICONWARNING|MB_DEFBUTTON2) == IDNO) @@ -10433,7 +10433,7 @@ static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM } catch (...) { - BootEncStatus.DriveMounted = false; + BootEncStatus.DriveMounted = false; } if (BootEncStatus.DriveMounted) @@ -10687,7 +10687,7 @@ static BOOL CALLBACK DefaultMountParametersDlgProc (HWND hwndDlg, UINT msg, WPAR { LocalizeDialog (hwndDlg, "IDD_DEFAULT_MOUNT_PARAMETERS"); - SendMessage (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), BM_SETCHECK, + SendMessage (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), BM_SETCHECK, DefaultVolumeTrueCryptMode ? BST_CHECKED:BST_UNCHECKED, 0); /* Populate the PRF algorithms list */ @@ -10711,7 +10711,7 @@ static BOOL CALLBACK DefaultMountParametersDlgProc (HWND hwndDlg, UINT msg, WPAR return 0; } - + case WM_COMMAND: switch (lw) @@ -10725,7 +10725,7 @@ static BOOL CALLBACK DefaultMountParametersDlgProc (HWND hwndDlg, UINT msg, WPAR int pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); BOOL truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); /* SHA-256 is not supported by TrueCrypt */ - if ( (truecryptMode) + if ( (truecryptMode) && (pkcs5 == SHA256) ) { @@ -10738,10 +10738,10 @@ static BOOL CALLBACK DefaultMountParametersDlgProc (HWND hwndDlg, UINT msg, WPAR DefaultVolumePkcs5 = pkcs5; SaveSettings (hwndDlg); - + NormalCursor (); EndDialog (hwndDlg, lw); - } + } return 1; } @@ -10937,7 +10937,7 @@ void MountSelectedVolume (HWND hwndDlg, BOOL mountWithOptions) if (mountWithOptions || GetAsyncKeyState (VK_CONTROL) < 0) { - /* Priority is given to command line parameters + /* Priority is given to command line parameters * Default values used only when nothing specified in command line */ if (CmdVolumePkcs5 == 0) @@ -10945,7 +10945,7 @@ void MountSelectedVolume (HWND hwndDlg, BOOL mountWithOptions) else mountOptions.ProtectedHidVolPkcs5Prf = CmdVolumePkcs5; mountOptions.ProtectedHidVolPim = CmdVolumePim; - if (IDCANCEL == DialogBoxParamW (hInst, + if (IDCANCEL == DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions)) return; @@ -10959,7 +10959,7 @@ void MountSelectedVolume (HWND hwndDlg, BOOL mountWithOptions) } if (CheckMountList (hwndDlg, FALSE)) - _beginthread (mountThreadFunction, 0, hwndDlg); + _beginthread (mountThreadFunction, 0, hwndDlg); } else Warning ("SELECT_FREE_DRIVE", hwndDlg); diff --git a/src/Mount/Mount.h b/src/Mount/Mount.h index 8e6a8e15..3a2a4056 100644 --- a/src/Mount/Mount.h +++ b/src/Mount/Mount.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Mount/Mount.rc b/src/Mount/Mount.rc index 1c45b89c..6aa544fa 100644 --- a/src/Mount/Mount.rc +++ b/src/Mount/Mount.rc @@ -393,7 +393,7 @@ END // #ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO +GUIDELINES DESIGNINFO BEGIN IDD_PREFERENCES_DLG, DIALOG BEGIN @@ -534,19 +534,19 @@ END // TEXTINCLUDE // -1 TEXTINCLUDE +1 TEXTINCLUDE BEGIN "resource.h\0" END -2 TEXTINCLUDE +2 TEXTINCLUDE BEGIN "#include ""afxres.h""\r\n" "#include ""..\\\\common\\\\resource.h""\r\n" "\0" END -3 TEXTINCLUDE +3 TEXTINCLUDE BEGIN "#include ""..\\\\common\\\\common.rc""\r\n" "\0" @@ -572,7 +572,7 @@ IDB_SYS_DRIVEICON_MASK BITMAP "System_drive_icon_mask_96dpi.bm // Menu // -IDR_MENU MENU +IDR_MENU MENU BEGIN POPUP "&Volumes" BEGIN @@ -691,7 +691,7 @@ END // String Table // -STRINGTABLE +STRINGTABLE BEGIN IDS_UACSTRING "VeraCrypt" END diff --git a/src/Mount/Resource.h b/src/Mount/Resource.h index fee7905b..3d93d81f 100644 --- a/src/Mount/Resource.h +++ b/src/Mount/Resource.h @@ -251,7 +251,7 @@ #define IDM_VERIFY_RESCUE_DISK_ISO 40068 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 diff --git a/src/PKCS11/cryptoki.h b/src/PKCS11/cryptoki.h index f457b3e9..821d73a7 100644 --- a/src/PKCS11/cryptoki.h +++ b/src/PKCS11/cryptoki.h @@ -7,10 +7,10 @@ * License is also granted to make and use derivative works provided that * such works are identified as "derived from the RSA Security Inc. PKCS #11 - * Cryptographic Token Interface (Cryptoki)" in all material mentioning or + * Cryptographic Token Interface (Cryptoki)" in all material mentioning or * referencing the derived work. - * RSA Security Inc. makes no representations concerning either the + * RSA Security Inc. makes no representations concerning either the * merchantability of this software or the suitability of this software for * any particular purpose. It is provided "as is" without express or implied * warranty of any kind. @@ -33,9 +33,9 @@ */ #ifdef CRYPTOKI_EXPORTS /* Specified that the function is an exported DLL entry point. */ -#define CK_EXPORT_SPEC __declspec(dllexport) +#define CK_EXPORT_SPEC __declspec(dllexport) #else -#define CK_EXPORT_SPEC CK_IMPORT_SPEC +#define CK_EXPORT_SPEC CK_IMPORT_SPEC #endif /* Ensures the calling convention for Win32 builds */ diff --git a/src/PKCS11/pkcs11.h b/src/PKCS11/pkcs11.h index 6c612204..37b59030 100644 --- a/src/PKCS11/pkcs11.h +++ b/src/PKCS11/pkcs11.h @@ -7,10 +7,10 @@ * License is also granted to make and use derivative works provided that * such works are identified as "derived from the RSA Security Inc. PKCS #11 - * Cryptographic Token Interface (Cryptoki)" in all material mentioning or + * Cryptographic Token Interface (Cryptoki)" in all material mentioning or * referencing the derived work. - * RSA Security Inc. makes no representations concerning either the + * RSA Security Inc. makes no representations concerning either the * merchantability of this software or the suitability of this software for * any particular purpose. It is provided "as is" without express or implied * warranty of any kind. @@ -275,7 +275,7 @@ extern "C" { #define CK_PKCS11_FUNCTION_INFO(name) \ __PASTE(CK_,name) name; - + struct CK_FUNCTION_LIST { CK_VERSION version; /* Cryptoki version */ diff --git a/src/PKCS11/pkcs11f.h b/src/PKCS11/pkcs11f.h index a479384e..bbd957bc 100644 --- a/src/PKCS11/pkcs11f.h +++ b/src/PKCS11/pkcs11f.h @@ -7,10 +7,10 @@ * License is also granted to make and use derivative works provided that * such works are identified as "derived from the RSA Security Inc. PKCS #11 - * Cryptographic Token Interface (Cryptoki)" in all material mentioning or + * Cryptographic Token Interface (Cryptoki)" in all material mentioning or * referencing the derived work. - * RSA Security Inc. makes no representations concerning either the + * RSA Security Inc. makes no representations concerning either the * merchantability of this software or the suitability of this software for * any particular purpose. It is provided "as is" without express or implied * warranty of any kind. @@ -564,7 +564,7 @@ CK_PKCS11_FUNCTION_INFO(C_Sign) /* C_SignUpdate continues a multiple-part signature operation, - * where the signature is (will be) an appendix to the data, + * where the signature is (will be) an appendix to the data, * and plaintext cannot be recovered from the signature. */ CK_PKCS11_FUNCTION_INFO(C_SignUpdate) #ifdef CK_NEED_ARG_LIST @@ -576,7 +576,7 @@ CK_PKCS11_FUNCTION_INFO(C_SignUpdate) #endif -/* C_SignFinal finishes a multiple-part signature operation, +/* C_SignFinal finishes a multiple-part signature operation, * returning the signature. */ CK_PKCS11_FUNCTION_INFO(C_SignFinal) #ifdef CK_NEED_ARG_LIST @@ -625,12 +625,12 @@ CK_PKCS11_FUNCTION_INFO(C_VerifyInit) ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_MECHANISM_PTR pMechanism, /* the verification mechanism */ - CK_OBJECT_HANDLE hKey /* verification key */ + CK_OBJECT_HANDLE hKey /* verification key */ ); #endif -/* C_Verify verifies a signature in a single-part operation, +/* C_Verify verifies a signature in a single-part operation, * where the signature is an appendix to the data, and plaintext * cannot be recovered from the signature. */ CK_PKCS11_FUNCTION_INFO(C_Verify) @@ -646,7 +646,7 @@ CK_PKCS11_FUNCTION_INFO(C_Verify) /* C_VerifyUpdate continues a multiple-part verification - * operation, where the signature is an appendix to the data, + * operation, where the signature is an appendix to the data, * and plaintext cannot be recovered from the signature. */ CK_PKCS11_FUNCTION_INFO(C_VerifyUpdate) #ifdef CK_NEED_ARG_LIST @@ -772,7 +772,7 @@ CK_PKCS11_FUNCTION_INFO(C_GenerateKey) #endif -/* C_GenerateKeyPair generates a public-key/private-key pair, +/* C_GenerateKeyPair generates a public-key/private-key pair, * creating new key objects. */ CK_PKCS11_FUNCTION_INFO(C_GenerateKeyPair) #ifdef CK_NEED_ARG_LIST diff --git a/src/Platform/Buffer.cpp b/src/Platform/Buffer.cpp index 2d2a9217..4948a875 100644 --- a/src/Platform/Buffer.cpp +++ b/src/Platform/Buffer.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -92,7 +92,7 @@ namespace VeraCrypt return BufferPtr (DataPtr + offset, size); } - + void Buffer::Zero () { if (DataSize > 0) diff --git a/src/Platform/Buffer.h b/src/Platform/Buffer.h index 3d2d5f53..b47907b3 100644 --- a/src/Platform/Buffer.h +++ b/src/Platform/Buffer.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Directory.h b/src/Platform/Directory.h index 574be3b2..89b91ad3 100644 --- a/src/Platform/Directory.h +++ b/src/Platform/Directory.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Event.cpp b/src/Platform/Event.cpp index d6e51182..bfa0da7c 100644 --- a/src/Platform/Event.cpp +++ b/src/Platform/Event.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -19,7 +19,7 @@ namespace VeraCrypt ScopeLock lock (HandlersMutex); ConnectedHandlers.push_back (shared_ptr (connector.CloneNew())); } - + void Event::Disconnect (void *handler) { ScopeLock lock (HandlersMutex); diff --git a/src/Platform/Event.h b/src/Platform/Event.h index b28bc90d..5aef3621 100644 --- a/src/Platform/Event.h +++ b/src/Platform/Event.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Exception.cpp b/src/Platform/Exception.cpp index 31d25b88..40739edd 100644 --- a/src/Platform/Exception.cpp +++ b/src/Platform/Exception.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Exception.h b/src/Platform/Exception.h index 1a5769ef..0b3aab43 100644 --- a/src/Platform/Exception.h +++ b/src/Platform/Exception.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/File.h b/src/Platform/File.h index d23ac6b1..5bb25a01 100644 --- a/src/Platform/File.h +++ b/src/Platform/File.h @@ -3,7 +3,7 @@ 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) + 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 @@ -56,7 +56,7 @@ namespace VeraCrypt File () : FileIsOpen (false), SharedHandle (false) { } virtual ~File (); - + void AssignSystemHandle (SystemFileHandleType openFileHandle, bool sharedHandle = true) { if (FileIsOpen) @@ -86,7 +86,7 @@ namespace VeraCrypt void Write (const ConstBufferPtr &buffer) const; void Write (const ConstBufferPtr &buffer, size_t length) const { Write (buffer.GetRange (0, length)); } void WriteAt (const ConstBufferPtr &buffer, uint64 position) const; - + protected: void ValidateState () const; diff --git a/src/Platform/FileCommon.cpp b/src/Platform/FileCommon.cpp index 934211bd..a5331266 100644 --- a/src/Platform/FileCommon.cpp +++ b/src/Platform/FileCommon.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -60,7 +60,7 @@ namespace VeraCrypt #endif } } - + FilePath File::GetPath () const { if_debug (ValidateState()); @@ -82,7 +82,7 @@ namespace VeraCrypt offset += dataRead; } } - + void File::ValidateState () const { if (!FileIsOpen) diff --git a/src/Platform/FileStream.h b/src/Platform/FileStream.h index 55c431ff..e64160e5 100644 --- a/src/Platform/FileStream.h +++ b/src/Platform/FileStream.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/FilesystemPath.h b/src/Platform/FilesystemPath.h index 83fcc5b3..145be3f8 100644 --- a/src/Platform/FilesystemPath.h +++ b/src/Platform/FilesystemPath.h @@ -3,7 +3,7 @@ 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) + 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 @@ -33,7 +33,7 @@ namespace VeraCrypt }; }; - class FilesystemPath + class FilesystemPath { public: FilesystemPath () { } @@ -59,7 +59,7 @@ namespace VeraCrypt bool IsFile () const throw () { try { return GetType() == FilesystemPathType::File; } catch (...) { return false; } } FilesystemPath ToBaseName () const; FilesystemPath ToHostDriveOfPartition () const; - + static const int MaxSize = 260; protected: diff --git a/src/Platform/Finally.h b/src/Platform/Finally.h index 5fa2e904..7afd9aef 100644 --- a/src/Platform/Finally.h +++ b/src/Platform/Finally.h @@ -3,7 +3,7 @@ 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) + 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 @@ -24,7 +24,7 @@ struct TC_JOIN(Finally,__LINE__) \ TC_UNUSED_VAR \ TC_JOIN(finally,__LINE__) -// Execute code with argument 'finally_arg' when leaving scope +// Execute code with argument 'finally_arg' when leaving scope #define finally_do_arg(argType, arg, code) \ struct TC_JOIN(Finally,__LINE__) \ { \ diff --git a/src/Platform/ForEach.h b/src/Platform/ForEach.h index e0fb121f..b16da0cf 100644 --- a/src/Platform/ForEach.h +++ b/src/Platform/ForEach.h @@ -3,7 +3,7 @@ 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) + 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 @@ -62,7 +62,7 @@ namespace VeraCrypt const T ContainerCopy; typename T::const_reverse_iterator EndIterator; mutable typename T::const_reverse_iterator Iterator; - + private: ContainerReverse &operator= (const ContainerReverse &); }; diff --git a/src/Platform/Functor.h b/src/Platform/Functor.h index 9bc96949..f17801d6 100644 --- a/src/Platform/Functor.h +++ b/src/Platform/Functor.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Memory.cpp b/src/Platform/Memory.cpp index f84a8741..c8c04766 100644 --- a/src/Platform/Memory.cpp +++ b/src/Platform/Memory.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -34,7 +34,7 @@ namespace VeraCrypt return 1; else if (size1 < size2) return -1; - + return memcmp (memory1, memory2, size1); } diff --git a/src/Platform/Memory.h b/src/Platform/Memory.h index dca1e5e2..69ce2211 100644 --- a/src/Platform/Memory.h +++ b/src/Platform/Memory.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/MemoryStream.cpp b/src/Platform/MemoryStream.cpp index b4b17cdc..ed888f4f 100644 --- a/src/Platform/MemoryStream.cpp +++ b/src/Platform/MemoryStream.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/MemoryStream.h b/src/Platform/MemoryStream.h index b3d19c7a..0c38f4d2 100644 --- a/src/Platform/MemoryStream.h +++ b/src/Platform/MemoryStream.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Mutex.h b/src/Platform/Mutex.h index c8786952..7289c5ce 100644 --- a/src/Platform/Mutex.h +++ b/src/Platform/Mutex.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Platform.h b/src/Platform/Platform.h index 9e8a4cca..c1c0834b 100644 --- a/src/Platform/Platform.h +++ b/src/Platform/Platform.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Platform.make b/src/Platform/Platform.make index 4d142317..3c04bd1a 100644 --- a/src/Platform/Platform.make +++ b/src/Platform/Platform.make @@ -3,7 +3,7 @@ # 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) +# 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 diff --git a/src/Platform/PlatformBase.h b/src/Platform/PlatformBase.h index 652069c4..bbe116f4 100644 --- a/src/Platform/PlatformBase.h +++ b/src/Platform/PlatformBase.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/PlatformTest.cpp b/src/Platform/PlatformTest.cpp index d6fcef3c..f5f5b1cb 100644 --- a/src/Platform/PlatformTest.cpp +++ b/src/Platform/PlatformTest.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -162,9 +162,9 @@ namespace VeraCrypt throw TestFailed (SRC_POS); } } - + // shared_ptr, Mutex, ScopeLock, SyncEvent, Thread - static struct + static struct { shared_ptr SharedIntPtr; Mutex IntMutex; @@ -216,7 +216,7 @@ namespace VeraCrypt TC_THREAD_PROC PlatformTest::ThreadTestProc (void *arg) { - + if (arg != (void *) &ThreadTestData) return 0; @@ -319,7 +319,7 @@ namespace VeraCrypt // uint64, vector, list, string, wstring, stringstream, wstringstream // shared_ptr, make_shared, StringConverter, foreach list > numList; - + numList.push_front (make_shared (StringConverter::ToUInt64 (StringConverter::FromNumber ((uint64) 0xFFFFffffFFFFfffeULL)))); numList.push_front (make_shared (StringConverter::ToUInt32 (StringConverter::GetTrailingNumber ("str2")))); numList.push_front (make_shared (3)); diff --git a/src/Platform/PlatformTest.h b/src/Platform/PlatformTest.h index e4dfb7ae..4b37f3a7 100644 --- a/src/Platform/PlatformTest.h +++ b/src/Platform/PlatformTest.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Serializable.cpp b/src/Platform/Serializable.cpp index 8ff2c829..a9151c0d 100644 --- a/src/Platform/Serializable.cpp +++ b/src/Platform/Serializable.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Serializable.h b/src/Platform/Serializable.h index 64c859f6..ef1fbdbe 100644 --- a/src/Platform/Serializable.h +++ b/src/Platform/Serializable.h @@ -3,7 +3,7 @@ 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) + 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 @@ -29,8 +29,8 @@ namespace VeraCrypt virtual void Deserialize (shared_ptr stream) = 0; static string DeserializeHeader (shared_ptr stream); static Serializable *DeserializeNew (shared_ptr stream); - - template + + template static shared_ptr DeserializeNew (shared_ptr stream) { shared_ptr p (dynamic_cast (DeserializeNew (stream))); @@ -39,7 +39,7 @@ namespace VeraCrypt return p; } - template + template static void DeserializeList (shared_ptr stream, list < shared_ptr > &dataList) { if (DeserializeHeader (stream) != string ("list<") + SerializerFactory::GetName (typeid (T)) + ">") diff --git a/src/Platform/Serializer.cpp b/src/Platform/Serializer.cpp index 1ac71cd1..0016694a 100644 --- a/src/Platform/Serializer.cpp +++ b/src/Platform/Serializer.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -22,7 +22,7 @@ namespace VeraCrypt { uint64 size; DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &size, sizeof (size))); - + if (Endian::Big (size) != sizeof (T)) throw ParameterIncorrect (SRC_POS); @@ -49,7 +49,7 @@ namespace VeraCrypt ValidateName (name); data = (int32) Deserialize (); } - + void Serializer::Deserialize (const string &name, int64 &data) { ValidateName (name); @@ -200,18 +200,18 @@ namespace VeraCrypt SerializeString (name); Serialize (data); } - + void Serializer::Serialize (const string &name, const char *data) { Serialize (name, string (data)); } - + void Serializer::Serialize (const string &name, int32 data) { SerializeString (name); Serialize ((uint32) data); } - + void Serializer::Serialize (const string &name, int64 data) { SerializeString (name); @@ -246,11 +246,11 @@ namespace VeraCrypt SerializeString (name); SerializeWString (data); } - + void Serializer::Serialize (const string &name, const list &stringList) { SerializeString (name); - + uint64 listSize = stringList.size(); Serialize (listSize); @@ -261,7 +261,7 @@ namespace VeraCrypt void Serializer::Serialize (const string &name, const list &stringList) { SerializeString (name); - + uint64 listSize = stringList.size(); Serialize (listSize); diff --git a/src/Platform/Serializer.h b/src/Platform/Serializer.h index 50065b9a..97d3f128 100644 --- a/src/Platform/Serializer.h +++ b/src/Platform/Serializer.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/SerializerFactory.cpp b/src/Platform/SerializerFactory.cpp index aca002ca..03bf9482 100644 --- a/src/Platform/SerializerFactory.cpp +++ b/src/Platform/SerializerFactory.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/SerializerFactory.h b/src/Platform/SerializerFactory.h index e3f7a892..29a1f655 100644 --- a/src/Platform/SerializerFactory.h +++ b/src/Platform/SerializerFactory.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/SharedPtr.h b/src/Platform/SharedPtr.h index ce49469b..5e865470 100644 --- a/src/Platform/SharedPtr.h +++ b/src/Platform/SharedPtr.h @@ -3,7 +3,7 @@ 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) + 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 @@ -21,7 +21,7 @@ namespace VeraCrypt { template - class SharedPtr + class SharedPtr { public: explicit SharedPtr () @@ -111,7 +111,7 @@ namespace VeraCrypt { Pointer = source.Pointer; UseCount = source.UseCount; - + if (UseCount) UseCount->Increment(); } diff --git a/src/Platform/SharedVal.h b/src/Platform/SharedVal.h index ffdc7e84..b66deaeb 100644 --- a/src/Platform/SharedVal.h +++ b/src/Platform/SharedVal.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Stream.h b/src/Platform/Stream.h index 293a66f1..ac3d52d1 100644 --- a/src/Platform/Stream.h +++ b/src/Platform/Stream.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/StringConverter.cpp b/src/Platform/StringConverter.cpp index d5c17e88..c6934aed 100644 --- a/src/Platform/StringConverter.cpp +++ b/src/Platform/StringConverter.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -176,7 +176,7 @@ namespace VeraCrypt return elements; } - + string StringConverter::StripTrailingNumber (const string &str) { size_t start = str.find_last_not_of ("0123456789"); @@ -194,7 +194,7 @@ namespace VeraCrypt if (ex.what() && !string (ex.what()).empty()) return ToWide (GetTypeName (typeid (ex)) + ": " + ex.what()); - + return ToWide (GetTypeName (typeid (ex))); } @@ -337,7 +337,7 @@ namespace VeraCrypt return n; } - + string StringConverter::ToUpper (const string &str) { string s; diff --git a/src/Platform/StringConverter.h b/src/Platform/StringConverter.h index 6c412437..ad391fc4 100644 --- a/src/Platform/StringConverter.h +++ b/src/Platform/StringConverter.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/SyncEvent.h b/src/Platform/SyncEvent.h index cea6610c..aa87cc16 100644 --- a/src/Platform/SyncEvent.h +++ b/src/Platform/SyncEvent.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/System.h b/src/Platform/System.h index 85385d85..918f264a 100644 --- a/src/Platform/System.h +++ b/src/Platform/System.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/SystemException.h b/src/Platform/SystemException.h index f4e6e9ab..7ba48e17 100644 --- a/src/Platform/SystemException.h +++ b/src/Platform/SystemException.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/SystemInfo.h b/src/Platform/SystemInfo.h index d8b29b77..89d3f448 100644 --- a/src/Platform/SystemInfo.h +++ b/src/Platform/SystemInfo.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/SystemLog.h b/src/Platform/SystemLog.h index eea7783f..72bd920f 100644 --- a/src/Platform/SystemLog.h +++ b/src/Platform/SystemLog.h @@ -3,7 +3,7 @@ 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) + 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 @@ -23,7 +23,7 @@ namespace VeraCrypt public: static void WriteDebug (const string &debugMessage); static void WriteError (const string &errorMessage); - + static void WriteException (const exception &ex) { WriteError (string ("exception: ") + StringConverter::ToSingle (StringConverter::ToExceptionString (ex))); diff --git a/src/Platform/TextReader.cpp b/src/Platform/TextReader.cpp index dcb1cd16..1f4003e5 100644 --- a/src/Platform/TextReader.cpp +++ b/src/Platform/TextReader.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/TextReader.h b/src/Platform/TextReader.h index 91006df6..4acc6a3d 100644 --- a/src/Platform/TextReader.h +++ b/src/Platform/TextReader.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Thread.h b/src/Platform/Thread.h index 4ec73e5e..6e8c394f 100644 --- a/src/Platform/Thread.h +++ b/src/Platform/Thread.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Time.h b/src/Platform/Time.h index 9fade923..ff606876 100644 --- a/src/Platform/Time.h +++ b/src/Platform/Time.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Unix/Directory.cpp b/src/Platform/Unix/Directory.cpp index db81b126..9c0590cb 100644 --- a/src/Platform/Unix/Directory.cpp +++ b/src/Platform/Unix/Directory.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -53,7 +53,7 @@ namespace VeraCrypt while ((dirEntry = readdir (dir)) != nullptr) { shared_ptr filePath (new FilePath (string (AppendSeparator (path)) + string (dirEntry->d_name))); - + if (!regularFilesOnly || filePath->IsFile()) files.push_back (filePath); diff --git a/src/Platform/Unix/File.cpp b/src/Platform/Unix/File.cpp index ddc7518e..5c45dcfc 100644 --- a/src/Platform/Unix/File.cpp +++ b/src/Platform/Unix/File.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -73,7 +73,7 @@ namespace VeraCrypt } catch (...) // Suppress errors to allow using read-only files { -#ifdef DEBUG +#ifdef DEBUG throw; #endif } @@ -132,7 +132,7 @@ namespace VeraCrypt // HDIO_GETGEO ioctl is limited by the size of long TextReader tr ("/sys/block/" + string (Path.ToHostDriveOfPartition().ToBaseName()) + "/" + string (Path.ToBaseName()) + "/start"); - + string line; tr.ReadLine (line); return StringConverter::ToUInt64 (line) * GetDeviceSectorSize(); @@ -199,7 +199,7 @@ namespace VeraCrypt case CreateReadWrite: sysFlags |= O_CREAT | O_TRUNC | O_RDWR; break; - + case CreateWrite: sysFlags |= O_CREAT | O_TRUNC | O_WRONLY; break; @@ -262,7 +262,7 @@ namespace VeraCrypt throw SystemException (SRC_POS, wstring (path)); } break; - + case ShareReadWriteIgnoreLock: break; @@ -339,7 +339,7 @@ namespace VeraCrypt #endif throw_sys_sub_if (write (FileHandle, buffer, buffer.Size()) != (ssize_t) buffer.Size(), wstring (Path)); } - + void File::WriteAt (const ConstBufferPtr &buffer, uint64 position) const { if_debug (ValidateState()); diff --git a/src/Platform/Unix/FilesystemPath.cpp b/src/Platform/Unix/FilesystemPath.cpp index 0beb4703..f5d59f9f 100644 --- a/src/Platform/Unix/FilesystemPath.cpp +++ b/src/Platform/Unix/FilesystemPath.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -43,7 +43,7 @@ namespace VeraCrypt struct stat statData; throw_sys_sub_if (stat (StringConverter::ToSingle (path).c_str(), &statData) != 0, Path); - + if (S_ISREG (statData.st_mode)) return FilesystemPathType::File; if (S_ISDIR (statData.st_mode)) return FilesystemPathType::Directory; if (S_ISCHR (statData.st_mode)) return FilesystemPathType::CharacterDevice; diff --git a/src/Platform/Unix/Mutex.cpp b/src/Platform/Unix/Mutex.cpp index 80b68ffb..a6b61de6 100644 --- a/src/Platform/Unix/Mutex.cpp +++ b/src/Platform/Unix/Mutex.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Unix/Pipe.cpp b/src/Platform/Unix/Pipe.cpp index 0d39adae..f427ae63 100644 --- a/src/Platform/Unix/Pipe.cpp +++ b/src/Platform/Unix/Pipe.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -44,7 +44,7 @@ namespace VeraCrypt int Pipe::GetReadFD () { assert (ReadFileDescriptor != -1); - + if (WriteFileDescriptor != -1) { close (WriteFileDescriptor); diff --git a/src/Platform/Unix/Pipe.h b/src/Platform/Unix/Pipe.h index 9bee3ec9..72af91bd 100644 --- a/src/Platform/Unix/Pipe.h +++ b/src/Platform/Unix/Pipe.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Unix/Poller.cpp b/src/Platform/Unix/Poller.cpp index ef202f49..6b845631 100644 --- a/src/Platform/Unix/Poller.cpp +++ b/src/Platform/Unix/Poller.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Unix/Poller.h b/src/Platform/Unix/Poller.h index 3dc06b98..054fe75e 100644 --- a/src/Platform/Unix/Poller.h +++ b/src/Platform/Unix/Poller.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Unix/Process.cpp b/src/Platform/Unix/Process.cpp index 07703649..92a8f478 100644 --- a/src/Platform/Unix/Process.cpp +++ b/src/Platform/Unix/Process.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -53,16 +53,16 @@ namespace VeraCrypt try { int argIndex = 0; - /* Workaround for gcc 5.X issue related to the use of STL (string and list) with muliple fork calls. - * + /* Workaround for gcc 5.X issue related to the use of STL (string and list) with muliple fork calls. + * * The char* pointers retrieved from the elements of parameter "arguments" are no longer valid after * a second fork is called. "arguments" was created in the parent of the current child process. - * - * The only solution is to copy the elements of "arguments" parameter in a local string array on this - * child process and then use char* pointers retrieved from this local copies before calling fork. - * + * + * The only solution is to copy the elements of "arguments" parameter in a local string array on this + * child process and then use char* pointers retrieved from this local copies before calling fork. + * * gcc 4.x doesn't suffer from this issue. - * + * */ string argsCopy[array_capacity (args)]; if (!execFunctor) @@ -74,7 +74,7 @@ namespace VeraCrypt { argsCopy[argIndex++] = arg; } - + for (int i = 0; i < argIndex; i++) { args[i] = const_cast (argsCopy[i].c_str()); diff --git a/src/Platform/Unix/Process.h b/src/Platform/Unix/Process.h index af9aa339..d19d5737 100644 --- a/src/Platform/Unix/Process.h +++ b/src/Platform/Unix/Process.h @@ -3,7 +3,7 @@ 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) + 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 @@ -31,7 +31,7 @@ namespace VeraCrypt Process (); virtual ~Process (); - static string Execute (const string &processName, const list &arguments, int timeOut = -1, ProcessExecFunctor *execFunctor = nullptr, const Buffer *inputData = nullptr); + static string Execute (const string &processName, const list &arguments, int timeOut = -1, ProcessExecFunctor *execFunctor = nullptr, const Buffer *inputData = nullptr); protected: diff --git a/src/Platform/Unix/SyncEvent.cpp b/src/Platform/Unix/SyncEvent.cpp index 6e775493..10bbc0c9 100644 --- a/src/Platform/Unix/SyncEvent.cpp +++ b/src/Platform/Unix/SyncEvent.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -66,7 +66,7 @@ namespace VeraCrypt if (status != 0) throw SystemException (SRC_POS, status); } - + Signaled = false; } } diff --git a/src/Platform/Unix/System.h b/src/Platform/Unix/System.h index e322d331..30384907 100644 --- a/src/Platform/Unix/System.h +++ b/src/Platform/Unix/System.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Unix/SystemException.cpp b/src/Platform/Unix/SystemException.cpp index 6fc29176..be051cc0 100644 --- a/src/Platform/Unix/SystemException.cpp +++ b/src/Platform/Unix/SystemException.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -37,7 +37,7 @@ namespace VeraCrypt : Exception (message, subject), ErrorCode (errno) { } - + void SystemException::Deserialize (shared_ptr stream) { Exception::Deserialize (stream); @@ -49,7 +49,7 @@ namespace VeraCrypt { return ErrorCode != 0; } - + void SystemException::Serialize (shared_ptr stream) const { Exception::Serialize (stream); diff --git a/src/Platform/Unix/SystemInfo.cpp b/src/Platform/Unix/SystemInfo.cpp index abf5a393..c3e3ab38 100644 --- a/src/Platform/Unix/SystemInfo.cpp +++ b/src/Platform/Unix/SystemInfo.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Unix/SystemLog.cpp b/src/Platform/Unix/SystemLog.cpp index 93fb4e35..88027e40 100644 --- a/src/Platform/Unix/SystemLog.cpp +++ b/src/Platform/Unix/SystemLog.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Unix/Thread.cpp b/src/Platform/Unix/Thread.cpp index 5d7fe2ea..2d9fae09 100644 --- a/src/Platform/Unix/Thread.cpp +++ b/src/Platform/Unix/Thread.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/Unix/Time.cpp b/src/Platform/Unix/Time.cpp index f30058e4..e98cea69 100644 --- a/src/Platform/Unix/Time.cpp +++ b/src/Platform/Unix/Time.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Platform/User.h b/src/Platform/User.h index 34c00527..ae7c179f 100644 --- a/src/Platform/User.h +++ b/src/Platform/User.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Readme.txt b/src/Readme.txt index faf1683f..97678b5d 100644 --- a/src/Readme.txt +++ b/src/Readme.txt @@ -17,16 +17,16 @@ called 'TrueCrypt' or 'VeraCrypt' Contents ======== -I. Windows - Requirements for Building VeraCrypt for Windows - Instructions for Building VeraCrypt for Windows +I. Windows + Requirements for Building VeraCrypt for Windows + Instructions for Building VeraCrypt for Windows Instructions for Signing and Packaging VeraCrypt for Windows -II. Linux and Mac OS X - Requirements for Building VeraCrypt for Linux and Mac OS X - Instructions for Building VeraCrypt for Linux and Mac OS X +II. Linux and Mac OS X + Requirements for Building VeraCrypt for Linux and Mac OS X + Instructions for Building VeraCrypt for Linux and Mac OS X Mac OS X specifics - + III. FreeBSD and OpenSolaris IV. Third-Party Developers (Contributors) @@ -65,7 +65,7 @@ issued by Thawte certification authority. At the end of each official .exe and .sys file, there are embedded digital signatures and all related certificates (i.e. all certificates in the relevant certification chain, such as the certification authority certificates, CA-MS cross-certificate, and the -IDRIX certificate). +IDRIX certificate). Keep this in mind if you compile VeraCrypt and compare your binaries with the official binaries. If your binaries are unsigned, the sizes of the official binaries will usually be approximately @@ -108,12 +108,12 @@ Instructions for Signing and Packaging VeraCrypt for Windows: First, create an environment variable 'WSDK81' pointing to the Windows SDK for Windows 8.1 installation directory. -The folder "Signing" contains a batch file (sign.bat) that will sign all -VeraCrypt components using a code signing certificate present on the +The folder "Signing" contains a batch file (sign.bat) that will sign all +VeraCrypt components using a code signing certificate present on the certificate store and also build the final installation setup. The batch file suppose that the code signing certificate is issued by Thawt. -This is the case for IDRIX's certificate. If yours is issued by another CA, -then you should put the Root and Intermediate certificates in the "Signing" +This is the case for IDRIX's certificate. If yours is issued by another CA, +then you should put the Root and Intermediate certificates in the "Signing" folder and then modify sign.bat accordingly. @@ -135,8 +135,8 @@ Requirements for Building VeraCrypt for Linux and Mac OS X: and https://osxfuse.github.io/) - RSA Security Inc. PKCS #11 Cryptographic Token Interface (Cryptoki) 2.20 header files (available at ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-11/v2-20). - They are already included in the source tree under the directory PKCS11 but - it is possible to override it using the environment variable 'PKCS11_INC'. + They are already included in the source tree under the directory PKCS11 but + it is possible to override it using the environment variable 'PKCS11_INC'. Instructions for Building VeraCrypt for Linux and Mac OS X: @@ -146,7 +146,7 @@ Instructions for Building VeraCrypt for Linux and Mac OS X: 2) If you have no wxWidgets shared library installed, run the following command to configure the wxWidgets static library for VeraCrypt and to - build it: + build it: $ make WXSTATIC=1 WX_ROOT=/usr/src/wxWidgets wxbuild @@ -159,7 +159,7 @@ Instructions for Building VeraCrypt for Linux and Mac OS X: $ make or if you have no wxWidgets shared library installed: - + $ make WXSTATIC=1 4) If successful, the VeraCrypt executable should be located in the directory @@ -172,21 +172,21 @@ built using the 'NOGUI' parameter: $ make NOGUI=1 WXSTATIC=1 WX_ROOT=/usr/src/wxWidgets wxbuild $ make NOGUI=1 WXSTATIC=1 - + On MacOSX, building a console-only executable is not supported. Mac OS X specifics: ----------------------------------------------------------- - + Under MacOSX, the SDK for OSX 10.7 is used by default. To use another version of the SDK (i.e. 10.6), you can export the environment variable VC_OSX_TARGET: - + $ export VC_OSX_TARGET=10.6 Before building under MacOSX, pkg-config must be installed if not yet available. Get it from http://pkgconfig.freedesktop.org/releases/pkg-config-0.28.tar.gz and -compile using the following commands : +compile using the following commands : $ ./configure --with-internal-glib $ make @@ -195,9 +195,9 @@ compile using the following commands : After making sure pkg-config is available, download and install OSXFuse from https://osxfuse.github.io/ (MacFUSE compatibility layer must selected) -The script build_veracrypt_macosx.sh available under "src/Build" performs the +The script build_veracrypt_macosx.sh available under "src/Build" performs the full build of VeraCrypt including the creation of the installer pkg. It expects -to find the wxWidgets 3.0.2 sources at the same level as where you put +to find the wxWidgets 3.0.2 sources at the same level as where you put VeraCrypt sources (i.e. if "src" path is "/Users/joe/Projects/VeraCrypt/src" then wxWidgets should be at "/Users/joe/Projects/wxWidgets-wxWidgets-3.0.2") @@ -224,8 +224,8 @@ IV. Third-Party Developers (Contributors) If you intend to implement a feature, please contact us first to make sure: 1) That the feature has not been implemented (we may have already implemented - it, but haven't released the code yet). -2) That the feature is acceptable. + it, but haven't released the code yet). +2) That the feature is acceptable. 3) Whether we need help of third-party developers with implementing the feature. Information on how to contact us can be found at: @@ -253,7 +253,7 @@ source code. Trademark Information --------------------- -Any trademarks contained in the source code, binaries, and/or in the +Any trademarks contained in the source code, binaries, and/or in the documentation, are the sole property of their respective owners. diff --git a/src/Release/Setup Files/License.txt b/src/Release/Setup Files/License.txt index 44c0c657..dc686dd1 100644 --- a/src/Release/Setup Files/License.txt +++ b/src/Release/Setup Files/License.txt @@ -8,16 +8,16 @@ BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE SOFTWARE, NOR ANY PART(S) THEREOF. -VeraCrypt is multi-licensed under Apache License 2.0 and -the TrueCrypt License version 3.0, a verbatim copy of both +VeraCrypt is multi-licensed under Apache License 2.0 and +the TrueCrypt License version 3.0, a verbatim copy of both licenses can be found below. -This license does not grant you rights to use any -contributors' name, logo, or trademarks, including IDRIX, +This license does not grant you rights to use any +contributors' name, logo, or trademarks, including IDRIX, VeraCrypt and all derivative names. -For example, the following names are not allowed: VeraCrypt, -VeraCrypt+, VeraCrypt Professional, iVeraCrypt, etc. Nor any -other names confusingly similar to the name VeraCrypt (e.g., +For example, the following names are not allowed: VeraCrypt, +VeraCrypt+, VeraCrypt Professional, iVeraCrypt, etc. Nor any +other names confusingly similar to the name VeraCrypt (e.g., Vera-Crypt, Vera Crypt, VerKrypt, etc.) ____________________________________________________________ diff --git a/src/Release/Setup Files/NOTICE b/src/Release/Setup Files/NOTICE index 42ae8da9..6c2416c2 100644 --- a/src/Release/Setup Files/NOTICE +++ b/src/Release/Setup Files/NOTICE @@ -9,8 +9,8 @@ http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. +See the License for the specific language governing permissions and +limitations under the License. ____________________________________________________________ Copyright (c) 2008-2012 TrueCrypt Developers Association. All rights reserved. diff --git a/src/Setup/ComSetup.cpp b/src/Setup/ComSetup.cpp index 24e5262f..1b3220d9 100644 --- a/src/Setup/ComSetup.cpp +++ b/src/Setup/ComSetup.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Setup/ComSetup.h b/src/Setup/ComSetup.h index 56e30139..6001fde2 100644 --- a/src/Setup/ComSetup.h +++ b/src/Setup/ComSetup.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Setup/ComSetup.rgs b/src/Setup/ComSetup.rgs index ed927913..b8201c10 100644 --- a/src/Setup/ComSetup.rgs +++ b/src/Setup/ComSetup.rgs @@ -20,7 +20,7 @@ HKCR LocalServer32 = s '"%MAIN_MODULE%"' TypeLib = s '{9ACF6176-5FC4-4690-A025-B3306A50EB6A}' - + Elevation { val Enabled = d 1 @@ -38,13 +38,13 @@ HKCR { val AccessPermission = b 010004803000000040000000000000001400000002001c000100000000001400070000000101000000000005040000000102000000000005200000002002000001020000000000052000000020020000 } - + ForceRemove VeraCrypt.exe { val AppId = s '{FE8B3B95-C80C-41f7-830F-FBA271C26F7E}' } } - + ForceRemove VeraCryptFormat.1 = s 'VeraCryptFormat class' { CLSID = s '{A96D3797-9F31-49f4-A0CE-9657392CF789}' @@ -55,7 +55,7 @@ HKCR CLSID = s '{A96D3797-9F31-49f4-A0CE-9657392CF789}' CurVer = s 'VeraCryptFormat.1' } - + NoRemove CLSID { ForceRemove {A96D3797-9F31-49f4-A0CE-9657392CF789} = s 'VeraCryptFormat class' @@ -65,7 +65,7 @@ HKCR LocalServer32 = s '"%FORMAT_MODULE%"' TypeLib = s '{56327DDA-F1A7-4e13-B128-520D129BDEF6}' - + Elevation { val Enabled = d 1 @@ -76,14 +76,14 @@ HKCR val LocalizedString = s '@%FORMAT_MODULE%,-112' } } - + NoRemove AppId { ForceRemove {A96D3797-9F31-49f4-A0CE-9657392CF789} = s 'VeraCryptFormat class' { val AccessPermission = b 010004803000000040000000000000001400000002001c000100000000001400070000000101000000000005040000000102000000000005200000002002000001020000000000052000000020020000 } - + ForceRemove 'VeraCrypt Format.exe' { val AppId = s '{A96D3797-9F31-49f4-A0CE-9657392CF789}' diff --git a/src/Setup/Dir.c b/src/Setup/Dir.c index 342ff748..3619f2d9 100644 --- a/src/Setup/Dir.c +++ b/src/Setup/Dir.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Setup/Dir.h b/src/Setup/Dir.h index 2126bb42..5db9fa51 100644 --- a/src/Setup/Dir.h +++ b/src/Setup/Dir.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Setup/Linux/veracrypt_install_template.sh b/src/Setup/Linux/veracrypt_install_template.sh index 170f72ec..8eaf15c8 100644 --- a/src/Setup/Linux/veracrypt_install_template.sh +++ b/src/Setup/Linux/veracrypt_install_template.sh @@ -3,7 +3,7 @@ # 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) +# 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 @@ -49,13 +49,13 @@ fi if [ $TTY -eq 0 ] then [ $GUI -eq 0 ] && echo 'Error: Terminal required' >&2 && exit 1 - + if [ $XMESSAGE -eq 0 ] || ([ $XTERM -eq 0 ] && [ $GTERM -eq 0 ] && [ $KTERM -eq 0 ]) then which gnome-terminal && exec gnome-terminal -e "$0" which konsole && exec konsole -e "$0" which xterm && exec xterm -e "$0" - + [ $XMESSAGE -eq 1 ] && show_exit_message 'Error: Terminal required' exit 1 fi @@ -107,7 +107,7 @@ show_message() show_exit_message() { show_message "$*" - + if [ $XMESSAGE -eq 0 ] then printf 'Press Enter to exit... ' @@ -131,16 +131,16 @@ BOUND BY ALL TERMS AND CONDITIONS OF THIS LICENSE. IF YOU DO NOT ACCEPT THEM, DO NOT USE, COPY, MODIFY, NOR (RE)DISTRIBUTE THE SOFTWARE, NOR ANY PART(S) THEREOF. -VeraCrypt is multi-licensed under Apache License 2.0 and -the TrueCrypt License version 3.0, a verbatim copy of both +VeraCrypt is multi-licensed under Apache License 2.0 and +the TrueCrypt License version 3.0, a verbatim copy of both licenses can be found below. -This license does not grant you rights to use any -contributors' name, logo, or trademarks, including IDRIX, +This license does not grant you rights to use any +contributors' name, logo, or trademarks, including IDRIX, VeraCrypt and all derivative names. -For example, the following names are not allowed: VeraCrypt, -VeraCrypt+, VeraCrypt Professional, iVeraCrypt, etc. Nor any -other names confusingly similar to the name VeraCrypt (e.g., +For example, the following names are not allowed: VeraCrypt, +VeraCrypt+, VeraCrypt Professional, iVeraCrypt, etc. Nor any +other names confusingly similar to the name VeraCrypt (e.g., Vera-Crypt, Vera Crypt, VerKrypt, etc.) ____________________________________________________________ @@ -172,7 +172,7 @@ of such entity. exercising permissions granted by this License. "Source" form shall mean the preferred form for making -modifications, including but not limited to software source +modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical @@ -200,7 +200,7 @@ additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the -purposes of this definition, "submitted" means any form +purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control @@ -222,18 +222,18 @@ prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. -3. Grant of Patent License. Subject to the terms and conditions +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable(except as stated in this section) patent license -to make, have made, use, offer to sell, sell, import, and -otherwise transfer the Work, where such license applies only +irrevocable(except as stated in this section) patent license +to make, have made, use, offer to sell, sell, import, and +otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are -necessarily infringed by their Contribution(s) alone or by +necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent -litigation against any entity (including a cross-claim or -counterclaim in a lawsuit) alleging that the Work or a +litigation against any entity (including a cross-claim or +counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate @@ -273,7 +273,7 @@ that You meet the following conditions: You may add Your own copyright statement to Your modifications and may provide additional or different license terms -and conditions for use, reproduction, or distribution of +and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. @@ -298,7 +298,7 @@ agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or -conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, +conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of @@ -311,7 +311,7 @@ deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or -out of the use or inability to use the Work (including but not +out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the @@ -320,7 +320,7 @@ possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, -warranty, indemnity, or other liability obligations and/or +warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, @@ -848,7 +848,7 @@ then cat <<_END | xmessage -center -file - -buttons "Exit:1,Extract .$PACKAGE_TYPE Package File:20,Install VeraCrypt:10" -default 'Install VeraCrypt' VeraCrypt $VERSION Setup ==================== - VeraCrypt is a free disk encryption software brought to you by IDRIX + VeraCrypt is a free disk encryption software brought to you by IDRIX (http://www.idrix.fr) and that is based on TrueCrypt. It is a software system for establishing and maintaining an on-the-fly-encrypted volume (data storage device). On-the-fly encryption @@ -864,7 +864,7 @@ Please select one of the below options: _END SEL=$? - + case $SEL in 1) exit 1 ;; @@ -892,10 +892,10 @@ Installation options: _MENU_END printf 'To select, enter 1 or 2: ' - + read SEL [ -z "$SEL" ] && SEL=1 - + case $SEL in 1) INSTALL=1 ;; @@ -948,14 +948,14 @@ Press Page Down key or use the scroll bar to see the rest of the license. _END SEL=$? - + rm -f $LICENSE if [ $SEL -ne 10 ] then show_exit_message 'Installation/extraction aborted' exit 1 fi - + else # Console license agreement @@ -1001,9 +1001,9 @@ _END while [ $ACCEPTED -eq 0 ] do printf '\n\nDo you accept and agree to be bound by the license terms? (yes/no): ' - + read SEL - + case $SEL in y|Y|yes|YES) ACCEPTED=1 @@ -1080,7 +1080,7 @@ then else echo 'Installing package...' $SUDO $PACKAGE_INSTALLER $PACKAGE_INSTALLER_OPTS $PACKAGE && INSTALLED=1 - + if [ $INSTALLED -eq 1 ] then show_exit_message '' diff --git a/src/Setup/MacOSX/veracrypt.pkgproj b/src/Setup/MacOSX/veracrypt.pkgproj index 3ccb7992..ecf06615 100755 --- a/src/Setup/MacOSX/veracrypt.pkgproj +++ b/src/Setup/MacOSX/veracrypt.pkgproj @@ -791,7 +791,7 @@ VALUE OSXFuse seems to be missing on your machine. VeraCrypt requires OSXFuse 2.3 or above. -Please download the latest OSXFuse version from : +Please download the latest OSXFuse version from : https://osxfuse.github.io/ diff --git a/src/Setup/Resource.h b/src/Setup/Resource.h index bbbd4766..8feaf3dc 100644 --- a/src/Setup/Resource.h +++ b/src/Setup/Resource.h @@ -52,7 +52,7 @@ #define IDC_DONATE 1032 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 diff --git a/src/Setup/SelfExtract.c b/src/Setup/SelfExtract.c index e427e44c..5129e991 100644 --- a/src/Setup/SelfExtract.c +++ b/src/Setup/SelfExtract.c @@ -3,7 +3,7 @@ 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) + 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 @@ -51,8 +51,8 @@ void SelfExtractStartupInit (void) } -// The end marker must be included in the self-extracting exe only once, not twice (used e.g. -// by IsSelfExtractingPackage()) and that's why MAG_END_MARKER_OBFUSCATED is obfuscated and +// The end marker must be included in the self-extracting exe only once, not twice (used e.g. +// by IsSelfExtractingPackage()) and that's why MAG_END_MARKER_OBFUSCATED is obfuscated and // needs to be deobfuscated using this function at startup. static void DeobfuscateMagEndMarker (void) { @@ -90,27 +90,27 @@ static int DecompressBuffer (char *out, char *in, int len) } -static void __cdecl PipeWriteThread (void *len) +static void __cdecl PipeWriteThread (void *len) { int sendBufSize = PIPE_BUFFER_LEN, bytesSent = 0; int bytesToSend = *((int *) len), bytesSentTotal = 0; if (PipeWriteBuf == NULL || (HANDLE) hChildStdinWrite == INVALID_HANDLE_VALUE) { - PkgError (L"Failed sending data to the STDIN pipe"); + PkgError (L"Failed sending data to the STDIN pipe"); return; } - while (bytesToSend > 0) - { + while (bytesToSend > 0) + { if (bytesToSend < PIPE_BUFFER_LEN) sendBufSize = bytesToSend; - if (!WriteFile ((HANDLE) hChildStdinWrite, (char *) PipeWriteBuf + bytesSentTotal, sendBufSize, &bytesSent, NULL) + if (!WriteFile ((HANDLE) hChildStdinWrite, (char *) PipeWriteBuf + bytesSentTotal, sendBufSize, &bytesSent, NULL) || bytesSent == 0 - || bytesSent != sendBufSize) + || bytesSent != sendBufSize) { - PkgError (L"Failed sending data to the STDIN pipe"); + PkgError (L"Failed sending data to the STDIN pipe"); return; } @@ -122,23 +122,23 @@ static void __cdecl PipeWriteThread (void *len) if (!CloseHandle (hChildStdinWrite)) { - PkgError (L"Cannot close pipe"); + PkgError (L"Cannot close pipe"); return; } } -// Returns 0 if compression fails or, if successful, the size of the compressed data +// Returns 0 if compression fails or, if successful, the size of the compressed data static int CompressBuffer (char *out, char *in, int len) { - SECURITY_ATTRIBUTES securityAttrib; + SECURITY_ATTRIBUTES securityAttrib; DWORD bytesReceived = 0; HANDLE hChildStdoutWrite = INVALID_HANDLE_VALUE; HANDLE hChildStdoutRead = INVALID_HANDLE_VALUE; HANDLE hChildStdinRead = INVALID_HANDLE_VALUE; STARTUPINFO startupInfo; - PROCESS_INFORMATION procInfo; - char pipeBuffer [PIPE_BUFFER_LEN]; + PROCESS_INFORMATION procInfo; + char pipeBuffer [PIPE_BUFFER_LEN]; int res_len = 0; BOOL bGzipHeaderRead = FALSE; wchar_t szGzipCmd[64]; @@ -147,13 +147,13 @@ static int CompressBuffer (char *out, char *in, int len) ZeroMemory (&procInfo, sizeof (procInfo)); // Pipe handle inheritance - securityAttrib.bInheritHandle = TRUE; - securityAttrib.nLength = sizeof (securityAttrib); - securityAttrib.lpSecurityDescriptor = NULL; + securityAttrib.bInheritHandle = TRUE; + securityAttrib.nLength = sizeof (securityAttrib); + securityAttrib.lpSecurityDescriptor = NULL; if (!CreatePipe (&hChildStdoutRead, &hChildStdoutWrite, &securityAttrib, 0)) { - PkgError (L"Cannot create STDOUT pipe."); + PkgError (L"Cannot create STDOUT pipe."); return 0; } SetHandleInformation (hChildStdoutRead, HANDLE_FLAG_INHERIT, 0); @@ -172,7 +172,7 @@ static int CompressBuffer (char *out, char *in, int len) startupInfo.wShowWindow = SW_HIDE; startupInfo.hStdInput = hChildStdinRead; startupInfo.hStdOutput = hChildStdoutWrite; - startupInfo.cb = sizeof (startupInfo); + startupInfo.cb = sizeof (startupInfo); startupInfo.hStdError = hChildStdoutWrite; startupInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; @@ -196,7 +196,7 @@ static int CompressBuffer (char *out, char *in, int len) if (!CloseHandle (hChildStdoutWrite)) { - PkgError (L"Cannot close STDOUT write"); + PkgError (L"Cannot close STDOUT write"); CloseHandle(hChildStdoutRead); CloseHandle(hChildStdinRead); return 0; @@ -205,10 +205,10 @@ static int CompressBuffer (char *out, char *in, int len) bGzipHeaderRead = FALSE; // Read the compressed data from the pipe (sent by the child process to STDOUT) - while (TRUE) - { - if (!ReadFile (hChildStdoutRead, pipeBuffer, bGzipHeaderRead ? PIPE_BUFFER_LEN : 10, &bytesReceived, NULL)) - break; + while (TRUE) + { + if (!ReadFile (hChildStdoutRead, pipeBuffer, bGzipHeaderRead ? PIPE_BUFFER_LEN : 10, &bytesReceived, NULL)) + break; if (bGzipHeaderRead) { @@ -217,7 +217,7 @@ static int CompressBuffer (char *out, char *in, int len) } else bGzipHeaderRead = TRUE; // Skip the 10-byte gzip header - } + } CloseHandle(hChildStdoutRead); CloseHandle(hChildStdinRead); @@ -225,7 +225,7 @@ static int CompressBuffer (char *out, char *in, int len) } -// Clears all bytes that change when an exe file is digitally signed, except the data that are appended. +// Clears all bytes that change when an exe file is digitally signed, except the data that are appended. // If those bytes weren't cleared, CRC-32 checks would fail after signing. static void WipeSignatureAreas (char *buffer) { @@ -295,7 +295,7 @@ BOOL MakeSelfExtractingPackage (HWND hwndDlg, wchar_t *szDestDir) bufLen += 4; // 32-bit file length } - buffer = malloc (bufLen + 524288); // + 512K reserve + buffer = malloc (bufLen + 524288); // + 512K reserve if (buffer == NULL) { PkgError (L"Cannot allocate memory for uncompressed data"); @@ -309,7 +309,7 @@ BOOL MakeSelfExtractingPackage (HWND hwndDlg, wchar_t *szDestDir) // Write the start marker if (!SaveBufferToFile (MAG_START_MARKER, outputFile, strlen (MAG_START_MARKER), TRUE, FALSE)) - { + { if (_wremove (outputFile)) PkgError (L"Cannot write the start marker\nFailed also to delete package file"); else @@ -645,7 +645,7 @@ BOOL SelfExtractInMemory (wchar_t *path) Error ("DIST_PACKAGE_CORRUPTED", NULL); } - DecompressedData = malloc (uncompressedLen + 524288); // + 512K reserve + DecompressedData = malloc (uncompressedLen + 524288); // + 512K reserve if (DecompressedData == NULL) { Error ("ERR_MEM_ALLOC", NULL); @@ -693,7 +693,7 @@ BOOL SelfExtractInMemory (wchar_t *path) bufPos += Decompressed_Files[fileNo].fileLength; // Verify CRC-32 of the file (to verify that it didn't get corrupted while creating the solid archive). - if (Decompressed_Files[fileNo].crc + if (Decompressed_Files[fileNo].crc != GetCrc32 (Decompressed_Files[fileNo].fileContent, Decompressed_Files[fileNo].fileLength)) { Error ("DIST_PACKAGE_CORRUPTED", NULL); diff --git a/src/Setup/SelfExtract.h b/src/Setup/SelfExtract.h index 529b24d7..91e2ca7c 100644 --- a/src/Setup/SelfExtract.h +++ b/src/Setup/SelfExtract.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Setup/Setup.c b/src/Setup/Setup.c index 899c1583..331b8ea4 100644 --- a/src/Setup/Setup.c +++ b/src/Setup/Setup.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -156,7 +156,7 @@ static void RecursiveSetOwner (HKEY hKey, PSECURITY_DESCRIPTOR pSD) { LSTATUS status = 0; DWORD dwIndex = 0, dwMaxNameLen = 0, dwNameLen = 0, numberSubKeys = 0; - HKEY hSubKey; + HKEY hSubKey; if ( (ERROR_SUCCESS == status) && (ERROR_SUCCESS == RegQueryInfoKey(hKey, NULL, NULL, NULL, &numberSubKeys, &dwMaxNameLen, NULL, NULL, NULL, NULL, NULL, NULL)) && (numberSubKeys >= 1) @@ -192,7 +192,7 @@ static void RecursiveSetDACL (HKEY hKey, const wchar_t* SubKeyName, PSECURITY_DE HKEY hSubKey; DWORD dwIndex = 0, dwMaxNameLen = 0, dwNameLen = 0, numberSubKeys = 0; LSTATUS status = RegOpenKeyExW(hKey, SubKeyName, 0, WRITE_DAC | KEY_READ /*| ACCESS_SYSTEM_SECURITY*/, &hSubKey); - if (status == ERROR_SUCCESS) + if (status == ERROR_SUCCESS) { status = RegSetKeySecurity (hSubKey, DACL_SECURITY_INFORMATION, pSD); if (status == ERROR_SUCCESS) @@ -235,16 +235,16 @@ static void AllowKeyAccess(HKEY Key,const wchar_t* SubKeyName) std::string sNewSD; RegResult = RegOpenKeyExW(Key, SubKeyName, 0, WRITE_OWNER | KEY_READ, &SvcKey); - if (RegResult==ERROR_SUCCESS) + if (RegResult==ERROR_SUCCESS) { - if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &Token)) + if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &Token)) { - if (!GetTokenInformation(Token, TokenUser, pTokenUser, 0, &dwLength)) + if (!GetTokenInformation(Token, TokenUser, pTokenUser, 0, &dwLength)) { - if (GetLastError() ==ERROR_INSUFFICIENT_BUFFER) + if (GetLastError() ==ERROR_INSUFFICIENT_BUFFER) { pTokenUser = (PTOKEN_USER) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength); - if (pTokenUser) + if (pTokenUser) { if (GetTokenInformation(Token, TokenUser, pTokenUser, dwLength, &dwLength)) { @@ -257,7 +257,7 @@ static void AllowKeyAccess(HKEY Key,const wchar_t* SubKeyName) RecursiveSetOwner(SvcKey, &SecDesc); } } - + } } } @@ -265,7 +265,7 @@ static void AllowKeyAccess(HKEY Key,const wchar_t* SubKeyName) RegCloseKey(SvcKey); } - if (pTokenUser) + if (pTokenUser) { PSID pSid = pTokenUser->User.Sid; DWORD dwAclSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + ::GetLengthSid(pSid) - sizeof(DWORD); @@ -338,7 +338,7 @@ void SearchAndDeleteRegistrySubString (HKEY hKey, const wchar_t *subKey, const w } for (std::list::iterator ItSubKey = subKeysList.begin(); ItSubKey != subKeysList.end(); ItSubKey++) - { + { // if the string to search for is empty, delete the sub key, otherwise, look for matching value and delete them if (subStringLength == 0) { @@ -378,13 +378,13 @@ void SearchAndDeleteRegistrySubString (HKEY hKey, const wchar_t *subKey, const w foundEntries.push_back(szNameValue); } } - } while ((status == ERROR_SUCCESS) || (status == ERROR_MORE_DATA)); // we ignore ERROR_MORE_DATA errors since + } while ((status == ERROR_SUCCESS) || (status == ERROR_MORE_DATA)); // we ignore ERROR_MORE_DATA errors since // we are sure to use the correct sizes // delete the entries if (!foundEntries.empty()) { - for (std::list::iterator It = foundEntries.begin(); + for (std::list::iterator It = foundEntries.begin(); It != foundEntries.end(); It++) { RegDeleteValueW (hSubKey, It->c_str()); @@ -403,18 +403,18 @@ void SearchAndDeleteRegistrySubString (HKEY hKey, const wchar_t *subKey, const w } /* Set the given privilege of the current process */ -BOOL SetPrivilege(LPTSTR szPrivilegeName, BOOL bEnable) +BOOL SetPrivilege(LPTSTR szPrivilegeName, BOOL bEnable) { TOKEN_PRIVILEGES tp; LUID luid; - HANDLE hProcessToken; + HANDLE hProcessToken; BOOL bStatus = FALSE; if ( OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hProcessToken) ) { - if ( LookupPrivilegeValue( + if ( LookupPrivilegeValue( NULL, szPrivilegeName, &luid ) ) @@ -426,11 +426,11 @@ BOOL SetPrivilege(LPTSTR szPrivilegeName, BOOL bEnable) // Enable the privilege bStatus = AdjustTokenPrivileges( - hProcessToken, - FALSE, - &tp, - sizeof(TOKEN_PRIVILEGES), - (PTOKEN_PRIVILEGES) NULL, + hProcessToken, + FALSE, + &tp, + sizeof(TOKEN_PRIVILEGES), + (PTOKEN_PRIVILEGES) NULL, (PDWORD) NULL); } @@ -522,7 +522,7 @@ BOOL IsSystemRestoreEnabled () wchar_t szRegPath[MAX_PATH]; GetRestorePointRegKeyName (szRegPath, sizeof (szRegPath)); if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, szRegPath, 0, KEY_READ | KEY_WOW64_64KEY, &hKey) == ERROR_SUCCESS) - { + { if (IsOSAtLeast (WIN_VISTA)) { if ( (ERROR_SUCCESS == RegQueryValueEx (hKey, L"RPSessionInterval", NULL, NULL, (LPBYTE) &dwValue, &cbValue)) @@ -542,7 +542,7 @@ BOOL IsSystemRestoreEnabled () } } - + RegCloseKey (hKey); } @@ -569,7 +569,7 @@ void StatusMessage (HWND hwndDlg, char *stringId) SendMessageW (GetDlgItem (hwndDlg, IDC_LOG_WINDOW), LB_ADDSTRING, 0, (LPARAM) GetString (stringId)); - SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_SETTOPINDEX, + SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_SETTOPINDEX, SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_GETCOUNT, 0, 0) - 1, 0); } @@ -582,8 +582,8 @@ void StatusMessageParam (HWND hwndDlg, char *stringId, wchar_t *param) StringCbPrintfW (szTmp, sizeof(szTmp), L"%s %s", GetString (stringId), param); SendMessageW (GetDlgItem (hwndDlg, IDC_LOG_WINDOW), LB_ADDSTRING, 0, (LPARAM) szTmp); - - SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_SETTOPINDEX, + + SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_SETTOPINDEX, SendDlgItemMessage (hwndDlg, IDC_LOG_WINDOW, LB_GETCOUNT, 0, 0) - 1, 0); } @@ -807,11 +807,11 @@ BOOL DoFilesInstall (HWND hwndDlg, wchar_t *szDestDir) // Find the correct decompressed file in memory for (fileNo = 0; fileNo < NBR_COMPRESSED_FILES; fileNo++) { - // Write the file (stored in memory) directly to the destination location + // Write the file (stored in memory) directly to the destination location // (there will be no temporary files). if (wmemcmp ( - curFileName, - Decompressed_Files[fileNo].fileName, + curFileName, + Decompressed_Files[fileNo].fileName, min (wcslen (curFileName), (size_t) Decompressed_Files[fileNo].fileNameLength)) == 0) { // Dump filter driver cannot be installed to SysWOW64 directory @@ -825,7 +825,7 @@ BOOL DoFilesInstall (HWND hwndDlg, wchar_t *szDestDir) bResult = SaveBufferToFile ( (char *) Decompressed_Files[fileNo].fileContent, szTmp, - Decompressed_Files[fileNo].fileLength, + Decompressed_Files[fileNo].fileLength, FALSE, TRUE); @@ -876,8 +876,8 @@ BOOL DoFilesInstall (HWND hwndDlg, wchar_t *szDestDir) bResult = CopyFile (szTmp, servicePath.c_str(), FALSE); } - if (bResult && Is64BitOs () - && FileExists (favoritesLegacyFile.c_str()) + if (bResult && Is64BitOs () + && FileExists (favoritesLegacyFile.c_str()) && !FileExists (favoritesFile.c_str())) { // copy the favorites XML file to the native system directory @@ -1013,7 +1013,7 @@ err: { WIN32_FIND_DATA f; HANDLE h; - + SetCurrentDirectory (SetupFilesDir); h = FindFirstFile (L"Language.*.xml", &f); @@ -1145,7 +1145,7 @@ BOOL DoRegInstall (HWND hwndDlg, wchar_t *szDestDir, BOOL bInstallType) StringCbCopyW (szTmp, sizeof(szTmp), L"VeraCryptVolume"); if (RegSetValueEx (hkey, L"", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) goto error; - + RegCloseKey (hkey); hkey = 0; @@ -1160,7 +1160,7 @@ BOOL DoRegInstall (HWND hwndDlg, wchar_t *szDestDir, BOOL bInstallType) 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_WOW64_32KEY, NULL, &hkey, &dw) != ERROR_SUCCESS) goto error; - /* IMPORTANT: IF YOU CHANGE THIS IN ANY WAY, REVISE AND UPDATE SetInstallationPath() ACCORDINGLY! */ + /* IMPORTANT: IF YOU CHANGE THIS IN ANY WAY, REVISE AND UPDATE SetInstallationPath() ACCORDINGLY! */ StringCbPrintfW (szTmp, sizeof(szTmp), L"\"%sVeraCrypt Setup.exe\" /u", szDir); if (RegSetValueEx (hkey, L"UninstallString", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) goto error; @@ -1176,7 +1176,7 @@ BOOL DoRegInstall (HWND hwndDlg, wchar_t *szDestDir, BOOL bInstallType) StringCbCopyW (szTmp, sizeof(szTmp), _T(VERSION_STRING)); if (RegSetValueEx (hkey, L"DisplayVersion", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) goto error; - + StringCbCopyW (szTmp, sizeof(szTmp), L"VeraCrypt"); if (RegSetValueEx (hkey, L"DisplayName", 0, REG_SZ, (BYTE *) szTmp, (wcslen (szTmp) + 1) * sizeof (wchar_t)) != ERROR_SUCCESS) goto error; @@ -1200,7 +1200,7 @@ error: handleWin32Error (hwndDlg, SRC_POS); Error ("REG_INSTALL_FAILED", hwndDlg); } - + // Register COM servers for UAC if (IsOSAtLeast (WIN_VISTA)) { @@ -1239,7 +1239,7 @@ BOOL DoApplicationDataUninstall (HWND hwndDlg) StringCbPrintfW (path2, sizeof(path2), L"%s%s", path, TC_APPD_FILENAME_HISTORY); RemoveMessage (hwndDlg, path2); StatDeleteFile (path2, FALSE); - + // Delete configuration file StringCbPrintfW (path2, sizeof(path2), L"%s%s", path, TC_APPD_FILENAME_CONFIGURATION); RemoveMessage (hwndDlg, path2); @@ -1314,7 +1314,7 @@ BOOL DoRegUninstall (HWND hwndDlg, BOOL bRemoveDeprecated) RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume\\Shell"); RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume\\DefaultIcon"); RegDeleteKey (HKEY_LOCAL_MACHINE, L"Software\\Classes\\VeraCryptVolume"); - + if (!bRemoveDeprecated) { HKEY hKey; @@ -1333,7 +1333,7 @@ BOOL DoRegUninstall (HWND hwndDlg, BOOL bRemoveDeprecated) SearchAndDeleteRegistrySubString (HKEY_USERS, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.hc", NULL, TRUE, NULL); SearchAndDeleteRegistrySubString (HKEY_USERS, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Compatibility Assistant\\Persisted", L"VeraCrypt", TRUE, NULL); SearchAndDeleteRegistrySubString (HKEY_USERS, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartPage\\NewShortcuts", L"VeraCrypt", TRUE, NULL); - + if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SYSTEM", 0, KEY_ALL_ACCESS | WRITE_DAC | WRITE_OWNER, &hKey) == ERROR_SUCCESS) { SearchAndDeleteRegistrySubString (hKey, L"Enum\\Root\\LEGACY_VERACRYPT", NULL, TRUE, L"ControlSet"); @@ -1346,7 +1346,7 @@ BOOL DoRegUninstall (HWND hwndDlg, BOOL bRemoveDeprecated) SHChangeNotify (SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); } - + if (hAdvapiDll) FreeLibrary (hAdvapiDll); @@ -1623,7 +1623,7 @@ BOOL DoDriverUnload (HWND hwndDlg) EnumWindows (CloseTCWindowsEnum, (LPARAM) &TCWindowClosed); - if (TCWindowClosed) + if (TCWindowClosed) Sleep (2000); } @@ -1648,7 +1648,7 @@ BOOL DoDriverUnload (HWND hwndDlg) } else { - // Note that the driver may have already been unloaded during this session (e.g. retry after an error, etc.) so it is not + // Note that the driver may have already been unloaded during this session (e.g. retry after an error, etc.) so it is not // guaranteed that the user is installing VeraCrypt for the first time now (we also cannot know if the user has already // installed and used VeraCrypt on another system before). bPossiblyFirstTimeInstall = TRUE; @@ -1748,7 +1748,7 @@ BOOL DoShortcutsUninstall (HWND hwndDlg, wchar_t *szDestDir) RemoveMessage (hwndDlg, szTmp2); if (StatDeleteFile (szTmp2, FALSE) == FALSE) goto error; - + StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s%s", szLinkDir, L"\\VeraCrypt User's Guide.lnk"); StatDeleteFile (szTmp2, FALSE); @@ -1950,7 +1950,7 @@ static void SetSystemRestorePoint (HWND hwndDlg, BOOL finalize) static STATEMGRSTATUS SMgrStatus; static BOOL failed = FALSE; static BOOL (__stdcall *_SRSetRestorePoint)(PRESTOREPOINTINFO, PSTATEMGRSTATUS); - + if (!SystemRestoreDll) return; _SRSetRestorePoint = (BOOL (__stdcall *)(PRESTOREPOINTINFO, PSTATEMGRSTATUS))GetProcAddress (SystemRestoreDll,"SRSetRestorePointW"); @@ -1970,7 +1970,7 @@ static void SetSystemRestorePoint (HWND hwndDlg, BOOL finalize) RestPtInfo.llSequenceNumber = 0; StringCbCopyW (RestPtInfo.szDescription, sizeof(RestPtInfo.szDescription), bUninstall ? L"VeraCrypt uninstallation" : L"VeraCrypt installation"); - if(!_SRSetRestorePoint (&RestPtInfo, &SMgrStatus)) + if(!_SRSetRestorePoint (&RestPtInfo, &SMgrStatus)) { StatusMessage (hwndDlg, "FAILED_SYS_RESTORE"); failed = TRUE; @@ -1981,7 +1981,7 @@ static void SetSystemRestorePoint (HWND hwndDlg, BOOL finalize) RestPtInfo.dwEventType = END_SYSTEM_CHANGE; RestPtInfo.llSequenceNumber = SMgrStatus.llSequenceNumber; - if(!_SRSetRestorePoint(&RestPtInfo, &SMgrStatus)) + if(!_SRSetRestorePoint(&RestPtInfo, &SMgrStatus)) { StatusMessage (hwndDlg, "FAILED_SYS_RESTORE"); } @@ -2145,12 +2145,12 @@ void DoInstall (void *arg) } UpdateProgressBarProc(12); - + if (bSystemRestore) SetSystemRestorePoint (hwndDlg, FALSE); UpdateProgressBarProc(48); - + if (bDisableSwapFiles && IsPagingFileActive (FALSE)) { @@ -2167,7 +2167,7 @@ void DoInstall (void *arg) // Remove deprecated DoServiceUninstall (hwndDlg, L"VeraCryptService"); - + UpdateProgressBarProc(55); if (!SystemEncryptionUpdate) @@ -2348,7 +2348,7 @@ void SetInstallationPath (HWND hwndDlg) { /* VeraCrypt is not installed or it wasn't possible to determine where it is installed. */ - // Default "Program Files" path. + // Default "Program Files" path. SHGetSpecialFolderLocation (hwndDlg, CSIDL_PROGRAM_FILES, &itemList); SHGetPathFromIDList (itemList, path); @@ -2545,7 +2545,7 @@ int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpsz { if (!VerifyPackageIntegrity()) { - // Package corrupted + // Package corrupted exit (1); } bDevm = FALSE; @@ -2598,7 +2598,7 @@ int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpsz { /* Create the main dialog for install */ - DialogBoxParamW (hInstance, MAKEINTRESOURCEW (IDD_INSTL_DLG), NULL, (DLGPROC) MainDialogProc, + DialogBoxParamW (hInstance, MAKEINTRESOURCEW (IDD_INSTL_DLG), NULL, (DLGPROC) MainDialogProc, (LPARAM)lpszCommandLine); } else diff --git a/src/Setup/Setup.h b/src/Setup/Setup.h index da31f3cd..76cc7e9a 100644 --- a/src/Setup/Setup.h +++ b/src/Setup/Setup.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Setup/Setup.rc b/src/Setup/Setup.rc index bdb89be1..47d1d149 100644 --- a/src/Setup/Setup.rc +++ b/src/Setup/Setup.rc @@ -201,19 +201,19 @@ IDI_SETUP ICON "Setup.ico" // TEXTINCLUDE // -1 TEXTINCLUDE +1 TEXTINCLUDE BEGIN "resource.h\0" END -2 TEXTINCLUDE +2 TEXTINCLUDE BEGIN "#include ""afxres.h""\r\n" "#include ""..\\\\common\\\\resource.h""\r\n" "\0" END -3 TEXTINCLUDE +3 TEXTINCLUDE BEGIN "#include ""..\\\\common\\\\common.rc""\r\n" "\0" @@ -228,7 +228,7 @@ END // #ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO +GUIDELINES DESIGNINFO BEGIN IDD_UNINSTALL, DIALOG BEGIN diff --git a/src/Setup/Wizard.c b/src/Setup/Wizard.c index 42ea42c9..8c0f058c 100644 --- a/src/Setup/Wizard.c +++ b/src/Setup/Wizard.c @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 @@ -192,7 +192,7 @@ static int GetDonVal (int minVal, int maxVal) prngInitialized = TRUE; } - if (OsPrngAvailable && CryptGenRandom (hCryptProv, sizeof (buffer), buffer) != 0) + if (OsPrngAvailable && CryptGenRandom (hCryptProv, sizeof (buffer), buffer) != 0) { return ((int) ((double) *((uint16 *) buffer) / (0xFFFF+1) * (maxVal + 1 - minVal)) + minVal); } @@ -310,7 +310,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa case EXTRACTION_OPTIONS_PAGE: if (wcslen(WizardDestExtractPath) < 2) - { + { StringCbCopyW (WizardDestExtractPath, sizeof(WizardDestExtractPath), SetupFilesDir); StringCbCatNW (WizardDestExtractPath, sizeof(WizardDestExtractPath), L"VeraCrypt\\", ARRAYSIZE (WizardDestExtractPath) - wcslen (WizardDestExtractPath) - 1); } @@ -704,7 +704,7 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (nCurPageNo == DONATIONS_PAGE) { PAINTSTRUCT tmpPaintStruct; - HDC hdc = BeginPaint (hCurPage, &tmpPaintStruct); + HDC hdc = BeginPaint (hCurPage, &tmpPaintStruct); if (hdc == NULL) AbortProcessSilent (); @@ -736,13 +736,13 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa TextOutW (hdc, CompensateXDPI (258), CompensateYDPI (70), - DonText.c_str(), - DonText.length()); - - EndPaint (hCurPage, &tmpPaintStruct); + DonText.c_str(), + DonText.length()); + + EndPaint (hCurPage, &tmpPaintStruct); ReleaseDC (hCurPage, hdc); } - return 0; + return 0; } @@ -813,8 +813,8 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa InitDialog (hwndDlg); LocalizeDialog (hwndDlg, "IDD_INSTL_DLG"); - - // Resize the bitmap if the user has a non-default DPI + + // Resize the bitmap if the user has a non-default DPI if (ScreenDPI != USER_DEFAULT_SCREEN_DPI) { hbmWizardBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_SETUP_WIZARD), @@ -916,7 +916,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { Info ("TRAVELER_LIMITATIONS_NOTE", hwndDlg); - if (IsUacSupported() + if (IsUacSupported() && AskWarnYesNo ("TRAVELER_UAC_NOTE", hwndDlg) == IDNO) { return 1; @@ -1001,12 +1001,12 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa HWND hwndItem = GetDlgItem (MainDlg, IDC_MAIN_CONTENT_CANVAS); PAINTSTRUCT tmpPaintStruct; - HDC hdc = BeginPaint (hwndItem, &tmpPaintStruct); + HDC hdc = BeginPaint (hwndItem, &tmpPaintStruct); if (DonColorSchemeId != 2) { HBRUSH tmpBrush = CreateSolidBrush (DonBkgColor); - + RECT trect; trect.left = CompensateXDPI (1); @@ -1016,11 +1016,11 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa FillRect (hdc, &trect, tmpBrush); } - - EndPaint(hwndItem, &tmpPaintStruct); + + EndPaint(hwndItem, &tmpPaintStruct); ReleaseDC (hwndItem, hdc); } - return 0; + return 0; @@ -1043,9 +1043,9 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa case TC_APPMSG_INSTALL_SUCCESS: - + /* Installation completed successfully */ - + bInProgress = FALSE; nCurPageNo = DONATIONS_PAGE; @@ -1065,7 +1065,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa return 1; case TC_APPMSG_INSTALL_FAILURE: - + /* Installation failed */ bInProgress = FALSE; @@ -1086,7 +1086,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa return 1; case TC_APPMSG_EXTRACTION_SUCCESS: - + /* Extraction completed successfully */ UpdateProgressBarProc(100); @@ -1115,7 +1115,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa return 1; case TC_APPMSG_EXTRACTION_FAILURE: - + /* Extraction failed */ bInProgress = FALSE; diff --git a/src/Setup/Wizard.h b/src/Setup/Wizard.h index 3d178e24..f52e32d6 100644 --- a/src/Setup/Wizard.h +++ b/src/Setup/Wizard.h @@ -1,11 +1,11 @@ /* Legal Notice: Some portions of the source code contained in this file were - derived from the source code of TrueCrypt 7.1a, which is - Copyright (c) 2003-2012 TrueCrypt Developers Association and which is + derived from the source code of TrueCrypt 7.1a, which is + Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux - and which is governed by the 'License Agreement for Encryption for the Masses' - Modifications and additions to the original source code (contained in this file) + and which is governed by the 'License Agreement for Encryption for the Masses' + 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 diff --git a/src/Volume/Cipher.cpp b/src/Volume/Cipher.cpp index 7178250e..4acea91e 100644 --- a/src/Volume/Cipher.cpp +++ b/src/Volume/Cipher.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -207,7 +207,7 @@ namespace VeraCrypt { serpent_encrypt (data, data, ScheduledKey); } - + size_t CipherSerpent::GetScheduledKeySize () const { return 140*4; diff --git a/src/Volume/Cipher.h b/src/Volume/Cipher.h index c06d65d8..866a2c2c 100644 --- a/src/Volume/Cipher.h +++ b/src/Volume/Cipher.h @@ -3,7 +3,7 @@ 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) + 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 @@ -93,7 +93,7 @@ namespace VeraCrypt TC_JOIN (Cipher,NAME) (const TC_JOIN (Cipher,NAME) &); \ TC_JOIN (Cipher,NAME) &operator= (const TC_JOIN (Cipher,NAME) &); \ } - + #define TC_CIPHER_ADD_METHODS \ virtual void DecryptBlocks (byte *data, size_t blockCount) const; \ virtual void EncryptBlocks (byte *data, size_t blockCount) const; \ @@ -109,7 +109,7 @@ namespace VeraCrypt #undef TC_CIPHER - + #define TC_EXCEPTION(NAME) TC_EXCEPTION_DECL(NAME,CipherException) #undef TC_EXCEPTION_SET diff --git a/src/Volume/Crc32.h b/src/Volume/Crc32.h index 4c8b9b4b..eb622807 100644 --- a/src/Volume/Crc32.h +++ b/src/Volume/Crc32.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/EncryptionAlgorithm.cpp b/src/Volume/EncryptionAlgorithm.cpp index 18d12602..77ed8807 100644 --- a/src/Volume/EncryptionAlgorithm.cpp +++ b/src/Volume/EncryptionAlgorithm.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -60,7 +60,7 @@ namespace VeraCrypt EncryptionAlgorithmList EncryptionAlgorithm::GetAvailableAlgorithms () { EncryptionAlgorithmList l; - + l.push_back (shared_ptr (new AES ())); l.push_back (shared_ptr (new Serpent ())); l.push_back (shared_ptr (new Twofish ())); @@ -98,7 +98,7 @@ namespace VeraCrypt return keySize; } - + size_t EncryptionAlgorithm::GetMaxBlockSize () const { size_t blockSize = 0; @@ -148,10 +148,10 @@ namespace VeraCrypt name += wstring (L"("); else name += wstring (L"-"); - name += c.GetName(); + name += c.GetName(); } } - + if (forGuiDisplay && depth) { for (int i = 0; i < depth; i++) @@ -177,7 +177,7 @@ namespace VeraCrypt return supported; } - + bool EncryptionAlgorithm::IsModeSupported (const shared_ptr mode) const { return IsModeSupported (*mode); @@ -191,7 +191,7 @@ namespace VeraCrypt mode->SetCiphers (Ciphers); Mode = mode; } - + void EncryptionAlgorithm::SetKey (const ConstBufferPtr &key) { if (Ciphers.size() < 1) diff --git a/src/Volume/EncryptionAlgorithm.h b/src/Volume/EncryptionAlgorithm.h index c4c18d59..f61358a2 100644 --- a/src/Volume/EncryptionAlgorithm.h +++ b/src/Volume/EncryptionAlgorithm.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/EncryptionMode.cpp b/src/Volume/EncryptionMode.cpp index 4a54e7c3..f87bee3f 100644 --- a/src/Volume/EncryptionMode.cpp +++ b/src/Volume/EncryptionMode.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/EncryptionMode.h b/src/Volume/EncryptionMode.h index 7d484191..de93b991 100644 --- a/src/Volume/EncryptionMode.h +++ b/src/Volume/EncryptionMode.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/EncryptionModeXTS.cpp b/src/Volume/EncryptionModeXTS.cpp index 569be747..4d713f74 100644 --- a/src/Volume/EncryptionModeXTS.cpp +++ b/src/Volume/EncryptionModeXTS.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -58,7 +58,7 @@ namespace VeraCrypt the shift of the highest byte results in a carry, 135 is XORed into the lowest byte. The value 135 is derived from the modulus of the Galois Field (x^128+x^7+x^2+x+1). */ - // Convert the 64-bit data unit number into a little-endian 16-byte array. + // Convert the 64-bit data unit number into a little-endian 16-byte array. // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. dataUnitNo = startDataUnitNo; *((uint64 *) byteBufUnitNo) = Endian::Little (dataUnitNo); @@ -80,7 +80,7 @@ namespace VeraCrypt whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; whiteningValuePtr64 = (uint64 *) whiteningValue; - // Encrypt the data unit number using the secondary key (in order to generate the first + // Encrypt the data unit number using the secondary key (in order to generate the first // whitening value for this data unit) *whiteningValuePtr64 = *((uint64 *) byteBufUnitNo); *(whiteningValuePtr64 + 1) = 0; @@ -104,21 +104,21 @@ namespace VeraCrypt // Little-endian platforms - finalCarry = + finalCarry = (*whiteningValuePtr64 & 0x8000000000000000ULL) ? 135 : 0; *whiteningValuePtr64-- <<= 1; if (*whiteningValuePtr64 & 0x8000000000000000ULL) - *(whiteningValuePtr64 + 1) |= 1; + *(whiteningValuePtr64 + 1) |= 1; *whiteningValuePtr64 <<= 1; #else // Big-endian platforms - finalCarry = + finalCarry = (*whiteningValuePtr64 & 0x80) ? 135 : 0; @@ -127,7 +127,7 @@ namespace VeraCrypt whiteningValuePtr64--; if (*whiteningValuePtr64 & 0x80) - *(whiteningValuePtr64 + 1) |= 0x0100000000000000ULL; + *(whiteningValuePtr64 + 1) |= 0x0100000000000000ULL; *whiteningValuePtr64 = Endian::Little (Endian::Little (*whiteningValuePtr64) << 1); #endif @@ -174,12 +174,12 @@ namespace VeraCrypt { EncryptBuffer (data, sectorCount * sectorSize, sectorIndex * sectorSize / ENCRYPTION_DATA_UNIT_SIZE); } - + size_t EncryptionModeXTS::GetKeySize () const { if (Ciphers.empty()) throw NotInitialized (SRC_POS); - + size_t keySize = 0; foreach_ref (const Cipher &cipher, SecondaryCiphers) { @@ -225,7 +225,7 @@ namespace VeraCrypt startDataUnitNo += SectorOffset; - // Convert the 64-bit data unit number into a little-endian 16-byte array. + // Convert the 64-bit data unit number into a little-endian 16-byte array. // Note that as we are converting a 64-bit number into a 16-byte array we can always zero the last 8 bytes. dataUnitNo = startDataUnitNo; *((uint64 *) byteBufUnitNo) = Endian::Little (dataUnitNo); @@ -247,7 +247,7 @@ namespace VeraCrypt whiteningValuesPtr64 = finalInt64WhiteningValuesPtr; whiteningValuePtr64 = (uint64 *) whiteningValue; - // Encrypt the data unit number using the secondary key (in order to generate the first + // Encrypt the data unit number using the secondary key (in order to generate the first // whitening value for this data unit) *whiteningValuePtr64 = *((uint64 *) byteBufUnitNo); *(whiteningValuePtr64 + 1) = 0; @@ -271,21 +271,21 @@ namespace VeraCrypt // Little-endian platforms - finalCarry = + finalCarry = (*whiteningValuePtr64 & 0x8000000000000000ULL) ? 135 : 0; *whiteningValuePtr64-- <<= 1; if (*whiteningValuePtr64 & 0x8000000000000000ULL) - *(whiteningValuePtr64 + 1) |= 1; + *(whiteningValuePtr64 + 1) |= 1; *whiteningValuePtr64 <<= 1; #else // Big-endian platforms - finalCarry = + finalCarry = (*whiteningValuePtr64 & 0x80) ? 135 : 0; @@ -294,7 +294,7 @@ namespace VeraCrypt whiteningValuePtr64--; if (*whiteningValuePtr64 & 0x80) - *(whiteningValuePtr64 + 1) |= 0x0100000000000000ULL; + *(whiteningValuePtr64 + 1) |= 0x0100000000000000ULL; *whiteningValuePtr64 = Endian::Little (Endian::Little (*whiteningValuePtr64) << 1); #endif @@ -363,7 +363,7 @@ namespace VeraCrypt if (!SecondaryCiphers.empty()) SetSecondaryCipherKeys(); } - + void EncryptionModeXTS::SetSecondaryCipherKeys () { size_t keyOffset = 0; diff --git a/src/Volume/EncryptionModeXTS.h b/src/Volume/EncryptionModeXTS.h index 9b1ddd4c..0b01f1d5 100644 --- a/src/Volume/EncryptionModeXTS.h +++ b/src/Volume/EncryptionModeXTS.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/EncryptionTest.cpp b/src/Volume/EncryptionTest.cpp index 90f9178c..26b5deab 100644 --- a/src/Volume/EncryptionTest.cpp +++ b/src/Volume/EncryptionTest.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -52,7 +52,7 @@ namespace VeraCrypt { { { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, }, { @@ -151,7 +151,7 @@ namespace VeraCrypt { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff }, 0, - { + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, @@ -167,9 +167,9 @@ namespace VeraCrypt 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, - { + { 0x1c, 0x3b, 0x3a, 0x10, 0x2f, 0x77, 0x03, 0x86, 0xe4, 0x83, 0x6c, 0x99, 0xe3, 0x70, 0xcf, 0x9b, 0xea, 0x00, 0x80, 0x3f, 0x5e, 0x48, 0x23, 0x57, 0xa4, 0xae, 0x12, 0xd4, 0x14, 0xa3, 0xe6, 0x3b, 0x5d, 0x31, 0xe2, 0x76, 0xf8, 0xfe, 0x4a, 0x8d, 0x66, 0xb3, 0x17, 0xf9, 0xac, 0x68, 0x3f, 0x44, 0x68, 0x0a, 0x86, 0xac, 0x35, 0xad, 0xfc, 0x33, 0x45, 0xbe, 0xfe, 0xcb, 0x4b, 0xb1, 0x88, 0xfd, 0x57, 0x76, 0x92, 0x6c, 0x49, 0xa3, 0x09, 0x5e, 0xb1, 0x08, 0xfd, 0x10, 0x98, 0xba, 0xec, 0x70, 0xaa, 0xa6, 0x69, 0x99, 0xa7, 0x2a, 0x82, 0xf2, 0x7d, 0x84, 0x8b, 0x21, 0xd4, 0xa7, 0x41, 0xb0, @@ -185,7 +185,7 @@ namespace VeraCrypt 0x6e, 0x33, 0x3b, 0x93, 0xeb, 0x4a, 0xff, 0x04, 0x79, 0xda, 0x9a, 0x41, 0x0e, 0x44, 0x50, 0xe0, 0xdd, 0x7a, 0xe4, 0xc6, 0xe2, 0x91, 0x09, 0x00, 0x57, 0x5d, 0xa4, 0x01, 0xfc, 0x07, 0x05, 0x9f, 0x64, 0x5e, 0x8b, 0x7e, 0x9b, 0xfd, 0xef, 0x33, 0x94, 0x30, 0x54, 0xff, 0x84, 0x01, 0x14, 0x93, 0xc2, 0x7b, 0x34, 0x29, 0xea, 0xed, 0xb4, 0xed, 0x53, 0x76, 0x44, 0x1a, 0x77, 0xed, 0x43, 0x85, 0x1a, 0xd7, 0x7f, 0x16, 0xf5, 0x41, 0xdf, 0xd2, 0x69, 0xd5, 0x0d, 0x6a, 0x5f, 0x14, 0xfb, 0x0a, 0xab, 0x1c, 0xbb, 0x4c, 0x15, 0x50, 0xbe, 0x97, 0xf7, 0xab, 0x40, 0x66, 0x19, 0x3c, 0x4c, 0xaa, - 0x77, 0x3d, 0xad, 0x38, 0x01, 0x4b, 0xd2, 0x09, 0x2f, 0xa7, 0x55, 0xc8, 0x24, 0xbb, 0x5e, 0x54, 0xc4, 0xf3, 0x6f, 0xfd, 0xa9, 0xfc, 0xea, 0x70, 0xb9, 0xc6, 0xe6, 0x93, 0xe1, 0x48, 0xc1, 0x51 + 0x77, 0x3d, 0xad, 0x38, 0x01, 0x4b, 0xd2, 0x09, 0x2f, 0xa7, 0x55, 0xc8, 0x24, 0xbb, 0x5e, 0x54, 0xc4, 0xf3, 0x6f, 0xfd, 0xa9, 0xfc, 0xea, 0x70, 0xb9, 0xc6, 0xe6, 0x93, 0xe1, 0x48, 0xc1, 0x51 } }, { @@ -194,8 +194,8 @@ namespace VeraCrypt { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff }, - 0, - { + 0, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, @@ -211,9 +211,9 @@ namespace VeraCrypt 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, - { + { 0x77, 0xa3, 0x12, 0x51, 0x61, 0x8a, 0x15, 0xe6, 0xb9, 0x2d, 0x1d, 0x66, 0xdf, 0xfe, 0x7b, 0x50, 0xb5, 0x0b, 0xad, 0x55, 0x23, 0x05, 0xba, 0x02, 0x17, 0xa6, 0x10, 0x68, 0x8e, 0xff, 0x7e, 0x11, 0xe1, 0xd0, 0x22, 0x54, 0x38, 0xe0, 0x93, 0x24, 0x2d, 0x6d, 0xb2, 0x74, 0xfd, 0xe8, 0x01, 0xd4, 0xca, 0xe0, 0x6f, 0x20, 0x92, 0xc7, 0x28, 0xb2, 0x47, 0x85, 0x59, 0xdf, 0x58, 0xe8, 0x37, 0xc2, 0x46, 0x9e, 0xe4, 0xa4, 0xfa, 0x79, 0x4e, 0x4b, 0xbc, 0x7f, 0x39, 0xbc, 0x02, 0x6e, 0x3c, 0xb7, 0x2c, 0x33, 0xb0, 0x88, 0x8f, 0x25, 0xb4, 0xac, 0xf5, 0x6a, 0x2a, 0x98, 0x04, 0xf1, 0xce, 0x6d, @@ -229,7 +229,7 @@ namespace VeraCrypt 0x09, 0x4f, 0x7c, 0x45, 0x3b, 0x7f, 0xf8, 0x7c, 0xb5, 0xbb, 0x36, 0xb7, 0xc7, 0x9e, 0xfb, 0x08, 0x72, 0xd1, 0x70, 0x58, 0xb8, 0x3b, 0x15, 0xab, 0x08, 0x66, 0xad, 0x8a, 0x58, 0x65, 0x6c, 0x5a, 0x7e, 0x20, 0xdb, 0xdf, 0x30, 0x8b, 0x24, 0x61, 0xd9, 0x7c, 0x0e, 0xc0, 0x02, 0x4a, 0x27, 0x15, 0x05, 0x52, 0x49, 0xcf, 0x3b, 0x47, 0x8d, 0xdd, 0x47, 0x40, 0xde, 0x65, 0x4f, 0x75, 0xca, 0x68, 0x6e, 0x0d, 0x73, 0x45, 0xc6, 0x9e, 0xd5, 0x0c, 0xdc, 0x2a, 0x8b, 0x33, 0x2b, 0x1f, 0x88, 0x24, 0x10, 0x8a, 0xc9, 0x37, 0xeb, 0x05, 0x05, 0x85, 0x60, 0x8e, 0xe7, 0x34, 0x09, 0x7f, 0xc0, 0x90, - 0x54, 0xfb, 0xff, 0x89, 0xee, 0xae, 0xea, 0x79, 0x1f, 0x4a, 0x7a, 0xb1, 0xf9, 0x86, 0x82, 0x94, 0xa4, 0xf9, 0xe2, 0x7b, 0x42, 0xaf, 0x81, 0x00, 0xcb, 0x9d, 0x59, 0xce, 0xf9, 0x64, 0x58, 0x03 + 0x54, 0xfb, 0xff, 0x89, 0xee, 0xae, 0xea, 0x79, 0x1f, 0x4a, 0x7a, 0xb1, 0xf9, 0x86, 0x82, 0x94, 0xa4, 0xf9, 0xe2, 0x7b, 0x42, 0xaf, 0x81, 0x00, 0xcb, 0x9d, 0x59, 0xce, 0xf9, 0x64, 0x58, 0x03 } }, { @@ -238,8 +238,8 @@ namespace VeraCrypt { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff }, - 0, - { + 0, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, @@ -255,9 +255,9 @@ namespace VeraCrypt 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, - { + { 0xe3, 0x87, 0xaa, 0xa5, 0x8b, 0xa4, 0x83, 0xaf, 0xa7, 0xe8, 0xeb, 0x46, 0x97, 0x78, 0x31, 0x7e, 0xcf, 0x4c, 0xf5, 0x73, 0xaa, 0x9d, 0x4e, 0xac, 0x23, 0xf2, 0xcd, 0xf9, 0x14, 0xe4, 0xe2, 0x00, 0xa8, 0xb4, 0x90, 0xe4, 0x2e, 0xe6, 0x46, 0x80, 0x2d, 0xc6, 0xee, 0x2b, 0x47, 0x1b, 0x27, 0x81, 0x95, 0xd6, 0x09, 0x18, 0xec, 0xec, 0xb4, 0x4b, 0xf7, 0x99, 0x66, 0xf8, 0x3f, 0xab, 0xa0, 0x49, 0x92, 0x98, 0xeb, 0xc6, 0x99, 0xc0, 0xc8, 0x63, 0x47, 0x15, 0xa3, 0x20, 0xbb, 0x4f, 0x07, 0x5d, 0x62, 0x2e, 0x74, 0xc8, 0xc9, 0x32, 0x00, 0x4f, 0x25, 0xb4, 0x1e, 0x36, 0x10, 0x25, 0xb5, 0xa8, @@ -273,7 +273,7 @@ namespace VeraCrypt 0xf0, 0x8a, 0xd7, 0xba, 0x89, 0x21, 0x28, 0x7e, 0x3b, 0xbe, 0xe3, 0x1b, 0x76, 0x7b, 0xe0, 0x6a, 0x0e, 0x70, 0x5c, 0x86, 0x4a, 0x76, 0x91, 0x37, 0xdf, 0x28, 0x29, 0x22, 0x83, 0xea, 0x81, 0xa2, 0x48, 0x02, 0x41, 0xb4, 0x4d, 0x99, 0x21, 0xcd, 0xbe, 0xc1, 0xbc, 0x28, 0xdc, 0x1f, 0xda, 0x11, 0x4b, 0xd8, 0xe5, 0x21, 0x7a, 0xc9, 0xd8, 0xeb, 0xaf, 0xa7, 0x20, 0xe9, 0xda, 0x4f, 0x9a, 0xce, 0x23, 0x1c, 0xc9, 0x49, 0xe5, 0xb9, 0x6f, 0xe7, 0x6f, 0xfc, 0x21, 0x06, 0x3f, 0xdd, 0xc8, 0x3a, 0x6b, 0x86, 0x79, 0xc0, 0x0d, 0x35, 0xe0, 0x95, 0x76, 0xa8, 0x75, 0x30, 0x5b, 0xed, 0x5f, 0x36, - 0xed, 0x24, 0x2c, 0x89, 0x00, 0xdd, 0x1f, 0xa9, 0x65, 0xbc, 0x95, 0x0d, 0xfc, 0xe0, 0x9b, 0x13, 0x22, 0x63, 0xa1, 0xee, 0xf5, 0x2d, 0xd6, 0x88, 0x8c, 0x30, 0x9f, 0x5a, 0x7d, 0x71, 0x28, 0x26 + 0xed, 0x24, 0x2c, 0x89, 0x00, 0xdd, 0x1f, 0xa9, 0x65, 0xbc, 0x95, 0x0d, 0xfc, 0xe0, 0x9b, 0x13, 0x22, 0x63, 0xa1, 0xee, 0xf5, 0x2d, 0xd6, 0x88, 0x8c, 0x30, 0x9f, 0x5a, 0x7d, 0x71, 0x28, 0x26 } }, { @@ -282,8 +282,8 @@ namespace VeraCrypt { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, { 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff }, - 0, - { + 0, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, @@ -299,9 +299,9 @@ namespace VeraCrypt 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, - { + { 0xbf, 0x53, 0xd2, 0xda, 0xde, 0x78, 0xe8, 0x22, 0xa4, 0xd9, 0x49, 0xa9, 0xbc, 0x67, 0x66, 0xb0, 0x1b, 0x06, 0xa8, 0xef, 0x70, 0xd2, 0x67, 0x48, 0xc6, 0xa7, 0xfc, 0x36, 0xd8, 0x0a, 0xe4, 0xc5, 0x52, 0x0f, 0x7c, 0x4a, 0xb0, 0xac, 0x85, 0x44, 0x42, 0x4f, 0xa4, 0x05, 0x16, 0x2f, 0xef, 0x5a, 0x6b, 0x7f, 0x22, 0x94, 0x98, 0x06, 0x36, 0x18, 0xd3, 0x9f, 0x00, 0x03, 0xcb, 0x5f, 0xb8, 0xd1, 0xc8, 0x6b, 0x64, 0x34, 0x97, 0xda, 0x1f, 0xf9, 0x45, 0xc8, 0xd3, 0xbe, 0xde, 0xca, 0x4f, 0x47, 0x97, 0x02, 0xa7, 0xa7, 0x35, 0xf0, 0x43, 0xdd, 0xb1, 0xd6, 0xaa, 0xad, 0xe3, 0xc4, 0xa0, 0xac, @@ -317,7 +317,7 @@ namespace VeraCrypt 0x77, 0xad, 0x22, 0x00, 0x0f, 0x1d, 0x50, 0x78, 0xf6, 0xb8, 0x66, 0x31, 0x8c, 0x66, 0x8f, 0x1a, 0xd0, 0x3d, 0x5a, 0x5f, 0xce, 0xd5, 0x21, 0x9f, 0x2e, 0xab, 0xbd, 0x0a, 0xa5, 0xc0, 0xf4, 0x60, 0xd1, 0x83, 0xf0, 0x44, 0x04, 0xa0, 0xd6, 0xf4, 0x69, 0x55, 0x8e, 0x81, 0xfa, 0xb2, 0x4a, 0x16, 0x79, 0x05, 0xab, 0x4c, 0x78, 0x78, 0x50, 0x2a, 0xd3, 0xe3, 0x8f, 0xdb, 0xe6, 0x2a, 0x41, 0x55, 0x6c, 0xec, 0x37, 0x32, 0x57, 0x59, 0x53, 0x3c, 0xe8, 0xf2, 0x5f, 0x36, 0x7c, 0x87, 0xbb, 0x55, 0x78, 0xd6, 0x67, 0xae, 0x93, 0xf9, 0xe2, 0xfd, 0x99, 0xbc, 0xbc, 0x5f, 0x2f, 0xbb, 0xa8, 0x8c, - 0xf6, 0x51, 0x61, 0x39, 0x42, 0x0f, 0xcf, 0xf3, 0xb7, 0x36, 0x1d, 0x86, 0x32, 0x2c, 0x4b, 0xd8, 0x4c, 0x82, 0xf3, 0x35, 0xab, 0xb1, 0x52, 0xc4, 0xa9, 0x34, 0x11, 0x37, 0x3a, 0xaa, 0x82, 0x20 + 0xf6, 0x51, 0x61, 0x39, 0x42, 0x0f, 0xcf, 0xf3, 0xb7, 0x36, 0x1d, 0x86, 0x32, 0x2c, 0x4b, 0xd8, 0x4c, 0x82, 0xf3, 0x35, 0xab, 0xb1, 0x52, 0xc4, 0xa9, 0x34, 0x11, 0x37, 0x3a, 0xaa, 0x82, 0x20 } }, { @@ -326,46 +326,46 @@ namespace VeraCrypt { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27 }, { 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92 }, { 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff }, - 0, - { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff + 0, + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }, - { - 0x64, 0x49, 0x7e, 0x5a, 0x83, 0x1e, 0x4a, 0x93, 0x2c, 0x09, 0xbe, 0x3e, 0x53, 0x93, 0x37, 0x6d, 0xaa, 0x59, 0x95, 0x48, 0xb8, 0x16, 0x03, 0x1d, 0x22, 0x4b, 0xbf, 0x50, 0xa8, 0x18, 0xed, 0x23, - 0x50, 0xea, 0xe7, 0xe9, 0x60, 0x87, 0xc8, 0xa0, 0xdb, 0x51, 0xad, 0x29, 0x0b, 0xd0, 0x0c, 0x1a, 0xc1, 0x62, 0x08, 0x57, 0x63, 0x5b, 0xf2, 0x46, 0xc1, 0x76, 0xab, 0x46, 0x3b, 0xe3, 0x0b, 0x80, - 0x8d, 0xa5, 0x48, 0x08, 0x1a, 0xc8, 0x47, 0xb1, 0x58, 0xe1, 0x26, 0x4b, 0xe2, 0x5b, 0xb0, 0x91, 0x0b, 0xbc, 0x92, 0x64, 0x71, 0x08, 0x08, 0x94, 0x15, 0xd4, 0x5f, 0xab, 0x1b, 0x3d, 0x26, 0x04, - 0xe8, 0xa8, 0xef, 0xf1, 0xae, 0x40, 0x20, 0xcf, 0xa3, 0x99, 0x36, 0xb6, 0x68, 0x27, 0xb2, 0x3f, 0x37, 0x1b, 0x92, 0x20, 0x0b, 0xe9, 0x02, 0x51, 0xe6, 0xd7, 0x3c, 0x5f, 0x86, 0xde, 0x5f, 0xd4, - 0xa9, 0x50, 0x78, 0x19, 0x33, 0xd7, 0x9a, 0x28, 0x27, 0x2b, 0x78, 0x2a, 0x2e, 0xc3, 0x13, 0xef, 0xdf, 0xcc, 0x06, 0x28, 0xf4, 0x3d, 0x74, 0x4c, 0x2d, 0xc2, 0xff, 0x3d, 0xcb, 0x66, 0x99, 0x9b, - 0x50, 0xc7, 0xca, 0x89, 0x5b, 0x0c, 0x64, 0x79, 0x1e, 0xea, 0xa5, 0xf2, 0x94, 0x99, 0xfb, 0x1c, 0x02, 0x6f, 0x84, 0xce, 0x5b, 0x5c, 0x72, 0xba, 0x10, 0x83, 0xcd, 0xdb, 0x5c, 0xe4, 0x54, 0x34, - 0x63, 0x16, 0x65, 0xc3, 0x33, 0xb6, 0x0b, 0x11, 0x59, 0x3f, 0xb2, 0x53, 0xc5, 0x17, 0x9a, 0x2c, 0x8d, 0xb8, 0x13, 0x78, 0x2a, 0x00, 0x48, 0x56, 0xa1, 0x65, 0x30, 0x11, 0xe9, 0x3f, 0xb6, 0xd8, - 0x76, 0xc1, 0x83, 0x66, 0xdd, 0x86, 0x83, 0xf5, 0x34, 0x12, 0xc0, 0xc1, 0x80, 0xf9, 0xc8, 0x48, 0x59, 0x2d, 0x59, 0x3f, 0x86, 0x09, 0xca, 0x73, 0x63, 0x17, 0xd3, 0x56, 0xe1, 0x3e, 0x2b, 0xff, - 0x3a, 0x9f, 0x59, 0xcd, 0x9a, 0xeb, 0x19, 0xcd, 0x48, 0x25, 0x93, 0xd8, 0xc4, 0x61, 0x28, 0xbb, 0x32, 0x42, 0x3b, 0x37, 0xa9, 0xad, 0xfb, 0x48, 0x2b, 0x99, 0x45, 0x3f, 0xbe, 0x25, 0xa4, 0x1b, - 0xf6, 0xfe, 0xb4, 0xaa, 0x0b, 0xef, 0x5e, 0xd2, 0x4b, 0xf7, 0x3c, 0x76, 0x29, 0x78, 0x02, 0x54, 0x82, 0xc1, 0x31, 0x15, 0xe4, 0x01, 0x5a, 0xac, 0x99, 0x2e, 0x56, 0x13, 0xa3, 0xb5, 0xc2, 0xf6, - 0x85, 0xb8, 0x47, 0x95, 0xcb, 0x6e, 0x9b, 0x26, 0x56, 0xd8, 0xc8, 0x81, 0x57, 0xe5, 0x2c, 0x42, 0xf9, 0x78, 0xd8, 0x63, 0x4c, 0x43, 0xd0, 0x6f, 0xea, 0x92, 0x8f, 0x28, 0x22, 0xe4, 0x65, 0xaa, - 0x65, 0x76, 0xe9, 0xbf, 0x41, 0x93, 0x84, 0x50, 0x6c, 0xc3, 0xce, 0x3c, 0x54, 0xac, 0x1a, 0x6f, 0x67, 0xdc, 0x66, 0xf3, 0xb3, 0x01, 0x91, 0xe6, 0x98, 0x38, 0x0b, 0xc9, 0x99, 0xb0, 0x5a, 0xbc, - 0xe1, 0x9d, 0xc0, 0xc6, 0xdc, 0xc2, 0xdd, 0x00, 0x1e, 0xc5, 0x35, 0xba, 0x18, 0xde, 0xb2, 0xdf, 0x1a, 0x10, 0x10, 0x23, 0x10, 0x83, 0x18, 0xc7, 0x5d, 0xc9, 0x86, 0x11, 0xa0, 0x9d, 0xc4, 0x8a, - 0x0a, 0xcd, 0xec, 0x67, 0x6f, 0xab, 0xdf, 0x22, 0x2f, 0x07, 0xe0, 0x26, 0xf0, 0x59, 0xb6, 0x72, 0xb5, 0x6e, 0x5c, 0xbc, 0x8e, 0x1d, 0x21, 0xbb, 0xd8, 0x67, 0xdd, 0x92, 0x72, 0x12, 0x05, 0x46, - 0x81, 0xd7, 0x0e, 0xa7, 0x37, 0x13, 0x4c, 0xdf, 0xce, 0x93, 0xb6, 0xf8, 0x2a, 0xe2, 0x24, 0x23, 0x27, 0x4e, 0x58, 0xa0, 0x82, 0x1c, 0xc5, 0x50, 0x2e, 0x2d, 0x0a, 0xb4, 0x58, 0x5e, 0x94, 0xde, - 0x69, 0x75, 0xbe, 0x5e, 0x0b, 0x4e, 0xfc, 0xe5, 0x1c, 0xd3, 0xe7, 0x0c, 0x25, 0xa1, 0xfb, 0xbb, 0xd6, 0x09, 0xd2, 0x73, 0xad, 0x5b, 0x0d, 0x59, 0x63, 0x1c, 0x53, 0x1f, 0x6a, 0x0a, 0x57, 0xb9 + { + 0x64, 0x49, 0x7e, 0x5a, 0x83, 0x1e, 0x4a, 0x93, 0x2c, 0x09, 0xbe, 0x3e, 0x53, 0x93, 0x37, 0x6d, 0xaa, 0x59, 0x95, 0x48, 0xb8, 0x16, 0x03, 0x1d, 0x22, 0x4b, 0xbf, 0x50, 0xa8, 0x18, 0xed, 0x23, + 0x50, 0xea, 0xe7, 0xe9, 0x60, 0x87, 0xc8, 0xa0, 0xdb, 0x51, 0xad, 0x29, 0x0b, 0xd0, 0x0c, 0x1a, 0xc1, 0x62, 0x08, 0x57, 0x63, 0x5b, 0xf2, 0x46, 0xc1, 0x76, 0xab, 0x46, 0x3b, 0xe3, 0x0b, 0x80, + 0x8d, 0xa5, 0x48, 0x08, 0x1a, 0xc8, 0x47, 0xb1, 0x58, 0xe1, 0x26, 0x4b, 0xe2, 0x5b, 0xb0, 0x91, 0x0b, 0xbc, 0x92, 0x64, 0x71, 0x08, 0x08, 0x94, 0x15, 0xd4, 0x5f, 0xab, 0x1b, 0x3d, 0x26, 0x04, + 0xe8, 0xa8, 0xef, 0xf1, 0xae, 0x40, 0x20, 0xcf, 0xa3, 0x99, 0x36, 0xb6, 0x68, 0x27, 0xb2, 0x3f, 0x37, 0x1b, 0x92, 0x20, 0x0b, 0xe9, 0x02, 0x51, 0xe6, 0xd7, 0x3c, 0x5f, 0x86, 0xde, 0x5f, 0xd4, + 0xa9, 0x50, 0x78, 0x19, 0x33, 0xd7, 0x9a, 0x28, 0x27, 0x2b, 0x78, 0x2a, 0x2e, 0xc3, 0x13, 0xef, 0xdf, 0xcc, 0x06, 0x28, 0xf4, 0x3d, 0x74, 0x4c, 0x2d, 0xc2, 0xff, 0x3d, 0xcb, 0x66, 0x99, 0x9b, + 0x50, 0xc7, 0xca, 0x89, 0x5b, 0x0c, 0x64, 0x79, 0x1e, 0xea, 0xa5, 0xf2, 0x94, 0x99, 0xfb, 0x1c, 0x02, 0x6f, 0x84, 0xce, 0x5b, 0x5c, 0x72, 0xba, 0x10, 0x83, 0xcd, 0xdb, 0x5c, 0xe4, 0x54, 0x34, + 0x63, 0x16, 0x65, 0xc3, 0x33, 0xb6, 0x0b, 0x11, 0x59, 0x3f, 0xb2, 0x53, 0xc5, 0x17, 0x9a, 0x2c, 0x8d, 0xb8, 0x13, 0x78, 0x2a, 0x00, 0x48, 0x56, 0xa1, 0x65, 0x30, 0x11, 0xe9, 0x3f, 0xb6, 0xd8, + 0x76, 0xc1, 0x83, 0x66, 0xdd, 0x86, 0x83, 0xf5, 0x34, 0x12, 0xc0, 0xc1, 0x80, 0xf9, 0xc8, 0x48, 0x59, 0x2d, 0x59, 0x3f, 0x86, 0x09, 0xca, 0x73, 0x63, 0x17, 0xd3, 0x56, 0xe1, 0x3e, 0x2b, 0xff, + 0x3a, 0x9f, 0x59, 0xcd, 0x9a, 0xeb, 0x19, 0xcd, 0x48, 0x25, 0x93, 0xd8, 0xc4, 0x61, 0x28, 0xbb, 0x32, 0x42, 0x3b, 0x37, 0xa9, 0xad, 0xfb, 0x48, 0x2b, 0x99, 0x45, 0x3f, 0xbe, 0x25, 0xa4, 0x1b, + 0xf6, 0xfe, 0xb4, 0xaa, 0x0b, 0xef, 0x5e, 0xd2, 0x4b, 0xf7, 0x3c, 0x76, 0x29, 0x78, 0x02, 0x54, 0x82, 0xc1, 0x31, 0x15, 0xe4, 0x01, 0x5a, 0xac, 0x99, 0x2e, 0x56, 0x13, 0xa3, 0xb5, 0xc2, 0xf6, + 0x85, 0xb8, 0x47, 0x95, 0xcb, 0x6e, 0x9b, 0x26, 0x56, 0xd8, 0xc8, 0x81, 0x57, 0xe5, 0x2c, 0x42, 0xf9, 0x78, 0xd8, 0x63, 0x4c, 0x43, 0xd0, 0x6f, 0xea, 0x92, 0x8f, 0x28, 0x22, 0xe4, 0x65, 0xaa, + 0x65, 0x76, 0xe9, 0xbf, 0x41, 0x93, 0x84, 0x50, 0x6c, 0xc3, 0xce, 0x3c, 0x54, 0xac, 0x1a, 0x6f, 0x67, 0xdc, 0x66, 0xf3, 0xb3, 0x01, 0x91, 0xe6, 0x98, 0x38, 0x0b, 0xc9, 0x99, 0xb0, 0x5a, 0xbc, + 0xe1, 0x9d, 0xc0, 0xc6, 0xdc, 0xc2, 0xdd, 0x00, 0x1e, 0xc5, 0x35, 0xba, 0x18, 0xde, 0xb2, 0xdf, 0x1a, 0x10, 0x10, 0x23, 0x10, 0x83, 0x18, 0xc7, 0x5d, 0xc9, 0x86, 0x11, 0xa0, 0x9d, 0xc4, 0x8a, + 0x0a, 0xcd, 0xec, 0x67, 0x6f, 0xab, 0xdf, 0x22, 0x2f, 0x07, 0xe0, 0x26, 0xf0, 0x59, 0xb6, 0x72, 0xb5, 0x6e, 0x5c, 0xbc, 0x8e, 0x1d, 0x21, 0xbb, 0xd8, 0x67, 0xdd, 0x92, 0x72, 0x12, 0x05, 0x46, + 0x81, 0xd7, 0x0e, 0xa7, 0x37, 0x13, 0x4c, 0xdf, 0xce, 0x93, 0xb6, 0xf8, 0x2a, 0xe2, 0x24, 0x23, 0x27, 0x4e, 0x58, 0xa0, 0x82, 0x1c, 0xc5, 0x50, 0x2e, 0x2d, 0x0a, 0xb4, 0x58, 0x5e, 0x94, 0xde, + 0x69, 0x75, 0xbe, 0x5e, 0x0b, 0x4e, 0xfc, 0xe5, 0x1c, 0xd3, 0xe7, 0x0c, 0x25, 0xa1, 0xfb, 0xbb, 0xd6, 0x09, 0xd2, 0x73, 0xad, 0x5b, 0x0d, 0x59, 0x63, 0x1c, 0x53, 0x1f, 0x6a, 0x0a, 0x57, 0xb9 } } }; - + void EncryptionTest::TestXtsAES () { unsigned __int8 p[ENCRYPTION_DATA_UNIT_SIZE]; @@ -386,7 +386,7 @@ namespace VeraCrypt dataUnitNo = Endian::Big (*((uint64 *) XtsTestVectors[i].dataUnitNo)); aes.EncryptSectors (p, dataUnitNo, sizeof (p) / ENCRYPTION_DATA_UNIT_SIZE, ENCRYPTION_DATA_UNIT_SIZE); - + aes.DecryptSectors (p, dataUnitNo, sizeof (p) / ENCRYPTION_DATA_UNIT_SIZE, ENCRYPTION_DATA_UNIT_SIZE); if (memcmp (XtsTestVectors[i].ciphertext, p, sizeof (p)) == 0) throw TestFailed (SRC_POS); @@ -408,9 +408,9 @@ namespace VeraCrypt uint64 writeOffset; int testCase = 0; int nTestsPerformed = 0; - + static const byte testKey[] = - { + { 0x27, 0x18, 0x28, 0x18, 0x28, 0x45, 0x90, 0x45, 0x23, 0x53, 0x60, 0x28, 0x74, 0x71, 0x35, 0x26, 0x62, 0x49, 0x77, 0x57, 0x24, 0x70, 0x93, 0x69, 0x99, 0x59, 0x57, 0x49, 0x66, 0x96, 0x76, 0x27, 0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27, 0x95, 0x02, 0x88, 0x41, 0x97, 0x16, 0x93, 0x99, 0x37, 0x51, 0x05, 0x82, 0x09, 0x74, 0x94, 0x45, 0x92, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13 @@ -423,8 +423,8 @@ namespace VeraCrypt /* The buffer can accommodate 4 data units and we'll test 4 cases by "scrolling". The data unit 0xFFFFFFFFFF will "move" from the start of the buffer to its end. For a 512-byte data unit, the byte offset 562949953420800 corresponds to the data unit 0xFFFFFFFFFF. */ - for (writeOffset = 562949953420800LL; - writeOffset > 562949953420800LL - nbrUnits * ENCRYPTION_DATA_UNIT_SIZE; + for (writeOffset = 562949953420800LL; + writeOffset > 562949953420800LL - nbrUnits * ENCRYPTION_DATA_UNIT_SIZE; writeOffset -= ENCRYPTION_DATA_UNIT_SIZE) { unitNo = writeOffset / ENCRYPTION_DATA_UNIT_SIZE; @@ -450,8 +450,8 @@ namespace VeraCrypt // Each data unit will contain the same plaintext for (i = 0; i < nbrUnits; i++) { - memcpy ((unsigned char *) buf + i * ENCRYPTION_DATA_UNIT_SIZE, - XtsTestVectors[array_capacity (XtsTestVectors)-1].plaintext, + memcpy ((unsigned char *) buf + i * ENCRYPTION_DATA_UNIT_SIZE, + XtsTestVectors[array_capacity (XtsTestVectors)-1].plaintext, ENCRYPTION_DATA_UNIT_SIZE); } @@ -472,7 +472,7 @@ namespace VeraCrypt // CRC of all data units in the buffer for each test case switch (testCase) { - case 0: + case 0: if (crc != 0x888f2990) throw TestFailed (SRC_POS); nTestsPerformed++; @@ -715,8 +715,8 @@ namespace VeraCrypt // Each data unit will contain the same plaintext for (i = 0; i < nbrUnits; i++) { - memcpy ((unsigned char *) buf + i * ENCRYPTION_DATA_UNIT_SIZE, - XtsTestVectors[array_capacity (XtsTestVectors)-1].plaintext, + memcpy ((unsigned char *) buf + i * ENCRYPTION_DATA_UNIT_SIZE, + XtsTestVectors[array_capacity (XtsTestVectors)-1].plaintext, ENCRYPTION_DATA_UNIT_SIZE); } diff --git a/src/Volume/EncryptionTest.h b/src/Volume/EncryptionTest.h index 888cff56..3123304f 100644 --- a/src/Volume/EncryptionTest.h +++ b/src/Volume/EncryptionTest.h @@ -3,7 +3,7 @@ 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) + 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 @@ -18,7 +18,7 @@ namespace VeraCrypt { - class EncryptionTest + class EncryptionTest { public: static void TestAll (); diff --git a/src/Volume/EncryptionThreadPool.cpp b/src/Volume/EncryptionThreadPool.cpp index 8ac1b52b..954322c4 100644 --- a/src/Volume/EncryptionThreadPool.cpp +++ b/src/Volume/EncryptionThreadPool.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -124,7 +124,7 @@ namespace VeraCrypt } firstFragmentWorkItem->ItemCompletedEvent.Wait(); - + auto_ptr itemException; if (firstFragmentWorkItem->ItemException.get()) itemException = firstFragmentWorkItem->ItemException; @@ -150,7 +150,7 @@ namespace VeraCrypt cpuCount = sysInfo.dwNumberOfProcessors; #elif defined (_SC_NPROCESSORS_ONLN) - + cpuCount = (size_t) sysconf (_SC_NPROCESSORS_ONLN); if (cpuCount == (size_t) -1) cpuCount = 1; diff --git a/src/Volume/EncryptionThreadPool.h b/src/Volume/EncryptionThreadPool.h index 666fa7a4..31886b21 100644 --- a/src/Volume/EncryptionThreadPool.h +++ b/src/Volume/EncryptionThreadPool.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/Hash.cpp b/src/Volume/Hash.cpp index 3c6619c3..c1baa9a3 100644 --- a/src/Volume/Hash.cpp +++ b/src/Volume/Hash.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -21,7 +21,7 @@ namespace VeraCrypt HashList Hash::GetAvailableAlgorithms () { HashList l; - + l.push_back (shared_ptr (new Sha512 ())); l.push_back (shared_ptr (new Whirlpool ())); l.push_back (shared_ptr (new Sha256 ())); @@ -66,7 +66,7 @@ namespace VeraCrypt if_debug (ValidateDataParameters (data)); RMD160Update ((RMD160_CTX *) Context.Ptr(), data.Get(), (int) data.Size()); } - + // SHA-256 Sha256::Sha256 () { diff --git a/src/Volume/Hash.h b/src/Volume/Hash.h index 19623ac9..139924c0 100644 --- a/src/Volume/Hash.h +++ b/src/Volume/Hash.h @@ -3,7 +3,7 @@ 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) + 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 @@ -70,7 +70,7 @@ namespace VeraCrypt Ripemd160 (const Ripemd160 &); Ripemd160 &operator= (const Ripemd160 &); }; - + // SHA-256 class Sha256 : public Hash { diff --git a/src/Volume/Keyfile.cpp b/src/Volume/Keyfile.cpp index e4669171..7fe81f2c 100644 --- a/src/Volume/Keyfile.cpp +++ b/src/Volume/Keyfile.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -156,7 +156,7 @@ done: { shared_ptr keyfiles; Serializer sr (stream); - + if (!sr.DeserializeBool (name + "Null")) { keyfiles.reset (new KeyfileList); diff --git a/src/Volume/Keyfile.h b/src/Volume/Keyfile.h index c7e52e97..d608a5f7 100644 --- a/src/Volume/Keyfile.h +++ b/src/Volume/Keyfile.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/Pkcs5Kdf.cpp b/src/Volume/Pkcs5Kdf.cpp index 82310dd2..d56fe029 100644 --- a/src/Volume/Pkcs5Kdf.cpp +++ b/src/Volume/Pkcs5Kdf.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -28,7 +28,7 @@ namespace VeraCrypt { DeriveKey (key, password, salt, GetIterationCount(pim)); } - + shared_ptr Pkcs5Kdf::GetAlgorithm (const wstring &name, bool truecryptMode) { foreach (shared_ptr kdf, GetAvailableAlgorithms(truecryptMode)) @@ -88,13 +88,13 @@ namespace VeraCrypt ValidateParameters (key, password, salt, iterationCount); derive_key_ripemd160 ((char *) password.DataPtr(), (int) password.Size(), (char *) salt.Get(), (int) salt.Size(), iterationCount, (char *) key.Get(), (int) key.Size()); } - + void Pkcs5HmacSha256_Boot::DeriveKey (const BufferPtr &key, const VolumePassword &password, const ConstBufferPtr &salt, int iterationCount) const { ValidateParameters (key, password, salt, iterationCount); derive_key_sha256 ((char *) password.DataPtr(), (int) password.Size(), (char *) salt.Get(), (int) salt.Size(), iterationCount, (char *) key.Get(), (int) key.Size()); } - + void Pkcs5HmacSha256::DeriveKey (const BufferPtr &key, const VolumePassword &password, const ConstBufferPtr &salt, int iterationCount) const { ValidateParameters (key, password, salt, iterationCount); diff --git a/src/Volume/Pkcs5Kdf.h b/src/Volume/Pkcs5Kdf.h index 48b3b2a6..d92a3301 100644 --- a/src/Volume/Pkcs5Kdf.h +++ b/src/Volume/Pkcs5Kdf.h @@ -3,7 +3,7 @@ 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) + 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 @@ -38,7 +38,7 @@ namespace VeraCrypt virtual Pkcs5Kdf* Clone () const = 0; virtual bool IsDeprecated () const { return GetHash()->IsDeprecated(); } bool GetTrueCryptMode () const { return m_truecryptMode;} - void SetTrueCryptMode (bool truecryptMode) { m_truecryptMode = truecryptMode;} + void SetTrueCryptMode (bool truecryptMode) { m_truecryptMode = truecryptMode;} protected: bool m_truecryptMode; @@ -84,7 +84,7 @@ namespace VeraCrypt Pkcs5HmacRipemd160_1000 (const Pkcs5HmacRipemd160_1000 &); Pkcs5HmacRipemd160_1000 &operator= (const Pkcs5HmacRipemd160_1000 &); }; - + class Pkcs5HmacSha256_Boot : public Pkcs5Kdf { public: diff --git a/src/Volume/Version.h b/src/Volume/Version.h index 633d44b9..9956297c 100644 --- a/src/Volume/Version.h +++ b/src/Volume/Version.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/Volume.cpp b/src/Volume/Volume.cpp index e4c6eb9d..e9bf40c0 100644 --- a/src/Volume/Volume.cpp +++ b/src/Volume/Volume.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -52,7 +52,7 @@ namespace VeraCrypt { if (VolumeFile.get() == nullptr) throw NotInitialized (SRC_POS); - + VolumeFile.reset(); } @@ -83,7 +83,7 @@ namespace VeraCrypt } catch (SystemException &e) { - if (e.GetErrorCode() == + if (e.GetErrorCode() == #ifdef TC_WINDOWS ERROR_SHARING_VIOLATION) #else @@ -109,7 +109,7 @@ namespace VeraCrypt // TrueCrypt doesn't support SHA-256 if (kdf && truecryptMode && (kdf->GetName() == L"HMAC-SHA-256")) - throw UnsupportedAlgoInTrueCryptMode (SRC_POS); + throw UnsupportedAlgoInTrueCryptMode (SRC_POS); Protection = protection; VolumeFile = volumeFile; @@ -272,7 +272,7 @@ namespace VeraCrypt { File driveDevice; driveDevice.Open (DevicePath (wstring (GetPath())).ToHostDriveOfPartition()); - + Buffer mbr (VolumeFile->GetDeviceSectorSize()); driveDevice.ReadAt (mbr, 0); @@ -321,12 +321,12 @@ namespace VeraCrypt void Volume::ReEncryptHeader (bool backupHeader, const ConstBufferPtr &newSalt, const ConstBufferPtr &newHeaderKey, shared_ptr newPkcs5Kdf) { if_debug (ValidateState ()); - + if (Protection == VolumeProtection::ReadOnly) throw VolumeReadOnly (SRC_POS); SecureBuffer newHeaderBuffer (Layout->GetHeaderSize()); - + Header->EncryptNew (newHeaderBuffer, newSalt, newHeaderKey, newPkcs5Kdf); int headerOffset = backupHeader ? Layout->GetBackupHeaderOffset() : Layout->GetHeaderOffset(); @@ -373,7 +373,7 @@ namespace VeraCrypt VolumeFile->WriteAt (encBuf, hostOffset); TotalDataWritten += length; - + uint64 writeEndOffset = byteOffset + buffer.Size(); if (writeEndOffset > TopWriteOffset) TopWriteOffset = writeEndOffset; diff --git a/src/Volume/Volume.h b/src/Volume/Volume.h index ad8a4db6..30373ca1 100644 --- a/src/Volume/Volume.h +++ b/src/Volume/Volume.h @@ -3,7 +3,7 @@ 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) + 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 @@ -117,7 +117,7 @@ namespace VeraCrypt VolumeType::Enum Type; shared_ptr VolumeFile; uint64 VolumeHostSize; - uint64 VolumeDataOffset; + uint64 VolumeDataOffset; uint64 VolumeDataSize; uint64 TopWriteOffset; uint64 TotalDataRead; diff --git a/src/Volume/Volume.make b/src/Volume/Volume.make index 130cda69..0ef42ac7 100644 --- a/src/Volume/Volume.make +++ b/src/Volume/Volume.make @@ -3,7 +3,7 @@ # 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) +# 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 diff --git a/src/Volume/VolumeException.cpp b/src/Volume/VolumeException.cpp index 68f3feb5..32e558e1 100644 --- a/src/Volume/VolumeException.cpp +++ b/src/Volume/VolumeException.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -23,7 +23,7 @@ namespace VeraCrypt VolumeException::VolumeException (const string &message) : Exception (message) { } - + VolumeException::VolumeException (const string &message, const wstring &subject) : Exception (message, subject) { } diff --git a/src/Volume/VolumeException.h b/src/Volume/VolumeException.h index 31393cb6..c480930c 100644 --- a/src/Volume/VolumeException.h +++ b/src/Volume/VolumeException.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/VolumeHeader.cpp b/src/Volume/VolumeHeader.cpp index 2f27ad66..13f04b35 100644 --- a/src/Volume/VolumeHeader.cpp +++ b/src/Volume/VolumeHeader.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -111,7 +111,7 @@ namespace VeraCrypt if (typeid (*mode) == typeid (EncryptionModeXTS)) { ea->SetKey (headerKey.GetRange (0, ea->GetKeySize())); - + mode = mode->GetNew(); mode->SetKey (headerKey.GetRange (ea->GetKeySize(), ea->GetKeySize())); } @@ -172,7 +172,7 @@ namespace VeraCrypt } RequiredMinProgramVersion = DeserializeEntry (header, offset); - + if (!truecryptMode && (RequiredMinProgramVersion > Version::Number())) throw HigherVersionRequired (SRC_POS); @@ -215,10 +215,10 @@ namespace VeraCrypt return false; DataAreaKey.CopyFrom (header.GetRange (offset, DataKeyAreaMaxSize)); - + ea = ea->GetNew(); mode = mode->GetNew(); - + if (typeid (*mode) == typeid (EncryptionModeXTS)) { ea->SetKey (header.GetRange (offset, ea->GetKeySize())); @@ -289,7 +289,7 @@ namespace VeraCrypt size_t VolumeHeader::GetLargestSerializedKeySize () { size_t largestKey = EncryptionAlgorithm::GetLargestKeySize (EncryptionAlgorithm::GetAvailableAlgorithms()); - + // XTS mode requires the same key size as the encryption algorithm. // Legacy modes may require larger key than XTS. if (LegacyEncryptionModeKeyAreaSize + largestKey > largestKey * 2) diff --git a/src/Volume/VolumeHeader.h b/src/Volume/VolumeHeader.h index 96d0fbed..26c32c06 100644 --- a/src/Volume/VolumeHeader.h +++ b/src/Volume/VolumeHeader.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/VolumeInfo.cpp b/src/Volume/VolumeInfo.cpp index ea02fd79..0c610a81 100644 --- a/src/Volume/VolumeInfo.cpp +++ b/src/Volume/VolumeInfo.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -62,7 +62,7 @@ namespace VeraCrypt { return first->SerialInstanceNumber > second->SerialInstanceNumber; } - + void VolumeInfo::Serialize (shared_ptr stream) const { Serializable::Serialize (stream); diff --git a/src/Volume/VolumeInfo.h b/src/Volume/VolumeInfo.h index 3a31ff66..b61dbdeb 100644 --- a/src/Volume/VolumeInfo.h +++ b/src/Volume/VolumeInfo.h @@ -3,7 +3,7 @@ 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) + 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 @@ -31,7 +31,7 @@ namespace VeraCrypt TC_SERIALIZABLE (VolumeInfo); static bool FirstVolumeMountedAfterSecond (shared_ptr first, shared_ptr second); - void Set (const Volume &volume); + void Set (const Volume &volume); // Modifying this structure can introduce incompatibility with previous versions DirectoryPath AuxMountPoint; diff --git a/src/Volume/VolumeLayout.cpp b/src/Volume/VolumeLayout.cpp index 9ea5f7c3..065045b9 100644 --- a/src/Volume/VolumeLayout.cpp +++ b/src/Volume/VolumeLayout.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/VolumeLayout.h b/src/Volume/VolumeLayout.h index ab6fe578..a83e5616 100644 --- a/src/Volume/VolumeLayout.h +++ b/src/Volume/VolumeLayout.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/VolumePassword.cpp b/src/Volume/VolumePassword.cpp index 9517cffd..bfa0ffe2 100644 --- a/src/Volume/VolumePassword.cpp +++ b/src/Volume/VolumePassword.cpp @@ -3,7 +3,7 @@ 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) + 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 @@ -38,7 +38,7 @@ namespace VeraCrypt sr.Deserialize ("PasswordSize", passwordSize); PasswordSize = static_cast (passwordSize); sr.Deserialize ("PasswordBuffer", BufferPtr (PasswordBuffer)); - + Buffer wipeBuffer (128 * 1024); sr.Deserialize ("WipeData", wipeBuffer); } @@ -59,7 +59,7 @@ namespace VeraCrypt void VolumePassword::Set (const byte *password, size_t size) { AllocateBuffer (); - + if (size > MaxSize) throw PasswordTooLong (SRC_POS); @@ -69,7 +69,7 @@ namespace VeraCrypt PasswordSize = size; } - + void VolumePassword::Set (const VolumePassword &password) { Set (password.DataPtr(), password.Size()); diff --git a/src/Volume/VolumePassword.h b/src/Volume/VolumePassword.h index 8d2a46de..a547aac0 100644 --- a/src/Volume/VolumePassword.h +++ b/src/Volume/VolumePassword.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/VolumePasswordCache.cpp b/src/Volume/VolumePasswordCache.cpp index 2e5e2733..d2a956cf 100644 --- a/src/Volume/VolumePasswordCache.cpp +++ b/src/Volume/VolumePasswordCache.cpp @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/VolumePasswordCache.h b/src/Volume/VolumePasswordCache.h index 11bef1f0..ab1692d9 100644 --- a/src/Volume/VolumePasswordCache.h +++ b/src/Volume/VolumePasswordCache.h @@ -3,7 +3,7 @@ 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) + 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 diff --git a/src/Volume/VolumeSlot.h b/src/Volume/VolumeSlot.h index 7df242d7..418328fc 100644 --- a/src/Volume/VolumeSlot.h +++ b/src/Volume/VolumeSlot.h @@ -3,7 +3,7 @@ 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) + 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 -- cgit v1.2.3 From 5f47d8b6f11cdb3c4c2f43e04e5acfc6ffcb3035 Mon Sep 17 00:00:00 2001 From: David Foerster Date: Tue, 10 May 2016 22:24:06 +0200 Subject: Fix space before tab --- src/Common/Dlgcode.c | 2 +- src/Common/EncryptionThreadPool.c | 2 +- src/Common/Keyfiles.c | 2 +- src/Crypto/AesSmall_x86.asm | 2 +- src/Format/Tcformat.c | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/Common/Dlgcode.c b/src/Common/Dlgcode.c index fd2601b4..13a439e0 100644 --- a/src/Common/Dlgcode.c +++ b/src/Common/Dlgcode.c @@ -8965,7 +8965,7 @@ char *LoadFileBlock (const wchar_t *fileName, __int64 fileOffset, DWORD count) // Returns -1 if there is an error, or the size of the file. __int64 GetFileSize64 (const wchar_t *path) { - HANDLE h = CreateFile (path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + HANDLE h = CreateFile (path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); LARGE_INTEGER size; __int64 retSize = -1; diff --git a/src/Common/EncryptionThreadPool.c b/src/Common/EncryptionThreadPool.c index f0889a34..d99512a9 100644 --- a/src/Common/EncryptionThreadPool.c +++ b/src/Common/EncryptionThreadPool.c @@ -475,7 +475,7 @@ void EncryptionThreadPoolDoWork (EncryptionThreadPoolWorkType type, byte *data, workItem->Encryption.UnitCount = unitsPerFragment; workItem->Encryption.StartUnitNo.Value = fragmentStartUnitNo; - fragmentData += unitsPerFragment * ENCRYPTION_DATA_UNIT_SIZE; + fragmentData += unitsPerFragment * ENCRYPTION_DATA_UNIT_SIZE; fragmentStartUnitNo += unitsPerFragment; if (remainder > 0 && --remainder == 0) diff --git a/src/Common/Keyfiles.c b/src/Common/Keyfiles.c index 10f49b5d..5ee5bccf 100644 --- a/src/Common/Keyfiles.c +++ b/src/Common/Keyfiles.c @@ -590,7 +590,7 @@ BOOL CALLBACK KeyFilesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa } LoadKeyList (hwndDlg, param->FirstKeyFile); - return 1; + return 1; } if (lw == IDC_KEYREMOVEALL) diff --git a/src/Crypto/AesSmall_x86.asm b/src/Crypto/AesSmall_x86.asm index 20008194..872aa013 100644 --- a/src/Crypto/AesSmall_x86.asm +++ b/src/Crypto/AesSmall_x86.asm @@ -946,7 +946,7 @@ dec_round: restore ebp,1 xor eax,[ebp] xor ebx,[ebp+4] - add sp, 2 + add sp, 2 ret %else diff --git a/src/Format/Tcformat.c b/src/Format/Tcformat.c index bb479395..40c17d66 100644 --- a/src/Format/Tcformat.c +++ b/src/Format/Tcformat.c @@ -3200,7 +3200,7 @@ __int64 PrintFreeSpace (HWND hwndTextBox, wchar_t *lpszDrive, PLARGE_INTEGER lDi else nResourceString = "DISK_FREE_GB"; } - else + else { if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume nResourceString = "MAX_HIDVOL_SIZE_TB"; @@ -9476,7 +9476,7 @@ int ScanVolClusterBitmap (HWND hwndDlg, int *driveNo, __int64 nbrClusters, __int goto vcmf_error; } - bufLen = (DWORD) (nbrClusters / 8 + 2 * sizeof(LARGE_INTEGER)); + bufLen = (DWORD) (nbrClusters / 8 + 2 * sizeof(LARGE_INTEGER)); bufLen += 100000 + bufLen/10; // Add reserve lpOutBuffer = (PVOLUME_BITMAP_BUFFER) malloc (bufLen); -- cgit v1.2.3