VeraCrypt
aboutsummaryrefslogtreecommitdiff
path: root/src/Common
diff options
context:
space:
mode:
authorDavid Foerster <david.foerster@informatik.hu-berlin.de>2016-05-10 18:20:14 (GMT)
committerDavid Foerster <david.foerster@informatik.hu-berlin.de>2016-05-10 18:20:14 (GMT)
commitfc37cc4a02ed13d1a73b941a9f80975600fd1b99 (patch)
treead9e5ac81111402b5c47dc06944cc5243824c4b5 /src/Common
parent98b04198c6ea5bc07cca50956809068adf1fea82 (diff)
downloadVeraCrypt-fc37cc4a02ed13d1a73b941a9f80975600fd1b99.zip
VeraCrypt-fc37cc4a02ed13d1a73b941a9f80975600fd1b99.tar.gz
Normalize all line terminators
Diffstat (limited to 'src/Common')
-rw-r--r--src/Common/Apidrvr.h688
-rw-r--r--src/Common/BaseCom.cpp492
-rw-r--r--src/Common/BaseCom.h238
-rw-r--r--src/Common/BootEncryption.cpp5626
-rw-r--r--src/Common/BootEncryption.h510
-rw-r--r--src/Common/Cache.c230
-rw-r--r--src/Common/Cache.h50
-rw-r--r--src/Common/Cmdline.c368
-rw-r--r--src/Common/Cmdline.h86
-rw-r--r--src/Common/Combo.c516
-rw-r--r--src/Common/Combo.h58
-rw-r--r--src/Common/Common.h190
-rw-r--r--src/Common/Common.rc1206
-rw-r--r--src/Common/Crc.c270
-rw-r--r--src/Common/Crc.h74
-rw-r--r--src/Common/Crypto.c2116
-rw-r--r--src/Common/Crypto.h726
-rw-r--r--src/Common/Dictionary.c174
-rw-r--r--src/Common/Dictionary.h68
-rw-r--r--src/Common/Dlgcode.c23780
-rw-r--r--src/Common/Dlgcode.h1186
-rw-r--r--src/Common/EncryptionThreadPool.c1022
-rw-r--r--src/Common/EncryptionThreadPool.h84
-rw-r--r--src/Common/Endian.c118
-rw-r--r--src/Common/Endian.h298
-rw-r--r--src/Common/Exception.h246
-rw-r--r--src/Common/Fat.c898
-rw-r--r--src/Common/Fat.h138
-rw-r--r--src/Common/Format.c2108
-rw-r--r--src/Common/Format.h152
-rw-r--r--src/Common/GfMul.c1536
-rw-r--r--src/Common/GfMul.h148
-rw-r--r--src/Common/Inflate.c2642
-rw-r--r--src/Common/Inflate.h102
-rw-r--r--src/Common/Keyfiles.c1556
-rw-r--r--src/Common/Keyfiles.h108
-rw-r--r--src/Common/Language.c1166
-rw-r--r--src/Common/Language.h86
-rw-r--r--src/Common/Language.xml2912
-rw-r--r--src/Common/Makefile2
-rw-r--r--src/Common/Password.c982
-rw-r--r--src/Common/Password.h104
-rw-r--r--src/Common/Pkcs5.c1918
-rw-r--r--src/Common/Pkcs5.h96
-rw-r--r--src/Common/Progress.c268
-rw-r--r--src/Common/Progress.h66
-rw-r--r--src/Common/Random.c1796
-rw-r--r--src/Common/Random.h152
-rw-r--r--src/Common/Registry.c598
-rw-r--r--src/Common/Registry.h74
-rw-r--r--src/Common/Resource.h422
-rw-r--r--src/Common/SecurityToken.cpp1570
-rw-r--r--src/Common/SecurityToken.h452
-rw-r--r--src/Common/Sources34
-rw-r--r--src/Common/Tcdefs.h646
-rw-r--r--src/Common/Tests.c2310
-rw-r--r--src/Common/Tests.h62
-rw-r--r--src/Common/Volumes.c2540
-rw-r--r--src/Common/Volumes.h310
-rw-r--r--src/Common/Wipe.c396
-rw-r--r--src/Common/Wipe.h90
-rw-r--r--src/Common/Xml.c536
-rw-r--r--src/Common/Xml.h58
-rw-r--r--src/Common/Xts.c1500
-rw-r--r--src/Common/Xts.h168
65 files changed, 35561 insertions, 35561 deletions
diff --git a/src/Common/Apidrvr.h b/src/Common/Apidrvr.h
index f584582..5ea8977 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 8e7d39f..f6c5597 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 <atlcomcli.h>
-#include <atlconv.h>
-#include <comutil.h>
-#include <windows.h>
-#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> 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 <atlcomcli.h>
+#include <atlconv.h>
+#include <comutil.h>
+#include <windows.h>
+#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> 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 9f5b312..9700941 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 <guiddef.h>
-
-template <class TClass>
-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 <guiddef.h>
+
+template <class TClass>
+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 851d762..73b6445 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 <devguid.h>
-#include <io.h>
-#include <shlobj.h>
-#include <atlbase.h>
-#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 <Strsafe.h>
-
-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 <MBR *> (mbrBuf);
- if (mbr->Signature != 0xaa55)
- throw ParameterIncorrect (SRC_POS);
-
- for (size_t i = 0; i < array_capacity (mbr->Partitions); ++i)
- {
- if (mbr->Partitions[i].Type == type)
- return true;
- }
-
- return false;
- }
-
-
- bool BootEncryption::SystemDriveContainsExtendedPartition ()
- {
- return SystemDriveContainsPartitionType (PARTITION_EXTENDED) || SystemDriveContainsPartitionType (PARTITION_XINT13_EXTENDED);
- }
-
-
- bool BootEncryption::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 <uint16> (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, &regKey));
- 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 <devguid.h>
+#include <io.h>
+#include <shlobj.h>
+#include <atlbase.h>
+#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 <Strsafe.h>
+
+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 <MBR *> (mbrBuf);
+ if (mbr->Signature != 0xaa55)
+ throw ParameterIncorrect (SRC_POS);
+
+ for (size_t i = 0; i < array_capacity (mbr->Partitions); ++i)
+ {
+ if (mbr->Partitions[i].Type == type)
+ return true;
+ }
+
+ return false;
+ }
+
+
+ bool BootEncryption::SystemDriveContainsExtendedPartition ()
+ {
+ return SystemDriveContainsPartitionType (PARTITION_EXTENDED) || SystemDriveContainsPartitionType (PARTITION_XINT13_EXTENDED);
+ }
+
+
+ bool BootEncryption::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 <uint16> (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, &regKey));
+ 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 a922d1f..a89b2ec 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 <Partition> 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 <Partition> 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 e32896f..ba6c6df 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 05f0ba0..c4587d0 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 759c63f..4a055c1 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 <malloc.h>
-#include <ctype.h>
-#include "Cmdline.h"
-
-#include "Resource.h"
-#include "Crypto.h"
-#include "Apidrvr.h"
-#include "Dlgcode.h"
-#include "Language.h"
-#include <Strsafe.h>
-
-#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 <malloc.h>
+#include <ctype.h>
+#include "Cmdline.h"
+
+#include "Resource.h"
+#include "Crypto.h"
+#include "Apidrvr.h"
+#include "Dlgcode.h"
+#include "Language.h"
+#include <Strsafe.h>
+
+#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 3088d56..51c173c 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 0340b23..fe45685 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 <time.h>
-
-#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<history>", 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<volume>%s</volume>", q);
- }
- }
-
- fputws (L"\n\t</history>", 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 <time.h>
+
+#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<history>", 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<volume>%s</volume>", q);
+ }
+ }
+
+ fputws (L"\n\t</history>", 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 dd18129..cacbc41 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 180cbff..05e2e12 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 a0dbd61..1e529c6 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 b66b86c..ba8777e 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 531a038..c89a619 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 d940a45..a524fd9 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 <string.h>
-#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 <string.h>
+#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 e081dc6..96f0a9a 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 41f447c..3474195 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 <windows.h>
-#include <map>
-#include <string>
-
-using namespace std;
-
-static map <string, void *> StringKeyMap;
-static map <int, void *> 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 <string, void *>::const_iterator i = StringKeyMap.find (key);
-
- if (i == StringKeyMap.end())
- return NULL;
-
- return i->second;
-}
-
-
-void *GetDictionaryValueByInt (int intKey)
-{
- map <int, void *>::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 <windows.h>
+#include <map>
+#include <string>
+
+using namespace std;
+
+static map <string, void *> StringKeyMap;
+static map <int, void *> 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 <string, void *>::const_iterator i = StringKeyMap.find (key);
+
+ if (i == StringKeyMap.end())
+ return NULL;
+
+ return i->second;
+}
+
+
+void *GetDictionaryValueByInt (int intKey)
+{
+ map <int, void *>::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 5a4d086..0fa9c7e 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 <windows.h>
-
-#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 <windows.h>
+
+#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 97dd524..ef6a942 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 <windowsx.h>
-#include <dbghelp.h>
-#include <dbt.h>
-#include <Setupapi.h>
-#include <fcntl.h>
-#include <io.h>
-#include <math.h>
-#include <shlobj.h>
-#include <sys/stat.h>
-#include <stdlib.h>
-#include <time.h>
-#include <tchar.h>
-#include <Richedit.h>
-
-#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 <strsafe.h>
-
-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 <DWORD> 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 <HostDevice> devices;
- static map <int, HostDevice> 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<byte>& 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);
-