/*
Legal Notice: Some portions of the source code contained in this file were
derived from the source code of TrueCrypt 7.1a, which is
Copyright (c) 2003-2012 TrueCrypt Developers Association and which is
governed by the TrueCrypt License 3.0, also from the source code of
Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux
and which is governed by the 'License Agreement for Encryption for the Masses'
Modifications and additions to the original source code (contained in this file)
and all other portions of this file are Copyright (c) 2013-2017 IDRIX
and are governed by the Apache License 2.0 the full text of which is
contained in the file License.txt included in VeraCrypt binary and source
code distribution packages. */
#include "Tcdefs.h"
#include <windowsx.h>
#include <dbghelp.h>
#include <dbt.h>
#include <Setupapi.h>
#include <aclapi.h>
#include <Netlistmgr.h>
#include <fcntl.h>
#include <io.h>
#include <math.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <time.h>
#include <tchar.h>
#include <Richedit.h>
#if defined (TCMOUNT) || defined (VOLFORMAT)
#include <process.h>
#include <Tlhelp32.h>
#endif
#if _WIN32_WINNT >= 0x0602
#include "processthreadsapi.h"
#endif
#include "Resource.h"
#include "Platform/Finally.h"
#include "Platform/ForEach.h"
#include "Apidrvr.h"
#include "BootEncryption.h"
#include "Combo.h"
#include "Crc.h"
#include "Crypto.h"
#include "Dictionary.h"
#include "Dlgcode.h"
#include "EncryptionThreadPool.h"
#include "Endian.h"
#include "Format/Inplace.h"
#include "Language.h"
#include "Keyfiles.h"
#include "Pkcs5.h"
#include "Random.h"
#include "Registry.h"
#include "SecurityToken.h"
#include "Tests.h"
#include "Volumes.h"
#include "Wipe.h"
#include "Xml.h"
#include "Xts.h"
#include "Boot/Windows/BootCommon.h"
#include "Progress.h"
#include "zip.h"
#include "rdrand.h"
#include "jitterentropy.h"
#ifdef TCMOUNT
#include "Mount/Mount.h"
#include "Mount/resource.h"
#endif
#ifdef VOLFORMAT
#include "Format/Tcformat.h"
#endif
#ifdef SETUP
#include "Setup/Setup.h"
#endif
#include <Setupapi.h>
#include <Softpub.h>
#include <WinTrust.h>
#include <strsafe.h>
#define _WIN32_DCOM
#include <comdef.h>
#include <Wbemidl.h>
#pragma comment(lib, "wbemuuid.lib")
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "setupapi.lib" )
#pragma comment(lib, "Wintrust.lib" )
#pragma comment(lib, "Comctl32.lib" )
#ifndef TTI_INFO_LARGE
#define TTI_INFO_LARGE 4
#endif
#ifndef TTI_WARNING_LARGE
#define TTI_WARNING_LARGE 5
#endif
#ifndef TTI_ERROR_LARGE
#define TTI_ERROR_LARGE 6
#endif
/* GPT Partition Type GUIDs */
#define LOCAL_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) const GUID name = {l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8}
LOCAL_DEFINE_GUID(PARTITION_ENTRY_UNUSED_GUID, 0x00000000L, 0x0000, 0x0000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); // Entry unused
LOCAL_DEFINE_GUID(PARTITION_SYSTEM_GUID, 0xC12A7328L, 0xF81F, 0x11D2, 0xBA, 0x4B, 0x00, 0xA0, 0xC9, 0x3E, 0xC9, 0x3B); // EFI system partition
LOCAL_DEFINE_GUID(PARTITION_MSFT_RESERVED_GUID, 0xE3C9E316L, 0x0B5C, 0x4DB8, 0x81, 0x7D, 0xF9, 0x2D, 0xF0, 0x02, 0x15, 0xAE); // Microsoft reserved space
LOCAL_DEFINE_GUID(PARTITION_BASIC_DATA_GUID, 0xEBD0A0A2L, 0xB9E5, 0x4433, 0x87, 0xC0, 0x68, 0xB6, 0xB7, 0x26, 0x99, 0xC7); // Basic data partition
LOCAL_DEFINE_GUID(PARTITION_LDM_METADATA_GUID, 0x5808C8AAL, 0x7E8F, 0x42E0, 0x85, 0xD2, 0xE1, 0xE9, 0x04, 0x34, 0xCF, 0xB3); // Logical Disk Manager metadata partition
LOCAL_DEFINE_GUID(PARTITION_LDM_DATA_GUID, 0xAF9B60A0L, 0x1431, 0x4F62, 0xBC, 0x68, 0x33, 0x11, 0x71, 0x4A, 0x69, 0xAD); // Logical Disk Manager data partition
LOCAL_DEFINE_GUID(PARTITION_MSFT_RECOVERY_GUID, 0xDE94BBA4L, 0x06D1, 0x4D40, 0xA1, 0x6A, 0xBF, 0xD5, 0x01, 0x79, 0xD6, 0xAC); // Microsoft recovery partition
LOCAL_DEFINE_GUID(PARTITION_CLUSTER_GUID, 0xdb97dba9L, 0x0840, 0x4bae, 0x97, 0xf0, 0xff, 0xb9, 0xa3, 0x27, 0xc7, 0xe1); // Cluster metadata partition
#ifndef PROCESSOR_ARCHITECTURE_ARM64
#define PROCESSOR_ARCHITECTURE_ARM64 12
#endif
#ifndef IMAGE_FILE_MACHINE_ARM64
#define IMAGE_FILE_MACHINE_ARM64 0xAA64
#endif
using namespace VeraCrypt;
LONG DriverVersion;
char *LastDialogId;
wchar_t szHelpFile[TC_MAX_PATH];
wchar_t szHelpFile2[TC_MAX_PATH];
wchar_t SecurityTokenLibraryPath[TC_MAX_PATH];
char CmdTokenPin [TC_MAX_PATH] = {0};
HFONT hFixedDigitFont = NULL;
HFONT hBoldFont = NULL;
HFONT hTitleFont = NULL;
HFONT hFixedFont = NULL;
HFONT hUserFont = NULL;
HFONT hUserUnderlineFont = NULL;
HFONT hUserBoldFont = NULL;
HFONT hUserUnderlineBoldFont = NULL;
HFONT WindowTitleBarFont;
WCHAR EditPasswordChar = 0;
int ScreenDPI = USER_DEFAULT_SCREEN_DPI;
double DPIScaleFactorX = 1;
double DPIScaleFactorY = 1;
double DlgAspectRatio = 1;
HWND MainDlg = NULL;
wchar_t *lpszTitle = NULL;
BOOL Silent = FALSE;
BOOL bPreserveTimestamp = TRUE;
BOOL bShowDisconnectedNetworkDrives = FALSE;
BOOL bHideWaitingDialog = FALSE;
BOOL bCmdHideWaitingDialog = FALSE;
BOOL bCmdHideWaitingDialogValid = FALSE;
BOOL bUseSecureDesktop = FALSE;
BOOL bUseLegacyMaxPasswordLength = FALSE;
BOOL bCmdUseSecureDesktop = FALSE;
BOOL bCmdUseSecureDesktopValid = FALSE;
BOOL bStartOnLogon = FALSE;
BOOL bMountDevicesOnLogon = FALSE;
BOOL bMountFavoritesOnLogon = FALSE;
BOOL bHistory = FALSE;
#ifndef SETUP
BOOL bLanguageSetInSetup = FALSE;
#else
extern BOOL bMakePackage;
#endif
#ifdef TCMOUNT
extern BOOL ServiceMode;
#endif
// Status of detection of hidden sectors (whole-system-drive encryption).
// 0 - Unknown/undetermined/completed, 1: Detection is or was in progress (but did not complete e.g. due to system crash).
int HiddenSectorDetectionStatus = 0;
OSVersionEnum nCurrentOS = WIN_UNKNOWN;
int CurrentOSMajor = 0;
int CurrentOSMinor = 0;
int CurrentOSServicePack = 0;
int CurrentOSBuildNumber = 0;
BOOL RemoteSession = FALSE;
BOOL UacElevated = FALSE;
BOOL bPortableModeConfirmed = FALSE; // TRUE if it is certain that the instance is running in portable mode
BOOL bInPlaceEncNonSysPending = FALSE; // TRUE if the non-system in-place encryption config file indicates that one or more partitions are scheduled to be encrypted. This flag is set only when config files are loaded during app startup.
/* Globals used by Mount and Format (separately per instance) */
BOOL PimEnable = FALSE;
BOOL KeyFilesEnable = FALSE;
KeyFile *FirstKeyFile = NULL;
KeyFilesDlgParam defaultKeyFilesParam = {0};
BOOL IgnoreWmDeviceChange = FALSE;
BOOL DeviceChangeBroadcastDisabled = FALSE;
BOOL LastMountedVolumeDirty;
BOOL MountVolumesAsSystemFavorite = FALSE;
BOOL FavoriteMountOnArrivalInProgress = FALSE;
BOOL MultipleMountOperationInProgress = FALSE;
BOOL EMVSupportEnabled = FALSE;
volatile BOOL NeedPeriodicDeviceListUpdate = FALSE;
BOOL DisablePeriodicDeviceListUpdate = FALSE;
BOOL EnableMemoryProtection = FALSE;
BOOL MemoryProtectionActivated = FALSE;
BOOL WaitDialogDisplaying = FALSE;
/* Handle to the device driver */
HANDLE hDriver = INVALID_HANDLE_VALUE;
/* This mutex is used to prevent multiple instances of the wizard or main app from dealing with system encryption */
volatile HANDLE hSysEncMutex = NULL;
/* This mutex is used for non-system in-place encryption but only for informative (non-blocking) purposes,
such as whether an app should prompt the user whether to resume scheduled process. */
volatile HANDLE hNonSysInplaceEncMutex = NULL;
/* This mutex is used to prevent multiple instances of the wizard or main app from trying to install or
register the driver or from trying to launch it in portable mode at the same time. */
volatile HANDLE hDriverSetupMutex = NULL;
/* This mutex is used to prevent users from running the main TrueCrypt app or the wizard while an instance
of the TrueCrypt installer is running (which is also useful for enforcing restart before the apps can be used). */
volatile HANDLE hAppSetupMutex = NULL;
/* Critical section used to protect access to global variables used in WNetGetConnection calls */
CRITICAL_SECTION csWNetCalls;
/* Critical section used to protect access to global list of physical drives */
CRITICAL_SECTION csMountableDevices;
CRITICAL_SECTION csVolumeIdCandidates;
static std::vector<HostDevice> mountableDevices;
static std::vector<HostDevice> rawHostDeviceList;
/* Critical section used to ensure that only one thread at a time can create a secure desktop */
CRITICAL_SECTION csSecureDesktop;
/* Boolean that indicates if our Secure Desktop is active and being used or not */
volatile BOOL bSecureDesktopOngoing = FALSE;
TCHAR SecureDesktopName[65];
HINSTANCE hInst = NULL;
HCURSOR hCursor = NULL;
ATOM hDlgClass, hSplashClass;
/* This value may changed only by calling ChangeSystemEncryptionStatus(). Only the wizard can change it
(others may still read it though). */
int SystemEncryptionStatus = SYSENC_STATUS_NONE;
/* Only the wizard can change this value (others may only read it). */
WipeAlgorithmId nWipeMode = TC_WIPE_NONE;
BOOL bSysPartitionSelected = FALSE; /* TRUE if the user selected the system partition via the Select Device dialog */
BOOL bSysDriveSelected = FALSE; /* TRUE if the user selected the system drive via the Select Device dialog */
/* To populate these arrays, call GetSysDevicePaths(). If they contain valid paths, bCachedSysDevicePathsValid is TRUE. */
wchar_t SysPartitionDevicePath [TC_MAX_PATH];
wchar_t SysDriveDevicePath [TC_MAX_PATH];
wstring ExtraBootPartitionDevicePath;
char bCachedSysDevicePathsValid = FALSE;
BOOL bHyperLinkBeingTracked = FALSE;
int WrongPwdRetryCounter = 0;
static FILE *ConfigFileHandle;
char *ConfigBuffer;
BOOL SystemFileSelectorCallPending = FALSE;
DWORD SystemFileSelectorCallerThreadId;
#define RANDPOOL_DISPLAY_REFRESH_INTERVAL 30
#define RANDPOOL_DISPLAY_ROWS 16
#define RANDPOOL_DISPLAY_COLUMNS 20
#ifndef LOAD_LIBRARY_SEARCH_SYSTEM32
#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#endif
typedef BOOL (WINAPI *SetDefaultDllDirectoriesPtr)(DWORD DirectoryFlags);
static unsigned char gpbSha512CodeSignCertFingerprint[64] = {
0x9C, 0xA0, 0x21, 0xD3, 0x7C, 0x90, 0x61, 0x88, 0xEF, 0x5F, 0x99, 0x3D,
0x54, 0x9F, 0xB8, 0xCE, 0x72, 0x32, 0x4F, 0x57, 0x4F, 0x19, 0xD2, 0xA4,
0xDC, 0x84, 0xFF, 0xE2, 0x84, 0x2B, 0xD4, 0x30, 0xAB, 0xA7, 0xE4, 0x63,
0x18, 0xD1, 0xD8, 0x32, 0x0E, 0xA4, 0x81, 0x3C, 0x19, 0xBF, 0x13, 0x11,
0xA4, 0x37, 0xD6, 0xDB, 0x26, 0xBA, 0xDC, 0x8F, 0x86, 0x96, 0x55, 0x96,
0xDB, 0x6F, 0xC0, 0x62
};
static unsigned char gpbSha512MSCodeSignCertFingerprint[64] = {
0xEB, 0x76, 0x2E, 0xD3, 0x5B, 0x4A, 0xB1, 0x0E, 0xF5, 0x3B, 0x99, 0x4E,
0xC1, 0xF7, 0x48, 0x88, 0xF6, 0xA0, 0xE9, 0xAC, 0x32, 0x69, 0xCF, 0x20,
0xE1, 0x60, 0xC4, 0x0C, 0xEF, 0x01, 0x1F, 0xCB, 0x41, 0x95, 0x72, 0xB9,
0xED, 0x63, 0x0C, 0x6B, 0xB9, 0xE9, 0xA2, 0x72, 0xA6, 0x78, 0x96, 0x4C,
0x69, 0x9F, 0x90, 0x3F, 0xB1, 0x3C, 0x64, 0xF2, 0xAB, 0xCF, 0x14, 0x1D,
0xEC, 0x7C, 0xB0, 0xC7
};
/* Windows dialog class */
#define WINDOWS_DIALOG_CLASS L"#32770"
/* Custom class names */
#define TC_DLG_CLASS L"VeraCryptCustomDlg"
#define TC_SPLASH_CLASS L"VeraCryptSplashDlg"
/* constant used by ChangeWindowMessageFilter calls */
#ifndef MSGFLT_ADD
#define MSGFLT_ADD 1
#endif
/* undocumented message sent during drag-n-drop */
#ifndef WM_COPYGLOBALDATA
#define WM_COPYGLOBALDATA 0x0049
#endif
/* Benchmarks */
#ifndef SETUP
#define BENCHMARK_MAX_ITEMS 100
#define BENCHMARK_DEFAULT_BUF_SIZE BYTES_PER_MB
#define HASH_FNC_BENCHMARKS FALSE // For development purposes only. Must be FALSE when building a public release.
#define PKCS5_BENCHMARKS FALSE // For development purposes only. Must be FALSE when building a public release.
#if PKCS5_BENCHMARKS && HASH_FNC_BENCHMARKS
#error PKCS5_BENCHMARKS and HASH_FNC_BENCHMARKS are both TRUE (at least one of them should be FALSE).
#endif
enum
{
BENCHMARK_TYPE_ENCRYPTION = 0,
BENCHMARK_TYPE_PRF,
BENCHMARK_TYPE_HASH
};
enum
{
BENCHMARK_SORT_BY_NAME = 0,
BENCHMARK_SORT_BY_SPEED
};
typedef struct
{
int id;
wchar_t name[100];
unsigned __int64 encSpeed;
unsigned __int64 decSpeed;
unsigned __int64 meanBytesPerSec;
} BENCHMARK_REC;
BENCHMARK_REC benchmarkTable [BENCHMARK_MAX_ITEMS];
int benchmarkTotalItems = 0;
int benchmarkBufferSize = BENCHMARK_DEFAULT_BUF_SIZE;
int benchmarkLastBufferSize = BENCHMARK_DEFAULT_BUF_SIZE;
int benchmarkSortMethod = BENCHMARK_SORT_BY_SPEED;
LARGE_INTEGER benchmarkPerformanceFrequency;
int benchmarkType = BENCHMARK_TYPE_ENCRYPTION;
int benchmarkPim = -1;
BOOL benchmarkPreBoot = FALSE;
BOOL benchmarkGPT = FALSE;
#endif // #ifndef SETUP
typedef struct
{
void *strings;
BOOL bold;
} MULTI_CHOICE_DLGPROC_PARAMS;
// Loads a 32-bit integer from the file at the specified file offset. The saved value is assumed to have been
// processed by mputLong(). The result is stored in *result. Returns TRUE if successful (otherwise FALSE).
BOOL LoadInt32 (const wchar_t *filePath, unsigned __int32 *result, __int64 fileOffset)
{
DWORD bufSize = sizeof(__int32);
unsigned char *buffer = (unsigned char *) malloc (bufSize);
unsigned char *bufferPtr = buffer;
HANDLE src = NULL;
DWORD bytesRead;
LARGE_INTEGER seekOffset, seekOffsetNew;
BOOL retVal = FALSE;
if (buffer == NULL)
return -1;
src = CreateFile (filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (src == INVALID_HANDLE_VALUE)
{
free (buffer);
return FALSE;
}
seekOffset.QuadPart = fileOffset;
if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0)
goto fsif_end;
if (ReadFile (src, buffer, bufSize, &bytesRead, NULL) == 0
|| bytesRead != bufSize)
goto fsif_end;
retVal = TRUE;
*result = mgetLong(bufferPtr);
fsif_end:
CloseHandle (src);
free (buffer);
return retVal;
}
// Loads a 16-bit integer from the file at the specified file offset. The saved value is assumed to have been
// processed by mputWord(). The result is stored in *result. Returns TRUE if successful (otherwise FALSE).
BOOL LoadInt16 (const wchar_t *filePath, int *result, __int64 fileOffset)
{
DWORD bufSize = sizeof(__int16);
unsigned char *buffer = (unsigned char *) malloc (bufSize);
unsigned char *bufferPtr = buffer;
HANDLE src = NULL;
DWORD bytesRead;
LARGE_INTEGER seekOffset, seekOffsetNew;
BOOL retVal = FALSE;
if (buffer == NULL)
return -1;
src = CreateFile (filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (src == INVALID_HANDLE_VALUE)
{
free (buffer);
return FALSE;
}
seekOffset.QuadPart = fileOffset;
if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0)
goto fsif_end;
if (ReadFile (src, buffer, bufSize, &bytesRead, NULL) == 0
|| bytesRead != bufSize)
goto fsif_end;
retVal = TRUE;
*result = mgetWord(bufferPtr);
fsif_end:
CloseHandle (src);
free (buffer);
return retVal;
}
// Returns NULL if there's any error. Although the buffer can contain binary data, it is always null-terminated.
char *LoadFile (const wchar_t *fileName, DWORD *size)
{
char *buf;
DWORD fileSize = INVALID_FILE_SIZE;
HANDLE h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
*size = 0;
if (h == INVALID_HANDLE_VALUE)
return NULL;
if ((fileSize = GetFileSize (h, NULL)) == INVALID_FILE_SIZE)
{
CloseHandle (h);
return NULL;
}
buf = (char *) calloc (fileSize + 1, 1);
if (buf == NULL)
{
CloseHandle (h);
return NULL;
}
if (!ReadFile (h, buf, fileSize, size, NULL))
{
free (buf);
buf = NULL;
}
else
{
buf[*size] = 0; //make coverity happy eventhough buf is guaranteed to be null terminated because of fileSize+1 in calloc call
}
CloseHandle (h);
return buf;
}
// Returns NULL if there's any error.
char *LoadFileBlock (const wchar_t *fileName, __int64 fileOffset, DWORD count)
{
char *buf;
DWORD bytesRead = 0;
LARGE_INTEGER seekOffset, seekOffsetNew;
BOOL bStatus;
HANDLE h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (h == INVALID_HANDLE_VALUE)
return NULL;
seekOffset.QuadPart = fileOffset;
if (SetFilePointerEx (h, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0)
{
CloseHandle (h);
return NULL;
}
buf = (char *) calloc (count, 1);
if (buf == NULL)
{
CloseHandle (h);
return NULL;
}
bStatus = ReadFile (h, buf, count, &bytesRead, NULL);
CloseHandle (h);
if (!bStatus || (bytesRead != count))
{
free (buf);
return NULL;
}
return buf;
}
// Returns -1 if there is an error, or the size of the file.
__int64 GetFileSize64 (const wchar_t *path)
{
HANDLE h = CreateFile (path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
LARGE_INTEGER size;
__int64 retSize = -1;
if (h)
{
if (GetFileSizeEx (h, &size))
{
retSize = size.QuadPart;
}
CloseHandle (h);
}
return retSize;
}
// If bAppend is TRUE, the buffer is appended to an existing file. If bAppend is FALSE, any existing file
// is replaced. If an error occurs, the incomplete file is deleted (provided that bAppend is FALSE).
BOOL SaveBufferToFile (const char *inputBuffer, const wchar_t *destinationFile, DWORD inputLength, BOOL bAppend, BOOL bRenameIfFailed)
{
HANDLE dst;
DWORD bytesWritten;
BOOL res = TRUE;
DWORD dwLastError = 0;
dst = CreateFile (destinationFile,
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, bAppend ? OPEN_EXISTING : CREATE_ALWAYS, 0, NULL);
dwLastError = GetLastError();
if (!bAppend && bRenameIfFailed && (dst == INVALID_HANDLE_VALUE) && (GetLastError () == ERROR_SHARING_VIOLATION))
{
wchar_t renamedPath[TC_MAX_PATH + 1];
StringCbCopyW (renamedPath, sizeof(renamedPath), destinationFile);
StringCbCatW (renamedPath, sizeof(renamedPath), VC_FILENAME_RENAMED_SUFFIX);
/* rename the locked file in order to be able to create a new one */
if (MoveFileEx (destinationFile, renamedPath, MOVEFILE_REPLACE_EXISTING))
{
dst = CreateFile (destinationFile,
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL);
dwLastError = GetLastError();
if (dst == INVALID_HANDLE_VALUE)
{
/* restore the original file name */
MoveFileEx (renamedPath, destinationFile, MOVEFILE_REPLACE_EXISTING);
}
else
{
/* delete the renamed file when the machine reboots */
MoveFileEx (renamedPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
}
}
}
if (dst == INVALID_HANDLE_VALUE)
{
SetLastError (dwLastError);
handleWin32Error (MainDlg, SRC_POS);
return FALSE;
}
if (bAppend)
SetFilePointer (dst, 0, NULL, FILE_END);
if (!WriteFile (dst, inputBuffer, inputLength, &bytesWritten, NULL)
|| inputLength != bytesWritten)
{
res = FALSE;
}
if (!res)
{
// If CREATE_ALWAYS is used, ERROR_ALREADY_EXISTS is returned after successful overwrite
// of an existing file (it's not an error)
if (! (GetLastError() == ERROR_ALREADY_EXISTS && !bAppend) )
handleWin32Error (MainDlg, SRC_POS);
}
CloseHandle (dst);
if (!res && !bAppend)
_wremove (destinationFile);
return res;
}
// Returns -1 if the specified string is not found in the buffer. Otherwise, returns the
// offset of the first occurrence of the string. The string and the buffer may contain zeroes,
// which do NOT terminate them.
int64 FindString (const char *buf, const char *str, int64 bufLen, int64 strLen, int64 startOffset)
{
if (buf == NULL
|| str == NULL
|| strLen > bufLen
|| bufLen < 1
|| strLen < 1
|| startOffset > bufLen - strLen)
{
return -1;
}
for (int64 i = startOffset; i <= bufLen - strLen; i++)
{
if (memcmp (buf + i, str, (size_t) strLen) == 0)
return i;
}
return -1;
}
// Returns TRUE if the file or directory exists (both may be enclosed in quotation marks).
BOOL FileExists (const wchar_t *filePathPtr)
{
wchar_t filePath [TC_MAX_PATH * 2 + 1];
// Strip quotation marks (if any)
if (filePathPtr [0] == L'"')
{
StringCbCopyW (filePath, sizeof(filePath), filePathPtr + 1);
}
else
{
StringCbCopyW (filePath, sizeof(filePath), filePathPtr);
}
// Strip quotation marks (if any)
if (filePath [wcslen (filePath) - 1] == L'"')
filePath [wcslen (filePath) - 1] = 0;
return (_waccess (filePath, 0) != -1);
}
// Searches the file from its end for the LAST occurrence of the string str.
// The string may contain zeroes, which do NOT terminate the string.
// If the string is found, its offset from the start of the file is returned.
// If the string isn't found or if any error occurs, -1 is returned.
__int64 FindStringInFile (const wchar_t *filePath, const char* str, int strLen)
{
int bufSize = 64 * BYTES_PER_KB;
char *buffer = (char *) err_malloc (bufSize);
HANDLE src = NULL;
DWORD bytesRead;
BOOL readRetVal;
__int64 filePos = GetFileSize64 (filePath);
int bufPos = 0;
LARGE_INTEGER seekOffset, seekOffsetNew;
BOOL bExit = FALSE;
int filePosStep;
__int64 retVal = -1;
if (filePos <= 0
|| buffer == NULL
|| strLen > bufSize
|| strLen < 1)
{
if (buffer)
free (buffer);
return -1;
}
src = CreateFile (filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (src == INVALID_HANDLE_VALUE)
{
free (buffer);
return -1;
}
filePosStep = bufSize - strLen + 1;
do
{
filePos -= filePosStep;
if (filePos < 0)
{
filePos = 0;
bExit = TRUE;
}
seekOffset.QuadPart = filePos;
if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0)
goto fsif_end;
if ((readRetVal = ReadFile (src, buffer, bufSize, &bytesRead, NULL)) == 0
|| bytesRead == 0)
goto fsif_end;
bufPos = bytesRead - strLen;
while (bufPos > 0)
{
if (memcmp (buffer + bufPos, str, strLen) == 0)
{
// String found
retVal = filePos + bufPos;
goto fsif_end;
}
bufPos--;
}
} while (!bExit);
fsif_end:
CloseHandle (src);
free (buffer);
return retVal;
}
// System CopyFile() copies source file attributes (like FILE_ATTRIBUTE_ENCRYPTED)
// so we need to use our own copy function
BOOL TCCopyFileBase (HANDLE src, HANDLE dst)
{
__int8 *buffer;
FILETIME fileTime;
DWORD bytesRead, bytesWritten;
BOOL res;
buffer = (char *) malloc (64 * 1024);
if (!buffer)
{
CloseHandle (src);
CloseHandle (dst);
return FALSE;
}
while (res = ReadFile (src, buffer, 64 * 1024, &bytesRead, NULL))
{
if (bytesRead == 0)
{
res = 1;
break;
}
if (!WriteFile (dst, buffer, bytesRead, &bytesWritten, NULL)
|| bytesRead != bytesWritten)
{
res = 0;
break;
}
}
if (GetFileTime (src, NULL, NULL, &fileTime))
SetFileTime (dst, NULL, NULL, &fileTime);
CloseHandle (src);
CloseHandle (dst);
free (buffer);
return res != 0;
}
BOOL TCCopyFile (wchar_t *sourceFileName, wchar_t *destinationFile)
{
HANDLE src, dst;
src = CreateFileW (sourceFileName,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (src == INVALID_HANDLE_VALUE)
return FALSE;
dst = CreateFileW (destinationFile,
GENERIC_WRITE,
0, NULL, CREATE_ALWAYS, 0, NULL);
if (dst == INVALID_HANDLE_VALUE)
{
CloseHandle (src);
return FALSE;
}
return TCCopyFileBase (src, dst);
}
BOOL VerifyModuleSignature (const wchar_t* path)
{
#if defined(NDEBUG) && !defined (VC_SKIP_OS_DRIVER_REQ_CHECK)
BOOL bResult = FALSE;
HRESULT hResult;
GUID gActionID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
WINTRUST_FILE_INFO fileInfo = {0};
WINTRUST_DATA WVTData = {0};
wchar_t filePath [TC_MAX_PATH + 1024];
// we check our own authenticode signature only starting from Windows 10 since this is
// the minimal supported OS apart from XP where we can't verify SHA256 signatures
if (!IsOSAtLeast (WIN_10))
return TRUE;
// Strip quotation marks (if any)
if (path [0] == L'"')
{
StringCbCopyW (filePath, sizeof(filePath), path + 1);
}
else
{
StringCbCopyW (filePath, sizeof(filePath), path);
}
// Strip quotation marks (if any)
if (filePath [wcslen (filePath) - 1] == L'"')
filePath [wcslen (filePath) - 1] = 0;
fileInfo.cbStruct = sizeof(WINTRUST_FILE_INFO);
fileInfo.pcwszFilePath = filePath;
fileInfo.hFile = NULL;
WVTData.cbStruct = sizeof(WINTRUST_DATA);
WVTData.dwUIChoice = WTD_UI_NONE;
WVTData.fdwRevocationChecks = WTD_REVOKE_NONE;
WVTData.dwUnionChoice = WTD_CHOICE_FILE;
WVTData.pFile = &fileInfo;
WVTData.dwStateAction = WTD_STATEACTION_VERIFY;
WVTData.dwProvFlags = WTD_REVOCATION_CHECK_NONE | WTD_CACHE_ONLY_URL_RETRIEVAL;
hResult = WinVerifyTrust(0, &gActionID, &WVTData);
if (0 == hResult)
{
PCRYPT_PROVIDER_DATA pProviderData = WTHelperProvDataFromStateData (WVTData.hWVTStateData);
if (pProviderData)
{
PCRYPT_PROVIDER_SGNR pProviderSigner = WTHelperGetProvSignerFromChain (pProviderData, 0, FALSE, 0);
if (pProviderSigner)
{
PCRYPT_PROVIDER_CERT pProviderCert = WTHelperGetProvCertFromChain (pProviderSigner, 0);
if (pProviderCert && (pProviderCert->pCert))
{
BYTE hashVal[64];
sha512 (hashVal, pProviderCert->pCert->pbCertEncoded, pProviderCert->pCert->cbCertEncoded);
if ( (0 == memcmp (hashVal, gpbSha512CodeSignCertFingerprint, 64))
|| (0 == memcmp (hashVal, gpbSha512MSCodeSignCertFingerprint, 64))
)
{
bResult = TRUE;
}
}
}
}
}
WVTData.dwUIChoice = WTD_UI_NONE;
WVTData.dwStateAction = WTD_STATEACTION_CLOSE;
WinVerifyTrust(0, &gActionID, &WVTData);
return bResult;
#else
return TRUE;
#endif
}
DWORD handleWin32Error (HWND hwndDlg, const char* srcPos)
{
#ifndef VC_COMREG
PWSTR lpMsgBuf;
DWORD dwError = GetLastError ();
wchar_t szErrorValue[32];
wchar_t* pszDesc;
if (Silent || dwError == 0 || dwError == ERROR_INVALID_WINDOW_HANDLE)
return dwError;
// Access denied
if (dwError == ERROR_ACCESS_DENIED && !IsAdmin ())
{
ErrorDirect ( AppendSrcPos (GetString ("ERR_ACCESS_DENIED"), srcPos).c_str (), hwndDlg);
SetLastError (dwError); // Preserve the original error code
return dwError;
}
FormatMessageW (
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwError,
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
(PWSTR) &lpMsgBuf,
0,
NULL
);
if (lpMsgBuf)
pszDesc = (wchar_t*) lpMsgBuf;
else
{
StringCchPrintfW (szErrorValue, ARRAYSIZE (szErrorValue), L"Error 0x%.8X", dwError);
pszDesc = szErrorValue;
}
MessageBoxW (hwndDlg, AppendSrcPos (pszDesc, srcPos).c_str (), lpszTitle, ICON_HAND);
if (lpMsgBuf) LocalFree (lpMsgBuf);
// User-friendly hardware error explanation
if (IsDiskError (dwError))
Error ("ERR_HARDWARE_ERROR", hwndDlg);
// Device not ready
if (dwError == ERROR_NOT_READY)
HandleDriveNotReadyError(hwndDlg);
SetLastError (dwError); // Preserve the original error code
return dwError;
#else
return GetLastError();
#endif
}
int Error (char *stringId, HWND hwnd)
{
#ifndef VC_COMREG
if (Silent) return 0;
return MessageBoxW (hwnd, GetString (stringId), lpszTitle, MB_ICONERROR);
#else
return 0;
#endif
}
BOOL IsOSAtLeast (OSVersionEnum reqMinOS)
{
return IsOSVersionAtLeast (reqMinOS, 0);
}
// Returns TRUE if the operating system is at least reqMinOS and service pack at least reqMinServicePack.
// Example 1: IsOSVersionAtLeast (WIN_VISTA, 1) called under Windows 2008, returns TRUE.
// Example 2: IsOSVersionAtLeast (WIN_XP, 3) called under Windows XP SP1, returns FALSE.
// Example 3: IsOSVersionAtLeast (WIN_XP, 3) called under Windows Vista SP1, returns TRUE.
BOOL IsOSVersionAtLeast (OSVersionEnum reqMinOS, int reqMinServicePack)
{
/* When updating this function, update IsOSAtLeast() in Ntdriver.c too. */
if (CurrentOSMajor <= 0)
TC_THROW_FATAL_EXCEPTION;
int major = 0, minor = 0;
switch (reqMinOS)
{
case WIN_2000: major = 5; minor = 0; break;
case WIN_XP: major = 5; minor = 1; break;
case WIN_SERVER_2003: major = 5; minor = 2; break;
case WIN_VISTA: major = 6; minor = 0; break;
case WIN_7: major = 6; minor = 1; break;
case WIN_8: major = 6; minor = 2; break;
case WIN_8_1: major = 6; minor = 3; break;
case WIN_10: major = 10; minor = 0; break;
default:
TC_THROW_FATAL_EXCEPTION;
break;
}
return ((CurrentOSMajor << 16 | CurrentOSMinor << 8 | CurrentOSServicePack)
>= (major << 16 | minor << 8 | reqMinServicePack));
}
#ifdef SETUP_DLL
static BOOL GetWindowVersionFromFile(DWORD* pdwMajor, DWORD* pdwMinor, DWORD* pdwBuildNumber)
{
wchar_t dllPath[MAX_PATH];
BOOL bRet = FALSE;
LPBYTE versionInfo = NULL;
UINT size;
VS_FIXEDFILEINFO *vinfo;
/* Load dll explictely from System32 to avoid Dll hijacking attacks*/
if (!GetSystemDirectory(dllPath, MAX_PATH))
StringCbCopyW(dllPath, sizeof(dllPath), L"C:\\Windows\\System32");
StringCbCatW(dllPath, sizeof(dllPath), L"\\");
StringCbCatW(dllPath, sizeof(dllPath), L"Kernel32.dll");
size = GetFileVersionInfoSizeW(dllPath, NULL);
if (size)
{
versionInfo = (LPBYTE) TCalloc(size);
if (GetFileVersionInfo(dllPath, 0, size, versionInfo))
{
if (VerQueryValueW(versionInfo, L"\\", (LPVOID *)&vinfo, &size) && (size >=sizeof(VS_FIXEDFILEINFO)))
{
*pdwMajor = HIWORD(vinfo->dwProductVersionMS);
*pdwMinor = LOWORD(vinfo->dwProductVersionMS);
*pdwBuildNumber = HIWORD(vinfo->dwProductVersionLS);
bRet = TRUE;
}
}
}
if (versionInfo)
TCfree(versionInfo);
return bRet;
}
#endif
/*
* Use RtlGetVersion to get Windows version because GetVersionEx is affected by application manifestation.
*/
typedef NTSTATUS (WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
static BOOL GetWindowsVersion(LPOSVERSIONINFOW lpVersionInformation)
{
BOOL bRet = FALSE;
#ifdef SETUP_DLL
DWORD dwMajor, dwMinor, dwBuildNumber;
#endif
RtlGetVersionPtr RtlGetVersionFn = (RtlGetVersionPtr) GetProcAddress(GetModuleHandle (L"ntdll.dll"), "RtlGetVersion");
if (RtlGetVersionFn != NULL)
{
if (ERROR_SUCCESS == RtlGetVersionFn (lpVersionInformation))
bRet = TRUE;
}
if (!bRet)
bRet = GetVersionExW (lpVersionInformation);
#ifdef SETUP_DLL
// we get real version from Kernel32.dll version since MSI always sets current version to 6.0
// https://stackoverflow.com/questions/49335885/windows-10-not-detecting-on-installshield/49343826#49343826
if (GetWindowVersionFromFile(&dwMajor, &dwMinor, &dwBuildNumber))
{
lpVersionInformation->dwMajorVersion = dwMajor;
lpVersionInformation->dwMinorVersion = dwMinor;
lpVersionInformation->dwBuildNumber = dwBuildNumber;
}
#endif
return bRet;
}
void InitOSVersionInfo ()
{
OSVERSIONINFOEXW os;
os.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW);
if (GetWindowsVersion ((LPOSVERSIONINFOW) &os) == FALSE)
AbortProcess ("NO_OS_VER");
CurrentOSMajor = os.dwMajorVersion;
CurrentOSMinor = os.dwMinorVersion;
CurrentOSServicePack = os.wServicePackMajor;
CurrentOSBuildNumber = os.dwBuildNumber;
if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 5 && CurrentOSMinor == 0)
nCurrentOS = WIN_2000;
else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 5 && CurrentOSMinor == 1)
nCurrentOS = WIN_XP;
else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 5 && CurrentOSMinor == 2)
{
if (os.wProductType == VER_NT_SERVER || os.wProductType == VER_NT_DOMAIN_CONTROLLER)
nCurrentOS = WIN_SERVER_2003;
else
nCurrentOS = WIN_XP64;
}
else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 6 && CurrentOSMinor == 0)
{
if (os.wProductType != VER_NT_WORKSTATION)
nCurrentOS = WIN_SERVER_2008;
else
nCurrentOS = WIN_VISTA;
}
else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 6 && CurrentOSMinor == 1)
nCurrentOS = ((os.wProductType != VER_NT_WORKSTATION) ? WIN_SERVER_2008_R2 : WIN_7);
else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 6 && CurrentOSMinor == 2)
nCurrentOS = ((os.wProductType != VER_NT_WORKSTATION) ? WIN_SERVER_2012 : WIN_8);
else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 6 && CurrentOSMinor == 3)
nCurrentOS = ((os.wProductType != VER_NT_WORKSTATION) ? WIN_SERVER_2012_R2 : WIN_8_1);
else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 10 && CurrentOSMinor == 0)
nCurrentOS = ((os.wProductType != VER_NT_WORKSTATION) ? WIN_SERVER_2016 : WIN_10);
else if (os.dwPlatformId == VER_PLATFORM_WIN32_NT && CurrentOSMajor == 4)
nCurrentOS = WIN_NT4;
else if (os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && os.dwMajorVersion == 4 && os.dwMinorVersion == 0)
nCurrentOS = WIN_95;
else if (os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && os.dwMajorVersion == 4 && os.dwMinorVersion == 10)
nCurrentOS = WIN_98;
else if (os.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && os.dwMajorVersion == 4 && os.dwMinorVersion == 90)
nCurrentOS = WIN_ME;
else if (os.dwPlatformId == VER_PLATFORM_WIN32s)
nCurrentOS = WIN_31;
else
nCurrentOS = WIN_UNKNOWN;
}
#pragma warning(push)
#pragma warning(disable:4702)
void *err_malloc (size_t size)
{
void *z = (void *) TCalloc (size);
if (z)
return z;
AbortProcess ("OUTOFMEMORY");
return 0;
}
#pragma warning(pop)
char *err_strdup (char *lpszText)
{
size_t j = (strlen (lpszText) + 1) * sizeof (char);
char *z = (char *) err_malloc (j);
memmove (z, lpszText, j);
return z;
}
void AbortProcessDirect (wchar_t *abortMsg)
{
// Note that this function also causes localcleanup() to be called (see atexit())
MessageBeep (MB_ICONEXCLAMATION);
MessageBoxW (NULL, abortMsg, lpszTitle, ICON_HAND);
exit (1);
}
void AbortProcess (char *stringId)
{
// Note that this function also causes localcleanup() to be called (see atexit())
#ifndef VC_COMREG
AbortProcessDirect (GetString (stringId));
#else
static wchar_t g_wszUnknown[1024];
StringCbPrintfW (g_wszUnknown, sizeof(g_wszUnknown), UNKNOWN_STRING_ID L"%hs" UNKNOWN_STRING_ID, stringId);
AbortProcessDirect (g_wszUnknown);
#endif
}
#ifndef VC_COMREG
void AbortProcessSilent (void)
{
// Note that this function also causes localcleanup() to be called (see atexit())
exit (1);
}
void InitGlobalLocks ()
{
InitializeCriticalSection (&csWNetCalls);
InitializeCriticalSection (&csMountableDevices);
InitializeCriticalSection (&csVolumeIdCandidates);
InitializeCriticalSection (&csSecureDesktop);
}
void FinalizeGlobalLocks ()
{
DeleteCriticalSection (&csWNetCalls);
DeleteCriticalSection (&csMountableDevices);
DeleteCriticalSection (&csVolumeIdCandidates);
DeleteCriticalSection (&csSecureDesktop);
}
void cleanup ()
{
burn (&CmdTokenPin, sizeof (CmdTokenPin));
#ifndef SETUP
KeyFileRemoveAll (&FirstKeyFile);
KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile);
#endif
/* Cleanup the GDI fonts */
if (hFixedFont != NULL)
DeleteObject (hFixedFont);
if (hFixedDigitFont != NULL)
DeleteObject (hFixedDigitFont);
if (hBoldFont != NULL)
DeleteObject (hBoldFont);
if (hTitleFont != NULL)
DeleteObject (hTitleFont);
if (hUserFont != NULL)
DeleteObject (hUserFont);
if (hUserUnderlineFont != NULL)
DeleteObject (hUserUnderlineFont);
if (hUserBoldFont != NULL)
DeleteObject (hUserBoldFont);
if (hUserUnderlineBoldFont != NULL)
DeleteObject (hUserUnderlineBoldFont);
/* Cleanup our dialog class */
if (hDlgClass)
UnregisterClassW (TC_DLG_CLASS, hInst);
if (hSplashClass)
UnregisterClassW (TC_SPLASH_CLASS, hInst);
/* Close the device driver handle */
if (hDriver != INVALID_HANDLE_VALUE)
{
// Unload driver mode if possible (non-install mode)
if (IsNonInstallMode ())
{
// If a dismount was forced in the lifetime of the driver, Windows may later prevent it to be loaded again from
// the same path. Therefore, the driver will not be unloaded even though it was loaded in non-install mode.
int driverUnloadDisabled;
DWORD dwResult;
if (!DeviceIoControl (hDriver, TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED, NULL, 0, &driverUnloadDisabled, sizeof (driverUnloadDisabled), &dwResult, NULL))
driverUnloadDisabled = 0;
if (!driverUnloadDisabled)
DriverUnload ();
else
{
CloseHandle (hDriver);
hDriver = INVALID_HANDLE_VALUE;
}
}
else
{
CloseHandle (hDriver);
hDriver = INVALID_HANDLE_VALUE;
}
}
if (ConfigBuffer != NULL)
{
free (ConfigBuffer);
ConfigBuffer = NULL;
}
CoUninitialize ();
CloseSysEncMutex ();
#ifndef SETUP
try
{
if (SecurityToken::IsInitialized())
SecurityToken::CloseLibrary();
}
catch (...) { }
EncryptionThreadPoolStop();
#endif
FinalizeGlobalLocks ();
}
void LowerCaseCopy (wchar_t *lpszDest, const wchar_t *lpszSource)
{
size_t i = wcslen (lpszSource) + 1;
lpszDest[i - 1] = 0;
while (--i > 0)
{
lpszDest[i - 1] = (wchar_t) towlower (lpszSource[i - 1]);
}
}
void UpperCaseCopy (wchar_t *lpszDest, size_t cbDest, const wchar_t *lpszSource)
{
if (lpszDest && (cbDest >= 2))
{
size_t i = wcslen (lpszSource);
if (i >= (cbDest/2))
i = (cbDest/2) - 1;
lpszDest[i] = 0;
i++;
while (--i > 0)
{
lpszDest[i - 1] = (wchar_t) towupper (lpszSource[i - 1]);
}
}
}
std::wstring ToUpperCase (const std::wstring &str)
{
wstring u;
foreach (wchar_t c, str)
{
u += (wchar_t) towupper (c);
}
return u;
}
size_t TrimWhiteSpace(wchar_t *str)
{
wchar_t *end, *ptr = str;
size_t out_size;
if(!str || *str == 0)
return 0;
// Trim leading space
while(iswspace(*ptr)) ptr++;
if(*ptr == 0) // All spaces?
{
*str = 0;
return 0;
}
// Trim trailing space
end = str + wcslen(str) - 1;
while(end > ptr && iswspace(*end)) end--;
end++;
// Set output size to trimmed string length
out_size = (end - ptr);
// Copy trimmed string and add null terminator
wmemmove(str, ptr, out_size);
str[out_size] = 0;
return out_size;
}
BOOL IsNullTerminateString (const wchar_t* str, size_t cbSize)
{
if (str && cbSize)
{
for (size_t i = 0; i < cbSize; i++)
{
if (str[i] == 0)
return TRUE;
}
}
return FALSE;
}
// check the validity of a file name
BOOL IsValidFileName(const wchar_t* str)
{
static wchar_t invalidChars[9] = {L'<', L'>', L':', L'"', L'/', L'\\', L'|', L'?', L'*'};
wchar_t c;
int i;
BOOL bNotDotOnly = FALSE;
while ((c = *str))
{
if (c != L'.')
bNotDotOnly = TRUE;
for (i= 0; i < ARRAYSIZE(invalidChars); i++)
if (c == invalidChars[i])
return FALSE;
str++;
}
return bNotDotOnly;
}
BOOL IsVolumeDeviceHosted (const wchar_t *lpszDiskFile)
{
return wcsstr (lpszDiskFile, L"\\Device\\") == lpszDiskFile
|| wcsstr (lpszDiskFile, L"\\DEVICE\\") == lpszDiskFile;
}
void CreateFullVolumePath (wchar_t *lpszDiskFile, size_t cbDiskFile, const wchar_t *lpszFileName, BOOL * bDevice)
{
UpperCaseCopy (lpszDiskFile, cbDiskFile, lpszFileName);
*bDevice = FALSE;
if (wmemcmp (lpszDiskFile, L"\\DEVICE", 7) == 0)
{
*bDevice = TRUE;
}
StringCbCopyW (lpszDiskFile, cbDiskFile, lpszFileName);
#if _DEBUG
OutputDebugString (L"CreateFullVolumePath: ");
OutputDebugString (lpszDiskFile);
OutputDebugString (L"\n");
#endif
}
int FakeDosNameForDevice (const wchar_t *lpszDiskFile , wchar_t *lpszDosDevice , size_t cbDosDevice, wchar_t *lpszCFDevice , size_t cbCFDevice, BOOL bNameOnly)
{
BOOL bDosLinkCreated = TRUE;
StringCbPrintfW (lpszDosDevice, cbDosDevice,L"veracrypt%lu", GetCurrentProcessId ());
if (bNameOnly == FALSE)
bDosLinkCreated = DefineDosDevice (DDD_RAW_TARGET_PATH, lpszDosDevice, lpszDiskFile);
if (bDosLinkCreated == FALSE)
return ERR_OS_ERROR;
else
StringCbPrintfW (lpszCFDevice, cbCFDevice,L"\\\\.\\%s", lpszDosDevice);
return 0;
}
int RemoveFakeDosName (wchar_t *lpszDiskFile, wchar_t *lpszDosDevice)
{
BOOL bDosLinkRemoved = DefineDosDevice (DDD_RAW_TARGET_PATH | DDD_EXACT_MATCH_ON_REMOVE |
DDD_REMOVE_DEFINITION, lpszDosDevice, lpszDiskFile);
if (bDosLinkRemoved == FALSE)
{
return ERR_OS_ERROR;
}
return 0;
}
BOOL IsDiskReadError (DWORD error)
{
return (error == ERROR_CRC
|| error == ERROR_IO_DEVICE
|| error == ERROR_BAD_CLUSTERS
|| error == ERROR_SECTOR_NOT_FOUND
|| error == ERROR_READ_FAULT
|| error == ERROR_INVALID_FUNCTION // I/O error may be reported as ERROR_INVALID_FUNCTION by buggy chipset drivers
|| error == ERROR_SEM_TIMEOUT); // I/O operation timeout may be reported as ERROR_SEM_TIMEOUT
}
BOOL IsDiskWriteError (DWORD error)
{
return (error == ERROR_IO_DEVICE
|| error == ERROR_BAD_CLUSTERS
|| error == ERROR_SECTOR_NOT_FOUND
|| error == ERROR_WRITE_FAULT
|| error == ERROR_INVALID_FUNCTION // I/O error may be reported as ERROR_INVALID_FUNCTION by buggy chipset drivers
|| error == ERROR_SEM_TIMEOUT); // I/O operation timeout may be reported as ERROR_SEM_TIMEOUT
}
BOOL IsDiskError (DWORD error)
{
return IsDiskReadError (error) || IsDiskWriteError (error);
}
BOOL translateWin32Error (wchar_t *lpszMsgBuf, int nWSizeOfBuf)
{
DWORD dwError = GetLastError ();
if (FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError,
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
lpszMsgBuf, nWSizeOfBuf, NULL))
{
SetLastError (dwError); // Preserve the original error code
return TRUE;
}
SetLastError (dwError); // Preserve the original error code
return FALSE;
}
// If the user has a non-default screen DPI, all absolute font sizes must be
// converted using this function.
int CompensateDPIFont (int val)
{
if (ScreenDPI == USER_DEFAULT_SCREEN_DPI)
return val;
else
{
double tmpVal = (double) val * DPIScaleFactorY * DlgAspectRatio * 0.999;
if (tmpVal > 0)
return (int) floor(tmpVal);
else
return (int) ceil(tmpVal);
}
}
// If the user has a non-default screen DPI, some screen coordinates and sizes must
// be converted using this function
int CompensateXDPI (int val)
{
if (ScreenDPI == USER_DEFAULT_SCREEN_DPI)
return val;
else
{
double tmpVal = (double) val * DPIScaleFactorX;
if (tmpVal > 0)
return (int) floor(tmpVal);
else
return (int) ceil(tmpVal);
}
}
// If the user has a non-default screen DPI, some screen coordinates and sizes must
// be converted using this function
int CompensateYDPI (int val)
{
if (ScreenDPI == USER_DEFAULT_SCREEN_DPI)
return val;
else
{
double tmpVal = (double) val * DPIScaleFactorY;
if (tmpVal > 0)
return (int) floor(tmpVal);
else
return (int) ceil(tmpVal);
}
}
int GetTextGfxWidth (HWND hwndDlgItem, const wchar_t *text, HFONT hFont)
{
SIZE sizes;
TEXTMETRIC textMetrics;
HDC hdc = GetDC (hwndDlgItem);
SelectObject(hdc, (HGDIOBJ) hFont);
GetTextExtentPoint32W (hdc, text, (int) wcslen (text), &sizes);
GetTextMetrics(hdc, &textMetrics); // Necessary for non-TrueType raster fonts (tmOverhang)
ReleaseDC (hwndDlgItem, hdc);
return ((int) sizes.cx - (int) textMetrics.tmOverhang);
}
int GetTextGfxHeight (HWND hwndDlgItem, const wchar_t *text, HFONT hFont)
{
SIZE sizes;
HDC hdc = GetDC (hwndDlgItem);
SelectObject(hdc, (HGDIOBJ) hFont);
GetTextExtentPoint32W (hdc, text, (int) wcslen (text), &sizes);
ReleaseDC (hwndDlgItem, hdc);
return ((int) sizes.cy);
}
std::wstring FitPathInGfxWidth (HWND hwnd, HFONT hFont, LONG width, const std::wstring &path)
{
wstring newPath;
RECT rect;
rect.left = 0;
rect.top = 0;
rect.right = width;
rect.bottom = LONG_MAX;
HDC hdc = GetDC (hwnd);
SelectObject (hdc, (HGDIOBJ) hFont);
wchar_t pathBuf[TC_MAX_PATH];
StringCchCopyW (pathBuf, ARRAYSIZE (pathBuf), path.c_str());
if (DrawText (hdc, pathBuf, (int) path.size(), &rect, DT_CALCRECT | DT_MODIFYSTRING | DT_PATH_ELLIPSIS | DT_SINGLELINE) != 0)
newPath = pathBuf;
ReleaseDC (hwnd, hdc);
return newPath;
}
static LRESULT CALLBACK HyperlinkProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
WNDPROC wp = (WNDPROC) GetWindowLongPtrW (hwnd, GWLP_USERDATA);
switch (message)
{
case WM_SETCURSOR:
if (!bHyperLinkBeingTracked)
{
TRACKMOUSEEVENT trackMouseEvent;
trackMouseEvent.cbSize = sizeof(trackMouseEvent);
trackMouseEvent.dwFlags = TME_LEAVE;
trackMouseEvent.hwndTrack = hwnd;
bHyperLinkBeingTracked = TrackMouseEvent(&trackMouseEvent);
HandCursor();
}
return 0;
case WM_MOUSELEAVE:
bHyperLinkBeingTracked = FALSE;
NormalCursor();
return 0;
}
return CallWindowProcW (wp, hwnd, message, wParam, lParam);
}
BOOL ToHyperlink (HWND hwndDlg, UINT ctrlId)
{
return ToCustHyperlink (hwndDlg, ctrlId, hUserUnderlineFont);
}
BOOL ToCustHyperlink (HWND hwndDlg, UINT ctrlId, HFONT hFont)
{
HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId);
SendMessageW (hwndCtrl, WM_SETFONT, (WPARAM) hFont, 0);
SetWindowLongPtrW (hwndCtrl, GWLP_USERDATA, (LONG_PTR) GetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC));
SetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC, (LONG_PTR) HyperlinkProc);
// Resize the field according to its actual size in pixels and move it if centered or right-aligned.
// This should be done again if the link text changes.
AccommodateTextField (hwndDlg, ctrlId, TRUE, hFont);
return TRUE;
}
// Resizes a text field according to its actual width and height in pixels (font size is taken into account) and moves
// it accordingly if the field is centered or right-aligned. Should be used on all hyperlinks upon dialog init
// after localization (bFirstUpdate should be TRUE) and later whenever a hyperlink text changes (bFirstUpdate
// must be FALSE).
void AccommodateTextField (HWND hwndDlg, UINT ctrlId, BOOL bFirstUpdate, HFONT hFont)
{
RECT rec, wrec, trec;
HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId);
int width, origWidth, height, origHeight;
int horizSubOffset, vertSubOffset, vertOffset, alignPosDiff = 0;
wchar_t text [MAX_URL_LENGTH];
WINDOWINFO windowInfo;
BOOL bBorderlessWindow = !(GetWindowLongPtrW (hwndDlg, GWL_STYLE) & (WS_BORDER | WS_DLGFRAME));
// Resize the field according to its length and font size and move if centered or right-aligned
GetWindowTextW (hwndCtrl, text, sizeof (text) / sizeof (wchar_t));
width = GetTextGfxWidth (hwndCtrl, text, hFont);
height = GetTextGfxHeight (hwndCtrl, text, hFont);
GetClientRect (hwndCtrl, &rec);
origWidth = rec.right;
origHeight = rec.bottom;
if (width >= 0
&& (!bFirstUpdate || origWidth > width)) // The original width of the field is the maximum allowed size
{
horizSubOffset = origWidth - width;
vertSubOffset = origHeight - height;
// Window coords
GetWindowRect(hwndDlg, &wrec);
GetClientRect(hwndDlg, &trec);
// Vertical "title bar" offset
vertOffset = wrec.bottom - wrec.top - trec.bottom - (bBorderlessWindow ? 0 : GetSystemMetrics(SM_CYFIXEDFRAME));
// Text field coords
GetWindowRect(hwndCtrl, &rec);
// Alignment offset
windowInfo.cbSize = sizeof(windowInfo);
GetWindowInfo (hwndCtrl, &windowInfo);
if (windowInfo.dwStyle & SS_CENTER)
alignPosDiff = horizSubOffset / 2;
else if (windowInfo.dwStyle & SS_RIGHT)
alignPosDiff = horizSubOffset;
// Resize/move
if (alignPosDiff > 0)
{
// Resize and move the text field
MoveWindow (hwndCtrl,
rec.left - wrec.left - (bBorderlessWindow ? 0 : GetSystemMetrics(SM_CXFIXEDFRAME)) + alignPosDiff,
rec.top - wrec.top - vertOffset,
origWidth - horizSubOffset,
origHeight - vertSubOffset,
TRUE);
}
else
{
// Resize the text field
SetWindowPos (hwndCtrl, 0, 0, 0,
origWidth - horizSubOffset,
origHeight - vertSubOffset,
SWP_NOMOVE | SWP_NOZORDER);
}
SetWindowPos (hwndCtrl, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
InvalidateRect (hwndCtrl, NULL, TRUE);
}
}
// Resizes width of a checkbox according to actual width in pixels of its label text (font size is taken into account)
void AccommodateCheckBoxTextWidth (HWND hwndDlg, UINT ctrlId)
{
RECT rec;
HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId);
int width, origWidth, origHeight;
int horizSubOffset;
wchar_t text [MAX_URL_LENGTH];
HFONT hFont = (HFONT) SendDlgItemMessage (hwndDlg, ctrlId, WM_GETFONT, 0, 0);
// Resize the field according to its length and font size and move if centered or right-aligned
GetWindowTextW (hwndCtrl, text, sizeof (text) / sizeof (wchar_t));
width = GetTextGfxWidth (hwndCtrl, text, hFont);
// add to width variable value the width of the checkbox square. We use SM_CXMENUCHECK which is a little larger than actual width
width += GetSystemMetrics(SM_CXMENUCHECK);
GetClientRect (hwndCtrl, &rec);
origWidth = rec.right;
origHeight = rec.bottom;
if (width >= 0
&& (origWidth > width)) // The original width of the field is the maximum allowed size
{
horizSubOffset = origWidth - width;
// Resize the text field
SetWindowPos (hwndCtrl, 0, 0, 0,
origWidth - horizSubOffset,
origHeight,
SWP_NOMOVE | SWP_NOZORDER);
InvalidateRect (hwndCtrl, NULL, TRUE);
}
}
// makes controls contiguous by moving the second control right next to the first one horizontally
void MakeControlsContiguous(HWND hwndDlg, UINT ctrl1ID, UINT ctrl2ID) {
HWND hwndCtrl1 = GetDlgItem(hwndDlg, ctrl1ID);
HWND hwndCtrl2 = GetDlgItem(hwndDlg, ctrl2ID);
RECT rect1, rect2;
POINT pt1, pt2;
int newLeftPosition;
// Exit silently if one or both controls are missing
if (!hwndCtrl1 || !hwndCtrl2) {
return;
}
GetWindowRect(hwndCtrl1, &rect1);
GetWindowRect(hwndCtrl2, &rect2);
// Convert the top-right point of the first control from screen to client coordinates
pt1.x = rect1.right;
pt1.y = rect1.top;
if (!ScreenToClient(hwndDlg, &pt1)) {
return; // Exit if the conversion fails
}
// Convert the top-left point of the second control from screen to client coordinates
pt2.x = rect2.left;
pt2.y = rect2.top;
if (!ScreenToClient(hwndDlg, &pt2)) {
return; // Exit if the conversion fails
}
// Ensure the second control is always placed to the right of the first one
newLeftPosition = pt1.x + 1;
if (pt2.x < pt1.x) { // if the second control is to the left of the first one
newLeftPosition += (pt1.x - pt2.x);
}
// Move the second control to its new position
SetWindowPos(hwndCtrl2, NULL, newLeftPosition, pt2.y, 0, 0, SWP_NOZORDER | SWP_NOSIZE);
}
// Note that the user can still close the window by right-clicking its taskbar icon and selecting 'Close window', or by pressing Alt-F4, or using the Task Manager.
void DisableCloseButton (HWND hwndDlg)
{
EnableMenuItem (GetSystemMenu (hwndDlg, FALSE), SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
}
void EnableCloseButton (HWND hwndDlg)
{
EnableMenuItem (GetSystemMenu (hwndDlg, FALSE), SC_CLOSE, MF_BYCOMMAND | MF_ENABLED);
}
void HandlePasswordEditWmChar (HWND hwnd, WPARAM wParam)
{
DWORD dwStartPos = 0, dwEndPos = 0;
short vk = VkKeyScanW ((WCHAR) wParam);
BYTE vkCode = LOBYTE (vk);
BYTE vkState = HIBYTE (vk);
bool ctrlPressed = (vkState & 2) && !(vkState & 4);
int dwMaxPassLen = (int) SendMessage (hwnd, EM_GETLIMITTEXT, 0, 0);
// check if there is a selected text
SendMessage (hwnd, EM_GETSEL, (WPARAM) &dwStartPos, (LPARAM) &dwEndPos);
if ((dwStartPos == dwEndPos)
&& (vkCode != VK_DELETE) && (vkCode != VK_BACK)
&& !ctrlPressed
&& (GetWindowTextLength (hwnd) == dwMaxPassLen))
{
EDITBALLOONTIP ebt;
DWORD dwTextSize = (DWORD) wcslen (GetString ("PASSWORD_MAXLENGTH_REACHED")) + 16;
WCHAR* szErrorText = (WCHAR*) malloc (dwTextSize * sizeof (WCHAR));
StringCchPrintf (szErrorText, dwTextSize, GetString ("PASSWORD_MAXLENGTH_REACHED"), dwMaxPassLen);
ebt.cbStruct = sizeof( EDITBALLOONTIP );
ebt.pszText = szErrorText;
ebt.pszTitle = lpszTitle;
ebt.ttiIcon = TTI_ERROR_LARGE; // tooltip warning icon
SendMessage(hwnd, EM_SHOWBALLOONTIP, 0, (LPARAM)&ebt);
MessageBeep (0xFFFFFFFF);
free (szErrorText);
}
else
SendMessage(hwnd, EM_HIDEBALLOONTIP, 0, 0);
}
// Protects an input field from having its content updated by a Paste action (call ToBootPwdField() to use this).
static LRESULT CALLBACK BootPwdFieldProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
WNDPROC wp = (WNDPROC) GetWindowLongPtrW (hwnd, GWLP_USERDATA);
switch (message)
{
case WM_PASTE:
return 1;
case WM_CHAR:
HandlePasswordEditWmChar (hwnd, wParam);
break;
}
return CallWindowProcW (wp, hwnd, message, wParam, lParam);
}
// Protects an input field from having its content updated by a Paste action. Used for pre-boot password
// input fields (only the US keyboard layout is supported in pre-boot environment so we must prevent the
// user from pasting a password typed using a non-US keyboard layout).
void ToBootPwdField (HWND hwndDlg, UINT ctrlId)
{
HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId);
WNDPROC originalwp = (WNDPROC) GetWindowLongPtrW (hwndCtrl, GWLP_USERDATA);
SendMessage (hwndCtrl, EM_LIMITTEXT, MAX_LEGACY_PASSWORD, 0);
// if ToNormalPwdField has been called before, GWLP_USERDATA already contains original WNDPROC
if (!originalwp)
{
SetWindowLongPtrW (hwndCtrl, GWLP_USERDATA, (LONG_PTR) GetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC));
}
SetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC, (LONG_PTR) BootPwdFieldProc);
}
// Ensures that a warning is displayed when user is pasting a password longer than the maximum
// length which is set to 64 characters
static LRESULT CALLBACK NormalPwdFieldProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
WNDPROC wp = (WNDPROC) GetWindowLongPtrW (hwnd, GWLP_USERDATA);
switch (message)
{
case WM_PASTE:
{
bool bBlock = false;
if (OpenClipboard (NULL))
{
HANDLE h = GetClipboardData (CF_UNICODETEXT);
if (h)
{
wchar_t *pchData = (wchar_t*)GlobalLock(h);
int txtlen = 0;
int dwMaxPassLen = bUseLegacyMaxPasswordLength? MAX_LEGACY_PASSWORD : MAX_PASSWORD;
while (*pchData)
{
if (*pchData == '\r' || *pchData == '\n')
break;
else
{
txtlen++;
pchData++;
}
}
if (txtlen)
{
int curLen = GetWindowTextLength (hwnd);
if (curLen == dwMaxPassLen)
{
EDITBALLOONTIP ebt;
DWORD dwTextSize = (DWORD) wcslen (GetString ("PASSWORD_MAXLENGTH_REACHED")) + 16;
WCHAR* szErrorText = (WCHAR*) malloc (dwTextSize * sizeof (WCHAR));
StringCchPrintf (szErrorText, dwTextSize, GetString ("PASSWORD_MAXLENGTH_REACHED"), dwMaxPassLen);
ebt.cbStruct = sizeof( EDITBALLOONTIP );
ebt.pszText = szErrorText;
ebt.pszTitle = lpszTitle;
ebt.ttiIcon = TTI_ERROR_LARGE; // tooltip warning icon
SendMessage(hwnd, EM_SHOWBALLOONTIP, 0, (LPARAM)&ebt);
MessageBeep (0xFFFFFFFF);
free (szErrorText);
bBlock = true;
}
else if ((txtlen + curLen) > dwMaxPassLen)
{
EDITBALLOONTIP ebt;
DWORD dwTextSize = (DWORD) wcslen (GetString ("PASSWORD_PASTED_TRUNCATED")) + 16;
WCHAR* szErrorText = (WCHAR*) malloc (dwTextSize * sizeof (WCHAR));
StringCchPrintf (szErrorText, dwTextSize, GetString ("PASSWORD_PASTED_TRUNCATED"), dwMaxPassLen);
ebt.cbStruct = sizeof( EDITBALLOONTIP );
ebt.pszText = szErrorText;
ebt.pszTitle = lpszTitle;
ebt.ttiIcon = TTI_WARNING_LARGE; // tooltip warning icon
SendMessage(hwnd, EM_SHOWBALLOONTIP, 0, (LPARAM)&ebt);
MessageBeep (0xFFFFFFFF);
free (szErrorText);
}
else
SendMessage(hwnd, EM_HIDEBALLOONTIP, 0, 0);
}
GlobalUnlock(h);
}
CloseClipboard ();
}
if (bBlock)
return FALSE;
}
break;
case WM_CHAR:
HandlePasswordEditWmChar (hwnd, wParam);
break;
}
return CallWindowProcW (wp, hwnd, message, wParam, lParam);
}
void ToNormalPwdField (HWND hwndDlg, UINT ctrlId)
{
HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId);
WNDPROC originalwp = (WNDPROC) GetWindowLongPtrW (hwndCtrl, GWLP_USERDATA);
DWORD dwMaxPassLen = bUseLegacyMaxPasswordLength? MAX_LEGACY_PASSWORD : MAX_PASSWORD;
SendMessage (hwndCtrl, EM_LIMITTEXT, dwMaxPassLen, 0);
// only change WNDPROC if not changed already
if (!originalwp)
{
SetWindowLongPtrW (hwndCtrl, GWLP_USERDATA, (LONG_PTR) GetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC));
SetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC, (LONG_PTR) NormalPwdFieldProc);
}
}
// This function currently serves the following purposes:
// - Determines scaling factors for current screen DPI and GUI aspect ratio.
// - Determines how Windows skews the GUI aspect ratio (which happens when the user has a non-default DPI).
// The determined values must be used when performing some GUI operations and calculations.
BOOL CALLBACK AuxiliaryDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_INITDIALOG:
{
HDC hDC = GetDC (hwndDlg);
if (hDC)
{
ScreenDPI = GetDeviceCaps (hDC, LOGPIXELSY);
ReleaseDC (hwndDlg, hDC);
}
DPIScaleFactorX = 1;
DPIScaleFactorY = 1;
DlgAspectRatio = 1;
if (ScreenDPI != USER_DEFAULT_SCREEN_DPI)
{
// Windows skews the GUI aspect ratio if the user has a non-default DPI. Hence, working with
// actual screen DPI is redundant and leads to incorrect results. What really matters here is
// how Windows actually renders our GUI. This is determined by comparing the expected and current
// sizes of a hidden calibration text field.
RECT trec;
trec.right = 0;
trec.bottom = 0;
GetClientRect (GetDlgItem (hwndDlg, IDC_ASPECT_RATIO_CALIBRATION_BOX), &trec);
if (trec.right != 0 && trec.bottom != 0)
{
// The size of the 282x282 IDC_ASPECT_RATIO_CALIBRATION_BOX rendered at the default DPI (96) is 423x458
DPIScaleFactorX = (double) trec.right / 423;
DPIScaleFactorY = (double) trec.bottom / 458;
DlgAspectRatio = DPIScaleFactorX / DPIScaleFactorY;
}
}
EndDialog (hwndDlg, 0);
return 1;
}
case WM_CLOSE:
EndDialog (hwndDlg, 0);
return 1;
}
return 0;
}
/* Except in response to the WM_INITDIALOG message, the dialog box procedure
should return nonzero if it processes the message, and zero if it does
not. - see DialogProc */
BOOL CALLBACK AboutDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
WORD lw = LOWORD (wParam);
static HBITMAP hbmTextualLogoBitmapRescaled = NULL;
switch (msg)
{
case WM_INITDIALOG:
{
wchar_t szTmp[100];
RECT rec;
LocalizeDialog (hwndDlg, "IDD_ABOUT_DLG");
// Hyperlink
SetWindowText (GetDlgItem (hwndDlg, IDC_HOMEPAGE), L"www.idrix.fr");
ToHyperlink (hwndDlg, IDC_HOMEPAGE);
// Logo area background (must not keep aspect ratio; must retain Windows-imposed distortion)
GetClientRect (GetDlgItem (hwndDlg, IDC_ABOUT_LOGO_AREA), &rec);
SetWindowPos (GetDlgItem (hwndDlg, IDC_ABOUT_BKG), HWND_TOP, 0, 0, rec.right, rec.bottom, SWP_NOMOVE);
// Resize the logo bitmap if the user has a non-default DPI
if (ScreenDPI != USER_DEFAULT_SCREEN_DPI)
{
// Logo (must recreate and keep the original aspect ratio as Windows distorts it)
hbmTextualLogoBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_TEXTUAL_LOGO_288DPI),
GetDlgItem (hwndDlg, IDC_TEXTUAL_LOGO_IMG),
0, 0, 0, 0, FALSE, TRUE);
SetWindowPos (GetDlgItem (hwndDlg, IDC_ABOUT_BKG), HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
// Version
SendMessage (GetDlgItem (hwndDlg, IDT_ABOUT_VERSION), WM_SETFONT, (WPARAM) hUserBoldFont, 0);
StringCbPrintfW (szTmp, sizeof(szTmp), L"VeraCrypt %s", _T(VERSION_STRING) _T(VERSION_STRING_SUFFIX));
#ifdef _WIN64
StringCbCatW (szTmp, sizeof(szTmp), L" (64-bit)");
#else
StringCbCatW (szTmp, sizeof(szTmp), L" (32-bit)");
#endif
#if (defined(_DEBUG) || defined(DEBUG))
StringCbCatW (szTmp, sizeof(szTmp), L" (debug)");
#endif
SetDlgItemText (hwndDlg, IDT_ABOUT_VERSION, szTmp);
SetDlgItemText (hwndDlg, IDT_ABOUT_RELEASE, TC_STR_RELEASED_BY);
// Credits
SendMessage (GetDlgItem (hwndDlg, IDC_ABOUT_CREDITS), WM_SETFONT, (WPARAM) hUserFont, (LPARAM) 0);
SendMessage (hwndDlg, WM_APP, 0, 0);
return 1;
}
case WM_APP:
SetWindowText (GetDlgItem (hwndDlg, IDC_ABOUT_CREDITS),
L"Based on TrueCrypt 7.1a, freely available at http://www.truecrypt.org/ .\r\n\r\n"
L"Portions of this software:\r\n"
L"Copyright \xA9 2013-2024 IDRIX. All rights reserved.\r\n"
L"Copyright \xA9 2003-2012 TrueCrypt Developers Association. All Rights Reserved.\r\n"
L"Copyright \xA9 1998-2000 Paul Le Roux. All Rights Reserved.\r\n"
L"Copyright \xA9 1998-2008 Brian Gladman. All Rights Reserved.\r\n"
L"Copyright \xA9 1995-2023 Jean-loup Gailly and Mark Adler.\r\n"
L"Copyright \xA9 2016 Disk Cryptography Services for EFI (DCS), Alex Kolotnikov.\r\n"
L"Copyright \xA9 1999-2023 Dieter Baron and Thomas Klausner.\r\n"
L"Copyright \xA9 2013, Alexey Degtyarev. All rights reserved.\r\n"
L"Copyright \xA9 1999-2016 Jack Lloyd. All rights reserved.\r\n"
L"Copyright \xA9 2013-2019 Stephan Mueller <smueller@chronox.de>\r\n"
L"Copyright \xA9 1999-2023 Igor Pavlov\r\n\r\n"
L"This software as a whole:\r\n"
L"Copyright \xA9 2013-2024 IDRIX. All rights reserved.\r\n\r\n"
L"An IDRIX Release");
return 1;
case WM_COMMAND:
if (lw == IDOK || lw == IDCANCEL)
{
PostMessage (hwndDlg, WM_CLOSE, 0, 0);
return 1;
}
if (lw == IDC_HOMEPAGE)
{
Applink ("main");
return 1;
}
// Disallow modification of credits
if (HIWORD (wParam) == EN_UPDATE)
{
SendMessage (hwndDlg, WM_APP, 0, 0);
return 1;
}
return 0;
case WM_CLOSE:
/* Delete buffered bitmaps (if any) */
if (hbmTextualLogoBitmapRescaled != NULL)
{
DeleteObject ((HGDIOBJ) hbmTextualLogoBitmapRescaled);
hbmTextualLogoBitmapRescaled = NULL;
}
EndDialog (hwndDlg, 0);
return 1;
}
return 0;
}
HWND CreateToolTip(int toolID, HWND hDlg, const char* strID)
{
if (!toolID || !hDlg)
{
return FALSE;
}
// Create the tooltip.
HWND hwndTip = CreateWindowExW(NULL, TOOLTIPS_CLASS, NULL,
WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX | TTS_BALLOON,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
hDlg, NULL,
hInst, NULL);
if (!hwndTip)
{
return (HWND)NULL;
}
// Associate the tooltip with the tool.
TOOLINFOW toolInfo = { 0 };
toolInfo.cbSize = sizeof(toolInfo);
toolInfo.hwnd = hDlg;
toolInfo.uFlags = TTF_SUBCLASS | TTF_IDISHWND;
toolInfo.uId = (UINT_PTR) GetDlgItem(hDlg, toolID);
toolInfo.lpszText = GetString(strID);
// set tooltip maximum width
SendMessage(hwndTip, TTM_SETMAXTIPWIDTH, 0, (LPARAM) 300);
SendMessage(hwndTip, TTM_ADDTOOL, 0, (LPARAM)&toolInfo);
return hwndTip;
}
static HWND StaticModelessWaitDlgHandle = NULL;
// Call DisplayStaticModelessWaitDlg() to open this dialog and CloseStaticModelessWaitDlg() to close it.
static BOOL CALLBACK StaticModelessWaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
WORD lw = LOWORD (wParam);
switch (msg)
{
case WM_INITDIALOG:
{
LocalizeDialog (hwndDlg, NULL);
return 0;
}
case WM_COMMAND:
if (lw == IDOK || lw == IDCANCEL)
return 1;
return 0;
case WM_CLOSE:
StaticModelessWaitDlgHandle = NULL;
EndDialog (hwndDlg, 0);
return 1;
}
return 0;
}
// Opens a dialog window saying "Please wait..." which is not modal and does not need any GUI refresh after initialization.
void DisplayStaticModelessWaitDlg (HWND parent)
{
if (StaticModelessWaitDlgHandle != NULL)
return; // Already shown
StaticModelessWaitDlgHandle = CreateDialogParamW (hInst, MAKEINTRESOURCEW (IDD_STATIC_MODELESS_WAIT_DLG), parent, (DLGPROC) StaticModelessWaitDlgProc, (LPARAM) 0);
ShowWindow (StaticModelessWaitDlgHandle, SW_SHOWNORMAL);
// Allow synchronous use with the GUI being instantly and fully rendered
ProcessPaintMessages (StaticModelessWaitDlgHandle, 500);
}
void CloseStaticModelessWaitDlg (void)
{
if (StaticModelessWaitDlgHandle == NULL)
return; // Not shown
DestroyWindow (StaticModelessWaitDlgHandle);
}
BOOL IsButtonChecked (HWND hButton)
{
if (SendMessage (hButton, BM_GETCHECK, 0, 0) == BST_CHECKED)
return TRUE;
else
return FALSE;
}
void CheckButton (HWND hButton)
{
SendMessage (hButton, BM_SETCHECK, BST_CHECKED, 0);
}
void LeftPadString (wchar_t *szTmp, int len, int targetLen, wchar_t filler)
{
int i;
if (targetLen <= len)
return;
for (i = targetLen-1; i >= (targetLen-len); i--)
szTmp [i] = szTmp [i-(targetLen-len)];
wmemset (szTmp, filler, targetLen-len);
szTmp [targetLen] = 0;
}
/* InitDialog - initialize the applications main dialog, this function should
be called only once in the dialogs WM_INITDIALOG message handler */
void InitDialog (HWND hwndDlg)
{
NONCLIENTMETRICSW metric;
static BOOL aboutMenuAppended = FALSE;
int nHeight;
LOGFONTW lf;
HMENU hMenu;
Font *font;
/* Fonts */
memset (&lf, 0, sizeof(lf));
// Normal
font = GetFont ("font_normal");
metric.cbSize = sizeof (metric);
SystemParametersInfoW (SPI_GETNONCLIENTMETRICS, sizeof(metric), &metric, 0);
WindowTitleBarFont = CreateFontIndirectW (&metric.lfCaptionFont);
metric.lfMessageFont.lfHeight = CompensateDPIFont (!font ? -11 : -font->Size);
metric.lfMessageFont.lfWidth = 0;
if (font && wcscmp (font->FaceName, L"default") != 0)
{
StringCbCopyW ((WCHAR *)metric.lfMessageFont.lfFaceName, sizeof (metric.lfMessageFont.lfFaceName), font->FaceName);
}
else
{
// Vista's new default font (size and spacing) breaks compatibility with Windows 2k/XP applications.
// Force use of Tahoma (as Microsoft does in many dialogs) until a native Vista look is implemented.
StringCbCopyW ((WCHAR *)metric.lfMessageFont.lfFaceName, sizeof (metric.lfMessageFont.lfFaceName), L"Tahoma");
}
hUserFont = CreateFontIndirectW (&metric.lfMessageFont);
metric.lfMessageFont.lfUnderline = TRUE;
hUserUnderlineFont = CreateFontIndirectW (&metric.lfMessageFont);
metric.lfMessageFont.lfUnderline = FALSE;
metric.lfMessageFont.lfWeight = FW_BOLD;
hUserBoldFont = CreateFontIndirectW (&metric.lfMessageFont);
metric.lfMessageFont.lfUnderline = TRUE;
metric.lfMessageFont.lfWeight = FW_BOLD;
hUserUnderlineBoldFont = CreateFontIndirectW (&metric.lfMessageFont);
// Fixed-size (hexadecimal digits)
nHeight = CompensateDPIFont (-12);
lf.lfHeight = nHeight;
lf.lfWidth = 0;
lf.lfEscapement = 0;
lf.lfOrientation = 0;
lf.lfWeight = FW_NORMAL;
lf.lfItalic = FALSE;
lf.lfUnderline = FALSE;
lf.lfStrikeOut = FALSE;
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfQuality = PROOF_QUALITY;
lf.lfPitchAndFamily = FF_DONTCARE;
StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName), L"Courier New");
hFixedDigitFont = CreateFontIndirectW (&lf);
if (hFixedDigitFont == NULL)
{
handleWin32Error (hwndDlg, SRC_POS);
AbortProcess ("NOFONT");
}
// Bold
font = GetFont ("font_bold");
nHeight = CompensateDPIFont (!font ? -13 : -font->Size);
lf.lfHeight = nHeight;
lf.lfWeight = FW_BLACK;
StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName), !font ? L"Arial" : font->FaceName);
hBoldFont = CreateFontIndirectW (&lf);
if (hBoldFont == NULL)
{
handleWin32Error (hwndDlg, SRC_POS);
AbortProcess ("NOFONT");
}
// Title
font = GetFont ("font_title");
nHeight = CompensateDPIFont (!font ? -21 : -font->Size);
lf.lfHeight = nHeight;
lf.lfWeight = FW_REGULAR;
StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName),!font ? L"Times New Roman" : font->FaceName);
hTitleFont = CreateFontIndirectW (&lf);
if (hTitleFont == NULL)
{
handleWin32Error (hwndDlg, SRC_POS);
AbortProcess ("NOFONT");
}
// Fixed-size
font = GetFont ("font_fixed");
nHeight = CompensateDPIFont (!font ? -12 : -font->Size);
lf.lfHeight = nHeight;
lf.lfWidth = 0;
lf.lfEscapement = 0;
lf.lfOrientation = 0;
lf.lfWeight = FW_NORMAL;
lf.lfItalic = FALSE;
lf.lfUnderline = FALSE;
lf.lfStrikeOut = FALSE;
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfQuality = PROOF_QUALITY;
lf.lfPitchAndFamily = FF_DONTCARE;
StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName),!font ? L"Lucida Console" : font->FaceName);
hFixedFont = CreateFontIndirectW (&lf);
if (hFixedFont == NULL)
{
handleWin32Error (hwndDlg, SRC_POS);
AbortProcess ("NOFONT");
}
if (!aboutMenuAppended)
{
hMenu = GetSystemMenu (hwndDlg, FALSE);
AppendMenu (hMenu, MF_SEPARATOR, 0, L"");
AppendMenuW (hMenu, MF_ENABLED | MF_STRING, IDC_ABOUT, GetString ("ABOUTBOX"));
aboutMenuAppended = TRUE;
}
}
// The parameter maxMessagesToProcess prevents endless processing of paint messages
void ProcessPaintMessages (HWND hwnd, int maxMessagesToProcess)
{
MSG paintMsg;
int msgCounter = maxMessagesToProcess;
while (PeekMessageW (&paintMsg, hwnd, 0, 0, PM_REMOVE | PM_QS_PAINT) != 0 && msgCounter-- > 0)
{
DispatchMessageW (&paintMsg);
}
}
HDC CreateMemBitmap (HINSTANCE hInstance, HWND hwnd, wchar_t *resource)
{
HBITMAP picture = LoadBitmap (hInstance, resource);
HDC viewDC = GetDC (hwnd), dcMem;
dcMem = CreateCompatibleDC (viewDC);
SetMapMode (dcMem, MM_TEXT);
SelectObject (dcMem, picture);
DeleteObject (picture);
ReleaseDC (hwnd, viewDC);
return dcMem;
}
/* Renders the specified bitmap at the specified location and stretches it to fit (anti-aliasing is applied).
If bDirectRender is FALSE and both nWidth and nHeight are zero, the width and height of hwndDest are
retrieved and adjusted according to screen DPI (the width and height of the resultant image are adjusted the
same way); furthermore, if bKeepAspectRatio is TRUE, the smaller DPI factor of the two (i.e. horiz. or vert.)
is used both for horiz. and vert. scaling (note that the overall GUI aspect ratio changes irregularly in
both directions depending on the DPI). If bDirectRender is TRUE, bKeepAspectRatio is ignored.
This function returns a handle to the scaled bitmap. When the bitmap is no longer needed, it should be
deleted by calling DeleteObject() with the handle passed as the parameter.
Known Windows issues:
- For some reason, anti-aliasing is not applied if the source bitmap contains less than 16K pixels.
- Windows 2000 may produce slightly inaccurate colors even when source, buffer, and target are 24-bit true color. */
HBITMAP RenderBitmap (wchar_t *resource, HWND hwndDest, int x, int y, int nWidth, int nHeight, BOOL bDirectRender, BOOL bKeepAspectRatio)
{
LRESULT lResult = 0;
HDC hdcSrc = CreateMemBitmap (hInst, hwndDest, resource);
if (!hdcSrc)
return NULL;
HGDIOBJ picture = GetCurrentObject (hdcSrc, OBJ_BITMAP);
HBITMAP hbmpRescaled = NULL;
BITMAP bitmap;
HDC hdcRescaled;
if (!bDirectRender && nWidth == 0 && nHeight == 0)
{
RECT rec;
GetClientRect (hwndDest, &rec);
if (bKeepAspectRatio)
{
if (DlgAspectRatio > 1)
{
// Do not fix this, it's correct. We use the Y scale factor intentionally for both
// directions to maintain aspect ratio (see above for more info).
nWidth = CompensateYDPI (rec.right);
nHeight = CompensateYDPI (rec.bottom);
}
else
{
// Do not fix this, it's correct. We use the X scale factor intentionally for both
// directions to maintain aspect ratio (see above for more info).
nWidth = CompensateXDPI (rec.right);
nHeight = CompensateXDPI (rec.bottom);
}
}
else
{
nWidth = CompensateXDPI (rec.right);
nHeight = CompensateYDPI (rec.bottom);
}
}
GetObject (picture, sizeof (BITMAP), &bitmap);
hdcRescaled = CreateCompatibleDC (hdcSrc);
if (hdcRescaled)
{
hbmpRescaled = CreateCompatibleBitmap (hdcSrc, nWidth, nHeight);
SelectObject (hdcRescaled, hbmpRescaled);
/* Anti-aliasing mode (HALFTONE is the only anti-aliasing algorithm natively supported by Windows 2000.
TODO: GDI+ offers higher quality -- InterpolationModeHighQualityBicubic) */
SetStretchBltMode (hdcRescaled, HALFTONE);
StretchBlt (hdcRescaled,
0,
0,
nWidth,
nHeight,
hdcSrc,
0,
0,
bitmap.bmWidth,
bitmap.bmHeight,
SRCCOPY);
DeleteDC (hdcSrc);
if (bDirectRender)
{
HDC hdcDest = GetDC (hwndDest);
if (hdcDest)
{
BitBlt (hdcDest, x, y, nWidth, nHeight, hdcRescaled, 0, 0, SRCCOPY);
ReleaseDC (hwndDest, hdcDest);
}
}
else
{
lResult = SendMessage (hwndDest, (UINT) STM_SETIMAGE, (WPARAM) IMAGE_BITMAP, (LPARAM) (HANDLE) hbmpRescaled);
}
if ((HGDIOBJ) lResult != NULL && (HGDIOBJ) lResult != (HGDIOBJ) hbmpRescaled)
DeleteObject ((HGDIOBJ) lResult);
DeleteDC (hdcRescaled);
}
return hbmpRescaled;
}
LRESULT CALLBACK
RedTick (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_CREATE)
{
}
else if (uMsg == WM_DESTROY)
{
}
else if (uMsg == WM_TIMER)
{
}
else if (uMsg == WM_PAINT)
{
PAINTSTRUCT tmp;
HPEN hPen;
HDC hDC;
BOOL bEndPaint;
RECT Rect;
if (GetUpdateRect (hwnd, NULL, FALSE))
{
hDC = BeginPaint (hwnd, &tmp);
bEndPaint = TRUE;
if (hDC == NULL)
return DefWindowProcW (hwnd, uMsg, wParam, lParam);
}
else
{
hDC = GetDC (hwnd);
bEndPaint = FALSE;
}
GetClientRect (hwnd, &Rect);
hPen = CreatePen (PS_SOLID, 2, RGB (0, 255, 0));
if (hPen != NULL)
{
HGDIOBJ hObj = SelectObject (hDC, hPen);
WORD bx = LOWORD (GetDialogBaseUnits ());
WORD by = HIWORD (GetDialogBaseUnits ());
MoveToEx (hDC, (Rect.right - Rect.left) / 2, Rect.bottom, NULL);
LineTo (hDC, Rect.right, Rect.top);
MoveToEx (hDC, (Rect.right - Rect.left) / 2, Rect.bottom, NULL);
LineTo (hDC, (3 * bx) / 4, (2 * by) / 8);
SelectObject (hDC, hObj);
DeleteObject (hPen);
}
if (bEndPaint)
EndPaint (hwnd, &tmp);
else
ReleaseDC (hwnd, hDC);
return TRUE;
}
return DefWindowProcW (hwnd, uMsg, wParam, lParam);
}
BOOL
RegisterRedTick (HINSTANCE hInstance)
{
WNDCLASSW wc;
ULONG rc;
memset(&wc, 0 , sizeof wc);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.cbClsExtra = 0;
wc.cbWndExtra = 4;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wc.hCursor = NULL;
wc.hbrBackground = (HBRUSH) GetStockObject (LTGRAY_BRUSH);
wc.lpszClassName = L"VCREDTICK";
wc.lpfnWndProc = &RedTick;
rc = (ULONG) RegisterClassW (&wc);
return rc == 0 ? FALSE : TRUE;
}
BOOL
UnregisterRedTick (HINSTANCE hInstance)
{
return UnregisterClassW (L"VCREDTICK", hInstance);
}
LRESULT CALLBACK
SplashDlgProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
return DefDlgProcW (hwnd, uMsg, wParam, lParam);
}
static int g_waitCursorCounter = 0;
void
WaitCursor ()
{
static HCURSOR hcWait = NULL;
if (hcWait == NULL)
hcWait = LoadCursor (NULL, IDC_WAIT);
if ((g_waitCursorCounter == 0) || (hCursor != hcWait))
{
if (!Silent) SetCursor (hcWait);
hCursor = hcWait;
}
g_waitCursorCounter++;
}
void
NormalCursor ()
{
static HCURSOR hcArrow = NULL;
if (hcArrow == NULL)
hcArrow = LoadCursor (NULL, IDC_ARROW);
if (g_waitCursorCounter > 0)
g_waitCursorCounter--;
if (g_waitCursorCounter == 0)
{
if (!Silent) SetCursor (hcArrow);
hCursor = NULL;
}
}
void
ArrowWaitCursor ()
{
static HCURSOR hcArrowWait = NULL;
if (hcArrowWait == NULL)
hcArrowWait = LoadCursor (NULL, IDC_APPSTARTING);
if ((g_waitCursorCounter == 0) || (hCursor != hcArrowWait))
{
if (!Silent) SetCursor (hcArrowWait);
hCursor = hcArrowWait;
}
g_waitCursorCounter++;
}
void HandCursor ()
{
static HCURSOR hcHand = NULL;
if (hcHand == NULL)
hcHand = LoadCursor (NULL, IDC_HAND);
SetCursor (hcHand);
hCursor = hcHand;
}
void
AddComboPair (HWND hComboBox, const wchar_t *lpszItem, int value)
{
LPARAM nIndex;
nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) lpszItem);
nIndex = SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) value);
}
void
SelectAlgo (HWND hComboBox, int *algo_id)
{
LPARAM nCount = SendMessage (hComboBox, CB_GETCOUNT, 0, 0);
LPARAM x, i;
for (i = 0; i < nCount; i++)
{
x = SendMessage (hComboBox, CB_GETITEMDATA, i, 0);
if (x == (LPARAM) *algo_id)
{
SendMessage (hComboBox, CB_SETCURSEL, i, 0);
return;
}
}
/* Something went wrong ; couldn't find the requested algo id so we drop
back to a default */
*algo_id = (int) SendMessage (hComboBox, CB_GETITEMDATA, 0, 0);
SendMessage (hComboBox, CB_SETCURSEL, 0, 0);
}
void PopulateWipeModeCombo (HWND hComboBox, BOOL bNA, BOOL bInPlaceEncryption, BOOL bHeaderWipe)
{
if (bNA)
{
AddComboPair (hComboBox, GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE"), TC_WIPE_NONE);
}
else
{
if (!bHeaderWipe)
{
AddComboPair (hComboBox, GetString ("WIPE_MODE_NONE"), TC_WIPE_NONE);
}
AddComboPair (hComboBox, GetString ("WIPE_MODE_1_RAND"), TC_WIPE_1_RAND);
AddComboPair (hComboBox, GetString ("WIPE_MODE_3_DOD_5220"), TC_WIPE_3_DOD_5220);
AddComboPair (hComboBox, GetString ("WIPE_MODE_7_DOD_5220"), TC_WIPE_7_DOD_5220);
AddComboPair (hComboBox, GetString ("WIPE_MODE_35_GUTMANN"), TC_WIPE_35_GUTMANN);
if (bHeaderWipe)
AddComboPair (hComboBox, GetString ("WIPE_MODE_256"), TC_WIPE_256); // paranoid wipe for volume header
}
}
wchar_t *GetWipeModeName (WipeAlgorithmId modeId)
{
switch (modeId)
{
case TC_WIPE_NONE:
return GetString ("WIPE_MODE_NONE");
case TC_WIPE_1_RAND:
return GetString ("WIPE_MODE_1_RAND");
case TC_WIPE_3_DOD_5220:
return GetString ("WIPE_MODE_3_DOD_5220");
case TC_WIPE_7_DOD_5220:
return GetString ("WIPE_MODE_7_DOD_5220");
case TC_WIPE_35_GUTMANN:
return GetString ("WIPE_MODE_35_GUTMANN");
case TC_WIPE_256:
return GetString ("WIPE_MODE_256");
default:
return GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE");
}
}
wchar_t *GetPathType (const wchar_t *path, BOOL bUpperCase, BOOL *bIsPartition)
{
if (wcsstr (path, L"Partition")
&& wcsstr (path, L"Partition0") == NULL)
{
*bIsPartition = TRUE;
return GetString (bUpperCase ? "PARTITION_UPPER_CASE" : "PARTITION_LOWER_CASE");
}
else if (wcsstr (path, L"HarddiskVolume"))
{
*bIsPartition = TRUE;
return GetString (bUpperCase ? "VOLUME_UPPER_CASE" : "VOLUME_LOWER_CASE");
}
*bIsPartition = FALSE;
return GetString (bUpperCase ? "DEVICE_UPPER_CASE" : "DEVICE_LOWER_CASE");
}
LRESULT CALLBACK CustomDlgProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_SETCURSOR && hCursor != NULL)
{
SetCursor (hCursor);
return TRUE;
}
return DefDlgProcW (hwnd, uMsg, wParam, lParam);
}
/*
static BOOL IsReturnAddress (DWORD64 address)
{
static size_t codeEnd = 0;
uint8 *sp = (uint8 *) address;
if (codeEnd == 0)
{
MEMORY_BASIC_INFORMATION mi;
if (VirtualQuery ((LPCVOID) 0x401000, &mi, sizeof (mi)) >= sizeof (mi))
codeEnd = (size_t) mi.BaseAddress + mi.RegionSize;
}
if (address < 0x401000 + 8 || address > codeEnd)
return FALSE;
return sp[-5] == 0xe8 // call ADDR
|| (sp[-6] == 0xff && sp[-5] == 0x15) // call [ADDR]
|| (sp[-2] == 0xff && (sp[-1] & 0xf0) == 0xd0); // call REG
}
*/
typedef struct
{
EXCEPTION_POINTERS *ExceptionPointers;
HANDLE ExceptionThread;
} ExceptionHandlerThreadArgs;
void ExceptionHandlerThread (void *threadArg)
{
ExceptionHandlerThreadArgs *args = (ExceptionHandlerThreadArgs *) threadArg;
EXCEPTION_POINTERS *ep = args->ExceptionPointers;
//DWORD addr;
DWORD exCode = ep->ExceptionRecord->ExceptionCode;
// SYSTEM_INFO si;
// wchar_t msg[8192];
// char modPath[MAX_PATH];
// int crc = 0;
// char url[MAX_URL_LENGTH];
// char lpack[128];
// stringstream callStack;
// addr = (DWORD) ep->ExceptionRecord->ExceptionAddress;
// PDWORD sp = (PDWORD) ep->ContextRecord->Esp;
// int frameNumber = 0;
switch (exCode)
{
case STATUS_IN_PAGE_ERROR:
case 0xeedfade:
// Exception not caused by VeraCrypt
MessageBoxW (0, GetString ("EXCEPTION_REPORT_EXT"),
GetString ("EXCEPTION_REPORT_TITLE"),
MB_ICONERROR | MB_OK | MB_SETFOREGROUND | MB_TOPMOST);
return;
}
// Call stack
/* HMODULE dbgDll = LoadLibrary ("dbghelp.dll");
if (dbgDll)
{
typedef DWORD (__stdcall *SymGetOptions_t) ();
typedef DWORD (__stdcall *SymSetOptions_t) (DWORD SymOptions);
typedef BOOL (__stdcall *SymInitialize_t) (HANDLE hProcess, PCSTR UserSearchPath, BOOL fInvadeProcess);
typedef BOOL (__stdcall *StackWalk64_t) (DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME64 StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
typedef BOOL (__stdcall * SymFromAddr_t) (HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol);
SymGetOptions_t DbgHelpSymGetOptions = (SymGetOptions_t) GetProcAddress (dbgDll, "SymGetOptions");
SymSetOptions_t DbgHelpSymSetOptions = (SymSetOptions_t) GetProcAddress (dbgDll, "SymSetOptions");
SymInitialize_t DbgHelpSymInitialize = (SymInitialize_t) GetProcAddress (dbgDll, "SymInitialize");
PFUNCTION_TABLE_ACCESS_ROUTINE64 DbgHelpSymFunctionTableAccess64 = (PFUNCTION_TABLE_ACCESS_ROUTINE64) GetProcAddress (dbgDll, "SymFunctionTableAccess64");
PGET_MODULE_BASE_ROUTINE64 DbgHelpSymGetModuleBase64 = (PGET_MODULE_BASE_ROUTINE64) GetProcAddress (dbgDll, "SymGetModuleBase64");
StackWalk64_t DbgHelpStackWalk64 = (StackWalk64_t) GetProcAddress (dbgDll, "StackWalk64");
SymFromAddr_t DbgHelpSymFromAddr = (SymFromAddr_t) GetProcAddress (dbgDll, "SymFromAddr");
if (DbgHelpSymGetOptions && DbgHelpSymSetOptions && DbgHelpSymInitialize && DbgHelpSymFunctionTableAccess64 && DbgHelpSymGetModuleBase64 && DbgHelpStackWalk64 && DbgHelpSymFromAddr)
{
DbgHelpSymSetOptions (DbgHelpSymGetOptions() | SYMOPT_DEFERRED_LOADS | SYMOPT_ALLOW_ABSOLUTE_SYMBOLS | SYMOPT_NO_CPP);
if (DbgHelpSymInitialize (GetCurrentProcess(), NULL, TRUE))
{
STACKFRAME64 frame;
memset (&frame, 0, sizeof (frame));
frame.AddrPC.Offset = ep->ContextRecord->Eip;
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrStack.Offset = ep->ContextRecord->Esp;
frame.AddrStack.Mode = AddrModeFlat;
frame.AddrFrame.Offset = ep->ContextRecord->Ebp;
frame.AddrFrame.Mode = AddrModeFlat;
string lastSymbol;
while (frameNumber < 32 && DbgHelpStackWalk64 (IMAGE_FILE_MACHINE_I386, GetCurrentProcess(), args->ExceptionThread, &frame, ep->ContextRecord, NULL, DbgHelpSymFunctionTableAccess64, DbgHelpSymGetModuleBase64, NULL))
{
if (!frame.AddrPC.Offset)
continue;
ULONG64 symbolBuffer[(sizeof (SYMBOL_INFO) + MAX_SYM_NAME * sizeof (TCHAR) + sizeof (ULONG64) - 1) / sizeof (ULONG64)];
memset (symbolBuffer, 0, sizeof (symbolBuffer));
PSYMBOL_INFO symbol = (PSYMBOL_INFO) symbolBuffer;
symbol->SizeOfStruct = sizeof (SYMBOL_INFO);
symbol->MaxNameLen = MAX_SYM_NAME;
if (DbgHelpSymFromAddr (GetCurrentProcess(), frame.AddrPC.Offset, NULL, symbol) && symbol->NameLen > 0)
{
for (size_t i = 0; i < symbol->NameLen; ++i)
{
if (!isalnum (symbol->Name[i]))
symbol->Name[i] = '_';
}
if (symbol->Name != lastSymbol)
callStack << "&st" << frameNumber++ << "=" << symbol->Name;
lastSymbol = symbol->Name;
}
else if (frameNumber == 0 || IsReturnAddress (frame.AddrPC.Offset))
{
callStack << "&st" << frameNumber++ << "=0x" << hex << frame.AddrPC.Offset << dec;
}
}
}
}
}
// StackWalk64() may fail due to missing frame pointers
list <DWORD> retAddrs;
if (frameNumber == 0)
retAddrs.push_back (ep->ContextRecord->Eip);
retAddrs.push_back (0);
MEMORY_BASIC_INFORMATION mi;
VirtualQuery (sp, &mi, sizeof (mi));
PDWORD stackTop = (PDWORD)((uint8 *) mi.BaseAddress + mi.RegionSize);
int i = 0;
while (retAddrs.size() < 16 && &sp[i] < stackTop)
{
if (IsReturnAddress (sp[i]))
{
bool duplicate = false;
foreach (DWORD prevAddr, retAddrs)
{
if (sp[i] == prevAddr)
{
duplicate = true;
break;
}
}
if (!duplicate)
retAddrs.push_back (sp[i]);
}
i++;
}
if (retAddrs.size() > 1)
{
foreach (DWORD addr, retAddrs)
{
callStack << "&st" << frameNumber++ << "=0x" << hex << addr << dec;
}
}
// Checksum of the module
if (GetModuleFileName (NULL, modPath, sizeof (modPath)))
{
HANDLE h = CreateFile (modPath, FILE_READ_DATA | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (h != INVALID_HANDLE_VALUE)
{
BY_HANDLE_FILE_INFORMATION fi;
if (GetFileInformationByHandle (h, &fi))
{
char *buf = (char *) malloc (fi.nFileSizeLow);
if (buf)
{
DWORD bytesRead;
if (ReadFile (h, buf, fi.nFileSizeLow, &bytesRead, NULL) && bytesRead == fi.nFileSizeLow)
crc = GetCrc32 ((unsigned char *) buf, fi.nFileSizeLow);
free (buf);
}
}
CloseHandle (h);
}
}
GetSystemInfo (&si);
if (LocalizationActive)
sprintf_s (lpack, sizeof (lpack), "&langpack=%s_%s", GetPreferredLangId (), GetActiveLangPackVersion ());
else
lpack[0] = 0;
sprintf (url, TC_APPLINK_SECURE "&dest=err-report%s&os=%s&osver=%d.%d.%d&arch=%s&cpus=%d&app=%s&cksum=%x&dlg=%s&err=%x&addr=%x"
, lpack
, GetWindowsEdition().c_str()
, CurrentOSMajor
, CurrentOSMinor
, CurrentOSServicePack
, Is64BitOs () ? "x64" : "x86"
, si.dwNumberOfProcessors
#ifdef TCMOUNT
,"main"
#endif
#ifdef VOLFORMAT
,"format"
#endif
#ifdef SETUP
,"setup"
#endif
, crc
, LastDialogId ? LastDialogId : "-"
, exCode
, addr);
string urlStr = url + callStack.str();
_snwprintf (msg, array_capacity (msg), GetString ("EXCEPTION_REPORT"), urlStr.c_str());
if (IDYES == MessageBoxW (0, msg, GetString ("EXCEPTION_REPORT_TITLE"), MB_ICONERROR | MB_YESNO | MB_DEFBUTTON1))
ShellExecute (NULL, "open", urlStr.c_str(), NULL, NULL, SW_SHOWNORMAL);
else */
UnhandledExceptionFilter (ep);
}
LONG __stdcall ExceptionHandler (EXCEPTION_POINTERS *ep)
{
SetUnhandledExceptionFilter (NULL);
if (SystemFileSelectorCallPending && SystemFileSelectorCallerThreadId == GetCurrentThreadId())
{
MessageBoxW (NULL, GetString ("EXCEPTION_REPORT_EXT_FILESEL"), GetString ("EXCEPTION_REPORT_TITLE"), MB_ICONERROR | MB_OK | MB_SETFOREGROUND | MB_TOPMOST);
UnhandledExceptionFilter (ep);
return EXCEPTION_EXECUTE_HANDLER;
}
ExceptionHandlerThreadArgs args;
args.ExceptionPointers = ep;
args.ExceptionThread = GetCurrentThread();
WaitForSingleObject ((HANDLE) _beginthread (ExceptionHandlerThread, 0, &args), INFINITE);
return EXCEPTION_EXECUTE_HANDLER;
}
void InvalidParameterHandler (const wchar_t *expression, const wchar_t *function, const wchar_t *file, unsigned int line, uintptr_t reserved)
{
TC_THROW_FATAL_EXCEPTION;
}
static LRESULT CALLBACK NonInstallUacWndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
return DefWindowProcW (hWnd, message, wParam, lParam);
}
BOOL LaunchElevatedProcess (HWND hwndDlg, const wchar_t* szModPath, const wchar_t* args)
{
wchar_t newCmdLine[4096];
WNDCLASSEXW wcex;
HWND hWnd;
memset (&wcex, 0, sizeof (wcex));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.lpfnWndProc = (WNDPROC) NonInstallUacWndProc;
wcex.hInstance = hInst;
wcex.lpszClassName = L"VeraCrypt";
RegisterClassExW (&wcex);
// A small transparent window is necessary to bring the new instance to foreground
hWnd = CreateWindowExW (WS_EX_TOOLWINDOW | WS_EX_LAYERED,
L"VeraCrypt", L"VeraCrypt", 0,
GetSystemMetrics (SM_CXSCREEN)/2,
GetSystemMetrics (SM_CYSCREEN)/2,
1, 1, NULL, NULL, hInst, NULL);
SetLayeredWindowAttributes (hWnd, 0, 0, LWA_ALPHA);
ShowWindow (hWnd, SW_SHOWNORMAL);
StringCbCopyW (newCmdLine, sizeof(newCmdLine), L"/q UAC ");
StringCbCatW (newCmdLine, sizeof (newCmdLine), args);
if ((int)ShellExecuteW (hWnd, L"runas", szModPath, newCmdLine, NULL, SW_SHOWNORMAL) <= 32)
{
if (hwndDlg)
handleWin32Error (hwndDlg, SRC_POS);
return FALSE;
}
else
{
Sleep (2000);
return TRUE;
}
}
// Mutex handling to prevent multiple instances of the wizard or main app from dealing with system encryption.
// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE).
BOOL CreateSysEncMutex (void)
{
return TCCreateMutex (&hSysEncMutex, TC_MUTEX_NAME_SYSENC);
}
BOOL InstanceHasSysEncMutex (void)
{
return (hSysEncMutex != NULL);
}
// Mutex handling to prevent multiple instances of the wizard from dealing with system encryption
void CloseSysEncMutex (void)
{
TCCloseMutex (&hSysEncMutex);
}
// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE).
BOOL CreateNonSysInplaceEncMutex (void)
{
return TCCreateMutex (&hNonSysInplaceEncMutex, TC_MUTEX_NAME_NONSYS_INPLACE_ENC);
}
BOOL InstanceHasNonSysInplaceEncMutex (void)
{
return (hNonSysInplaceEncMutex != NULL);
}
void CloseNonSysInplaceEncMutex (void)
{
TCCloseMutex (&hNonSysInplaceEncMutex);
}
// Returns TRUE if another instance of the wizard is preparing, resuming or performing non-system in-place encryption
BOOL NonSysInplaceEncInProgressElsewhere (void)
{
return (!InstanceHasNonSysInplaceEncMutex ()
&& MutexExistsOnSystem (TC_MUTEX_NAME_NONSYS_INPLACE_ENC));
}
// Mutex handling to prevent multiple instances of the wizard or main app from trying to install
// or register the driver or from trying to launch it in portable mode at the same time.
// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE).
BOOL CreateDriverSetupMutex (void)
{
return TCCreateMutex (&hDriverSetupMutex, TC_MUTEX_NAME_DRIVER_SETUP);
}
void CloseDriverSetupMutex (void)
{
TCCloseMutex (&hDriverSetupMutex);
}
BOOL CreateAppSetupMutex (void)
{
return TCCreateMutex (&hAppSetupMutex, TC_MUTEX_NAME_APP_SETUP);
}
void CloseAppSetupMutex (void)
{
TCCloseMutex (&hAppSetupMutex);
}
BOOL IsTrueCryptInstallerRunning (void)
{
return (MutexExistsOnSystem (TC_MUTEX_NAME_APP_SETUP));
}
// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE).
BOOL TCCreateMutex (volatile HANDLE *hMutex, wchar_t *name)
{
if (*hMutex != NULL)
return TRUE; // This instance already has the mutex
*hMutex = CreateMutex (NULL, TRUE, name);
if (*hMutex == NULL)
{
// In multi-user configurations, the OS returns "Access is denied" here when a user attempts
// to acquire the mutex if another user already has. However, on Vista, "Access is denied" is
// returned also if the mutex is owned by a process with admin rights while we have none.
return FALSE;
}
if (GetLastError () == ERROR_ALREADY_EXISTS)
{
ReleaseMutex (*hMutex);
CloseHandle (*hMutex);
*hMutex = NULL;
return FALSE;
}
return TRUE;
}
void TCCloseMutex (volatile HANDLE *hMutex)
{
if (*hMutex != NULL)
{
if (ReleaseMutex (*hMutex)
&& CloseHandle (*hMutex))
*hMutex = NULL;
}
}
// Returns TRUE if a process running on the system has the specified mutex (otherwise FALSE).
BOOL MutexExistsOnSystem (wchar_t *name)
{
if (name[0] == 0)
return FALSE;
HANDLE hMutex = OpenMutex (MUTEX_ALL_ACCESS, FALSE, name);
if (hMutex == NULL)
{
if (GetLastError () == ERROR_FILE_NOT_FOUND)
return FALSE;
if (GetLastError () == ERROR_ACCESS_DENIED) // On Vista, this is returned if the owner of the mutex is elevated while we are not
return TRUE;
// The call failed and it is not certain whether the mutex exists or not
return FALSE;
}
CloseHandle (hMutex);
return TRUE;
}
uint32 ReadDriverConfigurationFlags ()
{
DWORD configMap;
if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_DRIVER_CONFIG_REG_VALUE_NAME, &configMap))
configMap = 0;
return configMap;
}
uint32 ReadServiceConfigurationFlags ()
{
DWORD configMap;
if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\" TC_SYSTEM_FAVORITES_SERVICE_NAME, TC_SYSTEM_FAVORITES_SERVICE_NAME L"Config", &configMap))
configMap = 0;
return configMap;
}
uint32 ReadEncryptionThreadPoolFreeCpuCountLimit ()
{
DWORD count;
if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME, &count))
count = 0;
return count;
}
BOOL ReadMemoryProtectionConfig ()
{
DWORD config;
if (!ReadLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", VC_ENABLE_MEMORY_PROTECTION, &config))
{
// enabled by default
config = 1;
}
return (config)? TRUE: FALSE;
}
BOOL WriteMemoryProtectionConfig (BOOL bEnable)
{
DWORD config = bEnable? 1: 0;
return WriteLocalMachineRegistryDword (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", VC_ENABLE_MEMORY_PROTECTION, config);
}
BOOL LoadSysEncSettings ()
{
BOOL status = TRUE;
DWORD size = 0;
char *sysEncCfgFileBuf = LoadFile (GetConfigPath (TC_APPD_FILENAME_SYSTEM_ENCRYPTION), &size);
char *xml = sysEncCfgFileBuf;
char paramName[100], paramVal[MAX_PATH];
// Defaults
int newSystemEncryptionStatus = SYSENC_STATUS_NONE;
WipeAlgorithmId newnWipeMode = TC_WIPE_NONE;
if (!FileExists (GetConfigPath (TC_APPD_FILENAME_SYSTEM_ENCRYPTION)))
{
SystemEncryptionStatus = newSystemEncryptionStatus;
nWipeMode = newnWipeMode;
}
if (xml == NULL)
{
return FALSE;
}
while (xml = XmlFindElement (xml, "config"))
{
XmlGetAttributeText (xml, "key", paramName, sizeof (paramName));
XmlGetNodeText (xml, paramVal, sizeof (paramVal));
if (strcmp (paramName, "SystemEncryptionStatus") == 0)
{
newSystemEncryptionStatus = atoi (paramVal);
}
else if (strcmp (paramName, "WipeMode") == 0)
{
newnWipeMode = (WipeAlgorithmId) atoi (paramVal);
}
xml++;
}
SystemEncryptionStatus = newSystemEncryptionStatus;
nWipeMode = newnWipeMode;
free (sysEncCfgFileBuf);
return status;
}
// Returns the number of partitions where non-system in-place encryption is progress or had been in progress
// but was interrupted. In addition, via the passed pointer, returns the last selected wipe algorithm ID.
int LoadNonSysInPlaceEncSettings (WipeAlgorithmId *wipeAlgorithm)
{
char *fileBuf = NULL;
char *fileBuf2 = NULL;
DWORD size, size2;
int count;
*wipeAlgorithm = TC_WIPE_NONE;
if (!FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC)))
return 0;
if ((fileBuf = LoadFile (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC), &size)) == NULL)
return 0;
if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE)))
{
if ((fileBuf2 = LoadFile (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE), &size2)) != NULL)
*wipeAlgorithm = (WipeAlgorithmId) atoi (fileBuf2);
}
count = atoi (fileBuf);
if (fileBuf != NULL)
TCfree (fileBuf);
if (fileBuf2 != NULL)
TCfree (fileBuf2);
return (count);
}
void RemoveNonSysInPlaceEncNotifications (void)
{
if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC)))
_wremove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC));
if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE)))
_wremove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE));
if (!IsNonInstallMode () && SystemEncryptionStatus == SYSENC_STATUS_NONE)
ManageStartupSeqWiz (TRUE, L"");
}
void SavePostInstallTasksSettings (int command)
{
FILE *f = NULL;
if (IsNonInstallMode() && command != TC_POST_INSTALL_CFG_REMOVE_ALL)
return;
switch (command)
{
case TC_POST_INSTALL_CFG_REMOVE_ALL:
_wremove (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL));
_wremove (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES));
_wremove (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_RESCUE_DISK));
break;
case TC_POST_INSTALL_CFG_TUTORIAL:
f = _wfopen (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL), L"w");
break;
case TC_POST_INSTALL_CFG_RELEASE_NOTES:
f = _wfopen (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES), L"w");
break;
case TC_POST_INSTALL_CFG_RESCUE_DISK:
f = _wfopen (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_RESCUE_DISK), L"w");
break;
default:
return;
}
if (f == NULL)
return;
if (fputws (L"1", f) < 0)
{
// Error
fclose (f);
return;
}
TCFlushFile (f);
fclose (f);
}
void DoPostInstallTasks (HWND hwndDlg)
{
BOOL bDone = FALSE;
if (FileExists (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL)))
{
if (AskYesNo ("AFTER_INSTALL_TUTORIAL", hwndDlg) == IDYES)
Applink ("beginnerstutorial");
bDone = TRUE;
}
if (FileExists (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES)))
{
if (AskYesNo ("AFTER_UPGRADE_RELEASE_NOTES", hwndDlg) == IDYES)
Applink ("releasenotes");
bDone = TRUE;
}
if (FileExists (GetConfigPath (TC_APPD_FILENAME_POST_INSTALL_TASK_RESCUE_DISK)))
{
if (AskYesNo ("AFTER_UPGRADE_RESCUE_DISK", hwndDlg) == IDYES)
PostMessage (hwndDlg, VC_APPMSG_CREATE_RESCUE_DISK, 0, 0);
bDone = TRUE;
}
if (bDone)
SavePostInstallTasksSettings (TC_POST_INSTALL_CFG_REMOVE_ALL);
}
#ifndef SETUP_DLL
// Use an idea proposed in https://medium.com/@1ndahous3/safe-code-pitfalls-dll-side-loading-winapi-and-c-73baaf48bdf5
// it allows to set safe DLL search mode for the entire process very early on, before even the CRT is initialized and global constructors are called
#pragma comment(linker, "/ENTRY:CustomMainCrtStartup")
extern "C" {
int wWinMainCRTStartup();
int APIENTRY CustomMainCrtStartup()
{
SetDefaultDllDirectoriesPtr SetDefaultDllDirectoriesFn = NULL;
SetDefaultDllDirectoriesFn = (SetDefaultDllDirectoriesPtr) GetProcAddress (GetModuleHandle(L"kernel32.dll"), "SetDefaultDllDirectories");
if (SetDefaultDllDirectoriesFn)
{
/* remove current directory from dll search path */
SetDllDirectoryW (L"");
// Force loading dlls from system32 directory only
SetDefaultDllDirectoriesFn (LOAD_LIBRARY_SEARCH_SYSTEM32);
}
// activate process mitigations (currently only ASLR, dynamic code and extensions points)
ActivateProcessMitigations();
#ifndef SETUP
// call ActivateMemoryProtection if corresponding setting has been enabled (default is enabled)
if (ReadMemoryProtectionConfig())
{
ActivateMemoryProtection();
}
#endif
return wWinMainCRTStartup();
}
}
#endif
/* InitApp - initialize the application, this function is called once in the
applications WinMain function, but before the main dialog has been created */
void InitApp (HINSTANCE hInstance, wchar_t *lpszCommandLine)
{
WNDCLASSW wc;
char langId[6];
SetDefaultDllDirectoriesPtr SetDefaultDllDirectoriesFn = NULL;
#if !defined(SETUP)
wchar_t modPath[MAX_PATH];
#endif
INITCOMMONCONTROLSEX InitCtrls;
InitOSVersionInfo();
if (!IsOSAtLeast (WIN_7))
{
// abort using a message that says that VeraCrypt can run only on Windows 7 and later and that it is officially supported only on Windows 10 and later
AbortProcessDirect(L"VeraCrypt requires at least Windows 7 to run.");
}
SetDefaultDllDirectoriesFn = (SetDefaultDllDirectoriesPtr) GetProcAddress (GetModuleHandle(L"kernel32.dll"), "SetDefaultDllDirectories");
if (!SetDefaultDllDirectoriesFn)
{
// This can happen only if KB2533623 is missing from Windows 7
AbortProcessDirect(L"VeraCrypt requires KB2533623 to be installed on Windows 7 and Windows Server 2008 R2 in order to run.");
}
VirtualLock (&CmdTokenPin, sizeof (CmdTokenPin));
InitGlobalLocks ();
// call InitCommonControlsEx function to initialize the common controls
InitCtrls.dwSize = sizeof (InitCtrls);
InitCtrls.dwICC = ICC_WIN95_CLASSES | ICC_PAGESCROLLER_CLASS | ICC_NATIVEFNTCTL_CLASS | ICC_STANDARD_CLASSES | ICC_LINK_CLASS;
InitCommonControlsEx (&InitCtrls);
// Load RichEdit library in order to be able to use RichEdit20W class
LoadLibraryEx (L"Riched20.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
#if !defined(SETUP)
GetModuleFileNameW (NULL, modPath, ARRAYSIZE (modPath));
if (!VerifyModuleSignature (modPath))
AbortProcessDirect (L"This distribution package is damaged. Please try downloading it again (preferably from the official VeraCrypt website at https://www.veracrypt.fr).");
#endif
#ifndef SETUP
/* enable drag-n-drop when we are running elevated */
AllowMessageInUIPI (WM_DROPFILES);
AllowMessageInUIPI (WM_COPYDATA);
AllowMessageInUIPI (WM_COPYGLOBALDATA);
#endif
/* Save the instance handle for later */
hInst = hInstance;
SetErrorMode (SetErrorMode (0) | SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
#ifndef SETUP
// Application ID
SetCurrentProcessExplicitAppUserModelID (TC_APPLICATION_ID);
#endif
// Language
langId[0] = 0;
SetPreferredLangId (ConfigReadString ("Language", "", langId, sizeof (langId)));
#ifndef SETUP
if (langId[0] == 0)
{
// check if user selected a language during installation
WCHAR uiLang[6];
ReadRegistryString (L"Software\\VeraCrypt", L"SetupUILanguage", L"", uiLang, sizeof (uiLang));
if (0 < WideCharToMultiByte (CP_ACP, 0, uiLang, -1, langId, sizeof (langId), NULL, NULL))
{
SetPreferredLangId (langId);
bLanguageSetInSetup = TRUE;
}
}
#ifndef VCEXPANDER
// delete the registry key created by the installer (if any)
DeleteRegistryKey (HKEY_CURRENT_USER, L"Software\\VeraCrypt");
#endif
#endif
if (langId[0] == 0)
{
if (IsNonInstallMode ())
{
// only support automatic use of a language file in portable mode
// this is achieved by placing a unique language XML file in the same
// place as portable VeraCrypt binaries.
DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_LANGUAGE), NULL,
(DLGPROC) LanguageDlgProc, (LPARAM) 1);
}
else
{
// when installed, force using English as default language
SetPreferredLangId ("en");
}
}
LoadLanguageFile ();
#ifndef SETUP
// UAC elevation moniker cannot be used in portable mode.
// A new instance of the application must be created with elevated privileges.
if (IsNonInstallMode () && !IsAdmin () && IsUacSupported ())
{
if (wcsstr (lpszCommandLine, L"/q UAC ") == lpszCommandLine)
{
Error ("UAC_INIT_ERROR", NULL);
exit (1);
}
if (LaunchElevatedProcess (NULL, modPath, lpszCommandLine))
exit (0);
else
exit (1);
}
#endif
SetUnhandledExceptionFilter (ExceptionHandler);
_set_invalid_parameter_handler (InvalidParameterHandler);
RemoteSession = GetSystemMetrics (SM_REMOTESESSION) != 0;
#ifndef VC_SKIP_OS_DRIVER_REQ_CHECK
if (!IsSupportedOS())
{
MessageBoxW (NULL, GetString ("UNSUPPORTED_OS"), lpszTitle, MB_ICONSTOP);
exit (1);
}
#else
// in TESTSIGNING mode, we support only Windows 7 and Windows 8/8.1
if (
#ifndef SETUP
IsOSVersionAtLeast(WIN_10, 0)
#else
|| (IsOSVersionAtLeast(WIN_10, 0) && !bMakePackage)
#endif
)
{
MessageBoxW (NULL, L"TESTSIGNING version of VeraCrypt targets only Windows Vista, Windows 7 and Windows 8/8.1.\n\nPlease use the standard version of VeraCrypt instead.", lpszTitle, MB_ICONSTOP);
exit (1);
}
else if ( !IsTestSigningModeEnabled()
#ifdef SETUP
&& !bMakePackage
#endif
)
{
MessageBoxW (NULL, L"Test-Signing Mode, which is required to run VeraCrypt TESTSIGNING binaries, is not enabled in Windows.\n\nExecution aborted!", lpszTitle, MB_ICONSTOP);
exit (1);
}
#endif
/* Get the attributes for the standard dialog class */
if ((GetClassInfoW (hInst, WINDOWS_DIALOG_CLASS, &wc)) == 0)
{
handleWin32Error (NULL, SRC_POS);
AbortProcess ("INIT_REGISTER");
}
#ifndef SETUP
wc.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_TRUECRYPT_ICON));
#else
#include "../setup/resource.h"
wc.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_SETUP));
#endif
wc.lpszClassName = TC_DLG_CLASS;
wc.lpfnWndProc = &CustomDlgProc;
wc.hCursor = LoadCursor (NULL, IDC_ARROW);
wc.cbWndExtra = DLGWINDOWEXTRA;
hDlgClass = RegisterClassW (&wc);
if (hDlgClass == 0)
{
handleWin32Error (NULL, SRC_POS);
AbortProcess ("INIT_REGISTER");
}
wc.lpszClassName = TC_SPLASH_CLASS;
wc.lpfnWndProc = &SplashDlgProc;
wc.hCursor = LoadCursor (NULL, IDC_ARROW);
wc.cbWndExtra = DLGWINDOWEXTRA;
hSplashClass = RegisterClassW (&wc);
if (hSplashClass == 0)
{
handleWin32Error (NULL, SRC_POS);
AbortProcess ("INIT_REGISTER");
}
// DPI and GUI aspect ratio
DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_AUXILIARY_DLG), NULL,
(DLGPROC) AuxiliaryDlgProc, (LPARAM) 1);
InitHelpFileName ();
#ifndef SETUP
#ifdef _WIN64
EnableRamEncryption ((ReadDriverConfigurationFlags() & VC_DRIVER_CONFIG_ENABLE_RAM_ENCRYPTION) ? TRUE : FALSE);
if (IsRamEncryptionEnabled())
{
if (!InitializeSecurityParameters(GetAppRandomSeed))
AbortProcess("OUTOFMEMORY");
}
#endif
if (!EncryptionThreadPoolStart (ReadEncryptionThreadPoolFreeCpuCountLimit()))
{
handleWin32Error (NULL, SRC_POS);
exit (1);
}
#endif
}
void InitHelpFileName (void)
{
wchar_t *lpszTmp;
GetModuleFileNameW (NULL, szHelpFile, ARRAYSIZE (szHelpFile