diff options
Diffstat (limited to 'src/Common')
-rw-r--r-- | src/Common/BootEncryption.cpp | 29 | ||||
-rw-r--r-- | src/Common/Cache.c | 2 | ||||
-rw-r--r-- | src/Common/Cache.h | 2 | ||||
-rw-r--r-- | src/Common/Crypto.c | 13 | ||||
-rw-r--r-- | src/Common/Crypto.h | 10 | ||||
-rw-r--r-- | src/Common/Dlgcode.c | 263 | ||||
-rw-r--r-- | src/Common/Dlgcode.h | 2 | ||||
-rw-r--r-- | src/Common/EncryptionThreadPool.c | 8 | ||||
-rw-r--r-- | src/Common/EncryptionThreadPool.h | 2 | ||||
-rw-r--r-- | src/Common/Format.c | 8 | ||||
-rw-r--r-- | src/Common/Keyfiles.c | 4 | ||||
-rw-r--r-- | src/Common/Language.c | 12 | ||||
-rw-r--r-- | src/Common/Password.c | 2 | ||||
-rw-r--r-- | src/Common/Pkcs5.c | 409 | ||||
-rw-r--r-- | src/Common/Pkcs5.h | 20 | ||||
-rw-r--r-- | src/Common/Progress.c | 10 | ||||
-rw-r--r-- | src/Common/Random.c | 48 | ||||
-rw-r--r-- | src/Common/SecurityToken.cpp | 4 | ||||
-rw-r--r-- | src/Common/Tcdefs.h | 15 | ||||
-rw-r--r-- | src/Common/Tests.c | 66 | ||||
-rw-r--r-- | src/Common/Tests.h | 2 | ||||
-rw-r--r-- | src/Common/Volumes.c | 20 | ||||
-rw-r--r-- | src/Common/Volumes.h | 10 | ||||
-rw-r--r-- | src/Common/Wipe.c | 7 |
24 files changed, 420 insertions, 548 deletions
diff --git a/src/Common/BootEncryption.cpp b/src/Common/BootEncryption.cpp index f79e7339..b377ad7d 100644 --- a/src/Common/BootEncryption.cpp +++ b/src/Common/BootEncryption.cpp @@ -1114,80 +1114,80 @@ namespace VeraCrypt } 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) + for (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 (config.ExtraBootPartitionPresent) { int64 minOffsetFound = config.DrivePartition.Info.PartitionLength.QuadPart; Partition bootPartition = partition; Partition partitionBehindBoot; - foreach (const Partition &partition, config.Partitions) + for (const Partition &otherPartition : config.Partitions) { - if (partition.Info.StartingOffset.QuadPart > bootPartition.Info.StartingOffset.QuadPart - && partition.Info.StartingOffset.QuadPart < minOffsetFound) + if (otherPartition.Info.StartingOffset.QuadPart > bootPartition.Info.StartingOffset.QuadPart + && otherPartition.Info.StartingOffset.QuadPart < minOffsetFound) { - minOffsetFound = partition.Info.StartingOffset.QuadPart; - partitionBehindBoot = partition; + minOffsetFound = otherPartition.Info.StartingOffset.QuadPart; + partitionBehindBoot = otherPartition; } } 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; } } } else { // For GPT activePartitionFound = true; } /* 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 @@ -1324,65 +1324,65 @@ namespace VeraCrypt 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()); + int driveLetter = GetDiskDeviceDriveLetter ((wchar_t *) partPath.str().c_str()); - if (driveNumber >= 0) + if (driveLetter >= 0) { - part.MountPoint += (wchar_t) (driveNumber + L'A'); + part.MountPoint += (wchar_t) (driveLetter + 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); @@ -2414,61 +2414,62 @@ namespace VeraCrypt fwprintf (configFile, L"\n\t\t<config key=\"%hs\">%hs</config>", key, value); xml++; } fputws (L"\n\t</configuration>", configFile); XmlWriteFooter (configFile); TCFlushFile (configFile); bRet = CheckFileStreamWriteErrors (hwnd, configFile, fileName); fclose (configFile); if (configContent != NULL) { burn (configContent, size); free (configContent); } return bRet; } BOOL EfiBootConf::IsPostExecFileField (const string& fieldValue, string& filePath) { BOOL bRet = FALSE; filePath = ""; if (!fieldValue.empty() && strlen (fieldValue.c_str())) { string copieValue = fieldValue; - std::transform(copieValue.begin(), copieValue.end(), copieValue.begin(), ::tolower); + std::transform(copieValue.begin(), copieValue.end(), copieValue.begin(), + [](unsigned char c) { return static_cast<char>(std::tolower(c)); }); if (strstr (copieValue.c_str(), "postexec") && strstr (copieValue.c_str(), "file(")) { char c; const char* ptr = strstr (copieValue.c_str(), "file("); filePath = "\\"; ptr += 5; while ((c = *ptr)) { if (c == ')') break; if (c == '/') c = '\\'; filePath += c; ptr++; } if (c == ')') bRet = TRUE; else filePath = ""; } } return bRet; } BOOL EfiBootConf::IsPostExecFileField (const string& fieldValue, wstring& filePath) { @@ -4355,68 +4356,68 @@ namespace VeraCrypt { File rescueFile (imageFile, true); rescueFile.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 = rescueFile.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, + throw_sys_if (CreateVolumeHeaderInMemory (ParentWindow, TRUE, 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, NULL, cryptoInfo)) + if (0 != ReadVolumeHeader (TRUE, RescueVolumeHeader, password, pkcs5, pim, 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); uint8 *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); @@ -5364,91 +5365,91 @@ namespace VeraCrypt 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]; + unsigned 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 ((uint8 *) header, sizeof (header)); + device.Read (header, sizeof (header)); PCRYPTO_INFO cryptoInfo = NULL; int status = ReadVolumeHeader (!encStatus.HiddenSystem, header, oldPassword, old_pkcs5, old_pim, &cryptoInfo, NULL); finally_do_arg (PCRYPTO_INFO, cryptoInfo, { if (finally_arg) crypto_close (finally_arg); }); // if the XTS master key is vulnerable, return error and do not allow the user to change the password since the master key will not be changed if ((status == 0) && cryptoInfo->bVulnerableMasterKey) status = ERR_SYSENC_XTS_MASTERKEY_VULNERABLE; 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); } diff --git a/src/Common/Cache.c b/src/Common/Cache.c index 46249b9c..0d7a221f 100644 --- a/src/Common/Cache.c +++ b/src/Common/Cache.c @@ -16,61 +16,61 @@ #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; #ifdef _WIN64 uint64 VcGetPasswordEncryptionID (Password* pPassword) { return ((uint64) pPassword->Text) + ((uint64) pPassword); } void VcProtectPassword (Password* pPassword, uint64 encID) { VcProtectMemory (encID, (unsigned char*) pPassword->Text, sizeof(pPassword->Text), (unsigned char*) &pPassword->Length, sizeof (pPassword->Length)); } void VcUnprotectPassword (Password* pPassword, uint64 encID) { VcProtectPassword (pPassword, encID); } #endif -int ReadVolumeHeaderWCache (BOOL bBoot, BOOL bCache, BOOL bCachePim, char *header, Password *password, int pkcs5_prf, int pim, PCRYPTO_INFO *retInfo) +int ReadVolumeHeaderWCache (BOOL bBoot, BOOL bCache, BOOL bCachePim, unsigned char *header, Password *password, int pkcs5_prf, int pim, 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, retInfo, NULL); /* Save mount passwords back into cache if asked to do so */ if (bCache && (nReturnCode == 0 || nReturnCode == ERR_CIPHER_INIT_WEAK_KEY)) { #ifdef _WIN64 Password tmpPass; #endif for (i = 0; i < CACHE_SIZE; i++) { Password* pCurrentPassword = &CachedPasswords[i]; #ifdef _WIN64 if (IsRamEncryptionEnabled()) { memcpy (&tmpPass, pCurrentPassword, sizeof (Password)); VcUnprotectPassword (&tmpPass, VcGetPasswordEncryptionID (pCurrentPassword)); pCurrentPassword = &tmpPass; } #endif if (memcmp (pCurrentPassword, password, sizeof (Password)) == 0) break; } diff --git a/src/Common/Cache.h b/src/Common/Cache.h index 0988bf29..84bb6937 100644 --- a/src/Common/Cache.h +++ b/src/Common/Cache.h @@ -1,26 +1,26 @@ /* 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-2017 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #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, BOOL bCachePim); void AddLegacyPasswordToCache (PasswordLegacy *password, int pim); -int ReadVolumeHeaderWCache (BOOL bBoot, BOOL bCache, BOOL bCachePim,char *header, Password *password, int pkcs5_prf, int pim, PCRYPTO_INFO *retInfo); +int ReadVolumeHeaderWCache (BOOL bBoot, BOOL bCache, BOOL bCachePim, unsigned char *header, Password *password, int pkcs5_prf, int pim, PCRYPTO_INFO *retInfo); void WipeCache (void); diff --git a/src/Common/Crypto.c b/src/Common/Crypto.c index 9c4ee5a3..5a10e995 100644 --- a/src/Common/Crypto.c +++ b/src/Common/Crypto.c @@ -1,48 +1,49 @@ /* 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-2017 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #include "Tcdefs.h" #include "Crypto.h" #include "Xts.h" #include "Crc.h" #include "Common/Endian.h" +#include "Crypto/t1ha.h" #if !defined(_UEFI) #include <string.h> #ifndef TC_WINDOWS_BOOT #ifdef TC_WINDOWS_DRIVER #include <ntstrsafe.h> #define StringCchCatW RtlStringCchCatW #define StringCchCopyW RtlStringCchCopyW #else #include <strsafe.h> #endif #include "EncryptionThreadPool.h" #endif #endif #include "Volumes.h" #include "cpu.h" #pragma warning (disable:4706) // assignment within conditional expression /* 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() @@ -632,71 +633,71 @@ int EAGetKeySize (int ea) while (i = EAGetNextCipher (ea, i)) { size += CipherGetKeySize (i); } return size; } #ifndef TC_WINDOWS_BOOT // 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; } -// Returns the name of the mode of operation of the whole EA -wchar_t *EAGetModeName (int ea, int mode, BOOL capitalLetters) +// Returns the name of the mode of operation +const wchar_t *EAGetModeName (int mode) { switch (mode) { case XTS: return L"XTS"; } - return L"[unknown]"; + 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; } #ifndef TC_WINDOWS_BOOT // Returns number of ciphers in EA int EAGetCipherCount (int ea) { int i = 0; while (EncryptionAlgorithms[ea].Ciphers[i++]); return i - 1; } @@ -864,61 +865,61 @@ 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)); #if !defined(DEVICE_DRIVER) && !defined(_UEFI) 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) +void crypto_loadkey (PKEY_INFO keyInfo, unsigned char *lpszUserKey, int nUserKeyLen) { keyInfo->keyLength = nUserKeyLen; burn (keyInfo->userKey, sizeof (keyInfo->userKey)); memcpy (keyInfo->userKey, lpszUserKey, nUserKeyLen); } void crypto_eraseKeys (PCRYPTO_INFO cryptoInfo) { burn (cryptoInfo->ks, sizeof (cryptoInfo->ks)); burn (cryptoInfo->ks2, sizeof (cryptoInfo->ks2)); #ifdef TC_WINDOWS_DRIVER burn (cryptoInfo->master_keydata_hash, sizeof (cryptoInfo->master_keydata_hash)); #else burn (cryptoInfo->master_keydata, sizeof (cryptoInfo->master_keydata)); burn (cryptoInfo->k2, sizeof (cryptoInfo->k2)); #endif burn (&cryptoInfo->noIterations, sizeof (cryptoInfo->noIterations)); burn (&cryptoInfo->volumePim, sizeof (cryptoInfo->volumePim)); } #endif void crypto_close (PCRYPTO_INFO cryptoInfo) { #ifndef TC_WINDOWS_BOOT if (cryptoInfo != NULL) { burn (cryptoInfo, sizeof (CRYPTO_INFO)); #if !defined(DEVICE_DRIVER) && !defined(_UEFI) VirtualUnlock (cryptoInfo, sizeof (CRYPTO_INFO)); @@ -1212,63 +1213,65 @@ BOOL IsAesHwCpuSupported () return 0; #else return (HasAESNI() && !HwEncryptionDisabled)? TRUE : FALSE; #endif } 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 #if !defined (TC_WINDOWS_BOOT) && !defined (_UEFI) static BOOL CpuRngDisabled = TRUE; static BOOL RamEncryptionEnabled = FALSE; BOOL IsCpuRngSupported () { +#ifndef _M_ARM64 if (HasRDSEED() || HasRDRAND()) return TRUE; else +#endif return FALSE; } void EnableCpuRng (BOOL enable) { CpuRngDisabled = !enable; } BOOL IsCpuRngEnabled () { return !CpuRngDisabled; } BOOL IsRamEncryptionSupported () { #ifdef _WIN64 if (t1ha_selfcheck__t1ha2() == 0) return TRUE; else return FALSE; #else return FALSE; #endif } void EnableRamEncryption (BOOL enable) { RamEncryptionEnabled = enable; } @@ -1286,61 +1289,61 @@ uint8 GetRngMask (uint8 count) return 0x7F; if (count >= 32) return 0x3F; if (count >= 16) return 0x1F; if (count >= 8) return 0x0F; if (count >= 4) return 0x07; if (count >= 2) return 0x03; return 1; } uint8 GetRandomIndex (ChaCha20RngCtx* pCtx, uint8 elementsCount) { uint8 index = 0; uint8 mask = GetRngMask (elementsCount); while (TRUE) { ChaCha20RngGetBytes (pCtx, &index, 1); index &= mask; if (index < elementsCount) break; } return index; } -#if defined(_WIN64) && !defined (_UEFI) +#if !defined (_UEFI) /* declaration of variables and functions used for RAM encryption on 64-bit build */ static uint8* pbKeyDerivationArea = NULL; static ULONG cbKeyDerivationArea = 0; static uint64 HashSeedMask = 0; static uint64 CipherIVMask = 0; #ifdef TC_WINDOWS_DRIVER ULONG AllocTag = 'MMCV'; #endif #if !defined(PAGE_SIZE) #define PAGE_SIZE 4096 #endif BOOL InitializeSecurityParameters(GetRandSeedFn rngCallback) { ChaCha20RngCtx ctx; uint8 pbSeed[CHACHA20RNG_KEYSZ + CHACHA20RNG_IVSZ]; #ifdef TC_WINDOWS_DRIVER uint8 i; char randomStr[4]; Dump ("InitializeSecurityParameters BEGIN\n"); #endif rngCallback (pbSeed, sizeof (pbSeed)); ChaCha20RngInit (&ctx, pbSeed, rngCallback, 0); #ifdef TC_WINDOWS_DRIVER diff --git a/src/Common/Crypto.h b/src/Common/Crypto.h index 89d22f0e..6fc75b43 100644 --- a/src/Common/Crypto.h +++ b/src/Common/Crypto.h @@ -201,63 +201,63 @@ typedef struct #include "blake2.h" #ifndef TC_WINDOWS_BOOT # include "Sha2.h" # include "Whirlpool.h" # include "Streebog.h" # include "kuznyechik.h" # include "Camellia.h" #if !defined (_UEFI) # include "chachaRng.h" # ifdef _WIN64 # include "t1ha.h" # endif #endif #else # include "CamelliaSmall.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 */ - CRYPTOPP_ALIGN_DATA(16) __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. */ + unsigned __int8 salt[PKCS5_SALT_SIZE]; /* PKCS-5 salt */ + CRYPTOPP_ALIGN_DATA(16) unsigned __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) unsigned __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; #ifdef TC_WINDOWS_DRIVER unsigned __int8 master_keydata_hash[BLAKE2S_DIGESTSIZE]; #else CRYPTOPP_ALIGN_DATA(16) 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). */ CRYPTOPP_ALIGN_DATA(16) 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. */ #endif int noIterations; int volumePim; 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). @@ -282,100 +282,100 @@ typedef struct CRYPTO_INFO_t #endif // !TC_WINDOWS_BOOT UINT64_STRUCT VolumeSize; UINT64_STRUCT EncryptedAreaStart; UINT64_STRUCT EncryptedAreaLength; uint32 HeaderFlags; } CRYPTO_INFO, *PCRYPTO_INFO; #if defined(_WIN32) || defined(_UEFI) #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); +void crypto_loadkey (PKEY_INFO keyInfo, unsigned char *lpszUserKey, int nUserKeyLen); void crypto_eraseKeys (PCRYPTO_INFO cryptoInfo); #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, unsigned char* key2); 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, size_t bufLen, 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); +const wchar_t * EAGetModeName (int mode); #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); #ifndef TC_WINDOWS_BOOT int EAIsFormatEnabled (int ea); int EAIsMbrSysEncEnabled (int ea); #endif BOOL EAIsModeSupported (int ea, int testedMode); #ifndef TC_WINDOWS_BOOT const wchar_t *HashGetName (int hash_algo_id); #ifdef _WIN32 int HashGetIdByName (wchar_t *name); #endif Hash *HashGet (int id); void HashGetName2 (wchar_t *buf, size_t bufLen, int hashId); BOOL HashIsDeprecated (int hashId); BOOL HashForSystemEncryption (int hashId); int GetMaxPkcs5OutSize (void); #endif diff --git a/src/Common/Dlgcode.c b/src/Common/Dlgcode.c index b91167d4..e56c6b46 100644 --- a/src/Common/Dlgcode.c +++ b/src/Common/Dlgcode.c @@ -1,46 +1,47 @@ /* 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-2017 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #include "Tcdefs.h" #include <windowsx.h> +#include <versionhelpers.h> #include <dbghelp.h> #include <dbt.h> #include <Setupapi.h> #include <aclapi.h> #include <Netlistmgr.h> #include <fcntl.h> #include <io.h> #include <math.h> #include <shlobj.h> #include <shlwapi.h> #include <sys/stat.h> #include <stdlib.h> #include <time.h> #include <tchar.h> #include <Richedit.h> #if defined (TCMOUNT) || defined (VOLFORMAT) #include <process.h> #include <Tlhelp32.h> #endif #if _WIN32_WINNT >= 0x0602 #include "processthreadsapi.h" #endif #include "Resource.h" #include "Platform/Finally.h" #include "Platform/ForEach.h" #include "Apidrvr.h" #include "BootEncryption.h" #include "Combo.h" @@ -832,65 +833,60 @@ BOOL TCCopyFile (wchar_t *sourceFileName, wchar_t *destinationFile) GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (src == INVALID_HANDLE_VALUE) return FALSE; dst = CreateFileW (destinationFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); if (dst == INVALID_HANDLE_VALUE) { CloseHandle (src); return FALSE; } return TCCopyFileBase (src, dst); } BOOL VerifyModuleSignature (const wchar_t* path) { #if defined(NDEBUG) && !defined (VC_SKIP_OS_DRIVER_REQ_CHECK) BOOL bResult = FALSE; HRESULT hResult; GUID gActionID = WINTRUST_ACTION_GENERIC_VERIFY_V2; WINTRUST_FILE_INFO fileInfo = {0}; WINTRUST_DATA WVTData = {0}; wchar_t filePath [TC_MAX_PATH + 1024]; - // we check our own authenticode signature only starting from Windows 10 since this is - // the minimal supported OS apart from XP where we can't verify SHA256 signatures - if (!IsOSAtLeast (WIN_10)) - return TRUE; - // Strip quotation marks (if any) if (path [0] == L'"') { StringCbCopyW (filePath, sizeof(filePath), path + 1); } else { StringCbCopyW (filePath, sizeof(filePath), path); } // Strip quotation marks (if any) if (filePath [wcslen (filePath) - 1] == L'"') filePath [wcslen (filePath) - 1] = 0; fileInfo.cbStruct = sizeof(WINTRUST_FILE_INFO); fileInfo.pcwszFilePath = filePath; fileInfo.hFile = NULL; WVTData.cbStruct = sizeof(WINTRUST_DATA); WVTData.dwUIChoice = WTD_UI_NONE; WVTData.fdwRevocationChecks = WTD_REVOKE_NONE; WVTData.dwUnionChoice = WTD_CHOICE_FILE; WVTData.pFile = &fileInfo; WVTData.dwStateAction = WTD_STATEACTION_VERIFY; WVTData.dwProvFlags = WTD_REVOCATION_CHECK_NONE | WTD_CACHE_ONLY_URL_RETRIEVAL; hResult = WinVerifyTrust(0, &gActionID, &WVTData); if (0 == hResult) { PCRYPT_PROVIDER_DATA pProviderData = WTHelperProvDataFromStateData (WVTData.hWVTStateData); @@ -1061,63 +1057,60 @@ static BOOL GetWindowVersionFromFile(DWORD* pdwMajor, DWORD* pdwMinor, DWORD* pd *pdwBuildNumber = HIWORD(vinfo->dwProductVersionLS); bRet = TRUE; } } } if (versionInfo) TCfree(versionInfo); return bRet; } #endif /* * Use RtlGetVersion to get Windows version because GetVersionEx is affected by application manifestation. */ typedef NTSTATUS (WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); static BOOL GetWindowsVersion(LPOSVERSIONINFOW lpVersionInformation) { BOOL bRet = FALSE; #ifdef SETUP_DLL DWORD dwMajor, dwMinor, dwBuildNumber; #endif RtlGetVersionPtr RtlGetVersionFn = (RtlGetVersionPtr) GetProcAddress(GetModuleHandle (L"ntdll.dll"), "RtlGetVersion"); if (RtlGetVersionFn != NULL) { if (ERROR_SUCCESS == RtlGetVersionFn (lpVersionInformation)) bRet = TRUE; } - if (!bRet) - bRet = GetVersionExW (lpVersionInformation); - #ifdef SETUP_DLL // we get real version from Kernel32.dll version since MSI always sets current version to 6.0 // https://stackoverflow.com/questions/49335885/windows-10-not-detecting-on-installshield/49343826#49343826 if (GetWindowVersionFromFile(&dwMajor, &dwMinor, &dwBuildNumber)) { lpVersionInformation->dwMajorVersion = dwMajor; lpVersionInformation->dwMinorVersion = dwMinor; lpVersionInformation->dwBuildNumber = dwBuildNumber; } #endif return bRet; } void InitOSVersionInfo () { OSVERSIONINFOEXW os; os.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW); if (GetWindowsVersion ((LPOSVERSIONINFOW) &os) == FALSE) AbortProcess ("NO_OS_VER"); CurrentOSMajor = os.dwMajorVersion; CurrentOSMinor = os.dwMinorVersion; CurrentOSServicePack = os.wServicePackMajor; CurrentOSBuildNumber = os.dwBuildNumber; if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 5 && CurrentOSMinor == 0) nCurrentOS = WIN_2000; @@ -3144,61 +3137,61 @@ static LRESULT CALLBACK NonInstallUacWndProc (HWND hWnd, UINT message, WPARAM wP { return DefWindowProcW (hWnd, message, wParam, lParam); } BOOL LaunchElevatedProcess (HWND hwndDlg, const wchar_t* szModPath, const wchar_t* args) { wchar_t newCmdLine[4096]; WNDCLASSEXW wcex; HWND hWnd; memset (&wcex, 0, sizeof (wcex)); wcex.cbSize = sizeof(WNDCLASSEX); wcex.lpfnWndProc = (WNDPROC) NonInstallUacWndProc; wcex.hInstance = hInst; 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, hInst, NULL); SetLayeredWindowAttributes (hWnd, 0, 0, LWA_ALPHA); ShowWindow (hWnd, SW_SHOWNORMAL); StringCbCopyW (newCmdLine, sizeof(newCmdLine), L"/q UAC "); StringCbCatW (newCmdLine, sizeof (newCmdLine), args); - if ((int)ShellExecuteW (hWnd, L"runas", szModPath, newCmdLine, NULL, SW_SHOWNORMAL) <= 32) + if ((INT_PTR)ShellExecuteW (hWnd, L"runas", szModPath, newCmdLine, NULL, SW_SHOWNORMAL) <= 32) { if (hwndDlg) handleWin32Error (hwndDlg, SRC_POS); return FALSE; } else { Sleep (2000); return TRUE; } } // 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) { @@ -3576,64 +3569,64 @@ extern "C" { // activate process mitigations (currently only ASLR, dynamic code and extensions points) ActivateProcessMitigations(); #ifndef SETUP // call ActivateMemoryProtection if corresponding setting has been enabled (default is enabled) if (ReadMemoryProtectionConfig()) { ActivateMemoryProtection(); } #endif return wWinMainCRTStartup(); } } #endif /* 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]; SetDefaultDllDirectoriesPtr SetDefaultDllDirectoriesFn = NULL; #if !defined(SETUP) wchar_t modPath[MAX_PATH]; #endif INITCOMMONCONTROLSEX InitCtrls; InitOSVersionInfo(); - if (!IsOSAtLeast (WIN_7)) + if (!IsOSAtLeast (WIN_10)) { - // abort using a message that says that VeraCrypt can run only on Windows 7 and later and that it is officially supported only on Windows 10 and later - AbortProcessDirect(L"VeraCrypt requires at least Windows 7 to run."); + // abort using a message that says that VeraCrypt can run only on Windows 10 and later + AbortProcessDirect(L"VeraCrypt requires at least Windows 10 to run."); } SetDefaultDllDirectoriesFn = (SetDefaultDllDirectoriesPtr) GetProcAddress (GetModuleHandle(L"kernel32.dll"), "SetDefaultDllDirectories"); if (!SetDefaultDllDirectoriesFn) { // This can happen only if KB2533623 is missing from Windows 7 AbortProcessDirect(L"VeraCrypt requires KB2533623 to be installed on Windows 7 and Windows Server 2008 R2 in order to run."); } VirtualLock (&CmdTokenPin, sizeof (CmdTokenPin)); InitGlobalLocks (); // call InitCommonControlsEx function to initialize the common controls InitCtrls.dwSize = sizeof (InitCtrls); InitCtrls.dwICC = ICC_WIN95_CLASSES | ICC_PAGESCROLLER_CLASS | ICC_NATIVEFNTCTL_CLASS | ICC_STANDARD_CLASSES | ICC_LINK_CLASS; InitCommonControlsEx (&InitCtrls); // Load RichEdit library in order to be able to use RichEdit20W class LoadLibraryEx (L"Riched20.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); #if !defined(SETUP) GetModuleFileNameW (NULL, modPath, ARRAYSIZE (modPath)); if (!VerifyModuleSignature (modPath)) AbortProcessDirect (L"This distribution package is damaged. Please try downloading it again (preferably from the official VeraCrypt website at https://www.veracrypt.fr)."); #endif #ifndef SETUP /* enable drag-n-drop when we are running elevated */ AllowMessageInUIPI (WM_DROPFILES); @@ -3889,95 +3882,96 @@ BOOL OpenDevice (const wchar_t *lpszPath, OPEN_TEST_STRUCT *driver, BOOL detectF { driver->TCBootLoaderDetected = FALSE; driver->FilesystemDetected = FALSE; memset (driver->VolumeIDComputed, 0, sizeof (driver->VolumeIDComputed)); return TRUE; } else return FALSE; } return TRUE; } #endif // 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 }; + wchar_t root[] = { (wchar_t) (L'A' + driveNo), L':', L'\\', 0 }; return GetVolumeInformationW (root, label, labelSize / 2, NULL, NULL, &fileSystemFlags, NULL, 0); } #ifndef SETUP /* 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()); } // Find extra boot partition - foreach (const HostDevice &drive, GetAvailableHostDevices (false, false)) + std::vector <HostDevice> devices = GetAvailableHostDevices(false, false); + for (const HostDevice& drive : devices) { if (drive.ContainsSystem) { - foreach (const HostDevice &sysDrivePartition, drive.Partitions) + for (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 @@ -5367,88 +5361,88 @@ BOOL SelectMultipleFiles(HWND hwndDlg, const char *stringId, BOOL keepHistory, s hr = psiaResults->GetItemAt(i, &psi); if (SUCCEEDED(hr)) { PWSTR pszFilePath; hr = psi->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath); if (SUCCEEDED(hr)) { filesList.push_back(pszFilePath); CoTaskMemFree(pszFilePath); } psi->Release(); } } status = TRUE; } psiaResults->Release(); } } if (!keepHistory) CleanLastVisitedMRU(); pfd->Release(); } CoUninitialize(); return status; } -BOOL BrowseDirectories(HWND hwndDlg, char *lpszTitle, wchar_t *dirName, const wchar_t *initialDir) +BOOL BrowseDirectories(HWND hwndDlg, char *lpszDlgTitle, wchar_t *dirName, const wchar_t *initialDir) { IFileDialog *pfd = NULL; HRESULT hr; BOOL bOK = FALSE; hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); if (FAILED(hr)) { return FALSE; } hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd)); if (SUCCEEDED(hr)) { // Set the options on the dialog. DWORD dwFlags; hr = pfd->GetOptions(&dwFlags); if (SUCCEEDED(hr)) { dwFlags |= FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR; // Important to enable folder-picking mode hr = pfd->SetOptions(dwFlags); } // Set the title. - if (lpszTitle) + if (lpszDlgTitle) { - pfd->SetTitle(GetString(lpszTitle)); + pfd->SetTitle(GetString(lpszDlgTitle)); } IShellItem *psi; if (initialDir) { // Set the initial directory, if provided. hr = SHCreateItemFromParsingName(initialDir, NULL, IID_PPV_ARGS(&psi)); } else { // set folder to "This PC" shel item hr = SHCreateItemInKnownFolder(FOLDERID_ComputerFolder, 0, NULL, IID_PPV_ARGS(&psi)); } if (SUCCEEDED(hr)) { pfd->SetFolder(psi); psi->Release(); } // Show the dialog. hr = pfd->Show(hwndDlg); if (SUCCEEDED(hr)) { // Obtain the result when the user clicks the "OK" button. // The result is an IShellItem object. IShellItem *pItem; hr = pfd->GetResult(&pItem); if (SUCCEEDED(hr)) { PWSTR pszFolderPath; @@ -5732,61 +5726,61 @@ static BOOL CALLBACK CloseVolumeExplorerWindowsEnum (HWND hwnd, LPARAM driveNo) { 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}; + wchar_t driveStr[] = { (wchar_t) (L'A' + 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); } @@ -6239,99 +6233,99 @@ static BOOL PerformBenchmark(HWND hBenchDlg, HWND hwndDlg) STREEBOG_init(&stctx); STREEBOG_add(&stctx, lpTestBuffer, benchmarkBufferSize); STREEBOG_finalize(&stctx, (unsigned char *)digest); break; } #endif } 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 / 2)); StringCbPrintfW (benchmarkTable[benchmarkTotalItems].name, sizeof(benchmarkTable[benchmarkTotalItems].name),L"%s", HashGetName(hid)); benchmarkTotalItems++; } } break; case BENCHMARK_TYPE_PRF: /* Measures the time that it takes for the PKCS-5 routine to derive a header key using each of the implemented PRF algorithms. */ { int thid, i; - char dk[MASTER_KEYDATA_SIZE]; + unsigned 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 (benchmarkPreBoot && !benchmarkGPT && !HashForSystemEncryption (thid)) continue; if (QueryPerformanceCounter (&performanceCountStart) == 0) goto counter_error; for (i = 1; i <= 2; 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, benchmarkPim, benchmarkPreBoot), dk, MASTER_KEYDATA_SIZE); + derive_key_sha512 ((unsigned char*) "passphrase-1234567890", 21, (unsigned char*) tmp_salt, 64, get_pkcs5_iteration_count(thid, benchmarkPim, benchmarkPreBoot), 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, benchmarkPim, benchmarkPreBoot), dk, MASTER_KEYDATA_SIZE); + derive_key_sha256 ((unsigned char*)"passphrase-1234567890", 21, (unsigned char*) tmp_salt, 64, get_pkcs5_iteration_count(thid, benchmarkPim, benchmarkPreBoot), dk, MASTER_KEYDATA_SIZE); break; #ifndef WOLFCRYPT_BACKEND case BLAKE2S: /* PKCS-5 test with HMAC-BLAKE2s used as the PRF */ - derive_key_blake2s ("passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, benchmarkPim, benchmarkPreBoot), dk, MASTER_KEYDATA_SIZE); + derive_key_blake2s ((unsigned char*)"passphrase-1234567890", 21, (unsigned char*) tmp_salt, 64, get_pkcs5_iteration_count(thid, benchmarkPim, benchmarkPreBoot), 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, benchmarkPim, benchmarkPreBoot), dk, MASTER_KEYDATA_SIZE); + derive_key_whirlpool ((unsigned char*)"passphrase-1234567890", 21, (unsigned char*) tmp_salt, 64, get_pkcs5_iteration_count(thid, benchmarkPim, benchmarkPreBoot), dk, MASTER_KEYDATA_SIZE); break; case STREEBOG: /* PKCS-5 test with HMAC-STREEBOG used as the PRF */ - derive_key_streebog("passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, benchmarkPim, benchmarkPreBoot), dk, MASTER_KEYDATA_SIZE); + derive_key_streebog((unsigned char*)"passphrase-1234567890", 21, (unsigned char*) tmp_salt, 64, get_pkcs5_iteration_count(thid, benchmarkPim, benchmarkPreBoot), dk, MASTER_KEYDATA_SIZE); break; } #endif } if (QueryPerformanceCounter (&performanceCountEnd) == 0) goto counter_error; benchmarkTable[benchmarkTotalItems].encSpeed = performanceCountEnd.QuadPart - performanceCountStart.QuadPart; benchmarkTable[benchmarkTotalItems].id = thid; benchmarkTable[benchmarkTotalItems].decSpeed = get_pkcs5_iteration_count(thid, benchmarkPim, benchmarkPreBoot); benchmarkTable[benchmarkTotalItems].meanBytesPerSec = (unsigned __int64) (1000 * ((float) benchmarkTable[benchmarkTotalItems].encSpeed / benchmarkPerformanceFrequency.QuadPart / 2)); if (benchmarkPreBoot) { /* heuristics for boot times */ if (benchmarkGPT) { benchmarkTable[benchmarkTotalItems].meanBytesPerSec = (benchmarkTable[benchmarkTotalItems].meanBytesPerSec * 8) / 5; } else { if (thid == SHA256) { #ifdef _WIN64 benchmarkTable[benchmarkTotalItems].meanBytesPerSec = (benchmarkTable[benchmarkTotalItems].meanBytesPerSec * 26); #else benchmarkTable[benchmarkTotalItems].meanBytesPerSec = (benchmarkTable[benchmarkTotalItems].meanBytesPerSec * 24); #endif } else @@ -7612,61 +7606,61 @@ CipherTestDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) for (ci->ea = EAGetFirst (); ci->ea != 0 ; ci->ea = EAGetNext (ci->ea)) if (EAGetCipherCount (ci->ea) == 1 && EAGetFirstCipher (ci->ea) == idTestCipher) break; if ((tmpRetVal = EAInit (ci->ea, (unsigned char *) key, ci->ks)) != ERR_SUCCESS) { handleError (hwndDlg, tmpRetVal, SRC_POS); crypto_close (ci); return 1; } memcpy (&ci->k2, secondaryKey, sizeof (secondaryKey)); if (!EAInitMode (ci, ci->k2)) { crypto_close (ci); return 1; } structDataUnitNo.Value = BE64(((unsigned __int64 *)dataUnitNo)[0]); if (bEncrypt) EncryptBufferXTS ((unsigned char *) tmp, pt, &structDataUnitNo, blockNo, (unsigned char *) (ci->ks), (unsigned char *) ci->ks2, idTestCipher); else DecryptBufferXTS ((unsigned char *) tmp, pt, &structDataUnitNo, blockNo, (unsigned char *) (ci->ks), (unsigned char *) ci->ks2, idTestCipher); crypto_close (ci); } else { - CipherInit2(idTestCipher, key, ks_tmp, ks); + CipherInit2(idTestCipher, key, ks_tmp); if (bEncrypt) { EncipherBlock(idTestCipher, tmp, ks_tmp); } else { DecipherBlock(idTestCipher, tmp, ks_tmp); } } *szTmp = 0; for (n = 0; n < pt; n ++) { wchar_t szTmp2[3]; StringCbPrintfW(szTmp2, sizeof(szTmp2), L"%02x", (int)((unsigned char)tmp[n])); StringCbCatW(szTmp, sizeof(szTmp), szTmp2); } if (bEncrypt) SetWindowText(GetDlgItem(hwndDlg,IDC_CIPHERTEXT), szTmp); else SetWindowText(GetDlgItem(hwndDlg,IDC_PLAINTEXT), szTmp); } return 1; } if (lw == IDCLOSE || lw == IDCANCEL) @@ -8234,61 +8228,61 @@ int DriverUnmountVolume (HWND hwndDlg, int nDosDriveNo, BOOL forced) return unmount.nReturnCode; } void BroadcastDeviceChange (WPARAM message, int nDosDriveNo, DWORD driveMap) { DEV_BROADCAST_VOLUME dbv; DWORD_PTR dwResult; LONG eventId = 0; int i; if (DeviceChangeBroadcastDisabled) return; if (message == DBT_DEVICEARRIVAL) eventId = SHCNE_DRIVEADD; else if (message == DBT_DEVICEREMOVECOMPLETE) eventId = SHCNE_DRIVEREMOVED; else if (message == DBT_DEVICEREMOVEPENDING) // Explorer on Windows 7 holds open handles of all drives when 'Computer' is expanded in navigation pane. SHCNE_DRIVEREMOVED must be used as DBT_DEVICEREMOVEPENDING is ignored. eventId = SHCNE_DRIVEREMOVED; if (driveMap == 0) driveMap = (1 << nDosDriveNo); if (eventId != 0) { for (i = 0; i < 26; i++) { if (driveMap & (1 << i)) { - wchar_t root[] = { (wchar_t) i + L'A', L':', L'\\', 0 }; + wchar_t root[] = { (wchar_t) (i + L'A'), L':', L'\\', 0 }; SHChangeNotify (eventId, SHCNF_PATH, root, NULL); } } } dbv.dbcv_size = sizeof (dbv); dbv.dbcv_devicetype = DBT_DEVTYP_VOLUME; dbv.dbcv_reserved = 0; dbv.dbcv_unitmask = driveMap; dbv.dbcv_flags = 0; UINT timeOut = 1000; // SHChangeNotify() works on Vista, so the Explorer does not require WM_DEVICECHANGE if (CurrentOSMajor >= 6) timeOut = 100; IgnoreWmDeviceChange = TRUE; SendMessageTimeout (HWND_BROADCAST, WM_DEVICECHANGE, message, (LPARAM)(&dbv), SMTO_ABORTIFHUNG, timeOut, &dwResult); // Explorer prior Vista sometimes fails to register a new drive if (CurrentOSMajor < 6 && message == DBT_DEVICEARRIVAL) SendMessageTimeout (HWND_BROADCAST, WM_DEVICECHANGE, message, (LPARAM)(&dbv), SMTO_ABORTIFHUNG, 200, &dwResult); IgnoreWmDeviceChange = FALSE; } static BOOL GetDeviceStorageProperty (HANDLE hDevice, STORAGE_PROPERTY_ID propertyId, DWORD dwDescSize, void* pDesc) @@ -8791,66 +8785,66 @@ retry: // put default values mount.BytesPerSector = 512; mount.BytesPerPhysicalSector = 512; mount.MaximumTransferLength = 65536; mount.MaximumPhysicalPages = 17; mount.AlignmentMask = 0; // UNC path if (path.find (L"\\\\") == 0) { StringCbCopyW (mount.wszVolume, sizeof (mount.wszVolume), (L"UNC" + path.substr (1)).c_str()); } if (GetVolumePathName (volumePath, root, ARRAYSIZE (root) - 1)) { DWORD bps, flags, d; if (GetDiskFreeSpace (root, &d, &bps, &d, &d)) { mount.BytesPerSector = bps; mount.BytesPerPhysicalSector = bps; } if ( (wcslen(root) >= 2) && (root[1] == L':') && (towupper(root[0]) >= L'A' && towupper(root[0]) <= L'Z') ) { wstring drivePath = L"\\\\.\\X:"; HANDLE dev = INVALID_HANDLE_VALUE; VOLUME_DISK_EXTENTS extents = {0}; - DWORD dwResult = 0; + DWORD cbReturnedBytes = 0; drivePath[4] = root[0]; if ((dev = CreateFile (drivePath.c_str(),0, 0, NULL, OPEN_EXISTING, 0, NULL)) != INVALID_HANDLE_VALUE) { - if (DeviceIoControl (dev, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &extents, sizeof(extents), &dwResult, NULL)) + if (DeviceIoControl (dev, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &extents, sizeof(extents), &cbReturnedBytes, NULL)) { if (extents.NumberOfDiskExtents > 0) { STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR accessDesc; STORAGE_ADAPTER_DESCRIPTOR adapterDesc; if (GetPhysicalDriveStorageInformation (extents.Extents[0].DiskNumber, &accessDesc, &adapterDesc)) { if (accessDesc.Size >= sizeof (STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR)) { mount.BytesPerSector = accessDesc.BytesPerLogicalSector; mount.BytesPerPhysicalSector = accessDesc.BytesPerPhysicalSector; } if (adapterDesc.Size >= sizeof (STORAGE_ADAPTER_DESCRIPTOR)) { mount.MaximumTransferLength = adapterDesc.MaximumTransferLength; mount.MaximumPhysicalPages = adapterDesc.MaximumPhysicalPages; mount.AlignmentMask = adapterDesc.AlignmentMask; } } } } CloseHandle (dev); } } // Read-only host filesystem if (!mount.bMountReadOnly && GetVolumeInformation (root, NULL, 0, NULL, &d, &flags, NULL, 0)) mount.bMountReadOnly = (flags & FILE_READ_ONLY_VOLUME) != 0; @@ -8933,165 +8927,165 @@ retry: } return -1; } if (!quiet && (!MultipleMountOperationInProgress || GetLastError() != ERROR_NOT_READY)) handleWin32Error (hwndDlg, SRC_POS); return -1; } if (mount.nReturnCode != 0) { if (mount.nReturnCode == ERR_PASSWORD_WRONG) { // Do not report wrong password, if not instructed to if (bReportWrongPassword) { IncreaseWrongPwdRetryCount (1); // We increase the count here only if bReportWrongPassword is TRUE, because "Auto-Mount All Devices" and other callers do it separately if (WrongPwdRetryCountOverLimit () && !mount.UseBackupHeader) { // Retry using embedded header backup (if any) mount.UseBackupHeader = TRUE; goto retry; } if (bDevice && mount.bProtectHiddenVolume) { - int driveNo; + int diskNo; - if (swscanf (volumePath, L"\\Device\\Harddisk%d\\Partition", &driveNo) == 1) + if (swscanf (volumePath, L"\\Device\\Harddisk%d\\Partition", &diskNo) == 1) { OPEN_TEST_STRUCT openTestStruct; memset (&openTestStruct, 0, sizeof (openTestStruct)); openTestStruct.bDetectTCBootLoader = TRUE; - StringCchPrintfW ((wchar_t *) openTestStruct.wszFileName, array_capacity (openTestStruct.wszFileName), L"\\Device\\Harddisk%d\\Partition0", driveNo); + StringCchPrintfW ((wchar_t *) openTestStruct.wszFileName, array_capacity (openTestStruct.wszFileName), L"\\Device\\Harddisk%d\\Partition0", diskNo); - DWORD dwResult; - if (DeviceIoControl (hDriver, TC_IOCTL_OPEN_TEST, &openTestStruct, sizeof (OPEN_TEST_STRUCT), &openTestStruct, sizeof (OPEN_TEST_STRUCT), &dwResult, NULL) && openTestStruct.TCBootLoaderDetected) + DWORD cbBytesReturned; + if (DeviceIoControl (hDriver, TC_IOCTL_OPEN_TEST, &openTestStruct, sizeof (OPEN_TEST_STRUCT), &openTestStruct, sizeof (OPEN_TEST_STRUCT), &cbBytesReturned, NULL) && openTestStruct.TCBootLoaderDetected) WarningDirect ((GetWrongPasswordErrorMessage (hwndDlg) + L"\n\n" + GetString ("HIDDEN_VOL_PROT_PASSWORD_US_KEYB_LAYOUT")).c_str(), hwndDlg); else handleError (hwndDlg, mount.nReturnCode, SRC_POS); } } else handleError (hwndDlg, mount.nReturnCode, SRC_POS); } return 0; } if (!quiet) handleError (hwndDlg, mount.nReturnCode, SRC_POS); return 0; } // Mount successful if (mount.UseBackupHeader != mountOptions->UseBackupHeader && mount.UseBackupHeader) { if (bReportWrongPassword && !Silent) Warning ("HEADER_DAMAGED_AUTO_USED_HEADER_BAK", hwndDlg); } LastMountedVolumeDirty = mount.FilesystemDirty; if (mount.VolumeMasterKeyVulnerable && !Silent) { Warning ("ERR_XTS_MASTERKEY_VULNERABLE", hwndDlg); } if (mount.FilesystemDirty) { wchar_t msg[1024]; - wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; + wchar_t mountPoint[] = { (wchar_t) (L'A' + driveNo), L':', 0 }; StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_VOLUME_DIRTY"), mountPoint); if (AskWarnYesNoStringTopmost (msg, hwndDlg) == IDYES) CheckFilesystem (hwndDlg, driveNo, TRUE); } if (mount.VolumeMountedReadOnlyAfterAccessDenied && !Silent && !bDevice && !FileHasReadOnlyAttribute (volumePath) && !IsFileOnReadOnlyFilesystem (volumePath)) { wchar_t msg[1024]; - wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; + wchar_t mountPoint[] = { (wchar_t) (L'A' + driveNo), L':', 0 }; StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_CONTAINER_FORCED_READ_ONLY"), mountPoint); WarningDirect (msg, hwndDlg); } if (mount.VolumeMountedReadOnlyAfterAccessDenied && !Silent && bDevice) { wchar_t msg[1024]; - wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; + wchar_t mountPoint[] = { (wchar_t)(L'A' + driveNo), L':', 0 }; StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_DEVICE_FORCED_READ_ONLY"), mountPoint); WarningDirect (msg, hwndDlg); } if (mount.VolumeMountedReadOnlyAfterDeviceWriteProtected && !Silent && wcsstr (volumePath, L"\\Device\\Harddisk") == volumePath) { wchar_t msg[1024]; - wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; + wchar_t mountPoint[] = { (wchar_t) (L'A' + driveNo), L':', 0 }; StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_DEVICE_FORCED_READ_ONLY_WRITE_PROTECTION"), mountPoint); WarningDirect (msg, hwndDlg); if (CurrentOSMajor >= 6 && wcsstr (volumePath, L"\\Device\\HarddiskVolume") != volumePath && AskNoYes ("ASK_REMOVE_DEVICE_WRITE_PROTECTION", hwndDlg) == IDYES) { RemoveDeviceWriteProtection (hwndDlg, volumePath); } } if (mount.VolumeMountedReadOnlyAfterPartialSysEnc && !Silent && bDevice) { wchar_t msg[1024]; - wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 }; + wchar_t mountPoint[] = { (wchar_t) (L'A' + driveNo), L':', 0 }; StringCbPrintfW (msg, sizeof(msg), GetString ("PARTIAL_SYSENC_MOUNT_READONLY"), mountPoint); WarningDirect (msg, hwndDlg); } if (mount.wszLabel[0] && !mount.bDriverSetLabel) { // try setting the drive label on user-mode using registry UpdateDriveCustomLabel (driveNo, mount.wszLabel, TRUE); } ResetWrongPwdRetryCount (); BroadcastDeviceChange (DBT_DEVICEARRIVAL, driveNo, 0); if (mount.bExclusiveAccess == FALSE) return 2; return 1; } #endif typedef struct { int nDosDriveNo; BOOL forced; int dismountMaxRetries; DWORD retryDelay; int* presult; @@ -9130,61 +9124,61 @@ retry: BroadcastDeviceChange (DBT_DEVICEREMOVEPENDING, nDosDriveNo, 0); param.nDosDriveNo = nDosDriveNo; param.forced = forced; param.dismountMaxRetries = dismountMaxRetries; param.retryDelay = retryDelay; param.presult = &result; if (Silent) { UnmountWaitThreadProc (¶m, hwndDlg); } else { ShowWaitDialog (hwndDlg, FALSE, UnmountWaitThreadProc, ¶m); } SetLastError (param.dwLastError); if (result != 0) { if (result == ERR_FILES_OPEN && !Silent) { if (IDYES == AskWarnYesNoTopmost ("UNMOUNT_LOCK_FAILED", hwndDlg)) { forced = TRUE; goto retry; } // Undo SHCNE_DRIVEREMOVED - wchar_t root[] = { (wchar_t) nDosDriveNo + L'A', L':', L'\\', 0 }; + wchar_t root[] = { (wchar_t) (nDosDriveNo + L'A'), L':', L'\\', 0 }; SHChangeNotify (SHCNE_DRIVEADD, SHCNF_PATH, root, NULL); return FALSE; } Error ("UNMOUNT_FAILED", hwndDlg); return FALSE; } BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, nDosDriveNo, 0); return TRUE; } BOOL UnmountVolume (HWND hwndDlg, int nDosDriveNo, BOOL forceUnmount) { return UnmountVolumeBase (hwndDlg, nDosDriveNo, forceUnmount, FALSE); } BOOL UnmountVolumeAfterFormatExCall (HWND hwndDlg, int nDosDriveNo) { return UnmountVolumeBase (hwndDlg, nDosDriveNo, FALSE, TRUE); } BOOL IsPasswordCacheEmpty (void) { DWORD dw; return !DeviceIoControl (hDriver, TC_IOCTL_GET_PASSWORD_CACHE_STATUS, 0, 0, 0, 0, &dw, 0); } @@ -9484,61 +9478,61 @@ BOOL GetPhysicalDriveGeometry (int driveNumber, PDISK_GEOMETRY_EX diskGeometry) && (bytesRead >= sizeof (storage)) && (storage.Size == sizeof (STORAGE_READ_CAPACITY)) ) { diskGeometry->DiskSize.QuadPart = storage.DiskLength.QuadPart; } } } } CloseHandle (hDev); } return bResult; } #endif // Returns drive letter number assigned to device (-1 if none) int GetDiskDeviceDriveLetter (PWSTR deviceName) { int i; WCHAR link[MAX_PATH]; WCHAR target[MAX_PATH]; WCHAR device[MAX_PATH]; if (!ResolveSymbolicLink (deviceName, device, sizeof(device))) StringCchCopyW (device, MAX_PATH, deviceName); for (i = 0; i < 26; i++) { - WCHAR drive[] = { (WCHAR) i + L'A', L':', 0 }; + WCHAR drive[] = { (WCHAR) (i + L'A'), L':', 0 }; StringCchCopyW (link, MAX_PATH, L"\\DosDevices\\"); StringCchCatW (link, MAX_PATH, drive); if ( ResolveSymbolicLink (link, target, sizeof(target)) && (wcscmp (device, target) == 0) ) { return i; } } return -1; } // WARNING: This function does NOT provide 100% reliable results -- do NOT use it for critical/dangerous operations! // Return values: 0 - filesystem does not appear empty, 1 - filesystem appears empty, -1 - an error occurred int FileSystemAppearsEmpty (const wchar_t *devicePath) { float percentFreeSpace = 0.0; __int64 occupiedBytes = 0; if (GetStatsFreeSpaceOnPartition (devicePath, &percentFreeSpace, &occupiedBytes, TRUE) != -1) { if (occupiedBytes > BYTES_PER_GB && percentFreeSpace < 99.99 // "percentFreeSpace < 99.99" is needed because an NTFS filesystem larger than several terabytes can have more than 1GB of data in use, even if there are no files stored on it. || percentFreeSpace < 88) // A 24-MB NTFS filesystem has 11.5% of space in use even if there are no files stored on it. { return 0; } @@ -10682,66 +10676,66 @@ void ConfigReadCompareString (char *configKey, char *defaultValue, char *str, in *pbModified = TRUE; if (!bOnlyCheckModified) memcpy(str, strValue, maxLen); free (strValue); } else { /* allocation failed. Suppose that value changed */ if (pbModified) *pbModified = TRUE; if (!bOnlyCheckModified) ConfigReadString (configKey, defaultValue, str, maxLen); } } void OpenPageHelp (HWND hwndDlg, int nPage) { if (IsAdmin ()) { if (FileExists (szHelpFile)) SafeOpenURL (szHelpFile); else if (FileExists (szHelpFile2)) SafeOpenURL (szHelpFile2); else Applink ("help"); } else { - int r = (int)ShellExecuteW (NULL, L"open", szHelpFile, NULL, NULL, SW_SHOWNORMAL); + INT_PTR r = (INT_PTR)ShellExecuteW (NULL, L"open", szHelpFile, NULL, NULL, SW_SHOWNORMAL); if (r == ERROR_FILE_NOT_FOUND) { // Try the secondary help file - r = (int)ShellExecuteW (NULL, L"open", szHelpFile2, NULL, NULL, SW_SHOWNORMAL); + r = (INT_PTR)ShellExecuteW (NULL, L"open", szHelpFile2, NULL, NULL, SW_SHOWNORMAL); if (r == ERROR_FILE_NOT_FOUND) { // Open local HTML help. It will fallback to online help if not found. Applink ("help"); return; } } if (r == SE_ERR_NOASSOC) { if (AskYesNo ("HELP_READER_ERROR", MainDlg) == IDYES) OpenOnlineHelp (); } } } void OpenOnlineHelp () { Applink ("onlinehelp"); } #ifndef SETUP void RestoreDefaultKeyFilesParam (void) { KeyFileRemoveAll (&FirstKeyFile); if (defaultKeyFilesParam.FirstKeyFile != NULL) @@ -10914,68 +10908,65 @@ BOOL IsARM() if (fnIsWow64Process2) { USHORT processMachine, nativeMachine; if (fnIsWow64Process2(GetCurrentProcess(), &processMachine, &nativeMachine)) { if (IMAGE_FILE_MACHINE_ARM64 == nativeMachine || IMAGE_FILE_MACHINE_ARM == nativeMachine) isARM = TRUE; else isARM = FALSE; valid = TRUE; } } if (!valid) { SYSTEM_INFO systemInfo; GetNativeSystemInfo(&systemInfo); if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM || systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM64) isARM = TRUE; else isARM = FALSE; } valid = TRUE; return isARM; #endif } BOOL IsServerOS () { - OSVERSIONINFOEXW osVer; - osVer.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW); - GetVersionExW ((LPOSVERSIONINFOW) &osVer); - - return (osVer.wProductType == VER_NT_SERVER || osVer.wProductType == VER_NT_DOMAIN_CONTROLLER); + return IsWindowsServer()? TRUE : FALSE; } + // Returns TRUE, if the currently running operating system is installed in a hidden volume. If it's not, or if // there's an error, returns FALSE. BOOL IsHiddenOSRunning (void) { static BOOL statusCached = FALSE; static BOOL hiddenOSRunning; if (!statusCached) { try { hiddenOSRunning = BootEncryption (MainDlg).IsHiddenSystemRunning(); } catch (...) { hiddenOSRunning = FALSE; } statusCached = TRUE; } return hiddenOSRunning; } BOOL EnableWow64FsRedirection (BOOL enable) { typedef BOOLEAN (__stdcall *Wow64EnableWow64FsRedirection_t) (BOOL enable); Wow64EnableWow64FsRedirection_t wow64EnableWow64FsRedirection = (Wow64EnableWow64FsRedirection_t) GetProcAddress (GetModuleHandle (L"kernel32"), "Wow64EnableWow64FsRedirection"); @@ -10996,167 +10987,173 @@ BOOL RestartComputer (BOOL bShutdown) return false; } LookupPrivilegeValue (NULL, SE_SHUTDOWN_NAME, &tokenPrivil.Privileges[0].Luid); tokenPrivil.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; tokenPrivil.PrivilegeCount = 1; AdjustTokenPrivileges (hTkn, false, &tokenPrivil, 0, (PTOKEN_PRIVILEGES) NULL, 0); if (GetLastError() != ERROR_SUCCESS) { CloseHandle(hTkn); return false; } if (!ExitWindowsEx (bShutdown? EWX_POWEROFF: EWX_REBOOT, SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED)) { CloseHandle(hTkn); return false; } CloseHandle(hTkn); return true; } std::wstring GetWindowsEdition () { wstring osname = L"win"; - OSVERSIONINFOEXW osVer; + OSVERSIONINFOEXW osVer = { 0 }; osVer.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW); - GetVersionExW ((LPOSVERSIONINFOW) &osVer); + if (GetWindowsVersion((LPOSVERSIONINFOW)&osVer)) + { - BOOL home = (osVer.wSuiteMask & VER_SUITE_PERSONAL); - BOOL server = (osVer.wProductType == VER_NT_SERVER || osVer.wProductType == VER_NT_DOMAIN_CONTROLLER); + BOOL home = (osVer.wSuiteMask & VER_SUITE_PERSONAL); + BOOL server = (osVer.wProductType == VER_NT_SERVER || osVer.wProductType == VER_NT_DOMAIN_CONTROLLER); - HKEY hkey; - wchar_t productName[300] = {0}; - DWORD productNameSize = sizeof (productName); - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS) - { - if (RegQueryValueEx (hkey, L"ProductName", 0, 0, (LPBYTE) &productName, &productNameSize) != ERROR_SUCCESS || productNameSize < 1) - productName[0] = 0; + HKEY hkey; + wchar_t productName[300] = { 0 }; + DWORD productNameSize = sizeof(productName); + if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS) + { + if (RegQueryValueEx(hkey, L"ProductName", 0, 0, (LPBYTE)&productName, &productNameSize) != ERROR_SUCCESS || productNameSize < 1) + productName[0] = 0; - RegCloseKey (hkey); - } + RegCloseKey(hkey); + } - switch (nCurrentOS) - { - case WIN_2000: - osname += L"2000"; - break; + switch (nCurrentOS) + { + case WIN_2000: + osname += L"2000"; + break; - case WIN_XP: - case WIN_XP64: - osname += L"xp"; - osname += home ? L"-home" : L"-pro"; - break; + case WIN_XP: + case WIN_XP64: + osname += L"xp"; + osname += home ? L"-home" : L"-pro"; + break; - case WIN_SERVER_2003: - osname += L"2003"; - break; + case WIN_SERVER_2003: + osname += L"2003"; + break; - case WIN_VISTA: - osname += L"vista"; - break; + case WIN_VISTA: + osname += L"vista"; + break; - case WIN_SERVER_2008: - osname += L"2008"; - break; + case WIN_SERVER_2008: + osname += L"2008"; + break; - case WIN_7: - osname += L"7"; - break; + case WIN_7: + osname += L"7"; + break; - case WIN_SERVER_2008_R2: - osname += L"2008r2"; - break; + case WIN_SERVER_2008_R2: + osname += L"2008r2"; + break; - default: - wstringstream s; - s << CurrentOSMajor << L"." << CurrentOSMinor; - osname += s.str(); - break; - } + default: + wstringstream s; + s << CurrentOSMajor << L"." << CurrentOSMinor; + osname += s.str(); + break; + } - if (server) - osname += L"-server"; + if (server) + osname += L"-server"; - if (IsOSAtLeast (WIN_VISTA)) - { - if (home) - osname += L"-home"; - else if (wcsstr (productName, L"Standard") != 0) - osname += L"-standard"; - else if (wcsstr (productName, L"Professional") != 0) - osname += L"-pro"; - else if (wcsstr (productName, L"Business") != 0) - osname += L"-business"; - else if (wcsstr (productName, L"Enterprise") != 0) - osname += L"-enterprise"; - else if (wcsstr (productName, L"Datacenter") != 0) - osname += L"-datacenter"; - else if (wcsstr (productName, L"Ultimate") != 0) - osname += L"-ultimate"; - } + if (IsOSAtLeast(WIN_VISTA)) + { + if (home) + osname += L"-home"; + else if (wcsstr(productName, L"Standard") != 0) + osname += L"-standard"; + else if (wcsstr(productName, L"Professional") != 0) + osname += L"-pro"; + else if (wcsstr(productName, L"Business") != 0) + osname += L"-business"; + else if (wcsstr(productName, L"Enterprise") != 0) + osname += L"-enterprise"; + else if (wcsstr(productName, L"Datacenter") != 0) + osname += L"-datacenter"; + else if (wcsstr(productName, L"Ultimate") != 0) + osname += L"-ultimate"; + } + + if (GetSystemMetrics(SM_STARTER)) + osname += L"-starter"; + else if (wcsstr(productName, L"Basic") != 0) + osname += L"-basic"; - if (GetSystemMetrics (SM_STARTER)) - osname += L"-starter"; - else if (wcsstr (productName, L"Basic") != 0) - osname += L"-basic"; + if (Is64BitOs()) + osname += IsARM() ? L"-arm64" : L"-x64"; - if (Is64BitOs()) - osname += IsARM()? L"-arm64" : L"-x64"; + if (CurrentOSServicePack > 0) + { + wstringstream s; + s << L"-sp" << CurrentOSServicePack; + osname += s.str(); + } - if (CurrentOSServicePack > 0) + return osname; + } + else { - wstringstream s; - s << L"-sp" << CurrentOSServicePack; - osname += s.str(); + return L""; } - - return osname; } #ifdef SETUP extern wchar_t InstallationPath[TC_MAX_PATH]; #endif void Applink (const char *dest) { wchar_t url [MAX_URL_LENGTH] = {0}; wchar_t page[TC_MAX_PATH] = {0}; wchar_t installDir[TC_MAX_PATH] = {0}; BOOL buildUrl = TRUE; - int r; + INT_PTR r; ArrowWaitCursor (); #ifdef SETUP StringCbCopyW (installDir, sizeof (installDir), InstallationPath); #else GetModPath (installDir, TC_MAX_PATH); #endif if (strcmp(dest, "donate") == 0) { StringCbCopyW (page, sizeof (page),L"Donation.html"); } else if (strcmp(dest, "main") == 0) { StringCbCopyW (url, sizeof (url), TC_HOMEPAGE); buildUrl = FALSE; } else if (strcmp(dest,"localizations") == 0) { StringCbCopyW (page, sizeof (page),L"Language%20Packs.html"); } else if (strcmp(dest, "beginnerstutorial") == 0 || strcmp(dest,"tutorial") == 0) { StringCbCopyW (page, sizeof (page),L"Beginner%27s%20Tutorial.html"); } else if (strcmp(dest, "releasenotes") == 0 || strcmp(dest, "history") == 0) { StringCbCopyW (page, sizeof (page),L"Release%20Notes.html"); } @@ -11306,61 +11303,61 @@ void Applink (const char *dest) if (buildUrl) { wchar_t pageFileName [TC_MAX_PATH] = {0}; DWORD cchUnescaped = ARRAYSIZE(pageFileName); StringCbCopyW (pageFileName, sizeof(pageFileName), page); /* remove escape sequences from the page name before calling FileExists function */ if (S_OK == UrlUnescapeW (pageFileName, pageFileName, &cchUnescaped, URL_UNESCAPE_INPLACE)) { std::wstring pageFullPath = installDir; pageFullPath += L"docs\\html\\en\\"; pageFullPath += pageFileName; if (!FileExists (pageFullPath.c_str())) { // fallback to online resources StringCbPrintfW (url, sizeof (url), L"https://www.veracrypt.fr/en/%s", page); SafeOpenURL (url); openDone = 1; } } } if (!openDone) { SafeOpenURL (url); } } else { - r = (int) ShellExecuteW (NULL, L"open", url, NULL, NULL, SW_SHOWNORMAL); + r = (INT_PTR) ShellExecuteW (NULL, L"open", url, NULL, NULL, SW_SHOWNORMAL); if (((r == ERROR_FILE_NOT_FOUND) || (r == ERROR_PATH_NOT_FOUND)) && buildUrl) { // fallback to online resources StringCbPrintfW (url, sizeof (url), L"https://www.veracrypt.fr/en/%s", page); ShellExecuteW (NULL, L"open", url, NULL, NULL, SW_SHOWNORMAL); } } Sleep (200); NormalCursor (); } wchar_t *RelativePath2Absolute (wchar_t *szFileName) { if (szFileName[0] != L'\\' && wcschr (szFileName, L':') == 0 && wcsstr (szFileName, L"Volume{") != szFileName) { wchar_t path[MAX_PATH*2]; GetCurrentDirectory (MAX_PATH, path); if (path[wcslen (path) - 1] != L'\\') StringCbCatW (path, (MAX_PATH * 2), L"\\"); StringCbCatW (path, (MAX_PATH * 2), szFileName); StringCbCopyW (szFileName, MAX_PATH + 1, path); // szFileName size is always at least (MAX_PATH + 1) } @@ -11453,61 +11450,61 @@ BYTE *MapResource (wchar_t *resourceType, int resourceId, PDWORD size) return (BYTE *) LockResource (hResL); } void InconsistencyResolved (char *techInfo) { wchar_t finalMsg[8024]; StringCbPrintfW (finalMsg, sizeof(finalMsg), GetString ("INCONSISTENCY_RESOLVED"), techInfo); MessageBoxW (MainDlg, finalMsg, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); } void ReportUnexpectedState (const char *techInfo) { wchar_t finalMsg[8024]; StringCbPrintfW (finalMsg, sizeof(finalMsg), GetString ("UNEXPECTED_STATE"), techInfo); MessageBoxW (MainDlg, finalMsg, lpszTitle, MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); } #ifndef SETUP int OpenVolume (OpenVolumeContext *context, const wchar_t *volumePath, Password *password, int pkcs5_prf, int pim, BOOL write, BOOL preserveTimestamps, BOOL useBackupHeader) { int status = ERR_PARAMETER_INCORRECT; int volumeType; wchar_t szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH]; wchar_t szDosDevice[TC_MAX_PATH]; - char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; + unsigned char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; LARGE_INTEGER headerOffset; DWORD dwResult; DISK_GEOMETRY_EX deviceGeometry; context->VolumeIsOpen = FALSE; context->CryptoInfo = NULL; context->HostFileHandle = INVALID_HANDLE_VALUE; context->TimestampsValid = FALSE; CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), volumePath, &context->IsDevice); if (context->IsDevice) { status = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice), szCFDevice, sizeof(szCFDevice), FALSE); if (status != 0) return status; preserveTimestamps = FALSE; if (!GetDriveGeometry (volumePath, &deviceGeometry)) { status = ERR_OS_ERROR; goto error; } } else StringCbCopyW (szCFDevice, sizeof(szCFDevice), szDiskFile); context->HostFileHandle = CreateFile (szCFDevice, GENERIC_READ | (write ? GENERIC_WRITE : (!context->IsDevice && preserveTimestamps? FILE_WRITE_ATTRIBUTES : 0)), FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); @@ -11667,61 +11664,61 @@ error: SetLastError (sysError); return status; } void CloseVolume (OpenVolumeContext *context) { if (!context->VolumeIsOpen) return; if (context->HostFileHandle != INVALID_HANDLE_VALUE) { if (context->TimestampsValid) SetFileTime (context->HostFileHandle, &context->CreationTime, &context->LastAccessTime, &context->LastWriteTime); CloseHandle (context->HostFileHandle); context->HostFileHandle = INVALID_HANDLE_VALUE; } if (context->CryptoInfo) { crypto_close (context->CryptoInfo); context->CryptoInfo = NULL; } context->VolumeIsOpen = FALSE; } -int ReEncryptVolumeHeader (HWND hwndDlg, char *buffer, BOOL bBoot, CRYPTO_INFO *cryptoInfo, Password *password, int pim, BOOL wipeMode) +int ReEncryptVolumeHeader (HWND hwndDlg, unsigned char *buffer, BOOL bBoot, CRYPTO_INFO *cryptoInfo, Password *password, int pim, BOOL wipeMode) { CRYPTO_INFO *newCryptoInfo = NULL; RandSetHashFunction (cryptoInfo->pkcs5); if (Randinit() != ERR_SUCCESS) { if (CryptoAPILastError == ERROR_SUCCESS) return ERR_RAND_INIT_FAILED; else return ERR_CAPI_INIT_FAILED; } UserEnrichRandomPool (NULL); int status = CreateVolumeHeaderInMemory (hwndDlg, bBoot, buffer, cryptoInfo->ea, cryptoInfo->mode, password, cryptoInfo->pkcs5, pim, (char *) cryptoInfo->master_keydata, &newCryptoInfo, cryptoInfo->VolumeSize.Value, cryptoInfo->hiddenVolume ? cryptoInfo->hiddenVolumeSize : 0, cryptoInfo->EncryptedAreaStart.Value, cryptoInfo->EncryptedAreaLength.Value, cryptoInfo->RequiredProgramVersion, cryptoInfo->HeaderFlags, @@ -13032,61 +13029,61 @@ wstring FindDeviceByVolumeID (const BYTE volumeID [VOLUME_ID_SIZE], BOOL bFromSe return L""; } #endif // !SETUP BOOL FileHasReadOnlyAttribute (const wchar_t *path) { DWORD attributes = GetFileAttributes (path); return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_READONLY) != 0; } BOOL IsFileOnReadOnlyFilesystem (const wchar_t *path) { wchar_t root[MAX_PATH]; if (!GetVolumePathName (path, root, ARRAYSIZE (root))) return FALSE; DWORD flags, d; if (!GetVolumeInformation (root, NULL, 0, NULL, &d, &flags, NULL, 0)) return FALSE; return (flags & FILE_READ_ONLY_VOLUME) ? TRUE : FALSE; } void CheckFilesystem (HWND hwndDlg, int driveNo, BOOL fixErrors) { wchar_t msg[1024], param[1024], cmdPath[MAX_PATH]; - wchar_t driveRoot[] = { L'A' + (wchar_t) driveNo, L':', 0 }; + wchar_t driveRoot[] = { (wchar_t) (L'A' + driveNo), L':', 0 }; if (fixErrors && AskWarnYesNo ("FILESYS_REPAIR_CONFIRM_BACKUP", hwndDlg) == IDNO) return; StringCbPrintfW (msg, sizeof(msg), GetString (fixErrors ? "REPAIRING_FS" : "CHECKING_FS"), driveRoot); StringCbPrintfW (param, sizeof(param), fixErrors ? L"/C echo %s & chkdsk %s /F /X & pause" : L"/C echo %s & chkdsk %s & pause", msg, driveRoot); if (GetSystemDirectoryW(cmdPath, MAX_PATH)) { StringCbCatW(cmdPath, sizeof(cmdPath), L"\\cmd.exe"); } else StringCbCopyW(cmdPath, sizeof(cmdPath), L"C:\\Windows\\System32\\cmd.exe"); ShellExecuteW (NULL, (!IsAdmin() && IsUacSupported()) ? L"runas" : L"open", cmdPath, param, NULL, SW_SHOW); } BOOL BufferContainsPattern (const uint8 *buffer, size_t bufferSize, const uint8 *pattern, size_t patternSize) { if (bufferSize < patternSize) return FALSE; bufferSize -= patternSize; for (size_t i = 0; i < bufferSize; ++i) { if (memcmp (buffer + i, pattern, patternSize) == 0) return TRUE; } @@ -13278,72 +13275,72 @@ BOOL VolumePathExists (const wchar_t *volumePath) return TRUE; else { DWORD dwResult = GetLastError (); if (dwResult == ERROR_SHARING_VIOLATION) return TRUE; else return FALSE; } } BOOL IsWindowsIsoBurnerAvailable () { wchar_t path[MAX_PATH*2] = { 0 }; if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_SYSTEM, NULL, 0, path))) { StringCbCatW (path, MAX_PATH*2, L"\\" ISO_BURNER_TOOL); return (FileExists (path)); } return FALSE; } BOOL LaunchWindowsIsoBurner (HWND hwnd, const wchar_t *isoPath) { wchar_t path[MAX_PATH*2] = { 0 }; - int r; + INT_PTR r; if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_SYSTEM, NULL, 0, path))) StringCbCatW (path, MAX_PATH*2, L"\\" ISO_BURNER_TOOL); else StringCbCopyW (path, MAX_PATH*2, L"C:\\Windows\\System32\\" ISO_BURNER_TOOL); - r = (int) ShellExecute (hwnd, L"open", path, (wstring (L"\"") + isoPath + L"\"").c_str(), NULL, SW_SHOWNORMAL); + r = (INT_PTR) ShellExecute (hwnd, L"open", path, (wstring (L"\"") + isoPath + L"\"").c_str(), NULL, SW_SHOWNORMAL); if (r <= 32) { - SetLastError (r); + SetLastError ((DWORD) r); handleWin32Error (hwnd, SRC_POS); return FALSE; } return TRUE; } std::wstring VolumeGuidPathToDevicePath (std::wstring volumeGuidPath) { if (volumeGuidPath.find (L"\\\\?\\") == 0) volumeGuidPath = volumeGuidPath.substr (4); if (volumeGuidPath.find (L"Volume{") != 0 || volumeGuidPath.rfind (L"}\\") != volumeGuidPath.size() - 2) return wstring(); wchar_t volDevPath[TC_MAX_PATH]; if (QueryDosDevice (volumeGuidPath.substr (0, volumeGuidPath.size() - 1).c_str(), volDevPath, TC_MAX_PATH) == 0) return wstring(); wstring partitionPath = HarddiskVolumePathToPartitionPath (volDevPath); return partitionPath.empty() ? volDevPath : partitionPath; } std::wstring HarddiskVolumePathToPartitionPath (const std::wstring &harddiskVolumePath) { for (int driveNumber = 0; driveNumber < MAX_HOST_DRIVE_NUMBER; driveNumber++) @@ -15237,87 +15234,87 @@ DWORD GenericDropTarget::GotEnter(void) // PasswordEditDropTarget // Constructor // ************************************************************ PasswordEditDropTarget::PasswordEditDropTarget() : GenericDropTarget (g_supportedFormats, ARRAYSIZE (g_supportedFormats)) { } // ************************************************************ // GotDrag // ************************************************************ DWORD PasswordEditDropTarget::GotDrag(void) { return GotEnter(); } // ************************************************************ // GotLeave // ************************************************************ void PasswordEditDropTarget::GotLeave(void) { } // ************************************************************ // GotEnter // ************************************************************ DWORD PasswordEditDropTarget::GotEnter(void) { TCHAR szClassName[64]; - DWORD dwStyles; + DWORD_PTR dwStyles; int maxLen; HWND hChild = WindowFromPoint (m_DropPoint); // check that we are on password edit control (we use maximum length to correctly identify password fields since they don't always have ES_PASSWORD style (if the the user checked show password) if (hChild && GetClassName (hChild, szClassName, ARRAYSIZE (szClassName)) && (0 == _tcsicmp (szClassName, _T("EDIT"))) && (dwStyles = GetWindowLongPtr (hChild, GWL_STYLE)) && !(dwStyles & ES_NUMBER) && (maxLen = (int) SendMessage (hChild, EM_GETLIMITTEXT, 0, 0)) && (maxLen == MAX_PASSWORD || maxLen == MAX_LEGACY_PASSWORD) ) { return DROPEFFECT_COPY; } return DROPEFFECT_LINK; } // ************************************************************ // GotDrop // Called if we have a drop text drop here. // // ************************************************************ void PasswordEditDropTarget::GotDrop(CLIPFORMAT format) { // value contains the material itself if(m_Data) { TCHAR szClassName[64]; - DWORD dwStyles; + DWORD_PTR dwStyles; int maxLen; HWND hChild = WindowFromPoint (m_DropPoint); if (hChild && GetClassName (hChild, szClassName, ARRAYSIZE (szClassName)) && (0 == _tcsicmp (szClassName, _T("EDIT"))) && (dwStyles = GetWindowLongPtr (hChild, GWL_STYLE)) && !(dwStyles & ES_NUMBER) && (maxLen = (int) SendMessage (hChild, EM_GETLIMITTEXT, 0, 0)) && (maxLen == MAX_PASSWORD || maxLen == MAX_LEGACY_PASSWORD) ) { WCHAR* wszText; int wlen; bool bFree = false; // get the text if (format == CF_UNICODETEXT) { wszText = (WCHAR *)m_Data; } else { char *iText = (char *)m_Data; wlen = MultiByteToWideChar ((format == CF_OEMTEXT)? CP_OEMCP : CP_ACP, 0, iText, -1, NULL, 0); wszText = new WCHAR[wlen]; if (wszText) { wlen = MultiByteToWideChar (CP_ACP, 0, iText, -1, wszText, wlen); bFree = true; } } WCHAR* pchData = wszText; int txtlen = 0; bool bTruncated = false; diff --git a/src/Common/Dlgcode.h b/src/Common/Dlgcode.h index 288daecd..1b2ead2a 100644 --- a/src/Common/Dlgcode.h +++ b/src/Common/Dlgcode.h @@ -513,61 +513,61 @@ void HandleDriveNotReadyError (HWND hwnd); BOOL CALLBACK CloseTCWindowsEnum( HWND hwnd, LPARAM lParam); BOOL CALLBACK FindTCWindowEnum (HWND hwnd, LPARAM lParam); BYTE *MapResource (wchar_t *resourceType, int resourceId, PDWORD size); void InconsistencyResolved (char *msg); void ReportUnexpectedState (const char *techInfo); void OpenOnlineHelp (); BOOL GetPartitionInfo (const wchar_t *deviceName, PPARTITION_INFORMATION rpartInfo); BOOL GetDeviceInfo (const wchar_t *deviceName, DISK_PARTITION_INFO_STRUCT *info); BOOL GetDriveGeometry (const wchar_t *deviceName, PDISK_GEOMETRY_EX diskGeometry); BOOL GetPhysicalDriveGeometry (int driveNumber, PDISK_GEOMETRY diskGeometry); BOOL IsVolumeDeviceHosted (const wchar_t *lpszDiskFile); int CompensateXDPI (int val); int CompensateYDPI (int val); int CompensateDPIFont (int val); int GetTextGfxWidth (HWND hwndDlgItem, const wchar_t *text, HFONT hFont); int GetTextGfxHeight (HWND hwndDlgItem, const wchar_t *text, HFONT hFont); BOOL ToHyperlink (HWND hwndDlg, UINT ctrlId); BOOL ToCustHyperlink (HWND hwndDlg, UINT ctrlId, HFONT hFont); void DisableCloseButton (HWND hwndDlg); void EnableCloseButton (HWND hwndDlg); void ToBootPwdField (HWND hwndDlg, UINT ctrlId); void ToNormalPwdField (HWND hwndDlg, UINT ctrlId); void AccommodateTextField (HWND hwndDlg, UINT ctrlId, BOOL bFirstUpdate, HFONT hFont); void AccommodateCheckBoxTextWidth (HWND hwndDlg, UINT ctrlId); void MakeControlsContiguous(HWND hwndDlg, UINT ctrl1ID, UINT ctrl2ID); BOOL GetDriveLabel (int driveNo, wchar_t *label, int labelSize); BOOL GetSysDevicePaths (HWND hwndDlg); BOOL DoDriverInstall (HWND hwndDlg); int OpenVolume (OpenVolumeContext *context, const wchar_t *volumePath, Password *password, int pkcs5_prf, int pim, BOOL write, BOOL preserveTimestamps, BOOL useBackupHeader); void CloseVolume (OpenVolumeContext *context); -int ReEncryptVolumeHeader (HWND hwndDlg, char *buffer, BOOL bBoot, CRYPTO_INFO *cryptoInfo, Password *password, int pim, BOOL wipeMode); +int ReEncryptVolumeHeader (HWND hwndDlg, unsigned char *buffer, BOOL bBoot, CRYPTO_INFO *cryptoInfo, Password *password, int pim, BOOL wipeMode); BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly); BOOL IsPagingFileWildcardActive (); BOOL DisablePagingFile (); BOOL CALLBACK SecurityTokenPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); BOOL CALLBACK SecurityTokenKeyfileDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); BOOL InitSecurityTokenLibrary (HWND hwndDlg); BOOL FileHasReadOnlyAttribute (const wchar_t *path); BOOL IsFileOnReadOnlyFilesystem (const wchar_t *path); void CheckFilesystem (HWND hwndDlg, int driveNo, BOOL fixErrors); BOOL BufferContainsPattern (const uint8 *buffer, size_t bufferSize, const uint8 *pattern, size_t patternSize); BOOL BufferContainsString (const uint8 *buffer, size_t bufferSize, const char *str); BOOL BufferContainsWideString (const uint8 *buffer, size_t bufferSize, const wchar_t *str); int AskNonSysInPlaceEncryptionResume (HWND hwndDlg, BOOL* pbDecrypt); BOOL RemoveDeviceWriteProtection (HWND hwndDlg, wchar_t *devicePath); void EnableElevatedCursorChange (HWND parent); BOOL DisableFileCompression (HANDLE file); BOOL VolumePathExists (const wchar_t *volumePath); BOOL IsWindowsIsoBurnerAvailable (); BOOL LaunchWindowsIsoBurner (HWND hwnd, const wchar_t *isoPath); BOOL IsApplicationInstalled (const wchar_t *appName); int GetPim (HWND hwndDlg, UINT ctrlId, int defaultPim); void SetPim (HWND hwndDlg, UINT ctrlId, int pim); BOOL GetPassword (HWND hwndDlg, UINT ctrlID, char* passValue, int bufSize, BOOL bLegacyPassword, BOOL bShowError); void SetPassword (HWND hwndDlg, UINT ctrlID, char* passValue); void HandleShowPasswordFieldAction (HWND hwndDlg, UINT checkBoxId, UINT edit1Id, UINT edit2Id); HKEY OpenDeviceClassRegKey (const GUID *deviceClassGuid); LSTATUS DeleteRegistryKey (HKEY, LPCTSTR); HIMAGELIST CreateImageList(int cx, int cy, UINT flags, int cInitial, int cGrow); int AddBitmapToImageList(HIMAGELIST himl, HBITMAP hbmImage, HBITMAP hbmMask); HRESULT VCStrDupW(LPCWSTR psz, LPWSTR *ppwsz); diff --git a/src/Common/EncryptionThreadPool.c b/src/Common/EncryptionThreadPool.c index 79f1c890..3078e895 100644 --- a/src/Common/EncryptionThreadPool.c +++ b/src/Common/EncryptionThreadPool.c @@ -71,68 +71,68 @@ typedef enum WorkItemReady, WorkItemBusy } WorkItemState; typedef struct EncryptionThreadPoolWorkItemStruct { WorkItemState State; EncryptionThreadPoolWorkType Type; TC_EVENT ItemCompletedEvent; struct EncryptionThreadPoolWorkItemStruct *FirstFragment; LONG OutstandingFragmentCount; union { struct { PCRYPTO_INFO CryptoInfo; uint8 *Data; UINT64_STRUCT StartUnitNo; uint32 UnitCount; } Encryption; struct { TC_EVENT *CompletionEvent; LONG *CompletionFlag; - char *DerivedKey; + unsigned char *DerivedKey; int IterationCount; TC_EVENT *NoOutstandingWorkItemEvent; LONG *OutstandingWorkItemCount; - char *Password; + unsigned char *Password; int PasswordLength; int Pkcs5Prf; - char *Salt; + unsigned char *Salt; } KeyDerivation; struct { TC_EVENT *KeyDerivationCompletedEvent; TC_EVENT *NoOutstandingWorkItemEvent; LONG *outstandingWorkItemCount; void* keyInfoBuffer; int keyInfoBufferSize; void* keyDerivationWorkItems; int keyDerivationWorkItemsSize; } ReadVolumeHeaderFinalization; }; } EncryptionThreadPoolWorkItem; static volatile BOOL ThreadPoolRunning = FALSE; static volatile BOOL StopPending = FALSE; static uint32 ThreadCount; static TC_THREAD_HANDLE ThreadHandles[TC_ENC_THREAD_POOL_MAX_THREAD_COUNT]; static WORD ThreadProcessorGroups[TC_ENC_THREAD_POOL_MAX_THREAD_COUNT]; static EncryptionThreadPoolWorkItem WorkItemQueue[TC_ENC_THREAD_POOL_QUEUE_SIZE]; static volatile int EnqueuePosition; static volatile int DequeuePosition; @@ -506,61 +506,61 @@ void EncryptionThreadPoolStop () for (i = 0; i < ThreadCount; ++i) { #ifdef DEVICE_DRIVER TCStopThread (ThreadHandles[i], &WorkItemReadyEvent); #else TC_WAIT_EVENT (ThreadHandles[i]); #endif } ThreadCount = 0; #ifndef DEVICE_DRIVER CloseHandle (DequeueMutex); CloseHandle (EnqueueMutex); CloseHandle (WorkItemReadyEvent); CloseHandle (WorkItemCompletedEvent); for (i = 0; i < sizeof (WorkItemQueue) / sizeof (WorkItemQueue[0]); ++i) { if (WorkItemQueue[i].ItemCompletedEvent) CloseHandle (WorkItemQueue[i].ItemCompletedEvent); } #endif ThreadPoolRunning = FALSE; } -void EncryptionThreadPoolBeginKeyDerivation (TC_EVENT *completionEvent, TC_EVENT *noOutstandingWorkItemEvent, LONG *completionFlag, LONG *outstandingWorkItemCount, int pkcs5Prf, char *password, int passwordLength, char *salt, int iterationCount, char *derivedKey) +void EncryptionThreadPoolBeginKeyDerivation (TC_EVENT *completionEvent, TC_EVENT *noOutstandingWorkItemEvent, LONG *completionFlag, LONG *outstandingWorkItemCount, int pkcs5Prf, unsigned char *password, int passwordLength, unsigned char *salt, int iterationCount, unsigned char *derivedKey) { EncryptionThreadPoolWorkItem *workItem; if (!ThreadPoolRunning) TC_THROW_FATAL_EXCEPTION; TC_ACQUIRE_MUTEX (&EnqueueMutex); workItem = &WorkItemQueue[EnqueuePosition++]; if (EnqueuePosition >= ThreadQueueSize) EnqueuePosition = 0; while (GetWorkItemState (workItem) != WorkItemFree) { TC_WAIT_EVENT (WorkItemCompletedEvent); } workItem->Type = DeriveKeyWork; workItem->KeyDerivation.CompletionEvent = completionEvent; workItem->KeyDerivation.CompletionFlag = completionFlag; workItem->KeyDerivation.DerivedKey = derivedKey; workItem->KeyDerivation.IterationCount = iterationCount; workItem->KeyDerivation.NoOutstandingWorkItemEvent = noOutstandingWorkItemEvent; workItem->KeyDerivation.OutstandingWorkItemCount = outstandingWorkItemCount; workItem->KeyDerivation.Password = password; workItem->KeyDerivation.PasswordLength = passwordLength; workItem->KeyDerivation.Pkcs5Prf = pkcs5Prf; workItem->KeyDerivation.Salt = salt; InterlockedIncrement (outstandingWorkItemCount); diff --git a/src/Common/EncryptionThreadPool.h b/src/Common/EncryptionThreadPool.h index 71df4e4d..2e727a74 100644 --- a/src/Common/EncryptionThreadPool.h +++ b/src/Common/EncryptionThreadPool.h @@ -5,44 +5,44 @@ Modifications and additions to the original source code (contained in this file) and all other portions of this file are Copyright (c) 2013-2017 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #ifndef TC_HEADER_ENCRYPTION_THREAD_POOL #define TC_HEADER_ENCRYPTION_THREAD_POOL #include "Tcdefs.h" #include "Crypto.h" #ifdef __cplusplus extern "C" { #endif typedef enum { EncryptDataUnitsWork, DecryptDataUnitsWork, DeriveKeyWork, ReadVolumeHeaderFinalizationWork } EncryptionThreadPoolWorkType; #ifndef DEVICE_DRIVER size_t GetCpuCount (WORD* pGroupCount); #endif -void EncryptionThreadPoolBeginKeyDerivation (TC_EVENT *completionEvent, TC_EVENT *noOutstandingWorkItemEvent, LONG *completionFlag, LONG *outstandingWorkItemCount, int pkcs5Prf, char *password, int passwordLength, char *salt, int iterationCount, char *derivedKey); +void EncryptionThreadPoolBeginKeyDerivation (TC_EVENT *completionEvent, TC_EVENT *noOutstandingWorkItemEvent, LONG *completionFlag, LONG *outstandingWorkItemCount, int pkcs5Prf, unsigned char *password, int passwordLength, unsigned char *salt, int iterationCount, unsigned char *derivedKey); void EncryptionThreadPoolBeginReadVolumeHeaderFinalization (TC_EVENT *keyDerivationCompletedEvent, TC_EVENT *noOutstandingWorkItemEvent, LONG* outstandingWorkItemCount, void* keyInfoBuffer, int keyInfoBufferSize, void* keyDerivationWorkItems, int keyDerivationWorkItemsSize); void EncryptionThreadPoolDoWork (EncryptionThreadPoolWorkType type, uint8 *data, const UINT64_STRUCT *startUnitNo, uint32 unitCount, PCRYPTO_INFO cryptoInfo); BOOL EncryptionThreadPoolStart (size_t encryptionFreeCpuCount); void EncryptionThreadPoolStop (); size_t GetEncryptionThreadCount (); size_t GetMaxEncryptionThreadCount (); BOOL IsEncryptionThreadPoolRunning (); #ifdef __cplusplus } #endif #endif // TC_HEADER_ENCRYPTION_THREAD_POOL diff --git a/src/Common/Format.c b/src/Common/Format.c index 7eff80e6..482a87cd 100644 --- a/src/Common/Format.c +++ b/src/Common/Format.c @@ -57,61 +57,61 @@ uint64 GetVolumeDataAreaSize (BOOL hiddenVolume, uint64 volumeSize) # error TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE too large for very small volumes. Revise the code. #endif #if TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH < TC_MAX_VOLUME_SECTOR_SIZE # error TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH too small. #endif if (volumeSize < TC_VOLUME_SMALL_SIZE_THRESHOLD) reservedSize = TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE; else reservedSize = TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH; // Ensure size of a hidden volume larger than TC_VOLUME_SMALL_SIZE_THRESHOLD is a multiple of the maximum supported sector size } else { reservedSize = TC_TOTAL_VOLUME_HEADERS_SIZE; } if (volumeSize < reservedSize) return 0; return volumeSize - reservedSize; } int TCFormatVolume (volatile FORMAT_VOL_PARAMETERS *volParams) { int nStatus; PCRYPTO_INFO cryptoInfo = NULL; HANDLE dev = INVALID_HANDLE_VALUE; DWORD dwError; - char header[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; + unsigned char header[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; unsigned __int64 num_sectors, startSector; fatparams ft; FILETIME ftCreationTime; FILETIME ftLastWriteTime; FILETIME ftLastAccessTime; BOOL bTimeStampValid = FALSE; BOOL bInstantRetryOtherFilesys = FALSE; WCHAR dosDev[TC_MAX_PATH] = { 0 }; WCHAR devName[MAX_PATH] = { 0 }; int driveLetter = -1; WCHAR deviceName[MAX_PATH]; uint64 dataOffset, dataAreaSize; LARGE_INTEGER offset; BOOL bFailedRequiredDASD = FALSE; HWND hwndDlg = volParams->hwndDlg; #ifdef _WIN64 CRYPTO_INFO tmpCI; PCRYPTO_INFO cryptoInfoBackup = NULL; #endif FormatSectorSize = volParams->sectorSize; if (FormatSectorSize < TC_MIN_VOLUME_SECTOR_SIZE || FormatSectorSize > TC_MAX_VOLUME_SECTOR_SIZE || FormatSectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0) { Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg); return ERR_DONT_REPORT; } @@ -484,63 +484,63 @@ begin_format: /* Volume header */ // Hidden volume setup if (volParams->hiddenVol) { LARGE_INTEGER headerOffset; // Check hidden volume size if (volParams->hiddenVolHostSize < TC_MIN_HIDDEN_VOLUME_HOST_SIZE || volParams->hiddenVolHostSize > TC_MAX_HIDDEN_VOLUME_HOST_SIZE) { nStatus = ERR_VOL_SIZE_WRONG; goto error; } // Seek to hidden volume header location headerOffset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET; if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN)) { nStatus = ERR_OS_ERROR; goto error; } } else if (bInstantRetryOtherFilesys) { // The previous file system format failed and the user wants to try again with a different file system. // The volume header had been written successfully so we need to seek to the byte after the header. - LARGE_INTEGER offset; - offset.QuadPart = TC_VOLUME_DATA_OFFSET; - if (!SetFilePointerEx ((HANDLE) dev, offset, NULL, FILE_BEGIN)) + LARGE_INTEGER volDataOffset; + volDataOffset.QuadPart = TC_VOLUME_DATA_OFFSET; + if (!SetFilePointerEx ((HANDLE) dev, volDataOffset, NULL, FILE_BEGIN)) { nStatus = ERR_OS_ERROR; goto error; } } if (!bInstantRetryOtherFilesys) { // Write the volume header if (!WriteEffectiveVolumeHeader (volParams->bDevice, dev, header)) { nStatus = ERR_OS_ERROR; goto error; } // To prevent fragmentation, write zeroes to reserved header sectors which are going to be filled with random data if (!volParams->bDevice && !volParams->hiddenVol) { uint8 buf[TC_VOLUME_HEADER_GROUP_SIZE - TC_VOLUME_HEADER_EFFECTIVE_SIZE]; DWORD bytesWritten; ZeroMemory (buf, sizeof (buf)); if (!WriteFile (dev, buf, sizeof (buf), &bytesWritten, NULL)) { nStatus = ERR_OS_ERROR; goto error; } if (bytesWritten != sizeof (buf)) { diff --git a/src/Common/Keyfiles.c b/src/Common/Keyfiles.c index 6d9907cd..b21e371d 100644 --- a/src/Common/Keyfiles.c +++ b/src/Common/Keyfiles.c @@ -243,61 +243,61 @@ BOOL KeyFilesApply (HWND hwndDlg, Password *password, KeyFile *firstKeyFile, con if (firstKeyFile == NULL) return TRUE; VirtualLock (keyPool, sizeof (keyPool)); memset (keyPool, 0, sizeof (keyPool)); for (kf = firstKeyFile; kf != NULL; kf = kf->Next) { // Determine whether it's a security token path try { if (Token::IsKeyfilePathValid (kf->FileName, EMVSupportEnabled? true : false)) { // Apply security token keyfile vector <uint8> keyfileData; TokenKeyfilePath secPath (kf->FileName); Token::getTokenKeyfile (secPath)->GetKeyfileData (keyfileData); if (keyfileData.empty()) { SetLastError (ERROR_HANDLE_EOF); handleWin32Error (hwndDlg, SRC_POS); Error ("ERR_PROCESS_KEYFILE", hwndDlg); status = FALSE; continue; } unsigned __int32 crc = 0xffffffff; unsigned __int32 writePos = 0; size_t totalRead = 0; - for (size_t i = 0; i < keyfileData.size(); i++) + for (i = 0; i < keyfileData.size(); i++) { crc = UPDC32 (keyfileData[i], crc); keyPool[writePos++] += (unsigned __int8) (crc >> 24); keyPool[writePos++] += (unsigned __int8) (crc >> 16); keyPool[writePos++] += (unsigned __int8) (crc >> 8); keyPool[writePos++] += (unsigned __int8) crc; if (writePos >= keyPoolSize) writePos = 0; if (++totalRead >= KEYFILE_MAX_READ_LEN) break; } burn (&keyfileData.front(), keyfileData.size()); continue; } } catch (Exception &e) { e.Show (NULL); return FALSE; } // Determine whether it's a path or a file if (_wstat (kf->FileName, &statStruct) != 0) { handleWin32Error (hwndDlg, SRC_POS); Error ("ERR_PROCESS_KEYFILE", hwndDlg); @@ -469,61 +469,61 @@ BOOL CALLBACK KeyFilesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa LoadKeyList (hwndDlg, param->FirstKeyFile); SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, param->EnableKeyFiles); #ifdef TCMOUNT if ( (origParam.EnableKeyFiles == defaultKeyFilesParam.EnableKeyFiles) && (origParam.FirstKeyFile == defaultKeyFilesParam.FirstKeyFile) ) { /* default keyfile dialog case */ SetCheckBox (hwndDlg, IDC_KEYFILES_TRY_EMPTY_PASSWORD, bTryEmptyPasswordWhenKeyfileUsed); ShowWindow(GetDlgItem(hwndDlg, IDC_KEYFILES_TRY_EMPTY_PASSWORD), SW_SHOW); } #endif SetWindowTextW(GetDlgItem(hwndDlg, IDT_KEYFILES_NOTE), GetString ("KEYFILES_NOTE")); ToHyperlink (hwndDlg, IDC_LINK_KEYFILES_INFO); ToHyperlink (hwndDlg, IDC_LINK_KEYFILES_EXTENSIONS_WARNING); } return 1; case WM_CTLCOLORSTATIC: { if (((HWND)lParam == GetDlgItem(hwndDlg, IDT_KEYFILE_WARNING)) ) { // we're about to draw the static // set the text colour in (HDC)wParam SetBkMode((HDC)wParam,TRANSPARENT); SetTextColor((HDC)wParam, RGB(255,0,0)); - return (BOOL)GetSysColorBrush(COLOR_MENU); + return (BOOL)(INT_PTR)GetSysColorBrush(COLOR_MENU); } } return 0; case WM_COMMAND: if (lw == IDC_KEYADD) { KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile)); if (kf) { std::vector<std::wstring> filesList; if (SelectMultipleFiles (hwndDlg, "SELECT_KEYFILE", bHistory, filesList)) { bool containerFileSkipped = false; for (std::vector<std::wstring>::const_iterator it = filesList.begin(); it != filesList.end(); ++it) { StringCbCopyW (kf->FileName, sizeof (kf->FileName), it->c_str()); CorrectFileName (kf->FileName); if (_wcsicmp (param->VolumeFileName, kf->FileName) == 0) containerFileSkipped = true; else { param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf); LoadKeyList (hwndDlg, param->FirstKeyFile); kf = (KeyFile *) malloc (sizeof (KeyFile)); if (!kf) diff --git a/src/Common/Language.c b/src/Common/Language.c index a6bc9891..11c791d8 100644 --- a/src/Common/Language.c +++ b/src/Common/Language.c @@ -315,113 +315,113 @@ static BOOL LoadLanguageData (int resourceid, BOOL bForceSetPreferredLanguage, B if (!defaultLangParsed || strcmp (attr, langId) == 0) { Font font; memset (&font, 0, sizeof (font)); XmlGetAttributeText (xml, "face", attr, sizeof (attr)); len = MultiByteToWideChar (CP_UTF8, 0, attr, -1, wattr, sizeof (wattr) / sizeof(wattr[0])); font.FaceName = AddPoolData ((void *) wattr, len * 2); XmlGetAttributeText (xml, "size", attr, sizeof (attr)); sscanf (attr, "%d", &font.Size); StringCbCopyA (attr, sizeof(attr), "font_"); XmlGetAttributeText (xml, "class", attr + 5, sizeof (attr) - 5); AddDictionaryEntry ( AddPoolData ((void *) attr, strlen (attr) + 1), 0, AddPoolData ((void *) &font, sizeof(font))); } xml++; } // Create string and control dictionaries for (i = 0; xmlElements[i] != 0; i++) { xml = (char *) res; while (xml = XmlFindElement (xml, xmlElements[i])) { - void *key; + void *pkey; void *text; XmlGetAttributeText (xml, "lang", attr, sizeof (attr)); if (!defaultLangParsed || strcmp (attr, langId) == 0) { if (XmlGetAttributeText (xml, "key", attr, sizeof (attr))) { - key = AddPoolData (attr, strlen (attr) + 1); - if (key == NULL) return FALSE; + pkey = AddPoolData (attr, strlen (attr) + 1); + if (pkey == NULL) return FALSE; XmlGetNodeText (xml, attr, sizeof (attr)); // Parse \ escape sequences { char *in = attr, *out = attr; while (*in) { if (*in == '\\') { in++; switch (*in++) { case '\\': *out++ = '\\'; break; case 't': *out++ = '\t'; break; case 'n': *out++ = 13; *out++ = 10; break; default: if (!bForceSilent) - MessageBoxA (0, key, "VeraCrypt: Unknown '\\' escape sequence in string", MB_ICONERROR); + MessageBoxA (0, pkey, "VeraCrypt: Unknown '\\' escape sequence in string", MB_ICONERROR); return FALSE; } } else *out++ = *in++; } *out = 0; } // UTF8 => wide char len = MultiByteToWideChar (CP_UTF8, 0, attr, -1, wattr, sizeof (wattr) / sizeof(wattr[0])); if (len == 0) { if (!bForceSilent) - MessageBoxA (0, key, "VeraCrypt: Error while decoding UTF-8 string", MB_ICONERROR); + MessageBoxA (0, pkey, "VeraCrypt: Error while decoding UTF-8 string", MB_ICONERROR); return FALSE; } // Add to dictionary text = AddPoolData ((void *) wattr, len * 2); if (text == NULL) return FALSE; - AddDictionaryEntry ((char *) key, 0, text); + AddDictionaryEntry ((char *)pkey, 0, text); } } xml++; } } if (langFound) break; if (!defaultLangParsed) { defaultLangParsed = TRUE; if ((resourceid == 0) && (langId[0] == 0 || strcmp (langId, "en") == 0)) break; } } LocalizationActive = langFound && strcmp (langId, "en") != 0; LocalizationSerialNo++; if (bForceSetPreferredLanguage) StringCbCopyA (PreferredLangId, sizeof (PreferredLangId), langId); // Create control ID dictionary // Default controls AddDictionaryEntry (NULL, 1, GetString ("IDOK")); AddDictionaryEntry (NULL, 2, GetString ("IDCANCEL")); AddDictionaryEntry (NULL, 8, GetString ("IDCLOSE")); diff --git a/src/Common/Password.c b/src/Common/Password.c index c0247207..aed7cfb9 100644 --- a/src/Common/Password.c +++ b/src/Common/Password.c @@ -146,61 +146,61 @@ BOOL CheckPasswordLength (HWND hwndDlg, unsigned __int32 passwordLength, int pim return FALSE; } #ifndef _DEBUG if (!bSkipPasswordWarning && (MessageBoxW (hwndDlg, GetString ("PASSWORD_LENGTH_WARNING"), lpszTitle, MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2) != IDYES)) return FALSE; #endif } #ifndef _DEBUG else if (bCustomPimSmall) { if (!bSkipPimWarning && AskWarnNoYes ("PIM_SMALL_WARNING", hwndDlg) != IDYES) return FALSE; } #endif if ((pim != 0) && (pim > (bootPimCondition? 98 : 485))) { // warn that mount/boot will take more time Warning ("PIM_LARGE_WARNING", hwndDlg); } return TRUE; } int ChangePwd (const wchar_t *lpszVolume, Password *oldPassword, int old_pkcs5, int old_pim, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg) { int nDosLinkCreated = 1, nStatus = ERR_OS_ERROR; wchar_t szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH]; wchar_t szDosDevice[TC_MAX_PATH]; - char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; + unsigned char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; PCRYPTO_INFO cryptoInfo = NULL, ci = NULL; void *dev = INVALID_HANDLE_VALUE; DWORD dwError; DWORD bytesRead; BOOL bDevice; unsigned __int64 hostSize = 0; int volumeType; int wipePass; FILETIME ftCreationTime; FILETIME ftLastWriteTime; FILETIME ftLastAccessTime; BOOL bTimeStampValid = FALSE; LARGE_INTEGER headerOffset; BOOL backupHeader; if (oldPassword->Length == 0 || newPassword->Length == 0) return -1; if (wipePassCount <= 0) { nStatus = ERR_PARAMETER_INCORRECT; handleError (hwndDlg, nStatus, SRC_POS); return nStatus; } if (!lpszVolume) { nStatus = ERR_OUTOFMEMORY; handleError (hwndDlg, nStatus, SRC_POS); return nStatus; } diff --git a/src/Common/Pkcs5.c b/src/Common/Pkcs5.c index d81078e8..3e98ed40 100644 --- a/src/Common/Pkcs5.c +++ b/src/Common/Pkcs5.c @@ -16,1264 +16,1165 @@ #include <memory.h> #include <stdlib.h> #endif #include "blake2.h" #ifndef TC_WINDOWS_BOOT #include "Sha2.h" #include "Whirlpool.h" #include "cpu.h" #include "misc.h" #else #pragma optimize ("t", on) #include <string.h> #if defined( _MSC_VER ) # ifndef DEBUG # pragma intrinsic( memcpy ) # pragma intrinsic( memset ) # endif #endif #include "Sha2Small.h" #endif #include "Pkcs5.h" #include "Crypto.h" #if !defined(TC_WINDOWS_BOOT) || defined(TC_WINDOWS_BOOT_SHA2) typedef struct hmac_sha256_ctx_struct { sha256_ctx ctx; sha256_ctx inner_digest_ctx; /*pre-computed inner digest context */ sha256_ctx outer_digest_ctx; /*pre-computed outer digest context */ - char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the SHA256 hash */ - char u[SHA256_DIGESTSIZE]; + unsigned char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the SHA256 hash */ + unsigned char u[SHA256_DIGESTSIZE]; } hmac_sha256_ctx; void hmac_sha256_internal ( - char *d, /* input data. d pointer is guaranteed to be at least 32-bytes long */ + unsigned char *d, /* input data. d pointer is guaranteed to be at least 32-bytes long */ int ld, /* length of input data in bytes */ hmac_sha256_ctx* hmac /* HMAC-SHA256 context which holds temporary variables */ ) { sha256_ctx* ctx = &(hmac->ctx); /**** Restore Precomputed Inner Digest Context ****/ memcpy (ctx, &(hmac->inner_digest_ctx), sizeof (sha256_ctx)); - sha256_hash ((unsigned char *) d, ld, ctx); + sha256_hash (d, ld, ctx); - sha256_end ((unsigned char *) d, ctx); /* d = inner digest */ + sha256_end (d, ctx); /* d = inner digest */ /**** Restore Precomputed Outer Digest Context ****/ memcpy (ctx, &(hmac->outer_digest_ctx), sizeof (sha256_ctx)); - sha256_hash ((unsigned char *) d, SHA256_DIGESTSIZE, ctx); + sha256_hash (d, SHA256_DIGESTSIZE, ctx); - sha256_end ((unsigned char *) d, ctx); /* d = outer digest */ + sha256_end (d, ctx); /* d = outer digest */ } #ifndef TC_WINDOWS_BOOT void hmac_sha256 ( - char *k, /* secret key */ + unsigned char *k, /* secret key */ int lk, /* length of the key in bytes */ - char *d, /* data */ + unsigned char *d, /* data */ int ld /* length of data in bytes */ ) { hmac_sha256_ctx hmac; sha256_ctx* ctx; - char* buf = hmac.k; + unsigned char* buf = hmac.k; int b; - char key[SHA256_DIGESTSIZE]; -#if defined (DEVICE_DRIVER) + unsigned char key[SHA256_DIGESTSIZE]; +#if defined (DEVICE_DRIVER) && !defined(_M_ARM64) NTSTATUS saveStatus = STATUS_INVALID_PARAMETER; -#ifdef _WIN64 XSTATE_SAVE SaveState; if (IsCpuIntel() && HasSAVX()) saveStatus = KeSaveExtendedProcessorStateVC(XSTATE_MASK_GSSE, &SaveState); -#else - KFLOATING_SAVE floatingPointState; - if (HasSSE2()) - saveStatus = KeSaveFloatingPointState (&floatingPointState); -#endif #endif /* If the key is longer than the hash algorithm block size, let key = sha256(key), as per HMAC specifications. */ if (lk > SHA256_BLOCKSIZE) { sha256_ctx tctx; sha256_begin (&tctx); - sha256_hash ((unsigned char *) k, lk, &tctx); - sha256_end ((unsigned char *) key, &tctx); + sha256_hash (k, lk, &tctx); + sha256_end (key, &tctx); k = key; lk = SHA256_DIGESTSIZE; burn (&tctx, sizeof(tctx)); // Prevent leaks } /**** Precompute HMAC Inner Digest ****/ ctx = &(hmac.inner_digest_ctx); sha256_begin (ctx); /* Pad the key for inner digest */ for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x36); + buf[b] = (unsigned char) (k[b] ^ 0x36); memset (&buf[lk], 0x36, SHA256_BLOCKSIZE - lk); - sha256_hash ((unsigned char *) buf, SHA256_BLOCKSIZE, ctx); + sha256_hash (buf, SHA256_BLOCKSIZE, ctx); /**** Precompute HMAC Outer Digest ****/ ctx = &(hmac.outer_digest_ctx); sha256_begin (ctx); for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x5C); + buf[b] = (unsigned char) (k[b] ^ 0x5C); memset (&buf[lk], 0x5C, SHA256_BLOCKSIZE - lk); - sha256_hash ((unsigned char *) buf, SHA256_BLOCKSIZE, ctx); + sha256_hash (buf, SHA256_BLOCKSIZE, ctx); hmac_sha256_internal(d, ld, &hmac); -#if defined (DEVICE_DRIVER) +#if defined (DEVICE_DRIVER) && !defined(_M_ARM64) if (NT_SUCCESS (saveStatus)) -#ifdef _WIN64 KeRestoreExtendedProcessorStateVC(&SaveState); -#else - KeRestoreFloatingPointState (&floatingPointState); -#endif #endif /* Prevent leaks */ burn(&hmac, sizeof(hmac)); burn(key, sizeof(key)); } #endif -static void derive_u_sha256 (char *salt, int salt_len, uint32 iterations, int b, hmac_sha256_ctx* hmac) +static void derive_u_sha256 (const unsigned char *salt, int salt_len, uint32 iterations, int b, hmac_sha256_ctx* hmac) { - char* k = hmac->k; - char* u = hmac->u; + unsigned char* k = hmac->k; + unsigned char* u = hmac->u; uint32 c; int i; #ifdef TC_WINDOWS_BOOT /* In bootloader mode, least significant bit of iterations is a boolean (TRUE for boot derivation mode, FALSE otherwise) * and the most significant 16 bits hold the pim value * This enables us to save code space needed for implementing other features. */ c = iterations >> 16; i = ((int) iterations) & 0x01; if (i) c = (c == 0)? 200000 : c << 11; else c = (c == 0)? 500000 : 15000 + c * 1000; #else c = iterations; #endif /* iteration 1 */ memcpy (k, salt, salt_len); /* salt */ /* big-endian block number */ #ifdef TC_WINDOWS_BOOT /* specific case of 16-bit bootloader: b is a 16-bit integer that is always < 256 */ memset (&k[salt_len], 0, 3); - k[salt_len + 3] = (char) b; + k[salt_len + 3] = (unsigned char) b; #else b = bswap_32 (b); memcpy (&k[salt_len], &b, 4); #endif hmac_sha256_internal (k, salt_len + 4, hmac); memcpy (u, k, SHA256_DIGESTSIZE); /* remaining iterations */ while (c > 1) { hmac_sha256_internal (k, SHA256_DIGESTSIZE, hmac); for (i = 0; i < SHA256_DIGESTSIZE; i++) { u[i] ^= k[i]; } c--; } } -void derive_key_sha256 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) +void derive_key_sha256 (const unsigned char *pwd, int pwd_len, const unsigned char *salt, int salt_len, uint32 iterations, unsigned char *dk, int dklen) { hmac_sha256_ctx hmac; sha256_ctx* ctx; - char* buf = hmac.k; + unsigned char* buf = hmac.k; int b, l, r; #ifndef TC_WINDOWS_BOOT - char key[SHA256_DIGESTSIZE]; -#if defined (DEVICE_DRIVER) + unsigned char key[SHA256_DIGESTSIZE]; +#if defined (DEVICE_DRIVER) && !defined(_M_ARM64) NTSTATUS saveStatus = STATUS_INVALID_PARAMETER; -#ifdef _WIN64 XSTATE_SAVE SaveState; if (IsCpuIntel() && HasSAVX()) saveStatus = KeSaveExtendedProcessorStateVC(XSTATE_MASK_GSSE, &SaveState); -#else - KFLOATING_SAVE floatingPointState; - if (HasSSE2()) - saveStatus = KeSaveFloatingPointState (&floatingPointState); -#endif #endif /* If the password is longer than the hash algorithm block size, let pwd = sha256(pwd), as per HMAC specifications. */ if (pwd_len > SHA256_BLOCKSIZE) { sha256_ctx tctx; sha256_begin (&tctx); - sha256_hash ((unsigned char *) pwd, pwd_len, &tctx); - sha256_end ((unsigned char *) key, &tctx); + sha256_hash (pwd, pwd_len, &tctx); + sha256_end (key, &tctx); pwd = key; pwd_len = SHA256_DIGESTSIZE; burn (&tctx, sizeof(tctx)); // Prevent leaks } #endif if (dklen % SHA256_DIGESTSIZE) { l = 1 + dklen / SHA256_DIGESTSIZE; } else { l = dklen / SHA256_DIGESTSIZE; } r = dklen - (l - 1) * SHA256_DIGESTSIZE; /**** Precompute HMAC Inner Digest ****/ ctx = &(hmac.inner_digest_ctx); sha256_begin (ctx); /* Pad the key for inner digest */ for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x36); + buf[b] = (unsigned char) (pwd[b] ^ 0x36); memset (&buf[pwd_len], 0x36, SHA256_BLOCKSIZE - pwd_len); - sha256_hash ((unsigned char *) buf, SHA256_BLOCKSIZE, ctx); + sha256_hash (buf, SHA256_BLOCKSIZE, ctx); /**** Precompute HMAC Outer Digest ****/ ctx = &(hmac.outer_digest_ctx); sha256_begin (ctx); for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x5C); + buf[b] = (unsigned char) (pwd[b] ^ 0x5C); memset (&buf[pwd_len], 0x5C, SHA256_BLOCKSIZE - pwd_len); - sha256_hash ((unsigned char *) buf, SHA256_BLOCKSIZE, ctx); + sha256_hash (buf, SHA256_BLOCKSIZE, ctx); /* first l - 1 blocks */ for (b = 1; b < l; b++) { derive_u_sha256 (salt, salt_len, iterations, b, &hmac); memcpy (dk, hmac.u, SHA256_DIGESTSIZE); dk += SHA256_DIGESTSIZE; } /* last block */ derive_u_sha256 (salt, salt_len, iterations, b, &hmac); memcpy (dk, hmac.u, r); -#if defined (DEVICE_DRIVER) +#if defined (DEVICE_DRIVER) && !defined(_M_ARM64) if (NT_SUCCESS (saveStatus)) -#ifdef _WIN64 KeRestoreExtendedProcessorStateVC(&SaveState); -#else - KeRestoreFloatingPointState (&floatingPointState); -#endif #endif /* Prevent possible leaks. */ burn (&hmac, sizeof(hmac)); #ifndef TC_WINDOWS_BOOT burn (key, sizeof(key)); #endif } #endif #ifndef TC_WINDOWS_BOOT typedef struct hmac_sha512_ctx_struct { sha512_ctx ctx; sha512_ctx inner_digest_ctx; /*pre-computed inner digest context */ sha512_ctx outer_digest_ctx; /*pre-computed outer digest context */ - char k[SHA512_BLOCKSIZE]; /* enough to hold (salt_len + 4) and also the SHA512 hash */ - char u[SHA512_DIGESTSIZE]; + unsigned char k[SHA512_BLOCKSIZE]; /* enough to hold (salt_len + 4) and also the SHA512 hash */ + unsigned char u[SHA512_DIGESTSIZE]; } hmac_sha512_ctx; void hmac_sha512_internal ( - char *d, /* data and also output buffer of at least 64 bytes */ + unsigned char *d, /* data and also output buffer of at least 64 bytes */ int ld, /* length of data in bytes */ hmac_sha512_ctx* hmac ) { sha512_ctx* ctx = &(hmac->ctx); /**** Restore Precomputed Inner Digest Context ****/ memcpy (ctx, &(hmac->inner_digest_ctx), sizeof (sha512_ctx)); - sha512_hash ((unsigned char *) d, ld, ctx); + sha512_hash (d, ld, ctx); - sha512_end ((unsigned char *) d, ctx); + sha512_end (d, ctx); /**** Restore Precomputed Outer Digest Context ****/ memcpy (ctx, &(hmac->outer_digest_ctx), sizeof (sha512_ctx)); - sha512_hash ((unsigned char *) d, SHA512_DIGESTSIZE, ctx); + sha512_hash (d, SHA512_DIGESTSIZE, ctx); - sha512_end ((unsigned char *) d, ctx); + sha512_end (d, ctx); } void hmac_sha512 ( - char *k, /* secret key */ + unsigned char *k, /* secret key */ int lk, /* length of the key in bytes */ - char *d, /* data and also output buffer of at least 64 bytes */ + unsigned char *d, /* data and also output buffer of at least 64 bytes */ int ld /* length of data in bytes */ ) { hmac_sha512_ctx hmac; sha512_ctx* ctx; - char* buf = hmac.k; + unsigned char* buf = hmac.k; int b; - char key[SHA512_DIGESTSIZE]; -#if defined (DEVICE_DRIVER) + unsigned char key[SHA512_DIGESTSIZE]; +#if defined (DEVICE_DRIVER) && !defined(_M_ARM64) NTSTATUS saveStatus = STATUS_INVALID_PARAMETER; -#ifdef _WIN64 XSTATE_SAVE SaveState; if (IsCpuIntel() && HasSAVX()) saveStatus = KeSaveExtendedProcessorStateVC(XSTATE_MASK_GSSE, &SaveState); -#else - KFLOATING_SAVE floatingPointState; - if (HasSSSE3() && HasMMX()) - saveStatus = KeSaveFloatingPointState (&floatingPointState); -#endif #endif /* If the key is longer than the hash algorithm block size, let key = sha512(key), as per HMAC specifications. */ if (lk > SHA512_BLOCKSIZE) { sha512_ctx tctx; sha512_begin (&tctx); - sha512_hash ((unsigned char *) k, lk, &tctx); - sha512_end ((unsigned char *) key, &tctx); + sha512_hash (k, lk, &tctx); + sha512_end (key, &tctx); k = key; lk = SHA512_DIGESTSIZE; burn (&tctx, sizeof(tctx)); // Prevent leaks } /**** Precompute HMAC Inner Digest ****/ ctx = &(hmac.inner_digest_ctx); sha512_begin (ctx); /* Pad the key for inner digest */ for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x36); + buf[b] = (unsigned char) (k[b] ^ 0x36); memset (&buf[lk], 0x36, SHA512_BLOCKSIZE - lk); - sha512_hash ((unsigned char *) buf, SHA512_BLOCKSIZE, ctx); + sha512_hash (buf, SHA512_BLOCKSIZE, ctx); /**** Precompute HMAC Outer Digest ****/ ctx = &(hmac.outer_digest_ctx); sha512_begin (ctx); for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x5C); + buf[b] = (unsigned char) (k[b] ^ 0x5C); memset (&buf[lk], 0x5C, SHA512_BLOCKSIZE - lk); - sha512_hash ((unsigned char *) buf, SHA512_BLOCKSIZE, ctx); + sha512_hash (buf, SHA512_BLOCKSIZE, ctx); hmac_sha512_internal (d, ld, &hmac); -#if defined (DEVICE_DRIVER) +#if defined (DEVICE_DRIVER) && !defined(_M_ARM64) if (NT_SUCCESS (saveStatus)) -#ifdef _WIN64 KeRestoreExtendedProcessorStateVC(&SaveState); -#else - KeRestoreFloatingPointState (&floatingPointState); -#endif #endif /* Prevent leaks */ burn (&hmac, sizeof(hmac)); burn (key, sizeof(key)); } -static void derive_u_sha512 (char *salt, int salt_len, uint32 iterations, int b, hmac_sha512_ctx* hmac) +static void derive_u_sha512 (const unsigned char *salt, int salt_len, uint32 iterations, int b, hmac_sha512_ctx* hmac) { - char* k = hmac->k; - char* u = hmac->u; + unsigned char* k = hmac->k; + unsigned char* u = hmac->u; uint32 c, i; /* iteration 1 */ memcpy (k, salt, salt_len); /* salt */ /* big-endian block number */ b = bswap_32 (b); memcpy (&k[salt_len], &b, 4); hmac_sha512_internal (k, salt_len + 4, hmac); memcpy (u, k, SHA512_DIGESTSIZE); /* remaining iterations */ for (c = 1; c < iterations; c++) { hmac_sha512_internal (k, SHA512_DIGESTSIZE, hmac); for (i = 0; i < SHA512_DIGESTSIZE; i++) { u[i] ^= k[i]; } } } -void derive_key_sha512 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) +void derive_key_sha512 (const unsigned char *pwd, int pwd_len, const unsigned char *salt, int salt_len, uint32 iterations, unsigned char *dk, int dklen) { hmac_sha512_ctx hmac; sha512_ctx* ctx; - char* buf = hmac.k; + unsigned char* buf = hmac.k; int b, l, r; - char key[SHA512_DIGESTSIZE]; -#if defined (DEVICE_DRIVER) + unsigned char key[SHA512_DIGESTSIZE]; +#if defined (DEVICE_DRIVER) && !defined(_M_ARM64) NTSTATUS saveStatus = STATUS_INVALID_PARAMETER; -#ifdef _WIN64 XSTATE_SAVE SaveState; if (IsCpuIntel() && HasSAVX()) saveStatus = KeSaveExtendedProcessorStateVC(XSTATE_MASK_GSSE, &SaveState); -#else - KFLOATING_SAVE floatingPointState; - if (HasSSSE3() && HasMMX()) - saveStatus = KeSaveFloatingPointState (&floatingPointState); -#endif #endif /* If the password is longer than the hash algorithm block size, let pwd = sha512(pwd), as per HMAC specifications. */ if (pwd_len > SHA512_BLOCKSIZE) { sha512_ctx tctx; sha512_begin (&tctx); - sha512_hash ((unsigned char *) pwd, pwd_len, &tctx); - sha512_end ((unsigned char *) key, &tctx); + sha512_hash (pwd, pwd_len, &tctx); + sha512_end (key, &tctx); pwd = key; pwd_len = SHA512_DIGESTSIZE; burn (&tctx, sizeof(tctx)); // Prevent leaks } if (dklen % SHA512_DIGESTSIZE) { l = 1 + dklen / SHA512_DIGESTSIZE; } else { l = dklen / SHA512_DIGESTSIZE; } r = dklen - (l - 1) * SHA512_DIGESTSIZE; /**** Precompute HMAC Inner Digest ****/ ctx = &(hmac.inner_digest_ctx); sha512_begin (ctx); /* Pad the key for inner digest */ for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x36); + buf[b] = (unsigned char) (pwd[b] ^ 0x36); memset (&buf[pwd_len], 0x36, SHA512_BLOCKSIZE - pwd_len); - sha512_hash ((unsigned char *) buf, SHA512_BLOCKSIZE, ctx); + sha512_hash (buf, SHA512_BLOCKSIZE, ctx); /**** Precompute HMAC Outer Digest ****/ ctx = &(hmac.outer_digest_ctx); sha512_begin (ctx); for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x5C); + buf[b] = (unsigned char) (pwd[b] ^ 0x5C); memset (&buf[pwd_len], 0x5C, SHA512_BLOCKSIZE - pwd_len); - sha512_hash ((unsigned char *) buf, SHA512_BLOCKSIZE, ctx); + sha512_hash (buf, SHA512_BLOCKSIZE, ctx); /* first l - 1 blocks */ for (b = 1; b < l; b++) { derive_u_sha512 (salt, salt_len, iterations, b, &hmac); memcpy (dk, hmac.u, SHA512_DIGESTSIZE); dk += SHA512_DIGESTSIZE; } /* last block */ derive_u_sha512 (salt, salt_len, iterations, b, &hmac); memcpy (dk, hmac.u, r); -#if defined (DEVICE_DRIVER) +#if defined (DEVICE_DRIVER) && !defined(_M_ARM64) if (NT_SUCCESS (saveStatus)) -#ifdef _WIN64 KeRestoreExtendedProcessorStateVC(&SaveState); -#else - KeRestoreFloatingPointState (&floatingPointState); -#endif #endif /* Prevent possible leaks. */ burn (&hmac, sizeof(hmac)); burn (key, sizeof(key)); } #endif // TC_WINDOWS_BOOT #if !defined(TC_WINDOWS_BOOT) || defined(TC_WINDOWS_BOOT_BLAKE2S) typedef struct hmac_blake2s_ctx_struct { blake2s_state ctx; blake2s_state inner_digest_ctx; /*pre-computed inner digest context */ blake2s_state outer_digest_ctx; /*pre-computed outer digest context */ - char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the Blake2s hash */ - char u[BLAKE2S_DIGESTSIZE]; + unsigned char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the Blake2s hash */ + unsigned char u[BLAKE2S_DIGESTSIZE]; } hmac_blake2s_ctx; void hmac_blake2s_internal ( - char *d, /* input data. d pointer is guaranteed to be at least 32-bytes long */ + unsigned char *d, /* input data. d pointer is guaranteed to be at least 32-bytes long */ int ld, /* length of input data in bytes */ hmac_blake2s_ctx* hmac /* HMAC-BLAKE2S context which holds temporary variables */ ) { blake2s_state* ctx = &(hmac->ctx); /**** Restore Precomputed Inner Digest Context ****/ memcpy (ctx, &(hmac->inner_digest_ctx), sizeof (blake2s_state)); blake2s_update (ctx, d, ld); - blake2s_final (ctx, (unsigned char*) d); /* d = inner digest */ + blake2s_final (ctx, d); /* d = inner digest */ /**** Restore Precomputed Outer Digest Context ****/ memcpy (ctx, &(hmac->outer_digest_ctx), sizeof (blake2s_state)); blake2s_update (ctx, d, BLAKE2S_DIGESTSIZE); - blake2s_final (ctx, (unsigned char *) d); /* d = outer digest */ + blake2s_final (ctx, d); /* d = outer digest */ } #ifndef TC_WINDOWS_BOOT void hmac_blake2s ( - char *k, /* secret key */ + unsigned char *k, /* secret key */ int lk, /* length of the key in bytes */ - char *d, /* data */ + unsigned char *d, /* data */ int ld /* length of data in bytes */ ) { hmac_blake2s_ctx hmac; blake2s_state* ctx; - char* buf = hmac.k; + unsigned char* buf = hmac.k; int b; - char key[BLAKE2S_DIGESTSIZE]; -#if defined (DEVICE_DRIVER) + unsigned char key[BLAKE2S_DIGESTSIZE]; +#if defined (DEVICE_DRIVER) && !defined(_M_ARM64) NTSTATUS saveStatus = STATUS_INVALID_PARAMETER; -#ifdef _WIN64 XSTATE_SAVE SaveState; if (IsCpuIntel() && HasSAVX()) saveStatus = KeSaveExtendedProcessorStateVC(XSTATE_MASK_GSSE, &SaveState); -#else - KFLOATING_SAVE floatingPointState; - if (HasSSE2()) - saveStatus = KeSaveFloatingPointState (&floatingPointState); -#endif #endif /* If the key is longer than the hash algorithm block size, let key = blake2s(key), as per HMAC specifications. */ if (lk > BLAKE2S_BLOCKSIZE) { blake2s_state tctx; blake2s_init (&tctx); blake2s_update (&tctx, k, lk); - blake2s_final (&tctx, (unsigned char *) key); + blake2s_final (&tctx, key); k = key; lk = BLAKE2S_DIGESTSIZE; burn (&tctx, sizeof(tctx)); // Prevent leaks } /**** Precompute HMAC Inner Digest ****/ ctx = &(hmac.inner_digest_ctx); blake2s_init (ctx); /* Pad the key for inner digest */ for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x36); + buf[b] = (unsigned char) (k[b] ^ 0x36); memset (&buf[lk], 0x36, BLAKE2S_BLOCKSIZE - lk); - blake2s_update (ctx, (unsigned char *) buf, BLAKE2S_BLOCKSIZE); + blake2s_update (ctx, buf, BLAKE2S_BLOCKSIZE); /**** Precompute HMAC Outer Digest ****/ ctx = &(hmac.outer_digest_ctx); blake2s_init (ctx); for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x5C); + buf[b] = (unsigned char) (k[b] ^ 0x5C); memset (&buf[lk], 0x5C, BLAKE2S_BLOCKSIZE - lk); - blake2s_update (ctx, (unsigned char *) buf, BLAKE2S_BLOCKSIZE); + blake2s_update (ctx, buf, BLAKE2S_BLOCKSIZE); hmac_blake2s_internal(d, ld, &hmac); -#if defined (DEVICE_DRIVER) +#if defined (DEVICE_DRIVER) && !defined(_M_ARM64) if (NT_SUCCESS (saveStatus)) -#ifdef _WIN64 KeRestoreExtendedProcessorStateVC(&SaveState); -#else - KeRestoreFloatingPointState (&floatingPointState); -#endif #endif /* Prevent leaks */ burn(&hmac, sizeof(hmac)); burn(key, sizeof(key)); } #endif -static void derive_u_blake2s (char *salt, int salt_len, uint32 iterations, int b, hmac_blake2s_ctx* hmac) +static void derive_u_blake2s (const unsigned char *salt, int salt_len, uint32 iterations, int b, hmac_blake2s_ctx* hmac) { - char* k = hmac->k; - char* u = hmac->u; + unsigned char* k = hmac->k; + unsigned char* u = hmac->u; uint32 c; int i; #ifdef TC_WINDOWS_BOOT /* In bootloader mode, least significant bit of iterations is a boolean (TRUE for boot derivation mode, FALSE otherwise) * and the most significant 16 bits hold the pim value * This enables us to save code space needed for implementing other features. */ c = iterations >> 16; i = ((int) iterations) & 0x01; if (i) c = (c == 0)? 200000 : c << 11; else c = (c == 0)? 500000 : 15000 + c * 1000; #else c = iterations; #endif /* iteration 1 */ memcpy (k, salt, salt_len); /* salt */ /* big-endian block number */ #ifdef TC_WINDOWS_BOOT /* specific case of 16-bit bootloader: b is a 16-bit integer that is always < 256 */ memset (&k[salt_len], 0, 3); - k[salt_len + 3] = (char) b; + k[salt_len + 3] = (unsigned char) b; #else b = bswap_32 (b); memcpy (&k[salt_len], &b, 4); #endif hmac_blake2s_internal (k, salt_len + 4, hmac); memcpy (u, k, BLAKE2S_DIGESTSIZE); /* remaining iterations */ while (c > 1) { hmac_blake2s_internal (k, BLAKE2S_DIGESTSIZE, hmac); for (i = 0; i < BLAKE2S_DIGESTSIZE; i++) { u[i] ^= k[i]; } c--; } } -void derive_key_blake2s (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) +void derive_key_blake2s (const unsigned char *pwd, int pwd_len, const unsigned char *salt, int salt_len, uint32 iterations, unsigned char *dk, int dklen) { hmac_blake2s_ctx hmac; blake2s_state* ctx; - char* buf = hmac.k; + unsigned char* buf = hmac.k; int b, l, r; #ifndef TC_WINDOWS_BOOT - char key[BLAKE2S_DIGESTSIZE]; -#if defined (DEVICE_DRIVER) + unsigned char key[BLAKE2S_DIGESTSIZE]; +#if defined (DEVICE_DRIVER) && !defined(_M_ARM64) NTSTATUS saveStatus = STATUS_INVALID_PARAMETER; -#ifdef _WIN64 XSTATE_SAVE SaveState; if (IsCpuIntel() && HasSAVX()) saveStatus = KeSaveExtendedProcessorStateVC(XSTATE_MASK_GSSE, &SaveState); -#else KFLOATING_SAVE floatingPointState; if (HasSSE2()) saveStatus = KeSaveFloatingPointState (&floatingPointState); #endif -#endif /* If the password is longer than the hash algorithm block size, let pwd = blake2s(pwd), as per HMAC specifications. */ if (pwd_len > BLAKE2S_BLOCKSIZE) { blake2s_state tctx; blake2s_init (&tctx); blake2s_update (&tctx, pwd, pwd_len); - blake2s_final (&tctx, (unsigned char *) key); + blake2s_final (&tctx, key); pwd = key; pwd_len = BLAKE2S_DIGESTSIZE; burn (&tctx, sizeof(tctx)); // Prevent leaks } #endif if (dklen % BLAKE2S_DIGESTSIZE) { l = 1 + dklen / BLAKE2S_DIGESTSIZE; } else { l = dklen / BLAKE2S_DIGESTSIZE; } r = dklen - (l - 1) * BLAKE2S_DIGESTSIZE; /**** Precompute HMAC Inner Digest ****/ ctx = &(hmac.inner_digest_ctx); blake2s_init (ctx); /* Pad the key for inner digest */ for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x36); + buf[b] = (unsigned char) (pwd[b] ^ 0x36); memset (&buf[pwd_len], 0x36, BLAKE2S_BLOCKSIZE - pwd_len); blake2s_update (ctx, buf, BLAKE2S_BLOCKSIZE); /**** Precompute HMAC Outer Digest ****/ ctx = &(hmac.outer_digest_ctx); blake2s_init (ctx); for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x5C); + buf[b] = (unsigned char) (pwd[b] ^ 0x5C); memset (&buf[pwd_len], 0x5C, BLAKE2S_BLOCKSIZE - pwd_len); blake2s_update (ctx, buf, BLAKE2S_BLOCKSIZE); /* first l - 1 blocks */ for (b = 1; b < l; b++) { derive_u_blake2s (salt, salt_len, iterations, b, &hmac); memcpy (dk, hmac.u, BLAKE2S_DIGESTSIZE); dk += BLAKE2S_DIGESTSIZE; } /* last block */ derive_u_blake2s (salt, salt_len, iterations, b, &hmac); memcpy (dk, hmac.u, r); -#if defined (DEVICE_DRIVER) +#if defined (DEVICE_DRIVER) && !defined(_M_ARM64) if (NT_SUCCESS (saveStatus)) -#ifdef _WIN64 KeRestoreExtendedProcessorStateVC(&SaveState); -#else - KeRestoreFloatingPointState (&floatingPointState); -#endif #endif /* Prevent possible leaks. */ burn (&hmac, sizeof(hmac)); #ifndef TC_WINDOWS_BOOT burn (key, sizeof(key)); #endif } #endif #ifndef TC_WINDOWS_BOOT typedef struct hmac_whirlpool_ctx_struct { WHIRLPOOL_CTX ctx; WHIRLPOOL_CTX inner_digest_ctx; /*pre-computed inner digest context */ WHIRLPOOL_CTX outer_digest_ctx; /*pre-computed outer digest context */ - CRYPTOPP_ALIGN_DATA(16) char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the Whirlpool hash */ - char u[WHIRLPOOL_DIGESTSIZE]; + CRYPTOPP_ALIGN_DATA(16) unsigned char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the Whirlpool hash */ + unsigned char u[WHIRLPOOL_DIGESTSIZE]; } hmac_whirlpool_ctx; void hmac_whirlpool_internal ( - char *d, /* input/output data. d pointer is guaranteed to be at least 64-bytes long */ + unsigned char *d, /* input/output data. d pointer is guaranteed to be at least 64-bytes long */ int ld, /* length of input data in bytes */ hmac_whirlpool_ctx* hmac /* HMAC-Whirlpool context which holds temporary variables */ ) { WHIRLPOOL_CTX* ctx = &(hmac->ctx); /**** Restore Precomputed Inner Digest Context ****/ memcpy (ctx, &(hmac->inner_digest_ctx), sizeof (WHIRLPOOL_CTX)); - WHIRLPOOL_add ((unsigned char *) d, ld, ctx); + WHIRLPOOL_add (d, ld, ctx); - WHIRLPOOL_finalize (ctx, (unsigned char *) d); + WHIRLPOOL_finalize (ctx, d); /**** Restore Precomputed Outer Digest Context ****/ memcpy (ctx, &(hmac->outer_digest_ctx), sizeof (WHIRLPOOL_CTX)); - WHIRLPOOL_add ((unsigned char *) d, WHIRLPOOL_DIGESTSIZE, ctx); + WHIRLPOOL_add (d, WHIRLPOOL_DIGESTSIZE, ctx); - WHIRLPOOL_finalize (ctx, (unsigned char *) d); + WHIRLPOOL_finalize (ctx, d); } void hmac_whirlpool ( - char *k, /* secret key */ + unsigned char *k, /* secret key */ int lk, /* length of the key in bytes */ - char *d, /* input data. d pointer is guaranteed to be at least 32-bytes long */ + unsigned char *d, /* input data. d pointer is guaranteed to be at least 32-bytes long */ int ld /* length of data in bytes */ ) { hmac_whirlpool_ctx hmac; WHIRLPOOL_CTX* ctx; - char* buf = hmac.k; + unsigned char* buf = hmac.k; int b; - char key[WHIRLPOOL_DIGESTSIZE]; -#if defined (DEVICE_DRIVER) && !defined (_WIN64) - KFLOATING_SAVE floatingPointState; - NTSTATUS saveStatus = STATUS_INVALID_PARAMETER; - if (HasISSE()) - saveStatus = KeSaveFloatingPointState (&floatingPointState); -#endif + unsigned char key[WHIRLPOOL_DIGESTSIZE]; /* If the key is longer than the hash algorithm block size, let key = whirlpool(key), as per HMAC specifications. */ if (lk > WHIRLPOOL_BLOCKSIZE) { WHIRLPOOL_CTX tctx; WHIRLPOOL_init (&tctx); - WHIRLPOOL_add ((unsigned char *) k, lk, &tctx); - WHIRLPOOL_finalize (&tctx, (unsigned char *) key); + WHIRLPOOL_add (k, lk, &tctx); + WHIRLPOOL_finalize (&tctx, key); k = key; lk = WHIRLPOOL_DIGESTSIZE; burn (&tctx, sizeof(tctx)); // Prevent leaks } /**** Precompute HMAC Inner Digest ****/ ctx = &(hmac.inner_digest_ctx); WHIRLPOOL_init (ctx); /* Pad the key for inner digest */ for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x36); + buf[b] = (unsigned char) (k[b] ^ 0x36); memset (&buf[lk], 0x36, WHIRLPOOL_BLOCKSIZE - lk); - WHIRLPOOL_add ((unsigned char *) buf, WHIRLPOOL_BLOCKSIZE, ctx); + WHIRLPOOL_add (buf, WHIRLPOOL_BLOCKSIZE, ctx); /**** Precompute HMAC Outer Digest ****/ ctx = &(hmac.outer_digest_ctx); WHIRLPOOL_init (ctx); for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x5C); + buf[b] = (unsigned char) (k[b] ^ 0x5C); memset (&buf[lk], 0x5C, WHIRLPOOL_BLOCKSIZE - lk); - WHIRLPOOL_add ((unsigned char *) buf, WHIRLPOOL_BLOCKSIZE, ctx); + WHIRLPOOL_add (buf, WHIRLPOOL_BLOCKSIZE, ctx); hmac_whirlpool_internal(d, ld, &hmac); -#if defined (DEVICE_DRIVER) && !defined (_WIN64) - if (NT_SUCCESS (saveStatus)) - KeRestoreFloatingPointState (&floatingPointState); -#endif /* Prevent leaks */ burn(&hmac, sizeof(hmac)); } -static void derive_u_whirlpool (char *salt, int salt_len, uint32 iterations, int b, hmac_whirlpool_ctx* hmac) +static void derive_u_whirlpool (const unsigned char *salt, int salt_len, uint32 iterations, int b, hmac_whirlpool_ctx* hmac) { - char* u = hmac->u; - char* k = hmac->k; + unsigned char* u = hmac->u; + unsigned char* k = hmac->k; uint32 c, i; /* iteration 1 */ memcpy (k, salt, salt_len); /* salt */ /* big-endian block number */ b = bswap_32 (b); memcpy (&k[salt_len], &b, 4); hmac_whirlpool_internal (k, salt_len + 4, hmac); memcpy (u, k, WHIRLPOOL_DIGESTSIZE); /* remaining iterations */ for (c = 1; c < iterations; c++) { hmac_whirlpool_internal (k, WHIRLPOOL_DIGESTSIZE, hmac); for (i = 0; i < WHIRLPOOL_DIGESTSIZE; i++) { u[i] ^= k[i]; } } } -void derive_key_whirlpool (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) +void derive_key_whirlpool (const unsigned char *pwd, int pwd_len, const unsigned char *salt, int salt_len, uint32 iterations, unsigned char *dk, int dklen) { hmac_whirlpool_ctx hmac; WHIRLPOOL_CTX* ctx; - char* buf = hmac.k; - char key[WHIRLPOOL_DIGESTSIZE]; + unsigned char* buf = hmac.k; + unsigned char key[WHIRLPOOL_DIGESTSIZE]; int b, l, r; -#if defined (DEVICE_DRIVER) && !defined (_WIN64) - KFLOATING_SAVE floatingPointState; - NTSTATUS saveStatus = STATUS_INVALID_PARAMETER; - if (HasISSE()) - saveStatus = KeSaveFloatingPointState (&floatingPointState); -#endif /* If the password is longer than the hash algorithm block size, let pwd = whirlpool(pwd), as per HMAC specifications. */ if (pwd_len > WHIRLPOOL_BLOCKSIZE) { WHIRLPOOL_CTX tctx; WHIRLPOOL_init (&tctx); - WHIRLPOOL_add ((unsigned char *) pwd, pwd_len, &tctx); - WHIRLPOOL_finalize (&tctx, (unsigned char *) key); + WHIRLPOOL_add (pwd, pwd_len, &tctx); + WHIRLPOOL_finalize (&tctx, key); pwd = key; pwd_len = WHIRLPOOL_DIGESTSIZE; burn (&tctx, sizeof(tctx)); // Prevent leaks } if (dklen % WHIRLPOOL_DIGESTSIZE) { l = 1 + dklen / WHIRLPOOL_DIGESTSIZE; } else { l = dklen / WHIRLPOOL_DIGESTSIZE; } r = dklen - (l - 1) * WHIRLPOOL_DIGESTSIZE; /**** Precompute HMAC Inner Digest ****/ ctx = &(hmac.inner_digest_ctx); WHIRLPOOL_init (ctx); /* Pad the key for inner digest */ for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x36); + buf[b] = (unsigned char) (pwd[b] ^ 0x36); memset (&buf[pwd_len], 0x36, WHIRLPOOL_BLOCKSIZE - pwd_len); - WHIRLPOOL_add ((unsigned char *) buf, WHIRLPOOL_BLOCKSIZE, ctx); + WHIRLPOOL_add (buf, WHIRLPOOL_BLOCKSIZE, ctx); /**** Precompute HMAC Outer Digest ****/ ctx = &(hmac.outer_digest_ctx); WHIRLPOOL_init (ctx); for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x5C); + buf[b] = (unsigned char) (pwd[b] ^ 0x5C); memset (&buf[pwd_len], 0x5C, WHIRLPOOL_BLOCKSIZE - pwd_len); - WHIRLPOOL_add ((unsigned char *) buf, WHIRLPOOL_BLOCKSIZE, ctx); + WHIRLPOOL_add (buf, WHIRLPOOL_BLOCKSIZE, ctx); /* first l - 1 blocks */ for (b = 1; b < l; b++) { derive_u_whirlpool (salt, salt_len, iterations, b, &hmac); memcpy (dk, hmac.u, WHIRLPOOL_DIGESTSIZE); dk += WHIRLPOOL_DIGESTSIZE; } /* last block */ derive_u_whirlpool (salt, salt_len, iterations, b, &hmac); memcpy (dk, hmac.u, r); -#if defined (DEVICE_DRIVER) && !defined (_WIN64) - if (NT_SUCCESS (saveStatus)) - KeRestoreFloatingPointState (&floatingPointState); -#endif - /* Prevent possible leaks. */ burn (&hmac, sizeof(hmac)); burn (key, sizeof(key)); } typedef struct hmac_streebog_ctx_struct { STREEBOG_CTX ctx; STREEBOG_CTX inner_digest_ctx; /*pre-computed inner digest context */ STREEBOG_CTX outer_digest_ctx; /*pre-computed outer digest context */ - CRYPTOPP_ALIGN_DATA(16) char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the Streebog hash */ - char u[STREEBOG_DIGESTSIZE]; + CRYPTOPP_ALIGN_DATA(16) unsigned char k[PKCS5_SALT_SIZE + 4]; /* enough to hold (salt_len + 4) and also the Streebog hash */ + unsigned char u[STREEBOG_DIGESTSIZE]; } hmac_streebog_ctx; void hmac_streebog_internal ( - char *d, /* input/output data. d pointer is guaranteed to be at least 64-bytes long */ + unsigned char *d, /* input/output data. d pointer is guaranteed to be at least 64-bytes long */ int ld, /* length of input data in bytes */ hmac_streebog_ctx* hmac /* HMAC-Whirlpool context which holds temporary variables */ ) { STREEBOG_CTX* ctx = &(hmac->ctx); /**** Restore Precomputed Inner Digest Context ****/ memcpy (ctx, &(hmac->inner_digest_ctx), sizeof (STREEBOG_CTX)); - STREEBOG_add (ctx, (unsigned char *) d, ld); + STREEBOG_add (ctx, d, ld); - STREEBOG_finalize (ctx, (unsigned char *) d); + STREEBOG_finalize (ctx, d); /**** Restore Precomputed Outer Digest Context ****/ memcpy (ctx, &(hmac->outer_digest_ctx), sizeof (STREEBOG_CTX)); - STREEBOG_add (ctx, (unsigned char *) d, STREEBOG_DIGESTSIZE); + STREEBOG_add (ctx, d, STREEBOG_DIGESTSIZE); - STREEBOG_finalize (ctx, (unsigned char *) d); + STREEBOG_finalize (ctx, d); } void hmac_streebog ( - char *k, /* secret key */ + unsigned char *k, /* secret key */ int lk, /* length of the key in bytes */ - char *d, /* input data. d pointer is guaranteed to be at least 32-bytes long */ + unsigned char *d, /* input data. d pointer is guaranteed to be at least 32-bytes long */ int ld /* length of data in bytes */ ) { hmac_streebog_ctx hmac; STREEBOG_CTX* ctx; - char* buf = hmac.k; + unsigned char* buf = hmac.k; int b; - CRYPTOPP_ALIGN_DATA(16) char key[STREEBOG_DIGESTSIZE]; -#if defined (DEVICE_DRIVER) && !defined (_WIN64) - KFLOATING_SAVE floatingPointState; - NTSTATUS saveStatus = STATUS_INVALID_PARAMETER; - if (HasSSE2() || HasSSE41()) - saveStatus = KeSaveFloatingPointState (&floatingPointState); -#endif + CRYPTOPP_ALIGN_DATA(16) unsigned char key[STREEBOG_DIGESTSIZE]; /* If the key is longer than the hash algorithm block size, let key = streebog(key), as per HMAC specifications. */ if (lk > STREEBOG_BLOCKSIZE) { STREEBOG_CTX tctx; STREEBOG_init (&tctx); - STREEBOG_add (&tctx, (unsigned char *) k, lk); - STREEBOG_finalize (&tctx, (unsigned char *) key); + STREEBOG_add (&tctx, k, lk); + STREEBOG_finalize (&tctx, key); k = key; lk = STREEBOG_DIGESTSIZE; burn (&tctx, sizeof(tctx)); // Prevent leaks } /**** Precompute HMAC Inner Digest ****/ ctx = &(hmac.inner_digest_ctx); STREEBOG_init (ctx); /* Pad the key for inner digest */ for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x36); + buf[b] = (unsigned char) (k[b] ^ 0x36); memset (&buf[lk], 0x36, STREEBOG_BLOCKSIZE - lk); - STREEBOG_add (ctx, (unsigned char *) buf, STREEBOG_BLOCKSIZE); + STREEBOG_add (ctx, buf, STREEBOG_BLOCKSIZE); /**** Precompute HMAC Outer Digest ****/ ctx = &(hmac.outer_digest_ctx); STREEBOG_init (ctx); for (b = 0; b < lk; ++b) - buf[b] = (char) (k[b] ^ 0x5C); + buf[b] = (unsigned char) (k[b] ^ 0x5C); memset (&buf[lk], 0x5C, STREEBOG_BLOCKSIZE - lk); - STREEBOG_add (ctx, (unsigned char *) buf, STREEBOG_BLOCKSIZE); + STREEBOG_add (ctx, buf, STREEBOG_BLOCKSIZE); hmac_streebog_internal(d, ld, &hmac); -#if defined (DEVICE_DRIVER) && !defined (_WIN64) - if (NT_SUCCESS (saveStatus)) - KeRestoreFloatingPointState (&floatingPointState); -#endif /* Prevent leaks */ burn(&hmac, sizeof(hmac)); } -static void derive_u_streebog (char *salt, int salt_len, uint32 iterations, int b, hmac_streebog_ctx* hmac) +static void derive_u_streebog (const unsigned char *salt, int salt_len, uint32 iterations, int b, hmac_streebog_ctx* hmac) { - char* u = hmac->u; - char* k = hmac->k; + unsigned char* u = hmac->u; + unsigned char* k = hmac->k; uint32 c, i; /* iteration 1 */ memcpy (k, salt, salt_len); /* salt */ /* big-endian block number */ b = bswap_32 (b); memcpy (&k[salt_len], &b, 4); hmac_streebog_internal (k, salt_len + 4, hmac); memcpy (u, k, STREEBOG_DIGESTSIZE); /* remaining iterations */ for (c = 1; c < iterations; c++) { hmac_streebog_internal (k, STREEBOG_DIGESTSIZE, hmac); for (i = 0; i < STREEBOG_DIGESTSIZE; i++) { u[i] ^= k[i]; } } } -void derive_key_streebog (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen) +void derive_key_streebog (const unsigned char *pwd, int pwd_len, const unsigned char *salt, int salt_len, uint32 iterations, unsigned char *dk, int dklen) { hmac_streebog_ctx hmac; STREEBOG_CTX* ctx; - char* buf = hmac.k; - char key[STREEBOG_DIGESTSIZE]; + unsigned char* buf = hmac.k; + unsigned char key[STREEBOG_DIGESTSIZE]; int b, l, r; -#if defined (DEVICE_DRIVER) && !defined (_WIN64) - KFLOATING_SAVE floatingPointState; - NTSTATUS saveStatus = STATUS_INVALID_PARAMETER; - if (HasSSE2() || HasSSE41()) - saveStatus = KeSaveFloatingPointState (&floatingPointState); -#endif /* If the password is longer than the hash algorithm block size, let pwd = streebog(pwd), as per HMAC specifications. */ if (pwd_len > STREEBOG_BLOCKSIZE) { STREEBOG_CTX tctx; STREEBOG_init (&tctx); - STREEBOG_add (&tctx, (unsigned char *) pwd, pwd_len); - STREEBOG_finalize (&tctx, (unsigned char *) key); + STREEBOG_add (&tctx, pwd, pwd_len); + STREEBOG_finalize (&tctx, key); pwd = key; pwd_len = STREEBOG_DIGESTSIZE; burn (&tctx, sizeof(tctx)); // Prevent leaks } if (dklen % STREEBOG_DIGESTSIZE) { l = 1 + dklen / STREEBOG_DIGESTSIZE; } else { l = dklen / STREEBOG_DIGESTSIZE; } r = dklen - (l - 1) * STREEBOG_DIGESTSIZE; /**** Precompute HMAC Inner Digest ****/ ctx = &(hmac.inner_digest_ctx); STREEBOG_init (ctx); /* Pad the key for inner digest */ for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x36); + buf[b] = (unsigned char) (pwd[b] ^ 0x36); memset (&buf[pwd_len], 0x36, STREEBOG_BLOCKSIZE - pwd_len); - STREEBOG_add (ctx, (unsigned char *) buf, STREEBOG_BLOCKSIZE); + STREEBOG_add (ctx, buf, STREEBOG_BLOCKSIZE); /**** Precompute HMAC Outer Digest ****/ ctx = &(hmac.outer_digest_ctx); STREEBOG_init (ctx); for (b = 0; b < pwd_len; ++b) - buf[b] = (char) (pwd[b] ^ 0x5C); + buf[b] = (unsigned char) (pwd[b] ^ 0x5C); memset (&buf[pwd_len], 0x5C, STREEBOG_BLOCKSIZE - pwd_len); - STREEBOG_add (ctx, (unsigned char *) buf, STREEBOG_BLOCKSIZE); + STREEBOG_add (ctx, buf, STREEBOG_BLOCKSIZE); /* first l - 1 blocks */ for (b = 1; b < l; b++) { derive_u_streebog (salt, salt_len, iterations, b, &hmac); memcpy (dk, hmac.u, STREEBOG_DIGESTSIZE); dk += STREEBOG_DIGESTSIZE; } /* last block */ derive_u_streebog (salt, salt_len, iterations, b, &hmac); memcpy (dk, hmac.u, r); -#if defined (DEVICE_DRIVER) && !defined (_WIN64) - if (NT_SUCCESS (saveStatus)) - KeRestoreFloatingPointState (&floatingPointState); -#endif - /* Prevent possible leaks. */ burn (&hmac, sizeof(hmac)); burn (key, sizeof(key)); } wchar_t *get_pkcs5_prf_name (int pkcs5_prf_id) { switch (pkcs5_prf_id) { case SHA512: return L"HMAC-SHA-512"; case SHA256: return L"HMAC-SHA-256"; case BLAKE2S: return L"HMAC-BLAKE2s-256"; case WHIRLPOOL: return L"HMAC-Whirlpool"; case STREEBOG: return L"HMAC-STREEBOG"; default: return L"(Unknown)"; } } @@ -1295,50 +1196,50 @@ int get_pkcs5_iteration_count (int pkcs5_prf_id, int pim, BOOL bBoot) else { return bBoot? pim * 2048 : 15000 + pim * 1000; } case SHA512: return ((pim == 0)? 500000 : 15000 + pim * 1000); case WHIRLPOOL: return ((pim == 0)? 500000 : 15000 + pim * 1000); case SHA256: if (pim == 0) return bBoot? 200000 : 500000; else { return bBoot? pim * 2048 : 15000 + pim * 1000; } case STREEBOG: if (pim == 0) return bBoot? 200000 : 500000; else { return bBoot? pim * 2048 : 15000 + pim * 1000; } default: TC_THROW_FATAL_EXCEPTION; // Unknown/wrong ID } -#if _MSC_VER < 1900 + return 0; -#endif + } int is_pkcs5_prf_supported (int pkcs5_prf_id, PRF_BOOT_TYPE bootType) { if (pkcs5_prf_id == 0) // auto-detection always supported return 1; if ( (bootType == PRF_BOOT_MBR && pkcs5_prf_id != BLAKE2S && pkcs5_prf_id != SHA256) || (bootType != PRF_BOOT_MBR && (pkcs5_prf_id < FIRST_PRF_ID || pkcs5_prf_id > LAST_PRF_ID)) ) return 0; return 1; } #endif //!TC_WINDOWS_BOOT diff --git a/src/Common/Pkcs5.h b/src/Common/Pkcs5.h index a9abeec5..65fad038 100644 --- a/src/Common/Pkcs5.h +++ b/src/Common/Pkcs5.h @@ -1,61 +1,61 @@ /* 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-2017 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #ifndef TC_HEADER_PKCS5 #define TC_HEADER_PKCS5 #include "Tcdefs.h" #if defined(__cplusplus) extern "C" { #endif /* output written to input_digest which must be at lease 32 bytes long */ -void hmac_blake2s (char *key, int keylen, char *input_digest, int len); -void derive_key_blake2s (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); +void hmac_blake2s (unsigned char *key, int keylen, unsigned char *input_digest, int len); +void derive_key_blake2s (const unsigned char *pwd, int pwd_len, const unsigned char *salt, int salt_len, uint32 iterations, unsigned char *dk, int dklen); /* output written to d which must be at lease 32 bytes long */ -void hmac_sha256 (char *k, int lk, char *d, int ld); -void derive_key_sha256 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); +void hmac_sha256 (unsigned char *k, int lk, unsigned char *d, int ld); +void derive_key_sha256 (const unsigned char *pwd, int pwd_len, const unsigned char *salt, int salt_len, uint32 iterations, unsigned char *dk, int dklen); #ifndef TC_WINDOWS_BOOT /* output written to d which must be at lease 64 bytes long */ -void hmac_sha512 (char *k, int lk, char *d, int ld); -void derive_key_sha512 (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); +void hmac_sha512 (unsigned char *k, int lk, unsigned char *d, int ld); +void derive_key_sha512 (const unsigned char *pwd, int pwd_len, const unsigned char *salt, int salt_len, uint32 iterations, unsigned char *dk, int dklen); /* output written to d which must be at lease 64 bytes long */ -void hmac_whirlpool (char *k, int lk, char *d, int ld); -void derive_key_whirlpool (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); +void hmac_whirlpool (unsigned char *k, int lk, unsigned char *d, int ld); +void derive_key_whirlpool (const unsigned char *pwd, int pwd_len, const unsigned char *salt, int salt_len, uint32 iterations, unsigned char *dk, int dklen); -void hmac_streebog (char *k, int32 lk, char *d, int32 ld); -void derive_key_streebog (char *pwd, int pwd_len, char *salt, int salt_len, uint32 iterations, char *dk, int dklen); +void hmac_streebog (unsigned char *k, int lk, unsigned char *d, int ld); +void derive_key_streebog (const unsigned char *pwd, int pwd_len, const unsigned char *salt, int salt_len, uint32 iterations, unsigned char *dk, int dklen); int get_pkcs5_iteration_count (int pkcs5_prf_id, int pim, BOOL bBoot); wchar_t *get_pkcs5_prf_name (int pkcs5_prf_id); /* check if given PRF supported.*/ typedef enum { PRF_BOOT_NO = 0, PRF_BOOT_MBR, PRF_BOOT_GPT } PRF_BOOT_TYPE; int is_pkcs5_prf_supported (int pkcs5_prf_id, PRF_BOOT_TYPE bootType); #endif #if defined(__cplusplus) } #endif #endif // TC_HEADER_PKCS5 diff --git a/src/Common/Progress.c b/src/Common/Progress.c index 2619b173..24efcad5 100644 --- a/src/Common/Progress.c +++ b/src/Common/Progress.c @@ -9,126 +9,126 @@ and all other portions of this file are Copyright (c) 2013-2017 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #include "Tcdefs.h" #include "Language.h" #include "Dlgcode.h" #include "Progress.h" #include "../Format/Tcformat.h" #include "../Format/FormatCom.h" #include "../Format/resource.h" #include <Strsafe.h> static ULONG prevTime, startTime; static __int64 TotalSize; static __int64 resumedPointBytesDone; static BOOL bProgressBarReverse = FALSE; static BOOL bRWThroughput = FALSE; static BOOL bShowStatus = FALSE; static BOOL bPercentMode = FALSE; static wchar_t *seconds, *minutes, *hours, *days; // If bIOThroughput is TRUE, the speed reflects the amount of data read AND written per second (rather than // the speed of the "transform cursor"). void InitProgressBar (__int64 totalBytes, __int64 bytesDone, BOOL bReverse, BOOL bIOThroughput, BOOL bDisplayStatus, BOOL bShowPercent) { - HWND hProgressBar = GetDlgItem (hCurPage, nPbar); - SendMessage (hProgressBar, PBM_SETRANGE32, 0, 10000); - SendMessage (hProgressBar, PBM_SETSTEP, 1, 0); + HWND hCurProgressBar = GetDlgItem (hCurPage, nPbar); + SendMessage (hCurProgressBar, PBM_SETRANGE32, 0, 10000); + SendMessage (hCurProgressBar, PBM_SETSTEP, 1, 0); bProgressBarReverse = bReverse; bRWThroughput = bIOThroughput; bShowStatus = bDisplayStatus; bPercentMode = bShowPercent; seconds = GetString ("SECONDS"); minutes = GetString ("MINUTES"); hours = GetString ("HOURS"); days = GetString ("DAYS"); prevTime = startTime = GetTickCount (); TotalSize = totalBytes; resumedPointBytesDone = bytesDone; } BOOL UpdateProgressBar (__int64 byteOffset) { return UpdateProgressBarProc (byteOffset); } BOOL UpdateProgressBarProc (__int64 byteOffset) { wchar_t text[100]; wchar_t speed[100]; - HWND hProgressBar = GetDlgItem (hCurPage, nPbar); + HWND hCurProgressBar = GetDlgItem (hCurPage, nPbar); int time = GetTickCount (); int elapsed = (time - startTime) / 1000; uint64 bytesDone = (bProgressBarReverse ? (TotalSize - byteOffset) : byteOffset); uint64 bytesPerSec = (bProgressBarReverse ? (resumedPointBytesDone - byteOffset) : (bytesDone - resumedPointBytesDone)) / (elapsed + 1); if (bPercentMode) { double perc = (double) (100.0 * (bProgressBarReverse ? ((double) (TotalSize - byteOffset)) : ((double) byteOffset)) / (TotalSize == 0 ? 0.0001 : ((double) TotalSize))); if (perc > 99.999999999) StringCchCopyW (text,ARRAYSIZE(text), GetString ("PROCESSED_PORTION_100_PERCENT")); else StringCchPrintfW (text, ARRAYSIZE (text), GetString ("PROCESSED_PORTION_X_PERCENT"), perc); StringCchCatW (text, ARRAYSIZE(text), L" "); } else { GetSizeString (bytesDone, text, sizeof(text)); if (bytesDone < (unsigned __int64) BYTES_PER_MB * 1000000) StringCchPrintfW(text, ARRAYSIZE(text), L"%I64d %s ", bytesDone / BYTES_PER_MB, GetString ("MB")); else if (bytesDone < (unsigned __int64) BYTES_PER_GB * 1000000) StringCchPrintfW(text, ARRAYSIZE(text), L"%I64d %s ", bytesDone / BYTES_PER_GB, GetString ("GB")); else if (bytesDone < (unsigned __int64) BYTES_PER_TB * 1000000) StringCchPrintfW(text, ARRAYSIZE(text), L"%I64d %s ", bytesDone / BYTES_PER_TB, GetString ("TB")); else StringCchPrintfW(text, ARRAYSIZE(text), L"%I64d %s ", bytesDone / BYTES_PER_PB, GetString ("PB")); } SetWindowTextW (GetDlgItem (hCurPage, IDC_BYTESWRITTEN), text); if (!bShowStatus) { GetSpeedString (bRWThroughput ? bytesPerSec*2 : bytesPerSec, speed, sizeof(speed)); StringCchCatW (speed, ARRAYSIZE(speed), L" "); SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), speed); } if (byteOffset < TotalSize) { int64 sec = (int64) ((bProgressBarReverse ? byteOffset : (TotalSize - byteOffset)) / (bytesPerSec == 0 ? 0.001 : bytesPerSec)); if (bytesPerSec == 0 || sec > 60 * 60 * 24 * 999) StringCchPrintfW (text, ARRAYSIZE(text), L"%s ", GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE")); else if (sec >= 60 * 60 * 24 * 2) StringCchPrintfW (text, ARRAYSIZE(text), L"%I64d %s ", sec / (60 * 24 * 60), days); else if (sec >= 120 * 60) StringCchPrintfW (text, ARRAYSIZE(text), L"%I64d %s ", sec / (60 * 60), hours); else if (sec >= 120) StringCchPrintfW (text, ARRAYSIZE(text), L"%I64d %s ", sec / 60, minutes); else StringCchPrintfW (text, ARRAYSIZE(text), L"%I64d %s ", sec, seconds); SetWindowTextW (GetDlgItem (hCurPage, IDC_TIMEREMAIN), text); } prevTime = time; - SendMessage (hProgressBar, PBM_SETPOS, + SendMessage (hCurProgressBar, PBM_SETPOS, (int) (10000.0 * (bProgressBarReverse ? (TotalSize - byteOffset) : byteOffset) / (TotalSize == 0 ? 1 : TotalSize)), 0); return bVolTransformThreadCancel; } diff --git a/src/Common/Random.c b/src/Common/Random.c index ee3fcf53..0be4d601 100644 --- a/src/Common/Random.c +++ b/src/Common/Random.c @@ -1,51 +1,52 @@ /* Legal Notice: Some portions of the source code contained in this file were derived from the source code of TrueCrypt 7.1a, which is Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux and which is governed by the 'License Agreement for Encryption for the Masses' Modifications and additions to the original source code (contained in this file) and all other portions of this file are Copyright (c) 2013-2017 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #include "Tcdefs.h" #include "Crc.h" #include "Random.h" #include "Dlgcode.h" #include "Crypto\cpu.h" #include "Crypto\jitterentropy.h" #include "Crypto\rdrand.h" #include <Strsafe.h> +#include <bcrypt.h> static unsigned __int8 buffer[RNG_POOL_SIZE]; static unsigned char *pRandPool = NULL; static BOOL bRandDidInit = FALSE; static int nRandIndex = 0, randPoolReadIndex = 0; static int HashFunction = DEFAULT_HASH_ALGORITHM; static BOOL bDidSlowPoll = FALSE; BOOL volatile bFastPollEnabled = TRUE; /* Used to reduce CPU load when performing benchmarks */ BOOL volatile bRandmixEnabled = TRUE; /* Used to reduce CPU load when performing benchmarks */ static BOOL RandomPoolEnrichedByUser = FALSE; static HANDLE PeriodicFastPollThreadHandle = NULL; /* Macro to add a single byte to the pool */ #define RandaddByte(x) {\ if (nRandIndex == RNG_POOL_SIZE) nRandIndex = 0;\ pRandPool[nRandIndex] = (unsigned char) ((unsigned char)x + pRandPool[nRandIndex]); \ if (nRandIndex % RANDMIX_BYTE_INTERVAL == 0) Randmix();\ nRandIndex++; \ } /* Macro to add four bytes to the pool */ #define RandaddInt32(x) RandAddInt((unsigned __int32)x); #ifdef _WIN64 #define RandaddIntPtr(x) RandAddInt64((unsigned __int64)x); #else #define RandaddIntPtr(x) RandAddInt((unsigned __int32)x); #endif void RandAddInt (unsigned __int32 x) @@ -62,176 +63,171 @@ void RandAddInt64 (unsigned __int64 x) RandaddByte((x >> 8)); RandaddByte((x >> 16)); RandaddByte((x >> 24)); RandaddByte((x >> 32)); RandaddByte((x >> 40)); RandaddByte((x >> 48)); RandaddByte((x >> 56)); } #include <tlhelp32.h> #include "Dlgcode.h" #ifndef SRC_POS #define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) #endif HHOOK hMouse = NULL; /* Mouse hook for the random number generator */ HHOOK hKeyboard = NULL; /* Keyboard hook for the random number generator */ DWORD ProcessedMouseEventsCounter = 0; /* Variables for thread control, the thread is used to gather up info about the system in in the background */ CRITICAL_SECTION critRandProt; /* The critical section */ BOOL volatile bThreadTerminate = FALSE; /* This variable is shared among thread's so its made volatile */ /* Network library handle for the SlowPoll function */ HANDLE hNetAPI32 = NULL; // CryptoAPI -BOOL CryptoAPIAvailable = FALSE; DWORD CryptoAPILastError = ERROR_SUCCESS; -HCRYPTPROV hCryptProv; +typedef DWORD (WINAPI *RtlNtStatusToDosError_t)(NTSTATUS); +RtlNtStatusToDosError_t pRtlNtStatusToDosError = NULL; /* Init the random number generator, setup the hooks, and start the thread */ int RandinitWithCheck ( int* pAlreadyInitialized) { BOOL bIgnoreHookError = FALSE; DWORD dwLastError = ERROR_SUCCESS; + HMODULE ntdll; if (GetMaxPkcs5OutSize() > RNG_POOL_SIZE) TC_THROW_FATAL_EXCEPTION; if(bRandDidInit) { if (pAlreadyInitialized) *pAlreadyInitialized = 1; return 0; } if (pAlreadyInitialized) *pAlreadyInitialized = 0; InitializeCriticalSection (&critRandProt); bRandDidInit = TRUE; CryptoAPILastError = ERROR_SUCCESS; ProcessedMouseEventsCounter = 0; if (pRandPool == NULL) { pRandPool = (unsigned char *) _aligned_malloc (RANDOMPOOL_ALLOCSIZE, 16); if (pRandPool == NULL) goto error; bDidSlowPoll = FALSE; RandomPoolEnrichedByUser = FALSE; memset (pRandPool, 0, RANDOMPOOL_ALLOCSIZE); VirtualLock (pRandPool, RANDOMPOOL_ALLOCSIZE); } bIgnoreHookError = IsThreadInSecureDesktop(GetCurrentThreadId()); hKeyboard = SetWindowsHookEx (WH_KEYBOARD, (HOOKPROC)&KeyboardProc, NULL, GetCurrentThreadId ()); if (hKeyboard == 0 && !bIgnoreHookError) handleWin32Error (0, SRC_POS); hMouse = SetWindowsHookEx (WH_MOUSE, (HOOKPROC)&MouseProc, NULL, GetCurrentThreadId ()); if (hMouse == 0 && !bIgnoreHookError) { handleWin32Error (0, SRC_POS); goto error; } - if (!CryptAcquireContext (&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) - { - CryptoAPIAvailable = FALSE; - CryptoAPILastError = GetLastError (); + ntdll = GetModuleHandleW(L"ntdll.dll"); + if (!ntdll) { + // If ntdll.dll is not found, return a fallback error code + CryptoAPILastError = ERROR_MOD_NOT_FOUND; goto error; } else - CryptoAPIAvailable = TRUE; + pRtlNtStatusToDosError = (RtlNtStatusToDosError_t)GetProcAddress(ntdll, "RtlNtStatusToDosError"); if (!(PeriodicFastPollThreadHandle = (HANDLE) _beginthreadex (NULL, 0, PeriodicFastPollThreadProc, NULL, 0, NULL))) goto error; return 0; error: dwLastError = GetLastError(); RandStop (TRUE); SetLastError (dwLastError); return 1; } int Randinit () { return RandinitWithCheck (NULL); } /* Close everything down, including the thread which is closed down by setting a flag which eventually causes the thread function to exit */ void RandStop (BOOL freePool) { if (!bRandDidInit && freePool && pRandPool) goto freePool; if (bRandDidInit == FALSE) return; EnterCriticalSection (&critRandProt); if (hMouse != 0) UnhookWindowsHookEx (hMouse); if (hKeyboard != 0) UnhookWindowsHookEx (hKeyboard); bThreadTerminate = TRUE; LeaveCriticalSection (&critRandProt); if (PeriodicFastPollThreadHandle) WaitForSingleObject (PeriodicFastPollThreadHandle, INFINITE); if (hNetAPI32 != 0) { FreeLibrary (hNetAPI32); hNetAPI32 = NULL; } - if (CryptoAPIAvailable) - { - CryptReleaseContext (hCryptProv, 0); - CryptoAPIAvailable = FALSE; - CryptoAPILastError = ERROR_SUCCESS; - } hMouse = NULL; hKeyboard = NULL; bThreadTerminate = FALSE; DeleteCriticalSection (&critRandProt); bRandDidInit = FALSE; freePool: if (freePool) { bDidSlowPoll = FALSE; RandomPoolEnrichedByUser = FALSE; if (pRandPool != NULL) { burn (pRandPool, RANDOMPOOL_ALLOCSIZE); _aligned_free (pRandPool); pRandPool = NULL; } } } BOOL IsRandomNumberGeneratorStarted () { return bRandDidInit; } void RandSetHashFunction (int hash_algo_id) { @@ -648,60 +644,61 @@ static unsigned __stdcall PeriodicFastPollThreadProc (void *dummy) } } /* Type definitions for function pointers to call NetAPI32 functions */ typedef DWORD (WINAPI * NETSTATISTICSGET) (LPWSTR szServer, LPWSTR szService, DWORD dwLevel, DWORD dwOptions, LPBYTE * lpBuffer); typedef DWORD (WINAPI * NETAPIBUFFERSIZE) (LPVOID lpBuffer, LPDWORD cbBuffer); typedef DWORD (WINAPI * NETAPIBUFFERFREE) (LPVOID lpBuffer); NETSTATISTICSGET pNetStatisticsGet = NULL; NETAPIBUFFERSIZE pNetApiBufferSize = NULL; NETAPIBUFFERFREE pNetApiBufferFree = NULL; /* This is the slowpoll function which gathers up network/hard drive performance data for the random pool */ BOOL SlowPoll (void) { static int isWorkstation = -1; static int cbPerfData = 0x10000; HANDLE hDevice; LPBYTE lpBuffer; DWORD dwSize, status; LPWSTR lpszLanW, lpszLanS; int nDrive; + NTSTATUS bStatus = 0; /* Find out whether this is an NT server or workstation if necessary */ if (isWorkstation == -1) { HKEY hKey; if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_READ, &hKey) == ERROR_SUCCESS) { wchar_t szValue[32]; dwSize = sizeof (szValue); isWorkstation = TRUE; status = RegQueryValueEx (hKey, L"ProductType", 0, NULL, (LPBYTE) szValue, &dwSize); if (status == ERROR_SUCCESS && _wcsicmp (szValue, L"WinNT")) /* Note: There are (at least) three cases for ProductType: WinNT = NT Workstation, ServerNT = NT Server, LanmanNT = NT Server acting as a Domain Controller */ isWorkstation = FALSE; RegCloseKey (hKey); } } /* Initialize the NetAPI32 function pointers if necessary */ if (hNetAPI32 == NULL) { @@ -756,115 +753,114 @@ BOOL SlowPoll (void) RandaddBuf ((unsigned char *) lpBuffer, dwSize); pNetApiBufferFree (lpBuffer); } /* Get disk I/O statistics for all the hard drives */ for (nDrive = 0;; nDrive++) { DISK_PERFORMANCE diskPerformance; wchar_t szDevice[24]; /* Check whether we can access this device */ StringCchPrintfW (szDevice, ARRAYSIZE(szDevice), L"\\\\.\\PhysicalDrive%d", nDrive); hDevice = CreateFile (szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hDevice == INVALID_HANDLE_VALUE) break; /* Note: This only works if you have turned on the disk performance counters with 'diskperf -y'. These counters are off by default */ if (DeviceIoControl (hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0, &diskPerformance, sizeof (DISK_PERFORMANCE), &dwSize, NULL)) { RandaddBuf ((unsigned char *) &diskPerformance, dwSize); } CloseHandle (hDevice); } - // CryptoAPI: We always have a valid CryptoAPI context when we arrive here but - // we keep the check for clarity purpose - if ( !CryptoAPIAvailable ) - return FALSE; - if (CryptGenRandom (hCryptProv, sizeof (buffer), buffer)) + + bStatus = BCryptGenRandom(NULL, buffer, sizeof(buffer), BCRYPT_USE_SYSTEM_PREFERRED_RNG); + if (NT_SUCCESS(bStatus)) { RandaddBuf (buffer, sizeof (buffer)); } else { - /* return error in case CryptGenRandom fails */ - CryptoAPILastError = GetLastError (); + /* return error in case BCryptGenRandom fails */ + CryptoAPILastError = pRtlNtStatusToDosError (bStatus); return FALSE; } /* use JitterEntropy library to get good quality random bytes based on CPU timing jitter */ if (0 == jent_entropy_init ()) { struct rand_data *ec = jent_entropy_collector_alloc (1, 0); if (ec) { ssize_t rndLen = jent_read_entropy (ec, (char*) buffer, sizeof (buffer)); if (rndLen > 0) RandaddBuf (buffer, (int) rndLen); jent_entropy_collector_free (ec); } } // use RDSEED or RDRAND from CPU as source of entropy if present if ( IsCpuRngEnabled() && ( (HasRDSEED() && RDSEED_getBytes (buffer, sizeof (buffer))) || (HasRDRAND() && RDRAND_getBytes (buffer, sizeof (buffer))) )) { RandaddBuf (buffer, sizeof (buffer)); } burn(buffer, sizeof (buffer)); Randmix(); return TRUE; } /* This is the fastpoll function which gathers up info by calling various api's */ BOOL FastPoll (void) { int nOriginalRandIndex = nRandIndex; static BOOL addedFixedItems = FALSE; FILETIME creationTime, exitTime, kernelTime, userTime; SIZE_T minimumWorkingSetSize, maximumWorkingSetSize; LARGE_INTEGER performanceCount; MEMORYSTATUSEX memoryStatus; HANDLE handle; POINT point; + NTSTATUS bStatus = 0; /* Get various basic pieces of system information */ RandaddIntPtr (GetActiveWindow ()); /* Handle of active window */ RandaddIntPtr (GetCapture ()); /* Handle of window with mouse capture */ RandaddIntPtr (GetClipboardOwner ()); /* Handle of clipboard owner */ RandaddIntPtr (GetClipboardViewer ()); /* Handle of start of clpbd.viewer list */ RandaddIntPtr (GetCurrentProcess ()); /* Pseudohandle of current process */ RandaddInt32 (GetCurrentProcessId ()); /* Current process ID */ RandaddIntPtr (GetCurrentThread ()); /* Pseudohandle of current thread */ RandaddInt32 (GetCurrentThreadId ()); /* Current thread ID */ RandaddInt32 (GetCurrentTime ()); /* Milliseconds since Windows started */ RandaddIntPtr (GetDesktopWindow ()); /* Handle of desktop window */ RandaddIntPtr (GetFocus ()); /* Handle of window with kb.focus */ RandaddInt32 (GetInputState ()); /* Whether sys.queue has any events */ RandaddInt32 (GetMessagePos ()); /* Cursor pos.for last message */ RandaddInt32 (GetMessageTime ()); /* 1 ms time for last message */ RandaddIntPtr (GetOpenClipboardWindow ()); /* Handle of window with clpbd.open */ RandaddIntPtr (GetProcessHeap ()); /* Handle of process heap */ RandaddIntPtr (GetProcessWindowStation ()); /* Handle of procs window station */ RandaddInt32 (GetQueueStatus (QS_ALLEVENTS)); /* Types of events in input queue */ /* Get multiword system information */ @@ -901,70 +897,68 @@ BOOL FastPoll (void) &maximumWorkingSetSize); RandaddIntPtr (minimumWorkingSetSize); RandaddIntPtr (maximumWorkingSetSize); /* The following are fixed for the lifetime of the process so we only add them once */ if (addedFixedItems == 0) { STARTUPINFO startupInfo; /* Get name of desktop, console window title, new window position and size, window flags, and handles for stdin, stdout, and stderr */ startupInfo.cb = sizeof (STARTUPINFO); GetStartupInfo (&startupInfo); RandaddBuf ((unsigned char *) &startupInfo, sizeof (STARTUPINFO)); addedFixedItems = TRUE; } /* The docs say QPC can fail if appropriate hardware is not available. It works on 486 & Pentium boxes, but hasn't been tested for 386 or RISC boxes */ if (QueryPerformanceCounter (&performanceCount)) RandaddBuf ((unsigned char *) &performanceCount, sizeof (LARGE_INTEGER)); else { /* Millisecond accuracy at best... */ DWORD dwTicks = GetTickCount (); RandaddBuf ((unsigned char *) &dwTicks, sizeof (dwTicks)); } - // CryptoAPI: We always have a valid CryptoAPI context when we arrive here but - // we keep the check for clarity purpose - if ( !CryptoAPIAvailable ) - return FALSE; - if (CryptGenRandom (hCryptProv, sizeof (buffer), buffer)) + + bStatus = BCryptGenRandom(NULL, buffer, sizeof(buffer), BCRYPT_USE_SYSTEM_PREFERRED_RNG); + if (NT_SUCCESS(bStatus)) { RandaddBuf (buffer, sizeof (buffer)); } else { - /* return error in case CryptGenRandom fails */ - CryptoAPILastError = GetLastError (); + /* return error in case BCryptGenRandom fails */ + CryptoAPILastError = pRtlNtStatusToDosError (bStatus); return FALSE; } // use RDSEED or RDRAND from CPU as source of entropy if enabled if ( IsCpuRngEnabled() && ( (HasRDSEED() && RDSEED_getBytes (buffer, sizeof (buffer))) || (HasRDRAND() && RDRAND_getBytes (buffer, sizeof (buffer))) )) { RandaddBuf (buffer, sizeof (buffer)); } burn (buffer, sizeof(buffer)); /* Apply the pool mixing function */ Randmix(); /* Restore the original pool cursor position. If this wasn't done, mouse coordinates could be written to a limited area of the pool, especially when moving the mouse uninterruptedly. The severity of the problem would depend on the length of data written by FastPoll (if it was equal to the size of the pool, mouse coordinates would be written only to a particular 4-byte area, whenever moving the mouse uninterruptedly). */ nRandIndex = nOriginalRandIndex; return TRUE; } diff --git a/src/Common/SecurityToken.cpp b/src/Common/SecurityToken.cpp index 2a8222e6..cd4926a0 100644 --- a/src/Common/SecurityToken.cpp +++ b/src/Common/SecurityToken.cpp @@ -193,61 +193,61 @@ namespace VeraCrypt bool unrecognizedTokenPresent = false; vector <SecurityTokenKeyfile> keyfiles; foreach(const CK_SLOT_ID & slotId, GetTokenSlots()) { SecurityTokenInfo token; if (slotIdFilter && *slotIdFilter != slotId) continue; try { LoginUserIfRequired(slotId); token = GetTokenInfo(slotId); } catch (UserAbort&) { continue; } catch (Pkcs11Exception& e) { if (e.GetErrorCode() == CKR_TOKEN_NOT_RECOGNIZED) { unrecognizedTokenPresent = true; continue; } throw; } - foreach(const CK_OBJECT_HANDLE & dataHandle, GetObjects(slotId, CKO_DATA)) + for(const CK_OBJECT_HANDLE & dataHandle: GetObjects(slotId, CKO_DATA)) { SecurityTokenKeyfile keyfile; keyfile.Handle = dataHandle; keyfile.Token->SlotId = slotId; keyfile.Token = shared_ptr<SecurityTokenInfo>(new SecurityTokenInfo(token)); vector <uint8> privateAttrib; GetObjectAttribute(slotId, dataHandle, CKA_PRIVATE, privateAttrib); if (privateAttrib.size() == sizeof(CK_BBOOL) && *(CK_BBOOL*)&privateAttrib.front() != CK_TRUE) continue; vector <uint8> label; GetObjectAttribute(slotId, dataHandle, CKA_LABEL, label); label.push_back(0); keyfile.IdUtf8 = (char*)&label.front(); #if defined (TC_WINDOWS) && !defined (TC_PROTOTYPE) keyfile.Id = Utf8StringToWide((const char*)&label.front()); #else keyfile.Id = StringConverter::ToWide((const char*)&label.front()); #endif if (keyfile.Id.empty() || (!keyfileIdFilter.empty() && keyfileIdFilter != keyfile.Id)) continue; keyfiles.push_back(keyfile); if (!keyfileIdFilter.empty()) break; @@ -321,61 +321,61 @@ namespace VeraCrypt } void SecurityTokenKeyfile::GetKeyfileData(vector <uint8>& keyfileData) const { SecurityToken::LoginUserIfRequired(Token->SlotId); SecurityToken::GetObjectAttribute(Token->SlotId, Handle, CKA_VALUE, keyfileData); } vector <CK_OBJECT_HANDLE> SecurityToken::GetObjects(CK_SLOT_ID slotId, CK_ATTRIBUTE_TYPE objectClass) { if (Sessions.find(slotId) == Sessions.end()) throw ParameterIncorrect(SRC_POS); CK_ATTRIBUTE findTemplate; findTemplate.type = CKA_CLASS; findTemplate.pValue = &objectClass; findTemplate.ulValueLen = sizeof(objectClass); CK_RV status = Pkcs11Functions->C_FindObjectsInit(Sessions[slotId].Handle, &findTemplate, 1); if (status != CKR_OK) throw Pkcs11Exception(status); finally_do_arg(CK_SLOT_ID, slotId, { Pkcs11Functions->C_FindObjectsFinal(Sessions[finally_arg].Handle); }); CK_ULONG objectCount; vector <CK_OBJECT_HANDLE> objects; while (true) { CK_OBJECT_HANDLE object; - CK_RV status = Pkcs11Functions->C_FindObjects(Sessions[slotId].Handle, &object, 1, &objectCount); + status = Pkcs11Functions->C_FindObjects(Sessions[slotId].Handle, &object, 1, &objectCount); if (status != CKR_OK) throw Pkcs11Exception(status); if (objectCount != 1) break; objects.push_back(object); } return objects; } void SecurityToken::GetObjectAttribute(CK_SLOT_ID slotId, CK_OBJECT_HANDLE tokenObject, CK_ATTRIBUTE_TYPE attributeType, vector <uint8>& attributeValue) { attributeValue.clear(); if (Sessions.find(slotId) == Sessions.end()) throw ParameterIncorrect(SRC_POS); CK_ATTRIBUTE attribute; attribute.type = attributeType; attribute.pValue = NULL_PTR; CK_RV status = Pkcs11Functions->C_GetAttributeValue(Sessions[slotId].Handle, tokenObject, &attribute, 1); if (status != CKR_OK) throw Pkcs11Exception(status); if (attribute.ulValueLen == 0) return; diff --git a/src/Common/Tcdefs.h b/src/Common/Tcdefs.h index 3fd18358..e7eee177 100644 --- a/src/Common/Tcdefs.h +++ b/src/Common/Tcdefs.h @@ -213,89 +213,82 @@ typedef int LONG; #define strncpy(strDest,strSource,count) AsciiStrnCpyS(strDest,MAX_STRING_SIZE,strSource,(UINTN)count) #define strlen(str) (size_t)(AsciiStrnLenS(str,MAX_STRING_SIZE)) #define strstr AsciiStrStr // #define rotr32(x,n) (((x) >> n) | ((x) << (32 - n))) // #define rotl32(x,n) (((x) << n) | ((x) >> (32 - n))) // #define rotr64(x,n) (((x) >> n) | ((x) << (64 - n))) // #define rotl64(x,n) (((x) << n) | ((x) >> (64 - n))) // #define bswap_32(x) (rotl32((((x) & 0xFF00FF00) >> 8) | (((x) & 0x00FF00FF) << 8), 16U)) // #define bswap_64(x) rotl64(((((((x & LL(0xFF00FF00FF00FF00)) >> 8) | ((x & LL(0x00FF00FF00FF00FF)) << 8)) & LL(0xFFFF0000FFFF0000)) >> 16) | (((((x & LL(0xFF00FF00FF00FF00)) >> 8) | ((x & LL(0x00FF00FF00FF00FF)) << 8)) & LL(0x0000FFFF0000FFFF)) << 16)), 32U) #endif #ifdef TC_WINDOWS_BOOT # ifdef __cplusplus extern "C" # endif void ThrowFatalException (int line); # define TC_THROW_FATAL_EXCEPTION ThrowFatalException (__LINE__) #elif defined (TC_WINDOWS_DRIVER) # define TC_THROW_FATAL_EXCEPTION KeBugCheckEx (SECURITY_SYSTEM, __LINE__, 0, 0, 'VC') #elif defined(_UEFI) void ThrowFatalException(int line); # define TC_THROW_FATAL_EXCEPTION ThrowFatalException (__LINE__) #elif (defined(__clang__) && __has_builtin(__builtin_trap)) \ || (defined(__GNUC__ ) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3))) \ || (__has_builtin(__builtin_trap)) # define TC_THROW_FATAL_EXCEPTION __builtin_trap() +#elif defined(_MSC_VER) +#include <intrin.h> +# define TC_THROW_FATAL_EXCEPTION __fastfail(FAST_FAIL_FATAL_APP_EXIT) #else # define TC_THROW_FATAL_EXCEPTION *(char *) 0 = 0 #endif #ifdef __COVERITY__ #undef TC_THROW_FATAL_EXCEPTION #define TC_THROW_FATAL_EXCEPTION __coverity_panic__() #endif #ifdef TC_WINDOWS_DRIVER #include <ntifs.h> #include <ntddk.h> /* Standard header file for nt drivers */ #include <ntdddisk.h> /* Standard I/O control codes */ -/* defines needed for using enhanced protection of NX pool under Windows 8 and later */ -#define NonPagedPoolNx 512 -#define MdlMappingNoExecute 0x40000000 -/* variables used in the implementation of enhanced protection of NX pool under Windows 8 and later */ -extern POOL_TYPE ExDefaultNonPagedPoolType; -extern ULONG ExDefaultMdlProtection; -#ifdef _WIN64 extern ULONG AllocTag; -#else -#define AllocTag 'MMCV' -#endif -#define TCalloc(size) ((void *) ExAllocatePoolWithTag( ExDefaultNonPagedPoolType, size, AllocTag )) +#define TCalloc(size) ((void *) ExAllocatePool2( POOL_FLAG_NON_PAGED, size, AllocTag )) #define TCfree(memblock) ExFreePoolWithTag( memblock, AllocTag ) #define DEVICE_DRIVER #ifndef BOOL typedef int BOOL; #endif #ifndef WORD typedef USHORT WORD; #endif #ifndef BOOLEAN typedef unsigned char BOOLEAN; #endif #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE !TRUE #endif typedef NTSTATUS (NTAPI *KeSaveExtendedProcessorStateFn) ( __in ULONG64 Mask, PXSTATE_SAVE XStateSave ); diff --git a/src/Common/Tests.c b/src/Common/Tests.c index 530e7577..8f851f62 100644 --- a/src/Common/Tests.c +++ b/src/Common/Tests.c @@ -540,145 +540,134 @@ typedef struct _HashTestVector const char* hexOutput; } HashTestVector; typedef int (__cdecl HashFunction) (unsigned char* input, unsigned long inputLen, unsigned char* output); unsigned char HexCharToByte (char c) { if (c >= ('0') && c <= ('9')) return c - ('0'); else if (c >= ('A') && c <= ('F')) return c - ('A') + 10; else if (c >= ('a') && c <= ('f')) return c - ('a') + 10; else return 0xFF; } unsigned long HexStringToByteArray(const char* hexStr, unsigned char* pbData) { unsigned long count = 0; while (*hexStr) { *pbData++ = (HexCharToByte(hexStr[0]) << 4) | HexCharToByte(hexStr[1]); hexStr += 2; count++; } return count; } -BOOL RunHashTest (HashFunction fn, HashTestVector* vector, BOOL bUseSSE) +BOOL RunHashTest (HashFunction fn, HashTestVector* vector) { CRYPTOPP_ALIGN_DATA (16) unsigned char input[256]; unsigned char output[64]; unsigned char digest[64]; unsigned long i = 0, inputLen, outputLen, digestLen; BOOL bRet = TRUE; -#if defined (DEVICE_DRIVER) && !defined (_WIN64) - KFLOATING_SAVE floatingPointState; - NTSTATUS saveStatus = STATUS_INVALID_PARAMETER; - if (bUseSSE) - saveStatus = KeSaveFloatingPointState (&floatingPointState); -#endif while (vector[i].hexInput && vector[i].hexOutput) { inputLen = HexStringToByteArray (vector[i].hexInput, input); outputLen = HexStringToByteArray (vector[i].hexOutput, output); digestLen = fn (input, inputLen, digest); if ((digestLen != outputLen) || (0 != memcmp (digest, output, digestLen))) { bRet = FALSE; break; } i++; } -#if defined (DEVICE_DRIVER) && !defined (_WIN64) - if (NT_SUCCESS (saveStatus)) - KeRestoreFloatingPointState (&floatingPointState); -#endif - return bRet; } /* https://www.streebog.net/src/trunk/examples/ */ HashTestVector Streebog512TestVectors[] = { /* M1 */ {"303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132", "1b54d01a4af5b9d5cc3d86d68d285462b19abc2475222f35c085122be4ba1ffa00ad30f8767b3a82384c6574f024c311e2a481332b08ef7f41797891c1646f48" }, /* M2 */ {"d1e520e2e5f2f0e82c20d1f2f0e8e1eee6e820e2edf3f6e82c20e2e5fef2fa20f120eceef0ff20f1f2f0e5ebe0ece820ede020f5f0e0e1f0fbff20efebfaeafb20c8e3eef0e5e2fb", "1e88e62226bfca6f9994f1f2d51569e0daf8475a3b0fe61a5300eee46d961376035fe83549ada2b8620fcd7c496ce5b33f0cb9dddc2b6460143b03dabac9fb28" }, /* M3 */ {"", "8e945da209aa869f0455928529bcae4679e9873ab707b55315f56ceb98bef0a7362f715528356ee83cda5f2aac4c6ad2ba3a715c1bcd81cb8e9f90bf4c1c1a8a" }, /* M4 */ {"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "b0fd29ac1b0df441769ff3fdb8dc564df67721d6ac06fb28ceffb7bbaa7948c6c014ac999235b58cb26fb60fb112a145d7b4ade9ae566bf2611402c552d20db7" }, {NULL, NULL} }; /* https://github.com/openssl/openssl/blob/2d0b44126763f989a4cbffbffe9d0c7518158bb7/test/evptests.txt */ HashTestVector Blake2sTestVectors[] = { {"", "69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9" }, {"61", "4a0d129873403037c2cd9b9048203687f6233fb6738956e0349bd4320fec3e90" }, {"616263", "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982" }, {"6d65737361676520646967657374", "fa10ab775acf89b7d3c8a6e823d586f6b67bdbac4ce207fe145b7d3ac25cd28c" }, {"6162636465666768696a6b6c6d6e6f707172737475767778797a", "bdf88eb1f86a0cdf0e840ba88fa118508369df186c7355b4b16cf79fa2710a12" }, {"4142434445464748494a4b4c4d4e4f505152535455565758595a6162636465666768696a6b6c6d6e6f707172737475767778797a30313233343536373839", "c75439ea17e1de6fa4510c335dc3d3f343e6f9e1ce2773e25b4174f1df8b119b" }, {"3132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930", "fdaedb290a0d5af9870864fec2e090200989dc9cd53a3c092129e8535e8b4f66" }, {NULL, NULL} }; unsigned char ks_tmp[MAX_EXPANDED_KEY]; -void CipherInit2(int cipher, void* key, void* ks, int key_len) +void CipherInit2(int cipher, void* key, void* ks) { switch (cipher) { case AES: CipherInit(cipher,key,ks); break; case SERPENT: CipherInit(cipher,key,ks); break; case TWOFISH: CipherInit(cipher,key,ks); break; case CAMELLIA: CipherInit(cipher,key,ks); break; case KUZNYECHIK: CipherInit(cipher, key, ks); break; default: /* Unknown/wrong ID */ TC_THROW_FATAL_EXCEPTION; } } BOOL TestSectorBufEncryption (PCRYPTO_INFO ci) @@ -1280,96 +1269,95 @@ BOOL TestSectorBufEncryption (PCRYPTO_INFO ci) } else if (wcscmp (name, L"Kuznyechik-AES") == 0) { if (crc != 0x4641234a) return FALSE; nTestsPerformed++; } else if (wcscmp (name, L"Kuznyechik-Serpent-Camellia") == 0) { if (crc != 0x755dad72) return FALSE; nTestsPerformed++; } #endif if (crc == 0x9f5edd58) return FALSE; DecryptBuffer (buf, sizeof (buf), ci); if (GetCrc32 (buf, sizeof (buf)) != 0x9f5edd58) return FALSE; nTestsPerformed++; } return (nTestsPerformed == 150); } static BOOL DoAutoTestAlgorithms (void) { PCRYPTO_INFO ci; - CRYPTOPP_ALIGN_DATA(16) char key[32]; + CRYPTOPP_ALIGN_DATA(16) unsigned char key[32]; unsigned char tmp[16]; BOOL bFailed = FALSE; int i; ci = crypto_open (); if (!ci) return FALSE; memset (ci, 0, sizeof (*ci)); /* AES */ for (i = 0; i < AES_TEST_COUNT; i++) { int cipher = AES; memcpy(key, aes_ecb_vectors[i].key, 32); memcpy(tmp, aes_ecb_vectors[i].plaintext, 16); CipherInit(cipher, key, ks_tmp); EncipherBlock(cipher, tmp, ks_tmp); if (memcmp(aes_ecb_vectors[i].ciphertext, tmp, 16) != 0) break; DecipherBlock(cipher, tmp, ks_tmp); if (memcmp(aes_ecb_vectors[i].plaintext, tmp, 16) != 0) break; } if (i != AES_TEST_COUNT) bFailed = TRUE; // AES EncipherBlocks()/DecipherBlocks() { uint8 testData[1024]; uint32 origCrc; - size_t i; for (i = 0; i < sizeof (testData); ++i) { testData[i] = (uint8) i; } origCrc = GetCrc32 (testData, sizeof (testData)); CipherInit (AES, testData, ks_tmp); EncipherBlocks (AES, testData, ks_tmp, sizeof (testData) / CipherGetBlockSize (AES)); if (GetCrc32 (testData, sizeof (testData)) != 0xb5cd5631) bFailed = TRUE; DecipherBlocks (AES, testData, ks_tmp, sizeof (testData) / CipherGetBlockSize (AES)); if (origCrc != GetCrc32 (testData, sizeof (testData))) bFailed = TRUE; } #ifndef WOLFCRYPT_BACKEND /* Serpent */ for (i = 0; i < SERPENT_TEST_COUNT; i++) { int cipher = SERPENT; memcpy(key, serpent_vectors[i].key, 32); memcpy(tmp, serpent_vectors[i].plaintext, 16); CipherInit(cipher, key, ks_tmp); @@ -1499,267 +1487,267 @@ BOOL AutoTestAlgorithms (void) { exceptionCatched = TRUE; } if (exceptionCatched) { /* unexepected exception raised. Disable all CPU extended feature and try again */ EnableHwEncryption (hwEncryptionEnabled); DisableCPUExtendedFeatures (); __try { result = DoAutoTestAlgorithms(); } __except (EXCEPTION_EXECUTE_HANDLER) { /* exception still occuring. Report failure. */ result = FALSE; } } #endif return result; } BOOL test_hmac_sha256 () { unsigned int i; int nTestsPerformed = 0; for (i = 0; i < sizeof (hmac_sha256_test_data) / sizeof(char *); i++) { - char digest[1024]; /* large enough to hold digets and test vector inputs */ + unsigned char digest[1024]; /* large enough to hold digets and test vector inputs */ size_t dataLen = strlen (hmac_sha256_test_data[i]); if (dataLen <= sizeof(digest)) { memcpy (digest, hmac_sha256_test_data[i], dataLen); - hmac_sha256 (hmac_sha256_test_keys[i], (int) strlen (hmac_sha256_test_keys[i]), digest, (int) dataLen); + hmac_sha256 ((unsigned char*) hmac_sha256_test_keys[i], (int) strlen (hmac_sha256_test_keys[i]), digest, (int) dataLen); if (memcmp (digest, hmac_sha256_test_vectors[i], SHA256_DIGESTSIZE) != 0) return FALSE; else nTestsPerformed++; } else { return FALSE; } } return (nTestsPerformed == 6); } BOOL test_hmac_sha512 () { unsigned int i; int nTestsPerformed = 0; for (i = 0; i < sizeof (hmac_sha512_test_data) / sizeof(char *); i++) { - char digest[1024]; /* large enough to hold digets and test vector inputs */ + unsigned char digest[1024]; /* large enough to hold digets and test vector inputs */ size_t dataLen = strlen (hmac_sha512_test_data[i]); if (dataLen <= sizeof(digest)) { memcpy (digest, hmac_sha512_test_data[i], dataLen ); - hmac_sha512 (hmac_sha512_test_keys[i], (int) strlen (hmac_sha512_test_keys[i]), digest, (int) dataLen); + hmac_sha512 ((unsigned char*) hmac_sha512_test_keys[i], (int) strlen (hmac_sha512_test_keys[i]), digest, (int) dataLen); if (memcmp (digest, hmac_sha512_test_vectors[i], SHA512_DIGESTSIZE) != 0) return FALSE; else nTestsPerformed++; } else { return FALSE; } } return (nTestsPerformed == 6); } #ifndef WOLFCRYPT_BACKEND BOOL test_hmac_blake2s () { unsigned int i; int nTestsPerformed = 0; for (i = 0; i < sizeof (hmac_blake2s_test_data) / sizeof(char *); i++) { - char digest[1024]; /* large enough to hold digets and test vector inputs */ + unsigned char digest[1024]; /* large enough to hold digets and test vector inputs */ size_t dataLen = strlen (hmac_blake2s_test_data[i]); if (dataLen <= sizeof(digest)) { memcpy (digest, hmac_blake2s_test_data[i], dataLen); - hmac_blake2s (hmac_blake2s_test_keys[i], (int) strlen (hmac_blake2s_test_keys[i]), digest, (int) dataLen); + hmac_blake2s ((unsigned char*)(unsigned char*)hmac_blake2s_test_keys[i], (int) strlen (hmac_blake2s_test_keys[i]), digest, (int) dataLen); if (memcmp (digest, hmac_blake2s_test_vectors[i], BLAKE2S_DIGESTSIZE) != 0) return FALSE; else nTestsPerformed++; } else { return FALSE; } } return (nTestsPerformed == 6); } int __cdecl Blake2sHash (unsigned char* input, unsigned long inputLen, unsigned char* output) { blake2s(output, input, (size_t) inputLen); return BLAKE2S_DIGESTSIZE; } BOOL test_hmac_whirlpool () { unsigned char digest[1024]; /* large enough to hold digets and test vector inputs */ memcpy (digest, hmac_whirlpool_test_data, strlen (hmac_whirlpool_test_data)); - hmac_whirlpool (hmac_whirlpool_test_key, 64, digest, (int) strlen (hmac_whirlpool_test_data)); + hmac_whirlpool ((unsigned char*) hmac_whirlpool_test_key, 64, digest, (int) strlen (hmac_whirlpool_test_data)); if (memcmp (digest, hmac_whirlpool_test_vectors, WHIRLPOOL_DIGESTSIZE) != 0) return FALSE; return TRUE; } #endif /* http://www.tc26.ru/methods/recommendation/%D0%A2%D0%9A26%D0%90%D0%9B%D0%93.pdf */ /* https://tools.ietf.org/html/draft-smyshlyaev-gost-usage-00 */ /* https://datatracker.ietf.org/doc/rfc7836/?include_text=1 */ static const unsigned char gost3411_2012_hmac_k1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; static const unsigned char gost3411_2012_hmac_m1[] = { 0x01, 0x26, 0xbd, 0xb8, 0x78, 0x00, 0xaf, 0x21, 0x43, 0x41, 0x45, 0x65, 0x63, 0x78, 0x01, 0x00 }; static const unsigned char gost3411_2012_hmac_r1[] = { 0xA5, 0x9B, 0xAB, 0x22, 0xEC, 0xAE, 0x19, 0xC6, 0x5F, 0xBD, 0xE6, 0xE5, 0xF4, 0xE9, 0xF5, 0xD8, 0x54, 0x9D, 0x31, 0xF0, 0x37, 0xF9, 0xDF, 0x9B, 0x90, 0x55, 0x00, 0xE1, 0x71, 0x92, 0x3A, 0x77, 0x3D, 0x5F, 0x15, 0x30, 0xF2, 0xED, 0x7E, 0x96, 0x4C, 0xB2, 0xEE, 0xDC, 0x29, 0xE9, 0xAD, 0x2F, 0x3A, 0xFE, 0x93, 0xB2, 0x81, 0x4F, 0x79, 0xF5, 0x00, 0x0F, 0xFC, 0x03, 0x66, 0xC2, 0x51, 0xE6 }; #ifndef WOLFCRYPT_BACKEND BOOL test_hmac_streebog () { - CRYPTOPP_ALIGN_DATA(16) char digest[64]; /* large enough to hold digets and test vector inputs */ + CRYPTOPP_ALIGN_DATA(16) unsigned char digest[64]; /* large enough to hold digets and test vector inputs */ memcpy (digest, gost3411_2012_hmac_m1, sizeof (gost3411_2012_hmac_m1)); - hmac_streebog ((char*) gost3411_2012_hmac_k1, sizeof(gost3411_2012_hmac_k1), digest, (int) sizeof (gost3411_2012_hmac_m1)); + hmac_streebog ((unsigned char*) gost3411_2012_hmac_k1, sizeof(gost3411_2012_hmac_k1), digest, (int) sizeof (gost3411_2012_hmac_m1)); if (memcmp (digest, gost3411_2012_hmac_r1, STREEBOG_DIGESTSIZE) != 0) return FALSE; return TRUE; } int __cdecl StreebogHash (unsigned char* input, unsigned long inputLen, unsigned char* output) { STREEBOG_CTX ctx; STREEBOG_init (&ctx); STREEBOG_add (&ctx, input, inputLen); STREEBOG_finalize (&ctx, output); return STREEBOG_DIGESTSIZE; } #endif BOOL test_pkcs5 () { - char dk[144]; + unsigned char dk[144]; /* HMAC-SHA-256 tests */ if (!test_hmac_sha256()) return FALSE; /* HMAC-SHA-512 tests */ if (!test_hmac_sha512()) return FALSE; #ifndef WOLFCRYPT_BACKEND /* HMAC-BLAKE2s tests */ if (test_hmac_blake2s() == FALSE) return FALSE; /* Blake2s hash tests */ - if (RunHashTest (Blake2sHash, Blake2sTestVectors, (HasSSE2())? TRUE : FALSE) == FALSE) + if (RunHashTest (Blake2sHash, Blake2sTestVectors)) return FALSE; /* HMAC-Whirlpool tests */ if (test_hmac_whirlpool() == FALSE) return FALSE; /* HMAC-STREEBOG tests */ if (test_hmac_streebog() == FALSE) return FALSE; /* STREEBOG hash tests */ - if (RunHashTest (StreebogHash, Streebog512TestVectors, (HasSSE2() || HasSSE41())? TRUE : FALSE) == FALSE) + if (RunHashTest (StreebogHash, Streebog512TestVectors)) return FALSE; #endif /* PKCS-5 test 1 with HMAC-SHA-256 used as the PRF (https://tools.ietf.org/html/draft-josefsson-scrypt-kdf-00) */ - derive_key_sha256 ("passwd", 6, "\x73\x61\x6C\x74", 4, 1, dk, 64); + derive_key_sha256 ((unsigned char*) "passwd", 6, (unsigned char*) "\x73\x61\x6C\x74", 4, 1, dk, 64); if (memcmp (dk, "\x55\xac\x04\x6e\x56\xe3\x08\x9f\xec\x16\x91\xc2\x25\x44\xb6\x05\xf9\x41\x85\x21\x6d\xde\x04\x65\xe6\x8b\x9d\x57\xc2\x0d\xac\xbc\x49\xca\x9c\xcc\xf1\x79\xb6\x45\x99\x16\x64\xb3\x9d\x77\xef\x31\x7c\x71\xb8\x45\xb1\xe3\x0b\xd5\x09\x11\x20\x41\xd3\xa1\x97\x83", 64) != 0) return FALSE; /* PKCS-5 test 2 with HMAC-SHA-256 used as the PRF (https://stackoverflow.com/questions/5130513/pbkdf2-hmac-sha2-test-vectors) */ - derive_key_sha256 ("password", 8, "\x73\x61\x6C\x74", 4, 2, dk, 32); + derive_key_sha256 ((unsigned char*) "password", 8, (unsigned char*) "\x73\x61\x6C\x74", 4, 2, dk, 32); if (memcmp (dk, "\xae\x4d\x0c\x95\xaf\x6b\x46\xd3\x2d\x0a\xdf\xf9\x28\xf0\x6d\xd0\x2a\x30\x3f\x8e\xf3\xc2\x51\xdf\xd6\xe2\xd8\x5a\x95\x47\x4c\x43", 32) != 0) return FALSE; /* PKCS-5 test 3 with HMAC-SHA-256 used as the PRF (MS CryptoAPI) */ - derive_key_sha256 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); + derive_key_sha256 ((unsigned char*)"password", 8, (unsigned char*)"\x12\x34\x56\x78", 4, 5, dk, 4); if (memcmp (dk, "\xf2\xa0\x4f\xb2", 4) != 0) return FALSE; /* PKCS-5 test 4 with HMAC-SHA-256 used as the PRF (MS CryptoAPI) */ - derive_key_sha256 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 144); + derive_key_sha256 ((unsigned char*)"password", 8, (unsigned char*)"\x12\x34\x56\x78", 4, 5, dk, 144); if (memcmp (dk, "\xf2\xa0\x4f\xb2\xd3\xe9\xa5\xd8\x51\x0b\x5c\x06\xdf\x70\x8e\x24\xe9\xc7\xd9\x15\x3d\x22\xcd\xde\xb8\xa6\xdb\xfd\x71\x85\xc6\x99\x32\xc0\xee\x37\x27\xf7\x24\xcf\xea\xa6\xac\x73\xa1\x4c\x4e\x52\x9b\x94\xf3\x54\x06\xfc\x04\x65\xa1\x0a\x24\xfe\xf0\x98\x1d\xa6\x22\x28\xeb\x24\x55\x74\xce\x6a\x3a\x28\xe2\x04\x3a\x59\x13\xec\x3f\xf2\xdb\xcf\x58\xdd\x53\xd9\xf9\x17\xf6\xda\x74\x06\x3c\x0b\x66\xf5\x0f\xf5\x58\xa3\x27\x52\x8c\x5b\x07\x91\xd0\x81\xeb\xb6\xbc\x30\x69\x42\x71\xf2\xd7\x18\x42\xbe\xe8\x02\x93\x70\x66\xad\x35\x65\xbc\xf7\x96\x8e\x64\xf1\xc6\x92\xda\xe0\xdc\x1f\xb5\xf4", 144) != 0) return FALSE; /* PKCS-5 test 1 with HMAC-SHA-512 used as the PRF */ - derive_key_sha512 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); + derive_key_sha512 ((unsigned char*)"password", 8, (unsigned char*)"\x12\x34\x56\x78", 4, 5, dk, 4); if (memcmp (dk, "\x13\x64\xae\xf8", 4) != 0) return FALSE; /* PKCS-5 test 2 with HMAC-SHA-512 used as the PRF (derives a key longer than the underlying hash output size and block size) */ - derive_key_sha512 ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 144); + derive_key_sha512 ((unsigned char*)"password", 8, (unsigned char*)"\x12\x34\x56\x78", 4, 5, dk, 144); if (memcmp (dk, "\x13\x64\xae\xf8\x0d\xf5\x57\x6c\x30\xd5\x71\x4c\xa7\x75\x3f\xfd\x00\xe5\x25\x8b\x39\xc7\x44\x7f\xce\x23\x3d\x08\x75\xe0\x2f\x48\xd6\x30\xd7\x00\xb6\x24\xdb\xe0\x5a\xd7\x47\xef\x52\xca\xa6\x34\x83\x47\xe5\xcb\xe9\x87\xf1\x20\x59\x6a\xe6\xa9\xcf\x51\x78\xc6\xb6\x23\xa6\x74\x0d\xe8\x91\xbe\x1a\xd0\x28\xcc\xce\x16\x98\x9a\xbe\xfb\xdc\x78\xc9\xe1\x7d\x72\x67\xce\xe1\x61\x56\x5f\x96\x68\xe6\xe1\xdd\xf4\xbf\x1b\x80\xe0\x19\x1c\xf4\xc4\xd3\xdd\xd5\xd5\x57\x2d\x83\xc7\xa3\x37\x87\xf4\x4e\xe0\xf6\xd8\x6d\x65\xdc\xa0\x52\xa3\x13\xbe\x81\xfc\x30\xbe\x7d\x69\x58\x34\xb6\xdd\x41\xc6", 144) != 0) return FALSE; #ifndef WOLFCRYPT_BACKEND /* PKCS-5 test 1 with HMAC-BLAKE2s used as the PRF */ - derive_key_blake2s ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); + derive_key_blake2s ((unsigned char*)"password", 8, (unsigned char*)"\x12\x34\x56\x78", 4, 5, dk, 4); if (memcmp (dk, "\x8d\x51\xfa\x31", 4) != 0) return FALSE; /* PKCS-5 test 2 with HMAC-BLAKE2s used as the PRF (derives a key longer than the underlying hash) */ - derive_key_blake2s ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 48); + derive_key_blake2s ((unsigned char*)"password", 8, (unsigned char*)"\x12\x34\x56\x78", 4, 5, dk, 48); if (memcmp (dk, "\x8d\x51\xfa\x31\x46\x25\x37\x67\xa3\x29\x6b\x3c\x6b\xc1\x5d\xb2\xee\xe1\x6c\x28\x00\x26\xea\x08\x65\x9c\x12\xf1\x07\xde\x0d\xb9\x9b\x4f\x39\xfa\xc6\x80\x26\xb1\x8f\x8e\x48\x89\x85\x2d\x24\x2d", 48) != 0) return FALSE; /* PKCS-5 test 1 with HMAC-Whirlpool used as the PRF */ - derive_key_whirlpool ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); + derive_key_whirlpool ((unsigned char*)"password", 8, (unsigned char*)"\x12\x34\x56\x78", 4, 5, dk, 4); if (memcmp (dk, "\x50\x7c\x36\x6f", 4) != 0) return FALSE; /* PKCS-5 test 2 with HMAC-Whirlpool used as the PRF (derives a key longer than the underlying hash) */ - derive_key_whirlpool ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 96); + derive_key_whirlpool ((unsigned char*)"password", 8, (unsigned char*)"\x12\x34\x56\x78", 4, 5, dk, 96); if (memcmp (dk, "\x50\x7c\x36\x6f\xee\x10\x2e\x9a\xe2\x8a\xd5\x82\x72\x7d\x27\x0f\xe8\x4d\x7f\x68\x7a\xcf\xb5\xe7\x43\x67\xaa\x98\x93\x52\x2b\x09\x6e\x42\xdf\x2c\x59\x4a\x91\x6d\x7e\x10\xae\xb2\x1a\x89\x8f\xb9\x8f\xe6\x31\xa9\xd8\x9f\x98\x26\xf4\xda\xcd\x7d\x65\x65\xde\x10\x95\x91\xb4\x84\x26\xae\x43\xa1\x00\x5b\x1e\xb8\x38\x97\xa4\x1e\x4b\xd2\x65\x64\xbc\xfa\x1f\x35\x85\xdb\x4f\x97\x65\x6f\xbd\x24", 96) != 0) return FALSE; /* PKCS-5 test 1 with HMAC-STREEBOG used as the PRF */ - derive_key_streebog ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 4); + derive_key_streebog ((unsigned char*)"password", 8, (unsigned char*)"\x12\x34\x56\x78", 4, 5, dk, 4); if (memcmp (dk, "\xd0\x53\xa2\x30", 4) != 0) return FALSE; /* PKCS-5 test 2 with HMAC-STREEBOG used as the PRF (derives a key longer than the underlying hash) */ - derive_key_streebog ("password", 8, "\x12\x34\x56\x78", 4, 5, dk, 96); + derive_key_streebog ((unsigned char*)"password", 8, (unsigned char*)"\x12\x34\x56\x78", 4, 5, dk, 96); if (memcmp (dk, "\xd0\x53\xa2\x30\x6f\x45\x81\xeb\xbc\x06\x81\xc5\xe7\x53\xa8\x5d\xc7\xf1\x23\x33\x1e\xbe\x64\x2c\x3b\x0f\x26\xd7\x00\xe1\x95\xc9\x65\x26\xb1\x85\xbe\x1e\xe2\xf4\x9b\xfc\x6b\x14\x84\xda\x24\x61\xa0\x1b\x9e\x79\x5c\xee\x69\x6e\xf9\x25\xb1\x1d\xca\xa0\x31\xba\x02\x6f\x9e\x99\x0f\xdb\x25\x01\x5b\xf1\xc7\x10\x19\x53\x3b\x29\x3f\x18\x00\xd6\xfc\x85\x03\xdc\xf2\xe5\xe9\x5a\xb1\x1e\x61\xde", 96) != 0) return FALSE; #endif return TRUE; } diff --git a/src/Common/Tests.h b/src/Common/Tests.h index 356d54f4..bfdf7c40 100644 --- a/src/Common/Tests.h +++ b/src/Common/Tests.h @@ -1,31 +1,31 @@ /* Legal Notice: Some portions of the source code contained in this file were derived from the source code of TrueCrypt 7.1a, which is Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux and which is governed by the 'License Agreement for Encryption for the Masses' Modifications and additions to the original source code (contained in this file) and all other portions of this file are Copyright (c) 2013-2017 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #ifdef __cplusplus extern "C" { #endif extern unsigned char ks_tmp[MAX_EXPANDED_KEY]; -void CipherInit2(int cipher, void* key, void* ks, int key_len); +void CipherInit2(int cipher, void* key, void* ks); BOOL test_hmac_sha512 (void); BOOL test_hmac_blake2s (void); BOOL test_hmac_whirlpool (void); BOOL test_pkcs5 (void); BOOL TestSectorBufEncryption (); BOOL TestLegacySectorBufEncryption (); BOOL AutoTestAlgorithms (void); #ifdef __cplusplus } #endif diff --git a/src/Common/Volumes.c b/src/Common/Volumes.c index 7ee519f6..3a836787 100644 --- a/src/Common/Volumes.c +++ b/src/Common/Volumes.c @@ -133,78 +133,78 @@ uint16 GetHeaderField16 (uint8 *header, int offset) { return BE16 (*(uint16 *) (header + offset)); } uint32 GetHeaderField32 (uint8 *header, int offset) { return BE32 (*(uint32 *) (header + offset)); } UINT64_STRUCT GetHeaderField64 (uint8 *header, int offset) { UINT64_STRUCT uint64Struct; #ifndef TC_NO_COMPILER_INT64 uint64Struct.Value = BE64 (*(uint64 *) (header + offset)); #else uint64Struct.HighPart = BE32 (*(uint32 *) (header + offset)); uint64Struct.LowPart = BE32 (*(uint32 *) (header + offset + 4)); #endif return uint64Struct; } #ifndef TC_WINDOWS_BOOT typedef struct { - char DerivedKey[MASTER_KEYDATA_SIZE]; + unsigned char DerivedKey[MASTER_KEYDATA_SIZE]; BOOL Free; LONG KeyReady; int Pkcs5Prf; } KeyDerivationWorkItem; BOOL ReadVolumeHeaderRecoveryMode = FALSE; -int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, int selected_pkcs5_prf, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo) +int ReadVolumeHeader (BOOL bBoot, unsigned char *encryptedHeader, Password *password, int selected_pkcs5_prf, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo) { - char header[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; + unsigned char header[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; unsigned char* keyInfoBuffer = NULL; int keyInfoBufferSize = sizeof (KEY_INFO) + 16; size_t keyInfoBufferOffset; PKEY_INFO keyInfo; PCRYPTO_INFO cryptoInfo; - CRYPTOPP_ALIGN_DATA(16) char dk[MASTER_KEYDATA_SIZE]; + CRYPTOPP_ALIGN_DATA(16) unsigned char dk[MASTER_KEYDATA_SIZE]; int enqPkcs5Prf, pkcs5_prf; uint16 headerVersion; int status = ERR_PARAMETER_INCORRECT; int primaryKeyOffset; int pkcs5PrfCount = LAST_PRF_ID - FIRST_PRF_ID + 1; #if !defined(_UEFI) TC_EVENT *keyDerivationCompletedEvent = NULL; TC_EVENT *noOutstandingWorkItemEvent = NULL; KeyDerivationWorkItem *keyDerivationWorkItems = NULL; int keyDerivationWorkItemsSize = 0; KeyDerivationWorkItem *item; size_t encryptionThreadCount = GetEncryptionThreadCount(); LONG *outstandingWorkItemCount = NULL; int i; #endif size_t queuedWorkItems = 0; // allocate 16-bytes aligned buffer to hold KEY_INFO in a portable way keyInfoBuffer = TCalloc(keyInfoBufferSize); if (!keyInfoBuffer) return ERR_OUTOFMEMORY; keyInfoBufferOffset = 16 - (((uint64) keyInfoBuffer) % 16); keyInfo = (PKEY_INFO) (keyInfoBuffer + keyInfoBufferOffset); #if !defined(DEVICE_DRIVER) && !defined(_UEFI) VirtualLock (keyInfoBuffer, keyInfoBufferSize); #endif // if no PIM specified, use default value if (pim < 0) @@ -677,66 +677,66 @@ void ComputeBootloaderFingerprint (uint8 *bootLoaderBuf, unsigned int bootLoader WHIRLPOOL_add (bootLoaderBuf + TC_SECTOR_SIZE_BIOS, (bootLoaderSize - TC_SECTOR_SIZE_BIOS), &whirlpool); sha512_hash (bootLoaderBuf + TC_SECTOR_SIZE_BIOS, (bootLoaderSize - TC_SECTOR_SIZE_BIOS), &sha2); WHIRLPOOL_finalize (&whirlpool, fingerprint); sha512_end (&fingerprint [WHIRLPOOL_DIGESTSIZE], &sha2); #else sha512_ctx sha2_512; sha256_ctx sha2_256; sha512_begin (&sha2_512); sha256_begin (&sha2_256); sha512_hash (bootLoaderBuf, TC_BOOT_SECTOR_PIM_VALUE_OFFSET, &sha2_512); sha256_hash (bootLoaderBuf, TC_BOOT_SECTOR_PIM_VALUE_OFFSET, &sha2_256); sha512_hash (bootLoaderBuf + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH, (TC_BOOT_SECTOR_USER_CONFIG_OFFSET - (TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH)), &sha2_512); sha256_hash (bootLoaderBuf + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH, (TC_BOOT_SECTOR_USER_CONFIG_OFFSET - (TC_BOOT_SECTOR_USER_MESSAGE_OFFSET + TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH)), &sha2_256); sha512_hash (bootLoaderBuf + TC_SECTOR_SIZE_BIOS, (bootLoaderSize - TC_SECTOR_SIZE_BIOS), &sha2_512); sha256_hash (bootLoaderBuf + TC_SECTOR_SIZE_BIOS, (bootLoaderSize - TC_SECTOR_SIZE_BIOS), &sha2_256); sha512_end (&fingerprint, &sha2_512); sha256_end (&fingerprint [SHA512_DIGESTSIZE], &sha2_256); sha256_end (&fingerprint [SHA512_DIGESTSIZE + SHA256_DIGESTSIZE], &sha2_256); #endif } #endif #else // TC_WINDOWS_BOOT -int ReadVolumeHeader (BOOL bBoot, char *header, Password *password, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo) +int ReadVolumeHeader (BOOL bBoot, unsigned char *header, Password *password, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo) { #ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE - char dk[32 * 2]; // 2 * 256-bit key + unsigned char dk[32 * 2]; // 2 * 256-bit key #else - char dk[32 * 2 * 3]; // 6 * 256-bit key + unsigned char dk[32 * 2 * 3]; // 6 * 256-bit key #endif PCRYPTO_INFO cryptoInfo; int status = ERR_SUCCESS; uint32 iterations = pim; iterations <<= 16; iterations |= bBoot; if (retHeaderCryptoInfo != NULL) cryptoInfo = retHeaderCryptoInfo; else cryptoInfo = *retInfo = crypto_open (); // PKCS5 PRF #ifdef TC_WINDOWS_BOOT_SHA2 derive_key_sha256 (password->Text, (int) password->Length, header + HEADER_SALT_OFFSET, PKCS5_SALT_SIZE, iterations, dk, sizeof (dk)); #else derive_key_blake2s (password->Text, (int) password->Length, header + HEADER_SALT_OFFSET, PKCS5_SALT_SIZE, iterations, dk, sizeof (dk)); #endif // Mode of operation cryptoInfo->mode = FIRST_MODE_OF_OPERATION_ID; #ifdef TC_WINDOWS_BOOT_SINGLE_CIPHER_MODE cryptoInfo->ea = 1; #else // Test all available encryption algorithms for (cryptoInfo->ea = EAGetFirst (); cryptoInfo->ea != 0; cryptoInfo->ea = EAGetNext (cryptoInfo->ea)) @@ -855,72 +855,72 @@ int ReadVolumeHeader (BOOL bBoot, char *header, Password *password, int pim, PCR #endif goto ret; } status = ERR_PASSWORD_WRONG; err: if (cryptoInfo != retHeaderCryptoInfo) { crypto_close(cryptoInfo); *retInfo = NULL; } ret: burn (dk, sizeof(dk)); return status; } #endif // TC_WINDOWS_BOOT #if !defined (DEVICE_DRIVER) && !defined (TC_WINDOWS_BOOT) #ifdef VOLFORMAT # include "../Format/TcFormat.h" # include "Dlgcode.h" #endif // Creates a volume header in memory #if defined(_UEFI) -int CreateVolumeHeaderInMemory(BOOL bBoot, char *header, int ea, int mode, Password *password, +int CreateVolumeHeaderInMemory(BOOL bBoot, unsigned char *header, int ea, int mode, Password *password, int pkcs5_prf, int pim, char *masterKeydata, PCRYPTO_INFO *retInfo, unsigned __int64 volumeSize, unsigned __int64 hiddenVolumeSize, unsigned __int64 encryptedAreaStart, unsigned __int64 encryptedAreaLength, uint16 requiredProgramVersion, uint32 headerFlags, uint32 sectorSize, BOOL bWipeMode) #else -int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, char *header, int ea, int mode, Password *password, +int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, unsigned char *header, int ea, int mode, Password *password, int pkcs5_prf, int pim, char *masterKeydata, PCRYPTO_INFO *retInfo, unsigned __int64 volumeSize, unsigned __int64 hiddenVolumeSize, unsigned __int64 encryptedAreaStart, unsigned __int64 encryptedAreaLength, uint16 requiredProgramVersion, uint32 headerFlags, uint32 sectorSize, BOOL bWipeMode) #endif // !defined(_UEFI) { - unsigned char *p = (unsigned char *) header; + unsigned char *p = header; static CRYPTOPP_ALIGN_DATA(16) KEY_INFO keyInfo; int nUserKeyLen = password? password->Length : 0; PCRYPTO_INFO cryptoInfo = crypto_open (); static char dk[MASTER_KEYDATA_SIZE]; int x; int retVal = 0; int primaryKeyOffset; if (cryptoInfo == NULL) return ERR_OUTOFMEMORY; // if no PIM specified, use default value if (pim < 0) pim = 0; memset (header, 0, TC_VOLUME_HEADER_EFFECTIVE_SIZE); #if !defined(_UEFI) VirtualLock (&keyInfo, sizeof (keyInfo)); VirtualLock (&dk, sizeof (dk)); #endif // !defined(_UEFI) /* Encryption setup */ if (masterKeydata == NULL) { // We have no master key data (creating a new volume) so we'll use the TrueCrypt RNG to generate them int bytesNeeded; diff --git a/src/Common/Volumes.h b/src/Common/Volumes.h index daad25e3..07ed0fe8 100644 --- a/src/Common/Volumes.h +++ b/src/Common/Volumes.h @@ -106,56 +106,56 @@ extern "C" { #define TC_HEADER_OFFSET_MAGIC 64 #define TC_HEADER_OFFSET_VERSION 68 #define TC_HEADER_OFFSET_REQUIRED_VERSION 70 #define TC_HEADER_OFFSET_KEY_AREA_CRC 72 #define TC_HEADER_OFFSET_VOLUME_CREATION_TIME 76 #define TC_HEADER_OFFSET_MODIFICATION_TIME 84 #define TC_HEADER_OFFSET_HIDDEN_VOLUME_SIZE 92 #define TC_HEADER_OFFSET_VOLUME_SIZE 100 #define TC_HEADER_OFFSET_ENCRYPTED_AREA_START 108 #define TC_HEADER_OFFSET_ENCRYPTED_AREA_LENGTH 116 #define TC_HEADER_OFFSET_FLAGS 124 #define TC_HEADER_OFFSET_SECTOR_SIZE 128 #define TC_HEADER_OFFSET_HEADER_CRC 252 // Volume header flags #define TC_HEADER_FLAG_ENCRYPTED_SYSTEM 0x1 #define TC_HEADER_FLAG_NONSYS_INPLACE_ENC 0x2 // The volume has been created (or is being encrypted/decrypted) using non-system in-place encryption #ifndef TC_HEADER_Volume_VolumeHeader #include "Password.h" extern BOOL ReadVolumeHeaderRecoveryMode; uint16 GetHeaderField16 (uint8 *header, int offset); uint32 GetHeaderField32 (uint8 *header, int offset); UINT64_STRUCT GetHeaderField64 (uint8 *header, int offset); #if defined(TC_WINDOWS_BOOT) -int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo); +int ReadVolumeHeader (BOOL bBoot, unsigned char *encryptedHeader, Password *password, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo); #elif defined(_UEFI) -int ReadVolumeHeader(BOOL bBoot, char *encryptedHeader, Password *password, int pkcs5_prf, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo); -int CreateVolumeHeaderInMemory(BOOL bBoot, char *encryptedHeader, int ea, int mode, Password *password, int pkcs5_prf, int pim, char *masterKeydata, PCRYPTO_INFO *retInfo, unsigned __int64 volumeSize, unsigned __int64 hiddenVolumeSize, unsigned __int64 encryptedAreaStart, unsigned __int64 encryptedAreaLength, uint16 requiredProgramVersion, uint32 headerFlags, uint32 sectorSize, BOOL bWipeMode); +int ReadVolumeHeader(BOOL bBoot, unsigned char *encryptedHeader, Password *password, int pkcs5_prf, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo); +int CreateVolumeHeaderInMemory(BOOL bBoot, unsigned char *encryptedHeader, int ea, int mode, Password *password, int pkcs5_prf, int pim, char *masterKeydata, PCRYPTO_INFO *retInfo, unsigned __int64 volumeSize, unsigned __int64 hiddenVolumeSize, unsigned __int64 encryptedAreaStart, unsigned __int64 encryptedAreaLength, uint16 requiredProgramVersion, uint32 headerFlags, uint32 sectorSize, BOOL bWipeMode); BOOL RandgetBytes(unsigned char *buf, int len, BOOL forceSlowPoll); #else -int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, int pkcs5_prf, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo); +int ReadVolumeHeader (BOOL bBoot, unsigned char *encryptedHeader, Password *password, int pkcs5_prf, int pim, PCRYPTO_INFO *retInfo, CRYPTO_INFO *retHeaderCryptoInfo); #if defined(_WIN32) && !defined(_UEFI) void ComputeBootloaderFingerprint (uint8 *bootLoaderBuf, unsigned int bootLoaderSize, uint8* fingerprint); #endif #endif #if !defined (DEVICE_DRIVER) && !defined (TC_WINDOWS_BOOT) && !defined(_UEFI) -int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, char *encryptedHeader, int ea, int mode, Password *password, int pkcs5_prf, int pim, char *masterKeydata, PCRYPTO_INFO *retInfo, unsigned __int64 volumeSize, unsigned __int64 hiddenVolumeSize, unsigned __int64 encryptedAreaStart, unsigned __int64 encryptedAreaLength, uint16 requiredProgramVersion, uint32 headerFlags, uint32 sectorSize, BOOL bWipeMode); +int CreateVolumeHeaderInMemory (HWND hwndDlg, BOOL bBoot, unsigned char *encryptedHeader, int ea, int mode, Password *password, int pkcs5_prf, int pim, char *masterKeydata, PCRYPTO_INFO *retInfo, unsigned __int64 volumeSize, unsigned __int64 hiddenVolumeSize, unsigned __int64 encryptedAreaStart, unsigned __int64 encryptedAreaLength, uint16 requiredProgramVersion, uint32 headerFlags, uint32 sectorSize, BOOL bWipeMode); BOOL ReadEffectiveVolumeHeader (BOOL device, HANDLE fileHandle, uint8 *header, DWORD *bytesRead); BOOL WriteEffectiveVolumeHeader (BOOL device, HANDLE fileHandle, uint8 *header); int WriteRandomDataToReservedHeaderAreas (HWND hwndDlg, HANDLE dev, CRYPTO_INFO *cryptoInfo, uint64 dataAreaSize, BOOL bPrimaryOnly, BOOL bBackupOnly); #endif #endif // !TC_HEADER_Volume_VolumeHeader #ifdef __cplusplus } #endif #endif // TC_HEADER_Common_Volumes diff --git a/src/Common/Wipe.c b/src/Common/Wipe.c index d68b517b..af3d15db 100644 --- a/src/Common/Wipe.c +++ b/src/Common/Wipe.c @@ -1,51 +1,46 @@ /* Derived from source code of TrueCrypt 7.1a, which is Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0. Modifications and additions to the original source code (contained in this file) and all other portions of this file are Copyright (c) 2013-2017 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #include "Tcdefs.h" #include "Wipe.h" -static BOOL Wipe1PseudoRandom (int pass, uint8 *buffer, size_t size) -{ - return FALSE; -} - // Fill buffer with wipe patterns defined in "National Industrial Security Program Operating Manual", US DoD 5220.22-M. // Return: FALSE = buffer must be filled with random data static BOOL Wipe3Dod5220 (int pass, uint8 *buffer, size_t size) { uint8 wipeChar; switch (pass) { case 1: wipeChar = 0; break; case 2: wipeChar = 0xff; break; default: return FALSE; } memset (buffer, wipeChar, size); return TRUE; } static BOOL Wipe7Dod5220 (int pass, uint8 randChars[TC_WIPE_RAND_CHAR_COUNT], uint8 *buffer, size_t size) { uint8 wipeChar; @@ -146,53 +141,53 @@ wipe3: int GetWipePassCount (WipeAlgorithmId algorithm) { switch (algorithm) { case TC_WIPE_1_RAND: return 1; case TC_WIPE_3_DOD_5220: return 3; case TC_WIPE_7_DOD_5220: return 7; case TC_WIPE_35_GUTMANN: return 35; case TC_WIPE_256: return 256; } return -1; // Prevent compiler warnings } BOOL WipeBuffer (WipeAlgorithmId algorithm, uint8 randChars[TC_WIPE_RAND_CHAR_COUNT], int pass, uint8 *buffer, size_t size) { switch (algorithm) { case TC_WIPE_1_RAND: case TC_WIPE_256: - return Wipe1PseudoRandom (pass, buffer, size); + return FALSE; // Delegate buffer filling to the caller case TC_WIPE_3_DOD_5220: return Wipe3Dod5220 (pass, buffer, size); case TC_WIPE_7_DOD_5220: return Wipe7Dod5220 (pass, randChars, buffer, size); case TC_WIPE_35_GUTMANN: return Wipe35Gutmann (pass, buffer, size); /* we will never reach here because all calls to WipeBuffer are preceeded * by a call to GetWipePassCount that already checks the same algorithm * parameters and in case of unsupported value an error is returned before * calling WipeBuffer */ /* default: TC_THROW_FATAL_EXCEPTION;*/ } return FALSE; // Prevent compiler warnings } |