VeraCrypt
aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMounir IDRASSI <mounir.idrassi@idrix.fr>2014-07-14 17:41:09 +0200
committerMounir IDRASSI <mounir.idrassi@idrix.fr>2014-11-08 23:21:27 +0100
commitc220db01281564bf5b50575ee7e24b38e45f5050 (patch)
tree5e66aa935ec029ca2bac6fa282f4c18710fc2d0d
parentc01f392a7ba1d5cdd4aa182eeb273cf41717d94f (diff)
downloadVeraCrypt-c220db01281564bf5b50575ee7e24b38e45f5050.tar.gz
VeraCrypt-c220db01281564bf5b50575ee7e24b38e45f5050.zip
Static Code Analysis : Generalize the use of Safe String functions. Add some NULL pointer checks. Avoid false-positive detection in AppendMenu (MF_SEPARATOR) calls by setting the last parameter to "" instead of NULL.
-rw-r--r--src/Common/BootEncryption.cpp32
-rw-r--r--src/Common/Cmdline.c11
-rw-r--r--src/Common/Format.c14
-rw-r--r--src/Common/Keyfiles.c109
-rw-r--r--src/Common/Language.c50
-rw-r--r--src/Common/Progress.c32
-rw-r--r--src/Common/Random.c7
-rw-r--r--src/Common/Tcdefs.h2
-rw-r--r--src/Common/Volumes.c14
-rw-r--r--src/Format/InPlace.c34
-rw-r--r--src/Format/Tcformat.c188
-rw-r--r--src/Mount/Favorites.cpp4
-rw-r--r--src/Mount/Hotkeys.c94
-rw-r--r--src/Mount/Mount.c290
-rw-r--r--src/Mount/Mount.h4
15 files changed, 490 insertions, 395 deletions
diff --git a/src/Common/BootEncryption.cpp b/src/Common/BootEncryption.cpp
index 1a467eed..0fec2878 100644
--- a/src/Common/BootEncryption.cpp
+++ b/src/Common/BootEncryption.cpp
@@ -15,40 +15,42 @@
#include <shlobj.h>
#include <atlbase.h>
#include "BootEncryption.h"
#include "Boot/Windows/BootCommon.h"
#include "Common/Resource.h"
#include "Crc.h"
#include "Crypto.h"
#include "Dlgcode.h"
#include "Endian.h"
#include "Language.h"
#include "Random.h"
#include "Registry.h"
#include "Volumes.h"
#ifdef VOLFORMAT
#include "Format/FormatCom.h"
#elif defined (TCMOUNT)
#include "Mount/MainCom.h"
#endif
+#include <Strsafe.h>
+
namespace VeraCrypt
{
#if !defined (SETUP)
class Elevator
{
public:
static void AddReference ()
{
++ReferenceCount;
}
static void CallDriver (DWORD ioctl, void *input, DWORD inputSize, void *output, DWORD outputSize)
{
Elevate();
CComBSTR inputBstr;
if (input && inputBstr.AppendBytes ((const char *) input, inputSize) != S_OK)
@@ -587,100 +589,100 @@ namespace VeraCrypt
throw_sys_if (!ChangeServiceConfig (service, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE,
startOnBoot ? SERVICE_ERROR_SEVERE : SERVICE_ERROR_NORMAL,
driverPath.empty() ? NULL : driverPath.c_str(),
startOnBoot ? "Filter" : NULL,
NULL, NULL, NULL, NULL, NULL));
// ChangeServiceConfig() rejects SERVICE_BOOT_START with ERROR_INVALID_PARAMETER
throw_sys_if (!WriteLocalMachineRegistryDword ("SYSTEM\\CurrentControlSet\\Services\\veracrypt", "Start", startType));
}
void BootEncryption::ProbeRealSystemDriveSize ()
{
if (RealSystemDriveSizeValid)
return;
GetSystemDriveConfiguration();
ProbeRealDriveSizeRequest request;
- _snwprintf (request.DeviceName, array_capacity (request.DeviceName), L"%hs", DriveConfig.DrivePartition.DevicePath.c_str());
+ StringCbPrintfW (request.DeviceName, sizeof (request.DeviceName), L"%hs", DriveConfig.DrivePartition.DevicePath.c_str());
CallDriver (TC_IOCTL_PROBE_REAL_DRIVE_SIZE, &request, sizeof (request), &request, sizeof (request));
DriveConfig.DrivePartition.Info.PartitionLength = request.RealDriveSize;
RealSystemDriveSizeValid = true;
if (request.TimeOut)
throw TimeOut (SRC_POS);
}
void BootEncryption::InvalidateCachedSysDriveProperties ()
{
DriveConfigValid = false;
RealSystemDriveSizeValid = false;
}
PartitionList BootEncryption::GetDrivePartitions (int driveNumber)
{
PartitionList partList;
for (int partNumber = 0; partNumber < 64; ++partNumber)
{
stringstream partPath;
partPath << "\\Device\\Harddisk" << driveNumber << "\\Partition" << partNumber;
DISK_PARTITION_INFO_STRUCT diskPartInfo;
- _snwprintf (diskPartInfo.deviceName, array_capacity (diskPartInfo.deviceName), L"%hs", partPath.str().c_str());
+ StringCbPrintfW (diskPartInfo.deviceName, sizeof (diskPartInfo.deviceName), L"%hs", partPath.str().c_str());
try
{
CallDriver (TC_IOCTL_GET_DRIVE_PARTITION_INFO, &diskPartInfo, sizeof (diskPartInfo), &diskPartInfo, sizeof (diskPartInfo));
}
catch (...)
{
continue;
}
Partition part;
part.DevicePath = partPath.str();
part.Number = partNumber;
part.Info = diskPartInfo.partInfo;
part.IsGPT = diskPartInfo.IsGPT;
// Mount point
wstringstream ws;
ws << partPath.str().c_str();
int driveNumber = GetDiskDeviceDriveLetter ((wchar_t *) ws.str().c_str());
if (driveNumber >= 0)
{
part.MountPoint += (char) (driveNumber + 'A');
part.MountPoint += ":";
}
// Volume ID
wchar_t volumePath[TC_MAX_PATH];
- if (ResolveSymbolicLink ((wchar_t *) ws.str().c_str(), volumePath))
+ if (ResolveSymbolicLink ((wchar_t *) ws.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);
@@ -725,42 +727,42 @@ namespace VeraCrypt
}
uint16 BootEncryption::GetInstalledBootLoaderVersion ()
{
uint16 version;
CallDriver (TC_IOCTL_GET_BOOT_LOADER_VERSION, NULL, 0, &version, sizeof (version));
return version;
}
// Note that this does not require admin rights (it just requires the driver to be running)
bool BootEncryption::IsBootLoaderOnDrive (char *devicePath)
{
try
{
OPEN_TEST_STRUCT openTestStruct;
memset (&openTestStruct, 0, sizeof (openTestStruct));
DWORD dwResult;
- strcpy ((char *) &openTestStruct.wszFileName[0], devicePath);
- ToUNICODE ((char *) &openTestStruct.wszFileName[0]);
+ StringCbCopyA ((char *) &openTestStruct.wszFileName[0], sizeof(openTestStruct.wszFileName),devicePath);
+ ToUNICODE ((char *) &openTestStruct.wszFileName[0], sizeof(openTestStruct.wszFileName));
openTestStruct.bDetectTCBootLoader = TRUE;
return (DeviceIoControl (hDriver, TC_IOCTL_OPEN_TEST,
&openTestStruct, sizeof (OPEN_TEST_STRUCT),
&openTestStruct, sizeof (OPEN_TEST_STRUCT),
&dwResult, NULL) && openTestStruct.TCBootLoaderDetected);
}
catch (...)
{
return false;
}
}
BootEncryptionStatus BootEncryption::GetStatus ()
{
/* IMPORTANT: Do NOT add any potentially time-consuming operations to this function. */
BootEncryptionStatus status;
@@ -827,41 +829,41 @@ namespace VeraCrypt
case PARTITION_HUGE:
case PARTITION_IFS:
case PARTITION_FAT32:
case PARTITION_FAT32_XINT13:
case PARTITION_XINT13:
case PARTITION_XINT13_EXTENDED:
continue;
}
if (SystemDriveContainsPartitionType ((byte) partitionType))
return true;
}
return false;
}
bool BootEncryption::SystemDriveIsDynamic ()
{
GetSystemDriveConfigurationRequest request;
- _snwprintf (request.DevicePath, array_capacity (request.DevicePath), L"%hs", GetSystemDriveConfiguration().DeviceKernelPath.c_str());
+ StringCbPrintfW (request.DevicePath, sizeof (request.DevicePath), L"%hs", GetSystemDriveConfiguration().DeviceKernelPath.c_str());
CallDriver (TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG, &request, sizeof (request), &request, sizeof (request));
return request.DriveIsDynamic ? true : false;
}
SystemDriveConfiguration BootEncryption::GetSystemDriveConfiguration ()
{
if (DriveConfigValid)
return DriveConfig;
SystemDriveConfiguration config;
string winDir = GetWindowsDirectory();
// Scan all drives
for (int driveNumber = 0; driveNumber < 32; ++driveNumber)
{
bool windowsFound = false;
bool activePartitionFound = false;
@@ -1078,41 +1080,41 @@ namespace VeraCrypt
if (size + TC_BOOT_LOADER_DECOMPRESSOR_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS <= TC_BOOT_LOADER_BACKUP_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS)
{
memcpy (buffer + TC_SECTOR_SIZE_BIOS + TC_BOOT_LOADER_BACKUP_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS,
buffer + TC_SECTOR_SIZE_BIOS, TC_BOOT_LOADER_BACKUP_SECTOR_COUNT * TC_SECTOR_SIZE_BIOS);
buffer[TC_BOOT_SECTOR_CONFIG_OFFSET] |= TC_BOOT_CFG_FLAG_BACKUP_LOADER_AVAILABLE;
}
else if (!rescueDisk && bootLoaderId != IDR_BOOT_LOADER)
{
throw ParameterIncorrect (SRC_POS);
}
}
void BootEncryption::ReadBootSectorConfig (byte *config, size_t bufLength, byte *userConfig, string *customUserMessage, uint16 *bootLoaderVersion)
{
if (config && bufLength < TC_BOOT_CFG_FLAG_AREA_SIZE)
throw ParameterIncorrect (SRC_POS);
GetSystemDriveConfigurationRequest request;
- _snwprintf (request.DevicePath, array_capacity (request.DevicePath), L"%hs", GetSystemDriveConfiguration().DeviceKernelPath.c_str());
+ StringCbPrintfW (request.DevicePath, sizeof (request.DevicePath), L"%hs", GetSystemDriveConfiguration().DeviceKernelPath.c_str());
try
{
CallDriver (TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG, &request, sizeof (request), &request, sizeof (request));
if (config)
*config = request.Configuration;
if (userConfig)
*userConfig = request.UserConfiguration;
if (customUserMessage)
{
request.CustomUserMessage[TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH] = 0;
*customUserMessage = request.CustomUserMessage;
}
if (bootLoaderVersion)
*bootLoaderVersion = request.BootLoaderVersion;
}
catch (...)
@@ -1385,63 +1387,67 @@ namespace VeraCrypt
if (FileExists (path.c_str()) && !FileExists (GetSystemLoaderBackupPath().c_str()))
throw_sys_if (rename (path.c_str(), GetSystemLoaderBackupPath().c_str()) != 0);
}
}
#ifndef SETUP
void BootEncryption::CreateRescueIsoImage (bool initialSetup, const string &isoImagePath)
{
BootEncryptionStatus encStatus = GetStatus();
if (encStatus.SetupInProgress)
throw ParameterIncorrect (SRC_POS);
Buffer imageBuf (RescueIsoImageSize);
byte *image = imageBuf.Ptr();
memset (image, 0, RescueIsoImageSize);
// Primary volume descriptor
- strcpy ((char *)image + 0x8000, "\001CD001\001");
- strcpy ((char *)image + 0x7fff + 41, "VeraCrypt Rescue Disk ");
+ const char* szPrimVolDesc = "\001CD001\001";
+ const char* szPrimVolLabel = "VeraCrypt Rescue Disk ";
+ memcpy (image + 0x8000, szPrimVolDesc, strlen(szPrimVolDesc) + 1);
+ memcpy (image + 0x7fff + 41, szPrimVolLabel, strlen(szPrimVolLabel) + 1);
*(uint32 *) (image + 0x7fff + 81) = RescueIsoImageSize / 2048;
*(uint32 *) (image + 0x7fff + 85) = BE32 (RescueIsoImageSize / 2048);
image[0x7fff + 121] = 1;
image[0x7fff + 124] = 1;
image[0x7fff + 125] = 1;
image[0x7fff + 128] = 1;
image[0x7fff + 130] = 8;
image[0x7fff + 131] = 8;
image[0x7fff + 133] = 10;
image[0x7fff + 140] = 10;
image[0x7fff + 141] = 0x14;
image[0x7fff + 157] = 0x22;
image[0x7fff + 159] = 0x18;
// Boot record volume descriptor
- strcpy ((char *)image + 0x8801, "CD001\001EL TORITO SPECIFICATION");
+ const char* szBootRecDesc = "CD001\001EL TORITO SPECIFICATION";
+ memcpy (image + 0x8801, szBootRecDesc, strlen(szBootRecDesc) + 1);
image[0x8800 + 0x47] = 0x19;
// Volume descriptor set terminator
- strcpy ((char *)image + 0x9000, "\377CD001\001");
+ const char* szVolDescTerm = "\377CD001\001";
+ memcpy (image + 0x9000, szVolDescTerm, strlen(szVolDescTerm) + 1);
// Path table
image[0xA000 + 0] = 1;
image[0xA000 + 2] = 0x18;
image[0xA000 + 6] = 1;
// Root directory
image[0xc000 + 0] = 0x22;
image[0xc000 + 2] = 0x18;
image[0xc000 + 9] = 0x18;
image[0xc000 + 11] = 0x08;
image[0xc000 + 16] = 0x08;
image[0xc000 + 25] = 0x02;
image[0xc000 + 28] = 0x01;
image[0xc000 + 31] = 0x01;
image[0xc000 + 32] = 0x01;
image[0xc000 + 34] = 0x22;
image[0xc000 + 36] = 0x18;
image[0xc000 + 43] = 0x18;
image[0xc000 + 45] = 0x08;
@@ -1705,41 +1711,41 @@ namespace VeraCrypt
SetLastError (RegOpenKeyEx (HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\CrashControl", 0, KEY_READ | KEY_WRITE, &regKey));
throw_sys_if (GetLastError() != ERROR_SUCCESS);
break;
default:
throw ParameterIncorrect (SRC_POS);
}
finally_do_arg (HKEY, regKey, { RegCloseKey (finally_arg); });
if (registerFilter && filterType != DumpFilter)
{
// Register class filter below all other filters in the stack
size_t strSize = filter.size() + 1;
byte regKeyBuf[65536];
DWORD size = sizeof (regKeyBuf) - strSize;
// SetupInstallFromInfSection() does not support prepending of values so we have to modify the registry directly
- strncpy ((char *) regKeyBuf, filter.c_str(), sizeof (regKeyBuf));
+ StringCbCopyA ((char *) regKeyBuf, sizeof(regKeyBuf), filter.c_str());
if (RegQueryValueEx (regKey, filterReg.c_str(), NULL, NULL, regKeyBuf + strSize, &size) != ERROR_SUCCESS)
size = 1;
SetLastError (RegSetValueEx (regKey, filterReg.c_str(), 0, REG_MULTI_SZ, regKeyBuf, strSize + size));
throw_sys_if (GetLastError() != ERROR_SUCCESS);
}
else
{
string infFileName = GetTempPath() + "\\veracrypt_driver_setup.inf";
File infFile (infFileName, false, true);
finally_do_arg (string, infFileName, { DeleteFile (finally_arg.c_str()); });
string infTxt = "[veracrypt]\r\n"
+ string (registerFilter ? "Add" : "Del") + "Reg=veracrypt_reg\r\n\r\n"
"[veracrypt_reg]\r\n"
"HKR,,\"" + filterReg + "\",0x0001" + string (registerFilter ? "0008" : "8002") + ",\"" + filter + "\"\r\n";
infFile.Write ((byte *) infTxt.c_str(), infTxt.size());
@@ -2301,41 +2307,41 @@ namespace VeraCrypt
}
SelectedEncryptionAlgorithmId = ea;
CreateVolumeHeader (volumeSize, encryptedAreaStart, &password, ea, mode, pkcs5);
if (!rescueIsoImagePath.empty())
CreateRescueIsoImage (true, rescueIsoImagePath);
}
bool BootEncryption::IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly)
{
if (!IsAdmin() && IsUacSupported())
return Elevator::IsPagingFileActive (checkNonWindowsPartitionsOnly) ? true : false;
return ::IsPagingFileActive (checkNonWindowsPartitionsOnly) ? true : false;
}
void BootEncryption::RestrictPagingFilesToSystemPartition ()
{
char pagingFiles[128];
- strncpy (pagingFiles, "X:\\pagefile.sys 0 0", sizeof (pagingFiles));
+ StringCbCopyA (pagingFiles, sizeof(pagingFiles), "X:\\pagefile.sys 0 0");
pagingFiles[0] = GetWindowsDirectory()[0];
throw_sys_if (!WriteLocalMachineRegistryMultiString ("System\\CurrentControlSet\\Control\\Session Manager\\Memory Management", "PagingFiles", pagingFiles, strlen (pagingFiles) + 2));
}
void BootEncryption::WriteLocalMachineRegistryDwordValue (char *keyPath, char *valueName, DWORD value)
{
if (!IsAdmin() && IsUacSupported())
{
Elevator::WriteLocalMachineRegistryDwordValue (keyPath, valueName, value);
return;
}
throw_sys_if (!WriteLocalMachineRegistryDword (keyPath, valueName, value));
}
void BootEncryption::SetDriverConfigurationFlag (uint32 flag, bool state)
{
DWORD configMap = ReadDriverConfigurationFlags();
diff --git a/src/Common/Cmdline.c b/src/Common/Cmdline.c
index 35507c2b..f1f9a8fc 100644
--- a/src/Common/Cmdline.c
+++ b/src/Common/Cmdline.c
@@ -3,71 +3,72 @@
derived 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) 2003-2009 TrueCrypt Developers Association
and are governed by the TrueCrypt License 3.0 the full text of which is
contained in the file License.txt included in TrueCrypt binary and source
code distribution packages. */
#include "Tcdefs.h"
#include <malloc.h>
#include <ctype.h>
#include "Cmdline.h"
#include "Resource.h"
#include "Crypto.h"
#include "Apidrvr.h"
#include "Dlgcode.h"
#include "Language.h"
+#include <Strsafe.h>
/* Except in response to the WM_INITDIALOG message, the dialog box procedure
should return nonzero if it processes the message, and zero if it does
not. - see DialogProc */
BOOL CALLBACK CommandHelpDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (lParam); /* remove warning */
if (wParam); /* remove warning */
switch (msg)
{
case WM_INITDIALOG:
{
char * tmp = err_malloc(8192);
char tmp2[MAX_PATH * 2];
argumentspec *as;
int i;
LocalizeDialog (hwndDlg, "IDD_COMMANDHELP_DLG");
as = (argumentspec*) lParam;
*tmp = 0;
- strcpy (tmp, "Command line options:\n\n");
+ StringCbCopyA (tmp, 8192, "Command line options:\n\n");
for (i = 0; i < as->arg_cnt; i ++)
{
if (!as->args[i].Internal)
{
- sprintf(tmp2, "%s\t%s\n", as->args[i].short_name, as->args[i].long_name);
- strcat(tmp,tmp2);
+ StringCchPrintf(tmp2, MAX_PATH * 2, "%s\t%s\n", as->args[i].short_name, as->args[i].long_name);
+ StringCchCat(tmp, 8192, tmp2);
}
}
SetWindowText (GetDlgItem (hwndDlg, IDC_COMMANDHELP_TEXT), (char*) tmp);
TCfree(tmp);
return 1;
}
case WM_COMMAND:
EndDialog (hwndDlg, IDOK);
return 1;
case WM_CLOSE:
EndDialog (hwndDlg, 0);
return 1;
}
return 0;
}
@@ -203,40 +204,40 @@ int GetArgumentID (argumentspec *as, char *lpszArgument, int *nArgPos)
else
*nArgPos = 0;
return as->args[i].Id;
}
}
}
return -1;
}
int GetArgumentValue (char **lpszCommandLineArgs, int nArgPos, int *nArgIdx,
int nNoCommandLineArgs, char *lpszValue, int nValueSize)
{
*lpszValue = 0;
if (nArgPos)
{
/* Handles the case of no space between parameter code and
value */
- strncpy (lpszValue, &lpszCommandLineArgs[*nArgIdx][nArgPos], nValueSize);
+ StringCbCopyA (lpszValue, nValueSize, &lpszCommandLineArgs[*nArgIdx][nArgPos]);
lpszValue[nValueSize - 1] = 0;
return HAS_ARGUMENT;
}
else if (*nArgIdx + 1 < nNoCommandLineArgs)
{
int x = GetArgSepPosOffset (lpszCommandLineArgs[*nArgIdx + 1]);
if (x == 0)
{
/* Handles the case of space between parameter code
and value */
- strncpy (lpszValue, &lpszCommandLineArgs[*nArgIdx + 1][x], nValueSize);
+ StringCbCopyA (lpszValue, nValueSize, &lpszCommandLineArgs[*nArgIdx + 1][x]);
lpszValue[nValueSize - 1] = 0;
(*nArgIdx)++;
return HAS_ARGUMENT;
}
}
return HAS_NO_ARGUMENT;
}
diff --git a/src/Common/Format.c b/src/Common/Format.c
index 25f20acd..ad6be026 100644
--- a/src/Common/Format.c
+++ b/src/Common/Format.c
@@ -12,40 +12,42 @@
#include <stdlib.h>
#include <string.h>
#include "Tcdefs.h"
#include "Common.h"
#include "Crypto.h"
#include "Fat.h"
#include "Format.h"
#include "Random.h"
#include "Volumes.h"
#include "Apidrvr.h"
#include "Dlgcode.h"
#include "Language.h"
#include "Progress.h"
#include "Resource.h"
#include "Format/FormatCom.h"
#include "Format/Tcformat.h"
+#include <Strsafe.h>
+
int FormatWriteBufferSize = 1024 * 1024;
static uint32 FormatSectorSize = 0;
uint64 GetVolumeDataAreaSize (BOOL hiddenVolume, uint64 volumeSize)
{
uint64 reservedSize;
if (hiddenVolume)
{
// Reserve free space at the end of the host filesystem. FAT file system fills the last sector with
// zeroes (marked as free; observed when quick format was performed using the OS format tool).
// Therefore, when the outer volume is mounted with hidden volume protection, such write operations
// (e.g. quick formatting the outer volume filesystem as FAT) would needlessly trigger hidden volume
// protection.
#if TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE > 4096
# error TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE too large for very small volumes. Revise the code.
#endif
@@ -112,82 +114,82 @@ int TCFormatVolume (volatile FORMAT_VOL_PARAMETERS *volParams)
use the 'bInstantRetryOtherFilesys' flag to skip them. */
if (volParams->hiddenVol)
{
dataOffset = volParams->hiddenVolHostSize - TC_VOLUME_HEADER_GROUP_SIZE - volParams->size;
}
else
{
if (volParams->size <= TC_TOTAL_VOLUME_HEADERS_SIZE)
return ERR_VOL_SIZE_WRONG;
dataOffset = TC_VOLUME_DATA_OFFSET;
}
dataAreaSize = GetVolumeDataAreaSize (volParams->hiddenVol, volParams->size);
num_sectors = dataAreaSize / FormatSectorSize;
if (volParams->bDevice)
{
- strcpy ((char *)deviceName, volParams->volumePath);
- ToUNICODE ((char *)deviceName);
+ StringCbCopyA ((char *)deviceName, sizeof(deviceName), volParams->volumePath);
+ ToUNICODE ((char *)deviceName, sizeof(deviceName));
driveLetter = GetDiskDeviceDriveLetter (deviceName);
}
VirtualLock (header, sizeof (header));
nStatus = CreateVolumeHeaderInMemory (FALSE,
header,
volParams->ea,
FIRST_MODE_OF_OPERATION_ID,
volParams->password,
volParams->pkcs5,
NULL,
&cryptoInfo,
dataAreaSize,
volParams->hiddenVol ? dataAreaSize : 0,
dataOffset,
dataAreaSize,
0,
volParams->headerFlags,
FormatSectorSize,
FALSE);
if (nStatus != 0)
{
burn (header, sizeof (header));
VirtualUnlock (header, sizeof (header));
return nStatus;
}
begin_format:
if (volParams->bDevice)
{
/* Device-hosted volume */
DWORD dwResult;
int nPass;
- if (FakeDosNameForDevice (volParams->volumePath, dosDev, devName, FALSE) != 0)
+ if (FakeDosNameForDevice (volParams->volumePath, dosDev, sizeof(dosDev), devName, sizeof(devName), FALSE) != 0)
return ERR_OS_ERROR;
if (IsDeviceMounted (devName))
{
if ((dev = DismountDrive (devName, volParams->volumePath)) == INVALID_HANDLE_VALUE)
{
Error ("FORMAT_CANT_DISMOUNT_FILESYS");
nStatus = ERR_DONT_REPORT;
goto error;
}
/* Gain "raw" access to the partition (it contains a live filesystem and the filesystem driver
would otherwise prevent us from writing to hidden sectors). */
if (!DeviceIoControl (dev,
FSCTL_ALLOW_EXTENDED_DASD_IO,
NULL,
0,
NULL,
0,
@@ -786,57 +788,57 @@ fail:
volatile BOOLEAN FormatExResult;
BOOLEAN __stdcall FormatExCallback (int command, DWORD subCommand, PVOID parameter)
{
if (command == FMIFS_DONE)
FormatExResult = *(BOOLEAN *) parameter;
return TRUE;
}
BOOL FormatNtfs (int driveNo, int clusterSize)
{
char dllPath[MAX_PATH] = {0};
WCHAR dir[8] = { (WCHAR) driveNo + 'A', 0 };
PFORMATEX FormatEx;
HMODULE hModule;
int i;
if (GetSystemDirectory (dllPath, MAX_PATH))
{
- strcat(dllPath, "\\fmifs.dll");
+ StringCbCatA(dllPath, sizeof(dllPath), "\\fmifs.dll");
}
else
- strcpy(dllPath, "C:\\Windows\\System32\\fmifs.dll");
+ StringCbCopyA(dllPath, sizeof(dllPath), "C:\\Windows\\System32\\fmifs.dll");
hModule = LoadLibrary (dllPath);
if (hModule == NULL)
return FALSE;
if (!(FormatEx = (PFORMATEX) GetProcAddress (GetModuleHandle ("fmifs.dll"), "FormatEx")))
{
FreeLibrary (hModule);
return FALSE;
}
- wcscat (dir, L":\\");
+ StringCbCatW (dir, sizeof(dir), L":\\");
FormatExResult = FALSE;
// Windows sometimes fails to format a volume (hosted on a removable medium) as NTFS.
// It often helps to retry several times.
for (i = 0; i < 50 && FormatExResult != TRUE; i++)
{
FormatEx (dir, FMIFS_HARDDISK, L"NTFS", L"", TRUE, clusterSize * FormatSectorSize, FormatExCallback);
}
// The device may be referenced for some time after FormatEx() returns
Sleep (2000);
FreeLibrary (hModule);
return FormatExResult;
}
BOOL WriteSector (void *dev, char *sector,
char *write_buf, int *write_buf_cnt,
diff --git a/src/Common/Keyfiles.c b/src/Common/Keyfiles.c
index e7e55ca5..4a6baf46 100644
--- a/src/Common/Keyfiles.c
+++ b/src/Common/Keyfiles.c
@@ -6,45 +6,46 @@
packages.
*/
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "Tcdefs.h"
#include "Keyfiles.h"
#include "Crc.h"
#include <io.h>
#include "Dlgcode.h"
#include "Language.h"
#include "SecurityToken.h"
#include "Common/resource.h"
#include "Platform/Finally.h"
#include "Platform/ForEach.h"
+#include <Strsafe.h>
+
using namespace VeraCrypt;
#define stat _stat
#define S_IFDIR _S_IFDIR
-#define snprintf _snprintf
BOOL HiddenFilesPresentInKeyfilePath = FALSE;
KeyFile *KeyFileAdd (KeyFile *firstKeyFile, KeyFile *keyFile)
{
KeyFile *kf = firstKeyFile;
if (firstKeyFile != NULL)
{
while (kf->Next)
kf = kf->Next;
kf->Next = keyFile;
}
else
firstKeyFile = keyFile;
keyFile->Next = NULL;
@@ -80,47 +81,50 @@ static KeyFile *KeyFileRemove (KeyFile *firstKeyFile, KeyFile *keyFile)
}
void KeyFileRemoveAll (KeyFile **firstKeyFile)
{
KeyFile *kf = *firstKeyFile;
while (kf != NULL)
{
KeyFile *d = kf;
kf = kf->Next;
burn (d, sizeof(*d)); // wipe
free (d);
}
*firstKeyFile = NULL;
}
KeyFile *KeyFileClone (KeyFile *keyFile)
{
- KeyFile *clone;
+ KeyFile *clone = NULL;
if (keyFile == NULL) return NULL;
clone = (KeyFile *) malloc (sizeof (KeyFile));
- strcpy (clone->FileName, keyFile->FileName);
- clone->Next = NULL;
+ if (clone)
+ {
+ StringCbCopyA (clone->FileName, sizeof(clone->FileName), keyFile->FileName);
+ clone->Next = NULL;
+ }
return clone;
}
KeyFile *KeyFileCloneAll (KeyFile *firstKeyFile)
{
KeyFile *cloneFirstKeyFile = KeyFileClone (firstKeyFile);
KeyFile *kf;
if (firstKeyFile == NULL) return NULL;
kf = firstKeyFile->Next;
while (kf != NULL)
{
KeyFileAdd (cloneFirstKeyFile, KeyFileClone (kf));
kf = kf->Next;
}
return cloneFirstKeyFile;
}
@@ -281,54 +285,54 @@ BOOL KeyFilesApply (Password *password, KeyFile *firstKeyFile)
catch (Exception &e)
{
e.Show (NULL);
return FALSE;
}
// Determine whether it's a path or a file
if (stat (kf->FileName, &statStruct) != 0)
{
handleWin32Error (MainDlg);
Error ("ERR_PROCESS_KEYFILE");
status = FALSE;
continue;
}
if (statStruct.st_mode & S_IFDIR) // If it's a directory
{
/* Find and process all keyfiles in the directory */
int keyfileCount = 0;
- snprintf (searchPath, sizeof (searchPath), "%s\\*.*", kf->FileName);
+ StringCbPrintfA (searchPath, sizeof (searchPath), "%s\\*.*", kf->FileName);
if ((searchHandle = _findfirst (searchPath, &fBuf)) == -1)
{
handleWin32Error (MainDlg);
Error ("ERR_PROCESS_KEYFILE_PATH");
status = FALSE;
continue;
}
do
{
WIN32_FILE_ATTRIBUTE_DATA fileAttributes;
- snprintf (kfSub->FileName, sizeof(kfSub->FileName), "%s%c%s", kf->FileName,
+ StringCbPrintfA (kfSub->FileName, sizeof(kfSub->FileName), "%s%c%s", kf->FileName,
'\\',
fBuf.name
);
// Determine whether it's a path or a file
if (stat (kfSub->FileName, &statStruct) != 0)
{
handleWin32Error (MainDlg);
Error ("ERR_PROCESS_KEYFILE");
status = FALSE;
continue;
}
else if (statStruct.st_mode & S_IFDIR) // If it's a directory
{
// Prevent recursive folder scanning
continue;
}
// Skip hidden files
if (GetFileAttributesEx (kfSub->FileName, GetFileExInfoStandard, &fileAttributes)
@@ -445,83 +449,89 @@ BOOL CALLBACK KeyFilesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa
LvCol.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT;
LvCol.pszText = GetString ("KEYFILE");
LvCol.cx = CompensateXDPI (374);
LvCol.fmt = LVCFMT_LEFT;
SendMessageW (hList, LVM_INSERTCOLUMNW, 0, (LPARAM)&LvCol);
LoadKeyList (hwndDlg, param->FirstKeyFile);
SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, param->EnableKeyFiles);
SetWindowTextW(GetDlgItem(hwndDlg, IDT_KEYFILES_NOTE), GetString ("KEYFILES_NOTE"));
ToHyperlink (hwndDlg, IDC_LINK_KEYFILES_INFO);
}
return 1;
case WM_COMMAND:
if (lw == IDC_KEYADD)
{
KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
- if (SelectMultipleFiles (hwndDlg, "SELECT_KEYFILE", kf->FileName, bHistory))
+ if (kf)
{
- do
+ if (SelectMultipleFiles (hwndDlg, "SELECT_KEYFILE", kf->FileName, sizeof(kf->FileName),bHistory))
{
- param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
- LoadKeyList (hwndDlg, param->FirstKeyFile);
+ do
+ {
+ param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
+ LoadKeyList (hwndDlg, param->FirstKeyFile);
- kf = (KeyFile *) malloc (sizeof (KeyFile));
- } while (SelectMultipleFilesNext (kf->FileName));
- }
+ kf = (KeyFile *) malloc (sizeof (KeyFile));
+ } while (SelectMultipleFilesNext (kf->FileName, sizeof(kf->FileName)));
+ }
- free (kf);
+ free (kf);
+ }
return 1;
}
if (lw == IDC_ADD_KEYFILE_PATH)
{
KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
if (BrowseDirectories (hwndDlg,"SELECT_KEYFILE_PATH", kf->FileName))
{
param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
LoadKeyList (hwndDlg, param->FirstKeyFile);
}
else
{
free (kf);
}
return 1;
}
if (lw == IDC_TOKEN_FILES_ADD)
{
list <SecurityTokenKeyfilePath> selectedTokenKeyfiles;
if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TOKEN_KEYFILES), hwndDlg, (DLGPROC) SecurityTokenKeyfileDlgProc, (LPARAM) &selectedTokenKeyfiles) == IDOK)
{
foreach (const SecurityTokenKeyfilePath &keyPath, selectedTokenKeyfiles)
{
KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
- strcpy_s (kf->FileName, sizeof (kf->FileName), WideToSingleString (keyPath).c_str());
+ if (kf)
+ {
+ strcpy_s (kf->FileName, sizeof (kf->FileName), WideToSingleString (keyPath).c_str());
- param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
- LoadKeyList (hwndDlg, param->FirstKeyFile);
+ param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
+ LoadKeyList (hwndDlg, param->FirstKeyFile);
+ }
}
}
return 1;
}
if (lw == IDC_KEYREMOVE)
{
HWND list = GetDlgItem (hwndDlg, IDC_KEYLIST);
LVITEM LvItem;
memset (&LvItem, 0, sizeof(LvItem));
LvItem.mask = LVIF_PARAM;
LvItem.iItem = -1;
while (-1 != (LvItem.iItem = ListView_GetNextItem (list, LvItem.iItem, LVIS_SELECTED)))
{
ListView_GetItem (list, &LvItem);
param->FirstKeyFile = KeyFileRemove (param->FirstKeyFile, (KeyFile *) LvItem.lParam);
}
@@ -557,129 +567,142 @@ BOOL CALLBACK KeyFilesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa
}
if (lw == IDCANCEL)
{
KeyFileRemoveAll (&param->FirstKeyFile);
*param = origParam;
EndDialog (hwndDlg, IDCLOSE);
return 1;
}
case WM_DROPFILES:
{
HDROP hdrop = (HDROP) wParam;
int i = 0, count = DragQueryFile (hdrop, 0xFFFFFFFF, NULL, 0);
while (count-- > 0)
{
KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
- DragQueryFile (hdrop, i++, kf->FileName, sizeof (kf->FileName));
- param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
- LoadKeyList (hwndDlg, param->FirstKeyFile);
+ if (kf)
+ {
+ DragQueryFile (hdrop, i++, kf->FileName, sizeof (kf->FileName));
+ param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
+ LoadKeyList (hwndDlg, param->FirstKeyFile);
+ }
}
DragFinish (hdrop);
}
return 1;
case WM_NOTIFY:
if (((LPNMHDR) lParam)->code == LVN_ITEMCHANGED)
{
EnableWindow (GetDlgItem (hwndDlg, IDC_KEYREMOVE),
ListView_GetNextItem (GetDlgItem (hwndDlg, IDC_KEYLIST), -1, LVIS_SELECTED) != -1);
return 1;
}
break;
case WM_CLOSE:
KeyFileRemoveAll (&param->FirstKeyFile);
*param = origParam;
EndDialog (hwndDlg, IDCLOSE);
return 1;
break;
}
return 0;
}
#define IDM_KEYFILES_POPUP_ADD_FILES 9001
#define IDM_KEYFILES_POPUP_ADD_DIR 9002
#define IDM_KEYFILES_POPUP_ADD_TOKEN_FILES 9003
BOOL KeyfilesPopupMenu (HWND hwndDlg, POINT popupPosition, KeyFilesDlgParam *param)
{
HMENU popup = CreatePopupMenu ();
+ if (!popup)
+ return FALSE;
int sel;
BOOL status = FALSE;
AppendMenuW (popup, MF_STRING, IDM_KEYFILES_POPUP_ADD_FILES, GetString ("IDC_KEYADD"));
AppendMenuW (popup, MF_STRING, IDM_KEYFILES_POPUP_ADD_DIR, GetString ("IDC_ADD_KEYFILE_PATH"));
AppendMenuW (popup, MF_STRING, IDM_KEYFILES_POPUP_ADD_TOKEN_FILES, GetString ("IDC_TOKEN_FILES_ADD"));
sel = TrackPopupMenu (popup, TPM_RETURNCMD | TPM_LEFTBUTTON, popupPosition.x, popupPosition.y, 0, hwndDlg, NULL);
switch (sel)
{
case IDM_KEYFILES_POPUP_ADD_FILES:
{
KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
- if (SelectMultipleFiles (hwndDlg, "SELECT_KEYFILE", kf->FileName, bHistory))
+ if (kf)
{
- do
+ if (SelectMultipleFiles (hwndDlg, "SELECT_KEYFILE", kf->FileName, sizeof(kf->FileName),bHistory))
{
- param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
- kf = (KeyFile *) malloc (sizeof (KeyFile));
- } while (SelectMultipleFilesNext (kf->FileName));
+ do
+ {
+ param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
+ kf = (KeyFile *) malloc (sizeof (KeyFile));
+ } while (SelectMultipleFilesNext (kf->FileName, sizeof(kf->FileName)));
- param->EnableKeyFiles = TRUE;
- status = TRUE;
- }
+ param->EnableKeyFiles = TRUE;
+ status = TRUE;
+ }
- free (kf);
+ free (kf);
+ }
}
break;
case IDM_KEYFILES_POPUP_ADD_DIR:
{
KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
-
- if (BrowseDirectories (hwndDlg,"SELECT_KEYFILE_PATH", kf->FileName))
+ if (kf)
{
- param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
- param->EnableKeyFiles = TRUE;
- status = TRUE;
- }
- else
- {
- free (kf);
+ if (BrowseDirectories (hwndDlg,"SELECT_KEYFILE_PATH", kf->FileName))
+ {
+ param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
+ param->EnableKeyFiles = TRUE;
+ status = TRUE;
+ }
+ else
+ {
+ free (kf);
+ }
}
}
break;
case IDM_KEYFILES_POPUP_ADD_TOKEN_FILES:
{
list <SecurityTokenKeyfilePath> selectedTokenKeyfiles;
if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TOKEN_KEYFILES), hwndDlg, (DLGPROC) SecurityTokenKeyfileDlgProc, (LPARAM) &selectedTokenKeyfiles) == IDOK)
{
foreach (const SecurityTokenKeyfilePath &keyPath, selectedTokenKeyfiles)
{
KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
- strcpy_s (kf->FileName, sizeof (kf->FileName), WideToSingleString (keyPath).c_str());
-
- param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
- param->EnableKeyFiles = TRUE;
- status = TRUE;
+ if (kf)
+ {
+ strcpy_s (kf->FileName, sizeof (kf->FileName), WideToSingleString (keyPath).c_str());
+
+ param->FirstKeyFile = KeyFileAdd (param->FirstKeyFile, kf);
+ param->EnableKeyFiles = TRUE;
+ status = TRUE;
+ }
}
}
}
break;
}
DestroyMenu (popup);
return status;
}
diff --git a/src/Common/Language.c b/src/Common/Language.c
index b146f820..3ec95dba 100644
--- a/src/Common/Language.c
+++ b/src/Common/Language.c
@@ -9,40 +9,42 @@
#include "Language.h"
#include "Dlgcode.h"
#include "Dictionary.h"
#include "Tcdefs.h"
#include "Xml.h"
#include "../Common/Resource.h"
#ifdef TCMOUNT
#include "../Mount/Resource.h"
#endif
#ifdef VOLFORMAT
#include "../Format/Resource.h"
#endif
#ifdef SETUP
#include "../Setup/Resource.h"
#endif
+#include <Strsafe.h>
+
BOOL LocalizationActive;
int LocalizationSerialNo;
wchar_t UnknownString[1024];
static char *LanguageFileBuffer;
static HANDLE LanguageFileFindHandle = INVALID_HANDLE_VALUE;
static char PreferredLangId[6];
static char *LanguageResource;
static char *HeaderResource[2];
static char ActiveLangPackVersion[6];
static char *MapFirstLanguageFile ()
{
if (LanguageFileFindHandle != INVALID_HANDLE_VALUE)
{
FindClose (LanguageFileFindHandle);
LanguageFileFindHandle = INVALID_HANDLE_VALUE;
}
if (LanguageResource == NULL)
@@ -51,120 +53,136 @@ static char *MapFirstLanguageFile ()
LanguageResource = MapResource ("Xml", IDR_LANGUAGE, &size);
LanguageResource[size - 1] = 0;
}
return LanguageResource;
}
static char *MapNextLanguageFile ()
{
wchar_t f[TC_MAX_PATH*2], *t;
WIN32_FIND_DATAW find;
HANDLE file;
DWORD read;
if (LanguageFileFindHandle == INVALID_HANDLE_VALUE)
{
GetModuleFileNameW (NULL, f, sizeof (f) / sizeof (f[0]));
t = wcsrchr (f, L'\\');
if (t == NULL) return NULL;
-
- wcscpy (t, L"\\Language*.xml");
+
+ *t = 0;
+ StringCbCatW (f, sizeof(f), L"\\Language*.xml");
LanguageFileFindHandle = FindFirstFileW (f, &find);
}
else if (!FindNextFileW (LanguageFileFindHandle, &find))
{
FindClose (LanguageFileFindHandle);
LanguageFileFindHandle = INVALID_HANDLE_VALUE;
return NULL;
}
if (find.nFileSizeHigh != 0) return NULL;
if (LanguageFileBuffer != NULL) free (LanguageFileBuffer);
LanguageFileBuffer = malloc(find.nFileSizeLow);
if (LanguageFileBuffer == NULL) return NULL;
GetModuleFileNameW (NULL, f, sizeof (f) / sizeof(f[0]));
t = wcsrchr (f, L'\\');
- wcscpy (t + 1, find.cFileName);
+ if (t == NULL)
+ {
+ free(LanguageFileBuffer);
+ return NULL;
+ }
+
+ t[1] = 0;
+ StringCbCatW (f, sizeof(f),find.cFileName);
file = CreateFileW (f, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
- if (file == INVALID_HANDLE_VALUE) return NULL;
+ if (file == INVALID_HANDLE_VALUE)
+ {
+ free(LanguageFileBuffer);
+ return NULL;
+ }
ReadFile (file, LanguageFileBuffer, find.nFileSizeLow, &read, NULL);
CloseHandle (file);
- if (read != find.nFileSizeLow) return NULL;
+ if (read != find.nFileSizeLow)
+ {
+ free(LanguageFileBuffer);
+ return NULL;
+ }
return LanguageFileBuffer;
}
BOOL LoadLanguageFile ()
{
DWORD size;
BYTE *res;
char *xml, *header;
char langId[6] = "en", attr[32768], key[128];
BOOL defaultLangParsed = FALSE, langFound = FALSE;
WCHAR wattr[32768];
int i, intKey, len;
char *xmlElements[] = {"control", "string", 0};
#ifdef TCMOUNT
int headers[] = { IDR_COMMON_RSRC_HEADER, IDR_MOUNT_RSRC_HEADER, 0 };
#endif
#ifdef VOLFORMAT
int headers[] = { IDR_COMMON_RSRC_HEADER, IDR_FORMAT_RSRC_HEADER, 0 };
#endif
#ifdef SETUP
int headers[] = { IDR_COMMON_RSRC_HEADER, IDR_SETUP_RSRC_HEADER, 0 };
#endif
LocalizationActive = FALSE;
ActiveLangPackVersion[0] = 0;
ClearDictionaryPool ();
if (PreferredLangId[0] != 0)
- strcpy (langId, PreferredLangId);
+ StringCbCopyA (langId, sizeof(langId), PreferredLangId);
// Parse all available language files until preferred language is found
for (res = MapFirstLanguageFile (); res != NULL; res = MapNextLanguageFile ())
{
xml = (char *) res;
xml = XmlFindElement (xml, "localization");
if (!xml)
continue;
// Required TrueCrypt version
XmlGetAttributeText (xml, "prog-version", attr, sizeof (attr));
// Check version of external language file
if (defaultLangParsed && strcmp (attr, VERSION_STRING) && strcmp (attr, "DEBUG"))
{
wchar_t m[2048];
- swprintf (m, L"The installed language pack is incompatible with this version of VeraCrypt (the language pack is for VeraCrypt %hs). A newer version may be available at www.idrix.fr.\n\nTo prevent this message from being displayed, do any of the following:\n\n- Select 'Settings' > 'Language'; then select 'English' and click 'OK'.\n\n- Remove or replace the language pack with a compatible version (the language pack may reside e.g. in 'C:\\Program Files\\VeraCrypt' or '%%LOCALAPPDATA%%\\VirtualStore\\Program Files\\VeraCrypt', etc.)", attr);
+ StringCbPrintfW (m, sizeof(m), L"The installed language pack is incompatible with this version of VeraCrypt (the language pack is for VeraCrypt %hs). A newer version may be available at www.idrix.fr.\n\nTo prevent this message from being displayed, do any of the following:\n\n- Select 'Settings' > 'Language'; then select 'English' and click 'OK'.\n\n- Remove or replace the language pack with a compatible version (the language pack may reside e.g. in 'C:\\Program Files\\VeraCrypt' or '%%LOCALAPPDATA%%\\VirtualStore\\Program Files\\VeraCrypt', etc.)", attr);
MessageBoxW (NULL, m, L"VeraCrypt", MB_ICONERROR);
continue;
}
// Search language id in language file
if (defaultLangParsed)
{
while (xml = XmlFindElement (xml, "language"))
{
XmlGetAttributeText (xml, "langid", attr, sizeof (attr));
if (strcmp (attr, langId) == 0)
{
XmlGetAttributeText (xml++, "version", ActiveLangPackVersion, sizeof (ActiveLangPackVersion));
langFound = TRUE;
break;
}
xml++;
}
if (!langFound) continue;
@@ -172,41 +190,41 @@ BOOL LoadLanguageFile ()
// Create font dictionary
xml = (char *) res;
while (xml = XmlFindElement (xml, "font"))
{
XmlGetAttributeText (xml, "lang", attr, sizeof (attr));
if (!defaultLangParsed
|| strcmp (attr, langId) == 0)
{
Font font;
memset (&font, 0, sizeof (font));
XmlGetAttributeText (xml, "face", attr, sizeof (attr));
len = MultiByteToWideChar (CP_UTF8, 0, attr, -1, wattr, sizeof (wattr) / sizeof(wattr[0]));
font.FaceName = AddPoolData ((void *) wattr, len * 2);
XmlGetAttributeText (xml, "size", attr, sizeof (attr));
sscanf (attr, "%d", &font.Size);
- strcpy (attr, "font_");
+ StringCbCopyA (attr, sizeof(attr), "font_");
XmlGetAttributeText (xml, "class", attr + 5, sizeof (attr) - 5);
AddDictionaryEntry (
AddPoolData ((void *) attr, strlen (attr) + 1), 0,
AddPoolData ((void *) &font, sizeof(font)));
}
xml++;
}
// Create string and control dictionaries
for (i = 0; xmlElements[i] != 0; i++)
{
xml = (char *) res;
while (xml = XmlFindElement (xml, xmlElements[i]))
{
void *key;
void *text;
XmlGetAttributeText (xml, "lang", attr, sizeof (attr));
if (!defaultLangParsed
@@ -358,158 +376,158 @@ BOOL CALLBACK LanguageDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa
}
if (!defaultLangFound)
defaultLangFound = TRUE;
SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_SETITEMDATA, i, (LPARAM) id);
if (strcmp (attr, PreferredLangId) == 0)
{
char credits [10000];
WCHAR wcredits [10000];
WCHAR wversion [20];
wchar_t szVers [200];
int nLen;
SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_SETCURSEL, i, 0);
// Language pack version
if (!ActiveLangPackVersion[0] || memcmp (ActiveLangPackVersion, "0.0.0", 5) == 0)
{
- swprintf (szVers, GetString("LANG_PACK_VERSION"), L"--");
+ StringCbPrintfW (szVers, sizeof(szVers), GetString("LANG_PACK_VERSION"), L"--");
}
else
{
nLen = MultiByteToWideChar (CP_UTF8, 0, ActiveLangPackVersion, -1, wversion, sizeof (wversion) / sizeof(wversion[0]));
if (nLen != 0 && nLen != ERROR_NO_UNICODE_TRANSLATION)
- swprintf (szVers, GetString("LANG_PACK_VERSION"), wversion);
+ StringCbPrintfW (szVers, sizeof(szVers),GetString("LANG_PACK_VERSION"), wversion);
}
SetWindowTextW (GetDlgItem (hwndDlg, IDC_LANGPACK_VERSION), szVers);
// Translator credits
XmlGetAttributeText (xml, "translators", credits, sizeof (credits));
nLen = MultiByteToWideChar (CP_UTF8, 0, credits, -1, wcredits, sizeof (wcredits) / sizeof(wcredits[0]));
if (nLen != 0 && nLen != ERROR_NO_UNICODE_TRANSLATION)
{
SetWindowTextW (GetDlgItem (hwndDlg, IDC_LANGPACK_CREDITS), wcredits);
}
}
- strcpy (lastLangId, attr);
+ StringCbCopyA (lastLangId, sizeof(lastLangId),attr);
langCount++;
}
}
xml++;
}
}
if (lParam == 1)
{
// Auto mode
if (langCount < 2)
EndDialog (hwndDlg, IDCANCEL);
if (langCount == 2)
- strcpy (PreferredLangId, lastLangId);
+ StringCbCopyA (PreferredLangId, sizeof(PreferredLangId), lastLangId);
EndDialog (hwndDlg, IDOK);
}
return 1;
}
case WM_COMMAND:
if (lw == IDOK || hw == LBN_DBLCLK)
{
int i = SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_GETCURSEL, 0, 0);
if (i >= 0)
{
int id = SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_GETITEMDATA, i, 0);
if (id != LB_ERR)
{
char l[6];
// Decode language id from LPARAM
l[0] = (char) id;
l[1] = (char) (id >> 8);
l[2] = 0;
if ((id & 0xffff0000) != 0)
{
l[2] = '-';
l[3] = (char) (id >> 16);
l[4] = id >> 24;
l[5] = 0;
}
if (SendDlgItemMessage (hwndDlg, IDC_LANGLIST, LB_GETCOUNT, 0, 0) > 1)
- strcpy (PreferredLangId, l);
+ StringCbCopyA (PreferredLangId, sizeof(PreferredLangId), l);
}
}
EndDialog (hwndDlg, IDOK);
return 1;
}
if (lw == IDCANCEL)
{
EndDialog (hwndDlg, lw);
return 1;
}
if (lw == IDC_GET_LANG_PACKS)
{
char tmpstr [256];
if (strlen (ActiveLangPackVersion) > 0 && strlen (GetPreferredLangId()) > 0)
- sprintf (tmpstr, "&langpackversion=%s&lang=%s", ActiveLangPackVersion, GetPreferredLangId());
+ StringCbPrintfA (tmpstr, sizeof(tmpstr), "&langpackversion=%s&lang=%s", ActiveLangPackVersion, GetPreferredLangId());
else
tmpstr[0] = 0;
Applink ("localizations", TRUE, tmpstr);
return 1;
}
return 0;
}
return 0;
}
char *GetPreferredLangId ()
{
return PreferredLangId;
}
void SetPreferredLangId (char *langId)
{
- strncpy (PreferredLangId, langId, 5);
+ StringCbCopyA (PreferredLangId, sizeof(PreferredLangId), langId);
}
char *GetActiveLangPackVersion ()
{
return ActiveLangPackVersion;
}
wchar_t *GetString (const char *stringId)
{
WCHAR *str = (WCHAR *) GetDictionaryValue (stringId);
if (str != NULL) return str;
- wsprintfW (UnknownString, UNKNOWN_STRING_ID L"%hs" UNKNOWN_STRING_ID, stringId);
+ StringCbPrintfW (UnknownString, sizeof(UnknownString), UNKNOWN_STRING_ID L"%hs" UNKNOWN_STRING_ID, stringId);
return UnknownString;
}
Font *GetFont (char *fontType)
{
return (Font *) GetDictionaryValue (fontType);
}
diff --git a/src/Common/Progress.c b/src/Common/Progress.c
index afa6f645..89697a62 100644
--- a/src/Common/Progress.c
+++ b/src/Common/Progress.c
@@ -1,39 +1,41 @@
/*
Legal Notice: Some portions of the source code contained in this file were
derived 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) 2003-2009 TrueCrypt Developers Association
and are governed by the TrueCrypt License 3.0 the full text of which is
contained in the file License.txt included in TrueCrypt binary and source
code distribution packages. */
#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);
bProgressBarReverse = bReverse;
@@ -57,74 +59,74 @@ BOOL UpdateProgressBar (__int64 byteOffset)
return UpdateProgressBarProc (byteOffset);
}
BOOL UpdateProgressBarProc (__int64 byteOffset)
{
wchar_t text[100];
wchar_t speed[100];
HWND hProgressBar = GetDlgItem (hCurPage, nPbar);
int time = GetTickCount ();
int elapsed = (time - startTime) / 1000;
uint64 bytesDone = (bProgressBarReverse ? (TotalSize - byteOffset) : byteOffset);
uint64 bytesPerSec = (bProgressBarReverse ? (resumedPointBytesDone - byteOffset) : (bytesDone - resumedPointBytesDone)) / (elapsed + 1);
if (bPercentMode)
{
double perc = (double) (100.0 * (bProgressBarReverse ? ((double) (TotalSize - byteOffset)) : ((double) byteOffset)) / (TotalSize == 0 ? 0.0001 : ((double) TotalSize)));
if (perc > 99.999999999)
- wcscpy (text, GetString ("PROCESSED_PORTION_100_PERCENT"));
+ StringCbCopyW (text,sizeof(text), GetString ("PROCESSED_PORTION_100_PERCENT"));
else
- _snwprintf (text, sizeof text/2, GetString ("PROCESSED_PORTION_X_PERCENT"), perc);
+ StringCbPrintfW (text, sizeof text, GetString ("PROCESSED_PORTION_X_PERCENT"), perc);
- wcscat (speed, L" ");
+ StringCbCatW (speed, sizeof(speed), L" ");
}
else
{
- GetSizeString (bytesDone, text);
+ GetSizeString (bytesDone, text, sizeof(text));
if (bytesDone < (unsigned __int64) BYTES_PER_MB * 1000000)
- swprintf(text, L"%I64d %s ", bytesDone / BYTES_PER_MB, GetString ("MB"));
+ StringCbPrintfW(text, sizeof(text), L"%I64d %s ", bytesDone / BYTES_PER_MB, GetString ("MB"));
else if (bytesDone < (unsigned __int64) BYTES_PER_GB * 1000000)
- swprintf(text, L"%I64d %s ", bytesDone / BYTES_PER_GB, GetString ("GB"));
+ StringCbPrintfW(text, sizeof(text), L"%I64d %s ", bytesDone / BYTES_PER_GB, GetString ("GB"));
else if (bytesDone < (unsigned __int64) BYTES_PER_TB * 1000000)
- swprintf(text, L"%I64d %s ", bytesDone / BYTES_PER_TB, GetString ("TB"));
+ StringCbPrintfW(text, sizeof(text), L"%I64d %s ", bytesDone / BYTES_PER_TB, GetString ("TB"));
else
- swprintf(text, L"%I64d %s ", bytesDone / BYTES_PER_PB, GetString ("PB"));
+ StringCbPrintfW(text, sizeof(text), L"%I64d %s ", bytesDone / BYTES_PER_PB, GetString ("PB"));
}
SetWindowTextW (GetDlgItem (hCurPage, IDC_BYTESWRITTEN), text);
if (!bShowStatus)
{
- GetSpeedString (bRWThroughput ? bytesPerSec*2 : bytesPerSec, speed);
- wcscat (speed, L" ");
+ GetSpeedString (bRWThroughput ? bytesPerSec*2 : bytesPerSec, speed, sizeof(speed));
+ StringCbCatW (speed, sizeof(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)
- swprintf (text, L"%s ", GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE"));
+ StringCbPrintfW (text, sizeof(text), L"%s ", GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE"));
else if (sec >= 60 * 60 * 24 * 2)
- swprintf (text, L"%I64d %s ", sec / (60 * 24 * 60), days);
+ StringCbPrintfW (text, sizeof(text), L"%I64d %s ", sec / (60 * 24 * 60), days);
else if (sec >= 120 * 60)
- swprintf (text, L"%I64d %s ", sec / (60 * 60), hours);
+ StringCbPrintfW (text, sizeof(text), L"%I64d %s ", sec / (60 * 60), hours);
else if (sec >= 120)
- swprintf (text, L"%I64d %s ", sec / 60, minutes);
+ StringCbPrintfW (text, sizeof(text), L"%I64d %s ", sec / 60, minutes);
else
- swprintf (text, L"%I64d %s ", sec, seconds);
+ StringCbPrintfW (text, sizeof(text), L"%I64d %s ", sec, seconds);
SetWindowTextW (GetDlgItem (hCurPage, IDC_TIMEREMAIN), text);
}
prevTime = time;
SendMessage (hProgressBar, PBM_SETPOS,
(int) (10000.0 * (bProgressBarReverse ? (TotalSize - byteOffset) : byteOffset) / (TotalSize == 0 ? 1 : TotalSize)),
0);
return bVolTransformThreadCancel;
}
diff --git a/src/Common/Random.c b/src/Common/Random.c
index c897e3b7..445e8f24 100644
--- a/src/Common/Random.c
+++ b/src/Common/Random.c
@@ -1,34 +1,35 @@
/*
Legal Notice: Some portions of the source code contained in this file were
derived 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) 2003-2009 TrueCrypt Developers Association
and are governed by the TrueCrypt License 3.0 the full text of which is
contained in the file License.txt included in TrueCrypt binary and source
code distribution packages. */
#include "Tcdefs.h"
#include "Crc.h"
#include "Random.h"
+#include <Strsafe.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++; \
}
@@ -559,44 +560,44 @@ BOOL SlowPoll (void)
szValue, &dwSize);
if (status == ERROR_SUCCESS && _stricmp ((char *) szValue, "WinNT"))
/* Note: There are (at least) three cases for
ProductType: WinNT = NT Workstation,
ServerNT = NT Server, LanmanNT = NT Server
acting as a Domain Controller */
isWorkstation = FALSE;
RegCloseKey (hKey);
}
}
/* Initialize the NetAPI32 function pointers if necessary */
if (hNetAPI32 == NULL)
{
/* Obtain a handle to the module containing the Lan Manager
functions */
char dllPath[MAX_PATH];
if (GetSystemDirectory (dllPath, MAX_PATH))
{
- strcat(dllPath, "\\NETAPI32.DLL");
+ StringCbCatA(dllPath, sizeof(dllPath), "\\NETAPI32.DLL");
}
else
- strcpy(dllPath, "C:\\Windows\\System32\\NETAPI32.DLL");
+ StringCbCopyA(dllPath, sizeof(dllPath), "C:\\Windows\\System32\\NETAPI32.DLL");
hNetAPI32 = LoadLibrary (dllPath);
if (hNetAPI32 != NULL)
{
/* Now get pointers to the functions */
pNetStatisticsGet = (NETSTATISTICSGET) GetProcAddress (hNetAPI32,
"NetStatisticsGet");
pNetApiBufferSize = (NETAPIBUFFERSIZE) GetProcAddress (hNetAPI32,
"NetApiBufferSize");
pNetApiBufferFree = (NETAPIBUFFERFREE) GetProcAddress (hNetAPI32,
"NetApiBufferFree");
/* Make sure we got valid pointers for every NetAPI32
function */
if (pNetStatisticsGet == NULL ||
pNetApiBufferSize == NULL ||
pNetApiBufferFree == NULL)
{
/* Free the library reference and reset the
static handle */
@@ -613,41 +614,41 @@ BOOL SlowPoll (void)
the appropriate service */
lpszLanW = (LPWSTR) WIDE ("LanmanWorkstation");
lpszLanS = (LPWSTR) WIDE ("LanmanServer");
if (hNetAPI32 &&
pNetStatisticsGet (NULL,
isWorkstation ? lpszLanW : lpszLanS,
0, 0, &lpBuffer) == 0)
{
pNetApiBufferSize (lpBuffer, &dwSize);
RandaddBuf ((unsigned char *) lpBuffer, dwSize);
pNetApiBufferFree (lpBuffer);
}
/* Get disk I/O statistics for all the hard drives */
for (nDrive = 0;; nDrive++)
{
DISK_PERFORMANCE diskPerformance;
char szDevice[24];
/* Check whether we can access this device */
- sprintf (szDevice, "\\\\.\\PhysicalDrive%d", nDrive);
+ StringCbPrintfA (szDevice, sizeof(szDevice), "\\\\.\\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
if (CryptoAPIAvailable && CryptGenRandom (hCryptProv, sizeof (buffer), buffer))
diff --git a/src/Common/Tcdefs.h b/src/Common/Tcdefs.h
index 0bf41d79..423eed27 100644
--- a/src/Common/Tcdefs.h
+++ b/src/Common/Tcdefs.h
@@ -180,41 +180,41 @@ typedef int BOOL;
#ifdef DEVICE_DRIVER
# if defined (DEBUG) || 0
# if 1 // DbgPrintEx is not available on Windows 2000
# define Dump DbgPrint
# else
# define Dump(...) DbgPrintEx (DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, __VA_ARGS__)
# endif
# define DumpMem(...) DumpMemory (__VA_ARGS__)
# else
# define Dump(...)
# define DumpMem(...)
# endif
#endif
#if !defined (trace_msg) && !defined (TC_WINDOWS_BOOT)
# ifdef DEBUG
# ifdef DEVICE_DRIVER
# define trace_msg Dump
# elif defined (_WIN32)
-# define trace_msg(...) do { char msg[2048]; _snprintf (msg, sizeof (msg), __VA_ARGS__); OutputDebugString (msg); } while (0)
+# define trace_msg(...) do { char msg[2048]; StringCbPrintfA (msg, sizeof (msg), __VA_ARGS__); OutputDebugString (msg); } while (0)
# endif
# define trace_point trace_msg (__FUNCTION__ ":" TC_TO_STRING(__LINE__) "\n")
# else
# define trace_msg(...)
# define trace_point
# endif
#endif
#ifdef DEVICE_DRIVER
# define TC_EVENT KEVENT
# define TC_WAIT_EVENT(EVENT) KeWaitForSingleObject (&EVENT, Executive, KernelMode, FALSE, NULL)
#elif defined (_WIN32)
# define TC_EVENT HANDLE
# define TC_WAIT_EVENT(EVENT) WaitForSingleObject (EVENT, INFINITE)
#endif
#ifdef _WIN32
#define burn(mem,size) do { volatile char *burnm = (volatile char *)(mem); int burnc = size; RtlSecureZeroMemory (mem, size); while (burnc--) *burnm++ = 0; } while (0)
#else
#define burn(mem,size) do { volatile char *burnm = (volatile char *)(mem); int burnc = size; while (burnc--) *burnm++ = 0; } while (0)
diff --git a/src/Common/Volumes.c b/src/Common/Volumes.c
index 506a4d04..15ee8fe6 100644
--- a/src/Common/Volumes.c
+++ b/src/Common/Volumes.c
@@ -16,40 +16,43 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include "EncryptionThreadPool.h"
#endif
#include <stddef.h>
#include <string.h>
#include <io.h>
#ifndef DEVICE_DRIVER
#include "Random.h"
#endif
#include "Crc.h"
#include "Crypto.h"
#include "Endian.h"
#include "Volumes.h"
#include "Pkcs5.h"
+#ifdef _WIN32
+#include <Strsafe.h>
+#endif
/* Volume header v5 structure (used since TrueCrypt 7.0): */
//
// Offset Length Description
// ------------------------------------------
// Unencrypted:
// 0 64 Salt
// Encrypted:
// 64 4 ASCII string 'VERA'
// 68 2 Header version
// 70 2 Required program version
// 72 4 CRC-32 checksum of the (decrypted) bytes 256-511
// 76 16 Reserved (must contain zeroes)
// 92 8 Size of hidden volume in bytes (0 = normal volume)
// 100 8 Size of the volume in bytes (identical with field 92 for hidden volumes, valid if field 70 >= 0x600 or flag bit 0 == 1)
// 108 8 Byte offset of the start of the master key scope (valid if field 70 >= 0x600 or flag bit 0 == 1)
// 116 8 Size of the encrypted area within the master key scope (valid if field 70 >= 0x600 or flag bit 0 == 1)
// 124 4 Flags: bit 0 set = system encryption; bit 1 set = non-system in-place encryption, bits 2-31 are reserved (set to zero)
// 128 4 Sector size in bytes
// 132 120 Reserved (must contain zeroes)
@@ -170,40 +173,43 @@ int ReadVolumeHeader (BOOL bBoot, char *encryptedHeader, Password *password, PCR
uint16 headerVersion;
int status = ERR_PARAMETER_INCORRECT;
int primaryKeyOffset;
TC_EVENT keyDerivationCompletedEvent;
TC_EVENT noOutstandingWorkItemEvent;
KeyDerivationWorkItem *keyDerivationWorkItems;
KeyDerivationWorkItem *item;
int pkcs5PrfCount = LAST_PRF_ID - FIRST_PRF_ID + 1;
size_t encryptionThreadCount = GetEncryptionThreadCount();
size_t queuedWorkItems = 0;
LONG outstandingWorkItemCount = 0;
int i;
if (retHeaderCryptoInfo != NULL)
{
cryptoInfo = retHeaderCryptoInfo;
}
else
{
+ if (!retInfo)
+ return ERR_PARAMETER_INCORRECT;
+
cryptoInfo = *retInfo = crypto_open ();
if (cryptoInfo == NULL)
return ERR_OUTOFMEMORY;
}
if (encryptionThreadCount > 1)
{
keyDerivationWorkItems = TCalloc (sizeof (KeyDerivationWorkItem) * pkcs5PrfCount);
if (!keyDerivationWorkItems)
return ERR_OUTOFMEMORY;
for (i = 0; i < pkcs5PrfCount; ++i)
keyDerivationWorkItems[i].Free = TRUE;
#ifdef DEVICE_DRIVER
KeInitializeEvent (&keyDerivationCompletedEvent, SynchronizationEvent, FALSE);
KeInitializeEvent (&noOutstandingWorkItemEvent, SynchronizationEvent, TRUE);
#else
keyDerivationCompletedEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
if (!keyDerivationCompletedEvent)
@@ -917,50 +923,50 @@ int CreateVolumeHeaderInMemory (BOOL bBoot, char *header, int ea, int mode, Pass
#ifdef VOLFORMAT
if (showKeys && !bInPlaceEncNonSys)
{
BOOL dots3 = FALSE;
int i, j;
j = EAGetKeySize (ea);
if (j > NBR_KEY_BYTES_TO_DISPLAY)
{
dots3 = TRUE;
j = NBR_KEY_BYTES_TO_DISPLAY;
}
MasterKeyGUIView[0] = 0;
for (i = 0; i < j; i++)
{
char tmp2[8] = {0};
- sprintf (tmp2, "%02X", (int) (unsigned char) keyInfo.master_keydata[i + primaryKeyOffset]);
- strcat (MasterKeyGUIView, tmp2);
+ StringCbPrintfA (tmp2, sizeof(tmp2), "%02X", (int) (unsigned char) keyInfo.master_keydata[i + primaryKeyOffset]);
+ StringCbCatA (MasterKeyGUIView, sizeof(MasterKeyGUIView), tmp2);
}
HeaderKeyGUIView[0] = 0;
for (i = 0; i < NBR_KEY_BYTES_TO_DISPLAY; i++)
{
char tmp2[8];
- sprintf (tmp2, "%02X", (int) (unsigned char) dk[primaryKeyOffset + i]);
- strcat (HeaderKeyGUIView, tmp2);
+ StringCbPrintfA (tmp2, sizeof(tmp2), "%02X", (int) (unsigned char) dk[primaryKeyOffset + i]);
+ StringCbCatA (HeaderKeyGUIView, sizeof(HeaderKeyGUIView), tmp2);
}
if (dots3)
{
DisplayPortionsOfKeys (hHeaderKey, hMasterKey, HeaderKeyGUIView, MasterKeyGUIView, !showKeys);
}
else
{
SendMessage (hMasterKey, WM_SETTEXT, 0, (LPARAM) MasterKeyGUIView);
SendMessage (hHeaderKey, WM_SETTEXT, 0, (LPARAM) HeaderKeyGUIView);
}
}
#endif // #ifdef VOLFORMAT
burn (dk, sizeof(dk));
burn (&keyInfo, sizeof (keyInfo));
*retInfo = cryptoInfo;
return 0;
}
diff --git a/src/Format/InPlace.c b/src/Format/InPlace.c
index c3d09fb3..228e2e5f 100644
--- a/src/Format/InPlace.c
+++ b/src/Format/InPlace.c
@@ -17,40 +17,42 @@ IMPORTANT: Due to this issue, functions in this file must not directly interact
# define _WIN32_WINNT 0x0600
#endif
#include <stdlib.h>
#include <string.h>
#include <string>
#include "Tcdefs.h"
#include "Platform/Finally.h"
#include "Common.h"
#include "Crc.h"
#include "Dlgcode.h"
#include "Language.h"
#include "Tcformat.h"
#include "Volumes.h"
#include "InPlace.h"
+#include <Strsafe.h>
+
using namespace std;
using namespace VeraCrypt;
#define TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE (2048 * BYTES_PER_KB)
#define TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE (2 * TC_MAX_VOLUME_SECTOR_SIZE)
#define TC_NTFS_CONCEAL_CONSTANT 0xFF
#define TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL (64 * BYTES_PER_MB)
#define TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE (TC_TOTAL_VOLUME_HEADERS_SIZE + TC_MIN_NTFS_FS_SIZE * 2)
// If the returned value is greater than 0, it is the desired volume size in NTFS sectors (not in bytes)
// after shrinking has been performed. If there's any error, returns -1.
static __int64 NewFileSysSizeAfterShrink (HANDLE dev, const char *devicePath, int64 *totalClusterCount, DWORD *bytesPerCluster, BOOL silent)
{
NTFS_VOLUME_DATA_BUFFER ntfsVolData;
DWORD nBytesReturned;
__int64 fileSysSize, desiredNbrSectors;
// Filesystem size and sector size
@@ -134,49 +136,49 @@ BOOL CheckRequirementsForNonSysInPlaceEnc (const char *devicePath, BOOL silent)
}
/* Admin rights */
if (!IsAdmin())
{
// We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC
// status can be ignored). In case the IsAdmin() detection somehow fails, we allow the user to continue.
if (!silent)
Warning ("ADMIN_PRIVILEGES_WARN_DEVICES");
}
/* ---------- Checks that may require admin rights ----------- */
/* Access to the partition */
- strcpy ((char *) devPath, devicePath);
- ToUNICODE ((char *) devPath);
+ StringCbCopyA ((char *) devPath, sizeof(devPath), devicePath);
+ ToUNICODE ((char *) devPath, sizeof(devPath));
driveLetterNo = GetDiskDeviceDriveLetter (devPath);
if (driveLetterNo >= 0)
szRootPath[0] = (char) driveLetterNo + 'A';
- if (FakeDosNameForDevice (devicePath, dosDev, devName, FALSE) != 0)
+ if (FakeDosNameForDevice (devicePath, dosDev, sizeof(dosDev), devName, sizeof(devName),FALSE) != 0)
{
if (!silent)
{
handleWin32Error (MainDlg);
Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL");
}
return FALSE;
}
dev = OpenPartitionVolume (devName,
FALSE, // Do not require exclusive access
TRUE, // Require shared access (must be TRUE; otherwise, volume properties will not be possible to obtain)
FALSE, // Do not ask the user to confirm shared access (if exclusive fails)
FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages)
silent); // Silent mode
if (dev == INVALID_HANDLE_VALUE)
return FALSE;
@@ -331,47 +333,47 @@ int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, vol
VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
deviceSize = GetDeviceSize (volParams->volumePath);
if (deviceSize < 0)
{
// Cannot determine the size of the partition
nStatus = ERR_PARAMETER_INCORRECT;
goto closing_seq;
}
if (deviceSize < TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE)
{
ShowInPlaceEncErrMsgWAltSteps ("PARTITION_TOO_SMALL_FOR_NONSYS_INPLACE_ENC", TRUE);
nStatus = ERR_DONT_REPORT;
goto closing_seq;
}
dataAreaSize = GetVolumeDataAreaSize (volParams->hiddenVol, deviceSize);
- strcpy ((char *)deviceName, volParams->volumePath);
- ToUNICODE ((char *)deviceName);
+ StringCbCopyA ((char *)deviceName, sizeof(deviceName), volParams->volumePath);
+ ToUNICODE ((char *)deviceName, sizeof(deviceName));
driveLetter = GetDiskDeviceDriveLetter (deviceName);
- if (FakeDosNameForDevice (volParams->volumePath, dosDev, devName, FALSE) != 0)
+ if (FakeDosNameForDevice (volParams->volumePath, dosDev, sizeof(dosDev),devName, sizeof(devName),FALSE) != 0)
{
nStatus = ERR_OS_ERROR;
goto closing_seq;
}
if (IsDeviceMounted (devName))
{
dev = OpenPartitionVolume (devName,
FALSE, // Do not require exclusive access (must be FALSE; otherwise, it will not be possible to dismount the volume or obtain its properties and FSCTL_ALLOW_EXTENDED_DASD_IO will fail too)
TRUE, // Require shared access (must be TRUE; otherwise, it will not be possible to dismount the volume or obtain its properties and FSCTL_ALLOW_EXTENDED_DASD_IO will fail too)
FALSE, // Do not ask the user to confirm shared access (if exclusive fails)
FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages)
FALSE); // Non-silent mode
if (dev == INVALID_HANDLE_VALUE)
{
nStatus = ERR_DONT_REPORT;
goto closing_seq;
}
}
@@ -693,44 +695,44 @@ int EncryptPartitionInPlaceResume (HANDLE dev,
}
headerCryptoInfo = crypto_open();
if (headerCryptoInfo == NULL)
{
nStatus = ERR_OUTOFMEMORY;
goto closing_seq;
}
deviceSize = GetDeviceSize (devicePath);
if (deviceSize < 0)
{
// Cannot determine the size of the partition
nStatus = ERR_OS_ERROR;
goto closing_seq;
}
if (dev == INVALID_HANDLE_VALUE)
{
- strcpy ((char *)deviceName, devicePath);
- ToUNICODE ((char *)deviceName);
+ StringCbCopyA ((char *)deviceName, sizeof(deviceName), devicePath);
+ ToUNICODE ((char *)deviceName, sizeof(deviceName));
- if (FakeDosNameForDevice (devicePath, dosDev, devName, FALSE) != 0)
+ if (FakeDosNameForDevice (devicePath, dosDev, sizeof(dosDev),devName, sizeof(devName),FALSE) != 0)
{
nStatus = ERR_OS_ERROR;
goto closing_seq;
}
dev = OpenPartitionVolume (devName,
FALSE, // Do not require exclusive access
FALSE, // Do not require shared access
TRUE, // Ask the user to confirm shared access (if exclusive fails)
FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages)
FALSE); // Non-silent mode
if (dev == INVALID_HANDLE_VALUE)
{
nStatus = ERR_DONT_REPORT;
goto closing_seq;
}
}
// This should never be needed, but is still performed for extra safety (without checking the result)
@@ -1068,43 +1070,43 @@ closing_seq:
}
if (buf != NULL)
TCfree (buf);
if (header != NULL)
{
burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
TCfree (header);
}
if (wipeBuffer != NULL)
TCfree (wipeBuffer);
if (zeroedSectorCount > 0)
{
wchar_t msg[30000] = {0};
wchar_t sizeStr[500] = {0};
- GetSizeString (zeroedSectorCount * sectorSize, sizeStr);
+ GetSizeString (zeroedSectorCount * sectorSize, sizeStr, sizeof(sizeStr));
- wsprintfW (msg,
+ StringCbPrintfW (msg, sizeof(msg),
GetString ("ZEROED_BAD_SECTOR_COUNT"),
zeroedSectorCount,
sizeStr);
WarningDirect (msg);
}
if (nStatus != ERR_SUCCESS && nStatus != ERR_USER_ABORT)
SetLastError (dwError);
return nStatus;
}
int FastVolumeHeaderUpdate (HANDLE dev, CRYPTO_INFO *headerCryptoInfo, CRYPTO_INFO *masterCryptoInfo, __int64 deviceSize)
{
LARGE_INTEGER offset;
DWORD n;
int nStatus = ERR_SUCCESS;
byte *header;
@@ -1352,44 +1354,44 @@ static int ConcealNTFS (HANDLE dev)
do
{
Sleep (1);
}
while (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
|| WriteFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed2, NULL) == 0);
SetLastError (dwError);
return ERR_OS_ERROR;
}
return ERR_SUCCESS;
}
void ShowInPlaceEncErrMsgWAltSteps (char *iniStrId, BOOL bErr)
{
wchar_t msg[30000];
- wcscpy (msg, GetString (iniStrId));
+ StringCbCopyW (msg, sizeof(msg), GetString (iniStrId));
- wcscat (msg, L"\n\n\n");
- wcscat (msg, GetString ("INPLACE_ENC_ALTERNATIVE_STEPS"));
+ StringCbCatW (msg, sizeof(msg), L"\n\n\n");
+ StringCbCatW (msg, sizeof(msg), GetString ("INPLACE_ENC_ALTERNATIVE_STEPS"));
if (bErr)
ErrorDirect (msg);
else
WarningDirect (msg);
}
static void ExportProgressStats (__int64 bytesDone, __int64 totalSize)
{
NonSysInplaceEncBytesDone = bytesDone;
NonSysInplaceEncTotalSize = totalSize;
}
void SetNonSysInplaceEncUIStatus (int nonSysInplaceEncStatus)
{
NonSysInplaceEncStatus = nonSysInplaceEncStatus;
}
@@ -1397,50 +1399,50 @@ void SetNonSysInplaceEncUIStatus (int nonSysInplaceEncStatus)
BOOL SaveNonSysInPlaceEncSettings (int delta, WipeAlgorithmId newWipeAlgorithm)
{
int count;
char str[32];
WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE;
if (delta == 0)
return TRUE;
count = LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) + delta;
if (count < 1)
{
RemoveNonSysInPlaceEncNotifications();
return TRUE;
}
else
{
if (newWipeAlgorithm != TC_WIPE_NONE)
{
- sprintf (str, "%d", (int) newWipeAlgorithm);
+ StringCbPrintfA (str, sizeof(str), "%d", (int) newWipeAlgorithm);
SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE), strlen(str), FALSE);
}
else if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE)))
{
remove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE));
}
- sprintf (str, "%d", count);
+ StringCbPrintfA (str, sizeof(str), "%d", count);
return SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC), strlen(str), FALSE);
}
}
// Repairs damaged sectors (i.e. those with read errors) by zeroing them.
// Note that this operating fails if there are any write errors.
int ZeroUnreadableSectors (HANDLE dev, LARGE_INTEGER startOffset, int64 size, int sectorSize, uint64 *zeroedSectorCount)
{
int nStatus;
DWORD n;
int64 sectorCount;
LARGE_INTEGER workOffset;
byte *sectorBuffer = NULL;
DWORD dwError;
workOffset.QuadPart = startOffset.QuadPart;
sectorBuffer = (byte *) TCalloc (sectorSize);
diff --git a/src/Format/Tcformat.c b/src/Format/Tcformat.c
index 0074a169..d0b247fa 100644
--- a/src/Format/Tcformat.c
+++ b/src/Format/Tcformat.c
@@ -31,40 +31,42 @@
#include "Common/Dictionary.h"
#include "Common/Endian.h"
#include "Common/resource.h"
#include "Platform/Finally.h"
#include "Platform/ForEach.h"
#include "Random.h"
#include "Fat.h"
#include "InPlace.h"
#include "Resource.h"
#include "TcFormat.h"
#include "Format.h"
#include "FormatCom.h"
#include "Password.h"
#include "Progress.h"
#include "Tests.h"
#include "Cmdline.h"
#include "Volumes.h"
#include "Wipe.h"
#include "Xml.h"
+#include <Strsafe.h>
+
using namespace VeraCrypt;
enum wizard_pages
{
/* IMPORTANT: IF YOU ADD/REMOVE/MOVE ANY PAGES THAT ARE RELATED TO SYSTEM ENCRYPTION,
REVISE THE 'DECOY_OS_INSTRUCTIONS_PORTION_??' STRINGS! */
INTRO_PAGE,
SYSENC_TYPE_PAGE,
SYSENC_HIDDEN_OS_REQ_CHECK_PAGE,
SYSENC_SPAN_PAGE,
SYSENC_PRE_DRIVE_ANALYSIS_PAGE,
SYSENC_DRIVE_ANALYSIS_PAGE,
SYSENC_MULTI_BOOT_MODE_PAGE,
SYSENC_MULTI_BOOT_SYS_EQ_BOOT_PAGE,
SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE,
SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE,
SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE,
SYSENC_MULTI_BOOT_OUTCOME_PAGE,
VOLUME_TYPE_PAGE,
@@ -1200,59 +1202,59 @@ void ComboSelChangeEA (HWND hwndDlg)
}
else if (strcmp (name, "Twofish") == 0)
{
swprintf_s (hyperLink, sizeof(hyperLink) / 2, GetString ("MORE_INFO_ABOUT"), name);
SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("TWOFISH_HELP"));
}
else if (EAGetCipherCount (nIndex) > 1)
{
// Cascade
cipherIDs[cnt++] = i = EAGetLastCipher(nIndex);
while (i = EAGetPreviousCipher(nIndex, i))
{
cipherIDs[cnt] = i;
cnt++;
}
switch (cnt) // Number of ciphers in the cascade
{
case 2:
- swprintf (auxLine, GetString ("TWO_LAYER_CASCADE_HELP"),
+ StringCbPrintfW (auxLine, sizeof(auxLine), GetString ("TWO_LAYER_CASCADE_HELP"),
CipherGetName (cipherIDs[1]),
CipherGetKeySize (cipherIDs[1])*8,
CipherGetName (cipherIDs[0]),
CipherGetKeySize (cipherIDs[0])*8);
break;
case 3:
- swprintf (auxLine, GetString ("THREE_LAYER_CASCADE_HELP"),
+ StringCbPrintfW (auxLine, sizeof(auxLine), GetString ("THREE_LAYER_CASCADE_HELP"),
CipherGetName (cipherIDs[2]),
CipherGetKeySize (cipherIDs[2])*8,
CipherGetName (cipherIDs[1]),
CipherGetKeySize (cipherIDs[1])*8,
CipherGetName (cipherIDs[0]),
CipherGetKeySize (cipherIDs[0])*8);
break;
}
- wcscpy_s (hyperLink, sizeof(hyperLink) / 2, GetString ("IDC_LINK_MORE_INFO_ABOUT_CIPHER"));
+ StringCbCopyW (hyperLink, sizeof(hyperLink), GetString ("IDC_LINK_MORE_INFO_ABOUT_CIPHER"));
SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), auxLine);
}
else
{
// No info available for this encryption algorithm
SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), L"");
}
// Update hyperlink
SetWindowTextW (GetDlgItem (hwndDlg, IDC_LINK_MORE_INFO_ABOUT_CIPHER), hyperLink);
AccommodateTextField (hwndDlg, IDC_LINK_MORE_INFO_ABOUT_CIPHER, FALSE, hUserUnderlineFont);
}
}
static void VerifySizeAndUpdate (HWND hwndDlg, BOOL bUpdate)
{
BOOL bEnable = TRUE;
char szTmp[50];
@@ -1437,45 +1439,45 @@ static void UpdateSysEncProgressBar (void)
{
return;
}
if (locBootEncStatus.EncryptedAreaEnd == -1
|| locBootEncStatus.EncryptedAreaStart == -1)
{
UpdateProgressBarProc (0);
}
else
{
UpdateProgressBarProc (locBootEncStatus.EncryptedAreaEnd - locBootEncStatus.EncryptedAreaStart + 1);
if (locBootEncStatus.SetupInProgress)
{
wchar_t tmpStr[100];
// Status
if (locBootEncStatus.TransformWaitingForIdle)
- wcscpy (tmpStr, GetString ("PROGRESS_STATUS_WAITING"));
+ StringCbCopyW (tmpStr, sizeof(tmpStr), GetString ("PROGRESS_STATUS_WAITING"));
else
- wcscpy (tmpStr, GetString (SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING ? "PROGRESS_STATUS_DECRYPTING" : "PROGRESS_STATUS_ENCRYPTING"));
+ StringCbCopyW (tmpStr, sizeof(tmpStr), GetString (SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING ? "PROGRESS_STATUS_DECRYPTING" : "PROGRESS_STATUS_ENCRYPTING"));
- wcscat (tmpStr, L" ");
+ StringCbCatW (tmpStr, sizeof(tmpStr), L" ");
SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), tmpStr);
}
}
}
static void InitSysEncProgressBar (void)
{
BootEncryptionStatus locBootEncStatus;
try
{
locBootEncStatus = BootEncObj->GetStatus();
}
catch (...)
{
return;
}
if (locBootEncStatus.ConfiguredEncryptedAreaEnd == -1
@@ -1501,51 +1503,51 @@ static void UpdateSysEncControls (void)
locBootEncStatus = BootEncObj->GetStatus();
}
catch (...)
{
return;
}
EnableWindow (GetDlgItem (hCurPage, IDC_WIPE_MODE),
!locBootEncStatus.SetupInProgress
&& SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING);
SetWindowTextW (GetDlgItem (hCurPage, IDC_PAUSE),
GetString (locBootEncStatus.SetupInProgress ? "IDC_PAUSE" : "RESUME"));
EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), !locBootEncStatus.SetupInProgress && !bFirstSysEncResumeDone);
if (!locBootEncStatus.SetupInProgress)
{
wchar_t tmpStr[100];
- wcscpy (tmpStr, GetString ((SysDriveOrPartitionFullyEncrypted (TRUE) || !locBootEncStatus.DriveMounted) ?
+ StringCbCopyW (tmpStr, sizeof(tmpStr), GetString ((SysDriveOrPartitionFullyEncrypted (TRUE) || !locBootEncStatus.DriveMounted) ?
"PROGRESS_STATUS_FINISHED" : "PROGRESS_STATUS_PAUSED"));
- wcscat (tmpStr, L" ");
+ StringCbCatW (tmpStr, sizeof(tmpStr), L" ");
// Status
SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), tmpStr);
if (SysDriveOrPartitionFullyEncrypted (TRUE) || SystemEncryptionStatus == SYSENC_STATUS_NONE)
{
- wcscpy (tmpStr, GetString ("PROCESSED_PORTION_100_PERCENT"));
- wcscat (tmpStr, L" ");
+ StringCbCopyW (tmpStr, sizeof(tmpStr), GetString ("PROCESSED_PORTION_100_PERCENT"));
+ StringCbCatW (tmpStr, sizeof(tmpStr), L" ");
SetWindowTextW (GetDlgItem (hCurPage, IDC_BYTESWRITTEN), tmpStr);
}
SetWindowText (GetDlgItem (hCurPage, IDC_TIMEREMAIN), " ");
}
}
static void SysEncPause (void)
{
BootEncryptionStatus locBootEncStatus;
if (CreateSysEncMutex ())
{
EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), FALSE);
try
{
locBootEncStatus = BootEncObj->GetStatus();
}
@@ -1682,43 +1684,43 @@ static void SysEncResume (void)
SetThreadExecutionState (ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
bFirstSysEncResumeDone = TRUE;
InitSysEncProgressBar ();
UpdateSysEncProgressBar ();
UpdateSysEncControls ();
EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), TRUE);
SetTimer (MainDlg, TIMER_ID_SYSENC_PROGRESS, TIMER_INTERVAL_SYSENC_PROGRESS, NULL);
}
else
Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE");
}
static BOOL GetDevicePathForHiddenOS (void)
{
BOOL tmpbDevice = FALSE;
try
{
- strncpy (szFileName, BootEncObj->GetPartitionForHiddenOS().DevicePath.c_str(), sizeof(szFileName) - 1);
+ StringCbCopyA (szFileName, sizeof(szFileName), BootEncObj->GetPartitionForHiddenOS().DevicePath.c_str());
- CreateFullVolumePath (szDiskFile, szFileName, &tmpbDevice);
+ CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice);
}
catch (Exception &e)
{
e.Show (MainDlg);
return FALSE;
}
return (szFileName[0] != 0
&& szDiskFile[0] != 0
&& tmpbDevice);
}
// Returns TRUE if there is unallocated space greater than 64 MB (max possible slack space size) between the
// boot partition and the first partition behind it. If there's none or if an error occurs, returns FALSE.
static BOOL CheckGapBetweenSysAndHiddenOS (void)
{
try
{
SystemDriveConfiguration sysDriveCfg = BootEncObj->GetSystemDriveConfiguration();
@@ -1787,63 +1789,63 @@ static void NonSysInplaceEncResume (void)
bVolTransformThreadCancel = FALSE;
bVolTransformThreadToRun = TRUE;
UpdateNonSysInPlaceEncControls ();
LastDialogId = "NONSYS_INPLACE_ENC_IN_PROGRESS";
_beginthread (volTransformThreadFunction, 0, MainDlg);
return;
}
void ShowNonSysInPlaceEncUIStatus (void)
{
wchar_t nonSysInplaceEncUIStatus [300] = {0};
switch (NonSysInplaceEncStatus)
{
case NONSYS_INPLACE_ENC_STATUS_PAUSED:
- wcscpy (nonSysInplaceEncUIStatus, GetString ("PROGRESS_STATUS_PAUSED"));
+ StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_PAUSED"));
break;
case NONSYS_INPLACE_ENC_STATUS_PREPARING:
- wcscpy (nonSysInplaceEncUIStatus, GetString ("PROGRESS_STATUS_PREPARING"));
+ StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_PREPARING"));
break;
case NONSYS_INPLACE_ENC_STATUS_RESIZING:
- wcscpy (nonSysInplaceEncUIStatus, GetString ("PROGRESS_STATUS_RESIZING"));
+ StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_RESIZING"));
break;
case NONSYS_INPLACE_ENC_STATUS_ENCRYPTING:
- wcscpy (nonSysInplaceEncUIStatus, GetString ("PROGRESS_STATUS_ENCRYPTING"));
+ StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_ENCRYPTING"));
break;
case NONSYS_INPLACE_ENC_STATUS_FINALIZING:
- wcscpy (nonSysInplaceEncUIStatus, GetString ("PROGRESS_STATUS_FINALIZING"));
+ StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_FINALIZING"));
break;
case NONSYS_INPLACE_ENC_STATUS_FINISHED:
- wcscpy (nonSysInplaceEncUIStatus, GetString ("PROGRESS_STATUS_FINISHED"));
+ StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_FINISHED"));
break;
case NONSYS_INPLACE_ENC_STATUS_ERROR:
- wcscpy (nonSysInplaceEncUIStatus, GetString ("PROGRESS_STATUS_ERROR"));
+ StringCbCopyW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), GetString ("PROGRESS_STATUS_ERROR"));
break;
}
- wcscat (nonSysInplaceEncUIStatus, L" ");
+ StringCbCatW (nonSysInplaceEncUIStatus, sizeof(nonSysInplaceEncUIStatus), L" ");
SetWindowTextW (GetDlgItem (hCurPage, IDC_WRITESPEED), nonSysInplaceEncUIStatus);
}
void UpdateNonSysInPlaceEncControls (void)
{
EnableWindow (GetDlgItem (hCurPage, IDC_WIPE_MODE), !(bVolTransformThreadRunning || bVolTransformThreadToRun));
SetWindowTextW (GetDlgItem (hCurPage, IDC_PAUSE),
GetString ((bVolTransformThreadRunning || bVolTransformThreadToRun) ? "IDC_PAUSE" : "RESUME"));
SetWindowTextW (GetDlgItem (MainDlg, IDCANCEL), GetString (bInPlaceEncNonSysResumed ? "DEFER" : "CANCEL"));
EnableWindow (GetDlgItem (hCurPage, IDC_PAUSE), bFirstNonSysInPlaceEncResumeDone
&& NonSysInplaceEncStatus != NONSYS_INPLACE_ENC_STATUS_FINALIZING
&& NonSysInplaceEncStatus != NONSYS_INPLACE_ENC_STATUS_FINISHED);
EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), !(bVolTransformThreadRunning || bVolTransformThreadToRun) && !bFirstNonSysInPlaceEncResumeDone);
EnableWindow (GetDlgItem (MainDlg, IDC_PREV), !(bVolTransformThreadRunning || bVolTransformThreadToRun) && !bInPlaceEncNonSysResumed);
@@ -1957,44 +1959,44 @@ void DisplayRandPool (HWND hPoolDisplay, BOOL bShow)
static BOOL bRandPoolDispAscii = FALSE;
if (!bShow)
{
SetWindowText (hPoolDisplay, "");
return;
}
RandpeekBytes (randPool, sizeof (randPool));
if (memcmp (lastRandPool, randPool, sizeof(lastRandPool)) != 0)
{
outRandPoolDispBuffer[0] = 0;
for (row = 0; row < RANDPOOL_DISPLAY_ROWS; row++)
{
for (col = 0; col < RANDPOOL_DISPLAY_COLUMNS; col++)
{
tmpByte = randPool[row * RANDPOOL_DISPLAY_COLUMNS + col];
- sprintf ((char *) tmp, bRandPoolDispAscii ? ((tmpByte >= 32 && tmpByte < 255 && tmpByte != '&') ? " %c " : " . ") : "%02X ", tmpByte);
- strcat ((char *) outRandPoolDispBuffer, (char *) tmp);
+ StringCbPrintfA ((char *) tmp, sizeof(tmp), bRandPoolDispAscii ? ((tmpByte >= 32 && tmpByte < 255 && tmpByte != '&') ? " %c " : " . ") : "%02X ", tmpByte);
+ StringCbCatA ((char *) outRandPoolDispBuffer, sizeof(outRandPoolDispBuffer), (char *) tmp);
}
- strcat ((char *) outRandPoolDispBuffer, "\n");
+ StringCbCatA ((char *) outRandPoolDispBuffer, sizeof(outRandPoolDispBuffer), "\n");
}
SetWindowText (hPoolDisplay, (char *) outRandPoolDispBuffer);
memcpy (lastRandPool, randPool, sizeof(lastRandPool));
}
}
void DisplayPortionsOfKeys (HWND headerKeyHandle, HWND masterKeyHandle, char *headerKeyStr, char *masterKeyStr, BOOL hideKeys)
{
const wchar_t *hiddenKey = L"******************************** ";
SetWindowTextW (headerKeyHandle, hideKeys ? hiddenKey : (SingleStringToWide (headerKeyStr) + GetString ("TRIPLE_DOT_GLYPH_ELLIPSIS")).c_str());
SetWindowTextW (masterKeyHandle, hideKeys ? hiddenKey : (SingleStringToWide (masterKeyStr) + GetString ("TRIPLE_DOT_GLYPH_ELLIPSIS")).c_str());
}
static void WipeAbort (void)
{
EnableWindow (GetDlgItem (hCurPage, IDC_ABORT_BUTTON), FALSE);
@@ -2283,41 +2285,41 @@ static void __cdecl volTransformThreadFunction (void *hwndDlgArg)
goto cancel;
}
if (bDevice)
{
if (MessageBoxW (hwndDlg, GetString ("ADMIN_PRIVILEGES_WARN_DEVICES"), lpszTitle, MB_OKCANCEL|MB_ICONWARNING|MB_DEFBUTTON2) == IDCANCEL)
goto cancel;
}
}
if (!bInPlaceEncNonSys)
{
if (!bDevice)
{
int x = _access (szDiskFile, 06);
if (x == 0 || errno != ENOENT)
{
wchar_t szTmp[512];
if (! ((bHiddenVol && !bHiddenVolHost) && errno != EACCES)) // Only ask ask for permission to overwrite an existing volume if we're not creating a hidden volume
{
- _snwprintf (szTmp, sizeof szTmp / 2,
+ StringCbPrintfW (szTmp, sizeof szTmp,
GetString (errno == EACCES ? "READONLYPROMPT" : "OVERWRITEPROMPT"),
szDiskFile);
x = MessageBoxW (hwndDlg, szTmp, lpszTitle, YES_NO|MB_ICONWARNING|MB_DEFBUTTON2);
if (x != IDYES)
goto cancel;
}
}
if (_access (szDiskFile, 06) != 0)
{
if (errno == EACCES)
{
if (_chmod (szDiskFile, _S_IREAD | _S_IWRITE) != 0)
{
MessageBoxW (hwndDlg, GetString ("ACCESSMODEFAIL"), lpszTitle, ICON_HAND);
goto cancel;
}
}
@@ -2446,41 +2448,41 @@ static void __cdecl volTransformThreadFunction (void *hwndDlgArg)
wchar_t szMsg[8192];
handleError (hwndDlg, nStatus);
if (bInPlaceEncNonSys)
{
if (bInPlaceEncNonSysResumed)
{
SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED);
Error ("INPLACE_ENC_GENERIC_ERR_RESUME");
}
else
{
SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_ERROR);
ShowInPlaceEncErrMsgWAltSteps ("INPLACE_ENC_GENERIC_ERR_ALT_STEPS", TRUE);
}
}
else if (!(bHiddenVolHost && hiddenVolHostDriveNo < 0)) // If the error was not that the hidden volume host could not be mounted (this error has already been reported to the user)
{
- swprintf (szMsg, GetString ("CREATE_FAILED"), szDiskFile);
+ StringCbPrintfW (szMsg, sizeof(szMsg), GetString ("CREATE_FAILED"), szDiskFile);
MessageBoxW (hwndDlg, szMsg, lpszTitle, ICON_HAND);
}
if (!bDevice && !(bHiddenVol && !bHiddenVolHost)) // If we're not creating a hidden volume and if it's a file container
{
remove (szDiskFile); // Delete the container
}
goto cancel;
}
else
{
/* Volume successfully created */
RestoreDefaultKeyFilesParam ();
if (bDevice && !bInPlaceEncNonSys)
{
// Handle assigned drive letter (if any)
@@ -2887,62 +2889,62 @@ int PrintFreeSpace (HWND hwndTextBox, char *lpszDrive, PLARGE_INTEGER lDiskFree)
{
if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume
nResourceString = "MAX_HIDVOL_SIZE_MB";
else if (bDevice)
nResourceString = "DEVICE_FREE_MB";
else
nResourceString = "DISK_FREE_MB";
}
else
{
if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume
nResourceString = "MAX_HIDVOL_SIZE_GB";
else if (bDevice)
nResourceString = "DEVICE_FREE_GB";
else
nResourceString = "DISK_FREE_GB";
}
if (bHiddenVol && !bHiddenVolHost) // If it's a hidden volume
{
- _snwprintf (szTmp2, sizeof szTmp2 / 2, GetString (nResourceString), ((double) lDiskFree->QuadPart) / nMultiplier);
+ StringCbPrintfW (szTmp2, sizeof szTmp2, GetString (nResourceString), ((double) lDiskFree->QuadPart) / nMultiplier);
SetWindowTextW (GetDlgItem (hwndTextBox, IDC_SIZEBOX), szTmp2);
}
else
- _snwprintf (szTmp2, sizeof szTmp2 / 2, GetString (nResourceString), lpszDrive, ((double) lDiskFree->QuadPart) / nMultiplier);
+ StringCbPrintfW (szTmp2, sizeof szTmp2, GetString (nResourceString), lpszDrive, ((double) lDiskFree->QuadPart) / nMultiplier);
SetWindowTextW (hwndTextBox, szTmp2);
if (lDiskFree->QuadPart % (__int64) BYTES_PER_MB != 0)
nMultiplier = BYTES_PER_KB;
return nMultiplier;
}
void DisplaySizingErrorText (HWND hwndTextBox)
{
wchar_t szTmp[1024];
if (translateWin32Error (szTmp, sizeof (szTmp) / sizeof(szTmp[0])))
{
wchar_t szTmp2[1024];
- wsprintfW (szTmp2, L"%s\n%s", GetString ("CANNOT_CALC_SPACE"), szTmp);
+ StringCbPrintfW (szTmp2, sizeof(szTmp2), L"%s\n%s", GetString ("CANNOT_CALC_SPACE"), szTmp);
SetWindowTextW (hwndTextBox, szTmp2);
}
else
{
SetWindowText (hwndTextBox, "");
}
}
void EnableDisableFileNext (HWND hComboBox, HWND hMainButton)
{
LPARAM nIndex = SendMessage (hComboBox, CB_GETCURSEL, 0, 0);
if (bHistory && nIndex == CB_ERR)
{
EnableWindow (hMainButton, FALSE);
SetFocus (hComboBox);
}
else
{
EnableWindow (hMainButton, TRUE);
SetFocus (hMainButton);
@@ -3135,191 +3137,191 @@ BOOL QueryFreeSpace (HWND hwndDlg, HWND hwndTextBox, BOOL display)
nVolumeSize = lDiskFree.QuadPart;
if (display)
nMultiplier = PrintFreeSpace (hwndTextBox, szDiskFile, &lDiskFree);
nUIVolumeSize = lDiskFree.QuadPart / nMultiplier;
}
return TRUE;
}
}
static BOOL FinalPreTransformPrompts (void)
{
int x;
wchar_t szTmp[4096];
int driveNo;
WCHAR deviceName[MAX_PATH];
- strcpy ((char *)deviceName, szFileName);
- ToUNICODE ((char *)deviceName);
+ StringCbCopyA ((char *)deviceName, sizeof(deviceName), szFileName);
+ ToUNICODE ((char *)deviceName, sizeof(deviceName));
driveNo = GetDiskDeviceDriveLetter (deviceName);
if (!(bHiddenVol && !bHiddenVolHost)) // Do not ask for permission to overwrite an existing volume if we're creating a hidden volume within it
{
wchar_t drive[128];
wchar_t volumeLabel[128];
wchar_t *type;
BOOL bTmpIsPartition = FALSE;
type = GetPathType (szFileName, !bInPlaceEncNonSys, &bTmpIsPartition);
if (driveNo != -1)
{
if (!GetDriveLabel (driveNo, volumeLabel, sizeof (volumeLabel)))
volumeLabel[0] = 0;
- swprintf_s (drive, sizeof (drive)/2, volumeLabel[0] ? L" (%hc: '%s')" : L" (%hc:%s)", 'A' + driveNo, volumeLabel[0] ? volumeLabel : L"");
+ StringCbPrintfW (drive, sizeof (drive), volumeLabel[0] ? L" (%hc: '%s')" : L" (%hc:%s)", 'A' + driveNo, volumeLabel[0] ? volumeLabel : L"");
}
else
{
drive[0] = 0;
volumeLabel[0] = 0;
}
if (bHiddenOS && bHiddenVolHost)
- swprintf (szTmp, GetString ("OVERWRITEPROMPT_DEVICE_HIDDEN_OS_PARTITION"), szFileName, drive);
+ StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("OVERWRITEPROMPT_DEVICE_HIDDEN_OS_PARTITION"), szFileName, drive);
else
- swprintf (szTmp, GetString (bInPlaceEncNonSys ? "NONSYS_INPLACE_ENC_CONFIRM" : "OVERWRITEPROMPT_DEVICE"), type, szFileName, drive);
+ StringCbPrintfW (szTmp, sizeof(szTmp), GetString (bInPlaceEncNonSys ? "NONSYS_INPLACE_ENC_CONFIRM" : "OVERWRITEPROMPT_DEVICE"), type, szFileName, drive);
x = MessageBoxW (MainDlg, szTmp, lpszTitle, YES_NO | MB_ICONWARNING | (bInPlaceEncNonSys ? MB_DEFBUTTON1 : MB_DEFBUTTON2));
if (x != IDYES)
return FALSE;
if (driveNo != -1 && bTmpIsPartition && !bInPlaceEncNonSys)
{
float percentFreeSpace = 100.0;
__int64 occupiedBytes = 0;
// Do a second check. If we find that the partition contains more than 1GB of data or more than 12%
// of its space is occupied, we will display an extra warning, however, this time it won't be a Yes/No
// dialog box (because users often ignore such dialog boxes).
if (GetStatsFreeSpaceOnPartition (szFileName, &percentFreeSpace, &occupiedBytes, TRUE) != -1)
{
if (occupiedBytes > BYTES_PER_GB && percentFreeSpace < 99.99 // "percentFreeSpace < 99.99" is needed because an NTFS filesystem larger than several terabytes can have more than 1GB of data in use, even if there are no files stored on it.
|| percentFreeSpace < 88) // A 24-MB NTFS filesystem has 11.5% of space in use even if there are no files stored on it.
{
wchar_t tmpMcMsg [8000];
wchar_t tmpMcOption1 [500];
wchar_t tmpMcOptionCancel [50];
- wcscpy (tmpMcMsg, GetString("OVERWRITEPROMPT_DEVICE_SECOND_WARNING_LOTS_OF_DATA"));
- wcscpy (tmpMcOption1, GetString("ERASE_FILES_BY_CREATING_VOLUME"));
- wcscpy (tmpMcOptionCancel, GetString("CANCEL"));
+ StringCbCopyW (tmpMcMsg, sizeof(tmpMcMsg), GetString("OVERWRITEPROMPT_DEVICE_SECOND_WARNING_LOTS_OF_DATA"));
+ StringCbCopyW (tmpMcOption1, sizeof(tmpMcOption1), GetString("ERASE_FILES_BY_CREATING_VOLUME"));
+ StringCbCopyW (tmpMcOptionCancel, sizeof(tmpMcOptionCancel), GetString("CANCEL"));
- wcscat (tmpMcMsg, L"\n\n");
- wcscat (tmpMcMsg, GetString("DRIVE_LETTER_ITEM"));
- swprintf_s (szTmp, sizeof (szTmp)/2, L"%hc:", 'A' + driveNo);
- wcscat (tmpMcMsg, szTmp);
+ StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), L"\n\n");
+ StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), GetString("DRIVE_LETTER_ITEM"));
+ StringCbPrintfW (szTmp, sizeof (szTmp), L"%hc:", 'A' + driveNo);
+ StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), szTmp);
- wcscat (tmpMcMsg, L"\n");
- wcscat (tmpMcMsg, GetString("LABEL_ITEM"));
- wcscat (tmpMcMsg, volumeLabel[0] != 0 ? volumeLabel : GetString("NOT_APPLICABLE_OR_NOT_AVAILABLE"));
+ StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), L"\n");
+ StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), GetString("LABEL_ITEM"));
+ StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), volumeLabel[0] != 0 ? volumeLabel : GetString("NOT_APPLICABLE_OR_NOT_AVAILABLE"));
- wcscat (tmpMcMsg, L"\n");
- wcscat (tmpMcMsg, GetString("SIZE_ITEM"));
- GetSizeString (nVolumeSize, szTmp);
- wcscat (tmpMcMsg, szTmp);
+ StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), L"\n");
+ StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), GetString("SIZE_ITEM"));
+ GetSizeString (nVolumeSize, szTmp, sizeof(szTmp));
+ StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), szTmp);
- wcscat (tmpMcMsg, L"\n");
- wcscat (tmpMcMsg, GetString("PATH_ITEM"));
- wcscat (tmpMcMsg, deviceName);
+ StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), L"\n");
+ StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), GetString("PATH_ITEM"));
+ StringCbCatW (tmpMcMsg, sizeof(tmpMcMsg), deviceName);
wchar_t *tmpStr[] = {L"", tmpMcMsg, tmpMcOption1, tmpMcOptionCancel, 0};
switch (AskMultiChoice ((void **) tmpStr, TRUE))
{
case 1:
// Proceed
// NOP
break;
default:
return FALSE;
}
}
}
}
}
return TRUE;
}
void HandleOldAssignedDriveLetter (void)
{
if (bDevice)
{
// Handle assigned drive letter (if any)
WCHAR deviceName[MAX_PATH];
int driveLetter = -1;
- strcpy ((char *)deviceName, szDiskFile);
- ToUNICODE ((char *)deviceName);
+ StringCbCopyA ((char *)deviceName, sizeof(deviceName), szDiskFile);
+ ToUNICODE ((char *)deviceName, sizeof(deviceName));
driveLetter = GetDiskDeviceDriveLetter (deviceName);
if (!bHiddenVolHost
&& !bHiddenOS
&& driveLetter > 1) // If a drive letter is assigned to the device, but not A: or B:
{
char rootPath[] = { (char) driveLetter + 'A', ':', '\\', 0 };
wchar_t szTmp[8192];
- swprintf (szTmp, GetString ("AFTER_FORMAT_DRIVE_LETTER_WARN"), rootPath[0], rootPath[0], rootPath[0], rootPath[0]);
+ StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("AFTER_FORMAT_DRIVE_LETTER_WARN"), rootPath[0], rootPath[0], rootPath[0], rootPath[0]);
MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING);
}
}
}
// Returns TRUE if it makes sense to ask the user whether he wants to store files larger than 4GB in the volume.
static BOOL FileSize4GBLimitQuestionNeeded (void)
{
uint64 dataAreaSize = GetVolumeDataAreaSize (bHiddenVol && !bHiddenVolHost, nVolumeSize);
return (dataAreaSize > 4 * BYTES_PER_GB + TC_MIN_FAT_FS_SIZE
&& dataAreaSize <= TC_MAX_FAT_SECTOR_COUNT * GetFormatSectorSize());
}
/* Except in response to the WM_INITDIALOG message, the dialog box procedure
should return nonzero if it processes the message, and zero if it does
not. - see DialogProc */
BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static char PageDebugId[128];
WORD lw = LOWORD (wParam);
WORD hw = HIWORD (wParam);
hCurPage = hwndDlg;
switch (uMsg)
{
case WM_INITDIALOG:
LocalizeDialog (hwndDlg, "IDD_VOL_CREATION_WIZARD_DLG");
- sprintf (PageDebugId, "FORMAT_PAGE_%d", nCurPageNo);
+ StringCbPrintfA (PageDebugId, sizeof(PageDebugId), "FORMAT_PAGE_%d", nCurPageNo);
LastDialogId = PageDebugId;
switch (nCurPageNo)
{
case INTRO_PAGE:
SendMessage (GetDlgItem (hwndDlg, IDC_FILE_CONTAINER), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE);
SendMessage (GetDlgItem (hwndDlg, IDC_NONSYS_DEVICE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE);
SendMessage (GetDlgItem (hwndDlg, IDC_SYS_DEVICE), WM_SETFONT, (WPARAM) hUserBoldFont, (LPARAM) TRUE);
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("INTRO_TITLE"));
ToHyperlink (hwndDlg, IDC_MORE_INFO_ON_CONTAINERS);
ToHyperlink (hwndDlg, IDC_MORE_INFO_ON_SYS_ENCRYPTION);
EnableWindow (GetDlgItem (hwndDlg, IDC_STD_VOL), TRUE);
EnableWindow (GetDlgItem (hwndDlg, IDC_HIDDEN_VOL), TRUE);
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV"));
@@ -3743,50 +3745,50 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
AddComboPair (GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO), HashGetName(hid), hid);
}
SelectAlgo (GetDlgItem (hwndDlg, IDC_COMBO_BOX_HASH_ALGO), &hash_algo);
ToHyperlink (hwndDlg, IDC_LINK_HASH_INFO);
// Wizard buttons
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV"));
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE);
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE);
}
break;
case SIZE_PAGE:
{
wchar_t str[1000];
if (bHiddenVolHost)
{
- wcsncpy (str, GetString ("SIZE_HELP_HIDDEN_HOST_VOL"), sizeof (str) / 2);
+ StringCbCopyW (str, sizeof(str), GetString ("SIZE_HELP_HIDDEN_HOST_VOL"));
}
else
{
- wcsncpy (str, GetString (bHiddenVol ? "SIZE_HELP_HIDDEN_VOL" : "SIZE_HELP"), sizeof (str) / 2);
+ StringCbCopyW (str, sizeof(str), GetString (bHiddenVol ? "SIZE_HELP_HIDDEN_VOL" : "SIZE_HELP"));
}
if (bDevice && !(bHiddenVol && !bHiddenVolHost)) // If raw device but not a hidden volume
{
- _snwprintf (str, sizeof str / 2, L"%s%s",
+ StringCbPrintfW (str, sizeof str, L"%s%s",
GetString ((bHiddenOS && bHiddenVol) ? "SIZE_PARTITION_HIDDEN_SYSENC_HELP" : "SIZE_PARTITION_HELP"),
(bHiddenVolHost && !bHiddenOS) ? GetString ("SIZE_PARTITION_HIDDEN_VOL_HELP") : L"");
}
SendMessage (GetDlgItem (hwndDlg, IDC_SPACE_LEFT), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE);
SendMessage (GetDlgItem (hwndDlg, IDC_SIZEBOX), EM_LIMITTEXT, 12, 0);
if(!QueryFreeSpace (hwndDlg, GetDlgItem (hwndDlg, IDC_SPACE_LEFT), TRUE))
{
nUIVolumeSize=0;
nVolumeSize=0;
SetWindowTextW (GetDlgItem (hwndDlg, IDC_SIZEBOX), GetString ("UNKNOWN"));
EnableWindow (GetDlgItem (hwndDlg, IDC_SIZEBOX), FALSE);
EnableWindow (GetDlgItem (hwndDlg, IDC_KB), FALSE);
EnableWindow (GetDlgItem (hwndDlg, IDC_MB), FALSE);
EnableWindow (GetDlgItem (hwndDlg, IDC_GB), FALSE);
}
else if (bDevice && !(bHiddenVol && !bHiddenVolHost)) // If raw device but not a hidden volume
{
@@ -3806,41 +3808,41 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
SendMessage (GetDlgItem (hwndDlg, IDC_KB), BM_SETCHECK, BST_UNCHECKED, 0);
SendMessage (GetDlgItem (hwndDlg, IDC_MB), BM_SETCHECK, BST_UNCHECKED, 0);
SendMessage (GetDlgItem (hwndDlg, IDC_GB), BM_SETCHECK, BST_UNCHECKED, 0);
switch (nMultiplier)
{
case BYTES_PER_KB:
SendMessage (GetDlgItem (hwndDlg, IDC_KB), BM_SETCHECK, BST_CHECKED, 0);
break;
case BYTES_PER_MB:
SendMessage (GetDlgItem (hwndDlg, IDC_MB), BM_SETCHECK, BST_CHECKED, 0);
break;
case BYTES_PER_GB:
SendMessage (GetDlgItem (hwndDlg, IDC_GB), BM_SETCHECK, BST_CHECKED, 0);
break;
}
if (nUIVolumeSize != 0)
{
char szTmp[32];
- sprintf (szTmp, "%I64u", nUIVolumeSize);
+ StringCbPrintfA (szTmp, sizeof(szTmp), "%I64u", nUIVolumeSize);
SetWindowText (GetDlgItem (hwndDlg, IDC_SIZEBOX), szTmp);
}
SetFocus (GetDlgItem (hwndDlg, IDC_SIZEBOX));
SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), str);
if (bHiddenVol)
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVolHost ? "SIZE_HIDVOL_HOST_TITLE" : "SIZE_HIDVOL_TITLE"));
else
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SIZE_TITLE"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV"));
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE);
VerifySizeAndUpdate (hwndDlg, FALSE);
@@ -3865,78 +3867,78 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV"));
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), !bInPlaceEncNonSys);
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE);
break;
case PASSWORD_PAGE:
{
wchar_t str[1000];
hPasswordInputField = GetDlgItem (hwndDlg, IDC_PASSWORD);
hVerifyPasswordInputField = GetDlgItem (hwndDlg, IDC_VERIFY);
if (SysEncInEffect ())
{
ToBootPwdField (hwndDlg, IDC_PASSWORD);
ToBootPwdField (hwndDlg, IDC_VERIFY);
- sprintf (OrigKeyboardLayout, "%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF);
+ StringCbPrintfA (OrigKeyboardLayout, sizeof(OrigKeyboardLayout), "%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF);
if ((DWORD) GetKeyboardLayout (NULL) != 0x00000409 && (DWORD) GetKeyboardLayout (NULL) != 0x04090409)
{
DWORD keybLayout = (DWORD) LoadKeyboardLayout ("00000409", KLF_ACTIVATE);
if (keybLayout != 0x00000409 && keybLayout != 0x04090409)
{
Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION");
EndMainDlg (MainDlg);
return 1;
}
bKeyboardLayoutChanged = TRUE;
}
ShowWindow(GetDlgItem(hwndDlg, IDC_SHOW_PASSWORD), SW_HIDE);
if (SetTimer (MainDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0)
{
Error ("CANNOT_SET_TIMER");
EndMainDlg (MainDlg);
return 1;
}
}
if (bHiddenVolHost)
{
- wcsncpy (str, GetString (bHiddenOS ? "PASSWORD_SYSENC_OUTERVOL_HELP" : "PASSWORD_HIDDENVOL_HOST_HELP"), sizeof (str) / 2);
+ StringCbCopyW (str, sizeof(str), GetString (bHiddenOS ? "PASSWORD_SYSENC_OUTERVOL_HELP" : "PASSWORD_HIDDENVOL_HOST_HELP"));
}
else if (bHiddenVol)
{
- _snwprintf (str, sizeof str / 2, L"%s%s",
+ StringCbPrintfW (str, sizeof str, L"%s%s",
GetString (bHiddenOS ? "PASSWORD_HIDDEN_OS_HELP" : "PASSWORD_HIDDENVOL_HELP"),
GetString ("PASSWORD_HELP"));
}
else
{
- wcsncpy (str, GetString ("PASSWORD_HELP"), sizeof (str) / 2);
+ StringCbCopyW (str, sizeof(str), GetString ("PASSWORD_HELP"));
}
SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0);
SendMessage (GetDlgItem (hwndDlg, IDC_VERIFY), EM_LIMITTEXT, MAX_PASSWORD, 0);
SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), szRawPassword);
SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), szVerify);
SetFocus (GetDlgItem (hwndDlg, IDC_PASSWORD));
SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable && !SysEncInEffect());
EnableWindow (GetDlgItem (hwndDlg, IDC_KEY_FILES), KeyFilesEnable);
SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), str);
if (CreatingHiddenSysVol())
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("PASSWORD_HIDDEN_OS_TITLE"));
else if (bHiddenVol)
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVolHost ? "PASSWORD_HIDVOL_HOST_TITLE" : "PASSWORD_HIDVOL_TITLE"));
else if (WizardMode == WIZARD_MODE_SYS_DEVICE)
@@ -3949,56 +3951,56 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE);
VerifyPasswordAndUpdate (hwndDlg, GetDlgItem (GetParent (hwndDlg), IDC_NEXT),
GetDlgItem (hwndDlg, IDC_PASSWORD),
GetDlgItem (hwndDlg, IDC_VERIFY),
NULL,
NULL,
KeyFilesEnable && FirstKeyFile!=NULL && !SysEncInEffect());
volumePassword.Length = strlen ((char *) volumePassword.Text);
}
break;
case FILESYS_PAGE:
{
wchar_t szTmp[8192];
Init2RadButtonPageYesNo (nNeedToStoreFilesOver4GB);
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("FILESYS_PAGE_TITLE"));
- wcscpy (szTmp, GetString ("FILESYS_PAGE_HELP_QUESTION"));
+ StringCbCopyW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_QUESTION"));
if (bHiddenVolHost)
- wcscat (szTmp, L"\n\n");
+ StringCbCatW (szTmp, sizeof(szTmp), L"\n\n");
else
{
- wcscat (szTmp, L"\n\n\n");
- wcscat (szTmp, GetString ("NOTE_BEGINNING"));
+ StringCbCatW (szTmp, sizeof(szTmp), L"\n\n\n");
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("NOTE_BEGINNING"));
}
- wcscat (szTmp, GetString ("FILESYS_PAGE_HELP_EXPLANATION"));
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_EXPLANATION"));
if (bHiddenVolHost)
{
- wcscat (szTmp, L" ");
- wcscat (szTmp, GetString ("FILESYS_PAGE_HELP_EXPLANATION_HIDVOL"));
+ StringCbCatW (szTmp, sizeof(szTmp), L" ");
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_EXPLANATION_HIDVOL"));
}
SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), szTmp);
}
break;
case SYSENC_COLLECTING_RANDOM_DATA_PAGE:
case NONSYS_INPLACE_ENC_RAND_DATA_PAGE:
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("COLLECTING_RANDOM_DATA_TITLE"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV"));
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE);
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE);
SetTimer (GetParent (hwndDlg), TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL);
hRandPoolSys = GetDlgItem (hwndDlg, IDC_SYS_POOL_CONTENTS);
SendMessage (GetDlgItem (hwndDlg, IDC_SYS_POOL_CONTENTS), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE);
@@ -4032,41 +4034,41 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
case SYSENC_RESCUE_DISK_CREATION_PAGE:
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("RESCUE_DISK"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV"));
SetWindowTextW (GetDlgItem (hwndDlg, IDT_RESCUE_DISK_INFO), GetString ("RESCUE_DISK_INFO"));
SetDlgItemText (hwndDlg, IDC_RESCUE_DISK_ISO_PATH, szRescueDiskISO);
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), (GetWindowTextLength (GetDlgItem (hwndDlg, IDC_RESCUE_DISK_ISO_PATH)) > 1));
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE);
break;
case SYSENC_RESCUE_DISK_BURN_PAGE:
{
wchar_t szTmp[8192];
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bDontVerifyRescueDisk ? "RESCUE_DISK_CREATED_TITLE" : "RESCUE_DISK_RECORDING_TITLE"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV"));
- _snwprintf (szTmp, sizeof szTmp / 2,
+ StringCbPrintfW (szTmp, sizeof szTmp,
GetString (bDontVerifyRescueDisk ? "RESCUE_DISK_BURN_INFO_NO_CHECK" : "RESCUE_DISK_BURN_INFO"),
szRescueDiskISO, IsWindowsIsoBurnerAvailable() ? L"" : GetString ("RESCUE_DISK_BURN_INFO_NONWIN_ISO_BURNER"));
SetWindowTextW (GetDlgItem (hwndDlg, IDT_RESCUE_DISK_BURN_INFO), szTmp);
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE);
/* The 'Back' button must be disabled now because the user could burn a Rescue Disk, then go back, and
generate a different master key, which would cause the Rescue Disk verification to fail (the result
would be confusion and bug reports). */
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE);
if (IsWindowsIsoBurnerAvailable())
SetWindowTextW (GetDlgItem (hwndDlg, IDC_DOWNLOAD_CD_BURN_SOFTWARE), GetString ("LAUNCH_WIN_ISOBURN"));
ToHyperlink (hwndDlg, IDC_DOWNLOAD_CD_BURN_SOFTWARE);
if (IsWindowsIsoBurnerAvailable() && !bDontVerifyRescueDisk)
LaunchWindowsIsoBurner (hwndDlg, szRescueDiskISO);
}
break;
@@ -4112,41 +4114,41 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
}
break;
case SYSENC_PRETEST_INFO_PAGE:
if (bHiddenOS)
{
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDDEN_OS_CREATION_PREINFO_TITLE"));
SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("HIDDEN_OS_CREATION_PREINFO_HELP"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("START"));
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), FALSE);
}
else
{
wchar_t finalMsg[8024] = {0};
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("SYS_ENCRYPTION_PRETEST_TITLE"));
try
{
- wsprintfW (finalMsg,
+ StringCbPrintfW (finalMsg, sizeof(finalMsg),
GetString ("SYS_ENCRYPTION_PRETEST_INFO"),
BootEncObj->GetSystemDriveConfiguration().DriveNumber);
}
catch (Exception &e)
{
e.Show (hwndDlg);
EndMainDlg (MainDlg);
return 0;
}
SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), finalMsg);
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("TEST"));
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_PREV), TRUE);
}
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV"));
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE);
break;
@@ -4476,46 +4478,46 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
if (!bHiddenVolHost && bHiddenVol && !bHiddenVolFinished)
{
wchar_t msg[4096];
nNeedToStoreFilesOver4GB = -1;
if (bHiddenOS)
{
wchar_t szMaxRecomOuterVolFillSize[100];
__int64 maxRecomOuterVolFillSize = 0;
// Determine the maximum recommended total size of files that can be copied to the outer volume
// while leaving enough space for the hidden volume, which must contain a clone of the OS
maxRecomOuterVolFillSize = nVolumeSize - GetSystemPartitionSize();
// -50% reserve for filesystem "peculiarities"
maxRecomOuterVolFillSize /= 2;
- swprintf (szMaxRecomOuterVolFillSize, L"%I64d %s", maxRecomOuterVolFillSize / BYTES_PER_MB, GetString ("MB"));
+ StringCbPrintfW (szMaxRecomOuterVolFillSize, sizeof(szMaxRecomOuterVolFillSize), L"%I64d %s", maxRecomOuterVolFillSize / BYTES_PER_MB, GetString ("MB"));
- swprintf (msg, GetString ("HIDVOL_HOST_FILLING_HELP_SYSENC"), hiddenVolHostDriveNo + 'A', szMaxRecomOuterVolFillSize);
+ StringCbPrintfW (msg, sizeof(msg), GetString ("HIDVOL_HOST_FILLING_HELP_SYSENC"), hiddenVolHostDriveNo + 'A', szMaxRecomOuterVolFillSize);
}
else
- swprintf (msg, GetString ("HIDVOL_HOST_FILLING_HELP"), hiddenVolHostDriveNo + 'A');
+ StringCbPrintfW (msg, sizeof(msg), GetString ("HIDVOL_HOST_FILLING_HELP"), hiddenVolHostDriveNo + 'A');
SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), msg);
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString ("HIDVOL_HOST_FILLING_TITLE"));
}
else
{
if (bHiddenOS)
SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString ("SYSENC_HIDDEN_VOL_FORMAT_FINISHED_HELP"));
else
{
SetWindowTextW (GetDlgItem (hwndDlg, IDC_BOX_HELP), GetString (bInPlaceEncNonSys ? "NONSYS_INPLACE_ENC_FINISHED_INFO" : "FORMAT_FINISHED_HELP"));
bConfirmQuit = FALSE;
}
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_BOX_TITLE), GetString (bHiddenVol ? "HIDVOL_FORMAT_FINISHED_TITLE" : "FORMAT_FINISHED_TITLE"));
}
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), GetString ("NEXT"));
SetWindowTextW (GetDlgItem (GetParent (hwndDlg), IDC_PREV), GetString ("PREV"));
@@ -4721,43 +4723,43 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
case SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE:
case SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE:
case SYSENC_PRE_DRIVE_ANALYSIS_PAGE:
if (lw == IDC_CHOICE1 || lw == IDC_CHOICE2)
{
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE);
return 1;
}
break;
}
if (nCurPageNo == FILESYS_PAGE && (lw == IDC_CHOICE1 || lw == IDC_CHOICE2))
{
if (bWarnOuterVolSuitableFileSys && lw == IDC_CHOICE1 && bHiddenVolHost)
{
wchar_t szTmp [4096];
bWarnOuterVolSuitableFileSys = FALSE; // Do not show this warning anymore (this also prevents potential endless repetition due to some race conditions)
- wcscpy (szTmp, GetString ("FILESYS_PAGE_HELP_EXPLANATION_HIDVOL"));
- wcscat (szTmp, L"\n\n");
- wcscat (szTmp, GetString ("FILESYS_PAGE_HELP_EXPLANATION_HIDVOL_CONFIRM"));
+ StringCbCopyW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_EXPLANATION_HIDVOL"));
+ StringCbCatW (szTmp, sizeof(szTmp), L"\n\n");
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("FILESYS_PAGE_HELP_EXPLANATION_HIDVOL_CONFIRM"));
if (MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2) == IDNO)
{
nNeedToStoreFilesOver4GB = 0;
Init2RadButtonPageYesNo (nNeedToStoreFilesOver4GB);
}
}
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE);
return 1;
}
if (lw == IDC_HIDDEN_VOL && nCurPageNo == VOLUME_TYPE_PAGE)
{
bHiddenVol = TRUE;
bHiddenVolHost = TRUE;
bInPlaceEncNonSys = FALSE;
return 1;
}
@@ -4817,42 +4819,42 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
if (lw == IDC_LIST_BOX
&& (hw == LBN_SELCHANGE || hw == LBN_DBLCLK))
{
BOOL tmpbDevice = FALSE;
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), FALSE);
int selPartitionItemId = (int) SendMessage (GetDlgItem (hwndDlg, IDC_LIST_BOX), LB_GETCURSEL, 0, 0);
if (selPartitionItemId == LB_ERR)
{
// Deselect all
SendMessage (GetDlgItem (hwndDlg, IDC_LIST_BOX), LB_SETCURSEL, (WPARAM) -1, 0);
SetFocus (GetDlgItem (MainDlg, IDC_NEXT));
return 1;
}
SetFocus (GetDlgItem (MainDlg, IDC_NEXT));
- strcpy (szFileName, DeferredNonSysInPlaceEncDevices [selPartitionItemId].Path.c_str());
- CreateFullVolumePath (szDiskFile, szFileName, &tmpbDevice);
+ StringCbCopyA (szFileName, sizeof(szFileName), DeferredNonSysInPlaceEncDevices [selPartitionItemId].Path.c_str());
+ CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice);
nVolumeSize = GetDeviceSize (szDiskFile);
if (nVolumeSize == -1)
{
handleWin32Error (MainDlg);
return 1;
}
EnableWindow (GetDlgItem (GetParent (hwndDlg), IDC_NEXT), TRUE);
return 1;
}
break;
case NONSYS_INPLACE_ENC_ENCRYPTION_PAGE:
{
switch (lw)
{
case IDC_PAUSE:
@@ -5281,41 +5283,41 @@ BOOL CALLBACK PageDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
return 1;
}
if (lw == IDC_DISPLAY_KEYS && nCurPageNo == SYSENC_KEYS_GEN_PAGE)
{
showKeys = IsButtonChecked (GetDlgItem (hCurPage, IDC_DISPLAY_KEYS));
DisplayPortionsOfKeys (GetDlgItem (hwndDlg, IDC_HEADER_KEY), GetDlgItem (hwndDlg, IDC_DISK_KEY), HeaderKeyGUIView, MasterKeyGUIView, !showKeys);
return 1;
}
if (nCurPageNo == SYSENC_RESCUE_DISK_CREATION_PAGE)
{
if (lw == IDC_BROWSE)
{
char tmpszRescueDiskISO [TC_MAX_PATH+1];
if (!BrowseFiles (hwndDlg, "OPEN_TITLE", tmpszRescueDiskISO, FALSE, TRUE, NULL))
return 1;
- strcpy (szRescueDiskISO, tmpszRescueDiskISO);
+ StringCbCopyA (szRescueDiskISO, sizeof(szRescueDiskISO), tmpszRescueDiskISO);
SetDlgItemText (hwndDlg, IDC_RESCUE_DISK_ISO_PATH, szRescueDiskISO);
EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), (GetWindowTextLength (GetDlgItem (hwndDlg, IDC_RESCUE_DISK_ISO_PATH)) > 1));
return 1;
}
if ( hw == EN_CHANGE )
{
GetDlgItemText (hwndDlg, IDC_RESCUE_DISK_ISO_PATH, szRescueDiskISO, sizeof(szRescueDiskISO));
EnableWindow (GetDlgItem (MainDlg, IDC_NEXT), (GetWindowTextLength (GetDlgItem (hwndDlg, IDC_RESCUE_DISK_ISO_PATH)) > 1));
return 1;
}
}
if (nCurPageNo == SYSENC_RESCUE_DISK_BURN_PAGE && lw == IDC_DOWNLOAD_CD_BURN_SOFTWARE)
{
if (IsWindowsIsoBurnerAvailable())
LaunchWindowsIsoBurner (hwndDlg, szRescueDiskISO);
else
Applink ("isoburning", TRUE, "");
@@ -5414,41 +5416,41 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
}
SendMessage (GetDlgItem (hwndDlg, IDC_BOX_TITLE), WM_SETFONT, (WPARAM) hTitleFont, (LPARAM) TRUE);
SetWindowTextW (hwndDlg, lpszTitle);
ExtractCommandLine (hwndDlg, (char *) lParam);
if (ComServerMode)
{
InitDialog (hwndDlg);
if (!ComServerFormat ())
{
handleWin32Error (hwndDlg);
exit (1);
}
exit (0);
}
SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, 0, szRescueDiskISO);
- strcat (szRescueDiskISO, "\\VeraCrypt Rescue Disk.iso");
+ StringCbCatA (szRescueDiskISO, sizeof(szRescueDiskISO), "\\VeraCrypt Rescue Disk.iso");
if (IsOSAtLeast (WIN_VISTA))
{
// Availability of in-place encryption (which is pre-selected by default whenever
// possible) makes partition-hosted volume creation safer.
bWarnDeviceFormatAdvanced = FALSE;
}
#ifdef _DEBUG
// For faster testing
strcpy (szVerify, "q");
strcpy (szRawPassword, "q");
#endif
PostMessage (hwndDlg, TC_APPMSG_PERFORM_POST_WMINIT_TASKS, 0, 0);
}
return 0;
case WM_SYSCOMMAND:
if (lw == IDC_ABOUT)
@@ -5468,42 +5470,42 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
|| bInPlaceEncNonSys)
{
DisplayRandPool (hRandPoolSys, showKeys);
}
else
{
unsigned char tmp[17];
char tmp2[43];
int i;
if (!showKeys)
return 1;
RandpeekBytes (tmp, sizeof (tmp));
tmp2[0] = 0;
for (i = 0; i < sizeof (tmp); i++)
{
char tmp3[8];
- sprintf (tmp3, "%02X", (int) (unsigned char) tmp[i]);
- strcat (tmp2, tmp3);
+ StringCbPrintfA (tmp3, sizeof(tmp3), "%02X", (int) (unsigned char) tmp[i]);
+ StringCbCatA (tmp2, sizeof(tmp2), tmp3);
}
tmp2[32] = 0;
SetWindowTextW (GetDlgItem (hCurPage, IDC_RANDOM_BYTES), (SingleStringToWide (tmp2) + GetString ("TRIPLE_DOT_GLYPH_ELLIPSIS")).c_str());
burn (tmp, sizeof(tmp));
burn (tmp2, sizeof(tmp2));
}
return 1;
case TIMER_ID_SYSENC_PROGRESS:
{
// Manage system encryption/decryption and update related GUI
try
{
BootEncStatus = BootEncObj->GetStatus();
}
catch (Exception &e)
@@ -5686,58 +5688,58 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
// Keyboard layout is not standard US
WipePasswordsAndKeyfiles ();
SetWindowText (GetDlgItem (hCurPage, IDC_PASSWORD), szRawPassword);
SetWindowText (GetDlgItem (hCurPage, IDC_VERIFY), szVerify);
keybLayout = (DWORD) LoadKeyboardLayout ("00000409", KLF_ACTIVATE);
if (keybLayout != 0x00000409 && keybLayout != 0x04090409)
{
KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD);
Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION");
EndMainDlg (MainDlg);
return 1;
}
bKeyboardLayoutChanged = TRUE;
wchar_t szTmp [4096];
- wcscpy (szTmp, GetString ("KEYB_LAYOUT_CHANGE_PREVENTED"));
- wcscat (szTmp, L"\n\n");
- wcscat (szTmp, GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION"));
+ StringCbCopyW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_CHANGE_PREVENTED"));
+ StringCbCatW (szTmp, sizeof(szTmp), L"\n\n");
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION"));
MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST);
}
/* Watch the right Alt key (which is used to enter various characters on non-US keyboards) */
if (bKeyboardLayoutChanged && !bKeybLayoutAltKeyWarningShown)
{
if (GetAsyncKeyState (VK_RMENU) < 0)
{
bKeybLayoutAltKeyWarningShown = TRUE;
wchar_t szTmp [4096];
- wcscpy (szTmp, GetString ("ALT_KEY_CHARS_NOT_FOR_SYS_ENCRYPTION"));
- wcscat (szTmp, L"\n\n");
- wcscat (szTmp, GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION"));
+ StringCbCopyW (szTmp, sizeof(szTmp), GetString ("ALT_KEY_CHARS_NOT_FOR_SYS_ENCRYPTION"));
+ StringCbCatW (szTmp, sizeof(szTmp), L"\n\n");
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION"));
MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TOPMOST);
}
}
}
return 1;
case TIMER_ID_SYSENC_DRIVE_ANALYSIS_PROGRESS:
if (bSysEncDriveAnalysisInProgress)
{
UpdateProgressBarProc (GetTickCount() - SysEncDriveAnalysisStart);
if (GetTickCount() - SysEncDriveAnalysisStart > SYSENC_DRIVE_ANALYSIS_ETA)
{
// It's taking longer than expected -- reinit the progress bar
SysEncDriveAnalysisStart = GetTickCount ();
InitProgressBar (SYSENC_DRIVE_ANALYSIS_ETA, 0, FALSE, FALSE, FALSE, TRUE);
}
ArrowWaitCursor ();
@@ -6396,41 +6398,41 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
+ GetString ("NOTE_BEGINNING")
+ GetString ("HIDDEN_OS_WRITE_PROTECTION_BRIEF_INFO")
+ L" "
+ GetString ("HIDDEN_OS_WRITE_PROTECTION_EXPLANATION")).c_str());
NormalCursor ();
return 1;
}
bHiddenVolDirect = FALSE;
}
}
else if (nCurPageNo == VOLUME_LOCATION_PAGE)
{
BOOL tmpbDevice;
WaitCursor();
GetWindowText (GetDlgItem (hCurPage, IDC_COMBO_BOX), szFileName, sizeof (szFileName));
RelativePath2Absolute (szFileName);
- CreateFullVolumePath (szDiskFile, szFileName, &tmpbDevice);
+ CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice);
if (tmpbDevice != bDevice)
{
if (bDevice)
{
// Not a valid device path
Error ("CANNOT_CALC_SPACE");
NormalCursor ();
return 1;
}
else
{
if (AskWarnYesNo ("DEVICE_SELECTED_IN_NON_DEVICE_MODE") == IDNO)
{
NormalCursor ();
return 1;
}
SwitchWizardToNonSysDeviceMode ();
NormalCursor ();
@@ -6868,41 +6870,41 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
if ((volume.CryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) != 0
&& volume.CryptoInfo->EncryptedAreaLength.Value != volume.CryptoInfo->VolumeSize.Value)
{
DeferredNonSysInPlaceEncDevices.push_back (device);
}
CloseVolume (&volume);
}
}
}
if (DeferredNonSysInPlaceEncDevices.empty())
{
Warning ("FOUND_NO_PARTITION_W_DEFERRED_INPLACE_ENC");
NormalCursor();
return 1;
}
else if (DeferredNonSysInPlaceEncDevices.size() == 1)
{
- CreateFullVolumePath (szDiskFile, DeferredNonSysInPlaceEncDevices.front().Path.c_str(), &tmpbDevice);
+ CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), DeferredNonSysInPlaceEncDevices.front().Path.c_str(), &tmpbDevice);
nVolumeSize = GetDeviceSize (szDiskFile);
if (nVolumeSize == -1)
{
handleWin32Error (MainDlg);
NormalCursor();
return 1;
}
nNewPageNo = NONSYS_INPLACE_ENC_ENCRYPTION_PAGE - 1; // Skip irrelevant pages
}
NormalCursor();
}
}
else if (nCurPageNo == FILESYS_PAGE)
{
if (!bHiddenVol && IsHiddenOSRunning() && Get2RadButtonPageAnswer() == 1)
@@ -7025,41 +7027,41 @@ retryCDDriveCheck:
if (IsWindowsIsoBurnerAvailable() && !bDontVerifyRescueDisk)
Info ("RESCUE_DISK_WIN_ISOBURN_PRELAUNCH_NOTE");
NormalCursor ();
}
else if (nCurPageNo == SYSENC_RESCUE_DISK_BURN_PAGE)
{
if (!bDontVerifyRescueDisk)
{
/* Verify that the rescue disk has been written correctly */
try
{
WaitCursor();
if (!BootEncObj->VerifyRescueDisk ())
{
wchar_t szTmp[8000];
- swprintf (szTmp, GetString ("RESCUE_DISK_CHECK_FAILED"),
+ StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("RESCUE_DISK_CHECK_FAILED"),
IsWindowsIsoBurnerAvailable () ? L"" : GetString ("RESCUE_DISK_CHECK_FAILED_SENTENCE_APPENDIX"));
ErrorDirect (szTmp);
NormalCursor ();
#ifndef _DEBUG
return 1;
#endif
}
}
catch (Exception &e)
{
e.Show (hwndDlg);
NormalCursor ();
return 1;
}
NormalCursor ();
}
else
{
@@ -7575,41 +7577,41 @@ ovf_end:
nNewPageNo = VOLUME_LOCATION_PAGE + 1;
}
}
else if (nCurPageNo == HIDDEN_VOL_WIZARD_MODE_PAGE)
{
if (IsButtonChecked (GetDlgItem (hCurPage, IDC_HIDVOL_WIZ_MODE_DIRECT)))
bHiddenVolDirect = TRUE;
else
bHiddenVolDirect = FALSE;
}
else if (nCurPageNo == VOLUME_TYPE_PAGE)
{
if (WizardMode != WIZARD_MODE_SYS_DEVICE)
nNewPageNo = INTRO_PAGE + 1; // Skip irrelevant pages
}
else if (nCurPageNo == VOLUME_LOCATION_PAGE)
{
BOOL tmpbDevice;
GetWindowText (GetDlgItem (hCurPage, IDC_COMBO_BOX), szFileName, sizeof (szFileName));
- CreateFullVolumePath (szDiskFile, szFileName, &tmpbDevice);
+ CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szFileName, &tmpbDevice);
if (tmpbDevice == bDevice)
{
MoveEditToCombo (GetDlgItem (hCurPage, IDC_COMBO_BOX), bHistory);
SaveSettings (hCurPage);
}
if (!bHiddenVol)
nNewPageNo = VOLUME_TYPE_PAGE + 1; // Skip the hidden volume creation wizard mode selection
}
else if (nCurPageNo == CIPHER_PAGE)
{
LPARAM nIndex;
nIndex = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETCURSEL, 0, 0);
nVolumeEA = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX), CB_GETITEMDATA, nIndex, 0);
nIndex = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX_HASH_ALGO), CB_GETCURSEL, 0, 0);
hash_algo = SendMessage (GetDlgItem (hCurPage, IDC_COMBO_BOX_HASH_ALGO), CB_GETITEMDATA, nIndex, 0);
diff --git a/src/Mount/Favorites.cpp b/src/Mount/Favorites.cpp
index 06c1aa32..93d9c648 100644
--- a/src/Mount/Favorites.cpp
+++ b/src/Mount/Favorites.cpp
@@ -39,41 +39,41 @@ namespace VeraCrypt
if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &bytesReturned, NULL))
{
handleWin32Error (hwndDlg);
return FALSE;
}
FavoriteVolume favorite;
favorite.MountPoint = "X:\\";
favorite.MountPoint[0] = (char) (prop.driveNo + 'A');
favorite.Path = WideToSingleString ((wchar_t *) prop.wszVolume);
if (favorite.Path.find ("\\??\\") == 0)
favorite.Path = favorite.Path.substr (4);
if (IsVolumeDeviceHosted (favorite.Path.c_str()))
{
// Get GUID path
string volumeDevPath = favorite.Path;
wchar_t resolvedVolumeDevPath[TC_MAX_PATH];
- if (ResolveSymbolicLink (SingleStringToWide (volumeDevPath).c_str(), resolvedVolumeDevPath))
+ if (ResolveSymbolicLink (SingleStringToWide (volumeDevPath).c_str(), resolvedVolumeDevPath, sizeof(resolvedVolumeDevPath)))
volumeDevPath = WideToSingleString (resolvedVolumeDevPath);
char volumeName[TC_MAX_PATH];
HANDLE find = FindFirstVolume (volumeName, sizeof (volumeName));
if (find != INVALID_HANDLE_VALUE)
{
do
{
char findVolumeDevPath[TC_MAX_PATH];
string vn = volumeName;
if (QueryDosDevice (vn.substr (4, vn.size() - 5).c_str(), findVolumeDevPath, sizeof (findVolumeDevPath)) != 0
&& volumeDevPath == findVolumeDevPath)
{
favorite.VolumePathId = volumeName;
break;
}
} while (FindNextVolume (find, volumeName, sizeof (volumeName)));
@@ -397,41 +397,41 @@ namespace VeraCrypt
return 1;
}
break;
case WM_CLOSE:
EndDialog (hwndDlg, IDCLOSE);
return 1;
}
return 0;
}
static void FillFavoriteVolumesMenu ()
{
while (DeleteMenu (FavoriteVolumesMenu, 7, MF_BYPOSITION)) { }
if (FavoriteVolumes.empty())
return;
- AppendMenu (FavoriteVolumesMenu, MF_SEPARATOR, 0, NULL);
+ AppendMenu (FavoriteVolumesMenu, MF_SEPARATOR, 0, "");
int i = 0;
foreach (const FavoriteVolume &favorite, FavoriteVolumes)
{
UINT flags = MF_STRING;
if (favorite.DisconnectedDevice)
flags |= MF_GRAYED;
wstring menuText = SingleStringToWide (favorite.Path);
if (favorite.DisconnectedDevice)
menuText = favorite.Label.empty() ? wstring (L"(") + GetString ("FAVORITE_DISCONNECTED_DEV") + L")" : L"";
if (!favorite.Label.empty())
{
if (favorite.DisconnectedDevice)
menuText = favorite.Label + L" " + menuText;
else
menuText = favorite.Label;
}
diff --git a/src/Mount/Hotkeys.c b/src/Mount/Hotkeys.c
index 96f9abcd..c0829602 100644
--- a/src/Mount/Hotkeys.c
+++ b/src/Mount/Hotkeys.c
@@ -1,135 +1,137 @@
/*
Copyright (c) 2005 TrueCrypt Developers Association. All rights reserved.
Governed by the TrueCrypt License 3.0 the full text of which is contained in
the file License.txt included in TrueCrypt binary and source code distribution
packages.
*/
#include <windows.h>
#include "Dlgcode.h"
#include "Hotkeys.h"
#include "Language.h"
#include "Mount.h"
#include "Resource.h"
+#include <Strsafe.h>
+
#define MAX_KEY_COMB_NAME_LEN 260
TCHOTKEY Hotkeys [NBR_HOTKEYS];
static TCHOTKEY tmpHotkeys [NBR_HOTKEYS];
static int nSelectedHotkeyId;
static UINT currentVKeyCode;
static void ScanAndProcessKey (UINT *vKeyCode, wchar_t *keyName)
{
UINT vKey;
*vKeyCode = 0;
for (vKey = 0; vKey <= 0xFF; vKey++)
{
if (GetAsyncKeyState (vKey) < 0)
{
if (GetKeyName (vKey, keyName)) // If the key is allowed and its name has been resolved
*vKeyCode = vKey;
}
}
}
/* Returns TRUE if the key is allowed and its name is resolved. */
BOOL GetKeyName (UINT vKey, wchar_t *keyName)
{
BOOL result = TRUE;
if (vKey >= 0x30 && vKey <= 0x5a)
{
// ASCII characters
- wsprintfW (keyName, L"%hc", (char) vKey);
+ StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%hc", (char) vKey);
}
else if (vKey >= 0xE9 && vKey <= 0xF5)
{
// OEM-specific
- wsprintfW (keyName, L"OEM-%d", vKey);
+ StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM-%d", vKey);
}
else if (vKey >= VK_F1 && vKey <= VK_F24)
{
// F1-F24
- wsprintfW (keyName, L"F%d", vKey - VK_F1 + 1);
+ StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"F%d", vKey - VK_F1 + 1);
}
else if (vKey >= VK_NUMPAD0 && vKey <= VK_NUMPAD9)
{
// Numpad numbers
- wsprintfW (keyName, L"%s %d", GetString ("VK_NUMPAD"), vKey - VK_NUMPAD0);
+ StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s %d", GetString ("VK_NUMPAD"), vKey - VK_NUMPAD0);
}
else
{
switch (vKey)
{
- case VK_MULTIPLY: wsprintfW (keyName, L"%s *", GetString ("VK_NUMPAD")); break;
- case VK_ADD: wsprintfW (keyName, L"%s +", GetString ("VK_NUMPAD")); break;
- case VK_SEPARATOR: wsprintfW (keyName, L"%s Separator", GetString ("VK_NUMPAD")); break;
- case VK_SUBTRACT: wsprintfW (keyName, L"%s -", GetString ("VK_NUMPAD")); break;
- case VK_DECIMAL: wsprintfW (keyName, L"%s .", GetString ("VK_NUMPAD")); break;
- case VK_DIVIDE: wsprintfW (keyName, L"%s /", GetString ("VK_NUMPAD")); break;
- case VK_OEM_1: wcscpy (keyName, L"OEM 1 (';')"); break;
- case VK_OEM_PLUS: wcscpy (keyName, L"+"); break;
- case VK_OEM_COMMA: wcscpy (keyName, L","); break;
- case VK_OEM_MINUS: wcscpy (keyName, L"-"); break;
- case VK_OEM_PERIOD: wcscpy (keyName, L"."); break;
- case VK_OEM_2: wcscpy (keyName, L"OEM 2 ('/')"); break;
- case VK_OEM_3: wcscpy (keyName, L"OEM 3 (`)"); break;
- case VK_OEM_4: wcscpy (keyName, L"OEM 4 ('[')"); break;
- case VK_OEM_5: wcscpy (keyName, L"OEM 5 ('\\')"); break;
- case VK_OEM_6: wcscpy (keyName, L"OEM 6 (']')"); break;
- case VK_OEM_7: wcscpy (keyName, L"OEM 7 (')"); break;
- case VK_OEM_8: wcscpy (keyName, L"OEM 8"); break;
- case VK_OEM_AX: wcscpy (keyName, L"OEM AX"); break;
- case VK_OEM_102: wcscpy (keyName, L"OEM 102"); break;
- case VK_ICO_HELP: wcscpy (keyName, L"ICO_HELP"); break;
- case VK_ICO_00: wcscpy (keyName, L"ICO_00"); break;
- case VK_ICO_CLEAR: wcscpy (keyName, L"ICO_CLEAR"); break;
- case VK_ATTN: wcscpy (keyName, L"Attn"); break;
- case VK_CRSEL: wcscpy (keyName, L"CrSel"); break;
- case VK_EXSEL: wcscpy (keyName, L"ExSel"); break;
- case VK_EREOF: wcscpy (keyName, L"Erase EOF"); break;
- case VK_PA1: wcscpy (keyName, L"PA1"); break;
- case VK_OEM_CLEAR: wcscpy (keyName, L"OEM Clear"); break;
+ case VK_MULTIPLY: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s *", GetString ("VK_NUMPAD")); break;
+ case VK_ADD: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s +", GetString ("VK_NUMPAD")); break;
+ case VK_SEPARATOR: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s Separator", GetString ("VK_NUMPAD")); break;
+ case VK_SUBTRACT: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s -", GetString ("VK_NUMPAD")); break;
+ case VK_DECIMAL: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s .", GetString ("VK_NUMPAD")); break;
+ case VK_DIVIDE: StringCbPrintfW (keyName, MAX_KEY_COMB_NAME_LEN, L"%s /", GetString ("VK_NUMPAD")); break;
+ case VK_OEM_1: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 1 (';')"); break;
+ case VK_OEM_PLUS: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"+"); break;
+ case VK_OEM_COMMA: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L","); break;
+ case VK_OEM_MINUS: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"-"); break;
+ case VK_OEM_PERIOD: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"."); break;
+ case VK_OEM_2: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 2 ('/')"); break;
+ case VK_OEM_3: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 3 (`)"); break;
+ case VK_OEM_4: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 4 ('[')"); break;
+ case VK_OEM_5: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 5 ('\\')"); break;
+ case VK_OEM_6: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 6 (']')"); break;
+ case VK_OEM_7: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 7 (')"); break;
+ case VK_OEM_8: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 8"); break;
+ case VK_OEM_AX: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM AX"); break;
+ case VK_OEM_102: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM 102"); break;
+ case VK_ICO_HELP: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ICO_HELP"); break;
+ case VK_ICO_00: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ICO_00"); break;
+ case VK_ICO_CLEAR: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ICO_CLEAR"); break;
+ case VK_ATTN: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"Attn"); break;
+ case VK_CRSEL: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"CrSel"); break;
+ case VK_EXSEL: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"ExSel"); break;
+ case VK_EREOF: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"Erase EOF"); break;
+ case VK_PA1: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"PA1"); break;
+ case VK_OEM_CLEAR: StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, L"OEM Clear"); break;
case 0:
case 1:
case 0xFF:
result = FALSE;
break;
default:
{
char key[16];
wchar_t *desc;
- sprintf (key, "VKEY_%02X", vKey);
+ StringCbPrintfA (key, sizeof(key),"VKEY_%02X", vKey);
desc = GetString (key);
if (desc == UnknownString)
result = FALSE;
else
- wcsncpy (keyName, desc, MAX_KEY_COMB_NAME_LEN);
+ StringCbCopyW (keyName, MAX_KEY_COMB_NAME_LEN, desc);
}
}
}
return result;
}
static BOOL ShortcutInUse (UINT vKeyCode, UINT modifiers, TCHOTKEY hotkeys[])
{
int i;
for (i = 0; i < NBR_HOTKEYS; i++)
{
if (hotkeys[i].vKeyCode == vKeyCode && hotkeys[i].vKeyModifiers == modifiers)
return TRUE;
}
return FALSE;
}
@@ -209,70 +211,70 @@ static void DisplayHotkeyList (HWND hwndDlg)
case HK_MOUNT_FAVORITE_VOLUMES:
item.pszText = GetString ("HK_MOUNT_FAVORITE_VOLUMES");
break;
case HK_SHOW_HIDE_MAIN_WINDOW:
item.pszText = GetString ("HK_SHOW_HIDE_MAIN_WINDOW");
break;
case HK_CLOSE_SECURITY_TOKEN_SESSIONS:
item.pszText = GetString ("IDM_CLOSE_ALL_TOKEN_SESSIONS");
break;
default:
item.pszText = L"[?]";
}
SendMessageW (hList,LVM_INSERTITEMW,0,(LPARAM)&item);
item.iSubItem = 1;
- wcscpy (Shortcut, L"");
- wcscpy (ShortcutMod, L"");
+ Shortcut[0] = 0;
+ ShortcutMod[0] = 0;
if (GetKeyName (tmpHotkeys[i].vKeyCode, Shortcut))
{
if (tmpHotkeys[i].vKeyModifiers & MOD_CONTROL)
{
- wcscat (ShortcutMod, GetString ("VK_CONTROL"));
- wcscat (ShortcutMod, L"+");
+ StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_CONTROL"));
+ StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+");
}
if (tmpHotkeys[i].vKeyModifiers & MOD_SHIFT)
{
- wcscat (ShortcutMod, GetString ("VK_SHIFT"));
- wcscat (ShortcutMod, L"+");
+ StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_SHIFT"));
+ StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+");
}
if (tmpHotkeys[i].vKeyModifiers & MOD_ALT)
{
- wcscat (ShortcutMod, GetString ("VK_ALT"));
- wcscat (ShortcutMod, L"+");
+ StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_ALT"));
+ StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+");
}
if (tmpHotkeys[i].vKeyModifiers & MOD_WIN)
{
- wcscat (ShortcutMod, GetString ("VK_WIN"));
- wcscat (ShortcutMod, L"+");
+ StringCbCatW (ShortcutMod, sizeof(ShortcutMod),GetString ("VK_WIN"));
+ StringCbCatW (ShortcutMod, sizeof(ShortcutMod),L"+");
}
- wsprintfW (ShortcutFinal, L"%s%s", ShortcutMod, Shortcut);
+ StringCbPrintfW (ShortcutFinal, sizeof(ShortcutFinal), L"%s%s", ShortcutMod, Shortcut);
item.pszText = ShortcutFinal;
}
else
item.pszText = L"";
SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&item);
}
}
BOOL CALLBACK HotkeysDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
HWND hList = GetDlgItem (hwndDlg, IDC_HOTKEY_LIST);
HWND hwndMainDlg = hwndDlg;
WORD lw = LOWORD (wParam);
WORD hw = HIWORD (wParam);
static BOOL bKeyScanOn;
static BOOL bTPlaySoundOnSuccessfulHkDismount;
static BOOL bTDisplayBalloonOnSuccessfulHkDismount;
diff --git a/src/Mount/Mount.c b/src/Mount/Mount.c
index 5f6e472e..c63d31eb 100644
--- a/src/Mount/Mount.c
+++ b/src/Mount/Mount.c
@@ -29,40 +29,42 @@
#include "Favorites.h"
#include "Hotkeys.h"
#include "Keyfiles.h"
#include "Language.h"
#include "MainCom.h"
#include "Mount.h"
#include "Pkcs5.h"
#include "Random.h"
#include "Registry.h"
#include "Resource.h"
#include "Password.h"
#include "Xml.h"
#include "../Boot/Windows/BootCommon.h"
#include "../Common/Dictionary.h"
#include "../Common/Common.h"
#include "../Common/Resource.h"
#include "../Common/SecurityToken.h"
#include "../Platform/Finally.h"
#include "../Platform/ForEach.h"
+#include <Strsafe.h>
+
using namespace VeraCrypt;
enum timer_ids
{
TIMER_ID_MAIN = 0xff,
TIMER_ID_KEYB_LAYOUT_GUARD
};
enum hidden_os_read_only_notif_mode
{
TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_NONE = 0,
TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_COMPACT,
TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_DISABLED
};
#define TIMER_INTERVAL_MAIN 500
#define TIMER_INTERVAL_KEYB_LAYOUT_GUARD 10
BootEncryption *BootEncObj = NULL;
BootEncryptionStatus BootEncStatus;
@@ -517,41 +519,41 @@ void SaveSettings (HWND hwndDlg)
ConfigWriteInt ("EnableBackgroundTask", bEnableBkgTask);
ConfigWriteInt ("CloseBackgroundTaskOnNoVolumes", bCloseBkgTaskWhenNoVolumes);
ConfigWriteInt ("DismountOnLogOff", bDismountOnLogOff);
ConfigWriteInt ("DismountOnPowerSaving", bDismountOnPowerSaving);
ConfigWriteInt ("DismountOnScreenSaver", bDismountOnScreenSaver);
ConfigWriteInt ("ForceAutoDismount", bForceAutoDismount);
ConfigWriteInt ("MaxVolumeIdleTime", MaxVolumeIdleTime);
ConfigWriteInt ("HiddenSectorDetectionStatus", HiddenSectorDetectionStatus);
ConfigWriteInt ("UseKeyfiles", defaultKeyFilesParam.EnableKeyFiles);
if (IsHiddenOSRunning())
ConfigWriteInt ("HiddenSystemLeakProtNotifStatus", HiddenSysLeakProtectionNotificationStatus);
// Drive Letter
lLetter = GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST));
if (LOWORD (lLetter) != 0xffff)
- sprintf (szTmp, "%c:", (char) HIWORD (lLetter));
+ StringCbPrintfA (szTmp, sizeof(szTmp), "%c:", (char) HIWORD (lLetter));
ConfigWriteString ("LastSelectedDrive", szTmp);
ConfigWriteInt ("CloseSecurityTokenSessionsAfterMount", CloseSecurityTokenSessionsAfterMount);
ConfigWriteInt ("DisableSystemCrashDetection", DisableSystemCrashDetection);
// Hotkeys
ConfigWriteInt ("HotkeyModAutoMountDevices", Hotkeys[HK_AUTOMOUNT_DEVICES].vKeyModifiers);
ConfigWriteInt ("HotkeyCodeAutoMountDevices", Hotkeys[HK_AUTOMOUNT_DEVICES].vKeyCode);
ConfigWriteInt ("HotkeyModDismountAll", Hotkeys[HK_DISMOUNT_ALL].vKeyModifiers);
ConfigWriteInt ("HotkeyCodeDismountAll", Hotkeys[HK_DISMOUNT_ALL].vKeyCode);
ConfigWriteInt ("HotkeyModWipeCache", Hotkeys[HK_WIPE_CACHE].vKeyModifiers);
ConfigWriteInt ("HotkeyCodeWipeCache", Hotkeys[HK_WIPE_CACHE].vKeyCode);
ConfigWriteInt ("HotkeyModDismountAllWipe", Hotkeys[HK_DISMOUNT_ALL_AND_WIPE].vKeyModifiers);
ConfigWriteInt ("HotkeyCodeDismountAllWipe", Hotkeys[HK_DISMOUNT_ALL_AND_WIPE].vKeyCode);
ConfigWriteInt ("HotkeyModForceDismountAllWipe", Hotkeys[HK_FORCE_DISMOUNT_ALL_AND_WIPE].vKeyModifiers);
ConfigWriteInt ("HotkeyCodeForceDismountAllWipe", Hotkeys[HK_FORCE_DISMOUNT_ALL_AND_WIPE].vKeyCode);
ConfigWriteInt ("HotkeyModForceDismountAllWipeExit", Hotkeys[HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT].vKeyModifiers);
ConfigWriteInt ("HotkeyCodeForceDismountAllWipeExit", Hotkeys[HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT].vKeyCode);
ConfigWriteInt ("HotkeyModMountFavoriteVolumes", Hotkeys[HK_MOUNT_FAVORITE_VOLUMES].vKeyModifiers);
ConfigWriteInt ("HotkeyCodeMountFavoriteVolumes", Hotkeys[HK_MOUNT_FAVORITE_VOLUMES].vKeyCode);
@@ -704,135 +706,135 @@ static void PopulateSysEncContextMenu (HMENU popup, BOOL bToolsOnly)
try
{
BootEncStatus = BootEncObj->GetStatus();
}
catch (Exception &e)
{
e.Show (MainDlg);
}
if (!bToolsOnly && !IsHiddenOSRunning())
{
if (SysEncryptionOrDecryptionRequired ())
{
if (!BootEncStatus.SetupInProgress)
AppendMenuW (popup, MF_STRING, IDM_SYSENC_RESUME, GetString ("IDM_SYSENC_RESUME"));
if (SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING)
AppendMenuW (popup, MF_STRING, IDM_PERMANENTLY_DECRYPT_SYS, GetString ("PERMANENTLY_DECRYPT"));
AppendMenuW (popup, MF_STRING, IDM_ENCRYPT_SYSTEM_DEVICE, GetString ("ENCRYPT"));
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
}
}
AppendMenuW (popup, MF_STRING, IDM_CHANGE_SYS_PASSWORD, GetString ("IDM_CHANGE_SYS_PASSWORD"));
AppendMenuW (popup, MF_STRING, IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO, GetString ("IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO"));
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
AppendMenuW (popup, MF_STRING, IDM_SYS_ENC_SETTINGS, GetString ("IDM_SYS_ENC_SETTINGS"));
if (!IsHiddenOSRunning())
{
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
AppendMenuW (popup, MF_STRING, IDM_CREATE_RESCUE_DISK, GetString ("IDM_CREATE_RESCUE_DISK"));
AppendMenuW (popup, MF_STRING, IDM_VERIFY_RESCUE_DISK, GetString ("IDM_VERIFY_RESCUE_DISK"));
}
if (!bToolsOnly)
{
if (SysDriveOrPartitionFullyEncrypted (FALSE) && !IsHiddenOSRunning())
{
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
AppendMenuW (popup, MF_STRING, IDM_PERMANENTLY_DECRYPT_SYS, GetString ("PERMANENTLY_DECRYPT"));
}
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
AppendMenuW (popup, MF_STRING, IDM_VOLUME_PROPERTIES, GetString ("IDPM_PROPERTIES"));
}
}
// WARNING: This function may take a long time to complete. To prevent data corruption, it MUST be called before
// mounting a partition (as a regular volume) that is within key scope of system encryption.
// Returns TRUE if the partition can be mounted as a partition within key scope of inactive system encryption.
// If devicePath is empty, the currently selected partition in the GUI is checked.
BOOL CheckSysEncMountWithoutPBA (const char *devicePath, BOOL quiet)
{
BOOL tmpbDevice;
char szDevicePath [TC_MAX_PATH+1];
char szDiskFile [TC_MAX_PATH+1];
if (strlen (devicePath) < 2)
{
GetWindowText (GetDlgItem (MainDlg, IDC_VOLUME), szDevicePath, sizeof (szDevicePath));
- CreateFullVolumePath (szDiskFile, szDevicePath, &tmpbDevice);
+ CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), szDevicePath, &tmpbDevice);
if (!tmpbDevice)
{
if (!quiet)
Warning ("NO_SYSENC_PARTITION_SELECTED");
return FALSE;
}
if (LOWORD (GetSelectedLong (GetDlgItem (MainDlg, IDC_DRIVELIST))) != TC_MLIST_ITEM_FREE)
{
if (!quiet)
Warning ("SELECT_FREE_DRIVE");
return FALSE;
}
}
else
- strncpy (szDevicePath, devicePath, sizeof (szDevicePath) - 1);
+ StringCbCopyA (szDevicePath, sizeof(szDevicePath), devicePath);
char *partionPortion = strrchr (szDevicePath, '\\');
if (!partionPortion
|| !_stricmp (partionPortion, "\\Partition0"))
{
// Only partitions are supported (not whole drives)
if (!quiet)
Warning ("NO_SYSENC_PARTITION_SELECTED");
return FALSE;
}
try
{
BootEncStatus = BootEncObj->GetStatus();
if (BootEncStatus.DriveMounted)
{
int retCode = 0;
int driveNo;
char parentDrivePath [TC_MAX_PATH+1];
if (sscanf (szDevicePath, "\\Device\\Harddisk%d\\Partition", &driveNo) != 1)
{
if (!quiet)
Error ("INVALID_PATH");
return FALSE;
}
- _snprintf (parentDrivePath,
+ StringCbPrintfA (parentDrivePath,
sizeof (parentDrivePath),
"\\Device\\Harddisk%d\\Partition0",
driveNo);
WaitCursor ();
// This is critical (re-mounting a mounted system volume as a normal volume could cause data corruption)
// so we force the slower but reliable method
retCode = IsSystemDevicePath (parentDrivePath, MainDlg, TRUE);
NormalCursor();
if (retCode != 2)
return TRUE;
else
{
// The partition is located on active system drive
if (!quiet)
Warning ("MOUNT_WITHOUT_PBA_VOL_ON_ACTIVE_SYSENC_DRIVE");
@@ -855,41 +857,41 @@ BOOL CheckSysEncMountWithoutPBA (const char *devicePath, BOOL quiet)
// Returns TRUE if the host drive of the specified partition contains a portion of the TrueCrypt Boot Loader
// and if the drive is not within key scope of active system encryption (e.g. the system drive of the running OS).
// If bPrebootPasswordDlgMode is TRUE, this function returns FALSE (because the check would be redundant).
BOOL TCBootLoaderOnInactiveSysEncDrive (void)
{
try
{
int driveNo;
char szDevicePath [TC_MAX_PATH+1];
char parentDrivePath [TC_MAX_PATH+1];
if (bPrebootPasswordDlgMode)
return FALSE;
GetWindowText (GetDlgItem (MainDlg, IDC_VOLUME), szDevicePath, sizeof (szDevicePath));
if (sscanf (szDevicePath, "\\Device\\Harddisk%d\\Partition", &driveNo) != 1)
return FALSE;
- _snprintf (parentDrivePath,
+ StringCbPrintfA (parentDrivePath,
sizeof (parentDrivePath),
"\\Device\\Harddisk%d\\Partition0",
driveNo);
BootEncStatus = BootEncObj->GetStatus();
if (BootEncStatus.DriveMounted
&& IsSystemDevicePath (parentDrivePath, MainDlg, FALSE) == 2)
{
// The partition is within key scope of active system encryption
return FALSE;
}
return ((BOOL) BootEncObj->IsBootLoaderOnDrive (parentDrivePath));
}
catch (...)
{
return FALSE;
}
@@ -932,49 +934,50 @@ BOOL SelectItem (HWND hTree, char nLetter)
}
return TRUE;
}
static void LaunchVolCreationWizard (HWND hwndDlg, const char *arg)
{
char t[TC_MAX_PATH] = {'"',0};
char *tmp;
GetModuleFileName (NULL, t+1, sizeof(t)-1);
tmp = strrchr (t, '\\');
if (tmp)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory (&si, sizeof (si));
- strcpy (++tmp, "VeraCrypt Format.exe\"");
+ *tmp = 0;
+ StringCbCopyA (t, sizeof(t), "\\VeraCrypt Format.exe\"");
if (!FileExists(t))
Error ("VOL_CREATION_WIZARD_NOT_FOUND"); // Display a user-friendly error message and advise what to do
if (strlen (arg) > 0)
{
- strcat (t, " ");
- strcat (t, arg);
+ StringCbCatA (t, sizeof(t), " ");
+ StringCbCatA (t, sizeof(t), arg);
}
if (!CreateProcess (NULL, (LPSTR) t, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi))
{
handleWin32Error (hwndDlg);
}
else
{
CloseHandle (pi.hProcess);
CloseHandle (pi.hThread);
}
}
}
// Fills drive list
// drive>0 = update only the corresponding drive subitems
void LoadDriveLetters (HWND hTree, int drive)
{
// Remember the top-most visible item
@@ -1051,91 +1054,92 @@ void LoadDriveLetters (HWND hTree, int drive)
{
LVITEM tmp;
memset(&tmp, 0, sizeof(LVITEM));
tmp.mask = LVIF_PARAM;
tmp.iItem = item;
if (ListView_GetItem (hTree, &tmp))
curDrive = HIWORD(tmp.lParam);
}
{
char szTmp[1024];
wchar_t szTmpW[1024];
memset(&listItem, 0, sizeof(listItem));
listItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
listItem.iImage = 2;
listItem.iItem = item++;
listItem.pszText = szTmp;
- strcpy (szTmp, " ");
+ szTmp[0] = ' ';
+ szTmp[1] = 0;
listItem.lParam = MAKELONG (TC_MLIST_ITEM_SYS_DRIVE, ENC_SYSDRIVE_PSEUDO_DRIVE_LETTER);
if(drive == 0)
ListView_InsertItem (hTree, &listItem);
else
ListView_SetItem (hTree, &listItem);
listItem.mask=LVIF_TEXT;
// Fully encrypted
if (SysDriveOrPartitionFullyEncrypted (TRUE))
{
- wcscpy (szTmpW, GetString ("SYSTEM_DRIVE"));
+ StringCbCopyW (szTmpW, sizeof(szTmpW), GetString ("SYSTEM_DRIVE"));
}
else
{
// Partially encrypted
if (BootEncStatus.SetupInProgress)
{
// Currently encrypting/decrypting
if (BootEncStatus.SetupMode != SetupDecryption)
{
- _snwprintf (szTmpW,
- sizeof szTmpW/2,
+ StringCbPrintfW (szTmpW,
+ sizeof szTmpW,
GetString ("SYSTEM_DRIVE_ENCRYPTING"),
(double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0);
}
else
{
- _snwprintf (szTmpW,
- sizeof szTmpW/2,
+ StringCbPrintfW (szTmpW,
+ sizeof szTmpW,
GetString ("SYSTEM_DRIVE_DECRYPTING"),
100.0 - ((double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0));
}
}
else
{
- _snwprintf (szTmpW,
- sizeof szTmpW/2,
+ StringCbPrintfW (szTmpW,
+ sizeof szTmpW,
GetString ("SYSTEM_DRIVE_PARTIALLY_ENCRYPTED"),
(double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0);
}
}
ListSubItemSetW (hTree, listItem.iItem, 1, szTmpW);
- GetSizeString (GetSysEncDeviceSize(TRUE), szTmpW);
+ GetSizeString (GetSysEncDeviceSize(TRUE), szTmpW, sizeof(szTmpW));
ListSubItemSetW (hTree, listItem.iItem, 2, szTmpW);
EAGetName (szTmp, propSysEnc.ea);
listItem.iSubItem = 3;
ListView_SetItem (hTree, &listItem);
ListSubItemSetW (hTree, listItem.iItem, 4, GetString (IsHiddenOSRunning() ? "HIDDEN" : "SYSTEM_VOLUME_TYPE_ADJECTIVE"));
}
}
/* Drive letters */
for (i = 2; i < 26; i++)
{
int curDrive = 0;
BOOL bSysEncPartition = (bSysEnc && !bWholeSysDriveEncryption && sysDriveLetter == *((char *) szDriveLetters[i]));
if (drive > 0)
{
@@ -1165,135 +1169,135 @@ void LoadDriveLetters (HWND hTree, int drive)
listItem.lParam = MAKELONG (
bSysEncPartition ? TC_MLIST_ITEM_SYS_PARTITION : TC_MLIST_ITEM_NONSYS_VOL,
i + 'A');
listItem.pszText = szDriveLetters[i];
if (drive == 0)
ListView_InsertItem (hTree, &listItem);
else
ListView_SetItem (hTree, &listItem);
listItem.mask=LVIF_TEXT;
listItem.pszText = szTmp;
if (bSysEncPartition)
{
// Fully encrypted
if (SysDriveOrPartitionFullyEncrypted (TRUE))
{
- wcscpy (szTmpW, GetString (IsHiddenOSRunning() ? "HIDDEN_SYSTEM_PARTITION" : "SYSTEM_PARTITION"));
+ StringCbCopyW (szTmpW, sizeof(szTmpW), GetString (IsHiddenOSRunning() ? "HIDDEN_SYSTEM_PARTITION" : "SYSTEM_PARTITION"));
}
else
{
// Partially encrypted
if (BootEncStatus.SetupInProgress)
{
// Currently encrypting/decrypting
if (BootEncStatus.SetupMode != SetupDecryption)
{
- _snwprintf (szTmpW,
- sizeof szTmpW/2,
+ StringCbPrintfW (szTmpW,
+ sizeof szTmpW,
GetString ("SYSTEM_PARTITION_ENCRYPTING"),
(double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0);
}
else
{
- _snwprintf (szTmpW,
- sizeof szTmpW/2,
+ StringCbPrintfW (szTmpW,
+ sizeof szTmpW,
GetString ("SYSTEM_PARTITION_DECRYPTING"),
100.0 - ((double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0));
}
}
else
{
- _snwprintf (szTmpW,
- sizeof szTmpW/2,
+ StringCbPrintfW (szTmpW,
+ sizeof szTmpW,
GetString ("SYSTEM_PARTITION_PARTIALLY_ENCRYPTED"),
(double) GetSysEncDeviceEncryptedPartSize (TRUE) / (double) GetSysEncDeviceSize (TRUE) * 100.0);
}
}
ListSubItemSetW (hTree, listItem.iItem, 1, szTmpW);
}
else
{
- ToSBCS (driver.wszVolume[i]);
+ ToSBCS (driver.wszVolume[i], sizeof(driver.wszVolume[i]));
char *path = (char *) driver.wszVolume[i];
if (memcmp (path, "\\??\\", 4) == 0)
path += 4;
listItem.iSubItem = 1;
wstring label = GetFavoriteVolumeLabel (path);
if (!label.empty())
ListSubItemSetW (hTree, listItem.iItem, 1, (wchar_t *) label.c_str());
else
ListSubItemSet (hTree, listItem.iItem, 1, (char *) FitPathInGfxWidth (hTree, hUserFont, ListView_GetColumnWidth (hTree, 1) - GetTextGfxWidth (hTree, L"___", hUserFont), path).c_str());
}
- GetSizeString (bSysEncPartition ? GetSysEncDeviceSize(TRUE) : driver.diskLength[i], szTmpW);
+ GetSizeString (bSysEncPartition ? GetSysEncDeviceSize(TRUE) : driver.diskLength[i], szTmpW, sizeof(szTmpW));
ListSubItemSetW (hTree, listItem.iItem, 2, szTmpW);
EAGetName (szTmp, bSysEncPartition ? propSysEnc.ea : driver.ea[i]);
listItem.iSubItem = 3;
ListView_SetItem (hTree, &listItem);
if (bSysEncPartition)
{
ws = GetString (IsHiddenOSRunning() ? "HIDDEN" : "SYSTEM_VOLUME_TYPE_ADJECTIVE");
VolumeNotificationsList.bHidVolDamagePrevReported[i] = FALSE;
ListSubItemSetW (hTree, listItem.iItem, 4, ws);
}
else
{
switch (driver.volumeType[i])
{
case PROP_VOL_TYPE_NORMAL:
ws = GetString ("NORMAL");
break;
case PROP_VOL_TYPE_HIDDEN:
ws = GetString ("HIDDEN");
break;
case PROP_VOL_TYPE_OUTER:
ws = GetString ("OUTER"); // Normal/outer volume (hidden volume protected)
break;
case PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED:
ws = GetString ("OUTER_VOL_WRITE_PREVENTED"); // Normal/outer volume (hidden volume protected AND write denied)
break;
default:
ws = L"?";
}
ListSubItemSetW (hTree, listItem.iItem, 4, ws);
if (driver.volumeType[i] == PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED) // Normal/outer volume (hidden volume protected AND write denied)
{
if (!VolumeNotificationsList.bHidVolDamagePrevReported[i])
{
wchar_t szTmp[4096];
VolumeNotificationsList.bHidVolDamagePrevReported[i] = TRUE;
- swprintf (szTmp, GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), i+'A');
+ StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), i+'A');
SetForegroundWindow (GetParent(hTree));
MessageBoxW (GetParent(hTree), szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST);
}
}
else
{
VolumeNotificationsList.bHidVolDamagePrevReported[i] = FALSE;
}
}
}
else
{
VolumeNotificationsList.bHidVolDamagePrevReported[i] = FALSE;
if (!(dwUsedDrives & 1 << i))
{
if(drive > 0 && drive != HIWORD (GetSelectedLong (hTree)))
{
item++;
continue;
@@ -1537,59 +1541,59 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR
SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp);
SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), tmp);
SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), "");
SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), "");
SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), "");
keybLayout = (DWORD) LoadKeyboardLayout ("00000409", KLF_ACTIVATE);
if (keybLayout != 0x00000409 && keybLayout != 0x04090409)
{
KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD);
Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION");
EndDialog (hwndDlg, IDCANCEL);
return 1;
}
bKeyboardLayoutChanged = TRUE;
wchar_t szTmp [4096];
- wcscpy (szTmp, GetString ("KEYB_LAYOUT_CHANGE_PREVENTED"));
- wcscat (szTmp, L"\n\n");
- wcscat (szTmp, GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION"));
+ StringCbCopyW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_CHANGE_PREVENTED"));
+ StringCbCatW (szTmp, sizeof(szTmp), L"\n\n");
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION"));
MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST);
}
/* Watch the right Alt key (which is used to enter various characters on non-US keyboards) */
if (bKeyboardLayoutChanged && !bKeybLayoutAltKeyWarningShown)
{
if (GetAsyncKeyState (VK_RMENU) < 0)
{
bKeybLayoutAltKeyWarningShown = TRUE;
wchar_t szTmp [4096];
- wcscpy (szTmp, GetString ("ALT_KEY_CHARS_NOT_FOR_SYS_ENCRYPTION"));
- wcscat (szTmp, L"\n\n");
- wcscat (szTmp, GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION"));
+ StringCbCopyW (szTmp, sizeof(szTmp), GetString ("ALT_KEY_CHARS_NOT_FOR_SYS_ENCRYPTION"));
+ StringCbCatW (szTmp, sizeof(szTmp), L"\n\n");
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION"));
MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TOPMOST);
}
}
}
return 1;
}
return 0;
case WM_COMMAND:
if (lw == IDCANCEL)
{
// Attempt to wipe passwords stored in the input field buffers
char tmp[MAX_PASSWORD+1];
memset (tmp, 'X', MAX_PASSWORD);
tmp[MAX_PASSWORD] = 0;
SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp);
SetWindowText (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), tmp);
SetWindowText (GetDlgItem (hwndDlg, IDC_VERIFY), tmp);
RestoreDefaultKeyFilesParam ();
@@ -1882,46 +1886,46 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa
{
case WM_INITDIALOG:
{
szXPwd = (Password *) lParam;
LocalizeDialog (hwndDlg, "IDD_PASSWORD_DLG");
DragAcceptFiles (hwndDlg, TRUE);
if (PasswordDialogTitleStringId)
{
SetWindowTextW (hwndDlg, GetString (PasswordDialogTitleStringId));
}
else if (strlen (PasswordDlgVolume) > 0)
{
wchar_t s[1024];
RECT rect;
GetWindowRect (hwndDlg, &rect);
wstring label = GetFavoriteVolumeLabel (PasswordDlgVolume);
if (!label.empty())
{
- wsprintfW (s, GetString ("ENTER_PASSWORD_FOR_LABEL"), label.c_str());
+ StringCbPrintfW (s, sizeof(s), GetString ("ENTER_PASSWORD_FOR_LABEL"), label.c_str());
}
else
{
- wsprintfW (s, GetString ("ENTER_PASSWORD_FOR"), "___");
- wsprintfW (s, GetString ("ENTER_PASSWORD_FOR"), FitPathInGfxWidth (hwndDlg, WindowTitleBarFont, rect.right - rect.left - GetTextGfxWidth (hwndDlg, s, WindowTitleBarFont), PasswordDlgVolume).c_str());
+ StringCbPrintfW (s, sizeof(s), GetString ("ENTER_PASSWORD_FOR"), "___");
+ StringCbPrintfW (s, sizeof(s), GetString ("ENTER_PASSWORD_FOR"), FitPathInGfxWidth (hwndDlg, WindowTitleBarFont, rect.right - rect.left - GetTextGfxWidth (hwndDlg, s, WindowTitleBarFont), PasswordDlgVolume).c_str());
}
SetWindowTextW (hwndDlg, s);
}
SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0);
SendMessage (GetDlgItem (hwndDlg, IDC_CACHE), BM_SETCHECK, bCacheInDriver ? BST_CHECKED:BST_UNCHECKED, 0);
SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable);
mountOptions.PartitionInInactiveSysEncScope = bPrebootPasswordDlgMode;
if (bPrebootPasswordDlgMode)
{
SendMessage (hwndDlg, TC_APPMSG_PREBOOT_PASSWORD_MODE, 0, 0);
}
if (PasswordDialogDisableMountOptions)
{
EnableWindow (GetDlgItem (hwndDlg, IDC_CACHE), FALSE);
@@ -1940,41 +1944,41 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa
flash.uCount = 0;
FlashWindowEx (&flash);
SetWindowPos (hwndDlg, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
}
return 0;
case TC_APPMSG_PREBOOT_PASSWORD_MODE:
{
ToBootPwdField (hwndDlg, IDC_PASSWORD);
// Attempt to wipe the password stored in the input field buffer
char tmp[MAX_PASSWORD+1];
memset (tmp, 'X', MAX_PASSWORD);
tmp [MAX_PASSWORD] = 0;
SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp);
SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), "");
- sprintf (OrigKeyboardLayout, "%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF);
+ StringCbPrintfA (OrigKeyboardLayout, sizeof(OrigKeyboardLayout),"%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF);
DWORD keybLayout = (DWORD) LoadKeyboardLayout ("00000409", KLF_ACTIVATE);
if (keybLayout != 0x00000409 && keybLayout != 0x04090409)
{
Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION");
EndDialog (hwndDlg, IDCANCEL);
return 1;
}
if (SetTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0)
{
Error ("CANNOT_SET_TIMER");
EndDialog (hwndDlg, IDCANCEL);
return 1;
}
SetCheckBox (hwndDlg, IDC_SHOW_PASSWORD, FALSE);
EnableWindow (GetDlgItem (hwndDlg, IDC_SHOW_PASSWORD), FALSE);
@@ -1998,43 +2002,43 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa
// Keyboard layout is not standard US
// Attempt to wipe the password stored in the input field buffer
char tmp[MAX_PASSWORD+1];
memset (tmp, 'X', MAX_PASSWORD);
tmp [MAX_PASSWORD] = 0;
SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp);
SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), "");
keybLayout = (DWORD) LoadKeyboardLayout ("00000409", KLF_ACTIVATE);
if (keybLayout != 0x00000409 && keybLayout != 0x04090409)
{
KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD);
Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION");
EndDialog (hwndDlg, IDCANCEL);
return 1;
}
wchar_t szTmp [4096];
- wcscpy (szTmp, GetString ("KEYB_LAYOUT_CHANGE_PREVENTED"));
- wcscat (szTmp, L"\n\n");
- wcscat (szTmp, GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION"));
+ StringCbCopyW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_CHANGE_PREVENTED"));
+ StringCbCatW (szTmp, sizeof(szTmp), L"\n\n");
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION"));
MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST);
}
}
return 1;
}
return 0;
case WM_COMMAND:
if (lw == IDC_MOUNT_OPTIONS)
{
DialogBoxParamW (hInst,
MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg,
(DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions);
if (!bPrebootPasswordDlgMode && mountOptions.PartitionInInactiveSysEncScope)
SendMessage (hwndDlg, TC_APPMSG_PREBOOT_PASSWORD_MODE, 0, 0);
return 1;
}
@@ -2135,43 +2139,46 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa
popupPos.y = buttonRect.top + 2;
if (KeyfilesPopupMenu (hwndDlg, popupPos, &param))
{
KeyFilesEnable = param.EnableKeyFiles;
FirstKeyFile = param.FirstKeyFile;
SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable);
}
}
}
break;
case WM_DROPFILES:
{
HDROP hdrop = (HDROP) wParam;
int i = 0, count = DragQueryFile (hdrop, 0xFFFFFFFF, NULL, 0);
while (count-- > 0)
{
KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
- DragQueryFile (hdrop, i++, kf->FileName, sizeof (kf->FileName));
- FirstKeyFile = KeyFileAdd (FirstKeyFile, kf);
- KeyFilesEnable = TRUE;
+ if (kf)
+ {
+ DragQueryFile (hdrop, i++, kf->FileName, sizeof (kf->FileName));
+ FirstKeyFile = KeyFileAdd (FirstKeyFile, kf);
+ KeyFilesEnable = TRUE;
+ }
}
SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable);
DragFinish (hdrop);
}
return 1;
}
return 0;
}
static void PreferencesDlgEnableButtons (HWND hwndDlg)
{
BOOL back = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_BKG_TASK_ENABLE));
BOOL idle = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE));
BOOL installed = !IsNonInstallMode();
EnableWindow (GetDlgItem (hwndDlg, IDC_CLOSE_BKG_TASK_WHEN_NOVOL), back && installed);
EnableWindow (GetDlgItem (hwndDlg, IDT_LOGON), installed);
EnableWindow (GetDlgItem (hwndDlg, IDC_PREF_LOGON_START), back && installed);
@@ -2334,57 +2341,61 @@ BOOL CALLBACK PreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM
bForceAutoDismount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_FORCE_AUTO_DISMOUNT));
MaxVolumeIdleTime = GetDlgItemInt (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE_TIME, NULL, FALSE)
* (IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_DISMOUNT_INACTIVE)) ? 1 : -1);
bStartOnLogon = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_LOGON_START));
bMountDevicesOnLogon = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_LOGON_MOUNT_DEVICES));
ManageStartupSeq ();
SaveSettings (hwndDlg);
NormalCursor ();
PreferencesDialogActive = FALSE;
EndDialog (hwndDlg, lw);
return 1;
}
if (lw == IDC_MORE_SETTINGS)
{
HMENU popup = CreatePopupMenu ();
+ if (popup)
+ {
+ AppendMenuW (popup, MF_STRING, IDM_LANGUAGE, GetString ("IDM_LANGUAGE"));
+ AppendMenuW (popup, MF_STRING, IDM_HOTKEY_SETTINGS, GetString ("IDM_HOTKEY_SETTINGS"));
+ AppendMenuW (popup, MF_STRING, IDM_PERFORMANCE_SETTINGS, GetString ("IDM_PERFORMANCE_SETTINGS"));
+ AppendMenuW (popup, MF_STRING, IDM_SYSENC_SETTINGS, GetString ("IDM_SYSENC_SETTINGS"));
+ AppendMenuW (popup, MF_STRING, IDM_SYS_FAVORITES_SETTINGS, GetString ("IDM_SYS_FAVORITES_SETTINGS"));
+ AppendMenuW (popup, MF_STRING, IDM_DEFAULT_KEYFILES, GetString ("IDM_DEFAULT_KEYFILES"));
+ AppendMenuW (popup, MF_STRING, IDM_TOKEN_PREFERENCES, GetString ("IDM_TOKEN_PREFERENCES"));
- AppendMenuW (popup, MF_STRING, IDM_LANGUAGE, GetString ("IDM_LANGUAGE"));
- AppendMenuW (popup, MF_STRING, IDM_HOTKEY_SETTINGS, GetString ("IDM_HOTKEY_SETTINGS"));
- AppendMenuW (popup, MF_STRING, IDM_PERFORMANCE_SETTINGS, GetString ("IDM_PERFORMANCE_SETTINGS"));
- AppendMenuW (popup, MF_STRING, IDM_SYSENC_SETTINGS, GetString ("IDM_SYSENC_SETTINGS"));
- AppendMenuW (popup, MF_STRING, IDM_SYS_FAVORITES_SETTINGS, GetString ("IDM_SYS_FAVORITES_SETTINGS"));
- AppendMenuW (popup, MF_STRING, IDM_DEFAULT_KEYFILES, GetString ("IDM_DEFAULT_KEYFILES"));
- AppendMenuW (popup, MF_STRING, IDM_TOKEN_PREFERENCES, GetString ("IDM_TOKEN_PREFERENCES"));
-
- RECT rect;
- GetWindowRect (GetDlgItem (hwndDlg, IDC_MORE_SETTINGS), &rect);
+ RECT rect;
+ GetWindowRect (GetDlgItem (hwndDlg, IDC_MORE_SETTINGS), &rect);
- int menuItem = TrackPopupMenu (popup, TPM_RETURNCMD | TPM_LEFTBUTTON, rect.left + 2, rect.top + 2, 0, hwndDlg, NULL);
- DestroyMenu (popup);
+ int menuItem = TrackPopupMenu (popup, TPM_RETURNCMD | TPM_LEFTBUTTON, rect.left + 2, rect.top + 2, 0, hwndDlg, NULL);
+ DestroyMenu (popup);
- SendMessage (MainDlg, WM_COMMAND, menuItem, NULL);
- return 1;
+ SendMessage (MainDlg, WM_COMMAND, menuItem, NULL);
+ return 1;
+ }
+ else
+ return 0;
}
if (HIWORD (wParam) == BN_CLICKED)
{
PreferencesDlgEnableButtons (hwndDlg);
return 1;
}
return 0;
}
return 0;
}
BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
static MountOptions *mountOptions;
WORD lw = LOWORD (wParam);
@@ -2722,41 +2733,41 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP
{
e.Show (MainDlg);
return 0;
}
}
else
{
if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL) || dwResult == 0)
return 0;
}
// Location
ListItemAddW (list, i, GetString ("LOCATION"));
if (bSysEnc)
ListSubItemSetW (list, i++, 1, GetString (bSysEncWholeDrive ? "SYSTEM_DRIVE" : IsHiddenOSRunning() ? "HIDDEN_SYSTEM_PARTITION" : "SYSTEM_PARTITION"));
else
ListSubItemSetW (list, i++, 1, (wchar_t *) (prop.wszVolume[1] != L'?' ? prop.wszVolume : prop.wszVolume + 4));
// Size
ListItemAddW (list, i, GetString ("SIZE"));
- swprintf (sw, L"%I64u %s", prop.diskLength, GetString ("BYTES"));
+ StringCbPrintfW (sw, sizeof(sw), L"%I64u %s", prop.diskLength, GetString ("BYTES"));
ListSubItemSetW (list, i++, 1, sw);
// Type
ListItemAddW (list, i, GetString ("TYPE"));
if (bSysEnc)
ListSubItemSetW (list, i++, 1, GetString (IsHiddenOSRunning() ? "TYPE_HIDDEN_SYSTEM_ADJECTIVE" : "SYSTEM_VOLUME_TYPE_ADJECTIVE"));
else
{
ListSubItemSetW (list, i++, 1,
prop.hiddenVolume ? GetString ("HIDDEN") :
(prop.hiddenVolProtection != HIDVOL_PROT_STATUS_NONE ? GetString ("OUTER") : GetString ("NORMAL")));
}
if (!bSysEnc)
{
// Write protection
ListItemAddW (list, i, GetString ("READ_ONLY"));
if (prop.readOnly || prop.hiddenVolProtection == HIDVOL_PROT_STATUS_ACTION_TAKEN)
s = GetString ("UISTR_YES");
@@ -2785,82 +2796,82 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP
if (prop.ea == 0 || prop.ea > EAGetCount ())
{
ListSubItemSet (list, i, 1, "?");
return 1;
}
EAGetName (szTmp, prop.ea);
ListSubItemSet (list, i++, 1, szTmp);
// Key size(s)
{
char name[128];
int size = EAGetKeySize (prop.ea);
EAGetName (name, prop.ea);
if (strcmp (name, "Triple DES") == 0) /* Deprecated/legacy */
size -= 3; // Compensate for parity bytes
// Primary key
ListItemAddW (list, i, GetString ("KEY_SIZE"));
- wsprintfW (sw, L"%d %s", size * 8, GetString ("BITS"));
+ StringCbPrintfW (sw, sizeof(sw), L"%d %s", size * 8, GetString ("BITS"));
ListSubItemSetW (list, i++, 1, sw);
if (strcmp (EAGetModeName (prop.ea, prop.mode, TRUE), "XTS") == 0)
{
// Secondary key (XTS)
ListItemAddW (list, i, GetString ("SECONDARY_KEY_SIZE_XTS"));
ListSubItemSetW (list, i++, 1, sw);
}
else if (strcmp (EAGetModeName (prop.ea, prop.mode, TRUE), "LRW") == 0)
{
// Tweak key (LRW)
ListItemAddW (list, i, GetString ("SECONDARY_KEY_SIZE_LRW"));
- swprintf (sw, L"%d %s", CipherGetBlockSize (EAGetFirstCipher(prop.ea))*8, GetString ("BITS"));
+ StringCbPrintfW (sw, sizeof(sw), L"%d %s", CipherGetBlockSize (EAGetFirstCipher(prop.ea))*8, GetString ("BITS"));
ListSubItemSetW (list, i++, 1, sw);
}
}
// Block size
ListItemAddW (list, i, GetString ("BLOCK_SIZE"));
if (EAGetFirstMode (prop.ea) == INNER_CBC)
{
// Cascaded ciphers with non-equal block sizes (deprecated/legacy)
wchar_t tmpstr[64];
int i = EAGetLastCipher(prop.ea);
- swprintf (sw, L"%d", CipherGetBlockSize(i)*8);
+ StringCbPrintfW (sw, sizeof(sw), L"%d", CipherGetBlockSize(i)*8);
while (i = EAGetPreviousCipher(prop.ea, i))
{
- swprintf (tmpstr, L"/%d", CipherGetBlockSize(i)*8);
- wcscat (sw, tmpstr);
+ StringCbPrintfW (tmpstr, sizeof(tmpstr), L"/%d", CipherGetBlockSize(i)*8);
+ StringCbCatW (sw, sizeof(sw), tmpstr);
}
- wcscat (sw, L" ");
+ StringCbCatW (sw, sizeof(sw), L" ");
}
else
{
- swprintf (sw, L"%d ", CipherGetBlockSize (EAGetFirstCipher(prop.ea))*8);
+ StringCbPrintfW (sw, sizeof(sw), L"%d ", CipherGetBlockSize (EAGetFirstCipher(prop.ea))*8);
}
- wcscat (sw, GetString ("BITS"));
+ StringCbCatW (sw, sizeof(sw), GetString ("BITS"));
ListSubItemSetW (list, i++, 1, sw);
// Mode
ListItemAddW (list, i, GetString ("MODE_OF_OPERATION"));
ListSubItemSet (list, i++, 1, EAGetModeName (prop.ea, prop.mode, TRUE));
// PKCS 5 PRF
ListItemAddW (list, i, GetString ("PKCS5_PRF"));
ListSubItemSet (list, i++, 1, get_pkcs5_prf_name (prop.pkcs5));
#if 0
// PCKS 5 iterations
ListItemAddW (list, i, GetString ("PKCS5_ITERATIONS"));
sprintf (szTmp, "%d", prop.pkcs5Iterations);
ListSubItemSet (list, i++, 1, szTmp);
#endif
#if 0
{
// Legacy
@@ -2889,75 +2900,75 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP
swprintf (date, L"%s ", sw);
GetTimeFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2);
wcscat (date, sw);
GetLocalTime (&st);
SystemTimeToFileTime (&st, &curFt);
curFt64.HighPart = curFt.dwHighDateTime;
curFt64.LowPart = curFt.dwLowDateTime;
ft64.HighPart = ft.dwHighDateTime;
ft64.LowPart = ft.dwLowDateTime;
swprintf (date + wcslen (date), GetString ("VOLUME_HEADER_DAYS")
, (curFt64.QuadPart - ft64.QuadPart)/(24LL*3600*10000000));
ListSubItemSetW (list, i++, 1, date);
}
#endif // 0
if (!bSysEnc || IsHiddenOSRunning())
{
// Volume format version
ListItemAddW (list, i, GetString ("VOLUME_FORMAT_VERSION"));
- sprintf (szTmp, "%d", prop.volFormatVersion);
+ StringCbPrintfA (szTmp, sizeof(szTmp), "%d", prop.volFormatVersion);
ListSubItemSet (list, i++, 1, szTmp);
// Backup header
ListItemAddW (list, i, GetString ("BACKUP_HEADER"));
ListSubItemSetW (list, i++, 1, GetString (prop.volFormatVersion > 1 ? "UISTR_YES" : "UISTR_NO"));
}
// Total data read
ListItemAddW (list, i, GetString ("TOTAL_DATA_READ"));
- GetSizeString (prop.totalBytesRead, sw);
+ GetSizeString (prop.totalBytesRead, sw, sizeof(sw));
ListSubItemSetW (list, i++, 1, sw);
// Total data written
ListItemAddW (list, i, GetString ("TOTAL_DATA_WRITTEN"));
- GetSizeString (prop.totalBytesWritten, sw);
+ GetSizeString (prop.totalBytesWritten, sw, sizeof(sw));
ListSubItemSetW (list, i++, 1, sw);
if (bSysEnc)
{
// TrueCrypt Boot Loader version
ListItemAddW (list, i, GetString ("VC_BOOT_LOADER_VERSION"));
ListSubItemSet (list, i++, 1, (char *) GetUserFriendlyVersionString (BootEncStatus.BootLoaderVersion).c_str());
// Encrypted portion
ListItemAddW (list, i, GetString ("ENCRYPTED_PORTION"));
if (GetSysEncDeviceEncryptedPartSize (FALSE) == GetSysEncDeviceSize (FALSE))
ListSubItemSetW (list, i++, 1, GetString ("ENCRYPTED_PORTION_FULLY_ENCRYPTED"));
else if (GetSysEncDeviceEncryptedPartSize (FALSE) <= 1)
ListSubItemSetW (list, i++, 1, GetString ("ENCRYPTED_PORTION_NOT_ENCRYPTED"));
else
{
- _snwprintf (sw,
- sizeof sw/2,
+ StringCbPrintfW (sw,
+ sizeof sw,
GetString ("PROCESSED_PORTION_X_PERCENT"),
(double) GetSysEncDeviceEncryptedPartSize (FALSE) / (double) GetSysEncDeviceSize (FALSE) * 100.0);
ListSubItemSetW (list, i++, 1, sw);
}
}
return 0;
}
case WM_COMMAND:
if (lw == IDOK)
{
EndDialog (hwndDlg, lw);
return 1;
}
return 0;
case WM_CLOSE:
EndDialog (hwndDlg, lw);
@@ -3061,150 +3072,152 @@ BOOL CALLBACK TravelerDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa
return 1;
}
if (lw == IDCANCEL || lw == IDCLOSE)
{
EndDialog (hwndDlg, lw);
return 1;
}
if (lw == IDC_CREATE)
{
BOOL copyWizard, bExplore, bCacheInDriver, bAutoRun, bAutoMount, bMountReadOnly;
char dstDir[MAX_PATH];
char srcPath[MAX_PATH * 2];
char dstPath[MAX_PATH * 2];
char appDir[MAX_PATH];
char sysDir[MAX_PATH];
char volName[MAX_PATH];
int drive;
+ char* ptr;
GetDlgItemText (hwndDlg, IDC_DIRECTORY, dstDir, sizeof dstDir);
volName[0] = 0;
GetDlgItemText (hwndDlg, IDC_VOLUME_NAME, volName + 1, sizeof volName);
drive = SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_GETCURSEL, 0, 0);
drive = SendDlgItemMessage (hwndDlg, IDC_DRIVELIST, CB_GETITEMDATA, drive, 0);
copyWizard = IsButtonChecked (GetDlgItem (hwndDlg, IDC_COPY_WIZARD));
bExplore = IsButtonChecked (GetDlgItem (hwndDlg, IDC_TRAVEL_OPEN_EXPLORER));
bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_TRAV_CACHE_PASSWORDS));
bMountReadOnly = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY));
bAutoRun = !IsButtonChecked (GetDlgItem (hwndDlg, IDC_AUTORUN_DISABLE));
bAutoMount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_AUTORUN_MOUNT));
if (dstDir[0] == 0)
{
SetFocus (GetDlgItem (hwndDlg, IDC_DIRECTORY));
MessageBoxW (hwndDlg, GetString ("NO_PATH_SELECTED"), lpszTitle, MB_ICONEXCLAMATION);
return 1;
}
if (bAutoMount && volName[1] == 0)
{
SetFocus (GetDlgItem (hwndDlg, IDC_VOLUME_NAME));
MessageBoxW (hwndDlg, GetString ("NO_FILE_SELECTED"), lpszTitle, MB_ICONEXCLAMATION);
return 1;
}
if (volName[1] != 0)
{
volName[0] = '"';
- strcat (volName, "\"");
+ StringCbCatA (volName, sizeof(volName), "\"");
}
GetModuleFileName (NULL, appDir, sizeof (appDir));
- strrchr (appDir, '\\')[0] = 0;
+ if (ptr = strrchr (appDir, '\\'))
+ ptr[0] = 0;
WaitCursor ();
GetSystemDirectory (sysDir, sizeof (sysDir));
- sprintf (dstPath, "%s\\VeraCrypt", dstDir);
+ StringCbPrintfA (dstPath, sizeof(dstPath), "%s\\VeraCrypt", dstDir);
CreateDirectory (dstPath, NULL);
// Main app
- sprintf (srcPath, "%s\\VeraCrypt.exe", appDir);
- sprintf (dstPath, "%s\\VeraCrypt\\VeraCrypt.exe", dstDir);
+ StringCbPrintfA (srcPath, sizeof(srcPath), "%s\\VeraCrypt.exe", appDir);
+ StringCbPrintfA (dstPath, sizeof(dstPath), "%s\\VeraCrypt\\VeraCrypt.exe", dstDir);
if (!TCCopyFile (srcPath, dstPath))
{
handleWin32Error (hwndDlg);
goto stop;
}
// Wizard
if (copyWizard)
{
- sprintf (srcPath, "%s\\VeraCrypt Format.exe", appDir);
- sprintf (dstPath, "%s\\VeraCrypt\\VeraCrypt Format.exe", dstDir);
+ StringCbPrintfA (srcPath, sizeof(srcPath), "%s\\VeraCrypt Format.exe", appDir);
+ StringCbPrintfA (dstPath, sizeof(dstPath), "%s\\VeraCrypt\\VeraCrypt Format.exe", dstDir);
if (!TCCopyFile (srcPath, dstPath))
{
handleWin32Error (hwndDlg);
goto stop;
}
}
// Driver
- sprintf (srcPath, "%s\\veracrypt.sys", appDir);
- sprintf (dstPath, "%s\\VeraCrypt\\veracrypt.sys", dstDir);
+ StringCbPrintfA (srcPath, sizeof(srcPath), "%s\\veracrypt.sys", appDir);
+ StringCbPrintfA (dstPath, sizeof(dstPath), "%s\\VeraCrypt\\veracrypt.sys", dstDir);
if (!TCCopyFile (srcPath, dstPath))
{
handleWin32Error (hwndDlg);
goto stop;
}
// Driver x64
- sprintf (srcPath, "%s\\veracrypt-x64.sys", appDir);
- sprintf (dstPath, "%s\\VeraCrypt\\veracrypt-x64.sys", dstDir);
+ StringCbPrintfA (srcPath, sizeof(srcPath), "%s\\veracrypt-x64.sys", appDir);
+ StringCbPrintfA (dstPath, sizeof(dstPath), "%s\\VeraCrypt\\veracrypt-x64.sys", dstDir);
if (!TCCopyFile (srcPath, dstPath))
{
handleWin32Error (hwndDlg);
goto stop;
}
if (GetPreferredLangId () && strcmp (GetPreferredLangId (), "en") != 0)
{
// Language pack
- sprintf (srcPath, "%s\\Language.%s.xml", appDir, GetPreferredLangId ());
- sprintf (dstPath, "%s\\VeraCrypt\\Language.%s.xml", dstDir, GetPreferredLangId ());
+ StringCbPrintfA (srcPath, sizeof(srcPath), "%s\\Language.%s.xml", appDir, GetPreferredLangId ());
+ StringCbPrintfA (dstPath, sizeof(dstPath), "%s\\VeraCrypt\\Language.%s.xml", dstDir, GetPreferredLangId ());
TCCopyFile (srcPath, dstPath);
}
// AutoRun
- sprintf (dstPath, "%s\\autorun.inf", dstDir);
+ StringCbPrintfA (dstPath, sizeof(dstPath), "%s\\autorun.inf", dstDir);
DeleteFile (dstPath);
if (bAutoRun)
{
FILE *af;
char autoMount[100];
char driveLetter[] = { ' ', '/', 'l', (char) drive, 0 };
af = fopen (dstPath, "w,ccs=UNICODE");
if (af == NULL)
{
MessageBoxW (hwndDlg, GetString ("CANT_CREATE_AUTORUN"), lpszTitle, MB_ICONERROR);
goto stop;
}
- sprintf (autoMount, "VeraCrypt\\VeraCrypt.exe /q background%s%s%s%s /m rm /v %s",
+ StringCbPrintfA (autoMount, sizeof(autoMount), "VeraCrypt\\VeraCrypt.exe /q background%s%s%s%s /m rm /v %s",
drive > 0 ? driveLetter : "",
bExplore ? " /e" : "",
bCacheInDriver ? " /c y" : "",
bMountReadOnly ? " /m ro" : "",
volName);
fwprintf (af, L"[autorun]\nlabel=%s\nicon=VeraCrypt\\VeraCrypt.exe\n", GetString ("TC_TRAVELER_DISK"));
fwprintf (af, L"action=%s\n", bAutoMount ? GetString ("MOUNT_TC_VOLUME") : GetString ("IDC_PREF_LOGON_START"));
fwprintf (af, L"open=%hs\n", bAutoMount ? autoMount : "VeraCrypt\\VeraCrypt.exe");
fwprintf (af, L"shell\\start=%s\nshell\\start\\command=VeraCrypt\\VeraCrypt.exe\n", GetString ("IDC_PREF_LOGON_START"));
fwprintf (af, L"shell\\dismount=%s\nshell\\dismount\\command=VeraCrypt\\VeraCrypt.exe /q /d\n", GetString ("DISMOUNT_ALL_TC_VOLUMES"));
CheckFileStreamWriteErrors (af, dstPath);
fclose (af);
}
MessageBoxW (hwndDlg, GetString ("TRAVELER_DISK_CREATED"), lpszTitle, MB_ICONINFORMATION);
stop:
NormalCursor ();
return 1;
@@ -3435,41 +3448,41 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, char *szFileName)
if (modeOfOperation == CBC || modeOfOperation == OUTER_CBC)
Warning("WARN_CBC_MODE");
// Check for deprecated 64-bit-block ciphers
if (GetCipherBlockSizeByDriveNo (nDosDriveNo) == 64)
Warning("WARN_64_BIT_BLOCK_CIPHER");
// Check for problematic file extensions (exe, dll, sys)
if (CheckFileExtension(szFileName))
Warning ("EXE_FILE_EXTENSION_MOUNT_WARNING");
}
while (mounted == 0)
{
if (CmdVolumePassword.Length > 0)
{
VolumePassword = CmdVolumePassword;
}
else if (!Silent)
{
- strcpy (PasswordDlgVolume, szFileName);
+ StringCbCopyA (PasswordDlgVolume, sizeof(PasswordDlgVolume), szFileName);
if (!AskVolumePassword (hwndDlg, &VolumePassword, NULL, TRUE))
goto ret;
}
WaitCursor ();
if (KeyFilesEnable)
KeyFilesApply (&VolumePassword, FirstKeyFile);
mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, bCacheInDriver, bForceMount, &mountOptions, Silent, !Silent);
NormalCursor ();
// Check for deprecated CBC mode
modeOfOperation = GetModeOfOperationByDriveNo (nDosDriveNo);
if (modeOfOperation == CBC || modeOfOperation == OUTER_CBC)
Warning("WARN_CBC_MODE");
// Check for deprecated 64-bit-block ciphers
if (GetCipherBlockSizeByDriveNo (nDosDriveNo) == 64)
@@ -3598,41 +3611,41 @@ retry:
do
{
bResult = DeviceIoControl (hDriver, TC_IOCTL_DISMOUNT_ALL_VOLUMES, &unmount,
sizeof (unmount), &unmount, sizeof (unmount), &dwResult, NULL);
if (bResult == FALSE)
{
NormalCursor();
handleWin32Error (hwndDlg);
return FALSE;
}
if (unmount.nReturnCode == ERR_SUCCESS
&& unmount.HiddenVolumeProtectionTriggered
&& !VolumeNotificationsList.bHidVolDamagePrevReported [unmount.nDosDriveNo])
{
wchar_t msg[4096];
VolumeNotificationsList.bHidVolDamagePrevReported [unmount.nDosDriveNo] = TRUE;
- swprintf (msg, GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), unmount.nDosDriveNo + 'A');
+ StringCbPrintfW (msg, sizeof(msg), GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), unmount.nDosDriveNo + 'A');
SetForegroundWindow (hwndDlg);
MessageBoxW (hwndDlg, msg, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST);
unmount.HiddenVolumeProtectionTriggered = FALSE;
continue;
}
if (unmount.nReturnCode == ERR_FILES_OPEN)
Sleep (dismountAutoRetryDelay);
else
break;
} while (--dismountMaxRetries > 0);
memset (&mountList, 0, sizeof (mountList));
DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mountList, sizeof (mountList), &mountList, sizeof (mountList), &dwResult, NULL);
BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, 0, prevMountedDrives & ~mountList.ulMountedDrives);
RefreshMainDlg (hwndDlg);
@@ -3819,43 +3832,43 @@ static BOOL MountAllDevices (HWND hwndDlg, BOOL bPasswordPrompt)
IncreaseWrongPwdRetryCount (1);
if (WrongPwdRetryCountOverLimit ()
&& !mountOptions.UseBackupHeader
&& !bHeaderBakRetry)
{
// Retry using embedded header backup (if any)
mountOptions.UseBackupHeader = TRUE;
bHeaderBakRetry = TRUE;
}
else if (bHeaderBakRetry)
{
mountOptions.UseBackupHeader = defaultMountOptions.UseBackupHeader;
bHeaderBakRetry = FALSE;
}
if (!Silent && !bHeaderBakRetry)
{
WCHAR szTmp[4096];
- swprintf (szTmp, GetString (KeyFilesEnable || FirstCmdKeyFile ? "PASSWORD_OR_KEYFILE_WRONG_AUTOMOUNT" : "PASSWORD_WRONG_AUTOMOUNT"));
+ StringCbPrintfW (szTmp, sizeof(szTmp), GetString (KeyFilesEnable || FirstCmdKeyFile ? "PASSWORD_OR_KEYFILE_WRONG_AUTOMOUNT" : "PASSWORD_WRONG_AUTOMOUNT"));
if (CheckCapsLock (hwndDlg, TRUE))
- wcscat (szTmp, GetString ("PASSWORD_WRONG_CAPSLOCK_ON"));
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("PASSWORD_WRONG_CAPSLOCK_ON"));
MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_ICONWARNING);
}
}
else if (bHeaderBakRetry)
{
// We have successfully mounted a volume using the header backup embedded in the volume (the header is damaged)
mountOptions.UseBackupHeader = defaultMountOptions.UseBackupHeader;
bHeaderBakRetry = FALSE;
if (!Silent)
Warning ("HEADER_DAMAGED_AUTO_USED_HEADER_BAK");
}
if (!bHeaderBakRetry)
{
burn (&VolumePassword, sizeof (VolumePassword));
burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword));
}
@@ -3969,41 +3982,41 @@ static void ChangeSysEncPassword (HWND hwndDlg, BOOL bOnlyChangeKDF)
}
if (!BootEncStatus.DriveEncrypted
&& !BootEncStatus.DriveMounted
&& !BootEncStatus.VolumeHeaderPresent
&& !SysEncryptionOrDecryptionRequired ())
{
Warning ("SYS_DRIVE_NOT_ENCRYPTED");
return;
}
if (SysEncryptionOrDecryptionRequired ()
|| BootEncStatus.SetupInProgress)
{
Warning ("SYSTEM_ENCRYPTION_NOT_COMPLETED");
return;
}
if (CreateSysEncMutex ()) // If no instance of the wizard is currently taking care of system encryption
{
- sprintf (OrigKeyboardLayout, "%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF);
+ StringCbPrintfA (OrigKeyboardLayout, sizeof(OrigKeyboardLayout), "%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF);
bSysEncPwdChangeDlgMode = TRUE;
if (bOnlyChangeKDF)
pwdChangeDlgMode = PCDM_CHANGE_PKCS5_PRF;
else
pwdChangeDlgMode = PCDM_CHANGE_PASSWORD;
INT_PTR result = DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_PASSWORDCHANGE_DLG), hwndDlg, (DLGPROC) PasswordChangeDlgProc);
bSysEncPwdChangeDlgMode = FALSE;
if (bKeyboardLayoutChanged)
{
// Restore the original keyboard layout
if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL)
Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT");
else
bKeyboardLayoutChanged = FALSE;
@@ -4234,41 +4247,41 @@ void CreateRescueDisk (void)
char szRescueDiskISO [TC_MAX_PATH+1];
if (AskOkCancel ("RESCUE_DISK_NON_WIZARD_CREATION_SELECT_PATH") != IDOK)
{
CloseSysEncMutex ();
return;
}
char initialDir[MAX_PATH];
SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, 0, initialDir);
if (!BrowseFilesInDir (MainDlg, "OPEN_TITLE", initialDir, szRescueDiskISO, FALSE, TRUE, NULL, L"VeraCrypt Rescue Disk.iso", L"iso"))
{
CloseSysEncMutex ();
return;
}
WaitCursor();
BootEncObj->CreateRescueIsoImage (false, szRescueDiskISO);
- _snwprintf (szTmp, sizeof szTmp / 2,
+ StringCbPrintfW (szTmp, sizeof szTmp,
GetString (IsWindowsIsoBurnerAvailable() ? "RESCUE_DISK_NON_WIZARD_CREATION_WIN_ISOBURN" : "RESCUE_DISK_NON_WIZARD_CREATION_BURN"),
szRescueDiskISO);
if (IsWindowsIsoBurnerAvailable())
{
if (AskYesNoString (szTmp) == IDYES)
LaunchWindowsIsoBurner (MainDlg, szRescueDiskISO);
}
else
InfoDirect (szTmp);
}
catch (Exception &e)
{
e.Show (MainDlg);
Error ("ERROR_CREATING_RESCUE_DISK");
}
CloseSysEncMutex ();
NormalCursor ();
}
@@ -4768,41 +4781,41 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
KeyFilesApply (&CmdVolumePassword, FirstCmdKeyFile);
mounted = MountVolume (hwndDlg, szDriveLetter[0] - 'A',
szFileName, &CmdVolumePassword, bCacheInDriver, bForceMount,
&mountOptions, Silent, reportBadPasswd);
burn (&CmdVolumePassword, sizeof (CmdVolumePassword));
}
if (FirstCmdKeyFile)
{
FirstKeyFile = FirstCmdKeyFile;
KeyFilesEnable = TRUE;
}
// Ask user for password
while (!mounted && !Silent)
{
VolumePassword.Length = 0;
- strcpy (PasswordDlgVolume, szFileName);
+ StringCbCopyA (PasswordDlgVolume, sizeof(PasswordDlgVolume),szFileName);
if (!AskVolumePassword (hwndDlg, &VolumePassword, NULL, TRUE))
break;
WaitCursor ();
if (KeyFilesEnable && FirstKeyFile)
KeyFilesApply (&VolumePassword, FirstKeyFile);
mounted = MountVolume (hwndDlg, szDriveLetter[0] - 'A', szFileName, &VolumePassword, bCacheInDriver, bForceMount, &mountOptions, FALSE, TRUE);
burn (&VolumePassword, sizeof (VolumePassword));
burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword));
NormalCursor ();
}
if (UsePreferences)
{
RestoreDefaultKeyFilesParam ();
bCacheInDriver = bCacheInDriverDefault;
@@ -5306,111 +5319,111 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
case TC_APPMSG_TASKBAR_ICON:
{
switch (lParam)
{
case WM_LBUTTONDOWN:
SetForegroundWindow (hwndDlg);
MainWindowHidden = FALSE;
ShowWindow (hwndDlg, SW_SHOW);
ShowWindow (hwndDlg, SW_RESTORE);
return 1;
case WM_RBUTTONUP:
{
POINT pos;
HMENU popup = CreatePopupMenu ();
int sel, i, n;
if (MainWindowHidden)
{
AppendMenuW (popup, MF_STRING, IDM_SHOW_HIDE, GetString ("SHOW_TC"));
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
}
else if (bEnableBkgTask
&& (!(LastKnownMountList.ulMountedDrives == 0
&& (bCloseBkgTaskWhenNoVolumes || IsNonInstallMode ())
&& !SysEncDeviceActive (TRUE)
&& GetDriverRefCount () < 2)))
{
AppendMenuW (popup, MF_STRING, IDM_SHOW_HIDE, GetString ("HIDE_TC"));
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
}
AppendMenuW (popup, MF_STRING, IDM_MOUNTALL, GetString ("IDC_MOUNTALL"));
AppendMenuW (popup, MF_STRING, IDM_MOUNT_FAVORITE_VOLUMES, GetString ("IDM_MOUNT_FAVORITE_VOLUMES"));
AppendMenuW (popup, MF_STRING, IDM_UNMOUNTALL, GetString ("IDC_UNMOUNTALL"));
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
for (n = 0; n < 2; n++)
{
for (i = 0; i < 26; i++)
{
if (LastKnownMountList.ulMountedDrives & (1 << i))
{
wchar_t s[1024];
wchar_t *vol = (wchar_t *) LastKnownMountList.wszVolume[i];
if (wcsstr (vol, L"\\??\\")) vol += 4;
wstring label = GetFavoriteVolumeLabel (WideToSingleString (vol));
- wsprintfW (s, L"%s %c: (%s)",
+ StringCbPrintfW (s, sizeof(s), L"%s %c: (%s)",
GetString (n==0 ? "OPEN" : "DISMOUNT"),
i + L'A',
label.empty() ? vol : label.c_str());
AppendMenuW (popup, MF_STRING, n*26 + TRAYICON_MENU_DRIVE_OFFSET + i, s);
}
}
if (LastKnownMountList.ulMountedDrives != 0)
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
}
AppendMenuW (popup, MF_STRING, IDM_HELP, GetString ("MENU_HELP"));
AppendMenuW (popup, MF_STRING, IDM_HOMEPAGE_SYSTRAY, GetString ("HOMEPAGE"));
AppendMenuW (popup, MF_STRING, IDM_PREFERENCES, GetString ("IDM_PREFERENCES"));
AppendMenuW (popup, MF_STRING, IDM_ABOUT, GetString ("IDM_ABOUT"));
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
AppendMenuW (popup, MF_STRING, IDCANCEL, GetString ("EXIT"));
GetCursorPos (&pos);
SetForegroundWindow(hwndDlg);
sel = TrackPopupMenu (popup,
TPM_RETURNCMD | TPM_LEFTALIGN | TPM_BOTTOMALIGN | TPM_RIGHTBUTTON,
pos.x,
pos.y,
0,
hwndDlg,
NULL);
if (sel >= TRAYICON_MENU_DRIVE_OFFSET && sel < TRAYICON_MENU_DRIVE_OFFSET + 26)
{
OpenVolumeExplorerWindow (sel - TRAYICON_MENU_DRIVE_OFFSET);
}
else if (sel >= TRAYICON_MENU_DRIVE_OFFSET + 26 && sel < TRAYICON_MENU_DRIVE_OFFSET + 26*2)
{
if (CheckMountList ())
{
if (Dismount (hwndDlg, sel - TRAYICON_MENU_DRIVE_OFFSET - 26))
{
wchar_t txt [2048];
- wsprintfW (txt, GetString ("VOLUME_MOUNTED_AS_DRIVE_LETTER_X_DISMOUNTED"), sel - TRAYICON_MENU_DRIVE_OFFSET - 26 + L'A');
+ StringCbPrintfW (txt, sizeof(txt), GetString ("VOLUME_MOUNTED_AS_DRIVE_LETTER_X_DISMOUNTED"), sel - TRAYICON_MENU_DRIVE_OFFSET - 26 + L'A');
InfoBalloonDirect (GetString ("SUCCESSFULLY_DISMOUNTED"), txt);
}
}
}
else if (sel == IDM_SHOW_HIDE)
{
ChangeMainWindowVisibility ();
}
else if (sel == IDM_HOMEPAGE_SYSTRAY)
{
Applink ("home", TRUE, "");
}
else if (sel == IDCANCEL)
{
if ((LastKnownMountList.ulMountedDrives == 0
&& !SysEncDeviceActive (TRUE))
|| AskWarnNoYes ("CONFIRM_EXIT") == IDYES)
{
// Close all other TC windows
@@ -5482,41 +5495,41 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
UnmountVolume (hwndDlg, m, TRUE);
WarningBalloon ("HOST_DEVICE_REMOVAL_DISMOUNT_WARN_TITLE", "HOST_DEVICE_REMOVAL_DISMOUNT_WARN");
}
}
}
}
}
}
// Device-hosted volumes
for (m = 0; m < 26; m++)
{
if (LastKnownMountList.ulMountedDrives & (1 << m))
{
wchar_t *vol = (wchar_t *) LastKnownMountList.wszVolume[m];
char volp[MAX_PATH];
if (wcsstr (vol, L"\\??\\") == vol)
vol += 4;
- _snprintf (volp, sizeof(volp), "%ls", vol);
+ StringCbPrintfA (volp, sizeof(volp), "%ls", vol);
if (IsVolumeDeviceHosted (volp))
{
OPEN_TEST_STRUCT ots;
if (!OpenDevice (volp, &ots, FALSE))
{
UnmountVolume (hwndDlg, m, TRUE);
WarningBalloon ("HOST_DEVICE_REMOVAL_DISMOUNT_WARN_TITLE", "HOST_DEVICE_REMOVAL_DISMOUNT_WARN");
}
}
}
}
// Favorite volumes
UpdateDeviceHostedFavoriteVolumes();
return 1;
}
return 0;
@@ -5586,58 +5599,58 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
case LVN_BEGINRDRAG:
/* If the mouse was moving while the right mouse button is pressed, popup menu would
not open, because drag&drop operation would be initiated. Therefore, we're handling
RMB drag-and-drop operations as well. */
{
/* Drive list context menu */
int menuItem;
HMENU popup = CreatePopupMenu ();
SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST));
switch (LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))))
{
case TC_MLIST_ITEM_FREE:
// No mounted volume at this drive letter
AppendMenuW (popup, MF_STRING, IDM_MOUNT_VOLUME, GetString ("IDM_MOUNT_VOLUME"));
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
AppendMenuW (popup, MF_STRING, IDPM_SELECT_FILE_AND_MOUNT, GetString ("SELECT_FILE_AND_MOUNT"));
AppendMenuW (popup, MF_STRING, IDPM_SELECT_DEVICE_AND_MOUNT, GetString ("SELECT_DEVICE_AND_MOUNT"));
break;
case TC_MLIST_ITEM_NONSYS_VOL:
// There's a mounted non-system volume at this drive letter
AppendMenuW (popup, MF_STRING, IDM_UNMOUNT_VOLUME, GetString ("DISMOUNT"));
AppendMenuW (popup, MF_STRING, IDPM_OPEN_VOLUME, GetString ("OPEN"));
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
AppendMenuW (popup, MF_STRING, IDPM_CHECK_FILESYS, GetString ("IDPM_CHECK_FILESYS"));
AppendMenuW (popup, MF_STRING, IDPM_REPAIR_FILESYS, GetString ("IDPM_REPAIR_FILESYS"));
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
AppendMenuW (popup, MF_STRING, IDPM_ADD_TO_FAVORITES, GetString ("IDPM_ADD_TO_FAVORITES"));
AppendMenuW (popup, MF_STRING, IDPM_ADD_TO_SYSTEM_FAVORITES, GetString ("IDPM_ADD_TO_SYSTEM_FAVORITES"));
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
AppendMenuW (popup, MF_STRING, IDM_VOLUME_PROPERTIES, GetString ("IDPM_PROPERTIES"));
break;
case TC_MLIST_ITEM_SYS_PARTITION:
case TC_MLIST_ITEM_SYS_DRIVE:
// System partition/drive
PopulateSysEncContextMenu (popup, FALSE);
break;
}
mPos=GetMessagePos();
menuItem = TrackPopupMenu (popup,
TPM_RETURNCMD | TPM_LEFTBUTTON,
GET_X_LPARAM(mPos),
GET_Y_LPARAM(mPos),
0,
hwndDlg,
@@ -5850,44 +5863,44 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
break;
}
if (lw == IDC_VOLUME_TOOLS)
{
/* Volume Tools popup menu */
int menuItem;
char volPath[TC_MAX_PATH]; /* Volume to mount */
HMENU popup = CreatePopupMenu ();
RECT rect;
if (ActiveSysEncDeviceSelected ())
{
PopulateSysEncContextMenu (popup, TRUE);
}
else
{
AppendMenuW (popup, MF_STRING, IDM_CHANGE_PASSWORD, GetString ("IDM_CHANGE_PASSWORD"));
AppendMenuW (popup, MF_STRING, IDM_CHANGE_HEADER_KEY_DERIV_ALGO, GetString ("IDM_CHANGE_HEADER_KEY_DERIV_ALGO"));
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
AppendMenuW (popup, MF_STRING, IDM_ADD_REMOVE_VOL_KEYFILES, GetString ("IDM_ADD_REMOVE_VOL_KEYFILES"));
AppendMenuW (popup, MF_STRING, IDM_REMOVE_ALL_KEYFILES_FROM_VOL, GetString ("IDM_REMOVE_ALL_KEYFILES_FROM_VOL"));
- AppendMenu (popup, MF_SEPARATOR, 0, NULL);
+ AppendMenu (popup, MF_SEPARATOR, 0, "");
AppendMenuW (popup, MF_STRING, IDM_BACKUP_VOL_HEADER, GetString ("IDM_BACKUP_VOL_HEADER"));
AppendMenuW (popup, MF_STRING, IDM_RESTORE_VOL_HEADER, GetString ("IDM_RESTORE_VOL_HEADER"));
}
GetWindowRect (GetDlgItem (hwndDlg, IDC_VOLUME_TOOLS), &rect);
menuItem = TrackPopupMenu (popup,
TPM_RETURNCMD | TPM_LEFTBUTTON,
rect.left + 2,
rect.top + 2,
0,
hwndDlg,
NULL);
DestroyMenu (popup);
switch (menuItem)
{
case IDM_CHANGE_PASSWORD:
if (!VolumeSelected(hwndDlg))
@@ -6233,43 +6246,43 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa
else
{
/* We need to resolve selection ambiguity. Two different mounted volumes are currently
selected (one in the drive letter list and the other in the input field below the list). */
VOLUME_PROPERTIES_STRUCT prop;
DWORD dwResult;
memset (&prop, 0, sizeof(prop));
prop.driveNo = HIWORD (selectedDrive) - 'A';
if (!DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL) || dwResult == 0)
{
Warning ("SELECT_A_MOUNTED_VOLUME");
return 1;
}
// volPathHigher will contain the volume path selected in the main drive list
wstring volPathHigher (prop.wszVolume);
- ToSBCS (prop.wszVolume);
- strcpy ((char *) volPathLowerW, volPathLower);
- ToUNICODE ((char *) volPathLowerW);
+ ToSBCS (prop.wszVolume, sizeof(prop.wszVolume));
+ StringCbCopyA ((char *) volPathLowerW, sizeof(volPathLowerW), volPathLower);
+ ToUNICODE ((char *) volPathLowerW, sizeof(volPathLowerW));
if (strcmp (((memcmp ((char *) prop.wszVolume, "\\??\\", 4) == 0) ? (char *) prop.wszVolume + 4 : (char *) prop.wszVolume), volPathLower) != 0)
{
// The path selected in the input field is different from the path to the volume selected
// in the drive lettter list. We have to resolve possible ambiguity.
wchar_t *tmp[] = {L"", L"", L"", L"", L"", 0};
const int maxVolPathLen = 80;
if (volPathHigher.length () > maxVolPathLen)
{
volPathHigher = wstring (L"...") + volPathHigher.substr (volPathHigher.length () - maxVolPathLen, maxVolPathLen);
}
wstring volPathLowerWStr (volPathLowerW);
if (volPathLowerWStr.length () > maxVolPathLen)
{
volPathLowerWStr = wstring (L"...") + volPathLowerWStr.substr (volPathLowerWStr.length () - maxVolPathLen, maxVolPathLen);
}
@@ -6683,42 +6696,45 @@ void ExtractCommandLine (HWND hwndDlg, char *lpszCommandLine)
cmdUnmountDrive = -1;
break;
case OptionExplore:
bExplore = TRUE;
break;
case OptionForce:
bForceMount = TRUE;
bForceUnmount = TRUE;
break;
case OptionKeyfile:
if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, nArgPos, &i,
nNoCommandLineArgs, tmpPath, sizeof (tmpPath)))
{
KeyFile *kf;
RelativePath2Absolute (tmpPath);
kf = (KeyFile *) malloc (sizeof (KeyFile));
- strncpy (kf->FileName, tmpPath, sizeof (kf->FileName) - 1);
- FirstCmdKeyFile = KeyFileAdd (FirstCmdKeyFile, kf);
+ if (kf)
+ {
+ StringCbCopyA (kf->FileName, sizeof(kf->FileName), tmpPath);
+ FirstCmdKeyFile = KeyFileAdd (FirstCmdKeyFile, kf);
+ }
}
break;
case OptionLetter:
GetArgumentValue (lpszCommandLineArgs, nArgPos, &i, nNoCommandLineArgs,
szDriveLetter, sizeof (szDriveLetter));
commandLineDrive = *szDriveLetter = (char) toupper (*szDriveLetter);
if (commandLineDrive < 'C' || commandLineDrive > 'Z')
AbortProcess ("BAD_DRIVE_LETTER");
break;
case OptionHistory:
{
char szTmp[8];
bHistory = bHistoryCmdLine = TRUE;
GetArgumentValue (lpszCommandLineArgs, nArgPos, &i, nNoCommandLineArgs,
szTmp, sizeof (szTmp));
@@ -7008,41 +7024,41 @@ BOOL TaskBarIconAdd (HWND hwnd)
{
CloseHandle(TaskBarIconMutex);
TaskBarIconMutex = NULL;
}
return FALSE;
}
tnid.cbSize = sizeof (NOTIFYICONDATAW);
tnid.hWnd = hwnd;
tnid.uID = IDI_TRUECRYPT_ICON;
tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
tnid.uCallbackMessage = TC_APPMSG_TASKBAR_ICON;
tnid.hIcon = (HICON) LoadImage (hInst, MAKEINTRESOURCE (IDI_TRUECRYPT_ICON),
IMAGE_ICON,
ScreenDPI >= 120 ? 0 : 16,
ScreenDPI >= 120 ? 0 : 16,
(ScreenDPI >= 120 ? LR_DEFAULTSIZE : 0)
| LR_SHARED
| (nCurrentOS != WIN_2000 ? LR_DEFAULTCOLOR : LR_VGACOLOR)); // Windows 2000 cannot display more than 16 fixed colors in notification tray
- wcscpy (tnid.szTip, L"VeraCrypt");
+ StringCbCopyW (tnid.szTip, sizeof(tnid.szTip), L"VeraCrypt");
return Shell_NotifyIconW (NIM_ADD, &tnid);
}
BOOL TaskBarIconRemove (HWND hwnd)
{
if (TaskBarIconMutex != NULL)
{
NOTIFYICONDATA tnid;
BOOL res;
ZeroMemory (&tnid, sizeof (tnid));
tnid.cbSize = sizeof(NOTIFYICONDATA);
tnid.hWnd = hwnd;
tnid.uID = IDI_TRUECRYPT_ICON;
res = Shell_NotifyIcon (NIM_DELETE, &tnid);
if (TaskBarIconMutex)
{
@@ -7433,51 +7449,58 @@ static void HandleHotKey (HWND hwndDlg, WPARAM wParam)
break;
}
}
void ChangeMainWindowVisibility ()
{
MainWindowHidden = !MainWindowHidden;
if (!MainWindowHidden)
SetForegroundWindow (MainDlg);
ShowWindow (MainDlg, !MainWindowHidden ? SW_SHOW : SW_HIDE);
if (!MainWindowHidden)
ShowWindow (MainDlg, SW_RESTORE);
}
-int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, char *lpszVolume)
+int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, const char *lpszVolume)
{
int nStatus = ERR_OS_ERROR;
wchar_t szTmp[4096];
int fBackup = -1;
OpenVolumeContext volume;
OpenVolumeContext hiddenVolume;
Password hiddenVolPassword;
byte temporaryKey[MASTER_KEYDATA_SIZE];
byte originalK2[MASTER_KEYDATA_SIZE];
+ if (!lpszVolume)
+ {
+ nStatus = ERR_OUTOFMEMORY;
+ handleError (hwndDlg, nStatus);
+ return nStatus;
+ }
+
volume.VolumeIsOpen = FALSE;
hiddenVolume.VolumeIsOpen = FALSE;
switch (IsSystemDevicePath (lpszVolume, hwndDlg, TRUE))
{
case 1:
case 2:
if (AskErrNoYes ("BACKUP_HEADER_NOT_FOR_SYS_DEVICE") == IDYES)
CreateRescueDisk ();
return 0;
}
if (IsMountedVolume (lpszVolume))
{
Warning ("DISMOUNT_FIRST");
goto ret;
}
if (!VolumePathExists (lpszVolume))
@@ -7543,41 +7566,41 @@ int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, char *lpszVolum
}
}
break;
}
if (nStatus != ERR_PASSWORD_WRONG)
goto error;
handleError (hwndDlg, nStatus);
}
}
noHidden:
if (hiddenVolume.VolumeIsOpen && volume.CryptoInfo->LegacyVolume != hiddenVolume.CryptoInfo->LegacyVolume)
{
nStatus = ERR_PARAMETER_INCORRECT;
goto error;
}
- swprintf (szTmp, GetString ("CONFIRM_VOL_HEADER_BAK"), lpszVolume);
+ StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CONFIRM_VOL_HEADER_BAK"), lpszVolume);
if (bRequireConfirmation
&& (MessageBoxW (hwndDlg, szTmp, lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON1) == IDNO))
goto ret;
/* Select backup file */
if (!BrowseFiles (hwndDlg, "OPEN_TITLE", szFileName, bHistory, TRUE, NULL))
goto ret;
/* Conceive the backup file */
if ((fBackup = _open(szFileName, _O_CREAT|_O_TRUNC|_O_WRONLY|_O_BINARY, _S_IREAD|_S_IWRITE)) == -1)
{
nStatus = ERR_OS_ERROR;
goto error;
}
// Backup headers
byte backup[TC_VOLUME_HEADER_GROUP_SIZE];
@@ -7655,59 +7678,66 @@ error:
if (fBackup != -1)
_close (fBackup);
SetLastError (dwError);
if (nStatus != 0)
handleError (hwndDlg, nStatus);
burn (&VolumePassword, sizeof (VolumePassword));
burn (&hiddenVolPassword, sizeof (hiddenVolPassword));
burn (temporaryKey, sizeof (temporaryKey));
burn (originalK2, sizeof (originalK2));
RestoreDefaultKeyFilesParam();
RandStop (FALSE);
NormalCursor();
return nStatus;
}
-int RestoreVolumeHeader (HWND hwndDlg, char *lpszVolume)
+int RestoreVolumeHeader (HWND hwndDlg, const char *lpszVolume)
{
int nDosLinkCreated = -1, nStatus = ERR_OS_ERROR;
char szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH];
char szFileName[TC_MAX_PATH];
char szDosDevice[TC_MAX_PATH];
void *dev = INVALID_HANDLE_VALUE;
DWORD dwError;
BOOL bDevice;
unsigned __int64 hostSize = 0;
FILETIME ftCreationTime;
FILETIME ftLastWriteTime;
FILETIME ftLastAccessTime;
wchar_t szTmp[4096];
BOOL bTimeStampValid = FALSE;
HANDLE fBackup = INVALID_HANDLE_VALUE;
LARGE_INTEGER headerOffset;
CRYPTO_INFO *restoredCryptoInfo = NULL;
+ if (!lpszVolume)
+ {
+ nStatus = ERR_OUTOFMEMORY;
+ handleError (hwndDlg, nStatus);
+ return nStatus;
+ }
+
switch (IsSystemDevicePath (lpszVolume, hwndDlg, TRUE))
{
case 1:
case 2:
if (AskErrNoYes ("RESTORE_HEADER_NOT_FOR_SYS_DEVICE") == IDYES)
CreateRescueDisk ();
return 0;
case -1:
// In some environments (such as PE), the system volume is not located on a hard drive.
// Therefore, we must interpret this return code as "Not a system device path" (otherwise,
// it would not be possible to restore headers on non-system devices in such environments).
// Note that this is rather safe, because bReliableRequired is set to TRUE.
// NOP
break;
}
if (IsMountedVolume (lpszVolume))
@@ -7733,41 +7763,41 @@ int RestoreVolumeHeader (HWND hwndDlg, char *lpszVolume)
break;
case 2:
restoreInternalBackup = FALSE;
break;
default:
return 0;
}
OpenVolumeContext volume;
volume.VolumeIsOpen = FALSE;
WaitCursor();
if (restoreInternalBackup)
{
// Restore header from the internal backup
// Open the volume using backup header
while (TRUE)
{
- strncpy (PasswordDlgVolume, lpszVolume, sizeof (PasswordDlgVolume) - 1);
+ StringCbCopyA (PasswordDlgVolume, sizeof(PasswordDlgVolume), lpszVolume);
if (!AskVolumePassword (hwndDlg, &VolumePassword, NULL, FALSE))
{
nStatus = ERR_SUCCESS;
goto ret;
}
WaitCursor();
if (KeyFilesEnable && FirstKeyFile)
KeyFilesApply (&VolumePassword, FirstKeyFile);
nStatus = OpenVolume (&volume, lpszVolume, &VolumePassword, TRUE, bPreserveTimestamp, TRUE);
NormalCursor();
if (nStatus == ERR_SUCCESS)
break;
if (nStatus != ERR_PASSWORD_WRONG)
goto error;
@@ -7789,78 +7819,78 @@ int RestoreVolumeHeader (HWND hwndDlg, char *lpszVolume)
if (nStatus != 0)
goto error;
headerOffset.QuadPart = volume.CryptoInfo->hiddenVolume ? TC_HIDDEN_VOLUME_HEADER_OFFSET : TC_VOLUME_HEADER_OFFSET;
if (!SetFilePointerEx (volume.HostFileHandle, headerOffset, NULL, FILE_BEGIN))
{
nStatus = ERR_OS_ERROR;
goto error;
}
if (!WriteEffectiveVolumeHeader (volume.IsDevice, volume.HostFileHandle, (byte *) buffer))
{
nStatus = ERR_OS_ERROR;
goto error;
}
}
else
{
// Restore header from an external backup
- swprintf (szTmp, GetString ("CONFIRM_VOL_HEADER_RESTORE"), lpszVolume);
+ StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CONFIRM_VOL_HEADER_RESTORE"), lpszVolume);
if (MessageBoxW (hwndDlg, szTmp, lpszTitle, YES_NO|MB_ICONWARNING|MB_DEFBUTTON2) == IDNO)
{
nStatus = ERR_SUCCESS;
goto ret;
}
/* Select backup file */
if (!BrowseFiles (hwndDlg, "OPEN_TITLE", szFileName, bHistory, FALSE, NULL))
{
nStatus = ERR_SUCCESS;
goto ret;
}
/* Open the backup file */
fBackup = CreateFile (szFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (fBackup == INVALID_HANDLE_VALUE)
{
nStatus = ERR_OS_ERROR;
goto error;
}
// Determine size of the backup file
LARGE_INTEGER backupSize;
if (!GetFileSizeEx (fBackup, &backupSize))
{
nStatus = ERR_OS_ERROR;
goto error;
}
- CreateFullVolumePath (szDiskFile, lpszVolume, &bDevice);
+ CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), lpszVolume, &bDevice);
if (bDevice == FALSE)
- strcpy (szCFDevice, szDiskFile);
+ StringCbCopyA (szCFDevice, sizeof(szCFDevice), szDiskFile);
else
{
- nDosLinkCreated = FakeDosNameForDevice (szDiskFile, szDosDevice, szCFDevice, FALSE);
+ nDosLinkCreated = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice),szCFDevice, sizeof(szCFDevice),FALSE);
if (nDosLinkCreated != 0)
goto error;
}
// Open the volume
dev = CreateFile (szCFDevice, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (dev == INVALID_HANDLE_VALUE)
{
nStatus = ERR_OS_ERROR;
goto error;
}
// Determine volume host size
if (bDevice)
{
PARTITION_INFORMATION diskInfo;
DWORD dwResult;
BOOL bResult;
@@ -8285,46 +8315,46 @@ static BOOL CALLBACK SecurityTokenPreferencesDlgProc (HWND hwndDlg, UINT msg, WP
return 1;
case IDOK:
{
char securityTokenLibraryPath[MAX_PATH];
GetDlgItemText (hwndDlg, IDC_PKCS11_MODULE, securityTokenLibraryPath, sizeof (securityTokenLibraryPath));
if (securityTokenLibraryPath[0] == 0)
{
try
{
SecurityToken::CloseLibrary();
}
catch (...) { }
SecurityTokenLibraryPath[0] = 0;
}
else
{
char prevSecurityTokenLibraryPath[MAX_PATH];
- strcpy (prevSecurityTokenLibraryPath, SecurityTokenLibraryPath);
- strcpy (SecurityTokenLibraryPath, securityTokenLibraryPath);
+ StringCbCopyA (prevSecurityTokenLibraryPath, sizeof(prevSecurityTokenLibraryPath), SecurityTokenLibraryPath);
+ StringCbCopyA (SecurityTokenLibraryPath, sizeof(SecurityTokenLibraryPath), securityTokenLibraryPath);
if (!InitSecurityTokenLibrary())
{
- strcpy (SecurityTokenLibraryPath, prevSecurityTokenLibraryPath);
+ StringCbCopyA (SecurityTokenLibraryPath, sizeof(SecurityTokenLibraryPath), prevSecurityTokenLibraryPath);
return 1;
}
}
CloseSecurityTokenSessionsAfterMount = (IsDlgButtonChecked (hwndDlg, IDC_CLOSE_TOKEN_SESSION_AFTER_MOUNT) == BST_CHECKED);
WaitCursor ();
SaveSettings (hwndDlg);
NormalCursor ();
EndDialog (hwndDlg, lw);
return 1;
}
case IDC_AUTO_DETECT_PKCS11_MODULE:
{
char systemDir[MAX_PATH];
GetSystemDirectory (systemDir, sizeof (systemDir));
WIN32_FIND_DATA findData;
bool found = false;
@@ -8376,41 +8406,41 @@ static BOOL CALLBACK SecurityTokenPreferencesDlgProc (HWND hwndDlg, UINT msg, WP
if (find != INVALID_HANDLE_VALUE)
FindClose (find);
NormalCursor();
if (!found)
Warning ("PKCS11_MODULE_AUTO_DETECTION_FAILED");
return 1;
}
case IDC_SELECT_PKCS11_MODULE:
{
char securityTokenLibraryPath[MAX_PATH];
char systemDir[MAX_PATH];
wchar_t browseFilter[1024];
Info ("SELECT_PKCS11_MODULE_HELP");
- wsprintfW (browseFilter, L"%ls (*.dll)%c*.dll%c%c", GetString ("DLL_FILES"), 0, 0, 0);
+ StringCbPrintfW (browseFilter, sizeof(browseFilter), L"%ls (*.dll)%c*.dll%c%c", GetString ("DLL_FILES"), 0, 0, 0);
GetSystemDirectory (systemDir, sizeof (systemDir));
if (BrowseFilesInDir (hwndDlg, "SELECT_PKCS11_MODULE", systemDir, securityTokenLibraryPath, TRUE, FALSE, browseFilter))
SetDlgItemText (hwndDlg, IDC_PKCS11_MODULE, securityTokenLibraryPath);
return 1;
}
}
return 0;
}
return 0;
}
void SecurityTokenPreferencesDialog (HWND hwndDlg)
{
DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_TOKEN_PREFERENCES), hwndDlg, (DLGPROC) SecurityTokenPreferencesDlgProc, 0);
}
diff --git a/src/Mount/Mount.h b/src/Mount/Mount.h
index 140b3e99..7509542c 100644
--- a/src/Mount/Mount.h
+++ b/src/Mount/Mount.h
@@ -77,39 +77,39 @@ void ExtractCommandLine ( HWND hwndDlg , char *lpszCommandLine );
static void WipeCache (HWND hwndDlg, BOOL silent);
void OpenVolumeExplorerWindow (int driveNo);
BOOL TaskBarIconAdd (HWND hwnd);
BOOL TaskBarIconRemove (HWND hwnd);
BOOL TaskBarIconChange (HWND hwnd, int iconId);
void DismountIdleVolumes ();
static void SaveDefaultKeyFilesParam (void);
static BOOL Dismount (HWND hwndDlg, int nDosDriveNo);
static BOOL DismountAll (HWND hwndDlg, BOOL forceUnmount, BOOL interact, int dismountMaxRetries, int dismountAutoRetryDelay);
static void KeyfileDefaultsDlg (HWND hwndDlg);
static void HandleHotKey (HWND hwndDlg, WPARAM wParam);
static BOOL CheckMountList ();
int GetCipherBlockSizeByDriveNo (int nDosDriveNo);
int GetModeOfOperationByDriveNo (int nDosDriveNo);
void ChangeMainWindowVisibility ();
void LaunchVolCreationWizard (HWND hwndDlg);
BOOL WholeSysDriveEncryption (BOOL bSilent);
BOOL CheckSysEncMountWithoutPBA (const char *devicePath, BOOL quiet);
BOOL TCBootLoaderOnInactiveSysEncDrive (void);
void CreateRescueDisk (void);
-int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, char *lpszVolume);
-int RestoreVolumeHeader (HWND hwndDlg, char *lpszVolume);
+int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, const char *lpszVolume);
+int RestoreVolumeHeader (HWND hwndDlg, const char *lpszVolume);
void SecurityTokenPreferencesDialog (HWND hwndDlg);
static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
void MountSelectedVolume (HWND hwndDlg, BOOL mountWithOptions);
uint32 ReadDriverConfigurationFlags ();
void AnalyzeKernelMiniDump (HWND hwndDlg);
void HookMouseWheel (HWND hwndDlg, UINT ctrlId);
static BOOL HandleDriveListMouseWheelEvent (UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL bListMustBePointed);
#ifdef __cplusplus
}
void SetDriverConfigurationFlag (uint32 flag, BOOL state);
BOOL MountFavoriteVolumes (BOOL systemFavorites = FALSE, BOOL logOnMount = FALSE, BOOL hotKeyMount = FALSE, const VeraCrypt::FavoriteVolume &favoriteVolumeToMount = VeraCrypt::FavoriteVolume());
BOOL GetExecutableImageInformation (const string &path, string &version, string &description, string &companyName, string &productName);
#endif